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