xref: /openbmc/linux/fs/btrfs/disk-io.c (revision 576fa348)
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);
4620f805531SAlex Lyakas 	/*
4630f805531SAlex Lyakas 	 * Please do not consolidate these warnings into a single if.
4640f805531SAlex Lyakas 	 * It is useful to know what went wrong.
4650f805531SAlex Lyakas 	 */
4660f805531SAlex Lyakas 	if (WARN_ON(found_start != start))
4670f805531SAlex Lyakas 		return -EUCLEAN;
4680f805531SAlex Lyakas 	if (WARN_ON(!PageUptodate(page)))
4690f805531SAlex Lyakas 		return -EUCLEAN;
4700f805531SAlex Lyakas 
471de37aa51SNikolay Borisov 	ASSERT(memcmp_extent_buffer(eb, fs_info->fs_devices->metadata_uuid,
4729a8658e3SDavid Sterba 				    offsetof(struct btrfs_header, fsid),
4739a8658e3SDavid Sterba 				    BTRFS_FSID_SIZE) == 0);
4740f805531SAlex Lyakas 
475c67b3892SDavid Sterba 	csum_tree_block(eb, result);
4762996e1f8SJohannes Thumshirn 
4778d47a0d8SQu Wenruo 	if (btrfs_header_level(eb))
4788d47a0d8SQu Wenruo 		ret = btrfs_check_node(eb);
4798d47a0d8SQu Wenruo 	else
4808d47a0d8SQu Wenruo 		ret = btrfs_check_leaf_full(eb);
4818d47a0d8SQu Wenruo 
4828d47a0d8SQu Wenruo 	if (ret < 0) {
483c06631b0SQu Wenruo 		btrfs_print_tree(eb, 0);
4848d47a0d8SQu Wenruo 		btrfs_err(fs_info,
4858d47a0d8SQu Wenruo 		"block=%llu write time tree block corruption detected",
4868d47a0d8SQu Wenruo 			  eb->start);
487c06631b0SQu Wenruo 		WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
4888d47a0d8SQu Wenruo 		return ret;
4898d47a0d8SQu Wenruo 	}
490713cebfbSDavid Sterba 	write_extent_buffer(eb, result, 0, fs_info->csum_size);
4918d47a0d8SQu Wenruo 
4922996e1f8SJohannes Thumshirn 	return 0;
49319c00ddcSChris Mason }
49419c00ddcSChris Mason 
495b0c9b3b0SDavid Sterba static int check_tree_block_fsid(struct extent_buffer *eb)
4962b82032cSYan Zheng {
497b0c9b3b0SDavid Sterba 	struct btrfs_fs_info *fs_info = eb->fs_info;
498944d3f9fSNikolay Borisov 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices, *seed_devs;
49944880fdcSAnand Jain 	u8 fsid[BTRFS_FSID_SIZE];
500944d3f9fSNikolay Borisov 	u8 *metadata_uuid;
5012b82032cSYan Zheng 
5029a8658e3SDavid Sterba 	read_extent_buffer(eb, fsid, offsetof(struct btrfs_header, fsid),
5039a8658e3SDavid Sterba 			   BTRFS_FSID_SIZE);
5047239ff4bSNikolay Borisov 	/*
505944d3f9fSNikolay Borisov 	 * Checking the incompat flag is only valid for the current fs. For
506944d3f9fSNikolay Borisov 	 * seed devices it's forbidden to have their uuid changed so reading
507944d3f9fSNikolay Borisov 	 * ->fsid in this case is fine
5087239ff4bSNikolay Borisov 	 */
509944d3f9fSNikolay Borisov 	if (btrfs_fs_incompat(fs_info, METADATA_UUID))
5107239ff4bSNikolay Borisov 		metadata_uuid = fs_devices->metadata_uuid;
5117239ff4bSNikolay Borisov 	else
5127239ff4bSNikolay Borisov 		metadata_uuid = fs_devices->fsid;
5137239ff4bSNikolay Borisov 
514944d3f9fSNikolay Borisov 	if (!memcmp(fsid, metadata_uuid, BTRFS_FSID_SIZE))
515944d3f9fSNikolay Borisov 		return 0;
516944d3f9fSNikolay Borisov 
517944d3f9fSNikolay Borisov 	list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list)
518944d3f9fSNikolay Borisov 		if (!memcmp(fsid, seed_devs->fsid, BTRFS_FSID_SIZE))
519944d3f9fSNikolay Borisov 			return 0;
520944d3f9fSNikolay Borisov 
521944d3f9fSNikolay Borisov 	return 1;
5222b82032cSYan Zheng }
5232b82032cSYan Zheng 
52477bf40a2SQu Wenruo /* Do basic extent buffer checks at read time */
52577bf40a2SQu Wenruo static int validate_extent_buffer(struct extent_buffer *eb)
526ce9adaa5SChris Mason {
52777bf40a2SQu Wenruo 	struct btrfs_fs_info *fs_info = eb->fs_info;
528ce9adaa5SChris Mason 	u64 found_start;
52977bf40a2SQu Wenruo 	const u32 csum_size = fs_info->csum_size;
53077bf40a2SQu Wenruo 	u8 found_level;
5312996e1f8SJohannes Thumshirn 	u8 result[BTRFS_CSUM_SIZE];
53277bf40a2SQu Wenruo 	int ret = 0;
533ea466794SJosef Bacik 
534ce9adaa5SChris Mason 	found_start = btrfs_header_bytenr(eb);
535727011e0SChris Mason 	if (found_start != eb->start) {
536893bf4b1SSu Yue 		btrfs_err_rl(fs_info, "bad tree block start, want %llu have %llu",
537893bf4b1SSu Yue 			     eb->start, found_start);
538f188591eSChris Mason 		ret = -EIO;
53977bf40a2SQu Wenruo 		goto out;
540ce9adaa5SChris Mason 	}
541b0c9b3b0SDavid Sterba 	if (check_tree_block_fsid(eb)) {
54202873e43SZhao Lei 		btrfs_err_rl(fs_info, "bad fsid on block %llu",
54394647322SDavid Sterba 			     eb->start);
5441259ab75SChris Mason 		ret = -EIO;
54577bf40a2SQu Wenruo 		goto out;
5461259ab75SChris Mason 	}
547ce9adaa5SChris Mason 	found_level = btrfs_header_level(eb);
5481c24c3ceSJosef Bacik 	if (found_level >= BTRFS_MAX_LEVEL) {
549893bf4b1SSu Yue 		btrfs_err(fs_info, "bad tree block level %d on %llu",
550893bf4b1SSu Yue 			  (int)btrfs_header_level(eb), eb->start);
5511c24c3ceSJosef Bacik 		ret = -EIO;
55277bf40a2SQu Wenruo 		goto out;
5531c24c3ceSJosef Bacik 	}
554ce9adaa5SChris Mason 
555c67b3892SDavid Sterba 	csum_tree_block(eb, result);
556a826d6dcSJosef Bacik 
5572996e1f8SJohannes Thumshirn 	if (memcmp_extent_buffer(eb, result, 0, csum_size)) {
55835be8851SJohannes Thumshirn 		u8 val[BTRFS_CSUM_SIZE] = { 0 };
5592996e1f8SJohannes Thumshirn 
5602996e1f8SJohannes Thumshirn 		read_extent_buffer(eb, &val, 0, csum_size);
5612996e1f8SJohannes Thumshirn 		btrfs_warn_rl(fs_info,
56235be8851SJohannes Thumshirn 	"%s checksum verify failed on %llu wanted " CSUM_FMT " found " CSUM_FMT " level %d",
5632996e1f8SJohannes Thumshirn 			      fs_info->sb->s_id, eb->start,
56435be8851SJohannes Thumshirn 			      CSUM_FMT_VALUE(csum_size, val),
56535be8851SJohannes Thumshirn 			      CSUM_FMT_VALUE(csum_size, result),
56635be8851SJohannes Thumshirn 			      btrfs_header_level(eb));
5672996e1f8SJohannes Thumshirn 		ret = -EUCLEAN;
56877bf40a2SQu Wenruo 		goto out;
5692996e1f8SJohannes Thumshirn 	}
5702996e1f8SJohannes Thumshirn 
571a826d6dcSJosef Bacik 	/*
572a826d6dcSJosef Bacik 	 * If this is a leaf block and it is corrupt, set the corrupt bit so
573a826d6dcSJosef Bacik 	 * that we don't try and read the other copies of this block, just
574a826d6dcSJosef Bacik 	 * return -EIO.
575a826d6dcSJosef Bacik 	 */
5761c4360eeSDavid Sterba 	if (found_level == 0 && btrfs_check_leaf_full(eb)) {
577a826d6dcSJosef Bacik 		set_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags);
578a826d6dcSJosef Bacik 		ret = -EIO;
579a826d6dcSJosef Bacik 	}
580ce9adaa5SChris Mason 
581813fd1dcSDavid Sterba 	if (found_level > 0 && btrfs_check_node(eb))
582053ab70fSLiu Bo 		ret = -EIO;
583053ab70fSLiu Bo 
5840b32f4bbSJosef Bacik 	if (!ret)
5850b32f4bbSJosef Bacik 		set_extent_buffer_uptodate(eb);
58675391f0dSQu Wenruo 	else
58775391f0dSQu Wenruo 		btrfs_err(fs_info,
58875391f0dSQu Wenruo 			  "block=%llu read time tree block corruption detected",
58975391f0dSQu Wenruo 			  eb->start);
59077bf40a2SQu Wenruo out:
59177bf40a2SQu Wenruo 	return ret;
59277bf40a2SQu Wenruo }
59377bf40a2SQu Wenruo 
5948e1dc982SQu Wenruo int btrfs_validate_metadata_buffer(struct btrfs_io_bio *io_bio,
59577bf40a2SQu Wenruo 				   struct page *page, u64 start, u64 end,
59677bf40a2SQu Wenruo 				   int mirror)
59777bf40a2SQu Wenruo {
59877bf40a2SQu Wenruo 	struct extent_buffer *eb;
59977bf40a2SQu Wenruo 	int ret = 0;
60077bf40a2SQu Wenruo 	int reads_done;
60177bf40a2SQu Wenruo 
60277bf40a2SQu Wenruo 	ASSERT(page->private);
60377bf40a2SQu Wenruo 	eb = (struct extent_buffer *)page->private;
60477bf40a2SQu Wenruo 
60577bf40a2SQu Wenruo 	/*
60677bf40a2SQu Wenruo 	 * The pending IO might have been the only thing that kept this buffer
60777bf40a2SQu Wenruo 	 * in memory.  Make sure we have a ref for all this other checks
60877bf40a2SQu Wenruo 	 */
60977bf40a2SQu Wenruo 	atomic_inc(&eb->refs);
61077bf40a2SQu Wenruo 
61177bf40a2SQu Wenruo 	reads_done = atomic_dec_and_test(&eb->io_pages);
61277bf40a2SQu Wenruo 	if (!reads_done)
61377bf40a2SQu Wenruo 		goto err;
61477bf40a2SQu Wenruo 
61577bf40a2SQu Wenruo 	eb->read_mirror = mirror;
61677bf40a2SQu Wenruo 	if (test_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags)) {
61777bf40a2SQu Wenruo 		ret = -EIO;
61877bf40a2SQu Wenruo 		goto err;
61977bf40a2SQu Wenruo 	}
62077bf40a2SQu Wenruo 	ret = validate_extent_buffer(eb);
621ce9adaa5SChris Mason err:
62279fb65a1SJosef Bacik 	if (reads_done &&
62379fb65a1SJosef Bacik 	    test_and_clear_bit(EXTENT_BUFFER_READAHEAD, &eb->bflags))
624d48d71aaSDavid Sterba 		btree_readahead_hook(eb, ret);
6254bb31e92SArne Jansen 
62653b381b3SDavid Woodhouse 	if (ret) {
62753b381b3SDavid Woodhouse 		/*
62853b381b3SDavid Woodhouse 		 * our io error hook is going to dec the io pages
62953b381b3SDavid Woodhouse 		 * again, we have to make sure it has something
63053b381b3SDavid Woodhouse 		 * to decrement
63153b381b3SDavid Woodhouse 		 */
63253b381b3SDavid Woodhouse 		atomic_inc(&eb->io_pages);
6330b32f4bbSJosef Bacik 		clear_extent_buffer_uptodate(eb);
63453b381b3SDavid Woodhouse 	}
6350b32f4bbSJosef Bacik 	free_extent_buffer(eb);
63677bf40a2SQu Wenruo 
637f188591eSChris Mason 	return ret;
638ce9adaa5SChris Mason }
639ce9adaa5SChris Mason 
6404246a0b6SChristoph Hellwig static void end_workqueue_bio(struct bio *bio)
641ce9adaa5SChris Mason {
64297eb6b69SDavid Sterba 	struct btrfs_end_io_wq *end_io_wq = bio->bi_private;
643ce9adaa5SChris Mason 	struct btrfs_fs_info *fs_info;
6449e0af237SLiu Bo 	struct btrfs_workqueue *wq;
645ce9adaa5SChris Mason 
646ce9adaa5SChris Mason 	fs_info = end_io_wq->info;
6474e4cbee9SChristoph Hellwig 	end_io_wq->status = bio->bi_status;
648d20f7043SChris Mason 
64937226b21SMike Christie 	if (bio_op(bio) == REQ_OP_WRITE) {
650a0cac0ecSOmar Sandoval 		if (end_io_wq->metadata == BTRFS_WQ_ENDIO_METADATA)
6519e0af237SLiu Bo 			wq = fs_info->endio_meta_write_workers;
652a0cac0ecSOmar Sandoval 		else if (end_io_wq->metadata == BTRFS_WQ_ENDIO_FREE_SPACE)
6539e0af237SLiu Bo 			wq = fs_info->endio_freespace_worker;
654a0cac0ecSOmar Sandoval 		else if (end_io_wq->metadata == BTRFS_WQ_ENDIO_RAID56)
6559e0af237SLiu Bo 			wq = fs_info->endio_raid56_workers;
656a0cac0ecSOmar Sandoval 		else
6579e0af237SLiu Bo 			wq = fs_info->endio_write_workers;
6589e0af237SLiu Bo 	} else {
6595c047a69SOmar Sandoval 		if (end_io_wq->metadata == BTRFS_WQ_ENDIO_RAID56)
6609e0af237SLiu Bo 			wq = fs_info->endio_raid56_workers;
661a0cac0ecSOmar Sandoval 		else if (end_io_wq->metadata)
6629e0af237SLiu Bo 			wq = fs_info->endio_meta_workers;
663a0cac0ecSOmar Sandoval 		else
6649e0af237SLiu Bo 			wq = fs_info->endio_workers;
6659e0af237SLiu Bo 	}
6669e0af237SLiu Bo 
667a0cac0ecSOmar Sandoval 	btrfs_init_work(&end_io_wq->work, end_workqueue_fn, NULL, NULL);
6689e0af237SLiu Bo 	btrfs_queue_work(wq, &end_io_wq->work);
669ce9adaa5SChris Mason }
670ce9adaa5SChris Mason 
6714e4cbee9SChristoph Hellwig blk_status_t btrfs_bio_wq_end_io(struct btrfs_fs_info *info, struct bio *bio,
672bfebd8b5SDavid Sterba 			enum btrfs_wq_endio_type metadata)
6730b86a832SChris Mason {
67497eb6b69SDavid Sterba 	struct btrfs_end_io_wq *end_io_wq;
6758b110e39SMiao Xie 
67697eb6b69SDavid Sterba 	end_io_wq = kmem_cache_alloc(btrfs_end_io_wq_cache, GFP_NOFS);
677ce9adaa5SChris Mason 	if (!end_io_wq)
6784e4cbee9SChristoph Hellwig 		return BLK_STS_RESOURCE;
679ce9adaa5SChris Mason 
680ce9adaa5SChris Mason 	end_io_wq->private = bio->bi_private;
681ce9adaa5SChris Mason 	end_io_wq->end_io = bio->bi_end_io;
68222c59948SChris Mason 	end_io_wq->info = info;
6834e4cbee9SChristoph Hellwig 	end_io_wq->status = 0;
684ce9adaa5SChris Mason 	end_io_wq->bio = bio;
68522c59948SChris Mason 	end_io_wq->metadata = metadata;
686ce9adaa5SChris Mason 
687ce9adaa5SChris Mason 	bio->bi_private = end_io_wq;
688ce9adaa5SChris Mason 	bio->bi_end_io = end_workqueue_bio;
68922c59948SChris Mason 	return 0;
69022c59948SChris Mason }
69122c59948SChris Mason 
6924a69a410SChris Mason static void run_one_async_start(struct btrfs_work *work)
6934a69a410SChris Mason {
6944a69a410SChris Mason 	struct async_submit_bio *async;
6954e4cbee9SChristoph Hellwig 	blk_status_t ret;
6964a69a410SChris Mason 
6974a69a410SChris Mason 	async = container_of(work, struct  async_submit_bio, work);
6981941b64bSQu Wenruo 	ret = async->submit_bio_start(async->inode, async->bio,
6991941b64bSQu Wenruo 				      async->dio_file_offset);
70079787eaaSJeff Mahoney 	if (ret)
7014e4cbee9SChristoph Hellwig 		async->status = ret;
7024a69a410SChris Mason }
7034a69a410SChris Mason 
70406ea01b1SDavid Sterba /*
70506ea01b1SDavid Sterba  * In order to insert checksums into the metadata in large chunks, we wait
70606ea01b1SDavid Sterba  * until bio submission time.   All the pages in the bio are checksummed and
70706ea01b1SDavid Sterba  * sums are attached onto the ordered extent record.
70806ea01b1SDavid Sterba  *
70906ea01b1SDavid Sterba  * At IO completion time the csums attached on the ordered extent record are
71006ea01b1SDavid Sterba  * inserted into the tree.
71106ea01b1SDavid Sterba  */
7124a69a410SChris Mason static void run_one_async_done(struct btrfs_work *work)
7138b712842SChris Mason {
7148b712842SChris Mason 	struct async_submit_bio *async;
71506ea01b1SDavid Sterba 	struct inode *inode;
71606ea01b1SDavid Sterba 	blk_status_t ret;
7178b712842SChris Mason 
7188b712842SChris Mason 	async = container_of(work, struct  async_submit_bio, work);
7198896a08dSQu Wenruo 	inode = async->inode;
7204854ddd0SChris Mason 
721bb7ab3b9SAdam Buchbinder 	/* If an error occurred we just want to clean up the bio and move on */
7224e4cbee9SChristoph Hellwig 	if (async->status) {
7234e4cbee9SChristoph Hellwig 		async->bio->bi_status = async->status;
7244246a0b6SChristoph Hellwig 		bio_endio(async->bio);
72579787eaaSJeff Mahoney 		return;
72679787eaaSJeff Mahoney 	}
72779787eaaSJeff Mahoney 
728ec39f769SChris Mason 	/*
729ec39f769SChris Mason 	 * All of the bios that pass through here are from async helpers.
730ec39f769SChris Mason 	 * Use REQ_CGROUP_PUNT to issue them from the owning cgroup's context.
731ec39f769SChris Mason 	 * This changes nothing when cgroups aren't in use.
732ec39f769SChris Mason 	 */
733ec39f769SChris Mason 	async->bio->bi_opf |= REQ_CGROUP_PUNT;
73408635baeSChris Mason 	ret = btrfs_map_bio(btrfs_sb(inode->i_sb), async->bio, async->mirror_num);
73506ea01b1SDavid Sterba 	if (ret) {
73606ea01b1SDavid Sterba 		async->bio->bi_status = ret;
73706ea01b1SDavid Sterba 		bio_endio(async->bio);
73806ea01b1SDavid Sterba 	}
7394a69a410SChris Mason }
7404a69a410SChris Mason 
7414a69a410SChris Mason static void run_one_async_free(struct btrfs_work *work)
7424a69a410SChris Mason {
7434a69a410SChris Mason 	struct async_submit_bio *async;
7444a69a410SChris Mason 
7454a69a410SChris Mason 	async = container_of(work, struct  async_submit_bio, work);
7468b712842SChris Mason 	kfree(async);
7478b712842SChris Mason }
7488b712842SChris Mason 
7498896a08dSQu Wenruo blk_status_t btrfs_wq_submit_bio(struct inode *inode, struct bio *bio,
750c6100a4bSJosef Bacik 				 int mirror_num, unsigned long bio_flags,
7511941b64bSQu Wenruo 				 u64 dio_file_offset,
752e288c080SDavid Sterba 				 extent_submit_bio_start_t *submit_bio_start)
75344b8bd7eSChris Mason {
7548896a08dSQu Wenruo 	struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
75544b8bd7eSChris Mason 	struct async_submit_bio *async;
75644b8bd7eSChris Mason 
75744b8bd7eSChris Mason 	async = kmalloc(sizeof(*async), GFP_NOFS);
75844b8bd7eSChris Mason 	if (!async)
7594e4cbee9SChristoph Hellwig 		return BLK_STS_RESOURCE;
76044b8bd7eSChris Mason 
7618896a08dSQu Wenruo 	async->inode = inode;
76244b8bd7eSChris Mason 	async->bio = bio;
76344b8bd7eSChris Mason 	async->mirror_num = mirror_num;
7644a69a410SChris Mason 	async->submit_bio_start = submit_bio_start;
7654a69a410SChris Mason 
766a0cac0ecSOmar Sandoval 	btrfs_init_work(&async->work, run_one_async_start, run_one_async_done,
767a0cac0ecSOmar Sandoval 			run_one_async_free);
7684a69a410SChris Mason 
7691941b64bSQu Wenruo 	async->dio_file_offset = dio_file_offset;
7708c8bee1dSChris Mason 
7714e4cbee9SChristoph Hellwig 	async->status = 0;
77279787eaaSJeff Mahoney 
77367f055c7SChristoph Hellwig 	if (op_is_sync(bio->bi_opf))
7745cdc7ad3SQu Wenruo 		btrfs_set_work_high_priority(&async->work);
775d313d7a3SChris Mason 
7765cdc7ad3SQu Wenruo 	btrfs_queue_work(fs_info->workers, &async->work);
77744b8bd7eSChris Mason 	return 0;
77844b8bd7eSChris Mason }
77944b8bd7eSChris Mason 
7804e4cbee9SChristoph Hellwig static blk_status_t btree_csum_one_bio(struct bio *bio)
781ce3ed71aSChris Mason {
7822c30c71bSKent Overstreet 	struct bio_vec *bvec;
783ce3ed71aSChris Mason 	struct btrfs_root *root;
7842b070cfeSChristoph Hellwig 	int ret = 0;
7856dc4f100SMing Lei 	struct bvec_iter_all iter_all;
786ce3ed71aSChris Mason 
787c09abff8SDavid Sterba 	ASSERT(!bio_flagged(bio, BIO_CLONED));
7882b070cfeSChristoph Hellwig 	bio_for_each_segment_all(bvec, bio, iter_all) {
789ce3ed71aSChris Mason 		root = BTRFS_I(bvec->bv_page->mapping->host)->root;
790ac303b69SQu Wenruo 		ret = csum_dirty_buffer(root->fs_info, bvec);
79179787eaaSJeff Mahoney 		if (ret)
79279787eaaSJeff Mahoney 			break;
793ce3ed71aSChris Mason 	}
7942c30c71bSKent Overstreet 
7954e4cbee9SChristoph Hellwig 	return errno_to_blk_status(ret);
796ce3ed71aSChris Mason }
797ce3ed71aSChris Mason 
7988896a08dSQu Wenruo static blk_status_t btree_submit_bio_start(struct inode *inode, struct bio *bio,
7991941b64bSQu Wenruo 					   u64 dio_file_offset)
80022c59948SChris Mason {
8018b712842SChris Mason 	/*
8028b712842SChris Mason 	 * when we're called for a write, we're already in the async
8035443be45SChris Mason 	 * submission context.  Just jump into btrfs_map_bio
8048b712842SChris Mason 	 */
80579787eaaSJeff Mahoney 	return btree_csum_one_bio(bio);
80622c59948SChris Mason }
80722c59948SChris Mason 
8089b4e675aSDavid Sterba static int check_async_write(struct btrfs_fs_info *fs_info,
8099b4e675aSDavid Sterba 			     struct btrfs_inode *bi)
810de0022b9SJosef Bacik {
8116300463bSLiu Bo 	if (atomic_read(&bi->sync_writers))
8126300463bSLiu Bo 		return 0;
8139b4e675aSDavid Sterba 	if (test_bit(BTRFS_FS_CSUM_IMPL_FAST, &fs_info->flags))
814de0022b9SJosef Bacik 		return 0;
815de0022b9SJosef Bacik 	return 1;
816de0022b9SJosef Bacik }
817de0022b9SJosef Bacik 
8181b36294aSNikolay Borisov blk_status_t btrfs_submit_metadata_bio(struct inode *inode, struct bio *bio,
8191b36294aSNikolay Borisov 				       int mirror_num, unsigned long bio_flags)
82044b8bd7eSChris Mason {
8210b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8229b4e675aSDavid Sterba 	int async = check_async_write(fs_info, BTRFS_I(inode));
8234e4cbee9SChristoph Hellwig 	blk_status_t ret;
824cad321adSChris Mason 
82537226b21SMike Christie 	if (bio_op(bio) != REQ_OP_WRITE) {
826cad321adSChris Mason 		/*
827cad321adSChris Mason 		 * called for a read, do the setup so that checksum validation
828cad321adSChris Mason 		 * can happen in the async kernel threads
829cad321adSChris Mason 		 */
8300b246afaSJeff Mahoney 		ret = btrfs_bio_wq_end_io(fs_info, bio,
8310b246afaSJeff Mahoney 					  BTRFS_WQ_ENDIO_METADATA);
8321d4284bdSChris Mason 		if (ret)
83361891923SStefan Behrens 			goto out_w_error;
83408635baeSChris Mason 		ret = btrfs_map_bio(fs_info, bio, mirror_num);
835de0022b9SJosef Bacik 	} else if (!async) {
836de0022b9SJosef Bacik 		ret = btree_csum_one_bio(bio);
837de0022b9SJosef Bacik 		if (ret)
83861891923SStefan Behrens 			goto out_w_error;
83908635baeSChris Mason 		ret = btrfs_map_bio(fs_info, bio, mirror_num);
84061891923SStefan Behrens 	} else {
841cad321adSChris Mason 		/*
84261891923SStefan Behrens 		 * kthread helpers are used to submit writes so that
84361891923SStefan Behrens 		 * checksumming can happen in parallel across all CPUs
844cad321adSChris Mason 		 */
8458896a08dSQu Wenruo 		ret = btrfs_wq_submit_bio(inode, bio, mirror_num, 0,
8468896a08dSQu Wenruo 					  0, btree_submit_bio_start);
84744b8bd7eSChris Mason 	}
84844b8bd7eSChris Mason 
8494246a0b6SChristoph Hellwig 	if (ret)
8504246a0b6SChristoph Hellwig 		goto out_w_error;
8514246a0b6SChristoph Hellwig 	return 0;
8524246a0b6SChristoph Hellwig 
85361891923SStefan Behrens out_w_error:
8544e4cbee9SChristoph Hellwig 	bio->bi_status = ret;
8554246a0b6SChristoph Hellwig 	bio_endio(bio);
85661891923SStefan Behrens 	return ret;
85761891923SStefan Behrens }
85861891923SStefan Behrens 
8593dd1462eSJan Beulich #ifdef CONFIG_MIGRATION
860784b4e29SChris Mason static int btree_migratepage(struct address_space *mapping,
861a6bc32b8SMel Gorman 			struct page *newpage, struct page *page,
862a6bc32b8SMel Gorman 			enum migrate_mode mode)
863784b4e29SChris Mason {
864784b4e29SChris Mason 	/*
865784b4e29SChris Mason 	 * we can't safely write a btree page from here,
866784b4e29SChris Mason 	 * we haven't done the locking hook
867784b4e29SChris Mason 	 */
868784b4e29SChris Mason 	if (PageDirty(page))
869784b4e29SChris Mason 		return -EAGAIN;
870784b4e29SChris Mason 	/*
871784b4e29SChris Mason 	 * Buffers may be managed in a filesystem specific way.
872784b4e29SChris Mason 	 * We must have no buffers or drop them.
873784b4e29SChris Mason 	 */
874784b4e29SChris Mason 	if (page_has_private(page) &&
875784b4e29SChris Mason 	    !try_to_release_page(page, GFP_KERNEL))
876784b4e29SChris Mason 		return -EAGAIN;
877a6bc32b8SMel Gorman 	return migrate_page(mapping, newpage, page, mode);
878784b4e29SChris Mason }
8793dd1462eSJan Beulich #endif
880784b4e29SChris Mason 
8810da5468fSChris Mason 
8820da5468fSChris Mason static int btree_writepages(struct address_space *mapping,
8830da5468fSChris Mason 			    struct writeback_control *wbc)
8840da5468fSChris Mason {
885e2d84521SMiao Xie 	struct btrfs_fs_info *fs_info;
886e2d84521SMiao Xie 	int ret;
887e2d84521SMiao Xie 
888d8d5f3e1SChris Mason 	if (wbc->sync_mode == WB_SYNC_NONE) {
889448d640bSChris Mason 
890448d640bSChris Mason 		if (wbc->for_kupdate)
891448d640bSChris Mason 			return 0;
892448d640bSChris Mason 
893e2d84521SMiao Xie 		fs_info = BTRFS_I(mapping->host)->root->fs_info;
894b9473439SChris Mason 		/* this is a bit racy, but that's ok */
895d814a491SEthan Lien 		ret = __percpu_counter_compare(&fs_info->dirty_metadata_bytes,
896d814a491SEthan Lien 					     BTRFS_DIRTY_METADATA_THRESH,
897d814a491SEthan Lien 					     fs_info->dirty_metadata_batch);
898e2d84521SMiao Xie 		if (ret < 0)
899793955bcSChris Mason 			return 0;
900793955bcSChris Mason 	}
9010b32f4bbSJosef Bacik 	return btree_write_cache_pages(mapping, wbc);
9020da5468fSChris Mason }
9030da5468fSChris Mason 
90470dec807SChris Mason static int btree_releasepage(struct page *page, gfp_t gfp_flags)
9055f39d397SChris Mason {
90698509cfcSChris Mason 	if (PageWriteback(page) || PageDirty(page))
90798509cfcSChris Mason 		return 0;
9080c4e538bSDavid Sterba 
909f7a52a40SDavid Sterba 	return try_release_extent_buffer(page);
910d98237b3SChris Mason }
911d98237b3SChris Mason 
912d47992f8SLukas Czerner static void btree_invalidatepage(struct page *page, unsigned int offset,
913d47992f8SLukas Czerner 				 unsigned int length)
914d98237b3SChris Mason {
915d1310b2eSChris Mason 	struct extent_io_tree *tree;
916d1310b2eSChris Mason 	tree = &BTRFS_I(page->mapping->host)->io_tree;
9175f39d397SChris Mason 	extent_invalidatepage(tree, page, offset);
9185f39d397SChris Mason 	btree_releasepage(page, GFP_NOFS);
9199ad6b7bcSChris Mason 	if (PagePrivate(page)) {
920efe120a0SFrank Holton 		btrfs_warn(BTRFS_I(page->mapping->host)->root->fs_info,
921efe120a0SFrank Holton 			   "page private not zero on page %llu",
922efe120a0SFrank Holton 			   (unsigned long long)page_offset(page));
923d1b89bc0SGuoqing Jiang 		detach_page_private(page);
9249ad6b7bcSChris Mason 	}
925d98237b3SChris Mason }
926d98237b3SChris Mason 
9270b32f4bbSJosef Bacik static int btree_set_page_dirty(struct page *page)
9280b32f4bbSJosef Bacik {
929bb146eb2SJosef Bacik #ifdef DEBUG
9300b32f4bbSJosef Bacik 	struct extent_buffer *eb;
9310b32f4bbSJosef Bacik 
9320b32f4bbSJosef Bacik 	BUG_ON(!PagePrivate(page));
9330b32f4bbSJosef Bacik 	eb = (struct extent_buffer *)page->private;
9340b32f4bbSJosef Bacik 	BUG_ON(!eb);
9350b32f4bbSJosef Bacik 	BUG_ON(!test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
9360b32f4bbSJosef Bacik 	BUG_ON(!atomic_read(&eb->refs));
9370b32f4bbSJosef Bacik 	btrfs_assert_tree_locked(eb);
938bb146eb2SJosef Bacik #endif
9390b32f4bbSJosef Bacik 	return __set_page_dirty_nobuffers(page);
9400b32f4bbSJosef Bacik }
9410b32f4bbSJosef Bacik 
9427f09410bSAlexey Dobriyan static const struct address_space_operations btree_aops = {
9430da5468fSChris Mason 	.writepages	= btree_writepages,
9445f39d397SChris Mason 	.releasepage	= btree_releasepage,
9455f39d397SChris Mason 	.invalidatepage = btree_invalidatepage,
9465a92bc88SChris Mason #ifdef CONFIG_MIGRATION
947784b4e29SChris Mason 	.migratepage	= btree_migratepage,
9485a92bc88SChris Mason #endif
9490b32f4bbSJosef Bacik 	.set_page_dirty = btree_set_page_dirty,
950d98237b3SChris Mason };
951123abc88SChris Mason 
9522ff7e61eSJeff Mahoney struct extent_buffer *btrfs_find_create_tree_block(
9532ff7e61eSJeff Mahoney 						struct btrfs_fs_info *fs_info,
9543fbaf258SJosef Bacik 						u64 bytenr, u64 owner_root,
9553fbaf258SJosef Bacik 						int level)
9560999df54SChris Mason {
9570b246afaSJeff Mahoney 	if (btrfs_is_testing(fs_info))
9580b246afaSJeff Mahoney 		return alloc_test_extent_buffer(fs_info, bytenr);
9593fbaf258SJosef Bacik 	return alloc_extent_buffer(fs_info, bytenr, owner_root, level);
9600999df54SChris Mason }
9610999df54SChris Mason 
962581c1760SQu Wenruo /*
963581c1760SQu Wenruo  * Read tree block at logical address @bytenr and do variant basic but critical
964581c1760SQu Wenruo  * verification.
965581c1760SQu Wenruo  *
9661b7ec85eSJosef Bacik  * @owner_root:		the objectid of the root owner for this block.
967581c1760SQu Wenruo  * @parent_transid:	expected transid of this tree block, skip check if 0
968581c1760SQu Wenruo  * @level:		expected level, mandatory check
969581c1760SQu Wenruo  * @first_key:		expected key in slot 0, skip check if NULL
970581c1760SQu Wenruo  */
9712ff7e61eSJeff Mahoney struct extent_buffer *read_tree_block(struct btrfs_fs_info *fs_info, u64 bytenr,
9721b7ec85eSJosef Bacik 				      u64 owner_root, u64 parent_transid,
9731b7ec85eSJosef Bacik 				      int level, struct btrfs_key *first_key)
974e20d96d6SChris Mason {
9755f39d397SChris Mason 	struct extent_buffer *buf = NULL;
97619c00ddcSChris Mason 	int ret;
97719c00ddcSChris Mason 
9783fbaf258SJosef Bacik 	buf = btrfs_find_create_tree_block(fs_info, bytenr, owner_root, level);
979c871b0f2SLiu Bo 	if (IS_ERR(buf))
980c871b0f2SLiu Bo 		return buf;
981e4204dedSChris Mason 
9825ab12d1fSDavid Sterba 	ret = btree_read_extent_buffer_pages(buf, parent_transid,
983581c1760SQu Wenruo 					     level, first_key);
9840f0fe8f7SFilipe David Borba Manana 	if (ret) {
985537f38f0SNikolay Borisov 		free_extent_buffer_stale(buf);
98664c043deSLiu Bo 		return ERR_PTR(ret);
9870f0fe8f7SFilipe David Borba Manana 	}
9885f39d397SChris Mason 	return buf;
989ce9adaa5SChris Mason 
990eb60ceacSChris Mason }
991eb60ceacSChris Mason 
9926a884d7dSDavid Sterba void btrfs_clean_tree_block(struct extent_buffer *buf)
993ed2ff2cbSChris Mason {
9946a884d7dSDavid Sterba 	struct btrfs_fs_info *fs_info = buf->fs_info;
99555c69072SChris Mason 	if (btrfs_header_generation(buf) ==
996e2d84521SMiao Xie 	    fs_info->running_transaction->transid) {
997b9447ef8SChris Mason 		btrfs_assert_tree_locked(buf);
998b4ce94deSChris Mason 
999b9473439SChris Mason 		if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &buf->bflags)) {
1000104b4e51SNikolay Borisov 			percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
1001e2d84521SMiao Xie 						 -buf->len,
1002e2d84521SMiao Xie 						 fs_info->dirty_metadata_batch);
10030b32f4bbSJosef Bacik 			clear_extent_buffer_dirty(buf);
1004925baeddSChris Mason 		}
10055f39d397SChris Mason 	}
1006ed7b63ebSJosef Bacik }
10075f39d397SChris Mason 
1008da17066cSJeff Mahoney static void __setup_root(struct btrfs_root *root, struct btrfs_fs_info *fs_info,
1009e20d96d6SChris Mason 			 u64 objectid)
1010d97e63b6SChris Mason {
10117c0260eeSJeff Mahoney 	bool dummy = test_bit(BTRFS_FS_STATE_DUMMY_FS_INFO, &fs_info->fs_state);
101296dfcb46SJosef Bacik 	root->fs_info = fs_info;
1013cfaa7295SChris Mason 	root->node = NULL;
1014a28ec197SChris Mason 	root->commit_root = NULL;
101527cdeb70SMiao Xie 	root->state = 0;
1016d68fc57bSYan, Zheng 	root->orphan_cleanup_state = 0;
10170b86a832SChris Mason 
10180f7d52f4SChris Mason 	root->last_trans = 0;
10196b8fad57SNikolay Borisov 	root->free_objectid = 0;
1020eb73c1b7SMiao Xie 	root->nr_delalloc_inodes = 0;
1021199c2a9cSMiao Xie 	root->nr_ordered_extents = 0;
10226bef4d31SEric Paris 	root->inode_tree = RB_ROOT;
102316cdcec7SMiao Xie 	INIT_RADIX_TREE(&root->delayed_nodes_tree, GFP_ATOMIC);
1024f0486c68SYan, Zheng 	root->block_rsv = NULL;
10250b86a832SChris Mason 
10260b86a832SChris Mason 	INIT_LIST_HEAD(&root->dirty_list);
10275d4f98a2SYan Zheng 	INIT_LIST_HEAD(&root->root_list);
1028eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&root->delalloc_inodes);
1029eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&root->delalloc_root);
1030199c2a9cSMiao Xie 	INIT_LIST_HEAD(&root->ordered_extents);
1031199c2a9cSMiao Xie 	INIT_LIST_HEAD(&root->ordered_root);
1032d2311e69SQu Wenruo 	INIT_LIST_HEAD(&root->reloc_dirty_list);
10332ab28f32SJosef Bacik 	INIT_LIST_HEAD(&root->logged_list[0]);
10342ab28f32SJosef Bacik 	INIT_LIST_HEAD(&root->logged_list[1]);
10355d4f98a2SYan Zheng 	spin_lock_init(&root->inode_lock);
1036eb73c1b7SMiao Xie 	spin_lock_init(&root->delalloc_lock);
1037199c2a9cSMiao Xie 	spin_lock_init(&root->ordered_extent_lock);
1038f0486c68SYan, Zheng 	spin_lock_init(&root->accounting_lock);
10392ab28f32SJosef Bacik 	spin_lock_init(&root->log_extents_lock[0]);
10402ab28f32SJosef Bacik 	spin_lock_init(&root->log_extents_lock[1]);
10418287475aSQu Wenruo 	spin_lock_init(&root->qgroup_meta_rsv_lock);
1042a2135011SChris Mason 	mutex_init(&root->objectid_mutex);
1043e02119d5SChris Mason 	mutex_init(&root->log_mutex);
104431f3d255SMiao Xie 	mutex_init(&root->ordered_extent_mutex);
1045573bfb72SMiao Xie 	mutex_init(&root->delalloc_mutex);
1046c53e9653SQu Wenruo 	init_waitqueue_head(&root->qgroup_flush_wait);
10477237f183SYan Zheng 	init_waitqueue_head(&root->log_writer_wait);
10487237f183SYan Zheng 	init_waitqueue_head(&root->log_commit_wait[0]);
10497237f183SYan Zheng 	init_waitqueue_head(&root->log_commit_wait[1]);
10508b050d35SMiao Xie 	INIT_LIST_HEAD(&root->log_ctxs[0]);
10518b050d35SMiao Xie 	INIT_LIST_HEAD(&root->log_ctxs[1]);
10527237f183SYan Zheng 	atomic_set(&root->log_commit[0], 0);
10537237f183SYan Zheng 	atomic_set(&root->log_commit[1], 0);
10547237f183SYan Zheng 	atomic_set(&root->log_writers, 0);
10552ecb7923SMiao Xie 	atomic_set(&root->log_batch, 0);
10560700cea7SElena Reshetova 	refcount_set(&root->refs, 1);
10578ecebf4dSRobbie Ko 	atomic_set(&root->snapshot_force_cow, 0);
1058eede2bf3SOmar Sandoval 	atomic_set(&root->nr_swapfiles, 0);
10597237f183SYan Zheng 	root->log_transid = 0;
1060d1433debSMiao Xie 	root->log_transid_committed = -1;
1061257c62e1SChris Mason 	root->last_log_commit = 0;
1062e289f03eSFilipe Manana 	if (!dummy) {
106343eb5f29SQu Wenruo 		extent_io_tree_init(fs_info, &root->dirty_log_pages,
106443eb5f29SQu Wenruo 				    IO_TREE_ROOT_DIRTY_LOG_PAGES, NULL);
1065e289f03eSFilipe Manana 		extent_io_tree_init(fs_info, &root->log_csum_range,
1066e289f03eSFilipe Manana 				    IO_TREE_LOG_CSUM_RANGE, NULL);
1067e289f03eSFilipe Manana 	}
1068017e5369SChris Mason 
10693768f368SChris Mason 	memset(&root->root_key, 0, sizeof(root->root_key));
10703768f368SChris Mason 	memset(&root->root_item, 0, sizeof(root->root_item));
10716702ed49SChris Mason 	memset(&root->defrag_progress, 0, sizeof(root->defrag_progress));
10724d775673SChris Mason 	root->root_key.objectid = objectid;
10730ee5dc67SAl Viro 	root->anon_dev = 0;
10748ea05e3aSAlexander Block 
10755f3ab90aSAnand Jain 	spin_lock_init(&root->root_item_lock);
1076370a11b8SQu Wenruo 	btrfs_qgroup_init_swapped_blocks(&root->swapped_blocks);
1077bd647ce3SJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
1078bd647ce3SJosef Bacik 	INIT_LIST_HEAD(&root->leak_list);
1079bd647ce3SJosef Bacik 	spin_lock(&fs_info->fs_roots_radix_lock);
1080bd647ce3SJosef Bacik 	list_add_tail(&root->leak_list, &fs_info->allocated_roots);
1081bd647ce3SJosef Bacik 	spin_unlock(&fs_info->fs_roots_radix_lock);
1082bd647ce3SJosef Bacik #endif
10833768f368SChris Mason }
10843768f368SChris Mason 
108574e4d827SDavid Sterba static struct btrfs_root *btrfs_alloc_root(struct btrfs_fs_info *fs_info,
108696dfcb46SJosef Bacik 					   u64 objectid, gfp_t flags)
10876f07e42eSAl Viro {
108874e4d827SDavid Sterba 	struct btrfs_root *root = kzalloc(sizeof(*root), flags);
10896f07e42eSAl Viro 	if (root)
109096dfcb46SJosef Bacik 		__setup_root(root, fs_info, objectid);
10916f07e42eSAl Viro 	return root;
10926f07e42eSAl Viro }
10936f07e42eSAl Viro 
109406ea65a3SJosef Bacik #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
109506ea65a3SJosef Bacik /* Should only be used by the testing infrastructure */
1096da17066cSJeff Mahoney struct btrfs_root *btrfs_alloc_dummy_root(struct btrfs_fs_info *fs_info)
109706ea65a3SJosef Bacik {
109806ea65a3SJosef Bacik 	struct btrfs_root *root;
109906ea65a3SJosef Bacik 
11007c0260eeSJeff Mahoney 	if (!fs_info)
11017c0260eeSJeff Mahoney 		return ERR_PTR(-EINVAL);
11027c0260eeSJeff Mahoney 
110396dfcb46SJosef Bacik 	root = btrfs_alloc_root(fs_info, BTRFS_ROOT_TREE_OBJECTID, GFP_KERNEL);
110406ea65a3SJosef Bacik 	if (!root)
110506ea65a3SJosef Bacik 		return ERR_PTR(-ENOMEM);
1106da17066cSJeff Mahoney 
1107b9ef22deSFeifei Xu 	/* We don't use the stripesize in selftest, set it as sectorsize */
1108faa2dbf0SJosef Bacik 	root->alloc_bytenr = 0;
110906ea65a3SJosef Bacik 
111006ea65a3SJosef Bacik 	return root;
111106ea65a3SJosef Bacik }
111206ea65a3SJosef Bacik #endif
111306ea65a3SJosef Bacik 
111420897f5cSArne Jansen struct btrfs_root *btrfs_create_tree(struct btrfs_trans_handle *trans,
111520897f5cSArne Jansen 				     u64 objectid)
111620897f5cSArne Jansen {
11179b7a2440SDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
111820897f5cSArne Jansen 	struct extent_buffer *leaf;
111920897f5cSArne Jansen 	struct btrfs_root *tree_root = fs_info->tree_root;
112020897f5cSArne Jansen 	struct btrfs_root *root;
112120897f5cSArne Jansen 	struct btrfs_key key;
1122b89f6d1fSFilipe Manana 	unsigned int nofs_flag;
112320897f5cSArne Jansen 	int ret = 0;
112420897f5cSArne Jansen 
1125b89f6d1fSFilipe Manana 	/*
1126b89f6d1fSFilipe Manana 	 * We're holding a transaction handle, so use a NOFS memory allocation
1127b89f6d1fSFilipe Manana 	 * context to avoid deadlock if reclaim happens.
1128b89f6d1fSFilipe Manana 	 */
1129b89f6d1fSFilipe Manana 	nofs_flag = memalloc_nofs_save();
113096dfcb46SJosef Bacik 	root = btrfs_alloc_root(fs_info, objectid, GFP_KERNEL);
1131b89f6d1fSFilipe Manana 	memalloc_nofs_restore(nofs_flag);
113220897f5cSArne Jansen 	if (!root)
113320897f5cSArne Jansen 		return ERR_PTR(-ENOMEM);
113420897f5cSArne Jansen 
113520897f5cSArne Jansen 	root->root_key.objectid = objectid;
113620897f5cSArne Jansen 	root->root_key.type = BTRFS_ROOT_ITEM_KEY;
113720897f5cSArne Jansen 	root->root_key.offset = 0;
113820897f5cSArne Jansen 
11399631e4ccSJosef Bacik 	leaf = btrfs_alloc_tree_block(trans, root, 0, objectid, NULL, 0, 0, 0,
11409631e4ccSJosef Bacik 				      BTRFS_NESTING_NORMAL);
114120897f5cSArne Jansen 	if (IS_ERR(leaf)) {
114220897f5cSArne Jansen 		ret = PTR_ERR(leaf);
11431dd05682STsutomu Itoh 		leaf = NULL;
11448a6a87cdSBoris Burkov 		goto fail_unlock;
114520897f5cSArne Jansen 	}
114620897f5cSArne Jansen 
114720897f5cSArne Jansen 	root->node = leaf;
114820897f5cSArne Jansen 	btrfs_mark_buffer_dirty(leaf);
114920897f5cSArne Jansen 
115020897f5cSArne Jansen 	root->commit_root = btrfs_root_node(root);
115127cdeb70SMiao Xie 	set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
115220897f5cSArne Jansen 
1153f944d2cbSDavid Sterba 	btrfs_set_root_flags(&root->root_item, 0);
1154f944d2cbSDavid Sterba 	btrfs_set_root_limit(&root->root_item, 0);
115520897f5cSArne Jansen 	btrfs_set_root_bytenr(&root->root_item, leaf->start);
115620897f5cSArne Jansen 	btrfs_set_root_generation(&root->root_item, trans->transid);
115720897f5cSArne Jansen 	btrfs_set_root_level(&root->root_item, 0);
115820897f5cSArne Jansen 	btrfs_set_root_refs(&root->root_item, 1);
115920897f5cSArne Jansen 	btrfs_set_root_used(&root->root_item, leaf->len);
116020897f5cSArne Jansen 	btrfs_set_root_last_snapshot(&root->root_item, 0);
116120897f5cSArne Jansen 	btrfs_set_root_dirid(&root->root_item, 0);
116233d85fdaSQu Wenruo 	if (is_fstree(objectid))
1163807fc790SAndy Shevchenko 		generate_random_guid(root->root_item.uuid);
1164807fc790SAndy Shevchenko 	else
1165807fc790SAndy Shevchenko 		export_guid(root->root_item.uuid, &guid_null);
1166c8422684SDavid Sterba 	btrfs_set_root_drop_level(&root->root_item, 0);
116720897f5cSArne Jansen 
11688a6a87cdSBoris Burkov 	btrfs_tree_unlock(leaf);
11698a6a87cdSBoris Burkov 
117020897f5cSArne Jansen 	key.objectid = objectid;
117120897f5cSArne Jansen 	key.type = BTRFS_ROOT_ITEM_KEY;
117220897f5cSArne Jansen 	key.offset = 0;
117320897f5cSArne Jansen 	ret = btrfs_insert_root(trans, tree_root, &key, &root->root_item);
117420897f5cSArne Jansen 	if (ret)
117520897f5cSArne Jansen 		goto fail;
117620897f5cSArne Jansen 
117720897f5cSArne Jansen 	return root;
11781dd05682STsutomu Itoh 
11798a6a87cdSBoris Burkov fail_unlock:
11808c38938cSJosef Bacik 	if (leaf)
11811dd05682STsutomu Itoh 		btrfs_tree_unlock(leaf);
11828a6a87cdSBoris Burkov fail:
118300246528SJosef Bacik 	btrfs_put_root(root);
11841dd05682STsutomu Itoh 
11851dd05682STsutomu Itoh 	return ERR_PTR(ret);
118620897f5cSArne Jansen }
118720897f5cSArne Jansen 
11887237f183SYan Zheng static struct btrfs_root *alloc_log_tree(struct btrfs_trans_handle *trans,
1189e02119d5SChris Mason 					 struct btrfs_fs_info *fs_info)
11900f7d52f4SChris Mason {
11910f7d52f4SChris Mason 	struct btrfs_root *root;
11927237f183SYan Zheng 	struct extent_buffer *leaf;
1193e02119d5SChris Mason 
119496dfcb46SJosef Bacik 	root = btrfs_alloc_root(fs_info, BTRFS_TREE_LOG_OBJECTID, GFP_NOFS);
1195e02119d5SChris Mason 	if (!root)
11967237f183SYan Zheng 		return ERR_PTR(-ENOMEM);
1197e02119d5SChris Mason 
1198e02119d5SChris Mason 	root->root_key.objectid = BTRFS_TREE_LOG_OBJECTID;
1199e02119d5SChris Mason 	root->root_key.type = BTRFS_ROOT_ITEM_KEY;
1200e02119d5SChris Mason 	root->root_key.offset = BTRFS_TREE_LOG_OBJECTID;
120127cdeb70SMiao Xie 
12027237f183SYan Zheng 	/*
120392a7cc42SQu Wenruo 	 * DON'T set SHAREABLE bit for log trees.
120427cdeb70SMiao Xie 	 *
120592a7cc42SQu Wenruo 	 * Log trees are not exposed to user space thus can't be snapshotted,
120692a7cc42SQu Wenruo 	 * and they go away before a real commit is actually done.
120792a7cc42SQu Wenruo 	 *
120892a7cc42SQu Wenruo 	 * They do store pointers to file data extents, and those reference
120992a7cc42SQu Wenruo 	 * counts still get updated (along with back refs to the log tree).
12107237f183SYan Zheng 	 */
1211e02119d5SChris Mason 
12124d75f8a9SDavid Sterba 	leaf = btrfs_alloc_tree_block(trans, root, 0, BTRFS_TREE_LOG_OBJECTID,
12139631e4ccSJosef Bacik 			NULL, 0, 0, 0, BTRFS_NESTING_NORMAL);
12147237f183SYan Zheng 	if (IS_ERR(leaf)) {
121500246528SJosef Bacik 		btrfs_put_root(root);
12167237f183SYan Zheng 		return ERR_CAST(leaf);
12177237f183SYan Zheng 	}
1218e02119d5SChris Mason 
12197237f183SYan Zheng 	root->node = leaf;
1220e02119d5SChris Mason 
1221e02119d5SChris Mason 	btrfs_mark_buffer_dirty(root->node);
1222e02119d5SChris Mason 	btrfs_tree_unlock(root->node);
12237237f183SYan Zheng 	return root;
12247237f183SYan Zheng }
12257237f183SYan Zheng 
12267237f183SYan Zheng int btrfs_init_log_root_tree(struct btrfs_trans_handle *trans,
12277237f183SYan Zheng 			     struct btrfs_fs_info *fs_info)
12287237f183SYan Zheng {
12297237f183SYan Zheng 	struct btrfs_root *log_root;
12307237f183SYan Zheng 
12317237f183SYan Zheng 	log_root = alloc_log_tree(trans, fs_info);
12327237f183SYan Zheng 	if (IS_ERR(log_root))
12337237f183SYan Zheng 		return PTR_ERR(log_root);
12347237f183SYan Zheng 	WARN_ON(fs_info->log_root_tree);
12357237f183SYan Zheng 	fs_info->log_root_tree = log_root;
12367237f183SYan Zheng 	return 0;
12377237f183SYan Zheng }
12387237f183SYan Zheng 
12397237f183SYan Zheng int btrfs_add_log_tree(struct btrfs_trans_handle *trans,
12407237f183SYan Zheng 		       struct btrfs_root *root)
12417237f183SYan Zheng {
12420b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
12437237f183SYan Zheng 	struct btrfs_root *log_root;
12447237f183SYan Zheng 	struct btrfs_inode_item *inode_item;
12457237f183SYan Zheng 
12460b246afaSJeff Mahoney 	log_root = alloc_log_tree(trans, fs_info);
12477237f183SYan Zheng 	if (IS_ERR(log_root))
12487237f183SYan Zheng 		return PTR_ERR(log_root);
12497237f183SYan Zheng 
12507237f183SYan Zheng 	log_root->last_trans = trans->transid;
12517237f183SYan Zheng 	log_root->root_key.offset = root->root_key.objectid;
12527237f183SYan Zheng 
12537237f183SYan Zheng 	inode_item = &log_root->root_item.inode;
12543cae210fSQu Wenruo 	btrfs_set_stack_inode_generation(inode_item, 1);
12553cae210fSQu Wenruo 	btrfs_set_stack_inode_size(inode_item, 3);
12563cae210fSQu Wenruo 	btrfs_set_stack_inode_nlink(inode_item, 1);
1257da17066cSJeff Mahoney 	btrfs_set_stack_inode_nbytes(inode_item,
12580b246afaSJeff Mahoney 				     fs_info->nodesize);
12593cae210fSQu Wenruo 	btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
12607237f183SYan Zheng 
12615d4f98a2SYan Zheng 	btrfs_set_root_node(&log_root->root_item, log_root->node);
12627237f183SYan Zheng 
12637237f183SYan Zheng 	WARN_ON(root->log_root);
12647237f183SYan Zheng 	root->log_root = log_root;
12657237f183SYan Zheng 	root->log_transid = 0;
1266d1433debSMiao Xie 	root->log_transid_committed = -1;
1267257c62e1SChris Mason 	root->last_log_commit = 0;
1268e02119d5SChris Mason 	return 0;
1269e02119d5SChris Mason }
1270e02119d5SChris Mason 
127149d11beaSJosef Bacik static struct btrfs_root *read_tree_root_path(struct btrfs_root *tree_root,
127249d11beaSJosef Bacik 					      struct btrfs_path *path,
1273cb517eabSMiao Xie 					      struct btrfs_key *key)
1274e02119d5SChris Mason {
1275e02119d5SChris Mason 	struct btrfs_root *root;
1276e02119d5SChris Mason 	struct btrfs_fs_info *fs_info = tree_root->fs_info;
127784234f3aSYan Zheng 	u64 generation;
1278cb517eabSMiao Xie 	int ret;
1279581c1760SQu Wenruo 	int level;
1280cb517eabSMiao Xie 
128196dfcb46SJosef Bacik 	root = btrfs_alloc_root(fs_info, key->objectid, GFP_NOFS);
128249d11beaSJosef Bacik 	if (!root)
128349d11beaSJosef Bacik 		return ERR_PTR(-ENOMEM);
12840f7d52f4SChris Mason 
1285cb517eabSMiao Xie 	ret = btrfs_find_root(tree_root, key, path,
1286cb517eabSMiao Xie 			      &root->root_item, &root->root_key);
12870f7d52f4SChris Mason 	if (ret) {
128813a8a7c8SYan, Zheng 		if (ret > 0)
128913a8a7c8SYan, Zheng 			ret = -ENOENT;
129049d11beaSJosef Bacik 		goto fail;
12910f7d52f4SChris Mason 	}
129213a8a7c8SYan, Zheng 
129384234f3aSYan Zheng 	generation = btrfs_root_generation(&root->root_item);
1294581c1760SQu Wenruo 	level = btrfs_root_level(&root->root_item);
12952ff7e61eSJeff Mahoney 	root->node = read_tree_block(fs_info,
12962ff7e61eSJeff Mahoney 				     btrfs_root_bytenr(&root->root_item),
12971b7ec85eSJosef Bacik 				     key->objectid, generation, level, NULL);
129864c043deSLiu Bo 	if (IS_ERR(root->node)) {
129964c043deSLiu Bo 		ret = PTR_ERR(root->node);
13008c38938cSJosef Bacik 		root->node = NULL;
130149d11beaSJosef Bacik 		goto fail;
1302cb517eabSMiao Xie 	} else if (!btrfs_buffer_uptodate(root->node, generation, 0)) {
1303cb517eabSMiao Xie 		ret = -EIO;
130449d11beaSJosef Bacik 		goto fail;
1305416bc658SJosef Bacik 	}
13065d4f98a2SYan Zheng 	root->commit_root = btrfs_root_node(root);
1307cb517eabSMiao Xie 	return root;
130849d11beaSJosef Bacik fail:
130900246528SJosef Bacik 	btrfs_put_root(root);
131049d11beaSJosef Bacik 	return ERR_PTR(ret);
131149d11beaSJosef Bacik }
131249d11beaSJosef Bacik 
131349d11beaSJosef Bacik struct btrfs_root *btrfs_read_tree_root(struct btrfs_root *tree_root,
131449d11beaSJosef Bacik 					struct btrfs_key *key)
131549d11beaSJosef Bacik {
131649d11beaSJosef Bacik 	struct btrfs_root *root;
131749d11beaSJosef Bacik 	struct btrfs_path *path;
131849d11beaSJosef Bacik 
131949d11beaSJosef Bacik 	path = btrfs_alloc_path();
132049d11beaSJosef Bacik 	if (!path)
132149d11beaSJosef Bacik 		return ERR_PTR(-ENOMEM);
132249d11beaSJosef Bacik 	root = read_tree_root_path(tree_root, path, key);
132349d11beaSJosef Bacik 	btrfs_free_path(path);
132449d11beaSJosef Bacik 
132549d11beaSJosef Bacik 	return root;
1326cb517eabSMiao Xie }
1327cb517eabSMiao Xie 
13282dfb1e43SQu Wenruo /*
13292dfb1e43SQu Wenruo  * Initialize subvolume root in-memory structure
13302dfb1e43SQu Wenruo  *
13312dfb1e43SQu Wenruo  * @anon_dev:	anonymous device to attach to the root, if zero, allocate new
13322dfb1e43SQu Wenruo  */
13332dfb1e43SQu Wenruo static int btrfs_init_fs_root(struct btrfs_root *root, dev_t anon_dev)
1334cb517eabSMiao Xie {
1335cb517eabSMiao Xie 	int ret;
1336dcc3eb96SNikolay Borisov 	unsigned int nofs_flag;
1337cb517eabSMiao Xie 
1338dcc3eb96SNikolay Borisov 	/*
1339dcc3eb96SNikolay Borisov 	 * We might be called under a transaction (e.g. indirect backref
1340dcc3eb96SNikolay Borisov 	 * resolution) which could deadlock if it triggers memory reclaim
1341dcc3eb96SNikolay Borisov 	 */
1342dcc3eb96SNikolay Borisov 	nofs_flag = memalloc_nofs_save();
1343dcc3eb96SNikolay Borisov 	ret = btrfs_drew_lock_init(&root->snapshot_lock);
1344dcc3eb96SNikolay Borisov 	memalloc_nofs_restore(nofs_flag);
1345dcc3eb96SNikolay Borisov 	if (ret)
13468257b2dcSMiao Xie 		goto fail;
13478257b2dcSMiao Xie 
1348aeb935a4SQu Wenruo 	if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID &&
1349aeb935a4SQu Wenruo 	    root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID) {
135092a7cc42SQu Wenruo 		set_bit(BTRFS_ROOT_SHAREABLE, &root->state);
1351f39e4571SJosef Bacik 		btrfs_check_and_init_root_item(&root->root_item);
1352f39e4571SJosef Bacik 	}
1353f39e4571SJosef Bacik 
1354851fd730SQu Wenruo 	/*
1355851fd730SQu Wenruo 	 * Don't assign anonymous block device to roots that are not exposed to
1356851fd730SQu Wenruo 	 * userspace, the id pool is limited to 1M
1357851fd730SQu Wenruo 	 */
1358851fd730SQu Wenruo 	if (is_fstree(root->root_key.objectid) &&
1359851fd730SQu Wenruo 	    btrfs_root_refs(&root->root_item) > 0) {
13602dfb1e43SQu Wenruo 		if (!anon_dev) {
1361cb517eabSMiao Xie 			ret = get_anon_bdev(&root->anon_dev);
1362cb517eabSMiao Xie 			if (ret)
1363876d2cf1SLiu Bo 				goto fail;
13642dfb1e43SQu Wenruo 		} else {
13652dfb1e43SQu Wenruo 			root->anon_dev = anon_dev;
13662dfb1e43SQu Wenruo 		}
1367851fd730SQu Wenruo 	}
1368f32e48e9SChandan Rajendra 
1369f32e48e9SChandan Rajendra 	mutex_lock(&root->objectid_mutex);
1370453e4873SNikolay Borisov 	ret = btrfs_init_root_free_objectid(root);
1371f32e48e9SChandan Rajendra 	if (ret) {
1372f32e48e9SChandan Rajendra 		mutex_unlock(&root->objectid_mutex);
1373876d2cf1SLiu Bo 		goto fail;
1374f32e48e9SChandan Rajendra 	}
1375f32e48e9SChandan Rajendra 
13766b8fad57SNikolay Borisov 	ASSERT(root->free_objectid <= BTRFS_LAST_FREE_OBJECTID);
1377f32e48e9SChandan Rajendra 
1378f32e48e9SChandan Rajendra 	mutex_unlock(&root->objectid_mutex);
1379f32e48e9SChandan Rajendra 
1380cb517eabSMiao Xie 	return 0;
1381cb517eabSMiao Xie fail:
138284db5ccfSDavid Sterba 	/* The caller is responsible to call btrfs_free_fs_root */
1383cb517eabSMiao Xie 	return ret;
1384cb517eabSMiao Xie }
1385cb517eabSMiao Xie 
1386a98db0f3SJosef Bacik static struct btrfs_root *btrfs_lookup_fs_root(struct btrfs_fs_info *fs_info,
1387cb517eabSMiao Xie 					       u64 root_id)
1388cb517eabSMiao Xie {
1389cb517eabSMiao Xie 	struct btrfs_root *root;
1390cb517eabSMiao Xie 
1391cb517eabSMiao Xie 	spin_lock(&fs_info->fs_roots_radix_lock);
1392cb517eabSMiao Xie 	root = radix_tree_lookup(&fs_info->fs_roots_radix,
1393cb517eabSMiao Xie 				 (unsigned long)root_id);
1394bc44d7c4SJosef Bacik 	if (root)
139500246528SJosef Bacik 		root = btrfs_grab_root(root);
1396cb517eabSMiao Xie 	spin_unlock(&fs_info->fs_roots_radix_lock);
1397cb517eabSMiao Xie 	return root;
1398cb517eabSMiao Xie }
1399cb517eabSMiao Xie 
140049d11beaSJosef Bacik static struct btrfs_root *btrfs_get_global_root(struct btrfs_fs_info *fs_info,
140149d11beaSJosef Bacik 						u64 objectid)
140249d11beaSJosef Bacik {
140349d11beaSJosef Bacik 	if (objectid == BTRFS_ROOT_TREE_OBJECTID)
140449d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->tree_root);
140549d11beaSJosef Bacik 	if (objectid == BTRFS_EXTENT_TREE_OBJECTID)
140649d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->extent_root);
140749d11beaSJosef Bacik 	if (objectid == BTRFS_CHUNK_TREE_OBJECTID)
140849d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->chunk_root);
140949d11beaSJosef Bacik 	if (objectid == BTRFS_DEV_TREE_OBJECTID)
141049d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->dev_root);
141149d11beaSJosef Bacik 	if (objectid == BTRFS_CSUM_TREE_OBJECTID)
141249d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->csum_root);
141349d11beaSJosef Bacik 	if (objectid == BTRFS_QUOTA_TREE_OBJECTID)
141449d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->quota_root) ?
141549d11beaSJosef Bacik 			fs_info->quota_root : ERR_PTR(-ENOENT);
141649d11beaSJosef Bacik 	if (objectid == BTRFS_UUID_TREE_OBJECTID)
141749d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->uuid_root) ?
141849d11beaSJosef Bacik 			fs_info->uuid_root : ERR_PTR(-ENOENT);
141949d11beaSJosef Bacik 	if (objectid == BTRFS_FREE_SPACE_TREE_OBJECTID)
142049d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->free_space_root) ?
142149d11beaSJosef Bacik 			fs_info->free_space_root : ERR_PTR(-ENOENT);
142249d11beaSJosef Bacik 	return NULL;
142349d11beaSJosef Bacik }
142449d11beaSJosef Bacik 
1425cb517eabSMiao Xie int btrfs_insert_fs_root(struct btrfs_fs_info *fs_info,
1426cb517eabSMiao Xie 			 struct btrfs_root *root)
1427cb517eabSMiao Xie {
1428cb517eabSMiao Xie 	int ret;
1429cb517eabSMiao Xie 
1430e1860a77SDavid Sterba 	ret = radix_tree_preload(GFP_NOFS);
1431cb517eabSMiao Xie 	if (ret)
1432cb517eabSMiao Xie 		return ret;
1433cb517eabSMiao Xie 
1434cb517eabSMiao Xie 	spin_lock(&fs_info->fs_roots_radix_lock);
1435cb517eabSMiao Xie 	ret = radix_tree_insert(&fs_info->fs_roots_radix,
1436cb517eabSMiao Xie 				(unsigned long)root->root_key.objectid,
1437cb517eabSMiao Xie 				root);
1438af01d2e5SJosef Bacik 	if (ret == 0) {
143900246528SJosef Bacik 		btrfs_grab_root(root);
144027cdeb70SMiao Xie 		set_bit(BTRFS_ROOT_IN_RADIX, &root->state);
1441af01d2e5SJosef Bacik 	}
1442cb517eabSMiao Xie 	spin_unlock(&fs_info->fs_roots_radix_lock);
1443cb517eabSMiao Xie 	radix_tree_preload_end();
1444cb517eabSMiao Xie 
1445cb517eabSMiao Xie 	return ret;
1446cb517eabSMiao Xie }
1447cb517eabSMiao Xie 
1448bd647ce3SJosef Bacik void btrfs_check_leaked_roots(struct btrfs_fs_info *fs_info)
1449bd647ce3SJosef Bacik {
1450bd647ce3SJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
1451bd647ce3SJosef Bacik 	struct btrfs_root *root;
1452bd647ce3SJosef Bacik 
1453bd647ce3SJosef Bacik 	while (!list_empty(&fs_info->allocated_roots)) {
1454457f1864SJosef Bacik 		char buf[BTRFS_ROOT_NAME_BUF_LEN];
1455457f1864SJosef Bacik 
1456bd647ce3SJosef Bacik 		root = list_first_entry(&fs_info->allocated_roots,
1457bd647ce3SJosef Bacik 					struct btrfs_root, leak_list);
1458457f1864SJosef Bacik 		btrfs_err(fs_info, "leaked root %s refcount %d",
145971008734SJosef Bacik 			  btrfs_root_name(&root->root_key, buf),
1460bd647ce3SJosef Bacik 			  refcount_read(&root->refs));
1461bd647ce3SJosef Bacik 		while (refcount_read(&root->refs) > 1)
146200246528SJosef Bacik 			btrfs_put_root(root);
146300246528SJosef Bacik 		btrfs_put_root(root);
1464bd647ce3SJosef Bacik 	}
1465bd647ce3SJosef Bacik #endif
1466bd647ce3SJosef Bacik }
1467bd647ce3SJosef Bacik 
14680d4b0463SJosef Bacik void btrfs_free_fs_info(struct btrfs_fs_info *fs_info)
14690d4b0463SJosef Bacik {
1470141386e1SJosef Bacik 	percpu_counter_destroy(&fs_info->dirty_metadata_bytes);
1471141386e1SJosef Bacik 	percpu_counter_destroy(&fs_info->delalloc_bytes);
14725deb17e1SJosef Bacik 	percpu_counter_destroy(&fs_info->ordered_bytes);
1473141386e1SJosef Bacik 	percpu_counter_destroy(&fs_info->dev_replace.bio_counter);
1474141386e1SJosef Bacik 	btrfs_free_csum_hash(fs_info);
1475141386e1SJosef Bacik 	btrfs_free_stripe_hash_table(fs_info);
1476141386e1SJosef Bacik 	btrfs_free_ref_cache(fs_info);
14770d4b0463SJosef Bacik 	kfree(fs_info->balance_ctl);
14780d4b0463SJosef Bacik 	kfree(fs_info->delayed_root);
147900246528SJosef Bacik 	btrfs_put_root(fs_info->extent_root);
148000246528SJosef Bacik 	btrfs_put_root(fs_info->tree_root);
148100246528SJosef Bacik 	btrfs_put_root(fs_info->chunk_root);
148200246528SJosef Bacik 	btrfs_put_root(fs_info->dev_root);
148300246528SJosef Bacik 	btrfs_put_root(fs_info->csum_root);
148400246528SJosef Bacik 	btrfs_put_root(fs_info->quota_root);
148500246528SJosef Bacik 	btrfs_put_root(fs_info->uuid_root);
148600246528SJosef Bacik 	btrfs_put_root(fs_info->free_space_root);
148700246528SJosef Bacik 	btrfs_put_root(fs_info->fs_root);
1488aeb935a4SQu Wenruo 	btrfs_put_root(fs_info->data_reloc_root);
1489bd647ce3SJosef Bacik 	btrfs_check_leaked_roots(fs_info);
14903fd63727SJosef Bacik 	btrfs_extent_buffer_leak_debug_check(fs_info);
14910d4b0463SJosef Bacik 	kfree(fs_info->super_copy);
14920d4b0463SJosef Bacik 	kfree(fs_info->super_for_commit);
14930d4b0463SJosef Bacik 	kvfree(fs_info);
14940d4b0463SJosef Bacik }
14950d4b0463SJosef Bacik 
14960d4b0463SJosef Bacik 
14972dfb1e43SQu Wenruo /*
14982dfb1e43SQu Wenruo  * Get an in-memory reference of a root structure.
14992dfb1e43SQu Wenruo  *
15002dfb1e43SQu Wenruo  * For essential trees like root/extent tree, we grab it from fs_info directly.
15012dfb1e43SQu Wenruo  * For subvolume trees, we check the cached filesystem roots first. If not
15022dfb1e43SQu Wenruo  * found, then read it from disk and add it to cached fs roots.
15032dfb1e43SQu Wenruo  *
15042dfb1e43SQu Wenruo  * Caller should release the root by calling btrfs_put_root() after the usage.
15052dfb1e43SQu Wenruo  *
15062dfb1e43SQu Wenruo  * NOTE: Reloc and log trees can't be read by this function as they share the
15072dfb1e43SQu Wenruo  *	 same root objectid.
15082dfb1e43SQu Wenruo  *
15092dfb1e43SQu Wenruo  * @objectid:	root id
15102dfb1e43SQu Wenruo  * @anon_dev:	preallocated anonymous block device number for new roots,
15112dfb1e43SQu Wenruo  * 		pass 0 for new allocation.
15122dfb1e43SQu Wenruo  * @check_ref:	whether to check root item references, If true, return -ENOENT
15132dfb1e43SQu Wenruo  *		for orphan roots
15142dfb1e43SQu Wenruo  */
15152dfb1e43SQu Wenruo static struct btrfs_root *btrfs_get_root_ref(struct btrfs_fs_info *fs_info,
15162dfb1e43SQu Wenruo 					     u64 objectid, dev_t anon_dev,
15172dfb1e43SQu Wenruo 					     bool check_ref)
15185eda7b5eSChris Mason {
15195eda7b5eSChris Mason 	struct btrfs_root *root;
1520381cf658SDavid Sterba 	struct btrfs_path *path;
15211d4c08e0SDavid Sterba 	struct btrfs_key key;
15225eda7b5eSChris Mason 	int ret;
15235eda7b5eSChris Mason 
152449d11beaSJosef Bacik 	root = btrfs_get_global_root(fs_info, objectid);
152549d11beaSJosef Bacik 	if (root)
152649d11beaSJosef Bacik 		return root;
15274df27c4dSYan, Zheng again:
152856e9357aSDavid Sterba 	root = btrfs_lookup_fs_root(fs_info, objectid);
152948475471SStefan Behrens 	if (root) {
15302dfb1e43SQu Wenruo 		/* Shouldn't get preallocated anon_dev for cached roots */
15312dfb1e43SQu Wenruo 		ASSERT(!anon_dev);
1532bc44d7c4SJosef Bacik 		if (check_ref && btrfs_root_refs(&root->root_item) == 0) {
153300246528SJosef Bacik 			btrfs_put_root(root);
153448475471SStefan Behrens 			return ERR_PTR(-ENOENT);
1535bc44d7c4SJosef Bacik 		}
15365eda7b5eSChris Mason 		return root;
153748475471SStefan Behrens 	}
15385eda7b5eSChris Mason 
153956e9357aSDavid Sterba 	key.objectid = objectid;
154056e9357aSDavid Sterba 	key.type = BTRFS_ROOT_ITEM_KEY;
154156e9357aSDavid Sterba 	key.offset = (u64)-1;
154256e9357aSDavid Sterba 	root = btrfs_read_tree_root(fs_info->tree_root, &key);
15435eda7b5eSChris Mason 	if (IS_ERR(root))
15445eda7b5eSChris Mason 		return root;
15453394e160SChris Mason 
1546c00869f1SMiao Xie 	if (check_ref && btrfs_root_refs(&root->root_item) == 0) {
1547d68fc57bSYan, Zheng 		ret = -ENOENT;
1548d68fc57bSYan, Zheng 		goto fail;
1549d68fc57bSYan, Zheng 	}
1550d68fc57bSYan, Zheng 
15512dfb1e43SQu Wenruo 	ret = btrfs_init_fs_root(root, anon_dev);
1552cb517eabSMiao Xie 	if (ret)
1553cb517eabSMiao Xie 		goto fail;
1554cb517eabSMiao Xie 
1555381cf658SDavid Sterba 	path = btrfs_alloc_path();
1556381cf658SDavid Sterba 	if (!path) {
1557381cf658SDavid Sterba 		ret = -ENOMEM;
1558381cf658SDavid Sterba 		goto fail;
1559381cf658SDavid Sterba 	}
15601d4c08e0SDavid Sterba 	key.objectid = BTRFS_ORPHAN_OBJECTID;
15611d4c08e0SDavid Sterba 	key.type = BTRFS_ORPHAN_ITEM_KEY;
156256e9357aSDavid Sterba 	key.offset = objectid;
15631d4c08e0SDavid Sterba 
15641d4c08e0SDavid Sterba 	ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
1565381cf658SDavid Sterba 	btrfs_free_path(path);
1566d68fc57bSYan, Zheng 	if (ret < 0)
1567d68fc57bSYan, Zheng 		goto fail;
1568d68fc57bSYan, Zheng 	if (ret == 0)
156927cdeb70SMiao Xie 		set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state);
1570d68fc57bSYan, Zheng 
1571cb517eabSMiao Xie 	ret = btrfs_insert_fs_root(fs_info, root);
15720f7d52f4SChris Mason 	if (ret) {
157300246528SJosef Bacik 		btrfs_put_root(root);
15744785e24fSJosef Bacik 		if (ret == -EEXIST)
15754df27c4dSYan, Zheng 			goto again;
15764df27c4dSYan, Zheng 		goto fail;
15774df27c4dSYan, Zheng 	}
1578edbd8d4eSChris Mason 	return root;
15794df27c4dSYan, Zheng fail:
15808c38938cSJosef Bacik 	btrfs_put_root(root);
15814df27c4dSYan, Zheng 	return ERR_PTR(ret);
1582edbd8d4eSChris Mason }
1583edbd8d4eSChris Mason 
15842dfb1e43SQu Wenruo /*
15852dfb1e43SQu Wenruo  * Get in-memory reference of a root structure
15862dfb1e43SQu Wenruo  *
15872dfb1e43SQu Wenruo  * @objectid:	tree objectid
15882dfb1e43SQu Wenruo  * @check_ref:	if set, verify that the tree exists and the item has at least
15892dfb1e43SQu Wenruo  *		one reference
15902dfb1e43SQu Wenruo  */
15912dfb1e43SQu Wenruo struct btrfs_root *btrfs_get_fs_root(struct btrfs_fs_info *fs_info,
15922dfb1e43SQu Wenruo 				     u64 objectid, bool check_ref)
15932dfb1e43SQu Wenruo {
15942dfb1e43SQu Wenruo 	return btrfs_get_root_ref(fs_info, objectid, 0, check_ref);
15952dfb1e43SQu Wenruo }
15962dfb1e43SQu Wenruo 
15972dfb1e43SQu Wenruo /*
15982dfb1e43SQu Wenruo  * Get in-memory reference of a root structure, created as new, optionally pass
15992dfb1e43SQu Wenruo  * the anonymous block device id
16002dfb1e43SQu Wenruo  *
16012dfb1e43SQu Wenruo  * @objectid:	tree objectid
16022dfb1e43SQu Wenruo  * @anon_dev:	if zero, allocate a new anonymous block device or use the
16032dfb1e43SQu Wenruo  *		parameter value
16042dfb1e43SQu Wenruo  */
16052dfb1e43SQu Wenruo struct btrfs_root *btrfs_get_new_fs_root(struct btrfs_fs_info *fs_info,
16062dfb1e43SQu Wenruo 					 u64 objectid, dev_t anon_dev)
16072dfb1e43SQu Wenruo {
16082dfb1e43SQu Wenruo 	return btrfs_get_root_ref(fs_info, objectid, anon_dev, true);
16092dfb1e43SQu Wenruo }
16102dfb1e43SQu Wenruo 
16118b712842SChris Mason /*
161249d11beaSJosef Bacik  * btrfs_get_fs_root_commit_root - return a root for the given objectid
161349d11beaSJosef Bacik  * @fs_info:	the fs_info
161449d11beaSJosef Bacik  * @objectid:	the objectid we need to lookup
161549d11beaSJosef Bacik  *
161649d11beaSJosef Bacik  * This is exclusively used for backref walking, and exists specifically because
161749d11beaSJosef Bacik  * of how qgroups does lookups.  Qgroups will do a backref lookup at delayed ref
161849d11beaSJosef Bacik  * creation time, which means we may have to read the tree_root in order to look
161949d11beaSJosef Bacik  * up a fs root that is not in memory.  If the root is not in memory we will
162049d11beaSJosef Bacik  * read the tree root commit root and look up the fs root from there.  This is a
162149d11beaSJosef Bacik  * temporary root, it will not be inserted into the radix tree as it doesn't
162249d11beaSJosef Bacik  * have the most uptodate information, it'll simply be discarded once the
162349d11beaSJosef Bacik  * backref code is finished using the root.
162449d11beaSJosef Bacik  */
162549d11beaSJosef Bacik struct btrfs_root *btrfs_get_fs_root_commit_root(struct btrfs_fs_info *fs_info,
162649d11beaSJosef Bacik 						 struct btrfs_path *path,
162749d11beaSJosef Bacik 						 u64 objectid)
162849d11beaSJosef Bacik {
162949d11beaSJosef Bacik 	struct btrfs_root *root;
163049d11beaSJosef Bacik 	struct btrfs_key key;
163149d11beaSJosef Bacik 
163249d11beaSJosef Bacik 	ASSERT(path->search_commit_root && path->skip_locking);
163349d11beaSJosef Bacik 
163449d11beaSJosef Bacik 	/*
163549d11beaSJosef Bacik 	 * This can return -ENOENT if we ask for a root that doesn't exist, but
163649d11beaSJosef Bacik 	 * since this is called via the backref walking code we won't be looking
163749d11beaSJosef Bacik 	 * up a root that doesn't exist, unless there's corruption.  So if root
163849d11beaSJosef Bacik 	 * != NULL just return it.
163949d11beaSJosef Bacik 	 */
164049d11beaSJosef Bacik 	root = btrfs_get_global_root(fs_info, objectid);
164149d11beaSJosef Bacik 	if (root)
164249d11beaSJosef Bacik 		return root;
164349d11beaSJosef Bacik 
164449d11beaSJosef Bacik 	root = btrfs_lookup_fs_root(fs_info, objectid);
164549d11beaSJosef Bacik 	if (root)
164649d11beaSJosef Bacik 		return root;
164749d11beaSJosef Bacik 
164849d11beaSJosef Bacik 	key.objectid = objectid;
164949d11beaSJosef Bacik 	key.type = BTRFS_ROOT_ITEM_KEY;
165049d11beaSJosef Bacik 	key.offset = (u64)-1;
165149d11beaSJosef Bacik 	root = read_tree_root_path(fs_info->tree_root, path, &key);
165249d11beaSJosef Bacik 	btrfs_release_path(path);
165349d11beaSJosef Bacik 
165449d11beaSJosef Bacik 	return root;
165549d11beaSJosef Bacik }
165649d11beaSJosef Bacik 
165749d11beaSJosef Bacik /*
16588b712842SChris Mason  * called by the kthread helper functions to finally call the bio end_io
16598b712842SChris Mason  * functions.  This is where read checksum verification actually happens
16608b712842SChris Mason  */
16618b712842SChris Mason static void end_workqueue_fn(struct btrfs_work *work)
1662ce9adaa5SChris Mason {
1663ce9adaa5SChris Mason 	struct bio *bio;
166497eb6b69SDavid Sterba 	struct btrfs_end_io_wq *end_io_wq;
1665ce9adaa5SChris Mason 
166697eb6b69SDavid Sterba 	end_io_wq = container_of(work, struct btrfs_end_io_wq, work);
1667ce9adaa5SChris Mason 	bio = end_io_wq->bio;
16688b712842SChris Mason 
16694e4cbee9SChristoph Hellwig 	bio->bi_status = end_io_wq->status;
1670ce9adaa5SChris Mason 	bio->bi_private = end_io_wq->private;
1671ce9adaa5SChris Mason 	bio->bi_end_io = end_io_wq->end_io;
16724246a0b6SChristoph Hellwig 	bio_endio(bio);
16739be490f1SOmar Sandoval 	kmem_cache_free(btrfs_end_io_wq_cache, end_io_wq);
1674ce9adaa5SChris Mason }
167544b8bd7eSChris Mason 
1676a74a4b97SChris Mason static int cleaner_kthread(void *arg)
1677a74a4b97SChris Mason {
1678a74a4b97SChris Mason 	struct btrfs_root *root = arg;
16790b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
1680d0278245SMiao Xie 	int again;
1681a74a4b97SChris Mason 
1682d6fd0ae2SOmar Sandoval 	while (1) {
1683d0278245SMiao Xie 		again = 0;
16849d1a2a3aSDavid Sterba 
1685fd340d0fSJosef Bacik 		set_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags);
1686fd340d0fSJosef Bacik 
1687d0278245SMiao Xie 		/* Make the cleaner go to sleep early. */
16882ff7e61eSJeff Mahoney 		if (btrfs_need_cleaner_sleep(fs_info))
1689d0278245SMiao Xie 			goto sleep;
1690d0278245SMiao Xie 
169190c711abSZygo Blaxell 		/*
169290c711abSZygo Blaxell 		 * Do not do anything if we might cause open_ctree() to block
169390c711abSZygo Blaxell 		 * before we have finished mounting the filesystem.
169490c711abSZygo Blaxell 		 */
16950b246afaSJeff Mahoney 		if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
169690c711abSZygo Blaxell 			goto sleep;
169790c711abSZygo Blaxell 
16980b246afaSJeff Mahoney 		if (!mutex_trylock(&fs_info->cleaner_mutex))
1699d0278245SMiao Xie 			goto sleep;
1700d0278245SMiao Xie 
1701dc7f370cSMiao Xie 		/*
1702dc7f370cSMiao Xie 		 * Avoid the problem that we change the status of the fs
1703dc7f370cSMiao Xie 		 * during the above check and trylock.
1704dc7f370cSMiao Xie 		 */
17052ff7e61eSJeff Mahoney 		if (btrfs_need_cleaner_sleep(fs_info)) {
17060b246afaSJeff Mahoney 			mutex_unlock(&fs_info->cleaner_mutex);
1707dc7f370cSMiao Xie 			goto sleep;
1708dc7f370cSMiao Xie 		}
1709dc7f370cSMiao Xie 
17102ff7e61eSJeff Mahoney 		btrfs_run_delayed_iputs(fs_info);
1711c2d6cb16SFilipe Manana 
17129d1a2a3aSDavid Sterba 		again = btrfs_clean_one_deleted_snapshot(root);
17130b246afaSJeff Mahoney 		mutex_unlock(&fs_info->cleaner_mutex);
1714a74a4b97SChris Mason 
1715d0278245SMiao Xie 		/*
171605323cd1SMiao Xie 		 * The defragger has dealt with the R/O remount and umount,
171705323cd1SMiao Xie 		 * needn't do anything special here.
1718d0278245SMiao Xie 		 */
17190b246afaSJeff Mahoney 		btrfs_run_defrag_inodes(fs_info);
172067c5e7d4SFilipe Manana 
172167c5e7d4SFilipe Manana 		/*
172267c5e7d4SFilipe Manana 		 * Acquires fs_info->delete_unused_bgs_mutex to avoid racing
172367c5e7d4SFilipe Manana 		 * with relocation (btrfs_relocate_chunk) and relocation
172467c5e7d4SFilipe Manana 		 * acquires fs_info->cleaner_mutex (btrfs_relocate_block_group)
172567c5e7d4SFilipe Manana 		 * after acquiring fs_info->delete_unused_bgs_mutex. So we
172667c5e7d4SFilipe Manana 		 * can't hold, nor need to, fs_info->cleaner_mutex when deleting
172767c5e7d4SFilipe Manana 		 * unused block groups.
172867c5e7d4SFilipe Manana 		 */
17290b246afaSJeff Mahoney 		btrfs_delete_unused_bgs(fs_info);
1730d0278245SMiao Xie sleep:
1731a0a1db70SFilipe Manana 		clear_and_wake_up_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags);
1732d6fd0ae2SOmar Sandoval 		if (kthread_should_park())
1733d6fd0ae2SOmar Sandoval 			kthread_parkme();
1734d6fd0ae2SOmar Sandoval 		if (kthread_should_stop())
1735d6fd0ae2SOmar Sandoval 			return 0;
1736838fe188SJiri Kosina 		if (!again) {
1737a74a4b97SChris Mason 			set_current_state(TASK_INTERRUPTIBLE);
1738a74a4b97SChris Mason 			schedule();
1739a74a4b97SChris Mason 			__set_current_state(TASK_RUNNING);
1740a74a4b97SChris Mason 		}
1741da288d28SFilipe Manana 	}
1742a74a4b97SChris Mason }
1743a74a4b97SChris Mason 
1744a74a4b97SChris Mason static int transaction_kthread(void *arg)
1745a74a4b97SChris Mason {
1746a74a4b97SChris Mason 	struct btrfs_root *root = arg;
17470b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
1748a74a4b97SChris Mason 	struct btrfs_trans_handle *trans;
1749a74a4b97SChris Mason 	struct btrfs_transaction *cur;
17508929ecfaSYan, Zheng 	u64 transid;
1751643900beSNikolay Borisov 	time64_t delta;
1752a74a4b97SChris Mason 	unsigned long delay;
1753914b2007SJan Kara 	bool cannot_commit;
1754a74a4b97SChris Mason 
1755a74a4b97SChris Mason 	do {
1756914b2007SJan Kara 		cannot_commit = false;
1757ba1bc00fSNikolay Borisov 		delay = msecs_to_jiffies(fs_info->commit_interval * 1000);
17580b246afaSJeff Mahoney 		mutex_lock(&fs_info->transaction_kthread_mutex);
1759a74a4b97SChris Mason 
17600b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
17610b246afaSJeff Mahoney 		cur = fs_info->running_transaction;
1762a74a4b97SChris Mason 		if (!cur) {
17630b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
1764a74a4b97SChris Mason 			goto sleep;
1765a74a4b97SChris Mason 		}
176631153d81SYan Zheng 
1767643900beSNikolay Borisov 		delta = ktime_get_seconds() - cur->start_time;
17683296bf56SQu Wenruo 		if (cur->state < TRANS_STATE_COMMIT_START &&
1769643900beSNikolay Borisov 		    delta < fs_info->commit_interval) {
17700b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
1771fb8a7e94SNikolay Borisov 			delay -= msecs_to_jiffies((delta - 1) * 1000);
1772fb8a7e94SNikolay Borisov 			delay = min(delay,
1773fb8a7e94SNikolay Borisov 				    msecs_to_jiffies(fs_info->commit_interval * 1000));
1774a74a4b97SChris Mason 			goto sleep;
1775a74a4b97SChris Mason 		}
17768929ecfaSYan, Zheng 		transid = cur->transid;
17770b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
177856bec294SChris Mason 
177979787eaaSJeff Mahoney 		/* If the file system is aborted, this will always fail. */
1780354aa0fbSMiao Xie 		trans = btrfs_attach_transaction(root);
1781914b2007SJan Kara 		if (IS_ERR(trans)) {
1782354aa0fbSMiao Xie 			if (PTR_ERR(trans) != -ENOENT)
1783914b2007SJan Kara 				cannot_commit = true;
178479787eaaSJeff Mahoney 			goto sleep;
1785914b2007SJan Kara 		}
17868929ecfaSYan, Zheng 		if (transid == trans->transid) {
17873a45bb20SJeff Mahoney 			btrfs_commit_transaction(trans);
17888929ecfaSYan, Zheng 		} else {
17893a45bb20SJeff Mahoney 			btrfs_end_transaction(trans);
17908929ecfaSYan, Zheng 		}
1791a74a4b97SChris Mason sleep:
17920b246afaSJeff Mahoney 		wake_up_process(fs_info->cleaner_kthread);
17930b246afaSJeff Mahoney 		mutex_unlock(&fs_info->transaction_kthread_mutex);
1794a74a4b97SChris Mason 
17954e121c06SJosef Bacik 		if (unlikely(test_bit(BTRFS_FS_STATE_ERROR,
17960b246afaSJeff Mahoney 				      &fs_info->fs_state)))
17972ff7e61eSJeff Mahoney 			btrfs_cleanup_transaction(fs_info);
17988929ecfaSYan, Zheng 		if (!kthread_should_stop() &&
17990b246afaSJeff Mahoney 				(!btrfs_transaction_blocked(fs_info) ||
1800914b2007SJan Kara 				 cannot_commit))
1801bc5511d0SNikolay Borisov 			schedule_timeout_interruptible(delay);
1802a74a4b97SChris Mason 	} while (!kthread_should_stop());
1803a74a4b97SChris Mason 	return 0;
1804a74a4b97SChris Mason }
1805a74a4b97SChris Mason 
1806af31f5e5SChris Mason /*
180701f0f9daSNikolay Borisov  * This will find the highest generation in the array of root backups.  The
180801f0f9daSNikolay Borisov  * index of the highest array is returned, or -EINVAL if we can't find
180901f0f9daSNikolay Borisov  * anything.
1810af31f5e5SChris Mason  *
1811af31f5e5SChris Mason  * We check to make sure the array is valid by comparing the
1812af31f5e5SChris Mason  * generation of the latest  root in the array with the generation
1813af31f5e5SChris Mason  * in the super block.  If they don't match we pitch it.
1814af31f5e5SChris Mason  */
181501f0f9daSNikolay Borisov static int find_newest_super_backup(struct btrfs_fs_info *info)
1816af31f5e5SChris Mason {
181701f0f9daSNikolay Borisov 	const u64 newest_gen = btrfs_super_generation(info->super_copy);
1818af31f5e5SChris Mason 	u64 cur;
1819af31f5e5SChris Mason 	struct btrfs_root_backup *root_backup;
1820af31f5e5SChris Mason 	int i;
1821af31f5e5SChris Mason 
1822af31f5e5SChris Mason 	for (i = 0; i < BTRFS_NUM_BACKUP_ROOTS; i++) {
1823af31f5e5SChris Mason 		root_backup = info->super_copy->super_roots + i;
1824af31f5e5SChris Mason 		cur = btrfs_backup_tree_root_gen(root_backup);
1825af31f5e5SChris Mason 		if (cur == newest_gen)
182601f0f9daSNikolay Borisov 			return i;
1827af31f5e5SChris Mason 	}
1828af31f5e5SChris Mason 
182901f0f9daSNikolay Borisov 	return -EINVAL;
1830af31f5e5SChris Mason }
1831af31f5e5SChris Mason 
1832af31f5e5SChris Mason /*
1833af31f5e5SChris Mason  * copy all the root pointers into the super backup array.
1834af31f5e5SChris Mason  * this will bump the backup pointer by one when it is
1835af31f5e5SChris Mason  * done
1836af31f5e5SChris Mason  */
1837af31f5e5SChris Mason static void backup_super_roots(struct btrfs_fs_info *info)
1838af31f5e5SChris Mason {
18396ef108ddSNikolay Borisov 	const int next_backup = info->backup_root_index;
1840af31f5e5SChris Mason 	struct btrfs_root_backup *root_backup;
1841af31f5e5SChris Mason 
1842af31f5e5SChris Mason 	root_backup = info->super_for_commit->super_roots + next_backup;
1843af31f5e5SChris Mason 
1844af31f5e5SChris Mason 	/*
1845af31f5e5SChris Mason 	 * make sure all of our padding and empty slots get zero filled
1846af31f5e5SChris Mason 	 * regardless of which ones we use today
1847af31f5e5SChris Mason 	 */
1848af31f5e5SChris Mason 	memset(root_backup, 0, sizeof(*root_backup));
1849af31f5e5SChris Mason 
1850af31f5e5SChris Mason 	info->backup_root_index = (next_backup + 1) % BTRFS_NUM_BACKUP_ROOTS;
1851af31f5e5SChris Mason 
1852af31f5e5SChris Mason 	btrfs_set_backup_tree_root(root_backup, info->tree_root->node->start);
1853af31f5e5SChris Mason 	btrfs_set_backup_tree_root_gen(root_backup,
1854af31f5e5SChris Mason 			       btrfs_header_generation(info->tree_root->node));
1855af31f5e5SChris Mason 
1856af31f5e5SChris Mason 	btrfs_set_backup_tree_root_level(root_backup,
1857af31f5e5SChris Mason 			       btrfs_header_level(info->tree_root->node));
1858af31f5e5SChris Mason 
1859af31f5e5SChris Mason 	btrfs_set_backup_chunk_root(root_backup, info->chunk_root->node->start);
1860af31f5e5SChris Mason 	btrfs_set_backup_chunk_root_gen(root_backup,
1861af31f5e5SChris Mason 			       btrfs_header_generation(info->chunk_root->node));
1862af31f5e5SChris Mason 	btrfs_set_backup_chunk_root_level(root_backup,
1863af31f5e5SChris Mason 			       btrfs_header_level(info->chunk_root->node));
1864af31f5e5SChris Mason 
1865af31f5e5SChris Mason 	btrfs_set_backup_extent_root(root_backup, info->extent_root->node->start);
1866af31f5e5SChris Mason 	btrfs_set_backup_extent_root_gen(root_backup,
1867af31f5e5SChris Mason 			       btrfs_header_generation(info->extent_root->node));
1868af31f5e5SChris Mason 	btrfs_set_backup_extent_root_level(root_backup,
1869af31f5e5SChris Mason 			       btrfs_header_level(info->extent_root->node));
1870af31f5e5SChris Mason 
18717c7e82a7SChris Mason 	/*
18727c7e82a7SChris Mason 	 * we might commit during log recovery, which happens before we set
18737c7e82a7SChris Mason 	 * the fs_root.  Make sure it is valid before we fill it in.
18747c7e82a7SChris Mason 	 */
18757c7e82a7SChris Mason 	if (info->fs_root && info->fs_root->node) {
18767c7e82a7SChris Mason 		btrfs_set_backup_fs_root(root_backup,
18777c7e82a7SChris Mason 					 info->fs_root->node->start);
1878af31f5e5SChris Mason 		btrfs_set_backup_fs_root_gen(root_backup,
1879af31f5e5SChris Mason 			       btrfs_header_generation(info->fs_root->node));
1880af31f5e5SChris Mason 		btrfs_set_backup_fs_root_level(root_backup,
1881af31f5e5SChris Mason 			       btrfs_header_level(info->fs_root->node));
18827c7e82a7SChris Mason 	}
1883af31f5e5SChris Mason 
1884af31f5e5SChris Mason 	btrfs_set_backup_dev_root(root_backup, info->dev_root->node->start);
1885af31f5e5SChris Mason 	btrfs_set_backup_dev_root_gen(root_backup,
1886af31f5e5SChris Mason 			       btrfs_header_generation(info->dev_root->node));
1887af31f5e5SChris Mason 	btrfs_set_backup_dev_root_level(root_backup,
1888af31f5e5SChris Mason 				       btrfs_header_level(info->dev_root->node));
1889af31f5e5SChris Mason 
1890af31f5e5SChris Mason 	btrfs_set_backup_csum_root(root_backup, info->csum_root->node->start);
1891af31f5e5SChris Mason 	btrfs_set_backup_csum_root_gen(root_backup,
1892af31f5e5SChris Mason 			       btrfs_header_generation(info->csum_root->node));
1893af31f5e5SChris Mason 	btrfs_set_backup_csum_root_level(root_backup,
1894af31f5e5SChris Mason 			       btrfs_header_level(info->csum_root->node));
1895af31f5e5SChris Mason 
1896af31f5e5SChris Mason 	btrfs_set_backup_total_bytes(root_backup,
1897af31f5e5SChris Mason 			     btrfs_super_total_bytes(info->super_copy));
1898af31f5e5SChris Mason 	btrfs_set_backup_bytes_used(root_backup,
1899af31f5e5SChris Mason 			     btrfs_super_bytes_used(info->super_copy));
1900af31f5e5SChris Mason 	btrfs_set_backup_num_devices(root_backup,
1901af31f5e5SChris Mason 			     btrfs_super_num_devices(info->super_copy));
1902af31f5e5SChris Mason 
1903af31f5e5SChris Mason 	/*
1904af31f5e5SChris Mason 	 * if we don't copy this out to the super_copy, it won't get remembered
1905af31f5e5SChris Mason 	 * for the next commit
1906af31f5e5SChris Mason 	 */
1907af31f5e5SChris Mason 	memcpy(&info->super_copy->super_roots,
1908af31f5e5SChris Mason 	       &info->super_for_commit->super_roots,
1909af31f5e5SChris Mason 	       sizeof(*root_backup) * BTRFS_NUM_BACKUP_ROOTS);
1910af31f5e5SChris Mason }
1911af31f5e5SChris Mason 
1912af31f5e5SChris Mason /*
1913bd2336b2SNikolay Borisov  * read_backup_root - Reads a backup root based on the passed priority. Prio 0
1914bd2336b2SNikolay Borisov  * is the newest, prio 1/2/3 are 2nd newest/3rd newest/4th (oldest) backup roots
1915bd2336b2SNikolay Borisov  *
1916bd2336b2SNikolay Borisov  * fs_info - filesystem whose backup roots need to be read
1917bd2336b2SNikolay Borisov  * priority - priority of backup root required
1918bd2336b2SNikolay Borisov  *
1919bd2336b2SNikolay Borisov  * Returns backup root index on success and -EINVAL otherwise.
1920bd2336b2SNikolay Borisov  */
1921bd2336b2SNikolay Borisov static int read_backup_root(struct btrfs_fs_info *fs_info, u8 priority)
1922bd2336b2SNikolay Borisov {
1923bd2336b2SNikolay Borisov 	int backup_index = find_newest_super_backup(fs_info);
1924bd2336b2SNikolay Borisov 	struct btrfs_super_block *super = fs_info->super_copy;
1925bd2336b2SNikolay Borisov 	struct btrfs_root_backup *root_backup;
1926bd2336b2SNikolay Borisov 
1927bd2336b2SNikolay Borisov 	if (priority < BTRFS_NUM_BACKUP_ROOTS && backup_index >= 0) {
1928bd2336b2SNikolay Borisov 		if (priority == 0)
1929bd2336b2SNikolay Borisov 			return backup_index;
1930bd2336b2SNikolay Borisov 
1931bd2336b2SNikolay Borisov 		backup_index = backup_index + BTRFS_NUM_BACKUP_ROOTS - priority;
1932bd2336b2SNikolay Borisov 		backup_index %= BTRFS_NUM_BACKUP_ROOTS;
1933bd2336b2SNikolay Borisov 	} else {
1934bd2336b2SNikolay Borisov 		return -EINVAL;
1935bd2336b2SNikolay Borisov 	}
1936bd2336b2SNikolay Borisov 
1937bd2336b2SNikolay Borisov 	root_backup = super->super_roots + backup_index;
1938bd2336b2SNikolay Borisov 
1939bd2336b2SNikolay Borisov 	btrfs_set_super_generation(super,
1940bd2336b2SNikolay Borisov 				   btrfs_backup_tree_root_gen(root_backup));
1941bd2336b2SNikolay Borisov 	btrfs_set_super_root(super, btrfs_backup_tree_root(root_backup));
1942bd2336b2SNikolay Borisov 	btrfs_set_super_root_level(super,
1943bd2336b2SNikolay Borisov 				   btrfs_backup_tree_root_level(root_backup));
1944bd2336b2SNikolay Borisov 	btrfs_set_super_bytes_used(super, btrfs_backup_bytes_used(root_backup));
1945bd2336b2SNikolay Borisov 
1946bd2336b2SNikolay Borisov 	/*
1947bd2336b2SNikolay Borisov 	 * Fixme: the total bytes and num_devices need to match or we should
1948bd2336b2SNikolay Borisov 	 * need a fsck
1949bd2336b2SNikolay Borisov 	 */
1950bd2336b2SNikolay Borisov 	btrfs_set_super_total_bytes(super, btrfs_backup_total_bytes(root_backup));
1951bd2336b2SNikolay Borisov 	btrfs_set_super_num_devices(super, btrfs_backup_num_devices(root_backup));
1952bd2336b2SNikolay Borisov 
1953bd2336b2SNikolay Borisov 	return backup_index;
1954bd2336b2SNikolay Borisov }
1955bd2336b2SNikolay Borisov 
19567abadb64SLiu Bo /* helper to cleanup workers */
19577abadb64SLiu Bo static void btrfs_stop_all_workers(struct btrfs_fs_info *fs_info)
19587abadb64SLiu Bo {
1959dc6e3209SQu Wenruo 	btrfs_destroy_workqueue(fs_info->fixup_workers);
1960afe3d242SQu Wenruo 	btrfs_destroy_workqueue(fs_info->delalloc_workers);
19615cdc7ad3SQu Wenruo 	btrfs_destroy_workqueue(fs_info->workers);
1962fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_workers);
1963fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_raid56_workers);
1964d05a33acSQu Wenruo 	btrfs_destroy_workqueue(fs_info->rmw_workers);
1965fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_write_workers);
1966fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_freespace_worker);
19675b3bc44eSQu Wenruo 	btrfs_destroy_workqueue(fs_info->delayed_workers);
1968e66f0bb1SQu Wenruo 	btrfs_destroy_workqueue(fs_info->caching_workers);
1969736cfa15SQu Wenruo 	btrfs_destroy_workqueue(fs_info->readahead_workers);
1970a44903abSQu Wenruo 	btrfs_destroy_workqueue(fs_info->flush_workers);
1971fc97fab0SQu Wenruo 	btrfs_destroy_workqueue(fs_info->qgroup_rescan_workers);
1972b0643e59SDennis Zhou 	if (fs_info->discard_ctl.discard_workers)
1973b0643e59SDennis Zhou 		destroy_workqueue(fs_info->discard_ctl.discard_workers);
1974a9b9477dSFilipe Manana 	/*
1975a9b9477dSFilipe Manana 	 * Now that all other work queues are destroyed, we can safely destroy
1976a9b9477dSFilipe Manana 	 * the queues used for metadata I/O, since tasks from those other work
1977a9b9477dSFilipe Manana 	 * queues can do metadata I/O operations.
1978a9b9477dSFilipe Manana 	 */
1979a9b9477dSFilipe Manana 	btrfs_destroy_workqueue(fs_info->endio_meta_workers);
1980a9b9477dSFilipe Manana 	btrfs_destroy_workqueue(fs_info->endio_meta_write_workers);
19817abadb64SLiu Bo }
19827abadb64SLiu Bo 
19832e9f5954SRashika static void free_root_extent_buffers(struct btrfs_root *root)
19842e9f5954SRashika {
19852e9f5954SRashika 	if (root) {
19862e9f5954SRashika 		free_extent_buffer(root->node);
19872e9f5954SRashika 		free_extent_buffer(root->commit_root);
19882e9f5954SRashika 		root->node = NULL;
19892e9f5954SRashika 		root->commit_root = NULL;
19902e9f5954SRashika 	}
19912e9f5954SRashika }
19922e9f5954SRashika 
1993af31f5e5SChris Mason /* helper to cleanup tree roots */
19944273eaffSAnand Jain static void free_root_pointers(struct btrfs_fs_info *info, bool free_chunk_root)
1995af31f5e5SChris Mason {
19962e9f5954SRashika 	free_root_extent_buffers(info->tree_root);
1997655b09feSJosef Bacik 
19982e9f5954SRashika 	free_root_extent_buffers(info->dev_root);
19992e9f5954SRashika 	free_root_extent_buffers(info->extent_root);
20002e9f5954SRashika 	free_root_extent_buffers(info->csum_root);
20012e9f5954SRashika 	free_root_extent_buffers(info->quota_root);
20022e9f5954SRashika 	free_root_extent_buffers(info->uuid_root);
20038c38938cSJosef Bacik 	free_root_extent_buffers(info->fs_root);
2004aeb935a4SQu Wenruo 	free_root_extent_buffers(info->data_reloc_root);
20054273eaffSAnand Jain 	if (free_chunk_root)
20062e9f5954SRashika 		free_root_extent_buffers(info->chunk_root);
200770f6d82eSOmar Sandoval 	free_root_extent_buffers(info->free_space_root);
2008af31f5e5SChris Mason }
2009af31f5e5SChris Mason 
20108c38938cSJosef Bacik void btrfs_put_root(struct btrfs_root *root)
20118c38938cSJosef Bacik {
20128c38938cSJosef Bacik 	if (!root)
20138c38938cSJosef Bacik 		return;
20148c38938cSJosef Bacik 
20158c38938cSJosef Bacik 	if (refcount_dec_and_test(&root->refs)) {
20168c38938cSJosef Bacik 		WARN_ON(!RB_EMPTY_ROOT(&root->inode_tree));
20171dae7e0eSQu Wenruo 		WARN_ON(test_bit(BTRFS_ROOT_DEAD_RELOC_TREE, &root->state));
20188c38938cSJosef Bacik 		if (root->anon_dev)
20198c38938cSJosef Bacik 			free_anon_bdev(root->anon_dev);
20208c38938cSJosef Bacik 		btrfs_drew_lock_destroy(&root->snapshot_lock);
2021923eb523SJohannes Thumshirn 		free_root_extent_buffers(root);
20228c38938cSJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
20238c38938cSJosef Bacik 		spin_lock(&root->fs_info->fs_roots_radix_lock);
20248c38938cSJosef Bacik 		list_del_init(&root->leak_list);
20258c38938cSJosef Bacik 		spin_unlock(&root->fs_info->fs_roots_radix_lock);
20268c38938cSJosef Bacik #endif
20278c38938cSJosef Bacik 		kfree(root);
20288c38938cSJosef Bacik 	}
20298c38938cSJosef Bacik }
20308c38938cSJosef Bacik 
2031faa2dbf0SJosef Bacik void btrfs_free_fs_roots(struct btrfs_fs_info *fs_info)
2032171f6537SJosef Bacik {
2033171f6537SJosef Bacik 	int ret;
2034171f6537SJosef Bacik 	struct btrfs_root *gang[8];
2035171f6537SJosef Bacik 	int i;
2036171f6537SJosef Bacik 
2037171f6537SJosef Bacik 	while (!list_empty(&fs_info->dead_roots)) {
2038171f6537SJosef Bacik 		gang[0] = list_entry(fs_info->dead_roots.next,
2039171f6537SJosef Bacik 				     struct btrfs_root, root_list);
2040171f6537SJosef Bacik 		list_del(&gang[0]->root_list);
2041171f6537SJosef Bacik 
20428c38938cSJosef Bacik 		if (test_bit(BTRFS_ROOT_IN_RADIX, &gang[0]->state))
2043cb517eabSMiao Xie 			btrfs_drop_and_free_fs_root(fs_info, gang[0]);
204400246528SJosef Bacik 		btrfs_put_root(gang[0]);
2045171f6537SJosef Bacik 	}
2046171f6537SJosef Bacik 
2047171f6537SJosef Bacik 	while (1) {
2048171f6537SJosef Bacik 		ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
2049171f6537SJosef Bacik 					     (void **)gang, 0,
2050171f6537SJosef Bacik 					     ARRAY_SIZE(gang));
2051171f6537SJosef Bacik 		if (!ret)
2052171f6537SJosef Bacik 			break;
2053171f6537SJosef Bacik 		for (i = 0; i < ret; i++)
2054cb517eabSMiao Xie 			btrfs_drop_and_free_fs_root(fs_info, gang[i]);
2055171f6537SJosef Bacik 	}
2056171f6537SJosef Bacik }
2057af31f5e5SChris Mason 
2058638aa7edSEric Sandeen static void btrfs_init_scrub(struct btrfs_fs_info *fs_info)
2059638aa7edSEric Sandeen {
2060638aa7edSEric Sandeen 	mutex_init(&fs_info->scrub_lock);
2061638aa7edSEric Sandeen 	atomic_set(&fs_info->scrubs_running, 0);
2062638aa7edSEric Sandeen 	atomic_set(&fs_info->scrub_pause_req, 0);
2063638aa7edSEric Sandeen 	atomic_set(&fs_info->scrubs_paused, 0);
2064638aa7edSEric Sandeen 	atomic_set(&fs_info->scrub_cancel_req, 0);
2065638aa7edSEric Sandeen 	init_waitqueue_head(&fs_info->scrub_pause_wait);
2066ff09c4caSAnand Jain 	refcount_set(&fs_info->scrub_workers_refcnt, 0);
2067638aa7edSEric Sandeen }
2068638aa7edSEric Sandeen 
2069779a65a4SEric Sandeen static void btrfs_init_balance(struct btrfs_fs_info *fs_info)
2070779a65a4SEric Sandeen {
2071779a65a4SEric Sandeen 	spin_lock_init(&fs_info->balance_lock);
2072779a65a4SEric Sandeen 	mutex_init(&fs_info->balance_mutex);
2073779a65a4SEric Sandeen 	atomic_set(&fs_info->balance_pause_req, 0);
2074779a65a4SEric Sandeen 	atomic_set(&fs_info->balance_cancel_req, 0);
2075779a65a4SEric Sandeen 	fs_info->balance_ctl = NULL;
2076779a65a4SEric Sandeen 	init_waitqueue_head(&fs_info->balance_wait_q);
2077779a65a4SEric Sandeen }
2078779a65a4SEric Sandeen 
20796bccf3abSJeff Mahoney static void btrfs_init_btree_inode(struct btrfs_fs_info *fs_info)
2080f37938e0SEric Sandeen {
20812ff7e61eSJeff Mahoney 	struct inode *inode = fs_info->btree_inode;
20822ff7e61eSJeff Mahoney 
20832ff7e61eSJeff Mahoney 	inode->i_ino = BTRFS_BTREE_INODE_OBJECTID;
20842ff7e61eSJeff Mahoney 	set_nlink(inode, 1);
2085f37938e0SEric Sandeen 	/*
2086f37938e0SEric Sandeen 	 * we set the i_size on the btree inode to the max possible int.
2087f37938e0SEric Sandeen 	 * the real end of the address space is determined by all of
2088f37938e0SEric Sandeen 	 * the devices in the system
2089f37938e0SEric Sandeen 	 */
20902ff7e61eSJeff Mahoney 	inode->i_size = OFFSET_MAX;
20912ff7e61eSJeff Mahoney 	inode->i_mapping->a_ops = &btree_aops;
2092f37938e0SEric Sandeen 
20932ff7e61eSJeff Mahoney 	RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
209443eb5f29SQu Wenruo 	extent_io_tree_init(fs_info, &BTRFS_I(inode)->io_tree,
20952c53a14dSQu Wenruo 			    IO_TREE_BTREE_INODE_IO, inode);
20967b439738SDavid Sterba 	BTRFS_I(inode)->io_tree.track_uptodate = false;
20972ff7e61eSJeff Mahoney 	extent_map_tree_init(&BTRFS_I(inode)->extent_tree);
2098f37938e0SEric Sandeen 
20995c8fd99fSJosef Bacik 	BTRFS_I(inode)->root = btrfs_grab_root(fs_info->tree_root);
21002ff7e61eSJeff Mahoney 	memset(&BTRFS_I(inode)->location, 0, sizeof(struct btrfs_key));
21012ff7e61eSJeff Mahoney 	set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
21022ff7e61eSJeff Mahoney 	btrfs_insert_inode_hash(inode);
2103f37938e0SEric Sandeen }
2104f37938e0SEric Sandeen 
2105ad618368SEric Sandeen static void btrfs_init_dev_replace_locks(struct btrfs_fs_info *fs_info)
2106ad618368SEric Sandeen {
2107ad618368SEric Sandeen 	mutex_init(&fs_info->dev_replace.lock_finishing_cancel_unmount);
2108129827e3SDavid Sterba 	init_rwsem(&fs_info->dev_replace.rwsem);
21097f8d236aSDavid Sterba 	init_waitqueue_head(&fs_info->dev_replace.replace_wait);
2110ad618368SEric Sandeen }
2111ad618368SEric Sandeen 
2112f9e92e40SEric Sandeen static void btrfs_init_qgroup(struct btrfs_fs_info *fs_info)
2113f9e92e40SEric Sandeen {
2114f9e92e40SEric Sandeen 	spin_lock_init(&fs_info->qgroup_lock);
2115f9e92e40SEric Sandeen 	mutex_init(&fs_info->qgroup_ioctl_lock);
2116f9e92e40SEric Sandeen 	fs_info->qgroup_tree = RB_ROOT;
2117f9e92e40SEric Sandeen 	INIT_LIST_HEAD(&fs_info->dirty_qgroups);
2118f9e92e40SEric Sandeen 	fs_info->qgroup_seq = 1;
2119f9e92e40SEric Sandeen 	fs_info->qgroup_ulist = NULL;
2120d2c609b8SJeff Mahoney 	fs_info->qgroup_rescan_running = false;
2121f9e92e40SEric Sandeen 	mutex_init(&fs_info->qgroup_rescan_lock);
2122f9e92e40SEric Sandeen }
2123f9e92e40SEric Sandeen 
21242a458198SEric Sandeen static int btrfs_init_workqueues(struct btrfs_fs_info *fs_info,
21252a458198SEric Sandeen 		struct btrfs_fs_devices *fs_devices)
21262a458198SEric Sandeen {
2127f7b885beSAnand Jain 	u32 max_active = fs_info->thread_pool_size;
21286f011058SDavid Sterba 	unsigned int flags = WQ_MEM_RECLAIM | WQ_FREEZABLE | WQ_UNBOUND;
21292a458198SEric Sandeen 
21302a458198SEric Sandeen 	fs_info->workers =
2131cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "worker",
2132cb001095SJeff Mahoney 				      flags | WQ_HIGHPRI, max_active, 16);
21332a458198SEric Sandeen 
21342a458198SEric Sandeen 	fs_info->delalloc_workers =
2135cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "delalloc",
2136cb001095SJeff Mahoney 				      flags, max_active, 2);
21372a458198SEric Sandeen 
21382a458198SEric Sandeen 	fs_info->flush_workers =
2139cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "flush_delalloc",
2140cb001095SJeff Mahoney 				      flags, max_active, 0);
21412a458198SEric Sandeen 
21422a458198SEric Sandeen 	fs_info->caching_workers =
2143cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "cache", flags, max_active, 0);
21442a458198SEric Sandeen 
21452a458198SEric Sandeen 	fs_info->fixup_workers =
2146cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "fixup", flags, 1, 0);
21472a458198SEric Sandeen 
21482a458198SEric Sandeen 	/*
21492a458198SEric Sandeen 	 * endios are largely parallel and should have a very
21502a458198SEric Sandeen 	 * low idle thresh
21512a458198SEric Sandeen 	 */
21522a458198SEric Sandeen 	fs_info->endio_workers =
2153cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio", flags, max_active, 4);
21542a458198SEric Sandeen 	fs_info->endio_meta_workers =
2155cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio-meta", flags,
2156cb001095SJeff Mahoney 				      max_active, 4);
21572a458198SEric Sandeen 	fs_info->endio_meta_write_workers =
2158cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio-meta-write", flags,
2159cb001095SJeff Mahoney 				      max_active, 2);
21602a458198SEric Sandeen 	fs_info->endio_raid56_workers =
2161cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio-raid56", flags,
2162cb001095SJeff Mahoney 				      max_active, 4);
21632a458198SEric Sandeen 	fs_info->rmw_workers =
2164cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "rmw", flags, max_active, 2);
21652a458198SEric Sandeen 	fs_info->endio_write_workers =
2166cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio-write", flags,
2167cb001095SJeff Mahoney 				      max_active, 2);
21682a458198SEric Sandeen 	fs_info->endio_freespace_worker =
2169cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "freespace-write", flags,
2170cb001095SJeff Mahoney 				      max_active, 0);
21712a458198SEric Sandeen 	fs_info->delayed_workers =
2172cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "delayed-meta", flags,
2173cb001095SJeff Mahoney 				      max_active, 0);
21742a458198SEric Sandeen 	fs_info->readahead_workers =
2175cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "readahead", flags,
2176cb001095SJeff Mahoney 				      max_active, 2);
21772a458198SEric Sandeen 	fs_info->qgroup_rescan_workers =
2178cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "qgroup-rescan", flags, 1, 0);
2179b0643e59SDennis Zhou 	fs_info->discard_ctl.discard_workers =
2180b0643e59SDennis Zhou 		alloc_workqueue("btrfs_discard", WQ_UNBOUND | WQ_FREEZABLE, 1);
21812a458198SEric Sandeen 
21822a458198SEric Sandeen 	if (!(fs_info->workers && fs_info->delalloc_workers &&
2183ba8a9d07SChris Mason 	      fs_info->flush_workers &&
21842a458198SEric Sandeen 	      fs_info->endio_workers && fs_info->endio_meta_workers &&
21852a458198SEric Sandeen 	      fs_info->endio_meta_write_workers &&
21862a458198SEric Sandeen 	      fs_info->endio_write_workers && fs_info->endio_raid56_workers &&
21872a458198SEric Sandeen 	      fs_info->endio_freespace_worker && fs_info->rmw_workers &&
21882a458198SEric Sandeen 	      fs_info->caching_workers && fs_info->readahead_workers &&
21892a458198SEric Sandeen 	      fs_info->fixup_workers && fs_info->delayed_workers &&
2190b0643e59SDennis Zhou 	      fs_info->qgroup_rescan_workers &&
2191b0643e59SDennis Zhou 	      fs_info->discard_ctl.discard_workers)) {
21922a458198SEric Sandeen 		return -ENOMEM;
21932a458198SEric Sandeen 	}
21942a458198SEric Sandeen 
21952a458198SEric Sandeen 	return 0;
21962a458198SEric Sandeen }
21972a458198SEric Sandeen 
21986d97c6e3SJohannes Thumshirn static int btrfs_init_csum_hash(struct btrfs_fs_info *fs_info, u16 csum_type)
21996d97c6e3SJohannes Thumshirn {
22006d97c6e3SJohannes Thumshirn 	struct crypto_shash *csum_shash;
2201b4e967beSDavid Sterba 	const char *csum_driver = btrfs_super_csum_driver(csum_type);
22026d97c6e3SJohannes Thumshirn 
2203b4e967beSDavid Sterba 	csum_shash = crypto_alloc_shash(csum_driver, 0, 0);
22046d97c6e3SJohannes Thumshirn 
22056d97c6e3SJohannes Thumshirn 	if (IS_ERR(csum_shash)) {
22066d97c6e3SJohannes Thumshirn 		btrfs_err(fs_info, "error allocating %s hash for checksum",
2207b4e967beSDavid Sterba 			  csum_driver);
22086d97c6e3SJohannes Thumshirn 		return PTR_ERR(csum_shash);
22096d97c6e3SJohannes Thumshirn 	}
22106d97c6e3SJohannes Thumshirn 
22116d97c6e3SJohannes Thumshirn 	fs_info->csum_shash = csum_shash;
22126d97c6e3SJohannes Thumshirn 
22136d97c6e3SJohannes Thumshirn 	return 0;
22146d97c6e3SJohannes Thumshirn }
22156d97c6e3SJohannes Thumshirn 
221663443bf5SEric Sandeen static int btrfs_replay_log(struct btrfs_fs_info *fs_info,
221763443bf5SEric Sandeen 			    struct btrfs_fs_devices *fs_devices)
221863443bf5SEric Sandeen {
221963443bf5SEric Sandeen 	int ret;
222063443bf5SEric Sandeen 	struct btrfs_root *log_tree_root;
222163443bf5SEric Sandeen 	struct btrfs_super_block *disk_super = fs_info->super_copy;
222263443bf5SEric Sandeen 	u64 bytenr = btrfs_super_log_root(disk_super);
2223581c1760SQu Wenruo 	int level = btrfs_super_log_root_level(disk_super);
222463443bf5SEric Sandeen 
222563443bf5SEric Sandeen 	if (fs_devices->rw_devices == 0) {
2226f14d104dSDavid Sterba 		btrfs_warn(fs_info, "log replay required on RO media");
222763443bf5SEric Sandeen 		return -EIO;
222863443bf5SEric Sandeen 	}
222963443bf5SEric Sandeen 
223096dfcb46SJosef Bacik 	log_tree_root = btrfs_alloc_root(fs_info, BTRFS_TREE_LOG_OBJECTID,
223196dfcb46SJosef Bacik 					 GFP_KERNEL);
223263443bf5SEric Sandeen 	if (!log_tree_root)
223363443bf5SEric Sandeen 		return -ENOMEM;
223463443bf5SEric Sandeen 
22352ff7e61eSJeff Mahoney 	log_tree_root->node = read_tree_block(fs_info, bytenr,
22361b7ec85eSJosef Bacik 					      BTRFS_TREE_LOG_OBJECTID,
22371b7ec85eSJosef Bacik 					      fs_info->generation + 1, level,
22381b7ec85eSJosef Bacik 					      NULL);
223964c043deSLiu Bo 	if (IS_ERR(log_tree_root->node)) {
2240f14d104dSDavid Sterba 		btrfs_warn(fs_info, "failed to read log tree");
22410eeff236SLiu Bo 		ret = PTR_ERR(log_tree_root->node);
22428c38938cSJosef Bacik 		log_tree_root->node = NULL;
224300246528SJosef Bacik 		btrfs_put_root(log_tree_root);
22440eeff236SLiu Bo 		return ret;
224564c043deSLiu Bo 	} else if (!extent_buffer_uptodate(log_tree_root->node)) {
2246f14d104dSDavid Sterba 		btrfs_err(fs_info, "failed to read log tree");
224700246528SJosef Bacik 		btrfs_put_root(log_tree_root);
224863443bf5SEric Sandeen 		return -EIO;
224963443bf5SEric Sandeen 	}
225063443bf5SEric Sandeen 	/* returns with log_tree_root freed on success */
225163443bf5SEric Sandeen 	ret = btrfs_recover_log_trees(log_tree_root);
225263443bf5SEric Sandeen 	if (ret) {
22530b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, ret,
225463443bf5SEric Sandeen 				      "Failed to recover log tree");
225500246528SJosef Bacik 		btrfs_put_root(log_tree_root);
225663443bf5SEric Sandeen 		return ret;
225763443bf5SEric Sandeen 	}
225863443bf5SEric Sandeen 
2259bc98a42cSDavid Howells 	if (sb_rdonly(fs_info->sb)) {
22606bccf3abSJeff Mahoney 		ret = btrfs_commit_super(fs_info);
226163443bf5SEric Sandeen 		if (ret)
226263443bf5SEric Sandeen 			return ret;
226363443bf5SEric Sandeen 	}
226463443bf5SEric Sandeen 
226563443bf5SEric Sandeen 	return 0;
226663443bf5SEric Sandeen }
226763443bf5SEric Sandeen 
22686bccf3abSJeff Mahoney static int btrfs_read_roots(struct btrfs_fs_info *fs_info)
22694bbcaa64SEric Sandeen {
22706bccf3abSJeff Mahoney 	struct btrfs_root *tree_root = fs_info->tree_root;
2271a4f3d2c4SDavid Sterba 	struct btrfs_root *root;
22724bbcaa64SEric Sandeen 	struct btrfs_key location;
22734bbcaa64SEric Sandeen 	int ret;
22744bbcaa64SEric Sandeen 
22756bccf3abSJeff Mahoney 	BUG_ON(!fs_info->tree_root);
22766bccf3abSJeff Mahoney 
22774bbcaa64SEric Sandeen 	location.objectid = BTRFS_EXTENT_TREE_OBJECTID;
22784bbcaa64SEric Sandeen 	location.type = BTRFS_ROOT_ITEM_KEY;
22794bbcaa64SEric Sandeen 	location.offset = 0;
22804bbcaa64SEric Sandeen 
2281a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2282f50f4353SLiu Bo 	if (IS_ERR(root)) {
228342437a63SJosef Bacik 		if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2284f50f4353SLiu Bo 			ret = PTR_ERR(root);
2285f50f4353SLiu Bo 			goto out;
2286f50f4353SLiu Bo 		}
228742437a63SJosef Bacik 	} else {
2288a4f3d2c4SDavid Sterba 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2289a4f3d2c4SDavid Sterba 		fs_info->extent_root = root;
229042437a63SJosef Bacik 	}
22914bbcaa64SEric Sandeen 
22924bbcaa64SEric Sandeen 	location.objectid = BTRFS_DEV_TREE_OBJECTID;
2293a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2294f50f4353SLiu Bo 	if (IS_ERR(root)) {
229542437a63SJosef Bacik 		if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2296f50f4353SLiu Bo 			ret = PTR_ERR(root);
2297f50f4353SLiu Bo 			goto out;
2298f50f4353SLiu Bo 		}
229942437a63SJosef Bacik 	} else {
2300a4f3d2c4SDavid Sterba 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2301a4f3d2c4SDavid Sterba 		fs_info->dev_root = root;
23024bbcaa64SEric Sandeen 		btrfs_init_devices_late(fs_info);
230342437a63SJosef Bacik 	}
23044bbcaa64SEric Sandeen 
2305882dbe0cSJosef Bacik 	/* If IGNOREDATACSUMS is set don't bother reading the csum root. */
2306882dbe0cSJosef Bacik 	if (!btrfs_test_opt(fs_info, IGNOREDATACSUMS)) {
23074bbcaa64SEric Sandeen 		location.objectid = BTRFS_CSUM_TREE_OBJECTID;
2308a4f3d2c4SDavid Sterba 		root = btrfs_read_tree_root(tree_root, &location);
2309f50f4353SLiu Bo 		if (IS_ERR(root)) {
231042437a63SJosef Bacik 			if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2311f50f4353SLiu Bo 				ret = PTR_ERR(root);
2312f50f4353SLiu Bo 				goto out;
2313f50f4353SLiu Bo 			}
231442437a63SJosef Bacik 		} else {
2315a4f3d2c4SDavid Sterba 			set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2316a4f3d2c4SDavid Sterba 			fs_info->csum_root = root;
231742437a63SJosef Bacik 		}
2318882dbe0cSJosef Bacik 	}
23194bbcaa64SEric Sandeen 
2320aeb935a4SQu Wenruo 	/*
2321aeb935a4SQu Wenruo 	 * This tree can share blocks with some other fs tree during relocation
2322aeb935a4SQu Wenruo 	 * and we need a proper setup by btrfs_get_fs_root
2323aeb935a4SQu Wenruo 	 */
232456e9357aSDavid Sterba 	root = btrfs_get_fs_root(tree_root->fs_info,
232556e9357aSDavid Sterba 				 BTRFS_DATA_RELOC_TREE_OBJECTID, true);
2326aeb935a4SQu Wenruo 	if (IS_ERR(root)) {
232742437a63SJosef Bacik 		if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2328aeb935a4SQu Wenruo 			ret = PTR_ERR(root);
2329aeb935a4SQu Wenruo 			goto out;
2330aeb935a4SQu Wenruo 		}
233142437a63SJosef Bacik 	} else {
2332aeb935a4SQu Wenruo 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2333aeb935a4SQu Wenruo 		fs_info->data_reloc_root = root;
233442437a63SJosef Bacik 	}
2335aeb935a4SQu Wenruo 
23364bbcaa64SEric Sandeen 	location.objectid = BTRFS_QUOTA_TREE_OBJECTID;
2337a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2338a4f3d2c4SDavid Sterba 	if (!IS_ERR(root)) {
2339a4f3d2c4SDavid Sterba 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2340afcdd129SJosef Bacik 		set_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags);
2341a4f3d2c4SDavid Sterba 		fs_info->quota_root = root;
23424bbcaa64SEric Sandeen 	}
23434bbcaa64SEric Sandeen 
23444bbcaa64SEric Sandeen 	location.objectid = BTRFS_UUID_TREE_OBJECTID;
2345a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2346a4f3d2c4SDavid Sterba 	if (IS_ERR(root)) {
234742437a63SJosef Bacik 		if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2348a4f3d2c4SDavid Sterba 			ret = PTR_ERR(root);
23494bbcaa64SEric Sandeen 			if (ret != -ENOENT)
2350f50f4353SLiu Bo 				goto out;
235142437a63SJosef Bacik 		}
23524bbcaa64SEric Sandeen 	} else {
2353a4f3d2c4SDavid Sterba 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2354a4f3d2c4SDavid Sterba 		fs_info->uuid_root = root;
23554bbcaa64SEric Sandeen 	}
23564bbcaa64SEric Sandeen 
235770f6d82eSOmar Sandoval 	if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
235870f6d82eSOmar Sandoval 		location.objectid = BTRFS_FREE_SPACE_TREE_OBJECTID;
235970f6d82eSOmar Sandoval 		root = btrfs_read_tree_root(tree_root, &location);
2360f50f4353SLiu Bo 		if (IS_ERR(root)) {
236142437a63SJosef Bacik 			if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2362f50f4353SLiu Bo 				ret = PTR_ERR(root);
2363f50f4353SLiu Bo 				goto out;
2364f50f4353SLiu Bo 			}
236542437a63SJosef Bacik 		}  else {
236670f6d82eSOmar Sandoval 			set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
236770f6d82eSOmar Sandoval 			fs_info->free_space_root = root;
236870f6d82eSOmar Sandoval 		}
236942437a63SJosef Bacik 	}
237070f6d82eSOmar Sandoval 
23714bbcaa64SEric Sandeen 	return 0;
2372f50f4353SLiu Bo out:
2373f50f4353SLiu Bo 	btrfs_warn(fs_info, "failed to read root (objectid=%llu): %d",
2374f50f4353SLiu Bo 		   location.objectid, ret);
2375f50f4353SLiu Bo 	return ret;
23764bbcaa64SEric Sandeen }
23774bbcaa64SEric Sandeen 
2378069ec957SQu Wenruo /*
2379069ec957SQu Wenruo  * Real super block validation
2380069ec957SQu Wenruo  * NOTE: super csum type and incompat features will not be checked here.
2381069ec957SQu Wenruo  *
2382069ec957SQu Wenruo  * @sb:		super block to check
2383069ec957SQu Wenruo  * @mirror_num:	the super block number to check its bytenr:
2384069ec957SQu Wenruo  * 		0	the primary (1st) sb
2385069ec957SQu Wenruo  * 		1, 2	2nd and 3rd backup copy
2386069ec957SQu Wenruo  * 	       -1	skip bytenr check
2387069ec957SQu Wenruo  */
2388069ec957SQu Wenruo static int validate_super(struct btrfs_fs_info *fs_info,
2389069ec957SQu Wenruo 			    struct btrfs_super_block *sb, int mirror_num)
239021a852b0SQu Wenruo {
239121a852b0SQu Wenruo 	u64 nodesize = btrfs_super_nodesize(sb);
239221a852b0SQu Wenruo 	u64 sectorsize = btrfs_super_sectorsize(sb);
239321a852b0SQu Wenruo 	int ret = 0;
239421a852b0SQu Wenruo 
239521a852b0SQu Wenruo 	if (btrfs_super_magic(sb) != BTRFS_MAGIC) {
239621a852b0SQu Wenruo 		btrfs_err(fs_info, "no valid FS found");
239721a852b0SQu Wenruo 		ret = -EINVAL;
239821a852b0SQu Wenruo 	}
239921a852b0SQu Wenruo 	if (btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP) {
240021a852b0SQu Wenruo 		btrfs_err(fs_info, "unrecognized or unsupported super flag: %llu",
240121a852b0SQu Wenruo 				btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP);
240221a852b0SQu Wenruo 		ret = -EINVAL;
240321a852b0SQu Wenruo 	}
240421a852b0SQu Wenruo 	if (btrfs_super_root_level(sb) >= BTRFS_MAX_LEVEL) {
240521a852b0SQu Wenruo 		btrfs_err(fs_info, "tree_root level too big: %d >= %d",
240621a852b0SQu Wenruo 				btrfs_super_root_level(sb), BTRFS_MAX_LEVEL);
240721a852b0SQu Wenruo 		ret = -EINVAL;
240821a852b0SQu Wenruo 	}
240921a852b0SQu Wenruo 	if (btrfs_super_chunk_root_level(sb) >= BTRFS_MAX_LEVEL) {
241021a852b0SQu Wenruo 		btrfs_err(fs_info, "chunk_root level too big: %d >= %d",
241121a852b0SQu Wenruo 				btrfs_super_chunk_root_level(sb), BTRFS_MAX_LEVEL);
241221a852b0SQu Wenruo 		ret = -EINVAL;
241321a852b0SQu Wenruo 	}
241421a852b0SQu Wenruo 	if (btrfs_super_log_root_level(sb) >= BTRFS_MAX_LEVEL) {
241521a852b0SQu Wenruo 		btrfs_err(fs_info, "log_root level too big: %d >= %d",
241621a852b0SQu Wenruo 				btrfs_super_log_root_level(sb), BTRFS_MAX_LEVEL);
241721a852b0SQu Wenruo 		ret = -EINVAL;
241821a852b0SQu Wenruo 	}
241921a852b0SQu Wenruo 
242021a852b0SQu Wenruo 	/*
242121a852b0SQu Wenruo 	 * Check sectorsize and nodesize first, other check will need it.
242221a852b0SQu Wenruo 	 * Check all possible sectorsize(4K, 8K, 16K, 32K, 64K) here.
242321a852b0SQu Wenruo 	 */
242421a852b0SQu Wenruo 	if (!is_power_of_2(sectorsize) || sectorsize < 4096 ||
242521a852b0SQu Wenruo 	    sectorsize > BTRFS_MAX_METADATA_BLOCKSIZE) {
242621a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid sectorsize %llu", sectorsize);
242721a852b0SQu Wenruo 		ret = -EINVAL;
242821a852b0SQu Wenruo 	}
242921a852b0SQu Wenruo 	/* Only PAGE SIZE is supported yet */
243021a852b0SQu Wenruo 	if (sectorsize != PAGE_SIZE) {
243121a852b0SQu Wenruo 		btrfs_err(fs_info,
243221a852b0SQu Wenruo 			"sectorsize %llu not supported yet, only support %lu",
243321a852b0SQu Wenruo 			sectorsize, PAGE_SIZE);
243421a852b0SQu Wenruo 		ret = -EINVAL;
243521a852b0SQu Wenruo 	}
243621a852b0SQu Wenruo 	if (!is_power_of_2(nodesize) || nodesize < sectorsize ||
243721a852b0SQu Wenruo 	    nodesize > BTRFS_MAX_METADATA_BLOCKSIZE) {
243821a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid nodesize %llu", nodesize);
243921a852b0SQu Wenruo 		ret = -EINVAL;
244021a852b0SQu Wenruo 	}
244121a852b0SQu Wenruo 	if (nodesize != le32_to_cpu(sb->__unused_leafsize)) {
244221a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid leafsize %u, should be %llu",
244321a852b0SQu Wenruo 			  le32_to_cpu(sb->__unused_leafsize), nodesize);
244421a852b0SQu Wenruo 		ret = -EINVAL;
244521a852b0SQu Wenruo 	}
244621a852b0SQu Wenruo 
244721a852b0SQu Wenruo 	/* Root alignment check */
244821a852b0SQu Wenruo 	if (!IS_ALIGNED(btrfs_super_root(sb), sectorsize)) {
244921a852b0SQu Wenruo 		btrfs_warn(fs_info, "tree_root block unaligned: %llu",
245021a852b0SQu Wenruo 			   btrfs_super_root(sb));
245121a852b0SQu Wenruo 		ret = -EINVAL;
245221a852b0SQu Wenruo 	}
245321a852b0SQu Wenruo 	if (!IS_ALIGNED(btrfs_super_chunk_root(sb), sectorsize)) {
245421a852b0SQu Wenruo 		btrfs_warn(fs_info, "chunk_root block unaligned: %llu",
245521a852b0SQu Wenruo 			   btrfs_super_chunk_root(sb));
245621a852b0SQu Wenruo 		ret = -EINVAL;
245721a852b0SQu Wenruo 	}
245821a852b0SQu Wenruo 	if (!IS_ALIGNED(btrfs_super_log_root(sb), sectorsize)) {
245921a852b0SQu Wenruo 		btrfs_warn(fs_info, "log_root block unaligned: %llu",
246021a852b0SQu Wenruo 			   btrfs_super_log_root(sb));
246121a852b0SQu Wenruo 		ret = -EINVAL;
246221a852b0SQu Wenruo 	}
246321a852b0SQu Wenruo 
2464de37aa51SNikolay Borisov 	if (memcmp(fs_info->fs_devices->metadata_uuid, sb->dev_item.fsid,
24657239ff4bSNikolay Borisov 		   BTRFS_FSID_SIZE) != 0) {
246621a852b0SQu Wenruo 		btrfs_err(fs_info,
24677239ff4bSNikolay Borisov 			"dev_item UUID does not match metadata fsid: %pU != %pU",
2468de37aa51SNikolay Borisov 			fs_info->fs_devices->metadata_uuid, sb->dev_item.fsid);
246921a852b0SQu Wenruo 		ret = -EINVAL;
247021a852b0SQu Wenruo 	}
247121a852b0SQu Wenruo 
247221a852b0SQu Wenruo 	/*
247321a852b0SQu Wenruo 	 * Hint to catch really bogus numbers, bitflips or so, more exact checks are
247421a852b0SQu Wenruo 	 * done later
247521a852b0SQu Wenruo 	 */
247621a852b0SQu Wenruo 	if (btrfs_super_bytes_used(sb) < 6 * btrfs_super_nodesize(sb)) {
247721a852b0SQu Wenruo 		btrfs_err(fs_info, "bytes_used is too small %llu",
247821a852b0SQu Wenruo 			  btrfs_super_bytes_used(sb));
247921a852b0SQu Wenruo 		ret = -EINVAL;
248021a852b0SQu Wenruo 	}
248121a852b0SQu Wenruo 	if (!is_power_of_2(btrfs_super_stripesize(sb))) {
248221a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid stripesize %u",
248321a852b0SQu Wenruo 			  btrfs_super_stripesize(sb));
248421a852b0SQu Wenruo 		ret = -EINVAL;
248521a852b0SQu Wenruo 	}
248621a852b0SQu Wenruo 	if (btrfs_super_num_devices(sb) > (1UL << 31))
248721a852b0SQu Wenruo 		btrfs_warn(fs_info, "suspicious number of devices: %llu",
248821a852b0SQu Wenruo 			   btrfs_super_num_devices(sb));
248921a852b0SQu Wenruo 	if (btrfs_super_num_devices(sb) == 0) {
249021a852b0SQu Wenruo 		btrfs_err(fs_info, "number of devices is 0");
249121a852b0SQu Wenruo 		ret = -EINVAL;
249221a852b0SQu Wenruo 	}
249321a852b0SQu Wenruo 
2494069ec957SQu Wenruo 	if (mirror_num >= 0 &&
2495069ec957SQu Wenruo 	    btrfs_super_bytenr(sb) != btrfs_sb_offset(mirror_num)) {
249621a852b0SQu Wenruo 		btrfs_err(fs_info, "super offset mismatch %llu != %u",
249721a852b0SQu Wenruo 			  btrfs_super_bytenr(sb), BTRFS_SUPER_INFO_OFFSET);
249821a852b0SQu Wenruo 		ret = -EINVAL;
249921a852b0SQu Wenruo 	}
250021a852b0SQu Wenruo 
250121a852b0SQu Wenruo 	/*
250221a852b0SQu Wenruo 	 * Obvious sys_chunk_array corruptions, it must hold at least one key
250321a852b0SQu Wenruo 	 * and one chunk
250421a852b0SQu Wenruo 	 */
250521a852b0SQu Wenruo 	if (btrfs_super_sys_array_size(sb) > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
250621a852b0SQu Wenruo 		btrfs_err(fs_info, "system chunk array too big %u > %u",
250721a852b0SQu Wenruo 			  btrfs_super_sys_array_size(sb),
250821a852b0SQu Wenruo 			  BTRFS_SYSTEM_CHUNK_ARRAY_SIZE);
250921a852b0SQu Wenruo 		ret = -EINVAL;
251021a852b0SQu Wenruo 	}
251121a852b0SQu Wenruo 	if (btrfs_super_sys_array_size(sb) < sizeof(struct btrfs_disk_key)
251221a852b0SQu Wenruo 			+ sizeof(struct btrfs_chunk)) {
251321a852b0SQu Wenruo 		btrfs_err(fs_info, "system chunk array too small %u < %zu",
251421a852b0SQu Wenruo 			  btrfs_super_sys_array_size(sb),
251521a852b0SQu Wenruo 			  sizeof(struct btrfs_disk_key)
251621a852b0SQu Wenruo 			  + sizeof(struct btrfs_chunk));
251721a852b0SQu Wenruo 		ret = -EINVAL;
251821a852b0SQu Wenruo 	}
251921a852b0SQu Wenruo 
252021a852b0SQu Wenruo 	/*
252121a852b0SQu Wenruo 	 * The generation is a global counter, we'll trust it more than the others
252221a852b0SQu Wenruo 	 * but it's still possible that it's the one that's wrong.
252321a852b0SQu Wenruo 	 */
252421a852b0SQu Wenruo 	if (btrfs_super_generation(sb) < btrfs_super_chunk_root_generation(sb))
252521a852b0SQu Wenruo 		btrfs_warn(fs_info,
252621a852b0SQu Wenruo 			"suspicious: generation < chunk_root_generation: %llu < %llu",
252721a852b0SQu Wenruo 			btrfs_super_generation(sb),
252821a852b0SQu Wenruo 			btrfs_super_chunk_root_generation(sb));
252921a852b0SQu Wenruo 	if (btrfs_super_generation(sb) < btrfs_super_cache_generation(sb)
253021a852b0SQu Wenruo 	    && btrfs_super_cache_generation(sb) != (u64)-1)
253121a852b0SQu Wenruo 		btrfs_warn(fs_info,
253221a852b0SQu Wenruo 			"suspicious: generation < cache_generation: %llu < %llu",
253321a852b0SQu Wenruo 			btrfs_super_generation(sb),
253421a852b0SQu Wenruo 			btrfs_super_cache_generation(sb));
253521a852b0SQu Wenruo 
253621a852b0SQu Wenruo 	return ret;
253721a852b0SQu Wenruo }
253821a852b0SQu Wenruo 
2539069ec957SQu Wenruo /*
2540069ec957SQu Wenruo  * Validation of super block at mount time.
2541069ec957SQu Wenruo  * Some checks already done early at mount time, like csum type and incompat
2542069ec957SQu Wenruo  * flags will be skipped.
2543069ec957SQu Wenruo  */
2544069ec957SQu Wenruo static int btrfs_validate_mount_super(struct btrfs_fs_info *fs_info)
2545069ec957SQu Wenruo {
2546069ec957SQu Wenruo 	return validate_super(fs_info, fs_info->super_copy, 0);
2547069ec957SQu Wenruo }
2548069ec957SQu Wenruo 
254975cb857dSQu Wenruo /*
255075cb857dSQu Wenruo  * Validation of super block at write time.
255175cb857dSQu Wenruo  * Some checks like bytenr check will be skipped as their values will be
255275cb857dSQu Wenruo  * overwritten soon.
255375cb857dSQu Wenruo  * Extra checks like csum type and incompat flags will be done here.
255475cb857dSQu Wenruo  */
255575cb857dSQu Wenruo static int btrfs_validate_write_super(struct btrfs_fs_info *fs_info,
255675cb857dSQu Wenruo 				      struct btrfs_super_block *sb)
255775cb857dSQu Wenruo {
255875cb857dSQu Wenruo 	int ret;
255975cb857dSQu Wenruo 
256075cb857dSQu Wenruo 	ret = validate_super(fs_info, sb, -1);
256175cb857dSQu Wenruo 	if (ret < 0)
256275cb857dSQu Wenruo 		goto out;
2563e7e16f48SJohannes Thumshirn 	if (!btrfs_supported_super_csum(btrfs_super_csum_type(sb))) {
256475cb857dSQu Wenruo 		ret = -EUCLEAN;
256575cb857dSQu Wenruo 		btrfs_err(fs_info, "invalid csum type, has %u want %u",
256675cb857dSQu Wenruo 			  btrfs_super_csum_type(sb), BTRFS_CSUM_TYPE_CRC32);
256775cb857dSQu Wenruo 		goto out;
256875cb857dSQu Wenruo 	}
256975cb857dSQu Wenruo 	if (btrfs_super_incompat_flags(sb) & ~BTRFS_FEATURE_INCOMPAT_SUPP) {
257075cb857dSQu Wenruo 		ret = -EUCLEAN;
257175cb857dSQu Wenruo 		btrfs_err(fs_info,
257275cb857dSQu Wenruo 		"invalid incompat flags, has 0x%llx valid mask 0x%llx",
257375cb857dSQu Wenruo 			  btrfs_super_incompat_flags(sb),
257475cb857dSQu Wenruo 			  (unsigned long long)BTRFS_FEATURE_INCOMPAT_SUPP);
257575cb857dSQu Wenruo 		goto out;
257675cb857dSQu Wenruo 	}
257775cb857dSQu Wenruo out:
257875cb857dSQu Wenruo 	if (ret < 0)
257975cb857dSQu Wenruo 		btrfs_err(fs_info,
258075cb857dSQu Wenruo 		"super block corruption detected before writing it to disk");
258175cb857dSQu Wenruo 	return ret;
258275cb857dSQu Wenruo }
258375cb857dSQu Wenruo 
25846ef108ddSNikolay Borisov static int __cold init_tree_roots(struct btrfs_fs_info *fs_info)
2585b8522a1eSNikolay Borisov {
25866ef108ddSNikolay Borisov 	int backup_index = find_newest_super_backup(fs_info);
2587b8522a1eSNikolay Borisov 	struct btrfs_super_block *sb = fs_info->super_copy;
2588b8522a1eSNikolay Borisov 	struct btrfs_root *tree_root = fs_info->tree_root;
2589b8522a1eSNikolay Borisov 	bool handle_error = false;
2590b8522a1eSNikolay Borisov 	int ret = 0;
2591b8522a1eSNikolay Borisov 	int i;
2592b8522a1eSNikolay Borisov 
2593b8522a1eSNikolay Borisov 	for (i = 0; i < BTRFS_NUM_BACKUP_ROOTS; i++) {
2594b8522a1eSNikolay Borisov 		u64 generation;
2595b8522a1eSNikolay Borisov 		int level;
2596b8522a1eSNikolay Borisov 
2597b8522a1eSNikolay Borisov 		if (handle_error) {
2598b8522a1eSNikolay Borisov 			if (!IS_ERR(tree_root->node))
2599b8522a1eSNikolay Borisov 				free_extent_buffer(tree_root->node);
2600b8522a1eSNikolay Borisov 			tree_root->node = NULL;
2601b8522a1eSNikolay Borisov 
2602b8522a1eSNikolay Borisov 			if (!btrfs_test_opt(fs_info, USEBACKUPROOT))
2603b8522a1eSNikolay Borisov 				break;
2604b8522a1eSNikolay Borisov 
2605b8522a1eSNikolay Borisov 			free_root_pointers(fs_info, 0);
2606b8522a1eSNikolay Borisov 
2607b8522a1eSNikolay Borisov 			/*
2608b8522a1eSNikolay Borisov 			 * Don't use the log in recovery mode, it won't be
2609b8522a1eSNikolay Borisov 			 * valid
2610b8522a1eSNikolay Borisov 			 */
2611b8522a1eSNikolay Borisov 			btrfs_set_super_log_root(sb, 0);
2612b8522a1eSNikolay Borisov 
2613b8522a1eSNikolay Borisov 			/* We can't trust the free space cache either */
2614b8522a1eSNikolay Borisov 			btrfs_set_opt(fs_info->mount_opt, CLEAR_CACHE);
2615b8522a1eSNikolay Borisov 
2616b8522a1eSNikolay Borisov 			ret = read_backup_root(fs_info, i);
26176ef108ddSNikolay Borisov 			backup_index = ret;
2618b8522a1eSNikolay Borisov 			if (ret < 0)
2619b8522a1eSNikolay Borisov 				return ret;
2620b8522a1eSNikolay Borisov 		}
2621b8522a1eSNikolay Borisov 		generation = btrfs_super_generation(sb);
2622b8522a1eSNikolay Borisov 		level = btrfs_super_root_level(sb);
2623b8522a1eSNikolay Borisov 		tree_root->node = read_tree_block(fs_info, btrfs_super_root(sb),
26241b7ec85eSJosef Bacik 						  BTRFS_ROOT_TREE_OBJECTID,
2625b8522a1eSNikolay Borisov 						  generation, level, NULL);
26260465337cSJosef Bacik 		if (IS_ERR(tree_root->node)) {
2627217f5004SNikolay Borisov 			handle_error = true;
2628b8522a1eSNikolay Borisov 			ret = PTR_ERR(tree_root->node);
26290465337cSJosef Bacik 			tree_root->node = NULL;
2630217f5004SNikolay Borisov 			btrfs_warn(fs_info, "couldn't read tree root");
2631217f5004SNikolay Borisov 			continue;
2632b8522a1eSNikolay Borisov 
2633217f5004SNikolay Borisov 		} else if (!extent_buffer_uptodate(tree_root->node)) {
2634217f5004SNikolay Borisov 			handle_error = true;
2635217f5004SNikolay Borisov 			ret = -EIO;
2636217f5004SNikolay Borisov 			btrfs_warn(fs_info, "error while reading tree root");
2637b8522a1eSNikolay Borisov 			continue;
2638b8522a1eSNikolay Borisov 		}
2639b8522a1eSNikolay Borisov 
2640b8522a1eSNikolay Borisov 		btrfs_set_root_node(&tree_root->root_item, tree_root->node);
2641b8522a1eSNikolay Borisov 		tree_root->commit_root = btrfs_root_node(tree_root);
2642b8522a1eSNikolay Borisov 		btrfs_set_root_refs(&tree_root->root_item, 1);
2643b8522a1eSNikolay Borisov 
2644336a0d8dSNikolay Borisov 		/*
2645336a0d8dSNikolay Borisov 		 * No need to hold btrfs_root::objectid_mutex since the fs
2646336a0d8dSNikolay Borisov 		 * hasn't been fully initialised and we are the only user
2647336a0d8dSNikolay Borisov 		 */
2648453e4873SNikolay Borisov 		ret = btrfs_init_root_free_objectid(tree_root);
2649b8522a1eSNikolay Borisov 		if (ret < 0) {
2650b8522a1eSNikolay Borisov 			handle_error = true;
2651b8522a1eSNikolay Borisov 			continue;
2652b8522a1eSNikolay Borisov 		}
2653b8522a1eSNikolay Borisov 
26546b8fad57SNikolay Borisov 		ASSERT(tree_root->free_objectid <= BTRFS_LAST_FREE_OBJECTID);
2655b8522a1eSNikolay Borisov 
2656b8522a1eSNikolay Borisov 		ret = btrfs_read_roots(fs_info);
2657b8522a1eSNikolay Borisov 		if (ret < 0) {
2658b8522a1eSNikolay Borisov 			handle_error = true;
2659b8522a1eSNikolay Borisov 			continue;
2660b8522a1eSNikolay Borisov 		}
2661b8522a1eSNikolay Borisov 
2662b8522a1eSNikolay Borisov 		/* All successful */
2663b8522a1eSNikolay Borisov 		fs_info->generation = generation;
2664b8522a1eSNikolay Borisov 		fs_info->last_trans_committed = generation;
26656ef108ddSNikolay Borisov 
26666ef108ddSNikolay Borisov 		/* Always begin writing backup roots after the one being used */
26676ef108ddSNikolay Borisov 		if (backup_index < 0) {
26686ef108ddSNikolay Borisov 			fs_info->backup_root_index = 0;
26696ef108ddSNikolay Borisov 		} else {
26706ef108ddSNikolay Borisov 			fs_info->backup_root_index = backup_index + 1;
26716ef108ddSNikolay Borisov 			fs_info->backup_root_index %= BTRFS_NUM_BACKUP_ROOTS;
26726ef108ddSNikolay Borisov 		}
2673b8522a1eSNikolay Borisov 		break;
2674b8522a1eSNikolay Borisov 	}
2675b8522a1eSNikolay Borisov 
2676b8522a1eSNikolay Borisov 	return ret;
2677b8522a1eSNikolay Borisov }
2678b8522a1eSNikolay Borisov 
26798260edbaSJosef Bacik void btrfs_init_fs_info(struct btrfs_fs_info *fs_info)
2680eb60ceacSChris Mason {
268176dda93cSYan, Zheng 	INIT_RADIX_TREE(&fs_info->fs_roots_radix, GFP_ATOMIC);
2682f28491e0SJosef Bacik 	INIT_RADIX_TREE(&fs_info->buffer_radix, GFP_ATOMIC);
26838fd17795SChris Mason 	INIT_LIST_HEAD(&fs_info->trans_list);
2684facda1e7SChris Mason 	INIT_LIST_HEAD(&fs_info->dead_roots);
268524bbcf04SYan, Zheng 	INIT_LIST_HEAD(&fs_info->delayed_iputs);
2686eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&fs_info->delalloc_roots);
268711833d66SYan Zheng 	INIT_LIST_HEAD(&fs_info->caching_block_groups);
2688eb73c1b7SMiao Xie 	spin_lock_init(&fs_info->delalloc_root_lock);
2689a4abeea4SJosef Bacik 	spin_lock_init(&fs_info->trans_lock);
269076dda93cSYan, Zheng 	spin_lock_init(&fs_info->fs_roots_radix_lock);
269124bbcf04SYan, Zheng 	spin_lock_init(&fs_info->delayed_iput_lock);
26924cb5300bSChris Mason 	spin_lock_init(&fs_info->defrag_inodes_lock);
2693ceda0864SMiao Xie 	spin_lock_init(&fs_info->super_lock);
2694f28491e0SJosef Bacik 	spin_lock_init(&fs_info->buffer_lock);
269547ab2a6cSJosef Bacik 	spin_lock_init(&fs_info->unused_bgs_lock);
2696f29021b2SJan Schmidt 	rwlock_init(&fs_info->tree_mod_log_lock);
2697d7c15171SZhao Lei 	mutex_init(&fs_info->unused_bg_unpin_mutex);
269867c5e7d4SFilipe Manana 	mutex_init(&fs_info->delete_unused_bgs_mutex);
26997585717fSChris Mason 	mutex_init(&fs_info->reloc_mutex);
2700573bfb72SMiao Xie 	mutex_init(&fs_info->delalloc_root_mutex);
2701de98ced9SMiao Xie 	seqlock_init(&fs_info->profiles_lock);
270219c00ddcSChris Mason 
27030b86a832SChris Mason 	INIT_LIST_HEAD(&fs_info->dirty_cowonly_roots);
27046324fbf3SChris Mason 	INIT_LIST_HEAD(&fs_info->space_info);
2705f29021b2SJan Schmidt 	INIT_LIST_HEAD(&fs_info->tree_mod_seq_list);
270647ab2a6cSJosef Bacik 	INIT_LIST_HEAD(&fs_info->unused_bgs);
2707bd647ce3SJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
2708bd647ce3SJosef Bacik 	INIT_LIST_HEAD(&fs_info->allocated_roots);
27093fd63727SJosef Bacik 	INIT_LIST_HEAD(&fs_info->allocated_ebs);
27103fd63727SJosef Bacik 	spin_lock_init(&fs_info->eb_leak_lock);
2711bd647ce3SJosef Bacik #endif
2712c8bf1b67SDavid Sterba 	extent_map_tree_init(&fs_info->mapping_tree);
271366d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->global_block_rsv,
271466d8f3ddSMiao Xie 			     BTRFS_BLOCK_RSV_GLOBAL);
271566d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->trans_block_rsv, BTRFS_BLOCK_RSV_TRANS);
271666d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->chunk_block_rsv, BTRFS_BLOCK_RSV_CHUNK);
271766d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->empty_block_rsv, BTRFS_BLOCK_RSV_EMPTY);
271866d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->delayed_block_rsv,
271966d8f3ddSMiao Xie 			     BTRFS_BLOCK_RSV_DELOPS);
2720ba2c4d4eSJosef Bacik 	btrfs_init_block_rsv(&fs_info->delayed_refs_rsv,
2721ba2c4d4eSJosef Bacik 			     BTRFS_BLOCK_RSV_DELREFS);
2722ba2c4d4eSJosef Bacik 
2723771ed689SChris Mason 	atomic_set(&fs_info->async_delalloc_pages, 0);
27244cb5300bSChris Mason 	atomic_set(&fs_info->defrag_running, 0);
27252fefd558SZhao Lei 	atomic_set(&fs_info->reada_works_cnt, 0);
2726034f784dSJosef Bacik 	atomic_set(&fs_info->nr_delayed_iputs, 0);
2727fc36ed7eSJan Schmidt 	atomic64_set(&fs_info->tree_mod_seq, 0);
272895ac567aSFilipe David Borba Manana 	fs_info->max_inline = BTRFS_DEFAULT_MAX_INLINE;
27299ed74f2dSJosef Bacik 	fs_info->metadata_ratio = 0;
27304cb5300bSChris Mason 	fs_info->defrag_inodes = RB_ROOT;
2731a5ed45f8SNikolay Borisov 	atomic64_set(&fs_info->free_chunk_space, 0);
2732f29021b2SJan Schmidt 	fs_info->tree_mod_log = RB_ROOT;
27338b87dc17SDavid Sterba 	fs_info->commit_interval = BTRFS_DEFAULT_COMMIT_INTERVAL;
2734f8c269d7SDavid Sterba 	fs_info->avg_delayed_ref_runtime = NSEC_PER_SEC >> 6; /* div by 64 */
273590519d66SArne Jansen 	/* readahead state */
2736d0164adcSMel Gorman 	INIT_RADIX_TREE(&fs_info->reada_tree, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
273790519d66SArne Jansen 	spin_lock_init(&fs_info->reada_lock);
2738fd708b81SJosef Bacik 	btrfs_init_ref_verify(fs_info);
2739c8b97818SChris Mason 
2740b34b086cSChris Mason 	fs_info->thread_pool_size = min_t(unsigned long,
2741b34b086cSChris Mason 					  num_online_cpus() + 2, 8);
27420afbaf8cSChris Mason 
2743199c2a9cSMiao Xie 	INIT_LIST_HEAD(&fs_info->ordered_roots);
2744199c2a9cSMiao Xie 	spin_lock_init(&fs_info->ordered_root_lock);
274569fe2d75SJosef Bacik 
2746638aa7edSEric Sandeen 	btrfs_init_scrub(fs_info);
274721adbd5cSStefan Behrens #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
274821adbd5cSStefan Behrens 	fs_info->check_integrity_print_mask = 0;
274921adbd5cSStefan Behrens #endif
2750779a65a4SEric Sandeen 	btrfs_init_balance(fs_info);
275157056740SJosef Bacik 	btrfs_init_async_reclaim_work(fs_info);
2752a2de733cSArne Jansen 
27530f9dd46cSJosef Bacik 	spin_lock_init(&fs_info->block_group_cache_lock);
27546bef4d31SEric Paris 	fs_info->block_group_cache_tree = RB_ROOT;
2755a1897fddSLiu Bo 	fs_info->first_logical_byte = (u64)-1;
27560f9dd46cSJosef Bacik 
2757fe119a6eSNikolay Borisov 	extent_io_tree_init(fs_info, &fs_info->excluded_extents,
2758fe119a6eSNikolay Borisov 			    IO_TREE_FS_EXCLUDED_EXTENTS, NULL);
2759afcdd129SJosef Bacik 	set_bit(BTRFS_FS_BARRIER, &fs_info->flags);
276039279cc3SChris Mason 
27615a3f23d5SChris Mason 	mutex_init(&fs_info->ordered_operations_mutex);
2762e02119d5SChris Mason 	mutex_init(&fs_info->tree_log_mutex);
2763925baeddSChris Mason 	mutex_init(&fs_info->chunk_mutex);
2764a74a4b97SChris Mason 	mutex_init(&fs_info->transaction_kthread_mutex);
2765a74a4b97SChris Mason 	mutex_init(&fs_info->cleaner_mutex);
27661bbc621eSChris Mason 	mutex_init(&fs_info->ro_block_group_mutex);
27679e351cc8SJosef Bacik 	init_rwsem(&fs_info->commit_root_sem);
2768c71bf099SYan, Zheng 	init_rwsem(&fs_info->cleanup_work_sem);
276976dda93cSYan, Zheng 	init_rwsem(&fs_info->subvol_sem);
2770803b2f54SStefan Behrens 	sema_init(&fs_info->uuid_tree_rescan_sem, 1);
2771fa9c0d79SChris Mason 
2772ad618368SEric Sandeen 	btrfs_init_dev_replace_locks(fs_info);
2773f9e92e40SEric Sandeen 	btrfs_init_qgroup(fs_info);
2774b0643e59SDennis Zhou 	btrfs_discard_init(fs_info);
2775416ac51dSArne Jansen 
2776fa9c0d79SChris Mason 	btrfs_init_free_cluster(&fs_info->meta_alloc_cluster);
2777fa9c0d79SChris Mason 	btrfs_init_free_cluster(&fs_info->data_alloc_cluster);
2778fa9c0d79SChris Mason 
2779e6dcd2dcSChris Mason 	init_waitqueue_head(&fs_info->transaction_throttle);
2780f9295749SChris Mason 	init_waitqueue_head(&fs_info->transaction_wait);
2781bb9c12c9SSage Weil 	init_waitqueue_head(&fs_info->transaction_blocked_wait);
27824854ddd0SChris Mason 	init_waitqueue_head(&fs_info->async_submit_wait);
2783034f784dSJosef Bacik 	init_waitqueue_head(&fs_info->delayed_iputs_wait);
27843768f368SChris Mason 
2785da17066cSJeff Mahoney 	/* Usable values until the real ones are cached from the superblock */
2786da17066cSJeff Mahoney 	fs_info->nodesize = 4096;
2787da17066cSJeff Mahoney 	fs_info->sectorsize = 4096;
2788ab108d99SDavid Sterba 	fs_info->sectorsize_bits = ilog2(4096);
2789da17066cSJeff Mahoney 	fs_info->stripesize = 4096;
2790da17066cSJeff Mahoney 
2791eede2bf3SOmar Sandoval 	spin_lock_init(&fs_info->swapfile_pins_lock);
2792eede2bf3SOmar Sandoval 	fs_info->swapfile_pins = RB_ROOT;
2793eede2bf3SOmar Sandoval 
27949e967495SFilipe Manana 	fs_info->send_in_progress = 0;
27958260edbaSJosef Bacik }
27968260edbaSJosef Bacik 
27978260edbaSJosef Bacik static int init_mount_fs_info(struct btrfs_fs_info *fs_info, struct super_block *sb)
27988260edbaSJosef Bacik {
27998260edbaSJosef Bacik 	int ret;
28008260edbaSJosef Bacik 
28018260edbaSJosef Bacik 	fs_info->sb = sb;
28028260edbaSJosef Bacik 	sb->s_blocksize = BTRFS_BDEV_BLOCKSIZE;
28038260edbaSJosef Bacik 	sb->s_blocksize_bits = blksize_bits(BTRFS_BDEV_BLOCKSIZE);
28049e967495SFilipe Manana 
28055deb17e1SJosef Bacik 	ret = percpu_counter_init(&fs_info->ordered_bytes, 0, GFP_KERNEL);
2806ae18c37aSJosef Bacik 	if (ret)
2807ae18c37aSJosef Bacik 		return ret;
2808ae18c37aSJosef Bacik 
2809ae18c37aSJosef Bacik 	ret = percpu_counter_init(&fs_info->dirty_metadata_bytes, 0, GFP_KERNEL);
2810ae18c37aSJosef Bacik 	if (ret)
2811c75e8394SJosef Bacik 		return ret;
2812ae18c37aSJosef Bacik 
2813ae18c37aSJosef Bacik 	fs_info->dirty_metadata_batch = PAGE_SIZE *
2814ae18c37aSJosef Bacik 					(1 + ilog2(nr_cpu_ids));
2815ae18c37aSJosef Bacik 
2816ae18c37aSJosef Bacik 	ret = percpu_counter_init(&fs_info->delalloc_bytes, 0, GFP_KERNEL);
2817ae18c37aSJosef Bacik 	if (ret)
2818c75e8394SJosef Bacik 		return ret;
2819ae18c37aSJosef Bacik 
2820ae18c37aSJosef Bacik 	ret = percpu_counter_init(&fs_info->dev_replace.bio_counter, 0,
2821ae18c37aSJosef Bacik 			GFP_KERNEL);
2822ae18c37aSJosef Bacik 	if (ret)
2823c75e8394SJosef Bacik 		return ret;
2824ae18c37aSJosef Bacik 
2825ae18c37aSJosef Bacik 	fs_info->delayed_root = kmalloc(sizeof(struct btrfs_delayed_root),
2826ae18c37aSJosef Bacik 					GFP_KERNEL);
2827c75e8394SJosef Bacik 	if (!fs_info->delayed_root)
2828c75e8394SJosef Bacik 		return -ENOMEM;
2829ae18c37aSJosef Bacik 	btrfs_init_delayed_root(fs_info->delayed_root);
2830ae18c37aSJosef Bacik 
2831a0a1db70SFilipe Manana 	if (sb_rdonly(sb))
2832a0a1db70SFilipe Manana 		set_bit(BTRFS_FS_STATE_RO, &fs_info->fs_state);
2833a0a1db70SFilipe Manana 
2834c75e8394SJosef Bacik 	return btrfs_alloc_stripe_hash_table(fs_info);
2835ae18c37aSJosef Bacik }
2836ae18c37aSJosef Bacik 
283797f4dd09SNikolay Borisov static int btrfs_uuid_rescan_kthread(void *data)
283897f4dd09SNikolay Borisov {
283997f4dd09SNikolay Borisov 	struct btrfs_fs_info *fs_info = (struct btrfs_fs_info *)data;
284097f4dd09SNikolay Borisov 	int ret;
284197f4dd09SNikolay Borisov 
284297f4dd09SNikolay Borisov 	/*
284397f4dd09SNikolay Borisov 	 * 1st step is to iterate through the existing UUID tree and
284497f4dd09SNikolay Borisov 	 * to delete all entries that contain outdated data.
284597f4dd09SNikolay Borisov 	 * 2nd step is to add all missing entries to the UUID tree.
284697f4dd09SNikolay Borisov 	 */
284797f4dd09SNikolay Borisov 	ret = btrfs_uuid_tree_iterate(fs_info);
284897f4dd09SNikolay Borisov 	if (ret < 0) {
2849c94bec2cSJosef Bacik 		if (ret != -EINTR)
2850c94bec2cSJosef Bacik 			btrfs_warn(fs_info, "iterating uuid_tree failed %d",
2851c94bec2cSJosef Bacik 				   ret);
285297f4dd09SNikolay Borisov 		up(&fs_info->uuid_tree_rescan_sem);
285397f4dd09SNikolay Borisov 		return ret;
285497f4dd09SNikolay Borisov 	}
285597f4dd09SNikolay Borisov 	return btrfs_uuid_scan_kthread(data);
285697f4dd09SNikolay Borisov }
285797f4dd09SNikolay Borisov 
285897f4dd09SNikolay Borisov static int btrfs_check_uuid_tree(struct btrfs_fs_info *fs_info)
285997f4dd09SNikolay Borisov {
286097f4dd09SNikolay Borisov 	struct task_struct *task;
286197f4dd09SNikolay Borisov 
286297f4dd09SNikolay Borisov 	down(&fs_info->uuid_tree_rescan_sem);
286397f4dd09SNikolay Borisov 	task = kthread_run(btrfs_uuid_rescan_kthread, fs_info, "btrfs-uuid");
286497f4dd09SNikolay Borisov 	if (IS_ERR(task)) {
286597f4dd09SNikolay Borisov 		/* fs_info->update_uuid_tree_gen remains 0 in all error case */
286697f4dd09SNikolay Borisov 		btrfs_warn(fs_info, "failed to start uuid_rescan task");
286797f4dd09SNikolay Borisov 		up(&fs_info->uuid_tree_rescan_sem);
286897f4dd09SNikolay Borisov 		return PTR_ERR(task);
286997f4dd09SNikolay Borisov 	}
287097f4dd09SNikolay Borisov 
287197f4dd09SNikolay Borisov 	return 0;
287297f4dd09SNikolay Borisov }
287397f4dd09SNikolay Borisov 
287444c0ca21SBoris Burkov /*
28758cd29088SBoris Burkov  * Some options only have meaning at mount time and shouldn't persist across
28768cd29088SBoris Burkov  * remounts, or be displayed. Clear these at the end of mount and remount
28778cd29088SBoris Burkov  * code paths.
28788cd29088SBoris Burkov  */
28798cd29088SBoris Burkov void btrfs_clear_oneshot_options(struct btrfs_fs_info *fs_info)
28808cd29088SBoris Burkov {
28818cd29088SBoris Burkov 	btrfs_clear_opt(fs_info->mount_opt, USEBACKUPROOT);
28828b228324SBoris Burkov 	btrfs_clear_opt(fs_info->mount_opt, CLEAR_CACHE);
28838cd29088SBoris Burkov }
28848cd29088SBoris Burkov 
28858cd29088SBoris Burkov /*
288644c0ca21SBoris Burkov  * Mounting logic specific to read-write file systems. Shared by open_ctree
288744c0ca21SBoris Burkov  * and btrfs_remount when remounting from read-only to read-write.
288844c0ca21SBoris Burkov  */
288944c0ca21SBoris Burkov int btrfs_start_pre_rw_mount(struct btrfs_fs_info *fs_info)
289044c0ca21SBoris Burkov {
289144c0ca21SBoris Burkov 	int ret;
289294846229SBoris Burkov 	const bool cache_opt = btrfs_test_opt(fs_info, SPACE_CACHE);
28938b228324SBoris Burkov 	bool clear_free_space_tree = false;
28948b228324SBoris Burkov 
28958b228324SBoris Burkov 	if (btrfs_test_opt(fs_info, CLEAR_CACHE) &&
28968b228324SBoris Burkov 	    btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
28978b228324SBoris Burkov 		clear_free_space_tree = true;
28988b228324SBoris Burkov 	} else if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE) &&
28998b228324SBoris Burkov 		   !btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE_VALID)) {
29008b228324SBoris Burkov 		btrfs_warn(fs_info, "free space tree is invalid");
29018b228324SBoris Burkov 		clear_free_space_tree = true;
29028b228324SBoris Burkov 	}
29038b228324SBoris Burkov 
29048b228324SBoris Burkov 	if (clear_free_space_tree) {
29058b228324SBoris Burkov 		btrfs_info(fs_info, "clearing free space tree");
29068b228324SBoris Burkov 		ret = btrfs_clear_free_space_tree(fs_info);
29078b228324SBoris Burkov 		if (ret) {
29088b228324SBoris Burkov 			btrfs_warn(fs_info,
29098b228324SBoris Burkov 				   "failed to clear free space tree: %d", ret);
29108b228324SBoris Burkov 			goto out;
29118b228324SBoris Burkov 		}
29128b228324SBoris Burkov 	}
291344c0ca21SBoris Burkov 
291444c0ca21SBoris Burkov 	ret = btrfs_cleanup_fs_roots(fs_info);
291544c0ca21SBoris Burkov 	if (ret)
291644c0ca21SBoris Burkov 		goto out;
291744c0ca21SBoris Burkov 
29188f1c21d7SBoris Burkov 	down_read(&fs_info->cleanup_work_sem);
29198f1c21d7SBoris Burkov 	if ((ret = btrfs_orphan_cleanup(fs_info->fs_root)) ||
29208f1c21d7SBoris Burkov 	    (ret = btrfs_orphan_cleanup(fs_info->tree_root))) {
29218f1c21d7SBoris Burkov 		up_read(&fs_info->cleanup_work_sem);
29228f1c21d7SBoris Burkov 		goto out;
29238f1c21d7SBoris Burkov 	}
29248f1c21d7SBoris Burkov 	up_read(&fs_info->cleanup_work_sem);
29258f1c21d7SBoris Burkov 
292644c0ca21SBoris Burkov 	mutex_lock(&fs_info->cleaner_mutex);
292744c0ca21SBoris Burkov 	ret = btrfs_recover_relocation(fs_info->tree_root);
292844c0ca21SBoris Burkov 	mutex_unlock(&fs_info->cleaner_mutex);
292944c0ca21SBoris Burkov 	if (ret < 0) {
293044c0ca21SBoris Burkov 		btrfs_warn(fs_info, "failed to recover relocation: %d", ret);
293144c0ca21SBoris Burkov 		goto out;
293244c0ca21SBoris Burkov 	}
293344c0ca21SBoris Burkov 
29345011139aSBoris Burkov 	if (btrfs_test_opt(fs_info, FREE_SPACE_TREE) &&
29355011139aSBoris Burkov 	    !btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
29365011139aSBoris Burkov 		btrfs_info(fs_info, "creating free space tree");
29375011139aSBoris Burkov 		ret = btrfs_create_free_space_tree(fs_info);
29385011139aSBoris Burkov 		if (ret) {
29395011139aSBoris Burkov 			btrfs_warn(fs_info,
29405011139aSBoris Burkov 				"failed to create free space tree: %d", ret);
29415011139aSBoris Burkov 			goto out;
29425011139aSBoris Burkov 		}
29435011139aSBoris Burkov 	}
29445011139aSBoris Burkov 
294594846229SBoris Burkov 	if (cache_opt != btrfs_free_space_cache_v1_active(fs_info)) {
294694846229SBoris Burkov 		ret = btrfs_set_free_space_cache_v1_active(fs_info, cache_opt);
294794846229SBoris Burkov 		if (ret)
294894846229SBoris Burkov 			goto out;
294994846229SBoris Burkov 	}
295094846229SBoris Burkov 
295144c0ca21SBoris Burkov 	ret = btrfs_resume_balance_async(fs_info);
295244c0ca21SBoris Burkov 	if (ret)
295344c0ca21SBoris Burkov 		goto out;
295444c0ca21SBoris Burkov 
295544c0ca21SBoris Burkov 	ret = btrfs_resume_dev_replace_async(fs_info);
295644c0ca21SBoris Burkov 	if (ret) {
295744c0ca21SBoris Burkov 		btrfs_warn(fs_info, "failed to resume dev_replace");
295844c0ca21SBoris Burkov 		goto out;
295944c0ca21SBoris Burkov 	}
296044c0ca21SBoris Burkov 
296144c0ca21SBoris Burkov 	btrfs_qgroup_rescan_resume(fs_info);
296244c0ca21SBoris Burkov 
296344c0ca21SBoris Burkov 	if (!fs_info->uuid_root) {
296444c0ca21SBoris Burkov 		btrfs_info(fs_info, "creating UUID tree");
296544c0ca21SBoris Burkov 		ret = btrfs_create_uuid_tree(fs_info);
296644c0ca21SBoris Burkov 		if (ret) {
296744c0ca21SBoris Burkov 			btrfs_warn(fs_info,
296844c0ca21SBoris Burkov 				   "failed to create the UUID tree %d", ret);
296944c0ca21SBoris Burkov 			goto out;
297044c0ca21SBoris Burkov 		}
297144c0ca21SBoris Burkov 	}
297244c0ca21SBoris Burkov 
2973638331faSFilipe Manana 	ret = btrfs_find_orphan_roots(fs_info);
297444c0ca21SBoris Burkov out:
297544c0ca21SBoris Burkov 	return ret;
297644c0ca21SBoris Burkov }
297744c0ca21SBoris Burkov 
2978ae18c37aSJosef Bacik int __cold open_ctree(struct super_block *sb, struct btrfs_fs_devices *fs_devices,
2979ae18c37aSJosef Bacik 		      char *options)
2980ae18c37aSJosef Bacik {
2981ae18c37aSJosef Bacik 	u32 sectorsize;
2982ae18c37aSJosef Bacik 	u32 nodesize;
2983ae18c37aSJosef Bacik 	u32 stripesize;
2984ae18c37aSJosef Bacik 	u64 generation;
2985ae18c37aSJosef Bacik 	u64 features;
2986ae18c37aSJosef Bacik 	u16 csum_type;
2987ae18c37aSJosef Bacik 	struct btrfs_super_block *disk_super;
2988ae18c37aSJosef Bacik 	struct btrfs_fs_info *fs_info = btrfs_sb(sb);
2989ae18c37aSJosef Bacik 	struct btrfs_root *tree_root;
2990ae18c37aSJosef Bacik 	struct btrfs_root *chunk_root;
2991ae18c37aSJosef Bacik 	int ret;
2992ae18c37aSJosef Bacik 	int err = -EINVAL;
2993ae18c37aSJosef Bacik 	int level;
2994ae18c37aSJosef Bacik 
29958260edbaSJosef Bacik 	ret = init_mount_fs_info(fs_info, sb);
299653b381b3SDavid Woodhouse 	if (ret) {
299783c8266aSDavid Sterba 		err = ret;
2998ae18c37aSJosef Bacik 		goto fail;
299953b381b3SDavid Woodhouse 	}
300053b381b3SDavid Woodhouse 
3001ae18c37aSJosef Bacik 	/* These need to be init'ed before we start creating inodes and such. */
3002ae18c37aSJosef Bacik 	tree_root = btrfs_alloc_root(fs_info, BTRFS_ROOT_TREE_OBJECTID,
3003ae18c37aSJosef Bacik 				     GFP_KERNEL);
3004ae18c37aSJosef Bacik 	fs_info->tree_root = tree_root;
3005ae18c37aSJosef Bacik 	chunk_root = btrfs_alloc_root(fs_info, BTRFS_CHUNK_TREE_OBJECTID,
3006ae18c37aSJosef Bacik 				      GFP_KERNEL);
3007ae18c37aSJosef Bacik 	fs_info->chunk_root = chunk_root;
3008ae18c37aSJosef Bacik 	if (!tree_root || !chunk_root) {
3009ae18c37aSJosef Bacik 		err = -ENOMEM;
3010c75e8394SJosef Bacik 		goto fail;
3011ae18c37aSJosef Bacik 	}
3012ae18c37aSJosef Bacik 
3013ae18c37aSJosef Bacik 	fs_info->btree_inode = new_inode(sb);
3014ae18c37aSJosef Bacik 	if (!fs_info->btree_inode) {
3015ae18c37aSJosef Bacik 		err = -ENOMEM;
3016c75e8394SJosef Bacik 		goto fail;
3017ae18c37aSJosef Bacik 	}
3018ae18c37aSJosef Bacik 	mapping_set_gfp_mask(fs_info->btree_inode->i_mapping, GFP_NOFS);
3019ae18c37aSJosef Bacik 	btrfs_init_btree_inode(fs_info);
3020ae18c37aSJosef Bacik 
30213c4bb26bSChris Mason 	invalidate_bdev(fs_devices->latest_bdev);
30221104a885SDavid Sterba 
30231104a885SDavid Sterba 	/*
30241104a885SDavid Sterba 	 * Read super block and check the signature bytes only
30251104a885SDavid Sterba 	 */
30268f32380dSJohannes Thumshirn 	disk_super = btrfs_read_dev_super(fs_devices->latest_bdev);
30278f32380dSJohannes Thumshirn 	if (IS_ERR(disk_super)) {
30288f32380dSJohannes Thumshirn 		err = PTR_ERR(disk_super);
302916cdcec7SMiao Xie 		goto fail_alloc;
303020b45077SDave Young 	}
303139279cc3SChris Mason 
30321104a885SDavid Sterba 	/*
3033260db43cSRandy Dunlap 	 * Verify the type first, if that or the checksum value are
30348dc3f22cSJohannes Thumshirn 	 * corrupted, we'll find out
30358dc3f22cSJohannes Thumshirn 	 */
30368f32380dSJohannes Thumshirn 	csum_type = btrfs_super_csum_type(disk_super);
303751bce6c9SJohannes Thumshirn 	if (!btrfs_supported_super_csum(csum_type)) {
30388dc3f22cSJohannes Thumshirn 		btrfs_err(fs_info, "unsupported checksum algorithm: %u",
303951bce6c9SJohannes Thumshirn 			  csum_type);
30408dc3f22cSJohannes Thumshirn 		err = -EINVAL;
30418f32380dSJohannes Thumshirn 		btrfs_release_disk_super(disk_super);
30428dc3f22cSJohannes Thumshirn 		goto fail_alloc;
30438dc3f22cSJohannes Thumshirn 	}
30448dc3f22cSJohannes Thumshirn 
30456d97c6e3SJohannes Thumshirn 	ret = btrfs_init_csum_hash(fs_info, csum_type);
30466d97c6e3SJohannes Thumshirn 	if (ret) {
30476d97c6e3SJohannes Thumshirn 		err = ret;
30488f32380dSJohannes Thumshirn 		btrfs_release_disk_super(disk_super);
30496d97c6e3SJohannes Thumshirn 		goto fail_alloc;
30506d97c6e3SJohannes Thumshirn 	}
30516d97c6e3SJohannes Thumshirn 
30528dc3f22cSJohannes Thumshirn 	/*
30531104a885SDavid Sterba 	 * We want to check superblock checksum, the type is stored inside.
30541104a885SDavid Sterba 	 * Pass the whole disk block of size BTRFS_SUPER_INFO_SIZE (4k).
30551104a885SDavid Sterba 	 */
30568f32380dSJohannes Thumshirn 	if (btrfs_check_super_csum(fs_info, (u8 *)disk_super)) {
305705135f59SDavid Sterba 		btrfs_err(fs_info, "superblock checksum mismatch");
30581104a885SDavid Sterba 		err = -EINVAL;
30598f32380dSJohannes Thumshirn 		btrfs_release_disk_super(disk_super);
3060141386e1SJosef Bacik 		goto fail_alloc;
30611104a885SDavid Sterba 	}
30621104a885SDavid Sterba 
30631104a885SDavid Sterba 	/*
30641104a885SDavid Sterba 	 * super_copy is zeroed at allocation time and we never touch the
30651104a885SDavid Sterba 	 * following bytes up to INFO_SIZE, the checksum is calculated from
30661104a885SDavid Sterba 	 * the whole block of INFO_SIZE
30671104a885SDavid Sterba 	 */
30688f32380dSJohannes Thumshirn 	memcpy(fs_info->super_copy, disk_super, sizeof(*fs_info->super_copy));
30698f32380dSJohannes Thumshirn 	btrfs_release_disk_super(disk_super);
30705f39d397SChris Mason 
3071fbc6feaeSNikolay Borisov 	disk_super = fs_info->super_copy;
3072fbc6feaeSNikolay Borisov 
3073de37aa51SNikolay Borisov 	ASSERT(!memcmp(fs_info->fs_devices->fsid, fs_info->super_copy->fsid,
3074de37aa51SNikolay Borisov 		       BTRFS_FSID_SIZE));
3075de37aa51SNikolay Borisov 
30767239ff4bSNikolay Borisov 	if (btrfs_fs_incompat(fs_info, METADATA_UUID)) {
3077de37aa51SNikolay Borisov 		ASSERT(!memcmp(fs_info->fs_devices->metadata_uuid,
3078de37aa51SNikolay Borisov 				fs_info->super_copy->metadata_uuid,
3079de37aa51SNikolay Borisov 				BTRFS_FSID_SIZE));
30807239ff4bSNikolay Borisov 	}
30810b86a832SChris Mason 
3082fbc6feaeSNikolay Borisov 	features = btrfs_super_flags(disk_super);
3083fbc6feaeSNikolay Borisov 	if (features & BTRFS_SUPER_FLAG_CHANGING_FSID_V2) {
3084fbc6feaeSNikolay Borisov 		features &= ~BTRFS_SUPER_FLAG_CHANGING_FSID_V2;
3085fbc6feaeSNikolay Borisov 		btrfs_set_super_flags(disk_super, features);
3086fbc6feaeSNikolay Borisov 		btrfs_info(fs_info,
3087fbc6feaeSNikolay Borisov 			"found metadata UUID change in progress flag, clearing");
3088fbc6feaeSNikolay Borisov 	}
3089fbc6feaeSNikolay Borisov 
3090fbc6feaeSNikolay Borisov 	memcpy(fs_info->super_for_commit, fs_info->super_copy,
3091fbc6feaeSNikolay Borisov 	       sizeof(*fs_info->super_for_commit));
3092de37aa51SNikolay Borisov 
3093069ec957SQu Wenruo 	ret = btrfs_validate_mount_super(fs_info);
30941104a885SDavid Sterba 	if (ret) {
309505135f59SDavid Sterba 		btrfs_err(fs_info, "superblock contains fatal errors");
30961104a885SDavid Sterba 		err = -EINVAL;
3097141386e1SJosef Bacik 		goto fail_alloc;
30981104a885SDavid Sterba 	}
30991104a885SDavid Sterba 
31000f7d52f4SChris Mason 	if (!btrfs_super_root(disk_super))
3101141386e1SJosef Bacik 		goto fail_alloc;
31020f7d52f4SChris Mason 
3103acce952bSliubo 	/* check FS state, whether FS is broken. */
310487533c47SMiao Xie 	if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_ERROR)
310587533c47SMiao Xie 		set_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state);
3106acce952bSliubo 
310775e7cb7fSLiu Bo 	/*
310875e7cb7fSLiu Bo 	 * In the long term, we'll store the compression type in the super
310975e7cb7fSLiu Bo 	 * block, and it'll be used for per file compression control.
311075e7cb7fSLiu Bo 	 */
311175e7cb7fSLiu Bo 	fs_info->compress_type = BTRFS_COMPRESS_ZLIB;
311275e7cb7fSLiu Bo 
31132ff7e61eSJeff Mahoney 	ret = btrfs_parse_options(fs_info, options, sb->s_flags);
31142b82032cSYan Zheng 	if (ret) {
31152b82032cSYan Zheng 		err = ret;
3116141386e1SJosef Bacik 		goto fail_alloc;
31172b82032cSYan Zheng 	}
3118dfe25020SChris Mason 
3119f2b636e8SJosef Bacik 	features = btrfs_super_incompat_flags(disk_super) &
3120f2b636e8SJosef Bacik 		~BTRFS_FEATURE_INCOMPAT_SUPP;
3121f2b636e8SJosef Bacik 	if (features) {
312205135f59SDavid Sterba 		btrfs_err(fs_info,
312305135f59SDavid Sterba 		    "cannot mount because of unsupported optional features (%llx)",
3124c1c9ff7cSGeert Uytterhoeven 		    features);
3125f2b636e8SJosef Bacik 		err = -EINVAL;
3126141386e1SJosef Bacik 		goto fail_alloc;
3127f2b636e8SJosef Bacik 	}
3128f2b636e8SJosef Bacik 
31295d4f98a2SYan Zheng 	features = btrfs_super_incompat_flags(disk_super);
31305d4f98a2SYan Zheng 	features |= BTRFS_FEATURE_INCOMPAT_MIXED_BACKREF;
31310b246afaSJeff Mahoney 	if (fs_info->compress_type == BTRFS_COMPRESS_LZO)
3132a6fa6faeSLi Zefan 		features |= BTRFS_FEATURE_INCOMPAT_COMPRESS_LZO;
31335c1aab1dSNick Terrell 	else if (fs_info->compress_type == BTRFS_COMPRESS_ZSTD)
31345c1aab1dSNick Terrell 		features |= BTRFS_FEATURE_INCOMPAT_COMPRESS_ZSTD;
3135727011e0SChris Mason 
31363173a18fSJosef Bacik 	if (features & BTRFS_FEATURE_INCOMPAT_SKINNY_METADATA)
313705135f59SDavid Sterba 		btrfs_info(fs_info, "has skinny extents");
31383173a18fSJosef Bacik 
3139b70f5097SNaohiro Aota 	fs_info->zoned = (features & BTRFS_FEATURE_INCOMPAT_ZONED);
3140b70f5097SNaohiro Aota 
3141727011e0SChris Mason 	/*
3142727011e0SChris Mason 	 * flag our filesystem as having big metadata blocks if
3143727011e0SChris Mason 	 * they are bigger than the page size
3144727011e0SChris Mason 	 */
314509cbfeafSKirill A. Shutemov 	if (btrfs_super_nodesize(disk_super) > PAGE_SIZE) {
3146727011e0SChris Mason 		if (!(features & BTRFS_FEATURE_INCOMPAT_BIG_METADATA))
314705135f59SDavid Sterba 			btrfs_info(fs_info,
314805135f59SDavid Sterba 				"flagging fs with big metadata feature");
3149727011e0SChris Mason 		features |= BTRFS_FEATURE_INCOMPAT_BIG_METADATA;
3150727011e0SChris Mason 	}
3151727011e0SChris Mason 
3152bc3f116fSChris Mason 	nodesize = btrfs_super_nodesize(disk_super);
3153bc3f116fSChris Mason 	sectorsize = btrfs_super_sectorsize(disk_super);
3154b7f67055SChandan Rajendra 	stripesize = sectorsize;
3155707e8a07SDavid Sterba 	fs_info->dirty_metadata_batch = nodesize * (1 + ilog2(nr_cpu_ids));
3156963d678bSMiao Xie 	fs_info->delalloc_batch = sectorsize * 512 * (1 + ilog2(nr_cpu_ids));
3157bc3f116fSChris Mason 
3158da17066cSJeff Mahoney 	/* Cache block sizes */
3159da17066cSJeff Mahoney 	fs_info->nodesize = nodesize;
3160da17066cSJeff Mahoney 	fs_info->sectorsize = sectorsize;
3161ab108d99SDavid Sterba 	fs_info->sectorsize_bits = ilog2(sectorsize);
316222b6331dSDavid Sterba 	fs_info->csum_size = btrfs_super_csum_size(disk_super);
3163fe5ecbe8SDavid Sterba 	fs_info->csums_per_leaf = BTRFS_MAX_ITEM_SIZE(fs_info) / fs_info->csum_size;
3164da17066cSJeff Mahoney 	fs_info->stripesize = stripesize;
3165da17066cSJeff Mahoney 
3166bc3f116fSChris Mason 	/*
3167bc3f116fSChris Mason 	 * mixed block groups end up with duplicate but slightly offset
3168bc3f116fSChris Mason 	 * extent buffers for the same range.  It leads to corruptions
3169bc3f116fSChris Mason 	 */
3170bc3f116fSChris Mason 	if ((features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS) &&
3171707e8a07SDavid Sterba 	    (sectorsize != nodesize)) {
317205135f59SDavid Sterba 		btrfs_err(fs_info,
317305135f59SDavid Sterba "unequal nodesize/sectorsize (%u != %u) are not allowed for mixed block groups",
317405135f59SDavid Sterba 			nodesize, sectorsize);
3175141386e1SJosef Bacik 		goto fail_alloc;
3176bc3f116fSChris Mason 	}
3177bc3f116fSChris Mason 
3178ceda0864SMiao Xie 	/*
3179ceda0864SMiao Xie 	 * Needn't use the lock because there is no other task which will
3180ceda0864SMiao Xie 	 * update the flag.
3181ceda0864SMiao Xie 	 */
31825d4f98a2SYan Zheng 	btrfs_set_super_incompat_flags(disk_super, features);
31835d4f98a2SYan Zheng 
3184f2b636e8SJosef Bacik 	features = btrfs_super_compat_ro_flags(disk_super) &
3185f2b636e8SJosef Bacik 		~BTRFS_FEATURE_COMPAT_RO_SUPP;
3186bc98a42cSDavid Howells 	if (!sb_rdonly(sb) && features) {
318705135f59SDavid Sterba 		btrfs_err(fs_info,
318805135f59SDavid Sterba 	"cannot mount read-write because of unsupported optional features (%llx)",
3189c1c9ff7cSGeert Uytterhoeven 		       features);
3190f2b636e8SJosef Bacik 		err = -EINVAL;
3191141386e1SJosef Bacik 		goto fail_alloc;
3192f2b636e8SJosef Bacik 	}
319361d92c32SChris Mason 
31942a458198SEric Sandeen 	ret = btrfs_init_workqueues(fs_info, fs_devices);
31952a458198SEric Sandeen 	if (ret) {
31962a458198SEric Sandeen 		err = ret;
31970dc3b84aSJosef Bacik 		goto fail_sb_buffer;
31980dc3b84aSJosef Bacik 	}
31994543df7eSChris Mason 
32009e11ceeeSJan Kara 	sb->s_bdi->ra_pages *= btrfs_super_num_devices(disk_super);
32019e11ceeeSJan Kara 	sb->s_bdi->ra_pages = max(sb->s_bdi->ra_pages, SZ_4M / PAGE_SIZE);
32024575c9ccSChris Mason 
3203a061fc8dSChris Mason 	sb->s_blocksize = sectorsize;
3204a061fc8dSChris Mason 	sb->s_blocksize_bits = blksize_bits(sectorsize);
3205de37aa51SNikolay Borisov 	memcpy(&sb->s_uuid, fs_info->fs_devices->fsid, BTRFS_FSID_SIZE);
3206db94535dSChris Mason 
3207925baeddSChris Mason 	mutex_lock(&fs_info->chunk_mutex);
32086bccf3abSJeff Mahoney 	ret = btrfs_read_sys_array(fs_info);
3209925baeddSChris Mason 	mutex_unlock(&fs_info->chunk_mutex);
321084eed90fSChris Mason 	if (ret) {
321105135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read the system array: %d", ret);
32125d4f98a2SYan Zheng 		goto fail_sb_buffer;
321384eed90fSChris Mason 	}
32140b86a832SChris Mason 
321584234f3aSYan Zheng 	generation = btrfs_super_chunk_root_generation(disk_super);
3216581c1760SQu Wenruo 	level = btrfs_super_chunk_root_level(disk_super);
32170b86a832SChris Mason 
32182ff7e61eSJeff Mahoney 	chunk_root->node = read_tree_block(fs_info,
32190b86a832SChris Mason 					   btrfs_super_chunk_root(disk_super),
32201b7ec85eSJosef Bacik 					   BTRFS_CHUNK_TREE_OBJECTID,
3221581c1760SQu Wenruo 					   generation, level, NULL);
322264c043deSLiu Bo 	if (IS_ERR(chunk_root->node) ||
322364c043deSLiu Bo 	    !extent_buffer_uptodate(chunk_root->node)) {
322405135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read chunk root");
3225e5fffbacSchandan 		if (!IS_ERR(chunk_root->node))
3226e5fffbacSchandan 			free_extent_buffer(chunk_root->node);
322795ab1f64SZhao Lei 		chunk_root->node = NULL;
3228af31f5e5SChris Mason 		goto fail_tree_roots;
322983121942SDavid Woodhouse 	}
32305d4f98a2SYan Zheng 	btrfs_set_root_node(&chunk_root->root_item, chunk_root->node);
32315d4f98a2SYan Zheng 	chunk_root->commit_root = btrfs_root_node(chunk_root);
32320b86a832SChris Mason 
3233e17cade2SChris Mason 	read_extent_buffer(chunk_root->node, fs_info->chunk_tree_uuid,
3234c4ac7541SDavid Sterba 			   offsetof(struct btrfs_header, chunk_tree_uuid),
3235c4ac7541SDavid Sterba 			   BTRFS_UUID_SIZE);
3236e17cade2SChris Mason 
32375b4aacefSJeff Mahoney 	ret = btrfs_read_chunk_tree(fs_info);
32382b82032cSYan Zheng 	if (ret) {
323905135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read chunk tree: %d", ret);
3240af31f5e5SChris Mason 		goto fail_tree_roots;
32412b82032cSYan Zheng 	}
32420b86a832SChris Mason 
32438dabb742SStefan Behrens 	/*
3244bacce86aSAnand Jain 	 * At this point we know all the devices that make this filesystem,
3245bacce86aSAnand Jain 	 * including the seed devices but we don't know yet if the replace
3246bacce86aSAnand Jain 	 * target is required. So free devices that are not part of this
3247bacce86aSAnand Jain 	 * filesystem but skip the replace traget device which is checked
3248bacce86aSAnand Jain 	 * below in btrfs_init_dev_replace().
32498dabb742SStefan Behrens 	 */
3250bacce86aSAnand Jain 	btrfs_free_extra_devids(fs_devices);
3251a6b0d5c8SChris Mason 	if (!fs_devices->latest_bdev) {
325205135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read devices");
3253a6b0d5c8SChris Mason 		goto fail_tree_roots;
3254a6b0d5c8SChris Mason 	}
3255a6b0d5c8SChris Mason 
3256b8522a1eSNikolay Borisov 	ret = init_tree_roots(fs_info);
32574bbcaa64SEric Sandeen 	if (ret)
3258b8522a1eSNikolay Borisov 		goto fail_tree_roots;
32598929ecfaSYan, Zheng 
326075ec1db8SJosef Bacik 	/*
326175ec1db8SJosef Bacik 	 * If we have a uuid root and we're not being told to rescan we need to
326275ec1db8SJosef Bacik 	 * check the generation here so we can set the
326375ec1db8SJosef Bacik 	 * BTRFS_FS_UPDATE_UUID_TREE_GEN bit.  Otherwise we could commit the
326475ec1db8SJosef Bacik 	 * transaction during a balance or the log replay without updating the
326575ec1db8SJosef Bacik 	 * uuid generation, and then if we crash we would rescan the uuid tree,
326675ec1db8SJosef Bacik 	 * even though it was perfectly fine.
326775ec1db8SJosef Bacik 	 */
326875ec1db8SJosef Bacik 	if (fs_info->uuid_root && !btrfs_test_opt(fs_info, RESCAN_UUID_TREE) &&
326975ec1db8SJosef Bacik 	    fs_info->generation == btrfs_super_uuid_tree_generation(disk_super))
327075ec1db8SJosef Bacik 		set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
327175ec1db8SJosef Bacik 
3272cf90d884SQu Wenruo 	ret = btrfs_verify_dev_extents(fs_info);
3273cf90d884SQu Wenruo 	if (ret) {
3274cf90d884SQu Wenruo 		btrfs_err(fs_info,
3275cf90d884SQu Wenruo 			  "failed to verify dev extents against chunks: %d",
3276cf90d884SQu Wenruo 			  ret);
3277cf90d884SQu Wenruo 		goto fail_block_groups;
3278cf90d884SQu Wenruo 	}
327968310a5eSIlya Dryomov 	ret = btrfs_recover_balance(fs_info);
328068310a5eSIlya Dryomov 	if (ret) {
328105135f59SDavid Sterba 		btrfs_err(fs_info, "failed to recover balance: %d", ret);
328268310a5eSIlya Dryomov 		goto fail_block_groups;
328368310a5eSIlya Dryomov 	}
328468310a5eSIlya Dryomov 
3285733f4fbbSStefan Behrens 	ret = btrfs_init_dev_stats(fs_info);
3286733f4fbbSStefan Behrens 	if (ret) {
328705135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init dev_stats: %d", ret);
3288733f4fbbSStefan Behrens 		goto fail_block_groups;
3289733f4fbbSStefan Behrens 	}
3290733f4fbbSStefan Behrens 
32918dabb742SStefan Behrens 	ret = btrfs_init_dev_replace(fs_info);
32928dabb742SStefan Behrens 	if (ret) {
329305135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init dev_replace: %d", ret);
32948dabb742SStefan Behrens 		goto fail_block_groups;
32958dabb742SStefan Behrens 	}
32968dabb742SStefan Behrens 
3297b70f5097SNaohiro Aota 	ret = btrfs_check_zoned_mode(fs_info);
3298b70f5097SNaohiro Aota 	if (ret) {
3299b70f5097SNaohiro Aota 		btrfs_err(fs_info, "failed to initialize zoned mode: %d",
3300b70f5097SNaohiro Aota 			  ret);
3301b70f5097SNaohiro Aota 		goto fail_block_groups;
3302b70f5097SNaohiro Aota 	}
3303b70f5097SNaohiro Aota 
3304c6761a9eSAnand Jain 	ret = btrfs_sysfs_add_fsid(fs_devices);
3305b7c35e81SAnand Jain 	if (ret) {
330605135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init sysfs fsid interface: %d",
330705135f59SDavid Sterba 				ret);
3308b7c35e81SAnand Jain 		goto fail_block_groups;
3309b7c35e81SAnand Jain 	}
3310b7c35e81SAnand Jain 
331196f3136eSAnand Jain 	ret = btrfs_sysfs_add_mounted(fs_info);
33125ac1d209SJeff Mahoney 	if (ret) {
331305135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init sysfs interface: %d", ret);
3314b7c35e81SAnand Jain 		goto fail_fsdev_sysfs;
33155ac1d209SJeff Mahoney 	}
33165ac1d209SJeff Mahoney 
3317c59021f8Sliubo 	ret = btrfs_init_space_info(fs_info);
3318c59021f8Sliubo 	if (ret) {
331905135f59SDavid Sterba 		btrfs_err(fs_info, "failed to initialize space info: %d", ret);
33202365dd3cSAnand Jain 		goto fail_sysfs;
3321c59021f8Sliubo 	}
3322c59021f8Sliubo 
33235b4aacefSJeff Mahoney 	ret = btrfs_read_block_groups(fs_info);
33241b1d1f66SJosef Bacik 	if (ret) {
332505135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read block groups: %d", ret);
33262365dd3cSAnand Jain 		goto fail_sysfs;
33271b1d1f66SJosef Bacik 	}
33284330e183SQu Wenruo 
33296528b99dSAnand Jain 	if (!sb_rdonly(sb) && !btrfs_check_rw_degradable(fs_info, NULL)) {
333005135f59SDavid Sterba 		btrfs_warn(fs_info,
333152042d8eSAndrea Gelmini 		"writable mount is not allowed due to too many missing devices");
33322365dd3cSAnand Jain 		goto fail_sysfs;
3333292fd7fcSStefan Behrens 	}
33349078a3e1SChris Mason 
3335a74a4b97SChris Mason 	fs_info->cleaner_kthread = kthread_run(cleaner_kthread, tree_root,
3336a74a4b97SChris Mason 					       "btrfs-cleaner");
333757506d50SQinghuang Feng 	if (IS_ERR(fs_info->cleaner_kthread))
33382365dd3cSAnand Jain 		goto fail_sysfs;
3339a74a4b97SChris Mason 
3340a74a4b97SChris Mason 	fs_info->transaction_kthread = kthread_run(transaction_kthread,
3341a74a4b97SChris Mason 						   tree_root,
3342a74a4b97SChris Mason 						   "btrfs-transaction");
334357506d50SQinghuang Feng 	if (IS_ERR(fs_info->transaction_kthread))
33443f157a2fSChris Mason 		goto fail_cleaner;
3345a74a4b97SChris Mason 
3346583b7231SHans van Kranenburg 	if (!btrfs_test_opt(fs_info, NOSSD) &&
3347c289811cSChris Mason 	    !fs_info->fs_devices->rotating) {
3348583b7231SHans van Kranenburg 		btrfs_set_and_info(fs_info, SSD, "enabling ssd optimizations");
3349c289811cSChris Mason 	}
3350c289811cSChris Mason 
3351572d9ab7SDavid Sterba 	/*
335201327610SNicholas D Steeves 	 * Mount does not set all options immediately, we can do it now and do
3353572d9ab7SDavid Sterba 	 * not have to wait for transaction commit
3354572d9ab7SDavid Sterba 	 */
3355572d9ab7SDavid Sterba 	btrfs_apply_pending_changes(fs_info);
33563818aea2SQu Wenruo 
335721adbd5cSStefan Behrens #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
33580b246afaSJeff Mahoney 	if (btrfs_test_opt(fs_info, CHECK_INTEGRITY)) {
33592ff7e61eSJeff Mahoney 		ret = btrfsic_mount(fs_info, fs_devices,
33600b246afaSJeff Mahoney 				    btrfs_test_opt(fs_info,
336121adbd5cSStefan Behrens 					CHECK_INTEGRITY_INCLUDING_EXTENT_DATA) ?
336221adbd5cSStefan Behrens 				    1 : 0,
336321adbd5cSStefan Behrens 				    fs_info->check_integrity_print_mask);
336421adbd5cSStefan Behrens 		if (ret)
336505135f59SDavid Sterba 			btrfs_warn(fs_info,
336605135f59SDavid Sterba 				"failed to initialize integrity check module: %d",
336705135f59SDavid Sterba 				ret);
336821adbd5cSStefan Behrens 	}
336921adbd5cSStefan Behrens #endif
3370bcef60f2SArne Jansen 	ret = btrfs_read_qgroup_config(fs_info);
3371bcef60f2SArne Jansen 	if (ret)
3372bcef60f2SArne Jansen 		goto fail_trans_kthread;
337321adbd5cSStefan Behrens 
3374fd708b81SJosef Bacik 	if (btrfs_build_ref_tree(fs_info))
3375fd708b81SJosef Bacik 		btrfs_err(fs_info, "couldn't build ref tree");
3376fd708b81SJosef Bacik 
337796da0919SQu Wenruo 	/* do not make disk changes in broken FS or nologreplay is given */
337896da0919SQu Wenruo 	if (btrfs_super_log_root(disk_super) != 0 &&
33790b246afaSJeff Mahoney 	    !btrfs_test_opt(fs_info, NOLOGREPLAY)) {
3380e8294f2fSDavid Sterba 		btrfs_info(fs_info, "start tree-log replay");
338163443bf5SEric Sandeen 		ret = btrfs_replay_log(fs_info, fs_devices);
338279787eaaSJeff Mahoney 		if (ret) {
338363443bf5SEric Sandeen 			err = ret;
338428c16cbbSWang Shilong 			goto fail_qgroup;
3385e556ce2cSYan Zheng 		}
3386e02119d5SChris Mason 	}
33871a40e23bSZheng Yan 
338856e9357aSDavid Sterba 	fs_info->fs_root = btrfs_get_fs_root(fs_info, BTRFS_FS_TREE_OBJECTID, true);
33893140c9a3SDan Carpenter 	if (IS_ERR(fs_info->fs_root)) {
33903140c9a3SDan Carpenter 		err = PTR_ERR(fs_info->fs_root);
3391f50f4353SLiu Bo 		btrfs_warn(fs_info, "failed to read fs tree: %d", err);
3392315bf8efSJosef Bacik 		fs_info->fs_root = NULL;
3393bcef60f2SArne Jansen 		goto fail_qgroup;
33943140c9a3SDan Carpenter 	}
3395c289811cSChris Mason 
3396bc98a42cSDavid Howells 	if (sb_rdonly(sb))
33978cd29088SBoris Burkov 		goto clear_oneshot;
33982b6ba629SIlya Dryomov 
339944c0ca21SBoris Burkov 	ret = btrfs_start_pre_rw_mount(fs_info);
34002b6ba629SIlya Dryomov 	if (ret) {
34016bccf3abSJeff Mahoney 		close_ctree(fs_info);
34022b6ba629SIlya Dryomov 		return ret;
3403e3acc2a6SJosef Bacik 	}
3404b0643e59SDennis Zhou 	btrfs_discard_resume(fs_info);
3405b382a324SJan Schmidt 
340644c0ca21SBoris Burkov 	if (fs_info->uuid_root &&
340744c0ca21SBoris Burkov 	    (btrfs_test_opt(fs_info, RESCAN_UUID_TREE) ||
340844c0ca21SBoris Burkov 	     fs_info->generation != btrfs_super_uuid_tree_generation(disk_super))) {
340905135f59SDavid Sterba 		btrfs_info(fs_info, "checking UUID tree");
341070f80175SStefan Behrens 		ret = btrfs_check_uuid_tree(fs_info);
341170f80175SStefan Behrens 		if (ret) {
341205135f59SDavid Sterba 			btrfs_warn(fs_info,
341305135f59SDavid Sterba 				"failed to check the UUID tree: %d", ret);
34146bccf3abSJeff Mahoney 			close_ctree(fs_info);
341570f80175SStefan Behrens 			return ret;
341670f80175SStefan Behrens 		}
3417f7a81ea4SStefan Behrens 	}
341894846229SBoris Burkov 
3419afcdd129SJosef Bacik 	set_bit(BTRFS_FS_OPEN, &fs_info->flags);
342047ab2a6cSJosef Bacik 
34218cd29088SBoris Burkov clear_oneshot:
34228cd29088SBoris Burkov 	btrfs_clear_oneshot_options(fs_info);
3423ad2b2c80SAl Viro 	return 0;
342439279cc3SChris Mason 
3425bcef60f2SArne Jansen fail_qgroup:
3426bcef60f2SArne Jansen 	btrfs_free_qgroup_config(fs_info);
34277c2ca468SChris Mason fail_trans_kthread:
34287c2ca468SChris Mason 	kthread_stop(fs_info->transaction_kthread);
34292ff7e61eSJeff Mahoney 	btrfs_cleanup_transaction(fs_info);
3430faa2dbf0SJosef Bacik 	btrfs_free_fs_roots(fs_info);
34313f157a2fSChris Mason fail_cleaner:
3432a74a4b97SChris Mason 	kthread_stop(fs_info->cleaner_kthread);
34337c2ca468SChris Mason 
34347c2ca468SChris Mason 	/*
34357c2ca468SChris Mason 	 * make sure we're done with the btree inode before we stop our
34367c2ca468SChris Mason 	 * kthreads
34377c2ca468SChris Mason 	 */
34387c2ca468SChris Mason 	filemap_write_and_wait(fs_info->btree_inode->i_mapping);
34397c2ca468SChris Mason 
34402365dd3cSAnand Jain fail_sysfs:
34416618a59bSAnand Jain 	btrfs_sysfs_remove_mounted(fs_info);
34422365dd3cSAnand Jain 
3443b7c35e81SAnand Jain fail_fsdev_sysfs:
3444b7c35e81SAnand Jain 	btrfs_sysfs_remove_fsid(fs_info->fs_devices);
3445b7c35e81SAnand Jain 
34461b1d1f66SJosef Bacik fail_block_groups:
344754067ae9SJosef Bacik 	btrfs_put_block_group_cache(fs_info);
3448af31f5e5SChris Mason 
3449af31f5e5SChris Mason fail_tree_roots:
34509e3aa805SJosef Bacik 	if (fs_info->data_reloc_root)
34519e3aa805SJosef Bacik 		btrfs_drop_and_free_fs_root(fs_info, fs_info->data_reloc_root);
34524273eaffSAnand Jain 	free_root_pointers(fs_info, true);
34532b8195bbSMiao Xie 	invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
3454af31f5e5SChris Mason 
345539279cc3SChris Mason fail_sb_buffer:
34567abadb64SLiu Bo 	btrfs_stop_all_workers(fs_info);
34575cdd7db6SFilipe Manana 	btrfs_free_block_groups(fs_info);
345816cdcec7SMiao Xie fail_alloc:
3459586e46e2SIlya Dryomov 	btrfs_mapping_tree_free(&fs_info->mapping_tree);
3460586e46e2SIlya Dryomov 
34614543df7eSChris Mason 	iput(fs_info->btree_inode);
34627e662854SQinghuang Feng fail:
3463586e46e2SIlya Dryomov 	btrfs_close_devices(fs_info->fs_devices);
3464ad2b2c80SAl Viro 	return err;
3465eb60ceacSChris Mason }
3466663faf9fSMasami Hiramatsu ALLOW_ERROR_INJECTION(open_ctree, ERRNO);
3467eb60ceacSChris Mason 
3468314b6dd0SJohannes Thumshirn static void btrfs_end_super_write(struct bio *bio)
3469f2984462SChris Mason {
3470314b6dd0SJohannes Thumshirn 	struct btrfs_device *device = bio->bi_private;
3471314b6dd0SJohannes Thumshirn 	struct bio_vec *bvec;
3472314b6dd0SJohannes Thumshirn 	struct bvec_iter_all iter_all;
3473314b6dd0SJohannes Thumshirn 	struct page *page;
3474442a4f63SStefan Behrens 
3475314b6dd0SJohannes Thumshirn 	bio_for_each_segment_all(bvec, bio, iter_all) {
3476314b6dd0SJohannes Thumshirn 		page = bvec->bv_page;
3477314b6dd0SJohannes Thumshirn 
3478314b6dd0SJohannes Thumshirn 		if (bio->bi_status) {
3479fb456252SJeff Mahoney 			btrfs_warn_rl_in_rcu(device->fs_info,
3480314b6dd0SJohannes Thumshirn 				"lost page write due to IO error on %s (%d)",
3481314b6dd0SJohannes Thumshirn 				rcu_str_deref(device->name),
3482314b6dd0SJohannes Thumshirn 				blk_status_to_errno(bio->bi_status));
3483314b6dd0SJohannes Thumshirn 			ClearPageUptodate(page);
3484314b6dd0SJohannes Thumshirn 			SetPageError(page);
3485314b6dd0SJohannes Thumshirn 			btrfs_dev_stat_inc_and_print(device,
3486314b6dd0SJohannes Thumshirn 						     BTRFS_DEV_STAT_WRITE_ERRS);
3487314b6dd0SJohannes Thumshirn 		} else {
3488314b6dd0SJohannes Thumshirn 			SetPageUptodate(page);
3489f2984462SChris Mason 		}
3490314b6dd0SJohannes Thumshirn 
3491314b6dd0SJohannes Thumshirn 		put_page(page);
3492314b6dd0SJohannes Thumshirn 		unlock_page(page);
3493314b6dd0SJohannes Thumshirn 	}
3494314b6dd0SJohannes Thumshirn 
3495314b6dd0SJohannes Thumshirn 	bio_put(bio);
3496f2984462SChris Mason }
3497f2984462SChris Mason 
34988f32380dSJohannes Thumshirn struct btrfs_super_block *btrfs_read_dev_one_super(struct block_device *bdev,
34998f32380dSJohannes Thumshirn 						   int copy_num)
350029c36d72SAnand Jain {
350129c36d72SAnand Jain 	struct btrfs_super_block *super;
35028f32380dSJohannes Thumshirn 	struct page *page;
350312659251SNaohiro Aota 	u64 bytenr, bytenr_orig;
35048f32380dSJohannes Thumshirn 	struct address_space *mapping = bdev->bd_inode->i_mapping;
350512659251SNaohiro Aota 	int ret;
350629c36d72SAnand Jain 
350712659251SNaohiro Aota 	bytenr_orig = btrfs_sb_offset(copy_num);
350812659251SNaohiro Aota 	ret = btrfs_sb_log_location_bdev(bdev, copy_num, READ, &bytenr);
350912659251SNaohiro Aota 	if (ret == -ENOENT)
351012659251SNaohiro Aota 		return ERR_PTR(-EINVAL);
351112659251SNaohiro Aota 	else if (ret)
351212659251SNaohiro Aota 		return ERR_PTR(ret);
351312659251SNaohiro Aota 
351429c36d72SAnand Jain 	if (bytenr + BTRFS_SUPER_INFO_SIZE >= i_size_read(bdev->bd_inode))
35158f32380dSJohannes Thumshirn 		return ERR_PTR(-EINVAL);
351629c36d72SAnand Jain 
35178f32380dSJohannes Thumshirn 	page = read_cache_page_gfp(mapping, bytenr >> PAGE_SHIFT, GFP_NOFS);
35188f32380dSJohannes Thumshirn 	if (IS_ERR(page))
35198f32380dSJohannes Thumshirn 		return ERR_CAST(page);
352029c36d72SAnand Jain 
35218f32380dSJohannes Thumshirn 	super = page_address(page);
352296c2e067SAnand Jain 	if (btrfs_super_magic(super) != BTRFS_MAGIC) {
352396c2e067SAnand Jain 		btrfs_release_disk_super(super);
352496c2e067SAnand Jain 		return ERR_PTR(-ENODATA);
352596c2e067SAnand Jain 	}
352696c2e067SAnand Jain 
352712659251SNaohiro Aota 	if (btrfs_super_bytenr(super) != bytenr_orig) {
35288f32380dSJohannes Thumshirn 		btrfs_release_disk_super(super);
35298f32380dSJohannes Thumshirn 		return ERR_PTR(-EINVAL);
353029c36d72SAnand Jain 	}
353129c36d72SAnand Jain 
35328f32380dSJohannes Thumshirn 	return super;
353329c36d72SAnand Jain }
353429c36d72SAnand Jain 
353529c36d72SAnand Jain 
35368f32380dSJohannes Thumshirn struct btrfs_super_block *btrfs_read_dev_super(struct block_device *bdev)
3537a512bbf8SYan Zheng {
35388f32380dSJohannes Thumshirn 	struct btrfs_super_block *super, *latest = NULL;
3539a512bbf8SYan Zheng 	int i;
3540a512bbf8SYan Zheng 	u64 transid = 0;
3541a512bbf8SYan Zheng 
3542a512bbf8SYan Zheng 	/* we would like to check all the supers, but that would make
3543a512bbf8SYan Zheng 	 * a btrfs mount succeed after a mkfs from a different FS.
3544a512bbf8SYan Zheng 	 * So, we need to add a special mount option to scan for
3545a512bbf8SYan Zheng 	 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
3546a512bbf8SYan Zheng 	 */
3547a512bbf8SYan Zheng 	for (i = 0; i < 1; i++) {
35488f32380dSJohannes Thumshirn 		super = btrfs_read_dev_one_super(bdev, i);
35498f32380dSJohannes Thumshirn 		if (IS_ERR(super))
3550a512bbf8SYan Zheng 			continue;
3551a512bbf8SYan Zheng 
3552a512bbf8SYan Zheng 		if (!latest || btrfs_super_generation(super) > transid) {
35538f32380dSJohannes Thumshirn 			if (latest)
35548f32380dSJohannes Thumshirn 				btrfs_release_disk_super(super);
35558f32380dSJohannes Thumshirn 
35568f32380dSJohannes Thumshirn 			latest = super;
3557a512bbf8SYan Zheng 			transid = btrfs_super_generation(super);
3558a512bbf8SYan Zheng 		}
3559a512bbf8SYan Zheng 	}
356092fc03fbSAnand Jain 
35618f32380dSJohannes Thumshirn 	return super;
3562a512bbf8SYan Zheng }
3563a512bbf8SYan Zheng 
35644eedeb75SHisashi Hifumi /*
3565abbb3b8eSDavid Sterba  * Write superblock @sb to the @device. Do not wait for completion, all the
3566314b6dd0SJohannes Thumshirn  * pages we use for writing are locked.
35674eedeb75SHisashi Hifumi  *
3568abbb3b8eSDavid Sterba  * Write @max_mirrors copies of the superblock, where 0 means default that fit
3569abbb3b8eSDavid Sterba  * the expected device size at commit time. Note that max_mirrors must be
3570abbb3b8eSDavid Sterba  * same for write and wait phases.
35714eedeb75SHisashi Hifumi  *
3572314b6dd0SJohannes Thumshirn  * Return number of errors when page is not found or submission fails.
35734eedeb75SHisashi Hifumi  */
3574a512bbf8SYan Zheng static int write_dev_supers(struct btrfs_device *device,
3575abbb3b8eSDavid Sterba 			    struct btrfs_super_block *sb, int max_mirrors)
3576a512bbf8SYan Zheng {
3577d5178578SJohannes Thumshirn 	struct btrfs_fs_info *fs_info = device->fs_info;
3578314b6dd0SJohannes Thumshirn 	struct address_space *mapping = device->bdev->bd_inode->i_mapping;
3579d5178578SJohannes Thumshirn 	SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
3580a512bbf8SYan Zheng 	int i;
3581a512bbf8SYan Zheng 	int errors = 0;
358212659251SNaohiro Aota 	int ret;
358312659251SNaohiro Aota 	u64 bytenr, bytenr_orig;
3584a512bbf8SYan Zheng 
3585a512bbf8SYan Zheng 	if (max_mirrors == 0)
3586a512bbf8SYan Zheng 		max_mirrors = BTRFS_SUPER_MIRROR_MAX;
3587a512bbf8SYan Zheng 
3588d5178578SJohannes Thumshirn 	shash->tfm = fs_info->csum_shash;
3589d5178578SJohannes Thumshirn 
3590a512bbf8SYan Zheng 	for (i = 0; i < max_mirrors; i++) {
3591314b6dd0SJohannes Thumshirn 		struct page *page;
3592314b6dd0SJohannes Thumshirn 		struct bio *bio;
3593314b6dd0SJohannes Thumshirn 		struct btrfs_super_block *disk_super;
3594314b6dd0SJohannes Thumshirn 
359512659251SNaohiro Aota 		bytenr_orig = btrfs_sb_offset(i);
359612659251SNaohiro Aota 		ret = btrfs_sb_log_location(device, i, WRITE, &bytenr);
359712659251SNaohiro Aota 		if (ret == -ENOENT) {
359812659251SNaohiro Aota 			continue;
359912659251SNaohiro Aota 		} else if (ret < 0) {
360012659251SNaohiro Aota 			btrfs_err(device->fs_info,
360112659251SNaohiro Aota 				"couldn't get super block location for mirror %d",
360212659251SNaohiro Aota 				i);
360312659251SNaohiro Aota 			errors++;
360412659251SNaohiro Aota 			continue;
360512659251SNaohiro Aota 		}
3606935e5cc9SMiao Xie 		if (bytenr + BTRFS_SUPER_INFO_SIZE >=
3607935e5cc9SMiao Xie 		    device->commit_total_bytes)
3608a512bbf8SYan Zheng 			break;
3609a512bbf8SYan Zheng 
361012659251SNaohiro Aota 		btrfs_set_super_bytenr(sb, bytenr_orig);
3611a512bbf8SYan Zheng 
3612fd08001fSEric Biggers 		crypto_shash_digest(shash, (const char *)sb + BTRFS_CSUM_SIZE,
3613fd08001fSEric Biggers 				    BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE,
3614fd08001fSEric Biggers 				    sb->csum);
3615a512bbf8SYan Zheng 
3616314b6dd0SJohannes Thumshirn 		page = find_or_create_page(mapping, bytenr >> PAGE_SHIFT,
3617314b6dd0SJohannes Thumshirn 					   GFP_NOFS);
3618314b6dd0SJohannes Thumshirn 		if (!page) {
3619fb456252SJeff Mahoney 			btrfs_err(device->fs_info,
3620314b6dd0SJohannes Thumshirn 			    "couldn't get super block page for bytenr %llu",
3621f14d104dSDavid Sterba 			    bytenr);
3622634554dcSJosef Bacik 			errors++;
3623634554dcSJosef Bacik 			continue;
3624634554dcSJosef Bacik 		}
3625634554dcSJosef Bacik 
3626314b6dd0SJohannes Thumshirn 		/* Bump the refcount for wait_dev_supers() */
3627314b6dd0SJohannes Thumshirn 		get_page(page);
3628a512bbf8SYan Zheng 
3629314b6dd0SJohannes Thumshirn 		disk_super = page_address(page);
3630314b6dd0SJohannes Thumshirn 		memcpy(disk_super, sb, BTRFS_SUPER_INFO_SIZE);
3631a512bbf8SYan Zheng 
3632387125fcSChris Mason 		/*
3633314b6dd0SJohannes Thumshirn 		 * Directly use bios here instead of relying on the page cache
3634314b6dd0SJohannes Thumshirn 		 * to do I/O, so we don't lose the ability to do integrity
3635314b6dd0SJohannes Thumshirn 		 * checking.
3636387125fcSChris Mason 		 */
3637314b6dd0SJohannes Thumshirn 		bio = bio_alloc(GFP_NOFS, 1);
3638314b6dd0SJohannes Thumshirn 		bio_set_dev(bio, device->bdev);
3639314b6dd0SJohannes Thumshirn 		bio->bi_iter.bi_sector = bytenr >> SECTOR_SHIFT;
3640314b6dd0SJohannes Thumshirn 		bio->bi_private = device;
3641314b6dd0SJohannes Thumshirn 		bio->bi_end_io = btrfs_end_super_write;
3642314b6dd0SJohannes Thumshirn 		__bio_add_page(bio, page, BTRFS_SUPER_INFO_SIZE,
3643314b6dd0SJohannes Thumshirn 			       offset_in_page(bytenr));
3644314b6dd0SJohannes Thumshirn 
3645314b6dd0SJohannes Thumshirn 		/*
3646314b6dd0SJohannes Thumshirn 		 * We FUA only the first super block.  The others we allow to
3647314b6dd0SJohannes Thumshirn 		 * go down lazy and there's a short window where the on-disk
3648314b6dd0SJohannes Thumshirn 		 * copies might still contain the older version.
3649314b6dd0SJohannes Thumshirn 		 */
3650314b6dd0SJohannes Thumshirn 		bio->bi_opf = REQ_OP_WRITE | REQ_SYNC | REQ_META | REQ_PRIO;
36511b9e619cSOmar Sandoval 		if (i == 0 && !btrfs_test_opt(device->fs_info, NOBARRIER))
3652314b6dd0SJohannes Thumshirn 			bio->bi_opf |= REQ_FUA;
3653314b6dd0SJohannes Thumshirn 
3654314b6dd0SJohannes Thumshirn 		btrfsic_submit_bio(bio);
365512659251SNaohiro Aota 		btrfs_advance_sb_log(device, i);
3656a512bbf8SYan Zheng 	}
3657a512bbf8SYan Zheng 	return errors < i ? 0 : -1;
3658a512bbf8SYan Zheng }
3659a512bbf8SYan Zheng 
3660387125fcSChris Mason /*
3661abbb3b8eSDavid Sterba  * Wait for write completion of superblocks done by write_dev_supers,
3662abbb3b8eSDavid Sterba  * @max_mirrors same for write and wait phases.
3663abbb3b8eSDavid Sterba  *
3664314b6dd0SJohannes Thumshirn  * Return number of errors when page is not found or not marked up to
3665abbb3b8eSDavid Sterba  * date.
3666abbb3b8eSDavid Sterba  */
3667abbb3b8eSDavid Sterba static int wait_dev_supers(struct btrfs_device *device, int max_mirrors)
3668abbb3b8eSDavid Sterba {
3669abbb3b8eSDavid Sterba 	int i;
3670abbb3b8eSDavid Sterba 	int errors = 0;
3671b6a535faSHoward McLauchlan 	bool primary_failed = false;
367212659251SNaohiro Aota 	int ret;
3673abbb3b8eSDavid Sterba 	u64 bytenr;
3674abbb3b8eSDavid Sterba 
3675abbb3b8eSDavid Sterba 	if (max_mirrors == 0)
3676abbb3b8eSDavid Sterba 		max_mirrors = BTRFS_SUPER_MIRROR_MAX;
3677abbb3b8eSDavid Sterba 
3678abbb3b8eSDavid Sterba 	for (i = 0; i < max_mirrors; i++) {
3679314b6dd0SJohannes Thumshirn 		struct page *page;
3680314b6dd0SJohannes Thumshirn 
368112659251SNaohiro Aota 		ret = btrfs_sb_log_location(device, i, READ, &bytenr);
368212659251SNaohiro Aota 		if (ret == -ENOENT) {
368312659251SNaohiro Aota 			break;
368412659251SNaohiro Aota 		} else if (ret < 0) {
368512659251SNaohiro Aota 			errors++;
368612659251SNaohiro Aota 			if (i == 0)
368712659251SNaohiro Aota 				primary_failed = true;
368812659251SNaohiro Aota 			continue;
368912659251SNaohiro Aota 		}
3690abbb3b8eSDavid Sterba 		if (bytenr + BTRFS_SUPER_INFO_SIZE >=
3691abbb3b8eSDavid Sterba 		    device->commit_total_bytes)
3692abbb3b8eSDavid Sterba 			break;
3693abbb3b8eSDavid Sterba 
3694314b6dd0SJohannes Thumshirn 		page = find_get_page(device->bdev->bd_inode->i_mapping,
3695314b6dd0SJohannes Thumshirn 				     bytenr >> PAGE_SHIFT);
3696314b6dd0SJohannes Thumshirn 		if (!page) {
3697abbb3b8eSDavid Sterba 			errors++;
3698b6a535faSHoward McLauchlan 			if (i == 0)
3699b6a535faSHoward McLauchlan 				primary_failed = true;
3700abbb3b8eSDavid Sterba 			continue;
3701abbb3b8eSDavid Sterba 		}
3702314b6dd0SJohannes Thumshirn 		/* Page is submitted locked and unlocked once the IO completes */
3703314b6dd0SJohannes Thumshirn 		wait_on_page_locked(page);
3704314b6dd0SJohannes Thumshirn 		if (PageError(page)) {
3705abbb3b8eSDavid Sterba 			errors++;
3706b6a535faSHoward McLauchlan 			if (i == 0)
3707b6a535faSHoward McLauchlan 				primary_failed = true;
3708b6a535faSHoward McLauchlan 		}
3709abbb3b8eSDavid Sterba 
3710314b6dd0SJohannes Thumshirn 		/* Drop our reference */
3711314b6dd0SJohannes Thumshirn 		put_page(page);
3712abbb3b8eSDavid Sterba 
3713314b6dd0SJohannes Thumshirn 		/* Drop the reference from the writing run */
3714314b6dd0SJohannes Thumshirn 		put_page(page);
3715abbb3b8eSDavid Sterba 	}
3716abbb3b8eSDavid Sterba 
3717b6a535faSHoward McLauchlan 	/* log error, force error return */
3718b6a535faSHoward McLauchlan 	if (primary_failed) {
3719b6a535faSHoward McLauchlan 		btrfs_err(device->fs_info, "error writing primary super block to device %llu",
3720b6a535faSHoward McLauchlan 			  device->devid);
3721b6a535faSHoward McLauchlan 		return -1;
3722b6a535faSHoward McLauchlan 	}
3723b6a535faSHoward McLauchlan 
3724abbb3b8eSDavid Sterba 	return errors < i ? 0 : -1;
3725abbb3b8eSDavid Sterba }
3726abbb3b8eSDavid Sterba 
3727abbb3b8eSDavid Sterba /*
3728387125fcSChris Mason  * endio for the write_dev_flush, this will wake anyone waiting
3729387125fcSChris Mason  * for the barrier when it is done
3730387125fcSChris Mason  */
37314246a0b6SChristoph Hellwig static void btrfs_end_empty_barrier(struct bio *bio)
3732387125fcSChris Mason {
3733387125fcSChris Mason 	complete(bio->bi_private);
3734387125fcSChris Mason }
3735387125fcSChris Mason 
3736387125fcSChris Mason /*
37374fc6441aSAnand Jain  * Submit a flush request to the device if it supports it. Error handling is
37384fc6441aSAnand Jain  * done in the waiting counterpart.
3739387125fcSChris Mason  */
37404fc6441aSAnand Jain static void write_dev_flush(struct btrfs_device *device)
3741387125fcSChris Mason {
3742c2a9c7abSAnand Jain 	struct request_queue *q = bdev_get_queue(device->bdev);
3743e0ae9994SDavid Sterba 	struct bio *bio = device->flush_bio;
3744387125fcSChris Mason 
3745c2a9c7abSAnand Jain 	if (!test_bit(QUEUE_FLAG_WC, &q->queue_flags))
37464fc6441aSAnand Jain 		return;
3747387125fcSChris Mason 
3748e0ae9994SDavid Sterba 	bio_reset(bio);
3749387125fcSChris Mason 	bio->bi_end_io = btrfs_end_empty_barrier;
375074d46992SChristoph Hellwig 	bio_set_dev(bio, device->bdev);
37518d910125SJan Kara 	bio->bi_opf = REQ_OP_WRITE | REQ_SYNC | REQ_PREFLUSH;
3752387125fcSChris Mason 	init_completion(&device->flush_wait);
3753387125fcSChris Mason 	bio->bi_private = &device->flush_wait;
3754387125fcSChris Mason 
375543a01111SLu Fengqi 	btrfsic_submit_bio(bio);
37561c3063b6SAnand Jain 	set_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state);
37574fc6441aSAnand Jain }
3758387125fcSChris Mason 
37594fc6441aSAnand Jain /*
37604fc6441aSAnand Jain  * If the flush bio has been submitted by write_dev_flush, wait for it.
37614fc6441aSAnand Jain  */
37628c27cb35SLinus Torvalds static blk_status_t wait_dev_flush(struct btrfs_device *device)
37634fc6441aSAnand Jain {
37644fc6441aSAnand Jain 	struct bio *bio = device->flush_bio;
37654fc6441aSAnand Jain 
37661c3063b6SAnand Jain 	if (!test_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state))
376758efbc9fSOmar Sandoval 		return BLK_STS_OK;
37684fc6441aSAnand Jain 
37691c3063b6SAnand Jain 	clear_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state);
37702980d574SDavid Sterba 	wait_for_completion_io(&device->flush_wait);
37714fc6441aSAnand Jain 
37728c27cb35SLinus Torvalds 	return bio->bi_status;
3773387125fcSChris Mason }
3774387125fcSChris Mason 
3775d10b82feSQu Wenruo static int check_barrier_error(struct btrfs_fs_info *fs_info)
3776401b41e5SAnand Jain {
37776528b99dSAnand Jain 	if (!btrfs_check_rw_degradable(fs_info, NULL))
3778401b41e5SAnand Jain 		return -EIO;
3779387125fcSChris Mason 	return 0;
3780387125fcSChris Mason }
3781387125fcSChris Mason 
3782387125fcSChris Mason /*
3783387125fcSChris Mason  * send an empty flush down to each device in parallel,
3784387125fcSChris Mason  * then wait for them
3785387125fcSChris Mason  */
3786387125fcSChris Mason static int barrier_all_devices(struct btrfs_fs_info *info)
3787387125fcSChris Mason {
3788387125fcSChris Mason 	struct list_head *head;
3789387125fcSChris Mason 	struct btrfs_device *dev;
37905af3e8ccSStefan Behrens 	int errors_wait = 0;
37914e4cbee9SChristoph Hellwig 	blk_status_t ret;
3792387125fcSChris Mason 
37931538e6c5SDavid Sterba 	lockdep_assert_held(&info->fs_devices->device_list_mutex);
3794387125fcSChris Mason 	/* send down all the barriers */
3795387125fcSChris Mason 	head = &info->fs_devices->devices;
37961538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
3797e6e674bdSAnand Jain 		if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
3798f88ba6a2SHidetoshi Seto 			continue;
3799cea7c8bfSAnand Jain 		if (!dev->bdev)
3800387125fcSChris Mason 			continue;
3801e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
3802ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
3803387125fcSChris Mason 			continue;
3804387125fcSChris Mason 
38054fc6441aSAnand Jain 		write_dev_flush(dev);
380658efbc9fSOmar Sandoval 		dev->last_flush_error = BLK_STS_OK;
3807387125fcSChris Mason 	}
3808387125fcSChris Mason 
3809387125fcSChris Mason 	/* wait for all the barriers */
38101538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
3811e6e674bdSAnand Jain 		if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
3812f88ba6a2SHidetoshi Seto 			continue;
3813387125fcSChris Mason 		if (!dev->bdev) {
38145af3e8ccSStefan Behrens 			errors_wait++;
3815387125fcSChris Mason 			continue;
3816387125fcSChris Mason 		}
3817e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
3818ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
3819387125fcSChris Mason 			continue;
3820387125fcSChris Mason 
38214fc6441aSAnand Jain 		ret = wait_dev_flush(dev);
3822401b41e5SAnand Jain 		if (ret) {
3823401b41e5SAnand Jain 			dev->last_flush_error = ret;
382466b4993eSDavid Sterba 			btrfs_dev_stat_inc_and_print(dev,
382566b4993eSDavid Sterba 					BTRFS_DEV_STAT_FLUSH_ERRS);
38265af3e8ccSStefan Behrens 			errors_wait++;
3827387125fcSChris Mason 		}
3828401b41e5SAnand Jain 	}
3829401b41e5SAnand Jain 
3830cea7c8bfSAnand Jain 	if (errors_wait) {
3831401b41e5SAnand Jain 		/*
3832401b41e5SAnand Jain 		 * At some point we need the status of all disks
3833401b41e5SAnand Jain 		 * to arrive at the volume status. So error checking
3834401b41e5SAnand Jain 		 * is being pushed to a separate loop.
3835401b41e5SAnand Jain 		 */
3836d10b82feSQu Wenruo 		return check_barrier_error(info);
3837401b41e5SAnand Jain 	}
3838387125fcSChris Mason 	return 0;
3839387125fcSChris Mason }
3840387125fcSChris Mason 
3841943c6e99SZhao Lei int btrfs_get_num_tolerated_disk_barrier_failures(u64 flags)
3842943c6e99SZhao Lei {
38438789f4feSZhao Lei 	int raid_type;
38448789f4feSZhao Lei 	int min_tolerated = INT_MAX;
3845943c6e99SZhao Lei 
38468789f4feSZhao Lei 	if ((flags & BTRFS_BLOCK_GROUP_PROFILE_MASK) == 0 ||
38478789f4feSZhao Lei 	    (flags & BTRFS_AVAIL_ALLOC_BIT_SINGLE))
38488c3e3582SDavid Sterba 		min_tolerated = min_t(int, min_tolerated,
38498789f4feSZhao Lei 				    btrfs_raid_array[BTRFS_RAID_SINGLE].
38508789f4feSZhao Lei 				    tolerated_failures);
3851943c6e99SZhao Lei 
38528789f4feSZhao Lei 	for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) {
38538789f4feSZhao Lei 		if (raid_type == BTRFS_RAID_SINGLE)
38548789f4feSZhao Lei 			continue;
385541a6e891SAnand Jain 		if (!(flags & btrfs_raid_array[raid_type].bg_flag))
38568789f4feSZhao Lei 			continue;
38578c3e3582SDavid Sterba 		min_tolerated = min_t(int, min_tolerated,
38588789f4feSZhao Lei 				    btrfs_raid_array[raid_type].
38598789f4feSZhao Lei 				    tolerated_failures);
38608789f4feSZhao Lei 	}
3861943c6e99SZhao Lei 
38628789f4feSZhao Lei 	if (min_tolerated == INT_MAX) {
3863ab8d0fc4SJeff Mahoney 		pr_warn("BTRFS: unknown raid flag: %llu", flags);
38648789f4feSZhao Lei 		min_tolerated = 0;
38658789f4feSZhao Lei 	}
38668789f4feSZhao Lei 
38678789f4feSZhao Lei 	return min_tolerated;
3868943c6e99SZhao Lei }
3869943c6e99SZhao Lei 
3870eece6a9cSDavid Sterba int write_all_supers(struct btrfs_fs_info *fs_info, int max_mirrors)
3871f2984462SChris Mason {
3872e5e9a520SChris Mason 	struct list_head *head;
3873f2984462SChris Mason 	struct btrfs_device *dev;
3874a061fc8dSChris Mason 	struct btrfs_super_block *sb;
3875f2984462SChris Mason 	struct btrfs_dev_item *dev_item;
3876f2984462SChris Mason 	int ret;
3877f2984462SChris Mason 	int do_barriers;
3878a236aed1SChris Mason 	int max_errors;
3879a236aed1SChris Mason 	int total_errors = 0;
3880a061fc8dSChris Mason 	u64 flags;
3881f2984462SChris Mason 
38820b246afaSJeff Mahoney 	do_barriers = !btrfs_test_opt(fs_info, NOBARRIER);
3883fed3b381SLiu Bo 
3884fed3b381SLiu Bo 	/*
3885fed3b381SLiu Bo 	 * max_mirrors == 0 indicates we're from commit_transaction,
3886fed3b381SLiu Bo 	 * not from fsync where the tree roots in fs_info have not
3887fed3b381SLiu Bo 	 * been consistent on disk.
3888fed3b381SLiu Bo 	 */
3889fed3b381SLiu Bo 	if (max_mirrors == 0)
38900b246afaSJeff Mahoney 		backup_super_roots(fs_info);
3891f2984462SChris Mason 
38920b246afaSJeff Mahoney 	sb = fs_info->super_for_commit;
3893a061fc8dSChris Mason 	dev_item = &sb->dev_item;
3894e5e9a520SChris Mason 
38950b246afaSJeff Mahoney 	mutex_lock(&fs_info->fs_devices->device_list_mutex);
38960b246afaSJeff Mahoney 	head = &fs_info->fs_devices->devices;
38970b246afaSJeff Mahoney 	max_errors = btrfs_super_num_devices(fs_info->super_copy) - 1;
3898387125fcSChris Mason 
38995af3e8ccSStefan Behrens 	if (do_barriers) {
39000b246afaSJeff Mahoney 		ret = barrier_all_devices(fs_info);
39015af3e8ccSStefan Behrens 		if (ret) {
39025af3e8ccSStefan Behrens 			mutex_unlock(
39030b246afaSJeff Mahoney 				&fs_info->fs_devices->device_list_mutex);
39040b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret,
39055af3e8ccSStefan Behrens 					      "errors while submitting device barriers.");
39065af3e8ccSStefan Behrens 			return ret;
39075af3e8ccSStefan Behrens 		}
39085af3e8ccSStefan Behrens 	}
3909387125fcSChris Mason 
39101538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
3911dfe25020SChris Mason 		if (!dev->bdev) {
3912dfe25020SChris Mason 			total_errors++;
3913dfe25020SChris Mason 			continue;
3914dfe25020SChris Mason 		}
3915e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
3916ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
3917dfe25020SChris Mason 			continue;
3918dfe25020SChris Mason 
39192b82032cSYan Zheng 		btrfs_set_stack_device_generation(dev_item, 0);
3920a061fc8dSChris Mason 		btrfs_set_stack_device_type(dev_item, dev->type);
3921a061fc8dSChris Mason 		btrfs_set_stack_device_id(dev_item, dev->devid);
39227df69d3eSMiao Xie 		btrfs_set_stack_device_total_bytes(dev_item,
3923935e5cc9SMiao Xie 						   dev->commit_total_bytes);
3924ce7213c7SMiao Xie 		btrfs_set_stack_device_bytes_used(dev_item,
3925ce7213c7SMiao Xie 						  dev->commit_bytes_used);
3926a061fc8dSChris Mason 		btrfs_set_stack_device_io_align(dev_item, dev->io_align);
3927a061fc8dSChris Mason 		btrfs_set_stack_device_io_width(dev_item, dev->io_width);
3928a061fc8dSChris Mason 		btrfs_set_stack_device_sector_size(dev_item, dev->sector_size);
3929a061fc8dSChris Mason 		memcpy(dev_item->uuid, dev->uuid, BTRFS_UUID_SIZE);
39307239ff4bSNikolay Borisov 		memcpy(dev_item->fsid, dev->fs_devices->metadata_uuid,
39317239ff4bSNikolay Borisov 		       BTRFS_FSID_SIZE);
3932a512bbf8SYan Zheng 
3933a061fc8dSChris Mason 		flags = btrfs_super_flags(sb);
3934a061fc8dSChris Mason 		btrfs_set_super_flags(sb, flags | BTRFS_HEADER_FLAG_WRITTEN);
3935f2984462SChris Mason 
393675cb857dSQu Wenruo 		ret = btrfs_validate_write_super(fs_info, sb);
393775cb857dSQu Wenruo 		if (ret < 0) {
393875cb857dSQu Wenruo 			mutex_unlock(&fs_info->fs_devices->device_list_mutex);
393975cb857dSQu Wenruo 			btrfs_handle_fs_error(fs_info, -EUCLEAN,
394075cb857dSQu Wenruo 				"unexpected superblock corruption detected");
394175cb857dSQu Wenruo 			return -EUCLEAN;
394275cb857dSQu Wenruo 		}
394375cb857dSQu Wenruo 
3944abbb3b8eSDavid Sterba 		ret = write_dev_supers(dev, sb, max_mirrors);
3945a236aed1SChris Mason 		if (ret)
3946a236aed1SChris Mason 			total_errors++;
3947f2984462SChris Mason 	}
3948a236aed1SChris Mason 	if (total_errors > max_errors) {
39490b246afaSJeff Mahoney 		btrfs_err(fs_info, "%d errors while writing supers",
3950d397712bSChris Mason 			  total_errors);
39510b246afaSJeff Mahoney 		mutex_unlock(&fs_info->fs_devices->device_list_mutex);
395279787eaaSJeff Mahoney 
39539d565ba4SStefan Behrens 		/* FUA is masked off if unsupported and can't be the reason */
39540b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, -EIO,
39550b246afaSJeff Mahoney 				      "%d errors while writing supers",
39560b246afaSJeff Mahoney 				      total_errors);
39579d565ba4SStefan Behrens 		return -EIO;
3958a236aed1SChris Mason 	}
3959f2984462SChris Mason 
3960a512bbf8SYan Zheng 	total_errors = 0;
39611538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
3962dfe25020SChris Mason 		if (!dev->bdev)
3963dfe25020SChris Mason 			continue;
3964e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
3965ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
3966dfe25020SChris Mason 			continue;
3967dfe25020SChris Mason 
3968abbb3b8eSDavid Sterba 		ret = wait_dev_supers(dev, max_mirrors);
3969a512bbf8SYan Zheng 		if (ret)
39701259ab75SChris Mason 			total_errors++;
3971f2984462SChris Mason 	}
39720b246afaSJeff Mahoney 	mutex_unlock(&fs_info->fs_devices->device_list_mutex);
3973a236aed1SChris Mason 	if (total_errors > max_errors) {
39740b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, -EIO,
39750b246afaSJeff Mahoney 				      "%d errors while writing supers",
39760b246afaSJeff Mahoney 				      total_errors);
397779787eaaSJeff Mahoney 		return -EIO;
3978a236aed1SChris Mason 	}
3979f2984462SChris Mason 	return 0;
3980f2984462SChris Mason }
3981f2984462SChris Mason 
3982cb517eabSMiao Xie /* Drop a fs root from the radix tree and free it. */
3983cb517eabSMiao Xie void btrfs_drop_and_free_fs_root(struct btrfs_fs_info *fs_info,
3984cb517eabSMiao Xie 				  struct btrfs_root *root)
39852619ba1fSChris Mason {
39864785e24fSJosef Bacik 	bool drop_ref = false;
39874785e24fSJosef Bacik 
39884df27c4dSYan, Zheng 	spin_lock(&fs_info->fs_roots_radix_lock);
39892619ba1fSChris Mason 	radix_tree_delete(&fs_info->fs_roots_radix,
39902619ba1fSChris Mason 			  (unsigned long)root->root_key.objectid);
3991af01d2e5SJosef Bacik 	if (test_and_clear_bit(BTRFS_ROOT_IN_RADIX, &root->state))
39924785e24fSJosef Bacik 		drop_ref = true;
39934df27c4dSYan, Zheng 	spin_unlock(&fs_info->fs_roots_radix_lock);
399476dda93cSYan, Zheng 
39951c1ea4f7SLiu Bo 	if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {
3996ef67963dSJosef Bacik 		ASSERT(root->log_root == NULL);
39971c1ea4f7SLiu Bo 		if (root->reloc_root) {
399800246528SJosef Bacik 			btrfs_put_root(root->reloc_root);
39991c1ea4f7SLiu Bo 			root->reloc_root = NULL;
40001c1ea4f7SLiu Bo 		}
40011c1ea4f7SLiu Bo 	}
40023321719eSLiu Bo 
40034785e24fSJosef Bacik 	if (drop_ref)
400400246528SJosef Bacik 		btrfs_put_root(root);
40052619ba1fSChris Mason }
40062619ba1fSChris Mason 
4007c146afadSYan Zheng int btrfs_cleanup_fs_roots(struct btrfs_fs_info *fs_info)
4008c146afadSYan Zheng {
4009c146afadSYan Zheng 	u64 root_objectid = 0;
4010c146afadSYan Zheng 	struct btrfs_root *gang[8];
401165d33fd7SQu Wenruo 	int i = 0;
401265d33fd7SQu Wenruo 	int err = 0;
401365d33fd7SQu Wenruo 	unsigned int ret = 0;
4014c146afadSYan Zheng 
4015c146afadSYan Zheng 	while (1) {
4016efc34534SJosef Bacik 		spin_lock(&fs_info->fs_roots_radix_lock);
4017c146afadSYan Zheng 		ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
4018c146afadSYan Zheng 					     (void **)gang, root_objectid,
4019c146afadSYan Zheng 					     ARRAY_SIZE(gang));
402065d33fd7SQu Wenruo 		if (!ret) {
4021efc34534SJosef Bacik 			spin_unlock(&fs_info->fs_roots_radix_lock);
4022c146afadSYan Zheng 			break;
402365d33fd7SQu Wenruo 		}
40245d4f98a2SYan Zheng 		root_objectid = gang[ret - 1]->root_key.objectid + 1;
402566b4ffd1SJosef Bacik 
402665d33fd7SQu Wenruo 		for (i = 0; i < ret; i++) {
402765d33fd7SQu Wenruo 			/* Avoid to grab roots in dead_roots */
402865d33fd7SQu Wenruo 			if (btrfs_root_refs(&gang[i]->root_item) == 0) {
402965d33fd7SQu Wenruo 				gang[i] = NULL;
403065d33fd7SQu Wenruo 				continue;
403165d33fd7SQu Wenruo 			}
403265d33fd7SQu Wenruo 			/* grab all the search result for later use */
403300246528SJosef Bacik 			gang[i] = btrfs_grab_root(gang[i]);
403465d33fd7SQu Wenruo 		}
4035efc34534SJosef Bacik 		spin_unlock(&fs_info->fs_roots_radix_lock);
403665d33fd7SQu Wenruo 
403765d33fd7SQu Wenruo 		for (i = 0; i < ret; i++) {
403865d33fd7SQu Wenruo 			if (!gang[i])
403965d33fd7SQu Wenruo 				continue;
4040c146afadSYan Zheng 			root_objectid = gang[i]->root_key.objectid;
404166b4ffd1SJosef Bacik 			err = btrfs_orphan_cleanup(gang[i]);
404266b4ffd1SJosef Bacik 			if (err)
404365d33fd7SQu Wenruo 				break;
404400246528SJosef Bacik 			btrfs_put_root(gang[i]);
4045c146afadSYan Zheng 		}
4046c146afadSYan Zheng 		root_objectid++;
4047c146afadSYan Zheng 	}
404865d33fd7SQu Wenruo 
404965d33fd7SQu Wenruo 	/* release the uncleaned roots due to error */
405065d33fd7SQu Wenruo 	for (; i < ret; i++) {
405165d33fd7SQu Wenruo 		if (gang[i])
405200246528SJosef Bacik 			btrfs_put_root(gang[i]);
405365d33fd7SQu Wenruo 	}
405465d33fd7SQu Wenruo 	return err;
4055c146afadSYan Zheng }
4056c146afadSYan Zheng 
40576bccf3abSJeff Mahoney int btrfs_commit_super(struct btrfs_fs_info *fs_info)
4058c146afadSYan Zheng {
40596bccf3abSJeff Mahoney 	struct btrfs_root *root = fs_info->tree_root;
4060c146afadSYan Zheng 	struct btrfs_trans_handle *trans;
4061c146afadSYan Zheng 
40620b246afaSJeff Mahoney 	mutex_lock(&fs_info->cleaner_mutex);
40632ff7e61eSJeff Mahoney 	btrfs_run_delayed_iputs(fs_info);
40640b246afaSJeff Mahoney 	mutex_unlock(&fs_info->cleaner_mutex);
40650b246afaSJeff Mahoney 	wake_up_process(fs_info->cleaner_kthread);
4066c71bf099SYan, Zheng 
4067c71bf099SYan, Zheng 	/* wait until ongoing cleanup work done */
40680b246afaSJeff Mahoney 	down_write(&fs_info->cleanup_work_sem);
40690b246afaSJeff Mahoney 	up_write(&fs_info->cleanup_work_sem);
4070c71bf099SYan, Zheng 
40717a7eaa40SJosef Bacik 	trans = btrfs_join_transaction(root);
40723612b495STsutomu Itoh 	if (IS_ERR(trans))
40733612b495STsutomu Itoh 		return PTR_ERR(trans);
40743a45bb20SJeff Mahoney 	return btrfs_commit_transaction(trans);
4075c146afadSYan Zheng }
4076c146afadSYan Zheng 
4077b105e927SDavid Sterba void __cold close_ctree(struct btrfs_fs_info *fs_info)
4078eb60ceacSChris Mason {
4079c146afadSYan Zheng 	int ret;
4080e089f05cSChris Mason 
4081afcdd129SJosef Bacik 	set_bit(BTRFS_FS_CLOSING_START, &fs_info->flags);
4082d6fd0ae2SOmar Sandoval 	/*
4083d6fd0ae2SOmar Sandoval 	 * We don't want the cleaner to start new transactions, add more delayed
4084d6fd0ae2SOmar Sandoval 	 * iputs, etc. while we're closing. We can't use kthread_stop() yet
4085d6fd0ae2SOmar Sandoval 	 * because that frees the task_struct, and the transaction kthread might
4086d6fd0ae2SOmar Sandoval 	 * still try to wake up the cleaner.
4087d6fd0ae2SOmar Sandoval 	 */
4088d6fd0ae2SOmar Sandoval 	kthread_park(fs_info->cleaner_kthread);
4089a2135011SChris Mason 
40907343dd61SJustin Maggard 	/* wait for the qgroup rescan worker to stop */
4091d06f23d6SJeff Mahoney 	btrfs_qgroup_wait_for_completion(fs_info, false);
40927343dd61SJustin Maggard 
4093803b2f54SStefan Behrens 	/* wait for the uuid_scan task to finish */
4094803b2f54SStefan Behrens 	down(&fs_info->uuid_tree_rescan_sem);
4095803b2f54SStefan Behrens 	/* avoid complains from lockdep et al., set sem back to initial state */
4096803b2f54SStefan Behrens 	up(&fs_info->uuid_tree_rescan_sem);
4097803b2f54SStefan Behrens 
4098837d5b6eSIlya Dryomov 	/* pause restriper - we want to resume on mount */
4099aa1b8cd4SStefan Behrens 	btrfs_pause_balance(fs_info);
4100837d5b6eSIlya Dryomov 
41018dabb742SStefan Behrens 	btrfs_dev_replace_suspend_for_unmount(fs_info);
41028dabb742SStefan Behrens 
4103aa1b8cd4SStefan Behrens 	btrfs_scrub_cancel(fs_info);
41044cb5300bSChris Mason 
41054cb5300bSChris Mason 	/* wait for any defraggers to finish */
41064cb5300bSChris Mason 	wait_event(fs_info->transaction_wait,
41074cb5300bSChris Mason 		   (atomic_read(&fs_info->defrag_running) == 0));
41084cb5300bSChris Mason 
41094cb5300bSChris Mason 	/* clear out the rbtree of defraggable inodes */
411026176e7cSMiao Xie 	btrfs_cleanup_defrag_inodes(fs_info);
41114cb5300bSChris Mason 
411221c7e756SMiao Xie 	cancel_work_sync(&fs_info->async_reclaim_work);
411357056740SJosef Bacik 	cancel_work_sync(&fs_info->async_data_reclaim_work);
4114*576fa348SJosef Bacik 	cancel_work_sync(&fs_info->preempt_reclaim_work);
411521c7e756SMiao Xie 
4116b0643e59SDennis Zhou 	/* Cancel or finish ongoing discard work */
4117b0643e59SDennis Zhou 	btrfs_discard_cleanup(fs_info);
4118b0643e59SDennis Zhou 
4119bc98a42cSDavid Howells 	if (!sb_rdonly(fs_info->sb)) {
4120e44163e1SJeff Mahoney 		/*
4121d6fd0ae2SOmar Sandoval 		 * The cleaner kthread is stopped, so do one final pass over
4122d6fd0ae2SOmar Sandoval 		 * unused block groups.
4123e44163e1SJeff Mahoney 		 */
41240b246afaSJeff Mahoney 		btrfs_delete_unused_bgs(fs_info);
4125e44163e1SJeff Mahoney 
4126f0cc2cd7SFilipe Manana 		/*
4127f0cc2cd7SFilipe Manana 		 * There might be existing delayed inode workers still running
4128f0cc2cd7SFilipe Manana 		 * and holding an empty delayed inode item. We must wait for
4129f0cc2cd7SFilipe Manana 		 * them to complete first because they can create a transaction.
4130f0cc2cd7SFilipe Manana 		 * This happens when someone calls btrfs_balance_delayed_items()
4131f0cc2cd7SFilipe Manana 		 * and then a transaction commit runs the same delayed nodes
4132f0cc2cd7SFilipe Manana 		 * before any delayed worker has done something with the nodes.
4133f0cc2cd7SFilipe Manana 		 * We must wait for any worker here and not at transaction
4134f0cc2cd7SFilipe Manana 		 * commit time since that could cause a deadlock.
4135f0cc2cd7SFilipe Manana 		 * This is a very rare case.
4136f0cc2cd7SFilipe Manana 		 */
4137f0cc2cd7SFilipe Manana 		btrfs_flush_workqueue(fs_info->delayed_workers);
4138f0cc2cd7SFilipe Manana 
41396bccf3abSJeff Mahoney 		ret = btrfs_commit_super(fs_info);
4140d397712bSChris Mason 		if (ret)
414104892340SEric Sandeen 			btrfs_err(fs_info, "commit super ret %d", ret);
4142c146afadSYan Zheng 	}
4143ed2ff2cbSChris Mason 
4144af722733SLiu Bo 	if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state) ||
4145af722733SLiu Bo 	    test_bit(BTRFS_FS_STATE_TRANS_ABORTED, &fs_info->fs_state))
41462ff7e61eSJeff Mahoney 		btrfs_error_commit_super(fs_info);
4147acce952bSliubo 
4148e3029d9fSAl Viro 	kthread_stop(fs_info->transaction_kthread);
4149e3029d9fSAl Viro 	kthread_stop(fs_info->cleaner_kthread);
41508929ecfaSYan, Zheng 
4151e187831eSJosef Bacik 	ASSERT(list_empty(&fs_info->delayed_iputs));
4152afcdd129SJosef Bacik 	set_bit(BTRFS_FS_CLOSING_DONE, &fs_info->flags);
4153f25784b3SYan Zheng 
41545958253cSQu Wenruo 	if (btrfs_check_quota_leak(fs_info)) {
41555958253cSQu Wenruo 		WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
41565958253cSQu Wenruo 		btrfs_err(fs_info, "qgroup reserved space leaked");
41575958253cSQu Wenruo 	}
41585958253cSQu Wenruo 
415904892340SEric Sandeen 	btrfs_free_qgroup_config(fs_info);
4160fe816d0fSNikolay Borisov 	ASSERT(list_empty(&fs_info->delalloc_roots));
4161bcef60f2SArne Jansen 
4162963d678bSMiao Xie 	if (percpu_counter_sum(&fs_info->delalloc_bytes)) {
416304892340SEric Sandeen 		btrfs_info(fs_info, "at unmount delalloc count %lld",
4164963d678bSMiao Xie 		       percpu_counter_sum(&fs_info->delalloc_bytes));
4165b0c68f8bSChris Mason 	}
416631153d81SYan Zheng 
41675deb17e1SJosef Bacik 	if (percpu_counter_sum(&fs_info->ordered_bytes))
41684297ff84SJosef Bacik 		btrfs_info(fs_info, "at unmount dio bytes count %lld",
41695deb17e1SJosef Bacik 			   percpu_counter_sum(&fs_info->ordered_bytes));
41704297ff84SJosef Bacik 
41716618a59bSAnand Jain 	btrfs_sysfs_remove_mounted(fs_info);
4172b7c35e81SAnand Jain 	btrfs_sysfs_remove_fsid(fs_info->fs_devices);
41735ac1d209SJeff Mahoney 
41741a4319ccSLiu Bo 	btrfs_put_block_group_cache(fs_info);
41751a4319ccSLiu Bo 
4176de348ee0SWang Shilong 	/*
4177de348ee0SWang Shilong 	 * we must make sure there is not any read request to
4178de348ee0SWang Shilong 	 * submit after we stopping all workers.
4179de348ee0SWang Shilong 	 */
4180de348ee0SWang Shilong 	invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
418196192499SJosef Bacik 	btrfs_stop_all_workers(fs_info);
418296192499SJosef Bacik 
41830a31daa4SFilipe Manana 	/* We shouldn't have any transaction open at this point */
41840a31daa4SFilipe Manana 	ASSERT(list_empty(&fs_info->trans_list));
41850a31daa4SFilipe Manana 
4186afcdd129SJosef Bacik 	clear_bit(BTRFS_FS_OPEN, &fs_info->flags);
41874273eaffSAnand Jain 	free_root_pointers(fs_info, true);
41888c38938cSJosef Bacik 	btrfs_free_fs_roots(fs_info);
41899ad6b7bcSChris Mason 
41904e19443dSJosef Bacik 	/*
41914e19443dSJosef Bacik 	 * We must free the block groups after dropping the fs_roots as we could
41924e19443dSJosef Bacik 	 * have had an IO error and have left over tree log blocks that aren't
41934e19443dSJosef Bacik 	 * cleaned up until the fs roots are freed.  This makes the block group
41944e19443dSJosef Bacik 	 * accounting appear to be wrong because there's pending reserved bytes,
41954e19443dSJosef Bacik 	 * so make sure we do the block group cleanup afterwards.
41964e19443dSJosef Bacik 	 */
41974e19443dSJosef Bacik 	btrfs_free_block_groups(fs_info);
41984e19443dSJosef Bacik 
419913e6c37bSJosef Bacik 	iput(fs_info->btree_inode);
4200d6bfde87SChris Mason 
420121adbd5cSStefan Behrens #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
42020b246afaSJeff Mahoney 	if (btrfs_test_opt(fs_info, CHECK_INTEGRITY))
42032ff7e61eSJeff Mahoney 		btrfsic_unmount(fs_info->fs_devices);
420421adbd5cSStefan Behrens #endif
420521adbd5cSStefan Behrens 
42060b86a832SChris Mason 	btrfs_mapping_tree_free(&fs_info->mapping_tree);
420768c94e55SNikolay Borisov 	btrfs_close_devices(fs_info->fs_devices);
4208eb60ceacSChris Mason }
4209eb60ceacSChris Mason 
4210b9fab919SChris Mason int btrfs_buffer_uptodate(struct extent_buffer *buf, u64 parent_transid,
4211b9fab919SChris Mason 			  int atomic)
4212ccd467d6SChris Mason {
42131259ab75SChris Mason 	int ret;
4214727011e0SChris Mason 	struct inode *btree_inode = buf->pages[0]->mapping->host;
42151259ab75SChris Mason 
42160b32f4bbSJosef Bacik 	ret = extent_buffer_uptodate(buf);
42171259ab75SChris Mason 	if (!ret)
42181259ab75SChris Mason 		return ret;
42191259ab75SChris Mason 
42201259ab75SChris Mason 	ret = verify_parent_transid(&BTRFS_I(btree_inode)->io_tree, buf,
4221b9fab919SChris Mason 				    parent_transid, atomic);
4222b9fab919SChris Mason 	if (ret == -EAGAIN)
4223b9fab919SChris Mason 		return ret;
42241259ab75SChris Mason 	return !ret;
42255f39d397SChris Mason }
42266702ed49SChris Mason 
42275f39d397SChris Mason void btrfs_mark_buffer_dirty(struct extent_buffer *buf)
42285f39d397SChris Mason {
42292f4d60dfSQu Wenruo 	struct btrfs_fs_info *fs_info = buf->fs_info;
42305f39d397SChris Mason 	u64 transid = btrfs_header_generation(buf);
4231b9473439SChris Mason 	int was_dirty;
4232b4ce94deSChris Mason 
423306ea65a3SJosef Bacik #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
423406ea65a3SJosef Bacik 	/*
423506ea65a3SJosef Bacik 	 * This is a fast path so only do this check if we have sanity tests
423652042d8eSAndrea Gelmini 	 * enabled.  Normal people shouldn't be using unmapped buffers as dirty
423706ea65a3SJosef Bacik 	 * outside of the sanity tests.
423806ea65a3SJosef Bacik 	 */
4239b0132a3bSNikolay Borisov 	if (unlikely(test_bit(EXTENT_BUFFER_UNMAPPED, &buf->bflags)))
424006ea65a3SJosef Bacik 		return;
424106ea65a3SJosef Bacik #endif
4242b9447ef8SChris Mason 	btrfs_assert_tree_locked(buf);
42430b246afaSJeff Mahoney 	if (transid != fs_info->generation)
42445d163e0eSJeff Mahoney 		WARN(1, KERN_CRIT "btrfs transid mismatch buffer %llu, found %llu running %llu\n",
42450b246afaSJeff Mahoney 			buf->start, transid, fs_info->generation);
42460b32f4bbSJosef Bacik 	was_dirty = set_extent_buffer_dirty(buf);
4247e2d84521SMiao Xie 	if (!was_dirty)
4248104b4e51SNikolay Borisov 		percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
4249e2d84521SMiao Xie 					 buf->len,
42500b246afaSJeff Mahoney 					 fs_info->dirty_metadata_batch);
42511f21ef0aSFilipe Manana #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
425269fc6cbbSQu Wenruo 	/*
425369fc6cbbSQu Wenruo 	 * Since btrfs_mark_buffer_dirty() can be called with item pointer set
425469fc6cbbSQu Wenruo 	 * but item data not updated.
425569fc6cbbSQu Wenruo 	 * So here we should only check item pointers, not item data.
425669fc6cbbSQu Wenruo 	 */
425769fc6cbbSQu Wenruo 	if (btrfs_header_level(buf) == 0 &&
4258cfdaad5eSDavid Sterba 	    btrfs_check_leaf_relaxed(buf)) {
4259a4f78750SDavid Sterba 		btrfs_print_leaf(buf);
42601f21ef0aSFilipe Manana 		ASSERT(0);
42611f21ef0aSFilipe Manana 	}
42621f21ef0aSFilipe Manana #endif
4263eb60ceacSChris Mason }
4264eb60ceacSChris Mason 
42652ff7e61eSJeff Mahoney static void __btrfs_btree_balance_dirty(struct btrfs_fs_info *fs_info,
4266b53d3f5dSLiu Bo 					int flush_delayed)
426735b7e476SChris Mason {
4268188de649SChris Mason 	/*
4269188de649SChris Mason 	 * looks as though older kernels can get into trouble with
4270188de649SChris Mason 	 * this code, they end up stuck in balance_dirty_pages forever
4271188de649SChris Mason 	 */
4272e2d84521SMiao Xie 	int ret;
4273d6bfde87SChris Mason 
42746933c02eSJens Axboe 	if (current->flags & PF_MEMALLOC)
4275d6bfde87SChris Mason 		return;
4276d6bfde87SChris Mason 
4277b53d3f5dSLiu Bo 	if (flush_delayed)
42782ff7e61eSJeff Mahoney 		btrfs_balance_delayed_items(fs_info);
427916cdcec7SMiao Xie 
4280d814a491SEthan Lien 	ret = __percpu_counter_compare(&fs_info->dirty_metadata_bytes,
4281d814a491SEthan Lien 				     BTRFS_DIRTY_METADATA_THRESH,
4282d814a491SEthan Lien 				     fs_info->dirty_metadata_batch);
4283e2d84521SMiao Xie 	if (ret > 0) {
42840b246afaSJeff Mahoney 		balance_dirty_pages_ratelimited(fs_info->btree_inode->i_mapping);
428516cdcec7SMiao Xie 	}
428616cdcec7SMiao Xie }
428716cdcec7SMiao Xie 
42882ff7e61eSJeff Mahoney void btrfs_btree_balance_dirty(struct btrfs_fs_info *fs_info)
428916cdcec7SMiao Xie {
42902ff7e61eSJeff Mahoney 	__btrfs_btree_balance_dirty(fs_info, 1);
429135b7e476SChris Mason }
4292b53d3f5dSLiu Bo 
42932ff7e61eSJeff Mahoney void btrfs_btree_balance_dirty_nodelay(struct btrfs_fs_info *fs_info)
4294b53d3f5dSLiu Bo {
42952ff7e61eSJeff Mahoney 	__btrfs_btree_balance_dirty(fs_info, 0);
4296d6bfde87SChris Mason }
42976b80053dSChris Mason 
4298581c1760SQu Wenruo int btrfs_read_buffer(struct extent_buffer *buf, u64 parent_transid, int level,
4299581c1760SQu Wenruo 		      struct btrfs_key *first_key)
43006b80053dSChris Mason {
43015ab12d1fSDavid Sterba 	return btree_read_extent_buffer_pages(buf, parent_transid,
4302581c1760SQu Wenruo 					      level, first_key);
43036b80053dSChris Mason }
43040da5468fSChris Mason 
43052ff7e61eSJeff Mahoney static void btrfs_error_commit_super(struct btrfs_fs_info *fs_info)
4306acce952bSliubo {
4307fe816d0fSNikolay Borisov 	/* cleanup FS via transaction */
4308fe816d0fSNikolay Borisov 	btrfs_cleanup_transaction(fs_info);
4309fe816d0fSNikolay Borisov 
43100b246afaSJeff Mahoney 	mutex_lock(&fs_info->cleaner_mutex);
43112ff7e61eSJeff Mahoney 	btrfs_run_delayed_iputs(fs_info);
43120b246afaSJeff Mahoney 	mutex_unlock(&fs_info->cleaner_mutex);
4313acce952bSliubo 
43140b246afaSJeff Mahoney 	down_write(&fs_info->cleanup_work_sem);
43150b246afaSJeff Mahoney 	up_write(&fs_info->cleanup_work_sem);
4316acce952bSliubo }
4317acce952bSliubo 
4318ef67963dSJosef Bacik static void btrfs_drop_all_logs(struct btrfs_fs_info *fs_info)
4319ef67963dSJosef Bacik {
4320ef67963dSJosef Bacik 	struct btrfs_root *gang[8];
4321ef67963dSJosef Bacik 	u64 root_objectid = 0;
4322ef67963dSJosef Bacik 	int ret;
4323ef67963dSJosef Bacik 
4324ef67963dSJosef Bacik 	spin_lock(&fs_info->fs_roots_radix_lock);
4325ef67963dSJosef Bacik 	while ((ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
4326ef67963dSJosef Bacik 					     (void **)gang, root_objectid,
4327ef67963dSJosef Bacik 					     ARRAY_SIZE(gang))) != 0) {
4328ef67963dSJosef Bacik 		int i;
4329ef67963dSJosef Bacik 
4330ef67963dSJosef Bacik 		for (i = 0; i < ret; i++)
4331ef67963dSJosef Bacik 			gang[i] = btrfs_grab_root(gang[i]);
4332ef67963dSJosef Bacik 		spin_unlock(&fs_info->fs_roots_radix_lock);
4333ef67963dSJosef Bacik 
4334ef67963dSJosef Bacik 		for (i = 0; i < ret; i++) {
4335ef67963dSJosef Bacik 			if (!gang[i])
4336ef67963dSJosef Bacik 				continue;
4337ef67963dSJosef Bacik 			root_objectid = gang[i]->root_key.objectid;
4338ef67963dSJosef Bacik 			btrfs_free_log(NULL, gang[i]);
4339ef67963dSJosef Bacik 			btrfs_put_root(gang[i]);
4340ef67963dSJosef Bacik 		}
4341ef67963dSJosef Bacik 		root_objectid++;
4342ef67963dSJosef Bacik 		spin_lock(&fs_info->fs_roots_radix_lock);
4343ef67963dSJosef Bacik 	}
4344ef67963dSJosef Bacik 	spin_unlock(&fs_info->fs_roots_radix_lock);
4345ef67963dSJosef Bacik 	btrfs_free_log_root_tree(NULL, fs_info);
4346ef67963dSJosef Bacik }
4347ef67963dSJosef Bacik 
4348143bede5SJeff Mahoney static void btrfs_destroy_ordered_extents(struct btrfs_root *root)
4349acce952bSliubo {
4350acce952bSliubo 	struct btrfs_ordered_extent *ordered;
4351acce952bSliubo 
4352199c2a9cSMiao Xie 	spin_lock(&root->ordered_extent_lock);
4353779880efSJosef Bacik 	/*
4354779880efSJosef Bacik 	 * This will just short circuit the ordered completion stuff which will
4355779880efSJosef Bacik 	 * make sure the ordered extent gets properly cleaned up.
4356779880efSJosef Bacik 	 */
4357199c2a9cSMiao Xie 	list_for_each_entry(ordered, &root->ordered_extents,
4358779880efSJosef Bacik 			    root_extent_list)
4359779880efSJosef Bacik 		set_bit(BTRFS_ORDERED_IOERR, &ordered->flags);
4360199c2a9cSMiao Xie 	spin_unlock(&root->ordered_extent_lock);
4361199c2a9cSMiao Xie }
4362199c2a9cSMiao Xie 
4363199c2a9cSMiao Xie static void btrfs_destroy_all_ordered_extents(struct btrfs_fs_info *fs_info)
4364199c2a9cSMiao Xie {
4365199c2a9cSMiao Xie 	struct btrfs_root *root;
4366199c2a9cSMiao Xie 	struct list_head splice;
4367199c2a9cSMiao Xie 
4368199c2a9cSMiao Xie 	INIT_LIST_HEAD(&splice);
4369199c2a9cSMiao Xie 
4370199c2a9cSMiao Xie 	spin_lock(&fs_info->ordered_root_lock);
4371199c2a9cSMiao Xie 	list_splice_init(&fs_info->ordered_roots, &splice);
4372199c2a9cSMiao Xie 	while (!list_empty(&splice)) {
4373199c2a9cSMiao Xie 		root = list_first_entry(&splice, struct btrfs_root,
4374199c2a9cSMiao Xie 					ordered_root);
43751de2cfdeSJosef Bacik 		list_move_tail(&root->ordered_root,
43761de2cfdeSJosef Bacik 			       &fs_info->ordered_roots);
4377199c2a9cSMiao Xie 
43782a85d9caSLiu Bo 		spin_unlock(&fs_info->ordered_root_lock);
4379199c2a9cSMiao Xie 		btrfs_destroy_ordered_extents(root);
4380199c2a9cSMiao Xie 
43812a85d9caSLiu Bo 		cond_resched();
43822a85d9caSLiu Bo 		spin_lock(&fs_info->ordered_root_lock);
4383199c2a9cSMiao Xie 	}
4384199c2a9cSMiao Xie 	spin_unlock(&fs_info->ordered_root_lock);
438574d5d229SJosef Bacik 
438674d5d229SJosef Bacik 	/*
438774d5d229SJosef Bacik 	 * We need this here because if we've been flipped read-only we won't
438874d5d229SJosef Bacik 	 * get sync() from the umount, so we need to make sure any ordered
438974d5d229SJosef Bacik 	 * extents that haven't had their dirty pages IO start writeout yet
439074d5d229SJosef Bacik 	 * actually get run and error out properly.
439174d5d229SJosef Bacik 	 */
439274d5d229SJosef Bacik 	btrfs_wait_ordered_roots(fs_info, U64_MAX, 0, (u64)-1);
4393acce952bSliubo }
4394acce952bSliubo 
439535a3621bSStefan Behrens static int btrfs_destroy_delayed_refs(struct btrfs_transaction *trans,
43962ff7e61eSJeff Mahoney 				      struct btrfs_fs_info *fs_info)
4397acce952bSliubo {
4398acce952bSliubo 	struct rb_node *node;
4399acce952bSliubo 	struct btrfs_delayed_ref_root *delayed_refs;
4400acce952bSliubo 	struct btrfs_delayed_ref_node *ref;
4401acce952bSliubo 	int ret = 0;
4402acce952bSliubo 
4403acce952bSliubo 	delayed_refs = &trans->delayed_refs;
4404acce952bSliubo 
4405acce952bSliubo 	spin_lock(&delayed_refs->lock);
4406d7df2c79SJosef Bacik 	if (atomic_read(&delayed_refs->num_entries) == 0) {
4407cfece4dbSDavid Sterba 		spin_unlock(&delayed_refs->lock);
4408b79ce3ddSDavid Sterba 		btrfs_debug(fs_info, "delayed_refs has NO entry");
4409acce952bSliubo 		return ret;
4410acce952bSliubo 	}
4411acce952bSliubo 
44125c9d028bSLiu Bo 	while ((node = rb_first_cached(&delayed_refs->href_root)) != NULL) {
4413d7df2c79SJosef Bacik 		struct btrfs_delayed_ref_head *head;
44140e0adbcfSJosef Bacik 		struct rb_node *n;
4415e78417d1SJosef Bacik 		bool pin_bytes = false;
4416acce952bSliubo 
4417d7df2c79SJosef Bacik 		head = rb_entry(node, struct btrfs_delayed_ref_head,
4418d7df2c79SJosef Bacik 				href_node);
44193069bd26SJosef Bacik 		if (btrfs_delayed_ref_lock(delayed_refs, head))
4420b939d1abSJosef Bacik 			continue;
44213069bd26SJosef Bacik 
4422d7df2c79SJosef Bacik 		spin_lock(&head->lock);
4423e3d03965SLiu Bo 		while ((n = rb_first_cached(&head->ref_tree)) != NULL) {
44240e0adbcfSJosef Bacik 			ref = rb_entry(n, struct btrfs_delayed_ref_node,
44250e0adbcfSJosef Bacik 				       ref_node);
4426d7df2c79SJosef Bacik 			ref->in_tree = 0;
4427e3d03965SLiu Bo 			rb_erase_cached(&ref->ref_node, &head->ref_tree);
44280e0adbcfSJosef Bacik 			RB_CLEAR_NODE(&ref->ref_node);
44291d57ee94SWang Xiaoguang 			if (!list_empty(&ref->add_list))
44301d57ee94SWang Xiaoguang 				list_del(&ref->add_list);
4431d7df2c79SJosef Bacik 			atomic_dec(&delayed_refs->num_entries);
4432d7df2c79SJosef Bacik 			btrfs_put_delayed_ref(ref);
4433d7df2c79SJosef Bacik 		}
443454067ae9SJosef Bacik 		if (head->must_insert_reserved)
4435e78417d1SJosef Bacik 			pin_bytes = true;
443678a6184aSMiao Xie 		btrfs_free_delayed_extent_op(head->extent_op);
4437fa781ceaSJosef Bacik 		btrfs_delete_ref_head(delayed_refs, head);
4438d7df2c79SJosef Bacik 		spin_unlock(&head->lock);
4439acce952bSliubo 		spin_unlock(&delayed_refs->lock);
4440e78417d1SJosef Bacik 		mutex_unlock(&head->mutex);
4441acce952bSliubo 
4442f603bb94SNikolay Borisov 		if (pin_bytes) {
4443f603bb94SNikolay Borisov 			struct btrfs_block_group *cache;
4444f603bb94SNikolay Borisov 
4445f603bb94SNikolay Borisov 			cache = btrfs_lookup_block_group(fs_info, head->bytenr);
4446f603bb94SNikolay Borisov 			BUG_ON(!cache);
4447f603bb94SNikolay Borisov 
4448f603bb94SNikolay Borisov 			spin_lock(&cache->space_info->lock);
4449f603bb94SNikolay Borisov 			spin_lock(&cache->lock);
4450f603bb94SNikolay Borisov 			cache->pinned += head->num_bytes;
4451f603bb94SNikolay Borisov 			btrfs_space_info_update_bytes_pinned(fs_info,
4452f603bb94SNikolay Borisov 				cache->space_info, head->num_bytes);
4453f603bb94SNikolay Borisov 			cache->reserved -= head->num_bytes;
4454f603bb94SNikolay Borisov 			cache->space_info->bytes_reserved -= head->num_bytes;
4455f603bb94SNikolay Borisov 			spin_unlock(&cache->lock);
4456f603bb94SNikolay Borisov 			spin_unlock(&cache->space_info->lock);
4457f603bb94SNikolay Borisov 			percpu_counter_add_batch(
4458f603bb94SNikolay Borisov 				&cache->space_info->total_bytes_pinned,
4459f603bb94SNikolay Borisov 				head->num_bytes, BTRFS_TOTAL_BYTES_PINNED_BATCH);
4460f603bb94SNikolay Borisov 
4461f603bb94SNikolay Borisov 			btrfs_put_block_group(cache);
4462f603bb94SNikolay Borisov 
4463f603bb94SNikolay Borisov 			btrfs_error_unpin_extent_range(fs_info, head->bytenr,
4464f603bb94SNikolay Borisov 				head->bytenr + head->num_bytes - 1);
4465f603bb94SNikolay Borisov 		}
446631890da0SJosef Bacik 		btrfs_cleanup_ref_head_accounting(fs_info, delayed_refs, head);
4467d278850eSJosef Bacik 		btrfs_put_delayed_ref_head(head);
4468acce952bSliubo 		cond_resched();
4469acce952bSliubo 		spin_lock(&delayed_refs->lock);
4470acce952bSliubo 	}
447181f7eb00SJeff Mahoney 	btrfs_qgroup_destroy_extent_records(trans);
4472acce952bSliubo 
4473acce952bSliubo 	spin_unlock(&delayed_refs->lock);
4474acce952bSliubo 
4475acce952bSliubo 	return ret;
4476acce952bSliubo }
4477acce952bSliubo 
4478143bede5SJeff Mahoney static void btrfs_destroy_delalloc_inodes(struct btrfs_root *root)
4479acce952bSliubo {
4480acce952bSliubo 	struct btrfs_inode *btrfs_inode;
4481acce952bSliubo 	struct list_head splice;
4482acce952bSliubo 
4483acce952bSliubo 	INIT_LIST_HEAD(&splice);
4484acce952bSliubo 
4485eb73c1b7SMiao Xie 	spin_lock(&root->delalloc_lock);
4486eb73c1b7SMiao Xie 	list_splice_init(&root->delalloc_inodes, &splice);
4487acce952bSliubo 
4488acce952bSliubo 	while (!list_empty(&splice)) {
4489fe816d0fSNikolay Borisov 		struct inode *inode = NULL;
4490eb73c1b7SMiao Xie 		btrfs_inode = list_first_entry(&splice, struct btrfs_inode,
4491acce952bSliubo 					       delalloc_inodes);
4492fe816d0fSNikolay Borisov 		__btrfs_del_delalloc_inode(root, btrfs_inode);
4493eb73c1b7SMiao Xie 		spin_unlock(&root->delalloc_lock);
4494acce952bSliubo 
4495fe816d0fSNikolay Borisov 		/*
4496fe816d0fSNikolay Borisov 		 * Make sure we get a live inode and that it'll not disappear
4497fe816d0fSNikolay Borisov 		 * meanwhile.
4498fe816d0fSNikolay Borisov 		 */
4499fe816d0fSNikolay Borisov 		inode = igrab(&btrfs_inode->vfs_inode);
4500fe816d0fSNikolay Borisov 		if (inode) {
4501fe816d0fSNikolay Borisov 			invalidate_inode_pages2(inode->i_mapping);
4502fe816d0fSNikolay Borisov 			iput(inode);
4503fe816d0fSNikolay Borisov 		}
4504eb73c1b7SMiao Xie 		spin_lock(&root->delalloc_lock);
4505acce952bSliubo 	}
4506eb73c1b7SMiao Xie 	spin_unlock(&root->delalloc_lock);
4507eb73c1b7SMiao Xie }
4508eb73c1b7SMiao Xie 
4509eb73c1b7SMiao Xie static void btrfs_destroy_all_delalloc_inodes(struct btrfs_fs_info *fs_info)
4510eb73c1b7SMiao Xie {
4511eb73c1b7SMiao Xie 	struct btrfs_root *root;
4512eb73c1b7SMiao Xie 	struct list_head splice;
4513eb73c1b7SMiao Xie 
4514eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&splice);
4515eb73c1b7SMiao Xie 
4516eb73c1b7SMiao Xie 	spin_lock(&fs_info->delalloc_root_lock);
4517eb73c1b7SMiao Xie 	list_splice_init(&fs_info->delalloc_roots, &splice);
4518eb73c1b7SMiao Xie 	while (!list_empty(&splice)) {
4519eb73c1b7SMiao Xie 		root = list_first_entry(&splice, struct btrfs_root,
4520eb73c1b7SMiao Xie 					 delalloc_root);
452100246528SJosef Bacik 		root = btrfs_grab_root(root);
4522eb73c1b7SMiao Xie 		BUG_ON(!root);
4523eb73c1b7SMiao Xie 		spin_unlock(&fs_info->delalloc_root_lock);
4524eb73c1b7SMiao Xie 
4525eb73c1b7SMiao Xie 		btrfs_destroy_delalloc_inodes(root);
452600246528SJosef Bacik 		btrfs_put_root(root);
4527eb73c1b7SMiao Xie 
4528eb73c1b7SMiao Xie 		spin_lock(&fs_info->delalloc_root_lock);
4529eb73c1b7SMiao Xie 	}
4530eb73c1b7SMiao Xie 	spin_unlock(&fs_info->delalloc_root_lock);
4531acce952bSliubo }
4532acce952bSliubo 
45332ff7e61eSJeff Mahoney static int btrfs_destroy_marked_extents(struct btrfs_fs_info *fs_info,
4534acce952bSliubo 					struct extent_io_tree *dirty_pages,
4535acce952bSliubo 					int mark)
4536acce952bSliubo {
4537acce952bSliubo 	int ret;
4538acce952bSliubo 	struct extent_buffer *eb;
4539acce952bSliubo 	u64 start = 0;
4540acce952bSliubo 	u64 end;
4541acce952bSliubo 
4542acce952bSliubo 	while (1) {
4543acce952bSliubo 		ret = find_first_extent_bit(dirty_pages, start, &start, &end,
4544e6138876SJosef Bacik 					    mark, NULL);
4545acce952bSliubo 		if (ret)
4546acce952bSliubo 			break;
4547acce952bSliubo 
454891166212SDavid Sterba 		clear_extent_bits(dirty_pages, start, end, mark);
4549acce952bSliubo 		while (start <= end) {
45500b246afaSJeff Mahoney 			eb = find_extent_buffer(fs_info, start);
45510b246afaSJeff Mahoney 			start += fs_info->nodesize;
4552fd8b2b61SJosef Bacik 			if (!eb)
4553acce952bSliubo 				continue;
4554fd8b2b61SJosef Bacik 			wait_on_extent_buffer_writeback(eb);
4555acce952bSliubo 
4556fd8b2b61SJosef Bacik 			if (test_and_clear_bit(EXTENT_BUFFER_DIRTY,
4557fd8b2b61SJosef Bacik 					       &eb->bflags))
4558fd8b2b61SJosef Bacik 				clear_extent_buffer_dirty(eb);
4559fd8b2b61SJosef Bacik 			free_extent_buffer_stale(eb);
4560acce952bSliubo 		}
4561acce952bSliubo 	}
4562acce952bSliubo 
4563acce952bSliubo 	return ret;
4564acce952bSliubo }
4565acce952bSliubo 
45662ff7e61eSJeff Mahoney static int btrfs_destroy_pinned_extent(struct btrfs_fs_info *fs_info,
4567fe119a6eSNikolay Borisov 				       struct extent_io_tree *unpin)
4568acce952bSliubo {
4569acce952bSliubo 	u64 start;
4570acce952bSliubo 	u64 end;
4571acce952bSliubo 	int ret;
4572acce952bSliubo 
4573acce952bSliubo 	while (1) {
45740e6ec385SFilipe Manana 		struct extent_state *cached_state = NULL;
45750e6ec385SFilipe Manana 
4576fcd5e742SLu Fengqi 		/*
4577fcd5e742SLu Fengqi 		 * The btrfs_finish_extent_commit() may get the same range as
4578fcd5e742SLu Fengqi 		 * ours between find_first_extent_bit and clear_extent_dirty.
4579fcd5e742SLu Fengqi 		 * Hence, hold the unused_bg_unpin_mutex to avoid double unpin
4580fcd5e742SLu Fengqi 		 * the same extent range.
4581fcd5e742SLu Fengqi 		 */
4582fcd5e742SLu Fengqi 		mutex_lock(&fs_info->unused_bg_unpin_mutex);
4583acce952bSliubo 		ret = find_first_extent_bit(unpin, 0, &start, &end,
45840e6ec385SFilipe Manana 					    EXTENT_DIRTY, &cached_state);
4585fcd5e742SLu Fengqi 		if (ret) {
4586fcd5e742SLu Fengqi 			mutex_unlock(&fs_info->unused_bg_unpin_mutex);
4587acce952bSliubo 			break;
4588fcd5e742SLu Fengqi 		}
4589acce952bSliubo 
45900e6ec385SFilipe Manana 		clear_extent_dirty(unpin, start, end, &cached_state);
45910e6ec385SFilipe Manana 		free_extent_state(cached_state);
45922ff7e61eSJeff Mahoney 		btrfs_error_unpin_extent_range(fs_info, start, end);
4593fcd5e742SLu Fengqi 		mutex_unlock(&fs_info->unused_bg_unpin_mutex);
4594acce952bSliubo 		cond_resched();
4595acce952bSliubo 	}
4596acce952bSliubo 
4597acce952bSliubo 	return 0;
4598acce952bSliubo }
4599acce952bSliubo 
460032da5386SDavid Sterba static void btrfs_cleanup_bg_io(struct btrfs_block_group *cache)
4601c79a1751SLiu Bo {
4602c79a1751SLiu Bo 	struct inode *inode;
4603c79a1751SLiu Bo 
4604c79a1751SLiu Bo 	inode = cache->io_ctl.inode;
4605c79a1751SLiu Bo 	if (inode) {
4606c79a1751SLiu Bo 		invalidate_inode_pages2(inode->i_mapping);
4607c79a1751SLiu Bo 		BTRFS_I(inode)->generation = 0;
4608c79a1751SLiu Bo 		cache->io_ctl.inode = NULL;
4609c79a1751SLiu Bo 		iput(inode);
4610c79a1751SLiu Bo 	}
4611bbc37d6eSFilipe Manana 	ASSERT(cache->io_ctl.pages == NULL);
4612c79a1751SLiu Bo 	btrfs_put_block_group(cache);
4613c79a1751SLiu Bo }
4614c79a1751SLiu Bo 
4615c79a1751SLiu Bo void btrfs_cleanup_dirty_bgs(struct btrfs_transaction *cur_trans,
46162ff7e61eSJeff Mahoney 			     struct btrfs_fs_info *fs_info)
4617c79a1751SLiu Bo {
461832da5386SDavid Sterba 	struct btrfs_block_group *cache;
4619c79a1751SLiu Bo 
4620c79a1751SLiu Bo 	spin_lock(&cur_trans->dirty_bgs_lock);
4621c79a1751SLiu Bo 	while (!list_empty(&cur_trans->dirty_bgs)) {
4622c79a1751SLiu Bo 		cache = list_first_entry(&cur_trans->dirty_bgs,
462332da5386SDavid Sterba 					 struct btrfs_block_group,
4624c79a1751SLiu Bo 					 dirty_list);
4625c79a1751SLiu Bo 
4626c79a1751SLiu Bo 		if (!list_empty(&cache->io_list)) {
4627c79a1751SLiu Bo 			spin_unlock(&cur_trans->dirty_bgs_lock);
4628c79a1751SLiu Bo 			list_del_init(&cache->io_list);
4629c79a1751SLiu Bo 			btrfs_cleanup_bg_io(cache);
4630c79a1751SLiu Bo 			spin_lock(&cur_trans->dirty_bgs_lock);
4631c79a1751SLiu Bo 		}
4632c79a1751SLiu Bo 
4633c79a1751SLiu Bo 		list_del_init(&cache->dirty_list);
4634c79a1751SLiu Bo 		spin_lock(&cache->lock);
4635c79a1751SLiu Bo 		cache->disk_cache_state = BTRFS_DC_ERROR;
4636c79a1751SLiu Bo 		spin_unlock(&cache->lock);
4637c79a1751SLiu Bo 
4638c79a1751SLiu Bo 		spin_unlock(&cur_trans->dirty_bgs_lock);
4639c79a1751SLiu Bo 		btrfs_put_block_group(cache);
4640ba2c4d4eSJosef Bacik 		btrfs_delayed_refs_rsv_release(fs_info, 1);
4641c79a1751SLiu Bo 		spin_lock(&cur_trans->dirty_bgs_lock);
4642c79a1751SLiu Bo 	}
4643c79a1751SLiu Bo 	spin_unlock(&cur_trans->dirty_bgs_lock);
4644c79a1751SLiu Bo 
464545ae2c18SNikolay Borisov 	/*
464645ae2c18SNikolay Borisov 	 * Refer to the definition of io_bgs member for details why it's safe
464745ae2c18SNikolay Borisov 	 * to use it without any locking
464845ae2c18SNikolay Borisov 	 */
4649c79a1751SLiu Bo 	while (!list_empty(&cur_trans->io_bgs)) {
4650c79a1751SLiu Bo 		cache = list_first_entry(&cur_trans->io_bgs,
465132da5386SDavid Sterba 					 struct btrfs_block_group,
4652c79a1751SLiu Bo 					 io_list);
4653c79a1751SLiu Bo 
4654c79a1751SLiu Bo 		list_del_init(&cache->io_list);
4655c79a1751SLiu Bo 		spin_lock(&cache->lock);
4656c79a1751SLiu Bo 		cache->disk_cache_state = BTRFS_DC_ERROR;
4657c79a1751SLiu Bo 		spin_unlock(&cache->lock);
4658c79a1751SLiu Bo 		btrfs_cleanup_bg_io(cache);
4659c79a1751SLiu Bo 	}
4660c79a1751SLiu Bo }
4661c79a1751SLiu Bo 
466249b25e05SJeff Mahoney void btrfs_cleanup_one_transaction(struct btrfs_transaction *cur_trans,
46632ff7e61eSJeff Mahoney 				   struct btrfs_fs_info *fs_info)
466449b25e05SJeff Mahoney {
4665bbbf7243SNikolay Borisov 	struct btrfs_device *dev, *tmp;
4666bbbf7243SNikolay Borisov 
46672ff7e61eSJeff Mahoney 	btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
4668c79a1751SLiu Bo 	ASSERT(list_empty(&cur_trans->dirty_bgs));
4669c79a1751SLiu Bo 	ASSERT(list_empty(&cur_trans->io_bgs));
4670c79a1751SLiu Bo 
4671bbbf7243SNikolay Borisov 	list_for_each_entry_safe(dev, tmp, &cur_trans->dev_update_list,
4672bbbf7243SNikolay Borisov 				 post_commit_list) {
4673bbbf7243SNikolay Borisov 		list_del_init(&dev->post_commit_list);
4674bbbf7243SNikolay Borisov 	}
4675bbbf7243SNikolay Borisov 
46762ff7e61eSJeff Mahoney 	btrfs_destroy_delayed_refs(cur_trans, fs_info);
467749b25e05SJeff Mahoney 
46784a9d8bdeSMiao Xie 	cur_trans->state = TRANS_STATE_COMMIT_START;
46790b246afaSJeff Mahoney 	wake_up(&fs_info->transaction_blocked_wait);
468049b25e05SJeff Mahoney 
46814a9d8bdeSMiao Xie 	cur_trans->state = TRANS_STATE_UNBLOCKED;
46820b246afaSJeff Mahoney 	wake_up(&fs_info->transaction_wait);
468349b25e05SJeff Mahoney 
4684ccdf9b30SJeff Mahoney 	btrfs_destroy_delayed_inodes(fs_info);
468567cde344SMiao Xie 
46862ff7e61eSJeff Mahoney 	btrfs_destroy_marked_extents(fs_info, &cur_trans->dirty_pages,
468749b25e05SJeff Mahoney 				     EXTENT_DIRTY);
4688fe119a6eSNikolay Borisov 	btrfs_destroy_pinned_extent(fs_info, &cur_trans->pinned_extents);
468949b25e05SJeff Mahoney 
46904a9d8bdeSMiao Xie 	cur_trans->state =TRANS_STATE_COMPLETED;
46914a9d8bdeSMiao Xie 	wake_up(&cur_trans->commit_wait);
469249b25e05SJeff Mahoney }
469349b25e05SJeff Mahoney 
46942ff7e61eSJeff Mahoney static int btrfs_cleanup_transaction(struct btrfs_fs_info *fs_info)
4695acce952bSliubo {
4696acce952bSliubo 	struct btrfs_transaction *t;
4697acce952bSliubo 
46980b246afaSJeff Mahoney 	mutex_lock(&fs_info->transaction_kthread_mutex);
4699acce952bSliubo 
47000b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
47010b246afaSJeff Mahoney 	while (!list_empty(&fs_info->trans_list)) {
47020b246afaSJeff Mahoney 		t = list_first_entry(&fs_info->trans_list,
4703724e2315SJosef Bacik 				     struct btrfs_transaction, list);
4704724e2315SJosef Bacik 		if (t->state >= TRANS_STATE_COMMIT_START) {
47059b64f57dSElena Reshetova 			refcount_inc(&t->use_count);
47060b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
47072ff7e61eSJeff Mahoney 			btrfs_wait_for_commit(fs_info, t->transid);
4708724e2315SJosef Bacik 			btrfs_put_transaction(t);
47090b246afaSJeff Mahoney 			spin_lock(&fs_info->trans_lock);
4710724e2315SJosef Bacik 			continue;
4711724e2315SJosef Bacik 		}
47120b246afaSJeff Mahoney 		if (t == fs_info->running_transaction) {
4713724e2315SJosef Bacik 			t->state = TRANS_STATE_COMMIT_DOING;
47140b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
4715724e2315SJosef Bacik 			/*
4716724e2315SJosef Bacik 			 * We wait for 0 num_writers since we don't hold a trans
4717724e2315SJosef Bacik 			 * handle open currently for this transaction.
4718724e2315SJosef Bacik 			 */
4719724e2315SJosef Bacik 			wait_event(t->writer_wait,
4720724e2315SJosef Bacik 				   atomic_read(&t->num_writers) == 0);
4721724e2315SJosef Bacik 		} else {
47220b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
4723724e2315SJosef Bacik 		}
47242ff7e61eSJeff Mahoney 		btrfs_cleanup_one_transaction(t, fs_info);
4725724e2315SJosef Bacik 
47260b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
47270b246afaSJeff Mahoney 		if (t == fs_info->running_transaction)
47280b246afaSJeff Mahoney 			fs_info->running_transaction = NULL;
4729724e2315SJosef Bacik 		list_del_init(&t->list);
47300b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
4731a4abeea4SJosef Bacik 
4732724e2315SJosef Bacik 		btrfs_put_transaction(t);
47332ff7e61eSJeff Mahoney 		trace_btrfs_transaction_commit(fs_info->tree_root);
47340b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
4735724e2315SJosef Bacik 	}
47360b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
47370b246afaSJeff Mahoney 	btrfs_destroy_all_ordered_extents(fs_info);
4738ccdf9b30SJeff Mahoney 	btrfs_destroy_delayed_inodes(fs_info);
4739ccdf9b30SJeff Mahoney 	btrfs_assert_delayed_root_empty(fs_info);
47400b246afaSJeff Mahoney 	btrfs_destroy_all_delalloc_inodes(fs_info);
4741ef67963dSJosef Bacik 	btrfs_drop_all_logs(fs_info);
47420b246afaSJeff Mahoney 	mutex_unlock(&fs_info->transaction_kthread_mutex);
4743acce952bSliubo 
4744acce952bSliubo 	return 0;
4745acce952bSliubo }
4746ec7d6dfdSNikolay Borisov 
4747453e4873SNikolay Borisov int btrfs_init_root_free_objectid(struct btrfs_root *root)
4748ec7d6dfdSNikolay Borisov {
4749ec7d6dfdSNikolay Borisov 	struct btrfs_path *path;
4750ec7d6dfdSNikolay Borisov 	int ret;
4751ec7d6dfdSNikolay Borisov 	struct extent_buffer *l;
4752ec7d6dfdSNikolay Borisov 	struct btrfs_key search_key;
4753ec7d6dfdSNikolay Borisov 	struct btrfs_key found_key;
4754ec7d6dfdSNikolay Borisov 	int slot;
4755ec7d6dfdSNikolay Borisov 
4756ec7d6dfdSNikolay Borisov 	path = btrfs_alloc_path();
4757ec7d6dfdSNikolay Borisov 	if (!path)
4758ec7d6dfdSNikolay Borisov 		return -ENOMEM;
4759ec7d6dfdSNikolay Borisov 
4760ec7d6dfdSNikolay Borisov 	search_key.objectid = BTRFS_LAST_FREE_OBJECTID;
4761ec7d6dfdSNikolay Borisov 	search_key.type = -1;
4762ec7d6dfdSNikolay Borisov 	search_key.offset = (u64)-1;
4763ec7d6dfdSNikolay Borisov 	ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
4764ec7d6dfdSNikolay Borisov 	if (ret < 0)
4765ec7d6dfdSNikolay Borisov 		goto error;
4766ec7d6dfdSNikolay Borisov 	BUG_ON(ret == 0); /* Corruption */
4767ec7d6dfdSNikolay Borisov 	if (path->slots[0] > 0) {
4768ec7d6dfdSNikolay Borisov 		slot = path->slots[0] - 1;
4769ec7d6dfdSNikolay Borisov 		l = path->nodes[0];
4770ec7d6dfdSNikolay Borisov 		btrfs_item_key_to_cpu(l, &found_key, slot);
477123125104SNikolay Borisov 		root->free_objectid = max_t(u64, found_key.objectid + 1,
477223125104SNikolay Borisov 					    BTRFS_FIRST_FREE_OBJECTID);
4773ec7d6dfdSNikolay Borisov 	} else {
477423125104SNikolay Borisov 		root->free_objectid = BTRFS_FIRST_FREE_OBJECTID;
4775ec7d6dfdSNikolay Borisov 	}
4776ec7d6dfdSNikolay Borisov 	ret = 0;
4777ec7d6dfdSNikolay Borisov error:
4778ec7d6dfdSNikolay Borisov 	btrfs_free_path(path);
4779ec7d6dfdSNikolay Borisov 	return ret;
4780ec7d6dfdSNikolay Borisov }
4781ec7d6dfdSNikolay Borisov 
4782543068a2SNikolay Borisov int btrfs_get_free_objectid(struct btrfs_root *root, u64 *objectid)
4783ec7d6dfdSNikolay Borisov {
4784ec7d6dfdSNikolay Borisov 	int ret;
4785ec7d6dfdSNikolay Borisov 	mutex_lock(&root->objectid_mutex);
4786ec7d6dfdSNikolay Borisov 
47876b8fad57SNikolay Borisov 	if (unlikely(root->free_objectid >= BTRFS_LAST_FREE_OBJECTID)) {
4788ec7d6dfdSNikolay Borisov 		btrfs_warn(root->fs_info,
4789ec7d6dfdSNikolay Borisov 			   "the objectid of root %llu reaches its highest value",
4790ec7d6dfdSNikolay Borisov 			   root->root_key.objectid);
4791ec7d6dfdSNikolay Borisov 		ret = -ENOSPC;
4792ec7d6dfdSNikolay Borisov 		goto out;
4793ec7d6dfdSNikolay Borisov 	}
4794ec7d6dfdSNikolay Borisov 
479523125104SNikolay Borisov 	*objectid = root->free_objectid++;
4796ec7d6dfdSNikolay Borisov 	ret = 0;
4797ec7d6dfdSNikolay Borisov out:
4798ec7d6dfdSNikolay Borisov 	mutex_unlock(&root->objectid_mutex);
4799ec7d6dfdSNikolay Borisov 	return ret;
4800ec7d6dfdSNikolay Borisov }
4801