xref: /openbmc/linux/fs/btrfs/disk-io.c (revision aebcc159)
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 /*
822996e1f8SJohannes Thumshirn  * Compute the csum of a btree block and store the result to provided buffer.
83d352ac68SChris Mason  */
84c67b3892SDavid Sterba static void csum_tree_block(struct extent_buffer *buf, u8 *result)
8519c00ddcSChris Mason {
86d5178578SJohannes Thumshirn 	struct btrfs_fs_info *fs_info = buf->fs_info;
877280305eSDavid Sterba 	const int num_pages = num_extent_pages(buf);
88a26663e7SQu Wenruo 	const int first_page_part = min_t(u32, PAGE_SIZE, fs_info->nodesize);
89d5178578SJohannes Thumshirn 	SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
9019c00ddcSChris Mason 	char *kaddr;
91e9be5a30SDavid Sterba 	int i;
92d5178578SJohannes Thumshirn 
93d5178578SJohannes Thumshirn 	shash->tfm = fs_info->csum_shash;
94d5178578SJohannes Thumshirn 	crypto_shash_init(shash);
95a26663e7SQu Wenruo 	kaddr = page_address(buf->pages[0]) + offset_in_page(buf->start);
96e9be5a30SDavid Sterba 	crypto_shash_update(shash, kaddr + BTRFS_CSUM_SIZE,
97a26663e7SQu Wenruo 			    first_page_part - BTRFS_CSUM_SIZE);
9819c00ddcSChris Mason 
995ad9b471Spengfuyuan 	for (i = 1; i < num_pages && INLINE_EXTENT_BUFFER_PAGES > 1; i++) {
100e9be5a30SDavid Sterba 		kaddr = page_address(buf->pages[i]);
101e9be5a30SDavid Sterba 		crypto_shash_update(shash, kaddr, PAGE_SIZE);
10219c00ddcSChris Mason 	}
10371a63551SDavid Sterba 	memset(result, 0, BTRFS_CSUM_SIZE);
104d5178578SJohannes Thumshirn 	crypto_shash_final(shash, result);
10519c00ddcSChris Mason }
10619c00ddcSChris Mason 
107d352ac68SChris Mason /*
108d352ac68SChris Mason  * we can't consider a given block up to date unless the transid of the
109d352ac68SChris Mason  * block matches the transid in the parent node's pointer.  This is how we
110d352ac68SChris Mason  * detect blocks that either didn't get written at all or got written
111d352ac68SChris Mason  * in the wrong place.
112d352ac68SChris Mason  */
1131259ab75SChris Mason static int verify_parent_transid(struct extent_io_tree *io_tree,
114b9fab919SChris Mason 				 struct extent_buffer *eb, u64 parent_transid,
115b9fab919SChris Mason 				 int atomic)
1161259ab75SChris Mason {
1172ac55d41SJosef Bacik 	struct extent_state *cached_state = NULL;
1181259ab75SChris Mason 	int ret;
1191259ab75SChris Mason 
1201259ab75SChris Mason 	if (!parent_transid || btrfs_header_generation(eb) == parent_transid)
1211259ab75SChris Mason 		return 0;
1221259ab75SChris Mason 
123b9fab919SChris Mason 	if (atomic)
124b9fab919SChris Mason 		return -EAGAIN;
125b9fab919SChris Mason 
126570eb97bSJosef Bacik 	lock_extent(io_tree, eb->start, eb->start + eb->len - 1, &cached_state);
1270b32f4bbSJosef Bacik 	if (extent_buffer_uptodate(eb) &&
1281259ab75SChris Mason 	    btrfs_header_generation(eb) == parent_transid) {
1291259ab75SChris Mason 		ret = 0;
1301259ab75SChris Mason 		goto out;
1311259ab75SChris Mason 	}
13294647322SDavid Sterba 	btrfs_err_rl(eb->fs_info,
1338f0ed7d4SQu Wenruo "parent transid verify failed on logical %llu mirror %u wanted %llu found %llu",
1348f0ed7d4SQu Wenruo 			eb->start, eb->read_mirror,
13529549aecSWang Shilong 			parent_transid, btrfs_header_generation(eb));
1361259ab75SChris Mason 	ret = 1;
1370b32f4bbSJosef Bacik 	clear_extent_buffer_uptodate(eb);
13833958dc6SChris Mason out:
139570eb97bSJosef Bacik 	unlock_extent(io_tree, eb->start, eb->start + eb->len - 1,
140e43bbe5eSDavid Sterba 		      &cached_state);
1411259ab75SChris Mason 	return ret;
1421259ab75SChris Mason }
1431259ab75SChris Mason 
144e7e16f48SJohannes Thumshirn static bool btrfs_supported_super_csum(u16 csum_type)
145e7e16f48SJohannes Thumshirn {
146e7e16f48SJohannes Thumshirn 	switch (csum_type) {
147e7e16f48SJohannes Thumshirn 	case BTRFS_CSUM_TYPE_CRC32:
1483951e7f0SJohannes Thumshirn 	case BTRFS_CSUM_TYPE_XXHASH:
1493831bf00SJohannes Thumshirn 	case BTRFS_CSUM_TYPE_SHA256:
150352ae07bSDavid Sterba 	case BTRFS_CSUM_TYPE_BLAKE2:
151e7e16f48SJohannes Thumshirn 		return true;
152e7e16f48SJohannes Thumshirn 	default:
153e7e16f48SJohannes Thumshirn 		return false;
154e7e16f48SJohannes Thumshirn 	}
155e7e16f48SJohannes Thumshirn }
156e7e16f48SJohannes Thumshirn 
157d352ac68SChris Mason /*
1581104a885SDavid Sterba  * Return 0 if the superblock checksum type matches the checksum value of that
1591104a885SDavid Sterba  * algorithm. Pass the raw disk superblock data.
1601104a885SDavid Sterba  */
1613d17adeaSQu Wenruo int btrfs_check_super_csum(struct btrfs_fs_info *fs_info,
1623d17adeaSQu Wenruo 			   const struct btrfs_super_block *disk_sb)
1631104a885SDavid Sterba {
16451bce6c9SJohannes Thumshirn 	char result[BTRFS_CSUM_SIZE];
165d5178578SJohannes Thumshirn 	SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
166d5178578SJohannes Thumshirn 
167d5178578SJohannes Thumshirn 	shash->tfm = fs_info->csum_shash;
1681104a885SDavid Sterba 
1691104a885SDavid Sterba 	/*
1701104a885SDavid Sterba 	 * The super_block structure does not span the whole
17151bce6c9SJohannes Thumshirn 	 * BTRFS_SUPER_INFO_SIZE range, we expect that the unused space is
17251bce6c9SJohannes Thumshirn 	 * filled with zeros and is included in the checksum.
1731104a885SDavid Sterba 	 */
1743d17adeaSQu Wenruo 	crypto_shash_digest(shash, (const u8 *)disk_sb + BTRFS_CSUM_SIZE,
175fd08001fSEric Biggers 			    BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE, result);
1761104a885SDavid Sterba 
17755fc29beSDavid Sterba 	if (memcmp(disk_sb->csum, result, fs_info->csum_size))
178e7e16f48SJohannes Thumshirn 		return 1;
1791104a885SDavid Sterba 
180e7e16f48SJohannes Thumshirn 	return 0;
1811104a885SDavid Sterba }
1821104a885SDavid Sterba 
183bacf60e5SChristoph Hellwig static int btrfs_repair_eb_io_failure(const struct extent_buffer *eb,
184bacf60e5SChristoph Hellwig 				      int mirror_num)
185bacf60e5SChristoph Hellwig {
186bacf60e5SChristoph Hellwig 	struct btrfs_fs_info *fs_info = eb->fs_info;
187bacf60e5SChristoph Hellwig 	int i, num_pages = num_extent_pages(eb);
188bacf60e5SChristoph Hellwig 	int ret = 0;
189bacf60e5SChristoph Hellwig 
190bacf60e5SChristoph Hellwig 	if (sb_rdonly(fs_info->sb))
191bacf60e5SChristoph Hellwig 		return -EROFS;
192bacf60e5SChristoph Hellwig 
193bacf60e5SChristoph Hellwig 	for (i = 0; i < num_pages; i++) {
194bacf60e5SChristoph Hellwig 		struct page *p = eb->pages[i];
195917ac778SQu Wenruo 		u64 start = max_t(u64, eb->start, page_offset(p));
196917ac778SQu Wenruo 		u64 end = min_t(u64, eb->start + eb->len, page_offset(p) + PAGE_SIZE);
197917ac778SQu Wenruo 		u32 len = end - start;
198bacf60e5SChristoph Hellwig 
199917ac778SQu Wenruo 		ret = btrfs_repair_io_failure(fs_info, 0, start, len,
200917ac778SQu Wenruo 				start, p, offset_in_page(start), mirror_num);
201bacf60e5SChristoph Hellwig 		if (ret)
202bacf60e5SChristoph Hellwig 			break;
203bacf60e5SChristoph Hellwig 	}
204bacf60e5SChristoph Hellwig 
205bacf60e5SChristoph Hellwig 	return ret;
206bacf60e5SChristoph Hellwig }
207bacf60e5SChristoph Hellwig 
2081104a885SDavid Sterba /*
209d352ac68SChris Mason  * helper to read a given tree block, doing retries as required when
210d352ac68SChris Mason  * the checksums don't match and we have alternate mirrors to try.
211581c1760SQu Wenruo  *
212789d6a3aSQu Wenruo  * @check:		expected tree parentness check, see the comments of the
213789d6a3aSQu Wenruo  *			structure for details.
214d352ac68SChris Mason  */
2156a2e9dc4SFilipe Manana int btrfs_read_extent_buffer(struct extent_buffer *eb,
216789d6a3aSQu Wenruo 			     struct btrfs_tree_parent_check *check)
217f188591eSChris Mason {
2185ab12d1fSDavid Sterba 	struct btrfs_fs_info *fs_info = eb->fs_info;
219ea466794SJosef Bacik 	int failed = 0;
220f188591eSChris Mason 	int ret;
221f188591eSChris Mason 	int num_copies = 0;
222f188591eSChris Mason 	int mirror_num = 0;
223ea466794SJosef Bacik 	int failed_mirror = 0;
224f188591eSChris Mason 
225789d6a3aSQu Wenruo 	ASSERT(check);
226789d6a3aSQu Wenruo 
227f188591eSChris Mason 	while (1) {
228f8397d69SNikolay Borisov 		clear_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags);
229947a6299SQu Wenruo 		ret = read_extent_buffer_pages(eb, WAIT_COMPLETE, mirror_num, check);
230947a6299SQu Wenruo 		if (!ret)
231581c1760SQu Wenruo 			break;
232d397712bSChris Mason 
2330b246afaSJeff Mahoney 		num_copies = btrfs_num_copies(fs_info,
234f188591eSChris Mason 					      eb->start, eb->len);
2354235298eSChris Mason 		if (num_copies == 1)
236ea466794SJosef Bacik 			break;
2374235298eSChris Mason 
2385cf1ab56SJosef Bacik 		if (!failed_mirror) {
2395cf1ab56SJosef Bacik 			failed = 1;
2405cf1ab56SJosef Bacik 			failed_mirror = eb->read_mirror;
2415cf1ab56SJosef Bacik 		}
2425cf1ab56SJosef Bacik 
243f188591eSChris Mason 		mirror_num++;
244ea466794SJosef Bacik 		if (mirror_num == failed_mirror)
245ea466794SJosef Bacik 			mirror_num++;
246ea466794SJosef Bacik 
2474235298eSChris Mason 		if (mirror_num > num_copies)
248ea466794SJosef Bacik 			break;
249f188591eSChris Mason 	}
250ea466794SJosef Bacik 
251c0901581SStefan Behrens 	if (failed && !ret && failed_mirror)
25220a1fbf9SDavid Sterba 		btrfs_repair_eb_io_failure(eb, failed_mirror);
253ea466794SJosef Bacik 
254ea466794SJosef Bacik 	return ret;
255f188591eSChris Mason }
25619c00ddcSChris Mason 
257eca0f6f6SQu Wenruo static int csum_one_extent_buffer(struct extent_buffer *eb)
258eca0f6f6SQu Wenruo {
259eca0f6f6SQu Wenruo 	struct btrfs_fs_info *fs_info = eb->fs_info;
260eca0f6f6SQu Wenruo 	u8 result[BTRFS_CSUM_SIZE];
261eca0f6f6SQu Wenruo 	int ret;
262eca0f6f6SQu Wenruo 
263eca0f6f6SQu Wenruo 	ASSERT(memcmp_extent_buffer(eb, fs_info->fs_devices->metadata_uuid,
264eca0f6f6SQu Wenruo 				    offsetof(struct btrfs_header, fsid),
265eca0f6f6SQu Wenruo 				    BTRFS_FSID_SIZE) == 0);
266eca0f6f6SQu Wenruo 	csum_tree_block(eb, result);
267eca0f6f6SQu Wenruo 
268eca0f6f6SQu Wenruo 	if (btrfs_header_level(eb))
269eca0f6f6SQu Wenruo 		ret = btrfs_check_node(eb);
270eca0f6f6SQu Wenruo 	else
27185d8a826SJosef Bacik 		ret = btrfs_check_leaf(eb);
272eca0f6f6SQu Wenruo 
2733777369fSQu Wenruo 	if (ret < 0)
2743777369fSQu Wenruo 		goto error;
2753777369fSQu Wenruo 
2763777369fSQu Wenruo 	/*
2773777369fSQu Wenruo 	 * Also check the generation, the eb reached here must be newer than
2783777369fSQu Wenruo 	 * last committed. Or something seriously wrong happened.
2793777369fSQu Wenruo 	 */
2803777369fSQu Wenruo 	if (unlikely(btrfs_header_generation(eb) <= fs_info->last_trans_committed)) {
2813777369fSQu Wenruo 		ret = -EUCLEAN;
282eca0f6f6SQu Wenruo 		btrfs_err(fs_info,
2833777369fSQu Wenruo 			"block=%llu bad generation, have %llu expect > %llu",
2843777369fSQu Wenruo 			  eb->start, btrfs_header_generation(eb),
2853777369fSQu Wenruo 			  fs_info->last_trans_committed);
2863777369fSQu Wenruo 		goto error;
287eca0f6f6SQu Wenruo 	}
288eca0f6f6SQu Wenruo 	write_extent_buffer(eb, result, 0, fs_info->csum_size);
289eca0f6f6SQu Wenruo 
290eca0f6f6SQu Wenruo 	return 0;
2913777369fSQu Wenruo 
2923777369fSQu Wenruo error:
2933777369fSQu Wenruo 	btrfs_print_tree(eb, 0);
2943777369fSQu Wenruo 	btrfs_err(fs_info, "block=%llu write time tree block corruption detected",
2953777369fSQu Wenruo 		  eb->start);
29616199ad9SFilipe Manana 	/*
29716199ad9SFilipe Manana 	 * Be noisy if this is an extent buffer from a log tree. We don't abort
29816199ad9SFilipe Manana 	 * a transaction in case there's a bad log tree extent buffer, we just
29916199ad9SFilipe Manana 	 * fallback to a transaction commit. Still we want to know when there is
30016199ad9SFilipe Manana 	 * a bad log tree extent buffer, as that may signal a bug somewhere.
30116199ad9SFilipe Manana 	 */
30216199ad9SFilipe Manana 	WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG) ||
30316199ad9SFilipe Manana 		btrfs_header_owner(eb) == BTRFS_TREE_LOG_OBJECTID);
3043777369fSQu Wenruo 	return ret;
305eca0f6f6SQu Wenruo }
306eca0f6f6SQu Wenruo 
307eca0f6f6SQu Wenruo /* Checksum all dirty extent buffers in one bio_vec */
308eca0f6f6SQu Wenruo static int csum_dirty_subpage_buffers(struct btrfs_fs_info *fs_info,
309eca0f6f6SQu Wenruo 				      struct bio_vec *bvec)
310eca0f6f6SQu Wenruo {
311eca0f6f6SQu Wenruo 	struct page *page = bvec->bv_page;
312eca0f6f6SQu Wenruo 	u64 bvec_start = page_offset(page) + bvec->bv_offset;
313eca0f6f6SQu Wenruo 	u64 cur;
314eca0f6f6SQu Wenruo 	int ret = 0;
315eca0f6f6SQu Wenruo 
316eca0f6f6SQu Wenruo 	for (cur = bvec_start; cur < bvec_start + bvec->bv_len;
317eca0f6f6SQu Wenruo 	     cur += fs_info->nodesize) {
318eca0f6f6SQu Wenruo 		struct extent_buffer *eb;
319eca0f6f6SQu Wenruo 		bool uptodate;
320eca0f6f6SQu Wenruo 
321eca0f6f6SQu Wenruo 		eb = find_extent_buffer(fs_info, cur);
322eca0f6f6SQu Wenruo 		uptodate = btrfs_subpage_test_uptodate(fs_info, page, cur,
323eca0f6f6SQu Wenruo 						       fs_info->nodesize);
324eca0f6f6SQu Wenruo 
32501cd3909SDavid Sterba 		/* A dirty eb shouldn't disappear from buffer_radix */
326eca0f6f6SQu Wenruo 		if (WARN_ON(!eb))
327eca0f6f6SQu Wenruo 			return -EUCLEAN;
328eca0f6f6SQu Wenruo 
329eca0f6f6SQu Wenruo 		if (WARN_ON(cur != btrfs_header_bytenr(eb))) {
330eca0f6f6SQu Wenruo 			free_extent_buffer(eb);
331eca0f6f6SQu Wenruo 			return -EUCLEAN;
332eca0f6f6SQu Wenruo 		}
333eca0f6f6SQu Wenruo 		if (WARN_ON(!uptodate)) {
334eca0f6f6SQu Wenruo 			free_extent_buffer(eb);
335eca0f6f6SQu Wenruo 			return -EUCLEAN;
336eca0f6f6SQu Wenruo 		}
337eca0f6f6SQu Wenruo 
338eca0f6f6SQu Wenruo 		ret = csum_one_extent_buffer(eb);
339eca0f6f6SQu Wenruo 		free_extent_buffer(eb);
340eca0f6f6SQu Wenruo 		if (ret < 0)
341eca0f6f6SQu Wenruo 			return ret;
342eca0f6f6SQu Wenruo 	}
343eca0f6f6SQu Wenruo 	return ret;
344eca0f6f6SQu Wenruo }
345eca0f6f6SQu Wenruo 
346d352ac68SChris Mason /*
347ac303b69SQu Wenruo  * Checksum a dirty tree block before IO.  This has extra checks to make sure
348ac303b69SQu Wenruo  * we only fill in the checksum field in the first page of a multi-page block.
349ac303b69SQu Wenruo  * For subpage extent buffers we need bvec to also read the offset in the page.
350d352ac68SChris Mason  */
351ac303b69SQu Wenruo static int csum_dirty_buffer(struct btrfs_fs_info *fs_info, struct bio_vec *bvec)
35219c00ddcSChris Mason {
353ac303b69SQu Wenruo 	struct page *page = bvec->bv_page;
3544eee4fa4SMiao Xie 	u64 start = page_offset(page);
35519c00ddcSChris Mason 	u64 found_start;
35619c00ddcSChris Mason 	struct extent_buffer *eb;
357eca0f6f6SQu Wenruo 
358fbca46ebSQu Wenruo 	if (fs_info->nodesize < PAGE_SIZE)
359eca0f6f6SQu Wenruo 		return csum_dirty_subpage_buffers(fs_info, bvec);
360f188591eSChris Mason 
3614f2de97aSJosef Bacik 	eb = (struct extent_buffer *)page->private;
3624f2de97aSJosef Bacik 	if (page != eb->pages[0])
3634f2de97aSJosef Bacik 		return 0;
3640f805531SAlex Lyakas 
36519c00ddcSChris Mason 	found_start = btrfs_header_bytenr(eb);
366d3575156SNaohiro Aota 
367d3575156SNaohiro Aota 	if (test_bit(EXTENT_BUFFER_NO_CHECK, &eb->bflags)) {
368d3575156SNaohiro Aota 		WARN_ON(found_start != 0);
369d3575156SNaohiro Aota 		return 0;
370d3575156SNaohiro Aota 	}
371d3575156SNaohiro Aota 
3720f805531SAlex Lyakas 	/*
3730f805531SAlex Lyakas 	 * Please do not consolidate these warnings into a single if.
3740f805531SAlex Lyakas 	 * It is useful to know what went wrong.
3750f805531SAlex Lyakas 	 */
3760f805531SAlex Lyakas 	if (WARN_ON(found_start != start))
3770f805531SAlex Lyakas 		return -EUCLEAN;
3780f805531SAlex Lyakas 	if (WARN_ON(!PageUptodate(page)))
3790f805531SAlex Lyakas 		return -EUCLEAN;
3800f805531SAlex Lyakas 
381eca0f6f6SQu Wenruo 	return csum_one_extent_buffer(eb);
38219c00ddcSChris Mason }
38319c00ddcSChris Mason 
384542e300eSChristoph Hellwig blk_status_t btree_csum_one_bio(struct btrfs_bio *bbio)
385deb6216fSChristoph Hellwig {
386542e300eSChristoph Hellwig 	struct btrfs_fs_info *fs_info = bbio->inode->root->fs_info;
387542e300eSChristoph Hellwig 	struct bvec_iter iter;
388542e300eSChristoph Hellwig 	struct bio_vec bv;
389deb6216fSChristoph Hellwig 	int ret = 0;
390deb6216fSChristoph Hellwig 
391542e300eSChristoph Hellwig 	bio_for_each_segment(bv, &bbio->bio, iter) {
392542e300eSChristoph Hellwig 		ret = csum_dirty_buffer(fs_info, &bv);
393deb6216fSChristoph Hellwig 		if (ret)
394deb6216fSChristoph Hellwig 			break;
395deb6216fSChristoph Hellwig 	}
396deb6216fSChristoph Hellwig 
397deb6216fSChristoph Hellwig 	return errno_to_blk_status(ret);
398deb6216fSChristoph Hellwig }
399deb6216fSChristoph Hellwig 
400b0c9b3b0SDavid Sterba static int check_tree_block_fsid(struct extent_buffer *eb)
4012b82032cSYan Zheng {
402b0c9b3b0SDavid Sterba 	struct btrfs_fs_info *fs_info = eb->fs_info;
403944d3f9fSNikolay Borisov 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices, *seed_devs;
40444880fdcSAnand Jain 	u8 fsid[BTRFS_FSID_SIZE];
405944d3f9fSNikolay Borisov 	u8 *metadata_uuid;
4062b82032cSYan Zheng 
4079a8658e3SDavid Sterba 	read_extent_buffer(eb, fsid, offsetof(struct btrfs_header, fsid),
4089a8658e3SDavid Sterba 			   BTRFS_FSID_SIZE);
4097239ff4bSNikolay Borisov 	/*
410944d3f9fSNikolay Borisov 	 * Checking the incompat flag is only valid for the current fs. For
411944d3f9fSNikolay Borisov 	 * seed devices it's forbidden to have their uuid changed so reading
412944d3f9fSNikolay Borisov 	 * ->fsid in this case is fine
4137239ff4bSNikolay Borisov 	 */
414944d3f9fSNikolay Borisov 	if (btrfs_fs_incompat(fs_info, METADATA_UUID))
4157239ff4bSNikolay Borisov 		metadata_uuid = fs_devices->metadata_uuid;
4167239ff4bSNikolay Borisov 	else
4177239ff4bSNikolay Borisov 		metadata_uuid = fs_devices->fsid;
4187239ff4bSNikolay Borisov 
419944d3f9fSNikolay Borisov 	if (!memcmp(fsid, metadata_uuid, BTRFS_FSID_SIZE))
420944d3f9fSNikolay Borisov 		return 0;
421944d3f9fSNikolay Borisov 
422944d3f9fSNikolay Borisov 	list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list)
423944d3f9fSNikolay Borisov 		if (!memcmp(fsid, seed_devs->fsid, BTRFS_FSID_SIZE))
424944d3f9fSNikolay Borisov 			return 0;
425944d3f9fSNikolay Borisov 
426944d3f9fSNikolay Borisov 	return 1;
4272b82032cSYan Zheng }
4282b82032cSYan Zheng 
42977bf40a2SQu Wenruo /* Do basic extent buffer checks at read time */
430947a6299SQu Wenruo static int validate_extent_buffer(struct extent_buffer *eb,
431947a6299SQu Wenruo 				  struct btrfs_tree_parent_check *check)
432ce9adaa5SChris Mason {
43377bf40a2SQu Wenruo 	struct btrfs_fs_info *fs_info = eb->fs_info;
434ce9adaa5SChris Mason 	u64 found_start;
43577bf40a2SQu Wenruo 	const u32 csum_size = fs_info->csum_size;
43677bf40a2SQu Wenruo 	u8 found_level;
4372996e1f8SJohannes Thumshirn 	u8 result[BTRFS_CSUM_SIZE];
438dfd29eedSDavid Sterba 	const u8 *header_csum;
43977bf40a2SQu Wenruo 	int ret = 0;
440ea466794SJosef Bacik 
441947a6299SQu Wenruo 	ASSERT(check);
442947a6299SQu Wenruo 
443ce9adaa5SChris Mason 	found_start = btrfs_header_bytenr(eb);
444727011e0SChris Mason 	if (found_start != eb->start) {
4458f0ed7d4SQu Wenruo 		btrfs_err_rl(fs_info,
4468f0ed7d4SQu Wenruo 			"bad tree block start, mirror %u want %llu have %llu",
4478f0ed7d4SQu Wenruo 			     eb->read_mirror, eb->start, found_start);
448f188591eSChris Mason 		ret = -EIO;
44977bf40a2SQu Wenruo 		goto out;
450ce9adaa5SChris Mason 	}
451b0c9b3b0SDavid Sterba 	if (check_tree_block_fsid(eb)) {
4528f0ed7d4SQu Wenruo 		btrfs_err_rl(fs_info, "bad fsid on logical %llu mirror %u",
4538f0ed7d4SQu Wenruo 			     eb->start, eb->read_mirror);
4541259ab75SChris Mason 		ret = -EIO;
45577bf40a2SQu Wenruo 		goto out;
4561259ab75SChris Mason 	}
457ce9adaa5SChris Mason 	found_level = btrfs_header_level(eb);
4581c24c3ceSJosef Bacik 	if (found_level >= BTRFS_MAX_LEVEL) {
4598f0ed7d4SQu Wenruo 		btrfs_err(fs_info,
4608f0ed7d4SQu Wenruo 			"bad tree block level, mirror %u level %d on logical %llu",
4618f0ed7d4SQu Wenruo 			eb->read_mirror, btrfs_header_level(eb), eb->start);
4621c24c3ceSJosef Bacik 		ret = -EIO;
46377bf40a2SQu Wenruo 		goto out;
4641c24c3ceSJosef Bacik 	}
465ce9adaa5SChris Mason 
466c67b3892SDavid Sterba 	csum_tree_block(eb, result);
467dfd29eedSDavid Sterba 	header_csum = page_address(eb->pages[0]) +
468dfd29eedSDavid Sterba 		get_eb_offset_in_page(eb, offsetof(struct btrfs_header, csum));
469a826d6dcSJosef Bacik 
470dfd29eedSDavid Sterba 	if (memcmp(result, header_csum, csum_size) != 0) {
4712996e1f8SJohannes Thumshirn 		btrfs_warn_rl(fs_info,
4728f0ed7d4SQu Wenruo "checksum verify failed on logical %llu mirror %u wanted " CSUM_FMT " found " CSUM_FMT " level %d",
4738f0ed7d4SQu Wenruo 			      eb->start, eb->read_mirror,
474dfd29eedSDavid Sterba 			      CSUM_FMT_VALUE(csum_size, header_csum),
47535be8851SJohannes Thumshirn 			      CSUM_FMT_VALUE(csum_size, result),
47635be8851SJohannes Thumshirn 			      btrfs_header_level(eb));
4772996e1f8SJohannes Thumshirn 		ret = -EUCLEAN;
47877bf40a2SQu Wenruo 		goto out;
4792996e1f8SJohannes Thumshirn 	}
4802996e1f8SJohannes Thumshirn 
481947a6299SQu Wenruo 	if (found_level != check->level) {
48277177ed1SQu Wenruo 		btrfs_err(fs_info,
48377177ed1SQu Wenruo 		"level verify failed on logical %llu mirror %u wanted %u found %u",
48477177ed1SQu Wenruo 			  eb->start, eb->read_mirror, check->level, found_level);
485947a6299SQu Wenruo 		ret = -EIO;
486947a6299SQu Wenruo 		goto out;
487947a6299SQu Wenruo 	}
488947a6299SQu Wenruo 	if (unlikely(check->transid &&
489947a6299SQu Wenruo 		     btrfs_header_generation(eb) != check->transid)) {
490947a6299SQu Wenruo 		btrfs_err_rl(eb->fs_info,
491947a6299SQu Wenruo "parent transid verify failed on logical %llu mirror %u wanted %llu found %llu",
492947a6299SQu Wenruo 				eb->start, eb->read_mirror, check->transid,
493947a6299SQu Wenruo 				btrfs_header_generation(eb));
494947a6299SQu Wenruo 		ret = -EIO;
495947a6299SQu Wenruo 		goto out;
496947a6299SQu Wenruo 	}
497947a6299SQu Wenruo 	if (check->has_first_key) {
498947a6299SQu Wenruo 		struct btrfs_key *expect_key = &check->first_key;
499947a6299SQu Wenruo 		struct btrfs_key found_key;
500947a6299SQu Wenruo 
501947a6299SQu Wenruo 		if (found_level)
502947a6299SQu Wenruo 			btrfs_node_key_to_cpu(eb, &found_key, 0);
503947a6299SQu Wenruo 		else
504947a6299SQu Wenruo 			btrfs_item_key_to_cpu(eb, &found_key, 0);
505947a6299SQu Wenruo 		if (unlikely(btrfs_comp_cpu_keys(expect_key, &found_key))) {
506947a6299SQu Wenruo 			btrfs_err(fs_info,
507947a6299SQu Wenruo "tree first key mismatch detected, bytenr=%llu parent_transid=%llu key expected=(%llu,%u,%llu) has=(%llu,%u,%llu)",
508947a6299SQu Wenruo 				  eb->start, check->transid,
509947a6299SQu Wenruo 				  expect_key->objectid,
510947a6299SQu Wenruo 				  expect_key->type, expect_key->offset,
511947a6299SQu Wenruo 				  found_key.objectid, found_key.type,
512947a6299SQu Wenruo 				  found_key.offset);
513947a6299SQu Wenruo 			ret = -EUCLEAN;
514947a6299SQu Wenruo 			goto out;
515947a6299SQu Wenruo 		}
516947a6299SQu Wenruo 	}
517947a6299SQu Wenruo 	if (check->owner_root) {
518947a6299SQu Wenruo 		ret = btrfs_check_eb_owner(eb, check->owner_root);
519947a6299SQu Wenruo 		if (ret < 0)
520947a6299SQu Wenruo 			goto out;
521947a6299SQu Wenruo 	}
522947a6299SQu Wenruo 
523a826d6dcSJosef Bacik 	/*
524a826d6dcSJosef Bacik 	 * If this is a leaf block and it is corrupt, set the corrupt bit so
525a826d6dcSJosef Bacik 	 * that we don't try and read the other copies of this block, just
526a826d6dcSJosef Bacik 	 * return -EIO.
527a826d6dcSJosef Bacik 	 */
52885d8a826SJosef Bacik 	if (found_level == 0 && btrfs_check_leaf(eb)) {
529a826d6dcSJosef Bacik 		set_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags);
530a826d6dcSJosef Bacik 		ret = -EIO;
531a826d6dcSJosef Bacik 	}
532ce9adaa5SChris Mason 
533813fd1dcSDavid Sterba 	if (found_level > 0 && btrfs_check_node(eb))
534053ab70fSLiu Bo 		ret = -EIO;
535053ab70fSLiu Bo 
536*aebcc159SChristoph Hellwig 	if (ret)
53775391f0dSQu Wenruo 		btrfs_err(fs_info,
5388f0ed7d4SQu Wenruo 		"read time tree block corruption detected on logical %llu mirror %u",
5398f0ed7d4SQu Wenruo 			  eb->start, eb->read_mirror);
54077bf40a2SQu Wenruo out:
54177bf40a2SQu Wenruo 	return ret;
54277bf40a2SQu Wenruo }
54377bf40a2SQu Wenruo 
544371cdc07SQu Wenruo static int validate_subpage_buffer(struct page *page, u64 start, u64 end,
545947a6299SQu Wenruo 				   int mirror, struct btrfs_tree_parent_check *check)
546371cdc07SQu Wenruo {
547371cdc07SQu Wenruo 	struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
548371cdc07SQu Wenruo 	struct extent_buffer *eb;
549371cdc07SQu Wenruo 	bool reads_done;
550371cdc07SQu Wenruo 	int ret = 0;
551371cdc07SQu Wenruo 
552947a6299SQu Wenruo 	ASSERT(check);
553947a6299SQu Wenruo 
554371cdc07SQu Wenruo 	/*
555371cdc07SQu Wenruo 	 * We don't allow bio merge for subpage metadata read, so we should
556371cdc07SQu Wenruo 	 * only get one eb for each endio hook.
557371cdc07SQu Wenruo 	 */
558371cdc07SQu Wenruo 	ASSERT(end == start + fs_info->nodesize - 1);
559371cdc07SQu Wenruo 	ASSERT(PagePrivate(page));
560371cdc07SQu Wenruo 
561371cdc07SQu Wenruo 	eb = find_extent_buffer(fs_info, start);
562371cdc07SQu Wenruo 	/*
563371cdc07SQu Wenruo 	 * When we are reading one tree block, eb must have been inserted into
564371cdc07SQu Wenruo 	 * the radix tree. If not, something is wrong.
565371cdc07SQu Wenruo 	 */
566371cdc07SQu Wenruo 	ASSERT(eb);
567371cdc07SQu Wenruo 
568371cdc07SQu Wenruo 	reads_done = atomic_dec_and_test(&eb->io_pages);
569371cdc07SQu Wenruo 	/* Subpage read must finish in page read */
570371cdc07SQu Wenruo 	ASSERT(reads_done);
571371cdc07SQu Wenruo 
572371cdc07SQu Wenruo 	eb->read_mirror = mirror;
573371cdc07SQu Wenruo 	if (test_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags)) {
574371cdc07SQu Wenruo 		ret = -EIO;
575371cdc07SQu Wenruo 		goto err;
576371cdc07SQu Wenruo 	}
577947a6299SQu Wenruo 	ret = validate_extent_buffer(eb, check);
578371cdc07SQu Wenruo 	if (ret < 0)
579371cdc07SQu Wenruo 		goto err;
580371cdc07SQu Wenruo 
581371cdc07SQu Wenruo 	set_extent_buffer_uptodate(eb);
582371cdc07SQu Wenruo 
583371cdc07SQu Wenruo 	free_extent_buffer(eb);
584371cdc07SQu Wenruo 	return ret;
585371cdc07SQu Wenruo err:
586371cdc07SQu Wenruo 	/*
587371cdc07SQu Wenruo 	 * end_bio_extent_readpage decrements io_pages in case of error,
588371cdc07SQu Wenruo 	 * make sure it has something to decrement.
589371cdc07SQu Wenruo 	 */
590371cdc07SQu Wenruo 	atomic_inc(&eb->io_pages);
591371cdc07SQu Wenruo 	clear_extent_buffer_uptodate(eb);
592371cdc07SQu Wenruo 	free_extent_buffer(eb);
593371cdc07SQu Wenruo 	return ret;
594371cdc07SQu Wenruo }
595371cdc07SQu Wenruo 
596c3a3b19bSQu Wenruo int btrfs_validate_metadata_buffer(struct btrfs_bio *bbio,
59777bf40a2SQu Wenruo 				   struct page *page, u64 start, u64 end,
59877bf40a2SQu Wenruo 				   int mirror)
59977bf40a2SQu Wenruo {
60077bf40a2SQu Wenruo 	struct extent_buffer *eb;
60177bf40a2SQu Wenruo 	int ret = 0;
60277bf40a2SQu Wenruo 	int reads_done;
60377bf40a2SQu Wenruo 
60477bf40a2SQu Wenruo 	ASSERT(page->private);
605371cdc07SQu Wenruo 
606fbca46ebSQu Wenruo 	if (btrfs_sb(page->mapping->host->i_sb)->nodesize < PAGE_SIZE)
607947a6299SQu Wenruo 		return validate_subpage_buffer(page, start, end, mirror,
608947a6299SQu Wenruo 					       &bbio->parent_check);
609371cdc07SQu Wenruo 
61077bf40a2SQu Wenruo 	eb = (struct extent_buffer *)page->private;
61177bf40a2SQu Wenruo 
61277bf40a2SQu Wenruo 	/*
61377bf40a2SQu Wenruo 	 * The pending IO might have been the only thing that kept this buffer
61477bf40a2SQu Wenruo 	 * in memory.  Make sure we have a ref for all this other checks
61577bf40a2SQu Wenruo 	 */
61677bf40a2SQu Wenruo 	atomic_inc(&eb->refs);
61777bf40a2SQu Wenruo 
61877bf40a2SQu Wenruo 	reads_done = atomic_dec_and_test(&eb->io_pages);
61977bf40a2SQu Wenruo 	if (!reads_done)
62077bf40a2SQu Wenruo 		goto err;
62177bf40a2SQu Wenruo 
62277bf40a2SQu Wenruo 	eb->read_mirror = mirror;
62377bf40a2SQu Wenruo 	if (test_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags)) {
62477bf40a2SQu Wenruo 		ret = -EIO;
62577bf40a2SQu Wenruo 		goto err;
62677bf40a2SQu Wenruo 	}
627947a6299SQu Wenruo 	ret = validate_extent_buffer(eb, &bbio->parent_check);
628*aebcc159SChristoph Hellwig 	if (!ret)
629*aebcc159SChristoph Hellwig 		set_extent_buffer_uptodate(eb);
630ce9adaa5SChris Mason err:
63153b381b3SDavid Woodhouse 	if (ret) {
63253b381b3SDavid Woodhouse 		/*
63353b381b3SDavid Woodhouse 		 * our io error hook is going to dec the io pages
63453b381b3SDavid Woodhouse 		 * again, we have to make sure it has something
63553b381b3SDavid Woodhouse 		 * to decrement
63653b381b3SDavid Woodhouse 		 */
63753b381b3SDavid Woodhouse 		atomic_inc(&eb->io_pages);
6380b32f4bbSJosef Bacik 		clear_extent_buffer_uptodate(eb);
63953b381b3SDavid Woodhouse 	}
6400b32f4bbSJosef Bacik 	free_extent_buffer(eb);
64177bf40a2SQu Wenruo 
642f188591eSChris Mason 	return ret;
643ce9adaa5SChris Mason }
644ce9adaa5SChris Mason 
6453dd1462eSJan Beulich #ifdef CONFIG_MIGRATION
6468958b551SMatthew Wilcox (Oracle) static int btree_migrate_folio(struct address_space *mapping,
6478958b551SMatthew Wilcox (Oracle) 		struct folio *dst, struct folio *src, enum migrate_mode mode)
648784b4e29SChris Mason {
649784b4e29SChris Mason 	/*
650784b4e29SChris Mason 	 * we can't safely write a btree page from here,
651784b4e29SChris Mason 	 * we haven't done the locking hook
652784b4e29SChris Mason 	 */
6538958b551SMatthew Wilcox (Oracle) 	if (folio_test_dirty(src))
654784b4e29SChris Mason 		return -EAGAIN;
655784b4e29SChris Mason 	/*
656784b4e29SChris Mason 	 * Buffers may be managed in a filesystem specific way.
657784b4e29SChris Mason 	 * We must have no buffers or drop them.
658784b4e29SChris Mason 	 */
6598958b551SMatthew Wilcox (Oracle) 	if (folio_get_private(src) &&
6608958b551SMatthew Wilcox (Oracle) 	    !filemap_release_folio(src, GFP_KERNEL))
661784b4e29SChris Mason 		return -EAGAIN;
66254184650SMatthew Wilcox (Oracle) 	return migrate_folio(mapping, dst, src, mode);
663784b4e29SChris Mason }
6648958b551SMatthew Wilcox (Oracle) #else
6658958b551SMatthew Wilcox (Oracle) #define btree_migrate_folio NULL
6663dd1462eSJan Beulich #endif
667784b4e29SChris Mason 
6680da5468fSChris Mason static int btree_writepages(struct address_space *mapping,
6690da5468fSChris Mason 			    struct writeback_control *wbc)
6700da5468fSChris Mason {
671e2d84521SMiao Xie 	struct btrfs_fs_info *fs_info;
672e2d84521SMiao Xie 	int ret;
673e2d84521SMiao Xie 
674d8d5f3e1SChris Mason 	if (wbc->sync_mode == WB_SYNC_NONE) {
675448d640bSChris Mason 
676448d640bSChris Mason 		if (wbc->for_kupdate)
677448d640bSChris Mason 			return 0;
678448d640bSChris Mason 
679e2d84521SMiao Xie 		fs_info = BTRFS_I(mapping->host)->root->fs_info;
680b9473439SChris Mason 		/* this is a bit racy, but that's ok */
681d814a491SEthan Lien 		ret = __percpu_counter_compare(&fs_info->dirty_metadata_bytes,
682d814a491SEthan Lien 					     BTRFS_DIRTY_METADATA_THRESH,
683d814a491SEthan Lien 					     fs_info->dirty_metadata_batch);
684e2d84521SMiao Xie 		if (ret < 0)
685793955bcSChris Mason 			return 0;
686793955bcSChris Mason 	}
6870b32f4bbSJosef Bacik 	return btree_write_cache_pages(mapping, wbc);
6880da5468fSChris Mason }
6890da5468fSChris Mason 
690f913cff3SMatthew Wilcox (Oracle) static bool btree_release_folio(struct folio *folio, gfp_t gfp_flags)
6915f39d397SChris Mason {
692f913cff3SMatthew Wilcox (Oracle) 	if (folio_test_writeback(folio) || folio_test_dirty(folio))
693f913cff3SMatthew Wilcox (Oracle) 		return false;
6940c4e538bSDavid Sterba 
695f913cff3SMatthew Wilcox (Oracle) 	return try_release_extent_buffer(&folio->page);
696d98237b3SChris Mason }
697d98237b3SChris Mason 
698895586ebSMatthew Wilcox (Oracle) static void btree_invalidate_folio(struct folio *folio, size_t offset,
699895586ebSMatthew Wilcox (Oracle) 				 size_t length)
700d98237b3SChris Mason {
701d1310b2eSChris Mason 	struct extent_io_tree *tree;
702895586ebSMatthew Wilcox (Oracle) 	tree = &BTRFS_I(folio->mapping->host)->io_tree;
703895586ebSMatthew Wilcox (Oracle) 	extent_invalidate_folio(tree, folio, offset);
704f913cff3SMatthew Wilcox (Oracle) 	btree_release_folio(folio, GFP_NOFS);
705895586ebSMatthew Wilcox (Oracle) 	if (folio_get_private(folio)) {
706895586ebSMatthew Wilcox (Oracle) 		btrfs_warn(BTRFS_I(folio->mapping->host)->root->fs_info,
707895586ebSMatthew Wilcox (Oracle) 			   "folio private not zero on folio %llu",
708895586ebSMatthew Wilcox (Oracle) 			   (unsigned long long)folio_pos(folio));
709895586ebSMatthew Wilcox (Oracle) 		folio_detach_private(folio);
7109ad6b7bcSChris Mason 	}
711d98237b3SChris Mason }
712d98237b3SChris Mason 
713bb146eb2SJosef Bacik #ifdef DEBUG
7140079c3b1SMatthew Wilcox (Oracle) static bool btree_dirty_folio(struct address_space *mapping,
7150079c3b1SMatthew Wilcox (Oracle) 		struct folio *folio)
7160079c3b1SMatthew Wilcox (Oracle) {
7170079c3b1SMatthew Wilcox (Oracle) 	struct btrfs_fs_info *fs_info = btrfs_sb(mapping->host->i_sb);
718139e8cd3SQu Wenruo 	struct btrfs_subpage *subpage;
7190b32f4bbSJosef Bacik 	struct extent_buffer *eb;
720139e8cd3SQu Wenruo 	int cur_bit = 0;
7210079c3b1SMatthew Wilcox (Oracle) 	u64 page_start = folio_pos(folio);
7220b32f4bbSJosef Bacik 
723139e8cd3SQu Wenruo 	if (fs_info->sectorsize == PAGE_SIZE) {
7240079c3b1SMatthew Wilcox (Oracle) 		eb = folio_get_private(folio);
7250b32f4bbSJosef Bacik 		BUG_ON(!eb);
7260b32f4bbSJosef Bacik 		BUG_ON(!test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
7270b32f4bbSJosef Bacik 		BUG_ON(!atomic_read(&eb->refs));
72849d0c642SFilipe Manana 		btrfs_assert_tree_write_locked(eb);
7290079c3b1SMatthew Wilcox (Oracle) 		return filemap_dirty_folio(mapping, folio);
730139e8cd3SQu Wenruo 	}
7310079c3b1SMatthew Wilcox (Oracle) 	subpage = folio_get_private(folio);
732139e8cd3SQu Wenruo 
733139e8cd3SQu Wenruo 	ASSERT(subpage->dirty_bitmap);
734139e8cd3SQu Wenruo 	while (cur_bit < BTRFS_SUBPAGE_BITMAP_SIZE) {
735139e8cd3SQu Wenruo 		unsigned long flags;
736139e8cd3SQu Wenruo 		u64 cur;
737139e8cd3SQu Wenruo 		u16 tmp = (1 << cur_bit);
738139e8cd3SQu Wenruo 
739139e8cd3SQu Wenruo 		spin_lock_irqsave(&subpage->lock, flags);
740139e8cd3SQu Wenruo 		if (!(tmp & subpage->dirty_bitmap)) {
741139e8cd3SQu Wenruo 			spin_unlock_irqrestore(&subpage->lock, flags);
742139e8cd3SQu Wenruo 			cur_bit++;
743139e8cd3SQu Wenruo 			continue;
744139e8cd3SQu Wenruo 		}
745139e8cd3SQu Wenruo 		spin_unlock_irqrestore(&subpage->lock, flags);
746139e8cd3SQu Wenruo 		cur = page_start + cur_bit * fs_info->sectorsize;
747139e8cd3SQu Wenruo 
748139e8cd3SQu Wenruo 		eb = find_extent_buffer(fs_info, cur);
749139e8cd3SQu Wenruo 		ASSERT(eb);
750139e8cd3SQu Wenruo 		ASSERT(test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
751139e8cd3SQu Wenruo 		ASSERT(atomic_read(&eb->refs));
75249d0c642SFilipe Manana 		btrfs_assert_tree_write_locked(eb);
753139e8cd3SQu Wenruo 		free_extent_buffer(eb);
754139e8cd3SQu Wenruo 
755139e8cd3SQu Wenruo 		cur_bit += (fs_info->nodesize >> fs_info->sectorsize_bits);
756139e8cd3SQu Wenruo 	}
7570079c3b1SMatthew Wilcox (Oracle) 	return filemap_dirty_folio(mapping, folio);
7580b32f4bbSJosef Bacik }
7590079c3b1SMatthew Wilcox (Oracle) #else
7600079c3b1SMatthew Wilcox (Oracle) #define btree_dirty_folio filemap_dirty_folio
7610079c3b1SMatthew Wilcox (Oracle) #endif
7620b32f4bbSJosef Bacik 
7637f09410bSAlexey Dobriyan static const struct address_space_operations btree_aops = {
7640da5468fSChris Mason 	.writepages	= btree_writepages,
765f913cff3SMatthew Wilcox (Oracle) 	.release_folio	= btree_release_folio,
766895586ebSMatthew Wilcox (Oracle) 	.invalidate_folio = btree_invalidate_folio,
7678958b551SMatthew Wilcox (Oracle) 	.migrate_folio	= btree_migrate_folio,
7680079c3b1SMatthew Wilcox (Oracle) 	.dirty_folio	= btree_dirty_folio,
769d98237b3SChris Mason };
770123abc88SChris Mason 
7712ff7e61eSJeff Mahoney struct extent_buffer *btrfs_find_create_tree_block(
7722ff7e61eSJeff Mahoney 						struct btrfs_fs_info *fs_info,
7733fbaf258SJosef Bacik 						u64 bytenr, u64 owner_root,
7743fbaf258SJosef Bacik 						int level)
7750999df54SChris Mason {
7760b246afaSJeff Mahoney 	if (btrfs_is_testing(fs_info))
7770b246afaSJeff Mahoney 		return alloc_test_extent_buffer(fs_info, bytenr);
7783fbaf258SJosef Bacik 	return alloc_extent_buffer(fs_info, bytenr, owner_root, level);
7790999df54SChris Mason }
7800999df54SChris Mason 
781581c1760SQu Wenruo /*
782581c1760SQu Wenruo  * Read tree block at logical address @bytenr and do variant basic but critical
783581c1760SQu Wenruo  * verification.
784581c1760SQu Wenruo  *
785789d6a3aSQu Wenruo  * @check:		expected tree parentness check, see comments of the
786789d6a3aSQu Wenruo  *			structure for details.
787581c1760SQu Wenruo  */
7882ff7e61eSJeff Mahoney struct extent_buffer *read_tree_block(struct btrfs_fs_info *fs_info, u64 bytenr,
789789d6a3aSQu Wenruo 				      struct btrfs_tree_parent_check *check)
790e20d96d6SChris Mason {
7915f39d397SChris Mason 	struct extent_buffer *buf = NULL;
79219c00ddcSChris Mason 	int ret;
79319c00ddcSChris Mason 
794789d6a3aSQu Wenruo 	ASSERT(check);
795789d6a3aSQu Wenruo 
796789d6a3aSQu Wenruo 	buf = btrfs_find_create_tree_block(fs_info, bytenr, check->owner_root,
797789d6a3aSQu Wenruo 					   check->level);
798c871b0f2SLiu Bo 	if (IS_ERR(buf))
799c871b0f2SLiu Bo 		return buf;
800e4204dedSChris Mason 
801789d6a3aSQu Wenruo 	ret = btrfs_read_extent_buffer(buf, check);
8020f0fe8f7SFilipe David Borba Manana 	if (ret) {
803537f38f0SNikolay Borisov 		free_extent_buffer_stale(buf);
80464c043deSLiu Bo 		return ERR_PTR(ret);
8050f0fe8f7SFilipe David Borba Manana 	}
806789d6a3aSQu Wenruo 	if (btrfs_check_eb_owner(buf, check->owner_root)) {
80788c602abSQu Wenruo 		free_extent_buffer_stale(buf);
80888c602abSQu Wenruo 		return ERR_PTR(-EUCLEAN);
80988c602abSQu Wenruo 	}
8105f39d397SChris Mason 	return buf;
811ce9adaa5SChris Mason 
812eb60ceacSChris Mason }
813eb60ceacSChris Mason 
814da17066cSJeff Mahoney static void __setup_root(struct btrfs_root *root, struct btrfs_fs_info *fs_info,
815e20d96d6SChris Mason 			 u64 objectid)
816d97e63b6SChris Mason {
8177c0260eeSJeff Mahoney 	bool dummy = test_bit(BTRFS_FS_STATE_DUMMY_FS_INFO, &fs_info->fs_state);
8182e608bd1SJosef Bacik 
8192e608bd1SJosef Bacik 	memset(&root->root_key, 0, sizeof(root->root_key));
8202e608bd1SJosef Bacik 	memset(&root->root_item, 0, sizeof(root->root_item));
8212e608bd1SJosef Bacik 	memset(&root->defrag_progress, 0, sizeof(root->defrag_progress));
82296dfcb46SJosef Bacik 	root->fs_info = fs_info;
8232e608bd1SJosef Bacik 	root->root_key.objectid = objectid;
824cfaa7295SChris Mason 	root->node = NULL;
825a28ec197SChris Mason 	root->commit_root = NULL;
82627cdeb70SMiao Xie 	root->state = 0;
827abed4aaaSJosef Bacik 	RB_CLEAR_NODE(&root->rb_node);
8280b86a832SChris Mason 
8290f7d52f4SChris Mason 	root->last_trans = 0;
8306b8fad57SNikolay Borisov 	root->free_objectid = 0;
831eb73c1b7SMiao Xie 	root->nr_delalloc_inodes = 0;
832199c2a9cSMiao Xie 	root->nr_ordered_extents = 0;
8336bef4d31SEric Paris 	root->inode_tree = RB_ROOT;
834088aea3bSDavid Sterba 	INIT_RADIX_TREE(&root->delayed_nodes_tree, GFP_ATOMIC);
8352e608bd1SJosef Bacik 
8362e608bd1SJosef Bacik 	btrfs_init_root_block_rsv(root);
8370b86a832SChris Mason 
8380b86a832SChris Mason 	INIT_LIST_HEAD(&root->dirty_list);
8395d4f98a2SYan Zheng 	INIT_LIST_HEAD(&root->root_list);
840eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&root->delalloc_inodes);
841eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&root->delalloc_root);
842199c2a9cSMiao Xie 	INIT_LIST_HEAD(&root->ordered_extents);
843199c2a9cSMiao Xie 	INIT_LIST_HEAD(&root->ordered_root);
844d2311e69SQu Wenruo 	INIT_LIST_HEAD(&root->reloc_dirty_list);
8452ab28f32SJosef Bacik 	INIT_LIST_HEAD(&root->logged_list[0]);
8462ab28f32SJosef Bacik 	INIT_LIST_HEAD(&root->logged_list[1]);
8475d4f98a2SYan Zheng 	spin_lock_init(&root->inode_lock);
848eb73c1b7SMiao Xie 	spin_lock_init(&root->delalloc_lock);
849199c2a9cSMiao Xie 	spin_lock_init(&root->ordered_extent_lock);
850f0486c68SYan, Zheng 	spin_lock_init(&root->accounting_lock);
8512ab28f32SJosef Bacik 	spin_lock_init(&root->log_extents_lock[0]);
8522ab28f32SJosef Bacik 	spin_lock_init(&root->log_extents_lock[1]);
8538287475aSQu Wenruo 	spin_lock_init(&root->qgroup_meta_rsv_lock);
854a2135011SChris Mason 	mutex_init(&root->objectid_mutex);
855e02119d5SChris Mason 	mutex_init(&root->log_mutex);
85631f3d255SMiao Xie 	mutex_init(&root->ordered_extent_mutex);
857573bfb72SMiao Xie 	mutex_init(&root->delalloc_mutex);
858c53e9653SQu Wenruo 	init_waitqueue_head(&root->qgroup_flush_wait);
8597237f183SYan Zheng 	init_waitqueue_head(&root->log_writer_wait);
8607237f183SYan Zheng 	init_waitqueue_head(&root->log_commit_wait[0]);
8617237f183SYan Zheng 	init_waitqueue_head(&root->log_commit_wait[1]);
8628b050d35SMiao Xie 	INIT_LIST_HEAD(&root->log_ctxs[0]);
8638b050d35SMiao Xie 	INIT_LIST_HEAD(&root->log_ctxs[1]);
8647237f183SYan Zheng 	atomic_set(&root->log_commit[0], 0);
8657237f183SYan Zheng 	atomic_set(&root->log_commit[1], 0);
8667237f183SYan Zheng 	atomic_set(&root->log_writers, 0);
8672ecb7923SMiao Xie 	atomic_set(&root->log_batch, 0);
8680700cea7SElena Reshetova 	refcount_set(&root->refs, 1);
8698ecebf4dSRobbie Ko 	atomic_set(&root->snapshot_force_cow, 0);
870eede2bf3SOmar Sandoval 	atomic_set(&root->nr_swapfiles, 0);
8717237f183SYan Zheng 	root->log_transid = 0;
872d1433debSMiao Xie 	root->log_transid_committed = -1;
873257c62e1SChris Mason 	root->last_log_commit = 0;
8742e608bd1SJosef Bacik 	root->anon_dev = 0;
875e289f03eSFilipe Manana 	if (!dummy) {
87643eb5f29SQu Wenruo 		extent_io_tree_init(fs_info, &root->dirty_log_pages,
87735da5a7eSDavid Sterba 				    IO_TREE_ROOT_DIRTY_LOG_PAGES);
878e289f03eSFilipe Manana 		extent_io_tree_init(fs_info, &root->log_csum_range,
87935da5a7eSDavid Sterba 				    IO_TREE_LOG_CSUM_RANGE);
880e289f03eSFilipe Manana 	}
881017e5369SChris Mason 
8825f3ab90aSAnand Jain 	spin_lock_init(&root->root_item_lock);
883370a11b8SQu Wenruo 	btrfs_qgroup_init_swapped_blocks(&root->swapped_blocks);
884bd647ce3SJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
885bd647ce3SJosef Bacik 	INIT_LIST_HEAD(&root->leak_list);
886fc7cbcd4SDavid Sterba 	spin_lock(&fs_info->fs_roots_radix_lock);
887bd647ce3SJosef Bacik 	list_add_tail(&root->leak_list, &fs_info->allocated_roots);
888fc7cbcd4SDavid Sterba 	spin_unlock(&fs_info->fs_roots_radix_lock);
889bd647ce3SJosef Bacik #endif
8903768f368SChris Mason }
8913768f368SChris Mason 
89274e4d827SDavid Sterba static struct btrfs_root *btrfs_alloc_root(struct btrfs_fs_info *fs_info,
89396dfcb46SJosef Bacik 					   u64 objectid, gfp_t flags)
8946f07e42eSAl Viro {
89574e4d827SDavid Sterba 	struct btrfs_root *root = kzalloc(sizeof(*root), flags);
8966f07e42eSAl Viro 	if (root)
89796dfcb46SJosef Bacik 		__setup_root(root, fs_info, objectid);
8986f07e42eSAl Viro 	return root;
8996f07e42eSAl Viro }
9006f07e42eSAl Viro 
90106ea65a3SJosef Bacik #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
90206ea65a3SJosef Bacik /* Should only be used by the testing infrastructure */
903da17066cSJeff Mahoney struct btrfs_root *btrfs_alloc_dummy_root(struct btrfs_fs_info *fs_info)
90406ea65a3SJosef Bacik {
90506ea65a3SJosef Bacik 	struct btrfs_root *root;
90606ea65a3SJosef Bacik 
9077c0260eeSJeff Mahoney 	if (!fs_info)
9087c0260eeSJeff Mahoney 		return ERR_PTR(-EINVAL);
9097c0260eeSJeff Mahoney 
91096dfcb46SJosef Bacik 	root = btrfs_alloc_root(fs_info, BTRFS_ROOT_TREE_OBJECTID, GFP_KERNEL);
91106ea65a3SJosef Bacik 	if (!root)
91206ea65a3SJosef Bacik 		return ERR_PTR(-ENOMEM);
913da17066cSJeff Mahoney 
914b9ef22deSFeifei Xu 	/* We don't use the stripesize in selftest, set it as sectorsize */
915faa2dbf0SJosef Bacik 	root->alloc_bytenr = 0;
91606ea65a3SJosef Bacik 
91706ea65a3SJosef Bacik 	return root;
91806ea65a3SJosef Bacik }
91906ea65a3SJosef Bacik #endif
92006ea65a3SJosef Bacik 
921abed4aaaSJosef Bacik static int global_root_cmp(struct rb_node *a_node, const struct rb_node *b_node)
922abed4aaaSJosef Bacik {
923abed4aaaSJosef Bacik 	const struct btrfs_root *a = rb_entry(a_node, struct btrfs_root, rb_node);
924abed4aaaSJosef Bacik 	const struct btrfs_root *b = rb_entry(b_node, struct btrfs_root, rb_node);
925abed4aaaSJosef Bacik 
926abed4aaaSJosef Bacik 	return btrfs_comp_cpu_keys(&a->root_key, &b->root_key);
927abed4aaaSJosef Bacik }
928abed4aaaSJosef Bacik 
929abed4aaaSJosef Bacik static int global_root_key_cmp(const void *k, const struct rb_node *node)
930abed4aaaSJosef Bacik {
931abed4aaaSJosef Bacik 	const struct btrfs_key *key = k;
932abed4aaaSJosef Bacik 	const struct btrfs_root *root = rb_entry(node, struct btrfs_root, rb_node);
933abed4aaaSJosef Bacik 
934abed4aaaSJosef Bacik 	return btrfs_comp_cpu_keys(key, &root->root_key);
935abed4aaaSJosef Bacik }
936abed4aaaSJosef Bacik 
937abed4aaaSJosef Bacik int btrfs_global_root_insert(struct btrfs_root *root)
938abed4aaaSJosef Bacik {
939abed4aaaSJosef Bacik 	struct btrfs_fs_info *fs_info = root->fs_info;
940abed4aaaSJosef Bacik 	struct rb_node *tmp;
941745806fbSQu Wenruo 	int ret = 0;
942abed4aaaSJosef Bacik 
943abed4aaaSJosef Bacik 	write_lock(&fs_info->global_root_lock);
944abed4aaaSJosef Bacik 	tmp = rb_find_add(&root->rb_node, &fs_info->global_root_tree, global_root_cmp);
945abed4aaaSJosef Bacik 	write_unlock(&fs_info->global_root_lock);
946abed4aaaSJosef Bacik 
947745806fbSQu Wenruo 	if (tmp) {
948745806fbSQu Wenruo 		ret = -EEXIST;
949745806fbSQu Wenruo 		btrfs_warn(fs_info, "global root %llu %llu already exists",
950745806fbSQu Wenruo 				root->root_key.objectid, root->root_key.offset);
951745806fbSQu Wenruo 	}
952745806fbSQu Wenruo 	return ret;
953abed4aaaSJosef Bacik }
954abed4aaaSJosef Bacik 
955abed4aaaSJosef Bacik void btrfs_global_root_delete(struct btrfs_root *root)
956abed4aaaSJosef Bacik {
957abed4aaaSJosef Bacik 	struct btrfs_fs_info *fs_info = root->fs_info;
958abed4aaaSJosef Bacik 
959abed4aaaSJosef Bacik 	write_lock(&fs_info->global_root_lock);
960abed4aaaSJosef Bacik 	rb_erase(&root->rb_node, &fs_info->global_root_tree);
961abed4aaaSJosef Bacik 	write_unlock(&fs_info->global_root_lock);
962abed4aaaSJosef Bacik }
963abed4aaaSJosef Bacik 
964abed4aaaSJosef Bacik struct btrfs_root *btrfs_global_root(struct btrfs_fs_info *fs_info,
965abed4aaaSJosef Bacik 				     struct btrfs_key *key)
966abed4aaaSJosef Bacik {
967abed4aaaSJosef Bacik 	struct rb_node *node;
968abed4aaaSJosef Bacik 	struct btrfs_root *root = NULL;
969abed4aaaSJosef Bacik 
970abed4aaaSJosef Bacik 	read_lock(&fs_info->global_root_lock);
971abed4aaaSJosef Bacik 	node = rb_find(key, &fs_info->global_root_tree, global_root_key_cmp);
972abed4aaaSJosef Bacik 	if (node)
973abed4aaaSJosef Bacik 		root = container_of(node, struct btrfs_root, rb_node);
974abed4aaaSJosef Bacik 	read_unlock(&fs_info->global_root_lock);
975abed4aaaSJosef Bacik 
976abed4aaaSJosef Bacik 	return root;
977abed4aaaSJosef Bacik }
978abed4aaaSJosef Bacik 
979f7238e50SJosef Bacik static u64 btrfs_global_root_id(struct btrfs_fs_info *fs_info, u64 bytenr)
980f7238e50SJosef Bacik {
981f7238e50SJosef Bacik 	struct btrfs_block_group *block_group;
982f7238e50SJosef Bacik 	u64 ret;
983f7238e50SJosef Bacik 
984f7238e50SJosef Bacik 	if (!btrfs_fs_incompat(fs_info, EXTENT_TREE_V2))
985f7238e50SJosef Bacik 		return 0;
986f7238e50SJosef Bacik 
987f7238e50SJosef Bacik 	if (bytenr)
988f7238e50SJosef Bacik 		block_group = btrfs_lookup_block_group(fs_info, bytenr);
989f7238e50SJosef Bacik 	else
990f7238e50SJosef Bacik 		block_group = btrfs_lookup_first_block_group(fs_info, bytenr);
991f7238e50SJosef Bacik 	ASSERT(block_group);
992f7238e50SJosef Bacik 	if (!block_group)
993f7238e50SJosef Bacik 		return 0;
994f7238e50SJosef Bacik 	ret = block_group->global_root_id;
995f7238e50SJosef Bacik 	btrfs_put_block_group(block_group);
996f7238e50SJosef Bacik 
997f7238e50SJosef Bacik 	return ret;
998f7238e50SJosef Bacik }
999f7238e50SJosef Bacik 
1000abed4aaaSJosef Bacik struct btrfs_root *btrfs_csum_root(struct btrfs_fs_info *fs_info, u64 bytenr)
1001abed4aaaSJosef Bacik {
1002abed4aaaSJosef Bacik 	struct btrfs_key key = {
1003abed4aaaSJosef Bacik 		.objectid = BTRFS_CSUM_TREE_OBJECTID,
1004abed4aaaSJosef Bacik 		.type = BTRFS_ROOT_ITEM_KEY,
1005f7238e50SJosef Bacik 		.offset = btrfs_global_root_id(fs_info, bytenr),
1006abed4aaaSJosef Bacik 	};
1007abed4aaaSJosef Bacik 
1008abed4aaaSJosef Bacik 	return btrfs_global_root(fs_info, &key);
1009abed4aaaSJosef Bacik }
1010abed4aaaSJosef Bacik 
1011abed4aaaSJosef Bacik struct btrfs_root *btrfs_extent_root(struct btrfs_fs_info *fs_info, u64 bytenr)
1012abed4aaaSJosef Bacik {
1013abed4aaaSJosef Bacik 	struct btrfs_key key = {
1014abed4aaaSJosef Bacik 		.objectid = BTRFS_EXTENT_TREE_OBJECTID,
1015abed4aaaSJosef Bacik 		.type = BTRFS_ROOT_ITEM_KEY,
1016f7238e50SJosef Bacik 		.offset = btrfs_global_root_id(fs_info, bytenr),
1017abed4aaaSJosef Bacik 	};
1018abed4aaaSJosef Bacik 
1019abed4aaaSJosef Bacik 	return btrfs_global_root(fs_info, &key);
1020abed4aaaSJosef Bacik }
1021abed4aaaSJosef Bacik 
102251129b33SJosef Bacik struct btrfs_root *btrfs_block_group_root(struct btrfs_fs_info *fs_info)
102351129b33SJosef Bacik {
102451129b33SJosef Bacik 	if (btrfs_fs_compat_ro(fs_info, BLOCK_GROUP_TREE))
102551129b33SJosef Bacik 		return fs_info->block_group_root;
102651129b33SJosef Bacik 	return btrfs_extent_root(fs_info, 0);
102751129b33SJosef Bacik }
102851129b33SJosef Bacik 
102920897f5cSArne Jansen struct btrfs_root *btrfs_create_tree(struct btrfs_trans_handle *trans,
103020897f5cSArne Jansen 				     u64 objectid)
103120897f5cSArne Jansen {
10329b7a2440SDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
103320897f5cSArne Jansen 	struct extent_buffer *leaf;
103420897f5cSArne Jansen 	struct btrfs_root *tree_root = fs_info->tree_root;
103520897f5cSArne Jansen 	struct btrfs_root *root;
103620897f5cSArne Jansen 	struct btrfs_key key;
1037b89f6d1fSFilipe Manana 	unsigned int nofs_flag;
103820897f5cSArne Jansen 	int ret = 0;
103920897f5cSArne Jansen 
1040b89f6d1fSFilipe Manana 	/*
1041b89f6d1fSFilipe Manana 	 * We're holding a transaction handle, so use a NOFS memory allocation
1042b89f6d1fSFilipe Manana 	 * context to avoid deadlock if reclaim happens.
1043b89f6d1fSFilipe Manana 	 */
1044b89f6d1fSFilipe Manana 	nofs_flag = memalloc_nofs_save();
104596dfcb46SJosef Bacik 	root = btrfs_alloc_root(fs_info, objectid, GFP_KERNEL);
1046b89f6d1fSFilipe Manana 	memalloc_nofs_restore(nofs_flag);
104720897f5cSArne Jansen 	if (!root)
104820897f5cSArne Jansen 		return ERR_PTR(-ENOMEM);
104920897f5cSArne Jansen 
105020897f5cSArne Jansen 	root->root_key.objectid = objectid;
105120897f5cSArne Jansen 	root->root_key.type = BTRFS_ROOT_ITEM_KEY;
105220897f5cSArne Jansen 	root->root_key.offset = 0;
105320897f5cSArne Jansen 
10549631e4ccSJosef Bacik 	leaf = btrfs_alloc_tree_block(trans, root, 0, objectid, NULL, 0, 0, 0,
10559631e4ccSJosef Bacik 				      BTRFS_NESTING_NORMAL);
105620897f5cSArne Jansen 	if (IS_ERR(leaf)) {
105720897f5cSArne Jansen 		ret = PTR_ERR(leaf);
10581dd05682STsutomu Itoh 		leaf = NULL;
1059c1b07854SPeng Hao 		goto fail;
106020897f5cSArne Jansen 	}
106120897f5cSArne Jansen 
106220897f5cSArne Jansen 	root->node = leaf;
106320897f5cSArne Jansen 	btrfs_mark_buffer_dirty(leaf);
106420897f5cSArne Jansen 
106520897f5cSArne Jansen 	root->commit_root = btrfs_root_node(root);
106627cdeb70SMiao Xie 	set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
106720897f5cSArne Jansen 
1068f944d2cbSDavid Sterba 	btrfs_set_root_flags(&root->root_item, 0);
1069f944d2cbSDavid Sterba 	btrfs_set_root_limit(&root->root_item, 0);
107020897f5cSArne Jansen 	btrfs_set_root_bytenr(&root->root_item, leaf->start);
107120897f5cSArne Jansen 	btrfs_set_root_generation(&root->root_item, trans->transid);
107220897f5cSArne Jansen 	btrfs_set_root_level(&root->root_item, 0);
107320897f5cSArne Jansen 	btrfs_set_root_refs(&root->root_item, 1);
107420897f5cSArne Jansen 	btrfs_set_root_used(&root->root_item, leaf->len);
107520897f5cSArne Jansen 	btrfs_set_root_last_snapshot(&root->root_item, 0);
107620897f5cSArne Jansen 	btrfs_set_root_dirid(&root->root_item, 0);
107733d85fdaSQu Wenruo 	if (is_fstree(objectid))
1078807fc790SAndy Shevchenko 		generate_random_guid(root->root_item.uuid);
1079807fc790SAndy Shevchenko 	else
1080807fc790SAndy Shevchenko 		export_guid(root->root_item.uuid, &guid_null);
1081c8422684SDavid Sterba 	btrfs_set_root_drop_level(&root->root_item, 0);
108220897f5cSArne Jansen 
10838a6a87cdSBoris Burkov 	btrfs_tree_unlock(leaf);
10848a6a87cdSBoris Burkov 
108520897f5cSArne Jansen 	key.objectid = objectid;
108620897f5cSArne Jansen 	key.type = BTRFS_ROOT_ITEM_KEY;
108720897f5cSArne Jansen 	key.offset = 0;
108820897f5cSArne Jansen 	ret = btrfs_insert_root(trans, tree_root, &key, &root->root_item);
108920897f5cSArne Jansen 	if (ret)
109020897f5cSArne Jansen 		goto fail;
109120897f5cSArne Jansen 
109220897f5cSArne Jansen 	return root;
10931dd05682STsutomu Itoh 
10948a6a87cdSBoris Burkov fail:
109500246528SJosef Bacik 	btrfs_put_root(root);
10961dd05682STsutomu Itoh 
10971dd05682STsutomu Itoh 	return ERR_PTR(ret);
109820897f5cSArne Jansen }
109920897f5cSArne Jansen 
11007237f183SYan Zheng static struct btrfs_root *alloc_log_tree(struct btrfs_trans_handle *trans,
1101e02119d5SChris Mason 					 struct btrfs_fs_info *fs_info)
11020f7d52f4SChris Mason {
11030f7d52f4SChris Mason 	struct btrfs_root *root;
1104e02119d5SChris Mason 
110596dfcb46SJosef Bacik 	root = btrfs_alloc_root(fs_info, BTRFS_TREE_LOG_OBJECTID, GFP_NOFS);
1106e02119d5SChris Mason 	if (!root)
11077237f183SYan Zheng 		return ERR_PTR(-ENOMEM);
1108e02119d5SChris Mason 
1109e02119d5SChris Mason 	root->root_key.objectid = BTRFS_TREE_LOG_OBJECTID;
1110e02119d5SChris Mason 	root->root_key.type = BTRFS_ROOT_ITEM_KEY;
1111e02119d5SChris Mason 	root->root_key.offset = BTRFS_TREE_LOG_OBJECTID;
111227cdeb70SMiao Xie 
11136ab6ebb7SNaohiro Aota 	return root;
11146ab6ebb7SNaohiro Aota }
11156ab6ebb7SNaohiro Aota 
11166ab6ebb7SNaohiro Aota int btrfs_alloc_log_tree_node(struct btrfs_trans_handle *trans,
11176ab6ebb7SNaohiro Aota 			      struct btrfs_root *root)
11186ab6ebb7SNaohiro Aota {
11196ab6ebb7SNaohiro Aota 	struct extent_buffer *leaf;
11206ab6ebb7SNaohiro Aota 
11217237f183SYan Zheng 	/*
112292a7cc42SQu Wenruo 	 * DON'T set SHAREABLE bit for log trees.
112327cdeb70SMiao Xie 	 *
112492a7cc42SQu Wenruo 	 * Log trees are not exposed to user space thus can't be snapshotted,
112592a7cc42SQu Wenruo 	 * and they go away before a real commit is actually done.
112692a7cc42SQu Wenruo 	 *
112792a7cc42SQu Wenruo 	 * They do store pointers to file data extents, and those reference
112892a7cc42SQu Wenruo 	 * counts still get updated (along with back refs to the log tree).
11297237f183SYan Zheng 	 */
1130e02119d5SChris Mason 
11314d75f8a9SDavid Sterba 	leaf = btrfs_alloc_tree_block(trans, root, 0, BTRFS_TREE_LOG_OBJECTID,
11329631e4ccSJosef Bacik 			NULL, 0, 0, 0, BTRFS_NESTING_NORMAL);
11336ab6ebb7SNaohiro Aota 	if (IS_ERR(leaf))
11346ab6ebb7SNaohiro Aota 		return PTR_ERR(leaf);
1135e02119d5SChris Mason 
11367237f183SYan Zheng 	root->node = leaf;
1137e02119d5SChris Mason 
1138e02119d5SChris Mason 	btrfs_mark_buffer_dirty(root->node);
1139e02119d5SChris Mason 	btrfs_tree_unlock(root->node);
11406ab6ebb7SNaohiro Aota 
11416ab6ebb7SNaohiro Aota 	return 0;
11427237f183SYan Zheng }
11437237f183SYan Zheng 
11447237f183SYan Zheng int btrfs_init_log_root_tree(struct btrfs_trans_handle *trans,
11457237f183SYan Zheng 			     struct btrfs_fs_info *fs_info)
11467237f183SYan Zheng {
11477237f183SYan Zheng 	struct btrfs_root *log_root;
11487237f183SYan Zheng 
11497237f183SYan Zheng 	log_root = alloc_log_tree(trans, fs_info);
11507237f183SYan Zheng 	if (IS_ERR(log_root))
11517237f183SYan Zheng 		return PTR_ERR(log_root);
11526ab6ebb7SNaohiro Aota 
11533ddebf27SNaohiro Aota 	if (!btrfs_is_zoned(fs_info)) {
11543ddebf27SNaohiro Aota 		int ret = btrfs_alloc_log_tree_node(trans, log_root);
11553ddebf27SNaohiro Aota 
11566ab6ebb7SNaohiro Aota 		if (ret) {
11576ab6ebb7SNaohiro Aota 			btrfs_put_root(log_root);
11586ab6ebb7SNaohiro Aota 			return ret;
11596ab6ebb7SNaohiro Aota 		}
11603ddebf27SNaohiro Aota 	}
11616ab6ebb7SNaohiro Aota 
11627237f183SYan Zheng 	WARN_ON(fs_info->log_root_tree);
11637237f183SYan Zheng 	fs_info->log_root_tree = log_root;
11647237f183SYan Zheng 	return 0;
11657237f183SYan Zheng }
11667237f183SYan Zheng 
11677237f183SYan Zheng int btrfs_add_log_tree(struct btrfs_trans_handle *trans,
11687237f183SYan Zheng 		       struct btrfs_root *root)
11697237f183SYan Zheng {
11700b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
11717237f183SYan Zheng 	struct btrfs_root *log_root;
11727237f183SYan Zheng 	struct btrfs_inode_item *inode_item;
11736ab6ebb7SNaohiro Aota 	int ret;
11747237f183SYan Zheng 
11750b246afaSJeff Mahoney 	log_root = alloc_log_tree(trans, fs_info);
11767237f183SYan Zheng 	if (IS_ERR(log_root))
11777237f183SYan Zheng 		return PTR_ERR(log_root);
11787237f183SYan Zheng 
11796ab6ebb7SNaohiro Aota 	ret = btrfs_alloc_log_tree_node(trans, log_root);
11806ab6ebb7SNaohiro Aota 	if (ret) {
11816ab6ebb7SNaohiro Aota 		btrfs_put_root(log_root);
11826ab6ebb7SNaohiro Aota 		return ret;
11836ab6ebb7SNaohiro Aota 	}
11846ab6ebb7SNaohiro Aota 
11857237f183SYan Zheng 	log_root->last_trans = trans->transid;
11867237f183SYan Zheng 	log_root->root_key.offset = root->root_key.objectid;
11877237f183SYan Zheng 
11887237f183SYan Zheng 	inode_item = &log_root->root_item.inode;
11893cae210fSQu Wenruo 	btrfs_set_stack_inode_generation(inode_item, 1);
11903cae210fSQu Wenruo 	btrfs_set_stack_inode_size(inode_item, 3);
11913cae210fSQu Wenruo 	btrfs_set_stack_inode_nlink(inode_item, 1);
1192da17066cSJeff Mahoney 	btrfs_set_stack_inode_nbytes(inode_item,
11930b246afaSJeff Mahoney 				     fs_info->nodesize);
11943cae210fSQu Wenruo 	btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
11957237f183SYan Zheng 
11965d4f98a2SYan Zheng 	btrfs_set_root_node(&log_root->root_item, log_root->node);
11977237f183SYan Zheng 
11987237f183SYan Zheng 	WARN_ON(root->log_root);
11997237f183SYan Zheng 	root->log_root = log_root;
12007237f183SYan Zheng 	root->log_transid = 0;
1201d1433debSMiao Xie 	root->log_transid_committed = -1;
1202257c62e1SChris Mason 	root->last_log_commit = 0;
1203e02119d5SChris Mason 	return 0;
1204e02119d5SChris Mason }
1205e02119d5SChris Mason 
120649d11beaSJosef Bacik static struct btrfs_root *read_tree_root_path(struct btrfs_root *tree_root,
120749d11beaSJosef Bacik 					      struct btrfs_path *path,
1208cb517eabSMiao Xie 					      struct btrfs_key *key)
1209e02119d5SChris Mason {
1210e02119d5SChris Mason 	struct btrfs_root *root;
1211789d6a3aSQu Wenruo 	struct btrfs_tree_parent_check check = { 0 };
1212e02119d5SChris Mason 	struct btrfs_fs_info *fs_info = tree_root->fs_info;
121384234f3aSYan Zheng 	u64 generation;
1214cb517eabSMiao Xie 	int ret;
1215581c1760SQu Wenruo 	int level;
1216cb517eabSMiao Xie 
121796dfcb46SJosef Bacik 	root = btrfs_alloc_root(fs_info, key->objectid, GFP_NOFS);
121849d11beaSJosef Bacik 	if (!root)
121949d11beaSJosef Bacik 		return ERR_PTR(-ENOMEM);
12200f7d52f4SChris Mason 
1221cb517eabSMiao Xie 	ret = btrfs_find_root(tree_root, key, path,
1222cb517eabSMiao Xie 			      &root->root_item, &root->root_key);
12230f7d52f4SChris Mason 	if (ret) {
122413a8a7c8SYan, Zheng 		if (ret > 0)
122513a8a7c8SYan, Zheng 			ret = -ENOENT;
122649d11beaSJosef Bacik 		goto fail;
12270f7d52f4SChris Mason 	}
122813a8a7c8SYan, Zheng 
122984234f3aSYan Zheng 	generation = btrfs_root_generation(&root->root_item);
1230581c1760SQu Wenruo 	level = btrfs_root_level(&root->root_item);
1231789d6a3aSQu Wenruo 	check.level = level;
1232789d6a3aSQu Wenruo 	check.transid = generation;
1233789d6a3aSQu Wenruo 	check.owner_root = key->objectid;
1234789d6a3aSQu Wenruo 	root->node = read_tree_block(fs_info, btrfs_root_bytenr(&root->root_item),
1235789d6a3aSQu Wenruo 				     &check);
123664c043deSLiu Bo 	if (IS_ERR(root->node)) {
123764c043deSLiu Bo 		ret = PTR_ERR(root->node);
12388c38938cSJosef Bacik 		root->node = NULL;
123949d11beaSJosef Bacik 		goto fail;
12404eb150d6SQu Wenruo 	}
12414eb150d6SQu Wenruo 	if (!btrfs_buffer_uptodate(root->node, generation, 0)) {
1242cb517eabSMiao Xie 		ret = -EIO;
124349d11beaSJosef Bacik 		goto fail;
1244416bc658SJosef Bacik 	}
124588c602abSQu Wenruo 
124688c602abSQu Wenruo 	/*
124788c602abSQu Wenruo 	 * For real fs, and not log/reloc trees, root owner must
124888c602abSQu Wenruo 	 * match its root node owner
124988c602abSQu Wenruo 	 */
125088c602abSQu Wenruo 	if (!test_bit(BTRFS_FS_STATE_DUMMY_FS_INFO, &fs_info->fs_state) &&
125188c602abSQu Wenruo 	    root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID &&
125288c602abSQu Wenruo 	    root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
125388c602abSQu Wenruo 	    root->root_key.objectid != btrfs_header_owner(root->node)) {
125488c602abSQu Wenruo 		btrfs_crit(fs_info,
125588c602abSQu Wenruo "root=%llu block=%llu, tree root owner mismatch, have %llu expect %llu",
125688c602abSQu Wenruo 			   root->root_key.objectid, root->node->start,
125788c602abSQu Wenruo 			   btrfs_header_owner(root->node),
125888c602abSQu Wenruo 			   root->root_key.objectid);
125988c602abSQu Wenruo 		ret = -EUCLEAN;
126088c602abSQu Wenruo 		goto fail;
126188c602abSQu Wenruo 	}
12625d4f98a2SYan Zheng 	root->commit_root = btrfs_root_node(root);
1263cb517eabSMiao Xie 	return root;
126449d11beaSJosef Bacik fail:
126500246528SJosef Bacik 	btrfs_put_root(root);
126649d11beaSJosef Bacik 	return ERR_PTR(ret);
126749d11beaSJosef Bacik }
126849d11beaSJosef Bacik 
126949d11beaSJosef Bacik struct btrfs_root *btrfs_read_tree_root(struct btrfs_root *tree_root,
127049d11beaSJosef Bacik 					struct btrfs_key *key)
127149d11beaSJosef Bacik {
127249d11beaSJosef Bacik 	struct btrfs_root *root;
127349d11beaSJosef Bacik 	struct btrfs_path *path;
127449d11beaSJosef Bacik 
127549d11beaSJosef Bacik 	path = btrfs_alloc_path();
127649d11beaSJosef Bacik 	if (!path)
127749d11beaSJosef Bacik 		return ERR_PTR(-ENOMEM);
127849d11beaSJosef Bacik 	root = read_tree_root_path(tree_root, path, key);
127949d11beaSJosef Bacik 	btrfs_free_path(path);
128049d11beaSJosef Bacik 
128149d11beaSJosef Bacik 	return root;
1282cb517eabSMiao Xie }
1283cb517eabSMiao Xie 
12842dfb1e43SQu Wenruo /*
12852dfb1e43SQu Wenruo  * Initialize subvolume root in-memory structure
12862dfb1e43SQu Wenruo  *
12872dfb1e43SQu Wenruo  * @anon_dev:	anonymous device to attach to the root, if zero, allocate new
12882dfb1e43SQu Wenruo  */
12892dfb1e43SQu Wenruo static int btrfs_init_fs_root(struct btrfs_root *root, dev_t anon_dev)
1290cb517eabSMiao Xie {
1291cb517eabSMiao Xie 	int ret;
1292cb517eabSMiao Xie 
12930b548539SDavid Sterba 	btrfs_drew_lock_init(&root->snapshot_lock);
12948257b2dcSMiao Xie 
1295aeb935a4SQu Wenruo 	if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID &&
129637f00a6dSJohannes Thumshirn 	    !btrfs_is_data_reloc_root(root)) {
129792a7cc42SQu Wenruo 		set_bit(BTRFS_ROOT_SHAREABLE, &root->state);
1298f39e4571SJosef Bacik 		btrfs_check_and_init_root_item(&root->root_item);
1299f39e4571SJosef Bacik 	}
1300f39e4571SJosef Bacik 
1301851fd730SQu Wenruo 	/*
1302851fd730SQu Wenruo 	 * Don't assign anonymous block device to roots that are not exposed to
1303851fd730SQu Wenruo 	 * userspace, the id pool is limited to 1M
1304851fd730SQu Wenruo 	 */
1305851fd730SQu Wenruo 	if (is_fstree(root->root_key.objectid) &&
1306851fd730SQu Wenruo 	    btrfs_root_refs(&root->root_item) > 0) {
13072dfb1e43SQu Wenruo 		if (!anon_dev) {
1308cb517eabSMiao Xie 			ret = get_anon_bdev(&root->anon_dev);
1309cb517eabSMiao Xie 			if (ret)
1310876d2cf1SLiu Bo 				goto fail;
13112dfb1e43SQu Wenruo 		} else {
13122dfb1e43SQu Wenruo 			root->anon_dev = anon_dev;
13132dfb1e43SQu Wenruo 		}
1314851fd730SQu Wenruo 	}
1315f32e48e9SChandan Rajendra 
1316f32e48e9SChandan Rajendra 	mutex_lock(&root->objectid_mutex);
1317453e4873SNikolay Borisov 	ret = btrfs_init_root_free_objectid(root);
1318f32e48e9SChandan Rajendra 	if (ret) {
1319f32e48e9SChandan Rajendra 		mutex_unlock(&root->objectid_mutex);
1320876d2cf1SLiu Bo 		goto fail;
1321f32e48e9SChandan Rajendra 	}
1322f32e48e9SChandan Rajendra 
13236b8fad57SNikolay Borisov 	ASSERT(root->free_objectid <= BTRFS_LAST_FREE_OBJECTID);
1324f32e48e9SChandan Rajendra 
1325f32e48e9SChandan Rajendra 	mutex_unlock(&root->objectid_mutex);
1326f32e48e9SChandan Rajendra 
1327cb517eabSMiao Xie 	return 0;
1328cb517eabSMiao Xie fail:
132984db5ccfSDavid Sterba 	/* The caller is responsible to call btrfs_free_fs_root */
1330cb517eabSMiao Xie 	return ret;
1331cb517eabSMiao Xie }
1332cb517eabSMiao Xie 
1333a98db0f3SJosef Bacik static struct btrfs_root *btrfs_lookup_fs_root(struct btrfs_fs_info *fs_info,
1334cb517eabSMiao Xie 					       u64 root_id)
1335cb517eabSMiao Xie {
1336cb517eabSMiao Xie 	struct btrfs_root *root;
1337cb517eabSMiao Xie 
1338fc7cbcd4SDavid Sterba 	spin_lock(&fs_info->fs_roots_radix_lock);
1339fc7cbcd4SDavid Sterba 	root = radix_tree_lookup(&fs_info->fs_roots_radix,
1340fc7cbcd4SDavid Sterba 				 (unsigned long)root_id);
1341bc44d7c4SJosef Bacik 	if (root)
134200246528SJosef Bacik 		root = btrfs_grab_root(root);
1343fc7cbcd4SDavid Sterba 	spin_unlock(&fs_info->fs_roots_radix_lock);
1344cb517eabSMiao Xie 	return root;
1345cb517eabSMiao Xie }
1346cb517eabSMiao Xie 
134749d11beaSJosef Bacik static struct btrfs_root *btrfs_get_global_root(struct btrfs_fs_info *fs_info,
134849d11beaSJosef Bacik 						u64 objectid)
134949d11beaSJosef Bacik {
1350abed4aaaSJosef Bacik 	struct btrfs_key key = {
1351abed4aaaSJosef Bacik 		.objectid = objectid,
1352abed4aaaSJosef Bacik 		.type = BTRFS_ROOT_ITEM_KEY,
1353abed4aaaSJosef Bacik 		.offset = 0,
1354abed4aaaSJosef Bacik 	};
1355abed4aaaSJosef Bacik 
135649d11beaSJosef Bacik 	if (objectid == BTRFS_ROOT_TREE_OBJECTID)
135749d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->tree_root);
135849d11beaSJosef Bacik 	if (objectid == BTRFS_EXTENT_TREE_OBJECTID)
1359abed4aaaSJosef Bacik 		return btrfs_grab_root(btrfs_global_root(fs_info, &key));
136049d11beaSJosef Bacik 	if (objectid == BTRFS_CHUNK_TREE_OBJECTID)
136149d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->chunk_root);
136249d11beaSJosef Bacik 	if (objectid == BTRFS_DEV_TREE_OBJECTID)
136349d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->dev_root);
136449d11beaSJosef Bacik 	if (objectid == BTRFS_CSUM_TREE_OBJECTID)
1365abed4aaaSJosef Bacik 		return btrfs_grab_root(btrfs_global_root(fs_info, &key));
136649d11beaSJosef Bacik 	if (objectid == BTRFS_QUOTA_TREE_OBJECTID)
136749d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->quota_root) ?
136849d11beaSJosef Bacik 			fs_info->quota_root : ERR_PTR(-ENOENT);
136949d11beaSJosef Bacik 	if (objectid == BTRFS_UUID_TREE_OBJECTID)
137049d11beaSJosef Bacik 		return btrfs_grab_root(fs_info->uuid_root) ?
137149d11beaSJosef Bacik 			fs_info->uuid_root : ERR_PTR(-ENOENT);
137214033b08SQu Wenruo 	if (objectid == BTRFS_BLOCK_GROUP_TREE_OBJECTID)
137314033b08SQu Wenruo 		return btrfs_grab_root(fs_info->block_group_root) ?
137414033b08SQu Wenruo 			fs_info->block_group_root : ERR_PTR(-ENOENT);
1375abed4aaaSJosef Bacik 	if (objectid == BTRFS_FREE_SPACE_TREE_OBJECTID) {
1376abed4aaaSJosef Bacik 		struct btrfs_root *root = btrfs_global_root(fs_info, &key);
1377abed4aaaSJosef Bacik 
1378abed4aaaSJosef Bacik 		return btrfs_grab_root(root) ? root : ERR_PTR(-ENOENT);
1379abed4aaaSJosef Bacik 	}
138049d11beaSJosef Bacik 	return NULL;
138149d11beaSJosef Bacik }
138249d11beaSJosef Bacik 
1383cb517eabSMiao Xie int btrfs_insert_fs_root(struct btrfs_fs_info *fs_info,
1384cb517eabSMiao Xie 			 struct btrfs_root *root)
1385cb517eabSMiao Xie {
1386cb517eabSMiao Xie 	int ret;
1387cb517eabSMiao Xie 
1388fc7cbcd4SDavid Sterba 	ret = radix_tree_preload(GFP_NOFS);
1389fc7cbcd4SDavid Sterba 	if (ret)
1390fc7cbcd4SDavid Sterba 		return ret;
1391fc7cbcd4SDavid Sterba 
1392fc7cbcd4SDavid Sterba 	spin_lock(&fs_info->fs_roots_radix_lock);
1393fc7cbcd4SDavid Sterba 	ret = radix_tree_insert(&fs_info->fs_roots_radix,
1394fc7cbcd4SDavid Sterba 				(unsigned long)root->root_key.objectid,
1395fc7cbcd4SDavid Sterba 				root);
1396af01d2e5SJosef Bacik 	if (ret == 0) {
139700246528SJosef Bacik 		btrfs_grab_root(root);
1398fc7cbcd4SDavid Sterba 		set_bit(BTRFS_ROOT_IN_RADIX, &root->state);
1399af01d2e5SJosef Bacik 	}
1400fc7cbcd4SDavid Sterba 	spin_unlock(&fs_info->fs_roots_radix_lock);
1401fc7cbcd4SDavid Sterba 	radix_tree_preload_end();
1402cb517eabSMiao Xie 
1403cb517eabSMiao Xie 	return ret;
1404cb517eabSMiao Xie }
1405cb517eabSMiao Xie 
1406bd647ce3SJosef Bacik void btrfs_check_leaked_roots(struct btrfs_fs_info *fs_info)
1407bd647ce3SJosef Bacik {
1408bd647ce3SJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
1409bd647ce3SJosef Bacik 	struct btrfs_root *root;
1410bd647ce3SJosef Bacik 
1411bd647ce3SJosef Bacik 	while (!list_empty(&fs_info->allocated_roots)) {
1412457f1864SJosef Bacik 		char buf[BTRFS_ROOT_NAME_BUF_LEN];
1413457f1864SJosef Bacik 
1414bd647ce3SJosef Bacik 		root = list_first_entry(&fs_info->allocated_roots,
1415bd647ce3SJosef Bacik 					struct btrfs_root, leak_list);
1416457f1864SJosef Bacik 		btrfs_err(fs_info, "leaked root %s refcount %d",
141771008734SJosef Bacik 			  btrfs_root_name(&root->root_key, buf),
1418bd647ce3SJosef Bacik 			  refcount_read(&root->refs));
1419bd647ce3SJosef Bacik 		while (refcount_read(&root->refs) > 1)
142000246528SJosef Bacik 			btrfs_put_root(root);
142100246528SJosef Bacik 		btrfs_put_root(root);
1422bd647ce3SJosef Bacik 	}
1423bd647ce3SJosef Bacik #endif
1424bd647ce3SJosef Bacik }
1425bd647ce3SJosef Bacik 
1426abed4aaaSJosef Bacik static void free_global_roots(struct btrfs_fs_info *fs_info)
1427abed4aaaSJosef Bacik {
1428abed4aaaSJosef Bacik 	struct btrfs_root *root;
1429abed4aaaSJosef Bacik 	struct rb_node *node;
1430abed4aaaSJosef Bacik 
1431abed4aaaSJosef Bacik 	while ((node = rb_first_postorder(&fs_info->global_root_tree)) != NULL) {
1432abed4aaaSJosef Bacik 		root = rb_entry(node, struct btrfs_root, rb_node);
1433abed4aaaSJosef Bacik 		rb_erase(&root->rb_node, &fs_info->global_root_tree);
1434abed4aaaSJosef Bacik 		btrfs_put_root(root);
1435abed4aaaSJosef Bacik 	}
1436abed4aaaSJosef Bacik }
1437abed4aaaSJosef Bacik 
14380d4b0463SJosef Bacik void btrfs_free_fs_info(struct btrfs_fs_info *fs_info)
14390d4b0463SJosef Bacik {
1440141386e1SJosef Bacik 	percpu_counter_destroy(&fs_info->dirty_metadata_bytes);
1441141386e1SJosef Bacik 	percpu_counter_destroy(&fs_info->delalloc_bytes);
14425deb17e1SJosef Bacik 	percpu_counter_destroy(&fs_info->ordered_bytes);
1443141386e1SJosef Bacik 	percpu_counter_destroy(&fs_info->dev_replace.bio_counter);
1444141386e1SJosef Bacik 	btrfs_free_csum_hash(fs_info);
1445141386e1SJosef Bacik 	btrfs_free_stripe_hash_table(fs_info);
1446141386e1SJosef Bacik 	btrfs_free_ref_cache(fs_info);
14470d4b0463SJosef Bacik 	kfree(fs_info->balance_ctl);
14480d4b0463SJosef Bacik 	kfree(fs_info->delayed_root);
1449abed4aaaSJosef Bacik 	free_global_roots(fs_info);
145000246528SJosef Bacik 	btrfs_put_root(fs_info->tree_root);
145100246528SJosef Bacik 	btrfs_put_root(fs_info->chunk_root);
145200246528SJosef Bacik 	btrfs_put_root(fs_info->dev_root);
145300246528SJosef Bacik 	btrfs_put_root(fs_info->quota_root);
145400246528SJosef Bacik 	btrfs_put_root(fs_info->uuid_root);
145500246528SJosef Bacik 	btrfs_put_root(fs_info->fs_root);
1456aeb935a4SQu Wenruo 	btrfs_put_root(fs_info->data_reloc_root);
14579c54e80dSJosef Bacik 	btrfs_put_root(fs_info->block_group_root);
1458bd647ce3SJosef Bacik 	btrfs_check_leaked_roots(fs_info);
14593fd63727SJosef Bacik 	btrfs_extent_buffer_leak_debug_check(fs_info);
14600d4b0463SJosef Bacik 	kfree(fs_info->super_copy);
14610d4b0463SJosef Bacik 	kfree(fs_info->super_for_commit);
14628481dd80SQu Wenruo 	kfree(fs_info->subpage_info);
14630d4b0463SJosef Bacik 	kvfree(fs_info);
14640d4b0463SJosef Bacik }
14650d4b0463SJosef Bacik 
14660d4b0463SJosef Bacik 
14672dfb1e43SQu Wenruo /*
14682dfb1e43SQu Wenruo  * Get an in-memory reference of a root structure.
14692dfb1e43SQu Wenruo  *
14702dfb1e43SQu Wenruo  * For essential trees like root/extent tree, we grab it from fs_info directly.
14712dfb1e43SQu Wenruo  * For subvolume trees, we check the cached filesystem roots first. If not
14722dfb1e43SQu Wenruo  * found, then read it from disk and add it to cached fs roots.
14732dfb1e43SQu Wenruo  *
14742dfb1e43SQu Wenruo  * Caller should release the root by calling btrfs_put_root() after the usage.
14752dfb1e43SQu Wenruo  *
14762dfb1e43SQu Wenruo  * NOTE: Reloc and log trees can't be read by this function as they share the
14772dfb1e43SQu Wenruo  *	 same root objectid.
14782dfb1e43SQu Wenruo  *
14792dfb1e43SQu Wenruo  * @objectid:	root id
14802dfb1e43SQu Wenruo  * @anon_dev:	preallocated anonymous block device number for new roots,
14812dfb1e43SQu Wenruo  * 		pass 0 for new allocation.
14822dfb1e43SQu Wenruo  * @check_ref:	whether to check root item references, If true, return -ENOENT
14832dfb1e43SQu Wenruo  *		for orphan roots
14842dfb1e43SQu Wenruo  */
14852dfb1e43SQu Wenruo static struct btrfs_root *btrfs_get_root_ref(struct btrfs_fs_info *fs_info,
14862dfb1e43SQu Wenruo 					     u64 objectid, dev_t anon_dev,
14872dfb1e43SQu Wenruo 					     bool check_ref)
14885eda7b5eSChris Mason {
14895eda7b5eSChris Mason 	struct btrfs_root *root;
1490381cf658SDavid Sterba 	struct btrfs_path *path;
14911d4c08e0SDavid Sterba 	struct btrfs_key key;
14925eda7b5eSChris Mason 	int ret;
14935eda7b5eSChris Mason 
149449d11beaSJosef Bacik 	root = btrfs_get_global_root(fs_info, objectid);
149549d11beaSJosef Bacik 	if (root)
149649d11beaSJosef Bacik 		return root;
14974df27c4dSYan, Zheng again:
149856e9357aSDavid Sterba 	root = btrfs_lookup_fs_root(fs_info, objectid);
149948475471SStefan Behrens 	if (root) {
15002dfb1e43SQu Wenruo 		/* Shouldn't get preallocated anon_dev for cached roots */
15012dfb1e43SQu Wenruo 		ASSERT(!anon_dev);
1502bc44d7c4SJosef Bacik 		if (check_ref && btrfs_root_refs(&root->root_item) == 0) {
150300246528SJosef Bacik 			btrfs_put_root(root);
150448475471SStefan Behrens 			return ERR_PTR(-ENOENT);
1505bc44d7c4SJosef Bacik 		}
15065eda7b5eSChris Mason 		return root;
150748475471SStefan Behrens 	}
15085eda7b5eSChris Mason 
150956e9357aSDavid Sterba 	key.objectid = objectid;
151056e9357aSDavid Sterba 	key.type = BTRFS_ROOT_ITEM_KEY;
151156e9357aSDavid Sterba 	key.offset = (u64)-1;
151256e9357aSDavid Sterba 	root = btrfs_read_tree_root(fs_info->tree_root, &key);
15135eda7b5eSChris Mason 	if (IS_ERR(root))
15145eda7b5eSChris Mason 		return root;
15153394e160SChris Mason 
1516c00869f1SMiao Xie 	if (check_ref && btrfs_root_refs(&root->root_item) == 0) {
1517d68fc57bSYan, Zheng 		ret = -ENOENT;
1518d68fc57bSYan, Zheng 		goto fail;
1519d68fc57bSYan, Zheng 	}
1520d68fc57bSYan, Zheng 
15212dfb1e43SQu Wenruo 	ret = btrfs_init_fs_root(root, anon_dev);
1522cb517eabSMiao Xie 	if (ret)
1523cb517eabSMiao Xie 		goto fail;
1524cb517eabSMiao Xie 
1525381cf658SDavid Sterba 	path = btrfs_alloc_path();
1526381cf658SDavid Sterba 	if (!path) {
1527381cf658SDavid Sterba 		ret = -ENOMEM;
1528381cf658SDavid Sterba 		goto fail;
1529381cf658SDavid Sterba 	}
15301d4c08e0SDavid Sterba 	key.objectid = BTRFS_ORPHAN_OBJECTID;
15311d4c08e0SDavid Sterba 	key.type = BTRFS_ORPHAN_ITEM_KEY;
153256e9357aSDavid Sterba 	key.offset = objectid;
15331d4c08e0SDavid Sterba 
15341d4c08e0SDavid Sterba 	ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
1535381cf658SDavid Sterba 	btrfs_free_path(path);
1536d68fc57bSYan, Zheng 	if (ret < 0)
1537d68fc57bSYan, Zheng 		goto fail;
1538d68fc57bSYan, Zheng 	if (ret == 0)
153927cdeb70SMiao Xie 		set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state);
1540d68fc57bSYan, Zheng 
1541cb517eabSMiao Xie 	ret = btrfs_insert_fs_root(fs_info, root);
15420f7d52f4SChris Mason 	if (ret) {
1543168a2f77SJia-Ju Bai 		if (ret == -EEXIST) {
154400246528SJosef Bacik 			btrfs_put_root(root);
15454df27c4dSYan, Zheng 			goto again;
1546168a2f77SJia-Ju Bai 		}
15474df27c4dSYan, Zheng 		goto fail;
15484df27c4dSYan, Zheng 	}
1549edbd8d4eSChris Mason 	return root;
15504df27c4dSYan, Zheng fail:
155133fab972SFilipe Manana 	/*
155233fab972SFilipe Manana 	 * If our caller provided us an anonymous device, then it's his
1553143823cfSDavid Sterba 	 * responsibility to free it in case we fail. So we have to set our
155433fab972SFilipe Manana 	 * root's anon_dev to 0 to avoid a double free, once by btrfs_put_root()
155533fab972SFilipe Manana 	 * and once again by our caller.
155633fab972SFilipe Manana 	 */
155733fab972SFilipe Manana 	if (anon_dev)
155833fab972SFilipe Manana 		root->anon_dev = 0;
15598c38938cSJosef Bacik 	btrfs_put_root(root);
15604df27c4dSYan, Zheng 	return ERR_PTR(ret);
1561edbd8d4eSChris Mason }
1562edbd8d4eSChris Mason 
15632dfb1e43SQu Wenruo /*
15642dfb1e43SQu Wenruo  * Get in-memory reference of a root structure
15652dfb1e43SQu Wenruo  *
15662dfb1e43SQu Wenruo  * @objectid:	tree objectid
15672dfb1e43SQu Wenruo  * @check_ref:	if set, verify that the tree exists and the item has at least
15682dfb1e43SQu Wenruo  *		one reference
15692dfb1e43SQu Wenruo  */
15702dfb1e43SQu Wenruo struct btrfs_root *btrfs_get_fs_root(struct btrfs_fs_info *fs_info,
15712dfb1e43SQu Wenruo 				     u64 objectid, bool check_ref)
15722dfb1e43SQu Wenruo {
15732dfb1e43SQu Wenruo 	return btrfs_get_root_ref(fs_info, objectid, 0, check_ref);
15742dfb1e43SQu Wenruo }
15752dfb1e43SQu Wenruo 
15762dfb1e43SQu Wenruo /*
15772dfb1e43SQu Wenruo  * Get in-memory reference of a root structure, created as new, optionally pass
15782dfb1e43SQu Wenruo  * the anonymous block device id
15792dfb1e43SQu Wenruo  *
15802dfb1e43SQu Wenruo  * @objectid:	tree objectid
15812dfb1e43SQu Wenruo  * @anon_dev:	if zero, allocate a new anonymous block device or use the
15822dfb1e43SQu Wenruo  *		parameter value
15832dfb1e43SQu Wenruo  */
15842dfb1e43SQu Wenruo struct btrfs_root *btrfs_get_new_fs_root(struct btrfs_fs_info *fs_info,
15852dfb1e43SQu Wenruo 					 u64 objectid, dev_t anon_dev)
15862dfb1e43SQu Wenruo {
15872dfb1e43SQu Wenruo 	return btrfs_get_root_ref(fs_info, objectid, anon_dev, true);
15882dfb1e43SQu Wenruo }
15892dfb1e43SQu Wenruo 
15908b712842SChris Mason /*
159149d11beaSJosef Bacik  * btrfs_get_fs_root_commit_root - return a root for the given objectid
159249d11beaSJosef Bacik  * @fs_info:	the fs_info
159349d11beaSJosef Bacik  * @objectid:	the objectid we need to lookup
159449d11beaSJosef Bacik  *
159549d11beaSJosef Bacik  * This is exclusively used for backref walking, and exists specifically because
159649d11beaSJosef Bacik  * of how qgroups does lookups.  Qgroups will do a backref lookup at delayed ref
159749d11beaSJosef Bacik  * creation time, which means we may have to read the tree_root in order to look
159849d11beaSJosef Bacik  * up a fs root that is not in memory.  If the root is not in memory we will
159949d11beaSJosef Bacik  * read the tree root commit root and look up the fs root from there.  This is a
160049d11beaSJosef Bacik  * temporary root, it will not be inserted into the radix tree as it doesn't
160149d11beaSJosef Bacik  * have the most uptodate information, it'll simply be discarded once the
160249d11beaSJosef Bacik  * backref code is finished using the root.
160349d11beaSJosef Bacik  */
160449d11beaSJosef Bacik struct btrfs_root *btrfs_get_fs_root_commit_root(struct btrfs_fs_info *fs_info,
160549d11beaSJosef Bacik 						 struct btrfs_path *path,
160649d11beaSJosef Bacik 						 u64 objectid)
160749d11beaSJosef Bacik {
160849d11beaSJosef Bacik 	struct btrfs_root *root;
160949d11beaSJosef Bacik 	struct btrfs_key key;
161049d11beaSJosef Bacik 
161149d11beaSJosef Bacik 	ASSERT(path->search_commit_root && path->skip_locking);
161249d11beaSJosef Bacik 
161349d11beaSJosef Bacik 	/*
161449d11beaSJosef Bacik 	 * This can return -ENOENT if we ask for a root that doesn't exist, but
161549d11beaSJosef Bacik 	 * since this is called via the backref walking code we won't be looking
161649d11beaSJosef Bacik 	 * up a root that doesn't exist, unless there's corruption.  So if root
161749d11beaSJosef Bacik 	 * != NULL just return it.
161849d11beaSJosef Bacik 	 */
161949d11beaSJosef Bacik 	root = btrfs_get_global_root(fs_info, objectid);
162049d11beaSJosef Bacik 	if (root)
162149d11beaSJosef Bacik 		return root;
162249d11beaSJosef Bacik 
162349d11beaSJosef Bacik 	root = btrfs_lookup_fs_root(fs_info, objectid);
162449d11beaSJosef Bacik 	if (root)
162549d11beaSJosef Bacik 		return root;
162649d11beaSJosef Bacik 
162749d11beaSJosef Bacik 	key.objectid = objectid;
162849d11beaSJosef Bacik 	key.type = BTRFS_ROOT_ITEM_KEY;
162949d11beaSJosef Bacik 	key.offset = (u64)-1;
163049d11beaSJosef Bacik 	root = read_tree_root_path(fs_info->tree_root, path, &key);
163149d11beaSJosef Bacik 	btrfs_release_path(path);
163249d11beaSJosef Bacik 
163349d11beaSJosef Bacik 	return root;
163449d11beaSJosef Bacik }
163549d11beaSJosef Bacik 
1636a74a4b97SChris Mason static int cleaner_kthread(void *arg)
1637a74a4b97SChris Mason {
16380d031dc4SYu Zhe 	struct btrfs_fs_info *fs_info = arg;
1639d0278245SMiao Xie 	int again;
1640a74a4b97SChris Mason 
1641d6fd0ae2SOmar Sandoval 	while (1) {
1642d0278245SMiao Xie 		again = 0;
16439d1a2a3aSDavid Sterba 
1644fd340d0fSJosef Bacik 		set_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags);
1645fd340d0fSJosef Bacik 
1646d0278245SMiao Xie 		/* Make the cleaner go to sleep early. */
16472ff7e61eSJeff Mahoney 		if (btrfs_need_cleaner_sleep(fs_info))
1648d0278245SMiao Xie 			goto sleep;
1649d0278245SMiao Xie 
165090c711abSZygo Blaxell 		/*
165190c711abSZygo Blaxell 		 * Do not do anything if we might cause open_ctree() to block
165290c711abSZygo Blaxell 		 * before we have finished mounting the filesystem.
165390c711abSZygo Blaxell 		 */
16540b246afaSJeff Mahoney 		if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
165590c711abSZygo Blaxell 			goto sleep;
165690c711abSZygo Blaxell 
16570b246afaSJeff Mahoney 		if (!mutex_trylock(&fs_info->cleaner_mutex))
1658d0278245SMiao Xie 			goto sleep;
1659d0278245SMiao Xie 
1660dc7f370cSMiao Xie 		/*
1661dc7f370cSMiao Xie 		 * Avoid the problem that we change the status of the fs
1662dc7f370cSMiao Xie 		 * during the above check and trylock.
1663dc7f370cSMiao Xie 		 */
16642ff7e61eSJeff Mahoney 		if (btrfs_need_cleaner_sleep(fs_info)) {
16650b246afaSJeff Mahoney 			mutex_unlock(&fs_info->cleaner_mutex);
1666dc7f370cSMiao Xie 			goto sleep;
1667dc7f370cSMiao Xie 		}
1668dc7f370cSMiao Xie 
1669b7625f46SQu Wenruo 		if (test_and_clear_bit(BTRFS_FS_FEATURE_CHANGED, &fs_info->flags))
1670b7625f46SQu Wenruo 			btrfs_sysfs_feature_update(fs_info);
1671b7625f46SQu Wenruo 
16722ff7e61eSJeff Mahoney 		btrfs_run_delayed_iputs(fs_info);
1673c2d6cb16SFilipe Manana 
167433c44184SJosef Bacik 		again = btrfs_clean_one_deleted_snapshot(fs_info);
16750b246afaSJeff Mahoney 		mutex_unlock(&fs_info->cleaner_mutex);
1676a74a4b97SChris Mason 
1677d0278245SMiao Xie 		/*
167805323cd1SMiao Xie 		 * The defragger has dealt with the R/O remount and umount,
167905323cd1SMiao Xie 		 * needn't do anything special here.
1680d0278245SMiao Xie 		 */
16810b246afaSJeff Mahoney 		btrfs_run_defrag_inodes(fs_info);
168267c5e7d4SFilipe Manana 
168367c5e7d4SFilipe Manana 		/*
1684f3372065SJohannes Thumshirn 		 * Acquires fs_info->reclaim_bgs_lock to avoid racing
168567c5e7d4SFilipe Manana 		 * with relocation (btrfs_relocate_chunk) and relocation
168667c5e7d4SFilipe Manana 		 * acquires fs_info->cleaner_mutex (btrfs_relocate_block_group)
1687f3372065SJohannes Thumshirn 		 * after acquiring fs_info->reclaim_bgs_lock. So we
168867c5e7d4SFilipe Manana 		 * can't hold, nor need to, fs_info->cleaner_mutex when deleting
168967c5e7d4SFilipe Manana 		 * unused block groups.
169067c5e7d4SFilipe Manana 		 */
16910b246afaSJeff Mahoney 		btrfs_delete_unused_bgs(fs_info);
169218bb8bbfSJohannes Thumshirn 
169318bb8bbfSJohannes Thumshirn 		/*
169418bb8bbfSJohannes Thumshirn 		 * Reclaim block groups in the reclaim_bgs list after we deleted
169518bb8bbfSJohannes Thumshirn 		 * all unused block_groups. This possibly gives us some more free
169618bb8bbfSJohannes Thumshirn 		 * space.
169718bb8bbfSJohannes Thumshirn 		 */
169818bb8bbfSJohannes Thumshirn 		btrfs_reclaim_bgs(fs_info);
1699d0278245SMiao Xie sleep:
1700a0a1db70SFilipe Manana 		clear_and_wake_up_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags);
1701d6fd0ae2SOmar Sandoval 		if (kthread_should_park())
1702d6fd0ae2SOmar Sandoval 			kthread_parkme();
1703d6fd0ae2SOmar Sandoval 		if (kthread_should_stop())
1704d6fd0ae2SOmar Sandoval 			return 0;
1705838fe188SJiri Kosina 		if (!again) {
1706a74a4b97SChris Mason 			set_current_state(TASK_INTERRUPTIBLE);
1707a74a4b97SChris Mason 			schedule();
1708a74a4b97SChris Mason 			__set_current_state(TASK_RUNNING);
1709a74a4b97SChris Mason 		}
1710da288d28SFilipe Manana 	}
1711a74a4b97SChris Mason }
1712a74a4b97SChris Mason 
1713a74a4b97SChris Mason static int transaction_kthread(void *arg)
1714a74a4b97SChris Mason {
1715a74a4b97SChris Mason 	struct btrfs_root *root = arg;
17160b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
1717a74a4b97SChris Mason 	struct btrfs_trans_handle *trans;
1718a74a4b97SChris Mason 	struct btrfs_transaction *cur;
17198929ecfaSYan, Zheng 	u64 transid;
1720643900beSNikolay Borisov 	time64_t delta;
1721a74a4b97SChris Mason 	unsigned long delay;
1722914b2007SJan Kara 	bool cannot_commit;
1723a74a4b97SChris Mason 
1724a74a4b97SChris Mason 	do {
1725914b2007SJan Kara 		cannot_commit = false;
1726ba1bc00fSNikolay Borisov 		delay = msecs_to_jiffies(fs_info->commit_interval * 1000);
17270b246afaSJeff Mahoney 		mutex_lock(&fs_info->transaction_kthread_mutex);
1728a74a4b97SChris Mason 
17290b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
17300b246afaSJeff Mahoney 		cur = fs_info->running_transaction;
1731a74a4b97SChris Mason 		if (!cur) {
17320b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
1733a74a4b97SChris Mason 			goto sleep;
1734a74a4b97SChris Mason 		}
173531153d81SYan Zheng 
1736643900beSNikolay Borisov 		delta = ktime_get_seconds() - cur->start_time;
1737fdfbf020SJosef Bacik 		if (!test_and_clear_bit(BTRFS_FS_COMMIT_TRANS, &fs_info->flags) &&
1738fdfbf020SJosef Bacik 		    cur->state < TRANS_STATE_COMMIT_START &&
1739643900beSNikolay Borisov 		    delta < fs_info->commit_interval) {
17400b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
1741fb8a7e94SNikolay Borisov 			delay -= msecs_to_jiffies((delta - 1) * 1000);
1742fb8a7e94SNikolay Borisov 			delay = min(delay,
1743fb8a7e94SNikolay Borisov 				    msecs_to_jiffies(fs_info->commit_interval * 1000));
1744a74a4b97SChris Mason 			goto sleep;
1745a74a4b97SChris Mason 		}
17468929ecfaSYan, Zheng 		transid = cur->transid;
17470b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
174856bec294SChris Mason 
174979787eaaSJeff Mahoney 		/* If the file system is aborted, this will always fail. */
1750354aa0fbSMiao Xie 		trans = btrfs_attach_transaction(root);
1751914b2007SJan Kara 		if (IS_ERR(trans)) {
1752354aa0fbSMiao Xie 			if (PTR_ERR(trans) != -ENOENT)
1753914b2007SJan Kara 				cannot_commit = true;
175479787eaaSJeff Mahoney 			goto sleep;
1755914b2007SJan Kara 		}
17568929ecfaSYan, Zheng 		if (transid == trans->transid) {
17573a45bb20SJeff Mahoney 			btrfs_commit_transaction(trans);
17588929ecfaSYan, Zheng 		} else {
17593a45bb20SJeff Mahoney 			btrfs_end_transaction(trans);
17608929ecfaSYan, Zheng 		}
1761a74a4b97SChris Mason sleep:
17620b246afaSJeff Mahoney 		wake_up_process(fs_info->cleaner_kthread);
17630b246afaSJeff Mahoney 		mutex_unlock(&fs_info->transaction_kthread_mutex);
1764a74a4b97SChris Mason 
176584961539SJosef Bacik 		if (BTRFS_FS_ERROR(fs_info))
17662ff7e61eSJeff Mahoney 			btrfs_cleanup_transaction(fs_info);
17678929ecfaSYan, Zheng 		if (!kthread_should_stop() &&
17680b246afaSJeff Mahoney 				(!btrfs_transaction_blocked(fs_info) ||
1769914b2007SJan Kara 				 cannot_commit))
1770bc5511d0SNikolay Borisov 			schedule_timeout_interruptible(delay);
1771a74a4b97SChris Mason 	} while (!kthread_should_stop());
1772a74a4b97SChris Mason 	return 0;
1773a74a4b97SChris Mason }
1774a74a4b97SChris Mason 
1775af31f5e5SChris Mason /*
177601f0f9daSNikolay Borisov  * This will find the highest generation in the array of root backups.  The
177701f0f9daSNikolay Borisov  * index of the highest array is returned, or -EINVAL if we can't find
177801f0f9daSNikolay Borisov  * anything.
1779af31f5e5SChris Mason  *
1780af31f5e5SChris Mason  * We check to make sure the array is valid by comparing the
1781af31f5e5SChris Mason  * generation of the latest  root in the array with the generation
1782af31f5e5SChris Mason  * in the super block.  If they don't match we pitch it.
1783af31f5e5SChris Mason  */
178401f0f9daSNikolay Borisov static int find_newest_super_backup(struct btrfs_fs_info *info)
1785af31f5e5SChris Mason {
178601f0f9daSNikolay Borisov 	const u64 newest_gen = btrfs_super_generation(info->super_copy);
1787af31f5e5SChris Mason 	u64 cur;
1788af31f5e5SChris Mason 	struct btrfs_root_backup *root_backup;
1789af31f5e5SChris Mason 	int i;
1790af31f5e5SChris Mason 
1791af31f5e5SChris Mason 	for (i = 0; i < BTRFS_NUM_BACKUP_ROOTS; i++) {
1792af31f5e5SChris Mason 		root_backup = info->super_copy->super_roots + i;
1793af31f5e5SChris Mason 		cur = btrfs_backup_tree_root_gen(root_backup);
1794af31f5e5SChris Mason 		if (cur == newest_gen)
179501f0f9daSNikolay Borisov 			return i;
1796af31f5e5SChris Mason 	}
1797af31f5e5SChris Mason 
179801f0f9daSNikolay Borisov 	return -EINVAL;
1799af31f5e5SChris Mason }
1800af31f5e5SChris Mason 
1801af31f5e5SChris Mason /*
1802af31f5e5SChris Mason  * copy all the root pointers into the super backup array.
1803af31f5e5SChris Mason  * this will bump the backup pointer by one when it is
1804af31f5e5SChris Mason  * done
1805af31f5e5SChris Mason  */
1806af31f5e5SChris Mason static void backup_super_roots(struct btrfs_fs_info *info)
1807af31f5e5SChris Mason {
18086ef108ddSNikolay Borisov 	const int next_backup = info->backup_root_index;
1809af31f5e5SChris Mason 	struct btrfs_root_backup *root_backup;
1810af31f5e5SChris Mason 
1811af31f5e5SChris Mason 	root_backup = info->super_for_commit->super_roots + next_backup;
1812af31f5e5SChris Mason 
1813af31f5e5SChris Mason 	/*
1814af31f5e5SChris Mason 	 * make sure all of our padding and empty slots get zero filled
1815af31f5e5SChris Mason 	 * regardless of which ones we use today
1816af31f5e5SChris Mason 	 */
1817af31f5e5SChris Mason 	memset(root_backup, 0, sizeof(*root_backup));
1818af31f5e5SChris Mason 
1819af31f5e5SChris Mason 	info->backup_root_index = (next_backup + 1) % BTRFS_NUM_BACKUP_ROOTS;
1820af31f5e5SChris Mason 
1821af31f5e5SChris Mason 	btrfs_set_backup_tree_root(root_backup, info->tree_root->node->start);
1822af31f5e5SChris Mason 	btrfs_set_backup_tree_root_gen(root_backup,
1823af31f5e5SChris Mason 			       btrfs_header_generation(info->tree_root->node));
1824af31f5e5SChris Mason 
1825af31f5e5SChris Mason 	btrfs_set_backup_tree_root_level(root_backup,
1826af31f5e5SChris Mason 			       btrfs_header_level(info->tree_root->node));
1827af31f5e5SChris Mason 
1828af31f5e5SChris Mason 	btrfs_set_backup_chunk_root(root_backup, info->chunk_root->node->start);
1829af31f5e5SChris Mason 	btrfs_set_backup_chunk_root_gen(root_backup,
1830af31f5e5SChris Mason 			       btrfs_header_generation(info->chunk_root->node));
1831af31f5e5SChris Mason 	btrfs_set_backup_chunk_root_level(root_backup,
1832af31f5e5SChris Mason 			       btrfs_header_level(info->chunk_root->node));
1833af31f5e5SChris Mason 
18341c56ab99SQu Wenruo 	if (!btrfs_fs_compat_ro(info, BLOCK_GROUP_TREE)) {
18359c54e80dSJosef Bacik 		struct btrfs_root *extent_root = btrfs_extent_root(info, 0);
1836f7238e50SJosef Bacik 		struct btrfs_root *csum_root = btrfs_csum_root(info, 0);
18379c54e80dSJosef Bacik 
18389c54e80dSJosef Bacik 		btrfs_set_backup_extent_root(root_backup,
18399c54e80dSJosef Bacik 					     extent_root->node->start);
1840af31f5e5SChris Mason 		btrfs_set_backup_extent_root_gen(root_backup,
184129cbcf40SJosef Bacik 				btrfs_header_generation(extent_root->node));
1842af31f5e5SChris Mason 		btrfs_set_backup_extent_root_level(root_backup,
184329cbcf40SJosef Bacik 					btrfs_header_level(extent_root->node));
1844af31f5e5SChris Mason 
1845f7238e50SJosef Bacik 		btrfs_set_backup_csum_root(root_backup, csum_root->node->start);
1846f7238e50SJosef Bacik 		btrfs_set_backup_csum_root_gen(root_backup,
1847f7238e50SJosef Bacik 					       btrfs_header_generation(csum_root->node));
1848f7238e50SJosef Bacik 		btrfs_set_backup_csum_root_level(root_backup,
1849f7238e50SJosef Bacik 						 btrfs_header_level(csum_root->node));
18509c54e80dSJosef Bacik 	}
1851af31f5e5SChris Mason 
18527c7e82a7SChris Mason 	/*
18537c7e82a7SChris Mason 	 * we might commit during log recovery, which happens before we set
18547c7e82a7SChris Mason 	 * the fs_root.  Make sure it is valid before we fill it in.
18557c7e82a7SChris Mason 	 */
18567c7e82a7SChris Mason 	if (info->fs_root && info->fs_root->node) {
18577c7e82a7SChris Mason 		btrfs_set_backup_fs_root(root_backup,
18587c7e82a7SChris Mason 					 info->fs_root->node->start);
1859af31f5e5SChris Mason 		btrfs_set_backup_fs_root_gen(root_backup,
1860af31f5e5SChris Mason 			       btrfs_header_generation(info->fs_root->node));
1861af31f5e5SChris Mason 		btrfs_set_backup_fs_root_level(root_backup,
1862af31f5e5SChris Mason 			       btrfs_header_level(info->fs_root->node));
18637c7e82a7SChris Mason 	}
1864af31f5e5SChris Mason 
1865af31f5e5SChris Mason 	btrfs_set_backup_dev_root(root_backup, info->dev_root->node->start);
1866af31f5e5SChris Mason 	btrfs_set_backup_dev_root_gen(root_backup,
1867af31f5e5SChris Mason 			       btrfs_header_generation(info->dev_root->node));
1868af31f5e5SChris Mason 	btrfs_set_backup_dev_root_level(root_backup,
1869af31f5e5SChris Mason 				       btrfs_header_level(info->dev_root->node));
1870af31f5e5SChris Mason 
1871af31f5e5SChris Mason 	btrfs_set_backup_total_bytes(root_backup,
1872af31f5e5SChris Mason 			     btrfs_super_total_bytes(info->super_copy));
1873af31f5e5SChris Mason 	btrfs_set_backup_bytes_used(root_backup,
1874af31f5e5SChris Mason 			     btrfs_super_bytes_used(info->super_copy));
1875af31f5e5SChris Mason 	btrfs_set_backup_num_devices(root_backup,
1876af31f5e5SChris Mason 			     btrfs_super_num_devices(info->super_copy));
1877af31f5e5SChris Mason 
1878af31f5e5SChris Mason 	/*
1879af31f5e5SChris Mason 	 * if we don't copy this out to the super_copy, it won't get remembered
1880af31f5e5SChris Mason 	 * for the next commit
1881af31f5e5SChris Mason 	 */
1882af31f5e5SChris Mason 	memcpy(&info->super_copy->super_roots,
1883af31f5e5SChris Mason 	       &info->super_for_commit->super_roots,
1884af31f5e5SChris Mason 	       sizeof(*root_backup) * BTRFS_NUM_BACKUP_ROOTS);
1885af31f5e5SChris Mason }
1886af31f5e5SChris Mason 
1887af31f5e5SChris Mason /*
1888bd2336b2SNikolay Borisov  * read_backup_root - Reads a backup root based on the passed priority. Prio 0
1889bd2336b2SNikolay Borisov  * is the newest, prio 1/2/3 are 2nd newest/3rd newest/4th (oldest) backup roots
1890bd2336b2SNikolay Borisov  *
1891bd2336b2SNikolay Borisov  * fs_info - filesystem whose backup roots need to be read
1892bd2336b2SNikolay Borisov  * priority - priority of backup root required
1893bd2336b2SNikolay Borisov  *
1894bd2336b2SNikolay Borisov  * Returns backup root index on success and -EINVAL otherwise.
1895bd2336b2SNikolay Borisov  */
1896bd2336b2SNikolay Borisov static int read_backup_root(struct btrfs_fs_info *fs_info, u8 priority)
1897bd2336b2SNikolay Borisov {
1898bd2336b2SNikolay Borisov 	int backup_index = find_newest_super_backup(fs_info);
1899bd2336b2SNikolay Borisov 	struct btrfs_super_block *super = fs_info->super_copy;
1900bd2336b2SNikolay Borisov 	struct btrfs_root_backup *root_backup;
1901bd2336b2SNikolay Borisov 
1902bd2336b2SNikolay Borisov 	if (priority < BTRFS_NUM_BACKUP_ROOTS && backup_index >= 0) {
1903bd2336b2SNikolay Borisov 		if (priority == 0)
1904bd2336b2SNikolay Borisov 			return backup_index;
1905bd2336b2SNikolay Borisov 
1906bd2336b2SNikolay Borisov 		backup_index = backup_index + BTRFS_NUM_BACKUP_ROOTS - priority;
1907bd2336b2SNikolay Borisov 		backup_index %= BTRFS_NUM_BACKUP_ROOTS;
1908bd2336b2SNikolay Borisov 	} else {
1909bd2336b2SNikolay Borisov 		return -EINVAL;
1910bd2336b2SNikolay Borisov 	}
1911bd2336b2SNikolay Borisov 
1912bd2336b2SNikolay Borisov 	root_backup = super->super_roots + backup_index;
1913bd2336b2SNikolay Borisov 
1914bd2336b2SNikolay Borisov 	btrfs_set_super_generation(super,
1915bd2336b2SNikolay Borisov 				   btrfs_backup_tree_root_gen(root_backup));
1916bd2336b2SNikolay Borisov 	btrfs_set_super_root(super, btrfs_backup_tree_root(root_backup));
1917bd2336b2SNikolay Borisov 	btrfs_set_super_root_level(super,
1918bd2336b2SNikolay Borisov 				   btrfs_backup_tree_root_level(root_backup));
1919bd2336b2SNikolay Borisov 	btrfs_set_super_bytes_used(super, btrfs_backup_bytes_used(root_backup));
1920bd2336b2SNikolay Borisov 
1921bd2336b2SNikolay Borisov 	/*
1922bd2336b2SNikolay Borisov 	 * Fixme: the total bytes and num_devices need to match or we should
1923bd2336b2SNikolay Borisov 	 * need a fsck
1924bd2336b2SNikolay Borisov 	 */
1925bd2336b2SNikolay Borisov 	btrfs_set_super_total_bytes(super, btrfs_backup_total_bytes(root_backup));
1926bd2336b2SNikolay Borisov 	btrfs_set_super_num_devices(super, btrfs_backup_num_devices(root_backup));
1927bd2336b2SNikolay Borisov 
1928bd2336b2SNikolay Borisov 	return backup_index;
1929bd2336b2SNikolay Borisov }
1930bd2336b2SNikolay Borisov 
19317abadb64SLiu Bo /* helper to cleanup workers */
19327abadb64SLiu Bo static void btrfs_stop_all_workers(struct btrfs_fs_info *fs_info)
19337abadb64SLiu Bo {
1934dc6e3209SQu Wenruo 	btrfs_destroy_workqueue(fs_info->fixup_workers);
1935afe3d242SQu Wenruo 	btrfs_destroy_workqueue(fs_info->delalloc_workers);
19365cdc7ad3SQu Wenruo 	btrfs_destroy_workqueue(fs_info->workers);
1937d7b9416fSChristoph Hellwig 	if (fs_info->endio_workers)
1938d7b9416fSChristoph Hellwig 		destroy_workqueue(fs_info->endio_workers);
1939385de0efSChristoph Hellwig 	if (fs_info->rmw_workers)
1940385de0efSChristoph Hellwig 		destroy_workqueue(fs_info->rmw_workers);
1941fed8a72dSChristoph Hellwig 	if (fs_info->compressed_write_workers)
1942fed8a72dSChristoph Hellwig 		destroy_workqueue(fs_info->compressed_write_workers);
1943fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_write_workers);
1944fccb5d86SQu Wenruo 	btrfs_destroy_workqueue(fs_info->endio_freespace_worker);
19455b3bc44eSQu Wenruo 	btrfs_destroy_workqueue(fs_info->delayed_workers);
1946e66f0bb1SQu Wenruo 	btrfs_destroy_workqueue(fs_info->caching_workers);
1947a44903abSQu Wenruo 	btrfs_destroy_workqueue(fs_info->flush_workers);
1948fc97fab0SQu Wenruo 	btrfs_destroy_workqueue(fs_info->qgroup_rescan_workers);
1949b0643e59SDennis Zhou 	if (fs_info->discard_ctl.discard_workers)
1950b0643e59SDennis Zhou 		destroy_workqueue(fs_info->discard_ctl.discard_workers);
1951a9b9477dSFilipe Manana 	/*
1952a9b9477dSFilipe Manana 	 * Now that all other work queues are destroyed, we can safely destroy
1953a9b9477dSFilipe Manana 	 * the queues used for metadata I/O, since tasks from those other work
1954a9b9477dSFilipe Manana 	 * queues can do metadata I/O operations.
1955a9b9477dSFilipe Manana 	 */
1956d7b9416fSChristoph Hellwig 	if (fs_info->endio_meta_workers)
1957d7b9416fSChristoph Hellwig 		destroy_workqueue(fs_info->endio_meta_workers);
19587abadb64SLiu Bo }
19597abadb64SLiu Bo 
19602e9f5954SRashika static void free_root_extent_buffers(struct btrfs_root *root)
19612e9f5954SRashika {
19622e9f5954SRashika 	if (root) {
19632e9f5954SRashika 		free_extent_buffer(root->node);
19642e9f5954SRashika 		free_extent_buffer(root->commit_root);
19652e9f5954SRashika 		root->node = NULL;
19662e9f5954SRashika 		root->commit_root = NULL;
19672e9f5954SRashika 	}
19682e9f5954SRashika }
19692e9f5954SRashika 
1970abed4aaaSJosef Bacik static void free_global_root_pointers(struct btrfs_fs_info *fs_info)
1971abed4aaaSJosef Bacik {
1972abed4aaaSJosef Bacik 	struct btrfs_root *root, *tmp;
1973abed4aaaSJosef Bacik 
1974abed4aaaSJosef Bacik 	rbtree_postorder_for_each_entry_safe(root, tmp,
1975abed4aaaSJosef Bacik 					     &fs_info->global_root_tree,
1976abed4aaaSJosef Bacik 					     rb_node)
1977abed4aaaSJosef Bacik 		free_root_extent_buffers(root);
1978abed4aaaSJosef Bacik }
1979abed4aaaSJosef Bacik 
1980af31f5e5SChris Mason /* helper to cleanup tree roots */
19814273eaffSAnand Jain static void free_root_pointers(struct btrfs_fs_info *info, bool free_chunk_root)
1982af31f5e5SChris Mason {
19832e9f5954SRashika 	free_root_extent_buffers(info->tree_root);
1984655b09feSJosef Bacik 
1985abed4aaaSJosef Bacik 	free_global_root_pointers(info);
19862e9f5954SRashika 	free_root_extent_buffers(info->dev_root);
19872e9f5954SRashika 	free_root_extent_buffers(info->quota_root);
19882e9f5954SRashika 	free_root_extent_buffers(info->uuid_root);
19898c38938cSJosef Bacik 	free_root_extent_buffers(info->fs_root);
1990aeb935a4SQu Wenruo 	free_root_extent_buffers(info->data_reloc_root);
19919c54e80dSJosef Bacik 	free_root_extent_buffers(info->block_group_root);
19924273eaffSAnand Jain 	if (free_chunk_root)
19932e9f5954SRashika 		free_root_extent_buffers(info->chunk_root);
1994af31f5e5SChris Mason }
1995af31f5e5SChris Mason 
19968c38938cSJosef Bacik void btrfs_put_root(struct btrfs_root *root)
19978c38938cSJosef Bacik {
19988c38938cSJosef Bacik 	if (!root)
19998c38938cSJosef Bacik 		return;
20008c38938cSJosef Bacik 
20018c38938cSJosef Bacik 	if (refcount_dec_and_test(&root->refs)) {
20028c38938cSJosef Bacik 		WARN_ON(!RB_EMPTY_ROOT(&root->inode_tree));
20031dae7e0eSQu Wenruo 		WARN_ON(test_bit(BTRFS_ROOT_DEAD_RELOC_TREE, &root->state));
20048c38938cSJosef Bacik 		if (root->anon_dev)
20058c38938cSJosef Bacik 			free_anon_bdev(root->anon_dev);
2006923eb523SJohannes Thumshirn 		free_root_extent_buffers(root);
20078c38938cSJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
2008fc7cbcd4SDavid Sterba 		spin_lock(&root->fs_info->fs_roots_radix_lock);
20098c38938cSJosef Bacik 		list_del_init(&root->leak_list);
2010fc7cbcd4SDavid Sterba 		spin_unlock(&root->fs_info->fs_roots_radix_lock);
20118c38938cSJosef Bacik #endif
20128c38938cSJosef Bacik 		kfree(root);
20138c38938cSJosef Bacik 	}
20148c38938cSJosef Bacik }
20158c38938cSJosef Bacik 
2016faa2dbf0SJosef Bacik void btrfs_free_fs_roots(struct btrfs_fs_info *fs_info)
2017171f6537SJosef Bacik {
2018fc7cbcd4SDavid Sterba 	int ret;
2019fc7cbcd4SDavid Sterba 	struct btrfs_root *gang[8];
2020fc7cbcd4SDavid Sterba 	int i;
2021171f6537SJosef Bacik 
2022171f6537SJosef Bacik 	while (!list_empty(&fs_info->dead_roots)) {
2023fc7cbcd4SDavid Sterba 		gang[0] = list_entry(fs_info->dead_roots.next,
2024171f6537SJosef Bacik 				     struct btrfs_root, root_list);
2025fc7cbcd4SDavid Sterba 		list_del(&gang[0]->root_list);
2026171f6537SJosef Bacik 
2027fc7cbcd4SDavid Sterba 		if (test_bit(BTRFS_ROOT_IN_RADIX, &gang[0]->state))
2028fc7cbcd4SDavid Sterba 			btrfs_drop_and_free_fs_root(fs_info, gang[0]);
2029fc7cbcd4SDavid Sterba 		btrfs_put_root(gang[0]);
2030171f6537SJosef Bacik 	}
2031171f6537SJosef Bacik 
2032fc7cbcd4SDavid Sterba 	while (1) {
2033fc7cbcd4SDavid Sterba 		ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
2034fc7cbcd4SDavid Sterba 					     (void **)gang, 0,
2035fc7cbcd4SDavid Sterba 					     ARRAY_SIZE(gang));
2036fc7cbcd4SDavid Sterba 		if (!ret)
2037fc7cbcd4SDavid Sterba 			break;
2038fc7cbcd4SDavid Sterba 		for (i = 0; i < ret; i++)
2039fc7cbcd4SDavid Sterba 			btrfs_drop_and_free_fs_root(fs_info, gang[i]);
2040171f6537SJosef Bacik 	}
2041171f6537SJosef Bacik }
2042af31f5e5SChris Mason 
2043638aa7edSEric Sandeen static void btrfs_init_scrub(struct btrfs_fs_info *fs_info)
2044638aa7edSEric Sandeen {
2045638aa7edSEric Sandeen 	mutex_init(&fs_info->scrub_lock);
2046638aa7edSEric Sandeen 	atomic_set(&fs_info->scrubs_running, 0);
2047638aa7edSEric Sandeen 	atomic_set(&fs_info->scrub_pause_req, 0);
2048638aa7edSEric Sandeen 	atomic_set(&fs_info->scrubs_paused, 0);
2049638aa7edSEric Sandeen 	atomic_set(&fs_info->scrub_cancel_req, 0);
2050638aa7edSEric Sandeen 	init_waitqueue_head(&fs_info->scrub_pause_wait);
2051ff09c4caSAnand Jain 	refcount_set(&fs_info->scrub_workers_refcnt, 0);
2052638aa7edSEric Sandeen }
2053638aa7edSEric Sandeen 
2054779a65a4SEric Sandeen static void btrfs_init_balance(struct btrfs_fs_info *fs_info)
2055779a65a4SEric Sandeen {
2056779a65a4SEric Sandeen 	spin_lock_init(&fs_info->balance_lock);
2057779a65a4SEric Sandeen 	mutex_init(&fs_info->balance_mutex);
2058779a65a4SEric Sandeen 	atomic_set(&fs_info->balance_pause_req, 0);
2059779a65a4SEric Sandeen 	atomic_set(&fs_info->balance_cancel_req, 0);
2060779a65a4SEric Sandeen 	fs_info->balance_ctl = NULL;
2061779a65a4SEric Sandeen 	init_waitqueue_head(&fs_info->balance_wait_q);
2062907d2710SDavid Sterba 	atomic_set(&fs_info->reloc_cancel_req, 0);
2063779a65a4SEric Sandeen }
2064779a65a4SEric Sandeen 
2065dcb2137cSChristoph Hellwig static int btrfs_init_btree_inode(struct super_block *sb)
2066f37938e0SEric Sandeen {
2067dcb2137cSChristoph Hellwig 	struct btrfs_fs_info *fs_info = btrfs_sb(sb);
2068e256927bSJosef Bacik 	unsigned long hash = btrfs_inode_hash(BTRFS_BTREE_INODE_OBJECTID,
2069e256927bSJosef Bacik 					      fs_info->tree_root);
2070dcb2137cSChristoph Hellwig 	struct inode *inode;
2071dcb2137cSChristoph Hellwig 
2072dcb2137cSChristoph Hellwig 	inode = new_inode(sb);
2073dcb2137cSChristoph Hellwig 	if (!inode)
2074dcb2137cSChristoph Hellwig 		return -ENOMEM;
20752ff7e61eSJeff Mahoney 
20762ff7e61eSJeff Mahoney 	inode->i_ino = BTRFS_BTREE_INODE_OBJECTID;
20772ff7e61eSJeff Mahoney 	set_nlink(inode, 1);
2078f37938e0SEric Sandeen 	/*
2079f37938e0SEric Sandeen 	 * we set the i_size on the btree inode to the max possible int.
2080f37938e0SEric Sandeen 	 * the real end of the address space is determined by all of
2081f37938e0SEric Sandeen 	 * the devices in the system
2082f37938e0SEric Sandeen 	 */
20832ff7e61eSJeff Mahoney 	inode->i_size = OFFSET_MAX;
20842ff7e61eSJeff Mahoney 	inode->i_mapping->a_ops = &btree_aops;
2085dcb2137cSChristoph Hellwig 	mapping_set_gfp_mask(inode->i_mapping, GFP_NOFS);
2086f37938e0SEric Sandeen 
20872ff7e61eSJeff Mahoney 	RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
208843eb5f29SQu Wenruo 	extent_io_tree_init(fs_info, &BTRFS_I(inode)->io_tree,
208935da5a7eSDavid Sterba 			    IO_TREE_BTREE_INODE_IO);
20902ff7e61eSJeff Mahoney 	extent_map_tree_init(&BTRFS_I(inode)->extent_tree);
2091f37938e0SEric Sandeen 
20925c8fd99fSJosef Bacik 	BTRFS_I(inode)->root = btrfs_grab_root(fs_info->tree_root);
2093adac5584SFilipe Manana 	BTRFS_I(inode)->location.objectid = BTRFS_BTREE_INODE_OBJECTID;
2094adac5584SFilipe Manana 	BTRFS_I(inode)->location.type = 0;
2095adac5584SFilipe Manana 	BTRFS_I(inode)->location.offset = 0;
20962ff7e61eSJeff Mahoney 	set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
2097e256927bSJosef Bacik 	__insert_inode_hash(inode, hash);
2098dcb2137cSChristoph Hellwig 	fs_info->btree_inode = inode;
2099dcb2137cSChristoph Hellwig 
2100dcb2137cSChristoph Hellwig 	return 0;
2101f37938e0SEric Sandeen }
2102f37938e0SEric Sandeen 
2103ad618368SEric Sandeen static void btrfs_init_dev_replace_locks(struct btrfs_fs_info *fs_info)
2104ad618368SEric Sandeen {
2105ad618368SEric Sandeen 	mutex_init(&fs_info->dev_replace.lock_finishing_cancel_unmount);
2106129827e3SDavid Sterba 	init_rwsem(&fs_info->dev_replace.rwsem);
21077f8d236aSDavid Sterba 	init_waitqueue_head(&fs_info->dev_replace.replace_wait);
2108ad618368SEric Sandeen }
2109ad618368SEric Sandeen 
2110f9e92e40SEric Sandeen static void btrfs_init_qgroup(struct btrfs_fs_info *fs_info)
2111f9e92e40SEric Sandeen {
2112f9e92e40SEric Sandeen 	spin_lock_init(&fs_info->qgroup_lock);
2113f9e92e40SEric Sandeen 	mutex_init(&fs_info->qgroup_ioctl_lock);
2114f9e92e40SEric Sandeen 	fs_info->qgroup_tree = RB_ROOT;
2115f9e92e40SEric Sandeen 	INIT_LIST_HEAD(&fs_info->dirty_qgroups);
2116f9e92e40SEric Sandeen 	fs_info->qgroup_seq = 1;
2117f9e92e40SEric Sandeen 	fs_info->qgroup_ulist = NULL;
2118d2c609b8SJeff Mahoney 	fs_info->qgroup_rescan_running = false;
2119011b46c3SQu Wenruo 	fs_info->qgroup_drop_subtree_thres = BTRFS_MAX_LEVEL;
2120f9e92e40SEric Sandeen 	mutex_init(&fs_info->qgroup_rescan_lock);
2121f9e92e40SEric Sandeen }
2122f9e92e40SEric Sandeen 
2123d21deec5SSu Yue static int btrfs_init_workqueues(struct btrfs_fs_info *fs_info)
21242a458198SEric Sandeen {
2125f7b885beSAnand Jain 	u32 max_active = fs_info->thread_pool_size;
21266f011058SDavid Sterba 	unsigned int flags = WQ_MEM_RECLAIM | WQ_FREEZABLE | WQ_UNBOUND;
21272a458198SEric Sandeen 
21282a458198SEric Sandeen 	fs_info->workers =
2129a31b4a43SChristoph Hellwig 		btrfs_alloc_workqueue(fs_info, "worker", flags, max_active, 16);
21302a458198SEric Sandeen 
21312a458198SEric Sandeen 	fs_info->delalloc_workers =
2132cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "delalloc",
2133cb001095SJeff Mahoney 				      flags, max_active, 2);
21342a458198SEric Sandeen 
21352a458198SEric Sandeen 	fs_info->flush_workers =
2136cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "flush_delalloc",
2137cb001095SJeff Mahoney 				      flags, max_active, 0);
21382a458198SEric Sandeen 
21392a458198SEric Sandeen 	fs_info->caching_workers =
2140cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "cache", flags, max_active, 0);
21412a458198SEric Sandeen 
21422a458198SEric Sandeen 	fs_info->fixup_workers =
2143cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "fixup", flags, 1, 0);
21442a458198SEric Sandeen 
21452a458198SEric Sandeen 	fs_info->endio_workers =
2146d7b9416fSChristoph Hellwig 		alloc_workqueue("btrfs-endio", flags, max_active);
21472a458198SEric Sandeen 	fs_info->endio_meta_workers =
2148d7b9416fSChristoph Hellwig 		alloc_workqueue("btrfs-endio-meta", flags, max_active);
2149385de0efSChristoph Hellwig 	fs_info->rmw_workers = alloc_workqueue("btrfs-rmw", flags, max_active);
21502a458198SEric Sandeen 	fs_info->endio_write_workers =
2151cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "endio-write", flags,
2152cb001095SJeff Mahoney 				      max_active, 2);
2153fed8a72dSChristoph Hellwig 	fs_info->compressed_write_workers =
2154fed8a72dSChristoph Hellwig 		alloc_workqueue("btrfs-compressed-write", flags, max_active);
21552a458198SEric Sandeen 	fs_info->endio_freespace_worker =
2156cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "freespace-write", flags,
2157cb001095SJeff Mahoney 				      max_active, 0);
21582a458198SEric Sandeen 	fs_info->delayed_workers =
2159cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "delayed-meta", flags,
2160cb001095SJeff Mahoney 				      max_active, 0);
21612a458198SEric Sandeen 	fs_info->qgroup_rescan_workers =
2162cb001095SJeff Mahoney 		btrfs_alloc_workqueue(fs_info, "qgroup-rescan", flags, 1, 0);
2163b0643e59SDennis Zhou 	fs_info->discard_ctl.discard_workers =
2164b0643e59SDennis Zhou 		alloc_workqueue("btrfs_discard", WQ_UNBOUND | WQ_FREEZABLE, 1);
21652a458198SEric Sandeen 
21668bfec2e4SChristoph Hellwig 	if (!(fs_info->workers &&
2167a31b4a43SChristoph Hellwig 	      fs_info->delalloc_workers && fs_info->flush_workers &&
21682a458198SEric Sandeen 	      fs_info->endio_workers && fs_info->endio_meta_workers &&
2169fed8a72dSChristoph Hellwig 	      fs_info->compressed_write_workers &&
21701a1a2851SQu Wenruo 	      fs_info->endio_write_workers &&
21712a458198SEric Sandeen 	      fs_info->endio_freespace_worker && fs_info->rmw_workers &&
2172f26c9238SQu Wenruo 	      fs_info->caching_workers && fs_info->fixup_workers &&
2173f26c9238SQu Wenruo 	      fs_info->delayed_workers && fs_info->qgroup_rescan_workers &&
2174b0643e59SDennis Zhou 	      fs_info->discard_ctl.discard_workers)) {
21752a458198SEric Sandeen 		return -ENOMEM;
21762a458198SEric Sandeen 	}
21772a458198SEric Sandeen 
21782a458198SEric Sandeen 	return 0;
21792a458198SEric Sandeen }
21802a458198SEric Sandeen 
21816d97c6e3SJohannes Thumshirn static int btrfs_init_csum_hash(struct btrfs_fs_info *fs_info, u16 csum_type)
21826d97c6e3SJohannes Thumshirn {
21836d97c6e3SJohannes Thumshirn 	struct crypto_shash *csum_shash;
2184b4e967beSDavid Sterba 	const char *csum_driver = btrfs_super_csum_driver(csum_type);
21856d97c6e3SJohannes Thumshirn 
2186b4e967beSDavid Sterba 	csum_shash = crypto_alloc_shash(csum_driver, 0, 0);
21876d97c6e3SJohannes Thumshirn 
21886d97c6e3SJohannes Thumshirn 	if (IS_ERR(csum_shash)) {
21896d97c6e3SJohannes Thumshirn 		btrfs_err(fs_info, "error allocating %s hash for checksum",
2190b4e967beSDavid Sterba 			  csum_driver);
21916d97c6e3SJohannes Thumshirn 		return PTR_ERR(csum_shash);
21926d97c6e3SJohannes Thumshirn 	}
21936d97c6e3SJohannes Thumshirn 
21946d97c6e3SJohannes Thumshirn 	fs_info->csum_shash = csum_shash;
21956d97c6e3SJohannes Thumshirn 
219668d99ab0SChristoph Hellwig 	/*
219768d99ab0SChristoph Hellwig 	 * Check if the checksum implementation is a fast accelerated one.
219868d99ab0SChristoph Hellwig 	 * As-is this is a bit of a hack and should be replaced once the csum
219968d99ab0SChristoph Hellwig 	 * implementations provide that information themselves.
220068d99ab0SChristoph Hellwig 	 */
220168d99ab0SChristoph Hellwig 	switch (csum_type) {
220268d99ab0SChristoph Hellwig 	case BTRFS_CSUM_TYPE_CRC32:
220368d99ab0SChristoph Hellwig 		if (!strstr(crypto_shash_driver_name(csum_shash), "generic"))
220468d99ab0SChristoph Hellwig 			set_bit(BTRFS_FS_CSUM_IMPL_FAST, &fs_info->flags);
220568d99ab0SChristoph Hellwig 		break;
220668d99ab0SChristoph Hellwig 	default:
220768d99ab0SChristoph Hellwig 		break;
220868d99ab0SChristoph Hellwig 	}
220968d99ab0SChristoph Hellwig 
2210c8a5f8caSDavid Sterba 	btrfs_info(fs_info, "using %s (%s) checksum algorithm",
2211c8a5f8caSDavid Sterba 			btrfs_super_csum_name(csum_type),
2212c8a5f8caSDavid Sterba 			crypto_shash_driver_name(csum_shash));
22136d97c6e3SJohannes Thumshirn 	return 0;
22146d97c6e3SJohannes Thumshirn }
22156d97c6e3SJohannes Thumshirn 
221663443bf5SEric Sandeen static int btrfs_replay_log(struct btrfs_fs_info *fs_info,
221763443bf5SEric Sandeen 			    struct btrfs_fs_devices *fs_devices)
221863443bf5SEric Sandeen {
221963443bf5SEric Sandeen 	int ret;
2220789d6a3aSQu Wenruo 	struct btrfs_tree_parent_check check = { 0 };
222163443bf5SEric Sandeen 	struct btrfs_root *log_tree_root;
222263443bf5SEric Sandeen 	struct btrfs_super_block *disk_super = fs_info->super_copy;
222363443bf5SEric Sandeen 	u64 bytenr = btrfs_super_log_root(disk_super);
2224581c1760SQu Wenruo 	int level = btrfs_super_log_root_level(disk_super);
222563443bf5SEric Sandeen 
222663443bf5SEric Sandeen 	if (fs_devices->rw_devices == 0) {
2227f14d104dSDavid Sterba 		btrfs_warn(fs_info, "log replay required on RO media");
222863443bf5SEric Sandeen 		return -EIO;
222963443bf5SEric Sandeen 	}
223063443bf5SEric Sandeen 
223196dfcb46SJosef Bacik 	log_tree_root = btrfs_alloc_root(fs_info, BTRFS_TREE_LOG_OBJECTID,
223296dfcb46SJosef Bacik 					 GFP_KERNEL);
223363443bf5SEric Sandeen 	if (!log_tree_root)
223463443bf5SEric Sandeen 		return -ENOMEM;
223563443bf5SEric Sandeen 
2236789d6a3aSQu Wenruo 	check.level = level;
2237789d6a3aSQu Wenruo 	check.transid = fs_info->generation + 1;
2238789d6a3aSQu Wenruo 	check.owner_root = BTRFS_TREE_LOG_OBJECTID;
2239789d6a3aSQu Wenruo 	log_tree_root->node = read_tree_block(fs_info, bytenr, &check);
224064c043deSLiu Bo 	if (IS_ERR(log_tree_root->node)) {
2241f14d104dSDavid Sterba 		btrfs_warn(fs_info, "failed to read log tree");
22420eeff236SLiu Bo 		ret = PTR_ERR(log_tree_root->node);
22438c38938cSJosef Bacik 		log_tree_root->node = NULL;
224400246528SJosef Bacik 		btrfs_put_root(log_tree_root);
22450eeff236SLiu Bo 		return ret;
22464eb150d6SQu Wenruo 	}
22474eb150d6SQu Wenruo 	if (!extent_buffer_uptodate(log_tree_root->node)) {
2248f14d104dSDavid Sterba 		btrfs_err(fs_info, "failed to read log tree");
224900246528SJosef Bacik 		btrfs_put_root(log_tree_root);
225063443bf5SEric Sandeen 		return -EIO;
225163443bf5SEric Sandeen 	}
22524eb150d6SQu Wenruo 
225363443bf5SEric Sandeen 	/* returns with log_tree_root freed on success */
225463443bf5SEric Sandeen 	ret = btrfs_recover_log_trees(log_tree_root);
225563443bf5SEric Sandeen 	if (ret) {
22560b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, ret,
225763443bf5SEric Sandeen 				      "Failed to recover log tree");
225800246528SJosef Bacik 		btrfs_put_root(log_tree_root);
225963443bf5SEric Sandeen 		return ret;
226063443bf5SEric Sandeen 	}
226163443bf5SEric Sandeen 
2262bc98a42cSDavid Howells 	if (sb_rdonly(fs_info->sb)) {
22636bccf3abSJeff Mahoney 		ret = btrfs_commit_super(fs_info);
226463443bf5SEric Sandeen 		if (ret)
226563443bf5SEric Sandeen 			return ret;
226663443bf5SEric Sandeen 	}
226763443bf5SEric Sandeen 
226863443bf5SEric Sandeen 	return 0;
226963443bf5SEric Sandeen }
227063443bf5SEric Sandeen 
2271abed4aaaSJosef Bacik static int load_global_roots_objectid(struct btrfs_root *tree_root,
2272abed4aaaSJosef Bacik 				      struct btrfs_path *path, u64 objectid,
2273abed4aaaSJosef Bacik 				      const char *name)
2274abed4aaaSJosef Bacik {
2275abed4aaaSJosef Bacik 	struct btrfs_fs_info *fs_info = tree_root->fs_info;
2276abed4aaaSJosef Bacik 	struct btrfs_root *root;
2277f7238e50SJosef Bacik 	u64 max_global_id = 0;
2278abed4aaaSJosef Bacik 	int ret;
2279abed4aaaSJosef Bacik 	struct btrfs_key key = {
2280abed4aaaSJosef Bacik 		.objectid = objectid,
2281abed4aaaSJosef Bacik 		.type = BTRFS_ROOT_ITEM_KEY,
2282abed4aaaSJosef Bacik 		.offset = 0,
2283abed4aaaSJosef Bacik 	};
2284abed4aaaSJosef Bacik 	bool found = false;
2285abed4aaaSJosef Bacik 
2286abed4aaaSJosef Bacik 	/* If we have IGNOREDATACSUMS skip loading these roots. */
2287abed4aaaSJosef Bacik 	if (objectid == BTRFS_CSUM_TREE_OBJECTID &&
2288abed4aaaSJosef Bacik 	    btrfs_test_opt(fs_info, IGNOREDATACSUMS)) {
2289abed4aaaSJosef Bacik 		set_bit(BTRFS_FS_STATE_NO_CSUMS, &fs_info->fs_state);
2290abed4aaaSJosef Bacik 		return 0;
2291abed4aaaSJosef Bacik 	}
2292abed4aaaSJosef Bacik 
2293abed4aaaSJosef Bacik 	while (1) {
2294abed4aaaSJosef Bacik 		ret = btrfs_search_slot(NULL, tree_root, &key, path, 0, 0);
2295abed4aaaSJosef Bacik 		if (ret < 0)
2296abed4aaaSJosef Bacik 			break;
2297abed4aaaSJosef Bacik 
2298abed4aaaSJosef Bacik 		if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
2299abed4aaaSJosef Bacik 			ret = btrfs_next_leaf(tree_root, path);
2300abed4aaaSJosef Bacik 			if (ret) {
2301abed4aaaSJosef Bacik 				if (ret > 0)
2302abed4aaaSJosef Bacik 					ret = 0;
2303abed4aaaSJosef Bacik 				break;
2304abed4aaaSJosef Bacik 			}
2305abed4aaaSJosef Bacik 		}
2306abed4aaaSJosef Bacik 		ret = 0;
2307abed4aaaSJosef Bacik 
2308abed4aaaSJosef Bacik 		btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
2309abed4aaaSJosef Bacik 		if (key.objectid != objectid)
2310abed4aaaSJosef Bacik 			break;
2311abed4aaaSJosef Bacik 		btrfs_release_path(path);
2312abed4aaaSJosef Bacik 
2313f7238e50SJosef Bacik 		/*
2314f7238e50SJosef Bacik 		 * Just worry about this for extent tree, it'll be the same for
2315f7238e50SJosef Bacik 		 * everybody.
2316f7238e50SJosef Bacik 		 */
2317f7238e50SJosef Bacik 		if (objectid == BTRFS_EXTENT_TREE_OBJECTID)
2318f7238e50SJosef Bacik 			max_global_id = max(max_global_id, key.offset);
2319f7238e50SJosef Bacik 
2320abed4aaaSJosef Bacik 		found = true;
2321abed4aaaSJosef Bacik 		root = read_tree_root_path(tree_root, path, &key);
2322abed4aaaSJosef Bacik 		if (IS_ERR(root)) {
2323abed4aaaSJosef Bacik 			if (!btrfs_test_opt(fs_info, IGNOREBADROOTS))
2324abed4aaaSJosef Bacik 				ret = PTR_ERR(root);
2325abed4aaaSJosef Bacik 			break;
2326abed4aaaSJosef Bacik 		}
2327abed4aaaSJosef Bacik 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2328abed4aaaSJosef Bacik 		ret = btrfs_global_root_insert(root);
2329abed4aaaSJosef Bacik 		if (ret) {
2330abed4aaaSJosef Bacik 			btrfs_put_root(root);
2331abed4aaaSJosef Bacik 			break;
2332abed4aaaSJosef Bacik 		}
2333abed4aaaSJosef Bacik 		key.offset++;
2334abed4aaaSJosef Bacik 	}
2335abed4aaaSJosef Bacik 	btrfs_release_path(path);
2336abed4aaaSJosef Bacik 
2337f7238e50SJosef Bacik 	if (objectid == BTRFS_EXTENT_TREE_OBJECTID)
2338f7238e50SJosef Bacik 		fs_info->nr_global_roots = max_global_id + 1;
2339f7238e50SJosef Bacik 
2340abed4aaaSJosef Bacik 	if (!found || ret) {
2341abed4aaaSJosef Bacik 		if (objectid == BTRFS_CSUM_TREE_OBJECTID)
2342abed4aaaSJosef Bacik 			set_bit(BTRFS_FS_STATE_NO_CSUMS, &fs_info->fs_state);
2343abed4aaaSJosef Bacik 
2344abed4aaaSJosef Bacik 		if (!btrfs_test_opt(fs_info, IGNOREBADROOTS))
2345abed4aaaSJosef Bacik 			ret = ret ? ret : -ENOENT;
2346abed4aaaSJosef Bacik 		else
2347abed4aaaSJosef Bacik 			ret = 0;
2348abed4aaaSJosef Bacik 		btrfs_err(fs_info, "failed to load root %s", name);
2349abed4aaaSJosef Bacik 	}
2350abed4aaaSJosef Bacik 	return ret;
2351abed4aaaSJosef Bacik }
2352abed4aaaSJosef Bacik 
2353abed4aaaSJosef Bacik static int load_global_roots(struct btrfs_root *tree_root)
2354abed4aaaSJosef Bacik {
2355abed4aaaSJosef Bacik 	struct btrfs_path *path;
2356abed4aaaSJosef Bacik 	int ret = 0;
2357abed4aaaSJosef Bacik 
2358abed4aaaSJosef Bacik 	path = btrfs_alloc_path();
2359abed4aaaSJosef Bacik 	if (!path)
2360abed4aaaSJosef Bacik 		return -ENOMEM;
2361abed4aaaSJosef Bacik 
2362abed4aaaSJosef Bacik 	ret = load_global_roots_objectid(tree_root, path,
2363abed4aaaSJosef Bacik 					 BTRFS_EXTENT_TREE_OBJECTID, "extent");
2364abed4aaaSJosef Bacik 	if (ret)
2365abed4aaaSJosef Bacik 		goto out;
2366abed4aaaSJosef Bacik 	ret = load_global_roots_objectid(tree_root, path,
2367abed4aaaSJosef Bacik 					 BTRFS_CSUM_TREE_OBJECTID, "csum");
2368abed4aaaSJosef Bacik 	if (ret)
2369abed4aaaSJosef Bacik 		goto out;
2370abed4aaaSJosef Bacik 	if (!btrfs_fs_compat_ro(tree_root->fs_info, FREE_SPACE_TREE))
2371abed4aaaSJosef Bacik 		goto out;
2372abed4aaaSJosef Bacik 	ret = load_global_roots_objectid(tree_root, path,
2373abed4aaaSJosef Bacik 					 BTRFS_FREE_SPACE_TREE_OBJECTID,
2374abed4aaaSJosef Bacik 					 "free space");
2375abed4aaaSJosef Bacik out:
2376abed4aaaSJosef Bacik 	btrfs_free_path(path);
2377abed4aaaSJosef Bacik 	return ret;
2378abed4aaaSJosef Bacik }
2379abed4aaaSJosef Bacik 
23806bccf3abSJeff Mahoney static int btrfs_read_roots(struct btrfs_fs_info *fs_info)
23814bbcaa64SEric Sandeen {
23826bccf3abSJeff Mahoney 	struct btrfs_root *tree_root = fs_info->tree_root;
2383a4f3d2c4SDavid Sterba 	struct btrfs_root *root;
23844bbcaa64SEric Sandeen 	struct btrfs_key location;
23854bbcaa64SEric Sandeen 	int ret;
23864bbcaa64SEric Sandeen 
23876bccf3abSJeff Mahoney 	BUG_ON(!fs_info->tree_root);
23886bccf3abSJeff Mahoney 
2389abed4aaaSJosef Bacik 	ret = load_global_roots(tree_root);
2390abed4aaaSJosef Bacik 	if (ret)
2391abed4aaaSJosef Bacik 		return ret;
2392abed4aaaSJosef Bacik 
23934bbcaa64SEric Sandeen 	location.type = BTRFS_ROOT_ITEM_KEY;
23944bbcaa64SEric Sandeen 	location.offset = 0;
23954bbcaa64SEric Sandeen 
23961c56ab99SQu Wenruo 	if (btrfs_fs_compat_ro(fs_info, BLOCK_GROUP_TREE)) {
239714033b08SQu Wenruo 		location.objectid = BTRFS_BLOCK_GROUP_TREE_OBJECTID;
239814033b08SQu Wenruo 		root = btrfs_read_tree_root(tree_root, &location);
239914033b08SQu Wenruo 		if (IS_ERR(root)) {
240014033b08SQu Wenruo 			if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
240114033b08SQu Wenruo 				ret = PTR_ERR(root);
240214033b08SQu Wenruo 				goto out;
240314033b08SQu Wenruo 			}
240414033b08SQu Wenruo 		} else {
240514033b08SQu Wenruo 			set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
240614033b08SQu Wenruo 			fs_info->block_group_root = root;
240714033b08SQu Wenruo 		}
240814033b08SQu Wenruo 	}
240914033b08SQu Wenruo 
241014033b08SQu Wenruo 	location.objectid = BTRFS_DEV_TREE_OBJECTID;
2411a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2412f50f4353SLiu Bo 	if (IS_ERR(root)) {
241342437a63SJosef Bacik 		if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2414f50f4353SLiu Bo 			ret = PTR_ERR(root);
2415f50f4353SLiu Bo 			goto out;
2416f50f4353SLiu Bo 		}
241742437a63SJosef Bacik 	} else {
2418a4f3d2c4SDavid Sterba 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2419a4f3d2c4SDavid Sterba 		fs_info->dev_root = root;
242042437a63SJosef Bacik 	}
2421820a49daSJosef Bacik 	/* Initialize fs_info for all devices in any case */
2422a8d1b164SJohannes Thumshirn 	ret = btrfs_init_devices_late(fs_info);
2423a8d1b164SJohannes Thumshirn 	if (ret)
2424a8d1b164SJohannes Thumshirn 		goto out;
24254bbcaa64SEric Sandeen 
2426aeb935a4SQu Wenruo 	/*
2427aeb935a4SQu Wenruo 	 * This tree can share blocks with some other fs tree during relocation
2428aeb935a4SQu Wenruo 	 * and we need a proper setup by btrfs_get_fs_root
2429aeb935a4SQu Wenruo 	 */
243056e9357aSDavid Sterba 	root = btrfs_get_fs_root(tree_root->fs_info,
243156e9357aSDavid Sterba 				 BTRFS_DATA_RELOC_TREE_OBJECTID, true);
2432aeb935a4SQu Wenruo 	if (IS_ERR(root)) {
243342437a63SJosef Bacik 		if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2434aeb935a4SQu Wenruo 			ret = PTR_ERR(root);
2435aeb935a4SQu Wenruo 			goto out;
2436aeb935a4SQu Wenruo 		}
243742437a63SJosef Bacik 	} else {
2438aeb935a4SQu Wenruo 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2439aeb935a4SQu Wenruo 		fs_info->data_reloc_root = root;
244042437a63SJosef Bacik 	}
2441aeb935a4SQu Wenruo 
24424bbcaa64SEric Sandeen 	location.objectid = BTRFS_QUOTA_TREE_OBJECTID;
2443a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2444a4f3d2c4SDavid Sterba 	if (!IS_ERR(root)) {
2445a4f3d2c4SDavid Sterba 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2446afcdd129SJosef Bacik 		set_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags);
2447a4f3d2c4SDavid Sterba 		fs_info->quota_root = root;
24484bbcaa64SEric Sandeen 	}
24494bbcaa64SEric Sandeen 
24504bbcaa64SEric Sandeen 	location.objectid = BTRFS_UUID_TREE_OBJECTID;
2451a4f3d2c4SDavid Sterba 	root = btrfs_read_tree_root(tree_root, &location);
2452a4f3d2c4SDavid Sterba 	if (IS_ERR(root)) {
245342437a63SJosef Bacik 		if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2454a4f3d2c4SDavid Sterba 			ret = PTR_ERR(root);
24554bbcaa64SEric Sandeen 			if (ret != -ENOENT)
2456f50f4353SLiu Bo 				goto out;
245742437a63SJosef Bacik 		}
24584bbcaa64SEric Sandeen 	} else {
2459a4f3d2c4SDavid Sterba 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2460a4f3d2c4SDavid Sterba 		fs_info->uuid_root = root;
24614bbcaa64SEric Sandeen 	}
24624bbcaa64SEric Sandeen 
24634bbcaa64SEric Sandeen 	return 0;
2464f50f4353SLiu Bo out:
2465f50f4353SLiu Bo 	btrfs_warn(fs_info, "failed to read root (objectid=%llu): %d",
2466f50f4353SLiu Bo 		   location.objectid, ret);
2467f50f4353SLiu Bo 	return ret;
24684bbcaa64SEric Sandeen }
24694bbcaa64SEric Sandeen 
2470069ec957SQu Wenruo /*
2471069ec957SQu Wenruo  * Real super block validation
2472069ec957SQu Wenruo  * NOTE: super csum type and incompat features will not be checked here.
2473069ec957SQu Wenruo  *
2474069ec957SQu Wenruo  * @sb:		super block to check
2475069ec957SQu Wenruo  * @mirror_num:	the super block number to check its bytenr:
2476069ec957SQu Wenruo  * 		0	the primary (1st) sb
2477069ec957SQu Wenruo  * 		1, 2	2nd and 3rd backup copy
2478069ec957SQu Wenruo  * 	       -1	skip bytenr check
2479069ec957SQu Wenruo  */
2480a05d3c91SQu Wenruo int btrfs_validate_super(struct btrfs_fs_info *fs_info,
2481069ec957SQu Wenruo 			 struct btrfs_super_block *sb, int mirror_num)
248221a852b0SQu Wenruo {
248321a852b0SQu Wenruo 	u64 nodesize = btrfs_super_nodesize(sb);
248421a852b0SQu Wenruo 	u64 sectorsize = btrfs_super_sectorsize(sb);
248521a852b0SQu Wenruo 	int ret = 0;
248621a852b0SQu Wenruo 
248721a852b0SQu Wenruo 	if (btrfs_super_magic(sb) != BTRFS_MAGIC) {
248821a852b0SQu Wenruo 		btrfs_err(fs_info, "no valid FS found");
248921a852b0SQu Wenruo 		ret = -EINVAL;
249021a852b0SQu Wenruo 	}
249121a852b0SQu Wenruo 	if (btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP) {
249221a852b0SQu Wenruo 		btrfs_err(fs_info, "unrecognized or unsupported super flag: %llu",
249321a852b0SQu Wenruo 				btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP);
249421a852b0SQu Wenruo 		ret = -EINVAL;
249521a852b0SQu Wenruo 	}
249621a852b0SQu Wenruo 	if (btrfs_super_root_level(sb) >= BTRFS_MAX_LEVEL) {
249721a852b0SQu Wenruo 		btrfs_err(fs_info, "tree_root level too big: %d >= %d",
249821a852b0SQu Wenruo 				btrfs_super_root_level(sb), BTRFS_MAX_LEVEL);
249921a852b0SQu Wenruo 		ret = -EINVAL;
250021a852b0SQu Wenruo 	}
250121a852b0SQu Wenruo 	if (btrfs_super_chunk_root_level(sb) >= BTRFS_MAX_LEVEL) {
250221a852b0SQu Wenruo 		btrfs_err(fs_info, "chunk_root level too big: %d >= %d",
250321a852b0SQu Wenruo 				btrfs_super_chunk_root_level(sb), BTRFS_MAX_LEVEL);
250421a852b0SQu Wenruo 		ret = -EINVAL;
250521a852b0SQu Wenruo 	}
250621a852b0SQu Wenruo 	if (btrfs_super_log_root_level(sb) >= BTRFS_MAX_LEVEL) {
250721a852b0SQu Wenruo 		btrfs_err(fs_info, "log_root level too big: %d >= %d",
250821a852b0SQu Wenruo 				btrfs_super_log_root_level(sb), BTRFS_MAX_LEVEL);
250921a852b0SQu Wenruo 		ret = -EINVAL;
251021a852b0SQu Wenruo 	}
251121a852b0SQu Wenruo 
251221a852b0SQu Wenruo 	/*
251321a852b0SQu Wenruo 	 * Check sectorsize and nodesize first, other check will need it.
251421a852b0SQu Wenruo 	 * Check all possible sectorsize(4K, 8K, 16K, 32K, 64K) here.
251521a852b0SQu Wenruo 	 */
251621a852b0SQu Wenruo 	if (!is_power_of_2(sectorsize) || sectorsize < 4096 ||
251721a852b0SQu Wenruo 	    sectorsize > BTRFS_MAX_METADATA_BLOCKSIZE) {
251821a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid sectorsize %llu", sectorsize);
251921a852b0SQu Wenruo 		ret = -EINVAL;
252021a852b0SQu Wenruo 	}
25210bb3eb3eSQu Wenruo 
25220bb3eb3eSQu Wenruo 	/*
25231a42daabSQu Wenruo 	 * We only support at most two sectorsizes: 4K and PAGE_SIZE.
25241a42daabSQu Wenruo 	 *
25251a42daabSQu Wenruo 	 * We can support 16K sectorsize with 64K page size without problem,
25261a42daabSQu Wenruo 	 * but such sectorsize/pagesize combination doesn't make much sense.
25271a42daabSQu Wenruo 	 * 4K will be our future standard, PAGE_SIZE is supported from the very
25281a42daabSQu Wenruo 	 * beginning.
25290bb3eb3eSQu Wenruo 	 */
25301a42daabSQu Wenruo 	if (sectorsize > PAGE_SIZE || (sectorsize != SZ_4K && sectorsize != PAGE_SIZE)) {
253121a852b0SQu Wenruo 		btrfs_err(fs_info,
25320bb3eb3eSQu Wenruo 			"sectorsize %llu not yet supported for page size %lu",
253321a852b0SQu Wenruo 			sectorsize, PAGE_SIZE);
253421a852b0SQu Wenruo 		ret = -EINVAL;
253521a852b0SQu Wenruo 	}
25360bb3eb3eSQu Wenruo 
253721a852b0SQu Wenruo 	if (!is_power_of_2(nodesize) || nodesize < sectorsize ||
253821a852b0SQu Wenruo 	    nodesize > BTRFS_MAX_METADATA_BLOCKSIZE) {
253921a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid nodesize %llu", nodesize);
254021a852b0SQu Wenruo 		ret = -EINVAL;
254121a852b0SQu Wenruo 	}
254221a852b0SQu Wenruo 	if (nodesize != le32_to_cpu(sb->__unused_leafsize)) {
254321a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid leafsize %u, should be %llu",
254421a852b0SQu Wenruo 			  le32_to_cpu(sb->__unused_leafsize), nodesize);
254521a852b0SQu Wenruo 		ret = -EINVAL;
254621a852b0SQu Wenruo 	}
254721a852b0SQu Wenruo 
254821a852b0SQu Wenruo 	/* Root alignment check */
254921a852b0SQu Wenruo 	if (!IS_ALIGNED(btrfs_super_root(sb), sectorsize)) {
255021a852b0SQu Wenruo 		btrfs_warn(fs_info, "tree_root block unaligned: %llu",
255121a852b0SQu Wenruo 			   btrfs_super_root(sb));
255221a852b0SQu Wenruo 		ret = -EINVAL;
255321a852b0SQu Wenruo 	}
255421a852b0SQu Wenruo 	if (!IS_ALIGNED(btrfs_super_chunk_root(sb), sectorsize)) {
255521a852b0SQu Wenruo 		btrfs_warn(fs_info, "chunk_root block unaligned: %llu",
255621a852b0SQu Wenruo 			   btrfs_super_chunk_root(sb));
255721a852b0SQu Wenruo 		ret = -EINVAL;
255821a852b0SQu Wenruo 	}
255921a852b0SQu Wenruo 	if (!IS_ALIGNED(btrfs_super_log_root(sb), sectorsize)) {
256021a852b0SQu Wenruo 		btrfs_warn(fs_info, "log_root block unaligned: %llu",
256121a852b0SQu Wenruo 			   btrfs_super_log_root(sb));
256221a852b0SQu Wenruo 		ret = -EINVAL;
256321a852b0SQu Wenruo 	}
256421a852b0SQu Wenruo 
2565aefd7f70SNikolay Borisov 	if (memcmp(fs_info->fs_devices->fsid, fs_info->super_copy->fsid,
2566aefd7f70SNikolay Borisov 		   BTRFS_FSID_SIZE)) {
2567aefd7f70SNikolay Borisov 		btrfs_err(fs_info,
2568aefd7f70SNikolay Borisov 		"superblock fsid doesn't match fsid of fs_devices: %pU != %pU",
2569aefd7f70SNikolay Borisov 			fs_info->super_copy->fsid, fs_info->fs_devices->fsid);
2570aefd7f70SNikolay Borisov 		ret = -EINVAL;
2571aefd7f70SNikolay Borisov 	}
2572aefd7f70SNikolay Borisov 
2573aefd7f70SNikolay Borisov 	if (btrfs_fs_incompat(fs_info, METADATA_UUID) &&
2574aefd7f70SNikolay Borisov 	    memcmp(fs_info->fs_devices->metadata_uuid,
2575aefd7f70SNikolay Borisov 		   fs_info->super_copy->metadata_uuid, BTRFS_FSID_SIZE)) {
2576aefd7f70SNikolay Borisov 		btrfs_err(fs_info,
2577aefd7f70SNikolay Borisov "superblock metadata_uuid doesn't match metadata uuid of fs_devices: %pU != %pU",
2578aefd7f70SNikolay Borisov 			fs_info->super_copy->metadata_uuid,
2579aefd7f70SNikolay Borisov 			fs_info->fs_devices->metadata_uuid);
2580aefd7f70SNikolay Borisov 		ret = -EINVAL;
2581aefd7f70SNikolay Borisov 	}
2582aefd7f70SNikolay Borisov 
25831c56ab99SQu Wenruo 	/*
25841c56ab99SQu Wenruo 	 * Artificial requirement for block-group-tree to force newer features
25851c56ab99SQu Wenruo 	 * (free-space-tree, no-holes) so the test matrix is smaller.
25861c56ab99SQu Wenruo 	 */
25871c56ab99SQu Wenruo 	if (btrfs_fs_compat_ro(fs_info, BLOCK_GROUP_TREE) &&
25881c56ab99SQu Wenruo 	    (!btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE_VALID) ||
25891c56ab99SQu Wenruo 	     !btrfs_fs_incompat(fs_info, NO_HOLES))) {
25901c56ab99SQu Wenruo 		btrfs_err(fs_info,
25911c56ab99SQu Wenruo 		"block-group-tree feature requires fres-space-tree and no-holes");
25921c56ab99SQu Wenruo 		ret = -EINVAL;
25931c56ab99SQu Wenruo 	}
25941c56ab99SQu Wenruo 
2595de37aa51SNikolay Borisov 	if (memcmp(fs_info->fs_devices->metadata_uuid, sb->dev_item.fsid,
25967239ff4bSNikolay Borisov 		   BTRFS_FSID_SIZE) != 0) {
259721a852b0SQu Wenruo 		btrfs_err(fs_info,
25987239ff4bSNikolay Borisov 			"dev_item UUID does not match metadata fsid: %pU != %pU",
2599de37aa51SNikolay Borisov 			fs_info->fs_devices->metadata_uuid, sb->dev_item.fsid);
260021a852b0SQu Wenruo 		ret = -EINVAL;
260121a852b0SQu Wenruo 	}
260221a852b0SQu Wenruo 
260321a852b0SQu Wenruo 	/*
260421a852b0SQu Wenruo 	 * Hint to catch really bogus numbers, bitflips or so, more exact checks are
260521a852b0SQu Wenruo 	 * done later
260621a852b0SQu Wenruo 	 */
260721a852b0SQu Wenruo 	if (btrfs_super_bytes_used(sb) < 6 * btrfs_super_nodesize(sb)) {
260821a852b0SQu Wenruo 		btrfs_err(fs_info, "bytes_used is too small %llu",
260921a852b0SQu Wenruo 			  btrfs_super_bytes_used(sb));
261021a852b0SQu Wenruo 		ret = -EINVAL;
261121a852b0SQu Wenruo 	}
261221a852b0SQu Wenruo 	if (!is_power_of_2(btrfs_super_stripesize(sb))) {
261321a852b0SQu Wenruo 		btrfs_err(fs_info, "invalid stripesize %u",
261421a852b0SQu Wenruo 			  btrfs_super_stripesize(sb));
261521a852b0SQu Wenruo 		ret = -EINVAL;
261621a852b0SQu Wenruo 	}
261721a852b0SQu Wenruo 	if (btrfs_super_num_devices(sb) > (1UL << 31))
261821a852b0SQu Wenruo 		btrfs_warn(fs_info, "suspicious number of devices: %llu",
261921a852b0SQu Wenruo 			   btrfs_super_num_devices(sb));
262021a852b0SQu Wenruo 	if (btrfs_super_num_devices(sb) == 0) {
262121a852b0SQu Wenruo 		btrfs_err(fs_info, "number of devices is 0");
262221a852b0SQu Wenruo 		ret = -EINVAL;
262321a852b0SQu Wenruo 	}
262421a852b0SQu Wenruo 
2625069ec957SQu Wenruo 	if (mirror_num >= 0 &&
2626069ec957SQu Wenruo 	    btrfs_super_bytenr(sb) != btrfs_sb_offset(mirror_num)) {
262721a852b0SQu Wenruo 		btrfs_err(fs_info, "super offset mismatch %llu != %u",
262821a852b0SQu Wenruo 			  btrfs_super_bytenr(sb), BTRFS_SUPER_INFO_OFFSET);
262921a852b0SQu Wenruo 		ret = -EINVAL;
263021a852b0SQu Wenruo 	}
263121a852b0SQu Wenruo 
263221a852b0SQu Wenruo 	/*
263321a852b0SQu Wenruo 	 * Obvious sys_chunk_array corruptions, it must hold at least one key
263421a852b0SQu Wenruo 	 * and one chunk
263521a852b0SQu Wenruo 	 */
263621a852b0SQu Wenruo 	if (btrfs_super_sys_array_size(sb) > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
263721a852b0SQu Wenruo 		btrfs_err(fs_info, "system chunk array too big %u > %u",
263821a852b0SQu Wenruo 			  btrfs_super_sys_array_size(sb),
263921a852b0SQu Wenruo 			  BTRFS_SYSTEM_CHUNK_ARRAY_SIZE);
264021a852b0SQu Wenruo 		ret = -EINVAL;
264121a852b0SQu Wenruo 	}
264221a852b0SQu Wenruo 	if (btrfs_super_sys_array_size(sb) < sizeof(struct btrfs_disk_key)
264321a852b0SQu Wenruo 			+ sizeof(struct btrfs_chunk)) {
264421a852b0SQu Wenruo 		btrfs_err(fs_info, "system chunk array too small %u < %zu",
264521a852b0SQu Wenruo 			  btrfs_super_sys_array_size(sb),
264621a852b0SQu Wenruo 			  sizeof(struct btrfs_disk_key)
264721a852b0SQu Wenruo 			  + sizeof(struct btrfs_chunk));
264821a852b0SQu Wenruo 		ret = -EINVAL;
264921a852b0SQu Wenruo 	}
265021a852b0SQu Wenruo 
265121a852b0SQu Wenruo 	/*
265221a852b0SQu Wenruo 	 * The generation is a global counter, we'll trust it more than the others
265321a852b0SQu Wenruo 	 * but it's still possible that it's the one that's wrong.
265421a852b0SQu Wenruo 	 */
265521a852b0SQu Wenruo 	if (btrfs_super_generation(sb) < btrfs_super_chunk_root_generation(sb))
265621a852b0SQu Wenruo 		btrfs_warn(fs_info,
265721a852b0SQu Wenruo 			"suspicious: generation < chunk_root_generation: %llu < %llu",
265821a852b0SQu Wenruo 			btrfs_super_generation(sb),
265921a852b0SQu Wenruo 			btrfs_super_chunk_root_generation(sb));
266021a852b0SQu Wenruo 	if (btrfs_super_generation(sb) < btrfs_super_cache_generation(sb)
266121a852b0SQu Wenruo 	    && btrfs_super_cache_generation(sb) != (u64)-1)
266221a852b0SQu Wenruo 		btrfs_warn(fs_info,
266321a852b0SQu Wenruo 			"suspicious: generation < cache_generation: %llu < %llu",
266421a852b0SQu Wenruo 			btrfs_super_generation(sb),
266521a852b0SQu Wenruo 			btrfs_super_cache_generation(sb));
266621a852b0SQu Wenruo 
266721a852b0SQu Wenruo 	return ret;
266821a852b0SQu Wenruo }
266921a852b0SQu Wenruo 
2670069ec957SQu Wenruo /*
2671069ec957SQu Wenruo  * Validation of super block at mount time.
2672069ec957SQu Wenruo  * Some checks already done early at mount time, like csum type and incompat
2673069ec957SQu Wenruo  * flags will be skipped.
2674069ec957SQu Wenruo  */
2675069ec957SQu Wenruo static int btrfs_validate_mount_super(struct btrfs_fs_info *fs_info)
2676069ec957SQu Wenruo {
2677a05d3c91SQu Wenruo 	return btrfs_validate_super(fs_info, fs_info->super_copy, 0);
2678069ec957SQu Wenruo }
2679069ec957SQu Wenruo 
268075cb857dSQu Wenruo /*
268175cb857dSQu Wenruo  * Validation of super block at write time.
268275cb857dSQu Wenruo  * Some checks like bytenr check will be skipped as their values will be
268375cb857dSQu Wenruo  * overwritten soon.
268475cb857dSQu Wenruo  * Extra checks like csum type and incompat flags will be done here.
268575cb857dSQu Wenruo  */
268675cb857dSQu Wenruo static int btrfs_validate_write_super(struct btrfs_fs_info *fs_info,
268775cb857dSQu Wenruo 				      struct btrfs_super_block *sb)
268875cb857dSQu Wenruo {
268975cb857dSQu Wenruo 	int ret;
269075cb857dSQu Wenruo 
2691a05d3c91SQu Wenruo 	ret = btrfs_validate_super(fs_info, sb, -1);
269275cb857dSQu Wenruo 	if (ret < 0)
269375cb857dSQu Wenruo 		goto out;
2694e7e16f48SJohannes Thumshirn 	if (!btrfs_supported_super_csum(btrfs_super_csum_type(sb))) {
269575cb857dSQu Wenruo 		ret = -EUCLEAN;
269675cb857dSQu Wenruo 		btrfs_err(fs_info, "invalid csum type, has %u want %u",
269775cb857dSQu Wenruo 			  btrfs_super_csum_type(sb), BTRFS_CSUM_TYPE_CRC32);
269875cb857dSQu Wenruo 		goto out;
269975cb857dSQu Wenruo 	}
270075cb857dSQu Wenruo 	if (btrfs_super_incompat_flags(sb) & ~BTRFS_FEATURE_INCOMPAT_SUPP) {
270175cb857dSQu Wenruo 		ret = -EUCLEAN;
270275cb857dSQu Wenruo 		btrfs_err(fs_info,
270375cb857dSQu Wenruo 		"invalid incompat flags, has 0x%llx valid mask 0x%llx",
270475cb857dSQu Wenruo 			  btrfs_super_incompat_flags(sb),
270575cb857dSQu Wenruo 			  (unsigned long long)BTRFS_FEATURE_INCOMPAT_SUPP);
270675cb857dSQu Wenruo 		goto out;
270775cb857dSQu Wenruo 	}
270875cb857dSQu Wenruo out:
270975cb857dSQu Wenruo 	if (ret < 0)
271075cb857dSQu Wenruo 		btrfs_err(fs_info,
271175cb857dSQu Wenruo 		"super block corruption detected before writing it to disk");
271275cb857dSQu Wenruo 	return ret;
271375cb857dSQu Wenruo }
271475cb857dSQu Wenruo 
2715bd676446SJosef Bacik static int load_super_root(struct btrfs_root *root, u64 bytenr, u64 gen, int level)
2716bd676446SJosef Bacik {
2717789d6a3aSQu Wenruo 	struct btrfs_tree_parent_check check = {
2718789d6a3aSQu Wenruo 		.level = level,
2719789d6a3aSQu Wenruo 		.transid = gen,
2720789d6a3aSQu Wenruo 		.owner_root = root->root_key.objectid
2721789d6a3aSQu Wenruo 	};
2722bd676446SJosef Bacik 	int ret = 0;
2723bd676446SJosef Bacik 
2724789d6a3aSQu Wenruo 	root->node = read_tree_block(root->fs_info, bytenr, &check);
2725bd676446SJosef Bacik 	if (IS_ERR(root->node)) {
2726bd676446SJosef Bacik 		ret = PTR_ERR(root->node);
2727bd676446SJosef Bacik 		root->node = NULL;
27284eb150d6SQu Wenruo 		return ret;
27294eb150d6SQu Wenruo 	}
27304eb150d6SQu Wenruo 	if (!extent_buffer_uptodate(root->node)) {
2731bd676446SJosef Bacik 		free_extent_buffer(root->node);
2732bd676446SJosef Bacik 		root->node = NULL;
27334eb150d6SQu Wenruo 		return -EIO;
2734bd676446SJosef Bacik 	}
2735bd676446SJosef Bacik 
2736bd676446SJosef Bacik 	btrfs_set_root_node(&root->root_item, root->node);
2737bd676446SJosef Bacik 	root->commit_root = btrfs_root_node(root);
2738bd676446SJosef Bacik 	btrfs_set_root_refs(&root->root_item, 1);
2739bd676446SJosef Bacik 	return ret;
2740bd676446SJosef Bacik }
2741bd676446SJosef Bacik 
2742bd676446SJosef Bacik static int load_important_roots(struct btrfs_fs_info *fs_info)
2743bd676446SJosef Bacik {
2744bd676446SJosef Bacik 	struct btrfs_super_block *sb = fs_info->super_copy;
2745bd676446SJosef Bacik 	u64 gen, bytenr;
2746bd676446SJosef Bacik 	int level, ret;
2747bd676446SJosef Bacik 
2748bd676446SJosef Bacik 	bytenr = btrfs_super_root(sb);
2749bd676446SJosef Bacik 	gen = btrfs_super_generation(sb);
2750bd676446SJosef Bacik 	level = btrfs_super_root_level(sb);
2751bd676446SJosef Bacik 	ret = load_super_root(fs_info->tree_root, bytenr, gen, level);
27529c54e80dSJosef Bacik 	if (ret) {
2753bd676446SJosef Bacik 		btrfs_warn(fs_info, "couldn't read tree root");
2754bd676446SJosef Bacik 		return ret;
2755bd676446SJosef Bacik 	}
27569c54e80dSJosef Bacik 	return 0;
27579c54e80dSJosef Bacik }
27589c54e80dSJosef Bacik 
27596ef108ddSNikolay Borisov static int __cold init_tree_roots(struct btrfs_fs_info *fs_info)
2760b8522a1eSNikolay Borisov {
27616ef108ddSNikolay Borisov 	int backup_index = find_newest_super_backup(fs_info);
2762b8522a1eSNikolay Borisov 	struct btrfs_super_block *sb = fs_info->super_copy;
2763b8522a1eSNikolay Borisov 	struct btrfs_root *tree_root = fs_info->tree_root;
2764b8522a1eSNikolay Borisov 	bool handle_error = false;
2765b8522a1eSNikolay Borisov 	int ret = 0;
2766b8522a1eSNikolay Borisov 	int i;
2767b8522a1eSNikolay Borisov 
2768b8522a1eSNikolay Borisov 	for (i = 0; i < BTRFS_NUM_BACKUP_ROOTS; i++) {
2769b8522a1eSNikolay Borisov 		if (handle_error) {
2770b8522a1eSNikolay Borisov 			if (!IS_ERR(tree_root->node))
2771b8522a1eSNikolay Borisov 				free_extent_buffer(tree_root->node);
2772b8522a1eSNikolay Borisov 			tree_root->node = NULL;
2773b8522a1eSNikolay Borisov 
2774b8522a1eSNikolay Borisov 			if (!btrfs_test_opt(fs_info, USEBACKUPROOT))
2775b8522a1eSNikolay Borisov 				break;
2776b8522a1eSNikolay Borisov 
2777b8522a1eSNikolay Borisov 			free_root_pointers(fs_info, 0);
2778b8522a1eSNikolay Borisov 
2779b8522a1eSNikolay Borisov 			/*
2780b8522a1eSNikolay Borisov 			 * Don't use the log in recovery mode, it won't be
2781b8522a1eSNikolay Borisov 			 * valid
2782b8522a1eSNikolay Borisov 			 */
2783b8522a1eSNikolay Borisov 			btrfs_set_super_log_root(sb, 0);
2784b8522a1eSNikolay Borisov 
2785b8522a1eSNikolay Borisov 			/* We can't trust the free space cache either */
2786b8522a1eSNikolay Borisov 			btrfs_set_opt(fs_info->mount_opt, CLEAR_CACHE);
2787b8522a1eSNikolay Borisov 
2788745806fbSQu Wenruo 			btrfs_warn(fs_info, "try to load backup roots slot %d", i);
2789b8522a1eSNikolay Borisov 			ret = read_backup_root(fs_info, i);
27906ef108ddSNikolay Borisov 			backup_index = ret;
2791b8522a1eSNikolay Borisov 			if (ret < 0)
2792b8522a1eSNikolay Borisov 				return ret;
2793b8522a1eSNikolay Borisov 		}
2794b8522a1eSNikolay Borisov 
2795bd676446SJosef Bacik 		ret = load_important_roots(fs_info);
2796bd676446SJosef Bacik 		if (ret) {
2797217f5004SNikolay Borisov 			handle_error = true;
2798b8522a1eSNikolay Borisov 			continue;
2799b8522a1eSNikolay Borisov 		}
2800b8522a1eSNikolay Borisov 
2801336a0d8dSNikolay Borisov 		/*
2802336a0d8dSNikolay Borisov 		 * No need to hold btrfs_root::objectid_mutex since the fs
2803336a0d8dSNikolay Borisov 		 * hasn't been fully initialised and we are the only user
2804336a0d8dSNikolay Borisov 		 */
2805453e4873SNikolay Borisov 		ret = btrfs_init_root_free_objectid(tree_root);
2806b8522a1eSNikolay Borisov 		if (ret < 0) {
2807b8522a1eSNikolay Borisov 			handle_error = true;
2808b8522a1eSNikolay Borisov 			continue;
2809b8522a1eSNikolay Borisov 		}
2810b8522a1eSNikolay Borisov 
28116b8fad57SNikolay Borisov 		ASSERT(tree_root->free_objectid <= BTRFS_LAST_FREE_OBJECTID);
2812b8522a1eSNikolay Borisov 
2813b8522a1eSNikolay Borisov 		ret = btrfs_read_roots(fs_info);
2814b8522a1eSNikolay Borisov 		if (ret < 0) {
2815b8522a1eSNikolay Borisov 			handle_error = true;
2816b8522a1eSNikolay Borisov 			continue;
2817b8522a1eSNikolay Borisov 		}
2818b8522a1eSNikolay Borisov 
2819b8522a1eSNikolay Borisov 		/* All successful */
2820bd676446SJosef Bacik 		fs_info->generation = btrfs_header_generation(tree_root->node);
2821bd676446SJosef Bacik 		fs_info->last_trans_committed = fs_info->generation;
2822d96b3424SFilipe Manana 		fs_info->last_reloc_trans = 0;
28236ef108ddSNikolay Borisov 
28246ef108ddSNikolay Borisov 		/* Always begin writing backup roots after the one being used */
28256ef108ddSNikolay Borisov 		if (backup_index < 0) {
28266ef108ddSNikolay Borisov 			fs_info->backup_root_index = 0;
28276ef108ddSNikolay Borisov 		} else {
28286ef108ddSNikolay Borisov 			fs_info->backup_root_index = backup_index + 1;
28296ef108ddSNikolay Borisov 			fs_info->backup_root_index %= BTRFS_NUM_BACKUP_ROOTS;
28306ef108ddSNikolay Borisov 		}
2831b8522a1eSNikolay Borisov 		break;
2832b8522a1eSNikolay Borisov 	}
2833b8522a1eSNikolay Borisov 
2834b8522a1eSNikolay Borisov 	return ret;
2835b8522a1eSNikolay Borisov }
2836b8522a1eSNikolay Borisov 
28378260edbaSJosef Bacik void btrfs_init_fs_info(struct btrfs_fs_info *fs_info)
2838eb60ceacSChris Mason {
2839fc7cbcd4SDavid Sterba 	INIT_RADIX_TREE(&fs_info->fs_roots_radix, GFP_ATOMIC);
284001cd3909SDavid Sterba 	INIT_RADIX_TREE(&fs_info->buffer_radix, GFP_ATOMIC);
28418fd17795SChris Mason 	INIT_LIST_HEAD(&fs_info->trans_list);
2842facda1e7SChris Mason 	INIT_LIST_HEAD(&fs_info->dead_roots);
284324bbcf04SYan, Zheng 	INIT_LIST_HEAD(&fs_info->delayed_iputs);
2844eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&fs_info->delalloc_roots);
284511833d66SYan Zheng 	INIT_LIST_HEAD(&fs_info->caching_block_groups);
2846eb73c1b7SMiao Xie 	spin_lock_init(&fs_info->delalloc_root_lock);
2847a4abeea4SJosef Bacik 	spin_lock_init(&fs_info->trans_lock);
2848fc7cbcd4SDavid Sterba 	spin_lock_init(&fs_info->fs_roots_radix_lock);
284924bbcf04SYan, Zheng 	spin_lock_init(&fs_info->delayed_iput_lock);
28504cb5300bSChris Mason 	spin_lock_init(&fs_info->defrag_inodes_lock);
2851ceda0864SMiao Xie 	spin_lock_init(&fs_info->super_lock);
2852f28491e0SJosef Bacik 	spin_lock_init(&fs_info->buffer_lock);
285347ab2a6cSJosef Bacik 	spin_lock_init(&fs_info->unused_bgs_lock);
285440ab3be1SNaohiro Aota 	spin_lock_init(&fs_info->treelog_bg_lock);
2855afba2bc0SNaohiro Aota 	spin_lock_init(&fs_info->zone_active_bgs_lock);
2856c2707a25SJohannes Thumshirn 	spin_lock_init(&fs_info->relocation_bg_lock);
2857f29021b2SJan Schmidt 	rwlock_init(&fs_info->tree_mod_log_lock);
2858abed4aaaSJosef Bacik 	rwlock_init(&fs_info->global_root_lock);
2859d7c15171SZhao Lei 	mutex_init(&fs_info->unused_bg_unpin_mutex);
2860f3372065SJohannes Thumshirn 	mutex_init(&fs_info->reclaim_bgs_lock);
28617585717fSChris Mason 	mutex_init(&fs_info->reloc_mutex);
2862573bfb72SMiao Xie 	mutex_init(&fs_info->delalloc_root_mutex);
28630bc09ca1SNaohiro Aota 	mutex_init(&fs_info->zoned_meta_io_lock);
28645f0addf7SNaohiro Aota 	mutex_init(&fs_info->zoned_data_reloc_io_lock);
2865de98ced9SMiao Xie 	seqlock_init(&fs_info->profiles_lock);
286619c00ddcSChris Mason 
2867e1489b4fSIoannis Angelakopoulos 	btrfs_lockdep_init_map(fs_info, btrfs_trans_num_writers);
28685a9ba670SIoannis Angelakopoulos 	btrfs_lockdep_init_map(fs_info, btrfs_trans_num_extwriters);
28698b53779eSIoannis Angelakopoulos 	btrfs_lockdep_init_map(fs_info, btrfs_trans_pending_ordered);
28705f4403e1SIoannis Angelakopoulos 	btrfs_lockdep_init_map(fs_info, btrfs_ordered_extent);
28713e738c53SIoannis Angelakopoulos 	btrfs_state_lockdep_init_map(fs_info, btrfs_trans_commit_start,
28723e738c53SIoannis Angelakopoulos 				     BTRFS_LOCKDEP_TRANS_COMMIT_START);
28733e738c53SIoannis Angelakopoulos 	btrfs_state_lockdep_init_map(fs_info, btrfs_trans_unblocked,
28743e738c53SIoannis Angelakopoulos 				     BTRFS_LOCKDEP_TRANS_UNBLOCKED);
28753e738c53SIoannis Angelakopoulos 	btrfs_state_lockdep_init_map(fs_info, btrfs_trans_super_committed,
28763e738c53SIoannis Angelakopoulos 				     BTRFS_LOCKDEP_TRANS_SUPER_COMMITTED);
28773e738c53SIoannis Angelakopoulos 	btrfs_state_lockdep_init_map(fs_info, btrfs_trans_completed,
28783e738c53SIoannis Angelakopoulos 				     BTRFS_LOCKDEP_TRANS_COMPLETED);
2879e1489b4fSIoannis Angelakopoulos 
28800b86a832SChris Mason 	INIT_LIST_HEAD(&fs_info->dirty_cowonly_roots);
28816324fbf3SChris Mason 	INIT_LIST_HEAD(&fs_info->space_info);
2882f29021b2SJan Schmidt 	INIT_LIST_HEAD(&fs_info->tree_mod_seq_list);
288347ab2a6cSJosef Bacik 	INIT_LIST_HEAD(&fs_info->unused_bgs);
288418bb8bbfSJohannes Thumshirn 	INIT_LIST_HEAD(&fs_info->reclaim_bgs);
2885afba2bc0SNaohiro Aota 	INIT_LIST_HEAD(&fs_info->zone_active_bgs);
2886bd647ce3SJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
2887bd647ce3SJosef Bacik 	INIT_LIST_HEAD(&fs_info->allocated_roots);
28883fd63727SJosef Bacik 	INIT_LIST_HEAD(&fs_info->allocated_ebs);
28893fd63727SJosef Bacik 	spin_lock_init(&fs_info->eb_leak_lock);
2890bd647ce3SJosef Bacik #endif
2891c8bf1b67SDavid Sterba 	extent_map_tree_init(&fs_info->mapping_tree);
289266d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->global_block_rsv,
289366d8f3ddSMiao Xie 			     BTRFS_BLOCK_RSV_GLOBAL);
289466d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->trans_block_rsv, BTRFS_BLOCK_RSV_TRANS);
289566d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->chunk_block_rsv, BTRFS_BLOCK_RSV_CHUNK);
289666d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->empty_block_rsv, BTRFS_BLOCK_RSV_EMPTY);
289766d8f3ddSMiao Xie 	btrfs_init_block_rsv(&fs_info->delayed_block_rsv,
289866d8f3ddSMiao Xie 			     BTRFS_BLOCK_RSV_DELOPS);
2899ba2c4d4eSJosef Bacik 	btrfs_init_block_rsv(&fs_info->delayed_refs_rsv,
2900ba2c4d4eSJosef Bacik 			     BTRFS_BLOCK_RSV_DELREFS);
2901ba2c4d4eSJosef Bacik 
2902771ed689SChris Mason 	atomic_set(&fs_info->async_delalloc_pages, 0);
29034cb5300bSChris Mason 	atomic_set(&fs_info->defrag_running, 0);
2904034f784dSJosef Bacik 	atomic_set(&fs_info->nr_delayed_iputs, 0);
2905fc36ed7eSJan Schmidt 	atomic64_set(&fs_info->tree_mod_seq, 0);
2906abed4aaaSJosef Bacik 	fs_info->global_root_tree = RB_ROOT;
290795ac567aSFilipe David Borba Manana 	fs_info->max_inline = BTRFS_DEFAULT_MAX_INLINE;
29089ed74f2dSJosef Bacik 	fs_info->metadata_ratio = 0;
29094cb5300bSChris Mason 	fs_info->defrag_inodes = RB_ROOT;
2910a5ed45f8SNikolay Borisov 	atomic64_set(&fs_info->free_chunk_space, 0);
2911f29021b2SJan Schmidt 	fs_info->tree_mod_log = RB_ROOT;
29128b87dc17SDavid Sterba 	fs_info->commit_interval = BTRFS_DEFAULT_COMMIT_INTERVAL;
2913fd708b81SJosef Bacik 	btrfs_init_ref_verify(fs_info);
2914c8b97818SChris Mason 
2915b34b086cSChris Mason 	fs_info->thread_pool_size = min_t(unsigned long,
2916b34b086cSChris Mason 					  num_online_cpus() + 2, 8);
29170afbaf8cSChris Mason 
2918199c2a9cSMiao Xie 	INIT_LIST_HEAD(&fs_info->ordered_roots);
2919199c2a9cSMiao Xie 	spin_lock_init(&fs_info->ordered_root_lock);
292069fe2d75SJosef Bacik 
2921638aa7edSEric Sandeen 	btrfs_init_scrub(fs_info);
292221adbd5cSStefan Behrens #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
292321adbd5cSStefan Behrens 	fs_info->check_integrity_print_mask = 0;
292421adbd5cSStefan Behrens #endif
2925779a65a4SEric Sandeen 	btrfs_init_balance(fs_info);
292657056740SJosef Bacik 	btrfs_init_async_reclaim_work(fs_info);
2927a2de733cSArne Jansen 
292816b0c258SFilipe Manana 	rwlock_init(&fs_info->block_group_cache_lock);
292908dddb29SFilipe Manana 	fs_info->block_group_cache_tree = RB_ROOT_CACHED;
29300f9dd46cSJosef Bacik 
2931fe119a6eSNikolay Borisov 	extent_io_tree_init(fs_info, &fs_info->excluded_extents,
293235da5a7eSDavid Sterba 			    IO_TREE_FS_EXCLUDED_EXTENTS);
293339279cc3SChris Mason 
29345a3f23d5SChris Mason 	mutex_init(&fs_info->ordered_operations_mutex);
2935e02119d5SChris Mason 	mutex_init(&fs_info->tree_log_mutex);
2936925baeddSChris Mason 	mutex_init(&fs_info->chunk_mutex);
2937a74a4b97SChris Mason 	mutex_init(&fs_info->transaction_kthread_mutex);
2938a74a4b97SChris Mason 	mutex_init(&fs_info->cleaner_mutex);
29391bbc621eSChris Mason 	mutex_init(&fs_info->ro_block_group_mutex);
29409e351cc8SJosef Bacik 	init_rwsem(&fs_info->commit_root_sem);
2941c71bf099SYan, Zheng 	init_rwsem(&fs_info->cleanup_work_sem);
294276dda93cSYan, Zheng 	init_rwsem(&fs_info->subvol_sem);
2943803b2f54SStefan Behrens 	sema_init(&fs_info->uuid_tree_rescan_sem, 1);
2944fa9c0d79SChris Mason 
2945ad618368SEric Sandeen 	btrfs_init_dev_replace_locks(fs_info);
2946f9e92e40SEric Sandeen 	btrfs_init_qgroup(fs_info);
2947b0643e59SDennis Zhou 	btrfs_discard_init(fs_info);
2948416ac51dSArne Jansen 
2949fa9c0d79SChris Mason 	btrfs_init_free_cluster(&fs_info->meta_alloc_cluster);
2950fa9c0d79SChris Mason 	btrfs_init_free_cluster(&fs_info->data_alloc_cluster);
2951fa9c0d79SChris Mason 
2952e6dcd2dcSChris Mason 	init_waitqueue_head(&fs_info->transaction_throttle);
2953f9295749SChris Mason 	init_waitqueue_head(&fs_info->transaction_wait);
2954bb9c12c9SSage Weil 	init_waitqueue_head(&fs_info->transaction_blocked_wait);
29554854ddd0SChris Mason 	init_waitqueue_head(&fs_info->async_submit_wait);
2956034f784dSJosef Bacik 	init_waitqueue_head(&fs_info->delayed_iputs_wait);
29573768f368SChris Mason 
2958da17066cSJeff Mahoney 	/* Usable values until the real ones are cached from the superblock */
2959da17066cSJeff Mahoney 	fs_info->nodesize = 4096;
2960da17066cSJeff Mahoney 	fs_info->sectorsize = 4096;
2961ab108d99SDavid Sterba 	fs_info->sectorsize_bits = ilog2(4096);
2962da17066cSJeff Mahoney 	fs_info->stripesize = 4096;
2963da17066cSJeff Mahoney 
2964f7b12a62SNaohiro Aota 	fs_info->max_extent_size = BTRFS_MAX_EXTENT_SIZE;
2965f7b12a62SNaohiro Aota 
2966eede2bf3SOmar Sandoval 	spin_lock_init(&fs_info->swapfile_pins_lock);
2967eede2bf3SOmar Sandoval 	fs_info->swapfile_pins = RB_ROOT;
2968eede2bf3SOmar Sandoval 
296918bb8bbfSJohannes Thumshirn 	fs_info->bg_reclaim_threshold = BTRFS_DEFAULT_RECLAIM_THRESH;
297018bb8bbfSJohannes Thumshirn 	INIT_WORK(&fs_info->reclaim_bgs_work, btrfs_reclaim_bgs_work);
29718260edbaSJosef Bacik }
29728260edbaSJosef Bacik 
29738260edbaSJosef Bacik static int init_mount_fs_info(struct btrfs_fs_info *fs_info, struct super_block *sb)
29748260edbaSJosef Bacik {
29758260edbaSJosef Bacik 	int ret;
29768260edbaSJosef Bacik 
29778260edbaSJosef Bacik 	fs_info->sb = sb;
29788260edbaSJosef Bacik 	sb->s_blocksize = BTRFS_BDEV_BLOCKSIZE;
29798260edbaSJosef Bacik 	sb->s_blocksize_bits = blksize_bits(BTRFS_BDEV_BLOCKSIZE);
29809e967495SFilipe Manana 
29815deb17e1SJosef Bacik 	ret = percpu_counter_init(&fs_info->ordered_bytes, 0, GFP_KERNEL);
2982ae18c37aSJosef Bacik 	if (ret)
2983ae18c37aSJosef Bacik 		return ret;
2984ae18c37aSJosef Bacik 
2985ae18c37aSJosef Bacik 	ret = percpu_counter_init(&fs_info->dirty_metadata_bytes, 0, GFP_KERNEL);
2986ae18c37aSJosef Bacik 	if (ret)
2987c75e8394SJosef Bacik 		return ret;
2988ae18c37aSJosef Bacik 
2989ae18c37aSJosef Bacik 	fs_info->dirty_metadata_batch = PAGE_SIZE *
2990ae18c37aSJosef Bacik 					(1 + ilog2(nr_cpu_ids));
2991ae18c37aSJosef Bacik 
2992ae18c37aSJosef Bacik 	ret = percpu_counter_init(&fs_info->delalloc_bytes, 0, GFP_KERNEL);
2993ae18c37aSJosef Bacik 	if (ret)
2994c75e8394SJosef Bacik 		return ret;
2995ae18c37aSJosef Bacik 
2996ae18c37aSJosef Bacik 	ret = percpu_counter_init(&fs_info->dev_replace.bio_counter, 0,
2997ae18c37aSJosef Bacik 			GFP_KERNEL);
2998ae18c37aSJosef Bacik 	if (ret)
2999c75e8394SJosef Bacik 		return ret;
3000ae18c37aSJosef Bacik 
3001ae18c37aSJosef Bacik 	fs_info->delayed_root = kmalloc(sizeof(struct btrfs_delayed_root),
3002ae18c37aSJosef Bacik 					GFP_KERNEL);
3003c75e8394SJosef Bacik 	if (!fs_info->delayed_root)
3004c75e8394SJosef Bacik 		return -ENOMEM;
3005ae18c37aSJosef Bacik 	btrfs_init_delayed_root(fs_info->delayed_root);
3006ae18c37aSJosef Bacik 
3007a0a1db70SFilipe Manana 	if (sb_rdonly(sb))
3008a0a1db70SFilipe Manana 		set_bit(BTRFS_FS_STATE_RO, &fs_info->fs_state);
3009a0a1db70SFilipe Manana 
3010c75e8394SJosef Bacik 	return btrfs_alloc_stripe_hash_table(fs_info);
3011ae18c37aSJosef Bacik }
3012ae18c37aSJosef Bacik 
301397f4dd09SNikolay Borisov static int btrfs_uuid_rescan_kthread(void *data)
301497f4dd09SNikolay Borisov {
30150d031dc4SYu Zhe 	struct btrfs_fs_info *fs_info = data;
301697f4dd09SNikolay Borisov 	int ret;
301797f4dd09SNikolay Borisov 
301897f4dd09SNikolay Borisov 	/*
301997f4dd09SNikolay Borisov 	 * 1st step is to iterate through the existing UUID tree and
302097f4dd09SNikolay Borisov 	 * to delete all entries that contain outdated data.
302197f4dd09SNikolay Borisov 	 * 2nd step is to add all missing entries to the UUID tree.
302297f4dd09SNikolay Borisov 	 */
302397f4dd09SNikolay Borisov 	ret = btrfs_uuid_tree_iterate(fs_info);
302497f4dd09SNikolay Borisov 	if (ret < 0) {
3025c94bec2cSJosef Bacik 		if (ret != -EINTR)
3026c94bec2cSJosef Bacik 			btrfs_warn(fs_info, "iterating uuid_tree failed %d",
3027c94bec2cSJosef Bacik 				   ret);
302897f4dd09SNikolay Borisov 		up(&fs_info->uuid_tree_rescan_sem);
302997f4dd09SNikolay Borisov 		return ret;
303097f4dd09SNikolay Borisov 	}
303197f4dd09SNikolay Borisov 	return btrfs_uuid_scan_kthread(data);
303297f4dd09SNikolay Borisov }
303397f4dd09SNikolay Borisov 
303497f4dd09SNikolay Borisov static int btrfs_check_uuid_tree(struct btrfs_fs_info *fs_info)
303597f4dd09SNikolay Borisov {
303697f4dd09SNikolay Borisov 	struct task_struct *task;
303797f4dd09SNikolay Borisov 
303897f4dd09SNikolay Borisov 	down(&fs_info->uuid_tree_rescan_sem);
303997f4dd09SNikolay Borisov 	task = kthread_run(btrfs_uuid_rescan_kthread, fs_info, "btrfs-uuid");
304097f4dd09SNikolay Borisov 	if (IS_ERR(task)) {
304197f4dd09SNikolay Borisov 		/* fs_info->update_uuid_tree_gen remains 0 in all error case */
304297f4dd09SNikolay Borisov 		btrfs_warn(fs_info, "failed to start uuid_rescan task");
304397f4dd09SNikolay Borisov 		up(&fs_info->uuid_tree_rescan_sem);
304497f4dd09SNikolay Borisov 		return PTR_ERR(task);
304597f4dd09SNikolay Borisov 	}
304697f4dd09SNikolay Borisov 
304797f4dd09SNikolay Borisov 	return 0;
304897f4dd09SNikolay Borisov }
304997f4dd09SNikolay Borisov 
305044c0ca21SBoris Burkov /*
30518cd29088SBoris Burkov  * Some options only have meaning at mount time and shouldn't persist across
30528cd29088SBoris Burkov  * remounts, or be displayed. Clear these at the end of mount and remount
30538cd29088SBoris Burkov  * code paths.
30548cd29088SBoris Burkov  */
30558cd29088SBoris Burkov void btrfs_clear_oneshot_options(struct btrfs_fs_info *fs_info)
30568cd29088SBoris Burkov {
30578cd29088SBoris Burkov 	btrfs_clear_opt(fs_info->mount_opt, USEBACKUPROOT);
30588b228324SBoris Burkov 	btrfs_clear_opt(fs_info->mount_opt, CLEAR_CACHE);
30598cd29088SBoris Burkov }
30608cd29088SBoris Burkov 
30618cd29088SBoris Burkov /*
306244c0ca21SBoris Burkov  * Mounting logic specific to read-write file systems. Shared by open_ctree
306344c0ca21SBoris Burkov  * and btrfs_remount when remounting from read-only to read-write.
306444c0ca21SBoris Burkov  */
306544c0ca21SBoris Burkov int btrfs_start_pre_rw_mount(struct btrfs_fs_info *fs_info)
306644c0ca21SBoris Burkov {
306744c0ca21SBoris Burkov 	int ret;
306894846229SBoris Burkov 	const bool cache_opt = btrfs_test_opt(fs_info, SPACE_CACHE);
30691d6a4fc8SQu Wenruo 	bool rebuild_free_space_tree = false;
30708b228324SBoris Burkov 
30718b228324SBoris Burkov 	if (btrfs_test_opt(fs_info, CLEAR_CACHE) &&
30728b228324SBoris Burkov 	    btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
30731d6a4fc8SQu Wenruo 		rebuild_free_space_tree = true;
30748b228324SBoris Burkov 	} else if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE) &&
30758b228324SBoris Burkov 		   !btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE_VALID)) {
30768b228324SBoris Burkov 		btrfs_warn(fs_info, "free space tree is invalid");
30771d6a4fc8SQu Wenruo 		rebuild_free_space_tree = true;
30788b228324SBoris Burkov 	}
30798b228324SBoris Burkov 
30801d6a4fc8SQu Wenruo 	if (rebuild_free_space_tree) {
30811d6a4fc8SQu Wenruo 		btrfs_info(fs_info, "rebuilding free space tree");
30821d6a4fc8SQu Wenruo 		ret = btrfs_rebuild_free_space_tree(fs_info);
30838b228324SBoris Burkov 		if (ret) {
30848b228324SBoris Burkov 			btrfs_warn(fs_info,
30851d6a4fc8SQu Wenruo 				   "failed to rebuild free space tree: %d", ret);
30861d6a4fc8SQu Wenruo 			goto out;
30871d6a4fc8SQu Wenruo 		}
30881d6a4fc8SQu Wenruo 	}
30891d6a4fc8SQu Wenruo 
30901d6a4fc8SQu Wenruo 	if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE) &&
30911d6a4fc8SQu Wenruo 	    !btrfs_test_opt(fs_info, FREE_SPACE_TREE)) {
30921d6a4fc8SQu Wenruo 		btrfs_info(fs_info, "disabling free space tree");
30931d6a4fc8SQu Wenruo 		ret = btrfs_delete_free_space_tree(fs_info);
30941d6a4fc8SQu Wenruo 		if (ret) {
30951d6a4fc8SQu Wenruo 			btrfs_warn(fs_info,
30961d6a4fc8SQu Wenruo 				   "failed to disable free space tree: %d", ret);
30978b228324SBoris Burkov 			goto out;
30988b228324SBoris Burkov 		}
30998b228324SBoris Burkov 	}
310044c0ca21SBoris Burkov 
31018d488a8cSFilipe Manana 	/*
31028d488a8cSFilipe Manana 	 * btrfs_find_orphan_roots() is responsible for finding all the dead
31038d488a8cSFilipe Manana 	 * roots (with 0 refs), flag them with BTRFS_ROOT_DEAD_TREE and load
3104fc7cbcd4SDavid Sterba 	 * them into the fs_info->fs_roots_radix tree. This must be done before
31058d488a8cSFilipe Manana 	 * calling btrfs_orphan_cleanup() on the tree root. If we don't do it
31068d488a8cSFilipe Manana 	 * first, then btrfs_orphan_cleanup() will delete a dead root's orphan
31078d488a8cSFilipe Manana 	 * item before the root's tree is deleted - this means that if we unmount
31088d488a8cSFilipe Manana 	 * or crash before the deletion completes, on the next mount we will not
31098d488a8cSFilipe Manana 	 * delete what remains of the tree because the orphan item does not
31108d488a8cSFilipe Manana 	 * exists anymore, which is what tells us we have a pending deletion.
31118d488a8cSFilipe Manana 	 */
31128d488a8cSFilipe Manana 	ret = btrfs_find_orphan_roots(fs_info);
31138d488a8cSFilipe Manana 	if (ret)
31148d488a8cSFilipe Manana 		goto out;
31158d488a8cSFilipe Manana 
311644c0ca21SBoris Burkov 	ret = btrfs_cleanup_fs_roots(fs_info);
311744c0ca21SBoris Burkov 	if (ret)
311844c0ca21SBoris Burkov 		goto out;
311944c0ca21SBoris Burkov 
31208f1c21d7SBoris Burkov 	down_read(&fs_info->cleanup_work_sem);
31218f1c21d7SBoris Burkov 	if ((ret = btrfs_orphan_cleanup(fs_info->fs_root)) ||
31228f1c21d7SBoris Burkov 	    (ret = btrfs_orphan_cleanup(fs_info->tree_root))) {
31238f1c21d7SBoris Burkov 		up_read(&fs_info->cleanup_work_sem);
31248f1c21d7SBoris Burkov 		goto out;
31258f1c21d7SBoris Burkov 	}
31268f1c21d7SBoris Burkov 	up_read(&fs_info->cleanup_work_sem);
31278f1c21d7SBoris Burkov 
312844c0ca21SBoris Burkov 	mutex_lock(&fs_info->cleaner_mutex);
31297eefae6bSJosef Bacik 	ret = btrfs_recover_relocation(fs_info);
313044c0ca21SBoris Burkov 	mutex_unlock(&fs_info->cleaner_mutex);
313144c0ca21SBoris Burkov 	if (ret < 0) {
313244c0ca21SBoris Burkov 		btrfs_warn(fs_info, "failed to recover relocation: %d", ret);
313344c0ca21SBoris Burkov 		goto out;
313444c0ca21SBoris Burkov 	}
313544c0ca21SBoris Burkov 
31365011139aSBoris Burkov 	if (btrfs_test_opt(fs_info, FREE_SPACE_TREE) &&
31375011139aSBoris Burkov 	    !btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
31385011139aSBoris Burkov 		btrfs_info(fs_info, "creating free space tree");
31395011139aSBoris Burkov 		ret = btrfs_create_free_space_tree(fs_info);
31405011139aSBoris Burkov 		if (ret) {
31415011139aSBoris Burkov 			btrfs_warn(fs_info,
31425011139aSBoris Burkov 				"failed to create free space tree: %d", ret);
31435011139aSBoris Burkov 			goto out;
31445011139aSBoris Burkov 		}
31455011139aSBoris Burkov 	}
31465011139aSBoris Burkov 
314794846229SBoris Burkov 	if (cache_opt != btrfs_free_space_cache_v1_active(fs_info)) {
314894846229SBoris Burkov 		ret = btrfs_set_free_space_cache_v1_active(fs_info, cache_opt);
314994846229SBoris Burkov 		if (ret)
315094846229SBoris Burkov 			goto out;
315194846229SBoris Burkov 	}
315294846229SBoris Burkov 
315344c0ca21SBoris Burkov 	ret = btrfs_resume_balance_async(fs_info);
315444c0ca21SBoris Burkov 	if (ret)
315544c0ca21SBoris Burkov 		goto out;
315644c0ca21SBoris Burkov 
315744c0ca21SBoris Burkov 	ret = btrfs_resume_dev_replace_async(fs_info);
315844c0ca21SBoris Burkov 	if (ret) {
315944c0ca21SBoris Burkov 		btrfs_warn(fs_info, "failed to resume dev_replace");
316044c0ca21SBoris Burkov 		goto out;
316144c0ca21SBoris Burkov 	}
316244c0ca21SBoris Burkov 
316344c0ca21SBoris Burkov 	btrfs_qgroup_rescan_resume(fs_info);
316444c0ca21SBoris Burkov 
316544c0ca21SBoris Burkov 	if (!fs_info->uuid_root) {
316644c0ca21SBoris Burkov 		btrfs_info(fs_info, "creating UUID tree");
316744c0ca21SBoris Burkov 		ret = btrfs_create_uuid_tree(fs_info);
316844c0ca21SBoris Burkov 		if (ret) {
316944c0ca21SBoris Burkov 			btrfs_warn(fs_info,
317044c0ca21SBoris Burkov 				   "failed to create the UUID tree %d", ret);
317144c0ca21SBoris Burkov 			goto out;
317244c0ca21SBoris Burkov 		}
317344c0ca21SBoris Burkov 	}
317444c0ca21SBoris Burkov 
317544c0ca21SBoris Burkov out:
317644c0ca21SBoris Burkov 	return ret;
317744c0ca21SBoris Burkov }
317844c0ca21SBoris Burkov 
3179d7f67ac9SQu Wenruo /*
3180d7f67ac9SQu Wenruo  * Do various sanity and dependency checks of different features.
3181d7f67ac9SQu Wenruo  *
31822ba48b20SQu Wenruo  * @is_rw_mount:	If the mount is read-write.
31832ba48b20SQu Wenruo  *
3184d7f67ac9SQu Wenruo  * This is the place for less strict checks (like for subpage or artificial
3185d7f67ac9SQu Wenruo  * feature dependencies).
3186d7f67ac9SQu Wenruo  *
3187d7f67ac9SQu Wenruo  * For strict checks or possible corruption detection, see
3188d7f67ac9SQu Wenruo  * btrfs_validate_super().
3189d7f67ac9SQu Wenruo  *
3190d7f67ac9SQu Wenruo  * This should be called after btrfs_parse_options(), as some mount options
3191d7f67ac9SQu Wenruo  * (space cache related) can modify on-disk format like free space tree and
3192d7f67ac9SQu Wenruo  * screw up certain feature dependencies.
3193d7f67ac9SQu Wenruo  */
31942ba48b20SQu Wenruo int btrfs_check_features(struct btrfs_fs_info *fs_info, bool is_rw_mount)
3195d7f67ac9SQu Wenruo {
3196d7f67ac9SQu Wenruo 	struct btrfs_super_block *disk_super = fs_info->super_copy;
3197d7f67ac9SQu Wenruo 	u64 incompat = btrfs_super_incompat_flags(disk_super);
3198d7f67ac9SQu Wenruo 	const u64 compat_ro = btrfs_super_compat_ro_flags(disk_super);
3199d7f67ac9SQu Wenruo 	const u64 compat_ro_unsupp = (compat_ro & ~BTRFS_FEATURE_COMPAT_RO_SUPP);
3200d7f67ac9SQu Wenruo 
3201d7f67ac9SQu Wenruo 	if (incompat & ~BTRFS_FEATURE_INCOMPAT_SUPP) {
3202d7f67ac9SQu Wenruo 		btrfs_err(fs_info,
3203d7f67ac9SQu Wenruo 		"cannot mount because of unknown incompat features (0x%llx)",
3204d7f67ac9SQu Wenruo 		    incompat);
3205d7f67ac9SQu Wenruo 		return -EINVAL;
3206d7f67ac9SQu Wenruo 	}
3207d7f67ac9SQu Wenruo 
3208d7f67ac9SQu Wenruo 	/* Runtime limitation for mixed block groups. */
3209d7f67ac9SQu Wenruo 	if ((incompat & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS) &&
3210d7f67ac9SQu Wenruo 	    (fs_info->sectorsize != fs_info->nodesize)) {
3211d7f67ac9SQu Wenruo 		btrfs_err(fs_info,
3212d7f67ac9SQu Wenruo "unequal nodesize/sectorsize (%u != %u) are not allowed for mixed block groups",
3213d7f67ac9SQu Wenruo 			fs_info->nodesize, fs_info->sectorsize);
3214d7f67ac9SQu Wenruo 		return -EINVAL;
3215d7f67ac9SQu Wenruo 	}
3216d7f67ac9SQu Wenruo 
3217d7f67ac9SQu Wenruo 	/* Mixed backref is an always-enabled feature. */
3218d7f67ac9SQu Wenruo 	incompat |= BTRFS_FEATURE_INCOMPAT_MIXED_BACKREF;
3219d7f67ac9SQu Wenruo 
3220d7f67ac9SQu Wenruo 	/* Set compression related flags just in case. */
3221d7f67ac9SQu Wenruo 	if (fs_info->compress_type == BTRFS_COMPRESS_LZO)
3222d7f67ac9SQu Wenruo 		incompat |= BTRFS_FEATURE_INCOMPAT_COMPRESS_LZO;
3223d7f67ac9SQu Wenruo 	else if (fs_info->compress_type == BTRFS_COMPRESS_ZSTD)
3224d7f67ac9SQu Wenruo 		incompat |= BTRFS_FEATURE_INCOMPAT_COMPRESS_ZSTD;
3225d7f67ac9SQu Wenruo 
3226d7f67ac9SQu Wenruo 	/*
3227d7f67ac9SQu Wenruo 	 * An ancient flag, which should really be marked deprecated.
3228d7f67ac9SQu Wenruo 	 * Such runtime limitation doesn't really need a incompat flag.
3229d7f67ac9SQu Wenruo 	 */
3230d7f67ac9SQu Wenruo 	if (btrfs_super_nodesize(disk_super) > PAGE_SIZE)
3231d7f67ac9SQu Wenruo 		incompat |= BTRFS_FEATURE_INCOMPAT_BIG_METADATA;
3232d7f67ac9SQu Wenruo 
32332ba48b20SQu Wenruo 	if (compat_ro_unsupp && is_rw_mount) {
3234d7f67ac9SQu Wenruo 		btrfs_err(fs_info,
3235d7f67ac9SQu Wenruo 	"cannot mount read-write because of unknown compat_ro features (0x%llx)",
3236d7f67ac9SQu Wenruo 		       compat_ro);
3237d7f67ac9SQu Wenruo 		return -EINVAL;
3238d7f67ac9SQu Wenruo 	}
3239d7f67ac9SQu Wenruo 
3240d7f67ac9SQu Wenruo 	/*
3241d7f67ac9SQu Wenruo 	 * We have unsupported RO compat features, although RO mounted, we
3242d7f67ac9SQu Wenruo 	 * should not cause any metadata writes, including log replay.
3243d7f67ac9SQu Wenruo 	 * Or we could screw up whatever the new feature requires.
3244d7f67ac9SQu Wenruo 	 */
3245d7f67ac9SQu Wenruo 	if (compat_ro_unsupp && btrfs_super_log_root(disk_super) &&
3246d7f67ac9SQu Wenruo 	    !btrfs_test_opt(fs_info, NOLOGREPLAY)) {
3247d7f67ac9SQu Wenruo 		btrfs_err(fs_info,
3248d7f67ac9SQu Wenruo "cannot replay dirty log with unsupported compat_ro features (0x%llx), try rescue=nologreplay",
3249d7f67ac9SQu Wenruo 			  compat_ro);
3250d7f67ac9SQu Wenruo 		return -EINVAL;
3251d7f67ac9SQu Wenruo 	}
3252d7f67ac9SQu Wenruo 
3253d7f67ac9SQu Wenruo 	/*
3254d7f67ac9SQu Wenruo 	 * Artificial limitations for block group tree, to force
3255d7f67ac9SQu Wenruo 	 * block-group-tree to rely on no-holes and free-space-tree.
3256d7f67ac9SQu Wenruo 	 */
3257d7f67ac9SQu Wenruo 	if (btrfs_fs_compat_ro(fs_info, BLOCK_GROUP_TREE) &&
3258d7f67ac9SQu Wenruo 	    (!btrfs_fs_incompat(fs_info, NO_HOLES) ||
3259d7f67ac9SQu Wenruo 	     !btrfs_test_opt(fs_info, FREE_SPACE_TREE))) {
3260d7f67ac9SQu Wenruo 		btrfs_err(fs_info,
3261d7f67ac9SQu Wenruo "block-group-tree feature requires no-holes and free-space-tree features");
3262d7f67ac9SQu Wenruo 		return -EINVAL;
3263d7f67ac9SQu Wenruo 	}
3264d7f67ac9SQu Wenruo 
3265d7f67ac9SQu Wenruo 	/*
3266d7f67ac9SQu Wenruo 	 * Subpage runtime limitation on v1 cache.
3267d7f67ac9SQu Wenruo 	 *
3268d7f67ac9SQu Wenruo 	 * V1 space cache still has some hard codeed PAGE_SIZE usage, while
3269d7f67ac9SQu Wenruo 	 * we're already defaulting to v2 cache, no need to bother v1 as it's
3270d7f67ac9SQu Wenruo 	 * going to be deprecated anyway.
3271d7f67ac9SQu Wenruo 	 */
3272d7f67ac9SQu Wenruo 	if (fs_info->sectorsize < PAGE_SIZE && btrfs_test_opt(fs_info, SPACE_CACHE)) {
3273d7f67ac9SQu Wenruo 		btrfs_warn(fs_info,
3274d7f67ac9SQu Wenruo 	"v1 space cache is not supported for page size %lu with sectorsize %u",
3275d7f67ac9SQu Wenruo 			   PAGE_SIZE, fs_info->sectorsize);
3276d7f67ac9SQu Wenruo 		return -EINVAL;
3277d7f67ac9SQu Wenruo 	}
3278d7f67ac9SQu Wenruo 
3279d7f67ac9SQu Wenruo 	/* This can be called by remount, we need to protect the super block. */
3280d7f67ac9SQu Wenruo 	spin_lock(&fs_info->super_lock);
3281d7f67ac9SQu Wenruo 	btrfs_set_super_incompat_flags(disk_super, incompat);
3282d7f67ac9SQu Wenruo 	spin_unlock(&fs_info->super_lock);
3283d7f67ac9SQu Wenruo 
3284d7f67ac9SQu Wenruo 	return 0;
3285d7f67ac9SQu Wenruo }
3286d7f67ac9SQu Wenruo 
3287ae18c37aSJosef Bacik int __cold open_ctree(struct super_block *sb, struct btrfs_fs_devices *fs_devices,
3288ae18c37aSJosef Bacik 		      char *options)
3289ae18c37aSJosef Bacik {
3290ae18c37aSJosef Bacik 	u32 sectorsize;
3291ae18c37aSJosef Bacik 	u32 nodesize;
3292ae18c37aSJosef Bacik 	u32 stripesize;
3293ae18c37aSJosef Bacik 	u64 generation;
3294ae18c37aSJosef Bacik 	u64 features;
3295ae18c37aSJosef Bacik 	u16 csum_type;
3296ae18c37aSJosef Bacik 	struct btrfs_super_block *disk_super;
3297ae18c37aSJosef Bacik 	struct btrfs_fs_info *fs_info = btrfs_sb(sb);
3298ae18c37aSJosef Bacik 	struct btrfs_root *tree_root;
3299ae18c37aSJosef Bacik 	struct btrfs_root *chunk_root;
3300ae18c37aSJosef Bacik 	int ret;
3301ae18c37aSJosef Bacik 	int level;
3302ae18c37aSJosef Bacik 
33038260edbaSJosef Bacik 	ret = init_mount_fs_info(fs_info, sb);
33044871c33bSQu Wenruo 	if (ret)
3305ae18c37aSJosef Bacik 		goto fail;
330653b381b3SDavid Woodhouse 
3307ae18c37aSJosef Bacik 	/* These need to be init'ed before we start creating inodes and such. */
3308ae18c37aSJosef Bacik 	tree_root = btrfs_alloc_root(fs_info, BTRFS_ROOT_TREE_OBJECTID,
3309ae18c37aSJosef Bacik 				     GFP_KERNEL);
3310ae18c37aSJosef Bacik 	fs_info->tree_root = tree_root;
3311ae18c37aSJosef Bacik 	chunk_root = btrfs_alloc_root(fs_info, BTRFS_CHUNK_TREE_OBJECTID,
3312ae18c37aSJosef Bacik 				      GFP_KERNEL);
3313ae18c37aSJosef Bacik 	fs_info->chunk_root = chunk_root;
3314ae18c37aSJosef Bacik 	if (!tree_root || !chunk_root) {
33154871c33bSQu Wenruo 		ret = -ENOMEM;
3316c75e8394SJosef Bacik 		goto fail;
3317ae18c37aSJosef Bacik 	}
3318ae18c37aSJosef Bacik 
3319dcb2137cSChristoph Hellwig 	ret = btrfs_init_btree_inode(sb);
33204871c33bSQu Wenruo 	if (ret)
3321c75e8394SJosef Bacik 		goto fail;
3322ae18c37aSJosef Bacik 
3323d24fa5c1SAnand Jain 	invalidate_bdev(fs_devices->latest_dev->bdev);
33241104a885SDavid Sterba 
33251104a885SDavid Sterba 	/*
33261104a885SDavid Sterba 	 * Read super block and check the signature bytes only
33271104a885SDavid Sterba 	 */
3328d24fa5c1SAnand Jain 	disk_super = btrfs_read_dev_super(fs_devices->latest_dev->bdev);
33298f32380dSJohannes Thumshirn 	if (IS_ERR(disk_super)) {
33304871c33bSQu Wenruo 		ret = PTR_ERR(disk_super);
333116cdcec7SMiao Xie 		goto fail_alloc;
333220b45077SDave Young 	}
333339279cc3SChris Mason 
33341104a885SDavid Sterba 	/*
3335260db43cSRandy Dunlap 	 * Verify the type first, if that or the checksum value are
33368dc3f22cSJohannes Thumshirn 	 * corrupted, we'll find out
33378dc3f22cSJohannes Thumshirn 	 */
33388f32380dSJohannes Thumshirn 	csum_type = btrfs_super_csum_type(disk_super);
333951bce6c9SJohannes Thumshirn 	if (!btrfs_supported_super_csum(csum_type)) {
33408dc3f22cSJohannes Thumshirn 		btrfs_err(fs_info, "unsupported checksum algorithm: %u",
334151bce6c9SJohannes Thumshirn 			  csum_type);
33424871c33bSQu Wenruo 		ret = -EINVAL;
33438f32380dSJohannes Thumshirn 		btrfs_release_disk_super(disk_super);
33448dc3f22cSJohannes Thumshirn 		goto fail_alloc;
33458dc3f22cSJohannes Thumshirn 	}
33468dc3f22cSJohannes Thumshirn 
334783c68bbcSSu Yue 	fs_info->csum_size = btrfs_super_csum_size(disk_super);
334883c68bbcSSu Yue 
33496d97c6e3SJohannes Thumshirn 	ret = btrfs_init_csum_hash(fs_info, csum_type);
33506d97c6e3SJohannes Thumshirn 	if (ret) {
33518f32380dSJohannes Thumshirn 		btrfs_release_disk_super(disk_super);
33526d97c6e3SJohannes Thumshirn 		goto fail_alloc;
33536d97c6e3SJohannes Thumshirn 	}
33546d97c6e3SJohannes Thumshirn 
33558dc3f22cSJohannes Thumshirn 	/*
33561104a885SDavid Sterba 	 * We want to check superblock checksum, the type is stored inside.
33571104a885SDavid Sterba 	 * Pass the whole disk block of size BTRFS_SUPER_INFO_SIZE (4k).
33581104a885SDavid Sterba 	 */
33593d17adeaSQu Wenruo 	if (btrfs_check_super_csum(fs_info, disk_super)) {
336005135f59SDavid Sterba 		btrfs_err(fs_info, "superblock checksum mismatch");
33614871c33bSQu Wenruo 		ret = -EINVAL;
33628f32380dSJohannes Thumshirn 		btrfs_release_disk_super(disk_super);
3363141386e1SJosef Bacik 		goto fail_alloc;
33641104a885SDavid Sterba 	}
33651104a885SDavid Sterba 
33661104a885SDavid Sterba 	/*
33671104a885SDavid Sterba 	 * super_copy is zeroed at allocation time and we never touch the
33681104a885SDavid Sterba 	 * following bytes up to INFO_SIZE, the checksum is calculated from
33691104a885SDavid Sterba 	 * the whole block of INFO_SIZE
33701104a885SDavid Sterba 	 */
33718f32380dSJohannes Thumshirn 	memcpy(fs_info->super_copy, disk_super, sizeof(*fs_info->super_copy));
33728f32380dSJohannes Thumshirn 	btrfs_release_disk_super(disk_super);
33735f39d397SChris Mason 
3374fbc6feaeSNikolay Borisov 	disk_super = fs_info->super_copy;
3375fbc6feaeSNikolay Borisov 
33760b86a832SChris Mason 
3377fbc6feaeSNikolay Borisov 	features = btrfs_super_flags(disk_super);
3378fbc6feaeSNikolay Borisov 	if (features & BTRFS_SUPER_FLAG_CHANGING_FSID_V2) {
3379fbc6feaeSNikolay Borisov 		features &= ~BTRFS_SUPER_FLAG_CHANGING_FSID_V2;
3380fbc6feaeSNikolay Borisov 		btrfs_set_super_flags(disk_super, features);
3381fbc6feaeSNikolay Borisov 		btrfs_info(fs_info,
3382fbc6feaeSNikolay Borisov 			"found metadata UUID change in progress flag, clearing");
3383fbc6feaeSNikolay Borisov 	}
3384fbc6feaeSNikolay Borisov 
3385fbc6feaeSNikolay Borisov 	memcpy(fs_info->super_for_commit, fs_info->super_copy,
3386fbc6feaeSNikolay Borisov 	       sizeof(*fs_info->super_for_commit));
3387de37aa51SNikolay Borisov 
3388069ec957SQu Wenruo 	ret = btrfs_validate_mount_super(fs_info);
33891104a885SDavid Sterba 	if (ret) {
339005135f59SDavid Sterba 		btrfs_err(fs_info, "superblock contains fatal errors");
33914871c33bSQu Wenruo 		ret = -EINVAL;
3392141386e1SJosef Bacik 		goto fail_alloc;
33931104a885SDavid Sterba 	}
33941104a885SDavid Sterba 
33954871c33bSQu Wenruo 	if (!btrfs_super_root(disk_super)) {
33964871c33bSQu Wenruo 		btrfs_err(fs_info, "invalid superblock tree root bytenr");
33974871c33bSQu Wenruo 		ret = -EINVAL;
3398141386e1SJosef Bacik 		goto fail_alloc;
33994871c33bSQu Wenruo 	}
34000f7d52f4SChris Mason 
3401acce952bSliubo 	/* check FS state, whether FS is broken. */
340287533c47SMiao Xie 	if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_ERROR)
340387533c47SMiao Xie 		set_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state);
3404acce952bSliubo 
340575e7cb7fSLiu Bo 	/*
340675e7cb7fSLiu Bo 	 * In the long term, we'll store the compression type in the super
340775e7cb7fSLiu Bo 	 * block, and it'll be used for per file compression control.
340875e7cb7fSLiu Bo 	 */
340975e7cb7fSLiu Bo 	fs_info->compress_type = BTRFS_COMPRESS_ZLIB;
341075e7cb7fSLiu Bo 
34116f93e834SAnand Jain 
34126f93e834SAnand Jain 	/* Set up fs_info before parsing mount options */
34136f93e834SAnand Jain 	nodesize = btrfs_super_nodesize(disk_super);
34146f93e834SAnand Jain 	sectorsize = btrfs_super_sectorsize(disk_super);
34156f93e834SAnand Jain 	stripesize = sectorsize;
34166f93e834SAnand Jain 	fs_info->dirty_metadata_batch = nodesize * (1 + ilog2(nr_cpu_ids));
34176f93e834SAnand Jain 	fs_info->delalloc_batch = sectorsize * 512 * (1 + ilog2(nr_cpu_ids));
34186f93e834SAnand Jain 
34196f93e834SAnand Jain 	fs_info->nodesize = nodesize;
34206f93e834SAnand Jain 	fs_info->sectorsize = sectorsize;
34216f93e834SAnand Jain 	fs_info->sectorsize_bits = ilog2(sectorsize);
34226f93e834SAnand Jain 	fs_info->csums_per_leaf = BTRFS_MAX_ITEM_SIZE(fs_info) / fs_info->csum_size;
34236f93e834SAnand Jain 	fs_info->stripesize = stripesize;
34246f93e834SAnand Jain 
34252ff7e61eSJeff Mahoney 	ret = btrfs_parse_options(fs_info, options, sb->s_flags);
34264871c33bSQu Wenruo 	if (ret)
3427141386e1SJosef Bacik 		goto fail_alloc;
3428dfe25020SChris Mason 
34292ba48b20SQu Wenruo 	ret = btrfs_check_features(fs_info, !sb_rdonly(sb));
34304871c33bSQu Wenruo 	if (ret < 0)
3431141386e1SJosef Bacik 		goto fail_alloc;
3432f2b636e8SJosef Bacik 
34338481dd80SQu Wenruo 	if (sectorsize < PAGE_SIZE) {
34348481dd80SQu Wenruo 		struct btrfs_subpage_info *subpage_info;
34358481dd80SQu Wenruo 
34369f73f1aeSQu Wenruo 		/*
34379f73f1aeSQu Wenruo 		 * V1 space cache has some hardcoded PAGE_SIZE usage, and is
34389f73f1aeSQu Wenruo 		 * going to be deprecated.
34399f73f1aeSQu Wenruo 		 *
34409f73f1aeSQu Wenruo 		 * Force to use v2 cache for subpage case.
34419f73f1aeSQu Wenruo 		 */
34429f73f1aeSQu Wenruo 		btrfs_clear_opt(fs_info->mount_opt, SPACE_CACHE);
34439f73f1aeSQu Wenruo 		btrfs_set_and_info(fs_info, FREE_SPACE_TREE,
34449f73f1aeSQu Wenruo 			"forcing free space tree for sector size %u with page size %lu",
34459f73f1aeSQu Wenruo 			sectorsize, PAGE_SIZE);
34469f73f1aeSQu Wenruo 
344795ea0486SQu Wenruo 		btrfs_warn(fs_info,
344895ea0486SQu Wenruo 		"read-write for sector size %u with page size %lu is experimental",
34490bb3eb3eSQu Wenruo 			   sectorsize, PAGE_SIZE);
34508481dd80SQu Wenruo 		subpage_info = kzalloc(sizeof(*subpage_info), GFP_KERNEL);
34514871c33bSQu Wenruo 		if (!subpage_info) {
34524871c33bSQu Wenruo 			ret = -ENOMEM;
34538481dd80SQu Wenruo 			goto fail_alloc;
34544871c33bSQu Wenruo 		}
34558481dd80SQu Wenruo 		btrfs_init_subpage_info(subpage_info, sectorsize);
34568481dd80SQu Wenruo 		fs_info->subpage_info = subpage_info;
3457c8050b3bSQu Wenruo 	}
34580bb3eb3eSQu Wenruo 
3459d21deec5SSu Yue 	ret = btrfs_init_workqueues(fs_info);
34604871c33bSQu Wenruo 	if (ret)
34610dc3b84aSJosef Bacik 		goto fail_sb_buffer;
34624543df7eSChris Mason 
34639e11ceeeSJan Kara 	sb->s_bdi->ra_pages *= btrfs_super_num_devices(disk_super);
34649e11ceeeSJan Kara 	sb->s_bdi->ra_pages = max(sb->s_bdi->ra_pages, SZ_4M / PAGE_SIZE);
34654575c9ccSChris Mason 
3466a061fc8dSChris Mason 	sb->s_blocksize = sectorsize;
3467a061fc8dSChris Mason 	sb->s_blocksize_bits = blksize_bits(sectorsize);
3468de37aa51SNikolay Borisov 	memcpy(&sb->s_uuid, fs_info->fs_devices->fsid, BTRFS_FSID_SIZE);
3469db94535dSChris Mason 
3470925baeddSChris Mason 	mutex_lock(&fs_info->chunk_mutex);
34716bccf3abSJeff Mahoney 	ret = btrfs_read_sys_array(fs_info);
3472925baeddSChris Mason 	mutex_unlock(&fs_info->chunk_mutex);
347384eed90fSChris Mason 	if (ret) {
347405135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read the system array: %d", ret);
34755d4f98a2SYan Zheng 		goto fail_sb_buffer;
347684eed90fSChris Mason 	}
34770b86a832SChris Mason 
347884234f3aSYan Zheng 	generation = btrfs_super_chunk_root_generation(disk_super);
3479581c1760SQu Wenruo 	level = btrfs_super_chunk_root_level(disk_super);
3480bd676446SJosef Bacik 	ret = load_super_root(chunk_root, btrfs_super_chunk_root(disk_super),
3481bd676446SJosef Bacik 			      generation, level);
3482bd676446SJosef Bacik 	if (ret) {
348305135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read chunk root");
3484af31f5e5SChris Mason 		goto fail_tree_roots;
348583121942SDavid Woodhouse 	}
34860b86a832SChris Mason 
3487e17cade2SChris Mason 	read_extent_buffer(chunk_root->node, fs_info->chunk_tree_uuid,
3488c4ac7541SDavid Sterba 			   offsetof(struct btrfs_header, chunk_tree_uuid),
3489c4ac7541SDavid Sterba 			   BTRFS_UUID_SIZE);
3490e17cade2SChris Mason 
34915b4aacefSJeff Mahoney 	ret = btrfs_read_chunk_tree(fs_info);
34922b82032cSYan Zheng 	if (ret) {
349305135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read chunk tree: %d", ret);
3494af31f5e5SChris Mason 		goto fail_tree_roots;
34952b82032cSYan Zheng 	}
34960b86a832SChris Mason 
34978dabb742SStefan Behrens 	/*
3498bacce86aSAnand Jain 	 * At this point we know all the devices that make this filesystem,
3499bacce86aSAnand Jain 	 * including the seed devices but we don't know yet if the replace
3500bacce86aSAnand Jain 	 * target is required. So free devices that are not part of this
35011a9fd417SDavid Sterba 	 * filesystem but skip the replace target device which is checked
3502bacce86aSAnand Jain 	 * below in btrfs_init_dev_replace().
35038dabb742SStefan Behrens 	 */
3504bacce86aSAnand Jain 	btrfs_free_extra_devids(fs_devices);
3505d24fa5c1SAnand Jain 	if (!fs_devices->latest_dev->bdev) {
350605135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read devices");
35074871c33bSQu Wenruo 		ret = -EIO;
3508a6b0d5c8SChris Mason 		goto fail_tree_roots;
3509a6b0d5c8SChris Mason 	}
3510a6b0d5c8SChris Mason 
3511b8522a1eSNikolay Borisov 	ret = init_tree_roots(fs_info);
35124bbcaa64SEric Sandeen 	if (ret)
3513b8522a1eSNikolay Borisov 		goto fail_tree_roots;
35148929ecfaSYan, Zheng 
351575ec1db8SJosef Bacik 	/*
351673651042SNaohiro Aota 	 * Get zone type information of zoned block devices. This will also
351773651042SNaohiro Aota 	 * handle emulation of a zoned filesystem if a regular device has the
351873651042SNaohiro Aota 	 * zoned incompat feature flag set.
351973651042SNaohiro Aota 	 */
352073651042SNaohiro Aota 	ret = btrfs_get_dev_zone_info_all_devices(fs_info);
352173651042SNaohiro Aota 	if (ret) {
352273651042SNaohiro Aota 		btrfs_err(fs_info,
35234871c33bSQu Wenruo 			  "zoned: failed to read device zone info: %d", ret);
352473651042SNaohiro Aota 		goto fail_block_groups;
352573651042SNaohiro Aota 	}
352673651042SNaohiro Aota 
352773651042SNaohiro Aota 	/*
352875ec1db8SJosef Bacik 	 * If we have a uuid root and we're not being told to rescan we need to
352975ec1db8SJosef Bacik 	 * check the generation here so we can set the
353075ec1db8SJosef Bacik 	 * BTRFS_FS_UPDATE_UUID_TREE_GEN bit.  Otherwise we could commit the
353175ec1db8SJosef Bacik 	 * transaction during a balance or the log replay without updating the
353275ec1db8SJosef Bacik 	 * uuid generation, and then if we crash we would rescan the uuid tree,
353375ec1db8SJosef Bacik 	 * even though it was perfectly fine.
353475ec1db8SJosef Bacik 	 */
353575ec1db8SJosef Bacik 	if (fs_info->uuid_root && !btrfs_test_opt(fs_info, RESCAN_UUID_TREE) &&
353675ec1db8SJosef Bacik 	    fs_info->generation == btrfs_super_uuid_tree_generation(disk_super))
353775ec1db8SJosef Bacik 		set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
353875ec1db8SJosef Bacik 
3539cf90d884SQu Wenruo 	ret = btrfs_verify_dev_extents(fs_info);
3540cf90d884SQu Wenruo 	if (ret) {
3541cf90d884SQu Wenruo 		btrfs_err(fs_info,
3542cf90d884SQu Wenruo 			  "failed to verify dev extents against chunks: %d",
3543cf90d884SQu Wenruo 			  ret);
3544cf90d884SQu Wenruo 		goto fail_block_groups;
3545cf90d884SQu Wenruo 	}
354668310a5eSIlya Dryomov 	ret = btrfs_recover_balance(fs_info);
354768310a5eSIlya Dryomov 	if (ret) {
354805135f59SDavid Sterba 		btrfs_err(fs_info, "failed to recover balance: %d", ret);
354968310a5eSIlya Dryomov 		goto fail_block_groups;
355068310a5eSIlya Dryomov 	}
355168310a5eSIlya Dryomov 
3552733f4fbbSStefan Behrens 	ret = btrfs_init_dev_stats(fs_info);
3553733f4fbbSStefan Behrens 	if (ret) {
355405135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init dev_stats: %d", ret);
3555733f4fbbSStefan Behrens 		goto fail_block_groups;
3556733f4fbbSStefan Behrens 	}
3557733f4fbbSStefan Behrens 
35588dabb742SStefan Behrens 	ret = btrfs_init_dev_replace(fs_info);
35598dabb742SStefan Behrens 	if (ret) {
356005135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init dev_replace: %d", ret);
35618dabb742SStefan Behrens 		goto fail_block_groups;
35628dabb742SStefan Behrens 	}
35638dabb742SStefan Behrens 
3564b70f5097SNaohiro Aota 	ret = btrfs_check_zoned_mode(fs_info);
3565b70f5097SNaohiro Aota 	if (ret) {
3566b70f5097SNaohiro Aota 		btrfs_err(fs_info, "failed to initialize zoned mode: %d",
3567b70f5097SNaohiro Aota 			  ret);
3568b70f5097SNaohiro Aota 		goto fail_block_groups;
3569b70f5097SNaohiro Aota 	}
3570b70f5097SNaohiro Aota 
3571c6761a9eSAnand Jain 	ret = btrfs_sysfs_add_fsid(fs_devices);
3572b7c35e81SAnand Jain 	if (ret) {
357305135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init sysfs fsid interface: %d",
357405135f59SDavid Sterba 				ret);
3575b7c35e81SAnand Jain 		goto fail_block_groups;
3576b7c35e81SAnand Jain 	}
3577b7c35e81SAnand Jain 
357896f3136eSAnand Jain 	ret = btrfs_sysfs_add_mounted(fs_info);
35795ac1d209SJeff Mahoney 	if (ret) {
358005135f59SDavid Sterba 		btrfs_err(fs_info, "failed to init sysfs interface: %d", ret);
3581b7c35e81SAnand Jain 		goto fail_fsdev_sysfs;
35825ac1d209SJeff Mahoney 	}
35835ac1d209SJeff Mahoney 
3584c59021f8Sliubo 	ret = btrfs_init_space_info(fs_info);
3585c59021f8Sliubo 	if (ret) {
358605135f59SDavid Sterba 		btrfs_err(fs_info, "failed to initialize space info: %d", ret);
35872365dd3cSAnand Jain 		goto fail_sysfs;
3588c59021f8Sliubo 	}
3589c59021f8Sliubo 
35905b4aacefSJeff Mahoney 	ret = btrfs_read_block_groups(fs_info);
35911b1d1f66SJosef Bacik 	if (ret) {
359205135f59SDavid Sterba 		btrfs_err(fs_info, "failed to read block groups: %d", ret);
35932365dd3cSAnand Jain 		goto fail_sysfs;
35941b1d1f66SJosef Bacik 	}
35954330e183SQu Wenruo 
359616beac87SNaohiro Aota 	btrfs_free_zone_cache(fs_info);
359716beac87SNaohiro Aota 
35985c78a5e7SAnand Jain 	if (!sb_rdonly(sb) && fs_info->fs_devices->missing_devices &&
35995c78a5e7SAnand Jain 	    !btrfs_check_rw_degradable(fs_info, NULL)) {
360005135f59SDavid Sterba 		btrfs_warn(fs_info,
360152042d8eSAndrea Gelmini 		"writable mount is not allowed due to too many missing devices");
36024871c33bSQu Wenruo 		ret = -EINVAL;
36032365dd3cSAnand Jain 		goto fail_sysfs;
3604292fd7fcSStefan Behrens 	}
36059078a3e1SChris Mason 
360633c44184SJosef Bacik 	fs_info->cleaner_kthread = kthread_run(cleaner_kthread, fs_info,
3607a74a4b97SChris Mason 					       "btrfs-cleaner");
36084871c33bSQu Wenruo 	if (IS_ERR(fs_info->cleaner_kthread)) {
36094871c33bSQu Wenruo 		ret = PTR_ERR(fs_info->cleaner_kthread);
36102365dd3cSAnand Jain 		goto fail_sysfs;
36114871c33bSQu Wenruo 	}
3612a74a4b97SChris Mason 
3613a74a4b97SChris Mason 	fs_info->transaction_kthread = kthread_run(transaction_kthread,
3614a74a4b97SChris Mason 						   tree_root,
3615a74a4b97SChris Mason 						   "btrfs-transaction");
36164871c33bSQu Wenruo 	if (IS_ERR(fs_info->transaction_kthread)) {
36174871c33bSQu Wenruo 		ret = PTR_ERR(fs_info->transaction_kthread);
36183f157a2fSChris Mason 		goto fail_cleaner;
36194871c33bSQu Wenruo 	}
3620a74a4b97SChris Mason 
3621583b7231SHans van Kranenburg 	if (!btrfs_test_opt(fs_info, NOSSD) &&
3622c289811cSChris Mason 	    !fs_info->fs_devices->rotating) {
3623583b7231SHans van Kranenburg 		btrfs_set_and_info(fs_info, SSD, "enabling ssd optimizations");
3624c289811cSChris Mason 	}
3625c289811cSChris Mason 
3626572d9ab7SDavid Sterba 	/*
362763a7cb13SDavid Sterba 	 * For devices supporting discard turn on discard=async automatically,
362863a7cb13SDavid Sterba 	 * unless it's already set or disabled. This could be turned off by
362963a7cb13SDavid Sterba 	 * nodiscard for the same mount.
363063a7cb13SDavid Sterba 	 */
363163a7cb13SDavid Sterba 	if (!(btrfs_test_opt(fs_info, DISCARD_SYNC) ||
363263a7cb13SDavid Sterba 	      btrfs_test_opt(fs_info, DISCARD_ASYNC) ||
363363a7cb13SDavid Sterba 	      btrfs_test_opt(fs_info, NODISCARD)) &&
363463a7cb13SDavid Sterba 	    fs_info->fs_devices->discardable) {
363563a7cb13SDavid Sterba 		btrfs_set_and_info(fs_info, DISCARD_ASYNC,
363663a7cb13SDavid Sterba 				   "auto enabling async discard");
363763a7cb13SDavid Sterba 	}
363863a7cb13SDavid Sterba 
363921adbd5cSStefan Behrens #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
36400b246afaSJeff Mahoney 	if (btrfs_test_opt(fs_info, CHECK_INTEGRITY)) {
36412ff7e61eSJeff Mahoney 		ret = btrfsic_mount(fs_info, fs_devices,
36420b246afaSJeff Mahoney 				    btrfs_test_opt(fs_info,
3643cbeaae4fSDavid Sterba 					CHECK_INTEGRITY_DATA) ? 1 : 0,
364421adbd5cSStefan Behrens 				    fs_info->check_integrity_print_mask);
364521adbd5cSStefan Behrens 		if (ret)
364605135f59SDavid Sterba 			btrfs_warn(fs_info,
364705135f59SDavid Sterba 				"failed to initialize integrity check module: %d",
364805135f59SDavid Sterba 				ret);
364921adbd5cSStefan Behrens 	}
365021adbd5cSStefan Behrens #endif
3651bcef60f2SArne Jansen 	ret = btrfs_read_qgroup_config(fs_info);
3652bcef60f2SArne Jansen 	if (ret)
3653bcef60f2SArne Jansen 		goto fail_trans_kthread;
365421adbd5cSStefan Behrens 
3655fd708b81SJosef Bacik 	if (btrfs_build_ref_tree(fs_info))
3656fd708b81SJosef Bacik 		btrfs_err(fs_info, "couldn't build ref tree");
3657fd708b81SJosef Bacik 
365896da0919SQu Wenruo 	/* do not make disk changes in broken FS or nologreplay is given */
365996da0919SQu Wenruo 	if (btrfs_super_log_root(disk_super) != 0 &&
36600b246afaSJeff Mahoney 	    !btrfs_test_opt(fs_info, NOLOGREPLAY)) {
3661e8294f2fSDavid Sterba 		btrfs_info(fs_info, "start tree-log replay");
366263443bf5SEric Sandeen 		ret = btrfs_replay_log(fs_info, fs_devices);
36634871c33bSQu Wenruo 		if (ret)
366428c16cbbSWang Shilong 			goto fail_qgroup;
3665e556ce2cSYan Zheng 	}
36661a40e23bSZheng Yan 
366756e9357aSDavid Sterba 	fs_info->fs_root = btrfs_get_fs_root(fs_info, BTRFS_FS_TREE_OBJECTID, true);
36683140c9a3SDan Carpenter 	if (IS_ERR(fs_info->fs_root)) {
36694871c33bSQu Wenruo 		ret = PTR_ERR(fs_info->fs_root);
36704871c33bSQu Wenruo 		btrfs_warn(fs_info, "failed to read fs tree: %d", ret);
3671315bf8efSJosef Bacik 		fs_info->fs_root = NULL;
3672bcef60f2SArne Jansen 		goto fail_qgroup;
36733140c9a3SDan Carpenter 	}
3674c289811cSChris Mason 
3675bc98a42cSDavid Howells 	if (sb_rdonly(sb))
36768cd29088SBoris Burkov 		goto clear_oneshot;
36772b6ba629SIlya Dryomov 
367844c0ca21SBoris Burkov 	ret = btrfs_start_pre_rw_mount(fs_info);
36792b6ba629SIlya Dryomov 	if (ret) {
36806bccf3abSJeff Mahoney 		close_ctree(fs_info);
36812b6ba629SIlya Dryomov 		return ret;
3682e3acc2a6SJosef Bacik 	}
3683b0643e59SDennis Zhou 	btrfs_discard_resume(fs_info);
3684b382a324SJan Schmidt 
368544c0ca21SBoris Burkov 	if (fs_info->uuid_root &&
368644c0ca21SBoris Burkov 	    (btrfs_test_opt(fs_info, RESCAN_UUID_TREE) ||
368744c0ca21SBoris Burkov 	     fs_info->generation != btrfs_super_uuid_tree_generation(disk_super))) {
368805135f59SDavid Sterba 		btrfs_info(fs_info, "checking UUID tree");
368970f80175SStefan Behrens 		ret = btrfs_check_uuid_tree(fs_info);
369070f80175SStefan Behrens 		if (ret) {
369105135f59SDavid Sterba 			btrfs_warn(fs_info,
369205135f59SDavid Sterba 				"failed to check the UUID tree: %d", ret);
36936bccf3abSJeff Mahoney 			close_ctree(fs_info);
369470f80175SStefan Behrens 			return ret;
369570f80175SStefan Behrens 		}
3696f7a81ea4SStefan Behrens 	}
369794846229SBoris Burkov 
3698afcdd129SJosef Bacik 	set_bit(BTRFS_FS_OPEN, &fs_info->flags);
369947ab2a6cSJosef Bacik 
3700b4be6aefSJosef Bacik 	/* Kick the cleaner thread so it'll start deleting snapshots. */
3701b4be6aefSJosef Bacik 	if (test_bit(BTRFS_FS_UNFINISHED_DROPS, &fs_info->flags))
3702b4be6aefSJosef Bacik 		wake_up_process(fs_info->cleaner_kthread);
3703b4be6aefSJosef Bacik 
37048cd29088SBoris Burkov clear_oneshot:
37058cd29088SBoris Burkov 	btrfs_clear_oneshot_options(fs_info);
3706ad2b2c80SAl Viro 	return 0;
370739279cc3SChris Mason 
3708bcef60f2SArne Jansen fail_qgroup:
3709bcef60f2SArne Jansen 	btrfs_free_qgroup_config(fs_info);
37107c2ca468SChris Mason fail_trans_kthread:
37117c2ca468SChris Mason 	kthread_stop(fs_info->transaction_kthread);
37122ff7e61eSJeff Mahoney 	btrfs_cleanup_transaction(fs_info);
3713faa2dbf0SJosef Bacik 	btrfs_free_fs_roots(fs_info);
37143f157a2fSChris Mason fail_cleaner:
3715a74a4b97SChris Mason 	kthread_stop(fs_info->cleaner_kthread);
37167c2ca468SChris Mason 
37177c2ca468SChris Mason 	/*
37187c2ca468SChris Mason 	 * make sure we're done with the btree inode before we stop our
37197c2ca468SChris Mason 	 * kthreads
37207c2ca468SChris Mason 	 */
37217c2ca468SChris Mason 	filemap_write_and_wait(fs_info->btree_inode->i_mapping);
37227c2ca468SChris Mason 
37232365dd3cSAnand Jain fail_sysfs:
37246618a59bSAnand Jain 	btrfs_sysfs_remove_mounted(fs_info);
37252365dd3cSAnand Jain 
3726b7c35e81SAnand Jain fail_fsdev_sysfs:
3727b7c35e81SAnand Jain 	btrfs_sysfs_remove_fsid(fs_info->fs_devices);
3728b7c35e81SAnand Jain 
37291b1d1f66SJosef Bacik fail_block_groups:
373054067ae9SJosef Bacik 	btrfs_put_block_group_cache(fs_info);
3731af31f5e5SChris Mason 
3732af31f5e5SChris Mason fail_tree_roots:
37339e3aa805SJosef Bacik 	if (fs_info->data_reloc_root)
37349e3aa805SJosef Bacik 		btrfs_drop_and_free_fs_root(fs_info, fs_info->data_reloc_root);
37354273eaffSAnand Jain 	free_root_pointers(fs_info, true);
37362b8195bbSMiao Xie 	invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
3737af31f5e5SChris Mason 
373839279cc3SChris Mason fail_sb_buffer:
37397abadb64SLiu Bo 	btrfs_stop_all_workers(fs_info);
37405cdd7db6SFilipe Manana 	btrfs_free_block_groups(fs_info);
374116cdcec7SMiao Xie fail_alloc:
3742586e46e2SIlya Dryomov 	btrfs_mapping_tree_free(&fs_info->mapping_tree);
3743586e46e2SIlya Dryomov 
37444543df7eSChris Mason 	iput(fs_info->btree_inode);
37457e662854SQinghuang Feng fail:
3746586e46e2SIlya Dryomov 	btrfs_close_devices(fs_info->fs_devices);
37474871c33bSQu Wenruo 	ASSERT(ret < 0);
37484871c33bSQu Wenruo 	return ret;
3749eb60ceacSChris Mason }
3750663faf9fSMasami Hiramatsu ALLOW_ERROR_INJECTION(open_ctree, ERRNO);
3751eb60ceacSChris Mason 
3752314b6dd0SJohannes Thumshirn static void btrfs_end_super_write(struct bio *bio)
3753f2984462SChris Mason {
3754314b6dd0SJohannes Thumshirn 	struct btrfs_device *device = bio->bi_private;
3755314b6dd0SJohannes Thumshirn 	struct bio_vec *bvec;
3756314b6dd0SJohannes Thumshirn 	struct bvec_iter_all iter_all;
3757314b6dd0SJohannes Thumshirn 	struct page *page;
3758442a4f63SStefan Behrens 
3759314b6dd0SJohannes Thumshirn 	bio_for_each_segment_all(bvec, bio, iter_all) {
3760314b6dd0SJohannes Thumshirn 		page = bvec->bv_page;
3761314b6dd0SJohannes Thumshirn 
3762314b6dd0SJohannes Thumshirn 		if (bio->bi_status) {
3763fb456252SJeff Mahoney 			btrfs_warn_rl_in_rcu(device->fs_info,
3764314b6dd0SJohannes Thumshirn 				"lost page write due to IO error on %s (%d)",
3765cb3e217bSQu Wenruo 				btrfs_dev_name(device),
3766314b6dd0SJohannes Thumshirn 				blk_status_to_errno(bio->bi_status));
3767314b6dd0SJohannes Thumshirn 			ClearPageUptodate(page);
3768314b6dd0SJohannes Thumshirn 			SetPageError(page);
3769314b6dd0SJohannes Thumshirn 			btrfs_dev_stat_inc_and_print(device,
3770314b6dd0SJohannes Thumshirn 						     BTRFS_DEV_STAT_WRITE_ERRS);
3771314b6dd0SJohannes Thumshirn 		} else {
3772314b6dd0SJohannes Thumshirn 			SetPageUptodate(page);
3773f2984462SChris Mason 		}
3774314b6dd0SJohannes Thumshirn 
3775314b6dd0SJohannes Thumshirn 		put_page(page);
3776314b6dd0SJohannes Thumshirn 		unlock_page(page);
3777314b6dd0SJohannes Thumshirn 	}
3778314b6dd0SJohannes Thumshirn 
3779314b6dd0SJohannes Thumshirn 	bio_put(bio);
3780f2984462SChris Mason }
3781f2984462SChris Mason 
37828f32380dSJohannes Thumshirn struct btrfs_super_block *btrfs_read_dev_one_super(struct block_device *bdev,
3783a05d3c91SQu Wenruo 						   int copy_num, bool drop_cache)
378429c36d72SAnand Jain {
378529c36d72SAnand Jain 	struct btrfs_super_block *super;
37868f32380dSJohannes Thumshirn 	struct page *page;
378712659251SNaohiro Aota 	u64 bytenr, bytenr_orig;
37888f32380dSJohannes Thumshirn 	struct address_space *mapping = bdev->bd_inode->i_mapping;
378912659251SNaohiro Aota 	int ret;
379029c36d72SAnand Jain 
379112659251SNaohiro Aota 	bytenr_orig = btrfs_sb_offset(copy_num);
379212659251SNaohiro Aota 	ret = btrfs_sb_log_location_bdev(bdev, copy_num, READ, &bytenr);
379312659251SNaohiro Aota 	if (ret == -ENOENT)
379412659251SNaohiro Aota 		return ERR_PTR(-EINVAL);
379512659251SNaohiro Aota 	else if (ret)
379612659251SNaohiro Aota 		return ERR_PTR(ret);
379712659251SNaohiro Aota 
3798cda00ebaSChristoph Hellwig 	if (bytenr + BTRFS_SUPER_INFO_SIZE >= bdev_nr_bytes(bdev))
37998f32380dSJohannes Thumshirn 		return ERR_PTR(-EINVAL);
380029c36d72SAnand Jain 
3801a05d3c91SQu Wenruo 	if (drop_cache) {
3802a05d3c91SQu Wenruo 		/* This should only be called with the primary sb. */
3803a05d3c91SQu Wenruo 		ASSERT(copy_num == 0);
3804a05d3c91SQu Wenruo 
3805a05d3c91SQu Wenruo 		/*
3806a05d3c91SQu Wenruo 		 * Drop the page of the primary superblock, so later read will
3807a05d3c91SQu Wenruo 		 * always read from the device.
3808a05d3c91SQu Wenruo 		 */
3809a05d3c91SQu Wenruo 		invalidate_inode_pages2_range(mapping,
3810a05d3c91SQu Wenruo 				bytenr >> PAGE_SHIFT,
3811a05d3c91SQu Wenruo 				(bytenr + BTRFS_SUPER_INFO_SIZE) >> PAGE_SHIFT);
3812a05d3c91SQu Wenruo 	}
3813a05d3c91SQu Wenruo 
38148f32380dSJohannes Thumshirn 	page = read_cache_page_gfp(mapping, bytenr >> PAGE_SHIFT, GFP_NOFS);
38158f32380dSJohannes Thumshirn 	if (IS_ERR(page))
38168f32380dSJohannes Thumshirn 		return ERR_CAST(page);
381729c36d72SAnand Jain 
38188f32380dSJohannes Thumshirn 	super = page_address(page);
381996c2e067SAnand Jain 	if (btrfs_super_magic(super) != BTRFS_MAGIC) {
382096c2e067SAnand Jain 		btrfs_release_disk_super(super);
382196c2e067SAnand Jain 		return ERR_PTR(-ENODATA);
382296c2e067SAnand Jain 	}
382396c2e067SAnand Jain 
382412659251SNaohiro Aota 	if (btrfs_super_bytenr(super) != bytenr_orig) {
38258f32380dSJohannes Thumshirn 		btrfs_release_disk_super(super);
38268f32380dSJohannes Thumshirn 		return ERR_PTR(-EINVAL);
382729c36d72SAnand Jain 	}
382829c36d72SAnand Jain 
38298f32380dSJohannes Thumshirn 	return super;
383029c36d72SAnand Jain }
383129c36d72SAnand Jain 
383229c36d72SAnand Jain 
38338f32380dSJohannes Thumshirn struct btrfs_super_block *btrfs_read_dev_super(struct block_device *bdev)
3834a512bbf8SYan Zheng {
38358f32380dSJohannes Thumshirn 	struct btrfs_super_block *super, *latest = NULL;
3836a512bbf8SYan Zheng 	int i;
3837a512bbf8SYan Zheng 	u64 transid = 0;
3838a512bbf8SYan Zheng 
3839a512bbf8SYan Zheng 	/* we would like to check all the supers, but that would make
3840a512bbf8SYan Zheng 	 * a btrfs mount succeed after a mkfs from a different FS.
3841a512bbf8SYan Zheng 	 * So, we need to add a special mount option to scan for
3842a512bbf8SYan Zheng 	 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
3843a512bbf8SYan Zheng 	 */
3844a512bbf8SYan Zheng 	for (i = 0; i < 1; i++) {
3845a05d3c91SQu Wenruo 		super = btrfs_read_dev_one_super(bdev, i, false);
38468f32380dSJohannes Thumshirn 		if (IS_ERR(super))
3847a512bbf8SYan Zheng 			continue;
3848a512bbf8SYan Zheng 
3849a512bbf8SYan Zheng 		if (!latest || btrfs_super_generation(super) > transid) {
38508f32380dSJohannes Thumshirn 			if (latest)
38518f32380dSJohannes Thumshirn 				btrfs_release_disk_super(super);
38528f32380dSJohannes Thumshirn 
38538f32380dSJohannes Thumshirn 			latest = super;
3854a512bbf8SYan Zheng 			transid = btrfs_super_generation(super);
3855a512bbf8SYan Zheng 		}
3856a512bbf8SYan Zheng 	}
385792fc03fbSAnand Jain 
38588f32380dSJohannes Thumshirn 	return super;
3859a512bbf8SYan Zheng }
3860a512bbf8SYan Zheng 
38614eedeb75SHisashi Hifumi /*
3862abbb3b8eSDavid Sterba  * Write superblock @sb to the @device. Do not wait for completion, all the
3863314b6dd0SJohannes Thumshirn  * pages we use for writing are locked.
38644eedeb75SHisashi Hifumi  *
3865abbb3b8eSDavid Sterba  * Write @max_mirrors copies of the superblock, where 0 means default that fit
3866abbb3b8eSDavid Sterba  * the expected device size at commit time. Note that max_mirrors must be
3867abbb3b8eSDavid Sterba  * same for write and wait phases.
38684eedeb75SHisashi Hifumi  *
3869314b6dd0SJohannes Thumshirn  * Return number of errors when page is not found or submission fails.
38704eedeb75SHisashi Hifumi  */
3871a512bbf8SYan Zheng static int write_dev_supers(struct btrfs_device *device,
3872abbb3b8eSDavid Sterba 			    struct btrfs_super_block *sb, int max_mirrors)
3873a512bbf8SYan Zheng {
3874d5178578SJohannes Thumshirn 	struct btrfs_fs_info *fs_info = device->fs_info;
3875314b6dd0SJohannes Thumshirn 	struct address_space *mapping = device->bdev->bd_inode->i_mapping;
3876d5178578SJohannes Thumshirn 	SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
3877a512bbf8SYan Zheng 	int i;
3878a512bbf8SYan Zheng 	int errors = 0;
387912659251SNaohiro Aota 	int ret;
388012659251SNaohiro Aota 	u64 bytenr, bytenr_orig;
3881a512bbf8SYan Zheng 
3882a512bbf8SYan Zheng 	if (max_mirrors == 0)
3883a512bbf8SYan Zheng 		max_mirrors = BTRFS_SUPER_MIRROR_MAX;
3884a512bbf8SYan Zheng 
3885d5178578SJohannes Thumshirn 	shash->tfm = fs_info->csum_shash;
3886d5178578SJohannes Thumshirn 
3887a512bbf8SYan Zheng 	for (i = 0; i < max_mirrors; i++) {
3888314b6dd0SJohannes Thumshirn 		struct page *page;
3889314b6dd0SJohannes Thumshirn 		struct bio *bio;
3890314b6dd0SJohannes Thumshirn 		struct btrfs_super_block *disk_super;
3891314b6dd0SJohannes Thumshirn 
389212659251SNaohiro Aota 		bytenr_orig = btrfs_sb_offset(i);
389312659251SNaohiro Aota 		ret = btrfs_sb_log_location(device, i, WRITE, &bytenr);
389412659251SNaohiro Aota 		if (ret == -ENOENT) {
389512659251SNaohiro Aota 			continue;
389612659251SNaohiro Aota 		} else if (ret < 0) {
389712659251SNaohiro Aota 			btrfs_err(device->fs_info,
389812659251SNaohiro Aota 				"couldn't get super block location for mirror %d",
389912659251SNaohiro Aota 				i);
390012659251SNaohiro Aota 			errors++;
390112659251SNaohiro Aota 			continue;
390212659251SNaohiro Aota 		}
3903935e5cc9SMiao Xie 		if (bytenr + BTRFS_SUPER_INFO_SIZE >=
3904935e5cc9SMiao Xie 		    device->commit_total_bytes)
3905a512bbf8SYan Zheng 			break;
3906a512bbf8SYan Zheng 
390712659251SNaohiro Aota 		btrfs_set_super_bytenr(sb, bytenr_orig);
3908a512bbf8SYan Zheng 
3909fd08001fSEric Biggers 		crypto_shash_digest(shash, (const char *)sb + BTRFS_CSUM_SIZE,
3910fd08001fSEric Biggers 				    BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE,
3911fd08001fSEric Biggers 				    sb->csum);
3912a512bbf8SYan Zheng 
3913314b6dd0SJohannes Thumshirn 		page = find_or_create_page(mapping, bytenr >> PAGE_SHIFT,
3914314b6dd0SJohannes Thumshirn 					   GFP_NOFS);
3915314b6dd0SJohannes Thumshirn 		if (!page) {
3916fb456252SJeff Mahoney 			btrfs_err(device->fs_info,
3917314b6dd0SJohannes Thumshirn 			    "couldn't get super block page for bytenr %llu",
3918f14d104dSDavid Sterba 			    bytenr);
3919634554dcSJosef Bacik 			errors++;
3920634554dcSJosef Bacik 			continue;
3921634554dcSJosef Bacik 		}
3922634554dcSJosef Bacik 
3923314b6dd0SJohannes Thumshirn 		/* Bump the refcount for wait_dev_supers() */
3924314b6dd0SJohannes Thumshirn 		get_page(page);
3925a512bbf8SYan Zheng 
3926314b6dd0SJohannes Thumshirn 		disk_super = page_address(page);
3927314b6dd0SJohannes Thumshirn 		memcpy(disk_super, sb, BTRFS_SUPER_INFO_SIZE);
3928a512bbf8SYan Zheng 
3929387125fcSChris Mason 		/*
3930314b6dd0SJohannes Thumshirn 		 * Directly use bios here instead of relying on the page cache
3931314b6dd0SJohannes Thumshirn 		 * to do I/O, so we don't lose the ability to do integrity
3932314b6dd0SJohannes Thumshirn 		 * checking.
3933387125fcSChris Mason 		 */
393407888c66SChristoph Hellwig 		bio = bio_alloc(device->bdev, 1,
393507888c66SChristoph Hellwig 				REQ_OP_WRITE | REQ_SYNC | REQ_META | REQ_PRIO,
393607888c66SChristoph Hellwig 				GFP_NOFS);
3937314b6dd0SJohannes Thumshirn 		bio->bi_iter.bi_sector = bytenr >> SECTOR_SHIFT;
3938314b6dd0SJohannes Thumshirn 		bio->bi_private = device;
3939314b6dd0SJohannes Thumshirn 		bio->bi_end_io = btrfs_end_super_write;
3940314b6dd0SJohannes Thumshirn 		__bio_add_page(bio, page, BTRFS_SUPER_INFO_SIZE,
3941314b6dd0SJohannes Thumshirn 			       offset_in_page(bytenr));
3942314b6dd0SJohannes Thumshirn 
3943314b6dd0SJohannes Thumshirn 		/*
3944314b6dd0SJohannes Thumshirn 		 * We FUA only the first super block.  The others we allow to
3945314b6dd0SJohannes Thumshirn 		 * go down lazy and there's a short window where the on-disk
3946314b6dd0SJohannes Thumshirn 		 * copies might still contain the older version.
3947314b6dd0SJohannes Thumshirn 		 */
39481b9e619cSOmar Sandoval 		if (i == 0 && !btrfs_test_opt(device->fs_info, NOBARRIER))
3949314b6dd0SJohannes Thumshirn 			bio->bi_opf |= REQ_FUA;
3950314b6dd0SJohannes Thumshirn 
395158ff51f1SChristoph Hellwig 		btrfsic_check_bio(bio);
395258ff51f1SChristoph Hellwig 		submit_bio(bio);
39538376d9e1SNaohiro Aota 
39548376d9e1SNaohiro Aota 		if (btrfs_advance_sb_log(device, i))
39558376d9e1SNaohiro Aota 			errors++;
3956a512bbf8SYan Zheng 	}
3957a512bbf8SYan Zheng 	return errors < i ? 0 : -1;
3958a512bbf8SYan Zheng }
3959a512bbf8SYan Zheng 
3960387125fcSChris Mason /*
3961abbb3b8eSDavid Sterba  * Wait for write completion of superblocks done by write_dev_supers,
3962abbb3b8eSDavid Sterba  * @max_mirrors same for write and wait phases.
3963abbb3b8eSDavid Sterba  *
3964314b6dd0SJohannes Thumshirn  * Return number of errors when page is not found or not marked up to
3965abbb3b8eSDavid Sterba  * date.
3966abbb3b8eSDavid Sterba  */
3967abbb3b8eSDavid Sterba static int wait_dev_supers(struct btrfs_device *device, int max_mirrors)
3968abbb3b8eSDavid Sterba {
3969abbb3b8eSDavid Sterba 	int i;
3970abbb3b8eSDavid Sterba 	int errors = 0;
3971b6a535faSHoward McLauchlan 	bool primary_failed = false;
397212659251SNaohiro Aota 	int ret;
3973abbb3b8eSDavid Sterba 	u64 bytenr;
3974abbb3b8eSDavid Sterba 
3975abbb3b8eSDavid Sterba 	if (max_mirrors == 0)
3976abbb3b8eSDavid Sterba 		max_mirrors = BTRFS_SUPER_MIRROR_MAX;
3977abbb3b8eSDavid Sterba 
3978abbb3b8eSDavid Sterba 	for (i = 0; i < max_mirrors; i++) {
3979314b6dd0SJohannes Thumshirn 		struct page *page;
3980314b6dd0SJohannes Thumshirn 
398112659251SNaohiro Aota 		ret = btrfs_sb_log_location(device, i, READ, &bytenr);
398212659251SNaohiro Aota 		if (ret == -ENOENT) {
398312659251SNaohiro Aota 			break;
398412659251SNaohiro Aota 		} else if (ret < 0) {
398512659251SNaohiro Aota 			errors++;
398612659251SNaohiro Aota 			if (i == 0)
398712659251SNaohiro Aota 				primary_failed = true;
398812659251SNaohiro Aota 			continue;
398912659251SNaohiro Aota 		}
3990abbb3b8eSDavid Sterba 		if (bytenr + BTRFS_SUPER_INFO_SIZE >=
3991abbb3b8eSDavid Sterba 		    device->commit_total_bytes)
3992abbb3b8eSDavid Sterba 			break;
3993abbb3b8eSDavid Sterba 
3994314b6dd0SJohannes Thumshirn 		page = find_get_page(device->bdev->bd_inode->i_mapping,
3995314b6dd0SJohannes Thumshirn 				     bytenr >> PAGE_SHIFT);
3996314b6dd0SJohannes Thumshirn 		if (!page) {
3997abbb3b8eSDavid Sterba 			errors++;
3998b6a535faSHoward McLauchlan 			if (i == 0)
3999b6a535faSHoward McLauchlan 				primary_failed = true;
4000abbb3b8eSDavid Sterba 			continue;
4001abbb3b8eSDavid Sterba 		}
4002314b6dd0SJohannes Thumshirn 		/* Page is submitted locked and unlocked once the IO completes */
4003314b6dd0SJohannes Thumshirn 		wait_on_page_locked(page);
4004314b6dd0SJohannes Thumshirn 		if (PageError(page)) {
4005abbb3b8eSDavid Sterba 			errors++;
4006b6a535faSHoward McLauchlan 			if (i == 0)
4007b6a535faSHoward McLauchlan 				primary_failed = true;
4008b6a535faSHoward McLauchlan 		}
4009abbb3b8eSDavid Sterba 
4010314b6dd0SJohannes Thumshirn 		/* Drop our reference */
4011314b6dd0SJohannes Thumshirn 		put_page(page);
4012abbb3b8eSDavid Sterba 
4013314b6dd0SJohannes Thumshirn 		/* Drop the reference from the writing run */
4014314b6dd0SJohannes Thumshirn 		put_page(page);
4015abbb3b8eSDavid Sterba 	}
4016abbb3b8eSDavid Sterba 
4017b6a535faSHoward McLauchlan 	/* log error, force error return */
4018b6a535faSHoward McLauchlan 	if (primary_failed) {
4019b6a535faSHoward McLauchlan 		btrfs_err(device->fs_info, "error writing primary super block to device %llu",
4020b6a535faSHoward McLauchlan 			  device->devid);
4021b6a535faSHoward McLauchlan 		return -1;
4022b6a535faSHoward McLauchlan 	}
4023b6a535faSHoward McLauchlan 
4024abbb3b8eSDavid Sterba 	return errors < i ? 0 : -1;
4025abbb3b8eSDavid Sterba }
4026abbb3b8eSDavid Sterba 
4027abbb3b8eSDavid Sterba /*
4028387125fcSChris Mason  * endio for the write_dev_flush, this will wake anyone waiting
4029387125fcSChris Mason  * for the barrier when it is done
4030387125fcSChris Mason  */
40314246a0b6SChristoph Hellwig static void btrfs_end_empty_barrier(struct bio *bio)
4032387125fcSChris Mason {
4033f9e69aa9SChristoph Hellwig 	bio_uninit(bio);
4034387125fcSChris Mason 	complete(bio->bi_private);
4035387125fcSChris Mason }
4036387125fcSChris Mason 
4037387125fcSChris Mason /*
40384fc6441aSAnand Jain  * Submit a flush request to the device if it supports it. Error handling is
40394fc6441aSAnand Jain  * done in the waiting counterpart.
4040387125fcSChris Mason  */
40414fc6441aSAnand Jain static void write_dev_flush(struct btrfs_device *device)
4042387125fcSChris Mason {
4043f9e69aa9SChristoph Hellwig 	struct bio *bio = &device->flush_bio;
4044387125fcSChris Mason 
4045bfd3ea94SAnand Jain 	device->last_flush_error = BLK_STS_OK;
4046bfd3ea94SAnand Jain 
4047a91cf0ffSWang Yugui #ifndef CONFIG_BTRFS_FS_CHECK_INTEGRITY
4048a91cf0ffSWang Yugui 	/*
4049a91cf0ffSWang Yugui 	 * When a disk has write caching disabled, we skip submission of a bio
4050a91cf0ffSWang Yugui 	 * with flush and sync requests before writing the superblock, since
4051a91cf0ffSWang Yugui 	 * it's not needed. However when the integrity checker is enabled, this
4052a91cf0ffSWang Yugui 	 * results in reports that there are metadata blocks referred by a
4053a91cf0ffSWang Yugui 	 * superblock that were not properly flushed. So don't skip the bio
4054a91cf0ffSWang Yugui 	 * submission only when the integrity checker is enabled for the sake
4055a91cf0ffSWang Yugui 	 * of simplicity, since this is a debug tool and not meant for use in
4056a91cf0ffSWang Yugui 	 * non-debug builds.
4057a91cf0ffSWang Yugui 	 */
405808e688fdSChristoph Hellwig 	if (!bdev_write_cache(device->bdev))
40594fc6441aSAnand Jain 		return;
4060a91cf0ffSWang Yugui #endif
4061387125fcSChris Mason 
4062f9e69aa9SChristoph Hellwig 	bio_init(bio, device->bdev, NULL, 0,
4063f9e69aa9SChristoph Hellwig 		 REQ_OP_WRITE | REQ_SYNC | REQ_PREFLUSH);
4064387125fcSChris Mason 	bio->bi_end_io = btrfs_end_empty_barrier;
4065387125fcSChris Mason 	init_completion(&device->flush_wait);
4066387125fcSChris Mason 	bio->bi_private = &device->flush_wait;
4067387125fcSChris Mason 
406858ff51f1SChristoph Hellwig 	btrfsic_check_bio(bio);
406958ff51f1SChristoph Hellwig 	submit_bio(bio);
40701c3063b6SAnand Jain 	set_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state);
40714fc6441aSAnand Jain }
4072387125fcSChris Mason 
40734fc6441aSAnand Jain /*
40744fc6441aSAnand Jain  * If the flush bio has been submitted by write_dev_flush, wait for it.
40751b465784SAnand Jain  * Return true for any error, and false otherwise.
40764fc6441aSAnand Jain  */
40771b465784SAnand Jain static bool wait_dev_flush(struct btrfs_device *device)
40784fc6441aSAnand Jain {
4079f9e69aa9SChristoph Hellwig 	struct bio *bio = &device->flush_bio;
40804fc6441aSAnand Jain 
40817e812f20SAnand Jain 	if (!test_and_clear_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state))
40821b465784SAnand Jain 		return false;
40834fc6441aSAnand Jain 
40842980d574SDavid Sterba 	wait_for_completion_io(&device->flush_wait);
40854fc6441aSAnand Jain 
4086bfd3ea94SAnand Jain 	if (bio->bi_status) {
4087bfd3ea94SAnand Jain 		device->last_flush_error = bio->bi_status;
4088bfd3ea94SAnand Jain 		btrfs_dev_stat_inc_and_print(device, BTRFS_DEV_STAT_FLUSH_ERRS);
40891b465784SAnand Jain 		return true;
4090bfd3ea94SAnand Jain 	}
4091bfd3ea94SAnand Jain 
40921b465784SAnand Jain 	return false;
4093387125fcSChris Mason }
4094387125fcSChris Mason 
4095387125fcSChris Mason /*
4096387125fcSChris Mason  * send an empty flush down to each device in parallel,
4097387125fcSChris Mason  * then wait for them
4098387125fcSChris Mason  */
4099387125fcSChris Mason static int barrier_all_devices(struct btrfs_fs_info *info)
4100387125fcSChris Mason {
4101387125fcSChris Mason 	struct list_head *head;
4102387125fcSChris Mason 	struct btrfs_device *dev;
41035af3e8ccSStefan Behrens 	int errors_wait = 0;
4104387125fcSChris Mason 
41051538e6c5SDavid Sterba 	lockdep_assert_held(&info->fs_devices->device_list_mutex);
4106387125fcSChris Mason 	/* send down all the barriers */
4107387125fcSChris Mason 	head = &info->fs_devices->devices;
41081538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
4109e6e674bdSAnand Jain 		if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
4110f88ba6a2SHidetoshi Seto 			continue;
4111cea7c8bfSAnand Jain 		if (!dev->bdev)
4112387125fcSChris Mason 			continue;
4113e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
4114ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
4115387125fcSChris Mason 			continue;
4116387125fcSChris Mason 
41174fc6441aSAnand Jain 		write_dev_flush(dev);
4118387125fcSChris Mason 	}
4119387125fcSChris Mason 
4120387125fcSChris Mason 	/* wait for all the barriers */
41211538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
4122e6e674bdSAnand Jain 		if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
4123f88ba6a2SHidetoshi Seto 			continue;
4124387125fcSChris Mason 		if (!dev->bdev) {
41255af3e8ccSStefan Behrens 			errors_wait++;
4126387125fcSChris Mason 			continue;
4127387125fcSChris Mason 		}
4128e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
4129ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
4130387125fcSChris Mason 			continue;
4131387125fcSChris Mason 
41321b465784SAnand Jain 		if (wait_dev_flush(dev))
41335af3e8ccSStefan Behrens 			errors_wait++;
4134387125fcSChris Mason 	}
4135401b41e5SAnand Jain 
4136401b41e5SAnand Jain 	/*
4137de38a206SAnand Jain 	 * Checks last_flush_error of disks in order to determine the device
4138de38a206SAnand Jain 	 * state.
4139401b41e5SAnand Jain 	 */
4140de38a206SAnand Jain 	if (errors_wait && !btrfs_check_rw_degradable(info, NULL))
4141de38a206SAnand Jain 		return -EIO;
4142de38a206SAnand Jain 
4143387125fcSChris Mason 	return 0;
4144387125fcSChris Mason }
4145387125fcSChris Mason 
4146943c6e99SZhao Lei int btrfs_get_num_tolerated_disk_barrier_failures(u64 flags)
4147943c6e99SZhao Lei {
41488789f4feSZhao Lei 	int raid_type;
41498789f4feSZhao Lei 	int min_tolerated = INT_MAX;
4150943c6e99SZhao Lei 
41518789f4feSZhao Lei 	if ((flags & BTRFS_BLOCK_GROUP_PROFILE_MASK) == 0 ||
41528789f4feSZhao Lei 	    (flags & BTRFS_AVAIL_ALLOC_BIT_SINGLE))
41538c3e3582SDavid Sterba 		min_tolerated = min_t(int, min_tolerated,
41548789f4feSZhao Lei 				    btrfs_raid_array[BTRFS_RAID_SINGLE].
41558789f4feSZhao Lei 				    tolerated_failures);
4156943c6e99SZhao Lei 
41578789f4feSZhao Lei 	for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) {
41588789f4feSZhao Lei 		if (raid_type == BTRFS_RAID_SINGLE)
41598789f4feSZhao Lei 			continue;
416041a6e891SAnand Jain 		if (!(flags & btrfs_raid_array[raid_type].bg_flag))
41618789f4feSZhao Lei 			continue;
41628c3e3582SDavid Sterba 		min_tolerated = min_t(int, min_tolerated,
41638789f4feSZhao Lei 				    btrfs_raid_array[raid_type].
41648789f4feSZhao Lei 				    tolerated_failures);
41658789f4feSZhao Lei 	}
4166943c6e99SZhao Lei 
41678789f4feSZhao Lei 	if (min_tolerated == INT_MAX) {
4168ab8d0fc4SJeff Mahoney 		pr_warn("BTRFS: unknown raid flag: %llu", flags);
41698789f4feSZhao Lei 		min_tolerated = 0;
41708789f4feSZhao Lei 	}
41718789f4feSZhao Lei 
41728789f4feSZhao Lei 	return min_tolerated;
4173943c6e99SZhao Lei }
4174943c6e99SZhao Lei 
4175eece6a9cSDavid Sterba int write_all_supers(struct btrfs_fs_info *fs_info, int max_mirrors)
4176f2984462SChris Mason {
4177e5e9a520SChris Mason 	struct list_head *head;
4178f2984462SChris Mason 	struct btrfs_device *dev;
4179a061fc8dSChris Mason 	struct btrfs_super_block *sb;
4180f2984462SChris Mason 	struct btrfs_dev_item *dev_item;
4181f2984462SChris Mason 	int ret;
4182f2984462SChris Mason 	int do_barriers;
4183a236aed1SChris Mason 	int max_errors;
4184a236aed1SChris Mason 	int total_errors = 0;
4185a061fc8dSChris Mason 	u64 flags;
4186f2984462SChris Mason 
41870b246afaSJeff Mahoney 	do_barriers = !btrfs_test_opt(fs_info, NOBARRIER);
4188fed3b381SLiu Bo 
4189fed3b381SLiu Bo 	/*
4190fed3b381SLiu Bo 	 * max_mirrors == 0 indicates we're from commit_transaction,
4191fed3b381SLiu Bo 	 * not from fsync where the tree roots in fs_info have not
4192fed3b381SLiu Bo 	 * been consistent on disk.
4193fed3b381SLiu Bo 	 */
4194fed3b381SLiu Bo 	if (max_mirrors == 0)
41950b246afaSJeff Mahoney 		backup_super_roots(fs_info);
4196f2984462SChris Mason 
41970b246afaSJeff Mahoney 	sb = fs_info->super_for_commit;
4198a061fc8dSChris Mason 	dev_item = &sb->dev_item;
4199e5e9a520SChris Mason 
42000b246afaSJeff Mahoney 	mutex_lock(&fs_info->fs_devices->device_list_mutex);
42010b246afaSJeff Mahoney 	head = &fs_info->fs_devices->devices;
42020b246afaSJeff Mahoney 	max_errors = btrfs_super_num_devices(fs_info->super_copy) - 1;
4203387125fcSChris Mason 
42045af3e8ccSStefan Behrens 	if (do_barriers) {
42050b246afaSJeff Mahoney 		ret = barrier_all_devices(fs_info);
42065af3e8ccSStefan Behrens 		if (ret) {
42075af3e8ccSStefan Behrens 			mutex_unlock(
42080b246afaSJeff Mahoney 				&fs_info->fs_devices->device_list_mutex);
42090b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret,
42105af3e8ccSStefan Behrens 					      "errors while submitting device barriers.");
42115af3e8ccSStefan Behrens 			return ret;
42125af3e8ccSStefan Behrens 		}
42135af3e8ccSStefan Behrens 	}
4214387125fcSChris Mason 
42151538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
4216dfe25020SChris Mason 		if (!dev->bdev) {
4217dfe25020SChris Mason 			total_errors++;
4218dfe25020SChris Mason 			continue;
4219dfe25020SChris Mason 		}
4220e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
4221ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
4222dfe25020SChris Mason 			continue;
4223dfe25020SChris Mason 
42242b82032cSYan Zheng 		btrfs_set_stack_device_generation(dev_item, 0);
4225a061fc8dSChris Mason 		btrfs_set_stack_device_type(dev_item, dev->type);
4226a061fc8dSChris Mason 		btrfs_set_stack_device_id(dev_item, dev->devid);
42277df69d3eSMiao Xie 		btrfs_set_stack_device_total_bytes(dev_item,
4228935e5cc9SMiao Xie 						   dev->commit_total_bytes);
4229ce7213c7SMiao Xie 		btrfs_set_stack_device_bytes_used(dev_item,
4230ce7213c7SMiao Xie 						  dev->commit_bytes_used);
4231a061fc8dSChris Mason 		btrfs_set_stack_device_io_align(dev_item, dev->io_align);
4232a061fc8dSChris Mason 		btrfs_set_stack_device_io_width(dev_item, dev->io_width);
4233a061fc8dSChris Mason 		btrfs_set_stack_device_sector_size(dev_item, dev->sector_size);
4234a061fc8dSChris Mason 		memcpy(dev_item->uuid, dev->uuid, BTRFS_UUID_SIZE);
42357239ff4bSNikolay Borisov 		memcpy(dev_item->fsid, dev->fs_devices->metadata_uuid,
42367239ff4bSNikolay Borisov 		       BTRFS_FSID_SIZE);
4237a512bbf8SYan Zheng 
4238a061fc8dSChris Mason 		flags = btrfs_super_flags(sb);
4239a061fc8dSChris Mason 		btrfs_set_super_flags(sb, flags | BTRFS_HEADER_FLAG_WRITTEN);
4240f2984462SChris Mason 
424175cb857dSQu Wenruo 		ret = btrfs_validate_write_super(fs_info, sb);
424275cb857dSQu Wenruo 		if (ret < 0) {
424375cb857dSQu Wenruo 			mutex_unlock(&fs_info->fs_devices->device_list_mutex);
424475cb857dSQu Wenruo 			btrfs_handle_fs_error(fs_info, -EUCLEAN,
424575cb857dSQu Wenruo 				"unexpected superblock corruption detected");
424675cb857dSQu Wenruo 			return -EUCLEAN;
424775cb857dSQu Wenruo 		}
424875cb857dSQu Wenruo 
4249abbb3b8eSDavid Sterba 		ret = write_dev_supers(dev, sb, max_mirrors);
4250a236aed1SChris Mason 		if (ret)
4251a236aed1SChris Mason 			total_errors++;
4252f2984462SChris Mason 	}
4253a236aed1SChris Mason 	if (total_errors > max_errors) {
42540b246afaSJeff Mahoney 		btrfs_err(fs_info, "%d errors while writing supers",
4255d397712bSChris Mason 			  total_errors);
42560b246afaSJeff Mahoney 		mutex_unlock(&fs_info->fs_devices->device_list_mutex);
425779787eaaSJeff Mahoney 
42589d565ba4SStefan Behrens 		/* FUA is masked off if unsupported and can't be the reason */
42590b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, -EIO,
42600b246afaSJeff Mahoney 				      "%d errors while writing supers",
42610b246afaSJeff Mahoney 				      total_errors);
42629d565ba4SStefan Behrens 		return -EIO;
4263a236aed1SChris Mason 	}
4264f2984462SChris Mason 
4265a512bbf8SYan Zheng 	total_errors = 0;
42661538e6c5SDavid Sterba 	list_for_each_entry(dev, head, dev_list) {
4267dfe25020SChris Mason 		if (!dev->bdev)
4268dfe25020SChris Mason 			continue;
4269e12c9621SAnand Jain 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
4270ebbede42SAnand Jain 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
4271dfe25020SChris Mason 			continue;
4272dfe25020SChris Mason 
4273abbb3b8eSDavid Sterba 		ret = wait_dev_supers(dev, max_mirrors);
4274a512bbf8SYan Zheng 		if (ret)
42751259ab75SChris Mason 			total_errors++;
4276f2984462SChris Mason 	}
42770b246afaSJeff Mahoney 	mutex_unlock(&fs_info->fs_devices->device_list_mutex);
4278a236aed1SChris Mason 	if (total_errors > max_errors) {
42790b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, -EIO,
42800b246afaSJeff Mahoney 				      "%d errors while writing supers",
42810b246afaSJeff Mahoney 				      total_errors);
428279787eaaSJeff Mahoney 		return -EIO;
4283a236aed1SChris Mason 	}
4284f2984462SChris Mason 	return 0;
4285f2984462SChris Mason }
4286f2984462SChris Mason 
4287cb517eabSMiao Xie /* Drop a fs root from the radix tree and free it. */
4288cb517eabSMiao Xie void btrfs_drop_and_free_fs_root(struct btrfs_fs_info *fs_info,
4289cb517eabSMiao Xie 				  struct btrfs_root *root)
42902619ba1fSChris Mason {
42914785e24fSJosef Bacik 	bool drop_ref = false;
42924785e24fSJosef Bacik 
4293fc7cbcd4SDavid Sterba 	spin_lock(&fs_info->fs_roots_radix_lock);
4294fc7cbcd4SDavid Sterba 	radix_tree_delete(&fs_info->fs_roots_radix,
4295fc7cbcd4SDavid Sterba 			  (unsigned long)root->root_key.objectid);
4296fc7cbcd4SDavid Sterba 	if (test_and_clear_bit(BTRFS_ROOT_IN_RADIX, &root->state))
42974785e24fSJosef Bacik 		drop_ref = true;
4298fc7cbcd4SDavid Sterba 	spin_unlock(&fs_info->fs_roots_radix_lock);
429976dda93cSYan, Zheng 
430084961539SJosef Bacik 	if (BTRFS_FS_ERROR(fs_info)) {
4301ef67963dSJosef Bacik 		ASSERT(root->log_root == NULL);
43021c1ea4f7SLiu Bo 		if (root->reloc_root) {
430300246528SJosef Bacik 			btrfs_put_root(root->reloc_root);
43041c1ea4f7SLiu Bo 			root->reloc_root = NULL;
43051c1ea4f7SLiu Bo 		}
43061c1ea4f7SLiu Bo 	}
43073321719eSLiu Bo 
43084785e24fSJosef Bacik 	if (drop_ref)
430900246528SJosef Bacik 		btrfs_put_root(root);
43102619ba1fSChris Mason }
43112619ba1fSChris Mason 
4312c146afadSYan Zheng int btrfs_cleanup_fs_roots(struct btrfs_fs_info *fs_info)
4313c146afadSYan Zheng {
4314fc7cbcd4SDavid Sterba 	u64 root_objectid = 0;
4315fc7cbcd4SDavid Sterba 	struct btrfs_root *gang[8];
4316fc7cbcd4SDavid Sterba 	int i = 0;
431765d33fd7SQu Wenruo 	int err = 0;
4318fc7cbcd4SDavid Sterba 	unsigned int ret = 0;
4319c146afadSYan Zheng 
4320c146afadSYan Zheng 	while (1) {
4321fc7cbcd4SDavid Sterba 		spin_lock(&fs_info->fs_roots_radix_lock);
4322fc7cbcd4SDavid Sterba 		ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
4323fc7cbcd4SDavid Sterba 					     (void **)gang, root_objectid,
4324fc7cbcd4SDavid Sterba 					     ARRAY_SIZE(gang));
4325fc7cbcd4SDavid Sterba 		if (!ret) {
4326fc7cbcd4SDavid Sterba 			spin_unlock(&fs_info->fs_roots_radix_lock);
4327c146afadSYan Zheng 			break;
432865d33fd7SQu Wenruo 		}
4329fc7cbcd4SDavid Sterba 		root_objectid = gang[ret - 1]->root_key.objectid + 1;
433066b4ffd1SJosef Bacik 
4331fc7cbcd4SDavid Sterba 		for (i = 0; i < ret; i++) {
4332fc7cbcd4SDavid Sterba 			/* Avoid to grab roots in dead_roots */
4333fc7cbcd4SDavid Sterba 			if (btrfs_root_refs(&gang[i]->root_item) == 0) {
4334fc7cbcd4SDavid Sterba 				gang[i] = NULL;
433565d33fd7SQu Wenruo 				continue;
4336c146afadSYan Zheng 			}
4337fc7cbcd4SDavid Sterba 			/* grab all the search result for later use */
4338fc7cbcd4SDavid Sterba 			gang[i] = btrfs_grab_root(gang[i]);
4339fc7cbcd4SDavid Sterba 		}
4340fc7cbcd4SDavid Sterba 		spin_unlock(&fs_info->fs_roots_radix_lock);
4341fc7cbcd4SDavid Sterba 
4342fc7cbcd4SDavid Sterba 		for (i = 0; i < ret; i++) {
4343fc7cbcd4SDavid Sterba 			if (!gang[i])
4344fc7cbcd4SDavid Sterba 				continue;
4345fc7cbcd4SDavid Sterba 			root_objectid = gang[i]->root_key.objectid;
4346fc7cbcd4SDavid Sterba 			err = btrfs_orphan_cleanup(gang[i]);
4347fc7cbcd4SDavid Sterba 			if (err)
43486989627dSJosef Bacik 				goto out;
4349fc7cbcd4SDavid Sterba 			btrfs_put_root(gang[i]);
4350fc7cbcd4SDavid Sterba 		}
4351fc7cbcd4SDavid Sterba 		root_objectid++;
4352c146afadSYan Zheng 	}
43536989627dSJosef Bacik out:
4354fc7cbcd4SDavid Sterba 	/* release the uncleaned roots due to error */
4355fc7cbcd4SDavid Sterba 	for (; i < ret; i++) {
4356fc7cbcd4SDavid Sterba 		if (gang[i])
4357fc7cbcd4SDavid Sterba 			btrfs_put_root(gang[i]);
435865d33fd7SQu Wenruo 	}
435965d33fd7SQu Wenruo 	return err;
4360c146afadSYan Zheng }
4361c146afadSYan Zheng 
43626bccf3abSJeff Mahoney int btrfs_commit_super(struct btrfs_fs_info *fs_info)
4363c146afadSYan Zheng {
43646bccf3abSJeff Mahoney 	struct btrfs_root *root = fs_info->tree_root;
4365c146afadSYan Zheng 	struct btrfs_trans_handle *trans;
4366c146afadSYan Zheng 
43670b246afaSJeff Mahoney 	mutex_lock(&fs_info->cleaner_mutex);
43682ff7e61eSJeff Mahoney 	btrfs_run_delayed_iputs(fs_info);
43690b246afaSJeff Mahoney 	mutex_unlock(&fs_info->cleaner_mutex);
43700b246afaSJeff Mahoney 	wake_up_process(fs_info->cleaner_kthread);
4371c71bf099SYan, Zheng 
4372c71bf099SYan, Zheng 	/* wait until ongoing cleanup work done */
43730b246afaSJeff Mahoney 	down_write(&fs_info->cleanup_work_sem);
43740b246afaSJeff Mahoney 	up_write(&fs_info->cleanup_work_sem);
4375c71bf099SYan, Zheng 
43767a7eaa40SJosef Bacik 	trans = btrfs_join_transaction(root);
43773612b495STsutomu Itoh 	if (IS_ERR(trans))
43783612b495STsutomu Itoh 		return PTR_ERR(trans);
43793a45bb20SJeff Mahoney 	return btrfs_commit_transaction(trans);
4380c146afadSYan Zheng }
4381c146afadSYan Zheng 
438236c86a9eSQu Wenruo static void warn_about_uncommitted_trans(struct btrfs_fs_info *fs_info)
438336c86a9eSQu Wenruo {
438436c86a9eSQu Wenruo 	struct btrfs_transaction *trans;
438536c86a9eSQu Wenruo 	struct btrfs_transaction *tmp;
438636c86a9eSQu Wenruo 	bool found = false;
438736c86a9eSQu Wenruo 
438836c86a9eSQu Wenruo 	if (list_empty(&fs_info->trans_list))
438936c86a9eSQu Wenruo 		return;
439036c86a9eSQu Wenruo 
439136c86a9eSQu Wenruo 	/*
439236c86a9eSQu Wenruo 	 * This function is only called at the very end of close_ctree(),
439336c86a9eSQu Wenruo 	 * thus no other running transaction, no need to take trans_lock.
439436c86a9eSQu Wenruo 	 */
439536c86a9eSQu Wenruo 	ASSERT(test_bit(BTRFS_FS_CLOSING_DONE, &fs_info->flags));
439636c86a9eSQu Wenruo 	list_for_each_entry_safe(trans, tmp, &fs_info->trans_list, list) {
439736c86a9eSQu Wenruo 		struct extent_state *cached = NULL;
439836c86a9eSQu Wenruo 		u64 dirty_bytes = 0;
439936c86a9eSQu Wenruo 		u64 cur = 0;
440036c86a9eSQu Wenruo 		u64 found_start;
440136c86a9eSQu Wenruo 		u64 found_end;
440236c86a9eSQu Wenruo 
440336c86a9eSQu Wenruo 		found = true;
440436c86a9eSQu Wenruo 		while (!find_first_extent_bit(&trans->dirty_pages, cur,
440536c86a9eSQu Wenruo 			&found_start, &found_end, EXTENT_DIRTY, &cached)) {
440636c86a9eSQu Wenruo 			dirty_bytes += found_end + 1 - found_start;
440736c86a9eSQu Wenruo 			cur = found_end + 1;
440836c86a9eSQu Wenruo 		}
440936c86a9eSQu Wenruo 		btrfs_warn(fs_info,
441036c86a9eSQu Wenruo 	"transaction %llu (with %llu dirty metadata bytes) is not committed",
441136c86a9eSQu Wenruo 			   trans->transid, dirty_bytes);
441236c86a9eSQu Wenruo 		btrfs_cleanup_one_transaction(trans, fs_info);
441336c86a9eSQu Wenruo 
441436c86a9eSQu Wenruo 		if (trans == fs_info->running_transaction)
441536c86a9eSQu Wenruo 			fs_info->running_transaction = NULL;
441636c86a9eSQu Wenruo 		list_del_init(&trans->list);
441736c86a9eSQu Wenruo 
441836c86a9eSQu Wenruo 		btrfs_put_transaction(trans);
441936c86a9eSQu Wenruo 		trace_btrfs_transaction_commit(fs_info);
442036c86a9eSQu Wenruo 	}
442136c86a9eSQu Wenruo 	ASSERT(!found);
442236c86a9eSQu Wenruo }
442336c86a9eSQu Wenruo 
4424b105e927SDavid Sterba void __cold close_ctree(struct btrfs_fs_info *fs_info)
4425eb60ceacSChris Mason {
4426c146afadSYan Zheng 	int ret;
4427e089f05cSChris Mason 
4428afcdd129SJosef Bacik 	set_bit(BTRFS_FS_CLOSING_START, &fs_info->flags);
442931e70e52SFilipe Manana 
443031e70e52SFilipe Manana 	/*
44318a1f1e3dSFilipe Manana 	 * If we had UNFINISHED_DROPS we could still be processing them, so
44328a1f1e3dSFilipe Manana 	 * clear that bit and wake up relocation so it can stop.
44338a1f1e3dSFilipe Manana 	 * We must do this before stopping the block group reclaim task, because
44348a1f1e3dSFilipe Manana 	 * at btrfs_relocate_block_group() we wait for this bit, and after the
44358a1f1e3dSFilipe Manana 	 * wait we stop with -EINTR if btrfs_fs_closing() returns non-zero - we
44368a1f1e3dSFilipe Manana 	 * have just set BTRFS_FS_CLOSING_START, so btrfs_fs_closing() will
44378a1f1e3dSFilipe Manana 	 * return 1.
44388a1f1e3dSFilipe Manana 	 */
44398a1f1e3dSFilipe Manana 	btrfs_wake_unfinished_drop(fs_info);
44408a1f1e3dSFilipe Manana 
44418a1f1e3dSFilipe Manana 	/*
444231e70e52SFilipe Manana 	 * We may have the reclaim task running and relocating a data block group,
444331e70e52SFilipe Manana 	 * in which case it may create delayed iputs. So stop it before we park
444431e70e52SFilipe Manana 	 * the cleaner kthread otherwise we can get new delayed iputs after
444531e70e52SFilipe Manana 	 * parking the cleaner, and that can make the async reclaim task to hang
444631e70e52SFilipe Manana 	 * if it's waiting for delayed iputs to complete, since the cleaner is
444731e70e52SFilipe Manana 	 * parked and can not run delayed iputs - this will make us hang when
444831e70e52SFilipe Manana 	 * trying to stop the async reclaim task.
444931e70e52SFilipe Manana 	 */
445031e70e52SFilipe Manana 	cancel_work_sync(&fs_info->reclaim_bgs_work);
4451d6fd0ae2SOmar Sandoval 	/*
4452d6fd0ae2SOmar Sandoval 	 * We don't want the cleaner to start new transactions, add more delayed
4453d6fd0ae2SOmar Sandoval 	 * iputs, etc. while we're closing. We can't use kthread_stop() yet
4454d6fd0ae2SOmar Sandoval 	 * because that frees the task_struct, and the transaction kthread might
4455d6fd0ae2SOmar Sandoval 	 * still try to wake up the cleaner.
4456d6fd0ae2SOmar Sandoval 	 */
4457d6fd0ae2SOmar Sandoval 	kthread_park(fs_info->cleaner_kthread);
4458a2135011SChris Mason 
44597343dd61SJustin Maggard 	/* wait for the qgroup rescan worker to stop */
4460d06f23d6SJeff Mahoney 	btrfs_qgroup_wait_for_completion(fs_info, false);
44617343dd61SJustin Maggard 
4462803b2f54SStefan Behrens 	/* wait for the uuid_scan task to finish */
4463803b2f54SStefan Behrens 	down(&fs_info->uuid_tree_rescan_sem);
4464803b2f54SStefan Behrens 	/* avoid complains from lockdep et al., set sem back to initial state */
4465803b2f54SStefan Behrens 	up(&fs_info->uuid_tree_rescan_sem);
4466803b2f54SStefan Behrens 
4467837d5b6eSIlya Dryomov 	/* pause restriper - we want to resume on mount */
4468aa1b8cd4SStefan Behrens 	btrfs_pause_balance(fs_info);
4469837d5b6eSIlya Dryomov 
44708dabb742SStefan Behrens 	btrfs_dev_replace_suspend_for_unmount(fs_info);
44718dabb742SStefan Behrens 
4472aa1b8cd4SStefan Behrens 	btrfs_scrub_cancel(fs_info);
44734cb5300bSChris Mason 
44744cb5300bSChris Mason 	/* wait for any defraggers to finish */
44754cb5300bSChris Mason 	wait_event(fs_info->transaction_wait,
44764cb5300bSChris Mason 		   (atomic_read(&fs_info->defrag_running) == 0));
44774cb5300bSChris Mason 
44784cb5300bSChris Mason 	/* clear out the rbtree of defraggable inodes */
447926176e7cSMiao Xie 	btrfs_cleanup_defrag_inodes(fs_info);
44804cb5300bSChris Mason 
4481a362bb86SFilipe Manana 	/*
4482a362bb86SFilipe Manana 	 * After we parked the cleaner kthread, ordered extents may have
4483a362bb86SFilipe Manana 	 * completed and created new delayed iputs. If one of the async reclaim
4484a362bb86SFilipe Manana 	 * tasks is running and in the RUN_DELAYED_IPUTS flush state, then we
4485a362bb86SFilipe Manana 	 * can hang forever trying to stop it, because if a delayed iput is
4486a362bb86SFilipe Manana 	 * added after it ran btrfs_run_delayed_iputs() and before it called
4487a362bb86SFilipe Manana 	 * btrfs_wait_on_delayed_iputs(), it will hang forever since there is
4488a362bb86SFilipe Manana 	 * no one else to run iputs.
4489a362bb86SFilipe Manana 	 *
4490a362bb86SFilipe Manana 	 * So wait for all ongoing ordered extents to complete and then run
4491a362bb86SFilipe Manana 	 * delayed iputs. This works because once we reach this point no one
4492a362bb86SFilipe Manana 	 * can either create new ordered extents nor create delayed iputs
4493a362bb86SFilipe Manana 	 * through some other means.
4494a362bb86SFilipe Manana 	 *
4495a362bb86SFilipe Manana 	 * Also note that btrfs_wait_ordered_roots() is not safe here, because
4496a362bb86SFilipe Manana 	 * it waits for BTRFS_ORDERED_COMPLETE to be set on an ordered extent,
4497a362bb86SFilipe Manana 	 * but the delayed iput for the respective inode is made only when doing
4498a362bb86SFilipe Manana 	 * the final btrfs_put_ordered_extent() (which must happen at
4499a362bb86SFilipe Manana 	 * btrfs_finish_ordered_io() when we are unmounting).
4500a362bb86SFilipe Manana 	 */
4501a362bb86SFilipe Manana 	btrfs_flush_workqueue(fs_info->endio_write_workers);
4502a362bb86SFilipe Manana 	/* Ordered extents for free space inodes. */
4503a362bb86SFilipe Manana 	btrfs_flush_workqueue(fs_info->endio_freespace_worker);
4504a362bb86SFilipe Manana 	btrfs_run_delayed_iputs(fs_info);
4505a362bb86SFilipe Manana 
450621c7e756SMiao Xie 	cancel_work_sync(&fs_info->async_reclaim_work);
450757056740SJosef Bacik 	cancel_work_sync(&fs_info->async_data_reclaim_work);
4508576fa348SJosef Bacik 	cancel_work_sync(&fs_info->preempt_reclaim_work);
450921c7e756SMiao Xie 
4510b0643e59SDennis Zhou 	/* Cancel or finish ongoing discard work */
4511b0643e59SDennis Zhou 	btrfs_discard_cleanup(fs_info);
4512b0643e59SDennis Zhou 
4513bc98a42cSDavid Howells 	if (!sb_rdonly(fs_info->sb)) {
4514e44163e1SJeff Mahoney 		/*
4515d6fd0ae2SOmar Sandoval 		 * The cleaner kthread is stopped, so do one final pass over
4516d6fd0ae2SOmar Sandoval 		 * unused block groups.
4517e44163e1SJeff Mahoney 		 */
45180b246afaSJeff Mahoney 		btrfs_delete_unused_bgs(fs_info);
4519e44163e1SJeff Mahoney 
4520f0cc2cd7SFilipe Manana 		/*
4521f0cc2cd7SFilipe Manana 		 * There might be existing delayed inode workers still running
4522f0cc2cd7SFilipe Manana 		 * and holding an empty delayed inode item. We must wait for
4523f0cc2cd7SFilipe Manana 		 * them to complete first because they can create a transaction.
4524f0cc2cd7SFilipe Manana 		 * This happens when someone calls btrfs_balance_delayed_items()
4525f0cc2cd7SFilipe Manana 		 * and then a transaction commit runs the same delayed nodes
4526f0cc2cd7SFilipe Manana 		 * before any delayed worker has done something with the nodes.
4527f0cc2cd7SFilipe Manana 		 * We must wait for any worker here and not at transaction
4528f0cc2cd7SFilipe Manana 		 * commit time since that could cause a deadlock.
4529f0cc2cd7SFilipe Manana 		 * This is a very rare case.
4530f0cc2cd7SFilipe Manana 		 */
4531f0cc2cd7SFilipe Manana 		btrfs_flush_workqueue(fs_info->delayed_workers);
4532f0cc2cd7SFilipe Manana 
45336bccf3abSJeff Mahoney 		ret = btrfs_commit_super(fs_info);
4534d397712bSChris Mason 		if (ret)
453504892340SEric Sandeen 			btrfs_err(fs_info, "commit super ret %d", ret);
4536c146afadSYan Zheng 	}
4537ed2ff2cbSChris Mason 
453884961539SJosef Bacik 	if (BTRFS_FS_ERROR(fs_info))
45392ff7e61eSJeff Mahoney 		btrfs_error_commit_super(fs_info);
4540acce952bSliubo 
4541e3029d9fSAl Viro 	kthread_stop(fs_info->transaction_kthread);
4542e3029d9fSAl Viro 	kthread_stop(fs_info->cleaner_kthread);
45438929ecfaSYan, Zheng 
4544e187831eSJosef Bacik 	ASSERT(list_empty(&fs_info->delayed_iputs));
4545afcdd129SJosef Bacik 	set_bit(BTRFS_FS_CLOSING_DONE, &fs_info->flags);
4546f25784b3SYan Zheng 
45475958253cSQu Wenruo 	if (btrfs_check_quota_leak(fs_info)) {
45485958253cSQu Wenruo 		WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
45495958253cSQu Wenruo 		btrfs_err(fs_info, "qgroup reserved space leaked");
45505958253cSQu Wenruo 	}
45515958253cSQu Wenruo 
455204892340SEric Sandeen 	btrfs_free_qgroup_config(fs_info);
4553fe816d0fSNikolay Borisov 	ASSERT(list_empty(&fs_info->delalloc_roots));
4554bcef60f2SArne Jansen 
4555963d678bSMiao Xie 	if (percpu_counter_sum(&fs_info->delalloc_bytes)) {
455604892340SEric Sandeen 		btrfs_info(fs_info, "at unmount delalloc count %lld",
4557963d678bSMiao Xie 		       percpu_counter_sum(&fs_info->delalloc_bytes));
4558b0c68f8bSChris Mason 	}
455931153d81SYan Zheng 
45605deb17e1SJosef Bacik 	if (percpu_counter_sum(&fs_info->ordered_bytes))
45614297ff84SJosef Bacik 		btrfs_info(fs_info, "at unmount dio bytes count %lld",
45625deb17e1SJosef Bacik 			   percpu_counter_sum(&fs_info->ordered_bytes));
45634297ff84SJosef Bacik 
45646618a59bSAnand Jain 	btrfs_sysfs_remove_mounted(fs_info);
4565b7c35e81SAnand Jain 	btrfs_sysfs_remove_fsid(fs_info->fs_devices);
45665ac1d209SJeff Mahoney 
45671a4319ccSLiu Bo 	btrfs_put_block_group_cache(fs_info);
45681a4319ccSLiu Bo 
4569de348ee0SWang Shilong 	/*
4570de348ee0SWang Shilong 	 * we must make sure there is not any read request to
4571de348ee0SWang Shilong 	 * submit after we stopping all workers.
4572de348ee0SWang Shilong 	 */
4573de348ee0SWang Shilong 	invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
457496192499SJosef Bacik 	btrfs_stop_all_workers(fs_info);
457596192499SJosef Bacik 
45760a31daa4SFilipe Manana 	/* We shouldn't have any transaction open at this point */
457736c86a9eSQu Wenruo 	warn_about_uncommitted_trans(fs_info);
45780a31daa4SFilipe Manana 
4579afcdd129SJosef Bacik 	clear_bit(BTRFS_FS_OPEN, &fs_info->flags);
45804273eaffSAnand Jain 	free_root_pointers(fs_info, true);
45818c38938cSJosef Bacik 	btrfs_free_fs_roots(fs_info);
45829ad6b7bcSChris Mason 
45834e19443dSJosef Bacik 	/*
45844e19443dSJosef Bacik 	 * We must free the block groups after dropping the fs_roots as we could
45854e19443dSJosef Bacik 	 * have had an IO error and have left over tree log blocks that aren't
45864e19443dSJosef Bacik 	 * cleaned up until the fs roots are freed.  This makes the block group
45874e19443dSJosef Bacik 	 * accounting appear to be wrong because there's pending reserved bytes,
45884e19443dSJosef Bacik 	 * so make sure we do the block group cleanup afterwards.
45894e19443dSJosef Bacik 	 */
45904e19443dSJosef Bacik 	btrfs_free_block_groups(fs_info);
45914e19443dSJosef Bacik 
459213e6c37bSJosef Bacik 	iput(fs_info->btree_inode);
4593d6bfde87SChris Mason 
459421adbd5cSStefan Behrens #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
45950b246afaSJeff Mahoney 	if (btrfs_test_opt(fs_info, CHECK_INTEGRITY))
45962ff7e61eSJeff Mahoney 		btrfsic_unmount(fs_info->fs_devices);
459721adbd5cSStefan Behrens #endif
459821adbd5cSStefan Behrens 
45990b86a832SChris Mason 	btrfs_mapping_tree_free(&fs_info->mapping_tree);
460068c94e55SNikolay Borisov 	btrfs_close_devices(fs_info->fs_devices);
4601eb60ceacSChris Mason }
4602eb60ceacSChris Mason 
4603b9fab919SChris Mason int btrfs_buffer_uptodate(struct extent_buffer *buf, u64 parent_transid,
4604b9fab919SChris Mason 			  int atomic)
4605ccd467d6SChris Mason {
46061259ab75SChris Mason 	int ret;
4607727011e0SChris Mason 	struct inode *btree_inode = buf->pages[0]->mapping->host;
46081259ab75SChris Mason 
46090b32f4bbSJosef Bacik 	ret = extent_buffer_uptodate(buf);
46101259ab75SChris Mason 	if (!ret)
46111259ab75SChris Mason 		return ret;
46121259ab75SChris Mason 
46131259ab75SChris Mason 	ret = verify_parent_transid(&BTRFS_I(btree_inode)->io_tree, buf,
4614b9fab919SChris Mason 				    parent_transid, atomic);
4615b9fab919SChris Mason 	if (ret == -EAGAIN)
4616b9fab919SChris Mason 		return ret;
46171259ab75SChris Mason 	return !ret;
46185f39d397SChris Mason }
46196702ed49SChris Mason 
46205f39d397SChris Mason void btrfs_mark_buffer_dirty(struct extent_buffer *buf)
46215f39d397SChris Mason {
46222f4d60dfSQu Wenruo 	struct btrfs_fs_info *fs_info = buf->fs_info;
46235f39d397SChris Mason 	u64 transid = btrfs_header_generation(buf);
4624b4ce94deSChris Mason 
462506ea65a3SJosef Bacik #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
462606ea65a3SJosef Bacik 	/*
462706ea65a3SJosef Bacik 	 * This is a fast path so only do this check if we have sanity tests
462852042d8eSAndrea Gelmini 	 * enabled.  Normal people shouldn't be using unmapped buffers as dirty
462906ea65a3SJosef Bacik 	 * outside of the sanity tests.
463006ea65a3SJosef Bacik 	 */
4631b0132a3bSNikolay Borisov 	if (unlikely(test_bit(EXTENT_BUFFER_UNMAPPED, &buf->bflags)))
463206ea65a3SJosef Bacik 		return;
463306ea65a3SJosef Bacik #endif
463449d0c642SFilipe Manana 	btrfs_assert_tree_write_locked(buf);
46350b246afaSJeff Mahoney 	if (transid != fs_info->generation)
46365d163e0eSJeff Mahoney 		WARN(1, KERN_CRIT "btrfs transid mismatch buffer %llu, found %llu running %llu\n",
46370b246afaSJeff Mahoney 			buf->start, transid, fs_info->generation);
4638f18cc978SChristoph Hellwig 	set_extent_buffer_dirty(buf);
46391f21ef0aSFilipe Manana #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
464069fc6cbbSQu Wenruo 	/*
464185d8a826SJosef Bacik 	 * btrfs_check_leaf() won't check item data if we don't have WRITTEN
464285d8a826SJosef Bacik 	 * set, so this will only validate the basic structure of the items.
464369fc6cbbSQu Wenruo 	 */
464485d8a826SJosef Bacik 	if (btrfs_header_level(buf) == 0 && btrfs_check_leaf(buf)) {
4645a4f78750SDavid Sterba 		btrfs_print_leaf(buf);
46461f21ef0aSFilipe Manana 		ASSERT(0);
46471f21ef0aSFilipe Manana 	}
46481f21ef0aSFilipe Manana #endif
4649eb60ceacSChris Mason }
4650eb60ceacSChris Mason 
46512ff7e61eSJeff Mahoney static void __btrfs_btree_balance_dirty(struct btrfs_fs_info *fs_info,
4652b53d3f5dSLiu Bo 					int flush_delayed)
465335b7e476SChris Mason {
4654188de649SChris Mason 	/*
4655188de649SChris Mason 	 * looks as though older kernels can get into trouble with
4656188de649SChris Mason 	 * this code, they end up stuck in balance_dirty_pages forever
4657188de649SChris Mason 	 */
4658e2d84521SMiao Xie 	int ret;
4659d6bfde87SChris Mason 
46606933c02eSJens Axboe 	if (current->flags & PF_MEMALLOC)
4661d6bfde87SChris Mason 		return;
4662d6bfde87SChris Mason 
4663b53d3f5dSLiu Bo 	if (flush_delayed)
46642ff7e61eSJeff Mahoney 		btrfs_balance_delayed_items(fs_info);
466516cdcec7SMiao Xie 
4666d814a491SEthan Lien 	ret = __percpu_counter_compare(&fs_info->dirty_metadata_bytes,
4667d814a491SEthan Lien 				     BTRFS_DIRTY_METADATA_THRESH,
4668d814a491SEthan Lien 				     fs_info->dirty_metadata_batch);
4669e2d84521SMiao Xie 	if (ret > 0) {
46700b246afaSJeff Mahoney 		balance_dirty_pages_ratelimited(fs_info->btree_inode->i_mapping);
467116cdcec7SMiao Xie 	}
467216cdcec7SMiao Xie }
467316cdcec7SMiao Xie 
46742ff7e61eSJeff Mahoney void btrfs_btree_balance_dirty(struct btrfs_fs_info *fs_info)
467516cdcec7SMiao Xie {
46762ff7e61eSJeff Mahoney 	__btrfs_btree_balance_dirty(fs_info, 1);
467735b7e476SChris Mason }
4678b53d3f5dSLiu Bo 
46792ff7e61eSJeff Mahoney void btrfs_btree_balance_dirty_nodelay(struct btrfs_fs_info *fs_info)
4680b53d3f5dSLiu Bo {
46812ff7e61eSJeff Mahoney 	__btrfs_btree_balance_dirty(fs_info, 0);
4682d6bfde87SChris Mason }
46836b80053dSChris Mason 
46842ff7e61eSJeff Mahoney static void btrfs_error_commit_super(struct btrfs_fs_info *fs_info)
4685acce952bSliubo {
4686fe816d0fSNikolay Borisov 	/* cleanup FS via transaction */
4687fe816d0fSNikolay Borisov 	btrfs_cleanup_transaction(fs_info);
4688fe816d0fSNikolay Borisov 
46890b246afaSJeff Mahoney 	mutex_lock(&fs_info->cleaner_mutex);
46902ff7e61eSJeff Mahoney 	btrfs_run_delayed_iputs(fs_info);
46910b246afaSJeff Mahoney 	mutex_unlock(&fs_info->cleaner_mutex);
4692acce952bSliubo 
46930b246afaSJeff Mahoney 	down_write(&fs_info->cleanup_work_sem);
46940b246afaSJeff Mahoney 	up_write(&fs_info->cleanup_work_sem);
4695acce952bSliubo }
4696acce952bSliubo 
4697ef67963dSJosef Bacik static void btrfs_drop_all_logs(struct btrfs_fs_info *fs_info)
4698ef67963dSJosef Bacik {
4699fc7cbcd4SDavid Sterba 	struct btrfs_root *gang[8];
4700fc7cbcd4SDavid Sterba 	u64 root_objectid = 0;
4701fc7cbcd4SDavid Sterba 	int ret;
4702ef67963dSJosef Bacik 
4703fc7cbcd4SDavid Sterba 	spin_lock(&fs_info->fs_roots_radix_lock);
4704fc7cbcd4SDavid Sterba 	while ((ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
4705fc7cbcd4SDavid Sterba 					     (void **)gang, root_objectid,
4706fc7cbcd4SDavid Sterba 					     ARRAY_SIZE(gang))) != 0) {
4707fc7cbcd4SDavid Sterba 		int i;
4708ef67963dSJosef Bacik 
4709fc7cbcd4SDavid Sterba 		for (i = 0; i < ret; i++)
4710fc7cbcd4SDavid Sterba 			gang[i] = btrfs_grab_root(gang[i]);
4711fc7cbcd4SDavid Sterba 		spin_unlock(&fs_info->fs_roots_radix_lock);
4712fc7cbcd4SDavid Sterba 
4713fc7cbcd4SDavid Sterba 		for (i = 0; i < ret; i++) {
4714fc7cbcd4SDavid Sterba 			if (!gang[i])
4715ef67963dSJosef Bacik 				continue;
4716fc7cbcd4SDavid Sterba 			root_objectid = gang[i]->root_key.objectid;
4717fc7cbcd4SDavid Sterba 			btrfs_free_log(NULL, gang[i]);
4718fc7cbcd4SDavid Sterba 			btrfs_put_root(gang[i]);
4719ef67963dSJosef Bacik 		}
4720fc7cbcd4SDavid Sterba 		root_objectid++;
4721fc7cbcd4SDavid Sterba 		spin_lock(&fs_info->fs_roots_radix_lock);
4722ef67963dSJosef Bacik 	}
4723fc7cbcd4SDavid Sterba 	spin_unlock(&fs_info->fs_roots_radix_lock);
4724ef67963dSJosef Bacik 	btrfs_free_log_root_tree(NULL, fs_info);
4725ef67963dSJosef Bacik }
4726ef67963dSJosef Bacik 
4727143bede5SJeff Mahoney static void btrfs_destroy_ordered_extents(struct btrfs_root *root)
4728acce952bSliubo {
4729acce952bSliubo 	struct btrfs_ordered_extent *ordered;
4730acce952bSliubo 
4731199c2a9cSMiao Xie 	spin_lock(&root->ordered_extent_lock);
4732779880efSJosef Bacik 	/*
4733779880efSJosef Bacik 	 * This will just short circuit the ordered completion stuff which will
4734779880efSJosef Bacik 	 * make sure the ordered extent gets properly cleaned up.
4735779880efSJosef Bacik 	 */
4736199c2a9cSMiao Xie 	list_for_each_entry(ordered, &root->ordered_extents,
4737779880efSJosef Bacik 			    root_extent_list)
4738779880efSJosef Bacik 		set_bit(BTRFS_ORDERED_IOERR, &ordered->flags);
4739199c2a9cSMiao Xie 	spin_unlock(&root->ordered_extent_lock);
4740199c2a9cSMiao Xie }
4741199c2a9cSMiao Xie 
4742199c2a9cSMiao Xie static void btrfs_destroy_all_ordered_extents(struct btrfs_fs_info *fs_info)
4743199c2a9cSMiao Xie {
4744199c2a9cSMiao Xie 	struct btrfs_root *root;
4745199c2a9cSMiao Xie 	struct list_head splice;
4746199c2a9cSMiao Xie 
4747199c2a9cSMiao Xie 	INIT_LIST_HEAD(&splice);
4748199c2a9cSMiao Xie 
4749199c2a9cSMiao Xie 	spin_lock(&fs_info->ordered_root_lock);
4750199c2a9cSMiao Xie 	list_splice_init(&fs_info->ordered_roots, &splice);
4751199c2a9cSMiao Xie 	while (!list_empty(&splice)) {
4752199c2a9cSMiao Xie 		root = list_first_entry(&splice, struct btrfs_root,
4753199c2a9cSMiao Xie 					ordered_root);
47541de2cfdeSJosef Bacik 		list_move_tail(&root->ordered_root,
47551de2cfdeSJosef Bacik 			       &fs_info->ordered_roots);
4756199c2a9cSMiao Xie 
47572a85d9caSLiu Bo 		spin_unlock(&fs_info->ordered_root_lock);
4758199c2a9cSMiao Xie 		btrfs_destroy_ordered_extents(root);
4759199c2a9cSMiao Xie 
47602a85d9caSLiu Bo 		cond_resched();
47612a85d9caSLiu Bo 		spin_lock(&fs_info->ordered_root_lock);
4762199c2a9cSMiao Xie 	}
4763199c2a9cSMiao Xie 	spin_unlock(&fs_info->ordered_root_lock);
476474d5d229SJosef Bacik 
476574d5d229SJosef Bacik 	/*
476674d5d229SJosef Bacik 	 * We need this here because if we've been flipped read-only we won't
476774d5d229SJosef Bacik 	 * get sync() from the umount, so we need to make sure any ordered
476874d5d229SJosef Bacik 	 * extents that haven't had their dirty pages IO start writeout yet
476974d5d229SJosef Bacik 	 * actually get run and error out properly.
477074d5d229SJosef Bacik 	 */
477174d5d229SJosef Bacik 	btrfs_wait_ordered_roots(fs_info, U64_MAX, 0, (u64)-1);
4772acce952bSliubo }
4773acce952bSliubo 
477435a3621bSStefan Behrens static int btrfs_destroy_delayed_refs(struct btrfs_transaction *trans,
47752ff7e61eSJeff Mahoney 				      struct btrfs_fs_info *fs_info)
4776acce952bSliubo {
4777acce952bSliubo 	struct rb_node *node;
4778acce952bSliubo 	struct btrfs_delayed_ref_root *delayed_refs;
4779acce952bSliubo 	struct btrfs_delayed_ref_node *ref;
4780acce952bSliubo 	int ret = 0;
4781acce952bSliubo 
4782acce952bSliubo 	delayed_refs = &trans->delayed_refs;
4783acce952bSliubo 
4784acce952bSliubo 	spin_lock(&delayed_refs->lock);
4785d7df2c79SJosef Bacik 	if (atomic_read(&delayed_refs->num_entries) == 0) {
4786cfece4dbSDavid Sterba 		spin_unlock(&delayed_refs->lock);
4787b79ce3ddSDavid Sterba 		btrfs_debug(fs_info, "delayed_refs has NO entry");
4788acce952bSliubo 		return ret;
4789acce952bSliubo 	}
4790acce952bSliubo 
47915c9d028bSLiu Bo 	while ((node = rb_first_cached(&delayed_refs->href_root)) != NULL) {
4792d7df2c79SJosef Bacik 		struct btrfs_delayed_ref_head *head;
47930e0adbcfSJosef Bacik 		struct rb_node *n;
4794e78417d1SJosef Bacik 		bool pin_bytes = false;
4795acce952bSliubo 
4796d7df2c79SJosef Bacik 		head = rb_entry(node, struct btrfs_delayed_ref_head,
4797d7df2c79SJosef Bacik 				href_node);
47983069bd26SJosef Bacik 		if (btrfs_delayed_ref_lock(delayed_refs, head))
4799b939d1abSJosef Bacik 			continue;
48003069bd26SJosef Bacik 
4801d7df2c79SJosef Bacik 		spin_lock(&head->lock);
4802e3d03965SLiu Bo 		while ((n = rb_first_cached(&head->ref_tree)) != NULL) {
48030e0adbcfSJosef Bacik 			ref = rb_entry(n, struct btrfs_delayed_ref_node,
48040e0adbcfSJosef Bacik 				       ref_node);
4805d7df2c79SJosef Bacik 			ref->in_tree = 0;
4806e3d03965SLiu Bo 			rb_erase_cached(&ref->ref_node, &head->ref_tree);
48070e0adbcfSJosef Bacik 			RB_CLEAR_NODE(&ref->ref_node);
48081d57ee94SWang Xiaoguang 			if (!list_empty(&ref->add_list))
48091d57ee94SWang Xiaoguang 				list_del(&ref->add_list);
4810d7df2c79SJosef Bacik 			atomic_dec(&delayed_refs->num_entries);
4811d7df2c79SJosef Bacik 			btrfs_put_delayed_ref(ref);
4812d7df2c79SJosef Bacik 		}
481354067ae9SJosef Bacik 		if (head->must_insert_reserved)
4814e78417d1SJosef Bacik 			pin_bytes = true;
481578a6184aSMiao Xie 		btrfs_free_delayed_extent_op(head->extent_op);
4816fa781ceaSJosef Bacik 		btrfs_delete_ref_head(delayed_refs, head);
4817d7df2c79SJosef Bacik 		spin_unlock(&head->lock);
4818acce952bSliubo 		spin_unlock(&delayed_refs->lock);
4819e78417d1SJosef Bacik 		mutex_unlock(&head->mutex);
4820acce952bSliubo 
4821f603bb94SNikolay Borisov 		if (pin_bytes) {
4822f603bb94SNikolay Borisov 			struct btrfs_block_group *cache;
4823f603bb94SNikolay Borisov 
4824f603bb94SNikolay Borisov 			cache = btrfs_lookup_block_group(fs_info, head->bytenr);
4825f603bb94SNikolay Borisov 			BUG_ON(!cache);
4826f603bb94SNikolay Borisov 
4827f603bb94SNikolay Borisov 			spin_lock(&cache->space_info->lock);
4828f603bb94SNikolay Borisov 			spin_lock(&cache->lock);
4829f603bb94SNikolay Borisov 			cache->pinned += head->num_bytes;
4830f603bb94SNikolay Borisov 			btrfs_space_info_update_bytes_pinned(fs_info,
4831f603bb94SNikolay Borisov 				cache->space_info, head->num_bytes);
4832f603bb94SNikolay Borisov 			cache->reserved -= head->num_bytes;
4833f603bb94SNikolay Borisov 			cache->space_info->bytes_reserved -= head->num_bytes;
4834f603bb94SNikolay Borisov 			spin_unlock(&cache->lock);
4835f603bb94SNikolay Borisov 			spin_unlock(&cache->space_info->lock);
4836f603bb94SNikolay Borisov 
4837f603bb94SNikolay Borisov 			btrfs_put_block_group(cache);
4838f603bb94SNikolay Borisov 
4839f603bb94SNikolay Borisov 			btrfs_error_unpin_extent_range(fs_info, head->bytenr,
4840f603bb94SNikolay Borisov 				head->bytenr + head->num_bytes - 1);
4841f603bb94SNikolay Borisov 		}
484231890da0SJosef Bacik 		btrfs_cleanup_ref_head_accounting(fs_info, delayed_refs, head);
4843d278850eSJosef Bacik 		btrfs_put_delayed_ref_head(head);
4844acce952bSliubo 		cond_resched();
4845acce952bSliubo 		spin_lock(&delayed_refs->lock);
4846acce952bSliubo 	}
484781f7eb00SJeff Mahoney 	btrfs_qgroup_destroy_extent_records(trans);
4848acce952bSliubo 
4849acce952bSliubo 	spin_unlock(&delayed_refs->lock);
4850acce952bSliubo 
4851acce952bSliubo 	return ret;
4852acce952bSliubo }
4853acce952bSliubo 
4854143bede5SJeff Mahoney static void btrfs_destroy_delalloc_inodes(struct btrfs_root *root)
4855acce952bSliubo {
4856acce952bSliubo 	struct btrfs_inode *btrfs_inode;
4857acce952bSliubo 	struct list_head splice;
4858acce952bSliubo 
4859acce952bSliubo 	INIT_LIST_HEAD(&splice);
4860acce952bSliubo 
4861eb73c1b7SMiao Xie 	spin_lock(&root->delalloc_lock);
4862eb73c1b7SMiao Xie 	list_splice_init(&root->delalloc_inodes, &splice);
4863acce952bSliubo 
4864acce952bSliubo 	while (!list_empty(&splice)) {
4865fe816d0fSNikolay Borisov 		struct inode *inode = NULL;
4866eb73c1b7SMiao Xie 		btrfs_inode = list_first_entry(&splice, struct btrfs_inode,
4867acce952bSliubo 					       delalloc_inodes);
4868fe816d0fSNikolay Borisov 		__btrfs_del_delalloc_inode(root, btrfs_inode);
4869eb73c1b7SMiao Xie 		spin_unlock(&root->delalloc_lock);
4870acce952bSliubo 
4871fe816d0fSNikolay Borisov 		/*
4872fe816d0fSNikolay Borisov 		 * Make sure we get a live inode and that it'll not disappear
4873fe816d0fSNikolay Borisov 		 * meanwhile.
4874fe816d0fSNikolay Borisov 		 */
4875fe816d0fSNikolay Borisov 		inode = igrab(&btrfs_inode->vfs_inode);
4876fe816d0fSNikolay Borisov 		if (inode) {
4877597441b3SJosef Bacik 			unsigned int nofs_flag;
4878597441b3SJosef Bacik 
4879597441b3SJosef Bacik 			nofs_flag = memalloc_nofs_save();
4880fe816d0fSNikolay Borisov 			invalidate_inode_pages2(inode->i_mapping);
4881597441b3SJosef Bacik 			memalloc_nofs_restore(nofs_flag);
4882fe816d0fSNikolay Borisov 			iput(inode);
4883fe816d0fSNikolay Borisov 		}
4884eb73c1b7SMiao Xie 		spin_lock(&root->delalloc_lock);
4885acce952bSliubo 	}
4886eb73c1b7SMiao Xie 	spin_unlock(&root->delalloc_lock);
4887eb73c1b7SMiao Xie }
4888eb73c1b7SMiao Xie 
4889eb73c1b7SMiao Xie static void btrfs_destroy_all_delalloc_inodes(struct btrfs_fs_info *fs_info)
4890eb73c1b7SMiao Xie {
4891eb73c1b7SMiao Xie 	struct btrfs_root *root;
4892eb73c1b7SMiao Xie 	struct list_head splice;
4893eb73c1b7SMiao Xie 
4894eb73c1b7SMiao Xie 	INIT_LIST_HEAD(&splice);
4895eb73c1b7SMiao Xie 
4896eb73c1b7SMiao Xie 	spin_lock(&fs_info->delalloc_root_lock);
4897eb73c1b7SMiao Xie 	list_splice_init(&fs_info->delalloc_roots, &splice);
4898eb73c1b7SMiao Xie 	while (!list_empty(&splice)) {
4899eb73c1b7SMiao Xie 		root = list_first_entry(&splice, struct btrfs_root,
4900eb73c1b7SMiao Xie 					 delalloc_root);
490100246528SJosef Bacik 		root = btrfs_grab_root(root);
4902eb73c1b7SMiao Xie 		BUG_ON(!root);
4903eb73c1b7SMiao Xie 		spin_unlock(&fs_info->delalloc_root_lock);
4904eb73c1b7SMiao Xie 
4905eb73c1b7SMiao Xie 		btrfs_destroy_delalloc_inodes(root);
490600246528SJosef Bacik 		btrfs_put_root(root);
4907eb73c1b7SMiao Xie 
4908eb73c1b7SMiao Xie 		spin_lock(&fs_info->delalloc_root_lock);
4909eb73c1b7SMiao Xie 	}
4910eb73c1b7SMiao Xie 	spin_unlock(&fs_info->delalloc_root_lock);
4911acce952bSliubo }
4912acce952bSliubo 
49132ff7e61eSJeff Mahoney static int btrfs_destroy_marked_extents(struct btrfs_fs_info *fs_info,
4914acce952bSliubo 					struct extent_io_tree *dirty_pages,
4915acce952bSliubo 					int mark)
4916acce952bSliubo {
4917acce952bSliubo 	int ret;
4918acce952bSliubo 	struct extent_buffer *eb;
4919acce952bSliubo 	u64 start = 0;
4920acce952bSliubo 	u64 end;
4921acce952bSliubo 
4922acce952bSliubo 	while (1) {
4923acce952bSliubo 		ret = find_first_extent_bit(dirty_pages, start, &start, &end,
4924e6138876SJosef Bacik 					    mark, NULL);
4925acce952bSliubo 		if (ret)
4926acce952bSliubo 			break;
4927acce952bSliubo 
492891166212SDavid Sterba 		clear_extent_bits(dirty_pages, start, end, mark);
4929acce952bSliubo 		while (start <= end) {
49300b246afaSJeff Mahoney 			eb = find_extent_buffer(fs_info, start);
49310b246afaSJeff Mahoney 			start += fs_info->nodesize;
4932fd8b2b61SJosef Bacik 			if (!eb)
4933acce952bSliubo 				continue;
4934acce952bSliubo 
4935c4e54a65SJosef Bacik 			btrfs_tree_lock(eb);
4936c4e54a65SJosef Bacik 			wait_on_extent_buffer_writeback(eb);
4937190a8339SJosef Bacik 			btrfs_clear_buffer_dirty(NULL, eb);
4938c4e54a65SJosef Bacik 			btrfs_tree_unlock(eb);
4939c4e54a65SJosef Bacik 
4940fd8b2b61SJosef Bacik 			free_extent_buffer_stale(eb);
4941acce952bSliubo 		}
4942acce952bSliubo 	}
4943acce952bSliubo 
4944acce952bSliubo 	return ret;
4945acce952bSliubo }
4946acce952bSliubo 
49472ff7e61eSJeff Mahoney static int btrfs_destroy_pinned_extent(struct btrfs_fs_info *fs_info,
4948fe119a6eSNikolay Borisov 				       struct extent_io_tree *unpin)
4949acce952bSliubo {
4950acce952bSliubo 	u64 start;
4951acce952bSliubo 	u64 end;
4952acce952bSliubo 	int ret;
4953acce952bSliubo 
4954acce952bSliubo 	while (1) {
49550e6ec385SFilipe Manana 		struct extent_state *cached_state = NULL;
49560e6ec385SFilipe Manana 
4957fcd5e742SLu Fengqi 		/*
4958fcd5e742SLu Fengqi 		 * The btrfs_finish_extent_commit() may get the same range as
4959fcd5e742SLu Fengqi 		 * ours between find_first_extent_bit and clear_extent_dirty.
4960fcd5e742SLu Fengqi 		 * Hence, hold the unused_bg_unpin_mutex to avoid double unpin
4961fcd5e742SLu Fengqi 		 * the same extent range.
4962fcd5e742SLu Fengqi 		 */
4963fcd5e742SLu Fengqi 		mutex_lock(&fs_info->unused_bg_unpin_mutex);
4964acce952bSliubo 		ret = find_first_extent_bit(unpin, 0, &start, &end,
49650e6ec385SFilipe Manana 					    EXTENT_DIRTY, &cached_state);
4966fcd5e742SLu Fengqi 		if (ret) {
4967fcd5e742SLu Fengqi 			mutex_unlock(&fs_info->unused_bg_unpin_mutex);
4968acce952bSliubo 			break;
4969fcd5e742SLu Fengqi 		}
4970acce952bSliubo 
49710e6ec385SFilipe Manana 		clear_extent_dirty(unpin, start, end, &cached_state);
49720e6ec385SFilipe Manana 		free_extent_state(cached_state);
49732ff7e61eSJeff Mahoney 		btrfs_error_unpin_extent_range(fs_info, start, end);
4974fcd5e742SLu Fengqi 		mutex_unlock(&fs_info->unused_bg_unpin_mutex);
4975acce952bSliubo 		cond_resched();
4976acce952bSliubo 	}
4977acce952bSliubo 
4978acce952bSliubo 	return 0;
4979acce952bSliubo }
4980acce952bSliubo 
498132da5386SDavid Sterba static void btrfs_cleanup_bg_io(struct btrfs_block_group *cache)
4982c79a1751SLiu Bo {
4983c79a1751SLiu Bo 	struct inode *inode;
4984c79a1751SLiu Bo 
4985c79a1751SLiu Bo 	inode = cache->io_ctl.inode;
4986c79a1751SLiu Bo 	if (inode) {
4987597441b3SJosef Bacik 		unsigned int nofs_flag;
4988597441b3SJosef Bacik 
4989597441b3SJosef Bacik 		nofs_flag = memalloc_nofs_save();
4990c79a1751SLiu Bo 		invalidate_inode_pages2(inode->i_mapping);
4991597441b3SJosef Bacik 		memalloc_nofs_restore(nofs_flag);
4992597441b3SJosef Bacik 
4993c79a1751SLiu Bo 		BTRFS_I(inode)->generation = 0;
4994c79a1751SLiu Bo 		cache->io_ctl.inode = NULL;
4995c79a1751SLiu Bo 		iput(inode);
4996c79a1751SLiu Bo 	}
4997bbc37d6eSFilipe Manana 	ASSERT(cache->io_ctl.pages == NULL);
4998c79a1751SLiu Bo 	btrfs_put_block_group(cache);
4999c79a1751SLiu Bo }
5000c79a1751SLiu Bo 
5001c79a1751SLiu Bo void btrfs_cleanup_dirty_bgs(struct btrfs_transaction *cur_trans,
50022ff7e61eSJeff Mahoney 			     struct btrfs_fs_info *fs_info)
5003c79a1751SLiu Bo {
500432da5386SDavid Sterba 	struct btrfs_block_group *cache;
5005c79a1751SLiu Bo 
5006c79a1751SLiu Bo 	spin_lock(&cur_trans->dirty_bgs_lock);
5007c79a1751SLiu Bo 	while (!list_empty(&cur_trans->dirty_bgs)) {
5008c79a1751SLiu Bo 		cache = list_first_entry(&cur_trans->dirty_bgs,
500932da5386SDavid Sterba 					 struct btrfs_block_group,
5010c79a1751SLiu Bo 					 dirty_list);
5011c79a1751SLiu Bo 
5012c79a1751SLiu Bo 		if (!list_empty(&cache->io_list)) {
5013c79a1751SLiu Bo 			spin_unlock(&cur_trans->dirty_bgs_lock);
5014c79a1751SLiu Bo 			list_del_init(&cache->io_list);
5015c79a1751SLiu Bo 			btrfs_cleanup_bg_io(cache);
5016c79a1751SLiu Bo 			spin_lock(&cur_trans->dirty_bgs_lock);
5017c79a1751SLiu Bo 		}
5018c79a1751SLiu Bo 
5019c79a1751SLiu Bo 		list_del_init(&cache->dirty_list);
5020c79a1751SLiu Bo 		spin_lock(&cache->lock);
5021c79a1751SLiu Bo 		cache->disk_cache_state = BTRFS_DC_ERROR;
5022c79a1751SLiu Bo 		spin_unlock(&cache->lock);
5023c79a1751SLiu Bo 
5024c79a1751SLiu Bo 		spin_unlock(&cur_trans->dirty_bgs_lock);
5025c79a1751SLiu Bo 		btrfs_put_block_group(cache);
5026ba2c4d4eSJosef Bacik 		btrfs_delayed_refs_rsv_release(fs_info, 1);
5027c79a1751SLiu Bo 		spin_lock(&cur_trans->dirty_bgs_lock);
5028c79a1751SLiu Bo 	}
5029c79a1751SLiu Bo 	spin_unlock(&cur_trans->dirty_bgs_lock);
5030c79a1751SLiu Bo 
503145ae2c18SNikolay Borisov 	/*
503245ae2c18SNikolay Borisov 	 * Refer to the definition of io_bgs member for details why it's safe
503345ae2c18SNikolay Borisov 	 * to use it without any locking
503445ae2c18SNikolay Borisov 	 */
5035c79a1751SLiu Bo 	while (!list_empty(&cur_trans->io_bgs)) {
5036c79a1751SLiu Bo 		cache = list_first_entry(&cur_trans->io_bgs,
503732da5386SDavid Sterba 					 struct btrfs_block_group,
5038c79a1751SLiu Bo 					 io_list);
5039c79a1751SLiu Bo 
5040c79a1751SLiu Bo 		list_del_init(&cache->io_list);
5041c79a1751SLiu Bo 		spin_lock(&cache->lock);
5042c79a1751SLiu Bo 		cache->disk_cache_state = BTRFS_DC_ERROR;
5043c79a1751SLiu Bo 		spin_unlock(&cache->lock);
5044c79a1751SLiu Bo 		btrfs_cleanup_bg_io(cache);
5045c79a1751SLiu Bo 	}
5046c79a1751SLiu Bo }
5047c79a1751SLiu Bo 
504849b25e05SJeff Mahoney void btrfs_cleanup_one_transaction(struct btrfs_transaction *cur_trans,
50492ff7e61eSJeff Mahoney 				   struct btrfs_fs_info *fs_info)
505049b25e05SJeff Mahoney {
5051bbbf7243SNikolay Borisov 	struct btrfs_device *dev, *tmp;
5052bbbf7243SNikolay Borisov 
50532ff7e61eSJeff Mahoney 	btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
5054c79a1751SLiu Bo 	ASSERT(list_empty(&cur_trans->dirty_bgs));
5055c79a1751SLiu Bo 	ASSERT(list_empty(&cur_trans->io_bgs));
5056c79a1751SLiu Bo 
5057bbbf7243SNikolay Borisov 	list_for_each_entry_safe(dev, tmp, &cur_trans->dev_update_list,
5058bbbf7243SNikolay Borisov 				 post_commit_list) {
5059bbbf7243SNikolay Borisov 		list_del_init(&dev->post_commit_list);
5060bbbf7243SNikolay Borisov 	}
5061bbbf7243SNikolay Borisov 
50622ff7e61eSJeff Mahoney 	btrfs_destroy_delayed_refs(cur_trans, fs_info);
506349b25e05SJeff Mahoney 
50644a9d8bdeSMiao Xie 	cur_trans->state = TRANS_STATE_COMMIT_START;
50650b246afaSJeff Mahoney 	wake_up(&fs_info->transaction_blocked_wait);
506649b25e05SJeff Mahoney 
50674a9d8bdeSMiao Xie 	cur_trans->state = TRANS_STATE_UNBLOCKED;
50680b246afaSJeff Mahoney 	wake_up(&fs_info->transaction_wait);
506949b25e05SJeff Mahoney 
5070ccdf9b30SJeff Mahoney 	btrfs_destroy_delayed_inodes(fs_info);
507167cde344SMiao Xie 
50722ff7e61eSJeff Mahoney 	btrfs_destroy_marked_extents(fs_info, &cur_trans->dirty_pages,
507349b25e05SJeff Mahoney 				     EXTENT_DIRTY);
5074fe119a6eSNikolay Borisov 	btrfs_destroy_pinned_extent(fs_info, &cur_trans->pinned_extents);
507549b25e05SJeff Mahoney 
50764a9d8bdeSMiao Xie 	cur_trans->state =TRANS_STATE_COMPLETED;
50774a9d8bdeSMiao Xie 	wake_up(&cur_trans->commit_wait);
507849b25e05SJeff Mahoney }
507949b25e05SJeff Mahoney 
50802ff7e61eSJeff Mahoney static int btrfs_cleanup_transaction(struct btrfs_fs_info *fs_info)
5081acce952bSliubo {
5082acce952bSliubo 	struct btrfs_transaction *t;
5083acce952bSliubo 
50840b246afaSJeff Mahoney 	mutex_lock(&fs_info->transaction_kthread_mutex);
5085acce952bSliubo 
50860b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
50870b246afaSJeff Mahoney 	while (!list_empty(&fs_info->trans_list)) {
50880b246afaSJeff Mahoney 		t = list_first_entry(&fs_info->trans_list,
5089724e2315SJosef Bacik 				     struct btrfs_transaction, list);
5090724e2315SJosef Bacik 		if (t->state >= TRANS_STATE_COMMIT_START) {
50919b64f57dSElena Reshetova 			refcount_inc(&t->use_count);
50920b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
50932ff7e61eSJeff Mahoney 			btrfs_wait_for_commit(fs_info, t->transid);
5094724e2315SJosef Bacik 			btrfs_put_transaction(t);
50950b246afaSJeff Mahoney 			spin_lock(&fs_info->trans_lock);
5096724e2315SJosef Bacik 			continue;
5097724e2315SJosef Bacik 		}
50980b246afaSJeff Mahoney 		if (t == fs_info->running_transaction) {
5099724e2315SJosef Bacik 			t->state = TRANS_STATE_COMMIT_DOING;
51000b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
5101724e2315SJosef Bacik 			/*
5102724e2315SJosef Bacik 			 * We wait for 0 num_writers since we don't hold a trans
5103724e2315SJosef Bacik 			 * handle open currently for this transaction.
5104724e2315SJosef Bacik 			 */
5105724e2315SJosef Bacik 			wait_event(t->writer_wait,
5106724e2315SJosef Bacik 				   atomic_read(&t->num_writers) == 0);
5107724e2315SJosef Bacik 		} else {
51080b246afaSJeff Mahoney 			spin_unlock(&fs_info->trans_lock);
5109724e2315SJosef Bacik 		}
51102ff7e61eSJeff Mahoney 		btrfs_cleanup_one_transaction(t, fs_info);
5111724e2315SJosef Bacik 
51120b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
51130b246afaSJeff Mahoney 		if (t == fs_info->running_transaction)
51140b246afaSJeff Mahoney 			fs_info->running_transaction = NULL;
5115724e2315SJosef Bacik 		list_del_init(&t->list);
51160b246afaSJeff Mahoney 		spin_unlock(&fs_info->trans_lock);
5117a4abeea4SJosef Bacik 
5118724e2315SJosef Bacik 		btrfs_put_transaction(t);
51192e4e97abSJosef Bacik 		trace_btrfs_transaction_commit(fs_info);
51200b246afaSJeff Mahoney 		spin_lock(&fs_info->trans_lock);
5121724e2315SJosef Bacik 	}
51220b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
51230b246afaSJeff Mahoney 	btrfs_destroy_all_ordered_extents(fs_info);
5124ccdf9b30SJeff Mahoney 	btrfs_destroy_delayed_inodes(fs_info);
5125ccdf9b30SJeff Mahoney 	btrfs_assert_delayed_root_empty(fs_info);
51260b246afaSJeff Mahoney 	btrfs_destroy_all_delalloc_inodes(fs_info);
5127ef67963dSJosef Bacik 	btrfs_drop_all_logs(fs_info);
51280b246afaSJeff Mahoney 	mutex_unlock(&fs_info->transaction_kthread_mutex);
5129acce952bSliubo 
5130acce952bSliubo 	return 0;
5131acce952bSliubo }
5132ec7d6dfdSNikolay Borisov 
5133453e4873SNikolay Borisov int btrfs_init_root_free_objectid(struct btrfs_root *root)
5134ec7d6dfdSNikolay Borisov {
5135ec7d6dfdSNikolay Borisov 	struct btrfs_path *path;
5136ec7d6dfdSNikolay Borisov 	int ret;
5137ec7d6dfdSNikolay Borisov 	struct extent_buffer *l;
5138ec7d6dfdSNikolay Borisov 	struct btrfs_key search_key;
5139ec7d6dfdSNikolay Borisov 	struct btrfs_key found_key;
5140ec7d6dfdSNikolay Borisov 	int slot;
5141ec7d6dfdSNikolay Borisov 
5142ec7d6dfdSNikolay Borisov 	path = btrfs_alloc_path();
5143ec7d6dfdSNikolay Borisov 	if (!path)
5144ec7d6dfdSNikolay Borisov 		return -ENOMEM;
5145ec7d6dfdSNikolay Borisov 
5146ec7d6dfdSNikolay Borisov 	search_key.objectid = BTRFS_LAST_FREE_OBJECTID;
5147ec7d6dfdSNikolay Borisov 	search_key.type = -1;
5148ec7d6dfdSNikolay Borisov 	search_key.offset = (u64)-1;
5149ec7d6dfdSNikolay Borisov 	ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
5150ec7d6dfdSNikolay Borisov 	if (ret < 0)
5151ec7d6dfdSNikolay Borisov 		goto error;
5152ec7d6dfdSNikolay Borisov 	BUG_ON(ret == 0); /* Corruption */
5153ec7d6dfdSNikolay Borisov 	if (path->slots[0] > 0) {
5154ec7d6dfdSNikolay Borisov 		slot = path->slots[0] - 1;
5155ec7d6dfdSNikolay Borisov 		l = path->nodes[0];
5156ec7d6dfdSNikolay Borisov 		btrfs_item_key_to_cpu(l, &found_key, slot);
515723125104SNikolay Borisov 		root->free_objectid = max_t(u64, found_key.objectid + 1,
515823125104SNikolay Borisov 					    BTRFS_FIRST_FREE_OBJECTID);
5159ec7d6dfdSNikolay Borisov 	} else {
516023125104SNikolay Borisov 		root->free_objectid = BTRFS_FIRST_FREE_OBJECTID;
5161ec7d6dfdSNikolay Borisov 	}
5162ec7d6dfdSNikolay Borisov 	ret = 0;
5163ec7d6dfdSNikolay Borisov error:
5164ec7d6dfdSNikolay Borisov 	btrfs_free_path(path);
5165ec7d6dfdSNikolay Borisov 	return ret;
5166ec7d6dfdSNikolay Borisov }
5167ec7d6dfdSNikolay Borisov 
5168543068a2SNikolay Borisov int btrfs_get_free_objectid(struct btrfs_root *root, u64 *objectid)
5169ec7d6dfdSNikolay Borisov {
5170ec7d6dfdSNikolay Borisov 	int ret;
5171ec7d6dfdSNikolay Borisov 	mutex_lock(&root->objectid_mutex);
5172ec7d6dfdSNikolay Borisov 
51736b8fad57SNikolay Borisov 	if (unlikely(root->free_objectid >= BTRFS_LAST_FREE_OBJECTID)) {
5174ec7d6dfdSNikolay Borisov 		btrfs_warn(root->fs_info,
5175ec7d6dfdSNikolay Borisov 			   "the objectid of root %llu reaches its highest value",
5176ec7d6dfdSNikolay Borisov 			   root->root_key.objectid);
5177ec7d6dfdSNikolay Borisov 		ret = -ENOSPC;
5178ec7d6dfdSNikolay Borisov 		goto out;
5179ec7d6dfdSNikolay Borisov 	}
5180ec7d6dfdSNikolay Borisov 
518123125104SNikolay Borisov 	*objectid = root->free_objectid++;
5182ec7d6dfdSNikolay Borisov 	ret = 0;
5183ec7d6dfdSNikolay Borisov out:
5184ec7d6dfdSNikolay Borisov 	mutex_unlock(&root->objectid_mutex);
5185ec7d6dfdSNikolay Borisov 	return ret;
5186ec7d6dfdSNikolay Borisov }
5187