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