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