xref: /openbmc/linux/fs/btrfs/disk-io.c (revision afba2bc0)
1c1d7c514SDavid Sterba // SPDX-License-Identifier: GPL-2.0
26cbd5570SChris Mason /*
36cbd5570SChris Mason  * Copyright (C) 2007 Oracle.  All rights reserved.
46cbd5570SChris Mason  */
56cbd5570SChris Mason 
6e20d96d6SChris Mason #include <linux/fs.h>
7d98237b3SChris Mason #include <linux/blkdev.h>
80f7d52f4SChris Mason #include <linux/radix-tree.h>
935b7e476SChris Mason #include <linux/writeback.h>
10ce9adaa5SChris Mason #include <linux/workqueue.h>
11a74a4b97SChris Mason #include <linux/kthread.h>
125a0e3ad6STejun Heo #include <linux/slab.h>
13784b4e29SChris Mason #include <linux/migrate.h>
147a36ddecSDavid Sterba #include <linux/ratelimit.h>
156463fe58SStefan Behrens #include <linux/uuid.h>
16803b2f54SStefan Behrens #include <linux/semaphore.h>
17540adea3SMasami Hiramatsu #include <linux/error-injection.h>
189678c543SNikolay Borisov #include <linux/crc32c.h>
19b89f6d1fSFilipe Manana #include <linux/sched/mm.h>
207e75bf3fSDavid Sterba #include <asm/unaligned.h>
216d97c6e3SJohannes Thumshirn #include <crypto/hash.h>
22eb60ceacSChris Mason #include "ctree.h"
23eb60ceacSChris Mason #include "disk-io.h"
24e089f05cSChris Mason #include "transaction.h"
250f7d52f4SChris Mason #include "btrfs_inode.h"
260b86a832SChris Mason #include "volumes.h"
27db94535dSChris Mason #include "print-tree.h"
28925baeddSChris Mason #include "locking.h"
29e02119d5SChris Mason #include "tree-log.h"
30fa9c0d79SChris Mason #include "free-space-cache.h"
3170f6d82eSOmar Sandoval #include "free-space-tree.h"
3221adbd5cSStefan Behrens #include "check-integrity.h"
33606686eeSJosef Bacik #include "rcu-string.h"
348dabb742SStefan Behrens #include "dev-replace.h"
3553b381b3SDavid Woodhouse #include "raid56.h"
365ac1d209SJeff Mahoney #include "sysfs.h"
37fcebe456SJosef Bacik #include "qgroup.h"
38ebb8765bSAnand Jain #include "compression.h"
39557ea5ddSQu Wenruo #include "tree-checker.h"
40fd708b81SJosef Bacik #include "ref-verify.h"
41aac0023cSJosef Bacik #include "block-group.h"
42b0643e59SDennis Zhou #include "discard.h"
43f603bb94SNikolay Borisov #include "space-info.h"
44b70f5097SNaohiro Aota #include "zoned.h"
45139e8cd3SQu Wenruo #include "subpage.h"
46eb60ceacSChris Mason 
47319e4d06SQu Wenruo #define BTRFS_SUPER_FLAG_SUPP	(BTRFS_HEADER_FLAG_WRITTEN |\
48319e4d06SQu Wenruo 				 BTRFS_HEADER_FLAG_RELOC |\
49319e4d06SQu Wenruo 				 BTRFS_SUPER_FLAG_ERROR |\
50319e4d06SQu Wenruo 				 BTRFS_SUPER_FLAG_SEEDING |\
51e2731e55SAnand Jain 				 BTRFS_SUPER_FLAG_METADUMP |\
52e2731e55SAnand Jain 				 BTRFS_SUPER_FLAG_METADUMP_V2)
53319e4d06SQu Wenruo 
548b712842SChris Mason static void end_workqueue_fn(struct btrfs_work *work);
55143bede5SJeff Mahoney static void btrfs_destroy_ordered_extents(struct btrfs_root *root);
56acce952bSliubo static int btrfs_destroy_delayed_refs(struct btrfs_transaction *trans,
572ff7e61eSJeff Mahoney 				      struct btrfs_fs_info *fs_info);
58143bede5SJeff Mahoney static void btrfs_destroy_delalloc_inodes(struct btrfs_root *root);
592ff7e61eSJeff Mahoney static int btrfs_destroy_marked_extents(struct btrfs_fs_info *fs_info,
60acce952bSliubo 					struct extent_io_tree *dirty_pages,
61acce952bSliubo 					int mark);
622ff7e61eSJeff Mahoney static int btrfs_destroy_pinned_extent(struct btrfs_fs_info *fs_info,
63acce952bSliubo 				       struct extent_io_tree *pinned_extents);
642ff7e61eSJeff Mahoney static int btrfs_cleanup_transaction(struct btrfs_fs_info *fs_info);
652ff7e61eSJeff Mahoney static void btrfs_error_commit_super(struct btrfs_fs_info *fs_info);
66ce9adaa5SChris Mason 
67d352ac68SChris Mason /*
6897eb6b69SDavid Sterba  * btrfs_end_io_wq structs are used to do processing in task context when an IO
6997eb6b69SDavid Sterba  * is complete.  This is used during reads to verify checksums, and it is used
70d352ac68SChris Mason  * by writes to insert metadata for new file extents after IO is complete.
71d352ac68SChris Mason  */
7297eb6b69SDavid Sterba struct btrfs_end_io_wq {
73ce9adaa5SChris Mason 	struct bio *bio;
74ce9adaa5SChris Mason 	bio_end_io_t *end_io;
75ce9adaa5SChris Mason 	void *private;
76ce9adaa5SChris Mason 	struct btrfs_fs_info *info;
774e4cbee9SChristoph Hellwig 	blk_status_t status;
78bfebd8b5SDavid Sterba 	enum btrfs_wq_endio_type metadata;
798b712842SChris Mason 	struct btrfs_work work;
80ce9adaa5SChris Mason };
810da5468fSChris Mason 
8297eb6b69SDavid Sterba static struct kmem_cache *btrfs_end_io_wq_cache;
8397eb6b69SDavid Sterba 
8497eb6b69SDavid Sterba int __init btrfs_end_io_wq_init(void)
8597eb6b69SDavid Sterba {
8697eb6b69SDavid Sterba 	btrfs_end_io_wq_cache = kmem_cache_create("btrfs_end_io_wq",
8797eb6b69SDavid Sterba 					sizeof(struct btrfs_end_io_wq),
8897eb6b69SDavid Sterba 					0,
89fba4b697SNikolay Borisov 					SLAB_MEM_SPREAD,
9097eb6b69SDavid Sterba 					NULL);
9197eb6b69SDavid Sterba 	if (!btrfs_end_io_wq_cache)
9297eb6b69SDavid Sterba 		return -ENOMEM;
9397eb6b69SDavid Sterba 	return 0;
9497eb6b69SDavid Sterba }
9597eb6b69SDavid Sterba 
96e67c718bSDavid Sterba void __cold btrfs_end_io_wq_exit(void)
9797eb6b69SDavid Sterba {
9897eb6b69SDavid Sterba 	kmem_cache_destroy(btrfs_end_io_wq_cache);
9997eb6b69SDavid Sterba }
10097eb6b69SDavid Sterba 
101141386e1SJosef Bacik static void btrfs_free_csum_hash(struct btrfs_fs_info *fs_info)
102141386e1SJosef Bacik {
103141386e1SJosef Bacik 	if (fs_info->csum_shash)
104141386e1SJosef Bacik 		crypto_free_shash(fs_info->csum_shash);
105141386e1SJosef Bacik }
106141386e1SJosef Bacik 
107d352ac68SChris Mason /*
108d352ac68SChris Mason  * async submit bios are used to offload expensive checksumming
109d352ac68SChris Mason  * onto the worker threads.  They checksum file and metadata bios
110d352ac68SChris Mason  * just before they are sent down the IO stack.
111d352ac68SChris Mason  */
11244b8bd7eSChris Mason struct async_submit_bio {
1138896a08dSQu Wenruo 	struct inode *inode;
11444b8bd7eSChris Mason 	struct bio *bio;
115a758781dSDavid Sterba 	extent_submit_bio_start_t *submit_bio_start;
11644b8bd7eSChris Mason 	int mirror_num;
1171941b64bSQu Wenruo 
1181941b64bSQu Wenruo 	/* Optional parameter for submit_bio_start used by direct io */
1191941b64bSQu Wenruo 	u64 dio_file_offset;
1208b712842SChris Mason 	struct btrfs_work work;
1214e4cbee9SChristoph Hellwig 	blk_status_t status;
12244b8bd7eSChris Mason };
12344b8bd7eSChris Mason 
12485d4e461SChris Mason /*
12585d4e461SChris Mason  * Lockdep class keys for extent_buffer->lock's in this root.  For a given
12685d4e461SChris Mason  * eb, the lockdep key is determined by the btrfs_root it belongs to and
12785d4e461SChris Mason  * the level the eb occupies in the tree.
1284008c04aSChris Mason  *
12985d4e461SChris Mason  * Different roots are used for different purposes and may nest inside each
13085d4e461SChris Mason  * other and they require separate keysets.  As lockdep keys should be
13185d4e461SChris Mason  * static, assign keysets according to the purpose of the root as indicated
1324fd786e6SMisono Tomohiro  * by btrfs_root->root_key.objectid.  This ensures that all special purpose
1334fd786e6SMisono Tomohiro  * roots have separate keysets.
1344008c04aSChris Mason  *
13585d4e461SChris Mason  * Lock-nesting across peer nodes is always done with the immediate parent
13685d4e461SChris Mason  * node locked thus preventing deadlock.  As lockdep doesn't know this, use
13785d4e461SChris Mason  * subclass to avoid triggering lockdep warning in such cases.
1384008c04aSChris Mason  *
13985d4e461SChris Mason  * The key is set by the readpage_end_io_hook after the buffer has passed
14085d4e461SChris Mason  * csum validation but before the pages are unlocked.  It is also set by
14185d4e461SChris Mason  * btrfs_init_new_buffer on freshly allocated blocks.
14285d4e461SChris Mason  *
14385d4e461SChris Mason  * We also add a check to make sure the highest level of the tree is the
14485d4e461SChris Mason  * same as our lockdep setup here.  If BTRFS_MAX_LEVEL changes, this code
14585d4e461SChris Mason  * needs update as well.
1464008c04aSChris Mason  */
1474008c04aSChris Mason #ifdef CONFIG_DEBUG_LOCK_ALLOC
1484008c04aSChris Mason # if BTRFS_MAX_LEVEL != 8
1494008c04aSChris Mason #  error
1504008c04aSChris Mason # endif
15185d4e461SChris Mason 
152ab1405aaSDavid Sterba #define DEFINE_LEVEL(stem, level)					\
153ab1405aaSDavid Sterba 	.names[level] = "btrfs-" stem "-0" #level,
154ab1405aaSDavid Sterba 
155ab1405aaSDavid Sterba #define DEFINE_NAME(stem)						\
156ab1405aaSDavid Sterba 	DEFINE_LEVEL(stem, 0)						\
157ab1405aaSDavid Sterba 	DEFINE_LEVEL(stem, 1)						\
158ab1405aaSDavid Sterba 	DEFINE_LEVEL(stem, 2)						\
159ab1405aaSDavid Sterba 	DEFINE_LEVEL(stem, 3)						\
160ab1405aaSDavid Sterba 	DEFINE_LEVEL(stem, 4)						\
161ab1405aaSDavid Sterba 	DEFINE_LEVEL(stem, 5)						\
162ab1405aaSDavid Sterba 	DEFINE_LEVEL(stem, 6)						\
163ab1405aaSDavid Sterba 	DEFINE_LEVEL(stem, 7)
164ab1405aaSDavid Sterba 
16585d4e461SChris Mason static struct btrfs_lockdep_keyset {
16685d4e461SChris Mason 	u64			id;		/* root objectid */
167ab1405aaSDavid Sterba 	/* Longest entry: btrfs-free-space-00 */
168387824afSDavid Sterba 	char			names[BTRFS_MAX_LEVEL][20];
169387824afSDavid Sterba 	struct lock_class_key	keys[BTRFS_MAX_LEVEL];
17085d4e461SChris Mason } btrfs_lockdep_keysets[] = {
171ab1405aaSDavid Sterba 	{ .id = BTRFS_ROOT_TREE_OBJECTID,	DEFINE_NAME("root")	},
172ab1405aaSDavid Sterba 	{ .id = BTRFS_EXTENT_TREE_OBJECTID,	DEFINE_NAME("extent")	},
173ab1405aaSDavid Sterba 	{ .id = BTRFS_CHUNK_TREE_OBJECTID,	DEFINE_NAME("chunk")	},
174ab1405aaSDavid Sterba 	{ .id = BTRFS_DEV_TREE_OBJECTID,	DEFINE_NAME("dev")	},
175ab1405aaSDavid Sterba 	{ .id = BTRFS_CSUM_TREE_OBJECTID,	DEFINE_NAME("csum")	},
176ab1405aaSDavid Sterba 	{ .id = BTRFS_QUOTA_TREE_OBJECTID,	DEFINE_NAME("quota")	},
177ab1405aaSDavid Sterba 	{ .id = BTRFS_TREE_LOG_OBJECTID,	DEFINE_NAME("log")	},
178ab1405aaSDavid Sterba 	{ .id = BTRFS_TREE_RELOC_OBJECTID,	DEFINE_NAME("treloc")	},
179ab1405aaSDavid Sterba 	{ .id = BTRFS_DATA_RELOC_TREE_OBJECTID,	DEFINE_NAME("dreloc")	},
180ab1405aaSDavid Sterba 	{ .id = BTRFS_UUID_TREE_OBJECTID,	DEFINE_NAME("uuid")	},
181ab1405aaSDavid Sterba 	{ .id = BTRFS_FREE_SPACE_TREE_OBJECTID,	DEFINE_NAME("free-space") },
182ab1405aaSDavid Sterba 	{ .id = 0,				DEFINE_NAME("tree")	},
1834008c04aSChris Mason };
18485d4e461SChris Mason 
185ab1405aaSDavid Sterba #undef DEFINE_LEVEL
186ab1405aaSDavid Sterba #undef DEFINE_NAME
18785d4e461SChris Mason 
18885d4e461SChris Mason void btrfs_set_buffer_lockdep_class(u64 objectid, struct extent_buffer *eb,
18985d4e461SChris Mason 				    int level)
19085d4e461SChris Mason {
19185d4e461SChris Mason 	struct btrfs_lockdep_keyset *ks;
19285d4e461SChris Mason 
19385d4e461SChris Mason 	BUG_ON(level >= ARRAY_SIZE(ks->keys));
19485d4e461SChris Mason 
19585d4e461SChris Mason 	/* find the matching keyset, id 0 is the default entry */
19685d4e461SChris Mason 	for (ks = btrfs_lockdep_keysets; ks->id; ks++)
19785d4e461SChris Mason 		if (ks->id == objectid)
19885d4e461SChris Mason 			break;
19985d4e461SChris Mason 
20085d4e461SChris Mason 	lockdep_set_class_and_name(&eb->lock,
20185d4e461SChris Mason 				   &ks->keys[level], ks->names[level]);
20285d4e461SChris Mason }
20385d4e461SChris Mason 
2044008c04aSChris Mason #endif
2054008c04aSChris Mason 
206d352ac68SChris Mason /*
2072996e1f8SJohannes Thumshirn  * Compute the csum of a btree block and store the result to provided buffer.
208d352ac68SChris Mason  */
209c67b3892SDavid Sterba static void csum_tree_block(struct extent_buffer *buf, u8 *result)
21019c00ddcSChris Mason {
211d5178578SJohannes Thumshirn 	struct btrfs_fs_info *fs_info = buf->fs_info;
2127280305eSDavid Sterba 	const int num_pages = num_extent_pages(buf);
213a26663e7SQu Wenruo 	const int first_page_part = min_t(u32, PAGE_SIZE, fs_info->nodesize);
214d5178578SJohannes Thumshirn 	SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
21519c00ddcSChris Mason 	char *kaddr;
216e9be5a30SDavid Sterba 	int i;
217d5178578SJohannes Thumshirn 
218d5178578SJohannes Thumshirn 	shash->tfm = fs_info->csum_shash;
219d5178578SJohannes Thumshirn 	crypto_shash_init(shash);
220a26663e7SQu Wenruo 	kaddr = page_address(buf->pages[0]) + offset_in_page(buf->start);
221e9be5a30SDavid Sterba 	crypto_shash_update(shash, kaddr + BTRFS_CSUM_SIZE,
222a26663e7SQu Wenruo 			    first_page_part - BTRFS_CSUM_SIZE);
22319c00ddcSChris Mason 
224e9be5a30SDavid Sterba 	for (i = 1; i < num_pages; i++) {
225e9be5a30SDavid Sterba 		kaddr = page_address(buf->pages[i]);
226e9be5a30SDavid Sterba 		crypto_shash_update(shash, kaddr, PAGE_SIZE);
22719c00ddcSChris Mason 	}
22871a63551SDavid Sterba 	memset(result, 0, BTRFS_CSUM_SIZE);
229d5178578SJohannes Thumshirn 	crypto_shash_final(shash, result);
23019c00ddcSChris Mason }
23119c00ddcSChris Mason 
232d352ac68SChris Mason /*
233d352ac68SChris Mason  * we can't consider a given block up to date unless the transid of the
234d352ac68SChris Mason  * block matches the transid in the parent node's pointer.  This is how we
235d352ac68SChris Mason  * detect blocks that either didn't get written at all or got written
236d352ac68SChris Mason  * in the wrong place.
237d352ac68SChris Mason  */
2381259ab75SChris Mason static int verify_parent_transid(struct extent_io_tree *io_tree,
239b9fab919SChris Mason 				 struct extent_buffer *eb, u64 parent_transid,
240b9fab919SChris Mason 				 int atomic)
2411259ab75SChris Mason {
2422ac55d41SJosef Bacik 	struct extent_state *cached_state = NULL;
2431259ab75SChris Mason 	int ret;
2441259ab75SChris Mason 
2451259ab75SChris Mason 	if (!parent_transid || btrfs_header_generation(eb) == parent_transid)
2461259ab75SChris Mason 		return 0;
2471259ab75SChris Mason 
248b9fab919SChris Mason 	if (atomic)
249b9fab919SChris Mason 		return -EAGAIN;
250b9fab919SChris Mason 
2512ac55d41SJosef Bacik 	lock_extent_bits(io_tree, eb->start, eb->start + eb->len - 1,
252ff13db41SDavid Sterba 			 &cached_state);
2530b32f4bbSJosef Bacik 	if (extent_buffer_uptodate(eb) &&
2541259ab75SChris Mason 	    btrfs_header_generation(eb) == parent_transid) {
2551259ab75SChris Mason 		ret = 0;
2561259ab75SChris Mason 		goto out;
2571259ab75SChris Mason 	}
25894647322SDavid Sterba 	btrfs_err_rl(eb->fs_info,
25994647322SDavid Sterba 		"parent transid verify failed on %llu wanted %llu found %llu",
26094647322SDavid Sterba 			eb->start,
26129549aecSWang Shilong 			parent_transid, btrfs_header_generation(eb));
2621259ab75SChris Mason 	ret = 1;
2630b32f4bbSJosef Bacik 	clear_extent_buffer_uptodate(eb);
26433958dc6SChris Mason out:
2652ac55d41SJosef Bacik 	unlock_extent_cached(io_tree, eb->start, eb->start + eb->len - 1,
266e43bbe5eSDavid Sterba 			     &cached_state);
2671259ab75SChris Mason 	return ret;
2681259ab75SChris Mason }
2691259ab75SChris Mason 
270e7e16f48SJohannes Thumshirn static bool btrfs_supported_super_csum(u16 csum_type)
271e7e16f48SJohannes Thumshirn {
272e7e16f48SJohannes Thumshirn 	switch (csum_type) {
273e7e16f48SJohannes Thumshirn 	case BTRFS_CSUM_TYPE_CRC32:
2743951e7f0SJohannes Thumshirn 	case BTRFS_CSUM_TYPE_XXHASH:
2753831bf00SJohannes Thumshirn 	case BTRFS_CSUM_TYPE_SHA256:
276352ae07bSDavid Sterba 	case BTRFS_CSUM_TYPE_BLAKE2:
277e7e16f48SJohannes Thumshirn 		return true;
278e7e16f48SJohannes Thumshirn 	default:
279e7e16f48SJohannes Thumshirn 		return false;
280e7e16f48SJohannes Thumshirn 	}
281e7e16f48SJohannes Thumshirn }
282e7e16f48SJohannes Thumshirn 
283d352ac68SChris Mason /*
2841104a885SDavid Sterba  * Return 0 if the superblock checksum type matches the checksum value of that
2851104a885SDavid Sterba  * algorithm. Pass the raw disk superblock data.
2861104a885SDavid Sterba  */
287ab8d0fc4SJeff Mahoney static int btrfs_check_super_csum(struct btrfs_fs_info *fs_info,
288ab8d0fc4SJeff Mahoney 				  char *raw_disk_sb)
2891104a885SDavid Sterba {
2901104a885SDavid Sterba 	struct btrfs_super_block *disk_sb =
2911104a885SDavid Sterba 		(struct btrfs_super_block *)raw_disk_sb;
29251bce6c9SJohannes Thumshirn 	char result[BTRFS_CSUM_SIZE];
293d5178578SJohannes Thumshirn 	SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
294d5178578SJohannes Thumshirn 
295d5178578SJohannes Thumshirn 	shash->tfm = fs_info->csum_shash;
2961104a885SDavid Sterba 
2971104a885SDavid Sterba 	/*
2981104a885SDavid Sterba 	 * The super_block structure does not span the whole
29951bce6c9SJohannes Thumshirn 	 * BTRFS_SUPER_INFO_SIZE range, we expect that the unused space is
30051bce6c9SJohannes Thumshirn 	 * filled with zeros and is included in the checksum.
3011104a885SDavid Sterba 	 */
302fd08001fSEric Biggers 	crypto_shash_digest(shash, raw_disk_sb + BTRFS_CSUM_SIZE,
303fd08001fSEric Biggers 			    BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE, result);
3041104a885SDavid Sterba 
30555fc29beSDavid Sterba 	if (memcmp(disk_sb->csum, result, fs_info->csum_size))
306e7e16f48SJohannes Thumshirn 		return 1;
3071104a885SDavid Sterba 
308e7e16f48SJohannes Thumshirn 	return 0;
3091104a885SDavid Sterba }
3101104a885SDavid Sterba 
311e064d5e9SDavid Sterba int btrfs_verify_level_key(struct extent_buffer *eb, int level,
312ff76a864SLiu Bo 			   struct btrfs_key *first_key, u64 parent_transid)
313581c1760SQu Wenruo {
314e064d5e9SDavid Sterba 	struct btrfs_fs_info *fs_info = eb->fs_info;
315581c1760SQu Wenruo 	int found_level;
316581c1760SQu Wenruo 	struct btrfs_key found_key;
317581c1760SQu Wenruo 	int ret;
318581c1760SQu Wenruo 
319581c1760SQu Wenruo 	found_level = btrfs_header_level(eb);
320581c1760SQu Wenruo 	if (found_level != level) {
32163489055SQu Wenruo 		WARN(IS_ENABLED(CONFIG_BTRFS_DEBUG),
32263489055SQu Wenruo 		     KERN_ERR "BTRFS: tree level check failed\n");
323581c1760SQu Wenruo 		btrfs_err(fs_info,
324581c1760SQu Wenruo "tree level mismatch detected, bytenr=%llu level expected=%u has=%u",
325581c1760SQu Wenruo 			  eb->start, level, found_level);
326581c1760SQu Wenruo 		return -EIO;
327581c1760SQu Wenruo 	}
328581c1760SQu Wenruo 
329581c1760SQu Wenruo 	if (!first_key)
330581c1760SQu Wenruo 		return 0;
331581c1760SQu Wenruo 
3325d41be6fSQu Wenruo 	/*
3335d41be6fSQu Wenruo 	 * For live tree block (new tree blocks in current transaction),
3345d41be6fSQu Wenruo 	 * we need proper lock context to avoid race, which is impossible here.
3355d41be6fSQu Wenruo 	 * So we only checks tree blocks which is read from disk, whose
3365d41be6fSQu Wenruo 	 * generation <= fs_info->last_trans_committed.
3375d41be6fSQu Wenruo 	 */
3385d41be6fSQu Wenruo 	if (btrfs_header_generation(eb) > fs_info->last_trans_committed)
3395d41be6fSQu Wenruo 		return 0;
34062fdaa52SQu Wenruo 
34162fdaa52SQu Wenruo 	/* We have @first_key, so this @eb must have at least one item */
34262fdaa52SQu Wenruo 	if (btrfs_header_nritems(eb) == 0) {
34362fdaa52SQu Wenruo 		btrfs_err(fs_info,
34462fdaa52SQu Wenruo 		"invalid tree nritems, bytenr=%llu nritems=0 expect >0",
34562fdaa52SQu Wenruo 			  eb->start);
34662fdaa52SQu Wenruo 		WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
34762fdaa52SQu Wenruo 		return -EUCLEAN;
34862fdaa52SQu Wenruo 	}
34962fdaa52SQu Wenruo 
350581c1760SQu Wenruo 	if (found_level)
351581c1760SQu Wenruo 		btrfs_node_key_to_cpu(eb, &found_key, 0);
352581c1760SQu Wenruo 	else
353581c1760SQu Wenruo 		btrfs_item_key_to_cpu(eb, &found_key, 0);
354581c1760SQu Wenruo 	ret = btrfs_comp_cpu_keys(first_key, &found_key);
355581c1760SQu Wenruo 
356581c1760SQu Wenruo 	if (ret) {
35763489055SQu Wenruo 		WARN(IS_ENABLED(CONFIG_BTRFS_DEBUG),
35863489055SQu Wenruo 		     KERN_ERR "BTRFS: tree first key check failed\n");
359581c1760SQu Wenruo 		btrfs_err(fs_info,
360ff76a864SLiu Bo "tree first key mismatch detected, bytenr=%llu parent_transid=%llu key expected=(%llu,%u,%llu) has=(%llu,%u,%llu)",
361ff76a864SLiu Bo 			  eb->start, parent_transid, first_key->objectid,
362ff76a864SLiu Bo 			  first_key->type, first_key->offset,
363ff76a864SLiu Bo 			  found_key.objectid, found_key.type,
364ff76a864SLiu Bo 			  found_key.offset);
365581c1760SQu Wenruo 	}
366581c1760SQu Wenruo 	return ret;
367581c1760SQu Wenruo }
368581c1760SQu Wenruo 
3691104a885SDavid Sterba /*
370d352ac68SChris Mason  * helper to read a given tree block, doing retries as required when
371d352ac68SChris Mason  * the checksums don't match and we have alternate mirrors to try.
372581c1760SQu Wenruo  *
373581c1760SQu Wenruo  * @parent_transid:	expected transid, skip check if 0
374581c1760SQu Wenruo  * @level:		expected level, mandatory check
375581c1760SQu Wenruo  * @first_key:		expected key of first slot, skip check if NULL
376d352ac68SChris Mason  */
3775ab12d1fSDavid Sterba static int btree_read_extent_buffer_pages(struct extent_buffer *eb,
378581c1760SQu Wenruo 					  u64 parent_transid, int level,
379581c1760SQu Wenruo 					  struct btrfs_key *first_key)
380f188591eSChris Mason {
3815ab12d1fSDavid Sterba 	struct btrfs_fs_info *fs_info = eb->fs_info;
382f188591eSChris Mason 	struct extent_io_tree *io_tree;
383ea466794SJosef Bacik 	int failed = 0;
384f188591eSChris Mason 	int ret;
385f188591eSChris Mason 	int num_copies = 0;
386f188591eSChris Mason 	int mirror_num = 0;
387ea466794SJosef Bacik 	int failed_mirror = 0;
388f188591eSChris Mason 
3890b246afaSJeff Mahoney 	io_tree = &BTRFS_I(fs_info->btree_inode)->io_tree;
390f188591eSChris Mason 	while (1) {
391f8397d69SNikolay Borisov 		clear_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags);
392c2ccfbc6SNikolay Borisov 		ret = read_extent_buffer_pages(eb, WAIT_COMPLETE, mirror_num);
393256dd1bbSStefan Behrens 		if (!ret) {
394581c1760SQu Wenruo 			if (verify_parent_transid(io_tree, eb,
395b9fab919SChris Mason 						   parent_transid, 0))
396256dd1bbSStefan Behrens 				ret = -EIO;
397e064d5e9SDavid Sterba 			else if (btrfs_verify_level_key(eb, level,
398ff76a864SLiu Bo 						first_key, parent_transid))
399581c1760SQu Wenruo 				ret = -EUCLEAN;
400581c1760SQu Wenruo 			else
401581c1760SQu Wenruo 				break;
402256dd1bbSStefan Behrens 		}
403d397712bSChris Mason 
4040b246afaSJeff Mahoney 		num_copies = btrfs_num_copies(fs_info,
405f188591eSChris Mason 					      eb->start, eb->len);
4064235298eSChris Mason 		if (num_copies == 1)
407ea466794SJosef Bacik 			break;
4084235298eSChris Mason 
4095cf1ab56SJosef Bacik 		if (!failed_mirror) {
4105cf1ab56SJosef Bacik 			failed = 1;
4115cf1ab56SJosef Bacik 			failed_mirror = eb->read_mirror;
4125cf1ab56SJosef Bacik 		}
4135cf1ab56SJosef Bacik 
414f188591eSChris Mason 		mirror_num++;
415ea466794SJosef Bacik 		if (mirror_num == failed_mirror)
416ea466794SJosef Bacik 			mirror_num++;
417ea466794SJosef Bacik 
4184235298eSChris Mason 		if (mirror_num > num_copies)
419ea466794SJosef Bacik 			break;
420f188591eSChris Mason 	}
421ea466794SJosef Bacik 
422c0901581SStefan Behrens 	if (failed && !ret && failed_mirror)
42320a1fbf9SDavid Sterba 		btrfs_repair_eb_io_failure(eb, failed_mirror);
424ea466794SJosef Bacik 
425ea466794SJosef Bacik 	return ret;
426f188591eSChris Mason }
42719c00ddcSChris Mason 
428eca0f6f6SQu Wenruo static int csum_one_extent_buffer(struct extent_buffer *eb)
429eca0f6f6SQu Wenruo {
430eca0f6f6SQu Wenruo 	struct btrfs_fs_info *fs_info = eb->fs_info;
431eca0f6f6SQu Wenruo 	u8 result[BTRFS_CSUM_SIZE];
432eca0f6f6SQu Wenruo 	int ret;
433eca0f6f6SQu Wenruo 
434eca0f6f6SQu Wenruo 	ASSERT(memcmp_extent_buffer(eb, fs_info->fs_devices->metadata_uuid,
435eca0f6f6SQu Wenruo 				    offsetof(struct btrfs_header, fsid),
436eca0f6f6SQu Wenruo 				    BTRFS_FSID_SIZE) == 0);
437eca0f6f6SQu Wenruo 	csum_tree_block(eb, result);
438eca0f6f6SQu Wenruo 
439eca0f6f6SQu Wenruo 	if (btrfs_header_level(eb))
440eca0f6f6SQu Wenruo 		ret = btrfs_check_node(eb);
441eca0f6f6SQu Wenruo 	else
442eca0f6f6SQu Wenruo 		ret = btrfs_check_leaf_full(eb);
443eca0f6f6SQu Wenruo 
444eca0f6f6SQu Wenruo 	if (ret < 0) {
445eca0f6f6SQu Wenruo 		btrfs_print_tree(eb, 0);
446eca0f6f6SQu Wenruo 		btrfs_err(fs_info,
447eca0f6f6SQu Wenruo 			"block=%llu write time tree block corruption detected",
448eca0f6f6SQu Wenruo 			eb->start);
449eca0f6f6SQu Wenruo 		WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
450eca0f6f6SQu Wenruo 		return ret;
451eca0f6f6SQu Wenruo 	}
452eca0f6f6SQu Wenruo 	write_extent_buffer(eb, result, 0, fs_info->csum_size);
453eca0f6f6SQu Wenruo 
454eca0f6f6SQu Wenruo 	return 0;
455eca0f6f6SQu Wenruo }
456eca0f6f6SQu Wenruo 
457eca0f6f6SQu Wenruo /* Checksum all dirty extent buffers in one bio_vec */
458eca0f6f6SQu Wenruo static int csum_dirty_subpage_buffers(struct btrfs_fs_info *fs_info,
459eca0f6f6SQu Wenruo 				      struct bio_vec *bvec)
460eca0f6f6SQu Wenruo {
461eca0f6f6SQu Wenruo 	struct page *page = bvec->bv_page;
462eca0f6f6SQu Wenruo 	u64 bvec_start = page_offset(page) + bvec->bv_offset;
463eca0f6f6SQu Wenruo 	u64 cur;
464eca0f6f6SQu Wenruo 	int ret = 0;
465eca0f6f6SQu Wenruo 
466eca0f6f6SQu Wenruo 	for (cur = bvec_start; cur < bvec_start + bvec->bv_len;
467eca0f6f6SQu Wenruo 	     cur += fs_info->nodesize) {
468eca0f6f6SQu Wenruo 		struct extent_buffer *eb;
469eca0f6f6SQu Wenruo 		bool uptodate;
470eca0f6f6SQu Wenruo 
471eca0f6f6SQu Wenruo 		eb = find_extent_buffer(fs_info, cur);
472eca0f6f6SQu Wenruo 		uptodate = btrfs_subpage_test_uptodate(fs_info, page, cur,
473eca0f6f6SQu Wenruo 						       fs_info->nodesize);
474eca0f6f6SQu Wenruo 
475eca0f6f6SQu Wenruo 		/* A dirty eb shouldn't disappear from buffer_radix */
476eca0f6f6SQu Wenruo 		if (WARN_ON(!eb))
477eca0f6f6SQu Wenruo 			return -EUCLEAN;
478eca0f6f6SQu Wenruo 
479eca0f6f6SQu Wenruo 		if (WARN_ON(cur != btrfs_header_bytenr(eb))) {
480eca0f6f6SQu Wenruo 			free_extent_buffer(eb);
481eca0f6f6SQu Wenruo 			return -EUCLEAN;
482eca0f6f6SQu Wenruo 		}
483eca0f6f6SQu Wenruo 		if (WARN_ON(!uptodate)) {
484eca0f6f6SQu Wenruo 			free_extent_buffer(eb);
485eca0f6f6SQu Wenruo 			return -EUCLEAN;
486eca0f6f6SQu Wenruo 		}
487eca0f6f6SQu Wenruo 
488eca0f6f6SQu Wenruo 		ret = csum_one_extent_buffer(eb);
489eca0f6f6SQu Wenruo 		free_extent_buffer(eb);
490eca0f6f6SQu Wenruo 		if (ret < 0)
491eca0f6f6SQu Wenruo 			return ret;
492eca0f6f6SQu Wenruo 	}
493eca0f6f6SQu Wenruo 	return ret;
494eca0f6f6SQu Wenruo }
495eca0f6f6SQu Wenruo 
496d352ac68SChris Mason /*
497ac303b69SQu Wenruo  * Checksum a dirty tree block before IO.  This has extra checks to make sure
498ac303b69SQu Wenruo  * we only fill in the checksum field in the first page of a multi-page block.
499ac303b69SQu Wenruo  * For subpage extent buffers we need bvec to also read the offset in the page.
500d352ac68SChris Mason  */
501ac303b69SQu Wenruo static int csum_dirty_buffer(struct btrfs_fs_info *fs_info, struct bio_vec *bvec)
50219c00ddcSChris Mason {
503ac303b69SQu Wenruo 	struct page *page = bvec->bv_page;
5044eee4fa4SMiao Xie 	u64 start = page_offset(page);
50519c00ddcSChris Mason 	u64 found_start;
50619c00ddcSChris Mason 	struct extent_buffer *eb;
507eca0f6f6SQu Wenruo 
508eca0f6f6SQu Wenruo 	if (fs_info->sectorsize < PAGE_SIZE)
509eca0f6f6SQu Wenruo 		return csum_dirty_subpage_buffers(fs_info, bvec);
510f188591eSChris Mason 
5114f2de97aSJosef Bacik 	eb = (struct extent_buffer *)page->private;
5124f2de97aSJosef Bacik 	if (page != eb->pages[0])
5134f2de97aSJosef Bacik 		return 0;
5140f805531SAlex Lyakas 
51519c00ddcSChris Mason 	found_start = btrfs_header_bytenr(eb);
516d3575156SNaohiro Aota 
517d3575156SNaohiro Aota 	if (test_bit(EXTENT_BUFFER_NO_CHECK, &eb->bflags)) {
518d3575156SNaohiro Aota 		WARN_ON(found_start != 0);
519d3575156SNaohiro Aota 		return 0;
520d3575156SNaohiro Aota 	}
521d3575156SNaohiro Aota 
5220f805531SAlex Lyakas 	/*
5230f805531SAlex Lyakas 	 * Please do not consolidate these warnings into a single if.
5240f805531SAlex Lyakas 	 * It is useful to know what went wrong.
5250f805531SAlex Lyakas 	 */
5260f805531SAlex Lyakas 	if (WARN_ON(found_start != start))
5270f805531SAlex Lyakas 		return -EUCLEAN;
5280f805531SAlex Lyakas 	if (WARN_ON(!PageUptodate(page)))
5290f805531SAlex Lyakas 		return -EUCLEAN;
5300f805531SAlex Lyakas 
531eca0f6f6SQu Wenruo 	return csum_one_extent_buffer(eb);
53219c00ddcSChris Mason }
53319c00ddcSChris Mason 
534b0c9b3b0SDavid Sterba static int check_tree_block_fsid(struct extent_buffer *eb)
5352b82032cSYan Zheng {
536b0c9b3b0SDavid Sterba 	struct btrfs_fs_info *fs_info = eb->fs_info;
537944d3f9fSNikolay Borisov 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices, *seed_devs;
53844880fdcSAnand Jain 	u8 fsid[BTRFS_FSID_SIZE];
539944d3f9fSNikolay Borisov 	u8 *metadata_uuid;
5402b82032cSYan Zheng 
5419a8658e3SDavid Sterba 	read_extent_buffer(eb, fsid, offsetof(struct btrfs_header, fsid),
5429a8658e3SDavid Sterba 			   BTRFS_FSID_SIZE);
5437239ff4bSNikolay Borisov 	/*
544944d3f9fSNikolay Borisov 	 * Checking the incompat flag is only valid for the current fs. For
545944d3f9fSNikolay Borisov 	 * seed devices it's forbidden to have their uuid changed so reading
546944d3f9fSNikolay Borisov 	 * ->fsid in this case is fine
5477239ff4bSNikolay Borisov 	 */
548944d3f9fSNikolay Borisov 	if (btrfs_fs_incompat(fs_info, METADATA_UUID))
5497239ff4bSNikolay Borisov 		metadata_uuid = fs_devices->metadata_uuid;
5507239ff4bSNikolay Borisov 	else
5517239ff4bSNikolay Borisov 		metadata_uuid = fs_devices->fsid;
5527239ff4bSNikolay Borisov 
553944d3f9fSNikolay Borisov 	if (!memcmp(fsid, metadata_uuid, BTRFS_FSID_SIZE))
554944d3f9fSNikolay Borisov 		return 0;
555944d3f9fSNikolay Borisov 
556944d3f9fSNikolay Borisov 	list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list)
557944d3f9fSNikolay Borisov 		if (!memcmp(fsid, seed_devs->fsid, BTRFS_FSID_SIZE))
558944d3f9fSNikolay Borisov 			return 0;
559944d3f9fSNikolay Borisov 
560944d3f9fSNikolay Borisov 	return 1;
5612b82032cSYan Zheng }
5622b82032cSYan Zheng 
56377bf40a2SQu Wenruo /* Do basic extent buffer checks at read time */
56477bf40a2SQu Wenruo static int validate_extent_buffer(struct extent_buffer *eb)
565ce9adaa5SChris Mason {
56677bf40a2SQu Wenruo 	struct btrfs_fs_info *fs_info = eb->fs_info;
567ce9adaa5SChris Mason 	u64 found_start;
56877bf40a2SQu Wenruo 	const u32 csum_size = fs_info->csum_size;
56977bf40a2SQu Wenruo 	u8 found_level;
5702996e1f8SJohannes Thumshirn 	u8 result[BTRFS_CSUM_SIZE];
571dfd29eedSDavid Sterba 	const u8 *header_csum;
57277bf40a2SQu Wenruo 	int ret = 0;
573ea466794SJosef Bacik 
574ce9adaa5SChris Mason 	found_start = btrfs_header_bytenr(eb);
575727011e0SChris Mason 	if (found_start != eb->start) {
576893bf4b1SSu Yue 		btrfs_err_rl(fs_info, "bad tree block start, want %llu have %llu",
577893bf4b1SSu Yue 			     eb->start, found_start);
578f188591eSChris Mason 		ret = -EIO;
57977bf40a2SQu Wenruo 		goto out;
580ce9adaa5SChris Mason 	}
581b0c9b3b0SDavid Sterba 	if (check_tree_block_fsid(eb)) {
58202873e43SZhao Lei 		btrfs_err_rl(fs_info, "bad fsid on block %llu",
58394647322SDavid Sterba 			     eb->start);
5841259ab75SChris Mason 		ret = -EIO;
58577bf40a2SQu Wenruo 		goto out;
5861259ab75SChris Mason 	}
587ce9adaa5SChris Mason 	found_level = btrfs_header_level(eb);
5881c24c3ceSJosef Bacik 	if (found_level >= BTRFS_MAX_LEVEL) {
589893bf4b1SSu Yue 		btrfs_err(fs_info, "bad tree block level %d on %llu",
590893bf4b1SSu Yue 			  (int)btrfs_header_level(eb), eb->start);
5911c24c3ceSJosef Bacik 		ret = -EIO;
59277bf40a2SQu Wenruo 		goto out;
5931c24c3ceSJosef Bacik 	}
594ce9adaa5SChris Mason 
595c67b3892SDavid Sterba 	csum_tree_block(eb, result);
596dfd29eedSDavid Sterba 	header_csum = page_address(eb->pages[0]) +
597dfd29eedSDavid Sterba 		get_eb_offset_in_page(eb, offsetof(struct btrfs_header, csum));
598a826d6dcSJosef Bacik 
599dfd29eedSDavid Sterba 	if (memcmp(result, header_csum, csum_size) != 0) {
6002996e1f8SJohannes Thumshirn 		btrfs_warn_rl(fs_info,
601ff14aa79SDavid Sterba 	"checksum verify failed on %llu wanted " CSUM_FMT " found " CSUM_FMT " level %d",
602ff14aa79SDavid Sterba 			      eb->start,
603dfd29eedSDavid Sterba 			      CSUM_FMT_VALUE(csum_size, header_csum),
60435be8851SJohannes Thumshirn 			      CSUM_FMT_VALUE(csum_size, result),
60535be8851SJohannes Thumshirn 			      btrfs_header_level(eb));
6062996e1f8SJohannes Thumshirn 		ret = -EUCLEAN;
60777bf40a2SQu Wenruo 		goto out;
6082996e1f8SJohannes Thumshirn 	}
6092996e1f8SJohannes Thumshirn 
610a826d6dcSJosef Bacik 	/*
611a826d6dcSJosef Bacik 	 * If this is a leaf block and it is corrupt, set the corrupt bit so
612a826d6dcSJosef Bacik 	 * that we don't try and read the other copies of this block, just
613a826d6dcSJosef Bacik 	 * return -EIO.
614a826d6dcSJosef Bacik 	 */
6151c4360eeSDavid Sterba 	if (found_level == 0 && btrfs_check_leaf_full(eb)) {
616a826d6dcSJosef Bacik 		set_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags);
617a826d6dcSJosef Bacik 		ret = -EIO;
618a826d6dcSJosef Bacik 	}
619ce9adaa5SChris Mason 
620813fd1dcSDavid Sterba 	if (found_level > 0 && btrfs_check_node(eb))
621053ab70fSLiu Bo 		ret = -EIO;
622053ab70fSLiu Bo 
6230b32f4bbSJosef Bacik 	if (!ret)
6240b32f4bbSJosef Bacik 		set_extent_buffer_uptodate(eb);
62575391f0dSQu Wenruo 	else
62675391f0dSQu Wenruo 		btrfs_err(fs_info,
62775391f0dSQu Wenruo 			  "block=%llu read time tree block corruption detected",
62875391f0dSQu Wenruo 			  eb->start);
62977bf40a2SQu Wenruo out:
63077bf40a2SQu Wenruo 	return ret;
63177bf40a2SQu Wenruo }
63277bf40a2SQu Wenruo 
633371cdc07SQu Wenruo static int validate_subpage_buffer(struct page *page, u64 start, u64 end,
634371cdc07SQu Wenruo 				   int mirror)
635371cdc07SQu Wenruo {
636371cdc07SQu Wenruo 	struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
637371cdc07SQu Wenruo 	struct extent_buffer *eb;
638371cdc07SQu Wenruo 	bool reads_done;
639371cdc07SQu Wenruo 	int ret = 0;
640371cdc07SQu Wenruo 
641371cdc07SQu Wenruo 	/*
642371cdc07SQu Wenruo 	 * We don't allow bio merge for subpage metadata read, so we should
643371cdc07SQu Wenruo 	 * only get one eb for each endio hook.
644371cdc07SQu Wenruo 	 */
645371cdc07SQu Wenruo 	ASSERT(end == start + fs_info->nodesize - 1);
646371cdc07SQu Wenruo 	ASSERT(PagePrivate(page));
647371cdc07SQu Wenruo 
648371cdc07SQu Wenruo 	eb = find_extent_buffer(fs_info, start);
649371cdc07SQu Wenruo 	/*
650371cdc07SQu Wenruo 	 * When we are reading one tree block, eb must have been inserted into
651371cdc07SQu Wenruo 	 * the radix tree. If not, something is wrong.
652371cdc07SQu Wenruo 	 */
653371cdc07SQu Wenruo 	ASSERT(eb);
654371cdc07SQu Wenruo 
655371cdc07SQu Wenruo 	reads_done = atomic_dec_and_test(&eb->io_pages);
656371cdc07SQu Wenruo 	/* Subpage read must finish in page read */
657371cdc07SQu Wenruo 	ASSERT(reads_done);
658371cdc07SQu Wenruo 
659371cdc07SQu Wenruo 	eb->read_mirror = mirror;
660371cdc07SQu Wenruo 	if (test_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags)) {
661371cdc07SQu Wenruo 		ret = -EIO;
662371cdc07SQu Wenruo 		goto err;
663371cdc07SQu Wenruo 	}
664371cdc07SQu Wenruo 	ret = validate_extent_buffer(eb);
665371cdc07SQu Wenruo 	if (ret < 0)
666371cdc07SQu Wenruo 		goto err;
667371cdc07SQu Wenruo 
668371cdc07SQu Wenruo 	if (test_and_clear_bit(EXTENT_BUFFER_READAHEAD, &eb->bflags))
669371cdc07SQu Wenruo 		btree_readahead_hook(eb, ret);
670371cdc07SQu Wenruo 
671371cdc07SQu Wenruo 	set_extent_buffer_uptodate(eb);
672371cdc07SQu Wenruo 
673371cdc07SQu Wenruo 	free_extent_buffer(eb);
674371cdc07SQu Wenruo 	return ret;
675371cdc07SQu Wenruo err:
676371cdc07SQu Wenruo 	/*
677371cdc07SQu Wenruo 	 * end_bio_extent_readpage decrements io_pages in case of error,
678371cdc07SQu Wenruo 	 * make sure it has something to decrement.
679371cdc07SQu Wenruo 	 */
680371cdc07SQu Wenruo 	atomic_inc(&eb->io_pages);
681371cdc07SQu Wenruo 	clear_extent_buffer_uptodate(eb);
682371cdc07SQu Wenruo 	free_extent_buffer(eb);
683371cdc07SQu Wenruo 	return ret;
684371cdc07SQu Wenruo }
685371cdc07SQu Wenruo 
6868e1dc982SQu Wenruo int btrfs_validate_metadata_buffer(struct btrfs_io_bio *io_bio,
68777bf40a2SQu Wenruo 				   struct page *page, u64 start, u64 end,
68877bf40a2SQu Wenruo 				   int mirror)
68977bf40a2SQu Wenruo {
69077bf40a2SQu Wenruo 	struct extent_buffer *eb;
69177bf40a2SQu Wenruo 	int ret = 0;
69277bf40a2SQu Wenruo 	int reads_done;
69377bf40a2SQu Wenruo 
69477bf40a2SQu Wenruo 	ASSERT(page->private);
695371cdc07SQu Wenruo 
696371cdc07SQu Wenruo 	if (btrfs_sb(page->mapping->host->i_sb)->sectorsize < PAGE_SIZE)
697371cdc07SQu Wenruo 		return validate_subpage_buffer(page, start, end, mirror);
698371cdc07SQu Wenruo 
69977bf40a2SQu Wenruo 	eb = (struct extent_buffer *)page->private;
70077bf40a2SQu Wenruo 
70177bf40a2SQu Wenruo 	/*
70277bf40a2SQu Wenruo 	 * The pending IO might have been the only thing that kept this buffer
70377bf40a2SQu Wenruo 	 * in memory.  Make sure we have a ref for all this other checks
70477bf40a2SQu Wenruo 	 */
70577bf40a2SQu Wenruo 	atomic_inc(&eb->refs);
70677bf40a2SQu Wenruo 
70777bf40a2SQu Wenruo 	reads_done = atomic_dec_and_test(&eb->io_pages);
70877bf40a2SQu Wenruo 	if (!reads_done)
70977bf40a2SQu Wenruo 		goto err;
71077bf40a2SQu Wenruo 
71177bf40a2SQu Wenruo 	eb->read_mirror = mirror;
71277bf40a2SQu Wenruo 	if (test_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags)) {
71377bf40a2SQu Wenruo 		ret = -EIO;
71477bf40a2SQu Wenruo 		goto err;
71577bf40a2SQu Wenruo 	}
71677bf40a2SQu Wenruo 	ret = validate_extent_buffer(eb);
717ce9adaa5SChris Mason err:
71879fb65a1SJosef Bacik 	if (reads_done &&
71979fb65a1SJosef Bacik 	    test_and_clear_bit(EXTENT_BUFFER_READAHEAD, &eb->bflags))
720d48d71aaSDavid Sterba 		btree_readahead_hook(eb, ret);
7214bb31e92SArne Jansen 
72253b381b3SDavid Woodhouse 	if (ret) {
72353b381b3SDavid Woodhouse 		/*
72453b381b3SDavid Woodhouse 		 * our io error hook is going to dec the io pages
72553b381b3SDavid Woodhouse 		 * again, we have to make sure it has something
72653b381b3SDavid Woodhouse 		 * to decrement
72753b381b3SDavid Woodhouse 		 */
72853b381b3SDavid Woodhouse 		atomic_inc(&eb->io_pages);
7290b32f4bbSJosef Bacik 		clear_extent_buffer_uptodate(eb);
73053b381b3SDavid Woodhouse 	}
7310b32f4bbSJosef Bacik 	free_extent_buffer(eb);
73277bf40a2SQu Wenruo 
733f188591eSChris Mason 	return ret;
734ce9adaa5SChris Mason }
735ce9adaa5SChris Mason 
7364246a0b6SChristoph Hellwig static void end_workqueue_bio(struct bio *bio)
737ce9adaa5SChris Mason {
73897eb6b69SDavid Sterba 	struct btrfs_end_io_wq *end_io_wq = bio->bi_private;
739ce9adaa5SChris Mason 	struct btrfs_fs_info *fs_info;
7409e0af237SLiu Bo 	struct btrfs_workqueue *wq;
741ce9adaa5SChris Mason 
742ce9adaa5SChris Mason 	fs_info = end_io_wq->info;
7434e4cbee9SChristoph Hellwig 	end_io_wq->status = bio->bi_status;
744d20f7043SChris Mason 
745cfe94440SNaohiro Aota 	if (btrfs_op(bio) == BTRFS_MAP_WRITE) {
746a0cac0ecSOmar Sandoval 		if (end_io_wq->metadata == BTRFS_WQ_ENDIO_METADATA)
7479e0af237SLiu Bo 			wq = fs_info->endio_meta_write_workers;
748a0cac0ecSOmar Sandoval 		else if (end_io_wq->metadata == BTRFS_WQ_ENDIO_FREE_SPACE)
7499e0af237SLiu Bo 			wq = fs_info->endio_freespace_worker;
750a0cac0ecSOmar Sandoval 		else if (end_io_wq->metadata == BTRFS_WQ_ENDIO_RAID56)
7519e0af237SLiu Bo 			wq = fs_info->endio_raid56_workers;
752a0cac0ecSOmar Sandoval 		else
7539e0af237SLiu Bo 			wq = fs_info->endio_write_workers;
7549e0af237SLiu Bo 	} else {
7555c047a69SOmar Sandoval 		if (end_io_wq->metadata == BTRFS_WQ_ENDIO_RAID56)
7569e0af237SLiu Bo 			wq = fs_info->endio_raid56_workers;
757a0cac0ecSOmar Sandoval 		else if (end_io_wq->metadata)
7589e0af237SLiu Bo 			wq = fs_info->endio_meta_workers;
759a0cac0ecSOmar Sandoval 		else
7609e0af237SLiu Bo 			wq = fs_info->endio_workers;
7619e0af237SLiu Bo 	}
7629e0af237SLiu Bo 
763a0cac0ecSOmar Sandoval 	btrfs_init_work(&end_io_wq->work, end_workqueue_fn, NULL, NULL);
7649e0af237SLiu Bo 	btrfs_queue_work(wq, &end_io_wq->work);
765ce9adaa5SChris Mason }
766ce9adaa5SChris Mason 
7674e4cbee9SChristoph Hellwig blk_status_t btrfs_bio_wq_end_io(struct btrfs_fs_info *info, struct bio *bio,
768bfebd8b5SDavid Sterba 			enum btrfs_wq_endio_type metadata)
7690b86a832SChris Mason {
77097eb6b69SDavid Sterba 	struct btrfs_end_io_wq *end_io_wq;
7718b110e39SMiao Xie 
77297eb6b69SDavid Sterba 	end_io_wq = kmem_cache_alloc(btrfs_end_io_wq_cache, GFP_NOFS);
773ce9adaa5SChris Mason 	if (!end_io_wq)
7744e4cbee9SChristoph Hellwig 		return BLK_STS_RESOURCE;
775ce9adaa5SChris Mason 
776ce9adaa5SChris Mason 	end_io_wq->private = bio->bi_private;
777ce9adaa5SChris Mason 	end_io_wq->end_io = bio->bi_end_io;
77822c59948SChris Mason 	end_io_wq->info = info;
7794e4cbee9SChristoph Hellwig 	end_io_wq->status = 0;
780ce9adaa5SChris Mason 	end_io_wq->bio = bio;
78122c59948SChris Mason 	end_io_wq->metadata = metadata;
782ce9adaa5SChris Mason 
783ce9adaa5SChris Mason 	bio->bi_private = end_io_wq;
784ce9adaa5SChris Mason 	bio->bi_end_io = end_workqueue_bio;
78522c59948SChris Mason 	return 0;
78622c59948SChris Mason }
78722c59948SChris Mason 
7884a69a410SChris Mason static void run_one_async_start(struct btrfs_work *work)
7894a69a410SChris Mason {
7904a69a410SChris Mason 	struct async_submit_bio *async;
7914e4cbee9SChristoph Hellwig 	blk_status_t ret;
7924a69a410SChris Mason 
7934a69a410SChris Mason 	async = container_of(work, struct  async_submit_bio, work);
7941941b64bSQu Wenruo 	ret = async->submit_bio_start(async->inode, async->bio,
7951941b64bSQu Wenruo 				      async->dio_file_offset);
79679787eaaSJeff Mahoney 	if (ret)
7974e4cbee9SChristoph Hellwig 		async->status = ret;
7984a69a410SChris Mason }
7994a69a410SChris Mason 
80006ea01b1SDavid Sterba /*
80106ea01b1SDavid Sterba  * In order to insert checksums into the metadata in large chunks, we wait
80206ea01b1SDavid Sterba  * until bio submission time.   All the pages in the bio are checksummed and
80306ea01b1SDavid Sterba  * sums are attached onto the ordered extent record.
80406ea01b1SDavid Sterba  *
80506ea01b1SDavid Sterba  * At IO completion time the csums attached on the ordered extent record are
80606ea01b1SDavid Sterba  * inserted into the tree.
80706ea01b1SDavid Sterba  */
8084a69a410SChris Mason static void run_one_async_done(struct btrfs_work *work)
8098b712842SChris Mason {
8108b712842SChris Mason 	struct async_submit_bio *async;
81106ea01b1SDavid Sterba 	struct inode *inode;
81206ea01b1SDavid Sterba 	blk_status_t ret;
8138b712842SChris Mason 
8148b712842SChris Mason 	async = container_of(work, struct  async_submit_bio, work);
8158896a08dSQu Wenruo 	inode = async->inode;
8164854ddd0SChris Mason 
817bb7ab3b9SAdam Buchbinder 	/* If an error occurred we just want to clean up the bio and move on */
8184e4cbee9SChristoph Hellwig 	if (async->status) {
8194e4cbee9SChristoph Hellwig 		async->bio->bi_status = async->status;
8204246a0b6SChristoph Hellwig 		bio_endio(async->bio);
82179787eaaSJeff Mahoney 		return;
82279787eaaSJeff Mahoney 	}
82379787eaaSJeff Mahoney 
824ec39f769SChris Mason 	/*
825ec39f769SChris Mason 	 * All of the bios that pass through here are from async helpers.
826ec39f769SChris Mason 	 * Use REQ_CGROUP_PUNT to issue them from the owning cgroup's context.
827ec39f769SChris Mason 	 * This changes nothing when cgroups aren't in use.
828ec39f769SChris Mason 	 */
829ec39f769SChris Mason 	async->bio->bi_opf |= REQ_CGROUP_PUNT;
83008635baeSChris Mason 	ret = btrfs_map_bio(btrfs_sb(inode->i_sb), async->bio, async->mirror_num);
83106ea01b1SDavid Sterba 	if (ret) {
83206ea01b1SDavid Sterba 		async->bio->bi_status = ret;
83306ea01b1SDavid Sterba 		bio_endio(async->bio);
83406ea01b1SDavid Sterba 	}
8354a69a410SChris Mason }
8364a69a410SChris Mason 
8374a69a410SChris Mason static void run_one_async_free(struct btrfs_work *work)
8384a69a410SChris Mason {
8394a69a410SChris Mason 	struct async_submit_bio *async;
8404a69a410SChris Mason 
8414a69a410SChris Mason 	async = container_of(work, struct  async_submit_bio, work);
8428b712842SChris Mason 	kfree(async);
8438b712842SChris Mason }
8448b712842SChris Mason 
8458896a08dSQu Wenruo blk_status_t btrfs_wq_submit_bio(struct inode *inode, struct bio *bio,
846c6100a4bSJosef Bacik 				 int mirror_num, unsigned long bio_flags,
8471941b64bSQu Wenruo 				 u64 dio_file_offset,
848e288c080SDavid Sterba 				 extent_submit_bio_start_t *submit_bio_start)
84944b8bd7eSChris Mason {
8508896a08dSQu Wenruo 	struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
85144b8bd7eSChris Mason 	struct async_submit_bio *async;
85244b8bd7eSChris Mason 
85344b8bd7eSChris Mason 	async = kmalloc(sizeof(*async), GFP_NOFS);
85444b8bd7eSChris Mason 	if (!async)
8554e4cbee9SChristoph Hellwig 		return BLK_STS_RESOURCE;
85644b8bd7eSChris Mason 
8578896a08dSQu Wenruo 	async->inode = inode;
85844b8bd7eSChris Mason 	async->bio = bio;
85944b8bd7eSChris Mason 	async->mirror_num = mirror_num;
8604a69a410SChris Mason 	async->submit_bio_start = submit_bio_start;
8614a69a410SChris Mason 
862a0cac0ecSOmar Sandoval 	btrfs_init_work(&async->work, run_one_async_start, run_one_async_done,
863a0cac0ecSOmar Sandoval 			run_one_async_free);
8644a69a410SChris Mason 
8651941b64bSQu Wenruo 	async->dio_file_offset = dio_file_offset;
8668c8bee1dSChris Mason 
8674e4cbee9SChristoph Hellwig 	async->status = 0;
86879787eaaSJeff Mahoney 
86967f055c7SChristoph Hellwig 	if (op_is_sync(bio->bi_opf))
8705cdc7ad3SQu Wenruo 		btrfs_set_work_high_priority(&async->work);
871d313d7a3SChris Mason 
8725cdc7ad3SQu Wenruo 	btrfs_queue_work(fs_info->workers, &async->work);
87344b8bd7eSChris Mason 	return 0;
87444b8bd7eSChris Mason }
87544b8bd7eSChris Mason 
8764e4cbee9SChristoph Hellwig static blk_status_t btree_csum_one_bio(struct bio *bio)
877ce3ed71aSChris Mason {
8782c30c71bSKent Overstreet 	struct bio_vec *bvec;
879ce3ed71aSChris Mason 	struct btrfs_root *root;
8802b070cfeSChristoph Hellwig 	int ret = 0;
8816dc4f100SMing Lei 	struct bvec_iter_all iter_all;
882ce3ed71aSChris Mason 
883c09abff8SDavid Sterba 	ASSERT(!bio_flagged(bio, BIO_CLONED));
8842b070cfeSChristoph Hellwig 	bio_for_each_segment_all(bvec, bio, iter_all) {
885ce3ed71aSChris Mason 		root = BTRFS_I(bvec->bv_page->mapping->host)->root;
886ac303b69SQu Wenruo 		ret = csum_dirty_buffer(root->fs_info, bvec);
88779787eaaSJeff Mahoney 		if (ret)
88879787eaaSJeff Mahoney 			break;
889ce3ed71aSChris Mason 	}
8902c30c71bSKent Overstreet 
8914e4cbee9SChristoph Hellwig 	return errno_to_blk_status(ret);
892ce3ed71aSChris Mason }
893ce3ed71aSChris Mason 
8948896a08dSQu Wenruo static blk_status_t btree_submit_bio_start(struct inode *inode, struct bio *bio,
8951941b64bSQu Wenruo 					   u64 dio_file_offset)
89622c59948SChris Mason {
8978b712842SChris Mason 	/*
8988b712842SChris Mason 	 * when we're called for a write, we're already in the async
8995443be45SChris Mason 	 * submission context.  Just jump into btrfs_map_bio
9008b712842SChris Mason 	 */
90179787eaaSJeff Mahoney 	return btree_csum_one_bio(bio);
90222c59948SChris Mason }
90322c59948SChris Mason 
904f4dcfb30SJohannes Thumshirn static bool should_async_write(struct btrfs_fs_info *fs_info,
9059b4e675aSDavid Sterba 			     struct btrfs_inode *bi)
906de0022b9SJosef Bacik {
9074eef29efSNaohiro Aota 	if (btrfs_is_zoned(fs_info))
908f4dcfb30SJohannes Thumshirn 		return false;
9096300463bSLiu Bo 	if (atomic_read(&bi->sync_writers))
910f4dcfb30SJohannes Thumshirn 		return false;
9119b4e675aSDavid Sterba 	if (test_bit(BTRFS_FS_CSUM_IMPL_FAST, &fs_info->flags))
912f4dcfb30SJohannes Thumshirn 		return false;
913f4dcfb30SJohannes Thumshirn 	return true;
914de0022b9SJosef Bacik }
915de0022b9SJosef Bacik 
9161b36294aSNikolay Borisov blk_status_t btrfs_submit_metadata_bio(struct inode *inode, struct bio *bio,
9171b36294aSNikolay Borisov 				       int mirror_num, unsigned long bio_flags)
91844b8bd7eSChris Mason {
9190b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9204e4cbee9SChristoph Hellwig 	blk_status_t ret;
921cad321adSChris Mason 
922cfe94440SNaohiro Aota 	if (btrfs_op(bio) != BTRFS_MAP_WRITE) {
923cad321adSChris Mason 		/*
924cad321adSChris Mason 		 * called for a read, do the setup so that checksum validation
925cad321adSChris Mason 		 * can happen in the async kernel threads
926cad321adSChris Mason 		 */
9270b246afaSJeff Mahoney 		ret = btrfs_bio_wq_end_io(fs_info, bio,
9280b246afaSJeff Mahoney 					  BTRFS_WQ_ENDIO_METADATA);
9291d4284bdSChris Mason 		if (ret)
93061891923SStefan Behrens 			goto out_w_error;
93108635baeSChris Mason 		ret = btrfs_map_bio(fs_info, bio, mirror_num);
932f4dcfb30SJohannes Thumshirn 	} else if (!should_async_write(fs_info, BTRFS_I(inode))) {
933de0022b9SJosef Bacik 		ret = btree_csum_one_bio(bio);
934de0022b9SJosef Bacik 		if (ret)
93561891923SStefan Behrens 			goto out_w_error;
93608635baeSChris Mason 		ret = btrfs_map_bio(fs_info, bio, mirror_num);
93761891923SStefan Behrens 	} else {
938cad321adSChris Mason 		/*
93961891923SStefan Behrens 		 * kthread helpers are used to submit writes so that
94061891923SStefan Behrens 		 * checksumming can happen in parallel across all CPUs
941cad321adSChris Mason 		 */
9428896a08dSQu Wenruo 		ret = btrfs_wq_submit_bio(inode, bio, mirror_num, 0,
9438896a08dSQu Wenruo 					  0, btree_submit_bio_start);
94444b8bd7eSChris Mason 	}
94544b8bd7eSChris Mason 
9464246a0b6SChristoph Hellwig 	if (ret)
9474246a0b6SChristoph Hellwig 		goto out_w_error;
9484246a0b6SChristoph Hellwig 	return 0;
9494246a0b6SChristoph Hellwig 
95061891923SStefan Behrens out_w_error:
9514e4cbee9SChristoph Hellwig 	bio->bi_status = ret;
9524246a0b6SChristoph Hellwig 	bio_endio(bio);
95361891923SStefan Behrens 	return ret;
95461891923SStefan Behrens }
95561891923SStefan Behrens 
9563dd1462eSJan Beulich #ifdef CONFIG_MIGRATION
957784b4e29SChris Mason static int btree_migratepage(struct address_space *mapping,
958a6bc32b8SMel Gorman 			struct page *newpage, struct page *page,
959a6bc32b8SMel Gorman 			enum migrate_mode mode)
960784b4e29SChris Mason {
961784b4e29SChris Mason 	/*
962784b4e29SChris Mason 	 * we can't safely write a btree page from here,
963784b4e29SChris Mason 	 * we haven't done the locking hook
964784b4e29SChris Mason 	 */
965784b4e29SChris Mason 	if (PageDirty(page))
966784b4e29SChris Mason 		return -EAGAIN;
967784b4e29SChris Mason 	/*
968784b4e29SChris Mason 	 * Buffers may be managed in a filesystem specific way.
969784b4e29SChris Mason 	 * We must have no buffers or drop them.
970784b4e29SChris Mason 	 */
971784b4e29SChris Mason 	if (page_has_private(page) &&
972784b4e29SChris Mason 	    !try_to_release_page(page, GFP_KERNEL))
973784b4e29SChris Mason 		return -EAGAIN;
974a6bc32b8SMel Gorman 	return migrate_page(mapping, newpage, page, mode);
975784b4e29SChris Mason }
9763dd1462eSJan Beulich #endif
977784b4e29SChris Mason 
9780da5468fSChris Mason 
9790da5468fSChris Mason static int btree_writepages(struct address_space *mapping,
9800da5468fSChris Mason 			    struct writeback_control *wbc)
9810da5468fSChris Mason {
982e2d84521SMiao Xie 	struct btrfs_fs_info *fs_info;
983e2d84521SMiao Xie 	int ret;
984e2d84521SMiao Xie 
985d8d5f3e1SChris Mason 	if (wbc->sync_mode == WB_SYNC_NONE) {
986448d640bSChris Mason 
987448d640bSChris Mason 		if (wbc->for_kupdate)
988448d640bSChris Mason 			return 0;
989448d640bSChris Mason 
990e2d84521SMiao Xie 		fs_info = BTRFS_I(mapping->host)->root->fs_info;
991b9473439SChris Mason 		/* this is a bit racy, but that's ok */
992d814a491SEthan Lien 		ret = __percpu_counter_compare(&fs_info->dirty_metadata_bytes,
993d814a491SEthan Lien 					     BTRFS_DIRTY_METADATA_THRESH,
994d814a491SEthan Lien 					     fs_info->dirty_metadata_batch);
995e2d84521SMiao Xie 		if (ret < 0)
996793955bcSChris Mason 			return 0;
997793955bcSChris Mason 	}
9980b32f4bbSJosef Bacik 	return btree_write_cache_pages(mapping, wbc);
9990da5468fSChris Mason }
10000da5468fSChris Mason 
100170dec807SChris Mason static int btree_releasepage(struct page *page, gfp_t gfp_flags)
10025f39d397SChris Mason {
100398509cfcSChris Mason 	if (PageWriteback(page) || PageDirty(page))
100498509cfcSChris Mason 		return 0;
10050c4e538bSDavid Sterba 
1006f7a52a40SDavid Sterba 	return try_release_extent_buffer(page);
1007d98237b3SChris Mason }
1008d98237b3SChris Mason 
1009d47992f8SLukas Czerner static void btree_invalidatepage(struct page *page, unsigned int offset,
1010d47992f8SLukas Czerner 				 unsigned int length)
1011d98237b3SChris Mason {
1012d1310b2eSChris Mason 	struct extent_io_tree *tree;
1013d1310b2eSChris Mason 	tree = &BTRFS_I(page->mapping->host)->io_tree;
10145f39d397SChris Mason 	extent_invalidatepage(tree, page, offset);
10155f39d397SChris Mason 	btree_releasepage(page, GFP_NOFS);
10169ad6b7bcSChris Mason 	if (PagePrivate(page)) {
1017efe120a0SFrank Holton 		btrfs_warn(BTRFS_I(page->mapping->host)->root->fs_info,
1018efe120a0SFrank Holton 			   "page private not zero on page %llu",
1019efe120a0SFrank Holton 			   (unsigned long long)page_offset(page));
1020d1b89bc0SGuoqing Jiang 		detach_page_private(page);
10219ad6b7bcSChris Mason 	}
1022d98237b3SChris Mason }
1023d98237b3SChris Mason 
10240b32f4bbSJosef Bacik static int btree_set_page_dirty(struct page *page)
10250b32f4bbSJosef Bacik {
1026bb146eb2SJosef Bacik #ifdef DEBUG
1027139e8cd3SQu Wenruo 	struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
1028139e8cd3SQu Wenruo 	struct btrfs_subpage *subpage;
10290b32f4bbSJosef Bacik 	struct extent_buffer *eb;
1030139e8cd3SQu Wenruo 	int cur_bit = 0;
1031139e8cd3SQu Wenruo 	u64 page_start = page_offset(page);
10320b32f4bbSJosef Bacik 
1033139e8cd3SQu Wenruo 	if (fs_info->sectorsize == PAGE_SIZE) {
10340b32f4bbSJosef Bacik 		BUG_ON(!PagePrivate(page));
10350b32f4bbSJosef Bacik 		eb = (struct extent_buffer *)page->private;
10360b32f4bbSJosef Bacik 		BUG_ON(!eb);
10370b32f4bbSJosef Bacik 		BUG_ON(!test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
10380b32f4bbSJosef Bacik 		BUG_ON(!atomic_read(&eb->refs));
10390b32f4bbSJosef Bacik 		btrfs_assert_tree_locked(eb);
1040139e8cd3SQu Wenruo 		return __set_page_dirty_nobuffers(page);
1041139e8cd3SQu Wenruo 	}
1042139e8cd3SQu Wenruo 	ASSERT(PagePrivate(page) && page->private);
1043139e8cd3SQu Wenruo 	subpage = (struct btrfs_subpage *)page->private;
1044139e8cd3SQu Wenruo 
1045139e8cd3SQu Wenruo 	ASSERT(subpage->dirty_bitmap);
1046139e8cd3SQu Wenruo 	while (cur_bit < BTRFS_SUBPAGE_BITMAP_SIZE) {
1047139e8cd3SQu Wenruo 		unsigned long flags;
1048139e8cd3SQu Wenruo 		u64 cur;
1049139e8cd3SQu Wenruo 		u16 tmp = (1 << cur_bit);
1050139e8cd3SQu Wenruo 
1051139e8cd3SQu Wenruo 		spin_lock_irqsave(&subpage->lock, flags);
1052139e8cd3SQu Wenruo 		if (!(tmp & subpage->dirty_bitmap)) {
1053139e8cd3SQu Wenruo 			spin_unlock_irqrestore(&subpage->lock, flags);
1054139e8cd3SQu Wenruo 			cur_bit++;
1055139e8cd3SQu Wenruo 			continue;
1056139e8cd3SQu Wenruo 		}
1057139e8cd3SQu Wenruo 		spin_unlock_irqrestore(&subpage->lock, flags);
1058139e8cd3SQu Wenruo 		cur = page_start + cur_bit * fs_info->sectorsize;
1059139e8cd3SQu Wenruo 
1060139e8cd3SQu Wenruo 		eb = find_extent_buffer(fs_info, cur);
1061139e8cd3SQu Wenruo 		ASSERT(eb);
1062139e8cd3SQu Wenruo 		ASSERT(test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
1063139e8cd3SQu Wenruo 		ASSERT(atomic_read(&eb->refs));
1064139e8cd3SQu Wenruo 		btrfs_assert_tree_locked(eb);
1065139e8cd3SQu Wenruo 		free_extent_buffer(eb);
1066139e8cd3SQu Wenruo 
1067139e8cd3SQu Wenruo 		cur_bit += (fs_info->nodesize >> fs_info->sectorsize_bits);
1068139e8cd3SQu Wenruo 	}
1069bb146eb2SJosef Bacik #endif
10700b32f4bbSJosef Bacik 	return __set_page_dirty_nobuffers(page);
10710b32f4bbSJosef Bacik }
10720b32f4bbSJosef Bacik 
10737f09410bSAlexey Dobriyan static const struct address_space_operations btree_aops = {
10740da5468fSChris Mason 	.writepages	= btree_writepages,
10755f39d397SChris Mason 	.releasepage	= btree_releasepage,
10765f39d397SChris Mason 	.invalidatepage = btree_invalidatepage,
10775a92bc88SChris Mason #ifdef CONFIG_MIGRATION
1078784b4e29SChris Mason 	.migratepage	= btree_migratepage,
10795a92bc88SChris Mason #endif
10800b32f4bbSJosef Bacik 	.set_page_dirty = btree_set_page_dirty,
1081d98237b3SChris Mason };
1082123abc88SChris Mason 
10832ff7e61eSJeff Mahoney struct extent_buffer *btrfs_find_create_tree_block(
10842ff7e61eSJeff Mahoney 						struct btrfs_fs_info *fs_info,
10853fbaf258SJosef Bacik 						u64 bytenr, u64 owner_root,
10863fbaf258SJosef Bacik 						int level)
10870999df54SChris Mason {
10880b246afaSJeff Mahoney 	if (btrfs_is_testing(fs_info))
10890b246afaSJeff Mahoney 		return alloc_test_extent_buffer(fs_info, bytenr);
10903fbaf258SJosef Bacik 	return alloc_extent_buffer(fs_info, bytenr, owner_root, level);
10910999df54SChris Mason }
10920999df54SChris Mason 
1093581c1760SQu Wenruo /*
1094581c1760SQu Wenruo  * Read tree block at logical address @bytenr and do variant basic but critical
1095581c1760SQu Wenruo  * verification.
1096581c1760SQu Wenruo  *
10971b7ec85eSJosef Bacik  * @owner_root:		the objectid of the root owner for this block.
1098581c1760SQu Wenruo  * @parent_transid:	expected transid of this tree block, skip check if 0
1099581c1760SQu Wenruo  * @level:		expected level, mandatory check
1100581c1760SQu Wenruo  * @first_key:		expected key in slot 0, skip check if NULL
1101581c1760SQu Wenruo  */
11022ff7e61eSJeff Mahoney struct extent_buffer *read_tree_block(struct btrfs_fs_info *fs_info, u64 bytenr,
11031b7ec85eSJosef Bacik 				      u64 owner_root, u64 parent_transid,
11041b7ec85eSJosef Bacik 				      int level, struct btrfs_key *first_key)
1105e20d96d6SChris Mason {
11065f39d397SChris Mason 	struct extent_buffer *buf = NULL;
110719c00ddcSChris Mason 	int ret;
110819c00ddcSChris Mason 
11093fbaf258SJosef Bacik 	buf = btrfs_find_create_tree_block(fs_info, bytenr, owner_root, level);
1110c871b0f2SLiu Bo 	if (IS_ERR(buf))
1111c871b0f2SLiu Bo 		return buf;
1112e4204dedSChris Mason 
11135ab12d1fSDavid Sterba 	ret = btree_read_extent_buffer_pages(buf, parent_transid,
1114581c1760SQu Wenruo 					     level, first_key);
11150f0fe8f7SFilipe David Borba Manana 	if (ret) {
1116537f38f0SNikolay Borisov 		free_extent_buffer_stale(buf);
111764c043deSLiu Bo 		return ERR_PTR(ret);
11180f0fe8f7SFilipe David Borba Manana 	}
11195f39d397SChris Mason 	return buf;
1120ce9adaa5SChris Mason 
1121eb60ceacSChris Mason }
1122eb60ceacSChris Mason 
11236a884d7dSDavid Sterba void btrfs_clean_tree_block(struct extent_buffer *buf)
1124ed2ff2cbSChris Mason {
11256a884d7dSDavid Sterba 	struct btrfs_fs_info *fs_info = buf->fs_info;
112655c69072SChris Mason 	if (btrfs_header_generation(buf) ==
1127e2d84521SMiao Xie 	    fs_info->running_transaction->transid) {
1128b9447ef8SChris Mason 		btrfs_assert_tree_locked(buf);
1129b4ce94deSChris Mason 
1130b9473439SChris Mason 		if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &buf->bflags)) {
1131104b4e51SNikolay Borisov 			percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
1132e2d84521SMiao Xie 						 -buf->len,
1133e2d84521SMiao Xie 						 fs_info->dirty_metadata_batch);
11340b32f4bbSJosef Bacik 			clear_extent_buffer_dirty(buf);
1135925baeddSChris Mason 		}
11365f39d397SChris Mason 	}
1137ed7b63ebSJosef Bacik }
11385f39d397SChris Mason 
1139da17066cSJeff Mahoney static void __setup_root(struct btrfs_root *root, struct btrfs_fs_info *fs_info,
1140e20d96d6SChris Mason 			 u64 objectid)
1141d97e63b6SChris Mason {
11427c0260eeSJeff Mahoney 	bool dummy = test_bit(BTRFS_FS_STATE_DUMMY_FS_INFO, &fs_info->fs_state);
114396dfcb46SJosef Bacik 	root->fs_info = fs_info;
1144cfaa7295SChris Mason 	root->node = NULL;
1145a28ec197SChris Mason 	root->commit_root = NULL;
114627cdeb70SMiao Xie 	root->state = 0;
1147d68fc57bSYan, Zheng 	root->orphan_cleanup_state = 0;
11480b86a832SChris Mason 
11490f7d52f4SChris Mason 	root->last_trans = 0;
11506b8fad57SNikolay Borisov 	root->free_objectid = 0;
1151eb73c1b7SMiao Xie 	root->nr_delalloc_inodes = 0;
1152199c2a9cSMiao Xie 	root->nr_ordered_extents = 0;
11536bef4d31SEric Paris 	root->inode_tree = RB_ROOT;
115416cdcec7SMiao Xie 	INIT_RADIX_TREE(&root->delayed_nodes_tree, GFP_ATOMIC);
1155f0486c68SYan, Zheng 	root->block_rsv = NULL;
11560b86a832SChris Mason 
11570b86a832SChris Mason 	INIT_LIST_HEAD(&root->dirty_list);
11585d4f98a2SYan Zheng 	INIT_LIST_HEAD(&root->root_list);
1159eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&root->delalloc_inodes);
1160eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&root->delalloc_root);
1161199c2a9cSMiao Xie 	INIT_LIST_HEAD(&root->ordered_extents);
1162199c2a9cSMiao Xie 	INIT_LIST_HEAD(&root->ordered_root);
1163d2311e69SQu Wenruo 	INIT_LIST_HEAD(&root->reloc_dirty_list);
11642ab28f32SJosef Bacik 	INIT_LIST_HEAD(&root->logged_list[0]);
11652ab28f32SJosef Bacik 	INIT_LIST_HEAD(&root->logged_list[1]);
11665d4f98a2SYan Zheng 	spin_lock_init(&root->inode_lock);
1167eb73c1b7SMiao Xie 	spin_lock_init(&root->delalloc_lock);
1168199c2a9cSMiao Xie 	spin_lock_init(&root->ordered_extent_lock);
1169f0486c68SYan, Zheng 	spin_lock_init(&root->accounting_lock);
11702ab28f32SJosef Bacik 	spin_lock_init(&root->log_extents_lock[0]);
11712ab28f32SJosef Bacik 	spin_lock_init(&root->log_extents_lock[1]);
11728287475aSQu Wenruo 	spin_lock_init(&root->qgroup_meta_rsv_lock);
1173a2135011SChris Mason 	mutex_init(&root->objectid_mutex);
1174e02119d5SChris Mason 	mutex_init(&root->log_mutex);
117531f3d255SMiao Xie 	mutex_init(&root->ordered_extent_mutex);
1176573bfb72SMiao Xie 	mutex_init(&root->delalloc_mutex);
1177c53e9653SQu Wenruo 	init_waitqueue_head(&root->qgroup_flush_wait);
11787237f183SYan Zheng 	init_waitqueue_head(&root->log_writer_wait);
11797237f183SYan Zheng 	init_waitqueue_head(&root->log_commit_wait[0]);
11807237f183SYan Zheng 	init_waitqueue_head(&root->log_commit_wait[1]);
11818b050d35SMiao Xie 	INIT_LIST_HEAD(&root->log_ctxs[0]);
11828b050d35SMiao Xie 	INIT_LIST_HEAD(&root->log_ctxs[1]);
11837237f183SYan Zheng 	atomic_set(&root->log_commit[0], 0);
11847237f183SYan Zheng 	atomic_set(&root->log_commit[1], 0);
11857237f183SYan Zheng 	atomic_set(&root->log_writers, 0);
11862ecb7923SMiao Xie 	atomic_set(&root->log_batch, 0);
11870700cea7SElena Reshetova 	refcount_set(&root->refs, 1);
11888ecebf4dSRobbie Ko 	atomic_set(&root->snapshot_force_cow, 0);
1189eede2bf3SOmar Sandoval 	atomic_set(&root->nr_swapfiles, 0);
11907237f183SYan Zheng 	root->log_transid = 0;
1191d1433debSMiao Xie 	root->log_transid_committed = -1;
1192257c62e1SChris Mason 	root->last_log_commit = 0;
1193e289f03eSFilipe Manana 	if (!dummy) {
119443eb5f29SQu Wenruo 		extent_io_tree_init(fs_info, &root->dirty_log_pages,
119543eb5f29SQu Wenruo 				    IO_TREE_ROOT_DIRTY_LOG_PAGES, NULL);
1196e289f03eSFilipe Manana 		extent_io_tree_init(fs_info, &root->log_csum_range,
1197e289f03eSFilipe Manana 				    IO_TREE_LOG_CSUM_RANGE, NULL);
1198e289f03eSFilipe Manana 	}
1199017e5369SChris Mason 
12003768f368SChris Mason 	memset(&root->root_key, 0, sizeof(root->root_key));
12013768f368SChris Mason 	memset(&root->root_item, 0, sizeof(root->root_item));
12026702ed49SChris Mason 	memset(&root->defrag_progress, 0, sizeof(root->defrag_progress));
12034d775673SChris Mason 	root->root_key.objectid = objectid;
12040ee5dc67SAl Viro 	root->anon_dev = 0;
12058ea05e3aSAlexander Block 
12065f3ab90aSAnand Jain 	spin_lock_init(&root->root_item_lock);
1207370a11b8SQu Wenruo 	btrfs_qgroup_init_swapped_blocks(&root->swapped_blocks);
1208bd647ce3SJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
1209bd647ce3SJosef Bacik 	INIT_LIST_HEAD(&root->leak_list);
1210bd647ce3SJosef Bacik 	spin_lock(&fs_info->fs_roots_radix_lock);
1211bd647ce3SJosef Bacik 	list_add_tail(&root->leak_list, &fs_info->allocated_roots);
1212bd647ce3SJosef Bacik 	spin_unlock(&fs_info->fs_roots_radix_lock);
1213bd647ce3SJosef Bacik #endif
12143768f368SChris Mason }
12153768f368SChris Mason 
121674e4d827SDavid Sterba static struct btrfs_root *btrfs_alloc_root(struct btrfs_fs_info *fs_info,
121796dfcb46SJosef Bacik 					   u64 objectid, gfp_t flags)
12186f07e42eSAl Viro {
121974e4d827SDavid Sterba 	struct btrfs_root *root = kzalloc(sizeof(*root), flags);
12206f07e42eSAl Viro 	if (root)
122196dfcb46SJosef Bacik 		__setup_root(root, fs_info, objectid);
12226f07e42eSAl Viro 	return root;
12236f07e42eSAl Viro }
12246f07e42eSAl Viro 
122506ea65a3SJosef Bacik #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
122606ea65a3SJosef Bacik /* Should only be used by the testing infrastructure */
1227da17066cSJeff Mahoney struct btrfs_root *btrfs_alloc_dummy_root(struct btrfs_fs_info *fs_info)
122806ea65a3SJosef Bacik {
122906ea65a3SJosef Bacik 	struct btrfs_root *root;
123006ea65a3SJosef Bacik 
12317c0260eeSJeff Mahoney 	if (!fs_info)
12327c0260eeSJeff Mahoney 		return ERR_PTR(-EINVAL);
12337c0260eeSJeff Mahoney 
123496dfcb46SJosef Bacik 	root = btrfs_alloc_root(fs_info, BTRFS_ROOT_TREE_OBJECTID, GFP_KERNEL);
123506ea65a3SJosef Bacik 	if (!root)
123606ea65a3SJosef Bacik 		return ERR_PTR(-ENOMEM);
1237da17066cSJeff Mahoney 
1238b9ef22deSFeifei Xu 	/* We don't use the stripesize in selftest, set it as sectorsize */
1239faa2dbf0SJosef Bacik 	root->alloc_bytenr = 0;
124006ea65a3SJosef Bacik 
124106ea65a3SJosef Bacik 	return root;
124206ea65a3SJosef Bacik }
124306ea65a3SJosef Bacik #endif
124406ea65a3SJosef Bacik 
124520897f5cSArne Jansen struct btrfs_root *btrfs_create_tree(struct btrfs_trans_handle *trans,
124620897f5cSArne Jansen 				     u64 objectid)
124720897f5cSArne Jansen {
12489b7a2440SDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
124920897f5cSArne Jansen 	struct extent_buffer *leaf;
125020897f5cSArne Jansen 	struct btrfs_root *tree_root = fs_info->tree_root;
125120897f5cSArne Jansen 	struct btrfs_root *root;
125220897f5cSArne Jansen 	struct btrfs_key key;
1253b89f6d1fSFilipe Manana 	unsigned int nofs_flag;
125420897f5cSArne Jansen 	int ret = 0;
125520897f5cSArne Jansen 
1256b89f6d1fSFilipe Manana 	/*
1257b89f6d1fSFilipe Manana 	 * We're holding a transaction handle, so use a NOFS memory allocation
1258b89f6d1fSFilipe Manana 	 * context to avoid deadlock if reclaim happens.
1259b89f6d1fSFilipe Manana 	 */
1260b89f6d1fSFilipe Manana 	nofs_flag = memalloc_nofs_save();
126196dfcb46SJosef Bacik 	root = btrfs_alloc_root(fs_info, objectid, GFP_KERNEL);
1262b89f6d1fSFilipe Manana 	memalloc_nofs_restore(nofs_flag);
126320897f5cSArne Jansen 	if (!root)
126420897f5cSArne Jansen 		return ERR_PTR(-ENOMEM);
126520897f5cSArne Jansen 
126620897f5cSArne Jansen 	root->root_key.objectid = objectid;
126720897f5cSArne Jansen 	root->root_key.type = BTRFS_ROOT_ITEM_KEY;
126820897f5cSArne Jansen 	root->root_key.offset = 0;
126920897f5cSArne Jansen 
12709631e4ccSJosef Bacik 	leaf = btrfs_alloc_tree_block(trans, root, 0, objectid, NULL, 0, 0, 0,
12719631e4ccSJosef Bacik 				      BTRFS_NESTING_NORMAL);
127220897f5cSArne Jansen 	if (IS_ERR(leaf)) {
127320897f5cSArne Jansen 		ret = PTR_ERR(leaf);
12741dd05682STsutomu Itoh 		leaf = NULL;
12758a6a87cdSBoris Burkov 		goto fail_unlock;
127620897f5cSArne Jansen 	}
127720897f5cSArne Jansen 
127820897f5cSArne Jansen 	root->node = leaf;
127920897f5cSArne Jansen 	btrfs_mark_buffer_dirty(leaf);
128020897f5cSArne Jansen 
128120897f5cSArne Jansen 	root->commit_root = btrfs_root_node(root);
128227cdeb70SMiao Xie 	set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
128320897f5cSArne Jansen 
1284f944d2cbSDavid Sterba 	btrfs_set_root_flags(&root->root_item, 0);
1285f944d2cbSDavid Sterba 	btrfs_set_root_limit(&root->root_item, 0);
128620897f5cSArne Jansen 	btrfs_set_root_bytenr(&root->root_item, leaf->start);
128720897f5cSArne Jansen 	btrfs_set_root_generation(&root->root_item, trans->transid);
128820897f5cSArne Jansen 	btrfs_set_root_level(&root->root_item, 0);
128920897f5cSArne Jansen 	btrfs_set_root_refs(&root->root_item, 1);
129020897f5cSArne Jansen 	btrfs_set_root_used(&root->root_item, leaf->len);
129120897f5cSArne Jansen 	btrfs_set_root_last_snapshot(&root->root_item, 0);
129220897f5cSArne Jansen 	btrfs_set_root_dirid(&root->root_item, 0);
129333d85fdaSQu Wenruo 	if (is_fstree(objectid))
1294807fc790SAndy Shevchenko 		generate_random_guid(root->root_item.uuid);
1295807fc790SAndy Shevchenko 	else
1296807fc790SAndy Shevchenko 		export_guid(root->root_item.uuid, &guid_null);
1297c8422684SDavid Sterba 	btrfs_set_root_drop_level(&root->root_item, 0);
129820897f5cSArne Jansen 
12998a6a87cdSBoris Burkov 	btrfs_tree_unlock(leaf);
13008a6a87cdSBoris Burkov 
130120897f5cSArne Jansen 	key.objectid = objectid;
130220897f5cSArne Jansen 	key.type = BTRFS_ROOT_ITEM_KEY;
130320897f5cSArne Jansen 	key.offset = 0;
130420897f5cSArne Jansen 	ret = btrfs_insert_root(trans, tree_root, &key, &root->root_item);
130520897f5cSArne Jansen 	if (ret)
130620897f5cSArne Jansen 		goto fail;
130720897f5cSArne Jansen 
130820897f5cSArne Jansen 	return root;
13091dd05682STsutomu Itoh 
13108a6a87cdSBoris Burkov fail_unlock:
13118c38938cSJosef Bacik 	if (leaf)
13121dd05682STsutomu Itoh 		btrfs_tree_unlock(leaf);
13138a6a87cdSBoris Burkov fail:
131400246528SJosef Bacik 	btrfs_put_root(root);
13151dd05682STsutomu Itoh 
13161dd05682STsutomu Itoh 	return ERR_PTR(ret);
131720897f5cSArne Jansen }
131820897f5cSArne Jansen 
13197237f183SYan Zheng static struct btrfs_root *alloc_log_tree(struct btrfs_trans_handle *trans,
1320e02119d5SChris Mason 					 struct btrfs_fs_info *fs_info)
13210f7d52f4SChris Mason {
13220f7d52f4SChris Mason 	struct btrfs_root *root;
1323e02119d5SChris Mason 
132496dfcb46SJosef Bacik 	root = btrfs_alloc_root(fs_info, BTRFS_TREE_LOG_OBJECTID, GFP_NOFS);
1325e02119d5SChris Mason 	if (!root)
13267237f183SYan Zheng 		return ERR_PTR(-ENOMEM);
1327e02119d5SChris Mason 
1328e02119d5SChris Mason 	root->root_key.objectid = BTRFS_TREE_LOG_OBJECTID;
1329e02119d5SChris Mason 	root->root_key.type = BTRFS_ROOT_ITEM_KEY;
1330e02119d5SChris Mason 	root->root_key.offset = BTRFS_TREE_LOG_OBJECTID;
133127cdeb70SMiao Xie 
13326ab6ebb7SNaohiro Aota 	return root;
13336ab6ebb7SNaohiro Aota }
13346ab6ebb7SNaohiro Aota 
13356ab6ebb7SNaohiro Aota int btrfs_alloc_log_tree_node(struct btrfs_trans_handle *trans,
13366ab6ebb7SNaohiro Aota 			      struct btrfs_root *root)
13376ab6ebb7SNaohiro Aota {
13386ab6ebb7SNaohiro Aota 	struct extent_buffer *leaf;
13396ab6ebb7SNaohiro Aota 
13407237f183SYan Zheng 	/*
134192a7cc42SQu Wenruo 	 * DON'T set SHAREABLE bit for log trees.
134227cdeb70SMiao Xie 	 *
134392a7cc42SQu Wenruo 	 * Log trees are not exposed to user space thus can't be snapshotted,
134492a7cc42SQu Wenruo 	 * and they go away before a real commit is actually done.
134592a7cc42SQu Wenruo 	 *
134692a7cc42SQu Wenruo 	 * They do store pointers to file data extents, and those reference
134792a7cc42SQu Wenruo 	 * counts still get updated (along with back refs to the log tree).
13487237f183SYan Zheng 	 */
1349e02119d5SChris Mason 
13504d75f8a9SDavid Sterba 	leaf = btrfs_alloc_tree_block(trans, root, 0, BTRFS_TREE_LOG_OBJECTID,
13519631e4ccSJosef Bacik 			NULL, 0, 0, 0, BTRFS_NESTING_NORMAL);
13526ab6ebb7SNaohiro Aota 	if (IS_ERR(leaf))
13536ab6ebb7SNaohiro Aota 		return PTR_ERR(leaf);
1354e02119d5SChris Mason 
13557237f183SYan Zheng 	root->node = leaf;
1356e02119d5SChris Mason 
1357e02119d5SChris Mason 	btrfs_mark_buffer_dirty(root->node);
1358e02119d5SChris Mason 	btrfs_tree_unlock(root->node);
13596ab6ebb7SNaohiro Aota 
13606ab6ebb7SNaohiro Aota 	return 0;
13617237f183SYan Zheng }
13627237f183SYan Zheng 
13637237f183SYan Zheng int btrfs_init_log_root_tree(struct btrfs_trans_handle *trans,
13647237f183SYan Zheng 			     struct btrfs_fs_info *fs_info)
13657237f183SYan Zheng {
13667237f183SYan Zheng 	struct btrfs_root *log_root;
13677237f183SYan Zheng 
13687237f183SYan Zheng 	log_root = alloc_log_tree(trans, fs_info);
13697237f183SYan Zheng 	if (IS_ERR(log_root))
13707237f183SYan Zheng 		return PTR_ERR(log_root);
13716ab6ebb7SNaohiro Aota 
13723ddebf27SNaohiro Aota 	if (!btrfs_is_zoned(fs_info)) {
13733ddebf27SNaohiro Aota 		int ret = btrfs_alloc_log_tree_node(trans, log_root);
13743ddebf27SNaohiro Aota 
13756ab6ebb7SNaohiro Aota 		if (ret) {
13766ab6ebb7SNaohiro Aota 			btrfs_put_root(log_root);
13776ab6ebb7SNaohiro Aota 			return ret;
13786ab6ebb7SNaohiro Aota 		}
13793ddebf27SNaohiro Aota 	}
13806ab6ebb7SNaohiro Aota 
13817237f183SYan Zheng 	WARN_ON(fs_info->log_root_tree);
13827237f183SYan Zheng 	fs_info->log_root_tree = log_root;
13837237f183SYan Zheng 	return 0;
13847237f183SYan Zheng }
13857237f183SYan Zheng 
13867237f183SYan Zheng int btrfs_add_log_tree(struct btrfs_trans_handle *trans,
13877237f183SYan Zheng 		       struct btrfs_root *root)
13887237f183SYan Zheng {
13890b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
13907237f183SYan Zheng 	struct btrfs_root *log_root;
13917237f183SYan Zheng 	struct btrfs_inode_item *inode_item;
13926ab6ebb7SNaohiro Aota 	int ret;
13937237f183SYan Zheng 
13940b246afaSJeff Mahoney 	log_root = alloc_log_tree(trans, fs_info);
13957237f183SYan Zheng 	if (IS_ERR(log_root))
13967237f183SYan Zheng 		return PTR_ERR(log_root);
13977237f183SYan Zheng 
13986ab6ebb7SNaohiro Aota 	ret = btrfs_alloc_log_tree_node(trans, log_root);
13996ab6ebb7SNaohiro Aota 	if (ret) {
14006ab6ebb7SNaohiro Aota 		btrfs_put_root(log_root);
14016ab6ebb7SNaohiro Aota 		return ret;
14026ab6ebb7SNaohiro Aota 	}
14036ab6ebb7SNaohiro Aota 
14047237f183SYan Zheng 	log_root->last_trans = trans->transid;
14057237f183SYan Zheng 	log_root->root_key.offset = root->root_key.objectid;
14067237f183SYan Zheng 
14077237f183SYan Zheng 	inode_item = &log_root->root_item.inode;
14083cae210fSQu Wenruo 	btrfs_set_stack_inode_generation(inode_item, 1);
14093cae210fSQu Wenruo 	btrfs_set_stack_inode_size(inode_item, 3);
14103cae210fSQu Wenruo 	btrfs_set_stack_inode_nlink(inode_item, 1);
1411da17066cSJeff Mahoney 	btrfs_set_stack_inode_nbytes(inode_item,
14120b246afaSJeff Mahoney 				     fs_info->nodesize);
14133cae210fSQu Wenruo 	btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
14147237f183SYan Zheng 
14155d4f98a2SYan Zheng 	btrfs_set_root_node(&log_root->root_item, log_root->node);
14167237f183SYan Zheng 
14177237f183SYan Zheng 	WARN_ON(root->log_root);
14187237f183SYan Zheng 	root->log_root = log_root;
14197237f183SYan Zheng 	root->log_transid = 0;
1420d1433debSMiao Xie 	root->log_transid_committed = -1;
1421257c62e1SChris Mason 	root->last_log_commit = 0;
1422e02119d5SChris Mason 	return 0;
1423e02119d5SChris Mason }
1424e02119d5SChris Mason 
142549d11beaSJosef Bacik static struct btrfs_root *read_tree_root_path(struct btrfs_root *tree_root,
142649d11beaSJosef Bacik 					      struct btrfs_path *path,
1427cb517eabSMiao Xie 					      struct btrfs_key *key)
1428e02119d5SChris Mason {
1429e02119d5SChris Mason 	struct btrfs_root *root;
1430e02119d5SChris Mason 	struct btrfs_fs_info *fs_info = tree_root->fs_info;
143184234f3aSYan Zheng 	u64 generation;
1432cb517eabSMiao Xie 	int ret;
1433581c1760SQu Wenruo 	int level;
1434cb517eabSMiao Xie 
143596dfcb46SJosef Bacik 	root = btrfs_alloc_root(fs_info, key->objectid, GFP_NOFS);
143649d11beaSJosef Bacik 	if (!root)
143749d11beaSJosef Bacik 		return ERR_PTR(-ENOMEM);
14380f7d52f4SChris Mason 
1439cb517eabSMiao Xie 	ret = btrfs_find_root(tree_root, key, path,
1440cb517eabSMiao Xie 			      &root->root_item, &root->root_key);
14410f7d52f4SChris Mason 	if (ret) {
144213a8a7c8SYan, Zheng 		if (ret > 0)
144313a8a7c8SYan, Zheng 			ret = -ENOENT;
144449d11beaSJosef Bacik 		goto fail;
14450f7d52f4SChris Mason 	}
144613a8a7c8SYan, Zheng 
144784234f3aSYan Zheng 	generation = btrfs_root_generation(&root->root_item);
1448581c1760SQu Wenruo 	level = btrfs_root_level(&root->root_item);
14492ff7e61eSJeff Mahoney 	root->node = read_tree_block(fs_info,
14502ff7e61eSJeff Mahoney 				     btrfs_root_bytenr(&root->root_item),
14511b7ec85eSJosef Bacik 				     key->objectid, generation, level, NULL);
145264c043deSLiu Bo 	if (IS_ERR(root->node)) {
145364c043deSLiu Bo 		ret = PTR_ERR(root->node);
14548c38938cSJosef Bacik 		root->node = NULL;
145549d11beaSJosef Bacik 		goto fail;
1456cb517eabSMiao Xie 	} else if (!btrfs_buffer_uptodate(root->node, generation, 0)) {
1457cb517eabSMiao Xie 		ret = -EIO;
145849d11beaSJosef Bacik 		goto fail;
1459416bc658SJosef Bacik 	}
14605d4f98a2SYan Zheng 	root->commit_root = btrfs_root_node(root);
1461cb517eabSMiao Xie 	return root;
146249d11beaSJosef Bacik fail:
146300246528SJosef Bacik 	btrfs_put_root(root);
146449d11beaSJosef Bacik 	return ERR_PTR(ret);
146549d11beaSJosef Bacik }
146649d11beaSJosef Bacik 
146749d11beaSJosef Bacik struct btrfs_root *btrfs_read_tree_root(struct btrfs_root *tree_root,
146849d11beaSJosef Bacik 					struct btrfs_key *key)
146949d11beaSJosef Bacik {
147049d11beaSJosef Bacik 	struct btrfs_root *root;
147149d11beaSJosef Bacik 	struct btrfs_path *path;
147249d11beaSJosef Bacik 
147349d11beaSJosef Bacik 	path = btrfs_alloc_path();
147449d11beaSJosef Bacik 	if (!path)
147549d11beaSJosef Bacik 		return ERR_PTR(-ENOMEM);
147649d11beaSJosef Bacik 	root = read_tree_root_path(tree_root, path, key);
147749d11beaSJosef Bacik 	btrfs_free_path(path);
147849d11beaSJosef Bacik 
147949d11beaSJosef Bacik 	return root;
1480cb517eabSMiao Xie }
1481cb517eabSMiao Xie 
14822dfb1e43SQu Wenruo /*
14832dfb1e43SQu Wenruo  * Initialize subvolume root in-memory structure
14842dfb1e43SQu Wenruo  *
14852dfb1e43SQu Wenruo  * @anon_dev:	anonymous device to attach to the root, if zero, allocate new
14862dfb1e43SQu Wenruo  */
14872dfb1e43SQu Wenruo static int btrfs_init_fs_root(struct btrfs_root *root, dev_t anon_dev)
1488cb517eabSMiao Xie {
1489cb517eabSMiao Xie 	int ret;
1490dcc3eb96SNikolay Borisov 	unsigned int nofs_flag;
1491cb517eabSMiao Xie 
1492dcc3eb96SNikolay Borisov 	/*
1493dcc3eb96SNikolay Borisov 	 * We might be called under a transaction (e.g. indirect backref
1494dcc3eb96SNikolay Borisov 	 * resolution) which could deadlock if it triggers memory reclaim
1495dcc3eb96SNikolay Borisov 	 */
1496dcc3eb96SNikolay Borisov 	nofs_flag = memalloc_nofs_save();
1497dcc3eb96SNikolay Borisov 	ret = btrfs_drew_lock_init(&root->snapshot_lock);
1498dcc3eb96SNikolay Borisov 	memalloc_nofs_restore(nofs_flag);
1499dcc3eb96SNikolay Borisov 	if (ret)
15008257b2dcSMiao Xie 		goto fail;
15018257b2dcSMiao Xie 
1502aeb935a4SQu Wenruo 	if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID &&
1503aeb935a4SQu Wenruo 	    root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID) {
150492a7cc42SQu Wenruo 		set_bit(BTRFS_ROOT_SHAREABLE, &root->state);
1505f39e4571SJosef Bacik 		btrfs_check_and_init_root_item(&root->root_item);
1506f39e4571SJosef Bacik 	}
1507f39e4571SJosef Bacik 
1508851fd730SQu Wenruo 	/*
1509851fd730SQu Wenruo 	 * Don't assign anonymous block device to roots that are not exposed to
1510851fd730SQu Wenruo 	 * userspace, the id pool is limited to 1M
1511851fd730SQu Wenruo 	 */
1512851fd730SQu Wenruo 	if (is_fstree(root->root_key.objectid) &&
1513851fd730SQu Wenruo 	    btrfs_root_refs(&root->root_item) > 0) {
15142dfb1e43SQu Wenruo 		if (!anon_dev) {
1515cb517eabSMiao Xie 			ret = get_anon_bdev(&root->anon_dev);
1516cb517eabSMiao Xie 			if (ret)
1517876d2cf1SLiu Bo 				goto fail;
15182dfb1e43SQu Wenruo 		} else {
15192dfb1e43SQu Wenruo 			root->anon_dev = anon_dev;
15202dfb1e43SQu Wenruo 		}
1521851fd730SQu Wenruo 	}
1522f32e48e9SChandan Rajendra 
1523f32e48e9SChandan Rajendra 	mutex_lock(&root->objectid_mutex);
1524453e4873SNikolay Borisov 	ret = btrfs_init_root_free_objectid(root);
1525f32e48e9SChandan Rajendra 	if (ret) {
1526f32e48e9SChandan Rajendra 		mutex_unlock(&root->objectid_mutex);
1527876d2cf1SLiu Bo 		goto fail;
1528f32e48e9SChandan Rajendra 	}
1529f32e48e9SChandan Rajendra 
15306b8fad57SNikolay Borisov 	ASSERT(root->free_objectid <= BTRFS_LAST_FREE_OBJECTID);
1531f32e48e9SChandan Rajendra 
1532f32e48e9SChandan Rajendra 	mutex_unlock(&root->objectid_mutex);
1533f32e48e9SChandan Rajendra 
1534cb517eabSMiao Xie 	return 0;
1535cb517eabSMiao Xie fail:
153684db5ccfSDavid Sterba 	/* The caller is responsible to call btrfs_free_fs_root */
1537cb517eabSMiao Xie 	return ret;
1538cb517eabSMiao Xie }
1539cb517eabSMiao Xie 
1540a98db0f3SJosef Bacik static struct btrfs_root *btrfs_lookup_fs_root(struct btrfs_fs_info *fs_info,
1541cb517eabSMiao Xie 					       u64 root_id)
1542cb517eabSMiao Xie {
1543cb517eabSMiao Xie 	struct btrfs_root *root;
1544cb517eabSMiao Xie 
1545cb517eabSMiao Xie 	spin_lock(&fs_info->fs_roots_radix_lock);
1546cb517eabSMiao Xie 	root = radix_tree_lookup(&fs_info->fs_roots_radix,
1547cb517eabSMiao Xie 				 (unsigned long)root_id);
1548bc44d7c4SJosef Bacik 	if (root)
154900246528SJosef Bacik 		root = btrfs_grab_root(root);
1550cb517eabSMiao Xie 	spin_unlock(&fs_info->fs_roots_radix_lock);
1551cb517eabSMiao Xie 	return root;
1552cb517eabSMiao Xie }
1553cb517eabSMiao Xie 
155449d11beaSJosef Bacik static struct btrfs_root *btrfs_get_global_root(struct btrfs_fs_info *fs_info,
155549d11beaSJosef Bacik 						u64 objectid)
155649d11beaSJosef Bacik {
155749d11beaSJosef Bacik 	if (objectid == BTRFS_ROOT_TREE_OBJECTID)
155849d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->tree_root);
155949d11beaSJosef Bacik 	if (objectid == BTRFS_EXTENT_TREE_OBJECTID)
156049d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->extent_root);
156149d11beaSJosef Bacik 	if (objectid == BTRFS_CHUNK_TREE_OBJECTID)
156249d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->chunk_root);
156349d11beaSJosef Bacik 	if (objectid == BTRFS_DEV_TREE_OBJECTID)
156449d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->dev_root);
156549d11beaSJosef Bacik 	if (objectid == BTRFS_CSUM_TREE_OBJECTID)
156649d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->csum_root);
156749d11beaSJosef Bacik 	if (objectid == BTRFS_QUOTA_TREE_OBJECTID)
156849d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->quota_root) ?
156949d11beaSJosef Bacik 			fs_info->quota_root : ERR_PTR(-ENOENT);
157049d11beaSJosef Bacik 	if (objectid == BTRFS_UUID_TREE_OBJECTID)
157149d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->uuid_root) ?
157249d11beaSJosef Bacik 			fs_info->uuid_root : ERR_PTR(-ENOENT);
157349d11beaSJosef Bacik 	if (objectid == BTRFS_FREE_SPACE_TREE_OBJECTID)
157449d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->free_space_root) ?
157549d11beaSJosef Bacik 			fs_info->free_space_root : ERR_PTR(-ENOENT);
157649d11beaSJosef Bacik 	return NULL;
157749d11beaSJosef Bacik }
157849d11beaSJosef Bacik 
1579cb517eabSMiao Xie int btrfs_insert_fs_root(struct btrfs_fs_info *fs_info,
1580cb517eabSMiao Xie 			 struct btrfs_root *root)
1581cb517eabSMiao Xie {
1582cb517eabSMiao Xie 	int ret;
1583cb517eabSMiao Xie 
1584e1860a77SDavid Sterba 	ret = radix_tree_preload(GFP_NOFS);
1585cb517eabSMiao Xie 	if (ret)
1586cb517eabSMiao Xie 		return ret;
1587cb517eabSMiao Xie 
1588cb517eabSMiao Xie 	spin_lock(&fs_info->fs_roots_radix_lock);
1589cb517eabSMiao Xie 	ret = radix_tree_insert(&fs_info->fs_roots_radix,
1590cb517eabSMiao Xie 				(unsigned long)root->root_key.objectid,
1591cb517eabSMiao Xie 				root);
1592af01d2e5SJosef Bacik 	if (ret == 0) {
159300246528SJosef Bacik 		btrfs_grab_root(root);
159427cdeb70SMiao Xie 		set_bit(BTRFS_ROOT_IN_RADIX, &root->state);
1595af01d2e5SJosef Bacik 	}
1596cb517eabSMiao Xie 	spin_unlock(&fs_info->fs_roots_radix_lock);
1597cb517eabSMiao Xie 	radix_tree_preload_end();
1598cb517eabSMiao Xie 
1599cb517eabSMiao Xie 	return ret;
1600cb517eabSMiao Xie }
1601cb517eabSMiao Xie 
1602bd647ce3SJosef Bacik void btrfs_check_leaked_roots(struct btrfs_fs_info *fs_info)
1603bd647ce3SJosef Bacik {
1604bd647ce3SJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
1605bd647ce3SJosef Bacik 	struct btrfs_root *root;
1606bd647ce3SJosef Bacik 
1607bd647ce3SJosef Bacik 	while (!list_empty(&fs_info->allocated_roots)) {
1608457f1864SJosef Bacik 		char buf[BTRFS_ROOT_NAME_BUF_LEN];
1609457f1864SJosef Bacik 
1610bd647ce3SJosef Bacik 		root = list_first_entry(&fs_info->allocated_roots,
1611bd647ce3SJosef Bacik 					struct btrfs_root, leak_list);
1612457f1864SJosef Bacik 		btrfs_err(fs_info, "leaked root %s refcount %d",
161371008734SJosef Bacik 			  btrfs_root_name(&root->root_key, buf),
1614bd647ce3SJosef Bacik 			  refcount_read(&root->refs));
1615bd647ce3SJosef Bacik 		while (refcount_read(&root->refs) > 1)
161600246528SJosef Bacik 			btrfs_put_root(root);
161700246528SJosef Bacik 		btrfs_put_root(root);
1618bd647ce3SJosef Bacik 	}
1619bd647ce3SJosef Bacik #endif
1620bd647ce3SJosef Bacik }
1621bd647ce3SJosef Bacik 
16220d4b0463SJosef Bacik void btrfs_free_fs_info(struct btrfs_fs_info *fs_info)
16230d4b0463SJosef Bacik {
1624141386e1SJosef Bacik 	percpu_counter_destroy(&fs_info->dirty_metadata_bytes);
1625141386e1SJosef Bacik 	percpu_counter_destroy(&fs_info->delalloc_bytes);
16265deb17e1SJosef Bacik 	percpu_counter_destroy(&fs_info->ordered_bytes);
1627141386e1SJosef Bacik 	percpu_counter_destroy(&fs_info->dev_replace.bio_counter);
1628141386e1SJosef Bacik 	btrfs_free_csum_hash(fs_info);
1629141386e1SJosef Bacik 	btrfs_free_stripe_hash_table(fs_info);
1630141386e1SJosef Bacik 	btrfs_free_ref_cache(fs_info);
16310d4b0463SJosef Bacik 	kfree(fs_info->balance_ctl);
16320d4b0463SJosef Bacik 	kfree(fs_info->delayed_root);
163300246528SJosef Bacik 	btrfs_put_root(fs_info->extent_root);
163400246528SJosef Bacik 	btrfs_put_root(fs_info->tree_root);
163500246528SJosef Bacik 	btrfs_put_root(fs_info->chunk_root);
163600246528SJosef Bacik 	btrfs_put_root(fs_info->dev_root);
163700246528SJosef Bacik 	btrfs_put_root(fs_info->csum_root);
163800246528SJosef Bacik 	btrfs_put_root(fs_info->quota_root);
163900246528SJosef Bacik 	btrfs_put_root(fs_info->uuid_root);
164000246528SJosef Bacik 	btrfs_put_root(fs_info->free_space_root);
164100246528SJosef Bacik 	btrfs_put_root(fs_info->fs_root);
1642aeb935a4SQu Wenruo 	btrfs_put_root(fs_info->data_reloc_root);
1643bd647ce3SJosef Bacik 	btrfs_check_leaked_roots(fs_info);
16443fd63727SJosef Bacik 	btrfs_extent_buffer_leak_debug_check(fs_info);
16450d4b0463SJosef Bacik 	kfree(fs_info->super_copy);
16460d4b0463SJosef Bacik 	kfree(fs_info->super_for_commit);
16478481dd80SQu Wenruo 	kfree(fs_info->subpage_info);
16480d4b0463SJosef Bacik 	kvfree(fs_info);
16490d4b0463SJosef Bacik }
16500d4b0463SJosef Bacik 
16510d4b0463SJosef Bacik 
16522dfb1e43SQu Wenruo /*
16532dfb1e43SQu Wenruo  * Get an in-memory reference of a root structure.
16542dfb1e43SQu Wenruo  *
16552dfb1e43SQu Wenruo  * For essential trees like root/extent tree, we grab it from fs_info directly.
16562dfb1e43SQu Wenruo  * For subvolume trees, we check the cached filesystem roots first. If not
16572dfb1e43SQu Wenruo  * found, then read it from disk and add it to cached fs roots.
16582dfb1e43SQu Wenruo  *
16592dfb1e43SQu Wenruo  * Caller should release the root by calling btrfs_put_root() after the usage.
16602dfb1e43SQu Wenruo  *
16612dfb1e43SQu Wenruo  * NOTE: Reloc and log trees can't be read by this function as they share the
16622dfb1e43SQu Wenruo  *	 same root objectid.
16632dfb1e43SQu Wenruo  *
16642dfb1e43SQu Wenruo  * @objectid:	root id
16652dfb1e43SQu Wenruo  * @anon_dev:	preallocated anonymous block device number for new roots,
16662dfb1e43SQu Wenruo  * 		pass 0 for new allocation.
16672dfb1e43SQu Wenruo  * @check_ref:	whether to check root item references, If true, return -ENOENT
16682dfb1e43SQu Wenruo  *		for orphan roots
16692dfb1e43SQu Wenruo  */
16702dfb1e43SQu Wenruo static struct btrfs_root *btrfs_get_root_ref(struct btrfs_fs_info *fs_info,
16712dfb1e43SQu Wenruo 					     u64 objectid, dev_t anon_dev,
16722dfb1e43SQu Wenruo 					     bool check_ref)
16735eda7b5eSChris Mason {
16745eda7b5eSChris Mason 	struct btrfs_root *root;
1675381cf658SDavid Sterba 	struct btrfs_path *path;
16761d4c08e0SDavid Sterba 	struct btrfs_key key;
16775eda7b5eSChris Mason 	int ret;
16785eda7b5eSChris Mason 
167949d11beaSJosef Bacik 	root = btrfs_get_global_root(fs_info, objectid);
168049d11beaSJosef Bacik 	if (root)
168149d11beaSJosef Bacik 		return root;
16824df27c4dSYan, Zheng again:
168356e9357aSDavid Sterba 	root = btrfs_lookup_fs_root(fs_info, objectid);
168448475471SStefan Behrens 	if (root) {
16852dfb1e43SQu Wenruo 		/* Shouldn't get preallocated anon_dev for cached roots */
16862dfb1e43SQu Wenruo 		ASSERT(!anon_dev);
1687bc44d7c4SJosef Bacik 		if (check_ref && btrfs_root_refs(&root->root_item) == 0) {
168800246528SJosef Bacik 			btrfs_put_root(root);
168948475471SStefan Behrens 			return ERR_PTR(-ENOENT);
1690bc44d7c4SJosef Bacik 		}
16915eda7b5eSChris Mason 		return root;
169248475471SStefan Behrens 	}
16935eda7b5eSChris Mason 
169456e9357aSDavid Sterba 	key.objectid = objectid;
169556e9357aSDavid Sterba 	key.type = BTRFS_ROOT_ITEM_KEY;
169656e9357aSDavid Sterba 	key.offset = (u64)-1;
169756e9357aSDavid Sterba 	root = btrfs_read_tree_root(fs_info->tree_root, &key);
16985eda7b5eSChris Mason 	if (IS_ERR(root))
16995eda7b5eSChris Mason 		return root;
17003394e160SChris Mason 
1701c00869f1SMiao Xie 	if (check_ref && btrfs_root_refs(&root->root_item) == 0) {
1702d68fc57bSYan, Zheng 		ret = -ENOENT;
1703d68fc57bSYan, Zheng 		goto fail;
1704d68fc57bSYan, Zheng 	}
1705d68fc57bSYan, Zheng 
17062dfb1e43SQu Wenruo 	ret = btrfs_init_fs_root(root, anon_dev);
1707cb517eabSMiao Xie 	if (ret)
1708cb517eabSMiao Xie 		goto fail;
1709cb517eabSMiao Xie 
1710381cf658SDavid Sterba 	path = btrfs_alloc_path();
1711381cf658SDavid Sterba 	if (!path) {
1712381cf658SDavid Sterba 		ret = -ENOMEM;
1713381cf658SDavid Sterba 		goto fail;
1714381cf658SDavid Sterba 	}
17151d4c08e0SDavid Sterba 	key.objectid = BTRFS_ORPHAN_OBJECTID;
17161d4c08e0SDavid Sterba 	key.type = BTRFS_ORPHAN_ITEM_KEY;
171756e9357aSDavid Sterba 	key.offset = objectid;
17181d4c08e0SDavid Sterba 
17191d4c08e0SDavid Sterba 	ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
1720381cf658SDavid Sterba 	btrfs_free_path(path);
1721d68fc57bSYan, Zheng 	if (ret < 0)
1722d68fc57bSYan, Zheng 		goto fail;
1723d68fc57bSYan, Zheng 	if (ret == 0)
172427cdeb70SMiao Xie 		set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state);
1725d68fc57bSYan, Zheng 
1726cb517eabSMiao Xie 	ret = btrfs_insert_fs_root(fs_info, root);
17270f7d52f4SChris Mason 	if (ret) {
172800246528SJosef Bacik 		btrfs_put_root(root);
17294785e24fSJosef Bacik 		if (ret == -EEXIST)
17304df27c4dSYan, Zheng 			goto again;
17314df27c4dSYan, Zheng 		goto fail;
17324df27c4dSYan, Zheng 	}
1733edbd8d4eSChris Mason 	return root;
17344df27c4dSYan, Zheng fail:
17358c38938cSJosef Bacik 	btrfs_put_root(root);
17364df27c4dSYan, Zheng 	return ERR_PTR(ret);
1737edbd8d4eSChris Mason }
1738edbd8d4eSChris Mason 
17392dfb1e43SQu Wenruo /*
17402dfb1e43SQu Wenruo  * Get in-memory reference of a root structure
17412dfb1e43SQu Wenruo  *
17422dfb1e43SQu Wenruo  * @objectid:	tree objectid
17432dfb1e43SQu Wenruo  * @check_ref:	if set, verify that the tree exists and the item has at least
17442dfb1e43SQu Wenruo  *		one reference
17452dfb1e43SQu Wenruo  */
17462dfb1e43SQu Wenruo struct btrfs_root *btrfs_get_fs_root(struct btrfs_fs_info *fs_info,
17472dfb1e43SQu Wenruo 				     u64 objectid, bool check_ref)
17482dfb1e43SQu Wenruo {
17492dfb1e43SQu Wenruo 	return btrfs_get_root_ref(fs_info, objectid, 0, check_ref);
17502dfb1e43SQu Wenruo }
17512dfb1e43SQu Wenruo 
17522dfb1e43SQu Wenruo /*
17532dfb1e43SQu Wenruo  * Get in-memory reference of a root structure, created as new, optionally pass
17542dfb1e43SQu Wenruo  * the anonymous block device id
17552dfb1e43SQu Wenruo  *
17562dfb1e43SQu Wenruo  * @objectid:	tree objectid
17572dfb1e43SQu Wenruo  * @anon_dev:	if zero, allocate a new anonymous block device or use the
17582dfb1e43SQu Wenruo  *		parameter value
17592dfb1e43SQu Wenruo  */
17602dfb1e43SQu Wenruo struct btrfs_root *btrfs_get_new_fs_root(struct btrfs_fs_info *fs_info,
17612dfb1e43SQu Wenruo 					 u64 objectid, dev_t anon_dev)
17622dfb1e43SQu Wenruo {
17632dfb1e43SQu Wenruo 	return btrfs_get_root_ref(fs_info, objectid, anon_dev, true);
17642dfb1e43SQu Wenruo }
17652dfb1e43SQu Wenruo 
17668b712842SChris Mason /*
176749d11beaSJosef Bacik  * btrfs_get_fs_root_commit_root - return a root for the given objectid
176849d11beaSJosef Bacik  * @fs_info:	the fs_info
176949d11beaSJosef Bacik  * @objectid:	the objectid we need to lookup
177049d11beaSJosef Bacik  *
177149d11beaSJosef Bacik  * This is exclusively used for backref walking, and exists specifically because
177249d11beaSJosef Bacik  * of how qgroups does lookups.  Qgroups will do a backref lookup at delayed ref
177349d11beaSJosef Bacik  * creation time, which means we may have to read the tree_root in order to look
177449d11beaSJosef Bacik  * up a fs root that is not in memory.  If the root is not in memory we will
177549d11beaSJosef Bacik  * read the tree root commit root and look up the fs root from there.  This is a
177649d11beaSJosef Bacik  * temporary root, it will not be inserted into the radix tree as it doesn't
177749d11beaSJosef Bacik  * have the most uptodate information, it'll simply be discarded once the
177849d11beaSJosef Bacik  * backref code is finished using the root.
177949d11beaSJosef Bacik  */
178049d11beaSJosef Bacik struct btrfs_root *btrfs_get_fs_root_commit_root(struct btrfs_fs_info *fs_info,
178149d11beaSJosef Bacik 						 struct btrfs_path *path,
178249d11beaSJosef Bacik 						 u64 objectid)
178349d11beaSJosef Bacik {
178449d11beaSJosef Bacik 	struct btrfs_root *root;
178549d11beaSJosef Bacik 	struct btrfs_key key;
178649d11beaSJosef Bacik 
178749d11beaSJosef Bacik 	ASSERT(path->search_commit_root && path->skip_locking);
178849d11beaSJosef Bacik 
178949d11beaSJosef Bacik 	/*
179049d11beaSJosef Bacik 	 * This can return -ENOENT if we ask for a root that doesn't exist, but
179149d11beaSJosef Bacik 	 * since this is called via the backref walking code we won't be looking
179249d11beaSJosef Bacik 	 * up a root that doesn't exist, unless there's corruption.  So if root
179349d11beaSJosef Bacik 	 * != NULL just return it.
179449d11beaSJosef Bacik 	 */
179549d11beaSJosef Bacik 	root = btrfs_get_global_root(fs_info, objectid);
179649d11beaSJosef Bacik 	if (root)
179749d11beaSJosef Bacik 		return root;
179849d11beaSJosef Bacik 
179949d11beaSJosef Bacik 	root = btrfs_lookup_fs_root(fs_info, objectid);
180049d11beaSJosef Bacik 	if (root)
180149d11beaSJosef Bacik 		return root;
180249d11beaSJosef Bacik 
180349d11beaSJosef Bacik 	key.objectid = objectid;
180449d11beaSJosef Bacik 	key.type = BTRFS_ROOT_ITEM_KEY;
180549d11beaSJosef Bacik 	key.offset = (u64)-1;
180649d11beaSJosef Bacik 	root = read_tree_root_path(fs_info->tree_root, path, &key);
180749d11beaSJosef Bacik 	btrfs_release_path(path);
180849d11beaSJosef Bacik 
180949d11beaSJosef Bacik 	return root;
181049d11beaSJosef Bacik }
181149d11beaSJosef Bacik 
181249d11beaSJosef Bacik /*
18138b712842SChris Mason  * called by the kthread helper functions to finally call the bio end_io
18148b712842SChris Mason  * functions.  This is where read checksum verification actually happens
18158b712842SChris Mason  */
18168b712842SChris Mason static void end_workqueue_fn(struct btrfs_work *work)
1817ce9adaa5SChris Mason {
1818ce9adaa5SChris Mason 	struct bio *bio;
181997eb6b69SDavid Sterba 	struct btrfs_end_io_wq *end_io_wq;
1820ce9adaa5SChris Mason 
182197eb6b69SDavid Sterba 	end_io_wq = container_of(work, struct btrfs_end_io_wq, work);
1822ce9adaa5SChris Mason 	bio = end_io_wq->bio;
18238b712842SChris Mason 
18244e4cbee9SChristoph Hellwig 	bio->bi_status = end_io_wq->status;
1825ce9adaa5SChris Mason 	bio->bi_private = end_io_wq->private;
1826ce9adaa5SChris Mason 	bio->bi_end_io = end_io_wq->end_io;
18274246a0b6SChristoph Hellwig 	bio_endio(bio);
18289be490f1SOmar Sandoval 	kmem_cache_free(btrfs_end_io_wq_cache, end_io_wq);
1829ce9adaa5SChris Mason }
183044b8bd7eSChris Mason 
1831a74a4b97SChris Mason static int cleaner_kthread(void *arg)
1832a74a4b97SChris Mason {
1833a74a4b97SChris Mason 	struct btrfs_root *root = arg;
18340b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
1835d0278245SMiao Xie 	int again;
1836a74a4b97SChris Mason 
1837d6fd0ae2SOmar Sandoval 	while (1) {
1838d0278245SMiao Xie 		again = 0;
18399d1a2a3aSDavid Sterba 
1840fd340d0fSJosef Bacik 		set_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags);
1841fd340d0fSJosef Bacik 
1842d0278245SMiao Xie 		/* Make the cleaner go to sleep early. */
18432ff7e61eSJeff Mahoney 		if (btrfs_need_cleaner_sleep(fs_info))
1844d0278245SMiao Xie 			goto sleep;
1845d0278245SMiao Xie 
184690c711abSZygo Blaxell 		/*
184790c711abSZygo Blaxell 		 * Do not do anything if we might cause open_ctree() to block
184890c711abSZygo Blaxell 		 * before we have finished mounting the filesystem.
184990c711abSZygo Blaxell 		 */
18500b246afaSJeff Mahoney 		if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
185190c711abSZygo Blaxell 			goto sleep;
185290c711abSZygo Blaxell 
18530b246afaSJeff Mahoney 		if (!mutex_trylock(&fs_info->cleaner_mutex))
1854d0278245SMiao Xie 			goto sleep;
1855d0278245SMiao Xie 
1856dc7f370cSMiao Xie 		/*
1857dc7f370cSMiao Xie 		 * Avoid the problem that we change the status of the fs
1858dc7f370cSMiao Xie 		 * during the above check and trylock.
1859dc7f370cSMiao Xie 		 */
18602ff7e61eSJeff Mahoney 		if (btrfs_need_cleaner_sleep(fs_info)) {
18610b246afaSJeff Mahoney 			mutex_unlock(&fs_info->cleaner_mutex);
1862dc7f370cSMiao Xie 			goto sleep;
1863dc7f370cSMiao Xie 		}
1864dc7f370cSMiao Xie 
18652ff7e61eSJeff Mahoney 		btrfs_run_delayed_iputs(fs_info);
1866c2d6cb16SFilipe Manana 
18679d1a2a3aSDavid Sterba 		again = btrfs_clean_one_deleted_snapshot(root);
18680b246afaSJeff Mahoney 		mutex_unlock(&fs_info->cleaner_mutex);
1869a74a4b97SChris Mason 
1870d0278245SMiao Xie 		/*
187105323cd1SMiao Xie 		 * The defragger has dealt with the R/O remount and umount,
187205323cd1SMiao Xie 		 * needn't do anything special here.
1873d0278245SMiao Xie 		 */
18740b246afaSJeff Mahoney 		btrfs_run_defrag_inodes(fs_info);
187567c5e7d4SFilipe Manana 
187667c5e7d4SFilipe Manana 		/*
1877f3372065SJohannes Thumshirn 		 * Acquires fs_info->reclaim_bgs_lock to avoid racing
187867c5e7d4SFilipe Manana 		 * with relocation (btrfs_relocate_chunk) and relocation
187967c5e7d4SFilipe Manana 		 * acquires fs_info->cleaner_mutex (btrfs_relocate_block_group)
1880f3372065SJohannes Thumshirn 		 * after acquiring fs_info->reclaim_bgs_lock. So we
188167c5e7d4SFilipe Manana 		 * can't hold, nor need to, fs_info->cleaner_mutex when deleting
188267c5e7d4SFilipe Manana 		 * unused block groups.
188367c5e7d4SFilipe Manana 		 */
18840b246afaSJeff Mahoney 		btrfs_delete_unused_bgs(fs_info);
188518bb8bbfSJohannes Thumshirn 
188618bb8bbfSJohannes Thumshirn 		/*
188718bb8bbfSJohannes Thumshirn 		 * Reclaim block groups in the reclaim_bgs list after we deleted
188818bb8bbfSJohannes Thumshirn 		 * all unused block_groups. This possibly gives us some more free
188918bb8bbfSJohannes Thumshirn 		 * space.
189018bb8bbfSJohannes Thumshirn 		 */
189118bb8bbfSJohannes Thumshirn 		btrfs_reclaim_bgs(fs_info);
1892d0278245SMiao Xie sleep:
1893a0a1db70SFilipe Manana 		clear_and_wake_up_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags);
1894d6fd0ae2SOmar Sandoval 		if (kthread_should_park())
1895d6fd0ae2SOmar Sandoval 			kthread_parkme();
1896d6fd0ae2SOmar Sandoval 		if (kthread_should_stop())
1897d6fd0ae2SOmar Sandoval 			return 0;
1898838fe188SJiri Kosina 		if (!again) {
1899a74a4b97SChris Mason 			set_current_state(TASK_INTERRUPTIBLE);
1900a74a4b97SChris Mason 			schedule();
1901a74a4b97SChris Mason 			__set_current_state(TASK_RUNNING);
1902a74a4b97SChris Mason 		}
1903da288d28SFilipe Manana 	}
1904a74a4b97SChris Mason }
1905a74a4b97SChris Mason 
1906a74a4b97SChris Mason static int transaction_kthread(void *arg)
1907a74a4b97SChris Mason {
1908a74a4b97SChris Mason 	struct btrfs_root *root = arg;
19090b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
1910a74a4b97SChris Mason 	struct btrfs_trans_handle *trans;
1911a74a4b97SChris Mason 	struct btrfs_transaction *cur;
19128929ecfaSYan, Zheng 	u64 transid;
1913643900beSNikolay Borisov 	time64_t delta;
1914a74a4b97SChris Mason 	unsigned long delay;
1915914b2007SJan Kara 	bool cannot_commit;
1916a74a4b97SChris Mason 
1917a74a4b97SChris Mason 	do {
1918914b2007SJan Kara 		cannot_commit = false;
1919ba1bc00fSNikolay Borisov 		delay = msecs_to_jiffies(fs_info->commit_interval * 1000);
19200b246afaSJeff Mahoney 		mutex_lock(&fs_info->transaction_kthread_mutex);
1921a74a4b97SChris Mason 
19220b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
19230b246afaSJeff Mahoney 		cur = fs_info->running_transaction;
1924a74a4b97SChris Mason 		if (!cur) {
19250b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
1926a74a4b97SChris Mason 			goto sleep;
1927a74a4b97SChris Mason 		}
192831153d81SYan Zheng 
1929643900beSNikolay Borisov 		delta = ktime_get_seconds() - cur->start_time;
19303296bf56SQu Wenruo 		if (cur->state < TRANS_STATE_COMMIT_START &&
1931643900beSNikolay Borisov 		    delta < fs_info->commit_interval) {
19320b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
1933fb8a7e94SNikolay Borisov 			delay -= msecs_to_jiffies((delta - 1) * 1000);
1934fb8a7e94SNikolay Borisov 			delay = min(delay,
1935fb8a7e94SNikolay Borisov 				    msecs_to_jiffies(fs_info->commit_interval * 1000));
1936a74a4b97SChris Mason 			goto sleep;
1937a74a4b97SChris Mason 		}
19388929ecfaSYan, Zheng 		transid = cur->transid;
19390b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
194056bec294SChris Mason 
194179787eaaSJeff Mahoney 		/* If the file system is aborted, this will always fail. */
1942354aa0fbSMiao Xie 		trans = btrfs_attach_transaction(root);
1943914b2007SJan Kara 		if (IS_ERR(trans)) {
1944354aa0fbSMiao Xie 			if (PTR_ERR(trans) != -ENOENT)
1945914b2007SJan Kara 				cannot_commit = true;
194679787eaaSJeff Mahoney 			goto sleep;
1947914b2007SJan Kara 		}
19488929ecfaSYan, Zheng 		if (transid == trans->transid) {
19493a45bb20SJeff Mahoney 			btrfs_commit_transaction(trans);
19508929ecfaSYan, Zheng 		} else {
19513a45bb20SJeff Mahoney 			btrfs_end_transaction(trans);
19528929ecfaSYan, Zheng 		}
1953a74a4b97SChris Mason sleep:
19540b246afaSJeff Mahoney 		wake_up_process(fs_info->cleaner_kthread);
19550b246afaSJeff Mahoney 		mutex_unlock(&fs_info->transaction_kthread_mutex);
1956a74a4b97SChris Mason 
19574e121c06SJosef Bacik 		if (unlikely(test_bit(BTRFS_FS_STATE_ERROR,
19580b246afaSJeff Mahoney 				      &fs_info->fs_state)))
19592ff7e61eSJeff Mahoney 			btrfs_cleanup_transaction(fs_info);
19608929ecfaSYan, Zheng 		if (!kthread_should_stop() &&
19610b246afaSJeff Mahoney 				(!btrfs_transaction_blocked(fs_info) ||
1962914b2007SJan Kara 				 cannot_commit))
1963bc5511d0SNikolay Borisov 			schedule_timeout_interruptible(delay);
1964a74a4b97SChris Mason 	} while (!kthread_should_stop());
1965a74a4b97SChris Mason 	return 0;
1966a74a4b97SChris Mason }
1967a74a4b97SChris Mason 
1968af31f5e5SChris Mason /*
196901f0f9daSNikolay Borisov  * This will find the highest generation in the array of root backups.  The
197001f0f9daSNikolay Borisov  * index of the highest array is returned, or -EINVAL if we can't find
197101f0f9daSNikolay Borisov  * anything.
1972af31f5e5SChris Mason  *
1973af31f5e5SChris Mason  * We check to make sure the array is valid by comparing the
1974af31f5e5SChris Mason  * generation of the latest  root in the array with the generation
1975af31f5e5SChris Mason  * in the super block.  If they don't match we pitch it.
1976af31f5e5SChris Mason  */
197701f0f9daSNikolay Borisov static int find_newest_super_backup(struct btrfs_fs_info *info)
1978af31f5e5SChris Mason {
197901f0f9daSNikolay Borisov 	const u64 newest_gen = btrfs_super_generation(info->super_copy);
1980af31f5e5SChris Mason 	u64 cur;
1981af31f5e5SChris Mason 	struct btrfs_root_backup *root_backup;
1982af31f5e5SChris Mason 	int i;
1983af31f5e5SChris Mason 
1984af31f5e5SChris Mason 	for (i = 0; i < BTRFS_NUM_BACKUP_ROOTS; i++) {
1985af31f5e5SChris Mason 		root_backup = info->super_copy->super_roots + i;
1986af31f5e5SChris Mason 		cur = btrfs_backup_tree_root_gen(root_backup);
1987af31f5e5SChris Mason 		if (cur == newest_gen)
198801f0f9daSNikolay Borisov 			return i;
1989af31f5e5SChris Mason 	}
1990af31f5e5SChris Mason 
199101f0f9daSNikolay Borisov 	return -EINVAL;
1992af31f5e5SChris Mason }
1993af31f5e5SChris Mason 
1994af31f5e5SChris Mason /*
1995af31f5e5SChris Mason  * copy all the root pointers into the super backup array.
1996af31f5e5SChris Mason  * this will bump the backup pointer by one when it is
1997af31f5e5SChris Mason  * done
1998af31f5e5SChris Mason  */
1999af31f5e5SChris Mason static void backup_super_roots(struct btrfs_fs_info *info)
2000af31f5e5SChris Mason {
20016ef108ddSNikolay Borisov 	const int next_backup = info->backup_root_index;
2002af31f5e5SChris Mason 	struct btrfs_root_backup *root_backup;
2003af31f5e5SChris Mason 
2004af31f5e5SChris Mason 	root_backup = info->super_for_commit->super_roots + next_backup;
2005af31f5e5SChris Mason 
2006af31f5e5SChris Mason 	/*
2007af31f5e5SChris Mason 	 * make sure all of our padding and empty slots get zero filled
2008af31f5e5SChris Mason 	 * regardless of which ones we use today
2009af31f5e5SChris Mason 	 */
2010af31f5e5SChris Mason 	memset(root_backup, 0, sizeof(*root_backup));
2011af31f5e5SChris Mason 
2012af31f5e5SChris Mason 	info->backup_root_index = (next_backup + 1) % BTRFS_NUM_BACKUP_ROOTS;
2013af31f5e5SChris Mason 
2014af31f5e5SChris Mason 	btrfs_set_backup_tree_root(root_backup, info->tree_root->node->start);
2015af31f5e5SChris Mason 	btrfs_set_backup_tree_root_gen(root_backup,
2016af31f5e5SChris Mason 			       btrfs_header_generation(info->tree_root->node));
2017af31f5e5SChris Mason 
2018af31f5e5SChris Mason 	btrfs_set_backup_tree_root_level(root_backup,
2019af31f5e5SChris Mason 			       btrfs_header_level(info->tree_root->node));
2020af31f5e5SChris Mason 
2021af31f5e5SChris Mason 	btrfs_set_backup_chunk_root(root_backup, info->chunk_root->node->start);
2022af31f5e5SChris Mason 	btrfs_set_backup_chunk_root_gen(root_backup,
2023af31f5e5SChris Mason 			       btrfs_header_generation(info->chunk_root->node));
2024af31f5e5SChris Mason 	btrfs_set_backup_chunk_root_level(root_backup,
2025af31f5e5SChris Mason 			       btrfs_header_level(info->chunk_root->node));
2026af31f5e5SChris Mason 
2027af31f5e5SChris Mason 	btrfs_set_backup_extent_root(root_backup, info->extent_root->node->start);
2028af31f5e5SChris Mason 	btrfs_set_backup_extent_root_gen(root_backup,
2029af31f5e5SChris Mason 			       btrfs_header_generation(info->extent_root->node));
2030af31f5e5SChris Mason 	btrfs_set_backup_extent_root_level(root_backup,
2031af31f5e5SChris Mason 			       btrfs_header_level(info->extent_root->node));
2032af31f5e5SChris Mason 
20337c7e82a7SChris Mason 	/*
20347c7e82a7SChris Mason 	 * we might commit during log recovery, which happens before we set
20357c7e82a7SChris Mason 	 * the fs_root.  Make sure it is valid before we fill it in.
20367c7e82a7SChris Mason 	 */
20377c7e82a7SChris Mason 	if (info->fs_root && info->fs_root->node) {
20387c7e82a7SChris Mason 		btrfs_set_backup_fs_root(root_backup,
20397c7e82a7SChris Mason 					 info->fs_root->node->start);
2040af31f5e5SChris Mason 		btrfs_set_backup_fs_root_gen(root_backup,
2041af31f5e5SChris Mason 			       btrfs_header_generation(info->fs_root->node));
2042af31f5e5SChris Mason 		btrfs_set_backup_fs_root_level(root_backup,
2043af31f5e5SChris Mason 			       btrfs_header_level(info->fs_root->node));
20447c7e82a7SChris Mason 	}
2045af31f5e5SChris Mason 
2046af31f5e5SChris Mason 	btrfs_set_backup_dev_root(root_backup, info->dev_root->node->start);
2047af31f5e5SChris Mason 	btrfs_set_backup_dev_root_gen(root_backup,
2048af31f5e5SChris Mason 			       btrfs_header_generation(info->dev_root->node));
2049af31f5e5SChris Mason 	btrfs_set_backup_dev_root_level(root_backup,
2050af31f5e5SChris Mason 				       btrfs_header_level(info->dev_root->node));
2051af31f5e5SChris Mason 
2052af31f5e5SChris Mason 	btrfs_set_backup_csum_root(root_backup, info->csum_root->node->start);
2053af31f5e5SChris Mason 	btrfs_set_backup_csum_root_gen(root_backup,
2054af31f5e5SChris Mason 			       btrfs_header_generation(info->csum_root->node));
2055af31f5e5SChris Mason 	btrfs_set_backup_csum_root_level(root_backup,
2056af31f5e5SChris Mason 			       btrfs_header_level(info->csum_root->node));
2057af31f5e5SChris Mason 
2058af31f5e5SChris Mason 	btrfs_set_backup_total_bytes(root_backup,
2059af31f5e5SChris Mason 			     btrfs_super_total_bytes(info->super_copy));
2060af31f5e5SChris Mason 	btrfs_set_backup_bytes_used(root_backup,
2061af31f5e5SChris Mason 			     btrfs_super_bytes_used(info->super_copy));
2062af31f5e5SChris Mason 	btrfs_set_backup_num_devices(root_backup,
2063af31f5e5SChris Mason 			     btrfs_super_num_devices(info->super_copy));
2064af31f5e5SChris Mason 
2065af31f5e5SChris Mason 	/*
2066af31f5e5SChris Mason 	 * if we don't copy this out to the super_copy, it won't get remembered
2067af31f5e5SChris Mason 	 * for the next commit
2068af31f5e5SChris Mason 	 */
2069af31f5e5SChris Mason 	memcpy(&info->super_copy->super_roots,
2070af31f5e5SChris Mason 	       &info->super_for_commit->super_roots,
2071af31f5e5SChris Mason 	       sizeof(*root_backup) * BTRFS_NUM_BACKUP_ROOTS);
2072af31f5e5SChris Mason }
2073af31f5e5SChris Mason 
2074af31f5e5SChris Mason /*
2075bd2336b2SNikolay Borisov  * read_backup_root - Reads a backup root based on the passed priority. Prio 0
2076bd2336b2SNikolay Borisov  * is the newest, prio 1/2/3 are 2nd newest/3rd newest/4th (oldest) backup roots
2077bd2336b2SNikolay Borisov  *
2078bd2336b2SNikolay Borisov  * fs_info - filesystem whose backup roots need to be read
2079bd2336b2SNikolay Borisov  * priority - priority of backup root required
2080bd2336b2SNikolay Borisov  *
2081bd2336b2SNikolay Borisov  * Returns backup root index on success and -EINVAL otherwise.
2082bd2336b2SNikolay Borisov  */
2083bd2336b2SNikolay Borisov static int read_backup_root(struct btrfs_fs_info *fs_info, u8 priority)
2084bd2336b2SNikolay Borisov {
2085bd2336b2SNikolay Borisov 	int backup_index = find_newest_super_backup(fs_info);
2086bd2336b2SNikolay Borisov 	struct btrfs_super_block *super = fs_info->super_copy;
2087bd2336b2SNikolay Borisov 	struct btrfs_root_backup *root_backup;
2088bd2336b2SNikolay Borisov 
2089bd2336b2SNikolay Borisov 	if (priority < BTRFS_NUM_BACKUP_ROOTS && backup_index >= 0) {
2090bd2336b2SNikolay Borisov 		if (priority == 0)
2091bd2336b2SNikolay Borisov 			return backup_index;
2092bd2336b2SNikolay Borisov 
2093bd2336b2SNikolay Borisov 		backup_index = backup_index + BTRFS_NUM_BACKUP_ROOTS - priority;
2094bd2336b2SNikolay Borisov 		backup_index %= BTRFS_NUM_BACKUP_ROOTS;
2095bd2336b2SNikolay Borisov 	} else {
2096bd2336b2SNikolay Borisov 		return -EINVAL;
2097bd2336b2SNikolay Borisov 	}
2098bd2336b2SNikolay Borisov 
2099bd2336b2SNikolay Borisov 	root_backup = super->super_roots + backup_index;
2100bd2336b2SNikolay Borisov 
2101bd2336b2SNikolay Borisov 	btrfs_set_super_generation(super,
2102bd2336b2SNikolay Borisov 				   btrfs_backup_tree_root_gen(root_backup));
2103bd2336b2SNikolay Borisov 	btrfs_set_super_root(super, btrfs_backup_tree_root(root_backup));
2104bd2336b2SNikolay Borisov 	btrfs_set_super_root_level(super,
2105bd2336b2SNikolay Borisov 				   btrfs_backup_tree_root_level(root_backup));
2106bd2336b2SNikolay Borisov 	btrfs_set_super_bytes_used(super, btrfs_backup_bytes_used(root_backup));
2107bd2336b2SNikolay Borisov 
2108bd2336b2SNikolay Borisov 	/*
2109bd2336b2SNikolay Borisov 	 * Fixme: the total bytes and num_devices need to match or we should
2110bd2336b2SNikolay Borisov 	 * need a fsck
2111bd2336b2SNikolay Borisov 	 */
2112bd2336b2SNikolay Borisov 	btrfs_set_super_total_bytes(super, btrfs_backup_total_bytes(root_backup));
2113bd2336b2SNikolay Borisov 	btrfs_set_super_num_devices(super, btrfs_backup_num_devices(root_backup));
2114bd2336b2SNikolay Borisov 
2115bd2336b2SNikolay Borisov 	return backup_index;
2116bd2336b2SNikolay Borisov }
2117bd2336b2SNikolay Borisov 
21187abadb64SLiu Bo /* helper to cleanup workers */
21197abadb64SLiu Bo static void btrfs_stop_all_workers(struct btrfs_fs_info *fs_info)
21207abadb64SLiu Bo {
2121dc6e3209SQu Wenruo 	btrfs_destroy_workqueue(fs_info->fixup_workers);
2122afe3d242SQu Wenruo 	btrfs_destroy_workqueue(fs_info->delalloc_workers);
21235cdc7ad3SQu Wenruo 	btrfs_destroy_workqueue(fs_info->workers);
2124fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_workers);
2125fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_raid56_workers);
2126d05a33acSQu Wenruo 	btrfs_destroy_workqueue(fs_info->rmw_workers);
2127fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_write_workers);
2128fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_freespace_worker);
21295b3bc44eSQu Wenruo 	btrfs_destroy_workqueue(fs_info->delayed_workers);
2130e66f0bb1SQu Wenruo 	btrfs_destroy_workqueue(fs_info->caching_workers);
2131736cfa15SQu Wenruo 	btrfs_destroy_workqueue(fs_info->readahead_workers);
2132a44903abSQu Wenruo 	btrfs_destroy_workqueue(fs_info->flush_workers);
2133fc97fab0SQu Wenruo 	btrfs_destroy_workqueue(fs_info->qgroup_rescan_workers);
2134b0643e59SDennis Zhou 	if (fs_info->discard_ctl.discard_workers)
2135b0643e59SDennis Zhou 		destroy_workqueue(fs_info->discard_ctl.discard_workers);
2136a9b9477dSFilipe Manana 	/*
2137a9b9477dSFilipe Manana 	 * Now that all other work queues are destroyed, we can safely destroy
2138a9b9477dSFilipe Manana 	 * the queues used for metadata I/O, since tasks from those other work
2139a9b9477dSFilipe Manana 	 * queues can do metadata I/O operations.
2140a9b9477dSFilipe Manana 	 */
2141a9b9477dSFilipe Manana 	btrfs_destroy_workqueue(fs_info->endio_meta_workers);
2142a9b9477dSFilipe Manana 	btrfs_destroy_workqueue(fs_info->endio_meta_write_workers);
21437abadb64SLiu Bo }
21447abadb64SLiu Bo 
21452e9f5954SRashika static void free_root_extent_buffers(struct btrfs_root *root)
21462e9f5954SRashika {
21472e9f5954SRashika 	if (root) {
21482e9f5954SRashika 		free_extent_buffer(root->node);
21492e9f5954SRashika 		free_extent_buffer(root->commit_root);
21502e9f5954SRashika 		root->node = NULL;
21512e9f5954SRashika 		root->commit_root = NULL;
21522e9f5954SRashika 	}
21532e9f5954SRashika }
21542e9f5954SRashika 
2155af31f5e5SChris Mason /* helper to cleanup tree roots */
21564273eaffSAnand Jain static void free_root_pointers(struct btrfs_fs_info *info, bool free_chunk_root)
2157af31f5e5SChris Mason {
21582e9f5954SRashika 	free_root_extent_buffers(info->tree_root);
2159655b09feSJosef Bacik 
21602e9f5954SRashika 	free_root_extent_buffers(info->dev_root);
21612e9f5954SRashika 	free_root_extent_buffers(info->extent_root);
21622e9f5954SRashika 	free_root_extent_buffers(info->csum_root);
21632e9f5954SRashika 	free_root_extent_buffers(info->quota_root);
21642e9f5954SRashika 	free_root_extent_buffers(info->uuid_root);
21658c38938cSJosef Bacik 	free_root_extent_buffers(info->fs_root);
2166aeb935a4SQu Wenruo 	free_root_extent_buffers(info->data_reloc_root);
21674273eaffSAnand Jain 	if (free_chunk_root)
21682e9f5954SRashika 		free_root_extent_buffers(info->chunk_root);
216970f6d82eSOmar Sandoval 	free_root_extent_buffers(info->free_space_root);
2170af31f5e5SChris Mason }
2171af31f5e5SChris Mason 
21728c38938cSJosef Bacik void btrfs_put_root(struct btrfs_root *root)
21738c38938cSJosef Bacik {
21748c38938cSJosef Bacik 	if (!root)
21758c38938cSJosef Bacik 		return;
21768c38938cSJosef Bacik 
21778c38938cSJosef Bacik 	if (refcount_dec_and_test(&root->refs)) {
21788c38938cSJosef Bacik 		WARN_ON(!RB_EMPTY_ROOT(&root->inode_tree));
21791dae7e0eSQu Wenruo 		WARN_ON(test_bit(BTRFS_ROOT_DEAD_RELOC_TREE, &root->state));
21808c38938cSJosef Bacik 		if (root->anon_dev)
21818c38938cSJosef Bacik 			free_anon_bdev(root->anon_dev);
21828c38938cSJosef Bacik 		btrfs_drew_lock_destroy(&root->snapshot_lock);
2183923eb523SJohannes Thumshirn 		free_root_extent_buffers(root);
21848c38938cSJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
21858c38938cSJosef Bacik 		spin_lock(&root->fs_info->fs_roots_radix_lock);
21868c38938cSJosef Bacik 		list_del_init(&root->leak_list);
21878c38938cSJosef Bacik 		spin_unlock(&root->fs_info->fs_roots_radix_lock);
21888c38938cSJosef Bacik #endif
21898c38938cSJosef Bacik 		kfree(root);
21908c38938cSJosef Bacik 	}
21918c38938cSJosef Bacik }
21928c38938cSJosef Bacik 
2193faa2dbf0SJosef Bacik void btrfs_free_fs_roots(struct btrfs_fs_info *fs_info)
2194171f6537SJosef Bacik {
2195171f6537SJosef Bacik 	int ret;
2196171f6537SJosef Bacik 	struct btrfs_root *gang[8];
2197171f6537SJosef Bacik 	int i;
2198171f6537SJosef Bacik 
2199171f6537SJosef Bacik 	while (!list_empty(&fs_info->dead_roots)) {
2200171f6537SJosef Bacik 		gang[0] = list_entry(fs_info->dead_roots.next,
2201171f6537SJosef Bacik 				     struct btrfs_root, root_list);
2202171f6537SJosef Bacik 		list_del(&gang[0]->root_list);
2203171f6537SJosef Bacik 
22048c38938cSJosef Bacik 		if (test_bit(BTRFS_ROOT_IN_RADIX, &gang[0]->state))
2205cb517eabSMiao Xie 			btrfs_drop_and_free_fs_root(fs_info, gang[0]);
220600246528SJosef Bacik 		btrfs_put_root(gang[0]);
2207171f6537SJosef Bacik 	}
2208171f6537SJosef Bacik 
2209171f6537SJosef Bacik 	while (1) {
2210171f6537SJosef Bacik 		ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
2211171f6537SJosef Bacik 					     (void **)gang, 0,
2212171f6537SJosef Bacik 					     ARRAY_SIZE(gang));
2213171f6537SJosef Bacik 		if (!ret)
2214171f6537SJosef Bacik 			break;
2215171f6537SJosef Bacik 		for (i = 0; i < ret; i++)
2216cb517eabSMiao Xie 			btrfs_drop_and_free_fs_root(fs_info, gang[i]);
2217171f6537SJosef Bacik 	}
2218171f6537SJosef Bacik }
2219af31f5e5SChris Mason 
2220638aa7edSEric Sandeen static void btrfs_init_scrub(struct btrfs_fs_info *fs_info)
2221638aa7edSEric Sandeen {
2222638aa7edSEric Sandeen 	mutex_init(&fs_info->scrub_lock);
2223638aa7edSEric Sandeen 	atomic_set(&fs_info->scrubs_running, 0);
2224638aa7edSEric Sandeen 	atomic_set(&fs_info->scrub_pause_req, 0);
2225638aa7edSEric Sandeen 	atomic_set(&fs_info->scrubs_paused, 0);
2226638aa7edSEric Sandeen 	atomic_set(&fs_info->scrub_cancel_req, 0);
2227638aa7edSEric Sandeen 	init_waitqueue_head(&fs_info->scrub_pause_wait);
2228ff09c4caSAnand Jain 	refcount_set(&fs_info->scrub_workers_refcnt, 0);
2229638aa7edSEric Sandeen }
2230638aa7edSEric Sandeen 
2231779a65a4SEric Sandeen static void btrfs_init_balance(struct btrfs_fs_info *fs_info)
2232779a65a4SEric Sandeen {
2233779a65a4SEric Sandeen 	spin_lock_init(&fs_info->balance_lock);
2234779a65a4SEric Sandeen 	mutex_init(&fs_info->balance_mutex);
2235779a65a4SEric Sandeen 	atomic_set(&fs_info->balance_pause_req, 0);
2236779a65a4SEric Sandeen 	atomic_set(&fs_info->balance_cancel_req, 0);
2237779a65a4SEric Sandeen 	fs_info->balance_ctl = NULL;
2238779a65a4SEric Sandeen 	init_waitqueue_head(&fs_info->balance_wait_q);
2239907d2710SDavid Sterba 	atomic_set(&fs_info->reloc_cancel_req, 0);
2240779a65a4SEric Sandeen }
2241779a65a4SEric Sandeen 
22426bccf3abSJeff Mahoney static void btrfs_init_btree_inode(struct btrfs_fs_info *fs_info)
2243f37938e0SEric Sandeen {
22442ff7e61eSJeff Mahoney 	struct inode *inode = fs_info->btree_inode;
22452ff7e61eSJeff Mahoney 
22462ff7e61eSJeff Mahoney 	inode->i_ino = BTRFS_BTREE_INODE_OBJECTID;
22472ff7e61eSJeff Mahoney 	set_nlink(inode, 1);
2248f37938e0SEric Sandeen 	/*
2249f37938e0SEric Sandeen 	 * we set the i_size on the btree inode to the max possible int.
2250f37938e0SEric Sandeen 	 * the real end of the address space is determined by all of
2251f37938e0SEric Sandeen 	 * the devices in the system
2252f37938e0SEric Sandeen 	 */
22532ff7e61eSJeff Mahoney 	inode->i_size = OFFSET_MAX;
22542ff7e61eSJeff Mahoney 	inode->i_mapping->a_ops = &btree_aops;
2255f37938e0SEric Sandeen 
22562ff7e61eSJeff Mahoney 	RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
225743eb5f29SQu Wenruo 	extent_io_tree_init(fs_info, &BTRFS_I(inode)->io_tree,
22582c53a14dSQu Wenruo 			    IO_TREE_BTREE_INODE_IO, inode);
22597b439738SDavid Sterba 	BTRFS_I(inode)->io_tree.track_uptodate = false;
22602ff7e61eSJeff Mahoney 	extent_map_tree_init(&BTRFS_I(inode)->extent_tree);
2261f37938e0SEric Sandeen 
22625c8fd99fSJosef Bacik 	BTRFS_I(inode)->root = btrfs_grab_root(fs_info->tree_root);
22632ff7e61eSJeff Mahoney 	memset(&BTRFS_I(inode)->location, 0, sizeof(struct btrfs_key));
22642ff7e61eSJeff Mahoney 	set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
22652ff7e61eSJeff Mahoney 	btrfs_insert_inode_hash(inode);
2266f37938e0SEric Sandeen }
2267f37938e0SEric Sandeen 
2268ad618368SEric Sandeen static void btrfs_init_dev_replace_locks(struct btrfs_fs_info *fs_info)
2269ad618368SEric Sandeen {
2270ad618368SEric Sandeen 	mutex_init(&fs_info->dev_replace.lock_finishing_cancel_unmount);
2271129827e3SDavid Sterba 	init_rwsem(&fs_info->dev_replace.rwsem);
22727f8d236aSDavid Sterba 	init_waitqueue_head(&fs_info->dev_replace.replace_wait);
2273ad618368SEric Sandeen }
2274ad618368SEric Sandeen 
2275f9e92e40SEric Sandeen static void btrfs_init_qgroup(struct btrfs_fs_info *fs_info)
2276f9e92e40SEric Sandeen {
2277f9e92e40SEric Sandeen 	spin_lock_init(&fs_info->qgroup_lock);
2278f9e92e40SEric Sandeen 	mutex_init(&fs_info->qgroup_ioctl_lock);
2279f9e92e40SEric Sandeen 	fs_info->qgroup_tree = RB_ROOT;
2280f9e92e40SEric Sandeen 	INIT_LIST_HEAD(&fs_info->dirty_qgroups);
2281f9e92e40SEric Sandeen 	fs_info->qgroup_seq = 1;
2282f9e92e40SEric Sandeen 	fs_info->qgroup_ulist = NULL;
2283d2c609b8SJeff Mahoney 	fs_info->qgroup_rescan_running = false;
2284f9e92e40SEric Sandeen 	mutex_init(&fs_info->qgroup_rescan_lock);
2285f9e92e40SEric Sandeen }
2286f9e92e40SEric Sandeen 
22872a458198SEric Sandeen static int btrfs_init_workqueues(struct btrfs_fs_info *fs_info,
22882a458198SEric Sandeen 		struct btrfs_fs_devices *fs_devices)
22892a458198SEric Sandeen {
2290f7b885beSAnand Jain 	u32 max_active = fs_info->thread_pool_size;
22916f011058SDavid Sterba 	unsigned int flags = WQ_MEM_RECLAIM | WQ_FREEZABLE | WQ_UNBOUND;
22922a458198SEric Sandeen 
22932a458198SEric Sandeen 	fs_info->workers =
2294cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "worker",
2295cb001095SJeff Mahoney 				      flags | WQ_HIGHPRI, max_active, 16);
22962a458198SEric Sandeen 
22972a458198SEric Sandeen 	fs_info->delalloc_workers =
2298cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "delalloc",
2299cb001095SJeff Mahoney 				      flags, max_active, 2);
23002a458198SEric Sandeen 
23012a458198SEric Sandeen 	fs_info->flush_workers =
2302cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "flush_delalloc",
2303cb001095SJeff Mahoney 				      flags, max_active, 0);
23042a458198SEric Sandeen 
23052a458198SEric Sandeen 	fs_info->caching_workers =
2306cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "cache", flags, max_active, 0);
23072a458198SEric Sandeen 
23082a458198SEric Sandeen 	fs_info->fixup_workers =
2309cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "fixup", flags, 1, 0);
23102a458198SEric Sandeen 
23112a458198SEric Sandeen 	/*
23122a458198SEric Sandeen 	 * endios are largely parallel and should have a very
23132a458198SEric Sandeen 	 * low idle thresh
23142a458198SEric Sandeen 	 */
23152a458198SEric Sandeen 	fs_info->endio_workers =
2316cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio", flags, max_active, 4);
23172a458198SEric Sandeen 	fs_info->endio_meta_workers =
2318cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio-meta", flags,
2319cb001095SJeff Mahoney 				      max_active, 4);
23202a458198SEric Sandeen 	fs_info->endio_meta_write_workers =
2321cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio-meta-write", flags,
2322cb001095SJeff Mahoney 				      max_active, 2);
23232a458198SEric Sandeen 	fs_info->endio_raid56_workers =
2324cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio-raid56", flags,
2325cb001095SJeff Mahoney 				      max_active, 4);
23262a458198SEric Sandeen 	fs_info->rmw_workers =
2327cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "rmw", flags, max_active, 2);
23282a458198SEric Sandeen 	fs_info->endio_write_workers =
2329cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio-write", flags,
2330cb001095SJeff Mahoney 				      max_active, 2);
23312a458198SEric Sandeen 	fs_info->endio_freespace_worker =
2332cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "freespace-write", flags,
2333cb001095SJeff Mahoney 				      max_active, 0);
23342a458198SEric Sandeen 	fs_info->delayed_workers =
2335cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "delayed-meta", flags,
2336cb001095SJeff Mahoney 				      max_active, 0);
23372a458198SEric Sandeen 	fs_info->readahead_workers =
2338cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "readahead", flags,
2339cb001095SJeff Mahoney 				      max_active, 2);
23402a458198SEric Sandeen 	fs_info->qgroup_rescan_workers =
2341cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "qgroup-rescan", flags, 1, 0);
2342b0643e59SDennis Zhou 	fs_info->discard_ctl.discard_workers =
2343b0643e59SDennis Zhou 		alloc_workqueue("btrfs_discard", WQ_UNBOUND | WQ_FREEZABLE, 1);
23442a458198SEric Sandeen 
23452a458198SEric Sandeen 	if (!(fs_info->workers && fs_info->delalloc_workers &&
2346ba8a9d07SChris Mason 	      fs_info->flush_workers &&
23472a458198SEric Sandeen 	      fs_info->endio_workers && fs_info->endio_meta_workers &&
23482a458198SEric Sandeen 	      fs_info->endio_meta_write_workers &&
23492a458198SEric Sandeen 	      fs_info->endio_write_workers && fs_info->endio_raid56_workers &&
23502a458198SEric Sandeen 	      fs_info->endio_freespace_worker && fs_info->rmw_workers &&
23512a458198SEric Sandeen 	      fs_info->caching_workers && fs_info->readahead_workers &&
23522a458198SEric Sandeen 	      fs_info->fixup_workers && fs_info->delayed_workers &&
2353b0643e59SDennis Zhou 	      fs_info->qgroup_rescan_workers &&
2354b0643e59SDennis Zhou 	      fs_info->discard_ctl.discard_workers)) {
23552a458198SEric Sandeen 		return -ENOMEM;
23562a458198SEric Sandeen 	}
23572a458198SEric Sandeen 
23582a458198SEric Sandeen 	return 0;
23592a458198SEric Sandeen }
23602a458198SEric Sandeen 
23616d97c6e3SJohannes Thumshirn static int btrfs_init_csum_hash(struct btrfs_fs_info *fs_info, u16 csum_type)
23626d97c6e3SJohannes Thumshirn {
23636d97c6e3SJohannes Thumshirn 	struct crypto_shash *csum_shash;
2364b4e967beSDavid Sterba 	const char *csum_driver = btrfs_super_csum_driver(csum_type);
23656d97c6e3SJohannes Thumshirn 
2366b4e967beSDavid Sterba 	csum_shash = crypto_alloc_shash(csum_driver, 0, 0);
23676d97c6e3SJohannes Thumshirn 
23686d97c6e3SJohannes Thumshirn 	if (IS_ERR(csum_shash)) {
23696d97c6e3SJohannes Thumshirn 		btrfs_err(fs_info, "error allocating %s hash for checksum",
2370b4e967beSDavid Sterba 			  csum_driver);
23716d97c6e3SJohannes Thumshirn 		return PTR_ERR(csum_shash);
23726d97c6e3SJohannes Thumshirn 	}
23736d97c6e3SJohannes Thumshirn 
23746d97c6e3SJohannes Thumshirn 	fs_info->csum_shash = csum_shash;
23756d97c6e3SJohannes Thumshirn 
23766d97c6e3SJohannes Thumshirn 	return 0;
23776d97c6e3SJohannes Thumshirn }
23786d97c6e3SJohannes Thumshirn 
237963443bf5SEric Sandeen static int btrfs_replay_log(struct btrfs_fs_info *fs_info,
238063443bf5SEric Sandeen 			    struct btrfs_fs_devices *fs_devices)
238163443bf5SEric Sandeen {
238263443bf5SEric Sandeen 	int ret;
238363443bf5SEric Sandeen 	struct btrfs_root *log_tree_root;
238463443bf5SEric Sandeen 	struct btrfs_super_block *disk_super = fs_info->super_copy;
238563443bf5SEric Sandeen 	u64 bytenr = btrfs_super_log_root(disk_super);
2386581c1760SQu Wenruo 	int level = btrfs_super_log_root_level(disk_super);
238763443bf5SEric Sandeen 
238863443bf5SEric Sandeen 	if (fs_devices->rw_devices == 0) {
2389f14d104dSDavid Sterba 		btrfs_warn(fs_info, "log replay required on RO media");
239063443bf5SEric Sandeen 		return -EIO;
239163443bf5SEric Sandeen 	}
239263443bf5SEric Sandeen 
239396dfcb46SJosef Bacik 	log_tree_root = btrfs_alloc_root(fs_info, BTRFS_TREE_LOG_OBJECTID,
239496dfcb46SJosef Bacik 					 GFP_KERNEL);
239563443bf5SEric Sandeen 	if (!log_tree_root)
239663443bf5SEric Sandeen 		return -ENOMEM;
239763443bf5SEric Sandeen 
23982ff7e61eSJeff Mahoney 	log_tree_root->node = read_tree_block(fs_info, bytenr,
23991b7ec85eSJosef Bacik 					      BTRFS_TREE_LOG_OBJECTID,
24001b7ec85eSJosef Bacik 					      fs_info->generation + 1, level,
24011b7ec85eSJosef Bacik 					      NULL);
240264c043deSLiu Bo 	if (IS_ERR(log_tree_root->node)) {
2403f14d104dSDavid Sterba 		btrfs_warn(fs_info, "failed to read log tree");
24040eeff236SLiu Bo 		ret = PTR_ERR(log_tree_root->node);
24058c38938cSJosef Bacik 		log_tree_root->node = NULL;
240600246528SJosef Bacik 		btrfs_put_root(log_tree_root);
24070eeff236SLiu Bo 		return ret;
240864c043deSLiu Bo 	} else if (!extent_buffer_uptodate(log_tree_root->node)) {
2409f14d104dSDavid Sterba 		btrfs_err(fs_info, "failed to read log tree");
241000246528SJosef Bacik 		btrfs_put_root(log_tree_root);
241163443bf5SEric Sandeen 		return -EIO;
241263443bf5SEric Sandeen 	}
241363443bf5SEric Sandeen 	/* returns with log_tree_root freed on success */
241463443bf5SEric Sandeen 	ret = btrfs_recover_log_trees(log_tree_root);
241563443bf5SEric Sandeen 	if (ret) {
24160b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, ret,
241763443bf5SEric Sandeen 				      "Failed to recover log tree");
241800246528SJosef Bacik 		btrfs_put_root(log_tree_root);
241963443bf5SEric Sandeen 		return ret;
242063443bf5SEric Sandeen 	}
242163443bf5SEric Sandeen 
2422bc98a42cSDavid Howells 	if (sb_rdonly(fs_info->sb)) {
24236bccf3abSJeff Mahoney 		ret = btrfs_commit_super(fs_info);
242463443bf5SEric Sandeen 		if (ret)
242563443bf5SEric Sandeen 			return ret;
242663443bf5SEric Sandeen 	}
242763443bf5SEric Sandeen 
242863443bf5SEric Sandeen 	return 0;
242963443bf5SEric Sandeen }
243063443bf5SEric Sandeen 
24316bccf3abSJeff Mahoney static int btrfs_read_roots(struct btrfs_fs_info *fs_info)
24324bbcaa64SEric Sandeen {
24336bccf3abSJeff Mahoney 	struct btrfs_root *tree_root = fs_info->tree_root;
2434a4f3d2c4SDavid Sterba 	struct btrfs_root *root;
24354bbcaa64SEric Sandeen 	struct btrfs_key location;
24364bbcaa64SEric Sandeen 	int ret;
24374bbcaa64SEric Sandeen 
24386bccf3abSJeff Mahoney 	BUG_ON(!fs_info->tree_root);
24396bccf3abSJeff Mahoney 
24404bbcaa64SEric Sandeen 	location.objectid = BTRFS_EXTENT_TREE_OBJECTID;
24414bbcaa64SEric Sandeen 	location.type = BTRFS_ROOT_ITEM_KEY;
24424bbcaa64SEric Sandeen 	location.offset = 0;
24434bbcaa64SEric Sandeen 
2444a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2445f50f4353SLiu Bo 	if (IS_ERR(root)) {
244642437a63SJosef Bacik 		if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2447f50f4353SLiu Bo 			ret = PTR_ERR(root);
2448f50f4353SLiu Bo 			goto out;
2449f50f4353SLiu Bo 		}
245042437a63SJosef Bacik 	} else {
2451a4f3d2c4SDavid Sterba 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2452a4f3d2c4SDavid Sterba 		fs_info->extent_root = root;
245342437a63SJosef Bacik 	}
24544bbcaa64SEric Sandeen 
24554bbcaa64SEric Sandeen 	location.objectid = BTRFS_DEV_TREE_OBJECTID;
2456a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2457f50f4353SLiu Bo 	if (IS_ERR(root)) {
245842437a63SJosef Bacik 		if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2459f50f4353SLiu Bo 			ret = PTR_ERR(root);
2460f50f4353SLiu Bo 			goto out;
2461f50f4353SLiu Bo 		}
246242437a63SJosef Bacik 	} else {
2463a4f3d2c4SDavid Sterba 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2464a4f3d2c4SDavid Sterba 		fs_info->dev_root = root;
246542437a63SJosef Bacik 	}
2466820a49daSJosef Bacik 	/* Initialize fs_info for all devices in any case */
2467820a49daSJosef Bacik 	btrfs_init_devices_late(fs_info);
24684bbcaa64SEric Sandeen 
2469882dbe0cSJosef Bacik 	/* If IGNOREDATACSUMS is set don't bother reading the csum root. */
2470882dbe0cSJosef Bacik 	if (!btrfs_test_opt(fs_info, IGNOREDATACSUMS)) {
24714bbcaa64SEric Sandeen 		location.objectid = BTRFS_CSUM_TREE_OBJECTID;
2472a4f3d2c4SDavid Sterba 		root = btrfs_read_tree_root(tree_root, &location);
2473f50f4353SLiu Bo 		if (IS_ERR(root)) {
247442437a63SJosef Bacik 			if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2475f50f4353SLiu Bo 				ret = PTR_ERR(root);
2476f50f4353SLiu Bo 				goto out;
2477f50f4353SLiu Bo 			}
247842437a63SJosef Bacik 		} else {
2479a4f3d2c4SDavid Sterba 			set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2480a4f3d2c4SDavid Sterba 			fs_info->csum_root = root;
248142437a63SJosef Bacik 		}
2482882dbe0cSJosef Bacik 	}
24834bbcaa64SEric Sandeen 
2484aeb935a4SQu Wenruo 	/*
2485aeb935a4SQu Wenruo 	 * This tree can share blocks with some other fs tree during relocation
2486aeb935a4SQu Wenruo 	 * and we need a proper setup by btrfs_get_fs_root
2487aeb935a4SQu Wenruo 	 */
248856e9357aSDavid Sterba 	root = btrfs_get_fs_root(tree_root->fs_info,
248956e9357aSDavid Sterba 				 BTRFS_DATA_RELOC_TREE_OBJECTID, true);
2490aeb935a4SQu Wenruo 	if (IS_ERR(root)) {
249142437a63SJosef Bacik 		if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2492aeb935a4SQu Wenruo 			ret = PTR_ERR(root);
2493aeb935a4SQu Wenruo 			goto out;
2494aeb935a4SQu Wenruo 		}
249542437a63SJosef Bacik 	} else {
2496aeb935a4SQu Wenruo 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2497aeb935a4SQu Wenruo 		fs_info->data_reloc_root = root;
249842437a63SJosef Bacik 	}
2499aeb935a4SQu Wenruo 
25004bbcaa64SEric Sandeen 	location.objectid = BTRFS_QUOTA_TREE_OBJECTID;
2501a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2502a4f3d2c4SDavid Sterba 	if (!IS_ERR(root)) {
2503a4f3d2c4SDavid Sterba 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2504afcdd129SJosef Bacik 		set_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags);
2505a4f3d2c4SDavid Sterba 		fs_info->quota_root = root;
25064bbcaa64SEric Sandeen 	}
25074bbcaa64SEric Sandeen 
25084bbcaa64SEric Sandeen 	location.objectid = BTRFS_UUID_TREE_OBJECTID;
2509a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2510a4f3d2c4SDavid Sterba 	if (IS_ERR(root)) {
251142437a63SJosef Bacik 		if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2512a4f3d2c4SDavid Sterba 			ret = PTR_ERR(root);
25134bbcaa64SEric Sandeen 			if (ret != -ENOENT)
2514f50f4353SLiu Bo 				goto out;
251542437a63SJosef Bacik 		}
25164bbcaa64SEric Sandeen 	} else {
2517a4f3d2c4SDavid Sterba 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2518a4f3d2c4SDavid Sterba 		fs_info->uuid_root = root;
25194bbcaa64SEric Sandeen 	}
25204bbcaa64SEric Sandeen 
252170f6d82eSOmar Sandoval 	if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
252270f6d82eSOmar Sandoval 		location.objectid = BTRFS_FREE_SPACE_TREE_OBJECTID;
252370f6d82eSOmar Sandoval 		root = btrfs_read_tree_root(tree_root, &location);
2524f50f4353SLiu Bo 		if (IS_ERR(root)) {
252542437a63SJosef Bacik 			if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2526f50f4353SLiu Bo 				ret = PTR_ERR(root);
2527f50f4353SLiu Bo 				goto out;
2528f50f4353SLiu Bo 			}
252942437a63SJosef Bacik 		}  else {
253070f6d82eSOmar Sandoval 			set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
253170f6d82eSOmar Sandoval 			fs_info->free_space_root = root;
253270f6d82eSOmar Sandoval 		}
253342437a63SJosef Bacik 	}
253470f6d82eSOmar Sandoval 
25354bbcaa64SEric Sandeen 	return 0;
2536f50f4353SLiu Bo out:
2537f50f4353SLiu Bo 	btrfs_warn(fs_info, "failed to read root (objectid=%llu): %d",
2538f50f4353SLiu Bo 		   location.objectid, ret);
2539f50f4353SLiu Bo 	return ret;
25404bbcaa64SEric Sandeen }
25414bbcaa64SEric Sandeen 
2542069ec957SQu Wenruo /*
2543069ec957SQu Wenruo  * Real super block validation
2544069ec957SQu Wenruo  * NOTE: super csum type and incompat features will not be checked here.
2545069ec957SQu Wenruo  *
2546069ec957SQu Wenruo  * @sb:		super block to check
2547069ec957SQu Wenruo  * @mirror_num:	the super block number to check its bytenr:
2548069ec957SQu Wenruo  * 		0	the primary (1st) sb
2549069ec957SQu Wenruo  * 		1, 2	2nd and 3rd backup copy
2550069ec957SQu Wenruo  * 	       -1	skip bytenr check
2551069ec957SQu Wenruo  */
2552069ec957SQu Wenruo static int validate_super(struct btrfs_fs_info *fs_info,
2553069ec957SQu Wenruo 			    struct btrfs_super_block *sb, int mirror_num)
255421a852b0SQu Wenruo {
255521a852b0SQu Wenruo 	u64 nodesize = btrfs_super_nodesize(sb);
255621a852b0SQu Wenruo 	u64 sectorsize = btrfs_super_sectorsize(sb);
255721a852b0SQu Wenruo 	int ret = 0;
255821a852b0SQu Wenruo 
255921a852b0SQu Wenruo 	if (btrfs_super_magic(sb) != BTRFS_MAGIC) {
256021a852b0SQu Wenruo 		btrfs_err(fs_info, "no valid FS found");
256121a852b0SQu Wenruo 		ret = -EINVAL;
256221a852b0SQu Wenruo 	}
256321a852b0SQu Wenruo 	if (btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP) {
256421a852b0SQu Wenruo 		btrfs_err(fs_info, "unrecognized or unsupported super flag: %llu",
256521a852b0SQu Wenruo 				btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP);
256621a852b0SQu Wenruo 		ret = -EINVAL;
256721a852b0SQu Wenruo 	}
256821a852b0SQu Wenruo 	if (btrfs_super_root_level(sb) >= BTRFS_MAX_LEVEL) {
256921a852b0SQu Wenruo 		btrfs_err(fs_info, "tree_root level too big: %d >= %d",
257021a852b0SQu Wenruo 				btrfs_super_root_level(sb), BTRFS_MAX_LEVEL);
257121a852b0SQu Wenruo 		ret = -EINVAL;
257221a852b0SQu Wenruo 	}
257321a852b0SQu Wenruo 	if (btrfs_super_chunk_root_level(sb) >= BTRFS_MAX_LEVEL) {
257421a852b0SQu Wenruo 		btrfs_err(fs_info, "chunk_root level too big: %d >= %d",
257521a852b0SQu Wenruo 				btrfs_super_chunk_root_level(sb), BTRFS_MAX_LEVEL);
257621a852b0SQu Wenruo 		ret = -EINVAL;
257721a852b0SQu Wenruo 	}
257821a852b0SQu Wenruo 	if (btrfs_super_log_root_level(sb) >= BTRFS_MAX_LEVEL) {
257921a852b0SQu Wenruo 		btrfs_err(fs_info, "log_root level too big: %d >= %d",
258021a852b0SQu Wenruo 				btrfs_super_log_root_level(sb), BTRFS_MAX_LEVEL);
258121a852b0SQu Wenruo 		ret = -EINVAL;
258221a852b0SQu Wenruo 	}
258321a852b0SQu Wenruo 
258421a852b0SQu Wenruo 	/*
258521a852b0SQu Wenruo 	 * Check sectorsize and nodesize first, other check will need it.
258621a852b0SQu Wenruo 	 * Check all possible sectorsize(4K, 8K, 16K, 32K, 64K) here.
258721a852b0SQu Wenruo 	 */
258821a852b0SQu Wenruo 	if (!is_power_of_2(sectorsize) || sectorsize < 4096 ||
258921a852b0SQu Wenruo 	    sectorsize > BTRFS_MAX_METADATA_BLOCKSIZE) {
259021a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid sectorsize %llu", sectorsize);
259121a852b0SQu Wenruo 		ret = -EINVAL;
259221a852b0SQu Wenruo 	}
25930bb3eb3eSQu Wenruo 
25940bb3eb3eSQu Wenruo 	/*
25950bb3eb3eSQu Wenruo 	 * For 4K page size, we only support 4K sector size.
25960bb3eb3eSQu Wenruo 	 * For 64K page size, we support read-write for 64K sector size, and
25970bb3eb3eSQu Wenruo 	 * read-only for 4K sector size.
25980bb3eb3eSQu Wenruo 	 */
25990bb3eb3eSQu Wenruo 	if ((PAGE_SIZE == SZ_4K && sectorsize != PAGE_SIZE) ||
26000bb3eb3eSQu Wenruo 	    (PAGE_SIZE == SZ_64K && (sectorsize != SZ_4K &&
26010bb3eb3eSQu Wenruo 				     sectorsize != SZ_64K))) {
260221a852b0SQu Wenruo 		btrfs_err(fs_info,
26030bb3eb3eSQu Wenruo 			"sectorsize %llu not yet supported for page size %lu",
260421a852b0SQu Wenruo 			sectorsize, PAGE_SIZE);
260521a852b0SQu Wenruo 		ret = -EINVAL;
260621a852b0SQu Wenruo 	}
26070bb3eb3eSQu Wenruo 
260821a852b0SQu Wenruo 	if (!is_power_of_2(nodesize) || nodesize < sectorsize ||
260921a852b0SQu Wenruo 	    nodesize > BTRFS_MAX_METADATA_BLOCKSIZE) {
261021a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid nodesize %llu", nodesize);
261121a852b0SQu Wenruo 		ret = -EINVAL;
261221a852b0SQu Wenruo 	}
261321a852b0SQu Wenruo 	if (nodesize != le32_to_cpu(sb->__unused_leafsize)) {
261421a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid leafsize %u, should be %llu",
261521a852b0SQu Wenruo 			  le32_to_cpu(sb->__unused_leafsize), nodesize);
261621a852b0SQu Wenruo 		ret = -EINVAL;
261721a852b0SQu Wenruo 	}
261821a852b0SQu Wenruo 
261921a852b0SQu Wenruo 	/* Root alignment check */
262021a852b0SQu Wenruo 	if (!IS_ALIGNED(btrfs_super_root(sb), sectorsize)) {
262121a852b0SQu Wenruo 		btrfs_warn(fs_info, "tree_root block unaligned: %llu",
262221a852b0SQu Wenruo 			   btrfs_super_root(sb));
262321a852b0SQu Wenruo 		ret = -EINVAL;
262421a852b0SQu Wenruo 	}
262521a852b0SQu Wenruo 	if (!IS_ALIGNED(btrfs_super_chunk_root(sb), sectorsize)) {
262621a852b0SQu Wenruo 		btrfs_warn(fs_info, "chunk_root block unaligned: %llu",
262721a852b0SQu Wenruo 			   btrfs_super_chunk_root(sb));
262821a852b0SQu Wenruo 		ret = -EINVAL;
262921a852b0SQu Wenruo 	}
263021a852b0SQu Wenruo 	if (!IS_ALIGNED(btrfs_super_log_root(sb), sectorsize)) {
263121a852b0SQu Wenruo 		btrfs_warn(fs_info, "log_root block unaligned: %llu",
263221a852b0SQu Wenruo 			   btrfs_super_log_root(sb));
263321a852b0SQu Wenruo 		ret = -EINVAL;
263421a852b0SQu Wenruo 	}
263521a852b0SQu Wenruo 
2636aefd7f70SNikolay Borisov 	if (memcmp(fs_info->fs_devices->fsid, fs_info->super_copy->fsid,
2637aefd7f70SNikolay Borisov 		   BTRFS_FSID_SIZE)) {
2638aefd7f70SNikolay Borisov 		btrfs_err(fs_info,
2639aefd7f70SNikolay Borisov 		"superblock fsid doesn't match fsid of fs_devices: %pU != %pU",
2640aefd7f70SNikolay Borisov 			fs_info->super_copy->fsid, fs_info->fs_devices->fsid);
2641aefd7f70SNikolay Borisov 		ret = -EINVAL;
2642aefd7f70SNikolay Borisov 	}
2643aefd7f70SNikolay Borisov 
2644aefd7f70SNikolay Borisov 	if (btrfs_fs_incompat(fs_info, METADATA_UUID) &&
2645aefd7f70SNikolay Borisov 	    memcmp(fs_info->fs_devices->metadata_uuid,
2646aefd7f70SNikolay Borisov 		   fs_info->super_copy->metadata_uuid, BTRFS_FSID_SIZE)) {
2647aefd7f70SNikolay Borisov 		btrfs_err(fs_info,
2648aefd7f70SNikolay Borisov "superblock metadata_uuid doesn't match metadata uuid of fs_devices: %pU != %pU",
2649aefd7f70SNikolay Borisov 			fs_info->super_copy->metadata_uuid,
2650aefd7f70SNikolay Borisov 			fs_info->fs_devices->metadata_uuid);
2651aefd7f70SNikolay Borisov 		ret = -EINVAL;
2652aefd7f70SNikolay Borisov 	}
2653aefd7f70SNikolay Borisov 
2654de37aa51SNikolay Borisov 	if (memcmp(fs_info->fs_devices->metadata_uuid, sb->dev_item.fsid,
26557239ff4bSNikolay Borisov 		   BTRFS_FSID_SIZE) != 0) {
265621a852b0SQu Wenruo 		btrfs_err(fs_info,
26577239ff4bSNikolay Borisov 			"dev_item UUID does not match metadata fsid: %pU != %pU",
2658de37aa51SNikolay Borisov 			fs_info->fs_devices->metadata_uuid, sb->dev_item.fsid);
265921a852b0SQu Wenruo 		ret = -EINVAL;
266021a852b0SQu Wenruo 	}
266121a852b0SQu Wenruo 
266221a852b0SQu Wenruo 	/*
266321a852b0SQu Wenruo 	 * Hint to catch really bogus numbers, bitflips or so, more exact checks are
266421a852b0SQu Wenruo 	 * done later
266521a852b0SQu Wenruo 	 */
266621a852b0SQu Wenruo 	if (btrfs_super_bytes_used(sb) < 6 * btrfs_super_nodesize(sb)) {
266721a852b0SQu Wenruo 		btrfs_err(fs_info, "bytes_used is too small %llu",
266821a852b0SQu Wenruo 			  btrfs_super_bytes_used(sb));
266921a852b0SQu Wenruo 		ret = -EINVAL;
267021a852b0SQu Wenruo 	}
267121a852b0SQu Wenruo 	if (!is_power_of_2(btrfs_super_stripesize(sb))) {
267221a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid stripesize %u",
267321a852b0SQu Wenruo 			  btrfs_super_stripesize(sb));
267421a852b0SQu Wenruo 		ret = -EINVAL;
267521a852b0SQu Wenruo 	}
267621a852b0SQu Wenruo 	if (btrfs_super_num_devices(sb) > (1UL << 31))
267721a852b0SQu Wenruo 		btrfs_warn(fs_info, "suspicious number of devices: %llu",
267821a852b0SQu Wenruo 			   btrfs_super_num_devices(sb));
267921a852b0SQu Wenruo 	if (btrfs_super_num_devices(sb) == 0) {
268021a852b0SQu Wenruo 		btrfs_err(fs_info, "number of devices is 0");
268121a852b0SQu Wenruo 		ret = -EINVAL;
268221a852b0SQu Wenruo 	}
268321a852b0SQu Wenruo 
2684069ec957SQu Wenruo 	if (mirror_num >= 0 &&
2685069ec957SQu Wenruo 	    btrfs_super_bytenr(sb) != btrfs_sb_offset(mirror_num)) {
268621a852b0SQu Wenruo 		btrfs_err(fs_info, "super offset mismatch %llu != %u",
268721a852b0SQu Wenruo 			  btrfs_super_bytenr(sb), BTRFS_SUPER_INFO_OFFSET);
268821a852b0SQu Wenruo 		ret = -EINVAL;
268921a852b0SQu Wenruo 	}
269021a852b0SQu Wenruo 
269121a852b0SQu Wenruo 	/*
269221a852b0SQu Wenruo 	 * Obvious sys_chunk_array corruptions, it must hold at least one key
269321a852b0SQu Wenruo 	 * and one chunk
269421a852b0SQu Wenruo 	 */
269521a852b0SQu Wenruo 	if (btrfs_super_sys_array_size(sb) > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
269621a852b0SQu Wenruo 		btrfs_err(fs_info, "system chunk array too big %u > %u",
269721a852b0SQu Wenruo 			  btrfs_super_sys_array_size(sb),
269821a852b0SQu Wenruo 			  BTRFS_SYSTEM_CHUNK_ARRAY_SIZE);
269921a852b0SQu Wenruo 		ret = -EINVAL;
270021a852b0SQu Wenruo 	}
270121a852b0SQu Wenruo 	if (btrfs_super_sys_array_size(sb) < sizeof(struct btrfs_disk_key)
270221a852b0SQu Wenruo 			+ sizeof(struct btrfs_chunk)) {
270321a852b0SQu Wenruo 		btrfs_err(fs_info, "system chunk array too small %u < %zu",
270421a852b0SQu Wenruo 			  btrfs_super_sys_array_size(sb),
270521a852b0SQu Wenruo 			  sizeof(struct btrfs_disk_key)
270621a852b0SQu Wenruo 			  + sizeof(struct btrfs_chunk));
270721a852b0SQu Wenruo 		ret = -EINVAL;
270821a852b0SQu Wenruo 	}
270921a852b0SQu Wenruo 
271021a852b0SQu Wenruo 	/*
271121a852b0SQu Wenruo 	 * The generation is a global counter, we'll trust it more than the others
271221a852b0SQu Wenruo 	 * but it's still possible that it's the one that's wrong.
271321a852b0SQu Wenruo 	 */
271421a852b0SQu Wenruo 	if (btrfs_super_generation(sb) < btrfs_super_chunk_root_generation(sb))
271521a852b0SQu Wenruo 		btrfs_warn(fs_info,
271621a852b0SQu Wenruo 			"suspicious: generation < chunk_root_generation: %llu < %llu",
271721a852b0SQu Wenruo 			btrfs_super_generation(sb),
271821a852b0SQu Wenruo 			btrfs_super_chunk_root_generation(sb));
271921a852b0SQu Wenruo 	if (btrfs_super_generation(sb) < btrfs_super_cache_generation(sb)
272021a852b0SQu Wenruo 	    && btrfs_super_cache_generation(sb) != (u64)-1)
272121a852b0SQu Wenruo 		btrfs_warn(fs_info,
272221a852b0SQu Wenruo 			"suspicious: generation < cache_generation: %llu < %llu",
272321a852b0SQu Wenruo 			btrfs_super_generation(sb),
272421a852b0SQu Wenruo 			btrfs_super_cache_generation(sb));
272521a852b0SQu Wenruo 
272621a852b0SQu Wenruo 	return ret;
272721a852b0SQu Wenruo }
272821a852b0SQu Wenruo 
2729069ec957SQu Wenruo /*
2730069ec957SQu Wenruo  * Validation of super block at mount time.
2731069ec957SQu Wenruo  * Some checks already done early at mount time, like csum type and incompat
2732069ec957SQu Wenruo  * flags will be skipped.
2733069ec957SQu Wenruo  */
2734069ec957SQu Wenruo static int btrfs_validate_mount_super(struct btrfs_fs_info *fs_info)
2735069ec957SQu Wenruo {
2736069ec957SQu Wenruo 	return validate_super(fs_info, fs_info->super_copy, 0);
2737069ec957SQu Wenruo }
2738069ec957SQu Wenruo 
273975cb857dSQu Wenruo /*
274075cb857dSQu Wenruo  * Validation of super block at write time.
274175cb857dSQu Wenruo  * Some checks like bytenr check will be skipped as their values will be
274275cb857dSQu Wenruo  * overwritten soon.
274375cb857dSQu Wenruo  * Extra checks like csum type and incompat flags will be done here.
274475cb857dSQu Wenruo  */
274575cb857dSQu Wenruo static int btrfs_validate_write_super(struct btrfs_fs_info *fs_info,
274675cb857dSQu Wenruo 				      struct btrfs_super_block *sb)
274775cb857dSQu Wenruo {
274875cb857dSQu Wenruo 	int ret;
274975cb857dSQu Wenruo 
275075cb857dSQu Wenruo 	ret = validate_super(fs_info, sb, -1);
275175cb857dSQu Wenruo 	if (ret < 0)
275275cb857dSQu Wenruo 		goto out;
2753e7e16f48SJohannes Thumshirn 	if (!btrfs_supported_super_csum(btrfs_super_csum_type(sb))) {
275475cb857dSQu Wenruo 		ret = -EUCLEAN;
275575cb857dSQu Wenruo 		btrfs_err(fs_info, "invalid csum type, has %u want %u",
275675cb857dSQu Wenruo 			  btrfs_super_csum_type(sb), BTRFS_CSUM_TYPE_CRC32);
275775cb857dSQu Wenruo 		goto out;
275875cb857dSQu Wenruo 	}
275975cb857dSQu Wenruo 	if (btrfs_super_incompat_flags(sb) & ~BTRFS_FEATURE_INCOMPAT_SUPP) {
276075cb857dSQu Wenruo 		ret = -EUCLEAN;
276175cb857dSQu Wenruo 		btrfs_err(fs_info,
276275cb857dSQu Wenruo 		"invalid incompat flags, has 0x%llx valid mask 0x%llx",
276375cb857dSQu Wenruo 			  btrfs_super_incompat_flags(sb),
276475cb857dSQu Wenruo 			  (unsigned long long)BTRFS_FEATURE_INCOMPAT_SUPP);
276575cb857dSQu Wenruo 		goto out;
276675cb857dSQu Wenruo 	}
276775cb857dSQu Wenruo out:
276875cb857dSQu Wenruo 	if (ret < 0)
276975cb857dSQu Wenruo 		btrfs_err(fs_info,
277075cb857dSQu Wenruo 		"super block corruption detected before writing it to disk");
277175cb857dSQu Wenruo 	return ret;
277275cb857dSQu Wenruo }
277375cb857dSQu Wenruo 
27746ef108ddSNikolay Borisov static int __cold init_tree_roots(struct btrfs_fs_info *fs_info)
2775b8522a1eSNikolay Borisov {
27766ef108ddSNikolay Borisov 	int backup_index = find_newest_super_backup(fs_info);
2777b8522a1eSNikolay Borisov 	struct btrfs_super_block *sb = fs_info->super_copy;
2778b8522a1eSNikolay Borisov 	struct btrfs_root *tree_root = fs_info->tree_root;
2779b8522a1eSNikolay Borisov 	bool handle_error = false;
2780b8522a1eSNikolay Borisov 	int ret = 0;
2781b8522a1eSNikolay Borisov 	int i;
2782b8522a1eSNikolay Borisov 
2783b8522a1eSNikolay Borisov 	for (i = 0; i < BTRFS_NUM_BACKUP_ROOTS; i++) {
2784b8522a1eSNikolay Borisov 		u64 generation;
2785b8522a1eSNikolay Borisov 		int level;
2786b8522a1eSNikolay Borisov 
2787b8522a1eSNikolay Borisov 		if (handle_error) {
2788b8522a1eSNikolay Borisov 			if (!IS_ERR(tree_root->node))
2789b8522a1eSNikolay Borisov 				free_extent_buffer(tree_root->node);
2790b8522a1eSNikolay Borisov 			tree_root->node = NULL;
2791b8522a1eSNikolay Borisov 
2792b8522a1eSNikolay Borisov 			if (!btrfs_test_opt(fs_info, USEBACKUPROOT))
2793b8522a1eSNikolay Borisov 				break;
2794b8522a1eSNikolay Borisov 
2795b8522a1eSNikolay Borisov 			free_root_pointers(fs_info, 0);
2796b8522a1eSNikolay Borisov 
2797b8522a1eSNikolay Borisov 			/*
2798b8522a1eSNikolay Borisov 			 * Don't use the log in recovery mode, it won't be
2799b8522a1eSNikolay Borisov 			 * valid
2800b8522a1eSNikolay Borisov 			 */
2801b8522a1eSNikolay Borisov 			btrfs_set_super_log_root(sb, 0);
2802b8522a1eSNikolay Borisov 
2803b8522a1eSNikolay Borisov 			/* We can't trust the free space cache either */
2804b8522a1eSNikolay Borisov 			btrfs_set_opt(fs_info->mount_opt, CLEAR_CACHE);
2805b8522a1eSNikolay Borisov 
2806b8522a1eSNikolay Borisov 			ret = read_backup_root(fs_info, i);
28076ef108ddSNikolay Borisov 			backup_index = ret;
2808b8522a1eSNikolay Borisov 			if (ret < 0)
2809b8522a1eSNikolay Borisov 				return ret;
2810b8522a1eSNikolay Borisov 		}
2811b8522a1eSNikolay Borisov 		generation = btrfs_super_generation(sb);
2812b8522a1eSNikolay Borisov 		level = btrfs_super_root_level(sb);
2813b8522a1eSNikolay Borisov 		tree_root->node = read_tree_block(fs_info, btrfs_super_root(sb),
28141b7ec85eSJosef Bacik 						  BTRFS_ROOT_TREE_OBJECTID,
2815b8522a1eSNikolay Borisov 						  generation, level, NULL);
28160465337cSJosef Bacik 		if (IS_ERR(tree_root->node)) {
2817217f5004SNikolay Borisov 			handle_error = true;
2818b8522a1eSNikolay Borisov 			ret = PTR_ERR(tree_root->node);
28190465337cSJosef Bacik 			tree_root->node = NULL;
2820217f5004SNikolay Borisov 			btrfs_warn(fs_info, "couldn't read tree root");
2821217f5004SNikolay Borisov 			continue;
2822b8522a1eSNikolay Borisov 
2823217f5004SNikolay Borisov 		} else if (!extent_buffer_uptodate(tree_root->node)) {
2824217f5004SNikolay Borisov 			handle_error = true;
2825217f5004SNikolay Borisov 			ret = -EIO;
2826217f5004SNikolay Borisov 			btrfs_warn(fs_info, "error while reading tree root");
2827b8522a1eSNikolay Borisov 			continue;
2828b8522a1eSNikolay Borisov 		}
2829b8522a1eSNikolay Borisov 
2830b8522a1eSNikolay Borisov 		btrfs_set_root_node(&tree_root->root_item, tree_root->node);
2831b8522a1eSNikolay Borisov 		tree_root->commit_root = btrfs_root_node(tree_root);
2832b8522a1eSNikolay Borisov 		btrfs_set_root_refs(&tree_root->root_item, 1);
2833b8522a1eSNikolay Borisov 
2834336a0d8dSNikolay Borisov 		/*
2835336a0d8dSNikolay Borisov 		 * No need to hold btrfs_root::objectid_mutex since the fs
2836336a0d8dSNikolay Borisov 		 * hasn't been fully initialised and we are the only user
2837336a0d8dSNikolay Borisov 		 */
2838453e4873SNikolay Borisov 		ret = btrfs_init_root_free_objectid(tree_root);
2839b8522a1eSNikolay Borisov 		if (ret < 0) {
2840b8522a1eSNikolay Borisov 			handle_error = true;
2841b8522a1eSNikolay Borisov 			continue;
2842b8522a1eSNikolay Borisov 		}
2843b8522a1eSNikolay Borisov 
28446b8fad57SNikolay Borisov 		ASSERT(tree_root->free_objectid <= BTRFS_LAST_FREE_OBJECTID);
2845b8522a1eSNikolay Borisov 
2846b8522a1eSNikolay Borisov 		ret = btrfs_read_roots(fs_info);
2847b8522a1eSNikolay Borisov 		if (ret < 0) {
2848b8522a1eSNikolay Borisov 			handle_error = true;
2849b8522a1eSNikolay Borisov 			continue;
2850b8522a1eSNikolay Borisov 		}
2851b8522a1eSNikolay Borisov 
2852b8522a1eSNikolay Borisov 		/* All successful */
2853b8522a1eSNikolay Borisov 		fs_info->generation = generation;
2854b8522a1eSNikolay Borisov 		fs_info->last_trans_committed = generation;
28556ef108ddSNikolay Borisov 
28566ef108ddSNikolay Borisov 		/* Always begin writing backup roots after the one being used */
28576ef108ddSNikolay Borisov 		if (backup_index < 0) {
28586ef108ddSNikolay Borisov 			fs_info->backup_root_index = 0;
28596ef108ddSNikolay Borisov 		} else {
28606ef108ddSNikolay Borisov 			fs_info->backup_root_index = backup_index + 1;
28616ef108ddSNikolay Borisov 			fs_info->backup_root_index %= BTRFS_NUM_BACKUP_ROOTS;
28626ef108ddSNikolay Borisov 		}
2863b8522a1eSNikolay Borisov 		break;
2864b8522a1eSNikolay Borisov 	}
2865b8522a1eSNikolay Borisov 
2866b8522a1eSNikolay Borisov 	return ret;
2867b8522a1eSNikolay Borisov }
2868b8522a1eSNikolay Borisov 
28698260edbaSJosef Bacik void btrfs_init_fs_info(struct btrfs_fs_info *fs_info)
2870eb60ceacSChris Mason {
287176dda93cSYan, Zheng 	INIT_RADIX_TREE(&fs_info->fs_roots_radix, GFP_ATOMIC);
2872f28491e0SJosef Bacik 	INIT_RADIX_TREE(&fs_info->buffer_radix, GFP_ATOMIC);
28738fd17795SChris Mason 	INIT_LIST_HEAD(&fs_info->trans_list);
2874facda1e7SChris Mason 	INIT_LIST_HEAD(&fs_info->dead_roots);
287524bbcf04SYan, Zheng 	INIT_LIST_HEAD(&fs_info->delayed_iputs);
2876eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&fs_info->delalloc_roots);
287711833d66SYan Zheng 	INIT_LIST_HEAD(&fs_info->caching_block_groups);
2878eb73c1b7SMiao Xie 	spin_lock_init(&fs_info->delalloc_root_lock);
2879a4abeea4SJosef Bacik 	spin_lock_init(&fs_info->trans_lock);
288076dda93cSYan, Zheng 	spin_lock_init(&fs_info->fs_roots_radix_lock);
288124bbcf04SYan, Zheng 	spin_lock_init(&fs_info->delayed_iput_lock);
28824cb5300bSChris Mason 	spin_lock_init(&fs_info->defrag_inodes_lock);
2883ceda0864SMiao Xie 	spin_lock_init(&fs_info->super_lock);
2884f28491e0SJosef Bacik 	spin_lock_init(&fs_info->buffer_lock);
288547ab2a6cSJosef Bacik 	spin_lock_init(&fs_info->unused_bgs_lock);
288640ab3be1SNaohiro Aota 	spin_lock_init(&fs_info->treelog_bg_lock);
2887*afba2bc0SNaohiro Aota 	spin_lock_init(&fs_info->zone_active_bgs_lock);
2888f29021b2SJan Schmidt 	rwlock_init(&fs_info->tree_mod_log_lock);
2889d7c15171SZhao Lei 	mutex_init(&fs_info->unused_bg_unpin_mutex);
2890f3372065SJohannes Thumshirn 	mutex_init(&fs_info->reclaim_bgs_lock);
28917585717fSChris Mason 	mutex_init(&fs_info->reloc_mutex);
2892573bfb72SMiao Xie 	mutex_init(&fs_info->delalloc_root_mutex);
28930bc09ca1SNaohiro Aota 	mutex_init(&fs_info->zoned_meta_io_lock);
2894de98ced9SMiao Xie 	seqlock_init(&fs_info->profiles_lock);
289519c00ddcSChris Mason 
28960b86a832SChris Mason 	INIT_LIST_HEAD(&fs_info->dirty_cowonly_roots);
28976324fbf3SChris Mason 	INIT_LIST_HEAD(&fs_info->space_info);
2898f29021b2SJan Schmidt 	INIT_LIST_HEAD(&fs_info->tree_mod_seq_list);
289947ab2a6cSJosef Bacik 	INIT_LIST_HEAD(&fs_info->unused_bgs);
290018bb8bbfSJohannes Thumshirn 	INIT_LIST_HEAD(&fs_info->reclaim_bgs);
2901*afba2bc0SNaohiro Aota 	INIT_LIST_HEAD(&fs_info->zone_active_bgs);
2902bd647ce3SJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
2903bd647ce3SJosef Bacik 	INIT_LIST_HEAD(&fs_info->allocated_roots);
29043fd63727SJosef Bacik 	INIT_LIST_HEAD(&fs_info->allocated_ebs);
29053fd63727SJosef Bacik 	spin_lock_init(&fs_info->eb_leak_lock);
2906bd647ce3SJosef Bacik #endif
2907c8bf1b67SDavid Sterba 	extent_map_tree_init(&fs_info->mapping_tree);
290866d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->global_block_rsv,
290966d8f3ddSMiao Xie 			     BTRFS_BLOCK_RSV_GLOBAL);
291066d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->trans_block_rsv, BTRFS_BLOCK_RSV_TRANS);
291166d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->chunk_block_rsv, BTRFS_BLOCK_RSV_CHUNK);
291266d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->empty_block_rsv, BTRFS_BLOCK_RSV_EMPTY);
291366d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->delayed_block_rsv,
291466d8f3ddSMiao Xie 			     BTRFS_BLOCK_RSV_DELOPS);
2915ba2c4d4eSJosef Bacik 	btrfs_init_block_rsv(&fs_info->delayed_refs_rsv,
2916ba2c4d4eSJosef Bacik 			     BTRFS_BLOCK_RSV_DELREFS);
2917ba2c4d4eSJosef Bacik 
2918771ed689SChris Mason 	atomic_set(&fs_info->async_delalloc_pages, 0);
29194cb5300bSChris Mason 	atomic_set(&fs_info->defrag_running, 0);
29202fefd558SZhao Lei 	atomic_set(&fs_info->reada_works_cnt, 0);
2921034f784dSJosef Bacik 	atomic_set(&fs_info->nr_delayed_iputs, 0);
2922fc36ed7eSJan Schmidt 	atomic64_set(&fs_info->tree_mod_seq, 0);
292395ac567aSFilipe David Borba Manana 	fs_info->max_inline = BTRFS_DEFAULT_MAX_INLINE;
29249ed74f2dSJosef Bacik 	fs_info->metadata_ratio = 0;
29254cb5300bSChris Mason 	fs_info->defrag_inodes = RB_ROOT;
2926a5ed45f8SNikolay Borisov 	atomic64_set(&fs_info->free_chunk_space, 0);
2927f29021b2SJan Schmidt 	fs_info->tree_mod_log = RB_ROOT;
29288b87dc17SDavid Sterba 	fs_info->commit_interval = BTRFS_DEFAULT_COMMIT_INTERVAL;
2929f8c269d7SDavid Sterba 	fs_info->avg_delayed_ref_runtime = NSEC_PER_SEC >> 6; /* div by 64 */
293090519d66SArne Jansen 	/* readahead state */
2931d0164adcSMel Gorman 	INIT_RADIX_TREE(&fs_info->reada_tree, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
293290519d66SArne Jansen 	spin_lock_init(&fs_info->reada_lock);
2933fd708b81SJosef Bacik 	btrfs_init_ref_verify(fs_info);
2934c8b97818SChris Mason 
2935b34b086cSChris Mason 	fs_info->thread_pool_size = min_t(unsigned long,
2936b34b086cSChris Mason 					  num_online_cpus() + 2, 8);
29370afbaf8cSChris Mason 
2938199c2a9cSMiao Xie 	INIT_LIST_HEAD(&fs_info->ordered_roots);
2939199c2a9cSMiao Xie 	spin_lock_init(&fs_info->ordered_root_lock);
294069fe2d75SJosef Bacik 
2941638aa7edSEric Sandeen 	btrfs_init_scrub(fs_info);
294221adbd5cSStefan Behrens #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
294321adbd5cSStefan Behrens 	fs_info->check_integrity_print_mask = 0;
294421adbd5cSStefan Behrens #endif
2945779a65a4SEric Sandeen 	btrfs_init_balance(fs_info);
294657056740SJosef Bacik 	btrfs_init_async_reclaim_work(fs_info);
2947a2de733cSArne Jansen 
29480f9dd46cSJosef Bacik 	spin_lock_init(&fs_info->block_group_cache_lock);
29496bef4d31SEric Paris 	fs_info->block_group_cache_tree = RB_ROOT;
2950a1897fddSLiu Bo 	fs_info->first_logical_byte = (u64)-1;
29510f9dd46cSJosef Bacik 
2952fe119a6eSNikolay Borisov 	extent_io_tree_init(fs_info, &fs_info->excluded_extents,
2953fe119a6eSNikolay Borisov 			    IO_TREE_FS_EXCLUDED_EXTENTS, NULL);
2954afcdd129SJosef Bacik 	set_bit(BTRFS_FS_BARRIER, &fs_info->flags);
295539279cc3SChris Mason 
29565a3f23d5SChris Mason 	mutex_init(&fs_info->ordered_operations_mutex);
2957e02119d5SChris Mason 	mutex_init(&fs_info->tree_log_mutex);
2958925baeddSChris Mason 	mutex_init(&fs_info->chunk_mutex);
2959a74a4b97SChris Mason 	mutex_init(&fs_info->transaction_kthread_mutex);
2960a74a4b97SChris Mason 	mutex_init(&fs_info->cleaner_mutex);
29611bbc621eSChris Mason 	mutex_init(&fs_info->ro_block_group_mutex);
29629e351cc8SJosef Bacik 	init_rwsem(&fs_info->commit_root_sem);
2963c71bf099SYan, Zheng 	init_rwsem(&fs_info->cleanup_work_sem);
296476dda93cSYan, Zheng 	init_rwsem(&fs_info->subvol_sem);
2965803b2f54SStefan Behrens 	sema_init(&fs_info->uuid_tree_rescan_sem, 1);
2966fa9c0d79SChris Mason 
2967ad618368SEric Sandeen 	btrfs_init_dev_replace_locks(fs_info);
2968f9e92e40SEric Sandeen 	btrfs_init_qgroup(fs_info);
2969b0643e59SDennis Zhou 	btrfs_discard_init(fs_info);
2970416ac51dSArne Jansen 
2971fa9c0d79SChris Mason 	btrfs_init_free_cluster(&fs_info->meta_alloc_cluster);
2972fa9c0d79SChris Mason 	btrfs_init_free_cluster(&fs_info->data_alloc_cluster);
2973fa9c0d79SChris Mason 
2974e6dcd2dcSChris Mason 	init_waitqueue_head(&fs_info->transaction_throttle);
2975f9295749SChris Mason 	init_waitqueue_head(&fs_info->transaction_wait);
2976bb9c12c9SSage Weil 	init_waitqueue_head(&fs_info->transaction_blocked_wait);
29774854ddd0SChris Mason 	init_waitqueue_head(&fs_info->async_submit_wait);
2978034f784dSJosef Bacik 	init_waitqueue_head(&fs_info->delayed_iputs_wait);
29793768f368SChris Mason 
2980da17066cSJeff Mahoney 	/* Usable values until the real ones are cached from the superblock */
2981da17066cSJeff Mahoney 	fs_info->nodesize = 4096;
2982da17066cSJeff Mahoney 	fs_info->sectorsize = 4096;
2983ab108d99SDavid Sterba 	fs_info->sectorsize_bits = ilog2(4096);
2984da17066cSJeff Mahoney 	fs_info->stripesize = 4096;
2985da17066cSJeff Mahoney 
2986eede2bf3SOmar Sandoval 	spin_lock_init(&fs_info->swapfile_pins_lock);
2987eede2bf3SOmar Sandoval 	fs_info->swapfile_pins = RB_ROOT;
2988eede2bf3SOmar Sandoval 
29891cea5cf0SFilipe Manana 	spin_lock_init(&fs_info->send_reloc_lock);
29909e967495SFilipe Manana 	fs_info->send_in_progress = 0;
299118bb8bbfSJohannes Thumshirn 
299218bb8bbfSJohannes Thumshirn 	fs_info->bg_reclaim_threshold = BTRFS_DEFAULT_RECLAIM_THRESH;
299318bb8bbfSJohannes Thumshirn 	INIT_WORK(&fs_info->reclaim_bgs_work, btrfs_reclaim_bgs_work);
29948260edbaSJosef Bacik }
29958260edbaSJosef Bacik 
29968260edbaSJosef Bacik static int init_mount_fs_info(struct btrfs_fs_info *fs_info, struct super_block *sb)
29978260edbaSJosef Bacik {
29988260edbaSJosef Bacik 	int ret;
29998260edbaSJosef Bacik 
30008260edbaSJosef Bacik 	fs_info->sb = sb;
30018260edbaSJosef Bacik 	sb->s_blocksize = BTRFS_BDEV_BLOCKSIZE;
30028260edbaSJosef Bacik 	sb->s_blocksize_bits = blksize_bits(BTRFS_BDEV_BLOCKSIZE);
30039e967495SFilipe Manana 
30045deb17e1SJosef Bacik 	ret = percpu_counter_init(&fs_info->ordered_bytes, 0, GFP_KERNEL);
3005ae18c37aSJosef Bacik 	if (ret)
3006ae18c37aSJosef Bacik 		return ret;
3007ae18c37aSJosef Bacik 
3008ae18c37aSJosef Bacik 	ret = percpu_counter_init(&fs_info->dirty_metadata_bytes, 0, GFP_KERNEL);
3009ae18c37aSJosef Bacik 	if (ret)
3010c75e8394SJosef Bacik 		return ret;
3011ae18c37aSJosef Bacik 
3012ae18c37aSJosef Bacik 	fs_info->dirty_metadata_batch = PAGE_SIZE *
3013ae18c37aSJosef Bacik 					(1 + ilog2(nr_cpu_ids));
3014ae18c37aSJosef Bacik 
3015ae18c37aSJosef Bacik 	ret = percpu_counter_init(&fs_info->delalloc_bytes, 0, GFP_KERNEL);
3016ae18c37aSJosef Bacik 	if (ret)
3017c75e8394SJosef Bacik 		return ret;
3018ae18c37aSJosef Bacik 
3019ae18c37aSJosef Bacik 	ret = percpu_counter_init(&fs_info->dev_replace.bio_counter, 0,
3020ae18c37aSJosef Bacik 			GFP_KERNEL);
3021ae18c37aSJosef Bacik 	if (ret)
3022c75e8394SJosef Bacik 		return ret;
3023ae18c37aSJosef Bacik 
3024ae18c37aSJosef Bacik 	fs_info->delayed_root = kmalloc(sizeof(struct btrfs_delayed_root),
3025ae18c37aSJosef Bacik 					GFP_KERNEL);
3026c75e8394SJosef Bacik 	if (!fs_info->delayed_root)
3027c75e8394SJosef Bacik 		return -ENOMEM;
3028ae18c37aSJosef Bacik 	btrfs_init_delayed_root(fs_info->delayed_root);
3029ae18c37aSJosef Bacik 
3030a0a1db70SFilipe Manana 	if (sb_rdonly(sb))
3031a0a1db70SFilipe Manana 		set_bit(BTRFS_FS_STATE_RO, &fs_info->fs_state);
3032a0a1db70SFilipe Manana 
3033c75e8394SJosef Bacik 	return btrfs_alloc_stripe_hash_table(fs_info);
3034ae18c37aSJosef Bacik }
3035ae18c37aSJosef Bacik 
303697f4dd09SNikolay Borisov static int btrfs_uuid_rescan_kthread(void *data)
303797f4dd09SNikolay Borisov {
303897f4dd09SNikolay Borisov 	struct btrfs_fs_info *fs_info = (struct btrfs_fs_info *)data;
303997f4dd09SNikolay Borisov 	int ret;
304097f4dd09SNikolay Borisov 
304197f4dd09SNikolay Borisov 	/*
304297f4dd09SNikolay Borisov 	 * 1st step is to iterate through the existing UUID tree and
304397f4dd09SNikolay Borisov 	 * to delete all entries that contain outdated data.
304497f4dd09SNikolay Borisov 	 * 2nd step is to add all missing entries to the UUID tree.
304597f4dd09SNikolay Borisov 	 */
304697f4dd09SNikolay Borisov 	ret = btrfs_uuid_tree_iterate(fs_info);
304797f4dd09SNikolay Borisov 	if (ret < 0) {
3048c94bec2cSJosef Bacik 		if (ret != -EINTR)
3049c94bec2cSJosef Bacik 			btrfs_warn(fs_info, "iterating uuid_tree failed %d",
3050c94bec2cSJosef Bacik 				   ret);
305197f4dd09SNikolay Borisov 		up(&fs_info->uuid_tree_rescan_sem);
305297f4dd09SNikolay Borisov 		return ret;
305397f4dd09SNikolay Borisov 	}
305497f4dd09SNikolay Borisov 	return btrfs_uuid_scan_kthread(data);
305597f4dd09SNikolay Borisov }
305697f4dd09SNikolay Borisov 
305797f4dd09SNikolay Borisov static int btrfs_check_uuid_tree(struct btrfs_fs_info *fs_info)
305897f4dd09SNikolay Borisov {
305997f4dd09SNikolay Borisov 	struct task_struct *task;
306097f4dd09SNikolay Borisov 
306197f4dd09SNikolay Borisov 	down(&fs_info->uuid_tree_rescan_sem);
306297f4dd09SNikolay Borisov 	task = kthread_run(btrfs_uuid_rescan_kthread, fs_info, "btrfs-uuid");
306397f4dd09SNikolay Borisov 	if (IS_ERR(task)) {
306497f4dd09SNikolay Borisov 		/* fs_info->update_uuid_tree_gen remains 0 in all error case */
306597f4dd09SNikolay Borisov 		btrfs_warn(fs_info, "failed to start uuid_rescan task");
306697f4dd09SNikolay Borisov 		up(&fs_info->uuid_tree_rescan_sem);
306797f4dd09SNikolay Borisov 		return PTR_ERR(task);
306897f4dd09SNikolay Borisov 	}
306997f4dd09SNikolay Borisov 
307097f4dd09SNikolay Borisov 	return 0;
307197f4dd09SNikolay Borisov }
307297f4dd09SNikolay Borisov 
307344c0ca21SBoris Burkov /*
30748cd29088SBoris Burkov  * Some options only have meaning at mount time and shouldn't persist across
30758cd29088SBoris Burkov  * remounts, or be displayed. Clear these at the end of mount and remount
30768cd29088SBoris Burkov  * code paths.
30778cd29088SBoris Burkov  */
30788cd29088SBoris Burkov void btrfs_clear_oneshot_options(struct btrfs_fs_info *fs_info)
30798cd29088SBoris Burkov {
30808cd29088SBoris Burkov 	btrfs_clear_opt(fs_info->mount_opt, USEBACKUPROOT);
30818b228324SBoris Burkov 	btrfs_clear_opt(fs_info->mount_opt, CLEAR_CACHE);
30828cd29088SBoris Burkov }
30838cd29088SBoris Burkov 
30848cd29088SBoris Burkov /*
308544c0ca21SBoris Burkov  * Mounting logic specific to read-write file systems. Shared by open_ctree
308644c0ca21SBoris Burkov  * and btrfs_remount when remounting from read-only to read-write.
308744c0ca21SBoris Burkov  */
308844c0ca21SBoris Burkov int btrfs_start_pre_rw_mount(struct btrfs_fs_info *fs_info)
308944c0ca21SBoris Burkov {
309044c0ca21SBoris Burkov 	int ret;
309194846229SBoris Burkov 	const bool cache_opt = btrfs_test_opt(fs_info, SPACE_CACHE);
30928b228324SBoris Burkov 	bool clear_free_space_tree = false;
30938b228324SBoris Burkov 
30948b228324SBoris Burkov 	if (btrfs_test_opt(fs_info, CLEAR_CACHE) &&
30958b228324SBoris Burkov 	    btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
30968b228324SBoris Burkov 		clear_free_space_tree = true;
30978b228324SBoris Burkov 	} else if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE) &&
30988b228324SBoris Burkov 		   !btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE_VALID)) {
30998b228324SBoris Burkov 		btrfs_warn(fs_info, "free space tree is invalid");
31008b228324SBoris Burkov 		clear_free_space_tree = true;
31018b228324SBoris Burkov 	}
31028b228324SBoris Burkov 
31038b228324SBoris Burkov 	if (clear_free_space_tree) {
31048b228324SBoris Burkov 		btrfs_info(fs_info, "clearing free space tree");
31058b228324SBoris Burkov 		ret = btrfs_clear_free_space_tree(fs_info);
31068b228324SBoris Burkov 		if (ret) {
31078b228324SBoris Burkov 			btrfs_warn(fs_info,
31088b228324SBoris Burkov 				   "failed to clear free space tree: %d", ret);
31098b228324SBoris Burkov 			goto out;
31108b228324SBoris Burkov 		}
31118b228324SBoris Burkov 	}
311244c0ca21SBoris Burkov 
31138d488a8cSFilipe Manana 	/*
31148d488a8cSFilipe Manana 	 * btrfs_find_orphan_roots() is responsible for finding all the dead
31158d488a8cSFilipe Manana 	 * roots (with 0 refs), flag them with BTRFS_ROOT_DEAD_TREE and load
31168d488a8cSFilipe Manana 	 * them into the fs_info->fs_roots_radix tree. This must be done before
31178d488a8cSFilipe Manana 	 * calling btrfs_orphan_cleanup() on the tree root. If we don't do it
31188d488a8cSFilipe Manana 	 * first, then btrfs_orphan_cleanup() will delete a dead root's orphan
31198d488a8cSFilipe Manana 	 * item before the root's tree is deleted - this means that if we unmount
31208d488a8cSFilipe Manana 	 * or crash before the deletion completes, on the next mount we will not
31218d488a8cSFilipe Manana 	 * delete what remains of the tree because the orphan item does not
31228d488a8cSFilipe Manana 	 * exists anymore, which is what tells us we have a pending deletion.
31238d488a8cSFilipe Manana 	 */
31248d488a8cSFilipe Manana 	ret = btrfs_find_orphan_roots(fs_info);
31258d488a8cSFilipe Manana 	if (ret)
31268d488a8cSFilipe Manana 		goto out;
31278d488a8cSFilipe Manana 
312844c0ca21SBoris Burkov 	ret = btrfs_cleanup_fs_roots(fs_info);
312944c0ca21SBoris Burkov 	if (ret)
313044c0ca21SBoris Burkov 		goto out;
313144c0ca21SBoris Burkov 
31328f1c21d7SBoris Burkov 	down_read(&fs_info->cleanup_work_sem);
31338f1c21d7SBoris Burkov 	if ((ret = btrfs_orphan_cleanup(fs_info->fs_root)) ||
31348f1c21d7SBoris Burkov 	    (ret = btrfs_orphan_cleanup(fs_info->tree_root))) {
31358f1c21d7SBoris Burkov 		up_read(&fs_info->cleanup_work_sem);
31368f1c21d7SBoris Burkov 		goto out;
31378f1c21d7SBoris Burkov 	}
31388f1c21d7SBoris Burkov 	up_read(&fs_info->cleanup_work_sem);
31398f1c21d7SBoris Burkov 
314044c0ca21SBoris Burkov 	mutex_lock(&fs_info->cleaner_mutex);
314144c0ca21SBoris Burkov 	ret = btrfs_recover_relocation(fs_info->tree_root);
314244c0ca21SBoris Burkov 	mutex_unlock(&fs_info->cleaner_mutex);
314344c0ca21SBoris Burkov 	if (ret < 0) {
314444c0ca21SBoris Burkov 		btrfs_warn(fs_info, "failed to recover relocation: %d", ret);
314544c0ca21SBoris Burkov 		goto out;
314644c0ca21SBoris Burkov 	}
314744c0ca21SBoris Burkov 
31485011139aSBoris Burkov 	if (btrfs_test_opt(fs_info, FREE_SPACE_TREE) &&
31495011139aSBoris Burkov 	    !btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
31505011139aSBoris Burkov 		btrfs_info(fs_info, "creating free space tree");
31515011139aSBoris Burkov 		ret = btrfs_create_free_space_tree(fs_info);
31525011139aSBoris Burkov 		if (ret) {
31535011139aSBoris Burkov 			btrfs_warn(fs_info,
31545011139aSBoris Burkov 				"failed to create free space tree: %d", ret);
31555011139aSBoris Burkov 			goto out;
31565011139aSBoris Burkov 		}
31575011139aSBoris Burkov 	}
31585011139aSBoris Burkov 
315994846229SBoris Burkov 	if (cache_opt != btrfs_free_space_cache_v1_active(fs_info)) {
316094846229SBoris Burkov 		ret = btrfs_set_free_space_cache_v1_active(fs_info, cache_opt);
316194846229SBoris Burkov 		if (ret)
316294846229SBoris Burkov 			goto out;
316394846229SBoris Burkov 	}
316494846229SBoris Burkov 
316544c0ca21SBoris Burkov 	ret = btrfs_resume_balance_async(fs_info);
316644c0ca21SBoris Burkov 	if (ret)
316744c0ca21SBoris Burkov 		goto out;
316844c0ca21SBoris Burkov 
316944c0ca21SBoris Burkov 	ret = btrfs_resume_dev_replace_async(fs_info);
317044c0ca21SBoris Burkov 	if (ret) {
317144c0ca21SBoris Burkov 		btrfs_warn(fs_info, "failed to resume dev_replace");
317244c0ca21SBoris Burkov 		goto out;
317344c0ca21SBoris Burkov 	}
317444c0ca21SBoris Burkov 
317544c0ca21SBoris Burkov 	btrfs_qgroup_rescan_resume(fs_info);
317644c0ca21SBoris Burkov 
317744c0ca21SBoris Burkov 	if (!fs_info->uuid_root) {
317844c0ca21SBoris Burkov 		btrfs_info(fs_info, "creating UUID tree");
317944c0ca21SBoris Burkov 		ret = btrfs_create_uuid_tree(fs_info);
318044c0ca21SBoris Burkov 		if (ret) {
318144c0ca21SBoris Burkov 			btrfs_warn(fs_info,
318244c0ca21SBoris Burkov 				   "failed to create the UUID tree %d", ret);
318344c0ca21SBoris Burkov 			goto out;
318444c0ca21SBoris Burkov 		}
318544c0ca21SBoris Burkov 	}
318644c0ca21SBoris Burkov 
318744c0ca21SBoris Burkov out:
318844c0ca21SBoris Burkov 	return ret;
318944c0ca21SBoris Burkov }
319044c0ca21SBoris Burkov 
3191ae18c37aSJosef Bacik int __cold open_ctree(struct super_block *sb, struct btrfs_fs_devices *fs_devices,
3192ae18c37aSJosef Bacik 		      char *options)
3193ae18c37aSJosef Bacik {
3194ae18c37aSJosef Bacik 	u32 sectorsize;
3195ae18c37aSJosef Bacik 	u32 nodesize;
3196ae18c37aSJosef Bacik 	u32 stripesize;
3197ae18c37aSJosef Bacik 	u64 generation;
3198ae18c37aSJosef Bacik 	u64 features;
3199ae18c37aSJosef Bacik 	u16 csum_type;
3200ae18c37aSJosef Bacik 	struct btrfs_super_block *disk_super;
3201ae18c37aSJosef Bacik 	struct btrfs_fs_info *fs_info = btrfs_sb(sb);
3202ae18c37aSJosef Bacik 	struct btrfs_root *tree_root;
3203ae18c37aSJosef Bacik 	struct btrfs_root *chunk_root;
3204ae18c37aSJosef Bacik 	int ret;
3205ae18c37aSJosef Bacik 	int err = -EINVAL;
3206ae18c37aSJosef Bacik 	int level;
3207ae18c37aSJosef Bacik 
32088260edbaSJosef Bacik 	ret = init_mount_fs_info(fs_info, sb);
320953b381b3SDavid Woodhouse 	if (ret) {
321083c8266aSDavid Sterba 		err = ret;
3211ae18c37aSJosef Bacik 		goto fail;
321253b381b3SDavid Woodhouse 	}
321353b381b3SDavid Woodhouse 
3214ae18c37aSJosef Bacik 	/* These need to be init'ed before we start creating inodes and such. */
3215ae18c37aSJosef Bacik 	tree_root = btrfs_alloc_root(fs_info, BTRFS_ROOT_TREE_OBJECTID,
3216ae18c37aSJosef Bacik 				     GFP_KERNEL);
3217ae18c37aSJosef Bacik 	fs_info->tree_root = tree_root;
3218ae18c37aSJosef Bacik 	chunk_root = btrfs_alloc_root(fs_info, BTRFS_CHUNK_TREE_OBJECTID,
3219ae18c37aSJosef Bacik 				      GFP_KERNEL);
3220ae18c37aSJosef Bacik 	fs_info->chunk_root = chunk_root;
3221ae18c37aSJosef Bacik 	if (!tree_root || !chunk_root) {
3222ae18c37aSJosef Bacik 		err = -ENOMEM;
3223c75e8394SJosef Bacik 		goto fail;
3224ae18c37aSJosef Bacik 	}
3225ae18c37aSJosef Bacik 
3226ae18c37aSJosef Bacik 	fs_info->btree_inode = new_inode(sb);
3227ae18c37aSJosef Bacik 	if (!fs_info->btree_inode) {
3228ae18c37aSJosef Bacik 		err = -ENOMEM;
3229c75e8394SJosef Bacik 		goto fail;
3230ae18c37aSJosef Bacik 	}
3231ae18c37aSJosef Bacik 	mapping_set_gfp_mask(fs_info->btree_inode->i_mapping, GFP_NOFS);
3232ae18c37aSJosef Bacik 	btrfs_init_btree_inode(fs_info);
3233ae18c37aSJosef Bacik 
32343c4bb26bSChris Mason 	invalidate_bdev(fs_devices->latest_bdev);
32351104a885SDavid Sterba 
32361104a885SDavid Sterba 	/*
32371104a885SDavid Sterba 	 * Read super block and check the signature bytes only
32381104a885SDavid Sterba 	 */
32398f32380dSJohannes Thumshirn 	disk_super = btrfs_read_dev_super(fs_devices->latest_bdev);
32408f32380dSJohannes Thumshirn 	if (IS_ERR(disk_super)) {
32418f32380dSJohannes Thumshirn 		err = PTR_ERR(disk_super);
324216cdcec7SMiao Xie 		goto fail_alloc;
324320b45077SDave Young 	}
324439279cc3SChris Mason 
32451104a885SDavid Sterba 	/*
3246260db43cSRandy Dunlap 	 * Verify the type first, if that or the checksum value are
32478dc3f22cSJohannes Thumshirn 	 * corrupted, we'll find out
32488dc3f22cSJohannes Thumshirn 	 */
32498f32380dSJohannes Thumshirn 	csum_type = btrfs_super_csum_type(disk_super);
325051bce6c9SJohannes Thumshirn 	if (!btrfs_supported_super_csum(csum_type)) {
32518dc3f22cSJohannes Thumshirn 		btrfs_err(fs_info, "unsupported checksum algorithm: %u",
325251bce6c9SJohannes Thumshirn 			  csum_type);
32538dc3f22cSJohannes Thumshirn 		err = -EINVAL;
32548f32380dSJohannes Thumshirn 		btrfs_release_disk_super(disk_super);
32558dc3f22cSJohannes Thumshirn 		goto fail_alloc;
32568dc3f22cSJohannes Thumshirn 	}
32578dc3f22cSJohannes Thumshirn 
325883c68bbcSSu Yue 	fs_info->csum_size = btrfs_super_csum_size(disk_super);
325983c68bbcSSu Yue 
32606d97c6e3SJohannes Thumshirn 	ret = btrfs_init_csum_hash(fs_info, csum_type);
32616d97c6e3SJohannes Thumshirn 	if (ret) {
32626d97c6e3SJohannes Thumshirn 		err = ret;
32638f32380dSJohannes Thumshirn 		btrfs_release_disk_super(disk_super);
32646d97c6e3SJohannes Thumshirn 		goto fail_alloc;
32656d97c6e3SJohannes Thumshirn 	}
32666d97c6e3SJohannes Thumshirn 
32678dc3f22cSJohannes Thumshirn 	/*
32681104a885SDavid Sterba 	 * We want to check superblock checksum, the type is stored inside.
32691104a885SDavid Sterba 	 * Pass the whole disk block of size BTRFS_SUPER_INFO_SIZE (4k).
32701104a885SDavid Sterba 	 */
32718f32380dSJohannes Thumshirn 	if (btrfs_check_super_csum(fs_info, (u8 *)disk_super)) {
327205135f59SDavid Sterba 		btrfs_err(fs_info, "superblock checksum mismatch");
32731104a885SDavid Sterba 		err = -EINVAL;
32748f32380dSJohannes Thumshirn 		btrfs_release_disk_super(disk_super);
3275141386e1SJosef Bacik 		goto fail_alloc;
32761104a885SDavid Sterba 	}
32771104a885SDavid Sterba 
32781104a885SDavid Sterba 	/*
32791104a885SDavid Sterba 	 * super_copy is zeroed at allocation time and we never touch the
32801104a885SDavid Sterba 	 * following bytes up to INFO_SIZE, the checksum is calculated from
32811104a885SDavid Sterba 	 * the whole block of INFO_SIZE
32821104a885SDavid Sterba 	 */
32838f32380dSJohannes Thumshirn 	memcpy(fs_info->super_copy, disk_super, sizeof(*fs_info->super_copy));
32848f32380dSJohannes Thumshirn 	btrfs_release_disk_super(disk_super);
32855f39d397SChris Mason 
3286fbc6feaeSNikolay Borisov 	disk_super = fs_info->super_copy;
3287fbc6feaeSNikolay Borisov 
32880b86a832SChris Mason 
3289fbc6feaeSNikolay Borisov 	features = btrfs_super_flags(disk_super);
3290fbc6feaeSNikolay Borisov 	if (features & BTRFS_SUPER_FLAG_CHANGING_FSID_V2) {
3291fbc6feaeSNikolay Borisov 		features &= ~BTRFS_SUPER_FLAG_CHANGING_FSID_V2;
3292fbc6feaeSNikolay Borisov 		btrfs_set_super_flags(disk_super, features);
3293fbc6feaeSNikolay Borisov 		btrfs_info(fs_info,
3294fbc6feaeSNikolay Borisov 			"found metadata UUID change in progress flag, clearing");
3295fbc6feaeSNikolay Borisov 	}
3296fbc6feaeSNikolay Borisov 
3297fbc6feaeSNikolay Borisov 	memcpy(fs_info->super_for_commit, fs_info->super_copy,
3298fbc6feaeSNikolay Borisov 	       sizeof(*fs_info->super_for_commit));
3299de37aa51SNikolay Borisov 
3300069ec957SQu Wenruo 	ret = btrfs_validate_mount_super(fs_info);
33011104a885SDavid Sterba 	if (ret) {
330205135f59SDavid Sterba 		btrfs_err(fs_info, "superblock contains fatal errors");
33031104a885SDavid Sterba 		err = -EINVAL;
3304141386e1SJosef Bacik 		goto fail_alloc;
33051104a885SDavid Sterba 	}
33061104a885SDavid Sterba 
33070f7d52f4SChris Mason 	if (!btrfs_super_root(disk_super))
3308141386e1SJosef Bacik 		goto fail_alloc;
33090f7d52f4SChris Mason 
3310acce952bSliubo 	/* check FS state, whether FS is broken. */
331187533c47SMiao Xie 	if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_ERROR)
331287533c47SMiao Xie 		set_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state);
3313acce952bSliubo 
331475e7cb7fSLiu Bo 	/*
331575e7cb7fSLiu Bo 	 * In the long term, we'll store the compression type in the super
331675e7cb7fSLiu Bo 	 * block, and it'll be used for per file compression control.
331775e7cb7fSLiu Bo 	 */
331875e7cb7fSLiu Bo 	fs_info->compress_type = BTRFS_COMPRESS_ZLIB;
331975e7cb7fSLiu Bo 
33206f93e834SAnand Jain 	/*
33216f93e834SAnand Jain 	 * Flag our filesystem as having big metadata blocks if they are bigger
33226f93e834SAnand Jain 	 * than the page size.
33236f93e834SAnand Jain 	 */
33246f93e834SAnand Jain 	if (btrfs_super_nodesize(disk_super) > PAGE_SIZE) {
33256f93e834SAnand Jain 		if (!(features & BTRFS_FEATURE_INCOMPAT_BIG_METADATA))
33266f93e834SAnand Jain 			btrfs_info(fs_info,
33276f93e834SAnand Jain 				"flagging fs with big metadata feature");
33286f93e834SAnand Jain 		features |= BTRFS_FEATURE_INCOMPAT_BIG_METADATA;
33296f93e834SAnand Jain 	}
33306f93e834SAnand Jain 
33316f93e834SAnand Jain 	/* Set up fs_info before parsing mount options */
33326f93e834SAnand Jain 	nodesize = btrfs_super_nodesize(disk_super);
33336f93e834SAnand Jain 	sectorsize = btrfs_super_sectorsize(disk_super);
33346f93e834SAnand Jain 	stripesize = sectorsize;
33356f93e834SAnand Jain 	fs_info->dirty_metadata_batch = nodesize * (1 + ilog2(nr_cpu_ids));
33366f93e834SAnand Jain 	fs_info->delalloc_batch = sectorsize * 512 * (1 + ilog2(nr_cpu_ids));
33376f93e834SAnand Jain 
33386f93e834SAnand Jain 	fs_info->nodesize = nodesize;
33396f93e834SAnand Jain 	fs_info->sectorsize = sectorsize;
33406f93e834SAnand Jain 	fs_info->sectorsize_bits = ilog2(sectorsize);
33416f93e834SAnand Jain 	fs_info->csums_per_leaf = BTRFS_MAX_ITEM_SIZE(fs_info) / fs_info->csum_size;
33426f93e834SAnand Jain 	fs_info->stripesize = stripesize;
33436f93e834SAnand Jain 
33442ff7e61eSJeff Mahoney 	ret = btrfs_parse_options(fs_info, options, sb->s_flags);
33452b82032cSYan Zheng 	if (ret) {
33462b82032cSYan Zheng 		err = ret;
3347141386e1SJosef Bacik 		goto fail_alloc;
33482b82032cSYan Zheng 	}
3349dfe25020SChris Mason 
3350f2b636e8SJosef Bacik 	features = btrfs_super_incompat_flags(disk_super) &
3351f2b636e8SJosef Bacik 		~BTRFS_FEATURE_INCOMPAT_SUPP;
3352f2b636e8SJosef Bacik 	if (features) {
335305135f59SDavid Sterba 		btrfs_err(fs_info,
335405135f59SDavid Sterba 		    "cannot mount because of unsupported optional features (%llx)",
3355c1c9ff7cSGeert Uytterhoeven 		    features);
3356f2b636e8SJosef Bacik 		err = -EINVAL;
3357141386e1SJosef Bacik 		goto fail_alloc;
3358f2b636e8SJosef Bacik 	}
3359f2b636e8SJosef Bacik 
33605d4f98a2SYan Zheng 	features = btrfs_super_incompat_flags(disk_super);
33615d4f98a2SYan Zheng 	features |= BTRFS_FEATURE_INCOMPAT_MIXED_BACKREF;
33620b246afaSJeff Mahoney 	if (fs_info->compress_type == BTRFS_COMPRESS_LZO)
3363a6fa6faeSLi Zefan 		features |= BTRFS_FEATURE_INCOMPAT_COMPRESS_LZO;
33645c1aab1dSNick Terrell 	else if (fs_info->compress_type == BTRFS_COMPRESS_ZSTD)
33655c1aab1dSNick Terrell 		features |= BTRFS_FEATURE_INCOMPAT_COMPRESS_ZSTD;
3366727011e0SChris Mason 
33673173a18fSJosef Bacik 	if (features & BTRFS_FEATURE_INCOMPAT_SKINNY_METADATA)
336805135f59SDavid Sterba 		btrfs_info(fs_info, "has skinny extents");
33693173a18fSJosef Bacik 
3370727011e0SChris Mason 	/*
3371bc3f116fSChris Mason 	 * mixed block groups end up with duplicate but slightly offset
3372bc3f116fSChris Mason 	 * extent buffers for the same range.  It leads to corruptions
3373bc3f116fSChris Mason 	 */
3374bc3f116fSChris Mason 	if ((features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS) &&
3375707e8a07SDavid Sterba 	    (sectorsize != nodesize)) {
337605135f59SDavid Sterba 		btrfs_err(fs_info,
337705135f59SDavid Sterba "unequal nodesize/sectorsize (%u != %u) are not allowed for mixed block groups",
337805135f59SDavid Sterba 			nodesize, sectorsize);
3379141386e1SJosef Bacik 		goto fail_alloc;
3380bc3f116fSChris Mason 	}
3381bc3f116fSChris Mason 
3382ceda0864SMiao Xie 	/*
3383ceda0864SMiao Xie 	 * Needn't use the lock because there is no other task which will
3384ceda0864SMiao Xie 	 * update the flag.
3385ceda0864SMiao Xie 	 */
33865d4f98a2SYan Zheng 	btrfs_set_super_incompat_flags(disk_super, features);
33875d4f98a2SYan Zheng 
3388f2b636e8SJosef Bacik 	features = btrfs_super_compat_ro_flags(disk_super) &
3389f2b636e8SJosef Bacik 		~BTRFS_FEATURE_COMPAT_RO_SUPP;
3390bc98a42cSDavid Howells 	if (!sb_rdonly(sb) && features) {
339105135f59SDavid Sterba 		btrfs_err(fs_info,
339205135f59SDavid Sterba 	"cannot mount read-write because of unsupported optional features (%llx)",
3393c1c9ff7cSGeert Uytterhoeven 		       features);
3394f2b636e8SJosef Bacik 		err = -EINVAL;
3395141386e1SJosef Bacik 		goto fail_alloc;
3396f2b636e8SJosef Bacik 	}
339761d92c32SChris Mason 
33988481dd80SQu Wenruo 	if (sectorsize < PAGE_SIZE) {
33998481dd80SQu Wenruo 		struct btrfs_subpage_info *subpage_info;
34008481dd80SQu Wenruo 
340195ea0486SQu Wenruo 		btrfs_warn(fs_info,
340295ea0486SQu Wenruo 		"read-write for sector size %u with page size %lu is experimental",
34030bb3eb3eSQu Wenruo 			   sectorsize, PAGE_SIZE);
3404c8050b3bSQu Wenruo 		if (btrfs_super_incompat_flags(fs_info->super_copy) &
3405c8050b3bSQu Wenruo 			BTRFS_FEATURE_INCOMPAT_RAID56) {
3406c8050b3bSQu Wenruo 			btrfs_err(fs_info,
3407c8050b3bSQu Wenruo 		"RAID56 is not yet supported for sector size %u with page size %lu",
3408c8050b3bSQu Wenruo 				sectorsize, PAGE_SIZE);
3409c8050b3bSQu Wenruo 			err = -EINVAL;
3410c8050b3bSQu Wenruo 			goto fail_alloc;
3411c8050b3bSQu Wenruo 		}
34128481dd80SQu Wenruo 		subpage_info = kzalloc(sizeof(*subpage_info), GFP_KERNEL);
34138481dd80SQu Wenruo 		if (!subpage_info)
34148481dd80SQu Wenruo 			goto fail_alloc;
34158481dd80SQu Wenruo 		btrfs_init_subpage_info(subpage_info, sectorsize);
34168481dd80SQu Wenruo 		fs_info->subpage_info = subpage_info;
3417c8050b3bSQu Wenruo 	}
34180bb3eb3eSQu Wenruo 
34192a458198SEric Sandeen 	ret = btrfs_init_workqueues(fs_info, fs_devices);
34202a458198SEric Sandeen 	if (ret) {
34212a458198SEric Sandeen 		err = ret;
34220dc3b84aSJosef Bacik 		goto fail_sb_buffer;
34230dc3b84aSJosef Bacik 	}
34244543df7eSChris Mason 
34259e11ceeeSJan Kara 	sb->s_bdi->ra_pages *= btrfs_super_num_devices(disk_super);
34269e11ceeeSJan Kara 	sb->s_bdi->ra_pages = max(sb->s_bdi->ra_pages, SZ_4M / PAGE_SIZE);
34274575c9ccSChris Mason 
3428a061fc8dSChris Mason 	sb->s_blocksize = sectorsize;
3429a061fc8dSChris Mason 	sb->s_blocksize_bits = blksize_bits(sectorsize);
3430de37aa51SNikolay Borisov 	memcpy(&sb->s_uuid, fs_info->fs_devices->fsid, BTRFS_FSID_SIZE);
3431db94535dSChris Mason 
3432925baeddSChris Mason 	mutex_lock(&fs_info->chunk_mutex);
34336bccf3abSJeff Mahoney 	ret = btrfs_read_sys_array(fs_info);
3434925baeddSChris Mason 	mutex_unlock(&fs_info->chunk_mutex);
343584eed90fSChris Mason 	if (ret) {
343605135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read the system array: %d", ret);
34375d4f98a2SYan Zheng 		goto fail_sb_buffer;
343884eed90fSChris Mason 	}
34390b86a832SChris Mason 
344084234f3aSYan Zheng 	generation = btrfs_super_chunk_root_generation(disk_super);
3441581c1760SQu Wenruo 	level = btrfs_super_chunk_root_level(disk_super);
34420b86a832SChris Mason 
34432ff7e61eSJeff Mahoney 	chunk_root->node = read_tree_block(fs_info,
34440b86a832SChris Mason 					   btrfs_super_chunk_root(disk_super),
34451b7ec85eSJosef Bacik 					   BTRFS_CHUNK_TREE_OBJECTID,
3446581c1760SQu Wenruo 					   generation, level, NULL);
344764c043deSLiu Bo 	if (IS_ERR(chunk_root->node) ||
344864c043deSLiu Bo 	    !extent_buffer_uptodate(chunk_root->node)) {
344905135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read chunk root");
3450e5fffbacSchandan 		if (!IS_ERR(chunk_root->node))
3451e5fffbacSchandan 			free_extent_buffer(chunk_root->node);
345295ab1f64SZhao Lei 		chunk_root->node = NULL;
3453af31f5e5SChris Mason 		goto fail_tree_roots;
345483121942SDavid Woodhouse 	}
34555d4f98a2SYan Zheng 	btrfs_set_root_node(&chunk_root->root_item, chunk_root->node);
34565d4f98a2SYan Zheng 	chunk_root->commit_root = btrfs_root_node(chunk_root);
34570b86a832SChris Mason 
3458e17cade2SChris Mason 	read_extent_buffer(chunk_root->node, fs_info->chunk_tree_uuid,
3459c4ac7541SDavid Sterba 			   offsetof(struct btrfs_header, chunk_tree_uuid),
3460c4ac7541SDavid Sterba 			   BTRFS_UUID_SIZE);
3461e17cade2SChris Mason 
34625b4aacefSJeff Mahoney 	ret = btrfs_read_chunk_tree(fs_info);
34632b82032cSYan Zheng 	if (ret) {
346405135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read chunk tree: %d", ret);
3465af31f5e5SChris Mason 		goto fail_tree_roots;
34662b82032cSYan Zheng 	}
34670b86a832SChris Mason 
34688dabb742SStefan Behrens 	/*
3469bacce86aSAnand Jain 	 * At this point we know all the devices that make this filesystem,
3470bacce86aSAnand Jain 	 * including the seed devices but we don't know yet if the replace
3471bacce86aSAnand Jain 	 * target is required. So free devices that are not part of this
34721a9fd417SDavid Sterba 	 * filesystem but skip the replace target device which is checked
3473bacce86aSAnand Jain 	 * below in btrfs_init_dev_replace().
34748dabb742SStefan Behrens 	 */
3475bacce86aSAnand Jain 	btrfs_free_extra_devids(fs_devices);
3476a6b0d5c8SChris Mason 	if (!fs_devices->latest_bdev) {
347705135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read devices");
3478a6b0d5c8SChris Mason 		goto fail_tree_roots;
3479a6b0d5c8SChris Mason 	}
3480a6b0d5c8SChris Mason 
3481b8522a1eSNikolay Borisov 	ret = init_tree_roots(fs_info);
34824bbcaa64SEric Sandeen 	if (ret)
3483b8522a1eSNikolay Borisov 		goto fail_tree_roots;
34848929ecfaSYan, Zheng 
348575ec1db8SJosef Bacik 	/*
348673651042SNaohiro Aota 	 * Get zone type information of zoned block devices. This will also
348773651042SNaohiro Aota 	 * handle emulation of a zoned filesystem if a regular device has the
348873651042SNaohiro Aota 	 * zoned incompat feature flag set.
348973651042SNaohiro Aota 	 */
349073651042SNaohiro Aota 	ret = btrfs_get_dev_zone_info_all_devices(fs_info);
349173651042SNaohiro Aota 	if (ret) {
349273651042SNaohiro Aota 		btrfs_err(fs_info,
349373651042SNaohiro Aota 			  "zoned: failed to read device zone info: %d",
349473651042SNaohiro Aota 			  ret);
349573651042SNaohiro Aota 		goto fail_block_groups;
349673651042SNaohiro Aota 	}
349773651042SNaohiro Aota 
349873651042SNaohiro Aota 	/*
349975ec1db8SJosef Bacik 	 * If we have a uuid root and we're not being told to rescan we need to
350075ec1db8SJosef Bacik 	 * check the generation here so we can set the
350175ec1db8SJosef Bacik 	 * BTRFS_FS_UPDATE_UUID_TREE_GEN bit.  Otherwise we could commit the
350275ec1db8SJosef Bacik 	 * transaction during a balance or the log replay without updating the
350375ec1db8SJosef Bacik 	 * uuid generation, and then if we crash we would rescan the uuid tree,
350475ec1db8SJosef Bacik 	 * even though it was perfectly fine.
350575ec1db8SJosef Bacik 	 */
350675ec1db8SJosef Bacik 	if (fs_info->uuid_root && !btrfs_test_opt(fs_info, RESCAN_UUID_TREE) &&
350775ec1db8SJosef Bacik 	    fs_info->generation == btrfs_super_uuid_tree_generation(disk_super))
350875ec1db8SJosef Bacik 		set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
350975ec1db8SJosef Bacik 
3510cf90d884SQu Wenruo 	ret = btrfs_verify_dev_extents(fs_info);
3511cf90d884SQu Wenruo 	if (ret) {
3512cf90d884SQu Wenruo 		btrfs_err(fs_info,
3513cf90d884SQu Wenruo 			  "failed to verify dev extents against chunks: %d",
3514cf90d884SQu Wenruo 			  ret);
3515cf90d884SQu Wenruo 		goto fail_block_groups;
3516cf90d884SQu Wenruo 	}
351768310a5eSIlya Dryomov 	ret = btrfs_recover_balance(fs_info);
351868310a5eSIlya Dryomov 	if (ret) {
351905135f59SDavid Sterba 		btrfs_err(fs_info, "failed to recover balance: %d", ret);
352068310a5eSIlya Dryomov 		goto fail_block_groups;
352168310a5eSIlya Dryomov 	}
352268310a5eSIlya Dryomov 
3523733f4fbbSStefan Behrens 	ret = btrfs_init_dev_stats(fs_info);
3524733f4fbbSStefan Behrens 	if (ret) {
352505135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init dev_stats: %d", ret);
3526733f4fbbSStefan Behrens 		goto fail_block_groups;
3527733f4fbbSStefan Behrens 	}
3528733f4fbbSStefan Behrens 
35298dabb742SStefan Behrens 	ret = btrfs_init_dev_replace(fs_info);
35308dabb742SStefan Behrens 	if (ret) {
353105135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init dev_replace: %d", ret);
35328dabb742SStefan Behrens 		goto fail_block_groups;
35338dabb742SStefan Behrens 	}
35348dabb742SStefan Behrens 
3535b70f5097SNaohiro Aota 	ret = btrfs_check_zoned_mode(fs_info);
3536b70f5097SNaohiro Aota 	if (ret) {
3537b70f5097SNaohiro Aota 		btrfs_err(fs_info, "failed to initialize zoned mode: %d",
3538b70f5097SNaohiro Aota 			  ret);
3539b70f5097SNaohiro Aota 		goto fail_block_groups;
3540b70f5097SNaohiro Aota 	}
3541b70f5097SNaohiro Aota 
3542c6761a9eSAnand Jain 	ret = btrfs_sysfs_add_fsid(fs_devices);
3543b7c35e81SAnand Jain 	if (ret) {
354405135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init sysfs fsid interface: %d",
354505135f59SDavid Sterba 				ret);
3546b7c35e81SAnand Jain 		goto fail_block_groups;
3547b7c35e81SAnand Jain 	}
3548b7c35e81SAnand Jain 
354996f3136eSAnand Jain 	ret = btrfs_sysfs_add_mounted(fs_info);
35505ac1d209SJeff Mahoney 	if (ret) {
355105135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init sysfs interface: %d", ret);
3552b7c35e81SAnand Jain 		goto fail_fsdev_sysfs;
35535ac1d209SJeff Mahoney 	}
35545ac1d209SJeff Mahoney 
3555c59021f8Sliubo 	ret = btrfs_init_space_info(fs_info);
3556c59021f8Sliubo 	if (ret) {
355705135f59SDavid Sterba 		btrfs_err(fs_info, "failed to initialize space info: %d", ret);
35582365dd3cSAnand Jain 		goto fail_sysfs;
3559c59021f8Sliubo 	}
3560c59021f8Sliubo 
35615b4aacefSJeff Mahoney 	ret = btrfs_read_block_groups(fs_info);
35621b1d1f66SJosef Bacik 	if (ret) {
356305135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read block groups: %d", ret);
35642365dd3cSAnand Jain 		goto fail_sysfs;
35651b1d1f66SJosef Bacik 	}
35664330e183SQu Wenruo 
35676528b99dSAnand Jain 	if (!sb_rdonly(sb) && !btrfs_check_rw_degradable(fs_info, NULL)) {
356805135f59SDavid Sterba 		btrfs_warn(fs_info,
356952042d8eSAndrea Gelmini 		"writable mount is not allowed due to too many missing devices");
35702365dd3cSAnand Jain 		goto fail_sysfs;
3571292fd7fcSStefan Behrens 	}
35729078a3e1SChris Mason 
3573a74a4b97SChris Mason 	fs_info->cleaner_kthread = kthread_run(cleaner_kthread, tree_root,
3574a74a4b97SChris Mason 					       "btrfs-cleaner");
357557506d50SQinghuang Feng 	if (IS_ERR(fs_info->cleaner_kthread))
35762365dd3cSAnand Jain 		goto fail_sysfs;
3577a74a4b97SChris Mason 
3578a74a4b97SChris Mason 	fs_info->transaction_kthread = kthread_run(transaction_kthread,
3579a74a4b97SChris Mason 						   tree_root,
3580a74a4b97SChris Mason 						   "btrfs-transaction");
358157506d50SQinghuang Feng 	if (IS_ERR(fs_info->transaction_kthread))
35823f157a2fSChris Mason 		goto fail_cleaner;
3583a74a4b97SChris Mason 
3584583b7231SHans van Kranenburg 	if (!btrfs_test_opt(fs_info, NOSSD) &&
3585c289811cSChris Mason 	    !fs_info->fs_devices->rotating) {
3586583b7231SHans van Kranenburg 		btrfs_set_and_info(fs_info, SSD, "enabling ssd optimizations");
3587c289811cSChris Mason 	}
3588c289811cSChris Mason 
3589572d9ab7SDavid Sterba 	/*
359001327610SNicholas D Steeves 	 * Mount does not set all options immediately, we can do it now and do
3591572d9ab7SDavid Sterba 	 * not have to wait for transaction commit
3592572d9ab7SDavid Sterba 	 */
3593572d9ab7SDavid Sterba 	btrfs_apply_pending_changes(fs_info);
35943818aea2SQu Wenruo 
359521adbd5cSStefan Behrens #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
35960b246afaSJeff Mahoney 	if (btrfs_test_opt(fs_info, CHECK_INTEGRITY)) {
35972ff7e61eSJeff Mahoney 		ret = btrfsic_mount(fs_info, fs_devices,
35980b246afaSJeff Mahoney 				    btrfs_test_opt(fs_info,
3599cbeaae4fSDavid Sterba 					CHECK_INTEGRITY_DATA) ? 1 : 0,
360021adbd5cSStefan Behrens 				    fs_info->check_integrity_print_mask);
360121adbd5cSStefan Behrens 		if (ret)
360205135f59SDavid Sterba 			btrfs_warn(fs_info,
360305135f59SDavid Sterba 				"failed to initialize integrity check module: %d",
360405135f59SDavid Sterba 				ret);
360521adbd5cSStefan Behrens 	}
360621adbd5cSStefan Behrens #endif
3607bcef60f2SArne Jansen 	ret = btrfs_read_qgroup_config(fs_info);
3608bcef60f2SArne Jansen 	if (ret)
3609bcef60f2SArne Jansen 		goto fail_trans_kthread;
361021adbd5cSStefan Behrens 
3611fd708b81SJosef Bacik 	if (btrfs_build_ref_tree(fs_info))
3612fd708b81SJosef Bacik 		btrfs_err(fs_info, "couldn't build ref tree");
3613fd708b81SJosef Bacik 
361496da0919SQu Wenruo 	/* do not make disk changes in broken FS or nologreplay is given */
361596da0919SQu Wenruo 	if (btrfs_super_log_root(disk_super) != 0 &&
36160b246afaSJeff Mahoney 	    !btrfs_test_opt(fs_info, NOLOGREPLAY)) {
3617e8294f2fSDavid Sterba 		btrfs_info(fs_info, "start tree-log replay");
361863443bf5SEric Sandeen 		ret = btrfs_replay_log(fs_info, fs_devices);
361979787eaaSJeff Mahoney 		if (ret) {
362063443bf5SEric Sandeen 			err = ret;
362128c16cbbSWang Shilong 			goto fail_qgroup;
3622e556ce2cSYan Zheng 		}
3623e02119d5SChris Mason 	}
36241a40e23bSZheng Yan 
362556e9357aSDavid Sterba 	fs_info->fs_root = btrfs_get_fs_root(fs_info, BTRFS_FS_TREE_OBJECTID, true);
36263140c9a3SDan Carpenter 	if (IS_ERR(fs_info->fs_root)) {
36273140c9a3SDan Carpenter 		err = PTR_ERR(fs_info->fs_root);
3628f50f4353SLiu Bo 		btrfs_warn(fs_info, "failed to read fs tree: %d", err);
3629315bf8efSJosef Bacik 		fs_info->fs_root = NULL;
3630bcef60f2SArne Jansen 		goto fail_qgroup;
36313140c9a3SDan Carpenter 	}
3632c289811cSChris Mason 
3633bc98a42cSDavid Howells 	if (sb_rdonly(sb))
36348cd29088SBoris Burkov 		goto clear_oneshot;
36352b6ba629SIlya Dryomov 
363644c0ca21SBoris Burkov 	ret = btrfs_start_pre_rw_mount(fs_info);
36372b6ba629SIlya Dryomov 	if (ret) {
36386bccf3abSJeff Mahoney 		close_ctree(fs_info);
36392b6ba629SIlya Dryomov 		return ret;
3640e3acc2a6SJosef Bacik 	}
3641b0643e59SDennis Zhou 	btrfs_discard_resume(fs_info);
3642b382a324SJan Schmidt 
364344c0ca21SBoris Burkov 	if (fs_info->uuid_root &&
364444c0ca21SBoris Burkov 	    (btrfs_test_opt(fs_info, RESCAN_UUID_TREE) ||
364544c0ca21SBoris Burkov 	     fs_info->generation != btrfs_super_uuid_tree_generation(disk_super))) {
364605135f59SDavid Sterba 		btrfs_info(fs_info, "checking UUID tree");
364770f80175SStefan Behrens 		ret = btrfs_check_uuid_tree(fs_info);
364870f80175SStefan Behrens 		if (ret) {
364905135f59SDavid Sterba 			btrfs_warn(fs_info,
365005135f59SDavid Sterba 				"failed to check the UUID tree: %d", ret);
36516bccf3abSJeff Mahoney 			close_ctree(fs_info);
365270f80175SStefan Behrens 			return ret;
365370f80175SStefan Behrens 		}
3654f7a81ea4SStefan Behrens 	}
365594846229SBoris Burkov 
3656afcdd129SJosef Bacik 	set_bit(BTRFS_FS_OPEN, &fs_info->flags);
365747ab2a6cSJosef Bacik 
36588cd29088SBoris Burkov clear_oneshot:
36598cd29088SBoris Burkov 	btrfs_clear_oneshot_options(fs_info);
3660ad2b2c80SAl Viro 	return 0;
366139279cc3SChris Mason 
3662bcef60f2SArne Jansen fail_qgroup:
3663bcef60f2SArne Jansen 	btrfs_free_qgroup_config(fs_info);
36647c2ca468SChris Mason fail_trans_kthread:
36657c2ca468SChris Mason 	kthread_stop(fs_info->transaction_kthread);
36662ff7e61eSJeff Mahoney 	btrfs_cleanup_transaction(fs_info);
3667faa2dbf0SJosef Bacik 	btrfs_free_fs_roots(fs_info);
36683f157a2fSChris Mason fail_cleaner:
3669a74a4b97SChris Mason 	kthread_stop(fs_info->cleaner_kthread);
36707c2ca468SChris Mason 
36717c2ca468SChris Mason 	/*
36727c2ca468SChris Mason 	 * make sure we're done with the btree inode before we stop our
36737c2ca468SChris Mason 	 * kthreads
36747c2ca468SChris Mason 	 */
36757c2ca468SChris Mason 	filemap_write_and_wait(fs_info->btree_inode->i_mapping);
36767c2ca468SChris Mason 
36772365dd3cSAnand Jain fail_sysfs:
36786618a59bSAnand Jain 	btrfs_sysfs_remove_mounted(fs_info);
36792365dd3cSAnand Jain 
3680b7c35e81SAnand Jain fail_fsdev_sysfs:
3681b7c35e81SAnand Jain 	btrfs_sysfs_remove_fsid(fs_info->fs_devices);
3682b7c35e81SAnand Jain 
36831b1d1f66SJosef Bacik fail_block_groups:
368454067ae9SJosef Bacik 	btrfs_put_block_group_cache(fs_info);
3685af31f5e5SChris Mason 
3686af31f5e5SChris Mason fail_tree_roots:
36879e3aa805SJosef Bacik 	if (fs_info->data_reloc_root)
36889e3aa805SJosef Bacik 		btrfs_drop_and_free_fs_root(fs_info, fs_info->data_reloc_root);
36894273eaffSAnand Jain 	free_root_pointers(fs_info, true);
36902b8195bbSMiao Xie 	invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
3691af31f5e5SChris Mason 
369239279cc3SChris Mason fail_sb_buffer:
36937abadb64SLiu Bo 	btrfs_stop_all_workers(fs_info);
36945cdd7db6SFilipe Manana 	btrfs_free_block_groups(fs_info);
369516cdcec7SMiao Xie fail_alloc:
3696586e46e2SIlya Dryomov 	btrfs_mapping_tree_free(&fs_info->mapping_tree);
3697586e46e2SIlya Dryomov 
36984543df7eSChris Mason 	iput(fs_info->btree_inode);
36997e662854SQinghuang Feng fail:
3700586e46e2SIlya Dryomov 	btrfs_close_devices(fs_info->fs_devices);
3701ad2b2c80SAl Viro 	return err;
3702eb60ceacSChris Mason }
3703663faf9fSMasami Hiramatsu ALLOW_ERROR_INJECTION(open_ctree, ERRNO);
3704eb60ceacSChris Mason 
3705314b6dd0SJohannes Thumshirn static void btrfs_end_super_write(struct bio *bio)
3706f2984462SChris Mason {
3707314b6dd0SJohannes Thumshirn 	struct btrfs_device *device = bio->bi_private;
3708314b6dd0SJohannes Thumshirn 	struct bio_vec *bvec;
3709314b6dd0SJohannes Thumshirn 	struct bvec_iter_all iter_all;
3710314b6dd0SJohannes Thumshirn 	struct page *page;
3711442a4f63SStefan Behrens 
3712314b6dd0SJohannes Thumshirn 	bio_for_each_segment_all(bvec, bio, iter_all) {
3713314b6dd0SJohannes Thumshirn 		page = bvec->bv_page;
3714314b6dd0SJohannes Thumshirn 
3715314b6dd0SJohannes Thumshirn 		if (bio->bi_status) {
3716fb456252SJeff Mahoney 			btrfs_warn_rl_in_rcu(device->fs_info,
3717314b6dd0SJohannes Thumshirn 				"lost page write due to IO error on %s (%d)",
3718314b6dd0SJohannes Thumshirn 				rcu_str_deref(device->name),
3719314b6dd0SJohannes Thumshirn 				blk_status_to_errno(bio->bi_status));
3720314b6dd0SJohannes Thumshirn 			ClearPageUptodate(page);
3721314b6dd0SJohannes Thumshirn 			SetPageError(page);
3722314b6dd0SJohannes Thumshirn 			btrfs_dev_stat_inc_and_print(device,
3723314b6dd0SJohannes Thumshirn 						     BTRFS_DEV_STAT_WRITE_ERRS);
3724314b6dd0SJohannes Thumshirn 		} else {
3725314b6dd0SJohannes Thumshirn 			SetPageUptodate(page);
3726f2984462SChris Mason 		}
3727314b6dd0SJohannes Thumshirn 
3728314b6dd0SJohannes Thumshirn 		put_page(page);
3729314b6dd0SJohannes Thumshirn 		unlock_page(page);
3730314b6dd0SJohannes Thumshirn 	}
3731314b6dd0SJohannes Thumshirn 
3732314b6dd0SJohannes Thumshirn 	bio_put(bio);
3733f2984462SChris Mason }
3734f2984462SChris Mason 
37358f32380dSJohannes Thumshirn struct btrfs_super_block *btrfs_read_dev_one_super(struct block_device *bdev,
37368f32380dSJohannes Thumshirn 						   int copy_num)
373729c36d72SAnand Jain {
373829c36d72SAnand Jain 	struct btrfs_super_block *super;
37398f32380dSJohannes Thumshirn 	struct page *page;
374012659251SNaohiro Aota 	u64 bytenr, bytenr_orig;
37418f32380dSJohannes Thumshirn 	struct address_space *mapping = bdev->bd_inode->i_mapping;
374212659251SNaohiro Aota 	int ret;
374329c36d72SAnand Jain 
374412659251SNaohiro Aota 	bytenr_orig = btrfs_sb_offset(copy_num);
374512659251SNaohiro Aota 	ret = btrfs_sb_log_location_bdev(bdev, copy_num, READ, &bytenr);
374612659251SNaohiro Aota 	if (ret == -ENOENT)
374712659251SNaohiro Aota 		return ERR_PTR(-EINVAL);
374812659251SNaohiro Aota 	else if (ret)
374912659251SNaohiro Aota 		return ERR_PTR(ret);
375012659251SNaohiro Aota 
375129c36d72SAnand Jain 	if (bytenr + BTRFS_SUPER_INFO_SIZE >= i_size_read(bdev->bd_inode))
37528f32380dSJohannes Thumshirn 		return ERR_PTR(-EINVAL);
375329c36d72SAnand Jain 
37548f32380dSJohannes Thumshirn 	page = read_cache_page_gfp(mapping, bytenr >> PAGE_SHIFT, GFP_NOFS);
37558f32380dSJohannes Thumshirn 	if (IS_ERR(page))
37568f32380dSJohannes Thumshirn 		return ERR_CAST(page);
375729c36d72SAnand Jain 
37588f32380dSJohannes Thumshirn 	super = page_address(page);
375996c2e067SAnand Jain 	if (btrfs_super_magic(super) != BTRFS_MAGIC) {
376096c2e067SAnand Jain 		btrfs_release_disk_super(super);
376196c2e067SAnand Jain 		return ERR_PTR(-ENODATA);
376296c2e067SAnand Jain 	}
376396c2e067SAnand Jain 
376412659251SNaohiro Aota 	if (btrfs_super_bytenr(super) != bytenr_orig) {
37658f32380dSJohannes Thumshirn 		btrfs_release_disk_super(super);
37668f32380dSJohannes Thumshirn 		return ERR_PTR(-EINVAL);
376729c36d72SAnand Jain 	}
376829c36d72SAnand Jain 
37698f32380dSJohannes Thumshirn 	return super;
377029c36d72SAnand Jain }
377129c36d72SAnand Jain 
377229c36d72SAnand Jain 
37738f32380dSJohannes Thumshirn struct btrfs_super_block *btrfs_read_dev_super(struct block_device *bdev)
3774a512bbf8SYan Zheng {
37758f32380dSJohannes Thumshirn 	struct btrfs_super_block *super, *latest = NULL;
3776a512bbf8SYan Zheng 	int i;
3777a512bbf8SYan Zheng 	u64 transid = 0;
3778a512bbf8SYan Zheng 
3779a512bbf8SYan Zheng 	/* we would like to check all the supers, but that would make
3780a512bbf8SYan Zheng 	 * a btrfs mount succeed after a mkfs from a different FS.
3781a512bbf8SYan Zheng 	 * So, we need to add a special mount option to scan for
3782a512bbf8SYan Zheng 	 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
3783a512bbf8SYan Zheng 	 */
3784a512bbf8SYan Zheng 	for (i = 0; i < 1; i++) {
37858f32380dSJohannes Thumshirn 		super = btrfs_read_dev_one_super(bdev, i);
37868f32380dSJohannes Thumshirn 		if (IS_ERR(super))
3787a512bbf8SYan Zheng 			continue;
3788a512bbf8SYan Zheng 
3789a512bbf8SYan Zheng 		if (!latest || btrfs_super_generation(super) > transid) {
37908f32380dSJohannes Thumshirn 			if (latest)
37918f32380dSJohannes Thumshirn 				btrfs_release_disk_super(super);
37928f32380dSJohannes Thumshirn 
37938f32380dSJohannes Thumshirn 			latest = super;
3794a512bbf8SYan Zheng 			transid = btrfs_super_generation(super);
3795a512bbf8SYan Zheng 		}
3796a512bbf8SYan Zheng 	}
379792fc03fbSAnand Jain 
37988f32380dSJohannes Thumshirn 	return super;
3799a512bbf8SYan Zheng }
3800a512bbf8SYan Zheng 
38014eedeb75SHisashi Hifumi /*
3802abbb3b8eSDavid Sterba  * Write superblock @sb to the @device. Do not wait for completion, all the
3803314b6dd0SJohannes Thumshirn  * pages we use for writing are locked.
38044eedeb75SHisashi Hifumi  *
3805abbb3b8eSDavid Sterba  * Write @max_mirrors copies of the superblock, where 0 means default that fit
3806abbb3b8eSDavid Sterba  * the expected device size at commit time. Note that max_mirrors must be
3807abbb3b8eSDavid Sterba  * same for write and wait phases.
38084eedeb75SHisashi Hifumi  *
3809314b6dd0SJohannes Thumshirn  * Return number of errors when page is not found or submission fails.
38104eedeb75SHisashi Hifumi  */
3811a512bbf8SYan Zheng static int write_dev_supers(struct btrfs_device *device,
3812abbb3b8eSDavid Sterba 			    struct btrfs_super_block *sb, int max_mirrors)
3813a512bbf8SYan Zheng {
3814d5178578SJohannes Thumshirn 	struct btrfs_fs_info *fs_info = device->fs_info;
3815314b6dd0SJohannes Thumshirn 	struct address_space *mapping = device->bdev->bd_inode->i_mapping;
3816d5178578SJohannes Thumshirn 	SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
3817a512bbf8SYan Zheng 	int i;
3818a512bbf8SYan Zheng 	int errors = 0;
381912659251SNaohiro Aota 	int ret;
382012659251SNaohiro Aota 	u64 bytenr, bytenr_orig;
3821a512bbf8SYan Zheng 
3822a512bbf8SYan Zheng 	if (max_mirrors == 0)
3823a512bbf8SYan Zheng 		max_mirrors = BTRFS_SUPER_MIRROR_MAX;
3824a512bbf8SYan Zheng 
3825d5178578SJohannes Thumshirn 	shash->tfm = fs_info->csum_shash;
3826d5178578SJohannes Thumshirn 
3827a512bbf8SYan Zheng 	for (i = 0; i < max_mirrors; i++) {
3828314b6dd0SJohannes Thumshirn 		struct page *page;
3829314b6dd0SJohannes Thumshirn 		struct bio *bio;
3830314b6dd0SJohannes Thumshirn 		struct btrfs_super_block *disk_super;
3831314b6dd0SJohannes Thumshirn 
383212659251SNaohiro Aota 		bytenr_orig = btrfs_sb_offset(i);
383312659251SNaohiro Aota 		ret = btrfs_sb_log_location(device, i, WRITE, &bytenr);
383412659251SNaohiro Aota 		if (ret == -ENOENT) {
383512659251SNaohiro Aota 			continue;
383612659251SNaohiro Aota 		} else if (ret < 0) {
383712659251SNaohiro Aota 			btrfs_err(device->fs_info,
383812659251SNaohiro Aota 				"couldn't get super block location for mirror %d",
383912659251SNaohiro Aota 				i);
384012659251SNaohiro Aota 			errors++;
384112659251SNaohiro Aota 			continue;
384212659251SNaohiro Aota 		}
3843935e5cc9SMiao Xie 		if (bytenr + BTRFS_SUPER_INFO_SIZE >=
3844935e5cc9SMiao Xie 		    device->commit_total_bytes)
3845a512bbf8SYan Zheng 			break;
3846a512bbf8SYan Zheng 
384712659251SNaohiro Aota 		btrfs_set_super_bytenr(sb, bytenr_orig);
3848a512bbf8SYan Zheng 
3849fd08001fSEric Biggers 		crypto_shash_digest(shash, (const char *)sb + BTRFS_CSUM_SIZE,
3850fd08001fSEric Biggers 				    BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE,
3851fd08001fSEric Biggers 				    sb->csum);
3852a512bbf8SYan Zheng 
3853314b6dd0SJohannes Thumshirn 		page = find_or_create_page(mapping, bytenr >> PAGE_SHIFT,
3854314b6dd0SJohannes Thumshirn 					   GFP_NOFS);
3855314b6dd0SJohannes Thumshirn 		if (!page) {
3856fb456252SJeff Mahoney 			btrfs_err(device->fs_info,
3857314b6dd0SJohannes Thumshirn 			    "couldn't get super block page for bytenr %llu",
3858f14d104dSDavid Sterba 			    bytenr);
3859634554dcSJosef Bacik 			errors++;
3860634554dcSJosef Bacik 			continue;
3861634554dcSJosef Bacik 		}
3862634554dcSJosef Bacik 
3863314b6dd0SJohannes Thumshirn 		/* Bump the refcount for wait_dev_supers() */
3864314b6dd0SJohannes Thumshirn 		get_page(page);
3865a512bbf8SYan Zheng 
3866314b6dd0SJohannes Thumshirn 		disk_super = page_address(page);
3867314b6dd0SJohannes Thumshirn 		memcpy(disk_super, sb, BTRFS_SUPER_INFO_SIZE);
3868a512bbf8SYan Zheng 
3869387125fcSChris Mason 		/*
3870314b6dd0SJohannes Thumshirn 		 * Directly use bios here instead of relying on the page cache
3871314b6dd0SJohannes Thumshirn 		 * to do I/O, so we don't lose the ability to do integrity
3872314b6dd0SJohannes Thumshirn 		 * checking.
3873387125fcSChris Mason 		 */
3874314b6dd0SJohannes Thumshirn 		bio = bio_alloc(GFP_NOFS, 1);
3875314b6dd0SJohannes Thumshirn 		bio_set_dev(bio, device->bdev);
3876314b6dd0SJohannes Thumshirn 		bio->bi_iter.bi_sector = bytenr >> SECTOR_SHIFT;
3877314b6dd0SJohannes Thumshirn 		bio->bi_private = device;
3878314b6dd0SJohannes Thumshirn 		bio->bi_end_io = btrfs_end_super_write;
3879314b6dd0SJohannes Thumshirn 		__bio_add_page(bio, page, BTRFS_SUPER_INFO_SIZE,
3880314b6dd0SJohannes Thumshirn 			       offset_in_page(bytenr));
3881314b6dd0SJohannes Thumshirn 
3882314b6dd0SJohannes Thumshirn 		/*
3883314b6dd0SJohannes Thumshirn 		 * We FUA only the first super block.  The others we allow to
3884314b6dd0SJohannes Thumshirn 		 * go down lazy and there's a short window where the on-disk
3885314b6dd0SJohannes Thumshirn 		 * copies might still contain the older version.
3886314b6dd0SJohannes Thumshirn 		 */
3887314b6dd0SJohannes Thumshirn 		bio->bi_opf = REQ_OP_WRITE | REQ_SYNC | REQ_META | REQ_PRIO;
38881b9e619cSOmar Sandoval 		if (i == 0 && !btrfs_test_opt(device->fs_info, NOBARRIER))
3889314b6dd0SJohannes Thumshirn 			bio->bi_opf |= REQ_FUA;
3890314b6dd0SJohannes Thumshirn 
3891314b6dd0SJohannes Thumshirn 		btrfsic_submit_bio(bio);
38928376d9e1SNaohiro Aota 
38938376d9e1SNaohiro Aota 		if (btrfs_advance_sb_log(device, i))
38948376d9e1SNaohiro Aota 			errors++;
3895a512bbf8SYan Zheng 	}
3896a512bbf8SYan Zheng 	return errors < i ? 0 : -1;
3897a512bbf8SYan Zheng }
3898a512bbf8SYan Zheng 
3899387125fcSChris Mason /*
3900abbb3b8eSDavid Sterba  * Wait for write completion of superblocks done by write_dev_supers,
3901abbb3b8eSDavid Sterba  * @max_mirrors same for write and wait phases.
3902abbb3b8eSDavid Sterba  *
3903314b6dd0SJohannes Thumshirn  * Return number of errors when page is not found or not marked up to
3904abbb3b8eSDavid Sterba  * date.
3905abbb3b8eSDavid Sterba  */
3906abbb3b8eSDavid Sterba static int wait_dev_supers(struct btrfs_device *device, int max_mirrors)
3907abbb3b8eSDavid Sterba {
3908abbb3b8eSDavid Sterba 	int i;
3909abbb3b8eSDavid Sterba 	int errors = 0;
3910b6a535faSHoward McLauchlan 	bool primary_failed = false;
391112659251SNaohiro Aota 	int ret;
3912abbb3b8eSDavid Sterba 	u64 bytenr;
3913abbb3b8eSDavid Sterba 
3914abbb3b8eSDavid Sterba 	if (max_mirrors == 0)
3915abbb3b8eSDavid Sterba 		max_mirrors = BTRFS_SUPER_MIRROR_MAX;
3916abbb3b8eSDavid Sterba 
3917abbb3b8eSDavid Sterba 	for (i = 0; i < max_mirrors; i++) {
3918314b6dd0SJohannes Thumshirn 		struct page *page;
3919314b6dd0SJohannes Thumshirn 
392012659251SNaohiro Aota 		ret = btrfs_sb_log_location(device, i, READ, &bytenr);
392112659251SNaohiro Aota 		if (ret == -ENOENT) {
392212659251SNaohiro Aota 			break;
392312659251SNaohiro Aota 		} else if (ret < 0) {
392412659251SNaohiro Aota 			errors++;
392512659251SNaohiro Aota 			if (i == 0)
392612659251SNaohiro Aota 				primary_failed = true;
392712659251SNaohiro Aota 			continue;
392812659251SNaohiro Aota 		}
3929abbb3b8eSDavid Sterba 		if (bytenr + BTRFS_SUPER_INFO_SIZE >=
3930abbb3b8eSDavid Sterba 		    device->commit_total_bytes)
3931abbb3b8eSDavid Sterba 			break;
3932abbb3b8eSDavid Sterba 
3933314b6dd0SJohannes Thumshirn 		page = find_get_page(device->bdev->bd_inode->i_mapping,
3934314b6dd0SJohannes Thumshirn 				     bytenr >> PAGE_SHIFT);
3935314b6dd0SJohannes Thumshirn 		if (!page) {
3936abbb3b8eSDavid Sterba 			errors++;
3937b6a535faSHoward McLauchlan 			if (i == 0)
3938b6a535faSHoward McLauchlan 				primary_failed = true;
3939abbb3b8eSDavid Sterba 			continue;
3940abbb3b8eSDavid Sterba 		}
3941314b6dd0SJohannes Thumshirn 		/* Page is submitted locked and unlocked once the IO completes */
3942314b6dd0SJohannes Thumshirn 		wait_on_page_locked(page);
3943314b6dd0SJohannes Thumshirn 		if (PageError(page)) {
3944abbb3b8eSDavid Sterba 			errors++;
3945b6a535faSHoward McLauchlan 			if (i == 0)
3946b6a535faSHoward McLauchlan 				primary_failed = true;
3947b6a535faSHoward McLauchlan 		}
3948abbb3b8eSDavid Sterba 
3949314b6dd0SJohannes Thumshirn 		/* Drop our reference */
3950314b6dd0SJohannes Thumshirn 		put_page(page);
3951abbb3b8eSDavid Sterba 
3952314b6dd0SJohannes Thumshirn 		/* Drop the reference from the writing run */
3953314b6dd0SJohannes Thumshirn 		put_page(page);
3954abbb3b8eSDavid Sterba 	}
3955abbb3b8eSDavid Sterba 
3956b6a535faSHoward McLauchlan 	/* log error, force error return */
3957b6a535faSHoward McLauchlan 	if (primary_failed) {
3958b6a535faSHoward McLauchlan 		btrfs_err(device->fs_info, "error writing primary super block to device %llu",
3959b6a535faSHoward McLauchlan 			  device->devid);
3960b6a535faSHoward McLauchlan 		return -1;
3961b6a535faSHoward McLauchlan 	}
3962b6a535faSHoward McLauchlan 
3963abbb3b8eSDavid Sterba 	return errors < i ? 0 : -1;
3964abbb3b8eSDavid Sterba }
3965abbb3b8eSDavid Sterba 
3966abbb3b8eSDavid Sterba /*
3967387125fcSChris Mason  * endio for the write_dev_flush, this will wake anyone waiting
3968387125fcSChris Mason  * for the barrier when it is done
3969387125fcSChris Mason  */
39704246a0b6SChristoph Hellwig static void btrfs_end_empty_barrier(struct bio *bio)
3971387125fcSChris Mason {
3972387125fcSChris Mason 	complete(bio->bi_private);
3973387125fcSChris Mason }
3974387125fcSChris Mason 
3975387125fcSChris Mason /*
39764fc6441aSAnand Jain  * Submit a flush request to the device if it supports it. Error handling is
39774fc6441aSAnand Jain  * done in the waiting counterpart.
3978387125fcSChris Mason  */
39794fc6441aSAnand Jain static void write_dev_flush(struct btrfs_device *device)
3980387125fcSChris Mason {
3981c2a9c7abSAnand Jain 	struct request_queue *q = bdev_get_queue(device->bdev);
3982e0ae9994SDavid Sterba 	struct bio *bio = device->flush_bio;
3983387125fcSChris Mason 
3984c2a9c7abSAnand Jain 	if (!test_bit(QUEUE_FLAG_WC, &q->queue_flags))
39854fc6441aSAnand Jain 		return;
3986387125fcSChris Mason 
3987e0ae9994SDavid Sterba 	bio_reset(bio);
3988387125fcSChris Mason 	bio->bi_end_io = btrfs_end_empty_barrier;
398974d46992SChristoph Hellwig 	bio_set_dev(bio, device->bdev);
39908d910125SJan Kara 	bio->bi_opf = REQ_OP_WRITE | REQ_SYNC | REQ_PREFLUSH;
3991387125fcSChris Mason 	init_completion(&device->flush_wait);
3992387125fcSChris Mason 	bio->bi_private = &device->flush_wait;
3993387125fcSChris Mason 
399443a01111SLu Fengqi 	btrfsic_submit_bio(bio);
39951c3063b6SAnand Jain 	set_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state);
39964fc6441aSAnand Jain }
3997387125fcSChris Mason 
39984fc6441aSAnand Jain /*
39994fc6441aSAnand Jain  * If the flush bio has been submitted by write_dev_flush, wait for it.
40004fc6441aSAnand Jain  */
40018c27cb35SLinus Torvalds static blk_status_t wait_dev_flush(struct btrfs_device *device)
40024fc6441aSAnand Jain {
40034fc6441aSAnand Jain 	struct bio *bio = device->flush_bio;
40044fc6441aSAnand Jain 
40051c3063b6SAnand Jain 	if (!test_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state))
400658efbc9fSOmar Sandoval 		return BLK_STS_OK;
40074fc6441aSAnand Jain 
40081c3063b6SAnand Jain 	clear_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state);
40092980d574SDavid Sterba 	wait_for_completion_io(&device->flush_wait);
40104fc6441aSAnand Jain 
40118c27cb35SLinus Torvalds 	return bio->bi_status;
4012387125fcSChris Mason }
4013387125fcSChris Mason 
4014d10b82feSQu Wenruo static int check_barrier_error(struct btrfs_fs_info *fs_info)
4015401b41e5SAnand Jain {
40166528b99dSAnand Jain 	if (!btrfs_check_rw_degradable(fs_info, NULL))
4017401b41e5SAnand Jain 		return -EIO;
4018387125fcSChris Mason 	return 0;
4019387125fcSChris Mason }
4020387125fcSChris Mason 
4021387125fcSChris Mason /*
4022387125fcSChris Mason  * send an empty flush down to each device in parallel,
4023387125fcSChris Mason  * then wait for them
4024387125fcSChris Mason  */
4025387125fcSChris Mason static int barrier_all_devices(struct btrfs_fs_info *info)
4026387125fcSChris Mason {
4027387125fcSChris Mason 	struct list_head *head;
4028387125fcSChris Mason 	struct btrfs_device *dev;
40295af3e8ccSStefan Behrens 	int errors_wait = 0;
40304e4cbee9SChristoph Hellwig 	blk_status_t ret;
4031387125fcSChris Mason 
40321538e6c5SDavid Sterba 	lockdep_assert_held(&info->fs_devices->device_list_mutex);
4033387125fcSChris Mason 	/* send down all the barriers */
4034387125fcSChris Mason 	head = &info->fs_devices->devices;
40351538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
4036e6e674bdSAnand Jain 		if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
4037f88ba6a2SHidetoshi Seto 			continue;
4038cea7c8bfSAnand Jain 		if (!dev->bdev)
4039387125fcSChris Mason 			continue;
4040e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
4041ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
4042387125fcSChris Mason 			continue;
4043387125fcSChris Mason 
40444fc6441aSAnand Jain 		write_dev_flush(dev);
404558efbc9fSOmar Sandoval 		dev->last_flush_error = BLK_STS_OK;
4046387125fcSChris Mason 	}
4047387125fcSChris Mason 
4048387125fcSChris Mason 	/* wait for all the barriers */
40491538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
4050e6e674bdSAnand Jain 		if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
4051f88ba6a2SHidetoshi Seto 			continue;
4052387125fcSChris Mason 		if (!dev->bdev) {
40535af3e8ccSStefan Behrens 			errors_wait++;
4054387125fcSChris Mason 			continue;
4055387125fcSChris Mason 		}
4056e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
4057ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
4058387125fcSChris Mason 			continue;
4059387125fcSChris Mason 
40604fc6441aSAnand Jain 		ret = wait_dev_flush(dev);
4061401b41e5SAnand Jain 		if (ret) {
4062401b41e5SAnand Jain 			dev->last_flush_error = ret;
406366b4993eSDavid Sterba 			btrfs_dev_stat_inc_and_print(dev,
406466b4993eSDavid Sterba 					BTRFS_DEV_STAT_FLUSH_ERRS);
40655af3e8ccSStefan Behrens 			errors_wait++;
4066387125fcSChris Mason 		}
4067401b41e5SAnand Jain 	}
4068401b41e5SAnand Jain 
4069cea7c8bfSAnand Jain 	if (errors_wait) {
4070401b41e5SAnand Jain 		/*
4071401b41e5SAnand Jain 		 * At some point we need the status of all disks
4072401b41e5SAnand Jain 		 * to arrive at the volume status. So error checking
4073401b41e5SAnand Jain 		 * is being pushed to a separate loop.
4074401b41e5SAnand Jain 		 */
4075d10b82feSQu Wenruo 		return check_barrier_error(info);
4076401b41e5SAnand Jain 	}
4077387125fcSChris Mason 	return 0;
4078387125fcSChris Mason }
4079387125fcSChris Mason 
4080943c6e99SZhao Lei int btrfs_get_num_tolerated_disk_barrier_failures(u64 flags)
4081943c6e99SZhao Lei {
40828789f4feSZhao Lei 	int raid_type;
40838789f4feSZhao Lei 	int min_tolerated = INT_MAX;
4084943c6e99SZhao Lei 
40858789f4feSZhao Lei 	if ((flags & BTRFS_BLOCK_GROUP_PROFILE_MASK) == 0 ||
40868789f4feSZhao Lei 	    (flags & BTRFS_AVAIL_ALLOC_BIT_SINGLE))
40878c3e3582SDavid Sterba 		min_tolerated = min_t(int, min_tolerated,
40888789f4feSZhao Lei 				    btrfs_raid_array[BTRFS_RAID_SINGLE].
40898789f4feSZhao Lei 				    tolerated_failures);
4090943c6e99SZhao Lei 
40918789f4feSZhao Lei 	for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) {
40928789f4feSZhao Lei 		if (raid_type == BTRFS_RAID_SINGLE)
40938789f4feSZhao Lei 			continue;
409441a6e891SAnand Jain 		if (!(flags & btrfs_raid_array[raid_type].bg_flag))
40958789f4feSZhao Lei 			continue;
40968c3e3582SDavid Sterba 		min_tolerated = min_t(int, min_tolerated,
40978789f4feSZhao Lei 				    btrfs_raid_array[raid_type].
40988789f4feSZhao Lei 				    tolerated_failures);
40998789f4feSZhao Lei 	}
4100943c6e99SZhao Lei 
41018789f4feSZhao Lei 	if (min_tolerated == INT_MAX) {
4102ab8d0fc4SJeff Mahoney 		pr_warn("BTRFS: unknown raid flag: %llu", flags);
41038789f4feSZhao Lei 		min_tolerated = 0;
41048789f4feSZhao Lei 	}
41058789f4feSZhao Lei 
41068789f4feSZhao Lei 	return min_tolerated;
4107943c6e99SZhao Lei }
4108943c6e99SZhao Lei 
4109eece6a9cSDavid Sterba int write_all_supers(struct btrfs_fs_info *fs_info, int max_mirrors)
4110f2984462SChris Mason {
4111e5e9a520SChris Mason 	struct list_head *head;
4112f2984462SChris Mason 	struct btrfs_device *dev;
4113a061fc8dSChris Mason 	struct btrfs_super_block *sb;
4114f2984462SChris Mason 	struct btrfs_dev_item *dev_item;
4115f2984462SChris Mason 	int ret;
4116f2984462SChris Mason 	int do_barriers;
4117a236aed1SChris Mason 	int max_errors;
4118a236aed1SChris Mason 	int total_errors = 0;
4119a061fc8dSChris Mason 	u64 flags;
4120f2984462SChris Mason 
41210b246afaSJeff Mahoney 	do_barriers = !btrfs_test_opt(fs_info, NOBARRIER);
4122fed3b381SLiu Bo 
4123fed3b381SLiu Bo 	/*
4124fed3b381SLiu Bo 	 * max_mirrors == 0 indicates we're from commit_transaction,
4125fed3b381SLiu Bo 	 * not from fsync where the tree roots in fs_info have not
4126fed3b381SLiu Bo 	 * been consistent on disk.
4127fed3b381SLiu Bo 	 */
4128fed3b381SLiu Bo 	if (max_mirrors == 0)
41290b246afaSJeff Mahoney 		backup_super_roots(fs_info);
4130f2984462SChris Mason 
41310b246afaSJeff Mahoney 	sb = fs_info->super_for_commit;
4132a061fc8dSChris Mason 	dev_item = &sb->dev_item;
4133e5e9a520SChris Mason 
41340b246afaSJeff Mahoney 	mutex_lock(&fs_info->fs_devices->device_list_mutex);
41350b246afaSJeff Mahoney 	head = &fs_info->fs_devices->devices;
41360b246afaSJeff Mahoney 	max_errors = btrfs_super_num_devices(fs_info->super_copy) - 1;
4137387125fcSChris Mason 
41385af3e8ccSStefan Behrens 	if (do_barriers) {
41390b246afaSJeff Mahoney 		ret = barrier_all_devices(fs_info);
41405af3e8ccSStefan Behrens 		if (ret) {
41415af3e8ccSStefan Behrens 			mutex_unlock(
41420b246afaSJeff Mahoney 				&fs_info->fs_devices->device_list_mutex);
41430b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret,
41445af3e8ccSStefan Behrens 					      "errors while submitting device barriers.");
41455af3e8ccSStefan Behrens 			return ret;
41465af3e8ccSStefan Behrens 		}
41475af3e8ccSStefan Behrens 	}
4148387125fcSChris Mason 
41491538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
4150dfe25020SChris Mason 		if (!dev->bdev) {
4151dfe25020SChris Mason 			total_errors++;
4152dfe25020SChris Mason 			continue;
4153dfe25020SChris Mason 		}
4154e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
4155ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
4156dfe25020SChris Mason 			continue;
4157dfe25020SChris Mason 
41582b82032cSYan Zheng 		btrfs_set_stack_device_generation(dev_item, 0);
4159a061fc8dSChris Mason 		btrfs_set_stack_device_type(dev_item, dev->type);
4160a061fc8dSChris Mason 		btrfs_set_stack_device_id(dev_item, dev->devid);
41617df69d3eSMiao Xie 		btrfs_set_stack_device_total_bytes(dev_item,
4162935e5cc9SMiao Xie 						   dev->commit_total_bytes);
4163ce7213c7SMiao Xie 		btrfs_set_stack_device_bytes_used(dev_item,
4164ce7213c7SMiao Xie 						  dev->commit_bytes_used);
4165a061fc8dSChris Mason 		btrfs_set_stack_device_io_align(dev_item, dev->io_align);
4166a061fc8dSChris Mason 		btrfs_set_stack_device_io_width(dev_item, dev->io_width);
4167a061fc8dSChris Mason 		btrfs_set_stack_device_sector_size(dev_item, dev->sector_size);
4168a061fc8dSChris Mason 		memcpy(dev_item->uuid, dev->uuid, BTRFS_UUID_SIZE);
41697239ff4bSNikolay Borisov 		memcpy(dev_item->fsid, dev->fs_devices->metadata_uuid,
41707239ff4bSNikolay Borisov 		       BTRFS_FSID_SIZE);
4171a512bbf8SYan Zheng 
4172a061fc8dSChris Mason 		flags = btrfs_super_flags(sb);
4173a061fc8dSChris Mason 		btrfs_set_super_flags(sb, flags | BTRFS_HEADER_FLAG_WRITTEN);
4174f2984462SChris Mason 
417575cb857dSQu Wenruo 		ret = btrfs_validate_write_super(fs_info, sb);
417675cb857dSQu Wenruo 		if (ret < 0) {
417775cb857dSQu Wenruo 			mutex_unlock(&fs_info->fs_devices->device_list_mutex);
417875cb857dSQu Wenruo 			btrfs_handle_fs_error(fs_info, -EUCLEAN,
417975cb857dSQu Wenruo 				"unexpected superblock corruption detected");
418075cb857dSQu Wenruo 			return -EUCLEAN;
418175cb857dSQu Wenruo 		}
418275cb857dSQu Wenruo 
4183abbb3b8eSDavid Sterba 		ret = write_dev_supers(dev, sb, max_mirrors);
4184a236aed1SChris Mason 		if (ret)
4185a236aed1SChris Mason 			total_errors++;
4186f2984462SChris Mason 	}
4187a236aed1SChris Mason 	if (total_errors > max_errors) {
41880b246afaSJeff Mahoney 		btrfs_err(fs_info, "%d errors while writing supers",
4189d397712bSChris Mason 			  total_errors);
41900b246afaSJeff Mahoney 		mutex_unlock(&fs_info->fs_devices->device_list_mutex);
419179787eaaSJeff Mahoney 
41929d565ba4SStefan Behrens 		/* FUA is masked off if unsupported and can't be the reason */
41930b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, -EIO,
41940b246afaSJeff Mahoney 				      "%d errors while writing supers",
41950b246afaSJeff Mahoney 				      total_errors);
41969d565ba4SStefan Behrens 		return -EIO;
4197a236aed1SChris Mason 	}
4198f2984462SChris Mason 
4199a512bbf8SYan Zheng 	total_errors = 0;
42001538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
4201dfe25020SChris Mason 		if (!dev->bdev)
4202dfe25020SChris Mason 			continue;
4203e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
4204ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
4205dfe25020SChris Mason 			continue;
4206dfe25020SChris Mason 
4207abbb3b8eSDavid Sterba 		ret = wait_dev_supers(dev, max_mirrors);
4208a512bbf8SYan Zheng 		if (ret)
42091259ab75SChris Mason 			total_errors++;
4210f2984462SChris Mason 	}
42110b246afaSJeff Mahoney 	mutex_unlock(&fs_info->fs_devices->device_list_mutex);
4212a236aed1SChris Mason 	if (total_errors > max_errors) {
42130b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, -EIO,
42140b246afaSJeff Mahoney 				      "%d errors while writing supers",
42150b246afaSJeff Mahoney 				      total_errors);
421679787eaaSJeff Mahoney 		return -EIO;
4217a236aed1SChris Mason 	}
4218f2984462SChris Mason 	return 0;
4219f2984462SChris Mason }
4220f2984462SChris Mason 
4221cb517eabSMiao Xie /* Drop a fs root from the radix tree and free it. */
4222cb517eabSMiao Xie void btrfs_drop_and_free_fs_root(struct btrfs_fs_info *fs_info,
4223cb517eabSMiao Xie 				  struct btrfs_root *root)
42242619ba1fSChris Mason {
42254785e24fSJosef Bacik 	bool drop_ref = false;
42264785e24fSJosef Bacik 
42274df27c4dSYan, Zheng 	spin_lock(&fs_info->fs_roots_radix_lock);
42282619ba1fSChris Mason 	radix_tree_delete(&fs_info->fs_roots_radix,
42292619ba1fSChris Mason 			  (unsigned long)root->root_key.objectid);
4230af01d2e5SJosef Bacik 	if (test_and_clear_bit(BTRFS_ROOT_IN_RADIX, &root->state))
42314785e24fSJosef Bacik 		drop_ref = true;
42324df27c4dSYan, Zheng 	spin_unlock(&fs_info->fs_roots_radix_lock);
423376dda93cSYan, Zheng 
42341c1ea4f7SLiu Bo 	if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {
4235ef67963dSJosef Bacik 		ASSERT(root->log_root == NULL);
42361c1ea4f7SLiu Bo 		if (root->reloc_root) {
423700246528SJosef Bacik 			btrfs_put_root(root->reloc_root);
42381c1ea4f7SLiu Bo 			root->reloc_root = NULL;
42391c1ea4f7SLiu Bo 		}
42401c1ea4f7SLiu Bo 	}
42413321719eSLiu Bo 
42424785e24fSJosef Bacik 	if (drop_ref)
424300246528SJosef Bacik 		btrfs_put_root(root);
42442619ba1fSChris Mason }
42452619ba1fSChris Mason 
4246c146afadSYan Zheng int btrfs_cleanup_fs_roots(struct btrfs_fs_info *fs_info)
4247c146afadSYan Zheng {
4248c146afadSYan Zheng 	u64 root_objectid = 0;
4249c146afadSYan Zheng 	struct btrfs_root *gang[8];
425065d33fd7SQu Wenruo 	int i = 0;
425165d33fd7SQu Wenruo 	int err = 0;
425265d33fd7SQu Wenruo 	unsigned int ret = 0;
4253c146afadSYan Zheng 
4254c146afadSYan Zheng 	while (1) {
4255efc34534SJosef Bacik 		spin_lock(&fs_info->fs_roots_radix_lock);
4256c146afadSYan Zheng 		ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
4257c146afadSYan Zheng 					     (void **)gang, root_objectid,
4258c146afadSYan Zheng 					     ARRAY_SIZE(gang));
425965d33fd7SQu Wenruo 		if (!ret) {
4260efc34534SJosef Bacik 			spin_unlock(&fs_info->fs_roots_radix_lock);
4261c146afadSYan Zheng 			break;
426265d33fd7SQu Wenruo 		}
42635d4f98a2SYan Zheng 		root_objectid = gang[ret - 1]->root_key.objectid + 1;
426466b4ffd1SJosef Bacik 
426565d33fd7SQu Wenruo 		for (i = 0; i < ret; i++) {
426665d33fd7SQu Wenruo 			/* Avoid to grab roots in dead_roots */
426765d33fd7SQu Wenruo 			if (btrfs_root_refs(&gang[i]->root_item) == 0) {
426865d33fd7SQu Wenruo 				gang[i] = NULL;
426965d33fd7SQu Wenruo 				continue;
427065d33fd7SQu Wenruo 			}
427165d33fd7SQu Wenruo 			/* grab all the search result for later use */
427200246528SJosef Bacik 			gang[i] = btrfs_grab_root(gang[i]);
427365d33fd7SQu Wenruo 		}
4274efc34534SJosef Bacik 		spin_unlock(&fs_info->fs_roots_radix_lock);
427565d33fd7SQu Wenruo 
427665d33fd7SQu Wenruo 		for (i = 0; i < ret; i++) {
427765d33fd7SQu Wenruo 			if (!gang[i])
427865d33fd7SQu Wenruo 				continue;
4279c146afadSYan Zheng 			root_objectid = gang[i]->root_key.objectid;
428066b4ffd1SJosef Bacik 			err = btrfs_orphan_cleanup(gang[i]);
428166b4ffd1SJosef Bacik 			if (err)
428265d33fd7SQu Wenruo 				break;
428300246528SJosef Bacik 			btrfs_put_root(gang[i]);
4284c146afadSYan Zheng 		}
4285c146afadSYan Zheng 		root_objectid++;
4286c146afadSYan Zheng 	}
428765d33fd7SQu Wenruo 
428865d33fd7SQu Wenruo 	/* release the uncleaned roots due to error */
428965d33fd7SQu Wenruo 	for (; i < ret; i++) {
429065d33fd7SQu Wenruo 		if (gang[i])
429100246528SJosef Bacik 			btrfs_put_root(gang[i]);
429265d33fd7SQu Wenruo 	}
429365d33fd7SQu Wenruo 	return err;
4294c146afadSYan Zheng }
4295c146afadSYan Zheng 
42966bccf3abSJeff Mahoney int btrfs_commit_super(struct btrfs_fs_info *fs_info)
4297c146afadSYan Zheng {
42986bccf3abSJeff Mahoney 	struct btrfs_root *root = fs_info->tree_root;
4299c146afadSYan Zheng 	struct btrfs_trans_handle *trans;
4300c146afadSYan Zheng 
43010b246afaSJeff Mahoney 	mutex_lock(&fs_info->cleaner_mutex);
43022ff7e61eSJeff Mahoney 	btrfs_run_delayed_iputs(fs_info);
43030b246afaSJeff Mahoney 	mutex_unlock(&fs_info->cleaner_mutex);
43040b246afaSJeff Mahoney 	wake_up_process(fs_info->cleaner_kthread);
4305c71bf099SYan, Zheng 
4306c71bf099SYan, Zheng 	/* wait until ongoing cleanup work done */
43070b246afaSJeff Mahoney 	down_write(&fs_info->cleanup_work_sem);
43080b246afaSJeff Mahoney 	up_write(&fs_info->cleanup_work_sem);
4309c71bf099SYan, Zheng 
43107a7eaa40SJosef Bacik 	trans = btrfs_join_transaction(root);
43113612b495STsutomu Itoh 	if (IS_ERR(trans))
43123612b495STsutomu Itoh 		return PTR_ERR(trans);
43133a45bb20SJeff Mahoney 	return btrfs_commit_transaction(trans);
4314c146afadSYan Zheng }
4315c146afadSYan Zheng 
4316b105e927SDavid Sterba void __cold close_ctree(struct btrfs_fs_info *fs_info)
4317eb60ceacSChris Mason {
4318c146afadSYan Zheng 	int ret;
4319e089f05cSChris Mason 
4320afcdd129SJosef Bacik 	set_bit(BTRFS_FS_CLOSING_START, &fs_info->flags);
4321d6fd0ae2SOmar Sandoval 	/*
4322d6fd0ae2SOmar Sandoval 	 * We don't want the cleaner to start new transactions, add more delayed
4323d6fd0ae2SOmar Sandoval 	 * iputs, etc. while we're closing. We can't use kthread_stop() yet
4324d6fd0ae2SOmar Sandoval 	 * because that frees the task_struct, and the transaction kthread might
4325d6fd0ae2SOmar Sandoval 	 * still try to wake up the cleaner.
4326d6fd0ae2SOmar Sandoval 	 */
4327d6fd0ae2SOmar Sandoval 	kthread_park(fs_info->cleaner_kthread);
4328a2135011SChris Mason 
43297343dd61SJustin Maggard 	/* wait for the qgroup rescan worker to stop */
4330d06f23d6SJeff Mahoney 	btrfs_qgroup_wait_for_completion(fs_info, false);
43317343dd61SJustin Maggard 
4332803b2f54SStefan Behrens 	/* wait for the uuid_scan task to finish */
4333803b2f54SStefan Behrens 	down(&fs_info->uuid_tree_rescan_sem);
4334803b2f54SStefan Behrens 	/* avoid complains from lockdep et al., set sem back to initial state */
4335803b2f54SStefan Behrens 	up(&fs_info->uuid_tree_rescan_sem);
4336803b2f54SStefan Behrens 
4337837d5b6eSIlya Dryomov 	/* pause restriper - we want to resume on mount */
4338aa1b8cd4SStefan Behrens 	btrfs_pause_balance(fs_info);
4339837d5b6eSIlya Dryomov 
43408dabb742SStefan Behrens 	btrfs_dev_replace_suspend_for_unmount(fs_info);
43418dabb742SStefan Behrens 
4342aa1b8cd4SStefan Behrens 	btrfs_scrub_cancel(fs_info);
43434cb5300bSChris Mason 
43444cb5300bSChris Mason 	/* wait for any defraggers to finish */
43454cb5300bSChris Mason 	wait_event(fs_info->transaction_wait,
43464cb5300bSChris Mason 		   (atomic_read(&fs_info->defrag_running) == 0));
43474cb5300bSChris Mason 
43484cb5300bSChris Mason 	/* clear out the rbtree of defraggable inodes */
434926176e7cSMiao Xie 	btrfs_cleanup_defrag_inodes(fs_info);
43504cb5300bSChris Mason 
435121c7e756SMiao Xie 	cancel_work_sync(&fs_info->async_reclaim_work);
435257056740SJosef Bacik 	cancel_work_sync(&fs_info->async_data_reclaim_work);
4353576fa348SJosef Bacik 	cancel_work_sync(&fs_info->preempt_reclaim_work);
435421c7e756SMiao Xie 
435518bb8bbfSJohannes Thumshirn 	cancel_work_sync(&fs_info->reclaim_bgs_work);
435618bb8bbfSJohannes Thumshirn 
4357b0643e59SDennis Zhou 	/* Cancel or finish ongoing discard work */
4358b0643e59SDennis Zhou 	btrfs_discard_cleanup(fs_info);
4359b0643e59SDennis Zhou 
4360bc98a42cSDavid Howells 	if (!sb_rdonly(fs_info->sb)) {
4361e44163e1SJeff Mahoney 		/*
4362d6fd0ae2SOmar Sandoval 		 * The cleaner kthread is stopped, so do one final pass over
4363d6fd0ae2SOmar Sandoval 		 * unused block groups.
4364e44163e1SJeff Mahoney 		 */
43650b246afaSJeff Mahoney 		btrfs_delete_unused_bgs(fs_info);
4366e44163e1SJeff Mahoney 
4367f0cc2cd7SFilipe Manana 		/*
4368f0cc2cd7SFilipe Manana 		 * There might be existing delayed inode workers still running
4369f0cc2cd7SFilipe Manana 		 * and holding an empty delayed inode item. We must wait for
4370f0cc2cd7SFilipe Manana 		 * them to complete first because they can create a transaction.
4371f0cc2cd7SFilipe Manana 		 * This happens when someone calls btrfs_balance_delayed_items()
4372f0cc2cd7SFilipe Manana 		 * and then a transaction commit runs the same delayed nodes
4373f0cc2cd7SFilipe Manana 		 * before any delayed worker has done something with the nodes.
4374f0cc2cd7SFilipe Manana 		 * We must wait for any worker here and not at transaction
4375f0cc2cd7SFilipe Manana 		 * commit time since that could cause a deadlock.
4376f0cc2cd7SFilipe Manana 		 * This is a very rare case.
4377f0cc2cd7SFilipe Manana 		 */
4378f0cc2cd7SFilipe Manana 		btrfs_flush_workqueue(fs_info->delayed_workers);
4379f0cc2cd7SFilipe Manana 
43806bccf3abSJeff Mahoney 		ret = btrfs_commit_super(fs_info);
4381d397712bSChris Mason 		if (ret)
438204892340SEric Sandeen 			btrfs_err(fs_info, "commit super ret %d", ret);
4383c146afadSYan Zheng 	}
4384ed2ff2cbSChris Mason 
4385af722733SLiu Bo 	if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state) ||
4386af722733SLiu Bo 	    test_bit(BTRFS_FS_STATE_TRANS_ABORTED, &fs_info->fs_state))
43872ff7e61eSJeff Mahoney 		btrfs_error_commit_super(fs_info);
4388acce952bSliubo 
4389e3029d9fSAl Viro 	kthread_stop(fs_info->transaction_kthread);
4390e3029d9fSAl Viro 	kthread_stop(fs_info->cleaner_kthread);
43918929ecfaSYan, Zheng 
4392e187831eSJosef Bacik 	ASSERT(list_empty(&fs_info->delayed_iputs));
4393afcdd129SJosef Bacik 	set_bit(BTRFS_FS_CLOSING_DONE, &fs_info->flags);
4394f25784b3SYan Zheng 
43955958253cSQu Wenruo 	if (btrfs_check_quota_leak(fs_info)) {
43965958253cSQu Wenruo 		WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
43975958253cSQu Wenruo 		btrfs_err(fs_info, "qgroup reserved space leaked");
43985958253cSQu Wenruo 	}
43995958253cSQu Wenruo 
440004892340SEric Sandeen 	btrfs_free_qgroup_config(fs_info);
4401fe816d0fSNikolay Borisov 	ASSERT(list_empty(&fs_info->delalloc_roots));
4402bcef60f2SArne Jansen 
4403963d678bSMiao Xie 	if (percpu_counter_sum(&fs_info->delalloc_bytes)) {
440404892340SEric Sandeen 		btrfs_info(fs_info, "at unmount delalloc count %lld",
4405963d678bSMiao Xie 		       percpu_counter_sum(&fs_info->delalloc_bytes));
4406b0c68f8bSChris Mason 	}
440731153d81SYan Zheng 
44085deb17e1SJosef Bacik 	if (percpu_counter_sum(&fs_info->ordered_bytes))
44094297ff84SJosef Bacik 		btrfs_info(fs_info, "at unmount dio bytes count %lld",
44105deb17e1SJosef Bacik 			   percpu_counter_sum(&fs_info->ordered_bytes));
44114297ff84SJosef Bacik 
44126618a59bSAnand Jain 	btrfs_sysfs_remove_mounted(fs_info);
4413b7c35e81SAnand Jain 	btrfs_sysfs_remove_fsid(fs_info->fs_devices);
44145ac1d209SJeff Mahoney 
44151a4319ccSLiu Bo 	btrfs_put_block_group_cache(fs_info);
44161a4319ccSLiu Bo 
4417de348ee0SWang Shilong 	/*
4418de348ee0SWang Shilong 	 * we must make sure there is not any read request to
4419de348ee0SWang Shilong 	 * submit after we stopping all workers.
4420de348ee0SWang Shilong 	 */
4421de348ee0SWang Shilong 	invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
442296192499SJosef Bacik 	btrfs_stop_all_workers(fs_info);
442396192499SJosef Bacik 
44240a31daa4SFilipe Manana 	/* We shouldn't have any transaction open at this point */
44250a31daa4SFilipe Manana 	ASSERT(list_empty(&fs_info->trans_list));
44260a31daa4SFilipe Manana 
4427afcdd129SJosef Bacik 	clear_bit(BTRFS_FS_OPEN, &fs_info->flags);
44284273eaffSAnand Jain 	free_root_pointers(fs_info, true);
44298c38938cSJosef Bacik 	btrfs_free_fs_roots(fs_info);
44309ad6b7bcSChris Mason 
44314e19443dSJosef Bacik 	/*
44324e19443dSJosef Bacik 	 * We must free the block groups after dropping the fs_roots as we could
44334e19443dSJosef Bacik 	 * have had an IO error and have left over tree log blocks that aren't
44344e19443dSJosef Bacik 	 * cleaned up until the fs roots are freed.  This makes the block group
44354e19443dSJosef Bacik 	 * accounting appear to be wrong because there's pending reserved bytes,
44364e19443dSJosef Bacik 	 * so make sure we do the block group cleanup afterwards.
44374e19443dSJosef Bacik 	 */
44384e19443dSJosef Bacik 	btrfs_free_block_groups(fs_info);
44394e19443dSJosef Bacik 
444013e6c37bSJosef Bacik 	iput(fs_info->btree_inode);
4441d6bfde87SChris Mason 
444221adbd5cSStefan Behrens #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
44430b246afaSJeff Mahoney 	if (btrfs_test_opt(fs_info, CHECK_INTEGRITY))
44442ff7e61eSJeff Mahoney 		btrfsic_unmount(fs_info->fs_devices);
444521adbd5cSStefan Behrens #endif
444621adbd5cSStefan Behrens 
44470b86a832SChris Mason 	btrfs_mapping_tree_free(&fs_info->mapping_tree);
444868c94e55SNikolay Borisov 	btrfs_close_devices(fs_info->fs_devices);
4449eb60ceacSChris Mason }
4450eb60ceacSChris Mason 
4451b9fab919SChris Mason int btrfs_buffer_uptodate(struct extent_buffer *buf, u64 parent_transid,
4452b9fab919SChris Mason 			  int atomic)
4453ccd467d6SChris Mason {
44541259ab75SChris Mason 	int ret;
4455727011e0SChris Mason 	struct inode *btree_inode = buf->pages[0]->mapping->host;
44561259ab75SChris Mason 
44570b32f4bbSJosef Bacik 	ret = extent_buffer_uptodate(buf);
44581259ab75SChris Mason 	if (!ret)
44591259ab75SChris Mason 		return ret;
44601259ab75SChris Mason 
44611259ab75SChris Mason 	ret = verify_parent_transid(&BTRFS_I(btree_inode)->io_tree, buf,
4462b9fab919SChris Mason 				    parent_transid, atomic);
4463b9fab919SChris Mason 	if (ret == -EAGAIN)
4464b9fab919SChris Mason 		return ret;
44651259ab75SChris Mason 	return !ret;
44665f39d397SChris Mason }
44676702ed49SChris Mason 
44685f39d397SChris Mason void btrfs_mark_buffer_dirty(struct extent_buffer *buf)
44695f39d397SChris Mason {
44702f4d60dfSQu Wenruo 	struct btrfs_fs_info *fs_info = buf->fs_info;
44715f39d397SChris Mason 	u64 transid = btrfs_header_generation(buf);
4472b9473439SChris Mason 	int was_dirty;
4473b4ce94deSChris Mason 
447406ea65a3SJosef Bacik #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
447506ea65a3SJosef Bacik 	/*
447606ea65a3SJosef Bacik 	 * This is a fast path so only do this check if we have sanity tests
447752042d8eSAndrea Gelmini 	 * enabled.  Normal people shouldn't be using unmapped buffers as dirty
447806ea65a3SJosef Bacik 	 * outside of the sanity tests.
447906ea65a3SJosef Bacik 	 */
4480b0132a3bSNikolay Borisov 	if (unlikely(test_bit(EXTENT_BUFFER_UNMAPPED, &buf->bflags)))
448106ea65a3SJosef Bacik 		return;
448206ea65a3SJosef Bacik #endif
4483b9447ef8SChris Mason 	btrfs_assert_tree_locked(buf);
44840b246afaSJeff Mahoney 	if (transid != fs_info->generation)
44855d163e0eSJeff Mahoney 		WARN(1, KERN_CRIT "btrfs transid mismatch buffer %llu, found %llu running %llu\n",
44860b246afaSJeff Mahoney 			buf->start, transid, fs_info->generation);
44870b32f4bbSJosef Bacik 	was_dirty = set_extent_buffer_dirty(buf);
4488e2d84521SMiao Xie 	if (!was_dirty)
4489104b4e51SNikolay Borisov 		percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
4490e2d84521SMiao Xie 					 buf->len,
44910b246afaSJeff Mahoney 					 fs_info->dirty_metadata_batch);
44921f21ef0aSFilipe Manana #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
449369fc6cbbSQu Wenruo 	/*
449469fc6cbbSQu Wenruo 	 * Since btrfs_mark_buffer_dirty() can be called with item pointer set
449569fc6cbbSQu Wenruo 	 * but item data not updated.
449669fc6cbbSQu Wenruo 	 * So here we should only check item pointers, not item data.
449769fc6cbbSQu Wenruo 	 */
449869fc6cbbSQu Wenruo 	if (btrfs_header_level(buf) == 0 &&
4499cfdaad5eSDavid Sterba 	    btrfs_check_leaf_relaxed(buf)) {
4500a4f78750SDavid Sterba 		btrfs_print_leaf(buf);
45011f21ef0aSFilipe Manana 		ASSERT(0);
45021f21ef0aSFilipe Manana 	}
45031f21ef0aSFilipe Manana #endif
4504eb60ceacSChris Mason }
4505eb60ceacSChris Mason 
45062ff7e61eSJeff Mahoney static void __btrfs_btree_balance_dirty(struct btrfs_fs_info *fs_info,
4507b53d3f5dSLiu Bo 					int flush_delayed)
450835b7e476SChris Mason {
4509188de649SChris Mason 	/*
4510188de649SChris Mason 	 * looks as though older kernels can get into trouble with
4511188de649SChris Mason 	 * this code, they end up stuck in balance_dirty_pages forever
4512188de649SChris Mason 	 */
4513e2d84521SMiao Xie 	int ret;
4514d6bfde87SChris Mason 
45156933c02eSJens Axboe 	if (current->flags & PF_MEMALLOC)
4516d6bfde87SChris Mason 		return;
4517d6bfde87SChris Mason 
4518b53d3f5dSLiu Bo 	if (flush_delayed)
45192ff7e61eSJeff Mahoney 		btrfs_balance_delayed_items(fs_info);
452016cdcec7SMiao Xie 
4521d814a491SEthan Lien 	ret = __percpu_counter_compare(&fs_info->dirty_metadata_bytes,
4522d814a491SEthan Lien 				     BTRFS_DIRTY_METADATA_THRESH,
4523d814a491SEthan Lien 				     fs_info->dirty_metadata_batch);
4524e2d84521SMiao Xie 	if (ret > 0) {
45250b246afaSJeff Mahoney 		balance_dirty_pages_ratelimited(fs_info->btree_inode->i_mapping);
452616cdcec7SMiao Xie 	}
452716cdcec7SMiao Xie }
452816cdcec7SMiao Xie 
45292ff7e61eSJeff Mahoney void btrfs_btree_balance_dirty(struct btrfs_fs_info *fs_info)
453016cdcec7SMiao Xie {
45312ff7e61eSJeff Mahoney 	__btrfs_btree_balance_dirty(fs_info, 1);
453235b7e476SChris Mason }
4533b53d3f5dSLiu Bo 
45342ff7e61eSJeff Mahoney void btrfs_btree_balance_dirty_nodelay(struct btrfs_fs_info *fs_info)
4535b53d3f5dSLiu Bo {
45362ff7e61eSJeff Mahoney 	__btrfs_btree_balance_dirty(fs_info, 0);
4537d6bfde87SChris Mason }
45386b80053dSChris Mason 
4539581c1760SQu Wenruo int btrfs_read_buffer(struct extent_buffer *buf, u64 parent_transid, int level,
4540581c1760SQu Wenruo 		      struct btrfs_key *first_key)
45416b80053dSChris Mason {
45425ab12d1fSDavid Sterba 	return btree_read_extent_buffer_pages(buf, parent_transid,
4543581c1760SQu Wenruo 					      level, first_key);
45446b80053dSChris Mason }
45450da5468fSChris Mason 
45462ff7e61eSJeff Mahoney static void btrfs_error_commit_super(struct btrfs_fs_info *fs_info)
4547acce952bSliubo {
4548fe816d0fSNikolay Borisov 	/* cleanup FS via transaction */
4549fe816d0fSNikolay Borisov 	btrfs_cleanup_transaction(fs_info);
4550fe816d0fSNikolay Borisov 
45510b246afaSJeff Mahoney 	mutex_lock(&fs_info->cleaner_mutex);
45522ff7e61eSJeff Mahoney 	btrfs_run_delayed_iputs(fs_info);
45530b246afaSJeff Mahoney 	mutex_unlock(&fs_info->cleaner_mutex);
4554acce952bSliubo 
45550b246afaSJeff Mahoney 	down_write(&fs_info->cleanup_work_sem);
45560b246afaSJeff Mahoney 	up_write(&fs_info->cleanup_work_sem);
4557acce952bSliubo }
4558acce952bSliubo 
4559ef67963dSJosef Bacik static void btrfs_drop_all_logs(struct btrfs_fs_info *fs_info)
4560ef67963dSJosef Bacik {
4561ef67963dSJosef Bacik 	struct btrfs_root *gang[8];
4562ef67963dSJosef Bacik 	u64 root_objectid = 0;
4563ef67963dSJosef Bacik 	int ret;
4564ef67963dSJosef Bacik 
4565ef67963dSJosef Bacik 	spin_lock(&fs_info->fs_roots_radix_lock);
4566ef67963dSJosef Bacik 	while ((ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
4567ef67963dSJosef Bacik 					     (void **)gang, root_objectid,
4568ef67963dSJosef Bacik 					     ARRAY_SIZE(gang))) != 0) {
4569ef67963dSJosef Bacik 		int i;
4570ef67963dSJosef Bacik 
4571ef67963dSJosef Bacik 		for (i = 0; i < ret; i++)
4572ef67963dSJosef Bacik 			gang[i] = btrfs_grab_root(gang[i]);
4573ef67963dSJosef Bacik 		spin_unlock(&fs_info->fs_roots_radix_lock);
4574ef67963dSJosef Bacik 
4575ef67963dSJosef Bacik 		for (i = 0; i < ret; i++) {
4576ef67963dSJosef Bacik 			if (!gang[i])
4577ef67963dSJosef Bacik 				continue;
4578ef67963dSJosef Bacik 			root_objectid = gang[i]->root_key.objectid;
4579ef67963dSJosef Bacik 			btrfs_free_log(NULL, gang[i]);
4580ef67963dSJosef Bacik 			btrfs_put_root(gang[i]);
4581ef67963dSJosef Bacik 		}
4582ef67963dSJosef Bacik 		root_objectid++;
4583ef67963dSJosef Bacik 		spin_lock(&fs_info->fs_roots_radix_lock);
4584ef67963dSJosef Bacik 	}
4585ef67963dSJosef Bacik 	spin_unlock(&fs_info->fs_roots_radix_lock);
4586ef67963dSJosef Bacik 	btrfs_free_log_root_tree(NULL, fs_info);
4587ef67963dSJosef Bacik }
4588ef67963dSJosef Bacik 
4589143bede5SJeff Mahoney static void btrfs_destroy_ordered_extents(struct btrfs_root *root)
4590acce952bSliubo {
4591acce952bSliubo 	struct btrfs_ordered_extent *ordered;
4592acce952bSliubo 
4593199c2a9cSMiao Xie 	spin_lock(&root->ordered_extent_lock);
4594779880efSJosef Bacik 	/*
4595779880efSJosef Bacik 	 * This will just short circuit the ordered completion stuff which will
4596779880efSJosef Bacik 	 * make sure the ordered extent gets properly cleaned up.
4597779880efSJosef Bacik 	 */
4598199c2a9cSMiao Xie 	list_for_each_entry(ordered, &root->ordered_extents,
4599779880efSJosef Bacik 			    root_extent_list)
4600779880efSJosef Bacik 		set_bit(BTRFS_ORDERED_IOERR, &ordered->flags);
4601199c2a9cSMiao Xie 	spin_unlock(&root->ordered_extent_lock);
4602199c2a9cSMiao Xie }
4603199c2a9cSMiao Xie 
4604199c2a9cSMiao Xie static void btrfs_destroy_all_ordered_extents(struct btrfs_fs_info *fs_info)
4605199c2a9cSMiao Xie {
4606199c2a9cSMiao Xie 	struct btrfs_root *root;
4607199c2a9cSMiao Xie 	struct list_head splice;
4608199c2a9cSMiao Xie 
4609199c2a9cSMiao Xie 	INIT_LIST_HEAD(&splice);
4610199c2a9cSMiao Xie 
4611199c2a9cSMiao Xie 	spin_lock(&fs_info->ordered_root_lock);
4612199c2a9cSMiao Xie 	list_splice_init(&fs_info->ordered_roots, &splice);
4613199c2a9cSMiao Xie 	while (!list_empty(&splice)) {
4614199c2a9cSMiao Xie 		root = list_first_entry(&splice, struct btrfs_root,
4615199c2a9cSMiao Xie 					ordered_root);
46161de2cfdeSJosef Bacik 		list_move_tail(&root->ordered_root,
46171de2cfdeSJosef Bacik 			       &fs_info->ordered_roots);
4618199c2a9cSMiao Xie 
46192a85d9caSLiu Bo 		spin_unlock(&fs_info->ordered_root_lock);
4620199c2a9cSMiao Xie 		btrfs_destroy_ordered_extents(root);
4621199c2a9cSMiao Xie 
46222a85d9caSLiu Bo 		cond_resched();
46232a85d9caSLiu Bo 		spin_lock(&fs_info->ordered_root_lock);
4624199c2a9cSMiao Xie 	}
4625199c2a9cSMiao Xie 	spin_unlock(&fs_info->ordered_root_lock);
462674d5d229SJosef Bacik 
462774d5d229SJosef Bacik 	/*
462874d5d229SJosef Bacik 	 * We need this here because if we've been flipped read-only we won't
462974d5d229SJosef Bacik 	 * get sync() from the umount, so we need to make sure any ordered
463074d5d229SJosef Bacik 	 * extents that haven't had their dirty pages IO start writeout yet
463174d5d229SJosef Bacik 	 * actually get run and error out properly.
463274d5d229SJosef Bacik 	 */
463374d5d229SJosef Bacik 	btrfs_wait_ordered_roots(fs_info, U64_MAX, 0, (u64)-1);
4634acce952bSliubo }
4635acce952bSliubo 
463635a3621bSStefan Behrens static int btrfs_destroy_delayed_refs(struct btrfs_transaction *trans,
46372ff7e61eSJeff Mahoney 				      struct btrfs_fs_info *fs_info)
4638acce952bSliubo {
4639acce952bSliubo 	struct rb_node *node;
4640acce952bSliubo 	struct btrfs_delayed_ref_root *delayed_refs;
4641acce952bSliubo 	struct btrfs_delayed_ref_node *ref;
4642acce952bSliubo 	int ret = 0;
4643acce952bSliubo 
4644acce952bSliubo 	delayed_refs = &trans->delayed_refs;
4645acce952bSliubo 
4646acce952bSliubo 	spin_lock(&delayed_refs->lock);
4647d7df2c79SJosef Bacik 	if (atomic_read(&delayed_refs->num_entries) == 0) {
4648cfece4dbSDavid Sterba 		spin_unlock(&delayed_refs->lock);
4649b79ce3ddSDavid Sterba 		btrfs_debug(fs_info, "delayed_refs has NO entry");
4650acce952bSliubo 		return ret;
4651acce952bSliubo 	}
4652acce952bSliubo 
46535c9d028bSLiu Bo 	while ((node = rb_first_cached(&delayed_refs->href_root)) != NULL) {
4654d7df2c79SJosef Bacik 		struct btrfs_delayed_ref_head *head;
46550e0adbcfSJosef Bacik 		struct rb_node *n;
4656e78417d1SJosef Bacik 		bool pin_bytes = false;
4657acce952bSliubo 
4658d7df2c79SJosef Bacik 		head = rb_entry(node, struct btrfs_delayed_ref_head,
4659d7df2c79SJosef Bacik 				href_node);
46603069bd26SJosef Bacik 		if (btrfs_delayed_ref_lock(delayed_refs, head))
4661b939d1abSJosef Bacik 			continue;
46623069bd26SJosef Bacik 
4663d7df2c79SJosef Bacik 		spin_lock(&head->lock);
4664e3d03965SLiu Bo 		while ((n = rb_first_cached(&head->ref_tree)) != NULL) {
46650e0adbcfSJosef Bacik 			ref = rb_entry(n, struct btrfs_delayed_ref_node,
46660e0adbcfSJosef Bacik 				       ref_node);
4667d7df2c79SJosef Bacik 			ref->in_tree = 0;
4668e3d03965SLiu Bo 			rb_erase_cached(&ref->ref_node, &head->ref_tree);
46690e0adbcfSJosef Bacik 			RB_CLEAR_NODE(&ref->ref_node);
46701d57ee94SWang Xiaoguang 			if (!list_empty(&ref->add_list))
46711d57ee94SWang Xiaoguang 				list_del(&ref->add_list);
4672d7df2c79SJosef Bacik 			atomic_dec(&delayed_refs->num_entries);
4673d7df2c79SJosef Bacik 			btrfs_put_delayed_ref(ref);
4674d7df2c79SJosef Bacik 		}
467554067ae9SJosef Bacik 		if (head->must_insert_reserved)
4676e78417d1SJosef Bacik 			pin_bytes = true;
467778a6184aSMiao Xie 		btrfs_free_delayed_extent_op(head->extent_op);
4678fa781ceaSJosef Bacik 		btrfs_delete_ref_head(delayed_refs, head);
4679d7df2c79SJosef Bacik 		spin_unlock(&head->lock);
4680acce952bSliubo 		spin_unlock(&delayed_refs->lock);
4681e78417d1SJosef Bacik 		mutex_unlock(&head->mutex);
4682acce952bSliubo 
4683f603bb94SNikolay Borisov 		if (pin_bytes) {
4684f603bb94SNikolay Borisov 			struct btrfs_block_group *cache;
4685f603bb94SNikolay Borisov 
4686f603bb94SNikolay Borisov 			cache = btrfs_lookup_block_group(fs_info, head->bytenr);
4687f603bb94SNikolay Borisov 			BUG_ON(!cache);
4688f603bb94SNikolay Borisov 
4689f603bb94SNikolay Borisov 			spin_lock(&cache->space_info->lock);
4690f603bb94SNikolay Borisov 			spin_lock(&cache->lock);
4691f603bb94SNikolay Borisov 			cache->pinned += head->num_bytes;
4692f603bb94SNikolay Borisov 			btrfs_space_info_update_bytes_pinned(fs_info,
4693f603bb94SNikolay Borisov 				cache->space_info, head->num_bytes);
4694f603bb94SNikolay Borisov 			cache->reserved -= head->num_bytes;
4695f603bb94SNikolay Borisov 			cache->space_info->bytes_reserved -= head->num_bytes;
4696f603bb94SNikolay Borisov 			spin_unlock(&cache->lock);
4697f603bb94SNikolay Borisov 			spin_unlock(&cache->space_info->lock);
4698f603bb94SNikolay Borisov 
4699f603bb94SNikolay Borisov 			btrfs_put_block_group(cache);
4700f603bb94SNikolay Borisov 
4701f603bb94SNikolay Borisov 			btrfs_error_unpin_extent_range(fs_info, head->bytenr,
4702f603bb94SNikolay Borisov 				head->bytenr + head->num_bytes - 1);
4703f603bb94SNikolay Borisov 		}
470431890da0SJosef Bacik 		btrfs_cleanup_ref_head_accounting(fs_info, delayed_refs, head);
4705d278850eSJosef Bacik 		btrfs_put_delayed_ref_head(head);
4706acce952bSliubo 		cond_resched();
4707acce952bSliubo 		spin_lock(&delayed_refs->lock);
4708acce952bSliubo 	}
470981f7eb00SJeff Mahoney 	btrfs_qgroup_destroy_extent_records(trans);
4710acce952bSliubo 
4711acce952bSliubo 	spin_unlock(&delayed_refs->lock);
4712acce952bSliubo 
4713acce952bSliubo 	return ret;
4714acce952bSliubo }
4715acce952bSliubo 
4716143bede5SJeff Mahoney static void btrfs_destroy_delalloc_inodes(struct btrfs_root *root)
4717acce952bSliubo {
4718acce952bSliubo 	struct btrfs_inode *btrfs_inode;
4719acce952bSliubo 	struct list_head splice;
4720acce952bSliubo 
4721acce952bSliubo 	INIT_LIST_HEAD(&splice);
4722acce952bSliubo 
4723eb73c1b7SMiao Xie 	spin_lock(&root->delalloc_lock);
4724eb73c1b7SMiao Xie 	list_splice_init(&root->delalloc_inodes, &splice);
4725acce952bSliubo 
4726acce952bSliubo 	while (!list_empty(&splice)) {
4727fe816d0fSNikolay Borisov 		struct inode *inode = NULL;
4728eb73c1b7SMiao Xie 		btrfs_inode = list_first_entry(&splice, struct btrfs_inode,
4729acce952bSliubo 					       delalloc_inodes);
4730fe816d0fSNikolay Borisov 		__btrfs_del_delalloc_inode(root, btrfs_inode);
4731eb73c1b7SMiao Xie 		spin_unlock(&root->delalloc_lock);
4732acce952bSliubo 
4733fe816d0fSNikolay Borisov 		/*
4734fe816d0fSNikolay Borisov 		 * Make sure we get a live inode and that it'll not disappear
4735fe816d0fSNikolay Borisov 		 * meanwhile.
4736fe816d0fSNikolay Borisov 		 */
4737fe816d0fSNikolay Borisov 		inode = igrab(&btrfs_inode->vfs_inode);
4738fe816d0fSNikolay Borisov 		if (inode) {
4739fe816d0fSNikolay Borisov 			invalidate_inode_pages2(inode->i_mapping);
4740fe816d0fSNikolay Borisov 			iput(inode);
4741fe816d0fSNikolay Borisov 		}
4742eb73c1b7SMiao Xie 		spin_lock(&root->delalloc_lock);
4743acce952bSliubo 	}
4744eb73c1b7SMiao Xie 	spin_unlock(&root->delalloc_lock);
4745eb73c1b7SMiao Xie }
4746eb73c1b7SMiao Xie 
4747eb73c1b7SMiao Xie static void btrfs_destroy_all_delalloc_inodes(struct btrfs_fs_info *fs_info)
4748eb73c1b7SMiao Xie {
4749eb73c1b7SMiao Xie 	struct btrfs_root *root;
4750eb73c1b7SMiao Xie 	struct list_head splice;
4751eb73c1b7SMiao Xie 
4752eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&splice);
4753eb73c1b7SMiao Xie 
4754eb73c1b7SMiao Xie 	spin_lock(&fs_info->delalloc_root_lock);
4755eb73c1b7SMiao Xie 	list_splice_init(&fs_info->delalloc_roots, &splice);
4756eb73c1b7SMiao Xie 	while (!list_empty(&splice)) {
4757eb73c1b7SMiao Xie 		root = list_first_entry(&splice, struct btrfs_root,
4758eb73c1b7SMiao Xie 					 delalloc_root);
475900246528SJosef Bacik 		root = btrfs_grab_root(root);
4760eb73c1b7SMiao Xie 		BUG_ON(!root);
4761eb73c1b7SMiao Xie 		spin_unlock(&fs_info->delalloc_root_lock);
4762eb73c1b7SMiao Xie 
4763eb73c1b7SMiao Xie 		btrfs_destroy_delalloc_inodes(root);
476400246528SJosef Bacik 		btrfs_put_root(root);
4765eb73c1b7SMiao Xie 
4766eb73c1b7SMiao Xie 		spin_lock(&fs_info->delalloc_root_lock);
4767eb73c1b7SMiao Xie 	}
4768eb73c1b7SMiao Xie 	spin_unlock(&fs_info->delalloc_root_lock);
4769acce952bSliubo }
4770acce952bSliubo 
47712ff7e61eSJeff Mahoney static int btrfs_destroy_marked_extents(struct btrfs_fs_info *fs_info,
4772acce952bSliubo 					struct extent_io_tree *dirty_pages,
4773acce952bSliubo 					int mark)
4774acce952bSliubo {
4775acce952bSliubo 	int ret;
4776acce952bSliubo 	struct extent_buffer *eb;
4777acce952bSliubo 	u64 start = 0;
4778acce952bSliubo 	u64 end;
4779acce952bSliubo 
4780acce952bSliubo 	while (1) {
4781acce952bSliubo 		ret = find_first_extent_bit(dirty_pages, start, &start, &end,
4782e6138876SJosef Bacik 					    mark, NULL);
4783acce952bSliubo 		if (ret)
4784acce952bSliubo 			break;
4785acce952bSliubo 
478691166212SDavid Sterba 		clear_extent_bits(dirty_pages, start, end, mark);
4787acce952bSliubo 		while (start <= end) {
47880b246afaSJeff Mahoney 			eb = find_extent_buffer(fs_info, start);
47890b246afaSJeff Mahoney 			start += fs_info->nodesize;
4790fd8b2b61SJosef Bacik 			if (!eb)
4791acce952bSliubo 				continue;
4792fd8b2b61SJosef Bacik 			wait_on_extent_buffer_writeback(eb);
4793acce952bSliubo 
4794fd8b2b61SJosef Bacik 			if (test_and_clear_bit(EXTENT_BUFFER_DIRTY,
4795fd8b2b61SJosef Bacik 					       &eb->bflags))
4796fd8b2b61SJosef Bacik 				clear_extent_buffer_dirty(eb);
4797fd8b2b61SJosef Bacik 			free_extent_buffer_stale(eb);
4798acce952bSliubo 		}
4799acce952bSliubo 	}
4800acce952bSliubo 
4801acce952bSliubo 	return ret;
4802acce952bSliubo }
4803acce952bSliubo 
48042ff7e61eSJeff Mahoney static int btrfs_destroy_pinned_extent(struct btrfs_fs_info *fs_info,
4805fe119a6eSNikolay Borisov 				       struct extent_io_tree *unpin)
4806acce952bSliubo {
4807acce952bSliubo 	u64 start;
4808acce952bSliubo 	u64 end;
4809acce952bSliubo 	int ret;
4810acce952bSliubo 
4811acce952bSliubo 	while (1) {
48120e6ec385SFilipe Manana 		struct extent_state *cached_state = NULL;
48130e6ec385SFilipe Manana 
4814fcd5e742SLu Fengqi 		/*
4815fcd5e742SLu Fengqi 		 * The btrfs_finish_extent_commit() may get the same range as
4816fcd5e742SLu Fengqi 		 * ours between find_first_extent_bit and clear_extent_dirty.
4817fcd5e742SLu Fengqi 		 * Hence, hold the unused_bg_unpin_mutex to avoid double unpin
4818fcd5e742SLu Fengqi 		 * the same extent range.
4819fcd5e742SLu Fengqi 		 */
4820fcd5e742SLu Fengqi 		mutex_lock(&fs_info->unused_bg_unpin_mutex);
4821acce952bSliubo 		ret = find_first_extent_bit(unpin, 0, &start, &end,
48220e6ec385SFilipe Manana 					    EXTENT_DIRTY, &cached_state);
4823fcd5e742SLu Fengqi 		if (ret) {
4824fcd5e742SLu Fengqi 			mutex_unlock(&fs_info->unused_bg_unpin_mutex);
4825acce952bSliubo 			break;
4826fcd5e742SLu Fengqi 		}
4827acce952bSliubo 
48280e6ec385SFilipe Manana 		clear_extent_dirty(unpin, start, end, &cached_state);
48290e6ec385SFilipe Manana 		free_extent_state(cached_state);
48302ff7e61eSJeff Mahoney 		btrfs_error_unpin_extent_range(fs_info, start, end);
4831fcd5e742SLu Fengqi 		mutex_unlock(&fs_info->unused_bg_unpin_mutex);
4832acce952bSliubo 		cond_resched();
4833acce952bSliubo 	}
4834acce952bSliubo 
4835acce952bSliubo 	return 0;
4836acce952bSliubo }
4837acce952bSliubo 
483832da5386SDavid Sterba static void btrfs_cleanup_bg_io(struct btrfs_block_group *cache)
4839c79a1751SLiu Bo {
4840c79a1751SLiu Bo 	struct inode *inode;
4841c79a1751SLiu Bo 
4842c79a1751SLiu Bo 	inode = cache->io_ctl.inode;
4843c79a1751SLiu Bo 	if (inode) {
4844c79a1751SLiu Bo 		invalidate_inode_pages2(inode->i_mapping);
4845c79a1751SLiu Bo 		BTRFS_I(inode)->generation = 0;
4846c79a1751SLiu Bo 		cache->io_ctl.inode = NULL;
4847c79a1751SLiu Bo 		iput(inode);
4848c79a1751SLiu Bo 	}
4849bbc37d6eSFilipe Manana 	ASSERT(cache->io_ctl.pages == NULL);
4850c79a1751SLiu Bo 	btrfs_put_block_group(cache);
4851c79a1751SLiu Bo }
4852c79a1751SLiu Bo 
4853c79a1751SLiu Bo void btrfs_cleanup_dirty_bgs(struct btrfs_transaction *cur_trans,
48542ff7e61eSJeff Mahoney 			     struct btrfs_fs_info *fs_info)
4855c79a1751SLiu Bo {
485632da5386SDavid Sterba 	struct btrfs_block_group *cache;
4857c79a1751SLiu Bo 
4858c79a1751SLiu Bo 	spin_lock(&cur_trans->dirty_bgs_lock);
4859c79a1751SLiu Bo 	while (!list_empty(&cur_trans->dirty_bgs)) {
4860c79a1751SLiu Bo 		cache = list_first_entry(&cur_trans->dirty_bgs,
486132da5386SDavid Sterba 					 struct btrfs_block_group,
4862c79a1751SLiu Bo 					 dirty_list);
4863c79a1751SLiu Bo 
4864c79a1751SLiu Bo 		if (!list_empty(&cache->io_list)) {
4865c79a1751SLiu Bo 			spin_unlock(&cur_trans->dirty_bgs_lock);
4866c79a1751SLiu Bo 			list_del_init(&cache->io_list);
4867c79a1751SLiu Bo 			btrfs_cleanup_bg_io(cache);
4868c79a1751SLiu Bo 			spin_lock(&cur_trans->dirty_bgs_lock);
4869c79a1751SLiu Bo 		}
4870c79a1751SLiu Bo 
4871c79a1751SLiu Bo 		list_del_init(&cache->dirty_list);
4872c79a1751SLiu Bo 		spin_lock(&cache->lock);
4873c79a1751SLiu Bo 		cache->disk_cache_state = BTRFS_DC_ERROR;
4874c79a1751SLiu Bo 		spin_unlock(&cache->lock);
4875c79a1751SLiu Bo 
4876c79a1751SLiu Bo 		spin_unlock(&cur_trans->dirty_bgs_lock);
4877c79a1751SLiu Bo 		btrfs_put_block_group(cache);
4878ba2c4d4eSJosef Bacik 		btrfs_delayed_refs_rsv_release(fs_info, 1);
4879c79a1751SLiu Bo 		spin_lock(&cur_trans->dirty_bgs_lock);
4880c79a1751SLiu Bo 	}
4881c79a1751SLiu Bo 	spin_unlock(&cur_trans->dirty_bgs_lock);
4882c79a1751SLiu Bo 
488345ae2c18SNikolay Borisov 	/*
488445ae2c18SNikolay Borisov 	 * Refer to the definition of io_bgs member for details why it's safe
488545ae2c18SNikolay Borisov 	 * to use it without any locking
488645ae2c18SNikolay Borisov 	 */
4887c79a1751SLiu Bo 	while (!list_empty(&cur_trans->io_bgs)) {
4888c79a1751SLiu Bo 		cache = list_first_entry(&cur_trans->io_bgs,
488932da5386SDavid Sterba 					 struct btrfs_block_group,
4890c79a1751SLiu Bo 					 io_list);
4891c79a1751SLiu Bo 
4892c79a1751SLiu Bo 		list_del_init(&cache->io_list);
4893c79a1751SLiu Bo 		spin_lock(&cache->lock);
4894c79a1751SLiu Bo 		cache->disk_cache_state = BTRFS_DC_ERROR;
4895c79a1751SLiu Bo 		spin_unlock(&cache->lock);
4896c79a1751SLiu Bo 		btrfs_cleanup_bg_io(cache);
4897c79a1751SLiu Bo 	}
4898c79a1751SLiu Bo }
4899c79a1751SLiu Bo 
490049b25e05SJeff Mahoney void btrfs_cleanup_one_transaction(struct btrfs_transaction *cur_trans,
49012ff7e61eSJeff Mahoney 				   struct btrfs_fs_info *fs_info)
490249b25e05SJeff Mahoney {
4903bbbf7243SNikolay Borisov 	struct btrfs_device *dev, *tmp;
4904bbbf7243SNikolay Borisov 
49052ff7e61eSJeff Mahoney 	btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
4906c79a1751SLiu Bo 	ASSERT(list_empty(&cur_trans->dirty_bgs));
4907c79a1751SLiu Bo 	ASSERT(list_empty(&cur_trans->io_bgs));
4908c79a1751SLiu Bo 
4909bbbf7243SNikolay Borisov 	list_for_each_entry_safe(dev, tmp, &cur_trans->dev_update_list,
4910bbbf7243SNikolay Borisov 				 post_commit_list) {
4911bbbf7243SNikolay Borisov 		list_del_init(&dev->post_commit_list);
4912bbbf7243SNikolay Borisov 	}
4913bbbf7243SNikolay Borisov 
49142ff7e61eSJeff Mahoney 	btrfs_destroy_delayed_refs(cur_trans, fs_info);
491549b25e05SJeff Mahoney 
49164a9d8bdeSMiao Xie 	cur_trans->state = TRANS_STATE_COMMIT_START;
49170b246afaSJeff Mahoney 	wake_up(&fs_info->transaction_blocked_wait);
491849b25e05SJeff Mahoney 
49194a9d8bdeSMiao Xie 	cur_trans->state = TRANS_STATE_UNBLOCKED;
49200b246afaSJeff Mahoney 	wake_up(&fs_info->transaction_wait);
492149b25e05SJeff Mahoney 
4922ccdf9b30SJeff Mahoney 	btrfs_destroy_delayed_inodes(fs_info);
492367cde344SMiao Xie 
49242ff7e61eSJeff Mahoney 	btrfs_destroy_marked_extents(fs_info, &cur_trans->dirty_pages,
492549b25e05SJeff Mahoney 				     EXTENT_DIRTY);
4926fe119a6eSNikolay Borisov 	btrfs_destroy_pinned_extent(fs_info, &cur_trans->pinned_extents);
492749b25e05SJeff Mahoney 
4928d3575156SNaohiro Aota 	btrfs_free_redirty_list(cur_trans);
4929d3575156SNaohiro Aota 
49304a9d8bdeSMiao Xie 	cur_trans->state =TRANS_STATE_COMPLETED;
49314a9d8bdeSMiao Xie 	wake_up(&cur_trans->commit_wait);
493249b25e05SJeff Mahoney }
493349b25e05SJeff Mahoney 
49342ff7e61eSJeff Mahoney static int btrfs_cleanup_transaction(struct btrfs_fs_info *fs_info)
4935acce952bSliubo {
4936acce952bSliubo 	struct btrfs_transaction *t;
4937acce952bSliubo 
49380b246afaSJeff Mahoney 	mutex_lock(&fs_info->transaction_kthread_mutex);
4939acce952bSliubo 
49400b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
49410b246afaSJeff Mahoney 	while (!list_empty(&fs_info->trans_list)) {
49420b246afaSJeff Mahoney 		t = list_first_entry(&fs_info->trans_list,
4943724e2315SJosef Bacik 				     struct btrfs_transaction, list);
4944724e2315SJosef Bacik 		if (t->state >= TRANS_STATE_COMMIT_START) {
49459b64f57dSElena Reshetova 			refcount_inc(&t->use_count);
49460b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
49472ff7e61eSJeff Mahoney 			btrfs_wait_for_commit(fs_info, t->transid);
4948724e2315SJosef Bacik 			btrfs_put_transaction(t);
49490b246afaSJeff Mahoney 			spin_lock(&fs_info->trans_lock);
4950724e2315SJosef Bacik 			continue;
4951724e2315SJosef Bacik 		}
49520b246afaSJeff Mahoney 		if (t == fs_info->running_transaction) {
4953724e2315SJosef Bacik 			t->state = TRANS_STATE_COMMIT_DOING;
49540b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
4955724e2315SJosef Bacik 			/*
4956724e2315SJosef Bacik 			 * We wait for 0 num_writers since we don't hold a trans
4957724e2315SJosef Bacik 			 * handle open currently for this transaction.
4958724e2315SJosef Bacik 			 */
4959724e2315SJosef Bacik 			wait_event(t->writer_wait,
4960724e2315SJosef Bacik 				   atomic_read(&t->num_writers) == 0);
4961724e2315SJosef Bacik 		} else {
49620b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
4963724e2315SJosef Bacik 		}
49642ff7e61eSJeff Mahoney 		btrfs_cleanup_one_transaction(t, fs_info);
4965724e2315SJosef Bacik 
49660b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
49670b246afaSJeff Mahoney 		if (t == fs_info->running_transaction)
49680b246afaSJeff Mahoney 			fs_info->running_transaction = NULL;
4969724e2315SJosef Bacik 		list_del_init(&t->list);
49700b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
4971a4abeea4SJosef Bacik 
4972724e2315SJosef Bacik 		btrfs_put_transaction(t);
49732ff7e61eSJeff Mahoney 		trace_btrfs_transaction_commit(fs_info->tree_root);
49740b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
4975724e2315SJosef Bacik 	}
49760b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
49770b246afaSJeff Mahoney 	btrfs_destroy_all_ordered_extents(fs_info);
4978ccdf9b30SJeff Mahoney 	btrfs_destroy_delayed_inodes(fs_info);
4979ccdf9b30SJeff Mahoney 	btrfs_assert_delayed_root_empty(fs_info);
49800b246afaSJeff Mahoney 	btrfs_destroy_all_delalloc_inodes(fs_info);
4981ef67963dSJosef Bacik 	btrfs_drop_all_logs(fs_info);
49820b246afaSJeff Mahoney 	mutex_unlock(&fs_info->transaction_kthread_mutex);
4983acce952bSliubo 
4984acce952bSliubo 	return 0;
4985acce952bSliubo }
4986ec7d6dfdSNikolay Borisov 
4987453e4873SNikolay Borisov int btrfs_init_root_free_objectid(struct btrfs_root *root)
4988ec7d6dfdSNikolay Borisov {
4989ec7d6dfdSNikolay Borisov 	struct btrfs_path *path;
4990ec7d6dfdSNikolay Borisov 	int ret;
4991ec7d6dfdSNikolay Borisov 	struct extent_buffer *l;
4992ec7d6dfdSNikolay Borisov 	struct btrfs_key search_key;
4993ec7d6dfdSNikolay Borisov 	struct btrfs_key found_key;
4994ec7d6dfdSNikolay Borisov 	int slot;
4995ec7d6dfdSNikolay Borisov 
4996ec7d6dfdSNikolay Borisov 	path = btrfs_alloc_path();
4997ec7d6dfdSNikolay Borisov 	if (!path)
4998ec7d6dfdSNikolay Borisov 		return -ENOMEM;
4999ec7d6dfdSNikolay Borisov 
5000ec7d6dfdSNikolay Borisov 	search_key.objectid = BTRFS_LAST_FREE_OBJECTID;
5001ec7d6dfdSNikolay Borisov 	search_key.type = -1;
5002ec7d6dfdSNikolay Borisov 	search_key.offset = (u64)-1;
5003ec7d6dfdSNikolay Borisov 	ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
5004ec7d6dfdSNikolay Borisov 	if (ret < 0)
5005ec7d6dfdSNikolay Borisov 		goto error;
5006ec7d6dfdSNikolay Borisov 	BUG_ON(ret == 0); /* Corruption */
5007ec7d6dfdSNikolay Borisov 	if (path->slots[0] > 0) {
5008ec7d6dfdSNikolay Borisov 		slot = path->slots[0] - 1;
5009ec7d6dfdSNikolay Borisov 		l = path->nodes[0];
5010ec7d6dfdSNikolay Borisov 		btrfs_item_key_to_cpu(l, &found_key, slot);
501123125104SNikolay Borisov 		root->free_objectid = max_t(u64, found_key.objectid + 1,
501223125104SNikolay Borisov 					    BTRFS_FIRST_FREE_OBJECTID);
5013ec7d6dfdSNikolay Borisov 	} else {
501423125104SNikolay Borisov 		root->free_objectid = BTRFS_FIRST_FREE_OBJECTID;
5015ec7d6dfdSNikolay Borisov 	}
5016ec7d6dfdSNikolay Borisov 	ret = 0;
5017ec7d6dfdSNikolay Borisov error:
5018ec7d6dfdSNikolay Borisov 	btrfs_free_path(path);
5019ec7d6dfdSNikolay Borisov 	return ret;
5020ec7d6dfdSNikolay Borisov }
5021ec7d6dfdSNikolay Borisov 
5022543068a2SNikolay Borisov int btrfs_get_free_objectid(struct btrfs_root *root, u64 *objectid)
5023ec7d6dfdSNikolay Borisov {
5024ec7d6dfdSNikolay Borisov 	int ret;
5025ec7d6dfdSNikolay Borisov 	mutex_lock(&root->objectid_mutex);
5026ec7d6dfdSNikolay Borisov 
50276b8fad57SNikolay Borisov 	if (unlikely(root->free_objectid >= BTRFS_LAST_FREE_OBJECTID)) {
5028ec7d6dfdSNikolay Borisov 		btrfs_warn(root->fs_info,
5029ec7d6dfdSNikolay Borisov 			   "the objectid of root %llu reaches its highest value",
5030ec7d6dfdSNikolay Borisov 			   root->root_key.objectid);
5031ec7d6dfdSNikolay Borisov 		ret = -ENOSPC;
5032ec7d6dfdSNikolay Borisov 		goto out;
5033ec7d6dfdSNikolay Borisov 	}
5034ec7d6dfdSNikolay Borisov 
503523125104SNikolay Borisov 	*objectid = root->free_objectid++;
5036ec7d6dfdSNikolay Borisov 	ret = 0;
5037ec7d6dfdSNikolay Borisov out:
5038ec7d6dfdSNikolay Borisov 	mutex_unlock(&root->objectid_mutex);
5039ec7d6dfdSNikolay Borisov 	return ret;
5040ec7d6dfdSNikolay Borisov }
5041