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