1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 2007 Oracle. All rights reserved.
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>
24 #include "transaction.h"
25 #include "btrfs_inode.h"
27 #include "print-tree.h"
30 #include "free-space-cache.h"
31 #include "free-space-tree.h"
32 #include "rcu-string.h"
33 #include "dev-replace.h"
37 #include "compression.h"
38 #include "tree-checker.h"
39 #include "ref-verify.h"
40 #include "block-group.h"
42 #include "space-info.h"
46 #include "accessors.h"
47 #include "extent-tree.h"
48 #include "root-tree.h"
50 #include "uuid-tree.h"
51 #include "relocation.h"
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)
62 static int btrfs_cleanup_transaction(struct btrfs_fs_info *fs_info);
63 static void btrfs_error_commit_super(struct btrfs_fs_info *fs_info);
65 static void btrfs_free_csum_hash(struct btrfs_fs_info *fs_info)
67 if (fs_info->csum_shash)
68 crypto_free_shash(fs_info->csum_shash);
72 * Compute the csum of a btree block and store the result to provided buffer.
74 static void csum_tree_block(struct extent_buffer *buf, u8 *result)
76 struct btrfs_fs_info *fs_info = buf->fs_info;
79 SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
83 shash->tfm = fs_info->csum_shash;
84 crypto_shash_init(shash);
87 /* Pages are contiguous, handle them as a big one. */
89 first_page_part = fs_info->nodesize;
92 kaddr = folio_address(buf->folios[0]);
93 first_page_part = min_t(u32, PAGE_SIZE, fs_info->nodesize);
94 num_pages = num_extent_pages(buf);
97 crypto_shash_update(shash, kaddr + BTRFS_CSUM_SIZE,
98 first_page_part - BTRFS_CSUM_SIZE);
100 for (i = 1; i < num_pages && INLINE_EXTENT_BUFFER_PAGES > 1; i++) {
101 kaddr = folio_address(buf->folios[i]);
102 crypto_shash_update(shash, kaddr, PAGE_SIZE);
104 memset(result, 0, BTRFS_CSUM_SIZE);
105 crypto_shash_final(shash, result);
109 * we can't consider a given block up to date unless the transid of the
110 * block matches the transid in the parent node's pointer. This is how we
111 * detect blocks that either didn't get written at all or got written
112 * in the wrong place.
114 int btrfs_buffer_uptodate(struct extent_buffer *eb, u64 parent_transid, int atomic)
116 if (!extent_buffer_uptodate(eb))
119 if (!parent_transid || btrfs_header_generation(eb) == parent_transid)
125 if (!extent_buffer_uptodate(eb) ||
126 btrfs_header_generation(eb) != parent_transid) {
127 btrfs_err_rl(eb->fs_info,
128 "parent transid verify failed on logical %llu mirror %u wanted %llu found %llu",
129 eb->start, eb->read_mirror,
130 parent_transid, btrfs_header_generation(eb));
131 clear_extent_buffer_uptodate(eb);
137 static bool btrfs_supported_super_csum(u16 csum_type)
140 case BTRFS_CSUM_TYPE_CRC32:
141 case BTRFS_CSUM_TYPE_XXHASH:
142 case BTRFS_CSUM_TYPE_SHA256:
143 case BTRFS_CSUM_TYPE_BLAKE2:
151 * Return 0 if the superblock checksum type matches the checksum value of that
152 * algorithm. Pass the raw disk superblock data.
154 int btrfs_check_super_csum(struct btrfs_fs_info *fs_info,
155 const struct btrfs_super_block *disk_sb)
157 char result[BTRFS_CSUM_SIZE];
158 SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
160 shash->tfm = fs_info->csum_shash;
163 * The super_block structure does not span the whole
164 * BTRFS_SUPER_INFO_SIZE range, we expect that the unused space is
165 * filled with zeros and is included in the checksum.
167 crypto_shash_digest(shash, (const u8 *)disk_sb + BTRFS_CSUM_SIZE,
168 BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE, result);
170 if (memcmp(disk_sb->csum, result, fs_info->csum_size))
176 static int btrfs_repair_eb_io_failure(const struct extent_buffer *eb,
179 struct btrfs_fs_info *fs_info = eb->fs_info;
180 int i, num_pages = num_extent_pages(eb);
183 if (sb_rdonly(fs_info->sb))
186 for (i = 0; i < num_pages; i++) {
187 u64 start = max_t(u64, eb->start, folio_pos(eb->folios[i]));
188 u64 end = min_t(u64, eb->start + eb->len,
189 folio_pos(eb->folios[i]) + PAGE_SIZE);
190 u32 len = end - start;
192 ret = btrfs_repair_io_failure(fs_info, 0, start, len,
193 start, folio_page(eb->folios[i], 0),
194 offset_in_page(start), mirror_num);
203 * helper to read a given tree block, doing retries as required when
204 * the checksums don't match and we have alternate mirrors to try.
206 * @check: expected tree parentness check, see the comments of the
207 * structure for details.
209 int btrfs_read_extent_buffer(struct extent_buffer *eb,
210 struct btrfs_tree_parent_check *check)
212 struct btrfs_fs_info *fs_info = eb->fs_info;
217 int failed_mirror = 0;
222 clear_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags);
223 ret = read_extent_buffer_pages(eb, WAIT_COMPLETE, mirror_num, check);
227 num_copies = btrfs_num_copies(fs_info,
232 if (!failed_mirror) {
234 failed_mirror = eb->read_mirror;
238 if (mirror_num == failed_mirror)
241 if (mirror_num > num_copies)
245 if (failed && !ret && failed_mirror)
246 btrfs_repair_eb_io_failure(eb, failed_mirror);
252 * Checksum a dirty tree block before IO.
254 blk_status_t btree_csum_one_bio(struct btrfs_bio *bbio)
256 struct extent_buffer *eb = bbio->private;
257 struct btrfs_fs_info *fs_info = eb->fs_info;
258 u64 found_start = btrfs_header_bytenr(eb);
260 u8 result[BTRFS_CSUM_SIZE];
263 /* Btree blocks are always contiguous on disk. */
264 if (WARN_ON_ONCE(bbio->file_offset != eb->start))
265 return BLK_STS_IOERR;
266 if (WARN_ON_ONCE(bbio->bio.bi_iter.bi_size != eb->len))
267 return BLK_STS_IOERR;
270 * If an extent_buffer is marked as EXTENT_BUFFER_ZONED_ZEROOUT, don't
271 * checksum it but zero-out its content. This is done to preserve
272 * ordering of I/O without unnecessarily writing out data.
274 if (test_bit(EXTENT_BUFFER_ZONED_ZEROOUT, &eb->bflags)) {
275 memzero_extent_buffer(eb, 0, eb->len);
279 if (WARN_ON_ONCE(found_start != eb->start))
280 return BLK_STS_IOERR;
281 if (WARN_ON(!btrfs_page_test_uptodate(fs_info, folio_page(eb->folios[0], 0),
282 eb->start, eb->len)))
283 return BLK_STS_IOERR;
285 ASSERT(memcmp_extent_buffer(eb, fs_info->fs_devices->metadata_uuid,
286 offsetof(struct btrfs_header, fsid),
287 BTRFS_FSID_SIZE) == 0);
288 csum_tree_block(eb, result);
290 if (btrfs_header_level(eb))
291 ret = btrfs_check_node(eb);
293 ret = btrfs_check_leaf(eb);
299 * Also check the generation, the eb reached here must be newer than
300 * last committed. Or something seriously wrong happened.
302 last_trans = btrfs_get_last_trans_committed(fs_info);
303 if (unlikely(btrfs_header_generation(eb) <= last_trans)) {
306 "block=%llu bad generation, have %llu expect > %llu",
307 eb->start, btrfs_header_generation(eb), last_trans);
310 write_extent_buffer(eb, result, 0, fs_info->csum_size);
314 btrfs_print_tree(eb, 0);
315 btrfs_err(fs_info, "block=%llu write time tree block corruption detected",
318 * Be noisy if this is an extent buffer from a log tree. We don't abort
319 * a transaction in case there's a bad log tree extent buffer, we just
320 * fallback to a transaction commit. Still we want to know when there is
321 * a bad log tree extent buffer, as that may signal a bug somewhere.
323 WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG) ||
324 btrfs_header_owner(eb) == BTRFS_TREE_LOG_OBJECTID);
325 return errno_to_blk_status(ret);
328 static bool check_tree_block_fsid(struct extent_buffer *eb)
330 struct btrfs_fs_info *fs_info = eb->fs_info;
331 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices, *seed_devs;
332 u8 fsid[BTRFS_FSID_SIZE];
334 read_extent_buffer(eb, fsid, offsetof(struct btrfs_header, fsid),
338 * alloc_fsid_devices() copies the fsid into fs_devices::metadata_uuid.
339 * This is then overwritten by metadata_uuid if it is present in the
340 * device_list_add(). The same true for a seed device as well. So use of
341 * fs_devices::metadata_uuid is appropriate here.
343 if (memcmp(fsid, fs_info->fs_devices->metadata_uuid, BTRFS_FSID_SIZE) == 0)
346 list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list)
347 if (!memcmp(fsid, seed_devs->fsid, BTRFS_FSID_SIZE))
353 /* Do basic extent buffer checks at read time */
354 int btrfs_validate_extent_buffer(struct extent_buffer *eb,
355 struct btrfs_tree_parent_check *check)
357 struct btrfs_fs_info *fs_info = eb->fs_info;
359 const u32 csum_size = fs_info->csum_size;
361 u8 result[BTRFS_CSUM_SIZE];
362 const u8 *header_csum;
367 found_start = btrfs_header_bytenr(eb);
368 if (found_start != eb->start) {
369 btrfs_err_rl(fs_info,
370 "bad tree block start, mirror %u want %llu have %llu",
371 eb->read_mirror, eb->start, found_start);
375 if (check_tree_block_fsid(eb)) {
376 btrfs_err_rl(fs_info, "bad fsid on logical %llu mirror %u",
377 eb->start, eb->read_mirror);
381 found_level = btrfs_header_level(eb);
382 if (found_level >= BTRFS_MAX_LEVEL) {
384 "bad tree block level, mirror %u level %d on logical %llu",
385 eb->read_mirror, btrfs_header_level(eb), eb->start);
390 csum_tree_block(eb, result);
391 header_csum = folio_address(eb->folios[0]) +
392 get_eb_offset_in_page(eb, offsetof(struct btrfs_header, csum));
394 if (memcmp(result, header_csum, csum_size) != 0) {
395 btrfs_warn_rl(fs_info,
396 "checksum verify failed on logical %llu mirror %u wanted " CSUM_FMT " found " CSUM_FMT " level %d",
397 eb->start, eb->read_mirror,
398 CSUM_FMT_VALUE(csum_size, header_csum),
399 CSUM_FMT_VALUE(csum_size, result),
400 btrfs_header_level(eb));
405 if (found_level != check->level) {
407 "level verify failed on logical %llu mirror %u wanted %u found %u",
408 eb->start, eb->read_mirror, check->level, found_level);
412 if (unlikely(check->transid &&
413 btrfs_header_generation(eb) != check->transid)) {
414 btrfs_err_rl(eb->fs_info,
415 "parent transid verify failed on logical %llu mirror %u wanted %llu found %llu",
416 eb->start, eb->read_mirror, check->transid,
417 btrfs_header_generation(eb));
421 if (check->has_first_key) {
422 struct btrfs_key *expect_key = &check->first_key;
423 struct btrfs_key found_key;
426 btrfs_node_key_to_cpu(eb, &found_key, 0);
428 btrfs_item_key_to_cpu(eb, &found_key, 0);
429 if (unlikely(btrfs_comp_cpu_keys(expect_key, &found_key))) {
431 "tree first key mismatch detected, bytenr=%llu parent_transid=%llu key expected=(%llu,%u,%llu) has=(%llu,%u,%llu)",
432 eb->start, check->transid,
433 expect_key->objectid,
434 expect_key->type, expect_key->offset,
435 found_key.objectid, found_key.type,
441 if (check->owner_root) {
442 ret = btrfs_check_eb_owner(eb, check->owner_root);
448 * If this is a leaf block and it is corrupt, set the corrupt bit so
449 * that we don't try and read the other copies of this block, just
452 if (found_level == 0 && btrfs_check_leaf(eb)) {
453 set_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags);
457 if (found_level > 0 && btrfs_check_node(eb))
462 "read time tree block corruption detected on logical %llu mirror %u",
463 eb->start, eb->read_mirror);
468 #ifdef CONFIG_MIGRATION
469 static int btree_migrate_folio(struct address_space *mapping,
470 struct folio *dst, struct folio *src, enum migrate_mode mode)
473 * we can't safely write a btree page from here,
474 * we haven't done the locking hook
476 if (folio_test_dirty(src))
479 * Buffers may be managed in a filesystem specific way.
480 * We must have no buffers or drop them.
482 if (folio_get_private(src) &&
483 !filemap_release_folio(src, GFP_KERNEL))
485 return migrate_folio(mapping, dst, src, mode);
488 #define btree_migrate_folio NULL
491 static int btree_writepages(struct address_space *mapping,
492 struct writeback_control *wbc)
494 struct btrfs_fs_info *fs_info;
497 if (wbc->sync_mode == WB_SYNC_NONE) {
499 if (wbc->for_kupdate)
502 fs_info = BTRFS_I(mapping->host)->root->fs_info;
503 /* this is a bit racy, but that's ok */
504 ret = __percpu_counter_compare(&fs_info->dirty_metadata_bytes,
505 BTRFS_DIRTY_METADATA_THRESH,
506 fs_info->dirty_metadata_batch);
510 return btree_write_cache_pages(mapping, wbc);
513 static bool btree_release_folio(struct folio *folio, gfp_t gfp_flags)
515 if (folio_test_writeback(folio) || folio_test_dirty(folio))
518 return try_release_extent_buffer(&folio->page);
521 static void btree_invalidate_folio(struct folio *folio, size_t offset,
524 struct extent_io_tree *tree;
525 tree = &BTRFS_I(folio->mapping->host)->io_tree;
526 extent_invalidate_folio(tree, folio, offset);
527 btree_release_folio(folio, GFP_NOFS);
528 if (folio_get_private(folio)) {
529 btrfs_warn(BTRFS_I(folio->mapping->host)->root->fs_info,
530 "folio private not zero on folio %llu",
531 (unsigned long long)folio_pos(folio));
532 folio_detach_private(folio);
537 static bool btree_dirty_folio(struct address_space *mapping,
540 struct btrfs_fs_info *fs_info = btrfs_sb(mapping->host->i_sb);
541 struct btrfs_subpage_info *spi = fs_info->subpage_info;
542 struct btrfs_subpage *subpage;
543 struct extent_buffer *eb;
545 u64 page_start = folio_pos(folio);
547 if (fs_info->sectorsize == PAGE_SIZE) {
548 eb = folio_get_private(folio);
550 BUG_ON(!test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
551 BUG_ON(!atomic_read(&eb->refs));
552 btrfs_assert_tree_write_locked(eb);
553 return filemap_dirty_folio(mapping, folio);
557 subpage = folio_get_private(folio);
559 for (cur_bit = spi->dirty_offset;
560 cur_bit < spi->dirty_offset + spi->bitmap_nr_bits;
565 spin_lock_irqsave(&subpage->lock, flags);
566 if (!test_bit(cur_bit, subpage->bitmaps)) {
567 spin_unlock_irqrestore(&subpage->lock, flags);
570 spin_unlock_irqrestore(&subpage->lock, flags);
571 cur = page_start + cur_bit * fs_info->sectorsize;
573 eb = find_extent_buffer(fs_info, cur);
575 ASSERT(test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
576 ASSERT(atomic_read(&eb->refs));
577 btrfs_assert_tree_write_locked(eb);
578 free_extent_buffer(eb);
580 cur_bit += (fs_info->nodesize >> fs_info->sectorsize_bits) - 1;
582 return filemap_dirty_folio(mapping, folio);
585 #define btree_dirty_folio filemap_dirty_folio
588 static const struct address_space_operations btree_aops = {
589 .writepages = btree_writepages,
590 .release_folio = btree_release_folio,
591 .invalidate_folio = btree_invalidate_folio,
592 .migrate_folio = btree_migrate_folio,
593 .dirty_folio = btree_dirty_folio,
596 struct extent_buffer *btrfs_find_create_tree_block(
597 struct btrfs_fs_info *fs_info,
598 u64 bytenr, u64 owner_root,
601 if (btrfs_is_testing(fs_info))
602 return alloc_test_extent_buffer(fs_info, bytenr);
603 return alloc_extent_buffer(fs_info, bytenr, owner_root, level);
607 * Read tree block at logical address @bytenr and do variant basic but critical
610 * @check: expected tree parentness check, see comments of the
611 * structure for details.
613 struct extent_buffer *read_tree_block(struct btrfs_fs_info *fs_info, u64 bytenr,
614 struct btrfs_tree_parent_check *check)
616 struct extent_buffer *buf = NULL;
621 buf = btrfs_find_create_tree_block(fs_info, bytenr, check->owner_root,
626 ret = btrfs_read_extent_buffer(buf, check);
628 free_extent_buffer_stale(buf);
631 if (btrfs_check_eb_owner(buf, check->owner_root)) {
632 free_extent_buffer_stale(buf);
633 return ERR_PTR(-EUCLEAN);
639 static void __setup_root(struct btrfs_root *root, struct btrfs_fs_info *fs_info,
642 bool dummy = test_bit(BTRFS_FS_STATE_DUMMY_FS_INFO, &fs_info->fs_state);
644 memset(&root->root_key, 0, sizeof(root->root_key));
645 memset(&root->root_item, 0, sizeof(root->root_item));
646 memset(&root->defrag_progress, 0, sizeof(root->defrag_progress));
647 root->fs_info = fs_info;
648 root->root_key.objectid = objectid;
650 root->commit_root = NULL;
652 RB_CLEAR_NODE(&root->rb_node);
654 root->last_trans = 0;
655 root->free_objectid = 0;
656 root->nr_delalloc_inodes = 0;
657 root->nr_ordered_extents = 0;
658 root->inode_tree = RB_ROOT;
659 /* GFP flags are compatible with XA_FLAGS_*. */
660 xa_init_flags(&root->delayed_nodes, GFP_ATOMIC);
662 btrfs_init_root_block_rsv(root);
664 INIT_LIST_HEAD(&root->dirty_list);
665 INIT_LIST_HEAD(&root->root_list);
666 INIT_LIST_HEAD(&root->delalloc_inodes);
667 INIT_LIST_HEAD(&root->delalloc_root);
668 INIT_LIST_HEAD(&root->ordered_extents);
669 INIT_LIST_HEAD(&root->ordered_root);
670 INIT_LIST_HEAD(&root->reloc_dirty_list);
671 spin_lock_init(&root->inode_lock);
672 spin_lock_init(&root->delalloc_lock);
673 spin_lock_init(&root->ordered_extent_lock);
674 spin_lock_init(&root->accounting_lock);
675 spin_lock_init(&root->qgroup_meta_rsv_lock);
676 mutex_init(&root->objectid_mutex);
677 mutex_init(&root->log_mutex);
678 mutex_init(&root->ordered_extent_mutex);
679 mutex_init(&root->delalloc_mutex);
680 init_waitqueue_head(&root->qgroup_flush_wait);
681 init_waitqueue_head(&root->log_writer_wait);
682 init_waitqueue_head(&root->log_commit_wait[0]);
683 init_waitqueue_head(&root->log_commit_wait[1]);
684 INIT_LIST_HEAD(&root->log_ctxs[0]);
685 INIT_LIST_HEAD(&root->log_ctxs[1]);
686 atomic_set(&root->log_commit[0], 0);
687 atomic_set(&root->log_commit[1], 0);
688 atomic_set(&root->log_writers, 0);
689 atomic_set(&root->log_batch, 0);
690 refcount_set(&root->refs, 1);
691 atomic_set(&root->snapshot_force_cow, 0);
692 atomic_set(&root->nr_swapfiles, 0);
693 btrfs_set_root_log_transid(root, 0);
694 root->log_transid_committed = -1;
695 btrfs_set_root_last_log_commit(root, 0);
698 extent_io_tree_init(fs_info, &root->dirty_log_pages,
699 IO_TREE_ROOT_DIRTY_LOG_PAGES);
700 extent_io_tree_init(fs_info, &root->log_csum_range,
701 IO_TREE_LOG_CSUM_RANGE);
704 spin_lock_init(&root->root_item_lock);
705 btrfs_qgroup_init_swapped_blocks(&root->swapped_blocks);
706 #ifdef CONFIG_BTRFS_DEBUG
707 INIT_LIST_HEAD(&root->leak_list);
708 spin_lock(&fs_info->fs_roots_radix_lock);
709 list_add_tail(&root->leak_list, &fs_info->allocated_roots);
710 spin_unlock(&fs_info->fs_roots_radix_lock);
714 static struct btrfs_root *btrfs_alloc_root(struct btrfs_fs_info *fs_info,
715 u64 objectid, gfp_t flags)
717 struct btrfs_root *root = kzalloc(sizeof(*root), flags);
719 __setup_root(root, fs_info, objectid);
723 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
724 /* Should only be used by the testing infrastructure */
725 struct btrfs_root *btrfs_alloc_dummy_root(struct btrfs_fs_info *fs_info)
727 struct btrfs_root *root;
730 return ERR_PTR(-EINVAL);
732 root = btrfs_alloc_root(fs_info, BTRFS_ROOT_TREE_OBJECTID, GFP_KERNEL);
734 return ERR_PTR(-ENOMEM);
736 /* We don't use the stripesize in selftest, set it as sectorsize */
737 root->alloc_bytenr = 0;
743 static int global_root_cmp(struct rb_node *a_node, const struct rb_node *b_node)
745 const struct btrfs_root *a = rb_entry(a_node, struct btrfs_root, rb_node);
746 const struct btrfs_root *b = rb_entry(b_node, struct btrfs_root, rb_node);
748 return btrfs_comp_cpu_keys(&a->root_key, &b->root_key);
751 static int global_root_key_cmp(const void *k, const struct rb_node *node)
753 const struct btrfs_key *key = k;
754 const struct btrfs_root *root = rb_entry(node, struct btrfs_root, rb_node);
756 return btrfs_comp_cpu_keys(key, &root->root_key);
759 int btrfs_global_root_insert(struct btrfs_root *root)
761 struct btrfs_fs_info *fs_info = root->fs_info;
765 write_lock(&fs_info->global_root_lock);
766 tmp = rb_find_add(&root->rb_node, &fs_info->global_root_tree, global_root_cmp);
767 write_unlock(&fs_info->global_root_lock);
771 btrfs_warn(fs_info, "global root %llu %llu already exists",
772 root->root_key.objectid, root->root_key.offset);
777 void btrfs_global_root_delete(struct btrfs_root *root)
779 struct btrfs_fs_info *fs_info = root->fs_info;
781 write_lock(&fs_info->global_root_lock);
782 rb_erase(&root->rb_node, &fs_info->global_root_tree);
783 write_unlock(&fs_info->global_root_lock);
786 struct btrfs_root *btrfs_global_root(struct btrfs_fs_info *fs_info,
787 struct btrfs_key *key)
789 struct rb_node *node;
790 struct btrfs_root *root = NULL;
792 read_lock(&fs_info->global_root_lock);
793 node = rb_find(key, &fs_info->global_root_tree, global_root_key_cmp);
795 root = container_of(node, struct btrfs_root, rb_node);
796 read_unlock(&fs_info->global_root_lock);
801 static u64 btrfs_global_root_id(struct btrfs_fs_info *fs_info, u64 bytenr)
803 struct btrfs_block_group *block_group;
806 if (!btrfs_fs_incompat(fs_info, EXTENT_TREE_V2))
810 block_group = btrfs_lookup_block_group(fs_info, bytenr);
812 block_group = btrfs_lookup_first_block_group(fs_info, bytenr);
816 ret = block_group->global_root_id;
817 btrfs_put_block_group(block_group);
822 struct btrfs_root *btrfs_csum_root(struct btrfs_fs_info *fs_info, u64 bytenr)
824 struct btrfs_key key = {
825 .objectid = BTRFS_CSUM_TREE_OBJECTID,
826 .type = BTRFS_ROOT_ITEM_KEY,
827 .offset = btrfs_global_root_id(fs_info, bytenr),
830 return btrfs_global_root(fs_info, &key);
833 struct btrfs_root *btrfs_extent_root(struct btrfs_fs_info *fs_info, u64 bytenr)
835 struct btrfs_key key = {
836 .objectid = BTRFS_EXTENT_TREE_OBJECTID,
837 .type = BTRFS_ROOT_ITEM_KEY,
838 .offset = btrfs_global_root_id(fs_info, bytenr),
841 return btrfs_global_root(fs_info, &key);
844 struct btrfs_root *btrfs_block_group_root(struct btrfs_fs_info *fs_info)
846 if (btrfs_fs_compat_ro(fs_info, BLOCK_GROUP_TREE))
847 return fs_info->block_group_root;
848 return btrfs_extent_root(fs_info, 0);
851 struct btrfs_root *btrfs_create_tree(struct btrfs_trans_handle *trans,
854 struct btrfs_fs_info *fs_info = trans->fs_info;
855 struct extent_buffer *leaf;
856 struct btrfs_root *tree_root = fs_info->tree_root;
857 struct btrfs_root *root;
858 struct btrfs_key key;
859 unsigned int nofs_flag;
863 * We're holding a transaction handle, so use a NOFS memory allocation
864 * context to avoid deadlock if reclaim happens.
866 nofs_flag = memalloc_nofs_save();
867 root = btrfs_alloc_root(fs_info, objectid, GFP_KERNEL);
868 memalloc_nofs_restore(nofs_flag);
870 return ERR_PTR(-ENOMEM);
872 root->root_key.objectid = objectid;
873 root->root_key.type = BTRFS_ROOT_ITEM_KEY;
874 root->root_key.offset = 0;
876 leaf = btrfs_alloc_tree_block(trans, root, 0, objectid, NULL, 0, 0, 0,
877 0, BTRFS_NESTING_NORMAL);
885 btrfs_mark_buffer_dirty(trans, leaf);
887 root->commit_root = btrfs_root_node(root);
888 set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
890 btrfs_set_root_flags(&root->root_item, 0);
891 btrfs_set_root_limit(&root->root_item, 0);
892 btrfs_set_root_bytenr(&root->root_item, leaf->start);
893 btrfs_set_root_generation(&root->root_item, trans->transid);
894 btrfs_set_root_level(&root->root_item, 0);
895 btrfs_set_root_refs(&root->root_item, 1);
896 btrfs_set_root_used(&root->root_item, leaf->len);
897 btrfs_set_root_last_snapshot(&root->root_item, 0);
898 btrfs_set_root_dirid(&root->root_item, 0);
899 if (is_fstree(objectid))
900 generate_random_guid(root->root_item.uuid);
902 export_guid(root->root_item.uuid, &guid_null);
903 btrfs_set_root_drop_level(&root->root_item, 0);
905 btrfs_tree_unlock(leaf);
907 key.objectid = objectid;
908 key.type = BTRFS_ROOT_ITEM_KEY;
910 ret = btrfs_insert_root(trans, tree_root, &key, &root->root_item);
917 btrfs_put_root(root);
922 static struct btrfs_root *alloc_log_tree(struct btrfs_trans_handle *trans,
923 struct btrfs_fs_info *fs_info)
925 struct btrfs_root *root;
927 root = btrfs_alloc_root(fs_info, BTRFS_TREE_LOG_OBJECTID, GFP_NOFS);
929 return ERR_PTR(-ENOMEM);
931 root->root_key.objectid = BTRFS_TREE_LOG_OBJECTID;
932 root->root_key.type = BTRFS_ROOT_ITEM_KEY;
933 root->root_key.offset = BTRFS_TREE_LOG_OBJECTID;
938 int btrfs_alloc_log_tree_node(struct btrfs_trans_handle *trans,
939 struct btrfs_root *root)
941 struct extent_buffer *leaf;
944 * DON'T set SHAREABLE bit for log trees.
946 * Log trees are not exposed to user space thus can't be snapshotted,
947 * and they go away before a real commit is actually done.
949 * They do store pointers to file data extents, and those reference
950 * counts still get updated (along with back refs to the log tree).
953 leaf = btrfs_alloc_tree_block(trans, root, 0, BTRFS_TREE_LOG_OBJECTID,
954 NULL, 0, 0, 0, 0, BTRFS_NESTING_NORMAL);
956 return PTR_ERR(leaf);
960 btrfs_mark_buffer_dirty(trans, root->node);
961 btrfs_tree_unlock(root->node);
966 int btrfs_init_log_root_tree(struct btrfs_trans_handle *trans,
967 struct btrfs_fs_info *fs_info)
969 struct btrfs_root *log_root;
971 log_root = alloc_log_tree(trans, fs_info);
972 if (IS_ERR(log_root))
973 return PTR_ERR(log_root);
975 if (!btrfs_is_zoned(fs_info)) {
976 int ret = btrfs_alloc_log_tree_node(trans, log_root);
979 btrfs_put_root(log_root);
984 WARN_ON(fs_info->log_root_tree);
985 fs_info->log_root_tree = log_root;
989 int btrfs_add_log_tree(struct btrfs_trans_handle *trans,
990 struct btrfs_root *root)
992 struct btrfs_fs_info *fs_info = root->fs_info;
993 struct btrfs_root *log_root;
994 struct btrfs_inode_item *inode_item;
997 log_root = alloc_log_tree(trans, fs_info);
998 if (IS_ERR(log_root))
999 return PTR_ERR(log_root);
1001 ret = btrfs_alloc_log_tree_node(trans, log_root);
1003 btrfs_put_root(log_root);
1007 log_root->last_trans = trans->transid;
1008 log_root->root_key.offset = root->root_key.objectid;
1010 inode_item = &log_root->root_item.inode;
1011 btrfs_set_stack_inode_generation(inode_item, 1);
1012 btrfs_set_stack_inode_size(inode_item, 3);
1013 btrfs_set_stack_inode_nlink(inode_item, 1);
1014 btrfs_set_stack_inode_nbytes(inode_item,
1016 btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
1018 btrfs_set_root_node(&log_root->root_item, log_root->node);
1020 WARN_ON(root->log_root);
1021 root->log_root = log_root;
1022 btrfs_set_root_log_transid(root, 0);
1023 root->log_transid_committed = -1;
1024 btrfs_set_root_last_log_commit(root, 0);
1028 static struct btrfs_root *read_tree_root_path(struct btrfs_root *tree_root,
1029 struct btrfs_path *path,
1030 struct btrfs_key *key)
1032 struct btrfs_root *root;
1033 struct btrfs_tree_parent_check check = { 0 };
1034 struct btrfs_fs_info *fs_info = tree_root->fs_info;
1039 root = btrfs_alloc_root(fs_info, key->objectid, GFP_NOFS);
1041 return ERR_PTR(-ENOMEM);
1043 ret = btrfs_find_root(tree_root, key, path,
1044 &root->root_item, &root->root_key);
1051 generation = btrfs_root_generation(&root->root_item);
1052 level = btrfs_root_level(&root->root_item);
1053 check.level = level;
1054 check.transid = generation;
1055 check.owner_root = key->objectid;
1056 root->node = read_tree_block(fs_info, btrfs_root_bytenr(&root->root_item),
1058 if (IS_ERR(root->node)) {
1059 ret = PTR_ERR(root->node);
1063 if (!btrfs_buffer_uptodate(root->node, generation, 0)) {
1069 * For real fs, and not log/reloc trees, root owner must
1070 * match its root node owner
1072 if (!test_bit(BTRFS_FS_STATE_DUMMY_FS_INFO, &fs_info->fs_state) &&
1073 root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID &&
1074 root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
1075 root->root_key.objectid != btrfs_header_owner(root->node)) {
1077 "root=%llu block=%llu, tree root owner mismatch, have %llu expect %llu",
1078 root->root_key.objectid, root->node->start,
1079 btrfs_header_owner(root->node),
1080 root->root_key.objectid);
1084 root->commit_root = btrfs_root_node(root);
1087 btrfs_put_root(root);
1088 return ERR_PTR(ret);
1091 struct btrfs_root *btrfs_read_tree_root(struct btrfs_root *tree_root,
1092 struct btrfs_key *key)
1094 struct btrfs_root *root;
1095 struct btrfs_path *path;
1097 path = btrfs_alloc_path();
1099 return ERR_PTR(-ENOMEM);
1100 root = read_tree_root_path(tree_root, path, key);
1101 btrfs_free_path(path);
1107 * Initialize subvolume root in-memory structure
1109 * @anon_dev: anonymous device to attach to the root, if zero, allocate new
1111 static int btrfs_init_fs_root(struct btrfs_root *root, dev_t anon_dev)
1115 btrfs_drew_lock_init(&root->snapshot_lock);
1117 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID &&
1118 !btrfs_is_data_reloc_root(root) &&
1119 is_fstree(root->root_key.objectid)) {
1120 set_bit(BTRFS_ROOT_SHAREABLE, &root->state);
1121 btrfs_check_and_init_root_item(&root->root_item);
1125 * Don't assign anonymous block device to roots that are not exposed to
1126 * userspace, the id pool is limited to 1M
1128 if (is_fstree(root->root_key.objectid) &&
1129 btrfs_root_refs(&root->root_item) > 0) {
1131 ret = get_anon_bdev(&root->anon_dev);
1135 root->anon_dev = anon_dev;
1139 mutex_lock(&root->objectid_mutex);
1140 ret = btrfs_init_root_free_objectid(root);
1142 mutex_unlock(&root->objectid_mutex);
1146 ASSERT(root->free_objectid <= BTRFS_LAST_FREE_OBJECTID);
1148 mutex_unlock(&root->objectid_mutex);
1152 /* The caller is responsible to call btrfs_free_fs_root */
1156 static struct btrfs_root *btrfs_lookup_fs_root(struct btrfs_fs_info *fs_info,
1159 struct btrfs_root *root;
1161 spin_lock(&fs_info->fs_roots_radix_lock);
1162 root = radix_tree_lookup(&fs_info->fs_roots_radix,
1163 (unsigned long)root_id);
1164 root = btrfs_grab_root(root);
1165 spin_unlock(&fs_info->fs_roots_radix_lock);
1169 static struct btrfs_root *btrfs_get_global_root(struct btrfs_fs_info *fs_info,
1172 struct btrfs_key key = {
1173 .objectid = objectid,
1174 .type = BTRFS_ROOT_ITEM_KEY,
1179 case BTRFS_ROOT_TREE_OBJECTID:
1180 return btrfs_grab_root(fs_info->tree_root);
1181 case BTRFS_EXTENT_TREE_OBJECTID:
1182 return btrfs_grab_root(btrfs_global_root(fs_info, &key));
1183 case BTRFS_CHUNK_TREE_OBJECTID:
1184 return btrfs_grab_root(fs_info->chunk_root);
1185 case BTRFS_DEV_TREE_OBJECTID:
1186 return btrfs_grab_root(fs_info->dev_root);
1187 case BTRFS_CSUM_TREE_OBJECTID:
1188 return btrfs_grab_root(btrfs_global_root(fs_info, &key));
1189 case BTRFS_QUOTA_TREE_OBJECTID:
1190 return btrfs_grab_root(fs_info->quota_root);
1191 case BTRFS_UUID_TREE_OBJECTID:
1192 return btrfs_grab_root(fs_info->uuid_root);
1193 case BTRFS_BLOCK_GROUP_TREE_OBJECTID:
1194 return btrfs_grab_root(fs_info->block_group_root);
1195 case BTRFS_FREE_SPACE_TREE_OBJECTID:
1196 return btrfs_grab_root(btrfs_global_root(fs_info, &key));
1197 case BTRFS_RAID_STRIPE_TREE_OBJECTID:
1198 return btrfs_grab_root(fs_info->stripe_root);
1204 int btrfs_insert_fs_root(struct btrfs_fs_info *fs_info,
1205 struct btrfs_root *root)
1209 ret = radix_tree_preload(GFP_NOFS);
1213 spin_lock(&fs_info->fs_roots_radix_lock);
1214 ret = radix_tree_insert(&fs_info->fs_roots_radix,
1215 (unsigned long)root->root_key.objectid,
1218 btrfs_grab_root(root);
1219 set_bit(BTRFS_ROOT_IN_RADIX, &root->state);
1221 spin_unlock(&fs_info->fs_roots_radix_lock);
1222 radix_tree_preload_end();
1227 void btrfs_check_leaked_roots(struct btrfs_fs_info *fs_info)
1229 #ifdef CONFIG_BTRFS_DEBUG
1230 struct btrfs_root *root;
1232 while (!list_empty(&fs_info->allocated_roots)) {
1233 char buf[BTRFS_ROOT_NAME_BUF_LEN];
1235 root = list_first_entry(&fs_info->allocated_roots,
1236 struct btrfs_root, leak_list);
1237 btrfs_err(fs_info, "leaked root %s refcount %d",
1238 btrfs_root_name(&root->root_key, buf),
1239 refcount_read(&root->refs));
1240 while (refcount_read(&root->refs) > 1)
1241 btrfs_put_root(root);
1242 btrfs_put_root(root);
1247 static void free_global_roots(struct btrfs_fs_info *fs_info)
1249 struct btrfs_root *root;
1250 struct rb_node *node;
1252 while ((node = rb_first_postorder(&fs_info->global_root_tree)) != NULL) {
1253 root = rb_entry(node, struct btrfs_root, rb_node);
1254 rb_erase(&root->rb_node, &fs_info->global_root_tree);
1255 btrfs_put_root(root);
1259 void btrfs_free_fs_info(struct btrfs_fs_info *fs_info)
1261 percpu_counter_destroy(&fs_info->dirty_metadata_bytes);
1262 percpu_counter_destroy(&fs_info->delalloc_bytes);
1263 percpu_counter_destroy(&fs_info->ordered_bytes);
1264 percpu_counter_destroy(&fs_info->dev_replace.bio_counter);
1265 btrfs_free_csum_hash(fs_info);
1266 btrfs_free_stripe_hash_table(fs_info);
1267 btrfs_free_ref_cache(fs_info);
1268 kfree(fs_info->balance_ctl);
1269 kfree(fs_info->delayed_root);
1270 free_global_roots(fs_info);
1271 btrfs_put_root(fs_info->tree_root);
1272 btrfs_put_root(fs_info->chunk_root);
1273 btrfs_put_root(fs_info->dev_root);
1274 btrfs_put_root(fs_info->quota_root);
1275 btrfs_put_root(fs_info->uuid_root);
1276 btrfs_put_root(fs_info->fs_root);
1277 btrfs_put_root(fs_info->data_reloc_root);
1278 btrfs_put_root(fs_info->block_group_root);
1279 btrfs_put_root(fs_info->stripe_root);
1280 btrfs_check_leaked_roots(fs_info);
1281 btrfs_extent_buffer_leak_debug_check(fs_info);
1282 kfree(fs_info->super_copy);
1283 kfree(fs_info->super_for_commit);
1284 kfree(fs_info->subpage_info);
1290 * Get an in-memory reference of a root structure.
1292 * For essential trees like root/extent tree, we grab it from fs_info directly.
1293 * For subvolume trees, we check the cached filesystem roots first. If not
1294 * found, then read it from disk and add it to cached fs roots.
1296 * Caller should release the root by calling btrfs_put_root() after the usage.
1298 * NOTE: Reloc and log trees can't be read by this function as they share the
1299 * same root objectid.
1301 * @objectid: root id
1302 * @anon_dev: preallocated anonymous block device number for new roots,
1303 * pass 0 for new allocation.
1304 * @check_ref: whether to check root item references, If true, return -ENOENT
1307 static struct btrfs_root *btrfs_get_root_ref(struct btrfs_fs_info *fs_info,
1308 u64 objectid, dev_t anon_dev,
1311 struct btrfs_root *root;
1312 struct btrfs_path *path;
1313 struct btrfs_key key;
1316 root = btrfs_get_global_root(fs_info, objectid);
1321 * If we're called for non-subvolume trees, and above function didn't
1322 * find one, do not try to read it from disk.
1324 * This is namely for free-space-tree and quota tree, which can change
1325 * at runtime and should only be grabbed from fs_info.
1327 if (!is_fstree(objectid) && objectid != BTRFS_DATA_RELOC_TREE_OBJECTID)
1328 return ERR_PTR(-ENOENT);
1330 root = btrfs_lookup_fs_root(fs_info, objectid);
1332 /* Shouldn't get preallocated anon_dev for cached roots */
1334 if (check_ref && btrfs_root_refs(&root->root_item) == 0) {
1335 btrfs_put_root(root);
1336 return ERR_PTR(-ENOENT);
1341 key.objectid = objectid;
1342 key.type = BTRFS_ROOT_ITEM_KEY;
1343 key.offset = (u64)-1;
1344 root = btrfs_read_tree_root(fs_info->tree_root, &key);
1348 if (check_ref && btrfs_root_refs(&root->root_item) == 0) {
1353 ret = btrfs_init_fs_root(root, anon_dev);
1357 path = btrfs_alloc_path();
1362 key.objectid = BTRFS_ORPHAN_OBJECTID;
1363 key.type = BTRFS_ORPHAN_ITEM_KEY;
1364 key.offset = objectid;
1366 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
1367 btrfs_free_path(path);
1371 set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state);
1373 ret = btrfs_insert_fs_root(fs_info, root);
1375 if (ret == -EEXIST) {
1376 btrfs_put_root(root);
1384 * If our caller provided us an anonymous device, then it's his
1385 * responsibility to free it in case we fail. So we have to set our
1386 * root's anon_dev to 0 to avoid a double free, once by btrfs_put_root()
1387 * and once again by our caller.
1391 btrfs_put_root(root);
1392 return ERR_PTR(ret);
1396 * Get in-memory reference of a root structure
1398 * @objectid: tree objectid
1399 * @check_ref: if set, verify that the tree exists and the item has at least
1402 struct btrfs_root *btrfs_get_fs_root(struct btrfs_fs_info *fs_info,
1403 u64 objectid, bool check_ref)
1405 return btrfs_get_root_ref(fs_info, objectid, 0, check_ref);
1409 * Get in-memory reference of a root structure, created as new, optionally pass
1410 * the anonymous block device id
1412 * @objectid: tree objectid
1413 * @anon_dev: if zero, allocate a new anonymous block device or use the
1416 struct btrfs_root *btrfs_get_new_fs_root(struct btrfs_fs_info *fs_info,
1417 u64 objectid, dev_t anon_dev)
1419 return btrfs_get_root_ref(fs_info, objectid, anon_dev, true);
1423 * Return a root for the given objectid.
1425 * @fs_info: the fs_info
1426 * @objectid: the objectid we need to lookup
1428 * This is exclusively used for backref walking, and exists specifically because
1429 * of how qgroups does lookups. Qgroups will do a backref lookup at delayed ref
1430 * creation time, which means we may have to read the tree_root in order to look
1431 * up a fs root that is not in memory. If the root is not in memory we will
1432 * read the tree root commit root and look up the fs root from there. This is a
1433 * temporary root, it will not be inserted into the radix tree as it doesn't
1434 * have the most uptodate information, it'll simply be discarded once the
1435 * backref code is finished using the root.
1437 struct btrfs_root *btrfs_get_fs_root_commit_root(struct btrfs_fs_info *fs_info,
1438 struct btrfs_path *path,
1441 struct btrfs_root *root;
1442 struct btrfs_key key;
1444 ASSERT(path->search_commit_root && path->skip_locking);
1447 * This can return -ENOENT if we ask for a root that doesn't exist, but
1448 * since this is called via the backref walking code we won't be looking
1449 * up a root that doesn't exist, unless there's corruption. So if root
1450 * != NULL just return it.
1452 root = btrfs_get_global_root(fs_info, objectid);
1456 root = btrfs_lookup_fs_root(fs_info, objectid);
1460 key.objectid = objectid;
1461 key.type = BTRFS_ROOT_ITEM_KEY;
1462 key.offset = (u64)-1;
1463 root = read_tree_root_path(fs_info->tree_root, path, &key);
1464 btrfs_release_path(path);
1469 static int cleaner_kthread(void *arg)
1471 struct btrfs_fs_info *fs_info = arg;
1477 set_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags);
1479 /* Make the cleaner go to sleep early. */
1480 if (btrfs_need_cleaner_sleep(fs_info))
1484 * Do not do anything if we might cause open_ctree() to block
1485 * before we have finished mounting the filesystem.
1487 if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
1490 if (!mutex_trylock(&fs_info->cleaner_mutex))
1494 * Avoid the problem that we change the status of the fs
1495 * during the above check and trylock.
1497 if (btrfs_need_cleaner_sleep(fs_info)) {
1498 mutex_unlock(&fs_info->cleaner_mutex);
1502 if (test_and_clear_bit(BTRFS_FS_FEATURE_CHANGED, &fs_info->flags))
1503 btrfs_sysfs_feature_update(fs_info);
1505 btrfs_run_delayed_iputs(fs_info);
1507 again = btrfs_clean_one_deleted_snapshot(fs_info);
1508 mutex_unlock(&fs_info->cleaner_mutex);
1511 * The defragger has dealt with the R/O remount and umount,
1512 * needn't do anything special here.
1514 btrfs_run_defrag_inodes(fs_info);
1517 * Acquires fs_info->reclaim_bgs_lock to avoid racing
1518 * with relocation (btrfs_relocate_chunk) and relocation
1519 * acquires fs_info->cleaner_mutex (btrfs_relocate_block_group)
1520 * after acquiring fs_info->reclaim_bgs_lock. So we
1521 * can't hold, nor need to, fs_info->cleaner_mutex when deleting
1522 * unused block groups.
1524 btrfs_delete_unused_bgs(fs_info);
1527 * Reclaim block groups in the reclaim_bgs list after we deleted
1528 * all unused block_groups. This possibly gives us some more free
1531 btrfs_reclaim_bgs(fs_info);
1533 clear_and_wake_up_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags);
1534 if (kthread_should_park())
1536 if (kthread_should_stop())
1539 set_current_state(TASK_INTERRUPTIBLE);
1541 __set_current_state(TASK_RUNNING);
1546 static int transaction_kthread(void *arg)
1548 struct btrfs_root *root = arg;
1549 struct btrfs_fs_info *fs_info = root->fs_info;
1550 struct btrfs_trans_handle *trans;
1551 struct btrfs_transaction *cur;
1554 unsigned long delay;
1558 cannot_commit = false;
1559 delay = msecs_to_jiffies(fs_info->commit_interval * 1000);
1560 mutex_lock(&fs_info->transaction_kthread_mutex);
1562 spin_lock(&fs_info->trans_lock);
1563 cur = fs_info->running_transaction;
1565 spin_unlock(&fs_info->trans_lock);
1569 delta = ktime_get_seconds() - cur->start_time;
1570 if (!test_and_clear_bit(BTRFS_FS_COMMIT_TRANS, &fs_info->flags) &&
1571 cur->state < TRANS_STATE_COMMIT_PREP &&
1572 delta < fs_info->commit_interval) {
1573 spin_unlock(&fs_info->trans_lock);
1574 delay -= msecs_to_jiffies((delta - 1) * 1000);
1576 msecs_to_jiffies(fs_info->commit_interval * 1000));
1579 transid = cur->transid;
1580 spin_unlock(&fs_info->trans_lock);
1582 /* If the file system is aborted, this will always fail. */
1583 trans = btrfs_attach_transaction(root);
1584 if (IS_ERR(trans)) {
1585 if (PTR_ERR(trans) != -ENOENT)
1586 cannot_commit = true;
1589 if (transid == trans->transid) {
1590 btrfs_commit_transaction(trans);
1592 btrfs_end_transaction(trans);
1595 wake_up_process(fs_info->cleaner_kthread);
1596 mutex_unlock(&fs_info->transaction_kthread_mutex);
1598 if (BTRFS_FS_ERROR(fs_info))
1599 btrfs_cleanup_transaction(fs_info);
1600 if (!kthread_should_stop() &&
1601 (!btrfs_transaction_blocked(fs_info) ||
1603 schedule_timeout_interruptible(delay);
1604 } while (!kthread_should_stop());
1609 * This will find the highest generation in the array of root backups. The
1610 * index of the highest array is returned, or -EINVAL if we can't find
1613 * We check to make sure the array is valid by comparing the
1614 * generation of the latest root in the array with the generation
1615 * in the super block. If they don't match we pitch it.
1617 static int find_newest_super_backup(struct btrfs_fs_info *info)
1619 const u64 newest_gen = btrfs_super_generation(info->super_copy);
1621 struct btrfs_root_backup *root_backup;
1624 for (i = 0; i < BTRFS_NUM_BACKUP_ROOTS; i++) {
1625 root_backup = info->super_copy->super_roots + i;
1626 cur = btrfs_backup_tree_root_gen(root_backup);
1627 if (cur == newest_gen)
1635 * copy all the root pointers into the super backup array.
1636 * this will bump the backup pointer by one when it is
1639 static void backup_super_roots(struct btrfs_fs_info *info)
1641 const int next_backup = info->backup_root_index;
1642 struct btrfs_root_backup *root_backup;
1644 root_backup = info->super_for_commit->super_roots + next_backup;
1647 * make sure all of our padding and empty slots get zero filled
1648 * regardless of which ones we use today
1650 memset(root_backup, 0, sizeof(*root_backup));
1652 info->backup_root_index = (next_backup + 1) % BTRFS_NUM_BACKUP_ROOTS;
1654 btrfs_set_backup_tree_root(root_backup, info->tree_root->node->start);
1655 btrfs_set_backup_tree_root_gen(root_backup,
1656 btrfs_header_generation(info->tree_root->node));
1658 btrfs_set_backup_tree_root_level(root_backup,
1659 btrfs_header_level(info->tree_root->node));
1661 btrfs_set_backup_chunk_root(root_backup, info->chunk_root->node->start);
1662 btrfs_set_backup_chunk_root_gen(root_backup,
1663 btrfs_header_generation(info->chunk_root->node));
1664 btrfs_set_backup_chunk_root_level(root_backup,
1665 btrfs_header_level(info->chunk_root->node));
1667 if (!btrfs_fs_compat_ro(info, BLOCK_GROUP_TREE)) {
1668 struct btrfs_root *extent_root = btrfs_extent_root(info, 0);
1669 struct btrfs_root *csum_root = btrfs_csum_root(info, 0);
1671 btrfs_set_backup_extent_root(root_backup,
1672 extent_root->node->start);
1673 btrfs_set_backup_extent_root_gen(root_backup,
1674 btrfs_header_generation(extent_root->node));
1675 btrfs_set_backup_extent_root_level(root_backup,
1676 btrfs_header_level(extent_root->node));
1678 btrfs_set_backup_csum_root(root_backup, csum_root->node->start);
1679 btrfs_set_backup_csum_root_gen(root_backup,
1680 btrfs_header_generation(csum_root->node));
1681 btrfs_set_backup_csum_root_level(root_backup,
1682 btrfs_header_level(csum_root->node));
1686 * we might commit during log recovery, which happens before we set
1687 * the fs_root. Make sure it is valid before we fill it in.
1689 if (info->fs_root && info->fs_root->node) {
1690 btrfs_set_backup_fs_root(root_backup,
1691 info->fs_root->node->start);
1692 btrfs_set_backup_fs_root_gen(root_backup,
1693 btrfs_header_generation(info->fs_root->node));
1694 btrfs_set_backup_fs_root_level(root_backup,
1695 btrfs_header_level(info->fs_root->node));
1698 btrfs_set_backup_dev_root(root_backup, info->dev_root->node->start);
1699 btrfs_set_backup_dev_root_gen(root_backup,
1700 btrfs_header_generation(info->dev_root->node));
1701 btrfs_set_backup_dev_root_level(root_backup,
1702 btrfs_header_level(info->dev_root->node));
1704 btrfs_set_backup_total_bytes(root_backup,
1705 btrfs_super_total_bytes(info->super_copy));
1706 btrfs_set_backup_bytes_used(root_backup,
1707 btrfs_super_bytes_used(info->super_copy));
1708 btrfs_set_backup_num_devices(root_backup,
1709 btrfs_super_num_devices(info->super_copy));
1712 * if we don't copy this out to the super_copy, it won't get remembered
1713 * for the next commit
1715 memcpy(&info->super_copy->super_roots,
1716 &info->super_for_commit->super_roots,
1717 sizeof(*root_backup) * BTRFS_NUM_BACKUP_ROOTS);
1721 * Reads a backup root based on the passed priority. Prio 0 is the newest, prio
1722 * 1/2/3 are 2nd newest/3rd newest/4th (oldest) backup roots
1724 * @fs_info: filesystem whose backup roots need to be read
1725 * @priority: priority of backup root required
1727 * Returns backup root index on success and -EINVAL otherwise.
1729 static int read_backup_root(struct btrfs_fs_info *fs_info, u8 priority)
1731 int backup_index = find_newest_super_backup(fs_info);
1732 struct btrfs_super_block *super = fs_info->super_copy;
1733 struct btrfs_root_backup *root_backup;
1735 if (priority < BTRFS_NUM_BACKUP_ROOTS && backup_index >= 0) {
1737 return backup_index;
1739 backup_index = backup_index + BTRFS_NUM_BACKUP_ROOTS - priority;
1740 backup_index %= BTRFS_NUM_BACKUP_ROOTS;
1745 root_backup = super->super_roots + backup_index;
1747 btrfs_set_super_generation(super,
1748 btrfs_backup_tree_root_gen(root_backup));
1749 btrfs_set_super_root(super, btrfs_backup_tree_root(root_backup));
1750 btrfs_set_super_root_level(super,
1751 btrfs_backup_tree_root_level(root_backup));
1752 btrfs_set_super_bytes_used(super, btrfs_backup_bytes_used(root_backup));
1755 * Fixme: the total bytes and num_devices need to match or we should
1758 btrfs_set_super_total_bytes(super, btrfs_backup_total_bytes(root_backup));
1759 btrfs_set_super_num_devices(super, btrfs_backup_num_devices(root_backup));
1761 return backup_index;
1764 /* helper to cleanup workers */
1765 static void btrfs_stop_all_workers(struct btrfs_fs_info *fs_info)
1767 btrfs_destroy_workqueue(fs_info->fixup_workers);
1768 btrfs_destroy_workqueue(fs_info->delalloc_workers);
1769 btrfs_destroy_workqueue(fs_info->workers);
1770 if (fs_info->endio_workers)
1771 destroy_workqueue(fs_info->endio_workers);
1772 if (fs_info->rmw_workers)
1773 destroy_workqueue(fs_info->rmw_workers);
1774 if (fs_info->compressed_write_workers)
1775 destroy_workqueue(fs_info->compressed_write_workers);
1776 btrfs_destroy_workqueue(fs_info->endio_write_workers);
1777 btrfs_destroy_workqueue(fs_info->endio_freespace_worker);
1778 btrfs_destroy_workqueue(fs_info->delayed_workers);
1779 btrfs_destroy_workqueue(fs_info->caching_workers);
1780 btrfs_destroy_workqueue(fs_info->flush_workers);
1781 btrfs_destroy_workqueue(fs_info->qgroup_rescan_workers);
1782 if (fs_info->discard_ctl.discard_workers)
1783 destroy_workqueue(fs_info->discard_ctl.discard_workers);
1785 * Now that all other work queues are destroyed, we can safely destroy
1786 * the queues used for metadata I/O, since tasks from those other work
1787 * queues can do metadata I/O operations.
1789 if (fs_info->endio_meta_workers)
1790 destroy_workqueue(fs_info->endio_meta_workers);
1793 static void free_root_extent_buffers(struct btrfs_root *root)
1796 free_extent_buffer(root->node);
1797 free_extent_buffer(root->commit_root);
1799 root->commit_root = NULL;
1803 static void free_global_root_pointers(struct btrfs_fs_info *fs_info)
1805 struct btrfs_root *root, *tmp;
1807 rbtree_postorder_for_each_entry_safe(root, tmp,
1808 &fs_info->global_root_tree,
1810 free_root_extent_buffers(root);
1813 /* helper to cleanup tree roots */
1814 static void free_root_pointers(struct btrfs_fs_info *info, bool free_chunk_root)
1816 free_root_extent_buffers(info->tree_root);
1818 free_global_root_pointers(info);
1819 free_root_extent_buffers(info->dev_root);
1820 free_root_extent_buffers(info->quota_root);
1821 free_root_extent_buffers(info->uuid_root);
1822 free_root_extent_buffers(info->fs_root);
1823 free_root_extent_buffers(info->data_reloc_root);
1824 free_root_extent_buffers(info->block_group_root);
1825 free_root_extent_buffers(info->stripe_root);
1826 if (free_chunk_root)
1827 free_root_extent_buffers(info->chunk_root);
1830 void btrfs_put_root(struct btrfs_root *root)
1835 if (refcount_dec_and_test(&root->refs)) {
1836 WARN_ON(!RB_EMPTY_ROOT(&root->inode_tree));
1837 WARN_ON(test_bit(BTRFS_ROOT_DEAD_RELOC_TREE, &root->state));
1839 free_anon_bdev(root->anon_dev);
1840 free_root_extent_buffers(root);
1841 #ifdef CONFIG_BTRFS_DEBUG
1842 spin_lock(&root->fs_info->fs_roots_radix_lock);
1843 list_del_init(&root->leak_list);
1844 spin_unlock(&root->fs_info->fs_roots_radix_lock);
1850 void btrfs_free_fs_roots(struct btrfs_fs_info *fs_info)
1853 struct btrfs_root *gang[8];
1856 while (!list_empty(&fs_info->dead_roots)) {
1857 gang[0] = list_entry(fs_info->dead_roots.next,
1858 struct btrfs_root, root_list);
1859 list_del(&gang[0]->root_list);
1861 if (test_bit(BTRFS_ROOT_IN_RADIX, &gang[0]->state))
1862 btrfs_drop_and_free_fs_root(fs_info, gang[0]);
1863 btrfs_put_root(gang[0]);
1867 ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
1872 for (i = 0; i < ret; i++)
1873 btrfs_drop_and_free_fs_root(fs_info, gang[i]);
1877 static void btrfs_init_scrub(struct btrfs_fs_info *fs_info)
1879 mutex_init(&fs_info->scrub_lock);
1880 atomic_set(&fs_info->scrubs_running, 0);
1881 atomic_set(&fs_info->scrub_pause_req, 0);
1882 atomic_set(&fs_info->scrubs_paused, 0);
1883 atomic_set(&fs_info->scrub_cancel_req, 0);
1884 init_waitqueue_head(&fs_info->scrub_pause_wait);
1885 refcount_set(&fs_info->scrub_workers_refcnt, 0);
1888 static void btrfs_init_balance(struct btrfs_fs_info *fs_info)
1890 spin_lock_init(&fs_info->balance_lock);
1891 mutex_init(&fs_info->balance_mutex);
1892 atomic_set(&fs_info->balance_pause_req, 0);
1893 atomic_set(&fs_info->balance_cancel_req, 0);
1894 fs_info->balance_ctl = NULL;
1895 init_waitqueue_head(&fs_info->balance_wait_q);
1896 atomic_set(&fs_info->reloc_cancel_req, 0);
1899 static int btrfs_init_btree_inode(struct super_block *sb)
1901 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
1902 unsigned long hash = btrfs_inode_hash(BTRFS_BTREE_INODE_OBJECTID,
1903 fs_info->tree_root);
1904 struct inode *inode;
1906 inode = new_inode(sb);
1910 inode->i_ino = BTRFS_BTREE_INODE_OBJECTID;
1911 set_nlink(inode, 1);
1913 * we set the i_size on the btree inode to the max possible int.
1914 * the real end of the address space is determined by all of
1915 * the devices in the system
1917 inode->i_size = OFFSET_MAX;
1918 inode->i_mapping->a_ops = &btree_aops;
1919 mapping_set_gfp_mask(inode->i_mapping, GFP_NOFS);
1921 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
1922 extent_io_tree_init(fs_info, &BTRFS_I(inode)->io_tree,
1923 IO_TREE_BTREE_INODE_IO);
1924 extent_map_tree_init(&BTRFS_I(inode)->extent_tree);
1926 BTRFS_I(inode)->root = btrfs_grab_root(fs_info->tree_root);
1927 BTRFS_I(inode)->location.objectid = BTRFS_BTREE_INODE_OBJECTID;
1928 BTRFS_I(inode)->location.type = 0;
1929 BTRFS_I(inode)->location.offset = 0;
1930 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
1931 __insert_inode_hash(inode, hash);
1932 fs_info->btree_inode = inode;
1937 static void btrfs_init_dev_replace_locks(struct btrfs_fs_info *fs_info)
1939 mutex_init(&fs_info->dev_replace.lock_finishing_cancel_unmount);
1940 init_rwsem(&fs_info->dev_replace.rwsem);
1941 init_waitqueue_head(&fs_info->dev_replace.replace_wait);
1944 static void btrfs_init_qgroup(struct btrfs_fs_info *fs_info)
1946 spin_lock_init(&fs_info->qgroup_lock);
1947 mutex_init(&fs_info->qgroup_ioctl_lock);
1948 fs_info->qgroup_tree = RB_ROOT;
1949 INIT_LIST_HEAD(&fs_info->dirty_qgroups);
1950 fs_info->qgroup_seq = 1;
1951 fs_info->qgroup_ulist = NULL;
1952 fs_info->qgroup_rescan_running = false;
1953 fs_info->qgroup_drop_subtree_thres = BTRFS_MAX_LEVEL;
1954 mutex_init(&fs_info->qgroup_rescan_lock);
1957 static int btrfs_init_workqueues(struct btrfs_fs_info *fs_info)
1959 u32 max_active = fs_info->thread_pool_size;
1960 unsigned int flags = WQ_MEM_RECLAIM | WQ_FREEZABLE | WQ_UNBOUND;
1961 unsigned int ordered_flags = WQ_MEM_RECLAIM | WQ_FREEZABLE;
1964 btrfs_alloc_workqueue(fs_info, "worker", flags, max_active, 16);
1966 fs_info->delalloc_workers =
1967 btrfs_alloc_workqueue(fs_info, "delalloc",
1968 flags, max_active, 2);
1970 fs_info->flush_workers =
1971 btrfs_alloc_workqueue(fs_info, "flush_delalloc",
1972 flags, max_active, 0);
1974 fs_info->caching_workers =
1975 btrfs_alloc_workqueue(fs_info, "cache", flags, max_active, 0);
1977 fs_info->fixup_workers =
1978 btrfs_alloc_ordered_workqueue(fs_info, "fixup", ordered_flags);
1980 fs_info->endio_workers =
1981 alloc_workqueue("btrfs-endio", flags, max_active);
1982 fs_info->endio_meta_workers =
1983 alloc_workqueue("btrfs-endio-meta", flags, max_active);
1984 fs_info->rmw_workers = alloc_workqueue("btrfs-rmw", flags, max_active);
1985 fs_info->endio_write_workers =
1986 btrfs_alloc_workqueue(fs_info, "endio-write", flags,
1988 fs_info->compressed_write_workers =
1989 alloc_workqueue("btrfs-compressed-write", flags, max_active);
1990 fs_info->endio_freespace_worker =
1991 btrfs_alloc_workqueue(fs_info, "freespace-write", flags,
1993 fs_info->delayed_workers =
1994 btrfs_alloc_workqueue(fs_info, "delayed-meta", flags,
1996 fs_info->qgroup_rescan_workers =
1997 btrfs_alloc_ordered_workqueue(fs_info, "qgroup-rescan",
1999 fs_info->discard_ctl.discard_workers =
2000 alloc_ordered_workqueue("btrfs_discard", WQ_FREEZABLE);
2002 if (!(fs_info->workers &&
2003 fs_info->delalloc_workers && fs_info->flush_workers &&
2004 fs_info->endio_workers && fs_info->endio_meta_workers &&
2005 fs_info->compressed_write_workers &&
2006 fs_info->endio_write_workers &&
2007 fs_info->endio_freespace_worker && fs_info->rmw_workers &&
2008 fs_info->caching_workers && fs_info->fixup_workers &&
2009 fs_info->delayed_workers && fs_info->qgroup_rescan_workers &&
2010 fs_info->discard_ctl.discard_workers)) {
2017 static int btrfs_init_csum_hash(struct btrfs_fs_info *fs_info, u16 csum_type)
2019 struct crypto_shash *csum_shash;
2020 const char *csum_driver = btrfs_super_csum_driver(csum_type);
2022 csum_shash = crypto_alloc_shash(csum_driver, 0, 0);
2024 if (IS_ERR(csum_shash)) {
2025 btrfs_err(fs_info, "error allocating %s hash for checksum",
2027 return PTR_ERR(csum_shash);
2030 fs_info->csum_shash = csum_shash;
2033 * Check if the checksum implementation is a fast accelerated one.
2034 * As-is this is a bit of a hack and should be replaced once the csum
2035 * implementations provide that information themselves.
2037 switch (csum_type) {
2038 case BTRFS_CSUM_TYPE_CRC32:
2039 if (!strstr(crypto_shash_driver_name(csum_shash), "generic"))
2040 set_bit(BTRFS_FS_CSUM_IMPL_FAST, &fs_info->flags);
2042 case BTRFS_CSUM_TYPE_XXHASH:
2043 set_bit(BTRFS_FS_CSUM_IMPL_FAST, &fs_info->flags);
2049 btrfs_info(fs_info, "using %s (%s) checksum algorithm",
2050 btrfs_super_csum_name(csum_type),
2051 crypto_shash_driver_name(csum_shash));
2055 static int btrfs_replay_log(struct btrfs_fs_info *fs_info,
2056 struct btrfs_fs_devices *fs_devices)
2059 struct btrfs_tree_parent_check check = { 0 };
2060 struct btrfs_root *log_tree_root;
2061 struct btrfs_super_block *disk_super = fs_info->super_copy;
2062 u64 bytenr = btrfs_super_log_root(disk_super);
2063 int level = btrfs_super_log_root_level(disk_super);
2065 if (fs_devices->rw_devices == 0) {
2066 btrfs_warn(fs_info, "log replay required on RO media");
2070 log_tree_root = btrfs_alloc_root(fs_info, BTRFS_TREE_LOG_OBJECTID,
2075 check.level = level;
2076 check.transid = fs_info->generation + 1;
2077 check.owner_root = BTRFS_TREE_LOG_OBJECTID;
2078 log_tree_root->node = read_tree_block(fs_info, bytenr, &check);
2079 if (IS_ERR(log_tree_root->node)) {
2080 btrfs_warn(fs_info, "failed to read log tree");
2081 ret = PTR_ERR(log_tree_root->node);
2082 log_tree_root->node = NULL;
2083 btrfs_put_root(log_tree_root);
2086 if (!extent_buffer_uptodate(log_tree_root->node)) {
2087 btrfs_err(fs_info, "failed to read log tree");
2088 btrfs_put_root(log_tree_root);
2092 /* returns with log_tree_root freed on success */
2093 ret = btrfs_recover_log_trees(log_tree_root);
2095 btrfs_handle_fs_error(fs_info, ret,
2096 "Failed to recover log tree");
2097 btrfs_put_root(log_tree_root);
2101 if (sb_rdonly(fs_info->sb)) {
2102 ret = btrfs_commit_super(fs_info);
2110 static int load_global_roots_objectid(struct btrfs_root *tree_root,
2111 struct btrfs_path *path, u64 objectid,
2114 struct btrfs_fs_info *fs_info = tree_root->fs_info;
2115 struct btrfs_root *root;
2116 u64 max_global_id = 0;
2118 struct btrfs_key key = {
2119 .objectid = objectid,
2120 .type = BTRFS_ROOT_ITEM_KEY,
2125 /* If we have IGNOREDATACSUMS skip loading these roots. */
2126 if (objectid == BTRFS_CSUM_TREE_OBJECTID &&
2127 btrfs_test_opt(fs_info, IGNOREDATACSUMS)) {
2128 set_bit(BTRFS_FS_STATE_NO_CSUMS, &fs_info->fs_state);
2133 ret = btrfs_search_slot(NULL, tree_root, &key, path, 0, 0);
2137 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
2138 ret = btrfs_next_leaf(tree_root, path);
2147 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
2148 if (key.objectid != objectid)
2150 btrfs_release_path(path);
2153 * Just worry about this for extent tree, it'll be the same for
2156 if (objectid == BTRFS_EXTENT_TREE_OBJECTID)
2157 max_global_id = max(max_global_id, key.offset);
2160 root = read_tree_root_path(tree_root, path, &key);
2162 if (!btrfs_test_opt(fs_info, IGNOREBADROOTS))
2163 ret = PTR_ERR(root);
2166 set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2167 ret = btrfs_global_root_insert(root);
2169 btrfs_put_root(root);
2174 btrfs_release_path(path);
2176 if (objectid == BTRFS_EXTENT_TREE_OBJECTID)
2177 fs_info->nr_global_roots = max_global_id + 1;
2179 if (!found || ret) {
2180 if (objectid == BTRFS_CSUM_TREE_OBJECTID)
2181 set_bit(BTRFS_FS_STATE_NO_CSUMS, &fs_info->fs_state);
2183 if (!btrfs_test_opt(fs_info, IGNOREBADROOTS))
2184 ret = ret ? ret : -ENOENT;
2187 btrfs_err(fs_info, "failed to load root %s", name);
2192 static int load_global_roots(struct btrfs_root *tree_root)
2194 struct btrfs_path *path;
2197 path = btrfs_alloc_path();
2201 ret = load_global_roots_objectid(tree_root, path,
2202 BTRFS_EXTENT_TREE_OBJECTID, "extent");
2205 ret = load_global_roots_objectid(tree_root, path,
2206 BTRFS_CSUM_TREE_OBJECTID, "csum");
2209 if (!btrfs_fs_compat_ro(tree_root->fs_info, FREE_SPACE_TREE))
2211 ret = load_global_roots_objectid(tree_root, path,
2212 BTRFS_FREE_SPACE_TREE_OBJECTID,
2215 btrfs_free_path(path);
2219 static int btrfs_read_roots(struct btrfs_fs_info *fs_info)
2221 struct btrfs_root *tree_root = fs_info->tree_root;
2222 struct btrfs_root *root;
2223 struct btrfs_key location;
2226 BUG_ON(!fs_info->tree_root);
2228 ret = load_global_roots(tree_root);
2232 location.type = BTRFS_ROOT_ITEM_KEY;
2233 location.offset = 0;
2235 if (btrfs_fs_compat_ro(fs_info, BLOCK_GROUP_TREE)) {
2236 location.objectid = BTRFS_BLOCK_GROUP_TREE_OBJECTID;
2237 root = btrfs_read_tree_root(tree_root, &location);
2239 if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2240 ret = PTR_ERR(root);
2244 set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2245 fs_info->block_group_root = root;
2249 location.objectid = BTRFS_DEV_TREE_OBJECTID;
2250 root = btrfs_read_tree_root(tree_root, &location);
2252 if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2253 ret = PTR_ERR(root);
2257 set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2258 fs_info->dev_root = root;
2260 /* Initialize fs_info for all devices in any case */
2261 ret = btrfs_init_devices_late(fs_info);
2266 * This tree can share blocks with some other fs tree during relocation
2267 * and we need a proper setup by btrfs_get_fs_root
2269 root = btrfs_get_fs_root(tree_root->fs_info,
2270 BTRFS_DATA_RELOC_TREE_OBJECTID, true);
2272 if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2273 ret = PTR_ERR(root);
2277 set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2278 fs_info->data_reloc_root = root;
2281 location.objectid = BTRFS_QUOTA_TREE_OBJECTID;
2282 root = btrfs_read_tree_root(tree_root, &location);
2283 if (!IS_ERR(root)) {
2284 set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2285 fs_info->quota_root = root;
2288 location.objectid = BTRFS_UUID_TREE_OBJECTID;
2289 root = btrfs_read_tree_root(tree_root, &location);
2291 if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2292 ret = PTR_ERR(root);
2297 set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2298 fs_info->uuid_root = root;
2301 if (btrfs_fs_incompat(fs_info, RAID_STRIPE_TREE)) {
2302 location.objectid = BTRFS_RAID_STRIPE_TREE_OBJECTID;
2303 root = btrfs_read_tree_root(tree_root, &location);
2305 if (!btrfs_test_opt(fs_info, IGNOREBADROOTS)) {
2306 ret = PTR_ERR(root);
2310 set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2311 fs_info->stripe_root = root;
2317 btrfs_warn(fs_info, "failed to read root (objectid=%llu): %d",
2318 location.objectid, ret);
2323 * Real super block validation
2324 * NOTE: super csum type and incompat features will not be checked here.
2326 * @sb: super block to check
2327 * @mirror_num: the super block number to check its bytenr:
2328 * 0 the primary (1st) sb
2329 * 1, 2 2nd and 3rd backup copy
2330 * -1 skip bytenr check
2332 int btrfs_validate_super(struct btrfs_fs_info *fs_info,
2333 struct btrfs_super_block *sb, int mirror_num)
2335 u64 nodesize = btrfs_super_nodesize(sb);
2336 u64 sectorsize = btrfs_super_sectorsize(sb);
2339 if (btrfs_super_magic(sb) != BTRFS_MAGIC) {
2340 btrfs_err(fs_info, "no valid FS found");
2343 if (btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP) {
2344 btrfs_err(fs_info, "unrecognized or unsupported super flag: %llu",
2345 btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP);
2348 if (btrfs_super_root_level(sb) >= BTRFS_MAX_LEVEL) {
2349 btrfs_err(fs_info, "tree_root level too big: %d >= %d",
2350 btrfs_super_root_level(sb), BTRFS_MAX_LEVEL);
2353 if (btrfs_super_chunk_root_level(sb) >= BTRFS_MAX_LEVEL) {
2354 btrfs_err(fs_info, "chunk_root level too big: %d >= %d",
2355 btrfs_super_chunk_root_level(sb), BTRFS_MAX_LEVEL);
2358 if (btrfs_super_log_root_level(sb) >= BTRFS_MAX_LEVEL) {
2359 btrfs_err(fs_info, "log_root level too big: %d >= %d",
2360 btrfs_super_log_root_level(sb), BTRFS_MAX_LEVEL);
2365 * Check sectorsize and nodesize first, other check will need it.
2366 * Check all possible sectorsize(4K, 8K, 16K, 32K, 64K) here.
2368 if (!is_power_of_2(sectorsize) || sectorsize < 4096 ||
2369 sectorsize > BTRFS_MAX_METADATA_BLOCKSIZE) {
2370 btrfs_err(fs_info, "invalid sectorsize %llu", sectorsize);
2375 * We only support at most two sectorsizes: 4K and PAGE_SIZE.
2377 * We can support 16K sectorsize with 64K page size without problem,
2378 * but such sectorsize/pagesize combination doesn't make much sense.
2379 * 4K will be our future standard, PAGE_SIZE is supported from the very
2382 if (sectorsize > PAGE_SIZE || (sectorsize != SZ_4K && sectorsize != PAGE_SIZE)) {
2384 "sectorsize %llu not yet supported for page size %lu",
2385 sectorsize, PAGE_SIZE);
2389 if (!is_power_of_2(nodesize) || nodesize < sectorsize ||
2390 nodesize > BTRFS_MAX_METADATA_BLOCKSIZE) {
2391 btrfs_err(fs_info, "invalid nodesize %llu", nodesize);
2394 if (nodesize != le32_to_cpu(sb->__unused_leafsize)) {
2395 btrfs_err(fs_info, "invalid leafsize %u, should be %llu",
2396 le32_to_cpu(sb->__unused_leafsize), nodesize);
2400 /* Root alignment check */
2401 if (!IS_ALIGNED(btrfs_super_root(sb), sectorsize)) {
2402 btrfs_warn(fs_info, "tree_root block unaligned: %llu",
2403 btrfs_super_root(sb));
2406 if (!IS_ALIGNED(btrfs_super_chunk_root(sb), sectorsize)) {
2407 btrfs_warn(fs_info, "chunk_root block unaligned: %llu",
2408 btrfs_super_chunk_root(sb));
2411 if (!IS_ALIGNED(btrfs_super_log_root(sb), sectorsize)) {
2412 btrfs_warn(fs_info, "log_root block unaligned: %llu",
2413 btrfs_super_log_root(sb));
2417 if (!fs_info->fs_devices->temp_fsid &&
2418 memcmp(fs_info->fs_devices->fsid, sb->fsid, BTRFS_FSID_SIZE) != 0) {
2420 "superblock fsid doesn't match fsid of fs_devices: %pU != %pU",
2421 sb->fsid, fs_info->fs_devices->fsid);
2425 if (memcmp(fs_info->fs_devices->metadata_uuid, btrfs_sb_fsid_ptr(sb),
2426 BTRFS_FSID_SIZE) != 0) {
2428 "superblock metadata_uuid doesn't match metadata uuid of fs_devices: %pU != %pU",
2429 btrfs_sb_fsid_ptr(sb), fs_info->fs_devices->metadata_uuid);
2433 if (memcmp(fs_info->fs_devices->metadata_uuid, sb->dev_item.fsid,
2434 BTRFS_FSID_SIZE) != 0) {
2436 "dev_item UUID does not match metadata fsid: %pU != %pU",
2437 fs_info->fs_devices->metadata_uuid, sb->dev_item.fsid);
2442 * Artificial requirement for block-group-tree to force newer features
2443 * (free-space-tree, no-holes) so the test matrix is smaller.
2445 if (btrfs_fs_compat_ro(fs_info, BLOCK_GROUP_TREE) &&
2446 (!btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE_VALID) ||
2447 !btrfs_fs_incompat(fs_info, NO_HOLES))) {
2449 "block-group-tree feature requires fres-space-tree and no-holes");
2454 * Hint to catch really bogus numbers, bitflips or so, more exact checks are
2457 if (btrfs_super_bytes_used(sb) < 6 * btrfs_super_nodesize(sb)) {
2458 btrfs_err(fs_info, "bytes_used is too small %llu",
2459 btrfs_super_bytes_used(sb));
2462 if (!is_power_of_2(btrfs_super_stripesize(sb))) {
2463 btrfs_err(fs_info, "invalid stripesize %u",
2464 btrfs_super_stripesize(sb));
2467 if (btrfs_super_num_devices(sb) > (1UL << 31))
2468 btrfs_warn(fs_info, "suspicious number of devices: %llu",
2469 btrfs_super_num_devices(sb));
2470 if (btrfs_super_num_devices(sb) == 0) {
2471 btrfs_err(fs_info, "number of devices is 0");
2475 if (mirror_num >= 0 &&
2476 btrfs_super_bytenr(sb) != btrfs_sb_offset(mirror_num)) {
2477 btrfs_err(fs_info, "super offset mismatch %llu != %u",
2478 btrfs_super_bytenr(sb), BTRFS_SUPER_INFO_OFFSET);
2483 * Obvious sys_chunk_array corruptions, it must hold at least one key
2486 if (btrfs_super_sys_array_size(sb) > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
2487 btrfs_err(fs_info, "system chunk array too big %u > %u",
2488 btrfs_super_sys_array_size(sb),
2489 BTRFS_SYSTEM_CHUNK_ARRAY_SIZE);
2492 if (btrfs_super_sys_array_size(sb) < sizeof(struct btrfs_disk_key)
2493 + sizeof(struct btrfs_chunk)) {
2494 btrfs_err(fs_info, "system chunk array too small %u < %zu",
2495 btrfs_super_sys_array_size(sb),
2496 sizeof(struct btrfs_disk_key)
2497 + sizeof(struct btrfs_chunk));
2502 * The generation is a global counter, we'll trust it more than the others
2503 * but it's still possible that it's the one that's wrong.
2505 if (btrfs_super_generation(sb) < btrfs_super_chunk_root_generation(sb))
2507 "suspicious: generation < chunk_root_generation: %llu < %llu",
2508 btrfs_super_generation(sb),
2509 btrfs_super_chunk_root_generation(sb));
2510 if (btrfs_super_generation(sb) < btrfs_super_cache_generation(sb)
2511 && btrfs_super_cache_generation(sb) != (u64)-1)
2513 "suspicious: generation < cache_generation: %llu < %llu",
2514 btrfs_super_generation(sb),
2515 btrfs_super_cache_generation(sb));
2521 * Validation of super block at mount time.
2522 * Some checks already done early at mount time, like csum type and incompat
2523 * flags will be skipped.
2525 static int btrfs_validate_mount_super(struct btrfs_fs_info *fs_info)
2527 return btrfs_validate_super(fs_info, fs_info->super_copy, 0);
2531 * Validation of super block at write time.
2532 * Some checks like bytenr check will be skipped as their values will be
2534 * Extra checks like csum type and incompat flags will be done here.
2536 static int btrfs_validate_write_super(struct btrfs_fs_info *fs_info,
2537 struct btrfs_super_block *sb)
2541 ret = btrfs_validate_super(fs_info, sb, -1);
2544 if (!btrfs_supported_super_csum(btrfs_super_csum_type(sb))) {
2546 btrfs_err(fs_info, "invalid csum type, has %u want %u",
2547 btrfs_super_csum_type(sb), BTRFS_CSUM_TYPE_CRC32);
2550 if (btrfs_super_incompat_flags(sb) & ~BTRFS_FEATURE_INCOMPAT_SUPP) {
2553 "invalid incompat flags, has 0x%llx valid mask 0x%llx",
2554 btrfs_super_incompat_flags(sb),
2555 (unsigned long long)BTRFS_FEATURE_INCOMPAT_SUPP);
2561 "super block corruption detected before writing it to disk");
2565 static int load_super_root(struct btrfs_root *root, u64 bytenr, u64 gen, int level)
2567 struct btrfs_tree_parent_check check = {
2570 .owner_root = root->root_key.objectid
2574 root->node = read_tree_block(root->fs_info, bytenr, &check);
2575 if (IS_ERR(root->node)) {
2576 ret = PTR_ERR(root->node);
2580 if (!extent_buffer_uptodate(root->node)) {
2581 free_extent_buffer(root->node);
2586 btrfs_set_root_node(&root->root_item, root->node);
2587 root->commit_root = btrfs_root_node(root);
2588 btrfs_set_root_refs(&root->root_item, 1);
2592 static int load_important_roots(struct btrfs_fs_info *fs_info)
2594 struct btrfs_super_block *sb = fs_info->super_copy;
2598 bytenr = btrfs_super_root(sb);
2599 gen = btrfs_super_generation(sb);
2600 level = btrfs_super_root_level(sb);
2601 ret = load_super_root(fs_info->tree_root, bytenr, gen, level);
2603 btrfs_warn(fs_info, "couldn't read tree root");
2609 static int __cold init_tree_roots(struct btrfs_fs_info *fs_info)
2611 int backup_index = find_newest_super_backup(fs_info);
2612 struct btrfs_super_block *sb = fs_info->super_copy;
2613 struct btrfs_root *tree_root = fs_info->tree_root;
2614 bool handle_error = false;
2618 for (i = 0; i < BTRFS_NUM_BACKUP_ROOTS; i++) {
2620 if (!IS_ERR(tree_root->node))
2621 free_extent_buffer(tree_root->node);
2622 tree_root->node = NULL;
2624 if (!btrfs_test_opt(fs_info, USEBACKUPROOT))
2627 free_root_pointers(fs_info, 0);
2630 * Don't use the log in recovery mode, it won't be
2633 btrfs_set_super_log_root(sb, 0);
2635 btrfs_warn(fs_info, "try to load backup roots slot %d", i);
2636 ret = read_backup_root(fs_info, i);
2642 ret = load_important_roots(fs_info);
2644 handle_error = true;
2649 * No need to hold btrfs_root::objectid_mutex since the fs
2650 * hasn't been fully initialised and we are the only user
2652 ret = btrfs_init_root_free_objectid(tree_root);
2654 handle_error = true;
2658 ASSERT(tree_root->free_objectid <= BTRFS_LAST_FREE_OBJECTID);
2660 ret = btrfs_read_roots(fs_info);
2662 handle_error = true;
2666 /* All successful */
2667 fs_info->generation = btrfs_header_generation(tree_root->node);
2668 btrfs_set_last_trans_committed(fs_info, fs_info->generation);
2669 fs_info->last_reloc_trans = 0;
2671 /* Always begin writing backup roots after the one being used */
2672 if (backup_index < 0) {
2673 fs_info->backup_root_index = 0;
2675 fs_info->backup_root_index = backup_index + 1;
2676 fs_info->backup_root_index %= BTRFS_NUM_BACKUP_ROOTS;
2684 void btrfs_init_fs_info(struct btrfs_fs_info *fs_info)
2686 INIT_RADIX_TREE(&fs_info->fs_roots_radix, GFP_ATOMIC);
2687 INIT_RADIX_TREE(&fs_info->buffer_radix, GFP_ATOMIC);
2688 INIT_LIST_HEAD(&fs_info->trans_list);
2689 INIT_LIST_HEAD(&fs_info->dead_roots);
2690 INIT_LIST_HEAD(&fs_info->delayed_iputs);
2691 INIT_LIST_HEAD(&fs_info->delalloc_roots);
2692 INIT_LIST_HEAD(&fs_info->caching_block_groups);
2693 spin_lock_init(&fs_info->delalloc_root_lock);
2694 spin_lock_init(&fs_info->trans_lock);
2695 spin_lock_init(&fs_info->fs_roots_radix_lock);
2696 spin_lock_init(&fs_info->delayed_iput_lock);
2697 spin_lock_init(&fs_info->defrag_inodes_lock);
2698 spin_lock_init(&fs_info->super_lock);
2699 spin_lock_init(&fs_info->buffer_lock);
2700 spin_lock_init(&fs_info->unused_bgs_lock);
2701 spin_lock_init(&fs_info->treelog_bg_lock);
2702 spin_lock_init(&fs_info->zone_active_bgs_lock);
2703 spin_lock_init(&fs_info->relocation_bg_lock);
2704 rwlock_init(&fs_info->tree_mod_log_lock);
2705 rwlock_init(&fs_info->global_root_lock);
2706 mutex_init(&fs_info->unused_bg_unpin_mutex);
2707 mutex_init(&fs_info->reclaim_bgs_lock);
2708 mutex_init(&fs_info->reloc_mutex);
2709 mutex_init(&fs_info->delalloc_root_mutex);
2710 mutex_init(&fs_info->zoned_meta_io_lock);
2711 mutex_init(&fs_info->zoned_data_reloc_io_lock);
2712 seqlock_init(&fs_info->profiles_lock);
2714 btrfs_lockdep_init_map(fs_info, btrfs_trans_num_writers);
2715 btrfs_lockdep_init_map(fs_info, btrfs_trans_num_extwriters);
2716 btrfs_lockdep_init_map(fs_info, btrfs_trans_pending_ordered);
2717 btrfs_lockdep_init_map(fs_info, btrfs_ordered_extent);
2718 btrfs_state_lockdep_init_map(fs_info, btrfs_trans_commit_prep,
2719 BTRFS_LOCKDEP_TRANS_COMMIT_PREP);
2720 btrfs_state_lockdep_init_map(fs_info, btrfs_trans_unblocked,
2721 BTRFS_LOCKDEP_TRANS_UNBLOCKED);
2722 btrfs_state_lockdep_init_map(fs_info, btrfs_trans_super_committed,
2723 BTRFS_LOCKDEP_TRANS_SUPER_COMMITTED);
2724 btrfs_state_lockdep_init_map(fs_info, btrfs_trans_completed,
2725 BTRFS_LOCKDEP_TRANS_COMPLETED);
2727 INIT_LIST_HEAD(&fs_info->dirty_cowonly_roots);
2728 INIT_LIST_HEAD(&fs_info->space_info);
2729 INIT_LIST_HEAD(&fs_info->tree_mod_seq_list);
2730 INIT_LIST_HEAD(&fs_info->unused_bgs);
2731 INIT_LIST_HEAD(&fs_info->reclaim_bgs);
2732 INIT_LIST_HEAD(&fs_info->zone_active_bgs);
2733 #ifdef CONFIG_BTRFS_DEBUG
2734 INIT_LIST_HEAD(&fs_info->allocated_roots);
2735 INIT_LIST_HEAD(&fs_info->allocated_ebs);
2736 spin_lock_init(&fs_info->eb_leak_lock);
2738 fs_info->mapping_tree = RB_ROOT_CACHED;
2739 rwlock_init(&fs_info->mapping_tree_lock);
2740 btrfs_init_block_rsv(&fs_info->global_block_rsv,
2741 BTRFS_BLOCK_RSV_GLOBAL);
2742 btrfs_init_block_rsv(&fs_info->trans_block_rsv, BTRFS_BLOCK_RSV_TRANS);
2743 btrfs_init_block_rsv(&fs_info->chunk_block_rsv, BTRFS_BLOCK_RSV_CHUNK);
2744 btrfs_init_block_rsv(&fs_info->empty_block_rsv, BTRFS_BLOCK_RSV_EMPTY);
2745 btrfs_init_block_rsv(&fs_info->delayed_block_rsv,
2746 BTRFS_BLOCK_RSV_DELOPS);
2747 btrfs_init_block_rsv(&fs_info->delayed_refs_rsv,
2748 BTRFS_BLOCK_RSV_DELREFS);
2750 atomic_set(&fs_info->async_delalloc_pages, 0);
2751 atomic_set(&fs_info->defrag_running, 0);
2752 atomic_set(&fs_info->nr_delayed_iputs, 0);
2753 atomic64_set(&fs_info->tree_mod_seq, 0);
2754 fs_info->global_root_tree = RB_ROOT;
2755 fs_info->max_inline = BTRFS_DEFAULT_MAX_INLINE;
2756 fs_info->metadata_ratio = 0;
2757 fs_info->defrag_inodes = RB_ROOT;
2758 atomic64_set(&fs_info->free_chunk_space, 0);
2759 fs_info->tree_mod_log = RB_ROOT;
2760 fs_info->commit_interval = BTRFS_DEFAULT_COMMIT_INTERVAL;
2761 btrfs_init_ref_verify(fs_info);
2763 fs_info->thread_pool_size = min_t(unsigned long,
2764 num_online_cpus() + 2, 8);
2766 INIT_LIST_HEAD(&fs_info->ordered_roots);
2767 spin_lock_init(&fs_info->ordered_root_lock);
2769 btrfs_init_scrub(fs_info);
2770 btrfs_init_balance(fs_info);
2771 btrfs_init_async_reclaim_work(fs_info);
2773 rwlock_init(&fs_info->block_group_cache_lock);
2774 fs_info->block_group_cache_tree = RB_ROOT_CACHED;
2776 extent_io_tree_init(fs_info, &fs_info->excluded_extents,
2777 IO_TREE_FS_EXCLUDED_EXTENTS);
2779 mutex_init(&fs_info->ordered_operations_mutex);
2780 mutex_init(&fs_info->tree_log_mutex);
2781 mutex_init(&fs_info->chunk_mutex);
2782 mutex_init(&fs_info->transaction_kthread_mutex);
2783 mutex_init(&fs_info->cleaner_mutex);
2784 mutex_init(&fs_info->ro_block_group_mutex);
2785 init_rwsem(&fs_info->commit_root_sem);
2786 init_rwsem(&fs_info->cleanup_work_sem);
2787 init_rwsem(&fs_info->subvol_sem);
2788 sema_init(&fs_info->uuid_tree_rescan_sem, 1);
2790 btrfs_init_dev_replace_locks(fs_info);
2791 btrfs_init_qgroup(fs_info);
2792 btrfs_discard_init(fs_info);
2794 btrfs_init_free_cluster(&fs_info->meta_alloc_cluster);
2795 btrfs_init_free_cluster(&fs_info->data_alloc_cluster);
2797 init_waitqueue_head(&fs_info->transaction_throttle);
2798 init_waitqueue_head(&fs_info->transaction_wait);
2799 init_waitqueue_head(&fs_info->transaction_blocked_wait);
2800 init_waitqueue_head(&fs_info->async_submit_wait);
2801 init_waitqueue_head(&fs_info->delayed_iputs_wait);
2803 /* Usable values until the real ones are cached from the superblock */
2804 fs_info->nodesize = 4096;
2805 fs_info->sectorsize = 4096;
2806 fs_info->sectorsize_bits = ilog2(4096);
2807 fs_info->stripesize = 4096;
2809 /* Default compress algorithm when user does -o compress */
2810 fs_info->compress_type = BTRFS_COMPRESS_ZLIB;
2812 fs_info->max_extent_size = BTRFS_MAX_EXTENT_SIZE;
2814 spin_lock_init(&fs_info->swapfile_pins_lock);
2815 fs_info->swapfile_pins = RB_ROOT;
2817 fs_info->bg_reclaim_threshold = BTRFS_DEFAULT_RECLAIM_THRESH;
2818 INIT_WORK(&fs_info->reclaim_bgs_work, btrfs_reclaim_bgs_work);
2821 static int init_mount_fs_info(struct btrfs_fs_info *fs_info, struct super_block *sb)
2826 sb->s_blocksize = BTRFS_BDEV_BLOCKSIZE;
2827 sb->s_blocksize_bits = blksize_bits(BTRFS_BDEV_BLOCKSIZE);
2829 ret = percpu_counter_init(&fs_info->ordered_bytes, 0, GFP_KERNEL);
2833 ret = percpu_counter_init(&fs_info->dirty_metadata_bytes, 0, GFP_KERNEL);
2837 fs_info->dirty_metadata_batch = PAGE_SIZE *
2838 (1 + ilog2(nr_cpu_ids));
2840 ret = percpu_counter_init(&fs_info->delalloc_bytes, 0, GFP_KERNEL);
2844 ret = percpu_counter_init(&fs_info->dev_replace.bio_counter, 0,
2849 fs_info->delayed_root = kmalloc(sizeof(struct btrfs_delayed_root),
2851 if (!fs_info->delayed_root)
2853 btrfs_init_delayed_root(fs_info->delayed_root);
2856 set_bit(BTRFS_FS_STATE_RO, &fs_info->fs_state);
2858 return btrfs_alloc_stripe_hash_table(fs_info);
2861 static int btrfs_uuid_rescan_kthread(void *data)
2863 struct btrfs_fs_info *fs_info = data;
2867 * 1st step is to iterate through the existing UUID tree and
2868 * to delete all entries that contain outdated data.
2869 * 2nd step is to add all missing entries to the UUID tree.
2871 ret = btrfs_uuid_tree_iterate(fs_info);
2874 btrfs_warn(fs_info, "iterating uuid_tree failed %d",
2876 up(&fs_info->uuid_tree_rescan_sem);
2879 return btrfs_uuid_scan_kthread(data);
2882 static int btrfs_check_uuid_tree(struct btrfs_fs_info *fs_info)
2884 struct task_struct *task;
2886 down(&fs_info->uuid_tree_rescan_sem);
2887 task = kthread_run(btrfs_uuid_rescan_kthread, fs_info, "btrfs-uuid");
2889 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
2890 btrfs_warn(fs_info, "failed to start uuid_rescan task");
2891 up(&fs_info->uuid_tree_rescan_sem);
2892 return PTR_ERR(task);
2898 static int btrfs_cleanup_fs_roots(struct btrfs_fs_info *fs_info)
2900 u64 root_objectid = 0;
2901 struct btrfs_root *gang[8];
2904 unsigned int ret = 0;
2907 spin_lock(&fs_info->fs_roots_radix_lock);
2908 ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
2909 (void **)gang, root_objectid,
2912 spin_unlock(&fs_info->fs_roots_radix_lock);
2915 root_objectid = gang[ret - 1]->root_key.objectid + 1;
2917 for (i = 0; i < ret; i++) {
2918 /* Avoid to grab roots in dead_roots. */
2919 if (btrfs_root_refs(&gang[i]->root_item) == 0) {
2923 /* Grab all the search result for later use. */
2924 gang[i] = btrfs_grab_root(gang[i]);
2926 spin_unlock(&fs_info->fs_roots_radix_lock);
2928 for (i = 0; i < ret; i++) {
2931 root_objectid = gang[i]->root_key.objectid;
2932 err = btrfs_orphan_cleanup(gang[i]);
2935 btrfs_put_root(gang[i]);
2940 /* Release the uncleaned roots due to error. */
2941 for (; i < ret; i++) {
2943 btrfs_put_root(gang[i]);
2949 * Mounting logic specific to read-write file systems. Shared by open_ctree
2950 * and btrfs_remount when remounting from read-only to read-write.
2952 int btrfs_start_pre_rw_mount(struct btrfs_fs_info *fs_info)
2955 const bool cache_opt = btrfs_test_opt(fs_info, SPACE_CACHE);
2956 bool rebuild_free_space_tree = false;
2958 if (btrfs_test_opt(fs_info, CLEAR_CACHE) &&
2959 btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
2960 if (btrfs_fs_incompat(fs_info, EXTENT_TREE_V2))
2962 "'clear_cache' option is ignored with extent tree v2");
2964 rebuild_free_space_tree = true;
2965 } else if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE) &&
2966 !btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE_VALID)) {
2967 btrfs_warn(fs_info, "free space tree is invalid");
2968 rebuild_free_space_tree = true;
2971 if (rebuild_free_space_tree) {
2972 btrfs_info(fs_info, "rebuilding free space tree");
2973 ret = btrfs_rebuild_free_space_tree(fs_info);
2976 "failed to rebuild free space tree: %d", ret);
2981 if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE) &&
2982 !btrfs_test_opt(fs_info, FREE_SPACE_TREE)) {
2983 btrfs_info(fs_info, "disabling free space tree");
2984 ret = btrfs_delete_free_space_tree(fs_info);
2987 "failed to disable free space tree: %d", ret);
2993 * btrfs_find_orphan_roots() is responsible for finding all the dead
2994 * roots (with 0 refs), flag them with BTRFS_ROOT_DEAD_TREE and load
2995 * them into the fs_info->fs_roots_radix tree. This must be done before
2996 * calling btrfs_orphan_cleanup() on the tree root. If we don't do it
2997 * first, then btrfs_orphan_cleanup() will delete a dead root's orphan
2998 * item before the root's tree is deleted - this means that if we unmount
2999 * or crash before the deletion completes, on the next mount we will not
3000 * delete what remains of the tree because the orphan item does not
3001 * exists anymore, which is what tells us we have a pending deletion.
3003 ret = btrfs_find_orphan_roots(fs_info);
3007 ret = btrfs_cleanup_fs_roots(fs_info);
3011 down_read(&fs_info->cleanup_work_sem);
3012 if ((ret = btrfs_orphan_cleanup(fs_info->fs_root)) ||
3013 (ret = btrfs_orphan_cleanup(fs_info->tree_root))) {
3014 up_read(&fs_info->cleanup_work_sem);
3017 up_read(&fs_info->cleanup_work_sem);
3019 mutex_lock(&fs_info->cleaner_mutex);
3020 ret = btrfs_recover_relocation(fs_info);
3021 mutex_unlock(&fs_info->cleaner_mutex);
3023 btrfs_warn(fs_info, "failed to recover relocation: %d", ret);
3027 if (btrfs_test_opt(fs_info, FREE_SPACE_TREE) &&
3028 !btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
3029 btrfs_info(fs_info, "creating free space tree");
3030 ret = btrfs_create_free_space_tree(fs_info);
3033 "failed to create free space tree: %d", ret);
3038 if (cache_opt != btrfs_free_space_cache_v1_active(fs_info)) {
3039 ret = btrfs_set_free_space_cache_v1_active(fs_info, cache_opt);
3044 ret = btrfs_resume_balance_async(fs_info);
3048 ret = btrfs_resume_dev_replace_async(fs_info);
3050 btrfs_warn(fs_info, "failed to resume dev_replace");
3054 btrfs_qgroup_rescan_resume(fs_info);
3056 if (!fs_info->uuid_root) {
3057 btrfs_info(fs_info, "creating UUID tree");
3058 ret = btrfs_create_uuid_tree(fs_info);
3061 "failed to create the UUID tree %d", ret);
3071 * Do various sanity and dependency checks of different features.
3073 * @is_rw_mount: If the mount is read-write.
3075 * This is the place for less strict checks (like for subpage or artificial
3076 * feature dependencies).
3078 * For strict checks or possible corruption detection, see
3079 * btrfs_validate_super().
3081 * This should be called after btrfs_parse_options(), as some mount options
3082 * (space cache related) can modify on-disk format like free space tree and
3083 * screw up certain feature dependencies.
3085 int btrfs_check_features(struct btrfs_fs_info *fs_info, bool is_rw_mount)
3087 struct btrfs_super_block *disk_super = fs_info->super_copy;
3088 u64 incompat = btrfs_super_incompat_flags(disk_super);
3089 const u64 compat_ro = btrfs_super_compat_ro_flags(disk_super);
3090 const u64 compat_ro_unsupp = (compat_ro & ~BTRFS_FEATURE_COMPAT_RO_SUPP);
3092 if (incompat & ~BTRFS_FEATURE_INCOMPAT_SUPP) {
3094 "cannot mount because of unknown incompat features (0x%llx)",
3099 /* Runtime limitation for mixed block groups. */
3100 if ((incompat & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS) &&
3101 (fs_info->sectorsize != fs_info->nodesize)) {
3103 "unequal nodesize/sectorsize (%u != %u) are not allowed for mixed block groups",
3104 fs_info->nodesize, fs_info->sectorsize);
3108 /* Mixed backref is an always-enabled feature. */
3109 incompat |= BTRFS_FEATURE_INCOMPAT_MIXED_BACKREF;
3111 /* Set compression related flags just in case. */
3112 if (fs_info->compress_type == BTRFS_COMPRESS_LZO)
3113 incompat |= BTRFS_FEATURE_INCOMPAT_COMPRESS_LZO;
3114 else if (fs_info->compress_type == BTRFS_COMPRESS_ZSTD)
3115 incompat |= BTRFS_FEATURE_INCOMPAT_COMPRESS_ZSTD;
3118 * An ancient flag, which should really be marked deprecated.
3119 * Such runtime limitation doesn't really need a incompat flag.
3121 if (btrfs_super_nodesize(disk_super) > PAGE_SIZE)
3122 incompat |= BTRFS_FEATURE_INCOMPAT_BIG_METADATA;
3124 if (compat_ro_unsupp && is_rw_mount) {
3126 "cannot mount read-write because of unknown compat_ro features (0x%llx)",
3132 * We have unsupported RO compat features, although RO mounted, we
3133 * should not cause any metadata writes, including log replay.
3134 * Or we could screw up whatever the new feature requires.
3136 if (compat_ro_unsupp && btrfs_super_log_root(disk_super) &&
3137 !btrfs_test_opt(fs_info, NOLOGREPLAY)) {
3139 "cannot replay dirty log with unsupported compat_ro features (0x%llx), try rescue=nologreplay",
3145 * Artificial limitations for block group tree, to force
3146 * block-group-tree to rely on no-holes and free-space-tree.
3148 if (btrfs_fs_compat_ro(fs_info, BLOCK_GROUP_TREE) &&
3149 (!btrfs_fs_incompat(fs_info, NO_HOLES) ||
3150 !btrfs_test_opt(fs_info, FREE_SPACE_TREE))) {
3152 "block-group-tree feature requires no-holes and free-space-tree features");
3157 * Subpage runtime limitation on v1 cache.
3159 * V1 space cache still has some hard codeed PAGE_SIZE usage, while
3160 * we're already defaulting to v2 cache, no need to bother v1 as it's
3161 * going to be deprecated anyway.
3163 if (fs_info->sectorsize < PAGE_SIZE && btrfs_test_opt(fs_info, SPACE_CACHE)) {
3165 "v1 space cache is not supported for page size %lu with sectorsize %u",
3166 PAGE_SIZE, fs_info->sectorsize);
3170 /* This can be called by remount, we need to protect the super block. */
3171 spin_lock(&fs_info->super_lock);
3172 btrfs_set_super_incompat_flags(disk_super, incompat);
3173 spin_unlock(&fs_info->super_lock);
3178 int __cold open_ctree(struct super_block *sb, struct btrfs_fs_devices *fs_devices,
3186 struct btrfs_super_block *disk_super;
3187 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
3188 struct btrfs_root *tree_root;
3189 struct btrfs_root *chunk_root;
3193 ret = init_mount_fs_info(fs_info, sb);
3197 /* These need to be init'ed before we start creating inodes and such. */
3198 tree_root = btrfs_alloc_root(fs_info, BTRFS_ROOT_TREE_OBJECTID,
3200 fs_info->tree_root = tree_root;
3201 chunk_root = btrfs_alloc_root(fs_info, BTRFS_CHUNK_TREE_OBJECTID,
3203 fs_info->chunk_root = chunk_root;
3204 if (!tree_root || !chunk_root) {
3209 ret = btrfs_init_btree_inode(sb);
3213 invalidate_bdev(fs_devices->latest_dev->bdev);
3216 * Read super block and check the signature bytes only
3218 disk_super = btrfs_read_dev_super(fs_devices->latest_dev->bdev);
3219 if (IS_ERR(disk_super)) {
3220 ret = PTR_ERR(disk_super);
3224 btrfs_info(fs_info, "first mount of filesystem %pU", disk_super->fsid);
3226 * Verify the type first, if that or the checksum value are
3227 * corrupted, we'll find out
3229 csum_type = btrfs_super_csum_type(disk_super);
3230 if (!btrfs_supported_super_csum(csum_type)) {
3231 btrfs_err(fs_info, "unsupported checksum algorithm: %u",
3234 btrfs_release_disk_super(disk_super);
3238 fs_info->csum_size = btrfs_super_csum_size(disk_super);
3240 ret = btrfs_init_csum_hash(fs_info, csum_type);
3242 btrfs_release_disk_super(disk_super);
3247 * We want to check superblock checksum, the type is stored inside.
3248 * Pass the whole disk block of size BTRFS_SUPER_INFO_SIZE (4k).
3250 if (btrfs_check_super_csum(fs_info, disk_super)) {
3251 btrfs_err(fs_info, "superblock checksum mismatch");
3253 btrfs_release_disk_super(disk_super);
3258 * super_copy is zeroed at allocation time and we never touch the
3259 * following bytes up to INFO_SIZE, the checksum is calculated from
3260 * the whole block of INFO_SIZE
3262 memcpy(fs_info->super_copy, disk_super, sizeof(*fs_info->super_copy));
3263 btrfs_release_disk_super(disk_super);
3265 disk_super = fs_info->super_copy;
3267 memcpy(fs_info->super_for_commit, fs_info->super_copy,
3268 sizeof(*fs_info->super_for_commit));
3270 ret = btrfs_validate_mount_super(fs_info);
3272 btrfs_err(fs_info, "superblock contains fatal errors");
3277 if (!btrfs_super_root(disk_super)) {
3278 btrfs_err(fs_info, "invalid superblock tree root bytenr");
3283 /* check FS state, whether FS is broken. */
3284 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_ERROR)
3285 WRITE_ONCE(fs_info->fs_error, -EUCLEAN);
3287 /* Set up fs_info before parsing mount options */
3288 nodesize = btrfs_super_nodesize(disk_super);
3289 sectorsize = btrfs_super_sectorsize(disk_super);
3290 stripesize = sectorsize;
3291 fs_info->dirty_metadata_batch = nodesize * (1 + ilog2(nr_cpu_ids));
3292 fs_info->delalloc_batch = sectorsize * 512 * (1 + ilog2(nr_cpu_ids));
3294 fs_info->nodesize = nodesize;
3295 fs_info->sectorsize = sectorsize;
3296 fs_info->sectorsize_bits = ilog2(sectorsize);
3297 fs_info->csums_per_leaf = BTRFS_MAX_ITEM_SIZE(fs_info) / fs_info->csum_size;
3298 fs_info->stripesize = stripesize;
3301 * Handle the space caching options appropriately now that we have the
3302 * super block loaded and validated.
3304 btrfs_set_free_space_cache_settings(fs_info);
3306 if (!btrfs_check_options(fs_info, &fs_info->mount_opt, sb->s_flags)) {
3311 ret = btrfs_check_features(fs_info, !sb_rdonly(sb));
3316 * At this point our mount options are validated, if we set ->max_inline
3317 * to something non-standard make sure we truncate it to sectorsize.
3319 fs_info->max_inline = min_t(u64, fs_info->max_inline, fs_info->sectorsize);
3321 if (sectorsize < PAGE_SIZE) {
3322 struct btrfs_subpage_info *subpage_info;
3325 "read-write for sector size %u with page size %lu is experimental",
3326 sectorsize, PAGE_SIZE);
3327 subpage_info = kzalloc(sizeof(*subpage_info), GFP_KERNEL);
3328 if (!subpage_info) {
3332 btrfs_init_subpage_info(subpage_info, sectorsize);
3333 fs_info->subpage_info = subpage_info;
3336 ret = btrfs_init_workqueues(fs_info);
3338 goto fail_sb_buffer;
3340 sb->s_bdi->ra_pages *= btrfs_super_num_devices(disk_super);
3341 sb->s_bdi->ra_pages = max(sb->s_bdi->ra_pages, SZ_4M / PAGE_SIZE);
3343 sb->s_blocksize = sectorsize;
3344 sb->s_blocksize_bits = blksize_bits(sectorsize);
3345 memcpy(&sb->s_uuid, fs_info->fs_devices->fsid, BTRFS_FSID_SIZE);
3347 mutex_lock(&fs_info->chunk_mutex);
3348 ret = btrfs_read_sys_array(fs_info);
3349 mutex_unlock(&fs_info->chunk_mutex);
3351 btrfs_err(fs_info, "failed to read the system array: %d", ret);
3352 goto fail_sb_buffer;
3355 generation = btrfs_super_chunk_root_generation(disk_super);
3356 level = btrfs_super_chunk_root_level(disk_super);
3357 ret = load_super_root(chunk_root, btrfs_super_chunk_root(disk_super),
3360 btrfs_err(fs_info, "failed to read chunk root");
3361 goto fail_tree_roots;
3364 read_extent_buffer(chunk_root->node, fs_info->chunk_tree_uuid,
3365 offsetof(struct btrfs_header, chunk_tree_uuid),
3368 ret = btrfs_read_chunk_tree(fs_info);
3370 btrfs_err(fs_info, "failed to read chunk tree: %d", ret);
3371 goto fail_tree_roots;
3375 * At this point we know all the devices that make this filesystem,
3376 * including the seed devices but we don't know yet if the replace
3377 * target is required. So free devices that are not part of this
3378 * filesystem but skip the replace target device which is checked
3379 * below in btrfs_init_dev_replace().
3381 btrfs_free_extra_devids(fs_devices);
3382 if (!fs_devices->latest_dev->bdev) {
3383 btrfs_err(fs_info, "failed to read devices");
3385 goto fail_tree_roots;
3388 ret = init_tree_roots(fs_info);
3390 goto fail_tree_roots;
3393 * Get zone type information of zoned block devices. This will also
3394 * handle emulation of a zoned filesystem if a regular device has the
3395 * zoned incompat feature flag set.
3397 ret = btrfs_get_dev_zone_info_all_devices(fs_info);
3400 "zoned: failed to read device zone info: %d", ret);
3401 goto fail_block_groups;
3405 * If we have a uuid root and we're not being told to rescan we need to
3406 * check the generation here so we can set the
3407 * BTRFS_FS_UPDATE_UUID_TREE_GEN bit. Otherwise we could commit the
3408 * transaction during a balance or the log replay without updating the
3409 * uuid generation, and then if we crash we would rescan the uuid tree,
3410 * even though it was perfectly fine.
3412 if (fs_info->uuid_root && !btrfs_test_opt(fs_info, RESCAN_UUID_TREE) &&
3413 fs_info->generation == btrfs_super_uuid_tree_generation(disk_super))
3414 set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
3416 ret = btrfs_verify_dev_extents(fs_info);
3419 "failed to verify dev extents against chunks: %d",
3421 goto fail_block_groups;
3423 ret = btrfs_recover_balance(fs_info);
3425 btrfs_err(fs_info, "failed to recover balance: %d", ret);
3426 goto fail_block_groups;
3429 ret = btrfs_init_dev_stats(fs_info);
3431 btrfs_err(fs_info, "failed to init dev_stats: %d", ret);
3432 goto fail_block_groups;
3435 ret = btrfs_init_dev_replace(fs_info);
3437 btrfs_err(fs_info, "failed to init dev_replace: %d", ret);
3438 goto fail_block_groups;
3441 ret = btrfs_check_zoned_mode(fs_info);
3443 btrfs_err(fs_info, "failed to initialize zoned mode: %d",
3445 goto fail_block_groups;
3448 ret = btrfs_sysfs_add_fsid(fs_devices);
3450 btrfs_err(fs_info, "failed to init sysfs fsid interface: %d",
3452 goto fail_block_groups;
3455 ret = btrfs_sysfs_add_mounted(fs_info);
3457 btrfs_err(fs_info, "failed to init sysfs interface: %d", ret);
3458 goto fail_fsdev_sysfs;
3461 ret = btrfs_init_space_info(fs_info);
3463 btrfs_err(fs_info, "failed to initialize space info: %d", ret);
3467 ret = btrfs_read_block_groups(fs_info);
3469 btrfs_err(fs_info, "failed to read block groups: %d", ret);
3473 btrfs_free_zone_cache(fs_info);
3475 btrfs_check_active_zone_reservation(fs_info);
3477 if (!sb_rdonly(sb) && fs_info->fs_devices->missing_devices &&
3478 !btrfs_check_rw_degradable(fs_info, NULL)) {
3480 "writable mount is not allowed due to too many missing devices");
3485 fs_info->cleaner_kthread = kthread_run(cleaner_kthread, fs_info,
3487 if (IS_ERR(fs_info->cleaner_kthread)) {
3488 ret = PTR_ERR(fs_info->cleaner_kthread);
3492 fs_info->transaction_kthread = kthread_run(transaction_kthread,
3494 "btrfs-transaction");
3495 if (IS_ERR(fs_info->transaction_kthread)) {
3496 ret = PTR_ERR(fs_info->transaction_kthread);
3500 ret = btrfs_read_qgroup_config(fs_info);
3502 goto fail_trans_kthread;
3504 if (btrfs_build_ref_tree(fs_info))
3505 btrfs_err(fs_info, "couldn't build ref tree");
3507 /* do not make disk changes in broken FS or nologreplay is given */
3508 if (btrfs_super_log_root(disk_super) != 0 &&
3509 !btrfs_test_opt(fs_info, NOLOGREPLAY)) {
3510 btrfs_info(fs_info, "start tree-log replay");
3511 ret = btrfs_replay_log(fs_info, fs_devices);
3516 fs_info->fs_root = btrfs_get_fs_root(fs_info, BTRFS_FS_TREE_OBJECTID, true);
3517 if (IS_ERR(fs_info->fs_root)) {
3518 ret = PTR_ERR(fs_info->fs_root);
3519 btrfs_warn(fs_info, "failed to read fs tree: %d", ret);
3520 fs_info->fs_root = NULL;
3527 ret = btrfs_start_pre_rw_mount(fs_info);
3529 close_ctree(fs_info);
3532 btrfs_discard_resume(fs_info);
3534 if (fs_info->uuid_root &&
3535 (btrfs_test_opt(fs_info, RESCAN_UUID_TREE) ||
3536 fs_info->generation != btrfs_super_uuid_tree_generation(disk_super))) {
3537 btrfs_info(fs_info, "checking UUID tree");
3538 ret = btrfs_check_uuid_tree(fs_info);
3541 "failed to check the UUID tree: %d", ret);
3542 close_ctree(fs_info);
3547 set_bit(BTRFS_FS_OPEN, &fs_info->flags);
3549 /* Kick the cleaner thread so it'll start deleting snapshots. */
3550 if (test_bit(BTRFS_FS_UNFINISHED_DROPS, &fs_info->flags))
3551 wake_up_process(fs_info->cleaner_kthread);
3556 btrfs_free_qgroup_config(fs_info);
3558 kthread_stop(fs_info->transaction_kthread);
3559 btrfs_cleanup_transaction(fs_info);
3560 btrfs_free_fs_roots(fs_info);
3562 kthread_stop(fs_info->cleaner_kthread);
3565 * make sure we're done with the btree inode before we stop our
3568 filemap_write_and_wait(fs_info->btree_inode->i_mapping);
3571 btrfs_sysfs_remove_mounted(fs_info);
3574 btrfs_sysfs_remove_fsid(fs_info->fs_devices);
3577 btrfs_put_block_group_cache(fs_info);
3580 if (fs_info->data_reloc_root)
3581 btrfs_drop_and_free_fs_root(fs_info, fs_info->data_reloc_root);
3582 free_root_pointers(fs_info, true);
3583 invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
3586 btrfs_stop_all_workers(fs_info);
3587 btrfs_free_block_groups(fs_info);
3589 btrfs_mapping_tree_free(fs_info);
3591 iput(fs_info->btree_inode);
3593 btrfs_close_devices(fs_info->fs_devices);
3597 ALLOW_ERROR_INJECTION(open_ctree, ERRNO);
3599 static void btrfs_end_super_write(struct bio *bio)
3601 struct btrfs_device *device = bio->bi_private;
3602 struct bio_vec *bvec;
3603 struct bvec_iter_all iter_all;
3606 bio_for_each_segment_all(bvec, bio, iter_all) {
3607 page = bvec->bv_page;
3609 if (bio->bi_status) {
3610 btrfs_warn_rl_in_rcu(device->fs_info,
3611 "lost page write due to IO error on %s (%d)",
3612 btrfs_dev_name(device),
3613 blk_status_to_errno(bio->bi_status));
3614 ClearPageUptodate(page);
3616 btrfs_dev_stat_inc_and_print(device,
3617 BTRFS_DEV_STAT_WRITE_ERRS);
3619 SetPageUptodate(page);
3629 struct btrfs_super_block *btrfs_read_dev_one_super(struct block_device *bdev,
3630 int copy_num, bool drop_cache)
3632 struct btrfs_super_block *super;
3634 u64 bytenr, bytenr_orig;
3635 struct address_space *mapping = bdev->bd_inode->i_mapping;
3638 bytenr_orig = btrfs_sb_offset(copy_num);
3639 ret = btrfs_sb_log_location_bdev(bdev, copy_num, READ, &bytenr);
3641 return ERR_PTR(-EINVAL);
3643 return ERR_PTR(ret);
3645 if (bytenr + BTRFS_SUPER_INFO_SIZE >= bdev_nr_bytes(bdev))
3646 return ERR_PTR(-EINVAL);
3649 /* This should only be called with the primary sb. */
3650 ASSERT(copy_num == 0);
3653 * Drop the page of the primary superblock, so later read will
3654 * always read from the device.
3656 invalidate_inode_pages2_range(mapping,
3657 bytenr >> PAGE_SHIFT,
3658 (bytenr + BTRFS_SUPER_INFO_SIZE) >> PAGE_SHIFT);
3661 page = read_cache_page_gfp(mapping, bytenr >> PAGE_SHIFT, GFP_NOFS);
3663 return ERR_CAST(page);
3665 super = page_address(page);
3666 if (btrfs_super_magic(super) != BTRFS_MAGIC) {
3667 btrfs_release_disk_super(super);
3668 return ERR_PTR(-ENODATA);
3671 if (btrfs_super_bytenr(super) != bytenr_orig) {
3672 btrfs_release_disk_super(super);
3673 return ERR_PTR(-EINVAL);
3680 struct btrfs_super_block *btrfs_read_dev_super(struct block_device *bdev)
3682 struct btrfs_super_block *super, *latest = NULL;
3686 /* we would like to check all the supers, but that would make
3687 * a btrfs mount succeed after a mkfs from a different FS.
3688 * So, we need to add a special mount option to scan for
3689 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
3691 for (i = 0; i < 1; i++) {
3692 super = btrfs_read_dev_one_super(bdev, i, false);
3696 if (!latest || btrfs_super_generation(super) > transid) {
3698 btrfs_release_disk_super(super);
3701 transid = btrfs_super_generation(super);
3709 * Write superblock @sb to the @device. Do not wait for completion, all the
3710 * pages we use for writing are locked.
3712 * Write @max_mirrors copies of the superblock, where 0 means default that fit
3713 * the expected device size at commit time. Note that max_mirrors must be
3714 * same for write and wait phases.
3716 * Return number of errors when page is not found or submission fails.
3718 static int write_dev_supers(struct btrfs_device *device,
3719 struct btrfs_super_block *sb, int max_mirrors)
3721 struct btrfs_fs_info *fs_info = device->fs_info;
3722 struct address_space *mapping = device->bdev->bd_inode->i_mapping;
3723 SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
3727 u64 bytenr, bytenr_orig;
3729 if (max_mirrors == 0)
3730 max_mirrors = BTRFS_SUPER_MIRROR_MAX;
3732 shash->tfm = fs_info->csum_shash;
3734 for (i = 0; i < max_mirrors; i++) {
3737 struct btrfs_super_block *disk_super;
3739 bytenr_orig = btrfs_sb_offset(i);
3740 ret = btrfs_sb_log_location(device, i, WRITE, &bytenr);
3741 if (ret == -ENOENT) {
3743 } else if (ret < 0) {
3744 btrfs_err(device->fs_info,
3745 "couldn't get super block location for mirror %d",
3750 if (bytenr + BTRFS_SUPER_INFO_SIZE >=
3751 device->commit_total_bytes)
3754 btrfs_set_super_bytenr(sb, bytenr_orig);
3756 crypto_shash_digest(shash, (const char *)sb + BTRFS_CSUM_SIZE,
3757 BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE,
3760 page = find_or_create_page(mapping, bytenr >> PAGE_SHIFT,
3763 btrfs_err(device->fs_info,
3764 "couldn't get super block page for bytenr %llu",
3770 /* Bump the refcount for wait_dev_supers() */
3773 disk_super = page_address(page);
3774 memcpy(disk_super, sb, BTRFS_SUPER_INFO_SIZE);
3777 * Directly use bios here instead of relying on the page cache
3778 * to do I/O, so we don't lose the ability to do integrity
3781 bio = bio_alloc(device->bdev, 1,
3782 REQ_OP_WRITE | REQ_SYNC | REQ_META | REQ_PRIO,
3784 bio->bi_iter.bi_sector = bytenr >> SECTOR_SHIFT;
3785 bio->bi_private = device;
3786 bio->bi_end_io = btrfs_end_super_write;
3787 __bio_add_page(bio, page, BTRFS_SUPER_INFO_SIZE,
3788 offset_in_page(bytenr));
3791 * We FUA only the first super block. The others we allow to
3792 * go down lazy and there's a short window where the on-disk
3793 * copies might still contain the older version.
3795 if (i == 0 && !btrfs_test_opt(device->fs_info, NOBARRIER))
3796 bio->bi_opf |= REQ_FUA;
3799 if (btrfs_advance_sb_log(device, i))
3802 return errors < i ? 0 : -1;
3806 * Wait for write completion of superblocks done by write_dev_supers,
3807 * @max_mirrors same for write and wait phases.
3809 * Return number of errors when page is not found or not marked up to
3812 static int wait_dev_supers(struct btrfs_device *device, int max_mirrors)
3816 bool primary_failed = false;
3820 if (max_mirrors == 0)
3821 max_mirrors = BTRFS_SUPER_MIRROR_MAX;
3823 for (i = 0; i < max_mirrors; i++) {
3826 ret = btrfs_sb_log_location(device, i, READ, &bytenr);
3827 if (ret == -ENOENT) {
3829 } else if (ret < 0) {
3832 primary_failed = true;
3835 if (bytenr + BTRFS_SUPER_INFO_SIZE >=
3836 device->commit_total_bytes)
3839 page = find_get_page(device->bdev->bd_inode->i_mapping,
3840 bytenr >> PAGE_SHIFT);
3844 primary_failed = true;
3847 /* Page is submitted locked and unlocked once the IO completes */
3848 wait_on_page_locked(page);
3849 if (PageError(page)) {
3852 primary_failed = true;
3855 /* Drop our reference */
3858 /* Drop the reference from the writing run */
3862 /* log error, force error return */
3863 if (primary_failed) {
3864 btrfs_err(device->fs_info, "error writing primary super block to device %llu",
3869 return errors < i ? 0 : -1;
3873 * endio for the write_dev_flush, this will wake anyone waiting
3874 * for the barrier when it is done
3876 static void btrfs_end_empty_barrier(struct bio *bio)
3879 complete(bio->bi_private);
3883 * Submit a flush request to the device if it supports it. Error handling is
3884 * done in the waiting counterpart.
3886 static void write_dev_flush(struct btrfs_device *device)
3888 struct bio *bio = &device->flush_bio;
3890 device->last_flush_error = BLK_STS_OK;
3892 bio_init(bio, device->bdev, NULL, 0,
3893 REQ_OP_WRITE | REQ_SYNC | REQ_PREFLUSH);
3894 bio->bi_end_io = btrfs_end_empty_barrier;
3895 init_completion(&device->flush_wait);
3896 bio->bi_private = &device->flush_wait;
3898 set_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state);
3902 * If the flush bio has been submitted by write_dev_flush, wait for it.
3903 * Return true for any error, and false otherwise.
3905 static bool wait_dev_flush(struct btrfs_device *device)
3907 struct bio *bio = &device->flush_bio;
3909 if (!test_and_clear_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state))
3912 wait_for_completion_io(&device->flush_wait);
3914 if (bio->bi_status) {
3915 device->last_flush_error = bio->bi_status;
3916 btrfs_dev_stat_inc_and_print(device, BTRFS_DEV_STAT_FLUSH_ERRS);
3924 * send an empty flush down to each device in parallel,
3925 * then wait for them
3927 static int barrier_all_devices(struct btrfs_fs_info *info)
3929 struct list_head *head;
3930 struct btrfs_device *dev;
3931 int errors_wait = 0;
3933 lockdep_assert_held(&info->fs_devices->device_list_mutex);
3934 /* send down all the barriers */
3935 head = &info->fs_devices->devices;
3936 list_for_each_entry(dev, head, dev_list) {
3937 if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
3941 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
3942 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
3945 write_dev_flush(dev);
3948 /* wait for all the barriers */
3949 list_for_each_entry(dev, head, dev_list) {
3950 if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
3956 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
3957 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
3960 if (wait_dev_flush(dev))
3965 * Checks last_flush_error of disks in order to determine the device
3968 if (errors_wait && !btrfs_check_rw_degradable(info, NULL))
3974 int btrfs_get_num_tolerated_disk_barrier_failures(u64 flags)
3977 int min_tolerated = INT_MAX;
3979 if ((flags & BTRFS_BLOCK_GROUP_PROFILE_MASK) == 0 ||
3980 (flags & BTRFS_AVAIL_ALLOC_BIT_SINGLE))
3981 min_tolerated = min_t(int, min_tolerated,
3982 btrfs_raid_array[BTRFS_RAID_SINGLE].
3983 tolerated_failures);
3985 for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) {
3986 if (raid_type == BTRFS_RAID_SINGLE)
3988 if (!(flags & btrfs_raid_array[raid_type].bg_flag))
3990 min_tolerated = min_t(int, min_tolerated,
3991 btrfs_raid_array[raid_type].
3992 tolerated_failures);
3995 if (min_tolerated == INT_MAX) {
3996 pr_warn("BTRFS: unknown raid flag: %llu", flags);
4000 return min_tolerated;
4003 int write_all_supers(struct btrfs_fs_info *fs_info, int max_mirrors)
4005 struct list_head *head;
4006 struct btrfs_device *dev;
4007 struct btrfs_super_block *sb;
4008 struct btrfs_dev_item *dev_item;
4012 int total_errors = 0;
4015 do_barriers = !btrfs_test_opt(fs_info, NOBARRIER);
4018 * max_mirrors == 0 indicates we're from commit_transaction,
4019 * not from fsync where the tree roots in fs_info have not
4020 * been consistent on disk.
4022 if (max_mirrors == 0)
4023 backup_super_roots(fs_info);
4025 sb = fs_info->super_for_commit;
4026 dev_item = &sb->dev_item;
4028 mutex_lock(&fs_info->fs_devices->device_list_mutex);
4029 head = &fs_info->fs_devices->devices;
4030 max_errors = btrfs_super_num_devices(fs_info->super_copy) - 1;
4033 ret = barrier_all_devices(fs_info);
4036 &fs_info->fs_devices->device_list_mutex);
4037 btrfs_handle_fs_error(fs_info, ret,
4038 "errors while submitting device barriers.");
4043 list_for_each_entry(dev, head, dev_list) {
4048 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
4049 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
4052 btrfs_set_stack_device_generation(dev_item, 0);
4053 btrfs_set_stack_device_type(dev_item, dev->type);
4054 btrfs_set_stack_device_id(dev_item, dev->devid);
4055 btrfs_set_stack_device_total_bytes(dev_item,
4056 dev->commit_total_bytes);
4057 btrfs_set_stack_device_bytes_used(dev_item,
4058 dev->commit_bytes_used);
4059 btrfs_set_stack_device_io_align(dev_item, dev->io_align);
4060 btrfs_set_stack_device_io_width(dev_item, dev->io_width);
4061 btrfs_set_stack_device_sector_size(dev_item, dev->sector_size);
4062 memcpy(dev_item->uuid, dev->uuid, BTRFS_UUID_SIZE);
4063 memcpy(dev_item->fsid, dev->fs_devices->metadata_uuid,
4066 flags = btrfs_super_flags(sb);
4067 btrfs_set_super_flags(sb, flags | BTRFS_HEADER_FLAG_WRITTEN);
4069 ret = btrfs_validate_write_super(fs_info, sb);
4071 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
4072 btrfs_handle_fs_error(fs_info, -EUCLEAN,
4073 "unexpected superblock corruption detected");
4077 ret = write_dev_supers(dev, sb, max_mirrors);
4081 if (total_errors > max_errors) {
4082 btrfs_err(fs_info, "%d errors while writing supers",
4084 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
4086 /* FUA is masked off if unsupported and can't be the reason */
4087 btrfs_handle_fs_error(fs_info, -EIO,
4088 "%d errors while writing supers",
4094 list_for_each_entry(dev, head, dev_list) {
4097 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
4098 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
4101 ret = wait_dev_supers(dev, max_mirrors);
4105 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
4106 if (total_errors > max_errors) {
4107 btrfs_handle_fs_error(fs_info, -EIO,
4108 "%d errors while writing supers",
4115 /* Drop a fs root from the radix tree and free it. */
4116 void btrfs_drop_and_free_fs_root(struct btrfs_fs_info *fs_info,
4117 struct btrfs_root *root)
4119 bool drop_ref = false;
4121 spin_lock(&fs_info->fs_roots_radix_lock);
4122 radix_tree_delete(&fs_info->fs_roots_radix,
4123 (unsigned long)root->root_key.objectid);
4124 if (test_and_clear_bit(BTRFS_ROOT_IN_RADIX, &root->state))
4126 spin_unlock(&fs_info->fs_roots_radix_lock);
4128 if (BTRFS_FS_ERROR(fs_info)) {
4129 ASSERT(root->log_root == NULL);
4130 if (root->reloc_root) {
4131 btrfs_put_root(root->reloc_root);
4132 root->reloc_root = NULL;
4137 btrfs_put_root(root);
4140 int btrfs_commit_super(struct btrfs_fs_info *fs_info)
4142 struct btrfs_root *root = fs_info->tree_root;
4143 struct btrfs_trans_handle *trans;
4145 mutex_lock(&fs_info->cleaner_mutex);
4146 btrfs_run_delayed_iputs(fs_info);
4147 mutex_unlock(&fs_info->cleaner_mutex);
4148 wake_up_process(fs_info->cleaner_kthread);
4150 /* wait until ongoing cleanup work done */
4151 down_write(&fs_info->cleanup_work_sem);
4152 up_write(&fs_info->cleanup_work_sem);
4154 trans = btrfs_join_transaction(root);
4156 return PTR_ERR(trans);
4157 return btrfs_commit_transaction(trans);
4160 static void warn_about_uncommitted_trans(struct btrfs_fs_info *fs_info)
4162 struct btrfs_transaction *trans;
4163 struct btrfs_transaction *tmp;
4166 if (list_empty(&fs_info->trans_list))
4170 * This function is only called at the very end of close_ctree(),
4171 * thus no other running transaction, no need to take trans_lock.
4173 ASSERT(test_bit(BTRFS_FS_CLOSING_DONE, &fs_info->flags));
4174 list_for_each_entry_safe(trans, tmp, &fs_info->trans_list, list) {
4175 struct extent_state *cached = NULL;
4176 u64 dirty_bytes = 0;
4182 while (find_first_extent_bit(&trans->dirty_pages, cur,
4183 &found_start, &found_end, EXTENT_DIRTY, &cached)) {
4184 dirty_bytes += found_end + 1 - found_start;
4185 cur = found_end + 1;
4188 "transaction %llu (with %llu dirty metadata bytes) is not committed",
4189 trans->transid, dirty_bytes);
4190 btrfs_cleanup_one_transaction(trans, fs_info);
4192 if (trans == fs_info->running_transaction)
4193 fs_info->running_transaction = NULL;
4194 list_del_init(&trans->list);
4196 btrfs_put_transaction(trans);
4197 trace_btrfs_transaction_commit(fs_info);
4202 void __cold close_ctree(struct btrfs_fs_info *fs_info)
4206 set_bit(BTRFS_FS_CLOSING_START, &fs_info->flags);
4209 * If we had UNFINISHED_DROPS we could still be processing them, so
4210 * clear that bit and wake up relocation so it can stop.
4211 * We must do this before stopping the block group reclaim task, because
4212 * at btrfs_relocate_block_group() we wait for this bit, and after the
4213 * wait we stop with -EINTR if btrfs_fs_closing() returns non-zero - we
4214 * have just set BTRFS_FS_CLOSING_START, so btrfs_fs_closing() will
4217 btrfs_wake_unfinished_drop(fs_info);
4220 * We may have the reclaim task running and relocating a data block group,
4221 * in which case it may create delayed iputs. So stop it before we park
4222 * the cleaner kthread otherwise we can get new delayed iputs after
4223 * parking the cleaner, and that can make the async reclaim task to hang
4224 * if it's waiting for delayed iputs to complete, since the cleaner is
4225 * parked and can not run delayed iputs - this will make us hang when
4226 * trying to stop the async reclaim task.
4228 cancel_work_sync(&fs_info->reclaim_bgs_work);
4230 * We don't want the cleaner to start new transactions, add more delayed
4231 * iputs, etc. while we're closing. We can't use kthread_stop() yet
4232 * because that frees the task_struct, and the transaction kthread might
4233 * still try to wake up the cleaner.
4235 kthread_park(fs_info->cleaner_kthread);
4237 /* wait for the qgroup rescan worker to stop */
4238 btrfs_qgroup_wait_for_completion(fs_info, false);
4240 /* wait for the uuid_scan task to finish */
4241 down(&fs_info->uuid_tree_rescan_sem);
4242 /* avoid complains from lockdep et al., set sem back to initial state */
4243 up(&fs_info->uuid_tree_rescan_sem);
4245 /* pause restriper - we want to resume on mount */
4246 btrfs_pause_balance(fs_info);
4248 btrfs_dev_replace_suspend_for_unmount(fs_info);
4250 btrfs_scrub_cancel(fs_info);
4252 /* wait for any defraggers to finish */
4253 wait_event(fs_info->transaction_wait,
4254 (atomic_read(&fs_info->defrag_running) == 0));
4256 /* clear out the rbtree of defraggable inodes */
4257 btrfs_cleanup_defrag_inodes(fs_info);
4260 * After we parked the cleaner kthread, ordered extents may have
4261 * completed and created new delayed iputs. If one of the async reclaim
4262 * tasks is running and in the RUN_DELAYED_IPUTS flush state, then we
4263 * can hang forever trying to stop it, because if a delayed iput is
4264 * added after it ran btrfs_run_delayed_iputs() and before it called
4265 * btrfs_wait_on_delayed_iputs(), it will hang forever since there is
4266 * no one else to run iputs.
4268 * So wait for all ongoing ordered extents to complete and then run
4269 * delayed iputs. This works because once we reach this point no one
4270 * can either create new ordered extents nor create delayed iputs
4271 * through some other means.
4273 * Also note that btrfs_wait_ordered_roots() is not safe here, because
4274 * it waits for BTRFS_ORDERED_COMPLETE to be set on an ordered extent,
4275 * but the delayed iput for the respective inode is made only when doing
4276 * the final btrfs_put_ordered_extent() (which must happen at
4277 * btrfs_finish_ordered_io() when we are unmounting).
4279 btrfs_flush_workqueue(fs_info->endio_write_workers);
4280 /* Ordered extents for free space inodes. */
4281 btrfs_flush_workqueue(fs_info->endio_freespace_worker);
4282 btrfs_run_delayed_iputs(fs_info);
4284 cancel_work_sync(&fs_info->async_reclaim_work);
4285 cancel_work_sync(&fs_info->async_data_reclaim_work);
4286 cancel_work_sync(&fs_info->preempt_reclaim_work);
4288 /* Cancel or finish ongoing discard work */
4289 btrfs_discard_cleanup(fs_info);
4291 if (!sb_rdonly(fs_info->sb)) {
4293 * The cleaner kthread is stopped, so do one final pass over
4294 * unused block groups.
4296 btrfs_delete_unused_bgs(fs_info);
4299 * There might be existing delayed inode workers still running
4300 * and holding an empty delayed inode item. We must wait for
4301 * them to complete first because they can create a transaction.
4302 * This happens when someone calls btrfs_balance_delayed_items()
4303 * and then a transaction commit runs the same delayed nodes
4304 * before any delayed worker has done something with the nodes.
4305 * We must wait for any worker here and not at transaction
4306 * commit time since that could cause a deadlock.
4307 * This is a very rare case.
4309 btrfs_flush_workqueue(fs_info->delayed_workers);
4311 ret = btrfs_commit_super(fs_info);
4313 btrfs_err(fs_info, "commit super ret %d", ret);
4316 if (BTRFS_FS_ERROR(fs_info))
4317 btrfs_error_commit_super(fs_info);
4319 kthread_stop(fs_info->transaction_kthread);
4320 kthread_stop(fs_info->cleaner_kthread);
4322 ASSERT(list_empty(&fs_info->delayed_iputs));
4323 set_bit(BTRFS_FS_CLOSING_DONE, &fs_info->flags);
4325 if (btrfs_check_quota_leak(fs_info)) {
4326 WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
4327 btrfs_err(fs_info, "qgroup reserved space leaked");
4330 btrfs_free_qgroup_config(fs_info);
4331 ASSERT(list_empty(&fs_info->delalloc_roots));
4333 if (percpu_counter_sum(&fs_info->delalloc_bytes)) {
4334 btrfs_info(fs_info, "at unmount delalloc count %lld",
4335 percpu_counter_sum(&fs_info->delalloc_bytes));
4338 if (percpu_counter_sum(&fs_info->ordered_bytes))
4339 btrfs_info(fs_info, "at unmount dio bytes count %lld",
4340 percpu_counter_sum(&fs_info->ordered_bytes));
4342 btrfs_sysfs_remove_mounted(fs_info);
4343 btrfs_sysfs_remove_fsid(fs_info->fs_devices);
4345 btrfs_put_block_group_cache(fs_info);
4348 * we must make sure there is not any read request to
4349 * submit after we stopping all workers.
4351 invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
4352 btrfs_stop_all_workers(fs_info);
4354 /* We shouldn't have any transaction open at this point */
4355 warn_about_uncommitted_trans(fs_info);
4357 clear_bit(BTRFS_FS_OPEN, &fs_info->flags);
4358 free_root_pointers(fs_info, true);
4359 btrfs_free_fs_roots(fs_info);
4362 * We must free the block groups after dropping the fs_roots as we could
4363 * have had an IO error and have left over tree log blocks that aren't
4364 * cleaned up until the fs roots are freed. This makes the block group
4365 * accounting appear to be wrong because there's pending reserved bytes,
4366 * so make sure we do the block group cleanup afterwards.
4368 btrfs_free_block_groups(fs_info);
4370 iput(fs_info->btree_inode);
4372 btrfs_mapping_tree_free(fs_info);
4373 btrfs_close_devices(fs_info->fs_devices);
4376 void btrfs_mark_buffer_dirty(struct btrfs_trans_handle *trans,
4377 struct extent_buffer *buf)
4379 struct btrfs_fs_info *fs_info = buf->fs_info;
4380 u64 transid = btrfs_header_generation(buf);
4382 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
4384 * This is a fast path so only do this check if we have sanity tests
4385 * enabled. Normal people shouldn't be using unmapped buffers as dirty
4386 * outside of the sanity tests.
4388 if (unlikely(test_bit(EXTENT_BUFFER_UNMAPPED, &buf->bflags)))
4391 /* This is an active transaction (its state < TRANS_STATE_UNBLOCKED). */
4392 ASSERT(trans->transid == fs_info->generation);
4393 btrfs_assert_tree_write_locked(buf);
4394 if (unlikely(transid != fs_info->generation)) {
4395 btrfs_abort_transaction(trans, -EUCLEAN);
4397 "dirty buffer transid mismatch, logical %llu found transid %llu running transid %llu",
4398 buf->start, transid, fs_info->generation);
4400 set_extent_buffer_dirty(buf);
4403 static void __btrfs_btree_balance_dirty(struct btrfs_fs_info *fs_info,
4407 * looks as though older kernels can get into trouble with
4408 * this code, they end up stuck in balance_dirty_pages forever
4412 if (current->flags & PF_MEMALLOC)
4416 btrfs_balance_delayed_items(fs_info);
4418 ret = __percpu_counter_compare(&fs_info->dirty_metadata_bytes,
4419 BTRFS_DIRTY_METADATA_THRESH,
4420 fs_info->dirty_metadata_batch);
4422 balance_dirty_pages_ratelimited(fs_info->btree_inode->i_mapping);
4426 void btrfs_btree_balance_dirty(struct btrfs_fs_info *fs_info)
4428 __btrfs_btree_balance_dirty(fs_info, 1);
4431 void btrfs_btree_balance_dirty_nodelay(struct btrfs_fs_info *fs_info)
4433 __btrfs_btree_balance_dirty(fs_info, 0);
4436 static void btrfs_error_commit_super(struct btrfs_fs_info *fs_info)
4438 /* cleanup FS via transaction */
4439 btrfs_cleanup_transaction(fs_info);
4441 mutex_lock(&fs_info->cleaner_mutex);
4442 btrfs_run_delayed_iputs(fs_info);
4443 mutex_unlock(&fs_info->cleaner_mutex);
4445 down_write(&fs_info->cleanup_work_sem);
4446 up_write(&fs_info->cleanup_work_sem);
4449 static void btrfs_drop_all_logs(struct btrfs_fs_info *fs_info)
4451 struct btrfs_root *gang[8];
4452 u64 root_objectid = 0;
4455 spin_lock(&fs_info->fs_roots_radix_lock);
4456 while ((ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
4457 (void **)gang, root_objectid,
4458 ARRAY_SIZE(gang))) != 0) {
4461 for (i = 0; i < ret; i++)
4462 gang[i] = btrfs_grab_root(gang[i]);
4463 spin_unlock(&fs_info->fs_roots_radix_lock);
4465 for (i = 0; i < ret; i++) {
4468 root_objectid = gang[i]->root_key.objectid;
4469 btrfs_free_log(NULL, gang[i]);
4470 btrfs_put_root(gang[i]);
4473 spin_lock(&fs_info->fs_roots_radix_lock);
4475 spin_unlock(&fs_info->fs_roots_radix_lock);
4476 btrfs_free_log_root_tree(NULL, fs_info);
4479 static void btrfs_destroy_ordered_extents(struct btrfs_root *root)
4481 struct btrfs_ordered_extent *ordered;
4483 spin_lock(&root->ordered_extent_lock);
4485 * This will just short circuit the ordered completion stuff which will
4486 * make sure the ordered extent gets properly cleaned up.
4488 list_for_each_entry(ordered, &root->ordered_extents,
4490 set_bit(BTRFS_ORDERED_IOERR, &ordered->flags);
4491 spin_unlock(&root->ordered_extent_lock);
4494 static void btrfs_destroy_all_ordered_extents(struct btrfs_fs_info *fs_info)
4496 struct btrfs_root *root;
4499 spin_lock(&fs_info->ordered_root_lock);
4500 list_splice_init(&fs_info->ordered_roots, &splice);
4501 while (!list_empty(&splice)) {
4502 root = list_first_entry(&splice, struct btrfs_root,
4504 list_move_tail(&root->ordered_root,
4505 &fs_info->ordered_roots);
4507 spin_unlock(&fs_info->ordered_root_lock);
4508 btrfs_destroy_ordered_extents(root);
4511 spin_lock(&fs_info->ordered_root_lock);
4513 spin_unlock(&fs_info->ordered_root_lock);
4516 * We need this here because if we've been flipped read-only we won't
4517 * get sync() from the umount, so we need to make sure any ordered
4518 * extents that haven't had their dirty pages IO start writeout yet
4519 * actually get run and error out properly.
4521 btrfs_wait_ordered_roots(fs_info, U64_MAX, 0, (u64)-1);
4524 static void btrfs_destroy_delayed_refs(struct btrfs_transaction *trans,
4525 struct btrfs_fs_info *fs_info)
4527 struct rb_node *node;
4528 struct btrfs_delayed_ref_root *delayed_refs;
4529 struct btrfs_delayed_ref_node *ref;
4531 delayed_refs = &trans->delayed_refs;
4533 spin_lock(&delayed_refs->lock);
4534 if (atomic_read(&delayed_refs->num_entries) == 0) {
4535 spin_unlock(&delayed_refs->lock);
4536 btrfs_debug(fs_info, "delayed_refs has NO entry");
4540 while ((node = rb_first_cached(&delayed_refs->href_root)) != NULL) {
4541 struct btrfs_delayed_ref_head *head;
4543 bool pin_bytes = false;
4545 head = rb_entry(node, struct btrfs_delayed_ref_head,
4547 if (btrfs_delayed_ref_lock(delayed_refs, head))
4550 spin_lock(&head->lock);
4551 while ((n = rb_first_cached(&head->ref_tree)) != NULL) {
4552 ref = rb_entry(n, struct btrfs_delayed_ref_node,
4554 rb_erase_cached(&ref->ref_node, &head->ref_tree);
4555 RB_CLEAR_NODE(&ref->ref_node);
4556 if (!list_empty(&ref->add_list))
4557 list_del(&ref->add_list);
4558 atomic_dec(&delayed_refs->num_entries);
4559 btrfs_put_delayed_ref(ref);
4560 btrfs_delayed_refs_rsv_release(fs_info, 1, 0);
4562 if (head->must_insert_reserved)
4564 btrfs_free_delayed_extent_op(head->extent_op);
4565 btrfs_delete_ref_head(delayed_refs, head);
4566 spin_unlock(&head->lock);
4567 spin_unlock(&delayed_refs->lock);
4568 mutex_unlock(&head->mutex);
4571 struct btrfs_block_group *cache;
4573 cache = btrfs_lookup_block_group(fs_info, head->bytenr);
4576 spin_lock(&cache->space_info->lock);
4577 spin_lock(&cache->lock);
4578 cache->pinned += head->num_bytes;
4579 btrfs_space_info_update_bytes_pinned(fs_info,
4580 cache->space_info, head->num_bytes);
4581 cache->reserved -= head->num_bytes;
4582 cache->space_info->bytes_reserved -= head->num_bytes;
4583 spin_unlock(&cache->lock);
4584 spin_unlock(&cache->space_info->lock);
4586 btrfs_put_block_group(cache);
4588 btrfs_error_unpin_extent_range(fs_info, head->bytenr,
4589 head->bytenr + head->num_bytes - 1);
4591 btrfs_cleanup_ref_head_accounting(fs_info, delayed_refs, head);
4592 btrfs_put_delayed_ref_head(head);
4594 spin_lock(&delayed_refs->lock);
4596 btrfs_qgroup_destroy_extent_records(trans);
4598 spin_unlock(&delayed_refs->lock);
4601 static void btrfs_destroy_delalloc_inodes(struct btrfs_root *root)
4603 struct btrfs_inode *btrfs_inode;
4606 spin_lock(&root->delalloc_lock);
4607 list_splice_init(&root->delalloc_inodes, &splice);
4609 while (!list_empty(&splice)) {
4610 struct inode *inode = NULL;
4611 btrfs_inode = list_first_entry(&splice, struct btrfs_inode,
4613 __btrfs_del_delalloc_inode(root, btrfs_inode);
4614 spin_unlock(&root->delalloc_lock);
4617 * Make sure we get a live inode and that it'll not disappear
4620 inode = igrab(&btrfs_inode->vfs_inode);
4622 unsigned int nofs_flag;
4624 nofs_flag = memalloc_nofs_save();
4625 invalidate_inode_pages2(inode->i_mapping);
4626 memalloc_nofs_restore(nofs_flag);
4629 spin_lock(&root->delalloc_lock);
4631 spin_unlock(&root->delalloc_lock);
4634 static void btrfs_destroy_all_delalloc_inodes(struct btrfs_fs_info *fs_info)
4636 struct btrfs_root *root;
4639 spin_lock(&fs_info->delalloc_root_lock);
4640 list_splice_init(&fs_info->delalloc_roots, &splice);
4641 while (!list_empty(&splice)) {
4642 root = list_first_entry(&splice, struct btrfs_root,
4644 root = btrfs_grab_root(root);
4646 spin_unlock(&fs_info->delalloc_root_lock);
4648 btrfs_destroy_delalloc_inodes(root);
4649 btrfs_put_root(root);
4651 spin_lock(&fs_info->delalloc_root_lock);
4653 spin_unlock(&fs_info->delalloc_root_lock);
4656 static void btrfs_destroy_marked_extents(struct btrfs_fs_info *fs_info,
4657 struct extent_io_tree *dirty_pages,
4660 struct extent_buffer *eb;
4664 while (find_first_extent_bit(dirty_pages, start, &start, &end,
4666 clear_extent_bits(dirty_pages, start, end, mark);
4667 while (start <= end) {
4668 eb = find_extent_buffer(fs_info, start);
4669 start += fs_info->nodesize;
4673 btrfs_tree_lock(eb);
4674 wait_on_extent_buffer_writeback(eb);
4675 btrfs_clear_buffer_dirty(NULL, eb);
4676 btrfs_tree_unlock(eb);
4678 free_extent_buffer_stale(eb);
4683 static void btrfs_destroy_pinned_extent(struct btrfs_fs_info *fs_info,
4684 struct extent_io_tree *unpin)
4690 struct extent_state *cached_state = NULL;
4693 * The btrfs_finish_extent_commit() may get the same range as
4694 * ours between find_first_extent_bit and clear_extent_dirty.
4695 * Hence, hold the unused_bg_unpin_mutex to avoid double unpin
4696 * the same extent range.
4698 mutex_lock(&fs_info->unused_bg_unpin_mutex);
4699 if (!find_first_extent_bit(unpin, 0, &start, &end,
4700 EXTENT_DIRTY, &cached_state)) {
4701 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
4705 clear_extent_dirty(unpin, start, end, &cached_state);
4706 free_extent_state(cached_state);
4707 btrfs_error_unpin_extent_range(fs_info, start, end);
4708 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
4713 static void btrfs_cleanup_bg_io(struct btrfs_block_group *cache)
4715 struct inode *inode;
4717 inode = cache->io_ctl.inode;
4719 unsigned int nofs_flag;
4721 nofs_flag = memalloc_nofs_save();
4722 invalidate_inode_pages2(inode->i_mapping);
4723 memalloc_nofs_restore(nofs_flag);
4725 BTRFS_I(inode)->generation = 0;
4726 cache->io_ctl.inode = NULL;
4729 ASSERT(cache->io_ctl.pages == NULL);
4730 btrfs_put_block_group(cache);
4733 void btrfs_cleanup_dirty_bgs(struct btrfs_transaction *cur_trans,
4734 struct btrfs_fs_info *fs_info)
4736 struct btrfs_block_group *cache;
4738 spin_lock(&cur_trans->dirty_bgs_lock);
4739 while (!list_empty(&cur_trans->dirty_bgs)) {
4740 cache = list_first_entry(&cur_trans->dirty_bgs,
4741 struct btrfs_block_group,
4744 if (!list_empty(&cache->io_list)) {
4745 spin_unlock(&cur_trans->dirty_bgs_lock);
4746 list_del_init(&cache->io_list);
4747 btrfs_cleanup_bg_io(cache);
4748 spin_lock(&cur_trans->dirty_bgs_lock);
4751 list_del_init(&cache->dirty_list);
4752 spin_lock(&cache->lock);
4753 cache->disk_cache_state = BTRFS_DC_ERROR;
4754 spin_unlock(&cache->lock);
4756 spin_unlock(&cur_trans->dirty_bgs_lock);
4757 btrfs_put_block_group(cache);
4758 btrfs_dec_delayed_refs_rsv_bg_updates(fs_info);
4759 spin_lock(&cur_trans->dirty_bgs_lock);
4761 spin_unlock(&cur_trans->dirty_bgs_lock);
4764 * Refer to the definition of io_bgs member for details why it's safe
4765 * to use it without any locking
4767 while (!list_empty(&cur_trans->io_bgs)) {
4768 cache = list_first_entry(&cur_trans->io_bgs,
4769 struct btrfs_block_group,
4772 list_del_init(&cache->io_list);
4773 spin_lock(&cache->lock);
4774 cache->disk_cache_state = BTRFS_DC_ERROR;
4775 spin_unlock(&cache->lock);
4776 btrfs_cleanup_bg_io(cache);
4780 static void btrfs_free_all_qgroup_pertrans(struct btrfs_fs_info *fs_info)
4782 struct btrfs_root *gang[8];
4786 spin_lock(&fs_info->fs_roots_radix_lock);
4788 ret = radix_tree_gang_lookup_tag(&fs_info->fs_roots_radix,
4791 BTRFS_ROOT_TRANS_TAG);
4794 for (i = 0; i < ret; i++) {
4795 struct btrfs_root *root = gang[i];
4797 btrfs_qgroup_free_meta_all_pertrans(root);
4798 radix_tree_tag_clear(&fs_info->fs_roots_radix,
4799 (unsigned long)root->root_key.objectid,
4800 BTRFS_ROOT_TRANS_TAG);
4803 spin_unlock(&fs_info->fs_roots_radix_lock);
4806 void btrfs_cleanup_one_transaction(struct btrfs_transaction *cur_trans,
4807 struct btrfs_fs_info *fs_info)
4809 struct btrfs_device *dev, *tmp;
4811 btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
4812 ASSERT(list_empty(&cur_trans->dirty_bgs));
4813 ASSERT(list_empty(&cur_trans->io_bgs));
4815 list_for_each_entry_safe(dev, tmp, &cur_trans->dev_update_list,
4817 list_del_init(&dev->post_commit_list);
4820 btrfs_destroy_delayed_refs(cur_trans, fs_info);
4822 cur_trans->state = TRANS_STATE_COMMIT_START;
4823 wake_up(&fs_info->transaction_blocked_wait);
4825 cur_trans->state = TRANS_STATE_UNBLOCKED;
4826 wake_up(&fs_info->transaction_wait);
4828 btrfs_destroy_delayed_inodes(fs_info);
4830 btrfs_destroy_marked_extents(fs_info, &cur_trans->dirty_pages,
4832 btrfs_destroy_pinned_extent(fs_info, &cur_trans->pinned_extents);
4834 btrfs_free_all_qgroup_pertrans(fs_info);
4836 cur_trans->state =TRANS_STATE_COMPLETED;
4837 wake_up(&cur_trans->commit_wait);
4840 static int btrfs_cleanup_transaction(struct btrfs_fs_info *fs_info)
4842 struct btrfs_transaction *t;
4844 mutex_lock(&fs_info->transaction_kthread_mutex);
4846 spin_lock(&fs_info->trans_lock);
4847 while (!list_empty(&fs_info->trans_list)) {
4848 t = list_first_entry(&fs_info->trans_list,
4849 struct btrfs_transaction, list);
4850 if (t->state >= TRANS_STATE_COMMIT_PREP) {
4851 refcount_inc(&t->use_count);
4852 spin_unlock(&fs_info->trans_lock);
4853 btrfs_wait_for_commit(fs_info, t->transid);
4854 btrfs_put_transaction(t);
4855 spin_lock(&fs_info->trans_lock);
4858 if (t == fs_info->running_transaction) {
4859 t->state = TRANS_STATE_COMMIT_DOING;
4860 spin_unlock(&fs_info->trans_lock);
4862 * We wait for 0 num_writers since we don't hold a trans
4863 * handle open currently for this transaction.
4865 wait_event(t->writer_wait,
4866 atomic_read(&t->num_writers) == 0);
4868 spin_unlock(&fs_info->trans_lock);
4870 btrfs_cleanup_one_transaction(t, fs_info);
4872 spin_lock(&fs_info->trans_lock);
4873 if (t == fs_info->running_transaction)
4874 fs_info->running_transaction = NULL;
4875 list_del_init(&t->list);
4876 spin_unlock(&fs_info->trans_lock);
4878 btrfs_put_transaction(t);
4879 trace_btrfs_transaction_commit(fs_info);
4880 spin_lock(&fs_info->trans_lock);
4882 spin_unlock(&fs_info->trans_lock);
4883 btrfs_destroy_all_ordered_extents(fs_info);
4884 btrfs_destroy_delayed_inodes(fs_info);
4885 btrfs_assert_delayed_root_empty(fs_info);
4886 btrfs_destroy_all_delalloc_inodes(fs_info);
4887 btrfs_drop_all_logs(fs_info);
4888 mutex_unlock(&fs_info->transaction_kthread_mutex);
4893 int btrfs_init_root_free_objectid(struct btrfs_root *root)
4895 struct btrfs_path *path;
4897 struct extent_buffer *l;
4898 struct btrfs_key search_key;
4899 struct btrfs_key found_key;
4902 path = btrfs_alloc_path();
4906 search_key.objectid = BTRFS_LAST_FREE_OBJECTID;
4907 search_key.type = -1;
4908 search_key.offset = (u64)-1;
4909 ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
4912 BUG_ON(ret == 0); /* Corruption */
4913 if (path->slots[0] > 0) {
4914 slot = path->slots[0] - 1;
4916 btrfs_item_key_to_cpu(l, &found_key, slot);
4917 root->free_objectid = max_t(u64, found_key.objectid + 1,
4918 BTRFS_FIRST_FREE_OBJECTID);
4920 root->free_objectid = BTRFS_FIRST_FREE_OBJECTID;
4924 btrfs_free_path(path);
4928 int btrfs_get_free_objectid(struct btrfs_root *root, u64 *objectid)
4931 mutex_lock(&root->objectid_mutex);
4933 if (unlikely(root->free_objectid >= BTRFS_LAST_FREE_OBJECTID)) {
4934 btrfs_warn(root->fs_info,
4935 "the objectid of root %llu reaches its highest value",
4936 root->root_key.objectid);
4941 *objectid = root->free_objectid++;
4944 mutex_unlock(&root->objectid_mutex);