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