]> git.proxmox.com Git - mirror_ubuntu-jammy-kernel.git/blame - fs/btrfs/disk-io.c
btrfs: simplify some assignments of inode numbers
[mirror_ubuntu-jammy-kernel.git] / fs / btrfs / disk-io.c
CommitLineData
c1d7c514 1// SPDX-License-Identifier: GPL-2.0
6cbd5570
CM
2/*
3 * Copyright (C) 2007 Oracle. All rights reserved.
6cbd5570
CM
4 */
5
e20d96d6 6#include <linux/fs.h>
d98237b3 7#include <linux/blkdev.h>
87cbda5c 8#include <linux/scatterlist.h>
22b0ebda 9#include <linux/swap.h>
0f7d52f4 10#include <linux/radix-tree.h>
35b7e476 11#include <linux/writeback.h>
d397712b 12#include <linux/buffer_head.h>
ce9adaa5 13#include <linux/workqueue.h>
a74a4b97 14#include <linux/kthread.h>
5a0e3ad6 15#include <linux/slab.h>
784b4e29 16#include <linux/migrate.h>
7a36ddec 17#include <linux/ratelimit.h>
6463fe58 18#include <linux/uuid.h>
803b2f54 19#include <linux/semaphore.h>
540adea3 20#include <linux/error-injection.h>
9678c543 21#include <linux/crc32c.h>
7e75bf3f 22#include <asm/unaligned.h>
eb60ceac
CM
23#include "ctree.h"
24#include "disk-io.h"
e089f05c 25#include "transaction.h"
0f7d52f4 26#include "btrfs_inode.h"
0b86a832 27#include "volumes.h"
db94535d 28#include "print-tree.h"
925baedd 29#include "locking.h"
e02119d5 30#include "tree-log.h"
fa9c0d79 31#include "free-space-cache.h"
70f6d82e 32#include "free-space-tree.h"
581bb050 33#include "inode-map.h"
21adbd5c 34#include "check-integrity.h"
606686ee 35#include "rcu-string.h"
8dabb742 36#include "dev-replace.h"
53b381b3 37#include "raid56.h"
5ac1d209 38#include "sysfs.h"
fcebe456 39#include "qgroup.h"
ebb8765b 40#include "compression.h"
557ea5dd 41#include "tree-checker.h"
fd708b81 42#include "ref-verify.h"
eb60ceac 43
de0022b9
JB
44#ifdef CONFIG_X86
45#include <asm/cpufeature.h>
46#endif
47
319e4d06
QW
48#define BTRFS_SUPER_FLAG_SUPP (BTRFS_HEADER_FLAG_WRITTEN |\
49 BTRFS_HEADER_FLAG_RELOC |\
50 BTRFS_SUPER_FLAG_ERROR |\
51 BTRFS_SUPER_FLAG_SEEDING |\
e2731e55
AJ
52 BTRFS_SUPER_FLAG_METADUMP |\
53 BTRFS_SUPER_FLAG_METADUMP_V2)
319e4d06 54
e8c9f186 55static const struct extent_io_ops btree_extent_io_ops;
8b712842 56static void end_workqueue_fn(struct btrfs_work *work);
4df27c4d 57static void free_fs_root(struct btrfs_root *root);
143bede5 58static void btrfs_destroy_ordered_extents(struct btrfs_root *root);
acce952b 59static int btrfs_destroy_delayed_refs(struct btrfs_transaction *trans,
2ff7e61e 60 struct btrfs_fs_info *fs_info);
143bede5 61static void btrfs_destroy_delalloc_inodes(struct btrfs_root *root);
2ff7e61e 62static int btrfs_destroy_marked_extents(struct btrfs_fs_info *fs_info,
acce952b 63 struct extent_io_tree *dirty_pages,
64 int mark);
2ff7e61e 65static int btrfs_destroy_pinned_extent(struct btrfs_fs_info *fs_info,
acce952b 66 struct extent_io_tree *pinned_extents);
2ff7e61e
JM
67static int btrfs_cleanup_transaction(struct btrfs_fs_info *fs_info);
68static void btrfs_error_commit_super(struct btrfs_fs_info *fs_info);
ce9adaa5 69
d352ac68 70/*
97eb6b69
DS
71 * btrfs_end_io_wq structs are used to do processing in task context when an IO
72 * is complete. This is used during reads to verify checksums, and it is used
d352ac68
CM
73 * by writes to insert metadata for new file extents after IO is complete.
74 */
97eb6b69 75struct btrfs_end_io_wq {
ce9adaa5
CM
76 struct bio *bio;
77 bio_end_io_t *end_io;
78 void *private;
79 struct btrfs_fs_info *info;
4e4cbee9 80 blk_status_t status;
bfebd8b5 81 enum btrfs_wq_endio_type metadata;
8b712842 82 struct btrfs_work work;
ce9adaa5 83};
0da5468f 84
97eb6b69
DS
85static struct kmem_cache *btrfs_end_io_wq_cache;
86
87int __init btrfs_end_io_wq_init(void)
88{
89 btrfs_end_io_wq_cache = kmem_cache_create("btrfs_end_io_wq",
90 sizeof(struct btrfs_end_io_wq),
91 0,
fba4b697 92 SLAB_MEM_SPREAD,
97eb6b69
DS
93 NULL);
94 if (!btrfs_end_io_wq_cache)
95 return -ENOMEM;
96 return 0;
97}
98
e67c718b 99void __cold btrfs_end_io_wq_exit(void)
97eb6b69 100{
5598e900 101 kmem_cache_destroy(btrfs_end_io_wq_cache);
97eb6b69
DS
102}
103
d352ac68
CM
104/*
105 * async submit bios are used to offload expensive checksumming
106 * onto the worker threads. They checksum file and metadata bios
107 * just before they are sent down the IO stack.
108 */
44b8bd7e 109struct async_submit_bio {
c6100a4b
JB
110 void *private_data;
111 struct btrfs_fs_info *fs_info;
44b8bd7e 112 struct bio *bio;
a758781d
DS
113 extent_submit_bio_start_t *submit_bio_start;
114 extent_submit_bio_done_t *submit_bio_done;
44b8bd7e 115 int mirror_num;
c8b97818 116 unsigned long bio_flags;
eaf25d93
CM
117 /*
118 * bio_offset is optional, can be used if the pages in the bio
119 * can't tell us where in the file the bio should go
120 */
121 u64 bio_offset;
8b712842 122 struct btrfs_work work;
4e4cbee9 123 blk_status_t status;
44b8bd7e
CM
124};
125
85d4e461
CM
126/*
127 * Lockdep class keys for extent_buffer->lock's in this root. For a given
128 * eb, the lockdep key is determined by the btrfs_root it belongs to and
129 * the level the eb occupies in the tree.
130 *
131 * Different roots are used for different purposes and may nest inside each
132 * other and they require separate keysets. As lockdep keys should be
133 * static, assign keysets according to the purpose of the root as indicated
134 * by btrfs_root->objectid. This ensures that all special purpose roots
135 * have separate keysets.
4008c04a 136 *
85d4e461
CM
137 * Lock-nesting across peer nodes is always done with the immediate parent
138 * node locked thus preventing deadlock. As lockdep doesn't know this, use
139 * subclass to avoid triggering lockdep warning in such cases.
4008c04a 140 *
85d4e461
CM
141 * The key is set by the readpage_end_io_hook after the buffer has passed
142 * csum validation but before the pages are unlocked. It is also set by
143 * btrfs_init_new_buffer on freshly allocated blocks.
4008c04a 144 *
85d4e461
CM
145 * We also add a check to make sure the highest level of the tree is the
146 * same as our lockdep setup here. If BTRFS_MAX_LEVEL changes, this code
147 * needs update as well.
4008c04a
CM
148 */
149#ifdef CONFIG_DEBUG_LOCK_ALLOC
150# if BTRFS_MAX_LEVEL != 8
151# error
152# endif
85d4e461
CM
153
154static struct btrfs_lockdep_keyset {
155 u64 id; /* root objectid */
156 const char *name_stem; /* lock name stem */
157 char names[BTRFS_MAX_LEVEL + 1][20];
158 struct lock_class_key keys[BTRFS_MAX_LEVEL + 1];
159} btrfs_lockdep_keysets[] = {
160 { .id = BTRFS_ROOT_TREE_OBJECTID, .name_stem = "root" },
161 { .id = BTRFS_EXTENT_TREE_OBJECTID, .name_stem = "extent" },
162 { .id = BTRFS_CHUNK_TREE_OBJECTID, .name_stem = "chunk" },
163 { .id = BTRFS_DEV_TREE_OBJECTID, .name_stem = "dev" },
164 { .id = BTRFS_FS_TREE_OBJECTID, .name_stem = "fs" },
165 { .id = BTRFS_CSUM_TREE_OBJECTID, .name_stem = "csum" },
60b62978 166 { .id = BTRFS_QUOTA_TREE_OBJECTID, .name_stem = "quota" },
85d4e461
CM
167 { .id = BTRFS_TREE_LOG_OBJECTID, .name_stem = "log" },
168 { .id = BTRFS_TREE_RELOC_OBJECTID, .name_stem = "treloc" },
169 { .id = BTRFS_DATA_RELOC_TREE_OBJECTID, .name_stem = "dreloc" },
13fd8da9 170 { .id = BTRFS_UUID_TREE_OBJECTID, .name_stem = "uuid" },
6b20e0ad 171 { .id = BTRFS_FREE_SPACE_TREE_OBJECTID, .name_stem = "free-space" },
85d4e461 172 { .id = 0, .name_stem = "tree" },
4008c04a 173};
85d4e461
CM
174
175void __init btrfs_init_lockdep(void)
176{
177 int i, j;
178
179 /* initialize lockdep class names */
180 for (i = 0; i < ARRAY_SIZE(btrfs_lockdep_keysets); i++) {
181 struct btrfs_lockdep_keyset *ks = &btrfs_lockdep_keysets[i];
182
183 for (j = 0; j < ARRAY_SIZE(ks->names); j++)
184 snprintf(ks->names[j], sizeof(ks->names[j]),
185 "btrfs-%s-%02d", ks->name_stem, j);
186 }
187}
188
189void btrfs_set_buffer_lockdep_class(u64 objectid, struct extent_buffer *eb,
190 int level)
191{
192 struct btrfs_lockdep_keyset *ks;
193
194 BUG_ON(level >= ARRAY_SIZE(ks->keys));
195
196 /* find the matching keyset, id 0 is the default entry */
197 for (ks = btrfs_lockdep_keysets; ks->id; ks++)
198 if (ks->id == objectid)
199 break;
200
201 lockdep_set_class_and_name(&eb->lock,
202 &ks->keys[level], ks->names[level]);
203}
204
4008c04a
CM
205#endif
206
d352ac68
CM
207/*
208 * extents on the btree inode are pretty simple, there's one extent
209 * that covers the entire device
210 */
6af49dbd 211struct extent_map *btree_get_extent(struct btrfs_inode *inode,
306e16ce 212 struct page *page, size_t pg_offset, u64 start, u64 len,
b2950863 213 int create)
7eccb903 214{
fc4f21b1
NB
215 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
216 struct extent_map_tree *em_tree = &inode->extent_tree;
5f39d397
CM
217 struct extent_map *em;
218 int ret;
219
890871be 220 read_lock(&em_tree->lock);
d1310b2e 221 em = lookup_extent_mapping(em_tree, start, len);
a061fc8d 222 if (em) {
0b246afa 223 em->bdev = fs_info->fs_devices->latest_bdev;
890871be 224 read_unlock(&em_tree->lock);
5f39d397 225 goto out;
a061fc8d 226 }
890871be 227 read_unlock(&em_tree->lock);
7b13b7b1 228
172ddd60 229 em = alloc_extent_map();
5f39d397
CM
230 if (!em) {
231 em = ERR_PTR(-ENOMEM);
232 goto out;
233 }
234 em->start = 0;
0afbaf8c 235 em->len = (u64)-1;
c8b97818 236 em->block_len = (u64)-1;
5f39d397 237 em->block_start = 0;
0b246afa 238 em->bdev = fs_info->fs_devices->latest_bdev;
d1310b2e 239
890871be 240 write_lock(&em_tree->lock);
09a2a8f9 241 ret = add_extent_mapping(em_tree, em, 0);
5f39d397
CM
242 if (ret == -EEXIST) {
243 free_extent_map(em);
7b13b7b1 244 em = lookup_extent_mapping(em_tree, start, len);
b4f359ab 245 if (!em)
0433f20d 246 em = ERR_PTR(-EIO);
5f39d397 247 } else if (ret) {
7b13b7b1 248 free_extent_map(em);
0433f20d 249 em = ERR_PTR(ret);
5f39d397 250 }
890871be 251 write_unlock(&em_tree->lock);
7b13b7b1 252
5f39d397
CM
253out:
254 return em;
7eccb903
CM
255}
256
9ed57367 257u32 btrfs_csum_data(const char *data, u32 seed, size_t len)
19c00ddc 258{
9678c543 259 return crc32c(seed, data, len);
19c00ddc
CM
260}
261
0b5e3daf 262void btrfs_csum_final(u32 crc, u8 *result)
19c00ddc 263{
7e75bf3f 264 put_unaligned_le32(~crc, result);
19c00ddc
CM
265}
266
d352ac68
CM
267/*
268 * compute the csum for a btree block, and either verify it or write it
269 * into the csum field of the block.
270 */
01d58472
DD
271static int csum_tree_block(struct btrfs_fs_info *fs_info,
272 struct extent_buffer *buf,
19c00ddc
CM
273 int verify)
274{
01d58472 275 u16 csum_size = btrfs_super_csum_size(fs_info->super_copy);
71a63551 276 char result[BTRFS_CSUM_SIZE];
19c00ddc
CM
277 unsigned long len;
278 unsigned long cur_len;
279 unsigned long offset = BTRFS_CSUM_SIZE;
19c00ddc
CM
280 char *kaddr;
281 unsigned long map_start;
282 unsigned long map_len;
283 int err;
284 u32 crc = ~(u32)0;
285
286 len = buf->len - offset;
d397712b 287 while (len > 0) {
19c00ddc 288 err = map_private_extent_buffer(buf, offset, 32,
a6591715 289 &kaddr, &map_start, &map_len);
d397712b 290 if (err)
8bd98f0e 291 return err;
19c00ddc 292 cur_len = min(len, map_len - (offset - map_start));
b0496686 293 crc = btrfs_csum_data(kaddr + offset - map_start,
19c00ddc
CM
294 crc, cur_len);
295 len -= cur_len;
296 offset += cur_len;
19c00ddc 297 }
71a63551 298 memset(result, 0, BTRFS_CSUM_SIZE);
607d432d 299
19c00ddc
CM
300 btrfs_csum_final(crc, result);
301
302 if (verify) {
607d432d 303 if (memcmp_extent_buffer(buf, result, 0, csum_size)) {
e4204ded
CM
304 u32 val;
305 u32 found = 0;
607d432d 306 memcpy(&found, result, csum_size);
e4204ded 307
607d432d 308 read_extent_buffer(buf, &val, 0, csum_size);
94647322 309 btrfs_warn_rl(fs_info,
5d163e0e 310 "%s checksum verify failed on %llu wanted %X found %X level %d",
01d58472 311 fs_info->sb->s_id, buf->start,
efe120a0 312 val, found, btrfs_header_level(buf));
8bd98f0e 313 return -EUCLEAN;
19c00ddc
CM
314 }
315 } else {
607d432d 316 write_extent_buffer(buf, result, 0, csum_size);
19c00ddc 317 }
71a63551 318
19c00ddc
CM
319 return 0;
320}
321
d352ac68
CM
322/*
323 * we can't consider a given block up to date unless the transid of the
324 * block matches the transid in the parent node's pointer. This is how we
325 * detect blocks that either didn't get written at all or got written
326 * in the wrong place.
327 */
1259ab75 328static int verify_parent_transid(struct extent_io_tree *io_tree,
b9fab919
CM
329 struct extent_buffer *eb, u64 parent_transid,
330 int atomic)
1259ab75 331{
2ac55d41 332 struct extent_state *cached_state = NULL;
1259ab75 333 int ret;
2755a0de 334 bool need_lock = (current->journal_info == BTRFS_SEND_TRANS_STUB);
1259ab75
CM
335
336 if (!parent_transid || btrfs_header_generation(eb) == parent_transid)
337 return 0;
338
b9fab919
CM
339 if (atomic)
340 return -EAGAIN;
341
a26e8c9f
JB
342 if (need_lock) {
343 btrfs_tree_read_lock(eb);
344 btrfs_set_lock_blocking_rw(eb, BTRFS_READ_LOCK);
345 }
346
2ac55d41 347 lock_extent_bits(io_tree, eb->start, eb->start + eb->len - 1,
ff13db41 348 &cached_state);
0b32f4bb 349 if (extent_buffer_uptodate(eb) &&
1259ab75
CM
350 btrfs_header_generation(eb) == parent_transid) {
351 ret = 0;
352 goto out;
353 }
94647322
DS
354 btrfs_err_rl(eb->fs_info,
355 "parent transid verify failed on %llu wanted %llu found %llu",
356 eb->start,
29549aec 357 parent_transid, btrfs_header_generation(eb));
1259ab75 358 ret = 1;
a26e8c9f
JB
359
360 /*
361 * Things reading via commit roots that don't have normal protection,
362 * like send, can have a really old block in cache that may point at a
01327610 363 * block that has been freed and re-allocated. So don't clear uptodate
a26e8c9f
JB
364 * if we find an eb that is under IO (dirty/writeback) because we could
365 * end up reading in the stale data and then writing it back out and
366 * making everybody very sad.
367 */
368 if (!extent_buffer_under_io(eb))
369 clear_extent_buffer_uptodate(eb);
33958dc6 370out:
2ac55d41 371 unlock_extent_cached(io_tree, eb->start, eb->start + eb->len - 1,
e43bbe5e 372 &cached_state);
472b909f
JB
373 if (need_lock)
374 btrfs_tree_read_unlock_blocking(eb);
1259ab75 375 return ret;
1259ab75
CM
376}
377
1104a885
DS
378/*
379 * Return 0 if the superblock checksum type matches the checksum value of that
380 * algorithm. Pass the raw disk superblock data.
381 */
ab8d0fc4
JM
382static int btrfs_check_super_csum(struct btrfs_fs_info *fs_info,
383 char *raw_disk_sb)
1104a885
DS
384{
385 struct btrfs_super_block *disk_sb =
386 (struct btrfs_super_block *)raw_disk_sb;
387 u16 csum_type = btrfs_super_csum_type(disk_sb);
388 int ret = 0;
389
390 if (csum_type == BTRFS_CSUM_TYPE_CRC32) {
391 u32 crc = ~(u32)0;
776c4a7c 392 char result[sizeof(crc)];
1104a885
DS
393
394 /*
395 * The super_block structure does not span the whole
396 * BTRFS_SUPER_INFO_SIZE range, we expect that the unused space
01327610 397 * is filled with zeros and is included in the checksum.
1104a885
DS
398 */
399 crc = btrfs_csum_data(raw_disk_sb + BTRFS_CSUM_SIZE,
400 crc, BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE);
401 btrfs_csum_final(crc, result);
402
776c4a7c 403 if (memcmp(raw_disk_sb, result, sizeof(result)))
1104a885
DS
404 ret = 1;
405 }
406
407 if (csum_type >= ARRAY_SIZE(btrfs_csum_sizes)) {
ab8d0fc4 408 btrfs_err(fs_info, "unsupported checksum algorithm %u",
1104a885
DS
409 csum_type);
410 ret = 1;
411 }
412
413 return ret;
414}
415
581c1760
QW
416static int verify_level_key(struct btrfs_fs_info *fs_info,
417 struct extent_buffer *eb, int level,
ff76a864 418 struct btrfs_key *first_key, u64 parent_transid)
581c1760
QW
419{
420 int found_level;
421 struct btrfs_key found_key;
422 int ret;
423
424 found_level = btrfs_header_level(eb);
425 if (found_level != level) {
426#ifdef CONFIG_BTRFS_DEBUG
427 WARN_ON(1);
428 btrfs_err(fs_info,
429"tree level mismatch detected, bytenr=%llu level expected=%u has=%u",
430 eb->start, level, found_level);
431#endif
432 return -EIO;
433 }
434
435 if (!first_key)
436 return 0;
437
5d41be6f
QW
438 /*
439 * For live tree block (new tree blocks in current transaction),
440 * we need proper lock context to avoid race, which is impossible here.
441 * So we only checks tree blocks which is read from disk, whose
442 * generation <= fs_info->last_trans_committed.
443 */
444 if (btrfs_header_generation(eb) > fs_info->last_trans_committed)
445 return 0;
581c1760
QW
446 if (found_level)
447 btrfs_node_key_to_cpu(eb, &found_key, 0);
448 else
449 btrfs_item_key_to_cpu(eb, &found_key, 0);
450 ret = btrfs_comp_cpu_keys(first_key, &found_key);
451
452#ifdef CONFIG_BTRFS_DEBUG
453 if (ret) {
454 WARN_ON(1);
455 btrfs_err(fs_info,
ff76a864
LB
456"tree first key mismatch detected, bytenr=%llu parent_transid=%llu key expected=(%llu,%u,%llu) has=(%llu,%u,%llu)",
457 eb->start, parent_transid, first_key->objectid,
458 first_key->type, first_key->offset,
459 found_key.objectid, found_key.type,
460 found_key.offset);
581c1760
QW
461 }
462#endif
463 return ret;
464}
465
d352ac68
CM
466/*
467 * helper to read a given tree block, doing retries as required when
468 * the checksums don't match and we have alternate mirrors to try.
581c1760
QW
469 *
470 * @parent_transid: expected transid, skip check if 0
471 * @level: expected level, mandatory check
472 * @first_key: expected key of first slot, skip check if NULL
d352ac68 473 */
2ff7e61e 474static int btree_read_extent_buffer_pages(struct btrfs_fs_info *fs_info,
f188591e 475 struct extent_buffer *eb,
581c1760
QW
476 u64 parent_transid, int level,
477 struct btrfs_key *first_key)
f188591e
CM
478{
479 struct extent_io_tree *io_tree;
ea466794 480 int failed = 0;
f188591e
CM
481 int ret;
482 int num_copies = 0;
483 int mirror_num = 0;
ea466794 484 int failed_mirror = 0;
f188591e 485
a826d6dc 486 clear_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags);
0b246afa 487 io_tree = &BTRFS_I(fs_info->btree_inode)->io_tree;
f188591e 488 while (1) {
8436ea91 489 ret = read_extent_buffer_pages(io_tree, eb, WAIT_COMPLETE,
6af49dbd 490 mirror_num);
256dd1bb 491 if (!ret) {
581c1760 492 if (verify_parent_transid(io_tree, eb,
b9fab919 493 parent_transid, 0))
256dd1bb 494 ret = -EIO;
581c1760 495 else if (verify_level_key(fs_info, eb, level,
ff76a864 496 first_key, parent_transid))
581c1760
QW
497 ret = -EUCLEAN;
498 else
499 break;
256dd1bb 500 }
d397712b 501
a826d6dc
JB
502 /*
503 * This buffer's crc is fine, but its contents are corrupted, so
504 * there is no reason to read the other copies, they won't be
505 * any less wrong.
506 */
581c1760
QW
507 if (test_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags) ||
508 ret == -EUCLEAN)
ea466794
JB
509 break;
510
0b246afa 511 num_copies = btrfs_num_copies(fs_info,
f188591e 512 eb->start, eb->len);
4235298e 513 if (num_copies == 1)
ea466794 514 break;
4235298e 515
5cf1ab56
JB
516 if (!failed_mirror) {
517 failed = 1;
518 failed_mirror = eb->read_mirror;
519 }
520
f188591e 521 mirror_num++;
ea466794
JB
522 if (mirror_num == failed_mirror)
523 mirror_num++;
524
4235298e 525 if (mirror_num > num_copies)
ea466794 526 break;
f188591e 527 }
ea466794 528
c0901581 529 if (failed && !ret && failed_mirror)
2ff7e61e 530 repair_eb_io_failure(fs_info, eb, failed_mirror);
ea466794
JB
531
532 return ret;
f188591e 533}
19c00ddc 534
d352ac68 535/*
d397712b
CM
536 * checksum a dirty tree block before IO. This has extra checks to make sure
537 * we only fill in the checksum field in the first page of a multi-page block
d352ac68 538 */
d397712b 539
01d58472 540static int csum_dirty_buffer(struct btrfs_fs_info *fs_info, struct page *page)
19c00ddc 541{
4eee4fa4 542 u64 start = page_offset(page);
19c00ddc 543 u64 found_start;
19c00ddc 544 struct extent_buffer *eb;
f188591e 545
4f2de97a
JB
546 eb = (struct extent_buffer *)page->private;
547 if (page != eb->pages[0])
548 return 0;
0f805531 549
19c00ddc 550 found_start = btrfs_header_bytenr(eb);
0f805531
AL
551 /*
552 * Please do not consolidate these warnings into a single if.
553 * It is useful to know what went wrong.
554 */
555 if (WARN_ON(found_start != start))
556 return -EUCLEAN;
557 if (WARN_ON(!PageUptodate(page)))
558 return -EUCLEAN;
559
560 ASSERT(memcmp_extent_buffer(eb, fs_info->fsid,
561 btrfs_header_fsid(), BTRFS_FSID_SIZE) == 0);
562
8bd98f0e 563 return csum_tree_block(fs_info, eb, 0);
19c00ddc
CM
564}
565
01d58472 566static int check_tree_block_fsid(struct btrfs_fs_info *fs_info,
2b82032c
YZ
567 struct extent_buffer *eb)
568{
01d58472 569 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
44880fdc 570 u8 fsid[BTRFS_FSID_SIZE];
2b82032c
YZ
571 int ret = 1;
572
0a4e5586 573 read_extent_buffer(eb, fsid, btrfs_header_fsid(), BTRFS_FSID_SIZE);
2b82032c
YZ
574 while (fs_devices) {
575 if (!memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE)) {
576 ret = 0;
577 break;
578 }
579 fs_devices = fs_devices->seed;
580 }
581 return ret;
582}
583
facc8a22
MX
584static int btree_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
585 u64 phy_offset, struct page *page,
586 u64 start, u64 end, int mirror)
ce9adaa5 587{
ce9adaa5
CM
588 u64 found_start;
589 int found_level;
ce9adaa5
CM
590 struct extent_buffer *eb;
591 struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
02873e43 592 struct btrfs_fs_info *fs_info = root->fs_info;
f188591e 593 int ret = 0;
727011e0 594 int reads_done;
ce9adaa5 595
ce9adaa5
CM
596 if (!page->private)
597 goto out;
d397712b 598
4f2de97a 599 eb = (struct extent_buffer *)page->private;
d397712b 600
0b32f4bb
JB
601 /* the pending IO might have been the only thing that kept this buffer
602 * in memory. Make sure we have a ref for all this other checks
603 */
604 extent_buffer_get(eb);
605
606 reads_done = atomic_dec_and_test(&eb->io_pages);
727011e0
CM
607 if (!reads_done)
608 goto err;
f188591e 609
5cf1ab56 610 eb->read_mirror = mirror;
656f30db 611 if (test_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags)) {
ea466794
JB
612 ret = -EIO;
613 goto err;
614 }
615
ce9adaa5 616 found_start = btrfs_header_bytenr(eb);
727011e0 617 if (found_start != eb->start) {
893bf4b1
SY
618 btrfs_err_rl(fs_info, "bad tree block start, want %llu have %llu",
619 eb->start, found_start);
f188591e 620 ret = -EIO;
ce9adaa5
CM
621 goto err;
622 }
02873e43
ZL
623 if (check_tree_block_fsid(fs_info, eb)) {
624 btrfs_err_rl(fs_info, "bad fsid on block %llu",
625 eb->start);
1259ab75
CM
626 ret = -EIO;
627 goto err;
628 }
ce9adaa5 629 found_level = btrfs_header_level(eb);
1c24c3ce 630 if (found_level >= BTRFS_MAX_LEVEL) {
893bf4b1
SY
631 btrfs_err(fs_info, "bad tree block level %d on %llu",
632 (int)btrfs_header_level(eb), eb->start);
1c24c3ce
JB
633 ret = -EIO;
634 goto err;
635 }
ce9adaa5 636
85d4e461
CM
637 btrfs_set_buffer_lockdep_class(btrfs_header_owner(eb),
638 eb, found_level);
4008c04a 639
02873e43 640 ret = csum_tree_block(fs_info, eb, 1);
8bd98f0e 641 if (ret)
a826d6dc 642 goto err;
a826d6dc
JB
643
644 /*
645 * If this is a leaf block and it is corrupt, set the corrupt bit so
646 * that we don't try and read the other copies of this block, just
647 * return -EIO.
648 */
2f659546 649 if (found_level == 0 && btrfs_check_leaf_full(fs_info, eb)) {
a826d6dc
JB
650 set_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags);
651 ret = -EIO;
652 }
ce9adaa5 653
2f659546 654 if (found_level > 0 && btrfs_check_node(fs_info, eb))
053ab70f
LB
655 ret = -EIO;
656
0b32f4bb
JB
657 if (!ret)
658 set_extent_buffer_uptodate(eb);
ce9adaa5 659err:
79fb65a1
JB
660 if (reads_done &&
661 test_and_clear_bit(EXTENT_BUFFER_READAHEAD, &eb->bflags))
d48d71aa 662 btree_readahead_hook(eb, ret);
4bb31e92 663
53b381b3
DW
664 if (ret) {
665 /*
666 * our io error hook is going to dec the io pages
667 * again, we have to make sure it has something
668 * to decrement
669 */
670 atomic_inc(&eb->io_pages);
0b32f4bb 671 clear_extent_buffer_uptodate(eb);
53b381b3 672 }
0b32f4bb 673 free_extent_buffer(eb);
ce9adaa5 674out:
f188591e 675 return ret;
ce9adaa5
CM
676}
677
ea466794 678static int btree_io_failed_hook(struct page *page, int failed_mirror)
4bb31e92 679{
4bb31e92 680 struct extent_buffer *eb;
4bb31e92 681
4f2de97a 682 eb = (struct extent_buffer *)page->private;
656f30db 683 set_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
5cf1ab56 684 eb->read_mirror = failed_mirror;
53b381b3 685 atomic_dec(&eb->io_pages);
ea466794 686 if (test_and_clear_bit(EXTENT_BUFFER_READAHEAD, &eb->bflags))
d48d71aa 687 btree_readahead_hook(eb, -EIO);
4bb31e92
AJ
688 return -EIO; /* we fixed nothing */
689}
690
4246a0b6 691static void end_workqueue_bio(struct bio *bio)
ce9adaa5 692{
97eb6b69 693 struct btrfs_end_io_wq *end_io_wq = bio->bi_private;
ce9adaa5 694 struct btrfs_fs_info *fs_info;
9e0af237
LB
695 struct btrfs_workqueue *wq;
696 btrfs_work_func_t func;
ce9adaa5 697
ce9adaa5 698 fs_info = end_io_wq->info;
4e4cbee9 699 end_io_wq->status = bio->bi_status;
d20f7043 700
37226b21 701 if (bio_op(bio) == REQ_OP_WRITE) {
9e0af237
LB
702 if (end_io_wq->metadata == BTRFS_WQ_ENDIO_METADATA) {
703 wq = fs_info->endio_meta_write_workers;
704 func = btrfs_endio_meta_write_helper;
705 } else if (end_io_wq->metadata == BTRFS_WQ_ENDIO_FREE_SPACE) {
706 wq = fs_info->endio_freespace_worker;
707 func = btrfs_freespace_write_helper;
708 } else if (end_io_wq->metadata == BTRFS_WQ_ENDIO_RAID56) {
709 wq = fs_info->endio_raid56_workers;
710 func = btrfs_endio_raid56_helper;
711 } else {
712 wq = fs_info->endio_write_workers;
713 func = btrfs_endio_write_helper;
714 }
d20f7043 715 } else {
8b110e39
MX
716 if (unlikely(end_io_wq->metadata ==
717 BTRFS_WQ_ENDIO_DIO_REPAIR)) {
718 wq = fs_info->endio_repair_workers;
719 func = btrfs_endio_repair_helper;
720 } else if (end_io_wq->metadata == BTRFS_WQ_ENDIO_RAID56) {
9e0af237
LB
721 wq = fs_info->endio_raid56_workers;
722 func = btrfs_endio_raid56_helper;
723 } else if (end_io_wq->metadata) {
724 wq = fs_info->endio_meta_workers;
725 func = btrfs_endio_meta_helper;
726 } else {
727 wq = fs_info->endio_workers;
728 func = btrfs_endio_helper;
729 }
d20f7043 730 }
9e0af237
LB
731
732 btrfs_init_work(&end_io_wq->work, func, end_workqueue_fn, NULL, NULL);
733 btrfs_queue_work(wq, &end_io_wq->work);
ce9adaa5
CM
734}
735
4e4cbee9 736blk_status_t btrfs_bio_wq_end_io(struct btrfs_fs_info *info, struct bio *bio,
bfebd8b5 737 enum btrfs_wq_endio_type metadata)
0b86a832 738{
97eb6b69 739 struct btrfs_end_io_wq *end_io_wq;
8b110e39 740
97eb6b69 741 end_io_wq = kmem_cache_alloc(btrfs_end_io_wq_cache, GFP_NOFS);
ce9adaa5 742 if (!end_io_wq)
4e4cbee9 743 return BLK_STS_RESOURCE;
ce9adaa5
CM
744
745 end_io_wq->private = bio->bi_private;
746 end_io_wq->end_io = bio->bi_end_io;
22c59948 747 end_io_wq->info = info;
4e4cbee9 748 end_io_wq->status = 0;
ce9adaa5 749 end_io_wq->bio = bio;
22c59948 750 end_io_wq->metadata = metadata;
ce9adaa5
CM
751
752 bio->bi_private = end_io_wq;
753 bio->bi_end_io = end_workqueue_bio;
22c59948
CM
754 return 0;
755}
756
4a69a410
CM
757static void run_one_async_start(struct btrfs_work *work)
758{
4a69a410 759 struct async_submit_bio *async;
4e4cbee9 760 blk_status_t ret;
4a69a410
CM
761
762 async = container_of(work, struct async_submit_bio, work);
c6100a4b 763 ret = async->submit_bio_start(async->private_data, async->bio,
79787eaa
JM
764 async->bio_offset);
765 if (ret)
4e4cbee9 766 async->status = ret;
4a69a410
CM
767}
768
769static void run_one_async_done(struct btrfs_work *work)
8b712842 770{
8b712842
CM
771 struct async_submit_bio *async;
772
773 async = container_of(work, struct async_submit_bio, work);
4854ddd0 774
bb7ab3b9 775 /* If an error occurred we just want to clean up the bio and move on */
4e4cbee9
CH
776 if (async->status) {
777 async->bio->bi_status = async->status;
4246a0b6 778 bio_endio(async->bio);
79787eaa
JM
779 return;
780 }
781
6c553435 782 async->submit_bio_done(async->private_data, async->bio, async->mirror_num);
4a69a410
CM
783}
784
785static void run_one_async_free(struct btrfs_work *work)
786{
787 struct async_submit_bio *async;
788
789 async = container_of(work, struct async_submit_bio, work);
8b712842
CM
790 kfree(async);
791}
792
8c27cb35
LT
793blk_status_t btrfs_wq_submit_bio(struct btrfs_fs_info *fs_info, struct bio *bio,
794 int mirror_num, unsigned long bio_flags,
795 u64 bio_offset, void *private_data,
a758781d
DS
796 extent_submit_bio_start_t *submit_bio_start,
797 extent_submit_bio_done_t *submit_bio_done)
44b8bd7e
CM
798{
799 struct async_submit_bio *async;
800
801 async = kmalloc(sizeof(*async), GFP_NOFS);
802 if (!async)
4e4cbee9 803 return BLK_STS_RESOURCE;
44b8bd7e 804
c6100a4b
JB
805 async->private_data = private_data;
806 async->fs_info = fs_info;
44b8bd7e
CM
807 async->bio = bio;
808 async->mirror_num = mirror_num;
4a69a410
CM
809 async->submit_bio_start = submit_bio_start;
810 async->submit_bio_done = submit_bio_done;
811
9e0af237 812 btrfs_init_work(&async->work, btrfs_worker_helper, run_one_async_start,
5cdc7ad3 813 run_one_async_done, run_one_async_free);
4a69a410 814
c8b97818 815 async->bio_flags = bio_flags;
eaf25d93 816 async->bio_offset = bio_offset;
8c8bee1d 817
4e4cbee9 818 async->status = 0;
79787eaa 819
67f055c7 820 if (op_is_sync(bio->bi_opf))
5cdc7ad3 821 btrfs_set_work_high_priority(&async->work);
d313d7a3 822
5cdc7ad3 823 btrfs_queue_work(fs_info->workers, &async->work);
44b8bd7e
CM
824 return 0;
825}
826
4e4cbee9 827static blk_status_t btree_csum_one_bio(struct bio *bio)
ce3ed71a 828{
2c30c71b 829 struct bio_vec *bvec;
ce3ed71a 830 struct btrfs_root *root;
2c30c71b 831 int i, ret = 0;
ce3ed71a 832
c09abff8 833 ASSERT(!bio_flagged(bio, BIO_CLONED));
2c30c71b 834 bio_for_each_segment_all(bvec, bio, i) {
ce3ed71a 835 root = BTRFS_I(bvec->bv_page->mapping->host)->root;
01d58472 836 ret = csum_dirty_buffer(root->fs_info, bvec->bv_page);
79787eaa
JM
837 if (ret)
838 break;
ce3ed71a 839 }
2c30c71b 840
4e4cbee9 841 return errno_to_blk_status(ret);
ce3ed71a
CM
842}
843
d0ee3934 844static blk_status_t btree_submit_bio_start(void *private_data, struct bio *bio,
8c27cb35 845 u64 bio_offset)
22c59948 846{
8b712842
CM
847 /*
848 * when we're called for a write, we're already in the async
5443be45 849 * submission context. Just jump into btrfs_map_bio
8b712842 850 */
79787eaa 851 return btree_csum_one_bio(bio);
4a69a410 852}
22c59948 853
d0ee3934 854static blk_status_t btree_submit_bio_done(void *private_data, struct bio *bio,
6c553435 855 int mirror_num)
4a69a410 856{
c6100a4b 857 struct inode *inode = private_data;
4e4cbee9 858 blk_status_t ret;
61891923 859
8b712842 860 /*
4a69a410
CM
861 * when we're called for a write, we're already in the async
862 * submission context. Just jump into btrfs_map_bio
8b712842 863 */
2ff7e61e 864 ret = btrfs_map_bio(btrfs_sb(inode->i_sb), bio, mirror_num, 1);
4246a0b6 865 if (ret) {
4e4cbee9 866 bio->bi_status = ret;
4246a0b6
CH
867 bio_endio(bio);
868 }
61891923 869 return ret;
0b86a832
CM
870}
871
18fdc679 872static int check_async_write(struct btrfs_inode *bi)
de0022b9 873{
6300463b
LB
874 if (atomic_read(&bi->sync_writers))
875 return 0;
de0022b9 876#ifdef CONFIG_X86
bc696ca0 877 if (static_cpu_has(X86_FEATURE_XMM4_2))
de0022b9
JB
878 return 0;
879#endif
880 return 1;
881}
882
8c27cb35
LT
883static blk_status_t btree_submit_bio_hook(void *private_data, struct bio *bio,
884 int mirror_num, unsigned long bio_flags,
885 u64 bio_offset)
44b8bd7e 886{
c6100a4b 887 struct inode *inode = private_data;
0b246afa 888 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
18fdc679 889 int async = check_async_write(BTRFS_I(inode));
4e4cbee9 890 blk_status_t ret;
cad321ad 891
37226b21 892 if (bio_op(bio) != REQ_OP_WRITE) {
4a69a410
CM
893 /*
894 * called for a read, do the setup so that checksum validation
895 * can happen in the async kernel threads
896 */
0b246afa
JM
897 ret = btrfs_bio_wq_end_io(fs_info, bio,
898 BTRFS_WQ_ENDIO_METADATA);
1d4284bd 899 if (ret)
61891923 900 goto out_w_error;
2ff7e61e 901 ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
de0022b9
JB
902 } else if (!async) {
903 ret = btree_csum_one_bio(bio);
904 if (ret)
61891923 905 goto out_w_error;
2ff7e61e 906 ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
61891923
SB
907 } else {
908 /*
909 * kthread helpers are used to submit writes so that
910 * checksumming can happen in parallel across all CPUs
911 */
c6100a4b
JB
912 ret = btrfs_wq_submit_bio(fs_info, bio, mirror_num, 0,
913 bio_offset, private_data,
d0ee3934
DS
914 btree_submit_bio_start,
915 btree_submit_bio_done);
44b8bd7e 916 }
d313d7a3 917
4246a0b6
CH
918 if (ret)
919 goto out_w_error;
920 return 0;
921
61891923 922out_w_error:
4e4cbee9 923 bio->bi_status = ret;
4246a0b6 924 bio_endio(bio);
61891923 925 return ret;
44b8bd7e
CM
926}
927
3dd1462e 928#ifdef CONFIG_MIGRATION
784b4e29 929static int btree_migratepage(struct address_space *mapping,
a6bc32b8
MG
930 struct page *newpage, struct page *page,
931 enum migrate_mode mode)
784b4e29
CM
932{
933 /*
934 * we can't safely write a btree page from here,
935 * we haven't done the locking hook
936 */
937 if (PageDirty(page))
938 return -EAGAIN;
939 /*
940 * Buffers may be managed in a filesystem specific way.
941 * We must have no buffers or drop them.
942 */
943 if (page_has_private(page) &&
944 !try_to_release_page(page, GFP_KERNEL))
945 return -EAGAIN;
a6bc32b8 946 return migrate_page(mapping, newpage, page, mode);
784b4e29 947}
3dd1462e 948#endif
784b4e29 949
0da5468f
CM
950
951static int btree_writepages(struct address_space *mapping,
952 struct writeback_control *wbc)
953{
e2d84521
MX
954 struct btrfs_fs_info *fs_info;
955 int ret;
956
d8d5f3e1 957 if (wbc->sync_mode == WB_SYNC_NONE) {
448d640b
CM
958
959 if (wbc->for_kupdate)
960 return 0;
961
e2d84521 962 fs_info = BTRFS_I(mapping->host)->root->fs_info;
b9473439 963 /* this is a bit racy, but that's ok */
e2d84521
MX
964 ret = percpu_counter_compare(&fs_info->dirty_metadata_bytes,
965 BTRFS_DIRTY_METADATA_THRESH);
966 if (ret < 0)
793955bc 967 return 0;
793955bc 968 }
0b32f4bb 969 return btree_write_cache_pages(mapping, wbc);
0da5468f
CM
970}
971
b2950863 972static int btree_readpage(struct file *file, struct page *page)
5f39d397 973{
d1310b2e
CM
974 struct extent_io_tree *tree;
975 tree = &BTRFS_I(page->mapping->host)->io_tree;
8ddc7d9c 976 return extent_read_full_page(tree, page, btree_get_extent, 0);
5f39d397 977}
22b0ebda 978
70dec807 979static int btree_releasepage(struct page *page, gfp_t gfp_flags)
5f39d397 980{
98509cfc 981 if (PageWriteback(page) || PageDirty(page))
d397712b 982 return 0;
0c4e538b 983
f7a52a40 984 return try_release_extent_buffer(page);
d98237b3
CM
985}
986
d47992f8
LC
987static void btree_invalidatepage(struct page *page, unsigned int offset,
988 unsigned int length)
d98237b3 989{
d1310b2e
CM
990 struct extent_io_tree *tree;
991 tree = &BTRFS_I(page->mapping->host)->io_tree;
5f39d397
CM
992 extent_invalidatepage(tree, page, offset);
993 btree_releasepage(page, GFP_NOFS);
9ad6b7bc 994 if (PagePrivate(page)) {
efe120a0
FH
995 btrfs_warn(BTRFS_I(page->mapping->host)->root->fs_info,
996 "page private not zero on page %llu",
997 (unsigned long long)page_offset(page));
9ad6b7bc
CM
998 ClearPagePrivate(page);
999 set_page_private(page, 0);
09cbfeaf 1000 put_page(page);
9ad6b7bc 1001 }
d98237b3
CM
1002}
1003
0b32f4bb
JB
1004static int btree_set_page_dirty(struct page *page)
1005{
bb146eb2 1006#ifdef DEBUG
0b32f4bb
JB
1007 struct extent_buffer *eb;
1008
1009 BUG_ON(!PagePrivate(page));
1010 eb = (struct extent_buffer *)page->private;
1011 BUG_ON(!eb);
1012 BUG_ON(!test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
1013 BUG_ON(!atomic_read(&eb->refs));
1014 btrfs_assert_tree_locked(eb);
bb146eb2 1015#endif
0b32f4bb
JB
1016 return __set_page_dirty_nobuffers(page);
1017}
1018
7f09410b 1019static const struct address_space_operations btree_aops = {
d98237b3 1020 .readpage = btree_readpage,
0da5468f 1021 .writepages = btree_writepages,
5f39d397
CM
1022 .releasepage = btree_releasepage,
1023 .invalidatepage = btree_invalidatepage,
5a92bc88 1024#ifdef CONFIG_MIGRATION
784b4e29 1025 .migratepage = btree_migratepage,
5a92bc88 1026#endif
0b32f4bb 1027 .set_page_dirty = btree_set_page_dirty,
d98237b3
CM
1028};
1029
2ff7e61e 1030void readahead_tree_block(struct btrfs_fs_info *fs_info, u64 bytenr)
090d1875 1031{
5f39d397 1032 struct extent_buffer *buf = NULL;
2ff7e61e 1033 struct inode *btree_inode = fs_info->btree_inode;
090d1875 1034
2ff7e61e 1035 buf = btrfs_find_create_tree_block(fs_info, bytenr);
c871b0f2 1036 if (IS_ERR(buf))
6197d86e 1037 return;
d1310b2e 1038 read_extent_buffer_pages(&BTRFS_I(btree_inode)->io_tree,
6af49dbd 1039 buf, WAIT_NONE, 0);
5f39d397 1040 free_extent_buffer(buf);
090d1875
CM
1041}
1042
2ff7e61e 1043int reada_tree_block_flagged(struct btrfs_fs_info *fs_info, u64 bytenr,
ab0fff03
AJ
1044 int mirror_num, struct extent_buffer **eb)
1045{
1046 struct extent_buffer *buf = NULL;
2ff7e61e 1047 struct inode *btree_inode = fs_info->btree_inode;
ab0fff03
AJ
1048 struct extent_io_tree *io_tree = &BTRFS_I(btree_inode)->io_tree;
1049 int ret;
1050
2ff7e61e 1051 buf = btrfs_find_create_tree_block(fs_info, bytenr);
c871b0f2 1052 if (IS_ERR(buf))
ab0fff03
AJ
1053 return 0;
1054
1055 set_bit(EXTENT_BUFFER_READAHEAD, &buf->bflags);
1056
8436ea91 1057 ret = read_extent_buffer_pages(io_tree, buf, WAIT_PAGE_LOCK,
6af49dbd 1058 mirror_num);
ab0fff03
AJ
1059 if (ret) {
1060 free_extent_buffer(buf);
1061 return ret;
1062 }
1063
1064 if (test_bit(EXTENT_BUFFER_CORRUPT, &buf->bflags)) {
1065 free_extent_buffer(buf);
1066 return -EIO;
0b32f4bb 1067 } else if (extent_buffer_uptodate(buf)) {
ab0fff03
AJ
1068 *eb = buf;
1069 } else {
1070 free_extent_buffer(buf);
1071 }
1072 return 0;
1073}
1074
2ff7e61e
JM
1075struct extent_buffer *btrfs_find_create_tree_block(
1076 struct btrfs_fs_info *fs_info,
1077 u64 bytenr)
0999df54 1078{
0b246afa
JM
1079 if (btrfs_is_testing(fs_info))
1080 return alloc_test_extent_buffer(fs_info, bytenr);
1081 return alloc_extent_buffer(fs_info, bytenr);
0999df54
CM
1082}
1083
1084
e02119d5
CM
1085int btrfs_write_tree_block(struct extent_buffer *buf)
1086{
727011e0 1087 return filemap_fdatawrite_range(buf->pages[0]->mapping, buf->start,
8aa38c31 1088 buf->start + buf->len - 1);
e02119d5
CM
1089}
1090
3189ff77 1091void btrfs_wait_tree_block_writeback(struct extent_buffer *buf)
e02119d5 1092{
3189ff77
JL
1093 filemap_fdatawait_range(buf->pages[0]->mapping,
1094 buf->start, buf->start + buf->len - 1);
e02119d5
CM
1095}
1096
581c1760
QW
1097/*
1098 * Read tree block at logical address @bytenr and do variant basic but critical
1099 * verification.
1100 *
1101 * @parent_transid: expected transid of this tree block, skip check if 0
1102 * @level: expected level, mandatory check
1103 * @first_key: expected key in slot 0, skip check if NULL
1104 */
2ff7e61e 1105struct extent_buffer *read_tree_block(struct btrfs_fs_info *fs_info, u64 bytenr,
581c1760
QW
1106 u64 parent_transid, int level,
1107 struct btrfs_key *first_key)
0999df54
CM
1108{
1109 struct extent_buffer *buf = NULL;
0999df54
CM
1110 int ret;
1111
2ff7e61e 1112 buf = btrfs_find_create_tree_block(fs_info, bytenr);
c871b0f2
LB
1113 if (IS_ERR(buf))
1114 return buf;
0999df54 1115
581c1760
QW
1116 ret = btree_read_extent_buffer_pages(fs_info, buf, parent_transid,
1117 level, first_key);
0f0fe8f7
FDBM
1118 if (ret) {
1119 free_extent_buffer(buf);
64c043de 1120 return ERR_PTR(ret);
0f0fe8f7 1121 }
5f39d397 1122 return buf;
ce9adaa5 1123
eb60ceac
CM
1124}
1125
7c302b49 1126void clean_tree_block(struct btrfs_fs_info *fs_info,
d5c13f92 1127 struct extent_buffer *buf)
ed2ff2cb 1128{
55c69072 1129 if (btrfs_header_generation(buf) ==
e2d84521 1130 fs_info->running_transaction->transid) {
b9447ef8 1131 btrfs_assert_tree_locked(buf);
b4ce94de 1132
b9473439 1133 if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &buf->bflags)) {
104b4e51
NB
1134 percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
1135 -buf->len,
1136 fs_info->dirty_metadata_batch);
ed7b63eb
JB
1137 /* ugh, clear_extent_buffer_dirty needs to lock the page */
1138 btrfs_set_lock_blocking(buf);
1139 clear_extent_buffer_dirty(buf);
1140 }
925baedd 1141 }
5f39d397
CM
1142}
1143
8257b2dc
MX
1144static struct btrfs_subvolume_writers *btrfs_alloc_subvolume_writers(void)
1145{
1146 struct btrfs_subvolume_writers *writers;
1147 int ret;
1148
1149 writers = kmalloc(sizeof(*writers), GFP_NOFS);
1150 if (!writers)
1151 return ERR_PTR(-ENOMEM);
1152
8a5a916d 1153 ret = percpu_counter_init(&writers->counter, 0, GFP_NOFS);
8257b2dc
MX
1154 if (ret < 0) {
1155 kfree(writers);
1156 return ERR_PTR(ret);
1157 }
1158
1159 init_waitqueue_head(&writers->wait);
1160 return writers;
1161}
1162
1163static void
1164btrfs_free_subvolume_writers(struct btrfs_subvolume_writers *writers)
1165{
1166 percpu_counter_destroy(&writers->counter);
1167 kfree(writers);
1168}
1169
da17066c 1170static void __setup_root(struct btrfs_root *root, struct btrfs_fs_info *fs_info,
143bede5 1171 u64 objectid)
d97e63b6 1172{
7c0260ee 1173 bool dummy = test_bit(BTRFS_FS_STATE_DUMMY_FS_INFO, &fs_info->fs_state);
cfaa7295 1174 root->node = NULL;
a28ec197 1175 root->commit_root = NULL;
27cdeb70 1176 root->state = 0;
d68fc57b 1177 root->orphan_cleanup_state = 0;
0b86a832 1178
0f7d52f4
CM
1179 root->objectid = objectid;
1180 root->last_trans = 0;
13a8a7c8 1181 root->highest_objectid = 0;
eb73c1b7 1182 root->nr_delalloc_inodes = 0;
199c2a9c 1183 root->nr_ordered_extents = 0;
58176a96 1184 root->name = NULL;
6bef4d31 1185 root->inode_tree = RB_ROOT;
16cdcec7 1186 INIT_RADIX_TREE(&root->delayed_nodes_tree, GFP_ATOMIC);
f0486c68 1187 root->block_rsv = NULL;
0b86a832
CM
1188
1189 INIT_LIST_HEAD(&root->dirty_list);
5d4f98a2 1190 INIT_LIST_HEAD(&root->root_list);
eb73c1b7
MX
1191 INIT_LIST_HEAD(&root->delalloc_inodes);
1192 INIT_LIST_HEAD(&root->delalloc_root);
199c2a9c
MX
1193 INIT_LIST_HEAD(&root->ordered_extents);
1194 INIT_LIST_HEAD(&root->ordered_root);
2ab28f32
JB
1195 INIT_LIST_HEAD(&root->logged_list[0]);
1196 INIT_LIST_HEAD(&root->logged_list[1]);
5d4f98a2 1197 spin_lock_init(&root->inode_lock);
eb73c1b7 1198 spin_lock_init(&root->delalloc_lock);
199c2a9c 1199 spin_lock_init(&root->ordered_extent_lock);
f0486c68 1200 spin_lock_init(&root->accounting_lock);
2ab28f32
JB
1201 spin_lock_init(&root->log_extents_lock[0]);
1202 spin_lock_init(&root->log_extents_lock[1]);
8287475a 1203 spin_lock_init(&root->qgroup_meta_rsv_lock);
a2135011 1204 mutex_init(&root->objectid_mutex);
e02119d5 1205 mutex_init(&root->log_mutex);
31f3d255 1206 mutex_init(&root->ordered_extent_mutex);
573bfb72 1207 mutex_init(&root->delalloc_mutex);
7237f183
YZ
1208 init_waitqueue_head(&root->log_writer_wait);
1209 init_waitqueue_head(&root->log_commit_wait[0]);
1210 init_waitqueue_head(&root->log_commit_wait[1]);
8b050d35
MX
1211 INIT_LIST_HEAD(&root->log_ctxs[0]);
1212 INIT_LIST_HEAD(&root->log_ctxs[1]);
7237f183
YZ
1213 atomic_set(&root->log_commit[0], 0);
1214 atomic_set(&root->log_commit[1], 0);
1215 atomic_set(&root->log_writers, 0);
2ecb7923 1216 atomic_set(&root->log_batch, 0);
0700cea7 1217 refcount_set(&root->refs, 1);
ea14b57f 1218 atomic_set(&root->will_be_snapshotted, 0);
7237f183 1219 root->log_transid = 0;
d1433deb 1220 root->log_transid_committed = -1;
257c62e1 1221 root->last_log_commit = 0;
7c0260ee 1222 if (!dummy)
c6100a4b 1223 extent_io_tree_init(&root->dirty_log_pages, NULL);
017e5369 1224
3768f368
CM
1225 memset(&root->root_key, 0, sizeof(root->root_key));
1226 memset(&root->root_item, 0, sizeof(root->root_item));
6702ed49 1227 memset(&root->defrag_progress, 0, sizeof(root->defrag_progress));
7c0260ee 1228 if (!dummy)
06ea65a3
JB
1229 root->defrag_trans_start = fs_info->generation;
1230 else
1231 root->defrag_trans_start = 0;
4d775673 1232 root->root_key.objectid = objectid;
0ee5dc67 1233 root->anon_dev = 0;
8ea05e3a 1234
5f3ab90a 1235 spin_lock_init(&root->root_item_lock);
3768f368
CM
1236}
1237
74e4d827
DS
1238static struct btrfs_root *btrfs_alloc_root(struct btrfs_fs_info *fs_info,
1239 gfp_t flags)
6f07e42e 1240{
74e4d827 1241 struct btrfs_root *root = kzalloc(sizeof(*root), flags);
6f07e42e
AV
1242 if (root)
1243 root->fs_info = fs_info;
1244 return root;
1245}
1246
06ea65a3
JB
1247#ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
1248/* Should only be used by the testing infrastructure */
da17066c 1249struct btrfs_root *btrfs_alloc_dummy_root(struct btrfs_fs_info *fs_info)
06ea65a3
JB
1250{
1251 struct btrfs_root *root;
1252
7c0260ee
JM
1253 if (!fs_info)
1254 return ERR_PTR(-EINVAL);
1255
1256 root = btrfs_alloc_root(fs_info, GFP_KERNEL);
06ea65a3
JB
1257 if (!root)
1258 return ERR_PTR(-ENOMEM);
da17066c 1259
b9ef22de 1260 /* We don't use the stripesize in selftest, set it as sectorsize */
da17066c 1261 __setup_root(root, fs_info, BTRFS_ROOT_TREE_OBJECTID);
faa2dbf0 1262 root->alloc_bytenr = 0;
06ea65a3
JB
1263
1264 return root;
1265}
1266#endif
1267
20897f5c
AJ
1268struct btrfs_root *btrfs_create_tree(struct btrfs_trans_handle *trans,
1269 struct btrfs_fs_info *fs_info,
1270 u64 objectid)
1271{
1272 struct extent_buffer *leaf;
1273 struct btrfs_root *tree_root = fs_info->tree_root;
1274 struct btrfs_root *root;
1275 struct btrfs_key key;
1276 int ret = 0;
33d85fda 1277 uuid_le uuid = NULL_UUID_LE;
20897f5c 1278
74e4d827 1279 root = btrfs_alloc_root(fs_info, GFP_KERNEL);
20897f5c
AJ
1280 if (!root)
1281 return ERR_PTR(-ENOMEM);
1282
da17066c 1283 __setup_root(root, fs_info, objectid);
20897f5c
AJ
1284 root->root_key.objectid = objectid;
1285 root->root_key.type = BTRFS_ROOT_ITEM_KEY;
1286 root->root_key.offset = 0;
1287
4d75f8a9 1288 leaf = btrfs_alloc_tree_block(trans, root, 0, objectid, NULL, 0, 0, 0);
20897f5c
AJ
1289 if (IS_ERR(leaf)) {
1290 ret = PTR_ERR(leaf);
1dd05682 1291 leaf = NULL;
20897f5c
AJ
1292 goto fail;
1293 }
1294
20897f5c 1295 root->node = leaf;
20897f5c
AJ
1296 btrfs_mark_buffer_dirty(leaf);
1297
1298 root->commit_root = btrfs_root_node(root);
27cdeb70 1299 set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
20897f5c
AJ
1300
1301 root->root_item.flags = 0;
1302 root->root_item.byte_limit = 0;
1303 btrfs_set_root_bytenr(&root->root_item, leaf->start);
1304 btrfs_set_root_generation(&root->root_item, trans->transid);
1305 btrfs_set_root_level(&root->root_item, 0);
1306 btrfs_set_root_refs(&root->root_item, 1);
1307 btrfs_set_root_used(&root->root_item, leaf->len);
1308 btrfs_set_root_last_snapshot(&root->root_item, 0);
1309 btrfs_set_root_dirid(&root->root_item, 0);
33d85fda
QW
1310 if (is_fstree(objectid))
1311 uuid_le_gen(&uuid);
6463fe58 1312 memcpy(root->root_item.uuid, uuid.b, BTRFS_UUID_SIZE);
20897f5c
AJ
1313 root->root_item.drop_level = 0;
1314
1315 key.objectid = objectid;
1316 key.type = BTRFS_ROOT_ITEM_KEY;
1317 key.offset = 0;
1318 ret = btrfs_insert_root(trans, tree_root, &key, &root->root_item);
1319 if (ret)
1320 goto fail;
1321
1322 btrfs_tree_unlock(leaf);
1323
1dd05682
TI
1324 return root;
1325
20897f5c 1326fail:
1dd05682
TI
1327 if (leaf) {
1328 btrfs_tree_unlock(leaf);
59885b39 1329 free_extent_buffer(root->commit_root);
1dd05682
TI
1330 free_extent_buffer(leaf);
1331 }
1332 kfree(root);
20897f5c 1333
1dd05682 1334 return ERR_PTR(ret);
20897f5c
AJ
1335}
1336
7237f183
YZ
1337static struct btrfs_root *alloc_log_tree(struct btrfs_trans_handle *trans,
1338 struct btrfs_fs_info *fs_info)
0f7d52f4
CM
1339{
1340 struct btrfs_root *root;
7237f183 1341 struct extent_buffer *leaf;
e02119d5 1342
74e4d827 1343 root = btrfs_alloc_root(fs_info, GFP_NOFS);
e02119d5 1344 if (!root)
7237f183 1345 return ERR_PTR(-ENOMEM);
e02119d5 1346
da17066c 1347 __setup_root(root, fs_info, BTRFS_TREE_LOG_OBJECTID);
e02119d5
CM
1348
1349 root->root_key.objectid = BTRFS_TREE_LOG_OBJECTID;
1350 root->root_key.type = BTRFS_ROOT_ITEM_KEY;
1351 root->root_key.offset = BTRFS_TREE_LOG_OBJECTID;
27cdeb70 1352
7237f183 1353 /*
27cdeb70
MX
1354 * DON'T set REF_COWS for log trees
1355 *
7237f183
YZ
1356 * log trees do not get reference counted because they go away
1357 * before a real commit is actually done. They do store pointers
1358 * to file data extents, and those reference counts still get
1359 * updated (along with back refs to the log tree).
1360 */
e02119d5 1361
4d75f8a9
DS
1362 leaf = btrfs_alloc_tree_block(trans, root, 0, BTRFS_TREE_LOG_OBJECTID,
1363 NULL, 0, 0, 0);
7237f183
YZ
1364 if (IS_ERR(leaf)) {
1365 kfree(root);
1366 return ERR_CAST(leaf);
1367 }
e02119d5 1368
7237f183 1369 root->node = leaf;
e02119d5 1370
e02119d5
CM
1371 btrfs_mark_buffer_dirty(root->node);
1372 btrfs_tree_unlock(root->node);
7237f183
YZ
1373 return root;
1374}
1375
1376int btrfs_init_log_root_tree(struct btrfs_trans_handle *trans,
1377 struct btrfs_fs_info *fs_info)
1378{
1379 struct btrfs_root *log_root;
1380
1381 log_root = alloc_log_tree(trans, fs_info);
1382 if (IS_ERR(log_root))
1383 return PTR_ERR(log_root);
1384 WARN_ON(fs_info->log_root_tree);
1385 fs_info->log_root_tree = log_root;
1386 return 0;
1387}
1388
1389int btrfs_add_log_tree(struct btrfs_trans_handle *trans,
1390 struct btrfs_root *root)
1391{
0b246afa 1392 struct btrfs_fs_info *fs_info = root->fs_info;
7237f183
YZ
1393 struct btrfs_root *log_root;
1394 struct btrfs_inode_item *inode_item;
1395
0b246afa 1396 log_root = alloc_log_tree(trans, fs_info);
7237f183
YZ
1397 if (IS_ERR(log_root))
1398 return PTR_ERR(log_root);
1399
1400 log_root->last_trans = trans->transid;
1401 log_root->root_key.offset = root->root_key.objectid;
1402
1403 inode_item = &log_root->root_item.inode;
3cae210f
QW
1404 btrfs_set_stack_inode_generation(inode_item, 1);
1405 btrfs_set_stack_inode_size(inode_item, 3);
1406 btrfs_set_stack_inode_nlink(inode_item, 1);
da17066c 1407 btrfs_set_stack_inode_nbytes(inode_item,
0b246afa 1408 fs_info->nodesize);
3cae210f 1409 btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
7237f183 1410
5d4f98a2 1411 btrfs_set_root_node(&log_root->root_item, log_root->node);
7237f183
YZ
1412
1413 WARN_ON(root->log_root);
1414 root->log_root = log_root;
1415 root->log_transid = 0;
d1433deb 1416 root->log_transid_committed = -1;
257c62e1 1417 root->last_log_commit = 0;
e02119d5
CM
1418 return 0;
1419}
1420
35a3621b
SB
1421static struct btrfs_root *btrfs_read_tree_root(struct btrfs_root *tree_root,
1422 struct btrfs_key *key)
e02119d5
CM
1423{
1424 struct btrfs_root *root;
1425 struct btrfs_fs_info *fs_info = tree_root->fs_info;
0f7d52f4 1426 struct btrfs_path *path;
84234f3a 1427 u64 generation;
cb517eab 1428 int ret;
581c1760 1429 int level;
0f7d52f4 1430
cb517eab
MX
1431 path = btrfs_alloc_path();
1432 if (!path)
0f7d52f4 1433 return ERR_PTR(-ENOMEM);
cb517eab 1434
74e4d827 1435 root = btrfs_alloc_root(fs_info, GFP_NOFS);
cb517eab
MX
1436 if (!root) {
1437 ret = -ENOMEM;
1438 goto alloc_fail;
0f7d52f4
CM
1439 }
1440
da17066c 1441 __setup_root(root, fs_info, key->objectid);
0f7d52f4 1442
cb517eab
MX
1443 ret = btrfs_find_root(tree_root, key, path,
1444 &root->root_item, &root->root_key);
0f7d52f4 1445 if (ret) {
13a8a7c8
YZ
1446 if (ret > 0)
1447 ret = -ENOENT;
cb517eab 1448 goto find_fail;
0f7d52f4 1449 }
13a8a7c8 1450
84234f3a 1451 generation = btrfs_root_generation(&root->root_item);
581c1760 1452 level = btrfs_root_level(&root->root_item);
2ff7e61e
JM
1453 root->node = read_tree_block(fs_info,
1454 btrfs_root_bytenr(&root->root_item),
581c1760 1455 generation, level, NULL);
64c043de
LB
1456 if (IS_ERR(root->node)) {
1457 ret = PTR_ERR(root->node);
cb517eab
MX
1458 goto find_fail;
1459 } else if (!btrfs_buffer_uptodate(root->node, generation, 0)) {
1460 ret = -EIO;
64c043de
LB
1461 free_extent_buffer(root->node);
1462 goto find_fail;
416bc658 1463 }
5d4f98a2 1464 root->commit_root = btrfs_root_node(root);
13a8a7c8 1465out:
cb517eab
MX
1466 btrfs_free_path(path);
1467 return root;
1468
cb517eab
MX
1469find_fail:
1470 kfree(root);
1471alloc_fail:
1472 root = ERR_PTR(ret);
1473 goto out;
1474}
1475
1476struct btrfs_root *btrfs_read_fs_root(struct btrfs_root *tree_root,
1477 struct btrfs_key *location)
1478{
1479 struct btrfs_root *root;
1480
1481 root = btrfs_read_tree_root(tree_root, location);
1482 if (IS_ERR(root))
1483 return root;
1484
1485 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
27cdeb70 1486 set_bit(BTRFS_ROOT_REF_COWS, &root->state);
08fe4db1
LZ
1487 btrfs_check_and_init_root_item(&root->root_item);
1488 }
13a8a7c8 1489
5eda7b5e
CM
1490 return root;
1491}
1492
cb517eab
MX
1493int btrfs_init_fs_root(struct btrfs_root *root)
1494{
1495 int ret;
8257b2dc 1496 struct btrfs_subvolume_writers *writers;
cb517eab
MX
1497
1498 root->free_ino_ctl = kzalloc(sizeof(*root->free_ino_ctl), GFP_NOFS);
1499 root->free_ino_pinned = kzalloc(sizeof(*root->free_ino_pinned),
1500 GFP_NOFS);
1501 if (!root->free_ino_pinned || !root->free_ino_ctl) {
1502 ret = -ENOMEM;
1503 goto fail;
1504 }
1505
8257b2dc
MX
1506 writers = btrfs_alloc_subvolume_writers();
1507 if (IS_ERR(writers)) {
1508 ret = PTR_ERR(writers);
1509 goto fail;
1510 }
1511 root->subv_writers = writers;
1512
cb517eab 1513 btrfs_init_free_ino_ctl(root);
57cdc8db
DS
1514 spin_lock_init(&root->ino_cache_lock);
1515 init_waitqueue_head(&root->ino_cache_wait);
cb517eab
MX
1516
1517 ret = get_anon_bdev(&root->anon_dev);
1518 if (ret)
876d2cf1 1519 goto fail;
f32e48e9
CR
1520
1521 mutex_lock(&root->objectid_mutex);
1522 ret = btrfs_find_highest_objectid(root,
1523 &root->highest_objectid);
1524 if (ret) {
1525 mutex_unlock(&root->objectid_mutex);
876d2cf1 1526 goto fail;
f32e48e9
CR
1527 }
1528
1529 ASSERT(root->highest_objectid <= BTRFS_LAST_FREE_OBJECTID);
1530
1531 mutex_unlock(&root->objectid_mutex);
1532
cb517eab
MX
1533 return 0;
1534fail:
876d2cf1 1535 /* the caller is responsible to call free_fs_root */
cb517eab
MX
1536 return ret;
1537}
1538
35bbb97f
JM
1539struct btrfs_root *btrfs_lookup_fs_root(struct btrfs_fs_info *fs_info,
1540 u64 root_id)
cb517eab
MX
1541{
1542 struct btrfs_root *root;
1543
1544 spin_lock(&fs_info->fs_roots_radix_lock);
1545 root = radix_tree_lookup(&fs_info->fs_roots_radix,
1546 (unsigned long)root_id);
1547 spin_unlock(&fs_info->fs_roots_radix_lock);
1548 return root;
1549}
1550
1551int btrfs_insert_fs_root(struct btrfs_fs_info *fs_info,
1552 struct btrfs_root *root)
1553{
1554 int ret;
1555
e1860a77 1556 ret = radix_tree_preload(GFP_NOFS);
cb517eab
MX
1557 if (ret)
1558 return ret;
1559
1560 spin_lock(&fs_info->fs_roots_radix_lock);
1561 ret = radix_tree_insert(&fs_info->fs_roots_radix,
1562 (unsigned long)root->root_key.objectid,
1563 root);
1564 if (ret == 0)
27cdeb70 1565 set_bit(BTRFS_ROOT_IN_RADIX, &root->state);
cb517eab
MX
1566 spin_unlock(&fs_info->fs_roots_radix_lock);
1567 radix_tree_preload_end();
1568
1569 return ret;
1570}
1571
c00869f1
MX
1572struct btrfs_root *btrfs_get_fs_root(struct btrfs_fs_info *fs_info,
1573 struct btrfs_key *location,
1574 bool check_ref)
5eda7b5e
CM
1575{
1576 struct btrfs_root *root;
381cf658 1577 struct btrfs_path *path;
1d4c08e0 1578 struct btrfs_key key;
5eda7b5e
CM
1579 int ret;
1580
edbd8d4e
CM
1581 if (location->objectid == BTRFS_ROOT_TREE_OBJECTID)
1582 return fs_info->tree_root;
1583 if (location->objectid == BTRFS_EXTENT_TREE_OBJECTID)
1584 return fs_info->extent_root;
8f18cf13
CM
1585 if (location->objectid == BTRFS_CHUNK_TREE_OBJECTID)
1586 return fs_info->chunk_root;
1587 if (location->objectid == BTRFS_DEV_TREE_OBJECTID)
1588 return fs_info->dev_root;
0403e47e
YZ
1589 if (location->objectid == BTRFS_CSUM_TREE_OBJECTID)
1590 return fs_info->csum_root;
bcef60f2
AJ
1591 if (location->objectid == BTRFS_QUOTA_TREE_OBJECTID)
1592 return fs_info->quota_root ? fs_info->quota_root :
1593 ERR_PTR(-ENOENT);
f7a81ea4
SB
1594 if (location->objectid == BTRFS_UUID_TREE_OBJECTID)
1595 return fs_info->uuid_root ? fs_info->uuid_root :
1596 ERR_PTR(-ENOENT);
70f6d82e
OS
1597 if (location->objectid == BTRFS_FREE_SPACE_TREE_OBJECTID)
1598 return fs_info->free_space_root ? fs_info->free_space_root :
1599 ERR_PTR(-ENOENT);
4df27c4d 1600again:
cb517eab 1601 root = btrfs_lookup_fs_root(fs_info, location->objectid);
48475471 1602 if (root) {
c00869f1 1603 if (check_ref && btrfs_root_refs(&root->root_item) == 0)
48475471 1604 return ERR_PTR(-ENOENT);
5eda7b5e 1605 return root;
48475471 1606 }
5eda7b5e 1607
cb517eab 1608 root = btrfs_read_fs_root(fs_info->tree_root, location);
5eda7b5e
CM
1609 if (IS_ERR(root))
1610 return root;
3394e160 1611
c00869f1 1612 if (check_ref && btrfs_root_refs(&root->root_item) == 0) {
cb517eab 1613 ret = -ENOENT;
581bb050 1614 goto fail;
35a30d7c 1615 }
581bb050 1616
cb517eab 1617 ret = btrfs_init_fs_root(root);
ac08aedf
CM
1618 if (ret)
1619 goto fail;
3394e160 1620
381cf658
DS
1621 path = btrfs_alloc_path();
1622 if (!path) {
1623 ret = -ENOMEM;
1624 goto fail;
1625 }
1d4c08e0
DS
1626 key.objectid = BTRFS_ORPHAN_OBJECTID;
1627 key.type = BTRFS_ORPHAN_ITEM_KEY;
1628 key.offset = location->objectid;
1629
1630 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
381cf658 1631 btrfs_free_path(path);
d68fc57b
YZ
1632 if (ret < 0)
1633 goto fail;
1634 if (ret == 0)
27cdeb70 1635 set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state);
d68fc57b 1636
cb517eab 1637 ret = btrfs_insert_fs_root(fs_info, root);
0f7d52f4 1638 if (ret) {
4df27c4d
YZ
1639 if (ret == -EEXIST) {
1640 free_fs_root(root);
1641 goto again;
1642 }
1643 goto fail;
0f7d52f4 1644 }
edbd8d4e 1645 return root;
4df27c4d
YZ
1646fail:
1647 free_fs_root(root);
1648 return ERR_PTR(ret);
edbd8d4e
CM
1649}
1650
04160088
CM
1651static int btrfs_congested_fn(void *congested_data, int bdi_bits)
1652{
1653 struct btrfs_fs_info *info = (struct btrfs_fs_info *)congested_data;
1654 int ret = 0;
04160088
CM
1655 struct btrfs_device *device;
1656 struct backing_dev_info *bdi;
b7967db7 1657
1f78160c
XG
1658 rcu_read_lock();
1659 list_for_each_entry_rcu(device, &info->fs_devices->devices, dev_list) {
dfe25020
CM
1660 if (!device->bdev)
1661 continue;
efa7c9f9 1662 bdi = device->bdev->bd_bdi;
ff9ea323 1663 if (bdi_congested(bdi, bdi_bits)) {
04160088
CM
1664 ret = 1;
1665 break;
1666 }
1667 }
1f78160c 1668 rcu_read_unlock();
04160088
CM
1669 return ret;
1670}
1671
8b712842
CM
1672/*
1673 * called by the kthread helper functions to finally call the bio end_io
1674 * functions. This is where read checksum verification actually happens
1675 */
1676static void end_workqueue_fn(struct btrfs_work *work)
ce9adaa5 1677{
ce9adaa5 1678 struct bio *bio;
97eb6b69 1679 struct btrfs_end_io_wq *end_io_wq;
ce9adaa5 1680
97eb6b69 1681 end_io_wq = container_of(work, struct btrfs_end_io_wq, work);
8b712842 1682 bio = end_io_wq->bio;
ce9adaa5 1683
4e4cbee9 1684 bio->bi_status = end_io_wq->status;
8b712842
CM
1685 bio->bi_private = end_io_wq->private;
1686 bio->bi_end_io = end_io_wq->end_io;
97eb6b69 1687 kmem_cache_free(btrfs_end_io_wq_cache, end_io_wq);
4246a0b6 1688 bio_endio(bio);
44b8bd7e
CM
1689}
1690
a74a4b97
CM
1691static int cleaner_kthread(void *arg)
1692{
1693 struct btrfs_root *root = arg;
0b246afa 1694 struct btrfs_fs_info *fs_info = root->fs_info;
d0278245 1695 int again;
da288d28 1696 struct btrfs_trans_handle *trans;
a74a4b97
CM
1697
1698 do {
d0278245 1699 again = 0;
a74a4b97 1700
d0278245 1701 /* Make the cleaner go to sleep early. */
2ff7e61e 1702 if (btrfs_need_cleaner_sleep(fs_info))
d0278245
MX
1703 goto sleep;
1704
90c711ab
ZB
1705 /*
1706 * Do not do anything if we might cause open_ctree() to block
1707 * before we have finished mounting the filesystem.
1708 */
0b246afa 1709 if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
90c711ab
ZB
1710 goto sleep;
1711
0b246afa 1712 if (!mutex_trylock(&fs_info->cleaner_mutex))
d0278245
MX
1713 goto sleep;
1714
dc7f370c
MX
1715 /*
1716 * Avoid the problem that we change the status of the fs
1717 * during the above check and trylock.
1718 */
2ff7e61e 1719 if (btrfs_need_cleaner_sleep(fs_info)) {
0b246afa 1720 mutex_unlock(&fs_info->cleaner_mutex);
dc7f370c 1721 goto sleep;
76dda93c 1722 }
a74a4b97 1723
0b246afa 1724 mutex_lock(&fs_info->cleaner_delayed_iput_mutex);
2ff7e61e 1725 btrfs_run_delayed_iputs(fs_info);
0b246afa 1726 mutex_unlock(&fs_info->cleaner_delayed_iput_mutex);
c2d6cb16 1727
d0278245 1728 again = btrfs_clean_one_deleted_snapshot(root);
0b246afa 1729 mutex_unlock(&fs_info->cleaner_mutex);
d0278245
MX
1730
1731 /*
05323cd1
MX
1732 * The defragger has dealt with the R/O remount and umount,
1733 * needn't do anything special here.
d0278245 1734 */
0b246afa 1735 btrfs_run_defrag_inodes(fs_info);
67c5e7d4
FM
1736
1737 /*
1738 * Acquires fs_info->delete_unused_bgs_mutex to avoid racing
1739 * with relocation (btrfs_relocate_chunk) and relocation
1740 * acquires fs_info->cleaner_mutex (btrfs_relocate_block_group)
1741 * after acquiring fs_info->delete_unused_bgs_mutex. So we
1742 * can't hold, nor need to, fs_info->cleaner_mutex when deleting
1743 * unused block groups.
1744 */
0b246afa 1745 btrfs_delete_unused_bgs(fs_info);
d0278245 1746sleep:
838fe188 1747 if (!again) {
a74a4b97 1748 set_current_state(TASK_INTERRUPTIBLE);
8929ecfa
YZ
1749 if (!kthread_should_stop())
1750 schedule();
a74a4b97
CM
1751 __set_current_state(TASK_RUNNING);
1752 }
1753 } while (!kthread_should_stop());
da288d28
FM
1754
1755 /*
1756 * Transaction kthread is stopped before us and wakes us up.
1757 * However we might have started a new transaction and COWed some
1758 * tree blocks when deleting unused block groups for example. So
1759 * make sure we commit the transaction we started to have a clean
1760 * shutdown when evicting the btree inode - if it has dirty pages
1761 * when we do the final iput() on it, eviction will trigger a
1762 * writeback for it which will fail with null pointer dereferences
1763 * since work queues and other resources were already released and
1764 * destroyed by the time the iput/eviction/writeback is made.
1765 */
1766 trans = btrfs_attach_transaction(root);
1767 if (IS_ERR(trans)) {
1768 if (PTR_ERR(trans) != -ENOENT)
0b246afa 1769 btrfs_err(fs_info,
da288d28
FM
1770 "cleaner transaction attach returned %ld",
1771 PTR_ERR(trans));
1772 } else {
1773 int ret;
1774
3a45bb20 1775 ret = btrfs_commit_transaction(trans);
da288d28 1776 if (ret)
0b246afa 1777 btrfs_err(fs_info,
da288d28
FM
1778 "cleaner open transaction commit returned %d",
1779 ret);
1780 }
1781
a74a4b97
CM
1782 return 0;
1783}
1784
1785static int transaction_kthread(void *arg)
1786{
1787 struct btrfs_root *root = arg;
0b246afa 1788 struct btrfs_fs_info *fs_info = root->fs_info;
a74a4b97
CM
1789 struct btrfs_trans_handle *trans;
1790 struct btrfs_transaction *cur;
8929ecfa 1791 u64 transid;
a944442c 1792 time64_t now;
a74a4b97 1793 unsigned long delay;
914b2007 1794 bool cannot_commit;
a74a4b97
CM
1795
1796 do {
914b2007 1797 cannot_commit = false;
0b246afa
JM
1798 delay = HZ * fs_info->commit_interval;
1799 mutex_lock(&fs_info->transaction_kthread_mutex);
a74a4b97 1800
0b246afa
JM
1801 spin_lock(&fs_info->trans_lock);
1802 cur = fs_info->running_transaction;
a74a4b97 1803 if (!cur) {
0b246afa 1804 spin_unlock(&fs_info->trans_lock);
a74a4b97
CM
1805 goto sleep;
1806 }
31153d81 1807
afd48513 1808 now = ktime_get_seconds();
4a9d8bde 1809 if (cur->state < TRANS_STATE_BLOCKED &&
a514d638 1810 !test_bit(BTRFS_FS_NEED_ASYNC_COMMIT, &fs_info->flags) &&
8b87dc17 1811 (now < cur->start_time ||
0b246afa
JM
1812 now - cur->start_time < fs_info->commit_interval)) {
1813 spin_unlock(&fs_info->trans_lock);
a74a4b97
CM
1814 delay = HZ * 5;
1815 goto sleep;
1816 }
8929ecfa 1817 transid = cur->transid;
0b246afa 1818 spin_unlock(&fs_info->trans_lock);
56bec294 1819
79787eaa 1820 /* If the file system is aborted, this will always fail. */
354aa0fb 1821 trans = btrfs_attach_transaction(root);
914b2007 1822 if (IS_ERR(trans)) {
354aa0fb
MX
1823 if (PTR_ERR(trans) != -ENOENT)
1824 cannot_commit = true;
79787eaa 1825 goto sleep;
914b2007 1826 }
8929ecfa 1827 if (transid == trans->transid) {
3a45bb20 1828 btrfs_commit_transaction(trans);
8929ecfa 1829 } else {
3a45bb20 1830 btrfs_end_transaction(trans);
8929ecfa 1831 }
a74a4b97 1832sleep:
0b246afa
JM
1833 wake_up_process(fs_info->cleaner_kthread);
1834 mutex_unlock(&fs_info->transaction_kthread_mutex);
a74a4b97 1835
4e121c06 1836 if (unlikely(test_bit(BTRFS_FS_STATE_ERROR,
0b246afa 1837 &fs_info->fs_state)))
2ff7e61e 1838 btrfs_cleanup_transaction(fs_info);
ce63f891 1839 if (!kthread_should_stop() &&
0b246afa 1840 (!btrfs_transaction_blocked(fs_info) ||
ce63f891 1841 cannot_commit))
bc5511d0 1842 schedule_timeout_interruptible(delay);
a74a4b97
CM
1843 } while (!kthread_should_stop());
1844 return 0;
1845}
1846
af31f5e5
CM
1847/*
1848 * this will find the highest generation in the array of
1849 * root backups. The index of the highest array is returned,
1850 * or -1 if we can't find anything.
1851 *
1852 * We check to make sure the array is valid by comparing the
1853 * generation of the latest root in the array with the generation
1854 * in the super block. If they don't match we pitch it.
1855 */
1856static int find_newest_super_backup(struct btrfs_fs_info *info, u64 newest_gen)
1857{
1858 u64 cur;
1859 int newest_index = -1;
1860 struct btrfs_root_backup *root_backup;
1861 int i;
1862
1863 for (i = 0; i < BTRFS_NUM_BACKUP_ROOTS; i++) {
1864 root_backup = info->super_copy->super_roots + i;
1865 cur = btrfs_backup_tree_root_gen(root_backup);
1866 if (cur == newest_gen)
1867 newest_index = i;
1868 }
1869
1870 /* check to see if we actually wrapped around */
1871 if (newest_index == BTRFS_NUM_BACKUP_ROOTS - 1) {
1872 root_backup = info->super_copy->super_roots;
1873 cur = btrfs_backup_tree_root_gen(root_backup);
1874 if (cur == newest_gen)
1875 newest_index = 0;
1876 }
1877 return newest_index;
1878}
1879
1880
1881/*
1882 * find the oldest backup so we know where to store new entries
1883 * in the backup array. This will set the backup_root_index
1884 * field in the fs_info struct
1885 */
1886static void find_oldest_super_backup(struct btrfs_fs_info *info,
1887 u64 newest_gen)
1888{
1889 int newest_index = -1;
1890
1891 newest_index = find_newest_super_backup(info, newest_gen);
1892 /* if there was garbage in there, just move along */
1893 if (newest_index == -1) {
1894 info->backup_root_index = 0;
1895 } else {
1896 info->backup_root_index = (newest_index + 1) % BTRFS_NUM_BACKUP_ROOTS;
1897 }
1898}
1899
1900/*
1901 * copy all the root pointers into the super backup array.
1902 * this will bump the backup pointer by one when it is
1903 * done
1904 */
1905static void backup_super_roots(struct btrfs_fs_info *info)
1906{
1907 int next_backup;
1908 struct btrfs_root_backup *root_backup;
1909 int last_backup;
1910
1911 next_backup = info->backup_root_index;
1912 last_backup = (next_backup + BTRFS_NUM_BACKUP_ROOTS - 1) %
1913 BTRFS_NUM_BACKUP_ROOTS;
1914
1915 /*
1916 * just overwrite the last backup if we're at the same generation
1917 * this happens only at umount
1918 */
1919 root_backup = info->super_for_commit->super_roots + last_backup;
1920 if (btrfs_backup_tree_root_gen(root_backup) ==
1921 btrfs_header_generation(info->tree_root->node))
1922 next_backup = last_backup;
1923
1924 root_backup = info->super_for_commit->super_roots + next_backup;
1925
1926 /*
1927 * make sure all of our padding and empty slots get zero filled
1928 * regardless of which ones we use today
1929 */
1930 memset(root_backup, 0, sizeof(*root_backup));
1931
1932 info->backup_root_index = (next_backup + 1) % BTRFS_NUM_BACKUP_ROOTS;
1933
1934 btrfs_set_backup_tree_root(root_backup, info->tree_root->node->start);
1935 btrfs_set_backup_tree_root_gen(root_backup,
1936 btrfs_header_generation(info->tree_root->node));
1937
1938 btrfs_set_backup_tree_root_level(root_backup,
1939 btrfs_header_level(info->tree_root->node));
1940
1941 btrfs_set_backup_chunk_root(root_backup, info->chunk_root->node->start);
1942 btrfs_set_backup_chunk_root_gen(root_backup,
1943 btrfs_header_generation(info->chunk_root->node));
1944 btrfs_set_backup_chunk_root_level(root_backup,
1945 btrfs_header_level(info->chunk_root->node));
1946
1947 btrfs_set_backup_extent_root(root_backup, info->extent_root->node->start);
1948 btrfs_set_backup_extent_root_gen(root_backup,
1949 btrfs_header_generation(info->extent_root->node));
1950 btrfs_set_backup_extent_root_level(root_backup,
1951 btrfs_header_level(info->extent_root->node));
1952
7c7e82a7
CM
1953 /*
1954 * we might commit during log recovery, which happens before we set
1955 * the fs_root. Make sure it is valid before we fill it in.
1956 */
1957 if (info->fs_root && info->fs_root->node) {
1958 btrfs_set_backup_fs_root(root_backup,
1959 info->fs_root->node->start);
1960 btrfs_set_backup_fs_root_gen(root_backup,
af31f5e5 1961 btrfs_header_generation(info->fs_root->node));
7c7e82a7 1962 btrfs_set_backup_fs_root_level(root_backup,
af31f5e5 1963 btrfs_header_level(info->fs_root->node));
7c7e82a7 1964 }
af31f5e5
CM
1965
1966 btrfs_set_backup_dev_root(root_backup, info->dev_root->node->start);
1967 btrfs_set_backup_dev_root_gen(root_backup,
1968 btrfs_header_generation(info->dev_root->node));
1969 btrfs_set_backup_dev_root_level(root_backup,
1970 btrfs_header_level(info->dev_root->node));
1971
1972 btrfs_set_backup_csum_root(root_backup, info->csum_root->node->start);
1973 btrfs_set_backup_csum_root_gen(root_backup,
1974 btrfs_header_generation(info->csum_root->node));
1975 btrfs_set_backup_csum_root_level(root_backup,
1976 btrfs_header_level(info->csum_root->node));
1977
1978 btrfs_set_backup_total_bytes(root_backup,
1979 btrfs_super_total_bytes(info->super_copy));
1980 btrfs_set_backup_bytes_used(root_backup,
1981 btrfs_super_bytes_used(info->super_copy));
1982 btrfs_set_backup_num_devices(root_backup,
1983 btrfs_super_num_devices(info->super_copy));
1984
1985 /*
1986 * if we don't copy this out to the super_copy, it won't get remembered
1987 * for the next commit
1988 */
1989 memcpy(&info->super_copy->super_roots,
1990 &info->super_for_commit->super_roots,
1991 sizeof(*root_backup) * BTRFS_NUM_BACKUP_ROOTS);
1992}
1993
1994/*
1995 * this copies info out of the root backup array and back into
1996 * the in-memory super block. It is meant to help iterate through
1997 * the array, so you send it the number of backups you've already
1998 * tried and the last backup index you used.
1999 *
2000 * this returns -1 when it has tried all the backups
2001 */
2002static noinline int next_root_backup(struct btrfs_fs_info *info,
2003 struct btrfs_super_block *super,
2004 int *num_backups_tried, int *backup_index)
2005{
2006 struct btrfs_root_backup *root_backup;
2007 int newest = *backup_index;
2008
2009 if (*num_backups_tried == 0) {
2010 u64 gen = btrfs_super_generation(super);
2011
2012 newest = find_newest_super_backup(info, gen);
2013 if (newest == -1)
2014 return -1;
2015
2016 *backup_index = newest;
2017 *num_backups_tried = 1;
2018 } else if (*num_backups_tried == BTRFS_NUM_BACKUP_ROOTS) {
2019 /* we've tried all the backups, all done */
2020 return -1;
2021 } else {
2022 /* jump to the next oldest backup */
2023 newest = (*backup_index + BTRFS_NUM_BACKUP_ROOTS - 1) %
2024 BTRFS_NUM_BACKUP_ROOTS;
2025 *backup_index = newest;
2026 *num_backups_tried += 1;
2027 }
2028 root_backup = super->super_roots + newest;
2029
2030 btrfs_set_super_generation(super,
2031 btrfs_backup_tree_root_gen(root_backup));
2032 btrfs_set_super_root(super, btrfs_backup_tree_root(root_backup));
2033 btrfs_set_super_root_level(super,
2034 btrfs_backup_tree_root_level(root_backup));
2035 btrfs_set_super_bytes_used(super, btrfs_backup_bytes_used(root_backup));
2036
2037 /*
2038 * fixme: the total bytes and num_devices need to match or we should
2039 * need a fsck
2040 */
2041 btrfs_set_super_total_bytes(super, btrfs_backup_total_bytes(root_backup));
2042 btrfs_set_super_num_devices(super, btrfs_backup_num_devices(root_backup));
2043 return 0;
2044}
2045
7abadb64
LB
2046/* helper to cleanup workers */
2047static void btrfs_stop_all_workers(struct btrfs_fs_info *fs_info)
2048{
dc6e3209 2049 btrfs_destroy_workqueue(fs_info->fixup_workers);
afe3d242 2050 btrfs_destroy_workqueue(fs_info->delalloc_workers);
5cdc7ad3 2051 btrfs_destroy_workqueue(fs_info->workers);
fccb5d86 2052 btrfs_destroy_workqueue(fs_info->endio_workers);
fccb5d86 2053 btrfs_destroy_workqueue(fs_info->endio_raid56_workers);
8b110e39 2054 btrfs_destroy_workqueue(fs_info->endio_repair_workers);
d05a33ac 2055 btrfs_destroy_workqueue(fs_info->rmw_workers);
fccb5d86
QW
2056 btrfs_destroy_workqueue(fs_info->endio_write_workers);
2057 btrfs_destroy_workqueue(fs_info->endio_freespace_worker);
a8c93d4e 2058 btrfs_destroy_workqueue(fs_info->submit_workers);
5b3bc44e 2059 btrfs_destroy_workqueue(fs_info->delayed_workers);
e66f0bb1 2060 btrfs_destroy_workqueue(fs_info->caching_workers);
736cfa15 2061 btrfs_destroy_workqueue(fs_info->readahead_workers);
a44903ab 2062 btrfs_destroy_workqueue(fs_info->flush_workers);
fc97fab0 2063 btrfs_destroy_workqueue(fs_info->qgroup_rescan_workers);
a79b7d4b 2064 btrfs_destroy_workqueue(fs_info->extent_workers);
a9b9477d
FM
2065 /*
2066 * Now that all other work queues are destroyed, we can safely destroy
2067 * the queues used for metadata I/O, since tasks from those other work
2068 * queues can do metadata I/O operations.
2069 */
2070 btrfs_destroy_workqueue(fs_info->endio_meta_workers);
2071 btrfs_destroy_workqueue(fs_info->endio_meta_write_workers);
7abadb64
LB
2072}
2073
2e9f5954
R
2074static void free_root_extent_buffers(struct btrfs_root *root)
2075{
2076 if (root) {
2077 free_extent_buffer(root->node);
2078 free_extent_buffer(root->commit_root);
2079 root->node = NULL;
2080 root->commit_root = NULL;
2081 }
2082}
2083
af31f5e5
CM
2084/* helper to cleanup tree roots */
2085static void free_root_pointers(struct btrfs_fs_info *info, int chunk_root)
2086{
2e9f5954 2087 free_root_extent_buffers(info->tree_root);
655b09fe 2088
2e9f5954
R
2089 free_root_extent_buffers(info->dev_root);
2090 free_root_extent_buffers(info->extent_root);
2091 free_root_extent_buffers(info->csum_root);
2092 free_root_extent_buffers(info->quota_root);
2093 free_root_extent_buffers(info->uuid_root);
2094 if (chunk_root)
2095 free_root_extent_buffers(info->chunk_root);
70f6d82e 2096 free_root_extent_buffers(info->free_space_root);
af31f5e5
CM
2097}
2098
faa2dbf0 2099void btrfs_free_fs_roots(struct btrfs_fs_info *fs_info)
171f6537
JB
2100{
2101 int ret;
2102 struct btrfs_root *gang[8];
2103 int i;
2104
2105 while (!list_empty(&fs_info->dead_roots)) {
2106 gang[0] = list_entry(fs_info->dead_roots.next,
2107 struct btrfs_root, root_list);
2108 list_del(&gang[0]->root_list);
2109
27cdeb70 2110 if (test_bit(BTRFS_ROOT_IN_RADIX, &gang[0]->state)) {
cb517eab 2111 btrfs_drop_and_free_fs_root(fs_info, gang[0]);
171f6537
JB
2112 } else {
2113 free_extent_buffer(gang[0]->node);
2114 free_extent_buffer(gang[0]->commit_root);
b0feb9d9 2115 btrfs_put_fs_root(gang[0]);
171f6537
JB
2116 }
2117 }
2118
2119 while (1) {
2120 ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
2121 (void **)gang, 0,
2122 ARRAY_SIZE(gang));
2123 if (!ret)
2124 break;
2125 for (i = 0; i < ret; i++)
cb517eab 2126 btrfs_drop_and_free_fs_root(fs_info, gang[i]);
171f6537 2127 }
1a4319cc
LB
2128
2129 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {
2130 btrfs_free_log_root_tree(NULL, fs_info);
2ff7e61e 2131 btrfs_destroy_pinned_extent(fs_info, fs_info->pinned_extents);
1a4319cc 2132 }
171f6537 2133}
af31f5e5 2134
638aa7ed
ES
2135static void btrfs_init_scrub(struct btrfs_fs_info *fs_info)
2136{
2137 mutex_init(&fs_info->scrub_lock);
2138 atomic_set(&fs_info->scrubs_running, 0);
2139 atomic_set(&fs_info->scrub_pause_req, 0);
2140 atomic_set(&fs_info->scrubs_paused, 0);
2141 atomic_set(&fs_info->scrub_cancel_req, 0);
2142 init_waitqueue_head(&fs_info->scrub_pause_wait);
2143 fs_info->scrub_workers_refcnt = 0;
2144}
2145
779a65a4
ES
2146static void btrfs_init_balance(struct btrfs_fs_info *fs_info)
2147{
2148 spin_lock_init(&fs_info->balance_lock);
2149 mutex_init(&fs_info->balance_mutex);
779a65a4
ES
2150 atomic_set(&fs_info->balance_pause_req, 0);
2151 atomic_set(&fs_info->balance_cancel_req, 0);
2152 fs_info->balance_ctl = NULL;
2153 init_waitqueue_head(&fs_info->balance_wait_q);
2154}
2155
6bccf3ab 2156static void btrfs_init_btree_inode(struct btrfs_fs_info *fs_info)
f37938e0 2157{
2ff7e61e
JM
2158 struct inode *inode = fs_info->btree_inode;
2159
2160 inode->i_ino = BTRFS_BTREE_INODE_OBJECTID;
2161 set_nlink(inode, 1);
f37938e0
ES
2162 /*
2163 * we set the i_size on the btree inode to the max possible int.
2164 * the real end of the address space is determined by all of
2165 * the devices in the system
2166 */
2ff7e61e
JM
2167 inode->i_size = OFFSET_MAX;
2168 inode->i_mapping->a_ops = &btree_aops;
f37938e0 2169
2ff7e61e 2170 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
c6100a4b 2171 extent_io_tree_init(&BTRFS_I(inode)->io_tree, inode);
2ff7e61e
JM
2172 BTRFS_I(inode)->io_tree.track_uptodate = 0;
2173 extent_map_tree_init(&BTRFS_I(inode)->extent_tree);
f37938e0 2174
2ff7e61e 2175 BTRFS_I(inode)->io_tree.ops = &btree_extent_io_ops;
f37938e0 2176
2ff7e61e
JM
2177 BTRFS_I(inode)->root = fs_info->tree_root;
2178 memset(&BTRFS_I(inode)->location, 0, sizeof(struct btrfs_key));
2179 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
2180 btrfs_insert_inode_hash(inode);
f37938e0
ES
2181}
2182
ad618368
ES
2183static void btrfs_init_dev_replace_locks(struct btrfs_fs_info *fs_info)
2184{
2185 fs_info->dev_replace.lock_owner = 0;
2186 atomic_set(&fs_info->dev_replace.nesting_level, 0);
2187 mutex_init(&fs_info->dev_replace.lock_finishing_cancel_unmount);
73beece9
LB
2188 rwlock_init(&fs_info->dev_replace.lock);
2189 atomic_set(&fs_info->dev_replace.read_locks, 0);
2190 atomic_set(&fs_info->dev_replace.blocking_readers, 0);
ad618368 2191 init_waitqueue_head(&fs_info->replace_wait);
73beece9 2192 init_waitqueue_head(&fs_info->dev_replace.read_lock_wq);
ad618368
ES
2193}
2194
f9e92e40
ES
2195static void btrfs_init_qgroup(struct btrfs_fs_info *fs_info)
2196{
2197 spin_lock_init(&fs_info->qgroup_lock);
2198 mutex_init(&fs_info->qgroup_ioctl_lock);
2199 fs_info->qgroup_tree = RB_ROOT;
2200 fs_info->qgroup_op_tree = RB_ROOT;
2201 INIT_LIST_HEAD(&fs_info->dirty_qgroups);
2202 fs_info->qgroup_seq = 1;
f9e92e40 2203 fs_info->qgroup_ulist = NULL;
d2c609b8 2204 fs_info->qgroup_rescan_running = false;
f9e92e40
ES
2205 mutex_init(&fs_info->qgroup_rescan_lock);
2206}
2207
2a458198
ES
2208static int btrfs_init_workqueues(struct btrfs_fs_info *fs_info,
2209 struct btrfs_fs_devices *fs_devices)
2210{
f7b885be 2211 u32 max_active = fs_info->thread_pool_size;
6f011058 2212 unsigned int flags = WQ_MEM_RECLAIM | WQ_FREEZABLE | WQ_UNBOUND;
2a458198
ES
2213
2214 fs_info->workers =
cb001095
JM
2215 btrfs_alloc_workqueue(fs_info, "worker",
2216 flags | WQ_HIGHPRI, max_active, 16);
2a458198
ES
2217
2218 fs_info->delalloc_workers =
cb001095
JM
2219 btrfs_alloc_workqueue(fs_info, "delalloc",
2220 flags, max_active, 2);
2a458198
ES
2221
2222 fs_info->flush_workers =
cb001095
JM
2223 btrfs_alloc_workqueue(fs_info, "flush_delalloc",
2224 flags, max_active, 0);
2a458198
ES
2225
2226 fs_info->caching_workers =
cb001095 2227 btrfs_alloc_workqueue(fs_info, "cache", flags, max_active, 0);
2a458198
ES
2228
2229 /*
2230 * a higher idle thresh on the submit workers makes it much more
2231 * likely that bios will be send down in a sane order to the
2232 * devices
2233 */
2234 fs_info->submit_workers =
cb001095 2235 btrfs_alloc_workqueue(fs_info, "submit", flags,
2a458198
ES
2236 min_t(u64, fs_devices->num_devices,
2237 max_active), 64);
2238
2239 fs_info->fixup_workers =
cb001095 2240 btrfs_alloc_workqueue(fs_info, "fixup", flags, 1, 0);
2a458198
ES
2241
2242 /*
2243 * endios are largely parallel and should have a very
2244 * low idle thresh
2245 */
2246 fs_info->endio_workers =
cb001095 2247 btrfs_alloc_workqueue(fs_info, "endio", flags, max_active, 4);
2a458198 2248 fs_info->endio_meta_workers =
cb001095
JM
2249 btrfs_alloc_workqueue(fs_info, "endio-meta", flags,
2250 max_active, 4);
2a458198 2251 fs_info->endio_meta_write_workers =
cb001095
JM
2252 btrfs_alloc_workqueue(fs_info, "endio-meta-write", flags,
2253 max_active, 2);
2a458198 2254 fs_info->endio_raid56_workers =
cb001095
JM
2255 btrfs_alloc_workqueue(fs_info, "endio-raid56", flags,
2256 max_active, 4);
2a458198 2257 fs_info->endio_repair_workers =
cb001095 2258 btrfs_alloc_workqueue(fs_info, "endio-repair", flags, 1, 0);
2a458198 2259 fs_info->rmw_workers =
cb001095 2260 btrfs_alloc_workqueue(fs_info, "rmw", flags, max_active, 2);
2a458198 2261 fs_info->endio_write_workers =
cb001095
JM
2262 btrfs_alloc_workqueue(fs_info, "endio-write", flags,
2263 max_active, 2);
2a458198 2264 fs_info->endio_freespace_worker =
cb001095
JM
2265 btrfs_alloc_workqueue(fs_info, "freespace-write", flags,
2266 max_active, 0);
2a458198 2267 fs_info->delayed_workers =
cb001095
JM
2268 btrfs_alloc_workqueue(fs_info, "delayed-meta", flags,
2269 max_active, 0);
2a458198 2270 fs_info->readahead_workers =
cb001095
JM
2271 btrfs_alloc_workqueue(fs_info, "readahead", flags,
2272 max_active, 2);
2a458198 2273 fs_info->qgroup_rescan_workers =
cb001095 2274 btrfs_alloc_workqueue(fs_info, "qgroup-rescan", flags, 1, 0);
2a458198 2275 fs_info->extent_workers =
cb001095 2276 btrfs_alloc_workqueue(fs_info, "extent-refs", flags,
2a458198
ES
2277 min_t(u64, fs_devices->num_devices,
2278 max_active), 8);
2279
2280 if (!(fs_info->workers && fs_info->delalloc_workers &&
2281 fs_info->submit_workers && fs_info->flush_workers &&
2282 fs_info->endio_workers && fs_info->endio_meta_workers &&
2283 fs_info->endio_meta_write_workers &&
2284 fs_info->endio_repair_workers &&
2285 fs_info->endio_write_workers && fs_info->endio_raid56_workers &&
2286 fs_info->endio_freespace_worker && fs_info->rmw_workers &&
2287 fs_info->caching_workers && fs_info->readahead_workers &&
2288 fs_info->fixup_workers && fs_info->delayed_workers &&
2289 fs_info->extent_workers &&
2290 fs_info->qgroup_rescan_workers)) {
2291 return -ENOMEM;
2292 }
2293
2294 return 0;
2295}
2296
63443bf5
ES
2297static int btrfs_replay_log(struct btrfs_fs_info *fs_info,
2298 struct btrfs_fs_devices *fs_devices)
2299{
2300 int ret;
63443bf5
ES
2301 struct btrfs_root *log_tree_root;
2302 struct btrfs_super_block *disk_super = fs_info->super_copy;
2303 u64 bytenr = btrfs_super_log_root(disk_super);
581c1760 2304 int level = btrfs_super_log_root_level(disk_super);
63443bf5
ES
2305
2306 if (fs_devices->rw_devices == 0) {
f14d104d 2307 btrfs_warn(fs_info, "log replay required on RO media");
63443bf5
ES
2308 return -EIO;
2309 }
2310
74e4d827 2311 log_tree_root = btrfs_alloc_root(fs_info, GFP_KERNEL);
63443bf5
ES
2312 if (!log_tree_root)
2313 return -ENOMEM;
2314
da17066c 2315 __setup_root(log_tree_root, fs_info, BTRFS_TREE_LOG_OBJECTID);
63443bf5 2316
2ff7e61e 2317 log_tree_root->node = read_tree_block(fs_info, bytenr,
581c1760
QW
2318 fs_info->generation + 1,
2319 level, NULL);
64c043de 2320 if (IS_ERR(log_tree_root->node)) {
f14d104d 2321 btrfs_warn(fs_info, "failed to read log tree");
0eeff236 2322 ret = PTR_ERR(log_tree_root->node);
64c043de 2323 kfree(log_tree_root);
0eeff236 2324 return ret;
64c043de 2325 } else if (!extent_buffer_uptodate(log_tree_root->node)) {
f14d104d 2326 btrfs_err(fs_info, "failed to read log tree");
63443bf5
ES
2327 free_extent_buffer(log_tree_root->node);
2328 kfree(log_tree_root);
2329 return -EIO;
2330 }
2331 /* returns with log_tree_root freed on success */
2332 ret = btrfs_recover_log_trees(log_tree_root);
2333 if (ret) {
0b246afa
JM
2334 btrfs_handle_fs_error(fs_info, ret,
2335 "Failed to recover log tree");
63443bf5
ES
2336 free_extent_buffer(log_tree_root->node);
2337 kfree(log_tree_root);
2338 return ret;
2339 }
2340
bc98a42c 2341 if (sb_rdonly(fs_info->sb)) {
6bccf3ab 2342 ret = btrfs_commit_super(fs_info);
63443bf5
ES
2343 if (ret)
2344 return ret;
2345 }
2346
2347 return 0;
2348}
2349
6bccf3ab 2350static int btrfs_read_roots(struct btrfs_fs_info *fs_info)
4bbcaa64 2351{
6bccf3ab 2352 struct btrfs_root *tree_root = fs_info->tree_root;
a4f3d2c4 2353 struct btrfs_root *root;
4bbcaa64
ES
2354 struct btrfs_key location;
2355 int ret;
2356
6bccf3ab
JM
2357 BUG_ON(!fs_info->tree_root);
2358
4bbcaa64
ES
2359 location.objectid = BTRFS_EXTENT_TREE_OBJECTID;
2360 location.type = BTRFS_ROOT_ITEM_KEY;
2361 location.offset = 0;
2362
a4f3d2c4 2363 root = btrfs_read_tree_root(tree_root, &location);
f50f4353
LB
2364 if (IS_ERR(root)) {
2365 ret = PTR_ERR(root);
2366 goto out;
2367 }
a4f3d2c4
DS
2368 set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2369 fs_info->extent_root = root;
4bbcaa64
ES
2370
2371 location.objectid = BTRFS_DEV_TREE_OBJECTID;
a4f3d2c4 2372 root = btrfs_read_tree_root(tree_root, &location);
f50f4353
LB
2373 if (IS_ERR(root)) {
2374 ret = PTR_ERR(root);
2375 goto out;
2376 }
a4f3d2c4
DS
2377 set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2378 fs_info->dev_root = root;
4bbcaa64
ES
2379 btrfs_init_devices_late(fs_info);
2380
2381 location.objectid = BTRFS_CSUM_TREE_OBJECTID;
a4f3d2c4 2382 root = btrfs_read_tree_root(tree_root, &location);
f50f4353
LB
2383 if (IS_ERR(root)) {
2384 ret = PTR_ERR(root);
2385 goto out;
2386 }
a4f3d2c4
DS
2387 set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2388 fs_info->csum_root = root;
4bbcaa64
ES
2389
2390 location.objectid = BTRFS_QUOTA_TREE_OBJECTID;
a4f3d2c4
DS
2391 root = btrfs_read_tree_root(tree_root, &location);
2392 if (!IS_ERR(root)) {
2393 set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
afcdd129 2394 set_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags);
a4f3d2c4 2395 fs_info->quota_root = root;
4bbcaa64
ES
2396 }
2397
2398 location.objectid = BTRFS_UUID_TREE_OBJECTID;
a4f3d2c4
DS
2399 root = btrfs_read_tree_root(tree_root, &location);
2400 if (IS_ERR(root)) {
2401 ret = PTR_ERR(root);
4bbcaa64 2402 if (ret != -ENOENT)
f50f4353 2403 goto out;
4bbcaa64 2404 } else {
a4f3d2c4
DS
2405 set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2406 fs_info->uuid_root = root;
4bbcaa64
ES
2407 }
2408
70f6d82e
OS
2409 if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
2410 location.objectid = BTRFS_FREE_SPACE_TREE_OBJECTID;
2411 root = btrfs_read_tree_root(tree_root, &location);
f50f4353
LB
2412 if (IS_ERR(root)) {
2413 ret = PTR_ERR(root);
2414 goto out;
2415 }
70f6d82e
OS
2416 set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
2417 fs_info->free_space_root = root;
2418 }
2419
4bbcaa64 2420 return 0;
f50f4353
LB
2421out:
2422 btrfs_warn(fs_info, "failed to read root (objectid=%llu): %d",
2423 location.objectid, ret);
2424 return ret;
4bbcaa64
ES
2425}
2426
069ec957
QW
2427/*
2428 * Real super block validation
2429 * NOTE: super csum type and incompat features will not be checked here.
2430 *
2431 * @sb: super block to check
2432 * @mirror_num: the super block number to check its bytenr:
2433 * 0 the primary (1st) sb
2434 * 1, 2 2nd and 3rd backup copy
2435 * -1 skip bytenr check
2436 */
2437static int validate_super(struct btrfs_fs_info *fs_info,
2438 struct btrfs_super_block *sb, int mirror_num)
21a852b0 2439{
21a852b0
QW
2440 u64 nodesize = btrfs_super_nodesize(sb);
2441 u64 sectorsize = btrfs_super_sectorsize(sb);
2442 int ret = 0;
2443
2444 if (btrfs_super_magic(sb) != BTRFS_MAGIC) {
2445 btrfs_err(fs_info, "no valid FS found");
2446 ret = -EINVAL;
2447 }
2448 if (btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP) {
2449 btrfs_err(fs_info, "unrecognized or unsupported super flag: %llu",
2450 btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP);
2451 ret = -EINVAL;
2452 }
2453 if (btrfs_super_root_level(sb) >= BTRFS_MAX_LEVEL) {
2454 btrfs_err(fs_info, "tree_root level too big: %d >= %d",
2455 btrfs_super_root_level(sb), BTRFS_MAX_LEVEL);
2456 ret = -EINVAL;
2457 }
2458 if (btrfs_super_chunk_root_level(sb) >= BTRFS_MAX_LEVEL) {
2459 btrfs_err(fs_info, "chunk_root level too big: %d >= %d",
2460 btrfs_super_chunk_root_level(sb), BTRFS_MAX_LEVEL);
2461 ret = -EINVAL;
2462 }
2463 if (btrfs_super_log_root_level(sb) >= BTRFS_MAX_LEVEL) {
2464 btrfs_err(fs_info, "log_root level too big: %d >= %d",
2465 btrfs_super_log_root_level(sb), BTRFS_MAX_LEVEL);
2466 ret = -EINVAL;
2467 }
2468
2469 /*
2470 * Check sectorsize and nodesize first, other check will need it.
2471 * Check all possible sectorsize(4K, 8K, 16K, 32K, 64K) here.
2472 */
2473 if (!is_power_of_2(sectorsize) || sectorsize < 4096 ||
2474 sectorsize > BTRFS_MAX_METADATA_BLOCKSIZE) {
2475 btrfs_err(fs_info, "invalid sectorsize %llu", sectorsize);
2476 ret = -EINVAL;
2477 }
2478 /* Only PAGE SIZE is supported yet */
2479 if (sectorsize != PAGE_SIZE) {
2480 btrfs_err(fs_info,
2481 "sectorsize %llu not supported yet, only support %lu",
2482 sectorsize, PAGE_SIZE);
2483 ret = -EINVAL;
2484 }
2485 if (!is_power_of_2(nodesize) || nodesize < sectorsize ||
2486 nodesize > BTRFS_MAX_METADATA_BLOCKSIZE) {
2487 btrfs_err(fs_info, "invalid nodesize %llu", nodesize);
2488 ret = -EINVAL;
2489 }
2490 if (nodesize != le32_to_cpu(sb->__unused_leafsize)) {
2491 btrfs_err(fs_info, "invalid leafsize %u, should be %llu",
2492 le32_to_cpu(sb->__unused_leafsize), nodesize);
2493 ret = -EINVAL;
2494 }
2495
2496 /* Root alignment check */
2497 if (!IS_ALIGNED(btrfs_super_root(sb), sectorsize)) {
2498 btrfs_warn(fs_info, "tree_root block unaligned: %llu",
2499 btrfs_super_root(sb));
2500 ret = -EINVAL;
2501 }
2502 if (!IS_ALIGNED(btrfs_super_chunk_root(sb), sectorsize)) {
2503 btrfs_warn(fs_info, "chunk_root block unaligned: %llu",
2504 btrfs_super_chunk_root(sb));
2505 ret = -EINVAL;
2506 }
2507 if (!IS_ALIGNED(btrfs_super_log_root(sb), sectorsize)) {
2508 btrfs_warn(fs_info, "log_root block unaligned: %llu",
2509 btrfs_super_log_root(sb));
2510 ret = -EINVAL;
2511 }
2512
2513 if (memcmp(fs_info->fsid, sb->dev_item.fsid, BTRFS_FSID_SIZE) != 0) {
2514 btrfs_err(fs_info,
2515 "dev_item UUID does not match fsid: %pU != %pU",
2516 fs_info->fsid, sb->dev_item.fsid);
2517 ret = -EINVAL;
2518 }
2519
2520 /*
2521 * Hint to catch really bogus numbers, bitflips or so, more exact checks are
2522 * done later
2523 */
2524 if (btrfs_super_bytes_used(sb) < 6 * btrfs_super_nodesize(sb)) {
2525 btrfs_err(fs_info, "bytes_used is too small %llu",
2526 btrfs_super_bytes_used(sb));
2527 ret = -EINVAL;
2528 }
2529 if (!is_power_of_2(btrfs_super_stripesize(sb))) {
2530 btrfs_err(fs_info, "invalid stripesize %u",
2531 btrfs_super_stripesize(sb));
2532 ret = -EINVAL;
2533 }
2534 if (btrfs_super_num_devices(sb) > (1UL << 31))
2535 btrfs_warn(fs_info, "suspicious number of devices: %llu",
2536 btrfs_super_num_devices(sb));
2537 if (btrfs_super_num_devices(sb) == 0) {
2538 btrfs_err(fs_info, "number of devices is 0");
2539 ret = -EINVAL;
2540 }
2541
069ec957
QW
2542 if (mirror_num >= 0 &&
2543 btrfs_super_bytenr(sb) != btrfs_sb_offset(mirror_num)) {
21a852b0
QW
2544 btrfs_err(fs_info, "super offset mismatch %llu != %u",
2545 btrfs_super_bytenr(sb), BTRFS_SUPER_INFO_OFFSET);
2546 ret = -EINVAL;
2547 }
2548
2549 /*
2550 * Obvious sys_chunk_array corruptions, it must hold at least one key
2551 * and one chunk
2552 */
2553 if (btrfs_super_sys_array_size(sb) > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
2554 btrfs_err(fs_info, "system chunk array too big %u > %u",
2555 btrfs_super_sys_array_size(sb),
2556 BTRFS_SYSTEM_CHUNK_ARRAY_SIZE);
2557 ret = -EINVAL;
2558 }
2559 if (btrfs_super_sys_array_size(sb) < sizeof(struct btrfs_disk_key)
2560 + sizeof(struct btrfs_chunk)) {
2561 btrfs_err(fs_info, "system chunk array too small %u < %zu",
2562 btrfs_super_sys_array_size(sb),
2563 sizeof(struct btrfs_disk_key)
2564 + sizeof(struct btrfs_chunk));
2565 ret = -EINVAL;
2566 }
2567
2568 /*
2569 * The generation is a global counter, we'll trust it more than the others
2570 * but it's still possible that it's the one that's wrong.
2571 */
2572 if (btrfs_super_generation(sb) < btrfs_super_chunk_root_generation(sb))
2573 btrfs_warn(fs_info,
2574 "suspicious: generation < chunk_root_generation: %llu < %llu",
2575 btrfs_super_generation(sb),
2576 btrfs_super_chunk_root_generation(sb));
2577 if (btrfs_super_generation(sb) < btrfs_super_cache_generation(sb)
2578 && btrfs_super_cache_generation(sb) != (u64)-1)
2579 btrfs_warn(fs_info,
2580 "suspicious: generation < cache_generation: %llu < %llu",
2581 btrfs_super_generation(sb),
2582 btrfs_super_cache_generation(sb));
2583
2584 return ret;
2585}
2586
069ec957
QW
2587/*
2588 * Validation of super block at mount time.
2589 * Some checks already done early at mount time, like csum type and incompat
2590 * flags will be skipped.
2591 */
2592static int btrfs_validate_mount_super(struct btrfs_fs_info *fs_info)
2593{
2594 return validate_super(fs_info, fs_info->super_copy, 0);
2595}
2596
75cb857d
QW
2597/*
2598 * Validation of super block at write time.
2599 * Some checks like bytenr check will be skipped as their values will be
2600 * overwritten soon.
2601 * Extra checks like csum type and incompat flags will be done here.
2602 */
2603static int btrfs_validate_write_super(struct btrfs_fs_info *fs_info,
2604 struct btrfs_super_block *sb)
2605{
2606 int ret;
2607
2608 ret = validate_super(fs_info, sb, -1);
2609 if (ret < 0)
2610 goto out;
2611 if (btrfs_super_csum_type(sb) != BTRFS_CSUM_TYPE_CRC32) {
2612 ret = -EUCLEAN;
2613 btrfs_err(fs_info, "invalid csum type, has %u want %u",
2614 btrfs_super_csum_type(sb), BTRFS_CSUM_TYPE_CRC32);
2615 goto out;
2616 }
2617 if (btrfs_super_incompat_flags(sb) & ~BTRFS_FEATURE_INCOMPAT_SUPP) {
2618 ret = -EUCLEAN;
2619 btrfs_err(fs_info,
2620 "invalid incompat flags, has 0x%llx valid mask 0x%llx",
2621 btrfs_super_incompat_flags(sb),
2622 (unsigned long long)BTRFS_FEATURE_INCOMPAT_SUPP);
2623 goto out;
2624 }
2625out:
2626 if (ret < 0)
2627 btrfs_err(fs_info,
2628 "super block corruption detected before writing it to disk");
2629 return ret;
2630}
2631
ad2b2c80
AV
2632int open_ctree(struct super_block *sb,
2633 struct btrfs_fs_devices *fs_devices,
2634 char *options)
2e635a27 2635{
db94535d
CM
2636 u32 sectorsize;
2637 u32 nodesize;
87ee04eb 2638 u32 stripesize;
84234f3a 2639 u64 generation;
f2b636e8 2640 u64 features;
3de4586c 2641 struct btrfs_key location;
a061fc8d 2642 struct buffer_head *bh;
4d34b278 2643 struct btrfs_super_block *disk_super;
815745cf 2644 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
f84a8bd6 2645 struct btrfs_root *tree_root;
4d34b278 2646 struct btrfs_root *chunk_root;
eb60ceac 2647 int ret;
e58ca020 2648 int err = -EINVAL;
af31f5e5
CM
2649 int num_backups_tried = 0;
2650 int backup_index = 0;
6675df31 2651 int clear_free_space_tree = 0;
581c1760 2652 int level;
4543df7e 2653
74e4d827
DS
2654 tree_root = fs_info->tree_root = btrfs_alloc_root(fs_info, GFP_KERNEL);
2655 chunk_root = fs_info->chunk_root = btrfs_alloc_root(fs_info, GFP_KERNEL);
cb517eab 2656 if (!tree_root || !chunk_root) {
39279cc3
CM
2657 err = -ENOMEM;
2658 goto fail;
2659 }
76dda93c
YZ
2660
2661 ret = init_srcu_struct(&fs_info->subvol_srcu);
2662 if (ret) {
2663 err = ret;
2664 goto fail;
2665 }
2666
908c7f19 2667 ret = percpu_counter_init(&fs_info->dirty_metadata_bytes, 0, GFP_KERNEL);
e2d84521
MX
2668 if (ret) {
2669 err = ret;
9e11ceee 2670 goto fail_srcu;
e2d84521 2671 }
09cbfeaf 2672 fs_info->dirty_metadata_batch = PAGE_SIZE *
e2d84521
MX
2673 (1 + ilog2(nr_cpu_ids));
2674
908c7f19 2675 ret = percpu_counter_init(&fs_info->delalloc_bytes, 0, GFP_KERNEL);
963d678b
MX
2676 if (ret) {
2677 err = ret;
2678 goto fail_dirty_metadata_bytes;
2679 }
2680
908c7f19 2681 ret = percpu_counter_init(&fs_info->bio_counter, 0, GFP_KERNEL);
c404e0dc
MX
2682 if (ret) {
2683 err = ret;
2684 goto fail_delalloc_bytes;
2685 }
2686
76dda93c 2687 INIT_RADIX_TREE(&fs_info->fs_roots_radix, GFP_ATOMIC);
f28491e0 2688 INIT_RADIX_TREE(&fs_info->buffer_radix, GFP_ATOMIC);
8fd17795 2689 INIT_LIST_HEAD(&fs_info->trans_list);
facda1e7 2690 INIT_LIST_HEAD(&fs_info->dead_roots);
24bbcf04 2691 INIT_LIST_HEAD(&fs_info->delayed_iputs);
eb73c1b7 2692 INIT_LIST_HEAD(&fs_info->delalloc_roots);
11833d66 2693 INIT_LIST_HEAD(&fs_info->caching_block_groups);
75cb379d
JM
2694 INIT_LIST_HEAD(&fs_info->pending_raid_kobjs);
2695 spin_lock_init(&fs_info->pending_raid_kobjs_lock);
eb73c1b7 2696 spin_lock_init(&fs_info->delalloc_root_lock);
a4abeea4 2697 spin_lock_init(&fs_info->trans_lock);
76dda93c 2698 spin_lock_init(&fs_info->fs_roots_radix_lock);
24bbcf04 2699 spin_lock_init(&fs_info->delayed_iput_lock);
4cb5300b 2700 spin_lock_init(&fs_info->defrag_inodes_lock);
f29021b2 2701 spin_lock_init(&fs_info->tree_mod_seq_lock);
ceda0864 2702 spin_lock_init(&fs_info->super_lock);
fcebe456 2703 spin_lock_init(&fs_info->qgroup_op_lock);
f28491e0 2704 spin_lock_init(&fs_info->buffer_lock);
47ab2a6c 2705 spin_lock_init(&fs_info->unused_bgs_lock);
f29021b2 2706 rwlock_init(&fs_info->tree_mod_log_lock);
d7c15171 2707 mutex_init(&fs_info->unused_bg_unpin_mutex);
67c5e7d4 2708 mutex_init(&fs_info->delete_unused_bgs_mutex);
7585717f 2709 mutex_init(&fs_info->reloc_mutex);
573bfb72 2710 mutex_init(&fs_info->delalloc_root_mutex);
c2d6cb16 2711 mutex_init(&fs_info->cleaner_delayed_iput_mutex);
de98ced9 2712 seqlock_init(&fs_info->profiles_lock);
19c00ddc 2713
0b86a832 2714 INIT_LIST_HEAD(&fs_info->dirty_cowonly_roots);
6324fbf3 2715 INIT_LIST_HEAD(&fs_info->space_info);
f29021b2 2716 INIT_LIST_HEAD(&fs_info->tree_mod_seq_list);
47ab2a6c 2717 INIT_LIST_HEAD(&fs_info->unused_bgs);
0b86a832 2718 btrfs_mapping_init(&fs_info->mapping_tree);
66d8f3dd
MX
2719 btrfs_init_block_rsv(&fs_info->global_block_rsv,
2720 BTRFS_BLOCK_RSV_GLOBAL);
66d8f3dd
MX
2721 btrfs_init_block_rsv(&fs_info->trans_block_rsv, BTRFS_BLOCK_RSV_TRANS);
2722 btrfs_init_block_rsv(&fs_info->chunk_block_rsv, BTRFS_BLOCK_RSV_CHUNK);
2723 btrfs_init_block_rsv(&fs_info->empty_block_rsv, BTRFS_BLOCK_RSV_EMPTY);
2724 btrfs_init_block_rsv(&fs_info->delayed_block_rsv,
2725 BTRFS_BLOCK_RSV_DELOPS);
771ed689 2726 atomic_set(&fs_info->async_delalloc_pages, 0);
4cb5300b 2727 atomic_set(&fs_info->defrag_running, 0);
fcebe456 2728 atomic_set(&fs_info->qgroup_op_seq, 0);
2fefd558 2729 atomic_set(&fs_info->reada_works_cnt, 0);
fc36ed7e 2730 atomic64_set(&fs_info->tree_mod_seq, 0);
e20d96d6 2731 fs_info->sb = sb;
95ac567a 2732 fs_info->max_inline = BTRFS_DEFAULT_MAX_INLINE;
9ed74f2d 2733 fs_info->metadata_ratio = 0;
4cb5300b 2734 fs_info->defrag_inodes = RB_ROOT;
a5ed45f8 2735 atomic64_set(&fs_info->free_chunk_space, 0);
f29021b2 2736 fs_info->tree_mod_log = RB_ROOT;
8b87dc17 2737 fs_info->commit_interval = BTRFS_DEFAULT_COMMIT_INTERVAL;
f8c269d7 2738 fs_info->avg_delayed_ref_runtime = NSEC_PER_SEC >> 6; /* div by 64 */
90519d66 2739 /* readahead state */
d0164adc 2740 INIT_RADIX_TREE(&fs_info->reada_tree, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
90519d66 2741 spin_lock_init(&fs_info->reada_lock);
fd708b81 2742 btrfs_init_ref_verify(fs_info);
c8b97818 2743
b34b086c
CM
2744 fs_info->thread_pool_size = min_t(unsigned long,
2745 num_online_cpus() + 2, 8);
0afbaf8c 2746
199c2a9c
MX
2747 INIT_LIST_HEAD(&fs_info->ordered_roots);
2748 spin_lock_init(&fs_info->ordered_root_lock);
69fe2d75
JB
2749
2750 fs_info->btree_inode = new_inode(sb);
2751 if (!fs_info->btree_inode) {
2752 err = -ENOMEM;
2753 goto fail_bio_counter;
2754 }
2755 mapping_set_gfp_mask(fs_info->btree_inode->i_mapping, GFP_NOFS);
2756
16cdcec7 2757 fs_info->delayed_root = kmalloc(sizeof(struct btrfs_delayed_root),
74e4d827 2758 GFP_KERNEL);
16cdcec7
MX
2759 if (!fs_info->delayed_root) {
2760 err = -ENOMEM;
2761 goto fail_iput;
2762 }
2763 btrfs_init_delayed_root(fs_info->delayed_root);
3eaa2885 2764
638aa7ed 2765 btrfs_init_scrub(fs_info);
21adbd5c
SB
2766#ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
2767 fs_info->check_integrity_print_mask = 0;
2768#endif
779a65a4 2769 btrfs_init_balance(fs_info);
21c7e756 2770 btrfs_init_async_reclaim_work(&fs_info->async_reclaim_work);
a2de733c 2771
9f6d2510
DS
2772 sb->s_blocksize = BTRFS_BDEV_BLOCKSIZE;
2773 sb->s_blocksize_bits = blksize_bits(BTRFS_BDEV_BLOCKSIZE);
a061fc8d 2774
6bccf3ab 2775 btrfs_init_btree_inode(fs_info);
76dda93c 2776
0f9dd46c 2777 spin_lock_init(&fs_info->block_group_cache_lock);
6bef4d31 2778 fs_info->block_group_cache_tree = RB_ROOT;
a1897fdd 2779 fs_info->first_logical_byte = (u64)-1;
0f9dd46c 2780
c6100a4b
JB
2781 extent_io_tree_init(&fs_info->freed_extents[0], NULL);
2782 extent_io_tree_init(&fs_info->freed_extents[1], NULL);
11833d66 2783 fs_info->pinned_extents = &fs_info->freed_extents[0];
afcdd129 2784 set_bit(BTRFS_FS_BARRIER, &fs_info->flags);
39279cc3 2785
5a3f23d5 2786 mutex_init(&fs_info->ordered_operations_mutex);
e02119d5 2787 mutex_init(&fs_info->tree_log_mutex);
925baedd 2788 mutex_init(&fs_info->chunk_mutex);
a74a4b97
CM
2789 mutex_init(&fs_info->transaction_kthread_mutex);
2790 mutex_init(&fs_info->cleaner_mutex);
1bbc621e 2791 mutex_init(&fs_info->ro_block_group_mutex);
9e351cc8 2792 init_rwsem(&fs_info->commit_root_sem);
c71bf099 2793 init_rwsem(&fs_info->cleanup_work_sem);
76dda93c 2794 init_rwsem(&fs_info->subvol_sem);
803b2f54 2795 sema_init(&fs_info->uuid_tree_rescan_sem, 1);
fa9c0d79 2796
ad618368 2797 btrfs_init_dev_replace_locks(fs_info);
f9e92e40 2798 btrfs_init_qgroup(fs_info);
416ac51d 2799
fa9c0d79
CM
2800 btrfs_init_free_cluster(&fs_info->meta_alloc_cluster);
2801 btrfs_init_free_cluster(&fs_info->data_alloc_cluster);
2802
e6dcd2dc 2803 init_waitqueue_head(&fs_info->transaction_throttle);
f9295749 2804 init_waitqueue_head(&fs_info->transaction_wait);
bb9c12c9 2805 init_waitqueue_head(&fs_info->transaction_blocked_wait);
4854ddd0 2806 init_waitqueue_head(&fs_info->async_submit_wait);
3768f368 2807
04216820
FM
2808 INIT_LIST_HEAD(&fs_info->pinned_chunks);
2809
da17066c
JM
2810 /* Usable values until the real ones are cached from the superblock */
2811 fs_info->nodesize = 4096;
2812 fs_info->sectorsize = 4096;
2813 fs_info->stripesize = 4096;
2814
53b381b3
DW
2815 ret = btrfs_alloc_stripe_hash_table(fs_info);
2816 if (ret) {
83c8266a 2817 err = ret;
53b381b3
DW
2818 goto fail_alloc;
2819 }
2820
da17066c 2821 __setup_root(tree_root, fs_info, BTRFS_ROOT_TREE_OBJECTID);
7eccb903 2822
3c4bb26b 2823 invalidate_bdev(fs_devices->latest_bdev);
1104a885
DS
2824
2825 /*
2826 * Read super block and check the signature bytes only
2827 */
a512bbf8 2828 bh = btrfs_read_dev_super(fs_devices->latest_bdev);
92fc03fb
AJ
2829 if (IS_ERR(bh)) {
2830 err = PTR_ERR(bh);
16cdcec7 2831 goto fail_alloc;
20b45077 2832 }
39279cc3 2833
1104a885
DS
2834 /*
2835 * We want to check superblock checksum, the type is stored inside.
2836 * Pass the whole disk block of size BTRFS_SUPER_INFO_SIZE (4k).
2837 */
ab8d0fc4 2838 if (btrfs_check_super_csum(fs_info, bh->b_data)) {
05135f59 2839 btrfs_err(fs_info, "superblock checksum mismatch");
1104a885 2840 err = -EINVAL;
b2acdddf 2841 brelse(bh);
1104a885
DS
2842 goto fail_alloc;
2843 }
2844
2845 /*
2846 * super_copy is zeroed at allocation time and we never touch the
2847 * following bytes up to INFO_SIZE, the checksum is calculated from
2848 * the whole block of INFO_SIZE
2849 */
6c41761f
DS
2850 memcpy(fs_info->super_copy, bh->b_data, sizeof(*fs_info->super_copy));
2851 memcpy(fs_info->super_for_commit, fs_info->super_copy,
2852 sizeof(*fs_info->super_for_commit));
a061fc8d 2853 brelse(bh);
5f39d397 2854
6c41761f 2855 memcpy(fs_info->fsid, fs_info->super_copy->fsid, BTRFS_FSID_SIZE);
0b86a832 2856
069ec957 2857 ret = btrfs_validate_mount_super(fs_info);
1104a885 2858 if (ret) {
05135f59 2859 btrfs_err(fs_info, "superblock contains fatal errors");
1104a885
DS
2860 err = -EINVAL;
2861 goto fail_alloc;
2862 }
2863
6c41761f 2864 disk_super = fs_info->super_copy;
0f7d52f4 2865 if (!btrfs_super_root(disk_super))
16cdcec7 2866 goto fail_alloc;
0f7d52f4 2867
acce952b 2868 /* check FS state, whether FS is broken. */
87533c47
MX
2869 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_ERROR)
2870 set_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state);
acce952b 2871
af31f5e5
CM
2872 /*
2873 * run through our array of backup supers and setup
2874 * our ring pointer to the oldest one
2875 */
2876 generation = btrfs_super_generation(disk_super);
2877 find_oldest_super_backup(fs_info, generation);
2878
75e7cb7f
LB
2879 /*
2880 * In the long term, we'll store the compression type in the super
2881 * block, and it'll be used for per file compression control.
2882 */
2883 fs_info->compress_type = BTRFS_COMPRESS_ZLIB;
2884
2ff7e61e 2885 ret = btrfs_parse_options(fs_info, options, sb->s_flags);
2b82032c
YZ
2886 if (ret) {
2887 err = ret;
16cdcec7 2888 goto fail_alloc;
2b82032c 2889 }
dfe25020 2890
f2b636e8
JB
2891 features = btrfs_super_incompat_flags(disk_super) &
2892 ~BTRFS_FEATURE_INCOMPAT_SUPP;
2893 if (features) {
05135f59
DS
2894 btrfs_err(fs_info,
2895 "cannot mount because of unsupported optional features (%llx)",
2896 features);
f2b636e8 2897 err = -EINVAL;
16cdcec7 2898 goto fail_alloc;
f2b636e8
JB
2899 }
2900
5d4f98a2 2901 features = btrfs_super_incompat_flags(disk_super);
a6fa6fae 2902 features |= BTRFS_FEATURE_INCOMPAT_MIXED_BACKREF;
0b246afa 2903 if (fs_info->compress_type == BTRFS_COMPRESS_LZO)
a6fa6fae 2904 features |= BTRFS_FEATURE_INCOMPAT_COMPRESS_LZO;
5c1aab1d
NT
2905 else if (fs_info->compress_type == BTRFS_COMPRESS_ZSTD)
2906 features |= BTRFS_FEATURE_INCOMPAT_COMPRESS_ZSTD;
727011e0 2907
3173a18f 2908 if (features & BTRFS_FEATURE_INCOMPAT_SKINNY_METADATA)
05135f59 2909 btrfs_info(fs_info, "has skinny extents");
3173a18f 2910
727011e0
CM
2911 /*
2912 * flag our filesystem as having big metadata blocks if
2913 * they are bigger than the page size
2914 */
09cbfeaf 2915 if (btrfs_super_nodesize(disk_super) > PAGE_SIZE) {
727011e0 2916 if (!(features & BTRFS_FEATURE_INCOMPAT_BIG_METADATA))
05135f59
DS
2917 btrfs_info(fs_info,
2918 "flagging fs with big metadata feature");
727011e0
CM
2919 features |= BTRFS_FEATURE_INCOMPAT_BIG_METADATA;
2920 }
2921
bc3f116f 2922 nodesize = btrfs_super_nodesize(disk_super);
bc3f116f 2923 sectorsize = btrfs_super_sectorsize(disk_super);
b7f67055 2924 stripesize = sectorsize;
707e8a07 2925 fs_info->dirty_metadata_batch = nodesize * (1 + ilog2(nr_cpu_ids));
963d678b 2926 fs_info->delalloc_batch = sectorsize * 512 * (1 + ilog2(nr_cpu_ids));
bc3f116f 2927
da17066c
JM
2928 /* Cache block sizes */
2929 fs_info->nodesize = nodesize;
2930 fs_info->sectorsize = sectorsize;
2931 fs_info->stripesize = stripesize;
2932
bc3f116f
CM
2933 /*
2934 * mixed block groups end up with duplicate but slightly offset
2935 * extent buffers for the same range. It leads to corruptions
2936 */
2937 if ((features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS) &&
707e8a07 2938 (sectorsize != nodesize)) {
05135f59
DS
2939 btrfs_err(fs_info,
2940"unequal nodesize/sectorsize (%u != %u) are not allowed for mixed block groups",
2941 nodesize, sectorsize);
bc3f116f
CM
2942 goto fail_alloc;
2943 }
2944
ceda0864
MX
2945 /*
2946 * Needn't use the lock because there is no other task which will
2947 * update the flag.
2948 */
a6fa6fae 2949 btrfs_set_super_incompat_flags(disk_super, features);
5d4f98a2 2950
f2b636e8
JB
2951 features = btrfs_super_compat_ro_flags(disk_super) &
2952 ~BTRFS_FEATURE_COMPAT_RO_SUPP;
bc98a42c 2953 if (!sb_rdonly(sb) && features) {
05135f59
DS
2954 btrfs_err(fs_info,
2955 "cannot mount read-write because of unsupported optional features (%llx)",
c1c9ff7c 2956 features);
f2b636e8 2957 err = -EINVAL;
16cdcec7 2958 goto fail_alloc;
f2b636e8 2959 }
61d92c32 2960
2a458198
ES
2961 ret = btrfs_init_workqueues(fs_info, fs_devices);
2962 if (ret) {
2963 err = ret;
0dc3b84a
JB
2964 goto fail_sb_buffer;
2965 }
4543df7e 2966
9e11ceee
JK
2967 sb->s_bdi->congested_fn = btrfs_congested_fn;
2968 sb->s_bdi->congested_data = fs_info;
2969 sb->s_bdi->capabilities |= BDI_CAP_CGROUP_WRITEBACK;
d4417e22 2970 sb->s_bdi->ra_pages = VM_MAX_READAHEAD * SZ_1K / PAGE_SIZE;
9e11ceee
JK
2971 sb->s_bdi->ra_pages *= btrfs_super_num_devices(disk_super);
2972 sb->s_bdi->ra_pages = max(sb->s_bdi->ra_pages, SZ_4M / PAGE_SIZE);
4575c9cc 2973
a061fc8d
CM
2974 sb->s_blocksize = sectorsize;
2975 sb->s_blocksize_bits = blksize_bits(sectorsize);
ee87cf5e 2976 memcpy(&sb->s_uuid, fs_info->fsid, BTRFS_FSID_SIZE);
db94535d 2977
925baedd 2978 mutex_lock(&fs_info->chunk_mutex);
6bccf3ab 2979 ret = btrfs_read_sys_array(fs_info);
925baedd 2980 mutex_unlock(&fs_info->chunk_mutex);
84eed90f 2981 if (ret) {
05135f59 2982 btrfs_err(fs_info, "failed to read the system array: %d", ret);
5d4f98a2 2983 goto fail_sb_buffer;
84eed90f 2984 }
0b86a832 2985
84234f3a 2986 generation = btrfs_super_chunk_root_generation(disk_super);
581c1760 2987 level = btrfs_super_chunk_root_level(disk_super);
0b86a832 2988
da17066c 2989 __setup_root(chunk_root, fs_info, BTRFS_CHUNK_TREE_OBJECTID);
0b86a832 2990
2ff7e61e 2991 chunk_root->node = read_tree_block(fs_info,
0b86a832 2992 btrfs_super_chunk_root(disk_super),
581c1760 2993 generation, level, NULL);
64c043de
LB
2994 if (IS_ERR(chunk_root->node) ||
2995 !extent_buffer_uptodate(chunk_root->node)) {
05135f59 2996 btrfs_err(fs_info, "failed to read chunk root");
e5fffbac 2997 if (!IS_ERR(chunk_root->node))
2998 free_extent_buffer(chunk_root->node);
95ab1f64 2999 chunk_root->node = NULL;
af31f5e5 3000 goto fail_tree_roots;
83121942 3001 }
5d4f98a2
YZ
3002 btrfs_set_root_node(&chunk_root->root_item, chunk_root->node);
3003 chunk_root->commit_root = btrfs_root_node(chunk_root);
0b86a832 3004
e17cade2 3005 read_extent_buffer(chunk_root->node, fs_info->chunk_tree_uuid,
b308bc2f 3006 btrfs_header_chunk_tree_uuid(chunk_root->node), BTRFS_UUID_SIZE);
e17cade2 3007
5b4aacef 3008 ret = btrfs_read_chunk_tree(fs_info);
2b82032c 3009 if (ret) {
05135f59 3010 btrfs_err(fs_info, "failed to read chunk tree: %d", ret);
af31f5e5 3011 goto fail_tree_roots;
2b82032c 3012 }
0b86a832 3013
8dabb742 3014 /*
9b99b115
AJ
3015 * Keep the devid that is marked to be the target device for the
3016 * device replace procedure
8dabb742 3017 */
9b99b115 3018 btrfs_free_extra_devids(fs_devices, 0);
dfe25020 3019
a6b0d5c8 3020 if (!fs_devices->latest_bdev) {
05135f59 3021 btrfs_err(fs_info, "failed to read devices");
a6b0d5c8
CM
3022 goto fail_tree_roots;
3023 }
3024
af31f5e5 3025retry_root_backup:
84234f3a 3026 generation = btrfs_super_generation(disk_super);
581c1760 3027 level = btrfs_super_root_level(disk_super);
0b86a832 3028
2ff7e61e 3029 tree_root->node = read_tree_block(fs_info,
db94535d 3030 btrfs_super_root(disk_super),
581c1760 3031 generation, level, NULL);
64c043de
LB
3032 if (IS_ERR(tree_root->node) ||
3033 !extent_buffer_uptodate(tree_root->node)) {
05135f59 3034 btrfs_warn(fs_info, "failed to read tree root");
e5fffbac 3035 if (!IS_ERR(tree_root->node))
3036 free_extent_buffer(tree_root->node);
95ab1f64 3037 tree_root->node = NULL;
af31f5e5 3038 goto recovery_tree_root;
83121942 3039 }
af31f5e5 3040
5d4f98a2
YZ
3041 btrfs_set_root_node(&tree_root->root_item, tree_root->node);
3042 tree_root->commit_root = btrfs_root_node(tree_root);
69e9c6c6 3043 btrfs_set_root_refs(&tree_root->root_item, 1);
db94535d 3044
f32e48e9
CR
3045 mutex_lock(&tree_root->objectid_mutex);
3046 ret = btrfs_find_highest_objectid(tree_root,
3047 &tree_root->highest_objectid);
3048 if (ret) {
3049 mutex_unlock(&tree_root->objectid_mutex);
3050 goto recovery_tree_root;
3051 }
3052
3053 ASSERT(tree_root->highest_objectid <= BTRFS_LAST_FREE_OBJECTID);
3054
3055 mutex_unlock(&tree_root->objectid_mutex);
3056
6bccf3ab 3057 ret = btrfs_read_roots(fs_info);
4bbcaa64 3058 if (ret)
af31f5e5 3059 goto recovery_tree_root;
f7a81ea4 3060
8929ecfa
YZ
3061 fs_info->generation = generation;
3062 fs_info->last_trans_committed = generation;
8929ecfa 3063
68310a5e
ID
3064 ret = btrfs_recover_balance(fs_info);
3065 if (ret) {
05135f59 3066 btrfs_err(fs_info, "failed to recover balance: %d", ret);
68310a5e
ID
3067 goto fail_block_groups;
3068 }
3069
733f4fbb
SB
3070 ret = btrfs_init_dev_stats(fs_info);
3071 if (ret) {
05135f59 3072 btrfs_err(fs_info, "failed to init dev_stats: %d", ret);
733f4fbb
SB
3073 goto fail_block_groups;
3074 }
3075
8dabb742
SB
3076 ret = btrfs_init_dev_replace(fs_info);
3077 if (ret) {
05135f59 3078 btrfs_err(fs_info, "failed to init dev_replace: %d", ret);
8dabb742
SB
3079 goto fail_block_groups;
3080 }
3081
9b99b115 3082 btrfs_free_extra_devids(fs_devices, 1);
8dabb742 3083
b7c35e81
AJ
3084 ret = btrfs_sysfs_add_fsid(fs_devices, NULL);
3085 if (ret) {
05135f59
DS
3086 btrfs_err(fs_info, "failed to init sysfs fsid interface: %d",
3087 ret);
b7c35e81
AJ
3088 goto fail_block_groups;
3089 }
3090
3091 ret = btrfs_sysfs_add_device(fs_devices);
3092 if (ret) {
05135f59
DS
3093 btrfs_err(fs_info, "failed to init sysfs device interface: %d",
3094 ret);
b7c35e81
AJ
3095 goto fail_fsdev_sysfs;
3096 }
3097
96f3136e 3098 ret = btrfs_sysfs_add_mounted(fs_info);
c59021f8 3099 if (ret) {
05135f59 3100 btrfs_err(fs_info, "failed to init sysfs interface: %d", ret);
b7c35e81 3101 goto fail_fsdev_sysfs;
c59021f8 3102 }
3103
c59021f8 3104 ret = btrfs_init_space_info(fs_info);
3105 if (ret) {
05135f59 3106 btrfs_err(fs_info, "failed to initialize space info: %d", ret);
2365dd3c 3107 goto fail_sysfs;
c59021f8 3108 }
3109
5b4aacef 3110 ret = btrfs_read_block_groups(fs_info);
1b1d1f66 3111 if (ret) {
05135f59 3112 btrfs_err(fs_info, "failed to read block groups: %d", ret);
2365dd3c 3113 goto fail_sysfs;
1b1d1f66 3114 }
4330e183 3115
6528b99d 3116 if (!sb_rdonly(sb) && !btrfs_check_rw_degradable(fs_info, NULL)) {
05135f59 3117 btrfs_warn(fs_info,
4330e183 3118 "writeable mount is not allowed due to too many missing devices");
2365dd3c 3119 goto fail_sysfs;
292fd7fc 3120 }
9078a3e1 3121
a74a4b97
CM
3122 fs_info->cleaner_kthread = kthread_run(cleaner_kthread, tree_root,
3123 "btrfs-cleaner");
57506d50 3124 if (IS_ERR(fs_info->cleaner_kthread))
2365dd3c 3125 goto fail_sysfs;
a74a4b97
CM
3126
3127 fs_info->transaction_kthread = kthread_run(transaction_kthread,
3128 tree_root,
3129 "btrfs-transaction");
57506d50 3130 if (IS_ERR(fs_info->transaction_kthread))
3f157a2f 3131 goto fail_cleaner;
a74a4b97 3132
583b7231 3133 if (!btrfs_test_opt(fs_info, NOSSD) &&
c289811c 3134 !fs_info->fs_devices->rotating) {
583b7231 3135 btrfs_set_and_info(fs_info, SSD, "enabling ssd optimizations");
c289811c
CM
3136 }
3137
572d9ab7 3138 /*
01327610 3139 * Mount does not set all options immediately, we can do it now and do
572d9ab7
DS
3140 * not have to wait for transaction commit
3141 */
3142 btrfs_apply_pending_changes(fs_info);
3818aea2 3143
21adbd5c 3144#ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
0b246afa 3145 if (btrfs_test_opt(fs_info, CHECK_INTEGRITY)) {
2ff7e61e 3146 ret = btrfsic_mount(fs_info, fs_devices,
0b246afa 3147 btrfs_test_opt(fs_info,
21adbd5c
SB
3148 CHECK_INTEGRITY_INCLUDING_EXTENT_DATA) ?
3149 1 : 0,
3150 fs_info->check_integrity_print_mask);
3151 if (ret)
05135f59
DS
3152 btrfs_warn(fs_info,
3153 "failed to initialize integrity check module: %d",
3154 ret);
21adbd5c
SB
3155 }
3156#endif
bcef60f2
AJ
3157 ret = btrfs_read_qgroup_config(fs_info);
3158 if (ret)
3159 goto fail_trans_kthread;
21adbd5c 3160
fd708b81
JB
3161 if (btrfs_build_ref_tree(fs_info))
3162 btrfs_err(fs_info, "couldn't build ref tree");
3163
96da0919
QW
3164 /* do not make disk changes in broken FS or nologreplay is given */
3165 if (btrfs_super_log_root(disk_super) != 0 &&
0b246afa 3166 !btrfs_test_opt(fs_info, NOLOGREPLAY)) {
63443bf5 3167 ret = btrfs_replay_log(fs_info, fs_devices);
79787eaa 3168 if (ret) {
63443bf5 3169 err = ret;
28c16cbb 3170 goto fail_qgroup;
79787eaa 3171 }
e02119d5 3172 }
1a40e23b 3173
6bccf3ab 3174 ret = btrfs_find_orphan_roots(fs_info);
79787eaa 3175 if (ret)
28c16cbb 3176 goto fail_qgroup;
76dda93c 3177
bc98a42c 3178 if (!sb_rdonly(sb)) {
d68fc57b 3179 ret = btrfs_cleanup_fs_roots(fs_info);
44c44af2 3180 if (ret)
28c16cbb 3181 goto fail_qgroup;
90c711ab
ZB
3182
3183 mutex_lock(&fs_info->cleaner_mutex);
5d4f98a2 3184 ret = btrfs_recover_relocation(tree_root);
90c711ab 3185 mutex_unlock(&fs_info->cleaner_mutex);
d7ce5843 3186 if (ret < 0) {
05135f59
DS
3187 btrfs_warn(fs_info, "failed to recover relocation: %d",
3188 ret);
d7ce5843 3189 err = -EINVAL;
bcef60f2 3190 goto fail_qgroup;
d7ce5843 3191 }
7c2ca468 3192 }
1a40e23b 3193
3de4586c
CM
3194 location.objectid = BTRFS_FS_TREE_OBJECTID;
3195 location.type = BTRFS_ROOT_ITEM_KEY;
cb517eab 3196 location.offset = 0;
3de4586c 3197
3de4586c 3198 fs_info->fs_root = btrfs_read_fs_root_no_name(fs_info, &location);
3140c9a3
DC
3199 if (IS_ERR(fs_info->fs_root)) {
3200 err = PTR_ERR(fs_info->fs_root);
f50f4353 3201 btrfs_warn(fs_info, "failed to read fs tree: %d", err);
bcef60f2 3202 goto fail_qgroup;
3140c9a3 3203 }
c289811c 3204
bc98a42c 3205 if (sb_rdonly(sb))
2b6ba629 3206 return 0;
59641015 3207
f8d468a1
OS
3208 if (btrfs_test_opt(fs_info, CLEAR_CACHE) &&
3209 btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
6675df31
OS
3210 clear_free_space_tree = 1;
3211 } else if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE) &&
3212 !btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE_VALID)) {
3213 btrfs_warn(fs_info, "free space tree is invalid");
3214 clear_free_space_tree = 1;
3215 }
3216
3217 if (clear_free_space_tree) {
f8d468a1
OS
3218 btrfs_info(fs_info, "clearing free space tree");
3219 ret = btrfs_clear_free_space_tree(fs_info);
3220 if (ret) {
3221 btrfs_warn(fs_info,
3222 "failed to clear free space tree: %d", ret);
6bccf3ab 3223 close_ctree(fs_info);
f8d468a1
OS
3224 return ret;
3225 }
3226 }
3227
0b246afa 3228 if (btrfs_test_opt(fs_info, FREE_SPACE_TREE) &&
511711af 3229 !btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
05135f59 3230 btrfs_info(fs_info, "creating free space tree");
511711af
CM
3231 ret = btrfs_create_free_space_tree(fs_info);
3232 if (ret) {
05135f59
DS
3233 btrfs_warn(fs_info,
3234 "failed to create free space tree: %d", ret);
6bccf3ab 3235 close_ctree(fs_info);
511711af
CM
3236 return ret;
3237 }
3238 }
3239
2b6ba629
ID
3240 down_read(&fs_info->cleanup_work_sem);
3241 if ((ret = btrfs_orphan_cleanup(fs_info->fs_root)) ||
3242 (ret = btrfs_orphan_cleanup(fs_info->tree_root))) {
e3acc2a6 3243 up_read(&fs_info->cleanup_work_sem);
6bccf3ab 3244 close_ctree(fs_info);
2b6ba629
ID
3245 return ret;
3246 }
3247 up_read(&fs_info->cleanup_work_sem);
59641015 3248
2b6ba629
ID
3249 ret = btrfs_resume_balance_async(fs_info);
3250 if (ret) {
05135f59 3251 btrfs_warn(fs_info, "failed to resume balance: %d", ret);
6bccf3ab 3252 close_ctree(fs_info);
2b6ba629 3253 return ret;
e3acc2a6
JB
3254 }
3255
8dabb742
SB
3256 ret = btrfs_resume_dev_replace_async(fs_info);
3257 if (ret) {
05135f59 3258 btrfs_warn(fs_info, "failed to resume device replace: %d", ret);
6bccf3ab 3259 close_ctree(fs_info);
8dabb742
SB
3260 return ret;
3261 }
3262
b382a324
JS
3263 btrfs_qgroup_rescan_resume(fs_info);
3264
4bbcaa64 3265 if (!fs_info->uuid_root) {
05135f59 3266 btrfs_info(fs_info, "creating UUID tree");
f7a81ea4
SB
3267 ret = btrfs_create_uuid_tree(fs_info);
3268 if (ret) {
05135f59
DS
3269 btrfs_warn(fs_info,
3270 "failed to create the UUID tree: %d", ret);
6bccf3ab 3271 close_ctree(fs_info);
f7a81ea4
SB
3272 return ret;
3273 }
0b246afa 3274 } else if (btrfs_test_opt(fs_info, RESCAN_UUID_TREE) ||
4bbcaa64
ES
3275 fs_info->generation !=
3276 btrfs_super_uuid_tree_generation(disk_super)) {
05135f59 3277 btrfs_info(fs_info, "checking UUID tree");
70f80175
SB
3278 ret = btrfs_check_uuid_tree(fs_info);
3279 if (ret) {
05135f59
DS
3280 btrfs_warn(fs_info,
3281 "failed to check the UUID tree: %d", ret);
6bccf3ab 3282 close_ctree(fs_info);
70f80175
SB
3283 return ret;
3284 }
3285 } else {
afcdd129 3286 set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
f7a81ea4 3287 }
afcdd129 3288 set_bit(BTRFS_FS_OPEN, &fs_info->flags);
47ab2a6c 3289
8dcddfa0
QW
3290 /*
3291 * backuproot only affect mount behavior, and if open_ctree succeeded,
3292 * no need to keep the flag
3293 */
3294 btrfs_clear_opt(fs_info->mount_opt, USEBACKUPROOT);
3295
ad2b2c80 3296 return 0;
39279cc3 3297
bcef60f2
AJ
3298fail_qgroup:
3299 btrfs_free_qgroup_config(fs_info);
7c2ca468
CM
3300fail_trans_kthread:
3301 kthread_stop(fs_info->transaction_kthread);
2ff7e61e 3302 btrfs_cleanup_transaction(fs_info);
faa2dbf0 3303 btrfs_free_fs_roots(fs_info);
3f157a2f 3304fail_cleaner:
a74a4b97 3305 kthread_stop(fs_info->cleaner_kthread);
7c2ca468
CM
3306
3307 /*
3308 * make sure we're done with the btree inode before we stop our
3309 * kthreads
3310 */
3311 filemap_write_and_wait(fs_info->btree_inode->i_mapping);
7c2ca468 3312
2365dd3c 3313fail_sysfs:
6618a59b 3314 btrfs_sysfs_remove_mounted(fs_info);
2365dd3c 3315
b7c35e81
AJ
3316fail_fsdev_sysfs:
3317 btrfs_sysfs_remove_fsid(fs_info->fs_devices);
3318
1b1d1f66 3319fail_block_groups:
54067ae9 3320 btrfs_put_block_group_cache(fs_info);
af31f5e5
CM
3321
3322fail_tree_roots:
3323 free_root_pointers(fs_info, 1);
2b8195bb 3324 invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
af31f5e5 3325
39279cc3 3326fail_sb_buffer:
7abadb64 3327 btrfs_stop_all_workers(fs_info);
5cdd7db6 3328 btrfs_free_block_groups(fs_info);
16cdcec7 3329fail_alloc:
4543df7e 3330fail_iput:
586e46e2
ID
3331 btrfs_mapping_tree_free(&fs_info->mapping_tree);
3332
4543df7e 3333 iput(fs_info->btree_inode);
c404e0dc
MX
3334fail_bio_counter:
3335 percpu_counter_destroy(&fs_info->bio_counter);
963d678b
MX
3336fail_delalloc_bytes:
3337 percpu_counter_destroy(&fs_info->delalloc_bytes);
e2d84521
MX
3338fail_dirty_metadata_bytes:
3339 percpu_counter_destroy(&fs_info->dirty_metadata_bytes);
76dda93c
YZ
3340fail_srcu:
3341 cleanup_srcu_struct(&fs_info->subvol_srcu);
7e662854 3342fail:
53b381b3 3343 btrfs_free_stripe_hash_table(fs_info);
586e46e2 3344 btrfs_close_devices(fs_info->fs_devices);
ad2b2c80 3345 return err;
af31f5e5
CM
3346
3347recovery_tree_root:
0b246afa 3348 if (!btrfs_test_opt(fs_info, USEBACKUPROOT))
af31f5e5
CM
3349 goto fail_tree_roots;
3350
3351 free_root_pointers(fs_info, 0);
3352
3353 /* don't use the log in recovery mode, it won't be valid */
3354 btrfs_set_super_log_root(disk_super, 0);
3355
3356 /* we can't trust the free space cache either */
3357 btrfs_set_opt(fs_info->mount_opt, CLEAR_CACHE);
3358
3359 ret = next_root_backup(fs_info, fs_info->super_copy,
3360 &num_backups_tried, &backup_index);
3361 if (ret == -1)
3362 goto fail_block_groups;
3363 goto retry_root_backup;
eb60ceac 3364}
663faf9f 3365ALLOW_ERROR_INJECTION(open_ctree, ERRNO);
eb60ceac 3366
f2984462
CM
3367static void btrfs_end_buffer_write_sync(struct buffer_head *bh, int uptodate)
3368{
f2984462
CM
3369 if (uptodate) {
3370 set_buffer_uptodate(bh);
3371 } else {
442a4f63
SB
3372 struct btrfs_device *device = (struct btrfs_device *)
3373 bh->b_private;
3374
fb456252 3375 btrfs_warn_rl_in_rcu(device->fs_info,
b14af3b4 3376 "lost page write due to IO error on %s",
606686ee 3377 rcu_str_deref(device->name));
01327610 3378 /* note, we don't set_buffer_write_io_error because we have
1259ab75
CM
3379 * our own ways of dealing with the IO errors
3380 */
f2984462 3381 clear_buffer_uptodate(bh);
442a4f63 3382 btrfs_dev_stat_inc_and_print(device, BTRFS_DEV_STAT_WRITE_ERRS);
f2984462
CM
3383 }
3384 unlock_buffer(bh);
3385 put_bh(bh);
3386}
3387
29c36d72
AJ
3388int btrfs_read_dev_one_super(struct block_device *bdev, int copy_num,
3389 struct buffer_head **bh_ret)
3390{
3391 struct buffer_head *bh;
3392 struct btrfs_super_block *super;
3393 u64 bytenr;
3394
3395 bytenr = btrfs_sb_offset(copy_num);
3396 if (bytenr + BTRFS_SUPER_INFO_SIZE >= i_size_read(bdev->bd_inode))
3397 return -EINVAL;
3398
9f6d2510 3399 bh = __bread(bdev, bytenr / BTRFS_BDEV_BLOCKSIZE, BTRFS_SUPER_INFO_SIZE);
29c36d72
AJ
3400 /*
3401 * If we fail to read from the underlying devices, as of now
3402 * the best option we have is to mark it EIO.
3403 */
3404 if (!bh)
3405 return -EIO;
3406
3407 super = (struct btrfs_super_block *)bh->b_data;
3408 if (btrfs_super_bytenr(super) != bytenr ||
3409 btrfs_super_magic(super) != BTRFS_MAGIC) {
3410 brelse(bh);
3411 return -EINVAL;
3412 }
3413
3414 *bh_ret = bh;
3415 return 0;
3416}
3417
3418
a512bbf8
YZ
3419struct buffer_head *btrfs_read_dev_super(struct block_device *bdev)
3420{
3421 struct buffer_head *bh;
3422 struct buffer_head *latest = NULL;
3423 struct btrfs_super_block *super;
3424 int i;
3425 u64 transid = 0;
92fc03fb 3426 int ret = -EINVAL;
a512bbf8
YZ
3427
3428 /* we would like to check all the supers, but that would make
3429 * a btrfs mount succeed after a mkfs from a different FS.
3430 * So, we need to add a special mount option to scan for
3431 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
3432 */
3433 for (i = 0; i < 1; i++) {
29c36d72
AJ
3434 ret = btrfs_read_dev_one_super(bdev, i, &bh);
3435 if (ret)
a512bbf8
YZ
3436 continue;
3437
3438 super = (struct btrfs_super_block *)bh->b_data;
a512bbf8
YZ
3439
3440 if (!latest || btrfs_super_generation(super) > transid) {
3441 brelse(latest);
3442 latest = bh;
3443 transid = btrfs_super_generation(super);
3444 } else {
3445 brelse(bh);
3446 }
3447 }
92fc03fb
AJ
3448
3449 if (!latest)
3450 return ERR_PTR(ret);
3451
a512bbf8
YZ
3452 return latest;
3453}
3454
4eedeb75 3455/*
abbb3b8e
DS
3456 * Write superblock @sb to the @device. Do not wait for completion, all the
3457 * buffer heads we write are pinned.
4eedeb75 3458 *
abbb3b8e
DS
3459 * Write @max_mirrors copies of the superblock, where 0 means default that fit
3460 * the expected device size at commit time. Note that max_mirrors must be
3461 * same for write and wait phases.
4eedeb75 3462 *
abbb3b8e 3463 * Return number of errors when buffer head is not found or submission fails.
4eedeb75 3464 */
a512bbf8 3465static int write_dev_supers(struct btrfs_device *device,
abbb3b8e 3466 struct btrfs_super_block *sb, int max_mirrors)
a512bbf8
YZ
3467{
3468 struct buffer_head *bh;
3469 int i;
3470 int ret;
3471 int errors = 0;
3472 u32 crc;
3473 u64 bytenr;
1b9e619c 3474 int op_flags;
a512bbf8
YZ
3475
3476 if (max_mirrors == 0)
3477 max_mirrors = BTRFS_SUPER_MIRROR_MAX;
3478
a512bbf8
YZ
3479 for (i = 0; i < max_mirrors; i++) {
3480 bytenr = btrfs_sb_offset(i);
935e5cc9
MX
3481 if (bytenr + BTRFS_SUPER_INFO_SIZE >=
3482 device->commit_total_bytes)
a512bbf8
YZ
3483 break;
3484
abbb3b8e 3485 btrfs_set_super_bytenr(sb, bytenr);
4eedeb75 3486
abbb3b8e
DS
3487 crc = ~(u32)0;
3488 crc = btrfs_csum_data((const char *)sb + BTRFS_CSUM_SIZE, crc,
3489 BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE);
3490 btrfs_csum_final(crc, sb->csum);
4eedeb75 3491
abbb3b8e 3492 /* One reference for us, and we leave it for the caller */
9f6d2510 3493 bh = __getblk(device->bdev, bytenr / BTRFS_BDEV_BLOCKSIZE,
abbb3b8e
DS
3494 BTRFS_SUPER_INFO_SIZE);
3495 if (!bh) {
3496 btrfs_err(device->fs_info,
3497 "couldn't get super buffer head for bytenr %llu",
3498 bytenr);
3499 errors++;
4eedeb75 3500 continue;
abbb3b8e 3501 }
634554dc 3502
abbb3b8e 3503 memcpy(bh->b_data, sb, BTRFS_SUPER_INFO_SIZE);
a512bbf8 3504
abbb3b8e
DS
3505 /* one reference for submit_bh */
3506 get_bh(bh);
4eedeb75 3507
abbb3b8e
DS
3508 set_buffer_uptodate(bh);
3509 lock_buffer(bh);
3510 bh->b_end_io = btrfs_end_buffer_write_sync;
3511 bh->b_private = device;
a512bbf8 3512
387125fc
CM
3513 /*
3514 * we fua the first super. The others we allow
3515 * to go down lazy.
3516 */
1b9e619c
OS
3517 op_flags = REQ_SYNC | REQ_META | REQ_PRIO;
3518 if (i == 0 && !btrfs_test_opt(device->fs_info, NOBARRIER))
3519 op_flags |= REQ_FUA;
3520 ret = btrfsic_submit_bh(REQ_OP_WRITE, op_flags, bh);
4eedeb75 3521 if (ret)
a512bbf8 3522 errors++;
a512bbf8
YZ
3523 }
3524 return errors < i ? 0 : -1;
3525}
3526
abbb3b8e
DS
3527/*
3528 * Wait for write completion of superblocks done by write_dev_supers,
3529 * @max_mirrors same for write and wait phases.
3530 *
3531 * Return number of errors when buffer head is not found or not marked up to
3532 * date.
3533 */
3534static int wait_dev_supers(struct btrfs_device *device, int max_mirrors)
3535{
3536 struct buffer_head *bh;
3537 int i;
3538 int errors = 0;
b6a535fa 3539 bool primary_failed = false;
abbb3b8e
DS
3540 u64 bytenr;
3541
3542 if (max_mirrors == 0)
3543 max_mirrors = BTRFS_SUPER_MIRROR_MAX;
3544
3545 for (i = 0; i < max_mirrors; i++) {
3546 bytenr = btrfs_sb_offset(i);
3547 if (bytenr + BTRFS_SUPER_INFO_SIZE >=
3548 device->commit_total_bytes)
3549 break;
3550
9f6d2510
DS
3551 bh = __find_get_block(device->bdev,
3552 bytenr / BTRFS_BDEV_BLOCKSIZE,
abbb3b8e
DS
3553 BTRFS_SUPER_INFO_SIZE);
3554 if (!bh) {
3555 errors++;
b6a535fa
HM
3556 if (i == 0)
3557 primary_failed = true;
abbb3b8e
DS
3558 continue;
3559 }
3560 wait_on_buffer(bh);
b6a535fa 3561 if (!buffer_uptodate(bh)) {
abbb3b8e 3562 errors++;
b6a535fa
HM
3563 if (i == 0)
3564 primary_failed = true;
3565 }
abbb3b8e
DS
3566
3567 /* drop our reference */
3568 brelse(bh);
3569
3570 /* drop the reference from the writing run */
3571 brelse(bh);
3572 }
3573
b6a535fa
HM
3574 /* log error, force error return */
3575 if (primary_failed) {
3576 btrfs_err(device->fs_info, "error writing primary super block to device %llu",
3577 device->devid);
3578 return -1;
3579 }
3580
abbb3b8e
DS
3581 return errors < i ? 0 : -1;
3582}
3583
387125fc
CM
3584/*
3585 * endio for the write_dev_flush, this will wake anyone waiting
3586 * for the barrier when it is done
3587 */
4246a0b6 3588static void btrfs_end_empty_barrier(struct bio *bio)
387125fc 3589{
e0ae9994 3590 complete(bio->bi_private);
387125fc
CM
3591}
3592
3593/*
4fc6441a
AJ
3594 * Submit a flush request to the device if it supports it. Error handling is
3595 * done in the waiting counterpart.
387125fc 3596 */
4fc6441a 3597static void write_dev_flush(struct btrfs_device *device)
387125fc 3598{
c2a9c7ab 3599 struct request_queue *q = bdev_get_queue(device->bdev);
e0ae9994 3600 struct bio *bio = device->flush_bio;
387125fc 3601
c2a9c7ab 3602 if (!test_bit(QUEUE_FLAG_WC, &q->queue_flags))
4fc6441a 3603 return;
387125fc 3604
e0ae9994 3605 bio_reset(bio);
387125fc 3606 bio->bi_end_io = btrfs_end_empty_barrier;
74d46992 3607 bio_set_dev(bio, device->bdev);
8d910125 3608 bio->bi_opf = REQ_OP_WRITE | REQ_SYNC | REQ_PREFLUSH;
387125fc
CM
3609 init_completion(&device->flush_wait);
3610 bio->bi_private = &device->flush_wait;
387125fc 3611
43a01111 3612 btrfsic_submit_bio(bio);
1c3063b6 3613 set_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state);
4fc6441a 3614}
387125fc 3615
4fc6441a
AJ
3616/*
3617 * If the flush bio has been submitted by write_dev_flush, wait for it.
3618 */
8c27cb35 3619static blk_status_t wait_dev_flush(struct btrfs_device *device)
4fc6441a 3620{
4fc6441a 3621 struct bio *bio = device->flush_bio;
387125fc 3622
1c3063b6 3623 if (!test_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state))
58efbc9f 3624 return BLK_STS_OK;
387125fc 3625
1c3063b6 3626 clear_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state);
2980d574 3627 wait_for_completion_io(&device->flush_wait);
387125fc 3628
8c27cb35 3629 return bio->bi_status;
387125fc 3630}
387125fc 3631
d10b82fe 3632static int check_barrier_error(struct btrfs_fs_info *fs_info)
401b41e5 3633{
6528b99d 3634 if (!btrfs_check_rw_degradable(fs_info, NULL))
401b41e5 3635 return -EIO;
387125fc
CM
3636 return 0;
3637}
3638
3639/*
3640 * send an empty flush down to each device in parallel,
3641 * then wait for them
3642 */
3643static int barrier_all_devices(struct btrfs_fs_info *info)
3644{
3645 struct list_head *head;
3646 struct btrfs_device *dev;
5af3e8cc 3647 int errors_wait = 0;
4e4cbee9 3648 blk_status_t ret;
387125fc 3649
1538e6c5 3650 lockdep_assert_held(&info->fs_devices->device_list_mutex);
387125fc
CM
3651 /* send down all the barriers */
3652 head = &info->fs_devices->devices;
1538e6c5 3653 list_for_each_entry(dev, head, dev_list) {
e6e674bd 3654 if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
f88ba6a2 3655 continue;
cea7c8bf 3656 if (!dev->bdev)
387125fc 3657 continue;
e12c9621 3658 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
ebbede42 3659 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
387125fc
CM
3660 continue;
3661
4fc6441a 3662 write_dev_flush(dev);
58efbc9f 3663 dev->last_flush_error = BLK_STS_OK;
387125fc
CM
3664 }
3665
3666 /* wait for all the barriers */
1538e6c5 3667 list_for_each_entry(dev, head, dev_list) {
e6e674bd 3668 if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
f88ba6a2 3669 continue;
387125fc 3670 if (!dev->bdev) {
5af3e8cc 3671 errors_wait++;
387125fc
CM
3672 continue;
3673 }
e12c9621 3674 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
ebbede42 3675 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
387125fc
CM
3676 continue;
3677
4fc6441a 3678 ret = wait_dev_flush(dev);
401b41e5
AJ
3679 if (ret) {
3680 dev->last_flush_error = ret;
66b4993e
DS
3681 btrfs_dev_stat_inc_and_print(dev,
3682 BTRFS_DEV_STAT_FLUSH_ERRS);
5af3e8cc 3683 errors_wait++;
401b41e5
AJ
3684 }
3685 }
3686
cea7c8bf 3687 if (errors_wait) {
401b41e5
AJ
3688 /*
3689 * At some point we need the status of all disks
3690 * to arrive at the volume status. So error checking
3691 * is being pushed to a separate loop.
3692 */
d10b82fe 3693 return check_barrier_error(info);
387125fc 3694 }
387125fc
CM
3695 return 0;
3696}
3697
943c6e99
ZL
3698int btrfs_get_num_tolerated_disk_barrier_failures(u64 flags)
3699{
8789f4fe
ZL
3700 int raid_type;
3701 int min_tolerated = INT_MAX;
943c6e99 3702
8789f4fe
ZL
3703 if ((flags & BTRFS_BLOCK_GROUP_PROFILE_MASK) == 0 ||
3704 (flags & BTRFS_AVAIL_ALLOC_BIT_SINGLE))
3705 min_tolerated = min(min_tolerated,
3706 btrfs_raid_array[BTRFS_RAID_SINGLE].
3707 tolerated_failures);
943c6e99 3708
8789f4fe
ZL
3709 for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) {
3710 if (raid_type == BTRFS_RAID_SINGLE)
3711 continue;
41a6e891 3712 if (!(flags & btrfs_raid_array[raid_type].bg_flag))
8789f4fe
ZL
3713 continue;
3714 min_tolerated = min(min_tolerated,
3715 btrfs_raid_array[raid_type].
3716 tolerated_failures);
3717 }
943c6e99 3718
8789f4fe 3719 if (min_tolerated == INT_MAX) {
ab8d0fc4 3720 pr_warn("BTRFS: unknown raid flag: %llu", flags);
8789f4fe
ZL
3721 min_tolerated = 0;
3722 }
3723
3724 return min_tolerated;
943c6e99
ZL
3725}
3726
eece6a9c 3727int write_all_supers(struct btrfs_fs_info *fs_info, int max_mirrors)
f2984462 3728{
e5e9a520 3729 struct list_head *head;
f2984462 3730 struct btrfs_device *dev;
a061fc8d 3731 struct btrfs_super_block *sb;
f2984462 3732 struct btrfs_dev_item *dev_item;
f2984462
CM
3733 int ret;
3734 int do_barriers;
a236aed1
CM
3735 int max_errors;
3736 int total_errors = 0;
a061fc8d 3737 u64 flags;
f2984462 3738
0b246afa 3739 do_barriers = !btrfs_test_opt(fs_info, NOBARRIER);
fed3b381
LB
3740
3741 /*
3742 * max_mirrors == 0 indicates we're from commit_transaction,
3743 * not from fsync where the tree roots in fs_info have not
3744 * been consistent on disk.
3745 */
3746 if (max_mirrors == 0)
3747 backup_super_roots(fs_info);
f2984462 3748
0b246afa 3749 sb = fs_info->super_for_commit;
a061fc8d 3750 dev_item = &sb->dev_item;
e5e9a520 3751
0b246afa
JM
3752 mutex_lock(&fs_info->fs_devices->device_list_mutex);
3753 head = &fs_info->fs_devices->devices;
3754 max_errors = btrfs_super_num_devices(fs_info->super_copy) - 1;
387125fc 3755
5af3e8cc 3756 if (do_barriers) {
0b246afa 3757 ret = barrier_all_devices(fs_info);
5af3e8cc
SB
3758 if (ret) {
3759 mutex_unlock(
0b246afa
JM
3760 &fs_info->fs_devices->device_list_mutex);
3761 btrfs_handle_fs_error(fs_info, ret,
3762 "errors while submitting device barriers.");
5af3e8cc
SB
3763 return ret;
3764 }
3765 }
387125fc 3766
1538e6c5 3767 list_for_each_entry(dev, head, dev_list) {
dfe25020
CM
3768 if (!dev->bdev) {
3769 total_errors++;
3770 continue;
3771 }
e12c9621 3772 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
ebbede42 3773 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
dfe25020
CM
3774 continue;
3775
2b82032c 3776 btrfs_set_stack_device_generation(dev_item, 0);
a061fc8d
CM
3777 btrfs_set_stack_device_type(dev_item, dev->type);
3778 btrfs_set_stack_device_id(dev_item, dev->devid);
7df69d3e 3779 btrfs_set_stack_device_total_bytes(dev_item,
935e5cc9 3780 dev->commit_total_bytes);
ce7213c7
MX
3781 btrfs_set_stack_device_bytes_used(dev_item,
3782 dev->commit_bytes_used);
a061fc8d
CM
3783 btrfs_set_stack_device_io_align(dev_item, dev->io_align);
3784 btrfs_set_stack_device_io_width(dev_item, dev->io_width);
3785 btrfs_set_stack_device_sector_size(dev_item, dev->sector_size);
3786 memcpy(dev_item->uuid, dev->uuid, BTRFS_UUID_SIZE);
44880fdc 3787 memcpy(dev_item->fsid, dev->fs_devices->fsid, BTRFS_FSID_SIZE);
a512bbf8 3788
a061fc8d
CM
3789 flags = btrfs_super_flags(sb);
3790 btrfs_set_super_flags(sb, flags | BTRFS_HEADER_FLAG_WRITTEN);
3791
75cb857d
QW
3792 ret = btrfs_validate_write_super(fs_info, sb);
3793 if (ret < 0) {
3794 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
3795 btrfs_handle_fs_error(fs_info, -EUCLEAN,
3796 "unexpected superblock corruption detected");
3797 return -EUCLEAN;
3798 }
3799
abbb3b8e 3800 ret = write_dev_supers(dev, sb, max_mirrors);
a236aed1
CM
3801 if (ret)
3802 total_errors++;
f2984462 3803 }
a236aed1 3804 if (total_errors > max_errors) {
0b246afa
JM
3805 btrfs_err(fs_info, "%d errors while writing supers",
3806 total_errors);
3807 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
79787eaa 3808
9d565ba4 3809 /* FUA is masked off if unsupported and can't be the reason */
0b246afa
JM
3810 btrfs_handle_fs_error(fs_info, -EIO,
3811 "%d errors while writing supers",
3812 total_errors);
9d565ba4 3813 return -EIO;
a236aed1 3814 }
f2984462 3815
a512bbf8 3816 total_errors = 0;
1538e6c5 3817 list_for_each_entry(dev, head, dev_list) {
dfe25020
CM
3818 if (!dev->bdev)
3819 continue;
e12c9621 3820 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
ebbede42 3821 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
dfe25020
CM
3822 continue;
3823
abbb3b8e 3824 ret = wait_dev_supers(dev, max_mirrors);
a512bbf8
YZ
3825 if (ret)
3826 total_errors++;
f2984462 3827 }
0b246afa 3828 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
a236aed1 3829 if (total_errors > max_errors) {
0b246afa
JM
3830 btrfs_handle_fs_error(fs_info, -EIO,
3831 "%d errors while writing supers",
3832 total_errors);
79787eaa 3833 return -EIO;
a236aed1 3834 }
f2984462
CM
3835 return 0;
3836}
3837
cb517eab
MX
3838/* Drop a fs root from the radix tree and free it. */
3839void btrfs_drop_and_free_fs_root(struct btrfs_fs_info *fs_info,
3840 struct btrfs_root *root)
2619ba1f 3841{
4df27c4d 3842 spin_lock(&fs_info->fs_roots_radix_lock);
2619ba1f
CM
3843 radix_tree_delete(&fs_info->fs_roots_radix,
3844 (unsigned long)root->root_key.objectid);
4df27c4d 3845 spin_unlock(&fs_info->fs_roots_radix_lock);
76dda93c
YZ
3846
3847 if (btrfs_root_refs(&root->root_item) == 0)
3848 synchronize_srcu(&fs_info->subvol_srcu);
3849
1c1ea4f7 3850 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {
3321719e 3851 btrfs_free_log(NULL, root);
1c1ea4f7
LB
3852 if (root->reloc_root) {
3853 free_extent_buffer(root->reloc_root->node);
3854 free_extent_buffer(root->reloc_root->commit_root);
3855 btrfs_put_fs_root(root->reloc_root);
3856 root->reloc_root = NULL;
3857 }
3858 }
3321719e 3859
faa2dbf0
JB
3860 if (root->free_ino_pinned)
3861 __btrfs_remove_free_space_cache(root->free_ino_pinned);
3862 if (root->free_ino_ctl)
3863 __btrfs_remove_free_space_cache(root->free_ino_ctl);
4df27c4d 3864 free_fs_root(root);
4df27c4d
YZ
3865}
3866
3867static void free_fs_root(struct btrfs_root *root)
3868{
57cdc8db 3869 iput(root->ino_cache_inode);
4df27c4d 3870 WARN_ON(!RB_EMPTY_ROOT(&root->inode_tree));
0ee5dc67
AV
3871 if (root->anon_dev)
3872 free_anon_bdev(root->anon_dev);
8257b2dc
MX
3873 if (root->subv_writers)
3874 btrfs_free_subvolume_writers(root->subv_writers);
4df27c4d
YZ
3875 free_extent_buffer(root->node);
3876 free_extent_buffer(root->commit_root);
581bb050
LZ
3877 kfree(root->free_ino_ctl);
3878 kfree(root->free_ino_pinned);
d397712b 3879 kfree(root->name);
b0feb9d9 3880 btrfs_put_fs_root(root);
2619ba1f
CM
3881}
3882
cb517eab
MX
3883void btrfs_free_fs_root(struct btrfs_root *root)
3884{
3885 free_fs_root(root);
2619ba1f
CM
3886}
3887
c146afad 3888int btrfs_cleanup_fs_roots(struct btrfs_fs_info *fs_info)
cfaa7295 3889{
c146afad
YZ
3890 u64 root_objectid = 0;
3891 struct btrfs_root *gang[8];
65d33fd7
QW
3892 int i = 0;
3893 int err = 0;
3894 unsigned int ret = 0;
3895 int index;
e089f05c 3896
c146afad 3897 while (1) {
65d33fd7 3898 index = srcu_read_lock(&fs_info->subvol_srcu);
c146afad
YZ
3899 ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
3900 (void **)gang, root_objectid,
3901 ARRAY_SIZE(gang));
65d33fd7
QW
3902 if (!ret) {
3903 srcu_read_unlock(&fs_info->subvol_srcu, index);
c146afad 3904 break;
65d33fd7 3905 }
5d4f98a2 3906 root_objectid = gang[ret - 1]->root_key.objectid + 1;
65d33fd7 3907
c146afad 3908 for (i = 0; i < ret; i++) {
65d33fd7
QW
3909 /* Avoid to grab roots in dead_roots */
3910 if (btrfs_root_refs(&gang[i]->root_item) == 0) {
3911 gang[i] = NULL;
3912 continue;
3913 }
3914 /* grab all the search result for later use */
3915 gang[i] = btrfs_grab_fs_root(gang[i]);
3916 }
3917 srcu_read_unlock(&fs_info->subvol_srcu, index);
66b4ffd1 3918
65d33fd7
QW
3919 for (i = 0; i < ret; i++) {
3920 if (!gang[i])
3921 continue;
c146afad 3922 root_objectid = gang[i]->root_key.objectid;
66b4ffd1
JB
3923 err = btrfs_orphan_cleanup(gang[i]);
3924 if (err)
65d33fd7
QW
3925 break;
3926 btrfs_put_fs_root(gang[i]);
c146afad
YZ
3927 }
3928 root_objectid++;
3929 }
65d33fd7
QW
3930
3931 /* release the uncleaned roots due to error */
3932 for (; i < ret; i++) {
3933 if (gang[i])
3934 btrfs_put_fs_root(gang[i]);
3935 }
3936 return err;
c146afad 3937}
a2135011 3938
6bccf3ab 3939int btrfs_commit_super(struct btrfs_fs_info *fs_info)
c146afad 3940{
6bccf3ab 3941 struct btrfs_root *root = fs_info->tree_root;
c146afad 3942 struct btrfs_trans_handle *trans;
a74a4b97 3943
0b246afa 3944 mutex_lock(&fs_info->cleaner_mutex);
2ff7e61e 3945 btrfs_run_delayed_iputs(fs_info);
0b246afa
JM
3946 mutex_unlock(&fs_info->cleaner_mutex);
3947 wake_up_process(fs_info->cleaner_kthread);
c71bf099
YZ
3948
3949 /* wait until ongoing cleanup work done */
0b246afa
JM
3950 down_write(&fs_info->cleanup_work_sem);
3951 up_write(&fs_info->cleanup_work_sem);
c71bf099 3952
7a7eaa40 3953 trans = btrfs_join_transaction(root);
3612b495
TI
3954 if (IS_ERR(trans))
3955 return PTR_ERR(trans);
3a45bb20 3956 return btrfs_commit_transaction(trans);
c146afad
YZ
3957}
3958
6bccf3ab 3959void close_ctree(struct btrfs_fs_info *fs_info)
c146afad 3960{
c146afad
YZ
3961 int ret;
3962
afcdd129 3963 set_bit(BTRFS_FS_CLOSING_START, &fs_info->flags);
c146afad 3964
7343dd61 3965 /* wait for the qgroup rescan worker to stop */
d06f23d6 3966 btrfs_qgroup_wait_for_completion(fs_info, false);
7343dd61 3967
803b2f54
SB
3968 /* wait for the uuid_scan task to finish */
3969 down(&fs_info->uuid_tree_rescan_sem);
3970 /* avoid complains from lockdep et al., set sem back to initial state */
3971 up(&fs_info->uuid_tree_rescan_sem);
3972
837d5b6e 3973 /* pause restriper - we want to resume on mount */
aa1b8cd4 3974 btrfs_pause_balance(fs_info);
837d5b6e 3975
8dabb742
SB
3976 btrfs_dev_replace_suspend_for_unmount(fs_info);
3977
aa1b8cd4 3978 btrfs_scrub_cancel(fs_info);
4cb5300b
CM
3979
3980 /* wait for any defraggers to finish */
3981 wait_event(fs_info->transaction_wait,
3982 (atomic_read(&fs_info->defrag_running) == 0));
3983
3984 /* clear out the rbtree of defraggable inodes */
26176e7c 3985 btrfs_cleanup_defrag_inodes(fs_info);
4cb5300b 3986
21c7e756
MX
3987 cancel_work_sync(&fs_info->async_reclaim_work);
3988
bc98a42c 3989 if (!sb_rdonly(fs_info->sb)) {
e44163e1
JM
3990 /*
3991 * If the cleaner thread is stopped and there are
3992 * block groups queued for removal, the deletion will be
3993 * skipped when we quit the cleaner thread.
3994 */
0b246afa 3995 btrfs_delete_unused_bgs(fs_info);
e44163e1 3996
6bccf3ab 3997 ret = btrfs_commit_super(fs_info);
acce952b 3998 if (ret)
04892340 3999 btrfs_err(fs_info, "commit super ret %d", ret);
acce952b 4000 }
4001
af722733
LB
4002 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state) ||
4003 test_bit(BTRFS_FS_STATE_TRANS_ABORTED, &fs_info->fs_state))
2ff7e61e 4004 btrfs_error_commit_super(fs_info);
0f7d52f4 4005
e3029d9f
AV
4006 kthread_stop(fs_info->transaction_kthread);
4007 kthread_stop(fs_info->cleaner_kthread);
8929ecfa 4008
afcdd129 4009 set_bit(BTRFS_FS_CLOSING_DONE, &fs_info->flags);
f25784b3 4010
04892340 4011 btrfs_free_qgroup_config(fs_info);
fe816d0f 4012 ASSERT(list_empty(&fs_info->delalloc_roots));
bcef60f2 4013
963d678b 4014 if (percpu_counter_sum(&fs_info->delalloc_bytes)) {
04892340 4015 btrfs_info(fs_info, "at unmount delalloc count %lld",
963d678b 4016 percpu_counter_sum(&fs_info->delalloc_bytes));
b0c68f8b 4017 }
bcc63abb 4018
6618a59b 4019 btrfs_sysfs_remove_mounted(fs_info);
b7c35e81 4020 btrfs_sysfs_remove_fsid(fs_info->fs_devices);
5ac1d209 4021
faa2dbf0 4022 btrfs_free_fs_roots(fs_info);
d10c5f31 4023
1a4319cc
LB
4024 btrfs_put_block_group_cache(fs_info);
4025
de348ee0
WS
4026 /*
4027 * we must make sure there is not any read request to
4028 * submit after we stopping all workers.
4029 */
4030 invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
96192499
JB
4031 btrfs_stop_all_workers(fs_info);
4032
5cdd7db6
FM
4033 btrfs_free_block_groups(fs_info);
4034
afcdd129 4035 clear_bit(BTRFS_FS_OPEN, &fs_info->flags);
13e6c37b 4036 free_root_pointers(fs_info, 1);
9ad6b7bc 4037
13e6c37b 4038 iput(fs_info->btree_inode);
d6bfde87 4039
21adbd5c 4040#ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
0b246afa 4041 if (btrfs_test_opt(fs_info, CHECK_INTEGRITY))
2ff7e61e 4042 btrfsic_unmount(fs_info->fs_devices);
21adbd5c
SB
4043#endif
4044
dfe25020 4045 btrfs_close_devices(fs_info->fs_devices);
0b86a832 4046 btrfs_mapping_tree_free(&fs_info->mapping_tree);
b248a415 4047
e2d84521 4048 percpu_counter_destroy(&fs_info->dirty_metadata_bytes);
963d678b 4049 percpu_counter_destroy(&fs_info->delalloc_bytes);
c404e0dc 4050 percpu_counter_destroy(&fs_info->bio_counter);
76dda93c 4051 cleanup_srcu_struct(&fs_info->subvol_srcu);
0b86a832 4052
53b381b3 4053 btrfs_free_stripe_hash_table(fs_info);
fd708b81 4054 btrfs_free_ref_cache(fs_info);
53b381b3 4055
04216820
FM
4056 while (!list_empty(&fs_info->pinned_chunks)) {
4057 struct extent_map *em;
4058
4059 em = list_first_entry(&fs_info->pinned_chunks,
4060 struct extent_map, list);
4061 list_del_init(&em->list);
4062 free_extent_map(em);
4063 }
eb60ceac
CM
4064}
4065
b9fab919
CM
4066int btrfs_buffer_uptodate(struct extent_buffer *buf, u64 parent_transid,
4067 int atomic)
5f39d397 4068{
1259ab75 4069 int ret;
727011e0 4070 struct inode *btree_inode = buf->pages[0]->mapping->host;
1259ab75 4071
0b32f4bb 4072 ret = extent_buffer_uptodate(buf);
1259ab75
CM
4073 if (!ret)
4074 return ret;
4075
4076 ret = verify_parent_transid(&BTRFS_I(btree_inode)->io_tree, buf,
b9fab919
CM
4077 parent_transid, atomic);
4078 if (ret == -EAGAIN)
4079 return ret;
1259ab75 4080 return !ret;
5f39d397
CM
4081}
4082
5f39d397
CM
4083void btrfs_mark_buffer_dirty(struct extent_buffer *buf)
4084{
0b246afa 4085 struct btrfs_fs_info *fs_info;
06ea65a3 4086 struct btrfs_root *root;
5f39d397 4087 u64 transid = btrfs_header_generation(buf);
b9473439 4088 int was_dirty;
b4ce94de 4089
06ea65a3
JB
4090#ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
4091 /*
4092 * This is a fast path so only do this check if we have sanity tests
4093 * enabled. Normal people shouldn't be marking dummy buffers as dirty
4094 * outside of the sanity tests.
4095 */
4096 if (unlikely(test_bit(EXTENT_BUFFER_DUMMY, &buf->bflags)))
4097 return;
4098#endif
4099 root = BTRFS_I(buf->pages[0]->mapping->host)->root;
0b246afa 4100 fs_info = root->fs_info;
b9447ef8 4101 btrfs_assert_tree_locked(buf);
0b246afa 4102 if (transid != fs_info->generation)
5d163e0e 4103 WARN(1, KERN_CRIT "btrfs transid mismatch buffer %llu, found %llu running %llu\n",
0b246afa 4104 buf->start, transid, fs_info->generation);
0b32f4bb 4105 was_dirty = set_extent_buffer_dirty(buf);
e2d84521 4106 if (!was_dirty)
104b4e51
NB
4107 percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
4108 buf->len,
4109 fs_info->dirty_metadata_batch);
1f21ef0a 4110#ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
69fc6cbb
QW
4111 /*
4112 * Since btrfs_mark_buffer_dirty() can be called with item pointer set
4113 * but item data not updated.
4114 * So here we should only check item pointers, not item data.
4115 */
4116 if (btrfs_header_level(buf) == 0 &&
2f659546 4117 btrfs_check_leaf_relaxed(fs_info, buf)) {
a4f78750 4118 btrfs_print_leaf(buf);
1f21ef0a
FM
4119 ASSERT(0);
4120 }
4121#endif
eb60ceac
CM
4122}
4123
2ff7e61e 4124static void __btrfs_btree_balance_dirty(struct btrfs_fs_info *fs_info,
b53d3f5d 4125 int flush_delayed)
16cdcec7
MX
4126{
4127 /*
4128 * looks as though older kernels can get into trouble with
4129 * this code, they end up stuck in balance_dirty_pages forever
4130 */
e2d84521 4131 int ret;
16cdcec7
MX
4132
4133 if (current->flags & PF_MEMALLOC)
4134 return;
4135
b53d3f5d 4136 if (flush_delayed)
2ff7e61e 4137 btrfs_balance_delayed_items(fs_info);
16cdcec7 4138
0b246afa 4139 ret = percpu_counter_compare(&fs_info->dirty_metadata_bytes,
e2d84521
MX
4140 BTRFS_DIRTY_METADATA_THRESH);
4141 if (ret > 0) {
0b246afa 4142 balance_dirty_pages_ratelimited(fs_info->btree_inode->i_mapping);
16cdcec7 4143 }
16cdcec7
MX
4144}
4145
2ff7e61e 4146void btrfs_btree_balance_dirty(struct btrfs_fs_info *fs_info)
35b7e476 4147{
2ff7e61e 4148 __btrfs_btree_balance_dirty(fs_info, 1);
b53d3f5d 4149}
585ad2c3 4150
2ff7e61e 4151void btrfs_btree_balance_dirty_nodelay(struct btrfs_fs_info *fs_info)
b53d3f5d 4152{
2ff7e61e 4153 __btrfs_btree_balance_dirty(fs_info, 0);
35b7e476 4154}
6b80053d 4155
581c1760
QW
4156int btrfs_read_buffer(struct extent_buffer *buf, u64 parent_transid, int level,
4157 struct btrfs_key *first_key)
6b80053d 4158{
727011e0 4159 struct btrfs_root *root = BTRFS_I(buf->pages[0]->mapping->host)->root;
2ff7e61e
JM
4160 struct btrfs_fs_info *fs_info = root->fs_info;
4161
581c1760
QW
4162 return btree_read_extent_buffer_pages(fs_info, buf, parent_transid,
4163 level, first_key);
6b80053d 4164}
0da5468f 4165
2ff7e61e 4166static void btrfs_error_commit_super(struct btrfs_fs_info *fs_info)
acce952b 4167{
fe816d0f
NB
4168 /* cleanup FS via transaction */
4169 btrfs_cleanup_transaction(fs_info);
4170
0b246afa 4171 mutex_lock(&fs_info->cleaner_mutex);
2ff7e61e 4172 btrfs_run_delayed_iputs(fs_info);
0b246afa 4173 mutex_unlock(&fs_info->cleaner_mutex);
acce952b 4174
0b246afa
JM
4175 down_write(&fs_info->cleanup_work_sem);
4176 up_write(&fs_info->cleanup_work_sem);
acce952b 4177}
4178
143bede5 4179static void btrfs_destroy_ordered_extents(struct btrfs_root *root)
acce952b 4180{
acce952b 4181 struct btrfs_ordered_extent *ordered;
acce952b 4182
199c2a9c 4183 spin_lock(&root->ordered_extent_lock);
779880ef
JB
4184 /*
4185 * This will just short circuit the ordered completion stuff which will
4186 * make sure the ordered extent gets properly cleaned up.
4187 */
199c2a9c 4188 list_for_each_entry(ordered, &root->ordered_extents,
779880ef
JB
4189 root_extent_list)
4190 set_bit(BTRFS_ORDERED_IOERR, &ordered->flags);
199c2a9c
MX
4191 spin_unlock(&root->ordered_extent_lock);
4192}
4193
4194static void btrfs_destroy_all_ordered_extents(struct btrfs_fs_info *fs_info)
4195{
4196 struct btrfs_root *root;
4197 struct list_head splice;
4198
4199 INIT_LIST_HEAD(&splice);
4200
4201 spin_lock(&fs_info->ordered_root_lock);
4202 list_splice_init(&fs_info->ordered_roots, &splice);
4203 while (!list_empty(&splice)) {
4204 root = list_first_entry(&splice, struct btrfs_root,
4205 ordered_root);
1de2cfde
JB
4206 list_move_tail(&root->ordered_root,
4207 &fs_info->ordered_roots);
199c2a9c 4208
2a85d9ca 4209 spin_unlock(&fs_info->ordered_root_lock);
199c2a9c
MX
4210 btrfs_destroy_ordered_extents(root);
4211
2a85d9ca
LB
4212 cond_resched();
4213 spin_lock(&fs_info->ordered_root_lock);
199c2a9c
MX
4214 }
4215 spin_unlock(&fs_info->ordered_root_lock);
acce952b 4216}
4217
35a3621b 4218static int btrfs_destroy_delayed_refs(struct btrfs_transaction *trans,
2ff7e61e 4219 struct btrfs_fs_info *fs_info)
acce952b 4220{
4221 struct rb_node *node;
4222 struct btrfs_delayed_ref_root *delayed_refs;
4223 struct btrfs_delayed_ref_node *ref;
4224 int ret = 0;
4225
4226 delayed_refs = &trans->delayed_refs;
4227
4228 spin_lock(&delayed_refs->lock);
d7df2c79 4229 if (atomic_read(&delayed_refs->num_entries) == 0) {
cfece4db 4230 spin_unlock(&delayed_refs->lock);
0b246afa 4231 btrfs_info(fs_info, "delayed_refs has NO entry");
acce952b 4232 return ret;
4233 }
4234
d7df2c79
JB
4235 while ((node = rb_first(&delayed_refs->href_root)) != NULL) {
4236 struct btrfs_delayed_ref_head *head;
0e0adbcf 4237 struct rb_node *n;
e78417d1 4238 bool pin_bytes = false;
acce952b 4239
d7df2c79
JB
4240 head = rb_entry(node, struct btrfs_delayed_ref_head,
4241 href_node);
4242 if (!mutex_trylock(&head->mutex)) {
d278850e 4243 refcount_inc(&head->refs);
d7df2c79 4244 spin_unlock(&delayed_refs->lock);
eb12db69 4245
d7df2c79 4246 mutex_lock(&head->mutex);
e78417d1 4247 mutex_unlock(&head->mutex);
d278850e 4248 btrfs_put_delayed_ref_head(head);
d7df2c79
JB
4249 spin_lock(&delayed_refs->lock);
4250 continue;
4251 }
4252 spin_lock(&head->lock);
0e0adbcf
JB
4253 while ((n = rb_first(&head->ref_tree)) != NULL) {
4254 ref = rb_entry(n, struct btrfs_delayed_ref_node,
4255 ref_node);
d7df2c79 4256 ref->in_tree = 0;
0e0adbcf
JB
4257 rb_erase(&ref->ref_node, &head->ref_tree);
4258 RB_CLEAR_NODE(&ref->ref_node);
1d57ee94
WX
4259 if (!list_empty(&ref->add_list))
4260 list_del(&ref->add_list);
d7df2c79
JB
4261 atomic_dec(&delayed_refs->num_entries);
4262 btrfs_put_delayed_ref(ref);
e78417d1 4263 }
d7df2c79
JB
4264 if (head->must_insert_reserved)
4265 pin_bytes = true;
4266 btrfs_free_delayed_extent_op(head->extent_op);
4267 delayed_refs->num_heads--;
4268 if (head->processing == 0)
4269 delayed_refs->num_heads_ready--;
4270 atomic_dec(&delayed_refs->num_entries);
d7df2c79 4271 rb_erase(&head->href_node, &delayed_refs->href_root);
d278850e 4272 RB_CLEAR_NODE(&head->href_node);
d7df2c79
JB
4273 spin_unlock(&head->lock);
4274 spin_unlock(&delayed_refs->lock);
4275 mutex_unlock(&head->mutex);
acce952b 4276
d7df2c79 4277 if (pin_bytes)
d278850e
JB
4278 btrfs_pin_extent(fs_info, head->bytenr,
4279 head->num_bytes, 1);
4280 btrfs_put_delayed_ref_head(head);
acce952b 4281 cond_resched();
4282 spin_lock(&delayed_refs->lock);
4283 }
4284
4285 spin_unlock(&delayed_refs->lock);
4286
4287 return ret;
4288}
4289
143bede5 4290static void btrfs_destroy_delalloc_inodes(struct btrfs_root *root)
acce952b 4291{
4292 struct btrfs_inode *btrfs_inode;
4293 struct list_head splice;
4294
4295 INIT_LIST_HEAD(&splice);
4296
eb73c1b7
MX
4297 spin_lock(&root->delalloc_lock);
4298 list_splice_init(&root->delalloc_inodes, &splice);
acce952b 4299
4300 while (!list_empty(&splice)) {
fe816d0f 4301 struct inode *inode = NULL;
eb73c1b7
MX
4302 btrfs_inode = list_first_entry(&splice, struct btrfs_inode,
4303 delalloc_inodes);
fe816d0f 4304 __btrfs_del_delalloc_inode(root, btrfs_inode);
eb73c1b7 4305 spin_unlock(&root->delalloc_lock);
acce952b 4306
fe816d0f
NB
4307 /*
4308 * Make sure we get a live inode and that it'll not disappear
4309 * meanwhile.
4310 */
4311 inode = igrab(&btrfs_inode->vfs_inode);
4312 if (inode) {
4313 invalidate_inode_pages2(inode->i_mapping);
4314 iput(inode);
4315 }
eb73c1b7 4316 spin_lock(&root->delalloc_lock);
acce952b 4317 }
eb73c1b7
MX
4318 spin_unlock(&root->delalloc_lock);
4319}
4320
4321static void btrfs_destroy_all_delalloc_inodes(struct btrfs_fs_info *fs_info)
4322{
4323 struct btrfs_root *root;
4324 struct list_head splice;
4325
4326 INIT_LIST_HEAD(&splice);
4327
4328 spin_lock(&fs_info->delalloc_root_lock);
4329 list_splice_init(&fs_info->delalloc_roots, &splice);
4330 while (!list_empty(&splice)) {
4331 root = list_first_entry(&splice, struct btrfs_root,
4332 delalloc_root);
eb73c1b7
MX
4333 root = btrfs_grab_fs_root(root);
4334 BUG_ON(!root);
4335 spin_unlock(&fs_info->delalloc_root_lock);
4336
4337 btrfs_destroy_delalloc_inodes(root);
4338 btrfs_put_fs_root(root);
4339
4340 spin_lock(&fs_info->delalloc_root_lock);
4341 }
4342 spin_unlock(&fs_info->delalloc_root_lock);
acce952b 4343}
4344
2ff7e61e 4345static int btrfs_destroy_marked_extents(struct btrfs_fs_info *fs_info,
acce952b 4346 struct extent_io_tree *dirty_pages,
4347 int mark)
4348{
4349 int ret;
acce952b 4350 struct extent_buffer *eb;
4351 u64 start = 0;
4352 u64 end;
acce952b 4353
4354 while (1) {
4355 ret = find_first_extent_bit(dirty_pages, start, &start, &end,
e6138876 4356 mark, NULL);
acce952b 4357 if (ret)
4358 break;
4359
91166212 4360 clear_extent_bits(dirty_pages, start, end, mark);
acce952b 4361 while (start <= end) {
0b246afa
JM
4362 eb = find_extent_buffer(fs_info, start);
4363 start += fs_info->nodesize;
fd8b2b61 4364 if (!eb)
acce952b 4365 continue;
fd8b2b61 4366 wait_on_extent_buffer_writeback(eb);
acce952b 4367
fd8b2b61
JB
4368 if (test_and_clear_bit(EXTENT_BUFFER_DIRTY,
4369 &eb->bflags))
4370 clear_extent_buffer_dirty(eb);
4371 free_extent_buffer_stale(eb);
acce952b 4372 }
4373 }
4374
4375 return ret;
4376}
4377
2ff7e61e 4378static int btrfs_destroy_pinned_extent(struct btrfs_fs_info *fs_info,
acce952b 4379 struct extent_io_tree *pinned_extents)
4380{
4381 struct extent_io_tree *unpin;
4382 u64 start;
4383 u64 end;
4384 int ret;
ed0eaa14 4385 bool loop = true;
acce952b 4386
4387 unpin = pinned_extents;
ed0eaa14 4388again:
acce952b 4389 while (1) {
4390 ret = find_first_extent_bit(unpin, 0, &start, &end,
e6138876 4391 EXTENT_DIRTY, NULL);
acce952b 4392 if (ret)
4393 break;
4394
af6f8f60 4395 clear_extent_dirty(unpin, start, end);
2ff7e61e 4396 btrfs_error_unpin_extent_range(fs_info, start, end);
acce952b 4397 cond_resched();
4398 }
4399
ed0eaa14 4400 if (loop) {
0b246afa
JM
4401 if (unpin == &fs_info->freed_extents[0])
4402 unpin = &fs_info->freed_extents[1];
ed0eaa14 4403 else
0b246afa 4404 unpin = &fs_info->freed_extents[0];
ed0eaa14
LB
4405 loop = false;
4406 goto again;
4407 }
4408
acce952b 4409 return 0;
4410}
4411
c79a1751
LB
4412static void btrfs_cleanup_bg_io(struct btrfs_block_group_cache *cache)
4413{
4414 struct inode *inode;
4415
4416 inode = cache->io_ctl.inode;
4417 if (inode) {
4418 invalidate_inode_pages2(inode->i_mapping);
4419 BTRFS_I(inode)->generation = 0;
4420 cache->io_ctl.inode = NULL;
4421 iput(inode);
4422 }
4423 btrfs_put_block_group(cache);
4424}
4425
4426void btrfs_cleanup_dirty_bgs(struct btrfs_transaction *cur_trans,
2ff7e61e 4427 struct btrfs_fs_info *fs_info)
c79a1751
LB
4428{
4429 struct btrfs_block_group_cache *cache;
4430
4431 spin_lock(&cur_trans->dirty_bgs_lock);
4432 while (!list_empty(&cur_trans->dirty_bgs)) {
4433 cache = list_first_entry(&cur_trans->dirty_bgs,
4434 struct btrfs_block_group_cache,
4435 dirty_list);
c79a1751
LB
4436
4437 if (!list_empty(&cache->io_list)) {
4438 spin_unlock(&cur_trans->dirty_bgs_lock);
4439 list_del_init(&cache->io_list);
4440 btrfs_cleanup_bg_io(cache);
4441 spin_lock(&cur_trans->dirty_bgs_lock);
4442 }
4443
4444 list_del_init(&cache->dirty_list);
4445 spin_lock(&cache->lock);
4446 cache->disk_cache_state = BTRFS_DC_ERROR;
4447 spin_unlock(&cache->lock);
4448
4449 spin_unlock(&cur_trans->dirty_bgs_lock);
4450 btrfs_put_block_group(cache);
4451 spin_lock(&cur_trans->dirty_bgs_lock);
4452 }
4453 spin_unlock(&cur_trans->dirty_bgs_lock);
4454
45ae2c18
NB
4455 /*
4456 * Refer to the definition of io_bgs member for details why it's safe
4457 * to use it without any locking
4458 */
c79a1751
LB
4459 while (!list_empty(&cur_trans->io_bgs)) {
4460 cache = list_first_entry(&cur_trans->io_bgs,
4461 struct btrfs_block_group_cache,
4462 io_list);
c79a1751
LB
4463
4464 list_del_init(&cache->io_list);
4465 spin_lock(&cache->lock);
4466 cache->disk_cache_state = BTRFS_DC_ERROR;
4467 spin_unlock(&cache->lock);
4468 btrfs_cleanup_bg_io(cache);
4469 }
4470}
4471
49b25e05 4472void btrfs_cleanup_one_transaction(struct btrfs_transaction *cur_trans,
2ff7e61e 4473 struct btrfs_fs_info *fs_info)
49b25e05 4474{
2ff7e61e 4475 btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
c79a1751
LB
4476 ASSERT(list_empty(&cur_trans->dirty_bgs));
4477 ASSERT(list_empty(&cur_trans->io_bgs));
4478
2ff7e61e 4479 btrfs_destroy_delayed_refs(cur_trans, fs_info);
49b25e05 4480
4a9d8bde 4481 cur_trans->state = TRANS_STATE_COMMIT_START;
0b246afa 4482 wake_up(&fs_info->transaction_blocked_wait);
49b25e05 4483
4a9d8bde 4484 cur_trans->state = TRANS_STATE_UNBLOCKED;
0b246afa 4485 wake_up(&fs_info->transaction_wait);
49b25e05 4486
ccdf9b30
JM
4487 btrfs_destroy_delayed_inodes(fs_info);
4488 btrfs_assert_delayed_root_empty(fs_info);
49b25e05 4489
2ff7e61e 4490 btrfs_destroy_marked_extents(fs_info, &cur_trans->dirty_pages,
49b25e05 4491 EXTENT_DIRTY);
2ff7e61e 4492 btrfs_destroy_pinned_extent(fs_info,
0b246afa 4493 fs_info->pinned_extents);
49b25e05 4494
4a9d8bde
MX
4495 cur_trans->state =TRANS_STATE_COMPLETED;
4496 wake_up(&cur_trans->commit_wait);
49b25e05
JM
4497}
4498
2ff7e61e 4499static int btrfs_cleanup_transaction(struct btrfs_fs_info *fs_info)
acce952b 4500{
4501 struct btrfs_transaction *t;
acce952b 4502
0b246afa 4503 mutex_lock(&fs_info->transaction_kthread_mutex);
acce952b 4504
0b246afa
JM
4505 spin_lock(&fs_info->trans_lock);
4506 while (!list_empty(&fs_info->trans_list)) {
4507 t = list_first_entry(&fs_info->trans_list,
724e2315
JB
4508 struct btrfs_transaction, list);
4509 if (t->state >= TRANS_STATE_COMMIT_START) {
9b64f57d 4510 refcount_inc(&t->use_count);
0b246afa 4511 spin_unlock(&fs_info->trans_lock);
2ff7e61e 4512 btrfs_wait_for_commit(fs_info, t->transid);
724e2315 4513 btrfs_put_transaction(t);
0b246afa 4514 spin_lock(&fs_info->trans_lock);
724e2315
JB
4515 continue;
4516 }
0b246afa 4517 if (t == fs_info->running_transaction) {
724e2315 4518 t->state = TRANS_STATE_COMMIT_DOING;
0b246afa 4519 spin_unlock(&fs_info->trans_lock);
724e2315
JB
4520 /*
4521 * We wait for 0 num_writers since we don't hold a trans
4522 * handle open currently for this transaction.
4523 */
4524 wait_event(t->writer_wait,
4525 atomic_read(&t->num_writers) == 0);
4526 } else {
0b246afa 4527 spin_unlock(&fs_info->trans_lock);
724e2315 4528 }
2ff7e61e 4529 btrfs_cleanup_one_transaction(t, fs_info);
4a9d8bde 4530
0b246afa
JM
4531 spin_lock(&fs_info->trans_lock);
4532 if (t == fs_info->running_transaction)
4533 fs_info->running_transaction = NULL;
acce952b 4534 list_del_init(&t->list);
0b246afa 4535 spin_unlock(&fs_info->trans_lock);
acce952b 4536
724e2315 4537 btrfs_put_transaction(t);
2ff7e61e 4538 trace_btrfs_transaction_commit(fs_info->tree_root);
0b246afa 4539 spin_lock(&fs_info->trans_lock);
724e2315 4540 }
0b246afa
JM
4541 spin_unlock(&fs_info->trans_lock);
4542 btrfs_destroy_all_ordered_extents(fs_info);
ccdf9b30
JM
4543 btrfs_destroy_delayed_inodes(fs_info);
4544 btrfs_assert_delayed_root_empty(fs_info);
2ff7e61e 4545 btrfs_destroy_pinned_extent(fs_info, fs_info->pinned_extents);
0b246afa
JM
4546 btrfs_destroy_all_delalloc_inodes(fs_info);
4547 mutex_unlock(&fs_info->transaction_kthread_mutex);
acce952b 4548
4549 return 0;
4550}
4551
c6100a4b
JB
4552static struct btrfs_fs_info *btree_fs_info(void *private_data)
4553{
4554 struct inode *inode = private_data;
4555 return btrfs_sb(inode->i_sb);
4556}
4557
e8c9f186 4558static const struct extent_io_ops btree_extent_io_ops = {
4d53dddb 4559 /* mandatory callbacks */
0b86a832 4560 .submit_bio_hook = btree_submit_bio_hook,
4d53dddb 4561 .readpage_end_io_hook = btree_readpage_end_io_hook,
239b14b3
CM
4562 /* note we're sharing with inode.c for the merge bio hook */
4563 .merge_bio_hook = btrfs_merge_bio_hook,
20a7db8a 4564 .readpage_io_failed_hook = btree_io_failed_hook,
c6100a4b
JB
4565 .set_range_writeback = btrfs_set_range_writeback,
4566 .tree_fs_info = btree_fs_info,
4d53dddb
DS
4567
4568 /* optional callbacks */
0da5468f 4569};