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