1 // SPDX-License-Identifier: GPL-2.0 2 3 #include <linux/list_sort.h> 4 #include "misc.h" 5 #include "ctree.h" 6 #include "block-group.h" 7 #include "space-info.h" 8 #include "disk-io.h" 9 #include "free-space-cache.h" 10 #include "free-space-tree.h" 11 #include "volumes.h" 12 #include "transaction.h" 13 #include "ref-verify.h" 14 #include "sysfs.h" 15 #include "tree-log.h" 16 #include "delalloc-space.h" 17 #include "discard.h" 18 #include "raid56.h" 19 #include "zoned.h" 20 21 /* 22 * Return target flags in extended format or 0 if restripe for this chunk_type 23 * is not in progress 24 * 25 * Should be called with balance_lock held 26 */ 27 static u64 get_restripe_target(struct btrfs_fs_info *fs_info, u64 flags) 28 { 29 struct btrfs_balance_control *bctl = fs_info->balance_ctl; 30 u64 target = 0; 31 32 if (!bctl) 33 return 0; 34 35 if (flags & BTRFS_BLOCK_GROUP_DATA && 36 bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) { 37 target = BTRFS_BLOCK_GROUP_DATA | bctl->data.target; 38 } else if (flags & BTRFS_BLOCK_GROUP_SYSTEM && 39 bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) { 40 target = BTRFS_BLOCK_GROUP_SYSTEM | bctl->sys.target; 41 } else if (flags & BTRFS_BLOCK_GROUP_METADATA && 42 bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) { 43 target = BTRFS_BLOCK_GROUP_METADATA | bctl->meta.target; 44 } 45 46 return target; 47 } 48 49 /* 50 * @flags: available profiles in extended format (see ctree.h) 51 * 52 * Return reduced profile in chunk format. If profile changing is in progress 53 * (either running or paused) picks the target profile (if it's already 54 * available), otherwise falls back to plain reducing. 55 */ 56 static u64 btrfs_reduce_alloc_profile(struct btrfs_fs_info *fs_info, u64 flags) 57 { 58 u64 num_devices = fs_info->fs_devices->rw_devices; 59 u64 target; 60 u64 raid_type; 61 u64 allowed = 0; 62 63 /* 64 * See if restripe for this chunk_type is in progress, if so try to 65 * reduce to the target profile 66 */ 67 spin_lock(&fs_info->balance_lock); 68 target = get_restripe_target(fs_info, flags); 69 if (target) { 70 spin_unlock(&fs_info->balance_lock); 71 return extended_to_chunk(target); 72 } 73 spin_unlock(&fs_info->balance_lock); 74 75 /* First, mask out the RAID levels which aren't possible */ 76 for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) { 77 if (num_devices >= btrfs_raid_array[raid_type].devs_min) 78 allowed |= btrfs_raid_array[raid_type].bg_flag; 79 } 80 allowed &= flags; 81 82 if (allowed & BTRFS_BLOCK_GROUP_RAID6) 83 allowed = BTRFS_BLOCK_GROUP_RAID6; 84 else if (allowed & BTRFS_BLOCK_GROUP_RAID5) 85 allowed = BTRFS_BLOCK_GROUP_RAID5; 86 else if (allowed & BTRFS_BLOCK_GROUP_RAID10) 87 allowed = BTRFS_BLOCK_GROUP_RAID10; 88 else if (allowed & BTRFS_BLOCK_GROUP_RAID1) 89 allowed = BTRFS_BLOCK_GROUP_RAID1; 90 else if (allowed & BTRFS_BLOCK_GROUP_RAID0) 91 allowed = BTRFS_BLOCK_GROUP_RAID0; 92 93 flags &= ~BTRFS_BLOCK_GROUP_PROFILE_MASK; 94 95 return extended_to_chunk(flags | allowed); 96 } 97 98 u64 btrfs_get_alloc_profile(struct btrfs_fs_info *fs_info, u64 orig_flags) 99 { 100 unsigned seq; 101 u64 flags; 102 103 do { 104 flags = orig_flags; 105 seq = read_seqbegin(&fs_info->profiles_lock); 106 107 if (flags & BTRFS_BLOCK_GROUP_DATA) 108 flags |= fs_info->avail_data_alloc_bits; 109 else if (flags & BTRFS_BLOCK_GROUP_SYSTEM) 110 flags |= fs_info->avail_system_alloc_bits; 111 else if (flags & BTRFS_BLOCK_GROUP_METADATA) 112 flags |= fs_info->avail_metadata_alloc_bits; 113 } while (read_seqretry(&fs_info->profiles_lock, seq)); 114 115 return btrfs_reduce_alloc_profile(fs_info, flags); 116 } 117 118 void btrfs_get_block_group(struct btrfs_block_group *cache) 119 { 120 refcount_inc(&cache->refs); 121 } 122 123 void btrfs_put_block_group(struct btrfs_block_group *cache) 124 { 125 if (refcount_dec_and_test(&cache->refs)) { 126 WARN_ON(cache->pinned > 0); 127 WARN_ON(cache->reserved > 0); 128 129 /* 130 * A block_group shouldn't be on the discard_list anymore. 131 * Remove the block_group from the discard_list to prevent us 132 * from causing a panic due to NULL pointer dereference. 133 */ 134 if (WARN_ON(!list_empty(&cache->discard_list))) 135 btrfs_discard_cancel_work(&cache->fs_info->discard_ctl, 136 cache); 137 138 /* 139 * If not empty, someone is still holding mutex of 140 * full_stripe_lock, which can only be released by caller. 141 * And it will definitely cause use-after-free when caller 142 * tries to release full stripe lock. 143 * 144 * No better way to resolve, but only to warn. 145 */ 146 WARN_ON(!RB_EMPTY_ROOT(&cache->full_stripe_locks_root.root)); 147 kfree(cache->free_space_ctl); 148 kfree(cache->physical_map); 149 kfree(cache); 150 } 151 } 152 153 /* 154 * This adds the block group to the fs_info rb tree for the block group cache 155 */ 156 static int btrfs_add_block_group_cache(struct btrfs_fs_info *info, 157 struct btrfs_block_group *block_group) 158 { 159 struct rb_node **p; 160 struct rb_node *parent = NULL; 161 struct btrfs_block_group *cache; 162 163 ASSERT(block_group->length != 0); 164 165 spin_lock(&info->block_group_cache_lock); 166 p = &info->block_group_cache_tree.rb_node; 167 168 while (*p) { 169 parent = *p; 170 cache = rb_entry(parent, struct btrfs_block_group, cache_node); 171 if (block_group->start < cache->start) { 172 p = &(*p)->rb_left; 173 } else if (block_group->start > cache->start) { 174 p = &(*p)->rb_right; 175 } else { 176 spin_unlock(&info->block_group_cache_lock); 177 return -EEXIST; 178 } 179 } 180 181 rb_link_node(&block_group->cache_node, parent, p); 182 rb_insert_color(&block_group->cache_node, 183 &info->block_group_cache_tree); 184 185 if (info->first_logical_byte > block_group->start) 186 info->first_logical_byte = block_group->start; 187 188 spin_unlock(&info->block_group_cache_lock); 189 190 return 0; 191 } 192 193 /* 194 * This will return the block group at or after bytenr if contains is 0, else 195 * it will return the block group that contains the bytenr 196 */ 197 static struct btrfs_block_group *block_group_cache_tree_search( 198 struct btrfs_fs_info *info, u64 bytenr, int contains) 199 { 200 struct btrfs_block_group *cache, *ret = NULL; 201 struct rb_node *n; 202 u64 end, start; 203 204 spin_lock(&info->block_group_cache_lock); 205 n = info->block_group_cache_tree.rb_node; 206 207 while (n) { 208 cache = rb_entry(n, struct btrfs_block_group, cache_node); 209 end = cache->start + cache->length - 1; 210 start = cache->start; 211 212 if (bytenr < start) { 213 if (!contains && (!ret || start < ret->start)) 214 ret = cache; 215 n = n->rb_left; 216 } else if (bytenr > start) { 217 if (contains && bytenr <= end) { 218 ret = cache; 219 break; 220 } 221 n = n->rb_right; 222 } else { 223 ret = cache; 224 break; 225 } 226 } 227 if (ret) { 228 btrfs_get_block_group(ret); 229 if (bytenr == 0 && info->first_logical_byte > ret->start) 230 info->first_logical_byte = ret->start; 231 } 232 spin_unlock(&info->block_group_cache_lock); 233 234 return ret; 235 } 236 237 /* 238 * Return the block group that starts at or after bytenr 239 */ 240 struct btrfs_block_group *btrfs_lookup_first_block_group( 241 struct btrfs_fs_info *info, u64 bytenr) 242 { 243 return block_group_cache_tree_search(info, bytenr, 0); 244 } 245 246 /* 247 * Return the block group that contains the given bytenr 248 */ 249 struct btrfs_block_group *btrfs_lookup_block_group( 250 struct btrfs_fs_info *info, u64 bytenr) 251 { 252 return block_group_cache_tree_search(info, bytenr, 1); 253 } 254 255 struct btrfs_block_group *btrfs_next_block_group( 256 struct btrfs_block_group *cache) 257 { 258 struct btrfs_fs_info *fs_info = cache->fs_info; 259 struct rb_node *node; 260 261 spin_lock(&fs_info->block_group_cache_lock); 262 263 /* If our block group was removed, we need a full search. */ 264 if (RB_EMPTY_NODE(&cache->cache_node)) { 265 const u64 next_bytenr = cache->start + cache->length; 266 267 spin_unlock(&fs_info->block_group_cache_lock); 268 btrfs_put_block_group(cache); 269 cache = btrfs_lookup_first_block_group(fs_info, next_bytenr); return cache; 270 } 271 node = rb_next(&cache->cache_node); 272 btrfs_put_block_group(cache); 273 if (node) { 274 cache = rb_entry(node, struct btrfs_block_group, cache_node); 275 btrfs_get_block_group(cache); 276 } else 277 cache = NULL; 278 spin_unlock(&fs_info->block_group_cache_lock); 279 return cache; 280 } 281 282 bool btrfs_inc_nocow_writers(struct btrfs_fs_info *fs_info, u64 bytenr) 283 { 284 struct btrfs_block_group *bg; 285 bool ret = true; 286 287 bg = btrfs_lookup_block_group(fs_info, bytenr); 288 if (!bg) 289 return false; 290 291 spin_lock(&bg->lock); 292 if (bg->ro) 293 ret = false; 294 else 295 atomic_inc(&bg->nocow_writers); 296 spin_unlock(&bg->lock); 297 298 /* No put on block group, done by btrfs_dec_nocow_writers */ 299 if (!ret) 300 btrfs_put_block_group(bg); 301 302 return ret; 303 } 304 305 void btrfs_dec_nocow_writers(struct btrfs_fs_info *fs_info, u64 bytenr) 306 { 307 struct btrfs_block_group *bg; 308 309 bg = btrfs_lookup_block_group(fs_info, bytenr); 310 ASSERT(bg); 311 if (atomic_dec_and_test(&bg->nocow_writers)) 312 wake_up_var(&bg->nocow_writers); 313 /* 314 * Once for our lookup and once for the lookup done by a previous call 315 * to btrfs_inc_nocow_writers() 316 */ 317 btrfs_put_block_group(bg); 318 btrfs_put_block_group(bg); 319 } 320 321 void btrfs_wait_nocow_writers(struct btrfs_block_group *bg) 322 { 323 wait_var_event(&bg->nocow_writers, !atomic_read(&bg->nocow_writers)); 324 } 325 326 void btrfs_dec_block_group_reservations(struct btrfs_fs_info *fs_info, 327 const u64 start) 328 { 329 struct btrfs_block_group *bg; 330 331 bg = btrfs_lookup_block_group(fs_info, start); 332 ASSERT(bg); 333 if (atomic_dec_and_test(&bg->reservations)) 334 wake_up_var(&bg->reservations); 335 btrfs_put_block_group(bg); 336 } 337 338 void btrfs_wait_block_group_reservations(struct btrfs_block_group *bg) 339 { 340 struct btrfs_space_info *space_info = bg->space_info; 341 342 ASSERT(bg->ro); 343 344 if (!(bg->flags & BTRFS_BLOCK_GROUP_DATA)) 345 return; 346 347 /* 348 * Our block group is read only but before we set it to read only, 349 * some task might have had allocated an extent from it already, but it 350 * has not yet created a respective ordered extent (and added it to a 351 * root's list of ordered extents). 352 * Therefore wait for any task currently allocating extents, since the 353 * block group's reservations counter is incremented while a read lock 354 * on the groups' semaphore is held and decremented after releasing 355 * the read access on that semaphore and creating the ordered extent. 356 */ 357 down_write(&space_info->groups_sem); 358 up_write(&space_info->groups_sem); 359 360 wait_var_event(&bg->reservations, !atomic_read(&bg->reservations)); 361 } 362 363 struct btrfs_caching_control *btrfs_get_caching_control( 364 struct btrfs_block_group *cache) 365 { 366 struct btrfs_caching_control *ctl; 367 368 spin_lock(&cache->lock); 369 if (!cache->caching_ctl) { 370 spin_unlock(&cache->lock); 371 return NULL; 372 } 373 374 ctl = cache->caching_ctl; 375 refcount_inc(&ctl->count); 376 spin_unlock(&cache->lock); 377 return ctl; 378 } 379 380 void btrfs_put_caching_control(struct btrfs_caching_control *ctl) 381 { 382 if (refcount_dec_and_test(&ctl->count)) 383 kfree(ctl); 384 } 385 386 /* 387 * When we wait for progress in the block group caching, its because our 388 * allocation attempt failed at least once. So, we must sleep and let some 389 * progress happen before we try again. 390 * 391 * This function will sleep at least once waiting for new free space to show 392 * up, and then it will check the block group free space numbers for our min 393 * num_bytes. Another option is to have it go ahead and look in the rbtree for 394 * a free extent of a given size, but this is a good start. 395 * 396 * Callers of this must check if cache->cached == BTRFS_CACHE_ERROR before using 397 * any of the information in this block group. 398 */ 399 void btrfs_wait_block_group_cache_progress(struct btrfs_block_group *cache, 400 u64 num_bytes) 401 { 402 struct btrfs_caching_control *caching_ctl; 403 404 caching_ctl = btrfs_get_caching_control(cache); 405 if (!caching_ctl) 406 return; 407 408 wait_event(caching_ctl->wait, btrfs_block_group_done(cache) || 409 (cache->free_space_ctl->free_space >= num_bytes)); 410 411 btrfs_put_caching_control(caching_ctl); 412 } 413 414 int btrfs_wait_block_group_cache_done(struct btrfs_block_group *cache) 415 { 416 struct btrfs_caching_control *caching_ctl; 417 int ret = 0; 418 419 caching_ctl = btrfs_get_caching_control(cache); 420 if (!caching_ctl) 421 return (cache->cached == BTRFS_CACHE_ERROR) ? -EIO : 0; 422 423 wait_event(caching_ctl->wait, btrfs_block_group_done(cache)); 424 if (cache->cached == BTRFS_CACHE_ERROR) 425 ret = -EIO; 426 btrfs_put_caching_control(caching_ctl); 427 return ret; 428 } 429 430 static bool space_cache_v1_done(struct btrfs_block_group *cache) 431 { 432 bool ret; 433 434 spin_lock(&cache->lock); 435 ret = cache->cached != BTRFS_CACHE_FAST; 436 spin_unlock(&cache->lock); 437 438 return ret; 439 } 440 441 void btrfs_wait_space_cache_v1_finished(struct btrfs_block_group *cache, 442 struct btrfs_caching_control *caching_ctl) 443 { 444 wait_event(caching_ctl->wait, space_cache_v1_done(cache)); 445 } 446 447 #ifdef CONFIG_BTRFS_DEBUG 448 static void fragment_free_space(struct btrfs_block_group *block_group) 449 { 450 struct btrfs_fs_info *fs_info = block_group->fs_info; 451 u64 start = block_group->start; 452 u64 len = block_group->length; 453 u64 chunk = block_group->flags & BTRFS_BLOCK_GROUP_METADATA ? 454 fs_info->nodesize : fs_info->sectorsize; 455 u64 step = chunk << 1; 456 457 while (len > chunk) { 458 btrfs_remove_free_space(block_group, start, chunk); 459 start += step; 460 if (len < step) 461 len = 0; 462 else 463 len -= step; 464 } 465 } 466 #endif 467 468 /* 469 * This is only called by btrfs_cache_block_group, since we could have freed 470 * extents we need to check the pinned_extents for any extents that can't be 471 * used yet since their free space will be released as soon as the transaction 472 * commits. 473 */ 474 u64 add_new_free_space(struct btrfs_block_group *block_group, u64 start, u64 end) 475 { 476 struct btrfs_fs_info *info = block_group->fs_info; 477 u64 extent_start, extent_end, size, total_added = 0; 478 int ret; 479 480 while (start < end) { 481 ret = find_first_extent_bit(&info->excluded_extents, start, 482 &extent_start, &extent_end, 483 EXTENT_DIRTY | EXTENT_UPTODATE, 484 NULL); 485 if (ret) 486 break; 487 488 if (extent_start <= start) { 489 start = extent_end + 1; 490 } else if (extent_start > start && extent_start < end) { 491 size = extent_start - start; 492 total_added += size; 493 ret = btrfs_add_free_space_async_trimmed(block_group, 494 start, size); 495 BUG_ON(ret); /* -ENOMEM or logic error */ 496 start = extent_end + 1; 497 } else { 498 break; 499 } 500 } 501 502 if (start < end) { 503 size = end - start; 504 total_added += size; 505 ret = btrfs_add_free_space_async_trimmed(block_group, start, 506 size); 507 BUG_ON(ret); /* -ENOMEM or logic error */ 508 } 509 510 return total_added; 511 } 512 513 static int load_extent_tree_free(struct btrfs_caching_control *caching_ctl) 514 { 515 struct btrfs_block_group *block_group = caching_ctl->block_group; 516 struct btrfs_fs_info *fs_info = block_group->fs_info; 517 struct btrfs_root *extent_root = fs_info->extent_root; 518 struct btrfs_path *path; 519 struct extent_buffer *leaf; 520 struct btrfs_key key; 521 u64 total_found = 0; 522 u64 last = 0; 523 u32 nritems; 524 int ret; 525 bool wakeup = true; 526 527 path = btrfs_alloc_path(); 528 if (!path) 529 return -ENOMEM; 530 531 last = max_t(u64, block_group->start, BTRFS_SUPER_INFO_OFFSET); 532 533 #ifdef CONFIG_BTRFS_DEBUG 534 /* 535 * If we're fragmenting we don't want to make anybody think we can 536 * allocate from this block group until we've had a chance to fragment 537 * the free space. 538 */ 539 if (btrfs_should_fragment_free_space(block_group)) 540 wakeup = false; 541 #endif 542 /* 543 * We don't want to deadlock with somebody trying to allocate a new 544 * extent for the extent root while also trying to search the extent 545 * root to add free space. So we skip locking and search the commit 546 * root, since its read-only 547 */ 548 path->skip_locking = 1; 549 path->search_commit_root = 1; 550 path->reada = READA_FORWARD; 551 552 key.objectid = last; 553 key.offset = 0; 554 key.type = BTRFS_EXTENT_ITEM_KEY; 555 556 next: 557 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0); 558 if (ret < 0) 559 goto out; 560 561 leaf = path->nodes[0]; 562 nritems = btrfs_header_nritems(leaf); 563 564 while (1) { 565 if (btrfs_fs_closing(fs_info) > 1) { 566 last = (u64)-1; 567 break; 568 } 569 570 if (path->slots[0] < nritems) { 571 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]); 572 } else { 573 ret = btrfs_find_next_key(extent_root, path, &key, 0, 0); 574 if (ret) 575 break; 576 577 if (need_resched() || 578 rwsem_is_contended(&fs_info->commit_root_sem)) { 579 if (wakeup) 580 caching_ctl->progress = last; 581 btrfs_release_path(path); 582 up_read(&fs_info->commit_root_sem); 583 mutex_unlock(&caching_ctl->mutex); 584 cond_resched(); 585 mutex_lock(&caching_ctl->mutex); 586 down_read(&fs_info->commit_root_sem); 587 goto next; 588 } 589 590 ret = btrfs_next_leaf(extent_root, path); 591 if (ret < 0) 592 goto out; 593 if (ret) 594 break; 595 leaf = path->nodes[0]; 596 nritems = btrfs_header_nritems(leaf); 597 continue; 598 } 599 600 if (key.objectid < last) { 601 key.objectid = last; 602 key.offset = 0; 603 key.type = BTRFS_EXTENT_ITEM_KEY; 604 605 if (wakeup) 606 caching_ctl->progress = last; 607 btrfs_release_path(path); 608 goto next; 609 } 610 611 if (key.objectid < block_group->start) { 612 path->slots[0]++; 613 continue; 614 } 615 616 if (key.objectid >= block_group->start + block_group->length) 617 break; 618 619 if (key.type == BTRFS_EXTENT_ITEM_KEY || 620 key.type == BTRFS_METADATA_ITEM_KEY) { 621 total_found += add_new_free_space(block_group, last, 622 key.objectid); 623 if (key.type == BTRFS_METADATA_ITEM_KEY) 624 last = key.objectid + 625 fs_info->nodesize; 626 else 627 last = key.objectid + key.offset; 628 629 if (total_found > CACHING_CTL_WAKE_UP) { 630 total_found = 0; 631 if (wakeup) 632 wake_up(&caching_ctl->wait); 633 } 634 } 635 path->slots[0]++; 636 } 637 ret = 0; 638 639 total_found += add_new_free_space(block_group, last, 640 block_group->start + block_group->length); 641 caching_ctl->progress = (u64)-1; 642 643 out: 644 btrfs_free_path(path); 645 return ret; 646 } 647 648 static noinline void caching_thread(struct btrfs_work *work) 649 { 650 struct btrfs_block_group *block_group; 651 struct btrfs_fs_info *fs_info; 652 struct btrfs_caching_control *caching_ctl; 653 int ret; 654 655 caching_ctl = container_of(work, struct btrfs_caching_control, work); 656 block_group = caching_ctl->block_group; 657 fs_info = block_group->fs_info; 658 659 mutex_lock(&caching_ctl->mutex); 660 down_read(&fs_info->commit_root_sem); 661 662 if (btrfs_test_opt(fs_info, SPACE_CACHE)) { 663 ret = load_free_space_cache(block_group); 664 if (ret == 1) { 665 ret = 0; 666 goto done; 667 } 668 669 /* 670 * We failed to load the space cache, set ourselves to 671 * CACHE_STARTED and carry on. 672 */ 673 spin_lock(&block_group->lock); 674 block_group->cached = BTRFS_CACHE_STARTED; 675 spin_unlock(&block_group->lock); 676 wake_up(&caching_ctl->wait); 677 } 678 679 /* 680 * If we are in the transaction that populated the free space tree we 681 * can't actually cache from the free space tree as our commit root and 682 * real root are the same, so we could change the contents of the blocks 683 * while caching. Instead do the slow caching in this case, and after 684 * the transaction has committed we will be safe. 685 */ 686 if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE) && 687 !(test_bit(BTRFS_FS_FREE_SPACE_TREE_UNTRUSTED, &fs_info->flags))) 688 ret = load_free_space_tree(caching_ctl); 689 else 690 ret = load_extent_tree_free(caching_ctl); 691 done: 692 spin_lock(&block_group->lock); 693 block_group->caching_ctl = NULL; 694 block_group->cached = ret ? BTRFS_CACHE_ERROR : BTRFS_CACHE_FINISHED; 695 spin_unlock(&block_group->lock); 696 697 #ifdef CONFIG_BTRFS_DEBUG 698 if (btrfs_should_fragment_free_space(block_group)) { 699 u64 bytes_used; 700 701 spin_lock(&block_group->space_info->lock); 702 spin_lock(&block_group->lock); 703 bytes_used = block_group->length - block_group->used; 704 block_group->space_info->bytes_used += bytes_used >> 1; 705 spin_unlock(&block_group->lock); 706 spin_unlock(&block_group->space_info->lock); 707 fragment_free_space(block_group); 708 } 709 #endif 710 711 caching_ctl->progress = (u64)-1; 712 713 up_read(&fs_info->commit_root_sem); 714 btrfs_free_excluded_extents(block_group); 715 mutex_unlock(&caching_ctl->mutex); 716 717 wake_up(&caching_ctl->wait); 718 719 btrfs_put_caching_control(caching_ctl); 720 btrfs_put_block_group(block_group); 721 } 722 723 int btrfs_cache_block_group(struct btrfs_block_group *cache, int load_cache_only) 724 { 725 DEFINE_WAIT(wait); 726 struct btrfs_fs_info *fs_info = cache->fs_info; 727 struct btrfs_caching_control *caching_ctl = NULL; 728 int ret = 0; 729 730 /* Allocator for zoned filesystems does not use the cache at all */ 731 if (btrfs_is_zoned(fs_info)) 732 return 0; 733 734 caching_ctl = kzalloc(sizeof(*caching_ctl), GFP_NOFS); 735 if (!caching_ctl) 736 return -ENOMEM; 737 738 INIT_LIST_HEAD(&caching_ctl->list); 739 mutex_init(&caching_ctl->mutex); 740 init_waitqueue_head(&caching_ctl->wait); 741 caching_ctl->block_group = cache; 742 caching_ctl->progress = cache->start; 743 refcount_set(&caching_ctl->count, 2); 744 btrfs_init_work(&caching_ctl->work, caching_thread, NULL, NULL); 745 746 spin_lock(&cache->lock); 747 if (cache->cached != BTRFS_CACHE_NO) { 748 kfree(caching_ctl); 749 750 caching_ctl = cache->caching_ctl; 751 if (caching_ctl) 752 refcount_inc(&caching_ctl->count); 753 spin_unlock(&cache->lock); 754 goto out; 755 } 756 WARN_ON(cache->caching_ctl); 757 cache->caching_ctl = caching_ctl; 758 if (btrfs_test_opt(fs_info, SPACE_CACHE)) 759 cache->cached = BTRFS_CACHE_FAST; 760 else 761 cache->cached = BTRFS_CACHE_STARTED; 762 cache->has_caching_ctl = 1; 763 spin_unlock(&cache->lock); 764 765 spin_lock(&fs_info->block_group_cache_lock); 766 refcount_inc(&caching_ctl->count); 767 list_add_tail(&caching_ctl->list, &fs_info->caching_block_groups); 768 spin_unlock(&fs_info->block_group_cache_lock); 769 770 btrfs_get_block_group(cache); 771 772 btrfs_queue_work(fs_info->caching_workers, &caching_ctl->work); 773 out: 774 if (load_cache_only && caching_ctl) 775 btrfs_wait_space_cache_v1_finished(cache, caching_ctl); 776 if (caching_ctl) 777 btrfs_put_caching_control(caching_ctl); 778 779 return ret; 780 } 781 782 static void clear_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags) 783 { 784 u64 extra_flags = chunk_to_extended(flags) & 785 BTRFS_EXTENDED_PROFILE_MASK; 786 787 write_seqlock(&fs_info->profiles_lock); 788 if (flags & BTRFS_BLOCK_GROUP_DATA) 789 fs_info->avail_data_alloc_bits &= ~extra_flags; 790 if (flags & BTRFS_BLOCK_GROUP_METADATA) 791 fs_info->avail_metadata_alloc_bits &= ~extra_flags; 792 if (flags & BTRFS_BLOCK_GROUP_SYSTEM) 793 fs_info->avail_system_alloc_bits &= ~extra_flags; 794 write_sequnlock(&fs_info->profiles_lock); 795 } 796 797 /* 798 * Clear incompat bits for the following feature(s): 799 * 800 * - RAID56 - in case there's neither RAID5 nor RAID6 profile block group 801 * in the whole filesystem 802 * 803 * - RAID1C34 - same as above for RAID1C3 and RAID1C4 block groups 804 */ 805 static void clear_incompat_bg_bits(struct btrfs_fs_info *fs_info, u64 flags) 806 { 807 bool found_raid56 = false; 808 bool found_raid1c34 = false; 809 810 if ((flags & BTRFS_BLOCK_GROUP_RAID56_MASK) || 811 (flags & BTRFS_BLOCK_GROUP_RAID1C3) || 812 (flags & BTRFS_BLOCK_GROUP_RAID1C4)) { 813 struct list_head *head = &fs_info->space_info; 814 struct btrfs_space_info *sinfo; 815 816 list_for_each_entry_rcu(sinfo, head, list) { 817 down_read(&sinfo->groups_sem); 818 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID5])) 819 found_raid56 = true; 820 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID6])) 821 found_raid56 = true; 822 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID1C3])) 823 found_raid1c34 = true; 824 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID1C4])) 825 found_raid1c34 = true; 826 up_read(&sinfo->groups_sem); 827 } 828 if (!found_raid56) 829 btrfs_clear_fs_incompat(fs_info, RAID56); 830 if (!found_raid1c34) 831 btrfs_clear_fs_incompat(fs_info, RAID1C34); 832 } 833 } 834 835 static int remove_block_group_item(struct btrfs_trans_handle *trans, 836 struct btrfs_path *path, 837 struct btrfs_block_group *block_group) 838 { 839 struct btrfs_fs_info *fs_info = trans->fs_info; 840 struct btrfs_root *root; 841 struct btrfs_key key; 842 int ret; 843 844 root = btrfs_block_group_root(fs_info); 845 key.objectid = block_group->start; 846 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY; 847 key.offset = block_group->length; 848 849 ret = btrfs_search_slot(trans, root, &key, path, -1, 1); 850 if (ret > 0) 851 ret = -ENOENT; 852 if (ret < 0) 853 return ret; 854 855 ret = btrfs_del_item(trans, root, path); 856 return ret; 857 } 858 859 int btrfs_remove_block_group(struct btrfs_trans_handle *trans, 860 u64 group_start, struct extent_map *em) 861 { 862 struct btrfs_fs_info *fs_info = trans->fs_info; 863 struct btrfs_path *path; 864 struct btrfs_block_group *block_group; 865 struct btrfs_free_cluster *cluster; 866 struct inode *inode; 867 struct kobject *kobj = NULL; 868 int ret; 869 int index; 870 int factor; 871 struct btrfs_caching_control *caching_ctl = NULL; 872 bool remove_em; 873 bool remove_rsv = false; 874 875 block_group = btrfs_lookup_block_group(fs_info, group_start); 876 BUG_ON(!block_group); 877 BUG_ON(!block_group->ro); 878 879 trace_btrfs_remove_block_group(block_group); 880 /* 881 * Free the reserved super bytes from this block group before 882 * remove it. 883 */ 884 btrfs_free_excluded_extents(block_group); 885 btrfs_free_ref_tree_range(fs_info, block_group->start, 886 block_group->length); 887 888 index = btrfs_bg_flags_to_raid_index(block_group->flags); 889 factor = btrfs_bg_type_to_factor(block_group->flags); 890 891 /* make sure this block group isn't part of an allocation cluster */ 892 cluster = &fs_info->data_alloc_cluster; 893 spin_lock(&cluster->refill_lock); 894 btrfs_return_cluster_to_free_space(block_group, cluster); 895 spin_unlock(&cluster->refill_lock); 896 897 /* 898 * make sure this block group isn't part of a metadata 899 * allocation cluster 900 */ 901 cluster = &fs_info->meta_alloc_cluster; 902 spin_lock(&cluster->refill_lock); 903 btrfs_return_cluster_to_free_space(block_group, cluster); 904 spin_unlock(&cluster->refill_lock); 905 906 btrfs_clear_treelog_bg(block_group); 907 btrfs_clear_data_reloc_bg(block_group); 908 909 path = btrfs_alloc_path(); 910 if (!path) { 911 ret = -ENOMEM; 912 goto out; 913 } 914 915 /* 916 * get the inode first so any iput calls done for the io_list 917 * aren't the final iput (no unlinks allowed now) 918 */ 919 inode = lookup_free_space_inode(block_group, path); 920 921 mutex_lock(&trans->transaction->cache_write_mutex); 922 /* 923 * Make sure our free space cache IO is done before removing the 924 * free space inode 925 */ 926 spin_lock(&trans->transaction->dirty_bgs_lock); 927 if (!list_empty(&block_group->io_list)) { 928 list_del_init(&block_group->io_list); 929 930 WARN_ON(!IS_ERR(inode) && inode != block_group->io_ctl.inode); 931 932 spin_unlock(&trans->transaction->dirty_bgs_lock); 933 btrfs_wait_cache_io(trans, block_group, path); 934 btrfs_put_block_group(block_group); 935 spin_lock(&trans->transaction->dirty_bgs_lock); 936 } 937 938 if (!list_empty(&block_group->dirty_list)) { 939 list_del_init(&block_group->dirty_list); 940 remove_rsv = true; 941 btrfs_put_block_group(block_group); 942 } 943 spin_unlock(&trans->transaction->dirty_bgs_lock); 944 mutex_unlock(&trans->transaction->cache_write_mutex); 945 946 ret = btrfs_remove_free_space_inode(trans, inode, block_group); 947 if (ret) 948 goto out; 949 950 spin_lock(&fs_info->block_group_cache_lock); 951 rb_erase(&block_group->cache_node, 952 &fs_info->block_group_cache_tree); 953 RB_CLEAR_NODE(&block_group->cache_node); 954 955 /* Once for the block groups rbtree */ 956 btrfs_put_block_group(block_group); 957 958 if (fs_info->first_logical_byte == block_group->start) 959 fs_info->first_logical_byte = (u64)-1; 960 spin_unlock(&fs_info->block_group_cache_lock); 961 962 down_write(&block_group->space_info->groups_sem); 963 /* 964 * we must use list_del_init so people can check to see if they 965 * are still on the list after taking the semaphore 966 */ 967 list_del_init(&block_group->list); 968 if (list_empty(&block_group->space_info->block_groups[index])) { 969 kobj = block_group->space_info->block_group_kobjs[index]; 970 block_group->space_info->block_group_kobjs[index] = NULL; 971 clear_avail_alloc_bits(fs_info, block_group->flags); 972 } 973 up_write(&block_group->space_info->groups_sem); 974 clear_incompat_bg_bits(fs_info, block_group->flags); 975 if (kobj) { 976 kobject_del(kobj); 977 kobject_put(kobj); 978 } 979 980 if (block_group->has_caching_ctl) 981 caching_ctl = btrfs_get_caching_control(block_group); 982 if (block_group->cached == BTRFS_CACHE_STARTED) 983 btrfs_wait_block_group_cache_done(block_group); 984 if (block_group->has_caching_ctl) { 985 spin_lock(&fs_info->block_group_cache_lock); 986 if (!caching_ctl) { 987 struct btrfs_caching_control *ctl; 988 989 list_for_each_entry(ctl, 990 &fs_info->caching_block_groups, list) 991 if (ctl->block_group == block_group) { 992 caching_ctl = ctl; 993 refcount_inc(&caching_ctl->count); 994 break; 995 } 996 } 997 if (caching_ctl) 998 list_del_init(&caching_ctl->list); 999 spin_unlock(&fs_info->block_group_cache_lock); 1000 if (caching_ctl) { 1001 /* Once for the caching bgs list and once for us. */ 1002 btrfs_put_caching_control(caching_ctl); 1003 btrfs_put_caching_control(caching_ctl); 1004 } 1005 } 1006 1007 spin_lock(&trans->transaction->dirty_bgs_lock); 1008 WARN_ON(!list_empty(&block_group->dirty_list)); 1009 WARN_ON(!list_empty(&block_group->io_list)); 1010 spin_unlock(&trans->transaction->dirty_bgs_lock); 1011 1012 btrfs_remove_free_space_cache(block_group); 1013 1014 spin_lock(&block_group->space_info->lock); 1015 list_del_init(&block_group->ro_list); 1016 1017 if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) { 1018 WARN_ON(block_group->space_info->total_bytes 1019 < block_group->length); 1020 WARN_ON(block_group->space_info->bytes_readonly 1021 < block_group->length - block_group->zone_unusable); 1022 WARN_ON(block_group->space_info->bytes_zone_unusable 1023 < block_group->zone_unusable); 1024 WARN_ON(block_group->space_info->disk_total 1025 < block_group->length * factor); 1026 } 1027 block_group->space_info->total_bytes -= block_group->length; 1028 block_group->space_info->bytes_readonly -= 1029 (block_group->length - block_group->zone_unusable); 1030 block_group->space_info->bytes_zone_unusable -= 1031 block_group->zone_unusable; 1032 block_group->space_info->disk_total -= block_group->length * factor; 1033 1034 spin_unlock(&block_group->space_info->lock); 1035 1036 /* 1037 * Remove the free space for the block group from the free space tree 1038 * and the block group's item from the extent tree before marking the 1039 * block group as removed. This is to prevent races with tasks that 1040 * freeze and unfreeze a block group, this task and another task 1041 * allocating a new block group - the unfreeze task ends up removing 1042 * the block group's extent map before the task calling this function 1043 * deletes the block group item from the extent tree, allowing for 1044 * another task to attempt to create another block group with the same 1045 * item key (and failing with -EEXIST and a transaction abort). 1046 */ 1047 ret = remove_block_group_free_space(trans, block_group); 1048 if (ret) 1049 goto out; 1050 1051 ret = remove_block_group_item(trans, path, block_group); 1052 if (ret < 0) 1053 goto out; 1054 1055 spin_lock(&block_group->lock); 1056 block_group->removed = 1; 1057 /* 1058 * At this point trimming or scrub can't start on this block group, 1059 * because we removed the block group from the rbtree 1060 * fs_info->block_group_cache_tree so no one can't find it anymore and 1061 * even if someone already got this block group before we removed it 1062 * from the rbtree, they have already incremented block_group->frozen - 1063 * if they didn't, for the trimming case they won't find any free space 1064 * entries because we already removed them all when we called 1065 * btrfs_remove_free_space_cache(). 1066 * 1067 * And we must not remove the extent map from the fs_info->mapping_tree 1068 * to prevent the same logical address range and physical device space 1069 * ranges from being reused for a new block group. This is needed to 1070 * avoid races with trimming and scrub. 1071 * 1072 * An fs trim operation (btrfs_trim_fs() / btrfs_ioctl_fitrim()) is 1073 * completely transactionless, so while it is trimming a range the 1074 * currently running transaction might finish and a new one start, 1075 * allowing for new block groups to be created that can reuse the same 1076 * physical device locations unless we take this special care. 1077 * 1078 * There may also be an implicit trim operation if the file system 1079 * is mounted with -odiscard. The same protections must remain 1080 * in place until the extents have been discarded completely when 1081 * the transaction commit has completed. 1082 */ 1083 remove_em = (atomic_read(&block_group->frozen) == 0); 1084 spin_unlock(&block_group->lock); 1085 1086 if (remove_em) { 1087 struct extent_map_tree *em_tree; 1088 1089 em_tree = &fs_info->mapping_tree; 1090 write_lock(&em_tree->lock); 1091 remove_extent_mapping(em_tree, em); 1092 write_unlock(&em_tree->lock); 1093 /* once for the tree */ 1094 free_extent_map(em); 1095 } 1096 1097 out: 1098 /* Once for the lookup reference */ 1099 btrfs_put_block_group(block_group); 1100 if (remove_rsv) 1101 btrfs_delayed_refs_rsv_release(fs_info, 1); 1102 btrfs_free_path(path); 1103 return ret; 1104 } 1105 1106 struct btrfs_trans_handle *btrfs_start_trans_remove_block_group( 1107 struct btrfs_fs_info *fs_info, const u64 chunk_offset) 1108 { 1109 struct btrfs_root *root = btrfs_block_group_root(fs_info); 1110 struct extent_map_tree *em_tree = &fs_info->mapping_tree; 1111 struct extent_map *em; 1112 struct map_lookup *map; 1113 unsigned int num_items; 1114 1115 read_lock(&em_tree->lock); 1116 em = lookup_extent_mapping(em_tree, chunk_offset, 1); 1117 read_unlock(&em_tree->lock); 1118 ASSERT(em && em->start == chunk_offset); 1119 1120 /* 1121 * We need to reserve 3 + N units from the metadata space info in order 1122 * to remove a block group (done at btrfs_remove_chunk() and at 1123 * btrfs_remove_block_group()), which are used for: 1124 * 1125 * 1 unit for adding the free space inode's orphan (located in the tree 1126 * of tree roots). 1127 * 1 unit for deleting the block group item (located in the extent 1128 * tree). 1129 * 1 unit for deleting the free space item (located in tree of tree 1130 * roots). 1131 * N units for deleting N device extent items corresponding to each 1132 * stripe (located in the device tree). 1133 * 1134 * In order to remove a block group we also need to reserve units in the 1135 * system space info in order to update the chunk tree (update one or 1136 * more device items and remove one chunk item), but this is done at 1137 * btrfs_remove_chunk() through a call to check_system_chunk(). 1138 */ 1139 map = em->map_lookup; 1140 num_items = 3 + map->num_stripes; 1141 free_extent_map(em); 1142 1143 return btrfs_start_transaction_fallback_global_rsv(root, num_items); 1144 } 1145 1146 /* 1147 * Mark block group @cache read-only, so later write won't happen to block 1148 * group @cache. 1149 * 1150 * If @force is not set, this function will only mark the block group readonly 1151 * if we have enough free space (1M) in other metadata/system block groups. 1152 * If @force is not set, this function will mark the block group readonly 1153 * without checking free space. 1154 * 1155 * NOTE: This function doesn't care if other block groups can contain all the 1156 * data in this block group. That check should be done by relocation routine, 1157 * not this function. 1158 */ 1159 static int inc_block_group_ro(struct btrfs_block_group *cache, int force) 1160 { 1161 struct btrfs_space_info *sinfo = cache->space_info; 1162 u64 num_bytes; 1163 int ret = -ENOSPC; 1164 1165 spin_lock(&sinfo->lock); 1166 spin_lock(&cache->lock); 1167 1168 if (cache->swap_extents) { 1169 ret = -ETXTBSY; 1170 goto out; 1171 } 1172 1173 if (cache->ro) { 1174 cache->ro++; 1175 ret = 0; 1176 goto out; 1177 } 1178 1179 num_bytes = cache->length - cache->reserved - cache->pinned - 1180 cache->bytes_super - cache->zone_unusable - cache->used; 1181 1182 /* 1183 * Data never overcommits, even in mixed mode, so do just the straight 1184 * check of left over space in how much we have allocated. 1185 */ 1186 if (force) { 1187 ret = 0; 1188 } else if (sinfo->flags & BTRFS_BLOCK_GROUP_DATA) { 1189 u64 sinfo_used = btrfs_space_info_used(sinfo, true); 1190 1191 /* 1192 * Here we make sure if we mark this bg RO, we still have enough 1193 * free space as buffer. 1194 */ 1195 if (sinfo_used + num_bytes <= sinfo->total_bytes) 1196 ret = 0; 1197 } else { 1198 /* 1199 * We overcommit metadata, so we need to do the 1200 * btrfs_can_overcommit check here, and we need to pass in 1201 * BTRFS_RESERVE_NO_FLUSH to give ourselves the most amount of 1202 * leeway to allow us to mark this block group as read only. 1203 */ 1204 if (btrfs_can_overcommit(cache->fs_info, sinfo, num_bytes, 1205 BTRFS_RESERVE_NO_FLUSH)) 1206 ret = 0; 1207 } 1208 1209 if (!ret) { 1210 sinfo->bytes_readonly += num_bytes; 1211 if (btrfs_is_zoned(cache->fs_info)) { 1212 /* Migrate zone_unusable bytes to readonly */ 1213 sinfo->bytes_readonly += cache->zone_unusable; 1214 sinfo->bytes_zone_unusable -= cache->zone_unusable; 1215 cache->zone_unusable = 0; 1216 } 1217 cache->ro++; 1218 list_add_tail(&cache->ro_list, &sinfo->ro_bgs); 1219 } 1220 out: 1221 spin_unlock(&cache->lock); 1222 spin_unlock(&sinfo->lock); 1223 if (ret == -ENOSPC && btrfs_test_opt(cache->fs_info, ENOSPC_DEBUG)) { 1224 btrfs_info(cache->fs_info, 1225 "unable to make block group %llu ro", cache->start); 1226 btrfs_dump_space_info(cache->fs_info, cache->space_info, 0, 0); 1227 } 1228 return ret; 1229 } 1230 1231 static bool clean_pinned_extents(struct btrfs_trans_handle *trans, 1232 struct btrfs_block_group *bg) 1233 { 1234 struct btrfs_fs_info *fs_info = bg->fs_info; 1235 struct btrfs_transaction *prev_trans = NULL; 1236 const u64 start = bg->start; 1237 const u64 end = start + bg->length - 1; 1238 int ret; 1239 1240 spin_lock(&fs_info->trans_lock); 1241 if (trans->transaction->list.prev != &fs_info->trans_list) { 1242 prev_trans = list_last_entry(&trans->transaction->list, 1243 struct btrfs_transaction, list); 1244 refcount_inc(&prev_trans->use_count); 1245 } 1246 spin_unlock(&fs_info->trans_lock); 1247 1248 /* 1249 * Hold the unused_bg_unpin_mutex lock to avoid racing with 1250 * btrfs_finish_extent_commit(). If we are at transaction N, another 1251 * task might be running finish_extent_commit() for the previous 1252 * transaction N - 1, and have seen a range belonging to the block 1253 * group in pinned_extents before we were able to clear the whole block 1254 * group range from pinned_extents. This means that task can lookup for 1255 * the block group after we unpinned it from pinned_extents and removed 1256 * it, leading to a BUG_ON() at unpin_extent_range(). 1257 */ 1258 mutex_lock(&fs_info->unused_bg_unpin_mutex); 1259 if (prev_trans) { 1260 ret = clear_extent_bits(&prev_trans->pinned_extents, start, end, 1261 EXTENT_DIRTY); 1262 if (ret) 1263 goto out; 1264 } 1265 1266 ret = clear_extent_bits(&trans->transaction->pinned_extents, start, end, 1267 EXTENT_DIRTY); 1268 out: 1269 mutex_unlock(&fs_info->unused_bg_unpin_mutex); 1270 if (prev_trans) 1271 btrfs_put_transaction(prev_trans); 1272 1273 return ret == 0; 1274 } 1275 1276 /* 1277 * Process the unused_bgs list and remove any that don't have any allocated 1278 * space inside of them. 1279 */ 1280 void btrfs_delete_unused_bgs(struct btrfs_fs_info *fs_info) 1281 { 1282 struct btrfs_block_group *block_group; 1283 struct btrfs_space_info *space_info; 1284 struct btrfs_trans_handle *trans; 1285 const bool async_trim_enabled = btrfs_test_opt(fs_info, DISCARD_ASYNC); 1286 int ret = 0; 1287 1288 if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags)) 1289 return; 1290 1291 /* 1292 * Long running balances can keep us blocked here for eternity, so 1293 * simply skip deletion if we're unable to get the mutex. 1294 */ 1295 if (!mutex_trylock(&fs_info->reclaim_bgs_lock)) 1296 return; 1297 1298 spin_lock(&fs_info->unused_bgs_lock); 1299 while (!list_empty(&fs_info->unused_bgs)) { 1300 int trimming; 1301 1302 block_group = list_first_entry(&fs_info->unused_bgs, 1303 struct btrfs_block_group, 1304 bg_list); 1305 list_del_init(&block_group->bg_list); 1306 1307 space_info = block_group->space_info; 1308 1309 if (ret || btrfs_mixed_space_info(space_info)) { 1310 btrfs_put_block_group(block_group); 1311 continue; 1312 } 1313 spin_unlock(&fs_info->unused_bgs_lock); 1314 1315 btrfs_discard_cancel_work(&fs_info->discard_ctl, block_group); 1316 1317 /* Don't want to race with allocators so take the groups_sem */ 1318 down_write(&space_info->groups_sem); 1319 1320 /* 1321 * Async discard moves the final block group discard to be prior 1322 * to the unused_bgs code path. Therefore, if it's not fully 1323 * trimmed, punt it back to the async discard lists. 1324 */ 1325 if (btrfs_test_opt(fs_info, DISCARD_ASYNC) && 1326 !btrfs_is_free_space_trimmed(block_group)) { 1327 trace_btrfs_skip_unused_block_group(block_group); 1328 up_write(&space_info->groups_sem); 1329 /* Requeue if we failed because of async discard */ 1330 btrfs_discard_queue_work(&fs_info->discard_ctl, 1331 block_group); 1332 goto next; 1333 } 1334 1335 spin_lock(&block_group->lock); 1336 if (block_group->reserved || block_group->pinned || 1337 block_group->used || block_group->ro || 1338 list_is_singular(&block_group->list)) { 1339 /* 1340 * We want to bail if we made new allocations or have 1341 * outstanding allocations in this block group. We do 1342 * the ro check in case balance is currently acting on 1343 * this block group. 1344 */ 1345 trace_btrfs_skip_unused_block_group(block_group); 1346 spin_unlock(&block_group->lock); 1347 up_write(&space_info->groups_sem); 1348 goto next; 1349 } 1350 spin_unlock(&block_group->lock); 1351 1352 /* We don't want to force the issue, only flip if it's ok. */ 1353 ret = inc_block_group_ro(block_group, 0); 1354 up_write(&space_info->groups_sem); 1355 if (ret < 0) { 1356 ret = 0; 1357 goto next; 1358 } 1359 1360 /* 1361 * Want to do this before we do anything else so we can recover 1362 * properly if we fail to join the transaction. 1363 */ 1364 trans = btrfs_start_trans_remove_block_group(fs_info, 1365 block_group->start); 1366 if (IS_ERR(trans)) { 1367 btrfs_dec_block_group_ro(block_group); 1368 ret = PTR_ERR(trans); 1369 goto next; 1370 } 1371 1372 /* 1373 * We could have pending pinned extents for this block group, 1374 * just delete them, we don't care about them anymore. 1375 */ 1376 if (!clean_pinned_extents(trans, block_group)) { 1377 btrfs_dec_block_group_ro(block_group); 1378 goto end_trans; 1379 } 1380 1381 /* 1382 * At this point, the block_group is read only and should fail 1383 * new allocations. However, btrfs_finish_extent_commit() can 1384 * cause this block_group to be placed back on the discard 1385 * lists because now the block_group isn't fully discarded. 1386 * Bail here and try again later after discarding everything. 1387 */ 1388 spin_lock(&fs_info->discard_ctl.lock); 1389 if (!list_empty(&block_group->discard_list)) { 1390 spin_unlock(&fs_info->discard_ctl.lock); 1391 btrfs_dec_block_group_ro(block_group); 1392 btrfs_discard_queue_work(&fs_info->discard_ctl, 1393 block_group); 1394 goto end_trans; 1395 } 1396 spin_unlock(&fs_info->discard_ctl.lock); 1397 1398 /* Reset pinned so btrfs_put_block_group doesn't complain */ 1399 spin_lock(&space_info->lock); 1400 spin_lock(&block_group->lock); 1401 1402 btrfs_space_info_update_bytes_pinned(fs_info, space_info, 1403 -block_group->pinned); 1404 space_info->bytes_readonly += block_group->pinned; 1405 block_group->pinned = 0; 1406 1407 spin_unlock(&block_group->lock); 1408 spin_unlock(&space_info->lock); 1409 1410 /* 1411 * The normal path here is an unused block group is passed here, 1412 * then trimming is handled in the transaction commit path. 1413 * Async discard interposes before this to do the trimming 1414 * before coming down the unused block group path as trimming 1415 * will no longer be done later in the transaction commit path. 1416 */ 1417 if (!async_trim_enabled && btrfs_test_opt(fs_info, DISCARD_ASYNC)) 1418 goto flip_async; 1419 1420 /* 1421 * DISCARD can flip during remount. On zoned filesystems, we 1422 * need to reset sequential-required zones. 1423 */ 1424 trimming = btrfs_test_opt(fs_info, DISCARD_SYNC) || 1425 btrfs_is_zoned(fs_info); 1426 1427 /* Implicit trim during transaction commit. */ 1428 if (trimming) 1429 btrfs_freeze_block_group(block_group); 1430 1431 /* 1432 * Btrfs_remove_chunk will abort the transaction if things go 1433 * horribly wrong. 1434 */ 1435 ret = btrfs_remove_chunk(trans, block_group->start); 1436 1437 if (ret) { 1438 if (trimming) 1439 btrfs_unfreeze_block_group(block_group); 1440 goto end_trans; 1441 } 1442 1443 /* 1444 * If we're not mounted with -odiscard, we can just forget 1445 * about this block group. Otherwise we'll need to wait 1446 * until transaction commit to do the actual discard. 1447 */ 1448 if (trimming) { 1449 spin_lock(&fs_info->unused_bgs_lock); 1450 /* 1451 * A concurrent scrub might have added us to the list 1452 * fs_info->unused_bgs, so use a list_move operation 1453 * to add the block group to the deleted_bgs list. 1454 */ 1455 list_move(&block_group->bg_list, 1456 &trans->transaction->deleted_bgs); 1457 spin_unlock(&fs_info->unused_bgs_lock); 1458 btrfs_get_block_group(block_group); 1459 } 1460 end_trans: 1461 btrfs_end_transaction(trans); 1462 next: 1463 btrfs_put_block_group(block_group); 1464 spin_lock(&fs_info->unused_bgs_lock); 1465 } 1466 spin_unlock(&fs_info->unused_bgs_lock); 1467 mutex_unlock(&fs_info->reclaim_bgs_lock); 1468 return; 1469 1470 flip_async: 1471 btrfs_end_transaction(trans); 1472 mutex_unlock(&fs_info->reclaim_bgs_lock); 1473 btrfs_put_block_group(block_group); 1474 btrfs_discard_punt_unused_bgs_list(fs_info); 1475 } 1476 1477 void btrfs_mark_bg_unused(struct btrfs_block_group *bg) 1478 { 1479 struct btrfs_fs_info *fs_info = bg->fs_info; 1480 1481 spin_lock(&fs_info->unused_bgs_lock); 1482 if (list_empty(&bg->bg_list)) { 1483 btrfs_get_block_group(bg); 1484 trace_btrfs_add_unused_block_group(bg); 1485 list_add_tail(&bg->bg_list, &fs_info->unused_bgs); 1486 } 1487 spin_unlock(&fs_info->unused_bgs_lock); 1488 } 1489 1490 /* 1491 * We want block groups with a low number of used bytes to be in the beginning 1492 * of the list, so they will get reclaimed first. 1493 */ 1494 static int reclaim_bgs_cmp(void *unused, const struct list_head *a, 1495 const struct list_head *b) 1496 { 1497 const struct btrfs_block_group *bg1, *bg2; 1498 1499 bg1 = list_entry(a, struct btrfs_block_group, bg_list); 1500 bg2 = list_entry(b, struct btrfs_block_group, bg_list); 1501 1502 return bg1->used > bg2->used; 1503 } 1504 1505 void btrfs_reclaim_bgs_work(struct work_struct *work) 1506 { 1507 struct btrfs_fs_info *fs_info = 1508 container_of(work, struct btrfs_fs_info, reclaim_bgs_work); 1509 struct btrfs_block_group *bg; 1510 struct btrfs_space_info *space_info; 1511 LIST_HEAD(again_list); 1512 1513 if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags)) 1514 return; 1515 1516 if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_BALANCE)) 1517 return; 1518 1519 /* 1520 * Long running balances can keep us blocked here for eternity, so 1521 * simply skip reclaim if we're unable to get the mutex. 1522 */ 1523 if (!mutex_trylock(&fs_info->reclaim_bgs_lock)) { 1524 btrfs_exclop_finish(fs_info); 1525 return; 1526 } 1527 1528 spin_lock(&fs_info->unused_bgs_lock); 1529 /* 1530 * Sort happens under lock because we can't simply splice it and sort. 1531 * The block groups might still be in use and reachable via bg_list, 1532 * and their presence in the reclaim_bgs list must be preserved. 1533 */ 1534 list_sort(NULL, &fs_info->reclaim_bgs, reclaim_bgs_cmp); 1535 while (!list_empty(&fs_info->reclaim_bgs)) { 1536 u64 zone_unusable; 1537 int ret = 0; 1538 1539 bg = list_first_entry(&fs_info->reclaim_bgs, 1540 struct btrfs_block_group, 1541 bg_list); 1542 list_del_init(&bg->bg_list); 1543 1544 space_info = bg->space_info; 1545 spin_unlock(&fs_info->unused_bgs_lock); 1546 1547 /* Don't race with allocators so take the groups_sem */ 1548 down_write(&space_info->groups_sem); 1549 1550 spin_lock(&bg->lock); 1551 if (bg->reserved || bg->pinned || bg->ro) { 1552 /* 1553 * We want to bail if we made new allocations or have 1554 * outstanding allocations in this block group. We do 1555 * the ro check in case balance is currently acting on 1556 * this block group. 1557 */ 1558 spin_unlock(&bg->lock); 1559 up_write(&space_info->groups_sem); 1560 goto next; 1561 } 1562 spin_unlock(&bg->lock); 1563 1564 /* Get out fast, in case we're unmounting the filesystem */ 1565 if (btrfs_fs_closing(fs_info)) { 1566 up_write(&space_info->groups_sem); 1567 goto next; 1568 } 1569 1570 /* 1571 * Cache the zone_unusable value before turning the block group 1572 * to read only. As soon as the blog group is read only it's 1573 * zone_unusable value gets moved to the block group's read-only 1574 * bytes and isn't available for calculations anymore. 1575 */ 1576 zone_unusable = bg->zone_unusable; 1577 ret = inc_block_group_ro(bg, 0); 1578 up_write(&space_info->groups_sem); 1579 if (ret < 0) 1580 goto next; 1581 1582 btrfs_info(fs_info, 1583 "reclaiming chunk %llu with %llu%% used %llu%% unusable", 1584 bg->start, div_u64(bg->used * 100, bg->length), 1585 div64_u64(zone_unusable * 100, bg->length)); 1586 trace_btrfs_reclaim_block_group(bg); 1587 ret = btrfs_relocate_chunk(fs_info, bg->start); 1588 if (ret && ret != -EAGAIN) 1589 btrfs_err(fs_info, "error relocating chunk %llu", 1590 bg->start); 1591 1592 next: 1593 spin_lock(&fs_info->unused_bgs_lock); 1594 if (ret == -EAGAIN && list_empty(&bg->bg_list)) 1595 list_add_tail(&bg->bg_list, &again_list); 1596 else 1597 btrfs_put_block_group(bg); 1598 } 1599 list_splice_tail(&again_list, &fs_info->reclaim_bgs); 1600 spin_unlock(&fs_info->unused_bgs_lock); 1601 mutex_unlock(&fs_info->reclaim_bgs_lock); 1602 btrfs_exclop_finish(fs_info); 1603 } 1604 1605 void btrfs_reclaim_bgs(struct btrfs_fs_info *fs_info) 1606 { 1607 spin_lock(&fs_info->unused_bgs_lock); 1608 if (!list_empty(&fs_info->reclaim_bgs)) 1609 queue_work(system_unbound_wq, &fs_info->reclaim_bgs_work); 1610 spin_unlock(&fs_info->unused_bgs_lock); 1611 } 1612 1613 void btrfs_mark_bg_to_reclaim(struct btrfs_block_group *bg) 1614 { 1615 struct btrfs_fs_info *fs_info = bg->fs_info; 1616 1617 spin_lock(&fs_info->unused_bgs_lock); 1618 if (list_empty(&bg->bg_list)) { 1619 btrfs_get_block_group(bg); 1620 trace_btrfs_add_reclaim_block_group(bg); 1621 list_add_tail(&bg->bg_list, &fs_info->reclaim_bgs); 1622 } 1623 spin_unlock(&fs_info->unused_bgs_lock); 1624 } 1625 1626 static int read_bg_from_eb(struct btrfs_fs_info *fs_info, struct btrfs_key *key, 1627 struct btrfs_path *path) 1628 { 1629 struct extent_map_tree *em_tree; 1630 struct extent_map *em; 1631 struct btrfs_block_group_item bg; 1632 struct extent_buffer *leaf; 1633 int slot; 1634 u64 flags; 1635 int ret = 0; 1636 1637 slot = path->slots[0]; 1638 leaf = path->nodes[0]; 1639 1640 em_tree = &fs_info->mapping_tree; 1641 read_lock(&em_tree->lock); 1642 em = lookup_extent_mapping(em_tree, key->objectid, key->offset); 1643 read_unlock(&em_tree->lock); 1644 if (!em) { 1645 btrfs_err(fs_info, 1646 "logical %llu len %llu found bg but no related chunk", 1647 key->objectid, key->offset); 1648 return -ENOENT; 1649 } 1650 1651 if (em->start != key->objectid || em->len != key->offset) { 1652 btrfs_err(fs_info, 1653 "block group %llu len %llu mismatch with chunk %llu len %llu", 1654 key->objectid, key->offset, em->start, em->len); 1655 ret = -EUCLEAN; 1656 goto out_free_em; 1657 } 1658 1659 read_extent_buffer(leaf, &bg, btrfs_item_ptr_offset(leaf, slot), 1660 sizeof(bg)); 1661 flags = btrfs_stack_block_group_flags(&bg) & 1662 BTRFS_BLOCK_GROUP_TYPE_MASK; 1663 1664 if (flags != (em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK)) { 1665 btrfs_err(fs_info, 1666 "block group %llu len %llu type flags 0x%llx mismatch with chunk type flags 0x%llx", 1667 key->objectid, key->offset, flags, 1668 (BTRFS_BLOCK_GROUP_TYPE_MASK & em->map_lookup->type)); 1669 ret = -EUCLEAN; 1670 } 1671 1672 out_free_em: 1673 free_extent_map(em); 1674 return ret; 1675 } 1676 1677 static int find_first_block_group(struct btrfs_fs_info *fs_info, 1678 struct btrfs_path *path, 1679 struct btrfs_key *key) 1680 { 1681 struct btrfs_root *root = btrfs_block_group_root(fs_info); 1682 int ret; 1683 struct btrfs_key found_key; 1684 struct extent_buffer *leaf; 1685 int slot; 1686 1687 ret = btrfs_search_slot(NULL, root, key, path, 0, 0); 1688 if (ret < 0) 1689 return ret; 1690 1691 while (1) { 1692 slot = path->slots[0]; 1693 leaf = path->nodes[0]; 1694 if (slot >= btrfs_header_nritems(leaf)) { 1695 ret = btrfs_next_leaf(root, path); 1696 if (ret == 0) 1697 continue; 1698 if (ret < 0) 1699 goto out; 1700 break; 1701 } 1702 btrfs_item_key_to_cpu(leaf, &found_key, slot); 1703 1704 if (found_key.objectid >= key->objectid && 1705 found_key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) { 1706 ret = read_bg_from_eb(fs_info, &found_key, path); 1707 break; 1708 } 1709 1710 path->slots[0]++; 1711 } 1712 out: 1713 return ret; 1714 } 1715 1716 static void set_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags) 1717 { 1718 u64 extra_flags = chunk_to_extended(flags) & 1719 BTRFS_EXTENDED_PROFILE_MASK; 1720 1721 write_seqlock(&fs_info->profiles_lock); 1722 if (flags & BTRFS_BLOCK_GROUP_DATA) 1723 fs_info->avail_data_alloc_bits |= extra_flags; 1724 if (flags & BTRFS_BLOCK_GROUP_METADATA) 1725 fs_info->avail_metadata_alloc_bits |= extra_flags; 1726 if (flags & BTRFS_BLOCK_GROUP_SYSTEM) 1727 fs_info->avail_system_alloc_bits |= extra_flags; 1728 write_sequnlock(&fs_info->profiles_lock); 1729 } 1730 1731 /** 1732 * Map a physical disk address to a list of logical addresses 1733 * 1734 * @fs_info: the filesystem 1735 * @chunk_start: logical address of block group 1736 * @bdev: physical device to resolve, can be NULL to indicate any device 1737 * @physical: physical address to map to logical addresses 1738 * @logical: return array of logical addresses which map to @physical 1739 * @naddrs: length of @logical 1740 * @stripe_len: size of IO stripe for the given block group 1741 * 1742 * Maps a particular @physical disk address to a list of @logical addresses. 1743 * Used primarily to exclude those portions of a block group that contain super 1744 * block copies. 1745 */ 1746 int btrfs_rmap_block(struct btrfs_fs_info *fs_info, u64 chunk_start, 1747 struct block_device *bdev, u64 physical, u64 **logical, 1748 int *naddrs, int *stripe_len) 1749 { 1750 struct extent_map *em; 1751 struct map_lookup *map; 1752 u64 *buf; 1753 u64 bytenr; 1754 u64 data_stripe_length; 1755 u64 io_stripe_size; 1756 int i, nr = 0; 1757 int ret = 0; 1758 1759 em = btrfs_get_chunk_map(fs_info, chunk_start, 1); 1760 if (IS_ERR(em)) 1761 return -EIO; 1762 1763 map = em->map_lookup; 1764 data_stripe_length = em->orig_block_len; 1765 io_stripe_size = map->stripe_len; 1766 chunk_start = em->start; 1767 1768 /* For RAID5/6 adjust to a full IO stripe length */ 1769 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) 1770 io_stripe_size = map->stripe_len * nr_data_stripes(map); 1771 1772 buf = kcalloc(map->num_stripes, sizeof(u64), GFP_NOFS); 1773 if (!buf) { 1774 ret = -ENOMEM; 1775 goto out; 1776 } 1777 1778 for (i = 0; i < map->num_stripes; i++) { 1779 bool already_inserted = false; 1780 u64 stripe_nr; 1781 u64 offset; 1782 int j; 1783 1784 if (!in_range(physical, map->stripes[i].physical, 1785 data_stripe_length)) 1786 continue; 1787 1788 if (bdev && map->stripes[i].dev->bdev != bdev) 1789 continue; 1790 1791 stripe_nr = physical - map->stripes[i].physical; 1792 stripe_nr = div64_u64_rem(stripe_nr, map->stripe_len, &offset); 1793 1794 if (map->type & BTRFS_BLOCK_GROUP_RAID10) { 1795 stripe_nr = stripe_nr * map->num_stripes + i; 1796 stripe_nr = div_u64(stripe_nr, map->sub_stripes); 1797 } else if (map->type & BTRFS_BLOCK_GROUP_RAID0) { 1798 stripe_nr = stripe_nr * map->num_stripes + i; 1799 } 1800 /* 1801 * The remaining case would be for RAID56, multiply by 1802 * nr_data_stripes(). Alternatively, just use rmap_len below 1803 * instead of map->stripe_len 1804 */ 1805 1806 bytenr = chunk_start + stripe_nr * io_stripe_size + offset; 1807 1808 /* Ensure we don't add duplicate addresses */ 1809 for (j = 0; j < nr; j++) { 1810 if (buf[j] == bytenr) { 1811 already_inserted = true; 1812 break; 1813 } 1814 } 1815 1816 if (!already_inserted) 1817 buf[nr++] = bytenr; 1818 } 1819 1820 *logical = buf; 1821 *naddrs = nr; 1822 *stripe_len = io_stripe_size; 1823 out: 1824 free_extent_map(em); 1825 return ret; 1826 } 1827 1828 static int exclude_super_stripes(struct btrfs_block_group *cache) 1829 { 1830 struct btrfs_fs_info *fs_info = cache->fs_info; 1831 const bool zoned = btrfs_is_zoned(fs_info); 1832 u64 bytenr; 1833 u64 *logical; 1834 int stripe_len; 1835 int i, nr, ret; 1836 1837 if (cache->start < BTRFS_SUPER_INFO_OFFSET) { 1838 stripe_len = BTRFS_SUPER_INFO_OFFSET - cache->start; 1839 cache->bytes_super += stripe_len; 1840 ret = btrfs_add_excluded_extent(fs_info, cache->start, 1841 stripe_len); 1842 if (ret) 1843 return ret; 1844 } 1845 1846 for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) { 1847 bytenr = btrfs_sb_offset(i); 1848 ret = btrfs_rmap_block(fs_info, cache->start, NULL, 1849 bytenr, &logical, &nr, &stripe_len); 1850 if (ret) 1851 return ret; 1852 1853 /* Shouldn't have super stripes in sequential zones */ 1854 if (zoned && nr) { 1855 btrfs_err(fs_info, 1856 "zoned: block group %llu must not contain super block", 1857 cache->start); 1858 return -EUCLEAN; 1859 } 1860 1861 while (nr--) { 1862 u64 len = min_t(u64, stripe_len, 1863 cache->start + cache->length - logical[nr]); 1864 1865 cache->bytes_super += len; 1866 ret = btrfs_add_excluded_extent(fs_info, logical[nr], 1867 len); 1868 if (ret) { 1869 kfree(logical); 1870 return ret; 1871 } 1872 } 1873 1874 kfree(logical); 1875 } 1876 return 0; 1877 } 1878 1879 static void link_block_group(struct btrfs_block_group *cache) 1880 { 1881 struct btrfs_space_info *space_info = cache->space_info; 1882 int index = btrfs_bg_flags_to_raid_index(cache->flags); 1883 1884 down_write(&space_info->groups_sem); 1885 list_add_tail(&cache->list, &space_info->block_groups[index]); 1886 up_write(&space_info->groups_sem); 1887 } 1888 1889 static struct btrfs_block_group *btrfs_create_block_group_cache( 1890 struct btrfs_fs_info *fs_info, u64 start) 1891 { 1892 struct btrfs_block_group *cache; 1893 1894 cache = kzalloc(sizeof(*cache), GFP_NOFS); 1895 if (!cache) 1896 return NULL; 1897 1898 cache->free_space_ctl = kzalloc(sizeof(*cache->free_space_ctl), 1899 GFP_NOFS); 1900 if (!cache->free_space_ctl) { 1901 kfree(cache); 1902 return NULL; 1903 } 1904 1905 cache->start = start; 1906 1907 cache->fs_info = fs_info; 1908 cache->full_stripe_len = btrfs_full_stripe_len(fs_info, start); 1909 1910 cache->discard_index = BTRFS_DISCARD_INDEX_UNUSED; 1911 1912 refcount_set(&cache->refs, 1); 1913 spin_lock_init(&cache->lock); 1914 init_rwsem(&cache->data_rwsem); 1915 INIT_LIST_HEAD(&cache->list); 1916 INIT_LIST_HEAD(&cache->cluster_list); 1917 INIT_LIST_HEAD(&cache->bg_list); 1918 INIT_LIST_HEAD(&cache->ro_list); 1919 INIT_LIST_HEAD(&cache->discard_list); 1920 INIT_LIST_HEAD(&cache->dirty_list); 1921 INIT_LIST_HEAD(&cache->io_list); 1922 INIT_LIST_HEAD(&cache->active_bg_list); 1923 btrfs_init_free_space_ctl(cache, cache->free_space_ctl); 1924 atomic_set(&cache->frozen, 0); 1925 mutex_init(&cache->free_space_lock); 1926 btrfs_init_full_stripe_locks_tree(&cache->full_stripe_locks_root); 1927 1928 return cache; 1929 } 1930 1931 /* 1932 * Iterate all chunks and verify that each of them has the corresponding block 1933 * group 1934 */ 1935 static int check_chunk_block_group_mappings(struct btrfs_fs_info *fs_info) 1936 { 1937 struct extent_map_tree *map_tree = &fs_info->mapping_tree; 1938 struct extent_map *em; 1939 struct btrfs_block_group *bg; 1940 u64 start = 0; 1941 int ret = 0; 1942 1943 while (1) { 1944 read_lock(&map_tree->lock); 1945 /* 1946 * lookup_extent_mapping will return the first extent map 1947 * intersecting the range, so setting @len to 1 is enough to 1948 * get the first chunk. 1949 */ 1950 em = lookup_extent_mapping(map_tree, start, 1); 1951 read_unlock(&map_tree->lock); 1952 if (!em) 1953 break; 1954 1955 bg = btrfs_lookup_block_group(fs_info, em->start); 1956 if (!bg) { 1957 btrfs_err(fs_info, 1958 "chunk start=%llu len=%llu doesn't have corresponding block group", 1959 em->start, em->len); 1960 ret = -EUCLEAN; 1961 free_extent_map(em); 1962 break; 1963 } 1964 if (bg->start != em->start || bg->length != em->len || 1965 (bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK) != 1966 (em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK)) { 1967 btrfs_err(fs_info, 1968 "chunk start=%llu len=%llu flags=0x%llx doesn't match block group start=%llu len=%llu flags=0x%llx", 1969 em->start, em->len, 1970 em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK, 1971 bg->start, bg->length, 1972 bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK); 1973 ret = -EUCLEAN; 1974 free_extent_map(em); 1975 btrfs_put_block_group(bg); 1976 break; 1977 } 1978 start = em->start + em->len; 1979 free_extent_map(em); 1980 btrfs_put_block_group(bg); 1981 } 1982 return ret; 1983 } 1984 1985 static int read_one_block_group(struct btrfs_fs_info *info, 1986 struct btrfs_block_group_item *bgi, 1987 const struct btrfs_key *key, 1988 int need_clear) 1989 { 1990 struct btrfs_block_group *cache; 1991 struct btrfs_space_info *space_info; 1992 const bool mixed = btrfs_fs_incompat(info, MIXED_GROUPS); 1993 int ret; 1994 1995 ASSERT(key->type == BTRFS_BLOCK_GROUP_ITEM_KEY); 1996 1997 cache = btrfs_create_block_group_cache(info, key->objectid); 1998 if (!cache) 1999 return -ENOMEM; 2000 2001 cache->length = key->offset; 2002 cache->used = btrfs_stack_block_group_used(bgi); 2003 cache->flags = btrfs_stack_block_group_flags(bgi); 2004 2005 set_free_space_tree_thresholds(cache); 2006 2007 if (need_clear) { 2008 /* 2009 * When we mount with old space cache, we need to 2010 * set BTRFS_DC_CLEAR and set dirty flag. 2011 * 2012 * a) Setting 'BTRFS_DC_CLEAR' makes sure that we 2013 * truncate the old free space cache inode and 2014 * setup a new one. 2015 * b) Setting 'dirty flag' makes sure that we flush 2016 * the new space cache info onto disk. 2017 */ 2018 if (btrfs_test_opt(info, SPACE_CACHE)) 2019 cache->disk_cache_state = BTRFS_DC_CLEAR; 2020 } 2021 if (!mixed && ((cache->flags & BTRFS_BLOCK_GROUP_METADATA) && 2022 (cache->flags & BTRFS_BLOCK_GROUP_DATA))) { 2023 btrfs_err(info, 2024 "bg %llu is a mixed block group but filesystem hasn't enabled mixed block groups", 2025 cache->start); 2026 ret = -EINVAL; 2027 goto error; 2028 } 2029 2030 ret = btrfs_load_block_group_zone_info(cache, false); 2031 if (ret) { 2032 btrfs_err(info, "zoned: failed to load zone info of bg %llu", 2033 cache->start); 2034 goto error; 2035 } 2036 2037 /* 2038 * We need to exclude the super stripes now so that the space info has 2039 * super bytes accounted for, otherwise we'll think we have more space 2040 * than we actually do. 2041 */ 2042 ret = exclude_super_stripes(cache); 2043 if (ret) { 2044 /* We may have excluded something, so call this just in case. */ 2045 btrfs_free_excluded_extents(cache); 2046 goto error; 2047 } 2048 2049 /* 2050 * For zoned filesystem, space after the allocation offset is the only 2051 * free space for a block group. So, we don't need any caching work. 2052 * btrfs_calc_zone_unusable() will set the amount of free space and 2053 * zone_unusable space. 2054 * 2055 * For regular filesystem, check for two cases, either we are full, and 2056 * therefore don't need to bother with the caching work since we won't 2057 * find any space, or we are empty, and we can just add all the space 2058 * in and be done with it. This saves us _a_lot_ of time, particularly 2059 * in the full case. 2060 */ 2061 if (btrfs_is_zoned(info)) { 2062 btrfs_calc_zone_unusable(cache); 2063 /* Should not have any excluded extents. Just in case, though. */ 2064 btrfs_free_excluded_extents(cache); 2065 } else if (cache->length == cache->used) { 2066 cache->last_byte_to_unpin = (u64)-1; 2067 cache->cached = BTRFS_CACHE_FINISHED; 2068 btrfs_free_excluded_extents(cache); 2069 } else if (cache->used == 0) { 2070 cache->last_byte_to_unpin = (u64)-1; 2071 cache->cached = BTRFS_CACHE_FINISHED; 2072 add_new_free_space(cache, cache->start, 2073 cache->start + cache->length); 2074 btrfs_free_excluded_extents(cache); 2075 } 2076 2077 ret = btrfs_add_block_group_cache(info, cache); 2078 if (ret) { 2079 btrfs_remove_free_space_cache(cache); 2080 goto error; 2081 } 2082 trace_btrfs_add_block_group(info, cache, 0); 2083 btrfs_update_space_info(info, cache->flags, cache->length, 2084 cache->used, cache->bytes_super, 2085 cache->zone_unusable, &space_info); 2086 2087 cache->space_info = space_info; 2088 2089 link_block_group(cache); 2090 2091 set_avail_alloc_bits(info, cache->flags); 2092 if (btrfs_chunk_writeable(info, cache->start)) { 2093 if (cache->used == 0) { 2094 ASSERT(list_empty(&cache->bg_list)); 2095 if (btrfs_test_opt(info, DISCARD_ASYNC)) 2096 btrfs_discard_queue_work(&info->discard_ctl, cache); 2097 else 2098 btrfs_mark_bg_unused(cache); 2099 } 2100 } else { 2101 inc_block_group_ro(cache, 1); 2102 } 2103 2104 return 0; 2105 error: 2106 btrfs_put_block_group(cache); 2107 return ret; 2108 } 2109 2110 static int fill_dummy_bgs(struct btrfs_fs_info *fs_info) 2111 { 2112 struct extent_map_tree *em_tree = &fs_info->mapping_tree; 2113 struct btrfs_space_info *space_info; 2114 struct rb_node *node; 2115 int ret = 0; 2116 2117 for (node = rb_first_cached(&em_tree->map); node; node = rb_next(node)) { 2118 struct extent_map *em; 2119 struct map_lookup *map; 2120 struct btrfs_block_group *bg; 2121 2122 em = rb_entry(node, struct extent_map, rb_node); 2123 map = em->map_lookup; 2124 bg = btrfs_create_block_group_cache(fs_info, em->start); 2125 if (!bg) { 2126 ret = -ENOMEM; 2127 break; 2128 } 2129 2130 /* Fill dummy cache as FULL */ 2131 bg->length = em->len; 2132 bg->flags = map->type; 2133 bg->last_byte_to_unpin = (u64)-1; 2134 bg->cached = BTRFS_CACHE_FINISHED; 2135 bg->used = em->len; 2136 bg->flags = map->type; 2137 ret = btrfs_add_block_group_cache(fs_info, bg); 2138 /* 2139 * We may have some valid block group cache added already, in 2140 * that case we skip to the next one. 2141 */ 2142 if (ret == -EEXIST) { 2143 ret = 0; 2144 btrfs_put_block_group(bg); 2145 continue; 2146 } 2147 2148 if (ret) { 2149 btrfs_remove_free_space_cache(bg); 2150 btrfs_put_block_group(bg); 2151 break; 2152 } 2153 2154 btrfs_update_space_info(fs_info, bg->flags, em->len, em->len, 2155 0, 0, &space_info); 2156 bg->space_info = space_info; 2157 link_block_group(bg); 2158 2159 set_avail_alloc_bits(fs_info, bg->flags); 2160 } 2161 if (!ret) 2162 btrfs_init_global_block_rsv(fs_info); 2163 return ret; 2164 } 2165 2166 int btrfs_read_block_groups(struct btrfs_fs_info *info) 2167 { 2168 struct btrfs_root *root = btrfs_block_group_root(info); 2169 struct btrfs_path *path; 2170 int ret; 2171 struct btrfs_block_group *cache; 2172 struct btrfs_space_info *space_info; 2173 struct btrfs_key key; 2174 int need_clear = 0; 2175 u64 cache_gen; 2176 2177 if (!root) 2178 return fill_dummy_bgs(info); 2179 2180 key.objectid = 0; 2181 key.offset = 0; 2182 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY; 2183 path = btrfs_alloc_path(); 2184 if (!path) 2185 return -ENOMEM; 2186 2187 cache_gen = btrfs_super_cache_generation(info->super_copy); 2188 if (btrfs_test_opt(info, SPACE_CACHE) && 2189 btrfs_super_generation(info->super_copy) != cache_gen) 2190 need_clear = 1; 2191 if (btrfs_test_opt(info, CLEAR_CACHE)) 2192 need_clear = 1; 2193 2194 while (1) { 2195 struct btrfs_block_group_item bgi; 2196 struct extent_buffer *leaf; 2197 int slot; 2198 2199 ret = find_first_block_group(info, path, &key); 2200 if (ret > 0) 2201 break; 2202 if (ret != 0) 2203 goto error; 2204 2205 leaf = path->nodes[0]; 2206 slot = path->slots[0]; 2207 2208 read_extent_buffer(leaf, &bgi, btrfs_item_ptr_offset(leaf, slot), 2209 sizeof(bgi)); 2210 2211 btrfs_item_key_to_cpu(leaf, &key, slot); 2212 btrfs_release_path(path); 2213 ret = read_one_block_group(info, &bgi, &key, need_clear); 2214 if (ret < 0) 2215 goto error; 2216 key.objectid += key.offset; 2217 key.offset = 0; 2218 } 2219 btrfs_release_path(path); 2220 2221 list_for_each_entry(space_info, &info->space_info, list) { 2222 int i; 2223 2224 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) { 2225 if (list_empty(&space_info->block_groups[i])) 2226 continue; 2227 cache = list_first_entry(&space_info->block_groups[i], 2228 struct btrfs_block_group, 2229 list); 2230 btrfs_sysfs_add_block_group_type(cache); 2231 } 2232 2233 if (!(btrfs_get_alloc_profile(info, space_info->flags) & 2234 (BTRFS_BLOCK_GROUP_RAID10 | 2235 BTRFS_BLOCK_GROUP_RAID1_MASK | 2236 BTRFS_BLOCK_GROUP_RAID56_MASK | 2237 BTRFS_BLOCK_GROUP_DUP))) 2238 continue; 2239 /* 2240 * Avoid allocating from un-mirrored block group if there are 2241 * mirrored block groups. 2242 */ 2243 list_for_each_entry(cache, 2244 &space_info->block_groups[BTRFS_RAID_RAID0], 2245 list) 2246 inc_block_group_ro(cache, 1); 2247 list_for_each_entry(cache, 2248 &space_info->block_groups[BTRFS_RAID_SINGLE], 2249 list) 2250 inc_block_group_ro(cache, 1); 2251 } 2252 2253 btrfs_init_global_block_rsv(info); 2254 ret = check_chunk_block_group_mappings(info); 2255 error: 2256 btrfs_free_path(path); 2257 /* 2258 * We've hit some error while reading the extent tree, and have 2259 * rescue=ibadroots mount option. 2260 * Try to fill the tree using dummy block groups so that the user can 2261 * continue to mount and grab their data. 2262 */ 2263 if (ret && btrfs_test_opt(info, IGNOREBADROOTS)) 2264 ret = fill_dummy_bgs(info); 2265 return ret; 2266 } 2267 2268 /* 2269 * This function, insert_block_group_item(), belongs to the phase 2 of chunk 2270 * allocation. 2271 * 2272 * See the comment at btrfs_chunk_alloc() for details about the chunk allocation 2273 * phases. 2274 */ 2275 static int insert_block_group_item(struct btrfs_trans_handle *trans, 2276 struct btrfs_block_group *block_group) 2277 { 2278 struct btrfs_fs_info *fs_info = trans->fs_info; 2279 struct btrfs_block_group_item bgi; 2280 struct btrfs_root *root = btrfs_block_group_root(fs_info); 2281 struct btrfs_key key; 2282 2283 spin_lock(&block_group->lock); 2284 btrfs_set_stack_block_group_used(&bgi, block_group->used); 2285 btrfs_set_stack_block_group_chunk_objectid(&bgi, 2286 BTRFS_FIRST_CHUNK_TREE_OBJECTID); 2287 btrfs_set_stack_block_group_flags(&bgi, block_group->flags); 2288 key.objectid = block_group->start; 2289 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY; 2290 key.offset = block_group->length; 2291 spin_unlock(&block_group->lock); 2292 2293 return btrfs_insert_item(trans, root, &key, &bgi, sizeof(bgi)); 2294 } 2295 2296 static int insert_dev_extent(struct btrfs_trans_handle *trans, 2297 struct btrfs_device *device, u64 chunk_offset, 2298 u64 start, u64 num_bytes) 2299 { 2300 struct btrfs_fs_info *fs_info = device->fs_info; 2301 struct btrfs_root *root = fs_info->dev_root; 2302 struct btrfs_path *path; 2303 struct btrfs_dev_extent *extent; 2304 struct extent_buffer *leaf; 2305 struct btrfs_key key; 2306 int ret; 2307 2308 WARN_ON(!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state)); 2309 WARN_ON(test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)); 2310 path = btrfs_alloc_path(); 2311 if (!path) 2312 return -ENOMEM; 2313 2314 key.objectid = device->devid; 2315 key.type = BTRFS_DEV_EXTENT_KEY; 2316 key.offset = start; 2317 ret = btrfs_insert_empty_item(trans, root, path, &key, sizeof(*extent)); 2318 if (ret) 2319 goto out; 2320 2321 leaf = path->nodes[0]; 2322 extent = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_extent); 2323 btrfs_set_dev_extent_chunk_tree(leaf, extent, BTRFS_CHUNK_TREE_OBJECTID); 2324 btrfs_set_dev_extent_chunk_objectid(leaf, extent, 2325 BTRFS_FIRST_CHUNK_TREE_OBJECTID); 2326 btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset); 2327 2328 btrfs_set_dev_extent_length(leaf, extent, num_bytes); 2329 btrfs_mark_buffer_dirty(leaf); 2330 out: 2331 btrfs_free_path(path); 2332 return ret; 2333 } 2334 2335 /* 2336 * This function belongs to phase 2. 2337 * 2338 * See the comment at btrfs_chunk_alloc() for details about the chunk allocation 2339 * phases. 2340 */ 2341 static int insert_dev_extents(struct btrfs_trans_handle *trans, 2342 u64 chunk_offset, u64 chunk_size) 2343 { 2344 struct btrfs_fs_info *fs_info = trans->fs_info; 2345 struct btrfs_device *device; 2346 struct extent_map *em; 2347 struct map_lookup *map; 2348 u64 dev_offset; 2349 u64 stripe_size; 2350 int i; 2351 int ret = 0; 2352 2353 em = btrfs_get_chunk_map(fs_info, chunk_offset, chunk_size); 2354 if (IS_ERR(em)) 2355 return PTR_ERR(em); 2356 2357 map = em->map_lookup; 2358 stripe_size = em->orig_block_len; 2359 2360 /* 2361 * Take the device list mutex to prevent races with the final phase of 2362 * a device replace operation that replaces the device object associated 2363 * with the map's stripes, because the device object's id can change 2364 * at any time during that final phase of the device replace operation 2365 * (dev-replace.c:btrfs_dev_replace_finishing()), so we could grab the 2366 * replaced device and then see it with an ID of BTRFS_DEV_REPLACE_DEVID, 2367 * resulting in persisting a device extent item with such ID. 2368 */ 2369 mutex_lock(&fs_info->fs_devices->device_list_mutex); 2370 for (i = 0; i < map->num_stripes; i++) { 2371 device = map->stripes[i].dev; 2372 dev_offset = map->stripes[i].physical; 2373 2374 ret = insert_dev_extent(trans, device, chunk_offset, dev_offset, 2375 stripe_size); 2376 if (ret) 2377 break; 2378 } 2379 mutex_unlock(&fs_info->fs_devices->device_list_mutex); 2380 2381 free_extent_map(em); 2382 return ret; 2383 } 2384 2385 /* 2386 * This function, btrfs_create_pending_block_groups(), belongs to the phase 2 of 2387 * chunk allocation. 2388 * 2389 * See the comment at btrfs_chunk_alloc() for details about the chunk allocation 2390 * phases. 2391 */ 2392 void btrfs_create_pending_block_groups(struct btrfs_trans_handle *trans) 2393 { 2394 struct btrfs_fs_info *fs_info = trans->fs_info; 2395 struct btrfs_block_group *block_group; 2396 int ret = 0; 2397 2398 while (!list_empty(&trans->new_bgs)) { 2399 int index; 2400 2401 block_group = list_first_entry(&trans->new_bgs, 2402 struct btrfs_block_group, 2403 bg_list); 2404 if (ret) 2405 goto next; 2406 2407 index = btrfs_bg_flags_to_raid_index(block_group->flags); 2408 2409 ret = insert_block_group_item(trans, block_group); 2410 if (ret) 2411 btrfs_abort_transaction(trans, ret); 2412 if (!block_group->chunk_item_inserted) { 2413 mutex_lock(&fs_info->chunk_mutex); 2414 ret = btrfs_chunk_alloc_add_chunk_item(trans, block_group); 2415 mutex_unlock(&fs_info->chunk_mutex); 2416 if (ret) 2417 btrfs_abort_transaction(trans, ret); 2418 } 2419 ret = insert_dev_extents(trans, block_group->start, 2420 block_group->length); 2421 if (ret) 2422 btrfs_abort_transaction(trans, ret); 2423 add_block_group_free_space(trans, block_group); 2424 2425 /* 2426 * If we restriped during balance, we may have added a new raid 2427 * type, so now add the sysfs entries when it is safe to do so. 2428 * We don't have to worry about locking here as it's handled in 2429 * btrfs_sysfs_add_block_group_type. 2430 */ 2431 if (block_group->space_info->block_group_kobjs[index] == NULL) 2432 btrfs_sysfs_add_block_group_type(block_group); 2433 2434 /* Already aborted the transaction if it failed. */ 2435 next: 2436 btrfs_delayed_refs_rsv_release(fs_info, 1); 2437 list_del_init(&block_group->bg_list); 2438 } 2439 btrfs_trans_release_chunk_metadata(trans); 2440 } 2441 2442 struct btrfs_block_group *btrfs_make_block_group(struct btrfs_trans_handle *trans, 2443 u64 bytes_used, u64 type, 2444 u64 chunk_offset, u64 size) 2445 { 2446 struct btrfs_fs_info *fs_info = trans->fs_info; 2447 struct btrfs_block_group *cache; 2448 int ret; 2449 2450 btrfs_set_log_full_commit(trans); 2451 2452 cache = btrfs_create_block_group_cache(fs_info, chunk_offset); 2453 if (!cache) 2454 return ERR_PTR(-ENOMEM); 2455 2456 cache->length = size; 2457 set_free_space_tree_thresholds(cache); 2458 cache->used = bytes_used; 2459 cache->flags = type; 2460 cache->last_byte_to_unpin = (u64)-1; 2461 cache->cached = BTRFS_CACHE_FINISHED; 2462 if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) 2463 cache->needs_free_space = 1; 2464 2465 ret = btrfs_load_block_group_zone_info(cache, true); 2466 if (ret) { 2467 btrfs_put_block_group(cache); 2468 return ERR_PTR(ret); 2469 } 2470 2471 /* 2472 * New block group is likely to be used soon. Try to activate it now. 2473 * Failure is OK for now. 2474 */ 2475 btrfs_zone_activate(cache); 2476 2477 ret = exclude_super_stripes(cache); 2478 if (ret) { 2479 /* We may have excluded something, so call this just in case */ 2480 btrfs_free_excluded_extents(cache); 2481 btrfs_put_block_group(cache); 2482 return ERR_PTR(ret); 2483 } 2484 2485 add_new_free_space(cache, chunk_offset, chunk_offset + size); 2486 2487 btrfs_free_excluded_extents(cache); 2488 2489 #ifdef CONFIG_BTRFS_DEBUG 2490 if (btrfs_should_fragment_free_space(cache)) { 2491 u64 new_bytes_used = size - bytes_used; 2492 2493 bytes_used += new_bytes_used >> 1; 2494 fragment_free_space(cache); 2495 } 2496 #endif 2497 /* 2498 * Ensure the corresponding space_info object is created and 2499 * assigned to our block group. We want our bg to be added to the rbtree 2500 * with its ->space_info set. 2501 */ 2502 cache->space_info = btrfs_find_space_info(fs_info, cache->flags); 2503 ASSERT(cache->space_info); 2504 2505 ret = btrfs_add_block_group_cache(fs_info, cache); 2506 if (ret) { 2507 btrfs_remove_free_space_cache(cache); 2508 btrfs_put_block_group(cache); 2509 return ERR_PTR(ret); 2510 } 2511 2512 /* 2513 * Now that our block group has its ->space_info set and is inserted in 2514 * the rbtree, update the space info's counters. 2515 */ 2516 trace_btrfs_add_block_group(fs_info, cache, 1); 2517 btrfs_update_space_info(fs_info, cache->flags, size, bytes_used, 2518 cache->bytes_super, cache->zone_unusable, 2519 &cache->space_info); 2520 btrfs_update_global_block_rsv(fs_info); 2521 2522 link_block_group(cache); 2523 2524 list_add_tail(&cache->bg_list, &trans->new_bgs); 2525 trans->delayed_ref_updates++; 2526 btrfs_update_delayed_refs_rsv(trans); 2527 2528 set_avail_alloc_bits(fs_info, type); 2529 return cache; 2530 } 2531 2532 /* 2533 * Mark one block group RO, can be called several times for the same block 2534 * group. 2535 * 2536 * @cache: the destination block group 2537 * @do_chunk_alloc: whether need to do chunk pre-allocation, this is to 2538 * ensure we still have some free space after marking this 2539 * block group RO. 2540 */ 2541 int btrfs_inc_block_group_ro(struct btrfs_block_group *cache, 2542 bool do_chunk_alloc) 2543 { 2544 struct btrfs_fs_info *fs_info = cache->fs_info; 2545 struct btrfs_trans_handle *trans; 2546 struct btrfs_root *root = btrfs_block_group_root(fs_info); 2547 u64 alloc_flags; 2548 int ret; 2549 bool dirty_bg_running; 2550 2551 do { 2552 trans = btrfs_join_transaction(root); 2553 if (IS_ERR(trans)) 2554 return PTR_ERR(trans); 2555 2556 dirty_bg_running = false; 2557 2558 /* 2559 * We're not allowed to set block groups readonly after the dirty 2560 * block group cache has started writing. If it already started, 2561 * back off and let this transaction commit. 2562 */ 2563 mutex_lock(&fs_info->ro_block_group_mutex); 2564 if (test_bit(BTRFS_TRANS_DIRTY_BG_RUN, &trans->transaction->flags)) { 2565 u64 transid = trans->transid; 2566 2567 mutex_unlock(&fs_info->ro_block_group_mutex); 2568 btrfs_end_transaction(trans); 2569 2570 ret = btrfs_wait_for_commit(fs_info, transid); 2571 if (ret) 2572 return ret; 2573 dirty_bg_running = true; 2574 } 2575 } while (dirty_bg_running); 2576 2577 if (do_chunk_alloc) { 2578 /* 2579 * If we are changing raid levels, try to allocate a 2580 * corresponding block group with the new raid level. 2581 */ 2582 alloc_flags = btrfs_get_alloc_profile(fs_info, cache->flags); 2583 if (alloc_flags != cache->flags) { 2584 ret = btrfs_chunk_alloc(trans, alloc_flags, 2585 CHUNK_ALLOC_FORCE); 2586 /* 2587 * ENOSPC is allowed here, we may have enough space 2588 * already allocated at the new raid level to carry on 2589 */ 2590 if (ret == -ENOSPC) 2591 ret = 0; 2592 if (ret < 0) 2593 goto out; 2594 } 2595 } 2596 2597 ret = inc_block_group_ro(cache, 0); 2598 if (!do_chunk_alloc || ret == -ETXTBSY) 2599 goto unlock_out; 2600 if (!ret) 2601 goto out; 2602 alloc_flags = btrfs_get_alloc_profile(fs_info, cache->space_info->flags); 2603 ret = btrfs_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE); 2604 if (ret < 0) 2605 goto out; 2606 ret = inc_block_group_ro(cache, 0); 2607 if (ret == -ETXTBSY) 2608 goto unlock_out; 2609 out: 2610 if (cache->flags & BTRFS_BLOCK_GROUP_SYSTEM) { 2611 alloc_flags = btrfs_get_alloc_profile(fs_info, cache->flags); 2612 mutex_lock(&fs_info->chunk_mutex); 2613 check_system_chunk(trans, alloc_flags); 2614 mutex_unlock(&fs_info->chunk_mutex); 2615 } 2616 unlock_out: 2617 mutex_unlock(&fs_info->ro_block_group_mutex); 2618 2619 btrfs_end_transaction(trans); 2620 return ret; 2621 } 2622 2623 void btrfs_dec_block_group_ro(struct btrfs_block_group *cache) 2624 { 2625 struct btrfs_space_info *sinfo = cache->space_info; 2626 u64 num_bytes; 2627 2628 BUG_ON(!cache->ro); 2629 2630 spin_lock(&sinfo->lock); 2631 spin_lock(&cache->lock); 2632 if (!--cache->ro) { 2633 if (btrfs_is_zoned(cache->fs_info)) { 2634 /* Migrate zone_unusable bytes back */ 2635 cache->zone_unusable = 2636 (cache->alloc_offset - cache->used) + 2637 (cache->length - cache->zone_capacity); 2638 sinfo->bytes_zone_unusable += cache->zone_unusable; 2639 sinfo->bytes_readonly -= cache->zone_unusable; 2640 } 2641 num_bytes = cache->length - cache->reserved - 2642 cache->pinned - cache->bytes_super - 2643 cache->zone_unusable - cache->used; 2644 sinfo->bytes_readonly -= num_bytes; 2645 list_del_init(&cache->ro_list); 2646 } 2647 spin_unlock(&cache->lock); 2648 spin_unlock(&sinfo->lock); 2649 } 2650 2651 static int update_block_group_item(struct btrfs_trans_handle *trans, 2652 struct btrfs_path *path, 2653 struct btrfs_block_group *cache) 2654 { 2655 struct btrfs_fs_info *fs_info = trans->fs_info; 2656 int ret; 2657 struct btrfs_root *root = btrfs_block_group_root(fs_info); 2658 unsigned long bi; 2659 struct extent_buffer *leaf; 2660 struct btrfs_block_group_item bgi; 2661 struct btrfs_key key; 2662 2663 key.objectid = cache->start; 2664 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY; 2665 key.offset = cache->length; 2666 2667 ret = btrfs_search_slot(trans, root, &key, path, 0, 1); 2668 if (ret) { 2669 if (ret > 0) 2670 ret = -ENOENT; 2671 goto fail; 2672 } 2673 2674 leaf = path->nodes[0]; 2675 bi = btrfs_item_ptr_offset(leaf, path->slots[0]); 2676 btrfs_set_stack_block_group_used(&bgi, cache->used); 2677 btrfs_set_stack_block_group_chunk_objectid(&bgi, 2678 BTRFS_FIRST_CHUNK_TREE_OBJECTID); 2679 btrfs_set_stack_block_group_flags(&bgi, cache->flags); 2680 write_extent_buffer(leaf, &bgi, bi, sizeof(bgi)); 2681 btrfs_mark_buffer_dirty(leaf); 2682 fail: 2683 btrfs_release_path(path); 2684 return ret; 2685 2686 } 2687 2688 static int cache_save_setup(struct btrfs_block_group *block_group, 2689 struct btrfs_trans_handle *trans, 2690 struct btrfs_path *path) 2691 { 2692 struct btrfs_fs_info *fs_info = block_group->fs_info; 2693 struct btrfs_root *root = fs_info->tree_root; 2694 struct inode *inode = NULL; 2695 struct extent_changeset *data_reserved = NULL; 2696 u64 alloc_hint = 0; 2697 int dcs = BTRFS_DC_ERROR; 2698 u64 cache_size = 0; 2699 int retries = 0; 2700 int ret = 0; 2701 2702 if (!btrfs_test_opt(fs_info, SPACE_CACHE)) 2703 return 0; 2704 2705 /* 2706 * If this block group is smaller than 100 megs don't bother caching the 2707 * block group. 2708 */ 2709 if (block_group->length < (100 * SZ_1M)) { 2710 spin_lock(&block_group->lock); 2711 block_group->disk_cache_state = BTRFS_DC_WRITTEN; 2712 spin_unlock(&block_group->lock); 2713 return 0; 2714 } 2715 2716 if (TRANS_ABORTED(trans)) 2717 return 0; 2718 again: 2719 inode = lookup_free_space_inode(block_group, path); 2720 if (IS_ERR(inode) && PTR_ERR(inode) != -ENOENT) { 2721 ret = PTR_ERR(inode); 2722 btrfs_release_path(path); 2723 goto out; 2724 } 2725 2726 if (IS_ERR(inode)) { 2727 BUG_ON(retries); 2728 retries++; 2729 2730 if (block_group->ro) 2731 goto out_free; 2732 2733 ret = create_free_space_inode(trans, block_group, path); 2734 if (ret) 2735 goto out_free; 2736 goto again; 2737 } 2738 2739 /* 2740 * We want to set the generation to 0, that way if anything goes wrong 2741 * from here on out we know not to trust this cache when we load up next 2742 * time. 2743 */ 2744 BTRFS_I(inode)->generation = 0; 2745 ret = btrfs_update_inode(trans, root, BTRFS_I(inode)); 2746 if (ret) { 2747 /* 2748 * So theoretically we could recover from this, simply set the 2749 * super cache generation to 0 so we know to invalidate the 2750 * cache, but then we'd have to keep track of the block groups 2751 * that fail this way so we know we _have_ to reset this cache 2752 * before the next commit or risk reading stale cache. So to 2753 * limit our exposure to horrible edge cases lets just abort the 2754 * transaction, this only happens in really bad situations 2755 * anyway. 2756 */ 2757 btrfs_abort_transaction(trans, ret); 2758 goto out_put; 2759 } 2760 WARN_ON(ret); 2761 2762 /* We've already setup this transaction, go ahead and exit */ 2763 if (block_group->cache_generation == trans->transid && 2764 i_size_read(inode)) { 2765 dcs = BTRFS_DC_SETUP; 2766 goto out_put; 2767 } 2768 2769 if (i_size_read(inode) > 0) { 2770 ret = btrfs_check_trunc_cache_free_space(fs_info, 2771 &fs_info->global_block_rsv); 2772 if (ret) 2773 goto out_put; 2774 2775 ret = btrfs_truncate_free_space_cache(trans, NULL, inode); 2776 if (ret) 2777 goto out_put; 2778 } 2779 2780 spin_lock(&block_group->lock); 2781 if (block_group->cached != BTRFS_CACHE_FINISHED || 2782 !btrfs_test_opt(fs_info, SPACE_CACHE)) { 2783 /* 2784 * don't bother trying to write stuff out _if_ 2785 * a) we're not cached, 2786 * b) we're with nospace_cache mount option, 2787 * c) we're with v2 space_cache (FREE_SPACE_TREE). 2788 */ 2789 dcs = BTRFS_DC_WRITTEN; 2790 spin_unlock(&block_group->lock); 2791 goto out_put; 2792 } 2793 spin_unlock(&block_group->lock); 2794 2795 /* 2796 * We hit an ENOSPC when setting up the cache in this transaction, just 2797 * skip doing the setup, we've already cleared the cache so we're safe. 2798 */ 2799 if (test_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags)) { 2800 ret = -ENOSPC; 2801 goto out_put; 2802 } 2803 2804 /* 2805 * Try to preallocate enough space based on how big the block group is. 2806 * Keep in mind this has to include any pinned space which could end up 2807 * taking up quite a bit since it's not folded into the other space 2808 * cache. 2809 */ 2810 cache_size = div_u64(block_group->length, SZ_256M); 2811 if (!cache_size) 2812 cache_size = 1; 2813 2814 cache_size *= 16; 2815 cache_size *= fs_info->sectorsize; 2816 2817 ret = btrfs_check_data_free_space(BTRFS_I(inode), &data_reserved, 0, 2818 cache_size); 2819 if (ret) 2820 goto out_put; 2821 2822 ret = btrfs_prealloc_file_range_trans(inode, trans, 0, 0, cache_size, 2823 cache_size, cache_size, 2824 &alloc_hint); 2825 /* 2826 * Our cache requires contiguous chunks so that we don't modify a bunch 2827 * of metadata or split extents when writing the cache out, which means 2828 * we can enospc if we are heavily fragmented in addition to just normal 2829 * out of space conditions. So if we hit this just skip setting up any 2830 * other block groups for this transaction, maybe we'll unpin enough 2831 * space the next time around. 2832 */ 2833 if (!ret) 2834 dcs = BTRFS_DC_SETUP; 2835 else if (ret == -ENOSPC) 2836 set_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags); 2837 2838 out_put: 2839 iput(inode); 2840 out_free: 2841 btrfs_release_path(path); 2842 out: 2843 spin_lock(&block_group->lock); 2844 if (!ret && dcs == BTRFS_DC_SETUP) 2845 block_group->cache_generation = trans->transid; 2846 block_group->disk_cache_state = dcs; 2847 spin_unlock(&block_group->lock); 2848 2849 extent_changeset_free(data_reserved); 2850 return ret; 2851 } 2852 2853 int btrfs_setup_space_cache(struct btrfs_trans_handle *trans) 2854 { 2855 struct btrfs_fs_info *fs_info = trans->fs_info; 2856 struct btrfs_block_group *cache, *tmp; 2857 struct btrfs_transaction *cur_trans = trans->transaction; 2858 struct btrfs_path *path; 2859 2860 if (list_empty(&cur_trans->dirty_bgs) || 2861 !btrfs_test_opt(fs_info, SPACE_CACHE)) 2862 return 0; 2863 2864 path = btrfs_alloc_path(); 2865 if (!path) 2866 return -ENOMEM; 2867 2868 /* Could add new block groups, use _safe just in case */ 2869 list_for_each_entry_safe(cache, tmp, &cur_trans->dirty_bgs, 2870 dirty_list) { 2871 if (cache->disk_cache_state == BTRFS_DC_CLEAR) 2872 cache_save_setup(cache, trans, path); 2873 } 2874 2875 btrfs_free_path(path); 2876 return 0; 2877 } 2878 2879 /* 2880 * Transaction commit does final block group cache writeback during a critical 2881 * section where nothing is allowed to change the FS. This is required in 2882 * order for the cache to actually match the block group, but can introduce a 2883 * lot of latency into the commit. 2884 * 2885 * So, btrfs_start_dirty_block_groups is here to kick off block group cache IO. 2886 * There's a chance we'll have to redo some of it if the block group changes 2887 * again during the commit, but it greatly reduces the commit latency by 2888 * getting rid of the easy block groups while we're still allowing others to 2889 * join the commit. 2890 */ 2891 int btrfs_start_dirty_block_groups(struct btrfs_trans_handle *trans) 2892 { 2893 struct btrfs_fs_info *fs_info = trans->fs_info; 2894 struct btrfs_block_group *cache; 2895 struct btrfs_transaction *cur_trans = trans->transaction; 2896 int ret = 0; 2897 int should_put; 2898 struct btrfs_path *path = NULL; 2899 LIST_HEAD(dirty); 2900 struct list_head *io = &cur_trans->io_bgs; 2901 int num_started = 0; 2902 int loops = 0; 2903 2904 spin_lock(&cur_trans->dirty_bgs_lock); 2905 if (list_empty(&cur_trans->dirty_bgs)) { 2906 spin_unlock(&cur_trans->dirty_bgs_lock); 2907 return 0; 2908 } 2909 list_splice_init(&cur_trans->dirty_bgs, &dirty); 2910 spin_unlock(&cur_trans->dirty_bgs_lock); 2911 2912 again: 2913 /* Make sure all the block groups on our dirty list actually exist */ 2914 btrfs_create_pending_block_groups(trans); 2915 2916 if (!path) { 2917 path = btrfs_alloc_path(); 2918 if (!path) { 2919 ret = -ENOMEM; 2920 goto out; 2921 } 2922 } 2923 2924 /* 2925 * cache_write_mutex is here only to save us from balance or automatic 2926 * removal of empty block groups deleting this block group while we are 2927 * writing out the cache 2928 */ 2929 mutex_lock(&trans->transaction->cache_write_mutex); 2930 while (!list_empty(&dirty)) { 2931 bool drop_reserve = true; 2932 2933 cache = list_first_entry(&dirty, struct btrfs_block_group, 2934 dirty_list); 2935 /* 2936 * This can happen if something re-dirties a block group that 2937 * is already under IO. Just wait for it to finish and then do 2938 * it all again 2939 */ 2940 if (!list_empty(&cache->io_list)) { 2941 list_del_init(&cache->io_list); 2942 btrfs_wait_cache_io(trans, cache, path); 2943 btrfs_put_block_group(cache); 2944 } 2945 2946 2947 /* 2948 * btrfs_wait_cache_io uses the cache->dirty_list to decide if 2949 * it should update the cache_state. Don't delete until after 2950 * we wait. 2951 * 2952 * Since we're not running in the commit critical section 2953 * we need the dirty_bgs_lock to protect from update_block_group 2954 */ 2955 spin_lock(&cur_trans->dirty_bgs_lock); 2956 list_del_init(&cache->dirty_list); 2957 spin_unlock(&cur_trans->dirty_bgs_lock); 2958 2959 should_put = 1; 2960 2961 cache_save_setup(cache, trans, path); 2962 2963 if (cache->disk_cache_state == BTRFS_DC_SETUP) { 2964 cache->io_ctl.inode = NULL; 2965 ret = btrfs_write_out_cache(trans, cache, path); 2966 if (ret == 0 && cache->io_ctl.inode) { 2967 num_started++; 2968 should_put = 0; 2969 2970 /* 2971 * The cache_write_mutex is protecting the 2972 * io_list, also refer to the definition of 2973 * btrfs_transaction::io_bgs for more details 2974 */ 2975 list_add_tail(&cache->io_list, io); 2976 } else { 2977 /* 2978 * If we failed to write the cache, the 2979 * generation will be bad and life goes on 2980 */ 2981 ret = 0; 2982 } 2983 } 2984 if (!ret) { 2985 ret = update_block_group_item(trans, path, cache); 2986 /* 2987 * Our block group might still be attached to the list 2988 * of new block groups in the transaction handle of some 2989 * other task (struct btrfs_trans_handle->new_bgs). This 2990 * means its block group item isn't yet in the extent 2991 * tree. If this happens ignore the error, as we will 2992 * try again later in the critical section of the 2993 * transaction commit. 2994 */ 2995 if (ret == -ENOENT) { 2996 ret = 0; 2997 spin_lock(&cur_trans->dirty_bgs_lock); 2998 if (list_empty(&cache->dirty_list)) { 2999 list_add_tail(&cache->dirty_list, 3000 &cur_trans->dirty_bgs); 3001 btrfs_get_block_group(cache); 3002 drop_reserve = false; 3003 } 3004 spin_unlock(&cur_trans->dirty_bgs_lock); 3005 } else if (ret) { 3006 btrfs_abort_transaction(trans, ret); 3007 } 3008 } 3009 3010 /* If it's not on the io list, we need to put the block group */ 3011 if (should_put) 3012 btrfs_put_block_group(cache); 3013 if (drop_reserve) 3014 btrfs_delayed_refs_rsv_release(fs_info, 1); 3015 /* 3016 * Avoid blocking other tasks for too long. It might even save 3017 * us from writing caches for block groups that are going to be 3018 * removed. 3019 */ 3020 mutex_unlock(&trans->transaction->cache_write_mutex); 3021 if (ret) 3022 goto out; 3023 mutex_lock(&trans->transaction->cache_write_mutex); 3024 } 3025 mutex_unlock(&trans->transaction->cache_write_mutex); 3026 3027 /* 3028 * Go through delayed refs for all the stuff we've just kicked off 3029 * and then loop back (just once) 3030 */ 3031 if (!ret) 3032 ret = btrfs_run_delayed_refs(trans, 0); 3033 if (!ret && loops == 0) { 3034 loops++; 3035 spin_lock(&cur_trans->dirty_bgs_lock); 3036 list_splice_init(&cur_trans->dirty_bgs, &dirty); 3037 /* 3038 * dirty_bgs_lock protects us from concurrent block group 3039 * deletes too (not just cache_write_mutex). 3040 */ 3041 if (!list_empty(&dirty)) { 3042 spin_unlock(&cur_trans->dirty_bgs_lock); 3043 goto again; 3044 } 3045 spin_unlock(&cur_trans->dirty_bgs_lock); 3046 } 3047 out: 3048 if (ret < 0) { 3049 spin_lock(&cur_trans->dirty_bgs_lock); 3050 list_splice_init(&dirty, &cur_trans->dirty_bgs); 3051 spin_unlock(&cur_trans->dirty_bgs_lock); 3052 btrfs_cleanup_dirty_bgs(cur_trans, fs_info); 3053 } 3054 3055 btrfs_free_path(path); 3056 return ret; 3057 } 3058 3059 int btrfs_write_dirty_block_groups(struct btrfs_trans_handle *trans) 3060 { 3061 struct btrfs_fs_info *fs_info = trans->fs_info; 3062 struct btrfs_block_group *cache; 3063 struct btrfs_transaction *cur_trans = trans->transaction; 3064 int ret = 0; 3065 int should_put; 3066 struct btrfs_path *path; 3067 struct list_head *io = &cur_trans->io_bgs; 3068 int num_started = 0; 3069 3070 path = btrfs_alloc_path(); 3071 if (!path) 3072 return -ENOMEM; 3073 3074 /* 3075 * Even though we are in the critical section of the transaction commit, 3076 * we can still have concurrent tasks adding elements to this 3077 * transaction's list of dirty block groups. These tasks correspond to 3078 * endio free space workers started when writeback finishes for a 3079 * space cache, which run inode.c:btrfs_finish_ordered_io(), and can 3080 * allocate new block groups as a result of COWing nodes of the root 3081 * tree when updating the free space inode. The writeback for the space 3082 * caches is triggered by an earlier call to 3083 * btrfs_start_dirty_block_groups() and iterations of the following 3084 * loop. 3085 * Also we want to do the cache_save_setup first and then run the 3086 * delayed refs to make sure we have the best chance at doing this all 3087 * in one shot. 3088 */ 3089 spin_lock(&cur_trans->dirty_bgs_lock); 3090 while (!list_empty(&cur_trans->dirty_bgs)) { 3091 cache = list_first_entry(&cur_trans->dirty_bgs, 3092 struct btrfs_block_group, 3093 dirty_list); 3094 3095 /* 3096 * This can happen if cache_save_setup re-dirties a block group 3097 * that is already under IO. Just wait for it to finish and 3098 * then do it all again 3099 */ 3100 if (!list_empty(&cache->io_list)) { 3101 spin_unlock(&cur_trans->dirty_bgs_lock); 3102 list_del_init(&cache->io_list); 3103 btrfs_wait_cache_io(trans, cache, path); 3104 btrfs_put_block_group(cache); 3105 spin_lock(&cur_trans->dirty_bgs_lock); 3106 } 3107 3108 /* 3109 * Don't remove from the dirty list until after we've waited on 3110 * any pending IO 3111 */ 3112 list_del_init(&cache->dirty_list); 3113 spin_unlock(&cur_trans->dirty_bgs_lock); 3114 should_put = 1; 3115 3116 cache_save_setup(cache, trans, path); 3117 3118 if (!ret) 3119 ret = btrfs_run_delayed_refs(trans, 3120 (unsigned long) -1); 3121 3122 if (!ret && cache->disk_cache_state == BTRFS_DC_SETUP) { 3123 cache->io_ctl.inode = NULL; 3124 ret = btrfs_write_out_cache(trans, cache, path); 3125 if (ret == 0 && cache->io_ctl.inode) { 3126 num_started++; 3127 should_put = 0; 3128 list_add_tail(&cache->io_list, io); 3129 } else { 3130 /* 3131 * If we failed to write the cache, the 3132 * generation will be bad and life goes on 3133 */ 3134 ret = 0; 3135 } 3136 } 3137 if (!ret) { 3138 ret = update_block_group_item(trans, path, cache); 3139 /* 3140 * One of the free space endio workers might have 3141 * created a new block group while updating a free space 3142 * cache's inode (at inode.c:btrfs_finish_ordered_io()) 3143 * and hasn't released its transaction handle yet, in 3144 * which case the new block group is still attached to 3145 * its transaction handle and its creation has not 3146 * finished yet (no block group item in the extent tree 3147 * yet, etc). If this is the case, wait for all free 3148 * space endio workers to finish and retry. This is a 3149 * very rare case so no need for a more efficient and 3150 * complex approach. 3151 */ 3152 if (ret == -ENOENT) { 3153 wait_event(cur_trans->writer_wait, 3154 atomic_read(&cur_trans->num_writers) == 1); 3155 ret = update_block_group_item(trans, path, cache); 3156 } 3157 if (ret) 3158 btrfs_abort_transaction(trans, ret); 3159 } 3160 3161 /* If its not on the io list, we need to put the block group */ 3162 if (should_put) 3163 btrfs_put_block_group(cache); 3164 btrfs_delayed_refs_rsv_release(fs_info, 1); 3165 spin_lock(&cur_trans->dirty_bgs_lock); 3166 } 3167 spin_unlock(&cur_trans->dirty_bgs_lock); 3168 3169 /* 3170 * Refer to the definition of io_bgs member for details why it's safe 3171 * to use it without any locking 3172 */ 3173 while (!list_empty(io)) { 3174 cache = list_first_entry(io, struct btrfs_block_group, 3175 io_list); 3176 list_del_init(&cache->io_list); 3177 btrfs_wait_cache_io(trans, cache, path); 3178 btrfs_put_block_group(cache); 3179 } 3180 3181 btrfs_free_path(path); 3182 return ret; 3183 } 3184 3185 int btrfs_update_block_group(struct btrfs_trans_handle *trans, 3186 u64 bytenr, u64 num_bytes, bool alloc) 3187 { 3188 struct btrfs_fs_info *info = trans->fs_info; 3189 struct btrfs_block_group *cache = NULL; 3190 u64 total = num_bytes; 3191 u64 old_val; 3192 u64 byte_in_group; 3193 int factor; 3194 int ret = 0; 3195 3196 /* Block accounting for super block */ 3197 spin_lock(&info->delalloc_root_lock); 3198 old_val = btrfs_super_bytes_used(info->super_copy); 3199 if (alloc) 3200 old_val += num_bytes; 3201 else 3202 old_val -= num_bytes; 3203 btrfs_set_super_bytes_used(info->super_copy, old_val); 3204 spin_unlock(&info->delalloc_root_lock); 3205 3206 while (total) { 3207 cache = btrfs_lookup_block_group(info, bytenr); 3208 if (!cache) { 3209 ret = -ENOENT; 3210 break; 3211 } 3212 factor = btrfs_bg_type_to_factor(cache->flags); 3213 3214 /* 3215 * If this block group has free space cache written out, we 3216 * need to make sure to load it if we are removing space. This 3217 * is because we need the unpinning stage to actually add the 3218 * space back to the block group, otherwise we will leak space. 3219 */ 3220 if (!alloc && !btrfs_block_group_done(cache)) 3221 btrfs_cache_block_group(cache, 1); 3222 3223 byte_in_group = bytenr - cache->start; 3224 WARN_ON(byte_in_group > cache->length); 3225 3226 spin_lock(&cache->space_info->lock); 3227 spin_lock(&cache->lock); 3228 3229 if (btrfs_test_opt(info, SPACE_CACHE) && 3230 cache->disk_cache_state < BTRFS_DC_CLEAR) 3231 cache->disk_cache_state = BTRFS_DC_CLEAR; 3232 3233 old_val = cache->used; 3234 num_bytes = min(total, cache->length - byte_in_group); 3235 if (alloc) { 3236 old_val += num_bytes; 3237 cache->used = old_val; 3238 cache->reserved -= num_bytes; 3239 cache->space_info->bytes_reserved -= num_bytes; 3240 cache->space_info->bytes_used += num_bytes; 3241 cache->space_info->disk_used += num_bytes * factor; 3242 spin_unlock(&cache->lock); 3243 spin_unlock(&cache->space_info->lock); 3244 } else { 3245 old_val -= num_bytes; 3246 cache->used = old_val; 3247 cache->pinned += num_bytes; 3248 btrfs_space_info_update_bytes_pinned(info, 3249 cache->space_info, num_bytes); 3250 cache->space_info->bytes_used -= num_bytes; 3251 cache->space_info->disk_used -= num_bytes * factor; 3252 spin_unlock(&cache->lock); 3253 spin_unlock(&cache->space_info->lock); 3254 3255 set_extent_dirty(&trans->transaction->pinned_extents, 3256 bytenr, bytenr + num_bytes - 1, 3257 GFP_NOFS | __GFP_NOFAIL); 3258 } 3259 3260 spin_lock(&trans->transaction->dirty_bgs_lock); 3261 if (list_empty(&cache->dirty_list)) { 3262 list_add_tail(&cache->dirty_list, 3263 &trans->transaction->dirty_bgs); 3264 trans->delayed_ref_updates++; 3265 btrfs_get_block_group(cache); 3266 } 3267 spin_unlock(&trans->transaction->dirty_bgs_lock); 3268 3269 /* 3270 * No longer have used bytes in this block group, queue it for 3271 * deletion. We do this after adding the block group to the 3272 * dirty list to avoid races between cleaner kthread and space 3273 * cache writeout. 3274 */ 3275 if (!alloc && old_val == 0) { 3276 if (!btrfs_test_opt(info, DISCARD_ASYNC)) 3277 btrfs_mark_bg_unused(cache); 3278 } 3279 3280 btrfs_put_block_group(cache); 3281 total -= num_bytes; 3282 bytenr += num_bytes; 3283 } 3284 3285 /* Modified block groups are accounted for in the delayed_refs_rsv. */ 3286 btrfs_update_delayed_refs_rsv(trans); 3287 return ret; 3288 } 3289 3290 /** 3291 * btrfs_add_reserved_bytes - update the block_group and space info counters 3292 * @cache: The cache we are manipulating 3293 * @ram_bytes: The number of bytes of file content, and will be same to 3294 * @num_bytes except for the compress path. 3295 * @num_bytes: The number of bytes in question 3296 * @delalloc: The blocks are allocated for the delalloc write 3297 * 3298 * This is called by the allocator when it reserves space. If this is a 3299 * reservation and the block group has become read only we cannot make the 3300 * reservation and return -EAGAIN, otherwise this function always succeeds. 3301 */ 3302 int btrfs_add_reserved_bytes(struct btrfs_block_group *cache, 3303 u64 ram_bytes, u64 num_bytes, int delalloc) 3304 { 3305 struct btrfs_space_info *space_info = cache->space_info; 3306 int ret = 0; 3307 3308 spin_lock(&space_info->lock); 3309 spin_lock(&cache->lock); 3310 if (cache->ro) { 3311 ret = -EAGAIN; 3312 } else { 3313 cache->reserved += num_bytes; 3314 space_info->bytes_reserved += num_bytes; 3315 trace_btrfs_space_reservation(cache->fs_info, "space_info", 3316 space_info->flags, num_bytes, 1); 3317 btrfs_space_info_update_bytes_may_use(cache->fs_info, 3318 space_info, -ram_bytes); 3319 if (delalloc) 3320 cache->delalloc_bytes += num_bytes; 3321 3322 /* 3323 * Compression can use less space than we reserved, so wake 3324 * tickets if that happens 3325 */ 3326 if (num_bytes < ram_bytes) 3327 btrfs_try_granting_tickets(cache->fs_info, space_info); 3328 } 3329 spin_unlock(&cache->lock); 3330 spin_unlock(&space_info->lock); 3331 return ret; 3332 } 3333 3334 /** 3335 * btrfs_free_reserved_bytes - update the block_group and space info counters 3336 * @cache: The cache we are manipulating 3337 * @num_bytes: The number of bytes in question 3338 * @delalloc: The blocks are allocated for the delalloc write 3339 * 3340 * This is called by somebody who is freeing space that was never actually used 3341 * on disk. For example if you reserve some space for a new leaf in transaction 3342 * A and before transaction A commits you free that leaf, you call this with 3343 * reserve set to 0 in order to clear the reservation. 3344 */ 3345 void btrfs_free_reserved_bytes(struct btrfs_block_group *cache, 3346 u64 num_bytes, int delalloc) 3347 { 3348 struct btrfs_space_info *space_info = cache->space_info; 3349 3350 spin_lock(&space_info->lock); 3351 spin_lock(&cache->lock); 3352 if (cache->ro) 3353 space_info->bytes_readonly += num_bytes; 3354 cache->reserved -= num_bytes; 3355 space_info->bytes_reserved -= num_bytes; 3356 space_info->max_extent_size = 0; 3357 3358 if (delalloc) 3359 cache->delalloc_bytes -= num_bytes; 3360 spin_unlock(&cache->lock); 3361 3362 btrfs_try_granting_tickets(cache->fs_info, space_info); 3363 spin_unlock(&space_info->lock); 3364 } 3365 3366 static void force_metadata_allocation(struct btrfs_fs_info *info) 3367 { 3368 struct list_head *head = &info->space_info; 3369 struct btrfs_space_info *found; 3370 3371 list_for_each_entry(found, head, list) { 3372 if (found->flags & BTRFS_BLOCK_GROUP_METADATA) 3373 found->force_alloc = CHUNK_ALLOC_FORCE; 3374 } 3375 } 3376 3377 static int should_alloc_chunk(struct btrfs_fs_info *fs_info, 3378 struct btrfs_space_info *sinfo, int force) 3379 { 3380 u64 bytes_used = btrfs_space_info_used(sinfo, false); 3381 u64 thresh; 3382 3383 if (force == CHUNK_ALLOC_FORCE) 3384 return 1; 3385 3386 /* 3387 * in limited mode, we want to have some free space up to 3388 * about 1% of the FS size. 3389 */ 3390 if (force == CHUNK_ALLOC_LIMITED) { 3391 thresh = btrfs_super_total_bytes(fs_info->super_copy); 3392 thresh = max_t(u64, SZ_64M, div_factor_fine(thresh, 1)); 3393 3394 if (sinfo->total_bytes - bytes_used < thresh) 3395 return 1; 3396 } 3397 3398 if (bytes_used + SZ_2M < div_factor(sinfo->total_bytes, 8)) 3399 return 0; 3400 return 1; 3401 } 3402 3403 int btrfs_force_chunk_alloc(struct btrfs_trans_handle *trans, u64 type) 3404 { 3405 u64 alloc_flags = btrfs_get_alloc_profile(trans->fs_info, type); 3406 3407 return btrfs_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE); 3408 } 3409 3410 static int do_chunk_alloc(struct btrfs_trans_handle *trans, u64 flags) 3411 { 3412 struct btrfs_block_group *bg; 3413 int ret; 3414 3415 /* 3416 * Check if we have enough space in the system space info because we 3417 * will need to update device items in the chunk btree and insert a new 3418 * chunk item in the chunk btree as well. This will allocate a new 3419 * system block group if needed. 3420 */ 3421 check_system_chunk(trans, flags); 3422 3423 bg = btrfs_create_chunk(trans, flags); 3424 if (IS_ERR(bg)) { 3425 ret = PTR_ERR(bg); 3426 goto out; 3427 } 3428 3429 ret = btrfs_chunk_alloc_add_chunk_item(trans, bg); 3430 /* 3431 * Normally we are not expected to fail with -ENOSPC here, since we have 3432 * previously reserved space in the system space_info and allocated one 3433 * new system chunk if necessary. However there are three exceptions: 3434 * 3435 * 1) We may have enough free space in the system space_info but all the 3436 * existing system block groups have a profile which can not be used 3437 * for extent allocation. 3438 * 3439 * This happens when mounting in degraded mode. For example we have a 3440 * RAID1 filesystem with 2 devices, lose one device and mount the fs 3441 * using the other device in degraded mode. If we then allocate a chunk, 3442 * we may have enough free space in the existing system space_info, but 3443 * none of the block groups can be used for extent allocation since they 3444 * have a RAID1 profile, and because we are in degraded mode with a 3445 * single device, we are forced to allocate a new system chunk with a 3446 * SINGLE profile. Making check_system_chunk() iterate over all system 3447 * block groups and check if they have a usable profile and enough space 3448 * can be slow on very large filesystems, so we tolerate the -ENOSPC and 3449 * try again after forcing allocation of a new system chunk. Like this 3450 * we avoid paying the cost of that search in normal circumstances, when 3451 * we were not mounted in degraded mode; 3452 * 3453 * 2) We had enough free space info the system space_info, and one suitable 3454 * block group to allocate from when we called check_system_chunk() 3455 * above. However right after we called it, the only system block group 3456 * with enough free space got turned into RO mode by a running scrub, 3457 * and in this case we have to allocate a new one and retry. We only 3458 * need do this allocate and retry once, since we have a transaction 3459 * handle and scrub uses the commit root to search for block groups; 3460 * 3461 * 3) We had one system block group with enough free space when we called 3462 * check_system_chunk(), but after that, right before we tried to 3463 * allocate the last extent buffer we needed, a discard operation came 3464 * in and it temporarily removed the last free space entry from the 3465 * block group (discard removes a free space entry, discards it, and 3466 * then adds back the entry to the block group cache). 3467 */ 3468 if (ret == -ENOSPC) { 3469 const u64 sys_flags = btrfs_system_alloc_profile(trans->fs_info); 3470 struct btrfs_block_group *sys_bg; 3471 3472 sys_bg = btrfs_create_chunk(trans, sys_flags); 3473 if (IS_ERR(sys_bg)) { 3474 ret = PTR_ERR(sys_bg); 3475 btrfs_abort_transaction(trans, ret); 3476 goto out; 3477 } 3478 3479 ret = btrfs_chunk_alloc_add_chunk_item(trans, sys_bg); 3480 if (ret) { 3481 btrfs_abort_transaction(trans, ret); 3482 goto out; 3483 } 3484 3485 ret = btrfs_chunk_alloc_add_chunk_item(trans, bg); 3486 if (ret) { 3487 btrfs_abort_transaction(trans, ret); 3488 goto out; 3489 } 3490 } else if (ret) { 3491 btrfs_abort_transaction(trans, ret); 3492 goto out; 3493 } 3494 out: 3495 btrfs_trans_release_chunk_metadata(trans); 3496 3497 return ret; 3498 } 3499 3500 /* 3501 * Chunk allocation is done in 2 phases: 3502 * 3503 * 1) Phase 1 - through btrfs_chunk_alloc() we allocate device extents for 3504 * the chunk, the chunk mapping, create its block group and add the items 3505 * that belong in the chunk btree to it - more specifically, we need to 3506 * update device items in the chunk btree and add a new chunk item to it. 3507 * 3508 * 2) Phase 2 - through btrfs_create_pending_block_groups(), we add the block 3509 * group item to the extent btree and the device extent items to the devices 3510 * btree. 3511 * 3512 * This is done to prevent deadlocks. For example when COWing a node from the 3513 * extent btree we are holding a write lock on the node's parent and if we 3514 * trigger chunk allocation and attempted to insert the new block group item 3515 * in the extent btree right way, we could deadlock because the path for the 3516 * insertion can include that parent node. At first glance it seems impossible 3517 * to trigger chunk allocation after starting a transaction since tasks should 3518 * reserve enough transaction units (metadata space), however while that is true 3519 * most of the time, chunk allocation may still be triggered for several reasons: 3520 * 3521 * 1) When reserving metadata, we check if there is enough free space in the 3522 * metadata space_info and therefore don't trigger allocation of a new chunk. 3523 * However later when the task actually tries to COW an extent buffer from 3524 * the extent btree or from the device btree for example, it is forced to 3525 * allocate a new block group (chunk) because the only one that had enough 3526 * free space was just turned to RO mode by a running scrub for example (or 3527 * device replace, block group reclaim thread, etc), so we can not use it 3528 * for allocating an extent and end up being forced to allocate a new one; 3529 * 3530 * 2) Because we only check that the metadata space_info has enough free bytes, 3531 * we end up not allocating a new metadata chunk in that case. However if 3532 * the filesystem was mounted in degraded mode, none of the existing block 3533 * groups might be suitable for extent allocation due to their incompatible 3534 * profile (for e.g. mounting a 2 devices filesystem, where all block groups 3535 * use a RAID1 profile, in degraded mode using a single device). In this case 3536 * when the task attempts to COW some extent buffer of the extent btree for 3537 * example, it will trigger allocation of a new metadata block group with a 3538 * suitable profile (SINGLE profile in the example of the degraded mount of 3539 * the RAID1 filesystem); 3540 * 3541 * 3) The task has reserved enough transaction units / metadata space, but when 3542 * it attempts to COW an extent buffer from the extent or device btree for 3543 * example, it does not find any free extent in any metadata block group, 3544 * therefore forced to try to allocate a new metadata block group. 3545 * This is because some other task allocated all available extents in the 3546 * meanwhile - this typically happens with tasks that don't reserve space 3547 * properly, either intentionally or as a bug. One example where this is 3548 * done intentionally is fsync, as it does not reserve any transaction units 3549 * and ends up allocating a variable number of metadata extents for log 3550 * tree extent buffers; 3551 * 3552 * 4) The task has reserved enough transaction units / metadata space, but right 3553 * before it tries to allocate the last extent buffer it needs, a discard 3554 * operation comes in and, temporarily, removes the last free space entry from 3555 * the only metadata block group that had free space (discard starts by 3556 * removing a free space entry from a block group, then does the discard 3557 * operation and, once it's done, it adds back the free space entry to the 3558 * block group). 3559 * 3560 * We also need this 2 phases setup when adding a device to a filesystem with 3561 * a seed device - we must create new metadata and system chunks without adding 3562 * any of the block group items to the chunk, extent and device btrees. If we 3563 * did not do it this way, we would get ENOSPC when attempting to update those 3564 * btrees, since all the chunks from the seed device are read-only. 3565 * 3566 * Phase 1 does the updates and insertions to the chunk btree because if we had 3567 * it done in phase 2 and have a thundering herd of tasks allocating chunks in 3568 * parallel, we risk having too many system chunks allocated by many tasks if 3569 * many tasks reach phase 1 without the previous ones completing phase 2. In the 3570 * extreme case this leads to exhaustion of the system chunk array in the 3571 * superblock. This is easier to trigger if using a btree node/leaf size of 64K 3572 * and with RAID filesystems (so we have more device items in the chunk btree). 3573 * This has happened before and commit eafa4fd0ad0607 ("btrfs: fix exhaustion of 3574 * the system chunk array due to concurrent allocations") provides more details. 3575 * 3576 * Allocation of system chunks does not happen through this function. A task that 3577 * needs to update the chunk btree (the only btree that uses system chunks), must 3578 * preallocate chunk space by calling either check_system_chunk() or 3579 * btrfs_reserve_chunk_metadata() - the former is used when allocating a data or 3580 * metadata chunk or when removing a chunk, while the later is used before doing 3581 * a modification to the chunk btree - use cases for the later are adding, 3582 * removing and resizing a device as well as relocation of a system chunk. 3583 * See the comment below for more details. 3584 * 3585 * The reservation of system space, done through check_system_chunk(), as well 3586 * as all the updates and insertions into the chunk btree must be done while 3587 * holding fs_info->chunk_mutex. This is important to guarantee that while COWing 3588 * an extent buffer from the chunks btree we never trigger allocation of a new 3589 * system chunk, which would result in a deadlock (trying to lock twice an 3590 * extent buffer of the chunk btree, first time before triggering the chunk 3591 * allocation and the second time during chunk allocation while attempting to 3592 * update the chunks btree). The system chunk array is also updated while holding 3593 * that mutex. The same logic applies to removing chunks - we must reserve system 3594 * space, update the chunk btree and the system chunk array in the superblock 3595 * while holding fs_info->chunk_mutex. 3596 * 3597 * This function, btrfs_chunk_alloc(), belongs to phase 1. 3598 * 3599 * If @force is CHUNK_ALLOC_FORCE: 3600 * - return 1 if it successfully allocates a chunk, 3601 * - return errors including -ENOSPC otherwise. 3602 * If @force is NOT CHUNK_ALLOC_FORCE: 3603 * - return 0 if it doesn't need to allocate a new chunk, 3604 * - return 1 if it successfully allocates a chunk, 3605 * - return errors including -ENOSPC otherwise. 3606 */ 3607 int btrfs_chunk_alloc(struct btrfs_trans_handle *trans, u64 flags, 3608 enum btrfs_chunk_alloc_enum force) 3609 { 3610 struct btrfs_fs_info *fs_info = trans->fs_info; 3611 struct btrfs_space_info *space_info; 3612 bool wait_for_alloc = false; 3613 bool should_alloc = false; 3614 int ret = 0; 3615 3616 /* Don't re-enter if we're already allocating a chunk */ 3617 if (trans->allocating_chunk) 3618 return -ENOSPC; 3619 /* 3620 * Allocation of system chunks can not happen through this path, as we 3621 * could end up in a deadlock if we are allocating a data or metadata 3622 * chunk and there is another task modifying the chunk btree. 3623 * 3624 * This is because while we are holding the chunk mutex, we will attempt 3625 * to add the new chunk item to the chunk btree or update an existing 3626 * device item in the chunk btree, while the other task that is modifying 3627 * the chunk btree is attempting to COW an extent buffer while holding a 3628 * lock on it and on its parent - if the COW operation triggers a system 3629 * chunk allocation, then we can deadlock because we are holding the 3630 * chunk mutex and we may need to access that extent buffer or its parent 3631 * in order to add the chunk item or update a device item. 3632 * 3633 * Tasks that want to modify the chunk tree should reserve system space 3634 * before updating the chunk btree, by calling either 3635 * btrfs_reserve_chunk_metadata() or check_system_chunk(). 3636 * It's possible that after a task reserves the space, it still ends up 3637 * here - this happens in the cases described above at do_chunk_alloc(). 3638 * The task will have to either retry or fail. 3639 */ 3640 if (flags & BTRFS_BLOCK_GROUP_SYSTEM) 3641 return -ENOSPC; 3642 3643 space_info = btrfs_find_space_info(fs_info, flags); 3644 ASSERT(space_info); 3645 3646 do { 3647 spin_lock(&space_info->lock); 3648 if (force < space_info->force_alloc) 3649 force = space_info->force_alloc; 3650 should_alloc = should_alloc_chunk(fs_info, space_info, force); 3651 if (space_info->full) { 3652 /* No more free physical space */ 3653 if (should_alloc) 3654 ret = -ENOSPC; 3655 else 3656 ret = 0; 3657 spin_unlock(&space_info->lock); 3658 return ret; 3659 } else if (!should_alloc) { 3660 spin_unlock(&space_info->lock); 3661 return 0; 3662 } else if (space_info->chunk_alloc) { 3663 /* 3664 * Someone is already allocating, so we need to block 3665 * until this someone is finished and then loop to 3666 * recheck if we should continue with our allocation 3667 * attempt. 3668 */ 3669 wait_for_alloc = true; 3670 spin_unlock(&space_info->lock); 3671 mutex_lock(&fs_info->chunk_mutex); 3672 mutex_unlock(&fs_info->chunk_mutex); 3673 } else { 3674 /* Proceed with allocation */ 3675 space_info->chunk_alloc = 1; 3676 wait_for_alloc = false; 3677 spin_unlock(&space_info->lock); 3678 } 3679 3680 cond_resched(); 3681 } while (wait_for_alloc); 3682 3683 mutex_lock(&fs_info->chunk_mutex); 3684 trans->allocating_chunk = true; 3685 3686 /* 3687 * If we have mixed data/metadata chunks we want to make sure we keep 3688 * allocating mixed chunks instead of individual chunks. 3689 */ 3690 if (btrfs_mixed_space_info(space_info)) 3691 flags |= (BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA); 3692 3693 /* 3694 * if we're doing a data chunk, go ahead and make sure that 3695 * we keep a reasonable number of metadata chunks allocated in the 3696 * FS as well. 3697 */ 3698 if (flags & BTRFS_BLOCK_GROUP_DATA && fs_info->metadata_ratio) { 3699 fs_info->data_chunk_allocations++; 3700 if (!(fs_info->data_chunk_allocations % 3701 fs_info->metadata_ratio)) 3702 force_metadata_allocation(fs_info); 3703 } 3704 3705 ret = do_chunk_alloc(trans, flags); 3706 trans->allocating_chunk = false; 3707 3708 spin_lock(&space_info->lock); 3709 if (ret < 0) { 3710 if (ret == -ENOSPC) 3711 space_info->full = 1; 3712 else 3713 goto out; 3714 } else { 3715 ret = 1; 3716 space_info->max_extent_size = 0; 3717 } 3718 3719 space_info->force_alloc = CHUNK_ALLOC_NO_FORCE; 3720 out: 3721 space_info->chunk_alloc = 0; 3722 spin_unlock(&space_info->lock); 3723 mutex_unlock(&fs_info->chunk_mutex); 3724 3725 return ret; 3726 } 3727 3728 static u64 get_profile_num_devs(struct btrfs_fs_info *fs_info, u64 type) 3729 { 3730 u64 num_dev; 3731 3732 num_dev = btrfs_raid_array[btrfs_bg_flags_to_raid_index(type)].devs_max; 3733 if (!num_dev) 3734 num_dev = fs_info->fs_devices->rw_devices; 3735 3736 return num_dev; 3737 } 3738 3739 static void reserve_chunk_space(struct btrfs_trans_handle *trans, 3740 u64 bytes, 3741 u64 type) 3742 { 3743 struct btrfs_fs_info *fs_info = trans->fs_info; 3744 struct btrfs_space_info *info; 3745 u64 left; 3746 int ret = 0; 3747 3748 /* 3749 * Needed because we can end up allocating a system chunk and for an 3750 * atomic and race free space reservation in the chunk block reserve. 3751 */ 3752 lockdep_assert_held(&fs_info->chunk_mutex); 3753 3754 info = btrfs_find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM); 3755 spin_lock(&info->lock); 3756 left = info->total_bytes - btrfs_space_info_used(info, true); 3757 spin_unlock(&info->lock); 3758 3759 if (left < bytes && btrfs_test_opt(fs_info, ENOSPC_DEBUG)) { 3760 btrfs_info(fs_info, "left=%llu, need=%llu, flags=%llu", 3761 left, bytes, type); 3762 btrfs_dump_space_info(fs_info, info, 0, 0); 3763 } 3764 3765 if (left < bytes) { 3766 u64 flags = btrfs_system_alloc_profile(fs_info); 3767 struct btrfs_block_group *bg; 3768 3769 /* 3770 * Ignore failure to create system chunk. We might end up not 3771 * needing it, as we might not need to COW all nodes/leafs from 3772 * the paths we visit in the chunk tree (they were already COWed 3773 * or created in the current transaction for example). 3774 */ 3775 bg = btrfs_create_chunk(trans, flags); 3776 if (IS_ERR(bg)) { 3777 ret = PTR_ERR(bg); 3778 } else { 3779 /* 3780 * If we fail to add the chunk item here, we end up 3781 * trying again at phase 2 of chunk allocation, at 3782 * btrfs_create_pending_block_groups(). So ignore 3783 * any error here. An ENOSPC here could happen, due to 3784 * the cases described at do_chunk_alloc() - the system 3785 * block group we just created was just turned into RO 3786 * mode by a scrub for example, or a running discard 3787 * temporarily removed its free space entries, etc. 3788 */ 3789 btrfs_chunk_alloc_add_chunk_item(trans, bg); 3790 } 3791 } 3792 3793 if (!ret) { 3794 ret = btrfs_block_rsv_add(fs_info, 3795 &fs_info->chunk_block_rsv, 3796 bytes, BTRFS_RESERVE_NO_FLUSH); 3797 if (!ret) 3798 trans->chunk_bytes_reserved += bytes; 3799 } 3800 } 3801 3802 /* 3803 * Reserve space in the system space for allocating or removing a chunk. 3804 * The caller must be holding fs_info->chunk_mutex. 3805 */ 3806 void check_system_chunk(struct btrfs_trans_handle *trans, u64 type) 3807 { 3808 struct btrfs_fs_info *fs_info = trans->fs_info; 3809 const u64 num_devs = get_profile_num_devs(fs_info, type); 3810 u64 bytes; 3811 3812 /* num_devs device items to update and 1 chunk item to add or remove. */ 3813 bytes = btrfs_calc_metadata_size(fs_info, num_devs) + 3814 btrfs_calc_insert_metadata_size(fs_info, 1); 3815 3816 reserve_chunk_space(trans, bytes, type); 3817 } 3818 3819 /* 3820 * Reserve space in the system space, if needed, for doing a modification to the 3821 * chunk btree. 3822 * 3823 * @trans: A transaction handle. 3824 * @is_item_insertion: Indicate if the modification is for inserting a new item 3825 * in the chunk btree or if it's for the deletion or update 3826 * of an existing item. 3827 * 3828 * This is used in a context where we need to update the chunk btree outside 3829 * block group allocation and removal, to avoid a deadlock with a concurrent 3830 * task that is allocating a metadata or data block group and therefore needs to 3831 * update the chunk btree while holding the chunk mutex. After the update to the 3832 * chunk btree is done, btrfs_trans_release_chunk_metadata() should be called. 3833 * 3834 */ 3835 void btrfs_reserve_chunk_metadata(struct btrfs_trans_handle *trans, 3836 bool is_item_insertion) 3837 { 3838 struct btrfs_fs_info *fs_info = trans->fs_info; 3839 u64 bytes; 3840 3841 if (is_item_insertion) 3842 bytes = btrfs_calc_insert_metadata_size(fs_info, 1); 3843 else 3844 bytes = btrfs_calc_metadata_size(fs_info, 1); 3845 3846 mutex_lock(&fs_info->chunk_mutex); 3847 reserve_chunk_space(trans, bytes, BTRFS_BLOCK_GROUP_SYSTEM); 3848 mutex_unlock(&fs_info->chunk_mutex); 3849 } 3850 3851 void btrfs_put_block_group_cache(struct btrfs_fs_info *info) 3852 { 3853 struct btrfs_block_group *block_group; 3854 u64 last = 0; 3855 3856 while (1) { 3857 struct inode *inode; 3858 3859 block_group = btrfs_lookup_first_block_group(info, last); 3860 while (block_group) { 3861 btrfs_wait_block_group_cache_done(block_group); 3862 spin_lock(&block_group->lock); 3863 if (block_group->iref) 3864 break; 3865 spin_unlock(&block_group->lock); 3866 block_group = btrfs_next_block_group(block_group); 3867 } 3868 if (!block_group) { 3869 if (last == 0) 3870 break; 3871 last = 0; 3872 continue; 3873 } 3874 3875 inode = block_group->inode; 3876 block_group->iref = 0; 3877 block_group->inode = NULL; 3878 spin_unlock(&block_group->lock); 3879 ASSERT(block_group->io_ctl.inode == NULL); 3880 iput(inode); 3881 last = block_group->start + block_group->length; 3882 btrfs_put_block_group(block_group); 3883 } 3884 } 3885 3886 /* 3887 * Must be called only after stopping all workers, since we could have block 3888 * group caching kthreads running, and therefore they could race with us if we 3889 * freed the block groups before stopping them. 3890 */ 3891 int btrfs_free_block_groups(struct btrfs_fs_info *info) 3892 { 3893 struct btrfs_block_group *block_group; 3894 struct btrfs_space_info *space_info; 3895 struct btrfs_caching_control *caching_ctl; 3896 struct rb_node *n; 3897 3898 spin_lock(&info->block_group_cache_lock); 3899 while (!list_empty(&info->caching_block_groups)) { 3900 caching_ctl = list_entry(info->caching_block_groups.next, 3901 struct btrfs_caching_control, list); 3902 list_del(&caching_ctl->list); 3903 btrfs_put_caching_control(caching_ctl); 3904 } 3905 spin_unlock(&info->block_group_cache_lock); 3906 3907 spin_lock(&info->unused_bgs_lock); 3908 while (!list_empty(&info->unused_bgs)) { 3909 block_group = list_first_entry(&info->unused_bgs, 3910 struct btrfs_block_group, 3911 bg_list); 3912 list_del_init(&block_group->bg_list); 3913 btrfs_put_block_group(block_group); 3914 } 3915 3916 while (!list_empty(&info->reclaim_bgs)) { 3917 block_group = list_first_entry(&info->reclaim_bgs, 3918 struct btrfs_block_group, 3919 bg_list); 3920 list_del_init(&block_group->bg_list); 3921 btrfs_put_block_group(block_group); 3922 } 3923 spin_unlock(&info->unused_bgs_lock); 3924 3925 spin_lock(&info->zone_active_bgs_lock); 3926 while (!list_empty(&info->zone_active_bgs)) { 3927 block_group = list_first_entry(&info->zone_active_bgs, 3928 struct btrfs_block_group, 3929 active_bg_list); 3930 list_del_init(&block_group->active_bg_list); 3931 btrfs_put_block_group(block_group); 3932 } 3933 spin_unlock(&info->zone_active_bgs_lock); 3934 3935 spin_lock(&info->block_group_cache_lock); 3936 while ((n = rb_last(&info->block_group_cache_tree)) != NULL) { 3937 block_group = rb_entry(n, struct btrfs_block_group, 3938 cache_node); 3939 rb_erase(&block_group->cache_node, 3940 &info->block_group_cache_tree); 3941 RB_CLEAR_NODE(&block_group->cache_node); 3942 spin_unlock(&info->block_group_cache_lock); 3943 3944 down_write(&block_group->space_info->groups_sem); 3945 list_del(&block_group->list); 3946 up_write(&block_group->space_info->groups_sem); 3947 3948 /* 3949 * We haven't cached this block group, which means we could 3950 * possibly have excluded extents on this block group. 3951 */ 3952 if (block_group->cached == BTRFS_CACHE_NO || 3953 block_group->cached == BTRFS_CACHE_ERROR) 3954 btrfs_free_excluded_extents(block_group); 3955 3956 btrfs_remove_free_space_cache(block_group); 3957 ASSERT(block_group->cached != BTRFS_CACHE_STARTED); 3958 ASSERT(list_empty(&block_group->dirty_list)); 3959 ASSERT(list_empty(&block_group->io_list)); 3960 ASSERT(list_empty(&block_group->bg_list)); 3961 ASSERT(refcount_read(&block_group->refs) == 1); 3962 ASSERT(block_group->swap_extents == 0); 3963 btrfs_put_block_group(block_group); 3964 3965 spin_lock(&info->block_group_cache_lock); 3966 } 3967 spin_unlock(&info->block_group_cache_lock); 3968 3969 btrfs_release_global_block_rsv(info); 3970 3971 while (!list_empty(&info->space_info)) { 3972 space_info = list_entry(info->space_info.next, 3973 struct btrfs_space_info, 3974 list); 3975 3976 /* 3977 * Do not hide this behind enospc_debug, this is actually 3978 * important and indicates a real bug if this happens. 3979 */ 3980 if (WARN_ON(space_info->bytes_pinned > 0 || 3981 space_info->bytes_reserved > 0 || 3982 space_info->bytes_may_use > 0)) 3983 btrfs_dump_space_info(info, space_info, 0, 0); 3984 WARN_ON(space_info->reclaim_size > 0); 3985 list_del(&space_info->list); 3986 btrfs_sysfs_remove_space_info(space_info); 3987 } 3988 return 0; 3989 } 3990 3991 void btrfs_freeze_block_group(struct btrfs_block_group *cache) 3992 { 3993 atomic_inc(&cache->frozen); 3994 } 3995 3996 void btrfs_unfreeze_block_group(struct btrfs_block_group *block_group) 3997 { 3998 struct btrfs_fs_info *fs_info = block_group->fs_info; 3999 struct extent_map_tree *em_tree; 4000 struct extent_map *em; 4001 bool cleanup; 4002 4003 spin_lock(&block_group->lock); 4004 cleanup = (atomic_dec_and_test(&block_group->frozen) && 4005 block_group->removed); 4006 spin_unlock(&block_group->lock); 4007 4008 if (cleanup) { 4009 em_tree = &fs_info->mapping_tree; 4010 write_lock(&em_tree->lock); 4011 em = lookup_extent_mapping(em_tree, block_group->start, 4012 1); 4013 BUG_ON(!em); /* logic error, can't happen */ 4014 remove_extent_mapping(em_tree, em); 4015 write_unlock(&em_tree->lock); 4016 4017 /* once for us and once for the tree */ 4018 free_extent_map(em); 4019 free_extent_map(em); 4020 4021 /* 4022 * We may have left one free space entry and other possible 4023 * tasks trimming this block group have left 1 entry each one. 4024 * Free them if any. 4025 */ 4026 __btrfs_remove_free_space_cache(block_group->free_space_ctl); 4027 } 4028 } 4029 4030 bool btrfs_inc_block_group_swap_extents(struct btrfs_block_group *bg) 4031 { 4032 bool ret = true; 4033 4034 spin_lock(&bg->lock); 4035 if (bg->ro) 4036 ret = false; 4037 else 4038 bg->swap_extents++; 4039 spin_unlock(&bg->lock); 4040 4041 return ret; 4042 } 4043 4044 void btrfs_dec_block_group_swap_extents(struct btrfs_block_group *bg, int amount) 4045 { 4046 spin_lock(&bg->lock); 4047 ASSERT(!bg->ro); 4048 ASSERT(bg->swap_extents >= amount); 4049 bg->swap_extents -= amount; 4050 spin_unlock(&bg->lock); 4051 } 4052