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