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