2 * Copyright (C) 2007 Oracle. All rights reserved.
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public
6 * License v2 as published by the Free Software Foundation.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * General Public License for more details.
13 * You should have received a copy of the GNU General Public
14 * License along with this program; if not, write to the
15 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16 * Boston, MA 021110-1307, USA.
20 #include <linux/blkdev.h>
21 #include <linux/scatterlist.h>
22 #include <linux/swap.h>
23 #include <linux/radix-tree.h>
24 #include <linux/writeback.h>
25 #include <linux/buffer_head.h>
26 #include <linux/workqueue.h>
27 #include <linux/kthread.h>
28 #include <linux/slab.h>
29 #include <linux/migrate.h>
30 #include <linux/ratelimit.h>
31 #include <linux/uuid.h>
32 #include <linux/semaphore.h>
33 #include <linux/error-injection.h>
34 #include <asm/unaligned.h>
38 #include "transaction.h"
39 #include "btrfs_inode.h"
41 #include "print-tree.h"
44 #include "free-space-cache.h"
45 #include "free-space-tree.h"
46 #include "inode-map.h"
47 #include "check-integrity.h"
48 #include "rcu-string.h"
49 #include "dev-replace.h"
53 #include "compression.h"
54 #include "tree-checker.h"
55 #include "ref-verify.h"
58 #include <asm/cpufeature.h>
61 #define BTRFS_SUPER_FLAG_SUPP (BTRFS_HEADER_FLAG_WRITTEN |\
62 BTRFS_HEADER_FLAG_RELOC |\
63 BTRFS_SUPER_FLAG_ERROR |\
64 BTRFS_SUPER_FLAG_SEEDING |\
65 BTRFS_SUPER_FLAG_METADUMP |\
66 BTRFS_SUPER_FLAG_METADUMP_V2)
68 static const struct extent_io_ops btree_extent_io_ops;
69 static void end_workqueue_fn(struct btrfs_work *work);
70 static void free_fs_root(struct btrfs_root *root);
71 static int btrfs_check_super_valid(struct btrfs_fs_info *fs_info);
72 static void btrfs_destroy_ordered_extents(struct btrfs_root *root);
73 static int btrfs_destroy_delayed_refs(struct btrfs_transaction *trans,
74 struct btrfs_fs_info *fs_info);
75 static void btrfs_destroy_delalloc_inodes(struct btrfs_root *root);
76 static int btrfs_destroy_marked_extents(struct btrfs_fs_info *fs_info,
77 struct extent_io_tree *dirty_pages,
79 static int btrfs_destroy_pinned_extent(struct btrfs_fs_info *fs_info,
80 struct extent_io_tree *pinned_extents);
81 static int btrfs_cleanup_transaction(struct btrfs_fs_info *fs_info);
82 static void btrfs_error_commit_super(struct btrfs_fs_info *fs_info);
85 * btrfs_end_io_wq structs are used to do processing in task context when an IO
86 * is complete. This is used during reads to verify checksums, and it is used
87 * by writes to insert metadata for new file extents after IO is complete.
89 struct btrfs_end_io_wq {
93 struct btrfs_fs_info *info;
95 enum btrfs_wq_endio_type metadata;
96 struct btrfs_work work;
99 static struct kmem_cache *btrfs_end_io_wq_cache;
101 int __init btrfs_end_io_wq_init(void)
103 btrfs_end_io_wq_cache = kmem_cache_create("btrfs_end_io_wq",
104 sizeof(struct btrfs_end_io_wq),
108 if (!btrfs_end_io_wq_cache)
113 void btrfs_end_io_wq_exit(void)
115 kmem_cache_destroy(btrfs_end_io_wq_cache);
119 * async submit bios are used to offload expensive checksumming
120 * onto the worker threads. They checksum file and metadata bios
121 * just before they are sent down the IO stack.
123 struct async_submit_bio {
125 struct btrfs_fs_info *fs_info;
127 extent_submit_bio_hook_t *submit_bio_start;
128 extent_submit_bio_hook_t *submit_bio_done;
130 unsigned long bio_flags;
132 * bio_offset is optional, can be used if the pages in the bio
133 * can't tell us where in the file the bio should go
136 struct btrfs_work work;
141 * Lockdep class keys for extent_buffer->lock's in this root. For a given
142 * eb, the lockdep key is determined by the btrfs_root it belongs to and
143 * the level the eb occupies in the tree.
145 * Different roots are used for different purposes and may nest inside each
146 * other and they require separate keysets. As lockdep keys should be
147 * static, assign keysets according to the purpose of the root as indicated
148 * by btrfs_root->objectid. This ensures that all special purpose roots
149 * have separate keysets.
151 * Lock-nesting across peer nodes is always done with the immediate parent
152 * node locked thus preventing deadlock. As lockdep doesn't know this, use
153 * subclass to avoid triggering lockdep warning in such cases.
155 * The key is set by the readpage_end_io_hook after the buffer has passed
156 * csum validation but before the pages are unlocked. It is also set by
157 * btrfs_init_new_buffer on freshly allocated blocks.
159 * We also add a check to make sure the highest level of the tree is the
160 * same as our lockdep setup here. If BTRFS_MAX_LEVEL changes, this code
161 * needs update as well.
163 #ifdef CONFIG_DEBUG_LOCK_ALLOC
164 # if BTRFS_MAX_LEVEL != 8
168 static struct btrfs_lockdep_keyset {
169 u64 id; /* root objectid */
170 const char *name_stem; /* lock name stem */
171 char names[BTRFS_MAX_LEVEL + 1][20];
172 struct lock_class_key keys[BTRFS_MAX_LEVEL + 1];
173 } btrfs_lockdep_keysets[] = {
174 { .id = BTRFS_ROOT_TREE_OBJECTID, .name_stem = "root" },
175 { .id = BTRFS_EXTENT_TREE_OBJECTID, .name_stem = "extent" },
176 { .id = BTRFS_CHUNK_TREE_OBJECTID, .name_stem = "chunk" },
177 { .id = BTRFS_DEV_TREE_OBJECTID, .name_stem = "dev" },
178 { .id = BTRFS_FS_TREE_OBJECTID, .name_stem = "fs" },
179 { .id = BTRFS_CSUM_TREE_OBJECTID, .name_stem = "csum" },
180 { .id = BTRFS_QUOTA_TREE_OBJECTID, .name_stem = "quota" },
181 { .id = BTRFS_TREE_LOG_OBJECTID, .name_stem = "log" },
182 { .id = BTRFS_TREE_RELOC_OBJECTID, .name_stem = "treloc" },
183 { .id = BTRFS_DATA_RELOC_TREE_OBJECTID, .name_stem = "dreloc" },
184 { .id = BTRFS_UUID_TREE_OBJECTID, .name_stem = "uuid" },
185 { .id = BTRFS_FREE_SPACE_TREE_OBJECTID, .name_stem = "free-space" },
186 { .id = 0, .name_stem = "tree" },
189 void __init btrfs_init_lockdep(void)
193 /* initialize lockdep class names */
194 for (i = 0; i < ARRAY_SIZE(btrfs_lockdep_keysets); i++) {
195 struct btrfs_lockdep_keyset *ks = &btrfs_lockdep_keysets[i];
197 for (j = 0; j < ARRAY_SIZE(ks->names); j++)
198 snprintf(ks->names[j], sizeof(ks->names[j]),
199 "btrfs-%s-%02d", ks->name_stem, j);
203 void btrfs_set_buffer_lockdep_class(u64 objectid, struct extent_buffer *eb,
206 struct btrfs_lockdep_keyset *ks;
208 BUG_ON(level >= ARRAY_SIZE(ks->keys));
210 /* find the matching keyset, id 0 is the default entry */
211 for (ks = btrfs_lockdep_keysets; ks->id; ks++)
212 if (ks->id == objectid)
215 lockdep_set_class_and_name(&eb->lock,
216 &ks->keys[level], ks->names[level]);
222 * extents on the btree inode are pretty simple, there's one extent
223 * that covers the entire device
225 struct extent_map *btree_get_extent(struct btrfs_inode *inode,
226 struct page *page, size_t pg_offset, u64 start, u64 len,
229 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
230 struct extent_map_tree *em_tree = &inode->extent_tree;
231 struct extent_map *em;
234 read_lock(&em_tree->lock);
235 em = lookup_extent_mapping(em_tree, start, len);
237 em->bdev = fs_info->fs_devices->latest_bdev;
238 read_unlock(&em_tree->lock);
241 read_unlock(&em_tree->lock);
243 em = alloc_extent_map();
245 em = ERR_PTR(-ENOMEM);
250 em->block_len = (u64)-1;
252 em->bdev = fs_info->fs_devices->latest_bdev;
254 write_lock(&em_tree->lock);
255 ret = add_extent_mapping(em_tree, em, 0);
256 if (ret == -EEXIST) {
258 em = lookup_extent_mapping(em_tree, start, len);
265 write_unlock(&em_tree->lock);
271 u32 btrfs_csum_data(const char *data, u32 seed, size_t len)
273 return btrfs_crc32c(seed, data, len);
276 void btrfs_csum_final(u32 crc, u8 *result)
278 put_unaligned_le32(~crc, result);
282 * compute the csum for a btree block, and either verify it or write it
283 * into the csum field of the block.
285 static int csum_tree_block(struct btrfs_fs_info *fs_info,
286 struct extent_buffer *buf,
289 u16 csum_size = btrfs_super_csum_size(fs_info->super_copy);
290 char result[BTRFS_CSUM_SIZE];
292 unsigned long cur_len;
293 unsigned long offset = BTRFS_CSUM_SIZE;
295 unsigned long map_start;
296 unsigned long map_len;
300 len = buf->len - offset;
302 err = map_private_extent_buffer(buf, offset, 32,
303 &kaddr, &map_start, &map_len);
306 cur_len = min(len, map_len - (offset - map_start));
307 crc = btrfs_csum_data(kaddr + offset - map_start,
312 memset(result, 0, BTRFS_CSUM_SIZE);
314 btrfs_csum_final(crc, result);
317 if (memcmp_extent_buffer(buf, result, 0, csum_size)) {
320 memcpy(&found, result, csum_size);
322 read_extent_buffer(buf, &val, 0, csum_size);
323 btrfs_warn_rl(fs_info,
324 "%s checksum verify failed on %llu wanted %X found %X level %d",
325 fs_info->sb->s_id, buf->start,
326 val, found, btrfs_header_level(buf));
330 write_extent_buffer(buf, result, 0, csum_size);
337 * we can't consider a given block up to date unless the transid of the
338 * block matches the transid in the parent node's pointer. This is how we
339 * detect blocks that either didn't get written at all or got written
340 * in the wrong place.
342 static int verify_parent_transid(struct extent_io_tree *io_tree,
343 struct extent_buffer *eb, u64 parent_transid,
346 struct extent_state *cached_state = NULL;
348 bool need_lock = (current->journal_info == BTRFS_SEND_TRANS_STUB);
350 if (!parent_transid || btrfs_header_generation(eb) == parent_transid)
357 btrfs_tree_read_lock(eb);
358 btrfs_set_lock_blocking_rw(eb, BTRFS_READ_LOCK);
361 lock_extent_bits(io_tree, eb->start, eb->start + eb->len - 1,
363 if (extent_buffer_uptodate(eb) &&
364 btrfs_header_generation(eb) == parent_transid) {
368 btrfs_err_rl(eb->fs_info,
369 "parent transid verify failed on %llu wanted %llu found %llu",
371 parent_transid, btrfs_header_generation(eb));
375 * Things reading via commit roots that don't have normal protection,
376 * like send, can have a really old block in cache that may point at a
377 * block that has been freed and re-allocated. So don't clear uptodate
378 * if we find an eb that is under IO (dirty/writeback) because we could
379 * end up reading in the stale data and then writing it back out and
380 * making everybody very sad.
382 if (!extent_buffer_under_io(eb))
383 clear_extent_buffer_uptodate(eb);
385 unlock_extent_cached(io_tree, eb->start, eb->start + eb->len - 1,
388 btrfs_tree_read_unlock_blocking(eb);
393 * Return 0 if the superblock checksum type matches the checksum value of that
394 * algorithm. Pass the raw disk superblock data.
396 static int btrfs_check_super_csum(struct btrfs_fs_info *fs_info,
399 struct btrfs_super_block *disk_sb =
400 (struct btrfs_super_block *)raw_disk_sb;
401 u16 csum_type = btrfs_super_csum_type(disk_sb);
404 if (csum_type == BTRFS_CSUM_TYPE_CRC32) {
406 const int csum_size = sizeof(crc);
407 char result[csum_size];
410 * The super_block structure does not span the whole
411 * BTRFS_SUPER_INFO_SIZE range, we expect that the unused space
412 * is filled with zeros and is included in the checksum.
414 crc = btrfs_csum_data(raw_disk_sb + BTRFS_CSUM_SIZE,
415 crc, BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE);
416 btrfs_csum_final(crc, result);
418 if (memcmp(raw_disk_sb, result, csum_size))
422 if (csum_type >= ARRAY_SIZE(btrfs_csum_sizes)) {
423 btrfs_err(fs_info, "unsupported checksum algorithm %u",
432 * helper to read a given tree block, doing retries as required when
433 * the checksums don't match and we have alternate mirrors to try.
435 static int btree_read_extent_buffer_pages(struct btrfs_fs_info *fs_info,
436 struct extent_buffer *eb,
439 struct extent_io_tree *io_tree;
444 int failed_mirror = 0;
446 clear_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags);
447 io_tree = &BTRFS_I(fs_info->btree_inode)->io_tree;
449 ret = read_extent_buffer_pages(io_tree, eb, WAIT_COMPLETE,
452 if (!verify_parent_transid(io_tree, eb,
460 * This buffer's crc is fine, but its contents are corrupted, so
461 * there is no reason to read the other copies, they won't be
464 if (test_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags))
467 num_copies = btrfs_num_copies(fs_info,
472 if (!failed_mirror) {
474 failed_mirror = eb->read_mirror;
478 if (mirror_num == failed_mirror)
481 if (mirror_num > num_copies)
485 if (failed && !ret && failed_mirror)
486 repair_eb_io_failure(fs_info, eb, failed_mirror);
492 * checksum a dirty tree block before IO. This has extra checks to make sure
493 * we only fill in the checksum field in the first page of a multi-page block
496 static int csum_dirty_buffer(struct btrfs_fs_info *fs_info, struct page *page)
498 u64 start = page_offset(page);
500 struct extent_buffer *eb;
502 eb = (struct extent_buffer *)page->private;
503 if (page != eb->pages[0])
506 found_start = btrfs_header_bytenr(eb);
508 * Please do not consolidate these warnings into a single if.
509 * It is useful to know what went wrong.
511 if (WARN_ON(found_start != start))
513 if (WARN_ON(!PageUptodate(page)))
516 ASSERT(memcmp_extent_buffer(eb, fs_info->fsid,
517 btrfs_header_fsid(), BTRFS_FSID_SIZE) == 0);
519 return csum_tree_block(fs_info, eb, 0);
522 static int check_tree_block_fsid(struct btrfs_fs_info *fs_info,
523 struct extent_buffer *eb)
525 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
526 u8 fsid[BTRFS_FSID_SIZE];
529 read_extent_buffer(eb, fsid, btrfs_header_fsid(), BTRFS_FSID_SIZE);
531 if (!memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE)) {
535 fs_devices = fs_devices->seed;
540 static int btree_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
541 u64 phy_offset, struct page *page,
542 u64 start, u64 end, int mirror)
546 struct extent_buffer *eb;
547 struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
548 struct btrfs_fs_info *fs_info = root->fs_info;
555 eb = (struct extent_buffer *)page->private;
557 /* the pending IO might have been the only thing that kept this buffer
558 * in memory. Make sure we have a ref for all this other checks
560 extent_buffer_get(eb);
562 reads_done = atomic_dec_and_test(&eb->io_pages);
566 eb->read_mirror = mirror;
567 if (test_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags)) {
572 found_start = btrfs_header_bytenr(eb);
573 if (found_start != eb->start) {
574 btrfs_err_rl(fs_info, "bad tree block start %llu %llu",
575 found_start, eb->start);
579 if (check_tree_block_fsid(fs_info, eb)) {
580 btrfs_err_rl(fs_info, "bad fsid on block %llu",
585 found_level = btrfs_header_level(eb);
586 if (found_level >= BTRFS_MAX_LEVEL) {
587 btrfs_err(fs_info, "bad tree block level %d",
588 (int)btrfs_header_level(eb));
593 btrfs_set_buffer_lockdep_class(btrfs_header_owner(eb),
596 ret = csum_tree_block(fs_info, eb, 1);
601 * If this is a leaf block and it is corrupt, set the corrupt bit so
602 * that we don't try and read the other copies of this block, just
605 if (found_level == 0 && btrfs_check_leaf_full(root, eb)) {
606 set_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags);
610 if (found_level > 0 && btrfs_check_node(root, eb))
614 set_extent_buffer_uptodate(eb);
617 test_and_clear_bit(EXTENT_BUFFER_READAHEAD, &eb->bflags))
618 btree_readahead_hook(eb, ret);
622 * our io error hook is going to dec the io pages
623 * again, we have to make sure it has something
626 atomic_inc(&eb->io_pages);
627 clear_extent_buffer_uptodate(eb);
629 free_extent_buffer(eb);
634 static int btree_io_failed_hook(struct page *page, int failed_mirror)
636 struct extent_buffer *eb;
638 eb = (struct extent_buffer *)page->private;
639 set_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
640 eb->read_mirror = failed_mirror;
641 atomic_dec(&eb->io_pages);
642 if (test_and_clear_bit(EXTENT_BUFFER_READAHEAD, &eb->bflags))
643 btree_readahead_hook(eb, -EIO);
644 return -EIO; /* we fixed nothing */
647 static void end_workqueue_bio(struct bio *bio)
649 struct btrfs_end_io_wq *end_io_wq = bio->bi_private;
650 struct btrfs_fs_info *fs_info;
651 struct btrfs_workqueue *wq;
652 btrfs_work_func_t func;
654 fs_info = end_io_wq->info;
655 end_io_wq->status = bio->bi_status;
657 if (bio_op(bio) == REQ_OP_WRITE) {
658 if (end_io_wq->metadata == BTRFS_WQ_ENDIO_METADATA) {
659 wq = fs_info->endio_meta_write_workers;
660 func = btrfs_endio_meta_write_helper;
661 } else if (end_io_wq->metadata == BTRFS_WQ_ENDIO_FREE_SPACE) {
662 wq = fs_info->endio_freespace_worker;
663 func = btrfs_freespace_write_helper;
664 } else if (end_io_wq->metadata == BTRFS_WQ_ENDIO_RAID56) {
665 wq = fs_info->endio_raid56_workers;
666 func = btrfs_endio_raid56_helper;
668 wq = fs_info->endio_write_workers;
669 func = btrfs_endio_write_helper;
672 if (unlikely(end_io_wq->metadata ==
673 BTRFS_WQ_ENDIO_DIO_REPAIR)) {
674 wq = fs_info->endio_repair_workers;
675 func = btrfs_endio_repair_helper;
676 } else if (end_io_wq->metadata == BTRFS_WQ_ENDIO_RAID56) {
677 wq = fs_info->endio_raid56_workers;
678 func = btrfs_endio_raid56_helper;
679 } else if (end_io_wq->metadata) {
680 wq = fs_info->endio_meta_workers;
681 func = btrfs_endio_meta_helper;
683 wq = fs_info->endio_workers;
684 func = btrfs_endio_helper;
688 btrfs_init_work(&end_io_wq->work, func, end_workqueue_fn, NULL, NULL);
689 btrfs_queue_work(wq, &end_io_wq->work);
692 blk_status_t btrfs_bio_wq_end_io(struct btrfs_fs_info *info, struct bio *bio,
693 enum btrfs_wq_endio_type metadata)
695 struct btrfs_end_io_wq *end_io_wq;
697 end_io_wq = kmem_cache_alloc(btrfs_end_io_wq_cache, GFP_NOFS);
699 return BLK_STS_RESOURCE;
701 end_io_wq->private = bio->bi_private;
702 end_io_wq->end_io = bio->bi_end_io;
703 end_io_wq->info = info;
704 end_io_wq->status = 0;
705 end_io_wq->bio = bio;
706 end_io_wq->metadata = metadata;
708 bio->bi_private = end_io_wq;
709 bio->bi_end_io = end_workqueue_bio;
713 static void run_one_async_start(struct btrfs_work *work)
715 struct async_submit_bio *async;
718 async = container_of(work, struct async_submit_bio, work);
719 ret = async->submit_bio_start(async->private_data, async->bio,
720 async->mirror_num, async->bio_flags,
726 static void run_one_async_done(struct btrfs_work *work)
728 struct async_submit_bio *async;
730 async = container_of(work, struct async_submit_bio, work);
732 /* If an error occurred we just want to clean up the bio and move on */
734 async->bio->bi_status = async->status;
735 bio_endio(async->bio);
739 async->submit_bio_done(async->private_data, async->bio, async->mirror_num,
740 async->bio_flags, async->bio_offset);
743 static void run_one_async_free(struct btrfs_work *work)
745 struct async_submit_bio *async;
747 async = container_of(work, struct async_submit_bio, work);
751 blk_status_t btrfs_wq_submit_bio(struct btrfs_fs_info *fs_info, struct bio *bio,
752 int mirror_num, unsigned long bio_flags,
753 u64 bio_offset, void *private_data,
754 extent_submit_bio_hook_t *submit_bio_start,
755 extent_submit_bio_hook_t *submit_bio_done)
757 struct async_submit_bio *async;
759 async = kmalloc(sizeof(*async), GFP_NOFS);
761 return BLK_STS_RESOURCE;
763 async->private_data = private_data;
764 async->fs_info = fs_info;
766 async->mirror_num = mirror_num;
767 async->submit_bio_start = submit_bio_start;
768 async->submit_bio_done = submit_bio_done;
770 btrfs_init_work(&async->work, btrfs_worker_helper, run_one_async_start,
771 run_one_async_done, run_one_async_free);
773 async->bio_flags = bio_flags;
774 async->bio_offset = bio_offset;
778 if (op_is_sync(bio->bi_opf))
779 btrfs_set_work_high_priority(&async->work);
781 btrfs_queue_work(fs_info->workers, &async->work);
785 static blk_status_t btree_csum_one_bio(struct bio *bio)
787 struct bio_vec *bvec;
788 struct btrfs_root *root;
791 ASSERT(!bio_flagged(bio, BIO_CLONED));
792 bio_for_each_segment_all(bvec, bio, i) {
793 root = BTRFS_I(bvec->bv_page->mapping->host)->root;
794 ret = csum_dirty_buffer(root->fs_info, bvec->bv_page);
799 return errno_to_blk_status(ret);
802 static blk_status_t __btree_submit_bio_start(void *private_data, struct bio *bio,
803 int mirror_num, unsigned long bio_flags,
807 * when we're called for a write, we're already in the async
808 * submission context. Just jump into btrfs_map_bio
810 return btree_csum_one_bio(bio);
813 static blk_status_t __btree_submit_bio_done(void *private_data, struct bio *bio,
814 int mirror_num, unsigned long bio_flags,
817 struct inode *inode = private_data;
821 * when we're called for a write, we're already in the async
822 * submission context. Just jump into btrfs_map_bio
824 ret = btrfs_map_bio(btrfs_sb(inode->i_sb), bio, mirror_num, 1);
826 bio->bi_status = ret;
832 static int check_async_write(struct btrfs_inode *bi)
834 if (atomic_read(&bi->sync_writers))
837 if (static_cpu_has(X86_FEATURE_XMM4_2))
843 static blk_status_t btree_submit_bio_hook(void *private_data, struct bio *bio,
844 int mirror_num, unsigned long bio_flags,
847 struct inode *inode = private_data;
848 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
849 int async = check_async_write(BTRFS_I(inode));
852 if (bio_op(bio) != REQ_OP_WRITE) {
854 * called for a read, do the setup so that checksum validation
855 * can happen in the async kernel threads
857 ret = btrfs_bio_wq_end_io(fs_info, bio,
858 BTRFS_WQ_ENDIO_METADATA);
861 ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
863 ret = btree_csum_one_bio(bio);
866 ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
869 * kthread helpers are used to submit writes so that
870 * checksumming can happen in parallel across all CPUs
872 ret = btrfs_wq_submit_bio(fs_info, bio, mirror_num, 0,
873 bio_offset, private_data,
874 __btree_submit_bio_start,
875 __btree_submit_bio_done);
883 bio->bi_status = ret;
888 #ifdef CONFIG_MIGRATION
889 static int btree_migratepage(struct address_space *mapping,
890 struct page *newpage, struct page *page,
891 enum migrate_mode mode)
894 * we can't safely write a btree page from here,
895 * we haven't done the locking hook
900 * Buffers may be managed in a filesystem specific way.
901 * We must have no buffers or drop them.
903 if (page_has_private(page) &&
904 !try_to_release_page(page, GFP_KERNEL))
906 return migrate_page(mapping, newpage, page, mode);
911 static int btree_writepages(struct address_space *mapping,
912 struct writeback_control *wbc)
914 struct btrfs_fs_info *fs_info;
917 if (wbc->sync_mode == WB_SYNC_NONE) {
919 if (wbc->for_kupdate)
922 fs_info = BTRFS_I(mapping->host)->root->fs_info;
923 /* this is a bit racy, but that's ok */
924 ret = percpu_counter_compare(&fs_info->dirty_metadata_bytes,
925 BTRFS_DIRTY_METADATA_THRESH);
929 return btree_write_cache_pages(mapping, wbc);
932 static int btree_readpage(struct file *file, struct page *page)
934 struct extent_io_tree *tree;
935 tree = &BTRFS_I(page->mapping->host)->io_tree;
936 return extent_read_full_page(tree, page, btree_get_extent, 0);
939 static int btree_releasepage(struct page *page, gfp_t gfp_flags)
941 if (PageWriteback(page) || PageDirty(page))
944 return try_release_extent_buffer(page);
947 static void btree_invalidatepage(struct page *page, unsigned int offset,
950 struct extent_io_tree *tree;
951 tree = &BTRFS_I(page->mapping->host)->io_tree;
952 extent_invalidatepage(tree, page, offset);
953 btree_releasepage(page, GFP_NOFS);
954 if (PagePrivate(page)) {
955 btrfs_warn(BTRFS_I(page->mapping->host)->root->fs_info,
956 "page private not zero on page %llu",
957 (unsigned long long)page_offset(page));
958 ClearPagePrivate(page);
959 set_page_private(page, 0);
964 static int btree_set_page_dirty(struct page *page)
967 struct extent_buffer *eb;
969 BUG_ON(!PagePrivate(page));
970 eb = (struct extent_buffer *)page->private;
972 BUG_ON(!test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
973 BUG_ON(!atomic_read(&eb->refs));
974 btrfs_assert_tree_locked(eb);
976 return __set_page_dirty_nobuffers(page);
979 static const struct address_space_operations btree_aops = {
980 .readpage = btree_readpage,
981 .writepages = btree_writepages,
982 .releasepage = btree_releasepage,
983 .invalidatepage = btree_invalidatepage,
984 #ifdef CONFIG_MIGRATION
985 .migratepage = btree_migratepage,
987 .set_page_dirty = btree_set_page_dirty,
990 void readahead_tree_block(struct btrfs_fs_info *fs_info, u64 bytenr)
992 struct extent_buffer *buf = NULL;
993 struct inode *btree_inode = fs_info->btree_inode;
995 buf = btrfs_find_create_tree_block(fs_info, bytenr);
998 read_extent_buffer_pages(&BTRFS_I(btree_inode)->io_tree,
1000 free_extent_buffer(buf);
1003 int reada_tree_block_flagged(struct btrfs_fs_info *fs_info, u64 bytenr,
1004 int mirror_num, struct extent_buffer **eb)
1006 struct extent_buffer *buf = NULL;
1007 struct inode *btree_inode = fs_info->btree_inode;
1008 struct extent_io_tree *io_tree = &BTRFS_I(btree_inode)->io_tree;
1011 buf = btrfs_find_create_tree_block(fs_info, bytenr);
1015 set_bit(EXTENT_BUFFER_READAHEAD, &buf->bflags);
1017 ret = read_extent_buffer_pages(io_tree, buf, WAIT_PAGE_LOCK,
1020 free_extent_buffer(buf);
1024 if (test_bit(EXTENT_BUFFER_CORRUPT, &buf->bflags)) {
1025 free_extent_buffer(buf);
1027 } else if (extent_buffer_uptodate(buf)) {
1030 free_extent_buffer(buf);
1035 struct extent_buffer *btrfs_find_create_tree_block(
1036 struct btrfs_fs_info *fs_info,
1039 if (btrfs_is_testing(fs_info))
1040 return alloc_test_extent_buffer(fs_info, bytenr);
1041 return alloc_extent_buffer(fs_info, bytenr);
1045 int btrfs_write_tree_block(struct extent_buffer *buf)
1047 return filemap_fdatawrite_range(buf->pages[0]->mapping, buf->start,
1048 buf->start + buf->len - 1);
1051 void btrfs_wait_tree_block_writeback(struct extent_buffer *buf)
1053 filemap_fdatawait_range(buf->pages[0]->mapping,
1054 buf->start, buf->start + buf->len - 1);
1057 struct extent_buffer *read_tree_block(struct btrfs_fs_info *fs_info, u64 bytenr,
1060 struct extent_buffer *buf = NULL;
1063 buf = btrfs_find_create_tree_block(fs_info, bytenr);
1067 ret = btree_read_extent_buffer_pages(fs_info, buf, parent_transid);
1069 free_extent_buffer(buf);
1070 return ERR_PTR(ret);
1076 void clean_tree_block(struct btrfs_fs_info *fs_info,
1077 struct extent_buffer *buf)
1079 if (btrfs_header_generation(buf) ==
1080 fs_info->running_transaction->transid) {
1081 btrfs_assert_tree_locked(buf);
1083 if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &buf->bflags)) {
1084 percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
1086 fs_info->dirty_metadata_batch);
1087 /* ugh, clear_extent_buffer_dirty needs to lock the page */
1088 btrfs_set_lock_blocking(buf);
1089 clear_extent_buffer_dirty(buf);
1094 static struct btrfs_subvolume_writers *btrfs_alloc_subvolume_writers(void)
1096 struct btrfs_subvolume_writers *writers;
1099 writers = kmalloc(sizeof(*writers), GFP_NOFS);
1101 return ERR_PTR(-ENOMEM);
1103 ret = percpu_counter_init(&writers->counter, 0, GFP_KERNEL);
1106 return ERR_PTR(ret);
1109 init_waitqueue_head(&writers->wait);
1114 btrfs_free_subvolume_writers(struct btrfs_subvolume_writers *writers)
1116 percpu_counter_destroy(&writers->counter);
1120 static void __setup_root(struct btrfs_root *root, struct btrfs_fs_info *fs_info,
1123 bool dummy = test_bit(BTRFS_FS_STATE_DUMMY_FS_INFO, &fs_info->fs_state);
1125 root->commit_root = NULL;
1127 root->orphan_cleanup_state = 0;
1129 root->objectid = objectid;
1130 root->last_trans = 0;
1131 root->highest_objectid = 0;
1132 root->nr_delalloc_inodes = 0;
1133 root->nr_ordered_extents = 0;
1135 root->inode_tree = RB_ROOT;
1136 INIT_RADIX_TREE(&root->delayed_nodes_tree, GFP_ATOMIC);
1137 root->block_rsv = NULL;
1138 root->orphan_block_rsv = NULL;
1140 INIT_LIST_HEAD(&root->dirty_list);
1141 INIT_LIST_HEAD(&root->root_list);
1142 INIT_LIST_HEAD(&root->delalloc_inodes);
1143 INIT_LIST_HEAD(&root->delalloc_root);
1144 INIT_LIST_HEAD(&root->ordered_extents);
1145 INIT_LIST_HEAD(&root->ordered_root);
1146 INIT_LIST_HEAD(&root->logged_list[0]);
1147 INIT_LIST_HEAD(&root->logged_list[1]);
1148 spin_lock_init(&root->orphan_lock);
1149 spin_lock_init(&root->inode_lock);
1150 spin_lock_init(&root->delalloc_lock);
1151 spin_lock_init(&root->ordered_extent_lock);
1152 spin_lock_init(&root->accounting_lock);
1153 spin_lock_init(&root->log_extents_lock[0]);
1154 spin_lock_init(&root->log_extents_lock[1]);
1155 mutex_init(&root->objectid_mutex);
1156 mutex_init(&root->log_mutex);
1157 mutex_init(&root->ordered_extent_mutex);
1158 mutex_init(&root->delalloc_mutex);
1159 init_waitqueue_head(&root->log_writer_wait);
1160 init_waitqueue_head(&root->log_commit_wait[0]);
1161 init_waitqueue_head(&root->log_commit_wait[1]);
1162 INIT_LIST_HEAD(&root->log_ctxs[0]);
1163 INIT_LIST_HEAD(&root->log_ctxs[1]);
1164 atomic_set(&root->log_commit[0], 0);
1165 atomic_set(&root->log_commit[1], 0);
1166 atomic_set(&root->log_writers, 0);
1167 atomic_set(&root->log_batch, 0);
1168 atomic_set(&root->orphan_inodes, 0);
1169 refcount_set(&root->refs, 1);
1170 atomic_set(&root->will_be_snapshotted, 0);
1171 atomic64_set(&root->qgroup_meta_rsv, 0);
1172 root->log_transid = 0;
1173 root->log_transid_committed = -1;
1174 root->last_log_commit = 0;
1176 extent_io_tree_init(&root->dirty_log_pages, NULL);
1178 memset(&root->root_key, 0, sizeof(root->root_key));
1179 memset(&root->root_item, 0, sizeof(root->root_item));
1180 memset(&root->defrag_progress, 0, sizeof(root->defrag_progress));
1182 root->defrag_trans_start = fs_info->generation;
1184 root->defrag_trans_start = 0;
1185 root->root_key.objectid = objectid;
1188 spin_lock_init(&root->root_item_lock);
1191 static struct btrfs_root *btrfs_alloc_root(struct btrfs_fs_info *fs_info,
1194 struct btrfs_root *root = kzalloc(sizeof(*root), flags);
1196 root->fs_info = fs_info;
1200 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
1201 /* Should only be used by the testing infrastructure */
1202 struct btrfs_root *btrfs_alloc_dummy_root(struct btrfs_fs_info *fs_info)
1204 struct btrfs_root *root;
1207 return ERR_PTR(-EINVAL);
1209 root = btrfs_alloc_root(fs_info, GFP_KERNEL);
1211 return ERR_PTR(-ENOMEM);
1213 /* We don't use the stripesize in selftest, set it as sectorsize */
1214 __setup_root(root, fs_info, BTRFS_ROOT_TREE_OBJECTID);
1215 root->alloc_bytenr = 0;
1221 struct btrfs_root *btrfs_create_tree(struct btrfs_trans_handle *trans,
1222 struct btrfs_fs_info *fs_info,
1225 struct extent_buffer *leaf;
1226 struct btrfs_root *tree_root = fs_info->tree_root;
1227 struct btrfs_root *root;
1228 struct btrfs_key key;
1230 uuid_le uuid = NULL_UUID_LE;
1232 root = btrfs_alloc_root(fs_info, GFP_KERNEL);
1234 return ERR_PTR(-ENOMEM);
1236 __setup_root(root, fs_info, objectid);
1237 root->root_key.objectid = objectid;
1238 root->root_key.type = BTRFS_ROOT_ITEM_KEY;
1239 root->root_key.offset = 0;
1241 leaf = btrfs_alloc_tree_block(trans, root, 0, objectid, NULL, 0, 0, 0);
1243 ret = PTR_ERR(leaf);
1248 memzero_extent_buffer(leaf, 0, sizeof(struct btrfs_header));
1249 btrfs_set_header_bytenr(leaf, leaf->start);
1250 btrfs_set_header_generation(leaf, trans->transid);
1251 btrfs_set_header_backref_rev(leaf, BTRFS_MIXED_BACKREF_REV);
1252 btrfs_set_header_owner(leaf, objectid);
1255 write_extent_buffer_fsid(leaf, fs_info->fsid);
1256 write_extent_buffer_chunk_tree_uuid(leaf, fs_info->chunk_tree_uuid);
1257 btrfs_mark_buffer_dirty(leaf);
1259 root->commit_root = btrfs_root_node(root);
1260 set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
1262 root->root_item.flags = 0;
1263 root->root_item.byte_limit = 0;
1264 btrfs_set_root_bytenr(&root->root_item, leaf->start);
1265 btrfs_set_root_generation(&root->root_item, trans->transid);
1266 btrfs_set_root_level(&root->root_item, 0);
1267 btrfs_set_root_refs(&root->root_item, 1);
1268 btrfs_set_root_used(&root->root_item, leaf->len);
1269 btrfs_set_root_last_snapshot(&root->root_item, 0);
1270 btrfs_set_root_dirid(&root->root_item, 0);
1271 if (is_fstree(objectid))
1273 memcpy(root->root_item.uuid, uuid.b, BTRFS_UUID_SIZE);
1274 root->root_item.drop_level = 0;
1276 key.objectid = objectid;
1277 key.type = BTRFS_ROOT_ITEM_KEY;
1279 ret = btrfs_insert_root(trans, tree_root, &key, &root->root_item);
1283 btrfs_tree_unlock(leaf);
1289 btrfs_tree_unlock(leaf);
1290 free_extent_buffer(root->commit_root);
1291 free_extent_buffer(leaf);
1295 return ERR_PTR(ret);
1298 static struct btrfs_root *alloc_log_tree(struct btrfs_trans_handle *trans,
1299 struct btrfs_fs_info *fs_info)
1301 struct btrfs_root *root;
1302 struct extent_buffer *leaf;
1304 root = btrfs_alloc_root(fs_info, GFP_NOFS);
1306 return ERR_PTR(-ENOMEM);
1308 __setup_root(root, fs_info, BTRFS_TREE_LOG_OBJECTID);
1310 root->root_key.objectid = BTRFS_TREE_LOG_OBJECTID;
1311 root->root_key.type = BTRFS_ROOT_ITEM_KEY;
1312 root->root_key.offset = BTRFS_TREE_LOG_OBJECTID;
1315 * DON'T set REF_COWS for log trees
1317 * log trees do not get reference counted because they go away
1318 * before a real commit is actually done. They do store pointers
1319 * to file data extents, and those reference counts still get
1320 * updated (along with back refs to the log tree).
1323 leaf = btrfs_alloc_tree_block(trans, root, 0, BTRFS_TREE_LOG_OBJECTID,
1327 return ERR_CAST(leaf);
1330 memzero_extent_buffer(leaf, 0, sizeof(struct btrfs_header));
1331 btrfs_set_header_bytenr(leaf, leaf->start);
1332 btrfs_set_header_generation(leaf, trans->transid);
1333 btrfs_set_header_backref_rev(leaf, BTRFS_MIXED_BACKREF_REV);
1334 btrfs_set_header_owner(leaf, BTRFS_TREE_LOG_OBJECTID);
1337 write_extent_buffer_fsid(root->node, fs_info->fsid);
1338 btrfs_mark_buffer_dirty(root->node);
1339 btrfs_tree_unlock(root->node);
1343 int btrfs_init_log_root_tree(struct btrfs_trans_handle *trans,
1344 struct btrfs_fs_info *fs_info)
1346 struct btrfs_root *log_root;
1348 log_root = alloc_log_tree(trans, fs_info);
1349 if (IS_ERR(log_root))
1350 return PTR_ERR(log_root);
1351 WARN_ON(fs_info->log_root_tree);
1352 fs_info->log_root_tree = log_root;
1356 int btrfs_add_log_tree(struct btrfs_trans_handle *trans,
1357 struct btrfs_root *root)
1359 struct btrfs_fs_info *fs_info = root->fs_info;
1360 struct btrfs_root *log_root;
1361 struct btrfs_inode_item *inode_item;
1363 log_root = alloc_log_tree(trans, fs_info);
1364 if (IS_ERR(log_root))
1365 return PTR_ERR(log_root);
1367 log_root->last_trans = trans->transid;
1368 log_root->root_key.offset = root->root_key.objectid;
1370 inode_item = &log_root->root_item.inode;
1371 btrfs_set_stack_inode_generation(inode_item, 1);
1372 btrfs_set_stack_inode_size(inode_item, 3);
1373 btrfs_set_stack_inode_nlink(inode_item, 1);
1374 btrfs_set_stack_inode_nbytes(inode_item,
1376 btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
1378 btrfs_set_root_node(&log_root->root_item, log_root->node);
1380 WARN_ON(root->log_root);
1381 root->log_root = log_root;
1382 root->log_transid = 0;
1383 root->log_transid_committed = -1;
1384 root->last_log_commit = 0;
1388 static struct btrfs_root *btrfs_read_tree_root(struct btrfs_root *tree_root,
1389 struct btrfs_key *key)
1391 struct btrfs_root *root;
1392 struct btrfs_fs_info *fs_info = tree_root->fs_info;
1393 struct btrfs_path *path;
1397 path = btrfs_alloc_path();
1399 return ERR_PTR(-ENOMEM);
1401 root = btrfs_alloc_root(fs_info, GFP_NOFS);
1407 __setup_root(root, fs_info, key->objectid);
1409 ret = btrfs_find_root(tree_root, key, path,
1410 &root->root_item, &root->root_key);
1417 generation = btrfs_root_generation(&root->root_item);
1418 root->node = read_tree_block(fs_info,
1419 btrfs_root_bytenr(&root->root_item),
1421 if (IS_ERR(root->node)) {
1422 ret = PTR_ERR(root->node);
1424 } else if (!btrfs_buffer_uptodate(root->node, generation, 0)) {
1426 free_extent_buffer(root->node);
1429 root->commit_root = btrfs_root_node(root);
1431 btrfs_free_path(path);
1437 root = ERR_PTR(ret);
1441 struct btrfs_root *btrfs_read_fs_root(struct btrfs_root *tree_root,
1442 struct btrfs_key *location)
1444 struct btrfs_root *root;
1446 root = btrfs_read_tree_root(tree_root, location);
1450 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
1451 set_bit(BTRFS_ROOT_REF_COWS, &root->state);
1452 btrfs_check_and_init_root_item(&root->root_item);
1458 int btrfs_init_fs_root(struct btrfs_root *root)
1461 struct btrfs_subvolume_writers *writers;
1463 root->free_ino_ctl = kzalloc(sizeof(*root->free_ino_ctl), GFP_NOFS);
1464 root->free_ino_pinned = kzalloc(sizeof(*root->free_ino_pinned),
1466 if (!root->free_ino_pinned || !root->free_ino_ctl) {
1471 writers = btrfs_alloc_subvolume_writers();
1472 if (IS_ERR(writers)) {
1473 ret = PTR_ERR(writers);
1476 root->subv_writers = writers;
1478 btrfs_init_free_ino_ctl(root);
1479 spin_lock_init(&root->ino_cache_lock);
1480 init_waitqueue_head(&root->ino_cache_wait);
1482 ret = get_anon_bdev(&root->anon_dev);
1486 mutex_lock(&root->objectid_mutex);
1487 ret = btrfs_find_highest_objectid(root,
1488 &root->highest_objectid);
1490 mutex_unlock(&root->objectid_mutex);
1494 ASSERT(root->highest_objectid <= BTRFS_LAST_FREE_OBJECTID);
1496 mutex_unlock(&root->objectid_mutex);
1500 /* the caller is responsible to call free_fs_root */
1504 struct btrfs_root *btrfs_lookup_fs_root(struct btrfs_fs_info *fs_info,
1507 struct btrfs_root *root;
1509 spin_lock(&fs_info->fs_roots_radix_lock);
1510 root = radix_tree_lookup(&fs_info->fs_roots_radix,
1511 (unsigned long)root_id);
1512 spin_unlock(&fs_info->fs_roots_radix_lock);
1516 int btrfs_insert_fs_root(struct btrfs_fs_info *fs_info,
1517 struct btrfs_root *root)
1521 ret = radix_tree_preload(GFP_NOFS);
1525 spin_lock(&fs_info->fs_roots_radix_lock);
1526 ret = radix_tree_insert(&fs_info->fs_roots_radix,
1527 (unsigned long)root->root_key.objectid,
1530 set_bit(BTRFS_ROOT_IN_RADIX, &root->state);
1531 spin_unlock(&fs_info->fs_roots_radix_lock);
1532 radix_tree_preload_end();
1537 struct btrfs_root *btrfs_get_fs_root(struct btrfs_fs_info *fs_info,
1538 struct btrfs_key *location,
1541 struct btrfs_root *root;
1542 struct btrfs_path *path;
1543 struct btrfs_key key;
1546 if (location->objectid == BTRFS_ROOT_TREE_OBJECTID)
1547 return fs_info->tree_root;
1548 if (location->objectid == BTRFS_EXTENT_TREE_OBJECTID)
1549 return fs_info->extent_root;
1550 if (location->objectid == BTRFS_CHUNK_TREE_OBJECTID)
1551 return fs_info->chunk_root;
1552 if (location->objectid == BTRFS_DEV_TREE_OBJECTID)
1553 return fs_info->dev_root;
1554 if (location->objectid == BTRFS_CSUM_TREE_OBJECTID)
1555 return fs_info->csum_root;
1556 if (location->objectid == BTRFS_QUOTA_TREE_OBJECTID)
1557 return fs_info->quota_root ? fs_info->quota_root :
1559 if (location->objectid == BTRFS_UUID_TREE_OBJECTID)
1560 return fs_info->uuid_root ? fs_info->uuid_root :
1562 if (location->objectid == BTRFS_FREE_SPACE_TREE_OBJECTID)
1563 return fs_info->free_space_root ? fs_info->free_space_root :
1566 root = btrfs_lookup_fs_root(fs_info, location->objectid);
1568 if (check_ref && btrfs_root_refs(&root->root_item) == 0)
1569 return ERR_PTR(-ENOENT);
1573 root = btrfs_read_fs_root(fs_info->tree_root, location);
1577 if (check_ref && btrfs_root_refs(&root->root_item) == 0) {
1582 ret = btrfs_init_fs_root(root);
1586 path = btrfs_alloc_path();
1591 key.objectid = BTRFS_ORPHAN_OBJECTID;
1592 key.type = BTRFS_ORPHAN_ITEM_KEY;
1593 key.offset = location->objectid;
1595 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
1596 btrfs_free_path(path);
1600 set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state);
1602 ret = btrfs_insert_fs_root(fs_info, root);
1604 if (ret == -EEXIST) {
1613 return ERR_PTR(ret);
1616 static int btrfs_congested_fn(void *congested_data, int bdi_bits)
1618 struct btrfs_fs_info *info = (struct btrfs_fs_info *)congested_data;
1620 struct btrfs_device *device;
1621 struct backing_dev_info *bdi;
1624 list_for_each_entry_rcu(device, &info->fs_devices->devices, dev_list) {
1627 bdi = device->bdev->bd_bdi;
1628 if (bdi_congested(bdi, bdi_bits)) {
1638 * called by the kthread helper functions to finally call the bio end_io
1639 * functions. This is where read checksum verification actually happens
1641 static void end_workqueue_fn(struct btrfs_work *work)
1644 struct btrfs_end_io_wq *end_io_wq;
1646 end_io_wq = container_of(work, struct btrfs_end_io_wq, work);
1647 bio = end_io_wq->bio;
1649 bio->bi_status = end_io_wq->status;
1650 bio->bi_private = end_io_wq->private;
1651 bio->bi_end_io = end_io_wq->end_io;
1652 kmem_cache_free(btrfs_end_io_wq_cache, end_io_wq);
1656 static int cleaner_kthread(void *arg)
1658 struct btrfs_root *root = arg;
1659 struct btrfs_fs_info *fs_info = root->fs_info;
1661 struct btrfs_trans_handle *trans;
1666 /* Make the cleaner go to sleep early. */
1667 if (btrfs_need_cleaner_sleep(fs_info))
1671 * Do not do anything if we might cause open_ctree() to block
1672 * before we have finished mounting the filesystem.
1674 if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
1677 if (!mutex_trylock(&fs_info->cleaner_mutex))
1681 * Avoid the problem that we change the status of the fs
1682 * during the above check and trylock.
1684 if (btrfs_need_cleaner_sleep(fs_info)) {
1685 mutex_unlock(&fs_info->cleaner_mutex);
1689 mutex_lock(&fs_info->cleaner_delayed_iput_mutex);
1690 btrfs_run_delayed_iputs(fs_info);
1691 mutex_unlock(&fs_info->cleaner_delayed_iput_mutex);
1693 again = btrfs_clean_one_deleted_snapshot(root);
1694 mutex_unlock(&fs_info->cleaner_mutex);
1697 * The defragger has dealt with the R/O remount and umount,
1698 * needn't do anything special here.
1700 btrfs_run_defrag_inodes(fs_info);
1703 * Acquires fs_info->delete_unused_bgs_mutex to avoid racing
1704 * with relocation (btrfs_relocate_chunk) and relocation
1705 * acquires fs_info->cleaner_mutex (btrfs_relocate_block_group)
1706 * after acquiring fs_info->delete_unused_bgs_mutex. So we
1707 * can't hold, nor need to, fs_info->cleaner_mutex when deleting
1708 * unused block groups.
1710 btrfs_delete_unused_bgs(fs_info);
1713 set_current_state(TASK_INTERRUPTIBLE);
1714 if (!kthread_should_stop())
1716 __set_current_state(TASK_RUNNING);
1718 } while (!kthread_should_stop());
1721 * Transaction kthread is stopped before us and wakes us up.
1722 * However we might have started a new transaction and COWed some
1723 * tree blocks when deleting unused block groups for example. So
1724 * make sure we commit the transaction we started to have a clean
1725 * shutdown when evicting the btree inode - if it has dirty pages
1726 * when we do the final iput() on it, eviction will trigger a
1727 * writeback for it which will fail with null pointer dereferences
1728 * since work queues and other resources were already released and
1729 * destroyed by the time the iput/eviction/writeback is made.
1731 trans = btrfs_attach_transaction(root);
1732 if (IS_ERR(trans)) {
1733 if (PTR_ERR(trans) != -ENOENT)
1735 "cleaner transaction attach returned %ld",
1740 ret = btrfs_commit_transaction(trans);
1743 "cleaner open transaction commit returned %d",
1750 static int transaction_kthread(void *arg)
1752 struct btrfs_root *root = arg;
1753 struct btrfs_fs_info *fs_info = root->fs_info;
1754 struct btrfs_trans_handle *trans;
1755 struct btrfs_transaction *cur;
1758 unsigned long delay;
1762 cannot_commit = false;
1763 delay = HZ * fs_info->commit_interval;
1764 mutex_lock(&fs_info->transaction_kthread_mutex);
1766 spin_lock(&fs_info->trans_lock);
1767 cur = fs_info->running_transaction;
1769 spin_unlock(&fs_info->trans_lock);
1773 now = get_seconds();
1774 if (cur->state < TRANS_STATE_BLOCKED &&
1775 (now < cur->start_time ||
1776 now - cur->start_time < fs_info->commit_interval)) {
1777 spin_unlock(&fs_info->trans_lock);
1781 transid = cur->transid;
1782 spin_unlock(&fs_info->trans_lock);
1784 /* If the file system is aborted, this will always fail. */
1785 trans = btrfs_attach_transaction(root);
1786 if (IS_ERR(trans)) {
1787 if (PTR_ERR(trans) != -ENOENT)
1788 cannot_commit = true;
1791 if (transid == trans->transid) {
1792 btrfs_commit_transaction(trans);
1794 btrfs_end_transaction(trans);
1797 wake_up_process(fs_info->cleaner_kthread);
1798 mutex_unlock(&fs_info->transaction_kthread_mutex);
1800 if (unlikely(test_bit(BTRFS_FS_STATE_ERROR,
1801 &fs_info->fs_state)))
1802 btrfs_cleanup_transaction(fs_info);
1803 if (!kthread_should_stop() &&
1804 (!btrfs_transaction_blocked(fs_info) ||
1806 schedule_timeout_interruptible(delay);
1807 } while (!kthread_should_stop());
1812 * this will find the highest generation in the array of
1813 * root backups. The index of the highest array is returned,
1814 * or -1 if we can't find anything.
1816 * We check to make sure the array is valid by comparing the
1817 * generation of the latest root in the array with the generation
1818 * in the super block. If they don't match we pitch it.
1820 static int find_newest_super_backup(struct btrfs_fs_info *info, u64 newest_gen)
1823 int newest_index = -1;
1824 struct btrfs_root_backup *root_backup;
1827 for (i = 0; i < BTRFS_NUM_BACKUP_ROOTS; i++) {
1828 root_backup = info->super_copy->super_roots + i;
1829 cur = btrfs_backup_tree_root_gen(root_backup);
1830 if (cur == newest_gen)
1834 /* check to see if we actually wrapped around */
1835 if (newest_index == BTRFS_NUM_BACKUP_ROOTS - 1) {
1836 root_backup = info->super_copy->super_roots;
1837 cur = btrfs_backup_tree_root_gen(root_backup);
1838 if (cur == newest_gen)
1841 return newest_index;
1846 * find the oldest backup so we know where to store new entries
1847 * in the backup array. This will set the backup_root_index
1848 * field in the fs_info struct
1850 static void find_oldest_super_backup(struct btrfs_fs_info *info,
1853 int newest_index = -1;
1855 newest_index = find_newest_super_backup(info, newest_gen);
1856 /* if there was garbage in there, just move along */
1857 if (newest_index == -1) {
1858 info->backup_root_index = 0;
1860 info->backup_root_index = (newest_index + 1) % BTRFS_NUM_BACKUP_ROOTS;
1865 * copy all the root pointers into the super backup array.
1866 * this will bump the backup pointer by one when it is
1869 static void backup_super_roots(struct btrfs_fs_info *info)
1872 struct btrfs_root_backup *root_backup;
1875 next_backup = info->backup_root_index;
1876 last_backup = (next_backup + BTRFS_NUM_BACKUP_ROOTS - 1) %
1877 BTRFS_NUM_BACKUP_ROOTS;
1880 * just overwrite the last backup if we're at the same generation
1881 * this happens only at umount
1883 root_backup = info->super_for_commit->super_roots + last_backup;
1884 if (btrfs_backup_tree_root_gen(root_backup) ==
1885 btrfs_header_generation(info->tree_root->node))
1886 next_backup = last_backup;
1888 root_backup = info->super_for_commit->super_roots + next_backup;
1891 * make sure all of our padding and empty slots get zero filled
1892 * regardless of which ones we use today
1894 memset(root_backup, 0, sizeof(*root_backup));
1896 info->backup_root_index = (next_backup + 1) % BTRFS_NUM_BACKUP_ROOTS;
1898 btrfs_set_backup_tree_root(root_backup, info->tree_root->node->start);
1899 btrfs_set_backup_tree_root_gen(root_backup,
1900 btrfs_header_generation(info->tree_root->node));
1902 btrfs_set_backup_tree_root_level(root_backup,
1903 btrfs_header_level(info->tree_root->node));
1905 btrfs_set_backup_chunk_root(root_backup, info->chunk_root->node->start);
1906 btrfs_set_backup_chunk_root_gen(root_backup,
1907 btrfs_header_generation(info->chunk_root->node));
1908 btrfs_set_backup_chunk_root_level(root_backup,
1909 btrfs_header_level(info->chunk_root->node));
1911 btrfs_set_backup_extent_root(root_backup, info->extent_root->node->start);
1912 btrfs_set_backup_extent_root_gen(root_backup,
1913 btrfs_header_generation(info->extent_root->node));
1914 btrfs_set_backup_extent_root_level(root_backup,
1915 btrfs_header_level(info->extent_root->node));
1918 * we might commit during log recovery, which happens before we set
1919 * the fs_root. Make sure it is valid before we fill it in.
1921 if (info->fs_root && info->fs_root->node) {
1922 btrfs_set_backup_fs_root(root_backup,
1923 info->fs_root->node->start);
1924 btrfs_set_backup_fs_root_gen(root_backup,
1925 btrfs_header_generation(info->fs_root->node));
1926 btrfs_set_backup_fs_root_level(root_backup,
1927 btrfs_header_level(info->fs_root->node));
1930 btrfs_set_backup_dev_root(root_backup, info->dev_root->node->start);
1931 btrfs_set_backup_dev_root_gen(root_backup,
1932 btrfs_header_generation(info->dev_root->node));
1933 btrfs_set_backup_dev_root_level(root_backup,
1934 btrfs_header_level(info->dev_root->node));
1936 btrfs_set_backup_csum_root(root_backup, info->csum_root->node->start);
1937 btrfs_set_backup_csum_root_gen(root_backup,
1938 btrfs_header_generation(info->csum_root->node));
1939 btrfs_set_backup_csum_root_level(root_backup,
1940 btrfs_header_level(info->csum_root->node));
1942 btrfs_set_backup_total_bytes(root_backup,
1943 btrfs_super_total_bytes(info->super_copy));
1944 btrfs_set_backup_bytes_used(root_backup,
1945 btrfs_super_bytes_used(info->super_copy));
1946 btrfs_set_backup_num_devices(root_backup,
1947 btrfs_super_num_devices(info->super_copy));
1950 * if we don't copy this out to the super_copy, it won't get remembered
1951 * for the next commit
1953 memcpy(&info->super_copy->super_roots,
1954 &info->super_for_commit->super_roots,
1955 sizeof(*root_backup) * BTRFS_NUM_BACKUP_ROOTS);
1959 * this copies info out of the root backup array and back into
1960 * the in-memory super block. It is meant to help iterate through
1961 * the array, so you send it the number of backups you've already
1962 * tried and the last backup index you used.
1964 * this returns -1 when it has tried all the backups
1966 static noinline int next_root_backup(struct btrfs_fs_info *info,
1967 struct btrfs_super_block *super,
1968 int *num_backups_tried, int *backup_index)
1970 struct btrfs_root_backup *root_backup;
1971 int newest = *backup_index;
1973 if (*num_backups_tried == 0) {
1974 u64 gen = btrfs_super_generation(super);
1976 newest = find_newest_super_backup(info, gen);
1980 *backup_index = newest;
1981 *num_backups_tried = 1;
1982 } else if (*num_backups_tried == BTRFS_NUM_BACKUP_ROOTS) {
1983 /* we've tried all the backups, all done */
1986 /* jump to the next oldest backup */
1987 newest = (*backup_index + BTRFS_NUM_BACKUP_ROOTS - 1) %
1988 BTRFS_NUM_BACKUP_ROOTS;
1989 *backup_index = newest;
1990 *num_backups_tried += 1;
1992 root_backup = super->super_roots + newest;
1994 btrfs_set_super_generation(super,
1995 btrfs_backup_tree_root_gen(root_backup));
1996 btrfs_set_super_root(super, btrfs_backup_tree_root(root_backup));
1997 btrfs_set_super_root_level(super,
1998 btrfs_backup_tree_root_level(root_backup));
1999 btrfs_set_super_bytes_used(super, btrfs_backup_bytes_used(root_backup));
2002 * fixme: the total bytes and num_devices need to match or we should
2005 btrfs_set_super_total_bytes(super, btrfs_backup_total_bytes(root_backup));
2006 btrfs_set_super_num_devices(super, btrfs_backup_num_devices(root_backup));
2010 /* helper to cleanup workers */
2011 static void btrfs_stop_all_workers(struct btrfs_fs_info *fs_info)
2013 btrfs_destroy_workqueue(fs_info->fixup_workers);
2014 btrfs_destroy_workqueue(fs_info->delalloc_workers);
2015 btrfs_destroy_workqueue(fs_info->workers);
2016 btrfs_destroy_workqueue(fs_info->endio_workers);
2017 btrfs_destroy_workqueue(fs_info->endio_raid56_workers);
2018 btrfs_destroy_workqueue(fs_info->endio_repair_workers);
2019 btrfs_destroy_workqueue(fs_info->rmw_workers);
2020 btrfs_destroy_workqueue(fs_info->endio_write_workers);
2021 btrfs_destroy_workqueue(fs_info->endio_freespace_worker);
2022 btrfs_destroy_workqueue(fs_info->submit_workers);
2023 btrfs_destroy_workqueue(fs_info->delayed_workers);
2024 btrfs_destroy_workqueue(fs_info->caching_workers);
2025 btrfs_destroy_workqueue(fs_info->readahead_workers);
2026 btrfs_destroy_workqueue(fs_info->flush_workers);
2027 btrfs_destroy_workqueue(fs_info->qgroup_rescan_workers);
2028 btrfs_destroy_workqueue(fs_info->extent_workers);
2030 * Now that all other work queues are destroyed, we can safely destroy
2031 * the queues used for metadata I/O, since tasks from those other work
2032 * queues can do metadata I/O operations.
2034 btrfs_destroy_workqueue(fs_info->endio_meta_workers);
2035 btrfs_destroy_workqueue(fs_info->endio_meta_write_workers);
2038 static void free_root_extent_buffers(struct btrfs_root *root)
2041 free_extent_buffer(root->node);
2042 free_extent_buffer(root->commit_root);
2044 root->commit_root = NULL;
2048 /* helper to cleanup tree roots */
2049 static void free_root_pointers(struct btrfs_fs_info *info, int chunk_root)
2051 free_root_extent_buffers(info->tree_root);
2053 free_root_extent_buffers(info->dev_root);
2054 free_root_extent_buffers(info->extent_root);
2055 free_root_extent_buffers(info->csum_root);
2056 free_root_extent_buffers(info->quota_root);
2057 free_root_extent_buffers(info->uuid_root);
2059 free_root_extent_buffers(info->chunk_root);
2060 free_root_extent_buffers(info->free_space_root);
2063 void btrfs_free_fs_roots(struct btrfs_fs_info *fs_info)
2066 struct btrfs_root *gang[8];
2069 while (!list_empty(&fs_info->dead_roots)) {
2070 gang[0] = list_entry(fs_info->dead_roots.next,
2071 struct btrfs_root, root_list);
2072 list_del(&gang[0]->root_list);
2074 if (test_bit(BTRFS_ROOT_IN_RADIX, &gang[0]->state)) {
2075 btrfs_drop_and_free_fs_root(fs_info, gang[0]);
2077 free_extent_buffer(gang[0]->node);
2078 free_extent_buffer(gang[0]->commit_root);
2079 btrfs_put_fs_root(gang[0]);
2084 ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
2089 for (i = 0; i < ret; i++)
2090 btrfs_drop_and_free_fs_root(fs_info, gang[i]);
2093 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {
2094 btrfs_free_log_root_tree(NULL, fs_info);
2095 btrfs_destroy_pinned_extent(fs_info, fs_info->pinned_extents);
2099 static void btrfs_init_scrub(struct btrfs_fs_info *fs_info)
2101 mutex_init(&fs_info->scrub_lock);
2102 atomic_set(&fs_info->scrubs_running, 0);
2103 atomic_set(&fs_info->scrub_pause_req, 0);
2104 atomic_set(&fs_info->scrubs_paused, 0);
2105 atomic_set(&fs_info->scrub_cancel_req, 0);
2106 init_waitqueue_head(&fs_info->scrub_pause_wait);
2107 fs_info->scrub_workers_refcnt = 0;
2110 static void btrfs_init_balance(struct btrfs_fs_info *fs_info)
2112 spin_lock_init(&fs_info->balance_lock);
2113 mutex_init(&fs_info->balance_mutex);
2114 atomic_set(&fs_info->balance_running, 0);
2115 atomic_set(&fs_info->balance_pause_req, 0);
2116 atomic_set(&fs_info->balance_cancel_req, 0);
2117 fs_info->balance_ctl = NULL;
2118 init_waitqueue_head(&fs_info->balance_wait_q);
2121 static void btrfs_init_btree_inode(struct btrfs_fs_info *fs_info)
2123 struct inode *inode = fs_info->btree_inode;
2125 inode->i_ino = BTRFS_BTREE_INODE_OBJECTID;
2126 set_nlink(inode, 1);
2128 * we set the i_size on the btree inode to the max possible int.
2129 * the real end of the address space is determined by all of
2130 * the devices in the system
2132 inode->i_size = OFFSET_MAX;
2133 inode->i_mapping->a_ops = &btree_aops;
2135 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
2136 extent_io_tree_init(&BTRFS_I(inode)->io_tree, inode);
2137 BTRFS_I(inode)->io_tree.track_uptodate = 0;
2138 extent_map_tree_init(&BTRFS_I(inode)->extent_tree);
2140 BTRFS_I(inode)->io_tree.ops = &btree_extent_io_ops;
2142 BTRFS_I(inode)->root = fs_info->tree_root;
2143 memset(&BTRFS_I(inode)->location, 0, sizeof(struct btrfs_key));
2144 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
2145 btrfs_insert_inode_hash(inode);
2148 static void btrfs_init_dev_replace_locks(struct btrfs_fs_info *fs_info)
2150 fs_info->dev_replace.lock_owner = 0;
2151 atomic_set(&fs_info->dev_replace.nesting_level, 0);
2152 mutex_init(&fs_info->dev_replace.lock_finishing_cancel_unmount);
2153 rwlock_init(&fs_info->dev_replace.lock);
2154 atomic_set(&fs_info->dev_replace.read_locks, 0);
2155 atomic_set(&fs_info->dev_replace.blocking_readers, 0);
2156 init_waitqueue_head(&fs_info->replace_wait);
2157 init_waitqueue_head(&fs_info->dev_replace.read_lock_wq);
2160 static void btrfs_init_qgroup(struct btrfs_fs_info *fs_info)
2162 spin_lock_init(&fs_info->qgroup_lock);
2163 mutex_init(&fs_info->qgroup_ioctl_lock);
2164 fs_info->qgroup_tree = RB_ROOT;
2165 fs_info->qgroup_op_tree = RB_ROOT;
2166 INIT_LIST_HEAD(&fs_info->dirty_qgroups);
2167 fs_info->qgroup_seq = 1;
2168 fs_info->qgroup_ulist = NULL;
2169 fs_info->qgroup_rescan_running = false;
2170 mutex_init(&fs_info->qgroup_rescan_lock);
2173 static int btrfs_init_workqueues(struct btrfs_fs_info *fs_info,
2174 struct btrfs_fs_devices *fs_devices)
2176 u32 max_active = fs_info->thread_pool_size;
2177 unsigned int flags = WQ_MEM_RECLAIM | WQ_FREEZABLE | WQ_UNBOUND;
2180 btrfs_alloc_workqueue(fs_info, "worker",
2181 flags | WQ_HIGHPRI, max_active, 16);
2183 fs_info->delalloc_workers =
2184 btrfs_alloc_workqueue(fs_info, "delalloc",
2185 flags, max_active, 2);
2187 fs_info->flush_workers =
2188 btrfs_alloc_workqueue(fs_info, "flush_delalloc",
2189 flags, max_active, 0);
2191 fs_info->caching_workers =
2192 btrfs_alloc_workqueue(fs_info, "cache", flags, max_active, 0);
2195 * a higher idle thresh on the submit workers makes it much more
2196 * likely that bios will be send down in a sane order to the
2199 fs_info->submit_workers =
2200 btrfs_alloc_workqueue(fs_info, "submit", flags,
2201 min_t(u64, fs_devices->num_devices,
2204 fs_info->fixup_workers =
2205 btrfs_alloc_workqueue(fs_info, "fixup", flags, 1, 0);
2208 * endios are largely parallel and should have a very
2211 fs_info->endio_workers =
2212 btrfs_alloc_workqueue(fs_info, "endio", flags, max_active, 4);
2213 fs_info->endio_meta_workers =
2214 btrfs_alloc_workqueue(fs_info, "endio-meta", flags,
2216 fs_info->endio_meta_write_workers =
2217 btrfs_alloc_workqueue(fs_info, "endio-meta-write", flags,
2219 fs_info->endio_raid56_workers =
2220 btrfs_alloc_workqueue(fs_info, "endio-raid56", flags,
2222 fs_info->endio_repair_workers =
2223 btrfs_alloc_workqueue(fs_info, "endio-repair", flags, 1, 0);
2224 fs_info->rmw_workers =
2225 btrfs_alloc_workqueue(fs_info, "rmw", flags, max_active, 2);
2226 fs_info->endio_write_workers =
2227 btrfs_alloc_workqueue(fs_info, "endio-write", flags,
2229 fs_info->endio_freespace_worker =
2230 btrfs_alloc_workqueue(fs_info, "freespace-write", flags,
2232 fs_info->delayed_workers =
2233 btrfs_alloc_workqueue(fs_info, "delayed-meta", flags,
2235 fs_info->readahead_workers =
2236 btrfs_alloc_workqueue(fs_info, "readahead", flags,
2238 fs_info->qgroup_rescan_workers =
2239 btrfs_alloc_workqueue(fs_info, "qgroup-rescan", flags, 1, 0);
2240 fs_info->extent_workers =
2241 btrfs_alloc_workqueue(fs_info, "extent-refs", flags,
2242 min_t(u64, fs_devices->num_devices,
2245 if (!(fs_info->workers && fs_info->delalloc_workers &&
2246 fs_info->submit_workers && fs_info->flush_workers &&
2247 fs_info->endio_workers && fs_info->endio_meta_workers &&
2248 fs_info->endio_meta_write_workers &&
2249 fs_info->endio_repair_workers &&
2250 fs_info->endio_write_workers && fs_info->endio_raid56_workers &&
2251 fs_info->endio_freespace_worker && fs_info->rmw_workers &&
2252 fs_info->caching_workers && fs_info->readahead_workers &&
2253 fs_info->fixup_workers && fs_info->delayed_workers &&
2254 fs_info->extent_workers &&
2255 fs_info->qgroup_rescan_workers)) {
2262 static int btrfs_replay_log(struct btrfs_fs_info *fs_info,
2263 struct btrfs_fs_devices *fs_devices)
2266 struct btrfs_root *log_tree_root;
2267 struct btrfs_super_block *disk_super = fs_info->super_copy;
2268 u64 bytenr = btrfs_super_log_root(disk_super);
2270 if (fs_devices->rw_devices == 0) {
2271 btrfs_warn(fs_info, "log replay required on RO media");
2275 log_tree_root = btrfs_alloc_root(fs_info, GFP_KERNEL);
2279 __setup_root(log_tree_root, fs_info, BTRFS_TREE_LOG_OBJECTID);
2281 log_tree_root->node = read_tree_block(fs_info, bytenr,
2282 fs_info->generation + 1);
2283 if (IS_ERR(log_tree_root->node)) {
2284 btrfs_warn(fs_info, "failed to read log tree");
2285 ret = PTR_ERR(log_tree_root->node);
2286 kfree(log_tree_root);
2288 } else if (!extent_buffer_uptodate(log_tree_root->node)) {
2289 btrfs_err(fs_info, "failed to read log tree");
2290 free_extent_buffer(log_tree_root->node);
2291 kfree(log_tree_root);
2294 /* returns with log_tree_root freed on success */
2295 ret = btrfs_recover_log_trees(log_tree_root);
2297 btrfs_handle_fs_error(fs_info, ret,
2298 "Failed to recover log tree");
2299 free_extent_buffer(log_tree_root->node);
2300 kfree(log_tree_root);
2304 if (sb_rdonly(fs_info->sb)) {
2305 ret = btrfs_commit_super(fs_info);
2313 static int btrfs_read_roots(struct btrfs_fs_info *fs_info)
2315 struct btrfs_root *tree_root = fs_info->tree_root;
2316 struct btrfs_root *root;
2317 struct btrfs_key location;
2320 BUG_ON(!fs_info->tree_root);
2322 location.objectid = BTRFS_EXTENT_TREE_OBJECTID;
2323 location.type = BTRFS_ROOT_ITEM_KEY;
2324 location.offset = 0;
2326 root = btrfs_read_tree_root(tree_root, &location);
2328 return 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 return PTR_ERR(root);
2336 set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2337 fs_info->dev_root = root;
2338 btrfs_init_devices_late(fs_info);
2340 location.objectid = BTRFS_CSUM_TREE_OBJECTID;
2341 root = btrfs_read_tree_root(tree_root, &location);
2343 return PTR_ERR(root);
2344 set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2345 fs_info->csum_root = root;
2347 location.objectid = BTRFS_QUOTA_TREE_OBJECTID;
2348 root = btrfs_read_tree_root(tree_root, &location);
2349 if (!IS_ERR(root)) {
2350 set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2351 set_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags);
2352 fs_info->quota_root = root;
2355 location.objectid = BTRFS_UUID_TREE_OBJECTID;
2356 root = btrfs_read_tree_root(tree_root, &location);
2358 ret = PTR_ERR(root);
2362 set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2363 fs_info->uuid_root = root;
2366 if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
2367 location.objectid = BTRFS_FREE_SPACE_TREE_OBJECTID;
2368 root = btrfs_read_tree_root(tree_root, &location);
2370 return PTR_ERR(root);
2371 set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2372 fs_info->free_space_root = root;
2378 int open_ctree(struct super_block *sb,
2379 struct btrfs_fs_devices *fs_devices,
2387 struct btrfs_key location;
2388 struct buffer_head *bh;
2389 struct btrfs_super_block *disk_super;
2390 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
2391 struct btrfs_root *tree_root;
2392 struct btrfs_root *chunk_root;
2395 int num_backups_tried = 0;
2396 int backup_index = 0;
2398 int clear_free_space_tree = 0;
2400 tree_root = fs_info->tree_root = btrfs_alloc_root(fs_info, GFP_KERNEL);
2401 chunk_root = fs_info->chunk_root = btrfs_alloc_root(fs_info, GFP_KERNEL);
2402 if (!tree_root || !chunk_root) {
2407 ret = init_srcu_struct(&fs_info->subvol_srcu);
2413 ret = percpu_counter_init(&fs_info->dirty_metadata_bytes, 0, GFP_KERNEL);
2418 fs_info->dirty_metadata_batch = PAGE_SIZE *
2419 (1 + ilog2(nr_cpu_ids));
2421 ret = percpu_counter_init(&fs_info->delalloc_bytes, 0, GFP_KERNEL);
2424 goto fail_dirty_metadata_bytes;
2427 ret = percpu_counter_init(&fs_info->bio_counter, 0, GFP_KERNEL);
2430 goto fail_delalloc_bytes;
2433 INIT_RADIX_TREE(&fs_info->fs_roots_radix, GFP_ATOMIC);
2434 INIT_RADIX_TREE(&fs_info->buffer_radix, GFP_ATOMIC);
2435 INIT_LIST_HEAD(&fs_info->trans_list);
2436 INIT_LIST_HEAD(&fs_info->dead_roots);
2437 INIT_LIST_HEAD(&fs_info->delayed_iputs);
2438 INIT_LIST_HEAD(&fs_info->delalloc_roots);
2439 INIT_LIST_HEAD(&fs_info->caching_block_groups);
2440 spin_lock_init(&fs_info->delalloc_root_lock);
2441 spin_lock_init(&fs_info->trans_lock);
2442 spin_lock_init(&fs_info->fs_roots_radix_lock);
2443 spin_lock_init(&fs_info->delayed_iput_lock);
2444 spin_lock_init(&fs_info->defrag_inodes_lock);
2445 spin_lock_init(&fs_info->tree_mod_seq_lock);
2446 spin_lock_init(&fs_info->super_lock);
2447 spin_lock_init(&fs_info->qgroup_op_lock);
2448 spin_lock_init(&fs_info->buffer_lock);
2449 spin_lock_init(&fs_info->unused_bgs_lock);
2450 rwlock_init(&fs_info->tree_mod_log_lock);
2451 mutex_init(&fs_info->unused_bg_unpin_mutex);
2452 mutex_init(&fs_info->delete_unused_bgs_mutex);
2453 mutex_init(&fs_info->reloc_mutex);
2454 mutex_init(&fs_info->delalloc_root_mutex);
2455 mutex_init(&fs_info->cleaner_delayed_iput_mutex);
2456 seqlock_init(&fs_info->profiles_lock);
2458 INIT_LIST_HEAD(&fs_info->dirty_cowonly_roots);
2459 INIT_LIST_HEAD(&fs_info->space_info);
2460 INIT_LIST_HEAD(&fs_info->tree_mod_seq_list);
2461 INIT_LIST_HEAD(&fs_info->unused_bgs);
2462 btrfs_mapping_init(&fs_info->mapping_tree);
2463 btrfs_init_block_rsv(&fs_info->global_block_rsv,
2464 BTRFS_BLOCK_RSV_GLOBAL);
2465 btrfs_init_block_rsv(&fs_info->trans_block_rsv, BTRFS_BLOCK_RSV_TRANS);
2466 btrfs_init_block_rsv(&fs_info->chunk_block_rsv, BTRFS_BLOCK_RSV_CHUNK);
2467 btrfs_init_block_rsv(&fs_info->empty_block_rsv, BTRFS_BLOCK_RSV_EMPTY);
2468 btrfs_init_block_rsv(&fs_info->delayed_block_rsv,
2469 BTRFS_BLOCK_RSV_DELOPS);
2470 atomic_set(&fs_info->async_delalloc_pages, 0);
2471 atomic_set(&fs_info->defrag_running, 0);
2472 atomic_set(&fs_info->qgroup_op_seq, 0);
2473 atomic_set(&fs_info->reada_works_cnt, 0);
2474 atomic64_set(&fs_info->tree_mod_seq, 0);
2476 fs_info->max_inline = BTRFS_DEFAULT_MAX_INLINE;
2477 fs_info->metadata_ratio = 0;
2478 fs_info->defrag_inodes = RB_ROOT;
2479 atomic64_set(&fs_info->free_chunk_space, 0);
2480 fs_info->tree_mod_log = RB_ROOT;
2481 fs_info->commit_interval = BTRFS_DEFAULT_COMMIT_INTERVAL;
2482 fs_info->avg_delayed_ref_runtime = NSEC_PER_SEC >> 6; /* div by 64 */
2483 /* readahead state */
2484 INIT_RADIX_TREE(&fs_info->reada_tree, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
2485 spin_lock_init(&fs_info->reada_lock);
2486 btrfs_init_ref_verify(fs_info);
2488 fs_info->thread_pool_size = min_t(unsigned long,
2489 num_online_cpus() + 2, 8);
2491 INIT_LIST_HEAD(&fs_info->ordered_roots);
2492 spin_lock_init(&fs_info->ordered_root_lock);
2494 fs_info->btree_inode = new_inode(sb);
2495 if (!fs_info->btree_inode) {
2497 goto fail_bio_counter;
2499 mapping_set_gfp_mask(fs_info->btree_inode->i_mapping, GFP_NOFS);
2501 fs_info->delayed_root = kmalloc(sizeof(struct btrfs_delayed_root),
2503 if (!fs_info->delayed_root) {
2507 btrfs_init_delayed_root(fs_info->delayed_root);
2509 btrfs_init_scrub(fs_info);
2510 #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
2511 fs_info->check_integrity_print_mask = 0;
2513 btrfs_init_balance(fs_info);
2514 btrfs_init_async_reclaim_work(&fs_info->async_reclaim_work);
2516 sb->s_blocksize = BTRFS_BDEV_BLOCKSIZE;
2517 sb->s_blocksize_bits = blksize_bits(BTRFS_BDEV_BLOCKSIZE);
2519 btrfs_init_btree_inode(fs_info);
2521 spin_lock_init(&fs_info->block_group_cache_lock);
2522 fs_info->block_group_cache_tree = RB_ROOT;
2523 fs_info->first_logical_byte = (u64)-1;
2525 extent_io_tree_init(&fs_info->freed_extents[0], NULL);
2526 extent_io_tree_init(&fs_info->freed_extents[1], NULL);
2527 fs_info->pinned_extents = &fs_info->freed_extents[0];
2528 set_bit(BTRFS_FS_BARRIER, &fs_info->flags);
2530 mutex_init(&fs_info->ordered_operations_mutex);
2531 mutex_init(&fs_info->tree_log_mutex);
2532 mutex_init(&fs_info->chunk_mutex);
2533 mutex_init(&fs_info->transaction_kthread_mutex);
2534 mutex_init(&fs_info->cleaner_mutex);
2535 mutex_init(&fs_info->volume_mutex);
2536 mutex_init(&fs_info->ro_block_group_mutex);
2537 init_rwsem(&fs_info->commit_root_sem);
2538 init_rwsem(&fs_info->cleanup_work_sem);
2539 init_rwsem(&fs_info->subvol_sem);
2540 sema_init(&fs_info->uuid_tree_rescan_sem, 1);
2542 btrfs_init_dev_replace_locks(fs_info);
2543 btrfs_init_qgroup(fs_info);
2545 btrfs_init_free_cluster(&fs_info->meta_alloc_cluster);
2546 btrfs_init_free_cluster(&fs_info->data_alloc_cluster);
2548 init_waitqueue_head(&fs_info->transaction_throttle);
2549 init_waitqueue_head(&fs_info->transaction_wait);
2550 init_waitqueue_head(&fs_info->transaction_blocked_wait);
2551 init_waitqueue_head(&fs_info->async_submit_wait);
2553 INIT_LIST_HEAD(&fs_info->pinned_chunks);
2555 /* Usable values until the real ones are cached from the superblock */
2556 fs_info->nodesize = 4096;
2557 fs_info->sectorsize = 4096;
2558 fs_info->stripesize = 4096;
2560 ret = btrfs_alloc_stripe_hash_table(fs_info);
2566 __setup_root(tree_root, fs_info, BTRFS_ROOT_TREE_OBJECTID);
2568 invalidate_bdev(fs_devices->latest_bdev);
2571 * Read super block and check the signature bytes only
2573 bh = btrfs_read_dev_super(fs_devices->latest_bdev);
2580 * We want to check superblock checksum, the type is stored inside.
2581 * Pass the whole disk block of size BTRFS_SUPER_INFO_SIZE (4k).
2583 if (btrfs_check_super_csum(fs_info, bh->b_data)) {
2584 btrfs_err(fs_info, "superblock checksum mismatch");
2591 * super_copy is zeroed at allocation time and we never touch the
2592 * following bytes up to INFO_SIZE, the checksum is calculated from
2593 * the whole block of INFO_SIZE
2595 memcpy(fs_info->super_copy, bh->b_data, sizeof(*fs_info->super_copy));
2596 memcpy(fs_info->super_for_commit, fs_info->super_copy,
2597 sizeof(*fs_info->super_for_commit));
2600 memcpy(fs_info->fsid, fs_info->super_copy->fsid, BTRFS_FSID_SIZE);
2602 ret = btrfs_check_super_valid(fs_info);
2604 btrfs_err(fs_info, "superblock contains fatal errors");
2609 disk_super = fs_info->super_copy;
2610 if (!btrfs_super_root(disk_super))
2613 /* check FS state, whether FS is broken. */
2614 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_ERROR)
2615 set_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state);
2618 * run through our array of backup supers and setup
2619 * our ring pointer to the oldest one
2621 generation = btrfs_super_generation(disk_super);
2622 find_oldest_super_backup(fs_info, generation);
2625 * In the long term, we'll store the compression type in the super
2626 * block, and it'll be used for per file compression control.
2628 fs_info->compress_type = BTRFS_COMPRESS_ZLIB;
2630 ret = btrfs_parse_options(fs_info, options, sb->s_flags);
2636 features = btrfs_super_incompat_flags(disk_super) &
2637 ~BTRFS_FEATURE_INCOMPAT_SUPP;
2640 "cannot mount because of unsupported optional features (%llx)",
2646 features = btrfs_super_incompat_flags(disk_super);
2647 features |= BTRFS_FEATURE_INCOMPAT_MIXED_BACKREF;
2648 if (fs_info->compress_type == BTRFS_COMPRESS_LZO)
2649 features |= BTRFS_FEATURE_INCOMPAT_COMPRESS_LZO;
2650 else if (fs_info->compress_type == BTRFS_COMPRESS_ZSTD)
2651 features |= BTRFS_FEATURE_INCOMPAT_COMPRESS_ZSTD;
2653 if (features & BTRFS_FEATURE_INCOMPAT_SKINNY_METADATA)
2654 btrfs_info(fs_info, "has skinny extents");
2657 * flag our filesystem as having big metadata blocks if
2658 * they are bigger than the page size
2660 if (btrfs_super_nodesize(disk_super) > PAGE_SIZE) {
2661 if (!(features & BTRFS_FEATURE_INCOMPAT_BIG_METADATA))
2663 "flagging fs with big metadata feature");
2664 features |= BTRFS_FEATURE_INCOMPAT_BIG_METADATA;
2667 nodesize = btrfs_super_nodesize(disk_super);
2668 sectorsize = btrfs_super_sectorsize(disk_super);
2669 stripesize = sectorsize;
2670 fs_info->dirty_metadata_batch = nodesize * (1 + ilog2(nr_cpu_ids));
2671 fs_info->delalloc_batch = sectorsize * 512 * (1 + ilog2(nr_cpu_ids));
2673 /* Cache block sizes */
2674 fs_info->nodesize = nodesize;
2675 fs_info->sectorsize = sectorsize;
2676 fs_info->stripesize = stripesize;
2679 * mixed block groups end up with duplicate but slightly offset
2680 * extent buffers for the same range. It leads to corruptions
2682 if ((features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS) &&
2683 (sectorsize != nodesize)) {
2685 "unequal nodesize/sectorsize (%u != %u) are not allowed for mixed block groups",
2686 nodesize, sectorsize);
2691 * Needn't use the lock because there is no other task which will
2694 btrfs_set_super_incompat_flags(disk_super, features);
2696 features = btrfs_super_compat_ro_flags(disk_super) &
2697 ~BTRFS_FEATURE_COMPAT_RO_SUPP;
2698 if (!sb_rdonly(sb) && features) {
2700 "cannot mount read-write because of unsupported optional features (%llx)",
2706 max_active = fs_info->thread_pool_size;
2708 ret = btrfs_init_workqueues(fs_info, fs_devices);
2711 goto fail_sb_buffer;
2714 sb->s_bdi->congested_fn = btrfs_congested_fn;
2715 sb->s_bdi->congested_data = fs_info;
2716 sb->s_bdi->capabilities |= BDI_CAP_CGROUP_WRITEBACK;
2717 sb->s_bdi->ra_pages = VM_MAX_READAHEAD * SZ_1K / PAGE_SIZE;
2718 sb->s_bdi->ra_pages *= btrfs_super_num_devices(disk_super);
2719 sb->s_bdi->ra_pages = max(sb->s_bdi->ra_pages, SZ_4M / PAGE_SIZE);
2721 sb->s_blocksize = sectorsize;
2722 sb->s_blocksize_bits = blksize_bits(sectorsize);
2723 memcpy(&sb->s_uuid, fs_info->fsid, BTRFS_FSID_SIZE);
2725 mutex_lock(&fs_info->chunk_mutex);
2726 ret = btrfs_read_sys_array(fs_info);
2727 mutex_unlock(&fs_info->chunk_mutex);
2729 btrfs_err(fs_info, "failed to read the system array: %d", ret);
2730 goto fail_sb_buffer;
2733 generation = btrfs_super_chunk_root_generation(disk_super);
2735 __setup_root(chunk_root, fs_info, BTRFS_CHUNK_TREE_OBJECTID);
2737 chunk_root->node = read_tree_block(fs_info,
2738 btrfs_super_chunk_root(disk_super),
2740 if (IS_ERR(chunk_root->node) ||
2741 !extent_buffer_uptodate(chunk_root->node)) {
2742 btrfs_err(fs_info, "failed to read chunk root");
2743 if (!IS_ERR(chunk_root->node))
2744 free_extent_buffer(chunk_root->node);
2745 chunk_root->node = NULL;
2746 goto fail_tree_roots;
2748 btrfs_set_root_node(&chunk_root->root_item, chunk_root->node);
2749 chunk_root->commit_root = btrfs_root_node(chunk_root);
2751 read_extent_buffer(chunk_root->node, fs_info->chunk_tree_uuid,
2752 btrfs_header_chunk_tree_uuid(chunk_root->node), BTRFS_UUID_SIZE);
2754 ret = btrfs_read_chunk_tree(fs_info);
2756 btrfs_err(fs_info, "failed to read chunk tree: %d", ret);
2757 goto fail_tree_roots;
2761 * keep the device that is marked to be the target device for the
2762 * dev_replace procedure
2764 btrfs_close_extra_devices(fs_devices, 0);
2766 if (!fs_devices->latest_bdev) {
2767 btrfs_err(fs_info, "failed to read devices");
2768 goto fail_tree_roots;
2772 generation = btrfs_super_generation(disk_super);
2774 tree_root->node = read_tree_block(fs_info,
2775 btrfs_super_root(disk_super),
2777 if (IS_ERR(tree_root->node) ||
2778 !extent_buffer_uptodate(tree_root->node)) {
2779 btrfs_warn(fs_info, "failed to read tree root");
2780 if (!IS_ERR(tree_root->node))
2781 free_extent_buffer(tree_root->node);
2782 tree_root->node = NULL;
2783 goto recovery_tree_root;
2786 btrfs_set_root_node(&tree_root->root_item, tree_root->node);
2787 tree_root->commit_root = btrfs_root_node(tree_root);
2788 btrfs_set_root_refs(&tree_root->root_item, 1);
2790 mutex_lock(&tree_root->objectid_mutex);
2791 ret = btrfs_find_highest_objectid(tree_root,
2792 &tree_root->highest_objectid);
2794 mutex_unlock(&tree_root->objectid_mutex);
2795 goto recovery_tree_root;
2798 ASSERT(tree_root->highest_objectid <= BTRFS_LAST_FREE_OBJECTID);
2800 mutex_unlock(&tree_root->objectid_mutex);
2802 ret = btrfs_read_roots(fs_info);
2804 goto recovery_tree_root;
2806 fs_info->generation = generation;
2807 fs_info->last_trans_committed = generation;
2809 ret = btrfs_recover_balance(fs_info);
2811 btrfs_err(fs_info, "failed to recover balance: %d", ret);
2812 goto fail_block_groups;
2815 ret = btrfs_init_dev_stats(fs_info);
2817 btrfs_err(fs_info, "failed to init dev_stats: %d", ret);
2818 goto fail_block_groups;
2821 ret = btrfs_init_dev_replace(fs_info);
2823 btrfs_err(fs_info, "failed to init dev_replace: %d", ret);
2824 goto fail_block_groups;
2827 btrfs_close_extra_devices(fs_devices, 1);
2829 ret = btrfs_sysfs_add_fsid(fs_devices, NULL);
2831 btrfs_err(fs_info, "failed to init sysfs fsid interface: %d",
2833 goto fail_block_groups;
2836 ret = btrfs_sysfs_add_device(fs_devices);
2838 btrfs_err(fs_info, "failed to init sysfs device interface: %d",
2840 goto fail_fsdev_sysfs;
2843 ret = btrfs_sysfs_add_mounted(fs_info);
2845 btrfs_err(fs_info, "failed to init sysfs interface: %d", ret);
2846 goto fail_fsdev_sysfs;
2849 ret = btrfs_init_space_info(fs_info);
2851 btrfs_err(fs_info, "failed to initialize space info: %d", ret);
2855 ret = btrfs_read_block_groups(fs_info);
2857 btrfs_err(fs_info, "failed to read block groups: %d", ret);
2861 if (!sb_rdonly(sb) && !btrfs_check_rw_degradable(fs_info, NULL)) {
2863 "writeable mount is not allowed due to too many missing devices");
2867 fs_info->cleaner_kthread = kthread_run(cleaner_kthread, tree_root,
2869 if (IS_ERR(fs_info->cleaner_kthread))
2872 fs_info->transaction_kthread = kthread_run(transaction_kthread,
2874 "btrfs-transaction");
2875 if (IS_ERR(fs_info->transaction_kthread))
2878 if (!btrfs_test_opt(fs_info, NOSSD) &&
2879 !fs_info->fs_devices->rotating) {
2880 btrfs_set_and_info(fs_info, SSD, "enabling ssd optimizations");
2884 * Mount does not set all options immediately, we can do it now and do
2885 * not have to wait for transaction commit
2887 btrfs_apply_pending_changes(fs_info);
2889 #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
2890 if (btrfs_test_opt(fs_info, CHECK_INTEGRITY)) {
2891 ret = btrfsic_mount(fs_info, fs_devices,
2892 btrfs_test_opt(fs_info,
2893 CHECK_INTEGRITY_INCLUDING_EXTENT_DATA) ?
2895 fs_info->check_integrity_print_mask);
2898 "failed to initialize integrity check module: %d",
2902 ret = btrfs_read_qgroup_config(fs_info);
2904 goto fail_trans_kthread;
2906 if (btrfs_build_ref_tree(fs_info))
2907 btrfs_err(fs_info, "couldn't build ref tree");
2909 /* do not make disk changes in broken FS or nologreplay is given */
2910 if (btrfs_super_log_root(disk_super) != 0 &&
2911 !btrfs_test_opt(fs_info, NOLOGREPLAY)) {
2912 ret = btrfs_replay_log(fs_info, fs_devices);
2919 ret = btrfs_find_orphan_roots(fs_info);
2923 if (!sb_rdonly(sb)) {
2924 ret = btrfs_cleanup_fs_roots(fs_info);
2928 mutex_lock(&fs_info->cleaner_mutex);
2929 ret = btrfs_recover_relocation(tree_root);
2930 mutex_unlock(&fs_info->cleaner_mutex);
2932 btrfs_warn(fs_info, "failed to recover relocation: %d",
2939 location.objectid = BTRFS_FS_TREE_OBJECTID;
2940 location.type = BTRFS_ROOT_ITEM_KEY;
2941 location.offset = 0;
2943 fs_info->fs_root = btrfs_read_fs_root_no_name(fs_info, &location);
2944 if (IS_ERR(fs_info->fs_root)) {
2945 err = PTR_ERR(fs_info->fs_root);
2952 if (btrfs_test_opt(fs_info, CLEAR_CACHE) &&
2953 btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
2954 clear_free_space_tree = 1;
2955 } else if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE) &&
2956 !btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE_VALID)) {
2957 btrfs_warn(fs_info, "free space tree is invalid");
2958 clear_free_space_tree = 1;
2961 if (clear_free_space_tree) {
2962 btrfs_info(fs_info, "clearing free space tree");
2963 ret = btrfs_clear_free_space_tree(fs_info);
2966 "failed to clear free space tree: %d", ret);
2967 close_ctree(fs_info);
2972 if (btrfs_test_opt(fs_info, FREE_SPACE_TREE) &&
2973 !btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
2974 btrfs_info(fs_info, "creating free space tree");
2975 ret = btrfs_create_free_space_tree(fs_info);
2978 "failed to create free space tree: %d", ret);
2979 close_ctree(fs_info);
2984 down_read(&fs_info->cleanup_work_sem);
2985 if ((ret = btrfs_orphan_cleanup(fs_info->fs_root)) ||
2986 (ret = btrfs_orphan_cleanup(fs_info->tree_root))) {
2987 up_read(&fs_info->cleanup_work_sem);
2988 close_ctree(fs_info);
2991 up_read(&fs_info->cleanup_work_sem);
2993 ret = btrfs_resume_balance_async(fs_info);
2995 btrfs_warn(fs_info, "failed to resume balance: %d", ret);
2996 close_ctree(fs_info);
3000 ret = btrfs_resume_dev_replace_async(fs_info);
3002 btrfs_warn(fs_info, "failed to resume device replace: %d", ret);
3003 close_ctree(fs_info);
3007 btrfs_qgroup_rescan_resume(fs_info);
3009 if (!fs_info->uuid_root) {
3010 btrfs_info(fs_info, "creating UUID tree");
3011 ret = btrfs_create_uuid_tree(fs_info);
3014 "failed to create the UUID tree: %d", ret);
3015 close_ctree(fs_info);
3018 } else if (btrfs_test_opt(fs_info, RESCAN_UUID_TREE) ||
3019 fs_info->generation !=
3020 btrfs_super_uuid_tree_generation(disk_super)) {
3021 btrfs_info(fs_info, "checking UUID tree");
3022 ret = btrfs_check_uuid_tree(fs_info);
3025 "failed to check the UUID tree: %d", ret);
3026 close_ctree(fs_info);
3030 set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
3032 set_bit(BTRFS_FS_OPEN, &fs_info->flags);
3035 * backuproot only affect mount behavior, and if open_ctree succeeded,
3036 * no need to keep the flag
3038 btrfs_clear_opt(fs_info->mount_opt, USEBACKUPROOT);
3043 btrfs_free_qgroup_config(fs_info);
3045 kthread_stop(fs_info->transaction_kthread);
3046 btrfs_cleanup_transaction(fs_info);
3047 btrfs_free_fs_roots(fs_info);
3049 kthread_stop(fs_info->cleaner_kthread);
3052 * make sure we're done with the btree inode before we stop our
3055 filemap_write_and_wait(fs_info->btree_inode->i_mapping);
3058 btrfs_sysfs_remove_mounted(fs_info);
3061 btrfs_sysfs_remove_fsid(fs_info->fs_devices);
3064 btrfs_put_block_group_cache(fs_info);
3067 free_root_pointers(fs_info, 1);
3068 invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
3071 btrfs_stop_all_workers(fs_info);
3072 btrfs_free_block_groups(fs_info);
3075 btrfs_mapping_tree_free(&fs_info->mapping_tree);
3077 iput(fs_info->btree_inode);
3079 percpu_counter_destroy(&fs_info->bio_counter);
3080 fail_delalloc_bytes:
3081 percpu_counter_destroy(&fs_info->delalloc_bytes);
3082 fail_dirty_metadata_bytes:
3083 percpu_counter_destroy(&fs_info->dirty_metadata_bytes);
3085 cleanup_srcu_struct(&fs_info->subvol_srcu);
3087 btrfs_free_stripe_hash_table(fs_info);
3088 btrfs_close_devices(fs_info->fs_devices);
3092 if (!btrfs_test_opt(fs_info, USEBACKUPROOT))
3093 goto fail_tree_roots;
3095 free_root_pointers(fs_info, 0);
3097 /* don't use the log in recovery mode, it won't be valid */
3098 btrfs_set_super_log_root(disk_super, 0);
3100 /* we can't trust the free space cache either */
3101 btrfs_set_opt(fs_info->mount_opt, CLEAR_CACHE);
3103 ret = next_root_backup(fs_info, fs_info->super_copy,
3104 &num_backups_tried, &backup_index);
3106 goto fail_block_groups;
3107 goto retry_root_backup;
3109 ALLOW_ERROR_INJECTION(open_ctree, ERRNO);
3111 static void btrfs_end_buffer_write_sync(struct buffer_head *bh, int uptodate)
3114 set_buffer_uptodate(bh);
3116 struct btrfs_device *device = (struct btrfs_device *)
3119 btrfs_warn_rl_in_rcu(device->fs_info,
3120 "lost page write due to IO error on %s",
3121 rcu_str_deref(device->name));
3122 /* note, we don't set_buffer_write_io_error because we have
3123 * our own ways of dealing with the IO errors
3125 clear_buffer_uptodate(bh);
3126 btrfs_dev_stat_inc_and_print(device, BTRFS_DEV_STAT_WRITE_ERRS);
3132 int btrfs_read_dev_one_super(struct block_device *bdev, int copy_num,
3133 struct buffer_head **bh_ret)
3135 struct buffer_head *bh;
3136 struct btrfs_super_block *super;
3139 bytenr = btrfs_sb_offset(copy_num);
3140 if (bytenr + BTRFS_SUPER_INFO_SIZE >= i_size_read(bdev->bd_inode))
3143 bh = __bread(bdev, bytenr / BTRFS_BDEV_BLOCKSIZE, BTRFS_SUPER_INFO_SIZE);
3145 * If we fail to read from the underlying devices, as of now
3146 * the best option we have is to mark it EIO.
3151 super = (struct btrfs_super_block *)bh->b_data;
3152 if (btrfs_super_bytenr(super) != bytenr ||
3153 btrfs_super_magic(super) != BTRFS_MAGIC) {
3163 struct buffer_head *btrfs_read_dev_super(struct block_device *bdev)
3165 struct buffer_head *bh;
3166 struct buffer_head *latest = NULL;
3167 struct btrfs_super_block *super;
3172 /* we would like to check all the supers, but that would make
3173 * a btrfs mount succeed after a mkfs from a different FS.
3174 * So, we need to add a special mount option to scan for
3175 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
3177 for (i = 0; i < 1; i++) {
3178 ret = btrfs_read_dev_one_super(bdev, i, &bh);
3182 super = (struct btrfs_super_block *)bh->b_data;
3184 if (!latest || btrfs_super_generation(super) > transid) {
3187 transid = btrfs_super_generation(super);
3194 return ERR_PTR(ret);
3200 * Write superblock @sb to the @device. Do not wait for completion, all the
3201 * buffer heads we write are pinned.
3203 * Write @max_mirrors copies of the superblock, where 0 means default that fit
3204 * the expected device size at commit time. Note that max_mirrors must be
3205 * same for write and wait phases.
3207 * Return number of errors when buffer head is not found or submission fails.
3209 static int write_dev_supers(struct btrfs_device *device,
3210 struct btrfs_super_block *sb, int max_mirrors)
3212 struct buffer_head *bh;
3220 if (max_mirrors == 0)
3221 max_mirrors = BTRFS_SUPER_MIRROR_MAX;
3223 for (i = 0; i < max_mirrors; i++) {
3224 bytenr = btrfs_sb_offset(i);
3225 if (bytenr + BTRFS_SUPER_INFO_SIZE >=
3226 device->commit_total_bytes)
3229 btrfs_set_super_bytenr(sb, bytenr);
3232 crc = btrfs_csum_data((const char *)sb + BTRFS_CSUM_SIZE, crc,
3233 BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE);
3234 btrfs_csum_final(crc, sb->csum);
3236 /* One reference for us, and we leave it for the caller */
3237 bh = __getblk(device->bdev, bytenr / BTRFS_BDEV_BLOCKSIZE,
3238 BTRFS_SUPER_INFO_SIZE);
3240 btrfs_err(device->fs_info,
3241 "couldn't get super buffer head for bytenr %llu",
3247 memcpy(bh->b_data, sb, BTRFS_SUPER_INFO_SIZE);
3249 /* one reference for submit_bh */
3252 set_buffer_uptodate(bh);
3254 bh->b_end_io = btrfs_end_buffer_write_sync;
3255 bh->b_private = device;
3258 * we fua the first super. The others we allow
3261 op_flags = REQ_SYNC | REQ_META | REQ_PRIO;
3262 if (i == 0 && !btrfs_test_opt(device->fs_info, NOBARRIER))
3263 op_flags |= REQ_FUA;
3264 ret = btrfsic_submit_bh(REQ_OP_WRITE, op_flags, bh);
3268 return errors < i ? 0 : -1;
3272 * Wait for write completion of superblocks done by write_dev_supers,
3273 * @max_mirrors same for write and wait phases.
3275 * Return number of errors when buffer head is not found or not marked up to
3278 static int wait_dev_supers(struct btrfs_device *device, int max_mirrors)
3280 struct buffer_head *bh;