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