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/buffer_head.h>
11 #include <linux/workqueue.h>
12 #include <linux/kthread.h>
13 #include <linux/slab.h>
14 #include <linux/migrate.h>
15 #include <linux/ratelimit.h>
16 #include <linux/uuid.h>
17 #include <linux/semaphore.h>
18 #include <linux/error-injection.h>
19 #include <linux/crc32c.h>
20 #include <linux/sched/mm.h>
21 #include <asm/unaligned.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 "inode-map.h"
33 #include "check-integrity.h"
34 #include "rcu-string.h"
35 #include "dev-replace.h"
39 #include "compression.h"
40 #include "tree-checker.h"
41 #include "ref-verify.h"
43 #define BTRFS_SUPER_FLAG_SUPP (BTRFS_HEADER_FLAG_WRITTEN |\
44 BTRFS_HEADER_FLAG_RELOC |\
45 BTRFS_SUPER_FLAG_ERROR |\
46 BTRFS_SUPER_FLAG_SEEDING |\
47 BTRFS_SUPER_FLAG_METADUMP |\
48 BTRFS_SUPER_FLAG_METADUMP_V2)
50 static const struct extent_io_ops btree_extent_io_ops;
51 static void end_workqueue_fn(struct btrfs_work *work);
52 static void btrfs_destroy_ordered_extents(struct btrfs_root *root);
53 static int btrfs_destroy_delayed_refs(struct btrfs_transaction *trans,
54 struct btrfs_fs_info *fs_info);
55 static void btrfs_destroy_delalloc_inodes(struct btrfs_root *root);
56 static int btrfs_destroy_marked_extents(struct btrfs_fs_info *fs_info,
57 struct extent_io_tree *dirty_pages,
59 static int btrfs_destroy_pinned_extent(struct btrfs_fs_info *fs_info,
60 struct extent_io_tree *pinned_extents);
61 static int btrfs_cleanup_transaction(struct btrfs_fs_info *fs_info);
62 static void btrfs_error_commit_super(struct btrfs_fs_info *fs_info);
65 * btrfs_end_io_wq structs are used to do processing in task context when an IO
66 * is complete. This is used during reads to verify checksums, and it is used
67 * by writes to insert metadata for new file extents after IO is complete.
69 struct btrfs_end_io_wq {
73 struct btrfs_fs_info *info;
75 enum btrfs_wq_endio_type metadata;
76 struct btrfs_work work;
79 static struct kmem_cache *btrfs_end_io_wq_cache;
81 int __init btrfs_end_io_wq_init(void)
83 btrfs_end_io_wq_cache = kmem_cache_create("btrfs_end_io_wq",
84 sizeof(struct btrfs_end_io_wq),
88 if (!btrfs_end_io_wq_cache)
93 void __cold btrfs_end_io_wq_exit(void)
95 kmem_cache_destroy(btrfs_end_io_wq_cache);
99 * async submit bios are used to offload expensive checksumming
100 * onto the worker threads. They checksum file and metadata bios
101 * just before they are sent down the IO stack.
103 struct async_submit_bio {
106 extent_submit_bio_start_t *submit_bio_start;
109 * bio_offset is optional, can be used if the pages in the bio
110 * can't tell us where in the file the bio should go
113 struct btrfs_work work;
118 * Lockdep class keys for extent_buffer->lock's in this root. For a given
119 * eb, the lockdep key is determined by the btrfs_root it belongs to and
120 * the level the eb occupies in the tree.
122 * Different roots are used for different purposes and may nest inside each
123 * other and they require separate keysets. As lockdep keys should be
124 * static, assign keysets according to the purpose of the root as indicated
125 * by btrfs_root->root_key.objectid. This ensures that all special purpose
126 * roots have separate keysets.
128 * Lock-nesting across peer nodes is always done with the immediate parent
129 * node locked thus preventing deadlock. As lockdep doesn't know this, use
130 * subclass to avoid triggering lockdep warning in such cases.
132 * The key is set by the readpage_end_io_hook after the buffer has passed
133 * csum validation but before the pages are unlocked. It is also set by
134 * btrfs_init_new_buffer on freshly allocated blocks.
136 * We also add a check to make sure the highest level of the tree is the
137 * same as our lockdep setup here. If BTRFS_MAX_LEVEL changes, this code
138 * needs update as well.
140 #ifdef CONFIG_DEBUG_LOCK_ALLOC
141 # if BTRFS_MAX_LEVEL != 8
145 static struct btrfs_lockdep_keyset {
146 u64 id; /* root objectid */
147 const char *name_stem; /* lock name stem */
148 char names[BTRFS_MAX_LEVEL + 1][20];
149 struct lock_class_key keys[BTRFS_MAX_LEVEL + 1];
150 } btrfs_lockdep_keysets[] = {
151 { .id = BTRFS_ROOT_TREE_OBJECTID, .name_stem = "root" },
152 { .id = BTRFS_EXTENT_TREE_OBJECTID, .name_stem = "extent" },
153 { .id = BTRFS_CHUNK_TREE_OBJECTID, .name_stem = "chunk" },
154 { .id = BTRFS_DEV_TREE_OBJECTID, .name_stem = "dev" },
155 { .id = BTRFS_FS_TREE_OBJECTID, .name_stem = "fs" },
156 { .id = BTRFS_CSUM_TREE_OBJECTID, .name_stem = "csum" },
157 { .id = BTRFS_QUOTA_TREE_OBJECTID, .name_stem = "quota" },
158 { .id = BTRFS_TREE_LOG_OBJECTID, .name_stem = "log" },
159 { .id = BTRFS_TREE_RELOC_OBJECTID, .name_stem = "treloc" },
160 { .id = BTRFS_DATA_RELOC_TREE_OBJECTID, .name_stem = "dreloc" },
161 { .id = BTRFS_UUID_TREE_OBJECTID, .name_stem = "uuid" },
162 { .id = BTRFS_FREE_SPACE_TREE_OBJECTID, .name_stem = "free-space" },
163 { .id = 0, .name_stem = "tree" },
166 void __init btrfs_init_lockdep(void)
170 /* initialize lockdep class names */
171 for (i = 0; i < ARRAY_SIZE(btrfs_lockdep_keysets); i++) {
172 struct btrfs_lockdep_keyset *ks = &btrfs_lockdep_keysets[i];
174 for (j = 0; j < ARRAY_SIZE(ks->names); j++)
175 snprintf(ks->names[j], sizeof(ks->names[j]),
176 "btrfs-%s-%02d", ks->name_stem, j);
180 void btrfs_set_buffer_lockdep_class(u64 objectid, struct extent_buffer *eb,
183 struct btrfs_lockdep_keyset *ks;
185 BUG_ON(level >= ARRAY_SIZE(ks->keys));
187 /* find the matching keyset, id 0 is the default entry */
188 for (ks = btrfs_lockdep_keysets; ks->id; ks++)
189 if (ks->id == objectid)
192 lockdep_set_class_and_name(&eb->lock,
193 &ks->keys[level], ks->names[level]);
199 * extents on the btree inode are pretty simple, there's one extent
200 * that covers the entire device
202 struct extent_map *btree_get_extent(struct btrfs_inode *inode,
203 struct page *page, size_t pg_offset, u64 start, u64 len,
206 struct btrfs_fs_info *fs_info = inode->root->fs_info;
207 struct extent_map_tree *em_tree = &inode->extent_tree;
208 struct extent_map *em;
211 read_lock(&em_tree->lock);
212 em = lookup_extent_mapping(em_tree, start, len);
214 em->bdev = fs_info->fs_devices->latest_bdev;
215 read_unlock(&em_tree->lock);
218 read_unlock(&em_tree->lock);
220 em = alloc_extent_map();
222 em = ERR_PTR(-ENOMEM);
227 em->block_len = (u64)-1;
229 em->bdev = fs_info->fs_devices->latest_bdev;
231 write_lock(&em_tree->lock);
232 ret = add_extent_mapping(em_tree, em, 0);
233 if (ret == -EEXIST) {
235 em = lookup_extent_mapping(em_tree, start, len);
242 write_unlock(&em_tree->lock);
248 u32 btrfs_csum_data(const char *data, u32 seed, size_t len)
250 return crc32c(seed, data, len);
253 void btrfs_csum_final(u32 crc, u8 *result)
255 put_unaligned_le32(~crc, result);
259 * Compute the csum of a btree block and store the result to provided buffer.
261 * Returns error if the extent buffer cannot be mapped.
263 static int csum_tree_block(struct extent_buffer *buf, u8 *result)
266 unsigned long cur_len;
267 unsigned long offset = BTRFS_CSUM_SIZE;
269 unsigned long map_start;
270 unsigned long map_len;
274 len = buf->len - offset;
277 * Note: we don't need to check for the err == 1 case here, as
278 * with the given combination of 'start = BTRFS_CSUM_SIZE (32)'
279 * and 'min_len = 32' and the currently implemented mapping
280 * algorithm we cannot cross a page boundary.
282 err = map_private_extent_buffer(buf, offset, 32,
283 &kaddr, &map_start, &map_len);
286 cur_len = min(len, map_len - (offset - map_start));
287 crc = btrfs_csum_data(kaddr + offset - map_start,
292 memset(result, 0, BTRFS_CSUM_SIZE);
294 btrfs_csum_final(crc, result);
300 * we can't consider a given block up to date unless the transid of the
301 * block matches the transid in the parent node's pointer. This is how we
302 * detect blocks that either didn't get written at all or got written
303 * in the wrong place.
305 static int verify_parent_transid(struct extent_io_tree *io_tree,
306 struct extent_buffer *eb, u64 parent_transid,
309 struct extent_state *cached_state = NULL;
311 bool need_lock = (current->journal_info == BTRFS_SEND_TRANS_STUB);
313 if (!parent_transid || btrfs_header_generation(eb) == parent_transid)
320 btrfs_tree_read_lock(eb);
321 btrfs_set_lock_blocking_read(eb);
324 lock_extent_bits(io_tree, eb->start, eb->start + eb->len - 1,
326 if (extent_buffer_uptodate(eb) &&
327 btrfs_header_generation(eb) == parent_transid) {
331 btrfs_err_rl(eb->fs_info,
332 "parent transid verify failed on %llu wanted %llu found %llu",
334 parent_transid, btrfs_header_generation(eb));
338 * Things reading via commit roots that don't have normal protection,
339 * like send, can have a really old block in cache that may point at a
340 * block that has been freed and re-allocated. So don't clear uptodate
341 * if we find an eb that is under IO (dirty/writeback) because we could
342 * end up reading in the stale data and then writing it back out and
343 * making everybody very sad.
345 if (!extent_buffer_under_io(eb))
346 clear_extent_buffer_uptodate(eb);
348 unlock_extent_cached(io_tree, eb->start, eb->start + eb->len - 1,
351 btrfs_tree_read_unlock_blocking(eb);
355 static bool btrfs_supported_super_csum(u16 csum_type)
358 case BTRFS_CSUM_TYPE_CRC32:
366 * Return 0 if the superblock checksum type matches the checksum value of that
367 * algorithm. Pass the raw disk superblock data.
369 static int btrfs_check_super_csum(struct btrfs_fs_info *fs_info,
372 struct btrfs_super_block *disk_sb =
373 (struct btrfs_super_block *)raw_disk_sb;
375 char result[BTRFS_CSUM_SIZE];
378 * The super_block structure does not span the whole
379 * BTRFS_SUPER_INFO_SIZE range, we expect that the unused space is
380 * filled with zeros and is included in the checksum.
382 crc = btrfs_csum_data(raw_disk_sb + BTRFS_CSUM_SIZE,
383 crc, BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE);
384 btrfs_csum_final(crc, result);
386 if (memcmp(disk_sb->csum, result, btrfs_super_csum_size(disk_sb)))
392 int btrfs_verify_level_key(struct extent_buffer *eb, int level,
393 struct btrfs_key *first_key, u64 parent_transid)
395 struct btrfs_fs_info *fs_info = eb->fs_info;
397 struct btrfs_key found_key;
400 found_level = btrfs_header_level(eb);
401 if (found_level != level) {
402 WARN(IS_ENABLED(CONFIG_BTRFS_DEBUG),
403 KERN_ERR "BTRFS: tree level check failed\n");
405 "tree level mismatch detected, bytenr=%llu level expected=%u has=%u",
406 eb->start, level, found_level);
414 * For live tree block (new tree blocks in current transaction),
415 * we need proper lock context to avoid race, which is impossible here.
416 * So we only checks tree blocks which is read from disk, whose
417 * generation <= fs_info->last_trans_committed.
419 if (btrfs_header_generation(eb) > fs_info->last_trans_committed)
422 btrfs_node_key_to_cpu(eb, &found_key, 0);
424 btrfs_item_key_to_cpu(eb, &found_key, 0);
425 ret = btrfs_comp_cpu_keys(first_key, &found_key);
428 WARN(IS_ENABLED(CONFIG_BTRFS_DEBUG),
429 KERN_ERR "BTRFS: tree first key check failed\n");
431 "tree first key mismatch detected, bytenr=%llu parent_transid=%llu key expected=(%llu,%u,%llu) has=(%llu,%u,%llu)",
432 eb->start, parent_transid, first_key->objectid,
433 first_key->type, first_key->offset,
434 found_key.objectid, found_key.type,
441 * helper to read a given tree block, doing retries as required when
442 * the checksums don't match and we have alternate mirrors to try.
444 * @parent_transid: expected transid, skip check if 0
445 * @level: expected level, mandatory check
446 * @first_key: expected key of first slot, skip check if NULL
448 static int btree_read_extent_buffer_pages(struct extent_buffer *eb,
449 u64 parent_transid, int level,
450 struct btrfs_key *first_key)
452 struct btrfs_fs_info *fs_info = eb->fs_info;
453 struct extent_io_tree *io_tree;
458 int failed_mirror = 0;
460 io_tree = &BTRFS_I(fs_info->btree_inode)->io_tree;
462 clear_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags);
463 ret = read_extent_buffer_pages(eb, WAIT_COMPLETE, mirror_num);
465 if (verify_parent_transid(io_tree, eb,
468 else if (btrfs_verify_level_key(eb, level,
469 first_key, parent_transid))
475 num_copies = btrfs_num_copies(fs_info,
480 if (!failed_mirror) {
482 failed_mirror = eb->read_mirror;
486 if (mirror_num == failed_mirror)
489 if (mirror_num > num_copies)
493 if (failed && !ret && failed_mirror)
494 btrfs_repair_eb_io_failure(eb, failed_mirror);
500 * checksum a dirty tree block before IO. This has extra checks to make sure
501 * we only fill in the checksum field in the first page of a multi-page block
504 static int csum_dirty_buffer(struct btrfs_fs_info *fs_info, struct page *page)
506 u64 start = page_offset(page);
508 u8 result[BTRFS_CSUM_SIZE];
509 u16 csum_size = btrfs_super_csum_size(fs_info->super_copy);
510 struct extent_buffer *eb;
513 eb = (struct extent_buffer *)page->private;
514 if (page != eb->pages[0])
517 found_start = btrfs_header_bytenr(eb);
519 * Please do not consolidate these warnings into a single if.
520 * It is useful to know what went wrong.
522 if (WARN_ON(found_start != start))
524 if (WARN_ON(!PageUptodate(page)))
527 ASSERT(memcmp_extent_buffer(eb, fs_info->fs_devices->metadata_uuid,
528 btrfs_header_fsid(), BTRFS_FSID_SIZE) == 0);
530 if (csum_tree_block(eb, result))
533 if (btrfs_header_level(eb))
534 ret = btrfs_check_node(eb);
536 ret = btrfs_check_leaf_full(eb);
540 "block=%llu write time tree block corruption detected",
544 write_extent_buffer(eb, result, 0, csum_size);
549 static int check_tree_block_fsid(struct extent_buffer *eb)
551 struct btrfs_fs_info *fs_info = eb->fs_info;
552 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
553 u8 fsid[BTRFS_FSID_SIZE];
556 read_extent_buffer(eb, fsid, btrfs_header_fsid(), BTRFS_FSID_SIZE);
561 * Checking the incompat flag is only valid for the current
562 * fs. For seed devices it's forbidden to have their uuid
563 * changed so reading ->fsid in this case is fine
565 if (fs_devices == fs_info->fs_devices &&
566 btrfs_fs_incompat(fs_info, METADATA_UUID))
567 metadata_uuid = fs_devices->metadata_uuid;
569 metadata_uuid = fs_devices->fsid;
571 if (!memcmp(fsid, metadata_uuid, BTRFS_FSID_SIZE)) {
575 fs_devices = fs_devices->seed;
580 static int btree_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
581 u64 phy_offset, struct page *page,
582 u64 start, u64 end, int mirror)
586 struct extent_buffer *eb;
587 struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
588 struct btrfs_fs_info *fs_info = root->fs_info;
589 u16 csum_size = btrfs_super_csum_size(fs_info->super_copy);
591 u8 result[BTRFS_CSUM_SIZE];
597 eb = (struct extent_buffer *)page->private;
599 /* the pending IO might have been the only thing that kept this buffer
600 * in memory. Make sure we have a ref for all this other checks
602 extent_buffer_get(eb);
604 reads_done = atomic_dec_and_test(&eb->io_pages);
608 eb->read_mirror = mirror;
609 if (test_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags)) {
614 found_start = btrfs_header_bytenr(eb);
615 if (found_start != eb->start) {
616 btrfs_err_rl(fs_info, "bad tree block start, want %llu have %llu",
617 eb->start, found_start);
621 if (check_tree_block_fsid(eb)) {
622 btrfs_err_rl(fs_info, "bad fsid on block %llu",
627 found_level = btrfs_header_level(eb);
628 if (found_level >= BTRFS_MAX_LEVEL) {
629 btrfs_err(fs_info, "bad tree block level %d on %llu",
630 (int)btrfs_header_level(eb), eb->start);
635 btrfs_set_buffer_lockdep_class(btrfs_header_owner(eb),
638 ret = csum_tree_block(eb, result);
642 if (memcmp_extent_buffer(eb, result, 0, csum_size)) {
646 memcpy(&found, result, csum_size);
648 read_extent_buffer(eb, &val, 0, csum_size);
649 btrfs_warn_rl(fs_info,
650 "%s checksum verify failed on %llu wanted %x found %x level %d",
651 fs_info->sb->s_id, eb->start,
652 val, found, btrfs_header_level(eb));
658 * If this is a leaf block and it is corrupt, set the corrupt bit so
659 * that we don't try and read the other copies of this block, just
662 if (found_level == 0 && btrfs_check_leaf_full(eb)) {
663 set_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags);
667 if (found_level > 0 && btrfs_check_node(eb))
671 set_extent_buffer_uptodate(eb);
674 "block=%llu read time tree block corruption detected",
678 test_and_clear_bit(EXTENT_BUFFER_READAHEAD, &eb->bflags))
679 btree_readahead_hook(eb, ret);
683 * our io error hook is going to dec the io pages
684 * again, we have to make sure it has something
687 atomic_inc(&eb->io_pages);
688 clear_extent_buffer_uptodate(eb);
690 free_extent_buffer(eb);
695 static void end_workqueue_bio(struct bio *bio)
697 struct btrfs_end_io_wq *end_io_wq = bio->bi_private;
698 struct btrfs_fs_info *fs_info;
699 struct btrfs_workqueue *wq;
700 btrfs_work_func_t func;
702 fs_info = end_io_wq->info;
703 end_io_wq->status = bio->bi_status;
705 if (bio_op(bio) == REQ_OP_WRITE) {
706 if (end_io_wq->metadata == BTRFS_WQ_ENDIO_METADATA) {
707 wq = fs_info->endio_meta_write_workers;
708 func = btrfs_endio_meta_write_helper;
709 } else if (end_io_wq->metadata == BTRFS_WQ_ENDIO_FREE_SPACE) {
710 wq = fs_info->endio_freespace_worker;
711 func = btrfs_freespace_write_helper;
712 } else if (end_io_wq->metadata == BTRFS_WQ_ENDIO_RAID56) {
713 wq = fs_info->endio_raid56_workers;
714 func = btrfs_endio_raid56_helper;
716 wq = fs_info->endio_write_workers;
717 func = btrfs_endio_write_helper;
720 if (unlikely(end_io_wq->metadata ==
721 BTRFS_WQ_ENDIO_DIO_REPAIR)) {
722 wq = fs_info->endio_repair_workers;
723 func = btrfs_endio_repair_helper;
724 } else if (end_io_wq->metadata == BTRFS_WQ_ENDIO_RAID56) {
725 wq = fs_info->endio_raid56_workers;
726 func = btrfs_endio_raid56_helper;
727 } else if (end_io_wq->metadata) {
728 wq = fs_info->endio_meta_workers;
729 func = btrfs_endio_meta_helper;
731 wq = fs_info->endio_workers;
732 func = btrfs_endio_helper;
736 btrfs_init_work(&end_io_wq->work, func, end_workqueue_fn, NULL, NULL);
737 btrfs_queue_work(wq, &end_io_wq->work);
740 blk_status_t btrfs_bio_wq_end_io(struct btrfs_fs_info *info, struct bio *bio,
741 enum btrfs_wq_endio_type metadata)
743 struct btrfs_end_io_wq *end_io_wq;
745 end_io_wq = kmem_cache_alloc(btrfs_end_io_wq_cache, GFP_NOFS);
747 return BLK_STS_RESOURCE;
749 end_io_wq->private = bio->bi_private;
750 end_io_wq->end_io = bio->bi_end_io;
751 end_io_wq->info = info;
752 end_io_wq->status = 0;
753 end_io_wq->bio = bio;
754 end_io_wq->metadata = metadata;
756 bio->bi_private = end_io_wq;
757 bio->bi_end_io = end_workqueue_bio;
761 static void run_one_async_start(struct btrfs_work *work)
763 struct async_submit_bio *async;
766 async = container_of(work, struct async_submit_bio, work);
767 ret = async->submit_bio_start(async->private_data, async->bio,
774 * In order to insert checksums into the metadata in large chunks, we wait
775 * until bio submission time. All the pages in the bio are checksummed and
776 * sums are attached onto the ordered extent record.
778 * At IO completion time the csums attached on the ordered extent record are
779 * inserted into the tree.
781 static void run_one_async_done(struct btrfs_work *work)
783 struct async_submit_bio *async;
787 async = container_of(work, struct async_submit_bio, work);
788 inode = async->private_data;
790 /* If an error occurred we just want to clean up the bio and move on */
792 async->bio->bi_status = async->status;
793 bio_endio(async->bio);
797 ret = btrfs_map_bio(btrfs_sb(inode->i_sb), async->bio,
798 async->mirror_num, 1);
800 async->bio->bi_status = ret;
801 bio_endio(async->bio);
805 static void run_one_async_free(struct btrfs_work *work)
807 struct async_submit_bio *async;
809 async = container_of(work, struct async_submit_bio, work);
813 blk_status_t btrfs_wq_submit_bio(struct btrfs_fs_info *fs_info, struct bio *bio,
814 int mirror_num, unsigned long bio_flags,
815 u64 bio_offset, void *private_data,
816 extent_submit_bio_start_t *submit_bio_start)
818 struct async_submit_bio *async;
820 async = kmalloc(sizeof(*async), GFP_NOFS);
822 return BLK_STS_RESOURCE;
824 async->private_data = private_data;
826 async->mirror_num = mirror_num;
827 async->submit_bio_start = submit_bio_start;
829 btrfs_init_work(&async->work, btrfs_worker_helper, run_one_async_start,
830 run_one_async_done, run_one_async_free);
832 async->bio_offset = bio_offset;
836 if (op_is_sync(bio->bi_opf))
837 btrfs_set_work_high_priority(&async->work);
839 btrfs_queue_work(fs_info->workers, &async->work);
843 static blk_status_t btree_csum_one_bio(struct bio *bio)
845 struct bio_vec *bvec;
846 struct btrfs_root *root;
848 struct bvec_iter_all iter_all;
850 ASSERT(!bio_flagged(bio, BIO_CLONED));
851 bio_for_each_segment_all(bvec, bio, iter_all) {
852 root = BTRFS_I(bvec->bv_page->mapping->host)->root;
853 ret = csum_dirty_buffer(root->fs_info, bvec->bv_page);
858 return errno_to_blk_status(ret);
861 static blk_status_t btree_submit_bio_start(void *private_data, struct bio *bio,
865 * when we're called for a write, we're already in the async
866 * submission context. Just jump into btrfs_map_bio
868 return btree_csum_one_bio(bio);
871 static int check_async_write(struct btrfs_fs_info *fs_info,
872 struct btrfs_inode *bi)
874 if (atomic_read(&bi->sync_writers))
876 if (test_bit(BTRFS_FS_CSUM_IMPL_FAST, &fs_info->flags))
881 static blk_status_t btree_submit_bio_hook(struct inode *inode, struct bio *bio,
883 unsigned long bio_flags)
885 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
886 int async = check_async_write(fs_info, BTRFS_I(inode));
889 if (bio_op(bio) != REQ_OP_WRITE) {
891 * called for a read, do the setup so that checksum validation
892 * can happen in the async kernel threads
894 ret = btrfs_bio_wq_end_io(fs_info, bio,
895 BTRFS_WQ_ENDIO_METADATA);
898 ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
900 ret = btree_csum_one_bio(bio);
903 ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
906 * kthread helpers are used to submit writes so that
907 * checksumming can happen in parallel across all CPUs
909 ret = btrfs_wq_submit_bio(fs_info, bio, mirror_num, 0,
910 0, inode, btree_submit_bio_start);
918 bio->bi_status = ret;
923 #ifdef CONFIG_MIGRATION
924 static int btree_migratepage(struct address_space *mapping,
925 struct page *newpage, struct page *page,
926 enum migrate_mode mode)
929 * we can't safely write a btree page from here,
930 * we haven't done the locking hook
935 * Buffers may be managed in a filesystem specific way.
936 * We must have no buffers or drop them.
938 if (page_has_private(page) &&
939 !try_to_release_page(page, GFP_KERNEL))
941 return migrate_page(mapping, newpage, page, mode);
946 static int btree_writepages(struct address_space *mapping,
947 struct writeback_control *wbc)
949 struct btrfs_fs_info *fs_info;
952 if (wbc->sync_mode == WB_SYNC_NONE) {
954 if (wbc->for_kupdate)
957 fs_info = BTRFS_I(mapping->host)->root->fs_info;
958 /* this is a bit racy, but that's ok */
959 ret = __percpu_counter_compare(&fs_info->dirty_metadata_bytes,
960 BTRFS_DIRTY_METADATA_THRESH,
961 fs_info->dirty_metadata_batch);
965 return btree_write_cache_pages(mapping, wbc);
968 static int btree_readpage(struct file *file, struct page *page)
970 struct extent_io_tree *tree;
971 tree = &BTRFS_I(page->mapping->host)->io_tree;
972 return extent_read_full_page(tree, page, btree_get_extent, 0);
975 static int btree_releasepage(struct page *page, gfp_t gfp_flags)
977 if (PageWriteback(page) || PageDirty(page))
980 return try_release_extent_buffer(page);
983 static void btree_invalidatepage(struct page *page, unsigned int offset,
986 struct extent_io_tree *tree;
987 tree = &BTRFS_I(page->mapping->host)->io_tree;
988 extent_invalidatepage(tree, page, offset);
989 btree_releasepage(page, GFP_NOFS);
990 if (PagePrivate(page)) {
991 btrfs_warn(BTRFS_I(page->mapping->host)->root->fs_info,
992 "page private not zero on page %llu",
993 (unsigned long long)page_offset(page));
994 ClearPagePrivate(page);
995 set_page_private(page, 0);
1000 static int btree_set_page_dirty(struct page *page)
1003 struct extent_buffer *eb;
1005 BUG_ON(!PagePrivate(page));
1006 eb = (struct extent_buffer *)page->private;
1008 BUG_ON(!test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
1009 BUG_ON(!atomic_read(&eb->refs));
1010 btrfs_assert_tree_locked(eb);
1012 return __set_page_dirty_nobuffers(page);
1015 static const struct address_space_operations btree_aops = {
1016 .readpage = btree_readpage,
1017 .writepages = btree_writepages,
1018 .releasepage = btree_releasepage,
1019 .invalidatepage = btree_invalidatepage,
1020 #ifdef CONFIG_MIGRATION
1021 .migratepage = btree_migratepage,
1023 .set_page_dirty = btree_set_page_dirty,
1026 void readahead_tree_block(struct btrfs_fs_info *fs_info, u64 bytenr)
1028 struct extent_buffer *buf = NULL;
1031 buf = btrfs_find_create_tree_block(fs_info, bytenr);
1035 ret = read_extent_buffer_pages(buf, WAIT_NONE, 0);
1037 free_extent_buffer_stale(buf);
1039 free_extent_buffer(buf);
1042 int reada_tree_block_flagged(struct btrfs_fs_info *fs_info, u64 bytenr,
1043 int mirror_num, struct extent_buffer **eb)
1045 struct extent_buffer *buf = NULL;
1048 buf = btrfs_find_create_tree_block(fs_info, bytenr);
1052 set_bit(EXTENT_BUFFER_READAHEAD, &buf->bflags);
1054 ret = read_extent_buffer_pages(buf, WAIT_PAGE_LOCK, mirror_num);
1056 free_extent_buffer_stale(buf);
1060 if (test_bit(EXTENT_BUFFER_CORRUPT, &buf->bflags)) {
1061 free_extent_buffer_stale(buf);
1063 } else if (extent_buffer_uptodate(buf)) {
1066 free_extent_buffer(buf);
1071 struct extent_buffer *btrfs_find_create_tree_block(
1072 struct btrfs_fs_info *fs_info,
1075 if (btrfs_is_testing(fs_info))
1076 return alloc_test_extent_buffer(fs_info, bytenr);
1077 return alloc_extent_buffer(fs_info, bytenr);
1081 * Read tree block at logical address @bytenr and do variant basic but critical
1084 * @parent_transid: expected transid of this tree block, skip check if 0
1085 * @level: expected level, mandatory check
1086 * @first_key: expected key in slot 0, skip check if NULL
1088 struct extent_buffer *read_tree_block(struct btrfs_fs_info *fs_info, u64 bytenr,
1089 u64 parent_transid, int level,
1090 struct btrfs_key *first_key)
1092 struct extent_buffer *buf = NULL;
1095 buf = btrfs_find_create_tree_block(fs_info, bytenr);
1099 ret = btree_read_extent_buffer_pages(buf, parent_transid,
1102 free_extent_buffer_stale(buf);
1103 return ERR_PTR(ret);
1109 void btrfs_clean_tree_block(struct extent_buffer *buf)
1111 struct btrfs_fs_info *fs_info = buf->fs_info;
1112 if (btrfs_header_generation(buf) ==
1113 fs_info->running_transaction->transid) {
1114 btrfs_assert_tree_locked(buf);
1116 if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &buf->bflags)) {
1117 percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
1119 fs_info->dirty_metadata_batch);
1120 /* ugh, clear_extent_buffer_dirty needs to lock the page */
1121 btrfs_set_lock_blocking_write(buf);
1122 clear_extent_buffer_dirty(buf);
1127 static struct btrfs_subvolume_writers *btrfs_alloc_subvolume_writers(void)
1129 struct btrfs_subvolume_writers *writers;
1132 writers = kmalloc(sizeof(*writers), GFP_NOFS);
1134 return ERR_PTR(-ENOMEM);
1136 ret = percpu_counter_init(&writers->counter, 0, GFP_NOFS);
1139 return ERR_PTR(ret);
1142 init_waitqueue_head(&writers->wait);
1147 btrfs_free_subvolume_writers(struct btrfs_subvolume_writers *writers)
1149 percpu_counter_destroy(&writers->counter);
1153 static void __setup_root(struct btrfs_root *root, struct btrfs_fs_info *fs_info,
1156 bool dummy = test_bit(BTRFS_FS_STATE_DUMMY_FS_INFO, &fs_info->fs_state);
1158 root->commit_root = NULL;
1160 root->orphan_cleanup_state = 0;
1162 root->last_trans = 0;
1163 root->highest_objectid = 0;
1164 root->nr_delalloc_inodes = 0;
1165 root->nr_ordered_extents = 0;
1166 root->inode_tree = RB_ROOT;
1167 INIT_RADIX_TREE(&root->delayed_nodes_tree, GFP_ATOMIC);
1168 root->block_rsv = NULL;
1170 INIT_LIST_HEAD(&root->dirty_list);
1171 INIT_LIST_HEAD(&root->root_list);
1172 INIT_LIST_HEAD(&root->delalloc_inodes);
1173 INIT_LIST_HEAD(&root->delalloc_root);
1174 INIT_LIST_HEAD(&root->ordered_extents);
1175 INIT_LIST_HEAD(&root->ordered_root);
1176 INIT_LIST_HEAD(&root->reloc_dirty_list);
1177 INIT_LIST_HEAD(&root->logged_list[0]);
1178 INIT_LIST_HEAD(&root->logged_list[1]);
1179 spin_lock_init(&root->inode_lock);
1180 spin_lock_init(&root->delalloc_lock);
1181 spin_lock_init(&root->ordered_extent_lock);
1182 spin_lock_init(&root->accounting_lock);
1183 spin_lock_init(&root->log_extents_lock[0]);
1184 spin_lock_init(&root->log_extents_lock[1]);
1185 spin_lock_init(&root->qgroup_meta_rsv_lock);
1186 mutex_init(&root->objectid_mutex);
1187 mutex_init(&root->log_mutex);
1188 mutex_init(&root->ordered_extent_mutex);
1189 mutex_init(&root->delalloc_mutex);
1190 init_waitqueue_head(&root->log_writer_wait);
1191 init_waitqueue_head(&root->log_commit_wait[0]);
1192 init_waitqueue_head(&root->log_commit_wait[1]);
1193 INIT_LIST_HEAD(&root->log_ctxs[0]);
1194 INIT_LIST_HEAD(&root->log_ctxs[1]);
1195 atomic_set(&root->log_commit[0], 0);
1196 atomic_set(&root->log_commit[1], 0);
1197 atomic_set(&root->log_writers, 0);
1198 atomic_set(&root->log_batch, 0);
1199 refcount_set(&root->refs, 1);
1200 atomic_set(&root->will_be_snapshotted, 0);
1201 atomic_set(&root->snapshot_force_cow, 0);
1202 atomic_set(&root->nr_swapfiles, 0);
1203 root->log_transid = 0;
1204 root->log_transid_committed = -1;
1205 root->last_log_commit = 0;
1207 extent_io_tree_init(fs_info, &root->dirty_log_pages,
1208 IO_TREE_ROOT_DIRTY_LOG_PAGES, NULL);
1210 memset(&root->root_key, 0, sizeof(root->root_key));
1211 memset(&root->root_item, 0, sizeof(root->root_item));
1212 memset(&root->defrag_progress, 0, sizeof(root->defrag_progress));
1214 root->defrag_trans_start = fs_info->generation;
1216 root->defrag_trans_start = 0;
1217 root->root_key.objectid = objectid;
1220 spin_lock_init(&root->root_item_lock);
1221 btrfs_qgroup_init_swapped_blocks(&root->swapped_blocks);
1224 static struct btrfs_root *btrfs_alloc_root(struct btrfs_fs_info *fs_info,
1227 struct btrfs_root *root = kzalloc(sizeof(*root), flags);
1229 root->fs_info = fs_info;
1233 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
1234 /* Should only be used by the testing infrastructure */
1235 struct btrfs_root *btrfs_alloc_dummy_root(struct btrfs_fs_info *fs_info)
1237 struct btrfs_root *root;
1240 return ERR_PTR(-EINVAL);
1242 root = btrfs_alloc_root(fs_info, GFP_KERNEL);
1244 return ERR_PTR(-ENOMEM);
1246 /* We don't use the stripesize in selftest, set it as sectorsize */
1247 __setup_root(root, fs_info, BTRFS_ROOT_TREE_OBJECTID);
1248 root->alloc_bytenr = 0;
1254 struct btrfs_root *btrfs_create_tree(struct btrfs_trans_handle *trans,
1257 struct btrfs_fs_info *fs_info = trans->fs_info;
1258 struct extent_buffer *leaf;
1259 struct btrfs_root *tree_root = fs_info->tree_root;
1260 struct btrfs_root *root;
1261 struct btrfs_key key;
1262 unsigned int nofs_flag;
1264 uuid_le uuid = NULL_UUID_LE;
1267 * We're holding a transaction handle, so use a NOFS memory allocation
1268 * context to avoid deadlock if reclaim happens.
1270 nofs_flag = memalloc_nofs_save();
1271 root = btrfs_alloc_root(fs_info, GFP_KERNEL);
1272 memalloc_nofs_restore(nofs_flag);
1274 return ERR_PTR(-ENOMEM);
1276 __setup_root(root, fs_info, objectid);
1277 root->root_key.objectid = objectid;
1278 root->root_key.type = BTRFS_ROOT_ITEM_KEY;
1279 root->root_key.offset = 0;
1281 leaf = btrfs_alloc_tree_block(trans, root, 0, objectid, NULL, 0, 0, 0);
1283 ret = PTR_ERR(leaf);
1289 btrfs_mark_buffer_dirty(leaf);
1291 root->commit_root = btrfs_root_node(root);
1292 set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
1294 root->root_item.flags = 0;
1295 root->root_item.byte_limit = 0;
1296 btrfs_set_root_bytenr(&root->root_item, leaf->start);
1297 btrfs_set_root_generation(&root->root_item, trans->transid);
1298 btrfs_set_root_level(&root->root_item, 0);
1299 btrfs_set_root_refs(&root->root_item, 1);
1300 btrfs_set_root_used(&root->root_item, leaf->len);
1301 btrfs_set_root_last_snapshot(&root->root_item, 0);
1302 btrfs_set_root_dirid(&root->root_item, 0);
1303 if (is_fstree(objectid))
1305 memcpy(root->root_item.uuid, uuid.b, BTRFS_UUID_SIZE);
1306 root->root_item.drop_level = 0;
1308 key.objectid = objectid;
1309 key.type = BTRFS_ROOT_ITEM_KEY;
1311 ret = btrfs_insert_root(trans, tree_root, &key, &root->root_item);
1315 btrfs_tree_unlock(leaf);
1321 btrfs_tree_unlock(leaf);
1322 free_extent_buffer(root->commit_root);
1323 free_extent_buffer(leaf);
1327 return ERR_PTR(ret);
1330 static struct btrfs_root *alloc_log_tree(struct btrfs_trans_handle *trans,
1331 struct btrfs_fs_info *fs_info)
1333 struct btrfs_root *root;
1334 struct extent_buffer *leaf;
1336 root = btrfs_alloc_root(fs_info, GFP_NOFS);
1338 return ERR_PTR(-ENOMEM);
1340 __setup_root(root, fs_info, BTRFS_TREE_LOG_OBJECTID);
1342 root->root_key.objectid = BTRFS_TREE_LOG_OBJECTID;
1343 root->root_key.type = BTRFS_ROOT_ITEM_KEY;
1344 root->root_key.offset = BTRFS_TREE_LOG_OBJECTID;
1347 * DON'T set REF_COWS for log trees
1349 * log trees do not get reference counted because they go away
1350 * before a real commit is actually done. They do store pointers
1351 * to file data extents, and those reference counts still get
1352 * updated (along with back refs to the log tree).
1355 leaf = btrfs_alloc_tree_block(trans, root, 0, BTRFS_TREE_LOG_OBJECTID,
1359 return ERR_CAST(leaf);
1364 btrfs_mark_buffer_dirty(root->node);
1365 btrfs_tree_unlock(root->node);
1369 int btrfs_init_log_root_tree(struct btrfs_trans_handle *trans,
1370 struct btrfs_fs_info *fs_info)
1372 struct btrfs_root *log_root;
1374 log_root = alloc_log_tree(trans, fs_info);
1375 if (IS_ERR(log_root))
1376 return PTR_ERR(log_root);
1377 WARN_ON(fs_info->log_root_tree);
1378 fs_info->log_root_tree = log_root;
1382 int btrfs_add_log_tree(struct btrfs_trans_handle *trans,
1383 struct btrfs_root *root)
1385 struct btrfs_fs_info *fs_info = root->fs_info;
1386 struct btrfs_root *log_root;
1387 struct btrfs_inode_item *inode_item;
1389 log_root = alloc_log_tree(trans, fs_info);
1390 if (IS_ERR(log_root))
1391 return PTR_ERR(log_root);
1393 log_root->last_trans = trans->transid;
1394 log_root->root_key.offset = root->root_key.objectid;
1396 inode_item = &log_root->root_item.inode;
1397 btrfs_set_stack_inode_generation(inode_item, 1);
1398 btrfs_set_stack_inode_size(inode_item, 3);
1399 btrfs_set_stack_inode_nlink(inode_item, 1);
1400 btrfs_set_stack_inode_nbytes(inode_item,
1402 btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
1404 btrfs_set_root_node(&log_root->root_item, log_root->node);
1406 WARN_ON(root->log_root);
1407 root->log_root = log_root;
1408 root->log_transid = 0;
1409 root->log_transid_committed = -1;
1410 root->last_log_commit = 0;
1414 static struct btrfs_root *btrfs_read_tree_root(struct btrfs_root *tree_root,
1415 struct btrfs_key *key)
1417 struct btrfs_root *root;
1418 struct btrfs_fs_info *fs_info = tree_root->fs_info;
1419 struct btrfs_path *path;
1424 path = btrfs_alloc_path();
1426 return ERR_PTR(-ENOMEM);
1428 root = btrfs_alloc_root(fs_info, GFP_NOFS);
1434 __setup_root(root, fs_info, key->objectid);
1436 ret = btrfs_find_root(tree_root, key, path,
1437 &root->root_item, &root->root_key);
1444 generation = btrfs_root_generation(&root->root_item);
1445 level = btrfs_root_level(&root->root_item);
1446 root->node = read_tree_block(fs_info,
1447 btrfs_root_bytenr(&root->root_item),
1448 generation, level, NULL);
1449 if (IS_ERR(root->node)) {
1450 ret = PTR_ERR(root->node);
1452 } else if (!btrfs_buffer_uptodate(root->node, generation, 0)) {
1454 free_extent_buffer(root->node);
1457 root->commit_root = btrfs_root_node(root);
1459 btrfs_free_path(path);
1465 root = ERR_PTR(ret);
1469 struct btrfs_root *btrfs_read_fs_root(struct btrfs_root *tree_root,
1470 struct btrfs_key *location)
1472 struct btrfs_root *root;
1474 root = btrfs_read_tree_root(tree_root, location);
1478 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
1479 set_bit(BTRFS_ROOT_REF_COWS, &root->state);
1480 btrfs_check_and_init_root_item(&root->root_item);
1486 int btrfs_init_fs_root(struct btrfs_root *root)
1489 struct btrfs_subvolume_writers *writers;
1491 root->free_ino_ctl = kzalloc(sizeof(*root->free_ino_ctl), GFP_NOFS);
1492 root->free_ino_pinned = kzalloc(sizeof(*root->free_ino_pinned),
1494 if (!root->free_ino_pinned || !root->free_ino_ctl) {
1499 writers = btrfs_alloc_subvolume_writers();
1500 if (IS_ERR(writers)) {
1501 ret = PTR_ERR(writers);
1504 root->subv_writers = writers;
1506 btrfs_init_free_ino_ctl(root);
1507 spin_lock_init(&root->ino_cache_lock);
1508 init_waitqueue_head(&root->ino_cache_wait);
1510 ret = get_anon_bdev(&root->anon_dev);
1514 mutex_lock(&root->objectid_mutex);
1515 ret = btrfs_find_highest_objectid(root,
1516 &root->highest_objectid);
1518 mutex_unlock(&root->objectid_mutex);
1522 ASSERT(root->highest_objectid <= BTRFS_LAST_FREE_OBJECTID);
1524 mutex_unlock(&root->objectid_mutex);
1528 /* The caller is responsible to call btrfs_free_fs_root */
1532 struct btrfs_root *btrfs_lookup_fs_root(struct btrfs_fs_info *fs_info,
1535 struct btrfs_root *root;
1537 spin_lock(&fs_info->fs_roots_radix_lock);
1538 root = radix_tree_lookup(&fs_info->fs_roots_radix,
1539 (unsigned long)root_id);
1540 spin_unlock(&fs_info->fs_roots_radix_lock);
1544 int btrfs_insert_fs_root(struct btrfs_fs_info *fs_info,
1545 struct btrfs_root *root)
1549 ret = radix_tree_preload(GFP_NOFS);
1553 spin_lock(&fs_info->fs_roots_radix_lock);
1554 ret = radix_tree_insert(&fs_info->fs_roots_radix,
1555 (unsigned long)root->root_key.objectid,
1558 set_bit(BTRFS_ROOT_IN_RADIX, &root->state);
1559 spin_unlock(&fs_info->fs_roots_radix_lock);
1560 radix_tree_preload_end();
1565 struct btrfs_root *btrfs_get_fs_root(struct btrfs_fs_info *fs_info,
1566 struct btrfs_key *location,
1569 struct btrfs_root *root;
1570 struct btrfs_path *path;
1571 struct btrfs_key key;
1574 if (location->objectid == BTRFS_ROOT_TREE_OBJECTID)
1575 return fs_info->tree_root;
1576 if (location->objectid == BTRFS_EXTENT_TREE_OBJECTID)
1577 return fs_info->extent_root;
1578 if (location->objectid == BTRFS_CHUNK_TREE_OBJECTID)
1579 return fs_info->chunk_root;
1580 if (location->objectid == BTRFS_DEV_TREE_OBJECTID)
1581 return fs_info->dev_root;
1582 if (location->objectid == BTRFS_CSUM_TREE_OBJECTID)
1583 return fs_info->csum_root;
1584 if (location->objectid == BTRFS_QUOTA_TREE_OBJECTID)
1585 return fs_info->quota_root ? fs_info->quota_root :
1587 if (location->objectid == BTRFS_UUID_TREE_OBJECTID)
1588 return fs_info->uuid_root ? fs_info->uuid_root :
1590 if (location->objectid == BTRFS_FREE_SPACE_TREE_OBJECTID)
1591 return fs_info->free_space_root ? fs_info->free_space_root :
1594 root = btrfs_lookup_fs_root(fs_info, location->objectid);
1596 if (check_ref && btrfs_root_refs(&root->root_item) == 0)
1597 return ERR_PTR(-ENOENT);
1601 root = btrfs_read_fs_root(fs_info->tree_root, location);
1605 if (check_ref && btrfs_root_refs(&root->root_item) == 0) {
1610 ret = btrfs_init_fs_root(root);
1614 path = btrfs_alloc_path();
1619 key.objectid = BTRFS_ORPHAN_OBJECTID;
1620 key.type = BTRFS_ORPHAN_ITEM_KEY;
1621 key.offset = location->objectid;
1623 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
1624 btrfs_free_path(path);
1628 set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state);
1630 ret = btrfs_insert_fs_root(fs_info, root);
1632 if (ret == -EEXIST) {
1633 btrfs_free_fs_root(root);
1640 btrfs_free_fs_root(root);
1641 return ERR_PTR(ret);
1644 static int btrfs_congested_fn(void *congested_data, int bdi_bits)
1646 struct btrfs_fs_info *info = (struct btrfs_fs_info *)congested_data;
1648 struct btrfs_device *device;
1649 struct backing_dev_info *bdi;
1652 list_for_each_entry_rcu(device, &info->fs_devices->devices, dev_list) {
1655 bdi = device->bdev->bd_bdi;
1656 if (bdi_congested(bdi, bdi_bits)) {
1666 * called by the kthread helper functions to finally call the bio end_io
1667 * functions. This is where read checksum verification actually happens
1669 static void end_workqueue_fn(struct btrfs_work *work)
1672 struct btrfs_end_io_wq *end_io_wq;
1674 end_io_wq = container_of(work, struct btrfs_end_io_wq, work);
1675 bio = end_io_wq->bio;
1677 bio->bi_status = end_io_wq->status;
1678 bio->bi_private = end_io_wq->private;
1679 bio->bi_end_io = end_io_wq->end_io;
1680 kmem_cache_free(btrfs_end_io_wq_cache, end_io_wq);
1684 static int cleaner_kthread(void *arg)
1686 struct btrfs_root *root = arg;
1687 struct btrfs_fs_info *fs_info = root->fs_info;
1693 set_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags);
1695 /* Make the cleaner go to sleep early. */
1696 if (btrfs_need_cleaner_sleep(fs_info))
1700 * Do not do anything if we might cause open_ctree() to block
1701 * before we have finished mounting the filesystem.
1703 if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
1706 if (!mutex_trylock(&fs_info->cleaner_mutex))
1710 * Avoid the problem that we change the status of the fs
1711 * during the above check and trylock.
1713 if (btrfs_need_cleaner_sleep(fs_info)) {
1714 mutex_unlock(&fs_info->cleaner_mutex);
1718 btrfs_run_delayed_iputs(fs_info);
1720 again = btrfs_clean_one_deleted_snapshot(root);
1721 mutex_unlock(&fs_info->cleaner_mutex);
1724 * The defragger has dealt with the R/O remount and umount,
1725 * needn't do anything special here.
1727 btrfs_run_defrag_inodes(fs_info);
1730 * Acquires fs_info->delete_unused_bgs_mutex to avoid racing
1731 * with relocation (btrfs_relocate_chunk) and relocation
1732 * acquires fs_info->cleaner_mutex (btrfs_relocate_block_group)
1733 * after acquiring fs_info->delete_unused_bgs_mutex. So we
1734 * can't hold, nor need to, fs_info->cleaner_mutex when deleting
1735 * unused block groups.
1737 btrfs_delete_unused_bgs(fs_info);
1739 clear_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags);
1740 if (kthread_should_park())
1742 if (kthread_should_stop())
1745 set_current_state(TASK_INTERRUPTIBLE);
1747 __set_current_state(TASK_RUNNING);
1752 static int transaction_kthread(void *arg)
1754 struct btrfs_root *root = arg;
1755 struct btrfs_fs_info *fs_info = root->fs_info;
1756 struct btrfs_trans_handle *trans;
1757 struct btrfs_transaction *cur;
1760 unsigned long delay;
1764 cannot_commit = false;
1765 delay = HZ * fs_info->commit_interval;
1766 mutex_lock(&fs_info->transaction_kthread_mutex);
1768 spin_lock(&fs_info->trans_lock);
1769 cur = fs_info->running_transaction;
1771 spin_unlock(&fs_info->trans_lock);
1775 now = ktime_get_seconds();
1776 if (cur->state < TRANS_STATE_BLOCKED &&
1777 !test_bit(BTRFS_FS_NEED_ASYNC_COMMIT, &fs_info->flags) &&
1778 (now < cur->start_time ||
1779 now - cur->start_time < fs_info->commit_interval)) {
1780 spin_unlock(&fs_info->trans_lock);
1784 transid = cur->transid;
1785 spin_unlock(&fs_info->trans_lock);
1787 /* If the file system is aborted, this will always fail. */
1788 trans = btrfs_attach_transaction(root);
1789 if (IS_ERR(trans)) {
1790 if (PTR_ERR(trans) != -ENOENT)
1791 cannot_commit = true;
1794 if (transid == trans->transid) {
1795 btrfs_commit_transaction(trans);
1797 btrfs_end_transaction(trans);
1800 wake_up_process(fs_info->cleaner_kthread);
1801 mutex_unlock(&fs_info->transaction_kthread_mutex);
1803 if (unlikely(test_bit(BTRFS_FS_STATE_ERROR,
1804 &fs_info->fs_state)))
1805 btrfs_cleanup_transaction(fs_info);
1806 if (!kthread_should_stop() &&
1807 (!btrfs_transaction_blocked(fs_info) ||
1809 schedule_timeout_interruptible(delay);
1810 } while (!kthread_should_stop());
1815 * this will find the highest generation in the array of
1816 * root backups. The index of the highest array is returned,
1817 * or -1 if we can't find anything.
1819 * We check to make sure the array is valid by comparing the
1820 * generation of the latest root in the array with the generation
1821 * in the super block. If they don't match we pitch it.
1823 static int find_newest_super_backup(struct btrfs_fs_info *info, u64 newest_gen)
1826 int newest_index = -1;
1827 struct btrfs_root_backup *root_backup;
1830 for (i = 0; i < BTRFS_NUM_BACKUP_ROOTS; i++) {
1831 root_backup = info->super_copy->super_roots + i;
1832 cur = btrfs_backup_tree_root_gen(root_backup);
1833 if (cur == newest_gen)
1837 /* check to see if we actually wrapped around */
1838 if (newest_index == BTRFS_NUM_BACKUP_ROOTS - 1) {
1839 root_backup = info->super_copy->super_roots;
1840 cur = btrfs_backup_tree_root_gen(root_backup);
1841 if (cur == newest_gen)
1844 return newest_index;
1849 * find the oldest backup so we know where to store new entries
1850 * in the backup array. This will set the backup_root_index
1851 * field in the fs_info struct
1853 static void find_oldest_super_backup(struct btrfs_fs_info *info,
1856 int newest_index = -1;
1858 newest_index = find_newest_super_backup(info, newest_gen);
1859 /* if there was garbage in there, just move along */
1860 if (newest_index == -1) {
1861 info->backup_root_index = 0;
1863 info->backup_root_index = (newest_index + 1) % BTRFS_NUM_BACKUP_ROOTS;
1868 * copy all the root pointers into the super backup array.
1869 * this will bump the backup pointer by one when it is
1872 static void backup_super_roots(struct btrfs_fs_info *info)
1875 struct btrfs_root_backup *root_backup;
1878 next_backup = info->backup_root_index;
1879 last_backup = (next_backup + BTRFS_NUM_BACKUP_ROOTS - 1) %
1880 BTRFS_NUM_BACKUP_ROOTS;
1883 * just overwrite the last backup if we're at the same generation
1884 * this happens only at umount
1886 root_backup = info->super_for_commit->super_roots + last_backup;
1887 if (btrfs_backup_tree_root_gen(root_backup) ==
1888 btrfs_header_generation(info->tree_root->node))
1889 next_backup = last_backup;
1891 root_backup = info->super_for_commit->super_roots + next_backup;
1894 * make sure all of our padding and empty slots get zero filled
1895 * regardless of which ones we use today
1897 memset(root_backup, 0, sizeof(*root_backup));
1899 info->backup_root_index = (next_backup + 1) % BTRFS_NUM_BACKUP_ROOTS;
1901 btrfs_set_backup_tree_root(root_backup, info->tree_root->node->start);
1902 btrfs_set_backup_tree_root_gen(root_backup,
1903 btrfs_header_generation(info->tree_root->node));
1905 btrfs_set_backup_tree_root_level(root_backup,
1906 btrfs_header_level(info->tree_root->node));
1908 btrfs_set_backup_chunk_root(root_backup, info->chunk_root->node->start);
1909 btrfs_set_backup_chunk_root_gen(root_backup,
1910 btrfs_header_generation(info->chunk_root->node));
1911 btrfs_set_backup_chunk_root_level(root_backup,
1912 btrfs_header_level(info->chunk_root->node));
1914 btrfs_set_backup_extent_root(root_backup, info->extent_root->node->start);
1915 btrfs_set_backup_extent_root_gen(root_backup,
1916 btrfs_header_generation(info->extent_root->node));
1917 btrfs_set_backup_extent_root_level(root_backup,
1918 btrfs_header_level(info->extent_root->node));
1921 * we might commit during log recovery, which happens before we set
1922 * the fs_root. Make sure it is valid before we fill it in.
1924 if (info->fs_root && info->fs_root->node) {
1925 btrfs_set_backup_fs_root(root_backup,
1926 info->fs_root->node->start);
1927 btrfs_set_backup_fs_root_gen(root_backup,
1928 btrfs_header_generation(info->fs_root->node));
1929 btrfs_set_backup_fs_root_level(root_backup,
1930 btrfs_header_level(info->fs_root->node));
1933 btrfs_set_backup_dev_root(root_backup, info->dev_root->node->start);
1934 btrfs_set_backup_dev_root_gen(root_backup,
1935 btrfs_header_generation(info->dev_root->node));
1936 btrfs_set_backup_dev_root_level(root_backup,
1937 btrfs_header_level(info->dev_root->node));
1939 btrfs_set_backup_csum_root(root_backup, info->csum_root->node->start);
1940 btrfs_set_backup_csum_root_gen(root_backup,
1941 btrfs_header_generation(info->csum_root->node));
1942 btrfs_set_backup_csum_root_level(root_backup,
1943 btrfs_header_level(info->csum_root->node));
1945 btrfs_set_backup_total_bytes(root_backup,
1946 btrfs_super_total_bytes(info->super_copy));
1947 btrfs_set_backup_bytes_used(root_backup,
1948 btrfs_super_bytes_used(info->super_copy));
1949 btrfs_set_backup_num_devices(root_backup,
1950 btrfs_super_num_devices(info->super_copy));
1953 * if we don't copy this out to the super_copy, it won't get remembered
1954 * for the next commit
1956 memcpy(&info->super_copy->super_roots,
1957 &info->super_for_commit->super_roots,
1958 sizeof(*root_backup) * BTRFS_NUM_BACKUP_ROOTS);
1962 * this copies info out of the root backup array and back into
1963 * the in-memory super block. It is meant to help iterate through
1964 * the array, so you send it the number of backups you've already
1965 * tried and the last backup index you used.
1967 * this returns -1 when it has tried all the backups
1969 static noinline int next_root_backup(struct btrfs_fs_info *info,
1970 struct btrfs_super_block *super,
1971 int *num_backups_tried, int *backup_index)
1973 struct btrfs_root_backup *root_backup;
1974 int newest = *backup_index;
1976 if (*num_backups_tried == 0) {
1977 u64 gen = btrfs_super_generation(super);
1979 newest = find_newest_super_backup(info, gen);
1983 *backup_index = newest;
1984 *num_backups_tried = 1;
1985 } else if (*num_backups_tried == BTRFS_NUM_BACKUP_ROOTS) {
1986 /* we've tried all the backups, all done */
1989 /* jump to the next oldest backup */
1990 newest = (*backup_index + BTRFS_NUM_BACKUP_ROOTS - 1) %
1991 BTRFS_NUM_BACKUP_ROOTS;
1992 *backup_index = newest;
1993 *num_backups_tried += 1;
1995 root_backup = super->super_roots + newest;
1997 btrfs_set_super_generation(super,
1998 btrfs_backup_tree_root_gen(root_backup));
1999 btrfs_set_super_root(super, btrfs_backup_tree_root(root_backup));
2000 btrfs_set_super_root_level(super,
2001 btrfs_backup_tree_root_level(root_backup));
2002 btrfs_set_super_bytes_used(super, btrfs_backup_bytes_used(root_backup));
2005 * fixme: the total bytes and num_devices need to match or we should
2008 btrfs_set_super_total_bytes(super, btrfs_backup_total_bytes(root_backup));
2009 btrfs_set_super_num_devices(super, btrfs_backup_num_devices(root_backup));
2013 /* helper to cleanup workers */
2014 static void btrfs_stop_all_workers(struct btrfs_fs_info *fs_info)
2016 btrfs_destroy_workqueue(fs_info->fixup_workers);
2017 btrfs_destroy_workqueue(fs_info->delalloc_workers);
2018 btrfs_destroy_workqueue(fs_info->workers);
2019 btrfs_destroy_workqueue(fs_info->endio_workers);
2020 btrfs_destroy_workqueue(fs_info->endio_raid56_workers);
2021 btrfs_destroy_workqueue(fs_info->endio_repair_workers);
2022 btrfs_destroy_workqueue(fs_info->rmw_workers);
2023 btrfs_destroy_workqueue(fs_info->endio_write_workers);
2024 btrfs_destroy_workqueue(fs_info->endio_freespace_worker);
2025 btrfs_destroy_workqueue(fs_info->submit_workers);
2026 btrfs_destroy_workqueue(fs_info->delayed_workers);
2027 btrfs_destroy_workqueue(fs_info->caching_workers);
2028 btrfs_destroy_workqueue(fs_info->readahead_workers);
2029 btrfs_destroy_workqueue(fs_info->flush_workers);
2030 btrfs_destroy_workqueue(fs_info->qgroup_rescan_workers);
2031 btrfs_destroy_workqueue(fs_info->extent_workers);
2033 * Now that all other work queues are destroyed, we can safely destroy
2034 * the queues used for metadata I/O, since tasks from those other work
2035 * queues can do metadata I/O operations.
2037 btrfs_destroy_workqueue(fs_info->endio_meta_workers);
2038 btrfs_destroy_workqueue(fs_info->endio_meta_write_workers);
2041 static void free_root_extent_buffers(struct btrfs_root *root)
2044 free_extent_buffer(root->node);
2045 free_extent_buffer(root->commit_root);
2047 root->commit_root = NULL;
2051 /* helper to cleanup tree roots */
2052 static void free_root_pointers(struct btrfs_fs_info *info, int chunk_root)
2054 free_root_extent_buffers(info->tree_root);
2056 free_root_extent_buffers(info->dev_root);
2057 free_root_extent_buffers(info->extent_root);
2058 free_root_extent_buffers(info->csum_root);
2059 free_root_extent_buffers(info->quota_root);
2060 free_root_extent_buffers(info->uuid_root);
2062 free_root_extent_buffers(info->chunk_root);
2063 free_root_extent_buffers(info->free_space_root);
2066 void btrfs_free_fs_roots(struct btrfs_fs_info *fs_info)
2069 struct btrfs_root *gang[8];
2072 while (!list_empty(&fs_info->dead_roots)) {
2073 gang[0] = list_entry(fs_info->dead_roots.next,
2074 struct btrfs_root, root_list);
2075 list_del(&gang[0]->root_list);
2077 if (test_bit(BTRFS_ROOT_IN_RADIX, &gang[0]->state)) {
2078 btrfs_drop_and_free_fs_root(fs_info, gang[0]);
2080 free_extent_buffer(gang[0]->node);
2081 free_extent_buffer(gang[0]->commit_root);
2082 btrfs_put_fs_root(gang[0]);
2087 ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
2092 for (i = 0; i < ret; i++)
2093 btrfs_drop_and_free_fs_root(fs_info, gang[i]);
2096 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {
2097 btrfs_free_log_root_tree(NULL, fs_info);
2098 btrfs_destroy_pinned_extent(fs_info, fs_info->pinned_extents);
2102 static void btrfs_init_scrub(struct btrfs_fs_info *fs_info)
2104 mutex_init(&fs_info->scrub_lock);
2105 atomic_set(&fs_info->scrubs_running, 0);
2106 atomic_set(&fs_info->scrub_pause_req, 0);
2107 atomic_set(&fs_info->scrubs_paused, 0);
2108 atomic_set(&fs_info->scrub_cancel_req, 0);
2109 init_waitqueue_head(&fs_info->scrub_pause_wait);
2110 refcount_set(&fs_info->scrub_workers_refcnt, 0);
2113 static void btrfs_init_balance(struct btrfs_fs_info *fs_info)
2115 spin_lock_init(&fs_info->balance_lock);
2116 mutex_init(&fs_info->balance_mutex);
2117 atomic_set(&fs_info->balance_pause_req, 0);
2118 atomic_set(&fs_info->balance_cancel_req, 0);
2119 fs_info->balance_ctl = NULL;
2120 init_waitqueue_head(&fs_info->balance_wait_q);
2123 static void btrfs_init_btree_inode(struct btrfs_fs_info *fs_info)
2125 struct inode *inode = fs_info->btree_inode;
2127 inode->i_ino = BTRFS_BTREE_INODE_OBJECTID;
2128 set_nlink(inode, 1);
2130 * we set the i_size on the btree inode to the max possible int.
2131 * the real end of the address space is determined by all of
2132 * the devices in the system
2134 inode->i_size = OFFSET_MAX;
2135 inode->i_mapping->a_ops = &btree_aops;
2137 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
2138 extent_io_tree_init(fs_info, &BTRFS_I(inode)->io_tree,
2139 IO_TREE_INODE_IO, inode);
2140 BTRFS_I(inode)->io_tree.track_uptodate = false;
2141 extent_map_tree_init(&BTRFS_I(inode)->extent_tree);
2143 BTRFS_I(inode)->io_tree.ops = &btree_extent_io_ops;
2145 BTRFS_I(inode)->root = fs_info->tree_root;
2146 memset(&BTRFS_I(inode)->location, 0, sizeof(struct btrfs_key));
2147 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
2148 btrfs_insert_inode_hash(inode);
2151 static void btrfs_init_dev_replace_locks(struct btrfs_fs_info *fs_info)
2153 mutex_init(&fs_info->dev_replace.lock_finishing_cancel_unmount);
2154 init_rwsem(&fs_info->dev_replace.rwsem);
2155 init_waitqueue_head(&fs_info->dev_replace.replace_wait);
2158 static void btrfs_init_qgroup(struct btrfs_fs_info *fs_info)
2160 spin_lock_init(&fs_info->qgroup_lock);
2161 mutex_init(&fs_info->qgroup_ioctl_lock);
2162 fs_info->qgroup_tree = RB_ROOT;
2163 INIT_LIST_HEAD(&fs_info->dirty_qgroups);
2164 fs_info->qgroup_seq = 1;
2165 fs_info->qgroup_ulist = NULL;
2166 fs_info->qgroup_rescan_running = false;
2167 mutex_init(&fs_info->qgroup_rescan_lock);
2170 static int btrfs_init_workqueues(struct btrfs_fs_info *fs_info,
2171 struct btrfs_fs_devices *fs_devices)
2173 u32 max_active = fs_info->thread_pool_size;
2174 unsigned int flags = WQ_MEM_RECLAIM | WQ_FREEZABLE | WQ_UNBOUND;
2177 btrfs_alloc_workqueue(fs_info, "worker",
2178 flags | WQ_HIGHPRI, max_active, 16);
2180 fs_info->delalloc_workers =
2181 btrfs_alloc_workqueue(fs_info, "delalloc",
2182 flags, max_active, 2);
2184 fs_info->flush_workers =
2185 btrfs_alloc_workqueue(fs_info, "flush_delalloc",
2186 flags, max_active, 0);
2188 fs_info->caching_workers =
2189 btrfs_alloc_workqueue(fs_info, "cache", flags, max_active, 0);
2192 * a higher idle thresh on the submit workers makes it much more
2193 * likely that bios will be send down in a sane order to the
2196 fs_info->submit_workers =
2197 btrfs_alloc_workqueue(fs_info, "submit", flags,
2198 min_t(u64, fs_devices->num_devices,
2201 fs_info->fixup_workers =
2202 btrfs_alloc_workqueue(fs_info, "fixup", flags, 1, 0);
2205 * endios are largely parallel and should have a very
2208 fs_info->endio_workers =
2209 btrfs_alloc_workqueue(fs_info, "endio", flags, max_active, 4);
2210 fs_info->endio_meta_workers =
2211 btrfs_alloc_workqueue(fs_info, "endio-meta", flags,
2213 fs_info->endio_meta_write_workers =
2214 btrfs_alloc_workqueue(fs_info, "endio-meta-write", flags,
2216 fs_info->endio_raid56_workers =
2217 btrfs_alloc_workqueue(fs_info, "endio-raid56", flags,
2219 fs_info->endio_repair_workers =
2220 btrfs_alloc_workqueue(fs_info, "endio-repair", flags, 1, 0);
2221 fs_info->rmw_workers =
2222 btrfs_alloc_workqueue(fs_info, "rmw", flags, max_active, 2);
2223 fs_info->endio_write_workers =
2224 btrfs_alloc_workqueue(fs_info, "endio-write", flags,
2226 fs_info->endio_freespace_worker =
2227 btrfs_alloc_workqueue(fs_info, "freespace-write", flags,
2229 fs_info->delayed_workers =
2230 btrfs_alloc_workqueue(fs_info, "delayed-meta", flags,
2232 fs_info->readahead_workers =
2233 btrfs_alloc_workqueue(fs_info, "readahead", flags,
2235 fs_info->qgroup_rescan_workers =
2236 btrfs_alloc_workqueue(fs_info, "qgroup-rescan", flags, 1, 0);
2237 fs_info->extent_workers =
2238 btrfs_alloc_workqueue(fs_info, "extent-refs", flags,
2239 min_t(u64, fs_devices->num_devices,
2242 if (!(fs_info->workers && fs_info->delalloc_workers &&
2243 fs_info->submit_workers && fs_info->flush_workers &&
2244 fs_info->endio_workers && fs_info->endio_meta_workers &&
2245 fs_info->endio_meta_write_workers &&
2246 fs_info->endio_repair_workers &&
2247 fs_info->endio_write_workers && fs_info->endio_raid56_workers &&
2248 fs_info->endio_freespace_worker && fs_info->rmw_workers &&
2249 fs_info->caching_workers && fs_info->readahead_workers &&
2250 fs_info->fixup_workers && fs_info->delayed_workers &&
2251 fs_info->extent_workers &&
2252 fs_info->qgroup_rescan_workers)) {
2259 static int btrfs_replay_log(struct btrfs_fs_info *fs_info,
2260 struct btrfs_fs_devices *fs_devices)
2263 struct btrfs_root *log_tree_root;
2264 struct btrfs_super_block *disk_super = fs_info->super_copy;
2265 u64 bytenr = btrfs_super_log_root(disk_super);
2266 int level = btrfs_super_log_root_level(disk_super);
2268 if (fs_devices->rw_devices == 0) {
2269 btrfs_warn(fs_info, "log replay required on RO media");
2273 log_tree_root = btrfs_alloc_root(fs_info, GFP_KERNEL);
2277 __setup_root(log_tree_root, fs_info, BTRFS_TREE_LOG_OBJECTID);
2279 log_tree_root->node = read_tree_block(fs_info, bytenr,
2280 fs_info->generation + 1,
2282 if (IS_ERR(log_tree_root->node)) {
2283 btrfs_warn(fs_info, "failed to read log tree");
2284 ret = PTR_ERR(log_tree_root->node);
2285 kfree(log_tree_root);
2287 } else if (!extent_buffer_uptodate(log_tree_root->node)) {
2288 btrfs_err(fs_info, "failed to read log tree");
2289 free_extent_buffer(log_tree_root->node);
2290 kfree(log_tree_root);
2293 /* returns with log_tree_root freed on success */
2294 ret = btrfs_recover_log_trees(log_tree_root);
2296 btrfs_handle_fs_error(fs_info, ret,
2297 "Failed to recover log tree");
2298 free_extent_buffer(log_tree_root->node);
2299 kfree(log_tree_root);
2303 if (sb_rdonly(fs_info->sb)) {
2304 ret = btrfs_commit_super(fs_info);
2312 static int btrfs_read_roots(struct btrfs_fs_info *fs_info)
2314 struct btrfs_root *tree_root = fs_info->tree_root;
2315 struct btrfs_root *root;
2316 struct btrfs_key location;
2319 BUG_ON(!fs_info->tree_root);
2321 location.objectid = BTRFS_EXTENT_TREE_OBJECTID;
2322 location.type = BTRFS_ROOT_ITEM_KEY;
2323 location.offset = 0;
2325 root = btrfs_read_tree_root(tree_root, &location);
2327 ret = PTR_ERR(root);
2330 set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2331 fs_info->extent_root = root;
2333 location.objectid = BTRFS_DEV_TREE_OBJECTID;
2334 root = btrfs_read_tree_root(tree_root, &location);
2336 ret = PTR_ERR(root);
2339 set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2340 fs_info->dev_root = root;
2341 btrfs_init_devices_late(fs_info);
2343 location.objectid = BTRFS_CSUM_TREE_OBJECTID;
2344 root = btrfs_read_tree_root(tree_root, &location);
2346 ret = PTR_ERR(root);
2349 set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2350 fs_info->csum_root = root;
2352 location.objectid = BTRFS_QUOTA_TREE_OBJECTID;
2353 root = btrfs_read_tree_root(tree_root, &location);
2354 if (!IS_ERR(root)) {
2355 set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2356 set_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags);
2357 fs_info->quota_root = root;
2360 location.objectid = BTRFS_UUID_TREE_OBJECTID;
2361 root = btrfs_read_tree_root(tree_root, &location);
2363 ret = PTR_ERR(root);
2367 set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2368 fs_info->uuid_root = root;
2371 if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
2372 location.objectid = BTRFS_FREE_SPACE_TREE_OBJECTID;
2373 root = btrfs_read_tree_root(tree_root, &location);
2375 ret = PTR_ERR(root);
2378 set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2379 fs_info->free_space_root = root;
2384 btrfs_warn(fs_info, "failed to read root (objectid=%llu): %d",
2385 location.objectid, ret);
2390 * Real super block validation
2391 * NOTE: super csum type and incompat features will not be checked here.
2393 * @sb: super block to check
2394 * @mirror_num: the super block number to check its bytenr:
2395 * 0 the primary (1st) sb
2396 * 1, 2 2nd and 3rd backup copy
2397 * -1 skip bytenr check
2399 static int validate_super(struct btrfs_fs_info *fs_info,
2400 struct btrfs_super_block *sb, int mirror_num)
2402 u64 nodesize = btrfs_super_nodesize(sb);
2403 u64 sectorsize = btrfs_super_sectorsize(sb);
2406 if (btrfs_super_magic(sb) != BTRFS_MAGIC) {
2407 btrfs_err(fs_info, "no valid FS found");
2410 if (btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP) {
2411 btrfs_err(fs_info, "unrecognized or unsupported super flag: %llu",
2412 btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP);
2415 if (btrfs_super_root_level(sb) >= BTRFS_MAX_LEVEL) {
2416 btrfs_err(fs_info, "tree_root level too big: %d >= %d",
2417 btrfs_super_root_level(sb), BTRFS_MAX_LEVEL);
2420 if (btrfs_super_chunk_root_level(sb) >= BTRFS_MAX_LEVEL) {
2421 btrfs_err(fs_info, "chunk_root level too big: %d >= %d",
2422 btrfs_super_chunk_root_level(sb), BTRFS_MAX_LEVEL);
2425 if (btrfs_super_log_root_level(sb) >= BTRFS_MAX_LEVEL) {
2426 btrfs_err(fs_info, "log_root level too big: %d >= %d",
2427 btrfs_super_log_root_level(sb), BTRFS_MAX_LEVEL);
2432 * Check sectorsize and nodesize first, other check will need it.
2433 * Check all possible sectorsize(4K, 8K, 16K, 32K, 64K) here.
2435 if (!is_power_of_2(sectorsize) || sectorsize < 4096 ||
2436 sectorsize > BTRFS_MAX_METADATA_BLOCKSIZE) {
2437 btrfs_err(fs_info, "invalid sectorsize %llu", sectorsize);
2440 /* Only PAGE SIZE is supported yet */
2441 if (sectorsize != PAGE_SIZE) {
2443 "sectorsize %llu not supported yet, only support %lu",
2444 sectorsize, PAGE_SIZE);
2447 if (!is_power_of_2(nodesize) || nodesize < sectorsize ||
2448 nodesize > BTRFS_MAX_METADATA_BLOCKSIZE) {
2449 btrfs_err(fs_info, "invalid nodesize %llu", nodesize);
2452 if (nodesize != le32_to_cpu(sb->__unused_leafsize)) {
2453 btrfs_err(fs_info, "invalid leafsize %u, should be %llu",
2454 le32_to_cpu(sb->__unused_leafsize), nodesize);
2458 /* Root alignment check */
2459 if (!IS_ALIGNED(btrfs_super_root(sb), sectorsize)) {
2460 btrfs_warn(fs_info, "tree_root block unaligned: %llu",
2461 btrfs_super_root(sb));
2464 if (!IS_ALIGNED(btrfs_super_chunk_root(sb), sectorsize)) {
2465 btrfs_warn(fs_info, "chunk_root block unaligned: %llu",
2466 btrfs_super_chunk_root(sb));
2469 if (!IS_ALIGNED(btrfs_super_log_root(sb), sectorsize)) {
2470 btrfs_warn(fs_info, "log_root block unaligned: %llu",
2471 btrfs_super_log_root(sb));
2475 if (memcmp(fs_info->fs_devices->metadata_uuid, sb->dev_item.fsid,
2476 BTRFS_FSID_SIZE) != 0) {
2478 "dev_item UUID does not match metadata fsid: %pU != %pU",
2479 fs_info->fs_devices->metadata_uuid, sb->dev_item.fsid);
2484 * Hint to catch really bogus numbers, bitflips or so, more exact checks are
2487 if (btrfs_super_bytes_used(sb) < 6 * btrfs_super_nodesize(sb)) {
2488 btrfs_err(fs_info, "bytes_used is too small %llu",
2489 btrfs_super_bytes_used(sb));
2492 if (!is_power_of_2(btrfs_super_stripesize(sb))) {
2493 btrfs_err(fs_info, "invalid stripesize %u",
2494 btrfs_super_stripesize(sb));
2497 if (btrfs_super_num_devices(sb) > (1UL << 31))
2498 btrfs_warn(fs_info, "suspicious number of devices: %llu",
2499 btrfs_super_num_devices(sb));
2500 if (btrfs_super_num_devices(sb) == 0) {
2501 btrfs_err(fs_info, "number of devices is 0");
2505 if (mirror_num >= 0 &&
2506 btrfs_super_bytenr(sb) != btrfs_sb_offset(mirror_num)) {
2507 btrfs_err(fs_info, "super offset mismatch %llu != %u",
2508 btrfs_super_bytenr(sb), BTRFS_SUPER_INFO_OFFSET);
2513 * Obvious sys_chunk_array corruptions, it must hold at least one key
2516 if (btrfs_super_sys_array_size(sb) > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
2517 btrfs_err(fs_info, "system chunk array too big %u > %u",
2518 btrfs_super_sys_array_size(sb),
2519 BTRFS_SYSTEM_CHUNK_ARRAY_SIZE);
2522 if (btrfs_super_sys_array_size(sb) < sizeof(struct btrfs_disk_key)
2523 + sizeof(struct btrfs_chunk)) {
2524 btrfs_err(fs_info, "system chunk array too small %u < %zu",
2525 btrfs_super_sys_array_size(sb),
2526 sizeof(struct btrfs_disk_key)
2527 + sizeof(struct btrfs_chunk));
2532 * The generation is a global counter, we'll trust it more than the others
2533 * but it's still possible that it's the one that's wrong.
2535 if (btrfs_super_generation(sb) < btrfs_super_chunk_root_generation(sb))
2537 "suspicious: generation < chunk_root_generation: %llu < %llu",
2538 btrfs_super_generation(sb),
2539 btrfs_super_chunk_root_generation(sb));
2540 if (btrfs_super_generation(sb) < btrfs_super_cache_generation(sb)
2541 && btrfs_super_cache_generation(sb) != (u64)-1)
2543 "suspicious: generation < cache_generation: %llu < %llu",
2544 btrfs_super_generation(sb),
2545 btrfs_super_cache_generation(sb));
2551 * Validation of super block at mount time.
2552 * Some checks already done early at mount time, like csum type and incompat
2553 * flags will be skipped.
2555 static int btrfs_validate_mount_super(struct btrfs_fs_info *fs_info)
2557 return validate_super(fs_info, fs_info->super_copy, 0);
2561 * Validation of super block at write time.
2562 * Some checks like bytenr check will be skipped as their values will be
2564 * Extra checks like csum type and incompat flags will be done here.
2566 static int btrfs_validate_write_super(struct btrfs_fs_info *fs_info,
2567 struct btrfs_super_block *sb)
2571 ret = validate_super(fs_info, sb, -1);
2574 if (!btrfs_supported_super_csum(btrfs_super_csum_type(sb))) {
2576 btrfs_err(fs_info, "invalid csum type, has %u want %u",
2577 btrfs_super_csum_type(sb), BTRFS_CSUM_TYPE_CRC32);
2580 if (btrfs_super_incompat_flags(sb) & ~BTRFS_FEATURE_INCOMPAT_SUPP) {
2583 "invalid incompat flags, has 0x%llx valid mask 0x%llx",
2584 btrfs_super_incompat_flags(sb),
2585 (unsigned long long)BTRFS_FEATURE_INCOMPAT_SUPP);
2591 "super block corruption detected before writing it to disk");
2595 int open_ctree(struct super_block *sb,
2596 struct btrfs_fs_devices *fs_devices,
2605 struct btrfs_key location;
2606 struct buffer_head *bh;
2607 struct btrfs_super_block *disk_super;
2608 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
2609 struct btrfs_root *tree_root;
2610 struct btrfs_root *chunk_root;
2613 int num_backups_tried = 0;
2614 int backup_index = 0;
2615 int clear_free_space_tree = 0;
2618 tree_root = fs_info->tree_root = btrfs_alloc_root(fs_info, GFP_KERNEL);
2619 chunk_root = fs_info->chunk_root = btrfs_alloc_root(fs_info, GFP_KERNEL);
2620 if (!tree_root || !chunk_root) {
2625 ret = init_srcu_struct(&fs_info->subvol_srcu);
2631 ret = percpu_counter_init(&fs_info->dio_bytes, 0, GFP_KERNEL);
2637 ret = percpu_counter_init(&fs_info->dirty_metadata_bytes, 0, GFP_KERNEL);
2640 goto fail_dio_bytes;
2642 fs_info->dirty_metadata_batch = PAGE_SIZE *
2643 (1 + ilog2(nr_cpu_ids));
2645 ret = percpu_counter_init(&fs_info->delalloc_bytes, 0, GFP_KERNEL);
2648 goto fail_dirty_metadata_bytes;
2651 ret = percpu_counter_init(&fs_info->dev_replace.bio_counter, 0,
2655 goto fail_delalloc_bytes;
2658 INIT_RADIX_TREE(&fs_info->fs_roots_radix, GFP_ATOMIC);
2659 INIT_RADIX_TREE(&fs_info->buffer_radix, GFP_ATOMIC);
2660 INIT_LIST_HEAD(&fs_info->trans_list);
2661 INIT_LIST_HEAD(&fs_info->dead_roots);
2662 INIT_LIST_HEAD(&fs_info->delayed_iputs);
2663 INIT_LIST_HEAD(&fs_info->delalloc_roots);
2664 INIT_LIST_HEAD(&fs_info->caching_block_groups);
2665 INIT_LIST_HEAD(&fs_info->pending_raid_kobjs);
2666 spin_lock_init(&fs_info->pending_raid_kobjs_lock);
2667 spin_lock_init(&fs_info->delalloc_root_lock);
2668 spin_lock_init(&fs_info->trans_lock);
2669 spin_lock_init(&fs_info->fs_roots_radix_lock);
2670 spin_lock_init(&fs_info->delayed_iput_lock);
2671 spin_lock_init(&fs_info->defrag_inodes_lock);
2672 spin_lock_init(&fs_info->tree_mod_seq_lock);
2673 spin_lock_init(&fs_info->super_lock);
2674 spin_lock_init(&fs_info->buffer_lock);
2675 spin_lock_init(&fs_info->unused_bgs_lock);
2676 rwlock_init(&fs_info->tree_mod_log_lock);
2677 mutex_init(&fs_info->unused_bg_unpin_mutex);
2678 mutex_init(&fs_info->delete_unused_bgs_mutex);
2679 mutex_init(&fs_info->reloc_mutex);
2680 mutex_init(&fs_info->delalloc_root_mutex);
2681 seqlock_init(&fs_info->profiles_lock);
2683 INIT_LIST_HEAD(&fs_info->dirty_cowonly_roots);
2684 INIT_LIST_HEAD(&fs_info->space_info);
2685 INIT_LIST_HEAD(&fs_info->tree_mod_seq_list);
2686 INIT_LIST_HEAD(&fs_info->unused_bgs);
2687 extent_map_tree_init(&fs_info->mapping_tree);
2688 btrfs_init_block_rsv(&fs_info->global_block_rsv,
2689 BTRFS_BLOCK_RSV_GLOBAL);
2690 btrfs_init_block_rsv(&fs_info->trans_block_rsv, BTRFS_BLOCK_RSV_TRANS);
2691 btrfs_init_block_rsv(&fs_info->chunk_block_rsv, BTRFS_BLOCK_RSV_CHUNK);
2692 btrfs_init_block_rsv(&fs_info->empty_block_rsv, BTRFS_BLOCK_RSV_EMPTY);
2693 btrfs_init_block_rsv(&fs_info->delayed_block_rsv,
2694 BTRFS_BLOCK_RSV_DELOPS);
2695 btrfs_init_block_rsv(&fs_info->delayed_refs_rsv,
2696 BTRFS_BLOCK_RSV_DELREFS);
2698 atomic_set(&fs_info->async_delalloc_pages, 0);
2699 atomic_set(&fs_info->defrag_running, 0);
2700 atomic_set(&fs_info->reada_works_cnt, 0);
2701 atomic_set(&fs_info->nr_delayed_iputs, 0);
2702 atomic64_set(&fs_info->tree_mod_seq, 0);
2704 fs_info->max_inline = BTRFS_DEFAULT_MAX_INLINE;
2705 fs_info->metadata_ratio = 0;
2706 fs_info->defrag_inodes = RB_ROOT;
2707 atomic64_set(&fs_info->free_chunk_space, 0);
2708 fs_info->tree_mod_log = RB_ROOT;
2709 fs_info->commit_interval = BTRFS_DEFAULT_COMMIT_INTERVAL;
2710 fs_info->avg_delayed_ref_runtime = NSEC_PER_SEC >> 6; /* div by 64 */
2711 /* readahead state */
2712 INIT_RADIX_TREE(&fs_info->reada_tree, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
2713 spin_lock_init(&fs_info->reada_lock);
2714 btrfs_init_ref_verify(fs_info);
2716 fs_info->thread_pool_size = min_t(unsigned long,
2717 num_online_cpus() + 2, 8);
2719 INIT_LIST_HEAD(&fs_info->ordered_roots);
2720 spin_lock_init(&fs_info->ordered_root_lock);
2722 fs_info->btree_inode = new_inode(sb);
2723 if (!fs_info->btree_inode) {
2725 goto fail_bio_counter;
2727 mapping_set_gfp_mask(fs_info->btree_inode->i_mapping, GFP_NOFS);
2729 fs_info->delayed_root = kmalloc(sizeof(struct btrfs_delayed_root),
2731 if (!fs_info->delayed_root) {
2735 btrfs_init_delayed_root(fs_info->delayed_root);
2737 btrfs_init_scrub(fs_info);
2738 #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
2739 fs_info->check_integrity_print_mask = 0;
2741 btrfs_init_balance(fs_info);
2742 btrfs_init_async_reclaim_work(&fs_info->async_reclaim_work);
2744 sb->s_blocksize = BTRFS_BDEV_BLOCKSIZE;
2745 sb->s_blocksize_bits = blksize_bits(BTRFS_BDEV_BLOCKSIZE);
2747 btrfs_init_btree_inode(fs_info);
2749 spin_lock_init(&fs_info->block_group_cache_lock);
2750 fs_info->block_group_cache_tree = RB_ROOT;
2751 fs_info->first_logical_byte = (u64)-1;
2753 extent_io_tree_init(fs_info, &fs_info->freed_extents[0],
2754 IO_TREE_FS_INFO_FREED_EXTENTS0, NULL);
2755 extent_io_tree_init(fs_info, &fs_info->freed_extents[1],
2756 IO_TREE_FS_INFO_FREED_EXTENTS1, NULL);
2757 fs_info->pinned_extents = &fs_info->freed_extents[0];
2758 set_bit(BTRFS_FS_BARRIER, &fs_info->flags);
2760 mutex_init(&fs_info->ordered_operations_mutex);
2761 mutex_init(&fs_info->tree_log_mutex);
2762 mutex_init(&fs_info->chunk_mutex);
2763 mutex_init(&fs_info->transaction_kthread_mutex);
2764 mutex_init(&fs_info->cleaner_mutex);
2765 mutex_init(&fs_info->ro_block_group_mutex);
2766 init_rwsem(&fs_info->commit_root_sem);
2767 init_rwsem(&fs_info->cleanup_work_sem);
2768 init_rwsem(&fs_info->subvol_sem);
2769 sema_init(&fs_info->uuid_tree_rescan_sem, 1);
2771 btrfs_init_dev_replace_locks(fs_info);
2772 btrfs_init_qgroup(fs_info);
2774 btrfs_init_free_cluster(&fs_info->meta_alloc_cluster);
2775 btrfs_init_free_cluster(&fs_info->data_alloc_cluster);
2777 init_waitqueue_head(&fs_info->transaction_throttle);
2778 init_waitqueue_head(&fs_info->transaction_wait);
2779 init_waitqueue_head(&fs_info->transaction_blocked_wait);
2780 init_waitqueue_head(&fs_info->async_submit_wait);
2781 init_waitqueue_head(&fs_info->delayed_iputs_wait);
2783 /* Usable values until the real ones are cached from the superblock */
2784 fs_info->nodesize = 4096;
2785 fs_info->sectorsize = 4096;
2786 fs_info->stripesize = 4096;
2788 spin_lock_init(&fs_info->swapfile_pins_lock);
2789 fs_info->swapfile_pins = RB_ROOT;
2791 ret = btrfs_alloc_stripe_hash_table(fs_info);
2797 __setup_root(tree_root, fs_info, BTRFS_ROOT_TREE_OBJECTID);
2799 invalidate_bdev(fs_devices->latest_bdev);
2802 * Read super block and check the signature bytes only
2804 bh = btrfs_read_dev_super(fs_devices->latest_bdev);
2811 * Verify the type first, if that or the the checksum value are
2812 * corrupted, we'll find out
2814 csum_type = btrfs_super_csum_type((struct btrfs_super_block *)bh->b_data);
2815 if (!btrfs_supported_super_csum(csum_type)) {
2816 btrfs_err(fs_info, "unsupported checksum algorithm: %u",
2824 * We want to check superblock checksum, the type is stored inside.
2825 * Pass the whole disk block of size BTRFS_SUPER_INFO_SIZE (4k).
2827 if (btrfs_check_super_csum(fs_info, bh->b_data)) {
2828 btrfs_err(fs_info, "superblock checksum mismatch");
2835 * super_copy is zeroed at allocation time and we never touch the
2836 * following bytes up to INFO_SIZE, the checksum is calculated from
2837 * the whole block of INFO_SIZE
2839 memcpy(fs_info->super_copy, bh->b_data, sizeof(*fs_info->super_copy));
2842 disk_super = fs_info->super_copy;
2844 ASSERT(!memcmp(fs_info->fs_devices->fsid, fs_info->super_copy->fsid,
2847 if (btrfs_fs_incompat(fs_info, METADATA_UUID)) {
2848 ASSERT(!memcmp(fs_info->fs_devices->metadata_uuid,
2849 fs_info->super_copy->metadata_uuid,
2853 features = btrfs_super_flags(disk_super);
2854 if (features & BTRFS_SUPER_FLAG_CHANGING_FSID_V2) {
2855 features &= ~BTRFS_SUPER_FLAG_CHANGING_FSID_V2;
2856 btrfs_set_super_flags(disk_super, features);
2858 "found metadata UUID change in progress flag, clearing");
2861 memcpy(fs_info->super_for_commit, fs_info->super_copy,
2862 sizeof(*fs_info->super_for_commit));
2864 ret = btrfs_validate_mount_super(fs_info);
2866 btrfs_err(fs_info, "superblock contains fatal errors");
2871 if (!btrfs_super_root(disk_super))
2874 /* check FS state, whether FS is broken. */
2875 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_ERROR)
2876 set_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state);
2879 * run through our array of backup supers and setup
2880 * our ring pointer to the oldest one
2882 generation = btrfs_super_generation(disk_super);
2883 find_oldest_super_backup(fs_info, generation);
2886 * In the long term, we'll store the compression type in the super
2887 * block, and it'll be used for per file compression control.
2889 fs_info->compress_type = BTRFS_COMPRESS_ZLIB;
2891 ret = btrfs_parse_options(fs_info, options, sb->s_flags);
2897 features = btrfs_super_incompat_flags(disk_super) &
2898 ~BTRFS_FEATURE_INCOMPAT_SUPP;
2901 "cannot mount because of unsupported optional features (%llx)",
2907 features = btrfs_super_incompat_flags(disk_super);
2908 features |= BTRFS_FEATURE_INCOMPAT_MIXED_BACKREF;
2909 if (fs_info->compress_type == BTRFS_COMPRESS_LZO)
2910 features |= BTRFS_FEATURE_INCOMPAT_COMPRESS_LZO;
2911 else if (fs_info->compress_type == BTRFS_COMPRESS_ZSTD)
2912 features |= BTRFS_FEATURE_INCOMPAT_COMPRESS_ZSTD;
2914 if (features & BTRFS_FEATURE_INCOMPAT_SKINNY_METADATA)
2915 btrfs_info(fs_info, "has skinny extents");
2918 * flag our filesystem as having big metadata blocks if
2919 * they are bigger than the page size
2921 if (btrfs_super_nodesize(disk_super) > PAGE_SIZE) {
2922 if (!(features & BTRFS_FEATURE_INCOMPAT_BIG_METADATA))
2924 "flagging fs with big metadata feature");
2925 features |= BTRFS_FEATURE_INCOMPAT_BIG_METADATA;
2928 nodesize = btrfs_super_nodesize(disk_super);
2929 sectorsize = btrfs_super_sectorsize(disk_super);
2930 stripesize = sectorsize;
2931 fs_info->dirty_metadata_batch = nodesize * (1 + ilog2(nr_cpu_ids));
2932 fs_info->delalloc_batch = sectorsize * 512 * (1 + ilog2(nr_cpu_ids));
2934 /* Cache block sizes */
2935 fs_info->nodesize = nodesize;
2936 fs_info->sectorsize = sectorsize;
2937 fs_info->stripesize = stripesize;
2940 * mixed block groups end up with duplicate but slightly offset
2941 * extent buffers for the same range. It leads to corruptions
2943 if ((features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS) &&
2944 (sectorsize != nodesize)) {
2946 "unequal nodesize/sectorsize (%u != %u) are not allowed for mixed block groups",
2947 nodesize, sectorsize);
2952 * Needn't use the lock because there is no other task which will
2955 btrfs_set_super_incompat_flags(disk_super, features);
2957 features = btrfs_super_compat_ro_flags(disk_super) &
2958 ~BTRFS_FEATURE_COMPAT_RO_SUPP;
2959 if (!sb_rdonly(sb) && features) {
2961 "cannot mount read-write because of unsupported optional features (%llx)",
2967 ret = btrfs_init_workqueues(fs_info, fs_devices);
2970 goto fail_sb_buffer;
2973 sb->s_bdi->congested_fn = btrfs_congested_fn;
2974 sb->s_bdi->congested_data = fs_info;
2975 sb->s_bdi->capabilities |= BDI_CAP_CGROUP_WRITEBACK;
2976 sb->s_bdi->ra_pages = VM_READAHEAD_PAGES;
2977 sb->s_bdi->ra_pages *= btrfs_super_num_devices(disk_super);
2978 sb->s_bdi->ra_pages = max(sb->s_bdi->ra_pages, SZ_4M / PAGE_SIZE);
2980 sb->s_blocksize = sectorsize;
2981 sb->s_blocksize_bits = blksize_bits(sectorsize);
2982 memcpy(&sb->s_uuid, fs_info->fs_devices->fsid, BTRFS_FSID_SIZE);
2984 mutex_lock(&fs_info->chunk_mutex);
2985 ret = btrfs_read_sys_array(fs_info);
2986 mutex_unlock(&fs_info->chunk_mutex);
2988 btrfs_err(fs_info, "failed to read the system array: %d", ret);
2989 goto fail_sb_buffer;
2992 generation = btrfs_super_chunk_root_generation(disk_super);
2993 level = btrfs_super_chunk_root_level(disk_super);
2995 __setup_root(chunk_root, fs_info, BTRFS_CHUNK_TREE_OBJECTID);
2997 chunk_root->node = read_tree_block(fs_info,
2998 btrfs_super_chunk_root(disk_super),
2999 generation, level, NULL);
3000 if (IS_ERR(chunk_root->node) ||
3001 !extent_buffer_uptodate(chunk_root->node)) {
3002 btrfs_err(fs_info, "failed to read chunk root");
3003 if (!IS_ERR(chunk_root->node))
3004 free_extent_buffer(chunk_root->node);
3005 chunk_root->node = NULL;
3006 goto fail_tree_roots;
3008 btrfs_set_root_node(&chunk_root->root_item, chunk_root->node);
3009 chunk_root->commit_root = btrfs_root_node(chunk_root);
3011 read_extent_buffer(chunk_root->node, fs_info->chunk_tree_uuid,
3012 btrfs_header_chunk_tree_uuid(chunk_root->node), BTRFS_UUID_SIZE);
3014 ret = btrfs_read_chunk_tree(fs_info);
3016 btrfs_err(fs_info, "failed to read chunk tree: %d", ret);
3017 goto fail_tree_roots;
3021 * Keep the devid that is marked to be the target device for the
3022 * device replace procedure
3024 btrfs_free_extra_devids(fs_devices, 0);
3026 if (!fs_devices->latest_bdev) {
3027 btrfs_err(fs_info, "failed to read devices");
3028 goto fail_tree_roots;
3032 generation = btrfs_super_generation(disk_super);
3033 level = btrfs_super_root_level(disk_super);
3035 tree_root->node = read_tree_block(fs_info,
3036 btrfs_super_root(disk_super),
3037 generation, level, NULL);
3038 if (IS_ERR(tree_root->node) ||
3039 !extent_buffer_uptodate(tree_root->node)) {
3040 btrfs_warn(fs_info, "failed to read tree root");
3041 if (!IS_ERR(tree_root->node))
3042 free_extent_buffer(tree_root->node);
3043 tree_root->node = NULL;
3044 goto recovery_tree_root;
3047 btrfs_set_root_node(&tree_root->root_item, tree_root->node);
3048 tree_root->commit_root = btrfs_root_node(tree_root);
3049 btrfs_set_root_refs(&tree_root->root_item, 1);
3051 mutex_lock(&tree_root->objectid_mutex);
3052 ret = btrfs_find_highest_objectid(tree_root,
3053 &tree_root->highest_objectid);
3055 mutex_unlock(&tree_root->objectid_mutex);
3056 goto recovery_tree_root;
3059 ASSERT(tree_root->highest_objectid <= BTRFS_LAST_FREE_OBJECTID);
3061 mutex_unlock(&tree_root->objectid_mutex);
3063 ret = btrfs_read_roots(fs_info);
3065 goto recovery_tree_root;
3067 fs_info->generation = generation;
3068 fs_info->last_trans_committed = generation;
3070 ret = btrfs_verify_dev_extents(fs_info);
3073 "failed to verify dev extents against chunks: %d",
3075 goto fail_block_groups;
3077 ret = btrfs_recover_balance(fs_info);
3079 btrfs_err(fs_info, "failed to recover balance: %d", ret);
3080 goto fail_block_groups;
3083 ret = btrfs_init_dev_stats(fs_info);
3085 btrfs_err(fs_info, "failed to init dev_stats: %d", ret);
3086 goto fail_block_groups;
3089 ret = btrfs_init_dev_replace(fs_info);
3091 btrfs_err(fs_info, "failed to init dev_replace: %d", ret);
3092 goto fail_block_groups;
3095 btrfs_free_extra_devids(fs_devices, 1);
3097 ret = btrfs_sysfs_add_fsid(fs_devices, NULL);
3099 btrfs_err(fs_info, "failed to init sysfs fsid interface: %d",
3101 goto fail_block_groups;
3104 ret = btrfs_sysfs_add_device(fs_devices);
3106 btrfs_err(fs_info, "failed to init sysfs device interface: %d",
3108 goto fail_fsdev_sysfs;
3111 ret = btrfs_sysfs_add_mounted(fs_info);
3113 btrfs_err(fs_info, "failed to init sysfs interface: %d", ret);
3114 goto fail_fsdev_sysfs;
3117 ret = btrfs_init_space_info(fs_info);
3119 btrfs_err(fs_info, "failed to initialize space info: %d", ret);
3123 ret = btrfs_read_block_groups(fs_info);
3125 btrfs_err(fs_info, "failed to read block groups: %d", ret);
3129 if (!sb_rdonly(sb) && !btrfs_check_rw_degradable(fs_info, NULL)) {
3131 "writable mount is not allowed due to too many missing devices");
3135 fs_info->cleaner_kthread = kthread_run(cleaner_kthread, tree_root,
3137 if (IS_ERR(fs_info->cleaner_kthread))
3140 fs_info->transaction_kthread = kthread_run(transaction_kthread,
3142 "btrfs-transaction");
3143 if (IS_ERR(fs_info->transaction_kthread))
3146 if (!btrfs_test_opt(fs_info, NOSSD) &&
3147 !fs_info->fs_devices->rotating) {
3148 btrfs_set_and_info(fs_info, SSD, "enabling ssd optimizations");
3152 * Mount does not set all options immediately, we can do it now and do
3153 * not have to wait for transaction commit
3155 btrfs_apply_pending_changes(fs_info);
3157 #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
3158 if (btrfs_test_opt(fs_info, CHECK_INTEGRITY)) {
3159 ret = btrfsic_mount(fs_info, fs_devices,
3160 btrfs_test_opt(fs_info,
3161 CHECK_INTEGRITY_INCLUDING_EXTENT_DATA) ?
3163 fs_info->check_integrity_print_mask);
3166 "failed to initialize integrity check module: %d",
3170 ret = btrfs_read_qgroup_config(fs_info);
3172 goto fail_trans_kthread;
3174 if (btrfs_build_ref_tree(fs_info))
3175 btrfs_err(fs_info, "couldn't build ref tree");
3177 /* do not make disk changes in broken FS or nologreplay is given */
3178 if (btrfs_super_log_root(disk_super) != 0 &&
3179 !btrfs_test_opt(fs_info, NOLOGREPLAY)) {
3180 ret = btrfs_replay_log(fs_info, fs_devices);
3187 ret = btrfs_find_orphan_roots(fs_info);
3191 if (!sb_rdonly(sb)) {
3192 ret = btrfs_cleanup_fs_roots(fs_info);
3196 mutex_lock(&fs_info->cleaner_mutex);
3197 ret = btrfs_recover_relocation(tree_root);
3198 mutex_unlock(&fs_info->cleaner_mutex);
3200 btrfs_warn(fs_info, "failed to recover relocation: %d",
3207 location.objectid = BTRFS_FS_TREE_OBJECTID;
3208 location.type = BTRFS_ROOT_ITEM_KEY;
3209 location.offset = 0;
3211 fs_info->fs_root = btrfs_read_fs_root_no_name(fs_info, &location);
3212 if (IS_ERR(fs_info->fs_root)) {
3213 err = PTR_ERR(fs_info->fs_root);
3214 btrfs_warn(fs_info, "failed to read fs tree: %d", err);
3221 if (btrfs_test_opt(fs_info, CLEAR_CACHE) &&
3222 btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
3223 clear_free_space_tree = 1;
3224 } else if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE) &&
3225 !btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE_VALID)) {
3226 btrfs_warn(fs_info, "free space tree is invalid");
3227 clear_free_space_tree = 1;
3230 if (clear_free_space_tree) {
3231 btrfs_info(fs_info, "clearing free space tree");
3232 ret = btrfs_clear_free_space_tree(fs_info);
3235 "failed to clear free space tree: %d", ret);
3236 close_ctree(fs_info);
3241 if (btrfs_test_opt(fs_info, FREE_SPACE_TREE) &&
3242 !btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
3243 btrfs_info(fs_info, "creating free space tree");
3244 ret = btrfs_create_free_space_tree(fs_info);
3247 "failed to create free space tree: %d", ret);
3248 close_ctree(fs_info);
3253 down_read(&fs_info->cleanup_work_sem);
3254 if ((ret = btrfs_orphan_cleanup(fs_info->fs_root)) ||
3255 (ret = btrfs_orphan_cleanup(fs_info->tree_root))) {
3256 up_read(&fs_info->cleanup_work_sem);
3257 close_ctree(fs_info);
3260 up_read(&fs_info->cleanup_work_sem);
3262 ret = btrfs_resume_balance_async(fs_info);
3264 btrfs_warn(fs_info, "failed to resume balance: %d", ret);
3265 close_ctree(fs_info);
3269 ret = btrfs_resume_dev_replace_async(fs_info);
3271 btrfs_warn(fs_info, "failed to resume device replace: %d", ret);
3272 close_ctree(fs_info);
3276 btrfs_qgroup_rescan_resume(fs_info);
3278 if (!fs_info->uuid_root) {
3279 btrfs_info(fs_info, "creating UUID tree");
3280 ret = btrfs_create_uuid_tree(fs_info);
3283 "failed to create the UUID tree: %d", ret);
3284 close_ctree(fs_info);
3287 } else if (btrfs_test_opt(fs_info, RESCAN_UUID_TREE) ||
3288 fs_info->generation !=
3289 btrfs_super_uuid_tree_generation(disk_super)) {
3290 btrfs_info(fs_info, "checking UUID tree");
3291 ret = btrfs_check_uuid_tree(fs_info);
3294 "failed to check the UUID tree: %d", ret);
3295 close_ctree(fs_info);
3299 set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
3301 set_bit(BTRFS_FS_OPEN, &fs_info->flags);
3304 * backuproot only affect mount behavior, and if open_ctree succeeded,
3305 * no need to keep the flag
3307 btrfs_clear_opt(fs_info->mount_opt, USEBACKUPROOT);
3312 btrfs_free_qgroup_config(fs_info);
3314 kthread_stop(fs_info->transaction_kthread);
3315 btrfs_cleanup_transaction(fs_info);
3316 btrfs_free_fs_roots(fs_info);
3318 kthread_stop(fs_info->cleaner_kthread);
3321 * make sure we're done with the btree inode before we stop our
3324 filemap_write_and_wait(fs_info->btree_inode->i_mapping);
3327 btrfs_sysfs_remove_mounted(fs_info);
3330 btrfs_sysfs_remove_fsid(fs_info->fs_devices);
3333 btrfs_put_block_group_cache(fs_info);
3336 free_root_pointers(fs_info, 1);
3337 invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
3340 btrfs_stop_all_workers(fs_info);
3341 btrfs_free_block_groups(fs_info);
3344 btrfs_mapping_tree_free(&fs_info->mapping_tree);
3346 iput(fs_info->btree_inode);
3348 percpu_counter_destroy(&fs_info->dev_replace.bio_counter);
3349 fail_delalloc_bytes:
3350 percpu_counter_destroy(&fs_info->delalloc_bytes);
3351 fail_dirty_metadata_bytes:
3352 percpu_counter_destroy(&fs_info->dirty_metadata_bytes);
3354 percpu_counter_destroy(&fs_info->dio_bytes);
3356 cleanup_srcu_struct(&fs_info->subvol_srcu);
3358 btrfs_free_stripe_hash_table(fs_info);
3359 btrfs_close_devices(fs_info->fs_devices);
3363 if (!btrfs_test_opt(fs_info, USEBACKUPROOT))
3364 goto fail_tree_roots;
3366 free_root_pointers(fs_info, 0);
3368 /* don't use the log in recovery mode, it won't be valid */
3369 btrfs_set_super_log_root(disk_super, 0);
3371 /* we can't trust the free space cache either */
3372 btrfs_set_opt(fs_info->mount_opt, CLEAR_CACHE);
3374 ret = next_root_backup(fs_info, fs_info->super_copy,
3375 &num_backups_tried, &backup_index);
3377 goto fail_block_groups;
3378 goto retry_root_backup;
3380 ALLOW_ERROR_INJECTION(open_ctree, ERRNO);
3382 static void btrfs_end_buffer_write_sync(struct buffer_head *bh, int uptodate)
3385 set_buffer_uptodate(bh);
3387 struct btrfs_device *device = (struct btrfs_device *)
3390 btrfs_warn_rl_in_rcu(device->fs_info,
3391 "lost page write due to IO error on %s",
3392 rcu_str_deref(device->name));
3393 /* note, we don't set_buffer_write_io_error because we have
3394 * our own ways of dealing with the IO errors
3396 clear_buffer_uptodate(bh);
3397 btrfs_dev_stat_inc_and_print(device, BTRFS_DEV_STAT_WRITE_ERRS);
3403 int btrfs_read_dev_one_super(struct block_device *bdev, int copy_num,
3404 struct buffer_head **bh_ret)
3406 struct buffer_head *bh;
3407 struct btrfs_super_block *super;
3410 bytenr = btrfs_sb_offset(copy_num);
3411 if (bytenr + BTRFS_SUPER_INFO_SIZE >= i_size_read(bdev->bd_inode))
3414 bh = __bread(bdev, bytenr / BTRFS_BDEV_BLOCKSIZE, BTRFS_SUPER_INFO_SIZE);
3416 * If we fail to read from the underlying devices, as of now
3417 * the best option we have is to mark it EIO.
3422 super = (struct btrfs_super_block *)bh->b_data;
3423 if (btrfs_super_bytenr(super) != bytenr ||
3424 btrfs_super_magic(super) != BTRFS_MAGIC) {
3434 struct buffer_head *btrfs_read_dev_super(struct block_device *bdev)
3436 struct buffer_head *bh;
3437 struct buffer_head *latest = NULL;
3438 struct btrfs_super_block *super;
3443 /* we would like to check all the supers, but that would make
3444 * a btrfs mount succeed after a mkfs from a different FS.
3445 * So, we need to add a special mount option to scan for
3446 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
3448 for (i = 0; i < 1; i++) {
3449 ret = btrfs_read_dev_one_super(bdev, i, &bh);
3453 super = (struct btrfs_super_block *)bh->b_data;
3455 if (!latest || btrfs_super_generation(super) > transid) {
3458 transid = btrfs_super_generation(super);
3465 return ERR_PTR(ret);
3471 * Write superblock @sb to the @device. Do not wait for completion, all the
3472 * buffer heads we write are pinned.
3474 * Write @max_mirrors copies of the superblock, where 0 means default that fit
3475 * the expected device size at commit time. Note that max_mirrors must be
3476 * same for write and wait phases.
3478 * Return number of errors when buffer head is not found or submission fails.
3480 static int write_dev_supers(struct btrfs_device *device,
3481 struct btrfs_super_block *sb, int max_mirrors)
3483 struct buffer_head *bh;
3491 if (max_mirrors == 0)
3492 max_mirrors = BTRFS_SUPER_MIRROR_MAX;
3494 for (i = 0; i < max_mirrors; i++) {
3495 bytenr = btrfs_sb_offset(i);
3496 if (bytenr + BTRFS_SUPER_INFO_SIZE >=
3497 device->commit_total_bytes)
3500 btrfs_set_super_bytenr(sb, bytenr);
3503 crc = btrfs_csum_data((const char *)sb + BTRFS_CSUM_SIZE, crc,
3504 BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE);
3505 btrfs_csum_final(crc, sb->csum);
3507 /* One reference for us, and we leave it for the caller */
3508 bh = __getblk(device->bdev, bytenr / BTRFS_BDEV_BLOCKSIZE,
3509 BTRFS_SUPER_INFO_SIZE);
3511 btrfs_err(device->fs_info,
3512 "couldn't get super buffer head for bytenr %llu",
3518 memcpy(bh->b_data, sb, BTRFS_SUPER_INFO_SIZE);
3520 /* one reference for submit_bh */
3523 set_buffer_uptodate(bh);
3525 bh->b_end_io = btrfs_end_buffer_write_sync;
3526 bh->b_private = device;
3529 * we fua the first super. The others we allow
3532 op_flags = REQ_SYNC | REQ_META | REQ_PRIO;
3533 if (i == 0 && !btrfs_test_opt(device->fs_info, NOBARRIER))
3534 op_flags |= REQ_FUA;
3535 ret = btrfsic_submit_bh(REQ_OP_WRITE, op_flags, bh);
3539 return errors < i ? 0 : -1;
3543 * Wait for write completion of superblocks done by write_dev_supers,
3544 * @max_mirrors same for write and wait phases.
3546 * Return number of errors when buffer head is not found or not marked up to
3549 static int wait_dev_supers(struct btrfs_device *device, int max_mirrors)
3551 struct buffer_head *bh;
3554 bool primary_failed = false;
3557 if (max_mirrors == 0)
3558 max_mirrors = BTRFS_SUPER_MIRROR_MAX;
3560 for (i = 0; i < max_mirrors; i++) {
3561 bytenr = btrfs_sb_offset(i);
3562 if (bytenr + BTRFS_SUPER_INFO_SIZE >=
3563 device->commit_total_bytes)
3566 bh = __find_get_block(device->bdev,
3567 bytenr / BTRFS_BDEV_BLOCKSIZE,
3568 BTRFS_SUPER_INFO_SIZE);
3572 primary_failed = true;
3576 if (!buffer_uptodate(bh)) {
3579 primary_failed = true;
3582 /* drop our reference */
3585 /* drop the reference from the writing run */
3589 /* log error, force error return */
3590 if (primary_failed) {
3591 btrfs_err(device->fs_info, "error writing primary super block to device %llu",
3596 return errors < i ? 0 : -1;
3600 * endio for the write_dev_flush, this will wake anyone waiting
3601 * for the barrier when it is done
3603 static void btrfs_end_empty_barrier(struct bio *bio)
3605 complete(bio->bi_private);
3609 * Submit a flush request to the device if it supports it. Error handling is
3610 * done in the waiting counterpart.
3612 static void write_dev_flush(struct btrfs_device *device)
3614 struct request_queue *q = bdev_get_queue(device->bdev);
3615 struct bio *bio = device->flush_bio;
3617 if (!test_bit(QUEUE_FLAG_WC, &q->queue_flags))
3621 bio->bi_end_io = btrfs_end_empty_barrier;
3622 bio_set_dev(bio, device->bdev);
3623 bio->bi_opf = REQ_OP_WRITE | REQ_SYNC | REQ_PREFLUSH;
3624 init_completion(&device->flush_wait);
3625 bio->bi_private = &device->flush_wait;
3627 btrfsic_submit_bio(bio);
3628 set_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state);
3632 * If the flush bio has been submitted by write_dev_flush, wait for it.
3634 static blk_status_t wait_dev_flush(struct btrfs_device *device)
3636 struct bio *bio = device->flush_bio;
3638 if (!test_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state))
3641 clear_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state);
3642 wait_for_completion_io(&device->flush_wait);
3644 return bio->bi_status;
3647 static int check_barrier_error(struct btrfs_fs_info *fs_info)
3649 if (!btrfs_check_rw_degradable(fs_info, NULL))
3655 * send an empty flush down to each device in parallel,
3656 * then wait for them
3658 static int barrier_all_devices(struct btrfs_fs_info *info)
3660 struct list_head *head;
3661 struct btrfs_device *dev;
3662 int errors_wait = 0;
3665 lockdep_assert_held(&info->fs_devices->device_list_mutex);
3666 /* send down all the barriers */
3667 head = &info->fs_devices->devices;
3668 list_for_each_entry(dev, head, dev_list) {
3669 if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
3673 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
3674 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
3677 write_dev_flush(dev);
3678 dev->last_flush_error = BLK_STS_OK;
3681 /* wait for all the barriers */
3682 list_for_each_entry(dev, head, dev_list) {
3683 if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
3689 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
3690 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
3693 ret = wait_dev_flush(dev);
3695 dev->last_flush_error = ret;
3696 btrfs_dev_stat_inc_and_print(dev,
3697 BTRFS_DEV_STAT_FLUSH_ERRS);
3704 * At some point we need the status of all disks
3705 * to arrive at the volume status. So error checking
3706 * is being pushed to a separate loop.
3708 return check_barrier_error(info);
3713 int btrfs_get_num_tolerated_disk_barrier_failures(u64 flags)
3716 int min_tolerated = INT_MAX;
3718 if ((flags & BTRFS_BLOCK_GROUP_PROFILE_MASK) == 0 ||
3719 (flags & BTRFS_AVAIL_ALLOC_BIT_SINGLE))
3720 min_tolerated = min_t(int, min_tolerated,
3721 btrfs_raid_array[BTRFS_RAID_SINGLE].
3722 tolerated_failures);
3724 for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) {
3725 if (raid_type == BTRFS_RAID_SINGLE)
3727 if (!(flags & btrfs_raid_array[raid_type].bg_flag))
3729 min_tolerated = min_t(int, min_tolerated,
3730 btrfs_raid_array[raid_type].
3731 tolerated_failures);
3734 if (min_tolerated == INT_MAX) {
3735 pr_warn("BTRFS: unknown raid flag: %llu", flags);
3739 return min_tolerated;
3742 int write_all_supers(struct btrfs_fs_info *fs_info, int max_mirrors)
3744 struct list_head *head;
3745 struct btrfs_device *dev;
3746 struct btrfs_super_block *sb;
3747 struct btrfs_dev_item *dev_item;
3751 int total_errors = 0;
3754 do_barriers = !btrfs_test_opt(fs_info, NOBARRIER);
3757 * max_mirrors == 0 indicates we're from commit_transaction,
3758 * not from fsync where the tree roots in fs_info have not
3759 * been consistent on disk.
3761 if (max_mirrors == 0)
3762 backup_super_roots(fs_info);
3764 sb = fs_info->super_for_commit;
3765 dev_item = &sb->dev_item;
3767 mutex_lock(&fs_info->fs_devices->device_list_mutex);
3768 head = &fs_info->fs_devices->devices;
3769 max_errors = btrfs_super_num_devices(fs_info->super_copy) - 1;
3772 ret = barrier_all_devices(fs_info);
3775 &fs_info->fs_devices->device_list_mutex);
3776 btrfs_handle_fs_error(fs_info, ret,
3777 "errors while submitting device barriers.");
3782 list_for_each_entry(dev, head, dev_list) {
3787 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
3788 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))