xref: /openbmc/linux/fs/btrfs/disk-io.c (revision 16beac87)
1c1d7c514SDavid Sterba // SPDX-License-Identifier: GPL-2.0
26cbd5570SChris Mason /*
36cbd5570SChris Mason  * Copyright (C) 2007 Oracle.  All rights reserved.
46cbd5570SChris Mason  */
56cbd5570SChris Mason 
6e20d96d6SChris Mason #include <linux/fs.h>
7d98237b3SChris Mason #include <linux/blkdev.h>
80f7d52f4SChris Mason #include <linux/radix-tree.h>
935b7e476SChris Mason #include <linux/writeback.h>
10ce9adaa5SChris Mason #include <linux/workqueue.h>
11a74a4b97SChris Mason #include <linux/kthread.h>
125a0e3ad6STejun Heo #include <linux/slab.h>
13784b4e29SChris Mason #include <linux/migrate.h>
147a36ddecSDavid Sterba #include <linux/ratelimit.h>
156463fe58SStefan Behrens #include <linux/uuid.h>
16803b2f54SStefan Behrens #include <linux/semaphore.h>
17540adea3SMasami Hiramatsu #include <linux/error-injection.h>
189678c543SNikolay Borisov #include <linux/crc32c.h>
19b89f6d1fSFilipe Manana #include <linux/sched/mm.h>
207e75bf3fSDavid Sterba #include <asm/unaligned.h>
216d97c6e3SJohannes Thumshirn #include <crypto/hash.h>
22eb60ceacSChris Mason #include "ctree.h"
23eb60ceacSChris Mason #include "disk-io.h"
24e089f05cSChris Mason #include "transaction.h"
250f7d52f4SChris Mason #include "btrfs_inode.h"
260b86a832SChris Mason #include "volumes.h"
27db94535dSChris Mason #include "print-tree.h"
28925baeddSChris Mason #include "locking.h"
29e02119d5SChris Mason #include "tree-log.h"
30fa9c0d79SChris Mason #include "free-space-cache.h"
3170f6d82eSOmar Sandoval #include "free-space-tree.h"
3221adbd5cSStefan Behrens #include "check-integrity.h"
33606686eeSJosef Bacik #include "rcu-string.h"
348dabb742SStefan Behrens #include "dev-replace.h"
3553b381b3SDavid Woodhouse #include "raid56.h"
365ac1d209SJeff Mahoney #include "sysfs.h"
37fcebe456SJosef Bacik #include "qgroup.h"
38ebb8765bSAnand Jain #include "compression.h"
39557ea5ddSQu Wenruo #include "tree-checker.h"
40fd708b81SJosef Bacik #include "ref-verify.h"
41aac0023cSJosef Bacik #include "block-group.h"
42b0643e59SDennis Zhou #include "discard.h"
43f603bb94SNikolay Borisov #include "space-info.h"
44b70f5097SNaohiro Aota #include "zoned.h"
45139e8cd3SQu Wenruo #include "subpage.h"
46eb60ceacSChris Mason 
47319e4d06SQu Wenruo #define BTRFS_SUPER_FLAG_SUPP	(BTRFS_HEADER_FLAG_WRITTEN |\
48319e4d06SQu Wenruo 				 BTRFS_HEADER_FLAG_RELOC |\
49319e4d06SQu Wenruo 				 BTRFS_SUPER_FLAG_ERROR |\
50319e4d06SQu Wenruo 				 BTRFS_SUPER_FLAG_SEEDING |\
51e2731e55SAnand Jain 				 BTRFS_SUPER_FLAG_METADUMP |\
52e2731e55SAnand Jain 				 BTRFS_SUPER_FLAG_METADUMP_V2)
53319e4d06SQu Wenruo 
548b712842SChris Mason static void end_workqueue_fn(struct btrfs_work *work);
55143bede5SJeff Mahoney static void btrfs_destroy_ordered_extents(struct btrfs_root *root);
56acce952bSliubo static int btrfs_destroy_delayed_refs(struct btrfs_transaction *trans,
572ff7e61eSJeff Mahoney 				      struct btrfs_fs_info *fs_info);
58143bede5SJeff Mahoney static void btrfs_destroy_delalloc_inodes(struct btrfs_root *root);
592ff7e61eSJeff Mahoney static int btrfs_destroy_marked_extents(struct btrfs_fs_info *fs_info,
60acce952bSliubo 					struct extent_io_tree *dirty_pages,
61acce952bSliubo 					int mark);
622ff7e61eSJeff Mahoney static int btrfs_destroy_pinned_extent(struct btrfs_fs_info *fs_info,
63acce952bSliubo 				       struct extent_io_tree *pinned_extents);
642ff7e61eSJeff Mahoney static int btrfs_cleanup_transaction(struct btrfs_fs_info *fs_info);
652ff7e61eSJeff Mahoney static void btrfs_error_commit_super(struct btrfs_fs_info *fs_info);
66ce9adaa5SChris Mason 
67d352ac68SChris Mason /*
6897eb6b69SDavid Sterba  * btrfs_end_io_wq structs are used to do processing in task context when an IO
6997eb6b69SDavid Sterba  * is complete.  This is used during reads to verify checksums, and it is used
70d352ac68SChris Mason  * by writes to insert metadata for new file extents after IO is complete.
71d352ac68SChris Mason  */
7297eb6b69SDavid Sterba struct btrfs_end_io_wq {
73ce9adaa5SChris Mason 	struct bio *bio;
74ce9adaa5SChris Mason 	bio_end_io_t *end_io;
75ce9adaa5SChris Mason 	void *private;
76ce9adaa5SChris Mason 	struct btrfs_fs_info *info;
774e4cbee9SChristoph Hellwig 	blk_status_t status;
78bfebd8b5SDavid Sterba 	enum btrfs_wq_endio_type metadata;
798b712842SChris Mason 	struct btrfs_work work;
80ce9adaa5SChris Mason };
810da5468fSChris Mason 
8297eb6b69SDavid Sterba static struct kmem_cache *btrfs_end_io_wq_cache;
8397eb6b69SDavid Sterba 
8497eb6b69SDavid Sterba int __init btrfs_end_io_wq_init(void)
8597eb6b69SDavid Sterba {
8697eb6b69SDavid Sterba 	btrfs_end_io_wq_cache = kmem_cache_create("btrfs_end_io_wq",
8797eb6b69SDavid Sterba 					sizeof(struct btrfs_end_io_wq),
8897eb6b69SDavid Sterba 					0,
89fba4b697SNikolay Borisov 					SLAB_MEM_SPREAD,
9097eb6b69SDavid Sterba 					NULL);
9197eb6b69SDavid Sterba 	if (!btrfs_end_io_wq_cache)
9297eb6b69SDavid Sterba 		return -ENOMEM;
9397eb6b69SDavid Sterba 	return 0;
9497eb6b69SDavid Sterba }
9597eb6b69SDavid Sterba 
96e67c718bSDavid Sterba void __cold btrfs_end_io_wq_exit(void)
9797eb6b69SDavid Sterba {
9897eb6b69SDavid Sterba 	kmem_cache_destroy(btrfs_end_io_wq_cache);
9997eb6b69SDavid Sterba }
10097eb6b69SDavid Sterba 
101141386e1SJosef Bacik static void btrfs_free_csum_hash(struct btrfs_fs_info *fs_info)
102141386e1SJosef Bacik {
103141386e1SJosef Bacik 	if (fs_info->csum_shash)
104141386e1SJosef Bacik 		crypto_free_shash(fs_info->csum_shash);
105141386e1SJosef Bacik }
106141386e1SJosef Bacik 
107d352ac68SChris Mason /*
108d352ac68SChris Mason  * async submit bios are used to offload expensive checksumming
109d352ac68SChris Mason  * onto the worker threads.  They checksum file and metadata bios
110d352ac68SChris Mason  * just before they are sent down the IO stack.
111d352ac68SChris Mason  */
11244b8bd7eSChris Mason struct async_submit_bio {
1138896a08dSQu Wenruo 	struct inode *inode;
11444b8bd7eSChris Mason 	struct bio *bio;
115a758781dSDavid Sterba 	extent_submit_bio_start_t *submit_bio_start;
11644b8bd7eSChris Mason 	int mirror_num;
1171941b64bSQu Wenruo 
1181941b64bSQu Wenruo 	/* Optional parameter for submit_bio_start used by direct io */
1191941b64bSQu Wenruo 	u64 dio_file_offset;
1208b712842SChris Mason 	struct btrfs_work work;
1214e4cbee9SChristoph Hellwig 	blk_status_t status;
12244b8bd7eSChris Mason };
12344b8bd7eSChris Mason 
12485d4e461SChris Mason /*
12585d4e461SChris Mason  * Lockdep class keys for extent_buffer->lock's in this root.  For a given
12685d4e461SChris Mason  * eb, the lockdep key is determined by the btrfs_root it belongs to and
12785d4e461SChris Mason  * the level the eb occupies in the tree.
1284008c04aSChris Mason  *
12985d4e461SChris Mason  * Different roots are used for different purposes and may nest inside each
13085d4e461SChris Mason  * other and they require separate keysets.  As lockdep keys should be
13185d4e461SChris Mason  * static, assign keysets according to the purpose of the root as indicated
1324fd786e6SMisono Tomohiro  * by btrfs_root->root_key.objectid.  This ensures that all special purpose
1334fd786e6SMisono Tomohiro  * roots have separate keysets.
1344008c04aSChris Mason  *
13585d4e461SChris Mason  * Lock-nesting across peer nodes is always done with the immediate parent
13685d4e461SChris Mason  * node locked thus preventing deadlock.  As lockdep doesn't know this, use
13785d4e461SChris Mason  * subclass to avoid triggering lockdep warning in such cases.
1384008c04aSChris Mason  *
13985d4e461SChris Mason  * The key is set by the readpage_end_io_hook after the buffer has passed
14085d4e461SChris Mason  * csum validation but before the pages are unlocked.  It is also set by
14185d4e461SChris Mason  * btrfs_init_new_buffer on freshly allocated blocks.
14285d4e461SChris Mason  *
14385d4e461SChris Mason  * We also add a check to make sure the highest level of the tree is the
14485d4e461SChris Mason  * same as our lockdep setup here.  If BTRFS_MAX_LEVEL changes, this code
14585d4e461SChris Mason  * needs update as well.
1464008c04aSChris Mason  */
1474008c04aSChris Mason #ifdef CONFIG_DEBUG_LOCK_ALLOC
1484008c04aSChris Mason # if BTRFS_MAX_LEVEL != 8
1494008c04aSChris Mason #  error
1504008c04aSChris Mason # endif
15185d4e461SChris Mason 
152ab1405aaSDavid Sterba #define DEFINE_LEVEL(stem, level)					\
153ab1405aaSDavid Sterba 	.names[level] = "btrfs-" stem "-0" #level,
154ab1405aaSDavid Sterba 
155ab1405aaSDavid Sterba #define DEFINE_NAME(stem)						\
156ab1405aaSDavid Sterba 	DEFINE_LEVEL(stem, 0)						\
157ab1405aaSDavid Sterba 	DEFINE_LEVEL(stem, 1)						\
158ab1405aaSDavid Sterba 	DEFINE_LEVEL(stem, 2)						\
159ab1405aaSDavid Sterba 	DEFINE_LEVEL(stem, 3)						\
160ab1405aaSDavid Sterba 	DEFINE_LEVEL(stem, 4)						\
161ab1405aaSDavid Sterba 	DEFINE_LEVEL(stem, 5)						\
162ab1405aaSDavid Sterba 	DEFINE_LEVEL(stem, 6)						\
163ab1405aaSDavid Sterba 	DEFINE_LEVEL(stem, 7)
164ab1405aaSDavid Sterba 
16585d4e461SChris Mason static struct btrfs_lockdep_keyset {
16685d4e461SChris Mason 	u64			id;		/* root objectid */
167ab1405aaSDavid Sterba 	/* Longest entry: btrfs-free-space-00 */
168387824afSDavid Sterba 	char			names[BTRFS_MAX_LEVEL][20];
169387824afSDavid Sterba 	struct lock_class_key	keys[BTRFS_MAX_LEVEL];
17085d4e461SChris Mason } btrfs_lockdep_keysets[] = {
171ab1405aaSDavid Sterba 	{ .id = BTRFS_ROOT_TREE_OBJECTID,	DEFINE_NAME("root")	},
172ab1405aaSDavid Sterba 	{ .id = BTRFS_EXTENT_TREE_OBJECTID,	DEFINE_NAME("extent")	},
173ab1405aaSDavid Sterba 	{ .id = BTRFS_CHUNK_TREE_OBJECTID,	DEFINE_NAME("chunk")	},
174ab1405aaSDavid Sterba 	{ .id = BTRFS_DEV_TREE_OBJECTID,	DEFINE_NAME("dev")	},
175ab1405aaSDavid Sterba 	{ .id = BTRFS_CSUM_TREE_OBJECTID,	DEFINE_NAME("csum")	},
176ab1405aaSDavid Sterba 	{ .id = BTRFS_QUOTA_TREE_OBJECTID,	DEFINE_NAME("quota")	},
177ab1405aaSDavid Sterba 	{ .id = BTRFS_TREE_LOG_OBJECTID,	DEFINE_NAME("log")	},
178ab1405aaSDavid Sterba 	{ .id = BTRFS_TREE_RELOC_OBJECTID,	DEFINE_NAME("treloc")	},
179ab1405aaSDavid Sterba 	{ .id = BTRFS_DATA_RELOC_TREE_OBJECTID,	DEFINE_NAME("dreloc")	},
180ab1405aaSDavid Sterba 	{ .id = BTRFS_UUID_TREE_OBJECTID,	DEFINE_NAME("uuid")	},
181ab1405aaSDavid Sterba 	{ .id = BTRFS_FREE_SPACE_TREE_OBJECTID,	DEFINE_NAME("free-space") },
182ab1405aaSDavid Sterba 	{ .id = 0,				DEFINE_NAME("tree")	},
1834008c04aSChris Mason };
18485d4e461SChris Mason 
185ab1405aaSDavid Sterba #undef DEFINE_LEVEL
186ab1405aaSDavid Sterba #undef DEFINE_NAME
18785d4e461SChris Mason 
18885d4e461SChris Mason void btrfs_set_buffer_lockdep_class(u64 objectid, struct extent_buffer *eb,
18985d4e461SChris Mason 				    int level)
19085d4e461SChris Mason {
19185d4e461SChris Mason 	struct btrfs_lockdep_keyset *ks;
19285d4e461SChris Mason 
19385d4e461SChris Mason 	BUG_ON(level >= ARRAY_SIZE(ks->keys));
19485d4e461SChris Mason 
19585d4e461SChris Mason 	/* find the matching keyset, id 0 is the default entry */
19685d4e461SChris Mason 	for (ks = btrfs_lockdep_keysets; ks->id; ks++)
19785d4e461SChris Mason 		if (ks->id == objectid)
19885d4e461SChris Mason 			break;
19985d4e461SChris Mason 
20085d4e461SChris Mason 	lockdep_set_class_and_name(&eb->lock,
20185d4e461SChris Mason 				   &ks->keys[level], ks->names[level]);
20285d4e461SChris Mason }
20385d4e461SChris Mason 
2044008c04aSChris Mason #endif
2054008c04aSChris Mason 
206d352ac68SChris Mason /*
2072996e1f8SJohannes Thumshirn  * Compute the csum of a btree block and store the result to provided buffer.
208d352ac68SChris Mason  */
209c67b3892SDavid Sterba static void csum_tree_block(struct extent_buffer *buf, u8 *result)
21019c00ddcSChris Mason {
211d5178578SJohannes Thumshirn 	struct btrfs_fs_info *fs_info = buf->fs_info;
2127280305eSDavid Sterba 	const int num_pages = num_extent_pages(buf);
213a26663e7SQu Wenruo 	const int first_page_part = min_t(u32, PAGE_SIZE, fs_info->nodesize);
214d5178578SJohannes Thumshirn 	SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
21519c00ddcSChris Mason 	char *kaddr;
216e9be5a30SDavid Sterba 	int i;
217d5178578SJohannes Thumshirn 
218d5178578SJohannes Thumshirn 	shash->tfm = fs_info->csum_shash;
219d5178578SJohannes Thumshirn 	crypto_shash_init(shash);
220a26663e7SQu Wenruo 	kaddr = page_address(buf->pages[0]) + offset_in_page(buf->start);
221e9be5a30SDavid Sterba 	crypto_shash_update(shash, kaddr + BTRFS_CSUM_SIZE,
222a26663e7SQu Wenruo 			    first_page_part - BTRFS_CSUM_SIZE);
22319c00ddcSChris Mason 
224e9be5a30SDavid Sterba 	for (i = 1; i < num_pages; i++) {
225e9be5a30SDavid Sterba 		kaddr = page_address(buf->pages[i]);
226e9be5a30SDavid Sterba 		crypto_shash_update(shash, kaddr, PAGE_SIZE);
22719c00ddcSChris Mason 	}
22871a63551SDavid Sterba 	memset(result, 0, BTRFS_CSUM_SIZE);
229d5178578SJohannes Thumshirn 	crypto_shash_final(shash, result);
23019c00ddcSChris Mason }
23119c00ddcSChris Mason 
232d352ac68SChris Mason /*
233d352ac68SChris Mason  * we can't consider a given block up to date unless the transid of the
234d352ac68SChris Mason  * block matches the transid in the parent node's pointer.  This is how we
235d352ac68SChris Mason  * detect blocks that either didn't get written at all or got written
236d352ac68SChris Mason  * in the wrong place.
237d352ac68SChris Mason  */
2381259ab75SChris Mason static int verify_parent_transid(struct extent_io_tree *io_tree,
239b9fab919SChris Mason 				 struct extent_buffer *eb, u64 parent_transid,
240b9fab919SChris Mason 				 int atomic)
2411259ab75SChris Mason {
2422ac55d41SJosef Bacik 	struct extent_state *cached_state = NULL;
2431259ab75SChris Mason 	int ret;
2441259ab75SChris Mason 
2451259ab75SChris Mason 	if (!parent_transid || btrfs_header_generation(eb) == parent_transid)
2461259ab75SChris Mason 		return 0;
2471259ab75SChris Mason 
248b9fab919SChris Mason 	if (atomic)
249b9fab919SChris Mason 		return -EAGAIN;
250b9fab919SChris Mason 
2512ac55d41SJosef Bacik 	lock_extent_bits(io_tree, eb->start, eb->start + eb->len - 1,
252ff13db41SDavid Sterba 			 &cached_state);
2530b32f4bbSJosef Bacik 	if (extent_buffer_uptodate(eb) &&
2541259ab75SChris Mason 	    btrfs_header_generation(eb) == parent_transid) {
2551259ab75SChris Mason 		ret = 0;
2561259ab75SChris Mason 		goto out;
2571259ab75SChris Mason 	}
25894647322SDavid Sterba 	btrfs_err_rl(eb->fs_info,
25994647322SDavid Sterba 		"parent transid verify failed on %llu wanted %llu found %llu",
26094647322SDavid Sterba 			eb->start,
26129549aecSWang Shilong 			parent_transid, btrfs_header_generation(eb));
2621259ab75SChris Mason 	ret = 1;
2630b32f4bbSJosef Bacik 	clear_extent_buffer_uptodate(eb);
26433958dc6SChris Mason out:
2652ac55d41SJosef Bacik 	unlock_extent_cached(io_tree, eb->start, eb->start + eb->len - 1,
266e43bbe5eSDavid Sterba 			     &cached_state);
2671259ab75SChris Mason 	return ret;
2681259ab75SChris Mason }
2691259ab75SChris Mason 
270e7e16f48SJohannes Thumshirn static bool btrfs_supported_super_csum(u16 csum_type)
271e7e16f48SJohannes Thumshirn {
272e7e16f48SJohannes Thumshirn 	switch (csum_type) {
273e7e16f48SJohannes Thumshirn 	case BTRFS_CSUM_TYPE_CRC32:
2743951e7f0SJohannes Thumshirn 	case BTRFS_CSUM_TYPE_XXHASH:
2753831bf00SJohannes Thumshirn 	case BTRFS_CSUM_TYPE_SHA256:
276352ae07bSDavid Sterba 	case BTRFS_CSUM_TYPE_BLAKE2:
277e7e16f48SJohannes Thumshirn 		return true;
278e7e16f48SJohannes Thumshirn 	default:
279e7e16f48SJohannes Thumshirn 		return false;
280e7e16f48SJohannes Thumshirn 	}
281e7e16f48SJohannes Thumshirn }
282e7e16f48SJohannes Thumshirn 
283d352ac68SChris Mason /*
2841104a885SDavid Sterba  * Return 0 if the superblock checksum type matches the checksum value of that
2851104a885SDavid Sterba  * algorithm. Pass the raw disk superblock data.
2861104a885SDavid Sterba  */
287ab8d0fc4SJeff Mahoney static int btrfs_check_super_csum(struct btrfs_fs_info *fs_info,
288ab8d0fc4SJeff Mahoney 				  char *raw_disk_sb)
2891104a885SDavid Sterba {
2901104a885SDavid Sterba 	struct btrfs_super_block *disk_sb =
2911104a885SDavid Sterba 		(struct btrfs_super_block *)raw_disk_sb;
29251bce6c9SJohannes Thumshirn 	char result[BTRFS_CSUM_SIZE];
293d5178578SJohannes Thumshirn 	SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
294d5178578SJohannes Thumshirn 
295d5178578SJohannes Thumshirn 	shash->tfm = fs_info->csum_shash;
2961104a885SDavid Sterba 
2971104a885SDavid Sterba 	/*
2981104a885SDavid Sterba 	 * The super_block structure does not span the whole
29951bce6c9SJohannes Thumshirn 	 * BTRFS_SUPER_INFO_SIZE range, we expect that the unused space is
30051bce6c9SJohannes Thumshirn 	 * filled with zeros and is included in the checksum.
3011104a885SDavid Sterba 	 */
302fd08001fSEric Biggers 	crypto_shash_digest(shash, raw_disk_sb + BTRFS_CSUM_SIZE,
303fd08001fSEric Biggers 			    BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE, result);
3041104a885SDavid Sterba 
30555fc29beSDavid Sterba 	if (memcmp(disk_sb->csum, result, fs_info->csum_size))
306e7e16f48SJohannes Thumshirn 		return 1;
3071104a885SDavid Sterba 
308e7e16f48SJohannes Thumshirn 	return 0;
3091104a885SDavid Sterba }
3101104a885SDavid Sterba 
311e064d5e9SDavid Sterba int btrfs_verify_level_key(struct extent_buffer *eb, int level,
312ff76a864SLiu Bo 			   struct btrfs_key *first_key, u64 parent_transid)
313581c1760SQu Wenruo {
314e064d5e9SDavid Sterba 	struct btrfs_fs_info *fs_info = eb->fs_info;
315581c1760SQu Wenruo 	int found_level;
316581c1760SQu Wenruo 	struct btrfs_key found_key;
317581c1760SQu Wenruo 	int ret;
318581c1760SQu Wenruo 
319581c1760SQu Wenruo 	found_level = btrfs_header_level(eb);
320581c1760SQu Wenruo 	if (found_level != level) {
32163489055SQu Wenruo 		WARN(IS_ENABLED(CONFIG_BTRFS_DEBUG),
32263489055SQu Wenruo 		     KERN_ERR "BTRFS: tree level check failed\n");
323581c1760SQu Wenruo 		btrfs_err(fs_info,
324581c1760SQu Wenruo "tree level mismatch detected, bytenr=%llu level expected=%u has=%u",
325581c1760SQu Wenruo 			  eb->start, level, found_level);
326581c1760SQu Wenruo 		return -EIO;
327581c1760SQu Wenruo 	}
328581c1760SQu Wenruo 
329581c1760SQu Wenruo 	if (!first_key)
330581c1760SQu Wenruo 		return 0;
331581c1760SQu Wenruo 
3325d41be6fSQu Wenruo 	/*
3335d41be6fSQu Wenruo 	 * For live tree block (new tree blocks in current transaction),
3345d41be6fSQu Wenruo 	 * we need proper lock context to avoid race, which is impossible here.
3355d41be6fSQu Wenruo 	 * So we only checks tree blocks which is read from disk, whose
3365d41be6fSQu Wenruo 	 * generation <= fs_info->last_trans_committed.
3375d41be6fSQu Wenruo 	 */
3385d41be6fSQu Wenruo 	if (btrfs_header_generation(eb) > fs_info->last_trans_committed)
3395d41be6fSQu Wenruo 		return 0;
34062fdaa52SQu Wenruo 
34162fdaa52SQu Wenruo 	/* We have @first_key, so this @eb must have at least one item */
34262fdaa52SQu Wenruo 	if (btrfs_header_nritems(eb) == 0) {
34362fdaa52SQu Wenruo 		btrfs_err(fs_info,
34462fdaa52SQu Wenruo 		"invalid tree nritems, bytenr=%llu nritems=0 expect >0",
34562fdaa52SQu Wenruo 			  eb->start);
34662fdaa52SQu Wenruo 		WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
34762fdaa52SQu Wenruo 		return -EUCLEAN;
34862fdaa52SQu Wenruo 	}
34962fdaa52SQu Wenruo 
350581c1760SQu Wenruo 	if (found_level)
351581c1760SQu Wenruo 		btrfs_node_key_to_cpu(eb, &found_key, 0);
352581c1760SQu Wenruo 	else
353581c1760SQu Wenruo 		btrfs_item_key_to_cpu(eb, &found_key, 0);
354581c1760SQu Wenruo 	ret = btrfs_comp_cpu_keys(first_key, &found_key);
355581c1760SQu Wenruo 
356581c1760SQu Wenruo 	if (ret) {
35763489055SQu Wenruo 		WARN(IS_ENABLED(CONFIG_BTRFS_DEBUG),
35863489055SQu Wenruo 		     KERN_ERR "BTRFS: tree first key check failed\n");
359581c1760SQu Wenruo 		btrfs_err(fs_info,
360ff76a864SLiu Bo "tree first key mismatch detected, bytenr=%llu parent_transid=%llu key expected=(%llu,%u,%llu) has=(%llu,%u,%llu)",
361ff76a864SLiu Bo 			  eb->start, parent_transid, first_key->objectid,
362ff76a864SLiu Bo 			  first_key->type, first_key->offset,
363ff76a864SLiu Bo 			  found_key.objectid, found_key.type,
364ff76a864SLiu Bo 			  found_key.offset);
365581c1760SQu Wenruo 	}
366581c1760SQu Wenruo 	return ret;
367581c1760SQu Wenruo }
368581c1760SQu Wenruo 
3691104a885SDavid Sterba /*
370d352ac68SChris Mason  * helper to read a given tree block, doing retries as required when
371d352ac68SChris Mason  * the checksums don't match and we have alternate mirrors to try.
372581c1760SQu Wenruo  *
373581c1760SQu Wenruo  * @parent_transid:	expected transid, skip check if 0
374581c1760SQu Wenruo  * @level:		expected level, mandatory check
375581c1760SQu Wenruo  * @first_key:		expected key of first slot, skip check if NULL
376d352ac68SChris Mason  */
3775ab12d1fSDavid Sterba static int btree_read_extent_buffer_pages(struct extent_buffer *eb,
378581c1760SQu Wenruo 					  u64 parent_transid, int level,
379581c1760SQu Wenruo 					  struct btrfs_key *first_key)
380f188591eSChris Mason {
3815ab12d1fSDavid Sterba 	struct btrfs_fs_info *fs_info = eb->fs_info;
382f188591eSChris Mason 	struct extent_io_tree *io_tree;
383ea466794SJosef Bacik 	int failed = 0;
384f188591eSChris Mason 	int ret;
385f188591eSChris Mason 	int num_copies = 0;
386f188591eSChris Mason 	int mirror_num = 0;
387ea466794SJosef Bacik 	int failed_mirror = 0;
388f188591eSChris Mason 
3890b246afaSJeff Mahoney 	io_tree = &BTRFS_I(fs_info->btree_inode)->io_tree;
390f188591eSChris Mason 	while (1) {
391f8397d69SNikolay Borisov 		clear_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags);
392c2ccfbc6SNikolay Borisov 		ret = read_extent_buffer_pages(eb, WAIT_COMPLETE, mirror_num);
393256dd1bbSStefan Behrens 		if (!ret) {
394581c1760SQu Wenruo 			if (verify_parent_transid(io_tree, eb,
395b9fab919SChris Mason 						   parent_transid, 0))
396256dd1bbSStefan Behrens 				ret = -EIO;
397e064d5e9SDavid Sterba 			else if (btrfs_verify_level_key(eb, level,
398ff76a864SLiu Bo 						first_key, parent_transid))
399581c1760SQu Wenruo 				ret = -EUCLEAN;
400581c1760SQu Wenruo 			else
401581c1760SQu Wenruo 				break;
402256dd1bbSStefan Behrens 		}
403d397712bSChris Mason 
4040b246afaSJeff Mahoney 		num_copies = btrfs_num_copies(fs_info,
405f188591eSChris Mason 					      eb->start, eb->len);
4064235298eSChris Mason 		if (num_copies == 1)
407ea466794SJosef Bacik 			break;
4084235298eSChris Mason 
4095cf1ab56SJosef Bacik 		if (!failed_mirror) {
4105cf1ab56SJosef Bacik 			failed = 1;
4115cf1ab56SJosef Bacik 			failed_mirror = eb->read_mirror;
4125cf1ab56SJosef Bacik 		}
4135cf1ab56SJosef Bacik 
414f188591eSChris Mason 		mirror_num++;
415ea466794SJosef Bacik 		if (mirror_num == failed_mirror)
416ea466794SJosef Bacik 			mirror_num++;
417ea466794SJosef Bacik 
4184235298eSChris Mason 		if (mirror_num > num_copies)
419ea466794SJosef Bacik 			break;
420f188591eSChris Mason 	}
421ea466794SJosef Bacik 
422c0901581SStefan Behrens 	if (failed && !ret && failed_mirror)
42320a1fbf9SDavid Sterba 		btrfs_repair_eb_io_failure(eb, failed_mirror);
424ea466794SJosef Bacik 
425ea466794SJosef Bacik 	return ret;
426f188591eSChris Mason }
42719c00ddcSChris Mason 
428eca0f6f6SQu Wenruo static int csum_one_extent_buffer(struct extent_buffer *eb)
429eca0f6f6SQu Wenruo {
430eca0f6f6SQu Wenruo 	struct btrfs_fs_info *fs_info = eb->fs_info;
431eca0f6f6SQu Wenruo 	u8 result[BTRFS_CSUM_SIZE];
432eca0f6f6SQu Wenruo 	int ret;
433eca0f6f6SQu Wenruo 
434eca0f6f6SQu Wenruo 	ASSERT(memcmp_extent_buffer(eb, fs_info->fs_devices->metadata_uuid,
435eca0f6f6SQu Wenruo 				    offsetof(struct btrfs_header, fsid),
436eca0f6f6SQu Wenruo 				    BTRFS_FSID_SIZE) == 0);
437eca0f6f6SQu Wenruo 	csum_tree_block(eb, result);
438eca0f6f6SQu Wenruo 
439eca0f6f6SQu Wenruo 	if (btrfs_header_level(eb))
440eca0f6f6SQu Wenruo 		ret = btrfs_check_node(eb);
441eca0f6f6SQu Wenruo 	else
442eca0f6f6SQu Wenruo 		ret = btrfs_check_leaf_full(eb);
443eca0f6f6SQu Wenruo 
444eca0f6f6SQu Wenruo 	if (ret < 0) {
445eca0f6f6SQu Wenruo 		btrfs_print_tree(eb, 0);
446eca0f6f6SQu Wenruo 		btrfs_err(fs_info,
447eca0f6f6SQu Wenruo 			"block=%llu write time tree block corruption detected",
448eca0f6f6SQu Wenruo 			eb->start);
449eca0f6f6SQu Wenruo 		WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
450eca0f6f6SQu Wenruo 		return ret;
451eca0f6f6SQu Wenruo 	}
452eca0f6f6SQu Wenruo 	write_extent_buffer(eb, result, 0, fs_info->csum_size);
453eca0f6f6SQu Wenruo 
454eca0f6f6SQu Wenruo 	return 0;
455eca0f6f6SQu Wenruo }
456eca0f6f6SQu Wenruo 
457eca0f6f6SQu Wenruo /* Checksum all dirty extent buffers in one bio_vec */
458eca0f6f6SQu Wenruo static int csum_dirty_subpage_buffers(struct btrfs_fs_info *fs_info,
459eca0f6f6SQu Wenruo 				      struct bio_vec *bvec)
460eca0f6f6SQu Wenruo {
461eca0f6f6SQu Wenruo 	struct page *page = bvec->bv_page;
462eca0f6f6SQu Wenruo 	u64 bvec_start = page_offset(page) + bvec->bv_offset;
463eca0f6f6SQu Wenruo 	u64 cur;
464eca0f6f6SQu Wenruo 	int ret = 0;
465eca0f6f6SQu Wenruo 
466eca0f6f6SQu Wenruo 	for (cur = bvec_start; cur < bvec_start + bvec->bv_len;
467eca0f6f6SQu Wenruo 	     cur += fs_info->nodesize) {
468eca0f6f6SQu Wenruo 		struct extent_buffer *eb;
469eca0f6f6SQu Wenruo 		bool uptodate;
470eca0f6f6SQu Wenruo 
471eca0f6f6SQu Wenruo 		eb = find_extent_buffer(fs_info, cur);
472eca0f6f6SQu Wenruo 		uptodate = btrfs_subpage_test_uptodate(fs_info, page, cur,
473eca0f6f6SQu Wenruo 						       fs_info->nodesize);
474eca0f6f6SQu Wenruo 
475eca0f6f6SQu Wenruo 		/* A dirty eb shouldn't disappear from buffer_radix */
476eca0f6f6SQu Wenruo 		if (WARN_ON(!eb))
477eca0f6f6SQu Wenruo 			return -EUCLEAN;
478eca0f6f6SQu Wenruo 
479eca0f6f6SQu Wenruo 		if (WARN_ON(cur != btrfs_header_bytenr(eb))) {
480eca0f6f6SQu Wenruo 			free_extent_buffer(eb);
481eca0f6f6SQu Wenruo 			return -EUCLEAN;
482eca0f6f6SQu Wenruo 		}
483eca0f6f6SQu Wenruo 		if (WARN_ON(!uptodate)) {
484eca0f6f6SQu Wenruo 			free_extent_buffer(eb);
485eca0f6f6SQu Wenruo 			return -EUCLEAN;
486eca0f6f6SQu Wenruo 		}
487eca0f6f6SQu Wenruo 
488eca0f6f6SQu Wenruo 		ret = csum_one_extent_buffer(eb);
489eca0f6f6SQu Wenruo 		free_extent_buffer(eb);
490eca0f6f6SQu Wenruo 		if (ret < 0)
491eca0f6f6SQu Wenruo 			return ret;
492eca0f6f6SQu Wenruo 	}
493eca0f6f6SQu Wenruo 	return ret;
494eca0f6f6SQu Wenruo }
495eca0f6f6SQu Wenruo 
496d352ac68SChris Mason /*
497ac303b69SQu Wenruo  * Checksum a dirty tree block before IO.  This has extra checks to make sure
498ac303b69SQu Wenruo  * we only fill in the checksum field in the first page of a multi-page block.
499ac303b69SQu Wenruo  * For subpage extent buffers we need bvec to also read the offset in the page.
500d352ac68SChris Mason  */
501ac303b69SQu Wenruo static int csum_dirty_buffer(struct btrfs_fs_info *fs_info, struct bio_vec *bvec)
50219c00ddcSChris Mason {
503ac303b69SQu Wenruo 	struct page *page = bvec->bv_page;
5044eee4fa4SMiao Xie 	u64 start = page_offset(page);
50519c00ddcSChris Mason 	u64 found_start;
50619c00ddcSChris Mason 	struct extent_buffer *eb;
507eca0f6f6SQu Wenruo 
508eca0f6f6SQu Wenruo 	if (fs_info->sectorsize < PAGE_SIZE)
509eca0f6f6SQu Wenruo 		return csum_dirty_subpage_buffers(fs_info, bvec);
510f188591eSChris Mason 
5114f2de97aSJosef Bacik 	eb = (struct extent_buffer *)page->private;
5124f2de97aSJosef Bacik 	if (page != eb->pages[0])
5134f2de97aSJosef Bacik 		return 0;
5140f805531SAlex Lyakas 
51519c00ddcSChris Mason 	found_start = btrfs_header_bytenr(eb);
516d3575156SNaohiro Aota 
517d3575156SNaohiro Aota 	if (test_bit(EXTENT_BUFFER_NO_CHECK, &eb->bflags)) {
518d3575156SNaohiro Aota 		WARN_ON(found_start != 0);
519d3575156SNaohiro Aota 		return 0;
520d3575156SNaohiro Aota 	}
521d3575156SNaohiro Aota 
5220f805531SAlex Lyakas 	/*
5230f805531SAlex Lyakas 	 * Please do not consolidate these warnings into a single if.
5240f805531SAlex Lyakas 	 * It is useful to know what went wrong.
5250f805531SAlex Lyakas 	 */
5260f805531SAlex Lyakas 	if (WARN_ON(found_start != start))
5270f805531SAlex Lyakas 		return -EUCLEAN;
5280f805531SAlex Lyakas 	if (WARN_ON(!PageUptodate(page)))
5290f805531SAlex Lyakas 		return -EUCLEAN;
5300f805531SAlex Lyakas 
531eca0f6f6SQu Wenruo 	return csum_one_extent_buffer(eb);
53219c00ddcSChris Mason }
53319c00ddcSChris Mason 
534b0c9b3b0SDavid Sterba static int check_tree_block_fsid(struct extent_buffer *eb)
5352b82032cSYan Zheng {
536b0c9b3b0SDavid Sterba 	struct btrfs_fs_info *fs_info = eb->fs_info;
537944d3f9fSNikolay Borisov 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices, *seed_devs;
53844880fdcSAnand Jain 	u8 fsid[BTRFS_FSID_SIZE];
539944d3f9fSNikolay Borisov 	u8 *metadata_uuid;
5402b82032cSYan Zheng 
5419a8658e3SDavid Sterba 	read_extent_buffer(eb, fsid, offsetof(struct btrfs_header, fsid),
5429a8658e3SDavid Sterba 			   BTRFS_FSID_SIZE);
5437239ff4bSNikolay Borisov 	/*
544944d3f9fSNikolay Borisov 	 * Checking the incompat flag is only valid for the current fs. For
545944d3f9fSNikolay Borisov 	 * seed devices it's forbidden to have their uuid changed so reading
546944d3f9fSNikolay Borisov 	 * ->fsid in this case is fine
5477239ff4bSNikolay Borisov 	 */
548944d3f9fSNikolay Borisov 	if (btrfs_fs_incompat(fs_info, METADATA_UUID))
5497239ff4bSNikolay Borisov 		metadata_uuid = fs_devices->metadata_uuid;
5507239ff4bSNikolay Borisov 	else
5517239ff4bSNikolay Borisov 		metadata_uuid = fs_devices->fsid;
5527239ff4bSNikolay Borisov 
553944d3f9fSNikolay Borisov 	if (!memcmp(fsid, metadata_uuid, BTRFS_FSID_SIZE))
554944d3f9fSNikolay Borisov 		return 0;
555944d3f9fSNikolay Borisov 
556944d3f9fSNikolay Borisov 	list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list)
557944d3f9fSNikolay Borisov 		if (!memcmp(fsid, seed_devs->fsid, BTRFS_FSID_SIZE))
558944d3f9fSNikolay Borisov 			return 0;
559944d3f9fSNikolay Borisov 
560944d3f9fSNikolay Borisov 	return 1;
5612b82032cSYan Zheng }
5622b82032cSYan Zheng 
56377bf40a2SQu Wenruo /* Do basic extent buffer checks at read time */
56477bf40a2SQu Wenruo static int validate_extent_buffer(struct extent_buffer *eb)
565ce9adaa5SChris Mason {
56677bf40a2SQu Wenruo 	struct btrfs_fs_info *fs_info = eb->fs_info;
567ce9adaa5SChris Mason 	u64 found_start;
56877bf40a2SQu Wenruo 	const u32 csum_size = fs_info->csum_size;
56977bf40a2SQu Wenruo 	u8 found_level;
5702996e1f8SJohannes Thumshirn 	u8 result[BTRFS_CSUM_SIZE];
571dfd29eedSDavid Sterba 	const u8 *header_csum;
57277bf40a2SQu Wenruo 	int ret = 0;
573ea466794SJosef Bacik 
574ce9adaa5SChris Mason 	found_start = btrfs_header_bytenr(eb);
575727011e0SChris Mason 	if (found_start != eb->start) {
576893bf4b1SSu Yue 		btrfs_err_rl(fs_info, "bad tree block start, want %llu have %llu",
577893bf4b1SSu Yue 			     eb->start, found_start);
578f188591eSChris Mason 		ret = -EIO;
57977bf40a2SQu Wenruo 		goto out;
580ce9adaa5SChris Mason 	}
581b0c9b3b0SDavid Sterba 	if (check_tree_block_fsid(eb)) {
58202873e43SZhao Lei 		btrfs_err_rl(fs_info, "bad fsid on block %llu",
58394647322SDavid Sterba 			     eb->start);
5841259ab75SChris Mason 		ret = -EIO;
58577bf40a2SQu Wenruo 		goto out;
5861259ab75SChris Mason 	}
587ce9adaa5SChris Mason 	found_level = btrfs_header_level(eb);
5881c24c3ceSJosef Bacik 	if (found_level >= BTRFS_MAX_LEVEL) {
589893bf4b1SSu Yue 		btrfs_err(fs_info, "bad tree block level %d on %llu",
590893bf4b1SSu Yue 			  (int)btrfs_header_level(eb), eb->start);
5911c24c3ceSJosef Bacik 		ret = -EIO;
59277bf40a2SQu Wenruo 		goto out;
5931c24c3ceSJosef Bacik 	}
594ce9adaa5SChris Mason 
595c67b3892SDavid Sterba 	csum_tree_block(eb, result);
596dfd29eedSDavid Sterba 	header_csum = page_address(eb->pages[0]) +
597dfd29eedSDavid Sterba 		get_eb_offset_in_page(eb, offsetof(struct btrfs_header, csum));
598a826d6dcSJosef Bacik 
599dfd29eedSDavid Sterba 	if (memcmp(result, header_csum, csum_size) != 0) {
6002996e1f8SJohannes Thumshirn 		btrfs_warn_rl(fs_info,
601ff14aa79SDavid Sterba 	"checksum verify failed on %llu wanted " CSUM_FMT " found " CSUM_FMT " level %d",
602ff14aa79SDavid Sterba 			      eb->start,
603dfd29eedSDavid Sterba 			      CSUM_FMT_VALUE(csum_size, header_csum),
60435be8851SJohannes Thumshirn 			      CSUM_FMT_VALUE(csum_size, result),
60535be8851SJohannes Thumshirn 			      btrfs_header_level(eb));
6062996e1f8SJohannes Thumshirn 		ret = -EUCLEAN;
60777bf40a2SQu Wenruo 		goto out;
6082996e1f8SJohannes Thumshirn 	}
6092996e1f8SJohannes Thumshirn 
610a826d6dcSJosef Bacik 	/*
611a826d6dcSJosef Bacik 	 * If this is a leaf block and it is corrupt, set the corrupt bit so
612a826d6dcSJosef Bacik 	 * that we don't try and read the other copies of this block, just
613a826d6dcSJosef Bacik 	 * return -EIO.
614a826d6dcSJosef Bacik 	 */
6151c4360eeSDavid Sterba 	if (found_level == 0 && btrfs_check_leaf_full(eb)) {
616a826d6dcSJosef Bacik 		set_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags);
617a826d6dcSJosef Bacik 		ret = -EIO;
618a826d6dcSJosef Bacik 	}
619ce9adaa5SChris Mason 
620813fd1dcSDavid Sterba 	if (found_level > 0 && btrfs_check_node(eb))
621053ab70fSLiu Bo 		ret = -EIO;
622053ab70fSLiu Bo 
6230b32f4bbSJosef Bacik 	if (!ret)
6240b32f4bbSJosef Bacik 		set_extent_buffer_uptodate(eb);
62575391f0dSQu Wenruo 	else
62675391f0dSQu Wenruo 		btrfs_err(fs_info,
62775391f0dSQu Wenruo 			  "block=%llu read time tree block corruption detected",
62875391f0dSQu Wenruo 			  eb->start);
62977bf40a2SQu Wenruo out:
63077bf40a2SQu Wenruo 	return ret;
63177bf40a2SQu Wenruo }
63277bf40a2SQu Wenruo 
633371cdc07SQu Wenruo static int validate_subpage_buffer(struct page *page, u64 start, u64 end,
634371cdc07SQu Wenruo 				   int mirror)
635371cdc07SQu Wenruo {
636371cdc07SQu Wenruo 	struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
637371cdc07SQu Wenruo 	struct extent_buffer *eb;
638371cdc07SQu Wenruo 	bool reads_done;
639371cdc07SQu Wenruo 	int ret = 0;
640371cdc07SQu Wenruo 
641371cdc07SQu Wenruo 	/*
642371cdc07SQu Wenruo 	 * We don't allow bio merge for subpage metadata read, so we should
643371cdc07SQu Wenruo 	 * only get one eb for each endio hook.
644371cdc07SQu Wenruo 	 */
645371cdc07SQu Wenruo 	ASSERT(end == start + fs_info->nodesize - 1);
646371cdc07SQu Wenruo 	ASSERT(PagePrivate(page));
647371cdc07SQu Wenruo 
648371cdc07SQu Wenruo 	eb = find_extent_buffer(fs_info, start);
649371cdc07SQu Wenruo 	/*
650371cdc07SQu Wenruo 	 * When we are reading one tree block, eb must have been inserted into
651371cdc07SQu Wenruo 	 * the radix tree. If not, something is wrong.
652371cdc07SQu Wenruo 	 */
653371cdc07SQu Wenruo 	ASSERT(eb);
654371cdc07SQu Wenruo 
655371cdc07SQu Wenruo 	reads_done = atomic_dec_and_test(&eb->io_pages);
656371cdc07SQu Wenruo 	/* Subpage read must finish in page read */
657371cdc07SQu Wenruo 	ASSERT(reads_done);
658371cdc07SQu Wenruo 
659371cdc07SQu Wenruo 	eb->read_mirror = mirror;
660371cdc07SQu Wenruo 	if (test_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags)) {
661371cdc07SQu Wenruo 		ret = -EIO;
662371cdc07SQu Wenruo 		goto err;
663371cdc07SQu Wenruo 	}
664371cdc07SQu Wenruo 	ret = validate_extent_buffer(eb);
665371cdc07SQu Wenruo 	if (ret < 0)
666371cdc07SQu Wenruo 		goto err;
667371cdc07SQu Wenruo 
668371cdc07SQu Wenruo 	if (test_and_clear_bit(EXTENT_BUFFER_READAHEAD, &eb->bflags))
669371cdc07SQu Wenruo 		btree_readahead_hook(eb, ret);
670371cdc07SQu Wenruo 
671371cdc07SQu Wenruo 	set_extent_buffer_uptodate(eb);
672371cdc07SQu Wenruo 
673371cdc07SQu Wenruo 	free_extent_buffer(eb);
674371cdc07SQu Wenruo 	return ret;
675371cdc07SQu Wenruo err:
676371cdc07SQu Wenruo 	/*
677371cdc07SQu Wenruo 	 * end_bio_extent_readpage decrements io_pages in case of error,
678371cdc07SQu Wenruo 	 * make sure it has something to decrement.
679371cdc07SQu Wenruo 	 */
680371cdc07SQu Wenruo 	atomic_inc(&eb->io_pages);
681371cdc07SQu Wenruo 	clear_extent_buffer_uptodate(eb);
682371cdc07SQu Wenruo 	free_extent_buffer(eb);
683371cdc07SQu Wenruo 	return ret;
684371cdc07SQu Wenruo }
685371cdc07SQu Wenruo 
686c3a3b19bSQu Wenruo int btrfs_validate_metadata_buffer(struct btrfs_bio *bbio,
68777bf40a2SQu Wenruo 				   struct page *page, u64 start, u64 end,
68877bf40a2SQu Wenruo 				   int mirror)
68977bf40a2SQu Wenruo {
69077bf40a2SQu Wenruo 	struct extent_buffer *eb;
69177bf40a2SQu Wenruo 	int ret = 0;
69277bf40a2SQu Wenruo 	int reads_done;
69377bf40a2SQu Wenruo 
69477bf40a2SQu Wenruo 	ASSERT(page->private);
695371cdc07SQu Wenruo 
696371cdc07SQu Wenruo 	if (btrfs_sb(page->mapping->host->i_sb)->sectorsize < PAGE_SIZE)
697371cdc07SQu Wenruo 		return validate_subpage_buffer(page, start, end, mirror);
698371cdc07SQu Wenruo 
69977bf40a2SQu Wenruo 	eb = (struct extent_buffer *)page->private;
70077bf40a2SQu Wenruo 
70177bf40a2SQu Wenruo 	/*
70277bf40a2SQu Wenruo 	 * The pending IO might have been the only thing that kept this buffer
70377bf40a2SQu Wenruo 	 * in memory.  Make sure we have a ref for all this other checks
70477bf40a2SQu Wenruo 	 */
70577bf40a2SQu Wenruo 	atomic_inc(&eb->refs);
70677bf40a2SQu Wenruo 
70777bf40a2SQu Wenruo 	reads_done = atomic_dec_and_test(&eb->io_pages);
70877bf40a2SQu Wenruo 	if (!reads_done)
70977bf40a2SQu Wenruo 		goto err;
71077bf40a2SQu Wenruo 
71177bf40a2SQu Wenruo 	eb->read_mirror = mirror;
71277bf40a2SQu Wenruo 	if (test_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags)) {
71377bf40a2SQu Wenruo 		ret = -EIO;
71477bf40a2SQu Wenruo 		goto err;
71577bf40a2SQu Wenruo 	}
71677bf40a2SQu Wenruo 	ret = validate_extent_buffer(eb);
717ce9adaa5SChris Mason err:
71879fb65a1SJosef Bacik 	if (reads_done &&
71979fb65a1SJosef Bacik 	    test_and_clear_bit(EXTENT_BUFFER_READAHEAD, &eb->bflags))
720d48d71aaSDavid Sterba 		btree_readahead_hook(eb, ret);
7214bb31e92SArne Jansen 
72253b381b3SDavid Woodhouse 	if (ret) {
72353b381b3SDavid Woodhouse 		/*
72453b381b3SDavid Woodhouse 		 * our io error hook is going to dec the io pages
72553b381b3SDavid Woodhouse 		 * again, we have to make sure it has something
72653b381b3SDavid Woodhouse 		 * to decrement
72753b381b3SDavid Woodhouse 		 */
72853b381b3SDavid Woodhouse 		atomic_inc(&eb->io_pages);
7290b32f4bbSJosef Bacik 		clear_extent_buffer_uptodate(eb);
73053b381b3SDavid Woodhouse 	}
7310b32f4bbSJosef Bacik 	free_extent_buffer(eb);
73277bf40a2SQu Wenruo 
733f188591eSChris Mason 	return ret;
734ce9adaa5SChris Mason }
735ce9adaa5SChris Mason 
7364246a0b6SChristoph Hellwig static void end_workqueue_bio(struct bio *bio)
737ce9adaa5SChris Mason {
73897eb6b69SDavid Sterba 	struct btrfs_end_io_wq *end_io_wq = bio->bi_private;
739ce9adaa5SChris Mason 	struct btrfs_fs_info *fs_info;
7409e0af237SLiu Bo 	struct btrfs_workqueue *wq;
741ce9adaa5SChris Mason 
742ce9adaa5SChris Mason 	fs_info = end_io_wq->info;
7434e4cbee9SChristoph Hellwig 	end_io_wq->status = bio->bi_status;
744d20f7043SChris Mason 
745cfe94440SNaohiro Aota 	if (btrfs_op(bio) == BTRFS_MAP_WRITE) {
746a0cac0ecSOmar Sandoval 		if (end_io_wq->metadata == BTRFS_WQ_ENDIO_METADATA)
7479e0af237SLiu Bo 			wq = fs_info->endio_meta_write_workers;
748a0cac0ecSOmar Sandoval 		else if (end_io_wq->metadata == BTRFS_WQ_ENDIO_FREE_SPACE)
7499e0af237SLiu Bo 			wq = fs_info->endio_freespace_worker;
750a0cac0ecSOmar Sandoval 		else if (end_io_wq->metadata == BTRFS_WQ_ENDIO_RAID56)
7519e0af237SLiu Bo 			wq = fs_info->endio_raid56_workers;
752a0cac0ecSOmar Sandoval 		else
7539e0af237SLiu Bo 			wq = fs_info->endio_write_workers;
7549e0af237SLiu Bo 	} else {
7555c047a69SOmar Sandoval 		if (end_io_wq->metadata == BTRFS_WQ_ENDIO_RAID56)
7569e0af237SLiu Bo 			wq = fs_info->endio_raid56_workers;
757a0cac0ecSOmar Sandoval 		else if (end_io_wq->metadata)
7589e0af237SLiu Bo 			wq = fs_info->endio_meta_workers;
759a0cac0ecSOmar Sandoval 		else
7609e0af237SLiu Bo 			wq = fs_info->endio_workers;
7619e0af237SLiu Bo 	}
7629e0af237SLiu Bo 
763a0cac0ecSOmar Sandoval 	btrfs_init_work(&end_io_wq->work, end_workqueue_fn, NULL, NULL);
7649e0af237SLiu Bo 	btrfs_queue_work(wq, &end_io_wq->work);
765ce9adaa5SChris Mason }
766ce9adaa5SChris Mason 
7674e4cbee9SChristoph Hellwig blk_status_t btrfs_bio_wq_end_io(struct btrfs_fs_info *info, struct bio *bio,
768bfebd8b5SDavid Sterba 			enum btrfs_wq_endio_type metadata)
7690b86a832SChris Mason {
77097eb6b69SDavid Sterba 	struct btrfs_end_io_wq *end_io_wq;
7718b110e39SMiao Xie 
77297eb6b69SDavid Sterba 	end_io_wq = kmem_cache_alloc(btrfs_end_io_wq_cache, GFP_NOFS);
773ce9adaa5SChris Mason 	if (!end_io_wq)
7744e4cbee9SChristoph Hellwig 		return BLK_STS_RESOURCE;
775ce9adaa5SChris Mason 
776ce9adaa5SChris Mason 	end_io_wq->private = bio->bi_private;
777ce9adaa5SChris Mason 	end_io_wq->end_io = bio->bi_end_io;
77822c59948SChris Mason 	end_io_wq->info = info;
7794e4cbee9SChristoph Hellwig 	end_io_wq->status = 0;
780ce9adaa5SChris Mason 	end_io_wq->bio = bio;
78122c59948SChris Mason 	end_io_wq->metadata = metadata;
782ce9adaa5SChris Mason 
783ce9adaa5SChris Mason 	bio->bi_private = end_io_wq;
784ce9adaa5SChris Mason 	bio->bi_end_io = end_workqueue_bio;
78522c59948SChris Mason 	return 0;
78622c59948SChris Mason }
78722c59948SChris Mason 
7884a69a410SChris Mason static void run_one_async_start(struct btrfs_work *work)
7894a69a410SChris Mason {
7904a69a410SChris Mason 	struct async_submit_bio *async;
7914e4cbee9SChristoph Hellwig 	blk_status_t ret;
7924a69a410SChris Mason 
7934a69a410SChris Mason 	async = container_of(work, struct  async_submit_bio, work);
7941941b64bSQu Wenruo 	ret = async->submit_bio_start(async->inode, async->bio,
7951941b64bSQu Wenruo 				      async->dio_file_offset);
79679787eaaSJeff Mahoney 	if (ret)
7974e4cbee9SChristoph Hellwig 		async->status = ret;
7984a69a410SChris Mason }
7994a69a410SChris Mason 
80006ea01b1SDavid Sterba /*
80106ea01b1SDavid Sterba  * In order to insert checksums into the metadata in large chunks, we wait
80206ea01b1SDavid Sterba  * until bio submission time.   All the pages in the bio are checksummed and
80306ea01b1SDavid Sterba  * sums are attached onto the ordered extent record.
80406ea01b1SDavid Sterba  *
80506ea01b1SDavid Sterba  * At IO completion time the csums attached on the ordered extent record are
80606ea01b1SDavid Sterba  * inserted into the tree.
80706ea01b1SDavid Sterba  */
8084a69a410SChris Mason static void run_one_async_done(struct btrfs_work *work)
8098b712842SChris Mason {
8108b712842SChris Mason 	struct async_submit_bio *async;
81106ea01b1SDavid Sterba 	struct inode *inode;
81206ea01b1SDavid Sterba 	blk_status_t ret;
8138b712842SChris Mason 
8148b712842SChris Mason 	async = container_of(work, struct  async_submit_bio, work);
8158896a08dSQu Wenruo 	inode = async->inode;
8164854ddd0SChris Mason 
817bb7ab3b9SAdam Buchbinder 	/* If an error occurred we just want to clean up the bio and move on */
8184e4cbee9SChristoph Hellwig 	if (async->status) {
8194e4cbee9SChristoph Hellwig 		async->bio->bi_status = async->status;
8204246a0b6SChristoph Hellwig 		bio_endio(async->bio);
82179787eaaSJeff Mahoney 		return;
82279787eaaSJeff Mahoney 	}
82379787eaaSJeff Mahoney 
824ec39f769SChris Mason 	/*
825ec39f769SChris Mason 	 * All of the bios that pass through here are from async helpers.
826ec39f769SChris Mason 	 * Use REQ_CGROUP_PUNT to issue them from the owning cgroup's context.
827ec39f769SChris Mason 	 * This changes nothing when cgroups aren't in use.
828ec39f769SChris Mason 	 */
829ec39f769SChris Mason 	async->bio->bi_opf |= REQ_CGROUP_PUNT;
83008635baeSChris Mason 	ret = btrfs_map_bio(btrfs_sb(inode->i_sb), async->bio, async->mirror_num);
83106ea01b1SDavid Sterba 	if (ret) {
83206ea01b1SDavid Sterba 		async->bio->bi_status = ret;
83306ea01b1SDavid Sterba 		bio_endio(async->bio);
83406ea01b1SDavid Sterba 	}
8354a69a410SChris Mason }
8364a69a410SChris Mason 
8374a69a410SChris Mason static void run_one_async_free(struct btrfs_work *work)
8384a69a410SChris Mason {
8394a69a410SChris Mason 	struct async_submit_bio *async;
8404a69a410SChris Mason 
8414a69a410SChris Mason 	async = container_of(work, struct  async_submit_bio, work);
8428b712842SChris Mason 	kfree(async);
8438b712842SChris Mason }
8448b712842SChris Mason 
8458896a08dSQu Wenruo blk_status_t btrfs_wq_submit_bio(struct inode *inode, struct bio *bio,
846c6100a4bSJosef Bacik 				 int mirror_num, unsigned long bio_flags,
8471941b64bSQu Wenruo 				 u64 dio_file_offset,
848e288c080SDavid Sterba 				 extent_submit_bio_start_t *submit_bio_start)
84944b8bd7eSChris Mason {
8508896a08dSQu Wenruo 	struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
85144b8bd7eSChris Mason 	struct async_submit_bio *async;
85244b8bd7eSChris Mason 
85344b8bd7eSChris Mason 	async = kmalloc(sizeof(*async), GFP_NOFS);
85444b8bd7eSChris Mason 	if (!async)
8554e4cbee9SChristoph Hellwig 		return BLK_STS_RESOURCE;
85644b8bd7eSChris Mason 
8578896a08dSQu Wenruo 	async->inode = inode;
85844b8bd7eSChris Mason 	async->bio = bio;
85944b8bd7eSChris Mason 	async->mirror_num = mirror_num;
8604a69a410SChris Mason 	async->submit_bio_start = submit_bio_start;
8614a69a410SChris Mason 
862a0cac0ecSOmar Sandoval 	btrfs_init_work(&async->work, run_one_async_start, run_one_async_done,
863a0cac0ecSOmar Sandoval 			run_one_async_free);
8644a69a410SChris Mason 
8651941b64bSQu Wenruo 	async->dio_file_offset = dio_file_offset;
8668c8bee1dSChris Mason 
8674e4cbee9SChristoph Hellwig 	async->status = 0;
86879787eaaSJeff Mahoney 
86967f055c7SChristoph Hellwig 	if (op_is_sync(bio->bi_opf))
8705cdc7ad3SQu Wenruo 		btrfs_set_work_high_priority(&async->work);
871d313d7a3SChris Mason 
8725cdc7ad3SQu Wenruo 	btrfs_queue_work(fs_info->workers, &async->work);
87344b8bd7eSChris Mason 	return 0;
87444b8bd7eSChris Mason }
87544b8bd7eSChris Mason 
8764e4cbee9SChristoph Hellwig static blk_status_t btree_csum_one_bio(struct bio *bio)
877ce3ed71aSChris Mason {
8782c30c71bSKent Overstreet 	struct bio_vec *bvec;
879ce3ed71aSChris Mason 	struct btrfs_root *root;
8802b070cfeSChristoph Hellwig 	int ret = 0;
8816dc4f100SMing Lei 	struct bvec_iter_all iter_all;
882ce3ed71aSChris Mason 
883c09abff8SDavid Sterba 	ASSERT(!bio_flagged(bio, BIO_CLONED));
8842b070cfeSChristoph Hellwig 	bio_for_each_segment_all(bvec, bio, iter_all) {
885ce3ed71aSChris Mason 		root = BTRFS_I(bvec->bv_page->mapping->host)->root;
886ac303b69SQu Wenruo 		ret = csum_dirty_buffer(root->fs_info, bvec);
88779787eaaSJeff Mahoney 		if (ret)
88879787eaaSJeff Mahoney 			break;
889ce3ed71aSChris Mason 	}
8902c30c71bSKent Overstreet 
8914e4cbee9SChristoph Hellwig 	return errno_to_blk_status(ret);
892ce3ed71aSChris Mason }
893ce3ed71aSChris Mason 
8948896a08dSQu Wenruo static blk_status_t btree_submit_bio_start(struct inode *inode, struct bio *bio,
8951941b64bSQu Wenruo 					   u64 dio_file_offset)
89622c59948SChris Mason {
8978b712842SChris Mason 	/*
8988b712842SChris Mason 	 * when we're called for a write, we're already in the async
8995443be45SChris Mason 	 * submission context.  Just jump into btrfs_map_bio
9008b712842SChris Mason 	 */
90179787eaaSJeff Mahoney 	return btree_csum_one_bio(bio);
90222c59948SChris Mason }
90322c59948SChris Mason 
904f4dcfb30SJohannes Thumshirn static bool should_async_write(struct btrfs_fs_info *fs_info,
9059b4e675aSDavid Sterba 			     struct btrfs_inode *bi)
906de0022b9SJosef Bacik {
9074eef29efSNaohiro Aota 	if (btrfs_is_zoned(fs_info))
908f4dcfb30SJohannes Thumshirn 		return false;
9096300463bSLiu Bo 	if (atomic_read(&bi->sync_writers))
910f4dcfb30SJohannes Thumshirn 		return false;
9119b4e675aSDavid Sterba 	if (test_bit(BTRFS_FS_CSUM_IMPL_FAST, &fs_info->flags))
912f4dcfb30SJohannes Thumshirn 		return false;
913f4dcfb30SJohannes Thumshirn 	return true;
914de0022b9SJosef Bacik }
915de0022b9SJosef Bacik 
9161b36294aSNikolay Borisov blk_status_t btrfs_submit_metadata_bio(struct inode *inode, struct bio *bio,
9171b36294aSNikolay Borisov 				       int mirror_num, unsigned long bio_flags)
91844b8bd7eSChris Mason {
9190b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9204e4cbee9SChristoph Hellwig 	blk_status_t ret;
921cad321adSChris Mason 
922cfe94440SNaohiro Aota 	if (btrfs_op(bio) != BTRFS_MAP_WRITE) {
923cad321adSChris Mason 		/*
924cad321adSChris Mason 		 * called for a read, do the setup so that checksum validation
925cad321adSChris Mason 		 * can happen in the async kernel threads
926cad321adSChris Mason 		 */
9270b246afaSJeff Mahoney 		ret = btrfs_bio_wq_end_io(fs_info, bio,
9280b246afaSJeff Mahoney 					  BTRFS_WQ_ENDIO_METADATA);
9291d4284bdSChris Mason 		if (ret)
93061891923SStefan Behrens 			goto out_w_error;
93108635baeSChris Mason 		ret = btrfs_map_bio(fs_info, bio, mirror_num);
932f4dcfb30SJohannes Thumshirn 	} else if (!should_async_write(fs_info, BTRFS_I(inode))) {
933de0022b9SJosef Bacik 		ret = btree_csum_one_bio(bio);
934de0022b9SJosef Bacik 		if (ret)
93561891923SStefan Behrens 			goto out_w_error;
93608635baeSChris Mason 		ret = btrfs_map_bio(fs_info, bio, mirror_num);
93761891923SStefan Behrens 	} else {
938cad321adSChris Mason 		/*
93961891923SStefan Behrens 		 * kthread helpers are used to submit writes so that
94061891923SStefan Behrens 		 * checksumming can happen in parallel across all CPUs
941cad321adSChris Mason 		 */
9428896a08dSQu Wenruo 		ret = btrfs_wq_submit_bio(inode, bio, mirror_num, 0,
9438896a08dSQu Wenruo 					  0, btree_submit_bio_start);
94444b8bd7eSChris Mason 	}
94544b8bd7eSChris Mason 
9464246a0b6SChristoph Hellwig 	if (ret)
9474246a0b6SChristoph Hellwig 		goto out_w_error;
9484246a0b6SChristoph Hellwig 	return 0;
9494246a0b6SChristoph Hellwig 
95061891923SStefan Behrens out_w_error:
9514e4cbee9SChristoph Hellwig 	bio->bi_status = ret;
9524246a0b6SChristoph Hellwig 	bio_endio(bio);
95361891923SStefan Behrens 	return ret;
95461891923SStefan Behrens }
95561891923SStefan Behrens 
9563dd1462eSJan Beulich #ifdef CONFIG_MIGRATION
957784b4e29SChris Mason static int btree_migratepage(struct address_space *mapping,
958a6bc32b8SMel Gorman 			struct page *newpage, struct page *page,
959a6bc32b8SMel Gorman 			enum migrate_mode mode)
960784b4e29SChris Mason {
961784b4e29SChris Mason 	/*
962784b4e29SChris Mason 	 * we can't safely write a btree page from here,
963784b4e29SChris Mason 	 * we haven't done the locking hook
964784b4e29SChris Mason 	 */
965784b4e29SChris Mason 	if (PageDirty(page))
966784b4e29SChris Mason 		return -EAGAIN;
967784b4e29SChris Mason 	/*
968784b4e29SChris Mason 	 * Buffers may be managed in a filesystem specific way.
969784b4e29SChris Mason 	 * We must have no buffers or drop them.
970784b4e29SChris Mason 	 */
971784b4e29SChris Mason 	if (page_has_private(page) &&
972784b4e29SChris Mason 	    !try_to_release_page(page, GFP_KERNEL))
973784b4e29SChris Mason 		return -EAGAIN;
974a6bc32b8SMel Gorman 	return migrate_page(mapping, newpage, page, mode);
975784b4e29SChris Mason }
9763dd1462eSJan Beulich #endif
977784b4e29SChris Mason 
9780da5468fSChris Mason 
9790da5468fSChris Mason static int btree_writepages(struct address_space *mapping,
9800da5468fSChris Mason 			    struct writeback_control *wbc)
9810da5468fSChris Mason {
982e2d84521SMiao Xie 	struct btrfs_fs_info *fs_info;
983e2d84521SMiao Xie 	int ret;
984e2d84521SMiao Xie 
985d8d5f3e1SChris Mason 	if (wbc->sync_mode == WB_SYNC_NONE) {
986448d640bSChris Mason 
987448d640bSChris Mason 		if (wbc->for_kupdate)
988448d640bSChris Mason 			return 0;
989448d640bSChris Mason 
990e2d84521SMiao Xie 		fs_info = BTRFS_I(mapping->host)->root->fs_info;
991b9473439SChris Mason 		/* this is a bit racy, but that's ok */
992d814a491SEthan Lien 		ret = __percpu_counter_compare(&fs_info->dirty_metadata_bytes,
993d814a491SEthan Lien 					     BTRFS_DIRTY_METADATA_THRESH,
994d814a491SEthan Lien 					     fs_info->dirty_metadata_batch);
995e2d84521SMiao Xie 		if (ret < 0)
996793955bcSChris Mason 			return 0;
997793955bcSChris Mason 	}
9980b32f4bbSJosef Bacik 	return btree_write_cache_pages(mapping, wbc);
9990da5468fSChris Mason }
10000da5468fSChris Mason 
100170dec807SChris Mason static int btree_releasepage(struct page *page, gfp_t gfp_flags)
10025f39d397SChris Mason {
100398509cfcSChris Mason 	if (PageWriteback(page) || PageDirty(page))
100498509cfcSChris Mason 		return 0;
10050c4e538bSDavid Sterba 
1006f7a52a40SDavid Sterba 	return try_release_extent_buffer(page);
1007d98237b3SChris Mason }
1008d98237b3SChris Mason 
1009d47992f8SLukas Czerner static void btree_invalidatepage(struct page *page, unsigned int offset,
1010d47992f8SLukas Czerner 				 unsigned int length)
1011d98237b3SChris Mason {
1012d1310b2eSChris Mason 	struct extent_io_tree *tree;
1013d1310b2eSChris Mason 	tree = &BTRFS_I(page->mapping->host)->io_tree;
10145f39d397SChris Mason 	extent_invalidatepage(tree, page, offset);
10155f39d397SChris Mason 	btree_releasepage(page, GFP_NOFS);
10169ad6b7bcSChris Mason 	if (PagePrivate(page)) {
1017efe120a0SFrank Holton 		btrfs_warn(BTRFS_I(page->mapping->host)->root->fs_info,
1018efe120a0SFrank Holton 			   "page private not zero on page %llu",
1019efe120a0SFrank Holton 			   (unsigned long long)page_offset(page));
1020d1b89bc0SGuoqing Jiang 		detach_page_private(page);
10219ad6b7bcSChris Mason 	}
1022d98237b3SChris Mason }
1023d98237b3SChris Mason 
10240b32f4bbSJosef Bacik static int btree_set_page_dirty(struct page *page)
10250b32f4bbSJosef Bacik {
1026bb146eb2SJosef Bacik #ifdef DEBUG
1027139e8cd3SQu Wenruo 	struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
1028139e8cd3SQu Wenruo 	struct btrfs_subpage *subpage;
10290b32f4bbSJosef Bacik 	struct extent_buffer *eb;
1030139e8cd3SQu Wenruo 	int cur_bit = 0;
1031139e8cd3SQu Wenruo 	u64 page_start = page_offset(page);
10320b32f4bbSJosef Bacik 
1033139e8cd3SQu Wenruo 	if (fs_info->sectorsize == PAGE_SIZE) {
10340b32f4bbSJosef Bacik 		BUG_ON(!PagePrivate(page));
10350b32f4bbSJosef Bacik 		eb = (struct extent_buffer *)page->private;
10360b32f4bbSJosef Bacik 		BUG_ON(!eb);
10370b32f4bbSJosef Bacik 		BUG_ON(!test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
10380b32f4bbSJosef Bacik 		BUG_ON(!atomic_read(&eb->refs));
103949d0c642SFilipe Manana 		btrfs_assert_tree_write_locked(eb);
1040139e8cd3SQu Wenruo 		return __set_page_dirty_nobuffers(page);
1041139e8cd3SQu Wenruo 	}
1042139e8cd3SQu Wenruo 	ASSERT(PagePrivate(page) && page->private);
1043139e8cd3SQu Wenruo 	subpage = (struct btrfs_subpage *)page->private;
1044139e8cd3SQu Wenruo 
1045139e8cd3SQu Wenruo 	ASSERT(subpage->dirty_bitmap);
1046139e8cd3SQu Wenruo 	while (cur_bit < BTRFS_SUBPAGE_BITMAP_SIZE) {
1047139e8cd3SQu Wenruo 		unsigned long flags;
1048139e8cd3SQu Wenruo 		u64 cur;
1049139e8cd3SQu Wenruo 		u16 tmp = (1 << cur_bit);
1050139e8cd3SQu Wenruo 
1051139e8cd3SQu Wenruo 		spin_lock_irqsave(&subpage->lock, flags);
1052139e8cd3SQu Wenruo 		if (!(tmp & subpage->dirty_bitmap)) {
1053139e8cd3SQu Wenruo 			spin_unlock_irqrestore(&subpage->lock, flags);
1054139e8cd3SQu Wenruo 			cur_bit++;
1055139e8cd3SQu Wenruo 			continue;
1056139e8cd3SQu Wenruo 		}
1057139e8cd3SQu Wenruo 		spin_unlock_irqrestore(&subpage->lock, flags);
1058139e8cd3SQu Wenruo 		cur = page_start + cur_bit * fs_info->sectorsize;
1059139e8cd3SQu Wenruo 
1060139e8cd3SQu Wenruo 		eb = find_extent_buffer(fs_info, cur);
1061139e8cd3SQu Wenruo 		ASSERT(eb);
1062139e8cd3SQu Wenruo 		ASSERT(test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
1063139e8cd3SQu Wenruo 		ASSERT(atomic_read(&eb->refs));
106449d0c642SFilipe Manana 		btrfs_assert_tree_write_locked(eb);
1065139e8cd3SQu Wenruo 		free_extent_buffer(eb);
1066139e8cd3SQu Wenruo 
1067139e8cd3SQu Wenruo 		cur_bit += (fs_info->nodesize >> fs_info->sectorsize_bits);
1068139e8cd3SQu Wenruo 	}
1069bb146eb2SJosef Bacik #endif
10700b32f4bbSJosef Bacik 	return __set_page_dirty_nobuffers(page);
10710b32f4bbSJosef Bacik }
10720b32f4bbSJosef Bacik 
10737f09410bSAlexey Dobriyan static const struct address_space_operations btree_aops = {
10740da5468fSChris Mason 	.writepages	= btree_writepages,
10755f39d397SChris Mason 	.releasepage	= btree_releasepage,
10765f39d397SChris Mason 	.invalidatepage = btree_invalidatepage,
10775a92bc88SChris Mason #ifdef CONFIG_MIGRATION
1078784b4e29SChris Mason 	.migratepage	= btree_migratepage,
10795a92bc88SChris Mason #endif
10800b32f4bbSJosef Bacik 	.set_page_dirty = btree_set_page_dirty,
1081d98237b3SChris Mason };
1082123abc88SChris Mason 
10832ff7e61eSJeff Mahoney struct extent_buffer *btrfs_find_create_tree_block(
10842ff7e61eSJeff Mahoney 						struct btrfs_fs_info *fs_info,
10853fbaf258SJosef Bacik 						u64 bytenr, u64 owner_root,
10863fbaf258SJosef Bacik 						int level)
10870999df54SChris Mason {
10880b246afaSJeff Mahoney 	if (btrfs_is_testing(fs_info))
10890b246afaSJeff Mahoney 		return alloc_test_extent_buffer(fs_info, bytenr);
10903fbaf258SJosef Bacik 	return alloc_extent_buffer(fs_info, bytenr, owner_root, level);
10910999df54SChris Mason }
10920999df54SChris Mason 
1093581c1760SQu Wenruo /*
1094581c1760SQu Wenruo  * Read tree block at logical address @bytenr and do variant basic but critical
1095581c1760SQu Wenruo  * verification.
1096581c1760SQu Wenruo  *
10971b7ec85eSJosef Bacik  * @owner_root:		the objectid of the root owner for this block.
1098581c1760SQu Wenruo  * @parent_transid:	expected transid of this tree block, skip check if 0
1099581c1760SQu Wenruo  * @level:		expected level, mandatory check
1100581c1760SQu Wenruo  * @first_key:		expected key in slot 0, skip check if NULL
1101581c1760SQu Wenruo  */
11022ff7e61eSJeff Mahoney struct extent_buffer *read_tree_block(struct btrfs_fs_info *fs_info, u64 bytenr,
11031b7ec85eSJosef Bacik 				      u64 owner_root, u64 parent_transid,
11041b7ec85eSJosef Bacik 				      int level, struct btrfs_key *first_key)
1105e20d96d6SChris Mason {
11065f39d397SChris Mason 	struct extent_buffer *buf = NULL;
110719c00ddcSChris Mason 	int ret;
110819c00ddcSChris Mason 
11093fbaf258SJosef Bacik 	buf = btrfs_find_create_tree_block(fs_info, bytenr, owner_root, level);
1110c871b0f2SLiu Bo 	if (IS_ERR(buf))
1111c871b0f2SLiu Bo 		return buf;
1112e4204dedSChris Mason 
11135ab12d1fSDavid Sterba 	ret = btree_read_extent_buffer_pages(buf, parent_transid,
1114581c1760SQu Wenruo 					     level, first_key);
11150f0fe8f7SFilipe David Borba Manana 	if (ret) {
1116537f38f0SNikolay Borisov 		free_extent_buffer_stale(buf);
111764c043deSLiu Bo 		return ERR_PTR(ret);
11180f0fe8f7SFilipe David Borba Manana 	}
11195f39d397SChris Mason 	return buf;
1120ce9adaa5SChris Mason 
1121eb60ceacSChris Mason }
1122eb60ceacSChris Mason 
11236a884d7dSDavid Sterba void btrfs_clean_tree_block(struct extent_buffer *buf)
1124ed2ff2cbSChris Mason {
11256a884d7dSDavid Sterba 	struct btrfs_fs_info *fs_info = buf->fs_info;
112655c69072SChris Mason 	if (btrfs_header_generation(buf) ==
1127e2d84521SMiao Xie 	    fs_info->running_transaction->transid) {
112849d0c642SFilipe Manana 		btrfs_assert_tree_write_locked(buf);
1129b4ce94deSChris Mason 
1130b9473439SChris Mason 		if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &buf->bflags)) {
1131104b4e51SNikolay Borisov 			percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
1132e2d84521SMiao Xie 						 -buf->len,
1133e2d84521SMiao Xie 						 fs_info->dirty_metadata_batch);
11340b32f4bbSJosef Bacik 			clear_extent_buffer_dirty(buf);
1135925baeddSChris Mason 		}
11365f39d397SChris Mason 	}
1137ed7b63ebSJosef Bacik }
11385f39d397SChris Mason 
1139da17066cSJeff Mahoney static void __setup_root(struct btrfs_root *root, struct btrfs_fs_info *fs_info,
1140e20d96d6SChris Mason 			 u64 objectid)
1141d97e63b6SChris Mason {
11427c0260eeSJeff Mahoney 	bool dummy = test_bit(BTRFS_FS_STATE_DUMMY_FS_INFO, &fs_info->fs_state);
114396dfcb46SJosef Bacik 	root->fs_info = fs_info;
1144cfaa7295SChris Mason 	root->node = NULL;
1145a28ec197SChris Mason 	root->commit_root = NULL;
114627cdeb70SMiao Xie 	root->state = 0;
1147d68fc57bSYan, Zheng 	root->orphan_cleanup_state = 0;
11480b86a832SChris Mason 
11490f7d52f4SChris Mason 	root->last_trans = 0;
11506b8fad57SNikolay Borisov 	root->free_objectid = 0;
1151eb73c1b7SMiao Xie 	root->nr_delalloc_inodes = 0;
1152199c2a9cSMiao Xie 	root->nr_ordered_extents = 0;
11536bef4d31SEric Paris 	root->inode_tree = RB_ROOT;
115416cdcec7SMiao Xie 	INIT_RADIX_TREE(&root->delayed_nodes_tree, GFP_ATOMIC);
1155f0486c68SYan, Zheng 	root->block_rsv = NULL;
11560b86a832SChris Mason 
11570b86a832SChris Mason 	INIT_LIST_HEAD(&root->dirty_list);
11585d4f98a2SYan Zheng 	INIT_LIST_HEAD(&root->root_list);
1159eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&root->delalloc_inodes);
1160eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&root->delalloc_root);
1161199c2a9cSMiao Xie 	INIT_LIST_HEAD(&root->ordered_extents);
1162199c2a9cSMiao Xie 	INIT_LIST_HEAD(&root->ordered_root);
1163d2311e69SQu Wenruo 	INIT_LIST_HEAD(&root->reloc_dirty_list);
11642ab28f32SJosef Bacik 	INIT_LIST_HEAD(&root->logged_list[0]);
11652ab28f32SJosef Bacik 	INIT_LIST_HEAD(&root->logged_list[1]);
11665d4f98a2SYan Zheng 	spin_lock_init(&root->inode_lock);
1167eb73c1b7SMiao Xie 	spin_lock_init(&root->delalloc_lock);
1168199c2a9cSMiao Xie 	spin_lock_init(&root->ordered_extent_lock);
1169f0486c68SYan, Zheng 	spin_lock_init(&root->accounting_lock);
11702ab28f32SJosef Bacik 	spin_lock_init(&root->log_extents_lock[0]);
11712ab28f32SJosef Bacik 	spin_lock_init(&root->log_extents_lock[1]);
11728287475aSQu Wenruo 	spin_lock_init(&root->qgroup_meta_rsv_lock);
1173a2135011SChris Mason 	mutex_init(&root->objectid_mutex);
1174e02119d5SChris Mason 	mutex_init(&root->log_mutex);
117531f3d255SMiao Xie 	mutex_init(&root->ordered_extent_mutex);
1176573bfb72SMiao Xie 	mutex_init(&root->delalloc_mutex);
1177c53e9653SQu Wenruo 	init_waitqueue_head(&root->qgroup_flush_wait);
11787237f183SYan Zheng 	init_waitqueue_head(&root->log_writer_wait);
11797237f183SYan Zheng 	init_waitqueue_head(&root->log_commit_wait[0]);
11807237f183SYan Zheng 	init_waitqueue_head(&root->log_commit_wait[1]);
11818b050d35SMiao Xie 	INIT_LIST_HEAD(&root->log_ctxs[0]);
11828b050d35SMiao Xie 	INIT_LIST_HEAD(&root->log_ctxs[1]);
11837237f183SYan Zheng 	atomic_set(&root->log_commit[0], 0);
11847237f183SYan Zheng 	atomic_set(&root->log_commit[1], 0);
11857237f183SYan Zheng 	atomic_set(&root->log_writers, 0);
11862ecb7923SMiao Xie 	atomic_set(&root->log_batch, 0);
11870700cea7SElena Reshetova 	refcount_set(&root->refs, 1);
11888ecebf4dSRobbie Ko 	atomic_set(&root->snapshot_force_cow, 0);
1189eede2bf3SOmar Sandoval 	atomic_set(&root->nr_swapfiles, 0);
11907237f183SYan Zheng 	root->log_transid = 0;
1191d1433debSMiao Xie 	root->log_transid_committed = -1;
1192257c62e1SChris Mason 	root->last_log_commit = 0;
1193e289f03eSFilipe Manana 	if (!dummy) {
119443eb5f29SQu Wenruo 		extent_io_tree_init(fs_info, &root->dirty_log_pages,
119543eb5f29SQu Wenruo 				    IO_TREE_ROOT_DIRTY_LOG_PAGES, NULL);
1196e289f03eSFilipe Manana 		extent_io_tree_init(fs_info, &root->log_csum_range,
1197e289f03eSFilipe Manana 				    IO_TREE_LOG_CSUM_RANGE, NULL);
1198e289f03eSFilipe Manana 	}
1199017e5369SChris Mason 
12003768f368SChris Mason 	memset(&root->root_key, 0, sizeof(root->root_key));
12013768f368SChris Mason 	memset(&root->root_item, 0, sizeof(root->root_item));
12026702ed49SChris Mason 	memset(&root->defrag_progress, 0, sizeof(root->defrag_progress));
12034d775673SChris Mason 	root->root_key.objectid = objectid;
12040ee5dc67SAl Viro 	root->anon_dev = 0;
12058ea05e3aSAlexander Block 
12065f3ab90aSAnand Jain 	spin_lock_init(&root->root_item_lock);
1207370a11b8SQu Wenruo 	btrfs_qgroup_init_swapped_blocks(&root->swapped_blocks);
1208bd647ce3SJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
1209bd647ce3SJosef Bacik 	INIT_LIST_HEAD(&root->leak_list);
1210bd647ce3SJosef Bacik 	spin_lock(&fs_info->fs_roots_radix_lock);
1211bd647ce3SJosef Bacik 	list_add_tail(&root->leak_list, &fs_info->allocated_roots);
1212bd647ce3SJosef Bacik 	spin_unlock(&fs_info->fs_roots_radix_lock);
1213bd647ce3SJosef Bacik #endif
12143768f368SChris Mason }
12153768f368SChris Mason 
121674e4d827SDavid Sterba static struct btrfs_root *btrfs_alloc_root(struct btrfs_fs_info *fs_info,
121796dfcb46SJosef Bacik 					   u64 objectid, gfp_t flags)
12186f07e42eSAl Viro {
121974e4d827SDavid Sterba 	struct btrfs_root *root = kzalloc(sizeof(*root), flags);
12206f07e42eSAl Viro 	if (root)
122196dfcb46SJosef Bacik 		__setup_root(root, fs_info, objectid);
12226f07e42eSAl Viro 	return root;
12236f07e42eSAl Viro }
12246f07e42eSAl Viro 
122506ea65a3SJosef Bacik #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
122606ea65a3SJosef Bacik /* Should only be used by the testing infrastructure */
1227da17066cSJeff Mahoney struct btrfs_root *btrfs_alloc_dummy_root(struct btrfs_fs_info *fs_info)
122806ea65a3SJosef Bacik {
122906ea65a3SJosef Bacik 	struct btrfs_root *root;
123006ea65a3SJosef Bacik 
12317c0260eeSJeff Mahoney 	if (!fs_info)
12327c0260eeSJeff Mahoney 		return ERR_PTR(-EINVAL);
12337c0260eeSJeff Mahoney 
123496dfcb46SJosef Bacik 	root = btrfs_alloc_root(fs_info, BTRFS_ROOT_TREE_OBJECTID, GFP_KERNEL);
123506ea65a3SJosef Bacik 	if (!root)
123606ea65a3SJosef Bacik 		return ERR_PTR(-ENOMEM);
1237da17066cSJeff Mahoney 
1238b9ef22deSFeifei Xu 	/* We don't use the stripesize in selftest, set it as sectorsize */
1239faa2dbf0SJosef Bacik 	root->alloc_bytenr = 0;
124006ea65a3SJosef Bacik 
124106ea65a3SJosef Bacik 	return root;
124206ea65a3SJosef Bacik }
124306ea65a3SJosef Bacik #endif
124406ea65a3SJosef Bacik 
124520897f5cSArne Jansen struct btrfs_root *btrfs_create_tree(struct btrfs_trans_handle *trans,
124620897f5cSArne Jansen 				     u64 objectid)
124720897f5cSArne Jansen {
12489b7a2440SDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
124920897f5cSArne Jansen 	struct extent_buffer *leaf;
125020897f5cSArne Jansen 	struct btrfs_root *tree_root = fs_info->tree_root;
125120897f5cSArne Jansen 	struct btrfs_root *root;
125220897f5cSArne Jansen 	struct btrfs_key key;
1253b89f6d1fSFilipe Manana 	unsigned int nofs_flag;
125420897f5cSArne Jansen 	int ret = 0;
125520897f5cSArne Jansen 
1256b89f6d1fSFilipe Manana 	/*
1257b89f6d1fSFilipe Manana 	 * We're holding a transaction handle, so use a NOFS memory allocation
1258b89f6d1fSFilipe Manana 	 * context to avoid deadlock if reclaim happens.
1259b89f6d1fSFilipe Manana 	 */
1260b89f6d1fSFilipe Manana 	nofs_flag = memalloc_nofs_save();
126196dfcb46SJosef Bacik 	root = btrfs_alloc_root(fs_info, objectid, GFP_KERNEL);
1262b89f6d1fSFilipe Manana 	memalloc_nofs_restore(nofs_flag);
126320897f5cSArne Jansen 	if (!root)
126420897f5cSArne Jansen 		return ERR_PTR(-ENOMEM);
126520897f5cSArne Jansen 
126620897f5cSArne Jansen 	root->root_key.objectid = objectid;
126720897f5cSArne Jansen 	root->root_key.type = BTRFS_ROOT_ITEM_KEY;
126820897f5cSArne Jansen 	root->root_key.offset = 0;
126920897f5cSArne Jansen 
12709631e4ccSJosef Bacik 	leaf = btrfs_alloc_tree_block(trans, root, 0, objectid, NULL, 0, 0, 0,
12719631e4ccSJosef Bacik 				      BTRFS_NESTING_NORMAL);
127220897f5cSArne Jansen 	if (IS_ERR(leaf)) {
127320897f5cSArne Jansen 		ret = PTR_ERR(leaf);
12741dd05682STsutomu Itoh 		leaf = NULL;
12758a6a87cdSBoris Burkov 		goto fail_unlock;
127620897f5cSArne Jansen 	}
127720897f5cSArne Jansen 
127820897f5cSArne Jansen 	root->node = leaf;
127920897f5cSArne Jansen 	btrfs_mark_buffer_dirty(leaf);
128020897f5cSArne Jansen 
128120897f5cSArne Jansen 	root->commit_root = btrfs_root_node(root);
128227cdeb70SMiao Xie 	set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
128320897f5cSArne Jansen 
1284f944d2cbSDavid Sterba 	btrfs_set_root_flags(&root->root_item, 0);
1285f944d2cbSDavid Sterba 	btrfs_set_root_limit(&root->root_item, 0);
128620897f5cSArne Jansen 	btrfs_set_root_bytenr(&root->root_item, leaf->start);
128720897f5cSArne Jansen 	btrfs_set_root_generation(&root->root_item, trans->transid);
128820897f5cSArne Jansen 	btrfs_set_root_level(&root->root_item, 0);
128920897f5cSArne Jansen 	btrfs_set_root_refs(&root->root_item, 1);
129020897f5cSArne Jansen 	btrfs_set_root_used(&root->root_item, leaf->len);
129120897f5cSArne Jansen 	btrfs_set_root_last_snapshot(&root->root_item, 0);
129220897f5cSArne Jansen 	btrfs_set_root_dirid(&root->root_item, 0);
129333d85fdaSQu Wenruo 	if (is_fstree(objectid))
1294807fc790SAndy Shevchenko 		generate_random_guid(root->root_item.uuid);
1295807fc790SAndy Shevchenko 	else
1296807fc790SAndy Shevchenko 		export_guid(root->root_item.uuid, &guid_null);
1297c8422684SDavid Sterba 	btrfs_set_root_drop_level(&root->root_item, 0);
129820897f5cSArne Jansen 
12998a6a87cdSBoris Burkov 	btrfs_tree_unlock(leaf);
13008a6a87cdSBoris Burkov 
130120897f5cSArne Jansen 	key.objectid = objectid;
130220897f5cSArne Jansen 	key.type = BTRFS_ROOT_ITEM_KEY;
130320897f5cSArne Jansen 	key.offset = 0;
130420897f5cSArne Jansen 	ret = btrfs_insert_root(trans, tree_root, &key, &root->root_item);
130520897f5cSArne Jansen 	if (ret)
130620897f5cSArne Jansen 		goto fail;
130720897f5cSArne Jansen 
130820897f5cSArne Jansen 	return root;
13091dd05682STsutomu Itoh 
13108a6a87cdSBoris Burkov fail_unlock:
13118c38938cSJosef Bacik 	if (leaf)
13121dd05682STsutomu Itoh 		btrfs_tree_unlock(leaf);
13138a6a87cdSBoris Burkov fail:
131400246528SJosef Bacik 	btrfs_put_root(root);
13151dd05682STsutomu Itoh 
13161dd05682STsutomu Itoh 	return ERR_PTR(ret);
131720897f5cSArne Jansen }
131820897f5cSArne Jansen 
13197237f183SYan Zheng static struct btrfs_root *alloc_log_tree(struct btrfs_trans_handle *trans,
1320e02119d5SChris Mason 					 struct btrfs_fs_info *fs_info)
13210f7d52f4SChris Mason {
13220f7d52f4SChris Mason 	struct btrfs_root *root;
1323e02119d5SChris Mason 
132496dfcb46SJosef Bacik 	root = btrfs_alloc_root(fs_info, BTRFS_TREE_LOG_OBJECTID, GFP_NOFS);
1325e02119d5SChris Mason 	if (!root)
13267237f183SYan Zheng 		return ERR_PTR(-ENOMEM);
1327e02119d5SChris Mason 
1328e02119d5SChris Mason 	root->root_key.objectid = BTRFS_TREE_LOG_OBJECTID;
1329e02119d5SChris Mason 	root->root_key.type = BTRFS_ROOT_ITEM_KEY;
1330e02119d5SChris Mason 	root->root_key.offset = BTRFS_TREE_LOG_OBJECTID;
133127cdeb70SMiao Xie 
13326ab6ebb7SNaohiro Aota 	return root;
13336ab6ebb7SNaohiro Aota }
13346ab6ebb7SNaohiro Aota 
13356ab6ebb7SNaohiro Aota int btrfs_alloc_log_tree_node(struct btrfs_trans_handle *trans,
13366ab6ebb7SNaohiro Aota 			      struct btrfs_root *root)
13376ab6ebb7SNaohiro Aota {
13386ab6ebb7SNaohiro Aota 	struct extent_buffer *leaf;
13396ab6ebb7SNaohiro Aota 
13407237f183SYan Zheng 	/*
134192a7cc42SQu Wenruo 	 * DON'T set SHAREABLE bit for log trees.
134227cdeb70SMiao Xie 	 *
134392a7cc42SQu Wenruo 	 * Log trees are not exposed to user space thus can't be snapshotted,
134492a7cc42SQu Wenruo 	 * and they go away before a real commit is actually done.
134592a7cc42SQu Wenruo 	 *
134692a7cc42SQu Wenruo 	 * They do store pointers to file data extents, and those reference
134792a7cc42SQu Wenruo 	 * counts still get updated (along with back refs to the log tree).
13487237f183SYan Zheng 	 */
1349e02119d5SChris Mason 
13504d75f8a9SDavid Sterba 	leaf = btrfs_alloc_tree_block(trans, root, 0, BTRFS_TREE_LOG_OBJECTID,
13519631e4ccSJosef Bacik 			NULL, 0, 0, 0, BTRFS_NESTING_NORMAL);
13526ab6ebb7SNaohiro Aota 	if (IS_ERR(leaf))
13536ab6ebb7SNaohiro Aota 		return PTR_ERR(leaf);
1354e02119d5SChris Mason 
13557237f183SYan Zheng 	root->node = leaf;
1356e02119d5SChris Mason 
1357e02119d5SChris Mason 	btrfs_mark_buffer_dirty(root->node);
1358e02119d5SChris Mason 	btrfs_tree_unlock(root->node);
13596ab6ebb7SNaohiro Aota 
13606ab6ebb7SNaohiro Aota 	return 0;
13617237f183SYan Zheng }
13627237f183SYan Zheng 
13637237f183SYan Zheng int btrfs_init_log_root_tree(struct btrfs_trans_handle *trans,
13647237f183SYan Zheng 			     struct btrfs_fs_info *fs_info)
13657237f183SYan Zheng {
13667237f183SYan Zheng 	struct btrfs_root *log_root;
13677237f183SYan Zheng 
13687237f183SYan Zheng 	log_root = alloc_log_tree(trans, fs_info);
13697237f183SYan Zheng 	if (IS_ERR(log_root))
13707237f183SYan Zheng 		return PTR_ERR(log_root);
13716ab6ebb7SNaohiro Aota 
13723ddebf27SNaohiro Aota 	if (!btrfs_is_zoned(fs_info)) {
13733ddebf27SNaohiro Aota 		int ret = btrfs_alloc_log_tree_node(trans, log_root);
13743ddebf27SNaohiro Aota 
13756ab6ebb7SNaohiro Aota 		if (ret) {
13766ab6ebb7SNaohiro Aota 			btrfs_put_root(log_root);
13776ab6ebb7SNaohiro Aota 			return ret;
13786ab6ebb7SNaohiro Aota 		}
13793ddebf27SNaohiro Aota 	}
13806ab6ebb7SNaohiro Aota 
13817237f183SYan Zheng 	WARN_ON(fs_info->log_root_tree);
13827237f183SYan Zheng 	fs_info->log_root_tree = log_root;
13837237f183SYan Zheng 	return 0;
13847237f183SYan Zheng }
13857237f183SYan Zheng 
13867237f183SYan Zheng int btrfs_add_log_tree(struct btrfs_trans_handle *trans,
13877237f183SYan Zheng 		       struct btrfs_root *root)
13887237f183SYan Zheng {
13890b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
13907237f183SYan Zheng 	struct btrfs_root *log_root;
13917237f183SYan Zheng 	struct btrfs_inode_item *inode_item;
13926ab6ebb7SNaohiro Aota 	int ret;
13937237f183SYan Zheng 
13940b246afaSJeff Mahoney 	log_root = alloc_log_tree(trans, fs_info);
13957237f183SYan Zheng 	if (IS_ERR(log_root))
13967237f183SYan Zheng 		return PTR_ERR(log_root);
13977237f183SYan Zheng 
13986ab6ebb7SNaohiro Aota 	ret = btrfs_alloc_log_tree_node(trans, log_root);
13996ab6ebb7SNaohiro Aota 	if (ret) {
14006ab6ebb7SNaohiro Aota 		btrfs_put_root(log_root);
14016ab6ebb7SNaohiro Aota 		return ret;
14026ab6ebb7SNaohiro Aota 	}
14036ab6ebb7SNaohiro Aota 
14047237f183SYan Zheng 	log_root->last_trans = trans->transid;
14057237f183SYan Zheng 	log_root->root_key.offset = root->root_key.objectid;
14067237f183SYan Zheng 
14077237f183SYan Zheng 	inode_item = &log_root->root_item.inode;
14083cae210fSQu Wenruo 	btrfs_set_stack_inode_generation(inode_item, 1);
14093cae210fSQu Wenruo 	btrfs_set_stack_inode_size(inode_item, 3);
14103cae210fSQu Wenruo 	btrfs_set_stack_inode_nlink(inode_item, 1);
1411da17066cSJeff Mahoney 	btrfs_set_stack_inode_nbytes(inode_item,
14120b246afaSJeff Mahoney 				     fs_info->nodesize);
14133cae210fSQu Wenruo 	btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
14147237f183SYan Zheng 
14155d4f98a2SYan Zheng 	btrfs_set_root_node(&log_root->root_item, log_root->node);
14167237f183SYan Zheng 
14177237f183SYan Zheng 	WARN_ON(root->log_root);
14187237f183SYan Zheng 	root->log_root = log_root;
14197237f183SYan Zheng 	root->log_transid = 0;
1420d1433debSMiao Xie 	root->log_transid_committed = -1;
1421257c62e1SChris Mason 	root->last_log_commit = 0;
1422e02119d5SChris Mason 	return 0;
1423e02119d5SChris Mason }
1424e02119d5SChris Mason 
142549d11beaSJosef Bacik static struct btrfs_root *read_tree_root_path(struct btrfs_root *tree_root,
142649d11beaSJosef Bacik 					      struct btrfs_path *path,
1427cb517eabSMiao Xie 					      struct btrfs_key *key)
1428e02119d5SChris Mason {
1429e02119d5SChris Mason 	struct btrfs_root *root;
1430e02119d5SChris Mason 	struct btrfs_fs_info *fs_info = tree_root->fs_info;
143184234f3aSYan Zheng 	u64 generation;
1432cb517eabSMiao Xie 	int ret;
1433581c1760SQu Wenruo 	int level;
1434cb517eabSMiao Xie 
143596dfcb46SJosef Bacik 	root = btrfs_alloc_root(fs_info, key->objectid, GFP_NOFS);
143649d11beaSJosef Bacik 	if (!root)
143749d11beaSJosef Bacik 		return ERR_PTR(-ENOMEM);
14380f7d52f4SChris Mason 
1439cb517eabSMiao Xie 	ret = btrfs_find_root(tree_root, key, path,
1440cb517eabSMiao Xie 			      &root->root_item, &root->root_key);
14410f7d52f4SChris Mason 	if (ret) {
144213a8a7c8SYan, Zheng 		if (ret > 0)
144313a8a7c8SYan, Zheng 			ret = -ENOENT;
144449d11beaSJosef Bacik 		goto fail;
14450f7d52f4SChris Mason 	}
144613a8a7c8SYan, Zheng 
144784234f3aSYan Zheng 	generation = btrfs_root_generation(&root->root_item);
1448581c1760SQu Wenruo 	level = btrfs_root_level(&root->root_item);
14492ff7e61eSJeff Mahoney 	root->node = read_tree_block(fs_info,
14502ff7e61eSJeff Mahoney 				     btrfs_root_bytenr(&root->root_item),
14511b7ec85eSJosef Bacik 				     key->objectid, generation, level, NULL);
145264c043deSLiu Bo 	if (IS_ERR(root->node)) {
145364c043deSLiu Bo 		ret = PTR_ERR(root->node);
14548c38938cSJosef Bacik 		root->node = NULL;
145549d11beaSJosef Bacik 		goto fail;
1456cb517eabSMiao Xie 	} else if (!btrfs_buffer_uptodate(root->node, generation, 0)) {
1457cb517eabSMiao Xie 		ret = -EIO;
145849d11beaSJosef Bacik 		goto fail;
1459416bc658SJosef Bacik 	}
14605d4f98a2SYan Zheng 	root->commit_root = btrfs_root_node(root);
1461cb517eabSMiao Xie 	return root;
146249d11beaSJosef Bacik fail:
146300246528SJosef Bacik 	btrfs_put_root(root);
146449d11beaSJosef Bacik 	return ERR_PTR(ret);
146549d11beaSJosef Bacik }
146649d11beaSJosef Bacik 
146749d11beaSJosef Bacik struct btrfs_root *btrfs_read_tree_root(struct btrfs_root *tree_root,
146849d11beaSJosef Bacik 					struct btrfs_key *key)
146949d11beaSJosef Bacik {
147049d11beaSJosef Bacik 	struct btrfs_root *root;
147149d11beaSJosef Bacik 	struct btrfs_path *path;
147249d11beaSJosef Bacik 
147349d11beaSJosef Bacik 	path = btrfs_alloc_path();
147449d11beaSJosef Bacik 	if (!path)
147549d11beaSJosef Bacik 		return ERR_PTR(-ENOMEM);
147649d11beaSJosef Bacik 	root = read_tree_root_path(tree_root, path, key);
147749d11beaSJosef Bacik 	btrfs_free_path(path);
147849d11beaSJosef Bacik 
147949d11beaSJosef Bacik 	return root;
1480cb517eabSMiao Xie }
1481cb517eabSMiao Xie 
14822dfb1e43SQu Wenruo /*
14832dfb1e43SQu Wenruo  * Initialize subvolume root in-memory structure
14842dfb1e43SQu Wenruo  *
14852dfb1e43SQu Wenruo  * @anon_dev:	anonymous device to attach to the root, if zero, allocate new
14862dfb1e43SQu Wenruo  */
14872dfb1e43SQu Wenruo static int btrfs_init_fs_root(struct btrfs_root *root, dev_t anon_dev)
1488cb517eabSMiao Xie {
1489cb517eabSMiao Xie 	int ret;
1490dcc3eb96SNikolay Borisov 	unsigned int nofs_flag;
1491cb517eabSMiao Xie 
1492dcc3eb96SNikolay Borisov 	/*
1493dcc3eb96SNikolay Borisov 	 * We might be called under a transaction (e.g. indirect backref
1494dcc3eb96SNikolay Borisov 	 * resolution) which could deadlock if it triggers memory reclaim
1495dcc3eb96SNikolay Borisov 	 */
1496dcc3eb96SNikolay Borisov 	nofs_flag = memalloc_nofs_save();
1497dcc3eb96SNikolay Borisov 	ret = btrfs_drew_lock_init(&root->snapshot_lock);
1498dcc3eb96SNikolay Borisov 	memalloc_nofs_restore(nofs_flag);
1499dcc3eb96SNikolay Borisov 	if (ret)
15008257b2dcSMiao Xie 		goto fail;
15018257b2dcSMiao Xie 
1502aeb935a4SQu Wenruo 	if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID &&
150337f00a6dSJohannes Thumshirn 	    !btrfs_is_data_reloc_root(root)) {
150492a7cc42SQu Wenruo 		set_bit(BTRFS_ROOT_SHAREABLE, &root->state);
1505f39e4571SJosef Bacik 		btrfs_check_and_init_root_item(&root->root_item);
1506f39e4571SJosef Bacik 	}
1507f39e4571SJosef Bacik 
1508851fd730SQu Wenruo 	/*
1509851fd730SQu Wenruo 	 * Don't assign anonymous block device to roots that are not exposed to
1510851fd730SQu Wenruo 	 * userspace, the id pool is limited to 1M
1511851fd730SQu Wenruo 	 */
1512851fd730SQu Wenruo 	if (is_fstree(root->root_key.objectid) &&
1513851fd730SQu Wenruo 	    btrfs_root_refs(&root->root_item) > 0) {
15142dfb1e43SQu Wenruo 		if (!anon_dev) {
1515cb517eabSMiao Xie 			ret = get_anon_bdev(&root->anon_dev);
1516cb517eabSMiao Xie 			if (ret)
1517876d2cf1SLiu Bo 				goto fail;
15182dfb1e43SQu Wenruo 		} else {
15192dfb1e43SQu Wenruo 			root->anon_dev = anon_dev;
15202dfb1e43SQu Wenruo 		}
1521851fd730SQu Wenruo 	}
1522f32e48e9SChandan Rajendra 
1523f32e48e9SChandan Rajendra 	mutex_lock(&root->objectid_mutex);
1524453e4873SNikolay Borisov 	ret = btrfs_init_root_free_objectid(root);
1525f32e48e9SChandan Rajendra 	if (ret) {
1526f32e48e9SChandan Rajendra 		mutex_unlock(&root->objectid_mutex);
1527876d2cf1SLiu Bo 		goto fail;
1528f32e48e9SChandan Rajendra 	}
1529f32e48e9SChandan Rajendra 
15306b8fad57SNikolay Borisov 	ASSERT(root->free_objectid <= BTRFS_LAST_FREE_OBJECTID);
1531f32e48e9SChandan Rajendra 
1532f32e48e9SChandan Rajendra 	mutex_unlock(&root->objectid_mutex);
1533f32e48e9SChandan Rajendra 
1534cb517eabSMiao Xie 	return 0;
1535cb517eabSMiao Xie fail:
153684db5ccfSDavid Sterba 	/* The caller is responsible to call btrfs_free_fs_root */
1537cb517eabSMiao Xie 	return ret;
1538cb517eabSMiao Xie }
1539cb517eabSMiao Xie 
1540a98db0f3SJosef Bacik static struct btrfs_root *btrfs_lookup_fs_root(struct btrfs_fs_info *fs_info,
1541cb517eabSMiao Xie 					       u64 root_id)
1542cb517eabSMiao Xie {
1543cb517eabSMiao Xie 	struct btrfs_root *root;
1544cb517eabSMiao Xie 
1545cb517eabSMiao Xie 	spin_lock(&fs_info->fs_roots_radix_lock);
1546cb517eabSMiao Xie 	root = radix_tree_lookup(&fs_info->fs_roots_radix,
1547cb517eabSMiao Xie 				 (unsigned long)root_id);
1548bc44d7c4SJosef Bacik 	if (root)
154900246528SJosef Bacik 		root = btrfs_grab_root(root);
1550cb517eabSMiao Xie 	spin_unlock(&fs_info->fs_roots_radix_lock);
1551cb517eabSMiao Xie 	return root;
1552cb517eabSMiao Xie }
1553cb517eabSMiao Xie 
155449d11beaSJosef Bacik static struct btrfs_root *btrfs_get_global_root(struct btrfs_fs_info *fs_info,
155549d11beaSJosef Bacik 						u64 objectid)
155649d11beaSJosef Bacik {
155749d11beaSJosef Bacik 	if (objectid == BTRFS_ROOT_TREE_OBJECTID)
155849d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->tree_root);
155949d11beaSJosef Bacik 	if (objectid == BTRFS_EXTENT_TREE_OBJECTID)
156049d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->extent_root);
156149d11beaSJosef Bacik 	if (objectid == BTRFS_CHUNK_TREE_OBJECTID)
156249d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->chunk_root);
156349d11beaSJosef Bacik 	if (objectid == BTRFS_DEV_TREE_OBJECTID)
156449d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->dev_root);
156549d11beaSJosef Bacik 	if (objectid == BTRFS_CSUM_TREE_OBJECTID)
156649d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->csum_root);
156749d11beaSJosef Bacik 	if (objectid == BTRFS_QUOTA_TREE_OBJECTID)
156849d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->quota_root) ?
156949d11beaSJosef Bacik 			fs_info->quota_root : ERR_PTR(-ENOENT);
157049d11beaSJosef Bacik 	if (objectid == BTRFS_UUID_TREE_OBJECTID)
157149d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->uuid_root) ?
157249d11beaSJosef Bacik 			fs_info->uuid_root : ERR_PTR(-ENOENT);
157349d11beaSJosef Bacik 	if (objectid == BTRFS_FREE_SPACE_TREE_OBJECTID)
157449d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->free_space_root) ?
157549d11beaSJosef Bacik 			fs_info->free_space_root : ERR_PTR(-ENOENT);
157649d11beaSJosef Bacik 	return NULL;
157749d11beaSJosef Bacik }
157849d11beaSJosef Bacik 
1579cb517eabSMiao Xie int btrfs_insert_fs_root(struct btrfs_fs_info *fs_info,
1580cb517eabSMiao Xie 			 struct btrfs_root *root)
1581cb517eabSMiao Xie {
1582cb517eabSMiao Xie 	int ret;
1583cb517eabSMiao Xie 
1584e1860a77SDavid Sterba 	ret = radix_tree_preload(GFP_NOFS);
1585cb517eabSMiao Xie 	if (ret)
1586cb517eabSMiao Xie 		return ret;
1587cb517eabSMiao Xie 
1588cb517eabSMiao Xie 	spin_lock(&fs_info->fs_roots_radix_lock);
1589cb517eabSMiao Xie 	ret = radix_tree_insert(&fs_info->fs_roots_radix,
1590cb517eabSMiao Xie 				(unsigned long)root->root_key.objectid,
1591cb517eabSMiao Xie 				root);
1592af01d2e5SJosef Bacik 	if (ret == 0) {
159300246528SJosef Bacik 		btrfs_grab_root(root);
159427cdeb70SMiao Xie 		set_bit(BTRFS_ROOT_IN_RADIX, &root->state);
1595af01d2e5SJosef Bacik 	}
1596cb517eabSMiao Xie 	spin_unlock(&fs_info->fs_roots_radix_lock);
1597cb517eabSMiao Xie 	radix_tree_preload_end();
1598cb517eabSMiao Xie 
1599cb517eabSMiao Xie 	return ret;
1600cb517eabSMiao Xie }
1601cb517eabSMiao Xie 
1602bd647ce3SJosef Bacik void btrfs_check_leaked_roots(struct btrfs_fs_info *fs_info)
1603bd647ce3SJosef Bacik {
1604bd647ce3SJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
1605bd647ce3SJosef Bacik 	struct btrfs_root *root;
1606bd647ce3SJosef Bacik 
1607bd647ce3SJosef Bacik 	while (!list_empty(&fs_info->allocated_roots)) {
1608457f1864SJosef Bacik 		char buf[BTRFS_ROOT_NAME_BUF_LEN];
1609457f1864SJosef Bacik 
1610bd647ce3SJosef Bacik 		root = list_first_entry(&fs_info->allocated_roots,
1611bd647ce3SJosef Bacik 					struct btrfs_root, leak_list);
1612457f1864SJosef Bacik 		btrfs_err(fs_info, "leaked root %s refcount %d",
161371008734SJosef Bacik 			  btrfs_root_name(&root->root_key, buf),
1614bd647ce3SJosef Bacik 			  refcount_read(&root->refs));
1615bd647ce3SJosef Bacik 		while (refcount_read(&root->refs) > 1)
161600246528SJosef Bacik 			btrfs_put_root(root);
161700246528SJosef Bacik 		btrfs_put_root(root);
1618bd647ce3SJosef Bacik 	}
1619bd647ce3SJosef Bacik #endif
1620bd647ce3SJosef Bacik }
1621bd647ce3SJosef Bacik 
16220d4b0463SJosef Bacik void btrfs_free_fs_info(struct btrfs_fs_info *fs_info)
16230d4b0463SJosef Bacik {
1624141386e1SJosef Bacik 	percpu_counter_destroy(&fs_info->dirty_metadata_bytes);
1625141386e1SJosef Bacik 	percpu_counter_destroy(&fs_info->delalloc_bytes);
16265deb17e1SJosef Bacik 	percpu_counter_destroy(&fs_info->ordered_bytes);
1627141386e1SJosef Bacik 	percpu_counter_destroy(&fs_info->dev_replace.bio_counter);
1628141386e1SJosef Bacik 	btrfs_free_csum_hash(fs_info);
1629141386e1SJosef Bacik 	btrfs_free_stripe_hash_table(fs_info);
1630141386e1SJosef Bacik 	btrfs_free_ref_cache(fs_info);
16310d4b0463SJosef Bacik 	kfree(fs_info->balance_ctl);
16320d4b0463SJosef Bacik 	kfree(fs_info->delayed_root);
163300246528SJosef Bacik 	btrfs_put_root(fs_info->extent_root);
163400246528SJosef Bacik 	btrfs_put_root(fs_info->tree_root);
163500246528SJosef Bacik 	btrfs_put_root(fs_info->chunk_root);
163600246528SJosef Bacik 	btrfs_put_root(fs_info->dev_root);
163700246528SJosef Bacik 	btrfs_put_root(fs_info->csum_root);
163800246528SJosef Bacik 	btrfs_put_root(fs_info->quota_root);
163900246528SJosef Bacik 	btrfs_put_root(fs_info->uuid_root);
164000246528SJosef Bacik 	btrfs_put_root(fs_info->free_space_root);
164100246528SJosef Bacik 	btrfs_put_root(fs_info->fs_root);
1642aeb935a4SQu Wenruo 	btrfs_put_root(fs_info->data_reloc_root);
1643bd647ce3SJosef Bacik 	btrfs_check_leaked_roots(fs_info);
16443fd63727SJosef Bacik 	btrfs_extent_buffer_leak_debug_check(fs_info);
16450d4b0463SJosef Bacik 	kfree(fs_info->super_copy);
16460d4b0463SJosef Bacik 	kfree(fs_info->super_for_commit);
16478481dd80SQu Wenruo 	kfree(fs_info->subpage_info);
16480d4b0463SJosef Bacik 	kvfree(fs_info);
16490d4b0463SJosef Bacik }
16500d4b0463SJosef Bacik 
16510d4b0463SJosef Bacik 
16522dfb1e43SQu Wenruo /*
16532dfb1e43SQu Wenruo  * Get an in-memory reference of a root structure.
16542dfb1e43SQu Wenruo  *
16552dfb1e43SQu Wenruo  * For essential trees like root/extent tree, we grab it from fs_info directly.
16562dfb1e43SQu Wenruo  * For subvolume trees, we check the cached filesystem roots first. If not
16572dfb1e43SQu Wenruo  * found, then read it from disk and add it to cached fs roots.
16582dfb1e43SQu Wenruo  *
16592dfb1e43SQu Wenruo  * Caller should release the root by calling btrfs_put_root() after the usage.
16602dfb1e43SQu Wenruo  *
16612dfb1e43SQu Wenruo  * NOTE: Reloc and log trees can't be read by this function as they share the
16622dfb1e43SQu Wenruo  *	 same root objectid.
16632dfb1e43SQu Wenruo  *
16642dfb1e43SQu Wenruo  * @objectid:	root id
16652dfb1e43SQu Wenruo  * @anon_dev:	preallocated anonymous block device number for new roots,
16662dfb1e43SQu Wenruo  * 		pass 0 for new allocation.
16672dfb1e43SQu Wenruo  * @check_ref:	whether to check root item references, If true, return -ENOENT
16682dfb1e43SQu Wenruo  *		for orphan roots
16692dfb1e43SQu Wenruo  */
16702dfb1e43SQu Wenruo static struct btrfs_root *btrfs_get_root_ref(struct btrfs_fs_info *fs_info,
16712dfb1e43SQu Wenruo 					     u64 objectid, dev_t anon_dev,
16722dfb1e43SQu Wenruo 					     bool check_ref)
16735eda7b5eSChris Mason {
16745eda7b5eSChris Mason 	struct btrfs_root *root;
1675381cf658SDavid Sterba 	struct btrfs_path *path;
16761d4c08e0SDavid Sterba 	struct btrfs_key key;
16775eda7b5eSChris Mason 	int ret;
16785eda7b5eSChris Mason 
167949d11beaSJosef Bacik 	root = btrfs_get_global_root(fs_info, objectid);
168049d11beaSJosef Bacik 	if (root)
168149d11beaSJosef Bacik 		return root;
16824df27c4dSYan, Zheng again:
168356e9357aSDavid Sterba 	root = btrfs_lookup_fs_root(fs_info, objectid);
168448475471SStefan Behrens 	if (root) {
16852dfb1e43SQu Wenruo 		/* Shouldn't get preallocated anon_dev for cached roots */
16862dfb1e43SQu Wenruo 		ASSERT(!anon_dev);
1687bc44d7c4SJosef Bacik 		if (check_ref && btrfs_root_refs(&root->root_item) == 0) {
168800246528SJosef Bacik 			btrfs_put_root(root);
168948475471SStefan Behrens 			return ERR_PTR(-ENOENT);
1690bc44d7c4SJosef Bacik 		}
16915eda7b5eSChris Mason 		return root;
169248475471SStefan Behrens 	}
16935eda7b5eSChris Mason 
169456e9357aSDavid Sterba 	key.objectid = objectid;
169556e9357aSDavid Sterba 	key.type = BTRFS_ROOT_ITEM_KEY;
169656e9357aSDavid Sterba 	key.offset = (u64)-1;
169756e9357aSDavid Sterba 	root = btrfs_read_tree_root(fs_info->tree_root, &key);
16985eda7b5eSChris Mason 	if (IS_ERR(root))
16995eda7b5eSChris Mason 		return root;
17003394e160SChris Mason 
1701c00869f1SMiao Xie 	if (check_ref && btrfs_root_refs(&root->root_item) == 0) {
1702d68fc57bSYan, Zheng 		ret = -ENOENT;
1703d68fc57bSYan, Zheng 		goto fail;
1704d68fc57bSYan, Zheng 	}
1705d68fc57bSYan, Zheng 
17062dfb1e43SQu Wenruo 	ret = btrfs_init_fs_root(root, anon_dev);
1707cb517eabSMiao Xie 	if (ret)
1708cb517eabSMiao Xie 		goto fail;
1709cb517eabSMiao Xie 
1710381cf658SDavid Sterba 	path = btrfs_alloc_path();
1711381cf658SDavid Sterba 	if (!path) {
1712381cf658SDavid Sterba 		ret = -ENOMEM;
1713381cf658SDavid Sterba 		goto fail;
1714381cf658SDavid Sterba 	}
17151d4c08e0SDavid Sterba 	key.objectid = BTRFS_ORPHAN_OBJECTID;
17161d4c08e0SDavid Sterba 	key.type = BTRFS_ORPHAN_ITEM_KEY;
171756e9357aSDavid Sterba 	key.offset = objectid;
17181d4c08e0SDavid Sterba 
17191d4c08e0SDavid Sterba 	ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
1720381cf658SDavid Sterba 	btrfs_free_path(path);
1721d68fc57bSYan, Zheng 	if (ret < 0)
1722d68fc57bSYan, Zheng 		goto fail;
1723d68fc57bSYan, Zheng 	if (ret == 0)
172427cdeb70SMiao Xie 		set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state);
1725d68fc57bSYan, Zheng 
1726cb517eabSMiao Xie 	ret = btrfs_insert_fs_root(fs_info, root);
17270f7d52f4SChris Mason 	if (ret) {
172800246528SJosef Bacik 		btrfs_put_root(root);
17294785e24fSJosef Bacik 		if (ret == -EEXIST)
17304df27c4dSYan, Zheng 			goto again;
17314df27c4dSYan, Zheng 		goto fail;
17324df27c4dSYan, Zheng 	}
1733edbd8d4eSChris Mason 	return root;
17344df27c4dSYan, Zheng fail:
173533fab972SFilipe Manana 	/*
173633fab972SFilipe Manana 	 * If our caller provided us an anonymous device, then it's his
173733fab972SFilipe Manana 	 * responsability to free it in case we fail. So we have to set our
173833fab972SFilipe Manana 	 * root's anon_dev to 0 to avoid a double free, once by btrfs_put_root()
173933fab972SFilipe Manana 	 * and once again by our caller.
174033fab972SFilipe Manana 	 */
174133fab972SFilipe Manana 	if (anon_dev)
174233fab972SFilipe Manana 		root->anon_dev = 0;
17438c38938cSJosef Bacik 	btrfs_put_root(root);
17444df27c4dSYan, Zheng 	return ERR_PTR(ret);
1745edbd8d4eSChris Mason }
1746edbd8d4eSChris Mason 
17472dfb1e43SQu Wenruo /*
17482dfb1e43SQu Wenruo  * Get in-memory reference of a root structure
17492dfb1e43SQu Wenruo  *
17502dfb1e43SQu Wenruo  * @objectid:	tree objectid
17512dfb1e43SQu Wenruo  * @check_ref:	if set, verify that the tree exists and the item has at least
17522dfb1e43SQu Wenruo  *		one reference
17532dfb1e43SQu Wenruo  */
17542dfb1e43SQu Wenruo struct btrfs_root *btrfs_get_fs_root(struct btrfs_fs_info *fs_info,
17552dfb1e43SQu Wenruo 				     u64 objectid, bool check_ref)
17562dfb1e43SQu Wenruo {
17572dfb1e43SQu Wenruo 	return btrfs_get_root_ref(fs_info, objectid, 0, check_ref);
17582dfb1e43SQu Wenruo }
17592dfb1e43SQu Wenruo 
17602dfb1e43SQu Wenruo /*
17612dfb1e43SQu Wenruo  * Get in-memory reference of a root structure, created as new, optionally pass
17622dfb1e43SQu Wenruo  * the anonymous block device id
17632dfb1e43SQu Wenruo  *
17642dfb1e43SQu Wenruo  * @objectid:	tree objectid
17652dfb1e43SQu Wenruo  * @anon_dev:	if zero, allocate a new anonymous block device or use the
17662dfb1e43SQu Wenruo  *		parameter value
17672dfb1e43SQu Wenruo  */
17682dfb1e43SQu Wenruo struct btrfs_root *btrfs_get_new_fs_root(struct btrfs_fs_info *fs_info,
17692dfb1e43SQu Wenruo 					 u64 objectid, dev_t anon_dev)
17702dfb1e43SQu Wenruo {
17712dfb1e43SQu Wenruo 	return btrfs_get_root_ref(fs_info, objectid, anon_dev, true);
17722dfb1e43SQu Wenruo }
17732dfb1e43SQu Wenruo 
17748b712842SChris Mason /*
177549d11beaSJosef Bacik  * btrfs_get_fs_root_commit_root - return a root for the given objectid
177649d11beaSJosef Bacik  * @fs_info:	the fs_info
177749d11beaSJosef Bacik  * @objectid:	the objectid we need to lookup
177849d11beaSJosef Bacik  *
177949d11beaSJosef Bacik  * This is exclusively used for backref walking, and exists specifically because
178049d11beaSJosef Bacik  * of how qgroups does lookups.  Qgroups will do a backref lookup at delayed ref
178149d11beaSJosef Bacik  * creation time, which means we may have to read the tree_root in order to look
178249d11beaSJosef Bacik  * up a fs root that is not in memory.  If the root is not in memory we will
178349d11beaSJosef Bacik  * read the tree root commit root and look up the fs root from there.  This is a
178449d11beaSJosef Bacik  * temporary root, it will not be inserted into the radix tree as it doesn't
178549d11beaSJosef Bacik  * have the most uptodate information, it'll simply be discarded once the
178649d11beaSJosef Bacik  * backref code is finished using the root.
178749d11beaSJosef Bacik  */
178849d11beaSJosef Bacik struct btrfs_root *btrfs_get_fs_root_commit_root(struct btrfs_fs_info *fs_info,
178949d11beaSJosef Bacik 						 struct btrfs_path *path,
179049d11beaSJosef Bacik 						 u64 objectid)
179149d11beaSJosef Bacik {
179249d11beaSJosef Bacik 	struct btrfs_root *root;
179349d11beaSJosef Bacik 	struct btrfs_key key;
179449d11beaSJosef Bacik 
179549d11beaSJosef Bacik 	ASSERT(path->search_commit_root && path->skip_locking);
179649d11beaSJosef Bacik 
179749d11beaSJosef Bacik 	/*
179849d11beaSJosef Bacik 	 * This can return -ENOENT if we ask for a root that doesn't exist, but
179949d11beaSJosef Bacik 	 * since this is called via the backref walking code we won't be looking
180049d11beaSJosef Bacik 	 * up a root that doesn't exist, unless there's corruption.  So if root
180149d11beaSJosef Bacik 	 * != NULL just return it.
180249d11beaSJosef Bacik 	 */
180349d11beaSJosef Bacik 	root = btrfs_get_global_root(fs_info, objectid);
180449d11beaSJosef Bacik 	if (root)
180549d11beaSJosef Bacik 		return root;
180649d11beaSJosef Bacik 
180749d11beaSJosef Bacik 	root = btrfs_lookup_fs_root(fs_info, objectid);
180849d11beaSJosef Bacik 	if (root)
180949d11beaSJosef Bacik 		return root;
181049d11beaSJosef Bacik 
181149d11beaSJosef Bacik 	key.objectid = objectid;
181249d11beaSJosef Bacik 	key.type = BTRFS_ROOT_ITEM_KEY;
181349d11beaSJosef Bacik 	key.offset = (u64)-1;
181449d11beaSJosef Bacik 	root = read_tree_root_path(fs_info->tree_root, path, &key);
181549d11beaSJosef Bacik 	btrfs_release_path(path);
181649d11beaSJosef Bacik 
181749d11beaSJosef Bacik 	return root;
181849d11beaSJosef Bacik }
181949d11beaSJosef Bacik 
182049d11beaSJosef Bacik /*
18218b712842SChris Mason  * called by the kthread helper functions to finally call the bio end_io
18228b712842SChris Mason  * functions.  This is where read checksum verification actually happens
18238b712842SChris Mason  */
18248b712842SChris Mason static void end_workqueue_fn(struct btrfs_work *work)
1825ce9adaa5SChris Mason {
1826ce9adaa5SChris Mason 	struct bio *bio;
182797eb6b69SDavid Sterba 	struct btrfs_end_io_wq *end_io_wq;
1828ce9adaa5SChris Mason 
182997eb6b69SDavid Sterba 	end_io_wq = container_of(work, struct btrfs_end_io_wq, work);
1830ce9adaa5SChris Mason 	bio = end_io_wq->bio;
18318b712842SChris Mason 
18324e4cbee9SChristoph Hellwig 	bio->bi_status = end_io_wq->status;
1833ce9adaa5SChris Mason 	bio->bi_private = end_io_wq->private;
1834ce9adaa5SChris Mason 	bio->bi_end_io = end_io_wq->end_io;
18354246a0b6SChristoph Hellwig 	bio_endio(bio);
18369be490f1SOmar Sandoval 	kmem_cache_free(btrfs_end_io_wq_cache, end_io_wq);
1837ce9adaa5SChris Mason }
183844b8bd7eSChris Mason 
1839a74a4b97SChris Mason static int cleaner_kthread(void *arg)
1840a74a4b97SChris Mason {
1841a74a4b97SChris Mason 	struct btrfs_root *root = arg;
18420b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
1843d0278245SMiao Xie 	int again;
1844a74a4b97SChris Mason 
1845d6fd0ae2SOmar Sandoval 	while (1) {
1846d0278245SMiao Xie 		again = 0;
18479d1a2a3aSDavid Sterba 
1848fd340d0fSJosef Bacik 		set_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags);
1849fd340d0fSJosef Bacik 
1850d0278245SMiao Xie 		/* Make the cleaner go to sleep early. */
18512ff7e61eSJeff Mahoney 		if (btrfs_need_cleaner_sleep(fs_info))
1852d0278245SMiao Xie 			goto sleep;
1853d0278245SMiao Xie 
185490c711abSZygo Blaxell 		/*
185590c711abSZygo Blaxell 		 * Do not do anything if we might cause open_ctree() to block
185690c711abSZygo Blaxell 		 * before we have finished mounting the filesystem.
185790c711abSZygo Blaxell 		 */
18580b246afaSJeff Mahoney 		if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
185990c711abSZygo Blaxell 			goto sleep;
186090c711abSZygo Blaxell 
18610b246afaSJeff Mahoney 		if (!mutex_trylock(&fs_info->cleaner_mutex))
1862d0278245SMiao Xie 			goto sleep;
1863d0278245SMiao Xie 
1864dc7f370cSMiao Xie 		/*
1865dc7f370cSMiao Xie 		 * Avoid the problem that we change the status of the fs
1866dc7f370cSMiao Xie 		 * during the above check and trylock.
1867dc7f370cSMiao Xie 		 */
18682ff7e61eSJeff Mahoney 		if (btrfs_need_cleaner_sleep(fs_info)) {
18690b246afaSJeff Mahoney 			mutex_unlock(&fs_info->cleaner_mutex);
1870dc7f370cSMiao Xie 			goto sleep;
1871dc7f370cSMiao Xie 		}
1872dc7f370cSMiao Xie 
18732ff7e61eSJeff Mahoney 		btrfs_run_delayed_iputs(fs_info);
1874c2d6cb16SFilipe Manana 
18759d1a2a3aSDavid Sterba 		again = btrfs_clean_one_deleted_snapshot(root);
18760b246afaSJeff Mahoney 		mutex_unlock(&fs_info->cleaner_mutex);
1877a74a4b97SChris Mason 
1878d0278245SMiao Xie 		/*
187905323cd1SMiao Xie 		 * The defragger has dealt with the R/O remount and umount,
188005323cd1SMiao Xie 		 * needn't do anything special here.
1881d0278245SMiao Xie 		 */
18820b246afaSJeff Mahoney 		btrfs_run_defrag_inodes(fs_info);
188367c5e7d4SFilipe Manana 
188467c5e7d4SFilipe Manana 		/*
1885f3372065SJohannes Thumshirn 		 * Acquires fs_info->reclaim_bgs_lock to avoid racing
188667c5e7d4SFilipe Manana 		 * with relocation (btrfs_relocate_chunk) and relocation
188767c5e7d4SFilipe Manana 		 * acquires fs_info->cleaner_mutex (btrfs_relocate_block_group)
1888f3372065SJohannes Thumshirn 		 * after acquiring fs_info->reclaim_bgs_lock. So we
188967c5e7d4SFilipe Manana 		 * can't hold, nor need to, fs_info->cleaner_mutex when deleting
189067c5e7d4SFilipe Manana 		 * unused block groups.
189167c5e7d4SFilipe Manana 		 */
18920b246afaSJeff Mahoney 		btrfs_delete_unused_bgs(fs_info);
189318bb8bbfSJohannes Thumshirn 
189418bb8bbfSJohannes Thumshirn 		/*
189518bb8bbfSJohannes Thumshirn 		 * Reclaim block groups in the reclaim_bgs list after we deleted
189618bb8bbfSJohannes Thumshirn 		 * all unused block_groups. This possibly gives us some more free
189718bb8bbfSJohannes Thumshirn 		 * space.
189818bb8bbfSJohannes Thumshirn 		 */
189918bb8bbfSJohannes Thumshirn 		btrfs_reclaim_bgs(fs_info);
1900d0278245SMiao Xie sleep:
1901a0a1db70SFilipe Manana 		clear_and_wake_up_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags);
1902d6fd0ae2SOmar Sandoval 		if (kthread_should_park())
1903d6fd0ae2SOmar Sandoval 			kthread_parkme();
1904d6fd0ae2SOmar Sandoval 		if (kthread_should_stop())
1905d6fd0ae2SOmar Sandoval 			return 0;
1906838fe188SJiri Kosina 		if (!again) {
1907a74a4b97SChris Mason 			set_current_state(TASK_INTERRUPTIBLE);
1908a74a4b97SChris Mason 			schedule();
1909a74a4b97SChris Mason 			__set_current_state(TASK_RUNNING);
1910a74a4b97SChris Mason 		}
1911da288d28SFilipe Manana 	}
1912a74a4b97SChris Mason }
1913a74a4b97SChris Mason 
1914a74a4b97SChris Mason static int transaction_kthread(void *arg)
1915a74a4b97SChris Mason {
1916a74a4b97SChris Mason 	struct btrfs_root *root = arg;
19170b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
1918a74a4b97SChris Mason 	struct btrfs_trans_handle *trans;
1919a74a4b97SChris Mason 	struct btrfs_transaction *cur;
19208929ecfaSYan, Zheng 	u64 transid;
1921643900beSNikolay Borisov 	time64_t delta;
1922a74a4b97SChris Mason 	unsigned long delay;
1923914b2007SJan Kara 	bool cannot_commit;
1924a74a4b97SChris Mason 
1925a74a4b97SChris Mason 	do {
1926914b2007SJan Kara 		cannot_commit = false;
1927ba1bc00fSNikolay Borisov 		delay = msecs_to_jiffies(fs_info->commit_interval * 1000);
19280b246afaSJeff Mahoney 		mutex_lock(&fs_info->transaction_kthread_mutex);
1929a74a4b97SChris Mason 
19300b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
19310b246afaSJeff Mahoney 		cur = fs_info->running_transaction;
1932a74a4b97SChris Mason 		if (!cur) {
19330b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
1934a74a4b97SChris Mason 			goto sleep;
1935a74a4b97SChris Mason 		}
193631153d81SYan Zheng 
1937643900beSNikolay Borisov 		delta = ktime_get_seconds() - cur->start_time;
19383296bf56SQu Wenruo 		if (cur->state < TRANS_STATE_COMMIT_START &&
1939643900beSNikolay Borisov 		    delta < fs_info->commit_interval) {
19400b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
1941fb8a7e94SNikolay Borisov 			delay -= msecs_to_jiffies((delta - 1) * 1000);
1942fb8a7e94SNikolay Borisov 			delay = min(delay,
1943fb8a7e94SNikolay Borisov 				    msecs_to_jiffies(fs_info->commit_interval * 1000));
1944a74a4b97SChris Mason 			goto sleep;
1945a74a4b97SChris Mason 		}
19468929ecfaSYan, Zheng 		transid = cur->transid;
19470b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
194856bec294SChris Mason 
194979787eaaSJeff Mahoney 		/* If the file system is aborted, this will always fail. */
1950354aa0fbSMiao Xie 		trans = btrfs_attach_transaction(root);
1951914b2007SJan Kara 		if (IS_ERR(trans)) {
1952354aa0fbSMiao Xie 			if (PTR_ERR(trans) != -ENOENT)
1953914b2007SJan Kara 				cannot_commit = true;
195479787eaaSJeff Mahoney 			goto sleep;
1955914b2007SJan Kara 		}
19568929ecfaSYan, Zheng 		if (transid == trans->transid) {
19573a45bb20SJeff Mahoney 			btrfs_commit_transaction(trans);
19588929ecfaSYan, Zheng 		} else {
19593a45bb20SJeff Mahoney 			btrfs_end_transaction(trans);
19608929ecfaSYan, Zheng 		}
1961a74a4b97SChris Mason sleep:
19620b246afaSJeff Mahoney 		wake_up_process(fs_info->cleaner_kthread);
19630b246afaSJeff Mahoney 		mutex_unlock(&fs_info->transaction_kthread_mutex);
1964a74a4b97SChris Mason 
196584961539SJosef Bacik 		if (BTRFS_FS_ERROR(fs_info))
19662ff7e61eSJeff Mahoney 			btrfs_cleanup_transaction(fs_info);
19678929ecfaSYan, Zheng 		if (!kthread_should_stop() &&
19680b246afaSJeff Mahoney 				(!btrfs_transaction_blocked(fs_info) ||
1969914b2007SJan Kara 				 cannot_commit))
1970bc5511d0SNikolay Borisov 			schedule_timeout_interruptible(delay);
1971a74a4b97SChris Mason 	} while (!kthread_should_stop());
1972a74a4b97SChris Mason 	return 0;
1973a74a4b97SChris Mason }
1974a74a4b97SChris Mason 
1975af31f5e5SChris Mason /*
197601f0f9daSNikolay Borisov  * This will find the highest generation in the array of root backups.  The
197701f0f9daSNikolay Borisov  * index of the highest array is returned, or -EINVAL if we can't find
197801f0f9daSNikolay Borisov  * anything.
1979af31f5e5SChris Mason  *
1980af31f5e5SChris Mason  * We check to make sure the array is valid by comparing the
1981af31f5e5SChris Mason  * generation of the latest  root in the array with the generation
1982af31f5e5SChris Mason  * in the super block.  If they don't match we pitch it.
1983af31f5e5SChris Mason  */
198401f0f9daSNikolay Borisov static int find_newest_super_backup(struct btrfs_fs_info *info)
1985af31f5e5SChris Mason {
198601f0f9daSNikolay Borisov 	const u64 newest_gen = btrfs_super_generation(info->super_copy);
1987af31f5e5SChris Mason 	u64 cur;
1988af31f5e5SChris Mason 	struct btrfs_root_backup *root_backup;
1989af31f5e5SChris Mason 	int i;
1990af31f5e5SChris Mason 
1991af31f5e5SChris Mason 	for (i = 0; i < BTRFS_NUM_BACKUP_ROOTS; i++) {
1992af31f5e5SChris Mason 		root_backup = info->super_copy->super_roots + i;
1993af31f5e5SChris Mason 		cur = btrfs_backup_tree_root_gen(root_backup);
1994af31f5e5SChris Mason 		if (cur == newest_gen)
199501f0f9daSNikolay Borisov 			return i;
1996af31f5e5SChris Mason 	}
1997af31f5e5SChris Mason 
199801f0f9daSNikolay Borisov 	return -EINVAL;
1999af31f5e5SChris Mason }
2000af31f5e5SChris Mason 
2001af31f5e5SChris Mason /*
2002af31f5e5SChris Mason  * copy all the root pointers into the super backup array.
2003af31f5e5SChris Mason  * this will bump the backup pointer by one when it is
2004af31f5e5SChris Mason  * done
2005af31f5e5SChris Mason  */
2006af31f5e5SChris Mason static void backup_super_roots(struct btrfs_fs_info *info)
2007af31f5e5SChris Mason {
20086ef108ddSNikolay Borisov 	const int next_backup = info->backup_root_index;
2009af31f5e5SChris Mason 	struct btrfs_root_backup *root_backup;
2010af31f5e5SChris Mason 
2011af31f5e5SChris Mason 	root_backup = info->super_for_commit->super_roots + next_backup;
2012af31f5e5SChris Mason 
2013af31f5e5SChris Mason 	/*
2014af31f5e5SChris Mason 	 * make sure all of our padding and empty slots get zero filled
2015af31f5e5SChris Mason 	 * regardless of which ones we use today
2016af31f5e5SChris Mason 	 */
2017af31f5e5SChris Mason 	memset(root_backup, 0, sizeof(*root_backup));
2018af31f5e5SChris Mason 
2019af31f5e5SChris Mason 	info->backup_root_index = (next_backup + 1) % BTRFS_NUM_BACKUP_ROOTS;
2020af31f5e5SChris Mason 
2021af31f5e5SChris Mason 	btrfs_set_backup_tree_root(root_backup, info->tree_root->node->start);
2022af31f5e5SChris Mason 	btrfs_set_backup_tree_root_gen(root_backup,
2023af31f5e5SChris Mason 			       btrfs_header_generation(info->tree_root->node));
2024af31f5e5SChris Mason 
2025af31f5e5SChris Mason 	btrfs_set_backup_tree_root_level(root_backup,
2026af31f5e5SChris Mason 			       btrfs_header_level(info->tree_root->node));
2027af31f5e5SChris Mason 
2028af31f5e5SChris Mason 	btrfs_set_backup_chunk_root(root_backup, info->chunk_root->node->start);
2029af31f5e5SChris Mason 	btrfs_set_backup_chunk_root_gen(root_backup,
2030af31f5e5SChris Mason 			       btrfs_header_generation(info->chunk_root->node));
2031af31f5e5SChris Mason 	btrfs_set_backup_chunk_root_level(root_backup,
2032af31f5e5SChris Mason 			       btrfs_header_level(info->chunk_root->node));
2033af31f5e5SChris Mason 
2034af31f5e5SChris Mason 	btrfs_set_backup_extent_root(root_backup, info->extent_root->node->start);
2035af31f5e5SChris Mason 	btrfs_set_backup_extent_root_gen(root_backup,
2036af31f5e5SChris Mason 			       btrfs_header_generation(info->extent_root->node));
2037af31f5e5SChris Mason 	btrfs_set_backup_extent_root_level(root_backup,
2038af31f5e5SChris Mason 			       btrfs_header_level(info->extent_root->node));
2039af31f5e5SChris Mason 
20407c7e82a7SChris Mason 	/*
20417c7e82a7SChris Mason 	 * we might commit during log recovery, which happens before we set
20427c7e82a7SChris Mason 	 * the fs_root.  Make sure it is valid before we fill it in.
20437c7e82a7SChris Mason 	 */
20447c7e82a7SChris Mason 	if (info->fs_root && info->fs_root->node) {
20457c7e82a7SChris Mason 		btrfs_set_backup_fs_root(root_backup,
20467c7e82a7SChris Mason 					 info->fs_root->node->start);
2047af31f5e5SChris Mason 		btrfs_set_backup_fs_root_gen(root_backup,
2048af31f5e5SChris Mason 			       btrfs_header_generation(info->fs_root->node));
2049af31f5e5SChris Mason 		btrfs_set_backup_fs_root_level(root_backup,
2050af31f5e5SChris Mason 			       btrfs_header_level(info->fs_root->node));
20517c7e82a7SChris Mason 	}
2052af31f5e5SChris Mason 
2053af31f5e5SChris Mason 	btrfs_set_backup_dev_root(root_backup, info->dev_root->node->start);
2054af31f5e5SChris Mason 	btrfs_set_backup_dev_root_gen(root_backup,
2055af31f5e5SChris Mason 			       btrfs_header_generation(info->dev_root->node));
2056af31f5e5SChris Mason 	btrfs_set_backup_dev_root_level(root_backup,
2057af31f5e5SChris Mason 				       btrfs_header_level(info->dev_root->node));
2058af31f5e5SChris Mason 
2059af31f5e5SChris Mason 	btrfs_set_backup_csum_root(root_backup, info->csum_root->node->start);
2060af31f5e5SChris Mason 	btrfs_set_backup_csum_root_gen(root_backup,
2061af31f5e5SChris Mason 			       btrfs_header_generation(info->csum_root->node));
2062af31f5e5SChris Mason 	btrfs_set_backup_csum_root_level(root_backup,
2063af31f5e5SChris Mason 			       btrfs_header_level(info->csum_root->node));
2064af31f5e5SChris Mason 
2065af31f5e5SChris Mason 	btrfs_set_backup_total_bytes(root_backup,
2066af31f5e5SChris Mason 			     btrfs_super_total_bytes(info->super_copy));
2067af31f5e5SChris Mason 	btrfs_set_backup_bytes_used(root_backup,
2068af31f5e5SChris Mason 			     btrfs_super_bytes_used(info->super_copy));
2069af31f5e5SChris Mason 	btrfs_set_backup_num_devices(root_backup,
2070af31f5e5SChris Mason 			     btrfs_super_num_devices(info->super_copy));
2071af31f5e5SChris Mason 
2072af31f5e5SChris Mason 	/*
2073af31f5e5SChris Mason 	 * if we don't copy this out to the super_copy, it won't get remembered
2074af31f5e5SChris Mason 	 * for the next commit
2075af31f5e5SChris Mason 	 */
2076af31f5e5SChris Mason 	memcpy(&info->super_copy->super_roots,
2077af31f5e5SChris Mason 	       &info->super_for_commit->super_roots,
2078af31f5e5SChris Mason 	       sizeof(*root_backup) * BTRFS_NUM_BACKUP_ROOTS);
2079af31f5e5SChris Mason }
2080af31f5e5SChris Mason 
2081af31f5e5SChris Mason /*
2082bd2336b2SNikolay Borisov  * read_backup_root - Reads a backup root based on the passed priority. Prio 0
2083bd2336b2SNikolay Borisov  * is the newest, prio 1/2/3 are 2nd newest/3rd newest/4th (oldest) backup roots
2084bd2336b2SNikolay Borisov  *
2085bd2336b2SNikolay Borisov  * fs_info - filesystem whose backup roots need to be read
2086bd2336b2SNikolay Borisov  * priority - priority of backup root required
2087bd2336b2SNikolay Borisov  *
2088bd2336b2SNikolay Borisov  * Returns backup root index on success and -EINVAL otherwise.
2089bd2336b2SNikolay Borisov  */
2090bd2336b2SNikolay Borisov static int read_backup_root(struct btrfs_fs_info *fs_info, u8 priority)
2091bd2336b2SNikolay Borisov {
2092bd2336b2SNikolay Borisov 	int backup_index = find_newest_super_backup(fs_info);
2093bd2336b2SNikolay Borisov 	struct btrfs_super_block *super = fs_info->super_copy;
2094bd2336b2SNikolay Borisov 	struct btrfs_root_backup *root_backup;
2095bd2336b2SNikolay Borisov 
2096bd2336b2SNikolay Borisov 	if (priority < BTRFS_NUM_BACKUP_ROOTS && backup_index >= 0) {
2097bd2336b2SNikolay Borisov 		if (priority == 0)
2098bd2336b2SNikolay Borisov 			return backup_index;
2099bd2336b2SNikolay Borisov 
2100bd2336b2SNikolay Borisov 		backup_index = backup_index + BTRFS_NUM_BACKUP_ROOTS - priority;
2101bd2336b2SNikolay Borisov 		backup_index %= BTRFS_NUM_BACKUP_ROOTS;
2102bd2336b2SNikolay Borisov 	} else {
2103bd2336b2SNikolay Borisov 		return -EINVAL;
2104bd2336b2SNikolay Borisov 	}
2105bd2336b2SNikolay Borisov 
2106bd2336b2SNikolay Borisov 	root_backup = super->super_roots + backup_index;
2107bd2336b2SNikolay Borisov 
2108bd2336b2SNikolay Borisov 	btrfs_set_super_generation(super,
2109bd2336b2SNikolay Borisov 				   btrfs_backup_tree_root_gen(root_backup));
2110bd2336b2SNikolay Borisov 	btrfs_set_super_root(super, btrfs_backup_tree_root(root_backup));
2111bd2336b2SNikolay Borisov 	btrfs_set_super_root_level(super,
2112bd2336b2SNikolay Borisov 				   btrfs_backup_tree_root_level(root_backup));
2113bd2336b2SNikolay Borisov 	btrfs_set_super_bytes_used(super, btrfs_backup_bytes_used(root_backup));
2114bd2336b2SNikolay Borisov 
2115bd2336b2SNikolay Borisov 	/*
2116bd2336b2SNikolay Borisov 	 * Fixme: the total bytes and num_devices need to match or we should
2117bd2336b2SNikolay Borisov 	 * need a fsck
2118bd2336b2SNikolay Borisov 	 */
2119bd2336b2SNikolay Borisov 	btrfs_set_super_total_bytes(super, btrfs_backup_total_bytes(root_backup));
2120bd2336b2SNikolay Borisov 	btrfs_set_super_num_devices(super, btrfs_backup_num_devices(root_backup));
2121bd2336b2SNikolay Borisov 
2122bd2336b2SNikolay Borisov 	return backup_index;
2123bd2336b2SNikolay Borisov }
2124bd2336b2SNikolay Borisov 
21257abadb64SLiu Bo /* helper to cleanup workers */
21267abadb64SLiu Bo static void btrfs_stop_all_workers(struct btrfs_fs_info *fs_info)
21277abadb64SLiu Bo {
2128dc6e3209SQu Wenruo 	btrfs_destroy_workqueue(fs_info->fixup_workers);
2129afe3d242SQu Wenruo 	btrfs_destroy_workqueue(fs_info->delalloc_workers);
21305cdc7ad3SQu Wenruo 	btrfs_destroy_workqueue(fs_info->workers);
2131fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_workers);
2132fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_raid56_workers);
2133d05a33acSQu Wenruo 	btrfs_destroy_workqueue(fs_info->rmw_workers);
2134fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_write_workers);
2135fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_freespace_worker);
21365b3bc44eSQu Wenruo 	btrfs_destroy_workqueue(fs_info->delayed_workers);
2137e66f0bb1SQu Wenruo 	btrfs_destroy_workqueue(fs_info->caching_workers);
2138736cfa15SQu Wenruo 	btrfs_destroy_workqueue(fs_info->readahead_workers);
2139a44903abSQu Wenruo 	btrfs_destroy_workqueue(fs_info->flush_workers);
2140fc97fab0SQu Wenruo 	btrfs_destroy_workqueue(fs_info->qgroup_rescan_workers);
2141b0643e59SDennis Zhou 	if (fs_info->discard_ctl.discard_workers)
2142b0643e59SDennis Zhou 		destroy_workqueue(fs_info->discard_ctl.discard_workers);
2143a9b9477dSFilipe Manana 	/*
2144a9b9477dSFilipe Manana 	 * Now that all other work queues are destroyed, we can safely destroy
2145a9b9477dSFilipe Manana 	 * the queues used for metadata I/O, since tasks from those other work
2146a9b9477dSFilipe Manana 	 * queues can do metadata I/O operations.
2147a9b9477dSFilipe Manana 	 */
2148a9b9477dSFilipe Manana 	btrfs_destroy_workqueue(fs_info->endio_meta_workers);
2149a9b9477dSFilipe Manana 	btrfs_destroy_workqueue(fs_info->endio_meta_write_workers);
21507abadb64SLiu Bo }
21517abadb64SLiu Bo 
21522e9f5954SRashika static void free_root_extent_buffers(struct btrfs_root *root)
21532e9f5954SRashika {
21542e9f5954SRashika 	if (root) {
21552e9f5954SRashika 		free_extent_buffer(root->node);
21562e9f5954SRashika 		free_extent_buffer(root->commit_root);
21572e9f5954SRashika 		root->node = NULL;
21582e9f5954SRashika 		root->commit_root = NULL;
21592e9f5954SRashika 	}
21602e9f5954SRashika }
21612e9f5954SRashika 
2162af31f5e5SChris Mason /* helper to cleanup tree roots */
21634273eaffSAnand Jain static void free_root_pointers(struct btrfs_fs_info *info, bool free_chunk_root)
2164af31f5e5SChris Mason {
21652e9f5954SRashika 	free_root_extent_buffers(info->tree_root);
2166655b09feSJosef Bacik 
21672e9f5954SRashika 	free_root_extent_buffers(info->dev_root);
21682e9f5954SRashika 	free_root_extent_buffers(info->extent_root);
21692e9f5954SRashika 	free_root_extent_buffers(info->csum_root);
21702e9f5954SRashika 	free_root_extent_buffers(info->quota_root);
21712e9f5954SRashika 	free_root_extent_buffers(info->uuid_root);
21728c38938cSJosef Bacik 	free_root_extent_buffers(info->fs_root);
2173aeb935a4SQu Wenruo 	free_root_extent_buffers(info->data_reloc_root);
21744273eaffSAnand Jain 	if (free_chunk_root)
21752e9f5954SRashika 		free_root_extent_buffers(info->chunk_root);
217670f6d82eSOmar Sandoval 	free_root_extent_buffers(info->free_space_root);
2177af31f5e5SChris Mason }
2178af31f5e5SChris Mason 
21798c38938cSJosef Bacik void btrfs_put_root(struct btrfs_root *root)
21808c38938cSJosef Bacik {
21818c38938cSJosef Bacik 	if (!root)
21828c38938cSJosef Bacik 		return;
21838c38938cSJosef Bacik 
21848c38938cSJosef Bacik 	if (refcount_dec_and_test(&root->refs)) {
21858c38938cSJosef Bacik 		WARN_ON(!RB_EMPTY_ROOT(&root->inode_tree));
21861dae7e0eSQu Wenruo 		WARN_ON(test_bit(BTRFS_ROOT_DEAD_RELOC_TREE, &root->state));
21878c38938cSJosef Bacik 		if (root->anon_dev)
21888c38938cSJosef Bacik 			free_anon_bdev(root->anon_dev);
21898c38938cSJosef Bacik 		btrfs_drew_lock_destroy(&root->snapshot_lock);
2190923eb523SJohannes Thumshirn 		free_root_extent_buffers(root);
21918c38938cSJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
21928c38938cSJosef Bacik 		spin_lock(&root->fs_info->fs_roots_radix_lock);
21938c38938cSJosef Bacik 		list_del_init(&root->leak_list);
21948c38938cSJosef Bacik 		spin_unlock(&root->fs_info->fs_roots_radix_lock);
21958c38938cSJosef Bacik #endif
21968c38938cSJosef Bacik 		kfree(root);
21978c38938cSJosef Bacik 	}
21988c38938cSJosef Bacik }
21998c38938cSJosef Bacik 
2200faa2dbf0SJosef Bacik void btrfs_free_fs_roots(struct btrfs_fs_info *fs_info)
2201171f6537SJosef Bacik {
2202171f6537SJosef Bacik 	int ret;
2203171f6537SJosef Bacik 	struct btrfs_root *gang[8];
2204171f6537SJosef Bacik 	int i;
2205171f6537SJosef Bacik 
2206171f6537SJosef Bacik 	while (!list_empty(&fs_info->dead_roots)) {
2207171f6537SJosef Bacik 		gang[0] = list_entry(fs_info->dead_roots.next,
2208171f6537SJosef Bacik 				     struct btrfs_root, root_list);
2209171f6537SJosef Bacik 		list_del(&gang[0]->root_list);
2210171f6537SJosef Bacik 
22118c38938cSJosef Bacik 		if (test_bit(BTRFS_ROOT_IN_RADIX, &gang[0]->state))
2212cb517eabSMiao Xie 			btrfs_drop_and_free_fs_root(fs_info, gang[0]);
221300246528SJosef Bacik 		btrfs_put_root(gang[0]);
2214171f6537SJosef Bacik 	}
2215171f6537SJosef Bacik 
2216171f6537SJosef Bacik 	while (1) {
2217171f6537SJosef Bacik 		ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
2218171f6537SJosef Bacik 					     (void **)gang, 0,
2219171f6537SJosef Bacik 					     ARRAY_SIZE(gang));
2220171f6537SJosef Bacik 		if (!ret)
2221171f6537SJosef Bacik 			break;
2222171f6537SJosef Bacik 		for (i = 0; i < ret; i++)
2223cb517eabSMiao Xie 			btrfs_drop_and_free_fs_root(fs_info, gang[i]);
2224171f6537SJosef Bacik 	}
2225171f6537SJosef Bacik }
2226af31f5e5SChris Mason 
2227638aa7edSEric Sandeen static void btrfs_init_scrub(struct btrfs_fs_info *fs_info)
2228638aa7edSEric Sandeen {
2229638aa7edSEric Sandeen 	mutex_init(&fs_info->scrub_lock);
2230638aa7edSEric Sandeen 	atomic_set(&fs_info->scrubs_running, 0);
2231638aa7edSEric Sandeen 	atomic_set(&fs_info->scrub_pause_req, 0);
2232638aa7edSEric Sandeen 	atomic_set(&fs_info->scrubs_paused, 0);
2233638aa7edSEric Sandeen 	atomic_set(&fs_info->scrub_cancel_req, 0);
2234638aa7edSEric Sandeen 	init_waitqueue_head(&fs_info->scrub_pause_wait);
2235ff09c4caSAnand Jain 	refcount_set(&fs_info->scrub_workers_refcnt, 0);
2236638aa7edSEric Sandeen }
2237638aa7edSEric Sandeen 
2238779a65a4SEric Sandeen static void btrfs_init_balance(struct btrfs_fs_info *fs_info)
2239779a65a4SEric Sandeen {
2240779a65a4SEric Sandeen 	spin_lock_init(&fs_info->balance_lock);
2241779a65a4SEric Sandeen 	mutex_init(&fs_info->balance_mutex);
2242779a65a4SEric Sandeen 	atomic_set(&fs_info->balance_pause_req, 0);
2243779a65a4SEric Sandeen 	atomic_set(&fs_info->balance_cancel_req, 0);
2244779a65a4SEric Sandeen 	fs_info->balance_ctl = NULL;
2245779a65a4SEric Sandeen 	init_waitqueue_head(&fs_info->balance_wait_q);
2246907d2710SDavid Sterba 	atomic_set(&fs_info->reloc_cancel_req, 0);
2247779a65a4SEric Sandeen }
2248779a65a4SEric Sandeen 
22496bccf3abSJeff Mahoney static void btrfs_init_btree_inode(struct btrfs_fs_info *fs_info)
2250f37938e0SEric Sandeen {
22512ff7e61eSJeff Mahoney 	struct inode *inode = fs_info->btree_inode;
22522ff7e61eSJeff Mahoney 
22532ff7e61eSJeff Mahoney 	inode->i_ino = BTRFS_BTREE_INODE_OBJECTID;
22542ff7e61eSJeff Mahoney 	set_nlink(inode, 1);
2255f37938e0SEric Sandeen 	/*
2256f37938e0SEric Sandeen 	 * we set the i_size on the btree inode to the max possible int.
2257f37938e0SEric Sandeen 	 * the real end of the address space is determined by all of
2258f37938e0SEric Sandeen 	 * the devices in the system
2259f37938e0SEric Sandeen 	 */
22602ff7e61eSJeff Mahoney 	inode->i_size = OFFSET_MAX;
22612ff7e61eSJeff Mahoney 	inode->i_mapping->a_ops = &btree_aops;
2262f37938e0SEric Sandeen 
22632ff7e61eSJeff Mahoney 	RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
226443eb5f29SQu Wenruo 	extent_io_tree_init(fs_info, &BTRFS_I(inode)->io_tree,
22652c53a14dSQu Wenruo 			    IO_TREE_BTREE_INODE_IO, inode);
22667b439738SDavid Sterba 	BTRFS_I(inode)->io_tree.track_uptodate = false;
22672ff7e61eSJeff Mahoney 	extent_map_tree_init(&BTRFS_I(inode)->extent_tree);
2268f37938e0SEric Sandeen 
22695c8fd99fSJosef Bacik 	BTRFS_I(inode)->root = btrfs_grab_root(fs_info->tree_root);
22702ff7e61eSJeff Mahoney 	memset(&BTRFS_I(inode)->location, 0, sizeof(struct btrfs_key));
22712ff7e61eSJeff Mahoney 	set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
22722ff7e61eSJeff Mahoney 	btrfs_insert_inode_hash(inode);
2273f37938e0SEric Sandeen }
2274f37938e0SEric Sandeen 
2275ad618368SEric Sandeen static void btrfs_init_dev_replace_locks(struct btrfs_fs_info *fs_info)
2276ad618368SEric Sandeen {
2277ad618368SEric Sandeen 	mutex_init(&fs_info->dev_replace.lock_finishing_cancel_unmount);
2278129827e3SDavid Sterba 	init_rwsem(&fs_info->dev_replace.rwsem);
22797f8d236aSDavid Sterba 	init_waitqueue_head(&fs_info->dev_replace.replace_wait);
2280ad618368SEric Sandeen }
2281ad618368SEric Sandeen 
2282f9e92e40SEric Sandeen static void btrfs_init_qgroup(struct btrfs_fs_info *fs_info)
2283f9e92e40SEric Sandeen {
2284f9e92e40SEric Sandeen 	spin_lock_init(&fs_info->qgroup_lock);
2285f9e92e40SEric Sandeen 	mutex_init(&fs_info->qgroup_ioctl_lock);
2286f9e92e40SEric Sandeen 	fs_info->qgroup_tree = RB_ROOT;
2287f9e92e40SEric Sandeen 	INIT_LIST_HEAD(&fs_info->dirty_qgroups);
2288f9e92e40SEric Sandeen 	fs_info->qgroup_seq = 1;
2289f9e92e40SEric Sandeen 	fs_info->qgroup_ulist = NULL;
2290d2c609b8SJeff Mahoney 	fs_info->qgroup_rescan_running = false;
2291f9e92e40SEric Sandeen 	mutex_init(&fs_info->qgroup_rescan_lock);
2292f9e92e40SEric Sandeen }
2293f9e92e40SEric Sandeen 
2294d21deec5SSu Yue static int btrfs_init_workqueues(struct btrfs_fs_info *fs_info)
22952a458198SEric Sandeen {
2296f7b885beSAnand Jain 	u32 max_active = fs_info->thread_pool_size;
22976f011058SDavid Sterba 	unsigned int flags = WQ_MEM_RECLAIM | WQ_FREEZABLE | WQ_UNBOUND;
22982a458198SEric Sandeen 
22992a458198SEric Sandeen 	fs_info->workers =
2300cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "worker",
2301cb001095SJeff Mahoney 				      flags | WQ_HIGHPRI, max_active, 16);
23022a458198SEric Sandeen 
23032a458198SEric Sandeen 	fs_info->delalloc_workers =
2304cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "delalloc",
2305cb001095SJeff Mahoney 				      flags, max_active, 2);
23062a458198SEric Sandeen 
23072a458198SEric Sandeen 	fs_info->flush_workers =
2308cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "flush_delalloc",
2309cb001095SJeff Mahoney 				      flags, max_active, 0);
23102a458198SEric Sandeen 
23112a458198SEric Sandeen 	fs_info->caching_workers =
2312cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "cache", flags, max_active, 0);
23132a458198SEric Sandeen 
23142a458198SEric Sandeen 	fs_info->fixup_workers =
2315cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "fixup", flags, 1, 0);
23162a458198SEric Sandeen 
23172a458198SEric Sandeen 	/*
23182a458198SEric Sandeen 	 * endios are largely parallel and should have a very
23192a458198SEric Sandeen 	 * low idle thresh
23202a458198SEric Sandeen 	 */
23212a458198SEric Sandeen 	fs_info->endio_workers =
2322cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio", flags, max_active, 4);
23232a458198SEric Sandeen 	fs_info->endio_meta_workers =
2324cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio-meta", flags,
2325cb001095SJeff Mahoney 				      max_active, 4);
23262a458198SEric Sandeen 	fs_info->endio_meta_write_workers =
2327cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio-meta-write", flags,
2328cb001095SJeff Mahoney 				      max_active, 2);
23292a458198SEric Sandeen 	fs_info->endio_raid56_workers =
2330cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio-raid56", flags,
2331cb001095SJeff Mahoney 				      max_active, 4);
23322a458198SEric Sandeen 	fs_info->rmw_workers =
2333cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "rmw", flags, max_active, 2);
23342a458198SEric Sandeen 	fs_info->endio_write_workers =
2335cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio-write", flags,
2336cb001095SJeff Mahoney 				      max_active, 2);
23372a458198SEric Sandeen 	fs_info->endio_freespace_worker =
2338cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "freespace-write", flags,
2339cb001095SJeff Mahoney 				      max_active, 0);
23402a458198SEric Sandeen 	fs_info->delayed_workers =
2341cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "delayed-meta", flags,
2342cb001095SJeff Mahoney 				      max_active, 0);
23432a458198SEric Sandeen 	fs_info->readahead_workers =
2344cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "readahead", flags,
2345cb001095SJeff Mahoney 				      max_active, 2);
23462a458198SEric Sandeen 	fs_info->qgroup_rescan_workers =
2347cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "qgroup-rescan", flags, 1, 0);
2348b0643e59SDennis Zhou 	fs_info->discard_ctl.discard_workers =
2349b0643e59SDennis Zhou 		alloc_workqueue("btrfs_discard", WQ_UNBOUND | WQ_FREEZABLE, 1);
23502a458198SEric Sandeen 
23512a458198SEric Sandeen 	if (!(fs_info->workers && fs_info->delalloc_workers &&
2352ba8a9d07SChris Mason 	      fs_info->flush_workers &&
23532a458198SEric Sandeen 	      fs_info->endio_workers && fs_info->endio_meta_workers &&
23542a458198SEric Sandeen 	      fs_info->endio_meta_write_workers &&
23552a458198SEric Sandeen 	      fs_info->endio_write_workers && fs_info->endio_raid56_workers &&
23562a458198SEric Sandeen 	      fs_info->endio_freespace_worker && fs_info->rmw_workers &&
23572a458198SEric Sandeen 	      fs_info->caching_workers && fs_info->readahead_workers &&
23582a458198SEric Sandeen 	      fs_info->fixup_workers && fs_info->delayed_workers &&
2359b0643e59SDennis Zhou 	      fs_info->qgroup_rescan_workers &&
2360b0643e59SDennis Zhou 	      fs_info->discard_ctl.discard_workers)) {
23612a458198SEric Sandeen 		return -ENOMEM;
23622a458198SEric Sandeen 	}
23632a458198SEric Sandeen 
23642a458198SEric Sandeen 	return 0;
23652a458198SEric Sandeen }
23662a458198SEric Sandeen 
23676d97c6e3SJohannes Thumshirn static int btrfs_init_csum_hash(struct btrfs_fs_info *fs_info, u16 csum_type)
23686d97c6e3SJohannes Thumshirn {
23696d97c6e3SJohannes Thumshirn 	struct crypto_shash *csum_shash;
2370b4e967beSDavid Sterba 	const char *csum_driver = btrfs_super_csum_driver(csum_type);
23716d97c6e3SJohannes Thumshirn 
2372b4e967beSDavid Sterba 	csum_shash = crypto_alloc_shash(csum_driver, 0, 0);
23736d97c6e3SJohannes Thumshirn 
23746d97c6e3SJohannes Thumshirn 	if (IS_ERR(csum_shash)) {
23756d97c6e3SJohannes Thumshirn 		btrfs_err(fs_info, "error allocating %s hash for checksum",
2376b4e967beSDavid Sterba 			  csum_driver);
23776d97c6e3SJohannes Thumshirn 		return PTR_ERR(csum_shash);
23786d97c6e3SJohannes Thumshirn 	}
23796d97c6e3SJohannes Thumshirn 
23806d97c6e3SJohannes Thumshirn 	fs_info->csum_shash = csum_shash;
23816d97c6e3SJohannes Thumshirn 
23826d97c6e3SJohannes Thumshirn 	return 0;
23836d97c6e3SJohannes Thumshirn }
23846d97c6e3SJohannes Thumshirn 
238563443bf5SEric Sandeen static int btrfs_replay_log(struct btrfs_fs_info *fs_info,
238663443bf5SEric Sandeen 			    struct btrfs_fs_devices *fs_devices)
238763443bf5SEric Sandeen {
238863443bf5SEric Sandeen 	int ret;
238963443bf5SEric Sandeen 	struct btrfs_root *log_tree_root;
239063443bf5SEric Sandeen 	struct btrfs_super_block *disk_super = fs_info->super_copy;
239163443bf5SEric Sandeen 	u64 bytenr = btrfs_super_log_root(disk_super);
2392581c1760SQu Wenruo 	int level = btrfs_super_log_root_level(disk_super);
239363443bf5SEric Sandeen 
239463443bf5SEric Sandeen 	if (fs_devices->rw_devices == 0) {
2395f14d104dSDavid Sterba 		btrfs_warn(fs_info, "log replay required on RO media");
239663443bf5SEric Sandeen 		return -EIO;
239763443bf5SEric Sandeen 	}
239863443bf5SEric Sandeen 
239996dfcb46SJosef Bacik 	log_tree_root = btrfs_alloc_root(fs_info, BTRFS_TREE_LOG_OBJECTID,
240096dfcb46SJosef Bacik 					 GFP_KERNEL);
240163443bf5SEric Sandeen 	if (!log_tree_root)
240263443bf5SEric Sandeen 		return -ENOMEM;
240363443bf5SEric Sandeen 
24042ff7e61eSJeff Mahoney 	log_tree_root->node = read_tree_block(fs_info, bytenr,
24051b7ec85eSJosef Bacik 					      BTRFS_TREE_LOG_OBJECTID,
24061b7ec85eSJosef Bacik 					      fs_info->generation + 1, level,
24071b7ec85eSJosef Bacik 					      NULL);
240864c043deSLiu Bo 	if (IS_ERR(log_tree_root->node)) {
2409f14d104dSDavid Sterba 		btrfs_warn(fs_info, "failed to read log tree");
24100eeff236SLiu Bo 		ret = PTR_ERR(log_tree_root->node);
24118c38938cSJosef Bacik 		log_tree_root->node = NULL;
241200246528SJosef Bacik 		btrfs_put_root(log_tree_root);
24130eeff236SLiu Bo 		return ret;
241464c043deSLiu Bo 	} else if (!extent_buffer_uptodate(log_tree_root->node)) {
2415f14d104dSDavid Sterba 		btrfs_err(fs_info, "failed to read log tree");
241600246528SJosef Bacik 		btrfs_put_root(log_tree_root);
241763443bf5SEric Sandeen 		return -EIO;
241863443bf5SEric Sandeen 	}
241963443bf5SEric Sandeen 	/* returns with log_tree_root freed on success */
242063443bf5SEric Sandeen 	ret = btrfs_recover_log_trees(log_tree_root);
242163443bf5SEric Sandeen 	if (ret) {
24220b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, ret,
242363443bf5SEric Sandeen 				      "Failed to recover log tree");
242400246528SJosef Bacik 		btrfs_put_root(log_tree_root);
242563443bf5SEric Sandeen 		return ret;
242663443bf5SEric Sandeen 	}
242763443bf5SEric Sandeen 
2428bc98a42cSDavid Howells 	if (sb_rdonly(fs_info->sb)) {
24296bccf3abSJeff Mahoney 		ret = btrfs_commit_super(fs_info);
243063443bf5SEric Sandeen 		if (ret)
243163443bf5SEric Sandeen 			return ret;
243263443bf5SEric Sandeen 	}
243363443bf5SEric Sandeen 
243463443bf5SEric Sandeen 	return 0;
243563443bf5SEric Sandeen }
243663443bf5SEric Sandeen 
24376bccf3abSJeff Mahoney static int btrfs_read_roots(struct btrfs_fs_info *fs_info)
24384bbcaa64SEric Sandeen {
24396bccf3abSJeff Mahoney 	struct btrfs_root *tree_root = fs_info->tree_root;
2440a4f3d2c4SDavid Sterba 	struct btrfs_root *root;
24414bbcaa64SEric Sandeen 	struct btrfs_key location;
24424bbcaa64SEric Sandeen 	int ret;
24434bbcaa64SEric Sandeen 
24446bccf3abSJeff Mahoney 	BUG_ON(!fs_info->tree_root);
24456bccf3abSJeff Mahoney 
24464bbcaa64SEric Sandeen 	location.objectid = BTRFS_EXTENT_TREE_OBJECTID;
24474bbcaa64SEric Sandeen 	location.type = BTRFS_ROOT_ITEM_KEY;
24484bbcaa64SEric Sandeen 	location.offset = 0;
24494bbcaa64SEric Sandeen 
2450a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2451f50f4353SLiu Bo 	if (IS_ERR(root)) {
245242437a63SJosef Bacik 		if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2453f50f4353SLiu Bo 			ret = PTR_ERR(root);
2454f50f4353SLiu Bo 			goto out;
2455f50f4353SLiu Bo 		}
245642437a63SJosef Bacik 	} else {
2457a4f3d2c4SDavid Sterba 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2458a4f3d2c4SDavid Sterba 		fs_info->extent_root = root;
245942437a63SJosef Bacik 	}
24604bbcaa64SEric Sandeen 
24614bbcaa64SEric Sandeen 	location.objectid = BTRFS_DEV_TREE_OBJECTID;
2462a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2463f50f4353SLiu Bo 	if (IS_ERR(root)) {
246442437a63SJosef Bacik 		if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2465f50f4353SLiu Bo 			ret = PTR_ERR(root);
2466f50f4353SLiu Bo 			goto out;
2467f50f4353SLiu Bo 		}
246842437a63SJosef Bacik 	} else {
2469a4f3d2c4SDavid Sterba 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2470a4f3d2c4SDavid Sterba 		fs_info->dev_root = root;
247142437a63SJosef Bacik 	}
2472820a49daSJosef Bacik 	/* Initialize fs_info for all devices in any case */
2473820a49daSJosef Bacik 	btrfs_init_devices_late(fs_info);
24744bbcaa64SEric Sandeen 
2475882dbe0cSJosef Bacik 	/* If IGNOREDATACSUMS is set don't bother reading the csum root. */
2476882dbe0cSJosef Bacik 	if (!btrfs_test_opt(fs_info, IGNOREDATACSUMS)) {
24774bbcaa64SEric Sandeen 		location.objectid = BTRFS_CSUM_TREE_OBJECTID;
2478a4f3d2c4SDavid Sterba 		root = btrfs_read_tree_root(tree_root, &location);
2479f50f4353SLiu Bo 		if (IS_ERR(root)) {
248042437a63SJosef Bacik 			if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2481f50f4353SLiu Bo 				ret = PTR_ERR(root);
2482f50f4353SLiu Bo 				goto out;
2483f50f4353SLiu Bo 			}
248442437a63SJosef Bacik 		} else {
2485a4f3d2c4SDavid Sterba 			set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2486a4f3d2c4SDavid Sterba 			fs_info->csum_root = root;
248742437a63SJosef Bacik 		}
2488882dbe0cSJosef Bacik 	}
24894bbcaa64SEric Sandeen 
2490aeb935a4SQu Wenruo 	/*
2491aeb935a4SQu Wenruo 	 * This tree can share blocks with some other fs tree during relocation
2492aeb935a4SQu Wenruo 	 * and we need a proper setup by btrfs_get_fs_root
2493aeb935a4SQu Wenruo 	 */
249456e9357aSDavid Sterba 	root = btrfs_get_fs_root(tree_root->fs_info,
249556e9357aSDavid Sterba 				 BTRFS_DATA_RELOC_TREE_OBJECTID, true);
2496aeb935a4SQu Wenruo 	if (IS_ERR(root)) {
249742437a63SJosef Bacik 		if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2498aeb935a4SQu Wenruo 			ret = PTR_ERR(root);
2499aeb935a4SQu Wenruo 			goto out;
2500aeb935a4SQu Wenruo 		}
250142437a63SJosef Bacik 	} else {
2502aeb935a4SQu Wenruo 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2503aeb935a4SQu Wenruo 		fs_info->data_reloc_root = root;
250442437a63SJosef Bacik 	}
2505aeb935a4SQu Wenruo 
25064bbcaa64SEric Sandeen 	location.objectid = BTRFS_QUOTA_TREE_OBJECTID;
2507a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2508a4f3d2c4SDavid Sterba 	if (!IS_ERR(root)) {
2509a4f3d2c4SDavid Sterba 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2510afcdd129SJosef Bacik 		set_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags);
2511a4f3d2c4SDavid Sterba 		fs_info->quota_root = root;
25124bbcaa64SEric Sandeen 	}
25134bbcaa64SEric Sandeen 
25144bbcaa64SEric Sandeen 	location.objectid = BTRFS_UUID_TREE_OBJECTID;
2515a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2516a4f3d2c4SDavid Sterba 	if (IS_ERR(root)) {
251742437a63SJosef Bacik 		if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2518a4f3d2c4SDavid Sterba 			ret = PTR_ERR(root);
25194bbcaa64SEric Sandeen 			if (ret != -ENOENT)
2520f50f4353SLiu Bo 				goto out;
252142437a63SJosef Bacik 		}
25224bbcaa64SEric Sandeen 	} else {
2523a4f3d2c4SDavid Sterba 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2524a4f3d2c4SDavid Sterba 		fs_info->uuid_root = root;
25254bbcaa64SEric Sandeen 	}
25264bbcaa64SEric Sandeen 
252770f6d82eSOmar Sandoval 	if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
252870f6d82eSOmar Sandoval 		location.objectid = BTRFS_FREE_SPACE_TREE_OBJECTID;
252970f6d82eSOmar Sandoval 		root = btrfs_read_tree_root(tree_root, &location);
2530f50f4353SLiu Bo 		if (IS_ERR(root)) {
253142437a63SJosef Bacik 			if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2532f50f4353SLiu Bo 				ret = PTR_ERR(root);
2533f50f4353SLiu Bo 				goto out;
2534f50f4353SLiu Bo 			}
253542437a63SJosef Bacik 		}  else {
253670f6d82eSOmar Sandoval 			set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
253770f6d82eSOmar Sandoval 			fs_info->free_space_root = root;
253870f6d82eSOmar Sandoval 		}
253942437a63SJosef Bacik 	}
254070f6d82eSOmar Sandoval 
25414bbcaa64SEric Sandeen 	return 0;
2542f50f4353SLiu Bo out:
2543f50f4353SLiu Bo 	btrfs_warn(fs_info, "failed to read root (objectid=%llu): %d",
2544f50f4353SLiu Bo 		   location.objectid, ret);
2545f50f4353SLiu Bo 	return ret;
25464bbcaa64SEric Sandeen }
25474bbcaa64SEric Sandeen 
2548069ec957SQu Wenruo /*
2549069ec957SQu Wenruo  * Real super block validation
2550069ec957SQu Wenruo  * NOTE: super csum type and incompat features will not be checked here.
2551069ec957SQu Wenruo  *
2552069ec957SQu Wenruo  * @sb:		super block to check
2553069ec957SQu Wenruo  * @mirror_num:	the super block number to check its bytenr:
2554069ec957SQu Wenruo  * 		0	the primary (1st) sb
2555069ec957SQu Wenruo  * 		1, 2	2nd and 3rd backup copy
2556069ec957SQu Wenruo  * 	       -1	skip bytenr check
2557069ec957SQu Wenruo  */
2558069ec957SQu Wenruo static int validate_super(struct btrfs_fs_info *fs_info,
2559069ec957SQu Wenruo 			    struct btrfs_super_block *sb, int mirror_num)
256021a852b0SQu Wenruo {
256121a852b0SQu Wenruo 	u64 nodesize = btrfs_super_nodesize(sb);
256221a852b0SQu Wenruo 	u64 sectorsize = btrfs_super_sectorsize(sb);
256321a852b0SQu Wenruo 	int ret = 0;
256421a852b0SQu Wenruo 
256521a852b0SQu Wenruo 	if (btrfs_super_magic(sb) != BTRFS_MAGIC) {
256621a852b0SQu Wenruo 		btrfs_err(fs_info, "no valid FS found");
256721a852b0SQu Wenruo 		ret = -EINVAL;
256821a852b0SQu Wenruo 	}
256921a852b0SQu Wenruo 	if (btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP) {
257021a852b0SQu Wenruo 		btrfs_err(fs_info, "unrecognized or unsupported super flag: %llu",
257121a852b0SQu Wenruo 				btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP);
257221a852b0SQu Wenruo 		ret = -EINVAL;
257321a852b0SQu Wenruo 	}
257421a852b0SQu Wenruo 	if (btrfs_super_root_level(sb) >= BTRFS_MAX_LEVEL) {
257521a852b0SQu Wenruo 		btrfs_err(fs_info, "tree_root level too big: %d >= %d",
257621a852b0SQu Wenruo 				btrfs_super_root_level(sb), BTRFS_MAX_LEVEL);
257721a852b0SQu Wenruo 		ret = -EINVAL;
257821a852b0SQu Wenruo 	}
257921a852b0SQu Wenruo 	if (btrfs_super_chunk_root_level(sb) >= BTRFS_MAX_LEVEL) {
258021a852b0SQu Wenruo 		btrfs_err(fs_info, "chunk_root level too big: %d >= %d",
258121a852b0SQu Wenruo 				btrfs_super_chunk_root_level(sb), BTRFS_MAX_LEVEL);
258221a852b0SQu Wenruo 		ret = -EINVAL;
258321a852b0SQu Wenruo 	}
258421a852b0SQu Wenruo 	if (btrfs_super_log_root_level(sb) >= BTRFS_MAX_LEVEL) {
258521a852b0SQu Wenruo 		btrfs_err(fs_info, "log_root level too big: %d >= %d",
258621a852b0SQu Wenruo 				btrfs_super_log_root_level(sb), BTRFS_MAX_LEVEL);
258721a852b0SQu Wenruo 		ret = -EINVAL;
258821a852b0SQu Wenruo 	}
258921a852b0SQu Wenruo 
259021a852b0SQu Wenruo 	/*
259121a852b0SQu Wenruo 	 * Check sectorsize and nodesize first, other check will need it.
259221a852b0SQu Wenruo 	 * Check all possible sectorsize(4K, 8K, 16K, 32K, 64K) here.
259321a852b0SQu Wenruo 	 */
259421a852b0SQu Wenruo 	if (!is_power_of_2(sectorsize) || sectorsize < 4096 ||
259521a852b0SQu Wenruo 	    sectorsize > BTRFS_MAX_METADATA_BLOCKSIZE) {
259621a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid sectorsize %llu", sectorsize);
259721a852b0SQu Wenruo 		ret = -EINVAL;
259821a852b0SQu Wenruo 	}
25990bb3eb3eSQu Wenruo 
26000bb3eb3eSQu Wenruo 	/*
26010bb3eb3eSQu Wenruo 	 * For 4K page size, we only support 4K sector size.
260250780d9bSAnand Jain 	 * For 64K page size, we support 64K and 4K sector sizes.
26030bb3eb3eSQu Wenruo 	 */
26040bb3eb3eSQu Wenruo 	if ((PAGE_SIZE == SZ_4K && sectorsize != PAGE_SIZE) ||
26050bb3eb3eSQu Wenruo 	    (PAGE_SIZE == SZ_64K && (sectorsize != SZ_4K &&
26060bb3eb3eSQu Wenruo 				     sectorsize != SZ_64K))) {
260721a852b0SQu Wenruo 		btrfs_err(fs_info,
26080bb3eb3eSQu Wenruo 			"sectorsize %llu not yet supported for page size %lu",
260921a852b0SQu Wenruo 			sectorsize, PAGE_SIZE);
261021a852b0SQu Wenruo 		ret = -EINVAL;
261121a852b0SQu Wenruo 	}
26120bb3eb3eSQu Wenruo 
261321a852b0SQu Wenruo 	if (!is_power_of_2(nodesize) || nodesize < sectorsize ||
261421a852b0SQu Wenruo 	    nodesize > BTRFS_MAX_METADATA_BLOCKSIZE) {
261521a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid nodesize %llu", nodesize);
261621a852b0SQu Wenruo 		ret = -EINVAL;
261721a852b0SQu Wenruo 	}
261821a852b0SQu Wenruo 	if (nodesize != le32_to_cpu(sb->__unused_leafsize)) {
261921a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid leafsize %u, should be %llu",
262021a852b0SQu Wenruo 			  le32_to_cpu(sb->__unused_leafsize), nodesize);
262121a852b0SQu Wenruo 		ret = -EINVAL;
262221a852b0SQu Wenruo 	}
262321a852b0SQu Wenruo 
262421a852b0SQu Wenruo 	/* Root alignment check */
262521a852b0SQu Wenruo 	if (!IS_ALIGNED(btrfs_super_root(sb), sectorsize)) {
262621a852b0SQu Wenruo 		btrfs_warn(fs_info, "tree_root block unaligned: %llu",
262721a852b0SQu Wenruo 			   btrfs_super_root(sb));
262821a852b0SQu Wenruo 		ret = -EINVAL;
262921a852b0SQu Wenruo 	}
263021a852b0SQu Wenruo 	if (!IS_ALIGNED(btrfs_super_chunk_root(sb), sectorsize)) {
263121a852b0SQu Wenruo 		btrfs_warn(fs_info, "chunk_root block unaligned: %llu",
263221a852b0SQu Wenruo 			   btrfs_super_chunk_root(sb));
263321a852b0SQu Wenruo 		ret = -EINVAL;
263421a852b0SQu Wenruo 	}
263521a852b0SQu Wenruo 	if (!IS_ALIGNED(btrfs_super_log_root(sb), sectorsize)) {
263621a852b0SQu Wenruo 		btrfs_warn(fs_info, "log_root block unaligned: %llu",
263721a852b0SQu Wenruo 			   btrfs_super_log_root(sb));
263821a852b0SQu Wenruo 		ret = -EINVAL;
263921a852b0SQu Wenruo 	}
264021a852b0SQu Wenruo 
2641aefd7f70SNikolay Borisov 	if (memcmp(fs_info->fs_devices->fsid, fs_info->super_copy->fsid,
2642aefd7f70SNikolay Borisov 		   BTRFS_FSID_SIZE)) {
2643aefd7f70SNikolay Borisov 		btrfs_err(fs_info,
2644aefd7f70SNikolay Borisov 		"superblock fsid doesn't match fsid of fs_devices: %pU != %pU",
2645aefd7f70SNikolay Borisov 			fs_info->super_copy->fsid, fs_info->fs_devices->fsid);
2646aefd7f70SNikolay Borisov 		ret = -EINVAL;
2647aefd7f70SNikolay Borisov 	}
2648aefd7f70SNikolay Borisov 
2649aefd7f70SNikolay Borisov 	if (btrfs_fs_incompat(fs_info, METADATA_UUID) &&
2650aefd7f70SNikolay Borisov 	    memcmp(fs_info->fs_devices->metadata_uuid,
2651aefd7f70SNikolay Borisov 		   fs_info->super_copy->metadata_uuid, BTRFS_FSID_SIZE)) {
2652aefd7f70SNikolay Borisov 		btrfs_err(fs_info,
2653aefd7f70SNikolay Borisov "superblock metadata_uuid doesn't match metadata uuid of fs_devices: %pU != %pU",
2654aefd7f70SNikolay Borisov 			fs_info->super_copy->metadata_uuid,
2655aefd7f70SNikolay Borisov 			fs_info->fs_devices->metadata_uuid);
2656aefd7f70SNikolay Borisov 		ret = -EINVAL;
2657aefd7f70SNikolay Borisov 	}
2658aefd7f70SNikolay Borisov 
2659de37aa51SNikolay Borisov 	if (memcmp(fs_info->fs_devices->metadata_uuid, sb->dev_item.fsid,
26607239ff4bSNikolay Borisov 		   BTRFS_FSID_SIZE) != 0) {
266121a852b0SQu Wenruo 		btrfs_err(fs_info,
26627239ff4bSNikolay Borisov 			"dev_item UUID does not match metadata fsid: %pU != %pU",
2663de37aa51SNikolay Borisov 			fs_info->fs_devices->metadata_uuid, sb->dev_item.fsid);
266421a852b0SQu Wenruo 		ret = -EINVAL;
266521a852b0SQu Wenruo 	}
266621a852b0SQu Wenruo 
266721a852b0SQu Wenruo 	/*
266821a852b0SQu Wenruo 	 * Hint to catch really bogus numbers, bitflips or so, more exact checks are
266921a852b0SQu Wenruo 	 * done later
267021a852b0SQu Wenruo 	 */
267121a852b0SQu Wenruo 	if (btrfs_super_bytes_used(sb) < 6 * btrfs_super_nodesize(sb)) {
267221a852b0SQu Wenruo 		btrfs_err(fs_info, "bytes_used is too small %llu",
267321a852b0SQu Wenruo 			  btrfs_super_bytes_used(sb));
267421a852b0SQu Wenruo 		ret = -EINVAL;
267521a852b0SQu Wenruo 	}
267621a852b0SQu Wenruo 	if (!is_power_of_2(btrfs_super_stripesize(sb))) {
267721a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid stripesize %u",
267821a852b0SQu Wenruo 			  btrfs_super_stripesize(sb));
267921a852b0SQu Wenruo 		ret = -EINVAL;
268021a852b0SQu Wenruo 	}
268121a852b0SQu Wenruo 	if (btrfs_super_num_devices(sb) > (1UL << 31))
268221a852b0SQu Wenruo 		btrfs_warn(fs_info, "suspicious number of devices: %llu",
268321a852b0SQu Wenruo 			   btrfs_super_num_devices(sb));
268421a852b0SQu Wenruo 	if (btrfs_super_num_devices(sb) == 0) {
268521a852b0SQu Wenruo 		btrfs_err(fs_info, "number of devices is 0");
268621a852b0SQu Wenruo 		ret = -EINVAL;
268721a852b0SQu Wenruo 	}
268821a852b0SQu Wenruo 
2689069ec957SQu Wenruo 	if (mirror_num >= 0 &&
2690069ec957SQu Wenruo 	    btrfs_super_bytenr(sb) != btrfs_sb_offset(mirror_num)) {
269121a852b0SQu Wenruo 		btrfs_err(fs_info, "super offset mismatch %llu != %u",
269221a852b0SQu Wenruo 			  btrfs_super_bytenr(sb), BTRFS_SUPER_INFO_OFFSET);
269321a852b0SQu Wenruo 		ret = -EINVAL;
269421a852b0SQu Wenruo 	}
269521a852b0SQu Wenruo 
269621a852b0SQu Wenruo 	/*
269721a852b0SQu Wenruo 	 * Obvious sys_chunk_array corruptions, it must hold at least one key
269821a852b0SQu Wenruo 	 * and one chunk
269921a852b0SQu Wenruo 	 */
270021a852b0SQu Wenruo 	if (btrfs_super_sys_array_size(sb) > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
270121a852b0SQu Wenruo 		btrfs_err(fs_info, "system chunk array too big %u > %u",
270221a852b0SQu Wenruo 			  btrfs_super_sys_array_size(sb),
270321a852b0SQu Wenruo 			  BTRFS_SYSTEM_CHUNK_ARRAY_SIZE);
270421a852b0SQu Wenruo 		ret = -EINVAL;
270521a852b0SQu Wenruo 	}
270621a852b0SQu Wenruo 	if (btrfs_super_sys_array_size(sb) < sizeof(struct btrfs_disk_key)
270721a852b0SQu Wenruo 			+ sizeof(struct btrfs_chunk)) {
270821a852b0SQu Wenruo 		btrfs_err(fs_info, "system chunk array too small %u < %zu",
270921a852b0SQu Wenruo 			  btrfs_super_sys_array_size(sb),
271021a852b0SQu Wenruo 			  sizeof(struct btrfs_disk_key)
271121a852b0SQu Wenruo 			  + sizeof(struct btrfs_chunk));
271221a852b0SQu Wenruo 		ret = -EINVAL;
271321a852b0SQu Wenruo 	}
271421a852b0SQu Wenruo 
271521a852b0SQu Wenruo 	/*
271621a852b0SQu Wenruo 	 * The generation is a global counter, we'll trust it more than the others
271721a852b0SQu Wenruo 	 * but it's still possible that it's the one that's wrong.
271821a852b0SQu Wenruo 	 */
271921a852b0SQu Wenruo 	if (btrfs_super_generation(sb) < btrfs_super_chunk_root_generation(sb))
272021a852b0SQu Wenruo 		btrfs_warn(fs_info,
272121a852b0SQu Wenruo 			"suspicious: generation < chunk_root_generation: %llu < %llu",
272221a852b0SQu Wenruo 			btrfs_super_generation(sb),
272321a852b0SQu Wenruo 			btrfs_super_chunk_root_generation(sb));
272421a852b0SQu Wenruo 	if (btrfs_super_generation(sb) < btrfs_super_cache_generation(sb)
272521a852b0SQu Wenruo 	    && btrfs_super_cache_generation(sb) != (u64)-1)
272621a852b0SQu Wenruo 		btrfs_warn(fs_info,
272721a852b0SQu Wenruo 			"suspicious: generation < cache_generation: %llu < %llu",
272821a852b0SQu Wenruo 			btrfs_super_generation(sb),
272921a852b0SQu Wenruo 			btrfs_super_cache_generation(sb));
273021a852b0SQu Wenruo 
273121a852b0SQu Wenruo 	return ret;
273221a852b0SQu Wenruo }
273321a852b0SQu Wenruo 
2734069ec957SQu Wenruo /*
2735069ec957SQu Wenruo  * Validation of super block at mount time.
2736069ec957SQu Wenruo  * Some checks already done early at mount time, like csum type and incompat
2737069ec957SQu Wenruo  * flags will be skipped.
2738069ec957SQu Wenruo  */
2739069ec957SQu Wenruo static int btrfs_validate_mount_super(struct btrfs_fs_info *fs_info)
2740069ec957SQu Wenruo {
2741069ec957SQu Wenruo 	return validate_super(fs_info, fs_info->super_copy, 0);
2742069ec957SQu Wenruo }
2743069ec957SQu Wenruo 
274475cb857dSQu Wenruo /*
274575cb857dSQu Wenruo  * Validation of super block at write time.
274675cb857dSQu Wenruo  * Some checks like bytenr check will be skipped as their values will be
274775cb857dSQu Wenruo  * overwritten soon.
274875cb857dSQu Wenruo  * Extra checks like csum type and incompat flags will be done here.
274975cb857dSQu Wenruo  */
275075cb857dSQu Wenruo static int btrfs_validate_write_super(struct btrfs_fs_info *fs_info,
275175cb857dSQu Wenruo 				      struct btrfs_super_block *sb)
275275cb857dSQu Wenruo {
275375cb857dSQu Wenruo 	int ret;
275475cb857dSQu Wenruo 
275575cb857dSQu Wenruo 	ret = validate_super(fs_info, sb, -1);
275675cb857dSQu Wenruo 	if (ret < 0)
275775cb857dSQu Wenruo 		goto out;
2758e7e16f48SJohannes Thumshirn 	if (!btrfs_supported_super_csum(btrfs_super_csum_type(sb))) {
275975cb857dSQu Wenruo 		ret = -EUCLEAN;
276075cb857dSQu Wenruo 		btrfs_err(fs_info, "invalid csum type, has %u want %u",
276175cb857dSQu Wenruo 			  btrfs_super_csum_type(sb), BTRFS_CSUM_TYPE_CRC32);
276275cb857dSQu Wenruo 		goto out;
276375cb857dSQu Wenruo 	}
276475cb857dSQu Wenruo 	if (btrfs_super_incompat_flags(sb) & ~BTRFS_FEATURE_INCOMPAT_SUPP) {
276575cb857dSQu Wenruo 		ret = -EUCLEAN;
276675cb857dSQu Wenruo 		btrfs_err(fs_info,
276775cb857dSQu Wenruo 		"invalid incompat flags, has 0x%llx valid mask 0x%llx",
276875cb857dSQu Wenruo 			  btrfs_super_incompat_flags(sb),
276975cb857dSQu Wenruo 			  (unsigned long long)BTRFS_FEATURE_INCOMPAT_SUPP);
277075cb857dSQu Wenruo 		goto out;
277175cb857dSQu Wenruo 	}
277275cb857dSQu Wenruo out:
277375cb857dSQu Wenruo 	if (ret < 0)
277475cb857dSQu Wenruo 		btrfs_err(fs_info,
277575cb857dSQu Wenruo 		"super block corruption detected before writing it to disk");
277675cb857dSQu Wenruo 	return ret;
277775cb857dSQu Wenruo }
277875cb857dSQu Wenruo 
27796ef108ddSNikolay Borisov static int __cold init_tree_roots(struct btrfs_fs_info *fs_info)
2780b8522a1eSNikolay Borisov {
27816ef108ddSNikolay Borisov 	int backup_index = find_newest_super_backup(fs_info);
2782b8522a1eSNikolay Borisov 	struct btrfs_super_block *sb = fs_info->super_copy;
2783b8522a1eSNikolay Borisov 	struct btrfs_root *tree_root = fs_info->tree_root;
2784b8522a1eSNikolay Borisov 	bool handle_error = false;
2785b8522a1eSNikolay Borisov 	int ret = 0;
2786b8522a1eSNikolay Borisov 	int i;
2787b8522a1eSNikolay Borisov 
2788b8522a1eSNikolay Borisov 	for (i = 0; i < BTRFS_NUM_BACKUP_ROOTS; i++) {
2789b8522a1eSNikolay Borisov 		u64 generation;
2790b8522a1eSNikolay Borisov 		int level;
2791b8522a1eSNikolay Borisov 
2792b8522a1eSNikolay Borisov 		if (handle_error) {
2793b8522a1eSNikolay Borisov 			if (!IS_ERR(tree_root->node))
2794b8522a1eSNikolay Borisov 				free_extent_buffer(tree_root->node);
2795b8522a1eSNikolay Borisov 			tree_root->node = NULL;
2796b8522a1eSNikolay Borisov 
2797b8522a1eSNikolay Borisov 			if (!btrfs_test_opt(fs_info, USEBACKUPROOT))
2798b8522a1eSNikolay Borisov 				break;
2799b8522a1eSNikolay Borisov 
2800b8522a1eSNikolay Borisov 			free_root_pointers(fs_info, 0);
2801b8522a1eSNikolay Borisov 
2802b8522a1eSNikolay Borisov 			/*
2803b8522a1eSNikolay Borisov 			 * Don't use the log in recovery mode, it won't be
2804b8522a1eSNikolay Borisov 			 * valid
2805b8522a1eSNikolay Borisov 			 */
2806b8522a1eSNikolay Borisov 			btrfs_set_super_log_root(sb, 0);
2807b8522a1eSNikolay Borisov 
2808b8522a1eSNikolay Borisov 			/* We can't trust the free space cache either */
2809b8522a1eSNikolay Borisov 			btrfs_set_opt(fs_info->mount_opt, CLEAR_CACHE);
2810b8522a1eSNikolay Borisov 
2811b8522a1eSNikolay Borisov 			ret = read_backup_root(fs_info, i);
28126ef108ddSNikolay Borisov 			backup_index = ret;
2813b8522a1eSNikolay Borisov 			if (ret < 0)
2814b8522a1eSNikolay Borisov 				return ret;
2815b8522a1eSNikolay Borisov 		}
2816b8522a1eSNikolay Borisov 		generation = btrfs_super_generation(sb);
2817b8522a1eSNikolay Borisov 		level = btrfs_super_root_level(sb);
2818b8522a1eSNikolay Borisov 		tree_root->node = read_tree_block(fs_info, btrfs_super_root(sb),
28191b7ec85eSJosef Bacik 						  BTRFS_ROOT_TREE_OBJECTID,
2820b8522a1eSNikolay Borisov 						  generation, level, NULL);
28210465337cSJosef Bacik 		if (IS_ERR(tree_root->node)) {
2822217f5004SNikolay Borisov 			handle_error = true;
2823b8522a1eSNikolay Borisov 			ret = PTR_ERR(tree_root->node);
28240465337cSJosef Bacik 			tree_root->node = NULL;
2825217f5004SNikolay Borisov 			btrfs_warn(fs_info, "couldn't read tree root");
2826217f5004SNikolay Borisov 			continue;
2827b8522a1eSNikolay Borisov 
2828217f5004SNikolay Borisov 		} else if (!extent_buffer_uptodate(tree_root->node)) {
2829217f5004SNikolay Borisov 			handle_error = true;
2830217f5004SNikolay Borisov 			ret = -EIO;
2831217f5004SNikolay Borisov 			btrfs_warn(fs_info, "error while reading tree root");
2832b8522a1eSNikolay Borisov 			continue;
2833b8522a1eSNikolay Borisov 		}
2834b8522a1eSNikolay Borisov 
2835b8522a1eSNikolay Borisov 		btrfs_set_root_node(&tree_root->root_item, tree_root->node);
2836b8522a1eSNikolay Borisov 		tree_root->commit_root = btrfs_root_node(tree_root);
2837b8522a1eSNikolay Borisov 		btrfs_set_root_refs(&tree_root->root_item, 1);
2838b8522a1eSNikolay Borisov 
2839336a0d8dSNikolay Borisov 		/*
2840336a0d8dSNikolay Borisov 		 * No need to hold btrfs_root::objectid_mutex since the fs
2841336a0d8dSNikolay Borisov 		 * hasn't been fully initialised and we are the only user
2842336a0d8dSNikolay Borisov 		 */
2843453e4873SNikolay Borisov 		ret = btrfs_init_root_free_objectid(tree_root);
2844b8522a1eSNikolay Borisov 		if (ret < 0) {
2845b8522a1eSNikolay Borisov 			handle_error = true;
2846b8522a1eSNikolay Borisov 			continue;
2847b8522a1eSNikolay Borisov 		}
2848b8522a1eSNikolay Borisov 
28496b8fad57SNikolay Borisov 		ASSERT(tree_root->free_objectid <= BTRFS_LAST_FREE_OBJECTID);
2850b8522a1eSNikolay Borisov 
2851b8522a1eSNikolay Borisov 		ret = btrfs_read_roots(fs_info);
2852b8522a1eSNikolay Borisov 		if (ret < 0) {
2853b8522a1eSNikolay Borisov 			handle_error = true;
2854b8522a1eSNikolay Borisov 			continue;
2855b8522a1eSNikolay Borisov 		}
2856b8522a1eSNikolay Borisov 
2857b8522a1eSNikolay Borisov 		/* All successful */
2858b8522a1eSNikolay Borisov 		fs_info->generation = generation;
2859b8522a1eSNikolay Borisov 		fs_info->last_trans_committed = generation;
28606ef108ddSNikolay Borisov 
28616ef108ddSNikolay Borisov 		/* Always begin writing backup roots after the one being used */
28626ef108ddSNikolay Borisov 		if (backup_index < 0) {
28636ef108ddSNikolay Borisov 			fs_info->backup_root_index = 0;
28646ef108ddSNikolay Borisov 		} else {
28656ef108ddSNikolay Borisov 			fs_info->backup_root_index = backup_index + 1;
28666ef108ddSNikolay Borisov 			fs_info->backup_root_index %= BTRFS_NUM_BACKUP_ROOTS;
28676ef108ddSNikolay Borisov 		}
2868b8522a1eSNikolay Borisov 		break;
2869b8522a1eSNikolay Borisov 	}
2870b8522a1eSNikolay Borisov 
2871b8522a1eSNikolay Borisov 	return ret;
2872b8522a1eSNikolay Borisov }
2873b8522a1eSNikolay Borisov 
28748260edbaSJosef Bacik void btrfs_init_fs_info(struct btrfs_fs_info *fs_info)
2875eb60ceacSChris Mason {
287676dda93cSYan, Zheng 	INIT_RADIX_TREE(&fs_info->fs_roots_radix, GFP_ATOMIC);
2877f28491e0SJosef Bacik 	INIT_RADIX_TREE(&fs_info->buffer_radix, GFP_ATOMIC);
28788fd17795SChris Mason 	INIT_LIST_HEAD(&fs_info->trans_list);
2879facda1e7SChris Mason 	INIT_LIST_HEAD(&fs_info->dead_roots);
288024bbcf04SYan, Zheng 	INIT_LIST_HEAD(&fs_info->delayed_iputs);
2881eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&fs_info->delalloc_roots);
288211833d66SYan Zheng 	INIT_LIST_HEAD(&fs_info->caching_block_groups);
2883eb73c1b7SMiao Xie 	spin_lock_init(&fs_info->delalloc_root_lock);
2884a4abeea4SJosef Bacik 	spin_lock_init(&fs_info->trans_lock);
288576dda93cSYan, Zheng 	spin_lock_init(&fs_info->fs_roots_radix_lock);
288624bbcf04SYan, Zheng 	spin_lock_init(&fs_info->delayed_iput_lock);
28874cb5300bSChris Mason 	spin_lock_init(&fs_info->defrag_inodes_lock);
2888ceda0864SMiao Xie 	spin_lock_init(&fs_info->super_lock);
2889f28491e0SJosef Bacik 	spin_lock_init(&fs_info->buffer_lock);
289047ab2a6cSJosef Bacik 	spin_lock_init(&fs_info->unused_bgs_lock);
289140ab3be1SNaohiro Aota 	spin_lock_init(&fs_info->treelog_bg_lock);
2892afba2bc0SNaohiro Aota 	spin_lock_init(&fs_info->zone_active_bgs_lock);
2893c2707a25SJohannes Thumshirn 	spin_lock_init(&fs_info->relocation_bg_lock);
2894f29021b2SJan Schmidt 	rwlock_init(&fs_info->tree_mod_log_lock);
2895d7c15171SZhao Lei 	mutex_init(&fs_info->unused_bg_unpin_mutex);
2896f3372065SJohannes Thumshirn 	mutex_init(&fs_info->reclaim_bgs_lock);
28977585717fSChris Mason 	mutex_init(&fs_info->reloc_mutex);
2898573bfb72SMiao Xie 	mutex_init(&fs_info->delalloc_root_mutex);
28990bc09ca1SNaohiro Aota 	mutex_init(&fs_info->zoned_meta_io_lock);
2900de98ced9SMiao Xie 	seqlock_init(&fs_info->profiles_lock);
290119c00ddcSChris Mason 
29020b86a832SChris Mason 	INIT_LIST_HEAD(&fs_info->dirty_cowonly_roots);
29036324fbf3SChris Mason 	INIT_LIST_HEAD(&fs_info->space_info);
2904f29021b2SJan Schmidt 	INIT_LIST_HEAD(&fs_info->tree_mod_seq_list);
290547ab2a6cSJosef Bacik 	INIT_LIST_HEAD(&fs_info->unused_bgs);
290618bb8bbfSJohannes Thumshirn 	INIT_LIST_HEAD(&fs_info->reclaim_bgs);
2907afba2bc0SNaohiro Aota 	INIT_LIST_HEAD(&fs_info->zone_active_bgs);
2908bd647ce3SJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
2909bd647ce3SJosef Bacik 	INIT_LIST_HEAD(&fs_info->allocated_roots);
29103fd63727SJosef Bacik 	INIT_LIST_HEAD(&fs_info->allocated_ebs);
29113fd63727SJosef Bacik 	spin_lock_init(&fs_info->eb_leak_lock);
2912bd647ce3SJosef Bacik #endif
2913c8bf1b67SDavid Sterba 	extent_map_tree_init(&fs_info->mapping_tree);
291466d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->global_block_rsv,
291566d8f3ddSMiao Xie 			     BTRFS_BLOCK_RSV_GLOBAL);
291666d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->trans_block_rsv, BTRFS_BLOCK_RSV_TRANS);
291766d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->chunk_block_rsv, BTRFS_BLOCK_RSV_CHUNK);
291866d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->empty_block_rsv, BTRFS_BLOCK_RSV_EMPTY);
291966d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->delayed_block_rsv,
292066d8f3ddSMiao Xie 			     BTRFS_BLOCK_RSV_DELOPS);
2921ba2c4d4eSJosef Bacik 	btrfs_init_block_rsv(&fs_info->delayed_refs_rsv,
2922ba2c4d4eSJosef Bacik 			     BTRFS_BLOCK_RSV_DELREFS);
2923ba2c4d4eSJosef Bacik 
2924771ed689SChris Mason 	atomic_set(&fs_info->async_delalloc_pages, 0);
29254cb5300bSChris Mason 	atomic_set(&fs_info->defrag_running, 0);
29262fefd558SZhao Lei 	atomic_set(&fs_info->reada_works_cnt, 0);
2927034f784dSJosef Bacik 	atomic_set(&fs_info->nr_delayed_iputs, 0);
2928fc36ed7eSJan Schmidt 	atomic64_set(&fs_info->tree_mod_seq, 0);
292995ac567aSFilipe David Borba Manana 	fs_info->max_inline = BTRFS_DEFAULT_MAX_INLINE;
29309ed74f2dSJosef Bacik 	fs_info->metadata_ratio = 0;
29314cb5300bSChris Mason 	fs_info->defrag_inodes = RB_ROOT;
2932a5ed45f8SNikolay Borisov 	atomic64_set(&fs_info->free_chunk_space, 0);
2933f29021b2SJan Schmidt 	fs_info->tree_mod_log = RB_ROOT;
29348b87dc17SDavid Sterba 	fs_info->commit_interval = BTRFS_DEFAULT_COMMIT_INTERVAL;
2935f8c269d7SDavid Sterba 	fs_info->avg_delayed_ref_runtime = NSEC_PER_SEC >> 6; /* div by 64 */
293690519d66SArne Jansen 	/* readahead state */
2937d0164adcSMel Gorman 	INIT_RADIX_TREE(&fs_info->reada_tree, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
293890519d66SArne Jansen 	spin_lock_init(&fs_info->reada_lock);
2939fd708b81SJosef Bacik 	btrfs_init_ref_verify(fs_info);
2940c8b97818SChris Mason 
2941b34b086cSChris Mason 	fs_info->thread_pool_size = min_t(unsigned long,
2942b34b086cSChris Mason 					  num_online_cpus() + 2, 8);
29430afbaf8cSChris Mason 
2944199c2a9cSMiao Xie 	INIT_LIST_HEAD(&fs_info->ordered_roots);
2945199c2a9cSMiao Xie 	spin_lock_init(&fs_info->ordered_root_lock);
294669fe2d75SJosef Bacik 
2947638aa7edSEric Sandeen 	btrfs_init_scrub(fs_info);
294821adbd5cSStefan Behrens #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
294921adbd5cSStefan Behrens 	fs_info->check_integrity_print_mask = 0;
295021adbd5cSStefan Behrens #endif
2951779a65a4SEric Sandeen 	btrfs_init_balance(fs_info);
295257056740SJosef Bacik 	btrfs_init_async_reclaim_work(fs_info);
2953a2de733cSArne Jansen 
29540f9dd46cSJosef Bacik 	spin_lock_init(&fs_info->block_group_cache_lock);
29556bef4d31SEric Paris 	fs_info->block_group_cache_tree = RB_ROOT;
2956a1897fddSLiu Bo 	fs_info->first_logical_byte = (u64)-1;
29570f9dd46cSJosef Bacik 
2958fe119a6eSNikolay Borisov 	extent_io_tree_init(fs_info, &fs_info->excluded_extents,
2959fe119a6eSNikolay Borisov 			    IO_TREE_FS_EXCLUDED_EXTENTS, NULL);
2960afcdd129SJosef Bacik 	set_bit(BTRFS_FS_BARRIER, &fs_info->flags);
296139279cc3SChris Mason 
29625a3f23d5SChris Mason 	mutex_init(&fs_info->ordered_operations_mutex);
2963e02119d5SChris Mason 	mutex_init(&fs_info->tree_log_mutex);
2964925baeddSChris Mason 	mutex_init(&fs_info->chunk_mutex);
2965a74a4b97SChris Mason 	mutex_init(&fs_info->transaction_kthread_mutex);
2966a74a4b97SChris Mason 	mutex_init(&fs_info->cleaner_mutex);
29671bbc621eSChris Mason 	mutex_init(&fs_info->ro_block_group_mutex);
29689e351cc8SJosef Bacik 	init_rwsem(&fs_info->commit_root_sem);
2969c71bf099SYan, Zheng 	init_rwsem(&fs_info->cleanup_work_sem);
297076dda93cSYan, Zheng 	init_rwsem(&fs_info->subvol_sem);
2971803b2f54SStefan Behrens 	sema_init(&fs_info->uuid_tree_rescan_sem, 1);
2972fa9c0d79SChris Mason 
2973ad618368SEric Sandeen 	btrfs_init_dev_replace_locks(fs_info);
2974f9e92e40SEric Sandeen 	btrfs_init_qgroup(fs_info);
2975b0643e59SDennis Zhou 	btrfs_discard_init(fs_info);
2976416ac51dSArne Jansen 
2977fa9c0d79SChris Mason 	btrfs_init_free_cluster(&fs_info->meta_alloc_cluster);
2978fa9c0d79SChris Mason 	btrfs_init_free_cluster(&fs_info->data_alloc_cluster);
2979fa9c0d79SChris Mason 
2980e6dcd2dcSChris Mason 	init_waitqueue_head(&fs_info->transaction_throttle);
2981f9295749SChris Mason 	init_waitqueue_head(&fs_info->transaction_wait);
2982bb9c12c9SSage Weil 	init_waitqueue_head(&fs_info->transaction_blocked_wait);
29834854ddd0SChris Mason 	init_waitqueue_head(&fs_info->async_submit_wait);
2984034f784dSJosef Bacik 	init_waitqueue_head(&fs_info->delayed_iputs_wait);
29853768f368SChris Mason 
2986da17066cSJeff Mahoney 	/* Usable values until the real ones are cached from the superblock */
2987da17066cSJeff Mahoney 	fs_info->nodesize = 4096;
2988da17066cSJeff Mahoney 	fs_info->sectorsize = 4096;
2989ab108d99SDavid Sterba 	fs_info->sectorsize_bits = ilog2(4096);
2990da17066cSJeff Mahoney 	fs_info->stripesize = 4096;
2991da17066cSJeff Mahoney 
2992eede2bf3SOmar Sandoval 	spin_lock_init(&fs_info->swapfile_pins_lock);
2993eede2bf3SOmar Sandoval 	fs_info->swapfile_pins = RB_ROOT;
2994eede2bf3SOmar Sandoval 
29951cea5cf0SFilipe Manana 	spin_lock_init(&fs_info->send_reloc_lock);
29969e967495SFilipe Manana 	fs_info->send_in_progress = 0;
299718bb8bbfSJohannes Thumshirn 
299818bb8bbfSJohannes Thumshirn 	fs_info->bg_reclaim_threshold = BTRFS_DEFAULT_RECLAIM_THRESH;
299918bb8bbfSJohannes Thumshirn 	INIT_WORK(&fs_info->reclaim_bgs_work, btrfs_reclaim_bgs_work);
30008260edbaSJosef Bacik }
30018260edbaSJosef Bacik 
30028260edbaSJosef Bacik static int init_mount_fs_info(struct btrfs_fs_info *fs_info, struct super_block *sb)
30038260edbaSJosef Bacik {
30048260edbaSJosef Bacik 	int ret;
30058260edbaSJosef Bacik 
30068260edbaSJosef Bacik 	fs_info->sb = sb;
30078260edbaSJosef Bacik 	sb->s_blocksize = BTRFS_BDEV_BLOCKSIZE;
30088260edbaSJosef Bacik 	sb->s_blocksize_bits = blksize_bits(BTRFS_BDEV_BLOCKSIZE);
30099e967495SFilipe Manana 
30105deb17e1SJosef Bacik 	ret = percpu_counter_init(&fs_info->ordered_bytes, 0, GFP_KERNEL);
3011ae18c37aSJosef Bacik 	if (ret)
3012ae18c37aSJosef Bacik 		return ret;
3013ae18c37aSJosef Bacik 
3014ae18c37aSJosef Bacik 	ret = percpu_counter_init(&fs_info->dirty_metadata_bytes, 0, GFP_KERNEL);
3015ae18c37aSJosef Bacik 	if (ret)
3016c75e8394SJosef Bacik 		return ret;
3017ae18c37aSJosef Bacik 
3018ae18c37aSJosef Bacik 	fs_info->dirty_metadata_batch = PAGE_SIZE *
3019ae18c37aSJosef Bacik 					(1 + ilog2(nr_cpu_ids));
3020ae18c37aSJosef Bacik 
3021ae18c37aSJosef Bacik 	ret = percpu_counter_init(&fs_info->delalloc_bytes, 0, GFP_KERNEL);
3022ae18c37aSJosef Bacik 	if (ret)
3023c75e8394SJosef Bacik 		return ret;
3024ae18c37aSJosef Bacik 
3025ae18c37aSJosef Bacik 	ret = percpu_counter_init(&fs_info->dev_replace.bio_counter, 0,
3026ae18c37aSJosef Bacik 			GFP_KERNEL);
3027ae18c37aSJosef Bacik 	if (ret)
3028c75e8394SJosef Bacik 		return ret;
3029ae18c37aSJosef Bacik 
3030ae18c37aSJosef Bacik 	fs_info->delayed_root = kmalloc(sizeof(struct btrfs_delayed_root),
3031ae18c37aSJosef Bacik 					GFP_KERNEL);
3032c75e8394SJosef Bacik 	if (!fs_info->delayed_root)
3033c75e8394SJosef Bacik 		return -ENOMEM;
3034ae18c37aSJosef Bacik 	btrfs_init_delayed_root(fs_info->delayed_root);
3035ae18c37aSJosef Bacik 
3036a0a1db70SFilipe Manana 	if (sb_rdonly(sb))
3037a0a1db70SFilipe Manana 		set_bit(BTRFS_FS_STATE_RO, &fs_info->fs_state);
3038a0a1db70SFilipe Manana 
3039c75e8394SJosef Bacik 	return btrfs_alloc_stripe_hash_table(fs_info);
3040ae18c37aSJosef Bacik }
3041ae18c37aSJosef Bacik 
304297f4dd09SNikolay Borisov static int btrfs_uuid_rescan_kthread(void *data)
304397f4dd09SNikolay Borisov {
304497f4dd09SNikolay Borisov 	struct btrfs_fs_info *fs_info = (struct btrfs_fs_info *)data;
304597f4dd09SNikolay Borisov 	int ret;
304697f4dd09SNikolay Borisov 
304797f4dd09SNikolay Borisov 	/*
304897f4dd09SNikolay Borisov 	 * 1st step is to iterate through the existing UUID tree and
304997f4dd09SNikolay Borisov 	 * to delete all entries that contain outdated data.
305097f4dd09SNikolay Borisov 	 * 2nd step is to add all missing entries to the UUID tree.
305197f4dd09SNikolay Borisov 	 */
305297f4dd09SNikolay Borisov 	ret = btrfs_uuid_tree_iterate(fs_info);
305397f4dd09SNikolay Borisov 	if (ret < 0) {
3054c94bec2cSJosef Bacik 		if (ret != -EINTR)
3055c94bec2cSJosef Bacik 			btrfs_warn(fs_info, "iterating uuid_tree failed %d",
3056c94bec2cSJosef Bacik 				   ret);
305797f4dd09SNikolay Borisov 		up(&fs_info->uuid_tree_rescan_sem);
305897f4dd09SNikolay Borisov 		return ret;
305997f4dd09SNikolay Borisov 	}
306097f4dd09SNikolay Borisov 	return btrfs_uuid_scan_kthread(data);
306197f4dd09SNikolay Borisov }
306297f4dd09SNikolay Borisov 
306397f4dd09SNikolay Borisov static int btrfs_check_uuid_tree(struct btrfs_fs_info *fs_info)
306497f4dd09SNikolay Borisov {
306597f4dd09SNikolay Borisov 	struct task_struct *task;
306697f4dd09SNikolay Borisov 
306797f4dd09SNikolay Borisov 	down(&fs_info->uuid_tree_rescan_sem);
306897f4dd09SNikolay Borisov 	task = kthread_run(btrfs_uuid_rescan_kthread, fs_info, "btrfs-uuid");
306997f4dd09SNikolay Borisov 	if (IS_ERR(task)) {
307097f4dd09SNikolay Borisov 		/* fs_info->update_uuid_tree_gen remains 0 in all error case */
307197f4dd09SNikolay Borisov 		btrfs_warn(fs_info, "failed to start uuid_rescan task");
307297f4dd09SNikolay Borisov 		up(&fs_info->uuid_tree_rescan_sem);
307397f4dd09SNikolay Borisov 		return PTR_ERR(task);
307497f4dd09SNikolay Borisov 	}
307597f4dd09SNikolay Borisov 
307697f4dd09SNikolay Borisov 	return 0;
307797f4dd09SNikolay Borisov }
307897f4dd09SNikolay Borisov 
307944c0ca21SBoris Burkov /*
30808cd29088SBoris Burkov  * Some options only have meaning at mount time and shouldn't persist across
30818cd29088SBoris Burkov  * remounts, or be displayed. Clear these at the end of mount and remount
30828cd29088SBoris Burkov  * code paths.
30838cd29088SBoris Burkov  */
30848cd29088SBoris Burkov void btrfs_clear_oneshot_options(struct btrfs_fs_info *fs_info)
30858cd29088SBoris Burkov {
30868cd29088SBoris Burkov 	btrfs_clear_opt(fs_info->mount_opt, USEBACKUPROOT);
30878b228324SBoris Burkov 	btrfs_clear_opt(fs_info->mount_opt, CLEAR_CACHE);
30888cd29088SBoris Burkov }
30898cd29088SBoris Burkov 
30908cd29088SBoris Burkov /*
309144c0ca21SBoris Burkov  * Mounting logic specific to read-write file systems. Shared by open_ctree
309244c0ca21SBoris Burkov  * and btrfs_remount when remounting from read-only to read-write.
309344c0ca21SBoris Burkov  */
309444c0ca21SBoris Burkov int btrfs_start_pre_rw_mount(struct btrfs_fs_info *fs_info)
309544c0ca21SBoris Burkov {
309644c0ca21SBoris Burkov 	int ret;
309794846229SBoris Burkov 	const bool cache_opt = btrfs_test_opt(fs_info, SPACE_CACHE);
30988b228324SBoris Burkov 	bool clear_free_space_tree = false;
30998b228324SBoris Burkov 
31008b228324SBoris Burkov 	if (btrfs_test_opt(fs_info, CLEAR_CACHE) &&
31018b228324SBoris Burkov 	    btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
31028b228324SBoris Burkov 		clear_free_space_tree = true;
31038b228324SBoris Burkov 	} else if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE) &&
31048b228324SBoris Burkov 		   !btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE_VALID)) {
31058b228324SBoris Burkov 		btrfs_warn(fs_info, "free space tree is invalid");
31068b228324SBoris Burkov 		clear_free_space_tree = true;
31078b228324SBoris Burkov 	}
31088b228324SBoris Burkov 
31098b228324SBoris Burkov 	if (clear_free_space_tree) {
31108b228324SBoris Burkov 		btrfs_info(fs_info, "clearing free space tree");
31118b228324SBoris Burkov 		ret = btrfs_clear_free_space_tree(fs_info);
31128b228324SBoris Burkov 		if (ret) {
31138b228324SBoris Burkov 			btrfs_warn(fs_info,
31148b228324SBoris Burkov 				   "failed to clear free space tree: %d", ret);
31158b228324SBoris Burkov 			goto out;
31168b228324SBoris Burkov 		}
31178b228324SBoris Burkov 	}
311844c0ca21SBoris Burkov 
31198d488a8cSFilipe Manana 	/*
31208d488a8cSFilipe Manana 	 * btrfs_find_orphan_roots() is responsible for finding all the dead
31218d488a8cSFilipe Manana 	 * roots (with 0 refs), flag them with BTRFS_ROOT_DEAD_TREE and load
31228d488a8cSFilipe Manana 	 * them into the fs_info->fs_roots_radix tree. This must be done before
31238d488a8cSFilipe Manana 	 * calling btrfs_orphan_cleanup() on the tree root. If we don't do it
31248d488a8cSFilipe Manana 	 * first, then btrfs_orphan_cleanup() will delete a dead root's orphan
31258d488a8cSFilipe Manana 	 * item before the root's tree is deleted - this means that if we unmount
31268d488a8cSFilipe Manana 	 * or crash before the deletion completes, on the next mount we will not
31278d488a8cSFilipe Manana 	 * delete what remains of the tree because the orphan item does not
31288d488a8cSFilipe Manana 	 * exists anymore, which is what tells us we have a pending deletion.
31298d488a8cSFilipe Manana 	 */
31308d488a8cSFilipe Manana 	ret = btrfs_find_orphan_roots(fs_info);
31318d488a8cSFilipe Manana 	if (ret)
31328d488a8cSFilipe Manana 		goto out;
31338d488a8cSFilipe Manana 
313444c0ca21SBoris Burkov 	ret = btrfs_cleanup_fs_roots(fs_info);
313544c0ca21SBoris Burkov 	if (ret)
313644c0ca21SBoris Burkov 		goto out;
313744c0ca21SBoris Burkov 
31388f1c21d7SBoris Burkov 	down_read(&fs_info->cleanup_work_sem);
31398f1c21d7SBoris Burkov 	if ((ret = btrfs_orphan_cleanup(fs_info->fs_root)) ||
31408f1c21d7SBoris Burkov 	    (ret = btrfs_orphan_cleanup(fs_info->tree_root))) {
31418f1c21d7SBoris Burkov 		up_read(&fs_info->cleanup_work_sem);
31428f1c21d7SBoris Burkov 		goto out;
31438f1c21d7SBoris Burkov 	}
31448f1c21d7SBoris Burkov 	up_read(&fs_info->cleanup_work_sem);
31458f1c21d7SBoris Burkov 
314644c0ca21SBoris Burkov 	mutex_lock(&fs_info->cleaner_mutex);
314744c0ca21SBoris Burkov 	ret = btrfs_recover_relocation(fs_info->tree_root);
314844c0ca21SBoris Burkov 	mutex_unlock(&fs_info->cleaner_mutex);
314944c0ca21SBoris Burkov 	if (ret < 0) {
315044c0ca21SBoris Burkov 		btrfs_warn(fs_info, "failed to recover relocation: %d", ret);
315144c0ca21SBoris Burkov 		goto out;
315244c0ca21SBoris Burkov 	}
315344c0ca21SBoris Burkov 
31545011139aSBoris Burkov 	if (btrfs_test_opt(fs_info, FREE_SPACE_TREE) &&
31555011139aSBoris Burkov 	    !btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
31565011139aSBoris Burkov 		btrfs_info(fs_info, "creating free space tree");
31575011139aSBoris Burkov 		ret = btrfs_create_free_space_tree(fs_info);
31585011139aSBoris Burkov 		if (ret) {
31595011139aSBoris Burkov 			btrfs_warn(fs_info,
31605011139aSBoris Burkov 				"failed to create free space tree: %d", ret);
31615011139aSBoris Burkov 			goto out;
31625011139aSBoris Burkov 		}
31635011139aSBoris Burkov 	}
31645011139aSBoris Burkov 
316594846229SBoris Burkov 	if (cache_opt != btrfs_free_space_cache_v1_active(fs_info)) {
316694846229SBoris Burkov 		ret = btrfs_set_free_space_cache_v1_active(fs_info, cache_opt);
316794846229SBoris Burkov 		if (ret)
316894846229SBoris Burkov 			goto out;
316994846229SBoris Burkov 	}
317094846229SBoris Burkov 
317144c0ca21SBoris Burkov 	ret = btrfs_resume_balance_async(fs_info);
317244c0ca21SBoris Burkov 	if (ret)
317344c0ca21SBoris Burkov 		goto out;
317444c0ca21SBoris Burkov 
317544c0ca21SBoris Burkov 	ret = btrfs_resume_dev_replace_async(fs_info);
317644c0ca21SBoris Burkov 	if (ret) {
317744c0ca21SBoris Burkov 		btrfs_warn(fs_info, "failed to resume dev_replace");
317844c0ca21SBoris Burkov 		goto out;
317944c0ca21SBoris Burkov 	}
318044c0ca21SBoris Burkov 
318144c0ca21SBoris Burkov 	btrfs_qgroup_rescan_resume(fs_info);
318244c0ca21SBoris Burkov 
318344c0ca21SBoris Burkov 	if (!fs_info->uuid_root) {
318444c0ca21SBoris Burkov 		btrfs_info(fs_info, "creating UUID tree");
318544c0ca21SBoris Burkov 		ret = btrfs_create_uuid_tree(fs_info);
318644c0ca21SBoris Burkov 		if (ret) {
318744c0ca21SBoris Burkov 			btrfs_warn(fs_info,
318844c0ca21SBoris Burkov 				   "failed to create the UUID tree %d", ret);
318944c0ca21SBoris Burkov 			goto out;
319044c0ca21SBoris Burkov 		}
319144c0ca21SBoris Burkov 	}
319244c0ca21SBoris Burkov 
319344c0ca21SBoris Burkov out:
319444c0ca21SBoris Burkov 	return ret;
319544c0ca21SBoris Burkov }
319644c0ca21SBoris Burkov 
3197ae18c37aSJosef Bacik int __cold open_ctree(struct super_block *sb, struct btrfs_fs_devices *fs_devices,
3198ae18c37aSJosef Bacik 		      char *options)
3199ae18c37aSJosef Bacik {
3200ae18c37aSJosef Bacik 	u32 sectorsize;
3201ae18c37aSJosef Bacik 	u32 nodesize;
3202ae18c37aSJosef Bacik 	u32 stripesize;
3203ae18c37aSJosef Bacik 	u64 generation;
3204ae18c37aSJosef Bacik 	u64 features;
3205ae18c37aSJosef Bacik 	u16 csum_type;
3206ae18c37aSJosef Bacik 	struct btrfs_super_block *disk_super;
3207ae18c37aSJosef Bacik 	struct btrfs_fs_info *fs_info = btrfs_sb(sb);
3208ae18c37aSJosef Bacik 	struct btrfs_root *tree_root;
3209ae18c37aSJosef Bacik 	struct btrfs_root *chunk_root;
3210ae18c37aSJosef Bacik 	int ret;
3211ae18c37aSJosef Bacik 	int err = -EINVAL;
3212ae18c37aSJosef Bacik 	int level;
3213ae18c37aSJosef Bacik 
32148260edbaSJosef Bacik 	ret = init_mount_fs_info(fs_info, sb);
321553b381b3SDavid Woodhouse 	if (ret) {
321683c8266aSDavid Sterba 		err = ret;
3217ae18c37aSJosef Bacik 		goto fail;
321853b381b3SDavid Woodhouse 	}
321953b381b3SDavid Woodhouse 
3220ae18c37aSJosef Bacik 	/* These need to be init'ed before we start creating inodes and such. */
3221ae18c37aSJosef Bacik 	tree_root = btrfs_alloc_root(fs_info, BTRFS_ROOT_TREE_OBJECTID,
3222ae18c37aSJosef Bacik 				     GFP_KERNEL);
3223ae18c37aSJosef Bacik 	fs_info->tree_root = tree_root;
3224ae18c37aSJosef Bacik 	chunk_root = btrfs_alloc_root(fs_info, BTRFS_CHUNK_TREE_OBJECTID,
3225ae18c37aSJosef Bacik 				      GFP_KERNEL);
3226ae18c37aSJosef Bacik 	fs_info->chunk_root = chunk_root;
3227ae18c37aSJosef Bacik 	if (!tree_root || !chunk_root) {
3228ae18c37aSJosef Bacik 		err = -ENOMEM;
3229c75e8394SJosef Bacik 		goto fail;
3230ae18c37aSJosef Bacik 	}
3231ae18c37aSJosef Bacik 
3232ae18c37aSJosef Bacik 	fs_info->btree_inode = new_inode(sb);
3233ae18c37aSJosef Bacik 	if (!fs_info->btree_inode) {
3234ae18c37aSJosef Bacik 		err = -ENOMEM;
3235c75e8394SJosef Bacik 		goto fail;
3236ae18c37aSJosef Bacik 	}
3237ae18c37aSJosef Bacik 	mapping_set_gfp_mask(fs_info->btree_inode->i_mapping, GFP_NOFS);
3238ae18c37aSJosef Bacik 	btrfs_init_btree_inode(fs_info);
3239ae18c37aSJosef Bacik 
3240d24fa5c1SAnand Jain 	invalidate_bdev(fs_devices->latest_dev->bdev);
32411104a885SDavid Sterba 
32421104a885SDavid Sterba 	/*
32431104a885SDavid Sterba 	 * Read super block and check the signature bytes only
32441104a885SDavid Sterba 	 */
3245d24fa5c1SAnand Jain 	disk_super = btrfs_read_dev_super(fs_devices->latest_dev->bdev);
32468f32380dSJohannes Thumshirn 	if (IS_ERR(disk_super)) {
32478f32380dSJohannes Thumshirn 		err = PTR_ERR(disk_super);
324816cdcec7SMiao Xie 		goto fail_alloc;
324920b45077SDave Young 	}
325039279cc3SChris Mason 
32511104a885SDavid Sterba 	/*
3252260db43cSRandy Dunlap 	 * Verify the type first, if that or the checksum value are
32538dc3f22cSJohannes Thumshirn 	 * corrupted, we'll find out
32548dc3f22cSJohannes Thumshirn 	 */
32558f32380dSJohannes Thumshirn 	csum_type = btrfs_super_csum_type(disk_super);
325651bce6c9SJohannes Thumshirn 	if (!btrfs_supported_super_csum(csum_type)) {
32578dc3f22cSJohannes Thumshirn 		btrfs_err(fs_info, "unsupported checksum algorithm: %u",
325851bce6c9SJohannes Thumshirn 			  csum_type);
32598dc3f22cSJohannes Thumshirn 		err = -EINVAL;
32608f32380dSJohannes Thumshirn 		btrfs_release_disk_super(disk_super);
32618dc3f22cSJohannes Thumshirn 		goto fail_alloc;
32628dc3f22cSJohannes Thumshirn 	}
32638dc3f22cSJohannes Thumshirn 
326483c68bbcSSu Yue 	fs_info->csum_size = btrfs_super_csum_size(disk_super);
326583c68bbcSSu Yue 
32666d97c6e3SJohannes Thumshirn 	ret = btrfs_init_csum_hash(fs_info, csum_type);
32676d97c6e3SJohannes Thumshirn 	if (ret) {
32686d97c6e3SJohannes Thumshirn 		err = ret;
32698f32380dSJohannes Thumshirn 		btrfs_release_disk_super(disk_super);
32706d97c6e3SJohannes Thumshirn 		goto fail_alloc;
32716d97c6e3SJohannes Thumshirn 	}
32726d97c6e3SJohannes Thumshirn 
32738dc3f22cSJohannes Thumshirn 	/*
32741104a885SDavid Sterba 	 * We want to check superblock checksum, the type is stored inside.
32751104a885SDavid Sterba 	 * Pass the whole disk block of size BTRFS_SUPER_INFO_SIZE (4k).
32761104a885SDavid Sterba 	 */
32778f32380dSJohannes Thumshirn 	if (btrfs_check_super_csum(fs_info, (u8 *)disk_super)) {
327805135f59SDavid Sterba 		btrfs_err(fs_info, "superblock checksum mismatch");
32791104a885SDavid Sterba 		err = -EINVAL;
32808f32380dSJohannes Thumshirn 		btrfs_release_disk_super(disk_super);
3281141386e1SJosef Bacik 		goto fail_alloc;
32821104a885SDavid Sterba 	}
32831104a885SDavid Sterba 
32841104a885SDavid Sterba 	/*
32851104a885SDavid Sterba 	 * super_copy is zeroed at allocation time and we never touch the
32861104a885SDavid Sterba 	 * following bytes up to INFO_SIZE, the checksum is calculated from
32871104a885SDavid Sterba 	 * the whole block of INFO_SIZE
32881104a885SDavid Sterba 	 */
32898f32380dSJohannes Thumshirn 	memcpy(fs_info->super_copy, disk_super, sizeof(*fs_info->super_copy));
32908f32380dSJohannes Thumshirn 	btrfs_release_disk_super(disk_super);
32915f39d397SChris Mason 
3292fbc6feaeSNikolay Borisov 	disk_super = fs_info->super_copy;
3293fbc6feaeSNikolay Borisov 
32940b86a832SChris Mason 
3295fbc6feaeSNikolay Borisov 	features = btrfs_super_flags(disk_super);
3296fbc6feaeSNikolay Borisov 	if (features & BTRFS_SUPER_FLAG_CHANGING_FSID_V2) {
3297fbc6feaeSNikolay Borisov 		features &= ~BTRFS_SUPER_FLAG_CHANGING_FSID_V2;
3298fbc6feaeSNikolay Borisov 		btrfs_set_super_flags(disk_super, features);
3299fbc6feaeSNikolay Borisov 		btrfs_info(fs_info,
3300fbc6feaeSNikolay Borisov 			"found metadata UUID change in progress flag, clearing");
3301fbc6feaeSNikolay Borisov 	}
3302fbc6feaeSNikolay Borisov 
3303fbc6feaeSNikolay Borisov 	memcpy(fs_info->super_for_commit, fs_info->super_copy,
3304fbc6feaeSNikolay Borisov 	       sizeof(*fs_info->super_for_commit));
3305de37aa51SNikolay Borisov 
3306069ec957SQu Wenruo 	ret = btrfs_validate_mount_super(fs_info);
33071104a885SDavid Sterba 	if (ret) {
330805135f59SDavid Sterba 		btrfs_err(fs_info, "superblock contains fatal errors");
33091104a885SDavid Sterba 		err = -EINVAL;
3310141386e1SJosef Bacik 		goto fail_alloc;
33111104a885SDavid Sterba 	}
33121104a885SDavid Sterba 
33130f7d52f4SChris Mason 	if (!btrfs_super_root(disk_super))
3314141386e1SJosef Bacik 		goto fail_alloc;
33150f7d52f4SChris Mason 
3316acce952bSliubo 	/* check FS state, whether FS is broken. */
331787533c47SMiao Xie 	if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_ERROR)
331887533c47SMiao Xie 		set_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state);
3319acce952bSliubo 
332075e7cb7fSLiu Bo 	/*
332175e7cb7fSLiu Bo 	 * In the long term, we'll store the compression type in the super
332275e7cb7fSLiu Bo 	 * block, and it'll be used for per file compression control.
332375e7cb7fSLiu Bo 	 */
332475e7cb7fSLiu Bo 	fs_info->compress_type = BTRFS_COMPRESS_ZLIB;
332575e7cb7fSLiu Bo 
33266f93e834SAnand Jain 	/*
33276f93e834SAnand Jain 	 * Flag our filesystem as having big metadata blocks if they are bigger
33286f93e834SAnand Jain 	 * than the page size.
33296f93e834SAnand Jain 	 */
33306f93e834SAnand Jain 	if (btrfs_super_nodesize(disk_super) > PAGE_SIZE) {
33316f93e834SAnand Jain 		if (!(features & BTRFS_FEATURE_INCOMPAT_BIG_METADATA))
33326f93e834SAnand Jain 			btrfs_info(fs_info,
33336f93e834SAnand Jain 				"flagging fs with big metadata feature");
33346f93e834SAnand Jain 		features |= BTRFS_FEATURE_INCOMPAT_BIG_METADATA;
33356f93e834SAnand Jain 	}
33366f93e834SAnand Jain 
33376f93e834SAnand Jain 	/* Set up fs_info before parsing mount options */
33386f93e834SAnand Jain 	nodesize = btrfs_super_nodesize(disk_super);
33396f93e834SAnand Jain 	sectorsize = btrfs_super_sectorsize(disk_super);
33406f93e834SAnand Jain 	stripesize = sectorsize;
33416f93e834SAnand Jain 	fs_info->dirty_metadata_batch = nodesize * (1 + ilog2(nr_cpu_ids));
33426f93e834SAnand Jain 	fs_info->delalloc_batch = sectorsize * 512 * (1 + ilog2(nr_cpu_ids));
33436f93e834SAnand Jain 
33446f93e834SAnand Jain 	fs_info->nodesize = nodesize;
33456f93e834SAnand Jain 	fs_info->sectorsize = sectorsize;
33466f93e834SAnand Jain 	fs_info->sectorsize_bits = ilog2(sectorsize);
33476f93e834SAnand Jain 	fs_info->csums_per_leaf = BTRFS_MAX_ITEM_SIZE(fs_info) / fs_info->csum_size;
33486f93e834SAnand Jain 	fs_info->stripesize = stripesize;
33496f93e834SAnand Jain 
33502ff7e61eSJeff Mahoney 	ret = btrfs_parse_options(fs_info, options, sb->s_flags);
33512b82032cSYan Zheng 	if (ret) {
33522b82032cSYan Zheng 		err = ret;
3353141386e1SJosef Bacik 		goto fail_alloc;
33542b82032cSYan Zheng 	}
3355dfe25020SChris Mason 
3356f2b636e8SJosef Bacik 	features = btrfs_super_incompat_flags(disk_super) &
3357f2b636e8SJosef Bacik 		~BTRFS_FEATURE_INCOMPAT_SUPP;
3358f2b636e8SJosef Bacik 	if (features) {
335905135f59SDavid Sterba 		btrfs_err(fs_info,
336005135f59SDavid Sterba 		    "cannot mount because of unsupported optional features (%llx)",
3361c1c9ff7cSGeert Uytterhoeven 		    features);
3362f2b636e8SJosef Bacik 		err = -EINVAL;
3363141386e1SJosef Bacik 		goto fail_alloc;
3364f2b636e8SJosef Bacik 	}
3365f2b636e8SJosef Bacik 
33665d4f98a2SYan Zheng 	features = btrfs_super_incompat_flags(disk_super);
33675d4f98a2SYan Zheng 	features |= BTRFS_FEATURE_INCOMPAT_MIXED_BACKREF;
33680b246afaSJeff Mahoney 	if (fs_info->compress_type == BTRFS_COMPRESS_LZO)
3369a6fa6faeSLi Zefan 		features |= BTRFS_FEATURE_INCOMPAT_COMPRESS_LZO;
33705c1aab1dSNick Terrell 	else if (fs_info->compress_type == BTRFS_COMPRESS_ZSTD)
33715c1aab1dSNick Terrell 		features |= BTRFS_FEATURE_INCOMPAT_COMPRESS_ZSTD;
3372727011e0SChris Mason 
33733173a18fSJosef Bacik 	if (features & BTRFS_FEATURE_INCOMPAT_SKINNY_METADATA)
337405135f59SDavid Sterba 		btrfs_info(fs_info, "has skinny extents");
33753173a18fSJosef Bacik 
3376727011e0SChris Mason 	/*
3377bc3f116fSChris Mason 	 * mixed block groups end up with duplicate but slightly offset
3378bc3f116fSChris Mason 	 * extent buffers for the same range.  It leads to corruptions
3379bc3f116fSChris Mason 	 */
3380bc3f116fSChris Mason 	if ((features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS) &&
3381707e8a07SDavid Sterba 	    (sectorsize != nodesize)) {
338205135f59SDavid Sterba 		btrfs_err(fs_info,
338305135f59SDavid Sterba "unequal nodesize/sectorsize (%u != %u) are not allowed for mixed block groups",
338405135f59SDavid Sterba 			nodesize, sectorsize);
3385141386e1SJosef Bacik 		goto fail_alloc;
3386bc3f116fSChris Mason 	}
3387bc3f116fSChris Mason 
3388ceda0864SMiao Xie 	/*
3389ceda0864SMiao Xie 	 * Needn't use the lock because there is no other task which will
3390ceda0864SMiao Xie 	 * update the flag.
3391ceda0864SMiao Xie 	 */
33925d4f98a2SYan Zheng 	btrfs_set_super_incompat_flags(disk_super, features);
33935d4f98a2SYan Zheng 
3394f2b636e8SJosef Bacik 	features = btrfs_super_compat_ro_flags(disk_super) &
3395f2b636e8SJosef Bacik 		~BTRFS_FEATURE_COMPAT_RO_SUPP;
3396bc98a42cSDavid Howells 	if (!sb_rdonly(sb) && features) {
339705135f59SDavid Sterba 		btrfs_err(fs_info,
339805135f59SDavid Sterba 	"cannot mount read-write because of unsupported optional features (%llx)",
3399c1c9ff7cSGeert Uytterhoeven 		       features);
3400f2b636e8SJosef Bacik 		err = -EINVAL;
3401141386e1SJosef Bacik 		goto fail_alloc;
3402f2b636e8SJosef Bacik 	}
340361d92c32SChris Mason 
34048481dd80SQu Wenruo 	if (sectorsize < PAGE_SIZE) {
34058481dd80SQu Wenruo 		struct btrfs_subpage_info *subpage_info;
34068481dd80SQu Wenruo 
340795ea0486SQu Wenruo 		btrfs_warn(fs_info,
340895ea0486SQu Wenruo 		"read-write for sector size %u with page size %lu is experimental",
34090bb3eb3eSQu Wenruo 			   sectorsize, PAGE_SIZE);
3410c8050b3bSQu Wenruo 		if (btrfs_super_incompat_flags(fs_info->super_copy) &
3411c8050b3bSQu Wenruo 			BTRFS_FEATURE_INCOMPAT_RAID56) {
3412c8050b3bSQu Wenruo 			btrfs_err(fs_info,
3413c8050b3bSQu Wenruo 		"RAID56 is not yet supported for sector size %u with page size %lu",
3414c8050b3bSQu Wenruo 				sectorsize, PAGE_SIZE);
3415c8050b3bSQu Wenruo 			err = -EINVAL;
3416c8050b3bSQu Wenruo 			goto fail_alloc;
3417c8050b3bSQu Wenruo 		}
34188481dd80SQu Wenruo 		subpage_info = kzalloc(sizeof(*subpage_info), GFP_KERNEL);
34198481dd80SQu Wenruo 		if (!subpage_info)
34208481dd80SQu Wenruo 			goto fail_alloc;
34218481dd80SQu Wenruo 		btrfs_init_subpage_info(subpage_info, sectorsize);
34228481dd80SQu Wenruo 		fs_info->subpage_info = subpage_info;
3423c8050b3bSQu Wenruo 	}
34240bb3eb3eSQu Wenruo 
3425d21deec5SSu Yue 	ret = btrfs_init_workqueues(fs_info);
34262a458198SEric Sandeen 	if (ret) {
34272a458198SEric Sandeen 		err = ret;
34280dc3b84aSJosef Bacik 		goto fail_sb_buffer;
34290dc3b84aSJosef Bacik 	}
34304543df7eSChris Mason 
34319e11ceeeSJan Kara 	sb->s_bdi->ra_pages *= btrfs_super_num_devices(disk_super);
34329e11ceeeSJan Kara 	sb->s_bdi->ra_pages = max(sb->s_bdi->ra_pages, SZ_4M / PAGE_SIZE);
34334575c9ccSChris Mason 
3434a061fc8dSChris Mason 	sb->s_blocksize = sectorsize;
3435a061fc8dSChris Mason 	sb->s_blocksize_bits = blksize_bits(sectorsize);
3436de37aa51SNikolay Borisov 	memcpy(&sb->s_uuid, fs_info->fs_devices->fsid, BTRFS_FSID_SIZE);
3437db94535dSChris Mason 
3438925baeddSChris Mason 	mutex_lock(&fs_info->chunk_mutex);
34396bccf3abSJeff Mahoney 	ret = btrfs_read_sys_array(fs_info);
3440925baeddSChris Mason 	mutex_unlock(&fs_info->chunk_mutex);
344184eed90fSChris Mason 	if (ret) {
344205135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read the system array: %d", ret);
34435d4f98a2SYan Zheng 		goto fail_sb_buffer;
344484eed90fSChris Mason 	}
34450b86a832SChris Mason 
344684234f3aSYan Zheng 	generation = btrfs_super_chunk_root_generation(disk_super);
3447581c1760SQu Wenruo 	level = btrfs_super_chunk_root_level(disk_super);
34480b86a832SChris Mason 
34492ff7e61eSJeff Mahoney 	chunk_root->node = read_tree_block(fs_info,
34500b86a832SChris Mason 					   btrfs_super_chunk_root(disk_super),
34511b7ec85eSJosef Bacik 					   BTRFS_CHUNK_TREE_OBJECTID,
3452581c1760SQu Wenruo 					   generation, level, NULL);
345364c043deSLiu Bo 	if (IS_ERR(chunk_root->node) ||
345464c043deSLiu Bo 	    !extent_buffer_uptodate(chunk_root->node)) {
345505135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read chunk root");
3456e5fffbacSchandan 		if (!IS_ERR(chunk_root->node))
3457e5fffbacSchandan 			free_extent_buffer(chunk_root->node);
345895ab1f64SZhao Lei 		chunk_root->node = NULL;
3459af31f5e5SChris Mason 		goto fail_tree_roots;
346083121942SDavid Woodhouse 	}
34615d4f98a2SYan Zheng 	btrfs_set_root_node(&chunk_root->root_item, chunk_root->node);
34625d4f98a2SYan Zheng 	chunk_root->commit_root = btrfs_root_node(chunk_root);
34630b86a832SChris Mason 
3464e17cade2SChris Mason 	read_extent_buffer(chunk_root->node, fs_info->chunk_tree_uuid,
3465c4ac7541SDavid Sterba 			   offsetof(struct btrfs_header, chunk_tree_uuid),
3466c4ac7541SDavid Sterba 			   BTRFS_UUID_SIZE);
3467e17cade2SChris Mason 
34685b4aacefSJeff Mahoney 	ret = btrfs_read_chunk_tree(fs_info);
34692b82032cSYan Zheng 	if (ret) {
347005135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read chunk tree: %d", ret);
3471af31f5e5SChris Mason 		goto fail_tree_roots;
34722b82032cSYan Zheng 	}
34730b86a832SChris Mason 
34748dabb742SStefan Behrens 	/*
3475bacce86aSAnand Jain 	 * At this point we know all the devices that make this filesystem,
3476bacce86aSAnand Jain 	 * including the seed devices but we don't know yet if the replace
3477bacce86aSAnand Jain 	 * target is required. So free devices that are not part of this
34781a9fd417SDavid Sterba 	 * filesystem but skip the replace target device which is checked
3479bacce86aSAnand Jain 	 * below in btrfs_init_dev_replace().
34808dabb742SStefan Behrens 	 */
3481bacce86aSAnand Jain 	btrfs_free_extra_devids(fs_devices);
3482d24fa5c1SAnand Jain 	if (!fs_devices->latest_dev->bdev) {
348305135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read devices");
3484a6b0d5c8SChris Mason 		goto fail_tree_roots;
3485a6b0d5c8SChris Mason 	}
3486a6b0d5c8SChris Mason 
3487b8522a1eSNikolay Borisov 	ret = init_tree_roots(fs_info);
34884bbcaa64SEric Sandeen 	if (ret)
3489b8522a1eSNikolay Borisov 		goto fail_tree_roots;
34908929ecfaSYan, Zheng 
349175ec1db8SJosef Bacik 	/*
349273651042SNaohiro Aota 	 * Get zone type information of zoned block devices. This will also
349373651042SNaohiro Aota 	 * handle emulation of a zoned filesystem if a regular device has the
349473651042SNaohiro Aota 	 * zoned incompat feature flag set.
349573651042SNaohiro Aota 	 */
349673651042SNaohiro Aota 	ret = btrfs_get_dev_zone_info_all_devices(fs_info);
349773651042SNaohiro Aota 	if (ret) {
349873651042SNaohiro Aota 		btrfs_err(fs_info,
349973651042SNaohiro Aota 			  "zoned: failed to read device zone info: %d",
350073651042SNaohiro Aota 			  ret);
350173651042SNaohiro Aota 		goto fail_block_groups;
350273651042SNaohiro Aota 	}
350373651042SNaohiro Aota 
350473651042SNaohiro Aota 	/*
350575ec1db8SJosef Bacik 	 * If we have a uuid root and we're not being told to rescan we need to
350675ec1db8SJosef Bacik 	 * check the generation here so we can set the
350775ec1db8SJosef Bacik 	 * BTRFS_FS_UPDATE_UUID_TREE_GEN bit.  Otherwise we could commit the
350875ec1db8SJosef Bacik 	 * transaction during a balance or the log replay without updating the
350975ec1db8SJosef Bacik 	 * uuid generation, and then if we crash we would rescan the uuid tree,
351075ec1db8SJosef Bacik 	 * even though it was perfectly fine.
351175ec1db8SJosef Bacik 	 */
351275ec1db8SJosef Bacik 	if (fs_info->uuid_root && !btrfs_test_opt(fs_info, RESCAN_UUID_TREE) &&
351375ec1db8SJosef Bacik 	    fs_info->generation == btrfs_super_uuid_tree_generation(disk_super))
351475ec1db8SJosef Bacik 		set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
351575ec1db8SJosef Bacik 
3516cf90d884SQu Wenruo 	ret = btrfs_verify_dev_extents(fs_info);
3517cf90d884SQu Wenruo 	if (ret) {
3518cf90d884SQu Wenruo 		btrfs_err(fs_info,
3519cf90d884SQu Wenruo 			  "failed to verify dev extents against chunks: %d",
3520cf90d884SQu Wenruo 			  ret);
3521cf90d884SQu Wenruo 		goto fail_block_groups;
3522cf90d884SQu Wenruo 	}
352368310a5eSIlya Dryomov 	ret = btrfs_recover_balance(fs_info);
352468310a5eSIlya Dryomov 	if (ret) {
352505135f59SDavid Sterba 		btrfs_err(fs_info, "failed to recover balance: %d", ret);
352668310a5eSIlya Dryomov 		goto fail_block_groups;
352768310a5eSIlya Dryomov 	}
352868310a5eSIlya Dryomov 
3529733f4fbbSStefan Behrens 	ret = btrfs_init_dev_stats(fs_info);
3530733f4fbbSStefan Behrens 	if (ret) {
353105135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init dev_stats: %d", ret);
3532733f4fbbSStefan Behrens 		goto fail_block_groups;
3533733f4fbbSStefan Behrens 	}
3534733f4fbbSStefan Behrens 
35358dabb742SStefan Behrens 	ret = btrfs_init_dev_replace(fs_info);
35368dabb742SStefan Behrens 	if (ret) {
353705135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init dev_replace: %d", ret);
35388dabb742SStefan Behrens 		goto fail_block_groups;
35398dabb742SStefan Behrens 	}
35408dabb742SStefan Behrens 
3541b70f5097SNaohiro Aota 	ret = btrfs_check_zoned_mode(fs_info);
3542b70f5097SNaohiro Aota 	if (ret) {
3543b70f5097SNaohiro Aota 		btrfs_err(fs_info, "failed to initialize zoned mode: %d",
3544b70f5097SNaohiro Aota 			  ret);
3545b70f5097SNaohiro Aota 		goto fail_block_groups;
3546b70f5097SNaohiro Aota 	}
3547b70f5097SNaohiro Aota 
3548c6761a9eSAnand Jain 	ret = btrfs_sysfs_add_fsid(fs_devices);
3549b7c35e81SAnand Jain 	if (ret) {
355005135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init sysfs fsid interface: %d",
355105135f59SDavid Sterba 				ret);
3552b7c35e81SAnand Jain 		goto fail_block_groups;
3553b7c35e81SAnand Jain 	}
3554b7c35e81SAnand Jain 
355596f3136eSAnand Jain 	ret = btrfs_sysfs_add_mounted(fs_info);
35565ac1d209SJeff Mahoney 	if (ret) {
355705135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init sysfs interface: %d", ret);
3558b7c35e81SAnand Jain 		goto fail_fsdev_sysfs;
35595ac1d209SJeff Mahoney 	}
35605ac1d209SJeff Mahoney 
3561c59021f8Sliubo 	ret = btrfs_init_space_info(fs_info);
3562c59021f8Sliubo 	if (ret) {
356305135f59SDavid Sterba 		btrfs_err(fs_info, "failed to initialize space info: %d", ret);
35642365dd3cSAnand Jain 		goto fail_sysfs;
3565c59021f8Sliubo 	}
3566c59021f8Sliubo 
35675b4aacefSJeff Mahoney 	ret = btrfs_read_block_groups(fs_info);
35681b1d1f66SJosef Bacik 	if (ret) {
356905135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read block groups: %d", ret);
35702365dd3cSAnand Jain 		goto fail_sysfs;
35711b1d1f66SJosef Bacik 	}
35724330e183SQu Wenruo 
3573*16beac87SNaohiro Aota 	btrfs_free_zone_cache(fs_info);
3574*16beac87SNaohiro Aota 
35755c78a5e7SAnand Jain 	if (!sb_rdonly(sb) && fs_info->fs_devices->missing_devices &&
35765c78a5e7SAnand Jain 	    !btrfs_check_rw_degradable(fs_info, NULL)) {
357705135f59SDavid Sterba 		btrfs_warn(fs_info,
357852042d8eSAndrea Gelmini 		"writable mount is not allowed due to too many missing devices");
35792365dd3cSAnand Jain 		goto fail_sysfs;
3580292fd7fcSStefan Behrens 	}
35819078a3e1SChris Mason 
3582a74a4b97SChris Mason 	fs_info->cleaner_kthread = kthread_run(cleaner_kthread, tree_root,
3583a74a4b97SChris Mason 					       "btrfs-cleaner");
358457506d50SQinghuang Feng 	if (IS_ERR(fs_info->cleaner_kthread))
35852365dd3cSAnand Jain 		goto fail_sysfs;
3586a74a4b97SChris Mason 
3587a74a4b97SChris Mason 	fs_info->transaction_kthread = kthread_run(transaction_kthread,
3588a74a4b97SChris Mason 						   tree_root,
3589a74a4b97SChris Mason 						   "btrfs-transaction");
359057506d50SQinghuang Feng 	if (IS_ERR(fs_info->transaction_kthread))
35913f157a2fSChris Mason 		goto fail_cleaner;
3592a74a4b97SChris Mason 
3593583b7231SHans van Kranenburg 	if (!btrfs_test_opt(fs_info, NOSSD) &&
3594c289811cSChris Mason 	    !fs_info->fs_devices->rotating) {
3595583b7231SHans van Kranenburg 		btrfs_set_and_info(fs_info, SSD, "enabling ssd optimizations");
3596c289811cSChris Mason 	}
3597c289811cSChris Mason 
3598572d9ab7SDavid Sterba 	/*
359901327610SNicholas D Steeves 	 * Mount does not set all options immediately, we can do it now and do
3600572d9ab7SDavid Sterba 	 * not have to wait for transaction commit
3601572d9ab7SDavid Sterba 	 */
3602572d9ab7SDavid Sterba 	btrfs_apply_pending_changes(fs_info);
36033818aea2SQu Wenruo 
360421adbd5cSStefan Behrens #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
36050b246afaSJeff Mahoney 	if (btrfs_test_opt(fs_info, CHECK_INTEGRITY)) {
36062ff7e61eSJeff Mahoney 		ret = btrfsic_mount(fs_info, fs_devices,
36070b246afaSJeff Mahoney 				    btrfs_test_opt(fs_info,
3608cbeaae4fSDavid Sterba 					CHECK_INTEGRITY_DATA) ? 1 : 0,
360921adbd5cSStefan Behrens 				    fs_info->check_integrity_print_mask);
361021adbd5cSStefan Behrens 		if (ret)
361105135f59SDavid Sterba 			btrfs_warn(fs_info,
361205135f59SDavid Sterba 				"failed to initialize integrity check module: %d",
361305135f59SDavid Sterba 				ret);
361421adbd5cSStefan Behrens 	}
361521adbd5cSStefan Behrens #endif
3616bcef60f2SArne Jansen 	ret = btrfs_read_qgroup_config(fs_info);
3617bcef60f2SArne Jansen 	if (ret)
3618bcef60f2SArne Jansen 		goto fail_trans_kthread;
361921adbd5cSStefan Behrens 
3620fd708b81SJosef Bacik 	if (btrfs_build_ref_tree(fs_info))
3621fd708b81SJosef Bacik 		btrfs_err(fs_info, "couldn't build ref tree");
3622fd708b81SJosef Bacik 
362396da0919SQu Wenruo 	/* do not make disk changes in broken FS or nologreplay is given */
362496da0919SQu Wenruo 	if (btrfs_super_log_root(disk_super) != 0 &&
36250b246afaSJeff Mahoney 	    !btrfs_test_opt(fs_info, NOLOGREPLAY)) {
3626e8294f2fSDavid Sterba 		btrfs_info(fs_info, "start tree-log replay");
362763443bf5SEric Sandeen 		ret = btrfs_replay_log(fs_info, fs_devices);
362879787eaaSJeff Mahoney 		if (ret) {
362963443bf5SEric Sandeen 			err = ret;
363028c16cbbSWang Shilong 			goto fail_qgroup;
3631e556ce2cSYan Zheng 		}
3632e02119d5SChris Mason 	}
36331a40e23bSZheng Yan 
363456e9357aSDavid Sterba 	fs_info->fs_root = btrfs_get_fs_root(fs_info, BTRFS_FS_TREE_OBJECTID, true);
36353140c9a3SDan Carpenter 	if (IS_ERR(fs_info->fs_root)) {
36363140c9a3SDan Carpenter 		err = PTR_ERR(fs_info->fs_root);
3637f50f4353SLiu Bo 		btrfs_warn(fs_info, "failed to read fs tree: %d", err);
3638315bf8efSJosef Bacik 		fs_info->fs_root = NULL;
3639bcef60f2SArne Jansen 		goto fail_qgroup;
36403140c9a3SDan Carpenter 	}
3641c289811cSChris Mason 
3642bc98a42cSDavid Howells 	if (sb_rdonly(sb))
36438cd29088SBoris Burkov 		goto clear_oneshot;
36442b6ba629SIlya Dryomov 
364544c0ca21SBoris Burkov 	ret = btrfs_start_pre_rw_mount(fs_info);
36462b6ba629SIlya Dryomov 	if (ret) {
36476bccf3abSJeff Mahoney 		close_ctree(fs_info);
36482b6ba629SIlya Dryomov 		return ret;
3649e3acc2a6SJosef Bacik 	}
3650b0643e59SDennis Zhou 	btrfs_discard_resume(fs_info);
3651b382a324SJan Schmidt 
365244c0ca21SBoris Burkov 	if (fs_info->uuid_root &&
365344c0ca21SBoris Burkov 	    (btrfs_test_opt(fs_info, RESCAN_UUID_TREE) ||
365444c0ca21SBoris Burkov 	     fs_info->generation != btrfs_super_uuid_tree_generation(disk_super))) {
365505135f59SDavid Sterba 		btrfs_info(fs_info, "checking UUID tree");
365670f80175SStefan Behrens 		ret = btrfs_check_uuid_tree(fs_info);
365770f80175SStefan Behrens 		if (ret) {
365805135f59SDavid Sterba 			btrfs_warn(fs_info,
365905135f59SDavid Sterba 				"failed to check the UUID tree: %d", ret);
36606bccf3abSJeff Mahoney 			close_ctree(fs_info);
366170f80175SStefan Behrens 			return ret;
366270f80175SStefan Behrens 		}
3663f7a81ea4SStefan Behrens 	}
366494846229SBoris Burkov 
3665afcdd129SJosef Bacik 	set_bit(BTRFS_FS_OPEN, &fs_info->flags);
366647ab2a6cSJosef Bacik 
36678cd29088SBoris Burkov clear_oneshot:
36688cd29088SBoris Burkov 	btrfs_clear_oneshot_options(fs_info);
3669ad2b2c80SAl Viro 	return 0;
367039279cc3SChris Mason 
3671bcef60f2SArne Jansen fail_qgroup:
3672bcef60f2SArne Jansen 	btrfs_free_qgroup_config(fs_info);
36737c2ca468SChris Mason fail_trans_kthread:
36747c2ca468SChris Mason 	kthread_stop(fs_info->transaction_kthread);
36752ff7e61eSJeff Mahoney 	btrfs_cleanup_transaction(fs_info);
3676faa2dbf0SJosef Bacik 	btrfs_free_fs_roots(fs_info);
36773f157a2fSChris Mason fail_cleaner:
3678a74a4b97SChris Mason 	kthread_stop(fs_info->cleaner_kthread);
36797c2ca468SChris Mason 
36807c2ca468SChris Mason 	/*
36817c2ca468SChris Mason 	 * make sure we're done with the btree inode before we stop our
36827c2ca468SChris Mason 	 * kthreads
36837c2ca468SChris Mason 	 */
36847c2ca468SChris Mason 	filemap_write_and_wait(fs_info->btree_inode->i_mapping);
36857c2ca468SChris Mason 
36862365dd3cSAnand Jain fail_sysfs:
36876618a59bSAnand Jain 	btrfs_sysfs_remove_mounted(fs_info);
36882365dd3cSAnand Jain 
3689b7c35e81SAnand Jain fail_fsdev_sysfs:
3690b7c35e81SAnand Jain 	btrfs_sysfs_remove_fsid(fs_info->fs_devices);
3691b7c35e81SAnand Jain 
36921b1d1f66SJosef Bacik fail_block_groups:
369354067ae9SJosef Bacik 	btrfs_put_block_group_cache(fs_info);
3694af31f5e5SChris Mason 
3695af31f5e5SChris Mason fail_tree_roots:
36969e3aa805SJosef Bacik 	if (fs_info->data_reloc_root)
36979e3aa805SJosef Bacik 		btrfs_drop_and_free_fs_root(fs_info, fs_info->data_reloc_root);
36984273eaffSAnand Jain 	free_root_pointers(fs_info, true);
36992b8195bbSMiao Xie 	invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
3700af31f5e5SChris Mason 
370139279cc3SChris Mason fail_sb_buffer:
37027abadb64SLiu Bo 	btrfs_stop_all_workers(fs_info);
37035cdd7db6SFilipe Manana 	btrfs_free_block_groups(fs_info);
370416cdcec7SMiao Xie fail_alloc:
3705586e46e2SIlya Dryomov 	btrfs_mapping_tree_free(&fs_info->mapping_tree);
3706586e46e2SIlya Dryomov 
37074543df7eSChris Mason 	iput(fs_info->btree_inode);
37087e662854SQinghuang Feng fail:
3709586e46e2SIlya Dryomov 	btrfs_close_devices(fs_info->fs_devices);
3710ad2b2c80SAl Viro 	return err;
3711eb60ceacSChris Mason }
3712663faf9fSMasami Hiramatsu ALLOW_ERROR_INJECTION(open_ctree, ERRNO);
3713eb60ceacSChris Mason 
3714314b6dd0SJohannes Thumshirn static void btrfs_end_super_write(struct bio *bio)
3715f2984462SChris Mason {
3716314b6dd0SJohannes Thumshirn 	struct btrfs_device *device = bio->bi_private;
3717314b6dd0SJohannes Thumshirn 	struct bio_vec *bvec;
3718314b6dd0SJohannes Thumshirn 	struct bvec_iter_all iter_all;
3719314b6dd0SJohannes Thumshirn 	struct page *page;
3720442a4f63SStefan Behrens 
3721314b6dd0SJohannes Thumshirn 	bio_for_each_segment_all(bvec, bio, iter_all) {
3722314b6dd0SJohannes Thumshirn 		page = bvec->bv_page;
3723314b6dd0SJohannes Thumshirn 
3724314b6dd0SJohannes Thumshirn 		if (bio->bi_status) {
3725fb456252SJeff Mahoney 			btrfs_warn_rl_in_rcu(device->fs_info,
3726314b6dd0SJohannes Thumshirn 				"lost page write due to IO error on %s (%d)",
3727314b6dd0SJohannes Thumshirn 				rcu_str_deref(device->name),
3728314b6dd0SJohannes Thumshirn 				blk_status_to_errno(bio->bi_status));
3729314b6dd0SJohannes Thumshirn 			ClearPageUptodate(page);
3730314b6dd0SJohannes Thumshirn 			SetPageError(page);
3731314b6dd0SJohannes Thumshirn 			btrfs_dev_stat_inc_and_print(device,
3732314b6dd0SJohannes Thumshirn 						     BTRFS_DEV_STAT_WRITE_ERRS);
3733314b6dd0SJohannes Thumshirn 		} else {
3734314b6dd0SJohannes Thumshirn 			SetPageUptodate(page);
3735f2984462SChris Mason 		}
3736314b6dd0SJohannes Thumshirn 
3737314b6dd0SJohannes Thumshirn 		put_page(page);
3738314b6dd0SJohannes Thumshirn 		unlock_page(page);
3739314b6dd0SJohannes Thumshirn 	}
3740314b6dd0SJohannes Thumshirn 
3741314b6dd0SJohannes Thumshirn 	bio_put(bio);
3742f2984462SChris Mason }
3743f2984462SChris Mason 
37448f32380dSJohannes Thumshirn struct btrfs_super_block *btrfs_read_dev_one_super(struct block_device *bdev,
37458f32380dSJohannes Thumshirn 						   int copy_num)
374629c36d72SAnand Jain {
374729c36d72SAnand Jain 	struct btrfs_super_block *super;
37488f32380dSJohannes Thumshirn 	struct page *page;
374912659251SNaohiro Aota 	u64 bytenr, bytenr_orig;
37508f32380dSJohannes Thumshirn 	struct address_space *mapping = bdev->bd_inode->i_mapping;
375112659251SNaohiro Aota 	int ret;
375229c36d72SAnand Jain 
375312659251SNaohiro Aota 	bytenr_orig = btrfs_sb_offset(copy_num);
375412659251SNaohiro Aota 	ret = btrfs_sb_log_location_bdev(bdev, copy_num, READ, &bytenr);
375512659251SNaohiro Aota 	if (ret == -ENOENT)
375612659251SNaohiro Aota 		return ERR_PTR(-EINVAL);
375712659251SNaohiro Aota 	else if (ret)
375812659251SNaohiro Aota 		return ERR_PTR(ret);
375912659251SNaohiro Aota 
3760cda00ebaSChristoph Hellwig 	if (bytenr + BTRFS_SUPER_INFO_SIZE >= bdev_nr_bytes(bdev))
37618f32380dSJohannes Thumshirn 		return ERR_PTR(-EINVAL);
376229c36d72SAnand Jain 
37638f32380dSJohannes Thumshirn 	page = read_cache_page_gfp(mapping, bytenr >> PAGE_SHIFT, GFP_NOFS);
37648f32380dSJohannes Thumshirn 	if (IS_ERR(page))
37658f32380dSJohannes Thumshirn 		return ERR_CAST(page);
376629c36d72SAnand Jain 
37678f32380dSJohannes Thumshirn 	super = page_address(page);
376896c2e067SAnand Jain 	if (btrfs_super_magic(super) != BTRFS_MAGIC) {
376996c2e067SAnand Jain 		btrfs_release_disk_super(super);
377096c2e067SAnand Jain 		return ERR_PTR(-ENODATA);
377196c2e067SAnand Jain 	}
377296c2e067SAnand Jain 
377312659251SNaohiro Aota 	if (btrfs_super_bytenr(super) != bytenr_orig) {
37748f32380dSJohannes Thumshirn 		btrfs_release_disk_super(super);
37758f32380dSJohannes Thumshirn 		return ERR_PTR(-EINVAL);
377629c36d72SAnand Jain 	}
377729c36d72SAnand Jain 
37788f32380dSJohannes Thumshirn 	return super;
377929c36d72SAnand Jain }
378029c36d72SAnand Jain 
378129c36d72SAnand Jain 
37828f32380dSJohannes Thumshirn struct btrfs_super_block *btrfs_read_dev_super(struct block_device *bdev)
3783a512bbf8SYan Zheng {
37848f32380dSJohannes Thumshirn 	struct btrfs_super_block *super, *latest = NULL;
3785a512bbf8SYan Zheng 	int i;
3786a512bbf8SYan Zheng 	u64 transid = 0;
3787a512bbf8SYan Zheng 
3788a512bbf8SYan Zheng 	/* we would like to check all the supers, but that would make
3789a512bbf8SYan Zheng 	 * a btrfs mount succeed after a mkfs from a different FS.
3790a512bbf8SYan Zheng 	 * So, we need to add a special mount option to scan for
3791a512bbf8SYan Zheng 	 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
3792a512bbf8SYan Zheng 	 */
3793a512bbf8SYan Zheng 	for (i = 0; i < 1; i++) {
37948f32380dSJohannes Thumshirn 		super = btrfs_read_dev_one_super(bdev, i);
37958f32380dSJohannes Thumshirn 		if (IS_ERR(super))
3796a512bbf8SYan Zheng 			continue;
3797a512bbf8SYan Zheng 
3798a512bbf8SYan Zheng 		if (!latest || btrfs_super_generation(super) > transid) {
37998f32380dSJohannes Thumshirn 			if (latest)
38008f32380dSJohannes Thumshirn 				btrfs_release_disk_super(super);
38018f32380dSJohannes Thumshirn 
38028f32380dSJohannes Thumshirn 			latest = super;
3803a512bbf8SYan Zheng 			transid = btrfs_super_generation(super);
3804a512bbf8SYan Zheng 		}
3805a512bbf8SYan Zheng 	}
380692fc03fbSAnand Jain 
38078f32380dSJohannes Thumshirn 	return super;
3808a512bbf8SYan Zheng }
3809a512bbf8SYan Zheng 
38104eedeb75SHisashi Hifumi /*
3811abbb3b8eSDavid Sterba  * Write superblock @sb to the @device. Do not wait for completion, all the
3812314b6dd0SJohannes Thumshirn  * pages we use for writing are locked.
38134eedeb75SHisashi Hifumi  *
3814abbb3b8eSDavid Sterba  * Write @max_mirrors copies of the superblock, where 0 means default that fit
3815abbb3b8eSDavid Sterba  * the expected device size at commit time. Note that max_mirrors must be
3816abbb3b8eSDavid Sterba  * same for write and wait phases.
38174eedeb75SHisashi Hifumi  *
3818314b6dd0SJohannes Thumshirn  * Return number of errors when page is not found or submission fails.
38194eedeb75SHisashi Hifumi  */
3820a512bbf8SYan Zheng static int write_dev_supers(struct btrfs_device *device,
3821abbb3b8eSDavid Sterba 			    struct btrfs_super_block *sb, int max_mirrors)
3822a512bbf8SYan Zheng {
3823d5178578SJohannes Thumshirn 	struct btrfs_fs_info *fs_info = device->fs_info;
3824314b6dd0SJohannes Thumshirn 	struct address_space *mapping = device->bdev->bd_inode->i_mapping;
3825d5178578SJohannes Thumshirn 	SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
3826a512bbf8SYan Zheng 	int i;
3827a512bbf8SYan Zheng 	int errors = 0;
382812659251SNaohiro Aota 	int ret;
382912659251SNaohiro Aota 	u64 bytenr, bytenr_orig;
3830a512bbf8SYan Zheng 
3831a512bbf8SYan Zheng 	if (max_mirrors == 0)
3832a512bbf8SYan Zheng 		max_mirrors = BTRFS_SUPER_MIRROR_MAX;
3833a512bbf8SYan Zheng 
3834d5178578SJohannes Thumshirn 	shash->tfm = fs_info->csum_shash;
3835d5178578SJohannes Thumshirn 
3836a512bbf8SYan Zheng 	for (i = 0; i < max_mirrors; i++) {
3837314b6dd0SJohannes Thumshirn 		struct page *page;
3838314b6dd0SJohannes Thumshirn 		struct bio *bio;
3839314b6dd0SJohannes Thumshirn 		struct btrfs_super_block *disk_super;
3840314b6dd0SJohannes Thumshirn 
384112659251SNaohiro Aota 		bytenr_orig = btrfs_sb_offset(i);
384212659251SNaohiro Aota 		ret = btrfs_sb_log_location(device, i, WRITE, &bytenr);
384312659251SNaohiro Aota 		if (ret == -ENOENT) {
384412659251SNaohiro Aota 			continue;
384512659251SNaohiro Aota 		} else if (ret < 0) {
384612659251SNaohiro Aota 			btrfs_err(device->fs_info,
384712659251SNaohiro Aota 				"couldn't get super block location for mirror %d",
384812659251SNaohiro Aota 				i);
384912659251SNaohiro Aota 			errors++;
385012659251SNaohiro Aota 			continue;
385112659251SNaohiro Aota 		}
3852935e5cc9SMiao Xie 		if (bytenr + BTRFS_SUPER_INFO_SIZE >=
3853935e5cc9SMiao Xie 		    device->commit_total_bytes)
3854a512bbf8SYan Zheng 			break;
3855a512bbf8SYan Zheng 
385612659251SNaohiro Aota 		btrfs_set_super_bytenr(sb, bytenr_orig);
3857a512bbf8SYan Zheng 
3858fd08001fSEric Biggers 		crypto_shash_digest(shash, (const char *)sb + BTRFS_CSUM_SIZE,
3859fd08001fSEric Biggers 				    BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE,
3860fd08001fSEric Biggers 				    sb->csum);
3861a512bbf8SYan Zheng 
3862314b6dd0SJohannes Thumshirn 		page = find_or_create_page(mapping, bytenr >> PAGE_SHIFT,
3863314b6dd0SJohannes Thumshirn 					   GFP_NOFS);
3864314b6dd0SJohannes Thumshirn 		if (!page) {
3865fb456252SJeff Mahoney 			btrfs_err(device->fs_info,
3866314b6dd0SJohannes Thumshirn 			    "couldn't get super block page for bytenr %llu",
3867f14d104dSDavid Sterba 			    bytenr);
3868634554dcSJosef Bacik 			errors++;
3869634554dcSJosef Bacik 			continue;
3870634554dcSJosef Bacik 		}
3871634554dcSJosef Bacik 
3872314b6dd0SJohannes Thumshirn 		/* Bump the refcount for wait_dev_supers() */
3873314b6dd0SJohannes Thumshirn 		get_page(page);
3874a512bbf8SYan Zheng 
3875314b6dd0SJohannes Thumshirn 		disk_super = page_address(page);
3876314b6dd0SJohannes Thumshirn 		memcpy(disk_super, sb, BTRFS_SUPER_INFO_SIZE);
3877a512bbf8SYan Zheng 
3878387125fcSChris Mason 		/*
3879314b6dd0SJohannes Thumshirn 		 * Directly use bios here instead of relying on the page cache
3880314b6dd0SJohannes Thumshirn 		 * to do I/O, so we don't lose the ability to do integrity
3881314b6dd0SJohannes Thumshirn 		 * checking.
3882387125fcSChris Mason 		 */
3883314b6dd0SJohannes Thumshirn 		bio = bio_alloc(GFP_NOFS, 1);
3884314b6dd0SJohannes Thumshirn 		bio_set_dev(bio, device->bdev);
3885314b6dd0SJohannes Thumshirn 		bio->bi_iter.bi_sector = bytenr >> SECTOR_SHIFT;
3886314b6dd0SJohannes Thumshirn 		bio->bi_private = device;
3887314b6dd0SJohannes Thumshirn 		bio->bi_end_io = btrfs_end_super_write;
3888314b6dd0SJohannes Thumshirn 		__bio_add_page(bio, page, BTRFS_SUPER_INFO_SIZE,
3889314b6dd0SJohannes Thumshirn 			       offset_in_page(bytenr));
3890314b6dd0SJohannes Thumshirn 
3891314b6dd0SJohannes Thumshirn 		/*
3892314b6dd0SJohannes Thumshirn 		 * We FUA only the first super block.  The others we allow to
3893314b6dd0SJohannes Thumshirn 		 * go down lazy and there's a short window where the on-disk
3894314b6dd0SJohannes Thumshirn 		 * copies might still contain the older version.
3895314b6dd0SJohannes Thumshirn 		 */
3896314b6dd0SJohannes Thumshirn 		bio->bi_opf = REQ_OP_WRITE | REQ_SYNC | REQ_META | REQ_PRIO;
38971b9e619cSOmar Sandoval 		if (i == 0 && !btrfs_test_opt(device->fs_info, NOBARRIER))
3898314b6dd0SJohannes Thumshirn 			bio->bi_opf |= REQ_FUA;
3899314b6dd0SJohannes Thumshirn 
3900314b6dd0SJohannes Thumshirn 		btrfsic_submit_bio(bio);
39018376d9e1SNaohiro Aota 
39028376d9e1SNaohiro Aota 		if (btrfs_advance_sb_log(device, i))
39038376d9e1SNaohiro Aota 			errors++;
3904a512bbf8SYan Zheng 	}
3905a512bbf8SYan Zheng 	return errors < i ? 0 : -1;
3906a512bbf8SYan Zheng }
3907a512bbf8SYan Zheng 
3908387125fcSChris Mason /*
3909abbb3b8eSDavid Sterba  * Wait for write completion of superblocks done by write_dev_supers,
3910abbb3b8eSDavid Sterba  * @max_mirrors same for write and wait phases.
3911abbb3b8eSDavid Sterba  *
3912314b6dd0SJohannes Thumshirn  * Return number of errors when page is not found or not marked up to
3913abbb3b8eSDavid Sterba  * date.
3914abbb3b8eSDavid Sterba  */
3915abbb3b8eSDavid Sterba static int wait_dev_supers(struct btrfs_device *device, int max_mirrors)
3916abbb3b8eSDavid Sterba {
3917abbb3b8eSDavid Sterba 	int i;
3918abbb3b8eSDavid Sterba 	int errors = 0;
3919b6a535faSHoward McLauchlan 	bool primary_failed = false;
392012659251SNaohiro Aota 	int ret;
3921abbb3b8eSDavid Sterba 	u64 bytenr;
3922abbb3b8eSDavid Sterba 
3923abbb3b8eSDavid Sterba 	if (max_mirrors == 0)
3924abbb3b8eSDavid Sterba 		max_mirrors = BTRFS_SUPER_MIRROR_MAX;
3925abbb3b8eSDavid Sterba 
3926abbb3b8eSDavid Sterba 	for (i = 0; i < max_mirrors; i++) {
3927314b6dd0SJohannes Thumshirn 		struct page *page;
3928314b6dd0SJohannes Thumshirn 
392912659251SNaohiro Aota 		ret = btrfs_sb_log_location(device, i, READ, &bytenr);
393012659251SNaohiro Aota 		if (ret == -ENOENT) {
393112659251SNaohiro Aota 			break;
393212659251SNaohiro Aota 		} else if (ret < 0) {
393312659251SNaohiro Aota 			errors++;
393412659251SNaohiro Aota 			if (i == 0)
393512659251SNaohiro Aota 				primary_failed = true;
393612659251SNaohiro Aota 			continue;
393712659251SNaohiro Aota 		}
3938abbb3b8eSDavid Sterba 		if (bytenr + BTRFS_SUPER_INFO_SIZE >=
3939abbb3b8eSDavid Sterba 		    device->commit_total_bytes)
3940abbb3b8eSDavid Sterba 			break;
3941abbb3b8eSDavid Sterba 
3942314b6dd0SJohannes Thumshirn 		page = find_get_page(device->bdev->bd_inode->i_mapping,
3943314b6dd0SJohannes Thumshirn 				     bytenr >> PAGE_SHIFT);
3944314b6dd0SJohannes Thumshirn 		if (!page) {
3945abbb3b8eSDavid Sterba 			errors++;
3946b6a535faSHoward McLauchlan 			if (i == 0)
3947b6a535faSHoward McLauchlan 				primary_failed = true;
3948abbb3b8eSDavid Sterba 			continue;
3949abbb3b8eSDavid Sterba 		}
3950314b6dd0SJohannes Thumshirn 		/* Page is submitted locked and unlocked once the IO completes */
3951314b6dd0SJohannes Thumshirn 		wait_on_page_locked(page);
3952314b6dd0SJohannes Thumshirn 		if (PageError(page)) {
3953abbb3b8eSDavid Sterba 			errors++;
3954b6a535faSHoward McLauchlan 			if (i == 0)
3955b6a535faSHoward McLauchlan 				primary_failed = true;
3956b6a535faSHoward McLauchlan 		}
3957abbb3b8eSDavid Sterba 
3958314b6dd0SJohannes Thumshirn 		/* Drop our reference */
3959314b6dd0SJohannes Thumshirn 		put_page(page);
3960abbb3b8eSDavid Sterba 
3961314b6dd0SJohannes Thumshirn 		/* Drop the reference from the writing run */
3962314b6dd0SJohannes Thumshirn 		put_page(page);
3963abbb3b8eSDavid Sterba 	}
3964abbb3b8eSDavid Sterba 
3965b6a535faSHoward McLauchlan 	/* log error, force error return */
3966b6a535faSHoward McLauchlan 	if (primary_failed) {
3967b6a535faSHoward McLauchlan 		btrfs_err(device->fs_info, "error writing primary super block to device %llu",
3968b6a535faSHoward McLauchlan 			  device->devid);
3969b6a535faSHoward McLauchlan 		return -1;
3970b6a535faSHoward McLauchlan 	}
3971b6a535faSHoward McLauchlan 
3972abbb3b8eSDavid Sterba 	return errors < i ? 0 : -1;
3973abbb3b8eSDavid Sterba }
3974abbb3b8eSDavid Sterba 
3975abbb3b8eSDavid Sterba /*
3976387125fcSChris Mason  * endio for the write_dev_flush, this will wake anyone waiting
3977387125fcSChris Mason  * for the barrier when it is done
3978387125fcSChris Mason  */
39794246a0b6SChristoph Hellwig static void btrfs_end_empty_barrier(struct bio *bio)
3980387125fcSChris Mason {
3981387125fcSChris Mason 	complete(bio->bi_private);
3982387125fcSChris Mason }
3983387125fcSChris Mason 
3984387125fcSChris Mason /*
39854fc6441aSAnand Jain  * Submit a flush request to the device if it supports it. Error handling is
39864fc6441aSAnand Jain  * done in the waiting counterpart.
3987387125fcSChris Mason  */
39884fc6441aSAnand Jain static void write_dev_flush(struct btrfs_device *device)
3989387125fcSChris Mason {
3990e0ae9994SDavid Sterba 	struct bio *bio = device->flush_bio;
3991387125fcSChris Mason 
3992a91cf0ffSWang Yugui #ifndef CONFIG_BTRFS_FS_CHECK_INTEGRITY
3993a91cf0ffSWang Yugui 	/*
3994a91cf0ffSWang Yugui 	 * When a disk has write caching disabled, we skip submission of a bio
3995a91cf0ffSWang Yugui 	 * with flush and sync requests before writing the superblock, since
3996a91cf0ffSWang Yugui 	 * it's not needed. However when the integrity checker is enabled, this
3997a91cf0ffSWang Yugui 	 * results in reports that there are metadata blocks referred by a
3998a91cf0ffSWang Yugui 	 * superblock that were not properly flushed. So don't skip the bio
3999a91cf0ffSWang Yugui 	 * submission only when the integrity checker is enabled for the sake
4000a91cf0ffSWang Yugui 	 * of simplicity, since this is a debug tool and not meant for use in
4001a91cf0ffSWang Yugui 	 * non-debug builds.
4002a91cf0ffSWang Yugui 	 */
4003a91cf0ffSWang Yugui 	struct request_queue *q = bdev_get_queue(device->bdev);
4004c2a9c7abSAnand Jain 	if (!test_bit(QUEUE_FLAG_WC, &q->queue_flags))
40054fc6441aSAnand Jain 		return;
4006a91cf0ffSWang Yugui #endif
4007387125fcSChris Mason 
4008e0ae9994SDavid Sterba 	bio_reset(bio);
4009387125fcSChris Mason 	bio->bi_end_io = btrfs_end_empty_barrier;
401074d46992SChristoph Hellwig 	bio_set_dev(bio, device->bdev);
40118d910125SJan Kara 	bio->bi_opf = REQ_OP_WRITE | REQ_SYNC | REQ_PREFLUSH;
4012387125fcSChris Mason 	init_completion(&device->flush_wait);
4013387125fcSChris Mason 	bio->bi_private = &device->flush_wait;
4014387125fcSChris Mason 
401543a01111SLu Fengqi 	btrfsic_submit_bio(bio);
40161c3063b6SAnand Jain 	set_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state);
40174fc6441aSAnand Jain }
4018387125fcSChris Mason 
40194fc6441aSAnand Jain /*
40204fc6441aSAnand Jain  * If the flush bio has been submitted by write_dev_flush, wait for it.
40214fc6441aSAnand Jain  */
40228c27cb35SLinus Torvalds static blk_status_t wait_dev_flush(struct btrfs_device *device)
40234fc6441aSAnand Jain {
40244fc6441aSAnand Jain 	struct bio *bio = device->flush_bio;
40254fc6441aSAnand Jain 
40261c3063b6SAnand Jain 	if (!test_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state))
402758efbc9fSOmar Sandoval 		return BLK_STS_OK;
40284fc6441aSAnand Jain 
40291c3063b6SAnand Jain 	clear_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state);
40302980d574SDavid Sterba 	wait_for_completion_io(&device->flush_wait);
40314fc6441aSAnand Jain 
40328c27cb35SLinus Torvalds 	return bio->bi_status;
4033387125fcSChris Mason }
4034387125fcSChris Mason 
4035d10b82feSQu Wenruo static int check_barrier_error(struct btrfs_fs_info *fs_info)
4036401b41e5SAnand Jain {
40376528b99dSAnand Jain 	if (!btrfs_check_rw_degradable(fs_info, NULL))
4038401b41e5SAnand Jain 		return -EIO;
4039387125fcSChris Mason 	return 0;
4040387125fcSChris Mason }
4041387125fcSChris Mason 
4042387125fcSChris Mason /*
4043387125fcSChris Mason  * send an empty flush down to each device in parallel,
4044387125fcSChris Mason  * then wait for them
4045387125fcSChris Mason  */
4046387125fcSChris Mason static int barrier_all_devices(struct btrfs_fs_info *info)
4047387125fcSChris Mason {
4048387125fcSChris Mason 	struct list_head *head;
4049387125fcSChris Mason 	struct btrfs_device *dev;
40505af3e8ccSStefan Behrens 	int errors_wait = 0;
40514e4cbee9SChristoph Hellwig 	blk_status_t ret;
4052387125fcSChris Mason 
40531538e6c5SDavid Sterba 	lockdep_assert_held(&info->fs_devices->device_list_mutex);
4054387125fcSChris Mason 	/* send down all the barriers */
4055387125fcSChris Mason 	head = &info->fs_devices->devices;
40561538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
4057e6e674bdSAnand Jain 		if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
4058f88ba6a2SHidetoshi Seto 			continue;
4059cea7c8bfSAnand Jain 		if (!dev->bdev)
4060387125fcSChris Mason 			continue;
4061e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
4062ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
4063387125fcSChris Mason 			continue;
4064387125fcSChris Mason 
40654fc6441aSAnand Jain 		write_dev_flush(dev);
406658efbc9fSOmar Sandoval 		dev->last_flush_error = BLK_STS_OK;
4067387125fcSChris Mason 	}
4068387125fcSChris Mason 
4069387125fcSChris Mason 	/* wait for all the barriers */
40701538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
4071e6e674bdSAnand Jain 		if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
4072f88ba6a2SHidetoshi Seto 			continue;
4073387125fcSChris Mason 		if (!dev->bdev) {
40745af3e8ccSStefan Behrens 			errors_wait++;
4075387125fcSChris Mason 			continue;
4076387125fcSChris Mason 		}
4077e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
4078ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
4079387125fcSChris Mason 			continue;
4080387125fcSChris Mason 
40814fc6441aSAnand Jain 		ret = wait_dev_flush(dev);
4082401b41e5SAnand Jain 		if (ret) {
4083401b41e5SAnand Jain 			dev->last_flush_error = ret;
408466b4993eSDavid Sterba 			btrfs_dev_stat_inc_and_print(dev,
408566b4993eSDavid Sterba 					BTRFS_DEV_STAT_FLUSH_ERRS);
40865af3e8ccSStefan Behrens 			errors_wait++;
4087387125fcSChris Mason 		}
4088401b41e5SAnand Jain 	}
4089401b41e5SAnand Jain 
4090cea7c8bfSAnand Jain 	if (errors_wait) {
4091401b41e5SAnand Jain 		/*
4092401b41e5SAnand Jain 		 * At some point we need the status of all disks
4093401b41e5SAnand Jain 		 * to arrive at the volume status. So error checking
4094401b41e5SAnand Jain 		 * is being pushed to a separate loop.
4095401b41e5SAnand Jain 		 */
4096d10b82feSQu Wenruo 		return check_barrier_error(info);
4097401b41e5SAnand Jain 	}
4098387125fcSChris Mason 	return 0;
4099387125fcSChris Mason }
4100387125fcSChris Mason 
4101943c6e99SZhao Lei int btrfs_get_num_tolerated_disk_barrier_failures(u64 flags)
4102943c6e99SZhao Lei {
41038789f4feSZhao Lei 	int raid_type;
41048789f4feSZhao Lei 	int min_tolerated = INT_MAX;
4105943c6e99SZhao Lei 
41068789f4feSZhao Lei 	if ((flags & BTRFS_BLOCK_GROUP_PROFILE_MASK) == 0 ||
41078789f4feSZhao Lei 	    (flags & BTRFS_AVAIL_ALLOC_BIT_SINGLE))
41088c3e3582SDavid Sterba 		min_tolerated = min_t(int, min_tolerated,
41098789f4feSZhao Lei 				    btrfs_raid_array[BTRFS_RAID_SINGLE].
41108789f4feSZhao Lei 				    tolerated_failures);
4111943c6e99SZhao Lei 
41128789f4feSZhao Lei 	for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) {
41138789f4feSZhao Lei 		if (raid_type == BTRFS_RAID_SINGLE)
41148789f4feSZhao Lei 			continue;
411541a6e891SAnand Jain 		if (!(flags & btrfs_raid_array[raid_type].bg_flag))
41168789f4feSZhao Lei 			continue;
41178c3e3582SDavid Sterba 		min_tolerated = min_t(int, min_tolerated,
41188789f4feSZhao Lei 				    btrfs_raid_array[raid_type].
41198789f4feSZhao Lei 				    tolerated_failures);
41208789f4feSZhao Lei 	}
4121943c6e99SZhao Lei 
41228789f4feSZhao Lei 	if (min_tolerated == INT_MAX) {
4123ab8d0fc4SJeff Mahoney 		pr_warn("BTRFS: unknown raid flag: %llu", flags);
41248789f4feSZhao Lei 		min_tolerated = 0;
41258789f4feSZhao Lei 	}
41268789f4feSZhao Lei 
41278789f4feSZhao Lei 	return min_tolerated;
4128943c6e99SZhao Lei }
4129943c6e99SZhao Lei 
4130eece6a9cSDavid Sterba int write_all_supers(struct btrfs_fs_info *fs_info, int max_mirrors)
4131f2984462SChris Mason {
4132e5e9a520SChris Mason 	struct list_head *head;
4133f2984462SChris Mason 	struct btrfs_device *dev;
4134a061fc8dSChris Mason 	struct btrfs_super_block *sb;
4135f2984462SChris Mason 	struct btrfs_dev_item *dev_item;
4136f2984462SChris Mason 	int ret;
4137f2984462SChris Mason 	int do_barriers;
4138a236aed1SChris Mason 	int max_errors;
4139a236aed1SChris Mason 	int total_errors = 0;
4140a061fc8dSChris Mason 	u64 flags;
4141f2984462SChris Mason 
41420b246afaSJeff Mahoney 	do_barriers = !btrfs_test_opt(fs_info, NOBARRIER);
4143fed3b381SLiu Bo 
4144fed3b381SLiu Bo 	/*
4145fed3b381SLiu Bo 	 * max_mirrors == 0 indicates we're from commit_transaction,
4146fed3b381SLiu Bo 	 * not from fsync where the tree roots in fs_info have not
4147fed3b381SLiu Bo 	 * been consistent on disk.
4148fed3b381SLiu Bo 	 */
4149fed3b381SLiu Bo 	if (max_mirrors == 0)
41500b246afaSJeff Mahoney 		backup_super_roots(fs_info);
4151f2984462SChris Mason 
41520b246afaSJeff Mahoney 	sb = fs_info->super_for_commit;
4153a061fc8dSChris Mason 	dev_item = &sb->dev_item;
4154e5e9a520SChris Mason 
41550b246afaSJeff Mahoney 	mutex_lock(&fs_info->fs_devices->device_list_mutex);
41560b246afaSJeff Mahoney 	head = &fs_info->fs_devices->devices;
41570b246afaSJeff Mahoney 	max_errors = btrfs_super_num_devices(fs_info->super_copy) - 1;
4158387125fcSChris Mason 
41595af3e8ccSStefan Behrens 	if (do_barriers) {
41600b246afaSJeff Mahoney 		ret = barrier_all_devices(fs_info);
41615af3e8ccSStefan Behrens 		if (ret) {
41625af3e8ccSStefan Behrens 			mutex_unlock(
41630b246afaSJeff Mahoney 				&fs_info->fs_devices->device_list_mutex);
41640b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret,
41655af3e8ccSStefan Behrens 					      "errors while submitting device barriers.");
41665af3e8ccSStefan Behrens 			return ret;
41675af3e8ccSStefan Behrens 		}
41685af3e8ccSStefan Behrens 	}
4169387125fcSChris Mason 
41701538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
4171dfe25020SChris Mason 		if (!dev->bdev) {
4172dfe25020SChris Mason 			total_errors++;
4173dfe25020SChris Mason 			continue;
4174dfe25020SChris Mason 		}
4175e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
4176ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
4177dfe25020SChris Mason 			continue;
4178dfe25020SChris Mason 
41792b82032cSYan Zheng 		btrfs_set_stack_device_generation(dev_item, 0);
4180a061fc8dSChris Mason 		btrfs_set_stack_device_type(dev_item, dev->type);
4181a061fc8dSChris Mason 		btrfs_set_stack_device_id(dev_item, dev->devid);
41827df69d3eSMiao Xie 		btrfs_set_stack_device_total_bytes(dev_item,
4183935e5cc9SMiao Xie 						   dev->commit_total_bytes);
4184ce7213c7SMiao Xie 		btrfs_set_stack_device_bytes_used(dev_item,
4185ce7213c7SMiao Xie 						  dev->commit_bytes_used);
4186a061fc8dSChris Mason 		btrfs_set_stack_device_io_align(dev_item, dev->io_align);
4187a061fc8dSChris Mason 		btrfs_set_stack_device_io_width(dev_item, dev->io_width);
4188a061fc8dSChris Mason 		btrfs_set_stack_device_sector_size(dev_item, dev->sector_size);
4189a061fc8dSChris Mason 		memcpy(dev_item->uuid, dev->uuid, BTRFS_UUID_SIZE);
41907239ff4bSNikolay Borisov 		memcpy(dev_item->fsid, dev->fs_devices->metadata_uuid,
41917239ff4bSNikolay Borisov 		       BTRFS_FSID_SIZE);
4192a512bbf8SYan Zheng 
4193a061fc8dSChris Mason 		flags = btrfs_super_flags(sb);
4194a061fc8dSChris Mason 		btrfs_set_super_flags(sb, flags | BTRFS_HEADER_FLAG_WRITTEN);
4195f2984462SChris Mason 
419675cb857dSQu Wenruo 		ret = btrfs_validate_write_super(fs_info, sb);
419775cb857dSQu Wenruo 		if (ret < 0) {
419875cb857dSQu Wenruo 			mutex_unlock(&fs_info->fs_devices->device_list_mutex);
419975cb857dSQu Wenruo 			btrfs_handle_fs_error(fs_info, -EUCLEAN,
420075cb857dSQu Wenruo 				"unexpected superblock corruption detected");
420175cb857dSQu Wenruo 			return -EUCLEAN;
420275cb857dSQu Wenruo 		}
420375cb857dSQu Wenruo 
4204abbb3b8eSDavid Sterba 		ret = write_dev_supers(dev, sb, max_mirrors);
4205a236aed1SChris Mason 		if (ret)
4206a236aed1SChris Mason 			total_errors++;
4207f2984462SChris Mason 	}
4208a236aed1SChris Mason 	if (total_errors > max_errors) {
42090b246afaSJeff Mahoney 		btrfs_err(fs_info, "%d errors while writing supers",
4210d397712bSChris Mason 			  total_errors);
42110b246afaSJeff Mahoney 		mutex_unlock(&fs_info->fs_devices->device_list_mutex);
421279787eaaSJeff Mahoney 
42139d565ba4SStefan Behrens 		/* FUA is masked off if unsupported and can't be the reason */
42140b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, -EIO,
42150b246afaSJeff Mahoney 				      "%d errors while writing supers",
42160b246afaSJeff Mahoney 				      total_errors);
42179d565ba4SStefan Behrens 		return -EIO;
4218a236aed1SChris Mason 	}
4219f2984462SChris Mason 
4220a512bbf8SYan Zheng 	total_errors = 0;
42211538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
4222dfe25020SChris Mason 		if (!dev->bdev)
4223dfe25020SChris Mason 			continue;
4224e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
4225ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
4226dfe25020SChris Mason 			continue;
4227dfe25020SChris Mason 
4228abbb3b8eSDavid Sterba 		ret = wait_dev_supers(dev, max_mirrors);
4229a512bbf8SYan Zheng 		if (ret)
42301259ab75SChris Mason 			total_errors++;
4231f2984462SChris Mason 	}
42320b246afaSJeff Mahoney 	mutex_unlock(&fs_info->fs_devices->device_list_mutex);
4233a236aed1SChris Mason 	if (total_errors > max_errors) {
42340b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, -EIO,
42350b246afaSJeff Mahoney 				      "%d errors while writing supers",
42360b246afaSJeff Mahoney 				      total_errors);
423779787eaaSJeff Mahoney 		return -EIO;
4238a236aed1SChris Mason 	}
4239f2984462SChris Mason 	return 0;
4240f2984462SChris Mason }
4241f2984462SChris Mason 
4242cb517eabSMiao Xie /* Drop a fs root from the radix tree and free it. */
4243cb517eabSMiao Xie void btrfs_drop_and_free_fs_root(struct btrfs_fs_info *fs_info,
4244cb517eabSMiao Xie 				  struct btrfs_root *root)
42452619ba1fSChris Mason {
42464785e24fSJosef Bacik 	bool drop_ref = false;
42474785e24fSJosef Bacik 
42484df27c4dSYan, Zheng 	spin_lock(&fs_info->fs_roots_radix_lock);
42492619ba1fSChris Mason 	radix_tree_delete(&fs_info->fs_roots_radix,
42502619ba1fSChris Mason 			  (unsigned long)root->root_key.objectid);
4251af01d2e5SJosef Bacik 	if (test_and_clear_bit(BTRFS_ROOT_IN_RADIX, &root->state))
42524785e24fSJosef Bacik 		drop_ref = true;
42534df27c4dSYan, Zheng 	spin_unlock(&fs_info->fs_roots_radix_lock);
425476dda93cSYan, Zheng 
425584961539SJosef Bacik 	if (BTRFS_FS_ERROR(fs_info)) {
4256ef67963dSJosef Bacik 		ASSERT(root->log_root == NULL);
42571c1ea4f7SLiu Bo 		if (root->reloc_root) {
425800246528SJosef Bacik 			btrfs_put_root(root->reloc_root);
42591c1ea4f7SLiu Bo 			root->reloc_root = NULL;
42601c1ea4f7SLiu Bo 		}
42611c1ea4f7SLiu Bo 	}
42623321719eSLiu Bo 
42634785e24fSJosef Bacik 	if (drop_ref)
426400246528SJosef Bacik 		btrfs_put_root(root);
42652619ba1fSChris Mason }
42662619ba1fSChris Mason 
4267c146afadSYan Zheng int btrfs_cleanup_fs_roots(struct btrfs_fs_info *fs_info)
4268c146afadSYan Zheng {
4269c146afadSYan Zheng 	u64 root_objectid = 0;
4270c146afadSYan Zheng 	struct btrfs_root *gang[8];
427165d33fd7SQu Wenruo 	int i = 0;
427265d33fd7SQu Wenruo 	int err = 0;
427365d33fd7SQu Wenruo 	unsigned int ret = 0;
4274c146afadSYan Zheng 
4275c146afadSYan Zheng 	while (1) {
4276efc34534SJosef Bacik 		spin_lock(&fs_info->fs_roots_radix_lock);
4277c146afadSYan Zheng 		ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
4278c146afadSYan Zheng 					     (void **)gang, root_objectid,
4279c146afadSYan Zheng 					     ARRAY_SIZE(gang));
428065d33fd7SQu Wenruo 		if (!ret) {
4281efc34534SJosef Bacik 			spin_unlock(&fs_info->fs_roots_radix_lock);
4282c146afadSYan Zheng 			break;
428365d33fd7SQu Wenruo 		}
42845d4f98a2SYan Zheng 		root_objectid = gang[ret - 1]->root_key.objectid + 1;
428566b4ffd1SJosef Bacik 
428665d33fd7SQu Wenruo 		for (i = 0; i < ret; i++) {
428765d33fd7SQu Wenruo 			/* Avoid to grab roots in dead_roots */
428865d33fd7SQu Wenruo 			if (btrfs_root_refs(&gang[i]->root_item) == 0) {
428965d33fd7SQu Wenruo 				gang[i] = NULL;
429065d33fd7SQu Wenruo 				continue;
429165d33fd7SQu Wenruo 			}
429265d33fd7SQu Wenruo 			/* grab all the search result for later use */
429300246528SJosef Bacik 			gang[i] = btrfs_grab_root(gang[i]);
429465d33fd7SQu Wenruo 		}
4295efc34534SJosef Bacik 		spin_unlock(&fs_info->fs_roots_radix_lock);
429665d33fd7SQu Wenruo 
429765d33fd7SQu Wenruo 		for (i = 0; i < ret; i++) {
429865d33fd7SQu Wenruo 			if (!gang[i])
429965d33fd7SQu Wenruo 				continue;
4300c146afadSYan Zheng 			root_objectid = gang[i]->root_key.objectid;
430166b4ffd1SJosef Bacik 			err = btrfs_orphan_cleanup(gang[i]);
430266b4ffd1SJosef Bacik 			if (err)
430365d33fd7SQu Wenruo 				break;
430400246528SJosef Bacik 			btrfs_put_root(gang[i]);
4305c146afadSYan Zheng 		}
4306c146afadSYan Zheng 		root_objectid++;
4307c146afadSYan Zheng 	}
430865d33fd7SQu Wenruo 
430965d33fd7SQu Wenruo 	/* release the uncleaned roots due to error */
431065d33fd7SQu Wenruo 	for (; i < ret; i++) {
431165d33fd7SQu Wenruo 		if (gang[i])
431200246528SJosef Bacik 			btrfs_put_root(gang[i]);
431365d33fd7SQu Wenruo 	}
431465d33fd7SQu Wenruo 	return err;
4315c146afadSYan Zheng }
4316c146afadSYan Zheng 
43176bccf3abSJeff Mahoney int btrfs_commit_super(struct btrfs_fs_info *fs_info)
4318c146afadSYan Zheng {
43196bccf3abSJeff Mahoney 	struct btrfs_root *root = fs_info->tree_root;
4320c146afadSYan Zheng 	struct btrfs_trans_handle *trans;
4321c146afadSYan Zheng 
43220b246afaSJeff Mahoney 	mutex_lock(&fs_info->cleaner_mutex);
43232ff7e61eSJeff Mahoney 	btrfs_run_delayed_iputs(fs_info);
43240b246afaSJeff Mahoney 	mutex_unlock(&fs_info->cleaner_mutex);
43250b246afaSJeff Mahoney 	wake_up_process(fs_info->cleaner_kthread);
4326c71bf099SYan, Zheng 
4327c71bf099SYan, Zheng 	/* wait until ongoing cleanup work done */
43280b246afaSJeff Mahoney 	down_write(&fs_info->cleanup_work_sem);
43290b246afaSJeff Mahoney 	up_write(&fs_info->cleanup_work_sem);
4330c71bf099SYan, Zheng 
43317a7eaa40SJosef Bacik 	trans = btrfs_join_transaction(root);
43323612b495STsutomu Itoh 	if (IS_ERR(trans))
43333612b495STsutomu Itoh 		return PTR_ERR(trans);
43343a45bb20SJeff Mahoney 	return btrfs_commit_transaction(trans);
4335c146afadSYan Zheng }
4336c146afadSYan Zheng 
4337b105e927SDavid Sterba void __cold close_ctree(struct btrfs_fs_info *fs_info)
4338eb60ceacSChris Mason {
4339c146afadSYan Zheng 	int ret;
4340e089f05cSChris Mason 
4341afcdd129SJosef Bacik 	set_bit(BTRFS_FS_CLOSING_START, &fs_info->flags);
4342d6fd0ae2SOmar Sandoval 	/*
4343d6fd0ae2SOmar Sandoval 	 * We don't want the cleaner to start new transactions, add more delayed
4344d6fd0ae2SOmar Sandoval 	 * iputs, etc. while we're closing. We can't use kthread_stop() yet
4345d6fd0ae2SOmar Sandoval 	 * because that frees the task_struct, and the transaction kthread might
4346d6fd0ae2SOmar Sandoval 	 * still try to wake up the cleaner.
4347d6fd0ae2SOmar Sandoval 	 */
4348d6fd0ae2SOmar Sandoval 	kthread_park(fs_info->cleaner_kthread);
4349a2135011SChris Mason 
43507343dd61SJustin Maggard 	/* wait for the qgroup rescan worker to stop */
4351d06f23d6SJeff Mahoney 	btrfs_qgroup_wait_for_completion(fs_info, false);
43527343dd61SJustin Maggard 
4353803b2f54SStefan Behrens 	/* wait for the uuid_scan task to finish */
4354803b2f54SStefan Behrens 	down(&fs_info->uuid_tree_rescan_sem);
4355803b2f54SStefan Behrens 	/* avoid complains from lockdep et al., set sem back to initial state */
4356803b2f54SStefan Behrens 	up(&fs_info->uuid_tree_rescan_sem);
4357803b2f54SStefan Behrens 
4358837d5b6eSIlya Dryomov 	/* pause restriper - we want to resume on mount */
4359aa1b8cd4SStefan Behrens 	btrfs_pause_balance(fs_info);
4360837d5b6eSIlya Dryomov 
43618dabb742SStefan Behrens 	btrfs_dev_replace_suspend_for_unmount(fs_info);
43628dabb742SStefan Behrens 
4363aa1b8cd4SStefan Behrens 	btrfs_scrub_cancel(fs_info);
43644cb5300bSChris Mason 
43654cb5300bSChris Mason 	/* wait for any defraggers to finish */
43664cb5300bSChris Mason 	wait_event(fs_info->transaction_wait,
43674cb5300bSChris Mason 		   (atomic_read(&fs_info->defrag_running) == 0));
43684cb5300bSChris Mason 
43694cb5300bSChris Mason 	/* clear out the rbtree of defraggable inodes */
437026176e7cSMiao Xie 	btrfs_cleanup_defrag_inodes(fs_info);
43714cb5300bSChris Mason 
437221c7e756SMiao Xie 	cancel_work_sync(&fs_info->async_reclaim_work);
437357056740SJosef Bacik 	cancel_work_sync(&fs_info->async_data_reclaim_work);
4374576fa348SJosef Bacik 	cancel_work_sync(&fs_info->preempt_reclaim_work);
437521c7e756SMiao Xie 
437618bb8bbfSJohannes Thumshirn 	cancel_work_sync(&fs_info->reclaim_bgs_work);
437718bb8bbfSJohannes Thumshirn 
4378b0643e59SDennis Zhou 	/* Cancel or finish ongoing discard work */
4379b0643e59SDennis Zhou 	btrfs_discard_cleanup(fs_info);
4380b0643e59SDennis Zhou 
4381bc98a42cSDavid Howells 	if (!sb_rdonly(fs_info->sb)) {
4382e44163e1SJeff Mahoney 		/*
4383d6fd0ae2SOmar Sandoval 		 * The cleaner kthread is stopped, so do one final pass over
4384d6fd0ae2SOmar Sandoval 		 * unused block groups.
4385e44163e1SJeff Mahoney 		 */
43860b246afaSJeff Mahoney 		btrfs_delete_unused_bgs(fs_info);
4387e44163e1SJeff Mahoney 
4388f0cc2cd7SFilipe Manana 		/*
4389f0cc2cd7SFilipe Manana 		 * There might be existing delayed inode workers still running
4390f0cc2cd7SFilipe Manana 		 * and holding an empty delayed inode item. We must wait for
4391f0cc2cd7SFilipe Manana 		 * them to complete first because they can create a transaction.
4392f0cc2cd7SFilipe Manana 		 * This happens when someone calls btrfs_balance_delayed_items()
4393f0cc2cd7SFilipe Manana 		 * and then a transaction commit runs the same delayed nodes
4394f0cc2cd7SFilipe Manana 		 * before any delayed worker has done something with the nodes.
4395f0cc2cd7SFilipe Manana 		 * We must wait for any worker here and not at transaction
4396f0cc2cd7SFilipe Manana 		 * commit time since that could cause a deadlock.
4397f0cc2cd7SFilipe Manana 		 * This is a very rare case.
4398f0cc2cd7SFilipe Manana 		 */
4399f0cc2cd7SFilipe Manana 		btrfs_flush_workqueue(fs_info->delayed_workers);
4400f0cc2cd7SFilipe Manana 
44016bccf3abSJeff Mahoney 		ret = btrfs_commit_super(fs_info);
4402d397712bSChris Mason 		if (ret)
440304892340SEric Sandeen 			btrfs_err(fs_info, "commit super ret %d", ret);
4404c146afadSYan Zheng 	}
4405ed2ff2cbSChris Mason 
440684961539SJosef Bacik 	if (BTRFS_FS_ERROR(fs_info))
44072ff7e61eSJeff Mahoney 		btrfs_error_commit_super(fs_info);
4408acce952bSliubo 
4409e3029d9fSAl Viro 	kthread_stop(fs_info->transaction_kthread);
4410e3029d9fSAl Viro 	kthread_stop(fs_info->cleaner_kthread);
44118929ecfaSYan, Zheng 
4412e187831eSJosef Bacik 	ASSERT(list_empty(&fs_info->delayed_iputs));
4413afcdd129SJosef Bacik 	set_bit(BTRFS_FS_CLOSING_DONE, &fs_info->flags);
4414f25784b3SYan Zheng 
44155958253cSQu Wenruo 	if (btrfs_check_quota_leak(fs_info)) {
44165958253cSQu Wenruo 		WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
44175958253cSQu Wenruo 		btrfs_err(fs_info, "qgroup reserved space leaked");
44185958253cSQu Wenruo 	}
44195958253cSQu Wenruo 
442004892340SEric Sandeen 	btrfs_free_qgroup_config(fs_info);
4421fe816d0fSNikolay Borisov 	ASSERT(list_empty(&fs_info->delalloc_roots));
4422bcef60f2SArne Jansen 
4423963d678bSMiao Xie 	if (percpu_counter_sum(&fs_info->delalloc_bytes)) {
442404892340SEric Sandeen 		btrfs_info(fs_info, "at unmount delalloc count %lld",
4425963d678bSMiao Xie 		       percpu_counter_sum(&fs_info->delalloc_bytes));
4426b0c68f8bSChris Mason 	}
442731153d81SYan Zheng 
44285deb17e1SJosef Bacik 	if (percpu_counter_sum(&fs_info->ordered_bytes))
44294297ff84SJosef Bacik 		btrfs_info(fs_info, "at unmount dio bytes count %lld",
44305deb17e1SJosef Bacik 			   percpu_counter_sum(&fs_info->ordered_bytes));
44314297ff84SJosef Bacik 
44326618a59bSAnand Jain 	btrfs_sysfs_remove_mounted(fs_info);
4433b7c35e81SAnand Jain 	btrfs_sysfs_remove_fsid(fs_info->fs_devices);
44345ac1d209SJeff Mahoney 
44351a4319ccSLiu Bo 	btrfs_put_block_group_cache(fs_info);
44361a4319ccSLiu Bo 
4437de348ee0SWang Shilong 	/*
4438de348ee0SWang Shilong 	 * we must make sure there is not any read request to
4439de348ee0SWang Shilong 	 * submit after we stopping all workers.
4440de348ee0SWang Shilong 	 */
4441de348ee0SWang Shilong 	invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
444296192499SJosef Bacik 	btrfs_stop_all_workers(fs_info);
444396192499SJosef Bacik 
44440a31daa4SFilipe Manana 	/* We shouldn't have any transaction open at this point */
44450a31daa4SFilipe Manana 	ASSERT(list_empty(&fs_info->trans_list));
44460a31daa4SFilipe Manana 
4447afcdd129SJosef Bacik 	clear_bit(BTRFS_FS_OPEN, &fs_info->flags);
44484273eaffSAnand Jain 	free_root_pointers(fs_info, true);
44498c38938cSJosef Bacik 	btrfs_free_fs_roots(fs_info);
44509ad6b7bcSChris Mason 
44514e19443dSJosef Bacik 	/*
44524e19443dSJosef Bacik 	 * We must free the block groups after dropping the fs_roots as we could
44534e19443dSJosef Bacik 	 * have had an IO error and have left over tree log blocks that aren't
44544e19443dSJosef Bacik 	 * cleaned up until the fs roots are freed.  This makes the block group
44554e19443dSJosef Bacik 	 * accounting appear to be wrong because there's pending reserved bytes,
44564e19443dSJosef Bacik 	 * so make sure we do the block group cleanup afterwards.
44574e19443dSJosef Bacik 	 */
44584e19443dSJosef Bacik 	btrfs_free_block_groups(fs_info);
44594e19443dSJosef Bacik 
446013e6c37bSJosef Bacik 	iput(fs_info->btree_inode);
4461d6bfde87SChris Mason 
446221adbd5cSStefan Behrens #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
44630b246afaSJeff Mahoney 	if (btrfs_test_opt(fs_info, CHECK_INTEGRITY))
44642ff7e61eSJeff Mahoney 		btrfsic_unmount(fs_info->fs_devices);
446521adbd5cSStefan Behrens #endif
446621adbd5cSStefan Behrens 
44670b86a832SChris Mason 	btrfs_mapping_tree_free(&fs_info->mapping_tree);
446868c94e55SNikolay Borisov 	btrfs_close_devices(fs_info->fs_devices);
4469eb60ceacSChris Mason }
4470eb60ceacSChris Mason 
4471b9fab919SChris Mason int btrfs_buffer_uptodate(struct extent_buffer *buf, u64 parent_transid,
4472b9fab919SChris Mason 			  int atomic)
4473ccd467d6SChris Mason {
44741259ab75SChris Mason 	int ret;
4475727011e0SChris Mason 	struct inode *btree_inode = buf->pages[0]->mapping->host;
44761259ab75SChris Mason 
44770b32f4bbSJosef Bacik 	ret = extent_buffer_uptodate(buf);
44781259ab75SChris Mason 	if (!ret)
44791259ab75SChris Mason 		return ret;
44801259ab75SChris Mason 
44811259ab75SChris Mason 	ret = verify_parent_transid(&BTRFS_I(btree_inode)->io_tree, buf,
4482b9fab919SChris Mason 				    parent_transid, atomic);
4483b9fab919SChris Mason 	if (ret == -EAGAIN)
4484b9fab919SChris Mason 		return ret;
44851259ab75SChris Mason 	return !ret;
44865f39d397SChris Mason }
44876702ed49SChris Mason 
44885f39d397SChris Mason void btrfs_mark_buffer_dirty(struct extent_buffer *buf)
44895f39d397SChris Mason {
44902f4d60dfSQu Wenruo 	struct btrfs_fs_info *fs_info = buf->fs_info;
44915f39d397SChris Mason 	u64 transid = btrfs_header_generation(buf);
4492b9473439SChris Mason 	int was_dirty;
4493b4ce94deSChris Mason 
449406ea65a3SJosef Bacik #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
449506ea65a3SJosef Bacik 	/*
449606ea65a3SJosef Bacik 	 * This is a fast path so only do this check if we have sanity tests
449752042d8eSAndrea Gelmini 	 * enabled.  Normal people shouldn't be using unmapped buffers as dirty
449806ea65a3SJosef Bacik 	 * outside of the sanity tests.
449906ea65a3SJosef Bacik 	 */
4500b0132a3bSNikolay Borisov 	if (unlikely(test_bit(EXTENT_BUFFER_UNMAPPED, &buf->bflags)))
450106ea65a3SJosef Bacik 		return;
450206ea65a3SJosef Bacik #endif
450349d0c642SFilipe Manana 	btrfs_assert_tree_write_locked(buf);
45040b246afaSJeff Mahoney 	if (transid != fs_info->generation)
45055d163e0eSJeff Mahoney 		WARN(1, KERN_CRIT "btrfs transid mismatch buffer %llu, found %llu running %llu\n",
45060b246afaSJeff Mahoney 			buf->start, transid, fs_info->generation);
45070b32f4bbSJosef Bacik 	was_dirty = set_extent_buffer_dirty(buf);
4508e2d84521SMiao Xie 	if (!was_dirty)
4509104b4e51SNikolay Borisov 		percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
4510e2d84521SMiao Xie 					 buf->len,
45110b246afaSJeff Mahoney 					 fs_info->dirty_metadata_batch);
45121f21ef0aSFilipe Manana #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
451369fc6cbbSQu Wenruo 	/*
451469fc6cbbSQu Wenruo 	 * Since btrfs_mark_buffer_dirty() can be called with item pointer set
451569fc6cbbSQu Wenruo 	 * but item data not updated.
451669fc6cbbSQu Wenruo 	 * So here we should only check item pointers, not item data.
451769fc6cbbSQu Wenruo 	 */
451869fc6cbbSQu Wenruo 	if (btrfs_header_level(buf) == 0 &&
4519cfdaad5eSDavid Sterba 	    btrfs_check_leaf_relaxed(buf)) {
4520a4f78750SDavid Sterba 		btrfs_print_leaf(buf);
45211f21ef0aSFilipe Manana 		ASSERT(0);
45221f21ef0aSFilipe Manana 	}
45231f21ef0aSFilipe Manana #endif
4524eb60ceacSChris Mason }
4525eb60ceacSChris Mason 
45262ff7e61eSJeff Mahoney static void __btrfs_btree_balance_dirty(struct btrfs_fs_info *fs_info,
4527b53d3f5dSLiu Bo 					int flush_delayed)
452835b7e476SChris Mason {
4529188de649SChris Mason 	/*
4530188de649SChris Mason 	 * looks as though older kernels can get into trouble with
4531188de649SChris Mason 	 * this code, they end up stuck in balance_dirty_pages forever
4532188de649SChris Mason 	 */
4533e2d84521SMiao Xie 	int ret;
4534d6bfde87SChris Mason 
45356933c02eSJens Axboe 	if (current->flags & PF_MEMALLOC)
4536d6bfde87SChris Mason 		return;
4537d6bfde87SChris Mason 
4538b53d3f5dSLiu Bo 	if (flush_delayed)
45392ff7e61eSJeff Mahoney 		btrfs_balance_delayed_items(fs_info);
454016cdcec7SMiao Xie 
4541d814a491SEthan Lien 	ret = __percpu_counter_compare(&fs_info->dirty_metadata_bytes,
4542d814a491SEthan Lien 				     BTRFS_DIRTY_METADATA_THRESH,
4543d814a491SEthan Lien 				     fs_info->dirty_metadata_batch);
4544e2d84521SMiao Xie 	if (ret > 0) {
45450b246afaSJeff Mahoney 		balance_dirty_pages_ratelimited(fs_info->btree_inode->i_mapping);
454616cdcec7SMiao Xie 	}
454716cdcec7SMiao Xie }
454816cdcec7SMiao Xie 
45492ff7e61eSJeff Mahoney void btrfs_btree_balance_dirty(struct btrfs_fs_info *fs_info)
455016cdcec7SMiao Xie {
45512ff7e61eSJeff Mahoney 	__btrfs_btree_balance_dirty(fs_info, 1);
455235b7e476SChris Mason }
4553b53d3f5dSLiu Bo 
45542ff7e61eSJeff Mahoney void btrfs_btree_balance_dirty_nodelay(struct btrfs_fs_info *fs_info)
4555b53d3f5dSLiu Bo {
45562ff7e61eSJeff Mahoney 	__btrfs_btree_balance_dirty(fs_info, 0);
4557d6bfde87SChris Mason }
45586b80053dSChris Mason 
4559581c1760SQu Wenruo int btrfs_read_buffer(struct extent_buffer *buf, u64 parent_transid, int level,
4560581c1760SQu Wenruo 		      struct btrfs_key *first_key)
45616b80053dSChris Mason {
45625ab12d1fSDavid Sterba 	return btree_read_extent_buffer_pages(buf, parent_transid,
4563581c1760SQu Wenruo 					      level, first_key);
45646b80053dSChris Mason }
45650da5468fSChris Mason 
45662ff7e61eSJeff Mahoney static void btrfs_error_commit_super(struct btrfs_fs_info *fs_info)
4567acce952bSliubo {
4568fe816d0fSNikolay Borisov 	/* cleanup FS via transaction */
4569fe816d0fSNikolay Borisov 	btrfs_cleanup_transaction(fs_info);
4570fe816d0fSNikolay Borisov 
45710b246afaSJeff Mahoney 	mutex_lock(&fs_info->cleaner_mutex);
45722ff7e61eSJeff Mahoney 	btrfs_run_delayed_iputs(fs_info);
45730b246afaSJeff Mahoney 	mutex_unlock(&fs_info->cleaner_mutex);
4574acce952bSliubo 
45750b246afaSJeff Mahoney 	down_write(&fs_info->cleanup_work_sem);
45760b246afaSJeff Mahoney 	up_write(&fs_info->cleanup_work_sem);
4577acce952bSliubo }
4578acce952bSliubo 
4579ef67963dSJosef Bacik static void btrfs_drop_all_logs(struct btrfs_fs_info *fs_info)
4580ef67963dSJosef Bacik {
4581ef67963dSJosef Bacik 	struct btrfs_root *gang[8];
4582ef67963dSJosef Bacik 	u64 root_objectid = 0;
4583ef67963dSJosef Bacik 	int ret;
4584ef67963dSJosef Bacik 
4585ef67963dSJosef Bacik 	spin_lock(&fs_info->fs_roots_radix_lock);
4586ef67963dSJosef Bacik 	while ((ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
4587ef67963dSJosef Bacik 					     (void **)gang, root_objectid,
4588ef67963dSJosef Bacik 					     ARRAY_SIZE(gang))) != 0) {
4589ef67963dSJosef Bacik 		int i;
4590ef67963dSJosef Bacik 
4591ef67963dSJosef Bacik 		for (i = 0; i < ret; i++)
4592ef67963dSJosef Bacik 			gang[i] = btrfs_grab_root(gang[i]);
4593ef67963dSJosef Bacik 		spin_unlock(&fs_info->fs_roots_radix_lock);
4594ef67963dSJosef Bacik 
4595ef67963dSJosef Bacik 		for (i = 0; i < ret; i++) {
4596ef67963dSJosef Bacik 			if (!gang[i])
4597ef67963dSJosef Bacik 				continue;
4598ef67963dSJosef Bacik 			root_objectid = gang[i]->root_key.objectid;
4599ef67963dSJosef Bacik 			btrfs_free_log(NULL, gang[i]);
4600ef67963dSJosef Bacik 			btrfs_put_root(gang[i]);
4601ef67963dSJosef Bacik 		}
4602ef67963dSJosef Bacik 		root_objectid++;
4603ef67963dSJosef Bacik 		spin_lock(&fs_info->fs_roots_radix_lock);
4604ef67963dSJosef Bacik 	}
4605ef67963dSJosef Bacik 	spin_unlock(&fs_info->fs_roots_radix_lock);
4606ef67963dSJosef Bacik 	btrfs_free_log_root_tree(NULL, fs_info);
4607ef67963dSJosef Bacik }
4608ef67963dSJosef Bacik 
4609143bede5SJeff Mahoney static void btrfs_destroy_ordered_extents(struct btrfs_root *root)
4610acce952bSliubo {
4611acce952bSliubo 	struct btrfs_ordered_extent *ordered;
4612acce952bSliubo 
4613199c2a9cSMiao Xie 	spin_lock(&root->ordered_extent_lock);
4614779880efSJosef Bacik 	/*
4615779880efSJosef Bacik 	 * This will just short circuit the ordered completion stuff which will
4616779880efSJosef Bacik 	 * make sure the ordered extent gets properly cleaned up.
4617779880efSJosef Bacik 	 */
4618199c2a9cSMiao Xie 	list_for_each_entry(ordered, &root->ordered_extents,
4619779880efSJosef Bacik 			    root_extent_list)
4620779880efSJosef Bacik 		set_bit(BTRFS_ORDERED_IOERR, &ordered->flags);
4621199c2a9cSMiao Xie 	spin_unlock(&root->ordered_extent_lock);
4622199c2a9cSMiao Xie }
4623199c2a9cSMiao Xie 
4624199c2a9cSMiao Xie static void btrfs_destroy_all_ordered_extents(struct btrfs_fs_info *fs_info)
4625199c2a9cSMiao Xie {
4626199c2a9cSMiao Xie 	struct btrfs_root *root;
4627199c2a9cSMiao Xie 	struct list_head splice;
4628199c2a9cSMiao Xie 
4629199c2a9cSMiao Xie 	INIT_LIST_HEAD(&splice);
4630199c2a9cSMiao Xie 
4631199c2a9cSMiao Xie 	spin_lock(&fs_info->ordered_root_lock);
4632199c2a9cSMiao Xie 	list_splice_init(&fs_info->ordered_roots, &splice);
4633199c2a9cSMiao Xie 	while (!list_empty(&splice)) {
4634199c2a9cSMiao Xie 		root = list_first_entry(&splice, struct btrfs_root,
4635199c2a9cSMiao Xie 					ordered_root);
46361de2cfdeSJosef Bacik 		list_move_tail(&root->ordered_root,
46371de2cfdeSJosef Bacik 			       &fs_info->ordered_roots);
4638199c2a9cSMiao Xie 
46392a85d9caSLiu Bo 		spin_unlock(&fs_info->ordered_root_lock);
4640199c2a9cSMiao Xie 		btrfs_destroy_ordered_extents(root);
4641199c2a9cSMiao Xie 
46422a85d9caSLiu Bo 		cond_resched();
46432a85d9caSLiu Bo 		spin_lock(&fs_info->ordered_root_lock);
4644199c2a9cSMiao Xie 	}
4645199c2a9cSMiao Xie 	spin_unlock(&fs_info->ordered_root_lock);
464674d5d229SJosef Bacik 
464774d5d229SJosef Bacik 	/*
464874d5d229SJosef Bacik 	 * We need this here because if we've been flipped read-only we won't
464974d5d229SJosef Bacik 	 * get sync() from the umount, so we need to make sure any ordered
465074d5d229SJosef Bacik 	 * extents that haven't had their dirty pages IO start writeout yet
465174d5d229SJosef Bacik 	 * actually get run and error out properly.
465274d5d229SJosef Bacik 	 */
465374d5d229SJosef Bacik 	btrfs_wait_ordered_roots(fs_info, U64_MAX, 0, (u64)-1);
4654acce952bSliubo }
4655acce952bSliubo 
465635a3621bSStefan Behrens static int btrfs_destroy_delayed_refs(struct btrfs_transaction *trans,
46572ff7e61eSJeff Mahoney 				      struct btrfs_fs_info *fs_info)
4658acce952bSliubo {
4659acce952bSliubo 	struct rb_node *node;
4660acce952bSliubo 	struct btrfs_delayed_ref_root *delayed_refs;
4661acce952bSliubo 	struct btrfs_delayed_ref_node *ref;
4662acce952bSliubo 	int ret = 0;
4663acce952bSliubo 
4664acce952bSliubo 	delayed_refs = &trans->delayed_refs;
4665acce952bSliubo 
4666acce952bSliubo 	spin_lock(&delayed_refs->lock);
4667d7df2c79SJosef Bacik 	if (atomic_read(&delayed_refs->num_entries) == 0) {
4668cfece4dbSDavid Sterba 		spin_unlock(&delayed_refs->lock);
4669b79ce3ddSDavid Sterba 		btrfs_debug(fs_info, "delayed_refs has NO entry");
4670acce952bSliubo 		return ret;
4671acce952bSliubo 	}
4672acce952bSliubo 
46735c9d028bSLiu Bo 	while ((node = rb_first_cached(&delayed_refs->href_root)) != NULL) {
4674d7df2c79SJosef Bacik 		struct btrfs_delayed_ref_head *head;
46750e0adbcfSJosef Bacik 		struct rb_node *n;
4676e78417d1SJosef Bacik 		bool pin_bytes = false;
4677acce952bSliubo 
4678d7df2c79SJosef Bacik 		head = rb_entry(node, struct btrfs_delayed_ref_head,
4679d7df2c79SJosef Bacik 				href_node);
46803069bd26SJosef Bacik 		if (btrfs_delayed_ref_lock(delayed_refs, head))
4681b939d1abSJosef Bacik 			continue;
46823069bd26SJosef Bacik 
4683d7df2c79SJosef Bacik 		spin_lock(&head->lock);
4684e3d03965SLiu Bo 		while ((n = rb_first_cached(&head->ref_tree)) != NULL) {
46850e0adbcfSJosef Bacik 			ref = rb_entry(n, struct btrfs_delayed_ref_node,
46860e0adbcfSJosef Bacik 				       ref_node);
4687d7df2c79SJosef Bacik 			ref->in_tree = 0;
4688e3d03965SLiu Bo 			rb_erase_cached(&ref->ref_node, &head->ref_tree);
46890e0adbcfSJosef Bacik 			RB_CLEAR_NODE(&ref->ref_node);
46901d57ee94SWang Xiaoguang 			if (!list_empty(&ref->add_list))
46911d57ee94SWang Xiaoguang 				list_del(&ref->add_list);
4692d7df2c79SJosef Bacik 			atomic_dec(&delayed_refs->num_entries);
4693d7df2c79SJosef Bacik 			btrfs_put_delayed_ref(ref);
4694d7df2c79SJosef Bacik 		}
469554067ae9SJosef Bacik 		if (head->must_insert_reserved)
4696e78417d1SJosef Bacik 			pin_bytes = true;
469778a6184aSMiao Xie 		btrfs_free_delayed_extent_op(head->extent_op);
4698fa781ceaSJosef Bacik 		btrfs_delete_ref_head(delayed_refs, head);
4699d7df2c79SJosef Bacik 		spin_unlock(&head->lock);
4700acce952bSliubo 		spin_unlock(&delayed_refs->lock);
4701e78417d1SJosef Bacik 		mutex_unlock(&head->mutex);
4702acce952bSliubo 
4703f603bb94SNikolay Borisov 		if (pin_bytes) {
4704f603bb94SNikolay Borisov 			struct btrfs_block_group *cache;
4705f603bb94SNikolay Borisov 
4706f603bb94SNikolay Borisov 			cache = btrfs_lookup_block_group(fs_info, head->bytenr);
4707f603bb94SNikolay Borisov 			BUG_ON(!cache);
4708f603bb94SNikolay Borisov 
4709f603bb94SNikolay Borisov 			spin_lock(&cache->space_info->lock);
4710f603bb94SNikolay Borisov 			spin_lock(&cache->lock);
4711f603bb94SNikolay Borisov 			cache->pinned += head->num_bytes;
4712f603bb94SNikolay Borisov 			btrfs_space_info_update_bytes_pinned(fs_info,
4713f603bb94SNikolay Borisov 				cache->space_info, head->num_bytes);
4714f603bb94SNikolay Borisov 			cache->reserved -= head->num_bytes;
4715f603bb94SNikolay Borisov 			cache->space_info->bytes_reserved -= head->num_bytes;
4716f603bb94SNikolay Borisov 			spin_unlock(&cache->lock);
4717f603bb94SNikolay Borisov 			spin_unlock(&cache->space_info->lock);
4718f603bb94SNikolay Borisov 
4719f603bb94SNikolay Borisov 			btrfs_put_block_group(cache);
4720f603bb94SNikolay Borisov 
4721f603bb94SNikolay Borisov 			btrfs_error_unpin_extent_range(fs_info, head->bytenr,
4722f603bb94SNikolay Borisov 				head->bytenr + head->num_bytes - 1);
4723f603bb94SNikolay Borisov 		}
472431890da0SJosef Bacik 		btrfs_cleanup_ref_head_accounting(fs_info, delayed_refs, head);
4725d278850eSJosef Bacik 		btrfs_put_delayed_ref_head(head);
4726acce952bSliubo 		cond_resched();
4727acce952bSliubo 		spin_lock(&delayed_refs->lock);
4728acce952bSliubo 	}
472981f7eb00SJeff Mahoney 	btrfs_qgroup_destroy_extent_records(trans);
4730acce952bSliubo 
4731acce952bSliubo 	spin_unlock(&delayed_refs->lock);
4732acce952bSliubo 
4733acce952bSliubo 	return ret;
4734acce952bSliubo }
4735acce952bSliubo 
4736143bede5SJeff Mahoney static void btrfs_destroy_delalloc_inodes(struct btrfs_root *root)
4737acce952bSliubo {
4738acce952bSliubo 	struct btrfs_inode *btrfs_inode;
4739acce952bSliubo 	struct list_head splice;
4740acce952bSliubo 
4741acce952bSliubo 	INIT_LIST_HEAD(&splice);
4742acce952bSliubo 
4743eb73c1b7SMiao Xie 	spin_lock(&root->delalloc_lock);
4744eb73c1b7SMiao Xie 	list_splice_init(&root->delalloc_inodes, &splice);
4745acce952bSliubo 
4746acce952bSliubo 	while (!list_empty(&splice)) {
4747fe816d0fSNikolay Borisov 		struct inode *inode = NULL;
4748eb73c1b7SMiao Xie 		btrfs_inode = list_first_entry(&splice, struct btrfs_inode,
4749acce952bSliubo 					       delalloc_inodes);
4750fe816d0fSNikolay Borisov 		__btrfs_del_delalloc_inode(root, btrfs_inode);
4751eb73c1b7SMiao Xie 		spin_unlock(&root->delalloc_lock);
4752acce952bSliubo 
4753fe816d0fSNikolay Borisov 		/*
4754fe816d0fSNikolay Borisov 		 * Make sure we get a live inode and that it'll not disappear
4755fe816d0fSNikolay Borisov 		 * meanwhile.
4756fe816d0fSNikolay Borisov 		 */
4757fe816d0fSNikolay Borisov 		inode = igrab(&btrfs_inode->vfs_inode);
4758fe816d0fSNikolay Borisov 		if (inode) {
4759fe816d0fSNikolay Borisov 			invalidate_inode_pages2(inode->i_mapping);
4760fe816d0fSNikolay Borisov 			iput(inode);
4761fe816d0fSNikolay Borisov 		}
4762eb73c1b7SMiao Xie 		spin_lock(&root->delalloc_lock);
4763acce952bSliubo 	}
4764eb73c1b7SMiao Xie 	spin_unlock(&root->delalloc_lock);
4765eb73c1b7SMiao Xie }
4766eb73c1b7SMiao Xie 
4767eb73c1b7SMiao Xie static void btrfs_destroy_all_delalloc_inodes(struct btrfs_fs_info *fs_info)
4768eb73c1b7SMiao Xie {
4769eb73c1b7SMiao Xie 	struct btrfs_root *root;
4770eb73c1b7SMiao Xie 	struct list_head splice;
4771eb73c1b7SMiao Xie 
4772eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&splice);
4773eb73c1b7SMiao Xie 
4774eb73c1b7SMiao Xie 	spin_lock(&fs_info->delalloc_root_lock);
4775eb73c1b7SMiao Xie 	list_splice_init(&fs_info->delalloc_roots, &splice);
4776eb73c1b7SMiao Xie 	while (!list_empty(&splice)) {
4777eb73c1b7SMiao Xie 		root = list_first_entry(&splice, struct btrfs_root,
4778eb73c1b7SMiao Xie 					 delalloc_root);
477900246528SJosef Bacik 		root = btrfs_grab_root(root);
4780eb73c1b7SMiao Xie 		BUG_ON(!root);
4781eb73c1b7SMiao Xie 		spin_unlock(&fs_info->delalloc_root_lock);
4782eb73c1b7SMiao Xie 
4783eb73c1b7SMiao Xie 		btrfs_destroy_delalloc_inodes(root);
478400246528SJosef Bacik 		btrfs_put_root(root);
4785eb73c1b7SMiao Xie 
4786eb73c1b7SMiao Xie 		spin_lock(&fs_info->delalloc_root_lock);
4787eb73c1b7SMiao Xie 	}
4788eb73c1b7SMiao Xie 	spin_unlock(&fs_info->delalloc_root_lock);
4789acce952bSliubo }
4790acce952bSliubo 
47912ff7e61eSJeff Mahoney static int btrfs_destroy_marked_extents(struct btrfs_fs_info *fs_info,
4792acce952bSliubo 					struct extent_io_tree *dirty_pages,
4793acce952bSliubo 					int mark)
4794acce952bSliubo {
4795acce952bSliubo 	int ret;
4796acce952bSliubo 	struct extent_buffer *eb;
4797acce952bSliubo 	u64 start = 0;
4798acce952bSliubo 	u64 end;
4799acce952bSliubo 
4800acce952bSliubo 	while (1) {
4801acce952bSliubo 		ret = find_first_extent_bit(dirty_pages, start, &start, &end,
4802e6138876SJosef Bacik 					    mark, NULL);
4803acce952bSliubo 		if (ret)
4804acce952bSliubo 			break;
4805acce952bSliubo 
480691166212SDavid Sterba 		clear_extent_bits(dirty_pages, start, end, mark);
4807acce952bSliubo 		while (start <= end) {
48080b246afaSJeff Mahoney 			eb = find_extent_buffer(fs_info, start);
48090b246afaSJeff Mahoney 			start += fs_info->nodesize;
4810fd8b2b61SJosef Bacik 			if (!eb)
4811acce952bSliubo 				continue;
4812fd8b2b61SJosef Bacik 			wait_on_extent_buffer_writeback(eb);
4813acce952bSliubo 
4814fd8b2b61SJosef Bacik 			if (test_and_clear_bit(EXTENT_BUFFER_DIRTY,
4815fd8b2b61SJosef Bacik 					       &eb->bflags))
4816fd8b2b61SJosef Bacik 				clear_extent_buffer_dirty(eb);
4817fd8b2b61SJosef Bacik 			free_extent_buffer_stale(eb);
4818acce952bSliubo 		}
4819acce952bSliubo 	}
4820acce952bSliubo 
4821acce952bSliubo 	return ret;
4822acce952bSliubo }
4823acce952bSliubo 
48242ff7e61eSJeff Mahoney static int btrfs_destroy_pinned_extent(struct btrfs_fs_info *fs_info,
4825fe119a6eSNikolay Borisov 				       struct extent_io_tree *unpin)
4826acce952bSliubo {
4827acce952bSliubo 	u64 start;
4828acce952bSliubo 	u64 end;
4829acce952bSliubo 	int ret;
4830acce952bSliubo 
4831acce952bSliubo 	while (1) {
48320e6ec385SFilipe Manana 		struct extent_state *cached_state = NULL;
48330e6ec385SFilipe Manana 
4834fcd5e742SLu Fengqi 		/*
4835fcd5e742SLu Fengqi 		 * The btrfs_finish_extent_commit() may get the same range as
4836fcd5e742SLu Fengqi 		 * ours between find_first_extent_bit and clear_extent_dirty.
4837fcd5e742SLu Fengqi 		 * Hence, hold the unused_bg_unpin_mutex to avoid double unpin
4838fcd5e742SLu Fengqi 		 * the same extent range.
4839fcd5e742SLu Fengqi 		 */
4840fcd5e742SLu Fengqi 		mutex_lock(&fs_info->unused_bg_unpin_mutex);
4841acce952bSliubo 		ret = find_first_extent_bit(unpin, 0, &start, &end,
48420e6ec385SFilipe Manana 					    EXTENT_DIRTY, &cached_state);
4843fcd5e742SLu Fengqi 		if (ret) {
4844fcd5e742SLu Fengqi 			mutex_unlock(&fs_info->unused_bg_unpin_mutex);
4845acce952bSliubo 			break;
4846fcd5e742SLu Fengqi 		}
4847acce952bSliubo 
48480e6ec385SFilipe Manana 		clear_extent_dirty(unpin, start, end, &cached_state);
48490e6ec385SFilipe Manana 		free_extent_state(cached_state);
48502ff7e61eSJeff Mahoney 		btrfs_error_unpin_extent_range(fs_info, start, end);
4851fcd5e742SLu Fengqi 		mutex_unlock(&fs_info->unused_bg_unpin_mutex);
4852acce952bSliubo 		cond_resched();
4853acce952bSliubo 	}
4854acce952bSliubo 
4855acce952bSliubo 	return 0;
4856acce952bSliubo }
4857acce952bSliubo 
485832da5386SDavid Sterba static void btrfs_cleanup_bg_io(struct btrfs_block_group *cache)
4859c79a1751SLiu Bo {
4860c79a1751SLiu Bo 	struct inode *inode;
4861c79a1751SLiu Bo 
4862c79a1751SLiu Bo 	inode = cache->io_ctl.inode;
4863c79a1751SLiu Bo 	if (inode) {
4864c79a1751SLiu Bo 		invalidate_inode_pages2(inode->i_mapping);
4865c79a1751SLiu Bo 		BTRFS_I(inode)->generation = 0;
4866c79a1751SLiu Bo 		cache->io_ctl.inode = NULL;
4867c79a1751SLiu Bo 		iput(inode);
4868c79a1751SLiu Bo 	}
4869bbc37d6eSFilipe Manana 	ASSERT(cache->io_ctl.pages == NULL);
4870c79a1751SLiu Bo 	btrfs_put_block_group(cache);
4871c79a1751SLiu Bo }
4872c79a1751SLiu Bo 
4873c79a1751SLiu Bo void btrfs_cleanup_dirty_bgs(struct btrfs_transaction *cur_trans,
48742ff7e61eSJeff Mahoney 			     struct btrfs_fs_info *fs_info)
4875c79a1751SLiu Bo {
487632da5386SDavid Sterba 	struct btrfs_block_group *cache;
4877c79a1751SLiu Bo 
4878c79a1751SLiu Bo 	spin_lock(&cur_trans->dirty_bgs_lock);
4879c79a1751SLiu Bo 	while (!list_empty(&cur_trans->dirty_bgs)) {
4880c79a1751SLiu Bo 		cache = list_first_entry(&cur_trans->dirty_bgs,
488132da5386SDavid Sterba 					 struct btrfs_block_group,
4882c79a1751SLiu Bo 					 dirty_list);
4883c79a1751SLiu Bo 
4884c79a1751SLiu Bo 		if (!list_empty(&cache->io_list)) {
4885c79a1751SLiu Bo 			spin_unlock(&cur_trans->dirty_bgs_lock);
4886c79a1751SLiu Bo 			list_del_init(&cache->io_list);
4887c79a1751SLiu Bo 			btrfs_cleanup_bg_io(cache);
4888c79a1751SLiu Bo 			spin_lock(&cur_trans->dirty_bgs_lock);
4889c79a1751SLiu Bo 		}
4890c79a1751SLiu Bo 
4891c79a1751SLiu Bo 		list_del_init(&cache->dirty_list);
4892c79a1751SLiu Bo 		spin_lock(&cache->lock);
4893c79a1751SLiu Bo 		cache->disk_cache_state = BTRFS_DC_ERROR;
4894c79a1751SLiu Bo 		spin_unlock(&cache->lock);
4895c79a1751SLiu Bo 
4896c79a1751SLiu Bo 		spin_unlock(&cur_trans->dirty_bgs_lock);
4897c79a1751SLiu Bo 		btrfs_put_block_group(cache);
4898ba2c4d4eSJosef Bacik 		btrfs_delayed_refs_rsv_release(fs_info, 1);
4899c79a1751SLiu Bo 		spin_lock(&cur_trans->dirty_bgs_lock);
4900c79a1751SLiu Bo 	}
4901c79a1751SLiu Bo 	spin_unlock(&cur_trans->dirty_bgs_lock);
4902c79a1751SLiu Bo 
490345ae2c18SNikolay Borisov 	/*
490445ae2c18SNikolay Borisov 	 * Refer to the definition of io_bgs member for details why it's safe
490545ae2c18SNikolay Borisov 	 * to use it without any locking
490645ae2c18SNikolay Borisov 	 */
4907c79a1751SLiu Bo 	while (!list_empty(&cur_trans->io_bgs)) {
4908c79a1751SLiu Bo 		cache = list_first_entry(&cur_trans->io_bgs,
490932da5386SDavid Sterba 					 struct btrfs_block_group,
4910c79a1751SLiu Bo 					 io_list);
4911c79a1751SLiu Bo 
4912c79a1751SLiu Bo 		list_del_init(&cache->io_list);
4913c79a1751SLiu Bo 		spin_lock(&cache->lock);
4914c79a1751SLiu Bo 		cache->disk_cache_state = BTRFS_DC_ERROR;
4915c79a1751SLiu Bo 		spin_unlock(&cache->lock);
4916c79a1751SLiu Bo 		btrfs_cleanup_bg_io(cache);
4917c79a1751SLiu Bo 	}
4918c79a1751SLiu Bo }
4919c79a1751SLiu Bo 
492049b25e05SJeff Mahoney void btrfs_cleanup_one_transaction(struct btrfs_transaction *cur_trans,
49212ff7e61eSJeff Mahoney 				   struct btrfs_fs_info *fs_info)
492249b25e05SJeff Mahoney {
4923bbbf7243SNikolay Borisov 	struct btrfs_device *dev, *tmp;
4924bbbf7243SNikolay Borisov 
49252ff7e61eSJeff Mahoney 	btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
4926c79a1751SLiu Bo 	ASSERT(list_empty(&cur_trans->dirty_bgs));
4927c79a1751SLiu Bo 	ASSERT(list_empty(&cur_trans->io_bgs));
4928c79a1751SLiu Bo 
4929bbbf7243SNikolay Borisov 	list_for_each_entry_safe(dev, tmp, &cur_trans->dev_update_list,
4930bbbf7243SNikolay Borisov 				 post_commit_list) {
4931bbbf7243SNikolay Borisov 		list_del_init(&dev->post_commit_list);
4932bbbf7243SNikolay Borisov 	}
4933bbbf7243SNikolay Borisov 
49342ff7e61eSJeff Mahoney 	btrfs_destroy_delayed_refs(cur_trans, fs_info);
493549b25e05SJeff Mahoney 
49364a9d8bdeSMiao Xie 	cur_trans->state = TRANS_STATE_COMMIT_START;
49370b246afaSJeff Mahoney 	wake_up(&fs_info->transaction_blocked_wait);
493849b25e05SJeff Mahoney 
49394a9d8bdeSMiao Xie 	cur_trans->state = TRANS_STATE_UNBLOCKED;
49400b246afaSJeff Mahoney 	wake_up(&fs_info->transaction_wait);
494149b25e05SJeff Mahoney 
4942ccdf9b30SJeff Mahoney 	btrfs_destroy_delayed_inodes(fs_info);
494367cde344SMiao Xie 
49442ff7e61eSJeff Mahoney 	btrfs_destroy_marked_extents(fs_info, &cur_trans->dirty_pages,
494549b25e05SJeff Mahoney 				     EXTENT_DIRTY);
4946fe119a6eSNikolay Borisov 	btrfs_destroy_pinned_extent(fs_info, &cur_trans->pinned_extents);
494749b25e05SJeff Mahoney 
4948d3575156SNaohiro Aota 	btrfs_free_redirty_list(cur_trans);
4949d3575156SNaohiro Aota 
49504a9d8bdeSMiao Xie 	cur_trans->state =TRANS_STATE_COMPLETED;
49514a9d8bdeSMiao Xie 	wake_up(&cur_trans->commit_wait);
495249b25e05SJeff Mahoney }
495349b25e05SJeff Mahoney 
49542ff7e61eSJeff Mahoney static int btrfs_cleanup_transaction(struct btrfs_fs_info *fs_info)
4955acce952bSliubo {
4956acce952bSliubo 	struct btrfs_transaction *t;
4957acce952bSliubo 
49580b246afaSJeff Mahoney 	mutex_lock(&fs_info->transaction_kthread_mutex);
4959acce952bSliubo 
49600b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
49610b246afaSJeff Mahoney 	while (!list_empty(&fs_info->trans_list)) {
49620b246afaSJeff Mahoney 		t = list_first_entry(&fs_info->trans_list,
4963724e2315SJosef Bacik 				     struct btrfs_transaction, list);
4964724e2315SJosef Bacik 		if (t->state >= TRANS_STATE_COMMIT_START) {
49659b64f57dSElena Reshetova 			refcount_inc(&t->use_count);
49660b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
49672ff7e61eSJeff Mahoney 			btrfs_wait_for_commit(fs_info, t->transid);
4968724e2315SJosef Bacik 			btrfs_put_transaction(t);
49690b246afaSJeff Mahoney 			spin_lock(&fs_info->trans_lock);
4970724e2315SJosef Bacik 			continue;
4971724e2315SJosef Bacik 		}
49720b246afaSJeff Mahoney 		if (t == fs_info->running_transaction) {
4973724e2315SJosef Bacik 			t->state = TRANS_STATE_COMMIT_DOING;
49740b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
4975724e2315SJosef Bacik 			/*
4976724e2315SJosef Bacik 			 * We wait for 0 num_writers since we don't hold a trans
4977724e2315SJosef Bacik 			 * handle open currently for this transaction.
4978724e2315SJosef Bacik 			 */
4979724e2315SJosef Bacik 			wait_event(t->writer_wait,
4980724e2315SJosef Bacik 				   atomic_read(&t->num_writers) == 0);
4981724e2315SJosef Bacik 		} else {
49820b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
4983724e2315SJosef Bacik 		}
49842ff7e61eSJeff Mahoney 		btrfs_cleanup_one_transaction(t, fs_info);
4985724e2315SJosef Bacik 
49860b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
49870b246afaSJeff Mahoney 		if (t == fs_info->running_transaction)
49880b246afaSJeff Mahoney 			fs_info->running_transaction = NULL;
4989724e2315SJosef Bacik 		list_del_init(&t->list);
49900b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
4991a4abeea4SJosef Bacik 
4992724e2315SJosef Bacik 		btrfs_put_transaction(t);
49932ff7e61eSJeff Mahoney 		trace_btrfs_transaction_commit(fs_info->tree_root);
49940b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
4995724e2315SJosef Bacik 	}
49960b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
49970b246afaSJeff Mahoney 	btrfs_destroy_all_ordered_extents(fs_info);
4998ccdf9b30SJeff Mahoney 	btrfs_destroy_delayed_inodes(fs_info);
4999ccdf9b30SJeff Mahoney 	btrfs_assert_delayed_root_empty(fs_info);
50000b246afaSJeff Mahoney 	btrfs_destroy_all_delalloc_inodes(fs_info);
5001ef67963dSJosef Bacik 	btrfs_drop_all_logs(fs_info);
50020b246afaSJeff Mahoney 	mutex_unlock(&fs_info->transaction_kthread_mutex);
5003acce952bSliubo 
5004acce952bSliubo 	return 0;
5005acce952bSliubo }
5006ec7d6dfdSNikolay Borisov 
5007453e4873SNikolay Borisov int btrfs_init_root_free_objectid(struct btrfs_root *root)
5008ec7d6dfdSNikolay Borisov {
5009ec7d6dfdSNikolay Borisov 	struct btrfs_path *path;
5010ec7d6dfdSNikolay Borisov 	int ret;
5011ec7d6dfdSNikolay Borisov 	struct extent_buffer *l;
5012ec7d6dfdSNikolay Borisov 	struct btrfs_key search_key;
5013ec7d6dfdSNikolay Borisov 	struct btrfs_key found_key;
5014ec7d6dfdSNikolay Borisov 	int slot;
5015ec7d6dfdSNikolay Borisov 
5016ec7d6dfdSNikolay Borisov 	path = btrfs_alloc_path();
5017ec7d6dfdSNikolay Borisov 	if (!path)
5018ec7d6dfdSNikolay Borisov 		return -ENOMEM;
5019ec7d6dfdSNikolay Borisov 
5020ec7d6dfdSNikolay Borisov 	search_key.objectid = BTRFS_LAST_FREE_OBJECTID;
5021ec7d6dfdSNikolay Borisov 	search_key.type = -1;
5022ec7d6dfdSNikolay Borisov 	search_key.offset = (u64)-1;
5023ec7d6dfdSNikolay Borisov 	ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
5024ec7d6dfdSNikolay Borisov 	if (ret < 0)
5025ec7d6dfdSNikolay Borisov 		goto error;
5026ec7d6dfdSNikolay Borisov 	BUG_ON(ret == 0); /* Corruption */
5027ec7d6dfdSNikolay Borisov 	if (path->slots[0] > 0) {
5028ec7d6dfdSNikolay Borisov 		slot = path->slots[0] - 1;
5029ec7d6dfdSNikolay Borisov 		l = path->nodes[0];
5030ec7d6dfdSNikolay Borisov 		btrfs_item_key_to_cpu(l, &found_key, slot);
503123125104SNikolay Borisov 		root->free_objectid = max_t(u64, found_key.objectid + 1,
503223125104SNikolay Borisov 					    BTRFS_FIRST_FREE_OBJECTID);
5033ec7d6dfdSNikolay Borisov 	} else {
503423125104SNikolay Borisov 		root->free_objectid = BTRFS_FIRST_FREE_OBJECTID;
5035ec7d6dfdSNikolay Borisov 	}
5036ec7d6dfdSNikolay Borisov 	ret = 0;
5037ec7d6dfdSNikolay Borisov error:
5038ec7d6dfdSNikolay Borisov 	btrfs_free_path(path);
5039ec7d6dfdSNikolay Borisov 	return ret;
5040ec7d6dfdSNikolay Borisov }
5041ec7d6dfdSNikolay Borisov 
5042543068a2SNikolay Borisov int btrfs_get_free_objectid(struct btrfs_root *root, u64 *objectid)
5043ec7d6dfdSNikolay Borisov {
5044ec7d6dfdSNikolay Borisov 	int ret;
5045ec7d6dfdSNikolay Borisov 	mutex_lock(&root->objectid_mutex);
5046ec7d6dfdSNikolay Borisov 
50476b8fad57SNikolay Borisov 	if (unlikely(root->free_objectid >= BTRFS_LAST_FREE_OBJECTID)) {
5048ec7d6dfdSNikolay Borisov 		btrfs_warn(root->fs_info,
5049ec7d6dfdSNikolay Borisov 			   "the objectid of root %llu reaches its highest value",
5050ec7d6dfdSNikolay Borisov 			   root->root_key.objectid);
5051ec7d6dfdSNikolay Borisov 		ret = -ENOSPC;
5052ec7d6dfdSNikolay Borisov 		goto out;
5053ec7d6dfdSNikolay Borisov 	}
5054ec7d6dfdSNikolay Borisov 
505523125104SNikolay Borisov 	*objectid = root->free_objectid++;
5056ec7d6dfdSNikolay Borisov 	ret = 0;
5057ec7d6dfdSNikolay Borisov out:
5058ec7d6dfdSNikolay Borisov 	mutex_unlock(&root->objectid_mutex);
5059ec7d6dfdSNikolay Borisov 	return ret;
5060ec7d6dfdSNikolay Borisov }
5061