xref: /openbmc/linux/fs/btrfs/disk-io.c (revision 820a49da)
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"
45eb60ceacSChris Mason 
46319e4d06SQu Wenruo #define BTRFS_SUPER_FLAG_SUPP	(BTRFS_HEADER_FLAG_WRITTEN |\
47319e4d06SQu Wenruo 				 BTRFS_HEADER_FLAG_RELOC |\
48319e4d06SQu Wenruo 				 BTRFS_SUPER_FLAG_ERROR |\
49319e4d06SQu Wenruo 				 BTRFS_SUPER_FLAG_SEEDING |\
50e2731e55SAnand Jain 				 BTRFS_SUPER_FLAG_METADUMP |\
51e2731e55SAnand Jain 				 BTRFS_SUPER_FLAG_METADUMP_V2)
52319e4d06SQu Wenruo 
538b712842SChris Mason static void end_workqueue_fn(struct btrfs_work *work);
54143bede5SJeff Mahoney static void btrfs_destroy_ordered_extents(struct btrfs_root *root);
55acce952bSliubo static int btrfs_destroy_delayed_refs(struct btrfs_transaction *trans,
562ff7e61eSJeff Mahoney 				      struct btrfs_fs_info *fs_info);
57143bede5SJeff Mahoney static void btrfs_destroy_delalloc_inodes(struct btrfs_root *root);
582ff7e61eSJeff Mahoney static int btrfs_destroy_marked_extents(struct btrfs_fs_info *fs_info,
59acce952bSliubo 					struct extent_io_tree *dirty_pages,
60acce952bSliubo 					int mark);
612ff7e61eSJeff Mahoney static int btrfs_destroy_pinned_extent(struct btrfs_fs_info *fs_info,
62acce952bSliubo 				       struct extent_io_tree *pinned_extents);
632ff7e61eSJeff Mahoney static int btrfs_cleanup_transaction(struct btrfs_fs_info *fs_info);
642ff7e61eSJeff Mahoney static void btrfs_error_commit_super(struct btrfs_fs_info *fs_info);
65ce9adaa5SChris Mason 
66d352ac68SChris Mason /*
6797eb6b69SDavid Sterba  * btrfs_end_io_wq structs are used to do processing in task context when an IO
6897eb6b69SDavid Sterba  * is complete.  This is used during reads to verify checksums, and it is used
69d352ac68SChris Mason  * by writes to insert metadata for new file extents after IO is complete.
70d352ac68SChris Mason  */
7197eb6b69SDavid Sterba struct btrfs_end_io_wq {
72ce9adaa5SChris Mason 	struct bio *bio;
73ce9adaa5SChris Mason 	bio_end_io_t *end_io;
74ce9adaa5SChris Mason 	void *private;
75ce9adaa5SChris Mason 	struct btrfs_fs_info *info;
764e4cbee9SChristoph Hellwig 	blk_status_t status;
77bfebd8b5SDavid Sterba 	enum btrfs_wq_endio_type metadata;
788b712842SChris Mason 	struct btrfs_work work;
79ce9adaa5SChris Mason };
800da5468fSChris Mason 
8197eb6b69SDavid Sterba static struct kmem_cache *btrfs_end_io_wq_cache;
8297eb6b69SDavid Sterba 
8397eb6b69SDavid Sterba int __init btrfs_end_io_wq_init(void)
8497eb6b69SDavid Sterba {
8597eb6b69SDavid Sterba 	btrfs_end_io_wq_cache = kmem_cache_create("btrfs_end_io_wq",
8697eb6b69SDavid Sterba 					sizeof(struct btrfs_end_io_wq),
8797eb6b69SDavid Sterba 					0,
88fba4b697SNikolay Borisov 					SLAB_MEM_SPREAD,
8997eb6b69SDavid Sterba 					NULL);
9097eb6b69SDavid Sterba 	if (!btrfs_end_io_wq_cache)
9197eb6b69SDavid Sterba 		return -ENOMEM;
9297eb6b69SDavid Sterba 	return 0;
9397eb6b69SDavid Sterba }
9497eb6b69SDavid Sterba 
95e67c718bSDavid Sterba void __cold btrfs_end_io_wq_exit(void)
9697eb6b69SDavid Sterba {
9797eb6b69SDavid Sterba 	kmem_cache_destroy(btrfs_end_io_wq_cache);
9897eb6b69SDavid Sterba }
9997eb6b69SDavid Sterba 
100141386e1SJosef Bacik static void btrfs_free_csum_hash(struct btrfs_fs_info *fs_info)
101141386e1SJosef Bacik {
102141386e1SJosef Bacik 	if (fs_info->csum_shash)
103141386e1SJosef Bacik 		crypto_free_shash(fs_info->csum_shash);
104141386e1SJosef Bacik }
105141386e1SJosef Bacik 
106d352ac68SChris Mason /*
107d352ac68SChris Mason  * async submit bios are used to offload expensive checksumming
108d352ac68SChris Mason  * onto the worker threads.  They checksum file and metadata bios
109d352ac68SChris Mason  * just before they are sent down the IO stack.
110d352ac68SChris Mason  */
11144b8bd7eSChris Mason struct async_submit_bio {
1128896a08dSQu Wenruo 	struct inode *inode;
11344b8bd7eSChris Mason 	struct bio *bio;
114a758781dSDavid Sterba 	extent_submit_bio_start_t *submit_bio_start;
11544b8bd7eSChris Mason 	int mirror_num;
1161941b64bSQu Wenruo 
1171941b64bSQu Wenruo 	/* Optional parameter for submit_bio_start used by direct io */
1181941b64bSQu Wenruo 	u64 dio_file_offset;
1198b712842SChris Mason 	struct btrfs_work work;
1204e4cbee9SChristoph Hellwig 	blk_status_t status;
12144b8bd7eSChris Mason };
12244b8bd7eSChris Mason 
12385d4e461SChris Mason /*
12485d4e461SChris Mason  * Lockdep class keys for extent_buffer->lock's in this root.  For a given
12585d4e461SChris Mason  * eb, the lockdep key is determined by the btrfs_root it belongs to and
12685d4e461SChris Mason  * the level the eb occupies in the tree.
1274008c04aSChris Mason  *
12885d4e461SChris Mason  * Different roots are used for different purposes and may nest inside each
12985d4e461SChris Mason  * other and they require separate keysets.  As lockdep keys should be
13085d4e461SChris Mason  * static, assign keysets according to the purpose of the root as indicated
1314fd786e6SMisono Tomohiro  * by btrfs_root->root_key.objectid.  This ensures that all special purpose
1324fd786e6SMisono Tomohiro  * roots have separate keysets.
1334008c04aSChris Mason  *
13485d4e461SChris Mason  * Lock-nesting across peer nodes is always done with the immediate parent
13585d4e461SChris Mason  * node locked thus preventing deadlock.  As lockdep doesn't know this, use
13685d4e461SChris Mason  * subclass to avoid triggering lockdep warning in such cases.
1374008c04aSChris Mason  *
13885d4e461SChris Mason  * The key is set by the readpage_end_io_hook after the buffer has passed
13985d4e461SChris Mason  * csum validation but before the pages are unlocked.  It is also set by
14085d4e461SChris Mason  * btrfs_init_new_buffer on freshly allocated blocks.
14185d4e461SChris Mason  *
14285d4e461SChris Mason  * We also add a check to make sure the highest level of the tree is the
14385d4e461SChris Mason  * same as our lockdep setup here.  If BTRFS_MAX_LEVEL changes, this code
14485d4e461SChris Mason  * needs update as well.
1454008c04aSChris Mason  */
1464008c04aSChris Mason #ifdef CONFIG_DEBUG_LOCK_ALLOC
1474008c04aSChris Mason # if BTRFS_MAX_LEVEL != 8
1484008c04aSChris Mason #  error
1494008c04aSChris Mason # endif
15085d4e461SChris Mason 
151ab1405aaSDavid Sterba #define DEFINE_LEVEL(stem, level)					\
152ab1405aaSDavid Sterba 	.names[level] = "btrfs-" stem "-0" #level,
153ab1405aaSDavid Sterba 
154ab1405aaSDavid Sterba #define DEFINE_NAME(stem)						\
155ab1405aaSDavid Sterba 	DEFINE_LEVEL(stem, 0)						\
156ab1405aaSDavid Sterba 	DEFINE_LEVEL(stem, 1)						\
157ab1405aaSDavid Sterba 	DEFINE_LEVEL(stem, 2)						\
158ab1405aaSDavid Sterba 	DEFINE_LEVEL(stem, 3)						\
159ab1405aaSDavid Sterba 	DEFINE_LEVEL(stem, 4)						\
160ab1405aaSDavid Sterba 	DEFINE_LEVEL(stem, 5)						\
161ab1405aaSDavid Sterba 	DEFINE_LEVEL(stem, 6)						\
162ab1405aaSDavid Sterba 	DEFINE_LEVEL(stem, 7)
163ab1405aaSDavid Sterba 
16485d4e461SChris Mason static struct btrfs_lockdep_keyset {
16585d4e461SChris Mason 	u64			id;		/* root objectid */
166ab1405aaSDavid Sterba 	/* Longest entry: btrfs-free-space-00 */
167387824afSDavid Sterba 	char			names[BTRFS_MAX_LEVEL][20];
168387824afSDavid Sterba 	struct lock_class_key	keys[BTRFS_MAX_LEVEL];
16985d4e461SChris Mason } btrfs_lockdep_keysets[] = {
170ab1405aaSDavid Sterba 	{ .id = BTRFS_ROOT_TREE_OBJECTID,	DEFINE_NAME("root")	},
171ab1405aaSDavid Sterba 	{ .id = BTRFS_EXTENT_TREE_OBJECTID,	DEFINE_NAME("extent")	},
172ab1405aaSDavid Sterba 	{ .id = BTRFS_CHUNK_TREE_OBJECTID,	DEFINE_NAME("chunk")	},
173ab1405aaSDavid Sterba 	{ .id = BTRFS_DEV_TREE_OBJECTID,	DEFINE_NAME("dev")	},
174ab1405aaSDavid Sterba 	{ .id = BTRFS_CSUM_TREE_OBJECTID,	DEFINE_NAME("csum")	},
175ab1405aaSDavid Sterba 	{ .id = BTRFS_QUOTA_TREE_OBJECTID,	DEFINE_NAME("quota")	},
176ab1405aaSDavid Sterba 	{ .id = BTRFS_TREE_LOG_OBJECTID,	DEFINE_NAME("log")	},
177ab1405aaSDavid Sterba 	{ .id = BTRFS_TREE_RELOC_OBJECTID,	DEFINE_NAME("treloc")	},
178ab1405aaSDavid Sterba 	{ .id = BTRFS_DATA_RELOC_TREE_OBJECTID,	DEFINE_NAME("dreloc")	},
179ab1405aaSDavid Sterba 	{ .id = BTRFS_UUID_TREE_OBJECTID,	DEFINE_NAME("uuid")	},
180ab1405aaSDavid Sterba 	{ .id = BTRFS_FREE_SPACE_TREE_OBJECTID,	DEFINE_NAME("free-space") },
181ab1405aaSDavid Sterba 	{ .id = 0,				DEFINE_NAME("tree")	},
1824008c04aSChris Mason };
18385d4e461SChris Mason 
184ab1405aaSDavid Sterba #undef DEFINE_LEVEL
185ab1405aaSDavid Sterba #undef DEFINE_NAME
18685d4e461SChris Mason 
18785d4e461SChris Mason void btrfs_set_buffer_lockdep_class(u64 objectid, struct extent_buffer *eb,
18885d4e461SChris Mason 				    int level)
18985d4e461SChris Mason {
19085d4e461SChris Mason 	struct btrfs_lockdep_keyset *ks;
19185d4e461SChris Mason 
19285d4e461SChris Mason 	BUG_ON(level >= ARRAY_SIZE(ks->keys));
19385d4e461SChris Mason 
19485d4e461SChris Mason 	/* find the matching keyset, id 0 is the default entry */
19585d4e461SChris Mason 	for (ks = btrfs_lockdep_keysets; ks->id; ks++)
19685d4e461SChris Mason 		if (ks->id == objectid)
19785d4e461SChris Mason 			break;
19885d4e461SChris Mason 
19985d4e461SChris Mason 	lockdep_set_class_and_name(&eb->lock,
20085d4e461SChris Mason 				   &ks->keys[level], ks->names[level]);
20185d4e461SChris Mason }
20285d4e461SChris Mason 
2034008c04aSChris Mason #endif
2044008c04aSChris Mason 
205d352ac68SChris Mason /*
2062996e1f8SJohannes Thumshirn  * Compute the csum of a btree block and store the result to provided buffer.
207d352ac68SChris Mason  */
208c67b3892SDavid Sterba static void csum_tree_block(struct extent_buffer *buf, u8 *result)
20919c00ddcSChris Mason {
210d5178578SJohannes Thumshirn 	struct btrfs_fs_info *fs_info = buf->fs_info;
211e9be5a30SDavid Sterba 	const int num_pages = fs_info->nodesize >> PAGE_SHIFT;
212a26663e7SQu Wenruo 	const int first_page_part = min_t(u32, PAGE_SIZE, fs_info->nodesize);
213d5178578SJohannes Thumshirn 	SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
21419c00ddcSChris Mason 	char *kaddr;
215e9be5a30SDavid Sterba 	int i;
216d5178578SJohannes Thumshirn 
217d5178578SJohannes Thumshirn 	shash->tfm = fs_info->csum_shash;
218d5178578SJohannes Thumshirn 	crypto_shash_init(shash);
219a26663e7SQu Wenruo 	kaddr = page_address(buf->pages[0]) + offset_in_page(buf->start);
220e9be5a30SDavid Sterba 	crypto_shash_update(shash, kaddr + BTRFS_CSUM_SIZE,
221a26663e7SQu Wenruo 			    first_page_part - BTRFS_CSUM_SIZE);
22219c00ddcSChris Mason 
223e9be5a30SDavid Sterba 	for (i = 1; i < num_pages; i++) {
224e9be5a30SDavid Sterba 		kaddr = page_address(buf->pages[i]);
225e9be5a30SDavid Sterba 		crypto_shash_update(shash, kaddr, PAGE_SIZE);
22619c00ddcSChris Mason 	}
22771a63551SDavid Sterba 	memset(result, 0, BTRFS_CSUM_SIZE);
228d5178578SJohannes Thumshirn 	crypto_shash_final(shash, result);
22919c00ddcSChris Mason }
23019c00ddcSChris Mason 
231d352ac68SChris Mason /*
232d352ac68SChris Mason  * we can't consider a given block up to date unless the transid of the
233d352ac68SChris Mason  * block matches the transid in the parent node's pointer.  This is how we
234d352ac68SChris Mason  * detect blocks that either didn't get written at all or got written
235d352ac68SChris Mason  * in the wrong place.
236d352ac68SChris Mason  */
2371259ab75SChris Mason static int verify_parent_transid(struct extent_io_tree *io_tree,
238b9fab919SChris Mason 				 struct extent_buffer *eb, u64 parent_transid,
239b9fab919SChris Mason 				 int atomic)
2401259ab75SChris Mason {
2412ac55d41SJosef Bacik 	struct extent_state *cached_state = NULL;
2421259ab75SChris Mason 	int ret;
2432755a0deSDavid Sterba 	bool need_lock = (current->journal_info == BTRFS_SEND_TRANS_STUB);
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 
251ac5887c8SJosef Bacik 	if (need_lock)
252a26e8c9fSJosef Bacik 		btrfs_tree_read_lock(eb);
253a26e8c9fSJosef Bacik 
2542ac55d41SJosef Bacik 	lock_extent_bits(io_tree, eb->start, eb->start + eb->len - 1,
255ff13db41SDavid Sterba 			 &cached_state);
2560b32f4bbSJosef Bacik 	if (extent_buffer_uptodate(eb) &&
2571259ab75SChris Mason 	    btrfs_header_generation(eb) == parent_transid) {
2581259ab75SChris Mason 		ret = 0;
2591259ab75SChris Mason 		goto out;
2601259ab75SChris Mason 	}
26194647322SDavid Sterba 	btrfs_err_rl(eb->fs_info,
26294647322SDavid Sterba 		"parent transid verify failed on %llu wanted %llu found %llu",
26394647322SDavid Sterba 			eb->start,
26429549aecSWang Shilong 			parent_transid, btrfs_header_generation(eb));
2651259ab75SChris Mason 	ret = 1;
266a26e8c9fSJosef Bacik 
267a26e8c9fSJosef Bacik 	/*
268a26e8c9fSJosef Bacik 	 * Things reading via commit roots that don't have normal protection,
269a26e8c9fSJosef Bacik 	 * like send, can have a really old block in cache that may point at a
27001327610SNicholas D Steeves 	 * block that has been freed and re-allocated.  So don't clear uptodate
271a26e8c9fSJosef Bacik 	 * if we find an eb that is under IO (dirty/writeback) because we could
272a26e8c9fSJosef Bacik 	 * end up reading in the stale data and then writing it back out and
273a26e8c9fSJosef Bacik 	 * making everybody very sad.
274a26e8c9fSJosef Bacik 	 */
275a26e8c9fSJosef Bacik 	if (!extent_buffer_under_io(eb))
2760b32f4bbSJosef Bacik 		clear_extent_buffer_uptodate(eb);
27733958dc6SChris Mason out:
2782ac55d41SJosef Bacik 	unlock_extent_cached(io_tree, eb->start, eb->start + eb->len - 1,
279e43bbe5eSDavid Sterba 			     &cached_state);
280472b909fSJosef Bacik 	if (need_lock)
281ac5887c8SJosef Bacik 		btrfs_tree_read_unlock(eb);
2821259ab75SChris Mason 	return ret;
2831259ab75SChris Mason }
2841259ab75SChris Mason 
285e7e16f48SJohannes Thumshirn static bool btrfs_supported_super_csum(u16 csum_type)
286e7e16f48SJohannes Thumshirn {
287e7e16f48SJohannes Thumshirn 	switch (csum_type) {
288e7e16f48SJohannes Thumshirn 	case BTRFS_CSUM_TYPE_CRC32:
2893951e7f0SJohannes Thumshirn 	case BTRFS_CSUM_TYPE_XXHASH:
2903831bf00SJohannes Thumshirn 	case BTRFS_CSUM_TYPE_SHA256:
291352ae07bSDavid Sterba 	case BTRFS_CSUM_TYPE_BLAKE2:
292e7e16f48SJohannes Thumshirn 		return true;
293e7e16f48SJohannes Thumshirn 	default:
294e7e16f48SJohannes Thumshirn 		return false;
295e7e16f48SJohannes Thumshirn 	}
296e7e16f48SJohannes Thumshirn }
297e7e16f48SJohannes Thumshirn 
298d352ac68SChris Mason /*
2991104a885SDavid Sterba  * Return 0 if the superblock checksum type matches the checksum value of that
3001104a885SDavid Sterba  * algorithm. Pass the raw disk superblock data.
3011104a885SDavid Sterba  */
302ab8d0fc4SJeff Mahoney static int btrfs_check_super_csum(struct btrfs_fs_info *fs_info,
303ab8d0fc4SJeff Mahoney 				  char *raw_disk_sb)
3041104a885SDavid Sterba {
3051104a885SDavid Sterba 	struct btrfs_super_block *disk_sb =
3061104a885SDavid Sterba 		(struct btrfs_super_block *)raw_disk_sb;
30751bce6c9SJohannes Thumshirn 	char result[BTRFS_CSUM_SIZE];
308d5178578SJohannes Thumshirn 	SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
309d5178578SJohannes Thumshirn 
310d5178578SJohannes Thumshirn 	shash->tfm = fs_info->csum_shash;
3111104a885SDavid Sterba 
3121104a885SDavid Sterba 	/*
3131104a885SDavid Sterba 	 * The super_block structure does not span the whole
31451bce6c9SJohannes Thumshirn 	 * BTRFS_SUPER_INFO_SIZE range, we expect that the unused space is
31551bce6c9SJohannes Thumshirn 	 * filled with zeros and is included in the checksum.
3161104a885SDavid Sterba 	 */
317fd08001fSEric Biggers 	crypto_shash_digest(shash, raw_disk_sb + BTRFS_CSUM_SIZE,
318fd08001fSEric Biggers 			    BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE, result);
3191104a885SDavid Sterba 
32055fc29beSDavid Sterba 	if (memcmp(disk_sb->csum, result, fs_info->csum_size))
321e7e16f48SJohannes Thumshirn 		return 1;
3221104a885SDavid Sterba 
323e7e16f48SJohannes Thumshirn 	return 0;
3241104a885SDavid Sterba }
3251104a885SDavid Sterba 
326e064d5e9SDavid Sterba int btrfs_verify_level_key(struct extent_buffer *eb, int level,
327ff76a864SLiu Bo 			   struct btrfs_key *first_key, u64 parent_transid)
328581c1760SQu Wenruo {
329e064d5e9SDavid Sterba 	struct btrfs_fs_info *fs_info = eb->fs_info;
330581c1760SQu Wenruo 	int found_level;
331581c1760SQu Wenruo 	struct btrfs_key found_key;
332581c1760SQu Wenruo 	int ret;
333581c1760SQu Wenruo 
334581c1760SQu Wenruo 	found_level = btrfs_header_level(eb);
335581c1760SQu Wenruo 	if (found_level != level) {
33663489055SQu Wenruo 		WARN(IS_ENABLED(CONFIG_BTRFS_DEBUG),
33763489055SQu Wenruo 		     KERN_ERR "BTRFS: tree level check failed\n");
338581c1760SQu Wenruo 		btrfs_err(fs_info,
339581c1760SQu Wenruo "tree level mismatch detected, bytenr=%llu level expected=%u has=%u",
340581c1760SQu Wenruo 			  eb->start, level, found_level);
341581c1760SQu Wenruo 		return -EIO;
342581c1760SQu Wenruo 	}
343581c1760SQu Wenruo 
344581c1760SQu Wenruo 	if (!first_key)
345581c1760SQu Wenruo 		return 0;
346581c1760SQu Wenruo 
3475d41be6fSQu Wenruo 	/*
3485d41be6fSQu Wenruo 	 * For live tree block (new tree blocks in current transaction),
3495d41be6fSQu Wenruo 	 * we need proper lock context to avoid race, which is impossible here.
3505d41be6fSQu Wenruo 	 * So we only checks tree blocks which is read from disk, whose
3515d41be6fSQu Wenruo 	 * generation <= fs_info->last_trans_committed.
3525d41be6fSQu Wenruo 	 */
3535d41be6fSQu Wenruo 	if (btrfs_header_generation(eb) > fs_info->last_trans_committed)
3545d41be6fSQu Wenruo 		return 0;
35562fdaa52SQu Wenruo 
35662fdaa52SQu Wenruo 	/* We have @first_key, so this @eb must have at least one item */
35762fdaa52SQu Wenruo 	if (btrfs_header_nritems(eb) == 0) {
35862fdaa52SQu Wenruo 		btrfs_err(fs_info,
35962fdaa52SQu Wenruo 		"invalid tree nritems, bytenr=%llu nritems=0 expect >0",
36062fdaa52SQu Wenruo 			  eb->start);
36162fdaa52SQu Wenruo 		WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
36262fdaa52SQu Wenruo 		return -EUCLEAN;
36362fdaa52SQu Wenruo 	}
36462fdaa52SQu Wenruo 
365581c1760SQu Wenruo 	if (found_level)
366581c1760SQu Wenruo 		btrfs_node_key_to_cpu(eb, &found_key, 0);
367581c1760SQu Wenruo 	else
368581c1760SQu Wenruo 		btrfs_item_key_to_cpu(eb, &found_key, 0);
369581c1760SQu Wenruo 	ret = btrfs_comp_cpu_keys(first_key, &found_key);
370581c1760SQu Wenruo 
371581c1760SQu Wenruo 	if (ret) {
37263489055SQu Wenruo 		WARN(IS_ENABLED(CONFIG_BTRFS_DEBUG),
37363489055SQu Wenruo 		     KERN_ERR "BTRFS: tree first key check failed\n");
374581c1760SQu Wenruo 		btrfs_err(fs_info,
375ff76a864SLiu Bo "tree first key mismatch detected, bytenr=%llu parent_transid=%llu key expected=(%llu,%u,%llu) has=(%llu,%u,%llu)",
376ff76a864SLiu Bo 			  eb->start, parent_transid, first_key->objectid,
377ff76a864SLiu Bo 			  first_key->type, first_key->offset,
378ff76a864SLiu Bo 			  found_key.objectid, found_key.type,
379ff76a864SLiu Bo 			  found_key.offset);
380581c1760SQu Wenruo 	}
381581c1760SQu Wenruo 	return ret;
382581c1760SQu Wenruo }
383581c1760SQu Wenruo 
3841104a885SDavid Sterba /*
385d352ac68SChris Mason  * helper to read a given tree block, doing retries as required when
386d352ac68SChris Mason  * the checksums don't match and we have alternate mirrors to try.
387581c1760SQu Wenruo  *
388581c1760SQu Wenruo  * @parent_transid:	expected transid, skip check if 0
389581c1760SQu Wenruo  * @level:		expected level, mandatory check
390581c1760SQu Wenruo  * @first_key:		expected key of first slot, skip check if NULL
391d352ac68SChris Mason  */
3925ab12d1fSDavid Sterba static int btree_read_extent_buffer_pages(struct extent_buffer *eb,
393581c1760SQu Wenruo 					  u64 parent_transid, int level,
394581c1760SQu Wenruo 					  struct btrfs_key *first_key)
395f188591eSChris Mason {
3965ab12d1fSDavid Sterba 	struct btrfs_fs_info *fs_info = eb->fs_info;
397f188591eSChris Mason 	struct extent_io_tree *io_tree;
398ea466794SJosef Bacik 	int failed = 0;
399f188591eSChris Mason 	int ret;
400f188591eSChris Mason 	int num_copies = 0;
401f188591eSChris Mason 	int mirror_num = 0;
402ea466794SJosef Bacik 	int failed_mirror = 0;
403f188591eSChris Mason 
4040b246afaSJeff Mahoney 	io_tree = &BTRFS_I(fs_info->btree_inode)->io_tree;
405f188591eSChris Mason 	while (1) {
406f8397d69SNikolay Borisov 		clear_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags);
407c2ccfbc6SNikolay Borisov 		ret = read_extent_buffer_pages(eb, WAIT_COMPLETE, mirror_num);
408256dd1bbSStefan Behrens 		if (!ret) {
409581c1760SQu Wenruo 			if (verify_parent_transid(io_tree, eb,
410b9fab919SChris Mason 						   parent_transid, 0))
411256dd1bbSStefan Behrens 				ret = -EIO;
412e064d5e9SDavid Sterba 			else if (btrfs_verify_level_key(eb, level,
413ff76a864SLiu Bo 						first_key, parent_transid))
414581c1760SQu Wenruo 				ret = -EUCLEAN;
415581c1760SQu Wenruo 			else
416581c1760SQu Wenruo 				break;
417256dd1bbSStefan Behrens 		}
418d397712bSChris Mason 
4190b246afaSJeff Mahoney 		num_copies = btrfs_num_copies(fs_info,
420f188591eSChris Mason 					      eb->start, eb->len);
4214235298eSChris Mason 		if (num_copies == 1)
422ea466794SJosef Bacik 			break;
4234235298eSChris Mason 
4245cf1ab56SJosef Bacik 		if (!failed_mirror) {
4255cf1ab56SJosef Bacik 			failed = 1;
4265cf1ab56SJosef Bacik 			failed_mirror = eb->read_mirror;
4275cf1ab56SJosef Bacik 		}
4285cf1ab56SJosef Bacik 
429f188591eSChris Mason 		mirror_num++;
430ea466794SJosef Bacik 		if (mirror_num == failed_mirror)
431ea466794SJosef Bacik 			mirror_num++;
432ea466794SJosef Bacik 
4334235298eSChris Mason 		if (mirror_num > num_copies)
434ea466794SJosef Bacik 			break;
435f188591eSChris Mason 	}
436ea466794SJosef Bacik 
437c0901581SStefan Behrens 	if (failed && !ret && failed_mirror)
43820a1fbf9SDavid Sterba 		btrfs_repair_eb_io_failure(eb, failed_mirror);
439ea466794SJosef Bacik 
440ea466794SJosef Bacik 	return ret;
441f188591eSChris Mason }
44219c00ddcSChris Mason 
443d352ac68SChris Mason /*
444ac303b69SQu Wenruo  * Checksum a dirty tree block before IO.  This has extra checks to make sure
445ac303b69SQu Wenruo  * we only fill in the checksum field in the first page of a multi-page block.
446ac303b69SQu Wenruo  * For subpage extent buffers we need bvec to also read the offset in the page.
447d352ac68SChris Mason  */
448ac303b69SQu Wenruo static int csum_dirty_buffer(struct btrfs_fs_info *fs_info, struct bio_vec *bvec)
44919c00ddcSChris Mason {
450ac303b69SQu Wenruo 	struct page *page = bvec->bv_page;
4514eee4fa4SMiao Xie 	u64 start = page_offset(page);
45219c00ddcSChris Mason 	u64 found_start;
4532996e1f8SJohannes Thumshirn 	u8 result[BTRFS_CSUM_SIZE];
45419c00ddcSChris Mason 	struct extent_buffer *eb;
4558d47a0d8SQu Wenruo 	int ret;
456f188591eSChris Mason 
4574f2de97aSJosef Bacik 	eb = (struct extent_buffer *)page->private;
4584f2de97aSJosef Bacik 	if (page != eb->pages[0])
4594f2de97aSJosef Bacik 		return 0;
4600f805531SAlex Lyakas 
46119c00ddcSChris Mason 	found_start = btrfs_header_bytenr(eb);
462d3575156SNaohiro Aota 
463d3575156SNaohiro Aota 	if (test_bit(EXTENT_BUFFER_NO_CHECK, &eb->bflags)) {
464d3575156SNaohiro Aota 		WARN_ON(found_start != 0);
465d3575156SNaohiro Aota 		return 0;
466d3575156SNaohiro Aota 	}
467d3575156SNaohiro Aota 
4680f805531SAlex Lyakas 	/*
4690f805531SAlex Lyakas 	 * Please do not consolidate these warnings into a single if.
4700f805531SAlex Lyakas 	 * It is useful to know what went wrong.
4710f805531SAlex Lyakas 	 */
4720f805531SAlex Lyakas 	if (WARN_ON(found_start != start))
4730f805531SAlex Lyakas 		return -EUCLEAN;
4740f805531SAlex Lyakas 	if (WARN_ON(!PageUptodate(page)))
4750f805531SAlex Lyakas 		return -EUCLEAN;
4760f805531SAlex Lyakas 
477de37aa51SNikolay Borisov 	ASSERT(memcmp_extent_buffer(eb, fs_info->fs_devices->metadata_uuid,
4789a8658e3SDavid Sterba 				    offsetof(struct btrfs_header, fsid),
4799a8658e3SDavid Sterba 				    BTRFS_FSID_SIZE) == 0);
4800f805531SAlex Lyakas 
481c67b3892SDavid Sterba 	csum_tree_block(eb, result);
4822996e1f8SJohannes Thumshirn 
4838d47a0d8SQu Wenruo 	if (btrfs_header_level(eb))
4848d47a0d8SQu Wenruo 		ret = btrfs_check_node(eb);
4858d47a0d8SQu Wenruo 	else
4868d47a0d8SQu Wenruo 		ret = btrfs_check_leaf_full(eb);
4878d47a0d8SQu Wenruo 
4888d47a0d8SQu Wenruo 	if (ret < 0) {
489c06631b0SQu Wenruo 		btrfs_print_tree(eb, 0);
4908d47a0d8SQu Wenruo 		btrfs_err(fs_info,
4918d47a0d8SQu Wenruo 		"block=%llu write time tree block corruption detected",
4928d47a0d8SQu Wenruo 			  eb->start);
493c06631b0SQu Wenruo 		WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
4948d47a0d8SQu Wenruo 		return ret;
4958d47a0d8SQu Wenruo 	}
496713cebfbSDavid Sterba 	write_extent_buffer(eb, result, 0, fs_info->csum_size);
4978d47a0d8SQu Wenruo 
4982996e1f8SJohannes Thumshirn 	return 0;
49919c00ddcSChris Mason }
50019c00ddcSChris Mason 
501b0c9b3b0SDavid Sterba static int check_tree_block_fsid(struct extent_buffer *eb)
5022b82032cSYan Zheng {
503b0c9b3b0SDavid Sterba 	struct btrfs_fs_info *fs_info = eb->fs_info;
504944d3f9fSNikolay Borisov 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices, *seed_devs;
50544880fdcSAnand Jain 	u8 fsid[BTRFS_FSID_SIZE];
506944d3f9fSNikolay Borisov 	u8 *metadata_uuid;
5072b82032cSYan Zheng 
5089a8658e3SDavid Sterba 	read_extent_buffer(eb, fsid, offsetof(struct btrfs_header, fsid),
5099a8658e3SDavid Sterba 			   BTRFS_FSID_SIZE);
5107239ff4bSNikolay Borisov 	/*
511944d3f9fSNikolay Borisov 	 * Checking the incompat flag is only valid for the current fs. For
512944d3f9fSNikolay Borisov 	 * seed devices it's forbidden to have their uuid changed so reading
513944d3f9fSNikolay Borisov 	 * ->fsid in this case is fine
5147239ff4bSNikolay Borisov 	 */
515944d3f9fSNikolay Borisov 	if (btrfs_fs_incompat(fs_info, METADATA_UUID))
5167239ff4bSNikolay Borisov 		metadata_uuid = fs_devices->metadata_uuid;
5177239ff4bSNikolay Borisov 	else
5187239ff4bSNikolay Borisov 		metadata_uuid = fs_devices->fsid;
5197239ff4bSNikolay Borisov 
520944d3f9fSNikolay Borisov 	if (!memcmp(fsid, metadata_uuid, BTRFS_FSID_SIZE))
521944d3f9fSNikolay Borisov 		return 0;
522944d3f9fSNikolay Borisov 
523944d3f9fSNikolay Borisov 	list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list)
524944d3f9fSNikolay Borisov 		if (!memcmp(fsid, seed_devs->fsid, BTRFS_FSID_SIZE))
525944d3f9fSNikolay Borisov 			return 0;
526944d3f9fSNikolay Borisov 
527944d3f9fSNikolay Borisov 	return 1;
5282b82032cSYan Zheng }
5292b82032cSYan Zheng 
53077bf40a2SQu Wenruo /* Do basic extent buffer checks at read time */
53177bf40a2SQu Wenruo static int validate_extent_buffer(struct extent_buffer *eb)
532ce9adaa5SChris Mason {
53377bf40a2SQu Wenruo 	struct btrfs_fs_info *fs_info = eb->fs_info;
534ce9adaa5SChris Mason 	u64 found_start;
53577bf40a2SQu Wenruo 	const u32 csum_size = fs_info->csum_size;
53677bf40a2SQu Wenruo 	u8 found_level;
5372996e1f8SJohannes Thumshirn 	u8 result[BTRFS_CSUM_SIZE];
53877bf40a2SQu Wenruo 	int ret = 0;
539ea466794SJosef Bacik 
540ce9adaa5SChris Mason 	found_start = btrfs_header_bytenr(eb);
541727011e0SChris Mason 	if (found_start != eb->start) {
542893bf4b1SSu Yue 		btrfs_err_rl(fs_info, "bad tree block start, want %llu have %llu",
543893bf4b1SSu Yue 			     eb->start, found_start);
544f188591eSChris Mason 		ret = -EIO;
54577bf40a2SQu Wenruo 		goto out;
546ce9adaa5SChris Mason 	}
547b0c9b3b0SDavid Sterba 	if (check_tree_block_fsid(eb)) {
54802873e43SZhao Lei 		btrfs_err_rl(fs_info, "bad fsid on block %llu",
54994647322SDavid Sterba 			     eb->start);
5501259ab75SChris Mason 		ret = -EIO;
55177bf40a2SQu Wenruo 		goto out;
5521259ab75SChris Mason 	}
553ce9adaa5SChris Mason 	found_level = btrfs_header_level(eb);
5541c24c3ceSJosef Bacik 	if (found_level >= BTRFS_MAX_LEVEL) {
555893bf4b1SSu Yue 		btrfs_err(fs_info, "bad tree block level %d on %llu",
556893bf4b1SSu Yue 			  (int)btrfs_header_level(eb), eb->start);
5571c24c3ceSJosef Bacik 		ret = -EIO;
55877bf40a2SQu Wenruo 		goto out;
5591c24c3ceSJosef Bacik 	}
560ce9adaa5SChris Mason 
561c67b3892SDavid Sterba 	csum_tree_block(eb, result);
562a826d6dcSJosef Bacik 
5632996e1f8SJohannes Thumshirn 	if (memcmp_extent_buffer(eb, result, 0, csum_size)) {
56435be8851SJohannes Thumshirn 		u8 val[BTRFS_CSUM_SIZE] = { 0 };
5652996e1f8SJohannes Thumshirn 
5662996e1f8SJohannes Thumshirn 		read_extent_buffer(eb, &val, 0, csum_size);
5672996e1f8SJohannes Thumshirn 		btrfs_warn_rl(fs_info,
56835be8851SJohannes Thumshirn 	"%s checksum verify failed on %llu wanted " CSUM_FMT " found " CSUM_FMT " level %d",
5692996e1f8SJohannes Thumshirn 			      fs_info->sb->s_id, eb->start,
57035be8851SJohannes Thumshirn 			      CSUM_FMT_VALUE(csum_size, val),
57135be8851SJohannes Thumshirn 			      CSUM_FMT_VALUE(csum_size, result),
57235be8851SJohannes Thumshirn 			      btrfs_header_level(eb));
5732996e1f8SJohannes Thumshirn 		ret = -EUCLEAN;
57477bf40a2SQu Wenruo 		goto out;
5752996e1f8SJohannes Thumshirn 	}
5762996e1f8SJohannes Thumshirn 
577a826d6dcSJosef Bacik 	/*
578a826d6dcSJosef Bacik 	 * If this is a leaf block and it is corrupt, set the corrupt bit so
579a826d6dcSJosef Bacik 	 * that we don't try and read the other copies of this block, just
580a826d6dcSJosef Bacik 	 * return -EIO.
581a826d6dcSJosef Bacik 	 */
5821c4360eeSDavid Sterba 	if (found_level == 0 && btrfs_check_leaf_full(eb)) {
583a826d6dcSJosef Bacik 		set_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags);
584a826d6dcSJosef Bacik 		ret = -EIO;
585a826d6dcSJosef Bacik 	}
586ce9adaa5SChris Mason 
587813fd1dcSDavid Sterba 	if (found_level > 0 && btrfs_check_node(eb))
588053ab70fSLiu Bo 		ret = -EIO;
589053ab70fSLiu Bo 
5900b32f4bbSJosef Bacik 	if (!ret)
5910b32f4bbSJosef Bacik 		set_extent_buffer_uptodate(eb);
59275391f0dSQu Wenruo 	else
59375391f0dSQu Wenruo 		btrfs_err(fs_info,
59475391f0dSQu Wenruo 			  "block=%llu read time tree block corruption detected",
59575391f0dSQu Wenruo 			  eb->start);
59677bf40a2SQu Wenruo out:
59777bf40a2SQu Wenruo 	return ret;
59877bf40a2SQu Wenruo }
59977bf40a2SQu Wenruo 
600371cdc07SQu Wenruo static int validate_subpage_buffer(struct page *page, u64 start, u64 end,
601371cdc07SQu Wenruo 				   int mirror)
602371cdc07SQu Wenruo {
603371cdc07SQu Wenruo 	struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
604371cdc07SQu Wenruo 	struct extent_buffer *eb;
605371cdc07SQu Wenruo 	bool reads_done;
606371cdc07SQu Wenruo 	int ret = 0;
607371cdc07SQu Wenruo 
608371cdc07SQu Wenruo 	/*
609371cdc07SQu Wenruo 	 * We don't allow bio merge for subpage metadata read, so we should
610371cdc07SQu Wenruo 	 * only get one eb for each endio hook.
611371cdc07SQu Wenruo 	 */
612371cdc07SQu Wenruo 	ASSERT(end == start + fs_info->nodesize - 1);
613371cdc07SQu Wenruo 	ASSERT(PagePrivate(page));
614371cdc07SQu Wenruo 
615371cdc07SQu Wenruo 	eb = find_extent_buffer(fs_info, start);
616371cdc07SQu Wenruo 	/*
617371cdc07SQu Wenruo 	 * When we are reading one tree block, eb must have been inserted into
618371cdc07SQu Wenruo 	 * the radix tree. If not, something is wrong.
619371cdc07SQu Wenruo 	 */
620371cdc07SQu Wenruo 	ASSERT(eb);
621371cdc07SQu Wenruo 
622371cdc07SQu Wenruo 	reads_done = atomic_dec_and_test(&eb->io_pages);
623371cdc07SQu Wenruo 	/* Subpage read must finish in page read */
624371cdc07SQu Wenruo 	ASSERT(reads_done);
625371cdc07SQu Wenruo 
626371cdc07SQu Wenruo 	eb->read_mirror = mirror;
627371cdc07SQu Wenruo 	if (test_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags)) {
628371cdc07SQu Wenruo 		ret = -EIO;
629371cdc07SQu Wenruo 		goto err;
630371cdc07SQu Wenruo 	}
631371cdc07SQu Wenruo 	ret = validate_extent_buffer(eb);
632371cdc07SQu Wenruo 	if (ret < 0)
633371cdc07SQu Wenruo 		goto err;
634371cdc07SQu Wenruo 
635371cdc07SQu Wenruo 	if (test_and_clear_bit(EXTENT_BUFFER_READAHEAD, &eb->bflags))
636371cdc07SQu Wenruo 		btree_readahead_hook(eb, ret);
637371cdc07SQu Wenruo 
638371cdc07SQu Wenruo 	set_extent_buffer_uptodate(eb);
639371cdc07SQu Wenruo 
640371cdc07SQu Wenruo 	free_extent_buffer(eb);
641371cdc07SQu Wenruo 	return ret;
642371cdc07SQu Wenruo err:
643371cdc07SQu Wenruo 	/*
644371cdc07SQu Wenruo 	 * end_bio_extent_readpage decrements io_pages in case of error,
645371cdc07SQu Wenruo 	 * make sure it has something to decrement.
646371cdc07SQu Wenruo 	 */
647371cdc07SQu Wenruo 	atomic_inc(&eb->io_pages);
648371cdc07SQu Wenruo 	clear_extent_buffer_uptodate(eb);
649371cdc07SQu Wenruo 	free_extent_buffer(eb);
650371cdc07SQu Wenruo 	return ret;
651371cdc07SQu Wenruo }
652371cdc07SQu Wenruo 
6538e1dc982SQu Wenruo int btrfs_validate_metadata_buffer(struct btrfs_io_bio *io_bio,
65477bf40a2SQu Wenruo 				   struct page *page, u64 start, u64 end,
65577bf40a2SQu Wenruo 				   int mirror)
65677bf40a2SQu Wenruo {
65777bf40a2SQu Wenruo 	struct extent_buffer *eb;
65877bf40a2SQu Wenruo 	int ret = 0;
65977bf40a2SQu Wenruo 	int reads_done;
66077bf40a2SQu Wenruo 
66177bf40a2SQu Wenruo 	ASSERT(page->private);
662371cdc07SQu Wenruo 
663371cdc07SQu Wenruo 	if (btrfs_sb(page->mapping->host->i_sb)->sectorsize < PAGE_SIZE)
664371cdc07SQu Wenruo 		return validate_subpage_buffer(page, start, end, mirror);
665371cdc07SQu Wenruo 
66677bf40a2SQu Wenruo 	eb = (struct extent_buffer *)page->private;
66777bf40a2SQu Wenruo 
66877bf40a2SQu Wenruo 	/*
66977bf40a2SQu Wenruo 	 * The pending IO might have been the only thing that kept this buffer
67077bf40a2SQu Wenruo 	 * in memory.  Make sure we have a ref for all this other checks
67177bf40a2SQu Wenruo 	 */
67277bf40a2SQu Wenruo 	atomic_inc(&eb->refs);
67377bf40a2SQu Wenruo 
67477bf40a2SQu Wenruo 	reads_done = atomic_dec_and_test(&eb->io_pages);
67577bf40a2SQu Wenruo 	if (!reads_done)
67677bf40a2SQu Wenruo 		goto err;
67777bf40a2SQu Wenruo 
67877bf40a2SQu Wenruo 	eb->read_mirror = mirror;
67977bf40a2SQu Wenruo 	if (test_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags)) {
68077bf40a2SQu Wenruo 		ret = -EIO;
68177bf40a2SQu Wenruo 		goto err;
68277bf40a2SQu Wenruo 	}
68377bf40a2SQu Wenruo 	ret = validate_extent_buffer(eb);
684ce9adaa5SChris Mason err:
68579fb65a1SJosef Bacik 	if (reads_done &&
68679fb65a1SJosef Bacik 	    test_and_clear_bit(EXTENT_BUFFER_READAHEAD, &eb->bflags))
687d48d71aaSDavid Sterba 		btree_readahead_hook(eb, ret);
6884bb31e92SArne Jansen 
68953b381b3SDavid Woodhouse 	if (ret) {
69053b381b3SDavid Woodhouse 		/*
69153b381b3SDavid Woodhouse 		 * our io error hook is going to dec the io pages
69253b381b3SDavid Woodhouse 		 * again, we have to make sure it has something
69353b381b3SDavid Woodhouse 		 * to decrement
69453b381b3SDavid Woodhouse 		 */
69553b381b3SDavid Woodhouse 		atomic_inc(&eb->io_pages);
6960b32f4bbSJosef Bacik 		clear_extent_buffer_uptodate(eb);
69753b381b3SDavid Woodhouse 	}
6980b32f4bbSJosef Bacik 	free_extent_buffer(eb);
69977bf40a2SQu Wenruo 
700f188591eSChris Mason 	return ret;
701ce9adaa5SChris Mason }
702ce9adaa5SChris Mason 
7034246a0b6SChristoph Hellwig static void end_workqueue_bio(struct bio *bio)
704ce9adaa5SChris Mason {
70597eb6b69SDavid Sterba 	struct btrfs_end_io_wq *end_io_wq = bio->bi_private;
706ce9adaa5SChris Mason 	struct btrfs_fs_info *fs_info;
7079e0af237SLiu Bo 	struct btrfs_workqueue *wq;
708ce9adaa5SChris Mason 
709ce9adaa5SChris Mason 	fs_info = end_io_wq->info;
7104e4cbee9SChristoph Hellwig 	end_io_wq->status = bio->bi_status;
711d20f7043SChris Mason 
712cfe94440SNaohiro Aota 	if (btrfs_op(bio) == BTRFS_MAP_WRITE) {
713a0cac0ecSOmar Sandoval 		if (end_io_wq->metadata == BTRFS_WQ_ENDIO_METADATA)
7149e0af237SLiu Bo 			wq = fs_info->endio_meta_write_workers;
715a0cac0ecSOmar Sandoval 		else if (end_io_wq->metadata == BTRFS_WQ_ENDIO_FREE_SPACE)
7169e0af237SLiu Bo 			wq = fs_info->endio_freespace_worker;
717a0cac0ecSOmar Sandoval 		else if (end_io_wq->metadata == BTRFS_WQ_ENDIO_RAID56)
7189e0af237SLiu Bo 			wq = fs_info->endio_raid56_workers;
719a0cac0ecSOmar Sandoval 		else
7209e0af237SLiu Bo 			wq = fs_info->endio_write_workers;
7219e0af237SLiu Bo 	} else {
7225c047a69SOmar Sandoval 		if (end_io_wq->metadata == BTRFS_WQ_ENDIO_RAID56)
7239e0af237SLiu Bo 			wq = fs_info->endio_raid56_workers;
724a0cac0ecSOmar Sandoval 		else if (end_io_wq->metadata)
7259e0af237SLiu Bo 			wq = fs_info->endio_meta_workers;
726a0cac0ecSOmar Sandoval 		else
7279e0af237SLiu Bo 			wq = fs_info->endio_workers;
7289e0af237SLiu Bo 	}
7299e0af237SLiu Bo 
730a0cac0ecSOmar Sandoval 	btrfs_init_work(&end_io_wq->work, end_workqueue_fn, NULL, NULL);
7319e0af237SLiu Bo 	btrfs_queue_work(wq, &end_io_wq->work);
732ce9adaa5SChris Mason }
733ce9adaa5SChris Mason 
7344e4cbee9SChristoph Hellwig blk_status_t btrfs_bio_wq_end_io(struct btrfs_fs_info *info, struct bio *bio,
735bfebd8b5SDavid Sterba 			enum btrfs_wq_endio_type metadata)
7360b86a832SChris Mason {
73797eb6b69SDavid Sterba 	struct btrfs_end_io_wq *end_io_wq;
7388b110e39SMiao Xie 
73997eb6b69SDavid Sterba 	end_io_wq = kmem_cache_alloc(btrfs_end_io_wq_cache, GFP_NOFS);
740ce9adaa5SChris Mason 	if (!end_io_wq)
7414e4cbee9SChristoph Hellwig 		return BLK_STS_RESOURCE;
742ce9adaa5SChris Mason 
743ce9adaa5SChris Mason 	end_io_wq->private = bio->bi_private;
744ce9adaa5SChris Mason 	end_io_wq->end_io = bio->bi_end_io;
74522c59948SChris Mason 	end_io_wq->info = info;
7464e4cbee9SChristoph Hellwig 	end_io_wq->status = 0;
747ce9adaa5SChris Mason 	end_io_wq->bio = bio;
74822c59948SChris Mason 	end_io_wq->metadata = metadata;
749ce9adaa5SChris Mason 
750ce9adaa5SChris Mason 	bio->bi_private = end_io_wq;
751ce9adaa5SChris Mason 	bio->bi_end_io = end_workqueue_bio;
75222c59948SChris Mason 	return 0;
75322c59948SChris Mason }
75422c59948SChris Mason 
7554a69a410SChris Mason static void run_one_async_start(struct btrfs_work *work)
7564a69a410SChris Mason {
7574a69a410SChris Mason 	struct async_submit_bio *async;
7584e4cbee9SChristoph Hellwig 	blk_status_t ret;
7594a69a410SChris Mason 
7604a69a410SChris Mason 	async = container_of(work, struct  async_submit_bio, work);
7611941b64bSQu Wenruo 	ret = async->submit_bio_start(async->inode, async->bio,
7621941b64bSQu Wenruo 				      async->dio_file_offset);
76379787eaaSJeff Mahoney 	if (ret)
7644e4cbee9SChristoph Hellwig 		async->status = ret;
7654a69a410SChris Mason }
7664a69a410SChris Mason 
76706ea01b1SDavid Sterba /*
76806ea01b1SDavid Sterba  * In order to insert checksums into the metadata in large chunks, we wait
76906ea01b1SDavid Sterba  * until bio submission time.   All the pages in the bio are checksummed and
77006ea01b1SDavid Sterba  * sums are attached onto the ordered extent record.
77106ea01b1SDavid Sterba  *
77206ea01b1SDavid Sterba  * At IO completion time the csums attached on the ordered extent record are
77306ea01b1SDavid Sterba  * inserted into the tree.
77406ea01b1SDavid Sterba  */
7754a69a410SChris Mason static void run_one_async_done(struct btrfs_work *work)
7768b712842SChris Mason {
7778b712842SChris Mason 	struct async_submit_bio *async;
77806ea01b1SDavid Sterba 	struct inode *inode;
77906ea01b1SDavid Sterba 	blk_status_t ret;
7808b712842SChris Mason 
7818b712842SChris Mason 	async = container_of(work, struct  async_submit_bio, work);
7828896a08dSQu Wenruo 	inode = async->inode;
7834854ddd0SChris Mason 
784bb7ab3b9SAdam Buchbinder 	/* If an error occurred we just want to clean up the bio and move on */
7854e4cbee9SChristoph Hellwig 	if (async->status) {
7864e4cbee9SChristoph Hellwig 		async->bio->bi_status = async->status;
7874246a0b6SChristoph Hellwig 		bio_endio(async->bio);
78879787eaaSJeff Mahoney 		return;
78979787eaaSJeff Mahoney 	}
79079787eaaSJeff Mahoney 
791ec39f769SChris Mason 	/*
792ec39f769SChris Mason 	 * All of the bios that pass through here are from async helpers.
793ec39f769SChris Mason 	 * Use REQ_CGROUP_PUNT to issue them from the owning cgroup's context.
794ec39f769SChris Mason 	 * This changes nothing when cgroups aren't in use.
795ec39f769SChris Mason 	 */
796ec39f769SChris Mason 	async->bio->bi_opf |= REQ_CGROUP_PUNT;
79708635baeSChris Mason 	ret = btrfs_map_bio(btrfs_sb(inode->i_sb), async->bio, async->mirror_num);
79806ea01b1SDavid Sterba 	if (ret) {
79906ea01b1SDavid Sterba 		async->bio->bi_status = ret;
80006ea01b1SDavid Sterba 		bio_endio(async->bio);
80106ea01b1SDavid Sterba 	}
8024a69a410SChris Mason }
8034a69a410SChris Mason 
8044a69a410SChris Mason static void run_one_async_free(struct btrfs_work *work)
8054a69a410SChris Mason {
8064a69a410SChris Mason 	struct async_submit_bio *async;
8074a69a410SChris Mason 
8084a69a410SChris Mason 	async = container_of(work, struct  async_submit_bio, work);
8098b712842SChris Mason 	kfree(async);
8108b712842SChris Mason }
8118b712842SChris Mason 
8128896a08dSQu Wenruo blk_status_t btrfs_wq_submit_bio(struct inode *inode, struct bio *bio,
813c6100a4bSJosef Bacik 				 int mirror_num, unsigned long bio_flags,
8141941b64bSQu Wenruo 				 u64 dio_file_offset,
815e288c080SDavid Sterba 				 extent_submit_bio_start_t *submit_bio_start)
81644b8bd7eSChris Mason {
8178896a08dSQu Wenruo 	struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
81844b8bd7eSChris Mason 	struct async_submit_bio *async;
81944b8bd7eSChris Mason 
82044b8bd7eSChris Mason 	async = kmalloc(sizeof(*async), GFP_NOFS);
82144b8bd7eSChris Mason 	if (!async)
8224e4cbee9SChristoph Hellwig 		return BLK_STS_RESOURCE;
82344b8bd7eSChris Mason 
8248896a08dSQu Wenruo 	async->inode = inode;
82544b8bd7eSChris Mason 	async->bio = bio;
82644b8bd7eSChris Mason 	async->mirror_num = mirror_num;
8274a69a410SChris Mason 	async->submit_bio_start = submit_bio_start;
8284a69a410SChris Mason 
829a0cac0ecSOmar Sandoval 	btrfs_init_work(&async->work, run_one_async_start, run_one_async_done,
830a0cac0ecSOmar Sandoval 			run_one_async_free);
8314a69a410SChris Mason 
8321941b64bSQu Wenruo 	async->dio_file_offset = dio_file_offset;
8338c8bee1dSChris Mason 
8344e4cbee9SChristoph Hellwig 	async->status = 0;
83579787eaaSJeff Mahoney 
83667f055c7SChristoph Hellwig 	if (op_is_sync(bio->bi_opf))
8375cdc7ad3SQu Wenruo 		btrfs_set_work_high_priority(&async->work);
838d313d7a3SChris Mason 
8395cdc7ad3SQu Wenruo 	btrfs_queue_work(fs_info->workers, &async->work);
84044b8bd7eSChris Mason 	return 0;
84144b8bd7eSChris Mason }
84244b8bd7eSChris Mason 
8434e4cbee9SChristoph Hellwig static blk_status_t btree_csum_one_bio(struct bio *bio)
844ce3ed71aSChris Mason {
8452c30c71bSKent Overstreet 	struct bio_vec *bvec;
846ce3ed71aSChris Mason 	struct btrfs_root *root;
8472b070cfeSChristoph Hellwig 	int ret = 0;
8486dc4f100SMing Lei 	struct bvec_iter_all iter_all;
849ce3ed71aSChris Mason 
850c09abff8SDavid Sterba 	ASSERT(!bio_flagged(bio, BIO_CLONED));
8512b070cfeSChristoph Hellwig 	bio_for_each_segment_all(bvec, bio, iter_all) {
852ce3ed71aSChris Mason 		root = BTRFS_I(bvec->bv_page->mapping->host)->root;
853ac303b69SQu Wenruo 		ret = csum_dirty_buffer(root->fs_info, bvec);
85479787eaaSJeff Mahoney 		if (ret)
85579787eaaSJeff Mahoney 			break;
856ce3ed71aSChris Mason 	}
8572c30c71bSKent Overstreet 
8584e4cbee9SChristoph Hellwig 	return errno_to_blk_status(ret);
859ce3ed71aSChris Mason }
860ce3ed71aSChris Mason 
8618896a08dSQu Wenruo static blk_status_t btree_submit_bio_start(struct inode *inode, struct bio *bio,
8621941b64bSQu Wenruo 					   u64 dio_file_offset)
86322c59948SChris Mason {
8648b712842SChris Mason 	/*
8658b712842SChris Mason 	 * when we're called for a write, we're already in the async
8665443be45SChris Mason 	 * submission context.  Just jump into btrfs_map_bio
8678b712842SChris Mason 	 */
86879787eaaSJeff Mahoney 	return btree_csum_one_bio(bio);
86922c59948SChris Mason }
87022c59948SChris Mason 
8719b4e675aSDavid Sterba static int check_async_write(struct btrfs_fs_info *fs_info,
8729b4e675aSDavid Sterba 			     struct btrfs_inode *bi)
873de0022b9SJosef Bacik {
8744eef29efSNaohiro Aota 	if (btrfs_is_zoned(fs_info))
8754eef29efSNaohiro Aota 		return 0;
8766300463bSLiu Bo 	if (atomic_read(&bi->sync_writers))
8776300463bSLiu Bo 		return 0;
8789b4e675aSDavid Sterba 	if (test_bit(BTRFS_FS_CSUM_IMPL_FAST, &fs_info->flags))
879de0022b9SJosef Bacik 		return 0;
880de0022b9SJosef Bacik 	return 1;
881de0022b9SJosef Bacik }
882de0022b9SJosef Bacik 
8831b36294aSNikolay Borisov blk_status_t btrfs_submit_metadata_bio(struct inode *inode, struct bio *bio,
8841b36294aSNikolay Borisov 				       int mirror_num, unsigned long bio_flags)
88544b8bd7eSChris Mason {
8860b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8879b4e675aSDavid Sterba 	int async = check_async_write(fs_info, BTRFS_I(inode));
8884e4cbee9SChristoph Hellwig 	blk_status_t ret;
889cad321adSChris Mason 
890cfe94440SNaohiro Aota 	if (btrfs_op(bio) != BTRFS_MAP_WRITE) {
891cad321adSChris Mason 		/*
892cad321adSChris Mason 		 * called for a read, do the setup so that checksum validation
893cad321adSChris Mason 		 * can happen in the async kernel threads
894cad321adSChris Mason 		 */
8950b246afaSJeff Mahoney 		ret = btrfs_bio_wq_end_io(fs_info, bio,
8960b246afaSJeff Mahoney 					  BTRFS_WQ_ENDIO_METADATA);
8971d4284bdSChris Mason 		if (ret)
89861891923SStefan Behrens 			goto out_w_error;
89908635baeSChris Mason 		ret = btrfs_map_bio(fs_info, bio, mirror_num);
900de0022b9SJosef Bacik 	} else if (!async) {
901de0022b9SJosef Bacik 		ret = btree_csum_one_bio(bio);
902de0022b9SJosef Bacik 		if (ret)
90361891923SStefan Behrens 			goto out_w_error;
90408635baeSChris Mason 		ret = btrfs_map_bio(fs_info, bio, mirror_num);
90561891923SStefan Behrens 	} else {
906cad321adSChris Mason 		/*
90761891923SStefan Behrens 		 * kthread helpers are used to submit writes so that
90861891923SStefan Behrens 		 * checksumming can happen in parallel across all CPUs
909cad321adSChris Mason 		 */
9108896a08dSQu Wenruo 		ret = btrfs_wq_submit_bio(inode, bio, mirror_num, 0,
9118896a08dSQu Wenruo 					  0, btree_submit_bio_start);
91244b8bd7eSChris Mason 	}
91344b8bd7eSChris Mason 
9144246a0b6SChristoph Hellwig 	if (ret)
9154246a0b6SChristoph Hellwig 		goto out_w_error;
9164246a0b6SChristoph Hellwig 	return 0;
9174246a0b6SChristoph Hellwig 
91861891923SStefan Behrens out_w_error:
9194e4cbee9SChristoph Hellwig 	bio->bi_status = ret;
9204246a0b6SChristoph Hellwig 	bio_endio(bio);
92161891923SStefan Behrens 	return ret;
92261891923SStefan Behrens }
92361891923SStefan Behrens 
9243dd1462eSJan Beulich #ifdef CONFIG_MIGRATION
925784b4e29SChris Mason static int btree_migratepage(struct address_space *mapping,
926a6bc32b8SMel Gorman 			struct page *newpage, struct page *page,
927a6bc32b8SMel Gorman 			enum migrate_mode mode)
928784b4e29SChris Mason {
929784b4e29SChris Mason 	/*
930784b4e29SChris Mason 	 * we can't safely write a btree page from here,
931784b4e29SChris Mason 	 * we haven't done the locking hook
932784b4e29SChris Mason 	 */
933784b4e29SChris Mason 	if (PageDirty(page))
934784b4e29SChris Mason 		return -EAGAIN;
935784b4e29SChris Mason 	/*
936784b4e29SChris Mason 	 * Buffers may be managed in a filesystem specific way.
937784b4e29SChris Mason 	 * We must have no buffers or drop them.
938784b4e29SChris Mason 	 */
939784b4e29SChris Mason 	if (page_has_private(page) &&
940784b4e29SChris Mason 	    !try_to_release_page(page, GFP_KERNEL))
941784b4e29SChris Mason 		return -EAGAIN;
942a6bc32b8SMel Gorman 	return migrate_page(mapping, newpage, page, mode);
943784b4e29SChris Mason }
9443dd1462eSJan Beulich #endif
945784b4e29SChris Mason 
9460da5468fSChris Mason 
9470da5468fSChris Mason static int btree_writepages(struct address_space *mapping,
9480da5468fSChris Mason 			    struct writeback_control *wbc)
9490da5468fSChris Mason {
950e2d84521SMiao Xie 	struct btrfs_fs_info *fs_info;
951e2d84521SMiao Xie 	int ret;
952e2d84521SMiao Xie 
953d8d5f3e1SChris Mason 	if (wbc->sync_mode == WB_SYNC_NONE) {
954448d640bSChris Mason 
955448d640bSChris Mason 		if (wbc->for_kupdate)
956448d640bSChris Mason 			return 0;
957448d640bSChris Mason 
958e2d84521SMiao Xie 		fs_info = BTRFS_I(mapping->host)->root->fs_info;
959b9473439SChris Mason 		/* this is a bit racy, but that's ok */
960d814a491SEthan Lien 		ret = __percpu_counter_compare(&fs_info->dirty_metadata_bytes,
961d814a491SEthan Lien 					     BTRFS_DIRTY_METADATA_THRESH,
962d814a491SEthan Lien 					     fs_info->dirty_metadata_batch);
963e2d84521SMiao Xie 		if (ret < 0)
964793955bcSChris Mason 			return 0;
965793955bcSChris Mason 	}
9660b32f4bbSJosef Bacik 	return btree_write_cache_pages(mapping, wbc);
9670da5468fSChris Mason }
9680da5468fSChris Mason 
96970dec807SChris Mason static int btree_releasepage(struct page *page, gfp_t gfp_flags)
9705f39d397SChris Mason {
97198509cfcSChris Mason 	if (PageWriteback(page) || PageDirty(page))
97298509cfcSChris Mason 		return 0;
9730c4e538bSDavid Sterba 
974f7a52a40SDavid Sterba 	return try_release_extent_buffer(page);
975d98237b3SChris Mason }
976d98237b3SChris Mason 
977d47992f8SLukas Czerner static void btree_invalidatepage(struct page *page, unsigned int offset,
978d47992f8SLukas Czerner 				 unsigned int length)
979d98237b3SChris Mason {
980d1310b2eSChris Mason 	struct extent_io_tree *tree;
981d1310b2eSChris Mason 	tree = &BTRFS_I(page->mapping->host)->io_tree;
9825f39d397SChris Mason 	extent_invalidatepage(tree, page, offset);
9835f39d397SChris Mason 	btree_releasepage(page, GFP_NOFS);
9849ad6b7bcSChris Mason 	if (PagePrivate(page)) {
985efe120a0SFrank Holton 		btrfs_warn(BTRFS_I(page->mapping->host)->root->fs_info,
986efe120a0SFrank Holton 			   "page private not zero on page %llu",
987efe120a0SFrank Holton 			   (unsigned long long)page_offset(page));
988d1b89bc0SGuoqing Jiang 		detach_page_private(page);
9899ad6b7bcSChris Mason 	}
990d98237b3SChris Mason }
991d98237b3SChris Mason 
9920b32f4bbSJosef Bacik static int btree_set_page_dirty(struct page *page)
9930b32f4bbSJosef Bacik {
994bb146eb2SJosef Bacik #ifdef DEBUG
9950b32f4bbSJosef Bacik 	struct extent_buffer *eb;
9960b32f4bbSJosef Bacik 
9970b32f4bbSJosef Bacik 	BUG_ON(!PagePrivate(page));
9980b32f4bbSJosef Bacik 	eb = (struct extent_buffer *)page->private;
9990b32f4bbSJosef Bacik 	BUG_ON(!eb);
10000b32f4bbSJosef Bacik 	BUG_ON(!test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
10010b32f4bbSJosef Bacik 	BUG_ON(!atomic_read(&eb->refs));
10020b32f4bbSJosef Bacik 	btrfs_assert_tree_locked(eb);
1003bb146eb2SJosef Bacik #endif
10040b32f4bbSJosef Bacik 	return __set_page_dirty_nobuffers(page);
10050b32f4bbSJosef Bacik }
10060b32f4bbSJosef Bacik 
10077f09410bSAlexey Dobriyan static const struct address_space_operations btree_aops = {
10080da5468fSChris Mason 	.writepages	= btree_writepages,
10095f39d397SChris Mason 	.releasepage	= btree_releasepage,
10105f39d397SChris Mason 	.invalidatepage = btree_invalidatepage,
10115a92bc88SChris Mason #ifdef CONFIG_MIGRATION
1012784b4e29SChris Mason 	.migratepage	= btree_migratepage,
10135a92bc88SChris Mason #endif
10140b32f4bbSJosef Bacik 	.set_page_dirty = btree_set_page_dirty,
1015d98237b3SChris Mason };
1016123abc88SChris Mason 
10172ff7e61eSJeff Mahoney struct extent_buffer *btrfs_find_create_tree_block(
10182ff7e61eSJeff Mahoney 						struct btrfs_fs_info *fs_info,
10193fbaf258SJosef Bacik 						u64 bytenr, u64 owner_root,
10203fbaf258SJosef Bacik 						int level)
10210999df54SChris Mason {
10220b246afaSJeff Mahoney 	if (btrfs_is_testing(fs_info))
10230b246afaSJeff Mahoney 		return alloc_test_extent_buffer(fs_info, bytenr);
10243fbaf258SJosef Bacik 	return alloc_extent_buffer(fs_info, bytenr, owner_root, level);
10250999df54SChris Mason }
10260999df54SChris Mason 
1027581c1760SQu Wenruo /*
1028581c1760SQu Wenruo  * Read tree block at logical address @bytenr and do variant basic but critical
1029581c1760SQu Wenruo  * verification.
1030581c1760SQu Wenruo  *
10311b7ec85eSJosef Bacik  * @owner_root:		the objectid of the root owner for this block.
1032581c1760SQu Wenruo  * @parent_transid:	expected transid of this tree block, skip check if 0
1033581c1760SQu Wenruo  * @level:		expected level, mandatory check
1034581c1760SQu Wenruo  * @first_key:		expected key in slot 0, skip check if NULL
1035581c1760SQu Wenruo  */
10362ff7e61eSJeff Mahoney struct extent_buffer *read_tree_block(struct btrfs_fs_info *fs_info, u64 bytenr,
10371b7ec85eSJosef Bacik 				      u64 owner_root, u64 parent_transid,
10381b7ec85eSJosef Bacik 				      int level, struct btrfs_key *first_key)
1039e20d96d6SChris Mason {
10405f39d397SChris Mason 	struct extent_buffer *buf = NULL;
104119c00ddcSChris Mason 	int ret;
104219c00ddcSChris Mason 
10433fbaf258SJosef Bacik 	buf = btrfs_find_create_tree_block(fs_info, bytenr, owner_root, level);
1044c871b0f2SLiu Bo 	if (IS_ERR(buf))
1045c871b0f2SLiu Bo 		return buf;
1046e4204dedSChris Mason 
10475ab12d1fSDavid Sterba 	ret = btree_read_extent_buffer_pages(buf, parent_transid,
1048581c1760SQu Wenruo 					     level, first_key);
10490f0fe8f7SFilipe David Borba Manana 	if (ret) {
1050537f38f0SNikolay Borisov 		free_extent_buffer_stale(buf);
105164c043deSLiu Bo 		return ERR_PTR(ret);
10520f0fe8f7SFilipe David Borba Manana 	}
10535f39d397SChris Mason 	return buf;
1054ce9adaa5SChris Mason 
1055eb60ceacSChris Mason }
1056eb60ceacSChris Mason 
10576a884d7dSDavid Sterba void btrfs_clean_tree_block(struct extent_buffer *buf)
1058ed2ff2cbSChris Mason {
10596a884d7dSDavid Sterba 	struct btrfs_fs_info *fs_info = buf->fs_info;
106055c69072SChris Mason 	if (btrfs_header_generation(buf) ==
1061e2d84521SMiao Xie 	    fs_info->running_transaction->transid) {
1062b9447ef8SChris Mason 		btrfs_assert_tree_locked(buf);
1063b4ce94deSChris Mason 
1064b9473439SChris Mason 		if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &buf->bflags)) {
1065104b4e51SNikolay Borisov 			percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
1066e2d84521SMiao Xie 						 -buf->len,
1067e2d84521SMiao Xie 						 fs_info->dirty_metadata_batch);
10680b32f4bbSJosef Bacik 			clear_extent_buffer_dirty(buf);
1069925baeddSChris Mason 		}
10705f39d397SChris Mason 	}
1071ed7b63ebSJosef Bacik }
10725f39d397SChris Mason 
1073da17066cSJeff Mahoney static void __setup_root(struct btrfs_root *root, struct btrfs_fs_info *fs_info,
1074e20d96d6SChris Mason 			 u64 objectid)
1075d97e63b6SChris Mason {
10767c0260eeSJeff Mahoney 	bool dummy = test_bit(BTRFS_FS_STATE_DUMMY_FS_INFO, &fs_info->fs_state);
107796dfcb46SJosef Bacik 	root->fs_info = fs_info;
1078cfaa7295SChris Mason 	root->node = NULL;
1079a28ec197SChris Mason 	root->commit_root = NULL;
108027cdeb70SMiao Xie 	root->state = 0;
1081d68fc57bSYan, Zheng 	root->orphan_cleanup_state = 0;
10820b86a832SChris Mason 
10830f7d52f4SChris Mason 	root->last_trans = 0;
10846b8fad57SNikolay Borisov 	root->free_objectid = 0;
1085eb73c1b7SMiao Xie 	root->nr_delalloc_inodes = 0;
1086199c2a9cSMiao Xie 	root->nr_ordered_extents = 0;
10876bef4d31SEric Paris 	root->inode_tree = RB_ROOT;
108816cdcec7SMiao Xie 	INIT_RADIX_TREE(&root->delayed_nodes_tree, GFP_ATOMIC);
1089f0486c68SYan, Zheng 	root->block_rsv = NULL;
10900b86a832SChris Mason 
10910b86a832SChris Mason 	INIT_LIST_HEAD(&root->dirty_list);
10925d4f98a2SYan Zheng 	INIT_LIST_HEAD(&root->root_list);
1093eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&root->delalloc_inodes);
1094eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&root->delalloc_root);
1095199c2a9cSMiao Xie 	INIT_LIST_HEAD(&root->ordered_extents);
1096199c2a9cSMiao Xie 	INIT_LIST_HEAD(&root->ordered_root);
1097d2311e69SQu Wenruo 	INIT_LIST_HEAD(&root->reloc_dirty_list);
10982ab28f32SJosef Bacik 	INIT_LIST_HEAD(&root->logged_list[0]);
10992ab28f32SJosef Bacik 	INIT_LIST_HEAD(&root->logged_list[1]);
11005d4f98a2SYan Zheng 	spin_lock_init(&root->inode_lock);
1101eb73c1b7SMiao Xie 	spin_lock_init(&root->delalloc_lock);
1102199c2a9cSMiao Xie 	spin_lock_init(&root->ordered_extent_lock);
1103f0486c68SYan, Zheng 	spin_lock_init(&root->accounting_lock);
11042ab28f32SJosef Bacik 	spin_lock_init(&root->log_extents_lock[0]);
11052ab28f32SJosef Bacik 	spin_lock_init(&root->log_extents_lock[1]);
11068287475aSQu Wenruo 	spin_lock_init(&root->qgroup_meta_rsv_lock);
1107a2135011SChris Mason 	mutex_init(&root->objectid_mutex);
1108e02119d5SChris Mason 	mutex_init(&root->log_mutex);
110931f3d255SMiao Xie 	mutex_init(&root->ordered_extent_mutex);
1110573bfb72SMiao Xie 	mutex_init(&root->delalloc_mutex);
1111c53e9653SQu Wenruo 	init_waitqueue_head(&root->qgroup_flush_wait);
11127237f183SYan Zheng 	init_waitqueue_head(&root->log_writer_wait);
11137237f183SYan Zheng 	init_waitqueue_head(&root->log_commit_wait[0]);
11147237f183SYan Zheng 	init_waitqueue_head(&root->log_commit_wait[1]);
11158b050d35SMiao Xie 	INIT_LIST_HEAD(&root->log_ctxs[0]);
11168b050d35SMiao Xie 	INIT_LIST_HEAD(&root->log_ctxs[1]);
11177237f183SYan Zheng 	atomic_set(&root->log_commit[0], 0);
11187237f183SYan Zheng 	atomic_set(&root->log_commit[1], 0);
11197237f183SYan Zheng 	atomic_set(&root->log_writers, 0);
11202ecb7923SMiao Xie 	atomic_set(&root->log_batch, 0);
11210700cea7SElena Reshetova 	refcount_set(&root->refs, 1);
11228ecebf4dSRobbie Ko 	atomic_set(&root->snapshot_force_cow, 0);
1123eede2bf3SOmar Sandoval 	atomic_set(&root->nr_swapfiles, 0);
11247237f183SYan Zheng 	root->log_transid = 0;
1125d1433debSMiao Xie 	root->log_transid_committed = -1;
1126257c62e1SChris Mason 	root->last_log_commit = 0;
1127e289f03eSFilipe Manana 	if (!dummy) {
112843eb5f29SQu Wenruo 		extent_io_tree_init(fs_info, &root->dirty_log_pages,
112943eb5f29SQu Wenruo 				    IO_TREE_ROOT_DIRTY_LOG_PAGES, NULL);
1130e289f03eSFilipe Manana 		extent_io_tree_init(fs_info, &root->log_csum_range,
1131e289f03eSFilipe Manana 				    IO_TREE_LOG_CSUM_RANGE, NULL);
1132e289f03eSFilipe Manana 	}
1133017e5369SChris Mason 
11343768f368SChris Mason 	memset(&root->root_key, 0, sizeof(root->root_key));
11353768f368SChris Mason 	memset(&root->root_item, 0, sizeof(root->root_item));
11366702ed49SChris Mason 	memset(&root->defrag_progress, 0, sizeof(root->defrag_progress));
11374d775673SChris Mason 	root->root_key.objectid = objectid;
11380ee5dc67SAl Viro 	root->anon_dev = 0;
11398ea05e3aSAlexander Block 
11405f3ab90aSAnand Jain 	spin_lock_init(&root->root_item_lock);
1141370a11b8SQu Wenruo 	btrfs_qgroup_init_swapped_blocks(&root->swapped_blocks);
1142bd647ce3SJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
1143bd647ce3SJosef Bacik 	INIT_LIST_HEAD(&root->leak_list);
1144bd647ce3SJosef Bacik 	spin_lock(&fs_info->fs_roots_radix_lock);
1145bd647ce3SJosef Bacik 	list_add_tail(&root->leak_list, &fs_info->allocated_roots);
1146bd647ce3SJosef Bacik 	spin_unlock(&fs_info->fs_roots_radix_lock);
1147bd647ce3SJosef Bacik #endif
11483768f368SChris Mason }
11493768f368SChris Mason 
115074e4d827SDavid Sterba static struct btrfs_root *btrfs_alloc_root(struct btrfs_fs_info *fs_info,
115196dfcb46SJosef Bacik 					   u64 objectid, gfp_t flags)
11526f07e42eSAl Viro {
115374e4d827SDavid Sterba 	struct btrfs_root *root = kzalloc(sizeof(*root), flags);
11546f07e42eSAl Viro 	if (root)
115596dfcb46SJosef Bacik 		__setup_root(root, fs_info, objectid);
11566f07e42eSAl Viro 	return root;
11576f07e42eSAl Viro }
11586f07e42eSAl Viro 
115906ea65a3SJosef Bacik #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
116006ea65a3SJosef Bacik /* Should only be used by the testing infrastructure */
1161da17066cSJeff Mahoney struct btrfs_root *btrfs_alloc_dummy_root(struct btrfs_fs_info *fs_info)
116206ea65a3SJosef Bacik {
116306ea65a3SJosef Bacik 	struct btrfs_root *root;
116406ea65a3SJosef Bacik 
11657c0260eeSJeff Mahoney 	if (!fs_info)
11667c0260eeSJeff Mahoney 		return ERR_PTR(-EINVAL);
11677c0260eeSJeff Mahoney 
116896dfcb46SJosef Bacik 	root = btrfs_alloc_root(fs_info, BTRFS_ROOT_TREE_OBJECTID, GFP_KERNEL);
116906ea65a3SJosef Bacik 	if (!root)
117006ea65a3SJosef Bacik 		return ERR_PTR(-ENOMEM);
1171da17066cSJeff Mahoney 
1172b9ef22deSFeifei Xu 	/* We don't use the stripesize in selftest, set it as sectorsize */
1173faa2dbf0SJosef Bacik 	root->alloc_bytenr = 0;
117406ea65a3SJosef Bacik 
117506ea65a3SJosef Bacik 	return root;
117606ea65a3SJosef Bacik }
117706ea65a3SJosef Bacik #endif
117806ea65a3SJosef Bacik 
117920897f5cSArne Jansen struct btrfs_root *btrfs_create_tree(struct btrfs_trans_handle *trans,
118020897f5cSArne Jansen 				     u64 objectid)
118120897f5cSArne Jansen {
11829b7a2440SDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
118320897f5cSArne Jansen 	struct extent_buffer *leaf;
118420897f5cSArne Jansen 	struct btrfs_root *tree_root = fs_info->tree_root;
118520897f5cSArne Jansen 	struct btrfs_root *root;
118620897f5cSArne Jansen 	struct btrfs_key key;
1187b89f6d1fSFilipe Manana 	unsigned int nofs_flag;
118820897f5cSArne Jansen 	int ret = 0;
118920897f5cSArne Jansen 
1190b89f6d1fSFilipe Manana 	/*
1191b89f6d1fSFilipe Manana 	 * We're holding a transaction handle, so use a NOFS memory allocation
1192b89f6d1fSFilipe Manana 	 * context to avoid deadlock if reclaim happens.
1193b89f6d1fSFilipe Manana 	 */
1194b89f6d1fSFilipe Manana 	nofs_flag = memalloc_nofs_save();
119596dfcb46SJosef Bacik 	root = btrfs_alloc_root(fs_info, objectid, GFP_KERNEL);
1196b89f6d1fSFilipe Manana 	memalloc_nofs_restore(nofs_flag);
119720897f5cSArne Jansen 	if (!root)
119820897f5cSArne Jansen 		return ERR_PTR(-ENOMEM);
119920897f5cSArne Jansen 
120020897f5cSArne Jansen 	root->root_key.objectid = objectid;
120120897f5cSArne Jansen 	root->root_key.type = BTRFS_ROOT_ITEM_KEY;
120220897f5cSArne Jansen 	root->root_key.offset = 0;
120320897f5cSArne Jansen 
12049631e4ccSJosef Bacik 	leaf = btrfs_alloc_tree_block(trans, root, 0, objectid, NULL, 0, 0, 0,
12059631e4ccSJosef Bacik 				      BTRFS_NESTING_NORMAL);
120620897f5cSArne Jansen 	if (IS_ERR(leaf)) {
120720897f5cSArne Jansen 		ret = PTR_ERR(leaf);
12081dd05682STsutomu Itoh 		leaf = NULL;
12098a6a87cdSBoris Burkov 		goto fail_unlock;
121020897f5cSArne Jansen 	}
121120897f5cSArne Jansen 
121220897f5cSArne Jansen 	root->node = leaf;
121320897f5cSArne Jansen 	btrfs_mark_buffer_dirty(leaf);
121420897f5cSArne Jansen 
121520897f5cSArne Jansen 	root->commit_root = btrfs_root_node(root);
121627cdeb70SMiao Xie 	set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
121720897f5cSArne Jansen 
1218f944d2cbSDavid Sterba 	btrfs_set_root_flags(&root->root_item, 0);
1219f944d2cbSDavid Sterba 	btrfs_set_root_limit(&root->root_item, 0);
122020897f5cSArne Jansen 	btrfs_set_root_bytenr(&root->root_item, leaf->start);
122120897f5cSArne Jansen 	btrfs_set_root_generation(&root->root_item, trans->transid);
122220897f5cSArne Jansen 	btrfs_set_root_level(&root->root_item, 0);
122320897f5cSArne Jansen 	btrfs_set_root_refs(&root->root_item, 1);
122420897f5cSArne Jansen 	btrfs_set_root_used(&root->root_item, leaf->len);
122520897f5cSArne Jansen 	btrfs_set_root_last_snapshot(&root->root_item, 0);
122620897f5cSArne Jansen 	btrfs_set_root_dirid(&root->root_item, 0);
122733d85fdaSQu Wenruo 	if (is_fstree(objectid))
1228807fc790SAndy Shevchenko 		generate_random_guid(root->root_item.uuid);
1229807fc790SAndy Shevchenko 	else
1230807fc790SAndy Shevchenko 		export_guid(root->root_item.uuid, &guid_null);
1231c8422684SDavid Sterba 	btrfs_set_root_drop_level(&root->root_item, 0);
123220897f5cSArne Jansen 
12338a6a87cdSBoris Burkov 	btrfs_tree_unlock(leaf);
12348a6a87cdSBoris Burkov 
123520897f5cSArne Jansen 	key.objectid = objectid;
123620897f5cSArne Jansen 	key.type = BTRFS_ROOT_ITEM_KEY;
123720897f5cSArne Jansen 	key.offset = 0;
123820897f5cSArne Jansen 	ret = btrfs_insert_root(trans, tree_root, &key, &root->root_item);
123920897f5cSArne Jansen 	if (ret)
124020897f5cSArne Jansen 		goto fail;
124120897f5cSArne Jansen 
124220897f5cSArne Jansen 	return root;
12431dd05682STsutomu Itoh 
12448a6a87cdSBoris Burkov fail_unlock:
12458c38938cSJosef Bacik 	if (leaf)
12461dd05682STsutomu Itoh 		btrfs_tree_unlock(leaf);
12478a6a87cdSBoris Burkov fail:
124800246528SJosef Bacik 	btrfs_put_root(root);
12491dd05682STsutomu Itoh 
12501dd05682STsutomu Itoh 	return ERR_PTR(ret);
125120897f5cSArne Jansen }
125220897f5cSArne Jansen 
12537237f183SYan Zheng static struct btrfs_root *alloc_log_tree(struct btrfs_trans_handle *trans,
1254e02119d5SChris Mason 					 struct btrfs_fs_info *fs_info)
12550f7d52f4SChris Mason {
12560f7d52f4SChris Mason 	struct btrfs_root *root;
1257e02119d5SChris Mason 
125896dfcb46SJosef Bacik 	root = btrfs_alloc_root(fs_info, BTRFS_TREE_LOG_OBJECTID, GFP_NOFS);
1259e02119d5SChris Mason 	if (!root)
12607237f183SYan Zheng 		return ERR_PTR(-ENOMEM);
1261e02119d5SChris Mason 
1262e02119d5SChris Mason 	root->root_key.objectid = BTRFS_TREE_LOG_OBJECTID;
1263e02119d5SChris Mason 	root->root_key.type = BTRFS_ROOT_ITEM_KEY;
1264e02119d5SChris Mason 	root->root_key.offset = BTRFS_TREE_LOG_OBJECTID;
126527cdeb70SMiao Xie 
12666ab6ebb7SNaohiro Aota 	return root;
12676ab6ebb7SNaohiro Aota }
12686ab6ebb7SNaohiro Aota 
12696ab6ebb7SNaohiro Aota int btrfs_alloc_log_tree_node(struct btrfs_trans_handle *trans,
12706ab6ebb7SNaohiro Aota 			      struct btrfs_root *root)
12716ab6ebb7SNaohiro Aota {
12726ab6ebb7SNaohiro Aota 	struct extent_buffer *leaf;
12736ab6ebb7SNaohiro Aota 
12747237f183SYan Zheng 	/*
127592a7cc42SQu Wenruo 	 * DON'T set SHAREABLE bit for log trees.
127627cdeb70SMiao Xie 	 *
127792a7cc42SQu Wenruo 	 * Log trees are not exposed to user space thus can't be snapshotted,
127892a7cc42SQu Wenruo 	 * and they go away before a real commit is actually done.
127992a7cc42SQu Wenruo 	 *
128092a7cc42SQu Wenruo 	 * They do store pointers to file data extents, and those reference
128192a7cc42SQu Wenruo 	 * counts still get updated (along with back refs to the log tree).
12827237f183SYan Zheng 	 */
1283e02119d5SChris Mason 
12844d75f8a9SDavid Sterba 	leaf = btrfs_alloc_tree_block(trans, root, 0, BTRFS_TREE_LOG_OBJECTID,
12859631e4ccSJosef Bacik 			NULL, 0, 0, 0, BTRFS_NESTING_NORMAL);
12866ab6ebb7SNaohiro Aota 	if (IS_ERR(leaf))
12876ab6ebb7SNaohiro Aota 		return PTR_ERR(leaf);
1288e02119d5SChris Mason 
12897237f183SYan Zheng 	root->node = leaf;
1290e02119d5SChris Mason 
1291e02119d5SChris Mason 	btrfs_mark_buffer_dirty(root->node);
1292e02119d5SChris Mason 	btrfs_tree_unlock(root->node);
12936ab6ebb7SNaohiro Aota 
12946ab6ebb7SNaohiro Aota 	return 0;
12957237f183SYan Zheng }
12967237f183SYan Zheng 
12977237f183SYan Zheng int btrfs_init_log_root_tree(struct btrfs_trans_handle *trans,
12987237f183SYan Zheng 			     struct btrfs_fs_info *fs_info)
12997237f183SYan Zheng {
13007237f183SYan Zheng 	struct btrfs_root *log_root;
13017237f183SYan Zheng 
13027237f183SYan Zheng 	log_root = alloc_log_tree(trans, fs_info);
13037237f183SYan Zheng 	if (IS_ERR(log_root))
13047237f183SYan Zheng 		return PTR_ERR(log_root);
13056ab6ebb7SNaohiro Aota 
13063ddebf27SNaohiro Aota 	if (!btrfs_is_zoned(fs_info)) {
13073ddebf27SNaohiro Aota 		int ret = btrfs_alloc_log_tree_node(trans, log_root);
13083ddebf27SNaohiro Aota 
13096ab6ebb7SNaohiro Aota 		if (ret) {
13106ab6ebb7SNaohiro Aota 			btrfs_put_root(log_root);
13116ab6ebb7SNaohiro Aota 			return ret;
13126ab6ebb7SNaohiro Aota 		}
13133ddebf27SNaohiro Aota 	}
13146ab6ebb7SNaohiro Aota 
13157237f183SYan Zheng 	WARN_ON(fs_info->log_root_tree);
13167237f183SYan Zheng 	fs_info->log_root_tree = log_root;
13177237f183SYan Zheng 	return 0;
13187237f183SYan Zheng }
13197237f183SYan Zheng 
13207237f183SYan Zheng int btrfs_add_log_tree(struct btrfs_trans_handle *trans,
13217237f183SYan Zheng 		       struct btrfs_root *root)
13227237f183SYan Zheng {
13230b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
13247237f183SYan Zheng 	struct btrfs_root *log_root;
13257237f183SYan Zheng 	struct btrfs_inode_item *inode_item;
13266ab6ebb7SNaohiro Aota 	int ret;
13277237f183SYan Zheng 
13280b246afaSJeff Mahoney 	log_root = alloc_log_tree(trans, fs_info);
13297237f183SYan Zheng 	if (IS_ERR(log_root))
13307237f183SYan Zheng 		return PTR_ERR(log_root);
13317237f183SYan Zheng 
13326ab6ebb7SNaohiro Aota 	ret = btrfs_alloc_log_tree_node(trans, log_root);
13336ab6ebb7SNaohiro Aota 	if (ret) {
13346ab6ebb7SNaohiro Aota 		btrfs_put_root(log_root);
13356ab6ebb7SNaohiro Aota 		return ret;
13366ab6ebb7SNaohiro Aota 	}
13376ab6ebb7SNaohiro Aota 
13387237f183SYan Zheng 	log_root->last_trans = trans->transid;
13397237f183SYan Zheng 	log_root->root_key.offset = root->root_key.objectid;
13407237f183SYan Zheng 
13417237f183SYan Zheng 	inode_item = &log_root->root_item.inode;
13423cae210fSQu Wenruo 	btrfs_set_stack_inode_generation(inode_item, 1);
13433cae210fSQu Wenruo 	btrfs_set_stack_inode_size(inode_item, 3);
13443cae210fSQu Wenruo 	btrfs_set_stack_inode_nlink(inode_item, 1);
1345da17066cSJeff Mahoney 	btrfs_set_stack_inode_nbytes(inode_item,
13460b246afaSJeff Mahoney 				     fs_info->nodesize);
13473cae210fSQu Wenruo 	btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
13487237f183SYan Zheng 
13495d4f98a2SYan Zheng 	btrfs_set_root_node(&log_root->root_item, log_root->node);
13507237f183SYan Zheng 
13517237f183SYan Zheng 	WARN_ON(root->log_root);
13527237f183SYan Zheng 	root->log_root = log_root;
13537237f183SYan Zheng 	root->log_transid = 0;
1354d1433debSMiao Xie 	root->log_transid_committed = -1;
1355257c62e1SChris Mason 	root->last_log_commit = 0;
1356e02119d5SChris Mason 	return 0;
1357e02119d5SChris Mason }
1358e02119d5SChris Mason 
135949d11beaSJosef Bacik static struct btrfs_root *read_tree_root_path(struct btrfs_root *tree_root,
136049d11beaSJosef Bacik 					      struct btrfs_path *path,
1361cb517eabSMiao Xie 					      struct btrfs_key *key)
1362e02119d5SChris Mason {
1363e02119d5SChris Mason 	struct btrfs_root *root;
1364e02119d5SChris Mason 	struct btrfs_fs_info *fs_info = tree_root->fs_info;
136584234f3aSYan Zheng 	u64 generation;
1366cb517eabSMiao Xie 	int ret;
1367581c1760SQu Wenruo 	int level;
1368cb517eabSMiao Xie 
136996dfcb46SJosef Bacik 	root = btrfs_alloc_root(fs_info, key->objectid, GFP_NOFS);
137049d11beaSJosef Bacik 	if (!root)
137149d11beaSJosef Bacik 		return ERR_PTR(-ENOMEM);
13720f7d52f4SChris Mason 
1373cb517eabSMiao Xie 	ret = btrfs_find_root(tree_root, key, path,
1374cb517eabSMiao Xie 			      &root->root_item, &root->root_key);
13750f7d52f4SChris Mason 	if (ret) {
137613a8a7c8SYan, Zheng 		if (ret > 0)
137713a8a7c8SYan, Zheng 			ret = -ENOENT;
137849d11beaSJosef Bacik 		goto fail;
13790f7d52f4SChris Mason 	}
138013a8a7c8SYan, Zheng 
138184234f3aSYan Zheng 	generation = btrfs_root_generation(&root->root_item);
1382581c1760SQu Wenruo 	level = btrfs_root_level(&root->root_item);
13832ff7e61eSJeff Mahoney 	root->node = read_tree_block(fs_info,
13842ff7e61eSJeff Mahoney 				     btrfs_root_bytenr(&root->root_item),
13851b7ec85eSJosef Bacik 				     key->objectid, generation, level, NULL);
138664c043deSLiu Bo 	if (IS_ERR(root->node)) {
138764c043deSLiu Bo 		ret = PTR_ERR(root->node);
13888c38938cSJosef Bacik 		root->node = NULL;
138949d11beaSJosef Bacik 		goto fail;
1390cb517eabSMiao Xie 	} else if (!btrfs_buffer_uptodate(root->node, generation, 0)) {
1391cb517eabSMiao Xie 		ret = -EIO;
139249d11beaSJosef Bacik 		goto fail;
1393416bc658SJosef Bacik 	}
13945d4f98a2SYan Zheng 	root->commit_root = btrfs_root_node(root);
1395cb517eabSMiao Xie 	return root;
139649d11beaSJosef Bacik fail:
139700246528SJosef Bacik 	btrfs_put_root(root);
139849d11beaSJosef Bacik 	return ERR_PTR(ret);
139949d11beaSJosef Bacik }
140049d11beaSJosef Bacik 
140149d11beaSJosef Bacik struct btrfs_root *btrfs_read_tree_root(struct btrfs_root *tree_root,
140249d11beaSJosef Bacik 					struct btrfs_key *key)
140349d11beaSJosef Bacik {
140449d11beaSJosef Bacik 	struct btrfs_root *root;
140549d11beaSJosef Bacik 	struct btrfs_path *path;
140649d11beaSJosef Bacik 
140749d11beaSJosef Bacik 	path = btrfs_alloc_path();
140849d11beaSJosef Bacik 	if (!path)
140949d11beaSJosef Bacik 		return ERR_PTR(-ENOMEM);
141049d11beaSJosef Bacik 	root = read_tree_root_path(tree_root, path, key);
141149d11beaSJosef Bacik 	btrfs_free_path(path);
141249d11beaSJosef Bacik 
141349d11beaSJosef Bacik 	return root;
1414cb517eabSMiao Xie }
1415cb517eabSMiao Xie 
14162dfb1e43SQu Wenruo /*
14172dfb1e43SQu Wenruo  * Initialize subvolume root in-memory structure
14182dfb1e43SQu Wenruo  *
14192dfb1e43SQu Wenruo  * @anon_dev:	anonymous device to attach to the root, if zero, allocate new
14202dfb1e43SQu Wenruo  */
14212dfb1e43SQu Wenruo static int btrfs_init_fs_root(struct btrfs_root *root, dev_t anon_dev)
1422cb517eabSMiao Xie {
1423cb517eabSMiao Xie 	int ret;
1424dcc3eb96SNikolay Borisov 	unsigned int nofs_flag;
1425cb517eabSMiao Xie 
1426dcc3eb96SNikolay Borisov 	/*
1427dcc3eb96SNikolay Borisov 	 * We might be called under a transaction (e.g. indirect backref
1428dcc3eb96SNikolay Borisov 	 * resolution) which could deadlock if it triggers memory reclaim
1429dcc3eb96SNikolay Borisov 	 */
1430dcc3eb96SNikolay Borisov 	nofs_flag = memalloc_nofs_save();
1431dcc3eb96SNikolay Borisov 	ret = btrfs_drew_lock_init(&root->snapshot_lock);
1432dcc3eb96SNikolay Borisov 	memalloc_nofs_restore(nofs_flag);
1433dcc3eb96SNikolay Borisov 	if (ret)
14348257b2dcSMiao Xie 		goto fail;
14358257b2dcSMiao Xie 
1436aeb935a4SQu Wenruo 	if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID &&
1437aeb935a4SQu Wenruo 	    root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID) {
143892a7cc42SQu Wenruo 		set_bit(BTRFS_ROOT_SHAREABLE, &root->state);
1439f39e4571SJosef Bacik 		btrfs_check_and_init_root_item(&root->root_item);
1440f39e4571SJosef Bacik 	}
1441f39e4571SJosef Bacik 
1442851fd730SQu Wenruo 	/*
1443851fd730SQu Wenruo 	 * Don't assign anonymous block device to roots that are not exposed to
1444851fd730SQu Wenruo 	 * userspace, the id pool is limited to 1M
1445851fd730SQu Wenruo 	 */
1446851fd730SQu Wenruo 	if (is_fstree(root->root_key.objectid) &&
1447851fd730SQu Wenruo 	    btrfs_root_refs(&root->root_item) > 0) {
14482dfb1e43SQu Wenruo 		if (!anon_dev) {
1449cb517eabSMiao Xie 			ret = get_anon_bdev(&root->anon_dev);
1450cb517eabSMiao Xie 			if (ret)
1451876d2cf1SLiu Bo 				goto fail;
14522dfb1e43SQu Wenruo 		} else {
14532dfb1e43SQu Wenruo 			root->anon_dev = anon_dev;
14542dfb1e43SQu Wenruo 		}
1455851fd730SQu Wenruo 	}
1456f32e48e9SChandan Rajendra 
1457f32e48e9SChandan Rajendra 	mutex_lock(&root->objectid_mutex);
1458453e4873SNikolay Borisov 	ret = btrfs_init_root_free_objectid(root);
1459f32e48e9SChandan Rajendra 	if (ret) {
1460f32e48e9SChandan Rajendra 		mutex_unlock(&root->objectid_mutex);
1461876d2cf1SLiu Bo 		goto fail;
1462f32e48e9SChandan Rajendra 	}
1463f32e48e9SChandan Rajendra 
14646b8fad57SNikolay Borisov 	ASSERT(root->free_objectid <= BTRFS_LAST_FREE_OBJECTID);
1465f32e48e9SChandan Rajendra 
1466f32e48e9SChandan Rajendra 	mutex_unlock(&root->objectid_mutex);
1467f32e48e9SChandan Rajendra 
1468cb517eabSMiao Xie 	return 0;
1469cb517eabSMiao Xie fail:
147084db5ccfSDavid Sterba 	/* The caller is responsible to call btrfs_free_fs_root */
1471cb517eabSMiao Xie 	return ret;
1472cb517eabSMiao Xie }
1473cb517eabSMiao Xie 
1474a98db0f3SJosef Bacik static struct btrfs_root *btrfs_lookup_fs_root(struct btrfs_fs_info *fs_info,
1475cb517eabSMiao Xie 					       u64 root_id)
1476cb517eabSMiao Xie {
1477cb517eabSMiao Xie 	struct btrfs_root *root;
1478cb517eabSMiao Xie 
1479cb517eabSMiao Xie 	spin_lock(&fs_info->fs_roots_radix_lock);
1480cb517eabSMiao Xie 	root = radix_tree_lookup(&fs_info->fs_roots_radix,
1481cb517eabSMiao Xie 				 (unsigned long)root_id);
1482bc44d7c4SJosef Bacik 	if (root)
148300246528SJosef Bacik 		root = btrfs_grab_root(root);
1484cb517eabSMiao Xie 	spin_unlock(&fs_info->fs_roots_radix_lock);
1485cb517eabSMiao Xie 	return root;
1486cb517eabSMiao Xie }
1487cb517eabSMiao Xie 
148849d11beaSJosef Bacik static struct btrfs_root *btrfs_get_global_root(struct btrfs_fs_info *fs_info,
148949d11beaSJosef Bacik 						u64 objectid)
149049d11beaSJosef Bacik {
149149d11beaSJosef Bacik 	if (objectid == BTRFS_ROOT_TREE_OBJECTID)
149249d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->tree_root);
149349d11beaSJosef Bacik 	if (objectid == BTRFS_EXTENT_TREE_OBJECTID)
149449d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->extent_root);
149549d11beaSJosef Bacik 	if (objectid == BTRFS_CHUNK_TREE_OBJECTID)
149649d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->chunk_root);
149749d11beaSJosef Bacik 	if (objectid == BTRFS_DEV_TREE_OBJECTID)
149849d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->dev_root);
149949d11beaSJosef Bacik 	if (objectid == BTRFS_CSUM_TREE_OBJECTID)
150049d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->csum_root);
150149d11beaSJosef Bacik 	if (objectid == BTRFS_QUOTA_TREE_OBJECTID)
150249d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->quota_root) ?
150349d11beaSJosef Bacik 			fs_info->quota_root : ERR_PTR(-ENOENT);
150449d11beaSJosef Bacik 	if (objectid == BTRFS_UUID_TREE_OBJECTID)
150549d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->uuid_root) ?
150649d11beaSJosef Bacik 			fs_info->uuid_root : ERR_PTR(-ENOENT);
150749d11beaSJosef Bacik 	if (objectid == BTRFS_FREE_SPACE_TREE_OBJECTID)
150849d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->free_space_root) ?
150949d11beaSJosef Bacik 			fs_info->free_space_root : ERR_PTR(-ENOENT);
151049d11beaSJosef Bacik 	return NULL;
151149d11beaSJosef Bacik }
151249d11beaSJosef Bacik 
1513cb517eabSMiao Xie int btrfs_insert_fs_root(struct btrfs_fs_info *fs_info,
1514cb517eabSMiao Xie 			 struct btrfs_root *root)
1515cb517eabSMiao Xie {
1516cb517eabSMiao Xie 	int ret;
1517cb517eabSMiao Xie 
1518e1860a77SDavid Sterba 	ret = radix_tree_preload(GFP_NOFS);
1519cb517eabSMiao Xie 	if (ret)
1520cb517eabSMiao Xie 		return ret;
1521cb517eabSMiao Xie 
1522cb517eabSMiao Xie 	spin_lock(&fs_info->fs_roots_radix_lock);
1523cb517eabSMiao Xie 	ret = radix_tree_insert(&fs_info->fs_roots_radix,
1524cb517eabSMiao Xie 				(unsigned long)root->root_key.objectid,
1525cb517eabSMiao Xie 				root);
1526af01d2e5SJosef Bacik 	if (ret == 0) {
152700246528SJosef Bacik 		btrfs_grab_root(root);
152827cdeb70SMiao Xie 		set_bit(BTRFS_ROOT_IN_RADIX, &root->state);
1529af01d2e5SJosef Bacik 	}
1530cb517eabSMiao Xie 	spin_unlock(&fs_info->fs_roots_radix_lock);
1531cb517eabSMiao Xie 	radix_tree_preload_end();
1532cb517eabSMiao Xie 
1533cb517eabSMiao Xie 	return ret;
1534cb517eabSMiao Xie }
1535cb517eabSMiao Xie 
1536bd647ce3SJosef Bacik void btrfs_check_leaked_roots(struct btrfs_fs_info *fs_info)
1537bd647ce3SJosef Bacik {
1538bd647ce3SJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
1539bd647ce3SJosef Bacik 	struct btrfs_root *root;
1540bd647ce3SJosef Bacik 
1541bd647ce3SJosef Bacik 	while (!list_empty(&fs_info->allocated_roots)) {
1542457f1864SJosef Bacik 		char buf[BTRFS_ROOT_NAME_BUF_LEN];
1543457f1864SJosef Bacik 
1544bd647ce3SJosef Bacik 		root = list_first_entry(&fs_info->allocated_roots,
1545bd647ce3SJosef Bacik 					struct btrfs_root, leak_list);
1546457f1864SJosef Bacik 		btrfs_err(fs_info, "leaked root %s refcount %d",
154771008734SJosef Bacik 			  btrfs_root_name(&root->root_key, buf),
1548bd647ce3SJosef Bacik 			  refcount_read(&root->refs));
1549bd647ce3SJosef Bacik 		while (refcount_read(&root->refs) > 1)
155000246528SJosef Bacik 			btrfs_put_root(root);
155100246528SJosef Bacik 		btrfs_put_root(root);
1552bd647ce3SJosef Bacik 	}
1553bd647ce3SJosef Bacik #endif
1554bd647ce3SJosef Bacik }
1555bd647ce3SJosef Bacik 
15560d4b0463SJosef Bacik void btrfs_free_fs_info(struct btrfs_fs_info *fs_info)
15570d4b0463SJosef Bacik {
1558141386e1SJosef Bacik 	percpu_counter_destroy(&fs_info->dirty_metadata_bytes);
1559141386e1SJosef Bacik 	percpu_counter_destroy(&fs_info->delalloc_bytes);
15605deb17e1SJosef Bacik 	percpu_counter_destroy(&fs_info->ordered_bytes);
1561141386e1SJosef Bacik 	percpu_counter_destroy(&fs_info->dev_replace.bio_counter);
1562141386e1SJosef Bacik 	btrfs_free_csum_hash(fs_info);
1563141386e1SJosef Bacik 	btrfs_free_stripe_hash_table(fs_info);
1564141386e1SJosef Bacik 	btrfs_free_ref_cache(fs_info);
15650d4b0463SJosef Bacik 	kfree(fs_info->balance_ctl);
15660d4b0463SJosef Bacik 	kfree(fs_info->delayed_root);
156700246528SJosef Bacik 	btrfs_put_root(fs_info->extent_root);
156800246528SJosef Bacik 	btrfs_put_root(fs_info->tree_root);
156900246528SJosef Bacik 	btrfs_put_root(fs_info->chunk_root);
157000246528SJosef Bacik 	btrfs_put_root(fs_info->dev_root);
157100246528SJosef Bacik 	btrfs_put_root(fs_info->csum_root);
157200246528SJosef Bacik 	btrfs_put_root(fs_info->quota_root);
157300246528SJosef Bacik 	btrfs_put_root(fs_info->uuid_root);
157400246528SJosef Bacik 	btrfs_put_root(fs_info->free_space_root);
157500246528SJosef Bacik 	btrfs_put_root(fs_info->fs_root);
1576aeb935a4SQu Wenruo 	btrfs_put_root(fs_info->data_reloc_root);
1577bd647ce3SJosef Bacik 	btrfs_check_leaked_roots(fs_info);
15783fd63727SJosef Bacik 	btrfs_extent_buffer_leak_debug_check(fs_info);
15790d4b0463SJosef Bacik 	kfree(fs_info->super_copy);
15800d4b0463SJosef Bacik 	kfree(fs_info->super_for_commit);
15810d4b0463SJosef Bacik 	kvfree(fs_info);
15820d4b0463SJosef Bacik }
15830d4b0463SJosef Bacik 
15840d4b0463SJosef Bacik 
15852dfb1e43SQu Wenruo /*
15862dfb1e43SQu Wenruo  * Get an in-memory reference of a root structure.
15872dfb1e43SQu Wenruo  *
15882dfb1e43SQu Wenruo  * For essential trees like root/extent tree, we grab it from fs_info directly.
15892dfb1e43SQu Wenruo  * For subvolume trees, we check the cached filesystem roots first. If not
15902dfb1e43SQu Wenruo  * found, then read it from disk and add it to cached fs roots.
15912dfb1e43SQu Wenruo  *
15922dfb1e43SQu Wenruo  * Caller should release the root by calling btrfs_put_root() after the usage.
15932dfb1e43SQu Wenruo  *
15942dfb1e43SQu Wenruo  * NOTE: Reloc and log trees can't be read by this function as they share the
15952dfb1e43SQu Wenruo  *	 same root objectid.
15962dfb1e43SQu Wenruo  *
15972dfb1e43SQu Wenruo  * @objectid:	root id
15982dfb1e43SQu Wenruo  * @anon_dev:	preallocated anonymous block device number for new roots,
15992dfb1e43SQu Wenruo  * 		pass 0 for new allocation.
16002dfb1e43SQu Wenruo  * @check_ref:	whether to check root item references, If true, return -ENOENT
16012dfb1e43SQu Wenruo  *		for orphan roots
16022dfb1e43SQu Wenruo  */
16032dfb1e43SQu Wenruo static struct btrfs_root *btrfs_get_root_ref(struct btrfs_fs_info *fs_info,
16042dfb1e43SQu Wenruo 					     u64 objectid, dev_t anon_dev,
16052dfb1e43SQu Wenruo 					     bool check_ref)
16065eda7b5eSChris Mason {
16075eda7b5eSChris Mason 	struct btrfs_root *root;
1608381cf658SDavid Sterba 	struct btrfs_path *path;
16091d4c08e0SDavid Sterba 	struct btrfs_key key;
16105eda7b5eSChris Mason 	int ret;
16115eda7b5eSChris Mason 
161249d11beaSJosef Bacik 	root = btrfs_get_global_root(fs_info, objectid);
161349d11beaSJosef Bacik 	if (root)
161449d11beaSJosef Bacik 		return root;
16154df27c4dSYan, Zheng again:
161656e9357aSDavid Sterba 	root = btrfs_lookup_fs_root(fs_info, objectid);
161748475471SStefan Behrens 	if (root) {
16182dfb1e43SQu Wenruo 		/* Shouldn't get preallocated anon_dev for cached roots */
16192dfb1e43SQu Wenruo 		ASSERT(!anon_dev);
1620bc44d7c4SJosef Bacik 		if (check_ref && btrfs_root_refs(&root->root_item) == 0) {
162100246528SJosef Bacik 			btrfs_put_root(root);
162248475471SStefan Behrens 			return ERR_PTR(-ENOENT);
1623bc44d7c4SJosef Bacik 		}
16245eda7b5eSChris Mason 		return root;
162548475471SStefan Behrens 	}
16265eda7b5eSChris Mason 
162756e9357aSDavid Sterba 	key.objectid = objectid;
162856e9357aSDavid Sterba 	key.type = BTRFS_ROOT_ITEM_KEY;
162956e9357aSDavid Sterba 	key.offset = (u64)-1;
163056e9357aSDavid Sterba 	root = btrfs_read_tree_root(fs_info->tree_root, &key);
16315eda7b5eSChris Mason 	if (IS_ERR(root))
16325eda7b5eSChris Mason 		return root;
16333394e160SChris Mason 
1634c00869f1SMiao Xie 	if (check_ref && btrfs_root_refs(&root->root_item) == 0) {
1635d68fc57bSYan, Zheng 		ret = -ENOENT;
1636d68fc57bSYan, Zheng 		goto fail;
1637d68fc57bSYan, Zheng 	}
1638d68fc57bSYan, Zheng 
16392dfb1e43SQu Wenruo 	ret = btrfs_init_fs_root(root, anon_dev);
1640cb517eabSMiao Xie 	if (ret)
1641cb517eabSMiao Xie 		goto fail;
1642cb517eabSMiao Xie 
1643381cf658SDavid Sterba 	path = btrfs_alloc_path();
1644381cf658SDavid Sterba 	if (!path) {
1645381cf658SDavid Sterba 		ret = -ENOMEM;
1646381cf658SDavid Sterba 		goto fail;
1647381cf658SDavid Sterba 	}
16481d4c08e0SDavid Sterba 	key.objectid = BTRFS_ORPHAN_OBJECTID;
16491d4c08e0SDavid Sterba 	key.type = BTRFS_ORPHAN_ITEM_KEY;
165056e9357aSDavid Sterba 	key.offset = objectid;
16511d4c08e0SDavid Sterba 
16521d4c08e0SDavid Sterba 	ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
1653381cf658SDavid Sterba 	btrfs_free_path(path);
1654d68fc57bSYan, Zheng 	if (ret < 0)
1655d68fc57bSYan, Zheng 		goto fail;
1656d68fc57bSYan, Zheng 	if (ret == 0)
165727cdeb70SMiao Xie 		set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state);
1658d68fc57bSYan, Zheng 
1659cb517eabSMiao Xie 	ret = btrfs_insert_fs_root(fs_info, root);
16600f7d52f4SChris Mason 	if (ret) {
166100246528SJosef Bacik 		btrfs_put_root(root);
16624785e24fSJosef Bacik 		if (ret == -EEXIST)
16634df27c4dSYan, Zheng 			goto again;
16644df27c4dSYan, Zheng 		goto fail;
16654df27c4dSYan, Zheng 	}
1666edbd8d4eSChris Mason 	return root;
16674df27c4dSYan, Zheng fail:
16688c38938cSJosef Bacik 	btrfs_put_root(root);
16694df27c4dSYan, Zheng 	return ERR_PTR(ret);
1670edbd8d4eSChris Mason }
1671edbd8d4eSChris Mason 
16722dfb1e43SQu Wenruo /*
16732dfb1e43SQu Wenruo  * Get in-memory reference of a root structure
16742dfb1e43SQu Wenruo  *
16752dfb1e43SQu Wenruo  * @objectid:	tree objectid
16762dfb1e43SQu Wenruo  * @check_ref:	if set, verify that the tree exists and the item has at least
16772dfb1e43SQu Wenruo  *		one reference
16782dfb1e43SQu Wenruo  */
16792dfb1e43SQu Wenruo struct btrfs_root *btrfs_get_fs_root(struct btrfs_fs_info *fs_info,
16802dfb1e43SQu Wenruo 				     u64 objectid, bool check_ref)
16812dfb1e43SQu Wenruo {
16822dfb1e43SQu Wenruo 	return btrfs_get_root_ref(fs_info, objectid, 0, check_ref);
16832dfb1e43SQu Wenruo }
16842dfb1e43SQu Wenruo 
16852dfb1e43SQu Wenruo /*
16862dfb1e43SQu Wenruo  * Get in-memory reference of a root structure, created as new, optionally pass
16872dfb1e43SQu Wenruo  * the anonymous block device id
16882dfb1e43SQu Wenruo  *
16892dfb1e43SQu Wenruo  * @objectid:	tree objectid
16902dfb1e43SQu Wenruo  * @anon_dev:	if zero, allocate a new anonymous block device or use the
16912dfb1e43SQu Wenruo  *		parameter value
16922dfb1e43SQu Wenruo  */
16932dfb1e43SQu Wenruo struct btrfs_root *btrfs_get_new_fs_root(struct btrfs_fs_info *fs_info,
16942dfb1e43SQu Wenruo 					 u64 objectid, dev_t anon_dev)
16952dfb1e43SQu Wenruo {
16962dfb1e43SQu Wenruo 	return btrfs_get_root_ref(fs_info, objectid, anon_dev, true);
16972dfb1e43SQu Wenruo }
16982dfb1e43SQu Wenruo 
16998b712842SChris Mason /*
170049d11beaSJosef Bacik  * btrfs_get_fs_root_commit_root - return a root for the given objectid
170149d11beaSJosef Bacik  * @fs_info:	the fs_info
170249d11beaSJosef Bacik  * @objectid:	the objectid we need to lookup
170349d11beaSJosef Bacik  *
170449d11beaSJosef Bacik  * This is exclusively used for backref walking, and exists specifically because
170549d11beaSJosef Bacik  * of how qgroups does lookups.  Qgroups will do a backref lookup at delayed ref
170649d11beaSJosef Bacik  * creation time, which means we may have to read the tree_root in order to look
170749d11beaSJosef Bacik  * up a fs root that is not in memory.  If the root is not in memory we will
170849d11beaSJosef Bacik  * read the tree root commit root and look up the fs root from there.  This is a
170949d11beaSJosef Bacik  * temporary root, it will not be inserted into the radix tree as it doesn't
171049d11beaSJosef Bacik  * have the most uptodate information, it'll simply be discarded once the
171149d11beaSJosef Bacik  * backref code is finished using the root.
171249d11beaSJosef Bacik  */
171349d11beaSJosef Bacik struct btrfs_root *btrfs_get_fs_root_commit_root(struct btrfs_fs_info *fs_info,
171449d11beaSJosef Bacik 						 struct btrfs_path *path,
171549d11beaSJosef Bacik 						 u64 objectid)
171649d11beaSJosef Bacik {
171749d11beaSJosef Bacik 	struct btrfs_root *root;
171849d11beaSJosef Bacik 	struct btrfs_key key;
171949d11beaSJosef Bacik 
172049d11beaSJosef Bacik 	ASSERT(path->search_commit_root && path->skip_locking);
172149d11beaSJosef Bacik 
172249d11beaSJosef Bacik 	/*
172349d11beaSJosef Bacik 	 * This can return -ENOENT if we ask for a root that doesn't exist, but
172449d11beaSJosef Bacik 	 * since this is called via the backref walking code we won't be looking
172549d11beaSJosef Bacik 	 * up a root that doesn't exist, unless there's corruption.  So if root
172649d11beaSJosef Bacik 	 * != NULL just return it.
172749d11beaSJosef Bacik 	 */
172849d11beaSJosef Bacik 	root = btrfs_get_global_root(fs_info, objectid);
172949d11beaSJosef Bacik 	if (root)
173049d11beaSJosef Bacik 		return root;
173149d11beaSJosef Bacik 
173249d11beaSJosef Bacik 	root = btrfs_lookup_fs_root(fs_info, objectid);
173349d11beaSJosef Bacik 	if (root)
173449d11beaSJosef Bacik 		return root;
173549d11beaSJosef Bacik 
173649d11beaSJosef Bacik 	key.objectid = objectid;
173749d11beaSJosef Bacik 	key.type = BTRFS_ROOT_ITEM_KEY;
173849d11beaSJosef Bacik 	key.offset = (u64)-1;
173949d11beaSJosef Bacik 	root = read_tree_root_path(fs_info->tree_root, path, &key);
174049d11beaSJosef Bacik 	btrfs_release_path(path);
174149d11beaSJosef Bacik 
174249d11beaSJosef Bacik 	return root;
174349d11beaSJosef Bacik }
174449d11beaSJosef Bacik 
174549d11beaSJosef Bacik /*
17468b712842SChris Mason  * called by the kthread helper functions to finally call the bio end_io
17478b712842SChris Mason  * functions.  This is where read checksum verification actually happens
17488b712842SChris Mason  */
17498b712842SChris Mason static void end_workqueue_fn(struct btrfs_work *work)
1750ce9adaa5SChris Mason {
1751ce9adaa5SChris Mason 	struct bio *bio;
175297eb6b69SDavid Sterba 	struct btrfs_end_io_wq *end_io_wq;
1753ce9adaa5SChris Mason 
175497eb6b69SDavid Sterba 	end_io_wq = container_of(work, struct btrfs_end_io_wq, work);
1755ce9adaa5SChris Mason 	bio = end_io_wq->bio;
17568b712842SChris Mason 
17574e4cbee9SChristoph Hellwig 	bio->bi_status = end_io_wq->status;
1758ce9adaa5SChris Mason 	bio->bi_private = end_io_wq->private;
1759ce9adaa5SChris Mason 	bio->bi_end_io = end_io_wq->end_io;
17604246a0b6SChristoph Hellwig 	bio_endio(bio);
17619be490f1SOmar Sandoval 	kmem_cache_free(btrfs_end_io_wq_cache, end_io_wq);
1762ce9adaa5SChris Mason }
176344b8bd7eSChris Mason 
1764a74a4b97SChris Mason static int cleaner_kthread(void *arg)
1765a74a4b97SChris Mason {
1766a74a4b97SChris Mason 	struct btrfs_root *root = arg;
17670b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
1768d0278245SMiao Xie 	int again;
1769a74a4b97SChris Mason 
1770d6fd0ae2SOmar Sandoval 	while (1) {
1771d0278245SMiao Xie 		again = 0;
17729d1a2a3aSDavid Sterba 
1773fd340d0fSJosef Bacik 		set_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags);
1774fd340d0fSJosef Bacik 
1775d0278245SMiao Xie 		/* Make the cleaner go to sleep early. */
17762ff7e61eSJeff Mahoney 		if (btrfs_need_cleaner_sleep(fs_info))
1777d0278245SMiao Xie 			goto sleep;
1778d0278245SMiao Xie 
177990c711abSZygo Blaxell 		/*
178090c711abSZygo Blaxell 		 * Do not do anything if we might cause open_ctree() to block
178190c711abSZygo Blaxell 		 * before we have finished mounting the filesystem.
178290c711abSZygo Blaxell 		 */
17830b246afaSJeff Mahoney 		if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
178490c711abSZygo Blaxell 			goto sleep;
178590c711abSZygo Blaxell 
17860b246afaSJeff Mahoney 		if (!mutex_trylock(&fs_info->cleaner_mutex))
1787d0278245SMiao Xie 			goto sleep;
1788d0278245SMiao Xie 
1789dc7f370cSMiao Xie 		/*
1790dc7f370cSMiao Xie 		 * Avoid the problem that we change the status of the fs
1791dc7f370cSMiao Xie 		 * during the above check and trylock.
1792dc7f370cSMiao Xie 		 */
17932ff7e61eSJeff Mahoney 		if (btrfs_need_cleaner_sleep(fs_info)) {
17940b246afaSJeff Mahoney 			mutex_unlock(&fs_info->cleaner_mutex);
1795dc7f370cSMiao Xie 			goto sleep;
1796dc7f370cSMiao Xie 		}
1797dc7f370cSMiao Xie 
17982ff7e61eSJeff Mahoney 		btrfs_run_delayed_iputs(fs_info);
1799c2d6cb16SFilipe Manana 
18009d1a2a3aSDavid Sterba 		again = btrfs_clean_one_deleted_snapshot(root);
18010b246afaSJeff Mahoney 		mutex_unlock(&fs_info->cleaner_mutex);
1802a74a4b97SChris Mason 
1803d0278245SMiao Xie 		/*
180405323cd1SMiao Xie 		 * The defragger has dealt with the R/O remount and umount,
180505323cd1SMiao Xie 		 * needn't do anything special here.
1806d0278245SMiao Xie 		 */
18070b246afaSJeff Mahoney 		btrfs_run_defrag_inodes(fs_info);
180867c5e7d4SFilipe Manana 
180967c5e7d4SFilipe Manana 		/*
181067c5e7d4SFilipe Manana 		 * Acquires fs_info->delete_unused_bgs_mutex to avoid racing
181167c5e7d4SFilipe Manana 		 * with relocation (btrfs_relocate_chunk) and relocation
181267c5e7d4SFilipe Manana 		 * acquires fs_info->cleaner_mutex (btrfs_relocate_block_group)
181367c5e7d4SFilipe Manana 		 * after acquiring fs_info->delete_unused_bgs_mutex. So we
181467c5e7d4SFilipe Manana 		 * can't hold, nor need to, fs_info->cleaner_mutex when deleting
181567c5e7d4SFilipe Manana 		 * unused block groups.
181667c5e7d4SFilipe Manana 		 */
18170b246afaSJeff Mahoney 		btrfs_delete_unused_bgs(fs_info);
1818d0278245SMiao Xie sleep:
1819a0a1db70SFilipe Manana 		clear_and_wake_up_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags);
1820d6fd0ae2SOmar Sandoval 		if (kthread_should_park())
1821d6fd0ae2SOmar Sandoval 			kthread_parkme();
1822d6fd0ae2SOmar Sandoval 		if (kthread_should_stop())
1823d6fd0ae2SOmar Sandoval 			return 0;
1824838fe188SJiri Kosina 		if (!again) {
1825a74a4b97SChris Mason 			set_current_state(TASK_INTERRUPTIBLE);
1826a74a4b97SChris Mason 			schedule();
1827a74a4b97SChris Mason 			__set_current_state(TASK_RUNNING);
1828a74a4b97SChris Mason 		}
1829da288d28SFilipe Manana 	}
1830a74a4b97SChris Mason }
1831a74a4b97SChris Mason 
1832a74a4b97SChris Mason static int transaction_kthread(void *arg)
1833a74a4b97SChris Mason {
1834a74a4b97SChris Mason 	struct btrfs_root *root = arg;
18350b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
1836a74a4b97SChris Mason 	struct btrfs_trans_handle *trans;
1837a74a4b97SChris Mason 	struct btrfs_transaction *cur;
18388929ecfaSYan, Zheng 	u64 transid;
1839643900beSNikolay Borisov 	time64_t delta;
1840a74a4b97SChris Mason 	unsigned long delay;
1841914b2007SJan Kara 	bool cannot_commit;
1842a74a4b97SChris Mason 
1843a74a4b97SChris Mason 	do {
1844914b2007SJan Kara 		cannot_commit = false;
1845ba1bc00fSNikolay Borisov 		delay = msecs_to_jiffies(fs_info->commit_interval * 1000);
18460b246afaSJeff Mahoney 		mutex_lock(&fs_info->transaction_kthread_mutex);
1847a74a4b97SChris Mason 
18480b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
18490b246afaSJeff Mahoney 		cur = fs_info->running_transaction;
1850a74a4b97SChris Mason 		if (!cur) {
18510b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
1852a74a4b97SChris Mason 			goto sleep;
1853a74a4b97SChris Mason 		}
185431153d81SYan Zheng 
1855643900beSNikolay Borisov 		delta = ktime_get_seconds() - cur->start_time;
18563296bf56SQu Wenruo 		if (cur->state < TRANS_STATE_COMMIT_START &&
1857643900beSNikolay Borisov 		    delta < fs_info->commit_interval) {
18580b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
1859fb8a7e94SNikolay Borisov 			delay -= msecs_to_jiffies((delta - 1) * 1000);
1860fb8a7e94SNikolay Borisov 			delay = min(delay,
1861fb8a7e94SNikolay Borisov 				    msecs_to_jiffies(fs_info->commit_interval * 1000));
1862a74a4b97SChris Mason 			goto sleep;
1863a74a4b97SChris Mason 		}
18648929ecfaSYan, Zheng 		transid = cur->transid;
18650b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
186656bec294SChris Mason 
186779787eaaSJeff Mahoney 		/* If the file system is aborted, this will always fail. */
1868354aa0fbSMiao Xie 		trans = btrfs_attach_transaction(root);
1869914b2007SJan Kara 		if (IS_ERR(trans)) {
1870354aa0fbSMiao Xie 			if (PTR_ERR(trans) != -ENOENT)
1871914b2007SJan Kara 				cannot_commit = true;
187279787eaaSJeff Mahoney 			goto sleep;
1873914b2007SJan Kara 		}
18748929ecfaSYan, Zheng 		if (transid == trans->transid) {
18753a45bb20SJeff Mahoney 			btrfs_commit_transaction(trans);
18768929ecfaSYan, Zheng 		} else {
18773a45bb20SJeff Mahoney 			btrfs_end_transaction(trans);
18788929ecfaSYan, Zheng 		}
1879a74a4b97SChris Mason sleep:
18800b246afaSJeff Mahoney 		wake_up_process(fs_info->cleaner_kthread);
18810b246afaSJeff Mahoney 		mutex_unlock(&fs_info->transaction_kthread_mutex);
1882a74a4b97SChris Mason 
18834e121c06SJosef Bacik 		if (unlikely(test_bit(BTRFS_FS_STATE_ERROR,
18840b246afaSJeff Mahoney 				      &fs_info->fs_state)))
18852ff7e61eSJeff Mahoney 			btrfs_cleanup_transaction(fs_info);
18868929ecfaSYan, Zheng 		if (!kthread_should_stop() &&
18870b246afaSJeff Mahoney 				(!btrfs_transaction_blocked(fs_info) ||
1888914b2007SJan Kara 				 cannot_commit))
1889bc5511d0SNikolay Borisov 			schedule_timeout_interruptible(delay);
1890a74a4b97SChris Mason 	} while (!kthread_should_stop());
1891a74a4b97SChris Mason 	return 0;
1892a74a4b97SChris Mason }
1893a74a4b97SChris Mason 
1894af31f5e5SChris Mason /*
189501f0f9daSNikolay Borisov  * This will find the highest generation in the array of root backups.  The
189601f0f9daSNikolay Borisov  * index of the highest array is returned, or -EINVAL if we can't find
189701f0f9daSNikolay Borisov  * anything.
1898af31f5e5SChris Mason  *
1899af31f5e5SChris Mason  * We check to make sure the array is valid by comparing the
1900af31f5e5SChris Mason  * generation of the latest  root in the array with the generation
1901af31f5e5SChris Mason  * in the super block.  If they don't match we pitch it.
1902af31f5e5SChris Mason  */
190301f0f9daSNikolay Borisov static int find_newest_super_backup(struct btrfs_fs_info *info)
1904af31f5e5SChris Mason {
190501f0f9daSNikolay Borisov 	const u64 newest_gen = btrfs_super_generation(info->super_copy);
1906af31f5e5SChris Mason 	u64 cur;
1907af31f5e5SChris Mason 	struct btrfs_root_backup *root_backup;
1908af31f5e5SChris Mason 	int i;
1909af31f5e5SChris Mason 
1910af31f5e5SChris Mason 	for (i = 0; i < BTRFS_NUM_BACKUP_ROOTS; i++) {
1911af31f5e5SChris Mason 		root_backup = info->super_copy->super_roots + i;
1912af31f5e5SChris Mason 		cur = btrfs_backup_tree_root_gen(root_backup);
1913af31f5e5SChris Mason 		if (cur == newest_gen)
191401f0f9daSNikolay Borisov 			return i;
1915af31f5e5SChris Mason 	}
1916af31f5e5SChris Mason 
191701f0f9daSNikolay Borisov 	return -EINVAL;
1918af31f5e5SChris Mason }
1919af31f5e5SChris Mason 
1920af31f5e5SChris Mason /*
1921af31f5e5SChris Mason  * copy all the root pointers into the super backup array.
1922af31f5e5SChris Mason  * this will bump the backup pointer by one when it is
1923af31f5e5SChris Mason  * done
1924af31f5e5SChris Mason  */
1925af31f5e5SChris Mason static void backup_super_roots(struct btrfs_fs_info *info)
1926af31f5e5SChris Mason {
19276ef108ddSNikolay Borisov 	const int next_backup = info->backup_root_index;
1928af31f5e5SChris Mason 	struct btrfs_root_backup *root_backup;
1929af31f5e5SChris Mason 
1930af31f5e5SChris Mason 	root_backup = info->super_for_commit->super_roots + next_backup;
1931af31f5e5SChris Mason 
1932af31f5e5SChris Mason 	/*
1933af31f5e5SChris Mason 	 * make sure all of our padding and empty slots get zero filled
1934af31f5e5SChris Mason 	 * regardless of which ones we use today
1935af31f5e5SChris Mason 	 */
1936af31f5e5SChris Mason 	memset(root_backup, 0, sizeof(*root_backup));
1937af31f5e5SChris Mason 
1938af31f5e5SChris Mason 	info->backup_root_index = (next_backup + 1) % BTRFS_NUM_BACKUP_ROOTS;
1939af31f5e5SChris Mason 
1940af31f5e5SChris Mason 	btrfs_set_backup_tree_root(root_backup, info->tree_root->node->start);
1941af31f5e5SChris Mason 	btrfs_set_backup_tree_root_gen(root_backup,
1942af31f5e5SChris Mason 			       btrfs_header_generation(info->tree_root->node));
1943af31f5e5SChris Mason 
1944af31f5e5SChris Mason 	btrfs_set_backup_tree_root_level(root_backup,
1945af31f5e5SChris Mason 			       btrfs_header_level(info->tree_root->node));
1946af31f5e5SChris Mason 
1947af31f5e5SChris Mason 	btrfs_set_backup_chunk_root(root_backup, info->chunk_root->node->start);
1948af31f5e5SChris Mason 	btrfs_set_backup_chunk_root_gen(root_backup,
1949af31f5e5SChris Mason 			       btrfs_header_generation(info->chunk_root->node));
1950af31f5e5SChris Mason 	btrfs_set_backup_chunk_root_level(root_backup,
1951af31f5e5SChris Mason 			       btrfs_header_level(info->chunk_root->node));
1952af31f5e5SChris Mason 
1953af31f5e5SChris Mason 	btrfs_set_backup_extent_root(root_backup, info->extent_root->node->start);
1954af31f5e5SChris Mason 	btrfs_set_backup_extent_root_gen(root_backup,
1955af31f5e5SChris Mason 			       btrfs_header_generation(info->extent_root->node));
1956af31f5e5SChris Mason 	btrfs_set_backup_extent_root_level(root_backup,
1957af31f5e5SChris Mason 			       btrfs_header_level(info->extent_root->node));
1958af31f5e5SChris Mason 
19597c7e82a7SChris Mason 	/*
19607c7e82a7SChris Mason 	 * we might commit during log recovery, which happens before we set
19617c7e82a7SChris Mason 	 * the fs_root.  Make sure it is valid before we fill it in.
19627c7e82a7SChris Mason 	 */
19637c7e82a7SChris Mason 	if (info->fs_root && info->fs_root->node) {
19647c7e82a7SChris Mason 		btrfs_set_backup_fs_root(root_backup,
19657c7e82a7SChris Mason 					 info->fs_root->node->start);
1966af31f5e5SChris Mason 		btrfs_set_backup_fs_root_gen(root_backup,
1967af31f5e5SChris Mason 			       btrfs_header_generation(info->fs_root->node));
1968af31f5e5SChris Mason 		btrfs_set_backup_fs_root_level(root_backup,
1969af31f5e5SChris Mason 			       btrfs_header_level(info->fs_root->node));
19707c7e82a7SChris Mason 	}
1971af31f5e5SChris Mason 
1972af31f5e5SChris Mason 	btrfs_set_backup_dev_root(root_backup, info->dev_root->node->start);
1973af31f5e5SChris Mason 	btrfs_set_backup_dev_root_gen(root_backup,
1974af31f5e5SChris Mason 			       btrfs_header_generation(info->dev_root->node));
1975af31f5e5SChris Mason 	btrfs_set_backup_dev_root_level(root_backup,
1976af31f5e5SChris Mason 				       btrfs_header_level(info->dev_root->node));
1977af31f5e5SChris Mason 
1978af31f5e5SChris Mason 	btrfs_set_backup_csum_root(root_backup, info->csum_root->node->start);
1979af31f5e5SChris Mason 	btrfs_set_backup_csum_root_gen(root_backup,
1980af31f5e5SChris Mason 			       btrfs_header_generation(info->csum_root->node));
1981af31f5e5SChris Mason 	btrfs_set_backup_csum_root_level(root_backup,
1982af31f5e5SChris Mason 			       btrfs_header_level(info->csum_root->node));
1983af31f5e5SChris Mason 
1984af31f5e5SChris Mason 	btrfs_set_backup_total_bytes(root_backup,
1985af31f5e5SChris Mason 			     btrfs_super_total_bytes(info->super_copy));
1986af31f5e5SChris Mason 	btrfs_set_backup_bytes_used(root_backup,
1987af31f5e5SChris Mason 			     btrfs_super_bytes_used(info->super_copy));
1988af31f5e5SChris Mason 	btrfs_set_backup_num_devices(root_backup,
1989af31f5e5SChris Mason 			     btrfs_super_num_devices(info->super_copy));
1990af31f5e5SChris Mason 
1991af31f5e5SChris Mason 	/*
1992af31f5e5SChris Mason 	 * if we don't copy this out to the super_copy, it won't get remembered
1993af31f5e5SChris Mason 	 * for the next commit
1994af31f5e5SChris Mason 	 */
1995af31f5e5SChris Mason 	memcpy(&info->super_copy->super_roots,
1996af31f5e5SChris Mason 	       &info->super_for_commit->super_roots,
1997af31f5e5SChris Mason 	       sizeof(*root_backup) * BTRFS_NUM_BACKUP_ROOTS);
1998af31f5e5SChris Mason }
1999af31f5e5SChris Mason 
2000af31f5e5SChris Mason /*
2001bd2336b2SNikolay Borisov  * read_backup_root - Reads a backup root based on the passed priority. Prio 0
2002bd2336b2SNikolay Borisov  * is the newest, prio 1/2/3 are 2nd newest/3rd newest/4th (oldest) backup roots
2003bd2336b2SNikolay Borisov  *
2004bd2336b2SNikolay Borisov  * fs_info - filesystem whose backup roots need to be read
2005bd2336b2SNikolay Borisov  * priority - priority of backup root required
2006bd2336b2SNikolay Borisov  *
2007bd2336b2SNikolay Borisov  * Returns backup root index on success and -EINVAL otherwise.
2008bd2336b2SNikolay Borisov  */
2009bd2336b2SNikolay Borisov static int read_backup_root(struct btrfs_fs_info *fs_info, u8 priority)
2010bd2336b2SNikolay Borisov {
2011bd2336b2SNikolay Borisov 	int backup_index = find_newest_super_backup(fs_info);
2012bd2336b2SNikolay Borisov 	struct btrfs_super_block *super = fs_info->super_copy;
2013bd2336b2SNikolay Borisov 	struct btrfs_root_backup *root_backup;
2014bd2336b2SNikolay Borisov 
2015bd2336b2SNikolay Borisov 	if (priority < BTRFS_NUM_BACKUP_ROOTS && backup_index >= 0) {
2016bd2336b2SNikolay Borisov 		if (priority == 0)
2017bd2336b2SNikolay Borisov 			return backup_index;
2018bd2336b2SNikolay Borisov 
2019bd2336b2SNikolay Borisov 		backup_index = backup_index + BTRFS_NUM_BACKUP_ROOTS - priority;
2020bd2336b2SNikolay Borisov 		backup_index %= BTRFS_NUM_BACKUP_ROOTS;
2021bd2336b2SNikolay Borisov 	} else {
2022bd2336b2SNikolay Borisov 		return -EINVAL;
2023bd2336b2SNikolay Borisov 	}
2024bd2336b2SNikolay Borisov 
2025bd2336b2SNikolay Borisov 	root_backup = super->super_roots + backup_index;
2026bd2336b2SNikolay Borisov 
2027bd2336b2SNikolay Borisov 	btrfs_set_super_generation(super,
2028bd2336b2SNikolay Borisov 				   btrfs_backup_tree_root_gen(root_backup));
2029bd2336b2SNikolay Borisov 	btrfs_set_super_root(super, btrfs_backup_tree_root(root_backup));
2030bd2336b2SNikolay Borisov 	btrfs_set_super_root_level(super,
2031bd2336b2SNikolay Borisov 				   btrfs_backup_tree_root_level(root_backup));
2032bd2336b2SNikolay Borisov 	btrfs_set_super_bytes_used(super, btrfs_backup_bytes_used(root_backup));
2033bd2336b2SNikolay Borisov 
2034bd2336b2SNikolay Borisov 	/*
2035bd2336b2SNikolay Borisov 	 * Fixme: the total bytes and num_devices need to match or we should
2036bd2336b2SNikolay Borisov 	 * need a fsck
2037bd2336b2SNikolay Borisov 	 */
2038bd2336b2SNikolay Borisov 	btrfs_set_super_total_bytes(super, btrfs_backup_total_bytes(root_backup));
2039bd2336b2SNikolay Borisov 	btrfs_set_super_num_devices(super, btrfs_backup_num_devices(root_backup));
2040bd2336b2SNikolay Borisov 
2041bd2336b2SNikolay Borisov 	return backup_index;
2042bd2336b2SNikolay Borisov }
2043bd2336b2SNikolay Borisov 
20447abadb64SLiu Bo /* helper to cleanup workers */
20457abadb64SLiu Bo static void btrfs_stop_all_workers(struct btrfs_fs_info *fs_info)
20467abadb64SLiu Bo {
2047dc6e3209SQu Wenruo 	btrfs_destroy_workqueue(fs_info->fixup_workers);
2048afe3d242SQu Wenruo 	btrfs_destroy_workqueue(fs_info->delalloc_workers);
20495cdc7ad3SQu Wenruo 	btrfs_destroy_workqueue(fs_info->workers);
2050fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_workers);
2051fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_raid56_workers);
2052d05a33acSQu Wenruo 	btrfs_destroy_workqueue(fs_info->rmw_workers);
2053fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_write_workers);
2054fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_freespace_worker);
20555b3bc44eSQu Wenruo 	btrfs_destroy_workqueue(fs_info->delayed_workers);
2056e66f0bb1SQu Wenruo 	btrfs_destroy_workqueue(fs_info->caching_workers);
2057736cfa15SQu Wenruo 	btrfs_destroy_workqueue(fs_info->readahead_workers);
2058a44903abSQu Wenruo 	btrfs_destroy_workqueue(fs_info->flush_workers);
2059fc97fab0SQu Wenruo 	btrfs_destroy_workqueue(fs_info->qgroup_rescan_workers);
2060b0643e59SDennis Zhou 	if (fs_info->discard_ctl.discard_workers)
2061b0643e59SDennis Zhou 		destroy_workqueue(fs_info->discard_ctl.discard_workers);
2062a9b9477dSFilipe Manana 	/*
2063a9b9477dSFilipe Manana 	 * Now that all other work queues are destroyed, we can safely destroy
2064a9b9477dSFilipe Manana 	 * the queues used for metadata I/O, since tasks from those other work
2065a9b9477dSFilipe Manana 	 * queues can do metadata I/O operations.
2066a9b9477dSFilipe Manana 	 */
2067a9b9477dSFilipe Manana 	btrfs_destroy_workqueue(fs_info->endio_meta_workers);
2068a9b9477dSFilipe Manana 	btrfs_destroy_workqueue(fs_info->endio_meta_write_workers);
20697abadb64SLiu Bo }
20707abadb64SLiu Bo 
20712e9f5954SRashika static void free_root_extent_buffers(struct btrfs_root *root)
20722e9f5954SRashika {
20732e9f5954SRashika 	if (root) {
20742e9f5954SRashika 		free_extent_buffer(root->node);
20752e9f5954SRashika 		free_extent_buffer(root->commit_root);
20762e9f5954SRashika 		root->node = NULL;
20772e9f5954SRashika 		root->commit_root = NULL;
20782e9f5954SRashika 	}
20792e9f5954SRashika }
20802e9f5954SRashika 
2081af31f5e5SChris Mason /* helper to cleanup tree roots */
20824273eaffSAnand Jain static void free_root_pointers(struct btrfs_fs_info *info, bool free_chunk_root)
2083af31f5e5SChris Mason {
20842e9f5954SRashika 	free_root_extent_buffers(info->tree_root);
2085655b09feSJosef Bacik 
20862e9f5954SRashika 	free_root_extent_buffers(info->dev_root);
20872e9f5954SRashika 	free_root_extent_buffers(info->extent_root);
20882e9f5954SRashika 	free_root_extent_buffers(info->csum_root);
20892e9f5954SRashika 	free_root_extent_buffers(info->quota_root);
20902e9f5954SRashika 	free_root_extent_buffers(info->uuid_root);
20918c38938cSJosef Bacik 	free_root_extent_buffers(info->fs_root);
2092aeb935a4SQu Wenruo 	free_root_extent_buffers(info->data_reloc_root);
20934273eaffSAnand Jain 	if (free_chunk_root)
20942e9f5954SRashika 		free_root_extent_buffers(info->chunk_root);
209570f6d82eSOmar Sandoval 	free_root_extent_buffers(info->free_space_root);
2096af31f5e5SChris Mason }
2097af31f5e5SChris Mason 
20988c38938cSJosef Bacik void btrfs_put_root(struct btrfs_root *root)
20998c38938cSJosef Bacik {
21008c38938cSJosef Bacik 	if (!root)
21018c38938cSJosef Bacik 		return;
21028c38938cSJosef Bacik 
21038c38938cSJosef Bacik 	if (refcount_dec_and_test(&root->refs)) {
21048c38938cSJosef Bacik 		WARN_ON(!RB_EMPTY_ROOT(&root->inode_tree));
21051dae7e0eSQu Wenruo 		WARN_ON(test_bit(BTRFS_ROOT_DEAD_RELOC_TREE, &root->state));
21068c38938cSJosef Bacik 		if (root->anon_dev)
21078c38938cSJosef Bacik 			free_anon_bdev(root->anon_dev);
21088c38938cSJosef Bacik 		btrfs_drew_lock_destroy(&root->snapshot_lock);
2109923eb523SJohannes Thumshirn 		free_root_extent_buffers(root);
21108c38938cSJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
21118c38938cSJosef Bacik 		spin_lock(&root->fs_info->fs_roots_radix_lock);
21128c38938cSJosef Bacik 		list_del_init(&root->leak_list);
21138c38938cSJosef Bacik 		spin_unlock(&root->fs_info->fs_roots_radix_lock);
21148c38938cSJosef Bacik #endif
21158c38938cSJosef Bacik 		kfree(root);
21168c38938cSJosef Bacik 	}
21178c38938cSJosef Bacik }
21188c38938cSJosef Bacik 
2119faa2dbf0SJosef Bacik void btrfs_free_fs_roots(struct btrfs_fs_info *fs_info)
2120171f6537SJosef Bacik {
2121171f6537SJosef Bacik 	int ret;
2122171f6537SJosef Bacik 	struct btrfs_root *gang[8];
2123171f6537SJosef Bacik 	int i;
2124171f6537SJosef Bacik 
2125171f6537SJosef Bacik 	while (!list_empty(&fs_info->dead_roots)) {
2126171f6537SJosef Bacik 		gang[0] = list_entry(fs_info->dead_roots.next,
2127171f6537SJosef Bacik 				     struct btrfs_root, root_list);
2128171f6537SJosef Bacik 		list_del(&gang[0]->root_list);
2129171f6537SJosef Bacik 
21308c38938cSJosef Bacik 		if (test_bit(BTRFS_ROOT_IN_RADIX, &gang[0]->state))
2131cb517eabSMiao Xie 			btrfs_drop_and_free_fs_root(fs_info, gang[0]);
213200246528SJosef Bacik 		btrfs_put_root(gang[0]);
2133171f6537SJosef Bacik 	}
2134171f6537SJosef Bacik 
2135171f6537SJosef Bacik 	while (1) {
2136171f6537SJosef Bacik 		ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
2137171f6537SJosef Bacik 					     (void **)gang, 0,
2138171f6537SJosef Bacik 					     ARRAY_SIZE(gang));
2139171f6537SJosef Bacik 		if (!ret)
2140171f6537SJosef Bacik 			break;
2141171f6537SJosef Bacik 		for (i = 0; i < ret; i++)
2142cb517eabSMiao Xie 			btrfs_drop_and_free_fs_root(fs_info, gang[i]);
2143171f6537SJosef Bacik 	}
2144171f6537SJosef Bacik }
2145af31f5e5SChris Mason 
2146638aa7edSEric Sandeen static void btrfs_init_scrub(struct btrfs_fs_info *fs_info)
2147638aa7edSEric Sandeen {
2148638aa7edSEric Sandeen 	mutex_init(&fs_info->scrub_lock);
2149638aa7edSEric Sandeen 	atomic_set(&fs_info->scrubs_running, 0);
2150638aa7edSEric Sandeen 	atomic_set(&fs_info->scrub_pause_req, 0);
2151638aa7edSEric Sandeen 	atomic_set(&fs_info->scrubs_paused, 0);
2152638aa7edSEric Sandeen 	atomic_set(&fs_info->scrub_cancel_req, 0);
2153638aa7edSEric Sandeen 	init_waitqueue_head(&fs_info->scrub_pause_wait);
2154ff09c4caSAnand Jain 	refcount_set(&fs_info->scrub_workers_refcnt, 0);
2155638aa7edSEric Sandeen }
2156638aa7edSEric Sandeen 
2157779a65a4SEric Sandeen static void btrfs_init_balance(struct btrfs_fs_info *fs_info)
2158779a65a4SEric Sandeen {
2159779a65a4SEric Sandeen 	spin_lock_init(&fs_info->balance_lock);
2160779a65a4SEric Sandeen 	mutex_init(&fs_info->balance_mutex);
2161779a65a4SEric Sandeen 	atomic_set(&fs_info->balance_pause_req, 0);
2162779a65a4SEric Sandeen 	atomic_set(&fs_info->balance_cancel_req, 0);
2163779a65a4SEric Sandeen 	fs_info->balance_ctl = NULL;
2164779a65a4SEric Sandeen 	init_waitqueue_head(&fs_info->balance_wait_q);
2165779a65a4SEric Sandeen }
2166779a65a4SEric Sandeen 
21676bccf3abSJeff Mahoney static void btrfs_init_btree_inode(struct btrfs_fs_info *fs_info)
2168f37938e0SEric Sandeen {
21692ff7e61eSJeff Mahoney 	struct inode *inode = fs_info->btree_inode;
21702ff7e61eSJeff Mahoney 
21712ff7e61eSJeff Mahoney 	inode->i_ino = BTRFS_BTREE_INODE_OBJECTID;
21722ff7e61eSJeff Mahoney 	set_nlink(inode, 1);
2173f37938e0SEric Sandeen 	/*
2174f37938e0SEric Sandeen 	 * we set the i_size on the btree inode to the max possible int.
2175f37938e0SEric Sandeen 	 * the real end of the address space is determined by all of
2176f37938e0SEric Sandeen 	 * the devices in the system
2177f37938e0SEric Sandeen 	 */
21782ff7e61eSJeff Mahoney 	inode->i_size = OFFSET_MAX;
21792ff7e61eSJeff Mahoney 	inode->i_mapping->a_ops = &btree_aops;
2180f37938e0SEric Sandeen 
21812ff7e61eSJeff Mahoney 	RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
218243eb5f29SQu Wenruo 	extent_io_tree_init(fs_info, &BTRFS_I(inode)->io_tree,
21832c53a14dSQu Wenruo 			    IO_TREE_BTREE_INODE_IO, inode);
21847b439738SDavid Sterba 	BTRFS_I(inode)->io_tree.track_uptodate = false;
21852ff7e61eSJeff Mahoney 	extent_map_tree_init(&BTRFS_I(inode)->extent_tree);
2186f37938e0SEric Sandeen 
21875c8fd99fSJosef Bacik 	BTRFS_I(inode)->root = btrfs_grab_root(fs_info->tree_root);
21882ff7e61eSJeff Mahoney 	memset(&BTRFS_I(inode)->location, 0, sizeof(struct btrfs_key));
21892ff7e61eSJeff Mahoney 	set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
21902ff7e61eSJeff Mahoney 	btrfs_insert_inode_hash(inode);
2191f37938e0SEric Sandeen }
2192f37938e0SEric Sandeen 
2193ad618368SEric Sandeen static void btrfs_init_dev_replace_locks(struct btrfs_fs_info *fs_info)
2194ad618368SEric Sandeen {
2195ad618368SEric Sandeen 	mutex_init(&fs_info->dev_replace.lock_finishing_cancel_unmount);
2196129827e3SDavid Sterba 	init_rwsem(&fs_info->dev_replace.rwsem);
21977f8d236aSDavid Sterba 	init_waitqueue_head(&fs_info->dev_replace.replace_wait);
2198ad618368SEric Sandeen }
2199ad618368SEric Sandeen 
2200f9e92e40SEric Sandeen static void btrfs_init_qgroup(struct btrfs_fs_info *fs_info)
2201f9e92e40SEric Sandeen {
2202f9e92e40SEric Sandeen 	spin_lock_init(&fs_info->qgroup_lock);
2203f9e92e40SEric Sandeen 	mutex_init(&fs_info->qgroup_ioctl_lock);
2204f9e92e40SEric Sandeen 	fs_info->qgroup_tree = RB_ROOT;
2205f9e92e40SEric Sandeen 	INIT_LIST_HEAD(&fs_info->dirty_qgroups);
2206f9e92e40SEric Sandeen 	fs_info->qgroup_seq = 1;
2207f9e92e40SEric Sandeen 	fs_info->qgroup_ulist = NULL;
2208d2c609b8SJeff Mahoney 	fs_info->qgroup_rescan_running = false;
2209f9e92e40SEric Sandeen 	mutex_init(&fs_info->qgroup_rescan_lock);
2210f9e92e40SEric Sandeen }
2211f9e92e40SEric Sandeen 
22122a458198SEric Sandeen static int btrfs_init_workqueues(struct btrfs_fs_info *fs_info,
22132a458198SEric Sandeen 		struct btrfs_fs_devices *fs_devices)
22142a458198SEric Sandeen {
2215f7b885beSAnand Jain 	u32 max_active = fs_info->thread_pool_size;
22166f011058SDavid Sterba 	unsigned int flags = WQ_MEM_RECLAIM | WQ_FREEZABLE | WQ_UNBOUND;
22172a458198SEric Sandeen 
22182a458198SEric Sandeen 	fs_info->workers =
2219cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "worker",
2220cb001095SJeff Mahoney 				      flags | WQ_HIGHPRI, max_active, 16);
22212a458198SEric Sandeen 
22222a458198SEric Sandeen 	fs_info->delalloc_workers =
2223cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "delalloc",
2224cb001095SJeff Mahoney 				      flags, max_active, 2);
22252a458198SEric Sandeen 
22262a458198SEric Sandeen 	fs_info->flush_workers =
2227cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "flush_delalloc",
2228cb001095SJeff Mahoney 				      flags, max_active, 0);
22292a458198SEric Sandeen 
22302a458198SEric Sandeen 	fs_info->caching_workers =
2231cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "cache", flags, max_active, 0);
22322a458198SEric Sandeen 
22332a458198SEric Sandeen 	fs_info->fixup_workers =
2234cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "fixup", flags, 1, 0);
22352a458198SEric Sandeen 
22362a458198SEric Sandeen 	/*
22372a458198SEric Sandeen 	 * endios are largely parallel and should have a very
22382a458198SEric Sandeen 	 * low idle thresh
22392a458198SEric Sandeen 	 */
22402a458198SEric Sandeen 	fs_info->endio_workers =
2241cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio", flags, max_active, 4);
22422a458198SEric Sandeen 	fs_info->endio_meta_workers =
2243cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio-meta", flags,
2244cb001095SJeff Mahoney 				      max_active, 4);
22452a458198SEric Sandeen 	fs_info->endio_meta_write_workers =
2246cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio-meta-write", flags,
2247cb001095SJeff Mahoney 				      max_active, 2);
22482a458198SEric Sandeen 	fs_info->endio_raid56_workers =
2249cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio-raid56", flags,
2250cb001095SJeff Mahoney 				      max_active, 4);
22512a458198SEric Sandeen 	fs_info->rmw_workers =
2252cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "rmw", flags, max_active, 2);
22532a458198SEric Sandeen 	fs_info->endio_write_workers =
2254cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio-write", flags,
2255cb001095SJeff Mahoney 				      max_active, 2);
22562a458198SEric Sandeen 	fs_info->endio_freespace_worker =
2257cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "freespace-write", flags,
2258cb001095SJeff Mahoney 				      max_active, 0);
22592a458198SEric Sandeen 	fs_info->delayed_workers =
2260cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "delayed-meta", flags,
2261cb001095SJeff Mahoney 				      max_active, 0);
22622a458198SEric Sandeen 	fs_info->readahead_workers =
2263cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "readahead", flags,
2264cb001095SJeff Mahoney 				      max_active, 2);
22652a458198SEric Sandeen 	fs_info->qgroup_rescan_workers =
2266cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "qgroup-rescan", flags, 1, 0);
2267b0643e59SDennis Zhou 	fs_info->discard_ctl.discard_workers =
2268b0643e59SDennis Zhou 		alloc_workqueue("btrfs_discard", WQ_UNBOUND | WQ_FREEZABLE, 1);
22692a458198SEric Sandeen 
22702a458198SEric Sandeen 	if (!(fs_info->workers && fs_info->delalloc_workers &&
2271ba8a9d07SChris Mason 	      fs_info->flush_workers &&
22722a458198SEric Sandeen 	      fs_info->endio_workers && fs_info->endio_meta_workers &&
22732a458198SEric Sandeen 	      fs_info->endio_meta_write_workers &&
22742a458198SEric Sandeen 	      fs_info->endio_write_workers && fs_info->endio_raid56_workers &&
22752a458198SEric Sandeen 	      fs_info->endio_freespace_worker && fs_info->rmw_workers &&
22762a458198SEric Sandeen 	      fs_info->caching_workers && fs_info->readahead_workers &&
22772a458198SEric Sandeen 	      fs_info->fixup_workers && fs_info->delayed_workers &&
2278b0643e59SDennis Zhou 	      fs_info->qgroup_rescan_workers &&
2279b0643e59SDennis Zhou 	      fs_info->discard_ctl.discard_workers)) {
22802a458198SEric Sandeen 		return -ENOMEM;
22812a458198SEric Sandeen 	}
22822a458198SEric Sandeen 
22832a458198SEric Sandeen 	return 0;
22842a458198SEric Sandeen }
22852a458198SEric Sandeen 
22866d97c6e3SJohannes Thumshirn static int btrfs_init_csum_hash(struct btrfs_fs_info *fs_info, u16 csum_type)
22876d97c6e3SJohannes Thumshirn {
22886d97c6e3SJohannes Thumshirn 	struct crypto_shash *csum_shash;
2289b4e967beSDavid Sterba 	const char *csum_driver = btrfs_super_csum_driver(csum_type);
22906d97c6e3SJohannes Thumshirn 
2291b4e967beSDavid Sterba 	csum_shash = crypto_alloc_shash(csum_driver, 0, 0);
22926d97c6e3SJohannes Thumshirn 
22936d97c6e3SJohannes Thumshirn 	if (IS_ERR(csum_shash)) {
22946d97c6e3SJohannes Thumshirn 		btrfs_err(fs_info, "error allocating %s hash for checksum",
2295b4e967beSDavid Sterba 			  csum_driver);
22966d97c6e3SJohannes Thumshirn 		return PTR_ERR(csum_shash);
22976d97c6e3SJohannes Thumshirn 	}
22986d97c6e3SJohannes Thumshirn 
22996d97c6e3SJohannes Thumshirn 	fs_info->csum_shash = csum_shash;
23006d97c6e3SJohannes Thumshirn 
23016d97c6e3SJohannes Thumshirn 	return 0;
23026d97c6e3SJohannes Thumshirn }
23036d97c6e3SJohannes Thumshirn 
230463443bf5SEric Sandeen static int btrfs_replay_log(struct btrfs_fs_info *fs_info,
230563443bf5SEric Sandeen 			    struct btrfs_fs_devices *fs_devices)
230663443bf5SEric Sandeen {
230763443bf5SEric Sandeen 	int ret;
230863443bf5SEric Sandeen 	struct btrfs_root *log_tree_root;
230963443bf5SEric Sandeen 	struct btrfs_super_block *disk_super = fs_info->super_copy;
231063443bf5SEric Sandeen 	u64 bytenr = btrfs_super_log_root(disk_super);
2311581c1760SQu Wenruo 	int level = btrfs_super_log_root_level(disk_super);
231263443bf5SEric Sandeen 
231363443bf5SEric Sandeen 	if (fs_devices->rw_devices == 0) {
2314f14d104dSDavid Sterba 		btrfs_warn(fs_info, "log replay required on RO media");
231563443bf5SEric Sandeen 		return -EIO;
231663443bf5SEric Sandeen 	}
231763443bf5SEric Sandeen 
231896dfcb46SJosef Bacik 	log_tree_root = btrfs_alloc_root(fs_info, BTRFS_TREE_LOG_OBJECTID,
231996dfcb46SJosef Bacik 					 GFP_KERNEL);
232063443bf5SEric Sandeen 	if (!log_tree_root)
232163443bf5SEric Sandeen 		return -ENOMEM;
232263443bf5SEric Sandeen 
23232ff7e61eSJeff Mahoney 	log_tree_root->node = read_tree_block(fs_info, bytenr,
23241b7ec85eSJosef Bacik 					      BTRFS_TREE_LOG_OBJECTID,
23251b7ec85eSJosef Bacik 					      fs_info->generation + 1, level,
23261b7ec85eSJosef Bacik 					      NULL);
232764c043deSLiu Bo 	if (IS_ERR(log_tree_root->node)) {
2328f14d104dSDavid Sterba 		btrfs_warn(fs_info, "failed to read log tree");
23290eeff236SLiu Bo 		ret = PTR_ERR(log_tree_root->node);
23308c38938cSJosef Bacik 		log_tree_root->node = NULL;
233100246528SJosef Bacik 		btrfs_put_root(log_tree_root);
23320eeff236SLiu Bo 		return ret;
233364c043deSLiu Bo 	} else if (!extent_buffer_uptodate(log_tree_root->node)) {
2334f14d104dSDavid Sterba 		btrfs_err(fs_info, "failed to read log tree");
233500246528SJosef Bacik 		btrfs_put_root(log_tree_root);
233663443bf5SEric Sandeen 		return -EIO;
233763443bf5SEric Sandeen 	}
233863443bf5SEric Sandeen 	/* returns with log_tree_root freed on success */
233963443bf5SEric Sandeen 	ret = btrfs_recover_log_trees(log_tree_root);
234063443bf5SEric Sandeen 	if (ret) {
23410b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, ret,
234263443bf5SEric Sandeen 				      "Failed to recover log tree");
234300246528SJosef Bacik 		btrfs_put_root(log_tree_root);
234463443bf5SEric Sandeen 		return ret;
234563443bf5SEric Sandeen 	}
234663443bf5SEric Sandeen 
2347bc98a42cSDavid Howells 	if (sb_rdonly(fs_info->sb)) {
23486bccf3abSJeff Mahoney 		ret = btrfs_commit_super(fs_info);
234963443bf5SEric Sandeen 		if (ret)
235063443bf5SEric Sandeen 			return ret;
235163443bf5SEric Sandeen 	}
235263443bf5SEric Sandeen 
235363443bf5SEric Sandeen 	return 0;
235463443bf5SEric Sandeen }
235563443bf5SEric Sandeen 
23566bccf3abSJeff Mahoney static int btrfs_read_roots(struct btrfs_fs_info *fs_info)
23574bbcaa64SEric Sandeen {
23586bccf3abSJeff Mahoney 	struct btrfs_root *tree_root = fs_info->tree_root;
2359a4f3d2c4SDavid Sterba 	struct btrfs_root *root;
23604bbcaa64SEric Sandeen 	struct btrfs_key location;
23614bbcaa64SEric Sandeen 	int ret;
23624bbcaa64SEric Sandeen 
23636bccf3abSJeff Mahoney 	BUG_ON(!fs_info->tree_root);
23646bccf3abSJeff Mahoney 
23654bbcaa64SEric Sandeen 	location.objectid = BTRFS_EXTENT_TREE_OBJECTID;
23664bbcaa64SEric Sandeen 	location.type = BTRFS_ROOT_ITEM_KEY;
23674bbcaa64SEric Sandeen 	location.offset = 0;
23684bbcaa64SEric Sandeen 
2369a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2370f50f4353SLiu Bo 	if (IS_ERR(root)) {
237142437a63SJosef Bacik 		if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2372f50f4353SLiu Bo 			ret = PTR_ERR(root);
2373f50f4353SLiu Bo 			goto out;
2374f50f4353SLiu Bo 		}
237542437a63SJosef Bacik 	} else {
2376a4f3d2c4SDavid Sterba 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2377a4f3d2c4SDavid Sterba 		fs_info->extent_root = root;
237842437a63SJosef Bacik 	}
23794bbcaa64SEric Sandeen 
23804bbcaa64SEric Sandeen 	location.objectid = BTRFS_DEV_TREE_OBJECTID;
2381a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2382f50f4353SLiu Bo 	if (IS_ERR(root)) {
238342437a63SJosef Bacik 		if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2384f50f4353SLiu Bo 			ret = PTR_ERR(root);
2385f50f4353SLiu Bo 			goto out;
2386f50f4353SLiu Bo 		}
238742437a63SJosef Bacik 	} else {
2388a4f3d2c4SDavid Sterba 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2389a4f3d2c4SDavid Sterba 		fs_info->dev_root = root;
239042437a63SJosef Bacik 	}
2391*820a49daSJosef Bacik 	/* Initialize fs_info for all devices in any case */
2392*820a49daSJosef Bacik 	btrfs_init_devices_late(fs_info);
23934bbcaa64SEric Sandeen 
2394882dbe0cSJosef Bacik 	/* If IGNOREDATACSUMS is set don't bother reading the csum root. */
2395882dbe0cSJosef Bacik 	if (!btrfs_test_opt(fs_info, IGNOREDATACSUMS)) {
23964bbcaa64SEric Sandeen 		location.objectid = BTRFS_CSUM_TREE_OBJECTID;
2397a4f3d2c4SDavid Sterba 		root = btrfs_read_tree_root(tree_root, &location);
2398f50f4353SLiu Bo 		if (IS_ERR(root)) {
239942437a63SJosef Bacik 			if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2400f50f4353SLiu Bo 				ret = PTR_ERR(root);
2401f50f4353SLiu Bo 				goto out;
2402f50f4353SLiu Bo 			}
240342437a63SJosef Bacik 		} else {
2404a4f3d2c4SDavid Sterba 			set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2405a4f3d2c4SDavid Sterba 			fs_info->csum_root = root;
240642437a63SJosef Bacik 		}
2407882dbe0cSJosef Bacik 	}
24084bbcaa64SEric Sandeen 
2409aeb935a4SQu Wenruo 	/*
2410aeb935a4SQu Wenruo 	 * This tree can share blocks with some other fs tree during relocation
2411aeb935a4SQu Wenruo 	 * and we need a proper setup by btrfs_get_fs_root
2412aeb935a4SQu Wenruo 	 */
241356e9357aSDavid Sterba 	root = btrfs_get_fs_root(tree_root->fs_info,
241456e9357aSDavid Sterba 				 BTRFS_DATA_RELOC_TREE_OBJECTID, true);
2415aeb935a4SQu Wenruo 	if (IS_ERR(root)) {
241642437a63SJosef Bacik 		if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2417aeb935a4SQu Wenruo 			ret = PTR_ERR(root);
2418aeb935a4SQu Wenruo 			goto out;
2419aeb935a4SQu Wenruo 		}
242042437a63SJosef Bacik 	} else {
2421aeb935a4SQu Wenruo 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2422aeb935a4SQu Wenruo 		fs_info->data_reloc_root = root;
242342437a63SJosef Bacik 	}
2424aeb935a4SQu Wenruo 
24254bbcaa64SEric Sandeen 	location.objectid = BTRFS_QUOTA_TREE_OBJECTID;
2426a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2427a4f3d2c4SDavid Sterba 	if (!IS_ERR(root)) {
2428a4f3d2c4SDavid Sterba 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2429afcdd129SJosef Bacik 		set_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags);
2430a4f3d2c4SDavid Sterba 		fs_info->quota_root = root;
24314bbcaa64SEric Sandeen 	}
24324bbcaa64SEric Sandeen 
24334bbcaa64SEric Sandeen 	location.objectid = BTRFS_UUID_TREE_OBJECTID;
2434a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2435a4f3d2c4SDavid Sterba 	if (IS_ERR(root)) {
243642437a63SJosef Bacik 		if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2437a4f3d2c4SDavid Sterba 			ret = PTR_ERR(root);
24384bbcaa64SEric Sandeen 			if (ret != -ENOENT)
2439f50f4353SLiu Bo 				goto out;
244042437a63SJosef Bacik 		}
24414bbcaa64SEric Sandeen 	} else {
2442a4f3d2c4SDavid Sterba 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2443a4f3d2c4SDavid Sterba 		fs_info->uuid_root = root;
24444bbcaa64SEric Sandeen 	}
24454bbcaa64SEric Sandeen 
244670f6d82eSOmar Sandoval 	if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
244770f6d82eSOmar Sandoval 		location.objectid = BTRFS_FREE_SPACE_TREE_OBJECTID;
244870f6d82eSOmar Sandoval 		root = btrfs_read_tree_root(tree_root, &location);
2449f50f4353SLiu Bo 		if (IS_ERR(root)) {
245042437a63SJosef Bacik 			if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2451f50f4353SLiu Bo 				ret = PTR_ERR(root);
2452f50f4353SLiu Bo 				goto out;
2453f50f4353SLiu Bo 			}
245442437a63SJosef Bacik 		}  else {
245570f6d82eSOmar Sandoval 			set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
245670f6d82eSOmar Sandoval 			fs_info->free_space_root = root;
245770f6d82eSOmar Sandoval 		}
245842437a63SJosef Bacik 	}
245970f6d82eSOmar Sandoval 
24604bbcaa64SEric Sandeen 	return 0;
2461f50f4353SLiu Bo out:
2462f50f4353SLiu Bo 	btrfs_warn(fs_info, "failed to read root (objectid=%llu): %d",
2463f50f4353SLiu Bo 		   location.objectid, ret);
2464f50f4353SLiu Bo 	return ret;
24654bbcaa64SEric Sandeen }
24664bbcaa64SEric Sandeen 
2467069ec957SQu Wenruo /*
2468069ec957SQu Wenruo  * Real super block validation
2469069ec957SQu Wenruo  * NOTE: super csum type and incompat features will not be checked here.
2470069ec957SQu Wenruo  *
2471069ec957SQu Wenruo  * @sb:		super block to check
2472069ec957SQu Wenruo  * @mirror_num:	the super block number to check its bytenr:
2473069ec957SQu Wenruo  * 		0	the primary (1st) sb
2474069ec957SQu Wenruo  * 		1, 2	2nd and 3rd backup copy
2475069ec957SQu Wenruo  * 	       -1	skip bytenr check
2476069ec957SQu Wenruo  */
2477069ec957SQu Wenruo static int validate_super(struct btrfs_fs_info *fs_info,
2478069ec957SQu Wenruo 			    struct btrfs_super_block *sb, int mirror_num)
247921a852b0SQu Wenruo {
248021a852b0SQu Wenruo 	u64 nodesize = btrfs_super_nodesize(sb);
248121a852b0SQu Wenruo 	u64 sectorsize = btrfs_super_sectorsize(sb);
248221a852b0SQu Wenruo 	int ret = 0;
248321a852b0SQu Wenruo 
248421a852b0SQu Wenruo 	if (btrfs_super_magic(sb) != BTRFS_MAGIC) {
248521a852b0SQu Wenruo 		btrfs_err(fs_info, "no valid FS found");
248621a852b0SQu Wenruo 		ret = -EINVAL;
248721a852b0SQu Wenruo 	}
248821a852b0SQu Wenruo 	if (btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP) {
248921a852b0SQu Wenruo 		btrfs_err(fs_info, "unrecognized or unsupported super flag: %llu",
249021a852b0SQu Wenruo 				btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP);
249121a852b0SQu Wenruo 		ret = -EINVAL;
249221a852b0SQu Wenruo 	}
249321a852b0SQu Wenruo 	if (btrfs_super_root_level(sb) >= BTRFS_MAX_LEVEL) {
249421a852b0SQu Wenruo 		btrfs_err(fs_info, "tree_root level too big: %d >= %d",
249521a852b0SQu Wenruo 				btrfs_super_root_level(sb), BTRFS_MAX_LEVEL);
249621a852b0SQu Wenruo 		ret = -EINVAL;
249721a852b0SQu Wenruo 	}
249821a852b0SQu Wenruo 	if (btrfs_super_chunk_root_level(sb) >= BTRFS_MAX_LEVEL) {
249921a852b0SQu Wenruo 		btrfs_err(fs_info, "chunk_root level too big: %d >= %d",
250021a852b0SQu Wenruo 				btrfs_super_chunk_root_level(sb), BTRFS_MAX_LEVEL);
250121a852b0SQu Wenruo 		ret = -EINVAL;
250221a852b0SQu Wenruo 	}
250321a852b0SQu Wenruo 	if (btrfs_super_log_root_level(sb) >= BTRFS_MAX_LEVEL) {
250421a852b0SQu Wenruo 		btrfs_err(fs_info, "log_root level too big: %d >= %d",
250521a852b0SQu Wenruo 				btrfs_super_log_root_level(sb), BTRFS_MAX_LEVEL);
250621a852b0SQu Wenruo 		ret = -EINVAL;
250721a852b0SQu Wenruo 	}
250821a852b0SQu Wenruo 
250921a852b0SQu Wenruo 	/*
251021a852b0SQu Wenruo 	 * Check sectorsize and nodesize first, other check will need it.
251121a852b0SQu Wenruo 	 * Check all possible sectorsize(4K, 8K, 16K, 32K, 64K) here.
251221a852b0SQu Wenruo 	 */
251321a852b0SQu Wenruo 	if (!is_power_of_2(sectorsize) || sectorsize < 4096 ||
251421a852b0SQu Wenruo 	    sectorsize > BTRFS_MAX_METADATA_BLOCKSIZE) {
251521a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid sectorsize %llu", sectorsize);
251621a852b0SQu Wenruo 		ret = -EINVAL;
251721a852b0SQu Wenruo 	}
25180bb3eb3eSQu Wenruo 
25190bb3eb3eSQu Wenruo 	/*
25200bb3eb3eSQu Wenruo 	 * For 4K page size, we only support 4K sector size.
25210bb3eb3eSQu Wenruo 	 * For 64K page size, we support read-write for 64K sector size, and
25220bb3eb3eSQu Wenruo 	 * read-only for 4K sector size.
25230bb3eb3eSQu Wenruo 	 */
25240bb3eb3eSQu Wenruo 	if ((PAGE_SIZE == SZ_4K && sectorsize != PAGE_SIZE) ||
25250bb3eb3eSQu Wenruo 	    (PAGE_SIZE == SZ_64K && (sectorsize != SZ_4K &&
25260bb3eb3eSQu Wenruo 				     sectorsize != SZ_64K))) {
252721a852b0SQu Wenruo 		btrfs_err(fs_info,
25280bb3eb3eSQu Wenruo 			"sectorsize %llu not yet supported for page size %lu",
252921a852b0SQu Wenruo 			sectorsize, PAGE_SIZE);
253021a852b0SQu Wenruo 		ret = -EINVAL;
253121a852b0SQu Wenruo 	}
25320bb3eb3eSQu Wenruo 
253321a852b0SQu Wenruo 	if (!is_power_of_2(nodesize) || nodesize < sectorsize ||
253421a852b0SQu Wenruo 	    nodesize > BTRFS_MAX_METADATA_BLOCKSIZE) {
253521a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid nodesize %llu", nodesize);
253621a852b0SQu Wenruo 		ret = -EINVAL;
253721a852b0SQu Wenruo 	}
253821a852b0SQu Wenruo 	if (nodesize != le32_to_cpu(sb->__unused_leafsize)) {
253921a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid leafsize %u, should be %llu",
254021a852b0SQu Wenruo 			  le32_to_cpu(sb->__unused_leafsize), nodesize);
254121a852b0SQu Wenruo 		ret = -EINVAL;
254221a852b0SQu Wenruo 	}
254321a852b0SQu Wenruo 
254421a852b0SQu Wenruo 	/* Root alignment check */
254521a852b0SQu Wenruo 	if (!IS_ALIGNED(btrfs_super_root(sb), sectorsize)) {
254621a852b0SQu Wenruo 		btrfs_warn(fs_info, "tree_root block unaligned: %llu",
254721a852b0SQu Wenruo 			   btrfs_super_root(sb));
254821a852b0SQu Wenruo 		ret = -EINVAL;
254921a852b0SQu Wenruo 	}
255021a852b0SQu Wenruo 	if (!IS_ALIGNED(btrfs_super_chunk_root(sb), sectorsize)) {
255121a852b0SQu Wenruo 		btrfs_warn(fs_info, "chunk_root block unaligned: %llu",
255221a852b0SQu Wenruo 			   btrfs_super_chunk_root(sb));
255321a852b0SQu Wenruo 		ret = -EINVAL;
255421a852b0SQu Wenruo 	}
255521a852b0SQu Wenruo 	if (!IS_ALIGNED(btrfs_super_log_root(sb), sectorsize)) {
255621a852b0SQu Wenruo 		btrfs_warn(fs_info, "log_root block unaligned: %llu",
255721a852b0SQu Wenruo 			   btrfs_super_log_root(sb));
255821a852b0SQu Wenruo 		ret = -EINVAL;
255921a852b0SQu Wenruo 	}
256021a852b0SQu Wenruo 
2561de37aa51SNikolay Borisov 	if (memcmp(fs_info->fs_devices->metadata_uuid, sb->dev_item.fsid,
25627239ff4bSNikolay Borisov 		   BTRFS_FSID_SIZE) != 0) {
256321a852b0SQu Wenruo 		btrfs_err(fs_info,
25647239ff4bSNikolay Borisov 			"dev_item UUID does not match metadata fsid: %pU != %pU",
2565de37aa51SNikolay Borisov 			fs_info->fs_devices->metadata_uuid, sb->dev_item.fsid);
256621a852b0SQu Wenruo 		ret = -EINVAL;
256721a852b0SQu Wenruo 	}
256821a852b0SQu Wenruo 
256921a852b0SQu Wenruo 	/*
257021a852b0SQu Wenruo 	 * Hint to catch really bogus numbers, bitflips or so, more exact checks are
257121a852b0SQu Wenruo 	 * done later
257221a852b0SQu Wenruo 	 */
257321a852b0SQu Wenruo 	if (btrfs_super_bytes_used(sb) < 6 * btrfs_super_nodesize(sb)) {
257421a852b0SQu Wenruo 		btrfs_err(fs_info, "bytes_used is too small %llu",
257521a852b0SQu Wenruo 			  btrfs_super_bytes_used(sb));
257621a852b0SQu Wenruo 		ret = -EINVAL;
257721a852b0SQu Wenruo 	}
257821a852b0SQu Wenruo 	if (!is_power_of_2(btrfs_super_stripesize(sb))) {
257921a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid stripesize %u",
258021a852b0SQu Wenruo 			  btrfs_super_stripesize(sb));
258121a852b0SQu Wenruo 		ret = -EINVAL;
258221a852b0SQu Wenruo 	}
258321a852b0SQu Wenruo 	if (btrfs_super_num_devices(sb) > (1UL << 31))
258421a852b0SQu Wenruo 		btrfs_warn(fs_info, "suspicious number of devices: %llu",
258521a852b0SQu Wenruo 			   btrfs_super_num_devices(sb));
258621a852b0SQu Wenruo 	if (btrfs_super_num_devices(sb) == 0) {
258721a852b0SQu Wenruo 		btrfs_err(fs_info, "number of devices is 0");
258821a852b0SQu Wenruo 		ret = -EINVAL;
258921a852b0SQu Wenruo 	}
259021a852b0SQu Wenruo 
2591069ec957SQu Wenruo 	if (mirror_num >= 0 &&
2592069ec957SQu Wenruo 	    btrfs_super_bytenr(sb) != btrfs_sb_offset(mirror_num)) {
259321a852b0SQu Wenruo 		btrfs_err(fs_info, "super offset mismatch %llu != %u",
259421a852b0SQu Wenruo 			  btrfs_super_bytenr(sb), BTRFS_SUPER_INFO_OFFSET);
259521a852b0SQu Wenruo 		ret = -EINVAL;
259621a852b0SQu Wenruo 	}
259721a852b0SQu Wenruo 
259821a852b0SQu Wenruo 	/*
259921a852b0SQu Wenruo 	 * Obvious sys_chunk_array corruptions, it must hold at least one key
260021a852b0SQu Wenruo 	 * and one chunk
260121a852b0SQu Wenruo 	 */
260221a852b0SQu Wenruo 	if (btrfs_super_sys_array_size(sb) > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
260321a852b0SQu Wenruo 		btrfs_err(fs_info, "system chunk array too big %u > %u",
260421a852b0SQu Wenruo 			  btrfs_super_sys_array_size(sb),
260521a852b0SQu Wenruo 			  BTRFS_SYSTEM_CHUNK_ARRAY_SIZE);
260621a852b0SQu Wenruo 		ret = -EINVAL;
260721a852b0SQu Wenruo 	}
260821a852b0SQu Wenruo 	if (btrfs_super_sys_array_size(sb) < sizeof(struct btrfs_disk_key)
260921a852b0SQu Wenruo 			+ sizeof(struct btrfs_chunk)) {
261021a852b0SQu Wenruo 		btrfs_err(fs_info, "system chunk array too small %u < %zu",
261121a852b0SQu Wenruo 			  btrfs_super_sys_array_size(sb),
261221a852b0SQu Wenruo 			  sizeof(struct btrfs_disk_key)
261321a852b0SQu Wenruo 			  + sizeof(struct btrfs_chunk));
261421a852b0SQu Wenruo 		ret = -EINVAL;
261521a852b0SQu Wenruo 	}
261621a852b0SQu Wenruo 
261721a852b0SQu Wenruo 	/*
261821a852b0SQu Wenruo 	 * The generation is a global counter, we'll trust it more than the others
261921a852b0SQu Wenruo 	 * but it's still possible that it's the one that's wrong.
262021a852b0SQu Wenruo 	 */
262121a852b0SQu Wenruo 	if (btrfs_super_generation(sb) < btrfs_super_chunk_root_generation(sb))
262221a852b0SQu Wenruo 		btrfs_warn(fs_info,
262321a852b0SQu Wenruo 			"suspicious: generation < chunk_root_generation: %llu < %llu",
262421a852b0SQu Wenruo 			btrfs_super_generation(sb),
262521a852b0SQu Wenruo 			btrfs_super_chunk_root_generation(sb));
262621a852b0SQu Wenruo 	if (btrfs_super_generation(sb) < btrfs_super_cache_generation(sb)
262721a852b0SQu Wenruo 	    && btrfs_super_cache_generation(sb) != (u64)-1)
262821a852b0SQu Wenruo 		btrfs_warn(fs_info,
262921a852b0SQu Wenruo 			"suspicious: generation < cache_generation: %llu < %llu",
263021a852b0SQu Wenruo 			btrfs_super_generation(sb),
263121a852b0SQu Wenruo 			btrfs_super_cache_generation(sb));
263221a852b0SQu Wenruo 
263321a852b0SQu Wenruo 	return ret;
263421a852b0SQu Wenruo }
263521a852b0SQu Wenruo 
2636069ec957SQu Wenruo /*
2637069ec957SQu Wenruo  * Validation of super block at mount time.
2638069ec957SQu Wenruo  * Some checks already done early at mount time, like csum type and incompat
2639069ec957SQu Wenruo  * flags will be skipped.
2640069ec957SQu Wenruo  */
2641069ec957SQu Wenruo static int btrfs_validate_mount_super(struct btrfs_fs_info *fs_info)
2642069ec957SQu Wenruo {
2643069ec957SQu Wenruo 	return validate_super(fs_info, fs_info->super_copy, 0);
2644069ec957SQu Wenruo }
2645069ec957SQu Wenruo 
264675cb857dSQu Wenruo /*
264775cb857dSQu Wenruo  * Validation of super block at write time.
264875cb857dSQu Wenruo  * Some checks like bytenr check will be skipped as their values will be
264975cb857dSQu Wenruo  * overwritten soon.
265075cb857dSQu Wenruo  * Extra checks like csum type and incompat flags will be done here.
265175cb857dSQu Wenruo  */
265275cb857dSQu Wenruo static int btrfs_validate_write_super(struct btrfs_fs_info *fs_info,
265375cb857dSQu Wenruo 				      struct btrfs_super_block *sb)
265475cb857dSQu Wenruo {
265575cb857dSQu Wenruo 	int ret;
265675cb857dSQu Wenruo 
265775cb857dSQu Wenruo 	ret = validate_super(fs_info, sb, -1);
265875cb857dSQu Wenruo 	if (ret < 0)
265975cb857dSQu Wenruo 		goto out;
2660e7e16f48SJohannes Thumshirn 	if (!btrfs_supported_super_csum(btrfs_super_csum_type(sb))) {
266175cb857dSQu Wenruo 		ret = -EUCLEAN;
266275cb857dSQu Wenruo 		btrfs_err(fs_info, "invalid csum type, has %u want %u",
266375cb857dSQu Wenruo 			  btrfs_super_csum_type(sb), BTRFS_CSUM_TYPE_CRC32);
266475cb857dSQu Wenruo 		goto out;
266575cb857dSQu Wenruo 	}
266675cb857dSQu Wenruo 	if (btrfs_super_incompat_flags(sb) & ~BTRFS_FEATURE_INCOMPAT_SUPP) {
266775cb857dSQu Wenruo 		ret = -EUCLEAN;
266875cb857dSQu Wenruo 		btrfs_err(fs_info,
266975cb857dSQu Wenruo 		"invalid incompat flags, has 0x%llx valid mask 0x%llx",
267075cb857dSQu Wenruo 			  btrfs_super_incompat_flags(sb),
267175cb857dSQu Wenruo 			  (unsigned long long)BTRFS_FEATURE_INCOMPAT_SUPP);
267275cb857dSQu Wenruo 		goto out;
267375cb857dSQu Wenruo 	}
267475cb857dSQu Wenruo out:
267575cb857dSQu Wenruo 	if (ret < 0)
267675cb857dSQu Wenruo 		btrfs_err(fs_info,
267775cb857dSQu Wenruo 		"super block corruption detected before writing it to disk");
267875cb857dSQu Wenruo 	return ret;
267975cb857dSQu Wenruo }
268075cb857dSQu Wenruo 
26816ef108ddSNikolay Borisov static int __cold init_tree_roots(struct btrfs_fs_info *fs_info)
2682b8522a1eSNikolay Borisov {
26836ef108ddSNikolay Borisov 	int backup_index = find_newest_super_backup(fs_info);
2684b8522a1eSNikolay Borisov 	struct btrfs_super_block *sb = fs_info->super_copy;
2685b8522a1eSNikolay Borisov 	struct btrfs_root *tree_root = fs_info->tree_root;
2686b8522a1eSNikolay Borisov 	bool handle_error = false;
2687b8522a1eSNikolay Borisov 	int ret = 0;
2688b8522a1eSNikolay Borisov 	int i;
2689b8522a1eSNikolay Borisov 
2690b8522a1eSNikolay Borisov 	for (i = 0; i < BTRFS_NUM_BACKUP_ROOTS; i++) {
2691b8522a1eSNikolay Borisov 		u64 generation;
2692b8522a1eSNikolay Borisov 		int level;
2693b8522a1eSNikolay Borisov 
2694b8522a1eSNikolay Borisov 		if (handle_error) {
2695b8522a1eSNikolay Borisov 			if (!IS_ERR(tree_root->node))
2696b8522a1eSNikolay Borisov 				free_extent_buffer(tree_root->node);
2697b8522a1eSNikolay Borisov 			tree_root->node = NULL;
2698b8522a1eSNikolay Borisov 
2699b8522a1eSNikolay Borisov 			if (!btrfs_test_opt(fs_info, USEBACKUPROOT))
2700b8522a1eSNikolay Borisov 				break;
2701b8522a1eSNikolay Borisov 
2702b8522a1eSNikolay Borisov 			free_root_pointers(fs_info, 0);
2703b8522a1eSNikolay Borisov 
2704b8522a1eSNikolay Borisov 			/*
2705b8522a1eSNikolay Borisov 			 * Don't use the log in recovery mode, it won't be
2706b8522a1eSNikolay Borisov 			 * valid
2707b8522a1eSNikolay Borisov 			 */
2708b8522a1eSNikolay Borisov 			btrfs_set_super_log_root(sb, 0);
2709b8522a1eSNikolay Borisov 
2710b8522a1eSNikolay Borisov 			/* We can't trust the free space cache either */
2711b8522a1eSNikolay Borisov 			btrfs_set_opt(fs_info->mount_opt, CLEAR_CACHE);
2712b8522a1eSNikolay Borisov 
2713b8522a1eSNikolay Borisov 			ret = read_backup_root(fs_info, i);
27146ef108ddSNikolay Borisov 			backup_index = ret;
2715b8522a1eSNikolay Borisov 			if (ret < 0)
2716b8522a1eSNikolay Borisov 				return ret;
2717b8522a1eSNikolay Borisov 		}
2718b8522a1eSNikolay Borisov 		generation = btrfs_super_generation(sb);
2719b8522a1eSNikolay Borisov 		level = btrfs_super_root_level(sb);
2720b8522a1eSNikolay Borisov 		tree_root->node = read_tree_block(fs_info, btrfs_super_root(sb),
27211b7ec85eSJosef Bacik 						  BTRFS_ROOT_TREE_OBJECTID,
2722b8522a1eSNikolay Borisov 						  generation, level, NULL);
27230465337cSJosef Bacik 		if (IS_ERR(tree_root->node)) {
2724217f5004SNikolay Borisov 			handle_error = true;
2725b8522a1eSNikolay Borisov 			ret = PTR_ERR(tree_root->node);
27260465337cSJosef Bacik 			tree_root->node = NULL;
2727217f5004SNikolay Borisov 			btrfs_warn(fs_info, "couldn't read tree root");
2728217f5004SNikolay Borisov 			continue;
2729b8522a1eSNikolay Borisov 
2730217f5004SNikolay Borisov 		} else if (!extent_buffer_uptodate(tree_root->node)) {
2731217f5004SNikolay Borisov 			handle_error = true;
2732217f5004SNikolay Borisov 			ret = -EIO;
2733217f5004SNikolay Borisov 			btrfs_warn(fs_info, "error while reading tree root");
2734b8522a1eSNikolay Borisov 			continue;
2735b8522a1eSNikolay Borisov 		}
2736b8522a1eSNikolay Borisov 
2737b8522a1eSNikolay Borisov 		btrfs_set_root_node(&tree_root->root_item, tree_root->node);
2738b8522a1eSNikolay Borisov 		tree_root->commit_root = btrfs_root_node(tree_root);
2739b8522a1eSNikolay Borisov 		btrfs_set_root_refs(&tree_root->root_item, 1);
2740b8522a1eSNikolay Borisov 
2741336a0d8dSNikolay Borisov 		/*
2742336a0d8dSNikolay Borisov 		 * No need to hold btrfs_root::objectid_mutex since the fs
2743336a0d8dSNikolay Borisov 		 * hasn't been fully initialised and we are the only user
2744336a0d8dSNikolay Borisov 		 */
2745453e4873SNikolay Borisov 		ret = btrfs_init_root_free_objectid(tree_root);
2746b8522a1eSNikolay Borisov 		if (ret < 0) {
2747b8522a1eSNikolay Borisov 			handle_error = true;
2748b8522a1eSNikolay Borisov 			continue;
2749b8522a1eSNikolay Borisov 		}
2750b8522a1eSNikolay Borisov 
27516b8fad57SNikolay Borisov 		ASSERT(tree_root->free_objectid <= BTRFS_LAST_FREE_OBJECTID);
2752b8522a1eSNikolay Borisov 
2753b8522a1eSNikolay Borisov 		ret = btrfs_read_roots(fs_info);
2754b8522a1eSNikolay Borisov 		if (ret < 0) {
2755b8522a1eSNikolay Borisov 			handle_error = true;
2756b8522a1eSNikolay Borisov 			continue;
2757b8522a1eSNikolay Borisov 		}
2758b8522a1eSNikolay Borisov 
2759b8522a1eSNikolay Borisov 		/* All successful */
2760b8522a1eSNikolay Borisov 		fs_info->generation = generation;
2761b8522a1eSNikolay Borisov 		fs_info->last_trans_committed = generation;
27626ef108ddSNikolay Borisov 
27636ef108ddSNikolay Borisov 		/* Always begin writing backup roots after the one being used */
27646ef108ddSNikolay Borisov 		if (backup_index < 0) {
27656ef108ddSNikolay Borisov 			fs_info->backup_root_index = 0;
27666ef108ddSNikolay Borisov 		} else {
27676ef108ddSNikolay Borisov 			fs_info->backup_root_index = backup_index + 1;
27686ef108ddSNikolay Borisov 			fs_info->backup_root_index %= BTRFS_NUM_BACKUP_ROOTS;
27696ef108ddSNikolay Borisov 		}
2770b8522a1eSNikolay Borisov 		break;
2771b8522a1eSNikolay Borisov 	}
2772b8522a1eSNikolay Borisov 
2773b8522a1eSNikolay Borisov 	return ret;
2774b8522a1eSNikolay Borisov }
2775b8522a1eSNikolay Borisov 
27768260edbaSJosef Bacik void btrfs_init_fs_info(struct btrfs_fs_info *fs_info)
2777eb60ceacSChris Mason {
277876dda93cSYan, Zheng 	INIT_RADIX_TREE(&fs_info->fs_roots_radix, GFP_ATOMIC);
2779f28491e0SJosef Bacik 	INIT_RADIX_TREE(&fs_info->buffer_radix, GFP_ATOMIC);
27808fd17795SChris Mason 	INIT_LIST_HEAD(&fs_info->trans_list);
2781facda1e7SChris Mason 	INIT_LIST_HEAD(&fs_info->dead_roots);
278224bbcf04SYan, Zheng 	INIT_LIST_HEAD(&fs_info->delayed_iputs);
2783eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&fs_info->delalloc_roots);
278411833d66SYan Zheng 	INIT_LIST_HEAD(&fs_info->caching_block_groups);
2785eb73c1b7SMiao Xie 	spin_lock_init(&fs_info->delalloc_root_lock);
2786a4abeea4SJosef Bacik 	spin_lock_init(&fs_info->trans_lock);
278776dda93cSYan, Zheng 	spin_lock_init(&fs_info->fs_roots_radix_lock);
278824bbcf04SYan, Zheng 	spin_lock_init(&fs_info->delayed_iput_lock);
27894cb5300bSChris Mason 	spin_lock_init(&fs_info->defrag_inodes_lock);
2790ceda0864SMiao Xie 	spin_lock_init(&fs_info->super_lock);
2791f28491e0SJosef Bacik 	spin_lock_init(&fs_info->buffer_lock);
279247ab2a6cSJosef Bacik 	spin_lock_init(&fs_info->unused_bgs_lock);
279340ab3be1SNaohiro Aota 	spin_lock_init(&fs_info->treelog_bg_lock);
2794f29021b2SJan Schmidt 	rwlock_init(&fs_info->tree_mod_log_lock);
2795d7c15171SZhao Lei 	mutex_init(&fs_info->unused_bg_unpin_mutex);
279667c5e7d4SFilipe Manana 	mutex_init(&fs_info->delete_unused_bgs_mutex);
27977585717fSChris Mason 	mutex_init(&fs_info->reloc_mutex);
2798573bfb72SMiao Xie 	mutex_init(&fs_info->delalloc_root_mutex);
27990bc09ca1SNaohiro Aota 	mutex_init(&fs_info->zoned_meta_io_lock);
2800de98ced9SMiao Xie 	seqlock_init(&fs_info->profiles_lock);
280119c00ddcSChris Mason 
28020b86a832SChris Mason 	INIT_LIST_HEAD(&fs_info->dirty_cowonly_roots);
28036324fbf3SChris Mason 	INIT_LIST_HEAD(&fs_info->space_info);
2804f29021b2SJan Schmidt 	INIT_LIST_HEAD(&fs_info->tree_mod_seq_list);
280547ab2a6cSJosef Bacik 	INIT_LIST_HEAD(&fs_info->unused_bgs);
2806bd647ce3SJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
2807bd647ce3SJosef Bacik 	INIT_LIST_HEAD(&fs_info->allocated_roots);
28083fd63727SJosef Bacik 	INIT_LIST_HEAD(&fs_info->allocated_ebs);
28093fd63727SJosef Bacik 	spin_lock_init(&fs_info->eb_leak_lock);
2810bd647ce3SJosef Bacik #endif
2811c8bf1b67SDavid Sterba 	extent_map_tree_init(&fs_info->mapping_tree);
281266d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->global_block_rsv,
281366d8f3ddSMiao Xie 			     BTRFS_BLOCK_RSV_GLOBAL);
281466d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->trans_block_rsv, BTRFS_BLOCK_RSV_TRANS);
281566d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->chunk_block_rsv, BTRFS_BLOCK_RSV_CHUNK);
281666d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->empty_block_rsv, BTRFS_BLOCK_RSV_EMPTY);
281766d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->delayed_block_rsv,
281866d8f3ddSMiao Xie 			     BTRFS_BLOCK_RSV_DELOPS);
2819ba2c4d4eSJosef Bacik 	btrfs_init_block_rsv(&fs_info->delayed_refs_rsv,
2820ba2c4d4eSJosef Bacik 			     BTRFS_BLOCK_RSV_DELREFS);
2821ba2c4d4eSJosef Bacik 
2822771ed689SChris Mason 	atomic_set(&fs_info->async_delalloc_pages, 0);
28234cb5300bSChris Mason 	atomic_set(&fs_info->defrag_running, 0);
28242fefd558SZhao Lei 	atomic_set(&fs_info->reada_works_cnt, 0);
2825034f784dSJosef Bacik 	atomic_set(&fs_info->nr_delayed_iputs, 0);
2826fc36ed7eSJan Schmidt 	atomic64_set(&fs_info->tree_mod_seq, 0);
282795ac567aSFilipe David Borba Manana 	fs_info->max_inline = BTRFS_DEFAULT_MAX_INLINE;
28289ed74f2dSJosef Bacik 	fs_info->metadata_ratio = 0;
28294cb5300bSChris Mason 	fs_info->defrag_inodes = RB_ROOT;
2830a5ed45f8SNikolay Borisov 	atomic64_set(&fs_info->free_chunk_space, 0);
2831f29021b2SJan Schmidt 	fs_info->tree_mod_log = RB_ROOT;
28328b87dc17SDavid Sterba 	fs_info->commit_interval = BTRFS_DEFAULT_COMMIT_INTERVAL;
2833f8c269d7SDavid Sterba 	fs_info->avg_delayed_ref_runtime = NSEC_PER_SEC >> 6; /* div by 64 */
283490519d66SArne Jansen 	/* readahead state */
2835d0164adcSMel Gorman 	INIT_RADIX_TREE(&fs_info->reada_tree, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
283690519d66SArne Jansen 	spin_lock_init(&fs_info->reada_lock);
2837fd708b81SJosef Bacik 	btrfs_init_ref_verify(fs_info);
2838c8b97818SChris Mason 
2839b34b086cSChris Mason 	fs_info->thread_pool_size = min_t(unsigned long,
2840b34b086cSChris Mason 					  num_online_cpus() + 2, 8);
28410afbaf8cSChris Mason 
2842199c2a9cSMiao Xie 	INIT_LIST_HEAD(&fs_info->ordered_roots);
2843199c2a9cSMiao Xie 	spin_lock_init(&fs_info->ordered_root_lock);
284469fe2d75SJosef Bacik 
2845638aa7edSEric Sandeen 	btrfs_init_scrub(fs_info);
284621adbd5cSStefan Behrens #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
284721adbd5cSStefan Behrens 	fs_info->check_integrity_print_mask = 0;
284821adbd5cSStefan Behrens #endif
2849779a65a4SEric Sandeen 	btrfs_init_balance(fs_info);
285057056740SJosef Bacik 	btrfs_init_async_reclaim_work(fs_info);
2851a2de733cSArne Jansen 
28520f9dd46cSJosef Bacik 	spin_lock_init(&fs_info->block_group_cache_lock);
28536bef4d31SEric Paris 	fs_info->block_group_cache_tree = RB_ROOT;
2854a1897fddSLiu Bo 	fs_info->first_logical_byte = (u64)-1;
28550f9dd46cSJosef Bacik 
2856fe119a6eSNikolay Borisov 	extent_io_tree_init(fs_info, &fs_info->excluded_extents,
2857fe119a6eSNikolay Borisov 			    IO_TREE_FS_EXCLUDED_EXTENTS, NULL);
2858afcdd129SJosef Bacik 	set_bit(BTRFS_FS_BARRIER, &fs_info->flags);
285939279cc3SChris Mason 
28605a3f23d5SChris Mason 	mutex_init(&fs_info->ordered_operations_mutex);
2861e02119d5SChris Mason 	mutex_init(&fs_info->tree_log_mutex);
2862925baeddSChris Mason 	mutex_init(&fs_info->chunk_mutex);
2863a74a4b97SChris Mason 	mutex_init(&fs_info->transaction_kthread_mutex);
2864a74a4b97SChris Mason 	mutex_init(&fs_info->cleaner_mutex);
28651bbc621eSChris Mason 	mutex_init(&fs_info->ro_block_group_mutex);
28669e351cc8SJosef Bacik 	init_rwsem(&fs_info->commit_root_sem);
2867c71bf099SYan, Zheng 	init_rwsem(&fs_info->cleanup_work_sem);
286876dda93cSYan, Zheng 	init_rwsem(&fs_info->subvol_sem);
2869803b2f54SStefan Behrens 	sema_init(&fs_info->uuid_tree_rescan_sem, 1);
2870fa9c0d79SChris Mason 
2871ad618368SEric Sandeen 	btrfs_init_dev_replace_locks(fs_info);
2872f9e92e40SEric Sandeen 	btrfs_init_qgroup(fs_info);
2873b0643e59SDennis Zhou 	btrfs_discard_init(fs_info);
2874416ac51dSArne Jansen 
2875fa9c0d79SChris Mason 	btrfs_init_free_cluster(&fs_info->meta_alloc_cluster);
2876fa9c0d79SChris Mason 	btrfs_init_free_cluster(&fs_info->data_alloc_cluster);
2877fa9c0d79SChris Mason 
2878e6dcd2dcSChris Mason 	init_waitqueue_head(&fs_info->transaction_throttle);
2879f9295749SChris Mason 	init_waitqueue_head(&fs_info->transaction_wait);
2880bb9c12c9SSage Weil 	init_waitqueue_head(&fs_info->transaction_blocked_wait);
28814854ddd0SChris Mason 	init_waitqueue_head(&fs_info->async_submit_wait);
2882034f784dSJosef Bacik 	init_waitqueue_head(&fs_info->delayed_iputs_wait);
28833768f368SChris Mason 
2884da17066cSJeff Mahoney 	/* Usable values until the real ones are cached from the superblock */
2885da17066cSJeff Mahoney 	fs_info->nodesize = 4096;
2886da17066cSJeff Mahoney 	fs_info->sectorsize = 4096;
2887ab108d99SDavid Sterba 	fs_info->sectorsize_bits = ilog2(4096);
2888da17066cSJeff Mahoney 	fs_info->stripesize = 4096;
2889da17066cSJeff Mahoney 
2890eede2bf3SOmar Sandoval 	spin_lock_init(&fs_info->swapfile_pins_lock);
2891eede2bf3SOmar Sandoval 	fs_info->swapfile_pins = RB_ROOT;
2892eede2bf3SOmar Sandoval 
28939e967495SFilipe Manana 	fs_info->send_in_progress = 0;
28948260edbaSJosef Bacik }
28958260edbaSJosef Bacik 
28968260edbaSJosef Bacik static int init_mount_fs_info(struct btrfs_fs_info *fs_info, struct super_block *sb)
28978260edbaSJosef Bacik {
28988260edbaSJosef Bacik 	int ret;
28998260edbaSJosef Bacik 
29008260edbaSJosef Bacik 	fs_info->sb = sb;
29018260edbaSJosef Bacik 	sb->s_blocksize = BTRFS_BDEV_BLOCKSIZE;
29028260edbaSJosef Bacik 	sb->s_blocksize_bits = blksize_bits(BTRFS_BDEV_BLOCKSIZE);
29039e967495SFilipe Manana 
29045deb17e1SJosef Bacik 	ret = percpu_counter_init(&fs_info->ordered_bytes, 0, GFP_KERNEL);
2905ae18c37aSJosef Bacik 	if (ret)
2906ae18c37aSJosef Bacik 		return ret;
2907ae18c37aSJosef Bacik 
2908ae18c37aSJosef Bacik 	ret = percpu_counter_init(&fs_info->dirty_metadata_bytes, 0, GFP_KERNEL);
2909ae18c37aSJosef Bacik 	if (ret)
2910c75e8394SJosef Bacik 		return ret;
2911ae18c37aSJosef Bacik 
2912ae18c37aSJosef Bacik 	fs_info->dirty_metadata_batch = PAGE_SIZE *
2913ae18c37aSJosef Bacik 					(1 + ilog2(nr_cpu_ids));
2914ae18c37aSJosef Bacik 
2915ae18c37aSJosef Bacik 	ret = percpu_counter_init(&fs_info->delalloc_bytes, 0, GFP_KERNEL);
2916ae18c37aSJosef Bacik 	if (ret)
2917c75e8394SJosef Bacik 		return ret;
2918ae18c37aSJosef Bacik 
2919ae18c37aSJosef Bacik 	ret = percpu_counter_init(&fs_info->dev_replace.bio_counter, 0,
2920ae18c37aSJosef Bacik 			GFP_KERNEL);
2921ae18c37aSJosef Bacik 	if (ret)
2922c75e8394SJosef Bacik 		return ret;
2923ae18c37aSJosef Bacik 
2924ae18c37aSJosef Bacik 	fs_info->delayed_root = kmalloc(sizeof(struct btrfs_delayed_root),
2925ae18c37aSJosef Bacik 					GFP_KERNEL);
2926c75e8394SJosef Bacik 	if (!fs_info->delayed_root)
2927c75e8394SJosef Bacik 		return -ENOMEM;
2928ae18c37aSJosef Bacik 	btrfs_init_delayed_root(fs_info->delayed_root);
2929ae18c37aSJosef Bacik 
2930a0a1db70SFilipe Manana 	if (sb_rdonly(sb))
2931a0a1db70SFilipe Manana 		set_bit(BTRFS_FS_STATE_RO, &fs_info->fs_state);
2932a0a1db70SFilipe Manana 
2933c75e8394SJosef Bacik 	return btrfs_alloc_stripe_hash_table(fs_info);
2934ae18c37aSJosef Bacik }
2935ae18c37aSJosef Bacik 
293697f4dd09SNikolay Borisov static int btrfs_uuid_rescan_kthread(void *data)
293797f4dd09SNikolay Borisov {
293897f4dd09SNikolay Borisov 	struct btrfs_fs_info *fs_info = (struct btrfs_fs_info *)data;
293997f4dd09SNikolay Borisov 	int ret;
294097f4dd09SNikolay Borisov 
294197f4dd09SNikolay Borisov 	/*
294297f4dd09SNikolay Borisov 	 * 1st step is to iterate through the existing UUID tree and
294397f4dd09SNikolay Borisov 	 * to delete all entries that contain outdated data.
294497f4dd09SNikolay Borisov 	 * 2nd step is to add all missing entries to the UUID tree.
294597f4dd09SNikolay Borisov 	 */
294697f4dd09SNikolay Borisov 	ret = btrfs_uuid_tree_iterate(fs_info);
294797f4dd09SNikolay Borisov 	if (ret < 0) {
2948c94bec2cSJosef Bacik 		if (ret != -EINTR)
2949c94bec2cSJosef Bacik 			btrfs_warn(fs_info, "iterating uuid_tree failed %d",
2950c94bec2cSJosef Bacik 				   ret);
295197f4dd09SNikolay Borisov 		up(&fs_info->uuid_tree_rescan_sem);
295297f4dd09SNikolay Borisov 		return ret;
295397f4dd09SNikolay Borisov 	}
295497f4dd09SNikolay Borisov 	return btrfs_uuid_scan_kthread(data);
295597f4dd09SNikolay Borisov }
295697f4dd09SNikolay Borisov 
295797f4dd09SNikolay Borisov static int btrfs_check_uuid_tree(struct btrfs_fs_info *fs_info)
295897f4dd09SNikolay Borisov {
295997f4dd09SNikolay Borisov 	struct task_struct *task;
296097f4dd09SNikolay Borisov 
296197f4dd09SNikolay Borisov 	down(&fs_info->uuid_tree_rescan_sem);
296297f4dd09SNikolay Borisov 	task = kthread_run(btrfs_uuid_rescan_kthread, fs_info, "btrfs-uuid");
296397f4dd09SNikolay Borisov 	if (IS_ERR(task)) {
296497f4dd09SNikolay Borisov 		/* fs_info->update_uuid_tree_gen remains 0 in all error case */
296597f4dd09SNikolay Borisov 		btrfs_warn(fs_info, "failed to start uuid_rescan task");
296697f4dd09SNikolay Borisov 		up(&fs_info->uuid_tree_rescan_sem);
296797f4dd09SNikolay Borisov 		return PTR_ERR(task);
296897f4dd09SNikolay Borisov 	}
296997f4dd09SNikolay Borisov 
297097f4dd09SNikolay Borisov 	return 0;
297197f4dd09SNikolay Borisov }
297297f4dd09SNikolay Borisov 
297344c0ca21SBoris Burkov /*
29748cd29088SBoris Burkov  * Some options only have meaning at mount time and shouldn't persist across
29758cd29088SBoris Burkov  * remounts, or be displayed. Clear these at the end of mount and remount
29768cd29088SBoris Burkov  * code paths.
29778cd29088SBoris Burkov  */
29788cd29088SBoris Burkov void btrfs_clear_oneshot_options(struct btrfs_fs_info *fs_info)
29798cd29088SBoris Burkov {
29808cd29088SBoris Burkov 	btrfs_clear_opt(fs_info->mount_opt, USEBACKUPROOT);
29818b228324SBoris Burkov 	btrfs_clear_opt(fs_info->mount_opt, CLEAR_CACHE);
29828cd29088SBoris Burkov }
29838cd29088SBoris Burkov 
29848cd29088SBoris Burkov /*
298544c0ca21SBoris Burkov  * Mounting logic specific to read-write file systems. Shared by open_ctree
298644c0ca21SBoris Burkov  * and btrfs_remount when remounting from read-only to read-write.
298744c0ca21SBoris Burkov  */
298844c0ca21SBoris Burkov int btrfs_start_pre_rw_mount(struct btrfs_fs_info *fs_info)
298944c0ca21SBoris Burkov {
299044c0ca21SBoris Burkov 	int ret;
299194846229SBoris Burkov 	const bool cache_opt = btrfs_test_opt(fs_info, SPACE_CACHE);
29928b228324SBoris Burkov 	bool clear_free_space_tree = false;
29938b228324SBoris Burkov 
29948b228324SBoris Burkov 	if (btrfs_test_opt(fs_info, CLEAR_CACHE) &&
29958b228324SBoris Burkov 	    btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
29968b228324SBoris Burkov 		clear_free_space_tree = true;
29978b228324SBoris Burkov 	} else if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE) &&
29988b228324SBoris Burkov 		   !btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE_VALID)) {
29998b228324SBoris Burkov 		btrfs_warn(fs_info, "free space tree is invalid");
30008b228324SBoris Burkov 		clear_free_space_tree = true;
30018b228324SBoris Burkov 	}
30028b228324SBoris Burkov 
30038b228324SBoris Burkov 	if (clear_free_space_tree) {
30048b228324SBoris Burkov 		btrfs_info(fs_info, "clearing free space tree");
30058b228324SBoris Burkov 		ret = btrfs_clear_free_space_tree(fs_info);
30068b228324SBoris Burkov 		if (ret) {
30078b228324SBoris Burkov 			btrfs_warn(fs_info,
30088b228324SBoris Burkov 				   "failed to clear free space tree: %d", ret);
30098b228324SBoris Burkov 			goto out;
30108b228324SBoris Burkov 		}
30118b228324SBoris Burkov 	}
301244c0ca21SBoris Burkov 
301344c0ca21SBoris Burkov 	ret = btrfs_cleanup_fs_roots(fs_info);
301444c0ca21SBoris Burkov 	if (ret)
301544c0ca21SBoris Burkov 		goto out;
301644c0ca21SBoris Burkov 
30178f1c21d7SBoris Burkov 	down_read(&fs_info->cleanup_work_sem);
30188f1c21d7SBoris Burkov 	if ((ret = btrfs_orphan_cleanup(fs_info->fs_root)) ||
30198f1c21d7SBoris Burkov 	    (ret = btrfs_orphan_cleanup(fs_info->tree_root))) {
30208f1c21d7SBoris Burkov 		up_read(&fs_info->cleanup_work_sem);
30218f1c21d7SBoris Burkov 		goto out;
30228f1c21d7SBoris Burkov 	}
30238f1c21d7SBoris Burkov 	up_read(&fs_info->cleanup_work_sem);
30248f1c21d7SBoris Burkov 
302544c0ca21SBoris Burkov 	mutex_lock(&fs_info->cleaner_mutex);
302644c0ca21SBoris Burkov 	ret = btrfs_recover_relocation(fs_info->tree_root);
302744c0ca21SBoris Burkov 	mutex_unlock(&fs_info->cleaner_mutex);
302844c0ca21SBoris Burkov 	if (ret < 0) {
302944c0ca21SBoris Burkov 		btrfs_warn(fs_info, "failed to recover relocation: %d", ret);
303044c0ca21SBoris Burkov 		goto out;
303144c0ca21SBoris Burkov 	}
303244c0ca21SBoris Burkov 
30335011139aSBoris Burkov 	if (btrfs_test_opt(fs_info, FREE_SPACE_TREE) &&
30345011139aSBoris Burkov 	    !btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
30355011139aSBoris Burkov 		btrfs_info(fs_info, "creating free space tree");
30365011139aSBoris Burkov 		ret = btrfs_create_free_space_tree(fs_info);
30375011139aSBoris Burkov 		if (ret) {
30385011139aSBoris Burkov 			btrfs_warn(fs_info,
30395011139aSBoris Burkov 				"failed to create free space tree: %d", ret);
30405011139aSBoris Burkov 			goto out;
30415011139aSBoris Burkov 		}
30425011139aSBoris Burkov 	}
30435011139aSBoris Burkov 
304494846229SBoris Burkov 	if (cache_opt != btrfs_free_space_cache_v1_active(fs_info)) {
304594846229SBoris Burkov 		ret = btrfs_set_free_space_cache_v1_active(fs_info, cache_opt);
304694846229SBoris Burkov 		if (ret)
304794846229SBoris Burkov 			goto out;
304894846229SBoris Burkov 	}
304994846229SBoris Burkov 
305044c0ca21SBoris Burkov 	ret = btrfs_resume_balance_async(fs_info);
305144c0ca21SBoris Burkov 	if (ret)
305244c0ca21SBoris Burkov 		goto out;
305344c0ca21SBoris Burkov 
305444c0ca21SBoris Burkov 	ret = btrfs_resume_dev_replace_async(fs_info);
305544c0ca21SBoris Burkov 	if (ret) {
305644c0ca21SBoris Burkov 		btrfs_warn(fs_info, "failed to resume dev_replace");
305744c0ca21SBoris Burkov 		goto out;
305844c0ca21SBoris Burkov 	}
305944c0ca21SBoris Burkov 
306044c0ca21SBoris Burkov 	btrfs_qgroup_rescan_resume(fs_info);
306144c0ca21SBoris Burkov 
306244c0ca21SBoris Burkov 	if (!fs_info->uuid_root) {
306344c0ca21SBoris Burkov 		btrfs_info(fs_info, "creating UUID tree");
306444c0ca21SBoris Burkov 		ret = btrfs_create_uuid_tree(fs_info);
306544c0ca21SBoris Burkov 		if (ret) {
306644c0ca21SBoris Burkov 			btrfs_warn(fs_info,
306744c0ca21SBoris Burkov 				   "failed to create the UUID tree %d", ret);
306844c0ca21SBoris Burkov 			goto out;
306944c0ca21SBoris Burkov 		}
307044c0ca21SBoris Burkov 	}
307144c0ca21SBoris Burkov 
3072638331faSFilipe Manana 	ret = btrfs_find_orphan_roots(fs_info);
307344c0ca21SBoris Burkov out:
307444c0ca21SBoris Burkov 	return ret;
307544c0ca21SBoris Burkov }
307644c0ca21SBoris Burkov 
3077ae18c37aSJosef Bacik int __cold open_ctree(struct super_block *sb, struct btrfs_fs_devices *fs_devices,
3078ae18c37aSJosef Bacik 		      char *options)
3079ae18c37aSJosef Bacik {
3080ae18c37aSJosef Bacik 	u32 sectorsize;
3081ae18c37aSJosef Bacik 	u32 nodesize;
3082ae18c37aSJosef Bacik 	u32 stripesize;
3083ae18c37aSJosef Bacik 	u64 generation;
3084ae18c37aSJosef Bacik 	u64 features;
3085ae18c37aSJosef Bacik 	u16 csum_type;
3086ae18c37aSJosef Bacik 	struct btrfs_super_block *disk_super;
3087ae18c37aSJosef Bacik 	struct btrfs_fs_info *fs_info = btrfs_sb(sb);
3088ae18c37aSJosef Bacik 	struct btrfs_root *tree_root;
3089ae18c37aSJosef Bacik 	struct btrfs_root *chunk_root;
3090ae18c37aSJosef Bacik 	int ret;
3091ae18c37aSJosef Bacik 	int err = -EINVAL;
3092ae18c37aSJosef Bacik 	int level;
3093ae18c37aSJosef Bacik 
30948260edbaSJosef Bacik 	ret = init_mount_fs_info(fs_info, sb);
309553b381b3SDavid Woodhouse 	if (ret) {
309683c8266aSDavid Sterba 		err = ret;
3097ae18c37aSJosef Bacik 		goto fail;
309853b381b3SDavid Woodhouse 	}
309953b381b3SDavid Woodhouse 
3100ae18c37aSJosef Bacik 	/* These need to be init'ed before we start creating inodes and such. */
3101ae18c37aSJosef Bacik 	tree_root = btrfs_alloc_root(fs_info, BTRFS_ROOT_TREE_OBJECTID,
3102ae18c37aSJosef Bacik 				     GFP_KERNEL);
3103ae18c37aSJosef Bacik 	fs_info->tree_root = tree_root;
3104ae18c37aSJosef Bacik 	chunk_root = btrfs_alloc_root(fs_info, BTRFS_CHUNK_TREE_OBJECTID,
3105ae18c37aSJosef Bacik 				      GFP_KERNEL);
3106ae18c37aSJosef Bacik 	fs_info->chunk_root = chunk_root;
3107ae18c37aSJosef Bacik 	if (!tree_root || !chunk_root) {
3108ae18c37aSJosef Bacik 		err = -ENOMEM;
3109c75e8394SJosef Bacik 		goto fail;
3110ae18c37aSJosef Bacik 	}
3111ae18c37aSJosef Bacik 
3112ae18c37aSJosef Bacik 	fs_info->btree_inode = new_inode(sb);
3113ae18c37aSJosef Bacik 	if (!fs_info->btree_inode) {
3114ae18c37aSJosef Bacik 		err = -ENOMEM;
3115c75e8394SJosef Bacik 		goto fail;
3116ae18c37aSJosef Bacik 	}
3117ae18c37aSJosef Bacik 	mapping_set_gfp_mask(fs_info->btree_inode->i_mapping, GFP_NOFS);
3118ae18c37aSJosef Bacik 	btrfs_init_btree_inode(fs_info);
3119ae18c37aSJosef Bacik 
31203c4bb26bSChris Mason 	invalidate_bdev(fs_devices->latest_bdev);
31211104a885SDavid Sterba 
31221104a885SDavid Sterba 	/*
31231104a885SDavid Sterba 	 * Read super block and check the signature bytes only
31241104a885SDavid Sterba 	 */
31258f32380dSJohannes Thumshirn 	disk_super = btrfs_read_dev_super(fs_devices->latest_bdev);
31268f32380dSJohannes Thumshirn 	if (IS_ERR(disk_super)) {
31278f32380dSJohannes Thumshirn 		err = PTR_ERR(disk_super);
312816cdcec7SMiao Xie 		goto fail_alloc;
312920b45077SDave Young 	}
313039279cc3SChris Mason 
31311104a885SDavid Sterba 	/*
3132260db43cSRandy Dunlap 	 * Verify the type first, if that or the checksum value are
31338dc3f22cSJohannes Thumshirn 	 * corrupted, we'll find out
31348dc3f22cSJohannes Thumshirn 	 */
31358f32380dSJohannes Thumshirn 	csum_type = btrfs_super_csum_type(disk_super);
313651bce6c9SJohannes Thumshirn 	if (!btrfs_supported_super_csum(csum_type)) {
31378dc3f22cSJohannes Thumshirn 		btrfs_err(fs_info, "unsupported checksum algorithm: %u",
313851bce6c9SJohannes Thumshirn 			  csum_type);
31398dc3f22cSJohannes Thumshirn 		err = -EINVAL;
31408f32380dSJohannes Thumshirn 		btrfs_release_disk_super(disk_super);
31418dc3f22cSJohannes Thumshirn 		goto fail_alloc;
31428dc3f22cSJohannes Thumshirn 	}
31438dc3f22cSJohannes Thumshirn 
31446d97c6e3SJohannes Thumshirn 	ret = btrfs_init_csum_hash(fs_info, csum_type);
31456d97c6e3SJohannes Thumshirn 	if (ret) {
31466d97c6e3SJohannes Thumshirn 		err = ret;
31478f32380dSJohannes Thumshirn 		btrfs_release_disk_super(disk_super);
31486d97c6e3SJohannes Thumshirn 		goto fail_alloc;
31496d97c6e3SJohannes Thumshirn 	}
31506d97c6e3SJohannes Thumshirn 
31518dc3f22cSJohannes Thumshirn 	/*
31521104a885SDavid Sterba 	 * We want to check superblock checksum, the type is stored inside.
31531104a885SDavid Sterba 	 * Pass the whole disk block of size BTRFS_SUPER_INFO_SIZE (4k).
31541104a885SDavid Sterba 	 */
31558f32380dSJohannes Thumshirn 	if (btrfs_check_super_csum(fs_info, (u8 *)disk_super)) {
315605135f59SDavid Sterba 		btrfs_err(fs_info, "superblock checksum mismatch");
31571104a885SDavid Sterba 		err = -EINVAL;
31588f32380dSJohannes Thumshirn 		btrfs_release_disk_super(disk_super);
3159141386e1SJosef Bacik 		goto fail_alloc;
31601104a885SDavid Sterba 	}
31611104a885SDavid Sterba 
31621104a885SDavid Sterba 	/*
31631104a885SDavid Sterba 	 * super_copy is zeroed at allocation time and we never touch the
31641104a885SDavid Sterba 	 * following bytes up to INFO_SIZE, the checksum is calculated from
31651104a885SDavid Sterba 	 * the whole block of INFO_SIZE
31661104a885SDavid Sterba 	 */
31678f32380dSJohannes Thumshirn 	memcpy(fs_info->super_copy, disk_super, sizeof(*fs_info->super_copy));
31688f32380dSJohannes Thumshirn 	btrfs_release_disk_super(disk_super);
31695f39d397SChris Mason 
3170fbc6feaeSNikolay Borisov 	disk_super = fs_info->super_copy;
3171fbc6feaeSNikolay Borisov 
3172de37aa51SNikolay Borisov 	ASSERT(!memcmp(fs_info->fs_devices->fsid, fs_info->super_copy->fsid,
3173de37aa51SNikolay Borisov 		       BTRFS_FSID_SIZE));
3174de37aa51SNikolay Borisov 
31757239ff4bSNikolay Borisov 	if (btrfs_fs_incompat(fs_info, METADATA_UUID)) {
3176de37aa51SNikolay Borisov 		ASSERT(!memcmp(fs_info->fs_devices->metadata_uuid,
3177de37aa51SNikolay Borisov 				fs_info->super_copy->metadata_uuid,
3178de37aa51SNikolay Borisov 				BTRFS_FSID_SIZE));
31797239ff4bSNikolay Borisov 	}
31800b86a832SChris Mason 
3181fbc6feaeSNikolay Borisov 	features = btrfs_super_flags(disk_super);
3182fbc6feaeSNikolay Borisov 	if (features & BTRFS_SUPER_FLAG_CHANGING_FSID_V2) {
3183fbc6feaeSNikolay Borisov 		features &= ~BTRFS_SUPER_FLAG_CHANGING_FSID_V2;
3184fbc6feaeSNikolay Borisov 		btrfs_set_super_flags(disk_super, features);
3185fbc6feaeSNikolay Borisov 		btrfs_info(fs_info,
3186fbc6feaeSNikolay Borisov 			"found metadata UUID change in progress flag, clearing");
3187fbc6feaeSNikolay Borisov 	}
3188fbc6feaeSNikolay Borisov 
3189fbc6feaeSNikolay Borisov 	memcpy(fs_info->super_for_commit, fs_info->super_copy,
3190fbc6feaeSNikolay Borisov 	       sizeof(*fs_info->super_for_commit));
3191de37aa51SNikolay Borisov 
3192069ec957SQu Wenruo 	ret = btrfs_validate_mount_super(fs_info);
31931104a885SDavid Sterba 	if (ret) {
319405135f59SDavid Sterba 		btrfs_err(fs_info, "superblock contains fatal errors");
31951104a885SDavid Sterba 		err = -EINVAL;
3196141386e1SJosef Bacik 		goto fail_alloc;
31971104a885SDavid Sterba 	}
31981104a885SDavid Sterba 
31990f7d52f4SChris Mason 	if (!btrfs_super_root(disk_super))
3200141386e1SJosef Bacik 		goto fail_alloc;
32010f7d52f4SChris Mason 
3202acce952bSliubo 	/* check FS state, whether FS is broken. */
320387533c47SMiao Xie 	if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_ERROR)
320487533c47SMiao Xie 		set_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state);
3205acce952bSliubo 
320675e7cb7fSLiu Bo 	/*
320775e7cb7fSLiu Bo 	 * In the long term, we'll store the compression type in the super
320875e7cb7fSLiu Bo 	 * block, and it'll be used for per file compression control.
320975e7cb7fSLiu Bo 	 */
321075e7cb7fSLiu Bo 	fs_info->compress_type = BTRFS_COMPRESS_ZLIB;
321175e7cb7fSLiu Bo 
32122ff7e61eSJeff Mahoney 	ret = btrfs_parse_options(fs_info, options, sb->s_flags);
32132b82032cSYan Zheng 	if (ret) {
32142b82032cSYan Zheng 		err = ret;
3215141386e1SJosef Bacik 		goto fail_alloc;
32162b82032cSYan Zheng 	}
3217dfe25020SChris Mason 
3218f2b636e8SJosef Bacik 	features = btrfs_super_incompat_flags(disk_super) &
3219f2b636e8SJosef Bacik 		~BTRFS_FEATURE_INCOMPAT_SUPP;
3220f2b636e8SJosef Bacik 	if (features) {
322105135f59SDavid Sterba 		btrfs_err(fs_info,
322205135f59SDavid Sterba 		    "cannot mount because of unsupported optional features (%llx)",
3223c1c9ff7cSGeert Uytterhoeven 		    features);
3224f2b636e8SJosef Bacik 		err = -EINVAL;
3225141386e1SJosef Bacik 		goto fail_alloc;
3226f2b636e8SJosef Bacik 	}
3227f2b636e8SJosef Bacik 
32285d4f98a2SYan Zheng 	features = btrfs_super_incompat_flags(disk_super);
32295d4f98a2SYan Zheng 	features |= BTRFS_FEATURE_INCOMPAT_MIXED_BACKREF;
32300b246afaSJeff Mahoney 	if (fs_info->compress_type == BTRFS_COMPRESS_LZO)
3231a6fa6faeSLi Zefan 		features |= BTRFS_FEATURE_INCOMPAT_COMPRESS_LZO;
32325c1aab1dSNick Terrell 	else if (fs_info->compress_type == BTRFS_COMPRESS_ZSTD)
32335c1aab1dSNick Terrell 		features |= BTRFS_FEATURE_INCOMPAT_COMPRESS_ZSTD;
3234727011e0SChris Mason 
32353173a18fSJosef Bacik 	if (features & BTRFS_FEATURE_INCOMPAT_SKINNY_METADATA)
323605135f59SDavid Sterba 		btrfs_info(fs_info, "has skinny extents");
32373173a18fSJosef Bacik 
3238727011e0SChris Mason 	/*
3239727011e0SChris Mason 	 * flag our filesystem as having big metadata blocks if
3240727011e0SChris Mason 	 * they are bigger than the page size
3241727011e0SChris Mason 	 */
324209cbfeafSKirill A. Shutemov 	if (btrfs_super_nodesize(disk_super) > PAGE_SIZE) {
3243727011e0SChris Mason 		if (!(features & BTRFS_FEATURE_INCOMPAT_BIG_METADATA))
324405135f59SDavid Sterba 			btrfs_info(fs_info,
324505135f59SDavid Sterba 				"flagging fs with big metadata feature");
3246727011e0SChris Mason 		features |= BTRFS_FEATURE_INCOMPAT_BIG_METADATA;
3247727011e0SChris Mason 	}
3248727011e0SChris Mason 
3249bc3f116fSChris Mason 	nodesize = btrfs_super_nodesize(disk_super);
3250bc3f116fSChris Mason 	sectorsize = btrfs_super_sectorsize(disk_super);
3251b7f67055SChandan Rajendra 	stripesize = sectorsize;
3252707e8a07SDavid Sterba 	fs_info->dirty_metadata_batch = nodesize * (1 + ilog2(nr_cpu_ids));
3253963d678bSMiao Xie 	fs_info->delalloc_batch = sectorsize * 512 * (1 + ilog2(nr_cpu_ids));
3254bc3f116fSChris Mason 
3255da17066cSJeff Mahoney 	/* Cache block sizes */
3256da17066cSJeff Mahoney 	fs_info->nodesize = nodesize;
3257da17066cSJeff Mahoney 	fs_info->sectorsize = sectorsize;
3258ab108d99SDavid Sterba 	fs_info->sectorsize_bits = ilog2(sectorsize);
325922b6331dSDavid Sterba 	fs_info->csum_size = btrfs_super_csum_size(disk_super);
3260fe5ecbe8SDavid Sterba 	fs_info->csums_per_leaf = BTRFS_MAX_ITEM_SIZE(fs_info) / fs_info->csum_size;
3261da17066cSJeff Mahoney 	fs_info->stripesize = stripesize;
3262da17066cSJeff Mahoney 
3263bc3f116fSChris Mason 	/*
3264bc3f116fSChris Mason 	 * mixed block groups end up with duplicate but slightly offset
3265bc3f116fSChris Mason 	 * extent buffers for the same range.  It leads to corruptions
3266bc3f116fSChris Mason 	 */
3267bc3f116fSChris Mason 	if ((features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS) &&
3268707e8a07SDavid Sterba 	    (sectorsize != nodesize)) {
326905135f59SDavid Sterba 		btrfs_err(fs_info,
327005135f59SDavid Sterba "unequal nodesize/sectorsize (%u != %u) are not allowed for mixed block groups",
327105135f59SDavid Sterba 			nodesize, sectorsize);
3272141386e1SJosef Bacik 		goto fail_alloc;
3273bc3f116fSChris Mason 	}
3274bc3f116fSChris Mason 
3275ceda0864SMiao Xie 	/*
3276ceda0864SMiao Xie 	 * Needn't use the lock because there is no other task which will
3277ceda0864SMiao Xie 	 * update the flag.
3278ceda0864SMiao Xie 	 */
32795d4f98a2SYan Zheng 	btrfs_set_super_incompat_flags(disk_super, features);
32805d4f98a2SYan Zheng 
3281f2b636e8SJosef Bacik 	features = btrfs_super_compat_ro_flags(disk_super) &
3282f2b636e8SJosef Bacik 		~BTRFS_FEATURE_COMPAT_RO_SUPP;
3283bc98a42cSDavid Howells 	if (!sb_rdonly(sb) && features) {
328405135f59SDavid Sterba 		btrfs_err(fs_info,
328505135f59SDavid Sterba 	"cannot mount read-write because of unsupported optional features (%llx)",
3286c1c9ff7cSGeert Uytterhoeven 		       features);
3287f2b636e8SJosef Bacik 		err = -EINVAL;
3288141386e1SJosef Bacik 		goto fail_alloc;
3289f2b636e8SJosef Bacik 	}
329061d92c32SChris Mason 
32910bb3eb3eSQu Wenruo 	/* For 4K sector size support, it's only read-only */
32920bb3eb3eSQu Wenruo 	if (PAGE_SIZE == SZ_64K && sectorsize == SZ_4K) {
32930bb3eb3eSQu Wenruo 		if (!sb_rdonly(sb) || btrfs_super_log_root(disk_super)) {
32940bb3eb3eSQu Wenruo 			btrfs_err(fs_info,
32950bb3eb3eSQu Wenruo 	"subpage sectorsize %u only supported read-only for page size %lu",
32960bb3eb3eSQu Wenruo 				sectorsize, PAGE_SIZE);
32970bb3eb3eSQu Wenruo 			err = -EINVAL;
32980bb3eb3eSQu Wenruo 			goto fail_alloc;
32990bb3eb3eSQu Wenruo 		}
33000bb3eb3eSQu Wenruo 	}
33010bb3eb3eSQu Wenruo 
33022a458198SEric Sandeen 	ret = btrfs_init_workqueues(fs_info, fs_devices);
33032a458198SEric Sandeen 	if (ret) {
33042a458198SEric Sandeen 		err = ret;
33050dc3b84aSJosef Bacik 		goto fail_sb_buffer;
33060dc3b84aSJosef Bacik 	}
33074543df7eSChris Mason 
33089e11ceeeSJan Kara 	sb->s_bdi->ra_pages *= btrfs_super_num_devices(disk_super);
33099e11ceeeSJan Kara 	sb->s_bdi->ra_pages = max(sb->s_bdi->ra_pages, SZ_4M / PAGE_SIZE);
33104575c9ccSChris Mason 
3311a061fc8dSChris Mason 	sb->s_blocksize = sectorsize;
3312a061fc8dSChris Mason 	sb->s_blocksize_bits = blksize_bits(sectorsize);
3313de37aa51SNikolay Borisov 	memcpy(&sb->s_uuid, fs_info->fs_devices->fsid, BTRFS_FSID_SIZE);
3314db94535dSChris Mason 
3315925baeddSChris Mason 	mutex_lock(&fs_info->chunk_mutex);
33166bccf3abSJeff Mahoney 	ret = btrfs_read_sys_array(fs_info);
3317925baeddSChris Mason 	mutex_unlock(&fs_info->chunk_mutex);
331884eed90fSChris Mason 	if (ret) {
331905135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read the system array: %d", ret);
33205d4f98a2SYan Zheng 		goto fail_sb_buffer;
332184eed90fSChris Mason 	}
33220b86a832SChris Mason 
332384234f3aSYan Zheng 	generation = btrfs_super_chunk_root_generation(disk_super);
3324581c1760SQu Wenruo 	level = btrfs_super_chunk_root_level(disk_super);
33250b86a832SChris Mason 
33262ff7e61eSJeff Mahoney 	chunk_root->node = read_tree_block(fs_info,
33270b86a832SChris Mason 					   btrfs_super_chunk_root(disk_super),
33281b7ec85eSJosef Bacik 					   BTRFS_CHUNK_TREE_OBJECTID,
3329581c1760SQu Wenruo 					   generation, level, NULL);
333064c043deSLiu Bo 	if (IS_ERR(chunk_root->node) ||
333164c043deSLiu Bo 	    !extent_buffer_uptodate(chunk_root->node)) {
333205135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read chunk root");
3333e5fffbacSchandan 		if (!IS_ERR(chunk_root->node))
3334e5fffbacSchandan 			free_extent_buffer(chunk_root->node);
333595ab1f64SZhao Lei 		chunk_root->node = NULL;
3336af31f5e5SChris Mason 		goto fail_tree_roots;
333783121942SDavid Woodhouse 	}
33385d4f98a2SYan Zheng 	btrfs_set_root_node(&chunk_root->root_item, chunk_root->node);
33395d4f98a2SYan Zheng 	chunk_root->commit_root = btrfs_root_node(chunk_root);
33400b86a832SChris Mason 
3341e17cade2SChris Mason 	read_extent_buffer(chunk_root->node, fs_info->chunk_tree_uuid,
3342c4ac7541SDavid Sterba 			   offsetof(struct btrfs_header, chunk_tree_uuid),
3343c4ac7541SDavid Sterba 			   BTRFS_UUID_SIZE);
3344e17cade2SChris Mason 
33455b4aacefSJeff Mahoney 	ret = btrfs_read_chunk_tree(fs_info);
33462b82032cSYan Zheng 	if (ret) {
334705135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read chunk tree: %d", ret);
3348af31f5e5SChris Mason 		goto fail_tree_roots;
33492b82032cSYan Zheng 	}
33500b86a832SChris Mason 
33518dabb742SStefan Behrens 	/*
3352bacce86aSAnand Jain 	 * At this point we know all the devices that make this filesystem,
3353bacce86aSAnand Jain 	 * including the seed devices but we don't know yet if the replace
3354bacce86aSAnand Jain 	 * target is required. So free devices that are not part of this
3355bacce86aSAnand Jain 	 * filesystem but skip the replace traget device which is checked
3356bacce86aSAnand Jain 	 * below in btrfs_init_dev_replace().
33578dabb742SStefan Behrens 	 */
3358bacce86aSAnand Jain 	btrfs_free_extra_devids(fs_devices);
3359a6b0d5c8SChris Mason 	if (!fs_devices->latest_bdev) {
336005135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read devices");
3361a6b0d5c8SChris Mason 		goto fail_tree_roots;
3362a6b0d5c8SChris Mason 	}
3363a6b0d5c8SChris Mason 
3364b8522a1eSNikolay Borisov 	ret = init_tree_roots(fs_info);
33654bbcaa64SEric Sandeen 	if (ret)
3366b8522a1eSNikolay Borisov 		goto fail_tree_roots;
33678929ecfaSYan, Zheng 
336875ec1db8SJosef Bacik 	/*
336973651042SNaohiro Aota 	 * Get zone type information of zoned block devices. This will also
337073651042SNaohiro Aota 	 * handle emulation of a zoned filesystem if a regular device has the
337173651042SNaohiro Aota 	 * zoned incompat feature flag set.
337273651042SNaohiro Aota 	 */
337373651042SNaohiro Aota 	ret = btrfs_get_dev_zone_info_all_devices(fs_info);
337473651042SNaohiro Aota 	if (ret) {
337573651042SNaohiro Aota 		btrfs_err(fs_info,
337673651042SNaohiro Aota 			  "zoned: failed to read device zone info: %d",
337773651042SNaohiro Aota 			  ret);
337873651042SNaohiro Aota 		goto fail_block_groups;
337973651042SNaohiro Aota 	}
338073651042SNaohiro Aota 
338173651042SNaohiro Aota 	/*
338275ec1db8SJosef Bacik 	 * If we have a uuid root and we're not being told to rescan we need to
338375ec1db8SJosef Bacik 	 * check the generation here so we can set the
338475ec1db8SJosef Bacik 	 * BTRFS_FS_UPDATE_UUID_TREE_GEN bit.  Otherwise we could commit the
338575ec1db8SJosef Bacik 	 * transaction during a balance or the log replay without updating the
338675ec1db8SJosef Bacik 	 * uuid generation, and then if we crash we would rescan the uuid tree,
338775ec1db8SJosef Bacik 	 * even though it was perfectly fine.
338875ec1db8SJosef Bacik 	 */
338975ec1db8SJosef Bacik 	if (fs_info->uuid_root && !btrfs_test_opt(fs_info, RESCAN_UUID_TREE) &&
339075ec1db8SJosef Bacik 	    fs_info->generation == btrfs_super_uuid_tree_generation(disk_super))
339175ec1db8SJosef Bacik 		set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
339275ec1db8SJosef Bacik 
3393cf90d884SQu Wenruo 	ret = btrfs_verify_dev_extents(fs_info);
3394cf90d884SQu Wenruo 	if (ret) {
3395cf90d884SQu Wenruo 		btrfs_err(fs_info,
3396cf90d884SQu Wenruo 			  "failed to verify dev extents against chunks: %d",
3397cf90d884SQu Wenruo 			  ret);
3398cf90d884SQu Wenruo 		goto fail_block_groups;
3399cf90d884SQu Wenruo 	}
340068310a5eSIlya Dryomov 	ret = btrfs_recover_balance(fs_info);
340168310a5eSIlya Dryomov 	if (ret) {
340205135f59SDavid Sterba 		btrfs_err(fs_info, "failed to recover balance: %d", ret);
340368310a5eSIlya Dryomov 		goto fail_block_groups;
340468310a5eSIlya Dryomov 	}
340568310a5eSIlya Dryomov 
3406733f4fbbSStefan Behrens 	ret = btrfs_init_dev_stats(fs_info);
3407733f4fbbSStefan Behrens 	if (ret) {
340805135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init dev_stats: %d", ret);
3409733f4fbbSStefan Behrens 		goto fail_block_groups;
3410733f4fbbSStefan Behrens 	}
3411733f4fbbSStefan Behrens 
34128dabb742SStefan Behrens 	ret = btrfs_init_dev_replace(fs_info);
34138dabb742SStefan Behrens 	if (ret) {
341405135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init dev_replace: %d", ret);
34158dabb742SStefan Behrens 		goto fail_block_groups;
34168dabb742SStefan Behrens 	}
34178dabb742SStefan Behrens 
3418b70f5097SNaohiro Aota 	ret = btrfs_check_zoned_mode(fs_info);
3419b70f5097SNaohiro Aota 	if (ret) {
3420b70f5097SNaohiro Aota 		btrfs_err(fs_info, "failed to initialize zoned mode: %d",
3421b70f5097SNaohiro Aota 			  ret);
3422b70f5097SNaohiro Aota 		goto fail_block_groups;
3423b70f5097SNaohiro Aota 	}
3424b70f5097SNaohiro Aota 
3425c6761a9eSAnand Jain 	ret = btrfs_sysfs_add_fsid(fs_devices);
3426b7c35e81SAnand Jain 	if (ret) {
342705135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init sysfs fsid interface: %d",
342805135f59SDavid Sterba 				ret);
3429b7c35e81SAnand Jain 		goto fail_block_groups;
3430b7c35e81SAnand Jain 	}
3431b7c35e81SAnand Jain 
343296f3136eSAnand Jain 	ret = btrfs_sysfs_add_mounted(fs_info);
34335ac1d209SJeff Mahoney 	if (ret) {
343405135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init sysfs interface: %d", ret);
3435b7c35e81SAnand Jain 		goto fail_fsdev_sysfs;
34365ac1d209SJeff Mahoney 	}
34375ac1d209SJeff Mahoney 
3438c59021f8Sliubo 	ret = btrfs_init_space_info(fs_info);
3439c59021f8Sliubo 	if (ret) {
344005135f59SDavid Sterba 		btrfs_err(fs_info, "failed to initialize space info: %d", ret);
34412365dd3cSAnand Jain 		goto fail_sysfs;
3442c59021f8Sliubo 	}
3443c59021f8Sliubo 
34445b4aacefSJeff Mahoney 	ret = btrfs_read_block_groups(fs_info);
34451b1d1f66SJosef Bacik 	if (ret) {
344605135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read block groups: %d", ret);
34472365dd3cSAnand Jain 		goto fail_sysfs;
34481b1d1f66SJosef Bacik 	}
34494330e183SQu Wenruo 
34506528b99dSAnand Jain 	if (!sb_rdonly(sb) && !btrfs_check_rw_degradable(fs_info, NULL)) {
345105135f59SDavid Sterba 		btrfs_warn(fs_info,
345252042d8eSAndrea Gelmini 		"writable mount is not allowed due to too many missing devices");
34532365dd3cSAnand Jain 		goto fail_sysfs;
3454292fd7fcSStefan Behrens 	}
34559078a3e1SChris Mason 
3456a74a4b97SChris Mason 	fs_info->cleaner_kthread = kthread_run(cleaner_kthread, tree_root,
3457a74a4b97SChris Mason 					       "btrfs-cleaner");
345857506d50SQinghuang Feng 	if (IS_ERR(fs_info->cleaner_kthread))
34592365dd3cSAnand Jain 		goto fail_sysfs;
3460a74a4b97SChris Mason 
3461a74a4b97SChris Mason 	fs_info->transaction_kthread = kthread_run(transaction_kthread,
3462a74a4b97SChris Mason 						   tree_root,
3463a74a4b97SChris Mason 						   "btrfs-transaction");
346457506d50SQinghuang Feng 	if (IS_ERR(fs_info->transaction_kthread))
34653f157a2fSChris Mason 		goto fail_cleaner;
3466a74a4b97SChris Mason 
3467583b7231SHans van Kranenburg 	if (!btrfs_test_opt(fs_info, NOSSD) &&
3468c289811cSChris Mason 	    !fs_info->fs_devices->rotating) {
3469583b7231SHans van Kranenburg 		btrfs_set_and_info(fs_info, SSD, "enabling ssd optimizations");
3470c289811cSChris Mason 	}
3471c289811cSChris Mason 
3472572d9ab7SDavid Sterba 	/*
347301327610SNicholas D Steeves 	 * Mount does not set all options immediately, we can do it now and do
3474572d9ab7SDavid Sterba 	 * not have to wait for transaction commit
3475572d9ab7SDavid Sterba 	 */
3476572d9ab7SDavid Sterba 	btrfs_apply_pending_changes(fs_info);
34773818aea2SQu Wenruo 
347821adbd5cSStefan Behrens #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
34790b246afaSJeff Mahoney 	if (btrfs_test_opt(fs_info, CHECK_INTEGRITY)) {
34802ff7e61eSJeff Mahoney 		ret = btrfsic_mount(fs_info, fs_devices,
34810b246afaSJeff Mahoney 				    btrfs_test_opt(fs_info,
348221adbd5cSStefan Behrens 					CHECK_INTEGRITY_INCLUDING_EXTENT_DATA) ?
348321adbd5cSStefan Behrens 				    1 : 0,
348421adbd5cSStefan Behrens 				    fs_info->check_integrity_print_mask);
348521adbd5cSStefan Behrens 		if (ret)
348605135f59SDavid Sterba 			btrfs_warn(fs_info,
348705135f59SDavid Sterba 				"failed to initialize integrity check module: %d",
348805135f59SDavid Sterba 				ret);
348921adbd5cSStefan Behrens 	}
349021adbd5cSStefan Behrens #endif
3491bcef60f2SArne Jansen 	ret = btrfs_read_qgroup_config(fs_info);
3492bcef60f2SArne Jansen 	if (ret)
3493bcef60f2SArne Jansen 		goto fail_trans_kthread;
349421adbd5cSStefan Behrens 
3495fd708b81SJosef Bacik 	if (btrfs_build_ref_tree(fs_info))
3496fd708b81SJosef Bacik 		btrfs_err(fs_info, "couldn't build ref tree");
3497fd708b81SJosef Bacik 
349896da0919SQu Wenruo 	/* do not make disk changes in broken FS or nologreplay is given */
349996da0919SQu Wenruo 	if (btrfs_super_log_root(disk_super) != 0 &&
35000b246afaSJeff Mahoney 	    !btrfs_test_opt(fs_info, NOLOGREPLAY)) {
3501e8294f2fSDavid Sterba 		btrfs_info(fs_info, "start tree-log replay");
350263443bf5SEric Sandeen 		ret = btrfs_replay_log(fs_info, fs_devices);
350379787eaaSJeff Mahoney 		if (ret) {
350463443bf5SEric Sandeen 			err = ret;
350528c16cbbSWang Shilong 			goto fail_qgroup;
3506e556ce2cSYan Zheng 		}
3507e02119d5SChris Mason 	}
35081a40e23bSZheng Yan 
350956e9357aSDavid Sterba 	fs_info->fs_root = btrfs_get_fs_root(fs_info, BTRFS_FS_TREE_OBJECTID, true);
35103140c9a3SDan Carpenter 	if (IS_ERR(fs_info->fs_root)) {
35113140c9a3SDan Carpenter 		err = PTR_ERR(fs_info->fs_root);
3512f50f4353SLiu Bo 		btrfs_warn(fs_info, "failed to read fs tree: %d", err);
3513315bf8efSJosef Bacik 		fs_info->fs_root = NULL;
3514bcef60f2SArne Jansen 		goto fail_qgroup;
35153140c9a3SDan Carpenter 	}
3516c289811cSChris Mason 
3517bc98a42cSDavid Howells 	if (sb_rdonly(sb))
35188cd29088SBoris Burkov 		goto clear_oneshot;
35192b6ba629SIlya Dryomov 
352044c0ca21SBoris Burkov 	ret = btrfs_start_pre_rw_mount(fs_info);
35212b6ba629SIlya Dryomov 	if (ret) {
35226bccf3abSJeff Mahoney 		close_ctree(fs_info);
35232b6ba629SIlya Dryomov 		return ret;
3524e3acc2a6SJosef Bacik 	}
3525b0643e59SDennis Zhou 	btrfs_discard_resume(fs_info);
3526b382a324SJan Schmidt 
352744c0ca21SBoris Burkov 	if (fs_info->uuid_root &&
352844c0ca21SBoris Burkov 	    (btrfs_test_opt(fs_info, RESCAN_UUID_TREE) ||
352944c0ca21SBoris Burkov 	     fs_info->generation != btrfs_super_uuid_tree_generation(disk_super))) {
353005135f59SDavid Sterba 		btrfs_info(fs_info, "checking UUID tree");
353170f80175SStefan Behrens 		ret = btrfs_check_uuid_tree(fs_info);
353270f80175SStefan Behrens 		if (ret) {
353305135f59SDavid Sterba 			btrfs_warn(fs_info,
353405135f59SDavid Sterba 				"failed to check the UUID tree: %d", ret);
35356bccf3abSJeff Mahoney 			close_ctree(fs_info);
353670f80175SStefan Behrens 			return ret;
353770f80175SStefan Behrens 		}
3538f7a81ea4SStefan Behrens 	}
353994846229SBoris Burkov 
3540afcdd129SJosef Bacik 	set_bit(BTRFS_FS_OPEN, &fs_info->flags);
354147ab2a6cSJosef Bacik 
35428cd29088SBoris Burkov clear_oneshot:
35438cd29088SBoris Burkov 	btrfs_clear_oneshot_options(fs_info);
3544ad2b2c80SAl Viro 	return 0;
354539279cc3SChris Mason 
3546bcef60f2SArne Jansen fail_qgroup:
3547bcef60f2SArne Jansen 	btrfs_free_qgroup_config(fs_info);
35487c2ca468SChris Mason fail_trans_kthread:
35497c2ca468SChris Mason 	kthread_stop(fs_info->transaction_kthread);
35502ff7e61eSJeff Mahoney 	btrfs_cleanup_transaction(fs_info);
3551faa2dbf0SJosef Bacik 	btrfs_free_fs_roots(fs_info);
35523f157a2fSChris Mason fail_cleaner:
3553a74a4b97SChris Mason 	kthread_stop(fs_info->cleaner_kthread);
35547c2ca468SChris Mason 
35557c2ca468SChris Mason 	/*
35567c2ca468SChris Mason 	 * make sure we're done with the btree inode before we stop our
35577c2ca468SChris Mason 	 * kthreads
35587c2ca468SChris Mason 	 */
35597c2ca468SChris Mason 	filemap_write_and_wait(fs_info->btree_inode->i_mapping);
35607c2ca468SChris Mason 
35612365dd3cSAnand Jain fail_sysfs:
35626618a59bSAnand Jain 	btrfs_sysfs_remove_mounted(fs_info);
35632365dd3cSAnand Jain 
3564b7c35e81SAnand Jain fail_fsdev_sysfs:
3565b7c35e81SAnand Jain 	btrfs_sysfs_remove_fsid(fs_info->fs_devices);
3566b7c35e81SAnand Jain 
35671b1d1f66SJosef Bacik fail_block_groups:
356854067ae9SJosef Bacik 	btrfs_put_block_group_cache(fs_info);
3569af31f5e5SChris Mason 
3570af31f5e5SChris Mason fail_tree_roots:
35719e3aa805SJosef Bacik 	if (fs_info->data_reloc_root)
35729e3aa805SJosef Bacik 		btrfs_drop_and_free_fs_root(fs_info, fs_info->data_reloc_root);
35734273eaffSAnand Jain 	free_root_pointers(fs_info, true);
35742b8195bbSMiao Xie 	invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
3575af31f5e5SChris Mason 
357639279cc3SChris Mason fail_sb_buffer:
35777abadb64SLiu Bo 	btrfs_stop_all_workers(fs_info);
35785cdd7db6SFilipe Manana 	btrfs_free_block_groups(fs_info);
357916cdcec7SMiao Xie fail_alloc:
3580586e46e2SIlya Dryomov 	btrfs_mapping_tree_free(&fs_info->mapping_tree);
3581586e46e2SIlya Dryomov 
35824543df7eSChris Mason 	iput(fs_info->btree_inode);
35837e662854SQinghuang Feng fail:
3584586e46e2SIlya Dryomov 	btrfs_close_devices(fs_info->fs_devices);
3585ad2b2c80SAl Viro 	return err;
3586eb60ceacSChris Mason }
3587663faf9fSMasami Hiramatsu ALLOW_ERROR_INJECTION(open_ctree, ERRNO);
3588eb60ceacSChris Mason 
3589314b6dd0SJohannes Thumshirn static void btrfs_end_super_write(struct bio *bio)
3590f2984462SChris Mason {
3591314b6dd0SJohannes Thumshirn 	struct btrfs_device *device = bio->bi_private;
3592314b6dd0SJohannes Thumshirn 	struct bio_vec *bvec;
3593314b6dd0SJohannes Thumshirn 	struct bvec_iter_all iter_all;
3594314b6dd0SJohannes Thumshirn 	struct page *page;
3595442a4f63SStefan Behrens 
3596314b6dd0SJohannes Thumshirn 	bio_for_each_segment_all(bvec, bio, iter_all) {
3597314b6dd0SJohannes Thumshirn 		page = bvec->bv_page;
3598314b6dd0SJohannes Thumshirn 
3599314b6dd0SJohannes Thumshirn 		if (bio->bi_status) {
3600fb456252SJeff Mahoney 			btrfs_warn_rl_in_rcu(device->fs_info,
3601314b6dd0SJohannes Thumshirn 				"lost page write due to IO error on %s (%d)",
3602314b6dd0SJohannes Thumshirn 				rcu_str_deref(device->name),
3603314b6dd0SJohannes Thumshirn 				blk_status_to_errno(bio->bi_status));
3604314b6dd0SJohannes Thumshirn 			ClearPageUptodate(page);
3605314b6dd0SJohannes Thumshirn 			SetPageError(page);
3606314b6dd0SJohannes Thumshirn 			btrfs_dev_stat_inc_and_print(device,
3607314b6dd0SJohannes Thumshirn 						     BTRFS_DEV_STAT_WRITE_ERRS);
3608314b6dd0SJohannes Thumshirn 		} else {
3609314b6dd0SJohannes Thumshirn 			SetPageUptodate(page);
3610f2984462SChris Mason 		}
3611314b6dd0SJohannes Thumshirn 
3612314b6dd0SJohannes Thumshirn 		put_page(page);
3613314b6dd0SJohannes Thumshirn 		unlock_page(page);
3614314b6dd0SJohannes Thumshirn 	}
3615314b6dd0SJohannes Thumshirn 
3616314b6dd0SJohannes Thumshirn 	bio_put(bio);
3617f2984462SChris Mason }
3618f2984462SChris Mason 
36198f32380dSJohannes Thumshirn struct btrfs_super_block *btrfs_read_dev_one_super(struct block_device *bdev,
36208f32380dSJohannes Thumshirn 						   int copy_num)
362129c36d72SAnand Jain {
362229c36d72SAnand Jain 	struct btrfs_super_block *super;
36238f32380dSJohannes Thumshirn 	struct page *page;
362412659251SNaohiro Aota 	u64 bytenr, bytenr_orig;
36258f32380dSJohannes Thumshirn 	struct address_space *mapping = bdev->bd_inode->i_mapping;
362612659251SNaohiro Aota 	int ret;
362729c36d72SAnand Jain 
362812659251SNaohiro Aota 	bytenr_orig = btrfs_sb_offset(copy_num);
362912659251SNaohiro Aota 	ret = btrfs_sb_log_location_bdev(bdev, copy_num, READ, &bytenr);
363012659251SNaohiro Aota 	if (ret == -ENOENT)
363112659251SNaohiro Aota 		return ERR_PTR(-EINVAL);
363212659251SNaohiro Aota 	else if (ret)
363312659251SNaohiro Aota 		return ERR_PTR(ret);
363412659251SNaohiro Aota 
363529c36d72SAnand Jain 	if (bytenr + BTRFS_SUPER_INFO_SIZE >= i_size_read(bdev->bd_inode))
36368f32380dSJohannes Thumshirn 		return ERR_PTR(-EINVAL);
363729c36d72SAnand Jain 
36388f32380dSJohannes Thumshirn 	page = read_cache_page_gfp(mapping, bytenr >> PAGE_SHIFT, GFP_NOFS);
36398f32380dSJohannes Thumshirn 	if (IS_ERR(page))
36408f32380dSJohannes Thumshirn 		return ERR_CAST(page);
364129c36d72SAnand Jain 
36428f32380dSJohannes Thumshirn 	super = page_address(page);
364396c2e067SAnand Jain 	if (btrfs_super_magic(super) != BTRFS_MAGIC) {
364496c2e067SAnand Jain 		btrfs_release_disk_super(super);
364596c2e067SAnand Jain 		return ERR_PTR(-ENODATA);
364696c2e067SAnand Jain 	}
364796c2e067SAnand Jain 
364812659251SNaohiro Aota 	if (btrfs_super_bytenr(super) != bytenr_orig) {
36498f32380dSJohannes Thumshirn 		btrfs_release_disk_super(super);
36508f32380dSJohannes Thumshirn 		return ERR_PTR(-EINVAL);
365129c36d72SAnand Jain 	}
365229c36d72SAnand Jain 
36538f32380dSJohannes Thumshirn 	return super;
365429c36d72SAnand Jain }
365529c36d72SAnand Jain 
365629c36d72SAnand Jain 
36578f32380dSJohannes Thumshirn struct btrfs_super_block *btrfs_read_dev_super(struct block_device *bdev)
3658a512bbf8SYan Zheng {
36598f32380dSJohannes Thumshirn 	struct btrfs_super_block *super, *latest = NULL;
3660a512bbf8SYan Zheng 	int i;
3661a512bbf8SYan Zheng 	u64 transid = 0;
3662a512bbf8SYan Zheng 
3663a512bbf8SYan Zheng 	/* we would like to check all the supers, but that would make
3664a512bbf8SYan Zheng 	 * a btrfs mount succeed after a mkfs from a different FS.
3665a512bbf8SYan Zheng 	 * So, we need to add a special mount option to scan for
3666a512bbf8SYan Zheng 	 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
3667a512bbf8SYan Zheng 	 */
3668a512bbf8SYan Zheng 	for (i = 0; i < 1; i++) {
36698f32380dSJohannes Thumshirn 		super = btrfs_read_dev_one_super(bdev, i);
36708f32380dSJohannes Thumshirn 		if (IS_ERR(super))
3671a512bbf8SYan Zheng 			continue;
3672a512bbf8SYan Zheng 
3673a512bbf8SYan Zheng 		if (!latest || btrfs_super_generation(super) > transid) {
36748f32380dSJohannes Thumshirn 			if (latest)
36758f32380dSJohannes Thumshirn 				btrfs_release_disk_super(super);
36768f32380dSJohannes Thumshirn 
36778f32380dSJohannes Thumshirn 			latest = super;
3678a512bbf8SYan Zheng 			transid = btrfs_super_generation(super);
3679a512bbf8SYan Zheng 		}
3680a512bbf8SYan Zheng 	}
368192fc03fbSAnand Jain 
36828f32380dSJohannes Thumshirn 	return super;
3683a512bbf8SYan Zheng }
3684a512bbf8SYan Zheng 
36854eedeb75SHisashi Hifumi /*
3686abbb3b8eSDavid Sterba  * Write superblock @sb to the @device. Do not wait for completion, all the
3687314b6dd0SJohannes Thumshirn  * pages we use for writing are locked.
36884eedeb75SHisashi Hifumi  *
3689abbb3b8eSDavid Sterba  * Write @max_mirrors copies of the superblock, where 0 means default that fit
3690abbb3b8eSDavid Sterba  * the expected device size at commit time. Note that max_mirrors must be
3691abbb3b8eSDavid Sterba  * same for write and wait phases.
36924eedeb75SHisashi Hifumi  *
3693314b6dd0SJohannes Thumshirn  * Return number of errors when page is not found or submission fails.
36944eedeb75SHisashi Hifumi  */
3695a512bbf8SYan Zheng static int write_dev_supers(struct btrfs_device *device,
3696abbb3b8eSDavid Sterba 			    struct btrfs_super_block *sb, int max_mirrors)
3697a512bbf8SYan Zheng {
3698d5178578SJohannes Thumshirn 	struct btrfs_fs_info *fs_info = device->fs_info;
3699314b6dd0SJohannes Thumshirn 	struct address_space *mapping = device->bdev->bd_inode->i_mapping;
3700d5178578SJohannes Thumshirn 	SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
3701a512bbf8SYan Zheng 	int i;
3702a512bbf8SYan Zheng 	int errors = 0;
370312659251SNaohiro Aota 	int ret;
370412659251SNaohiro Aota 	u64 bytenr, bytenr_orig;
3705a512bbf8SYan Zheng 
3706a512bbf8SYan Zheng 	if (max_mirrors == 0)
3707a512bbf8SYan Zheng 		max_mirrors = BTRFS_SUPER_MIRROR_MAX;
3708a512bbf8SYan Zheng 
3709d5178578SJohannes Thumshirn 	shash->tfm = fs_info->csum_shash;
3710d5178578SJohannes Thumshirn 
3711a512bbf8SYan Zheng 	for (i = 0; i < max_mirrors; i++) {
3712314b6dd0SJohannes Thumshirn 		struct page *page;
3713314b6dd0SJohannes Thumshirn 		struct bio *bio;
3714314b6dd0SJohannes Thumshirn 		struct btrfs_super_block *disk_super;
3715314b6dd0SJohannes Thumshirn 
371612659251SNaohiro Aota 		bytenr_orig = btrfs_sb_offset(i);
371712659251SNaohiro Aota 		ret = btrfs_sb_log_location(device, i, WRITE, &bytenr);
371812659251SNaohiro Aota 		if (ret == -ENOENT) {
371912659251SNaohiro Aota 			continue;
372012659251SNaohiro Aota 		} else if (ret < 0) {
372112659251SNaohiro Aota 			btrfs_err(device->fs_info,
372212659251SNaohiro Aota 				"couldn't get super block location for mirror %d",
372312659251SNaohiro Aota 				i);
372412659251SNaohiro Aota 			errors++;
372512659251SNaohiro Aota 			continue;
372612659251SNaohiro Aota 		}
3727935e5cc9SMiao Xie 		if (bytenr + BTRFS_SUPER_INFO_SIZE >=
3728935e5cc9SMiao Xie 		    device->commit_total_bytes)
3729a512bbf8SYan Zheng 			break;
3730a512bbf8SYan Zheng 
373112659251SNaohiro Aota 		btrfs_set_super_bytenr(sb, bytenr_orig);
3732a512bbf8SYan Zheng 
3733fd08001fSEric Biggers 		crypto_shash_digest(shash, (const char *)sb + BTRFS_CSUM_SIZE,
3734fd08001fSEric Biggers 				    BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE,
3735fd08001fSEric Biggers 				    sb->csum);
3736a512bbf8SYan Zheng 
3737314b6dd0SJohannes Thumshirn 		page = find_or_create_page(mapping, bytenr >> PAGE_SHIFT,
3738314b6dd0SJohannes Thumshirn 					   GFP_NOFS);
3739314b6dd0SJohannes Thumshirn 		if (!page) {
3740fb456252SJeff Mahoney 			btrfs_err(device->fs_info,
3741314b6dd0SJohannes Thumshirn 			    "couldn't get super block page for bytenr %llu",
3742f14d104dSDavid Sterba 			    bytenr);
3743634554dcSJosef Bacik 			errors++;
3744634554dcSJosef Bacik 			continue;
3745634554dcSJosef Bacik 		}
3746634554dcSJosef Bacik 
3747314b6dd0SJohannes Thumshirn 		/* Bump the refcount for wait_dev_supers() */
3748314b6dd0SJohannes Thumshirn 		get_page(page);
3749a512bbf8SYan Zheng 
3750314b6dd0SJohannes Thumshirn 		disk_super = page_address(page);
3751314b6dd0SJohannes Thumshirn 		memcpy(disk_super, sb, BTRFS_SUPER_INFO_SIZE);
3752a512bbf8SYan Zheng 
3753387125fcSChris Mason 		/*
3754314b6dd0SJohannes Thumshirn 		 * Directly use bios here instead of relying on the page cache
3755314b6dd0SJohannes Thumshirn 		 * to do I/O, so we don't lose the ability to do integrity
3756314b6dd0SJohannes Thumshirn 		 * checking.
3757387125fcSChris Mason 		 */
3758314b6dd0SJohannes Thumshirn 		bio = bio_alloc(GFP_NOFS, 1);
3759314b6dd0SJohannes Thumshirn 		bio_set_dev(bio, device->bdev);
3760314b6dd0SJohannes Thumshirn 		bio->bi_iter.bi_sector = bytenr >> SECTOR_SHIFT;
3761314b6dd0SJohannes Thumshirn 		bio->bi_private = device;
3762314b6dd0SJohannes Thumshirn 		bio->bi_end_io = btrfs_end_super_write;
3763314b6dd0SJohannes Thumshirn 		__bio_add_page(bio, page, BTRFS_SUPER_INFO_SIZE,
3764314b6dd0SJohannes Thumshirn 			       offset_in_page(bytenr));
3765314b6dd0SJohannes Thumshirn 
3766314b6dd0SJohannes Thumshirn 		/*
3767314b6dd0SJohannes Thumshirn 		 * We FUA only the first super block.  The others we allow to
3768314b6dd0SJohannes Thumshirn 		 * go down lazy and there's a short window where the on-disk
3769314b6dd0SJohannes Thumshirn 		 * copies might still contain the older version.
3770314b6dd0SJohannes Thumshirn 		 */
3771314b6dd0SJohannes Thumshirn 		bio->bi_opf = REQ_OP_WRITE | REQ_SYNC | REQ_META | REQ_PRIO;
37721b9e619cSOmar Sandoval 		if (i == 0 && !btrfs_test_opt(device->fs_info, NOBARRIER))
3773314b6dd0SJohannes Thumshirn 			bio->bi_opf |= REQ_FUA;
3774314b6dd0SJohannes Thumshirn 
3775314b6dd0SJohannes Thumshirn 		btrfsic_submit_bio(bio);
377612659251SNaohiro Aota 		btrfs_advance_sb_log(device, i);
3777a512bbf8SYan Zheng 	}
3778a512bbf8SYan Zheng 	return errors < i ? 0 : -1;
3779a512bbf8SYan Zheng }
3780a512bbf8SYan Zheng 
3781387125fcSChris Mason /*
3782abbb3b8eSDavid Sterba  * Wait for write completion of superblocks done by write_dev_supers,
3783abbb3b8eSDavid Sterba  * @max_mirrors same for write and wait phases.
3784abbb3b8eSDavid Sterba  *
3785314b6dd0SJohannes Thumshirn  * Return number of errors when page is not found or not marked up to
3786abbb3b8eSDavid Sterba  * date.
3787abbb3b8eSDavid Sterba  */
3788abbb3b8eSDavid Sterba static int wait_dev_supers(struct btrfs_device *device, int max_mirrors)
3789abbb3b8eSDavid Sterba {
3790abbb3b8eSDavid Sterba 	int i;
3791abbb3b8eSDavid Sterba 	int errors = 0;
3792b6a535faSHoward McLauchlan 	bool primary_failed = false;
379312659251SNaohiro Aota 	int ret;
3794abbb3b8eSDavid Sterba 	u64 bytenr;
3795abbb3b8eSDavid Sterba 
3796abbb3b8eSDavid Sterba 	if (max_mirrors == 0)
3797abbb3b8eSDavid Sterba 		max_mirrors = BTRFS_SUPER_MIRROR_MAX;
3798abbb3b8eSDavid Sterba 
3799abbb3b8eSDavid Sterba 	for (i = 0; i < max_mirrors; i++) {
3800314b6dd0SJohannes Thumshirn 		struct page *page;
3801314b6dd0SJohannes Thumshirn 
380212659251SNaohiro Aota 		ret = btrfs_sb_log_location(device, i, READ, &bytenr);
380312659251SNaohiro Aota 		if (ret == -ENOENT) {
380412659251SNaohiro Aota 			break;
380512659251SNaohiro Aota 		} else if (ret < 0) {
380612659251SNaohiro Aota 			errors++;
380712659251SNaohiro Aota 			if (i == 0)
380812659251SNaohiro Aota 				primary_failed = true;
380912659251SNaohiro Aota 			continue;
381012659251SNaohiro Aota 		}
3811abbb3b8eSDavid Sterba 		if (bytenr + BTRFS_SUPER_INFO_SIZE >=
3812abbb3b8eSDavid Sterba 		    device->commit_total_bytes)
3813abbb3b8eSDavid Sterba 			break;
3814abbb3b8eSDavid Sterba 
3815314b6dd0SJohannes Thumshirn 		page = find_get_page(device->bdev->bd_inode->i_mapping,
3816314b6dd0SJohannes Thumshirn 				     bytenr >> PAGE_SHIFT);
3817314b6dd0SJohannes Thumshirn 		if (!page) {
3818abbb3b8eSDavid Sterba 			errors++;
3819b6a535faSHoward McLauchlan 			if (i == 0)
3820b6a535faSHoward McLauchlan 				primary_failed = true;
3821abbb3b8eSDavid Sterba 			continue;
3822abbb3b8eSDavid Sterba 		}
3823314b6dd0SJohannes Thumshirn 		/* Page is submitted locked and unlocked once the IO completes */
3824314b6dd0SJohannes Thumshirn 		wait_on_page_locked(page);
3825314b6dd0SJohannes Thumshirn 		if (PageError(page)) {
3826abbb3b8eSDavid Sterba 			errors++;
3827b6a535faSHoward McLauchlan 			if (i == 0)
3828b6a535faSHoward McLauchlan 				primary_failed = true;
3829b6a535faSHoward McLauchlan 		}
3830abbb3b8eSDavid Sterba 
3831314b6dd0SJohannes Thumshirn 		/* Drop our reference */
3832314b6dd0SJohannes Thumshirn 		put_page(page);
3833abbb3b8eSDavid Sterba 
3834314b6dd0SJohannes Thumshirn 		/* Drop the reference from the writing run */
3835314b6dd0SJohannes Thumshirn 		put_page(page);
3836abbb3b8eSDavid Sterba 	}
3837abbb3b8eSDavid Sterba 
3838b6a535faSHoward McLauchlan 	/* log error, force error return */
3839b6a535faSHoward McLauchlan 	if (primary_failed) {
3840b6a535faSHoward McLauchlan 		btrfs_err(device->fs_info, "error writing primary super block to device %llu",
3841b6a535faSHoward McLauchlan 			  device->devid);
3842b6a535faSHoward McLauchlan 		return -1;
3843b6a535faSHoward McLauchlan 	}
3844b6a535faSHoward McLauchlan 
3845abbb3b8eSDavid Sterba 	return errors < i ? 0 : -1;
3846abbb3b8eSDavid Sterba }
3847abbb3b8eSDavid Sterba 
3848abbb3b8eSDavid Sterba /*
3849387125fcSChris Mason  * endio for the write_dev_flush, this will wake anyone waiting
3850387125fcSChris Mason  * for the barrier when it is done
3851387125fcSChris Mason  */
38524246a0b6SChristoph Hellwig static void btrfs_end_empty_barrier(struct bio *bio)
3853387125fcSChris Mason {
3854387125fcSChris Mason 	complete(bio->bi_private);
3855387125fcSChris Mason }
3856387125fcSChris Mason 
3857387125fcSChris Mason /*
38584fc6441aSAnand Jain  * Submit a flush request to the device if it supports it. Error handling is
38594fc6441aSAnand Jain  * done in the waiting counterpart.
3860387125fcSChris Mason  */
38614fc6441aSAnand Jain static void write_dev_flush(struct btrfs_device *device)
3862387125fcSChris Mason {
3863c2a9c7abSAnand Jain 	struct request_queue *q = bdev_get_queue(device->bdev);
3864e0ae9994SDavid Sterba 	struct bio *bio = device->flush_bio;
3865387125fcSChris Mason 
3866c2a9c7abSAnand Jain 	if (!test_bit(QUEUE_FLAG_WC, &q->queue_flags))
38674fc6441aSAnand Jain 		return;
3868387125fcSChris Mason 
3869e0ae9994SDavid Sterba 	bio_reset(bio);
3870387125fcSChris Mason 	bio->bi_end_io = btrfs_end_empty_barrier;
387174d46992SChristoph Hellwig 	bio_set_dev(bio, device->bdev);
38728d910125SJan Kara 	bio->bi_opf = REQ_OP_WRITE | REQ_SYNC | REQ_PREFLUSH;
3873387125fcSChris Mason 	init_completion(&device->flush_wait);
3874387125fcSChris Mason 	bio->bi_private = &device->flush_wait;
3875387125fcSChris Mason 
387643a01111SLu Fengqi 	btrfsic_submit_bio(bio);
38771c3063b6SAnand Jain 	set_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state);
38784fc6441aSAnand Jain }
3879387125fcSChris Mason 
38804fc6441aSAnand Jain /*
38814fc6441aSAnand Jain  * If the flush bio has been submitted by write_dev_flush, wait for it.
38824fc6441aSAnand Jain  */
38838c27cb35SLinus Torvalds static blk_status_t wait_dev_flush(struct btrfs_device *device)
38844fc6441aSAnand Jain {
38854fc6441aSAnand Jain 	struct bio *bio = device->flush_bio;
38864fc6441aSAnand Jain 
38871c3063b6SAnand Jain 	if (!test_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state))
388858efbc9fSOmar Sandoval 		return BLK_STS_OK;
38894fc6441aSAnand Jain 
38901c3063b6SAnand Jain 	clear_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state);
38912980d574SDavid Sterba 	wait_for_completion_io(&device->flush_wait);
38924fc6441aSAnand Jain 
38938c27cb35SLinus Torvalds 	return bio->bi_status;
3894387125fcSChris Mason }
3895387125fcSChris Mason 
3896d10b82feSQu Wenruo static int check_barrier_error(struct btrfs_fs_info *fs_info)
3897401b41e5SAnand Jain {
38986528b99dSAnand Jain 	if (!btrfs_check_rw_degradable(fs_info, NULL))
3899401b41e5SAnand Jain 		return -EIO;
3900387125fcSChris Mason 	return 0;
3901387125fcSChris Mason }
3902387125fcSChris Mason 
3903387125fcSChris Mason /*
3904387125fcSChris Mason  * send an empty flush down to each device in parallel,
3905387125fcSChris Mason  * then wait for them
3906387125fcSChris Mason  */
3907387125fcSChris Mason static int barrier_all_devices(struct btrfs_fs_info *info)
3908387125fcSChris Mason {
3909387125fcSChris Mason 	struct list_head *head;
3910387125fcSChris Mason 	struct btrfs_device *dev;
39115af3e8ccSStefan Behrens 	int errors_wait = 0;
39124e4cbee9SChristoph Hellwig 	blk_status_t ret;
3913387125fcSChris Mason 
39141538e6c5SDavid Sterba 	lockdep_assert_held(&info->fs_devices->device_list_mutex);
3915387125fcSChris Mason 	/* send down all the barriers */
3916387125fcSChris Mason 	head = &info->fs_devices->devices;
39171538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
3918e6e674bdSAnand Jain 		if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
3919f88ba6a2SHidetoshi Seto 			continue;
3920cea7c8bfSAnand Jain 		if (!dev->bdev)
3921387125fcSChris Mason 			continue;
3922e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
3923ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
3924387125fcSChris Mason 			continue;
3925387125fcSChris Mason 
39264fc6441aSAnand Jain 		write_dev_flush(dev);
392758efbc9fSOmar Sandoval 		dev->last_flush_error = BLK_STS_OK;
3928387125fcSChris Mason 	}
3929387125fcSChris Mason 
3930387125fcSChris Mason 	/* wait for all the barriers */
39311538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
3932e6e674bdSAnand Jain 		if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
3933f88ba6a2SHidetoshi Seto 			continue;
3934387125fcSChris Mason 		if (!dev->bdev) {
39355af3e8ccSStefan Behrens 			errors_wait++;
3936387125fcSChris Mason 			continue;
3937387125fcSChris Mason 		}
3938e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
3939ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
3940387125fcSChris Mason 			continue;
3941387125fcSChris Mason 
39424fc6441aSAnand Jain 		ret = wait_dev_flush(dev);
3943401b41e5SAnand Jain 		if (ret) {
3944401b41e5SAnand Jain 			dev->last_flush_error = ret;
394566b4993eSDavid Sterba 			btrfs_dev_stat_inc_and_print(dev,
394666b4993eSDavid Sterba 					BTRFS_DEV_STAT_FLUSH_ERRS);
39475af3e8ccSStefan Behrens 			errors_wait++;
3948387125fcSChris Mason 		}
3949401b41e5SAnand Jain 	}
3950401b41e5SAnand Jain 
3951cea7c8bfSAnand Jain 	if (errors_wait) {
3952401b41e5SAnand Jain 		/*
3953401b41e5SAnand Jain 		 * At some point we need the status of all disks
3954401b41e5SAnand Jain 		 * to arrive at the volume status. So error checking
3955401b41e5SAnand Jain 		 * is being pushed to a separate loop.
3956401b41e5SAnand Jain 		 */
3957d10b82feSQu Wenruo 		return check_barrier_error(info);
3958401b41e5SAnand Jain 	}
3959387125fcSChris Mason 	return 0;
3960387125fcSChris Mason }
3961387125fcSChris Mason 
3962943c6e99SZhao Lei int btrfs_get_num_tolerated_disk_barrier_failures(u64 flags)
3963943c6e99SZhao Lei {
39648789f4feSZhao Lei 	int raid_type;
39658789f4feSZhao Lei 	int min_tolerated = INT_MAX;
3966943c6e99SZhao Lei 
39678789f4feSZhao Lei 	if ((flags & BTRFS_BLOCK_GROUP_PROFILE_MASK) == 0 ||
39688789f4feSZhao Lei 	    (flags & BTRFS_AVAIL_ALLOC_BIT_SINGLE))
39698c3e3582SDavid Sterba 		min_tolerated = min_t(int, min_tolerated,
39708789f4feSZhao Lei 				    btrfs_raid_array[BTRFS_RAID_SINGLE].
39718789f4feSZhao Lei 				    tolerated_failures);
3972943c6e99SZhao Lei 
39738789f4feSZhao Lei 	for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) {
39748789f4feSZhao Lei 		if (raid_type == BTRFS_RAID_SINGLE)
39758789f4feSZhao Lei 			continue;
397641a6e891SAnand Jain 		if (!(flags & btrfs_raid_array[raid_type].bg_flag))
39778789f4feSZhao Lei 			continue;
39788c3e3582SDavid Sterba 		min_tolerated = min_t(int, min_tolerated,
39798789f4feSZhao Lei 				    btrfs_raid_array[raid_type].
39808789f4feSZhao Lei 				    tolerated_failures);
39818789f4feSZhao Lei 	}
3982943c6e99SZhao Lei 
39838789f4feSZhao Lei 	if (min_tolerated == INT_MAX) {
3984ab8d0fc4SJeff Mahoney 		pr_warn("BTRFS: unknown raid flag: %llu", flags);
39858789f4feSZhao Lei 		min_tolerated = 0;
39868789f4feSZhao Lei 	}
39878789f4feSZhao Lei 
39888789f4feSZhao Lei 	return min_tolerated;
3989943c6e99SZhao Lei }
3990943c6e99SZhao Lei 
3991eece6a9cSDavid Sterba int write_all_supers(struct btrfs_fs_info *fs_info, int max_mirrors)
3992f2984462SChris Mason {
3993e5e9a520SChris Mason 	struct list_head *head;
3994f2984462SChris Mason 	struct btrfs_device *dev;
3995a061fc8dSChris Mason 	struct btrfs_super_block *sb;
3996f2984462SChris Mason 	struct btrfs_dev_item *dev_item;
3997f2984462SChris Mason 	int ret;
3998f2984462SChris Mason 	int do_barriers;
3999a236aed1SChris Mason 	int max_errors;
4000a236aed1SChris Mason 	int total_errors = 0;
4001a061fc8dSChris Mason 	u64 flags;
4002f2984462SChris Mason 
40030b246afaSJeff Mahoney 	do_barriers = !btrfs_test_opt(fs_info, NOBARRIER);
4004fed3b381SLiu Bo 
4005fed3b381SLiu Bo 	/*
4006fed3b381SLiu Bo 	 * max_mirrors == 0 indicates we're from commit_transaction,
4007fed3b381SLiu Bo 	 * not from fsync where the tree roots in fs_info have not
4008fed3b381SLiu Bo 	 * been consistent on disk.
4009fed3b381SLiu Bo 	 */
4010fed3b381SLiu Bo 	if (max_mirrors == 0)
40110b246afaSJeff Mahoney 		backup_super_roots(fs_info);
4012f2984462SChris Mason 
40130b246afaSJeff Mahoney 	sb = fs_info->super_for_commit;
4014a061fc8dSChris Mason 	dev_item = &sb->dev_item;
4015e5e9a520SChris Mason 
40160b246afaSJeff Mahoney 	mutex_lock(&fs_info->fs_devices->device_list_mutex);
40170b246afaSJeff Mahoney 	head = &fs_info->fs_devices->devices;
40180b246afaSJeff Mahoney 	max_errors = btrfs_super_num_devices(fs_info->super_copy) - 1;
4019387125fcSChris Mason 
40205af3e8ccSStefan Behrens 	if (do_barriers) {
40210b246afaSJeff Mahoney 		ret = barrier_all_devices(fs_info);
40225af3e8ccSStefan Behrens 		if (ret) {
40235af3e8ccSStefan Behrens 			mutex_unlock(
40240b246afaSJeff Mahoney 				&fs_info->fs_devices->device_list_mutex);
40250b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret,
40265af3e8ccSStefan Behrens 					      "errors while submitting device barriers.");
40275af3e8ccSStefan Behrens 			return ret;
40285af3e8ccSStefan Behrens 		}
40295af3e8ccSStefan Behrens 	}
4030387125fcSChris Mason 
40311538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
4032dfe25020SChris Mason 		if (!dev->bdev) {
4033dfe25020SChris Mason 			total_errors++;
4034dfe25020SChris Mason 			continue;
4035dfe25020SChris Mason 		}
4036e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
4037ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
4038dfe25020SChris Mason 			continue;
4039dfe25020SChris Mason 
40402b82032cSYan Zheng 		btrfs_set_stack_device_generation(dev_item, 0);
4041a061fc8dSChris Mason 		btrfs_set_stack_device_type(dev_item, dev->type);
4042a061fc8dSChris Mason 		btrfs_set_stack_device_id(dev_item, dev->devid);
40437df69d3eSMiao Xie 		btrfs_set_stack_device_total_bytes(dev_item,
4044935e5cc9SMiao Xie 						   dev->commit_total_bytes);
4045ce7213c7SMiao Xie 		btrfs_set_stack_device_bytes_used(dev_item,
4046ce7213c7SMiao Xie 						  dev->commit_bytes_used);
4047a061fc8dSChris Mason 		btrfs_set_stack_device_io_align(dev_item, dev->io_align);
4048a061fc8dSChris Mason 		btrfs_set_stack_device_io_width(dev_item, dev->io_width);
4049a061fc8dSChris Mason 		btrfs_set_stack_device_sector_size(dev_item, dev->sector_size);
4050a061fc8dSChris Mason 		memcpy(dev_item->uuid, dev->uuid, BTRFS_UUID_SIZE);
40517239ff4bSNikolay Borisov 		memcpy(dev_item->fsid, dev->fs_devices->metadata_uuid,
40527239ff4bSNikolay Borisov 		       BTRFS_FSID_SIZE);
4053a512bbf8SYan Zheng 
4054a061fc8dSChris Mason 		flags = btrfs_super_flags(sb);
4055a061fc8dSChris Mason 		btrfs_set_super_flags(sb, flags | BTRFS_HEADER_FLAG_WRITTEN);
4056f2984462SChris Mason 
405775cb857dSQu Wenruo 		ret = btrfs_validate_write_super(fs_info, sb);
405875cb857dSQu Wenruo 		if (ret < 0) {
405975cb857dSQu Wenruo 			mutex_unlock(&fs_info->fs_devices->device_list_mutex);
406075cb857dSQu Wenruo 			btrfs_handle_fs_error(fs_info, -EUCLEAN,
406175cb857dSQu Wenruo 				"unexpected superblock corruption detected");
406275cb857dSQu Wenruo 			return -EUCLEAN;
406375cb857dSQu Wenruo 		}
406475cb857dSQu Wenruo 
4065abbb3b8eSDavid Sterba 		ret = write_dev_supers(dev, sb, max_mirrors);
4066a236aed1SChris Mason 		if (ret)
4067a236aed1SChris Mason 			total_errors++;
4068f2984462SChris Mason 	}
4069a236aed1SChris Mason 	if (total_errors > max_errors) {
40700b246afaSJeff Mahoney 		btrfs_err(fs_info, "%d errors while writing supers",
4071d397712bSChris Mason 			  total_errors);
40720b246afaSJeff Mahoney 		mutex_unlock(&fs_info->fs_devices->device_list_mutex);
407379787eaaSJeff Mahoney 
40749d565ba4SStefan Behrens 		/* FUA is masked off if unsupported and can't be the reason */
40750b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, -EIO,
40760b246afaSJeff Mahoney 				      "%d errors while writing supers",
40770b246afaSJeff Mahoney 				      total_errors);
40789d565ba4SStefan Behrens 		return -EIO;
4079a236aed1SChris Mason 	}
4080f2984462SChris Mason 
4081a512bbf8SYan Zheng 	total_errors = 0;
40821538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
4083dfe25020SChris Mason 		if (!dev->bdev)
4084dfe25020SChris Mason 			continue;
4085e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
4086ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
4087dfe25020SChris Mason 			continue;
4088dfe25020SChris Mason 
4089abbb3b8eSDavid Sterba 		ret = wait_dev_supers(dev, max_mirrors);
4090a512bbf8SYan Zheng 		if (ret)
40911259ab75SChris Mason 			total_errors++;
4092f2984462SChris Mason 	}
40930b246afaSJeff Mahoney 	mutex_unlock(&fs_info->fs_devices->device_list_mutex);
4094a236aed1SChris Mason 	if (total_errors > max_errors) {
40950b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, -EIO,
40960b246afaSJeff Mahoney 				      "%d errors while writing supers",
40970b246afaSJeff Mahoney 				      total_errors);
409879787eaaSJeff Mahoney 		return -EIO;
4099a236aed1SChris Mason 	}
4100f2984462SChris Mason 	return 0;
4101f2984462SChris Mason }
4102f2984462SChris Mason 
4103cb517eabSMiao Xie /* Drop a fs root from the radix tree and free it. */
4104cb517eabSMiao Xie void btrfs_drop_and_free_fs_root(struct btrfs_fs_info *fs_info,
4105cb517eabSMiao Xie 				  struct btrfs_root *root)
41062619ba1fSChris Mason {
41074785e24fSJosef Bacik 	bool drop_ref = false;
41084785e24fSJosef Bacik 
41094df27c4dSYan, Zheng 	spin_lock(&fs_info->fs_roots_radix_lock);
41102619ba1fSChris Mason 	radix_tree_delete(&fs_info->fs_roots_radix,
41112619ba1fSChris Mason 			  (unsigned long)root->root_key.objectid);
4112af01d2e5SJosef Bacik 	if (test_and_clear_bit(BTRFS_ROOT_IN_RADIX, &root->state))
41134785e24fSJosef Bacik 		drop_ref = true;
41144df27c4dSYan, Zheng 	spin_unlock(&fs_info->fs_roots_radix_lock);
411576dda93cSYan, Zheng 
41161c1ea4f7SLiu Bo 	if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {
4117ef67963dSJosef Bacik 		ASSERT(root->log_root == NULL);
41181c1ea4f7SLiu Bo 		if (root->reloc_root) {
411900246528SJosef Bacik 			btrfs_put_root(root->reloc_root);
41201c1ea4f7SLiu Bo 			root->reloc_root = NULL;
41211c1ea4f7SLiu Bo 		}
41221c1ea4f7SLiu Bo 	}
41233321719eSLiu Bo 
41244785e24fSJosef Bacik 	if (drop_ref)
412500246528SJosef Bacik 		btrfs_put_root(root);
41262619ba1fSChris Mason }
41272619ba1fSChris Mason 
4128c146afadSYan Zheng int btrfs_cleanup_fs_roots(struct btrfs_fs_info *fs_info)
4129c146afadSYan Zheng {
4130c146afadSYan Zheng 	u64 root_objectid = 0;
4131c146afadSYan Zheng 	struct btrfs_root *gang[8];
413265d33fd7SQu Wenruo 	int i = 0;
413365d33fd7SQu Wenruo 	int err = 0;
413465d33fd7SQu Wenruo 	unsigned int ret = 0;
4135c146afadSYan Zheng 
4136c146afadSYan Zheng 	while (1) {
4137efc34534SJosef Bacik 		spin_lock(&fs_info->fs_roots_radix_lock);
4138c146afadSYan Zheng 		ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
4139c146afadSYan Zheng 					     (void **)gang, root_objectid,
4140c146afadSYan Zheng 					     ARRAY_SIZE(gang));
414165d33fd7SQu Wenruo 		if (!ret) {
4142efc34534SJosef Bacik 			spin_unlock(&fs_info->fs_roots_radix_lock);
4143c146afadSYan Zheng 			break;
414465d33fd7SQu Wenruo 		}
41455d4f98a2SYan Zheng 		root_objectid = gang[ret - 1]->root_key.objectid + 1;
414666b4ffd1SJosef Bacik 
414765d33fd7SQu Wenruo 		for (i = 0; i < ret; i++) {
414865d33fd7SQu Wenruo 			/* Avoid to grab roots in dead_roots */
414965d33fd7SQu Wenruo 			if (btrfs_root_refs(&gang[i]->root_item) == 0) {
415065d33fd7SQu Wenruo 				gang[i] = NULL;
415165d33fd7SQu Wenruo 				continue;
415265d33fd7SQu Wenruo 			}
415365d33fd7SQu Wenruo 			/* grab all the search result for later use */
415400246528SJosef Bacik 			gang[i] = btrfs_grab_root(gang[i]);
415565d33fd7SQu Wenruo 		}
4156efc34534SJosef Bacik 		spin_unlock(&fs_info->fs_roots_radix_lock);
415765d33fd7SQu Wenruo 
415865d33fd7SQu Wenruo 		for (i = 0; i < ret; i++) {
415965d33fd7SQu Wenruo 			if (!gang[i])
416065d33fd7SQu Wenruo 				continue;
4161c146afadSYan Zheng 			root_objectid = gang[i]->root_key.objectid;
416266b4ffd1SJosef Bacik 			err = btrfs_orphan_cleanup(gang[i]);
416366b4ffd1SJosef Bacik 			if (err)
416465d33fd7SQu Wenruo 				break;
416500246528SJosef Bacik 			btrfs_put_root(gang[i]);
4166c146afadSYan Zheng 		}
4167c146afadSYan Zheng 		root_objectid++;
4168c146afadSYan Zheng 	}
416965d33fd7SQu Wenruo 
417065d33fd7SQu Wenruo 	/* release the uncleaned roots due to error */
417165d33fd7SQu Wenruo 	for (; i < ret; i++) {
417265d33fd7SQu Wenruo 		if (gang[i])
417300246528SJosef Bacik 			btrfs_put_root(gang[i]);
417465d33fd7SQu Wenruo 	}
417565d33fd7SQu Wenruo 	return err;
4176c146afadSYan Zheng }
4177c146afadSYan Zheng 
41786bccf3abSJeff Mahoney int btrfs_commit_super(struct btrfs_fs_info *fs_info)
4179c146afadSYan Zheng {
41806bccf3abSJeff Mahoney 	struct btrfs_root *root = fs_info->tree_root;
4181c146afadSYan Zheng 	struct btrfs_trans_handle *trans;
4182c146afadSYan Zheng 
41830b246afaSJeff Mahoney 	mutex_lock(&fs_info->cleaner_mutex);
41842ff7e61eSJeff Mahoney 	btrfs_run_delayed_iputs(fs_info);
41850b246afaSJeff Mahoney 	mutex_unlock(&fs_info->cleaner_mutex);
41860b246afaSJeff Mahoney 	wake_up_process(fs_info->cleaner_kthread);
4187c71bf099SYan, Zheng 
4188c71bf099SYan, Zheng 	/* wait until ongoing cleanup work done */
41890b246afaSJeff Mahoney 	down_write(&fs_info->cleanup_work_sem);
41900b246afaSJeff Mahoney 	up_write(&fs_info->cleanup_work_sem);
4191c71bf099SYan, Zheng 
41927a7eaa40SJosef Bacik 	trans = btrfs_join_transaction(root);
41933612b495STsutomu Itoh 	if (IS_ERR(trans))
41943612b495STsutomu Itoh 		return PTR_ERR(trans);
41953a45bb20SJeff Mahoney 	return btrfs_commit_transaction(trans);
4196c146afadSYan Zheng }
4197c146afadSYan Zheng 
4198b105e927SDavid Sterba void __cold close_ctree(struct btrfs_fs_info *fs_info)
4199eb60ceacSChris Mason {
4200c146afadSYan Zheng 	int ret;
4201e089f05cSChris Mason 
4202afcdd129SJosef Bacik 	set_bit(BTRFS_FS_CLOSING_START, &fs_info->flags);
4203d6fd0ae2SOmar Sandoval 	/*
4204d6fd0ae2SOmar Sandoval 	 * We don't want the cleaner to start new transactions, add more delayed
4205d6fd0ae2SOmar Sandoval 	 * iputs, etc. while we're closing. We can't use kthread_stop() yet
4206d6fd0ae2SOmar Sandoval 	 * because that frees the task_struct, and the transaction kthread might
4207d6fd0ae2SOmar Sandoval 	 * still try to wake up the cleaner.
4208d6fd0ae2SOmar Sandoval 	 */
4209d6fd0ae2SOmar Sandoval 	kthread_park(fs_info->cleaner_kthread);
4210a2135011SChris Mason 
42117343dd61SJustin Maggard 	/* wait for the qgroup rescan worker to stop */
4212d06f23d6SJeff Mahoney 	btrfs_qgroup_wait_for_completion(fs_info, false);
42137343dd61SJustin Maggard 
4214803b2f54SStefan Behrens 	/* wait for the uuid_scan task to finish */
4215803b2f54SStefan Behrens 	down(&fs_info->uuid_tree_rescan_sem);
4216803b2f54SStefan Behrens 	/* avoid complains from lockdep et al., set sem back to initial state */
4217803b2f54SStefan Behrens 	up(&fs_info->uuid_tree_rescan_sem);
4218803b2f54SStefan Behrens 
4219837d5b6eSIlya Dryomov 	/* pause restriper - we want to resume on mount */
4220aa1b8cd4SStefan Behrens 	btrfs_pause_balance(fs_info);
4221837d5b6eSIlya Dryomov 
42228dabb742SStefan Behrens 	btrfs_dev_replace_suspend_for_unmount(fs_info);
42238dabb742SStefan Behrens 
4224aa1b8cd4SStefan Behrens 	btrfs_scrub_cancel(fs_info);
42254cb5300bSChris Mason 
42264cb5300bSChris Mason 	/* wait for any defraggers to finish */
42274cb5300bSChris Mason 	wait_event(fs_info->transaction_wait,
42284cb5300bSChris Mason 		   (atomic_read(&fs_info->defrag_running) == 0));
42294cb5300bSChris Mason 
42304cb5300bSChris Mason 	/* clear out the rbtree of defraggable inodes */
423126176e7cSMiao Xie 	btrfs_cleanup_defrag_inodes(fs_info);
42324cb5300bSChris Mason 
423321c7e756SMiao Xie 	cancel_work_sync(&fs_info->async_reclaim_work);
423457056740SJosef Bacik 	cancel_work_sync(&fs_info->async_data_reclaim_work);
4235576fa348SJosef Bacik 	cancel_work_sync(&fs_info->preempt_reclaim_work);
423621c7e756SMiao Xie 
4237b0643e59SDennis Zhou 	/* Cancel or finish ongoing discard work */
4238b0643e59SDennis Zhou 	btrfs_discard_cleanup(fs_info);
4239b0643e59SDennis Zhou 
4240bc98a42cSDavid Howells 	if (!sb_rdonly(fs_info->sb)) {
4241e44163e1SJeff Mahoney 		/*
4242d6fd0ae2SOmar Sandoval 		 * The cleaner kthread is stopped, so do one final pass over
4243d6fd0ae2SOmar Sandoval 		 * unused block groups.
4244e44163e1SJeff Mahoney 		 */
42450b246afaSJeff Mahoney 		btrfs_delete_unused_bgs(fs_info);
4246e44163e1SJeff Mahoney 
4247f0cc2cd7SFilipe Manana 		/*
4248f0cc2cd7SFilipe Manana 		 * There might be existing delayed inode workers still running
4249f0cc2cd7SFilipe Manana 		 * and holding an empty delayed inode item. We must wait for
4250f0cc2cd7SFilipe Manana 		 * them to complete first because they can create a transaction.
4251f0cc2cd7SFilipe Manana 		 * This happens when someone calls btrfs_balance_delayed_items()
4252f0cc2cd7SFilipe Manana 		 * and then a transaction commit runs the same delayed nodes
4253f0cc2cd7SFilipe Manana 		 * before any delayed worker has done something with the nodes.
4254f0cc2cd7SFilipe Manana 		 * We must wait for any worker here and not at transaction
4255f0cc2cd7SFilipe Manana 		 * commit time since that could cause a deadlock.
4256f0cc2cd7SFilipe Manana 		 * This is a very rare case.
4257f0cc2cd7SFilipe Manana 		 */
4258f0cc2cd7SFilipe Manana 		btrfs_flush_workqueue(fs_info->delayed_workers);
4259f0cc2cd7SFilipe Manana 
42606bccf3abSJeff Mahoney 		ret = btrfs_commit_super(fs_info);
4261d397712bSChris Mason 		if (ret)
426204892340SEric Sandeen 			btrfs_err(fs_info, "commit super ret %d", ret);
4263c146afadSYan Zheng 	}
4264ed2ff2cbSChris Mason 
4265af722733SLiu Bo 	if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state) ||
4266af722733SLiu Bo 	    test_bit(BTRFS_FS_STATE_TRANS_ABORTED, &fs_info->fs_state))
42672ff7e61eSJeff Mahoney 		btrfs_error_commit_super(fs_info);
4268acce952bSliubo 
4269e3029d9fSAl Viro 	kthread_stop(fs_info->transaction_kthread);
4270e3029d9fSAl Viro 	kthread_stop(fs_info->cleaner_kthread);
42718929ecfaSYan, Zheng 
4272e187831eSJosef Bacik 	ASSERT(list_empty(&fs_info->delayed_iputs));
4273afcdd129SJosef Bacik 	set_bit(BTRFS_FS_CLOSING_DONE, &fs_info->flags);
4274f25784b3SYan Zheng 
42755958253cSQu Wenruo 	if (btrfs_check_quota_leak(fs_info)) {
42765958253cSQu Wenruo 		WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
42775958253cSQu Wenruo 		btrfs_err(fs_info, "qgroup reserved space leaked");
42785958253cSQu Wenruo 	}
42795958253cSQu Wenruo 
428004892340SEric Sandeen 	btrfs_free_qgroup_config(fs_info);
4281fe816d0fSNikolay Borisov 	ASSERT(list_empty(&fs_info->delalloc_roots));
4282bcef60f2SArne Jansen 
4283963d678bSMiao Xie 	if (percpu_counter_sum(&fs_info->delalloc_bytes)) {
428404892340SEric Sandeen 		btrfs_info(fs_info, "at unmount delalloc count %lld",
4285963d678bSMiao Xie 		       percpu_counter_sum(&fs_info->delalloc_bytes));
4286b0c68f8bSChris Mason 	}
428731153d81SYan Zheng 
42885deb17e1SJosef Bacik 	if (percpu_counter_sum(&fs_info->ordered_bytes))
42894297ff84SJosef Bacik 		btrfs_info(fs_info, "at unmount dio bytes count %lld",
42905deb17e1SJosef Bacik 			   percpu_counter_sum(&fs_info->ordered_bytes));
42914297ff84SJosef Bacik 
42926618a59bSAnand Jain 	btrfs_sysfs_remove_mounted(fs_info);
4293b7c35e81SAnand Jain 	btrfs_sysfs_remove_fsid(fs_info->fs_devices);
42945ac1d209SJeff Mahoney 
42951a4319ccSLiu Bo 	btrfs_put_block_group_cache(fs_info);
42961a4319ccSLiu Bo 
4297de348ee0SWang Shilong 	/*
4298de348ee0SWang Shilong 	 * we must make sure there is not any read request to
4299de348ee0SWang Shilong 	 * submit after we stopping all workers.
4300de348ee0SWang Shilong 	 */
4301de348ee0SWang Shilong 	invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
430296192499SJosef Bacik 	btrfs_stop_all_workers(fs_info);
430396192499SJosef Bacik 
43040a31daa4SFilipe Manana 	/* We shouldn't have any transaction open at this point */
43050a31daa4SFilipe Manana 	ASSERT(list_empty(&fs_info->trans_list));
43060a31daa4SFilipe Manana 
4307afcdd129SJosef Bacik 	clear_bit(BTRFS_FS_OPEN, &fs_info->flags);
43084273eaffSAnand Jain 	free_root_pointers(fs_info, true);
43098c38938cSJosef Bacik 	btrfs_free_fs_roots(fs_info);
43109ad6b7bcSChris Mason 
43114e19443dSJosef Bacik 	/*
43124e19443dSJosef Bacik 	 * We must free the block groups after dropping the fs_roots as we could
43134e19443dSJosef Bacik 	 * have had an IO error and have left over tree log blocks that aren't
43144e19443dSJosef Bacik 	 * cleaned up until the fs roots are freed.  This makes the block group
43154e19443dSJosef Bacik 	 * accounting appear to be wrong because there's pending reserved bytes,
43164e19443dSJosef Bacik 	 * so make sure we do the block group cleanup afterwards.
43174e19443dSJosef Bacik 	 */
43184e19443dSJosef Bacik 	btrfs_free_block_groups(fs_info);
43194e19443dSJosef Bacik 
432013e6c37bSJosef Bacik 	iput(fs_info->btree_inode);
4321d6bfde87SChris Mason 
432221adbd5cSStefan Behrens #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
43230b246afaSJeff Mahoney 	if (btrfs_test_opt(fs_info, CHECK_INTEGRITY))
43242ff7e61eSJeff Mahoney 		btrfsic_unmount(fs_info->fs_devices);
432521adbd5cSStefan Behrens #endif
432621adbd5cSStefan Behrens 
43270b86a832SChris Mason 	btrfs_mapping_tree_free(&fs_info->mapping_tree);
432868c94e55SNikolay Borisov 	btrfs_close_devices(fs_info->fs_devices);
4329eb60ceacSChris Mason }
4330eb60ceacSChris Mason 
4331b9fab919SChris Mason int btrfs_buffer_uptodate(struct extent_buffer *buf, u64 parent_transid,
4332b9fab919SChris Mason 			  int atomic)
4333ccd467d6SChris Mason {
43341259ab75SChris Mason 	int ret;
4335727011e0SChris Mason 	struct inode *btree_inode = buf->pages[0]->mapping->host;
43361259ab75SChris Mason 
43370b32f4bbSJosef Bacik 	ret = extent_buffer_uptodate(buf);
43381259ab75SChris Mason 	if (!ret)
43391259ab75SChris Mason 		return ret;
43401259ab75SChris Mason 
43411259ab75SChris Mason 	ret = verify_parent_transid(&BTRFS_I(btree_inode)->io_tree, buf,
4342b9fab919SChris Mason 				    parent_transid, atomic);
4343b9fab919SChris Mason 	if (ret == -EAGAIN)
4344b9fab919SChris Mason 		return ret;
43451259ab75SChris Mason 	return !ret;
43465f39d397SChris Mason }
43476702ed49SChris Mason 
43485f39d397SChris Mason void btrfs_mark_buffer_dirty(struct extent_buffer *buf)
43495f39d397SChris Mason {
43502f4d60dfSQu Wenruo 	struct btrfs_fs_info *fs_info = buf->fs_info;
43515f39d397SChris Mason 	u64 transid = btrfs_header_generation(buf);
4352b9473439SChris Mason 	int was_dirty;
4353b4ce94deSChris Mason 
435406ea65a3SJosef Bacik #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
435506ea65a3SJosef Bacik 	/*
435606ea65a3SJosef Bacik 	 * This is a fast path so only do this check if we have sanity tests
435752042d8eSAndrea Gelmini 	 * enabled.  Normal people shouldn't be using unmapped buffers as dirty
435806ea65a3SJosef Bacik 	 * outside of the sanity tests.
435906ea65a3SJosef Bacik 	 */
4360b0132a3bSNikolay Borisov 	if (unlikely(test_bit(EXTENT_BUFFER_UNMAPPED, &buf->bflags)))
436106ea65a3SJosef Bacik 		return;
436206ea65a3SJosef Bacik #endif
4363b9447ef8SChris Mason 	btrfs_assert_tree_locked(buf);
43640b246afaSJeff Mahoney 	if (transid != fs_info->generation)
43655d163e0eSJeff Mahoney 		WARN(1, KERN_CRIT "btrfs transid mismatch buffer %llu, found %llu running %llu\n",
43660b246afaSJeff Mahoney 			buf->start, transid, fs_info->generation);
43670b32f4bbSJosef Bacik 	was_dirty = set_extent_buffer_dirty(buf);
4368e2d84521SMiao Xie 	if (!was_dirty)
4369104b4e51SNikolay Borisov 		percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
4370e2d84521SMiao Xie 					 buf->len,
43710b246afaSJeff Mahoney 					 fs_info->dirty_metadata_batch);
43721f21ef0aSFilipe Manana #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
437369fc6cbbSQu Wenruo 	/*
437469fc6cbbSQu Wenruo 	 * Since btrfs_mark_buffer_dirty() can be called with item pointer set
437569fc6cbbSQu Wenruo 	 * but item data not updated.
437669fc6cbbSQu Wenruo 	 * So here we should only check item pointers, not item data.
437769fc6cbbSQu Wenruo 	 */
437869fc6cbbSQu Wenruo 	if (btrfs_header_level(buf) == 0 &&
4379cfdaad5eSDavid Sterba 	    btrfs_check_leaf_relaxed(buf)) {
4380a4f78750SDavid Sterba 		btrfs_print_leaf(buf);
43811f21ef0aSFilipe Manana 		ASSERT(0);
43821f21ef0aSFilipe Manana 	}
43831f21ef0aSFilipe Manana #endif
4384eb60ceacSChris Mason }
4385eb60ceacSChris Mason 
43862ff7e61eSJeff Mahoney static void __btrfs_btree_balance_dirty(struct btrfs_fs_info *fs_info,
4387b53d3f5dSLiu Bo 					int flush_delayed)
438835b7e476SChris Mason {
4389188de649SChris Mason 	/*
4390188de649SChris Mason 	 * looks as though older kernels can get into trouble with
4391188de649SChris Mason 	 * this code, they end up stuck in balance_dirty_pages forever
4392188de649SChris Mason 	 */
4393e2d84521SMiao Xie 	int ret;
4394d6bfde87SChris Mason 
43956933c02eSJens Axboe 	if (current->flags & PF_MEMALLOC)
4396d6bfde87SChris Mason 		return;
4397d6bfde87SChris Mason 
4398b53d3f5dSLiu Bo 	if (flush_delayed)
43992ff7e61eSJeff Mahoney 		btrfs_balance_delayed_items(fs_info);
440016cdcec7SMiao Xie 
4401d814a491SEthan Lien 	ret = __percpu_counter_compare(&fs_info->dirty_metadata_bytes,
4402d814a491SEthan Lien 				     BTRFS_DIRTY_METADATA_THRESH,
4403d814a491SEthan Lien 				     fs_info->dirty_metadata_batch);
4404e2d84521SMiao Xie 	if (ret > 0) {
44050b246afaSJeff Mahoney 		balance_dirty_pages_ratelimited(fs_info->btree_inode->i_mapping);
440616cdcec7SMiao Xie 	}
440716cdcec7SMiao Xie }
440816cdcec7SMiao Xie 
44092ff7e61eSJeff Mahoney void btrfs_btree_balance_dirty(struct btrfs_fs_info *fs_info)
441016cdcec7SMiao Xie {
44112ff7e61eSJeff Mahoney 	__btrfs_btree_balance_dirty(fs_info, 1);
441235b7e476SChris Mason }
4413b53d3f5dSLiu Bo 
44142ff7e61eSJeff Mahoney void btrfs_btree_balance_dirty_nodelay(struct btrfs_fs_info *fs_info)
4415b53d3f5dSLiu Bo {
44162ff7e61eSJeff Mahoney 	__btrfs_btree_balance_dirty(fs_info, 0);
4417d6bfde87SChris Mason }
44186b80053dSChris Mason 
4419581c1760SQu Wenruo int btrfs_read_buffer(struct extent_buffer *buf, u64 parent_transid, int level,
4420581c1760SQu Wenruo 		      struct btrfs_key *first_key)
44216b80053dSChris Mason {
44225ab12d1fSDavid Sterba 	return btree_read_extent_buffer_pages(buf, parent_transid,
4423581c1760SQu Wenruo 					      level, first_key);
44246b80053dSChris Mason }
44250da5468fSChris Mason 
44262ff7e61eSJeff Mahoney static void btrfs_error_commit_super(struct btrfs_fs_info *fs_info)
4427acce952bSliubo {
4428fe816d0fSNikolay Borisov 	/* cleanup FS via transaction */
4429fe816d0fSNikolay Borisov 	btrfs_cleanup_transaction(fs_info);
4430fe816d0fSNikolay Borisov 
44310b246afaSJeff Mahoney 	mutex_lock(&fs_info->cleaner_mutex);
44322ff7e61eSJeff Mahoney 	btrfs_run_delayed_iputs(fs_info);
44330b246afaSJeff Mahoney 	mutex_unlock(&fs_info->cleaner_mutex);
4434acce952bSliubo 
44350b246afaSJeff Mahoney 	down_write(&fs_info->cleanup_work_sem);
44360b246afaSJeff Mahoney 	up_write(&fs_info->cleanup_work_sem);
4437acce952bSliubo }
4438acce952bSliubo 
4439ef67963dSJosef Bacik static void btrfs_drop_all_logs(struct btrfs_fs_info *fs_info)
4440ef67963dSJosef Bacik {
4441ef67963dSJosef Bacik 	struct btrfs_root *gang[8];
4442ef67963dSJosef Bacik 	u64 root_objectid = 0;
4443ef67963dSJosef Bacik 	int ret;
4444ef67963dSJosef Bacik 
4445ef67963dSJosef Bacik 	spin_lock(&fs_info->fs_roots_radix_lock);
4446ef67963dSJosef Bacik 	while ((ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
4447ef67963dSJosef Bacik 					     (void **)gang, root_objectid,
4448ef67963dSJosef Bacik 					     ARRAY_SIZE(gang))) != 0) {
4449ef67963dSJosef Bacik 		int i;
4450ef67963dSJosef Bacik 
4451ef67963dSJosef Bacik 		for (i = 0; i < ret; i++)
4452ef67963dSJosef Bacik 			gang[i] = btrfs_grab_root(gang[i]);
4453ef67963dSJosef Bacik 		spin_unlock(&fs_info->fs_roots_radix_lock);
4454ef67963dSJosef Bacik 
4455ef67963dSJosef Bacik 		for (i = 0; i < ret; i++) {
4456ef67963dSJosef Bacik 			if (!gang[i])
4457ef67963dSJosef Bacik 				continue;
4458ef67963dSJosef Bacik 			root_objectid = gang[i]->root_key.objectid;
4459ef67963dSJosef Bacik 			btrfs_free_log(NULL, gang[i]);
4460ef67963dSJosef Bacik 			btrfs_put_root(gang[i]);
4461ef67963dSJosef Bacik 		}
4462ef67963dSJosef Bacik 		root_objectid++;
4463ef67963dSJosef Bacik 		spin_lock(&fs_info->fs_roots_radix_lock);
4464ef67963dSJosef Bacik 	}
4465ef67963dSJosef Bacik 	spin_unlock(&fs_info->fs_roots_radix_lock);
4466ef67963dSJosef Bacik 	btrfs_free_log_root_tree(NULL, fs_info);
4467ef67963dSJosef Bacik }
4468ef67963dSJosef Bacik 
4469143bede5SJeff Mahoney static void btrfs_destroy_ordered_extents(struct btrfs_root *root)
4470acce952bSliubo {
4471acce952bSliubo 	struct btrfs_ordered_extent *ordered;
4472acce952bSliubo 
4473199c2a9cSMiao Xie 	spin_lock(&root->ordered_extent_lock);
4474779880efSJosef Bacik 	/*
4475779880efSJosef Bacik 	 * This will just short circuit the ordered completion stuff which will
4476779880efSJosef Bacik 	 * make sure the ordered extent gets properly cleaned up.
4477779880efSJosef Bacik 	 */
4478199c2a9cSMiao Xie 	list_for_each_entry(ordered, &root->ordered_extents,
4479779880efSJosef Bacik 			    root_extent_list)
4480779880efSJosef Bacik 		set_bit(BTRFS_ORDERED_IOERR, &ordered->flags);
4481199c2a9cSMiao Xie 	spin_unlock(&root->ordered_extent_lock);
4482199c2a9cSMiao Xie }
4483199c2a9cSMiao Xie 
4484199c2a9cSMiao Xie static void btrfs_destroy_all_ordered_extents(struct btrfs_fs_info *fs_info)
4485199c2a9cSMiao Xie {
4486199c2a9cSMiao Xie 	struct btrfs_root *root;
4487199c2a9cSMiao Xie 	struct list_head splice;
4488199c2a9cSMiao Xie 
4489199c2a9cSMiao Xie 	INIT_LIST_HEAD(&splice);
4490199c2a9cSMiao Xie 
4491199c2a9cSMiao Xie 	spin_lock(&fs_info->ordered_root_lock);
4492199c2a9cSMiao Xie 	list_splice_init(&fs_info->ordered_roots, &splice);
4493199c2a9cSMiao Xie 	while (!list_empty(&splice)) {
4494199c2a9cSMiao Xie 		root = list_first_entry(&splice, struct btrfs_root,
4495199c2a9cSMiao Xie 					ordered_root);
44961de2cfdeSJosef Bacik 		list_move_tail(&root->ordered_root,
44971de2cfdeSJosef Bacik 			       &fs_info->ordered_roots);
4498199c2a9cSMiao Xie 
44992a85d9caSLiu Bo 		spin_unlock(&fs_info->ordered_root_lock);
4500199c2a9cSMiao Xie 		btrfs_destroy_ordered_extents(root);
4501199c2a9cSMiao Xie 
45022a85d9caSLiu Bo 		cond_resched();
45032a85d9caSLiu Bo 		spin_lock(&fs_info->ordered_root_lock);
4504199c2a9cSMiao Xie 	}
4505199c2a9cSMiao Xie 	spin_unlock(&fs_info->ordered_root_lock);
450674d5d229SJosef Bacik 
450774d5d229SJosef Bacik 	/*
450874d5d229SJosef Bacik 	 * We need this here because if we've been flipped read-only we won't
450974d5d229SJosef Bacik 	 * get sync() from the umount, so we need to make sure any ordered
451074d5d229SJosef Bacik 	 * extents that haven't had their dirty pages IO start writeout yet
451174d5d229SJosef Bacik 	 * actually get run and error out properly.
451274d5d229SJosef Bacik 	 */
451374d5d229SJosef Bacik 	btrfs_wait_ordered_roots(fs_info, U64_MAX, 0, (u64)-1);
4514acce952bSliubo }
4515acce952bSliubo 
451635a3621bSStefan Behrens static int btrfs_destroy_delayed_refs(struct btrfs_transaction *trans,
45172ff7e61eSJeff Mahoney 				      struct btrfs_fs_info *fs_info)
4518acce952bSliubo {
4519acce952bSliubo 	struct rb_node *node;
4520acce952bSliubo 	struct btrfs_delayed_ref_root *delayed_refs;
4521acce952bSliubo 	struct btrfs_delayed_ref_node *ref;
4522acce952bSliubo 	int ret = 0;
4523acce952bSliubo 
4524acce952bSliubo 	delayed_refs = &trans->delayed_refs;
4525acce952bSliubo 
4526acce952bSliubo 	spin_lock(&delayed_refs->lock);
4527d7df2c79SJosef Bacik 	if (atomic_read(&delayed_refs->num_entries) == 0) {
4528cfece4dbSDavid Sterba 		spin_unlock(&delayed_refs->lock);
4529b79ce3ddSDavid Sterba 		btrfs_debug(fs_info, "delayed_refs has NO entry");
4530acce952bSliubo 		return ret;
4531acce952bSliubo 	}
4532acce952bSliubo 
45335c9d028bSLiu Bo 	while ((node = rb_first_cached(&delayed_refs->href_root)) != NULL) {
4534d7df2c79SJosef Bacik 		struct btrfs_delayed_ref_head *head;
45350e0adbcfSJosef Bacik 		struct rb_node *n;
4536e78417d1SJosef Bacik 		bool pin_bytes = false;
4537acce952bSliubo 
4538d7df2c79SJosef Bacik 		head = rb_entry(node, struct btrfs_delayed_ref_head,
4539d7df2c79SJosef Bacik 				href_node);
45403069bd26SJosef Bacik 		if (btrfs_delayed_ref_lock(delayed_refs, head))
4541b939d1abSJosef Bacik 			continue;
45423069bd26SJosef Bacik 
4543d7df2c79SJosef Bacik 		spin_lock(&head->lock);
4544e3d03965SLiu Bo 		while ((n = rb_first_cached(&head->ref_tree)) != NULL) {
45450e0adbcfSJosef Bacik 			ref = rb_entry(n, struct btrfs_delayed_ref_node,
45460e0adbcfSJosef Bacik 				       ref_node);
4547d7df2c79SJosef Bacik 			ref->in_tree = 0;
4548e3d03965SLiu Bo 			rb_erase_cached(&ref->ref_node, &head->ref_tree);
45490e0adbcfSJosef Bacik 			RB_CLEAR_NODE(&ref->ref_node);
45501d57ee94SWang Xiaoguang 			if (!list_empty(&ref->add_list))
45511d57ee94SWang Xiaoguang 				list_del(&ref->add_list);
4552d7df2c79SJosef Bacik 			atomic_dec(&delayed_refs->num_entries);
4553d7df2c79SJosef Bacik 			btrfs_put_delayed_ref(ref);
4554d7df2c79SJosef Bacik 		}
455554067ae9SJosef Bacik 		if (head->must_insert_reserved)
4556e78417d1SJosef Bacik 			pin_bytes = true;
455778a6184aSMiao Xie 		btrfs_free_delayed_extent_op(head->extent_op);
4558fa781ceaSJosef Bacik 		btrfs_delete_ref_head(delayed_refs, head);
4559d7df2c79SJosef Bacik 		spin_unlock(&head->lock);
4560acce952bSliubo 		spin_unlock(&delayed_refs->lock);
4561e78417d1SJosef Bacik 		mutex_unlock(&head->mutex);
4562acce952bSliubo 
4563f603bb94SNikolay Borisov 		if (pin_bytes) {
4564f603bb94SNikolay Borisov 			struct btrfs_block_group *cache;
4565f603bb94SNikolay Borisov 
4566f603bb94SNikolay Borisov 			cache = btrfs_lookup_block_group(fs_info, head->bytenr);
4567f603bb94SNikolay Borisov 			BUG_ON(!cache);
4568f603bb94SNikolay Borisov 
4569f603bb94SNikolay Borisov 			spin_lock(&cache->space_info->lock);
4570f603bb94SNikolay Borisov 			spin_lock(&cache->lock);
4571f603bb94SNikolay Borisov 			cache->pinned += head->num_bytes;
4572f603bb94SNikolay Borisov 			btrfs_space_info_update_bytes_pinned(fs_info,
4573f603bb94SNikolay Borisov 				cache->space_info, head->num_bytes);
4574f603bb94SNikolay Borisov 			cache->reserved -= head->num_bytes;
4575f603bb94SNikolay Borisov 			cache->space_info->bytes_reserved -= head->num_bytes;
4576f603bb94SNikolay Borisov 			spin_unlock(&cache->lock);
4577f603bb94SNikolay Borisov 			spin_unlock(&cache->space_info->lock);
4578f603bb94SNikolay Borisov 			percpu_counter_add_batch(
4579f603bb94SNikolay Borisov 				&cache->space_info->total_bytes_pinned,
4580f603bb94SNikolay Borisov 				head->num_bytes, BTRFS_TOTAL_BYTES_PINNED_BATCH);
4581f603bb94SNikolay Borisov 
4582f603bb94SNikolay Borisov 			btrfs_put_block_group(cache);
4583f603bb94SNikolay Borisov 
4584f603bb94SNikolay Borisov 			btrfs_error_unpin_extent_range(fs_info, head->bytenr,
4585f603bb94SNikolay Borisov 				head->bytenr + head->num_bytes - 1);
4586f603bb94SNikolay Borisov 		}
458731890da0SJosef Bacik 		btrfs_cleanup_ref_head_accounting(fs_info, delayed_refs, head);
4588d278850eSJosef Bacik 		btrfs_put_delayed_ref_head(head);
4589acce952bSliubo 		cond_resched();
4590acce952bSliubo 		spin_lock(&delayed_refs->lock);
4591acce952bSliubo 	}
459281f7eb00SJeff Mahoney 	btrfs_qgroup_destroy_extent_records(trans);
4593acce952bSliubo 
4594acce952bSliubo 	spin_unlock(&delayed_refs->lock);
4595acce952bSliubo 
4596acce952bSliubo 	return ret;
4597acce952bSliubo }
4598acce952bSliubo 
4599143bede5SJeff Mahoney static void btrfs_destroy_delalloc_inodes(struct btrfs_root *root)
4600acce952bSliubo {
4601acce952bSliubo 	struct btrfs_inode *btrfs_inode;
4602acce952bSliubo 	struct list_head splice;
4603acce952bSliubo 
4604acce952bSliubo 	INIT_LIST_HEAD(&splice);
4605acce952bSliubo 
4606eb73c1b7SMiao Xie 	spin_lock(&root->delalloc_lock);
4607eb73c1b7SMiao Xie 	list_splice_init(&root->delalloc_inodes, &splice);
4608acce952bSliubo 
4609acce952bSliubo 	while (!list_empty(&splice)) {
4610fe816d0fSNikolay Borisov 		struct inode *inode = NULL;
4611eb73c1b7SMiao Xie 		btrfs_inode = list_first_entry(&splice, struct btrfs_inode,
4612acce952bSliubo 					       delalloc_inodes);
4613fe816d0fSNikolay Borisov 		__btrfs_del_delalloc_inode(root, btrfs_inode);
4614eb73c1b7SMiao Xie 		spin_unlock(&root->delalloc_lock);
4615acce952bSliubo 
4616fe816d0fSNikolay Borisov 		/*
4617fe816d0fSNikolay Borisov 		 * Make sure we get a live inode and that it'll not disappear
4618fe816d0fSNikolay Borisov 		 * meanwhile.
4619fe816d0fSNikolay Borisov 		 */
4620fe816d0fSNikolay Borisov 		inode = igrab(&btrfs_inode->vfs_inode);
4621fe816d0fSNikolay Borisov 		if (inode) {
4622fe816d0fSNikolay Borisov 			invalidate_inode_pages2(inode->i_mapping);
4623fe816d0fSNikolay Borisov 			iput(inode);
4624fe816d0fSNikolay Borisov 		}
4625eb73c1b7SMiao Xie 		spin_lock(&root->delalloc_lock);
4626acce952bSliubo 	}
4627eb73c1b7SMiao Xie 	spin_unlock(&root->delalloc_lock);
4628eb73c1b7SMiao Xie }
4629eb73c1b7SMiao Xie 
4630eb73c1b7SMiao Xie static void btrfs_destroy_all_delalloc_inodes(struct btrfs_fs_info *fs_info)
4631eb73c1b7SMiao Xie {
4632eb73c1b7SMiao Xie 	struct btrfs_root *root;
4633eb73c1b7SMiao Xie 	struct list_head splice;
4634eb73c1b7SMiao Xie 
4635eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&splice);
4636eb73c1b7SMiao Xie 
4637eb73c1b7SMiao Xie 	spin_lock(&fs_info->delalloc_root_lock);
4638eb73c1b7SMiao Xie 	list_splice_init(&fs_info->delalloc_roots, &splice);
4639eb73c1b7SMiao Xie 	while (!list_empty(&splice)) {
4640eb73c1b7SMiao Xie 		root = list_first_entry(&splice, struct btrfs_root,
4641eb73c1b7SMiao Xie 					 delalloc_root);
464200246528SJosef Bacik 		root = btrfs_grab_root(root);
4643eb73c1b7SMiao Xie 		BUG_ON(!root);
4644eb73c1b7SMiao Xie 		spin_unlock(&fs_info->delalloc_root_lock);
4645eb73c1b7SMiao Xie 
4646eb73c1b7SMiao Xie 		btrfs_destroy_delalloc_inodes(root);
464700246528SJosef Bacik 		btrfs_put_root(root);
4648eb73c1b7SMiao Xie 
4649eb73c1b7SMiao Xie 		spin_lock(&fs_info->delalloc_root_lock);
4650eb73c1b7SMiao Xie 	}
4651eb73c1b7SMiao Xie 	spin_unlock(&fs_info->delalloc_root_lock);
4652acce952bSliubo }
4653acce952bSliubo 
46542ff7e61eSJeff Mahoney static int btrfs_destroy_marked_extents(struct btrfs_fs_info *fs_info,
4655acce952bSliubo 					struct extent_io_tree *dirty_pages,
4656acce952bSliubo 					int mark)
4657acce952bSliubo {
4658acce952bSliubo 	int ret;
4659acce952bSliubo 	struct extent_buffer *eb;
4660acce952bSliubo 	u64 start = 0;
4661acce952bSliubo 	u64 end;
4662acce952bSliubo 
4663acce952bSliubo 	while (1) {
4664acce952bSliubo 		ret = find_first_extent_bit(dirty_pages, start, &start, &end,
4665e6138876SJosef Bacik 					    mark, NULL);
4666acce952bSliubo 		if (ret)
4667acce952bSliubo 			break;
4668acce952bSliubo 
466991166212SDavid Sterba 		clear_extent_bits(dirty_pages, start, end, mark);
4670acce952bSliubo 		while (start <= end) {
46710b246afaSJeff Mahoney 			eb = find_extent_buffer(fs_info, start);
46720b246afaSJeff Mahoney 			start += fs_info->nodesize;
4673fd8b2b61SJosef Bacik 			if (!eb)
4674acce952bSliubo 				continue;
4675fd8b2b61SJosef Bacik 			wait_on_extent_buffer_writeback(eb);
4676acce952bSliubo 
4677fd8b2b61SJosef Bacik 			if (test_and_clear_bit(EXTENT_BUFFER_DIRTY,
4678fd8b2b61SJosef Bacik 					       &eb->bflags))
4679fd8b2b61SJosef Bacik 				clear_extent_buffer_dirty(eb);
4680fd8b2b61SJosef Bacik 			free_extent_buffer_stale(eb);
4681acce952bSliubo 		}
4682acce952bSliubo 	}
4683acce952bSliubo 
4684acce952bSliubo 	return ret;
4685acce952bSliubo }
4686acce952bSliubo 
46872ff7e61eSJeff Mahoney static int btrfs_destroy_pinned_extent(struct btrfs_fs_info *fs_info,
4688fe119a6eSNikolay Borisov 				       struct extent_io_tree *unpin)
4689acce952bSliubo {
4690acce952bSliubo 	u64 start;
4691acce952bSliubo 	u64 end;
4692acce952bSliubo 	int ret;
4693acce952bSliubo 
4694acce952bSliubo 	while (1) {
46950e6ec385SFilipe Manana 		struct extent_state *cached_state = NULL;
46960e6ec385SFilipe Manana 
4697fcd5e742SLu Fengqi 		/*
4698fcd5e742SLu Fengqi 		 * The btrfs_finish_extent_commit() may get the same range as
4699fcd5e742SLu Fengqi 		 * ours between find_first_extent_bit and clear_extent_dirty.
4700fcd5e742SLu Fengqi 		 * Hence, hold the unused_bg_unpin_mutex to avoid double unpin
4701fcd5e742SLu Fengqi 		 * the same extent range.
4702fcd5e742SLu Fengqi 		 */
4703fcd5e742SLu Fengqi 		mutex_lock(&fs_info->unused_bg_unpin_mutex);
4704acce952bSliubo 		ret = find_first_extent_bit(unpin, 0, &start, &end,
47050e6ec385SFilipe Manana 					    EXTENT_DIRTY, &cached_state);
4706fcd5e742SLu Fengqi 		if (ret) {
4707fcd5e742SLu Fengqi 			mutex_unlock(&fs_info->unused_bg_unpin_mutex);
4708acce952bSliubo 			break;
4709fcd5e742SLu Fengqi 		}
4710acce952bSliubo 
47110e6ec385SFilipe Manana 		clear_extent_dirty(unpin, start, end, &cached_state);
47120e6ec385SFilipe Manana 		free_extent_state(cached_state);
47132ff7e61eSJeff Mahoney 		btrfs_error_unpin_extent_range(fs_info, start, end);
4714fcd5e742SLu Fengqi 		mutex_unlock(&fs_info->unused_bg_unpin_mutex);
4715acce952bSliubo 		cond_resched();
4716acce952bSliubo 	}
4717acce952bSliubo 
4718acce952bSliubo 	return 0;
4719acce952bSliubo }
4720acce952bSliubo 
472132da5386SDavid Sterba static void btrfs_cleanup_bg_io(struct btrfs_block_group *cache)
4722c79a1751SLiu Bo {
4723c79a1751SLiu Bo 	struct inode *inode;
4724c79a1751SLiu Bo 
4725c79a1751SLiu Bo 	inode = cache->io_ctl.inode;
4726c79a1751SLiu Bo 	if (inode) {
4727c79a1751SLiu Bo 		invalidate_inode_pages2(inode->i_mapping);
4728c79a1751SLiu Bo 		BTRFS_I(inode)->generation = 0;
4729c79a1751SLiu Bo 		cache->io_ctl.inode = NULL;
4730c79a1751SLiu Bo 		iput(inode);
4731c79a1751SLiu Bo 	}
4732bbc37d6eSFilipe Manana 	ASSERT(cache->io_ctl.pages == NULL);
4733c79a1751SLiu Bo 	btrfs_put_block_group(cache);
4734c79a1751SLiu Bo }
4735c79a1751SLiu Bo 
4736c79a1751SLiu Bo void btrfs_cleanup_dirty_bgs(struct btrfs_transaction *cur_trans,
47372ff7e61eSJeff Mahoney 			     struct btrfs_fs_info *fs_info)
4738c79a1751SLiu Bo {
473932da5386SDavid Sterba 	struct btrfs_block_group *cache;
4740c79a1751SLiu Bo 
4741c79a1751SLiu Bo 	spin_lock(&cur_trans->dirty_bgs_lock);
4742c79a1751SLiu Bo 	while (!list_empty(&cur_trans->dirty_bgs)) {
4743c79a1751SLiu Bo 		cache = list_first_entry(&cur_trans->dirty_bgs,
474432da5386SDavid Sterba 					 struct btrfs_block_group,
4745c79a1751SLiu Bo 					 dirty_list);
4746c79a1751SLiu Bo 
4747c79a1751SLiu Bo 		if (!list_empty(&cache->io_list)) {
4748c79a1751SLiu Bo 			spin_unlock(&cur_trans->dirty_bgs_lock);
4749c79a1751SLiu Bo 			list_del_init(&cache->io_list);
4750c79a1751SLiu Bo 			btrfs_cleanup_bg_io(cache);
4751c79a1751SLiu Bo 			spin_lock(&cur_trans->dirty_bgs_lock);
4752c79a1751SLiu Bo 		}
4753c79a1751SLiu Bo 
4754c79a1751SLiu Bo 		list_del_init(&cache->dirty_list);
4755c79a1751SLiu Bo 		spin_lock(&cache->lock);
4756c79a1751SLiu Bo 		cache->disk_cache_state = BTRFS_DC_ERROR;
4757c79a1751SLiu Bo 		spin_unlock(&cache->lock);
4758c79a1751SLiu Bo 
4759c79a1751SLiu Bo 		spin_unlock(&cur_trans->dirty_bgs_lock);
4760c79a1751SLiu Bo 		btrfs_put_block_group(cache);
4761ba2c4d4eSJosef Bacik 		btrfs_delayed_refs_rsv_release(fs_info, 1);
4762c79a1751SLiu Bo 		spin_lock(&cur_trans->dirty_bgs_lock);
4763c79a1751SLiu Bo 	}
4764c79a1751SLiu Bo 	spin_unlock(&cur_trans->dirty_bgs_lock);
4765c79a1751SLiu Bo 
476645ae2c18SNikolay Borisov 	/*
476745ae2c18SNikolay Borisov 	 * Refer to the definition of io_bgs member for details why it's safe
476845ae2c18SNikolay Borisov 	 * to use it without any locking
476945ae2c18SNikolay Borisov 	 */
4770c79a1751SLiu Bo 	while (!list_empty(&cur_trans->io_bgs)) {
4771c79a1751SLiu Bo 		cache = list_first_entry(&cur_trans->io_bgs,
477232da5386SDavid Sterba 					 struct btrfs_block_group,
4773c79a1751SLiu Bo 					 io_list);
4774c79a1751SLiu Bo 
4775c79a1751SLiu Bo 		list_del_init(&cache->io_list);
4776c79a1751SLiu Bo 		spin_lock(&cache->lock);
4777c79a1751SLiu Bo 		cache->disk_cache_state = BTRFS_DC_ERROR;
4778c79a1751SLiu Bo 		spin_unlock(&cache->lock);
4779c79a1751SLiu Bo 		btrfs_cleanup_bg_io(cache);
4780c79a1751SLiu Bo 	}
4781c79a1751SLiu Bo }
4782c79a1751SLiu Bo 
478349b25e05SJeff Mahoney void btrfs_cleanup_one_transaction(struct btrfs_transaction *cur_trans,
47842ff7e61eSJeff Mahoney 				   struct btrfs_fs_info *fs_info)
478549b25e05SJeff Mahoney {
4786bbbf7243SNikolay Borisov 	struct btrfs_device *dev, *tmp;
4787bbbf7243SNikolay Borisov 
47882ff7e61eSJeff Mahoney 	btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
4789c79a1751SLiu Bo 	ASSERT(list_empty(&cur_trans->dirty_bgs));
4790c79a1751SLiu Bo 	ASSERT(list_empty(&cur_trans->io_bgs));
4791c79a1751SLiu Bo 
4792bbbf7243SNikolay Borisov 	list_for_each_entry_safe(dev, tmp, &cur_trans->dev_update_list,
4793bbbf7243SNikolay Borisov 				 post_commit_list) {
4794bbbf7243SNikolay Borisov 		list_del_init(&dev->post_commit_list);
4795bbbf7243SNikolay Borisov 	}
4796bbbf7243SNikolay Borisov 
47972ff7e61eSJeff Mahoney 	btrfs_destroy_delayed_refs(cur_trans, fs_info);
479849b25e05SJeff Mahoney 
47994a9d8bdeSMiao Xie 	cur_trans->state = TRANS_STATE_COMMIT_START;
48000b246afaSJeff Mahoney 	wake_up(&fs_info->transaction_blocked_wait);
480149b25e05SJeff Mahoney 
48024a9d8bdeSMiao Xie 	cur_trans->state = TRANS_STATE_UNBLOCKED;
48030b246afaSJeff Mahoney 	wake_up(&fs_info->transaction_wait);
480449b25e05SJeff Mahoney 
4805ccdf9b30SJeff Mahoney 	btrfs_destroy_delayed_inodes(fs_info);
480667cde344SMiao Xie 
48072ff7e61eSJeff Mahoney 	btrfs_destroy_marked_extents(fs_info, &cur_trans->dirty_pages,
480849b25e05SJeff Mahoney 				     EXTENT_DIRTY);
4809fe119a6eSNikolay Borisov 	btrfs_destroy_pinned_extent(fs_info, &cur_trans->pinned_extents);
481049b25e05SJeff Mahoney 
4811d3575156SNaohiro Aota 	btrfs_free_redirty_list(cur_trans);
4812d3575156SNaohiro Aota 
48134a9d8bdeSMiao Xie 	cur_trans->state =TRANS_STATE_COMPLETED;
48144a9d8bdeSMiao Xie 	wake_up(&cur_trans->commit_wait);
481549b25e05SJeff Mahoney }
481649b25e05SJeff Mahoney 
48172ff7e61eSJeff Mahoney static int btrfs_cleanup_transaction(struct btrfs_fs_info *fs_info)
4818acce952bSliubo {
4819acce952bSliubo 	struct btrfs_transaction *t;
4820acce952bSliubo 
48210b246afaSJeff Mahoney 	mutex_lock(&fs_info->transaction_kthread_mutex);
4822acce952bSliubo 
48230b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
48240b246afaSJeff Mahoney 	while (!list_empty(&fs_info->trans_list)) {
48250b246afaSJeff Mahoney 		t = list_first_entry(&fs_info->trans_list,
4826724e2315SJosef Bacik 				     struct btrfs_transaction, list);
4827724e2315SJosef Bacik 		if (t->state >= TRANS_STATE_COMMIT_START) {
48289b64f57dSElena Reshetova 			refcount_inc(&t->use_count);
48290b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
48302ff7e61eSJeff Mahoney 			btrfs_wait_for_commit(fs_info, t->transid);
4831724e2315SJosef Bacik 			btrfs_put_transaction(t);
48320b246afaSJeff Mahoney 			spin_lock(&fs_info->trans_lock);
4833724e2315SJosef Bacik 			continue;
4834724e2315SJosef Bacik 		}
48350b246afaSJeff Mahoney 		if (t == fs_info->running_transaction) {
4836724e2315SJosef Bacik 			t->state = TRANS_STATE_COMMIT_DOING;
48370b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
4838724e2315SJosef Bacik 			/*
4839724e2315SJosef Bacik 			 * We wait for 0 num_writers since we don't hold a trans
4840724e2315SJosef Bacik 			 * handle open currently for this transaction.
4841724e2315SJosef Bacik 			 */
4842724e2315SJosef Bacik 			wait_event(t->writer_wait,
4843724e2315SJosef Bacik 				   atomic_read(&t->num_writers) == 0);
4844724e2315SJosef Bacik 		} else {
48450b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
4846724e2315SJosef Bacik 		}
48472ff7e61eSJeff Mahoney 		btrfs_cleanup_one_transaction(t, fs_info);
4848724e2315SJosef Bacik 
48490b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
48500b246afaSJeff Mahoney 		if (t == fs_info->running_transaction)
48510b246afaSJeff Mahoney 			fs_info->running_transaction = NULL;
4852724e2315SJosef Bacik 		list_del_init(&t->list);
48530b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
4854a4abeea4SJosef Bacik 
4855724e2315SJosef Bacik 		btrfs_put_transaction(t);
48562ff7e61eSJeff Mahoney 		trace_btrfs_transaction_commit(fs_info->tree_root);
48570b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
4858724e2315SJosef Bacik 	}
48590b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
48600b246afaSJeff Mahoney 	btrfs_destroy_all_ordered_extents(fs_info);
4861ccdf9b30SJeff Mahoney 	btrfs_destroy_delayed_inodes(fs_info);
4862ccdf9b30SJeff Mahoney 	btrfs_assert_delayed_root_empty(fs_info);
48630b246afaSJeff Mahoney 	btrfs_destroy_all_delalloc_inodes(fs_info);
4864ef67963dSJosef Bacik 	btrfs_drop_all_logs(fs_info);
48650b246afaSJeff Mahoney 	mutex_unlock(&fs_info->transaction_kthread_mutex);
4866acce952bSliubo 
4867acce952bSliubo 	return 0;
4868acce952bSliubo }
4869ec7d6dfdSNikolay Borisov 
4870453e4873SNikolay Borisov int btrfs_init_root_free_objectid(struct btrfs_root *root)
4871ec7d6dfdSNikolay Borisov {
4872ec7d6dfdSNikolay Borisov 	struct btrfs_path *path;
4873ec7d6dfdSNikolay Borisov 	int ret;
4874ec7d6dfdSNikolay Borisov 	struct extent_buffer *l;
4875ec7d6dfdSNikolay Borisov 	struct btrfs_key search_key;
4876ec7d6dfdSNikolay Borisov 	struct btrfs_key found_key;
4877ec7d6dfdSNikolay Borisov 	int slot;
4878ec7d6dfdSNikolay Borisov 
4879ec7d6dfdSNikolay Borisov 	path = btrfs_alloc_path();
4880ec7d6dfdSNikolay Borisov 	if (!path)
4881ec7d6dfdSNikolay Borisov 		return -ENOMEM;
4882ec7d6dfdSNikolay Borisov 
4883ec7d6dfdSNikolay Borisov 	search_key.objectid = BTRFS_LAST_FREE_OBJECTID;
4884ec7d6dfdSNikolay Borisov 	search_key.type = -1;
4885ec7d6dfdSNikolay Borisov 	search_key.offset = (u64)-1;
4886ec7d6dfdSNikolay Borisov 	ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
4887ec7d6dfdSNikolay Borisov 	if (ret < 0)
4888ec7d6dfdSNikolay Borisov 		goto error;
4889ec7d6dfdSNikolay Borisov 	BUG_ON(ret == 0); /* Corruption */
4890ec7d6dfdSNikolay Borisov 	if (path->slots[0] > 0) {
4891ec7d6dfdSNikolay Borisov 		slot = path->slots[0] - 1;
4892ec7d6dfdSNikolay Borisov 		l = path->nodes[0];
4893ec7d6dfdSNikolay Borisov 		btrfs_item_key_to_cpu(l, &found_key, slot);
489423125104SNikolay Borisov 		root->free_objectid = max_t(u64, found_key.objectid + 1,
489523125104SNikolay Borisov 					    BTRFS_FIRST_FREE_OBJECTID);
4896ec7d6dfdSNikolay Borisov 	} else {
489723125104SNikolay Borisov 		root->free_objectid = BTRFS_FIRST_FREE_OBJECTID;
4898ec7d6dfdSNikolay Borisov 	}
4899ec7d6dfdSNikolay Borisov 	ret = 0;
4900ec7d6dfdSNikolay Borisov error:
4901ec7d6dfdSNikolay Borisov 	btrfs_free_path(path);
4902ec7d6dfdSNikolay Borisov 	return ret;
4903ec7d6dfdSNikolay Borisov }
4904ec7d6dfdSNikolay Borisov 
4905543068a2SNikolay Borisov int btrfs_get_free_objectid(struct btrfs_root *root, u64 *objectid)
4906ec7d6dfdSNikolay Borisov {
4907ec7d6dfdSNikolay Borisov 	int ret;
4908ec7d6dfdSNikolay Borisov 	mutex_lock(&root->objectid_mutex);
4909ec7d6dfdSNikolay Borisov 
49106b8fad57SNikolay Borisov 	if (unlikely(root->free_objectid >= BTRFS_LAST_FREE_OBJECTID)) {
4911ec7d6dfdSNikolay Borisov 		btrfs_warn(root->fs_info,
4912ec7d6dfdSNikolay Borisov 			   "the objectid of root %llu reaches its highest value",
4913ec7d6dfdSNikolay Borisov 			   root->root_key.objectid);
4914ec7d6dfdSNikolay Borisov 		ret = -ENOSPC;
4915ec7d6dfdSNikolay Borisov 		goto out;
4916ec7d6dfdSNikolay Borisov 	}
4917ec7d6dfdSNikolay Borisov 
491823125104SNikolay Borisov 	*objectid = root->free_objectid++;
4919ec7d6dfdSNikolay Borisov 	ret = 0;
4920ec7d6dfdSNikolay Borisov out:
4921ec7d6dfdSNikolay Borisov 	mutex_unlock(&root->objectid_mutex);
4922ec7d6dfdSNikolay Borisov 	return ret;
4923ec7d6dfdSNikolay Borisov }
4924