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 <asm/unaligned.h>
23 #include "transaction.h"
24 #include "btrfs_inode.h"
26 #include "print-tree.h"
29 #include "free-space-cache.h"
30 #include "free-space-tree.h"
31 #include "inode-map.h"
32 #include "check-integrity.h"
33 #include "rcu-string.h"
34 #include "dev-replace.h"
38 #include "compression.h"
39 #include "tree-checker.h"
40 #include "ref-verify.h"
43 #include <asm/cpufeature.h>
46 #define BTRFS_SUPER_FLAG_SUPP (BTRFS_HEADER_FLAG_WRITTEN |\
47 BTRFS_HEADER_FLAG_RELOC |\
48 BTRFS_SUPER_FLAG_ERROR |\
49 BTRFS_SUPER_FLAG_SEEDING |\
50 BTRFS_SUPER_FLAG_METADUMP |\
51 BTRFS_SUPER_FLAG_METADUMP_V2)
53 static const struct extent_io_ops btree_extent_io_ops;
54 static void end_workqueue_fn(struct btrfs_work *work);
55 static void btrfs_destroy_ordered_extents(struct btrfs_root *root);
56 static int btrfs_destroy_delayed_refs(struct btrfs_transaction *trans,
57 struct btrfs_fs_info *fs_info);
58 static void btrfs_destroy_delalloc_inodes(struct btrfs_root *root);
59 static int btrfs_destroy_marked_extents(struct btrfs_fs_info *fs_info,
60 struct extent_io_tree *dirty_pages,
62 static int btrfs_destroy_pinned_extent(struct btrfs_fs_info *fs_info,
63 struct extent_io_tree *pinned_extents);
64 static int btrfs_cleanup_transaction(struct btrfs_fs_info *fs_info);
65 static void btrfs_error_commit_super(struct btrfs_fs_info *fs_info);
68 * btrfs_end_io_wq structs are used to do processing in task context when an IO
69 * is complete. This is used during reads to verify checksums, and it is used
70 * by writes to insert metadata for new file extents after IO is complete.
72 struct btrfs_end_io_wq {
76 struct btrfs_fs_info *info;
78 enum btrfs_wq_endio_type metadata;
79 struct btrfs_work work;
82 static struct kmem_cache *btrfs_end_io_wq_cache;
84 int __init btrfs_end_io_wq_init(void)
86 btrfs_end_io_wq_cache = kmem_cache_create("btrfs_end_io_wq",
87 sizeof(struct btrfs_end_io_wq),
91 if (!btrfs_end_io_wq_cache)
96 void __cold btrfs_end_io_wq_exit(void)
98 kmem_cache_destroy(btrfs_end_io_wq_cache);
102 * async submit bios are used to offload expensive checksumming
103 * onto the worker threads. They checksum file and metadata bios
104 * just before they are sent down the IO stack.
106 struct async_submit_bio {
109 extent_submit_bio_start_t *submit_bio_start;
112 * bio_offset is optional, can be used if the pages in the bio
113 * can't tell us where in the file the bio should go
116 struct btrfs_work work;
121 * Lockdep class keys for extent_buffer->lock's in this root. For a given
122 * eb, the lockdep key is determined by the btrfs_root it belongs to and
123 * the level the eb occupies in the tree.
125 * Different roots are used for different purposes and may nest inside each
126 * other and they require separate keysets. As lockdep keys should be
127 * static, assign keysets according to the purpose of the root as indicated
128 * by btrfs_root->objectid. This ensures that all special purpose roots
129 * have separate keysets.
131 * Lock-nesting across peer nodes is always done with the immediate parent
132 * node locked thus preventing deadlock. As lockdep doesn't know this, use
133 * subclass to avoid triggering lockdep warning in such cases.
135 * The key is set by the readpage_end_io_hook after the buffer has passed
136 * csum validation but before the pages are unlocked. It is also set by
137 * btrfs_init_new_buffer on freshly allocated blocks.
139 * We also add a check to make sure the highest level of the tree is the
140 * same as our lockdep setup here. If BTRFS_MAX_LEVEL changes, this code
141 * needs update as well.
143 #ifdef CONFIG_DEBUG_LOCK_ALLOC
144 # if BTRFS_MAX_LEVEL != 8
148 static struct btrfs_lockdep_keyset {
149 u64 id; /* root objectid */
150 const char *name_stem; /* lock name stem */
151 char names[BTRFS_MAX_LEVEL + 1][20];
152 struct lock_class_key keys[BTRFS_MAX_LEVEL + 1];
153 } btrfs_lockdep_keysets[] = {
154 { .id = BTRFS_ROOT_TREE_OBJECTID, .name_stem = "root" },
155 { .id = BTRFS_EXTENT_TREE_OBJECTID, .name_stem = "extent" },
156 { .id = BTRFS_CHUNK_TREE_OBJECTID, .name_stem = "chunk" },
157 { .id = BTRFS_DEV_TREE_OBJECTID, .name_stem = "dev" },
158 { .id = BTRFS_FS_TREE_OBJECTID, .name_stem = "fs" },
159 { .id = BTRFS_CSUM_TREE_OBJECTID, .name_stem = "csum" },
160 { .id = BTRFS_QUOTA_TREE_OBJECTID, .name_stem = "quota" },
161 { .id = BTRFS_TREE_LOG_OBJECTID, .name_stem = "log" },
162 { .id = BTRFS_TREE_RELOC_OBJECTID, .name_stem = "treloc" },
163 { .id = BTRFS_DATA_RELOC_TREE_OBJECTID, .name_stem = "dreloc" },
164 { .id = BTRFS_UUID_TREE_OBJECTID, .name_stem = "uuid" },
165 { .id = BTRFS_FREE_SPACE_TREE_OBJECTID, .name_stem = "free-space" },
166 { .id = 0, .name_stem = "tree" },
169 void __init btrfs_init_lockdep(void)
173 /* initialize lockdep class names */
174 for (i = 0; i < ARRAY_SIZE(btrfs_lockdep_keysets); i++) {
175 struct btrfs_lockdep_keyset *ks = &btrfs_lockdep_keysets[i];
177 for (j = 0; j < ARRAY_SIZE(ks->names); j++)
178 snprintf(ks->names[j], sizeof(ks->names[j]),
179 "btrfs-%s-%02d", ks->name_stem, j);
183 void btrfs_set_buffer_lockdep_class(u64 objectid, struct extent_buffer *eb,
186 struct btrfs_lockdep_keyset *ks;
188 BUG_ON(level >= ARRAY_SIZE(ks->keys));
190 /* find the matching keyset, id 0 is the default entry */
191 for (ks = btrfs_lockdep_keysets; ks->id; ks++)
192 if (ks->id == objectid)
195 lockdep_set_class_and_name(&eb->lock,
196 &ks->keys[level], ks->names[level]);
202 * extents on the btree inode are pretty simple, there's one extent
203 * that covers the entire device
205 struct extent_map *btree_get_extent(struct btrfs_inode *inode,
206 struct page *page, size_t pg_offset, u64 start, u64 len,
209 struct btrfs_fs_info *fs_info = inode->root->fs_info;
210 struct extent_map_tree *em_tree = &inode->extent_tree;
211 struct extent_map *em;
214 read_lock(&em_tree->lock);
215 em = lookup_extent_mapping(em_tree, start, len);
217 em->bdev = fs_info->fs_devices->latest_bdev;
218 read_unlock(&em_tree->lock);
221 read_unlock(&em_tree->lock);
223 em = alloc_extent_map();
225 em = ERR_PTR(-ENOMEM);
230 em->block_len = (u64)-1;
232 em->bdev = fs_info->fs_devices->latest_bdev;
234 write_lock(&em_tree->lock);
235 ret = add_extent_mapping(em_tree, em, 0);
236 if (ret == -EEXIST) {
238 em = lookup_extent_mapping(em_tree, start, len);
245 write_unlock(&em_tree->lock);
251 u32 btrfs_csum_data(const char *data, u32 seed, size_t len)
253 return crc32c(seed, data, len);
256 void btrfs_csum_final(u32 crc, u8 *result)
258 put_unaligned_le32(~crc, result);
262 * compute the csum for a btree block, and either verify it or write it
263 * into the csum field of the block.
265 static int csum_tree_block(struct btrfs_fs_info *fs_info,
266 struct extent_buffer *buf,
269 u16 csum_size = btrfs_super_csum_size(fs_info->super_copy);
270 char result[BTRFS_CSUM_SIZE];
272 unsigned long cur_len;
273 unsigned long offset = BTRFS_CSUM_SIZE;
275 unsigned long map_start;
276 unsigned long map_len;
280 len = buf->len - offset;
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);
297 if (memcmp_extent_buffer(buf, result, 0, csum_size)) {
300 memcpy(&found, result, csum_size);
302 read_extent_buffer(buf, &val, 0, csum_size);
303 btrfs_warn_rl(fs_info,
304 "%s checksum verify failed on %llu wanted %X found %X level %d",
305 fs_info->sb->s_id, buf->start,
306 val, found, btrfs_header_level(buf));
310 write_extent_buffer(buf, result, 0, csum_size);
317 * we can't consider a given block up to date unless the transid of the
318 * block matches the transid in the parent node's pointer. This is how we
319 * detect blocks that either didn't get written at all or got written
320 * in the wrong place.
322 static int verify_parent_transid(struct extent_io_tree *io_tree,
323 struct extent_buffer *eb, u64 parent_transid,
326 struct extent_state *cached_state = NULL;
328 bool need_lock = (current->journal_info == BTRFS_SEND_TRANS_STUB);
330 if (!parent_transid || btrfs_header_generation(eb) == parent_transid)
337 btrfs_tree_read_lock(eb);
338 btrfs_set_lock_blocking_rw(eb, BTRFS_READ_LOCK);
341 lock_extent_bits(io_tree, eb->start, eb->start + eb->len - 1,
343 if (extent_buffer_uptodate(eb) &&
344 btrfs_header_generation(eb) == parent_transid) {
348 btrfs_err_rl(eb->fs_info,
349 "parent transid verify failed on %llu wanted %llu found %llu",
351 parent_transid, btrfs_header_generation(eb));
355 * Things reading via commit roots that don't have normal protection,
356 * like send, can have a really old block in cache that may point at a
357 * block that has been freed and re-allocated. So don't clear uptodate
358 * if we find an eb that is under IO (dirty/writeback) because we could
359 * end up reading in the stale data and then writing it back out and
360 * making everybody very sad.
362 if (!extent_buffer_under_io(eb))
363 clear_extent_buffer_uptodate(eb);
365 unlock_extent_cached(io_tree, eb->start, eb->start + eb->len - 1,
368 btrfs_tree_read_unlock_blocking(eb);
373 * Return 0 if the superblock checksum type matches the checksum value of that
374 * algorithm. Pass the raw disk superblock data.
376 static int btrfs_check_super_csum(struct btrfs_fs_info *fs_info,
379 struct btrfs_super_block *disk_sb =
380 (struct btrfs_super_block *)raw_disk_sb;
381 u16 csum_type = btrfs_super_csum_type(disk_sb);
384 if (csum_type == BTRFS_CSUM_TYPE_CRC32) {
386 char result[sizeof(crc)];
389 * The super_block structure does not span the whole
390 * BTRFS_SUPER_INFO_SIZE range, we expect that the unused space
391 * is filled with zeros and is included in the checksum.
393 crc = btrfs_csum_data(raw_disk_sb + BTRFS_CSUM_SIZE,
394 crc, BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE);
395 btrfs_csum_final(crc, result);
397 if (memcmp(raw_disk_sb, result, sizeof(result)))
401 if (csum_type >= ARRAY_SIZE(btrfs_csum_sizes)) {
402 btrfs_err(fs_info, "unsupported checksum algorithm %u",
410 static int verify_level_key(struct btrfs_fs_info *fs_info,
411 struct extent_buffer *eb, int level,
412 struct btrfs_key *first_key, u64 parent_transid)
415 struct btrfs_key found_key;
418 found_level = btrfs_header_level(eb);
419 if (found_level != level) {
420 #ifdef CONFIG_BTRFS_DEBUG
423 "tree level mismatch detected, bytenr=%llu level expected=%u has=%u",
424 eb->start, level, found_level);
433 * For live tree block (new tree blocks in current transaction),
434 * we need proper lock context to avoid race, which is impossible here.
435 * So we only checks tree blocks which is read from disk, whose
436 * generation <= fs_info->last_trans_committed.
438 if (btrfs_header_generation(eb) > fs_info->last_trans_committed)
441 btrfs_node_key_to_cpu(eb, &found_key, 0);
443 btrfs_item_key_to_cpu(eb, &found_key, 0);
444 ret = btrfs_comp_cpu_keys(first_key, &found_key);
446 #ifdef CONFIG_BTRFS_DEBUG
450 "tree first key mismatch detected, bytenr=%llu parent_transid=%llu key expected=(%llu,%u,%llu) has=(%llu,%u,%llu)",
451 eb->start, parent_transid, first_key->objectid,
452 first_key->type, first_key->offset,
453 found_key.objectid, found_key.type,
461 * helper to read a given tree block, doing retries as required when
462 * the checksums don't match and we have alternate mirrors to try.
464 * @parent_transid: expected transid, skip check if 0
465 * @level: expected level, mandatory check
466 * @first_key: expected key of first slot, skip check if NULL
468 static int btree_read_extent_buffer_pages(struct btrfs_fs_info *fs_info,
469 struct extent_buffer *eb,
470 u64 parent_transid, int level,
471 struct btrfs_key *first_key)
473 struct extent_io_tree *io_tree;
478 int failed_mirror = 0;
480 io_tree = &BTRFS_I(fs_info->btree_inode)->io_tree;
482 clear_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags);
483 ret = read_extent_buffer_pages(io_tree, eb, WAIT_COMPLETE,
486 if (verify_parent_transid(io_tree, eb,
489 else if (verify_level_key(fs_info, eb, level,
490 first_key, parent_transid))
496 num_copies = btrfs_num_copies(fs_info,
501 if (!failed_mirror) {
503 failed_mirror = eb->read_mirror;
507 if (mirror_num == failed_mirror)
510 if (mirror_num > num_copies)
514 if (failed && !ret && failed_mirror)
515 repair_eb_io_failure(fs_info, eb, failed_mirror);
521 * checksum a dirty tree block before IO. This has extra checks to make sure
522 * we only fill in the checksum field in the first page of a multi-page block
525 static int csum_dirty_buffer(struct btrfs_fs_info *fs_info, struct page *page)
527 u64 start = page_offset(page);
529 struct extent_buffer *eb;
531 eb = (struct extent_buffer *)page->private;
532 if (page != eb->pages[0])
535 found_start = btrfs_header_bytenr(eb);
537 * Please do not consolidate these warnings into a single if.
538 * It is useful to know what went wrong.
540 if (WARN_ON(found_start != start))
542 if (WARN_ON(!PageUptodate(page)))
545 ASSERT(memcmp_extent_buffer(eb, fs_info->fsid,
546 btrfs_header_fsid(), BTRFS_FSID_SIZE) == 0);
548 return csum_tree_block(fs_info, eb, 0);
551 static int check_tree_block_fsid(struct btrfs_fs_info *fs_info,
552 struct extent_buffer *eb)
554 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
555 u8 fsid[BTRFS_FSID_SIZE];
558 read_extent_buffer(eb, fsid, btrfs_header_fsid(), BTRFS_FSID_SIZE);
560 if (!memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE)) {
564 fs_devices = fs_devices->seed;
569 static int btree_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
570 u64 phy_offset, struct page *page,
571 u64 start, u64 end, int mirror)
575 struct extent_buffer *eb;
576 struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
577 struct btrfs_fs_info *fs_info = root->fs_info;
584 eb = (struct extent_buffer *)page->private;
586 /* the pending IO might have been the only thing that kept this buffer
587 * in memory. Make sure we have a ref for all this other checks
589 extent_buffer_get(eb);
591 reads_done = atomic_dec_and_test(&eb->io_pages);
595 eb->read_mirror = mirror;
596 if (test_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags)) {
601 found_start = btrfs_header_bytenr(eb);
602 if (found_start != eb->start) {
603 btrfs_err_rl(fs_info, "bad tree block start, want %llu have %llu",
604 eb->start, found_start);
608 if (check_tree_block_fsid(fs_info, eb)) {
609 btrfs_err_rl(fs_info, "bad fsid on block %llu",
614 found_level = btrfs_header_level(eb);
615 if (found_level >= BTRFS_MAX_LEVEL) {
616 btrfs_err(fs_info, "bad tree block level %d on %llu",
617 (int)btrfs_header_level(eb), eb->start);
622 btrfs_set_buffer_lockdep_class(btrfs_header_owner(eb),
625 ret = csum_tree_block(fs_info, eb, 1);
630 * If this is a leaf block and it is corrupt, set the corrupt bit so
631 * that we don't try and read the other copies of this block, just
634 if (found_level == 0 && btrfs_check_leaf_full(fs_info, eb)) {
635 set_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags);
639 if (found_level > 0 && btrfs_check_node(fs_info, eb))
643 set_extent_buffer_uptodate(eb);
646 test_and_clear_bit(EXTENT_BUFFER_READAHEAD, &eb->bflags))
647 btree_readahead_hook(eb, ret);
651 * our io error hook is going to dec the io pages
652 * again, we have to make sure it has something
655 atomic_inc(&eb->io_pages);
656 clear_extent_buffer_uptodate(eb);
658 free_extent_buffer(eb);
663 static int btree_io_failed_hook(struct page *page, int failed_mirror)
665 struct extent_buffer *eb;
667 eb = (struct extent_buffer *)page->private;
668 set_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
669 eb->read_mirror = failed_mirror;
670 atomic_dec(&eb->io_pages);
671 if (test_and_clear_bit(EXTENT_BUFFER_READAHEAD, &eb->bflags))
672 btree_readahead_hook(eb, -EIO);
673 return -EIO; /* we fixed nothing */
676 static void end_workqueue_bio(struct bio *bio)
678 struct btrfs_end_io_wq *end_io_wq = bio->bi_private;
679 struct btrfs_fs_info *fs_info;
680 struct btrfs_workqueue *wq;
681 btrfs_work_func_t func;
683 fs_info = end_io_wq->info;
684 end_io_wq->status = bio->bi_status;
686 if (bio_op(bio) == REQ_OP_WRITE) {
687 if (end_io_wq->metadata == BTRFS_WQ_ENDIO_METADATA) {
688 wq = fs_info->endio_meta_write_workers;
689 func = btrfs_endio_meta_write_helper;
690 } else if (end_io_wq->metadata == BTRFS_WQ_ENDIO_FREE_SPACE) {
691 wq = fs_info->endio_freespace_worker;
692 func = btrfs_freespace_write_helper;
693 } else if (end_io_wq->metadata == BTRFS_WQ_ENDIO_RAID56) {
694 wq = fs_info->endio_raid56_workers;
695 func = btrfs_endio_raid56_helper;
697 wq = fs_info->endio_write_workers;
698 func = btrfs_endio_write_helper;
701 if (unlikely(end_io_wq->metadata ==
702 BTRFS_WQ_ENDIO_DIO_REPAIR)) {
703 wq = fs_info->endio_repair_workers;
704 func = btrfs_endio_repair_helper;
705 } else if (end_io_wq->metadata == BTRFS_WQ_ENDIO_RAID56) {
706 wq = fs_info->endio_raid56_workers;
707 func = btrfs_endio_raid56_helper;
708 } else if (end_io_wq->metadata) {
709 wq = fs_info->endio_meta_workers;
710 func = btrfs_endio_meta_helper;
712 wq = fs_info->endio_workers;
713 func = btrfs_endio_helper;
717 btrfs_init_work(&end_io_wq->work, func, end_workqueue_fn, NULL, NULL);
718 btrfs_queue_work(wq, &end_io_wq->work);
721 blk_status_t btrfs_bio_wq_end_io(struct btrfs_fs_info *info, struct bio *bio,
722 enum btrfs_wq_endio_type metadata)
724 struct btrfs_end_io_wq *end_io_wq;
726 end_io_wq = kmem_cache_alloc(btrfs_end_io_wq_cache, GFP_NOFS);
728 return BLK_STS_RESOURCE;
730 end_io_wq->private = bio->bi_private;
731 end_io_wq->end_io = bio->bi_end_io;
732 end_io_wq->info = info;
733 end_io_wq->status = 0;
734 end_io_wq->bio = bio;
735 end_io_wq->metadata = metadata;
737 bio->bi_private = end_io_wq;
738 bio->bi_end_io = end_workqueue_bio;
742 static void run_one_async_start(struct btrfs_work *work)
744 struct async_submit_bio *async;
747 async = container_of(work, struct async_submit_bio, work);
748 ret = async->submit_bio_start(async->private_data, async->bio,
754 static void run_one_async_done(struct btrfs_work *work)
756 struct async_submit_bio *async;
758 async = container_of(work, struct async_submit_bio, work);
760 /* If an error occurred we just want to clean up the bio and move on */
762 async->bio->bi_status = async->status;
763 bio_endio(async->bio);
767 btrfs_submit_bio_done(async->private_data, async->bio, async->mirror_num);
770 static void run_one_async_free(struct btrfs_work *work)
772 struct async_submit_bio *async;
774 async = container_of(work, struct async_submit_bio, work);
778 blk_status_t btrfs_wq_submit_bio(struct btrfs_fs_info *fs_info, struct bio *bio,
779 int mirror_num, unsigned long bio_flags,
780 u64 bio_offset, void *private_data,
781 extent_submit_bio_start_t *submit_bio_start)
783 struct async_submit_bio *async;
785 async = kmalloc(sizeof(*async), GFP_NOFS);
787 return BLK_STS_RESOURCE;
789 async->private_data = private_data;
791 async->mirror_num = mirror_num;
792 async->submit_bio_start = submit_bio_start;
794 btrfs_init_work(&async->work, btrfs_worker_helper, run_one_async_start,
795 run_one_async_done, run_one_async_free);
797 async->bio_offset = bio_offset;
801 if (op_is_sync(bio->bi_opf))
802 btrfs_set_work_high_priority(&async->work);
804 btrfs_queue_work(fs_info->workers, &async->work);
808 static blk_status_t btree_csum_one_bio(struct bio *bio)
810 struct bio_vec *bvec;
811 struct btrfs_root *root;
814 ASSERT(!bio_flagged(bio, BIO_CLONED));
815 bio_for_each_segment_all(bvec, bio, i) {
816 root = BTRFS_I(bvec->bv_page->mapping->host)->root;
817 ret = csum_dirty_buffer(root->fs_info, bvec->bv_page);
822 return errno_to_blk_status(ret);
825 static blk_status_t btree_submit_bio_start(void *private_data, struct bio *bio,
829 * when we're called for a write, we're already in the async
830 * submission context. Just jump into btrfs_map_bio
832 return btree_csum_one_bio(bio);
835 static int check_async_write(struct btrfs_inode *bi)
837 if (atomic_read(&bi->sync_writers))
840 if (static_cpu_has(X86_FEATURE_XMM4_2))
846 static blk_status_t btree_submit_bio_hook(void *private_data, struct bio *bio,
847 int mirror_num, unsigned long bio_flags,
850 struct inode *inode = private_data;
851 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
852 int async = check_async_write(BTRFS_I(inode));
855 if (bio_op(bio) != REQ_OP_WRITE) {
857 * called for a read, do the setup so that checksum validation
858 * can happen in the async kernel threads
860 ret = btrfs_bio_wq_end_io(fs_info, bio,
861 BTRFS_WQ_ENDIO_METADATA);
864 ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
866 ret = btree_csum_one_bio(bio);
869 ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
872 * kthread helpers are used to submit writes so that
873 * checksumming can happen in parallel across all CPUs
875 ret = btrfs_wq_submit_bio(fs_info, bio, mirror_num, 0,
876 bio_offset, private_data,
877 btree_submit_bio_start);
885 bio->bi_status = ret;
890 #ifdef CONFIG_MIGRATION
891 static int btree_migratepage(struct address_space *mapping,
892 struct page *newpage, struct page *page,
893 enum migrate_mode mode)
896 * we can't safely write a btree page from here,
897 * we haven't done the locking hook
902 * Buffers may be managed in a filesystem specific way.
903 * We must have no buffers or drop them.
905 if (page_has_private(page) &&
906 !try_to_release_page(page, GFP_KERNEL))
908 return migrate_page(mapping, newpage, page, mode);
913 static int btree_writepages(struct address_space *mapping,
914 struct writeback_control *wbc)
916 struct btrfs_fs_info *fs_info;
919 if (wbc->sync_mode == WB_SYNC_NONE) {
921 if (wbc->for_kupdate)
924 fs_info = BTRFS_I(mapping->host)->root->fs_info;
925 /* this is a bit racy, but that's ok */
926 ret = __percpu_counter_compare(&fs_info->dirty_metadata_bytes,
927 BTRFS_DIRTY_METADATA_THRESH,
928 fs_info->dirty_metadata_batch);
932 return btree_write_cache_pages(mapping, wbc);
935 static int btree_readpage(struct file *file, struct page *page)
937 struct extent_io_tree *tree;
938 tree = &BTRFS_I(page->mapping->host)->io_tree;
939 return extent_read_full_page(tree, page, btree_get_extent, 0);
942 static int btree_releasepage(struct page *page, gfp_t gfp_flags)
944 if (PageWriteback(page) || PageDirty(page))
947 return try_release_extent_buffer(page);
950 static void btree_invalidatepage(struct page *page, unsigned int offset,
953 struct extent_io_tree *tree;
954 tree = &BTRFS_I(page->mapping->host)->io_tree;
955 extent_invalidatepage(tree, page, offset);
956 btree_releasepage(page, GFP_NOFS);
957 if (PagePrivate(page)) {
958 btrfs_warn(BTRFS_I(page->mapping->host)->root->fs_info,
959 "page private not zero on page %llu",
960 (unsigned long long)page_offset(page));
961 ClearPagePrivate(page);
962 set_page_private(page, 0);
967 static int btree_set_page_dirty(struct page *page)
970 struct extent_buffer *eb;
972 BUG_ON(!PagePrivate(page));
973 eb = (struct extent_buffer *)page->private;
975 BUG_ON(!test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
976 BUG_ON(!atomic_read(&eb->refs));
977 btrfs_assert_tree_locked(eb);
979 return __set_page_dirty_nobuffers(page);
982 static const struct address_space_operations btree_aops = {
983 .readpage = btree_readpage,
984 .writepages = btree_writepages,
985 .releasepage = btree_releasepage,
986 .invalidatepage = btree_invalidatepage,
987 #ifdef CONFIG_MIGRATION
988 .migratepage = btree_migratepage,
990 .set_page_dirty = btree_set_page_dirty,
993 void readahead_tree_block(struct btrfs_fs_info *fs_info, u64 bytenr)
995 struct extent_buffer *buf = NULL;
996 struct inode *btree_inode = fs_info->btree_inode;
998 buf = btrfs_find_create_tree_block(fs_info, bytenr);
1001 read_extent_buffer_pages(&BTRFS_I(btree_inode)->io_tree,
1003 free_extent_buffer(buf);
1006 int reada_tree_block_flagged(struct btrfs_fs_info *fs_info, u64 bytenr,
1007 int mirror_num, struct extent_buffer **eb)
1009 struct extent_buffer *buf = NULL;
1010 struct inode *btree_inode = fs_info->btree_inode;
1011 struct extent_io_tree *io_tree = &BTRFS_I(btree_inode)->io_tree;
1014 buf = btrfs_find_create_tree_block(fs_info, bytenr);
1018 set_bit(EXTENT_BUFFER_READAHEAD, &buf->bflags);
1020 ret = read_extent_buffer_pages(io_tree, buf, WAIT_PAGE_LOCK,
1023 free_extent_buffer(buf);
1027 if (test_bit(EXTENT_BUFFER_CORRUPT, &buf->bflags)) {
1028 free_extent_buffer(buf);
1030 } else if (extent_buffer_uptodate(buf)) {
1033 free_extent_buffer(buf);
1038 struct extent_buffer *btrfs_find_create_tree_block(
1039 struct btrfs_fs_info *fs_info,
1042 if (btrfs_is_testing(fs_info))
1043 return alloc_test_extent_buffer(fs_info, bytenr);
1044 return alloc_extent_buffer(fs_info, bytenr);
1048 int btrfs_write_tree_block(struct extent_buffer *buf)
1050 return filemap_fdatawrite_range(buf->pages[0]->mapping, buf->start,
1051 buf->start + buf->len - 1);
1054 void btrfs_wait_tree_block_writeback(struct extent_buffer *buf)
1056 filemap_fdatawait_range(buf->pages[0]->mapping,
1057 buf->start, buf->start + buf->len - 1);
1061 * Read tree block at logical address @bytenr and do variant basic but critical
1064 * @parent_transid: expected transid of this tree block, skip check if 0
1065 * @level: expected level, mandatory check
1066 * @first_key: expected key in slot 0, skip check if NULL
1068 struct extent_buffer *read_tree_block(struct btrfs_fs_info *fs_info, u64 bytenr,
1069 u64 parent_transid, int level,
1070 struct btrfs_key *first_key)
1072 struct extent_buffer *buf = NULL;
1075 buf = btrfs_find_create_tree_block(fs_info, bytenr);
1079 ret = btree_read_extent_buffer_pages(fs_info, buf, parent_transid,
1082 free_extent_buffer(buf);
1083 return ERR_PTR(ret);
1089 void clean_tree_block(struct btrfs_fs_info *fs_info,
1090 struct extent_buffer *buf)
1092 if (btrfs_header_generation(buf) ==
1093 fs_info->running_transaction->transid) {
1094 btrfs_assert_tree_locked(buf);
1096 if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &buf->bflags)) {
1097 percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
1099 fs_info->dirty_metadata_batch);
1100 /* ugh, clear_extent_buffer_dirty needs to lock the page */
1101 btrfs_set_lock_blocking(buf);
1102 clear_extent_buffer_dirty(buf);
1107 static struct btrfs_subvolume_writers *btrfs_alloc_subvolume_writers(void)
1109 struct btrfs_subvolume_writers *writers;
1112 writers = kmalloc(sizeof(*writers), GFP_NOFS);
1114 return ERR_PTR(-ENOMEM);
1116 ret = percpu_counter_init(&writers->counter, 0, GFP_NOFS);
1119 return ERR_PTR(ret);
1122 init_waitqueue_head(&writers->wait);
1127 btrfs_free_subvolume_writers(struct btrfs_subvolume_writers *writers)
1129 percpu_counter_destroy(&writers->counter);
1133 static void __setup_root(struct btrfs_root *root, struct btrfs_fs_info *fs_info,
1136 bool dummy = test_bit(BTRFS_FS_STATE_DUMMY_FS_INFO, &fs_info->fs_state);
1138 root->commit_root = NULL;
1140 root->orphan_cleanup_state = 0;
1142 root->objectid = objectid;
1143 root->last_trans = 0;
1144 root->highest_objectid = 0;
1145 root->nr_delalloc_inodes = 0;
1146 root->nr_ordered_extents = 0;
1147 root->inode_tree = RB_ROOT;
1148 INIT_RADIX_TREE(&root->delayed_nodes_tree, GFP_ATOMIC);
1149 root->block_rsv = NULL;
1151 INIT_LIST_HEAD(&root->dirty_list);
1152 INIT_LIST_HEAD(&root->root_list);
1153 INIT_LIST_HEAD(&root->delalloc_inodes);
1154 INIT_LIST_HEAD(&root->delalloc_root);
1155 INIT_LIST_HEAD(&root->ordered_extents);
1156 INIT_LIST_HEAD(&root->ordered_root);
1157 INIT_LIST_HEAD(&root->logged_list[0]);
1158 INIT_LIST_HEAD(&root->logged_list[1]);
1159 spin_lock_init(&root->inode_lock);
1160 spin_lock_init(&root->delalloc_lock);
1161 spin_lock_init(&root->ordered_extent_lock);
1162 spin_lock_init(&root->accounting_lock);
1163 spin_lock_init(&root->log_extents_lock[0]);
1164 spin_lock_init(&root->log_extents_lock[1]);
1165 spin_lock_init(&root->qgroup_meta_rsv_lock);
1166 mutex_init(&root->objectid_mutex);
1167 mutex_init(&root->log_mutex);
1168 mutex_init(&root->ordered_extent_mutex);
1169 mutex_init(&root->delalloc_mutex);
1170 init_waitqueue_head(&root->log_writer_wait);
1171 init_waitqueue_head(&root->log_commit_wait[0]);
1172 init_waitqueue_head(&root->log_commit_wait[1]);
1173 INIT_LIST_HEAD(&root->log_ctxs[0]);
1174 INIT_LIST_HEAD(&root->log_ctxs[1]);
1175 atomic_set(&root->log_commit[0], 0);
1176 atomic_set(&root->log_commit[1], 0);
1177 atomic_set(&root->log_writers, 0);
1178 atomic_set(&root->log_batch, 0);
1179 refcount_set(&root->refs, 1);
1180 atomic_set(&root->will_be_snapshotted, 0);
1181 atomic_set(&root->snapshot_force_cow, 0);
1182 root->log_transid = 0;
1183 root->log_transid_committed = -1;
1184 root->last_log_commit = 0;
1186 extent_io_tree_init(&root->dirty_log_pages, NULL);
1188 memset(&root->root_key, 0, sizeof(root->root_key));
1189 memset(&root->root_item, 0, sizeof(root->root_item));
1190 memset(&root->defrag_progress, 0, sizeof(root->defrag_progress));
1192 root->defrag_trans_start = fs_info->generation;
1194 root->defrag_trans_start = 0;
1195 root->root_key.objectid = objectid;
1198 spin_lock_init(&root->root_item_lock);
1201 static struct btrfs_root *btrfs_alloc_root(struct btrfs_fs_info *fs_info,
1204 struct btrfs_root *root = kzalloc(sizeof(*root), flags);
1206 root->fs_info = fs_info;
1210 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
1211 /* Should only be used by the testing infrastructure */
1212 struct btrfs_root *btrfs_alloc_dummy_root(struct btrfs_fs_info *fs_info)
1214 struct btrfs_root *root;
1217 return ERR_PTR(-EINVAL);
1219 root = btrfs_alloc_root(fs_info, GFP_KERNEL);
1221 return ERR_PTR(-ENOMEM);
1223 /* We don't use the stripesize in selftest, set it as sectorsize */
1224 __setup_root(root, fs_info, BTRFS_ROOT_TREE_OBJECTID);
1225 root->alloc_bytenr = 0;
1231 struct btrfs_root *btrfs_create_tree(struct btrfs_trans_handle *trans,
1232 struct btrfs_fs_info *fs_info,
1235 struct extent_buffer *leaf;
1236 struct btrfs_root *tree_root = fs_info->tree_root;
1237 struct btrfs_root *root;
1238 struct btrfs_key key;
1240 uuid_le uuid = NULL_UUID_LE;
1242 root = btrfs_alloc_root(fs_info, GFP_KERNEL);
1244 return ERR_PTR(-ENOMEM);
1246 __setup_root(root, fs_info, objectid);
1247 root->root_key.objectid = objectid;
1248 root->root_key.type = BTRFS_ROOT_ITEM_KEY;
1249 root->root_key.offset = 0;
1251 leaf = btrfs_alloc_tree_block(trans, root, 0, objectid, NULL, 0, 0, 0);
1253 ret = PTR_ERR(leaf);
1259 btrfs_mark_buffer_dirty(leaf);
1261 root->commit_root = btrfs_root_node(root);
1262 set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
1264 root->root_item.flags = 0;
1265 root->root_item.byte_limit = 0;
1266 btrfs_set_root_bytenr(&root->root_item, leaf->start);
1267 btrfs_set_root_generation(&root->root_item, trans->transid);
1268 btrfs_set_root_level(&root->root_item, 0);
1269 btrfs_set_root_refs(&root->root_item, 1);
1270 btrfs_set_root_used(&root->root_item, leaf->len);
1271 btrfs_set_root_last_snapshot(&root->root_item, 0);
1272 btrfs_set_root_dirid(&root->root_item, 0);
1273 if (is_fstree(objectid))
1275 memcpy(root->root_item.uuid, uuid.b, BTRFS_UUID_SIZE);
1276 root->root_item.drop_level = 0;
1278 key.objectid = objectid;
1279 key.type = BTRFS_ROOT_ITEM_KEY;
1281 ret = btrfs_insert_root(trans, tree_root, &key, &root->root_item);
1285 btrfs_tree_unlock(leaf);
1291 btrfs_tree_unlock(leaf);
1292 free_extent_buffer(root->commit_root);
1293 free_extent_buffer(leaf);
1297 return ERR_PTR(ret);
1300 static struct btrfs_root *alloc_log_tree(struct btrfs_trans_handle *trans,
1301 struct btrfs_fs_info *fs_info)
1303 struct btrfs_root *root;
1304 struct extent_buffer *leaf;
1306 root = btrfs_alloc_root(fs_info, GFP_NOFS);
1308 return ERR_PTR(-ENOMEM);
1310 __setup_root(root, fs_info, BTRFS_TREE_LOG_OBJECTID);
1312 root->root_key.objectid = BTRFS_TREE_LOG_OBJECTID;
1313 root->root_key.type = BTRFS_ROOT_ITEM_KEY;
1314 root->root_key.offset = BTRFS_TREE_LOG_OBJECTID;
1317 * DON'T set REF_COWS for log trees
1319 * log trees do not get reference counted because they go away
1320 * before a real commit is actually done. They do store pointers
1321 * to file data extents, and those reference counts still get
1322 * updated (along with back refs to the log tree).
1325 leaf = btrfs_alloc_tree_block(trans, root, 0, BTRFS_TREE_LOG_OBJECTID,
1329 return ERR_CAST(leaf);
1334 btrfs_mark_buffer_dirty(root->node);
1335 btrfs_tree_unlock(root->node);
1339 int btrfs_init_log_root_tree(struct btrfs_trans_handle *trans,
1340 struct btrfs_fs_info *fs_info)
1342 struct btrfs_root *log_root;
1344 log_root = alloc_log_tree(trans, fs_info);
1345 if (IS_ERR(log_root))
1346 return PTR_ERR(log_root);
1347 WARN_ON(fs_info->log_root_tree);
1348 fs_info->log_root_tree = log_root;
1352 int btrfs_add_log_tree(struct btrfs_trans_handle *trans,
1353 struct btrfs_root *root)
1355 struct btrfs_fs_info *fs_info = root->fs_info;
1356 struct btrfs_root *log_root;
1357 struct btrfs_inode_item *inode_item;
1359 log_root = alloc_log_tree(trans, fs_info);
1360 if (IS_ERR(log_root))
1361 return PTR_ERR(log_root);
1363 log_root->last_trans = trans->transid;
1364 log_root->root_key.offset = root->root_key.objectid;
1366 inode_item = &log_root->root_item.inode;
1367 btrfs_set_stack_inode_generation(inode_item, 1);
1368 btrfs_set_stack_inode_size(inode_item, 3);
1369 btrfs_set_stack_inode_nlink(inode_item, 1);
1370 btrfs_set_stack_inode_nbytes(inode_item,
1372 btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
1374 btrfs_set_root_node(&log_root->root_item, log_root->node);
1376 WARN_ON(root->log_root);
1377 root->log_root = log_root;
1378 root->log_transid = 0;
1379 root->log_transid_committed = -1;
1380 root->last_log_commit = 0;
1384 static struct btrfs_root *btrfs_read_tree_root(struct btrfs_root *tree_root,
1385 struct btrfs_key *key)
1387 struct btrfs_root *root;
1388 struct btrfs_fs_info *fs_info = tree_root->fs_info;
1389 struct btrfs_path *path;
1394 path = btrfs_alloc_path();
1396 return ERR_PTR(-ENOMEM);
1398 root = btrfs_alloc_root(fs_info, GFP_NOFS);
1404 __setup_root(root, fs_info, key->objectid);
1406 ret = btrfs_find_root(tree_root, key, path,
1407 &root->root_item, &root->root_key);
1414 generation = btrfs_root_generation(&root->root_item);
1415 level = btrfs_root_level(&root->root_item);
1416 root->node = read_tree_block(fs_info,
1417 btrfs_root_bytenr(&root->root_item),
1418 generation, level, NULL);
1419 if (IS_ERR(root->node)) {
1420 ret = PTR_ERR(root->node);
1422 } else if (!btrfs_buffer_uptodate(root->node, generation, 0)) {
1424 free_extent_buffer(root->node);
1427 root->commit_root = btrfs_root_node(root);
1429 btrfs_free_path(path);
1435 root = ERR_PTR(ret);
1439 struct btrfs_root *btrfs_read_fs_root(struct btrfs_root *tree_root,
1440 struct btrfs_key *location)
1442 struct btrfs_root *root;
1444 root = btrfs_read_tree_root(tree_root, location);
1448 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
1449 set_bit(BTRFS_ROOT_REF_COWS, &root->state);
1450 btrfs_check_and_init_root_item(&root->root_item);
1456 int btrfs_init_fs_root(struct btrfs_root *root)
1459 struct btrfs_subvolume_writers *writers;
1461 root->free_ino_ctl = kzalloc(sizeof(*root->free_ino_ctl), GFP_NOFS);
1462 root->free_ino_pinned = kzalloc(sizeof(*root->free_ino_pinned),
1464 if (!root->free_ino_pinned || !root->free_ino_ctl) {
1469 writers = btrfs_alloc_subvolume_writers();
1470 if (IS_ERR(writers)) {
1471 ret = PTR_ERR(writers);
1474 root->subv_writers = writers;
1476 btrfs_init_free_ino_ctl(root);
1477 spin_lock_init(&root->ino_cache_lock);
1478 init_waitqueue_head(&root->ino_cache_wait);
1480 ret = get_anon_bdev(&root->anon_dev);
1484 mutex_lock(&root->objectid_mutex);
1485 ret = btrfs_find_highest_objectid(root,
1486 &root->highest_objectid);
1488 mutex_unlock(&root->objectid_mutex);
1492 ASSERT(root->highest_objectid <= BTRFS_LAST_FREE_OBJECTID);
1494 mutex_unlock(&root->objectid_mutex);
1498 /* The caller is responsible to call btrfs_free_fs_root */
1502 struct btrfs_root *btrfs_lookup_fs_root(struct btrfs_fs_info *fs_info,
1505 struct btrfs_root *root;
1507 spin_lock(&fs_info->fs_roots_radix_lock);
1508 root = radix_tree_lookup(&fs_info->fs_roots_radix,
1509 (unsigned long)root_id);
1510 spin_unlock(&fs_info->fs_roots_radix_lock);
1514 int btrfs_insert_fs_root(struct btrfs_fs_info *fs_info,
1515 struct btrfs_root *root)
1519 ret = radix_tree_preload(GFP_NOFS);
1523 spin_lock(&fs_info->fs_roots_radix_lock);
1524 ret = radix_tree_insert(&fs_info->fs_roots_radix,
1525 (unsigned long)root->root_key.objectid,
1528 set_bit(BTRFS_ROOT_IN_RADIX, &root->state);
1529 spin_unlock(&fs_info->fs_roots_radix_lock);
1530 radix_tree_preload_end();
1535 struct btrfs_root *btrfs_get_fs_root(struct btrfs_fs_info *fs_info,
1536 struct btrfs_key *location,
1539 struct btrfs_root *root;
1540 struct btrfs_path *path;
1541 struct btrfs_key key;
1544 if (location->objectid == BTRFS_ROOT_TREE_OBJECTID)
1545 return fs_info->tree_root;
1546 if (location->objectid == BTRFS_EXTENT_TREE_OBJECTID)
1547 return fs_info->extent_root;
1548 if (location->objectid == BTRFS_CHUNK_TREE_OBJECTID)
1549 return fs_info->chunk_root;
1550 if (location->objectid == BTRFS_DEV_TREE_OBJECTID)
1551 return fs_info->dev_root;
1552 if (location->objectid == BTRFS_CSUM_TREE_OBJECTID)
1553 return fs_info->csum_root;
1554 if (location->objectid == BTRFS_QUOTA_TREE_OBJECTID)
1555 return fs_info->quota_root ? fs_info->quota_root :
1557 if (location->objectid == BTRFS_UUID_TREE_OBJECTID)
1558 return fs_info->uuid_root ? fs_info->uuid_root :
1560 if (location->objectid == BTRFS_FREE_SPACE_TREE_OBJECTID)
1561 return fs_info->free_space_root ? fs_info->free_space_root :
1564 root = btrfs_lookup_fs_root(fs_info, location->objectid);
1566 if (check_ref && btrfs_root_refs(&root->root_item) == 0)
1567 return ERR_PTR(-ENOENT);
1571 root = btrfs_read_fs_root(fs_info->tree_root, location);
1575 if (check_ref && btrfs_root_refs(&root->root_item) == 0) {
1580 ret = btrfs_init_fs_root(root);
1584 path = btrfs_alloc_path();
1589 key.objectid = BTRFS_ORPHAN_OBJECTID;
1590 key.type = BTRFS_ORPHAN_ITEM_KEY;
1591 key.offset = location->objectid;
1593 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
1594 btrfs_free_path(path);
1598 set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state);
1600 ret = btrfs_insert_fs_root(fs_info, root);
1602 if (ret == -EEXIST) {
1603 btrfs_free_fs_root(root);
1610 btrfs_free_fs_root(root);
1611 return ERR_PTR(ret);
1614 static int btrfs_congested_fn(void *congested_data, int bdi_bits)
1616 struct btrfs_fs_info *info = (struct btrfs_fs_info *)congested_data;
1618 struct btrfs_device *device;
1619 struct backing_dev_info *bdi;
1622 list_for_each_entry_rcu(device, &info->fs_devices->devices, dev_list) {
1625 bdi = device->bdev->bd_bdi;
1626 if (bdi_congested(bdi, bdi_bits)) {
1636 * called by the kthread helper functions to finally call the bio end_io
1637 * functions. This is where read checksum verification actually happens
1639 static void end_workqueue_fn(struct btrfs_work *work)
1642 struct btrfs_end_io_wq *end_io_wq;
1644 end_io_wq = container_of(work, struct btrfs_end_io_wq, work);
1645 bio = end_io_wq->bio;
1647 bio->bi_status = end_io_wq->status;
1648 bio->bi_private = end_io_wq->private;
1649 bio->bi_end_io = end_io_wq->end_io;
1650 kmem_cache_free(btrfs_end_io_wq_cache, end_io_wq);
1654 static int cleaner_kthread(void *arg)
1656 struct btrfs_root *root = arg;
1657 struct btrfs_fs_info *fs_info = root->fs_info;
1659 struct btrfs_trans_handle *trans;
1664 /* Make the cleaner go to sleep early. */
1665 if (btrfs_need_cleaner_sleep(fs_info))
1669 * Do not do anything if we might cause open_ctree() to block
1670 * before we have finished mounting the filesystem.
1672 if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
1675 if (!mutex_trylock(&fs_info->cleaner_mutex))
1679 * Avoid the problem that we change the status of the fs
1680 * during the above check and trylock.
1682 if (btrfs_need_cleaner_sleep(fs_info)) {
1683 mutex_unlock(&fs_info->cleaner_mutex);
1687 mutex_lock(&fs_info->cleaner_delayed_iput_mutex);
1688 btrfs_run_delayed_iputs(fs_info);
1689 mutex_unlock(&fs_info->cleaner_delayed_iput_mutex);
1691 again = btrfs_clean_one_deleted_snapshot(root);
1692 mutex_unlock(&fs_info->cleaner_mutex);
1695 * The defragger has dealt with the R/O remount and umount,
1696 * needn't do anything special here.
1698 btrfs_run_defrag_inodes(fs_info);
1701 * Acquires fs_info->delete_unused_bgs_mutex to avoid racing
1702 * with relocation (btrfs_relocate_chunk) and relocation
1703 * acquires fs_info->cleaner_mutex (btrfs_relocate_block_group)
1704 * after acquiring fs_info->delete_unused_bgs_mutex. So we
1705 * can't hold, nor need to, fs_info->cleaner_mutex when deleting
1706 * unused block groups.
1708 btrfs_delete_unused_bgs(fs_info);
1711 set_current_state(TASK_INTERRUPTIBLE);
1712 if (!kthread_should_stop())
1714 __set_current_state(TASK_RUNNING);
1716 } while (!kthread_should_stop());
1719 * Transaction kthread is stopped before us and wakes us up.
1720 * However we might have started a new transaction and COWed some
1721 * tree blocks when deleting unused block groups for example. So
1722 * make sure we commit the transaction we started to have a clean
1723 * shutdown when evicting the btree inode - if it has dirty pages
1724 * when we do the final iput() on it, eviction will trigger a
1725 * writeback for it which will fail with null pointer dereferences
1726 * since work queues and other resources were already released and
1727 * destroyed by the time the iput/eviction/writeback is made.
1729 trans = btrfs_attach_transaction(root);
1730 if (IS_ERR(trans)) {
1731 if (PTR_ERR(trans) != -ENOENT)
1733 "cleaner transaction attach returned %ld",
1738 ret = btrfs_commit_transaction(trans);
1741 "cleaner open transaction commit returned %d",
1748 static int transaction_kthread(void *arg)
1750 struct btrfs_root *root = arg;
1751 struct btrfs_fs_info *fs_info = root->fs_info;
1752 struct btrfs_trans_handle *trans;
1753 struct btrfs_transaction *cur;
1756 unsigned long delay;
1760 cannot_commit = false;
1761 delay = HZ * fs_info->commit_interval;
1762 mutex_lock(&fs_info->transaction_kthread_mutex);
1764 spin_lock(&fs_info->trans_lock);
1765 cur = fs_info->running_transaction;
1767 spin_unlock(&fs_info->trans_lock);
1771 now = ktime_get_seconds();
1772 if (cur->state < TRANS_STATE_BLOCKED &&
1773 !test_bit(BTRFS_FS_NEED_ASYNC_COMMIT, &fs_info->flags) &&
1774 (now < cur->start_time ||
1775 now - cur->start_time < fs_info->commit_interval)) {
1776 spin_unlock(&fs_info->trans_lock);
1780 transid = cur->transid;
1781 spin_unlock(&fs_info->trans_lock);
1783 /* If the file system is aborted, this will always fail. */
1784 trans = btrfs_attach_transaction(root);
1785 if (IS_ERR(trans)) {
1786 if (PTR_ERR(trans) != -ENOENT)
1787 cannot_commit = true;
1790 if (transid == trans->transid) {
1791 btrfs_commit_transaction(trans);
1793 btrfs_end_transaction(trans);
1796 wake_up_process(fs_info->cleaner_kthread);
1797 mutex_unlock(&fs_info->transaction_kthread_mutex);
1799 if (unlikely(test_bit(BTRFS_FS_STATE_ERROR,
1800 &fs_info->fs_state)))
1801 btrfs_cleanup_transaction(fs_info);
1802 if (!kthread_should_stop() &&
1803 (!btrfs_transaction_blocked(fs_info) ||
1805 schedule_timeout_interruptible(delay);
1806 } while (!kthread_should_stop());
1811 * this will find the highest generation in the array of
1812 * root backups. The index of the highest array is returned,
1813 * or -1 if we can't find anything.
1815 * We check to make sure the array is valid by comparing the
1816 * generation of the latest root in the array with the generation
1817 * in the super block. If they don't match we pitch it.
1819 static int find_newest_super_backup(struct btrfs_fs_info *info, u64 newest_gen)
1822 int newest_index = -1;
1823 struct btrfs_root_backup *root_backup;
1826 for (i = 0; i < BTRFS_NUM_BACKUP_ROOTS; i++) {
1827 root_backup = info->super_copy->super_roots + i;
1828 cur = btrfs_backup_tree_root_gen(root_backup);
1829 if (cur == newest_gen)
1833 /* check to see if we actually wrapped around */
1834 if (newest_index == BTRFS_NUM_BACKUP_ROOTS - 1) {
1835 root_backup = info->super_copy->super_roots;
1836 cur = btrfs_backup_tree_root_gen(root_backup);
1837 if (cur == newest_gen)
1840 return newest_index;
1845 * find the oldest backup so we know where to store new entries
1846 * in the backup array. This will set the backup_root_index
1847 * field in the fs_info struct
1849 static void find_oldest_super_backup(struct btrfs_fs_info *info,
1852 int newest_index = -1;
1854 newest_index = find_newest_super_backup(info, newest_gen);
1855 /* if there was garbage in there, just move along */
1856 if (newest_index == -1) {
1857 info->backup_root_index = 0;
1859 info->backup_root_index = (newest_index + 1) % BTRFS_NUM_BACKUP_ROOTS;
1864 * copy all the root pointers into the super backup array.
1865 * this will bump the backup pointer by one when it is
1868 static void backup_super_roots(struct btrfs_fs_info *info)
1871 struct btrfs_root_backup *root_backup;
1874 next_backup = info->backup_root_index;
1875 last_backup = (next_backup + BTRFS_NUM_BACKUP_ROOTS - 1) %
1876 BTRFS_NUM_BACKUP_ROOTS;
1879 * just overwrite the last backup if we're at the same generation
1880 * this happens only at umount
1882 root_backup = info->super_for_commit->super_roots + last_backup;
1883 if (btrfs_backup_tree_root_gen(root_backup) ==
1884 btrfs_header_generation(info->tree_root->node))
1885 next_backup = last_backup;
1887 root_backup = info->super_for_commit->super_roots + next_backup;
1890 * make sure all of our padding and empty slots get zero filled
1891 * regardless of which ones we use today
1893 memset(root_backup, 0, sizeof(*root_backup));
1895 info->backup_root_index = (next_backup + 1) % BTRFS_NUM_BACKUP_ROOTS;
1897 btrfs_set_backup_tree_root(root_backup, info->tree_root->node->start);
1898 btrfs_set_backup_tree_root_gen(root_backup,
1899 btrfs_header_generation(info->tree_root->node));
1901 btrfs_set_backup_tree_root_level(root_backup,
1902 btrfs_header_level(info->tree_root->node));
1904 btrfs_set_backup_chunk_root(root_backup, info->chunk_root->node->start);
1905 btrfs_set_backup_chunk_root_gen(root_backup,
1906 btrfs_header_generation(info->chunk_root->node));
1907 btrfs_set_backup_chunk_root_level(root_backup,
1908 btrfs_header_level(info->chunk_root->node));
1910 btrfs_set_backup_extent_root(root_backup, info->extent_root->node->start);
1911 btrfs_set_backup_extent_root_gen(root_backup,
1912 btrfs_header_generation(info->extent_root->node));
1913 btrfs_set_backup_extent_root_level(root_backup,
1914 btrfs_header_level(info->extent_root->node));
1917 * we might commit during log recovery, which happens before we set
1918 * the fs_root. Make sure it is valid before we fill it in.
1920 if (info->fs_root && info->fs_root->node) {
1921 btrfs_set_backup_fs_root(root_backup,
1922 info->fs_root->node->start);
1923 btrfs_set_backup_fs_root_gen(root_backup,
1924 btrfs_header_generation(info->fs_root->node));
1925 btrfs_set_backup_fs_root_level(root_backup,
1926 btrfs_header_level(info->fs_root->node));
1929 btrfs_set_backup_dev_root(root_backup, info->dev_root->node->start);
1930 btrfs_set_backup_dev_root_gen(root_backup,
1931 btrfs_header_generation(info->dev_root->node));
1932 btrfs_set_backup_dev_root_level(root_backup,
1933 btrfs_header_level(info->dev_root->node));
1935 btrfs_set_backup_csum_root(root_backup, info->csum_root->node->start);
1936 btrfs_set_backup_csum_root_gen(root_backup,
1937 btrfs_header_generation(info->csum_root->node));
1938 btrfs_set_backup_csum_root_level(root_backup,
1939 btrfs_header_level(info->csum_root->node));
1941 btrfs_set_backup_total_bytes(root_backup,
1942 btrfs_super_total_bytes(info->super_copy));
1943 btrfs_set_backup_bytes_used(root_backup,
1944 btrfs_super_bytes_used(info->super_copy));
1945 btrfs_set_backup_num_devices(root_backup,
1946 btrfs_super_num_devices(info->super_copy));
1949 * if we don't copy this out to the super_copy, it won't get remembered
1950 * for the next commit
1952 memcpy(&info->super_copy->super_roots,
1953 &info->super_for_commit->super_roots,
1954 sizeof(*root_backup) * BTRFS_NUM_BACKUP_ROOTS);
1958 * this copies info out of the root backup array and back into
1959 * the in-memory super block. It is meant to help iterate through
1960 * the array, so you send it the number of backups you've already
1961 * tried and the last backup index you used.
1963 * this returns -1 when it has tried all the backups
1965 static noinline int next_root_backup(struct btrfs_fs_info *info,
1966 struct btrfs_super_block *super,
1967 int *num_backups_tried, int *backup_index)
1969 struct btrfs_root_backup *root_backup;
1970 int newest = *backup_index;
1972 if (*num_backups_tried == 0) {
1973 u64 gen = btrfs_super_generation(super);
1975 newest = find_newest_super_backup(info, gen);
1979 *backup_index = newest;
1980 *num_backups_tried = 1;
1981 } else if (*num_backups_tried == BTRFS_NUM_BACKUP_ROOTS) {
1982 /* we've tried all the backups, all done */
1985 /* jump to the next oldest backup */
1986 newest = (*backup_index + BTRFS_NUM_BACKUP_ROOTS - 1) %
1987 BTRFS_NUM_BACKUP_ROOTS;
1988 *backup_index = newest;
1989 *num_backups_tried += 1;
1991 root_backup = super->super_roots + newest;
1993 btrfs_set_super_generation(super,
1994 btrfs_backup_tree_root_gen(root_backup));
1995 btrfs_set_super_root(super, btrfs_backup_tree_root(root_backup));
1996 btrfs_set_super_root_level(super,
1997 btrfs_backup_tree_root_level(root_backup));
1998 btrfs_set_super_bytes_used(super, btrfs_backup_bytes_used(root_backup));
2001 * fixme: the total bytes and num_devices need to match or we should
2004 btrfs_set_super_total_bytes(super, btrfs_backup_total_bytes(root_backup));
2005 btrfs_set_super_num_devices(super, btrfs_backup_num_devices(root_backup));
2009 /* helper to cleanup workers */
2010 static void btrfs_stop_all_workers(struct btrfs_fs_info *fs_info)
2012 btrfs_destroy_workqueue(fs_info->fixup_workers);
2013 btrfs_destroy_workqueue(fs_info->delalloc_workers);
2014 btrfs_destroy_workqueue(fs_info->workers);
2015 btrfs_destroy_workqueue(fs_info->endio_workers);
2016 btrfs_destroy_workqueue(fs_info->endio_raid56_workers);
2017 btrfs_destroy_workqueue(fs_info->endio_repair_workers);
2018 btrfs_destroy_workqueue(fs_info->rmw_workers);
2019 btrfs_destroy_workqueue(fs_info->endio_write_workers);
2020 btrfs_destroy_workqueue(fs_info->endio_freespace_worker);
2021 btrfs_destroy_workqueue(fs_info->submit_workers);
2022 btrfs_destroy_workqueue(fs_info->delayed_workers);
2023 btrfs_destroy_workqueue(fs_info->caching_workers);
2024 btrfs_destroy_workqueue(fs_info->readahead_workers);
2025 btrfs_destroy_workqueue(fs_info->flush_workers);
2026 btrfs_destroy_workqueue(fs_info->qgroup_rescan_workers);
2027 btrfs_destroy_workqueue(fs_info->extent_workers);
2029 * Now that all other work queues are destroyed, we can safely destroy
2030 * the queues used for metadata I/O, since tasks from those other work
2031 * queues can do metadata I/O operations.
2033 btrfs_destroy_workqueue(fs_info->endio_meta_workers);
2034 btrfs_destroy_workqueue(fs_info->endio_meta_write_workers);
2037 static void free_root_extent_buffers(struct btrfs_root *root)
2040 free_extent_buffer(root->node);
2041 free_extent_buffer(root->commit_root);
2043 root->commit_root = NULL;
2047 /* helper to cleanup tree roots */
2048 static void free_root_pointers(struct btrfs_fs_info *info, int chunk_root)
2050 free_root_extent_buffers(info->tree_root);
2052 free_root_extent_buffers(info->dev_root);
2053 free_root_extent_buffers(info->extent_root);
2054 free_root_extent_buffers(info->csum_root);
2055 free_root_extent_buffers(info->quota_root);
2056 free_root_extent_buffers(info->uuid_root);
2058 free_root_extent_buffers(info->chunk_root);
2059 free_root_extent_buffers(info->free_space_root);
2062 void btrfs_free_fs_roots(struct btrfs_fs_info *fs_info)
2065 struct btrfs_root *gang[8];
2068 while (!list_empty(&fs_info->dead_roots)) {
2069 gang[0] = list_entry(fs_info->dead_roots.next,
2070 struct btrfs_root, root_list);
2071 list_del(&gang[0]->root_list);
2073 if (test_bit(BTRFS_ROOT_IN_RADIX, &gang[0]->state)) {
2074 btrfs_drop_and_free_fs_root(fs_info, gang[0]);
2076 free_extent_buffer(gang[0]->node);
2077 free_extent_buffer(gang[0]->commit_root);
2078 btrfs_put_fs_root(gang[0]);
2083 ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
2088 for (i = 0; i < ret; i++)
2089 btrfs_drop_and_free_fs_root(fs_info, gang[i]);
2092 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {
2093 btrfs_free_log_root_tree(NULL, fs_info);
2094 btrfs_destroy_pinned_extent(fs_info, fs_info->pinned_extents);
2098 static void btrfs_init_scrub(struct btrfs_fs_info *fs_info)
2100 mutex_init(&fs_info->scrub_lock);
2101 atomic_set(&fs_info->scrubs_running, 0);
2102 atomic_set(&fs_info->scrub_pause_req, 0);
2103 atomic_set(&fs_info->scrubs_paused, 0);
2104 atomic_set(&fs_info->scrub_cancel_req, 0);
2105 init_waitqueue_head(&fs_info->scrub_pause_wait);
2106 fs_info->scrub_workers_refcnt = 0;
2109 static void btrfs_init_balance(struct btrfs_fs_info *fs_info)
2111 spin_lock_init(&fs_info->balance_lock);
2112 mutex_init(&fs_info->balance_mutex);
2113 atomic_set(&fs_info->balance_pause_req, 0);
2114 atomic_set(&fs_info->balance_cancel_req, 0);
2115 fs_info->balance_ctl = NULL;
2116 init_waitqueue_head(&fs_info->balance_wait_q);
2119 static void btrfs_init_btree_inode(struct btrfs_fs_info *fs_info)
2121 struct inode *inode = fs_info->btree_inode;
2123 inode->i_ino = BTRFS_BTREE_INODE_OBJECTID;
2124 set_nlink(inode, 1);
2126 * we set the i_size on the btree inode to the max possible int.
2127 * the real end of the address space is determined by all of
2128 * the devices in the system
2130 inode->i_size = OFFSET_MAX;
2131 inode->i_mapping->a_ops = &btree_aops;
2133 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
2134 extent_io_tree_init(&BTRFS_I(inode)->io_tree, inode);
2135 BTRFS_I(inode)->io_tree.track_uptodate = 0;
2136 extent_map_tree_init(&BTRFS_I(inode)->extent_tree);
2138 BTRFS_I(inode)->io_tree.ops = &btree_extent_io_ops;
2140 BTRFS_I(inode)->root = fs_info->tree_root;
2141 memset(&BTRFS_I(inode)->location, 0, sizeof(struct btrfs_key));
2142 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
2143 btrfs_insert_inode_hash(inode);
2146 static void btrfs_init_dev_replace_locks(struct btrfs_fs_info *fs_info)
2148 mutex_init(&fs_info->dev_replace.lock_finishing_cancel_unmount);
2149 rwlock_init(&fs_info->dev_replace.lock);
2150 atomic_set(&fs_info->dev_replace.read_locks, 0);
2151 atomic_set(&fs_info->dev_replace.blocking_readers, 0);
2152 init_waitqueue_head(&fs_info->replace_wait);
2153 init_waitqueue_head(&fs_info->dev_replace.read_lock_wq);
2156 static void btrfs_init_qgroup(struct btrfs_fs_info *fs_info)
2158 spin_lock_init(&fs_info->qgroup_lock);
2159 mutex_init(&fs_info->qgroup_ioctl_lock);
2160 fs_info->qgroup_tree = RB_ROOT;
2161 fs_info->qgroup_op_tree = RB_ROOT;
2162 INIT_LIST_HEAD(&fs_info->dirty_qgroups);
2163 fs_info->qgroup_seq = 1;
2164 fs_info->qgroup_ulist = NULL;
2165 fs_info->qgroup_rescan_running = false;
2166 mutex_init(&fs_info->qgroup_rescan_lock);
2169 static int btrfs_init_workqueues(struct btrfs_fs_info *fs_info,
2170 struct btrfs_fs_devices *fs_devices)
2172 u32 max_active = fs_info->thread_pool_size;
2173 unsigned int flags = WQ_MEM_RECLAIM | WQ_FREEZABLE | WQ_UNBOUND;
2176 btrfs_alloc_workqueue(fs_info, "worker",
2177 flags | WQ_HIGHPRI, max_active, 16);
2179 fs_info->delalloc_workers =
2180 btrfs_alloc_workqueue(fs_info, "delalloc",
2181 flags, max_active, 2);
2183 fs_info->flush_workers =
2184 btrfs_alloc_workqueue(fs_info, "flush_delalloc",
2185 flags, max_active, 0);
2187 fs_info->caching_workers =
2188 btrfs_alloc_workqueue(fs_info, "cache", flags, max_active, 0);
2191 * a higher idle thresh on the submit workers makes it much more
2192 * likely that bios will be send down in a sane order to the
2195 fs_info->submit_workers =
2196 btrfs_alloc_workqueue(fs_info, "submit", flags,
2197 min_t(u64, fs_devices->num_devices,
2200 fs_info->fixup_workers =
2201 btrfs_alloc_workqueue(fs_info, "fixup", flags, 1, 0);
2204 * endios are largely parallel and should have a very
2207 fs_info->endio_workers =
2208 btrfs_alloc_workqueue(fs_info, "endio", flags, max_active, 4);
2209 fs_info->endio_meta_workers =
2210 btrfs_alloc_workqueue(fs_info, "endio-meta", flags,
2212 fs_info->endio_meta_write_workers =
2213 btrfs_alloc_workqueue(fs_info, "endio-meta-write", flags,
2215 fs_info->endio_raid56_workers =
2216 btrfs_alloc_workqueue(fs_info, "endio-raid56", flags,
2218 fs_info->endio_repair_workers =
2219 btrfs_alloc_workqueue(fs_info, "endio-repair", flags, 1, 0);
2220 fs_info->rmw_workers =
2221 btrfs_alloc_workqueue(fs_info, "rmw", flags, max_active, 2);
2222 fs_info->endio_write_workers =
2223 btrfs_alloc_workqueue(fs_info, "endio-write", flags,
2225 fs_info->endio_freespace_worker =
2226 btrfs_alloc_workqueue(fs_info, "freespace-write", flags,
2228 fs_info->delayed_workers =
2229 btrfs_alloc_workqueue(fs_info, "delayed-meta", flags,
2231 fs_info->readahead_workers =
2232 btrfs_alloc_workqueue(fs_info, "readahead", flags,
2234 fs_info->qgroup_rescan_workers =
2235 btrfs_alloc_workqueue(fs_info, "qgroup-rescan", flags, 1, 0);
2236 fs_info->extent_workers =
2237 btrfs_alloc_workqueue(fs_info, "extent-refs", flags,
2238 min_t(u64, fs_devices->num_devices,
2241 if (!(fs_info->workers && fs_info->delalloc_workers &&
2242 fs_info->submit_workers && fs_info->flush_workers &&
2243 fs_info->endio_workers && fs_info->endio_meta_workers &&
2244 fs_info->endio_meta_write_workers &&
2245 fs_info->endio_repair_workers &&
2246 fs_info->endio_write_workers && fs_info->endio_raid56_workers &&
2247 fs_info->endio_freespace_worker && fs_info->rmw_workers &&
2248 fs_info->caching_workers && fs_info->readahead_workers &&
2249 fs_info->fixup_workers && fs_info->delayed_workers &&
2250 fs_info->extent_workers &&
2251 fs_info->qgroup_rescan_workers)) {
2258 static int btrfs_replay_log(struct btrfs_fs_info *fs_info,
2259 struct btrfs_fs_devices *fs_devices)
2262 struct btrfs_root *log_tree_root;
2263 struct btrfs_super_block *disk_super = fs_info->super_copy;
2264 u64 bytenr = btrfs_super_log_root(disk_super);
2265 int level = btrfs_super_log_root_level(disk_super);
2267 if (fs_devices->rw_devices == 0) {
2268 btrfs_warn(fs_info, "log replay required on RO media");
2272 log_tree_root = btrfs_alloc_root(fs_info, GFP_KERNEL);
2276 __setup_root(log_tree_root, fs_info, BTRFS_TREE_LOG_OBJECTID);
2278 log_tree_root->node = read_tree_block(fs_info, bytenr,
2279 fs_info->generation + 1,
2281 if (IS_ERR(log_tree_root->node)) {
2282 btrfs_warn(fs_info, "failed to read log tree");
2283 ret = PTR_ERR(log_tree_root->node);
2284 kfree(log_tree_root);
2286 } else if (!extent_buffer_uptodate(log_tree_root->node)) {
2287 btrfs_err(fs_info, "failed to read log tree");
2288 free_extent_buffer(log_tree_root->node);
2289 kfree(log_tree_root);
2292 /* returns with log_tree_root freed on success */
2293 ret = btrfs_recover_log_trees(log_tree_root);
2295 btrfs_handle_fs_error(fs_info, ret,
2296 "Failed to recover log tree");
2297 free_extent_buffer(log_tree_root->node);
2298 kfree(log_tree_root);
2302 if (sb_rdonly(fs_info->sb)) {
2303 ret = btrfs_commit_super(fs_info);
2311 static int btrfs_read_roots(struct btrfs_fs_info *fs_info)
2313 struct btrfs_root *tree_root = fs_info->tree_root;
2314 struct btrfs_root *root;
2315 struct btrfs_key location;
2318 BUG_ON(!fs_info->tree_root);
2320 location.objectid = BTRFS_EXTENT_TREE_OBJECTID;
2321 location.type = BTRFS_ROOT_ITEM_KEY;
2322 location.offset = 0;
2324 root = btrfs_read_tree_root(tree_root, &location);
2326 ret = PTR_ERR(root);
2329 set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2330 fs_info->extent_root = root;
2332 location.objectid = BTRFS_DEV_TREE_OBJECTID;
2333 root = btrfs_read_tree_root(tree_root, &location);
2335 ret = PTR_ERR(root);
2338 set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2339 fs_info->dev_root = root;
2340 btrfs_init_devices_late(fs_info);
2342 location.objectid = BTRFS_CSUM_TREE_OBJECTID;
2343 root = btrfs_read_tree_root(tree_root, &location);
2345 ret = PTR_ERR(root);
2348 set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2349 fs_info->csum_root = root;
2351 location.objectid = BTRFS_QUOTA_TREE_OBJECTID;
2352 root = btrfs_read_tree_root(tree_root, &location);
2353 if (!IS_ERR(root)) {
2354 set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2355 set_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags);
2356 fs_info->quota_root = root;
2359 location.objectid = BTRFS_UUID_TREE_OBJECTID;
2360 root = btrfs_read_tree_root(tree_root, &location);
2362 ret = PTR_ERR(root);
2366 set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2367 fs_info->uuid_root = root;
2370 if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
2371 location.objectid = BTRFS_FREE_SPACE_TREE_OBJECTID;
2372 root = btrfs_read_tree_root(tree_root, &location);
2374 ret = PTR_ERR(root);
2377 set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2378 fs_info->free_space_root = root;
2383 btrfs_warn(fs_info, "failed to read root (objectid=%llu): %d",
2384 location.objectid, ret);
2389 * Real super block validation
2390 * NOTE: super csum type and incompat features will not be checked here.
2392 * @sb: super block to check
2393 * @mirror_num: the super block number to check its bytenr:
2394 * 0 the primary (1st) sb
2395 * 1, 2 2nd and 3rd backup copy
2396 * -1 skip bytenr check
2398 static int validate_super(struct btrfs_fs_info *fs_info,
2399 struct btrfs_super_block *sb, int mirror_num)
2401 u64 nodesize = btrfs_super_nodesize(sb);
2402 u64 sectorsize = btrfs_super_sectorsize(sb);
2405 if (btrfs_super_magic(sb) != BTRFS_MAGIC) {
2406 btrfs_err(fs_info, "no valid FS found");
2409 if (btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP) {
2410 btrfs_err(fs_info, "unrecognized or unsupported super flag: %llu",
2411 btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP);
2414 if (btrfs_super_root_level(sb) >= BTRFS_MAX_LEVEL) {
2415 btrfs_err(fs_info, "tree_root level too big: %d >= %d",
2416 btrfs_super_root_level(sb), BTRFS_MAX_LEVEL);
2419 if (btrfs_super_chunk_root_level(sb) >= BTRFS_MAX_LEVEL) {
2420 btrfs_err(fs_info, "chunk_root level too big: %d >= %d",
2421 btrfs_super_chunk_root_level(sb), BTRFS_MAX_LEVEL);
2424 if (btrfs_super_log_root_level(sb) >= BTRFS_MAX_LEVEL) {
2425 btrfs_err(fs_info, "log_root level too big: %d >= %d",
2426 btrfs_super_log_root_level(sb), BTRFS_MAX_LEVEL);
2431 * Check sectorsize and nodesize first, other check will need it.
2432 * Check all possible sectorsize(4K, 8K, 16K, 32K, 64K) here.
2434 if (!is_power_of_2(sectorsize) || sectorsize < 4096 ||
2435 sectorsize > BTRFS_MAX_METADATA_BLOCKSIZE) {
2436 btrfs_err(fs_info, "invalid sectorsize %llu", sectorsize);
2439 /* Only PAGE SIZE is supported yet */
2440 if (sectorsize != PAGE_SIZE) {
2442 "sectorsize %llu not supported yet, only support %lu",
2443 sectorsize, PAGE_SIZE);
2446 if (!is_power_of_2(nodesize) || nodesize < sectorsize ||
2447 nodesize > BTRFS_MAX_METADATA_BLOCKSIZE) {
2448 btrfs_err(fs_info, "invalid nodesize %llu", nodesize);
2451 if (nodesize != le32_to_cpu(sb->__unused_leafsize)) {
2452 btrfs_err(fs_info, "invalid leafsize %u, should be %llu",
2453 le32_to_cpu(sb->__unused_leafsize), nodesize);
2457 /* Root alignment check */
2458 if (!IS_ALIGNED(btrfs_super_root(sb), sectorsize)) {
2459 btrfs_warn(fs_info, "tree_root block unaligned: %llu",
2460 btrfs_super_root(sb));
2463 if (!IS_ALIGNED(btrfs_super_chunk_root(sb), sectorsize)) {
2464 btrfs_warn(fs_info, "chunk_root block unaligned: %llu",
2465 btrfs_super_chunk_root(sb));
2468 if (!IS_ALIGNED(btrfs_super_log_root(sb), sectorsize)) {
2469 btrfs_warn(fs_info, "log_root block unaligned: %llu",
2470 btrfs_super_log_root(sb));
2474 if (memcmp(fs_info->fsid, sb->dev_item.fsid, BTRFS_FSID_SIZE) != 0) {
2476 "dev_item UUID does not match fsid: %pU != %pU",
2477 fs_info->fsid, sb->dev_item.fsid);
2482 * Hint to catch really bogus numbers, bitflips or so, more exact checks are
2485 if (btrfs_super_bytes_used(sb) < 6 * btrfs_super_nodesize(sb)) {
2486 btrfs_err(fs_info, "bytes_used is too small %llu",
2487 btrfs_super_bytes_used(sb));
2490 if (!is_power_of_2(btrfs_super_stripesize(sb))) {
2491 btrfs_err(fs_info, "invalid stripesize %u",
2492 btrfs_super_stripesize(sb));
2495 if (btrfs_super_num_devices(sb) > (1UL << 31))
2496 btrfs_warn(fs_info, "suspicious number of devices: %llu",
2497 btrfs_super_num_devices(sb));
2498 if (btrfs_super_num_devices(sb) == 0) {
2499 btrfs_err(fs_info, "number of devices is 0");
2503 if (mirror_num >= 0 &&
2504 btrfs_super_bytenr(sb) != btrfs_sb_offset(mirror_num)) {
2505 btrfs_err(fs_info, "super offset mismatch %llu != %u",
2506 btrfs_super_bytenr(sb), BTRFS_SUPER_INFO_OFFSET);
2511 * Obvious sys_chunk_array corruptions, it must hold at least one key
2514 if (btrfs_super_sys_array_size(sb) > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
2515 btrfs_err(fs_info, "system chunk array too big %u > %u",
2516 btrfs_super_sys_array_size(sb),
2517 BTRFS_SYSTEM_CHUNK_ARRAY_SIZE);
2520 if (btrfs_super_sys_array_size(sb) < sizeof(struct btrfs_disk_key)
2521 + sizeof(struct btrfs_chunk)) {
2522 btrfs_err(fs_info, "system chunk array too small %u < %zu",
2523 btrfs_super_sys_array_size(sb),
2524 sizeof(struct btrfs_disk_key)
2525 + sizeof(struct btrfs_chunk));
2530 * The generation is a global counter, we'll trust it more than the others
2531 * but it's still possible that it's the one that's wrong.
2533 if (btrfs_super_generation(sb) < btrfs_super_chunk_root_generation(sb))
2535 "suspicious: generation < chunk_root_generation: %llu < %llu",
2536 btrfs_super_generation(sb),
2537 btrfs_super_chunk_root_generation(sb));
2538 if (btrfs_super_generation(sb) < btrfs_super_cache_generation(sb)
2539 && btrfs_super_cache_generation(sb) != (u64)-1)
2541 "suspicious: generation < cache_generation: %llu < %llu",
2542 btrfs_super_generation(sb),
2543 btrfs_super_cache_generation(sb));
2549 * Validation of super block at mount time.
2550 * Some checks already done early at mount time, like csum type and incompat
2551 * flags will be skipped.
2553 static int btrfs_validate_mount_super(struct btrfs_fs_info *fs_info)
2555 return validate_super(fs_info, fs_info->super_copy, 0);
2559 * Validation of super block at write time.
2560 * Some checks like bytenr check will be skipped as their values will be
2562 * Extra checks like csum type and incompat flags will be done here.
2564 static int btrfs_validate_write_super(struct btrfs_fs_info *fs_info,
2565 struct btrfs_super_block *sb)
2569 ret = validate_super(fs_info, sb, -1);
2572 if (btrfs_super_csum_type(sb) != BTRFS_CSUM_TYPE_CRC32) {
2574 btrfs_err(fs_info, "invalid csum type, has %u want %u",
2575 btrfs_super_csum_type(sb), BTRFS_CSUM_TYPE_CRC32);
2578 if (btrfs_super_incompat_flags(sb) & ~BTRFS_FEATURE_INCOMPAT_SUPP) {
2581 "invalid incompat flags, has 0x%llx valid mask 0x%llx",
2582 btrfs_super_incompat_flags(sb),
2583 (unsigned long long)BTRFS_FEATURE_INCOMPAT_SUPP);
2589 "super block corruption detected before writing it to disk");
2593 int open_ctree(struct super_block *sb,
2594 struct btrfs_fs_devices *fs_devices,
2602 struct btrfs_key location;
2603 struct buffer_head *bh;
2604 struct btrfs_super_block *disk_super;
2605 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
2606 struct btrfs_root *tree_root;
2607 struct btrfs_root *chunk_root;
2610 int num_backups_tried = 0;
2611 int backup_index = 0;
2612 int clear_free_space_tree = 0;
2615 tree_root = fs_info->tree_root = btrfs_alloc_root(fs_info, GFP_KERNEL);
2616 chunk_root = fs_info->chunk_root = btrfs_alloc_root(fs_info, GFP_KERNEL);
2617 if (!tree_root || !chunk_root) {
2622 ret = init_srcu_struct(&fs_info->subvol_srcu);
2628 ret = percpu_counter_init(&fs_info->dirty_metadata_bytes, 0, GFP_KERNEL);
2633 fs_info->dirty_metadata_batch = PAGE_SIZE *
2634 (1 + ilog2(nr_cpu_ids));
2636 ret = percpu_counter_init(&fs_info->delalloc_bytes, 0, GFP_KERNEL);
2639 goto fail_dirty_metadata_bytes;
2642 ret = percpu_counter_init(&fs_info->bio_counter, 0, GFP_KERNEL);
2645 goto fail_delalloc_bytes;
2648 INIT_RADIX_TREE(&fs_info->fs_roots_radix, GFP_ATOMIC);
2649 INIT_RADIX_TREE(&fs_info->buffer_radix, GFP_ATOMIC);
2650 INIT_LIST_HEAD(&fs_info->trans_list);
2651 INIT_LIST_HEAD(&fs_info->dead_roots);
2652 INIT_LIST_HEAD(&fs_info->delayed_iputs);
2653 INIT_LIST_HEAD(&fs_info->delalloc_roots);
2654 INIT_LIST_HEAD(&fs_info->caching_block_groups);
2655 INIT_LIST_HEAD(&fs_info->pending_raid_kobjs);
2656 spin_lock_init(&fs_info->pending_raid_kobjs_lock);
2657 spin_lock_init(&fs_info->delalloc_root_lock);
2658 spin_lock_init(&fs_info->trans_lock);
2659 spin_lock_init(&fs_info->fs_roots_radix_lock);
2660 spin_lock_init(&fs_info->delayed_iput_lock);
2661 spin_lock_init(&fs_info->defrag_inodes_lock);
2662 spin_lock_init(&fs_info->tree_mod_seq_lock);
2663 spin_lock_init(&fs_info->super_lock);
2664 spin_lock_init(&fs_info->qgroup_op_lock);
2665 spin_lock_init(&fs_info->buffer_lock);
2666 spin_lock_init(&fs_info->unused_bgs_lock);
2667 rwlock_init(&fs_info->tree_mod_log_lock);
2668 mutex_init(&fs_info->unused_bg_unpin_mutex);
2669 mutex_init(&fs_info->delete_unused_bgs_mutex);
2670 mutex_init(&fs_info->reloc_mutex);
2671 mutex_init(&fs_info->delalloc_root_mutex);
2672 mutex_init(&fs_info->cleaner_delayed_iput_mutex);
2673 seqlock_init(&fs_info->profiles_lock);
2675 INIT_LIST_HEAD(&fs_info->dirty_cowonly_roots);
2676 INIT_LIST_HEAD(&fs_info->space_info);
2677 INIT_LIST_HEAD(&fs_info->tree_mod_seq_list);
2678 INIT_LIST_HEAD(&fs_info->unused_bgs);
2679 btrfs_mapping_init(&fs_info->mapping_tree);
2680 btrfs_init_block_rsv(&fs_info->global_block_rsv,
2681 BTRFS_BLOCK_RSV_GLOBAL);
2682 btrfs_init_block_rsv(&fs_info->trans_block_rsv, BTRFS_BLOCK_RSV_TRANS);
2683 btrfs_init_block_rsv(&fs_info->chunk_block_rsv, BTRFS_BLOCK_RSV_CHUNK);
2684 btrfs_init_block_rsv(&fs_info->empty_block_rsv, BTRFS_BLOCK_RSV_EMPTY);
2685 btrfs_init_block_rsv(&fs_info->delayed_block_rsv,
2686 BTRFS_BLOCK_RSV_DELOPS);
2687 atomic_set(&fs_info->async_delalloc_pages, 0);
2688 atomic_set(&fs_info->defrag_running, 0);
2689 atomic_set(&fs_info->qgroup_op_seq, 0);
2690 atomic_set(&fs_info->reada_works_cnt, 0);
2691 atomic64_set(&fs_info->tree_mod_seq, 0);
2693 fs_info->max_inline = BTRFS_DEFAULT_MAX_INLINE;
2694 fs_info->metadata_ratio = 0;
2695 fs_info->defrag_inodes = RB_ROOT;
2696 atomic64_set(&fs_info->free_chunk_space, 0);
2697 fs_info->tree_mod_log = RB_ROOT;
2698 fs_info->commit_interval = BTRFS_DEFAULT_COMMIT_INTERVAL;
2699 fs_info->avg_delayed_ref_runtime = NSEC_PER_SEC >> 6; /* div by 64 */
2700 /* readahead state */
2701 INIT_RADIX_TREE(&fs_info->reada_tree, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
2702 spin_lock_init(&fs_info->reada_lock);
2703 btrfs_init_ref_verify(fs_info);
2705 fs_info->thread_pool_size = min_t(unsigned long,
2706 num_online_cpus() + 2, 8);
2708 INIT_LIST_HEAD(&fs_info->ordered_roots);
2709 spin_lock_init(&fs_info->ordered_root_lock);
2711 fs_info->btree_inode = new_inode(sb);
2712 if (!fs_info->btree_inode) {
2714 goto fail_bio_counter;
2716 mapping_set_gfp_mask(fs_info->btree_inode->i_mapping, GFP_NOFS);
2718 fs_info->delayed_root = kmalloc(sizeof(struct btrfs_delayed_root),
2720 if (!fs_info->delayed_root) {
2724 btrfs_init_delayed_root(fs_info->delayed_root);
2726 btrfs_init_scrub(fs_info);
2727 #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
2728 fs_info->check_integrity_print_mask = 0;
2730 btrfs_init_balance(fs_info);
2731 btrfs_init_async_reclaim_work(&fs_info->async_reclaim_work);
2733 sb->s_blocksize = BTRFS_BDEV_BLOCKSIZE;
2734 sb->s_blocksize_bits = blksize_bits(BTRFS_BDEV_BLOCKSIZE);
2736 btrfs_init_btree_inode(fs_info);
2738 spin_lock_init(&fs_info->block_group_cache_lock);
2739 fs_info->block_group_cache_tree = RB_ROOT;
2740 fs_info->first_logical_byte = (u64)-1;
2742 extent_io_tree_init(&fs_info->freed_extents[0], NULL);
2743 extent_io_tree_init(&fs_info->freed_extents[1], NULL);
2744 fs_info->pinned_extents = &fs_info->freed_extents[0];
2745 set_bit(BTRFS_FS_BARRIER, &fs_info->flags);
2747 mutex_init(&fs_info->ordered_operations_mutex);
2748 mutex_init(&fs_info->tree_log_mutex);
2749 mutex_init(&fs_info->chunk_mutex);
2750 mutex_init(&fs_info->transaction_kthread_mutex);
2751 mutex_init(&fs_info->cleaner_mutex);
2752 mutex_init(&fs_info->ro_block_group_mutex);
2753 init_rwsem(&fs_info->commit_root_sem);
2754 init_rwsem(&fs_info->cleanup_work_sem);
2755 init_rwsem(&fs_info->subvol_sem);
2756 sema_init(&fs_info->uuid_tree_rescan_sem, 1);
2758 btrfs_init_dev_replace_locks(fs_info);
2759 btrfs_init_qgroup(fs_info);
2761 btrfs_init_free_cluster(&fs_info->meta_alloc_cluster);
2762 btrfs_init_free_cluster(&fs_info->data_alloc_cluster);
2764 init_waitqueue_head(&fs_info->transaction_throttle);
2765 init_waitqueue_head(&fs_info->transaction_wait);
2766 init_waitqueue_head(&fs_info->transaction_blocked_wait);
2767 init_waitqueue_head(&fs_info->async_submit_wait);
2769 INIT_LIST_HEAD(&fs_info->pinned_chunks);
2771 /* Usable values until the real ones are cached from the superblock */
2772 fs_info->nodesize = 4096;
2773 fs_info->sectorsize = 4096;
2774 fs_info->stripesize = 4096;
2776 ret = btrfs_alloc_stripe_hash_table(fs_info);
2782 __setup_root(tree_root, fs_info, BTRFS_ROOT_TREE_OBJECTID);
2784 invalidate_bdev(fs_devices->latest_bdev);
2787 * Read super block and check the signature bytes only
2789 bh = btrfs_read_dev_super(fs_devices->latest_bdev);
2796 * We want to check superblock checksum, the type is stored inside.
2797 * Pass the whole disk block of size BTRFS_SUPER_INFO_SIZE (4k).
2799 if (btrfs_check_super_csum(fs_info, bh->b_data)) {
2800 btrfs_err(fs_info, "superblock checksum mismatch");
2807 * super_copy is zeroed at allocation time and we never touch the
2808 * following bytes up to INFO_SIZE, the checksum is calculated from
2809 * the whole block of INFO_SIZE
2811 memcpy(fs_info->super_copy, bh->b_data, sizeof(*fs_info->super_copy));
2812 memcpy(fs_info->super_for_commit, fs_info->super_copy,
2813 sizeof(*fs_info->super_for_commit));
2816 memcpy(fs_info->fsid, fs_info->super_copy->fsid, BTRFS_FSID_SIZE);
2818 ret = btrfs_validate_mount_super(fs_info);
2820 btrfs_err(fs_info, "superblock contains fatal errors");
2825 disk_super = fs_info->super_copy;
2826 if (!btrfs_super_root(disk_super))
2829 /* check FS state, whether FS is broken. */
2830 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_ERROR)
2831 set_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state);
2834 * run through our array of backup supers and setup
2835 * our ring pointer to the oldest one
2837 generation = btrfs_super_generation(disk_super);
2838 find_oldest_super_backup(fs_info, generation);
2841 * In the long term, we'll store the compression type in the super
2842 * block, and it'll be used for per file compression control.
2844 fs_info->compress_type = BTRFS_COMPRESS_ZLIB;
2846 ret = btrfs_parse_options(fs_info, options, sb->s_flags);
2852 features = btrfs_super_incompat_flags(disk_super) &
2853 ~BTRFS_FEATURE_INCOMPAT_SUPP;
2856 "cannot mount because of unsupported optional features (%llx)",
2862 features = btrfs_super_incompat_flags(disk_super);
2863 features |= BTRFS_FEATURE_INCOMPAT_MIXED_BACKREF;
2864 if (fs_info->compress_type == BTRFS_COMPRESS_LZO)
2865 features |= BTRFS_FEATURE_INCOMPAT_COMPRESS_LZO;
2866 else if (fs_info->compress_type == BTRFS_COMPRESS_ZSTD)
2867 features |= BTRFS_FEATURE_INCOMPAT_COMPRESS_ZSTD;
2869 if (features & BTRFS_FEATURE_INCOMPAT_SKINNY_METADATA)
2870 btrfs_info(fs_info, "has skinny extents");
2873 * flag our filesystem as having big metadata blocks if
2874 * they are bigger than the page size
2876 if (btrfs_super_nodesize(disk_super) > PAGE_SIZE) {
2877 if (!(features & BTRFS_FEATURE_INCOMPAT_BIG_METADATA))
2879 "flagging fs with big metadata feature");
2880 features |= BTRFS_FEATURE_INCOMPAT_BIG_METADATA;
2883 nodesize = btrfs_super_nodesize(disk_super);
2884 sectorsize = btrfs_super_sectorsize(disk_super);
2885 stripesize = sectorsize;
2886 fs_info->dirty_metadata_batch = nodesize * (1 + ilog2(nr_cpu_ids));
2887 fs_info->delalloc_batch = sectorsize * 512 * (1 + ilog2(nr_cpu_ids));
2889 /* Cache block sizes */
2890 fs_info->nodesize = nodesize;
2891 fs_info->sectorsize = sectorsize;
2892 fs_info->stripesize = stripesize;
2895 * mixed block groups end up with duplicate but slightly offset
2896 * extent buffers for the same range. It leads to corruptions
2898 if ((features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS) &&
2899 (sectorsize != nodesize)) {
2901 "unequal nodesize/sectorsize (%u != %u) are not allowed for mixed block groups",
2902 nodesize, sectorsize);
2907 * Needn't use the lock because there is no other task which will
2910 btrfs_set_super_incompat_flags(disk_super, features);
2912 features = btrfs_super_compat_ro_flags(disk_super) &
2913 ~BTRFS_FEATURE_COMPAT_RO_SUPP;
2914 if (!sb_rdonly(sb) && features) {
2916 "cannot mount read-write because of unsupported optional features (%llx)",
2922 ret = btrfs_init_workqueues(fs_info, fs_devices);
2925 goto fail_sb_buffer;
2928 sb->s_bdi->congested_fn = btrfs_congested_fn;
2929 sb->s_bdi->congested_data = fs_info;
2930 sb->s_bdi->capabilities |= BDI_CAP_CGROUP_WRITEBACK;
2931 sb->s_bdi->ra_pages = VM_MAX_READAHEAD * SZ_1K / PAGE_SIZE;
2932 sb->s_bdi->ra_pages *= btrfs_super_num_devices(disk_super);
2933 sb->s_bdi->ra_pages = max(sb->s_bdi->ra_pages, SZ_4M / PAGE_SIZE);
2935 sb->s_blocksize = sectorsize;
2936 sb->s_blocksize_bits = blksize_bits(sectorsize);
2937 memcpy(&sb->s_uuid, fs_info->fsid, BTRFS_FSID_SIZE);
2939 mutex_lock(&fs_info->chunk_mutex);
2940 ret = btrfs_read_sys_array(fs_info);
2941 mutex_unlock(&fs_info->chunk_mutex);
2943 btrfs_err(fs_info, "failed to read the system array: %d", ret);
2944 goto fail_sb_buffer;
2947 generation = btrfs_super_chunk_root_generation(disk_super);
2948 level = btrfs_super_chunk_root_level(disk_super);
2950 __setup_root(chunk_root, fs_info, BTRFS_CHUNK_TREE_OBJECTID);
2952 chunk_root->node = read_tree_block(fs_info,
2953 btrfs_super_chunk_root(disk_super),
2954 generation, level, NULL);
2955 if (IS_ERR(chunk_root->node) ||
2956 !extent_buffer_uptodate(chunk_root->node)) {
2957 btrfs_err(fs_info, "failed to read chunk root");
2958 if (!IS_ERR(chunk_root->node))
2959 free_extent_buffer(chunk_root->node);
2960 chunk_root->node = NULL;
2961 goto fail_tree_roots;
2963 btrfs_set_root_node(&chunk_root->root_item, chunk_root->node);
2964 chunk_root->commit_root = btrfs_root_node(chunk_root);
2966 read_extent_buffer(chunk_root->node, fs_info->chunk_tree_uuid,
2967 btrfs_header_chunk_tree_uuid(chunk_root->node), BTRFS_UUID_SIZE);
2969 ret = btrfs_read_chunk_tree(fs_info);
2971 btrfs_err(fs_info, "failed to read chunk tree: %d", ret);
2972 goto fail_tree_roots;
2976 * Keep the devid that is marked to be the target device for the
2977 * device replace procedure
2979 btrfs_free_extra_devids(fs_devices, 0);
2981 if (!fs_devices->latest_bdev) {
2982 btrfs_err(fs_info, "failed to read devices");
2983 goto fail_tree_roots;
2987 generation = btrfs_super_generation(disk_super);
2988 level = btrfs_super_root_level(disk_super);
2990 tree_root->node = read_tree_block(fs_info,
2991 btrfs_super_root(disk_super),
2992 generation, level, NULL);
2993 if (IS_ERR(tree_root->node) ||
2994 !extent_buffer_uptodate(tree_root->node)) {
2995 btrfs_warn(fs_info, "failed to read tree root");
2996 if (!IS_ERR(tree_root->node))
2997 free_extent_buffer(tree_root->node);
2998 tree_root->node = NULL;
2999 goto recovery_tree_root;
3002 btrfs_set_root_node(&tree_root->root_item, tree_root->node);
3003 tree_root->commit_root = btrfs_root_node(tree_root);
3004 btrfs_set_root_refs(&tree_root->root_item, 1);
3006 mutex_lock(&tree_root->objectid_mutex);
3007 ret = btrfs_find_highest_objectid(tree_root,
3008 &tree_root->highest_objectid);
3010 mutex_unlock(&tree_root->objectid_mutex);
3011 goto recovery_tree_root;
3014 ASSERT(tree_root->highest_objectid <= BTRFS_LAST_FREE_OBJECTID);
3016 mutex_unlock(&tree_root->objectid_mutex);
3018 ret = btrfs_read_roots(fs_info);
3020 goto recovery_tree_root;
3022 fs_info->generation = generation;
3023 fs_info->last_trans_committed = generation;
3025 ret = btrfs_verify_dev_extents(fs_info);
3028 "failed to verify dev extents against chunks: %d",
3030 goto fail_block_groups;
3032 ret = btrfs_recover_balance(fs_info);
3034 btrfs_err(fs_info, "failed to recover balance: %d", ret);
3035 goto fail_block_groups;
3038 ret = btrfs_init_dev_stats(fs_info);
3040 btrfs_err(fs_info, "failed to init dev_stats: %d", ret);
3041 goto fail_block_groups;
3044 ret = btrfs_init_dev_replace(fs_info);
3046 btrfs_err(fs_info, "failed to init dev_replace: %d", ret);
3047 goto fail_block_groups;
3050 btrfs_free_extra_devids(fs_devices, 1);
3052 ret = btrfs_sysfs_add_fsid(fs_devices, NULL);
3054 btrfs_err(fs_info, "failed to init sysfs fsid interface: %d",
3056 goto fail_block_groups;
3059 ret = btrfs_sysfs_add_device(fs_devices);
3061 btrfs_err(fs_info, "failed to init sysfs device interface: %d",
3063 goto fail_fsdev_sysfs;
3066 ret = btrfs_sysfs_add_mounted(fs_info);
3068 btrfs_err(fs_info, "failed to init sysfs interface: %d", ret);
3069 goto fail_fsdev_sysfs;
3072 ret = btrfs_init_space_info(fs_info);
3074 btrfs_err(fs_info, "failed to initialize space info: %d", ret);
3078 ret = btrfs_read_block_groups(fs_info);
3080 btrfs_err(fs_info, "failed to read block groups: %d", ret);
3084 if (!sb_rdonly(sb) && !btrfs_check_rw_degradable(fs_info, NULL)) {
3086 "writeable mount is not allowed due to too many missing devices");
3090 fs_info->cleaner_kthread = kthread_run(cleaner_kthread, tree_root,
3092 if (IS_ERR(fs_info->cleaner_kthread))
3095 fs_info->transaction_kthread = kthread_run(transaction_kthread,
3097 "btrfs-transaction");
3098 if (IS_ERR(fs_info->transaction_kthread))
3101 if (!btrfs_test_opt(fs_info, NOSSD) &&
3102 !fs_info->fs_devices->rotating) {
3103 btrfs_set_and_info(fs_info, SSD, "enabling ssd optimizations");
3107 * Mount does not set all options immediately, we can do it now and do
3108 * not have to wait for transaction commit
3110 btrfs_apply_pending_changes(fs_info);
3112 #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
3113 if (btrfs_test_opt(fs_info, CHECK_INTEGRITY)) {
3114 ret = btrfsic_mount(fs_info, fs_devices,
3115 btrfs_test_opt(fs_info,
3116 CHECK_INTEGRITY_INCLUDING_EXTENT_DATA) ?
3118 fs_info->check_integrity_print_mask);
3121 "failed to initialize integrity check module: %d",
3125 ret = btrfs_read_qgroup_config(fs_info);
3127 goto fail_trans_kthread;
3129 if (btrfs_build_ref_tree(fs_info))
3130 btrfs_err(fs_info, "couldn't build ref tree");
3132 /* do not make disk changes in broken FS or nologreplay is given */
3133 if (btrfs_super_log_root(disk_super) != 0 &&
3134 !btrfs_test_opt(fs_info, NOLOGREPLAY)) {
3135 ret = btrfs_replay_log(fs_info, fs_devices);
3142 ret = btrfs_find_orphan_roots(fs_info);
3146 if (!sb_rdonly(sb)) {
3147 ret = btrfs_cleanup_fs_roots(fs_info);
3151 mutex_lock(&fs_info->cleaner_mutex);
3152 ret = btrfs_recover_relocation(tree_root);
3153 mutex_unlock(&fs_info->cleaner_mutex);
3155 btrfs_warn(fs_info, "failed to recover relocation: %d",
3162 location.objectid = BTRFS_FS_TREE_OBJECTID;
3163 location.type = BTRFS_ROOT_ITEM_KEY;
3164 location.offset = 0;
3166 fs_info->fs_root = btrfs_read_fs_root_no_name(fs_info, &location);
3167 if (IS_ERR(fs_info->fs_root)) {
3168 err = PTR_ERR(fs_info->fs_root);
3169 btrfs_warn(fs_info, "failed to read fs tree: %d", err);
3176 if (btrfs_test_opt(fs_info, CLEAR_CACHE) &&
3177 btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
3178 clear_free_space_tree = 1;
3179 } else if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE) &&
3180 !btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE_VALID)) {
3181 btrfs_warn(fs_info, "free space tree is invalid");
3182 clear_free_space_tree = 1;
3185 if (clear_free_space_tree) {
3186 btrfs_info(fs_info, "clearing free space tree");
3187 ret = btrfs_clear_free_space_tree(fs_info);
3190 "failed to clear free space tree: %d", ret);
3191 close_ctree(fs_info);
3196 if (btrfs_test_opt(fs_info, FREE_SPACE_TREE) &&
3197 !btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
3198 btrfs_info(fs_info, "creating free space tree");
3199 ret = btrfs_create_free_space_tree(fs_info);
3202 "failed to create free space tree: %d", ret);
3203 close_ctree(fs_info);
3208 down_read(&fs_info->cleanup_work_sem);
3209 if ((ret = btrfs_orphan_cleanup(fs_info->fs_root)) ||
3210 (ret = btrfs_orphan_cleanup(fs_info->tree_root))) {
3211 up_read(&fs_info->cleanup_work_sem);
3212 close_ctree(fs_info);
3215 up_read(&fs_info->cleanup_work_sem);
3217 ret = btrfs_resume_balance_async(fs_info);
3219 btrfs_warn(fs_info, "failed to resume balance: %d", ret);
3220 close_ctree(fs_info);
3224 ret = btrfs_resume_dev_replace_async(fs_info);
3226 btrfs_warn(fs_info, "failed to resume device replace: %d", ret);
3227 close_ctree(fs_info);
3231 btrfs_qgroup_rescan_resume(fs_info);
3233 if (!fs_info->uuid_root) {
3234 btrfs_info(fs_info, "creating UUID tree");
3235 ret = btrfs_create_uuid_tree(fs_info);
3238 "failed to create the UUID tree: %d", ret);
3239 close_ctree(fs_info);
3242 } else if (btrfs_test_opt(fs_info, RESCAN_UUID_TREE) ||
3243 fs_info->generation !=
3244 btrfs_super_uuid_tree_generation(disk_super)) {
3245 btrfs_info(fs_info, "checking UUID tree");
3246 ret = btrfs_check_uuid_tree(fs_info);
3249 "failed to check the UUID tree: %d", ret);
3250 close_ctree(fs_info);
3254 set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
3256 set_bit(BTRFS_FS_OPEN, &fs_info->flags);
3259 * backuproot only affect mount behavior, and if open_ctree succeeded,
3260 * no need to keep the flag
3262 btrfs_clear_opt(fs_info->mount_opt, USEBACKUPROOT);
3267 btrfs_free_qgroup_config(fs_info);
3269 kthread_stop(fs_info->transaction_kthread);
3270 btrfs_cleanup_transaction(fs_info);
3271 btrfs_free_fs_roots(fs_info);
3273 kthread_stop(fs_info->cleaner_kthread);
3276 * make sure we're done with the btree inode before we stop our
3279 filemap_write_and_wait(fs_info->btree_inode->i_mapping);
3282 btrfs_sysfs_remove_mounted(fs_info);
3285 btrfs_sysfs_remove_fsid(fs_info->fs_devices);
3288 btrfs_put_block_group_cache(fs_info);
3291 free_root_pointers(fs_info, 1);
3292 invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
3295 btrfs_stop_all_workers(fs_info);
3296 btrfs_free_block_groups(fs_info);
3299 btrfs_mapping_tree_free(&fs_info->mapping_tree);
3301 iput(fs_info->btree_inode);
3303 percpu_counter_destroy(&fs_info->bio_counter);
3304 fail_delalloc_bytes:
3305 percpu_counter_destroy(&fs_info->delalloc_bytes);
3306 fail_dirty_metadata_bytes:
3307 percpu_counter_destroy(&fs_info->dirty_metadata_bytes);
3309 cleanup_srcu_struct(&fs_info->subvol_srcu);
3311 btrfs_free_stripe_hash_table(fs_info);
3312 btrfs_close_devices(fs_info->fs_devices);
3316 if (!btrfs_test_opt(fs_info, USEBACKUPROOT))
3317 goto fail_tree_roots;
3319 free_root_pointers(fs_info, 0);
3321 /* don't use the log in recovery mode, it won't be valid */
3322 btrfs_set_super_log_root(disk_super, 0);
3324 /* we can't trust the free space cache either */
3325 btrfs_set_opt(fs_info->mount_opt, CLEAR_CACHE);
3327 ret = next_root_backup(fs_info, fs_info->super_copy,
3328 &num_backups_tried, &backup_index);
3330 goto fail_block_groups;
3331 goto retry_root_backup;
3333 ALLOW_ERROR_INJECTION(open_ctree, ERRNO);
3335 static void btrfs_end_buffer_write_sync(struct buffer_head *bh, int uptodate)
3338 set_buffer_uptodate(bh);
3340 struct btrfs_device *device = (struct btrfs_device *)
3343 btrfs_warn_rl_in_rcu(device->fs_info,
3344 "lost page write due to IO error on %s",
3345 rcu_str_deref(device->name));
3346 /* note, we don't set_buffer_write_io_error because we have
3347 * our own ways of dealing with the IO errors
3349 clear_buffer_uptodate(bh);
3350 btrfs_dev_stat_inc_and_print(device, BTRFS_DEV_STAT_WRITE_ERRS);
3356 int btrfs_read_dev_one_super(struct block_device *bdev, int copy_num,
3357 struct buffer_head **bh_ret)
3359 struct buffer_head *bh;
3360 struct btrfs_super_block *super;
3363 bytenr = btrfs_sb_offset(copy_num);
3364 if (bytenr + BTRFS_SUPER_INFO_SIZE >= i_size_read(bdev->bd_inode))
3367 bh = __bread(bdev, bytenr / BTRFS_BDEV_BLOCKSIZE, BTRFS_SUPER_INFO_SIZE);
3369 * If we fail to read from the underlying devices, as of now
3370 * the best option we have is to mark it EIO.
3375 super = (struct btrfs_super_block *)bh->b_data;
3376 if (btrfs_super_bytenr(super) != bytenr ||
3377 btrfs_super_magic(super) != BTRFS_MAGIC) {
3387 struct buffer_head *btrfs_read_dev_super(struct block_device *bdev)
3389 struct buffer_head *bh;
3390 struct buffer_head *latest = NULL;
3391 struct btrfs_super_block *super;
3396 /* we would like to check all the supers, but that would make
3397 * a btrfs mount succeed after a mkfs from a different FS.
3398 * So, we need to add a special mount option to scan for
3399 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
3401 for (i = 0; i < 1; i++) {
3402 ret = btrfs_read_dev_one_super(bdev, i, &bh);
3406 super = (struct btrfs_super_block *)bh->b_data;
3408 if (!latest || btrfs_super_generation(super) > transid) {
3411 transid = btrfs_super_generation(super);
3418 return ERR_PTR(ret);
3424 * Write superblock @sb to the @device. Do not wait for completion, all the
3425 * buffer heads we write are pinned.
3427 * Write @max_mirrors copies of the superblock, where 0 means default that fit
3428 * the expected device size at commit time. Note that max_mirrors must be
3429 * same for write and wait phases.
3431 * Return number of errors when buffer head is not found or submission fails.
3433 static int write_dev_supers(struct btrfs_device *device,
3434 struct btrfs_super_block *sb, int max_mirrors)
3436 struct buffer_head *bh;
3444 if (max_mirrors == 0)
3445 max_mirrors = BTRFS_SUPER_MIRROR_MAX;
3447 for (i = 0; i < max_mirrors; i++) {
3448 bytenr = btrfs_sb_offset(i);
3449 if (bytenr + BTRFS_SUPER_INFO_SIZE >=
3450 device->commit_total_bytes)
3453 btrfs_set_super_bytenr(sb, bytenr);
3456 crc = btrfs_csum_data((const char *)sb + BTRFS_CSUM_SIZE, crc,
3457 BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE);
3458 btrfs_csum_final(crc, sb->csum);
3460 /* One reference for us, and we leave it for the caller */
3461 bh = __getblk(device->bdev, bytenr / BTRFS_BDEV_BLOCKSIZE,
3462 BTRFS_SUPER_INFO_SIZE);
3464 btrfs_err(device->fs_info,
3465 "couldn't get super buffer head for bytenr %llu",
3471 memcpy(bh->b_data, sb, BTRFS_SUPER_INFO_SIZE);
3473 /* one reference for submit_bh */
3476 set_buffer_uptodate(bh);
3478 bh->b_end_io = btrfs_end_buffer_write_sync;
3479 bh->b_private = device;
3482 * we fua the first super. The others we allow
3485 op_flags = REQ_SYNC | REQ_META | REQ_PRIO;
3486 if (i == 0 && !btrfs_test_opt(device->fs_info, NOBARRIER))
3487 op_flags |= REQ_FUA;
3488 ret = btrfsic_submit_bh(REQ_OP_WRITE, op_flags, bh);
3492 return errors < i ? 0 : -1;
3496 * Wait for write completion of superblocks done by write_dev_supers,
3497 * @max_mirrors same for write and wait phases.
3499 * Return number of errors when buffer head is not found or not marked up to
3502 static int wait_dev_supers(struct btrfs_device *device, int max_mirrors)
3504 struct buffer_head *bh;
3507 bool primary_failed = false;
3510 if (max_mirrors == 0)
3511 max_mirrors = BTRFS_SUPER_MIRROR_MAX;
3513 for (i = 0; i < max_mirrors; i++) {
3514 bytenr = btrfs_sb_offset(i);
3515 if (bytenr + BTRFS_SUPER_INFO_SIZE >=
3516 device->commit_total_bytes)
3519 bh = __find_get_block(device->bdev,
3520 bytenr / BTRFS_BDEV_BLOCKSIZE,
3521 BTRFS_SUPER_INFO_SIZE);
3525 primary_failed = true;
3529 if (!buffer_uptodate(bh)) {
3532 primary_failed = true;
3535 /* drop our reference */
3538 /* drop the reference from the writing run */
3542 /* log error, force error return */
3543 if (primary_failed) {
3544 btrfs_err(device->fs_info, "error writing primary super block to device %llu",
3549 return errors < i ? 0 : -1;
3553 * endio for the write_dev_flush, this will wake anyone waiting
3554 * for the barrier when it is done
3556 static void btrfs_end_empty_barrier(struct bio *bio)
3558 complete(bio->bi_private);
3562 * Submit a flush request to the device if it supports it. Error handling is
3563 * done in the waiting counterpart.
3565 static void write_dev_flush(struct btrfs_device *device)
3567 struct request_queue *q = bdev_get_queue(device->bdev);
3568 struct bio *bio = device->flush_bio;
3570 if (!test_bit(QUEUE_FLAG_WC, &q->queue_flags))
3574 bio->bi_end_io = btrfs_end_empty_barrier;
3575 bio_set_dev(bio, device->bdev);
3576 bio->bi_opf = REQ_OP_WRITE | REQ_SYNC | REQ_PREFLUSH;
3577 init_completion(&device->flush_wait);
3578 bio->bi_private = &device->flush_wait;
3580 btrfsic_submit_bio(bio);
3581 set_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state);
3585 * If the flush bio has been submitted by write_dev_flush, wait for it.
3587 static blk_status_t wait_dev_flush(struct btrfs_device *device)
3589 struct bio *bio = device->flush_bio;
3591 if (!test_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state))
3594 clear_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state);
3595 wait_for_completion_io(&device->flush_wait);
3597 return bio->bi_status;
3600 static int check_barrier_error(struct btrfs_fs_info *fs_info)
3602 if (!btrfs_check_rw_degradable(fs_info, NULL))
3608 * send an empty flush down to each device in parallel,
3609 * then wait for them
3611 static int barrier_all_devices(struct btrfs_fs_info *info)
3613 struct list_head *head;
3614 struct btrfs_device *dev;
3615 int errors_wait = 0;
3618 lockdep_assert_held(&info->fs_devices->device_list_mutex);
3619 /* send down all the barriers */
3620 head = &info->fs_devices->devices;
3621 list_for_each_entry(dev, head, dev_list) {
3622 if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
3626 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
3627 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
3630 write_dev_flush(dev);
3631 dev->last_flush_error = BLK_STS_OK;
3634 /* wait for all the barriers */
3635 list_for_each_entry(dev, head, dev_list) {
3636 if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
3642 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
3643 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
3646 ret = wait_dev_flush(dev);
3648 dev->last_flush_error = ret;
3649 btrfs_dev_stat_inc_and_print(dev,
3650 BTRFS_DEV_STAT_FLUSH_ERRS);
3657 * At some point we need the status of all disks
3658 * to arrive at the volume status. So error checking
3659 * is being pushed to a separate loop.
3661 return check_barrier_error(info);
3666 int btrfs_get_num_tolerated_disk_barrier_failures(u64 flags)
3669 int min_tolerated = INT_MAX;
3671 if ((flags & BTRFS_BLOCK_GROUP_PROFILE_MASK) == 0 ||
3672 (flags & BTRFS_AVAIL_ALLOC_BIT_SINGLE))
3673 min_tolerated = min(min_tolerated,
3674 btrfs_raid_array[BTRFS_RAID_SINGLE].
3675 tolerated_failures);
3677 for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) {
3678 if (raid_type == BTRFS_RAID_SINGLE)
3680 if (!(flags & btrfs_raid_array[raid_type].bg_flag))
3682 min_tolerated = min(min_tolerated,
3683 btrfs_raid_array[raid_type].
3684 tolerated_failures);
3687 if (min_tolerated == INT_MAX) {
3688 pr_warn("BTRFS: unknown raid flag: %llu", flags);
3692 return min_tolerated;
3695 int write_all_supers(struct btrfs_fs_info *fs_info, int max_mirrors)
3697 struct list_head *head;
3698 struct btrfs_device *dev;
3699 struct btrfs_super_block *sb;
3700 struct btrfs_dev_item *dev_item;
3704 int total_errors = 0;
3707 do_barriers = !btrfs_test_opt(fs_info, NOBARRIER);
3710 * max_mirrors == 0 indicates we're from commit_transaction,
3711 * not from fsync where the tree roots in fs_info have not
3712 * been consistent on disk.
3714 if (max_mirrors == 0)
3715 backup_super_roots(fs_info);
3717 sb = fs_info->super_for_commit;
3718 dev_item = &sb->dev_item;
3720 mutex_lock(&fs_info->fs_devices->device_list_mutex);
3721 head = &fs_info->fs_devices->devices;
3722 max_errors = btrfs_super_num_devices(fs_info->super_copy) - 1;
3725 ret = barrier_all_devices(fs_info);
3728 &fs_info->fs_devices->device_list_mutex);
3729 btrfs_handle_fs_error(fs_info, ret,
3730 "errors while submitting device barriers.");
3735 list_for_each_entry(dev, head, dev_list) {
3740 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
3741 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
3744 btrfs_set_stack_device_generation(dev_item, 0);
3745 btrfs_set_stack_device_type(dev_item, dev->type);
3746 btrfs_set_stack_device_id(dev_item, dev->devid);
3747 btrfs_set_stack_device_total_bytes(dev_item,
3748 dev->commit_total_bytes);
3749 btrfs_set_stack_device_bytes_used(dev_item,
3750 dev->commit_bytes_used);
3751 btrfs_set_stack_device_io_align(dev_item, dev->io_align);
3752 btrfs_set_stack_device_io_width(dev_item, dev->io_width);
3753 btrfs_set_stack_device_sector_size(dev_item, dev->sector_size);
3754 memcpy(dev_item->uuid, dev->uuid, BTRFS_UUID_SIZE);
3755 memcpy(dev_item->fsid, dev->fs_devices->fsid, BTRFS_FSID_SIZE);
3757 flags = btrfs_super_flags(sb);
3758 btrfs_set_super_flags(sb, flags | BTRFS_HEADER_FLAG_WRITTEN);
3760 ret = btrfs_validate_write_super(fs_info, sb);
3762 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
3763 btrfs_handle_fs_error(fs_info, -EUCLEAN,
3764 "unexpected superblock corruption detected");
3768 ret = write_dev_supers(dev, sb, max_mirrors);
3772 if (total_errors > max_errors) {
3773 btrfs_err(fs_info, "%d errors while writing supers",
3775 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
3777 /* FUA is masked off if unsupported and can't be the reason */
3778 btrfs_handle_fs_error(fs_info, -EIO,
3779 "%d errors while writing supers",
3785 list_for_each_entry(dev, head, dev_list) {
3788 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
3789 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
3792 ret = wait_dev_supers(dev, max_mirrors);
3796 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
3797 if (total_errors > max_errors) {
3798 btrfs_handle_fs_error(fs_info, -EIO,
3799 "%d errors while writing supers",
3806 /* Drop a fs root from the radix tree and free it. */
3807 void btrfs_drop_and_free_fs_root(struct btrfs_fs_info *fs_info,
3808 struct btrfs_root *root)
3810 spin_lock(&fs_info->fs_roots_radix_lock);
3811 radix_tree_delete(&fs_info->fs_roots_radix,
3812 (unsigned long)root->root_key.objectid);
3813 spin_unlock(&fs_info->fs_roots_radix_lock);
3815 if (btrfs_root_refs(&root->root_item) == 0)
3816 synchronize_srcu(&fs_info->subvol_srcu);
3818 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {
3819 btrfs_free_log(NULL, root);
3820 if (root->reloc_root) {
3821 free_extent_buffer(root->reloc_root->node);
3822 free_extent_buffer(root->reloc_root->commit_root);
3823 btrfs_put_fs_root(root->reloc_root);
3824 root->reloc_root = NULL;
3828 if (root->free_ino_pinned)
3829 __btrfs_remove_free_space_cache(root->free_ino_pinned);
3830 if (root->free_ino_ctl)
3831 __btrfs_remove_free_space_cache(root->free_ino_ctl);
3832 btrfs_free_fs_root(root);
3835 void btrfs_free_fs_root(struct btrfs_root *root)
3837 iput(root->ino_cache_inode);
3838 WARN_ON(!RB_EMPTY_ROOT(&root->inode_tree));
3840 free_anon_bdev(root->anon_dev);
3841 if (root->subv_writers)
3842 btrfs_free_subvolume_writers(root->subv_writers);
3843 free_extent_buffer(root->node);
3844 free_extent_buffer(root->commit_root);
3845 kfree(root->free_ino_ctl);
3846 kfree(root->free_ino_pinned);
3847 btrfs_put_fs_root(root);
3850 int btrfs_cleanup_fs_roots(struct btrfs_fs_info *fs_info)
3852 u64 root_objectid = 0;
3853 struct btrfs_root *gang[8];
3856 unsigned int ret = 0;
3860 index = srcu_read_lock(&fs_info->subvol_srcu);
3861 ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
3862 (void **)gang, root_objectid,
3865 srcu_read_unlock(&fs_info->subvol_srcu, index);
3868 root_objectid = gang[ret - 1]->root_key.objectid + 1;
3870 for (i = 0; i < ret; i++) {
3871 /* Avoid to grab roots in dead_roots */
3872 if (btrfs_root_refs(&gang[i]->root_item) == 0) {
3876 /* grab all the search result for later use */
3877 gang[i] = btrfs_grab_fs_root(gang[i]);
3879 srcu_read_unlock(&fs_info->subvol_srcu, index);
3881 for (i = 0; i < ret; i++) {
3884 root_objectid = gang[i]->root_key.objectid;
3885 err = btrfs_orphan_cleanup(gang[i]);
3888 btrfs_put_fs_root(gang[i]);
3893 /* release the uncleaned roots due to error */
3894 for (; i < ret; i++) {
3896 btrfs_put_fs_root(gang[i]);
3901 int btrfs_commit_super(struct btrfs_fs_info *fs_info)
3903 struct btrfs_root *root = fs_info->tree_root;
3904 struct btrfs_trans_handle *trans;
3906 mutex_lock(&fs_info->cleaner_mutex);
3907 btrfs_run_delayed_iputs(fs_info);
3908 mutex_unlock(&fs_info->cleaner_mutex);
3909 wake_up_process(fs_info->cleaner_kthread);
3911 /* wait until ongoing cleanup work done */
3912 down_write(&fs_info->cleanup_work_sem);
3913 up_write(&fs_info->cleanup_work_sem);
3915 trans = btrfs_join_transaction(root);
3917 return PTR_ERR(trans);
3918 return btrfs_commit_transaction(trans);
3921 void close_ctree(struct btrfs_fs_info *fs_info)
3925 set_bit(BTRFS_FS_CLOSING_START, &fs_info->flags);
3927 /* wait for the qgroup rescan worker to stop */
3928 btrfs_qgroup_wait_for_completion(fs_info, false);
3930 /* wait for the uuid_scan task to finish */
3931 down(&fs_info->uuid_tree_rescan_sem);
3932 /* avoid complains from lockdep et al., set sem back to initial state */
3933 up(&fs_info->uuid_tree_rescan_sem);
3935 /* pause restriper - we want to resume on mount */
3936 btrfs_pause_balance(fs_info);
3938 btrfs_dev_replace_suspend_for_unmount(fs_info);
3940 btrfs_scrub_cancel(fs_info);
3942 /* wait for any defraggers to finish */
3943 wait_event(fs_info->transaction_wait,
3944 (atomic_read(&fs_info->defrag_running) == 0));
3946 /* clear out the rbtree of defraggable inodes */
3947 btrfs_cleanup_defrag_inodes(fs_info);
3949 cancel_work_sync(&fs_info->async_reclaim_work);
3951 if (!sb_rdonly(fs_info->sb)) {
3953 * If the cleaner thread is stopped and there are
3954 * block groups queued for removal, the deletion will be
3955 * skipped when we quit the cleaner thread.
3957 btrfs_delete_unused_bgs(fs_info);
3959 ret = btrfs_commit_super(fs_info);
3961 btrfs_err(fs_info, "commit super ret %d", ret);
3964 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state) ||
3965 test_bit(BTRFS_FS_STATE_TRANS_ABORTED, &fs_info->fs_state))
3966 btrfs_error_commit_super(fs_info);
3968 kthread_stop(fs_info->transaction_kthread);
3969 kthread_stop(fs_info->cleaner_kthread);
3971 set_bit(BTRFS_FS_CLOSING_DONE, &fs_info->flags);
3973 btrfs_free_qgroup_config(fs_info);
3974 ASSERT(list_empty(&fs_info->delalloc_roots));
3976 if (percpu_counter_sum(&fs_info->delalloc_bytes)) {
3977 btrfs_info(fs_info, "at unmount delalloc count %lld",
3978 percpu_counter_sum(&fs_info->delalloc_bytes));
3981 btrfs_sysfs_remove_mounted(fs_info);
3982 btrfs_sysfs_remove_fsid(fs_info->fs_devices);
3984 btrfs_free_fs_roots(fs_info);
3986 btrfs_put_block_group_cache(fs_info);
3989 * we must make sure there is not any read request to
3990 * submit after we stopping all workers.
3992 invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
3993 btrfs_stop_all_workers(fs_info);
3995 btrfs_free_block_groups(fs_info);
3997 clear_bit(BTRFS_FS_OPEN, &fs_info->flags);
3998 free_root_pointers(fs_info, 1);
4000 iput(fs_info->btree_inode);
4002 #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
4003 if (btrfs_test_opt(fs_info, CHECK_INTEGRITY))
4004 btrfsic_unmount(fs_info->fs_devices);
4007 btrfs_close_devices(fs_info->fs_devices);
4008 btrfs_mapping_tree_free(&fs_info->mapping_tree);
4010 percpu_counter_destroy(&fs_info->dirty_metadata_bytes);
4011 percpu_counter_destroy(&fs_info->delalloc_bytes);
4012 percpu_counter_destroy(&fs_info->bio_counter);
4013 cleanup_srcu_struct(&fs_info->subvol_srcu);
4015 btrfs_free_stripe_hash_table(fs_info);
4016 btrfs_free_ref_cache(fs_info);
4018 while (!list_empty(&fs_info->pinned_chunks)) {
4019 struct extent_map *em;
4021 em = list_first_entry(&fs_info->pinned_chunks,
4022 struct extent_map, list);
4023 list_del_init(&em->list);
4024 free_extent_map(em);
4028 int btrfs_buffer_uptodate(struct extent_buffer *buf, u64 parent_transid,
4032 struct inode *btree_inode = buf->pages[0]->mapping->host;
4034 ret = extent_buffer_uptodate(buf);
4038 ret = verify_parent_transid(&BTRFS_I(btree_inode)->io_tree, buf,
4039 parent_transid, atomic);
4045 void btrfs_mark_buffer_dirty(struct extent_buffer *buf)
4047 struct btrfs_fs_info *fs_info;
4048 struct btrfs_root *root;
4049 u64 transid = btrfs_header_generation(buf);
4052 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
4054 * This is a fast path so only do this check if we have sanity tests
4055 * enabled. Normal people shouldn't be using umapped buffers as dirty
4056 * outside of the sanity tests.
4058 if (unlikely(test_bit(EXTENT_BUFFER_UNMAPPED, &buf->bflags)))
4061 root = BTRFS_I(buf->pages[0]->mapping->host)->root;
4062 fs_info = root->fs_info;
4063 btrfs_assert_tree_locked(buf);
4064 if (transid != fs_info->generation)
4065 WARN(1, KERN_CRIT "btrfs transid mismatch buffer %llu, found %llu running %llu\n",
4066 buf->start, transid, fs_info->generation);
4067 was_dirty = set_extent_buffer_dirty(buf);
4069 percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
4071 fs_info->dirty_metadata_batch);
4072 #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
4074 * Since btrfs_mark_buffer_dirty() can be called with item pointer set
4075 * but item data not updated.
4076 * So here we should only check item pointers, not item data.
4078 if (btrfs_header_level(buf) == 0 &&
4079 btrfs_check_leaf_relaxed(fs_info, buf)) {
4080 btrfs_print_leaf(buf);
4086 static void __btrfs_btree_balance_dirty(struct btrfs_fs_info *fs_info,
4090 * looks as though older kernels can get into trouble with
4091 * this code, they end up stuck in balance_dirty_pages forever
4095 if (current->flags & PF_MEMALLOC)
4099 btrfs_balance_delayed_items(fs_info);
4101 ret = __percpu_counter_compare(&fs_info->dirty_metadata_bytes,
4102 BTRFS_DIRTY_METADATA_THRESH,
4103 fs_info->dirty_metadata_batch);
4105 balance_dirty_pages_ratelimited(fs_info->btree_inode->i_mapping);
4109 void btrfs_btree_balance_dirty(struct btrfs_fs_info *fs_info)
4111 __btrfs_btree_balance_dirty(fs_info, 1);
4114 void btrfs_btree_balance_dirty_nodelay(struct btrfs_fs_info *fs_info)
4116 __btrfs_btree_balance_dirty(fs_info, 0);
4119 int btrfs_read_buffer(struct extent_buffer *buf, u64 parent_transid, int level,
4120 struct btrfs_key *first_key)
4122 struct btrfs_root *root = BTRFS_I(buf->pages[0]->mapping->host)->root;
4123 struct btrfs_fs_info *fs_info = root->fs_info;
4125 return btree_read_extent_buffer_pages(fs_info, buf, parent_transid,
4129 static void btrfs_error_commit_super(struct btrfs_fs_info *fs_info)
4131 /* cleanup FS via transaction */
4132 btrfs_cleanup_transaction(fs_info);
4134 mutex_lock(&fs_info->cleaner_mutex);
4135 btrfs_run_delayed_iputs(fs_info);
4136 mutex_unlock(&fs_info->cleaner_mutex);
4138 down_write(&fs_info->cleanup_work_sem);
4139 up_write(&fs_info->cleanup_work_sem);
4142 static void btrfs_destroy_ordered_extents(struct btrfs_root *root)
4144 struct btrfs_ordered_extent *ordered;
4146 spin_lock(&root->ordered_extent_lock);
4148 * This will just short circuit the ordered completion stuff which will
4149 * make sure the ordered extent gets properly cleaned up.
4151 list_for_each_entry(ordered, &root->ordered_extents,
4153 set_bit(BTRFS_ORDERED_IOERR, &ordered->flags);
4154 spin_unlock(&root->ordered_extent_lock);
4157 static void btrfs_destroy_all_ordered_extents(struct btrfs_fs_info *fs_info)
4159 struct btrfs_root *root;
4160 struct list_head splice;
4162 INIT_LIST_HEAD(&splice);
4164 spin_lock(&fs_info->ordered_root_lock);
4165 list_splice_init(&fs_info->ordered_roots, &splice);
4166 while (!list_empty(&splice)) {
4167 root = list_first_entry(&splice, struct btrfs_root,
4169 list_move_tail(&root->ordered_root,
4170 &fs_info->ordered_roots);
4172 spin_unlock(&fs_info->ordered_root_lock);
4173 btrfs_destroy_ordered_extents(root);
4176 spin_lock(&fs_info->ordered_root_lock);
4178 spin_unlock(&fs_info->ordered_root_lock);
4181 static int btrfs_destroy_delayed_refs(struct btrfs_transaction *trans,
4182 struct btrfs_fs_info *fs_info)
4184 struct rb_node *node;
4185 struct btrfs_delayed_ref_root *delayed_refs;
4186 struct btrfs_delayed_ref_node *ref;
4189 delayed_refs = &trans->delayed_refs;
4191 spin_lock(&delayed_refs->lock);
4192 if (atomic_read(&delayed_refs->num_entries) == 0) {
4193 spin_unlock(&delayed_refs->lock);
4194 btrfs_info(fs_info, "delayed_refs has NO entry");
4198 while ((node = rb_first(&delayed_refs->href_root)) != NULL) {
4199 struct btrfs_delayed_ref_head *head;
4201 bool pin_bytes = false;
4203 head = rb_entry(node, struct btrfs_delayed_ref_head,
4205 if (!mutex_trylock(&head->mutex)) {
4206 refcount_inc(&head->refs);
4207 spin_unlock(&delayed_refs->lock);
4209 mutex_lock(&head->mutex);
4210 mutex_unlock(&head->mutex);
4211 btrfs_put_delayed_ref_head(head);
4212 spin_lock(&delayed_refs->lock);
4215 spin_lock(&head->lock);
4216 while ((n = rb_first(&head->ref_tree)) != NULL) {
4217 ref = rb_entry(n, struct btrfs_delayed_ref_node,
4220 rb_erase(&ref->ref_node, &head->ref_tree);
4221 RB_CLEAR_NODE(&ref->ref_node);
4222 if (!list_empty(&ref->add_list))
4223 list_del(&ref->add_list);
4224 atomic_dec(&delayed_refs->num_entries);
4225 btrfs_put_delayed_ref(ref);
4227 if (head->must_insert_reserved)
4229 btrfs_free_delayed_extent_op(head->extent_op);
4230 delayed_refs->num_heads--;
4231 if (head->processing == 0)
4232 delayed_refs->num_heads_ready--;
4233 atomic_dec(&delayed_refs->num_entries);
4234 rb_erase(&head->href_node, &delayed_refs->href_root);
4235 RB_CLEAR_NODE(&head->href_node);
4236 spin_unlock(&head->lock);
4237 spin_unlock(&delayed_refs->lock);
4238 mutex_unlock(&head->mutex);
4241 btrfs_pin_extent(fs_info, head->bytenr,
4242 head->num_bytes, 1);
4243 btrfs_put_delayed_ref_head(head);
4245 spin_lock(&delayed_refs->lock);
4248 spin_unlock(&delayed_refs->lock);
4253 static void btrfs_destroy_delalloc_inodes(struct btrfs_root *root)
4255 struct btrfs_inode *btrfs_inode;
4256 struct list_head splice;
4258 INIT_LIST_HEAD(&splice);
4260 spin_lock(&root->delalloc_lock);
4261 list_splice_init(&root->delalloc_inodes, &splice);
4263 while (!list_empty(&splice)) {
4264 struct inode *inode = NULL;
4265 btrfs_inode = list_first_entry(&splice, struct btrfs_inode,
4267 __btrfs_del_delalloc_inode(root, btrfs_inode);
4268 spin_unlock(&root->delalloc_lock);
4271 * Make sure we get a live inode and that it'll not disappear
4274 inode = igrab(&btrfs_inode->vfs_inode);
4276 invalidate_inode_pages2(inode->i_mapping);
4279 spin_lock(&root->delalloc_lock);
4281 spin_unlock(&root->delalloc_lock);
4284 static void btrfs_destroy_all_delalloc_inodes(struct btrfs_fs_info *fs_info)
4286 struct btrfs_root *root;
4287 struct list_head splice;
4289 INIT_LIST_HEAD(&splice);
4291 spin_lock(&fs_info->delalloc_root_lock);
4292 list_splice_init(&fs_info->delalloc_roots, &splice);
4293 while (!list_empty(&splice)) {
4294 root = list_first_entry(&splice, struct btrfs_root,
4296 root = btrfs_grab_fs_root(root);
4298 spin_unlock(&fs_info->delalloc_root_lock);
4300 btrfs_destroy_delalloc_inodes(root);
4301 btrfs_put_fs_root(root);
4303 spin_lock(&fs_info->delalloc_root_lock);
4305 spin_unlock(&fs_info->delalloc_root_lock);
4308 static int btrfs_destroy_marked_extents(struct btrfs_fs_info *fs_info,
4309 struct extent_io_tree *dirty_pages,
4313 struct extent_buffer *eb;
4318 ret = find_first_extent_bit(dirty_pages, start, &start, &end,
4323 clear_extent_bits(dirty_pages, start, end, mark);
4324 while (start <= end) {
4325 eb = find_extent_buffer(fs_info, start);
4326 start += fs_info->nodesize;
4329 wait_on_extent_buffer_writeback(eb);
4331 if (test_and_clear_bit(EXTENT_BUFFER_DIRTY,
4333 clear_extent_buffer_dirty(eb);
4334 free_extent_buffer_stale(eb);
4341 static int btrfs_destroy_pinned_extent(struct btrfs_fs_info *fs_info,
4342 struct extent_io_tree *pinned_extents)
4344 struct extent_io_tree *unpin;
4350 unpin = pinned_extents;
4354 * The btrfs_finish_extent_commit() may get the same range as
4355 * ours between find_first_extent_bit and clear_extent_dirty.
4356 * Hence, hold the unused_bg_unpin_mutex to avoid double unpin
4357 * the same extent range.
4359 mutex_lock(&fs_info->unused_bg_unpin_mutex);
4360 ret = find_first_extent_bit(unpin, 0, &start, &end,
4361 EXTENT_DIRTY, NULL);
4363 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
4367 clear_extent_dirty(unpin, start, end);
4368 btrfs_error_unpin_extent_range(fs_info, start, end);
4369 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
4374 if (unpin == &fs_info->freed_extents[0])
4375 unpin = &fs_info->freed_extents[1];
4377 unpin = &fs_info->freed_extents[0];
4385 static void btrfs_cleanup_bg_io(struct btrfs_block_group_cache *cache)
4387 struct inode *inode;
4389 inode = cache->io_ctl.inode;
4391 invalidate_inode_pages2(inode->i_mapping);
4392 BTRFS_I(inode)->generation = 0;
4393 cache->io_ctl.inode = NULL;
4396 btrfs_put_block_group(cache);
4399 void btrfs_cleanup_dirty_bgs(struct btrfs_transaction *cur_trans,
4400 struct btrfs_fs_info *fs_info)
4402 struct btrfs_block_group_cache *cache;
4404 spin_lock(&cur_trans->dirty_bgs_lock);
4405 while (!list_empty(&cur_trans->dirty_bgs)) {
4406 cache = list_first_entry(&cur_trans->dirty_bgs,
4407 struct btrfs_block_group_cache,
4410 if (!list_empty(&cache->io_list)) {
4411 spin_unlock(&cur_trans->dirty_bgs_lock);
4412 list_del_init(&cache->io_list);
4413 btrfs_cleanup_bg_io(cache);
4414 spin_lock(&cur_trans->dirty_bgs_lock);
4417 list_del_init(&cache->dirty_list);
4418 spin_lock(&cache->lock);
4419 cache->disk_cache_state = BTRFS_DC_ERROR;
4420 spin_unlock(&cache->lock);
4422 spin_unlock(&cur_trans->dirty_bgs_lock);
4423 btrfs_put_block_group(cache);
4424 spin_lock(&cur_trans->dirty_bgs_lock);
4426 spin_unlock(&cur_trans->dirty_bgs_lock);
4429 * Refer to the definition of io_bgs member for details why it's safe
4430 * to use it without any locking
4432 while (!list_empty(&cur_trans->io_bgs)) {
4433 cache = list_first_entry(&cur_trans->io_bgs,
4434 struct btrfs_block_group_cache,
4437 list_del_init(&cache->io_list);
4438 spin_lock(&cache->lock);
4439 cache->disk_cache_state = BTRFS_DC_ERROR;
4440 spin_unlock(&cache->lock);
4441 btrfs_cleanup_bg_io(cache);
4445 void btrfs_cleanup_one_transaction(struct btrfs_transaction *cur_trans,
4446 struct btrfs_fs_info *fs_info)
4448 btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
4449 ASSERT(list_empty(&cur_trans->dirty_bgs));
4450 ASSERT(list_empty(&cur_trans->io_bgs));
4452 btrfs_destroy_delayed_refs(cur_trans, fs_info);
4454 cur_trans->state = TRANS_STATE_COMMIT_START;
4455 wake_up(&fs_info->transaction_blocked_wait);
4457 cur_trans->state = TRANS_STATE_UNBLOCKED;
4458 wake_up(&fs_info->transaction_wait);
4460 btrfs_destroy_delayed_inodes(fs_info);
4461 btrfs_assert_delayed_root_empty(fs_info);
4463 btrfs_destroy_marked_extents(fs_info, &cur_trans->dirty_pages,
4465 btrfs_destroy_pinned_extent(fs_info,
4466 fs_info->pinned_extents);
4468 cur_trans->state =TRANS_STATE_COMPLETED;
4469 wake_up(&cur_trans->commit_wait);
4472 static int btrfs_cleanup_transaction(struct btrfs_fs_info *fs_info)
4474 struct btrfs_transaction *t;
4476 mutex_lock(&fs_info->transaction_kthread_mutex);
4478 spin_lock(&fs_info->trans_lock);
4479 while (!list_empty(&fs_info->trans_list)) {
4480 t = list_first_entry(&fs_info->trans_list,
4481 struct btrfs_transaction, list);
4482 if (t->state >= TRANS_STATE_COMMIT_START) {
4483 refcount_inc(&t->use_count);
4484 spin_unlock(&fs_info->trans_lock);
4485 btrfs_wait_for_commit(fs_info, t->transid);
4486 btrfs_put_transaction(t);
4487 spin_lock(&fs_info->trans_lock);
4490 if (t == fs_info->running_transaction) {
4491 t->state = TRANS_STATE_COMMIT_DOING;
4492 spin_unlock(&fs_info->trans_lock);
4494 * We wait for 0 num_writers since we don't hold a trans
4495 * handle open currently for this transaction.
4497 wait_event(t->writer_wait,
4498 atomic_read(&t->num_writers) == 0);
4500 spin_unlock(&fs_info->trans_lock);
4502 btrfs_cleanup_one_transaction(t, fs_info);
4504 spin_lock(&fs_info->trans_lock);
4505 if (t == fs_info->running_transaction)
4506 fs_info->running_transaction = NULL;
4507 list_del_init(&t->list);
4508 spin_unlock(&fs_info->trans_lock);
4510 btrfs_put_transaction(t);
4511 trace_btrfs_transaction_commit(fs_info->tree_root);
4512 spin_lock(&fs_info->trans_lock);
4514 spin_unlock(&fs_info->trans_lock);
4515 btrfs_destroy_all_ordered_extents(fs_info);
4516 btrfs_destroy_delayed_inodes(fs_info);
4517 btrfs_assert_delayed_root_empty(fs_info);
4518 btrfs_destroy_pinned_extent(fs_info, fs_info->pinned_extents);
4519 btrfs_destroy_all_delalloc_inodes(fs_info);
4520 mutex_unlock(&fs_info->transaction_kthread_mutex);
4525 static const struct extent_io_ops btree_extent_io_ops = {
4526 /* mandatory callbacks */
4527 .submit_bio_hook = btree_submit_bio_hook,
4528 .readpage_end_io_hook = btree_readpage_end_io_hook,
4529 .readpage_io_failed_hook = btree_io_failed_hook,
4531 /* optional callbacks */