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