xref: /linux/fs/btrfs/disk-io.c (revision 9fb023c34f5e5bf1b3edf8670c0adda1790f82db)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 2007 Oracle.  All rights reserved.
4  */
5 
6 #include <linux/fs.h>
7 #include <linux/blkdev.h>
8 #include <linux/radix-tree.h>
9 #include <linux/writeback.h>
10 #include <linux/workqueue.h>
11 #include <linux/kthread.h>
12 #include <linux/slab.h>
13 #include <linux/migrate.h>
14 #include <linux/ratelimit.h>
15 #include <linux/uuid.h>
16 #include <linux/semaphore.h>
17 #include <linux/error-injection.h>
18 #include <linux/crc32c.h>
19 #include <linux/sched/mm.h>
20 #include <linux/unaligned.h>
21 #include "ctree.h"
22 #include "disk-io.h"
23 #include "transaction.h"
24 #include "btrfs_inode.h"
25 #include "delayed-inode.h"
26 #include "bio.h"
27 #include "print-tree.h"
28 #include "locking.h"
29 #include "tree-log.h"
30 #include "free-space-cache.h"
31 #include "free-space-tree.h"
32 #include "dev-replace.h"
33 #include "raid56.h"
34 #include "sysfs.h"
35 #include "qgroup.h"
36 #include "compression.h"
37 #include "tree-checker.h"
38 #include "ref-verify.h"
39 #include "block-group.h"
40 #include "discard.h"
41 #include "space-info.h"
42 #include "zoned.h"
43 #include "subpage.h"
44 #include "fs.h"
45 #include "accessors.h"
46 #include "extent-tree.h"
47 #include "root-tree.h"
48 #include "defrag.h"
49 #include "uuid-tree.h"
50 #include "relocation.h"
51 #include "scrub.h"
52 #include "super.h"
53 
54 #define BTRFS_SUPER_FLAG_SUPP	(BTRFS_HEADER_FLAG_WRITTEN |\
55 				 BTRFS_HEADER_FLAG_RELOC |\
56 				 BTRFS_SUPER_FLAG_ERROR |\
57 				 BTRFS_SUPER_FLAG_SEEDING |\
58 				 BTRFS_SUPER_FLAG_METADUMP |\
59 				 BTRFS_SUPER_FLAG_METADUMP_V2)
60 
61 static int btrfs_cleanup_transaction(struct btrfs_fs_info *fs_info);
62 static void btrfs_error_commit_super(struct btrfs_fs_info *fs_info);
63 
64 /*
65  * Compute the csum of a btree block and store the result to provided buffer.
66  */
67 static void csum_tree_block(struct extent_buffer *buf, u8 *result)
68 {
69 	struct btrfs_fs_info *fs_info = buf->fs_info;
70 	int num_pages;
71 	u32 first_page_part;
72 	struct btrfs_csum_ctx csum;
73 	char *kaddr;
74 	int i;
75 
76 	btrfs_csum_init(&csum, fs_info->csum_type);
77 
78 	if (buf->addr) {
79 		/* Pages are contiguous, handle them as a big one. */
80 		kaddr = buf->addr;
81 		first_page_part = fs_info->nodesize;
82 		num_pages = 1;
83 	} else {
84 		kaddr = folio_address(buf->folios[0]);
85 		first_page_part = min_t(u32, PAGE_SIZE, fs_info->nodesize);
86 		num_pages = num_extent_pages(buf);
87 	}
88 
89 	btrfs_csum_update(&csum, kaddr + BTRFS_CSUM_SIZE,
90 			  first_page_part - BTRFS_CSUM_SIZE);
91 
92 	/*
93 	 * Multiple single-page folios case would reach here.
94 	 *
95 	 * nodesize <= PAGE_SIZE and large folio all handled by above
96 	 * btrfs_csum_update() already.
97 	 */
98 	for (i = 1; i < num_pages && INLINE_EXTENT_BUFFER_PAGES > 1; i++) {
99 		kaddr = folio_address(buf->folios[i]);
100 		btrfs_csum_update(&csum, kaddr, PAGE_SIZE);
101 	}
102 	memset(result, 0, BTRFS_CSUM_SIZE);
103 	btrfs_csum_final(&csum, result);
104 }
105 
106 /*
107  * we can't consider a given block up to date unless the transid of the
108  * block matches the transid in the parent node's pointer.  This is how we
109  * detect blocks that either didn't get written at all or got written
110  * in the wrong place.
111  */
112 int btrfs_buffer_uptodate(struct extent_buffer *eb, u64 parent_transid,
113 			  const struct btrfs_tree_parent_check *check)
114 {
115 	if (!extent_buffer_uptodate(eb))
116 		return 0;
117 
118 	if (!parent_transid || btrfs_header_generation(eb) == parent_transid) {
119 		/*
120 		 * On a cache hit, the caller may still need tree parent
121 		 * verification before reusing the buffer.
122 		 */
123 		if (unlikely(check && btrfs_verify_level_key(eb, check)))
124 			return -EUCLEAN;
125 		return 1;
126 	}
127 
128 	btrfs_err_rl(eb->fs_info,
129 "parent transid verify failed on logical %llu mirror %u wanted %llu found %llu",
130 		     eb->start, eb->read_mirror,
131 		     parent_transid, btrfs_header_generation(eb));
132 	clear_extent_buffer_uptodate(eb);
133 
134 	return 0;
135 }
136 
137 static bool btrfs_supported_super_csum(u16 csum_type)
138 {
139 	switch (csum_type) {
140 	case BTRFS_CSUM_TYPE_CRC32:
141 	case BTRFS_CSUM_TYPE_XXHASH:
142 	case BTRFS_CSUM_TYPE_SHA256:
143 	case BTRFS_CSUM_TYPE_BLAKE2:
144 		return true;
145 	default:
146 		return false;
147 	}
148 }
149 
150 /*
151  * Return 0 if the superblock checksum type matches the checksum value of that
152  * algorithm. Pass the raw disk superblock data.
153  */
154 int btrfs_check_super_csum(struct btrfs_fs_info *fs_info,
155 			   const struct btrfs_super_block *disk_sb)
156 {
157 	u8 result[BTRFS_CSUM_SIZE];
158 
159 	/*
160 	 * The super_block structure does not span the whole
161 	 * BTRFS_SUPER_INFO_SIZE range, we expect that the unused space is
162 	 * filled with zeros and is included in the checksum.
163 	 */
164 	btrfs_csum(fs_info->csum_type, (const u8 *)disk_sb + BTRFS_CSUM_SIZE,
165 		   BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE, result);
166 
167 	if (memcmp(disk_sb->csum, result, fs_info->csum_size))
168 		return 1;
169 
170 	return 0;
171 }
172 
173 static int btrfs_repair_eb_io_failure(const struct extent_buffer *eb,
174 				      int mirror_num)
175 {
176 	struct btrfs_fs_info *fs_info = eb->fs_info;
177 	struct btrfs_bio *bbio;
178 	int ret;
179 
180 	if (sb_rdonly(fs_info->sb))
181 		return -EROFS;
182 
183 	/*
184 	 * This bbio is only to queue all pages for btrfs_repair_bbio_failure().
185 	 * Thus it will never get its endio called.
186 	 */
187 	bbio = btrfs_bio_alloc(max(1, fs_info->nodesize >> PAGE_SHIFT), REQ_OP_READ,
188 			       BTRFS_I(fs_info->btree_inode), eb->start, NULL, NULL);
189 	bbio->bio.bi_iter.bi_sector = eb->start >> SECTOR_SHIFT;
190 	for (int i = 0; i < num_extent_pages(eb); i++) {
191 		struct folio *folio = eb->folios[i];
192 
193 		/* No large folio support yet. */
194 		ASSERT(folio_order(folio) == 0);
195 
196 		/*
197 		 * For nodesize < page size, there is just one paddr, with some
198 		 * offset inside the page.
199 		 *
200 		 * For nodesize >= page size, it's one or more paddrs, and eb->start
201 		 * must be aligned to page boundary.
202 		 */
203 		ret = bio_add_page(&bbio->bio, &folio->page, min(PAGE_SIZE, fs_info->nodesize),
204 				   offset_in_page(eb->start));
205 		ASSERT(ret == min(PAGE_SIZE, fs_info->nodesize));
206 	}
207 	/* Since the bbio is never submitted, we have to save the iter manually. */
208 	bbio->saved_iter = bbio->bio.bi_iter;
209 
210 	ret = btrfs_repair_bbio_failure(bbio, &bbio->saved_iter, fs_info->nodesize,
211 					mirror_num);
212 	bio_put(&bbio->bio);
213 	return ret;
214 }
215 
216 /*
217  * helper to read a given tree block, doing retries as required when
218  * the checksums don't match and we have alternate mirrors to try.
219  *
220  * @check:		expected tree parentness check, see the comments of the
221  *			structure for details.
222  */
223 int btrfs_read_extent_buffer(struct extent_buffer *eb,
224 			     const struct btrfs_tree_parent_check *check)
225 {
226 	struct btrfs_fs_info *fs_info = eb->fs_info;
227 	bool failed = false;
228 	int ret;
229 	int num_copies = 0;
230 	int mirror_num = 0;
231 	int failed_mirror = 0;
232 
233 	ASSERT(check);
234 
235 	while (1) {
236 		ret = read_extent_buffer_pages(eb, mirror_num, check);
237 		if (!ret)
238 			break;
239 
240 		num_copies = btrfs_num_copies(fs_info,
241 					      eb->start, eb->len);
242 		if (num_copies == 1)
243 			break;
244 
245 		if (!failed_mirror) {
246 			failed = true;
247 			failed_mirror = eb->read_mirror;
248 		}
249 
250 		mirror_num++;
251 		if (mirror_num == failed_mirror)
252 			mirror_num++;
253 
254 		if (mirror_num > num_copies)
255 			break;
256 	}
257 
258 	if (failed && !ret && failed_mirror)
259 		btrfs_repair_eb_io_failure(eb, failed_mirror);
260 
261 	return ret;
262 }
263 
264 /*
265  * Checksum a dirty tree block before IO.
266  */
267 int btree_csum_one_bio(struct btrfs_bio *bbio)
268 {
269 	struct extent_buffer *eb = bbio->private;
270 	struct btrfs_fs_info *fs_info = eb->fs_info;
271 	u64 found_start = btrfs_header_bytenr(eb);
272 	u64 last_trans;
273 	u8 result[BTRFS_CSUM_SIZE];
274 	int ret;
275 
276 	/* Btree blocks are always contiguous on disk. */
277 	if (WARN_ON_ONCE(bbio->file_offset != eb->start))
278 		return -EIO;
279 	if (WARN_ON_ONCE(bbio->bio.bi_iter.bi_size != eb->len))
280 		return -EIO;
281 
282 	/*
283 	 * An extent_buffer marked EXTENT_BUFFER_ZONED_ZEROOUT is written out as
284 	 * zeros to preserve ordering of I/O without persisting the now
285 	 * unnecessary block. The bio is fed from the shared zero page (see
286 	 * write_one_eb()), so there is nothing to checksum here. Crucially, the
287 	 * buffer's own content is left intact: it may still be referenced, e.g.
288 	 * btrfs_free_tree_block() reads its header to add a delayed reference.
289 	 */
290 	if (test_bit(EXTENT_BUFFER_ZONED_ZEROOUT, &eb->bflags))
291 		return 0;
292 
293 	if (WARN_ON_ONCE(found_start != eb->start))
294 		return -EIO;
295 	if (WARN_ON(!btrfs_meta_folio_test_uptodate(eb->folios[0], eb)))
296 		return -EIO;
297 
298 	ASSERT(memcmp_extent_buffer(eb, fs_info->fs_devices->metadata_uuid,
299 				    offsetof(struct btrfs_header, fsid),
300 				    BTRFS_FSID_SIZE) == 0);
301 	csum_tree_block(eb, result);
302 
303 	if (btrfs_header_level(eb))
304 		ret = btrfs_check_node(eb);
305 	else
306 		ret = btrfs_check_leaf(eb);
307 
308 	if (ret < 0)
309 		goto error;
310 
311 	/*
312 	 * Also check the generation, the eb reached here must be newer than
313 	 * last committed. Or something seriously wrong happened.
314 	 */
315 	last_trans = btrfs_get_last_trans_committed(fs_info);
316 	if (unlikely(btrfs_header_generation(eb) <= last_trans)) {
317 		ret = -EUCLEAN;
318 		btrfs_err(fs_info,
319 			"block=%llu bad generation, have %llu expect > %llu",
320 			  eb->start, btrfs_header_generation(eb), last_trans);
321 		goto error;
322 	}
323 	write_extent_buffer(eb, result, 0, fs_info->csum_size);
324 	return 0;
325 
326 error:
327 	btrfs_print_tree(eb, 0);
328 	btrfs_err(fs_info, "block=%llu write time tree block corruption detected",
329 		  eb->start);
330 	/*
331 	 * Be noisy if this is an extent buffer from a log tree. We don't abort
332 	 * a transaction in case there's a bad log tree extent buffer, we just
333 	 * fallback to a transaction commit. Still we want to know when there is
334 	 * a bad log tree extent buffer, as that may signal a bug somewhere.
335 	 */
336 	WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG) ||
337 		btrfs_header_owner(eb) == BTRFS_TREE_LOG_OBJECTID);
338 	return ret;
339 }
340 
341 static bool check_tree_block_fsid(struct extent_buffer *eb)
342 {
343 	struct btrfs_fs_info *fs_info = eb->fs_info;
344 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices, *seed_devs;
345 	u8 fsid[BTRFS_FSID_SIZE];
346 
347 	read_extent_buffer(eb, fsid, offsetof(struct btrfs_header, fsid),
348 			   BTRFS_FSID_SIZE);
349 
350 	/*
351 	 * alloc_fsid_devices() copies the fsid into fs_devices::metadata_uuid.
352 	 * This is then overwritten by metadata_uuid if it is present in the
353 	 * device_list_add(). The same true for a seed device as well. So use of
354 	 * fs_devices::metadata_uuid is appropriate here.
355 	 */
356 	if (memcmp(fsid, fs_info->fs_devices->metadata_uuid, BTRFS_FSID_SIZE) == 0)
357 		return false;
358 
359 	list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list)
360 		if (!memcmp(fsid, seed_devs->fsid, BTRFS_FSID_SIZE))
361 			return false;
362 
363 	return true;
364 }
365 
366 /* Do basic extent buffer checks at read time */
367 int btrfs_validate_extent_buffer(struct extent_buffer *eb,
368 				 const struct btrfs_tree_parent_check *check)
369 {
370 	struct btrfs_fs_info *fs_info = eb->fs_info;
371 	u64 found_start;
372 	const u32 csum_size = fs_info->csum_size;
373 	u8 found_level;
374 	u8 result[BTRFS_CSUM_SIZE];
375 	const u8 *header_csum;
376 	int ret = 0;
377 	const bool ignore_csum = btrfs_test_opt(fs_info, IGNOREMETACSUMS);
378 
379 	ASSERT(check);
380 
381 	found_start = btrfs_header_bytenr(eb);
382 	if (unlikely(found_start != eb->start)) {
383 		btrfs_err_rl(fs_info,
384 			"bad tree block start, mirror %u want %llu have %llu",
385 			     eb->read_mirror, eb->start, found_start);
386 		return -EIO;
387 	}
388 	if (unlikely(check_tree_block_fsid(eb))) {
389 		btrfs_err_rl(fs_info, "bad fsid on logical %llu mirror %u",
390 			     eb->start, eb->read_mirror);
391 		return -EIO;
392 	}
393 	found_level = btrfs_header_level(eb);
394 	if (unlikely(found_level >= BTRFS_MAX_LEVEL)) {
395 		btrfs_err(fs_info,
396 			"bad tree block level, mirror %u level %d on logical %llu",
397 			eb->read_mirror, btrfs_header_level(eb), eb->start);
398 		return -EIO;
399 	}
400 
401 	csum_tree_block(eb, result);
402 	header_csum = folio_address(eb->folios[0]) +
403 		get_eb_offset_in_folio(eb, offsetof(struct btrfs_header, csum));
404 
405 	if (memcmp(result, header_csum, csum_size) != 0) {
406 		btrfs_warn_rl(fs_info,
407 "checksum verify failed on logical %llu mirror %u wanted " BTRFS_CSUM_FMT " found " BTRFS_CSUM_FMT " level %d%s",
408 			      eb->start, eb->read_mirror,
409 			      BTRFS_CSUM_FMT_VALUE(csum_size, header_csum),
410 			      BTRFS_CSUM_FMT_VALUE(csum_size, result),
411 			      btrfs_header_level(eb),
412 			      ignore_csum ? ", ignored" : "");
413 		if (unlikely(!ignore_csum))
414 			return -EUCLEAN;
415 	}
416 
417 	if (unlikely(found_level != check->level)) {
418 		btrfs_err(fs_info,
419 		"level verify failed on logical %llu mirror %u wanted %u found %u",
420 			  eb->start, eb->read_mirror, check->level, found_level);
421 		return -EIO;
422 	}
423 	if (unlikely(check->transid &&
424 		     btrfs_header_generation(eb) != check->transid)) {
425 		btrfs_err_rl(eb->fs_info,
426 "parent transid verify failed on logical %llu mirror %u wanted %llu found %llu",
427 				eb->start, eb->read_mirror, check->transid,
428 				btrfs_header_generation(eb));
429 		return -EIO;
430 	}
431 	if (check->has_first_key) {
432 		const struct btrfs_key *expect_key = &check->first_key;
433 		struct btrfs_key found_key;
434 
435 		if (found_level)
436 			btrfs_node_key_to_cpu(eb, &found_key, 0);
437 		else
438 			btrfs_item_key_to_cpu(eb, &found_key, 0);
439 		if (unlikely(btrfs_comp_cpu_keys(expect_key, &found_key))) {
440 			btrfs_err(fs_info,
441 "tree first key mismatch detected, bytenr=%llu parent_transid=%llu key expected=(%llu,%u,%llu) has=(%llu,%u,%llu)",
442 				  eb->start, check->transid,
443 				  expect_key->objectid,
444 				  expect_key->type, expect_key->offset,
445 				  found_key.objectid, found_key.type,
446 				  found_key.offset);
447 			return -EUCLEAN;
448 		}
449 	}
450 	if (check->owner_root) {
451 		ret = btrfs_check_eb_owner(eb, check->owner_root);
452 		if (ret < 0)
453 			return ret;
454 	}
455 
456 	/* If this is a leaf block and it is corrupt, just return -EIO. */
457 	if (found_level == 0 && btrfs_check_leaf(eb))
458 		ret = -EIO;
459 
460 	if (found_level > 0 && btrfs_check_node(eb))
461 		ret = -EIO;
462 
463 	if (ret)
464 		btrfs_err(fs_info,
465 		"read time tree block corruption detected on logical %llu mirror %u",
466 			  eb->start, eb->read_mirror);
467 	return ret;
468 }
469 
470 #ifdef CONFIG_MIGRATION
471 static int btree_migrate_folio(struct address_space *mapping,
472 		struct folio *dst, struct folio *src, enum migrate_mode mode)
473 {
474 	/*
475 	 * we can't safely write a btree page from here,
476 	 * we haven't done the locking hook
477 	 */
478 	if (folio_test_dirty(src))
479 		return -EAGAIN;
480 	/*
481 	 * Buffers may be managed in a filesystem specific way.
482 	 * We must have no buffers or drop them.
483 	 */
484 	if (folio_get_private(src) &&
485 	    !filemap_release_folio(src, GFP_KERNEL))
486 		return -EAGAIN;
487 	return migrate_folio(mapping, dst, src, mode);
488 }
489 #else
490 #define btree_migrate_folio NULL
491 #endif
492 
493 static bool btree_release_folio(struct folio *folio, gfp_t gfp_flags)
494 {
495 	if (folio_test_writeback(folio) || folio_test_dirty(folio))
496 		return false;
497 
498 	return try_release_extent_buffer(folio);
499 }
500 
501 static void btree_invalidate_folio(struct folio *folio, size_t offset,
502 				 size_t length)
503 {
504 	struct extent_io_tree *tree = &folio_to_inode(folio)->io_tree;
505 	struct extent_state *cached_state = NULL;
506 	const u64 start = folio_pos(folio);
507 	const u64 end = folio_next_pos(folio) - 1;
508 
509 	/*
510 	 * The range must cover the full @folio.
511 	 * Btree inode is never exposed to regular file operations, thus there
512 	 * is no partial truncation.
513 	 * The folio is only invalidated when the btree inode is evicted.
514 	 */
515 	ASSERT(offset == 0, "folio=%llu offset=%zu", folio_pos(folio), offset);
516 	ASSERT(length == folio_size(folio), "folio=%llu folio_size=%zu length=%zu",
517 	       folio_pos(folio), folio_size(folio), length);
518 
519 	/* This function is only called for the btree inode */
520 	ASSERT(tree->owner == IO_TREE_BTREE_INODE_IO);
521 
522 	btrfs_lock_extent(tree, start, end, &cached_state);
523 	folio_wait_writeback(folio);
524 
525 	/*
526 	 * Currently for btree io tree, only EXTENT_LOCKED is utilized,
527 	 * so here we only need to unlock the extent range to free any
528 	 * existing extent state.
529 	 */
530 	btrfs_unlock_extent(tree, start, end, &cached_state);
531 
532 	btree_release_folio(folio, GFP_NOFS);
533 	if (folio_get_private(folio)) {
534 		btrfs_warn(folio_to_fs_info(folio),
535 			   "folio private not zero on folio %llu",
536 			   (unsigned long long)folio_pos(folio));
537 		folio_detach_private(folio);
538 	}
539 }
540 
541 #ifdef DEBUG
542 static bool btree_dirty_folio(struct address_space *mapping,
543 		struct folio *folio)
544 {
545 	struct btrfs_fs_info *fs_info = inode_to_fs_info(mapping->host);
546 	struct btrfs_subpage_info *spi = fs_info->subpage_info;
547 	struct btrfs_subpage *subpage;
548 	struct extent_buffer *eb;
549 	int cur_bit = 0;
550 	u64 page_start = folio_pos(folio);
551 
552 	if (fs_info->sectorsize == PAGE_SIZE) {
553 		eb = folio_get_private(folio);
554 		BUG_ON(!eb);
555 		BUG_ON(!test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
556 		BUG_ON(!atomic_read(&eb->refs));
557 		btrfs_assert_tree_write_locked(eb);
558 		return filemap_dirty_folio(mapping, folio);
559 	}
560 
561 	ASSERT(spi);
562 	subpage = folio_get_private(folio);
563 
564 	for (cur_bit = spi->dirty_offset;
565 	     cur_bit < spi->dirty_offset + spi->bitmap_nr_bits;
566 	     cur_bit++) {
567 		unsigned long flags;
568 		u64 cur;
569 
570 		spin_lock_irqsave(&subpage->lock, flags);
571 		if (!test_bit(cur_bit, subpage->bitmaps)) {
572 			spin_unlock_irqrestore(&subpage->lock, flags);
573 			continue;
574 		}
575 		spin_unlock_irqrestore(&subpage->lock, flags);
576 		cur = page_start + (cur_bit << fs_info->sectorsize_bits);
577 
578 		eb = find_extent_buffer(fs_info, cur);
579 		ASSERT(eb);
580 		ASSERT(test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
581 		ASSERT(atomic_read(&eb->refs));
582 		btrfs_assert_tree_write_locked(eb);
583 		free_extent_buffer(eb);
584 
585 		cur_bit += (fs_info->nodesize >> fs_info->sectorsize_bits) - 1;
586 	}
587 	return filemap_dirty_folio(mapping, folio);
588 }
589 #else
590 #define btree_dirty_folio filemap_dirty_folio
591 #endif
592 
593 static const struct address_space_operations btree_aops = {
594 	.writepages	= btree_writepages,
595 	.release_folio	= btree_release_folio,
596 	.invalidate_folio = btree_invalidate_folio,
597 	.migrate_folio	= btree_migrate_folio,
598 	.dirty_folio	= btree_dirty_folio,
599 };
600 
601 struct extent_buffer *btrfs_find_create_tree_block(
602 						struct btrfs_fs_info *fs_info,
603 						struct btrfs_eb_prealloc *pa,
604 						u64 bytenr, u64 owner_root,
605 						int level)
606 {
607 	if (btrfs_is_testing(fs_info))
608 		return alloc_test_extent_buffer(fs_info, bytenr);
609 	return alloc_extent_buffer(fs_info, pa, bytenr, owner_root, level);
610 }
611 
612 /*
613  * Read tree block at logical address @bytenr and do variant basic but critical
614  * verification.
615  *
616  * @check:		expected tree parentness check, see comments of the
617  *			structure for details.
618  */
619 struct extent_buffer *read_tree_block(struct btrfs_fs_info *fs_info, u64 bytenr,
620 				      struct btrfs_tree_parent_check *check)
621 {
622 	struct btrfs_eb_prealloc pa = { 0 };
623 	struct extent_buffer *buf = NULL;
624 	int ret;
625 
626 	ASSERT(check);
627 
628 	buf = btrfs_find_create_tree_block(fs_info, &pa, bytenr, check->owner_root,
629 					   check->level);
630 	if (IS_ERR(buf))
631 		return buf;
632 
633 	ret = btrfs_read_extent_buffer(buf, check);
634 	if (ret) {
635 		free_extent_buffer_stale(buf);
636 		return ERR_PTR(ret);
637 	}
638 	return buf;
639 
640 }
641 
642 static struct btrfs_root *btrfs_alloc_root(struct btrfs_fs_info *fs_info,
643 					   u64 objectid, gfp_t flags)
644 {
645 	struct btrfs_root *root;
646 
647 	root = kzalloc_obj(*root, flags);
648 	if (!root)
649 		return NULL;
650 
651 	root->fs_info = fs_info;
652 	root->root_key.objectid = objectid;
653 	RB_CLEAR_NODE(&root->rb_node);
654 
655 	xa_init(&root->inodes);
656 	xa_init(&root->delayed_nodes);
657 
658 	btrfs_init_root_block_rsv(root);
659 
660 	INIT_LIST_HEAD(&root->dirty_list);
661 	INIT_LIST_HEAD(&root->root_list);
662 	INIT_LIST_HEAD(&root->delalloc_inodes);
663 	INIT_LIST_HEAD(&root->delalloc_root);
664 	INIT_LIST_HEAD(&root->ordered_extents);
665 	INIT_LIST_HEAD(&root->ordered_root);
666 	INIT_LIST_HEAD(&root->reloc_dirty_list);
667 	spin_lock_init(&root->delalloc_lock);
668 	spin_lock_init(&root->ordered_extent_lock);
669 	spin_lock_init(&root->accounting_lock);
670 	spin_lock_init(&root->qgroup_meta_rsv_lock);
671 	mutex_init(&root->objectid_mutex);
672 	mutex_init(&root->log_mutex);
673 	mutex_init(&root->ordered_extent_mutex);
674 	mutex_init(&root->delalloc_mutex);
675 	init_waitqueue_head(&root->qgroup_flush_wait);
676 	init_waitqueue_head(&root->log_writer_wait);
677 	init_waitqueue_head(&root->log_commit_wait[0]);
678 	init_waitqueue_head(&root->log_commit_wait[1]);
679 	INIT_LIST_HEAD(&root->log_ctxs[0]);
680 	INIT_LIST_HEAD(&root->log_ctxs[1]);
681 	atomic_set(&root->log_writers, 0);
682 	refcount_set(&root->refs, 1);
683 	atomic_set(&root->snapshot_force_cow, 0);
684 	atomic_set(&root->nr_swapfiles, 0);
685 	root->log_transid_committed = -1;
686 	if (!btrfs_is_testing(fs_info)) {
687 		btrfs_extent_io_tree_init(fs_info, &root->dirty_log_pages,
688 					  IO_TREE_ROOT_DIRTY_LOG_PAGES);
689 		btrfs_extent_io_tree_init(fs_info, &root->log_csum_range,
690 					  IO_TREE_LOG_CSUM_RANGE);
691 	}
692 
693 	spin_lock_init(&root->root_item_lock);
694 	btrfs_qgroup_init_swapped_blocks(&root->swapped_blocks);
695 #ifdef CONFIG_BTRFS_DEBUG
696 	INIT_LIST_HEAD(&root->leak_list);
697 	spin_lock(&fs_info->fs_roots_radix_lock);
698 	list_add_tail(&root->leak_list, &fs_info->allocated_roots);
699 	spin_unlock(&fs_info->fs_roots_radix_lock);
700 #endif
701 
702 	return root;
703 }
704 
705 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
706 /* Should only be used by the testing infrastructure */
707 struct btrfs_root *btrfs_alloc_dummy_root(struct btrfs_fs_info *fs_info)
708 {
709 	struct btrfs_root *root;
710 
711 	if (!fs_info)
712 		return ERR_PTR(-EINVAL);
713 
714 	root = btrfs_alloc_root(fs_info, BTRFS_ROOT_TREE_OBJECTID, GFP_KERNEL);
715 	if (!root)
716 		return ERR_PTR(-ENOMEM);
717 
718 	/* We don't use the stripesize in selftest, set it as sectorsize */
719 	root->alloc_bytenr = 0;
720 
721 	return root;
722 }
723 #endif
724 
725 static int global_root_cmp(struct rb_node *a_node, const struct rb_node *b_node)
726 {
727 	const struct btrfs_root *a = rb_entry(a_node, struct btrfs_root, rb_node);
728 	const struct btrfs_root *b = rb_entry(b_node, struct btrfs_root, rb_node);
729 
730 	return btrfs_comp_cpu_keys(&a->root_key, &b->root_key);
731 }
732 
733 static int global_root_key_cmp(const void *k, const struct rb_node *node)
734 {
735 	const struct btrfs_key *key = k;
736 	const struct btrfs_root *root = rb_entry(node, struct btrfs_root, rb_node);
737 
738 	return btrfs_comp_cpu_keys(key, &root->root_key);
739 }
740 
741 int btrfs_global_root_insert(struct btrfs_root *root)
742 {
743 	struct btrfs_fs_info *fs_info = root->fs_info;
744 	struct rb_node *tmp;
745 	int ret = 0;
746 
747 	write_lock(&fs_info->global_root_lock);
748 	tmp = rb_find_add(&root->rb_node, &fs_info->global_root_tree, global_root_cmp);
749 	write_unlock(&fs_info->global_root_lock);
750 
751 	if (tmp) {
752 		ret = -EEXIST;
753 		btrfs_warn(fs_info, "global root %llu %llu already exists",
754 			   btrfs_root_id(root), root->root_key.offset);
755 	}
756 	return ret;
757 }
758 
759 void btrfs_global_root_delete(struct btrfs_root *root)
760 {
761 	struct btrfs_fs_info *fs_info = root->fs_info;
762 
763 	write_lock(&fs_info->global_root_lock);
764 	rb_erase(&root->rb_node, &fs_info->global_root_tree);
765 	write_unlock(&fs_info->global_root_lock);
766 }
767 
768 struct btrfs_root *btrfs_global_root(struct btrfs_fs_info *fs_info,
769 				     const struct btrfs_key *key)
770 {
771 	struct rb_node *node;
772 	struct btrfs_root *root = NULL;
773 
774 	read_lock(&fs_info->global_root_lock);
775 	node = rb_find(key, &fs_info->global_root_tree, global_root_key_cmp);
776 	if (node)
777 		root = container_of(node, struct btrfs_root, rb_node);
778 	read_unlock(&fs_info->global_root_lock);
779 
780 	return root;
781 }
782 
783 static u64 btrfs_global_root_id(struct btrfs_fs_info *fs_info, u64 bytenr)
784 {
785 	struct btrfs_block_group *block_group;
786 	u64 ret;
787 
788 	if (!btrfs_fs_incompat(fs_info, EXTENT_TREE_V2))
789 		return 0;
790 
791 	if (bytenr)
792 		block_group = btrfs_lookup_block_group(fs_info, bytenr);
793 	else
794 		block_group = btrfs_lookup_first_block_group(fs_info, bytenr);
795 	ASSERT(block_group);
796 	if (!block_group)
797 		return 0;
798 	ret = block_group->global_root_id;
799 	btrfs_put_block_group(block_group);
800 
801 	return ret;
802 }
803 
804 struct btrfs_root *btrfs_csum_root(struct btrfs_fs_info *fs_info, u64 bytenr)
805 {
806 	const struct btrfs_key key = {
807 		.objectid = BTRFS_CSUM_TREE_OBJECTID,
808 		.type = BTRFS_ROOT_ITEM_KEY,
809 		.offset = btrfs_global_root_id(fs_info, bytenr),
810 	};
811 
812 	return btrfs_global_root(fs_info, &key);
813 }
814 
815 struct btrfs_root *btrfs_extent_root(struct btrfs_fs_info *fs_info, u64 bytenr)
816 {
817 	const struct btrfs_key key = {
818 		.objectid = BTRFS_EXTENT_TREE_OBJECTID,
819 		.type = BTRFS_ROOT_ITEM_KEY,
820 		.offset = btrfs_global_root_id(fs_info, bytenr),
821 	};
822 
823 	return btrfs_global_root(fs_info, &key);
824 }
825 
826 struct btrfs_root *btrfs_create_tree(struct btrfs_trans_handle *trans,
827 				     u64 objectid)
828 {
829 	struct btrfs_fs_info *fs_info = trans->fs_info;
830 	struct extent_buffer *leaf;
831 	struct btrfs_root *tree_root = fs_info->tree_root;
832 	struct btrfs_root *root;
833 	unsigned int nofs_flag;
834 	int ret = 0;
835 
836 	/*
837 	 * We're holding a transaction handle, so use a NOFS memory allocation
838 	 * context to avoid deadlock if reclaim happens.
839 	 */
840 	nofs_flag = memalloc_nofs_save();
841 	root = btrfs_alloc_root(fs_info, objectid, GFP_KERNEL);
842 	memalloc_nofs_restore(nofs_flag);
843 	if (!root)
844 		return ERR_PTR(-ENOMEM);
845 
846 	root->root_key.objectid = objectid;
847 	root->root_key.type = BTRFS_ROOT_ITEM_KEY;
848 	root->root_key.offset = 0;
849 
850 	leaf = btrfs_alloc_tree_block(trans, root, 0, objectid, NULL, 0, 0, 0,
851 				      0, BTRFS_NESTING_NORMAL);
852 	if (IS_ERR(leaf)) {
853 		ret = PTR_ERR(leaf);
854 		leaf = NULL;
855 		goto fail;
856 	}
857 
858 	root->node = leaf;
859 	btrfs_mark_buffer_dirty(trans, leaf);
860 
861 	root->commit_root = btrfs_root_node(root);
862 	set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
863 
864 	btrfs_set_root_flags(&root->root_item, 0);
865 	btrfs_set_root_limit(&root->root_item, 0);
866 	btrfs_set_root_bytenr(&root->root_item, leaf->start);
867 	btrfs_set_root_generation(&root->root_item, trans->transid);
868 	btrfs_set_root_level(&root->root_item, 0);
869 	btrfs_set_root_refs(&root->root_item, 1);
870 	btrfs_set_root_used(&root->root_item, leaf->len);
871 	btrfs_set_root_last_snapshot(&root->root_item, 0);
872 	btrfs_set_root_dirid(&root->root_item, 0);
873 	if (btrfs_is_fstree(objectid))
874 		generate_random_guid(root->root_item.uuid);
875 	else
876 		export_guid(root->root_item.uuid, &guid_null);
877 	btrfs_set_root_drop_level(&root->root_item, 0);
878 
879 	btrfs_tree_unlock(leaf);
880 
881 	ret = btrfs_insert_root(trans, tree_root, &root->root_key, &root->root_item);
882 	if (ret)
883 		goto fail;
884 
885 	return root;
886 
887 fail:
888 	btrfs_put_root(root);
889 
890 	return ERR_PTR(ret);
891 }
892 
893 static struct btrfs_root *alloc_log_tree(struct btrfs_fs_info *fs_info)
894 {
895 	struct btrfs_root *root;
896 
897 	root = btrfs_alloc_root(fs_info, BTRFS_TREE_LOG_OBJECTID, GFP_NOFS);
898 	if (!root)
899 		return ERR_PTR(-ENOMEM);
900 
901 	root->root_key.objectid = BTRFS_TREE_LOG_OBJECTID;
902 	root->root_key.type = BTRFS_ROOT_ITEM_KEY;
903 	root->root_key.offset = BTRFS_TREE_LOG_OBJECTID;
904 
905 	return root;
906 }
907 
908 int btrfs_alloc_log_tree_node(struct btrfs_trans_handle *trans,
909 			      struct btrfs_root *root)
910 {
911 	struct extent_buffer *leaf;
912 
913 	/*
914 	 * DON'T set SHAREABLE bit for log trees.
915 	 *
916 	 * Log trees are not exposed to user space thus can't be snapshotted,
917 	 * and they go away before a real commit is actually done.
918 	 *
919 	 * They do store pointers to file data extents, and those reference
920 	 * counts still get updated (along with back refs to the log tree).
921 	 */
922 
923 	leaf = btrfs_alloc_tree_block(trans, root, 0, BTRFS_TREE_LOG_OBJECTID,
924 			NULL, 0, 0, 0, 0, BTRFS_NESTING_NORMAL);
925 	if (IS_ERR(leaf))
926 		return PTR_ERR(leaf);
927 
928 	root->node = leaf;
929 
930 	btrfs_mark_buffer_dirty(trans, root->node);
931 	btrfs_tree_unlock(root->node);
932 
933 	return 0;
934 }
935 
936 int btrfs_init_log_root_tree(struct btrfs_trans_handle *trans,
937 			     struct btrfs_fs_info *fs_info)
938 {
939 	struct btrfs_root *log_root;
940 
941 	log_root = alloc_log_tree(fs_info);
942 	if (IS_ERR(log_root))
943 		return PTR_ERR(log_root);
944 
945 	if (!btrfs_is_zoned(fs_info)) {
946 		int ret = btrfs_alloc_log_tree_node(trans, log_root);
947 
948 		if (ret) {
949 			btrfs_put_root(log_root);
950 			return ret;
951 		}
952 	}
953 
954 	WARN_ON(fs_info->log_root_tree);
955 	fs_info->log_root_tree = log_root;
956 	return 0;
957 }
958 
959 int btrfs_add_log_tree(struct btrfs_trans_handle *trans,
960 		       struct btrfs_root *root)
961 {
962 	struct btrfs_fs_info *fs_info = root->fs_info;
963 	struct btrfs_root *log_root;
964 	struct btrfs_inode_item *inode_item;
965 	int ret;
966 
967 	log_root = alloc_log_tree(fs_info);
968 	if (IS_ERR(log_root))
969 		return PTR_ERR(log_root);
970 
971 	ret = btrfs_alloc_log_tree_node(trans, log_root);
972 	if (ret) {
973 		btrfs_put_root(log_root);
974 		return ret;
975 	}
976 
977 	btrfs_set_root_last_trans(log_root, trans->transid);
978 	log_root->root_key.offset = btrfs_root_id(root);
979 
980 	inode_item = &log_root->root_item.inode;
981 	btrfs_set_stack_inode_generation(inode_item, 1);
982 	btrfs_set_stack_inode_size(inode_item, 3);
983 	btrfs_set_stack_inode_nlink(inode_item, 1);
984 	btrfs_set_stack_inode_nbytes(inode_item,
985 				     fs_info->nodesize);
986 	btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
987 
988 	btrfs_set_root_node(&log_root->root_item, log_root->node);
989 
990 	WARN_ON(root->log_root);
991 	root->log_root = log_root;
992 	btrfs_set_root_log_transid(root, 0);
993 	root->log_transid_committed = -1;
994 	btrfs_set_root_last_log_commit(root, 0);
995 	return 0;
996 }
997 
998 static struct btrfs_root *read_tree_root_path(struct btrfs_root *tree_root,
999 					      struct btrfs_path *path,
1000 					      const struct btrfs_key *key)
1001 {
1002 	struct btrfs_root *root;
1003 	struct btrfs_tree_parent_check check = { 0 };
1004 	struct btrfs_fs_info *fs_info = tree_root->fs_info;
1005 	u64 generation;
1006 	int ret;
1007 	int level;
1008 
1009 	root = btrfs_alloc_root(fs_info, key->objectid, GFP_NOFS);
1010 	if (!root)
1011 		return ERR_PTR(-ENOMEM);
1012 
1013 	ret = btrfs_find_root(tree_root, key, path,
1014 			      &root->root_item, &root->root_key);
1015 	if (ret) {
1016 		if (ret > 0)
1017 			ret = -ENOENT;
1018 		goto fail;
1019 	}
1020 
1021 	generation = btrfs_root_generation(&root->root_item);
1022 	level = btrfs_root_level(&root->root_item);
1023 	check.level = level;
1024 	check.transid = generation;
1025 	check.owner_root = key->objectid;
1026 	root->node = read_tree_block(fs_info, btrfs_root_bytenr(&root->root_item),
1027 				     &check);
1028 	if (IS_ERR(root->node)) {
1029 		ret = PTR_ERR(root->node);
1030 		root->node = NULL;
1031 		goto fail;
1032 	}
1033 
1034 	ret = btrfs_buffer_uptodate(root->node, generation, &check);
1035 	if (unlikely(ret <= 0)) {
1036 		if (ret == 0)
1037 			ret = -EIO;
1038 		goto fail;
1039 	}
1040 
1041 	/*
1042 	 * For real fs, and not log/reloc trees, root owner must
1043 	 * match its root node owner
1044 	 */
1045 	if (unlikely(!btrfs_is_testing(fs_info) &&
1046 		     btrfs_root_id(root) != BTRFS_TREE_LOG_OBJECTID &&
1047 		     btrfs_root_id(root) != BTRFS_TREE_RELOC_OBJECTID &&
1048 		     btrfs_root_id(root) != btrfs_header_owner(root->node))) {
1049 		btrfs_crit(fs_info,
1050 "root=%llu block=%llu, tree root owner mismatch, have %llu expect %llu",
1051 			   btrfs_root_id(root), root->node->start,
1052 			   btrfs_header_owner(root->node),
1053 			   btrfs_root_id(root));
1054 		ret = -EUCLEAN;
1055 		goto fail;
1056 	}
1057 	root->commit_root = btrfs_root_node(root);
1058 	return root;
1059 fail:
1060 	btrfs_put_root(root);
1061 	return ERR_PTR(ret);
1062 }
1063 
1064 struct btrfs_root *btrfs_read_tree_root(struct btrfs_root *tree_root,
1065 					const struct btrfs_key *key)
1066 {
1067 	struct btrfs_root *root;
1068 	BTRFS_PATH_AUTO_FREE(path);
1069 
1070 	path = btrfs_alloc_path();
1071 	if (!path)
1072 		return ERR_PTR(-ENOMEM);
1073 	root = read_tree_root_path(tree_root, path, key);
1074 
1075 	return root;
1076 }
1077 
1078 /*
1079  * Initialize subvolume root in-memory structure.
1080  *
1081  * @anon_dev:	anonymous device to attach to the root, if zero, allocate new
1082  *
1083  * In case of failure the caller is responsible to call btrfs_free_fs_root()
1084  */
1085 static int btrfs_init_fs_root(struct btrfs_root *root, dev_t anon_dev)
1086 {
1087 	int ret;
1088 
1089 	btrfs_drew_lock_init(&root->snapshot_lock);
1090 
1091 	if (btrfs_root_id(root) != BTRFS_TREE_LOG_OBJECTID &&
1092 	    !btrfs_is_data_reloc_root(root) &&
1093 	    btrfs_is_fstree(btrfs_root_id(root))) {
1094 		set_bit(BTRFS_ROOT_SHAREABLE, &root->state);
1095 		btrfs_check_and_init_root_item(&root->root_item);
1096 	}
1097 
1098 	/*
1099 	 * Don't assign anonymous block device to roots that are not exposed to
1100 	 * userspace, the id pool is limited to 1M
1101 	 */
1102 	if (btrfs_is_fstree(btrfs_root_id(root)) &&
1103 	    btrfs_root_refs(&root->root_item) > 0) {
1104 		if (!anon_dev) {
1105 			ret = get_anon_bdev(&root->anon_dev);
1106 			if (ret)
1107 				return ret;
1108 		} else {
1109 			root->anon_dev = anon_dev;
1110 		}
1111 	}
1112 
1113 	mutex_lock(&root->objectid_mutex);
1114 	ret = btrfs_init_root_free_objectid(root);
1115 	if (ret) {
1116 		mutex_unlock(&root->objectid_mutex);
1117 		return ret;
1118 	}
1119 
1120 	ASSERT(root->free_objectid <= BTRFS_LAST_FREE_OBJECTID);
1121 
1122 	mutex_unlock(&root->objectid_mutex);
1123 
1124 	return 0;
1125 }
1126 
1127 static struct btrfs_root *btrfs_lookup_fs_root(struct btrfs_fs_info *fs_info,
1128 					       u64 root_id)
1129 {
1130 	struct btrfs_root *root;
1131 
1132 	spin_lock(&fs_info->fs_roots_radix_lock);
1133 	root = radix_tree_lookup(&fs_info->fs_roots_radix,
1134 				 (unsigned long)root_id);
1135 	root = btrfs_grab_root(root);
1136 	spin_unlock(&fs_info->fs_roots_radix_lock);
1137 	return root;
1138 }
1139 
1140 static struct btrfs_root *btrfs_get_global_root(struct btrfs_fs_info *fs_info,
1141 						u64 objectid)
1142 {
1143 	struct btrfs_key key = {
1144 		.objectid = objectid,
1145 		.type = BTRFS_ROOT_ITEM_KEY,
1146 		.offset = 0,
1147 	};
1148 
1149 	switch (objectid) {
1150 	case BTRFS_ROOT_TREE_OBJECTID:
1151 		return btrfs_grab_root(fs_info->tree_root);
1152 	case BTRFS_EXTENT_TREE_OBJECTID:
1153 		return btrfs_grab_root(btrfs_global_root(fs_info, &key));
1154 	case BTRFS_CHUNK_TREE_OBJECTID:
1155 		return btrfs_grab_root(fs_info->chunk_root);
1156 	case BTRFS_DEV_TREE_OBJECTID:
1157 		return btrfs_grab_root(fs_info->dev_root);
1158 	case BTRFS_CSUM_TREE_OBJECTID:
1159 		return btrfs_grab_root(btrfs_global_root(fs_info, &key));
1160 	case BTRFS_QUOTA_TREE_OBJECTID:
1161 		return btrfs_grab_root(fs_info->quota_root);
1162 	case BTRFS_UUID_TREE_OBJECTID:
1163 		return btrfs_grab_root(fs_info->uuid_root);
1164 	case BTRFS_BLOCK_GROUP_TREE_OBJECTID:
1165 		return btrfs_grab_root(fs_info->block_group_root);
1166 	case BTRFS_FREE_SPACE_TREE_OBJECTID:
1167 		return btrfs_grab_root(btrfs_global_root(fs_info, &key));
1168 	case BTRFS_RAID_STRIPE_TREE_OBJECTID:
1169 		return btrfs_grab_root(fs_info->stripe_root);
1170 	case BTRFS_REMAP_TREE_OBJECTID:
1171 		return btrfs_grab_root(fs_info->remap_root);
1172 	default:
1173 		return NULL;
1174 	}
1175 }
1176 
1177 int btrfs_insert_fs_root(struct btrfs_fs_info *fs_info,
1178 			 struct btrfs_root *root)
1179 {
1180 	int ret;
1181 
1182 	ret = radix_tree_preload(GFP_NOFS);
1183 	if (ret)
1184 		return ret;
1185 
1186 	spin_lock(&fs_info->fs_roots_radix_lock);
1187 	ret = radix_tree_insert(&fs_info->fs_roots_radix,
1188 				(unsigned long)btrfs_root_id(root),
1189 				root);
1190 	if (ret == 0) {
1191 		btrfs_grab_root(root);
1192 		set_bit(BTRFS_ROOT_IN_RADIX, &root->state);
1193 	}
1194 	spin_unlock(&fs_info->fs_roots_radix_lock);
1195 	radix_tree_preload_end();
1196 
1197 	return ret;
1198 }
1199 
1200 void btrfs_check_leaked_roots(const struct btrfs_fs_info *fs_info)
1201 {
1202 #ifdef CONFIG_BTRFS_DEBUG
1203 	struct btrfs_root *root;
1204 
1205 	while (!list_empty(&fs_info->allocated_roots)) {
1206 		char buf[BTRFS_ROOT_NAME_BUF_LEN];
1207 
1208 		root = list_first_entry(&fs_info->allocated_roots,
1209 					struct btrfs_root, leak_list);
1210 		btrfs_err(fs_info, "leaked root %s refcount %d",
1211 			  btrfs_root_name(&root->root_key, buf),
1212 			  refcount_read(&root->refs));
1213 		WARN_ON_ONCE(1);
1214 		while (refcount_read(&root->refs) > 1)
1215 			btrfs_put_root(root);
1216 		btrfs_put_root(root);
1217 	}
1218 #endif
1219 }
1220 
1221 static void free_global_roots(struct btrfs_fs_info *fs_info)
1222 {
1223 	struct btrfs_root *root;
1224 	struct rb_node *node;
1225 
1226 	while ((node = rb_first_postorder(&fs_info->global_root_tree)) != NULL) {
1227 		root = rb_entry(node, struct btrfs_root, rb_node);
1228 		rb_erase(&root->rb_node, &fs_info->global_root_tree);
1229 		btrfs_put_root(root);
1230 	}
1231 }
1232 
1233 void btrfs_free_fs_info(struct btrfs_fs_info *fs_info)
1234 {
1235 	struct percpu_counter *em_counter = &fs_info->evictable_extent_maps;
1236 
1237 	if (fs_info->fs_devices)
1238 		btrfs_close_devices(fs_info->fs_devices);
1239 	btrfs_free_compress_wsm(fs_info);
1240 	percpu_counter_destroy(&fs_info->stats_read_blocks);
1241 	percpu_counter_destroy(&fs_info->dirty_metadata_bytes);
1242 	percpu_counter_destroy(&fs_info->delalloc_bytes);
1243 	percpu_counter_destroy(&fs_info->ordered_bytes);
1244 	if (percpu_counter_initialized(em_counter))
1245 		ASSERT(percpu_counter_sum_positive(em_counter) == 0);
1246 	percpu_counter_destroy(em_counter);
1247 	percpu_counter_destroy(&fs_info->dev_replace.bio_counter);
1248 	btrfs_free_stripe_hash_table(fs_info);
1249 	btrfs_free_ref_cache(fs_info);
1250 	kfree(fs_info->balance_ctl);
1251 	free_global_roots(fs_info);
1252 	btrfs_put_root(fs_info->tree_root);
1253 	btrfs_put_root(fs_info->chunk_root);
1254 	btrfs_put_root(fs_info->dev_root);
1255 	btrfs_put_root(fs_info->quota_root);
1256 	btrfs_put_root(fs_info->uuid_root);
1257 	btrfs_put_root(fs_info->fs_root);
1258 	btrfs_put_root(fs_info->data_reloc_root);
1259 	btrfs_put_root(fs_info->block_group_root);
1260 	btrfs_put_root(fs_info->stripe_root);
1261 	btrfs_put_root(fs_info->remap_root);
1262 	btrfs_check_leaked_roots(fs_info);
1263 	btrfs_extent_buffer_leak_debug_check(fs_info);
1264 	kfree(fs_info->super_copy);
1265 	kfree(fs_info->super_for_commit);
1266 	kvfree(fs_info);
1267 }
1268 
1269 
1270 /*
1271  * Get an in-memory reference of a root structure.
1272  *
1273  * For essential trees like root/extent tree, we grab it from fs_info directly.
1274  * For subvolume trees, we check the cached filesystem roots first. If not
1275  * found, then read it from disk and add it to cached fs roots.
1276  *
1277  * Caller should release the root by calling btrfs_put_root() after the usage.
1278  *
1279  * NOTE: Reloc and log trees can't be read by this function as they share the
1280  *	 same root objectid.
1281  *
1282  * @objectid:	root id
1283  * @anon_dev:	preallocated anonymous block device number for new roots,
1284  *		pass NULL for a new allocation.
1285  * @check_ref:	whether to check root item references, If true, return -ENOENT
1286  *		for orphan roots
1287  */
1288 static struct btrfs_root *btrfs_get_root_ref(struct btrfs_fs_info *fs_info,
1289 					     u64 objectid, dev_t *anon_dev,
1290 					     bool check_ref)
1291 {
1292 	struct btrfs_root *root;
1293 	struct btrfs_path *path;
1294 	struct btrfs_key key;
1295 	int ret;
1296 
1297 	root = btrfs_get_global_root(fs_info, objectid);
1298 	if (root)
1299 		return root;
1300 
1301 	/*
1302 	 * If we're called for non-subvolume trees, and above function didn't
1303 	 * find one, do not try to read it from disk.
1304 	 *
1305 	 * This is namely for free-space-tree and quota tree, which can change
1306 	 * at runtime and should only be grabbed from fs_info.
1307 	 */
1308 	if (!btrfs_is_fstree(objectid) && objectid != BTRFS_DATA_RELOC_TREE_OBJECTID)
1309 		return ERR_PTR(-ENOENT);
1310 again:
1311 	root = btrfs_lookup_fs_root(fs_info, objectid);
1312 	if (root) {
1313 		/*
1314 		 * Some other caller may have read out the newly inserted
1315 		 * subvolume already (for things like backref walk etc).  Not
1316 		 * that common but still possible.  In that case, we just need
1317 		 * to free the anon_dev.
1318 		 */
1319 		if (unlikely(anon_dev && *anon_dev)) {
1320 			free_anon_bdev(*anon_dev);
1321 			*anon_dev = 0;
1322 		}
1323 
1324 		if (check_ref && btrfs_root_refs(&root->root_item) == 0) {
1325 			btrfs_put_root(root);
1326 			return ERR_PTR(-ENOENT);
1327 		}
1328 		return root;
1329 	}
1330 
1331 	key.objectid = objectid;
1332 	key.type = BTRFS_ROOT_ITEM_KEY;
1333 	key.offset = (u64)-1;
1334 	root = btrfs_read_tree_root(fs_info->tree_root, &key);
1335 	if (IS_ERR(root))
1336 		return root;
1337 
1338 	if (check_ref && btrfs_root_refs(&root->root_item) == 0) {
1339 		ret = -ENOENT;
1340 		goto fail;
1341 	}
1342 
1343 	ret = btrfs_init_fs_root(root, anon_dev ? *anon_dev : 0);
1344 	if (ret)
1345 		goto fail;
1346 
1347 	path = btrfs_alloc_path();
1348 	if (!path) {
1349 		ret = -ENOMEM;
1350 		goto fail;
1351 	}
1352 	key.objectid = BTRFS_ORPHAN_OBJECTID;
1353 	key.type = BTRFS_ORPHAN_ITEM_KEY;
1354 	key.offset = objectid;
1355 
1356 	ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
1357 	btrfs_free_path(path);
1358 	if (ret < 0)
1359 		goto fail;
1360 	if (ret == 0)
1361 		set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state);
1362 
1363 	ret = btrfs_insert_fs_root(fs_info, root);
1364 	if (ret) {
1365 		if (ret == -EEXIST) {
1366 			btrfs_put_root(root);
1367 			goto again;
1368 		}
1369 		goto fail;
1370 	}
1371 	return root;
1372 fail:
1373 	/*
1374 	 * If our caller provided us an anonymous device, then it's his
1375 	 * responsibility to free it in case we fail. So we have to set our
1376 	 * root's anon_dev to 0 to avoid a double free, once by btrfs_put_root()
1377 	 * and once again by our caller.
1378 	 */
1379 	if (anon_dev && *anon_dev)
1380 		root->anon_dev = 0;
1381 	btrfs_put_root(root);
1382 	return ERR_PTR(ret);
1383 }
1384 
1385 /*
1386  * Get in-memory reference of a root structure
1387  *
1388  * @objectid:	tree objectid
1389  * @check_ref:	if set, verify that the tree exists and the item has at least
1390  *		one reference
1391  */
1392 struct btrfs_root *btrfs_get_fs_root(struct btrfs_fs_info *fs_info,
1393 				     u64 objectid, bool check_ref)
1394 {
1395 	return btrfs_get_root_ref(fs_info, objectid, NULL, check_ref);
1396 }
1397 
1398 /*
1399  * Get in-memory reference of a root structure, created as new, optionally pass
1400  * the anonymous block device id
1401  *
1402  * @objectid:	tree objectid
1403  * @anon_dev:	if NULL, allocate a new anonymous block device or use the
1404  *		parameter value if not NULL
1405  */
1406 struct btrfs_root *btrfs_get_new_fs_root(struct btrfs_fs_info *fs_info,
1407 					 u64 objectid, dev_t *anon_dev)
1408 {
1409 	return btrfs_get_root_ref(fs_info, objectid, anon_dev, true);
1410 }
1411 
1412 /*
1413  * Return a root for the given objectid.
1414  *
1415  * @fs_info:	the fs_info
1416  * @objectid:	the objectid we need to lookup
1417  *
1418  * This is exclusively used for backref walking, and exists specifically because
1419  * of how qgroups does lookups.  Qgroups will do a backref lookup at delayed ref
1420  * creation time, which means we may have to read the tree_root in order to look
1421  * up a fs root that is not in memory.  If the root is not in memory we will
1422  * read the tree root commit root and look up the fs root from there.  This is a
1423  * temporary root, it will not be inserted into the radix tree as it doesn't
1424  * have the most uptodate information, it'll simply be discarded once the
1425  * backref code is finished using the root.
1426  */
1427 struct btrfs_root *btrfs_get_fs_root_commit_root(struct btrfs_fs_info *fs_info,
1428 						 struct btrfs_path *path,
1429 						 u64 objectid)
1430 {
1431 	struct btrfs_root *root;
1432 	struct btrfs_key key;
1433 
1434 	ASSERT(path->search_commit_root && path->skip_locking);
1435 
1436 	/*
1437 	 * This can return -ENOENT if we ask for a root that doesn't exist, but
1438 	 * since this is called via the backref walking code we won't be looking
1439 	 * up a root that doesn't exist, unless there's corruption.  So if root
1440 	 * != NULL just return it.
1441 	 */
1442 	root = btrfs_get_global_root(fs_info, objectid);
1443 	if (root)
1444 		return root;
1445 
1446 	root = btrfs_lookup_fs_root(fs_info, objectid);
1447 	if (root)
1448 		return root;
1449 
1450 	key.objectid = objectid;
1451 	key.type = BTRFS_ROOT_ITEM_KEY;
1452 	key.offset = (u64)-1;
1453 	root = read_tree_root_path(fs_info->tree_root, path, &key);
1454 	btrfs_release_path(path);
1455 
1456 	return root;
1457 }
1458 
1459 static int cleaner_kthread(void *arg)
1460 {
1461 	struct btrfs_fs_info *fs_info = arg;
1462 	int again;
1463 
1464 	while (1) {
1465 		again = 0;
1466 
1467 		set_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags);
1468 
1469 		/* Make the cleaner go to sleep early. */
1470 		if (btrfs_need_cleaner_sleep(fs_info))
1471 			goto sleep;
1472 
1473 		/*
1474 		 * Do not do anything if we might cause open_ctree() to block
1475 		 * before we have finished mounting the filesystem.
1476 		 */
1477 		if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
1478 			goto sleep;
1479 
1480 		if (!mutex_trylock(&fs_info->cleaner_mutex))
1481 			goto sleep;
1482 
1483 		/*
1484 		 * Avoid the problem that we change the status of the fs
1485 		 * during the above check and trylock.
1486 		 */
1487 		if (btrfs_need_cleaner_sleep(fs_info)) {
1488 			mutex_unlock(&fs_info->cleaner_mutex);
1489 			goto sleep;
1490 		}
1491 
1492 		if (test_and_clear_bit(BTRFS_FS_FEATURE_CHANGED, &fs_info->flags))
1493 			btrfs_sysfs_feature_update(fs_info);
1494 
1495 		btrfs_run_delayed_iputs(fs_info);
1496 
1497 		set_bit(BTRFS_QGROUP_RUNTIME_BIT_REJECT_RESCAN, &fs_info->qgroup_flags);
1498 		again = btrfs_clean_one_deleted_snapshot(fs_info);
1499 		clear_bit(BTRFS_QGROUP_RUNTIME_BIT_REJECT_RESCAN, &fs_info->qgroup_flags);
1500 		mutex_unlock(&fs_info->cleaner_mutex);
1501 
1502 		/*
1503 		 * The defragger has dealt with the R/O remount and umount,
1504 		 * needn't do anything special here.
1505 		 */
1506 		btrfs_run_defrag_inodes(fs_info);
1507 
1508 		if (btrfs_fs_incompat(fs_info, REMAP_TREE) &&
1509 		    !btrfs_test_opt(fs_info, DISCARD_ASYNC))
1510 			btrfs_handle_fully_remapped_bgs(fs_info);
1511 
1512 		/*
1513 		 * Acquires fs_info->reclaim_bgs_lock to avoid racing
1514 		 * with relocation (btrfs_relocate_chunk) and relocation
1515 		 * acquires fs_info->cleaner_mutex (btrfs_relocate_block_group)
1516 		 * after acquiring fs_info->reclaim_bgs_lock. So we
1517 		 * can't hold, nor need to, fs_info->cleaner_mutex when deleting
1518 		 * unused block groups.
1519 		 */
1520 		btrfs_delete_unused_bgs(fs_info);
1521 
1522 		/*
1523 		 * Reclaim block groups in the reclaim_bgs list after we deleted
1524 		 * all unused block_groups. This possibly gives us some more free
1525 		 * space.
1526 		 */
1527 		btrfs_reclaim_bgs(fs_info);
1528 sleep:
1529 		clear_and_wake_up_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags);
1530 		if (kthread_should_park())
1531 			kthread_parkme();
1532 		if (kthread_should_stop())
1533 			return 0;
1534 		if (!again) {
1535 			set_current_state(TASK_INTERRUPTIBLE);
1536 			schedule();
1537 			__set_current_state(TASK_RUNNING);
1538 		}
1539 	}
1540 }
1541 
1542 static int transaction_kthread(void *arg)
1543 {
1544 	struct btrfs_root *root = arg;
1545 	struct btrfs_fs_info *fs_info = root->fs_info;
1546 	struct btrfs_trans_handle *trans;
1547 	struct btrfs_transaction *cur;
1548 	u64 transid;
1549 	time64_t delta;
1550 	unsigned long delay;
1551 	bool cannot_commit;
1552 
1553 	do {
1554 		cannot_commit = false;
1555 		delay = secs_to_jiffies(fs_info->commit_interval);
1556 		mutex_lock(&fs_info->transaction_kthread_mutex);
1557 
1558 		spin_lock(&fs_info->trans_lock);
1559 		cur = fs_info->running_transaction;
1560 		if (!cur) {
1561 			spin_unlock(&fs_info->trans_lock);
1562 			goto sleep;
1563 		}
1564 
1565 		delta = ktime_get_seconds() - cur->start_time;
1566 		if (!test_and_clear_bit(BTRFS_FS_COMMIT_TRANS, &fs_info->flags) &&
1567 		    cur->state < TRANS_STATE_COMMIT_PREP &&
1568 		    delta < fs_info->commit_interval) {
1569 			spin_unlock(&fs_info->trans_lock);
1570 			delay -= secs_to_jiffies(delta - 1);
1571 			delay = min(delay,
1572 				    secs_to_jiffies(fs_info->commit_interval));
1573 			goto sleep;
1574 		}
1575 		transid = cur->transid;
1576 		spin_unlock(&fs_info->trans_lock);
1577 
1578 		/* If the file system is aborted, this will always fail. */
1579 		trans = btrfs_attach_transaction(root);
1580 		if (IS_ERR(trans)) {
1581 			if (PTR_ERR(trans) != -ENOENT)
1582 				cannot_commit = true;
1583 			goto sleep;
1584 		}
1585 		if (transid == trans->transid) {
1586 			btrfs_commit_transaction(trans);
1587 		} else {
1588 			btrfs_end_transaction(trans);
1589 		}
1590 sleep:
1591 		wake_up_process(fs_info->cleaner_kthread);
1592 		mutex_unlock(&fs_info->transaction_kthread_mutex);
1593 
1594 		if (unlikely(BTRFS_FS_ERROR(fs_info)))
1595 			btrfs_cleanup_transaction(fs_info);
1596 		if (!kthread_should_stop() &&
1597 				(!btrfs_transaction_blocked(fs_info) ||
1598 				 cannot_commit))
1599 			schedule_timeout_interruptible(delay);
1600 	} while (!kthread_should_stop());
1601 	return 0;
1602 }
1603 
1604 /*
1605  * This will find the highest generation in the array of root backups.  The
1606  * index of the highest array is returned, or -EINVAL if we can't find
1607  * anything.
1608  *
1609  * We check to make sure the array is valid by comparing the
1610  * generation of the latest  root in the array with the generation
1611  * in the super block.  If they don't match we pitch it.
1612  */
1613 static int find_newest_super_backup(struct btrfs_fs_info *info)
1614 {
1615 	const u64 newest_gen = btrfs_super_generation(info->super_copy);
1616 	u64 cur;
1617 	struct btrfs_root_backup *root_backup;
1618 	int i;
1619 
1620 	for (i = 0; i < BTRFS_NUM_BACKUP_ROOTS; i++) {
1621 		root_backup = info->super_copy->super_roots + i;
1622 		cur = btrfs_backup_tree_root_gen(root_backup);
1623 		if (cur == newest_gen)
1624 			return i;
1625 	}
1626 
1627 	return -EINVAL;
1628 }
1629 
1630 /*
1631  * copy all the root pointers into the super backup array.
1632  * this will bump the backup pointer by one when it is
1633  * done
1634  */
1635 static int backup_super_roots(struct btrfs_fs_info *info)
1636 {
1637 	const int next_backup = info->backup_root_index;
1638 	struct btrfs_root_backup *root_backup;
1639 
1640 	root_backup = info->super_for_commit->super_roots + next_backup;
1641 
1642 	/*
1643 	 * make sure all of our padding and empty slots get zero filled
1644 	 * regardless of which ones we use today
1645 	 */
1646 	memset(root_backup, 0, sizeof(*root_backup));
1647 
1648 	info->backup_root_index = (next_backup + 1) % BTRFS_NUM_BACKUP_ROOTS;
1649 
1650 	btrfs_set_backup_tree_root(root_backup, info->tree_root->node->start);
1651 	btrfs_set_backup_tree_root_gen(root_backup,
1652 			       btrfs_header_generation(info->tree_root->node));
1653 
1654 	btrfs_set_backup_tree_root_level(root_backup,
1655 			       btrfs_header_level(info->tree_root->node));
1656 
1657 	btrfs_set_backup_chunk_root(root_backup, info->chunk_root->node->start);
1658 	btrfs_set_backup_chunk_root_gen(root_backup,
1659 			       btrfs_header_generation(info->chunk_root->node));
1660 	btrfs_set_backup_chunk_root_level(root_backup,
1661 			       btrfs_header_level(info->chunk_root->node));
1662 
1663 	if (!btrfs_fs_incompat(info, EXTENT_TREE_V2)) {
1664 		struct btrfs_root *extent_root = btrfs_extent_root(info, 0);
1665 		struct btrfs_root *csum_root = btrfs_csum_root(info, 0);
1666 
1667 		if (unlikely(!extent_root)) {
1668 			btrfs_err(info, "missing extent root for extent at bytenr 0");
1669 			return -EUCLEAN;
1670 		}
1671 		if (unlikely(!csum_root)) {
1672 			btrfs_err(info, "missing csum root for extent at bytenr 0");
1673 			return -EUCLEAN;
1674 		}
1675 
1676 		btrfs_set_backup_extent_root(root_backup,
1677 					     extent_root->node->start);
1678 		btrfs_set_backup_extent_root_gen(root_backup,
1679 				btrfs_header_generation(extent_root->node));
1680 		btrfs_set_backup_extent_root_level(root_backup,
1681 					btrfs_header_level(extent_root->node));
1682 
1683 		btrfs_set_backup_csum_root(root_backup, csum_root->node->start);
1684 		btrfs_set_backup_csum_root_gen(root_backup,
1685 					       btrfs_header_generation(csum_root->node));
1686 		btrfs_set_backup_csum_root_level(root_backup,
1687 						 btrfs_header_level(csum_root->node));
1688 	}
1689 
1690 	/*
1691 	 * we might commit during log recovery, which happens before we set
1692 	 * the fs_root.  Make sure it is valid before we fill it in.
1693 	 */
1694 	if (info->fs_root && info->fs_root->node) {
1695 		btrfs_set_backup_fs_root(root_backup,
1696 					 info->fs_root->node->start);
1697 		btrfs_set_backup_fs_root_gen(root_backup,
1698 			       btrfs_header_generation(info->fs_root->node));
1699 		btrfs_set_backup_fs_root_level(root_backup,
1700 			       btrfs_header_level(info->fs_root->node));
1701 	}
1702 
1703 	btrfs_set_backup_dev_root(root_backup, info->dev_root->node->start);
1704 	btrfs_set_backup_dev_root_gen(root_backup,
1705 			       btrfs_header_generation(info->dev_root->node));
1706 	btrfs_set_backup_dev_root_level(root_backup,
1707 				       btrfs_header_level(info->dev_root->node));
1708 
1709 	btrfs_set_backup_total_bytes(root_backup,
1710 			     btrfs_super_total_bytes(info->super_copy));
1711 	btrfs_set_backup_bytes_used(root_backup,
1712 			     btrfs_super_bytes_used(info->super_copy));
1713 	btrfs_set_backup_num_devices(root_backup,
1714 			     btrfs_super_num_devices(info->super_copy));
1715 
1716 	/*
1717 	 * if we don't copy this out to the super_copy, it won't get remembered
1718 	 * for the next commit
1719 	 */
1720 	memcpy(&info->super_copy->super_roots,
1721 	       &info->super_for_commit->super_roots,
1722 	       sizeof(*root_backup) * BTRFS_NUM_BACKUP_ROOTS);
1723 
1724 	return 0;
1725 }
1726 
1727 /*
1728  * Reads a backup root based on the passed priority. Prio 0 is the newest, prio
1729  * 1/2/3 are 2nd newest/3rd newest/4th (oldest) backup roots
1730  *
1731  * @fs_info:  filesystem whose backup roots need to be read
1732  * @priority: priority of backup root required
1733  *
1734  * Returns backup root index on success and -EINVAL otherwise.
1735  */
1736 static int read_backup_root(struct btrfs_fs_info *fs_info, u8 priority)
1737 {
1738 	int backup_index = find_newest_super_backup(fs_info);
1739 	struct btrfs_super_block *super = fs_info->super_copy;
1740 	struct btrfs_root_backup *root_backup;
1741 
1742 	if (priority < BTRFS_NUM_BACKUP_ROOTS && backup_index >= 0) {
1743 		if (priority == 0)
1744 			return backup_index;
1745 
1746 		backup_index = backup_index + BTRFS_NUM_BACKUP_ROOTS - priority;
1747 		backup_index %= BTRFS_NUM_BACKUP_ROOTS;
1748 	} else {
1749 		return -EINVAL;
1750 	}
1751 
1752 	root_backup = super->super_roots + backup_index;
1753 
1754 	btrfs_set_super_generation(super,
1755 				   btrfs_backup_tree_root_gen(root_backup));
1756 	btrfs_set_super_root(super, btrfs_backup_tree_root(root_backup));
1757 	btrfs_set_super_root_level(super,
1758 				   btrfs_backup_tree_root_level(root_backup));
1759 	btrfs_set_super_bytes_used(super, btrfs_backup_bytes_used(root_backup));
1760 
1761 	/*
1762 	 * Fixme: the total bytes and num_devices need to match or we should
1763 	 * need a fsck
1764 	 */
1765 	btrfs_set_super_total_bytes(super, btrfs_backup_total_bytes(root_backup));
1766 	btrfs_set_super_num_devices(super, btrfs_backup_num_devices(root_backup));
1767 
1768 	return backup_index;
1769 }
1770 
1771 /* helper to cleanup workers */
1772 static void btrfs_stop_all_workers(struct btrfs_fs_info *fs_info)
1773 {
1774 	if (fs_info->fixup_workers)
1775 		destroy_workqueue(fs_info->fixup_workers);
1776 	btrfs_destroy_workqueue(fs_info->delalloc_workers);
1777 	btrfs_destroy_workqueue(fs_info->workers);
1778 	if (fs_info->endio_workers)
1779 		destroy_workqueue(fs_info->endio_workers);
1780 	if (fs_info->rmw_workers)
1781 		destroy_workqueue(fs_info->rmw_workers);
1782 	btrfs_destroy_workqueue(fs_info->endio_write_workers);
1783 	btrfs_destroy_workqueue(fs_info->delayed_workers);
1784 	btrfs_destroy_workqueue(fs_info->caching_workers);
1785 	btrfs_destroy_workqueue(fs_info->flush_workers);
1786 	btrfs_destroy_workqueue(fs_info->qgroup_rescan_workers);
1787 	if (fs_info->discard_ctl.discard_workers)
1788 		destroy_workqueue(fs_info->discard_ctl.discard_workers);
1789 	/*
1790 	 * Now that all other work queues are destroyed, we can safely destroy
1791 	 * the queues used for metadata I/O, since tasks from those other work
1792 	 * queues can do metadata I/O operations.
1793 	 */
1794 	if (fs_info->endio_meta_workers)
1795 		destroy_workqueue(fs_info->endio_meta_workers);
1796 }
1797 
1798 static void free_root_extent_buffers(struct btrfs_root *root)
1799 {
1800 	if (root) {
1801 		free_extent_buffer(root->node);
1802 		free_extent_buffer(root->commit_root);
1803 		root->node = NULL;
1804 		root->commit_root = NULL;
1805 	}
1806 }
1807 
1808 static void free_global_root_pointers(struct btrfs_fs_info *fs_info)
1809 {
1810 	struct btrfs_root *root, *tmp;
1811 
1812 	rbtree_postorder_for_each_entry_safe(root, tmp,
1813 					     &fs_info->global_root_tree,
1814 					     rb_node)
1815 		free_root_extent_buffers(root);
1816 }
1817 
1818 /* helper to cleanup tree roots */
1819 static void free_root_pointers(struct btrfs_fs_info *info, bool free_chunk_root)
1820 {
1821 	free_root_extent_buffers(info->tree_root);
1822 
1823 	free_global_root_pointers(info);
1824 	free_root_extent_buffers(info->dev_root);
1825 	free_root_extent_buffers(info->quota_root);
1826 	free_root_extent_buffers(info->uuid_root);
1827 	free_root_extent_buffers(info->fs_root);
1828 	free_root_extent_buffers(info->data_reloc_root);
1829 	free_root_extent_buffers(info->block_group_root);
1830 	free_root_extent_buffers(info->stripe_root);
1831 	free_root_extent_buffers(info->remap_root);
1832 	if (free_chunk_root)
1833 		free_root_extent_buffers(info->chunk_root);
1834 }
1835 
1836 void btrfs_put_root(struct btrfs_root *root)
1837 {
1838 	if (!root)
1839 		return;
1840 
1841 	if (refcount_dec_and_test(&root->refs)) {
1842 		if (WARN_ON(!xa_empty(&root->inodes)))
1843 			xa_destroy(&root->inodes);
1844 		if (WARN_ON(!xa_empty(&root->delayed_nodes)))
1845 			xa_destroy(&root->delayed_nodes);
1846 		WARN_ON(test_bit(BTRFS_ROOT_DEAD_RELOC_TREE, &root->state));
1847 		if (root->anon_dev)
1848 			free_anon_bdev(root->anon_dev);
1849 		free_root_extent_buffers(root);
1850 #ifdef CONFIG_BTRFS_DEBUG
1851 		spin_lock(&root->fs_info->fs_roots_radix_lock);
1852 		list_del_init(&root->leak_list);
1853 		spin_unlock(&root->fs_info->fs_roots_radix_lock);
1854 #endif
1855 		kfree(root);
1856 	}
1857 }
1858 
1859 void btrfs_free_fs_roots(struct btrfs_fs_info *fs_info)
1860 {
1861 	int ret;
1862 	struct btrfs_root *gang[8];
1863 	int i;
1864 
1865 	while (!list_empty(&fs_info->dead_roots)) {
1866 		gang[0] = list_first_entry(&fs_info->dead_roots,
1867 					   struct btrfs_root, root_list);
1868 		list_del(&gang[0]->root_list);
1869 
1870 		if (test_bit(BTRFS_ROOT_IN_RADIX, &gang[0]->state))
1871 			btrfs_drop_and_free_fs_root(fs_info, gang[0]);
1872 		btrfs_put_root(gang[0]);
1873 	}
1874 
1875 	while (1) {
1876 		ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
1877 					     (void **)gang, 0,
1878 					     ARRAY_SIZE(gang));
1879 		if (!ret)
1880 			break;
1881 		for (i = 0; i < ret; i++)
1882 			btrfs_drop_and_free_fs_root(fs_info, gang[i]);
1883 	}
1884 }
1885 
1886 static void btrfs_init_scrub(struct btrfs_fs_info *fs_info)
1887 {
1888 	mutex_init(&fs_info->scrub_lock);
1889 	atomic_set(&fs_info->scrubs_running, 0);
1890 	atomic_set(&fs_info->scrub_pause_req, 0);
1891 	atomic_set(&fs_info->scrubs_paused, 0);
1892 	atomic_set(&fs_info->scrub_cancel_req, 0);
1893 	init_waitqueue_head(&fs_info->scrub_pause_wait);
1894 	refcount_set(&fs_info->scrub_workers_refcnt, 0);
1895 }
1896 
1897 static void btrfs_init_balance(struct btrfs_fs_info *fs_info)
1898 {
1899 	spin_lock_init(&fs_info->balance_lock);
1900 	mutex_init(&fs_info->balance_mutex);
1901 	atomic_set(&fs_info->balance_pause_req, 0);
1902 	atomic_set(&fs_info->balance_cancel_req, 0);
1903 	fs_info->balance_ctl = NULL;
1904 	init_waitqueue_head(&fs_info->balance_wait_q);
1905 	atomic_set(&fs_info->reloc_cancel_req, 0);
1906 }
1907 
1908 static int btrfs_init_btree_inode(struct super_block *sb)
1909 {
1910 	struct btrfs_fs_info *fs_info = btrfs_sb(sb);
1911 	unsigned long hash = btrfs_inode_hash(BTRFS_BTREE_INODE_OBJECTID,
1912 					      fs_info->tree_root);
1913 	struct inode *inode;
1914 
1915 	inode = new_inode(sb);
1916 	if (!inode)
1917 		return -ENOMEM;
1918 
1919 	btrfs_set_inode_number(BTRFS_I(inode), BTRFS_BTREE_INODE_OBJECTID);
1920 	set_nlink(inode, 1);
1921 	/*
1922 	 * we set the i_size on the btree inode to the max possible int.
1923 	 * the real end of the address space is determined by all of
1924 	 * the devices in the system
1925 	 */
1926 	inode->i_size = OFFSET_MAX;
1927 	inode->i_mapping->a_ops = &btree_aops;
1928 	mapping_set_gfp_mask(inode->i_mapping, GFP_NOFS);
1929 
1930 	btrfs_extent_io_tree_init(fs_info, &BTRFS_I(inode)->io_tree,
1931 				  IO_TREE_BTREE_INODE_IO);
1932 	btrfs_extent_map_tree_init(&BTRFS_I(inode)->extent_tree);
1933 
1934 	BTRFS_I(inode)->root = btrfs_grab_root(fs_info->tree_root);
1935 	set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
1936 	__insert_inode_hash(inode, hash);
1937 	set_bit(AS_KERNEL_FILE, &inode->i_mapping->flags);
1938 	fs_info->btree_inode = inode;
1939 
1940 	return 0;
1941 }
1942 
1943 static void btrfs_init_dev_replace_locks(struct btrfs_fs_info *fs_info)
1944 {
1945 	mutex_init(&fs_info->dev_replace.lock_finishing_cancel_unmount);
1946 	init_rwsem(&fs_info->dev_replace.rwsem);
1947 	init_waitqueue_head(&fs_info->dev_replace.replace_wait);
1948 }
1949 
1950 static void btrfs_init_qgroup(struct btrfs_fs_info *fs_info)
1951 {
1952 	spin_lock_init(&fs_info->qgroup_lock);
1953 	mutex_init(&fs_info->qgroup_ioctl_lock);
1954 	fs_info->qgroup_tree = RB_ROOT;
1955 	INIT_LIST_HEAD(&fs_info->dirty_qgroups);
1956 	fs_info->qgroup_seq = 1;
1957 	fs_info->qgroup_rescan_running = false;
1958 	fs_info->qgroup_drop_subtree_thres = BTRFS_QGROUP_DROP_SUBTREE_THRES_DEFAULT;
1959 	mutex_init(&fs_info->qgroup_rescan_lock);
1960 }
1961 
1962 static int btrfs_init_workqueues(struct btrfs_fs_info *fs_info)
1963 {
1964 	u32 max_active = fs_info->thread_pool_size;
1965 	unsigned int flags = WQ_MEM_RECLAIM | WQ_FREEZABLE | WQ_UNBOUND;
1966 	unsigned int ordered_flags = WQ_MEM_RECLAIM | WQ_FREEZABLE;
1967 
1968 	fs_info->workers =
1969 		btrfs_alloc_workqueue(fs_info, "worker", flags, max_active, 16);
1970 
1971 	fs_info->delalloc_workers =
1972 		btrfs_alloc_workqueue(fs_info, "delalloc",
1973 				      flags, max_active, 2);
1974 
1975 	fs_info->flush_workers =
1976 		btrfs_alloc_workqueue(fs_info, "flush_delalloc",
1977 				      flags, max_active, 0);
1978 
1979 	fs_info->caching_workers =
1980 		btrfs_alloc_workqueue(fs_info, "cache", flags, max_active, 0);
1981 
1982 	fs_info->fixup_workers =
1983 		alloc_ordered_workqueue("btrfs-fixup", ordered_flags);
1984 
1985 	fs_info->endio_workers =
1986 		alloc_workqueue("btrfs-endio", flags, max_active);
1987 	fs_info->endio_meta_workers =
1988 		alloc_workqueue("btrfs-endio-meta", flags, max_active);
1989 	fs_info->rmw_workers = alloc_workqueue("btrfs-rmw", flags, max_active);
1990 	fs_info->endio_write_workers =
1991 		btrfs_alloc_workqueue(fs_info, "endio-write", flags,
1992 				      max_active, 2);
1993 	fs_info->delayed_workers =
1994 		btrfs_alloc_workqueue(fs_info, "delayed-meta", flags,
1995 				      max_active, 0);
1996 	fs_info->qgroup_rescan_workers =
1997 		btrfs_alloc_ordered_workqueue(fs_info, "qgroup-rescan",
1998 					      ordered_flags);
1999 	fs_info->discard_ctl.discard_workers =
2000 		alloc_ordered_workqueue("btrfs-discard", WQ_FREEZABLE);
2001 
2002 	if (!(fs_info->workers &&
2003 	      fs_info->delalloc_workers && fs_info->flush_workers &&
2004 	      fs_info->endio_workers && fs_info->endio_meta_workers &&
2005 	      fs_info->endio_write_workers && fs_info->rmw_workers &&
2006 	      fs_info->caching_workers && fs_info->fixup_workers &&
2007 	      fs_info->delayed_workers && fs_info->qgroup_rescan_workers &&
2008 	      fs_info->discard_ctl.discard_workers)) {
2009 		return -ENOMEM;
2010 	}
2011 
2012 	return 0;
2013 }
2014 
2015 static void btrfs_init_csum_hash(struct btrfs_fs_info *fs_info, u16 csum_type)
2016 {
2017 	/* Check if the checksum implementation is a fast accelerated one. */
2018 	switch (csum_type) {
2019 	case BTRFS_CSUM_TYPE_CRC32:
2020 		if (crc32_optimizations() & CRC32C_OPTIMIZATION)
2021 			set_bit(BTRFS_FS_CSUM_IMPL_FAST, &fs_info->flags);
2022 		break;
2023 	case BTRFS_CSUM_TYPE_XXHASH:
2024 		set_bit(BTRFS_FS_CSUM_IMPL_FAST, &fs_info->flags);
2025 		break;
2026 	default:
2027 		break;
2028 	}
2029 
2030 	btrfs_info(fs_info, "using %s checksum algorithm",
2031 		   btrfs_super_csum_name(csum_type));
2032 }
2033 
2034 static int btrfs_replay_log(struct btrfs_fs_info *fs_info,
2035 			    struct btrfs_fs_devices *fs_devices)
2036 {
2037 	int ret;
2038 	struct btrfs_tree_parent_check check = { 0 };
2039 	struct btrfs_root *log_tree_root;
2040 	struct btrfs_super_block *disk_super = fs_info->super_copy;
2041 	u64 bytenr = btrfs_super_log_root(disk_super);
2042 	int level = btrfs_super_log_root_level(disk_super);
2043 
2044 	if (unlikely(fs_devices->rw_devices == 0)) {
2045 		btrfs_err(fs_info, "log replay required on RO media");
2046 		return -EIO;
2047 	}
2048 
2049 	log_tree_root = btrfs_alloc_root(fs_info, BTRFS_TREE_LOG_OBJECTID,
2050 					 GFP_KERNEL);
2051 	if (!log_tree_root)
2052 		return -ENOMEM;
2053 
2054 	check.level = level;
2055 	check.transid = fs_info->generation + 1;
2056 	check.owner_root = BTRFS_TREE_LOG_OBJECTID;
2057 	log_tree_root->node = read_tree_block(fs_info, bytenr, &check);
2058 	if (IS_ERR(log_tree_root->node)) {
2059 		ret = PTR_ERR(log_tree_root->node);
2060 		log_tree_root->node = NULL;
2061 		btrfs_err(fs_info, "failed to read log tree with error: %pe", ERR_PTR(ret));
2062 		btrfs_put_root(log_tree_root);
2063 		return ret;
2064 	}
2065 
2066 	/* returns with log_tree_root freed on success */
2067 	ret = btrfs_recover_log_trees(log_tree_root);
2068 	btrfs_put_root(log_tree_root);
2069 	if (unlikely(ret)) {
2070 		ASSERT(BTRFS_FS_ERROR(fs_info) != 0);
2071 		btrfs_err(fs_info, "failed to recover log trees with error: %pe", ERR_PTR(ret));
2072 		return ret;
2073 	}
2074 
2075 	if (sb_rdonly(fs_info->sb)) {
2076 		ret = btrfs_commit_super(fs_info);
2077 		if (ret)
2078 			return ret;
2079 	}
2080 
2081 	return 0;
2082 }
2083 
2084 static int load_global_roots_objectid(struct btrfs_root *tree_root,
2085 				      struct btrfs_path *path, u64 objectid,
2086 				      const char *name)
2087 {
2088 	struct btrfs_fs_info *fs_info = tree_root->fs_info;
2089 	struct btrfs_root *root;
2090 	u64 max_global_id = 0;
2091 	int ret;
2092 	struct btrfs_key key = {
2093 		.objectid = objectid,
2094 		.type = BTRFS_ROOT_ITEM_KEY,
2095 		.offset = 0,
2096 	};
2097 	bool found = false;
2098 
2099 	/* If we have IGNOREDATACSUMS skip loading these roots. */
2100 	if (objectid == BTRFS_CSUM_TREE_OBJECTID &&
2101 	    btrfs_test_opt(fs_info, IGNOREDATACSUMS)) {
2102 		set_bit(BTRFS_FS_STATE_NO_DATA_CSUMS, &fs_info->fs_state);
2103 		return 0;
2104 	}
2105 
2106 	while (1) {
2107 		ret = btrfs_search_slot(NULL, tree_root, &key, path, 0, 0);
2108 		if (ret < 0)
2109 			break;
2110 
2111 		if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
2112 			ret = btrfs_next_leaf(tree_root, path);
2113 			if (ret) {
2114 				if (ret > 0)
2115 					ret = 0;
2116 				break;
2117 			}
2118 		}
2119 		ret = 0;
2120 
2121 		btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
2122 		if (key.objectid != objectid)
2123 			break;
2124 		btrfs_release_path(path);
2125 
2126 		/*
2127 		 * Just worry about this for extent tree, it'll be the same for
2128 		 * everybody.
2129 		 */
2130 		if (objectid == BTRFS_EXTENT_TREE_OBJECTID)
2131 			max_global_id = max(max_global_id, key.offset);
2132 
2133 		found = true;
2134 		root = read_tree_root_path(tree_root, path, &key);
2135 		if (IS_ERR(root)) {
2136 			ret = PTR_ERR(root);
2137 			break;
2138 		}
2139 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2140 		ret = btrfs_global_root_insert(root);
2141 		if (ret) {
2142 			btrfs_put_root(root);
2143 			break;
2144 		}
2145 		key.offset++;
2146 	}
2147 	btrfs_release_path(path);
2148 
2149 	if (objectid == BTRFS_EXTENT_TREE_OBJECTID)
2150 		fs_info->nr_global_roots = max_global_id + 1;
2151 
2152 	if (!found || ret) {
2153 		if (objectid == BTRFS_CSUM_TREE_OBJECTID)
2154 			set_bit(BTRFS_FS_STATE_NO_DATA_CSUMS, &fs_info->fs_state);
2155 
2156 		if (!btrfs_test_opt(fs_info, IGNOREBADROOTS))
2157 			ret = ret ? ret : -ENOENT;
2158 		else
2159 			ret = 0;
2160 		btrfs_err(fs_info, "failed to load root %s", name);
2161 	}
2162 	return ret;
2163 }
2164 
2165 static int load_global_roots(struct btrfs_root *tree_root)
2166 {
2167 	BTRFS_PATH_AUTO_FREE(path);
2168 	int ret;
2169 
2170 	path = btrfs_alloc_path();
2171 	if (!path)
2172 		return -ENOMEM;
2173 
2174 	ret = load_global_roots_objectid(tree_root, path,
2175 					 BTRFS_EXTENT_TREE_OBJECTID, "extent");
2176 	if (ret)
2177 		return ret;
2178 	ret = load_global_roots_objectid(tree_root, path,
2179 					 BTRFS_CSUM_TREE_OBJECTID, "csum");
2180 	if (ret)
2181 		return ret;
2182 	if (!btrfs_fs_compat_ro(tree_root->fs_info, FREE_SPACE_TREE))
2183 		return ret;
2184 
2185 	return load_global_roots_objectid(tree_root, path,
2186 					  BTRFS_FREE_SPACE_TREE_OBJECTID,
2187 					  "free space");
2188 }
2189 
2190 static int btrfs_read_roots(struct btrfs_fs_info *fs_info)
2191 {
2192 	struct btrfs_root *tree_root = fs_info->tree_root;
2193 	struct btrfs_root *root;
2194 	struct btrfs_key location;
2195 	int ret;
2196 
2197 	ASSERT(fs_info->tree_root);
2198 
2199 	ret = load_global_roots(tree_root);
2200 	if (ret)
2201 		return ret;
2202 
2203 	location.type = BTRFS_ROOT_ITEM_KEY;
2204 	location.offset = 0;
2205 
2206 	if (btrfs_fs_compat_ro(fs_info, BLOCK_GROUP_TREE)) {
2207 		location.objectid = BTRFS_BLOCK_GROUP_TREE_OBJECTID;
2208 		root = btrfs_read_tree_root(tree_root, &location);
2209 		if (IS_ERR(root)) {
2210 			if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2211 				ret = PTR_ERR(root);
2212 				goto out;
2213 			}
2214 		} else {
2215 			set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2216 			fs_info->block_group_root = root;
2217 		}
2218 	}
2219 
2220 	location.objectid = BTRFS_DEV_TREE_OBJECTID;
2221 	root = btrfs_read_tree_root(tree_root, &location);
2222 	if (IS_ERR(root)) {
2223 		if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2224 			ret = PTR_ERR(root);
2225 			goto out;
2226 		}
2227 	} else {
2228 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2229 		fs_info->dev_root = root;
2230 	}
2231 	/* Initialize fs_info for all devices in any case */
2232 	ret = btrfs_init_devices_late(fs_info);
2233 	if (ret)
2234 		goto out;
2235 
2236 	if (btrfs_fs_incompat(fs_info, REMAP_TREE)) {
2237 		/* The remap_root has already been loaded in load_important_roots(). */
2238 		root = fs_info->remap_root;
2239 
2240 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2241 
2242 		root->root_key.objectid = BTRFS_REMAP_TREE_OBJECTID;
2243 		root->root_key.type = BTRFS_ROOT_ITEM_KEY;
2244 		root->root_key.offset = 0;
2245 
2246 		/* Check that data reloc tree doesn't also exist. */
2247 		location.objectid = BTRFS_DATA_RELOC_TREE_OBJECTID;
2248 		root = btrfs_read_tree_root(fs_info->tree_root, &location);
2249 		if (!IS_ERR(root)) {
2250 			btrfs_err(fs_info, "data reloc tree exists when remap-tree enabled");
2251 			btrfs_put_root(root);
2252 			return -EIO;
2253 		} else if (PTR_ERR(root) != -ENOENT) {
2254 			btrfs_warn(fs_info, "error %ld when checking for data reloc tree",
2255 				   PTR_ERR(root));
2256 		}
2257 	} else {
2258 		/*
2259 		 * This tree can share blocks with some other fs tree during
2260 		 * relocation and we need a proper setup by btrfs_get_fs_root().
2261 		 */
2262 		root = btrfs_get_fs_root(tree_root->fs_info,
2263 					 BTRFS_DATA_RELOC_TREE_OBJECTID, true);
2264 		if (IS_ERR(root)) {
2265 			if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2266 				location.objectid = BTRFS_DATA_RELOC_TREE_OBJECTID;
2267 				ret = PTR_ERR(root);
2268 				goto out;
2269 			}
2270 		} else {
2271 			set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2272 			fs_info->data_reloc_root = root;
2273 		}
2274 	}
2275 
2276 	location.objectid = BTRFS_QUOTA_TREE_OBJECTID;
2277 	root = btrfs_read_tree_root(tree_root, &location);
2278 	if (!IS_ERR(root)) {
2279 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2280 		fs_info->quota_root = root;
2281 	}
2282 
2283 	location.objectid = BTRFS_UUID_TREE_OBJECTID;
2284 	root = btrfs_read_tree_root(tree_root, &location);
2285 	if (IS_ERR(root)) {
2286 		if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2287 			ret = PTR_ERR(root);
2288 			if (ret != -ENOENT)
2289 				goto out;
2290 		}
2291 	} else {
2292 		set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2293 		fs_info->uuid_root = root;
2294 	}
2295 
2296 	if (btrfs_fs_incompat(fs_info, RAID_STRIPE_TREE)) {
2297 		location.objectid = BTRFS_RAID_STRIPE_TREE_OBJECTID;
2298 		root = btrfs_read_tree_root(tree_root, &location);
2299 		if (IS_ERR(root)) {
2300 			if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2301 				ret = PTR_ERR(root);
2302 				goto out;
2303 			}
2304 		} else {
2305 			set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2306 			fs_info->stripe_root = root;
2307 		}
2308 	}
2309 
2310 	return 0;
2311 out:
2312 	btrfs_warn(fs_info, "failed to read root (objectid=%llu): %pe",
2313 		   location.objectid, ERR_PTR(ret));
2314 	return ret;
2315 }
2316 
2317 static int validate_sys_chunk_array(const struct btrfs_fs_info *fs_info,
2318 				    const struct btrfs_super_block *sb)
2319 {
2320 	unsigned int cur = 0; /* Offset inside the sys chunk array */
2321 	/*
2322 	 * At sb read time, fs_info is not fully initialized. Thus we have
2323 	 * to use super block sectorsize, which should have been validated.
2324 	 */
2325 	const u32 sectorsize = btrfs_super_sectorsize(sb);
2326 	u32 sys_array_size = btrfs_super_sys_array_size(sb);
2327 
2328 	if (unlikely(sys_array_size > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE)) {
2329 		btrfs_err(fs_info, "system chunk array too big %u > %u",
2330 			  sys_array_size, BTRFS_SYSTEM_CHUNK_ARRAY_SIZE);
2331 		return -EUCLEAN;
2332 	}
2333 
2334 	/* It must hold at least one key and one chunk. */
2335 	if (unlikely(sys_array_size < sizeof(struct btrfs_disk_key) +
2336 		     sizeof(struct btrfs_chunk))) {
2337 		btrfs_err(fs_info, "system chunk array too small %u < %zu",
2338 			  sys_array_size,
2339 			  sizeof(struct btrfs_disk_key) + sizeof(struct btrfs_chunk));
2340 		return -EUCLEAN;
2341 	}
2342 
2343 	while (cur < sys_array_size) {
2344 		struct btrfs_disk_key *disk_key;
2345 		struct btrfs_chunk *chunk;
2346 		struct btrfs_key key;
2347 		u64 type;
2348 		u16 num_stripes;
2349 		u32 len;
2350 		int ret;
2351 
2352 		disk_key = (struct btrfs_disk_key *)(sb->sys_chunk_array + cur);
2353 		len = sizeof(*disk_key);
2354 
2355 		if (unlikely(cur + len > sys_array_size))
2356 			goto short_read;
2357 		cur += len;
2358 
2359 		btrfs_disk_key_to_cpu(&key, disk_key);
2360 		if (unlikely(key.type != BTRFS_CHUNK_ITEM_KEY)) {
2361 			btrfs_err(fs_info,
2362 			    "unexpected item type %u in sys_array at offset %u",
2363 				  key.type, cur);
2364 			return -EUCLEAN;
2365 		}
2366 
2367 		if (unlikely(cur + sizeof(*chunk) > sys_array_size))
2368 			goto short_read;
2369 
2370 		chunk = (struct btrfs_chunk *)(sb->sys_chunk_array + cur);
2371 		num_stripes = btrfs_stack_chunk_num_stripes(chunk);
2372 		if (unlikely(cur + btrfs_chunk_item_size(num_stripes) > sys_array_size))
2373 			goto short_read;
2374 		type = btrfs_stack_chunk_type(chunk);
2375 		if (unlikely(!(type & BTRFS_BLOCK_GROUP_SYSTEM))) {
2376 			btrfs_err(fs_info,
2377 			"invalid chunk type %llu in sys_array at offset %u",
2378 				  type, cur);
2379 			return -EUCLEAN;
2380 		}
2381 		ret = btrfs_check_chunk_valid(fs_info, NULL, chunk, key.offset,
2382 					      sectorsize);
2383 		if (unlikely(ret < 0))
2384 			return ret;
2385 		cur += btrfs_chunk_item_size(num_stripes);
2386 	}
2387 	return 0;
2388 short_read:
2389 	btrfs_err(fs_info,
2390 	"super block sys chunk array short read, cur=%u sys_array_size=%u",
2391 		  cur, sys_array_size);
2392 	return -EUCLEAN;
2393 }
2394 
2395 /*
2396  * Real super block validation
2397  * NOTE: super csum type and incompat features will not be checked here.
2398  *
2399  * @sb:		super block to check
2400  * @mirror_num:	the super block number to check its bytenr:
2401  * 		0	the primary (1st) sb
2402  * 		1, 2	2nd and 3rd backup copy
2403  * 	       -1	skip bytenr check
2404  */
2405 int btrfs_validate_super(const struct btrfs_fs_info *fs_info,
2406 			 const struct btrfs_super_block *sb, int mirror_num)
2407 {
2408 	const u32 nodesize = btrfs_super_nodesize(sb);
2409 	const u32 sectorsize = btrfs_super_sectorsize(sb);
2410 	int ret = 0;
2411 	const bool ignore_flags = btrfs_test_opt(fs_info, IGNORESUPERFLAGS);
2412 
2413 	if (unlikely(btrfs_super_magic(sb) != BTRFS_MAGIC)) {
2414 		btrfs_err(fs_info, "no valid FS found");
2415 		ret = -EINVAL;
2416 	}
2417 	if (unlikely(btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP)) {
2418 		if (!ignore_flags) {
2419 			btrfs_err(fs_info,
2420 			"unrecognized or unsupported super flag 0x%llx",
2421 				  btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP);
2422 			ret = -EINVAL;
2423 		} else {
2424 			btrfs_info(fs_info,
2425 			"unrecognized or unsupported super flags: 0x%llx, ignored",
2426 				   btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP);
2427 		}
2428 	}
2429 	if (unlikely(btrfs_super_root_level(sb) >= BTRFS_MAX_LEVEL)) {
2430 		btrfs_err(fs_info, "tree_root level too big: %d >= %d",
2431 				btrfs_super_root_level(sb), BTRFS_MAX_LEVEL);
2432 		ret = -EINVAL;
2433 	}
2434 	if (unlikely(btrfs_super_chunk_root_level(sb) >= BTRFS_MAX_LEVEL)) {
2435 		btrfs_err(fs_info, "chunk_root level too big: %d >= %d",
2436 				btrfs_super_chunk_root_level(sb), BTRFS_MAX_LEVEL);
2437 		ret = -EINVAL;
2438 	}
2439 	if (unlikely(btrfs_super_log_root_level(sb) >= BTRFS_MAX_LEVEL)) {
2440 		btrfs_err(fs_info, "log_root level too big: %d >= %d",
2441 				btrfs_super_log_root_level(sb), BTRFS_MAX_LEVEL);
2442 		ret = -EINVAL;
2443 	}
2444 
2445 	/*
2446 	 * Check sectorsize and nodesize first, other check will need it.
2447 	 * Check all possible sectorsize(4K, 8K, 16K, 32K, 64K) here.
2448 	 */
2449 	if (unlikely(!is_power_of_2(sectorsize) || sectorsize < BTRFS_MIN_BLOCKSIZE ||
2450 		     sectorsize > BTRFS_MAX_METADATA_BLOCKSIZE)) {
2451 		btrfs_err(fs_info, "invalid sectorsize %u", sectorsize);
2452 		ret = -EINVAL;
2453 	}
2454 
2455 	if (unlikely(!btrfs_supported_blocksize(sectorsize))) {
2456 		btrfs_err(fs_info,
2457 			"sectorsize %u not yet supported for page size %lu",
2458 			sectorsize, PAGE_SIZE);
2459 		ret = -EINVAL;
2460 	}
2461 
2462 	if (unlikely(!is_power_of_2(nodesize) || nodesize < sectorsize ||
2463 		     nodesize > BTRFS_MAX_METADATA_BLOCKSIZE)) {
2464 		btrfs_err(fs_info, "invalid nodesize %u", nodesize);
2465 		ret = -EINVAL;
2466 	}
2467 	if (unlikely(nodesize != le32_to_cpu(sb->__unused_leafsize))) {
2468 		btrfs_err(fs_info, "invalid leafsize %u, should be %u",
2469 			  le32_to_cpu(sb->__unused_leafsize), nodesize);
2470 		ret = -EINVAL;
2471 	}
2472 
2473 	/* Root alignment check */
2474 	if (unlikely(!IS_ALIGNED(btrfs_super_root(sb), sectorsize))) {
2475 		btrfs_err(fs_info, "tree_root block unaligned: %llu",
2476 			  btrfs_super_root(sb));
2477 		ret = -EINVAL;
2478 	}
2479 	if (unlikely(!IS_ALIGNED(btrfs_super_chunk_root(sb), sectorsize))) {
2480 		btrfs_err(fs_info, "chunk_root block unaligned: %llu",
2481 			   btrfs_super_chunk_root(sb));
2482 		ret = -EINVAL;
2483 	}
2484 	if (unlikely(!IS_ALIGNED(btrfs_super_log_root(sb), sectorsize))) {
2485 		btrfs_err(fs_info, "log_root block unaligned: %llu",
2486 			  btrfs_super_log_root(sb));
2487 		ret = -EINVAL;
2488 	}
2489 
2490 	if (unlikely(!fs_info->fs_devices->temp_fsid &&
2491 		     memcmp(fs_info->fs_devices->fsid, sb->fsid, BTRFS_FSID_SIZE) != 0)) {
2492 		btrfs_err(fs_info,
2493 		"superblock fsid doesn't match fsid of fs_devices: %pU != %pU",
2494 			  sb->fsid, fs_info->fs_devices->fsid);
2495 		ret = -EINVAL;
2496 	}
2497 
2498 	if (unlikely(memcmp(fs_info->fs_devices->metadata_uuid, btrfs_sb_fsid_ptr(sb),
2499 			    BTRFS_FSID_SIZE) != 0)) {
2500 		btrfs_err(fs_info,
2501 "superblock metadata_uuid doesn't match metadata uuid of fs_devices: %pU != %pU",
2502 			  btrfs_sb_fsid_ptr(sb), fs_info->fs_devices->metadata_uuid);
2503 		ret = -EINVAL;
2504 	}
2505 
2506 	if (unlikely(memcmp(fs_info->fs_devices->metadata_uuid, sb->dev_item.fsid,
2507 			    BTRFS_FSID_SIZE) != 0)) {
2508 		btrfs_err(fs_info,
2509 			"dev_item UUID does not match metadata fsid: %pU != %pU",
2510 			fs_info->fs_devices->metadata_uuid, sb->dev_item.fsid);
2511 		ret = -EINVAL;
2512 	}
2513 
2514 	/*
2515 	 * Artificial requirement for block-group-tree to force newer features
2516 	 * (free-space-tree, no-holes) so the test matrix is smaller.
2517 	 */
2518 	if (unlikely(btrfs_fs_compat_ro(fs_info, BLOCK_GROUP_TREE) &&
2519 		     (!btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE_VALID) ||
2520 		      !btrfs_fs_incompat(fs_info, NO_HOLES)))) {
2521 		btrfs_err(fs_info,
2522 		"block-group-tree feature requires free-space-tree and no-holes");
2523 		ret = -EINVAL;
2524 	}
2525 
2526 	if (btrfs_fs_incompat(fs_info, REMAP_TREE)) {
2527 		/*
2528 		 * Reduce test matrix for remap tree by requiring block-group-tree
2529 		 * and no-holes. Free-space-tree is a hard requirement.
2530 		 */
2531 		if (unlikely(!btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE_VALID) ||
2532 			     !btrfs_fs_incompat(fs_info, NO_HOLES) ||
2533 			     !btrfs_fs_compat_ro(fs_info, BLOCK_GROUP_TREE))) {
2534 			btrfs_err(fs_info,
2535 "remap-tree feature requires free-space-tree, no-holes, and block-group-tree");
2536 			ret = -EINVAL;
2537 		}
2538 
2539 		if (unlikely(btrfs_fs_incompat(fs_info, MIXED_GROUPS))) {
2540 			btrfs_err(fs_info, "remap-tree not supported with mixed-bg");
2541 			ret = -EINVAL;
2542 		}
2543 
2544 		if (unlikely(btrfs_fs_incompat(fs_info, ZONED))) {
2545 			btrfs_err(fs_info, "remap-tree not supported with zoned devices");
2546 			ret = -EINVAL;
2547 		}
2548 
2549 		if (unlikely(sectorsize > PAGE_SIZE)) {
2550 			btrfs_err(fs_info, "remap-tree not supported when block size > page size");
2551 			ret = -EINVAL;
2552 		}
2553 	}
2554 
2555 	/*
2556 	 * Hint to catch really bogus numbers, bitflips or so, more exact checks are
2557 	 * done later
2558 	 */
2559 	if (unlikely(btrfs_super_bytes_used(sb) < 6 * btrfs_super_nodesize(sb))) {
2560 		btrfs_err(fs_info, "bytes_used is too small %llu",
2561 			  btrfs_super_bytes_used(sb));
2562 		ret = -EINVAL;
2563 	}
2564 	if (unlikely(!is_power_of_2(btrfs_super_stripesize(sb)))) {
2565 		btrfs_err(fs_info, "invalid stripesize %u",
2566 			  btrfs_super_stripesize(sb));
2567 		ret = -EINVAL;
2568 	}
2569 	if (unlikely(btrfs_super_num_devices(sb) > (1UL << 31)))
2570 		btrfs_warn(fs_info, "suspicious number of devices: %llu",
2571 			   btrfs_super_num_devices(sb));
2572 	if (unlikely(btrfs_super_num_devices(sb) == 0)) {
2573 		btrfs_err(fs_info, "number of devices is 0");
2574 		ret = -EINVAL;
2575 	}
2576 
2577 	if (unlikely(mirror_num >= 0 &&
2578 		     btrfs_super_bytenr(sb) != btrfs_sb_offset(mirror_num))) {
2579 		btrfs_err(fs_info, "super offset mismatch %llu != %llu",
2580 			  btrfs_super_bytenr(sb), btrfs_sb_offset(mirror_num));
2581 		ret = -EINVAL;
2582 	}
2583 
2584 	if (unlikely(ret))
2585 		return ret;
2586 
2587 	ret = validate_sys_chunk_array(fs_info, sb);
2588 
2589 	/*
2590 	 * The generation is a global counter, we'll trust it more than the others
2591 	 * but it's still possible that it's the one that's wrong.
2592 	 */
2593 	if (unlikely(btrfs_super_generation(sb) < btrfs_super_chunk_root_generation(sb)))
2594 		btrfs_warn(fs_info,
2595 			"suspicious: generation < chunk_root_generation: %llu < %llu",
2596 			btrfs_super_generation(sb),
2597 			btrfs_super_chunk_root_generation(sb));
2598 	if (unlikely(btrfs_super_generation(sb) < btrfs_super_cache_generation(sb) &&
2599 		     btrfs_super_cache_generation(sb) != (u64)-1))
2600 		btrfs_warn(fs_info,
2601 			"suspicious: generation < cache_generation: %llu < %llu",
2602 			btrfs_super_generation(sb),
2603 			btrfs_super_cache_generation(sb));
2604 
2605 	return ret;
2606 }
2607 
2608 /*
2609  * Validation of super block at mount time.
2610  * Some checks already done early at mount time, like csum type and incompat
2611  * flags will be skipped.
2612  */
2613 static int btrfs_validate_mount_super(struct btrfs_fs_info *fs_info)
2614 {
2615 	return btrfs_validate_super(fs_info, fs_info->super_copy, 0);
2616 }
2617 
2618 /*
2619  * Validation of super block at write time.
2620  * Some checks like bytenr check will be skipped as their values will be
2621  * overwritten soon.
2622  * Extra checks like csum type and incompat flags will be done here.
2623  */
2624 static int btrfs_validate_write_super(struct btrfs_fs_info *fs_info,
2625 				      struct btrfs_super_block *sb)
2626 {
2627 	int ret;
2628 
2629 	ret = btrfs_validate_super(fs_info, sb, -1);
2630 	if (unlikely(ret < 0))
2631 		goto out;
2632 	if (unlikely(!btrfs_supported_super_csum(btrfs_super_csum_type(sb)))) {
2633 		ret = -EUCLEAN;
2634 		btrfs_err(fs_info, "invalid csum type, has %u want %u",
2635 			  btrfs_super_csum_type(sb), BTRFS_CSUM_TYPE_CRC32);
2636 		goto out;
2637 	}
2638 	if (unlikely(btrfs_super_incompat_flags(sb) & ~BTRFS_FEATURE_INCOMPAT_SUPP)) {
2639 		ret = -EUCLEAN;
2640 		btrfs_err(fs_info,
2641 		"invalid incompat flags, has 0x%llx valid mask 0x%llx",
2642 			  btrfs_super_incompat_flags(sb),
2643 			  (unsigned long long)BTRFS_FEATURE_INCOMPAT_SUPP);
2644 		goto out;
2645 	}
2646 out:
2647 	if (unlikely(ret < 0))
2648 		btrfs_err(fs_info,
2649 		"super block corruption detected before writing it to disk");
2650 	return ret;
2651 }
2652 
2653 static int load_super_root(struct btrfs_root *root, u64 bytenr, u64 gen, int level)
2654 {
2655 	struct btrfs_tree_parent_check check = {
2656 		.level = level,
2657 		.transid = gen,
2658 		.owner_root = btrfs_root_id(root)
2659 	};
2660 	int ret = 0;
2661 
2662 	root->node = read_tree_block(root->fs_info, bytenr, &check);
2663 	if (IS_ERR(root->node)) {
2664 		ret = PTR_ERR(root->node);
2665 		root->node = NULL;
2666 		return ret;
2667 	}
2668 
2669 	btrfs_set_root_node(&root->root_item, root->node);
2670 	root->commit_root = btrfs_root_node(root);
2671 	btrfs_set_root_refs(&root->root_item, 1);
2672 	return ret;
2673 }
2674 
2675 static int load_important_roots(struct btrfs_fs_info *fs_info)
2676 {
2677 	struct btrfs_super_block *sb = fs_info->super_copy;
2678 	u64 gen, bytenr;
2679 	int level, ret;
2680 
2681 	bytenr = btrfs_super_root(sb);
2682 	gen = btrfs_super_generation(sb);
2683 	level = btrfs_super_root_level(sb);
2684 	ret = load_super_root(fs_info->tree_root, bytenr, gen, level);
2685 	if (ret) {
2686 		btrfs_warn(fs_info, "couldn't read tree root");
2687 		return ret;
2688 	}
2689 
2690 	if (btrfs_fs_incompat(fs_info, REMAP_TREE)) {
2691 		bytenr = btrfs_super_remap_root(sb);
2692 		gen = btrfs_super_remap_root_generation(sb);
2693 		level = btrfs_super_remap_root_level(sb);
2694 		ret = load_super_root(fs_info->remap_root, bytenr, gen, level);
2695 		if (ret) {
2696 			btrfs_warn(fs_info, "couldn't read remap root");
2697 			return ret;
2698 		}
2699 	}
2700 
2701 	return 0;
2702 }
2703 
2704 static int __cold init_tree_roots(struct btrfs_fs_info *fs_info)
2705 {
2706 	int backup_index = find_newest_super_backup(fs_info);
2707 	struct btrfs_super_block *sb = fs_info->super_copy;
2708 	struct btrfs_root *tree_root = fs_info->tree_root;
2709 	bool use_backup = btrfs_test_opt(fs_info, USEBACKUPROOT);
2710 	int ret = 0;
2711 
2712 	if (use_backup) {
2713 		ASSERT(fs_info->use_backup_slot >= 0 &&
2714 		       fs_info->use_backup_slot < BTRFS_NUM_BACKUP_ROOTS);
2715 
2716 		ret = read_backup_root(fs_info, fs_info->use_backup_slot);
2717 		if (ret < 0) {
2718 			btrfs_err(fs_info,
2719 				  "failed to load backup roots at slot %d",
2720 				  fs_info->use_backup_slot);
2721 			return ret;
2722 		}
2723 		/*
2724 		 * Don't use the log in recovery mode, it won't be
2725 		 * valid
2726 		 */
2727 		btrfs_set_super_log_root(sb, 0);
2728 		backup_index = ret;
2729 		btrfs_warn(fs_info, "loaded backup roots at slot %d",
2730 			   fs_info->use_backup_slot);
2731 	}
2732 
2733 	ret = load_important_roots(fs_info);
2734 	if (ret)
2735 		return ret;
2736 
2737 	/*
2738 	 * No need to hold btrfs_root::objectid_mutex since the fs
2739 	 * hasn't been fully initialised and we are the only user
2740 	 */
2741 	ret = btrfs_init_root_free_objectid(tree_root);
2742 	if (ret < 0)
2743 		return ret;
2744 
2745 	ASSERT(tree_root->free_objectid <= BTRFS_LAST_FREE_OBJECTID);
2746 
2747 	ret = btrfs_read_roots(fs_info);
2748 	if (ret < 0)
2749 		return ret;
2750 
2751 	/* All successful */
2752 	fs_info->generation = btrfs_header_generation(tree_root->node);
2753 	btrfs_set_last_trans_committed(fs_info, fs_info->generation);
2754 	fs_info->last_reloc_trans = 0;
2755 
2756 	/* Always begin writing backup roots after the one being used */
2757 	if (backup_index < 0) {
2758 		fs_info->backup_root_index = 0;
2759 	} else {
2760 		fs_info->backup_root_index = backup_index + 1;
2761 		fs_info->backup_root_index %= BTRFS_NUM_BACKUP_ROOTS;
2762 	}
2763 	return ret;
2764 }
2765 
2766 /*
2767  * Lockdep gets confused between our buffer_tree which requires IRQ locking because
2768  * we modify marks in the IRQ context, and our delayed inode xarray which doesn't
2769  * have these requirements. Use a class key so lockdep doesn't get them mixed up.
2770  */
2771 static struct lock_class_key buffer_xa_class;
2772 
2773 void btrfs_init_fs_info(struct btrfs_fs_info *fs_info)
2774 {
2775 	INIT_RADIX_TREE(&fs_info->fs_roots_radix, GFP_ATOMIC);
2776 
2777 	/* Use the same flags as mapping->i_pages. */
2778 	xa_init_flags(&fs_info->buffer_tree, XA_FLAGS_LOCK_IRQ | XA_FLAGS_ACCOUNT);
2779 	lockdep_set_class(&fs_info->buffer_tree.xa_lock, &buffer_xa_class);
2780 
2781 	INIT_LIST_HEAD(&fs_info->trans_list);
2782 	INIT_LIST_HEAD(&fs_info->dead_roots);
2783 	INIT_LIST_HEAD(&fs_info->delayed_iputs);
2784 	INIT_LIST_HEAD(&fs_info->delalloc_roots);
2785 	INIT_LIST_HEAD(&fs_info->caching_block_groups);
2786 	spin_lock_init(&fs_info->delalloc_root_lock);
2787 	spin_lock_init(&fs_info->trans_lock);
2788 	spin_lock_init(&fs_info->fs_roots_radix_lock);
2789 	spin_lock_init(&fs_info->delayed_iput_lock);
2790 	spin_lock_init(&fs_info->defrag_inodes_lock);
2791 	spin_lock_init(&fs_info->super_lock);
2792 	spin_lock_init(&fs_info->unused_bgs_lock);
2793 	spin_lock_init(&fs_info->treelog_bg_lock);
2794 	spin_lock_init(&fs_info->zone_active_bgs_lock);
2795 	spin_lock_init(&fs_info->relocation_bg_lock);
2796 	rwlock_init(&fs_info->tree_mod_log_lock);
2797 	rwlock_init(&fs_info->global_root_lock);
2798 	mutex_init(&fs_info->unused_bg_unpin_mutex);
2799 	mutex_init(&fs_info->reclaim_bgs_lock);
2800 	mutex_init(&fs_info->reloc_mutex);
2801 	spin_lock_init(&fs_info->reloc_ctl_lock);
2802 	mutex_init(&fs_info->delalloc_root_mutex);
2803 	mutex_init(&fs_info->zoned_meta_io_lock);
2804 	mutex_init(&fs_info->zoned_data_reloc_io_lock);
2805 	seqlock_init(&fs_info->profiles_lock);
2806 
2807 	btrfs_lockdep_init_map(fs_info, btrfs_trans_num_writers);
2808 	btrfs_lockdep_init_map(fs_info, btrfs_trans_num_extwriters);
2809 	btrfs_lockdep_init_map(fs_info, btrfs_trans_pending_ordered);
2810 	btrfs_lockdep_init_map(fs_info, btrfs_ordered_extent);
2811 	btrfs_state_lockdep_init_map(fs_info, btrfs_trans_commit_prep,
2812 				     BTRFS_LOCKDEP_TRANS_COMMIT_PREP);
2813 	btrfs_state_lockdep_init_map(fs_info, btrfs_trans_unblocked,
2814 				     BTRFS_LOCKDEP_TRANS_UNBLOCKED);
2815 	btrfs_state_lockdep_init_map(fs_info, btrfs_trans_super_committed,
2816 				     BTRFS_LOCKDEP_TRANS_SUPER_COMMITTED);
2817 	btrfs_state_lockdep_init_map(fs_info, btrfs_trans_completed,
2818 				     BTRFS_LOCKDEP_TRANS_COMPLETED);
2819 
2820 	INIT_LIST_HEAD(&fs_info->dirty_cowonly_roots);
2821 	INIT_LIST_HEAD(&fs_info->space_info);
2822 	INIT_LIST_HEAD(&fs_info->tree_mod_seq_list);
2823 	INIT_LIST_HEAD(&fs_info->unused_bgs);
2824 	INIT_LIST_HEAD(&fs_info->reclaim_bgs);
2825 	INIT_LIST_HEAD(&fs_info->fully_remapped_bgs);
2826 	INIT_LIST_HEAD(&fs_info->zone_active_bgs);
2827 #ifdef CONFIG_BTRFS_DEBUG
2828 	INIT_LIST_HEAD(&fs_info->allocated_roots);
2829 	INIT_LIST_HEAD(&fs_info->allocated_ebs);
2830 	spin_lock_init(&fs_info->eb_leak_lock);
2831 #endif
2832 	fs_info->mapping_tree = RB_ROOT_CACHED;
2833 	rwlock_init(&fs_info->mapping_tree_lock);
2834 	btrfs_init_block_rsv(&fs_info->global_block_rsv,
2835 			     BTRFS_BLOCK_RSV_GLOBAL);
2836 	btrfs_init_block_rsv(&fs_info->trans_block_rsv, BTRFS_BLOCK_RSV_TRANS);
2837 	btrfs_init_block_rsv(&fs_info->chunk_block_rsv, BTRFS_BLOCK_RSV_CHUNK);
2838 	btrfs_init_block_rsv(&fs_info->remap_block_rsv, BTRFS_BLOCK_RSV_REMAP);
2839 	btrfs_init_block_rsv(&fs_info->treelog_rsv, BTRFS_BLOCK_RSV_TREELOG);
2840 	btrfs_init_block_rsv(&fs_info->empty_block_rsv, BTRFS_BLOCK_RSV_EMPTY);
2841 	btrfs_init_block_rsv(&fs_info->delayed_block_rsv,
2842 			     BTRFS_BLOCK_RSV_DELOPS);
2843 	btrfs_init_block_rsv(&fs_info->delayed_refs_rsv,
2844 			     BTRFS_BLOCK_RSV_DELREFS);
2845 
2846 	atomic_set(&fs_info->async_delalloc_pages, 0);
2847 	atomic_set(&fs_info->defrag_running, 0);
2848 	atomic_set(&fs_info->nr_delayed_iputs, 0);
2849 	atomic64_set(&fs_info->tree_mod_seq, 0);
2850 	fs_info->global_root_tree = RB_ROOT;
2851 	fs_info->max_inline = BTRFS_DEFAULT_MAX_INLINE;
2852 	fs_info->metadata_ratio = 0;
2853 	fs_info->defrag_inodes = RB_ROOT;
2854 	atomic64_set(&fs_info->free_chunk_space, 0);
2855 	fs_info->tree_mod_log = RB_ROOT;
2856 	fs_info->commit_interval = BTRFS_DEFAULT_COMMIT_INTERVAL;
2857 	btrfs_init_ref_verify(fs_info);
2858 
2859 	fs_info->thread_pool_size = min_t(unsigned long,
2860 					  num_online_cpus() + 2, 8);
2861 
2862 	INIT_LIST_HEAD(&fs_info->ordered_roots);
2863 	spin_lock_init(&fs_info->ordered_root_lock);
2864 
2865 	btrfs_init_scrub(fs_info);
2866 	btrfs_init_balance(fs_info);
2867 	btrfs_init_async_reclaim_work(fs_info);
2868 	btrfs_init_extent_map_shrinker_work(fs_info);
2869 
2870 	rwlock_init(&fs_info->block_group_cache_lock);
2871 	fs_info->block_group_cache_tree = RB_ROOT_CACHED;
2872 
2873 	btrfs_extent_io_tree_init(fs_info, &fs_info->excluded_extents,
2874 				  IO_TREE_FS_EXCLUDED_EXTENTS);
2875 
2876 	mutex_init(&fs_info->ordered_operations_mutex);
2877 	mutex_init(&fs_info->tree_log_mutex);
2878 	mutex_init(&fs_info->chunk_mutex);
2879 	mutex_init(&fs_info->transaction_kthread_mutex);
2880 	mutex_init(&fs_info->cleaner_mutex);
2881 	mutex_init(&fs_info->remap_mutex);
2882 	mutex_init(&fs_info->ro_block_group_mutex);
2883 	init_rwsem(&fs_info->commit_root_sem);
2884 	init_rwsem(&fs_info->cleanup_work_sem);
2885 	init_rwsem(&fs_info->subvol_sem);
2886 	sema_init(&fs_info->uuid_tree_rescan_sem, 1);
2887 
2888 	btrfs_init_dev_replace_locks(fs_info);
2889 	btrfs_init_qgroup(fs_info);
2890 	btrfs_discard_init(fs_info);
2891 
2892 	btrfs_init_free_cluster(&fs_info->meta_alloc_cluster);
2893 	btrfs_init_free_cluster(&fs_info->data_alloc_cluster);
2894 
2895 	init_waitqueue_head(&fs_info->transaction_throttle);
2896 	init_waitqueue_head(&fs_info->transaction_wait);
2897 	init_waitqueue_head(&fs_info->transaction_blocked_wait);
2898 	init_waitqueue_head(&fs_info->async_submit_wait);
2899 	init_waitqueue_head(&fs_info->delayed_iputs_wait);
2900 
2901 	fs_info->use_backup_slot = -1;
2902 	/* Usable values until the real ones are cached from the superblock */
2903 	fs_info->nodesize = 4096;
2904 	fs_info->sectorsize = 4096;
2905 	fs_info->sectorsize_bits = ilog2(4096);
2906 
2907 	/* Default compress algorithm when user does -o compress */
2908 	fs_info->compress_type = BTRFS_COMPRESS_ZLIB;
2909 
2910 	fs_info->max_extent_size = BTRFS_MAX_EXTENT_SIZE;
2911 
2912 	spin_lock_init(&fs_info->swapfile_pins_lock);
2913 	fs_info->swapfile_pins = RB_ROOT;
2914 
2915 	fs_info->bg_reclaim_threshold = BTRFS_DEFAULT_RECLAIM_THRESH;
2916 	INIT_WORK(&fs_info->reclaim_bgs_work, btrfs_reclaim_bgs_work);
2917 }
2918 
2919 static int init_mount_fs_info(struct btrfs_fs_info *fs_info, struct super_block *sb)
2920 {
2921 	int ret;
2922 
2923 	fs_info->sb = sb;
2924 	/* Temporary fixed values for block size until we read the superblock. */
2925 	sb->s_blocksize = BTRFS_BDEV_BLOCKSIZE;
2926 	sb->s_blocksize_bits = blksize_bits(BTRFS_BDEV_BLOCKSIZE);
2927 
2928 	ret = percpu_counter_init(&fs_info->ordered_bytes, 0, GFP_KERNEL);
2929 	if (ret)
2930 		return ret;
2931 
2932 	ret = percpu_counter_init(&fs_info->evictable_extent_maps, 0, GFP_KERNEL);
2933 	if (ret)
2934 		return ret;
2935 
2936 	ret = percpu_counter_init(&fs_info->dirty_metadata_bytes, 0, GFP_KERNEL);
2937 	if (ret)
2938 		return ret;
2939 
2940 	ret = percpu_counter_init(&fs_info->stats_read_blocks, 0, GFP_KERNEL);
2941 	if (ret)
2942 		return ret;
2943 
2944 	fs_info->dirty_metadata_batch = PAGE_SIZE *
2945 					(1 + ilog2(nr_cpu_ids));
2946 
2947 	ret = percpu_counter_init(&fs_info->delalloc_bytes, 0, GFP_KERNEL);
2948 	if (ret)
2949 		return ret;
2950 
2951 	ret = percpu_counter_init(&fs_info->dev_replace.bio_counter, 0,
2952 			GFP_KERNEL);
2953 	if (ret)
2954 		return ret;
2955 
2956 	btrfs_init_delayed_root(&fs_info->delayed_root);
2957 
2958 	if (sb_rdonly(sb))
2959 		set_bit(BTRFS_FS_STATE_RO, &fs_info->fs_state);
2960 	if (btrfs_test_opt(fs_info, IGNOREMETACSUMS))
2961 		set_bit(BTRFS_FS_STATE_SKIP_META_CSUMS, &fs_info->fs_state);
2962 
2963 	return btrfs_alloc_stripe_hash_table(fs_info);
2964 }
2965 
2966 static int btrfs_uuid_rescan_kthread(void *data)
2967 {
2968 	struct btrfs_fs_info *fs_info = data;
2969 	int ret;
2970 
2971 	/*
2972 	 * 1st step is to iterate through the existing UUID tree and
2973 	 * to delete all entries that contain outdated data.
2974 	 * 2nd step is to add all missing entries to the UUID tree.
2975 	 */
2976 	ret = btrfs_uuid_tree_iterate(fs_info);
2977 	if (ret < 0) {
2978 		if (ret != -EINTR)
2979 			btrfs_warn(fs_info, "iterating uuid_tree failed %pe",
2980 				   ERR_PTR(ret));
2981 		up(&fs_info->uuid_tree_rescan_sem);
2982 		return ret;
2983 	}
2984 	return btrfs_uuid_scan_kthread(data);
2985 }
2986 
2987 static int btrfs_check_uuid_tree(struct btrfs_fs_info *fs_info)
2988 {
2989 	struct task_struct *task;
2990 
2991 	down(&fs_info->uuid_tree_rescan_sem);
2992 	task = kthread_run(btrfs_uuid_rescan_kthread, fs_info, "btrfs-uuid");
2993 	if (IS_ERR(task)) {
2994 		/* fs_info->update_uuid_tree_gen remains 0 in all error case */
2995 		up(&fs_info->uuid_tree_rescan_sem);
2996 		return PTR_ERR(task);
2997 	}
2998 
2999 	return 0;
3000 }
3001 
3002 static int btrfs_cleanup_fs_roots(struct btrfs_fs_info *fs_info)
3003 {
3004 	u64 root_objectid = 0;
3005 	struct btrfs_root *gang[8];
3006 	int ret = 0;
3007 
3008 	while (1) {
3009 		unsigned int found;
3010 
3011 		spin_lock(&fs_info->fs_roots_radix_lock);
3012 		found = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
3013 					     (void **)gang, root_objectid,
3014 					     ARRAY_SIZE(gang));
3015 		if (!found) {
3016 			spin_unlock(&fs_info->fs_roots_radix_lock);
3017 			break;
3018 		}
3019 		root_objectid = btrfs_root_id(gang[found - 1]) + 1;
3020 
3021 		for (int i = 0; i < found; i++) {
3022 			/* Avoid to grab roots in dead_roots. */
3023 			if (btrfs_root_refs(&gang[i]->root_item) == 0) {
3024 				gang[i] = NULL;
3025 				continue;
3026 			}
3027 			/* Grab all the search result for later use. */
3028 			gang[i] = btrfs_grab_root(gang[i]);
3029 		}
3030 		spin_unlock(&fs_info->fs_roots_radix_lock);
3031 
3032 		for (int i = 0; i < found; i++) {
3033 			if (!gang[i])
3034 				continue;
3035 			root_objectid = btrfs_root_id(gang[i]);
3036 			/*
3037 			 * Continue to release the remaining roots after the first
3038 			 * error without cleanup and preserve the first error
3039 			 * for the return.
3040 			 */
3041 			if (!ret)
3042 				ret = btrfs_orphan_cleanup(gang[i]);
3043 			btrfs_put_root(gang[i]);
3044 		}
3045 		if (ret)
3046 			break;
3047 
3048 		root_objectid++;
3049 	}
3050 	return ret;
3051 }
3052 
3053 /*
3054  * Mounting logic specific to read-write file systems. Shared by open_ctree
3055  * and btrfs_remount when remounting from read-only to read-write.
3056  */
3057 int btrfs_start_pre_rw_mount(struct btrfs_fs_info *fs_info)
3058 {
3059 	int ret;
3060 	bool rebuild_free_space_tree = false;
3061 
3062 	if (btrfs_test_opt(fs_info, CLEAR_CACHE) &&
3063 	    btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
3064 		if (btrfs_fs_incompat(fs_info, EXTENT_TREE_V2))
3065 			btrfs_warn(fs_info,
3066 				   "'clear_cache' option is ignored with extent tree v2");
3067 		else if (btrfs_fs_incompat(fs_info, REMAP_TREE))
3068 			btrfs_warn(fs_info, "'clear_cache' option is ignored with remap tree");
3069 		else
3070 			rebuild_free_space_tree = true;
3071 	} else if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE) &&
3072 		   !btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE_VALID)) {
3073 		btrfs_warn(fs_info, "free space tree is invalid");
3074 		rebuild_free_space_tree = true;
3075 	}
3076 
3077 	if (rebuild_free_space_tree) {
3078 		btrfs_info(fs_info, "rebuilding free space tree");
3079 		ret = btrfs_rebuild_free_space_tree(fs_info);
3080 		if (ret) {
3081 			btrfs_warn(fs_info,
3082 				   "failed to rebuild free space tree: %pe", ERR_PTR(ret));
3083 			return ret;
3084 		}
3085 	}
3086 
3087 	if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE) &&
3088 	    !btrfs_test_opt(fs_info, FREE_SPACE_TREE)) {
3089 		btrfs_info(fs_info, "disabling free space tree");
3090 		ret = btrfs_delete_free_space_tree(fs_info);
3091 		if (ret) {
3092 			btrfs_warn(fs_info,
3093 				   "failed to disable free space tree: %pe", ERR_PTR(ret));
3094 			return ret;
3095 		}
3096 	}
3097 
3098 	/*
3099 	 * Before btrfs-progs v6.16.1 mkfs.btrfs can leave free space entries
3100 	 * for deleted temporary chunks. Delete them if they exist.
3101 	 */
3102 	ret = btrfs_delete_orphan_free_space_entries(fs_info);
3103 	if (ret < 0) {
3104 		btrfs_err(fs_info, "failed to delete orphan free space tree entries: %pe",
3105 			  ERR_PTR(ret));
3106 		return ret;
3107 	}
3108 	/*
3109 	 * btrfs_find_orphan_roots() is responsible for finding all the dead
3110 	 * roots (with 0 refs), flag them with BTRFS_ROOT_DEAD_TREE and load
3111 	 * them into the fs_info->fs_roots_radix tree. This must be done before
3112 	 * calling btrfs_orphan_cleanup() on the tree root. If we don't do it
3113 	 * first, then btrfs_orphan_cleanup() will delete a dead root's orphan
3114 	 * item before the root's tree is deleted - this means that if we unmount
3115 	 * or crash before the deletion completes, on the next mount we will not
3116 	 * delete what remains of the tree because the orphan item does not
3117 	 * exists anymore, which is what tells us we have a pending deletion.
3118 	 */
3119 	ret = btrfs_find_orphan_roots(fs_info);
3120 	if (ret)
3121 		return ret;
3122 
3123 	ret = btrfs_cleanup_fs_roots(fs_info);
3124 	if (ret)
3125 		return ret;
3126 
3127 	down_read(&fs_info->cleanup_work_sem);
3128 	if ((ret = btrfs_orphan_cleanup(fs_info->fs_root)) ||
3129 	    (ret = btrfs_orphan_cleanup(fs_info->tree_root))) {
3130 		up_read(&fs_info->cleanup_work_sem);
3131 		return ret;
3132 	}
3133 	up_read(&fs_info->cleanup_work_sem);
3134 
3135 	mutex_lock(&fs_info->cleaner_mutex);
3136 	ret = btrfs_recover_relocation(fs_info);
3137 	mutex_unlock(&fs_info->cleaner_mutex);
3138 	if (ret < 0) {
3139 		btrfs_warn(fs_info, "failed to recover relocation: %pe", ERR_PTR(ret));
3140 		return ret;
3141 	}
3142 
3143 	if (btrfs_test_opt(fs_info, FREE_SPACE_TREE) &&
3144 	    !btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
3145 		btrfs_info(fs_info, "creating free space tree");
3146 		ret = btrfs_create_free_space_tree(fs_info);
3147 		if (ret) {
3148 			btrfs_warn(fs_info,
3149 				"failed to create free space tree: %pe", ERR_PTR(ret));
3150 			return ret;
3151 		}
3152 	}
3153 
3154 	if (btrfs_free_space_cache_v1_active(fs_info)) {
3155 		ret = btrfs_cleanup_free_space_cache_v1(fs_info);
3156 		if (ret)
3157 			return ret;
3158 	}
3159 
3160 	ret = btrfs_resume_balance_async(fs_info);
3161 	if (ret)
3162 		return ret;
3163 
3164 	ret = btrfs_resume_dev_replace_async(fs_info);
3165 	if (ret) {
3166 		btrfs_warn(fs_info, "failed to resume dev_replace");
3167 		return ret;
3168 	}
3169 
3170 	btrfs_qgroup_rescan_resume(fs_info);
3171 
3172 	if (!fs_info->uuid_root) {
3173 		btrfs_info(fs_info, "creating UUID tree");
3174 		ret = btrfs_create_uuid_tree(fs_info);
3175 		if (ret) {
3176 			btrfs_warn(fs_info,
3177 				   "failed to create the UUID tree %pe", ERR_PTR(ret));
3178 			return ret;
3179 		}
3180 	}
3181 
3182 	return 0;
3183 }
3184 
3185 /*
3186  * Do various sanity and dependency checks of different features.
3187  *
3188  * @is_rw_mount:	If the mount is read-write.
3189  *
3190  * This is the place for less strict checks (like for subpage or artificial
3191  * feature dependencies).
3192  *
3193  * For strict checks or possible corruption detection, see
3194  * btrfs_validate_super().
3195  *
3196  * This should be called after btrfs_parse_options(), as some mount options
3197  * (space cache related) can modify on-disk format like free space tree and
3198  * screw up certain feature dependencies.
3199  */
3200 int btrfs_check_features(struct btrfs_fs_info *fs_info, bool is_rw_mount)
3201 {
3202 	struct btrfs_super_block *disk_super = fs_info->super_copy;
3203 	u64 incompat = btrfs_super_incompat_flags(disk_super);
3204 	const u64 compat_ro = btrfs_super_compat_ro_flags(disk_super);
3205 	const u64 compat_ro_unsupp = (compat_ro & ~BTRFS_FEATURE_COMPAT_RO_SUPP);
3206 
3207 	if (incompat & ~BTRFS_FEATURE_INCOMPAT_SUPP) {
3208 		btrfs_err(fs_info,
3209 		"cannot mount because of unknown incompat features (0x%llx)",
3210 		    incompat & ~BTRFS_FEATURE_INCOMPAT_SUPP);
3211 		return -EINVAL;
3212 	}
3213 
3214 	/* Runtime limitation for mixed block groups. */
3215 	if ((incompat & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS) &&
3216 	    (fs_info->sectorsize != fs_info->nodesize)) {
3217 		btrfs_err(fs_info,
3218 "unequal nodesize/sectorsize (%u != %u) are not allowed for mixed block groups",
3219 			fs_info->nodesize, fs_info->sectorsize);
3220 		return -EINVAL;
3221 	}
3222 
3223 	/* Mixed backref is an always-enabled feature. */
3224 	incompat |= BTRFS_FEATURE_INCOMPAT_MIXED_BACKREF;
3225 
3226 	/* Set compression related flags just in case. */
3227 	if (fs_info->compress_type == BTRFS_COMPRESS_LZO)
3228 		incompat |= BTRFS_FEATURE_INCOMPAT_COMPRESS_LZO;
3229 	else if (fs_info->compress_type == BTRFS_COMPRESS_ZSTD)
3230 		incompat |= BTRFS_FEATURE_INCOMPAT_COMPRESS_ZSTD;
3231 
3232 	/*
3233 	 * An ancient flag, which should really be marked deprecated.
3234 	 * Such runtime limitation doesn't really need a incompat flag.
3235 	 */
3236 	if (btrfs_super_nodesize(disk_super) > PAGE_SIZE)
3237 		incompat |= BTRFS_FEATURE_INCOMPAT_BIG_METADATA;
3238 
3239 	if (compat_ro_unsupp && is_rw_mount) {
3240 		btrfs_err(fs_info,
3241 	"cannot mount read-write because of unknown compat_ro features (0x%llx)",
3242 		       compat_ro_unsupp);
3243 		return -EINVAL;
3244 	}
3245 
3246 	/*
3247 	 * We have unsupported RO compat features, although RO mounted, we
3248 	 * should not cause any metadata writes, including log replay.
3249 	 * Or we could screw up whatever the new feature requires.
3250 	 */
3251 	if (compat_ro_unsupp && btrfs_super_log_root(disk_super) &&
3252 	    !btrfs_test_opt(fs_info, NOLOGREPLAY)) {
3253 		btrfs_err(fs_info,
3254 "cannot replay dirty log with unsupported compat_ro features (0x%llx), try rescue=nologreplay",
3255 			  compat_ro_unsupp);
3256 		return -EINVAL;
3257 	}
3258 
3259 	/*
3260 	 * Artificial limitations for block group tree, to force
3261 	 * block-group-tree to rely on no-holes and free-space-tree.
3262 	 */
3263 	if (btrfs_fs_compat_ro(fs_info, BLOCK_GROUP_TREE) &&
3264 	    (!btrfs_fs_incompat(fs_info, NO_HOLES) ||
3265 	     !btrfs_test_opt(fs_info, FREE_SPACE_TREE))) {
3266 		btrfs_err(fs_info,
3267 "block-group-tree feature requires no-holes and free-space-tree features");
3268 		return -EINVAL;
3269 	}
3270 
3271 	/* This can be called by remount, we need to protect the super block. */
3272 	spin_lock(&fs_info->super_lock);
3273 	btrfs_set_super_incompat_flags(disk_super, incompat);
3274 	spin_unlock(&fs_info->super_lock);
3275 
3276 	return 0;
3277 }
3278 
3279 /*
3280  * Try to wait for any metadata readahead, and invalidate all btree folios.
3281  *
3282  * If the invalidation failed, report any dirty/held extent buffers.
3283  */
3284 static void invalidate_and_check_btree_folios(struct btrfs_fs_info *fs_info)
3285 {
3286 	unsigned long index = 0;
3287 	struct extent_buffer *eb;
3288 	int ret;
3289 
3290 	ret = invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
3291 	if (likely(ret == 0))
3292 		return;
3293 
3294 	/*
3295 	 * Some btree pages can not be invalidated, this happens when some tree
3296 	 * blocks are still held (either by readahead or some task is holding a ref).
3297 	 */
3298 	rcu_read_lock();
3299 	xa_for_each(&fs_info->buffer_tree, index, eb) {
3300 		unsigned int refs;
3301 
3302 		/* Increase the ref so that the eb won't disappear. */
3303 		if (!refcount_inc_not_zero(&eb->refs))
3304 			continue;
3305 		rcu_read_unlock();
3306 
3307 		/* Wait for any readahead first. */
3308 		if (test_bit(EXTENT_BUFFER_READING, &eb->bflags))
3309 			wait_on_bit_io(&eb->bflags, EXTENT_BUFFER_READING,
3310 				       TASK_UNINTERRUPTIBLE);
3311 		/*
3312 		 * We hold the spinlock to make sure above
3313 		 * EXTENT_BUFFER_READING flag is cleared with the held
3314 		 * ref dropped.
3315 		 * Or we can hit a race window and lead to false alerts.
3316 		 */
3317 		spin_lock(&eb->refs_lock);
3318 		refs = refcount_read(&eb->refs);
3319 		spin_unlock(&eb->refs_lock);
3320 
3321 		/*
3322 		 * The refs threshold is 2, one held by us at the beginning
3323 		 * of the loop, one for the ownership in the buffer tree.
3324 		 */
3325 		if (unlikely(refs > 2 || extent_buffer_under_io(eb))) {
3326 			WARN_ON_ONCE(IS_ENABLED(CONFIG_BTRFS_DEBUG));
3327 			btrfs_warn(fs_info,
3328 			"unable to release extent buffer %llu owner %llu gen %llu refs %u flags 0x%lx",
3329 				   eb->start, btrfs_header_owner(eb),
3330 				   btrfs_header_generation(eb),
3331 				   refs, eb->bflags);
3332 		}
3333 		free_extent_buffer(eb);
3334 		rcu_read_lock();
3335 	}
3336 	rcu_read_unlock();
3337 	invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
3338 }
3339 
3340 static u32 calc_block_max_order(u32 sectorsize_bits)
3341 {
3342 	u32 max_size;
3343 
3344 	max_size = min(BTRFS_MAX_BLOCKS_PER_FOLIO << sectorsize_bits,
3345 		       BTRFS_MAX_FOLIO_SIZE);
3346 	return ilog2(round_up(max_size, PAGE_SIZE) >> PAGE_SHIFT);
3347 }
3348 
3349 int __cold open_ctree(struct super_block *sb, struct btrfs_fs_devices *fs_devices)
3350 {
3351 	u32 sectorsize;
3352 	u32 nodesize;
3353 	u64 generation;
3354 	u16 csum_type;
3355 	struct btrfs_super_block *disk_super;
3356 	struct btrfs_fs_info *fs_info = btrfs_sb(sb);
3357 	struct btrfs_root *tree_root;
3358 	struct btrfs_root *chunk_root;
3359 	struct btrfs_root *remap_root;
3360 	int ret;
3361 	int level;
3362 
3363 	ret = init_mount_fs_info(fs_info, sb);
3364 	if (ret)
3365 		goto fail;
3366 
3367 	/* These need to be init'ed before we start creating inodes and such. */
3368 	tree_root = btrfs_alloc_root(fs_info, BTRFS_ROOT_TREE_OBJECTID,
3369 				     GFP_KERNEL);
3370 	fs_info->tree_root = tree_root;
3371 	chunk_root = btrfs_alloc_root(fs_info, BTRFS_CHUNK_TREE_OBJECTID,
3372 				      GFP_KERNEL);
3373 	fs_info->chunk_root = chunk_root;
3374 	if (!tree_root || !chunk_root) {
3375 		ret = -ENOMEM;
3376 		goto fail;
3377 	}
3378 
3379 	ret = btrfs_init_btree_inode(sb);
3380 	if (ret)
3381 		goto fail;
3382 
3383 	invalidate_bdev(fs_devices->latest_dev->bdev);
3384 
3385 	/*
3386 	 * Read super block and check the signature bytes only
3387 	 */
3388 	disk_super = btrfs_read_disk_super(fs_devices->latest_dev->bdev, 0, false);
3389 	if (IS_ERR(disk_super)) {
3390 		ret = PTR_ERR(disk_super);
3391 		goto fail_alloc;
3392 	}
3393 
3394 	btrfs_info(fs_info, "first mount of filesystem %pU", disk_super->fsid);
3395 	/*
3396 	 * Verify the type first, if that or the checksum value are
3397 	 * corrupted, we'll find out
3398 	 */
3399 	csum_type = btrfs_super_csum_type(disk_super);
3400 	if (!btrfs_supported_super_csum(csum_type)) {
3401 		btrfs_err(fs_info, "unsupported checksum algorithm: %u",
3402 			  csum_type);
3403 		ret = -EINVAL;
3404 		btrfs_release_disk_super(disk_super);
3405 		goto fail_alloc;
3406 	}
3407 
3408 	fs_info->csum_size = btrfs_super_csum_size(disk_super);
3409 	fs_info->csum_type = csum_type;
3410 
3411 	btrfs_init_csum_hash(fs_info, csum_type);
3412 
3413 	/*
3414 	 * We want to check superblock checksum, the type is stored inside.
3415 	 * Pass the whole disk block of size BTRFS_SUPER_INFO_SIZE (4k).
3416 	 */
3417 	if (btrfs_check_super_csum(fs_info, disk_super)) {
3418 		btrfs_err(fs_info, "superblock checksum mismatch");
3419 		ret = -EINVAL;
3420 		btrfs_release_disk_super(disk_super);
3421 		goto fail_alloc;
3422 	}
3423 
3424 	/*
3425 	 * super_copy is zeroed at allocation time and we never touch the
3426 	 * following bytes up to INFO_SIZE, the checksum is calculated from
3427 	 * the whole block of INFO_SIZE
3428 	 */
3429 	memcpy(fs_info->super_copy, disk_super, sizeof(*fs_info->super_copy));
3430 	btrfs_release_disk_super(disk_super);
3431 
3432 	disk_super = fs_info->super_copy;
3433 
3434 	memcpy(fs_info->super_for_commit, fs_info->super_copy,
3435 	       sizeof(*fs_info->super_for_commit));
3436 
3437 	ret = btrfs_validate_mount_super(fs_info);
3438 	if (ret) {
3439 		btrfs_err(fs_info, "superblock contains fatal errors");
3440 		ret = -EINVAL;
3441 		goto fail_alloc;
3442 	}
3443 
3444 	if (!btrfs_super_root(disk_super)) {
3445 		btrfs_err(fs_info, "invalid superblock tree root bytenr");
3446 		ret = -EINVAL;
3447 		goto fail_alloc;
3448 	}
3449 
3450 	/* check FS state, whether FS is broken. */
3451 	if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_ERROR)
3452 		WRITE_ONCE(fs_info->fs_error, -EUCLEAN);
3453 
3454 	/* If the fs has any rescue options, no transaction is allowed. */
3455 	if (btrfs_is_full_ro(fs_info))
3456 		WRITE_ONCE(fs_info->fs_error, -EROFS);
3457 
3458 	/* Set up fs_info before parsing mount options */
3459 	nodesize = btrfs_super_nodesize(disk_super);
3460 	sectorsize = btrfs_super_sectorsize(disk_super);
3461 	fs_info->dirty_metadata_batch = nodesize * (1 + ilog2(nr_cpu_ids));
3462 	fs_info->delalloc_batch = sectorsize * 512 * (1 + ilog2(nr_cpu_ids));
3463 
3464 	fs_info->nodesize = nodesize;
3465 	fs_info->nodesize_bits = ilog2(nodesize);
3466 	fs_info->sectorsize = sectorsize;
3467 	fs_info->sectorsize_bits = ilog2(sectorsize);
3468 	fs_info->block_min_order = ilog2(round_up(sectorsize, PAGE_SIZE) >> PAGE_SHIFT);
3469 	/*
3470 	 * For HIGHMEM, a large folio cannot be mapped in one go, breaking a lot
3471 	 * of basic assumptions for btrfs IOs.
3472 	 * Disable large folios for such 32-bit systems.
3473 	 */
3474 	if (IS_ENABLED(CONFIG_HIGHMEM))
3475 		fs_info->block_max_order = fs_info->block_min_order;
3476 	else
3477 		fs_info->block_max_order = calc_block_max_order(fs_info->sectorsize_bits);
3478 	fs_info->csums_per_leaf = BTRFS_MAX_ITEM_SIZE(fs_info) / fs_info->csum_size;
3479 	fs_info->fs_devices->fs_info = fs_info;
3480 
3481 	if (fs_info->sectorsize > PAGE_SIZE)
3482 		btrfs_warn(fs_info,
3483 			   "support for block size %u with page size %lu is experimental, some features may be missing",
3484 			   fs_info->sectorsize, PAGE_SIZE);
3485 	/*
3486 	 * Handle the space caching options appropriately now that we have the
3487 	 * super block loaded and validated.
3488 	 */
3489 	btrfs_set_free_space_cache_settings(fs_info);
3490 
3491 	if (!btrfs_check_options(fs_info, &fs_info->mount_opt, sb->s_flags)) {
3492 		ret = -EINVAL;
3493 		goto fail_alloc;
3494 	}
3495 
3496 	ret = btrfs_check_features(fs_info, !sb_rdonly(sb));
3497 	if (ret < 0)
3498 		goto fail_alloc;
3499 
3500 	if (btrfs_super_incompat_flags(disk_super) & BTRFS_FEATURE_INCOMPAT_REMAP_TREE) {
3501 		remap_root = btrfs_alloc_root(fs_info, BTRFS_REMAP_TREE_OBJECTID,
3502 					      GFP_KERNEL);
3503 		fs_info->remap_root = remap_root;
3504 		if (!remap_root) {
3505 			ret = -ENOMEM;
3506 			goto fail_alloc;
3507 		}
3508 	}
3509 
3510 	/*
3511 	 * At this point our mount options are validated, if we set ->max_inline
3512 	 * to something non-standard make sure we truncate it to sectorsize.
3513 	 */
3514 	fs_info->max_inline = min_t(u64, fs_info->max_inline, fs_info->sectorsize);
3515 
3516 	ret = btrfs_alloc_compress_wsm(fs_info);
3517 	if (ret)
3518 		goto fail_sb_buffer;
3519 	ret = btrfs_init_workqueues(fs_info);
3520 	if (ret)
3521 		goto fail_sb_buffer;
3522 
3523 	sb->s_bdi->ra_pages *= btrfs_super_num_devices(disk_super);
3524 	sb->s_bdi->ra_pages = max(sb->s_bdi->ra_pages, SZ_4M / PAGE_SIZE);
3525 
3526 	/* Update the values for the current filesystem. */
3527 	sb->s_blocksize = sectorsize;
3528 	sb->s_blocksize_bits = blksize_bits(sectorsize);
3529 	/*
3530 	 * When temp_fsid is active, fs_devices->fsid is assigned a random UUID
3531 	 * at mount. This inconsistent UUID causes issues for layered filesystems
3532 	 * like OverlayFS. Since metadata_uuid may or may not be set, provide the
3533 	 * on-disk UUID directly from the super_copy.
3534 	 */
3535 	if (fs_info->fs_devices->temp_fsid)
3536 		memcpy(&sb->s_uuid, fs_info->super_copy->fsid, BTRFS_FSID_SIZE);
3537 	else
3538 		memcpy(&sb->s_uuid, fs_info->fs_devices->fsid, BTRFS_FSID_SIZE);
3539 
3540 	mutex_lock(&fs_info->chunk_mutex);
3541 	ret = btrfs_read_sys_array(fs_info);
3542 	mutex_unlock(&fs_info->chunk_mutex);
3543 	if (ret) {
3544 		btrfs_err(fs_info, "failed to read the system array: %pe", ERR_PTR(ret));
3545 		goto fail_sb_buffer;
3546 	}
3547 
3548 	generation = btrfs_super_chunk_root_generation(disk_super);
3549 	level = btrfs_super_chunk_root_level(disk_super);
3550 	ret = load_super_root(chunk_root, btrfs_super_chunk_root(disk_super),
3551 			      generation, level);
3552 	if (ret) {
3553 		btrfs_err(fs_info, "failed to read chunk root");
3554 		goto fail_tree_roots;
3555 	}
3556 
3557 	read_extent_buffer(chunk_root->node, fs_info->chunk_tree_uuid,
3558 			   offsetof(struct btrfs_header, chunk_tree_uuid),
3559 			   BTRFS_UUID_SIZE);
3560 
3561 	ret = btrfs_read_chunk_tree(fs_info);
3562 	if (ret) {
3563 		btrfs_err(fs_info, "failed to read chunk tree: %pe", ERR_PTR(ret));
3564 		goto fail_tree_roots;
3565 	}
3566 
3567 	/*
3568 	 * At this point we know all the devices that make this filesystem,
3569 	 * including the seed devices but we don't know yet if the replace
3570 	 * target is required. So free devices that are not part of this
3571 	 * filesystem but skip the replace target device which is checked
3572 	 * below in btrfs_init_dev_replace().
3573 	 */
3574 	btrfs_free_extra_devids(fs_devices);
3575 	if (unlikely(!fs_devices->latest_dev->bdev)) {
3576 		btrfs_err(fs_info, "failed to read devices");
3577 		ret = -EIO;
3578 		goto fail_tree_roots;
3579 	}
3580 
3581 	ret = init_tree_roots(fs_info);
3582 	if (ret)
3583 		goto fail_tree_roots;
3584 
3585 	/*
3586 	 * Get zone type information of zoned block devices. This will also
3587 	 * handle emulation of a zoned filesystem if a regular device has the
3588 	 * zoned incompat feature flag set.
3589 	 */
3590 	ret = btrfs_get_dev_zone_info_all_devices(fs_info);
3591 	if (ret) {
3592 		btrfs_err(fs_info,
3593 			  "zoned: failed to read device zone info: %pe", ERR_PTR(ret));
3594 		goto fail_block_groups;
3595 	}
3596 
3597 	/*
3598 	 * If we have a uuid root and we're not being told to rescan we need to
3599 	 * check the generation here so we can set the
3600 	 * BTRFS_FS_UPDATE_UUID_TREE_GEN bit.  Otherwise we could commit the
3601 	 * transaction during a balance or the log replay without updating the
3602 	 * uuid generation, and then if we crash we would rescan the uuid tree,
3603 	 * even though it was perfectly fine.
3604 	 */
3605 	if (fs_info->uuid_root && !btrfs_test_opt(fs_info, RESCAN_UUID_TREE) &&
3606 	    fs_info->generation == btrfs_super_uuid_tree_generation(disk_super))
3607 		set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
3608 
3609 	if (unlikely(btrfs_verify_dev_items(fs_info))) {
3610 		ret = -EUCLEAN;
3611 		goto fail_block_groups;
3612 	}
3613 	ret = btrfs_verify_dev_extents(fs_info);
3614 	if (ret) {
3615 		btrfs_err(fs_info,
3616 			  "failed to verify dev extents against chunks: %pe",
3617 			  ERR_PTR(ret));
3618 		goto fail_block_groups;
3619 	}
3620 	ret = btrfs_recover_balance(fs_info);
3621 	if (ret) {
3622 		btrfs_err(fs_info, "failed to recover balance: %pe", ERR_PTR(ret));
3623 		goto fail_block_groups;
3624 	}
3625 
3626 	ret = btrfs_init_dev_stats(fs_info);
3627 	if (ret) {
3628 		btrfs_err(fs_info, "failed to init dev_stats: %pe", ERR_PTR(ret));
3629 		goto fail_block_groups;
3630 	}
3631 
3632 	ret = btrfs_init_dev_replace(fs_info);
3633 	if (ret) {
3634 		btrfs_err(fs_info, "failed to init dev_replace: %pe", ERR_PTR(ret));
3635 		goto fail_block_groups;
3636 	}
3637 
3638 	ret = btrfs_check_zoned_mode(fs_info);
3639 	if (ret) {
3640 		btrfs_err(fs_info, "failed to initialize zoned mode: %pe",
3641 			  ERR_PTR(ret));
3642 		goto fail_block_groups;
3643 	}
3644 
3645 	ret = btrfs_sysfs_add_fsid(fs_devices);
3646 	if (ret) {
3647 		btrfs_err(fs_info, "failed to init sysfs fsid interface: %pe",
3648 			  ERR_PTR(ret));
3649 		goto fail_block_groups;
3650 	}
3651 
3652 	ret = btrfs_sysfs_add_mounted(fs_info);
3653 	if (ret) {
3654 		btrfs_err(fs_info, "failed to init sysfs interface: %pe", ERR_PTR(ret));
3655 		goto fail_fsdev_sysfs;
3656 	}
3657 
3658 	ret = btrfs_init_space_info(fs_info);
3659 	if (ret) {
3660 		btrfs_err(fs_info, "failed to initialize space info: %pe", ERR_PTR(ret));
3661 		goto fail_sysfs;
3662 	}
3663 
3664 	ret = btrfs_read_block_groups(fs_info);
3665 	if (ret) {
3666 		btrfs_err(fs_info, "failed to read block groups: %pe", ERR_PTR(ret));
3667 		goto fail_sysfs;
3668 	}
3669 
3670 	if (btrfs_fs_incompat(fs_info, REMAP_TREE)) {
3671 		ret = btrfs_populate_fully_remapped_bgs_list(fs_info);
3672 		if (ret) {
3673 			btrfs_err(fs_info, "failed to populate fully_remapped_bgs list: %pe",
3674 				  ERR_PTR(ret));
3675 			goto fail_sysfs;
3676 		}
3677 	}
3678 
3679 	ret = btrfs_init_writeback_bio_size(fs_info);
3680 	if (ret) {
3681 		btrfs_err(fs_info, "failed to get optimum writeback size: %pe",
3682 			  ERR_PTR(ret));
3683 		goto fail_sysfs;
3684 	}
3685 
3686 	btrfs_free_zone_cache(fs_info);
3687 
3688 	btrfs_check_active_zone_reservation(fs_info);
3689 
3690 	if (!sb_rdonly(sb) && fs_info->fs_devices->missing_devices &&
3691 	    !btrfs_check_rw_degradable(fs_info, NULL)) {
3692 		btrfs_warn(fs_info,
3693 		"writable mount is not allowed due to too many missing devices");
3694 		ret = -EINVAL;
3695 		goto fail_sysfs;
3696 	}
3697 
3698 	fs_info->cleaner_kthread = kthread_run(cleaner_kthread, fs_info,
3699 					       "btrfs-cleaner");
3700 	if (IS_ERR(fs_info->cleaner_kthread)) {
3701 		ret = PTR_ERR(fs_info->cleaner_kthread);
3702 		goto fail_sysfs;
3703 	}
3704 
3705 	fs_info->transaction_kthread = kthread_run(transaction_kthread,
3706 						   tree_root,
3707 						   "btrfs-transaction");
3708 	if (IS_ERR(fs_info->transaction_kthread)) {
3709 		ret = PTR_ERR(fs_info->transaction_kthread);
3710 		goto fail_cleaner;
3711 	}
3712 
3713 	/*
3714 	 * Starts a transaction, must be called after the transaction kthread
3715 	 * is initialized.
3716 	 */
3717 	btrfs_zoned_reserve_data_reloc_bg(fs_info);
3718 
3719 	ret = btrfs_read_qgroup_config(fs_info);
3720 	if (ret)
3721 		goto fail_trans_kthread;
3722 
3723 	if (btrfs_build_ref_tree(fs_info))
3724 		btrfs_err(fs_info, "couldn't build ref tree");
3725 
3726 	/* do not make disk changes in broken FS or nologreplay is given */
3727 	if (btrfs_super_log_root(disk_super) != 0 &&
3728 	    !btrfs_test_opt(fs_info, NOLOGREPLAY)) {
3729 		btrfs_info(fs_info, "start tree-log replay");
3730 		ret = btrfs_replay_log(fs_info, fs_devices);
3731 		if (ret)
3732 			goto fail_qgroup;
3733 	}
3734 
3735 	fs_info->fs_root = btrfs_get_fs_root(fs_info, BTRFS_FS_TREE_OBJECTID, true);
3736 	if (IS_ERR(fs_info->fs_root)) {
3737 		ret = PTR_ERR(fs_info->fs_root);
3738 		btrfs_err(fs_info, "failed to read fs tree: %pe", ERR_PTR(ret));
3739 		fs_info->fs_root = NULL;
3740 		goto fail_qgroup;
3741 	}
3742 
3743 	if (sb_rdonly(sb))
3744 		return 0;
3745 
3746 	ret = btrfs_start_pre_rw_mount(fs_info);
3747 	if (ret) {
3748 		close_ctree(fs_info);
3749 		return ret;
3750 	}
3751 	btrfs_discard_resume(fs_info);
3752 
3753 	if (fs_info->uuid_root &&
3754 	    (btrfs_test_opt(fs_info, RESCAN_UUID_TREE) ||
3755 	     !test_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags))) {
3756 		btrfs_info(fs_info, "checking UUID tree");
3757 		ret = btrfs_check_uuid_tree(fs_info);
3758 		if (ret) {
3759 			btrfs_err(fs_info, "failed to check the UUID tree: %pe", ERR_PTR(ret));
3760 			close_ctree(fs_info);
3761 			return ret;
3762 		}
3763 	}
3764 
3765 	set_bit(BTRFS_FS_OPEN, &fs_info->flags);
3766 
3767 	/* Kick the cleaner thread so it'll start deleting snapshots. */
3768 	if (test_bit(BTRFS_FS_UNFINISHED_DROPS, &fs_info->flags))
3769 		wake_up_process(fs_info->cleaner_kthread);
3770 
3771 	return 0;
3772 
3773 fail_qgroup:
3774 	btrfs_free_qgroup_config(fs_info);
3775 fail_trans_kthread:
3776 	kthread_stop(fs_info->transaction_kthread);
3777 	btrfs_cleanup_transaction(fs_info);
3778 	btrfs_free_fs_roots(fs_info);
3779 fail_cleaner:
3780 	kthread_stop(fs_info->cleaner_kthread);
3781 
3782 	/*
3783 	 * make sure we're done with the btree inode before we stop our
3784 	 * kthreads
3785 	 */
3786 	filemap_write_and_wait(fs_info->btree_inode->i_mapping);
3787 
3788 fail_sysfs:
3789 	btrfs_sysfs_remove_mounted(fs_info);
3790 
3791 fail_fsdev_sysfs:
3792 	btrfs_sysfs_remove_fsid(fs_info->fs_devices);
3793 
3794 fail_block_groups:
3795 	btrfs_put_block_group_cache(fs_info);
3796 
3797 fail_tree_roots:
3798 	if (fs_info->data_reloc_root)
3799 		btrfs_drop_and_free_fs_root(fs_info, fs_info->data_reloc_root);
3800 	free_root_pointers(fs_info, true);
3801 	invalidate_and_check_btree_folios(fs_info);
3802 
3803 fail_sb_buffer:
3804 	btrfs_stop_all_workers(fs_info);
3805 	btrfs_free_block_groups(fs_info);
3806 fail_alloc:
3807 	btrfs_mapping_tree_free(fs_info);
3808 
3809 	iput(fs_info->btree_inode);
3810 fail:
3811 	ASSERT(ret < 0);
3812 	return ret;
3813 }
3814 ALLOW_ERROR_INJECTION(open_ctree, ERRNO);
3815 
3816 static void btrfs_end_super_write(struct bio *bio)
3817 {
3818 	struct btrfs_device *device = bio->bi_private;
3819 	struct folio_iter fi;
3820 
3821 	bio_for_each_folio_all(fi, bio) {
3822 		if (bio->bi_status) {
3823 			btrfs_warn_rl(device->fs_info,
3824 				"lost super block write due to IO error on %s (%d)",
3825 				btrfs_dev_name(device),
3826 				blk_status_to_errno(bio->bi_status));
3827 			btrfs_dev_stat_inc_and_print(device,
3828 						     BTRFS_DEV_STAT_WRITE_ERRS);
3829 			/* Ensure failure if the primary sb fails. */
3830 			if (bio->bi_opf & REQ_FUA)
3831 				atomic_add(BTRFS_SUPER_PRIMARY_WRITE_ERROR,
3832 					   &device->sb_write_errors);
3833 			else
3834 				atomic_inc(&device->sb_write_errors);
3835 		}
3836 		folio_unlock(fi.folio);
3837 		folio_put(fi.folio);
3838 	}
3839 
3840 	bio_put(bio);
3841 }
3842 
3843 /*
3844  * Write superblock @sb to the @device. Do not wait for completion, all the
3845  * folios we use for writing are locked.
3846  *
3847  * Write @max_mirrors copies of the superblock. Note that max_mirrors must be
3848  * same for write and wait phases.
3849  *
3850  * Return number of errors when folio is not found or submission fails.
3851  */
3852 static int write_dev_supers(struct btrfs_device *device,
3853 			    struct btrfs_super_block *sb, int max_mirrors)
3854 {
3855 	struct btrfs_fs_info *fs_info = device->fs_info;
3856 	struct address_space *mapping = device->bdev->bd_mapping;
3857 	int i;
3858 	int ret;
3859 	u64 bytenr, bytenr_orig;
3860 
3861 	atomic_set(&device->sb_write_errors, 0);
3862 
3863 	for (i = 0; i < max_mirrors; i++) {
3864 		struct folio *folio;
3865 		struct bio *bio;
3866 		struct btrfs_super_block *disk_super;
3867 		size_t offset;
3868 
3869 		bytenr_orig = btrfs_sb_offset(i);
3870 		ret = btrfs_sb_log_location(device, i, WRITE, &bytenr);
3871 		if (ret == -ENOENT) {
3872 			continue;
3873 		} else if (ret < 0) {
3874 			btrfs_err(device->fs_info,
3875 			  "couldn't get super block location for mirror %d error %pe",
3876 			  i, ERR_PTR(ret));
3877 			atomic_inc(&device->sb_write_errors);
3878 			continue;
3879 		}
3880 		if (bytenr + BTRFS_SUPER_INFO_SIZE > device->commit_total_bytes)
3881 			break;
3882 
3883 		btrfs_set_super_bytenr(sb, bytenr_orig);
3884 
3885 		btrfs_csum(fs_info->csum_type, (const u8 *)sb + BTRFS_CSUM_SIZE,
3886 			   BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE, sb->csum);
3887 
3888 		folio = __filemap_get_folio(mapping, bytenr >> PAGE_SHIFT,
3889 					    FGP_LOCK | FGP_ACCESSED | FGP_CREAT,
3890 					    GFP_NOFS);
3891 		if (IS_ERR(folio)) {
3892 			btrfs_err(device->fs_info,
3893 			  "couldn't get super block page for bytenr %llu error %pe",
3894 			  bytenr, folio);
3895 			atomic_inc(&device->sb_write_errors);
3896 			continue;
3897 		}
3898 
3899 		offset = offset_in_folio(folio, bytenr);
3900 		disk_super = folio_address(folio) + offset;
3901 		memcpy(disk_super, sb, BTRFS_SUPER_INFO_SIZE);
3902 
3903 		/*
3904 		 * Directly use bios here instead of relying on the page cache
3905 		 * to do I/O, so we don't lose the ability to do integrity
3906 		 * checking.
3907 		 */
3908 		bio = bio_alloc(device->bdev, 1,
3909 				REQ_OP_WRITE | REQ_SYNC | REQ_META | REQ_PRIO,
3910 				GFP_NOFS);
3911 		bio->bi_iter.bi_sector = bytenr >> SECTOR_SHIFT;
3912 		bio->bi_private = device;
3913 		bio->bi_end_io = btrfs_end_super_write;
3914 		bio_add_folio_nofail(bio, folio, BTRFS_SUPER_INFO_SIZE, offset);
3915 
3916 		/*
3917 		 * We FUA only the first super block.  The others we allow to
3918 		 * go down lazy and there's a short window where the on-disk
3919 		 * copies might still contain the older version.
3920 		 */
3921 		if (i == 0 && !btrfs_test_opt(device->fs_info, NOBARRIER))
3922 			bio->bi_opf |= REQ_FUA;
3923 		submit_bio(bio);
3924 
3925 		if (btrfs_advance_sb_log(device, i))
3926 			atomic_inc(&device->sb_write_errors);
3927 	}
3928 	return atomic_read(&device->sb_write_errors) < i ? 0 : -1;
3929 }
3930 
3931 /*
3932  * Wait for write completion of superblocks done by write_dev_supers,
3933  * @max_mirrors same for write and wait phases.
3934  *
3935  * Return -1 if primary super block write failed or when there were no super block
3936  * copies written. Otherwise 0.
3937  */
3938 static int wait_dev_supers(struct btrfs_device *device, int max_mirrors)
3939 {
3940 	int i;
3941 	int errors = 0;
3942 	bool primary_failed = false;
3943 	int ret;
3944 	u64 bytenr;
3945 
3946 	for (i = 0; i < max_mirrors; i++) {
3947 		struct folio *folio;
3948 
3949 		ret = btrfs_sb_log_location(device, i, READ, &bytenr);
3950 		if (ret == -ENOENT) {
3951 			break;
3952 		} else if (unlikely(ret < 0)) {
3953 			errors++;
3954 			if (i == 0)
3955 				primary_failed = true;
3956 			continue;
3957 		}
3958 		if (bytenr + BTRFS_SUPER_INFO_SIZE > device->commit_total_bytes)
3959 			break;
3960 
3961 		folio = filemap_get_folio(device->bdev->bd_mapping,
3962 					  bytenr >> PAGE_SHIFT);
3963 		/* If the folio has been removed, then we know it completed. */
3964 		if (IS_ERR(folio))
3965 			continue;
3966 
3967 		/* Folio will be unlocked once the write completes. */
3968 		folio_wait_locked(folio);
3969 		folio_put(folio);
3970 	}
3971 
3972 	errors += atomic_read(&device->sb_write_errors);
3973 
3974 	if (unlikely(primary_failed || errors >= BTRFS_SUPER_PRIMARY_WRITE_ERROR)) {
3975 		btrfs_err(device->fs_info, "error writing primary super block to device %llu",
3976 			  device->devid);
3977 		return -1;
3978 	}
3979 
3980 	return errors < i ? 0 : -1;
3981 }
3982 
3983 /*
3984  * endio for the write_dev_flush, this will wake anyone waiting
3985  * for the barrier when it is done
3986  */
3987 static void btrfs_end_empty_barrier(struct bio *bio)
3988 {
3989 	bio_uninit(bio);
3990 	complete(bio->bi_private);
3991 }
3992 
3993 /*
3994  * Submit a flush request to the device if it supports it. Error handling is
3995  * done in the waiting counterpart.
3996  */
3997 static void write_dev_flush(struct btrfs_device *device)
3998 {
3999 	struct bio *bio = &device->flush_bio;
4000 
4001 	clear_bit(BTRFS_DEV_STATE_FLUSH_FAILED, &device->dev_state);
4002 
4003 	bio_init(bio, device->bdev, NULL, 0,
4004 		 REQ_OP_WRITE | REQ_SYNC | REQ_PREFLUSH);
4005 	bio->bi_end_io = btrfs_end_empty_barrier;
4006 	init_completion(&device->flush_wait);
4007 	bio->bi_private = &device->flush_wait;
4008 	submit_bio(bio);
4009 	set_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state);
4010 }
4011 
4012 /*
4013  * If the flush bio has been submitted by write_dev_flush, wait for it.
4014  * Return true for any error, and false otherwise.
4015  */
4016 static bool wait_dev_flush(struct btrfs_device *device)
4017 {
4018 	struct bio *bio = &device->flush_bio;
4019 
4020 	if (!test_and_clear_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state))
4021 		return false;
4022 
4023 	wait_for_completion_io(&device->flush_wait);
4024 
4025 	if (unlikely(bio->bi_status)) {
4026 		set_bit(BTRFS_DEV_STATE_FLUSH_FAILED, &device->dev_state);
4027 		btrfs_dev_stat_inc_and_print(device, BTRFS_DEV_STAT_FLUSH_ERRS);
4028 		return true;
4029 	}
4030 
4031 	return false;
4032 }
4033 
4034 /*
4035  * send an empty flush down to each device in parallel,
4036  * then wait for them
4037  */
4038 static int barrier_all_devices(struct btrfs_fs_info *info)
4039 {
4040 	struct list_head *head;
4041 	struct btrfs_device *dev;
4042 	int errors_wait = 0;
4043 
4044 	lockdep_assert_held(&info->fs_devices->device_list_mutex);
4045 	/* send down all the barriers */
4046 	head = &info->fs_devices->devices;
4047 	list_for_each_entry(dev, head, dev_list) {
4048 		if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
4049 			continue;
4050 		if (!dev->bdev)
4051 			continue;
4052 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
4053 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
4054 			continue;
4055 
4056 		write_dev_flush(dev);
4057 	}
4058 
4059 	/* wait for all the barriers */
4060 	list_for_each_entry(dev, head, dev_list) {
4061 		if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
4062 			continue;
4063 		if (unlikely(!dev->bdev)) {
4064 			errors_wait++;
4065 			continue;
4066 		}
4067 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
4068 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
4069 			continue;
4070 
4071 		if (unlikely(wait_dev_flush(dev)))
4072 			errors_wait++;
4073 	}
4074 
4075 	/*
4076 	 * Checks flush failure of disks in order to determine the device
4077 	 * state.
4078 	 */
4079 	if (unlikely(errors_wait && !btrfs_check_rw_degradable(info, NULL)))
4080 		return -EIO;
4081 
4082 	return 0;
4083 }
4084 
4085 int btrfs_get_num_tolerated_disk_barrier_failures(u64 flags)
4086 {
4087 	int raid_type;
4088 	int min_tolerated = INT_MAX;
4089 
4090 	if ((flags & BTRFS_BLOCK_GROUP_PROFILE_MASK) == 0 ||
4091 	    (flags & BTRFS_AVAIL_ALLOC_BIT_SINGLE))
4092 		min_tolerated = min_t(int, min_tolerated,
4093 				    btrfs_raid_array[BTRFS_RAID_SINGLE].
4094 				    tolerated_failures);
4095 
4096 	for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) {
4097 		if (raid_type == BTRFS_RAID_SINGLE)
4098 			continue;
4099 		if (!(flags & btrfs_raid_array[raid_type].bg_flag))
4100 			continue;
4101 		min_tolerated = min_t(int, min_tolerated,
4102 				    btrfs_raid_array[raid_type].
4103 				    tolerated_failures);
4104 	}
4105 
4106 	if (min_tolerated == INT_MAX) {
4107 		btrfs_warn(NULL, "unknown raid flag: %llu", flags);
4108 		min_tolerated = 0;
4109 	}
4110 
4111 	return min_tolerated;
4112 }
4113 
4114 int write_all_supers(struct btrfs_trans_handle *trans)
4115 {
4116 	struct btrfs_fs_info *fs_info = trans->fs_info;
4117 	struct list_head *head;
4118 	struct btrfs_device *dev;
4119 	struct btrfs_super_block *sb;
4120 	struct btrfs_dev_item *dev_item;
4121 	int max_mirrors;
4122 	int ret;
4123 	int do_barriers;
4124 	int max_errors;
4125 	int total_errors = 0;
4126 
4127 	do_barriers = !btrfs_test_opt(fs_info, NOBARRIER);
4128 
4129 	if (trans->transaction->state < TRANS_STATE_UNBLOCKED) {
4130 		/* We are called from fsync. */
4131 		max_mirrors = 1;
4132 	} else {
4133 		/* We are called from transaction commit. */
4134 		max_mirrors = BTRFS_SUPER_MIRROR_MAX;
4135 		ret = backup_super_roots(fs_info);
4136 		if (ret < 0)
4137 			return ret;
4138 	}
4139 
4140 	sb = fs_info->super_for_commit;
4141 	dev_item = &sb->dev_item;
4142 
4143 	mutex_lock(&fs_info->fs_devices->device_list_mutex);
4144 	head = &fs_info->fs_devices->devices;
4145 	max_errors = btrfs_super_num_devices(fs_info->super_copy) - 1;
4146 
4147 	if (do_barriers) {
4148 		ret = barrier_all_devices(fs_info);
4149 		if (unlikely(ret)) {
4150 			mutex_unlock(
4151 				&fs_info->fs_devices->device_list_mutex);
4152 			btrfs_abort_transaction(trans, ret);
4153 			btrfs_err(fs_info, "error while submitting device barriers");
4154 			return ret;
4155 		}
4156 	}
4157 
4158 	btrfs_set_super_flags(sb, btrfs_super_flags(sb) | BTRFS_HEADER_FLAG_WRITTEN);
4159 
4160 	list_for_each_entry(dev, head, dev_list) {
4161 		if (unlikely(!dev->bdev)) {
4162 			total_errors++;
4163 			continue;
4164 		}
4165 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
4166 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
4167 			continue;
4168 
4169 		btrfs_set_stack_device_generation(dev_item, 0);
4170 		btrfs_set_stack_device_type(dev_item, dev->type);
4171 		btrfs_set_stack_device_id(dev_item, dev->devid);
4172 		btrfs_set_stack_device_total_bytes(dev_item,
4173 						   dev->commit_total_bytes);
4174 		btrfs_set_stack_device_bytes_used(dev_item,
4175 						  dev->commit_bytes_used);
4176 		btrfs_set_stack_device_io_align(dev_item, dev->io_align);
4177 		btrfs_set_stack_device_io_width(dev_item, dev->io_width);
4178 		btrfs_set_stack_device_sector_size(dev_item, dev->sector_size);
4179 		memcpy(dev_item->uuid, dev->uuid, BTRFS_UUID_SIZE);
4180 		memcpy(dev_item->fsid, dev->fs_devices->metadata_uuid,
4181 		       BTRFS_FSID_SIZE);
4182 
4183 		ret = btrfs_validate_write_super(fs_info, sb);
4184 		if (unlikely(ret < 0)) {
4185 			mutex_unlock(&fs_info->fs_devices->device_list_mutex);
4186 			btrfs_abort_transaction(trans, ret);
4187 			btrfs_err(fs_info,
4188 			  "unexpected superblock corruption before writing it");
4189 			return ret;
4190 		}
4191 
4192 		ret = write_dev_supers(dev, sb, max_mirrors);
4193 		if (unlikely(ret))
4194 			total_errors++;
4195 	}
4196 	if (unlikely(total_errors > max_errors)) {
4197 		mutex_unlock(&fs_info->fs_devices->device_list_mutex);
4198 
4199 		/* FUA is masked off if unsupported and can't be the reason */
4200 		btrfs_abort_transaction(trans, -EIO);
4201 		btrfs_err(fs_info, "%d errors while writing supers", total_errors);
4202 		return -EIO;
4203 	}
4204 
4205 	total_errors = 0;
4206 	list_for_each_entry(dev, head, dev_list) {
4207 		if (unlikely(!dev->bdev))
4208 			continue;
4209 		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
4210 		    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
4211 			continue;
4212 
4213 		ret = wait_dev_supers(dev, max_mirrors);
4214 		if (unlikely(ret))
4215 			total_errors++;
4216 	}
4217 	mutex_unlock(&fs_info->fs_devices->device_list_mutex);
4218 	if (unlikely(total_errors > max_errors)) {
4219 		btrfs_abort_transaction(trans, -EIO);
4220 		btrfs_err(fs_info, "%d errors while writing supers", total_errors);
4221 		return -EIO;
4222 	}
4223 	return 0;
4224 }
4225 
4226 /* Drop a fs root from the radix tree and free it. */
4227 void btrfs_drop_and_free_fs_root(struct btrfs_fs_info *fs_info,
4228 				  struct btrfs_root *root)
4229 {
4230 	bool drop_ref = false;
4231 
4232 	spin_lock(&fs_info->fs_roots_radix_lock);
4233 	radix_tree_delete(&fs_info->fs_roots_radix,
4234 			  (unsigned long)btrfs_root_id(root));
4235 	if (test_and_clear_bit(BTRFS_ROOT_IN_RADIX, &root->state))
4236 		drop_ref = true;
4237 	spin_unlock(&fs_info->fs_roots_radix_lock);
4238 
4239 	if (unlikely(BTRFS_FS_ERROR(fs_info))) {
4240 		ASSERT(root->log_root == NULL);
4241 		if (root->reloc_root) {
4242 			btrfs_put_root(root->reloc_root);
4243 			root->reloc_root = NULL;
4244 		}
4245 	}
4246 
4247 	if (drop_ref)
4248 		btrfs_put_root(root);
4249 }
4250 
4251 int btrfs_commit_super(struct btrfs_fs_info *fs_info)
4252 {
4253 	mutex_lock(&fs_info->cleaner_mutex);
4254 	btrfs_run_delayed_iputs(fs_info);
4255 	mutex_unlock(&fs_info->cleaner_mutex);
4256 	wake_up_process(fs_info->cleaner_kthread);
4257 
4258 	/* wait until ongoing cleanup work done */
4259 	down_write(&fs_info->cleanup_work_sem);
4260 	up_write(&fs_info->cleanup_work_sem);
4261 
4262 	return btrfs_commit_current_transaction(fs_info->tree_root);
4263 }
4264 
4265 static void warn_about_uncommitted_trans(struct btrfs_fs_info *fs_info)
4266 {
4267 	struct btrfs_transaction *trans;
4268 	struct btrfs_transaction *tmp;
4269 	bool found = false;
4270 
4271 	/*
4272 	 * This function is only called at the very end of close_ctree(),
4273 	 * thus no other running transaction, no need to take trans_lock.
4274 	 */
4275 	ASSERT(test_bit(BTRFS_FS_CLOSING_DONE, &fs_info->flags));
4276 	list_for_each_entry_safe(trans, tmp, &fs_info->trans_list, list) {
4277 		struct extent_state *cached = NULL;
4278 		u64 dirty_bytes = 0;
4279 		u64 cur = 0;
4280 		u64 found_start;
4281 		u64 found_end;
4282 
4283 		found = true;
4284 		while (btrfs_find_first_extent_bit(&trans->dirty_pages, cur,
4285 						   &found_start, &found_end,
4286 						   EXTENT_DIRTY, &cached)) {
4287 			dirty_bytes += found_end + 1 - found_start;
4288 			cur = found_end + 1;
4289 		}
4290 		btrfs_warn(fs_info,
4291 	"transaction %llu (with %llu dirty metadata bytes) is not committed",
4292 			   trans->transid, dirty_bytes);
4293 		btrfs_cleanup_one_transaction(trans);
4294 
4295 		if (trans == fs_info->running_transaction)
4296 			fs_info->running_transaction = NULL;
4297 		list_del_init(&trans->list);
4298 
4299 		btrfs_put_transaction(trans);
4300 	}
4301 	ASSERT(!found);
4302 }
4303 
4304 void __cold close_ctree(struct btrfs_fs_info *fs_info)
4305 {
4306 	int ret;
4307 
4308 	set_bit(BTRFS_FS_CLOSING_START, &fs_info->flags);
4309 
4310 	/*
4311 	 * If we had UNFINISHED_DROPS we could still be processing them, so
4312 	 * clear that bit and wake up relocation so it can stop.
4313 	 * We must do this before stopping the block group reclaim task, because
4314 	 * at btrfs_relocate_block_group() we wait for this bit, and after the
4315 	 * wait we stop with -EINTR if btrfs_fs_closing() returns non-zero - we
4316 	 * have just set BTRFS_FS_CLOSING_START, so btrfs_fs_closing() will
4317 	 * return 1.
4318 	 */
4319 	btrfs_wake_unfinished_drop(fs_info);
4320 
4321 	/*
4322 	 * We may have the reclaim task running and relocating a data block group,
4323 	 * in which case it may create delayed iputs. So stop it before we park
4324 	 * the cleaner kthread otherwise we can get new delayed iputs after
4325 	 * parking the cleaner, and that can make the async reclaim task to hang
4326 	 * if it's waiting for delayed iputs to complete, since the cleaner is
4327 	 * parked and can not run delayed iputs - this will make us hang when
4328 	 * trying to stop the async reclaim task.
4329 	 */
4330 	cancel_work_sync(&fs_info->reclaim_bgs_work);
4331 	/*
4332 	 * We don't want the cleaner to start new transactions, add more delayed
4333 	 * iputs, etc. while we're closing. We can't use kthread_stop() yet
4334 	 * because that frees the task_struct, and the transaction kthread might
4335 	 * still try to wake up the cleaner.
4336 	 */
4337 	kthread_park(fs_info->cleaner_kthread);
4338 
4339 	/* wait for the qgroup rescan worker to stop */
4340 	btrfs_qgroup_wait_for_completion(fs_info, false);
4341 
4342 	/* wait for the uuid_scan task to finish */
4343 	down(&fs_info->uuid_tree_rescan_sem);
4344 	/* avoid complains from lockdep et al., set sem back to initial state */
4345 	up(&fs_info->uuid_tree_rescan_sem);
4346 
4347 	/* pause restriper - we want to resume on mount */
4348 	btrfs_pause_balance(fs_info);
4349 
4350 	btrfs_dev_replace_suspend_for_unmount(fs_info);
4351 
4352 	btrfs_scrub_cancel(fs_info);
4353 
4354 	/* wait for any defraggers to finish */
4355 	wait_event(fs_info->transaction_wait,
4356 		   (atomic_read(&fs_info->defrag_running) == 0));
4357 
4358 	/* clear out the rbtree of defraggable inodes */
4359 	btrfs_cleanup_defrag_inodes(fs_info);
4360 
4361 	/*
4362 	 * Before the unmount, we sync down all the writeback which can
4363 	 * generate fixup work. We are about to run delalloc for autodefrag so
4364 	 * piggy back on that by also flushing the fixup work which can also
4365 	 * generate delalloc we would like to get run.
4366 	 *
4367 	 * After this, it is still possible that some thread doing writeback is
4368 	 * in btrfs_queue_writepage_fixup() and might finish queueing some final
4369 	 * work, racing the btrfs_fs_closing() check there.
4370 	 */
4371 	flush_workqueue(fs_info->fixup_workers);
4372 
4373 	/*
4374 	 * After we entered close_ctree() autodefrag could be running and before
4375 	 * we parked the cleaner kthread, it dirtied folios of some inode.
4376 	 * We don't want to leave any delalloc here, it may be flushed any time
4377 	 * after this point and result in ordered extents that create delayed
4378 	 * iputs after flushed the ordered extent queues further below, run
4379 	 * delayed iputs and set BTRFS_FS_STATE_NO_DELAYED_IPUT. If we are
4380 	 * mounted with flushoncommit, then btrfs_commit_super() called below
4381 	 * will flush delalloc and wait for ordered extents but we end up
4382 	 * getting delayed iputs than are never run. So flush delalloc and wait
4383 	 * for ordered extents.
4384 	 */
4385 	btrfs_start_delalloc_roots(fs_info, LONG_MAX, false);
4386 	btrfs_wait_ordered_roots(fs_info, U64_MAX, NULL);
4387 
4388 	/*
4389 	 * Handle the error fs first, as it will flush and wait for all ordered
4390 	 * extents.  This will generate delayed iputs, thus we want to handle
4391 	 * it first.
4392 	 */
4393 	if (unlikely(BTRFS_FS_ERROR(fs_info)))
4394 		btrfs_error_commit_super(fs_info);
4395 
4396 	/*
4397 	 * Similar case here, we have to wait for delalloc workers before we
4398 	 * proceed below and stop the cleaner kthread, otherwise we trigger a
4399 	 * use-after-tree on the cleaner kthread task_struct when a delalloc
4400 	 * worker running submit_compressed_extents() adds a delayed iput, which
4401 	 * does a wake up on the cleaner kthread, which was already freed below
4402 	 * when we call kthread_stop().
4403 	 */
4404 	btrfs_flush_workqueue(fs_info->delalloc_workers);
4405 
4406 	/*
4407 	 * We can have ordered extents getting their last reference dropped from
4408 	 * the fs_info->workers queue because for async writes for data bios we
4409 	 * queue a work for that queue, at btrfs_wq_submit_bio(), that runs
4410 	 * run_one_async_done() which calls btrfs_bio_end_io() in case the bio
4411 	 * has an error, and that later function can do the final
4412 	 * btrfs_put_ordered_extent() on the ordered extent attached to the bio,
4413 	 * which adds a delayed iput for the inode. So we must flush the queue
4414 	 * so that we don't have delayed iputs after committing the current
4415 	 * transaction below and stopping the cleaner and transaction kthreads.
4416 	 */
4417 	btrfs_flush_workqueue(fs_info->workers);
4418 
4419 	/*
4420 	 * When finishing a compressed write bio we schedule a work queue item
4421 	 * to finish an ordered extent - end_bbio_compressed_write()
4422 	 * calls btrfs_finish_ordered_extent() which in turns does a call to
4423 	 * btrfs_queue_ordered_fn(), and that queues the ordered extent
4424 	 * completion in the endio_write_workers work queue. We flush that
4425 	 * queue below, so before we flush it we must flush this queue for the
4426 	 * workers of compressed writes.
4427 	 */
4428 	flush_workqueue(fs_info->endio_workers);
4429 
4430 	/*
4431 	 * After we parked the cleaner kthread, ordered extents may have
4432 	 * completed and created new delayed iputs. If one of the async reclaim
4433 	 * tasks is running and in the RUN_DELAYED_IPUTS flush state, then we
4434 	 * can hang forever trying to stop it, because if a delayed iput is
4435 	 * added after it ran btrfs_run_delayed_iputs() and before it called
4436 	 * btrfs_wait_on_delayed_iputs(), it will hang forever since there is
4437 	 * no one else to run iputs.
4438 	 *
4439 	 * So wait for all ongoing ordered extents to complete and then run
4440 	 * delayed iputs. This works because once we reach this point no one
4441 	 * can create new ordered extents, but delayed iputs can still be added
4442 	 * by a reclaim worker (see comments further below).
4443 	 *
4444 	 * Also note that btrfs_wait_ordered_roots() is not safe here, because
4445 	 * it waits for BTRFS_ORDERED_COMPLETE to be set on an ordered extent,
4446 	 * but the delayed iput for the respective inode is made only when doing
4447 	 * the final btrfs_put_ordered_extent() (which must happen at
4448 	 * btrfs_finish_ordered_io() when we are unmounting).
4449 	 */
4450 	btrfs_flush_workqueue(fs_info->endio_write_workers);
4451 	/*
4452 	 * Run delayed iputs in case an async reclaim worker is waiting for them
4453 	 * to be run as mentioned above.
4454 	 */
4455 	btrfs_run_delayed_iputs(fs_info);
4456 
4457 	cancel_work_sync(&fs_info->async_reclaim_work);
4458 	cancel_work_sync(&fs_info->async_data_reclaim_work);
4459 	cancel_work_sync(&fs_info->preempt_reclaim_work);
4460 	cancel_work_sync(&fs_info->em_shrinker_work);
4461 
4462 	/*
4463 	 * Reclaim workers can run writeback which can queue fixup.
4464 	 * After the above cancel_work_sync() calls, any such queueing attempts are
4465 	 * guaranteed to see btrfs_fs_closing(), so at this point we can genuinely fully
4466 	 * flush the fixup workqueue. This relies on the belief that *now* no thread can
4467 	 * still be sitting in btrfs_queue_writepage_fixup().
4468 	 */
4469 	flush_workqueue(fs_info->fixup_workers);
4470 
4471 	/*
4472 	 * Run delayed iputs again because an async reclaim worker may have
4473 	 * added new ones if it was flushing delalloc:
4474 	 *
4475 	 * shrink_delalloc() -> btrfs_start_delalloc_roots() ->
4476 	 *    start_delalloc_inodes() -> btrfs_add_delayed_iput()
4477 	 */
4478 	btrfs_run_delayed_iputs(fs_info);
4479 
4480 	/* There should be no more workload to generate new delayed iputs. */
4481 	set_bit(BTRFS_FS_STATE_NO_DELAYED_IPUT, &fs_info->fs_state);
4482 
4483 	/* Cancel or finish ongoing discard work */
4484 	btrfs_discard_cleanup(fs_info);
4485 
4486 	if (!sb_rdonly(fs_info->sb)) {
4487 		/*
4488 		 * The cleaner kthread is stopped, so do one final pass over
4489 		 * unused block groups.
4490 		 */
4491 		btrfs_delete_unused_bgs(fs_info);
4492 
4493 		/*
4494 		 * There might be existing delayed inode workers still running
4495 		 * and holding an empty delayed inode item. We must wait for
4496 		 * them to complete first because they can create a transaction.
4497 		 * This happens when someone calls btrfs_balance_delayed_items()
4498 		 * and then a transaction commit runs the same delayed nodes
4499 		 * before any delayed worker has done something with the nodes.
4500 		 * We must wait for any worker here and not at transaction
4501 		 * commit time since that could cause a deadlock.
4502 		 * This is a very rare case.
4503 		 */
4504 		btrfs_flush_workqueue(fs_info->delayed_workers);
4505 
4506 		/*
4507 		 * If the filesystem is shutdown, then an attempt to commit the
4508 		 * super block (or any write) will just fail. Since we freeze
4509 		 * the filesystem before shutting it down, the filesystem is in
4510 		 * a consistent state and we don't need to commit super blocks.
4511 		 */
4512 		if (!btrfs_is_shutdown(fs_info)) {
4513 			ret = btrfs_commit_super(fs_info);
4514 			if (ret)
4515 				btrfs_err(fs_info, "commit super block returned %pe", ERR_PTR(ret));
4516 		}
4517 	}
4518 
4519 	kthread_stop(fs_info->transaction_kthread);
4520 	kthread_stop(fs_info->cleaner_kthread);
4521 
4522 	ASSERT(list_empty(&fs_info->delayed_iputs));
4523 	set_bit(BTRFS_FS_CLOSING_DONE, &fs_info->flags);
4524 
4525 	if (unlikely(btrfs_check_quota_leak(fs_info))) {
4526 		DEBUG_WARN("qgroup reserved space leaked");
4527 		btrfs_err(fs_info, "qgroup reserved space leaked");
4528 	}
4529 
4530 	btrfs_free_qgroup_config(fs_info);
4531 	ASSERT(list_empty(&fs_info->delalloc_roots));
4532 
4533 	if (percpu_counter_sum(&fs_info->delalloc_bytes)) {
4534 		btrfs_info(fs_info, "at unmount delalloc count %lld",
4535 		       percpu_counter_sum(&fs_info->delalloc_bytes));
4536 	}
4537 
4538 	if (percpu_counter_sum(&fs_info->ordered_bytes))
4539 		btrfs_info(fs_info, "at unmount dio bytes count %lld",
4540 			   percpu_counter_sum(&fs_info->ordered_bytes));
4541 
4542 	btrfs_sysfs_remove_mounted(fs_info);
4543 	btrfs_sysfs_remove_fsid(fs_info->fs_devices);
4544 
4545 	btrfs_put_block_group_cache(fs_info);
4546 
4547 	/* We shouldn't have any transaction open at this point */
4548 	warn_about_uncommitted_trans(fs_info);
4549 
4550 	clear_bit(BTRFS_FS_OPEN, &fs_info->flags);
4551 	free_root_pointers(fs_info, true);
4552 	btrfs_free_fs_roots(fs_info);
4553 
4554 	/*
4555 	 * Drop metadata left stranded ahead of a zone write pointer while the
4556 	 * endio workqueues are still up, so the final iput() of the btree inode
4557 	 * below does not hang submitting a write that can no longer complete.
4558 	 */
4559 	btrfs_zoned_release_dirty_metadata(fs_info);
4560 
4561 	/*
4562 	 * We must make sure there is not any read request to
4563 	 * submit after we stop all workers.
4564 	 */
4565 	invalidate_and_check_btree_folios(fs_info);
4566 	btrfs_stop_all_workers(fs_info);
4567 
4568 	/*
4569 	 * We must free the block groups after dropping the fs_roots as we could
4570 	 * have had an IO error and have left over tree log blocks that aren't
4571 	 * cleaned up until the fs roots are freed.  This makes the block group
4572 	 * accounting appear to be wrong because there's pending reserved bytes,
4573 	 * so make sure we do the block group cleanup afterwards.
4574 	 */
4575 	btrfs_free_block_groups(fs_info);
4576 
4577 	iput(fs_info->btree_inode);
4578 
4579 	btrfs_mapping_tree_free(fs_info);
4580 }
4581 
4582 void btrfs_mark_buffer_dirty(struct btrfs_trans_handle *trans,
4583 			     struct extent_buffer *buf)
4584 {
4585 	struct btrfs_fs_info *fs_info = buf->fs_info;
4586 	u64 transid = btrfs_header_generation(buf);
4587 
4588 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
4589 	/*
4590 	 * This is a fast path so only do this check if we have sanity tests
4591 	 * enabled.  Normal people shouldn't be using unmapped buffers as dirty
4592 	 * outside of the sanity tests.
4593 	 */
4594 	if (unlikely(test_bit(EXTENT_BUFFER_UNMAPPED, &buf->bflags)))
4595 		return;
4596 #endif
4597 	/* This is an active transaction (its state < TRANS_STATE_UNBLOCKED). */
4598 	ASSERT(trans->transid == fs_info->generation);
4599 	btrfs_assert_tree_write_locked(buf);
4600 	if (unlikely(transid != fs_info->generation)) {
4601 		btrfs_abort_transaction(trans, -EUCLEAN);
4602 		btrfs_crit(fs_info,
4603 "dirty buffer transid mismatch, logical %llu found transid %llu running transid %llu",
4604 			   buf->start, transid, fs_info->generation);
4605 	}
4606 	set_extent_buffer_dirty(buf);
4607 }
4608 
4609 static void __btrfs_btree_balance_dirty(struct btrfs_fs_info *fs_info,
4610 					int flush_delayed)
4611 {
4612 	/*
4613 	 * looks as though older kernels can get into trouble with
4614 	 * this code, they end up stuck in balance_dirty_pages forever
4615 	 */
4616 	int ret;
4617 
4618 	if (current->flags & PF_MEMALLOC)
4619 		return;
4620 
4621 	if (flush_delayed)
4622 		btrfs_balance_delayed_items(fs_info);
4623 
4624 	ret = __percpu_counter_compare(&fs_info->dirty_metadata_bytes,
4625 				     BTRFS_DIRTY_METADATA_THRESH,
4626 				     fs_info->dirty_metadata_batch);
4627 	if (ret > 0) {
4628 		balance_dirty_pages_ratelimited(fs_info->btree_inode->i_mapping);
4629 	}
4630 }
4631 
4632 void btrfs_btree_balance_dirty(struct btrfs_fs_info *fs_info)
4633 {
4634 	__btrfs_btree_balance_dirty(fs_info, 1);
4635 }
4636 
4637 void btrfs_btree_balance_dirty_nodelay(struct btrfs_fs_info *fs_info)
4638 {
4639 	__btrfs_btree_balance_dirty(fs_info, 0);
4640 }
4641 
4642 static void btrfs_error_commit_super(struct btrfs_fs_info *fs_info)
4643 {
4644 	/* cleanup FS via transaction */
4645 	btrfs_cleanup_transaction(fs_info);
4646 
4647 	down_write(&fs_info->cleanup_work_sem);
4648 	up_write(&fs_info->cleanup_work_sem);
4649 }
4650 
4651 static void btrfs_drop_all_logs(struct btrfs_fs_info *fs_info)
4652 {
4653 	struct btrfs_root *gang[8];
4654 	u64 root_objectid = 0;
4655 	int ret;
4656 
4657 	spin_lock(&fs_info->fs_roots_radix_lock);
4658 	while ((ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
4659 					     (void **)gang, root_objectid,
4660 					     ARRAY_SIZE(gang))) != 0) {
4661 		int i;
4662 
4663 		for (i = 0; i < ret; i++)
4664 			gang[i] = btrfs_grab_root(gang[i]);
4665 		spin_unlock(&fs_info->fs_roots_radix_lock);
4666 
4667 		for (i = 0; i < ret; i++) {
4668 			if (!gang[i])
4669 				continue;
4670 			root_objectid = btrfs_root_id(gang[i]);
4671 			btrfs_free_log(NULL, gang[i]);
4672 			btrfs_put_root(gang[i]);
4673 		}
4674 		root_objectid++;
4675 		spin_lock(&fs_info->fs_roots_radix_lock);
4676 	}
4677 	spin_unlock(&fs_info->fs_roots_radix_lock);
4678 	btrfs_free_log_root_tree(NULL, fs_info);
4679 }
4680 
4681 static void btrfs_destroy_ordered_extents(struct btrfs_root *root)
4682 {
4683 	struct btrfs_ordered_extent *ordered;
4684 
4685 	spin_lock(&root->ordered_extent_lock);
4686 	/*
4687 	 * This will just short circuit the ordered completion stuff which will
4688 	 * make sure the ordered extent gets properly cleaned up.
4689 	 */
4690 	list_for_each_entry(ordered, &root->ordered_extents,
4691 			    root_extent_list)
4692 		set_bit(BTRFS_ORDERED_IOERR, &ordered->flags);
4693 	spin_unlock(&root->ordered_extent_lock);
4694 }
4695 
4696 static void btrfs_destroy_all_ordered_extents(struct btrfs_fs_info *fs_info)
4697 {
4698 	struct btrfs_root *root;
4699 	LIST_HEAD(splice);
4700 
4701 	spin_lock(&fs_info->ordered_root_lock);
4702 	list_splice_init(&fs_info->ordered_roots, &splice);
4703 	while (!list_empty(&splice)) {
4704 		root = list_first_entry(&splice, struct btrfs_root,
4705 					ordered_root);
4706 		list_move_tail(&root->ordered_root,
4707 			       &fs_info->ordered_roots);
4708 
4709 		spin_unlock(&fs_info->ordered_root_lock);
4710 		btrfs_destroy_ordered_extents(root);
4711 
4712 		cond_resched();
4713 		spin_lock(&fs_info->ordered_root_lock);
4714 	}
4715 	spin_unlock(&fs_info->ordered_root_lock);
4716 
4717 	/*
4718 	 * We need this here because if we've been flipped read-only we won't
4719 	 * get sync() from the umount, so we need to make sure any ordered
4720 	 * extents that haven't had their dirty pages IO start writeout yet
4721 	 * actually get run and error out properly.
4722 	 */
4723 	btrfs_wait_ordered_roots(fs_info, U64_MAX, NULL);
4724 }
4725 
4726 static void btrfs_destroy_delalloc_inodes(struct btrfs_root *root)
4727 {
4728 	struct btrfs_inode *btrfs_inode;
4729 	LIST_HEAD(splice);
4730 
4731 	spin_lock(&root->delalloc_lock);
4732 	list_splice_init(&root->delalloc_inodes, &splice);
4733 
4734 	while (!list_empty(&splice)) {
4735 		struct inode *inode = NULL;
4736 		btrfs_inode = list_first_entry(&splice, struct btrfs_inode,
4737 					       delalloc_inodes);
4738 		btrfs_del_delalloc_inode(btrfs_inode);
4739 		spin_unlock(&root->delalloc_lock);
4740 
4741 		/*
4742 		 * Make sure we get a live inode and that it'll not disappear
4743 		 * meanwhile.
4744 		 */
4745 		inode = igrab(&btrfs_inode->vfs_inode);
4746 		if (inode) {
4747 			unsigned int nofs_flag;
4748 
4749 			nofs_flag = memalloc_nofs_save();
4750 			invalidate_inode_pages2(inode->i_mapping);
4751 			memalloc_nofs_restore(nofs_flag);
4752 			iput(inode);
4753 		}
4754 		spin_lock(&root->delalloc_lock);
4755 	}
4756 	spin_unlock(&root->delalloc_lock);
4757 }
4758 
4759 static void btrfs_destroy_all_delalloc_inodes(struct btrfs_fs_info *fs_info)
4760 {
4761 	struct btrfs_root *root;
4762 	LIST_HEAD(splice);
4763 
4764 	spin_lock(&fs_info->delalloc_root_lock);
4765 	list_splice_init(&fs_info->delalloc_roots, &splice);
4766 	while (!list_empty(&splice)) {
4767 		root = list_first_entry(&splice, struct btrfs_root,
4768 					 delalloc_root);
4769 		root = btrfs_grab_root(root);
4770 		BUG_ON(!root);
4771 		spin_unlock(&fs_info->delalloc_root_lock);
4772 
4773 		btrfs_destroy_delalloc_inodes(root);
4774 		btrfs_put_root(root);
4775 
4776 		spin_lock(&fs_info->delalloc_root_lock);
4777 	}
4778 	spin_unlock(&fs_info->delalloc_root_lock);
4779 }
4780 
4781 static void btrfs_destroy_marked_extents(struct btrfs_fs_info *fs_info,
4782 					 struct extent_io_tree *dirty_pages,
4783 					 int mark)
4784 {
4785 	struct extent_buffer *eb;
4786 	u64 start = 0;
4787 	u64 end;
4788 
4789 	while (btrfs_find_first_extent_bit(dirty_pages, start, &start, &end,
4790 					   mark, NULL)) {
4791 		btrfs_clear_extent_bit(dirty_pages, start, end, mark, NULL);
4792 		while (start <= end) {
4793 			eb = find_extent_buffer(fs_info, start);
4794 			start += fs_info->nodesize;
4795 			if (!eb)
4796 				continue;
4797 
4798 			btrfs_tree_lock(eb);
4799 			wait_on_extent_buffer_writeback(eb);
4800 			btrfs_clear_buffer_dirty(NULL, eb);
4801 			btrfs_tree_unlock(eb);
4802 
4803 			free_extent_buffer_stale(eb);
4804 		}
4805 	}
4806 	btrfs_extent_io_tree_release(dirty_pages);
4807 }
4808 
4809 static void btrfs_destroy_pinned_extent(struct btrfs_fs_info *fs_info,
4810 					struct extent_io_tree *unpin)
4811 {
4812 	u64 start;
4813 	u64 end;
4814 
4815 	while (1) {
4816 		struct extent_state *cached_state = NULL;
4817 
4818 		/*
4819 		 * The btrfs_finish_extent_commit() may get the same range as
4820 		 * ours between find_first_extent_bit and clear_extent_dirty.
4821 		 * Hence, hold the unused_bg_unpin_mutex to avoid double unpin
4822 		 * the same extent range.
4823 		 */
4824 		mutex_lock(&fs_info->unused_bg_unpin_mutex);
4825 		if (!btrfs_find_first_extent_bit(unpin, 0, &start, &end,
4826 						 EXTENT_DIRTY, &cached_state)) {
4827 			mutex_unlock(&fs_info->unused_bg_unpin_mutex);
4828 			break;
4829 		}
4830 
4831 		btrfs_clear_extent_dirty(unpin, start, end, &cached_state);
4832 		btrfs_free_extent_state(cached_state);
4833 		btrfs_error_unpin_extent_range(fs_info, start, end);
4834 		mutex_unlock(&fs_info->unused_bg_unpin_mutex);
4835 		cond_resched();
4836 	}
4837 }
4838 
4839 void btrfs_cleanup_dirty_bgs(struct btrfs_transaction *cur_trans,
4840 			     struct btrfs_fs_info *fs_info)
4841 {
4842 	struct btrfs_block_group *cache;
4843 
4844 	spin_lock(&cur_trans->dirty_bgs_lock);
4845 	while (!list_empty(&cur_trans->dirty_bgs)) {
4846 		cache = list_first_entry(&cur_trans->dirty_bgs,
4847 					 struct btrfs_block_group,
4848 					 dirty_list);
4849 
4850 		list_del_init(&cache->dirty_list);
4851 		spin_unlock(&cur_trans->dirty_bgs_lock);
4852 		btrfs_put_block_group(cache);
4853 		btrfs_dec_delayed_refs_rsv_bg_updates(fs_info);
4854 		spin_lock(&cur_trans->dirty_bgs_lock);
4855 	}
4856 	spin_unlock(&cur_trans->dirty_bgs_lock);
4857 }
4858 
4859 static void btrfs_free_all_qgroup_pertrans(struct btrfs_fs_info *fs_info)
4860 {
4861 	struct btrfs_root *gang[8];
4862 	int i;
4863 	int ret;
4864 
4865 	spin_lock(&fs_info->fs_roots_radix_lock);
4866 	while (1) {
4867 		ret = radix_tree_gang_lookup_tag(&fs_info->fs_roots_radix,
4868 						 (void **)gang, 0,
4869 						 ARRAY_SIZE(gang),
4870 						 BTRFS_ROOT_TRANS_TAG);
4871 		if (ret == 0)
4872 			break;
4873 		for (i = 0; i < ret; i++) {
4874 			struct btrfs_root *root = gang[i];
4875 
4876 			btrfs_qgroup_free_meta_all_pertrans(root);
4877 			radix_tree_tag_clear(&fs_info->fs_roots_radix,
4878 					(unsigned long)btrfs_root_id(root),
4879 					BTRFS_ROOT_TRANS_TAG);
4880 		}
4881 	}
4882 	spin_unlock(&fs_info->fs_roots_radix_lock);
4883 }
4884 
4885 void btrfs_cleanup_one_transaction(struct btrfs_transaction *cur_trans)
4886 {
4887 	struct btrfs_fs_info *fs_info = cur_trans->fs_info;
4888 	struct btrfs_device *dev, *tmp;
4889 
4890 	btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
4891 	ASSERT(list_empty(&cur_trans->dirty_bgs));
4892 
4893 	list_for_each_entry_safe(dev, tmp, &cur_trans->dev_update_list,
4894 				 post_commit_list) {
4895 		list_del_init(&dev->post_commit_list);
4896 	}
4897 
4898 	while (!list_empty(&cur_trans->switch_commits)) {
4899 		struct btrfs_root *root;
4900 
4901 		root = list_first_entry(&cur_trans->switch_commits,
4902 					struct btrfs_root, dirty_list);
4903 		list_del_init(&root->dirty_list);
4904 		btrfs_extent_io_tree_release(&root->dirty_log_pages);
4905 		btrfs_qgroup_clean_swapped_blocks(root);
4906 	}
4907 
4908 	btrfs_destroy_delayed_refs(cur_trans);
4909 
4910 	cur_trans->state = TRANS_STATE_COMMIT_START;
4911 	wake_up(&fs_info->transaction_blocked_wait);
4912 
4913 	cur_trans->state = TRANS_STATE_UNBLOCKED;
4914 	wake_up(&fs_info->transaction_wait);
4915 
4916 	btrfs_destroy_marked_extents(fs_info, &cur_trans->dirty_pages,
4917 				     EXTENT_DIRTY);
4918 	btrfs_destroy_pinned_extent(fs_info, &cur_trans->pinned_extents);
4919 
4920 	cur_trans->state =TRANS_STATE_COMPLETED;
4921 	wake_up(&cur_trans->commit_wait);
4922 }
4923 
4924 static int btrfs_cleanup_transaction(struct btrfs_fs_info *fs_info)
4925 {
4926 	struct btrfs_transaction *t;
4927 
4928 	mutex_lock(&fs_info->transaction_kthread_mutex);
4929 
4930 	spin_lock(&fs_info->trans_lock);
4931 	while (!list_empty(&fs_info->trans_list)) {
4932 		t = list_first_entry(&fs_info->trans_list,
4933 				     struct btrfs_transaction, list);
4934 		if (t->state >= TRANS_STATE_COMMIT_PREP) {
4935 			refcount_inc(&t->use_count);
4936 			spin_unlock(&fs_info->trans_lock);
4937 			btrfs_wait_for_commit(fs_info, t->transid);
4938 			btrfs_put_transaction(t);
4939 			spin_lock(&fs_info->trans_lock);
4940 			continue;
4941 		}
4942 		if (t == fs_info->running_transaction) {
4943 			t->state = TRANS_STATE_COMMIT_DOING;
4944 			spin_unlock(&fs_info->trans_lock);
4945 			/*
4946 			 * We wait for 0 num_writers since we don't hold a trans
4947 			 * handle open currently for this transaction.
4948 			 */
4949 			wait_event(t->writer_wait,
4950 				   atomic_read(&t->num_writers) == 0);
4951 		} else {
4952 			spin_unlock(&fs_info->trans_lock);
4953 		}
4954 		btrfs_cleanup_one_transaction(t);
4955 
4956 		spin_lock(&fs_info->trans_lock);
4957 		if (t == fs_info->running_transaction)
4958 			fs_info->running_transaction = NULL;
4959 		list_del_init(&t->list);
4960 		spin_unlock(&fs_info->trans_lock);
4961 
4962 		btrfs_put_transaction(t);
4963 		spin_lock(&fs_info->trans_lock);
4964 	}
4965 	spin_unlock(&fs_info->trans_lock);
4966 	btrfs_destroy_all_ordered_extents(fs_info);
4967 	btrfs_destroy_delayed_inodes(fs_info);
4968 	btrfs_assert_delayed_root_empty(fs_info);
4969 	btrfs_destroy_all_delalloc_inodes(fs_info);
4970 	btrfs_drop_all_logs(fs_info);
4971 	btrfs_zoned_release_dirty_metadata(fs_info);
4972 	btrfs_free_all_qgroup_pertrans(fs_info);
4973 	mutex_unlock(&fs_info->transaction_kthread_mutex);
4974 
4975 	return 0;
4976 }
4977 
4978 int btrfs_init_root_free_objectid(struct btrfs_root *root)
4979 {
4980 	BTRFS_PATH_AUTO_FREE(path);
4981 	int ret;
4982 	struct extent_buffer *l;
4983 	struct btrfs_key search_key;
4984 	struct btrfs_key found_key;
4985 	int slot;
4986 
4987 	path = btrfs_alloc_path();
4988 	if (!path)
4989 		return -ENOMEM;
4990 
4991 	search_key.objectid = BTRFS_LAST_FREE_OBJECTID;
4992 	search_key.type = -1;
4993 	search_key.offset = (u64)-1;
4994 	ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
4995 	if (ret < 0)
4996 		return ret;
4997 	if (unlikely(ret == 0)) {
4998 		/*
4999 		 * Key with offset -1 found, there would have to exist a root
5000 		 * with such id, but this is out of valid range.
5001 		 */
5002 		return -EUCLEAN;
5003 	}
5004 	if (path->slots[0] > 0) {
5005 		slot = path->slots[0] - 1;
5006 		l = path->nodes[0];
5007 		btrfs_item_key_to_cpu(l, &found_key, slot);
5008 		root->free_objectid = max_t(u64, found_key.objectid + 1,
5009 					    BTRFS_FIRST_FREE_OBJECTID);
5010 	} else {
5011 		root->free_objectid = BTRFS_FIRST_FREE_OBJECTID;
5012 	}
5013 
5014 	return 0;
5015 }
5016 
5017 int btrfs_get_free_objectid(struct btrfs_root *root, u64 *objectid)
5018 {
5019 	int ret;
5020 	mutex_lock(&root->objectid_mutex);
5021 
5022 	if (unlikely(root->free_objectid >= BTRFS_LAST_FREE_OBJECTID)) {
5023 		btrfs_warn(root->fs_info,
5024 			   "the objectid of root %llu reaches its highest value",
5025 			   btrfs_root_id(root));
5026 		ret = -ENOSPC;
5027 		goto out;
5028 	}
5029 
5030 	*objectid = root->free_objectid++;
5031 	ret = 0;
5032 out:
5033 	mutex_unlock(&root->objectid_mutex);
5034 	return ret;
5035 }
5036