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