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