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