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