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