xref: /openbmc/linux/fs/btrfs/disk-io.c (revision 2ba48b20)
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>
8fc7cbcd4SDavid Sterba #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"
26103c1972SChristoph Hellwig #include "bio.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"
46c7f13d42SJosef Bacik #include "fs.h"
4707e81dc9SJosef Bacik #include "accessors.h"
48a0231804SJosef Bacik #include "extent-tree.h"
4945c40c8fSJosef Bacik #include "root-tree.h"
5059b818e0SJosef Bacik #include "defrag.h"
51c7a03b52SJosef Bacik #include "uuid-tree.h"
5267707479SJosef Bacik #include "relocation.h"
532fc6822cSJosef Bacik #include "scrub.h"
54c03b2207SJosef Bacik #include "super.h"
55eb60ceacSChris Mason 
56319e4d06SQu Wenruo #define BTRFS_SUPER_FLAG_SUPP	(BTRFS_HEADER_FLAG_WRITTEN |\
57319e4d06SQu Wenruo 				 BTRFS_HEADER_FLAG_RELOC |\
58319e4d06SQu Wenruo 				 BTRFS_SUPER_FLAG_ERROR |\
59319e4d06SQu Wenruo 				 BTRFS_SUPER_FLAG_SEEDING |\
60e2731e55SAnand Jain 				 BTRFS_SUPER_FLAG_METADUMP |\
61e2731e55SAnand Jain 				 BTRFS_SUPER_FLAG_METADUMP_V2)
62319e4d06SQu Wenruo 
63143bede5SJeff Mahoney static void btrfs_destroy_ordered_extents(struct btrfs_root *root);
64acce952bSliubo static int btrfs_destroy_delayed_refs(struct btrfs_transaction *trans,
652ff7e61eSJeff Mahoney 				      struct btrfs_fs_info *fs_info);
66143bede5SJeff Mahoney static void btrfs_destroy_delalloc_inodes(struct btrfs_root *root);
672ff7e61eSJeff Mahoney static int btrfs_destroy_marked_extents(struct btrfs_fs_info *fs_info,
68acce952bSliubo 					struct extent_io_tree *dirty_pages,
69acce952bSliubo 					int mark);
702ff7e61eSJeff Mahoney static int btrfs_destroy_pinned_extent(struct btrfs_fs_info *fs_info,
71acce952bSliubo 				       struct extent_io_tree *pinned_extents);
722ff7e61eSJeff Mahoney static int btrfs_cleanup_transaction(struct btrfs_fs_info *fs_info);
732ff7e61eSJeff Mahoney static void btrfs_error_commit_super(struct btrfs_fs_info *fs_info);
74ce9adaa5SChris Mason 
75141386e1SJosef Bacik static void btrfs_free_csum_hash(struct btrfs_fs_info *fs_info)
76141386e1SJosef Bacik {
77141386e1SJosef Bacik 	if (fs_info->csum_shash)
78141386e1SJosef Bacik 		crypto_free_shash(fs_info->csum_shash);
79141386e1SJosef Bacik }
80141386e1SJosef Bacik 
81d352ac68SChris Mason /*
82d352ac68SChris Mason  * async submit bios are used to offload expensive checksumming
83d352ac68SChris Mason  * onto the worker threads.  They checksum file and metadata bios
84d352ac68SChris Mason  * just before they are sent down the IO stack.
85d352ac68SChris Mason  */
8644b8bd7eSChris Mason struct async_submit_bio {
87da67daabSDavid Sterba 	struct btrfs_inode *inode;
8844b8bd7eSChris Mason 	struct bio *bio;
89ab2072b2SDavid Sterba 	enum btrfs_wq_submit_cmd submit_cmd;
9044b8bd7eSChris Mason 	int mirror_num;
911941b64bSQu Wenruo 
92ab2072b2SDavid Sterba 	/* Optional parameter for used by direct io */
931941b64bSQu Wenruo 	u64 dio_file_offset;
948b712842SChris Mason 	struct btrfs_work work;
954e4cbee9SChristoph Hellwig 	blk_status_t status;
9644b8bd7eSChris Mason };
9744b8bd7eSChris Mason 
9885d4e461SChris Mason /*
992996e1f8SJohannes Thumshirn  * Compute the csum of a btree block and store the result to provided buffer.
100d352ac68SChris Mason  */
101c67b3892SDavid Sterba static void csum_tree_block(struct extent_buffer *buf, u8 *result)
10219c00ddcSChris Mason {
103d5178578SJohannes Thumshirn 	struct btrfs_fs_info *fs_info = buf->fs_info;
1047280305eSDavid Sterba 	const int num_pages = num_extent_pages(buf);
105a26663e7SQu Wenruo 	const int first_page_part = min_t(u32, PAGE_SIZE, fs_info->nodesize);
106d5178578SJohannes Thumshirn 	SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
10719c00ddcSChris Mason 	char *kaddr;
108e9be5a30SDavid Sterba 	int i;
109d5178578SJohannes Thumshirn 
110d5178578SJohannes Thumshirn 	shash->tfm = fs_info->csum_shash;
111d5178578SJohannes Thumshirn 	crypto_shash_init(shash);
112a26663e7SQu Wenruo 	kaddr = page_address(buf->pages[0]) + offset_in_page(buf->start);
113e9be5a30SDavid Sterba 	crypto_shash_update(shash, kaddr + BTRFS_CSUM_SIZE,
114a26663e7SQu Wenruo 			    first_page_part - BTRFS_CSUM_SIZE);
11519c00ddcSChris Mason 
116e9be5a30SDavid Sterba 	for (i = 1; i < num_pages; i++) {
117e9be5a30SDavid Sterba 		kaddr = page_address(buf->pages[i]);
118e9be5a30SDavid Sterba 		crypto_shash_update(shash, kaddr, PAGE_SIZE);
11919c00ddcSChris Mason 	}
12071a63551SDavid Sterba 	memset(result, 0, BTRFS_CSUM_SIZE);
121d5178578SJohannes Thumshirn 	crypto_shash_final(shash, result);
12219c00ddcSChris Mason }
12319c00ddcSChris Mason 
124d352ac68SChris Mason /*
125d352ac68SChris Mason  * we can't consider a given block up to date unless the transid of the
126d352ac68SChris Mason  * block matches the transid in the parent node's pointer.  This is how we
127d352ac68SChris Mason  * detect blocks that either didn't get written at all or got written
128d352ac68SChris Mason  * in the wrong place.
129d352ac68SChris Mason  */
1301259ab75SChris Mason static int verify_parent_transid(struct extent_io_tree *io_tree,
131b9fab919SChris Mason 				 struct extent_buffer *eb, u64 parent_transid,
132b9fab919SChris Mason 				 int atomic)
1331259ab75SChris Mason {
1342ac55d41SJosef Bacik 	struct extent_state *cached_state = NULL;
1351259ab75SChris Mason 	int ret;
1361259ab75SChris Mason 
1371259ab75SChris Mason 	if (!parent_transid || btrfs_header_generation(eb) == parent_transid)
1381259ab75SChris Mason 		return 0;
1391259ab75SChris Mason 
140b9fab919SChris Mason 	if (atomic)
141b9fab919SChris Mason 		return -EAGAIN;
142b9fab919SChris Mason 
143570eb97bSJosef Bacik 	lock_extent(io_tree, eb->start, eb->start + eb->len - 1, &cached_state);
1440b32f4bbSJosef Bacik 	if (extent_buffer_uptodate(eb) &&
1451259ab75SChris Mason 	    btrfs_header_generation(eb) == parent_transid) {
1461259ab75SChris Mason 		ret = 0;
1471259ab75SChris Mason 		goto out;
1481259ab75SChris Mason 	}
14994647322SDavid Sterba 	btrfs_err_rl(eb->fs_info,
1508f0ed7d4SQu Wenruo "parent transid verify failed on logical %llu mirror %u wanted %llu found %llu",
1518f0ed7d4SQu Wenruo 			eb->start, eb->read_mirror,
15229549aecSWang Shilong 			parent_transid, btrfs_header_generation(eb));
1531259ab75SChris Mason 	ret = 1;
1540b32f4bbSJosef Bacik 	clear_extent_buffer_uptodate(eb);
15533958dc6SChris Mason out:
156570eb97bSJosef Bacik 	unlock_extent(io_tree, eb->start, eb->start + eb->len - 1,
157e43bbe5eSDavid Sterba 		      &cached_state);
1581259ab75SChris Mason 	return ret;
1591259ab75SChris Mason }
1601259ab75SChris Mason 
161e7e16f48SJohannes Thumshirn static bool btrfs_supported_super_csum(u16 csum_type)
162e7e16f48SJohannes Thumshirn {
163e7e16f48SJohannes Thumshirn 	switch (csum_type) {
164e7e16f48SJohannes Thumshirn 	case BTRFS_CSUM_TYPE_CRC32:
1653951e7f0SJohannes Thumshirn 	case BTRFS_CSUM_TYPE_XXHASH:
1663831bf00SJohannes Thumshirn 	case BTRFS_CSUM_TYPE_SHA256:
167352ae07bSDavid Sterba 	case BTRFS_CSUM_TYPE_BLAKE2:
168e7e16f48SJohannes Thumshirn 		return true;
169e7e16f48SJohannes Thumshirn 	default:
170e7e16f48SJohannes Thumshirn 		return false;
171e7e16f48SJohannes Thumshirn 	}
172e7e16f48SJohannes Thumshirn }
173e7e16f48SJohannes Thumshirn 
174d352ac68SChris Mason /*
1751104a885SDavid Sterba  * Return 0 if the superblock checksum type matches the checksum value of that
1761104a885SDavid Sterba  * algorithm. Pass the raw disk superblock data.
1771104a885SDavid Sterba  */
1783d17adeaSQu Wenruo int btrfs_check_super_csum(struct btrfs_fs_info *fs_info,
1793d17adeaSQu Wenruo 			   const struct btrfs_super_block *disk_sb)
1801104a885SDavid Sterba {
18151bce6c9SJohannes Thumshirn 	char result[BTRFS_CSUM_SIZE];
182d5178578SJohannes Thumshirn 	SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
183d5178578SJohannes Thumshirn 
184d5178578SJohannes Thumshirn 	shash->tfm = fs_info->csum_shash;
1851104a885SDavid Sterba 
1861104a885SDavid Sterba 	/*
1871104a885SDavid Sterba 	 * The super_block structure does not span the whole
18851bce6c9SJohannes Thumshirn 	 * BTRFS_SUPER_INFO_SIZE range, we expect that the unused space is
18951bce6c9SJohannes Thumshirn 	 * filled with zeros and is included in the checksum.
1901104a885SDavid Sterba 	 */
1913d17adeaSQu Wenruo 	crypto_shash_digest(shash, (const u8 *)disk_sb + BTRFS_CSUM_SIZE,
192fd08001fSEric Biggers 			    BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE, result);
1931104a885SDavid Sterba 
19455fc29beSDavid Sterba 	if (memcmp(disk_sb->csum, result, fs_info->csum_size))
195e7e16f48SJohannes Thumshirn 		return 1;
1961104a885SDavid Sterba 
197e7e16f48SJohannes Thumshirn 	return 0;
1981104a885SDavid Sterba }
1991104a885SDavid Sterba 
200e064d5e9SDavid Sterba int btrfs_verify_level_key(struct extent_buffer *eb, int level,
201ff76a864SLiu Bo 			   struct btrfs_key *first_key, u64 parent_transid)
202581c1760SQu Wenruo {
203e064d5e9SDavid Sterba 	struct btrfs_fs_info *fs_info = eb->fs_info;
204581c1760SQu Wenruo 	int found_level;
205581c1760SQu Wenruo 	struct btrfs_key found_key;
206581c1760SQu Wenruo 	int ret;
207581c1760SQu Wenruo 
208581c1760SQu Wenruo 	found_level = btrfs_header_level(eb);
209581c1760SQu Wenruo 	if (found_level != level) {
21063489055SQu Wenruo 		WARN(IS_ENABLED(CONFIG_BTRFS_DEBUG),
21163489055SQu Wenruo 		     KERN_ERR "BTRFS: tree level check failed\n");
212581c1760SQu Wenruo 		btrfs_err(fs_info,
213581c1760SQu Wenruo "tree level mismatch detected, bytenr=%llu level expected=%u has=%u",
214581c1760SQu Wenruo 			  eb->start, level, found_level);
215581c1760SQu Wenruo 		return -EIO;
216581c1760SQu Wenruo 	}
217581c1760SQu Wenruo 
218581c1760SQu Wenruo 	if (!first_key)
219581c1760SQu Wenruo 		return 0;
220581c1760SQu Wenruo 
2215d41be6fSQu Wenruo 	/*
2225d41be6fSQu Wenruo 	 * For live tree block (new tree blocks in current transaction),
2235d41be6fSQu Wenruo 	 * we need proper lock context to avoid race, which is impossible here.
2245d41be6fSQu Wenruo 	 * So we only checks tree blocks which is read from disk, whose
2255d41be6fSQu Wenruo 	 * generation <= fs_info->last_trans_committed.
2265d41be6fSQu Wenruo 	 */
2275d41be6fSQu Wenruo 	if (btrfs_header_generation(eb) > fs_info->last_trans_committed)
2285d41be6fSQu Wenruo 		return 0;
22962fdaa52SQu Wenruo 
23062fdaa52SQu Wenruo 	/* We have @first_key, so this @eb must have at least one item */
23162fdaa52SQu Wenruo 	if (btrfs_header_nritems(eb) == 0) {
23262fdaa52SQu Wenruo 		btrfs_err(fs_info,
23362fdaa52SQu Wenruo 		"invalid tree nritems, bytenr=%llu nritems=0 expect >0",
23462fdaa52SQu Wenruo 			  eb->start);
23562fdaa52SQu Wenruo 		WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
23662fdaa52SQu Wenruo 		return -EUCLEAN;
23762fdaa52SQu Wenruo 	}
23862fdaa52SQu Wenruo 
239581c1760SQu Wenruo 	if (found_level)
240581c1760SQu Wenruo 		btrfs_node_key_to_cpu(eb, &found_key, 0);
241581c1760SQu Wenruo 	else
242581c1760SQu Wenruo 		btrfs_item_key_to_cpu(eb, &found_key, 0);
243581c1760SQu Wenruo 	ret = btrfs_comp_cpu_keys(first_key, &found_key);
244581c1760SQu Wenruo 
245581c1760SQu Wenruo 	if (ret) {
24663489055SQu Wenruo 		WARN(IS_ENABLED(CONFIG_BTRFS_DEBUG),
24763489055SQu Wenruo 		     KERN_ERR "BTRFS: tree first key check failed\n");
248581c1760SQu Wenruo 		btrfs_err(fs_info,
249ff76a864SLiu Bo "tree first key mismatch detected, bytenr=%llu parent_transid=%llu key expected=(%llu,%u,%llu) has=(%llu,%u,%llu)",
250ff76a864SLiu Bo 			  eb->start, parent_transid, first_key->objectid,
251ff76a864SLiu Bo 			  first_key->type, first_key->offset,
252ff76a864SLiu Bo 			  found_key.objectid, found_key.type,
253ff76a864SLiu Bo 			  found_key.offset);
254581c1760SQu Wenruo 	}
255581c1760SQu Wenruo 	return ret;
256581c1760SQu Wenruo }
257581c1760SQu Wenruo 
258bacf60e5SChristoph Hellwig static int btrfs_repair_eb_io_failure(const struct extent_buffer *eb,
259bacf60e5SChristoph Hellwig 				      int mirror_num)
260bacf60e5SChristoph Hellwig {
261bacf60e5SChristoph Hellwig 	struct btrfs_fs_info *fs_info = eb->fs_info;
262bacf60e5SChristoph Hellwig 	u64 start = eb->start;
263bacf60e5SChristoph Hellwig 	int i, num_pages = num_extent_pages(eb);
264bacf60e5SChristoph Hellwig 	int ret = 0;
265bacf60e5SChristoph Hellwig 
266bacf60e5SChristoph Hellwig 	if (sb_rdonly(fs_info->sb))
267bacf60e5SChristoph Hellwig 		return -EROFS;
268bacf60e5SChristoph Hellwig 
269bacf60e5SChristoph Hellwig 	for (i = 0; i < num_pages; i++) {
270bacf60e5SChristoph Hellwig 		struct page *p = eb->pages[i];
271bacf60e5SChristoph Hellwig 
272bacf60e5SChristoph Hellwig 		ret = btrfs_repair_io_failure(fs_info, 0, start, PAGE_SIZE,
273bacf60e5SChristoph Hellwig 				start, p, start - page_offset(p), mirror_num);
274bacf60e5SChristoph Hellwig 		if (ret)
275bacf60e5SChristoph Hellwig 			break;
276bacf60e5SChristoph Hellwig 		start += PAGE_SIZE;
277bacf60e5SChristoph Hellwig 	}
278bacf60e5SChristoph Hellwig 
279bacf60e5SChristoph Hellwig 	return ret;
280bacf60e5SChristoph Hellwig }
281bacf60e5SChristoph Hellwig 
2821104a885SDavid Sterba /*
283d352ac68SChris Mason  * helper to read a given tree block, doing retries as required when
284d352ac68SChris Mason  * the checksums don't match and we have alternate mirrors to try.
285581c1760SQu Wenruo  *
286789d6a3aSQu Wenruo  * @check:		expected tree parentness check, see the comments of the
287789d6a3aSQu Wenruo  *			structure for details.
288d352ac68SChris Mason  */
2896a2e9dc4SFilipe Manana int btrfs_read_extent_buffer(struct extent_buffer *eb,
290789d6a3aSQu Wenruo 			     struct btrfs_tree_parent_check *check)
291f188591eSChris Mason {
2925ab12d1fSDavid Sterba 	struct btrfs_fs_info *fs_info = eb->fs_info;
293ea466794SJosef Bacik 	int failed = 0;
294f188591eSChris Mason 	int ret;
295f188591eSChris Mason 	int num_copies = 0;
296f188591eSChris Mason 	int mirror_num = 0;
297ea466794SJosef Bacik 	int failed_mirror = 0;
298f188591eSChris Mason 
299789d6a3aSQu Wenruo 	ASSERT(check);
300789d6a3aSQu Wenruo 
301f188591eSChris Mason 	while (1) {
302f8397d69SNikolay Borisov 		clear_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags);
303947a6299SQu Wenruo 		ret = read_extent_buffer_pages(eb, WAIT_COMPLETE, mirror_num, check);
304947a6299SQu Wenruo 		if (!ret)
305581c1760SQu Wenruo 			break;
306d397712bSChris Mason 
3070b246afaSJeff Mahoney 		num_copies = btrfs_num_copies(fs_info,
308f188591eSChris Mason 					      eb->start, eb->len);
3094235298eSChris Mason 		if (num_copies == 1)
310ea466794SJosef Bacik 			break;
3114235298eSChris Mason 
3125cf1ab56SJosef Bacik 		if (!failed_mirror) {
3135cf1ab56SJosef Bacik 			failed = 1;
3145cf1ab56SJosef Bacik 			failed_mirror = eb->read_mirror;
3155cf1ab56SJosef Bacik 		}
3165cf1ab56SJosef Bacik 
317f188591eSChris Mason 		mirror_num++;
318ea466794SJosef Bacik 		if (mirror_num == failed_mirror)
319ea466794SJosef Bacik 			mirror_num++;
320ea466794SJosef Bacik 
3214235298eSChris Mason 		if (mirror_num > num_copies)
322ea466794SJosef Bacik 			break;
323f188591eSChris Mason 	}
324ea466794SJosef Bacik 
325c0901581SStefan Behrens 	if (failed && !ret && failed_mirror)
32620a1fbf9SDavid Sterba 		btrfs_repair_eb_io_failure(eb, failed_mirror);
327ea466794SJosef Bacik 
328ea466794SJosef Bacik 	return ret;
329f188591eSChris Mason }
33019c00ddcSChris Mason 
331eca0f6f6SQu Wenruo static int csum_one_extent_buffer(struct extent_buffer *eb)
332eca0f6f6SQu Wenruo {
333eca0f6f6SQu Wenruo 	struct btrfs_fs_info *fs_info = eb->fs_info;
334eca0f6f6SQu Wenruo 	u8 result[BTRFS_CSUM_SIZE];
335eca0f6f6SQu Wenruo 	int ret;
336eca0f6f6SQu Wenruo 
337eca0f6f6SQu Wenruo 	ASSERT(memcmp_extent_buffer(eb, fs_info->fs_devices->metadata_uuid,
338eca0f6f6SQu Wenruo 				    offsetof(struct btrfs_header, fsid),
339eca0f6f6SQu Wenruo 				    BTRFS_FSID_SIZE) == 0);
340eca0f6f6SQu Wenruo 	csum_tree_block(eb, result);
341eca0f6f6SQu Wenruo 
342eca0f6f6SQu Wenruo 	if (btrfs_header_level(eb))
343eca0f6f6SQu Wenruo 		ret = btrfs_check_node(eb);
344eca0f6f6SQu Wenruo 	else
345eca0f6f6SQu Wenruo 		ret = btrfs_check_leaf_full(eb);
346eca0f6f6SQu Wenruo 
3473777369fSQu Wenruo 	if (ret < 0)
3483777369fSQu Wenruo 		goto error;
3493777369fSQu Wenruo 
3503777369fSQu Wenruo 	/*
3513777369fSQu Wenruo 	 * Also check the generation, the eb reached here must be newer than
3523777369fSQu Wenruo 	 * last committed. Or something seriously wrong happened.
3533777369fSQu Wenruo 	 */
3543777369fSQu Wenruo 	if (unlikely(btrfs_header_generation(eb) <= fs_info->last_trans_committed)) {
3553777369fSQu Wenruo 		ret = -EUCLEAN;
356eca0f6f6SQu Wenruo 		btrfs_err(fs_info,
3573777369fSQu Wenruo 			"block=%llu bad generation, have %llu expect > %llu",
3583777369fSQu Wenruo 			  eb->start, btrfs_header_generation(eb),
3593777369fSQu Wenruo 			  fs_info->last_trans_committed);
3603777369fSQu Wenruo 		goto error;
361eca0f6f6SQu Wenruo 	}
362eca0f6f6SQu Wenruo 	write_extent_buffer(eb, result, 0, fs_info->csum_size);
363eca0f6f6SQu Wenruo 
364eca0f6f6SQu Wenruo 	return 0;
3653777369fSQu Wenruo 
3663777369fSQu Wenruo error:
3673777369fSQu Wenruo 	btrfs_print_tree(eb, 0);
3683777369fSQu Wenruo 	btrfs_err(fs_info, "block=%llu write time tree block corruption detected",
3693777369fSQu Wenruo 		  eb->start);
3703777369fSQu Wenruo 	WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
3713777369fSQu Wenruo 	return ret;
372eca0f6f6SQu Wenruo }
373eca0f6f6SQu Wenruo 
374eca0f6f6SQu Wenruo /* Checksum all dirty extent buffers in one bio_vec */
375eca0f6f6SQu Wenruo static int csum_dirty_subpage_buffers(struct btrfs_fs_info *fs_info,
376eca0f6f6SQu Wenruo 				      struct bio_vec *bvec)
377eca0f6f6SQu Wenruo {
378eca0f6f6SQu Wenruo 	struct page *page = bvec->bv_page;
379eca0f6f6SQu Wenruo 	u64 bvec_start = page_offset(page) + bvec->bv_offset;
380eca0f6f6SQu Wenruo 	u64 cur;
381eca0f6f6SQu Wenruo 	int ret = 0;
382eca0f6f6SQu Wenruo 
383eca0f6f6SQu Wenruo 	for (cur = bvec_start; cur < bvec_start + bvec->bv_len;
384eca0f6f6SQu Wenruo 	     cur += fs_info->nodesize) {
385eca0f6f6SQu Wenruo 		struct extent_buffer *eb;
386eca0f6f6SQu Wenruo 		bool uptodate;
387eca0f6f6SQu Wenruo 
388eca0f6f6SQu Wenruo 		eb = find_extent_buffer(fs_info, cur);
389eca0f6f6SQu Wenruo 		uptodate = btrfs_subpage_test_uptodate(fs_info, page, cur,
390eca0f6f6SQu Wenruo 						       fs_info->nodesize);
391eca0f6f6SQu Wenruo 
39201cd3909SDavid Sterba 		/* A dirty eb shouldn't disappear from buffer_radix */
393eca0f6f6SQu Wenruo 		if (WARN_ON(!eb))
394eca0f6f6SQu Wenruo 			return -EUCLEAN;
395eca0f6f6SQu Wenruo 
396eca0f6f6SQu Wenruo 		if (WARN_ON(cur != btrfs_header_bytenr(eb))) {
397eca0f6f6SQu Wenruo 			free_extent_buffer(eb);
398eca0f6f6SQu Wenruo 			return -EUCLEAN;
399eca0f6f6SQu Wenruo 		}
400eca0f6f6SQu Wenruo 		if (WARN_ON(!uptodate)) {
401eca0f6f6SQu Wenruo 			free_extent_buffer(eb);
402eca0f6f6SQu Wenruo 			return -EUCLEAN;
403eca0f6f6SQu Wenruo 		}
404eca0f6f6SQu Wenruo 
405eca0f6f6SQu Wenruo 		ret = csum_one_extent_buffer(eb);
406eca0f6f6SQu Wenruo 		free_extent_buffer(eb);
407eca0f6f6SQu Wenruo 		if (ret < 0)
408eca0f6f6SQu Wenruo 			return ret;
409eca0f6f6SQu Wenruo 	}
410eca0f6f6SQu Wenruo 	return ret;
411eca0f6f6SQu Wenruo }
412eca0f6f6SQu Wenruo 
413d352ac68SChris Mason /*
414ac303b69SQu Wenruo  * Checksum a dirty tree block before IO.  This has extra checks to make sure
415ac303b69SQu Wenruo  * we only fill in the checksum field in the first page of a multi-page block.
416ac303b69SQu Wenruo  * For subpage extent buffers we need bvec to also read the offset in the page.
417d352ac68SChris Mason  */
418ac303b69SQu Wenruo static int csum_dirty_buffer(struct btrfs_fs_info *fs_info, struct bio_vec *bvec)
41919c00ddcSChris Mason {
420ac303b69SQu Wenruo 	struct page *page = bvec->bv_page;
4214eee4fa4SMiao Xie 	u64 start = page_offset(page);
42219c00ddcSChris Mason 	u64 found_start;
42319c00ddcSChris Mason 	struct extent_buffer *eb;
424eca0f6f6SQu Wenruo 
425fbca46ebSQu Wenruo 	if (fs_info->nodesize < PAGE_SIZE)
426eca0f6f6SQu Wenruo 		return csum_dirty_subpage_buffers(fs_info, bvec);
427f188591eSChris Mason 
4284f2de97aSJosef Bacik 	eb = (struct extent_buffer *)page->private;
4294f2de97aSJosef Bacik 	if (page != eb->pages[0])
4304f2de97aSJosef Bacik 		return 0;
4310f805531SAlex Lyakas 
43219c00ddcSChris Mason 	found_start = btrfs_header_bytenr(eb);
433d3575156SNaohiro Aota 
434d3575156SNaohiro Aota 	if (test_bit(EXTENT_BUFFER_NO_CHECK, &eb->bflags)) {
435d3575156SNaohiro Aota 		WARN_ON(found_start != 0);
436d3575156SNaohiro Aota 		return 0;
437d3575156SNaohiro Aota 	}
438d3575156SNaohiro Aota 
4390f805531SAlex Lyakas 	/*
4400f805531SAlex Lyakas 	 * Please do not consolidate these warnings into a single if.
4410f805531SAlex Lyakas 	 * It is useful to know what went wrong.
4420f805531SAlex Lyakas 	 */
4430f805531SAlex Lyakas 	if (WARN_ON(found_start != start))
4440f805531SAlex Lyakas 		return -EUCLEAN;
4450f805531SAlex Lyakas 	if (WARN_ON(!PageUptodate(page)))
4460f805531SAlex Lyakas 		return -EUCLEAN;
4470f805531SAlex Lyakas 
448eca0f6f6SQu Wenruo 	return csum_one_extent_buffer(eb);
44919c00ddcSChris Mason }
45019c00ddcSChris Mason 
451b0c9b3b0SDavid Sterba static int check_tree_block_fsid(struct extent_buffer *eb)
4522b82032cSYan Zheng {
453b0c9b3b0SDavid Sterba 	struct btrfs_fs_info *fs_info = eb->fs_info;
454944d3f9fSNikolay Borisov 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices, *seed_devs;
45544880fdcSAnand Jain 	u8 fsid[BTRFS_FSID_SIZE];
456944d3f9fSNikolay Borisov 	u8 *metadata_uuid;
4572b82032cSYan Zheng 
4589a8658e3SDavid Sterba 	read_extent_buffer(eb, fsid, offsetof(struct btrfs_header, fsid),
4599a8658e3SDavid Sterba 			   BTRFS_FSID_SIZE);
4607239ff4bSNikolay Borisov 	/*
461944d3f9fSNikolay Borisov 	 * Checking the incompat flag is only valid for the current fs. For
462944d3f9fSNikolay Borisov 	 * seed devices it's forbidden to have their uuid changed so reading
463944d3f9fSNikolay Borisov 	 * ->fsid in this case is fine
4647239ff4bSNikolay Borisov 	 */
465944d3f9fSNikolay Borisov 	if (btrfs_fs_incompat(fs_info, METADATA_UUID))
4667239ff4bSNikolay Borisov 		metadata_uuid = fs_devices->metadata_uuid;
4677239ff4bSNikolay Borisov 	else
4687239ff4bSNikolay Borisov 		metadata_uuid = fs_devices->fsid;
4697239ff4bSNikolay Borisov 
470944d3f9fSNikolay Borisov 	if (!memcmp(fsid, metadata_uuid, BTRFS_FSID_SIZE))
471944d3f9fSNikolay Borisov 		return 0;
472944d3f9fSNikolay Borisov 
473944d3f9fSNikolay Borisov 	list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list)
474944d3f9fSNikolay Borisov 		if (!memcmp(fsid, seed_devs->fsid, BTRFS_FSID_SIZE))
475944d3f9fSNikolay Borisov 			return 0;
476944d3f9fSNikolay Borisov 
477944d3f9fSNikolay Borisov 	return 1;
4782b82032cSYan Zheng }
4792b82032cSYan Zheng 
48077bf40a2SQu Wenruo /* Do basic extent buffer checks at read time */
481947a6299SQu Wenruo static int validate_extent_buffer(struct extent_buffer *eb,
482947a6299SQu Wenruo 				  struct btrfs_tree_parent_check *check)
483ce9adaa5SChris Mason {
48477bf40a2SQu Wenruo 	struct btrfs_fs_info *fs_info = eb->fs_info;
485ce9adaa5SChris Mason 	u64 found_start;
48677bf40a2SQu Wenruo 	const u32 csum_size = fs_info->csum_size;
48777bf40a2SQu Wenruo 	u8 found_level;
4882996e1f8SJohannes Thumshirn 	u8 result[BTRFS_CSUM_SIZE];
489dfd29eedSDavid Sterba 	const u8 *header_csum;
49077bf40a2SQu Wenruo 	int ret = 0;
491ea466794SJosef Bacik 
492947a6299SQu Wenruo 	ASSERT(check);
493947a6299SQu Wenruo 
494ce9adaa5SChris Mason 	found_start = btrfs_header_bytenr(eb);
495727011e0SChris Mason 	if (found_start != eb->start) {
4968f0ed7d4SQu Wenruo 		btrfs_err_rl(fs_info,
4978f0ed7d4SQu Wenruo 			"bad tree block start, mirror %u want %llu have %llu",
4988f0ed7d4SQu Wenruo 			     eb->read_mirror, eb->start, found_start);
499f188591eSChris Mason 		ret = -EIO;
50077bf40a2SQu Wenruo 		goto out;
501ce9adaa5SChris Mason 	}
502b0c9b3b0SDavid Sterba 	if (check_tree_block_fsid(eb)) {
5038f0ed7d4SQu Wenruo 		btrfs_err_rl(fs_info, "bad fsid on logical %llu mirror %u",
5048f0ed7d4SQu Wenruo 			     eb->start, eb->read_mirror);
5051259ab75SChris Mason 		ret = -EIO;
50677bf40a2SQu Wenruo 		goto out;
5071259ab75SChris Mason 	}
508ce9adaa5SChris Mason 	found_level = btrfs_header_level(eb);
5091c24c3ceSJosef Bacik 	if (found_level >= BTRFS_MAX_LEVEL) {
5108f0ed7d4SQu Wenruo 		btrfs_err(fs_info,
5118f0ed7d4SQu Wenruo 			"bad tree block level, mirror %u level %d on logical %llu",
5128f0ed7d4SQu Wenruo 			eb->read_mirror, btrfs_header_level(eb), eb->start);
5131c24c3ceSJosef Bacik 		ret = -EIO;
51477bf40a2SQu Wenruo 		goto out;
5151c24c3ceSJosef Bacik 	}
516ce9adaa5SChris Mason 
517c67b3892SDavid Sterba 	csum_tree_block(eb, result);
518dfd29eedSDavid Sterba 	header_csum = page_address(eb->pages[0]) +
519dfd29eedSDavid Sterba 		get_eb_offset_in_page(eb, offsetof(struct btrfs_header, csum));
520a826d6dcSJosef Bacik 
521dfd29eedSDavid Sterba 	if (memcmp(result, header_csum, csum_size) != 0) {
5222996e1f8SJohannes Thumshirn 		btrfs_warn_rl(fs_info,
5238f0ed7d4SQu Wenruo "checksum verify failed on logical %llu mirror %u wanted " CSUM_FMT " found " CSUM_FMT " level %d",
5248f0ed7d4SQu Wenruo 			      eb->start, eb->read_mirror,
525dfd29eedSDavid Sterba 			      CSUM_FMT_VALUE(csum_size, header_csum),
52635be8851SJohannes Thumshirn 			      CSUM_FMT_VALUE(csum_size, result),
52735be8851SJohannes Thumshirn 			      btrfs_header_level(eb));
5282996e1f8SJohannes Thumshirn 		ret = -EUCLEAN;
52977bf40a2SQu Wenruo 		goto out;
5302996e1f8SJohannes Thumshirn 	}
5312996e1f8SJohannes Thumshirn 
532947a6299SQu Wenruo 	if (found_level != check->level) {
53377177ed1SQu Wenruo 		btrfs_err(fs_info,
53477177ed1SQu Wenruo 		"level verify failed on logical %llu mirror %u wanted %u found %u",
53577177ed1SQu Wenruo 			  eb->start, eb->read_mirror, check->level, found_level);
536947a6299SQu Wenruo 		ret = -EIO;
537947a6299SQu Wenruo 		goto out;
538947a6299SQu Wenruo 	}
539947a6299SQu Wenruo 	if (unlikely(check->transid &&
540947a6299SQu Wenruo 		     btrfs_header_generation(eb) != check->transid)) {
541947a6299SQu Wenruo 		btrfs_err_rl(eb->fs_info,
542947a6299SQu Wenruo "parent transid verify failed on logical %llu mirror %u wanted %llu found %llu",
543947a6299SQu Wenruo 				eb->start, eb->read_mirror, check->transid,
544947a6299SQu Wenruo 				btrfs_header_generation(eb));
545947a6299SQu Wenruo 		ret = -EIO;
546947a6299SQu Wenruo 		goto out;
547947a6299SQu Wenruo 	}
548947a6299SQu Wenruo 	if (check->has_first_key) {
549947a6299SQu Wenruo 		struct btrfs_key *expect_key = &check->first_key;
550947a6299SQu Wenruo 		struct btrfs_key found_key;
551947a6299SQu Wenruo 
552947a6299SQu Wenruo 		if (found_level)
553947a6299SQu Wenruo 			btrfs_node_key_to_cpu(eb, &found_key, 0);
554947a6299SQu Wenruo 		else
555947a6299SQu Wenruo 			btrfs_item_key_to_cpu(eb, &found_key, 0);
556947a6299SQu Wenruo 		if (unlikely(btrfs_comp_cpu_keys(expect_key, &found_key))) {
557947a6299SQu Wenruo 			btrfs_err(fs_info,
558947a6299SQu Wenruo "tree first key mismatch detected, bytenr=%llu parent_transid=%llu key expected=(%llu,%u,%llu) has=(%llu,%u,%llu)",
559947a6299SQu Wenruo 				  eb->start, check->transid,
560947a6299SQu Wenruo 				  expect_key->objectid,
561947a6299SQu Wenruo 				  expect_key->type, expect_key->offset,
562947a6299SQu Wenruo 				  found_key.objectid, found_key.type,
563947a6299SQu Wenruo 				  found_key.offset);
564947a6299SQu Wenruo 			ret = -EUCLEAN;
565947a6299SQu Wenruo 			goto out;
566947a6299SQu Wenruo 		}
567947a6299SQu Wenruo 	}
568947a6299SQu Wenruo 	if (check->owner_root) {
569947a6299SQu Wenruo 		ret = btrfs_check_eb_owner(eb, check->owner_root);
570947a6299SQu Wenruo 		if (ret < 0)
571947a6299SQu Wenruo 			goto out;
572947a6299SQu Wenruo 	}
573947a6299SQu Wenruo 
574a826d6dcSJosef Bacik 	/*
575a826d6dcSJosef Bacik 	 * If this is a leaf block and it is corrupt, set the corrupt bit so
576a826d6dcSJosef Bacik 	 * that we don't try and read the other copies of this block, just
577a826d6dcSJosef Bacik 	 * return -EIO.
578a826d6dcSJosef Bacik 	 */
5791c4360eeSDavid Sterba 	if (found_level == 0 && btrfs_check_leaf_full(eb)) {
580a826d6dcSJosef Bacik 		set_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags);
581a826d6dcSJosef Bacik 		ret = -EIO;
582a826d6dcSJosef Bacik 	}
583ce9adaa5SChris Mason 
584813fd1dcSDavid Sterba 	if (found_level > 0 && btrfs_check_node(eb))
585053ab70fSLiu Bo 		ret = -EIO;
586053ab70fSLiu Bo 
5870b32f4bbSJosef Bacik 	if (!ret)
5880b32f4bbSJosef Bacik 		set_extent_buffer_uptodate(eb);
58975391f0dSQu Wenruo 	else
59075391f0dSQu Wenruo 		btrfs_err(fs_info,
5918f0ed7d4SQu Wenruo 		"read time tree block corruption detected on logical %llu mirror %u",
5928f0ed7d4SQu Wenruo 			  eb->start, eb->read_mirror);
59377bf40a2SQu Wenruo out:
59477bf40a2SQu Wenruo 	return ret;
59577bf40a2SQu Wenruo }
59677bf40a2SQu Wenruo 
597371cdc07SQu Wenruo static int validate_subpage_buffer(struct page *page, u64 start, u64 end,
598947a6299SQu Wenruo 				   int mirror, struct btrfs_tree_parent_check *check)
599371cdc07SQu Wenruo {
600371cdc07SQu Wenruo 	struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
601371cdc07SQu Wenruo 	struct extent_buffer *eb;
602371cdc07SQu Wenruo 	bool reads_done;
603371cdc07SQu Wenruo 	int ret = 0;
604371cdc07SQu Wenruo 
605947a6299SQu Wenruo 	ASSERT(check);
606947a6299SQu Wenruo 
607371cdc07SQu Wenruo 	/*
608371cdc07SQu Wenruo 	 * We don't allow bio merge for subpage metadata read, so we should
609371cdc07SQu Wenruo 	 * only get one eb for each endio hook.
610371cdc07SQu Wenruo 	 */
611371cdc07SQu Wenruo 	ASSERT(end == start + fs_info->nodesize - 1);
612371cdc07SQu Wenruo 	ASSERT(PagePrivate(page));
613371cdc07SQu Wenruo 
614371cdc07SQu Wenruo 	eb = find_extent_buffer(fs_info, start);
615371cdc07SQu Wenruo 	/*
616371cdc07SQu Wenruo 	 * When we are reading one tree block, eb must have been inserted into
617371cdc07SQu Wenruo 	 * the radix tree. If not, something is wrong.
618371cdc07SQu Wenruo 	 */
619371cdc07SQu Wenruo 	ASSERT(eb);
620371cdc07SQu Wenruo 
621371cdc07SQu Wenruo 	reads_done = atomic_dec_and_test(&eb->io_pages);
622371cdc07SQu Wenruo 	/* Subpage read must finish in page read */
623371cdc07SQu Wenruo 	ASSERT(reads_done);
624371cdc07SQu Wenruo 
625371cdc07SQu Wenruo 	eb->read_mirror = mirror;
626371cdc07SQu Wenruo 	if (test_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags)) {
627371cdc07SQu Wenruo 		ret = -EIO;
628371cdc07SQu Wenruo 		goto err;
629371cdc07SQu Wenruo 	}
630947a6299SQu Wenruo 	ret = validate_extent_buffer(eb, check);
631371cdc07SQu Wenruo 	if (ret < 0)
632371cdc07SQu Wenruo 		goto err;
633371cdc07SQu Wenruo 
634371cdc07SQu Wenruo 	set_extent_buffer_uptodate(eb);
635371cdc07SQu Wenruo 
636371cdc07SQu Wenruo 	free_extent_buffer(eb);
637371cdc07SQu Wenruo 	return ret;
638371cdc07SQu Wenruo err:
639371cdc07SQu Wenruo 	/*
640371cdc07SQu Wenruo 	 * end_bio_extent_readpage decrements io_pages in case of error,
641371cdc07SQu Wenruo 	 * make sure it has something to decrement.
642371cdc07SQu Wenruo 	 */
643371cdc07SQu Wenruo 	atomic_inc(&eb->io_pages);
644371cdc07SQu Wenruo 	clear_extent_buffer_uptodate(eb);
645371cdc07SQu Wenruo 	free_extent_buffer(eb);
646371cdc07SQu Wenruo 	return ret;
647371cdc07SQu Wenruo }
648371cdc07SQu Wenruo 
649c3a3b19bSQu Wenruo int btrfs_validate_metadata_buffer(struct btrfs_bio *bbio,
65077bf40a2SQu Wenruo 				   struct page *page, u64 start, u64 end,
65177bf40a2SQu Wenruo 				   int mirror)
65277bf40a2SQu Wenruo {
65377bf40a2SQu Wenruo 	struct extent_buffer *eb;
65477bf40a2SQu Wenruo 	int ret = 0;
65577bf40a2SQu Wenruo 	int reads_done;
65677bf40a2SQu Wenruo 
65777bf40a2SQu Wenruo 	ASSERT(page->private);
658371cdc07SQu Wenruo 
659fbca46ebSQu Wenruo 	if (btrfs_sb(page->mapping->host->i_sb)->nodesize < PAGE_SIZE)
660947a6299SQu Wenruo 		return validate_subpage_buffer(page, start, end, mirror,
661947a6299SQu Wenruo 					       &bbio->parent_check);
662371cdc07SQu Wenruo 
66377bf40a2SQu Wenruo 	eb = (struct extent_buffer *)page->private;
66477bf40a2SQu Wenruo 
66577bf40a2SQu Wenruo 	/*
66677bf40a2SQu Wenruo 	 * The pending IO might have been the only thing that kept this buffer
66777bf40a2SQu Wenruo 	 * in memory.  Make sure we have a ref for all this other checks
66877bf40a2SQu Wenruo 	 */
66977bf40a2SQu Wenruo 	atomic_inc(&eb->refs);
67077bf40a2SQu Wenruo 
67177bf40a2SQu Wenruo 	reads_done = atomic_dec_and_test(&eb->io_pages);
67277bf40a2SQu Wenruo 	if (!reads_done)
67377bf40a2SQu Wenruo 		goto err;
67477bf40a2SQu Wenruo 
67577bf40a2SQu Wenruo 	eb->read_mirror = mirror;
67677bf40a2SQu Wenruo 	if (test_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags)) {
67777bf40a2SQu Wenruo 		ret = -EIO;
67877bf40a2SQu Wenruo 		goto err;
67977bf40a2SQu Wenruo 	}
680947a6299SQu Wenruo 	ret = validate_extent_buffer(eb, &bbio->parent_check);
681ce9adaa5SChris Mason err:
68253b381b3SDavid Woodhouse 	if (ret) {
68353b381b3SDavid Woodhouse 		/*
68453b381b3SDavid Woodhouse 		 * our io error hook is going to dec the io pages
68553b381b3SDavid Woodhouse 		 * again, we have to make sure it has something
68653b381b3SDavid Woodhouse 		 * to decrement
68753b381b3SDavid Woodhouse 		 */
68853b381b3SDavid Woodhouse 		atomic_inc(&eb->io_pages);
6890b32f4bbSJosef Bacik 		clear_extent_buffer_uptodate(eb);
69053b381b3SDavid Woodhouse 	}
6910b32f4bbSJosef Bacik 	free_extent_buffer(eb);
69277bf40a2SQu Wenruo 
693f188591eSChris Mason 	return ret;
694ce9adaa5SChris Mason }
695ce9adaa5SChris Mason 
6964a69a410SChris Mason static void run_one_async_start(struct btrfs_work *work)
6974a69a410SChris Mason {
6984a69a410SChris Mason 	struct async_submit_bio *async;
6994e4cbee9SChristoph Hellwig 	blk_status_t ret;
7004a69a410SChris Mason 
7014a69a410SChris Mason 	async = container_of(work, struct  async_submit_bio, work);
702ab2072b2SDavid Sterba 	switch (async->submit_cmd) {
703ab2072b2SDavid Sterba 	case WQ_SUBMIT_METADATA:
704ad65ecf3SDavid Sterba 		ret = btree_submit_bio_start(async->bio);
705ab2072b2SDavid Sterba 		break;
706ab2072b2SDavid Sterba 	case WQ_SUBMIT_DATA:
707882681acSDavid Sterba 		ret = btrfs_submit_bio_start(async->inode, async->bio);
708ab2072b2SDavid Sterba 		break;
709ab2072b2SDavid Sterba 	case WQ_SUBMIT_DATA_DIO:
710bfa17066SDavid Sterba 		ret = btrfs_submit_bio_start_direct_io(async->inode,
711da67daabSDavid Sterba 				async->bio, async->dio_file_offset);
712ab2072b2SDavid Sterba 		break;
713ab2072b2SDavid Sterba 	}
71479787eaaSJeff Mahoney 	if (ret)
7154e4cbee9SChristoph Hellwig 		async->status = ret;
7164a69a410SChris Mason }
7174a69a410SChris Mason 
71806ea01b1SDavid Sterba /*
71906ea01b1SDavid Sterba  * In order to insert checksums into the metadata in large chunks, we wait
72006ea01b1SDavid Sterba  * until bio submission time.   All the pages in the bio are checksummed and
72106ea01b1SDavid Sterba  * sums are attached onto the ordered extent record.
72206ea01b1SDavid Sterba  *
72306ea01b1SDavid Sterba  * At IO completion time the csums attached on the ordered extent record are
72406ea01b1SDavid Sterba  * inserted into the tree.
72506ea01b1SDavid Sterba  */
7264a69a410SChris Mason static void run_one_async_done(struct btrfs_work *work)
7278b712842SChris Mason {
728917f32a2SChristoph Hellwig 	struct async_submit_bio *async =
729917f32a2SChristoph Hellwig 		container_of(work, struct  async_submit_bio, work);
730da67daabSDavid Sterba 	struct btrfs_inode *inode = async->inode;
731917f32a2SChristoph Hellwig 	struct btrfs_bio *bbio = btrfs_bio(async->bio);
7324854ddd0SChris Mason 
733bb7ab3b9SAdam Buchbinder 	/* If an error occurred we just want to clean up the bio and move on */
7344e4cbee9SChristoph Hellwig 	if (async->status) {
735917f32a2SChristoph Hellwig 		btrfs_bio_end_io(bbio, async->status);
73679787eaaSJeff Mahoney 		return;
73779787eaaSJeff Mahoney 	}
73879787eaaSJeff Mahoney 
739ec39f769SChris Mason 	/*
740ec39f769SChris Mason 	 * All of the bios that pass through here are from async helpers.
741ec39f769SChris Mason 	 * Use REQ_CGROUP_PUNT to issue them from the owning cgroup's context.
742ec39f769SChris Mason 	 * This changes nothing when cgroups aren't in use.
743ec39f769SChris Mason 	 */
744ec39f769SChris Mason 	async->bio->bi_opf |= REQ_CGROUP_PUNT;
745da67daabSDavid Sterba 	btrfs_submit_bio(inode->root->fs_info, async->bio, async->mirror_num);
7464a69a410SChris Mason }
7474a69a410SChris Mason 
7484a69a410SChris Mason static void run_one_async_free(struct btrfs_work *work)
7494a69a410SChris Mason {
7504a69a410SChris Mason 	struct async_submit_bio *async;
7514a69a410SChris Mason 
7524a69a410SChris Mason 	async = container_of(work, struct  async_submit_bio, work);
7538b712842SChris Mason 	kfree(async);
7548b712842SChris Mason }
7558b712842SChris Mason 
756ea1f0cedSChristoph Hellwig /*
757ea1f0cedSChristoph Hellwig  * Submit bio to an async queue.
758ea1f0cedSChristoph Hellwig  *
759ea1f0cedSChristoph Hellwig  * Retrun:
760ea1f0cedSChristoph Hellwig  * - true if the work has been succesfuly submitted
761ea1f0cedSChristoph Hellwig  * - false in case of error
762ea1f0cedSChristoph Hellwig  */
7635fcdadc2SDavid Sterba bool btrfs_wq_submit_bio(struct btrfs_inode *inode, struct bio *bio, int mirror_num,
764ab2072b2SDavid Sterba 			 u64 dio_file_offset, enum btrfs_wq_submit_cmd cmd)
76544b8bd7eSChris Mason {
7665fcdadc2SDavid Sterba 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
76744b8bd7eSChris Mason 	struct async_submit_bio *async;
76844b8bd7eSChris Mason 
76944b8bd7eSChris Mason 	async = kmalloc(sizeof(*async), GFP_NOFS);
77044b8bd7eSChris Mason 	if (!async)
771ea1f0cedSChristoph Hellwig 		return false;
77244b8bd7eSChris Mason 
7735fcdadc2SDavid Sterba 	async->inode = inode;
77444b8bd7eSChris Mason 	async->bio = bio;
77544b8bd7eSChris Mason 	async->mirror_num = mirror_num;
776ab2072b2SDavid Sterba 	async->submit_cmd = cmd;
7774a69a410SChris Mason 
778a0cac0ecSOmar Sandoval 	btrfs_init_work(&async->work, run_one_async_start, run_one_async_done,
779a0cac0ecSOmar Sandoval 			run_one_async_free);
7804a69a410SChris Mason 
7811941b64bSQu Wenruo 	async->dio_file_offset = dio_file_offset;
7828c8bee1dSChris Mason 
7834e4cbee9SChristoph Hellwig 	async->status = 0;
78479787eaaSJeff Mahoney 
78567f055c7SChristoph Hellwig 	if (op_is_sync(bio->bi_opf))
786a31b4a43SChristoph Hellwig 		btrfs_queue_work(fs_info->hipri_workers, &async->work);
787a31b4a43SChristoph Hellwig 	else
7885cdc7ad3SQu Wenruo 		btrfs_queue_work(fs_info->workers, &async->work);
789ea1f0cedSChristoph Hellwig 	return true;
79044b8bd7eSChris Mason }
79144b8bd7eSChris Mason 
7924e4cbee9SChristoph Hellwig static blk_status_t btree_csum_one_bio(struct bio *bio)
793ce3ed71aSChris Mason {
7942c30c71bSKent Overstreet 	struct bio_vec *bvec;
795ce3ed71aSChris Mason 	struct btrfs_root *root;
7962b070cfeSChristoph Hellwig 	int ret = 0;
7976dc4f100SMing Lei 	struct bvec_iter_all iter_all;
798ce3ed71aSChris Mason 
799c09abff8SDavid Sterba 	ASSERT(!bio_flagged(bio, BIO_CLONED));
8002b070cfeSChristoph Hellwig 	bio_for_each_segment_all(bvec, bio, iter_all) {
801ce3ed71aSChris Mason 		root = BTRFS_I(bvec->bv_page->mapping->host)->root;
802ac303b69SQu Wenruo 		ret = csum_dirty_buffer(root->fs_info, bvec);
80379787eaaSJeff Mahoney 		if (ret)
80479787eaaSJeff Mahoney 			break;
805ce3ed71aSChris Mason 	}
8062c30c71bSKent Overstreet 
8074e4cbee9SChristoph Hellwig 	return errno_to_blk_status(ret);
808ce3ed71aSChris Mason }
809ce3ed71aSChris Mason 
810ad65ecf3SDavid Sterba blk_status_t btree_submit_bio_start(struct bio *bio)
81122c59948SChris Mason {
8128b712842SChris Mason 	/*
8138b712842SChris Mason 	 * when we're called for a write, we're already in the async
8141a722d8fSChristoph Hellwig 	 * submission context.  Just jump into btrfs_submit_bio.
8158b712842SChris Mason 	 */
81679787eaaSJeff Mahoney 	return btree_csum_one_bio(bio);
81722c59948SChris Mason }
81822c59948SChris Mason 
819f4dcfb30SJohannes Thumshirn static bool should_async_write(struct btrfs_fs_info *fs_info,
8209b4e675aSDavid Sterba 			     struct btrfs_inode *bi)
821de0022b9SJosef Bacik {
8224eef29efSNaohiro Aota 	if (btrfs_is_zoned(fs_info))
823f4dcfb30SJohannes Thumshirn 		return false;
8246300463bSLiu Bo 	if (atomic_read(&bi->sync_writers))
825f4dcfb30SJohannes Thumshirn 		return false;
8269b4e675aSDavid Sterba 	if (test_bit(BTRFS_FS_CSUM_IMPL_FAST, &fs_info->flags))
827f4dcfb30SJohannes Thumshirn 		return false;
828f4dcfb30SJohannes Thumshirn 	return true;
829de0022b9SJosef Bacik }
830de0022b9SJosef Bacik 
831644094fdSDavid Sterba void btrfs_submit_metadata_bio(struct btrfs_inode *inode, struct bio *bio, int mirror_num)
83244b8bd7eSChris Mason {
833644094fdSDavid Sterba 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
834917f32a2SChristoph Hellwig 	struct btrfs_bio *bbio = btrfs_bio(bio);
8354e4cbee9SChristoph Hellwig 	blk_status_t ret;
836cad321adSChris Mason 
83708a6f464SChristoph Hellwig 	bio->bi_opf |= REQ_META;
838947a6299SQu Wenruo 	bbio->is_metadata = 1;
83908a6f464SChristoph Hellwig 
840cfe94440SNaohiro Aota 	if (btrfs_op(bio) != BTRFS_MAP_WRITE) {
8411a722d8fSChristoph Hellwig 		btrfs_submit_bio(fs_info, bio, mirror_num);
8421a722d8fSChristoph Hellwig 		return;
84344b8bd7eSChris Mason 	}
84444b8bd7eSChris Mason 
845ea1f0cedSChristoph Hellwig 	/*
846ea1f0cedSChristoph Hellwig 	 * Kthread helpers are used to submit writes so that checksumming can
847ea1f0cedSChristoph Hellwig 	 * happen in parallel across all CPUs.
848ea1f0cedSChristoph Hellwig 	 */
849644094fdSDavid Sterba 	if (should_async_write(fs_info, inode) &&
850644094fdSDavid Sterba 	    btrfs_wq_submit_bio(inode, bio, mirror_num, 0, WQ_SUBMIT_METADATA))
851ea1f0cedSChristoph Hellwig 		return;
852ea1f0cedSChristoph Hellwig 
853ea1f0cedSChristoph Hellwig 	ret = btree_csum_one_bio(bio);
85494d9e11bSChristoph Hellwig 	if (ret) {
855917f32a2SChristoph Hellwig 		btrfs_bio_end_io(bbio, ret);
856ea1f0cedSChristoph Hellwig 		return;
85794d9e11bSChristoph Hellwig 	}
858ea1f0cedSChristoph Hellwig 
859ea1f0cedSChristoph Hellwig 	btrfs_submit_bio(fs_info, bio, mirror_num);
86061891923SStefan Behrens }
86161891923SStefan Behrens 
8623dd1462eSJan Beulich #ifdef CONFIG_MIGRATION
8638958b551SMatthew Wilcox (Oracle) static int btree_migrate_folio(struct address_space *mapping,
8648958b551SMatthew Wilcox (Oracle) 		struct folio *dst, struct folio *src, enum migrate_mode mode)
865784b4e29SChris Mason {
866784b4e29SChris Mason 	/*
867784b4e29SChris Mason 	 * we can't safely write a btree page from here,
868784b4e29SChris Mason 	 * we haven't done the locking hook
869784b4e29SChris Mason 	 */
8708958b551SMatthew Wilcox (Oracle) 	if (folio_test_dirty(src))
871784b4e29SChris Mason 		return -EAGAIN;
872784b4e29SChris Mason 	/*
873784b4e29SChris Mason 	 * Buffers may be managed in a filesystem specific way.
874784b4e29SChris Mason 	 * We must have no buffers or drop them.
875784b4e29SChris Mason 	 */
8768958b551SMatthew Wilcox (Oracle) 	if (folio_get_private(src) &&
8778958b551SMatthew Wilcox (Oracle) 	    !filemap_release_folio(src, GFP_KERNEL))
878784b4e29SChris Mason 		return -EAGAIN;
87954184650SMatthew Wilcox (Oracle) 	return migrate_folio(mapping, dst, src, mode);
880784b4e29SChris Mason }
8818958b551SMatthew Wilcox (Oracle) #else
8828958b551SMatthew Wilcox (Oracle) #define btree_migrate_folio NULL
8833dd1462eSJan Beulich #endif
884784b4e29SChris Mason 
8850da5468fSChris Mason static int btree_writepages(struct address_space *mapping,
8860da5468fSChris Mason 			    struct writeback_control *wbc)
8870da5468fSChris Mason {
888e2d84521SMiao Xie 	struct btrfs_fs_info *fs_info;
889e2d84521SMiao Xie 	int ret;
890e2d84521SMiao Xie 
891d8d5f3e1SChris Mason 	if (wbc->sync_mode == WB_SYNC_NONE) {
892448d640bSChris Mason 
893448d640bSChris Mason 		if (wbc->for_kupdate)
894448d640bSChris Mason 			return 0;
895448d640bSChris Mason 
896e2d84521SMiao Xie 		fs_info = BTRFS_I(mapping->host)->root->fs_info;
897b9473439SChris Mason 		/* this is a bit racy, but that's ok */
898d814a491SEthan Lien 		ret = __percpu_counter_compare(&fs_info->dirty_metadata_bytes,
899d814a491SEthan Lien 					     BTRFS_DIRTY_METADATA_THRESH,
900d814a491SEthan Lien 					     fs_info->dirty_metadata_batch);
901e2d84521SMiao Xie 		if (ret < 0)
902793955bcSChris Mason 			return 0;
903793955bcSChris Mason 	}
9040b32f4bbSJosef Bacik 	return btree_write_cache_pages(mapping, wbc);
9050da5468fSChris Mason }
9060da5468fSChris Mason 
907f913cff3SMatthew Wilcox (Oracle) static bool btree_release_folio(struct folio *folio, gfp_t gfp_flags)
9085f39d397SChris Mason {
909f913cff3SMatthew Wilcox (Oracle) 	if (folio_test_writeback(folio) || folio_test_dirty(folio))
910f913cff3SMatthew Wilcox (Oracle) 		return false;
9110c4e538bSDavid Sterba 
912f913cff3SMatthew Wilcox (Oracle) 	return try_release_extent_buffer(&folio->page);
913d98237b3SChris Mason }
914d98237b3SChris Mason 
915895586ebSMatthew Wilcox (Oracle) static void btree_invalidate_folio(struct folio *folio, size_t offset,
916895586ebSMatthew Wilcox (Oracle) 				 size_t length)
917d98237b3SChris Mason {
918d1310b2eSChris Mason 	struct extent_io_tree *tree;
919895586ebSMatthew Wilcox (Oracle) 	tree = &BTRFS_I(folio->mapping->host)->io_tree;
920895586ebSMatthew Wilcox (Oracle) 	extent_invalidate_folio(tree, folio, offset);
921f913cff3SMatthew Wilcox (Oracle) 	btree_release_folio(folio, GFP_NOFS);
922895586ebSMatthew Wilcox (Oracle) 	if (folio_get_private(folio)) {
923895586ebSMatthew Wilcox (Oracle) 		btrfs_warn(BTRFS_I(folio->mapping->host)->root->fs_info,
924895586ebSMatthew Wilcox (Oracle) 			   "folio private not zero on folio %llu",
925895586ebSMatthew Wilcox (Oracle) 			   (unsigned long long)folio_pos(folio));
926895586ebSMatthew Wilcox (Oracle) 		folio_detach_private(folio);
9279ad6b7bcSChris Mason 	}
928d98237b3SChris Mason }
929d98237b3SChris Mason 
930bb146eb2SJosef Bacik #ifdef DEBUG
9310079c3b1SMatthew Wilcox (Oracle) static bool btree_dirty_folio(struct address_space *mapping,
9320079c3b1SMatthew Wilcox (Oracle) 		struct folio *folio)
9330079c3b1SMatthew Wilcox (Oracle) {
9340079c3b1SMatthew Wilcox (Oracle) 	struct btrfs_fs_info *fs_info = btrfs_sb(mapping->host->i_sb);
935139e8cd3SQu Wenruo 	struct btrfs_subpage *subpage;
9360b32f4bbSJosef Bacik 	struct extent_buffer *eb;
937139e8cd3SQu Wenruo 	int cur_bit = 0;
9380079c3b1SMatthew Wilcox (Oracle) 	u64 page_start = folio_pos(folio);
9390b32f4bbSJosef Bacik 
940139e8cd3SQu Wenruo 	if (fs_info->sectorsize == PAGE_SIZE) {
9410079c3b1SMatthew Wilcox (Oracle) 		eb = folio_get_private(folio);
9420b32f4bbSJosef Bacik 		BUG_ON(!eb);
9430b32f4bbSJosef Bacik 		BUG_ON(!test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
9440b32f4bbSJosef Bacik 		BUG_ON(!atomic_read(&eb->refs));
94549d0c642SFilipe Manana 		btrfs_assert_tree_write_locked(eb);
9460079c3b1SMatthew Wilcox (Oracle) 		return filemap_dirty_folio(mapping, folio);
947139e8cd3SQu Wenruo 	}
9480079c3b1SMatthew Wilcox (Oracle) 	subpage = folio_get_private(folio);
949139e8cd3SQu Wenruo 
950139e8cd3SQu Wenruo 	ASSERT(subpage->dirty_bitmap);
951139e8cd3SQu Wenruo 	while (cur_bit < BTRFS_SUBPAGE_BITMAP_SIZE) {
952139e8cd3SQu Wenruo 		unsigned long flags;
953139e8cd3SQu Wenruo 		u64 cur;
954139e8cd3SQu Wenruo 		u16 tmp = (1 << cur_bit);
955139e8cd3SQu Wenruo 
956139e8cd3SQu Wenruo 		spin_lock_irqsave(&subpage->lock, flags);
957139e8cd3SQu Wenruo 		if (!(tmp & subpage->dirty_bitmap)) {
958139e8cd3SQu Wenruo 			spin_unlock_irqrestore(&subpage->lock, flags);
959139e8cd3SQu Wenruo 			cur_bit++;
960139e8cd3SQu Wenruo 			continue;
961139e8cd3SQu Wenruo 		}
962139e8cd3SQu Wenruo 		spin_unlock_irqrestore(&subpage->lock, flags);
963139e8cd3SQu Wenruo 		cur = page_start + cur_bit * fs_info->sectorsize;
964139e8cd3SQu Wenruo 
965139e8cd3SQu Wenruo 		eb = find_extent_buffer(fs_info, cur);
966139e8cd3SQu Wenruo 		ASSERT(eb);
967139e8cd3SQu Wenruo 		ASSERT(test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
968139e8cd3SQu Wenruo 		ASSERT(atomic_read(&eb->refs));
96949d0c642SFilipe Manana 		btrfs_assert_tree_write_locked(eb);
970139e8cd3SQu Wenruo 		free_extent_buffer(eb);
971139e8cd3SQu Wenruo 
972139e8cd3SQu Wenruo 		cur_bit += (fs_info->nodesize >> fs_info->sectorsize_bits);
973139e8cd3SQu Wenruo 	}
9740079c3b1SMatthew Wilcox (Oracle) 	return filemap_dirty_folio(mapping, folio);
9750b32f4bbSJosef Bacik }
9760079c3b1SMatthew Wilcox (Oracle) #else
9770079c3b1SMatthew Wilcox (Oracle) #define btree_dirty_folio filemap_dirty_folio
9780079c3b1SMatthew Wilcox (Oracle) #endif
9790b32f4bbSJosef Bacik 
9807f09410bSAlexey Dobriyan static const struct address_space_operations btree_aops = {
9810da5468fSChris Mason 	.writepages	= btree_writepages,
982f913cff3SMatthew Wilcox (Oracle) 	.release_folio	= btree_release_folio,
983895586ebSMatthew Wilcox (Oracle) 	.invalidate_folio = btree_invalidate_folio,
9848958b551SMatthew Wilcox (Oracle) 	.migrate_folio	= btree_migrate_folio,
9850079c3b1SMatthew Wilcox (Oracle) 	.dirty_folio	= btree_dirty_folio,
986d98237b3SChris Mason };
987123abc88SChris Mason 
9882ff7e61eSJeff Mahoney struct extent_buffer *btrfs_find_create_tree_block(
9892ff7e61eSJeff Mahoney 						struct btrfs_fs_info *fs_info,
9903fbaf258SJosef Bacik 						u64 bytenr, u64 owner_root,
9913fbaf258SJosef Bacik 						int level)
9920999df54SChris Mason {
9930b246afaSJeff Mahoney 	if (btrfs_is_testing(fs_info))
9940b246afaSJeff Mahoney 		return alloc_test_extent_buffer(fs_info, bytenr);
9953fbaf258SJosef Bacik 	return alloc_extent_buffer(fs_info, bytenr, owner_root, level);
9960999df54SChris Mason }
9970999df54SChris Mason 
998581c1760SQu Wenruo /*
999581c1760SQu Wenruo  * Read tree block at logical address @bytenr and do variant basic but critical
1000581c1760SQu Wenruo  * verification.
1001581c1760SQu Wenruo  *
1002789d6a3aSQu Wenruo  * @check:		expected tree parentness check, see comments of the
1003789d6a3aSQu Wenruo  *			structure for details.
1004581c1760SQu Wenruo  */
10052ff7e61eSJeff Mahoney struct extent_buffer *read_tree_block(struct btrfs_fs_info *fs_info, u64 bytenr,
1006789d6a3aSQu Wenruo 				      struct btrfs_tree_parent_check *check)
1007e20d96d6SChris Mason {
10085f39d397SChris Mason 	struct extent_buffer *buf = NULL;
100919c00ddcSChris Mason 	int ret;
101019c00ddcSChris Mason 
1011789d6a3aSQu Wenruo 	ASSERT(check);
1012789d6a3aSQu Wenruo 
1013789d6a3aSQu Wenruo 	buf = btrfs_find_create_tree_block(fs_info, bytenr, check->owner_root,
1014789d6a3aSQu Wenruo 					   check->level);
1015c871b0f2SLiu Bo 	if (IS_ERR(buf))
1016c871b0f2SLiu Bo 		return buf;
1017e4204dedSChris Mason 
1018789d6a3aSQu Wenruo 	ret = btrfs_read_extent_buffer(buf, check);
10190f0fe8f7SFilipe David Borba Manana 	if (ret) {
1020537f38f0SNikolay Borisov 		free_extent_buffer_stale(buf);
102164c043deSLiu Bo 		return ERR_PTR(ret);
10220f0fe8f7SFilipe David Borba Manana 	}
1023789d6a3aSQu Wenruo 	if (btrfs_check_eb_owner(buf, check->owner_root)) {
102488c602abSQu Wenruo 		free_extent_buffer_stale(buf);
102588c602abSQu Wenruo 		return ERR_PTR(-EUCLEAN);
102688c602abSQu Wenruo 	}
10275f39d397SChris Mason 	return buf;
1028ce9adaa5SChris Mason 
1029eb60ceacSChris Mason }
1030eb60ceacSChris Mason 
10316a884d7dSDavid Sterba void btrfs_clean_tree_block(struct extent_buffer *buf)
1032ed2ff2cbSChris Mason {
10336a884d7dSDavid Sterba 	struct btrfs_fs_info *fs_info = buf->fs_info;
103455c69072SChris Mason 	if (btrfs_header_generation(buf) ==
1035e2d84521SMiao Xie 	    fs_info->running_transaction->transid) {
103649d0c642SFilipe Manana 		btrfs_assert_tree_write_locked(buf);
1037b4ce94deSChris Mason 
1038b9473439SChris Mason 		if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &buf->bflags)) {
1039104b4e51SNikolay Borisov 			percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
1040e2d84521SMiao Xie 						 -buf->len,
1041e2d84521SMiao Xie 						 fs_info->dirty_metadata_batch);
10420b32f4bbSJosef Bacik 			clear_extent_buffer_dirty(buf);
1043925baeddSChris Mason 		}
10445f39d397SChris Mason 	}
1045ed7b63ebSJosef Bacik }
10465f39d397SChris Mason 
1047da17066cSJeff Mahoney static void __setup_root(struct btrfs_root *root, struct btrfs_fs_info *fs_info,
1048e20d96d6SChris Mason 			 u64 objectid)
1049d97e63b6SChris Mason {
10507c0260eeSJeff Mahoney 	bool dummy = test_bit(BTRFS_FS_STATE_DUMMY_FS_INFO, &fs_info->fs_state);
10512e608bd1SJosef Bacik 
10522e608bd1SJosef Bacik 	memset(&root->root_key, 0, sizeof(root->root_key));
10532e608bd1SJosef Bacik 	memset(&root->root_item, 0, sizeof(root->root_item));
10542e608bd1SJosef Bacik 	memset(&root->defrag_progress, 0, sizeof(root->defrag_progress));
105596dfcb46SJosef Bacik 	root->fs_info = fs_info;
10562e608bd1SJosef Bacik 	root->root_key.objectid = objectid;
1057cfaa7295SChris Mason 	root->node = NULL;
1058a28ec197SChris Mason 	root->commit_root = NULL;
105927cdeb70SMiao Xie 	root->state = 0;
1060abed4aaaSJosef Bacik 	RB_CLEAR_NODE(&root->rb_node);
10610b86a832SChris Mason 
10620f7d52f4SChris Mason 	root->last_trans = 0;
10636b8fad57SNikolay Borisov 	root->free_objectid = 0;
1064eb73c1b7SMiao Xie 	root->nr_delalloc_inodes = 0;
1065199c2a9cSMiao Xie 	root->nr_ordered_extents = 0;
10666bef4d31SEric Paris 	root->inode_tree = RB_ROOT;
1067088aea3bSDavid Sterba 	INIT_RADIX_TREE(&root->delayed_nodes_tree, GFP_ATOMIC);
10682e608bd1SJosef Bacik 
10692e608bd1SJosef Bacik 	btrfs_init_root_block_rsv(root);
10700b86a832SChris Mason 
10710b86a832SChris Mason 	INIT_LIST_HEAD(&root->dirty_list);
10725d4f98a2SYan Zheng 	INIT_LIST_HEAD(&root->root_list);
1073eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&root->delalloc_inodes);
1074eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&root->delalloc_root);
1075199c2a9cSMiao Xie 	INIT_LIST_HEAD(&root->ordered_extents);
1076199c2a9cSMiao Xie 	INIT_LIST_HEAD(&root->ordered_root);
1077d2311e69SQu Wenruo 	INIT_LIST_HEAD(&root->reloc_dirty_list);
10782ab28f32SJosef Bacik 	INIT_LIST_HEAD(&root->logged_list[0]);
10792ab28f32SJosef Bacik 	INIT_LIST_HEAD(&root->logged_list[1]);
10805d4f98a2SYan Zheng 	spin_lock_init(&root->inode_lock);
1081eb73c1b7SMiao Xie 	spin_lock_init(&root->delalloc_lock);
1082199c2a9cSMiao Xie 	spin_lock_init(&root->ordered_extent_lock);
1083f0486c68SYan, Zheng 	spin_lock_init(&root->accounting_lock);
10842ab28f32SJosef Bacik 	spin_lock_init(&root->log_extents_lock[0]);
10852ab28f32SJosef Bacik 	spin_lock_init(&root->log_extents_lock[1]);
10868287475aSQu Wenruo 	spin_lock_init(&root->qgroup_meta_rsv_lock);
1087a2135011SChris Mason 	mutex_init(&root->objectid_mutex);
1088e02119d5SChris Mason 	mutex_init(&root->log_mutex);
108931f3d255SMiao Xie 	mutex_init(&root->ordered_extent_mutex);
1090573bfb72SMiao Xie 	mutex_init(&root->delalloc_mutex);
1091c53e9653SQu Wenruo 	init_waitqueue_head(&root->qgroup_flush_wait);
10927237f183SYan Zheng 	init_waitqueue_head(&root->log_writer_wait);
10937237f183SYan Zheng 	init_waitqueue_head(&root->log_commit_wait[0]);
10947237f183SYan Zheng 	init_waitqueue_head(&root->log_commit_wait[1]);
10958b050d35SMiao Xie 	INIT_LIST_HEAD(&root->log_ctxs[0]);
10968b050d35SMiao Xie 	INIT_LIST_HEAD(&root->log_ctxs[1]);
10977237f183SYan Zheng 	atomic_set(&root->log_commit[0], 0);
10987237f183SYan Zheng 	atomic_set(&root->log_commit[1], 0);
10997237f183SYan Zheng 	atomic_set(&root->log_writers, 0);
11002ecb7923SMiao Xie 	atomic_set(&root->log_batch, 0);
11010700cea7SElena Reshetova 	refcount_set(&root->refs, 1);
11028ecebf4dSRobbie Ko 	atomic_set(&root->snapshot_force_cow, 0);
1103eede2bf3SOmar Sandoval 	atomic_set(&root->nr_swapfiles, 0);
11047237f183SYan Zheng 	root->log_transid = 0;
1105d1433debSMiao Xie 	root->log_transid_committed = -1;
1106257c62e1SChris Mason 	root->last_log_commit = 0;
11072e608bd1SJosef Bacik 	root->anon_dev = 0;
1108e289f03eSFilipe Manana 	if (!dummy) {
110943eb5f29SQu Wenruo 		extent_io_tree_init(fs_info, &root->dirty_log_pages,
111035da5a7eSDavid Sterba 				    IO_TREE_ROOT_DIRTY_LOG_PAGES);
1111e289f03eSFilipe Manana 		extent_io_tree_init(fs_info, &root->log_csum_range,
111235da5a7eSDavid Sterba 				    IO_TREE_LOG_CSUM_RANGE);
1113e289f03eSFilipe Manana 	}
1114017e5369SChris Mason 
11155f3ab90aSAnand Jain 	spin_lock_init(&root->root_item_lock);
1116370a11b8SQu Wenruo 	btrfs_qgroup_init_swapped_blocks(&root->swapped_blocks);
1117bd647ce3SJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
1118bd647ce3SJosef Bacik 	INIT_LIST_HEAD(&root->leak_list);
1119fc7cbcd4SDavid Sterba 	spin_lock(&fs_info->fs_roots_radix_lock);
1120bd647ce3SJosef Bacik 	list_add_tail(&root->leak_list, &fs_info->allocated_roots);
1121fc7cbcd4SDavid Sterba 	spin_unlock(&fs_info->fs_roots_radix_lock);
1122bd647ce3SJosef Bacik #endif
11233768f368SChris Mason }
11243768f368SChris Mason 
112574e4d827SDavid Sterba static struct btrfs_root *btrfs_alloc_root(struct btrfs_fs_info *fs_info,
112696dfcb46SJosef Bacik 					   u64 objectid, gfp_t flags)
11276f07e42eSAl Viro {
112874e4d827SDavid Sterba 	struct btrfs_root *root = kzalloc(sizeof(*root), flags);
11296f07e42eSAl Viro 	if (root)
113096dfcb46SJosef Bacik 		__setup_root(root, fs_info, objectid);
11316f07e42eSAl Viro 	return root;
11326f07e42eSAl Viro }
11336f07e42eSAl Viro 
113406ea65a3SJosef Bacik #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
113506ea65a3SJosef Bacik /* Should only be used by the testing infrastructure */
1136da17066cSJeff Mahoney struct btrfs_root *btrfs_alloc_dummy_root(struct btrfs_fs_info *fs_info)
113706ea65a3SJosef Bacik {
113806ea65a3SJosef Bacik 	struct btrfs_root *root;
113906ea65a3SJosef Bacik 
11407c0260eeSJeff Mahoney 	if (!fs_info)
11417c0260eeSJeff Mahoney 		return ERR_PTR(-EINVAL);
11427c0260eeSJeff Mahoney 
114396dfcb46SJosef Bacik 	root = btrfs_alloc_root(fs_info, BTRFS_ROOT_TREE_OBJECTID, GFP_KERNEL);
114406ea65a3SJosef Bacik 	if (!root)
114506ea65a3SJosef Bacik 		return ERR_PTR(-ENOMEM);
1146da17066cSJeff Mahoney 
1147b9ef22deSFeifei Xu 	/* We don't use the stripesize in selftest, set it as sectorsize */
1148faa2dbf0SJosef Bacik 	root->alloc_bytenr = 0;
114906ea65a3SJosef Bacik 
115006ea65a3SJosef Bacik 	return root;
115106ea65a3SJosef Bacik }
115206ea65a3SJosef Bacik #endif
115306ea65a3SJosef Bacik 
1154abed4aaaSJosef Bacik static int global_root_cmp(struct rb_node *a_node, const struct rb_node *b_node)
1155abed4aaaSJosef Bacik {
1156abed4aaaSJosef Bacik 	const struct btrfs_root *a = rb_entry(a_node, struct btrfs_root, rb_node);
1157abed4aaaSJosef Bacik 	const struct btrfs_root *b = rb_entry(b_node, struct btrfs_root, rb_node);
1158abed4aaaSJosef Bacik 
1159abed4aaaSJosef Bacik 	return btrfs_comp_cpu_keys(&a->root_key, &b->root_key);
1160abed4aaaSJosef Bacik }
1161abed4aaaSJosef Bacik 
1162abed4aaaSJosef Bacik static int global_root_key_cmp(const void *k, const struct rb_node *node)
1163abed4aaaSJosef Bacik {
1164abed4aaaSJosef Bacik 	const struct btrfs_key *key = k;
1165abed4aaaSJosef Bacik 	const struct btrfs_root *root = rb_entry(node, struct btrfs_root, rb_node);
1166abed4aaaSJosef Bacik 
1167abed4aaaSJosef Bacik 	return btrfs_comp_cpu_keys(key, &root->root_key);
1168abed4aaaSJosef Bacik }
1169abed4aaaSJosef Bacik 
1170abed4aaaSJosef Bacik int btrfs_global_root_insert(struct btrfs_root *root)
1171abed4aaaSJosef Bacik {
1172abed4aaaSJosef Bacik 	struct btrfs_fs_info *fs_info = root->fs_info;
1173abed4aaaSJosef Bacik 	struct rb_node *tmp;
1174abed4aaaSJosef Bacik 
1175abed4aaaSJosef Bacik 	write_lock(&fs_info->global_root_lock);
1176abed4aaaSJosef Bacik 	tmp = rb_find_add(&root->rb_node, &fs_info->global_root_tree, global_root_cmp);
1177abed4aaaSJosef Bacik 	write_unlock(&fs_info->global_root_lock);
1178abed4aaaSJosef Bacik 	ASSERT(!tmp);
1179abed4aaaSJosef Bacik 
1180abed4aaaSJosef Bacik 	return tmp ? -EEXIST : 0;
1181abed4aaaSJosef Bacik }
1182abed4aaaSJosef Bacik 
1183abed4aaaSJosef Bacik void btrfs_global_root_delete(struct btrfs_root *root)
1184abed4aaaSJosef Bacik {
1185abed4aaaSJosef Bacik 	struct btrfs_fs_info *fs_info = root->fs_info;
1186abed4aaaSJosef Bacik 
1187abed4aaaSJosef Bacik 	write_lock(&fs_info->global_root_lock);
1188abed4aaaSJosef Bacik 	rb_erase(&root->rb_node, &fs_info->global_root_tree);
1189abed4aaaSJosef Bacik 	write_unlock(&fs_info->global_root_lock);
1190abed4aaaSJosef Bacik }
1191abed4aaaSJosef Bacik 
1192abed4aaaSJosef Bacik struct btrfs_root *btrfs_global_root(struct btrfs_fs_info *fs_info,
1193abed4aaaSJosef Bacik 				     struct btrfs_key *key)
1194abed4aaaSJosef Bacik {
1195abed4aaaSJosef Bacik 	struct rb_node *node;
1196abed4aaaSJosef Bacik 	struct btrfs_root *root = NULL;
1197abed4aaaSJosef Bacik 
1198abed4aaaSJosef Bacik 	read_lock(&fs_info->global_root_lock);
1199abed4aaaSJosef Bacik 	node = rb_find(key, &fs_info->global_root_tree, global_root_key_cmp);
1200abed4aaaSJosef Bacik 	if (node)
1201abed4aaaSJosef Bacik 		root = container_of(node, struct btrfs_root, rb_node);
1202abed4aaaSJosef Bacik 	read_unlock(&fs_info->global_root_lock);
1203abed4aaaSJosef Bacik 
1204abed4aaaSJosef Bacik 	return root;
1205abed4aaaSJosef Bacik }
1206abed4aaaSJosef Bacik 
1207f7238e50SJosef Bacik static u64 btrfs_global_root_id(struct btrfs_fs_info *fs_info, u64 bytenr)
1208f7238e50SJosef Bacik {
1209f7238e50SJosef Bacik 	struct btrfs_block_group *block_group;
1210f7238e50SJosef Bacik 	u64 ret;
1211f7238e50SJosef Bacik 
1212f7238e50SJosef Bacik 	if (!btrfs_fs_incompat(fs_info, EXTENT_TREE_V2))
1213f7238e50SJosef Bacik 		return 0;
1214f7238e50SJosef Bacik 
1215f7238e50SJosef Bacik 	if (bytenr)
1216f7238e50SJosef Bacik 		block_group = btrfs_lookup_block_group(fs_info, bytenr);
1217f7238e50SJosef Bacik 	else
1218f7238e50SJosef Bacik 		block_group = btrfs_lookup_first_block_group(fs_info, bytenr);
1219f7238e50SJosef Bacik 	ASSERT(block_group);
1220f7238e50SJosef Bacik 	if (!block_group)
1221f7238e50SJosef Bacik 		return 0;
1222f7238e50SJosef Bacik 	ret = block_group->global_root_id;
1223f7238e50SJosef Bacik 	btrfs_put_block_group(block_group);
1224f7238e50SJosef Bacik 
1225f7238e50SJosef Bacik 	return ret;
1226f7238e50SJosef Bacik }
1227f7238e50SJosef Bacik 
1228abed4aaaSJosef Bacik struct btrfs_root *btrfs_csum_root(struct btrfs_fs_info *fs_info, u64 bytenr)
1229abed4aaaSJosef Bacik {
1230abed4aaaSJosef Bacik 	struct btrfs_key key = {
1231abed4aaaSJosef Bacik 		.objectid = BTRFS_CSUM_TREE_OBJECTID,
1232abed4aaaSJosef Bacik 		.type = BTRFS_ROOT_ITEM_KEY,
1233f7238e50SJosef Bacik 		.offset = btrfs_global_root_id(fs_info, bytenr),
1234abed4aaaSJosef Bacik 	};
1235abed4aaaSJosef Bacik 
1236abed4aaaSJosef Bacik 	return btrfs_global_root(fs_info, &key);
1237abed4aaaSJosef Bacik }
1238abed4aaaSJosef Bacik 
1239abed4aaaSJosef Bacik struct btrfs_root *btrfs_extent_root(struct btrfs_fs_info *fs_info, u64 bytenr)
1240abed4aaaSJosef Bacik {
1241abed4aaaSJosef Bacik 	struct btrfs_key key = {
1242abed4aaaSJosef Bacik 		.objectid = BTRFS_EXTENT_TREE_OBJECTID,
1243abed4aaaSJosef Bacik 		.type = BTRFS_ROOT_ITEM_KEY,
1244f7238e50SJosef Bacik 		.offset = btrfs_global_root_id(fs_info, bytenr),
1245abed4aaaSJosef Bacik 	};
1246abed4aaaSJosef Bacik 
1247abed4aaaSJosef Bacik 	return btrfs_global_root(fs_info, &key);
1248abed4aaaSJosef Bacik }
1249abed4aaaSJosef Bacik 
125051129b33SJosef Bacik struct btrfs_root *btrfs_block_group_root(struct btrfs_fs_info *fs_info)
125151129b33SJosef Bacik {
125251129b33SJosef Bacik 	if (btrfs_fs_compat_ro(fs_info, BLOCK_GROUP_TREE))
125351129b33SJosef Bacik 		return fs_info->block_group_root;
125451129b33SJosef Bacik 	return btrfs_extent_root(fs_info, 0);
125551129b33SJosef Bacik }
125651129b33SJosef Bacik 
125720897f5cSArne Jansen struct btrfs_root *btrfs_create_tree(struct btrfs_trans_handle *trans,
125820897f5cSArne Jansen 				     u64 objectid)
125920897f5cSArne Jansen {
12609b7a2440SDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
126120897f5cSArne Jansen 	struct extent_buffer *leaf;
126220897f5cSArne Jansen 	struct btrfs_root *tree_root = fs_info->tree_root;
126320897f5cSArne Jansen 	struct btrfs_root *root;
126420897f5cSArne Jansen 	struct btrfs_key key;
1265b89f6d1fSFilipe Manana 	unsigned int nofs_flag;
126620897f5cSArne Jansen 	int ret = 0;
126720897f5cSArne Jansen 
1268b89f6d1fSFilipe Manana 	/*
1269b89f6d1fSFilipe Manana 	 * We're holding a transaction handle, so use a NOFS memory allocation
1270b89f6d1fSFilipe Manana 	 * context to avoid deadlock if reclaim happens.
1271b89f6d1fSFilipe Manana 	 */
1272b89f6d1fSFilipe Manana 	nofs_flag = memalloc_nofs_save();
127396dfcb46SJosef Bacik 	root = btrfs_alloc_root(fs_info, objectid, GFP_KERNEL);
1274b89f6d1fSFilipe Manana 	memalloc_nofs_restore(nofs_flag);
127520897f5cSArne Jansen 	if (!root)
127620897f5cSArne Jansen 		return ERR_PTR(-ENOMEM);
127720897f5cSArne Jansen 
127820897f5cSArne Jansen 	root->root_key.objectid = objectid;
127920897f5cSArne Jansen 	root->root_key.type = BTRFS_ROOT_ITEM_KEY;
128020897f5cSArne Jansen 	root->root_key.offset = 0;
128120897f5cSArne Jansen 
12829631e4ccSJosef Bacik 	leaf = btrfs_alloc_tree_block(trans, root, 0, objectid, NULL, 0, 0, 0,
12839631e4ccSJosef Bacik 				      BTRFS_NESTING_NORMAL);
128420897f5cSArne Jansen 	if (IS_ERR(leaf)) {
128520897f5cSArne Jansen 		ret = PTR_ERR(leaf);
12861dd05682STsutomu Itoh 		leaf = NULL;
1287c1b07854SPeng Hao 		goto fail;
128820897f5cSArne Jansen 	}
128920897f5cSArne Jansen 
129020897f5cSArne Jansen 	root->node = leaf;
129120897f5cSArne Jansen 	btrfs_mark_buffer_dirty(leaf);
129220897f5cSArne Jansen 
129320897f5cSArne Jansen 	root->commit_root = btrfs_root_node(root);
129427cdeb70SMiao Xie 	set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
129520897f5cSArne Jansen 
1296f944d2cbSDavid Sterba 	btrfs_set_root_flags(&root->root_item, 0);
1297f944d2cbSDavid Sterba 	btrfs_set_root_limit(&root->root_item, 0);
129820897f5cSArne Jansen 	btrfs_set_root_bytenr(&root->root_item, leaf->start);
129920897f5cSArne Jansen 	btrfs_set_root_generation(&root->root_item, trans->transid);
130020897f5cSArne Jansen 	btrfs_set_root_level(&root->root_item, 0);
130120897f5cSArne Jansen 	btrfs_set_root_refs(&root->root_item, 1);
130220897f5cSArne Jansen 	btrfs_set_root_used(&root->root_item, leaf->len);
130320897f5cSArne Jansen 	btrfs_set_root_last_snapshot(&root->root_item, 0);
130420897f5cSArne Jansen 	btrfs_set_root_dirid(&root->root_item, 0);
130533d85fdaSQu Wenruo 	if (is_fstree(objectid))
1306807fc790SAndy Shevchenko 		generate_random_guid(root->root_item.uuid);
1307807fc790SAndy Shevchenko 	else
1308807fc790SAndy Shevchenko 		export_guid(root->root_item.uuid, &guid_null);
1309c8422684SDavid Sterba 	btrfs_set_root_drop_level(&root->root_item, 0);
131020897f5cSArne Jansen 
13118a6a87cdSBoris Burkov 	btrfs_tree_unlock(leaf);
13128a6a87cdSBoris Burkov 
131320897f5cSArne Jansen 	key.objectid = objectid;
131420897f5cSArne Jansen 	key.type = BTRFS_ROOT_ITEM_KEY;
131520897f5cSArne Jansen 	key.offset = 0;
131620897f5cSArne Jansen 	ret = btrfs_insert_root(trans, tree_root, &key, &root->root_item);
131720897f5cSArne Jansen 	if (ret)
131820897f5cSArne Jansen 		goto fail;
131920897f5cSArne Jansen 
132020897f5cSArne Jansen 	return root;
13211dd05682STsutomu Itoh 
13228a6a87cdSBoris Burkov fail:
132300246528SJosef Bacik 	btrfs_put_root(root);
13241dd05682STsutomu Itoh 
13251dd05682STsutomu Itoh 	return ERR_PTR(ret);
132620897f5cSArne Jansen }
132720897f5cSArne Jansen 
13287237f183SYan Zheng static struct btrfs_root *alloc_log_tree(struct btrfs_trans_handle *trans,
1329e02119d5SChris Mason 					 struct btrfs_fs_info *fs_info)
13300f7d52f4SChris Mason {
13310f7d52f4SChris Mason 	struct btrfs_root *root;
1332e02119d5SChris Mason 
133396dfcb46SJosef Bacik 	root = btrfs_alloc_root(fs_info, BTRFS_TREE_LOG_OBJECTID, GFP_NOFS);
1334e02119d5SChris Mason 	if (!root)
13357237f183SYan Zheng 		return ERR_PTR(-ENOMEM);
1336e02119d5SChris Mason 
1337e02119d5SChris Mason 	root->root_key.objectid = BTRFS_TREE_LOG_OBJECTID;
1338e02119d5SChris Mason 	root->root_key.type = BTRFS_ROOT_ITEM_KEY;
1339e02119d5SChris Mason 	root->root_key.offset = BTRFS_TREE_LOG_OBJECTID;
134027cdeb70SMiao Xie 
13416ab6ebb7SNaohiro Aota 	return root;
13426ab6ebb7SNaohiro Aota }
13436ab6ebb7SNaohiro Aota 
13446ab6ebb7SNaohiro Aota int btrfs_alloc_log_tree_node(struct btrfs_trans_handle *trans,
13456ab6ebb7SNaohiro Aota 			      struct btrfs_root *root)
13466ab6ebb7SNaohiro Aota {
13476ab6ebb7SNaohiro Aota 	struct extent_buffer *leaf;
13486ab6ebb7SNaohiro Aota 
13497237f183SYan Zheng 	/*
135092a7cc42SQu Wenruo 	 * DON'T set SHAREABLE bit for log trees.
135127cdeb70SMiao Xie 	 *
135292a7cc42SQu Wenruo 	 * Log trees are not exposed to user space thus can't be snapshotted,
135392a7cc42SQu Wenruo 	 * and they go away before a real commit is actually done.
135492a7cc42SQu Wenruo 	 *
135592a7cc42SQu Wenruo 	 * They do store pointers to file data extents, and those reference
135692a7cc42SQu Wenruo 	 * counts still get updated (along with back refs to the log tree).
13577237f183SYan Zheng 	 */
1358e02119d5SChris Mason 
13594d75f8a9SDavid Sterba 	leaf = btrfs_alloc_tree_block(trans, root, 0, BTRFS_TREE_LOG_OBJECTID,
13609631e4ccSJosef Bacik 			NULL, 0, 0, 0, BTRFS_NESTING_NORMAL);
13616ab6ebb7SNaohiro Aota 	if (IS_ERR(leaf))
13626ab6ebb7SNaohiro Aota 		return PTR_ERR(leaf);
1363e02119d5SChris Mason 
13647237f183SYan Zheng 	root->node = leaf;
1365e02119d5SChris Mason 
1366e02119d5SChris Mason 	btrfs_mark_buffer_dirty(root->node);
1367e02119d5SChris Mason 	btrfs_tree_unlock(root->node);
13686ab6ebb7SNaohiro Aota 
13696ab6ebb7SNaohiro Aota 	return 0;
13707237f183SYan Zheng }
13717237f183SYan Zheng 
13727237f183SYan Zheng int btrfs_init_log_root_tree(struct btrfs_trans_handle *trans,
13737237f183SYan Zheng 			     struct btrfs_fs_info *fs_info)
13747237f183SYan Zheng {
13757237f183SYan Zheng 	struct btrfs_root *log_root;
13767237f183SYan Zheng 
13777237f183SYan Zheng 	log_root = alloc_log_tree(trans, fs_info);
13787237f183SYan Zheng 	if (IS_ERR(log_root))
13797237f183SYan Zheng 		return PTR_ERR(log_root);
13806ab6ebb7SNaohiro Aota 
13813ddebf27SNaohiro Aota 	if (!btrfs_is_zoned(fs_info)) {
13823ddebf27SNaohiro Aota 		int ret = btrfs_alloc_log_tree_node(trans, log_root);
13833ddebf27SNaohiro Aota 
13846ab6ebb7SNaohiro Aota 		if (ret) {
13856ab6ebb7SNaohiro Aota 			btrfs_put_root(log_root);
13866ab6ebb7SNaohiro Aota 			return ret;
13876ab6ebb7SNaohiro Aota 		}
13883ddebf27SNaohiro Aota 	}
13896ab6ebb7SNaohiro Aota 
13907237f183SYan Zheng 	WARN_ON(fs_info->log_root_tree);
13917237f183SYan Zheng 	fs_info->log_root_tree = log_root;
13927237f183SYan Zheng 	return 0;
13937237f183SYan Zheng }
13947237f183SYan Zheng 
13957237f183SYan Zheng int btrfs_add_log_tree(struct btrfs_trans_handle *trans,
13967237f183SYan Zheng 		       struct btrfs_root *root)
13977237f183SYan Zheng {
13980b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
13997237f183SYan Zheng 	struct btrfs_root *log_root;
14007237f183SYan Zheng 	struct btrfs_inode_item *inode_item;
14016ab6ebb7SNaohiro Aota 	int ret;
14027237f183SYan Zheng 
14030b246afaSJeff Mahoney 	log_root = alloc_log_tree(trans, fs_info);
14047237f183SYan Zheng 	if (IS_ERR(log_root))
14057237f183SYan Zheng 		return PTR_ERR(log_root);
14067237f183SYan Zheng 
14076ab6ebb7SNaohiro Aota 	ret = btrfs_alloc_log_tree_node(trans, log_root);
14086ab6ebb7SNaohiro Aota 	if (ret) {
14096ab6ebb7SNaohiro Aota 		btrfs_put_root(log_root);
14106ab6ebb7SNaohiro Aota 		return ret;
14116ab6ebb7SNaohiro Aota 	}
14126ab6ebb7SNaohiro Aota 
14137237f183SYan Zheng 	log_root->last_trans = trans->transid;
14147237f183SYan Zheng 	log_root->root_key.offset = root->root_key.objectid;
14157237f183SYan Zheng 
14167237f183SYan Zheng 	inode_item = &log_root->root_item.inode;
14173cae210fSQu Wenruo 	btrfs_set_stack_inode_generation(inode_item, 1);
14183cae210fSQu Wenruo 	btrfs_set_stack_inode_size(inode_item, 3);
14193cae210fSQu Wenruo 	btrfs_set_stack_inode_nlink(inode_item, 1);
1420da17066cSJeff Mahoney 	btrfs_set_stack_inode_nbytes(inode_item,
14210b246afaSJeff Mahoney 				     fs_info->nodesize);
14223cae210fSQu Wenruo 	btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
14237237f183SYan Zheng 
14245d4f98a2SYan Zheng 	btrfs_set_root_node(&log_root->root_item, log_root->node);
14257237f183SYan Zheng 
14267237f183SYan Zheng 	WARN_ON(root->log_root);
14277237f183SYan Zheng 	root->log_root = log_root;
14287237f183SYan Zheng 	root->log_transid = 0;
1429d1433debSMiao Xie 	root->log_transid_committed = -1;
1430257c62e1SChris Mason 	root->last_log_commit = 0;
1431e02119d5SChris Mason 	return 0;
1432e02119d5SChris Mason }
1433e02119d5SChris Mason 
143449d11beaSJosef Bacik static struct btrfs_root *read_tree_root_path(struct btrfs_root *tree_root,
143549d11beaSJosef Bacik 					      struct btrfs_path *path,
1436cb517eabSMiao Xie 					      struct btrfs_key *key)
1437e02119d5SChris Mason {
1438e02119d5SChris Mason 	struct btrfs_root *root;
1439789d6a3aSQu Wenruo 	struct btrfs_tree_parent_check check = { 0 };
1440e02119d5SChris Mason 	struct btrfs_fs_info *fs_info = tree_root->fs_info;
144184234f3aSYan Zheng 	u64 generation;
1442cb517eabSMiao Xie 	int ret;
1443581c1760SQu Wenruo 	int level;
1444cb517eabSMiao Xie 
144596dfcb46SJosef Bacik 	root = btrfs_alloc_root(fs_info, key->objectid, GFP_NOFS);
144649d11beaSJosef Bacik 	if (!root)
144749d11beaSJosef Bacik 		return ERR_PTR(-ENOMEM);
14480f7d52f4SChris Mason 
1449cb517eabSMiao Xie 	ret = btrfs_find_root(tree_root, key, path,
1450cb517eabSMiao Xie 			      &root->root_item, &root->root_key);
14510f7d52f4SChris Mason 	if (ret) {
145213a8a7c8SYan, Zheng 		if (ret > 0)
145313a8a7c8SYan, Zheng 			ret = -ENOENT;
145449d11beaSJosef Bacik 		goto fail;
14550f7d52f4SChris Mason 	}
145613a8a7c8SYan, Zheng 
145784234f3aSYan Zheng 	generation = btrfs_root_generation(&root->root_item);
1458581c1760SQu Wenruo 	level = btrfs_root_level(&root->root_item);
1459789d6a3aSQu Wenruo 	check.level = level;
1460789d6a3aSQu Wenruo 	check.transid = generation;
1461789d6a3aSQu Wenruo 	check.owner_root = key->objectid;
1462789d6a3aSQu Wenruo 	root->node = read_tree_block(fs_info, btrfs_root_bytenr(&root->root_item),
1463789d6a3aSQu Wenruo 				     &check);
146464c043deSLiu Bo 	if (IS_ERR(root->node)) {
146564c043deSLiu Bo 		ret = PTR_ERR(root->node);
14668c38938cSJosef Bacik 		root->node = NULL;
146749d11beaSJosef Bacik 		goto fail;
14684eb150d6SQu Wenruo 	}
14694eb150d6SQu Wenruo 	if (!btrfs_buffer_uptodate(root->node, generation, 0)) {
1470cb517eabSMiao Xie 		ret = -EIO;
147149d11beaSJosef Bacik 		goto fail;
1472416bc658SJosef Bacik 	}
147388c602abSQu Wenruo 
147488c602abSQu Wenruo 	/*
147588c602abSQu Wenruo 	 * For real fs, and not log/reloc trees, root owner must
147688c602abSQu Wenruo 	 * match its root node owner
147788c602abSQu Wenruo 	 */
147888c602abSQu Wenruo 	if (!test_bit(BTRFS_FS_STATE_DUMMY_FS_INFO, &fs_info->fs_state) &&
147988c602abSQu Wenruo 	    root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID &&
148088c602abSQu Wenruo 	    root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
148188c602abSQu Wenruo 	    root->root_key.objectid != btrfs_header_owner(root->node)) {
148288c602abSQu Wenruo 		btrfs_crit(fs_info,
148388c602abSQu Wenruo "root=%llu block=%llu, tree root owner mismatch, have %llu expect %llu",
148488c602abSQu Wenruo 			   root->root_key.objectid, root->node->start,
148588c602abSQu Wenruo 			   btrfs_header_owner(root->node),
148688c602abSQu Wenruo 			   root->root_key.objectid);
148788c602abSQu Wenruo 		ret = -EUCLEAN;
148888c602abSQu Wenruo 		goto fail;
148988c602abSQu Wenruo 	}
14905d4f98a2SYan Zheng 	root->commit_root = btrfs_root_node(root);
1491cb517eabSMiao Xie 	return root;
149249d11beaSJosef Bacik fail:
149300246528SJosef Bacik 	btrfs_put_root(root);
149449d11beaSJosef Bacik 	return ERR_PTR(ret);
149549d11beaSJosef Bacik }
149649d11beaSJosef Bacik 
149749d11beaSJosef Bacik struct btrfs_root *btrfs_read_tree_root(struct btrfs_root *tree_root,
149849d11beaSJosef Bacik 					struct btrfs_key *key)
149949d11beaSJosef Bacik {
150049d11beaSJosef Bacik 	struct btrfs_root *root;
150149d11beaSJosef Bacik 	struct btrfs_path *path;
150249d11beaSJosef Bacik 
150349d11beaSJosef Bacik 	path = btrfs_alloc_path();
150449d11beaSJosef Bacik 	if (!path)
150549d11beaSJosef Bacik 		return ERR_PTR(-ENOMEM);
150649d11beaSJosef Bacik 	root = read_tree_root_path(tree_root, path, key);
150749d11beaSJosef Bacik 	btrfs_free_path(path);
150849d11beaSJosef Bacik 
150949d11beaSJosef Bacik 	return root;
1510cb517eabSMiao Xie }
1511cb517eabSMiao Xie 
15122dfb1e43SQu Wenruo /*
15132dfb1e43SQu Wenruo  * Initialize subvolume root in-memory structure
15142dfb1e43SQu Wenruo  *
15152dfb1e43SQu Wenruo  * @anon_dev:	anonymous device to attach to the root, if zero, allocate new
15162dfb1e43SQu Wenruo  */
15172dfb1e43SQu Wenruo static int btrfs_init_fs_root(struct btrfs_root *root, dev_t anon_dev)
1518cb517eabSMiao Xie {
1519cb517eabSMiao Xie 	int ret;
1520dcc3eb96SNikolay Borisov 	unsigned int nofs_flag;
1521cb517eabSMiao Xie 
1522dcc3eb96SNikolay Borisov 	/*
1523dcc3eb96SNikolay Borisov 	 * We might be called under a transaction (e.g. indirect backref
1524dcc3eb96SNikolay Borisov 	 * resolution) which could deadlock if it triggers memory reclaim
1525dcc3eb96SNikolay Borisov 	 */
1526dcc3eb96SNikolay Borisov 	nofs_flag = memalloc_nofs_save();
1527dcc3eb96SNikolay Borisov 	ret = btrfs_drew_lock_init(&root->snapshot_lock);
1528dcc3eb96SNikolay Borisov 	memalloc_nofs_restore(nofs_flag);
1529dcc3eb96SNikolay Borisov 	if (ret)
15308257b2dcSMiao Xie 		goto fail;
15318257b2dcSMiao Xie 
1532aeb935a4SQu Wenruo 	if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID &&
153337f00a6dSJohannes Thumshirn 	    !btrfs_is_data_reloc_root(root)) {
153492a7cc42SQu Wenruo 		set_bit(BTRFS_ROOT_SHAREABLE, &root->state);
1535f39e4571SJosef Bacik 		btrfs_check_and_init_root_item(&root->root_item);
1536f39e4571SJosef Bacik 	}
1537f39e4571SJosef Bacik 
1538851fd730SQu Wenruo 	/*
1539851fd730SQu Wenruo 	 * Don't assign anonymous block device to roots that are not exposed to
1540851fd730SQu Wenruo 	 * userspace, the id pool is limited to 1M
1541851fd730SQu Wenruo 	 */
1542851fd730SQu Wenruo 	if (is_fstree(root->root_key.objectid) &&
1543851fd730SQu Wenruo 	    btrfs_root_refs(&root->root_item) > 0) {
15442dfb1e43SQu Wenruo 		if (!anon_dev) {
1545cb517eabSMiao Xie 			ret = get_anon_bdev(&root->anon_dev);
1546cb517eabSMiao Xie 			if (ret)
1547876d2cf1SLiu Bo 				goto fail;
15482dfb1e43SQu Wenruo 		} else {
15492dfb1e43SQu Wenruo 			root->anon_dev = anon_dev;
15502dfb1e43SQu Wenruo 		}
1551851fd730SQu Wenruo 	}
1552f32e48e9SChandan Rajendra 
1553f32e48e9SChandan Rajendra 	mutex_lock(&root->objectid_mutex);
1554453e4873SNikolay Borisov 	ret = btrfs_init_root_free_objectid(root);
1555f32e48e9SChandan Rajendra 	if (ret) {
1556f32e48e9SChandan Rajendra 		mutex_unlock(&root->objectid_mutex);
1557876d2cf1SLiu Bo 		goto fail;
1558f32e48e9SChandan Rajendra 	}
1559f32e48e9SChandan Rajendra 
15606b8fad57SNikolay Borisov 	ASSERT(root->free_objectid <= BTRFS_LAST_FREE_OBJECTID);
1561f32e48e9SChandan Rajendra 
1562f32e48e9SChandan Rajendra 	mutex_unlock(&root->objectid_mutex);
1563f32e48e9SChandan Rajendra 
1564cb517eabSMiao Xie 	return 0;
1565cb517eabSMiao Xie fail:
156684db5ccfSDavid Sterba 	/* The caller is responsible to call btrfs_free_fs_root */
1567cb517eabSMiao Xie 	return ret;
1568cb517eabSMiao Xie }
1569cb517eabSMiao Xie 
1570a98db0f3SJosef Bacik static struct btrfs_root *btrfs_lookup_fs_root(struct btrfs_fs_info *fs_info,
1571cb517eabSMiao Xie 					       u64 root_id)
1572cb517eabSMiao Xie {
1573cb517eabSMiao Xie 	struct btrfs_root *root;
1574cb517eabSMiao Xie 
1575fc7cbcd4SDavid Sterba 	spin_lock(&fs_info->fs_roots_radix_lock);
1576fc7cbcd4SDavid Sterba 	root = radix_tree_lookup(&fs_info->fs_roots_radix,
1577fc7cbcd4SDavid Sterba 				 (unsigned long)root_id);
1578bc44d7c4SJosef Bacik 	if (root)
157900246528SJosef Bacik 		root = btrfs_grab_root(root);
1580fc7cbcd4SDavid Sterba 	spin_unlock(&fs_info->fs_roots_radix_lock);
1581cb517eabSMiao Xie 	return root;
1582cb517eabSMiao Xie }
1583cb517eabSMiao Xie 
158449d11beaSJosef Bacik static struct btrfs_root *btrfs_get_global_root(struct btrfs_fs_info *fs_info,
158549d11beaSJosef Bacik 						u64 objectid)
158649d11beaSJosef Bacik {
1587abed4aaaSJosef Bacik 	struct btrfs_key key = {
1588abed4aaaSJosef Bacik 		.objectid = objectid,
1589abed4aaaSJosef Bacik 		.type = BTRFS_ROOT_ITEM_KEY,
1590abed4aaaSJosef Bacik 		.offset = 0,
1591abed4aaaSJosef Bacik 	};
1592abed4aaaSJosef Bacik 
159349d11beaSJosef Bacik 	if (objectid == BTRFS_ROOT_TREE_OBJECTID)
159449d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->tree_root);
159549d11beaSJosef Bacik 	if (objectid == BTRFS_EXTENT_TREE_OBJECTID)
1596abed4aaaSJosef Bacik 		return btrfs_grab_root(btrfs_global_root(fs_info, &key));
159749d11beaSJosef Bacik 	if (objectid == BTRFS_CHUNK_TREE_OBJECTID)
159849d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->chunk_root);
159949d11beaSJosef Bacik 	if (objectid == BTRFS_DEV_TREE_OBJECTID)
160049d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->dev_root);
160149d11beaSJosef Bacik 	if (objectid == BTRFS_CSUM_TREE_OBJECTID)
1602abed4aaaSJosef Bacik 		return btrfs_grab_root(btrfs_global_root(fs_info, &key));
160349d11beaSJosef Bacik 	if (objectid == BTRFS_QUOTA_TREE_OBJECTID)
160449d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->quota_root) ?
160549d11beaSJosef Bacik 			fs_info->quota_root : ERR_PTR(-ENOENT);
160649d11beaSJosef Bacik 	if (objectid == BTRFS_UUID_TREE_OBJECTID)
160749d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->uuid_root) ?
160849d11beaSJosef Bacik 			fs_info->uuid_root : ERR_PTR(-ENOENT);
160914033b08SQu Wenruo 	if (objectid == BTRFS_BLOCK_GROUP_TREE_OBJECTID)
161014033b08SQu Wenruo 		return btrfs_grab_root(fs_info->block_group_root) ?
161114033b08SQu Wenruo 			fs_info->block_group_root : ERR_PTR(-ENOENT);
1612abed4aaaSJosef Bacik 	if (objectid == BTRFS_FREE_SPACE_TREE_OBJECTID) {
1613abed4aaaSJosef Bacik 		struct btrfs_root *root = btrfs_global_root(fs_info, &key);
1614abed4aaaSJosef Bacik 
1615abed4aaaSJosef Bacik 		return btrfs_grab_root(root) ? root : ERR_PTR(-ENOENT);
1616abed4aaaSJosef Bacik 	}
161749d11beaSJosef Bacik 	return NULL;
161849d11beaSJosef Bacik }
161949d11beaSJosef Bacik 
1620cb517eabSMiao Xie int btrfs_insert_fs_root(struct btrfs_fs_info *fs_info,
1621cb517eabSMiao Xie 			 struct btrfs_root *root)
1622cb517eabSMiao Xie {
1623cb517eabSMiao Xie 	int ret;
1624cb517eabSMiao Xie 
1625fc7cbcd4SDavid Sterba 	ret = radix_tree_preload(GFP_NOFS);
1626fc7cbcd4SDavid Sterba 	if (ret)
1627fc7cbcd4SDavid Sterba 		return ret;
1628fc7cbcd4SDavid Sterba 
1629fc7cbcd4SDavid Sterba 	spin_lock(&fs_info->fs_roots_radix_lock);
1630fc7cbcd4SDavid Sterba 	ret = radix_tree_insert(&fs_info->fs_roots_radix,
1631fc7cbcd4SDavid Sterba 				(unsigned long)root->root_key.objectid,
1632fc7cbcd4SDavid Sterba 				root);
1633af01d2e5SJosef Bacik 	if (ret == 0) {
163400246528SJosef Bacik 		btrfs_grab_root(root);
1635fc7cbcd4SDavid Sterba 		set_bit(BTRFS_ROOT_IN_RADIX, &root->state);
1636af01d2e5SJosef Bacik 	}
1637fc7cbcd4SDavid Sterba 	spin_unlock(&fs_info->fs_roots_radix_lock);
1638fc7cbcd4SDavid Sterba 	radix_tree_preload_end();
1639cb517eabSMiao Xie 
1640cb517eabSMiao Xie 	return ret;
1641cb517eabSMiao Xie }
1642cb517eabSMiao Xie 
1643bd647ce3SJosef Bacik void btrfs_check_leaked_roots(struct btrfs_fs_info *fs_info)
1644bd647ce3SJosef Bacik {
1645bd647ce3SJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
1646bd647ce3SJosef Bacik 	struct btrfs_root *root;
1647bd647ce3SJosef Bacik 
1648bd647ce3SJosef Bacik 	while (!list_empty(&fs_info->allocated_roots)) {
1649457f1864SJosef Bacik 		char buf[BTRFS_ROOT_NAME_BUF_LEN];
1650457f1864SJosef Bacik 
1651bd647ce3SJosef Bacik 		root = list_first_entry(&fs_info->allocated_roots,
1652bd647ce3SJosef Bacik 					struct btrfs_root, leak_list);
1653457f1864SJosef Bacik 		btrfs_err(fs_info, "leaked root %s refcount %d",
165471008734SJosef Bacik 			  btrfs_root_name(&root->root_key, buf),
1655bd647ce3SJosef Bacik 			  refcount_read(&root->refs));
1656bd647ce3SJosef Bacik 		while (refcount_read(&root->refs) > 1)
165700246528SJosef Bacik 			btrfs_put_root(root);
165800246528SJosef Bacik 		btrfs_put_root(root);
1659bd647ce3SJosef Bacik 	}
1660bd647ce3SJosef Bacik #endif
1661bd647ce3SJosef Bacik }
1662bd647ce3SJosef Bacik 
1663abed4aaaSJosef Bacik static void free_global_roots(struct btrfs_fs_info *fs_info)
1664abed4aaaSJosef Bacik {
1665abed4aaaSJosef Bacik 	struct btrfs_root *root;
1666abed4aaaSJosef Bacik 	struct rb_node *node;
1667abed4aaaSJosef Bacik 
1668abed4aaaSJosef Bacik 	while ((node = rb_first_postorder(&fs_info->global_root_tree)) != NULL) {
1669abed4aaaSJosef Bacik 		root = rb_entry(node, struct btrfs_root, rb_node);
1670abed4aaaSJosef Bacik 		rb_erase(&root->rb_node, &fs_info->global_root_tree);
1671abed4aaaSJosef Bacik 		btrfs_put_root(root);
1672abed4aaaSJosef Bacik 	}
1673abed4aaaSJosef Bacik }
1674abed4aaaSJosef Bacik 
16750d4b0463SJosef Bacik void btrfs_free_fs_info(struct btrfs_fs_info *fs_info)
16760d4b0463SJosef Bacik {
1677141386e1SJosef Bacik 	percpu_counter_destroy(&fs_info->dirty_metadata_bytes);
1678141386e1SJosef Bacik 	percpu_counter_destroy(&fs_info->delalloc_bytes);
16795deb17e1SJosef Bacik 	percpu_counter_destroy(&fs_info->ordered_bytes);
1680141386e1SJosef Bacik 	percpu_counter_destroy(&fs_info->dev_replace.bio_counter);
1681141386e1SJosef Bacik 	btrfs_free_csum_hash(fs_info);
1682141386e1SJosef Bacik 	btrfs_free_stripe_hash_table(fs_info);
1683141386e1SJosef Bacik 	btrfs_free_ref_cache(fs_info);
16840d4b0463SJosef Bacik 	kfree(fs_info->balance_ctl);
16850d4b0463SJosef Bacik 	kfree(fs_info->delayed_root);
1686abed4aaaSJosef Bacik 	free_global_roots(fs_info);
168700246528SJosef Bacik 	btrfs_put_root(fs_info->tree_root);
168800246528SJosef Bacik 	btrfs_put_root(fs_info->chunk_root);
168900246528SJosef Bacik 	btrfs_put_root(fs_info->dev_root);
169000246528SJosef Bacik 	btrfs_put_root(fs_info->quota_root);
169100246528SJosef Bacik 	btrfs_put_root(fs_info->uuid_root);
169200246528SJosef Bacik 	btrfs_put_root(fs_info->fs_root);
1693aeb935a4SQu Wenruo 	btrfs_put_root(fs_info->data_reloc_root);
16949c54e80dSJosef Bacik 	btrfs_put_root(fs_info->block_group_root);
1695bd647ce3SJosef Bacik 	btrfs_check_leaked_roots(fs_info);
16963fd63727SJosef Bacik 	btrfs_extent_buffer_leak_debug_check(fs_info);
16970d4b0463SJosef Bacik 	kfree(fs_info->super_copy);
16980d4b0463SJosef Bacik 	kfree(fs_info->super_for_commit);
16998481dd80SQu Wenruo 	kfree(fs_info->subpage_info);
17000d4b0463SJosef Bacik 	kvfree(fs_info);
17010d4b0463SJosef Bacik }
17020d4b0463SJosef Bacik 
17030d4b0463SJosef Bacik 
17042dfb1e43SQu Wenruo /*
17052dfb1e43SQu Wenruo  * Get an in-memory reference of a root structure.
17062dfb1e43SQu Wenruo  *
17072dfb1e43SQu Wenruo  * For essential trees like root/extent tree, we grab it from fs_info directly.
17082dfb1e43SQu Wenruo  * For subvolume trees, we check the cached filesystem roots first. If not
17092dfb1e43SQu Wenruo  * found, then read it from disk and add it to cached fs roots.
17102dfb1e43SQu Wenruo  *
17112dfb1e43SQu Wenruo  * Caller should release the root by calling btrfs_put_root() after the usage.
17122dfb1e43SQu Wenruo  *
17132dfb1e43SQu Wenruo  * NOTE: Reloc and log trees can't be read by this function as they share the
17142dfb1e43SQu Wenruo  *	 same root objectid.
17152dfb1e43SQu Wenruo  *
17162dfb1e43SQu Wenruo  * @objectid:	root id
17172dfb1e43SQu Wenruo  * @anon_dev:	preallocated anonymous block device number for new roots,
17182dfb1e43SQu Wenruo  * 		pass 0 for new allocation.
17192dfb1e43SQu Wenruo  * @check_ref:	whether to check root item references, If true, return -ENOENT
17202dfb1e43SQu Wenruo  *		for orphan roots
17212dfb1e43SQu Wenruo  */
17222dfb1e43SQu Wenruo static struct btrfs_root *btrfs_get_root_ref(struct btrfs_fs_info *fs_info,
17232dfb1e43SQu Wenruo 					     u64 objectid, dev_t anon_dev,
17242dfb1e43SQu Wenruo 					     bool check_ref)
17255eda7b5eSChris Mason {
17265eda7b5eSChris Mason 	struct btrfs_root *root;
1727381cf658SDavid Sterba 	struct btrfs_path *path;
17281d4c08e0SDavid Sterba 	struct btrfs_key key;
17295eda7b5eSChris Mason 	int ret;
17305eda7b5eSChris Mason 
173149d11beaSJosef Bacik 	root = btrfs_get_global_root(fs_info, objectid);
173249d11beaSJosef Bacik 	if (root)
173349d11beaSJosef Bacik 		return root;
17344df27c4dSYan, Zheng again:
173556e9357aSDavid Sterba 	root = btrfs_lookup_fs_root(fs_info, objectid);
173648475471SStefan Behrens 	if (root) {
17372dfb1e43SQu Wenruo 		/* Shouldn't get preallocated anon_dev for cached roots */
17382dfb1e43SQu Wenruo 		ASSERT(!anon_dev);
1739bc44d7c4SJosef Bacik 		if (check_ref && btrfs_root_refs(&root->root_item) == 0) {
174000246528SJosef Bacik 			btrfs_put_root(root);
174148475471SStefan Behrens 			return ERR_PTR(-ENOENT);
1742bc44d7c4SJosef Bacik 		}
17435eda7b5eSChris Mason 		return root;
174448475471SStefan Behrens 	}
17455eda7b5eSChris Mason 
174656e9357aSDavid Sterba 	key.objectid = objectid;
174756e9357aSDavid Sterba 	key.type = BTRFS_ROOT_ITEM_KEY;
174856e9357aSDavid Sterba 	key.offset = (u64)-1;
174956e9357aSDavid Sterba 	root = btrfs_read_tree_root(fs_info->tree_root, &key);
17505eda7b5eSChris Mason 	if (IS_ERR(root))
17515eda7b5eSChris Mason 		return root;
17523394e160SChris Mason 
1753c00869f1SMiao Xie 	if (check_ref && btrfs_root_refs(&root->root_item) == 0) {
1754d68fc57bSYan, Zheng 		ret = -ENOENT;
1755d68fc57bSYan, Zheng 		goto fail;
1756d68fc57bSYan, Zheng 	}
1757d68fc57bSYan, Zheng 
17582dfb1e43SQu Wenruo 	ret = btrfs_init_fs_root(root, anon_dev);
1759cb517eabSMiao Xie 	if (ret)
1760cb517eabSMiao Xie 		goto fail;
1761cb517eabSMiao Xie 
1762381cf658SDavid Sterba 	path = btrfs_alloc_path();
1763381cf658SDavid Sterba 	if (!path) {
1764381cf658SDavid Sterba 		ret = -ENOMEM;
1765381cf658SDavid Sterba 		goto fail;
1766381cf658SDavid Sterba 	}
17671d4c08e0SDavid Sterba 	key.objectid = BTRFS_ORPHAN_OBJECTID;
17681d4c08e0SDavid Sterba 	key.type = BTRFS_ORPHAN_ITEM_KEY;
176956e9357aSDavid Sterba 	key.offset = objectid;
17701d4c08e0SDavid Sterba 
17711d4c08e0SDavid Sterba 	ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
1772381cf658SDavid Sterba 	btrfs_free_path(path);
1773d68fc57bSYan, Zheng 	if (ret < 0)
1774d68fc57bSYan, Zheng 		goto fail;
1775d68fc57bSYan, Zheng 	if (ret == 0)
177627cdeb70SMiao Xie 		set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state);
1777d68fc57bSYan, Zheng 
1778cb517eabSMiao Xie 	ret = btrfs_insert_fs_root(fs_info, root);
17790f7d52f4SChris Mason 	if (ret) {
1780168a2f77SJia-Ju Bai 		if (ret == -EEXIST) {
178100246528SJosef Bacik 			btrfs_put_root(root);
17824df27c4dSYan, Zheng 			goto again;
1783168a2f77SJia-Ju Bai 		}
17844df27c4dSYan, Zheng 		goto fail;
17854df27c4dSYan, Zheng 	}
1786edbd8d4eSChris Mason 	return root;
17874df27c4dSYan, Zheng fail:
178833fab972SFilipe Manana 	/*
178933fab972SFilipe Manana 	 * If our caller provided us an anonymous device, then it's his
1790143823cfSDavid Sterba 	 * responsibility to free it in case we fail. So we have to set our
179133fab972SFilipe Manana 	 * root's anon_dev to 0 to avoid a double free, once by btrfs_put_root()
179233fab972SFilipe Manana 	 * and once again by our caller.
179333fab972SFilipe Manana 	 */
179433fab972SFilipe Manana 	if (anon_dev)
179533fab972SFilipe Manana 		root->anon_dev = 0;
17968c38938cSJosef Bacik 	btrfs_put_root(root);
17974df27c4dSYan, Zheng 	return ERR_PTR(ret);
1798edbd8d4eSChris Mason }
1799edbd8d4eSChris Mason 
18002dfb1e43SQu Wenruo /*
18012dfb1e43SQu Wenruo  * Get in-memory reference of a root structure
18022dfb1e43SQu Wenruo  *
18032dfb1e43SQu Wenruo  * @objectid:	tree objectid
18042dfb1e43SQu Wenruo  * @check_ref:	if set, verify that the tree exists and the item has at least
18052dfb1e43SQu Wenruo  *		one reference
18062dfb1e43SQu Wenruo  */
18072dfb1e43SQu Wenruo struct btrfs_root *btrfs_get_fs_root(struct btrfs_fs_info *fs_info,
18082dfb1e43SQu Wenruo 				     u64 objectid, bool check_ref)
18092dfb1e43SQu Wenruo {
18102dfb1e43SQu Wenruo 	return btrfs_get_root_ref(fs_info, objectid, 0, check_ref);
18112dfb1e43SQu Wenruo }
18122dfb1e43SQu Wenruo 
18132dfb1e43SQu Wenruo /*
18142dfb1e43SQu Wenruo  * Get in-memory reference of a root structure, created as new, optionally pass
18152dfb1e43SQu Wenruo  * the anonymous block device id
18162dfb1e43SQu Wenruo  *
18172dfb1e43SQu Wenruo  * @objectid:	tree objectid
18182dfb1e43SQu Wenruo  * @anon_dev:	if zero, allocate a new anonymous block device or use the
18192dfb1e43SQu Wenruo  *		parameter value
18202dfb1e43SQu Wenruo  */
18212dfb1e43SQu Wenruo struct btrfs_root *btrfs_get_new_fs_root(struct btrfs_fs_info *fs_info,
18222dfb1e43SQu Wenruo 					 u64 objectid, dev_t anon_dev)
18232dfb1e43SQu Wenruo {
18242dfb1e43SQu Wenruo 	return btrfs_get_root_ref(fs_info, objectid, anon_dev, true);
18252dfb1e43SQu Wenruo }
18262dfb1e43SQu Wenruo 
18278b712842SChris Mason /*
182849d11beaSJosef Bacik  * btrfs_get_fs_root_commit_root - return a root for the given objectid
182949d11beaSJosef Bacik  * @fs_info:	the fs_info
183049d11beaSJosef Bacik  * @objectid:	the objectid we need to lookup
183149d11beaSJosef Bacik  *
183249d11beaSJosef Bacik  * This is exclusively used for backref walking, and exists specifically because
183349d11beaSJosef Bacik  * of how qgroups does lookups.  Qgroups will do a backref lookup at delayed ref
183449d11beaSJosef Bacik  * creation time, which means we may have to read the tree_root in order to look
183549d11beaSJosef Bacik  * up a fs root that is not in memory.  If the root is not in memory we will
183649d11beaSJosef Bacik  * read the tree root commit root and look up the fs root from there.  This is a
183749d11beaSJosef Bacik  * temporary root, it will not be inserted into the radix tree as it doesn't
183849d11beaSJosef Bacik  * have the most uptodate information, it'll simply be discarded once the
183949d11beaSJosef Bacik  * backref code is finished using the root.
184049d11beaSJosef Bacik  */
184149d11beaSJosef Bacik struct btrfs_root *btrfs_get_fs_root_commit_root(struct btrfs_fs_info *fs_info,
184249d11beaSJosef Bacik 						 struct btrfs_path *path,
184349d11beaSJosef Bacik 						 u64 objectid)
184449d11beaSJosef Bacik {
184549d11beaSJosef Bacik 	struct btrfs_root *root;
184649d11beaSJosef Bacik 	struct btrfs_key key;
184749d11beaSJosef Bacik 
184849d11beaSJosef Bacik 	ASSERT(path->search_commit_root && path->skip_locking);
184949d11beaSJosef Bacik 
185049d11beaSJosef Bacik 	/*
185149d11beaSJosef Bacik 	 * This can return -ENOENT if we ask for a root that doesn't exist, but
185249d11beaSJosef Bacik 	 * since this is called via the backref walking code we won't be looking
185349d11beaSJosef Bacik 	 * up a root that doesn't exist, unless there's corruption.  So if root
185449d11beaSJosef Bacik 	 * != NULL just return it.
185549d11beaSJosef Bacik 	 */
185649d11beaSJosef Bacik 	root = btrfs_get_global_root(fs_info, objectid);
185749d11beaSJosef Bacik 	if (root)
185849d11beaSJosef Bacik 		return root;
185949d11beaSJosef Bacik 
186049d11beaSJosef Bacik 	root = btrfs_lookup_fs_root(fs_info, objectid);
186149d11beaSJosef Bacik 	if (root)
186249d11beaSJosef Bacik 		return root;
186349d11beaSJosef Bacik 
186449d11beaSJosef Bacik 	key.objectid = objectid;
186549d11beaSJosef Bacik 	key.type = BTRFS_ROOT_ITEM_KEY;
186649d11beaSJosef Bacik 	key.offset = (u64)-1;
186749d11beaSJosef Bacik 	root = read_tree_root_path(fs_info->tree_root, path, &key);
186849d11beaSJosef Bacik 	btrfs_release_path(path);
186949d11beaSJosef Bacik 
187049d11beaSJosef Bacik 	return root;
187149d11beaSJosef Bacik }
187249d11beaSJosef Bacik 
1873a74a4b97SChris Mason static int cleaner_kthread(void *arg)
1874a74a4b97SChris Mason {
18750d031dc4SYu Zhe 	struct btrfs_fs_info *fs_info = arg;
1876d0278245SMiao Xie 	int again;
1877a74a4b97SChris Mason 
1878d6fd0ae2SOmar Sandoval 	while (1) {
1879d0278245SMiao Xie 		again = 0;
18809d1a2a3aSDavid Sterba 
1881fd340d0fSJosef Bacik 		set_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags);
1882fd340d0fSJosef Bacik 
1883d0278245SMiao Xie 		/* Make the cleaner go to sleep early. */
18842ff7e61eSJeff Mahoney 		if (btrfs_need_cleaner_sleep(fs_info))
1885d0278245SMiao Xie 			goto sleep;
1886d0278245SMiao Xie 
188790c711abSZygo Blaxell 		/*
188890c711abSZygo Blaxell 		 * Do not do anything if we might cause open_ctree() to block
188990c711abSZygo Blaxell 		 * before we have finished mounting the filesystem.
189090c711abSZygo Blaxell 		 */
18910b246afaSJeff Mahoney 		if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
189290c711abSZygo Blaxell 			goto sleep;
189390c711abSZygo Blaxell 
18940b246afaSJeff Mahoney 		if (!mutex_trylock(&fs_info->cleaner_mutex))
1895d0278245SMiao Xie 			goto sleep;
1896d0278245SMiao Xie 
1897dc7f370cSMiao Xie 		/*
1898dc7f370cSMiao Xie 		 * Avoid the problem that we change the status of the fs
1899dc7f370cSMiao Xie 		 * during the above check and trylock.
1900dc7f370cSMiao Xie 		 */
19012ff7e61eSJeff Mahoney 		if (btrfs_need_cleaner_sleep(fs_info)) {
19020b246afaSJeff Mahoney 			mutex_unlock(&fs_info->cleaner_mutex);
1903dc7f370cSMiao Xie 			goto sleep;
1904dc7f370cSMiao Xie 		}
1905dc7f370cSMiao Xie 
19062ff7e61eSJeff Mahoney 		btrfs_run_delayed_iputs(fs_info);
1907c2d6cb16SFilipe Manana 
190833c44184SJosef Bacik 		again = btrfs_clean_one_deleted_snapshot(fs_info);
19090b246afaSJeff Mahoney 		mutex_unlock(&fs_info->cleaner_mutex);
1910a74a4b97SChris Mason 
1911d0278245SMiao Xie 		/*
191205323cd1SMiao Xie 		 * The defragger has dealt with the R/O remount and umount,
191305323cd1SMiao Xie 		 * needn't do anything special here.
1914d0278245SMiao Xie 		 */
19150b246afaSJeff Mahoney 		btrfs_run_defrag_inodes(fs_info);
191667c5e7d4SFilipe Manana 
191767c5e7d4SFilipe Manana 		/*
1918f3372065SJohannes Thumshirn 		 * Acquires fs_info->reclaim_bgs_lock to avoid racing
191967c5e7d4SFilipe Manana 		 * with relocation (btrfs_relocate_chunk) and relocation
192067c5e7d4SFilipe Manana 		 * acquires fs_info->cleaner_mutex (btrfs_relocate_block_group)
1921f3372065SJohannes Thumshirn 		 * after acquiring fs_info->reclaim_bgs_lock. So we
192267c5e7d4SFilipe Manana 		 * can't hold, nor need to, fs_info->cleaner_mutex when deleting
192367c5e7d4SFilipe Manana 		 * unused block groups.
192467c5e7d4SFilipe Manana 		 */
19250b246afaSJeff Mahoney 		btrfs_delete_unused_bgs(fs_info);
192618bb8bbfSJohannes Thumshirn 
192718bb8bbfSJohannes Thumshirn 		/*
192818bb8bbfSJohannes Thumshirn 		 * Reclaim block groups in the reclaim_bgs list after we deleted
192918bb8bbfSJohannes Thumshirn 		 * all unused block_groups. This possibly gives us some more free
193018bb8bbfSJohannes Thumshirn 		 * space.
193118bb8bbfSJohannes Thumshirn 		 */
193218bb8bbfSJohannes Thumshirn 		btrfs_reclaim_bgs(fs_info);
1933d0278245SMiao Xie sleep:
1934a0a1db70SFilipe Manana 		clear_and_wake_up_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags);
1935d6fd0ae2SOmar Sandoval 		if (kthread_should_park())
1936d6fd0ae2SOmar Sandoval 			kthread_parkme();
1937d6fd0ae2SOmar Sandoval 		if (kthread_should_stop())
1938d6fd0ae2SOmar Sandoval 			return 0;
1939838fe188SJiri Kosina 		if (!again) {
1940a74a4b97SChris Mason 			set_current_state(TASK_INTERRUPTIBLE);
1941a74a4b97SChris Mason 			schedule();
1942a74a4b97SChris Mason 			__set_current_state(TASK_RUNNING);
1943a74a4b97SChris Mason 		}
1944da288d28SFilipe Manana 	}
1945a74a4b97SChris Mason }
1946a74a4b97SChris Mason 
1947a74a4b97SChris Mason static int transaction_kthread(void *arg)
1948a74a4b97SChris Mason {
1949a74a4b97SChris Mason 	struct btrfs_root *root = arg;
19500b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
1951a74a4b97SChris Mason 	struct btrfs_trans_handle *trans;
1952a74a4b97SChris Mason 	struct btrfs_transaction *cur;
19538929ecfaSYan, Zheng 	u64 transid;
1954643900beSNikolay Borisov 	time64_t delta;
1955a74a4b97SChris Mason 	unsigned long delay;
1956914b2007SJan Kara 	bool cannot_commit;
1957a74a4b97SChris Mason 
1958a74a4b97SChris Mason 	do {
1959914b2007SJan Kara 		cannot_commit = false;
1960ba1bc00fSNikolay Borisov 		delay = msecs_to_jiffies(fs_info->commit_interval * 1000);
19610b246afaSJeff Mahoney 		mutex_lock(&fs_info->transaction_kthread_mutex);
1962a74a4b97SChris Mason 
19630b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
19640b246afaSJeff Mahoney 		cur = fs_info->running_transaction;
1965a74a4b97SChris Mason 		if (!cur) {
19660b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
1967a74a4b97SChris Mason 			goto sleep;
1968a74a4b97SChris Mason 		}
196931153d81SYan Zheng 
1970643900beSNikolay Borisov 		delta = ktime_get_seconds() - cur->start_time;
1971fdfbf020SJosef Bacik 		if (!test_and_clear_bit(BTRFS_FS_COMMIT_TRANS, &fs_info->flags) &&
1972fdfbf020SJosef Bacik 		    cur->state < TRANS_STATE_COMMIT_START &&
1973643900beSNikolay Borisov 		    delta < fs_info->commit_interval) {
19740b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
1975fb8a7e94SNikolay Borisov 			delay -= msecs_to_jiffies((delta - 1) * 1000);
1976fb8a7e94SNikolay Borisov 			delay = min(delay,
1977fb8a7e94SNikolay Borisov 				    msecs_to_jiffies(fs_info->commit_interval * 1000));
1978a74a4b97SChris Mason 			goto sleep;
1979a74a4b97SChris Mason 		}
19808929ecfaSYan, Zheng 		transid = cur->transid;
19810b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
198256bec294SChris Mason 
198379787eaaSJeff Mahoney 		/* If the file system is aborted, this will always fail. */
1984354aa0fbSMiao Xie 		trans = btrfs_attach_transaction(root);
1985914b2007SJan Kara 		if (IS_ERR(trans)) {
1986354aa0fbSMiao Xie 			if (PTR_ERR(trans) != -ENOENT)
1987914b2007SJan Kara 				cannot_commit = true;
198879787eaaSJeff Mahoney 			goto sleep;
1989914b2007SJan Kara 		}
19908929ecfaSYan, Zheng 		if (transid == trans->transid) {
19913a45bb20SJeff Mahoney 			btrfs_commit_transaction(trans);
19928929ecfaSYan, Zheng 		} else {
19933a45bb20SJeff Mahoney 			btrfs_end_transaction(trans);
19948929ecfaSYan, Zheng 		}
1995a74a4b97SChris Mason sleep:
19960b246afaSJeff Mahoney 		wake_up_process(fs_info->cleaner_kthread);
19970b246afaSJeff Mahoney 		mutex_unlock(&fs_info->transaction_kthread_mutex);
1998a74a4b97SChris Mason 
199984961539SJosef Bacik 		if (BTRFS_FS_ERROR(fs_info))
20002ff7e61eSJeff Mahoney 			btrfs_cleanup_transaction(fs_info);
20018929ecfaSYan, Zheng 		if (!kthread_should_stop() &&
20020b246afaSJeff Mahoney 				(!btrfs_transaction_blocked(fs_info) ||
2003914b2007SJan Kara 				 cannot_commit))
2004bc5511d0SNikolay Borisov 			schedule_timeout_interruptible(delay);
2005a74a4b97SChris Mason 	} while (!kthread_should_stop());
2006a74a4b97SChris Mason 	return 0;
2007a74a4b97SChris Mason }
2008a74a4b97SChris Mason 
2009af31f5e5SChris Mason /*
201001f0f9daSNikolay Borisov  * This will find the highest generation in the array of root backups.  The
201101f0f9daSNikolay Borisov  * index of the highest array is returned, or -EINVAL if we can't find
201201f0f9daSNikolay Borisov  * anything.
2013af31f5e5SChris Mason  *
2014af31f5e5SChris Mason  * We check to make sure the array is valid by comparing the
2015af31f5e5SChris Mason  * generation of the latest  root in the array with the generation
2016af31f5e5SChris Mason  * in the super block.  If they don't match we pitch it.
2017af31f5e5SChris Mason  */
201801f0f9daSNikolay Borisov static int find_newest_super_backup(struct btrfs_fs_info *info)
2019af31f5e5SChris Mason {
202001f0f9daSNikolay Borisov 	const u64 newest_gen = btrfs_super_generation(info->super_copy);
2021af31f5e5SChris Mason 	u64 cur;
2022af31f5e5SChris Mason 	struct btrfs_root_backup *root_backup;
2023af31f5e5SChris Mason 	int i;
2024af31f5e5SChris Mason 
2025af31f5e5SChris Mason 	for (i = 0; i < BTRFS_NUM_BACKUP_ROOTS; i++) {
2026af31f5e5SChris Mason 		root_backup = info->super_copy->super_roots + i;
2027af31f5e5SChris Mason 		cur = btrfs_backup_tree_root_gen(root_backup);
2028af31f5e5SChris Mason 		if (cur == newest_gen)
202901f0f9daSNikolay Borisov 			return i;
2030af31f5e5SChris Mason 	}
2031af31f5e5SChris Mason 
203201f0f9daSNikolay Borisov 	return -EINVAL;
2033af31f5e5SChris Mason }
2034af31f5e5SChris Mason 
2035af31f5e5SChris Mason /*
2036af31f5e5SChris Mason  * copy all the root pointers into the super backup array.
2037af31f5e5SChris Mason  * this will bump the backup pointer by one when it is
2038af31f5e5SChris Mason  * done
2039af31f5e5SChris Mason  */
2040af31f5e5SChris Mason static void backup_super_roots(struct btrfs_fs_info *info)
2041af31f5e5SChris Mason {
20426ef108ddSNikolay Borisov 	const int next_backup = info->backup_root_index;
2043af31f5e5SChris Mason 	struct btrfs_root_backup *root_backup;
2044af31f5e5SChris Mason 
2045af31f5e5SChris Mason 	root_backup = info->super_for_commit->super_roots + next_backup;
2046af31f5e5SChris Mason 
2047af31f5e5SChris Mason 	/*
2048af31f5e5SChris Mason 	 * make sure all of our padding and empty slots get zero filled
2049af31f5e5SChris Mason 	 * regardless of which ones we use today
2050af31f5e5SChris Mason 	 */
2051af31f5e5SChris Mason 	memset(root_backup, 0, sizeof(*root_backup));
2052af31f5e5SChris Mason 
2053af31f5e5SChris Mason 	info->backup_root_index = (next_backup + 1) % BTRFS_NUM_BACKUP_ROOTS;
2054af31f5e5SChris Mason 
2055af31f5e5SChris Mason 	btrfs_set_backup_tree_root(root_backup, info->tree_root->node->start);
2056af31f5e5SChris Mason 	btrfs_set_backup_tree_root_gen(root_backup,
2057af31f5e5SChris Mason 			       btrfs_header_generation(info->tree_root->node));
2058af31f5e5SChris Mason 
2059af31f5e5SChris Mason 	btrfs_set_backup_tree_root_level(root_backup,
2060af31f5e5SChris Mason 			       btrfs_header_level(info->tree_root->node));
2061af31f5e5SChris Mason 
2062af31f5e5SChris Mason 	btrfs_set_backup_chunk_root(root_backup, info->chunk_root->node->start);
2063af31f5e5SChris Mason 	btrfs_set_backup_chunk_root_gen(root_backup,
2064af31f5e5SChris Mason 			       btrfs_header_generation(info->chunk_root->node));
2065af31f5e5SChris Mason 	btrfs_set_backup_chunk_root_level(root_backup,
2066af31f5e5SChris Mason 			       btrfs_header_level(info->chunk_root->node));
2067af31f5e5SChris Mason 
20681c56ab99SQu Wenruo 	if (!btrfs_fs_compat_ro(info, BLOCK_GROUP_TREE)) {
20699c54e80dSJosef Bacik 		struct btrfs_root *extent_root = btrfs_extent_root(info, 0);
2070f7238e50SJosef Bacik 		struct btrfs_root *csum_root = btrfs_csum_root(info, 0);
20719c54e80dSJosef Bacik 
20729c54e80dSJosef Bacik 		btrfs_set_backup_extent_root(root_backup,
20739c54e80dSJosef Bacik 					     extent_root->node->start);
2074af31f5e5SChris Mason 		btrfs_set_backup_extent_root_gen(root_backup,
207529cbcf40SJosef Bacik 				btrfs_header_generation(extent_root->node));
2076af31f5e5SChris Mason 		btrfs_set_backup_extent_root_level(root_backup,
207729cbcf40SJosef Bacik 					btrfs_header_level(extent_root->node));
2078af31f5e5SChris Mason 
2079f7238e50SJosef Bacik 		btrfs_set_backup_csum_root(root_backup, csum_root->node->start);
2080f7238e50SJosef Bacik 		btrfs_set_backup_csum_root_gen(root_backup,
2081f7238e50SJosef Bacik 					       btrfs_header_generation(csum_root->node));
2082f7238e50SJosef Bacik 		btrfs_set_backup_csum_root_level(root_backup,
2083f7238e50SJosef Bacik 						 btrfs_header_level(csum_root->node));
20849c54e80dSJosef Bacik 	}
2085af31f5e5SChris Mason 
20867c7e82a7SChris Mason 	/*
20877c7e82a7SChris Mason 	 * we might commit during log recovery, which happens before we set
20887c7e82a7SChris Mason 	 * the fs_root.  Make sure it is valid before we fill it in.
20897c7e82a7SChris Mason 	 */
20907c7e82a7SChris Mason 	if (info->fs_root && info->fs_root->node) {
20917c7e82a7SChris Mason 		btrfs_set_backup_fs_root(root_backup,
20927c7e82a7SChris Mason 					 info->fs_root->node->start);
2093af31f5e5SChris Mason 		btrfs_set_backup_fs_root_gen(root_backup,
2094af31f5e5SChris Mason 			       btrfs_header_generation(info->fs_root->node));
2095af31f5e5SChris Mason 		btrfs_set_backup_fs_root_level(root_backup,
2096af31f5e5SChris Mason 			       btrfs_header_level(info->fs_root->node));
20977c7e82a7SChris Mason 	}
2098af31f5e5SChris Mason 
2099af31f5e5SChris Mason 	btrfs_set_backup_dev_root(root_backup, info->dev_root->node->start);
2100af31f5e5SChris Mason 	btrfs_set_backup_dev_root_gen(root_backup,
2101af31f5e5SChris Mason 			       btrfs_header_generation(info->dev_root->node));
2102af31f5e5SChris Mason 	btrfs_set_backup_dev_root_level(root_backup,
2103af31f5e5SChris Mason 				       btrfs_header_level(info->dev_root->node));
2104af31f5e5SChris Mason 
2105af31f5e5SChris Mason 	btrfs_set_backup_total_bytes(root_backup,
2106af31f5e5SChris Mason 			     btrfs_super_total_bytes(info->super_copy));
2107af31f5e5SChris Mason 	btrfs_set_backup_bytes_used(root_backup,
2108af31f5e5SChris Mason 			     btrfs_super_bytes_used(info->super_copy));
2109af31f5e5SChris Mason 	btrfs_set_backup_num_devices(root_backup,
2110af31f5e5SChris Mason 			     btrfs_super_num_devices(info->super_copy));
2111af31f5e5SChris Mason 
2112af31f5e5SChris Mason 	/*
2113af31f5e5SChris Mason 	 * if we don't copy this out to the super_copy, it won't get remembered
2114af31f5e5SChris Mason 	 * for the next commit
2115af31f5e5SChris Mason 	 */
2116af31f5e5SChris Mason 	memcpy(&info->super_copy->super_roots,
2117af31f5e5SChris Mason 	       &info->super_for_commit->super_roots,
2118af31f5e5SChris Mason 	       sizeof(*root_backup) * BTRFS_NUM_BACKUP_ROOTS);
2119af31f5e5SChris Mason }
2120af31f5e5SChris Mason 
2121af31f5e5SChris Mason /*
2122bd2336b2SNikolay Borisov  * read_backup_root - Reads a backup root based on the passed priority. Prio 0
2123bd2336b2SNikolay Borisov  * is the newest, prio 1/2/3 are 2nd newest/3rd newest/4th (oldest) backup roots
2124bd2336b2SNikolay Borisov  *
2125bd2336b2SNikolay Borisov  * fs_info - filesystem whose backup roots need to be read
2126bd2336b2SNikolay Borisov  * priority - priority of backup root required
2127bd2336b2SNikolay Borisov  *
2128bd2336b2SNikolay Borisov  * Returns backup root index on success and -EINVAL otherwise.
2129bd2336b2SNikolay Borisov  */
2130bd2336b2SNikolay Borisov static int read_backup_root(struct btrfs_fs_info *fs_info, u8 priority)
2131bd2336b2SNikolay Borisov {
2132bd2336b2SNikolay Borisov 	int backup_index = find_newest_super_backup(fs_info);
2133bd2336b2SNikolay Borisov 	struct btrfs_super_block *super = fs_info->super_copy;
2134bd2336b2SNikolay Borisov 	struct btrfs_root_backup *root_backup;
2135bd2336b2SNikolay Borisov 
2136bd2336b2SNikolay Borisov 	if (priority < BTRFS_NUM_BACKUP_ROOTS && backup_index >= 0) {
2137bd2336b2SNikolay Borisov 		if (priority == 0)
2138bd2336b2SNikolay Borisov 			return backup_index;
2139bd2336b2SNikolay Borisov 
2140bd2336b2SNikolay Borisov 		backup_index = backup_index + BTRFS_NUM_BACKUP_ROOTS - priority;
2141bd2336b2SNikolay Borisov 		backup_index %= BTRFS_NUM_BACKUP_ROOTS;
2142bd2336b2SNikolay Borisov 	} else {
2143bd2336b2SNikolay Borisov 		return -EINVAL;
2144bd2336b2SNikolay Borisov 	}
2145bd2336b2SNikolay Borisov 
2146bd2336b2SNikolay Borisov 	root_backup = super->super_roots + backup_index;
2147bd2336b2SNikolay Borisov 
2148bd2336b2SNikolay Borisov 	btrfs_set_super_generation(super,
2149bd2336b2SNikolay Borisov 				   btrfs_backup_tree_root_gen(root_backup));
2150bd2336b2SNikolay Borisov 	btrfs_set_super_root(super, btrfs_backup_tree_root(root_backup));
2151bd2336b2SNikolay Borisov 	btrfs_set_super_root_level(super,
2152bd2336b2SNikolay Borisov 				   btrfs_backup_tree_root_level(root_backup));
2153bd2336b2SNikolay Borisov 	btrfs_set_super_bytes_used(super, btrfs_backup_bytes_used(root_backup));
2154bd2336b2SNikolay Borisov 
2155bd2336b2SNikolay Borisov 	/*
2156bd2336b2SNikolay Borisov 	 * Fixme: the total bytes and num_devices need to match or we should
2157bd2336b2SNikolay Borisov 	 * need a fsck
2158bd2336b2SNikolay Borisov 	 */
2159bd2336b2SNikolay Borisov 	btrfs_set_super_total_bytes(super, btrfs_backup_total_bytes(root_backup));
2160bd2336b2SNikolay Borisov 	btrfs_set_super_num_devices(super, btrfs_backup_num_devices(root_backup));
2161bd2336b2SNikolay Borisov 
2162bd2336b2SNikolay Borisov 	return backup_index;
2163bd2336b2SNikolay Borisov }
2164bd2336b2SNikolay Borisov 
21657abadb64SLiu Bo /* helper to cleanup workers */
21667abadb64SLiu Bo static void btrfs_stop_all_workers(struct btrfs_fs_info *fs_info)
21677abadb64SLiu Bo {
2168dc6e3209SQu Wenruo 	btrfs_destroy_workqueue(fs_info->fixup_workers);
2169afe3d242SQu Wenruo 	btrfs_destroy_workqueue(fs_info->delalloc_workers);
2170a31b4a43SChristoph Hellwig 	btrfs_destroy_workqueue(fs_info->hipri_workers);
21715cdc7ad3SQu Wenruo 	btrfs_destroy_workqueue(fs_info->workers);
2172d7b9416fSChristoph Hellwig 	if (fs_info->endio_workers)
2173d7b9416fSChristoph Hellwig 		destroy_workqueue(fs_info->endio_workers);
2174385de0efSChristoph Hellwig 	if (fs_info->rmw_workers)
2175385de0efSChristoph Hellwig 		destroy_workqueue(fs_info->rmw_workers);
2176fed8a72dSChristoph Hellwig 	if (fs_info->compressed_write_workers)
2177fed8a72dSChristoph Hellwig 		destroy_workqueue(fs_info->compressed_write_workers);
2178fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_write_workers);
2179fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_freespace_worker);
21805b3bc44eSQu Wenruo 	btrfs_destroy_workqueue(fs_info->delayed_workers);
2181e66f0bb1SQu Wenruo 	btrfs_destroy_workqueue(fs_info->caching_workers);
2182a44903abSQu Wenruo 	btrfs_destroy_workqueue(fs_info->flush_workers);
2183fc97fab0SQu Wenruo 	btrfs_destroy_workqueue(fs_info->qgroup_rescan_workers);
2184b0643e59SDennis Zhou 	if (fs_info->discard_ctl.discard_workers)
2185b0643e59SDennis Zhou 		destroy_workqueue(fs_info->discard_ctl.discard_workers);
2186a9b9477dSFilipe Manana 	/*
2187a9b9477dSFilipe Manana 	 * Now that all other work queues are destroyed, we can safely destroy
2188a9b9477dSFilipe Manana 	 * the queues used for metadata I/O, since tasks from those other work
2189a9b9477dSFilipe Manana 	 * queues can do metadata I/O operations.
2190a9b9477dSFilipe Manana 	 */
2191d7b9416fSChristoph Hellwig 	if (fs_info->endio_meta_workers)
2192d7b9416fSChristoph Hellwig 		destroy_workqueue(fs_info->endio_meta_workers);
21937abadb64SLiu Bo }
21947abadb64SLiu Bo 
21952e9f5954SRashika static void free_root_extent_buffers(struct btrfs_root *root)
21962e9f5954SRashika {
21972e9f5954SRashika 	if (root) {
21982e9f5954SRashika 		free_extent_buffer(root->node);
21992e9f5954SRashika 		free_extent_buffer(root->commit_root);
22002e9f5954SRashika 		root->node = NULL;
22012e9f5954SRashika 		root->commit_root = NULL;
22022e9f5954SRashika 	}
22032e9f5954SRashika }
22042e9f5954SRashika 
2205abed4aaaSJosef Bacik static void free_global_root_pointers(struct btrfs_fs_info *fs_info)
2206abed4aaaSJosef Bacik {
2207abed4aaaSJosef Bacik 	struct btrfs_root *root, *tmp;
2208abed4aaaSJosef Bacik 
2209abed4aaaSJosef Bacik 	rbtree_postorder_for_each_entry_safe(root, tmp,
2210abed4aaaSJosef Bacik 					     &fs_info->global_root_tree,
2211abed4aaaSJosef Bacik 					     rb_node)
2212abed4aaaSJosef Bacik 		free_root_extent_buffers(root);
2213abed4aaaSJosef Bacik }
2214abed4aaaSJosef Bacik 
2215af31f5e5SChris Mason /* helper to cleanup tree roots */
22164273eaffSAnand Jain static void free_root_pointers(struct btrfs_fs_info *info, bool free_chunk_root)
2217af31f5e5SChris Mason {
22182e9f5954SRashika 	free_root_extent_buffers(info->tree_root);
2219655b09feSJosef Bacik 
2220abed4aaaSJosef Bacik 	free_global_root_pointers(info);
22212e9f5954SRashika 	free_root_extent_buffers(info->dev_root);
22222e9f5954SRashika 	free_root_extent_buffers(info->quota_root);
22232e9f5954SRashika 	free_root_extent_buffers(info->uuid_root);
22248c38938cSJosef Bacik 	free_root_extent_buffers(info->fs_root);
2225aeb935a4SQu Wenruo 	free_root_extent_buffers(info->data_reloc_root);
22269c54e80dSJosef Bacik 	free_root_extent_buffers(info->block_group_root);
22274273eaffSAnand Jain 	if (free_chunk_root)
22282e9f5954SRashika 		free_root_extent_buffers(info->chunk_root);
2229af31f5e5SChris Mason }
2230af31f5e5SChris Mason 
22318c38938cSJosef Bacik void btrfs_put_root(struct btrfs_root *root)
22328c38938cSJosef Bacik {
22338c38938cSJosef Bacik 	if (!root)
22348c38938cSJosef Bacik 		return;
22358c38938cSJosef Bacik 
22368c38938cSJosef Bacik 	if (refcount_dec_and_test(&root->refs)) {
22378c38938cSJosef Bacik 		WARN_ON(!RB_EMPTY_ROOT(&root->inode_tree));
22381dae7e0eSQu Wenruo 		WARN_ON(test_bit(BTRFS_ROOT_DEAD_RELOC_TREE, &root->state));
22398c38938cSJosef Bacik 		if (root->anon_dev)
22408c38938cSJosef Bacik 			free_anon_bdev(root->anon_dev);
22418c38938cSJosef Bacik 		btrfs_drew_lock_destroy(&root->snapshot_lock);
2242923eb523SJohannes Thumshirn 		free_root_extent_buffers(root);
22438c38938cSJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
2244fc7cbcd4SDavid Sterba 		spin_lock(&root->fs_info->fs_roots_radix_lock);
22458c38938cSJosef Bacik 		list_del_init(&root->leak_list);
2246fc7cbcd4SDavid Sterba 		spin_unlock(&root->fs_info->fs_roots_radix_lock);
22478c38938cSJosef Bacik #endif
22488c38938cSJosef Bacik 		kfree(root);
22498c38938cSJosef Bacik 	}
22508c38938cSJosef Bacik }
22518c38938cSJosef Bacik 
2252faa2dbf0SJosef Bacik void btrfs_free_fs_roots(struct btrfs_fs_info *fs_info)
2253171f6537SJosef Bacik {
2254fc7cbcd4SDavid Sterba 	int ret;
2255fc7cbcd4SDavid Sterba 	struct btrfs_root *gang[8];
2256fc7cbcd4SDavid Sterba 	int i;
2257171f6537SJosef Bacik 
2258171f6537SJosef Bacik 	while (!list_empty(&fs_info->dead_roots)) {
2259fc7cbcd4SDavid Sterba 		gang[0] = list_entry(fs_info->dead_roots.next,
2260171f6537SJosef Bacik 				     struct btrfs_root, root_list);
2261fc7cbcd4SDavid Sterba 		list_del(&gang[0]->root_list);
2262171f6537SJosef Bacik 
2263fc7cbcd4SDavid Sterba 		if (test_bit(BTRFS_ROOT_IN_RADIX, &gang[0]->state))
2264fc7cbcd4SDavid Sterba 			btrfs_drop_and_free_fs_root(fs_info, gang[0]);
2265fc7cbcd4SDavid Sterba 		btrfs_put_root(gang[0]);
2266171f6537SJosef Bacik 	}
2267171f6537SJosef Bacik 
2268fc7cbcd4SDavid Sterba 	while (1) {
2269fc7cbcd4SDavid Sterba 		ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
2270fc7cbcd4SDavid Sterba 					     (void **)gang, 0,
2271fc7cbcd4SDavid Sterba 					     ARRAY_SIZE(gang));
2272fc7cbcd4SDavid Sterba 		if (!ret)
2273fc7cbcd4SDavid Sterba 			break;
2274fc7cbcd4SDavid Sterba 		for (i = 0; i < ret; i++)
2275fc7cbcd4SDavid Sterba 			btrfs_drop_and_free_fs_root(fs_info, gang[i]);
2276171f6537SJosef Bacik 	}
2277171f6537SJosef Bacik }
2278af31f5e5SChris Mason 
2279638aa7edSEric Sandeen static void btrfs_init_scrub(struct btrfs_fs_info *fs_info)
2280638aa7edSEric Sandeen {
2281638aa7edSEric Sandeen 	mutex_init(&fs_info->scrub_lock);
2282638aa7edSEric Sandeen 	atomic_set(&fs_info->scrubs_running, 0);
2283638aa7edSEric Sandeen 	atomic_set(&fs_info->scrub_pause_req, 0);
2284638aa7edSEric Sandeen 	atomic_set(&fs_info->scrubs_paused, 0);
2285638aa7edSEric Sandeen 	atomic_set(&fs_info->scrub_cancel_req, 0);
2286638aa7edSEric Sandeen 	init_waitqueue_head(&fs_info->scrub_pause_wait);
2287ff09c4caSAnand Jain 	refcount_set(&fs_info->scrub_workers_refcnt, 0);
2288638aa7edSEric Sandeen }
2289638aa7edSEric Sandeen 
2290779a65a4SEric Sandeen static void btrfs_init_balance(struct btrfs_fs_info *fs_info)
2291779a65a4SEric Sandeen {
2292779a65a4SEric Sandeen 	spin_lock_init(&fs_info->balance_lock);
2293779a65a4SEric Sandeen 	mutex_init(&fs_info->balance_mutex);
2294779a65a4SEric Sandeen 	atomic_set(&fs_info->balance_pause_req, 0);
2295779a65a4SEric Sandeen 	atomic_set(&fs_info->balance_cancel_req, 0);
2296779a65a4SEric Sandeen 	fs_info->balance_ctl = NULL;
2297779a65a4SEric Sandeen 	init_waitqueue_head(&fs_info->balance_wait_q);
2298907d2710SDavid Sterba 	atomic_set(&fs_info->reloc_cancel_req, 0);
2299779a65a4SEric Sandeen }
2300779a65a4SEric Sandeen 
23016bccf3abSJeff Mahoney static void btrfs_init_btree_inode(struct btrfs_fs_info *fs_info)
2302f37938e0SEric Sandeen {
23032ff7e61eSJeff Mahoney 	struct inode *inode = fs_info->btree_inode;
2304e256927bSJosef Bacik 	unsigned long hash = btrfs_inode_hash(BTRFS_BTREE_INODE_OBJECTID,
2305e256927bSJosef Bacik 					      fs_info->tree_root);
23062ff7e61eSJeff Mahoney 
23072ff7e61eSJeff Mahoney 	inode->i_ino = BTRFS_BTREE_INODE_OBJECTID;
23082ff7e61eSJeff Mahoney 	set_nlink(inode, 1);
2309f37938e0SEric Sandeen 	/*
2310f37938e0SEric Sandeen 	 * we set the i_size on the btree inode to the max possible int.
2311f37938e0SEric Sandeen 	 * the real end of the address space is determined by all of
2312f37938e0SEric Sandeen 	 * the devices in the system
2313f37938e0SEric Sandeen 	 */
23142ff7e61eSJeff Mahoney 	inode->i_size = OFFSET_MAX;
23152ff7e61eSJeff Mahoney 	inode->i_mapping->a_ops = &btree_aops;
2316f37938e0SEric Sandeen 
23172ff7e61eSJeff Mahoney 	RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
231843eb5f29SQu Wenruo 	extent_io_tree_init(fs_info, &BTRFS_I(inode)->io_tree,
231935da5a7eSDavid Sterba 			    IO_TREE_BTREE_INODE_IO);
23202ff7e61eSJeff Mahoney 	extent_map_tree_init(&BTRFS_I(inode)->extent_tree);
2321f37938e0SEric Sandeen 
23225c8fd99fSJosef Bacik 	BTRFS_I(inode)->root = btrfs_grab_root(fs_info->tree_root);
2323adac5584SFilipe Manana 	BTRFS_I(inode)->location.objectid = BTRFS_BTREE_INODE_OBJECTID;
2324adac5584SFilipe Manana 	BTRFS_I(inode)->location.type = 0;
2325adac5584SFilipe Manana 	BTRFS_I(inode)->location.offset = 0;
23262ff7e61eSJeff Mahoney 	set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
2327e256927bSJosef Bacik 	__insert_inode_hash(inode, hash);
2328f37938e0SEric Sandeen }
2329f37938e0SEric Sandeen 
2330ad618368SEric Sandeen static void btrfs_init_dev_replace_locks(struct btrfs_fs_info *fs_info)
2331ad618368SEric Sandeen {
2332ad618368SEric Sandeen 	mutex_init(&fs_info->dev_replace.lock_finishing_cancel_unmount);
2333129827e3SDavid Sterba 	init_rwsem(&fs_info->dev_replace.rwsem);
23347f8d236aSDavid Sterba 	init_waitqueue_head(&fs_info->dev_replace.replace_wait);
2335ad618368SEric Sandeen }
2336ad618368SEric Sandeen 
2337f9e92e40SEric Sandeen static void btrfs_init_qgroup(struct btrfs_fs_info *fs_info)
2338f9e92e40SEric Sandeen {
2339f9e92e40SEric Sandeen 	spin_lock_init(&fs_info->qgroup_lock);
2340f9e92e40SEric Sandeen 	mutex_init(&fs_info->qgroup_ioctl_lock);
2341f9e92e40SEric Sandeen 	fs_info->qgroup_tree = RB_ROOT;
2342f9e92e40SEric Sandeen 	INIT_LIST_HEAD(&fs_info->dirty_qgroups);
2343f9e92e40SEric Sandeen 	fs_info->qgroup_seq = 1;
2344f9e92e40SEric Sandeen 	fs_info->qgroup_ulist = NULL;
2345d2c609b8SJeff Mahoney 	fs_info->qgroup_rescan_running = false;
2346011b46c3SQu Wenruo 	fs_info->qgroup_drop_subtree_thres = BTRFS_MAX_LEVEL;
2347f9e92e40SEric Sandeen 	mutex_init(&fs_info->qgroup_rescan_lock);
2348f9e92e40SEric Sandeen }
2349f9e92e40SEric Sandeen 
2350d21deec5SSu Yue static int btrfs_init_workqueues(struct btrfs_fs_info *fs_info)
23512a458198SEric Sandeen {
2352f7b885beSAnand Jain 	u32 max_active = fs_info->thread_pool_size;
23536f011058SDavid Sterba 	unsigned int flags = WQ_MEM_RECLAIM | WQ_FREEZABLE | WQ_UNBOUND;
23542a458198SEric Sandeen 
23552a458198SEric Sandeen 	fs_info->workers =
2356a31b4a43SChristoph Hellwig 		btrfs_alloc_workqueue(fs_info, "worker", flags, max_active, 16);
2357a31b4a43SChristoph Hellwig 	fs_info->hipri_workers =
2358a31b4a43SChristoph Hellwig 		btrfs_alloc_workqueue(fs_info, "worker-high",
2359cb001095SJeff Mahoney 				      flags | WQ_HIGHPRI, max_active, 16);
23602a458198SEric Sandeen 
23612a458198SEric Sandeen 	fs_info->delalloc_workers =
2362cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "delalloc",
2363cb001095SJeff Mahoney 				      flags, max_active, 2);
23642a458198SEric Sandeen 
23652a458198SEric Sandeen 	fs_info->flush_workers =
2366cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "flush_delalloc",
2367cb001095SJeff Mahoney 				      flags, max_active, 0);
23682a458198SEric Sandeen 
23692a458198SEric Sandeen 	fs_info->caching_workers =
2370cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "cache", flags, max_active, 0);
23712a458198SEric Sandeen 
23722a458198SEric Sandeen 	fs_info->fixup_workers =
2373cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "fixup", flags, 1, 0);
23742a458198SEric Sandeen 
23752a458198SEric Sandeen 	fs_info->endio_workers =
2376d7b9416fSChristoph Hellwig 		alloc_workqueue("btrfs-endio", flags, max_active);
23772a458198SEric Sandeen 	fs_info->endio_meta_workers =
2378d7b9416fSChristoph Hellwig 		alloc_workqueue("btrfs-endio-meta", flags, max_active);
2379385de0efSChristoph Hellwig 	fs_info->rmw_workers = alloc_workqueue("btrfs-rmw", flags, max_active);
23802a458198SEric Sandeen 	fs_info->endio_write_workers =
2381cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio-write", flags,
2382cb001095SJeff Mahoney 				      max_active, 2);
2383fed8a72dSChristoph Hellwig 	fs_info->compressed_write_workers =
2384fed8a72dSChristoph Hellwig 		alloc_workqueue("btrfs-compressed-write", flags, max_active);
23852a458198SEric Sandeen 	fs_info->endio_freespace_worker =
2386cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "freespace-write", flags,
2387cb001095SJeff Mahoney 				      max_active, 0);
23882a458198SEric Sandeen 	fs_info->delayed_workers =
2389cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "delayed-meta", flags,
2390cb001095SJeff Mahoney 				      max_active, 0);
23912a458198SEric Sandeen 	fs_info->qgroup_rescan_workers =
2392cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "qgroup-rescan", flags, 1, 0);
2393b0643e59SDennis Zhou 	fs_info->discard_ctl.discard_workers =
2394b0643e59SDennis Zhou 		alloc_workqueue("btrfs_discard", WQ_UNBOUND | WQ_FREEZABLE, 1);
23952a458198SEric Sandeen 
2396a31b4a43SChristoph Hellwig 	if (!(fs_info->workers && fs_info->hipri_workers &&
2397a31b4a43SChristoph Hellwig 	      fs_info->delalloc_workers && fs_info->flush_workers &&
23982a458198SEric Sandeen 	      fs_info->endio_workers && fs_info->endio_meta_workers &&
2399fed8a72dSChristoph Hellwig 	      fs_info->compressed_write_workers &&
24001a1a2851SQu Wenruo 	      fs_info->endio_write_workers &&
24012a458198SEric Sandeen 	      fs_info->endio_freespace_worker && fs_info->rmw_workers &&
2402f26c9238SQu Wenruo 	      fs_info->caching_workers && fs_info->fixup_workers &&
2403f26c9238SQu Wenruo 	      fs_info->delayed_workers && fs_info->qgroup_rescan_workers &&
2404b0643e59SDennis Zhou 	      fs_info->discard_ctl.discard_workers)) {
24052a458198SEric Sandeen 		return -ENOMEM;
24062a458198SEric Sandeen 	}
24072a458198SEric Sandeen 
24082a458198SEric Sandeen 	return 0;
24092a458198SEric Sandeen }
24102a458198SEric Sandeen 
24116d97c6e3SJohannes Thumshirn static int btrfs_init_csum_hash(struct btrfs_fs_info *fs_info, u16 csum_type)
24126d97c6e3SJohannes Thumshirn {
24136d97c6e3SJohannes Thumshirn 	struct crypto_shash *csum_shash;
2414b4e967beSDavid Sterba 	const char *csum_driver = btrfs_super_csum_driver(csum_type);
24156d97c6e3SJohannes Thumshirn 
2416b4e967beSDavid Sterba 	csum_shash = crypto_alloc_shash(csum_driver, 0, 0);
24176d97c6e3SJohannes Thumshirn 
24186d97c6e3SJohannes Thumshirn 	if (IS_ERR(csum_shash)) {
24196d97c6e3SJohannes Thumshirn 		btrfs_err(fs_info, "error allocating %s hash for checksum",
2420b4e967beSDavid Sterba 			  csum_driver);
24216d97c6e3SJohannes Thumshirn 		return PTR_ERR(csum_shash);
24226d97c6e3SJohannes Thumshirn 	}
24236d97c6e3SJohannes Thumshirn 
24246d97c6e3SJohannes Thumshirn 	fs_info->csum_shash = csum_shash;
24256d97c6e3SJohannes Thumshirn 
2426c8a5f8caSDavid Sterba 	btrfs_info(fs_info, "using %s (%s) checksum algorithm",
2427c8a5f8caSDavid Sterba 			btrfs_super_csum_name(csum_type),
2428c8a5f8caSDavid Sterba 			crypto_shash_driver_name(csum_shash));
24296d97c6e3SJohannes Thumshirn 	return 0;
24306d97c6e3SJohannes Thumshirn }
24316d97c6e3SJohannes Thumshirn 
243263443bf5SEric Sandeen static int btrfs_replay_log(struct btrfs_fs_info *fs_info,
243363443bf5SEric Sandeen 			    struct btrfs_fs_devices *fs_devices)
243463443bf5SEric Sandeen {
243563443bf5SEric Sandeen 	int ret;
2436789d6a3aSQu Wenruo 	struct btrfs_tree_parent_check check = { 0 };
243763443bf5SEric Sandeen 	struct btrfs_root *log_tree_root;
243863443bf5SEric Sandeen 	struct btrfs_super_block *disk_super = fs_info->super_copy;
243963443bf5SEric Sandeen 	u64 bytenr = btrfs_super_log_root(disk_super);
2440581c1760SQu Wenruo 	int level = btrfs_super_log_root_level(disk_super);
244163443bf5SEric Sandeen 
244263443bf5SEric Sandeen 	if (fs_devices->rw_devices == 0) {
2443f14d104dSDavid Sterba 		btrfs_warn(fs_info, "log replay required on RO media");
244463443bf5SEric Sandeen 		return -EIO;
244563443bf5SEric Sandeen 	}
244663443bf5SEric Sandeen 
244796dfcb46SJosef Bacik 	log_tree_root = btrfs_alloc_root(fs_info, BTRFS_TREE_LOG_OBJECTID,
244896dfcb46SJosef Bacik 					 GFP_KERNEL);
244963443bf5SEric Sandeen 	if (!log_tree_root)
245063443bf5SEric Sandeen 		return -ENOMEM;
245163443bf5SEric Sandeen 
2452789d6a3aSQu Wenruo 	check.level = level;
2453789d6a3aSQu Wenruo 	check.transid = fs_info->generation + 1;
2454789d6a3aSQu Wenruo 	check.owner_root = BTRFS_TREE_LOG_OBJECTID;
2455789d6a3aSQu Wenruo 	log_tree_root->node = read_tree_block(fs_info, bytenr, &check);
245664c043deSLiu Bo 	if (IS_ERR(log_tree_root->node)) {
2457f14d104dSDavid Sterba 		btrfs_warn(fs_info, "failed to read log tree");
24580eeff236SLiu Bo 		ret = PTR_ERR(log_tree_root->node);
24598c38938cSJosef Bacik 		log_tree_root->node = NULL;
246000246528SJosef Bacik 		btrfs_put_root(log_tree_root);
24610eeff236SLiu Bo 		return ret;
24624eb150d6SQu Wenruo 	}
24634eb150d6SQu Wenruo 	if (!extent_buffer_uptodate(log_tree_root->node)) {
2464f14d104dSDavid Sterba 		btrfs_err(fs_info, "failed to read log tree");
246500246528SJosef Bacik 		btrfs_put_root(log_tree_root);
246663443bf5SEric Sandeen 		return -EIO;
246763443bf5SEric Sandeen 	}
24684eb150d6SQu Wenruo 
246963443bf5SEric Sandeen 	/* returns with log_tree_root freed on success */
247063443bf5SEric Sandeen 	ret = btrfs_recover_log_trees(log_tree_root);
247163443bf5SEric Sandeen 	if (ret) {
24720b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, ret,
247363443bf5SEric Sandeen 				      "Failed to recover log tree");
247400246528SJosef Bacik 		btrfs_put_root(log_tree_root);
247563443bf5SEric Sandeen 		return ret;
247663443bf5SEric Sandeen 	}
247763443bf5SEric Sandeen 
2478bc98a42cSDavid Howells 	if (sb_rdonly(fs_info->sb)) {
24796bccf3abSJeff Mahoney 		ret = btrfs_commit_super(fs_info);
248063443bf5SEric Sandeen 		if (ret)
248163443bf5SEric Sandeen 			return ret;
248263443bf5SEric Sandeen 	}
248363443bf5SEric Sandeen 
248463443bf5SEric Sandeen 	return 0;
248563443bf5SEric Sandeen }
248663443bf5SEric Sandeen 
2487abed4aaaSJosef Bacik static int load_global_roots_objectid(struct btrfs_root *tree_root,
2488abed4aaaSJosef Bacik 				      struct btrfs_path *path, u64 objectid,
2489abed4aaaSJosef Bacik 				      const char *name)
2490abed4aaaSJosef Bacik {
2491abed4aaaSJosef Bacik 	struct btrfs_fs_info *fs_info = tree_root->fs_info;
2492abed4aaaSJosef Bacik 	struct btrfs_root *root;
2493f7238e50SJosef Bacik 	u64 max_global_id = 0;
2494abed4aaaSJosef Bacik 	int ret;
2495abed4aaaSJosef Bacik 	struct btrfs_key key = {
2496abed4aaaSJosef Bacik 		.objectid = objectid,
2497abed4aaaSJosef Bacik 		.type = BTRFS_ROOT_ITEM_KEY,
2498abed4aaaSJosef Bacik 		.offset = 0,
2499abed4aaaSJosef Bacik 	};
2500abed4aaaSJosef Bacik 	bool found = false;
2501abed4aaaSJosef Bacik 
2502abed4aaaSJosef Bacik 	/* If we have IGNOREDATACSUMS skip loading these roots. */
2503abed4aaaSJosef Bacik 	if (objectid == BTRFS_CSUM_TREE_OBJECTID &&
2504abed4aaaSJosef Bacik 	    btrfs_test_opt(fs_info, IGNOREDATACSUMS)) {
2505abed4aaaSJosef Bacik 		set_bit(BTRFS_FS_STATE_NO_CSUMS, &fs_info->fs_state);
2506abed4aaaSJosef Bacik 		return 0;
2507abed4aaaSJosef Bacik 	}
2508abed4aaaSJosef Bacik 
2509abed4aaaSJosef Bacik 	while (1) {
2510abed4aaaSJosef Bacik 		ret = btrfs_search_slot(NULL, tree_root, &key, path, 0, 0);
2511abed4aaaSJosef Bacik 		if (ret < 0)
2512abed4aaaSJosef Bacik 			break;
2513abed4aaaSJosef Bacik 
2514abed4aaaSJosef Bacik 		if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
2515abed4aaaSJosef Bacik 			ret = btrfs_next_leaf(tree_root, path);
2516abed4aaaSJosef Bacik 			if (ret) {
2517abed4aaaSJosef Bacik 				if (ret > 0)
2518abed4aaaSJosef Bacik 					ret = 0;
2519abed4aaaSJosef Bacik 				break;
2520abed4aaaSJosef Bacik 			}
2521abed4aaaSJosef Bacik 		}
2522abed4aaaSJosef Bacik 		ret = 0;
2523abed4aaaSJosef Bacik 
2524abed4aaaSJosef Bacik 		btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
2525abed4aaaSJosef Bacik 		if (key.objectid != objectid)
2526abed4aaaSJosef Bacik 			break;
2527abed4aaaSJosef Bacik 		btrfs_release_path(path);
2528abed4aaaSJosef Bacik 
2529f7238e50SJosef Bacik 		/*
2530f7238e50SJosef Bacik 		 * Just worry about this for extent tree, it'll be the same for
2531f7238e50SJosef Bacik 		 * everybody.
2532f7238e50SJosef Bacik 		 */
2533f7238e50SJosef Bacik 		if (objectid == BTRFS_EXTENT_TREE_OBJECTID)
2534f7238e50SJosef Bacik 			max_global_id = max(max_global_id, key.offset);
2535f7238e50SJosef Bacik 
2536abed4aaaSJosef Bacik 		found = true;
2537abed4aaaSJosef Bacik 		root = read_tree_root_path(tree_root, path, &key);
2538abed4aaaSJosef Bacik 		if (IS_ERR(root)) {
2539abed4aaaSJosef Bacik 			if (!btrfs_test_opt(fs_info, IGNOREBADROOTS))
2540abed4aaaSJosef Bacik 				ret = PTR_ERR(root);
2541abed4aaaSJosef Bacik 			break;
2542abed4aaaSJosef Bacik 		}
2543abed4aaaSJosef Bacik 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2544abed4aaaSJosef Bacik 		ret = btrfs_global_root_insert(root);
2545abed4aaaSJosef Bacik 		if (ret) {
2546abed4aaaSJosef Bacik 			btrfs_put_root(root);
2547abed4aaaSJosef Bacik 			break;
2548abed4aaaSJosef Bacik 		}
2549abed4aaaSJosef Bacik 		key.offset++;
2550abed4aaaSJosef Bacik 	}
2551abed4aaaSJosef Bacik 	btrfs_release_path(path);
2552abed4aaaSJosef Bacik 
2553f7238e50SJosef Bacik 	if (objectid == BTRFS_EXTENT_TREE_OBJECTID)
2554f7238e50SJosef Bacik 		fs_info->nr_global_roots = max_global_id + 1;
2555f7238e50SJosef Bacik 
2556abed4aaaSJosef Bacik 	if (!found || ret) {
2557abed4aaaSJosef Bacik 		if (objectid == BTRFS_CSUM_TREE_OBJECTID)
2558abed4aaaSJosef Bacik 			set_bit(BTRFS_FS_STATE_NO_CSUMS, &fs_info->fs_state);
2559abed4aaaSJosef Bacik 
2560abed4aaaSJosef Bacik 		if (!btrfs_test_opt(fs_info, IGNOREBADROOTS))
2561abed4aaaSJosef Bacik 			ret = ret ? ret : -ENOENT;
2562abed4aaaSJosef Bacik 		else
2563abed4aaaSJosef Bacik 			ret = 0;
2564abed4aaaSJosef Bacik 		btrfs_err(fs_info, "failed to load root %s", name);
2565abed4aaaSJosef Bacik 	}
2566abed4aaaSJosef Bacik 	return ret;
2567abed4aaaSJosef Bacik }
2568abed4aaaSJosef Bacik 
2569abed4aaaSJosef Bacik static int load_global_roots(struct btrfs_root *tree_root)
2570abed4aaaSJosef Bacik {
2571abed4aaaSJosef Bacik 	struct btrfs_path *path;
2572abed4aaaSJosef Bacik 	int ret = 0;
2573abed4aaaSJosef Bacik 
2574abed4aaaSJosef Bacik 	path = btrfs_alloc_path();
2575abed4aaaSJosef Bacik 	if (!path)
2576abed4aaaSJosef Bacik 		return -ENOMEM;
2577abed4aaaSJosef Bacik 
2578abed4aaaSJosef Bacik 	ret = load_global_roots_objectid(tree_root, path,
2579abed4aaaSJosef Bacik 					 BTRFS_EXTENT_TREE_OBJECTID, "extent");
2580abed4aaaSJosef Bacik 	if (ret)
2581abed4aaaSJosef Bacik 		goto out;
2582abed4aaaSJosef Bacik 	ret = load_global_roots_objectid(tree_root, path,
2583abed4aaaSJosef Bacik 					 BTRFS_CSUM_TREE_OBJECTID, "csum");
2584abed4aaaSJosef Bacik 	if (ret)
2585abed4aaaSJosef Bacik 		goto out;
2586abed4aaaSJosef Bacik 	if (!btrfs_fs_compat_ro(tree_root->fs_info, FREE_SPACE_TREE))
2587abed4aaaSJosef Bacik 		goto out;
2588abed4aaaSJosef Bacik 	ret = load_global_roots_objectid(tree_root, path,
2589abed4aaaSJosef Bacik 					 BTRFS_FREE_SPACE_TREE_OBJECTID,
2590abed4aaaSJosef Bacik 					 "free space");
2591abed4aaaSJosef Bacik out:
2592abed4aaaSJosef Bacik 	btrfs_free_path(path);
2593abed4aaaSJosef Bacik 	return ret;
2594abed4aaaSJosef Bacik }
2595abed4aaaSJosef Bacik 
25966bccf3abSJeff Mahoney static int btrfs_read_roots(struct btrfs_fs_info *fs_info)
25974bbcaa64SEric Sandeen {
25986bccf3abSJeff Mahoney 	struct btrfs_root *tree_root = fs_info->tree_root;
2599a4f3d2c4SDavid Sterba 	struct btrfs_root *root;
26004bbcaa64SEric Sandeen 	struct btrfs_key location;
26014bbcaa64SEric Sandeen 	int ret;
26024bbcaa64SEric Sandeen 
26036bccf3abSJeff Mahoney 	BUG_ON(!fs_info->tree_root);
26046bccf3abSJeff Mahoney 
2605abed4aaaSJosef Bacik 	ret = load_global_roots(tree_root);
2606abed4aaaSJosef Bacik 	if (ret)
2607abed4aaaSJosef Bacik 		return ret;
2608abed4aaaSJosef Bacik 
26094bbcaa64SEric Sandeen 	location.type = BTRFS_ROOT_ITEM_KEY;
26104bbcaa64SEric Sandeen 	location.offset = 0;
26114bbcaa64SEric Sandeen 
26121c56ab99SQu Wenruo 	if (btrfs_fs_compat_ro(fs_info, BLOCK_GROUP_TREE)) {
261314033b08SQu Wenruo 		location.objectid = BTRFS_BLOCK_GROUP_TREE_OBJECTID;
261414033b08SQu Wenruo 		root = btrfs_read_tree_root(tree_root, &location);
261514033b08SQu Wenruo 		if (IS_ERR(root)) {
261614033b08SQu Wenruo 			if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
261714033b08SQu Wenruo 				ret = PTR_ERR(root);
261814033b08SQu Wenruo 				goto out;
261914033b08SQu Wenruo 			}
262014033b08SQu Wenruo 		} else {
262114033b08SQu Wenruo 			set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
262214033b08SQu Wenruo 			fs_info->block_group_root = root;
262314033b08SQu Wenruo 		}
262414033b08SQu Wenruo 	}
262514033b08SQu Wenruo 
262614033b08SQu Wenruo 	location.objectid = BTRFS_DEV_TREE_OBJECTID;
2627a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2628f50f4353SLiu Bo 	if (IS_ERR(root)) {
262942437a63SJosef Bacik 		if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2630f50f4353SLiu Bo 			ret = PTR_ERR(root);
2631f50f4353SLiu Bo 			goto out;
2632f50f4353SLiu Bo 		}
263342437a63SJosef Bacik 	} else {
2634a4f3d2c4SDavid Sterba 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2635a4f3d2c4SDavid Sterba 		fs_info->dev_root = root;
263642437a63SJosef Bacik 	}
2637820a49daSJosef Bacik 	/* Initialize fs_info for all devices in any case */
2638a8d1b164SJohannes Thumshirn 	ret = btrfs_init_devices_late(fs_info);
2639a8d1b164SJohannes Thumshirn 	if (ret)
2640a8d1b164SJohannes Thumshirn 		goto out;
26414bbcaa64SEric Sandeen 
2642aeb935a4SQu Wenruo 	/*
2643aeb935a4SQu Wenruo 	 * This tree can share blocks with some other fs tree during relocation
2644aeb935a4SQu Wenruo 	 * and we need a proper setup by btrfs_get_fs_root
2645aeb935a4SQu Wenruo 	 */
264656e9357aSDavid Sterba 	root = btrfs_get_fs_root(tree_root->fs_info,
264756e9357aSDavid Sterba 				 BTRFS_DATA_RELOC_TREE_OBJECTID, true);
2648aeb935a4SQu Wenruo 	if (IS_ERR(root)) {
264942437a63SJosef Bacik 		if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2650aeb935a4SQu Wenruo 			ret = PTR_ERR(root);
2651aeb935a4SQu Wenruo 			goto out;
2652aeb935a4SQu Wenruo 		}
265342437a63SJosef Bacik 	} else {
2654aeb935a4SQu Wenruo 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2655aeb935a4SQu Wenruo 		fs_info->data_reloc_root = root;
265642437a63SJosef Bacik 	}
2657aeb935a4SQu Wenruo 
26584bbcaa64SEric Sandeen 	location.objectid = BTRFS_QUOTA_TREE_OBJECTID;
2659a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2660a4f3d2c4SDavid Sterba 	if (!IS_ERR(root)) {
2661a4f3d2c4SDavid Sterba 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2662afcdd129SJosef Bacik 		set_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags);
2663a4f3d2c4SDavid Sterba 		fs_info->quota_root = root;
26644bbcaa64SEric Sandeen 	}
26654bbcaa64SEric Sandeen 
26664bbcaa64SEric Sandeen 	location.objectid = BTRFS_UUID_TREE_OBJECTID;
2667a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2668a4f3d2c4SDavid Sterba 	if (IS_ERR(root)) {
266942437a63SJosef Bacik 		if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2670a4f3d2c4SDavid Sterba 			ret = PTR_ERR(root);
26714bbcaa64SEric Sandeen 			if (ret != -ENOENT)
2672f50f4353SLiu Bo 				goto out;
267342437a63SJosef Bacik 		}
26744bbcaa64SEric Sandeen 	} else {
2675a4f3d2c4SDavid Sterba 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2676a4f3d2c4SDavid Sterba 		fs_info->uuid_root = root;
26774bbcaa64SEric Sandeen 	}
26784bbcaa64SEric Sandeen 
26794bbcaa64SEric Sandeen 	return 0;
2680f50f4353SLiu Bo out:
2681f50f4353SLiu Bo 	btrfs_warn(fs_info, "failed to read root (objectid=%llu): %d",
2682f50f4353SLiu Bo 		   location.objectid, ret);
2683f50f4353SLiu Bo 	return ret;
26844bbcaa64SEric Sandeen }
26854bbcaa64SEric Sandeen 
2686069ec957SQu Wenruo /*
2687069ec957SQu Wenruo  * Real super block validation
2688069ec957SQu Wenruo  * NOTE: super csum type and incompat features will not be checked here.
2689069ec957SQu Wenruo  *
2690069ec957SQu Wenruo  * @sb:		super block to check
2691069ec957SQu Wenruo  * @mirror_num:	the super block number to check its bytenr:
2692069ec957SQu Wenruo  * 		0	the primary (1st) sb
2693069ec957SQu Wenruo  * 		1, 2	2nd and 3rd backup copy
2694069ec957SQu Wenruo  * 	       -1	skip bytenr check
2695069ec957SQu Wenruo  */
2696a05d3c91SQu Wenruo int btrfs_validate_super(struct btrfs_fs_info *fs_info,
2697069ec957SQu Wenruo 			 struct btrfs_super_block *sb, int mirror_num)
269821a852b0SQu Wenruo {
269921a852b0SQu Wenruo 	u64 nodesize = btrfs_super_nodesize(sb);
270021a852b0SQu Wenruo 	u64 sectorsize = btrfs_super_sectorsize(sb);
270121a852b0SQu Wenruo 	int ret = 0;
270221a852b0SQu Wenruo 
270321a852b0SQu Wenruo 	if (btrfs_super_magic(sb) != BTRFS_MAGIC) {
270421a852b0SQu Wenruo 		btrfs_err(fs_info, "no valid FS found");
270521a852b0SQu Wenruo 		ret = -EINVAL;
270621a852b0SQu Wenruo 	}
270721a852b0SQu Wenruo 	if (btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP) {
270821a852b0SQu Wenruo 		btrfs_err(fs_info, "unrecognized or unsupported super flag: %llu",
270921a852b0SQu Wenruo 				btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP);
271021a852b0SQu Wenruo 		ret = -EINVAL;
271121a852b0SQu Wenruo 	}
271221a852b0SQu Wenruo 	if (btrfs_super_root_level(sb) >= BTRFS_MAX_LEVEL) {
271321a852b0SQu Wenruo 		btrfs_err(fs_info, "tree_root level too big: %d >= %d",
271421a852b0SQu Wenruo 				btrfs_super_root_level(sb), BTRFS_MAX_LEVEL);
271521a852b0SQu Wenruo 		ret = -EINVAL;
271621a852b0SQu Wenruo 	}
271721a852b0SQu Wenruo 	if (btrfs_super_chunk_root_level(sb) >= BTRFS_MAX_LEVEL) {
271821a852b0SQu Wenruo 		btrfs_err(fs_info, "chunk_root level too big: %d >= %d",
271921a852b0SQu Wenruo 				btrfs_super_chunk_root_level(sb), BTRFS_MAX_LEVEL);
272021a852b0SQu Wenruo 		ret = -EINVAL;
272121a852b0SQu Wenruo 	}
272221a852b0SQu Wenruo 	if (btrfs_super_log_root_level(sb) >= BTRFS_MAX_LEVEL) {
272321a852b0SQu Wenruo 		btrfs_err(fs_info, "log_root level too big: %d >= %d",
272421a852b0SQu Wenruo 				btrfs_super_log_root_level(sb), BTRFS_MAX_LEVEL);
272521a852b0SQu Wenruo 		ret = -EINVAL;
272621a852b0SQu Wenruo 	}
272721a852b0SQu Wenruo 
272821a852b0SQu Wenruo 	/*
272921a852b0SQu Wenruo 	 * Check sectorsize and nodesize first, other check will need it.
273021a852b0SQu Wenruo 	 * Check all possible sectorsize(4K, 8K, 16K, 32K, 64K) here.
273121a852b0SQu Wenruo 	 */
273221a852b0SQu Wenruo 	if (!is_power_of_2(sectorsize) || sectorsize < 4096 ||
273321a852b0SQu Wenruo 	    sectorsize > BTRFS_MAX_METADATA_BLOCKSIZE) {
273421a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid sectorsize %llu", sectorsize);
273521a852b0SQu Wenruo 		ret = -EINVAL;
273621a852b0SQu Wenruo 	}
27370bb3eb3eSQu Wenruo 
27380bb3eb3eSQu Wenruo 	/*
27391a42daabSQu Wenruo 	 * We only support at most two sectorsizes: 4K and PAGE_SIZE.
27401a42daabSQu Wenruo 	 *
27411a42daabSQu Wenruo 	 * We can support 16K sectorsize with 64K page size without problem,
27421a42daabSQu Wenruo 	 * but such sectorsize/pagesize combination doesn't make much sense.
27431a42daabSQu Wenruo 	 * 4K will be our future standard, PAGE_SIZE is supported from the very
27441a42daabSQu Wenruo 	 * beginning.
27450bb3eb3eSQu Wenruo 	 */
27461a42daabSQu Wenruo 	if (sectorsize > PAGE_SIZE || (sectorsize != SZ_4K && sectorsize != PAGE_SIZE)) {
274721a852b0SQu Wenruo 		btrfs_err(fs_info,
27480bb3eb3eSQu Wenruo 			"sectorsize %llu not yet supported for page size %lu",
274921a852b0SQu Wenruo 			sectorsize, PAGE_SIZE);
275021a852b0SQu Wenruo 		ret = -EINVAL;
275121a852b0SQu Wenruo 	}
27520bb3eb3eSQu Wenruo 
275321a852b0SQu Wenruo 	if (!is_power_of_2(nodesize) || nodesize < sectorsize ||
275421a852b0SQu Wenruo 	    nodesize > BTRFS_MAX_METADATA_BLOCKSIZE) {
275521a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid nodesize %llu", nodesize);
275621a852b0SQu Wenruo 		ret = -EINVAL;
275721a852b0SQu Wenruo 	}
275821a852b0SQu Wenruo 	if (nodesize != le32_to_cpu(sb->__unused_leafsize)) {
275921a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid leafsize %u, should be %llu",
276021a852b0SQu Wenruo 			  le32_to_cpu(sb->__unused_leafsize), nodesize);
276121a852b0SQu Wenruo 		ret = -EINVAL;
276221a852b0SQu Wenruo 	}
276321a852b0SQu Wenruo 
276421a852b0SQu Wenruo 	/* Root alignment check */
276521a852b0SQu Wenruo 	if (!IS_ALIGNED(btrfs_super_root(sb), sectorsize)) {
276621a852b0SQu Wenruo 		btrfs_warn(fs_info, "tree_root block unaligned: %llu",
276721a852b0SQu Wenruo 			   btrfs_super_root(sb));
276821a852b0SQu Wenruo 		ret = -EINVAL;
276921a852b0SQu Wenruo 	}
277021a852b0SQu Wenruo 	if (!IS_ALIGNED(btrfs_super_chunk_root(sb), sectorsize)) {
277121a852b0SQu Wenruo 		btrfs_warn(fs_info, "chunk_root block unaligned: %llu",
277221a852b0SQu Wenruo 			   btrfs_super_chunk_root(sb));
277321a852b0SQu Wenruo 		ret = -EINVAL;
277421a852b0SQu Wenruo 	}
277521a852b0SQu Wenruo 	if (!IS_ALIGNED(btrfs_super_log_root(sb), sectorsize)) {
277621a852b0SQu Wenruo 		btrfs_warn(fs_info, "log_root block unaligned: %llu",
277721a852b0SQu Wenruo 			   btrfs_super_log_root(sb));
277821a852b0SQu Wenruo 		ret = -EINVAL;
277921a852b0SQu Wenruo 	}
278021a852b0SQu Wenruo 
2781aefd7f70SNikolay Borisov 	if (memcmp(fs_info->fs_devices->fsid, fs_info->super_copy->fsid,
2782aefd7f70SNikolay Borisov 		   BTRFS_FSID_SIZE)) {
2783aefd7f70SNikolay Borisov 		btrfs_err(fs_info,
2784aefd7f70SNikolay Borisov 		"superblock fsid doesn't match fsid of fs_devices: %pU != %pU",
2785aefd7f70SNikolay Borisov 			fs_info->super_copy->fsid, fs_info->fs_devices->fsid);
2786aefd7f70SNikolay Borisov 		ret = -EINVAL;
2787aefd7f70SNikolay Borisov 	}
2788aefd7f70SNikolay Borisov 
2789aefd7f70SNikolay Borisov 	if (btrfs_fs_incompat(fs_info, METADATA_UUID) &&
2790aefd7f70SNikolay Borisov 	    memcmp(fs_info->fs_devices->metadata_uuid,
2791aefd7f70SNikolay Borisov 		   fs_info->super_copy->metadata_uuid, BTRFS_FSID_SIZE)) {
2792aefd7f70SNikolay Borisov 		btrfs_err(fs_info,
2793aefd7f70SNikolay Borisov "superblock metadata_uuid doesn't match metadata uuid of fs_devices: %pU != %pU",
2794aefd7f70SNikolay Borisov 			fs_info->super_copy->metadata_uuid,
2795aefd7f70SNikolay Borisov 			fs_info->fs_devices->metadata_uuid);
2796aefd7f70SNikolay Borisov 		ret = -EINVAL;
2797aefd7f70SNikolay Borisov 	}
2798aefd7f70SNikolay Borisov 
27991c56ab99SQu Wenruo 	/*
28001c56ab99SQu Wenruo 	 * Artificial requirement for block-group-tree to force newer features
28011c56ab99SQu Wenruo 	 * (free-space-tree, no-holes) so the test matrix is smaller.
28021c56ab99SQu Wenruo 	 */
28031c56ab99SQu Wenruo 	if (btrfs_fs_compat_ro(fs_info, BLOCK_GROUP_TREE) &&
28041c56ab99SQu Wenruo 	    (!btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE_VALID) ||
28051c56ab99SQu Wenruo 	     !btrfs_fs_incompat(fs_info, NO_HOLES))) {
28061c56ab99SQu Wenruo 		btrfs_err(fs_info,
28071c56ab99SQu Wenruo 		"block-group-tree feature requires fres-space-tree and no-holes");
28081c56ab99SQu Wenruo 		ret = -EINVAL;
28091c56ab99SQu Wenruo 	}
28101c56ab99SQu Wenruo 
2811de37aa51SNikolay Borisov 	if (memcmp(fs_info->fs_devices->metadata_uuid, sb->dev_item.fsid,
28127239ff4bSNikolay Borisov 		   BTRFS_FSID_SIZE) != 0) {
281321a852b0SQu Wenruo 		btrfs_err(fs_info,
28147239ff4bSNikolay Borisov 			"dev_item UUID does not match metadata fsid: %pU != %pU",
2815de37aa51SNikolay Borisov 			fs_info->fs_devices->metadata_uuid, sb->dev_item.fsid);
281621a852b0SQu Wenruo 		ret = -EINVAL;
281721a852b0SQu Wenruo 	}
281821a852b0SQu Wenruo 
281921a852b0SQu Wenruo 	/*
282021a852b0SQu Wenruo 	 * Hint to catch really bogus numbers, bitflips or so, more exact checks are
282121a852b0SQu Wenruo 	 * done later
282221a852b0SQu Wenruo 	 */
282321a852b0SQu Wenruo 	if (btrfs_super_bytes_used(sb) < 6 * btrfs_super_nodesize(sb)) {
282421a852b0SQu Wenruo 		btrfs_err(fs_info, "bytes_used is too small %llu",
282521a852b0SQu Wenruo 			  btrfs_super_bytes_used(sb));
282621a852b0SQu Wenruo 		ret = -EINVAL;
282721a852b0SQu Wenruo 	}
282821a852b0SQu Wenruo 	if (!is_power_of_2(btrfs_super_stripesize(sb))) {
282921a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid stripesize %u",
283021a852b0SQu Wenruo 			  btrfs_super_stripesize(sb));
283121a852b0SQu Wenruo 		ret = -EINVAL;
283221a852b0SQu Wenruo 	}
283321a852b0SQu Wenruo 	if (btrfs_super_num_devices(sb) > (1UL << 31))
283421a852b0SQu Wenruo 		btrfs_warn(fs_info, "suspicious number of devices: %llu",
283521a852b0SQu Wenruo 			   btrfs_super_num_devices(sb));
283621a852b0SQu Wenruo 	if (btrfs_super_num_devices(sb) == 0) {
283721a852b0SQu Wenruo 		btrfs_err(fs_info, "number of devices is 0");
283821a852b0SQu Wenruo 		ret = -EINVAL;
283921a852b0SQu Wenruo 	}
284021a852b0SQu Wenruo 
2841069ec957SQu Wenruo 	if (mirror_num >= 0 &&
2842069ec957SQu Wenruo 	    btrfs_super_bytenr(sb) != btrfs_sb_offset(mirror_num)) {
284321a852b0SQu Wenruo 		btrfs_err(fs_info, "super offset mismatch %llu != %u",
284421a852b0SQu Wenruo 			  btrfs_super_bytenr(sb), BTRFS_SUPER_INFO_OFFSET);
284521a852b0SQu Wenruo 		ret = -EINVAL;
284621a852b0SQu Wenruo 	}
284721a852b0SQu Wenruo 
284821a852b0SQu Wenruo 	/*
284921a852b0SQu Wenruo 	 * Obvious sys_chunk_array corruptions, it must hold at least one key
285021a852b0SQu Wenruo 	 * and one chunk
285121a852b0SQu Wenruo 	 */
285221a852b0SQu Wenruo 	if (btrfs_super_sys_array_size(sb) > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
285321a852b0SQu Wenruo 		btrfs_err(fs_info, "system chunk array too big %u > %u",
285421a852b0SQu Wenruo 			  btrfs_super_sys_array_size(sb),
285521a852b0SQu Wenruo 			  BTRFS_SYSTEM_CHUNK_ARRAY_SIZE);
285621a852b0SQu Wenruo 		ret = -EINVAL;
285721a852b0SQu Wenruo 	}
285821a852b0SQu Wenruo 	if (btrfs_super_sys_array_size(sb) < sizeof(struct btrfs_disk_key)
285921a852b0SQu Wenruo 			+ sizeof(struct btrfs_chunk)) {
286021a852b0SQu Wenruo 		btrfs_err(fs_info, "system chunk array too small %u < %zu",
286121a852b0SQu Wenruo 			  btrfs_super_sys_array_size(sb),
286221a852b0SQu Wenruo 			  sizeof(struct btrfs_disk_key)
286321a852b0SQu Wenruo 			  + sizeof(struct btrfs_chunk));
286421a852b0SQu Wenruo 		ret = -EINVAL;
286521a852b0SQu Wenruo 	}
286621a852b0SQu Wenruo 
286721a852b0SQu Wenruo 	/*
286821a852b0SQu Wenruo 	 * The generation is a global counter, we'll trust it more than the others
286921a852b0SQu Wenruo 	 * but it's still possible that it's the one that's wrong.
287021a852b0SQu Wenruo 	 */
287121a852b0SQu Wenruo 	if (btrfs_super_generation(sb) < btrfs_super_chunk_root_generation(sb))
287221a852b0SQu Wenruo 		btrfs_warn(fs_info,
287321a852b0SQu Wenruo 			"suspicious: generation < chunk_root_generation: %llu < %llu",
287421a852b0SQu Wenruo 			btrfs_super_generation(sb),
287521a852b0SQu Wenruo 			btrfs_super_chunk_root_generation(sb));
287621a852b0SQu Wenruo 	if (btrfs_super_generation(sb) < btrfs_super_cache_generation(sb)
287721a852b0SQu Wenruo 	    && btrfs_super_cache_generation(sb) != (u64)-1)
287821a852b0SQu Wenruo 		btrfs_warn(fs_info,
287921a852b0SQu Wenruo 			"suspicious: generation < cache_generation: %llu < %llu",
288021a852b0SQu Wenruo 			btrfs_super_generation(sb),
288121a852b0SQu Wenruo 			btrfs_super_cache_generation(sb));
288221a852b0SQu Wenruo 
288321a852b0SQu Wenruo 	return ret;
288421a852b0SQu Wenruo }
288521a852b0SQu Wenruo 
2886069ec957SQu Wenruo /*
2887069ec957SQu Wenruo  * Validation of super block at mount time.
2888069ec957SQu Wenruo  * Some checks already done early at mount time, like csum type and incompat
2889069ec957SQu Wenruo  * flags will be skipped.
2890069ec957SQu Wenruo  */
2891069ec957SQu Wenruo static int btrfs_validate_mount_super(struct btrfs_fs_info *fs_info)
2892069ec957SQu Wenruo {
2893a05d3c91SQu Wenruo 	return btrfs_validate_super(fs_info, fs_info->super_copy, 0);
2894069ec957SQu Wenruo }
2895069ec957SQu Wenruo 
289675cb857dSQu Wenruo /*
289775cb857dSQu Wenruo  * Validation of super block at write time.
289875cb857dSQu Wenruo  * Some checks like bytenr check will be skipped as their values will be
289975cb857dSQu Wenruo  * overwritten soon.
290075cb857dSQu Wenruo  * Extra checks like csum type and incompat flags will be done here.
290175cb857dSQu Wenruo  */
290275cb857dSQu Wenruo static int btrfs_validate_write_super(struct btrfs_fs_info *fs_info,
290375cb857dSQu Wenruo 				      struct btrfs_super_block *sb)
290475cb857dSQu Wenruo {
290575cb857dSQu Wenruo 	int ret;
290675cb857dSQu Wenruo 
2907a05d3c91SQu Wenruo 	ret = btrfs_validate_super(fs_info, sb, -1);
290875cb857dSQu Wenruo 	if (ret < 0)
290975cb857dSQu Wenruo 		goto out;
2910e7e16f48SJohannes Thumshirn 	if (!btrfs_supported_super_csum(btrfs_super_csum_type(sb))) {
291175cb857dSQu Wenruo 		ret = -EUCLEAN;
291275cb857dSQu Wenruo 		btrfs_err(fs_info, "invalid csum type, has %u want %u",
291375cb857dSQu Wenruo 			  btrfs_super_csum_type(sb), BTRFS_CSUM_TYPE_CRC32);
291475cb857dSQu Wenruo 		goto out;
291575cb857dSQu Wenruo 	}
291675cb857dSQu Wenruo 	if (btrfs_super_incompat_flags(sb) & ~BTRFS_FEATURE_INCOMPAT_SUPP) {
291775cb857dSQu Wenruo 		ret = -EUCLEAN;
291875cb857dSQu Wenruo 		btrfs_err(fs_info,
291975cb857dSQu Wenruo 		"invalid incompat flags, has 0x%llx valid mask 0x%llx",
292075cb857dSQu Wenruo 			  btrfs_super_incompat_flags(sb),
292175cb857dSQu Wenruo 			  (unsigned long long)BTRFS_FEATURE_INCOMPAT_SUPP);
292275cb857dSQu Wenruo 		goto out;
292375cb857dSQu Wenruo 	}
292475cb857dSQu Wenruo out:
292575cb857dSQu Wenruo 	if (ret < 0)
292675cb857dSQu Wenruo 		btrfs_err(fs_info,
292775cb857dSQu Wenruo 		"super block corruption detected before writing it to disk");
292875cb857dSQu Wenruo 	return ret;
292975cb857dSQu Wenruo }
293075cb857dSQu Wenruo 
2931bd676446SJosef Bacik static int load_super_root(struct btrfs_root *root, u64 bytenr, u64 gen, int level)
2932bd676446SJosef Bacik {
2933789d6a3aSQu Wenruo 	struct btrfs_tree_parent_check check = {
2934789d6a3aSQu Wenruo 		.level = level,
2935789d6a3aSQu Wenruo 		.transid = gen,
2936789d6a3aSQu Wenruo 		.owner_root = root->root_key.objectid
2937789d6a3aSQu Wenruo 	};
2938bd676446SJosef Bacik 	int ret = 0;
2939bd676446SJosef Bacik 
2940789d6a3aSQu Wenruo 	root->node = read_tree_block(root->fs_info, bytenr, &check);
2941bd676446SJosef Bacik 	if (IS_ERR(root->node)) {
2942bd676446SJosef Bacik 		ret = PTR_ERR(root->node);
2943bd676446SJosef Bacik 		root->node = NULL;
29444eb150d6SQu Wenruo 		return ret;
29454eb150d6SQu Wenruo 	}
29464eb150d6SQu Wenruo 	if (!extent_buffer_uptodate(root->node)) {
2947bd676446SJosef Bacik 		free_extent_buffer(root->node);
2948bd676446SJosef Bacik 		root->node = NULL;
29494eb150d6SQu Wenruo 		return -EIO;
2950bd676446SJosef Bacik 	}
2951bd676446SJosef Bacik 
2952bd676446SJosef Bacik 	btrfs_set_root_node(&root->root_item, root->node);
2953bd676446SJosef Bacik 	root->commit_root = btrfs_root_node(root);
2954bd676446SJosef Bacik 	btrfs_set_root_refs(&root->root_item, 1);
2955bd676446SJosef Bacik 	return ret;
2956bd676446SJosef Bacik }
2957bd676446SJosef Bacik 
2958bd676446SJosef Bacik static int load_important_roots(struct btrfs_fs_info *fs_info)
2959bd676446SJosef Bacik {
2960bd676446SJosef Bacik 	struct btrfs_super_block *sb = fs_info->super_copy;
2961bd676446SJosef Bacik 	u64 gen, bytenr;
2962bd676446SJosef Bacik 	int level, ret;
2963bd676446SJosef Bacik 
2964bd676446SJosef Bacik 	bytenr = btrfs_super_root(sb);
2965bd676446SJosef Bacik 	gen = btrfs_super_generation(sb);
2966bd676446SJosef Bacik 	level = btrfs_super_root_level(sb);
2967bd676446SJosef Bacik 	ret = load_super_root(fs_info->tree_root, bytenr, gen, level);
29689c54e80dSJosef Bacik 	if (ret) {
2969bd676446SJosef Bacik 		btrfs_warn(fs_info, "couldn't read tree root");
2970bd676446SJosef Bacik 		return ret;
2971bd676446SJosef Bacik 	}
29729c54e80dSJosef Bacik 	return 0;
29739c54e80dSJosef Bacik }
29749c54e80dSJosef Bacik 
29756ef108ddSNikolay Borisov static int __cold init_tree_roots(struct btrfs_fs_info *fs_info)
2976b8522a1eSNikolay Borisov {
29776ef108ddSNikolay Borisov 	int backup_index = find_newest_super_backup(fs_info);
2978b8522a1eSNikolay Borisov 	struct btrfs_super_block *sb = fs_info->super_copy;
2979b8522a1eSNikolay Borisov 	struct btrfs_root *tree_root = fs_info->tree_root;
2980b8522a1eSNikolay Borisov 	bool handle_error = false;
2981b8522a1eSNikolay Borisov 	int ret = 0;
2982b8522a1eSNikolay Borisov 	int i;
2983b8522a1eSNikolay Borisov 
2984b8522a1eSNikolay Borisov 	for (i = 0; i < BTRFS_NUM_BACKUP_ROOTS; i++) {
2985b8522a1eSNikolay Borisov 		if (handle_error) {
2986b8522a1eSNikolay Borisov 			if (!IS_ERR(tree_root->node))
2987b8522a1eSNikolay Borisov 				free_extent_buffer(tree_root->node);
2988b8522a1eSNikolay Borisov 			tree_root->node = NULL;
2989b8522a1eSNikolay Borisov 
2990b8522a1eSNikolay Borisov 			if (!btrfs_test_opt(fs_info, USEBACKUPROOT))
2991b8522a1eSNikolay Borisov 				break;
2992b8522a1eSNikolay Borisov 
2993b8522a1eSNikolay Borisov 			free_root_pointers(fs_info, 0);
2994b8522a1eSNikolay Borisov 
2995b8522a1eSNikolay Borisov 			/*
2996b8522a1eSNikolay Borisov 			 * Don't use the log in recovery mode, it won't be
2997b8522a1eSNikolay Borisov 			 * valid
2998b8522a1eSNikolay Borisov 			 */
2999b8522a1eSNikolay Borisov 			btrfs_set_super_log_root(sb, 0);
3000b8522a1eSNikolay Borisov 
3001b8522a1eSNikolay Borisov 			/* We can't trust the free space cache either */
3002b8522a1eSNikolay Borisov 			btrfs_set_opt(fs_info->mount_opt, CLEAR_CACHE);
3003b8522a1eSNikolay Borisov 
3004b8522a1eSNikolay Borisov 			ret = read_backup_root(fs_info, i);
30056ef108ddSNikolay Borisov 			backup_index = ret;
3006b8522a1eSNikolay Borisov 			if (ret < 0)
3007b8522a1eSNikolay Borisov 				return ret;
3008b8522a1eSNikolay Borisov 		}
3009b8522a1eSNikolay Borisov 
3010bd676446SJosef Bacik 		ret = load_important_roots(fs_info);
3011bd676446SJosef Bacik 		if (ret) {
3012217f5004SNikolay Borisov 			handle_error = true;
3013b8522a1eSNikolay Borisov 			continue;
3014b8522a1eSNikolay Borisov 		}
3015b8522a1eSNikolay Borisov 
3016336a0d8dSNikolay Borisov 		/*
3017336a0d8dSNikolay Borisov 		 * No need to hold btrfs_root::objectid_mutex since the fs
3018336a0d8dSNikolay Borisov 		 * hasn't been fully initialised and we are the only user
3019336a0d8dSNikolay Borisov 		 */
3020453e4873SNikolay Borisov 		ret = btrfs_init_root_free_objectid(tree_root);
3021b8522a1eSNikolay Borisov 		if (ret < 0) {
3022b8522a1eSNikolay Borisov 			handle_error = true;
3023b8522a1eSNikolay Borisov 			continue;
3024b8522a1eSNikolay Borisov 		}
3025b8522a1eSNikolay Borisov 
30266b8fad57SNikolay Borisov 		ASSERT(tree_root->free_objectid <= BTRFS_LAST_FREE_OBJECTID);
3027b8522a1eSNikolay Borisov 
3028b8522a1eSNikolay Borisov 		ret = btrfs_read_roots(fs_info);
3029b8522a1eSNikolay Borisov 		if (ret < 0) {
3030b8522a1eSNikolay Borisov 			handle_error = true;
3031b8522a1eSNikolay Borisov 			continue;
3032b8522a1eSNikolay Borisov 		}
3033b8522a1eSNikolay Borisov 
3034b8522a1eSNikolay Borisov 		/* All successful */
3035bd676446SJosef Bacik 		fs_info->generation = btrfs_header_generation(tree_root->node);
3036bd676446SJosef Bacik 		fs_info->last_trans_committed = fs_info->generation;
3037d96b3424SFilipe Manana 		fs_info->last_reloc_trans = 0;
30386ef108ddSNikolay Borisov 
30396ef108ddSNikolay Borisov 		/* Always begin writing backup roots after the one being used */
30406ef108ddSNikolay Borisov 		if (backup_index < 0) {
30416ef108ddSNikolay Borisov 			fs_info->backup_root_index = 0;
30426ef108ddSNikolay Borisov 		} else {
30436ef108ddSNikolay Borisov 			fs_info->backup_root_index = backup_index + 1;
30446ef108ddSNikolay Borisov 			fs_info->backup_root_index %= BTRFS_NUM_BACKUP_ROOTS;
30456ef108ddSNikolay Borisov 		}
3046b8522a1eSNikolay Borisov 		break;
3047b8522a1eSNikolay Borisov 	}
3048b8522a1eSNikolay Borisov 
3049b8522a1eSNikolay Borisov 	return ret;
3050b8522a1eSNikolay Borisov }
3051b8522a1eSNikolay Borisov 
30528260edbaSJosef Bacik void btrfs_init_fs_info(struct btrfs_fs_info *fs_info)
3053eb60ceacSChris Mason {
3054fc7cbcd4SDavid Sterba 	INIT_RADIX_TREE(&fs_info->fs_roots_radix, GFP_ATOMIC);
305501cd3909SDavid Sterba 	INIT_RADIX_TREE(&fs_info->buffer_radix, GFP_ATOMIC);
30568fd17795SChris Mason 	INIT_LIST_HEAD(&fs_info->trans_list);
3057facda1e7SChris Mason 	INIT_LIST_HEAD(&fs_info->dead_roots);
305824bbcf04SYan, Zheng 	INIT_LIST_HEAD(&fs_info->delayed_iputs);
3059eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&fs_info->delalloc_roots);
306011833d66SYan Zheng 	INIT_LIST_HEAD(&fs_info->caching_block_groups);
3061eb73c1b7SMiao Xie 	spin_lock_init(&fs_info->delalloc_root_lock);
3062a4abeea4SJosef Bacik 	spin_lock_init(&fs_info->trans_lock);
3063fc7cbcd4SDavid Sterba 	spin_lock_init(&fs_info->fs_roots_radix_lock);
306424bbcf04SYan, Zheng 	spin_lock_init(&fs_info->delayed_iput_lock);
30654cb5300bSChris Mason 	spin_lock_init(&fs_info->defrag_inodes_lock);
3066ceda0864SMiao Xie 	spin_lock_init(&fs_info->super_lock);
3067f28491e0SJosef Bacik 	spin_lock_init(&fs_info->buffer_lock);
306847ab2a6cSJosef Bacik 	spin_lock_init(&fs_info->unused_bgs_lock);
306940ab3be1SNaohiro Aota 	spin_lock_init(&fs_info->treelog_bg_lock);
3070afba2bc0SNaohiro Aota 	spin_lock_init(&fs_info->zone_active_bgs_lock);
3071c2707a25SJohannes Thumshirn 	spin_lock_init(&fs_info->relocation_bg_lock);
3072f29021b2SJan Schmidt 	rwlock_init(&fs_info->tree_mod_log_lock);
3073abed4aaaSJosef Bacik 	rwlock_init(&fs_info->global_root_lock);
3074d7c15171SZhao Lei 	mutex_init(&fs_info->unused_bg_unpin_mutex);
3075f3372065SJohannes Thumshirn 	mutex_init(&fs_info->reclaim_bgs_lock);
30767585717fSChris Mason 	mutex_init(&fs_info->reloc_mutex);
3077573bfb72SMiao Xie 	mutex_init(&fs_info->delalloc_root_mutex);
30780bc09ca1SNaohiro Aota 	mutex_init(&fs_info->zoned_meta_io_lock);
30795f0addf7SNaohiro Aota 	mutex_init(&fs_info->zoned_data_reloc_io_lock);
3080de98ced9SMiao Xie 	seqlock_init(&fs_info->profiles_lock);
308119c00ddcSChris Mason 
3082e1489b4fSIoannis Angelakopoulos 	btrfs_lockdep_init_map(fs_info, btrfs_trans_num_writers);
30835a9ba670SIoannis Angelakopoulos 	btrfs_lockdep_init_map(fs_info, btrfs_trans_num_extwriters);
30848b53779eSIoannis Angelakopoulos 	btrfs_lockdep_init_map(fs_info, btrfs_trans_pending_ordered);
30855f4403e1SIoannis Angelakopoulos 	btrfs_lockdep_init_map(fs_info, btrfs_ordered_extent);
30863e738c53SIoannis Angelakopoulos 	btrfs_state_lockdep_init_map(fs_info, btrfs_trans_commit_start,
30873e738c53SIoannis Angelakopoulos 				     BTRFS_LOCKDEP_TRANS_COMMIT_START);
30883e738c53SIoannis Angelakopoulos 	btrfs_state_lockdep_init_map(fs_info, btrfs_trans_unblocked,
30893e738c53SIoannis Angelakopoulos 				     BTRFS_LOCKDEP_TRANS_UNBLOCKED);
30903e738c53SIoannis Angelakopoulos 	btrfs_state_lockdep_init_map(fs_info, btrfs_trans_super_committed,
30913e738c53SIoannis Angelakopoulos 				     BTRFS_LOCKDEP_TRANS_SUPER_COMMITTED);
30923e738c53SIoannis Angelakopoulos 	btrfs_state_lockdep_init_map(fs_info, btrfs_trans_completed,
30933e738c53SIoannis Angelakopoulos 				     BTRFS_LOCKDEP_TRANS_COMPLETED);
3094e1489b4fSIoannis Angelakopoulos 
30950b86a832SChris Mason 	INIT_LIST_HEAD(&fs_info->dirty_cowonly_roots);
30966324fbf3SChris Mason 	INIT_LIST_HEAD(&fs_info->space_info);
3097f29021b2SJan Schmidt 	INIT_LIST_HEAD(&fs_info->tree_mod_seq_list);
309847ab2a6cSJosef Bacik 	INIT_LIST_HEAD(&fs_info->unused_bgs);
309918bb8bbfSJohannes Thumshirn 	INIT_LIST_HEAD(&fs_info->reclaim_bgs);
3100afba2bc0SNaohiro Aota 	INIT_LIST_HEAD(&fs_info->zone_active_bgs);
3101bd647ce3SJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
3102bd647ce3SJosef Bacik 	INIT_LIST_HEAD(&fs_info->allocated_roots);
31033fd63727SJosef Bacik 	INIT_LIST_HEAD(&fs_info->allocated_ebs);
31043fd63727SJosef Bacik 	spin_lock_init(&fs_info->eb_leak_lock);
3105bd647ce3SJosef Bacik #endif
3106c8bf1b67SDavid Sterba 	extent_map_tree_init(&fs_info->mapping_tree);
310766d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->global_block_rsv,
310866d8f3ddSMiao Xie 			     BTRFS_BLOCK_RSV_GLOBAL);
310966d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->trans_block_rsv, BTRFS_BLOCK_RSV_TRANS);
311066d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->chunk_block_rsv, BTRFS_BLOCK_RSV_CHUNK);
311166d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->empty_block_rsv, BTRFS_BLOCK_RSV_EMPTY);
311266d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->delayed_block_rsv,
311366d8f3ddSMiao Xie 			     BTRFS_BLOCK_RSV_DELOPS);
3114ba2c4d4eSJosef Bacik 	btrfs_init_block_rsv(&fs_info->delayed_refs_rsv,
3115ba2c4d4eSJosef Bacik 			     BTRFS_BLOCK_RSV_DELREFS);
3116ba2c4d4eSJosef Bacik 
3117771ed689SChris Mason 	atomic_set(&fs_info->async_delalloc_pages, 0);
31184cb5300bSChris Mason 	atomic_set(&fs_info->defrag_running, 0);
3119034f784dSJosef Bacik 	atomic_set(&fs_info->nr_delayed_iputs, 0);
3120fc36ed7eSJan Schmidt 	atomic64_set(&fs_info->tree_mod_seq, 0);
3121abed4aaaSJosef Bacik 	fs_info->global_root_tree = RB_ROOT;
312295ac567aSFilipe David Borba Manana 	fs_info->max_inline = BTRFS_DEFAULT_MAX_INLINE;
31239ed74f2dSJosef Bacik 	fs_info->metadata_ratio = 0;
31244cb5300bSChris Mason 	fs_info->defrag_inodes = RB_ROOT;
3125a5ed45f8SNikolay Borisov 	atomic64_set(&fs_info->free_chunk_space, 0);
3126f29021b2SJan Schmidt 	fs_info->tree_mod_log = RB_ROOT;
31278b87dc17SDavid Sterba 	fs_info->commit_interval = BTRFS_DEFAULT_COMMIT_INTERVAL;
3128f8c269d7SDavid Sterba 	fs_info->avg_delayed_ref_runtime = NSEC_PER_SEC >> 6; /* div by 64 */
3129fd708b81SJosef Bacik 	btrfs_init_ref_verify(fs_info);
3130c8b97818SChris Mason 
3131b34b086cSChris Mason 	fs_info->thread_pool_size = min_t(unsigned long,
3132b34b086cSChris Mason 					  num_online_cpus() + 2, 8);
31330afbaf8cSChris Mason 
3134199c2a9cSMiao Xie 	INIT_LIST_HEAD(&fs_info->ordered_roots);
3135199c2a9cSMiao Xie 	spin_lock_init(&fs_info->ordered_root_lock);
313669fe2d75SJosef Bacik 
3137638aa7edSEric Sandeen 	btrfs_init_scrub(fs_info);
313821adbd5cSStefan Behrens #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
313921adbd5cSStefan Behrens 	fs_info->check_integrity_print_mask = 0;
314021adbd5cSStefan Behrens #endif
3141779a65a4SEric Sandeen 	btrfs_init_balance(fs_info);
314257056740SJosef Bacik 	btrfs_init_async_reclaim_work(fs_info);
3143a2de733cSArne Jansen 
314416b0c258SFilipe Manana 	rwlock_init(&fs_info->block_group_cache_lock);
314508dddb29SFilipe Manana 	fs_info->block_group_cache_tree = RB_ROOT_CACHED;
31460f9dd46cSJosef Bacik 
3147fe119a6eSNikolay Borisov 	extent_io_tree_init(fs_info, &fs_info->excluded_extents,
314835da5a7eSDavid Sterba 			    IO_TREE_FS_EXCLUDED_EXTENTS);
314939279cc3SChris Mason 
31505a3f23d5SChris Mason 	mutex_init(&fs_info->ordered_operations_mutex);
3151e02119d5SChris Mason 	mutex_init(&fs_info->tree_log_mutex);
3152925baeddSChris Mason 	mutex_init(&fs_info->chunk_mutex);
3153a74a4b97SChris Mason 	mutex_init(&fs_info->transaction_kthread_mutex);
3154a74a4b97SChris Mason 	mutex_init(&fs_info->cleaner_mutex);
31551bbc621eSChris Mason 	mutex_init(&fs_info->ro_block_group_mutex);
31569e351cc8SJosef Bacik 	init_rwsem(&fs_info->commit_root_sem);
3157c71bf099SYan, Zheng 	init_rwsem(&fs_info->cleanup_work_sem);
315876dda93cSYan, Zheng 	init_rwsem(&fs_info->subvol_sem);
3159803b2f54SStefan Behrens 	sema_init(&fs_info->uuid_tree_rescan_sem, 1);
3160fa9c0d79SChris Mason 
3161ad618368SEric Sandeen 	btrfs_init_dev_replace_locks(fs_info);
3162f9e92e40SEric Sandeen 	btrfs_init_qgroup(fs_info);
3163b0643e59SDennis Zhou 	btrfs_discard_init(fs_info);
3164416ac51dSArne Jansen 
3165fa9c0d79SChris Mason 	btrfs_init_free_cluster(&fs_info->meta_alloc_cluster);
3166fa9c0d79SChris Mason 	btrfs_init_free_cluster(&fs_info->data_alloc_cluster);
3167fa9c0d79SChris Mason 
3168e6dcd2dcSChris Mason 	init_waitqueue_head(&fs_info->transaction_throttle);
3169f9295749SChris Mason 	init_waitqueue_head(&fs_info->transaction_wait);
3170bb9c12c9SSage Weil 	init_waitqueue_head(&fs_info->transaction_blocked_wait);
31714854ddd0SChris Mason 	init_waitqueue_head(&fs_info->async_submit_wait);
3172034f784dSJosef Bacik 	init_waitqueue_head(&fs_info->delayed_iputs_wait);
31733768f368SChris Mason 
3174da17066cSJeff Mahoney 	/* Usable values until the real ones are cached from the superblock */
3175da17066cSJeff Mahoney 	fs_info->nodesize = 4096;
3176da17066cSJeff Mahoney 	fs_info->sectorsize = 4096;
3177ab108d99SDavid Sterba 	fs_info->sectorsize_bits = ilog2(4096);
3178da17066cSJeff Mahoney 	fs_info->stripesize = 4096;
3179da17066cSJeff Mahoney 
3180f7b12a62SNaohiro Aota 	fs_info->max_extent_size = BTRFS_MAX_EXTENT_SIZE;
3181f7b12a62SNaohiro Aota 
3182eede2bf3SOmar Sandoval 	spin_lock_init(&fs_info->swapfile_pins_lock);
3183eede2bf3SOmar Sandoval 	fs_info->swapfile_pins = RB_ROOT;
3184eede2bf3SOmar Sandoval 
318518bb8bbfSJohannes Thumshirn 	fs_info->bg_reclaim_threshold = BTRFS_DEFAULT_RECLAIM_THRESH;
318618bb8bbfSJohannes Thumshirn 	INIT_WORK(&fs_info->reclaim_bgs_work, btrfs_reclaim_bgs_work);
31878260edbaSJosef Bacik }
31888260edbaSJosef Bacik 
31898260edbaSJosef Bacik static int init_mount_fs_info(struct btrfs_fs_info *fs_info, struct super_block *sb)
31908260edbaSJosef Bacik {
31918260edbaSJosef Bacik 	int ret;
31928260edbaSJosef Bacik 
31938260edbaSJosef Bacik 	fs_info->sb = sb;
31948260edbaSJosef Bacik 	sb->s_blocksize = BTRFS_BDEV_BLOCKSIZE;
31958260edbaSJosef Bacik 	sb->s_blocksize_bits = blksize_bits(BTRFS_BDEV_BLOCKSIZE);
31969e967495SFilipe Manana 
31975deb17e1SJosef Bacik 	ret = percpu_counter_init(&fs_info->ordered_bytes, 0, GFP_KERNEL);
3198ae18c37aSJosef Bacik 	if (ret)
3199ae18c37aSJosef Bacik 		return ret;
3200ae18c37aSJosef Bacik 
3201ae18c37aSJosef Bacik 	ret = percpu_counter_init(&fs_info->dirty_metadata_bytes, 0, GFP_KERNEL);
3202ae18c37aSJosef Bacik 	if (ret)
3203c75e8394SJosef Bacik 		return ret;
3204ae18c37aSJosef Bacik 
3205ae18c37aSJosef Bacik 	fs_info->dirty_metadata_batch = PAGE_SIZE *
3206ae18c37aSJosef Bacik 					(1 + ilog2(nr_cpu_ids));
3207ae18c37aSJosef Bacik 
3208ae18c37aSJosef Bacik 	ret = percpu_counter_init(&fs_info->delalloc_bytes, 0, GFP_KERNEL);
3209ae18c37aSJosef Bacik 	if (ret)
3210c75e8394SJosef Bacik 		return ret;
3211ae18c37aSJosef Bacik 
3212ae18c37aSJosef Bacik 	ret = percpu_counter_init(&fs_info->dev_replace.bio_counter, 0,
3213ae18c37aSJosef Bacik 			GFP_KERNEL);
3214ae18c37aSJosef Bacik 	if (ret)
3215c75e8394SJosef Bacik 		return ret;
3216ae18c37aSJosef Bacik 
3217ae18c37aSJosef Bacik 	fs_info->delayed_root = kmalloc(sizeof(struct btrfs_delayed_root),
3218ae18c37aSJosef Bacik 					GFP_KERNEL);
3219c75e8394SJosef Bacik 	if (!fs_info->delayed_root)
3220c75e8394SJosef Bacik 		return -ENOMEM;
3221ae18c37aSJosef Bacik 	btrfs_init_delayed_root(fs_info->delayed_root);
3222ae18c37aSJosef Bacik 
3223a0a1db70SFilipe Manana 	if (sb_rdonly(sb))
3224a0a1db70SFilipe Manana 		set_bit(BTRFS_FS_STATE_RO, &fs_info->fs_state);
3225a0a1db70SFilipe Manana 
3226c75e8394SJosef Bacik 	return btrfs_alloc_stripe_hash_table(fs_info);
3227ae18c37aSJosef Bacik }
3228ae18c37aSJosef Bacik 
322997f4dd09SNikolay Borisov static int btrfs_uuid_rescan_kthread(void *data)
323097f4dd09SNikolay Borisov {
32310d031dc4SYu Zhe 	struct btrfs_fs_info *fs_info = data;
323297f4dd09SNikolay Borisov 	int ret;
323397f4dd09SNikolay Borisov 
323497f4dd09SNikolay Borisov 	/*
323597f4dd09SNikolay Borisov 	 * 1st step is to iterate through the existing UUID tree and
323697f4dd09SNikolay Borisov 	 * to delete all entries that contain outdated data.
323797f4dd09SNikolay Borisov 	 * 2nd step is to add all missing entries to the UUID tree.
323897f4dd09SNikolay Borisov 	 */
323997f4dd09SNikolay Borisov 	ret = btrfs_uuid_tree_iterate(fs_info);
324097f4dd09SNikolay Borisov 	if (ret < 0) {
3241c94bec2cSJosef Bacik 		if (ret != -EINTR)
3242c94bec2cSJosef Bacik 			btrfs_warn(fs_info, "iterating uuid_tree failed %d",
3243c94bec2cSJosef Bacik 				   ret);
324497f4dd09SNikolay Borisov 		up(&fs_info->uuid_tree_rescan_sem);
324597f4dd09SNikolay Borisov 		return ret;
324697f4dd09SNikolay Borisov 	}
324797f4dd09SNikolay Borisov 	return btrfs_uuid_scan_kthread(data);
324897f4dd09SNikolay Borisov }
324997f4dd09SNikolay Borisov 
325097f4dd09SNikolay Borisov static int btrfs_check_uuid_tree(struct btrfs_fs_info *fs_info)
325197f4dd09SNikolay Borisov {
325297f4dd09SNikolay Borisov 	struct task_struct *task;
325397f4dd09SNikolay Borisov 
325497f4dd09SNikolay Borisov 	down(&fs_info->uuid_tree_rescan_sem);
325597f4dd09SNikolay Borisov 	task = kthread_run(btrfs_uuid_rescan_kthread, fs_info, "btrfs-uuid");
325697f4dd09SNikolay Borisov 	if (IS_ERR(task)) {
325797f4dd09SNikolay Borisov 		/* fs_info->update_uuid_tree_gen remains 0 in all error case */
325897f4dd09SNikolay Borisov 		btrfs_warn(fs_info, "failed to start uuid_rescan task");
325997f4dd09SNikolay Borisov 		up(&fs_info->uuid_tree_rescan_sem);
326097f4dd09SNikolay Borisov 		return PTR_ERR(task);
326197f4dd09SNikolay Borisov 	}
326297f4dd09SNikolay Borisov 
326397f4dd09SNikolay Borisov 	return 0;
326497f4dd09SNikolay Borisov }
326597f4dd09SNikolay Borisov 
326644c0ca21SBoris Burkov /*
32678cd29088SBoris Burkov  * Some options only have meaning at mount time and shouldn't persist across
32688cd29088SBoris Burkov  * remounts, or be displayed. Clear these at the end of mount and remount
32698cd29088SBoris Burkov  * code paths.
32708cd29088SBoris Burkov  */
32718cd29088SBoris Burkov void btrfs_clear_oneshot_options(struct btrfs_fs_info *fs_info)
32728cd29088SBoris Burkov {
32738cd29088SBoris Burkov 	btrfs_clear_opt(fs_info->mount_opt, USEBACKUPROOT);
32748b228324SBoris Burkov 	btrfs_clear_opt(fs_info->mount_opt, CLEAR_CACHE);
32758cd29088SBoris Burkov }
32768cd29088SBoris Burkov 
32778cd29088SBoris Burkov /*
327844c0ca21SBoris Burkov  * Mounting logic specific to read-write file systems. Shared by open_ctree
327944c0ca21SBoris Burkov  * and btrfs_remount when remounting from read-only to read-write.
328044c0ca21SBoris Burkov  */
328144c0ca21SBoris Burkov int btrfs_start_pre_rw_mount(struct btrfs_fs_info *fs_info)
328244c0ca21SBoris Burkov {
328344c0ca21SBoris Burkov 	int ret;
328494846229SBoris Burkov 	const bool cache_opt = btrfs_test_opt(fs_info, SPACE_CACHE);
32858b228324SBoris Burkov 	bool clear_free_space_tree = false;
32868b228324SBoris Burkov 
32878b228324SBoris Burkov 	if (btrfs_test_opt(fs_info, CLEAR_CACHE) &&
32888b228324SBoris Burkov 	    btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
32898b228324SBoris Burkov 		clear_free_space_tree = true;
32908b228324SBoris Burkov 	} else if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE) &&
32918b228324SBoris Burkov 		   !btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE_VALID)) {
32928b228324SBoris Burkov 		btrfs_warn(fs_info, "free space tree is invalid");
32938b228324SBoris Burkov 		clear_free_space_tree = true;
32948b228324SBoris Burkov 	}
32958b228324SBoris Burkov 
32968b228324SBoris Burkov 	if (clear_free_space_tree) {
32978b228324SBoris Burkov 		btrfs_info(fs_info, "clearing free space tree");
32988b228324SBoris Burkov 		ret = btrfs_clear_free_space_tree(fs_info);
32998b228324SBoris Burkov 		if (ret) {
33008b228324SBoris Burkov 			btrfs_warn(fs_info,
33018b228324SBoris Burkov 				   "failed to clear free space tree: %d", ret);
33028b228324SBoris Burkov 			goto out;
33038b228324SBoris Burkov 		}
33048b228324SBoris Burkov 	}
330544c0ca21SBoris Burkov 
33068d488a8cSFilipe Manana 	/*
33078d488a8cSFilipe Manana 	 * btrfs_find_orphan_roots() is responsible for finding all the dead
33088d488a8cSFilipe Manana 	 * roots (with 0 refs), flag them with BTRFS_ROOT_DEAD_TREE and load
3309fc7cbcd4SDavid Sterba 	 * them into the fs_info->fs_roots_radix tree. This must be done before
33108d488a8cSFilipe Manana 	 * calling btrfs_orphan_cleanup() on the tree root. If we don't do it
33118d488a8cSFilipe Manana 	 * first, then btrfs_orphan_cleanup() will delete a dead root's orphan
33128d488a8cSFilipe Manana 	 * item before the root's tree is deleted - this means that if we unmount
33138d488a8cSFilipe Manana 	 * or crash before the deletion completes, on the next mount we will not
33148d488a8cSFilipe Manana 	 * delete what remains of the tree because the orphan item does not
33158d488a8cSFilipe Manana 	 * exists anymore, which is what tells us we have a pending deletion.
33168d488a8cSFilipe Manana 	 */
33178d488a8cSFilipe Manana 	ret = btrfs_find_orphan_roots(fs_info);
33188d488a8cSFilipe Manana 	if (ret)
33198d488a8cSFilipe Manana 		goto out;
33208d488a8cSFilipe Manana 
332144c0ca21SBoris Burkov 	ret = btrfs_cleanup_fs_roots(fs_info);
332244c0ca21SBoris Burkov 	if (ret)
332344c0ca21SBoris Burkov 		goto out;
332444c0ca21SBoris Burkov 
33258f1c21d7SBoris Burkov 	down_read(&fs_info->cleanup_work_sem);
33268f1c21d7SBoris Burkov 	if ((ret = btrfs_orphan_cleanup(fs_info->fs_root)) ||
33278f1c21d7SBoris Burkov 	    (ret = btrfs_orphan_cleanup(fs_info->tree_root))) {
33288f1c21d7SBoris Burkov 		up_read(&fs_info->cleanup_work_sem);
33298f1c21d7SBoris Burkov 		goto out;
33308f1c21d7SBoris Burkov 	}
33318f1c21d7SBoris Burkov 	up_read(&fs_info->cleanup_work_sem);
33328f1c21d7SBoris Burkov 
333344c0ca21SBoris Burkov 	mutex_lock(&fs_info->cleaner_mutex);
33347eefae6bSJosef Bacik 	ret = btrfs_recover_relocation(fs_info);
333544c0ca21SBoris Burkov 	mutex_unlock(&fs_info->cleaner_mutex);
333644c0ca21SBoris Burkov 	if (ret < 0) {
333744c0ca21SBoris Burkov 		btrfs_warn(fs_info, "failed to recover relocation: %d", ret);
333844c0ca21SBoris Burkov 		goto out;
333944c0ca21SBoris Burkov 	}
334044c0ca21SBoris Burkov 
33415011139aSBoris Burkov 	if (btrfs_test_opt(fs_info, FREE_SPACE_TREE) &&
33425011139aSBoris Burkov 	    !btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
33435011139aSBoris Burkov 		btrfs_info(fs_info, "creating free space tree");
33445011139aSBoris Burkov 		ret = btrfs_create_free_space_tree(fs_info);
33455011139aSBoris Burkov 		if (ret) {
33465011139aSBoris Burkov 			btrfs_warn(fs_info,
33475011139aSBoris Burkov 				"failed to create free space tree: %d", ret);
33485011139aSBoris Burkov 			goto out;
33495011139aSBoris Burkov 		}
33505011139aSBoris Burkov 	}
33515011139aSBoris Burkov 
335294846229SBoris Burkov 	if (cache_opt != btrfs_free_space_cache_v1_active(fs_info)) {
335394846229SBoris Burkov 		ret = btrfs_set_free_space_cache_v1_active(fs_info, cache_opt);
335494846229SBoris Burkov 		if (ret)
335594846229SBoris Burkov 			goto out;
335694846229SBoris Burkov 	}
335794846229SBoris Burkov 
335844c0ca21SBoris Burkov 	ret = btrfs_resume_balance_async(fs_info);
335944c0ca21SBoris Burkov 	if (ret)
336044c0ca21SBoris Burkov 		goto out;
336144c0ca21SBoris Burkov 
336244c0ca21SBoris Burkov 	ret = btrfs_resume_dev_replace_async(fs_info);
336344c0ca21SBoris Burkov 	if (ret) {
336444c0ca21SBoris Burkov 		btrfs_warn(fs_info, "failed to resume dev_replace");
336544c0ca21SBoris Burkov 		goto out;
336644c0ca21SBoris Burkov 	}
336744c0ca21SBoris Burkov 
336844c0ca21SBoris Burkov 	btrfs_qgroup_rescan_resume(fs_info);
336944c0ca21SBoris Burkov 
337044c0ca21SBoris Burkov 	if (!fs_info->uuid_root) {
337144c0ca21SBoris Burkov 		btrfs_info(fs_info, "creating UUID tree");
337244c0ca21SBoris Burkov 		ret = btrfs_create_uuid_tree(fs_info);
337344c0ca21SBoris Burkov 		if (ret) {
337444c0ca21SBoris Burkov 			btrfs_warn(fs_info,
337544c0ca21SBoris Burkov 				   "failed to create the UUID tree %d", ret);
337644c0ca21SBoris Burkov 			goto out;
337744c0ca21SBoris Burkov 		}
337844c0ca21SBoris Burkov 	}
337944c0ca21SBoris Burkov 
338044c0ca21SBoris Burkov out:
338144c0ca21SBoris Burkov 	return ret;
338244c0ca21SBoris Burkov }
338344c0ca21SBoris Burkov 
3384d7f67ac9SQu Wenruo /*
3385d7f67ac9SQu Wenruo  * Do various sanity and dependency checks of different features.
3386d7f67ac9SQu Wenruo  *
3387*2ba48b20SQu Wenruo  * @is_rw_mount:	If the mount is read-write.
3388*2ba48b20SQu Wenruo  *
3389d7f67ac9SQu Wenruo  * This is the place for less strict checks (like for subpage or artificial
3390d7f67ac9SQu Wenruo  * feature dependencies).
3391d7f67ac9SQu Wenruo  *
3392d7f67ac9SQu Wenruo  * For strict checks or possible corruption detection, see
3393d7f67ac9SQu Wenruo  * btrfs_validate_super().
3394d7f67ac9SQu Wenruo  *
3395d7f67ac9SQu Wenruo  * This should be called after btrfs_parse_options(), as some mount options
3396d7f67ac9SQu Wenruo  * (space cache related) can modify on-disk format like free space tree and
3397d7f67ac9SQu Wenruo  * screw up certain feature dependencies.
3398d7f67ac9SQu Wenruo  */
3399*2ba48b20SQu Wenruo int btrfs_check_features(struct btrfs_fs_info *fs_info, bool is_rw_mount)
3400d7f67ac9SQu Wenruo {
3401d7f67ac9SQu Wenruo 	struct btrfs_super_block *disk_super = fs_info->super_copy;
3402d7f67ac9SQu Wenruo 	u64 incompat = btrfs_super_incompat_flags(disk_super);
3403d7f67ac9SQu Wenruo 	const u64 compat_ro = btrfs_super_compat_ro_flags(disk_super);
3404d7f67ac9SQu Wenruo 	const u64 compat_ro_unsupp = (compat_ro & ~BTRFS_FEATURE_COMPAT_RO_SUPP);
3405d7f67ac9SQu Wenruo 
3406d7f67ac9SQu Wenruo 	if (incompat & ~BTRFS_FEATURE_INCOMPAT_SUPP) {
3407d7f67ac9SQu Wenruo 		btrfs_err(fs_info,
3408d7f67ac9SQu Wenruo 		"cannot mount because of unknown incompat features (0x%llx)",
3409d7f67ac9SQu Wenruo 		    incompat);
3410d7f67ac9SQu Wenruo 		return -EINVAL;
3411d7f67ac9SQu Wenruo 	}
3412d7f67ac9SQu Wenruo 
3413d7f67ac9SQu Wenruo 	/* Runtime limitation for mixed block groups. */
3414d7f67ac9SQu Wenruo 	if ((incompat & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS) &&
3415d7f67ac9SQu Wenruo 	    (fs_info->sectorsize != fs_info->nodesize)) {
3416d7f67ac9SQu Wenruo 		btrfs_err(fs_info,
3417d7f67ac9SQu Wenruo "unequal nodesize/sectorsize (%u != %u) are not allowed for mixed block groups",
3418d7f67ac9SQu Wenruo 			fs_info->nodesize, fs_info->sectorsize);
3419d7f67ac9SQu Wenruo 		return -EINVAL;
3420d7f67ac9SQu Wenruo 	}
3421d7f67ac9SQu Wenruo 
3422d7f67ac9SQu Wenruo 	/* Mixed backref is an always-enabled feature. */
3423d7f67ac9SQu Wenruo 	incompat |= BTRFS_FEATURE_INCOMPAT_MIXED_BACKREF;
3424d7f67ac9SQu Wenruo 
3425d7f67ac9SQu Wenruo 	/* Set compression related flags just in case. */
3426d7f67ac9SQu Wenruo 	if (fs_info->compress_type == BTRFS_COMPRESS_LZO)
3427d7f67ac9SQu Wenruo 		incompat |= BTRFS_FEATURE_INCOMPAT_COMPRESS_LZO;
3428d7f67ac9SQu Wenruo 	else if (fs_info->compress_type == BTRFS_COMPRESS_ZSTD)
3429d7f67ac9SQu Wenruo 		incompat |= BTRFS_FEATURE_INCOMPAT_COMPRESS_ZSTD;
3430d7f67ac9SQu Wenruo 
3431d7f67ac9SQu Wenruo 	/*
3432d7f67ac9SQu Wenruo 	 * An ancient flag, which should really be marked deprecated.
3433d7f67ac9SQu Wenruo 	 * Such runtime limitation doesn't really need a incompat flag.
3434d7f67ac9SQu Wenruo 	 */
3435d7f67ac9SQu Wenruo 	if (btrfs_super_nodesize(disk_super) > PAGE_SIZE)
3436d7f67ac9SQu Wenruo 		incompat |= BTRFS_FEATURE_INCOMPAT_BIG_METADATA;
3437d7f67ac9SQu Wenruo 
3438*2ba48b20SQu Wenruo 	if (compat_ro_unsupp && is_rw_mount) {
3439d7f67ac9SQu Wenruo 		btrfs_err(fs_info,
3440d7f67ac9SQu Wenruo 	"cannot mount read-write because of unknown compat_ro features (0x%llx)",
3441d7f67ac9SQu Wenruo 		       compat_ro);
3442d7f67ac9SQu Wenruo 		return -EINVAL;
3443d7f67ac9SQu Wenruo 	}
3444d7f67ac9SQu Wenruo 
3445d7f67ac9SQu Wenruo 	/*
3446d7f67ac9SQu Wenruo 	 * We have unsupported RO compat features, although RO mounted, we
3447d7f67ac9SQu Wenruo 	 * should not cause any metadata writes, including log replay.
3448d7f67ac9SQu Wenruo 	 * Or we could screw up whatever the new feature requires.
3449d7f67ac9SQu Wenruo 	 */
3450d7f67ac9SQu Wenruo 	if (compat_ro_unsupp && btrfs_super_log_root(disk_super) &&
3451d7f67ac9SQu Wenruo 	    !btrfs_test_opt(fs_info, NOLOGREPLAY)) {
3452d7f67ac9SQu Wenruo 		btrfs_err(fs_info,
3453d7f67ac9SQu Wenruo "cannot replay dirty log with unsupported compat_ro features (0x%llx), try rescue=nologreplay",
3454d7f67ac9SQu Wenruo 			  compat_ro);
3455d7f67ac9SQu Wenruo 		return -EINVAL;
3456d7f67ac9SQu Wenruo 	}
3457d7f67ac9SQu Wenruo 
3458d7f67ac9SQu Wenruo 	/*
3459d7f67ac9SQu Wenruo 	 * Artificial limitations for block group tree, to force
3460d7f67ac9SQu Wenruo 	 * block-group-tree to rely on no-holes and free-space-tree.
3461d7f67ac9SQu Wenruo 	 */
3462d7f67ac9SQu Wenruo 	if (btrfs_fs_compat_ro(fs_info, BLOCK_GROUP_TREE) &&
3463d7f67ac9SQu Wenruo 	    (!btrfs_fs_incompat(fs_info, NO_HOLES) ||
3464d7f67ac9SQu Wenruo 	     !btrfs_test_opt(fs_info, FREE_SPACE_TREE))) {
3465d7f67ac9SQu Wenruo 		btrfs_err(fs_info,
3466d7f67ac9SQu Wenruo "block-group-tree feature requires no-holes and free-space-tree features");
3467d7f67ac9SQu Wenruo 		return -EINVAL;
3468d7f67ac9SQu Wenruo 	}
3469d7f67ac9SQu Wenruo 
3470d7f67ac9SQu Wenruo 	/*
3471d7f67ac9SQu Wenruo 	 * Subpage runtime limitation on v1 cache.
3472d7f67ac9SQu Wenruo 	 *
3473d7f67ac9SQu Wenruo 	 * V1 space cache still has some hard codeed PAGE_SIZE usage, while
3474d7f67ac9SQu Wenruo 	 * we're already defaulting to v2 cache, no need to bother v1 as it's
3475d7f67ac9SQu Wenruo 	 * going to be deprecated anyway.
3476d7f67ac9SQu Wenruo 	 */
3477d7f67ac9SQu Wenruo 	if (fs_info->sectorsize < PAGE_SIZE && btrfs_test_opt(fs_info, SPACE_CACHE)) {
3478d7f67ac9SQu Wenruo 		btrfs_warn(fs_info,
3479d7f67ac9SQu Wenruo 	"v1 space cache is not supported for page size %lu with sectorsize %u",
3480d7f67ac9SQu Wenruo 			   PAGE_SIZE, fs_info->sectorsize);
3481d7f67ac9SQu Wenruo 		return -EINVAL;
3482d7f67ac9SQu Wenruo 	}
3483d7f67ac9SQu Wenruo 
3484d7f67ac9SQu Wenruo 	/* This can be called by remount, we need to protect the super block. */
3485d7f67ac9SQu Wenruo 	spin_lock(&fs_info->super_lock);
3486d7f67ac9SQu Wenruo 	btrfs_set_super_incompat_flags(disk_super, incompat);
3487d7f67ac9SQu Wenruo 	spin_unlock(&fs_info->super_lock);
3488d7f67ac9SQu Wenruo 
3489d7f67ac9SQu Wenruo 	return 0;
3490d7f67ac9SQu Wenruo }
3491d7f67ac9SQu Wenruo 
3492ae18c37aSJosef Bacik int __cold open_ctree(struct super_block *sb, struct btrfs_fs_devices *fs_devices,
3493ae18c37aSJosef Bacik 		      char *options)
3494ae18c37aSJosef Bacik {
3495ae18c37aSJosef Bacik 	u32 sectorsize;
3496ae18c37aSJosef Bacik 	u32 nodesize;
3497ae18c37aSJosef Bacik 	u32 stripesize;
3498ae18c37aSJosef Bacik 	u64 generation;
3499ae18c37aSJosef Bacik 	u64 features;
3500ae18c37aSJosef Bacik 	u16 csum_type;
3501ae18c37aSJosef Bacik 	struct btrfs_super_block *disk_super;
3502ae18c37aSJosef Bacik 	struct btrfs_fs_info *fs_info = btrfs_sb(sb);
3503ae18c37aSJosef Bacik 	struct btrfs_root *tree_root;
3504ae18c37aSJosef Bacik 	struct btrfs_root *chunk_root;
3505ae18c37aSJosef Bacik 	int ret;
3506ae18c37aSJosef Bacik 	int err = -EINVAL;
3507ae18c37aSJosef Bacik 	int level;
3508ae18c37aSJosef Bacik 
35098260edbaSJosef Bacik 	ret = init_mount_fs_info(fs_info, sb);
351053b381b3SDavid Woodhouse 	if (ret) {
351183c8266aSDavid Sterba 		err = ret;
3512ae18c37aSJosef Bacik 		goto fail;
351353b381b3SDavid Woodhouse 	}
351453b381b3SDavid Woodhouse 
3515ae18c37aSJosef Bacik 	/* These need to be init'ed before we start creating inodes and such. */
3516ae18c37aSJosef Bacik 	tree_root = btrfs_alloc_root(fs_info, BTRFS_ROOT_TREE_OBJECTID,
3517ae18c37aSJosef Bacik 				     GFP_KERNEL);
3518ae18c37aSJosef Bacik 	fs_info->tree_root = tree_root;
3519ae18c37aSJosef Bacik 	chunk_root = btrfs_alloc_root(fs_info, BTRFS_CHUNK_TREE_OBJECTID,
3520ae18c37aSJosef Bacik 				      GFP_KERNEL);
3521ae18c37aSJosef Bacik 	fs_info->chunk_root = chunk_root;
3522ae18c37aSJosef Bacik 	if (!tree_root || !chunk_root) {
3523ae18c37aSJosef Bacik 		err = -ENOMEM;
3524c75e8394SJosef Bacik 		goto fail;
3525ae18c37aSJosef Bacik 	}
3526ae18c37aSJosef Bacik 
3527ae18c37aSJosef Bacik 	fs_info->btree_inode = new_inode(sb);
3528ae18c37aSJosef Bacik 	if (!fs_info->btree_inode) {
3529ae18c37aSJosef Bacik 		err = -ENOMEM;
3530c75e8394SJosef Bacik 		goto fail;
3531ae18c37aSJosef Bacik 	}
3532ae18c37aSJosef Bacik 	mapping_set_gfp_mask(fs_info->btree_inode->i_mapping, GFP_NOFS);
3533ae18c37aSJosef Bacik 	btrfs_init_btree_inode(fs_info);
3534ae18c37aSJosef Bacik 
3535d24fa5c1SAnand Jain 	invalidate_bdev(fs_devices->latest_dev->bdev);
35361104a885SDavid Sterba 
35371104a885SDavid Sterba 	/*
35381104a885SDavid Sterba 	 * Read super block and check the signature bytes only
35391104a885SDavid Sterba 	 */
3540d24fa5c1SAnand Jain 	disk_super = btrfs_read_dev_super(fs_devices->latest_dev->bdev);
35418f32380dSJohannes Thumshirn 	if (IS_ERR(disk_super)) {
35428f32380dSJohannes Thumshirn 		err = PTR_ERR(disk_super);
354316cdcec7SMiao Xie 		goto fail_alloc;
354420b45077SDave Young 	}
354539279cc3SChris Mason 
35461104a885SDavid Sterba 	/*
3547260db43cSRandy Dunlap 	 * Verify the type first, if that or the checksum value are
35488dc3f22cSJohannes Thumshirn 	 * corrupted, we'll find out
35498dc3f22cSJohannes Thumshirn 	 */
35508f32380dSJohannes Thumshirn 	csum_type = btrfs_super_csum_type(disk_super);
355151bce6c9SJohannes Thumshirn 	if (!btrfs_supported_super_csum(csum_type)) {
35528dc3f22cSJohannes Thumshirn 		btrfs_err(fs_info, "unsupported checksum algorithm: %u",
355351bce6c9SJohannes Thumshirn 			  csum_type);
35548dc3f22cSJohannes Thumshirn 		err = -EINVAL;
35558f32380dSJohannes Thumshirn 		btrfs_release_disk_super(disk_super);
35568dc3f22cSJohannes Thumshirn 		goto fail_alloc;
35578dc3f22cSJohannes Thumshirn 	}
35588dc3f22cSJohannes Thumshirn 
355983c68bbcSSu Yue 	fs_info->csum_size = btrfs_super_csum_size(disk_super);
356083c68bbcSSu Yue 
35616d97c6e3SJohannes Thumshirn 	ret = btrfs_init_csum_hash(fs_info, csum_type);
35626d97c6e3SJohannes Thumshirn 	if (ret) {
35636d97c6e3SJohannes Thumshirn 		err = ret;
35648f32380dSJohannes Thumshirn 		btrfs_release_disk_super(disk_super);
35656d97c6e3SJohannes Thumshirn 		goto fail_alloc;
35666d97c6e3SJohannes Thumshirn 	}
35676d97c6e3SJohannes Thumshirn 
35688dc3f22cSJohannes Thumshirn 	/*
35691104a885SDavid Sterba 	 * We want to check superblock checksum, the type is stored inside.
35701104a885SDavid Sterba 	 * Pass the whole disk block of size BTRFS_SUPER_INFO_SIZE (4k).
35711104a885SDavid Sterba 	 */
35723d17adeaSQu Wenruo 	if (btrfs_check_super_csum(fs_info, disk_super)) {
357305135f59SDavid Sterba 		btrfs_err(fs_info, "superblock checksum mismatch");
35741104a885SDavid Sterba 		err = -EINVAL;
35758f32380dSJohannes Thumshirn 		btrfs_release_disk_super(disk_super);
3576141386e1SJosef Bacik 		goto fail_alloc;
35771104a885SDavid Sterba 	}
35781104a885SDavid Sterba 
35791104a885SDavid Sterba 	/*
35801104a885SDavid Sterba 	 * super_copy is zeroed at allocation time and we never touch the
35811104a885SDavid Sterba 	 * following bytes up to INFO_SIZE, the checksum is calculated from
35821104a885SDavid Sterba 	 * the whole block of INFO_SIZE
35831104a885SDavid Sterba 	 */
35848f32380dSJohannes Thumshirn 	memcpy(fs_info->super_copy, disk_super, sizeof(*fs_info->super_copy));
35858f32380dSJohannes Thumshirn 	btrfs_release_disk_super(disk_super);
35865f39d397SChris Mason 
3587fbc6feaeSNikolay Borisov 	disk_super = fs_info->super_copy;
3588fbc6feaeSNikolay Borisov 
35890b86a832SChris Mason 
3590fbc6feaeSNikolay Borisov 	features = btrfs_super_flags(disk_super);
3591fbc6feaeSNikolay Borisov 	if (features & BTRFS_SUPER_FLAG_CHANGING_FSID_V2) {
3592fbc6feaeSNikolay Borisov 		features &= ~BTRFS_SUPER_FLAG_CHANGING_FSID_V2;
3593fbc6feaeSNikolay Borisov 		btrfs_set_super_flags(disk_super, features);
3594fbc6feaeSNikolay Borisov 		btrfs_info(fs_info,
3595fbc6feaeSNikolay Borisov 			"found metadata UUID change in progress flag, clearing");
3596fbc6feaeSNikolay Borisov 	}
3597fbc6feaeSNikolay Borisov 
3598fbc6feaeSNikolay Borisov 	memcpy(fs_info->super_for_commit, fs_info->super_copy,
3599fbc6feaeSNikolay Borisov 	       sizeof(*fs_info->super_for_commit));
3600de37aa51SNikolay Borisov 
3601069ec957SQu Wenruo 	ret = btrfs_validate_mount_super(fs_info);
36021104a885SDavid Sterba 	if (ret) {
360305135f59SDavid Sterba 		btrfs_err(fs_info, "superblock contains fatal errors");
36041104a885SDavid Sterba 		err = -EINVAL;
3605141386e1SJosef Bacik 		goto fail_alloc;
36061104a885SDavid Sterba 	}
36071104a885SDavid Sterba 
36080f7d52f4SChris Mason 	if (!btrfs_super_root(disk_super))
3609141386e1SJosef Bacik 		goto fail_alloc;
36100f7d52f4SChris Mason 
3611acce952bSliubo 	/* check FS state, whether FS is broken. */
361287533c47SMiao Xie 	if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_ERROR)
361387533c47SMiao Xie 		set_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state);
3614acce952bSliubo 
361575e7cb7fSLiu Bo 	/*
361675e7cb7fSLiu Bo 	 * In the long term, we'll store the compression type in the super
361775e7cb7fSLiu Bo 	 * block, and it'll be used for per file compression control.
361875e7cb7fSLiu Bo 	 */
361975e7cb7fSLiu Bo 	fs_info->compress_type = BTRFS_COMPRESS_ZLIB;
362075e7cb7fSLiu Bo 
36216f93e834SAnand Jain 
36226f93e834SAnand Jain 	/* Set up fs_info before parsing mount options */
36236f93e834SAnand Jain 	nodesize = btrfs_super_nodesize(disk_super);
36246f93e834SAnand Jain 	sectorsize = btrfs_super_sectorsize(disk_super);
36256f93e834SAnand Jain 	stripesize = sectorsize;
36266f93e834SAnand Jain 	fs_info->dirty_metadata_batch = nodesize * (1 + ilog2(nr_cpu_ids));
36276f93e834SAnand Jain 	fs_info->delalloc_batch = sectorsize * 512 * (1 + ilog2(nr_cpu_ids));
36286f93e834SAnand Jain 
36296f93e834SAnand Jain 	fs_info->nodesize = nodesize;
36306f93e834SAnand Jain 	fs_info->sectorsize = sectorsize;
36316f93e834SAnand Jain 	fs_info->sectorsize_bits = ilog2(sectorsize);
36326f93e834SAnand Jain 	fs_info->csums_per_leaf = BTRFS_MAX_ITEM_SIZE(fs_info) / fs_info->csum_size;
36336f93e834SAnand Jain 	fs_info->stripesize = stripesize;
36346f93e834SAnand Jain 
36352ff7e61eSJeff Mahoney 	ret = btrfs_parse_options(fs_info, options, sb->s_flags);
36362b82032cSYan Zheng 	if (ret) {
36372b82032cSYan Zheng 		err = ret;
3638141386e1SJosef Bacik 		goto fail_alloc;
36392b82032cSYan Zheng 	}
3640dfe25020SChris Mason 
3641*2ba48b20SQu Wenruo 	ret = btrfs_check_features(fs_info, !sb_rdonly(sb));
3642d7f67ac9SQu Wenruo 	if (ret < 0) {
3643d7f67ac9SQu Wenruo 		err = ret;
3644141386e1SJosef Bacik 		goto fail_alloc;
3645f2b636e8SJosef Bacik 	}
3646f2b636e8SJosef Bacik 
36478481dd80SQu Wenruo 	if (sectorsize < PAGE_SIZE) {
36488481dd80SQu Wenruo 		struct btrfs_subpage_info *subpage_info;
36498481dd80SQu Wenruo 
36509f73f1aeSQu Wenruo 		/*
36519f73f1aeSQu Wenruo 		 * V1 space cache has some hardcoded PAGE_SIZE usage, and is
36529f73f1aeSQu Wenruo 		 * going to be deprecated.
36539f73f1aeSQu Wenruo 		 *
36549f73f1aeSQu Wenruo 		 * Force to use v2 cache for subpage case.
36559f73f1aeSQu Wenruo 		 */
36569f73f1aeSQu Wenruo 		btrfs_clear_opt(fs_info->mount_opt, SPACE_CACHE);
36579f73f1aeSQu Wenruo 		btrfs_set_and_info(fs_info, FREE_SPACE_TREE,
36589f73f1aeSQu Wenruo 			"forcing free space tree for sector size %u with page size %lu",
36599f73f1aeSQu Wenruo 			sectorsize, PAGE_SIZE);
36609f73f1aeSQu Wenruo 
366195ea0486SQu Wenruo 		btrfs_warn(fs_info,
366295ea0486SQu Wenruo 		"read-write for sector size %u with page size %lu is experimental",
36630bb3eb3eSQu Wenruo 			   sectorsize, PAGE_SIZE);
36648481dd80SQu Wenruo 		subpage_info = kzalloc(sizeof(*subpage_info), GFP_KERNEL);
36658481dd80SQu Wenruo 		if (!subpage_info)
36668481dd80SQu Wenruo 			goto fail_alloc;
36678481dd80SQu Wenruo 		btrfs_init_subpage_info(subpage_info, sectorsize);
36688481dd80SQu Wenruo 		fs_info->subpage_info = subpage_info;
3669c8050b3bSQu Wenruo 	}
36700bb3eb3eSQu Wenruo 
3671d21deec5SSu Yue 	ret = btrfs_init_workqueues(fs_info);
36722a458198SEric Sandeen 	if (ret) {
36732a458198SEric Sandeen 		err = ret;
36740dc3b84aSJosef Bacik 		goto fail_sb_buffer;
36750dc3b84aSJosef Bacik 	}
36764543df7eSChris Mason 
36779e11ceeeSJan Kara 	sb->s_bdi->ra_pages *= btrfs_super_num_devices(disk_super);
36789e11ceeeSJan Kara 	sb->s_bdi->ra_pages = max(sb->s_bdi->ra_pages, SZ_4M / PAGE_SIZE);
36794575c9ccSChris Mason 
3680a061fc8dSChris Mason 	sb->s_blocksize = sectorsize;
3681a061fc8dSChris Mason 	sb->s_blocksize_bits = blksize_bits(sectorsize);
3682de37aa51SNikolay Borisov 	memcpy(&sb->s_uuid, fs_info->fs_devices->fsid, BTRFS_FSID_SIZE);
3683db94535dSChris Mason 
3684925baeddSChris Mason 	mutex_lock(&fs_info->chunk_mutex);
36856bccf3abSJeff Mahoney 	ret = btrfs_read_sys_array(fs_info);
3686925baeddSChris Mason 	mutex_unlock(&fs_info->chunk_mutex);
368784eed90fSChris Mason 	if (ret) {
368805135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read the system array: %d", ret);
36895d4f98a2SYan Zheng 		goto fail_sb_buffer;
369084eed90fSChris Mason 	}
36910b86a832SChris Mason 
369284234f3aSYan Zheng 	generation = btrfs_super_chunk_root_generation(disk_super);
3693581c1760SQu Wenruo 	level = btrfs_super_chunk_root_level(disk_super);
3694bd676446SJosef Bacik 	ret = load_super_root(chunk_root, btrfs_super_chunk_root(disk_super),
3695bd676446SJosef Bacik 			      generation, level);
3696bd676446SJosef Bacik 	if (ret) {
369705135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read chunk root");
3698af31f5e5SChris Mason 		goto fail_tree_roots;
369983121942SDavid Woodhouse 	}
37000b86a832SChris Mason 
3701e17cade2SChris Mason 	read_extent_buffer(chunk_root->node, fs_info->chunk_tree_uuid,
3702c4ac7541SDavid Sterba 			   offsetof(struct btrfs_header, chunk_tree_uuid),
3703c4ac7541SDavid Sterba 			   BTRFS_UUID_SIZE);
3704e17cade2SChris Mason 
37055b4aacefSJeff Mahoney 	ret = btrfs_read_chunk_tree(fs_info);
37062b82032cSYan Zheng 	if (ret) {
370705135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read chunk tree: %d", ret);
3708af31f5e5SChris Mason 		goto fail_tree_roots;
37092b82032cSYan Zheng 	}
37100b86a832SChris Mason 
37118dabb742SStefan Behrens 	/*
3712bacce86aSAnand Jain 	 * At this point we know all the devices that make this filesystem,
3713bacce86aSAnand Jain 	 * including the seed devices but we don't know yet if the replace
3714bacce86aSAnand Jain 	 * target is required. So free devices that are not part of this
37151a9fd417SDavid Sterba 	 * filesystem but skip the replace target device which is checked
3716bacce86aSAnand Jain 	 * below in btrfs_init_dev_replace().
37178dabb742SStefan Behrens 	 */
3718bacce86aSAnand Jain 	btrfs_free_extra_devids(fs_devices);
3719d24fa5c1SAnand Jain 	if (!fs_devices->latest_dev->bdev) {
372005135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read devices");
3721a6b0d5c8SChris Mason 		goto fail_tree_roots;
3722a6b0d5c8SChris Mason 	}
3723a6b0d5c8SChris Mason 
3724b8522a1eSNikolay Borisov 	ret = init_tree_roots(fs_info);
37254bbcaa64SEric Sandeen 	if (ret)
3726b8522a1eSNikolay Borisov 		goto fail_tree_roots;
37278929ecfaSYan, Zheng 
372875ec1db8SJosef Bacik 	/*
372973651042SNaohiro Aota 	 * Get zone type information of zoned block devices. This will also
373073651042SNaohiro Aota 	 * handle emulation of a zoned filesystem if a regular device has the
373173651042SNaohiro Aota 	 * zoned incompat feature flag set.
373273651042SNaohiro Aota 	 */
373373651042SNaohiro Aota 	ret = btrfs_get_dev_zone_info_all_devices(fs_info);
373473651042SNaohiro Aota 	if (ret) {
373573651042SNaohiro Aota 		btrfs_err(fs_info,
373673651042SNaohiro Aota 			  "zoned: failed to read device zone info: %d",
373773651042SNaohiro Aota 			  ret);
373873651042SNaohiro Aota 		goto fail_block_groups;
373973651042SNaohiro Aota 	}
374073651042SNaohiro Aota 
374173651042SNaohiro Aota 	/*
374275ec1db8SJosef Bacik 	 * If we have a uuid root and we're not being told to rescan we need to
374375ec1db8SJosef Bacik 	 * check the generation here so we can set the
374475ec1db8SJosef Bacik 	 * BTRFS_FS_UPDATE_UUID_TREE_GEN bit.  Otherwise we could commit the
374575ec1db8SJosef Bacik 	 * transaction during a balance or the log replay without updating the
374675ec1db8SJosef Bacik 	 * uuid generation, and then if we crash we would rescan the uuid tree,
374775ec1db8SJosef Bacik 	 * even though it was perfectly fine.
374875ec1db8SJosef Bacik 	 */
374975ec1db8SJosef Bacik 	if (fs_info->uuid_root && !btrfs_test_opt(fs_info, RESCAN_UUID_TREE) &&
375075ec1db8SJosef Bacik 	    fs_info->generation == btrfs_super_uuid_tree_generation(disk_super))
375175ec1db8SJosef Bacik 		set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
375275ec1db8SJosef Bacik 
3753cf90d884SQu Wenruo 	ret = btrfs_verify_dev_extents(fs_info);
3754cf90d884SQu Wenruo 	if (ret) {
3755cf90d884SQu Wenruo 		btrfs_err(fs_info,
3756cf90d884SQu Wenruo 			  "failed to verify dev extents against chunks: %d",
3757cf90d884SQu Wenruo 			  ret);
3758cf90d884SQu Wenruo 		goto fail_block_groups;
3759cf90d884SQu Wenruo 	}
376068310a5eSIlya Dryomov 	ret = btrfs_recover_balance(fs_info);
376168310a5eSIlya Dryomov 	if (ret) {
376205135f59SDavid Sterba 		btrfs_err(fs_info, "failed to recover balance: %d", ret);
376368310a5eSIlya Dryomov 		goto fail_block_groups;
376468310a5eSIlya Dryomov 	}
376568310a5eSIlya Dryomov 
3766733f4fbbSStefan Behrens 	ret = btrfs_init_dev_stats(fs_info);
3767733f4fbbSStefan Behrens 	if (ret) {
376805135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init dev_stats: %d", ret);
3769733f4fbbSStefan Behrens 		goto fail_block_groups;
3770733f4fbbSStefan Behrens 	}
3771733f4fbbSStefan Behrens 
37728dabb742SStefan Behrens 	ret = btrfs_init_dev_replace(fs_info);
37738dabb742SStefan Behrens 	if (ret) {
377405135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init dev_replace: %d", ret);
37758dabb742SStefan Behrens 		goto fail_block_groups;
37768dabb742SStefan Behrens 	}
37778dabb742SStefan Behrens 
3778b70f5097SNaohiro Aota 	ret = btrfs_check_zoned_mode(fs_info);
3779b70f5097SNaohiro Aota 	if (ret) {
3780b70f5097SNaohiro Aota 		btrfs_err(fs_info, "failed to initialize zoned mode: %d",
3781b70f5097SNaohiro Aota 			  ret);
3782b70f5097SNaohiro Aota 		goto fail_block_groups;
3783b70f5097SNaohiro Aota 	}
3784b70f5097SNaohiro Aota 
3785c6761a9eSAnand Jain 	ret = btrfs_sysfs_add_fsid(fs_devices);
3786b7c35e81SAnand Jain 	if (ret) {
378705135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init sysfs fsid interface: %d",
378805135f59SDavid Sterba 				ret);
3789b7c35e81SAnand Jain 		goto fail_block_groups;
3790b7c35e81SAnand Jain 	}
3791b7c35e81SAnand Jain 
379296f3136eSAnand Jain 	ret = btrfs_sysfs_add_mounted(fs_info);
37935ac1d209SJeff Mahoney 	if (ret) {
379405135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init sysfs interface: %d", ret);
3795b7c35e81SAnand Jain 		goto fail_fsdev_sysfs;
37965ac1d209SJeff Mahoney 	}
37975ac1d209SJeff Mahoney 
3798c59021f8Sliubo 	ret = btrfs_init_space_info(fs_info);
3799c59021f8Sliubo 	if (ret) {
380005135f59SDavid Sterba 		btrfs_err(fs_info, "failed to initialize space info: %d", ret);
38012365dd3cSAnand Jain 		goto fail_sysfs;
3802c59021f8Sliubo 	}
3803c59021f8Sliubo 
38045b4aacefSJeff Mahoney 	ret = btrfs_read_block_groups(fs_info);
38051b1d1f66SJosef Bacik 	if (ret) {
380605135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read block groups: %d", ret);
38072365dd3cSAnand Jain 		goto fail_sysfs;
38081b1d1f66SJosef Bacik 	}
38094330e183SQu Wenruo 
381016beac87SNaohiro Aota 	btrfs_free_zone_cache(fs_info);
381116beac87SNaohiro Aota 
38125c78a5e7SAnand Jain 	if (!sb_rdonly(sb) && fs_info->fs_devices->missing_devices &&
38135c78a5e7SAnand Jain 	    !btrfs_check_rw_degradable(fs_info, NULL)) {
381405135f59SDavid Sterba 		btrfs_warn(fs_info,
381552042d8eSAndrea Gelmini 		"writable mount is not allowed due to too many missing devices");
38162365dd3cSAnand Jain 		goto fail_sysfs;
3817292fd7fcSStefan Behrens 	}
38189078a3e1SChris Mason 
381933c44184SJosef Bacik 	fs_info->cleaner_kthread = kthread_run(cleaner_kthread, fs_info,
3820a74a4b97SChris Mason 					       "btrfs-cleaner");
382157506d50SQinghuang Feng 	if (IS_ERR(fs_info->cleaner_kthread))
38222365dd3cSAnand Jain 		goto fail_sysfs;
3823a74a4b97SChris Mason 
3824a74a4b97SChris Mason 	fs_info->transaction_kthread = kthread_run(transaction_kthread,
3825a74a4b97SChris Mason 						   tree_root,
3826a74a4b97SChris Mason 						   "btrfs-transaction");
382757506d50SQinghuang Feng 	if (IS_ERR(fs_info->transaction_kthread))
38283f157a2fSChris Mason 		goto fail_cleaner;
3829a74a4b97SChris Mason 
3830583b7231SHans van Kranenburg 	if (!btrfs_test_opt(fs_info, NOSSD) &&
3831c289811cSChris Mason 	    !fs_info->fs_devices->rotating) {
3832583b7231SHans van Kranenburg 		btrfs_set_and_info(fs_info, SSD, "enabling ssd optimizations");
3833c289811cSChris Mason 	}
3834c289811cSChris Mason 
3835572d9ab7SDavid Sterba 	/*
383663a7cb13SDavid Sterba 	 * For devices supporting discard turn on discard=async automatically,
383763a7cb13SDavid Sterba 	 * unless it's already set or disabled. This could be turned off by
383863a7cb13SDavid Sterba 	 * nodiscard for the same mount.
383963a7cb13SDavid Sterba 	 */
384063a7cb13SDavid Sterba 	if (!(btrfs_test_opt(fs_info, DISCARD_SYNC) ||
384163a7cb13SDavid Sterba 	      btrfs_test_opt(fs_info, DISCARD_ASYNC) ||
384263a7cb13SDavid Sterba 	      btrfs_test_opt(fs_info, NODISCARD)) &&
384363a7cb13SDavid Sterba 	    fs_info->fs_devices->discardable) {
384463a7cb13SDavid Sterba 		btrfs_set_and_info(fs_info, DISCARD_ASYNC,
384563a7cb13SDavid Sterba 				   "auto enabling async discard");
384663a7cb13SDavid Sterba 		btrfs_clear_opt(fs_info->mount_opt, NODISCARD);
384763a7cb13SDavid Sterba 	}
384863a7cb13SDavid Sterba 
384921adbd5cSStefan Behrens #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
38500b246afaSJeff Mahoney 	if (btrfs_test_opt(fs_info, CHECK_INTEGRITY)) {
38512ff7e61eSJeff Mahoney 		ret = btrfsic_mount(fs_info, fs_devices,
38520b246afaSJeff Mahoney 				    btrfs_test_opt(fs_info,
3853cbeaae4fSDavid Sterba 					CHECK_INTEGRITY_DATA) ? 1 : 0,
385421adbd5cSStefan Behrens 				    fs_info->check_integrity_print_mask);
385521adbd5cSStefan Behrens 		if (ret)
385605135f59SDavid Sterba 			btrfs_warn(fs_info,
385705135f59SDavid Sterba 				"failed to initialize integrity check module: %d",
385805135f59SDavid Sterba 				ret);
385921adbd5cSStefan Behrens 	}
386021adbd5cSStefan Behrens #endif
3861bcef60f2SArne Jansen 	ret = btrfs_read_qgroup_config(fs_info);
3862bcef60f2SArne Jansen 	if (ret)
3863bcef60f2SArne Jansen 		goto fail_trans_kthread;
386421adbd5cSStefan Behrens 
3865fd708b81SJosef Bacik 	if (btrfs_build_ref_tree(fs_info))
3866fd708b81SJosef Bacik 		btrfs_err(fs_info, "couldn't build ref tree");
3867fd708b81SJosef Bacik 
386896da0919SQu Wenruo 	/* do not make disk changes in broken FS or nologreplay is given */
386996da0919SQu Wenruo 	if (btrfs_super_log_root(disk_super) != 0 &&
38700b246afaSJeff Mahoney 	    !btrfs_test_opt(fs_info, NOLOGREPLAY)) {
3871e8294f2fSDavid Sterba 		btrfs_info(fs_info, "start tree-log replay");
387263443bf5SEric Sandeen 		ret = btrfs_replay_log(fs_info, fs_devices);
387379787eaaSJeff Mahoney 		if (ret) {
387463443bf5SEric Sandeen 			err = ret;
387528c16cbbSWang Shilong 			goto fail_qgroup;
3876e556ce2cSYan Zheng 		}
3877e02119d5SChris Mason 	}
38781a40e23bSZheng Yan 
387956e9357aSDavid Sterba 	fs_info->fs_root = btrfs_get_fs_root(fs_info, BTRFS_FS_TREE_OBJECTID, true);
38803140c9a3SDan Carpenter 	if (IS_ERR(fs_info->fs_root)) {
38813140c9a3SDan Carpenter 		err = PTR_ERR(fs_info->fs_root);
3882f50f4353SLiu Bo 		btrfs_warn(fs_info, "failed to read fs tree: %d", err);
3883315bf8efSJosef Bacik 		fs_info->fs_root = NULL;
3884bcef60f2SArne Jansen 		goto fail_qgroup;
38853140c9a3SDan Carpenter 	}
3886c289811cSChris Mason 
3887bc98a42cSDavid Howells 	if (sb_rdonly(sb))
38888cd29088SBoris Burkov 		goto clear_oneshot;
38892b6ba629SIlya Dryomov 
389044c0ca21SBoris Burkov 	ret = btrfs_start_pre_rw_mount(fs_info);
38912b6ba629SIlya Dryomov 	if (ret) {
38926bccf3abSJeff Mahoney 		close_ctree(fs_info);
38932b6ba629SIlya Dryomov 		return ret;
3894e3acc2a6SJosef Bacik 	}
3895b0643e59SDennis Zhou 	btrfs_discard_resume(fs_info);
3896b382a324SJan Schmidt 
389744c0ca21SBoris Burkov 	if (fs_info->uuid_root &&
389844c0ca21SBoris Burkov 	    (btrfs_test_opt(fs_info, RESCAN_UUID_TREE) ||
389944c0ca21SBoris Burkov 	     fs_info->generation != btrfs_super_uuid_tree_generation(disk_super))) {
390005135f59SDavid Sterba 		btrfs_info(fs_info, "checking UUID tree");
390170f80175SStefan Behrens 		ret = btrfs_check_uuid_tree(fs_info);
390270f80175SStefan Behrens 		if (ret) {
390305135f59SDavid Sterba 			btrfs_warn(fs_info,
390405135f59SDavid Sterba 				"failed to check the UUID tree: %d", ret);
39056bccf3abSJeff Mahoney 			close_ctree(fs_info);
390670f80175SStefan Behrens 			return ret;
390770f80175SStefan Behrens 		}
3908f7a81ea4SStefan Behrens 	}
390994846229SBoris Burkov 
3910afcdd129SJosef Bacik 	set_bit(BTRFS_FS_OPEN, &fs_info->flags);
391147ab2a6cSJosef Bacik 
3912b4be6aefSJosef Bacik 	/* Kick the cleaner thread so it'll start deleting snapshots. */
3913b4be6aefSJosef Bacik 	if (test_bit(BTRFS_FS_UNFINISHED_DROPS, &fs_info->flags))
3914b4be6aefSJosef Bacik 		wake_up_process(fs_info->cleaner_kthread);
3915b4be6aefSJosef Bacik 
39168cd29088SBoris Burkov clear_oneshot:
39178cd29088SBoris Burkov 	btrfs_clear_oneshot_options(fs_info);
3918ad2b2c80SAl Viro 	return 0;
391939279cc3SChris Mason 
3920bcef60f2SArne Jansen fail_qgroup:
3921bcef60f2SArne Jansen 	btrfs_free_qgroup_config(fs_info);
39227c2ca468SChris Mason fail_trans_kthread:
39237c2ca468SChris Mason 	kthread_stop(fs_info->transaction_kthread);
39242ff7e61eSJeff Mahoney 	btrfs_cleanup_transaction(fs_info);
3925faa2dbf0SJosef Bacik 	btrfs_free_fs_roots(fs_info);
39263f157a2fSChris Mason fail_cleaner:
3927a74a4b97SChris Mason 	kthread_stop(fs_info->cleaner_kthread);
39287c2ca468SChris Mason 
39297c2ca468SChris Mason 	/*
39307c2ca468SChris Mason 	 * make sure we're done with the btree inode before we stop our
39317c2ca468SChris Mason 	 * kthreads
39327c2ca468SChris Mason 	 */
39337c2ca468SChris Mason 	filemap_write_and_wait(fs_info->btree_inode->i_mapping);
39347c2ca468SChris Mason 
39352365dd3cSAnand Jain fail_sysfs:
39366618a59bSAnand Jain 	btrfs_sysfs_remove_mounted(fs_info);
39372365dd3cSAnand Jain 
3938b7c35e81SAnand Jain fail_fsdev_sysfs:
3939b7c35e81SAnand Jain 	btrfs_sysfs_remove_fsid(fs_info->fs_devices);
3940b7c35e81SAnand Jain 
39411b1d1f66SJosef Bacik fail_block_groups:
394254067ae9SJosef Bacik 	btrfs_put_block_group_cache(fs_info);
3943af31f5e5SChris Mason 
3944af31f5e5SChris Mason fail_tree_roots:
39459e3aa805SJosef Bacik 	if (fs_info->data_reloc_root)
39469e3aa805SJosef Bacik 		btrfs_drop_and_free_fs_root(fs_info, fs_info->data_reloc_root);
39474273eaffSAnand Jain 	free_root_pointers(fs_info, true);
39482b8195bbSMiao Xie 	invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
3949af31f5e5SChris Mason 
395039279cc3SChris Mason fail_sb_buffer:
39517abadb64SLiu Bo 	btrfs_stop_all_workers(fs_info);
39525cdd7db6SFilipe Manana 	btrfs_free_block_groups(fs_info);
395316cdcec7SMiao Xie fail_alloc:
3954586e46e2SIlya Dryomov 	btrfs_mapping_tree_free(&fs_info->mapping_tree);
3955586e46e2SIlya Dryomov 
39564543df7eSChris Mason 	iput(fs_info->btree_inode);
39577e662854SQinghuang Feng fail:
3958586e46e2SIlya Dryomov 	btrfs_close_devices(fs_info->fs_devices);
3959ad2b2c80SAl Viro 	return err;
3960eb60ceacSChris Mason }
3961663faf9fSMasami Hiramatsu ALLOW_ERROR_INJECTION(open_ctree, ERRNO);
3962eb60ceacSChris Mason 
3963314b6dd0SJohannes Thumshirn static void btrfs_end_super_write(struct bio *bio)
3964f2984462SChris Mason {
3965314b6dd0SJohannes Thumshirn 	struct btrfs_device *device = bio->bi_private;
3966314b6dd0SJohannes Thumshirn 	struct bio_vec *bvec;
3967314b6dd0SJohannes Thumshirn 	struct bvec_iter_all iter_all;
3968314b6dd0SJohannes Thumshirn 	struct page *page;
3969442a4f63SStefan Behrens 
3970314b6dd0SJohannes Thumshirn 	bio_for_each_segment_all(bvec, bio, iter_all) {
3971314b6dd0SJohannes Thumshirn 		page = bvec->bv_page;
3972314b6dd0SJohannes Thumshirn 
3973314b6dd0SJohannes Thumshirn 		if (bio->bi_status) {
3974fb456252SJeff Mahoney 			btrfs_warn_rl_in_rcu(device->fs_info,
3975314b6dd0SJohannes Thumshirn 				"lost page write due to IO error on %s (%d)",
3976cb3e217bSQu Wenruo 				btrfs_dev_name(device),
3977314b6dd0SJohannes Thumshirn 				blk_status_to_errno(bio->bi_status));
3978314b6dd0SJohannes Thumshirn 			ClearPageUptodate(page);
3979314b6dd0SJohannes Thumshirn 			SetPageError(page);
3980314b6dd0SJohannes Thumshirn 			btrfs_dev_stat_inc_and_print(device,
3981314b6dd0SJohannes Thumshirn 						     BTRFS_DEV_STAT_WRITE_ERRS);
3982314b6dd0SJohannes Thumshirn 		} else {
3983314b6dd0SJohannes Thumshirn 			SetPageUptodate(page);
3984f2984462SChris Mason 		}
3985314b6dd0SJohannes Thumshirn 
3986314b6dd0SJohannes Thumshirn 		put_page(page);
3987314b6dd0SJohannes Thumshirn 		unlock_page(page);
3988314b6dd0SJohannes Thumshirn 	}
3989314b6dd0SJohannes Thumshirn 
3990314b6dd0SJohannes Thumshirn 	bio_put(bio);
3991f2984462SChris Mason }
3992f2984462SChris Mason 
39938f32380dSJohannes Thumshirn struct btrfs_super_block *btrfs_read_dev_one_super(struct block_device *bdev,
3994a05d3c91SQu Wenruo 						   int copy_num, bool drop_cache)
399529c36d72SAnand Jain {
399629c36d72SAnand Jain 	struct btrfs_super_block *super;
39978f32380dSJohannes Thumshirn 	struct page *page;
399812659251SNaohiro Aota 	u64 bytenr, bytenr_orig;
39998f32380dSJohannes Thumshirn 	struct address_space *mapping = bdev->bd_inode->i_mapping;
400012659251SNaohiro Aota 	int ret;
400129c36d72SAnand Jain 
400212659251SNaohiro Aota 	bytenr_orig = btrfs_sb_offset(copy_num);
400312659251SNaohiro Aota 	ret = btrfs_sb_log_location_bdev(bdev, copy_num, READ, &bytenr);
400412659251SNaohiro Aota 	if (ret == -ENOENT)
400512659251SNaohiro Aota 		return ERR_PTR(-EINVAL);
400612659251SNaohiro Aota 	else if (ret)
400712659251SNaohiro Aota 		return ERR_PTR(ret);
400812659251SNaohiro Aota 
4009cda00ebaSChristoph Hellwig 	if (bytenr + BTRFS_SUPER_INFO_SIZE >= bdev_nr_bytes(bdev))
40108f32380dSJohannes Thumshirn 		return ERR_PTR(-EINVAL);
401129c36d72SAnand Jain 
4012a05d3c91SQu Wenruo 	if (drop_cache) {
4013a05d3c91SQu Wenruo 		/* This should only be called with the primary sb. */
4014a05d3c91SQu Wenruo 		ASSERT(copy_num == 0);
4015a05d3c91SQu Wenruo 
4016a05d3c91SQu Wenruo 		/*
4017a05d3c91SQu Wenruo 		 * Drop the page of the primary superblock, so later read will
4018a05d3c91SQu Wenruo 		 * always read from the device.
4019a05d3c91SQu Wenruo 		 */
4020a05d3c91SQu Wenruo 		invalidate_inode_pages2_range(mapping,
4021a05d3c91SQu Wenruo 				bytenr >> PAGE_SHIFT,
4022a05d3c91SQu Wenruo 				(bytenr + BTRFS_SUPER_INFO_SIZE) >> PAGE_SHIFT);
4023a05d3c91SQu Wenruo 	}
4024a05d3c91SQu Wenruo 
40258f32380dSJohannes Thumshirn 	page = read_cache_page_gfp(mapping, bytenr >> PAGE_SHIFT, GFP_NOFS);
40268f32380dSJohannes Thumshirn 	if (IS_ERR(page))
40278f32380dSJohannes Thumshirn 		return ERR_CAST(page);
402829c36d72SAnand Jain 
40298f32380dSJohannes Thumshirn 	super = page_address(page);
403096c2e067SAnand Jain 	if (btrfs_super_magic(super) != BTRFS_MAGIC) {
403196c2e067SAnand Jain 		btrfs_release_disk_super(super);
403296c2e067SAnand Jain 		return ERR_PTR(-ENODATA);
403396c2e067SAnand Jain 	}
403496c2e067SAnand Jain 
403512659251SNaohiro Aota 	if (btrfs_super_bytenr(super) != bytenr_orig) {
40368f32380dSJohannes Thumshirn 		btrfs_release_disk_super(super);
40378f32380dSJohannes Thumshirn 		return ERR_PTR(-EINVAL);
403829c36d72SAnand Jain 	}
403929c36d72SAnand Jain 
40408f32380dSJohannes Thumshirn 	return super;
404129c36d72SAnand Jain }
404229c36d72SAnand Jain 
404329c36d72SAnand Jain 
40448f32380dSJohannes Thumshirn struct btrfs_super_block *btrfs_read_dev_super(struct block_device *bdev)
4045a512bbf8SYan Zheng {
40468f32380dSJohannes Thumshirn 	struct btrfs_super_block *super, *latest = NULL;
4047a512bbf8SYan Zheng 	int i;
4048a512bbf8SYan Zheng 	u64 transid = 0;
4049a512bbf8SYan Zheng 
4050a512bbf8SYan Zheng 	/* we would like to check all the supers, but that would make
4051a512bbf8SYan Zheng 	 * a btrfs mount succeed after a mkfs from a different FS.
4052a512bbf8SYan Zheng 	 * So, we need to add a special mount option to scan for
4053a512bbf8SYan Zheng 	 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
4054a512bbf8SYan Zheng 	 */
4055a512bbf8SYan Zheng 	for (i = 0; i < 1; i++) {
4056a05d3c91SQu Wenruo 		super = btrfs_read_dev_one_super(bdev, i, false);
40578f32380dSJohannes Thumshirn 		if (IS_ERR(super))
4058a512bbf8SYan Zheng 			continue;
4059a512bbf8SYan Zheng 
4060a512bbf8SYan Zheng 		if (!latest || btrfs_super_generation(super) > transid) {
40618f32380dSJohannes Thumshirn 			if (latest)
40628f32380dSJohannes Thumshirn 				btrfs_release_disk_super(super);
40638f32380dSJohannes Thumshirn 
40648f32380dSJohannes Thumshirn 			latest = super;
4065a512bbf8SYan Zheng 			transid = btrfs_super_generation(super);
4066a512bbf8SYan Zheng 		}
4067a512bbf8SYan Zheng 	}
406892fc03fbSAnand Jain 
40698f32380dSJohannes Thumshirn 	return super;
4070a512bbf8SYan Zheng }
4071a512bbf8SYan Zheng 
40724eedeb75SHisashi Hifumi /*
4073abbb3b8eSDavid Sterba  * Write superblock @sb to the @device. Do not wait for completion, all the
4074314b6dd0SJohannes Thumshirn  * pages we use for writing are locked.
40754eedeb75SHisashi Hifumi  *
4076abbb3b8eSDavid Sterba  * Write @max_mirrors copies of the superblock, where 0 means default that fit
4077abbb3b8eSDavid Sterba  * the expected device size at commit time. Note that max_mirrors must be
4078abbb3b8eSDavid Sterba  * same for write and wait phases.
40794eedeb75SHisashi Hifumi  *
4080314b6dd0SJohannes Thumshirn  * Return number of errors when page is not found or submission fails.
40814eedeb75SHisashi Hifumi  */
4082a512bbf8SYan Zheng static int write_dev_supers(struct btrfs_device *device,
4083abbb3b8eSDavid Sterba 			    struct btrfs_super_block *sb, int max_mirrors)
4084a512bbf8SYan Zheng {
4085d5178578SJohannes Thumshirn 	struct btrfs_fs_info *fs_info = device->fs_info;
4086314b6dd0SJohannes Thumshirn 	struct address_space *mapping = device->bdev->bd_inode->i_mapping;
4087d5178578SJohannes Thumshirn 	SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
4088a512bbf8SYan Zheng 	int i;
4089a512bbf8SYan Zheng 	int errors = 0;
409012659251SNaohiro Aota 	int ret;
409112659251SNaohiro Aota 	u64 bytenr, bytenr_orig;
4092a512bbf8SYan Zheng 
4093a512bbf8SYan Zheng 	if (max_mirrors == 0)
4094a512bbf8SYan Zheng 		max_mirrors = BTRFS_SUPER_MIRROR_MAX;
4095a512bbf8SYan Zheng 
4096d5178578SJohannes Thumshirn 	shash->tfm = fs_info->csum_shash;
4097d5178578SJohannes Thumshirn 
4098a512bbf8SYan Zheng 	for (i = 0; i < max_mirrors; i++) {
4099314b6dd0SJohannes Thumshirn 		struct page *page;
4100314b6dd0SJohannes Thumshirn 		struct bio *bio;
4101314b6dd0SJohannes Thumshirn 		struct btrfs_super_block *disk_super;
4102314b6dd0SJohannes Thumshirn 
410312659251SNaohiro Aota 		bytenr_orig = btrfs_sb_offset(i);
410412659251SNaohiro Aota 		ret = btrfs_sb_log_location(device, i, WRITE, &bytenr);
410512659251SNaohiro Aota 		if (ret == -ENOENT) {
410612659251SNaohiro Aota 			continue;
410712659251SNaohiro Aota 		} else if (ret < 0) {
410812659251SNaohiro Aota 			btrfs_err(device->fs_info,
410912659251SNaohiro Aota 				"couldn't get super block location for mirror %d",
411012659251SNaohiro Aota 				i);
411112659251SNaohiro Aota 			errors++;
411212659251SNaohiro Aota 			continue;
411312659251SNaohiro Aota 		}
4114935e5cc9SMiao Xie 		if (bytenr + BTRFS_SUPER_INFO_SIZE >=
4115935e5cc9SMiao Xie 		    device->commit_total_bytes)
4116a512bbf8SYan Zheng 			break;
4117a512bbf8SYan Zheng 
411812659251SNaohiro Aota 		btrfs_set_super_bytenr(sb, bytenr_orig);
4119a512bbf8SYan Zheng 
4120fd08001fSEric Biggers 		crypto_shash_digest(shash, (const char *)sb + BTRFS_CSUM_SIZE,
4121fd08001fSEric Biggers 				    BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE,
4122fd08001fSEric Biggers 				    sb->csum);
4123a512bbf8SYan Zheng 
4124314b6dd0SJohannes Thumshirn 		page = find_or_create_page(mapping, bytenr >> PAGE_SHIFT,
4125314b6dd0SJohannes Thumshirn 					   GFP_NOFS);
4126314b6dd0SJohannes Thumshirn 		if (!page) {
4127fb456252SJeff Mahoney 			btrfs_err(device->fs_info,
4128314b6dd0SJohannes Thumshirn 			    "couldn't get super block page for bytenr %llu",
4129f14d104dSDavid Sterba 			    bytenr);
4130634554dcSJosef Bacik 			errors++;
4131634554dcSJosef Bacik 			continue;
4132634554dcSJosef Bacik 		}
4133634554dcSJosef Bacik 
4134314b6dd0SJohannes Thumshirn 		/* Bump the refcount for wait_dev_supers() */
4135314b6dd0SJohannes Thumshirn 		get_page(page);
4136a512bbf8SYan Zheng 
4137314b6dd0SJohannes Thumshirn 		disk_super = page_address(page);
4138314b6dd0SJohannes Thumshirn 		memcpy(disk_super, sb, BTRFS_SUPER_INFO_SIZE);
4139a512bbf8SYan Zheng 
4140387125fcSChris Mason 		/*
4141314b6dd0SJohannes Thumshirn 		 * Directly use bios here instead of relying on the page cache
4142314b6dd0SJohannes Thumshirn 		 * to do I/O, so we don't lose the ability to do integrity
4143314b6dd0SJohannes Thumshirn 		 * checking.
4144387125fcSChris Mason 		 */
414507888c66SChristoph Hellwig 		bio = bio_alloc(device->bdev, 1,
414607888c66SChristoph Hellwig 				REQ_OP_WRITE | REQ_SYNC | REQ_META | REQ_PRIO,
414707888c66SChristoph Hellwig 				GFP_NOFS);
4148314b6dd0SJohannes Thumshirn 		bio->bi_iter.bi_sector = bytenr >> SECTOR_SHIFT;
4149314b6dd0SJohannes Thumshirn 		bio->bi_private = device;
4150314b6dd0SJohannes Thumshirn 		bio->bi_end_io = btrfs_end_super_write;
4151314b6dd0SJohannes Thumshirn 		__bio_add_page(bio, page, BTRFS_SUPER_INFO_SIZE,
4152314b6dd0SJohannes Thumshirn 			       offset_in_page(bytenr));
4153314b6dd0SJohannes Thumshirn 
4154314b6dd0SJohannes Thumshirn 		/*
4155314b6dd0SJohannes Thumshirn 		 * We FUA only the first super block.  The others we allow to
4156314b6dd0SJohannes Thumshirn 		 * go down lazy and there's a short window where the on-disk
4157314b6dd0SJohannes Thumshirn 		 * copies might still contain the older version.
4158314b6dd0SJohannes Thumshirn 		 */
41591b9e619cSOmar Sandoval 		if (i == 0 && !btrfs_test_opt(device->fs_info, NOBARRIER))
4160314b6dd0SJohannes Thumshirn 			bio->bi_opf |= REQ_FUA;
4161314b6dd0SJohannes Thumshirn 
416258ff51f1SChristoph Hellwig 		btrfsic_check_bio(bio);
416358ff51f1SChristoph Hellwig 		submit_bio(bio);
41648376d9e1SNaohiro Aota 
41658376d9e1SNaohiro Aota 		if (btrfs_advance_sb_log(device, i))
41668376d9e1SNaohiro Aota 			errors++;
4167a512bbf8SYan Zheng 	}
4168a512bbf8SYan Zheng 	return errors < i ? 0 : -1;
4169a512bbf8SYan Zheng }
4170a512bbf8SYan Zheng 
4171387125fcSChris Mason /*
4172abbb3b8eSDavid Sterba  * Wait for write completion of superblocks done by write_dev_supers,
4173abbb3b8eSDavid Sterba  * @max_mirrors same for write and wait phases.
4174abbb3b8eSDavid Sterba  *
4175314b6dd0SJohannes Thumshirn  * Return number of errors when page is not found or not marked up to
4176abbb3b8eSDavid Sterba  * date.
4177abbb3b8eSDavid Sterba  */
4178abbb3b8eSDavid Sterba static int wait_dev_supers(struct btrfs_device *device, int max_mirrors)
4179abbb3b8eSDavid Sterba {
4180abbb3b8eSDavid Sterba 	int i;
4181abbb3b8eSDavid Sterba 	int errors = 0;
4182b6a535faSHoward McLauchlan 	bool primary_failed = false;
418312659251SNaohiro Aota 	int ret;
4184abbb3b8eSDavid Sterba 	u64 bytenr;
4185abbb3b8eSDavid Sterba 
4186abbb3b8eSDavid Sterba 	if (max_mirrors == 0)
4187abbb3b8eSDavid Sterba 		max_mirrors = BTRFS_SUPER_MIRROR_MAX;
4188abbb3b8eSDavid Sterba 
4189abbb3b8eSDavid Sterba 	for (i = 0; i < max_mirrors; i++) {
4190314b6dd0SJohannes Thumshirn 		struct page *page;
4191314b6dd0SJohannes Thumshirn 
419212659251SNaohiro Aota 		ret = btrfs_sb_log_location(device, i, READ, &bytenr);
419312659251SNaohiro Aota 		if (ret == -ENOENT) {
419412659251SNaohiro Aota 			break;
419512659251SNaohiro Aota 		} else if (ret < 0) {
419612659251SNaohiro Aota 			errors++;
419712659251SNaohiro Aota 			if (i == 0)
419812659251SNaohiro Aota 				primary_failed = true;
419912659251SNaohiro Aota 			continue;
420012659251SNaohiro Aota 		}
4201abbb3b8eSDavid Sterba 		if (bytenr + BTRFS_SUPER_INFO_SIZE >=
4202abbb3b8eSDavid Sterba 		    device->commit_total_bytes)
4203abbb3b8eSDavid Sterba 			break;
4204abbb3b8eSDavid Sterba 
4205314b6dd0SJohannes Thumshirn 		page = find_get_page(device->bdev->bd_inode->i_mapping,
4206314b6dd0SJohannes Thumshirn 				     bytenr >> PAGE_SHIFT);
4207314b6dd0SJohannes Thumshirn 		if (!page) {
4208abbb3b8eSDavid Sterba 			errors++;
4209b6a535faSHoward McLauchlan 			if (i == 0)
4210b6a535faSHoward McLauchlan 				primary_failed = true;
4211abbb3b8eSDavid Sterba 			continue;
4212abbb3b8eSDavid Sterba 		}
4213314b6dd0SJohannes Thumshirn 		/* Page is submitted locked and unlocked once the IO completes */
4214314b6dd0SJohannes Thumshirn 		wait_on_page_locked(page);
4215314b6dd0SJohannes Thumshirn 		if (PageError(page)) {
4216abbb3b8eSDavid Sterba 			errors++;
4217b6a535faSHoward McLauchlan 			if (i == 0)
4218b6a535faSHoward McLauchlan 				primary_failed = true;
4219b6a535faSHoward McLauchlan 		}
4220abbb3b8eSDavid Sterba 
4221314b6dd0SJohannes Thumshirn 		/* Drop our reference */
4222314b6dd0SJohannes Thumshirn 		put_page(page);
4223abbb3b8eSDavid Sterba 
4224314b6dd0SJohannes Thumshirn 		/* Drop the reference from the writing run */
4225314b6dd0SJohannes Thumshirn 		put_page(page);
4226abbb3b8eSDavid Sterba 	}
4227abbb3b8eSDavid Sterba 
4228b6a535faSHoward McLauchlan 	/* log error, force error return */
4229b6a535faSHoward McLauchlan 	if (primary_failed) {
4230b6a535faSHoward McLauchlan 		btrfs_err(device->fs_info, "error writing primary super block to device %llu",
4231b6a535faSHoward McLauchlan 			  device->devid);
4232b6a535faSHoward McLauchlan 		return -1;
4233b6a535faSHoward McLauchlan 	}
4234b6a535faSHoward McLauchlan 
4235abbb3b8eSDavid Sterba 	return errors < i ? 0 : -1;
4236abbb3b8eSDavid Sterba }
4237abbb3b8eSDavid Sterba 
4238abbb3b8eSDavid Sterba /*
4239387125fcSChris Mason  * endio for the write_dev_flush, this will wake anyone waiting
4240387125fcSChris Mason  * for the barrier when it is done
4241387125fcSChris Mason  */
42424246a0b6SChristoph Hellwig static void btrfs_end_empty_barrier(struct bio *bio)
4243387125fcSChris Mason {
4244f9e69aa9SChristoph Hellwig 	bio_uninit(bio);
4245387125fcSChris Mason 	complete(bio->bi_private);
4246387125fcSChris Mason }
4247387125fcSChris Mason 
4248387125fcSChris Mason /*
42494fc6441aSAnand Jain  * Submit a flush request to the device if it supports it. Error handling is
42504fc6441aSAnand Jain  * done in the waiting counterpart.
4251387125fcSChris Mason  */
42524fc6441aSAnand Jain static void write_dev_flush(struct btrfs_device *device)
4253387125fcSChris Mason {
4254f9e69aa9SChristoph Hellwig 	struct bio *bio = &device->flush_bio;
4255387125fcSChris Mason 
4256a91cf0ffSWang Yugui #ifndef CONFIG_BTRFS_FS_CHECK_INTEGRITY
4257a91cf0ffSWang Yugui 	/*
4258a91cf0ffSWang Yugui 	 * When a disk has write caching disabled, we skip submission of a bio
4259a91cf0ffSWang Yugui 	 * with flush and sync requests before writing the superblock, since
4260a91cf0ffSWang Yugui 	 * it's not needed. However when the integrity checker is enabled, this
4261a91cf0ffSWang Yugui 	 * results in reports that there are metadata blocks referred by a
4262a91cf0ffSWang Yugui 	 * superblock that were not properly flushed. So don't skip the bio
4263a91cf0ffSWang Yugui 	 * submission only when the integrity checker is enabled for the sake
4264a91cf0ffSWang Yugui 	 * of simplicity, since this is a debug tool and not meant for use in
4265a91cf0ffSWang Yugui 	 * non-debug builds.
4266a91cf0ffSWang Yugui 	 */
426708e688fdSChristoph Hellwig 	if (!bdev_write_cache(device->bdev))
42684fc6441aSAnand Jain 		return;
4269a91cf0ffSWang Yugui #endif
4270387125fcSChris Mason 
4271f9e69aa9SChristoph Hellwig 	bio_init(bio, device->bdev, NULL, 0,
4272f9e69aa9SChristoph Hellwig 		 REQ_OP_WRITE | REQ_SYNC | REQ_PREFLUSH);
4273387125fcSChris Mason 	bio->bi_end_io = btrfs_end_empty_barrier;
4274387125fcSChris Mason 	init_completion(&device->flush_wait);
4275387125fcSChris Mason 	bio->bi_private = &device->flush_wait;
4276387125fcSChris Mason 
427758ff51f1SChristoph Hellwig 	btrfsic_check_bio(bio);
427858ff51f1SChristoph Hellwig 	submit_bio(bio);
42791c3063b6SAnand Jain 	set_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state);
42804fc6441aSAnand Jain }
4281387125fcSChris Mason 
42824fc6441aSAnand Jain /*
42834fc6441aSAnand Jain  * If the flush bio has been submitted by write_dev_flush, wait for it.
42844fc6441aSAnand Jain  */
42858c27cb35SLinus Torvalds static blk_status_t wait_dev_flush(struct btrfs_device *device)
42864fc6441aSAnand Jain {
4287f9e69aa9SChristoph Hellwig 	struct bio *bio = &device->flush_bio;
42884fc6441aSAnand Jain 
42891c3063b6SAnand Jain 	if (!test_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state))
429058efbc9fSOmar Sandoval 		return BLK_STS_OK;
42914fc6441aSAnand Jain 
42921c3063b6SAnand Jain 	clear_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state);
42932980d574SDavid Sterba 	wait_for_completion_io(&device->flush_wait);
42944fc6441aSAnand Jain 
42958c27cb35SLinus Torvalds 	return bio->bi_status;
4296387125fcSChris Mason }
4297387125fcSChris Mason 
4298d10b82feSQu Wenruo static int check_barrier_error(struct btrfs_fs_info *fs_info)
4299401b41e5SAnand Jain {
43006528b99dSAnand Jain 	if (!btrfs_check_rw_degradable(fs_info, NULL))
4301401b41e5SAnand Jain 		return -EIO;
4302387125fcSChris Mason 	return 0;
4303387125fcSChris Mason }
4304387125fcSChris Mason 
4305387125fcSChris Mason /*
4306387125fcSChris Mason  * send an empty flush down to each device in parallel,
4307387125fcSChris Mason  * then wait for them
4308387125fcSChris Mason  */
4309387125fcSChris Mason static int barrier_all_devices(struct btrfs_fs_info *info)
4310387125fcSChris Mason {
4311387125fcSChris Mason 	struct list_head *head;
4312387125fcSChris Mason 	struct btrfs_device *dev;
43135af3e8ccSStefan Behrens 	int errors_wait = 0;
43144e4cbee9SChristoph Hellwig 	blk_status_t ret;
4315387125fcSChris Mason 
43161538e6c5SDavid Sterba 	lockdep_assert_held(&info->fs_devices->device_list_mutex);
4317387125fcSChris Mason 	/* send down all the barriers */
4318387125fcSChris Mason 	head = &info->fs_devices->devices;
43191538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
4320e6e674bdSAnand Jain 		if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
4321f88ba6a2SHidetoshi Seto 			continue;
4322cea7c8bfSAnand Jain 		if (!dev->bdev)
4323387125fcSChris Mason 			continue;
4324e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
4325ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
4326387125fcSChris Mason 			continue;
4327387125fcSChris Mason 
43284fc6441aSAnand Jain 		write_dev_flush(dev);
432958efbc9fSOmar Sandoval 		dev->last_flush_error = BLK_STS_OK;
4330387125fcSChris Mason 	}
4331387125fcSChris Mason 
4332387125fcSChris Mason 	/* wait for all the barriers */
43331538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
4334e6e674bdSAnand Jain 		if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
4335f88ba6a2SHidetoshi Seto 			continue;
4336387125fcSChris Mason 		if (!dev->bdev) {
43375af3e8ccSStefan Behrens 			errors_wait++;
4338387125fcSChris Mason 			continue;
4339387125fcSChris Mason 		}
4340e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
4341ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
4342387125fcSChris Mason 			continue;
4343387125fcSChris Mason 
43444fc6441aSAnand Jain 		ret = wait_dev_flush(dev);
4345401b41e5SAnand Jain 		if (ret) {
4346401b41e5SAnand Jain 			dev->last_flush_error = ret;
434766b4993eSDavid Sterba 			btrfs_dev_stat_inc_and_print(dev,
434866b4993eSDavid Sterba 					BTRFS_DEV_STAT_FLUSH_ERRS);
43495af3e8ccSStefan Behrens 			errors_wait++;
4350387125fcSChris Mason 		}
4351401b41e5SAnand Jain 	}
4352401b41e5SAnand Jain 
4353cea7c8bfSAnand Jain 	if (errors_wait) {
4354401b41e5SAnand Jain 		/*
4355401b41e5SAnand Jain 		 * At some point we need the status of all disks
4356401b41e5SAnand Jain 		 * to arrive at the volume status. So error checking
4357401b41e5SAnand Jain 		 * is being pushed to a separate loop.
4358401b41e5SAnand Jain 		 */
4359d10b82feSQu Wenruo 		return check_barrier_error(info);
4360401b41e5SAnand Jain 	}
4361387125fcSChris Mason 	return 0;
4362387125fcSChris Mason }
4363387125fcSChris Mason 
4364943c6e99SZhao Lei int btrfs_get_num_tolerated_disk_barrier_failures(u64 flags)
4365943c6e99SZhao Lei {
43668789f4feSZhao Lei 	int raid_type;
43678789f4feSZhao Lei 	int min_tolerated = INT_MAX;
4368943c6e99SZhao Lei 
43698789f4feSZhao Lei 	if ((flags & BTRFS_BLOCK_GROUP_PROFILE_MASK) == 0 ||
43708789f4feSZhao Lei 	    (flags & BTRFS_AVAIL_ALLOC_BIT_SINGLE))
43718c3e3582SDavid Sterba 		min_tolerated = min_t(int, min_tolerated,
43728789f4feSZhao Lei 				    btrfs_raid_array[BTRFS_RAID_SINGLE].
43738789f4feSZhao Lei 				    tolerated_failures);
4374943c6e99SZhao Lei 
43758789f4feSZhao Lei 	for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) {
43768789f4feSZhao Lei 		if (raid_type == BTRFS_RAID_SINGLE)
43778789f4feSZhao Lei 			continue;
437841a6e891SAnand Jain 		if (!(flags & btrfs_raid_array[raid_type].bg_flag))
43798789f4feSZhao Lei 			continue;
43808c3e3582SDavid Sterba 		min_tolerated = min_t(int, min_tolerated,
43818789f4feSZhao Lei 				    btrfs_raid_array[raid_type].
43828789f4feSZhao Lei 				    tolerated_failures);
43838789f4feSZhao Lei 	}
4384943c6e99SZhao Lei 
43858789f4feSZhao Lei 	if (min_tolerated == INT_MAX) {
4386ab8d0fc4SJeff Mahoney 		pr_warn("BTRFS: unknown raid flag: %llu", flags);
43878789f4feSZhao Lei 		min_tolerated = 0;
43888789f4feSZhao Lei 	}
43898789f4feSZhao Lei 
43908789f4feSZhao Lei 	return min_tolerated;
4391943c6e99SZhao Lei }
4392943c6e99SZhao Lei 
4393eece6a9cSDavid Sterba int write_all_supers(struct btrfs_fs_info *fs_info, int max_mirrors)
4394f2984462SChris Mason {
4395e5e9a520SChris Mason 	struct list_head *head;
4396f2984462SChris Mason 	struct btrfs_device *dev;
4397a061fc8dSChris Mason 	struct btrfs_super_block *sb;
4398f2984462SChris Mason 	struct btrfs_dev_item *dev_item;
4399f2984462SChris Mason 	int ret;
4400f2984462SChris Mason 	int do_barriers;
4401a236aed1SChris Mason 	int max_errors;
4402a236aed1SChris Mason 	int total_errors = 0;
4403a061fc8dSChris Mason 	u64 flags;
4404f2984462SChris Mason 
44050b246afaSJeff Mahoney 	do_barriers = !btrfs_test_opt(fs_info, NOBARRIER);
4406fed3b381SLiu Bo 
4407fed3b381SLiu Bo 	/*
4408fed3b381SLiu Bo 	 * max_mirrors == 0 indicates we're from commit_transaction,
4409fed3b381SLiu Bo 	 * not from fsync where the tree roots in fs_info have not
4410fed3b381SLiu Bo 	 * been consistent on disk.
4411fed3b381SLiu Bo 	 */
4412fed3b381SLiu Bo 	if (max_mirrors == 0)
44130b246afaSJeff Mahoney 		backup_super_roots(fs_info);
4414f2984462SChris Mason 
44150b246afaSJeff Mahoney 	sb = fs_info->super_for_commit;
4416a061fc8dSChris Mason 	dev_item = &sb->dev_item;
4417e5e9a520SChris Mason 
44180b246afaSJeff Mahoney 	mutex_lock(&fs_info->fs_devices->device_list_mutex);
44190b246afaSJeff Mahoney 	head = &fs_info->fs_devices->devices;
44200b246afaSJeff Mahoney 	max_errors = btrfs_super_num_devices(fs_info->super_copy) - 1;
4421387125fcSChris Mason 
44225af3e8ccSStefan Behrens 	if (do_barriers) {
44230b246afaSJeff Mahoney 		ret = barrier_all_devices(fs_info);
44245af3e8ccSStefan Behrens 		if (ret) {
44255af3e8ccSStefan Behrens 			mutex_unlock(
44260b246afaSJeff Mahoney 				&fs_info->fs_devices->device_list_mutex);
44270b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret,
44285af3e8ccSStefan Behrens 					      "errors while submitting device barriers.");
44295af3e8ccSStefan Behrens 			return ret;
44305af3e8ccSStefan Behrens 		}
44315af3e8ccSStefan Behrens 	}
4432387125fcSChris Mason 
44331538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
4434dfe25020SChris Mason 		if (!dev->bdev) {
4435dfe25020SChris Mason 			total_errors++;
4436dfe25020SChris Mason 			continue;
4437dfe25020SChris Mason 		}
4438e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
4439ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
4440dfe25020SChris Mason 			continue;
4441dfe25020SChris Mason 
44422b82032cSYan Zheng 		btrfs_set_stack_device_generation(dev_item, 0);
4443a061fc8dSChris Mason 		btrfs_set_stack_device_type(dev_item, dev->type);
4444a061fc8dSChris Mason 		btrfs_set_stack_device_id(dev_item, dev->devid);
44457df69d3eSMiao Xie 		btrfs_set_stack_device_total_bytes(dev_item,
4446935e5cc9SMiao Xie 						   dev->commit_total_bytes);
4447ce7213c7SMiao Xie 		btrfs_set_stack_device_bytes_used(dev_item,
4448ce7213c7SMiao Xie 						  dev->commit_bytes_used);
4449a061fc8dSChris Mason 		btrfs_set_stack_device_io_align(dev_item, dev->io_align);
4450a061fc8dSChris Mason 		btrfs_set_stack_device_io_width(dev_item, dev->io_width);
4451a061fc8dSChris Mason 		btrfs_set_stack_device_sector_size(dev_item, dev->sector_size);
4452a061fc8dSChris Mason 		memcpy(dev_item->uuid, dev->uuid, BTRFS_UUID_SIZE);
44537239ff4bSNikolay Borisov 		memcpy(dev_item->fsid, dev->fs_devices->metadata_uuid,
44547239ff4bSNikolay Borisov 		       BTRFS_FSID_SIZE);
4455a512bbf8SYan Zheng 
4456a061fc8dSChris Mason 		flags = btrfs_super_flags(sb);
4457a061fc8dSChris Mason 		btrfs_set_super_flags(sb, flags | BTRFS_HEADER_FLAG_WRITTEN);
4458f2984462SChris Mason 
445975cb857dSQu Wenruo 		ret = btrfs_validate_write_super(fs_info, sb);
446075cb857dSQu Wenruo 		if (ret < 0) {
446175cb857dSQu Wenruo 			mutex_unlock(&fs_info->fs_devices->device_list_mutex);
446275cb857dSQu Wenruo 			btrfs_handle_fs_error(fs_info, -EUCLEAN,
446375cb857dSQu Wenruo 				"unexpected superblock corruption detected");
446475cb857dSQu Wenruo 			return -EUCLEAN;
446575cb857dSQu Wenruo 		}
446675cb857dSQu Wenruo 
4467abbb3b8eSDavid Sterba 		ret = write_dev_supers(dev, sb, max_mirrors);
4468a236aed1SChris Mason 		if (ret)
4469a236aed1SChris Mason 			total_errors++;
4470f2984462SChris Mason 	}
4471a236aed1SChris Mason 	if (total_errors > max_errors) {
44720b246afaSJeff Mahoney 		btrfs_err(fs_info, "%d errors while writing supers",
4473d397712bSChris Mason 			  total_errors);
44740b246afaSJeff Mahoney 		mutex_unlock(&fs_info->fs_devices->device_list_mutex);
447579787eaaSJeff Mahoney 
44769d565ba4SStefan Behrens 		/* FUA is masked off if unsupported and can't be the reason */
44770b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, -EIO,
44780b246afaSJeff Mahoney 				      "%d errors while writing supers",
44790b246afaSJeff Mahoney 				      total_errors);
44809d565ba4SStefan Behrens 		return -EIO;
4481a236aed1SChris Mason 	}
4482f2984462SChris Mason 
4483a512bbf8SYan Zheng 	total_errors = 0;
44841538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
4485dfe25020SChris Mason 		if (!dev->bdev)
4486dfe25020SChris Mason 			continue;
4487e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
4488ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
4489dfe25020SChris Mason 			continue;
4490dfe25020SChris Mason 
4491abbb3b8eSDavid Sterba 		ret = wait_dev_supers(dev, max_mirrors);
4492a512bbf8SYan Zheng 		if (ret)
44931259ab75SChris Mason 			total_errors++;
4494f2984462SChris Mason 	}
44950b246afaSJeff Mahoney 	mutex_unlock(&fs_info->fs_devices->device_list_mutex);
4496a236aed1SChris Mason 	if (total_errors > max_errors) {
44970b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, -EIO,
44980b246afaSJeff Mahoney 				      "%d errors while writing supers",
44990b246afaSJeff Mahoney 				      total_errors);
450079787eaaSJeff Mahoney 		return -EIO;
4501a236aed1SChris Mason 	}
4502f2984462SChris Mason 	return 0;
4503f2984462SChris Mason }
4504f2984462SChris Mason 
4505cb517eabSMiao Xie /* Drop a fs root from the radix tree and free it. */
4506cb517eabSMiao Xie void btrfs_drop_and_free_fs_root(struct btrfs_fs_info *fs_info,
4507cb517eabSMiao Xie 				  struct btrfs_root *root)
45082619ba1fSChris Mason {
45094785e24fSJosef Bacik 	bool drop_ref = false;
45104785e24fSJosef Bacik 
4511fc7cbcd4SDavid Sterba 	spin_lock(&fs_info->fs_roots_radix_lock);
4512fc7cbcd4SDavid Sterba 	radix_tree_delete(&fs_info->fs_roots_radix,
4513fc7cbcd4SDavid Sterba 			  (unsigned long)root->root_key.objectid);
4514fc7cbcd4SDavid Sterba 	if (test_and_clear_bit(BTRFS_ROOT_IN_RADIX, &root->state))
45154785e24fSJosef Bacik 		drop_ref = true;
4516fc7cbcd4SDavid Sterba 	spin_unlock(&fs_info->fs_roots_radix_lock);
451776dda93cSYan, Zheng 
451884961539SJosef Bacik 	if (BTRFS_FS_ERROR(fs_info)) {
4519ef67963dSJosef Bacik 		ASSERT(root->log_root == NULL);
45201c1ea4f7SLiu Bo 		if (root->reloc_root) {
452100246528SJosef Bacik 			btrfs_put_root(root->reloc_root);
45221c1ea4f7SLiu Bo 			root->reloc_root = NULL;
45231c1ea4f7SLiu Bo 		}
45241c1ea4f7SLiu Bo 	}
45253321719eSLiu Bo 
45264785e24fSJosef Bacik 	if (drop_ref)
452700246528SJosef Bacik 		btrfs_put_root(root);
45282619ba1fSChris Mason }
45292619ba1fSChris Mason 
4530c146afadSYan Zheng int btrfs_cleanup_fs_roots(struct btrfs_fs_info *fs_info)
4531c146afadSYan Zheng {
4532fc7cbcd4SDavid Sterba 	u64 root_objectid = 0;
4533fc7cbcd4SDavid Sterba 	struct btrfs_root *gang[8];
4534fc7cbcd4SDavid Sterba 	int i = 0;
453565d33fd7SQu Wenruo 	int err = 0;
4536fc7cbcd4SDavid Sterba 	unsigned int ret = 0;
4537c146afadSYan Zheng 
4538c146afadSYan Zheng 	while (1) {
4539fc7cbcd4SDavid Sterba 		spin_lock(&fs_info->fs_roots_radix_lock);
4540fc7cbcd4SDavid Sterba 		ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
4541fc7cbcd4SDavid Sterba 					     (void **)gang, root_objectid,
4542fc7cbcd4SDavid Sterba 					     ARRAY_SIZE(gang));
4543fc7cbcd4SDavid Sterba 		if (!ret) {
4544fc7cbcd4SDavid Sterba 			spin_unlock(&fs_info->fs_roots_radix_lock);
4545c146afadSYan Zheng 			break;
454665d33fd7SQu Wenruo 		}
4547fc7cbcd4SDavid Sterba 		root_objectid = gang[ret - 1]->root_key.objectid + 1;
454866b4ffd1SJosef Bacik 
4549fc7cbcd4SDavid Sterba 		for (i = 0; i < ret; i++) {
4550fc7cbcd4SDavid Sterba 			/* Avoid to grab roots in dead_roots */
4551fc7cbcd4SDavid Sterba 			if (btrfs_root_refs(&gang[i]->root_item) == 0) {
4552fc7cbcd4SDavid Sterba 				gang[i] = NULL;
455365d33fd7SQu Wenruo 				continue;
4554c146afadSYan Zheng 			}
4555fc7cbcd4SDavid Sterba 			/* grab all the search result for later use */
4556fc7cbcd4SDavid Sterba 			gang[i] = btrfs_grab_root(gang[i]);
4557fc7cbcd4SDavid Sterba 		}
4558fc7cbcd4SDavid Sterba 		spin_unlock(&fs_info->fs_roots_radix_lock);
4559fc7cbcd4SDavid Sterba 
4560fc7cbcd4SDavid Sterba 		for (i = 0; i < ret; i++) {
4561fc7cbcd4SDavid Sterba 			if (!gang[i])
4562fc7cbcd4SDavid Sterba 				continue;
4563fc7cbcd4SDavid Sterba 			root_objectid = gang[i]->root_key.objectid;
4564fc7cbcd4SDavid Sterba 			err = btrfs_orphan_cleanup(gang[i]);
4565fc7cbcd4SDavid Sterba 			if (err)
4566fc7cbcd4SDavid Sterba 				break;
4567fc7cbcd4SDavid Sterba 			btrfs_put_root(gang[i]);
4568fc7cbcd4SDavid Sterba 		}
4569fc7cbcd4SDavid Sterba 		root_objectid++;
4570c146afadSYan Zheng 	}
457165d33fd7SQu Wenruo 
4572fc7cbcd4SDavid Sterba 	/* release the uncleaned roots due to error */
4573fc7cbcd4SDavid Sterba 	for (; i < ret; i++) {
4574fc7cbcd4SDavid Sterba 		if (gang[i])
4575fc7cbcd4SDavid Sterba 			btrfs_put_root(gang[i]);
457665d33fd7SQu Wenruo 	}
457765d33fd7SQu Wenruo 	return err;
4578c146afadSYan Zheng }
4579c146afadSYan Zheng 
45806bccf3abSJeff Mahoney int btrfs_commit_super(struct btrfs_fs_info *fs_info)
4581c146afadSYan Zheng {
45826bccf3abSJeff Mahoney 	struct btrfs_root *root = fs_info->tree_root;
4583c146afadSYan Zheng 	struct btrfs_trans_handle *trans;
4584c146afadSYan Zheng 
45850b246afaSJeff Mahoney 	mutex_lock(&fs_info->cleaner_mutex);
45862ff7e61eSJeff Mahoney 	btrfs_run_delayed_iputs(fs_info);
45870b246afaSJeff Mahoney 	mutex_unlock(&fs_info->cleaner_mutex);
45880b246afaSJeff Mahoney 	wake_up_process(fs_info->cleaner_kthread);
4589c71bf099SYan, Zheng 
4590c71bf099SYan, Zheng 	/* wait until ongoing cleanup work done */
45910b246afaSJeff Mahoney 	down_write(&fs_info->cleanup_work_sem);
45920b246afaSJeff Mahoney 	up_write(&fs_info->cleanup_work_sem);
4593c71bf099SYan, Zheng 
45947a7eaa40SJosef Bacik 	trans = btrfs_join_transaction(root);
45953612b495STsutomu Itoh 	if (IS_ERR(trans))
45963612b495STsutomu Itoh 		return PTR_ERR(trans);
45973a45bb20SJeff Mahoney 	return btrfs_commit_transaction(trans);
4598c146afadSYan Zheng }
4599c146afadSYan Zheng 
460036c86a9eSQu Wenruo static void warn_about_uncommitted_trans(struct btrfs_fs_info *fs_info)
460136c86a9eSQu Wenruo {
460236c86a9eSQu Wenruo 	struct btrfs_transaction *trans;
460336c86a9eSQu Wenruo 	struct btrfs_transaction *tmp;
460436c86a9eSQu Wenruo 	bool found = false;
460536c86a9eSQu Wenruo 
460636c86a9eSQu Wenruo 	if (list_empty(&fs_info->trans_list))
460736c86a9eSQu Wenruo 		return;
460836c86a9eSQu Wenruo 
460936c86a9eSQu Wenruo 	/*
461036c86a9eSQu Wenruo 	 * This function is only called at the very end of close_ctree(),
461136c86a9eSQu Wenruo 	 * thus no other running transaction, no need to take trans_lock.
461236c86a9eSQu Wenruo 	 */
461336c86a9eSQu Wenruo 	ASSERT(test_bit(BTRFS_FS_CLOSING_DONE, &fs_info->flags));
461436c86a9eSQu Wenruo 	list_for_each_entry_safe(trans, tmp, &fs_info->trans_list, list) {
461536c86a9eSQu Wenruo 		struct extent_state *cached = NULL;
461636c86a9eSQu Wenruo 		u64 dirty_bytes = 0;
461736c86a9eSQu Wenruo 		u64 cur = 0;
461836c86a9eSQu Wenruo 		u64 found_start;
461936c86a9eSQu Wenruo 		u64 found_end;
462036c86a9eSQu Wenruo 
462136c86a9eSQu Wenruo 		found = true;
462236c86a9eSQu Wenruo 		while (!find_first_extent_bit(&trans->dirty_pages, cur,
462336c86a9eSQu Wenruo 			&found_start, &found_end, EXTENT_DIRTY, &cached)) {
462436c86a9eSQu Wenruo 			dirty_bytes += found_end + 1 - found_start;
462536c86a9eSQu Wenruo 			cur = found_end + 1;
462636c86a9eSQu Wenruo 		}
462736c86a9eSQu Wenruo 		btrfs_warn(fs_info,
462836c86a9eSQu Wenruo 	"transaction %llu (with %llu dirty metadata bytes) is not committed",
462936c86a9eSQu Wenruo 			   trans->transid, dirty_bytes);
463036c86a9eSQu Wenruo 		btrfs_cleanup_one_transaction(trans, fs_info);
463136c86a9eSQu Wenruo 
463236c86a9eSQu Wenruo 		if (trans == fs_info->running_transaction)
463336c86a9eSQu Wenruo 			fs_info->running_transaction = NULL;
463436c86a9eSQu Wenruo 		list_del_init(&trans->list);
463536c86a9eSQu Wenruo 
463636c86a9eSQu Wenruo 		btrfs_put_transaction(trans);
463736c86a9eSQu Wenruo 		trace_btrfs_transaction_commit(fs_info);
463836c86a9eSQu Wenruo 	}
463936c86a9eSQu Wenruo 	ASSERT(!found);
464036c86a9eSQu Wenruo }
464136c86a9eSQu Wenruo 
4642b105e927SDavid Sterba void __cold close_ctree(struct btrfs_fs_info *fs_info)
4643eb60ceacSChris Mason {
4644c146afadSYan Zheng 	int ret;
4645e089f05cSChris Mason 
4646afcdd129SJosef Bacik 	set_bit(BTRFS_FS_CLOSING_START, &fs_info->flags);
464731e70e52SFilipe Manana 
464831e70e52SFilipe Manana 	/*
46498a1f1e3dSFilipe Manana 	 * If we had UNFINISHED_DROPS we could still be processing them, so
46508a1f1e3dSFilipe Manana 	 * clear that bit and wake up relocation so it can stop.
46518a1f1e3dSFilipe Manana 	 * We must do this before stopping the block group reclaim task, because
46528a1f1e3dSFilipe Manana 	 * at btrfs_relocate_block_group() we wait for this bit, and after the
46538a1f1e3dSFilipe Manana 	 * wait we stop with -EINTR if btrfs_fs_closing() returns non-zero - we
46548a1f1e3dSFilipe Manana 	 * have just set BTRFS_FS_CLOSING_START, so btrfs_fs_closing() will
46558a1f1e3dSFilipe Manana 	 * return 1.
46568a1f1e3dSFilipe Manana 	 */
46578a1f1e3dSFilipe Manana 	btrfs_wake_unfinished_drop(fs_info);
46588a1f1e3dSFilipe Manana 
46598a1f1e3dSFilipe Manana 	/*
466031e70e52SFilipe Manana 	 * We may have the reclaim task running and relocating a data block group,
466131e70e52SFilipe Manana 	 * in which case it may create delayed iputs. So stop it before we park
466231e70e52SFilipe Manana 	 * the cleaner kthread otherwise we can get new delayed iputs after
466331e70e52SFilipe Manana 	 * parking the cleaner, and that can make the async reclaim task to hang
466431e70e52SFilipe Manana 	 * if it's waiting for delayed iputs to complete, since the cleaner is
466531e70e52SFilipe Manana 	 * parked and can not run delayed iputs - this will make us hang when
466631e70e52SFilipe Manana 	 * trying to stop the async reclaim task.
466731e70e52SFilipe Manana 	 */
466831e70e52SFilipe Manana 	cancel_work_sync(&fs_info->reclaim_bgs_work);
4669d6fd0ae2SOmar Sandoval 	/*
4670d6fd0ae2SOmar Sandoval 	 * We don't want the cleaner to start new transactions, add more delayed
4671d6fd0ae2SOmar Sandoval 	 * iputs, etc. while we're closing. We can't use kthread_stop() yet
4672d6fd0ae2SOmar Sandoval 	 * because that frees the task_struct, and the transaction kthread might
4673d6fd0ae2SOmar Sandoval 	 * still try to wake up the cleaner.
4674d6fd0ae2SOmar Sandoval 	 */
4675d6fd0ae2SOmar Sandoval 	kthread_park(fs_info->cleaner_kthread);
4676a2135011SChris Mason 
46777343dd61SJustin Maggard 	/* wait for the qgroup rescan worker to stop */
4678d06f23d6SJeff Mahoney 	btrfs_qgroup_wait_for_completion(fs_info, false);
46797343dd61SJustin Maggard 
4680803b2f54SStefan Behrens 	/* wait for the uuid_scan task to finish */
4681803b2f54SStefan Behrens 	down(&fs_info->uuid_tree_rescan_sem);
4682803b2f54SStefan Behrens 	/* avoid complains from lockdep et al., set sem back to initial state */
4683803b2f54SStefan Behrens 	up(&fs_info->uuid_tree_rescan_sem);
4684803b2f54SStefan Behrens 
4685837d5b6eSIlya Dryomov 	/* pause restriper - we want to resume on mount */
4686aa1b8cd4SStefan Behrens 	btrfs_pause_balance(fs_info);
4687837d5b6eSIlya Dryomov 
46888dabb742SStefan Behrens 	btrfs_dev_replace_suspend_for_unmount(fs_info);
46898dabb742SStefan Behrens 
4690aa1b8cd4SStefan Behrens 	btrfs_scrub_cancel(fs_info);
46914cb5300bSChris Mason 
46924cb5300bSChris Mason 	/* wait for any defraggers to finish */
46934cb5300bSChris Mason 	wait_event(fs_info->transaction_wait,
46944cb5300bSChris Mason 		   (atomic_read(&fs_info->defrag_running) == 0));
46954cb5300bSChris Mason 
46964cb5300bSChris Mason 	/* clear out the rbtree of defraggable inodes */
469726176e7cSMiao Xie 	btrfs_cleanup_defrag_inodes(fs_info);
46984cb5300bSChris Mason 
4699a362bb86SFilipe Manana 	/*
4700a362bb86SFilipe Manana 	 * After we parked the cleaner kthread, ordered extents may have
4701a362bb86SFilipe Manana 	 * completed and created new delayed iputs. If one of the async reclaim
4702a362bb86SFilipe Manana 	 * tasks is running and in the RUN_DELAYED_IPUTS flush state, then we
4703a362bb86SFilipe Manana 	 * can hang forever trying to stop it, because if a delayed iput is
4704a362bb86SFilipe Manana 	 * added after it ran btrfs_run_delayed_iputs() and before it called
4705a362bb86SFilipe Manana 	 * btrfs_wait_on_delayed_iputs(), it will hang forever since there is
4706a362bb86SFilipe Manana 	 * no one else to run iputs.
4707a362bb86SFilipe Manana 	 *
4708a362bb86SFilipe Manana 	 * So wait for all ongoing ordered extents to complete and then run
4709a362bb86SFilipe Manana 	 * delayed iputs. This works because once we reach this point no one
4710a362bb86SFilipe Manana 	 * can either create new ordered extents nor create delayed iputs
4711a362bb86SFilipe Manana 	 * through some other means.
4712a362bb86SFilipe Manana 	 *
4713a362bb86SFilipe Manana 	 * Also note that btrfs_wait_ordered_roots() is not safe here, because
4714a362bb86SFilipe Manana 	 * it waits for BTRFS_ORDERED_COMPLETE to be set on an ordered extent,
4715a362bb86SFilipe Manana 	 * but the delayed iput for the respective inode is made only when doing
4716a362bb86SFilipe Manana 	 * the final btrfs_put_ordered_extent() (which must happen at
4717a362bb86SFilipe Manana 	 * btrfs_finish_ordered_io() when we are unmounting).
4718a362bb86SFilipe Manana 	 */
4719a362bb86SFilipe Manana 	btrfs_flush_workqueue(fs_info->endio_write_workers);
4720a362bb86SFilipe Manana 	/* Ordered extents for free space inodes. */
4721a362bb86SFilipe Manana 	btrfs_flush_workqueue(fs_info->endio_freespace_worker);
4722a362bb86SFilipe Manana 	btrfs_run_delayed_iputs(fs_info);
4723a362bb86SFilipe Manana 
472421c7e756SMiao Xie 	cancel_work_sync(&fs_info->async_reclaim_work);
472557056740SJosef Bacik 	cancel_work_sync(&fs_info->async_data_reclaim_work);
4726576fa348SJosef Bacik 	cancel_work_sync(&fs_info->preempt_reclaim_work);
472721c7e756SMiao Xie 
4728b0643e59SDennis Zhou 	/* Cancel or finish ongoing discard work */
4729b0643e59SDennis Zhou 	btrfs_discard_cleanup(fs_info);
4730b0643e59SDennis Zhou 
4731bc98a42cSDavid Howells 	if (!sb_rdonly(fs_info->sb)) {
4732e44163e1SJeff Mahoney 		/*
4733d6fd0ae2SOmar Sandoval 		 * The cleaner kthread is stopped, so do one final pass over
4734d6fd0ae2SOmar Sandoval 		 * unused block groups.
4735e44163e1SJeff Mahoney 		 */
47360b246afaSJeff Mahoney 		btrfs_delete_unused_bgs(fs_info);
4737e44163e1SJeff Mahoney 
4738f0cc2cd7SFilipe Manana 		/*
4739f0cc2cd7SFilipe Manana 		 * There might be existing delayed inode workers still running
4740f0cc2cd7SFilipe Manana 		 * and holding an empty delayed inode item. We must wait for
4741f0cc2cd7SFilipe Manana 		 * them to complete first because they can create a transaction.
4742f0cc2cd7SFilipe Manana 		 * This happens when someone calls btrfs_balance_delayed_items()
4743f0cc2cd7SFilipe Manana 		 * and then a transaction commit runs the same delayed nodes
4744f0cc2cd7SFilipe Manana 		 * before any delayed worker has done something with the nodes.
4745f0cc2cd7SFilipe Manana 		 * We must wait for any worker here and not at transaction
4746f0cc2cd7SFilipe Manana 		 * commit time since that could cause a deadlock.
4747f0cc2cd7SFilipe Manana 		 * This is a very rare case.
4748f0cc2cd7SFilipe Manana 		 */
4749f0cc2cd7SFilipe Manana 		btrfs_flush_workqueue(fs_info->delayed_workers);
4750f0cc2cd7SFilipe Manana 
47516bccf3abSJeff Mahoney 		ret = btrfs_commit_super(fs_info);
4752d397712bSChris Mason 		if (ret)
475304892340SEric Sandeen 			btrfs_err(fs_info, "commit super ret %d", ret);
4754c146afadSYan Zheng 	}
4755ed2ff2cbSChris Mason 
475684961539SJosef Bacik 	if (BTRFS_FS_ERROR(fs_info))
47572ff7e61eSJeff Mahoney 		btrfs_error_commit_super(fs_info);
4758acce952bSliubo 
4759e3029d9fSAl Viro 	kthread_stop(fs_info->transaction_kthread);
4760e3029d9fSAl Viro 	kthread_stop(fs_info->cleaner_kthread);
47618929ecfaSYan, Zheng 
4762e187831eSJosef Bacik 	ASSERT(list_empty(&fs_info->delayed_iputs));
4763afcdd129SJosef Bacik 	set_bit(BTRFS_FS_CLOSING_DONE, &fs_info->flags);
4764f25784b3SYan Zheng 
47655958253cSQu Wenruo 	if (btrfs_check_quota_leak(fs_info)) {
47665958253cSQu Wenruo 		WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
47675958253cSQu Wenruo 		btrfs_err(fs_info, "qgroup reserved space leaked");
47685958253cSQu Wenruo 	}
47695958253cSQu Wenruo 
477004892340SEric Sandeen 	btrfs_free_qgroup_config(fs_info);
4771fe816d0fSNikolay Borisov 	ASSERT(list_empty(&fs_info->delalloc_roots));
4772bcef60f2SArne Jansen 
4773963d678bSMiao Xie 	if (percpu_counter_sum(&fs_info->delalloc_bytes)) {
477404892340SEric Sandeen 		btrfs_info(fs_info, "at unmount delalloc count %lld",
4775963d678bSMiao Xie 		       percpu_counter_sum(&fs_info->delalloc_bytes));
4776b0c68f8bSChris Mason 	}
477731153d81SYan Zheng 
47785deb17e1SJosef Bacik 	if (percpu_counter_sum(&fs_info->ordered_bytes))
47794297ff84SJosef Bacik 		btrfs_info(fs_info, "at unmount dio bytes count %lld",
47805deb17e1SJosef Bacik 			   percpu_counter_sum(&fs_info->ordered_bytes));
47814297ff84SJosef Bacik 
47826618a59bSAnand Jain 	btrfs_sysfs_remove_mounted(fs_info);
4783b7c35e81SAnand Jain 	btrfs_sysfs_remove_fsid(fs_info->fs_devices);
47845ac1d209SJeff Mahoney 
47851a4319ccSLiu Bo 	btrfs_put_block_group_cache(fs_info);
47861a4319ccSLiu Bo 
4787de348ee0SWang Shilong 	/*
4788de348ee0SWang Shilong 	 * we must make sure there is not any read request to
4789de348ee0SWang Shilong 	 * submit after we stopping all workers.
4790de348ee0SWang Shilong 	 */
4791de348ee0SWang Shilong 	invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
479296192499SJosef Bacik 	btrfs_stop_all_workers(fs_info);
479396192499SJosef Bacik 
47940a31daa4SFilipe Manana 	/* We shouldn't have any transaction open at this point */
479536c86a9eSQu Wenruo 	warn_about_uncommitted_trans(fs_info);
47960a31daa4SFilipe Manana 
4797afcdd129SJosef Bacik 	clear_bit(BTRFS_FS_OPEN, &fs_info->flags);
47984273eaffSAnand Jain 	free_root_pointers(fs_info, true);
47998c38938cSJosef Bacik 	btrfs_free_fs_roots(fs_info);
48009ad6b7bcSChris Mason 
48014e19443dSJosef Bacik 	/*
48024e19443dSJosef Bacik 	 * We must free the block groups after dropping the fs_roots as we could
48034e19443dSJosef Bacik 	 * have had an IO error and have left over tree log blocks that aren't
48044e19443dSJosef Bacik 	 * cleaned up until the fs roots are freed.  This makes the block group
48054e19443dSJosef Bacik 	 * accounting appear to be wrong because there's pending reserved bytes,
48064e19443dSJosef Bacik 	 * so make sure we do the block group cleanup afterwards.
48074e19443dSJosef Bacik 	 */
48084e19443dSJosef Bacik 	btrfs_free_block_groups(fs_info);
48094e19443dSJosef Bacik 
481013e6c37bSJosef Bacik 	iput(fs_info->btree_inode);
4811d6bfde87SChris Mason 
481221adbd5cSStefan Behrens #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
48130b246afaSJeff Mahoney 	if (btrfs_test_opt(fs_info, CHECK_INTEGRITY))
48142ff7e61eSJeff Mahoney 		btrfsic_unmount(fs_info->fs_devices);
481521adbd5cSStefan Behrens #endif
481621adbd5cSStefan Behrens 
48170b86a832SChris Mason 	btrfs_mapping_tree_free(&fs_info->mapping_tree);
481868c94e55SNikolay Borisov 	btrfs_close_devices(fs_info->fs_devices);
4819eb60ceacSChris Mason }
4820eb60ceacSChris Mason 
4821b9fab919SChris Mason int btrfs_buffer_uptodate(struct extent_buffer *buf, u64 parent_transid,
4822b9fab919SChris Mason 			  int atomic)
4823ccd467d6SChris Mason {
48241259ab75SChris Mason 	int ret;
4825727011e0SChris Mason 	struct inode *btree_inode = buf->pages[0]->mapping->host;
48261259ab75SChris Mason 
48270b32f4bbSJosef Bacik 	ret = extent_buffer_uptodate(buf);
48281259ab75SChris Mason 	if (!ret)
48291259ab75SChris Mason 		return ret;
48301259ab75SChris Mason 
48311259ab75SChris Mason 	ret = verify_parent_transid(&BTRFS_I(btree_inode)->io_tree, buf,
4832b9fab919SChris Mason 				    parent_transid, atomic);
4833b9fab919SChris Mason 	if (ret == -EAGAIN)
4834b9fab919SChris Mason 		return ret;
48351259ab75SChris Mason 	return !ret;
48365f39d397SChris Mason }
48376702ed49SChris Mason 
48385f39d397SChris Mason void btrfs_mark_buffer_dirty(struct extent_buffer *buf)
48395f39d397SChris Mason {
48402f4d60dfSQu Wenruo 	struct btrfs_fs_info *fs_info = buf->fs_info;
48415f39d397SChris Mason 	u64 transid = btrfs_header_generation(buf);
4842b9473439SChris Mason 	int was_dirty;
4843b4ce94deSChris Mason 
484406ea65a3SJosef Bacik #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
484506ea65a3SJosef Bacik 	/*
484606ea65a3SJosef Bacik 	 * This is a fast path so only do this check if we have sanity tests
484752042d8eSAndrea Gelmini 	 * enabled.  Normal people shouldn't be using unmapped buffers as dirty
484806ea65a3SJosef Bacik 	 * outside of the sanity tests.
484906ea65a3SJosef Bacik 	 */
4850b0132a3bSNikolay Borisov 	if (unlikely(test_bit(EXTENT_BUFFER_UNMAPPED, &buf->bflags)))
485106ea65a3SJosef Bacik 		return;
485206ea65a3SJosef Bacik #endif
485349d0c642SFilipe Manana 	btrfs_assert_tree_write_locked(buf);
48540b246afaSJeff Mahoney 	if (transid != fs_info->generation)
48555d163e0eSJeff Mahoney 		WARN(1, KERN_CRIT "btrfs transid mismatch buffer %llu, found %llu running %llu\n",
48560b246afaSJeff Mahoney 			buf->start, transid, fs_info->generation);
48570b32f4bbSJosef Bacik 	was_dirty = set_extent_buffer_dirty(buf);
4858e2d84521SMiao Xie 	if (!was_dirty)
4859104b4e51SNikolay Borisov 		percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
4860e2d84521SMiao Xie 					 buf->len,
48610b246afaSJeff Mahoney 					 fs_info->dirty_metadata_batch);
48621f21ef0aSFilipe Manana #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
486369fc6cbbSQu Wenruo 	/*
486469fc6cbbSQu Wenruo 	 * Since btrfs_mark_buffer_dirty() can be called with item pointer set
486569fc6cbbSQu Wenruo 	 * but item data not updated.
486669fc6cbbSQu Wenruo 	 * So here we should only check item pointers, not item data.
486769fc6cbbSQu Wenruo 	 */
486869fc6cbbSQu Wenruo 	if (btrfs_header_level(buf) == 0 &&
4869cfdaad5eSDavid Sterba 	    btrfs_check_leaf_relaxed(buf)) {
4870a4f78750SDavid Sterba 		btrfs_print_leaf(buf);
48711f21ef0aSFilipe Manana 		ASSERT(0);
48721f21ef0aSFilipe Manana 	}
48731f21ef0aSFilipe Manana #endif
4874eb60ceacSChris Mason }
4875eb60ceacSChris Mason 
48762ff7e61eSJeff Mahoney static void __btrfs_btree_balance_dirty(struct btrfs_fs_info *fs_info,
4877b53d3f5dSLiu Bo 					int flush_delayed)
487835b7e476SChris Mason {
4879188de649SChris Mason 	/*
4880188de649SChris Mason 	 * looks as though older kernels can get into trouble with
4881188de649SChris Mason 	 * this code, they end up stuck in balance_dirty_pages forever
4882188de649SChris Mason 	 */
4883e2d84521SMiao Xie 	int ret;
4884d6bfde87SChris Mason 
48856933c02eSJens Axboe 	if (current->flags & PF_MEMALLOC)
4886d6bfde87SChris Mason 		return;
4887d6bfde87SChris Mason 
4888b53d3f5dSLiu Bo 	if (flush_delayed)
48892ff7e61eSJeff Mahoney 		btrfs_balance_delayed_items(fs_info);
489016cdcec7SMiao Xie 
4891d814a491SEthan Lien 	ret = __percpu_counter_compare(&fs_info->dirty_metadata_bytes,
4892d814a491SEthan Lien 				     BTRFS_DIRTY_METADATA_THRESH,
4893d814a491SEthan Lien 				     fs_info->dirty_metadata_batch);
4894e2d84521SMiao Xie 	if (ret > 0) {
48950b246afaSJeff Mahoney 		balance_dirty_pages_ratelimited(fs_info->btree_inode->i_mapping);
489616cdcec7SMiao Xie 	}
489716cdcec7SMiao Xie }
489816cdcec7SMiao Xie 
48992ff7e61eSJeff Mahoney void btrfs_btree_balance_dirty(struct btrfs_fs_info *fs_info)
490016cdcec7SMiao Xie {
49012ff7e61eSJeff Mahoney 	__btrfs_btree_balance_dirty(fs_info, 1);
490235b7e476SChris Mason }
4903b53d3f5dSLiu Bo 
49042ff7e61eSJeff Mahoney void btrfs_btree_balance_dirty_nodelay(struct btrfs_fs_info *fs_info)
4905b53d3f5dSLiu Bo {
49062ff7e61eSJeff Mahoney 	__btrfs_btree_balance_dirty(fs_info, 0);
4907d6bfde87SChris Mason }
49086b80053dSChris Mason 
49092ff7e61eSJeff Mahoney static void btrfs_error_commit_super(struct btrfs_fs_info *fs_info)
4910acce952bSliubo {
4911fe816d0fSNikolay Borisov 	/* cleanup FS via transaction */
4912fe816d0fSNikolay Borisov 	btrfs_cleanup_transaction(fs_info);
4913fe816d0fSNikolay Borisov 
49140b246afaSJeff Mahoney 	mutex_lock(&fs_info->cleaner_mutex);
49152ff7e61eSJeff Mahoney 	btrfs_run_delayed_iputs(fs_info);
49160b246afaSJeff Mahoney 	mutex_unlock(&fs_info->cleaner_mutex);
4917acce952bSliubo 
49180b246afaSJeff Mahoney 	down_write(&fs_info->cleanup_work_sem);
49190b246afaSJeff Mahoney 	up_write(&fs_info->cleanup_work_sem);
4920acce952bSliubo }
4921acce952bSliubo 
4922ef67963dSJosef Bacik static void btrfs_drop_all_logs(struct btrfs_fs_info *fs_info)
4923ef67963dSJosef Bacik {
4924fc7cbcd4SDavid Sterba 	struct btrfs_root *gang[8];
4925fc7cbcd4SDavid Sterba 	u64 root_objectid = 0;
4926fc7cbcd4SDavid Sterba 	int ret;
4927ef67963dSJosef Bacik 
4928fc7cbcd4SDavid Sterba 	spin_lock(&fs_info->fs_roots_radix_lock);
4929fc7cbcd4SDavid Sterba 	while ((ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
4930fc7cbcd4SDavid Sterba 					     (void **)gang, root_objectid,
4931fc7cbcd4SDavid Sterba 					     ARRAY_SIZE(gang))) != 0) {
4932fc7cbcd4SDavid Sterba 		int i;
4933ef67963dSJosef Bacik 
4934fc7cbcd4SDavid Sterba 		for (i = 0; i < ret; i++)
4935fc7cbcd4SDavid Sterba 			gang[i] = btrfs_grab_root(gang[i]);
4936fc7cbcd4SDavid Sterba 		spin_unlock(&fs_info->fs_roots_radix_lock);
4937fc7cbcd4SDavid Sterba 
4938fc7cbcd4SDavid Sterba 		for (i = 0; i < ret; i++) {
4939fc7cbcd4SDavid Sterba 			if (!gang[i])
4940ef67963dSJosef Bacik 				continue;
4941fc7cbcd4SDavid Sterba 			root_objectid = gang[i]->root_key.objectid;
4942fc7cbcd4SDavid Sterba 			btrfs_free_log(NULL, gang[i]);
4943fc7cbcd4SDavid Sterba 			btrfs_put_root(gang[i]);
4944ef67963dSJosef Bacik 		}
4945fc7cbcd4SDavid Sterba 		root_objectid++;
4946fc7cbcd4SDavid Sterba 		spin_lock(&fs_info->fs_roots_radix_lock);
4947ef67963dSJosef Bacik 	}
4948fc7cbcd4SDavid Sterba 	spin_unlock(&fs_info->fs_roots_radix_lock);
4949ef67963dSJosef Bacik 	btrfs_free_log_root_tree(NULL, fs_info);
4950ef67963dSJosef Bacik }
4951ef67963dSJosef Bacik 
4952143bede5SJeff Mahoney static void btrfs_destroy_ordered_extents(struct btrfs_root *root)
4953acce952bSliubo {
4954acce952bSliubo 	struct btrfs_ordered_extent *ordered;
4955acce952bSliubo 
4956199c2a9cSMiao Xie 	spin_lock(&root->ordered_extent_lock);
4957779880efSJosef Bacik 	/*
4958779880efSJosef Bacik 	 * This will just short circuit the ordered completion stuff which will
4959779880efSJosef Bacik 	 * make sure the ordered extent gets properly cleaned up.
4960779880efSJosef Bacik 	 */
4961199c2a9cSMiao Xie 	list_for_each_entry(ordered, &root->ordered_extents,
4962779880efSJosef Bacik 			    root_extent_list)
4963779880efSJosef Bacik 		set_bit(BTRFS_ORDERED_IOERR, &ordered->flags);
4964199c2a9cSMiao Xie 	spin_unlock(&root->ordered_extent_lock);
4965199c2a9cSMiao Xie }
4966199c2a9cSMiao Xie 
4967199c2a9cSMiao Xie static void btrfs_destroy_all_ordered_extents(struct btrfs_fs_info *fs_info)
4968199c2a9cSMiao Xie {
4969199c2a9cSMiao Xie 	struct btrfs_root *root;
4970199c2a9cSMiao Xie 	struct list_head splice;
4971199c2a9cSMiao Xie 
4972199c2a9cSMiao Xie 	INIT_LIST_HEAD(&splice);
4973199c2a9cSMiao Xie 
4974199c2a9cSMiao Xie 	spin_lock(&fs_info->ordered_root_lock);
4975199c2a9cSMiao Xie 	list_splice_init(&fs_info->ordered_roots, &splice);
4976199c2a9cSMiao Xie 	while (!list_empty(&splice)) {
4977199c2a9cSMiao Xie 		root = list_first_entry(&splice, struct btrfs_root,
4978199c2a9cSMiao Xie 					ordered_root);
49791de2cfdeSJosef Bacik 		list_move_tail(&root->ordered_root,
49801de2cfdeSJosef Bacik 			       &fs_info->ordered_roots);
4981199c2a9cSMiao Xie 
49822a85d9caSLiu Bo 		spin_unlock(&fs_info->ordered_root_lock);
4983199c2a9cSMiao Xie 		btrfs_destroy_ordered_extents(root);
4984199c2a9cSMiao Xie 
49852a85d9caSLiu Bo 		cond_resched();
49862a85d9caSLiu Bo 		spin_lock(&fs_info->ordered_root_lock);
4987199c2a9cSMiao Xie 	}
4988199c2a9cSMiao Xie 	spin_unlock(&fs_info->ordered_root_lock);
498974d5d229SJosef Bacik 
499074d5d229SJosef Bacik 	/*
499174d5d229SJosef Bacik 	 * We need this here because if we've been flipped read-only we won't
499274d5d229SJosef Bacik 	 * get sync() from the umount, so we need to make sure any ordered
499374d5d229SJosef Bacik 	 * extents that haven't had their dirty pages IO start writeout yet
499474d5d229SJosef Bacik 	 * actually get run and error out properly.
499574d5d229SJosef Bacik 	 */
499674d5d229SJosef Bacik 	btrfs_wait_ordered_roots(fs_info, U64_MAX, 0, (u64)-1);
4997acce952bSliubo }
4998acce952bSliubo 
499935a3621bSStefan Behrens static int btrfs_destroy_delayed_refs(struct btrfs_transaction *trans,
50002ff7e61eSJeff Mahoney 				      struct btrfs_fs_info *fs_info)
5001acce952bSliubo {
5002acce952bSliubo 	struct rb_node *node;
5003acce952bSliubo 	struct btrfs_delayed_ref_root *delayed_refs;
5004acce952bSliubo 	struct btrfs_delayed_ref_node *ref;
5005acce952bSliubo 	int ret = 0;
5006acce952bSliubo 
5007acce952bSliubo 	delayed_refs = &trans->delayed_refs;
5008acce952bSliubo 
5009acce952bSliubo 	spin_lock(&delayed_refs->lock);
5010d7df2c79SJosef Bacik 	if (atomic_read(&delayed_refs->num_entries) == 0) {
5011cfece4dbSDavid Sterba 		spin_unlock(&delayed_refs->lock);
5012b79ce3ddSDavid Sterba 		btrfs_debug(fs_info, "delayed_refs has NO entry");
5013acce952bSliubo 		return ret;
5014acce952bSliubo 	}
5015acce952bSliubo 
50165c9d028bSLiu Bo 	while ((node = rb_first_cached(&delayed_refs->href_root)) != NULL) {
5017d7df2c79SJosef Bacik 		struct btrfs_delayed_ref_head *head;
50180e0adbcfSJosef Bacik 		struct rb_node *n;
5019e78417d1SJosef Bacik 		bool pin_bytes = false;
5020acce952bSliubo 
5021d7df2c79SJosef Bacik 		head = rb_entry(node, struct btrfs_delayed_ref_head,
5022d7df2c79SJosef Bacik 				href_node);
50233069bd26SJosef Bacik 		if (btrfs_delayed_ref_lock(delayed_refs, head))
5024b939d1abSJosef Bacik 			continue;
50253069bd26SJosef Bacik 
5026d7df2c79SJosef Bacik 		spin_lock(&head->lock);
5027e3d03965SLiu Bo 		while ((n = rb_first_cached(&head->ref_tree)) != NULL) {
50280e0adbcfSJosef Bacik 			ref = rb_entry(n, struct btrfs_delayed_ref_node,
50290e0adbcfSJosef Bacik 				       ref_node);
5030d7df2c79SJosef Bacik 			ref->in_tree = 0;
5031e3d03965SLiu Bo 			rb_erase_cached(&ref->ref_node, &head->ref_tree);
50320e0adbcfSJosef Bacik 			RB_CLEAR_NODE(&ref->ref_node);
50331d57ee94SWang Xiaoguang 			if (!list_empty(&ref->add_list))
50341d57ee94SWang Xiaoguang 				list_del(&ref->add_list);
5035d7df2c79SJosef Bacik 			atomic_dec(&delayed_refs->num_entries);
5036d7df2c79SJosef Bacik 			btrfs_put_delayed_ref(ref);
5037d7df2c79SJosef Bacik 		}
503854067ae9SJosef Bacik 		if (head->must_insert_reserved)
5039e78417d1SJosef Bacik 			pin_bytes = true;
504078a6184aSMiao Xie 		btrfs_free_delayed_extent_op(head->extent_op);
5041fa781ceaSJosef Bacik 		btrfs_delete_ref_head(delayed_refs, head);
5042d7df2c79SJosef Bacik 		spin_unlock(&head->lock);
5043acce952bSliubo 		spin_unlock(&delayed_refs->lock);
5044e78417d1SJosef Bacik 		mutex_unlock(&head->mutex);
5045acce952bSliubo 
5046f603bb94SNikolay Borisov 		if (pin_bytes) {
5047f603bb94SNikolay Borisov 			struct btrfs_block_group *cache;
5048f603bb94SNikolay Borisov 
5049f603bb94SNikolay Borisov 			cache = btrfs_lookup_block_group(fs_info, head->bytenr);
5050f603bb94SNikolay Borisov 			BUG_ON(!cache);
5051f603bb94SNikolay Borisov 
5052f603bb94SNikolay Borisov 			spin_lock(&cache->space_info->lock);
5053f603bb94SNikolay Borisov 			spin_lock(&cache->lock);
5054f603bb94SNikolay Borisov 			cache->pinned += head->num_bytes;
5055f603bb94SNikolay Borisov 			btrfs_space_info_update_bytes_pinned(fs_info,
5056f603bb94SNikolay Borisov 				cache->space_info, head->num_bytes);
5057f603bb94SNikolay Borisov 			cache->reserved -= head->num_bytes;
5058f603bb94SNikolay Borisov 			cache->space_info->bytes_reserved -= head->num_bytes;
5059f603bb94SNikolay Borisov 			spin_unlock(&cache->lock);
5060f603bb94SNikolay Borisov 			spin_unlock(&cache->space_info->lock);
5061f603bb94SNikolay Borisov 
5062f603bb94SNikolay Borisov 			btrfs_put_block_group(cache);
5063f603bb94SNikolay Borisov 
5064f603bb94SNikolay Borisov 			btrfs_error_unpin_extent_range(fs_info, head->bytenr,
5065f603bb94SNikolay Borisov 				head->bytenr + head->num_bytes - 1);
5066f603bb94SNikolay Borisov 		}
506731890da0SJosef Bacik 		btrfs_cleanup_ref_head_accounting(fs_info, delayed_refs, head);
5068d278850eSJosef Bacik 		btrfs_put_delayed_ref_head(head);
5069acce952bSliubo 		cond_resched();
5070acce952bSliubo 		spin_lock(&delayed_refs->lock);
5071acce952bSliubo 	}
507281f7eb00SJeff Mahoney 	btrfs_qgroup_destroy_extent_records(trans);
5073acce952bSliubo 
5074acce952bSliubo 	spin_unlock(&delayed_refs->lock);
5075acce952bSliubo 
5076acce952bSliubo 	return ret;
5077acce952bSliubo }
5078acce952bSliubo 
5079143bede5SJeff Mahoney static void btrfs_destroy_delalloc_inodes(struct btrfs_root *root)
5080acce952bSliubo {
5081acce952bSliubo 	struct btrfs_inode *btrfs_inode;
5082acce952bSliubo 	struct list_head splice;
5083acce952bSliubo 
5084acce952bSliubo 	INIT_LIST_HEAD(&splice);
5085acce952bSliubo 
5086eb73c1b7SMiao Xie 	spin_lock(&root->delalloc_lock);
5087eb73c1b7SMiao Xie 	list_splice_init(&root->delalloc_inodes, &splice);
5088acce952bSliubo 
5089acce952bSliubo 	while (!list_empty(&splice)) {
5090fe816d0fSNikolay Borisov 		struct inode *inode = NULL;
5091eb73c1b7SMiao Xie 		btrfs_inode = list_first_entry(&splice, struct btrfs_inode,
5092acce952bSliubo 					       delalloc_inodes);
5093fe816d0fSNikolay Borisov 		__btrfs_del_delalloc_inode(root, btrfs_inode);
5094eb73c1b7SMiao Xie 		spin_unlock(&root->delalloc_lock);
5095acce952bSliubo 
5096fe816d0fSNikolay Borisov 		/*
5097fe816d0fSNikolay Borisov 		 * Make sure we get a live inode and that it'll not disappear
5098fe816d0fSNikolay Borisov 		 * meanwhile.
5099fe816d0fSNikolay Borisov 		 */
5100fe816d0fSNikolay Borisov 		inode = igrab(&btrfs_inode->vfs_inode);
5101fe816d0fSNikolay Borisov 		if (inode) {
5102fe816d0fSNikolay Borisov 			invalidate_inode_pages2(inode->i_mapping);
5103fe816d0fSNikolay Borisov 			iput(inode);
5104fe816d0fSNikolay Borisov 		}
5105eb73c1b7SMiao Xie 		spin_lock(&root->delalloc_lock);
5106acce952bSliubo 	}
5107eb73c1b7SMiao Xie 	spin_unlock(&root->delalloc_lock);
5108eb73c1b7SMiao Xie }
5109eb73c1b7SMiao Xie 
5110eb73c1b7SMiao Xie static void btrfs_destroy_all_delalloc_inodes(struct btrfs_fs_info *fs_info)
5111eb73c1b7SMiao Xie {
5112eb73c1b7SMiao Xie 	struct btrfs_root *root;
5113eb73c1b7SMiao Xie 	struct list_head splice;
5114eb73c1b7SMiao Xie 
5115eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&splice);
5116eb73c1b7SMiao Xie 
5117eb73c1b7SMiao Xie 	spin_lock(&fs_info->delalloc_root_lock);
5118eb73c1b7SMiao Xie 	list_splice_init(&fs_info->delalloc_roots, &splice);
5119eb73c1b7SMiao Xie 	while (!list_empty(&splice)) {
5120eb73c1b7SMiao Xie 		root = list_first_entry(&splice, struct btrfs_root,
5121eb73c1b7SMiao Xie 					 delalloc_root);
512200246528SJosef Bacik 		root = btrfs_grab_root(root);
5123eb73c1b7SMiao Xie 		BUG_ON(!root);
5124eb73c1b7SMiao Xie 		spin_unlock(&fs_info->delalloc_root_lock);
5125eb73c1b7SMiao Xie 
5126eb73c1b7SMiao Xie 		btrfs_destroy_delalloc_inodes(root);
512700246528SJosef Bacik 		btrfs_put_root(root);
5128eb73c1b7SMiao Xie 
5129eb73c1b7SMiao Xie 		spin_lock(&fs_info->delalloc_root_lock);
5130eb73c1b7SMiao Xie 	}
5131eb73c1b7SMiao Xie 	spin_unlock(&fs_info->delalloc_root_lock);
5132acce952bSliubo }
5133acce952bSliubo 
51342ff7e61eSJeff Mahoney static int btrfs_destroy_marked_extents(struct btrfs_fs_info *fs_info,
5135acce952bSliubo 					struct extent_io_tree *dirty_pages,
5136acce952bSliubo 					int mark)
5137acce952bSliubo {
5138acce952bSliubo 	int ret;
5139acce952bSliubo 	struct extent_buffer *eb;
5140acce952bSliubo 	u64 start = 0;
5141acce952bSliubo 	u64 end;
5142acce952bSliubo 
5143acce952bSliubo 	while (1) {
5144acce952bSliubo 		ret = find_first_extent_bit(dirty_pages, start, &start, &end,
5145e6138876SJosef Bacik 					    mark, NULL);
5146acce952bSliubo 		if (ret)
5147acce952bSliubo 			break;
5148acce952bSliubo 
514991166212SDavid Sterba 		clear_extent_bits(dirty_pages, start, end, mark);
5150acce952bSliubo 		while (start <= end) {
51510b246afaSJeff Mahoney 			eb = find_extent_buffer(fs_info, start);
51520b246afaSJeff Mahoney 			start += fs_info->nodesize;
5153fd8b2b61SJosef Bacik 			if (!eb)
5154acce952bSliubo 				continue;
5155fd8b2b61SJosef Bacik 			wait_on_extent_buffer_writeback(eb);
5156acce952bSliubo 
5157fd8b2b61SJosef Bacik 			if (test_and_clear_bit(EXTENT_BUFFER_DIRTY,
5158fd8b2b61SJosef Bacik 					       &eb->bflags))
5159fd8b2b61SJosef Bacik 				clear_extent_buffer_dirty(eb);
5160fd8b2b61SJosef Bacik 			free_extent_buffer_stale(eb);
5161acce952bSliubo 		}
5162acce952bSliubo 	}
5163acce952bSliubo 
5164acce952bSliubo 	return ret;
5165acce952bSliubo }
5166acce952bSliubo 
51672ff7e61eSJeff Mahoney static int btrfs_destroy_pinned_extent(struct btrfs_fs_info *fs_info,
5168fe119a6eSNikolay Borisov 				       struct extent_io_tree *unpin)
5169acce952bSliubo {
5170acce952bSliubo 	u64 start;
5171acce952bSliubo 	u64 end;
5172acce952bSliubo 	int ret;
5173acce952bSliubo 
5174acce952bSliubo 	while (1) {
51750e6ec385SFilipe Manana 		struct extent_state *cached_state = NULL;
51760e6ec385SFilipe Manana 
5177fcd5e742SLu Fengqi 		/*
5178fcd5e742SLu Fengqi 		 * The btrfs_finish_extent_commit() may get the same range as
5179fcd5e742SLu Fengqi 		 * ours between find_first_extent_bit and clear_extent_dirty.
5180fcd5e742SLu Fengqi 		 * Hence, hold the unused_bg_unpin_mutex to avoid double unpin
5181fcd5e742SLu Fengqi 		 * the same extent range.
5182fcd5e742SLu Fengqi 		 */
5183fcd5e742SLu Fengqi 		mutex_lock(&fs_info->unused_bg_unpin_mutex);
5184acce952bSliubo 		ret = find_first_extent_bit(unpin, 0, &start, &end,
51850e6ec385SFilipe Manana 					    EXTENT_DIRTY, &cached_state);
5186fcd5e742SLu Fengqi 		if (ret) {
5187fcd5e742SLu Fengqi 			mutex_unlock(&fs_info->unused_bg_unpin_mutex);
5188acce952bSliubo 			break;
5189fcd5e742SLu Fengqi 		}
5190acce952bSliubo 
51910e6ec385SFilipe Manana 		clear_extent_dirty(unpin, start, end, &cached_state);
51920e6ec385SFilipe Manana 		free_extent_state(cached_state);
51932ff7e61eSJeff Mahoney 		btrfs_error_unpin_extent_range(fs_info, start, end);
5194fcd5e742SLu Fengqi 		mutex_unlock(&fs_info->unused_bg_unpin_mutex);
5195acce952bSliubo 		cond_resched();
5196acce952bSliubo 	}
5197acce952bSliubo 
5198acce952bSliubo 	return 0;
5199acce952bSliubo }
5200acce952bSliubo 
520132da5386SDavid Sterba static void btrfs_cleanup_bg_io(struct btrfs_block_group *cache)
5202c79a1751SLiu Bo {
5203c79a1751SLiu Bo 	struct inode *inode;
5204c79a1751SLiu Bo 
5205c79a1751SLiu Bo 	inode = cache->io_ctl.inode;
5206c79a1751SLiu Bo 	if (inode) {
5207c79a1751SLiu Bo 		invalidate_inode_pages2(inode->i_mapping);
5208c79a1751SLiu Bo 		BTRFS_I(inode)->generation = 0;
5209c79a1751SLiu Bo 		cache->io_ctl.inode = NULL;
5210c79a1751SLiu Bo 		iput(inode);
5211c79a1751SLiu Bo 	}
5212bbc37d6eSFilipe Manana 	ASSERT(cache->io_ctl.pages == NULL);
5213c79a1751SLiu Bo 	btrfs_put_block_group(cache);
5214c79a1751SLiu Bo }
5215c79a1751SLiu Bo 
5216c79a1751SLiu Bo void btrfs_cleanup_dirty_bgs(struct btrfs_transaction *cur_trans,
52172ff7e61eSJeff Mahoney 			     struct btrfs_fs_info *fs_info)
5218c79a1751SLiu Bo {
521932da5386SDavid Sterba 	struct btrfs_block_group *cache;
5220c79a1751SLiu Bo 
5221c79a1751SLiu Bo 	spin_lock(&cur_trans->dirty_bgs_lock);
5222c79a1751SLiu Bo 	while (!list_empty(&cur_trans->dirty_bgs)) {
5223c79a1751SLiu Bo 		cache = list_first_entry(&cur_trans->dirty_bgs,
522432da5386SDavid Sterba 					 struct btrfs_block_group,
5225c79a1751SLiu Bo 					 dirty_list);
5226c79a1751SLiu Bo 
5227c79a1751SLiu Bo 		if (!list_empty(&cache->io_list)) {
5228c79a1751SLiu Bo 			spin_unlock(&cur_trans->dirty_bgs_lock);
5229c79a1751SLiu Bo 			list_del_init(&cache->io_list);
5230c79a1751SLiu Bo 			btrfs_cleanup_bg_io(cache);
5231c79a1751SLiu Bo 			spin_lock(&cur_trans->dirty_bgs_lock);
5232c79a1751SLiu Bo 		}
5233c79a1751SLiu Bo 
5234c79a1751SLiu Bo 		list_del_init(&cache->dirty_list);
5235c79a1751SLiu Bo 		spin_lock(&cache->lock);
5236c79a1751SLiu Bo 		cache->disk_cache_state = BTRFS_DC_ERROR;
5237c79a1751SLiu Bo 		spin_unlock(&cache->lock);
5238c79a1751SLiu Bo 
5239c79a1751SLiu Bo 		spin_unlock(&cur_trans->dirty_bgs_lock);
5240c79a1751SLiu Bo 		btrfs_put_block_group(cache);
5241ba2c4d4eSJosef Bacik 		btrfs_delayed_refs_rsv_release(fs_info, 1);
5242c79a1751SLiu Bo 		spin_lock(&cur_trans->dirty_bgs_lock);
5243c79a1751SLiu Bo 	}
5244c79a1751SLiu Bo 	spin_unlock(&cur_trans->dirty_bgs_lock);
5245c79a1751SLiu Bo 
524645ae2c18SNikolay Borisov 	/*
524745ae2c18SNikolay Borisov 	 * Refer to the definition of io_bgs member for details why it's safe
524845ae2c18SNikolay Borisov 	 * to use it without any locking
524945ae2c18SNikolay Borisov 	 */
5250c79a1751SLiu Bo 	while (!list_empty(&cur_trans->io_bgs)) {
5251c79a1751SLiu Bo 		cache = list_first_entry(&cur_trans->io_bgs,
525232da5386SDavid Sterba 					 struct btrfs_block_group,
5253c79a1751SLiu Bo 					 io_list);
5254c79a1751SLiu Bo 
5255c79a1751SLiu Bo 		list_del_init(&cache->io_list);
5256c79a1751SLiu Bo 		spin_lock(&cache->lock);
5257c79a1751SLiu Bo 		cache->disk_cache_state = BTRFS_DC_ERROR;
5258c79a1751SLiu Bo 		spin_unlock(&cache->lock);
5259c79a1751SLiu Bo 		btrfs_cleanup_bg_io(cache);
5260c79a1751SLiu Bo 	}
5261c79a1751SLiu Bo }
5262c79a1751SLiu Bo 
526349b25e05SJeff Mahoney void btrfs_cleanup_one_transaction(struct btrfs_transaction *cur_trans,
52642ff7e61eSJeff Mahoney 				   struct btrfs_fs_info *fs_info)
526549b25e05SJeff Mahoney {
5266bbbf7243SNikolay Borisov 	struct btrfs_device *dev, *tmp;
5267bbbf7243SNikolay Borisov 
52682ff7e61eSJeff Mahoney 	btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
5269c79a1751SLiu Bo 	ASSERT(list_empty(&cur_trans->dirty_bgs));
5270c79a1751SLiu Bo 	ASSERT(list_empty(&cur_trans->io_bgs));
5271c79a1751SLiu Bo 
5272bbbf7243SNikolay Borisov 	list_for_each_entry_safe(dev, tmp, &cur_trans->dev_update_list,
5273bbbf7243SNikolay Borisov 				 post_commit_list) {
5274bbbf7243SNikolay Borisov 		list_del_init(&dev->post_commit_list);
5275bbbf7243SNikolay Borisov 	}
5276bbbf7243SNikolay Borisov 
52772ff7e61eSJeff Mahoney 	btrfs_destroy_delayed_refs(cur_trans, fs_info);
527849b25e05SJeff Mahoney 
52794a9d8bdeSMiao Xie 	cur_trans->state = TRANS_STATE_COMMIT_START;
52800b246afaSJeff Mahoney 	wake_up(&fs_info->transaction_blocked_wait);
528149b25e05SJeff Mahoney 
52824a9d8bdeSMiao Xie 	cur_trans->state = TRANS_STATE_UNBLOCKED;
52830b246afaSJeff Mahoney 	wake_up(&fs_info->transaction_wait);
528449b25e05SJeff Mahoney 
5285ccdf9b30SJeff Mahoney 	btrfs_destroy_delayed_inodes(fs_info);
528667cde344SMiao Xie 
52872ff7e61eSJeff Mahoney 	btrfs_destroy_marked_extents(fs_info, &cur_trans->dirty_pages,
528849b25e05SJeff Mahoney 				     EXTENT_DIRTY);
5289fe119a6eSNikolay Borisov 	btrfs_destroy_pinned_extent(fs_info, &cur_trans->pinned_extents);
529049b25e05SJeff Mahoney 
5291d3575156SNaohiro Aota 	btrfs_free_redirty_list(cur_trans);
5292d3575156SNaohiro Aota 
52934a9d8bdeSMiao Xie 	cur_trans->state =TRANS_STATE_COMPLETED;
52944a9d8bdeSMiao Xie 	wake_up(&cur_trans->commit_wait);
529549b25e05SJeff Mahoney }
529649b25e05SJeff Mahoney 
52972ff7e61eSJeff Mahoney static int btrfs_cleanup_transaction(struct btrfs_fs_info *fs_info)
5298acce952bSliubo {
5299acce952bSliubo 	struct btrfs_transaction *t;
5300acce952bSliubo 
53010b246afaSJeff Mahoney 	mutex_lock(&fs_info->transaction_kthread_mutex);
5302acce952bSliubo 
53030b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
53040b246afaSJeff Mahoney 	while (!list_empty(&fs_info->trans_list)) {
53050b246afaSJeff Mahoney 		t = list_first_entry(&fs_info->trans_list,
5306724e2315SJosef Bacik 				     struct btrfs_transaction, list);
5307724e2315SJosef Bacik 		if (t->state >= TRANS_STATE_COMMIT_START) {
53089b64f57dSElena Reshetova 			refcount_inc(&t->use_count);
53090b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
53102ff7e61eSJeff Mahoney 			btrfs_wait_for_commit(fs_info, t->transid);
5311724e2315SJosef Bacik 			btrfs_put_transaction(t);
53120b246afaSJeff Mahoney 			spin_lock(&fs_info->trans_lock);
5313724e2315SJosef Bacik 			continue;
5314724e2315SJosef Bacik 		}
53150b246afaSJeff Mahoney 		if (t == fs_info->running_transaction) {
5316724e2315SJosef Bacik 			t->state = TRANS_STATE_COMMIT_DOING;
53170b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
5318724e2315SJosef Bacik 			/*
5319724e2315SJosef Bacik 			 * We wait for 0 num_writers since we don't hold a trans
5320724e2315SJosef Bacik 			 * handle open currently for this transaction.
5321724e2315SJosef Bacik 			 */
5322724e2315SJosef Bacik 			wait_event(t->writer_wait,
5323724e2315SJosef Bacik 				   atomic_read(&t->num_writers) == 0);
5324724e2315SJosef Bacik 		} else {
53250b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
5326724e2315SJosef Bacik 		}
53272ff7e61eSJeff Mahoney 		btrfs_cleanup_one_transaction(t, fs_info);
5328724e2315SJosef Bacik 
53290b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
53300b246afaSJeff Mahoney 		if (t == fs_info->running_transaction)
53310b246afaSJeff Mahoney 			fs_info->running_transaction = NULL;
5332724e2315SJosef Bacik 		list_del_init(&t->list);
53330b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
5334a4abeea4SJosef Bacik 
5335724e2315SJosef Bacik 		btrfs_put_transaction(t);
53362e4e97abSJosef Bacik 		trace_btrfs_transaction_commit(fs_info);
53370b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
5338724e2315SJosef Bacik 	}
53390b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
53400b246afaSJeff Mahoney 	btrfs_destroy_all_ordered_extents(fs_info);
5341ccdf9b30SJeff Mahoney 	btrfs_destroy_delayed_inodes(fs_info);
5342ccdf9b30SJeff Mahoney 	btrfs_assert_delayed_root_empty(fs_info);
53430b246afaSJeff Mahoney 	btrfs_destroy_all_delalloc_inodes(fs_info);
5344ef67963dSJosef Bacik 	btrfs_drop_all_logs(fs_info);
53450b246afaSJeff Mahoney 	mutex_unlock(&fs_info->transaction_kthread_mutex);
5346acce952bSliubo 
5347acce952bSliubo 	return 0;
5348acce952bSliubo }
5349ec7d6dfdSNikolay Borisov 
5350453e4873SNikolay Borisov int btrfs_init_root_free_objectid(struct btrfs_root *root)
5351ec7d6dfdSNikolay Borisov {
5352ec7d6dfdSNikolay Borisov 	struct btrfs_path *path;
5353ec7d6dfdSNikolay Borisov 	int ret;
5354ec7d6dfdSNikolay Borisov 	struct extent_buffer *l;
5355ec7d6dfdSNikolay Borisov 	struct btrfs_key search_key;
5356ec7d6dfdSNikolay Borisov 	struct btrfs_key found_key;
5357ec7d6dfdSNikolay Borisov 	int slot;
5358ec7d6dfdSNikolay Borisov 
5359ec7d6dfdSNikolay Borisov 	path = btrfs_alloc_path();
5360ec7d6dfdSNikolay Borisov 	if (!path)
5361ec7d6dfdSNikolay Borisov 		return -ENOMEM;
5362ec7d6dfdSNikolay Borisov 
5363ec7d6dfdSNikolay Borisov 	search_key.objectid = BTRFS_LAST_FREE_OBJECTID;
5364ec7d6dfdSNikolay Borisov 	search_key.type = -1;
5365ec7d6dfdSNikolay Borisov 	search_key.offset = (u64)-1;
5366ec7d6dfdSNikolay Borisov 	ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
5367ec7d6dfdSNikolay Borisov 	if (ret < 0)
5368ec7d6dfdSNikolay Borisov 		goto error;
5369ec7d6dfdSNikolay Borisov 	BUG_ON(ret == 0); /* Corruption */
5370ec7d6dfdSNikolay Borisov 	if (path->slots[0] > 0) {
5371ec7d6dfdSNikolay Borisov 		slot = path->slots[0] - 1;
5372ec7d6dfdSNikolay Borisov 		l = path->nodes[0];
5373ec7d6dfdSNikolay Borisov 		btrfs_item_key_to_cpu(l, &found_key, slot);
537423125104SNikolay Borisov 		root->free_objectid = max_t(u64, found_key.objectid + 1,
537523125104SNikolay Borisov 					    BTRFS_FIRST_FREE_OBJECTID);
5376ec7d6dfdSNikolay Borisov 	} else {
537723125104SNikolay Borisov 		root->free_objectid = BTRFS_FIRST_FREE_OBJECTID;
5378ec7d6dfdSNikolay Borisov 	}
5379ec7d6dfdSNikolay Borisov 	ret = 0;
5380ec7d6dfdSNikolay Borisov error:
5381ec7d6dfdSNikolay Borisov 	btrfs_free_path(path);
5382ec7d6dfdSNikolay Borisov 	return ret;
5383ec7d6dfdSNikolay Borisov }
5384ec7d6dfdSNikolay Borisov 
5385543068a2SNikolay Borisov int btrfs_get_free_objectid(struct btrfs_root *root, u64 *objectid)
5386ec7d6dfdSNikolay Borisov {
5387ec7d6dfdSNikolay Borisov 	int ret;
5388ec7d6dfdSNikolay Borisov 	mutex_lock(&root->objectid_mutex);
5389ec7d6dfdSNikolay Borisov 
53906b8fad57SNikolay Borisov 	if (unlikely(root->free_objectid >= BTRFS_LAST_FREE_OBJECTID)) {
5391ec7d6dfdSNikolay Borisov 		btrfs_warn(root->fs_info,
5392ec7d6dfdSNikolay Borisov 			   "the objectid of root %llu reaches its highest value",
5393ec7d6dfdSNikolay Borisov 			   root->root_key.objectid);
5394ec7d6dfdSNikolay Borisov 		ret = -ENOSPC;
5395ec7d6dfdSNikolay Borisov 		goto out;
5396ec7d6dfdSNikolay Borisov 	}
5397ec7d6dfdSNikolay Borisov 
539823125104SNikolay Borisov 	*objectid = root->free_objectid++;
5399ec7d6dfdSNikolay Borisov 	ret = 0;
5400ec7d6dfdSNikolay Borisov out:
5401ec7d6dfdSNikolay Borisov 	mutex_unlock(&root->objectid_mutex);
5402ec7d6dfdSNikolay Borisov 	return ret;
5403ec7d6dfdSNikolay Borisov }
5404