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