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