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