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