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