1 // SPDX-License-Identifier: GPL-2.0 2 3 #include <linux/sizes.h> 4 #include <linux/list_sort.h> 5 #include "misc.h" 6 #include "ctree.h" 7 #include "block-group.h" 8 #include "space-info.h" 9 #include "disk-io.h" 10 #include "free-space-cache.h" 11 #include "free-space-tree.h" 12 #include "volumes.h" 13 #include "transaction.h" 14 #include "ref-verify.h" 15 #include "sysfs.h" 16 #include "tree-log.h" 17 #include "delalloc-space.h" 18 #include "discard.h" 19 #include "raid56.h" 20 #include "zoned.h" 21 #include "fs.h" 22 #include "accessors.h" 23 #include "extent-tree.h" 24 25 #ifdef CONFIG_BTRFS_DEBUG 26 int btrfs_should_fragment_free_space(const struct btrfs_block_group *block_group) 27 { 28 struct btrfs_fs_info *fs_info = block_group->fs_info; 29 30 return (btrfs_test_opt(fs_info, FRAGMENT_METADATA) && 31 block_group->flags & BTRFS_BLOCK_GROUP_METADATA) || 32 (btrfs_test_opt(fs_info, FRAGMENT_DATA) && 33 block_group->flags & BTRFS_BLOCK_GROUP_DATA); 34 } 35 #endif 36 37 static inline bool has_unwritten_metadata(struct btrfs_block_group *block_group) 38 { 39 /* The meta_write_pointer is available only on the zoned setup. */ 40 if (!btrfs_is_zoned(block_group->fs_info)) 41 return false; 42 43 if (block_group->flags & BTRFS_BLOCK_GROUP_DATA) 44 return false; 45 46 return block_group->start + block_group->alloc_offset > 47 block_group->meta_write_pointer; 48 } 49 50 /* 51 * Return target flags in extended format or 0 if restripe for this chunk_type 52 * is not in progress 53 * 54 * Should be called with balance_lock held 55 */ 56 static u64 get_restripe_target(const struct btrfs_fs_info *fs_info, u64 flags) 57 { 58 const struct btrfs_balance_control *bctl = fs_info->balance_ctl; 59 u64 target = 0; 60 61 if (!bctl) 62 return 0; 63 64 if (flags & BTRFS_BLOCK_GROUP_DATA && 65 bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) { 66 target = BTRFS_BLOCK_GROUP_DATA | bctl->data.target; 67 } else if (flags & BTRFS_BLOCK_GROUP_SYSTEM && 68 bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) { 69 target = BTRFS_BLOCK_GROUP_SYSTEM | bctl->sys.target; 70 } else if (flags & BTRFS_BLOCK_GROUP_METADATA && 71 bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) { 72 target = BTRFS_BLOCK_GROUP_METADATA | bctl->meta.target; 73 } 74 75 return target; 76 } 77 78 /* 79 * @flags: available profiles in extended format (see ctree.h) 80 * 81 * Return reduced profile in chunk format. If profile changing is in progress 82 * (either running or paused) picks the target profile (if it's already 83 * available), otherwise falls back to plain reducing. 84 */ 85 static u64 btrfs_reduce_alloc_profile(struct btrfs_fs_info *fs_info, u64 flags) 86 { 87 u64 num_devices = fs_info->fs_devices->rw_devices; 88 u64 target; 89 u64 raid_type; 90 u64 allowed = 0; 91 92 /* 93 * See if restripe for this chunk_type is in progress, if so try to 94 * reduce to the target profile 95 */ 96 spin_lock(&fs_info->balance_lock); 97 target = get_restripe_target(fs_info, flags); 98 if (target) { 99 spin_unlock(&fs_info->balance_lock); 100 return extended_to_chunk(target); 101 } 102 spin_unlock(&fs_info->balance_lock); 103 104 /* First, mask out the RAID levels which aren't possible */ 105 for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) { 106 if (num_devices >= btrfs_raid_array[raid_type].devs_min) 107 allowed |= btrfs_raid_array[raid_type].bg_flag; 108 } 109 allowed &= flags; 110 111 /* Select the highest-redundancy RAID level. */ 112 if (allowed & BTRFS_BLOCK_GROUP_RAID1C4) 113 allowed = BTRFS_BLOCK_GROUP_RAID1C4; 114 else if (allowed & BTRFS_BLOCK_GROUP_RAID6) 115 allowed = BTRFS_BLOCK_GROUP_RAID6; 116 else if (allowed & BTRFS_BLOCK_GROUP_RAID1C3) 117 allowed = BTRFS_BLOCK_GROUP_RAID1C3; 118 else if (allowed & BTRFS_BLOCK_GROUP_RAID5) 119 allowed = BTRFS_BLOCK_GROUP_RAID5; 120 else if (allowed & BTRFS_BLOCK_GROUP_RAID10) 121 allowed = BTRFS_BLOCK_GROUP_RAID10; 122 else if (allowed & BTRFS_BLOCK_GROUP_RAID1) 123 allowed = BTRFS_BLOCK_GROUP_RAID1; 124 else if (allowed & BTRFS_BLOCK_GROUP_DUP) 125 allowed = BTRFS_BLOCK_GROUP_DUP; 126 else if (allowed & BTRFS_BLOCK_GROUP_RAID0) 127 allowed = BTRFS_BLOCK_GROUP_RAID0; 128 129 flags &= ~BTRFS_BLOCK_GROUP_PROFILE_MASK; 130 131 return extended_to_chunk(flags | allowed); 132 } 133 134 u64 btrfs_get_alloc_profile(struct btrfs_fs_info *fs_info, u64 orig_flags) 135 { 136 unsigned seq; 137 u64 flags; 138 139 do { 140 flags = orig_flags; 141 seq = read_seqbegin(&fs_info->profiles_lock); 142 143 if (flags & BTRFS_BLOCK_GROUP_DATA) 144 flags |= fs_info->avail_data_alloc_bits; 145 else if (flags & BTRFS_BLOCK_GROUP_SYSTEM) 146 flags |= fs_info->avail_system_alloc_bits; 147 else if (flags & BTRFS_BLOCK_GROUP_METADATA) 148 flags |= fs_info->avail_metadata_alloc_bits; 149 } while (read_seqretry(&fs_info->profiles_lock, seq)); 150 151 return btrfs_reduce_alloc_profile(fs_info, flags); 152 } 153 154 void btrfs_get_block_group(struct btrfs_block_group *cache) 155 { 156 refcount_inc(&cache->refs); 157 } 158 159 void btrfs_put_block_group(struct btrfs_block_group *cache) 160 { 161 if (refcount_dec_and_test(&cache->refs)) { 162 WARN_ON(cache->pinned > 0); 163 /* 164 * If there was a failure to cleanup a log tree, very likely due 165 * to an IO failure on a writeback attempt of one or more of its 166 * extent buffers, we could not do proper (and cheap) unaccounting 167 * of their reserved space, so don't warn on reserved > 0 in that 168 * case. 169 */ 170 if (!(cache->flags & BTRFS_BLOCK_GROUP_METADATA) || 171 !BTRFS_FS_LOG_CLEANUP_ERROR(cache->fs_info)) 172 WARN_ON(cache->reserved > 0); 173 174 /* 175 * A block_group shouldn't be on the discard_list anymore. 176 * Remove the block_group from the discard_list to prevent us 177 * from causing a panic due to NULL pointer dereference. 178 */ 179 if (WARN_ON(!list_empty(&cache->discard_list))) 180 btrfs_discard_cancel_work(&cache->fs_info->discard_ctl, 181 cache); 182 183 kfree(cache->free_space_ctl); 184 btrfs_free_chunk_map(cache->physical_map); 185 kfree(cache); 186 } 187 } 188 189 static int btrfs_bg_start_cmp(const struct rb_node *new, 190 const struct rb_node *exist) 191 { 192 const struct btrfs_block_group *new_bg = 193 rb_entry(new, struct btrfs_block_group, cache_node); 194 const struct btrfs_block_group *exist_bg = 195 rb_entry(exist, struct btrfs_block_group, cache_node); 196 197 if (new_bg->start < exist_bg->start) 198 return -1; 199 if (new_bg->start > exist_bg->start) 200 return 1; 201 return 0; 202 } 203 204 /* 205 * This adds the block group to the fs_info rb tree for the block group cache 206 */ 207 static int btrfs_add_block_group_cache(struct btrfs_block_group *block_group) 208 { 209 struct btrfs_fs_info *fs_info = block_group->fs_info; 210 struct rb_node *exist; 211 int ret = 0; 212 213 ASSERT(block_group->length != 0); 214 215 write_lock(&fs_info->block_group_cache_lock); 216 217 exist = rb_find_add_cached(&block_group->cache_node, 218 &fs_info->block_group_cache_tree, btrfs_bg_start_cmp); 219 if (exist) 220 ret = -EEXIST; 221 write_unlock(&fs_info->block_group_cache_lock); 222 223 return ret; 224 } 225 226 /* 227 * This will return the block group at or after bytenr if contains is 0, else 228 * it will return the block group that contains the bytenr 229 */ 230 static struct btrfs_block_group *block_group_cache_tree_search( 231 struct btrfs_fs_info *info, u64 bytenr, int contains) 232 { 233 struct btrfs_block_group *cache, *ret = NULL; 234 struct rb_node *n; 235 u64 end, start; 236 237 read_lock(&info->block_group_cache_lock); 238 n = info->block_group_cache_tree.rb_root.rb_node; 239 240 while (n) { 241 cache = rb_entry(n, struct btrfs_block_group, cache_node); 242 end = btrfs_block_group_end(cache) - 1; 243 start = cache->start; 244 245 if (bytenr < start) { 246 if (!contains && (!ret || start < ret->start)) 247 ret = cache; 248 n = n->rb_left; 249 } else if (bytenr > start) { 250 if (contains && bytenr <= end) { 251 ret = cache; 252 break; 253 } 254 n = n->rb_right; 255 } else { 256 ret = cache; 257 break; 258 } 259 } 260 if (ret) 261 btrfs_get_block_group(ret); 262 read_unlock(&info->block_group_cache_lock); 263 264 return ret; 265 } 266 267 /* 268 * Return the block group that starts at or after bytenr 269 */ 270 struct btrfs_block_group *btrfs_lookup_first_block_group( 271 struct btrfs_fs_info *info, u64 bytenr) 272 { 273 return block_group_cache_tree_search(info, bytenr, 0); 274 } 275 276 /* 277 * Return the block group that contains the given bytenr 278 */ 279 struct btrfs_block_group *btrfs_lookup_block_group( 280 struct btrfs_fs_info *info, u64 bytenr) 281 { 282 return block_group_cache_tree_search(info, bytenr, 1); 283 } 284 285 struct btrfs_block_group *btrfs_next_block_group( 286 struct btrfs_block_group *cache) 287 { 288 struct btrfs_fs_info *fs_info = cache->fs_info; 289 struct rb_node *node; 290 291 read_lock(&fs_info->block_group_cache_lock); 292 293 /* If our block group was removed, we need a full search. */ 294 if (RB_EMPTY_NODE(&cache->cache_node)) { 295 const u64 next_bytenr = btrfs_block_group_end(cache); 296 297 read_unlock(&fs_info->block_group_cache_lock); 298 btrfs_put_block_group(cache); 299 return btrfs_lookup_first_block_group(fs_info, next_bytenr); 300 } 301 node = rb_next(&cache->cache_node); 302 btrfs_put_block_group(cache); 303 if (node) { 304 cache = rb_entry(node, struct btrfs_block_group, cache_node); 305 btrfs_get_block_group(cache); 306 } else 307 cache = NULL; 308 read_unlock(&fs_info->block_group_cache_lock); 309 return cache; 310 } 311 312 /* 313 * Check if we can do a NOCOW write for a given extent. 314 * 315 * @fs_info: The filesystem information object. 316 * @bytenr: Logical start address of the extent. 317 * 318 * Check if we can do a NOCOW write for the given extent, and increments the 319 * number of NOCOW writers in the block group that contains the extent, as long 320 * as the block group exists and it's currently not in read-only mode. 321 * 322 * Returns: A non-NULL block group pointer if we can do a NOCOW write, the caller 323 * is responsible for calling btrfs_dec_nocow_writers() later. 324 * 325 * Or NULL if we can not do a NOCOW write 326 */ 327 struct btrfs_block_group *btrfs_inc_nocow_writers(struct btrfs_fs_info *fs_info, 328 u64 bytenr) 329 { 330 struct btrfs_block_group *bg; 331 bool can_nocow = true; 332 333 bg = btrfs_lookup_block_group(fs_info, bytenr); 334 if (!bg) 335 return NULL; 336 337 spin_lock(&bg->lock); 338 if (bg->ro) 339 can_nocow = false; 340 else 341 atomic_inc(&bg->nocow_writers); 342 spin_unlock(&bg->lock); 343 344 if (!can_nocow) { 345 btrfs_put_block_group(bg); 346 return NULL; 347 } 348 349 /* No put on block group, done by btrfs_dec_nocow_writers(). */ 350 return bg; 351 } 352 353 /* 354 * Decrement the number of NOCOW writers in a block group. 355 * 356 * This is meant to be called after a previous call to btrfs_inc_nocow_writers(), 357 * and on the block group returned by that call. Typically this is called after 358 * creating an ordered extent for a NOCOW write, to prevent races with scrub and 359 * relocation. 360 * 361 * After this call, the caller should not use the block group anymore. It it wants 362 * to use it, then it should get a reference on it before calling this function. 363 */ 364 void btrfs_dec_nocow_writers(struct btrfs_block_group *bg) 365 { 366 if (atomic_dec_and_test(&bg->nocow_writers)) 367 wake_up_var(&bg->nocow_writers); 368 369 /* For the lookup done by a previous call to btrfs_inc_nocow_writers(). */ 370 btrfs_put_block_group(bg); 371 } 372 373 void btrfs_wait_nocow_writers(struct btrfs_block_group *bg) 374 { 375 wait_var_event(&bg->nocow_writers, !atomic_read(&bg->nocow_writers)); 376 } 377 378 void btrfs_dec_block_group_reservations(struct btrfs_fs_info *fs_info, 379 const u64 start) 380 { 381 struct btrfs_block_group *bg; 382 383 bg = btrfs_lookup_block_group(fs_info, start); 384 ASSERT(bg); 385 if (atomic_dec_and_test(&bg->reservations)) 386 wake_up_var(&bg->reservations); 387 btrfs_put_block_group(bg); 388 } 389 390 void btrfs_wait_block_group_reservations(struct btrfs_block_group *bg) 391 { 392 struct btrfs_space_info *space_info = bg->space_info; 393 394 ASSERT(bg->ro); 395 396 if (!(bg->flags & BTRFS_BLOCK_GROUP_DATA)) 397 return; 398 399 /* 400 * Our block group is read only but before we set it to read only, 401 * some task might have had allocated an extent from it already, but it 402 * has not yet created a respective ordered extent (and added it to a 403 * root's list of ordered extents). 404 * Therefore wait for any task currently allocating extents, since the 405 * block group's reservations counter is incremented while a read lock 406 * on the groups' semaphore is held and decremented after releasing 407 * the read access on that semaphore and creating the ordered extent. 408 */ 409 down_write(&space_info->groups_sem); 410 up_write(&space_info->groups_sem); 411 412 wait_var_event(&bg->reservations, !atomic_read(&bg->reservations)); 413 } 414 415 struct btrfs_caching_control *btrfs_get_caching_control( 416 struct btrfs_block_group *cache) 417 { 418 struct btrfs_caching_control *ctl; 419 420 spin_lock(&cache->lock); 421 if (!cache->caching_ctl) { 422 spin_unlock(&cache->lock); 423 return NULL; 424 } 425 426 ctl = cache->caching_ctl; 427 refcount_inc(&ctl->count); 428 spin_unlock(&cache->lock); 429 return ctl; 430 } 431 432 static void btrfs_put_caching_control(struct btrfs_caching_control *ctl) 433 { 434 if (refcount_dec_and_test(&ctl->count)) 435 kfree(ctl); 436 } 437 438 /* 439 * When we wait for progress in the block group caching, its because our 440 * allocation attempt failed at least once. So, we must sleep and let some 441 * progress happen before we try again. 442 * 443 * This function will sleep at least once waiting for new free space to show 444 * up, and then it will check the block group free space numbers for our min 445 * num_bytes. Another option is to have it go ahead and look in the rbtree for 446 * a free extent of a given size, but this is a good start. 447 * 448 * Callers of this must check if cache->cached == BTRFS_CACHE_ERROR before using 449 * any of the information in this block group. 450 */ 451 void btrfs_wait_block_group_cache_progress(struct btrfs_block_group *cache, 452 u64 num_bytes) 453 { 454 struct btrfs_caching_control *caching_ctl; 455 int progress; 456 457 caching_ctl = btrfs_get_caching_control(cache); 458 if (!caching_ctl) 459 return; 460 461 /* 462 * We've already failed to allocate from this block group, so even if 463 * there's enough space in the block group it isn't contiguous enough to 464 * allow for an allocation, so wait for at least the next wakeup tick, 465 * or for the thing to be done. 466 */ 467 progress = atomic_read(&caching_ctl->progress); 468 469 wait_event(caching_ctl->wait, btrfs_block_group_done(cache) || 470 (progress != atomic_read(&caching_ctl->progress) && 471 (cache->free_space_ctl->free_space >= num_bytes))); 472 473 btrfs_put_caching_control(caching_ctl); 474 } 475 476 static int btrfs_caching_ctl_wait_done(struct btrfs_block_group *cache, 477 struct btrfs_caching_control *caching_ctl) 478 { 479 wait_event(caching_ctl->wait, btrfs_block_group_done(cache)); 480 return cache->cached == BTRFS_CACHE_ERROR ? -EIO : 0; 481 } 482 483 static int btrfs_wait_block_group_cache_done(struct btrfs_block_group *cache) 484 { 485 struct btrfs_caching_control *caching_ctl; 486 int ret; 487 488 caching_ctl = btrfs_get_caching_control(cache); 489 if (!caching_ctl) 490 return (cache->cached == BTRFS_CACHE_ERROR) ? -EIO : 0; 491 ret = btrfs_caching_ctl_wait_done(cache, caching_ctl); 492 btrfs_put_caching_control(caching_ctl); 493 return ret; 494 } 495 496 #ifdef CONFIG_BTRFS_DEBUG 497 static void fragment_free_space(struct btrfs_block_group *block_group) 498 { 499 struct btrfs_fs_info *fs_info = block_group->fs_info; 500 u64 start = block_group->start; 501 u64 len = block_group->length; 502 u64 chunk = block_group->flags & BTRFS_BLOCK_GROUP_METADATA ? 503 fs_info->nodesize : fs_info->sectorsize; 504 u64 step = chunk << 1; 505 506 while (len > chunk) { 507 btrfs_remove_free_space(block_group, start, chunk); 508 start += step; 509 if (len < step) 510 len = 0; 511 else 512 len -= step; 513 } 514 } 515 #endif 516 517 /* 518 * Add a free space range to the in memory free space cache of a block group. 519 * This checks if the range contains super block locations and any such 520 * locations are not added to the free space cache. 521 * 522 * @block_group: The target block group. 523 * @start: Start offset of the range. 524 * @end: End offset of the range (exclusive). 525 * @total_added_ret: Optional pointer to return the total amount of space 526 * added to the block group's free space cache. 527 * 528 * Returns 0 on success or < 0 on error. 529 */ 530 int btrfs_add_new_free_space(struct btrfs_block_group *block_group, u64 start, 531 u64 end, u64 *total_added_ret) 532 { 533 struct btrfs_fs_info *info = block_group->fs_info; 534 u64 extent_start, extent_end, size; 535 int ret; 536 537 if (total_added_ret) 538 *total_added_ret = 0; 539 540 while (start < end) { 541 if (!btrfs_find_first_extent_bit(&info->excluded_extents, start, 542 &extent_start, &extent_end, 543 EXTENT_DIRTY, NULL)) 544 break; 545 546 if (extent_start <= start) { 547 start = extent_end + 1; 548 } else if (extent_start > start && extent_start < end) { 549 size = extent_start - start; 550 ret = btrfs_add_free_space_async_trimmed(block_group, 551 start, size); 552 if (ret) 553 return ret; 554 if (total_added_ret) 555 *total_added_ret += size; 556 start = extent_end + 1; 557 } else { 558 break; 559 } 560 } 561 562 if (start < end) { 563 size = end - start; 564 ret = btrfs_add_free_space_async_trimmed(block_group, start, 565 size); 566 if (ret) 567 return ret; 568 if (total_added_ret) 569 *total_added_ret += size; 570 } 571 572 return 0; 573 } 574 575 /* 576 * Get an arbitrary extent item index / max_index through the block group 577 * 578 * @caching_ctl the caching control containing the block group to sample from 579 * @index: the integral step through the block group to grab from 580 * @max_index: the granularity of the sampling 581 * @key: return value parameter for the item we find 582 * @path: path to use for searching in the extent tree 583 * 584 * Pre-conditions on indices: 585 * 0 <= index <= max_index 586 * 0 < max_index 587 * 588 * Returns: 0 on success, 1 if the search didn't yield a useful item. 589 */ 590 static int sample_block_group_extent_item(struct btrfs_caching_control *caching_ctl, 591 int index, int max_index, 592 struct btrfs_key *found_key, 593 struct btrfs_path *path) 594 { 595 struct btrfs_block_group *block_group = caching_ctl->block_group; 596 struct btrfs_fs_info *fs_info = block_group->fs_info; 597 struct btrfs_root *extent_root; 598 u64 search_offset; 599 const u64 search_end = btrfs_block_group_end(block_group); 600 struct btrfs_key search_key; 601 int ret = 0; 602 603 ASSERT(index >= 0); 604 ASSERT(index <= max_index); 605 ASSERT(max_index > 0); 606 lockdep_assert_held(&caching_ctl->mutex); 607 lockdep_assert_held_read(&fs_info->commit_root_sem); 608 609 extent_root = btrfs_extent_root(fs_info, block_group->start); 610 if (unlikely(!extent_root)) { 611 btrfs_err(fs_info, 612 "missing extent root for block group at offset %llu", 613 block_group->start); 614 return -EUCLEAN; 615 } 616 617 search_offset = index * div_u64(block_group->length, max_index); 618 search_key.objectid = block_group->start + search_offset; 619 search_key.type = BTRFS_EXTENT_ITEM_KEY; 620 search_key.offset = 0; 621 622 btrfs_for_each_slot(extent_root, &search_key, found_key, path, ret) { 623 /* Success; sampled an extent item in the block group */ 624 if (found_key->type == BTRFS_EXTENT_ITEM_KEY && 625 found_key->objectid >= block_group->start && 626 found_key->objectid + found_key->offset <= search_end) 627 break; 628 629 /* We can't possibly find a valid extent item anymore */ 630 if (found_key->objectid >= search_end) { 631 ret = 1; 632 break; 633 } 634 } 635 636 lockdep_assert_held(&caching_ctl->mutex); 637 lockdep_assert_held_read(&fs_info->commit_root_sem); 638 return ret; 639 } 640 641 /* 642 * Best effort attempt to compute a block group's size class while caching it. 643 * 644 * @block_group: the block group we are caching 645 * 646 * We cannot infer the size class while adding free space extents, because that 647 * logic doesn't care about contiguous file extents (it doesn't differentiate 648 * between a 100M extent and 100 contiguous 1M extents). So we need to read the 649 * file extent items. Reading all of them is quite wasteful, because usually 650 * only a handful are enough to give a good answer. Therefore, we just grab 5 of 651 * them at even steps through the block group and pick the smallest size class 652 * we see. Since size class is best effort, and not guaranteed in general, 653 * inaccuracy is acceptable. 654 * 655 * To be more explicit about why this algorithm makes sense: 656 * 657 * If we are caching in a block group from disk, then there are three major cases 658 * to consider: 659 * 1. the block group is well behaved and all extents in it are the same size 660 * class. 661 * 2. the block group is mostly one size class with rare exceptions for last 662 * ditch allocations 663 * 3. the block group was populated before size classes and can have a totally 664 * arbitrary mix of size classes. 665 * 666 * In case 1, looking at any extent in the block group will yield the correct 667 * result. For the mixed cases, taking the minimum size class seems like a good 668 * approximation, since gaps from frees will be usable to the size class. For 669 * 2., a small handful of file extents is likely to yield the right answer. For 670 * 3, we can either read every file extent, or admit that this is best effort 671 * anyway and try to stay fast. 672 * 673 * No errors are returned since failing to determine the size class is not a 674 * critical error, size classes are just an optimization. 675 */ 676 static void load_block_group_size_class(struct btrfs_caching_control *caching_ctl) 677 { 678 BTRFS_PATH_AUTO_RELEASE(path); 679 struct btrfs_block_group *block_group = caching_ctl->block_group; 680 struct btrfs_fs_info *fs_info = block_group->fs_info; 681 struct btrfs_key key; 682 int i; 683 u64 min_size = block_group->length; 684 enum btrfs_block_group_size_class size_class = BTRFS_BG_SZ_NONE; 685 686 /* 687 * Since we run in workqueue context, we allocate the path on stack to 688 * avoid memory allocation failure, as the stack in a work queue task 689 * is not deep. 690 */ 691 ASSERT(current_work() == &caching_ctl->work.normal_work); 692 693 if (!btrfs_block_group_should_use_size_class(block_group)) 694 return; 695 696 path.skip_locking = true; 697 path.search_commit_root = true; 698 path.reada = READA_FORWARD; 699 700 lockdep_assert_held(&caching_ctl->mutex); 701 lockdep_assert_held_read(&fs_info->commit_root_sem); 702 for (i = 0; i < 5; ++i) { 703 int ret; 704 705 ret = sample_block_group_extent_item(caching_ctl, i, 5, &key, &path); 706 if (ret < 0) 707 return; 708 btrfs_release_path(&path); 709 if (ret > 0) 710 continue; 711 min_size = min_t(u64, min_size, key.offset); 712 size_class = btrfs_calc_block_group_size_class(min_size); 713 } 714 if (size_class != BTRFS_BG_SZ_NONE) { 715 spin_lock(&block_group->lock); 716 block_group->size_class = size_class; 717 spin_unlock(&block_group->lock); 718 } 719 } 720 721 static int load_extent_tree_free(struct btrfs_caching_control *caching_ctl) 722 { 723 struct btrfs_block_group *block_group = caching_ctl->block_group; 724 const u64 block_group_end = btrfs_block_group_end(block_group); 725 struct btrfs_fs_info *fs_info = block_group->fs_info; 726 struct btrfs_root *extent_root; 727 BTRFS_PATH_AUTO_FREE(path); 728 struct extent_buffer *leaf; 729 struct btrfs_key key; 730 u64 total_found = 0; 731 u64 last = block_group->start; 732 u32 nritems; 733 int ret; 734 bool wakeup = true; 735 736 path = btrfs_alloc_path(); 737 if (!path) 738 return -ENOMEM; 739 740 extent_root = btrfs_extent_root(fs_info, last); 741 if (unlikely(!extent_root)) { 742 btrfs_err(fs_info, 743 "missing extent root for block group at offset %llu", 744 block_group->start); 745 return -EUCLEAN; 746 } 747 748 #ifdef CONFIG_BTRFS_DEBUG 749 /* 750 * If we're fragmenting we don't want to make anybody think we can 751 * allocate from this block group until we've had a chance to fragment 752 * the free space. 753 */ 754 if (btrfs_should_fragment_free_space(block_group)) 755 wakeup = false; 756 #endif 757 /* 758 * We don't want to deadlock with somebody trying to allocate a new 759 * extent for the extent root while also trying to search the extent 760 * root to add free space. So we skip locking and search the commit 761 * root, since its read-only 762 */ 763 path->skip_locking = true; 764 path->search_commit_root = true; 765 path->reada = READA_FORWARD; 766 767 key.objectid = last; 768 key.type = BTRFS_EXTENT_ITEM_KEY; 769 key.offset = 0; 770 771 next: 772 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0); 773 if (ret < 0) 774 return ret; 775 776 leaf = path->nodes[0]; 777 nritems = btrfs_header_nritems(leaf); 778 779 while (1) { 780 if (btrfs_fs_closing_done(fs_info)) { 781 last = (u64)-1; 782 break; 783 } 784 785 if (path->slots[0] < nritems) { 786 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]); 787 } else { 788 ret = btrfs_find_next_key(extent_root, path, &key, 0, 0); 789 if (ret) 790 break; 791 792 if (need_resched() || 793 rwsem_is_contended(&fs_info->commit_root_sem)) { 794 btrfs_release_path(path); 795 up_read(&fs_info->commit_root_sem); 796 mutex_unlock(&caching_ctl->mutex); 797 cond_resched(); 798 mutex_lock(&caching_ctl->mutex); 799 down_read(&fs_info->commit_root_sem); 800 goto next; 801 } 802 803 ret = btrfs_next_leaf(extent_root, path); 804 if (ret < 0) 805 return ret; 806 if (ret) 807 break; 808 leaf = path->nodes[0]; 809 nritems = btrfs_header_nritems(leaf); 810 continue; 811 } 812 813 if (key.objectid < last) { 814 key.objectid = last; 815 key.type = BTRFS_EXTENT_ITEM_KEY; 816 key.offset = 0; 817 btrfs_release_path(path); 818 goto next; 819 } 820 821 if (key.objectid < block_group->start) { 822 path->slots[0]++; 823 continue; 824 } 825 826 if (key.objectid >= block_group_end) 827 break; 828 829 if (key.type == BTRFS_EXTENT_ITEM_KEY || 830 key.type == BTRFS_METADATA_ITEM_KEY) { 831 u64 space_added; 832 833 ret = btrfs_add_new_free_space(block_group, last, 834 key.objectid, &space_added); 835 if (ret) 836 return ret; 837 total_found += space_added; 838 if (key.type == BTRFS_METADATA_ITEM_KEY) 839 last = key.objectid + 840 fs_info->nodesize; 841 else 842 last = key.objectid + key.offset; 843 844 if (total_found > CACHING_CTL_WAKE_UP) { 845 total_found = 0; 846 if (wakeup) { 847 atomic_inc(&caching_ctl->progress); 848 wake_up(&caching_ctl->wait); 849 } 850 } 851 } 852 path->slots[0]++; 853 } 854 855 return btrfs_add_new_free_space(block_group, last, block_group_end, NULL); 856 } 857 858 static inline void btrfs_free_excluded_extents(const struct btrfs_block_group *bg) 859 { 860 btrfs_clear_extent_bit(&bg->fs_info->excluded_extents, bg->start, 861 btrfs_block_group_end(bg) - 1, EXTENT_DIRTY, NULL); 862 } 863 864 static noinline void caching_thread(struct btrfs_work *work) 865 { 866 struct btrfs_block_group *block_group; 867 struct btrfs_fs_info *fs_info; 868 struct btrfs_caching_control *caching_ctl; 869 int ret; 870 871 caching_ctl = container_of(work, struct btrfs_caching_control, work); 872 block_group = caching_ctl->block_group; 873 fs_info = block_group->fs_info; 874 875 mutex_lock(&caching_ctl->mutex); 876 down_read(&fs_info->commit_root_sem); 877 878 load_block_group_size_class(caching_ctl); 879 if (btrfs_test_opt(fs_info, SPACE_CACHE)) { 880 ret = load_free_space_cache(block_group); 881 if (ret == 1) { 882 ret = 0; 883 goto done; 884 } 885 886 /* 887 * We failed to load the space cache, set ourselves to 888 * CACHE_STARTED and carry on. 889 */ 890 spin_lock(&block_group->lock); 891 block_group->cached = BTRFS_CACHE_STARTED; 892 spin_unlock(&block_group->lock); 893 wake_up(&caching_ctl->wait); 894 } 895 896 /* 897 * If we are in the transaction that populated the free space tree we 898 * can't actually cache from the free space tree as our commit root and 899 * real root are the same, so we could change the contents of the blocks 900 * while caching. Instead do the slow caching in this case, and after 901 * the transaction has committed we will be safe. 902 */ 903 if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE) && 904 !(test_bit(BTRFS_FS_FREE_SPACE_TREE_UNTRUSTED, &fs_info->flags))) 905 ret = btrfs_load_free_space_tree(caching_ctl); 906 else 907 ret = load_extent_tree_free(caching_ctl); 908 done: 909 spin_lock(&block_group->lock); 910 block_group->caching_ctl = NULL; 911 block_group->cached = ret ? BTRFS_CACHE_ERROR : BTRFS_CACHE_FINISHED; 912 spin_unlock(&block_group->lock); 913 914 #ifdef CONFIG_BTRFS_DEBUG 915 if (btrfs_should_fragment_free_space(block_group)) { 916 u64 bytes_used; 917 918 spin_lock(&block_group->space_info->lock); 919 spin_lock(&block_group->lock); 920 bytes_used = block_group->length - block_group->used; 921 block_group->space_info->bytes_used += bytes_used >> 1; 922 spin_unlock(&block_group->lock); 923 spin_unlock(&block_group->space_info->lock); 924 fragment_free_space(block_group); 925 } 926 #endif 927 928 up_read(&fs_info->commit_root_sem); 929 btrfs_free_excluded_extents(block_group); 930 mutex_unlock(&caching_ctl->mutex); 931 932 wake_up(&caching_ctl->wait); 933 934 btrfs_put_caching_control(caching_ctl); 935 btrfs_put_block_group(block_group); 936 } 937 938 int btrfs_cache_block_group(struct btrfs_block_group *cache, bool wait) 939 { 940 struct btrfs_fs_info *fs_info = cache->fs_info; 941 struct btrfs_caching_control *caching_ctl = NULL; 942 int ret = 0; 943 944 /* Allocator for zoned filesystems does not use the cache at all */ 945 if (btrfs_is_zoned(fs_info)) 946 return 0; 947 948 /* 949 * No allocations can be done from remapped block groups, so they have 950 * no entries in the free-space tree. 951 */ 952 if (cache->flags & BTRFS_BLOCK_GROUP_REMAPPED) 953 return 0; 954 955 caching_ctl = kzalloc_obj(*caching_ctl, GFP_NOFS); 956 if (!caching_ctl) 957 return -ENOMEM; 958 959 INIT_LIST_HEAD(&caching_ctl->list); 960 mutex_init(&caching_ctl->mutex); 961 init_waitqueue_head(&caching_ctl->wait); 962 caching_ctl->block_group = cache; 963 refcount_set(&caching_ctl->count, 2); 964 atomic_set(&caching_ctl->progress, 0); 965 btrfs_init_work(&caching_ctl->work, caching_thread, NULL); 966 967 spin_lock(&cache->lock); 968 if (cache->cached != BTRFS_CACHE_NO) { 969 kfree(caching_ctl); 970 971 caching_ctl = cache->caching_ctl; 972 if (caching_ctl) 973 refcount_inc(&caching_ctl->count); 974 spin_unlock(&cache->lock); 975 goto out; 976 } 977 WARN_ON(cache->caching_ctl); 978 cache->caching_ctl = caching_ctl; 979 cache->cached = BTRFS_CACHE_STARTED; 980 spin_unlock(&cache->lock); 981 982 write_lock(&fs_info->block_group_cache_lock); 983 refcount_inc(&caching_ctl->count); 984 list_add_tail(&caching_ctl->list, &fs_info->caching_block_groups); 985 write_unlock(&fs_info->block_group_cache_lock); 986 987 btrfs_get_block_group(cache); 988 989 btrfs_queue_work(fs_info->caching_workers, &caching_ctl->work); 990 out: 991 if (wait && caching_ctl) 992 ret = btrfs_caching_ctl_wait_done(cache, caching_ctl); 993 if (caching_ctl) 994 btrfs_put_caching_control(caching_ctl); 995 996 return ret; 997 } 998 999 static void clear_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags) 1000 { 1001 u64 extra_flags = chunk_to_extended(flags) & 1002 BTRFS_EXTENDED_PROFILE_MASK; 1003 1004 write_seqlock(&fs_info->profiles_lock); 1005 if (flags & BTRFS_BLOCK_GROUP_DATA) 1006 fs_info->avail_data_alloc_bits &= ~extra_flags; 1007 if (flags & BTRFS_BLOCK_GROUP_METADATA) 1008 fs_info->avail_metadata_alloc_bits &= ~extra_flags; 1009 if (flags & BTRFS_BLOCK_GROUP_SYSTEM) 1010 fs_info->avail_system_alloc_bits &= ~extra_flags; 1011 write_sequnlock(&fs_info->profiles_lock); 1012 } 1013 1014 /* 1015 * Clear incompat bits for the following feature(s): 1016 * 1017 * - RAID56 - in case there's neither RAID5 nor RAID6 profile block group 1018 * in the whole filesystem 1019 * 1020 * - RAID1C34 - same as above for RAID1C3 and RAID1C4 block groups 1021 */ 1022 static void clear_incompat_bg_bits(struct btrfs_fs_info *fs_info, u64 flags) 1023 { 1024 bool found_raid56 = false; 1025 bool found_raid1c34 = false; 1026 1027 if ((flags & BTRFS_BLOCK_GROUP_RAID56_MASK) || 1028 (flags & BTRFS_BLOCK_GROUP_RAID1C3) || 1029 (flags & BTRFS_BLOCK_GROUP_RAID1C4)) { 1030 struct list_head *head = &fs_info->space_info; 1031 struct btrfs_space_info *sinfo; 1032 1033 list_for_each_entry_rcu(sinfo, head, list) { 1034 down_read(&sinfo->groups_sem); 1035 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID5])) 1036 found_raid56 = true; 1037 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID6])) 1038 found_raid56 = true; 1039 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID1C3])) 1040 found_raid1c34 = true; 1041 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID1C4])) 1042 found_raid1c34 = true; 1043 up_read(&sinfo->groups_sem); 1044 } 1045 if (!found_raid56) 1046 btrfs_clear_fs_incompat(fs_info, RAID56); 1047 if (!found_raid1c34) 1048 btrfs_clear_fs_incompat(fs_info, RAID1C34); 1049 } 1050 } 1051 1052 static struct btrfs_root *btrfs_block_group_root(struct btrfs_fs_info *fs_info) 1053 { 1054 if (btrfs_fs_compat_ro(fs_info, BLOCK_GROUP_TREE)) 1055 return fs_info->block_group_root; 1056 return btrfs_extent_root(fs_info, 0); 1057 } 1058 1059 static int remove_block_group_item(struct btrfs_trans_handle *trans, 1060 struct btrfs_path *path, 1061 struct btrfs_block_group *block_group) 1062 { 1063 struct btrfs_fs_info *fs_info = trans->fs_info; 1064 struct btrfs_root *root; 1065 struct btrfs_key key; 1066 int ret; 1067 1068 root = btrfs_block_group_root(fs_info); 1069 if (unlikely(!root)) { 1070 btrfs_err(fs_info, "missing block group root"); 1071 return -EUCLEAN; 1072 } 1073 1074 key.objectid = block_group->start; 1075 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY; 1076 key.offset = block_group->length; 1077 1078 ret = btrfs_search_slot(trans, root, &key, path, -1, 1); 1079 if (ret > 0) 1080 ret = -ENOENT; 1081 if (ret < 0) 1082 return ret; 1083 1084 return btrfs_del_item(trans, root, path); 1085 } 1086 1087 void btrfs_remove_bg_from_sinfo(struct btrfs_block_group *bg) 1088 { 1089 int factor = btrfs_bg_type_to_factor(bg->flags); 1090 1091 spin_lock(&bg->space_info->lock); 1092 if (btrfs_test_opt(bg->fs_info, ENOSPC_DEBUG)) { 1093 WARN_ON(bg->space_info->total_bytes < bg->length); 1094 WARN_ON(bg->space_info->bytes_readonly < bg->length - bg->zone_unusable); 1095 WARN_ON(bg->space_info->bytes_zone_unusable < bg->zone_unusable); 1096 WARN_ON(bg->space_info->disk_total < bg->length * factor); 1097 } 1098 bg->space_info->total_bytes -= bg->length; 1099 bg->space_info->bytes_readonly -= (bg->length - bg->zone_unusable); 1100 btrfs_space_info_update_bytes_zone_unusable(bg->space_info, -bg->zone_unusable); 1101 bg->space_info->disk_total -= bg->length * factor; 1102 spin_unlock(&bg->space_info->lock); 1103 } 1104 1105 int btrfs_remove_block_group(struct btrfs_trans_handle *trans, 1106 struct btrfs_chunk_map *map) 1107 { 1108 struct btrfs_fs_info *fs_info = trans->fs_info; 1109 BTRFS_PATH_AUTO_FREE(path); 1110 struct btrfs_block_group *block_group; 1111 struct btrfs_free_cluster *cluster; 1112 struct inode *inode; 1113 struct kobject *kobj = NULL; 1114 int ret; 1115 int index; 1116 struct btrfs_caching_control *caching_ctl = NULL; 1117 bool remove_map; 1118 bool remove_rsv = false; 1119 1120 block_group = btrfs_lookup_block_group(fs_info, map->start); 1121 if (unlikely(!block_group)) { 1122 btrfs_abort_transaction(trans, -ENOENT); 1123 return -ENOENT; 1124 } 1125 1126 if (unlikely(!block_group->ro && 1127 !(block_group->flags & BTRFS_BLOCK_GROUP_REMAPPED))) { 1128 ret = -EUCLEAN; 1129 btrfs_abort_transaction(trans, ret); 1130 goto out; 1131 } 1132 1133 trace_btrfs_remove_block_group(block_group); 1134 /* 1135 * Free the reserved super bytes from this block group before 1136 * remove it. 1137 */ 1138 btrfs_free_excluded_extents(block_group); 1139 btrfs_free_ref_tree_range(fs_info, block_group->start, 1140 block_group->length); 1141 1142 index = btrfs_bg_flags_to_raid_index(block_group->flags); 1143 1144 /* make sure this block group isn't part of an allocation cluster */ 1145 cluster = &fs_info->data_alloc_cluster; 1146 spin_lock(&cluster->refill_lock); 1147 btrfs_return_cluster_to_free_space(block_group, cluster); 1148 spin_unlock(&cluster->refill_lock); 1149 1150 /* 1151 * make sure this block group isn't part of a metadata 1152 * allocation cluster 1153 */ 1154 cluster = &fs_info->meta_alloc_cluster; 1155 spin_lock(&cluster->refill_lock); 1156 btrfs_return_cluster_to_free_space(block_group, cluster); 1157 spin_unlock(&cluster->refill_lock); 1158 1159 btrfs_clear_treelog_bg(block_group); 1160 btrfs_clear_data_reloc_bg(block_group); 1161 1162 path = btrfs_alloc_path(); 1163 if (unlikely(!path)) { 1164 ret = -ENOMEM; 1165 btrfs_abort_transaction(trans, ret); 1166 goto out; 1167 } 1168 1169 /* 1170 * get the inode first so any iput calls done for the io_list 1171 * aren't the final iput (no unlinks allowed now) 1172 */ 1173 inode = lookup_free_space_inode(block_group, path); 1174 1175 mutex_lock(&trans->transaction->cache_write_mutex); 1176 /* 1177 * Make sure our free space cache IO is done before removing the 1178 * free space inode 1179 */ 1180 spin_lock(&trans->transaction->dirty_bgs_lock); 1181 if (!list_empty(&block_group->io_list)) { 1182 list_del_init(&block_group->io_list); 1183 1184 WARN_ON(!IS_ERR(inode) && inode != block_group->io_ctl.inode); 1185 1186 spin_unlock(&trans->transaction->dirty_bgs_lock); 1187 btrfs_wait_cache_io(trans, block_group, path); 1188 btrfs_put_block_group(block_group); 1189 spin_lock(&trans->transaction->dirty_bgs_lock); 1190 } 1191 1192 if (!list_empty(&block_group->dirty_list)) { 1193 list_del_init(&block_group->dirty_list); 1194 remove_rsv = true; 1195 btrfs_put_block_group(block_group); 1196 } 1197 spin_unlock(&trans->transaction->dirty_bgs_lock); 1198 mutex_unlock(&trans->transaction->cache_write_mutex); 1199 1200 ret = btrfs_remove_free_space_inode(trans, inode, block_group); 1201 if (unlikely(ret)) { 1202 btrfs_abort_transaction(trans, ret); 1203 goto out; 1204 } 1205 1206 write_lock(&fs_info->block_group_cache_lock); 1207 rb_erase_cached(&block_group->cache_node, 1208 &fs_info->block_group_cache_tree); 1209 RB_CLEAR_NODE(&block_group->cache_node); 1210 1211 /* Once for the block groups rbtree */ 1212 btrfs_put_block_group(block_group); 1213 1214 write_unlock(&fs_info->block_group_cache_lock); 1215 1216 down_write(&block_group->space_info->groups_sem); 1217 /* 1218 * we must use list_del_init so people can check to see if they 1219 * are still on the list after taking the semaphore 1220 */ 1221 list_del_init(&block_group->list); 1222 if (list_empty(&block_group->space_info->block_groups[index])) { 1223 kobj = block_group->space_info->block_group_kobjs[index]; 1224 block_group->space_info->block_group_kobjs[index] = NULL; 1225 clear_avail_alloc_bits(fs_info, block_group->flags); 1226 } 1227 up_write(&block_group->space_info->groups_sem); 1228 clear_incompat_bg_bits(fs_info, block_group->flags); 1229 if (kobj) { 1230 kobject_del(kobj); 1231 kobject_put(kobj); 1232 } 1233 1234 if (block_group->cached == BTRFS_CACHE_STARTED) 1235 btrfs_wait_block_group_cache_done(block_group); 1236 1237 write_lock(&fs_info->block_group_cache_lock); 1238 caching_ctl = btrfs_get_caching_control(block_group); 1239 if (!caching_ctl) { 1240 struct btrfs_caching_control *ctl; 1241 1242 list_for_each_entry(ctl, &fs_info->caching_block_groups, list) { 1243 if (ctl->block_group == block_group) { 1244 caching_ctl = ctl; 1245 refcount_inc(&caching_ctl->count); 1246 break; 1247 } 1248 } 1249 } 1250 if (caching_ctl) 1251 list_del_init(&caching_ctl->list); 1252 write_unlock(&fs_info->block_group_cache_lock); 1253 1254 if (caching_ctl) { 1255 /* Once for the caching bgs list and once for us. */ 1256 btrfs_put_caching_control(caching_ctl); 1257 btrfs_put_caching_control(caching_ctl); 1258 } 1259 1260 spin_lock(&trans->transaction->dirty_bgs_lock); 1261 WARN_ON(!list_empty(&block_group->dirty_list)); 1262 WARN_ON(!list_empty(&block_group->io_list)); 1263 spin_unlock(&trans->transaction->dirty_bgs_lock); 1264 1265 btrfs_remove_free_space_cache(block_group); 1266 1267 spin_lock(&block_group->space_info->lock); 1268 list_del_init(&block_group->ro_list); 1269 spin_unlock(&block_group->space_info->lock); 1270 1271 if (!(block_group->flags & BTRFS_BLOCK_GROUP_REMAPPED)) 1272 btrfs_remove_bg_from_sinfo(block_group); 1273 1274 /* 1275 * Remove the free space for the block group from the free space tree 1276 * and the block group's item from the extent tree before marking the 1277 * block group as removed. This is to prevent races with tasks that 1278 * freeze and unfreeze a block group, this task and another task 1279 * allocating a new block group - the unfreeze task ends up removing 1280 * the block group's extent map before the task calling this function 1281 * deletes the block group item from the extent tree, allowing for 1282 * another task to attempt to create another block group with the same 1283 * item key (and failing with -EEXIST and a transaction abort). 1284 * 1285 * If the REMAPPED flag has been set the block group's free space 1286 * has already been removed, so we can skip the call to 1287 * btrfs_remove_block_group_free_space(). 1288 */ 1289 if (!(block_group->flags & BTRFS_BLOCK_GROUP_REMAPPED)) { 1290 ret = btrfs_remove_block_group_free_space(trans, block_group); 1291 if (unlikely(ret)) { 1292 btrfs_abort_transaction(trans, ret); 1293 goto out; 1294 } 1295 } 1296 1297 ret = remove_block_group_item(trans, path, block_group); 1298 if (unlikely(ret < 0)) { 1299 btrfs_abort_transaction(trans, ret); 1300 goto out; 1301 } 1302 1303 spin_lock(&block_group->lock); 1304 /* 1305 * Hitting this WARN means we removed a block group with an unwritten 1306 * region. It will cause "unable to find chunk map for logical" errors. 1307 */ 1308 if (WARN_ON(has_unwritten_metadata(block_group))) 1309 btrfs_warn(fs_info, 1310 "block group %llu is removed before metadata write out", 1311 block_group->start); 1312 1313 set_bit(BLOCK_GROUP_FLAG_REMOVED, &block_group->runtime_flags); 1314 1315 /* 1316 * At this point trimming or scrub can't start on this block group, 1317 * because we removed the block group from the rbtree 1318 * fs_info->block_group_cache_tree so no one can't find it anymore and 1319 * even if someone already got this block group before we removed it 1320 * from the rbtree, they have already incremented block_group->frozen - 1321 * if they didn't, for the trimming case they won't find any free space 1322 * entries because we already removed them all when we called 1323 * btrfs_remove_free_space_cache(). 1324 * 1325 * And we must not remove the chunk map from the fs_info->mapping_tree 1326 * to prevent the same logical address range and physical device space 1327 * ranges from being reused for a new block group. This is needed to 1328 * avoid races with trimming and scrub. 1329 * 1330 * An fs trim operation (btrfs_trim_fs() / btrfs_ioctl_fitrim()) is 1331 * completely transactionless, so while it is trimming a range the 1332 * currently running transaction might finish and a new one start, 1333 * allowing for new block groups to be created that can reuse the same 1334 * physical device locations unless we take this special care. 1335 * 1336 * There may also be an implicit trim operation if the file system 1337 * is mounted with -odiscard. The same protections must remain 1338 * in place until the extents have been discarded completely when 1339 * the transaction commit has completed. 1340 */ 1341 remove_map = (atomic_read(&block_group->frozen) == 0); 1342 spin_unlock(&block_group->lock); 1343 1344 if (remove_map) 1345 btrfs_remove_chunk_map(fs_info, map); 1346 1347 out: 1348 /* Once for the lookup reference */ 1349 btrfs_put_block_group(block_group); 1350 if (remove_rsv) 1351 btrfs_dec_delayed_refs_rsv_bg_updates(fs_info); 1352 return ret; 1353 } 1354 1355 struct btrfs_trans_handle *btrfs_start_trans_remove_block_group( 1356 struct btrfs_fs_info *fs_info, const u64 chunk_offset) 1357 { 1358 struct btrfs_root *root = btrfs_block_group_root(fs_info); 1359 struct btrfs_chunk_map *map; 1360 unsigned int num_items; 1361 1362 if (unlikely(!root)) { 1363 btrfs_err(fs_info, "missing block group root"); 1364 return ERR_PTR(-EUCLEAN); 1365 } 1366 1367 map = btrfs_find_chunk_map(fs_info, chunk_offset, 1); 1368 ASSERT(map != NULL); 1369 ASSERT(map->start == chunk_offset); 1370 1371 /* 1372 * We need to reserve 3 + N units from the metadata space info in order 1373 * to remove a block group (done at btrfs_remove_chunk() and at 1374 * btrfs_remove_block_group()), which are used for: 1375 * 1376 * 1 unit for adding the free space inode's orphan (located in the tree 1377 * of tree roots). 1378 * 1 unit for deleting the block group item (located in the extent 1379 * tree). 1380 * 1 unit for deleting the free space item (located in tree of tree 1381 * roots). 1382 * N units for deleting N device extent items corresponding to each 1383 * stripe (located in the device tree). 1384 * 1385 * In order to remove a block group we also need to reserve units in the 1386 * system space info in order to update the chunk tree (update one or 1387 * more device items and remove one chunk item), but this is done at 1388 * btrfs_remove_chunk() through a call to check_system_chunk(). 1389 */ 1390 num_items = 3 + map->num_stripes; 1391 btrfs_free_chunk_map(map); 1392 1393 return btrfs_start_transaction_fallback_global_rsv(root, num_items); 1394 } 1395 1396 /* 1397 * Mark block group @cache read-only, so later write won't happen to block 1398 * group @cache. 1399 * 1400 * If @force is not set, this function will only mark the block group readonly 1401 * if we have enough free space (1M) in other metadata/system block groups. 1402 * If @force is not set, this function will mark the block group readonly 1403 * without checking free space. 1404 * 1405 * NOTE: This function doesn't care if other block groups can contain all the 1406 * data in this block group. That check should be done by relocation routine, 1407 * not this function. 1408 */ 1409 static int inc_block_group_ro(struct btrfs_block_group *cache, bool force) 1410 { 1411 struct btrfs_space_info *sinfo = cache->space_info; 1412 u64 num_bytes; 1413 int ret = -ENOSPC; 1414 1415 spin_lock(&sinfo->lock); 1416 spin_lock(&cache->lock); 1417 1418 if (cache->swap_extents) { 1419 ret = -ETXTBSY; 1420 goto out; 1421 } 1422 1423 if (cache->ro) { 1424 cache->ro++; 1425 ret = 0; 1426 goto out; 1427 } 1428 1429 num_bytes = btrfs_block_group_available_space(cache); 1430 1431 /* 1432 * Data never overcommits, even in mixed mode, so do just the straight 1433 * check of left over space in how much we have allocated. 1434 */ 1435 if (force) { 1436 ret = 0; 1437 } else if (sinfo->flags & BTRFS_BLOCK_GROUP_DATA) { 1438 u64 sinfo_used = btrfs_space_info_used(sinfo, true); 1439 1440 /* 1441 * Here we make sure if we mark this bg RO, we still have enough 1442 * free space as buffer. 1443 */ 1444 if (sinfo_used + num_bytes <= sinfo->total_bytes) 1445 ret = 0; 1446 } else { 1447 /* 1448 * We overcommit metadata, so we need to do the 1449 * btrfs_can_overcommit check here, and we need to pass in 1450 * BTRFS_RESERVE_NO_FLUSH to give ourselves the most amount of 1451 * leeway to allow us to mark this block group as read only. 1452 */ 1453 if (btrfs_can_overcommit(sinfo, num_bytes, BTRFS_RESERVE_NO_FLUSH)) 1454 ret = 0; 1455 } 1456 1457 if (!ret) { 1458 sinfo->bytes_readonly += num_bytes; 1459 if (btrfs_is_zoned(cache->fs_info)) { 1460 /* Migrate zone_unusable bytes to readonly */ 1461 sinfo->bytes_readonly += cache->zone_unusable; 1462 btrfs_space_info_update_bytes_zone_unusable(sinfo, -cache->zone_unusable); 1463 cache->zone_unusable = 0; 1464 } 1465 cache->ro++; 1466 list_add_tail(&cache->ro_list, &sinfo->ro_bgs); 1467 } 1468 out: 1469 spin_unlock(&cache->lock); 1470 spin_unlock(&sinfo->lock); 1471 if (ret == -ENOSPC && btrfs_test_opt(cache->fs_info, ENOSPC_DEBUG)) { 1472 btrfs_info(cache->fs_info, 1473 "unable to make block group %llu ro", cache->start); 1474 btrfs_dump_space_info(cache->space_info, 0, false); 1475 } 1476 return ret; 1477 } 1478 1479 static bool clean_pinned_extents(struct btrfs_trans_handle *trans, 1480 const struct btrfs_block_group *bg) 1481 { 1482 struct btrfs_fs_info *fs_info = trans->fs_info; 1483 struct btrfs_transaction *prev_trans = NULL; 1484 const u64 start = bg->start; 1485 const u64 end = start + bg->length - 1; 1486 int ret; 1487 1488 spin_lock(&fs_info->trans_lock); 1489 if (!list_is_first(&trans->transaction->list, &fs_info->trans_list)) { 1490 prev_trans = list_prev_entry(trans->transaction, list); 1491 refcount_inc(&prev_trans->use_count); 1492 } 1493 spin_unlock(&fs_info->trans_lock); 1494 1495 /* 1496 * Hold the unused_bg_unpin_mutex lock to avoid racing with 1497 * btrfs_finish_extent_commit(). If we are at transaction N, another 1498 * task might be running finish_extent_commit() for the previous 1499 * transaction N - 1, and have seen a range belonging to the block 1500 * group in pinned_extents before we were able to clear the whole block 1501 * group range from pinned_extents. This means that task can lookup for 1502 * the block group after we unpinned it from pinned_extents and removed 1503 * it, leading to an error at unpin_extent_range(). 1504 */ 1505 mutex_lock(&fs_info->unused_bg_unpin_mutex); 1506 if (prev_trans) { 1507 ret = btrfs_clear_extent_bit(&prev_trans->pinned_extents, start, end, 1508 EXTENT_DIRTY, NULL); 1509 if (ret) 1510 goto out; 1511 } 1512 1513 ret = btrfs_clear_extent_bit(&trans->transaction->pinned_extents, start, end, 1514 EXTENT_DIRTY, NULL); 1515 out: 1516 mutex_unlock(&fs_info->unused_bg_unpin_mutex); 1517 if (prev_trans) 1518 btrfs_put_transaction(prev_trans); 1519 1520 return ret == 0; 1521 } 1522 1523 /* 1524 * Link the block_group to a list via bg_list. 1525 * 1526 * @bg: The block_group to link to the list. 1527 * @list: The list to link it to. 1528 * 1529 * Use this rather than list_add_tail() directly to ensure proper respect 1530 * to locking and refcounting. 1531 * 1532 * Returns: true if the bg was linked with a refcount bump and false otherwise. 1533 */ 1534 static bool btrfs_link_bg_list(struct btrfs_block_group *bg, struct list_head *list) 1535 { 1536 struct btrfs_fs_info *fs_info = bg->fs_info; 1537 bool added = false; 1538 1539 spin_lock(&fs_info->unused_bgs_lock); 1540 if (list_empty(&bg->bg_list)) { 1541 btrfs_get_block_group(bg); 1542 list_add_tail(&bg->bg_list, list); 1543 added = true; 1544 } 1545 spin_unlock(&fs_info->unused_bgs_lock); 1546 return added; 1547 } 1548 1549 /* 1550 * Process the unused_bgs list and remove any that don't have any allocated 1551 * space inside of them. 1552 */ 1553 void btrfs_delete_unused_bgs(struct btrfs_fs_info *fs_info) 1554 { 1555 LIST_HEAD(retry_list); 1556 struct btrfs_block_group *block_group; 1557 struct btrfs_space_info *space_info; 1558 struct btrfs_trans_handle *trans; 1559 const bool async_trim_enabled = btrfs_test_opt(fs_info, DISCARD_ASYNC); 1560 int ret = 0; 1561 1562 if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags)) 1563 return; 1564 1565 if (btrfs_fs_closing(fs_info)) 1566 return; 1567 1568 /* 1569 * Long running balances can keep us blocked here for eternity, so 1570 * simply skip deletion if we're unable to get the mutex. 1571 */ 1572 if (!mutex_trylock(&fs_info->reclaim_bgs_lock)) 1573 return; 1574 1575 spin_lock(&fs_info->unused_bgs_lock); 1576 while (!list_empty(&fs_info->unused_bgs)) { 1577 u64 used; 1578 int trimming; 1579 1580 block_group = list_first_entry(&fs_info->unused_bgs, 1581 struct btrfs_block_group, 1582 bg_list); 1583 list_del_init(&block_group->bg_list); 1584 1585 space_info = block_group->space_info; 1586 1587 if (ret || btrfs_mixed_space_info(space_info)) { 1588 btrfs_put_block_group(block_group); 1589 continue; 1590 } 1591 spin_unlock(&fs_info->unused_bgs_lock); 1592 1593 btrfs_discard_cancel_work(&fs_info->discard_ctl, block_group); 1594 1595 /* Don't want to race with allocators so take the groups_sem */ 1596 down_write(&space_info->groups_sem); 1597 1598 /* 1599 * Async discard moves the final block group discard to be prior 1600 * to the unused_bgs code path. Therefore, if it's not fully 1601 * trimmed, punt it back to the async discard lists. 1602 */ 1603 if (btrfs_test_opt(fs_info, DISCARD_ASYNC) && 1604 !btrfs_is_free_space_trimmed(block_group)) { 1605 trace_btrfs_skip_unused_block_group(block_group); 1606 up_write(&space_info->groups_sem); 1607 /* Requeue if we failed because of async discard */ 1608 btrfs_discard_queue_work(&fs_info->discard_ctl, 1609 block_group); 1610 goto next; 1611 } 1612 1613 spin_lock(&space_info->lock); 1614 spin_lock(&block_group->lock); 1615 1616 if (btrfs_is_zoned(fs_info) && btrfs_is_block_group_used(block_group) && 1617 block_group->zone_unusable >= div_u64(block_group->length, 2)) { 1618 /* 1619 * If the block group has data left, but at least half 1620 * of the block group is zone_unusable, mark it as 1621 * reclaimable before continuing with the next block group. 1622 */ 1623 1624 spin_unlock(&block_group->lock); 1625 spin_unlock(&space_info->lock); 1626 up_write(&space_info->groups_sem); 1627 1628 btrfs_mark_bg_to_reclaim(block_group); 1629 1630 goto next; 1631 } 1632 1633 if (btrfs_is_block_group_used(block_group) || 1634 (block_group->ro && !(block_group->flags & BTRFS_BLOCK_GROUP_REMAPPED)) || 1635 list_is_singular(&block_group->list) || 1636 test_bit(BLOCK_GROUP_FLAG_FULLY_REMAPPED, &block_group->runtime_flags)) { 1637 /* 1638 * We want to bail if we made new allocations or have 1639 * outstanding allocations in this block group. We do 1640 * the ro check in case balance is currently acting on 1641 * this block group. 1642 * 1643 * Also bail out if this is the only block group for its 1644 * type, because otherwise we would lose profile 1645 * information from fs_info->avail_*_alloc_bits and the 1646 * next block group of this type would be created with a 1647 * "single" profile (even if we're in a raid fs) because 1648 * fs_info->avail_*_alloc_bits would be 0. 1649 */ 1650 trace_btrfs_skip_unused_block_group(block_group); 1651 spin_unlock(&block_group->lock); 1652 spin_unlock(&space_info->lock); 1653 up_write(&space_info->groups_sem); 1654 goto next; 1655 } 1656 1657 /* 1658 * The block group may be unused but there may be space reserved 1659 * accounting with the existence of that block group, that is, 1660 * space_info->bytes_may_use was incremented by a task but no 1661 * space was yet allocated from the block group by the task. 1662 * That space may or may not be allocated, as we are generally 1663 * pessimistic about space reservation for metadata as well as 1664 * for data when using compression (as we reserve space based on 1665 * the worst case, when data can't be compressed, and before 1666 * actually attempting compression, before starting writeback). 1667 * 1668 * So check if the total space of the space_info minus the size 1669 * of this block group is less than the used space of the 1670 * space_info - if that's the case, then it means we have tasks 1671 * that might be relying on the block group in order to allocate 1672 * extents, and add back the block group to the unused list when 1673 * we finish, so that we retry later in case no tasks ended up 1674 * needing to allocate extents from the block group. 1675 */ 1676 used = btrfs_space_info_used(space_info, true); 1677 if (((space_info->total_bytes - block_group->length < used && 1678 block_group->zone_unusable < block_group->length) || 1679 has_unwritten_metadata(block_group)) && 1680 !(block_group->flags & BTRFS_BLOCK_GROUP_REMAPPED)) { 1681 /* 1682 * Add a reference for the list, compensate for the ref 1683 * drop under the "next" label for the 1684 * fs_info->unused_bgs list. 1685 */ 1686 btrfs_link_bg_list(block_group, &retry_list); 1687 1688 trace_btrfs_skip_unused_block_group(block_group); 1689 spin_unlock(&block_group->lock); 1690 spin_unlock(&space_info->lock); 1691 up_write(&space_info->groups_sem); 1692 goto next; 1693 } 1694 1695 spin_unlock(&block_group->lock); 1696 spin_unlock(&space_info->lock); 1697 1698 /* We don't want to force the issue, only flip if it's ok. */ 1699 ret = inc_block_group_ro(block_group, false); 1700 up_write(&space_info->groups_sem); 1701 if (ret < 0) { 1702 ret = 0; 1703 goto next; 1704 } 1705 1706 ret = btrfs_zone_finish(block_group); 1707 if (ret < 0) { 1708 btrfs_dec_block_group_ro(block_group); 1709 if (ret == -EAGAIN) { 1710 btrfs_link_bg_list(block_group, &retry_list); 1711 ret = 0; 1712 } 1713 goto next; 1714 } 1715 1716 /* 1717 * Want to do this before we do anything else so we can recover 1718 * properly if we fail to join the transaction. 1719 */ 1720 trans = btrfs_start_trans_remove_block_group(fs_info, 1721 block_group->start); 1722 if (IS_ERR(trans)) { 1723 btrfs_dec_block_group_ro(block_group); 1724 ret = PTR_ERR(trans); 1725 goto next; 1726 } 1727 1728 /* 1729 * We could have pending pinned extents for this block group, 1730 * just delete them, we don't care about them anymore. 1731 */ 1732 if (!clean_pinned_extents(trans, block_group)) { 1733 btrfs_dec_block_group_ro(block_group); 1734 goto end_trans; 1735 } 1736 1737 /* 1738 * At this point, the block_group is read only and should fail 1739 * new allocations. However, btrfs_finish_extent_commit() can 1740 * cause this block_group to be placed back on the discard 1741 * lists because now the block_group isn't fully discarded. 1742 * Bail here and try again later after discarding everything. 1743 */ 1744 spin_lock(&fs_info->discard_ctl.lock); 1745 if (!list_empty(&block_group->discard_list)) { 1746 spin_unlock(&fs_info->discard_ctl.lock); 1747 btrfs_dec_block_group_ro(block_group); 1748 btrfs_discard_queue_work(&fs_info->discard_ctl, 1749 block_group); 1750 goto end_trans; 1751 } 1752 spin_unlock(&fs_info->discard_ctl.lock); 1753 1754 /* Reset pinned so btrfs_put_block_group doesn't complain */ 1755 spin_lock(&space_info->lock); 1756 spin_lock(&block_group->lock); 1757 1758 btrfs_space_info_update_bytes_pinned(space_info, -block_group->pinned); 1759 space_info->bytes_readonly += block_group->pinned; 1760 block_group->pinned = 0; 1761 1762 spin_unlock(&block_group->lock); 1763 spin_unlock(&space_info->lock); 1764 1765 /* 1766 * The normal path here is an unused block group is passed here, 1767 * then trimming is handled in the transaction commit path. 1768 * Async discard interposes before this to do the trimming 1769 * before coming down the unused block group path as trimming 1770 * will no longer be done later in the transaction commit path. 1771 */ 1772 if (!async_trim_enabled && btrfs_test_opt(fs_info, DISCARD_ASYNC)) 1773 goto flip_async; 1774 1775 /* 1776 * DISCARD can flip during remount. On zoned filesystems, we 1777 * need to reset sequential-required zones. 1778 */ 1779 trimming = btrfs_test_opt(fs_info, DISCARD_SYNC) || 1780 btrfs_is_zoned(fs_info); 1781 1782 /* Implicit trim during transaction commit. */ 1783 if (trimming) 1784 btrfs_freeze_block_group(block_group); 1785 1786 /* 1787 * Btrfs_remove_chunk will abort the transaction if things go 1788 * horribly wrong. 1789 */ 1790 ret = btrfs_remove_chunk(trans, block_group->start); 1791 1792 if (ret) { 1793 if (trimming) 1794 btrfs_unfreeze_block_group(block_group); 1795 goto end_trans; 1796 } 1797 1798 /* 1799 * If we're not mounted with -odiscard, we can just forget 1800 * about this block group. Otherwise we'll need to wait 1801 * until transaction commit to do the actual discard. 1802 */ 1803 if (trimming) { 1804 spin_lock(&fs_info->unused_bgs_lock); 1805 /* 1806 * A concurrent scrub might have added us to the list 1807 * fs_info->unused_bgs, so use a list_move operation 1808 * to add the block group to the deleted_bgs list. 1809 */ 1810 list_move(&block_group->bg_list, 1811 &trans->transaction->deleted_bgs); 1812 spin_unlock(&fs_info->unused_bgs_lock); 1813 btrfs_get_block_group(block_group); 1814 } 1815 end_trans: 1816 btrfs_end_transaction(trans); 1817 next: 1818 btrfs_put_block_group(block_group); 1819 spin_lock(&fs_info->unused_bgs_lock); 1820 } 1821 list_splice_tail(&retry_list, &fs_info->unused_bgs); 1822 spin_unlock(&fs_info->unused_bgs_lock); 1823 mutex_unlock(&fs_info->reclaim_bgs_lock); 1824 return; 1825 1826 flip_async: 1827 btrfs_end_transaction(trans); 1828 spin_lock(&fs_info->unused_bgs_lock); 1829 list_splice_tail(&retry_list, &fs_info->unused_bgs); 1830 spin_unlock(&fs_info->unused_bgs_lock); 1831 mutex_unlock(&fs_info->reclaim_bgs_lock); 1832 btrfs_put_block_group(block_group); 1833 btrfs_discard_punt_unused_bgs_list(fs_info); 1834 } 1835 1836 void btrfs_mark_bg_unused(struct btrfs_block_group *bg) 1837 { 1838 struct btrfs_fs_info *fs_info = bg->fs_info; 1839 1840 spin_lock(&fs_info->unused_bgs_lock); 1841 if (list_empty(&bg->bg_list)) { 1842 btrfs_get_block_group(bg); 1843 trace_btrfs_add_unused_block_group(bg); 1844 list_add_tail(&bg->bg_list, &fs_info->unused_bgs); 1845 } else if (bg->flags & BTRFS_BLOCK_GROUP_REMAPPED && 1846 bg->identity_remap_count == 0) { 1847 /* Leave fully remapped block groups on the fully_remapped_bgs list. */ 1848 } else if (!test_bit(BLOCK_GROUP_FLAG_NEW, &bg->runtime_flags)) { 1849 /* Pull out the block group from the reclaim_bgs list. */ 1850 trace_btrfs_add_unused_block_group(bg); 1851 list_move_tail(&bg->bg_list, &fs_info->unused_bgs); 1852 } 1853 spin_unlock(&fs_info->unused_bgs_lock); 1854 } 1855 1856 /* 1857 * We want block groups with a low number of used bytes to be in the beginning 1858 * of the list, so they will get reclaimed first. 1859 */ 1860 static int reclaim_bgs_cmp(void *unused, const struct list_head *a, 1861 const struct list_head *b) 1862 { 1863 const struct btrfs_block_group *bg1, *bg2; 1864 1865 bg1 = list_entry(a, struct btrfs_block_group, bg_list); 1866 bg2 = list_entry(b, struct btrfs_block_group, bg_list); 1867 1868 /* 1869 * Some other task may be updating the ->used field concurrently, but it 1870 * is not serious if we get a stale value or load/store tearing issues, 1871 * as sorting the list of block groups to reclaim is not critical and an 1872 * occasional imperfect order is ok. So silence KCSAN and avoid the 1873 * overhead of locking or any other synchronization. 1874 */ 1875 return data_race(bg1->used > bg2->used); 1876 } 1877 1878 static inline bool btrfs_should_reclaim(const struct btrfs_fs_info *fs_info) 1879 { 1880 if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags)) 1881 return false; 1882 1883 if (btrfs_fs_closing(fs_info)) 1884 return false; 1885 1886 if (btrfs_is_zoned(fs_info)) 1887 return btrfs_zoned_should_reclaim(fs_info); 1888 return true; 1889 } 1890 1891 static bool should_reclaim_block_group(const struct btrfs_block_group *bg, u64 bytes_freed) 1892 { 1893 const int thresh_pct = btrfs_calc_reclaim_threshold(bg->space_info); 1894 u64 thresh_bytes = mult_perc(bg->length, thresh_pct); 1895 const u64 new_val = bg->used; 1896 const u64 old_val = new_val + bytes_freed; 1897 1898 if (thresh_bytes == 0) 1899 return false; 1900 1901 /* 1902 * If we were below the threshold before don't reclaim, we are likely a 1903 * brand new block group and we don't want to relocate new block groups. 1904 */ 1905 if (old_val < thresh_bytes) 1906 return false; 1907 if (new_val >= thresh_bytes) 1908 return false; 1909 return true; 1910 } 1911 1912 static int btrfs_reclaim_block_group(struct btrfs_block_group *bg, int *reclaimed) 1913 { 1914 struct btrfs_fs_info *fs_info = bg->fs_info; 1915 struct btrfs_space_info *space_info = bg->space_info; 1916 u64 used; 1917 u64 reserved; 1918 u64 old_total; 1919 int ret = 0; 1920 1921 /* Don't race with allocators so take the groups_sem */ 1922 down_write(&space_info->groups_sem); 1923 1924 spin_lock(&space_info->lock); 1925 spin_lock(&bg->lock); 1926 if (bg->reserved || bg->pinned || bg->ro) { 1927 /* 1928 * We want to bail if we made new allocations or have 1929 * outstanding allocations in this block group. We do 1930 * the ro check in case balance is currently acting on 1931 * this block group. 1932 */ 1933 spin_unlock(&bg->lock); 1934 spin_unlock(&space_info->lock); 1935 up_write(&space_info->groups_sem); 1936 return 0; 1937 } 1938 1939 if (bg->used == 0) { 1940 /* 1941 * It is possible that we trigger relocation on a block 1942 * group as its extents are deleted and it first goes 1943 * below the threshold, then shortly after goes empty. 1944 * 1945 * In this case, relocating it does delete it, but has 1946 * some overhead in relocation specific metadata, looking 1947 * for the non-existent extents and running some extra 1948 * transactions, which we can avoid by using one of the 1949 * other mechanisms for dealing with empty block groups. 1950 */ 1951 if (!btrfs_test_opt(fs_info, DISCARD_ASYNC)) 1952 btrfs_mark_bg_unused(bg); 1953 spin_unlock(&bg->lock); 1954 spin_unlock(&space_info->lock); 1955 up_write(&space_info->groups_sem); 1956 return 0; 1957 } 1958 1959 /* 1960 * The block group might no longer meet the reclaim condition by 1961 * the time we get around to reclaiming it, so to avoid 1962 * reclaiming overly full block_groups, skip reclaiming them. 1963 * 1964 * Since the decision making process also depends on the amount 1965 * being freed, pass in a fake giant value to skip that extra 1966 * check, which is more meaningful when adding to the list in 1967 * the first place. 1968 */ 1969 if (!should_reclaim_block_group(bg, bg->length)) { 1970 spin_unlock(&bg->lock); 1971 spin_unlock(&space_info->lock); 1972 up_write(&space_info->groups_sem); 1973 return 0; 1974 } 1975 1976 spin_unlock(&bg->lock); 1977 old_total = space_info->total_bytes; 1978 spin_unlock(&space_info->lock); 1979 1980 /* 1981 * Get out fast, in case we're read-only or unmounting the 1982 * filesystem. It is OK to drop block groups from the list even 1983 * for the read-only case. As we did take the super write lock, 1984 * "mount -o remount,ro" won't happen and read-only filesystem 1985 * means it is forced read-only due to a fatal error. So, it 1986 * never gets back to read-write to let us reclaim again. 1987 */ 1988 if (btrfs_need_cleaner_sleep(fs_info)) { 1989 up_write(&space_info->groups_sem); 1990 return 0; 1991 } 1992 1993 ret = inc_block_group_ro(bg, false); 1994 up_write(&space_info->groups_sem); 1995 if (ret < 0) 1996 return ret; 1997 1998 /* 1999 * The amount of bytes reclaimed corresponds to the sum of the 2000 * "used" and "reserved" counters. We have set the block group 2001 * to RO above, which prevents reservations from happening but 2002 * we may have existing reservations for which allocation has 2003 * not yet been done - btrfs_update_block_group() was not yet 2004 * called, which is where we will transfer a reserved extent's 2005 * size from the "reserved" counter to the "used" counter - this 2006 * happens when running delayed references. When we relocate the 2007 * chunk below, relocation first flushes delalloc, waits for 2008 * ordered extent completion (which is where we create delayed 2009 * references for data extents) and commits the current 2010 * transaction (which runs delayed references), and only after 2011 * it does the actual work to move extents out of the block 2012 * group. So the reported amount of reclaimed bytes is 2013 * effectively the sum of the 'used' and 'reserved' counters. 2014 */ 2015 spin_lock(&bg->lock); 2016 used = bg->used; 2017 reserved = bg->reserved; 2018 spin_unlock(&bg->lock); 2019 2020 trace_btrfs_reclaim_block_group(bg); 2021 ret = btrfs_relocate_chunk(fs_info, bg->start, false); 2022 if (ret) { 2023 btrfs_dec_block_group_ro(bg); 2024 btrfs_err(fs_info, "error relocating chunk %llu", 2025 bg->start); 2026 used = 0; 2027 reserved = 0; 2028 spin_lock(&space_info->lock); 2029 space_info->reclaim_errors++; 2030 spin_unlock(&space_info->lock); 2031 } 2032 spin_lock(&space_info->lock); 2033 space_info->reclaim_count++; 2034 space_info->reclaim_bytes += used; 2035 space_info->reclaim_bytes += reserved; 2036 if (space_info->total_bytes < old_total) 2037 btrfs_set_periodic_reclaim_ready(space_info, true); 2038 spin_unlock(&space_info->lock); 2039 if (!ret) 2040 (*reclaimed)++; 2041 2042 return ret; 2043 } 2044 2045 void btrfs_reclaim_block_groups(struct btrfs_fs_info *fs_info, unsigned int limit) 2046 { 2047 struct btrfs_block_group *bg; 2048 struct btrfs_space_info *space_info; 2049 LIST_HEAD(retry_list); 2050 int reclaimed = 0; 2051 2052 if (!btrfs_should_reclaim(fs_info)) 2053 return; 2054 2055 guard(super_write)(fs_info->sb); 2056 2057 if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_BALANCE)) 2058 return; 2059 2060 /* 2061 * Long running balances can keep us blocked here for eternity, so 2062 * simply skip reclaim if we're unable to get the mutex. 2063 */ 2064 if (!mutex_trylock(&fs_info->reclaim_bgs_lock)) { 2065 btrfs_exclop_finish(fs_info); 2066 return; 2067 } 2068 2069 spin_lock(&fs_info->unused_bgs_lock); 2070 /* 2071 * Sort happens under lock because we can't simply splice it and sort. 2072 * The block groups might still be in use and reachable via bg_list, 2073 * and their presence in the reclaim_bgs list must be preserved. 2074 */ 2075 list_sort(NULL, &fs_info->reclaim_bgs, reclaim_bgs_cmp); 2076 while (!list_empty(&fs_info->reclaim_bgs)) { 2077 int ret; 2078 2079 bg = list_first_entry(&fs_info->reclaim_bgs, 2080 struct btrfs_block_group, 2081 bg_list); 2082 list_del_init(&bg->bg_list); 2083 2084 space_info = bg->space_info; 2085 spin_unlock(&fs_info->unused_bgs_lock); 2086 ret = btrfs_reclaim_block_group(bg, &reclaimed); 2087 2088 if (ret && !READ_ONCE(space_info->periodic_reclaim)) 2089 btrfs_link_bg_list(bg, &retry_list); 2090 btrfs_put_block_group(bg); 2091 2092 mutex_unlock(&fs_info->reclaim_bgs_lock); 2093 /* 2094 * Reclaiming all the block groups in the list can take really 2095 * long. Prioritize cleaning up unused block groups. 2096 */ 2097 btrfs_delete_unused_bgs(fs_info); 2098 /* 2099 * If we are interrupted by a balance, we can just bail out. The 2100 * cleaner thread restart again if necessary. 2101 */ 2102 if (!mutex_trylock(&fs_info->reclaim_bgs_lock)) 2103 goto end; 2104 spin_lock(&fs_info->unused_bgs_lock); 2105 if (reclaimed >= limit) 2106 break; 2107 } 2108 spin_unlock(&fs_info->unused_bgs_lock); 2109 mutex_unlock(&fs_info->reclaim_bgs_lock); 2110 end: 2111 spin_lock(&fs_info->unused_bgs_lock); 2112 list_splice_tail(&retry_list, &fs_info->reclaim_bgs); 2113 spin_unlock(&fs_info->unused_bgs_lock); 2114 btrfs_exclop_finish(fs_info); 2115 } 2116 2117 void btrfs_reclaim_bgs_work(struct work_struct *work) 2118 { 2119 struct btrfs_fs_info *fs_info = 2120 container_of(work, struct btrfs_fs_info, reclaim_bgs_work); 2121 2122 btrfs_reclaim_block_groups(fs_info, -1); 2123 } 2124 2125 void btrfs_reclaim_bgs(struct btrfs_fs_info *fs_info) 2126 { 2127 btrfs_reclaim_sweep(fs_info); 2128 spin_lock(&fs_info->unused_bgs_lock); 2129 if (!list_empty(&fs_info->reclaim_bgs)) 2130 queue_work(system_dfl_wq, &fs_info->reclaim_bgs_work); 2131 spin_unlock(&fs_info->unused_bgs_lock); 2132 } 2133 2134 void btrfs_mark_bg_to_reclaim(struct btrfs_block_group *bg) 2135 { 2136 struct btrfs_fs_info *fs_info = bg->fs_info; 2137 2138 if (btrfs_link_bg_list(bg, &fs_info->reclaim_bgs)) 2139 trace_btrfs_add_reclaim_block_group(bg); 2140 } 2141 2142 static int read_bg_from_eb(struct btrfs_fs_info *fs_info, const struct btrfs_key *key, 2143 const struct btrfs_path *path) 2144 { 2145 struct btrfs_chunk_map *map; 2146 struct btrfs_block_group_item bg; 2147 struct extent_buffer *leaf; 2148 int slot; 2149 u64 flags; 2150 int ret = 0; 2151 2152 slot = path->slots[0]; 2153 leaf = path->nodes[0]; 2154 2155 map = btrfs_find_chunk_map(fs_info, key->objectid, key->offset); 2156 if (!map) { 2157 btrfs_err(fs_info, 2158 "logical %llu len %llu found bg but no related chunk", 2159 key->objectid, key->offset); 2160 return -ENOENT; 2161 } 2162 2163 if (unlikely(map->start != key->objectid || map->chunk_len != key->offset)) { 2164 btrfs_err(fs_info, 2165 "block group %llu len %llu mismatch with chunk %llu len %llu", 2166 key->objectid, key->offset, map->start, map->chunk_len); 2167 ret = -EUCLEAN; 2168 goto out_free_map; 2169 } 2170 2171 read_extent_buffer(leaf, &bg, btrfs_item_ptr_offset(leaf, slot), 2172 sizeof(bg)); 2173 flags = btrfs_stack_block_group_flags(&bg) & 2174 BTRFS_BLOCK_GROUP_TYPE_MASK; 2175 2176 if (unlikely(flags != (map->type & BTRFS_BLOCK_GROUP_TYPE_MASK))) { 2177 btrfs_err(fs_info, 2178 "block group %llu len %llu type flags 0x%llx mismatch with chunk type flags 0x%llx", 2179 key->objectid, key->offset, flags, 2180 (BTRFS_BLOCK_GROUP_TYPE_MASK & map->type)); 2181 ret = -EUCLEAN; 2182 } 2183 2184 out_free_map: 2185 btrfs_free_chunk_map(map); 2186 return ret; 2187 } 2188 2189 static int find_first_block_group(struct btrfs_fs_info *fs_info, 2190 struct btrfs_path *path, 2191 const struct btrfs_key *key) 2192 { 2193 struct btrfs_root *root = btrfs_block_group_root(fs_info); 2194 int ret; 2195 struct btrfs_key found_key; 2196 2197 if (unlikely(!root)) { 2198 btrfs_err(fs_info, "missing block group root"); 2199 return -EUCLEAN; 2200 } 2201 2202 btrfs_for_each_slot(root, key, &found_key, path, ret) { 2203 if (found_key.objectid >= key->objectid && 2204 found_key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) { 2205 return read_bg_from_eb(fs_info, &found_key, path); 2206 } 2207 } 2208 return ret; 2209 } 2210 2211 static void set_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags) 2212 { 2213 u64 extra_flags = chunk_to_extended(flags) & 2214 BTRFS_EXTENDED_PROFILE_MASK; 2215 2216 write_seqlock(&fs_info->profiles_lock); 2217 if (flags & BTRFS_BLOCK_GROUP_DATA) 2218 fs_info->avail_data_alloc_bits |= extra_flags; 2219 if (flags & BTRFS_BLOCK_GROUP_METADATA) 2220 fs_info->avail_metadata_alloc_bits |= extra_flags; 2221 if (flags & BTRFS_BLOCK_GROUP_SYSTEM) 2222 fs_info->avail_system_alloc_bits |= extra_flags; 2223 write_sequnlock(&fs_info->profiles_lock); 2224 } 2225 2226 /* 2227 * Map a physical disk address to a list of logical addresses. 2228 * 2229 * @fs_info: the filesystem 2230 * @chunk_start: logical address of block group 2231 * @physical: physical address to map to logical addresses 2232 * @logical: return array of logical addresses which map to @physical 2233 * @naddrs: length of @logical 2234 * @stripe_len: size of IO stripe for the given block group 2235 * 2236 * Maps a particular @physical disk address to a list of @logical addresses. 2237 * Used primarily to exclude those portions of a block group that contain super 2238 * block copies. 2239 */ 2240 int btrfs_rmap_block(struct btrfs_fs_info *fs_info, u64 chunk_start, 2241 u64 physical, u64 **logical, int *naddrs, int *stripe_len) 2242 { 2243 struct btrfs_chunk_map *map; 2244 u64 *buf; 2245 u64 bytenr; 2246 u64 data_stripe_length; 2247 u64 io_stripe_size; 2248 int i, nr = 0; 2249 int ret = 0; 2250 2251 map = btrfs_get_chunk_map(fs_info, chunk_start, 1); 2252 if (IS_ERR(map)) 2253 return -EIO; 2254 2255 data_stripe_length = map->stripe_size; 2256 io_stripe_size = BTRFS_STRIPE_LEN; 2257 chunk_start = map->start; 2258 2259 /* For RAID5/6 adjust to a full IO stripe length */ 2260 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) 2261 io_stripe_size = btrfs_stripe_nr_to_offset(nr_data_stripes(map)); 2262 2263 buf = kzalloc_objs(u64, map->num_stripes, GFP_NOFS); 2264 if (!buf) { 2265 ret = -ENOMEM; 2266 goto out; 2267 } 2268 2269 for (i = 0; i < map->num_stripes; i++) { 2270 bool already_inserted = false; 2271 u32 stripe_nr; 2272 u32 offset; 2273 int j; 2274 2275 if (!in_range(physical, map->stripes[i].physical, 2276 data_stripe_length)) 2277 continue; 2278 2279 stripe_nr = (physical - map->stripes[i].physical) >> 2280 BTRFS_STRIPE_LEN_SHIFT; 2281 offset = (physical - map->stripes[i].physical) & 2282 BTRFS_STRIPE_LEN_MASK; 2283 2284 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 | 2285 BTRFS_BLOCK_GROUP_RAID10)) 2286 stripe_nr = div_u64(stripe_nr * map->num_stripes + i, 2287 map->sub_stripes); 2288 /* 2289 * The remaining case would be for RAID56, multiply by 2290 * nr_data_stripes(). Alternatively, just use rmap_len below 2291 * instead of map->stripe_len 2292 */ 2293 bytenr = chunk_start + stripe_nr * io_stripe_size + offset; 2294 2295 /* Ensure we don't add duplicate addresses */ 2296 for (j = 0; j < nr; j++) { 2297 if (buf[j] == bytenr) { 2298 already_inserted = true; 2299 break; 2300 } 2301 } 2302 2303 if (!already_inserted) 2304 buf[nr++] = bytenr; 2305 } 2306 2307 *logical = buf; 2308 *naddrs = nr; 2309 *stripe_len = io_stripe_size; 2310 out: 2311 btrfs_free_chunk_map(map); 2312 return ret; 2313 } 2314 2315 static int exclude_super_stripes(struct btrfs_block_group *cache) 2316 { 2317 struct btrfs_fs_info *fs_info = cache->fs_info; 2318 const bool zoned = btrfs_is_zoned(fs_info); 2319 u64 bytenr; 2320 u64 *logical; 2321 int stripe_len; 2322 int i, nr, ret; 2323 2324 if (cache->start < BTRFS_SUPER_INFO_OFFSET) { 2325 stripe_len = BTRFS_SUPER_INFO_OFFSET - cache->start; 2326 cache->bytes_super += stripe_len; 2327 ret = btrfs_set_extent_bit(&fs_info->excluded_extents, cache->start, 2328 cache->start + stripe_len - 1, 2329 EXTENT_DIRTY, NULL); 2330 if (ret) 2331 return ret; 2332 } 2333 2334 for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) { 2335 bytenr = btrfs_sb_offset(i); 2336 ret = btrfs_rmap_block(fs_info, cache->start, 2337 bytenr, &logical, &nr, &stripe_len); 2338 if (ret) 2339 return ret; 2340 2341 /* Shouldn't have super stripes in sequential zones */ 2342 if (unlikely(zoned && nr)) { 2343 kfree(logical); 2344 btrfs_err(fs_info, 2345 "zoned: block group %llu must not contain super block", 2346 cache->start); 2347 return -EUCLEAN; 2348 } 2349 2350 while (nr--) { 2351 u64 len = min_t(u64, stripe_len, 2352 btrfs_block_group_end(cache) - logical[nr]); 2353 2354 cache->bytes_super += len; 2355 ret = btrfs_set_extent_bit(&fs_info->excluded_extents, 2356 logical[nr], logical[nr] + len - 1, 2357 EXTENT_DIRTY, NULL); 2358 if (ret) { 2359 kfree(logical); 2360 return ret; 2361 } 2362 } 2363 2364 kfree(logical); 2365 } 2366 return 0; 2367 } 2368 2369 static struct btrfs_block_group *btrfs_create_block_group( 2370 struct btrfs_fs_info *fs_info, u64 start) 2371 { 2372 struct btrfs_block_group *cache; 2373 2374 cache = kzalloc_obj(*cache, GFP_NOFS); 2375 if (!cache) 2376 return NULL; 2377 2378 cache->free_space_ctl = kzalloc_obj(*cache->free_space_ctl, GFP_NOFS); 2379 if (!cache->free_space_ctl) { 2380 kfree(cache); 2381 return NULL; 2382 } 2383 2384 cache->start = start; 2385 2386 cache->fs_info = fs_info; 2387 cache->full_stripe_len = btrfs_full_stripe_len(fs_info, start); 2388 2389 cache->discard_index = BTRFS_DISCARD_INDEX_UNUSED; 2390 2391 refcount_set(&cache->refs, 1); 2392 spin_lock_init(&cache->lock); 2393 init_rwsem(&cache->data_rwsem); 2394 INIT_LIST_HEAD(&cache->list); 2395 INIT_LIST_HEAD(&cache->cluster_list); 2396 INIT_LIST_HEAD(&cache->bg_list); 2397 INIT_LIST_HEAD(&cache->ro_list); 2398 INIT_LIST_HEAD(&cache->discard_list); 2399 INIT_LIST_HEAD(&cache->dirty_list); 2400 INIT_LIST_HEAD(&cache->io_list); 2401 INIT_LIST_HEAD(&cache->active_bg_list); 2402 btrfs_init_free_space_ctl(cache, cache->free_space_ctl); 2403 atomic_set(&cache->frozen, 0); 2404 mutex_init(&cache->free_space_lock); 2405 2406 return cache; 2407 } 2408 2409 /* 2410 * Iterate all chunks and verify that each of them has the corresponding block 2411 * group 2412 */ 2413 static int check_chunk_block_group_mappings(struct btrfs_fs_info *fs_info) 2414 { 2415 u64 start = 0; 2416 int ret = 0; 2417 2418 while (1) { 2419 struct btrfs_chunk_map *map; 2420 struct btrfs_block_group *bg; 2421 2422 /* 2423 * btrfs_find_chunk_map() will return the first chunk map 2424 * intersecting the range, so setting @length to 1 is enough to 2425 * get the first chunk. 2426 */ 2427 map = btrfs_find_chunk_map(fs_info, start, 1); 2428 if (!map) 2429 break; 2430 2431 bg = btrfs_lookup_block_group(fs_info, map->start); 2432 if (unlikely(!bg)) { 2433 btrfs_err(fs_info, 2434 "chunk start=%llu len=%llu doesn't have corresponding block group", 2435 map->start, map->chunk_len); 2436 ret = -EUCLEAN; 2437 btrfs_free_chunk_map(map); 2438 break; 2439 } 2440 if (unlikely(bg->start != map->start || bg->length != map->chunk_len || 2441 (bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK) != 2442 (map->type & BTRFS_BLOCK_GROUP_TYPE_MASK))) { 2443 btrfs_err(fs_info, 2444 "chunk start=%llu len=%llu flags=0x%llx doesn't match block group start=%llu len=%llu flags=0x%llx", 2445 map->start, map->chunk_len, 2446 map->type & BTRFS_BLOCK_GROUP_TYPE_MASK, 2447 bg->start, bg->length, 2448 bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK); 2449 ret = -EUCLEAN; 2450 btrfs_free_chunk_map(map); 2451 btrfs_put_block_group(bg); 2452 break; 2453 } 2454 start = map->start + map->chunk_len; 2455 btrfs_free_chunk_map(map); 2456 btrfs_put_block_group(bg); 2457 } 2458 return ret; 2459 } 2460 2461 static int read_one_block_group(struct btrfs_fs_info *info, 2462 struct btrfs_block_group_item_v2 *bgi, 2463 const struct btrfs_key *key, 2464 int need_clear) 2465 { 2466 struct btrfs_block_group *cache; 2467 const bool mixed = btrfs_fs_incompat(info, MIXED_GROUPS); 2468 int ret; 2469 2470 ASSERT(key->type == BTRFS_BLOCK_GROUP_ITEM_KEY); 2471 2472 cache = btrfs_create_block_group(info, key->objectid); 2473 if (!cache) 2474 return -ENOMEM; 2475 2476 cache->length = key->offset; 2477 cache->used = btrfs_stack_block_group_v2_used(bgi); 2478 cache->last_used = cache->used; 2479 cache->flags = btrfs_stack_block_group_v2_flags(bgi); 2480 cache->last_flags = cache->flags; 2481 cache->global_root_id = btrfs_stack_block_group_v2_chunk_objectid(bgi); 2482 cache->space_info = btrfs_find_space_info(info, cache->flags); 2483 cache->remap_bytes = btrfs_stack_block_group_v2_remap_bytes(bgi); 2484 cache->last_remap_bytes = cache->remap_bytes; 2485 cache->identity_remap_count = btrfs_stack_block_group_v2_identity_remap_count(bgi); 2486 cache->last_identity_remap_count = cache->identity_remap_count; 2487 2488 btrfs_set_free_space_tree_thresholds(cache); 2489 2490 if (need_clear) { 2491 /* 2492 * When we mount with old space cache, we need to 2493 * set BTRFS_DC_CLEAR and set dirty flag. 2494 * 2495 * a) Setting 'BTRFS_DC_CLEAR' makes sure that we 2496 * truncate the old free space cache inode and 2497 * setup a new one. 2498 * b) Setting 'dirty flag' makes sure that we flush 2499 * the new space cache info onto disk. 2500 */ 2501 if (btrfs_test_opt(info, SPACE_CACHE)) 2502 cache->disk_cache_state = BTRFS_DC_CLEAR; 2503 } 2504 if (!mixed && ((cache->flags & BTRFS_BLOCK_GROUP_METADATA) && 2505 (cache->flags & BTRFS_BLOCK_GROUP_DATA))) { 2506 btrfs_err(info, 2507 "bg %llu is a mixed block group but filesystem hasn't enabled mixed block groups", 2508 cache->start); 2509 ret = -EINVAL; 2510 goto error; 2511 } 2512 2513 ret = btrfs_load_block_group_zone_info(cache, false); 2514 if (ret) { 2515 btrfs_err(info, "zoned: failed to load zone info of bg %llu", 2516 cache->start); 2517 goto error; 2518 } 2519 2520 /* 2521 * We need to exclude the super stripes now so that the space info has 2522 * super bytes accounted for, otherwise we'll think we have more space 2523 * than we actually do. 2524 */ 2525 ret = exclude_super_stripes(cache); 2526 if (ret) { 2527 /* We may have excluded something, so call this just in case. */ 2528 btrfs_free_excluded_extents(cache); 2529 goto error; 2530 } 2531 2532 /* 2533 * For zoned filesystem, space after the allocation offset is the only 2534 * free space for a block group. So, we don't need any caching work. 2535 * btrfs_calc_zone_unusable() will set the amount of free space and 2536 * zone_unusable space. 2537 * 2538 * For regular filesystem, check for two cases, either we are full, and 2539 * therefore don't need to bother with the caching work since we won't 2540 * find any space, or we are empty, and we can just add all the space 2541 * in and be done with it. This saves us _a_lot_ of time, particularly 2542 * in the full case. 2543 */ 2544 if (btrfs_is_zoned(info)) { 2545 btrfs_calc_zone_unusable(cache); 2546 /* Should not have any excluded extents. Just in case, though. */ 2547 btrfs_free_excluded_extents(cache); 2548 } else if (cache->length == cache->used) { 2549 cache->cached = BTRFS_CACHE_FINISHED; 2550 btrfs_free_excluded_extents(cache); 2551 } else if (cache->used == 0 && cache->remap_bytes == 0) { 2552 cache->cached = BTRFS_CACHE_FINISHED; 2553 ret = btrfs_add_new_free_space(cache, cache->start, 2554 btrfs_block_group_end(cache), NULL); 2555 btrfs_free_excluded_extents(cache); 2556 if (ret) 2557 goto error; 2558 } 2559 2560 ret = btrfs_add_block_group_cache(cache); 2561 if (ret) { 2562 btrfs_remove_free_space_cache(cache); 2563 goto error; 2564 } 2565 2566 trace_btrfs_add_block_group(info, cache, 0); 2567 btrfs_add_bg_to_space_info(info, cache); 2568 2569 set_avail_alloc_bits(info, cache->flags); 2570 if (btrfs_chunk_writeable(info, cache->start)) { 2571 if (cache->used == 0 && cache->remap_bytes == 0) { 2572 ASSERT(list_empty(&cache->bg_list)); 2573 if (btrfs_test_opt(info, DISCARD_ASYNC)) 2574 btrfs_discard_queue_work(&info->discard_ctl, cache); 2575 else 2576 btrfs_mark_bg_unused(cache); 2577 } 2578 } else { 2579 inc_block_group_ro(cache, true); 2580 } 2581 2582 return 0; 2583 error: 2584 btrfs_put_block_group(cache); 2585 return ret; 2586 } 2587 2588 static int fill_dummy_bgs(struct btrfs_fs_info *fs_info) 2589 { 2590 struct rb_node *node; 2591 int ret = 0; 2592 2593 for (node = rb_first_cached(&fs_info->mapping_tree); node; node = rb_next(node)) { 2594 struct btrfs_chunk_map *map; 2595 struct btrfs_block_group *bg; 2596 2597 map = rb_entry(node, struct btrfs_chunk_map, rb_node); 2598 bg = btrfs_create_block_group(fs_info, map->start); 2599 if (!bg) { 2600 ret = -ENOMEM; 2601 break; 2602 } 2603 2604 /* Fill dummy cache as FULL */ 2605 bg->length = map->chunk_len; 2606 bg->flags = map->type; 2607 bg->cached = BTRFS_CACHE_FINISHED; 2608 bg->used = map->chunk_len; 2609 bg->flags = map->type; 2610 bg->space_info = btrfs_find_space_info(fs_info, bg->flags); 2611 ret = btrfs_add_block_group_cache(bg); 2612 /* 2613 * We may have some valid block group cache added already, in 2614 * that case we skip to the next one. 2615 */ 2616 if (ret == -EEXIST) { 2617 ret = 0; 2618 btrfs_put_block_group(bg); 2619 continue; 2620 } 2621 2622 if (ret) { 2623 btrfs_remove_free_space_cache(bg); 2624 btrfs_put_block_group(bg); 2625 break; 2626 } 2627 2628 btrfs_add_bg_to_space_info(fs_info, bg); 2629 2630 set_avail_alloc_bits(fs_info, bg->flags); 2631 } 2632 if (!ret) 2633 btrfs_init_global_block_rsv(fs_info); 2634 return ret; 2635 } 2636 2637 int btrfs_read_block_groups(struct btrfs_fs_info *info) 2638 { 2639 struct btrfs_root *root = btrfs_block_group_root(info); 2640 struct btrfs_path *path; 2641 int ret; 2642 struct btrfs_block_group *cache; 2643 struct btrfs_space_info *space_info; 2644 struct btrfs_key key; 2645 int need_clear = 0; 2646 u64 cache_gen; 2647 2648 /* 2649 * Either no extent root (with ibadroots rescue option) or we have 2650 * unsupported RO options. The fs can never be mounted read-write, so no 2651 * need to waste time searching block group items. 2652 * 2653 * This also allows new extent tree related changes to be RO compat, 2654 * no need for a full incompat flag. 2655 */ 2656 if (!root || (btrfs_super_compat_ro_flags(info->super_copy) & 2657 ~BTRFS_FEATURE_COMPAT_RO_SUPP)) 2658 return fill_dummy_bgs(info); 2659 2660 key.objectid = 0; 2661 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY; 2662 key.offset = 0; 2663 path = btrfs_alloc_path(); 2664 if (!path) 2665 return -ENOMEM; 2666 2667 cache_gen = btrfs_super_cache_generation(info->super_copy); 2668 if (btrfs_test_opt(info, SPACE_CACHE) && 2669 btrfs_super_generation(info->super_copy) != cache_gen) 2670 need_clear = 1; 2671 if (btrfs_test_opt(info, CLEAR_CACHE)) 2672 need_clear = 1; 2673 2674 while (1) { 2675 struct btrfs_block_group_item_v2 bgi; 2676 struct extent_buffer *leaf; 2677 int slot; 2678 size_t size; 2679 2680 ret = find_first_block_group(info, path, &key); 2681 if (ret > 0) 2682 break; 2683 if (ret != 0) 2684 goto error; 2685 2686 leaf = path->nodes[0]; 2687 slot = path->slots[0]; 2688 2689 if (btrfs_fs_incompat(info, REMAP_TREE)) { 2690 size = sizeof(struct btrfs_block_group_item_v2); 2691 } else { 2692 size = sizeof(struct btrfs_block_group_item); 2693 btrfs_set_stack_block_group_v2_remap_bytes(&bgi, 0); 2694 btrfs_set_stack_block_group_v2_identity_remap_count(&bgi, 0); 2695 } 2696 2697 read_extent_buffer(leaf, &bgi, btrfs_item_ptr_offset(leaf, slot), 2698 size); 2699 2700 btrfs_item_key_to_cpu(leaf, &key, slot); 2701 btrfs_release_path(path); 2702 ret = read_one_block_group(info, &bgi, &key, need_clear); 2703 if (ret < 0) 2704 goto error; 2705 key.objectid += key.offset; 2706 key.offset = 0; 2707 } 2708 btrfs_release_path(path); 2709 2710 list_for_each_entry(space_info, &info->space_info, list) { 2711 int i; 2712 2713 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) { 2714 if (list_empty(&space_info->block_groups[i])) 2715 continue; 2716 cache = list_first_entry(&space_info->block_groups[i], 2717 struct btrfs_block_group, 2718 list); 2719 btrfs_sysfs_add_block_group_type(cache); 2720 } 2721 2722 if (!(btrfs_get_alloc_profile(info, space_info->flags) & 2723 (BTRFS_BLOCK_GROUP_RAID10 | 2724 BTRFS_BLOCK_GROUP_RAID1_MASK | 2725 BTRFS_BLOCK_GROUP_RAID56_MASK | 2726 BTRFS_BLOCK_GROUP_DUP))) 2727 continue; 2728 /* 2729 * Avoid allocating from un-mirrored block group if there are 2730 * mirrored block groups. 2731 */ 2732 list_for_each_entry(cache, 2733 &space_info->block_groups[BTRFS_RAID_RAID0], 2734 list) 2735 inc_block_group_ro(cache, true); 2736 list_for_each_entry(cache, 2737 &space_info->block_groups[BTRFS_RAID_SINGLE], 2738 list) 2739 inc_block_group_ro(cache, true); 2740 } 2741 2742 btrfs_init_global_block_rsv(info); 2743 ret = check_chunk_block_group_mappings(info); 2744 error: 2745 btrfs_free_path(path); 2746 /* 2747 * We've hit some error while reading the extent tree, and have 2748 * rescue=ibadroots mount option. 2749 * Try to fill the tree using dummy block groups so that the user can 2750 * continue to mount and grab their data. 2751 */ 2752 if (ret && btrfs_test_opt(info, IGNOREBADROOTS)) 2753 ret = fill_dummy_bgs(info); 2754 return ret; 2755 } 2756 2757 /* 2758 * This function, insert_block_group_item(), belongs to the phase 2 of chunk 2759 * allocation. 2760 * 2761 * See the comment at btrfs_chunk_alloc() for details about the chunk allocation 2762 * phases. 2763 */ 2764 static int insert_block_group_item(struct btrfs_trans_handle *trans, 2765 struct btrfs_block_group *block_group) 2766 { 2767 struct btrfs_fs_info *fs_info = trans->fs_info; 2768 struct btrfs_block_group_item_v2 bgi; 2769 struct btrfs_root *root = btrfs_block_group_root(fs_info); 2770 struct btrfs_key key; 2771 u64 old_last_used; 2772 size_t size; 2773 int ret; 2774 2775 if (unlikely(!root)) { 2776 btrfs_err(fs_info, "missing block group root"); 2777 return -EUCLEAN; 2778 } 2779 2780 spin_lock(&block_group->lock); 2781 btrfs_set_stack_block_group_v2_used(&bgi, block_group->used); 2782 btrfs_set_stack_block_group_v2_chunk_objectid(&bgi, block_group->global_root_id); 2783 btrfs_set_stack_block_group_v2_flags(&bgi, block_group->flags); 2784 btrfs_set_stack_block_group_v2_remap_bytes(&bgi, block_group->remap_bytes); 2785 btrfs_set_stack_block_group_v2_identity_remap_count(&bgi, block_group->identity_remap_count); 2786 old_last_used = block_group->last_used; 2787 block_group->last_used = block_group->used; 2788 block_group->last_remap_bytes = block_group->remap_bytes; 2789 block_group->last_identity_remap_count = block_group->identity_remap_count; 2790 block_group->last_flags = block_group->flags; 2791 key.objectid = block_group->start; 2792 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY; 2793 key.offset = block_group->length; 2794 spin_unlock(&block_group->lock); 2795 2796 if (btrfs_fs_incompat(fs_info, REMAP_TREE)) 2797 size = sizeof(struct btrfs_block_group_item_v2); 2798 else 2799 size = sizeof(struct btrfs_block_group_item); 2800 2801 ret = btrfs_insert_item(trans, root, &key, &bgi, size); 2802 if (ret < 0) { 2803 spin_lock(&block_group->lock); 2804 block_group->last_used = old_last_used; 2805 spin_unlock(&block_group->lock); 2806 } 2807 2808 return ret; 2809 } 2810 2811 static int insert_dev_extent(struct btrfs_trans_handle *trans, 2812 const struct btrfs_device *device, u64 chunk_offset, 2813 u64 start, u64 num_bytes) 2814 { 2815 struct btrfs_fs_info *fs_info = device->fs_info; 2816 struct btrfs_root *root = fs_info->dev_root; 2817 BTRFS_PATH_AUTO_FREE(path); 2818 struct btrfs_dev_extent *extent; 2819 struct extent_buffer *leaf; 2820 struct btrfs_key key; 2821 int ret; 2822 2823 WARN_ON(!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state)); 2824 WARN_ON(test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)); 2825 path = btrfs_alloc_path(); 2826 if (!path) 2827 return -ENOMEM; 2828 2829 key.objectid = device->devid; 2830 key.type = BTRFS_DEV_EXTENT_KEY; 2831 key.offset = start; 2832 ret = btrfs_insert_empty_item(trans, root, path, &key, sizeof(*extent)); 2833 if (ret) 2834 return ret; 2835 2836 leaf = path->nodes[0]; 2837 extent = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_extent); 2838 btrfs_set_dev_extent_chunk_tree(leaf, extent, BTRFS_CHUNK_TREE_OBJECTID); 2839 btrfs_set_dev_extent_chunk_objectid(leaf, extent, 2840 BTRFS_FIRST_CHUNK_TREE_OBJECTID); 2841 btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset); 2842 btrfs_set_dev_extent_length(leaf, extent, num_bytes); 2843 2844 return ret; 2845 } 2846 2847 /* 2848 * This function belongs to phase 2. 2849 * 2850 * See the comment at btrfs_chunk_alloc() for details about the chunk allocation 2851 * phases. 2852 */ 2853 static int insert_dev_extents(struct btrfs_trans_handle *trans, 2854 u64 chunk_offset, u64 chunk_size) 2855 { 2856 struct btrfs_fs_info *fs_info = trans->fs_info; 2857 struct btrfs_device *device; 2858 struct btrfs_chunk_map *map; 2859 u64 dev_offset; 2860 int i; 2861 int ret = 0; 2862 2863 map = btrfs_get_chunk_map(fs_info, chunk_offset, chunk_size); 2864 if (IS_ERR(map)) 2865 return PTR_ERR(map); 2866 2867 /* 2868 * Take the device list mutex to prevent races with the final phase of 2869 * a device replace operation that replaces the device object associated 2870 * with the map's stripes, because the device object's id can change 2871 * at any time during that final phase of the device replace operation 2872 * (dev-replace.c:btrfs_dev_replace_finishing()), so we could grab the 2873 * replaced device and then see it with an ID of BTRFS_DEV_REPLACE_DEVID, 2874 * resulting in persisting a device extent item with such ID. 2875 */ 2876 mutex_lock(&fs_info->fs_devices->device_list_mutex); 2877 for (i = 0; i < map->num_stripes; i++) { 2878 device = map->stripes[i].dev; 2879 dev_offset = map->stripes[i].physical; 2880 2881 ret = insert_dev_extent(trans, device, chunk_offset, dev_offset, 2882 map->stripe_size); 2883 if (ret) 2884 break; 2885 } 2886 mutex_unlock(&fs_info->fs_devices->device_list_mutex); 2887 2888 btrfs_free_chunk_map(map); 2889 return ret; 2890 } 2891 2892 /* 2893 * This function, btrfs_create_pending_block_groups(), belongs to the phase 2 of 2894 * chunk allocation. 2895 * 2896 * See the comment at btrfs_chunk_alloc() for details about the chunk allocation 2897 * phases. 2898 */ 2899 void btrfs_create_pending_block_groups(struct btrfs_trans_handle *trans) 2900 { 2901 struct btrfs_fs_info *fs_info = trans->fs_info; 2902 struct btrfs_block_group *block_group; 2903 int ret = 0; 2904 2905 while (!list_empty(&trans->new_bgs)) { 2906 int index; 2907 2908 block_group = list_first_entry(&trans->new_bgs, 2909 struct btrfs_block_group, 2910 bg_list); 2911 if (ret) 2912 goto next; 2913 2914 index = btrfs_bg_flags_to_raid_index(block_group->flags); 2915 2916 ret = insert_block_group_item(trans, block_group); 2917 if (ret) 2918 btrfs_abort_transaction(trans, ret); 2919 if (!test_bit(BLOCK_GROUP_FLAG_CHUNK_ITEM_INSERTED, 2920 &block_group->runtime_flags)) { 2921 mutex_lock(&fs_info->chunk_mutex); 2922 ret = btrfs_chunk_alloc_add_chunk_item(trans, block_group); 2923 mutex_unlock(&fs_info->chunk_mutex); 2924 if (ret) 2925 btrfs_abort_transaction(trans, ret); 2926 } 2927 ret = insert_dev_extents(trans, block_group->start, 2928 block_group->length); 2929 if (ret) 2930 btrfs_abort_transaction(trans, ret); 2931 btrfs_add_block_group_free_space(trans, block_group); 2932 2933 /* 2934 * If we restriped during balance, we may have added a new raid 2935 * type, so now add the sysfs entries when it is safe to do so. 2936 * We don't have to worry about locking here as it's handled in 2937 * btrfs_sysfs_add_block_group_type. 2938 */ 2939 if (block_group->space_info->block_group_kobjs[index] == NULL) 2940 btrfs_sysfs_add_block_group_type(block_group); 2941 2942 /* Already aborted the transaction if it failed. */ 2943 next: 2944 btrfs_dec_delayed_refs_rsv_bg_inserts(fs_info); 2945 2946 spin_lock(&fs_info->unused_bgs_lock); 2947 list_del_init(&block_group->bg_list); 2948 clear_bit(BLOCK_GROUP_FLAG_NEW, &block_group->runtime_flags); 2949 btrfs_put_block_group(block_group); 2950 spin_unlock(&fs_info->unused_bgs_lock); 2951 2952 /* 2953 * If the block group is still unused, add it to the list of 2954 * unused block groups. The block group may have been created in 2955 * order to satisfy a space reservation, in which case the 2956 * extent allocation only happens later. But often we don't 2957 * actually need to allocate space that we previously reserved, 2958 * so the block group may become unused for a long time. For 2959 * example for metadata we generally reserve space for a worst 2960 * possible scenario, but then don't end up allocating all that 2961 * space or none at all (due to no need to COW, extent buffers 2962 * were already COWed in the current transaction and still 2963 * unwritten, tree heights lower than the maximum possible 2964 * height, etc). For data we generally reserve the exact amount 2965 * of space we are going to allocate later, the exception is 2966 * when using compression, as we must reserve space based on the 2967 * uncompressed data size, because the compression is only done 2968 * when writeback triggered and we don't know how much space we 2969 * are actually going to need, so we reserve the uncompressed 2970 * size because the data may be incompressible in the worst case. 2971 */ 2972 if (ret == 0) { 2973 bool used; 2974 2975 spin_lock(&block_group->lock); 2976 used = btrfs_is_block_group_used(block_group); 2977 spin_unlock(&block_group->lock); 2978 2979 if (!used) 2980 btrfs_mark_bg_unused(block_group); 2981 } 2982 } 2983 btrfs_trans_release_chunk_metadata(trans); 2984 } 2985 2986 /* 2987 * For extent tree v2 we use the block_group_item->chunk_offset to point at our 2988 * global root id. For v1 it's always set to BTRFS_FIRST_CHUNK_TREE_OBJECTID. 2989 */ 2990 static u64 calculate_global_root_id(const struct btrfs_fs_info *fs_info, u64 offset) 2991 { 2992 u64 div = SZ_1G; 2993 u64 index; 2994 2995 if (!btrfs_fs_incompat(fs_info, EXTENT_TREE_V2)) 2996 return BTRFS_FIRST_CHUNK_TREE_OBJECTID; 2997 2998 /* If we have a smaller fs index based on 128MiB. */ 2999 if (btrfs_super_total_bytes(fs_info->super_copy) <= (SZ_1G * 10ULL)) 3000 div = SZ_128M; 3001 3002 offset = div64_u64(offset, div); 3003 div64_u64_rem(offset, fs_info->nr_global_roots, &index); 3004 return index; 3005 } 3006 3007 struct btrfs_block_group *btrfs_make_block_group(struct btrfs_trans_handle *trans, 3008 struct btrfs_space_info *space_info, 3009 u64 type, u64 chunk_offset, u64 size) 3010 { 3011 struct btrfs_fs_info *fs_info = trans->fs_info; 3012 struct btrfs_block_group *cache; 3013 int ret; 3014 3015 btrfs_set_log_full_commit(trans); 3016 3017 cache = btrfs_create_block_group(fs_info, chunk_offset); 3018 if (!cache) 3019 return ERR_PTR(-ENOMEM); 3020 3021 /* 3022 * Mark it as new before adding it to the rbtree of block groups or any 3023 * list, so that no other task finds it and calls btrfs_mark_bg_unused() 3024 * before the new flag is set. 3025 */ 3026 set_bit(BLOCK_GROUP_FLAG_NEW, &cache->runtime_flags); 3027 3028 cache->length = size; 3029 btrfs_set_free_space_tree_thresholds(cache); 3030 cache->flags = type; 3031 cache->cached = BTRFS_CACHE_FINISHED; 3032 cache->global_root_id = calculate_global_root_id(fs_info, cache->start); 3033 3034 if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) 3035 set_bit(BLOCK_GROUP_FLAG_NEEDS_FREE_SPACE, &cache->runtime_flags); 3036 3037 ret = btrfs_load_block_group_zone_info(cache, true); 3038 if (ret) { 3039 btrfs_put_block_group(cache); 3040 return ERR_PTR(ret); 3041 } 3042 3043 ret = exclude_super_stripes(cache); 3044 if (ret) { 3045 /* We may have excluded something, so call this just in case */ 3046 btrfs_free_excluded_extents(cache); 3047 btrfs_put_block_group(cache); 3048 return ERR_PTR(ret); 3049 } 3050 3051 ret = btrfs_add_new_free_space(cache, chunk_offset, chunk_offset + size, NULL); 3052 btrfs_free_excluded_extents(cache); 3053 if (ret) { 3054 btrfs_put_block_group(cache); 3055 return ERR_PTR(ret); 3056 } 3057 3058 /* 3059 * Ensure the corresponding space_info object is created and 3060 * assigned to our block group. We want our bg to be added to the rbtree 3061 * with its ->space_info set. 3062 */ 3063 cache->space_info = space_info; 3064 ASSERT(cache->space_info); 3065 3066 ret = btrfs_add_block_group_cache(cache); 3067 if (ret) { 3068 btrfs_remove_free_space_cache(cache); 3069 btrfs_put_block_group(cache); 3070 return ERR_PTR(ret); 3071 } 3072 3073 /* 3074 * Now that our block group has its ->space_info set and is inserted in 3075 * the rbtree, update the space info's counters. 3076 */ 3077 trace_btrfs_add_block_group(fs_info, cache, 1); 3078 btrfs_add_bg_to_space_info(fs_info, cache); 3079 btrfs_update_global_block_rsv(fs_info); 3080 3081 #ifdef CONFIG_BTRFS_DEBUG 3082 if (btrfs_should_fragment_free_space(cache)) { 3083 cache->space_info->bytes_used += size >> 1; 3084 fragment_free_space(cache); 3085 } 3086 #endif 3087 3088 btrfs_link_bg_list(cache, &trans->new_bgs); 3089 btrfs_inc_delayed_refs_rsv_bg_inserts(fs_info); 3090 3091 set_avail_alloc_bits(fs_info, type); 3092 return cache; 3093 } 3094 3095 /* 3096 * Mark one block group RO, can be called several times for the same block 3097 * group. 3098 * 3099 * @cache: the destination block group 3100 * @do_chunk_alloc: whether need to do chunk pre-allocation, this is to 3101 * ensure we still have some free space after marking this 3102 * block group RO. 3103 */ 3104 int btrfs_inc_block_group_ro(struct btrfs_block_group *cache, 3105 bool do_chunk_alloc) 3106 { 3107 struct btrfs_fs_info *fs_info = cache->fs_info; 3108 struct btrfs_space_info *space_info = cache->space_info; 3109 struct btrfs_trans_handle *trans; 3110 struct btrfs_root *root = btrfs_block_group_root(fs_info); 3111 u64 alloc_flags; 3112 int ret; 3113 bool dirty_bg_running; 3114 3115 if (unlikely(!root)) { 3116 btrfs_err(fs_info, "missing block group root"); 3117 return -EUCLEAN; 3118 } 3119 3120 /* 3121 * This can only happen when we are doing read-only scrub on read-only 3122 * mount. 3123 * In that case we should not start a new transaction on read-only fs. 3124 * Thus here we skip all chunk allocations. 3125 */ 3126 if (sb_rdonly(fs_info->sb)) { 3127 mutex_lock(&fs_info->ro_block_group_mutex); 3128 ret = inc_block_group_ro(cache, false); 3129 mutex_unlock(&fs_info->ro_block_group_mutex); 3130 return ret; 3131 } 3132 3133 do { 3134 trans = btrfs_join_transaction(root); 3135 if (IS_ERR(trans)) 3136 return PTR_ERR(trans); 3137 3138 dirty_bg_running = false; 3139 3140 /* 3141 * We're not allowed to set block groups readonly after the dirty 3142 * block group cache has started writing. If it already started, 3143 * back off and let this transaction commit. 3144 */ 3145 mutex_lock(&fs_info->ro_block_group_mutex); 3146 if (test_bit(BTRFS_TRANS_DIRTY_BG_RUN, &trans->transaction->flags)) { 3147 u64 transid = trans->transid; 3148 3149 mutex_unlock(&fs_info->ro_block_group_mutex); 3150 btrfs_end_transaction(trans); 3151 3152 ret = btrfs_wait_for_commit(fs_info, transid); 3153 if (ret) 3154 return ret; 3155 dirty_bg_running = true; 3156 } 3157 } while (dirty_bg_running); 3158 3159 if (do_chunk_alloc) { 3160 /* 3161 * If we are changing raid levels, try to allocate a 3162 * corresponding block group with the new raid level. 3163 */ 3164 alloc_flags = btrfs_get_alloc_profile(fs_info, cache->flags); 3165 if (alloc_flags != cache->flags) { 3166 ret = btrfs_chunk_alloc(trans, space_info, alloc_flags, 3167 CHUNK_ALLOC_FORCE); 3168 /* 3169 * ENOSPC is allowed here, we may have enough space 3170 * already allocated at the new raid level to carry on 3171 */ 3172 if (ret == -ENOSPC) 3173 ret = 0; 3174 if (ret < 0) 3175 goto out; 3176 } 3177 } 3178 3179 ret = inc_block_group_ro(cache, false); 3180 if (!ret) 3181 goto out; 3182 if (ret == -ETXTBSY) 3183 goto unlock_out; 3184 3185 /* 3186 * Skip chunk allocation if the bg is SYSTEM, this is to avoid system 3187 * chunk allocation storm to exhaust the system chunk array. Otherwise 3188 * we still want to try our best to mark the block group read-only. 3189 */ 3190 if (!do_chunk_alloc && ret == -ENOSPC && 3191 (cache->flags & BTRFS_BLOCK_GROUP_SYSTEM)) 3192 goto unlock_out; 3193 3194 alloc_flags = btrfs_get_alloc_profile(fs_info, space_info->flags); 3195 ret = btrfs_chunk_alloc(trans, space_info, alloc_flags, CHUNK_ALLOC_FORCE); 3196 if (ret < 0) 3197 goto out; 3198 /* 3199 * We have allocated a new chunk. We also need to activate that chunk to 3200 * grant metadata tickets for zoned filesystem. 3201 */ 3202 ret = btrfs_zoned_activate_one_bg(space_info, true); 3203 if (ret < 0) 3204 goto out; 3205 3206 ret = inc_block_group_ro(cache, false); 3207 if (ret == -ETXTBSY) 3208 goto unlock_out; 3209 out: 3210 if (cache->flags & BTRFS_BLOCK_GROUP_SYSTEM) { 3211 alloc_flags = btrfs_get_alloc_profile(fs_info, cache->flags); 3212 mutex_lock(&fs_info->chunk_mutex); 3213 check_system_chunk(trans, alloc_flags); 3214 mutex_unlock(&fs_info->chunk_mutex); 3215 } 3216 unlock_out: 3217 mutex_unlock(&fs_info->ro_block_group_mutex); 3218 3219 btrfs_end_transaction(trans); 3220 return ret; 3221 } 3222 3223 void btrfs_dec_block_group_ro(struct btrfs_block_group *cache) 3224 { 3225 struct btrfs_space_info *sinfo = cache->space_info; 3226 3227 BUG_ON(!cache->ro); 3228 3229 spin_lock(&sinfo->lock); 3230 spin_lock(&cache->lock); 3231 if (!--cache->ro) { 3232 if (btrfs_is_zoned(cache->fs_info)) { 3233 /* Migrate zone_unusable bytes back */ 3234 cache->zone_unusable = 3235 (cache->alloc_offset - cache->used - cache->pinned - 3236 cache->reserved) + 3237 (cache->length - cache->zone_capacity); 3238 btrfs_space_info_update_bytes_zone_unusable(sinfo, cache->zone_unusable); 3239 sinfo->bytes_readonly -= cache->zone_unusable; 3240 } 3241 sinfo->bytes_readonly -= btrfs_block_group_available_space(cache); 3242 list_del_init(&cache->ro_list); 3243 } 3244 spin_unlock(&cache->lock); 3245 spin_unlock(&sinfo->lock); 3246 } 3247 3248 static int update_block_group_item(struct btrfs_trans_handle *trans, 3249 struct btrfs_path *path, 3250 struct btrfs_block_group *cache) 3251 { 3252 struct btrfs_fs_info *fs_info = trans->fs_info; 3253 int ret; 3254 struct btrfs_root *root = btrfs_block_group_root(fs_info); 3255 unsigned long bi; 3256 struct extent_buffer *leaf; 3257 struct btrfs_block_group_item_v2 bgi; 3258 struct btrfs_key key; 3259 u64 old_last_used, old_last_remap_bytes; 3260 u32 old_last_identity_remap_count; 3261 u64 used, remap_bytes; 3262 u32 identity_remap_count; 3263 3264 if (unlikely(!root)) { 3265 btrfs_err(fs_info, "missing block group root"); 3266 return -EUCLEAN; 3267 } 3268 3269 /* 3270 * Block group items update can be triggered out of commit transaction 3271 * critical section, thus we need a consistent view of used bytes. 3272 * We cannot use cache->used directly outside of the spin lock, as it 3273 * may be changed. 3274 */ 3275 spin_lock(&cache->lock); 3276 old_last_used = cache->last_used; 3277 old_last_remap_bytes = cache->last_remap_bytes; 3278 old_last_identity_remap_count = cache->last_identity_remap_count; 3279 used = cache->used; 3280 remap_bytes = cache->remap_bytes; 3281 identity_remap_count = cache->identity_remap_count; 3282 /* No change in values, can safely skip it. */ 3283 if (cache->last_used == used && 3284 cache->last_remap_bytes == remap_bytes && 3285 cache->last_identity_remap_count == identity_remap_count && 3286 cache->last_flags == cache->flags) { 3287 spin_unlock(&cache->lock); 3288 return 0; 3289 } 3290 cache->last_used = used; 3291 cache->last_remap_bytes = remap_bytes; 3292 cache->last_identity_remap_count = identity_remap_count; 3293 cache->last_flags = cache->flags; 3294 spin_unlock(&cache->lock); 3295 3296 key.objectid = cache->start; 3297 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY; 3298 key.offset = cache->length; 3299 3300 ret = btrfs_search_slot(trans, root, &key, path, 0, 1); 3301 if (ret) { 3302 if (ret > 0) 3303 ret = -ENOENT; 3304 goto fail; 3305 } 3306 3307 leaf = path->nodes[0]; 3308 bi = btrfs_item_ptr_offset(leaf, path->slots[0]); 3309 btrfs_set_stack_block_group_v2_used(&bgi, used); 3310 btrfs_set_stack_block_group_v2_chunk_objectid(&bgi, cache->global_root_id); 3311 btrfs_set_stack_block_group_v2_flags(&bgi, cache->flags); 3312 3313 if (btrfs_fs_incompat(fs_info, REMAP_TREE)) { 3314 btrfs_set_stack_block_group_v2_remap_bytes(&bgi, cache->remap_bytes); 3315 btrfs_set_stack_block_group_v2_identity_remap_count(&bgi, 3316 cache->identity_remap_count); 3317 write_extent_buffer(leaf, &bgi, bi, 3318 sizeof(struct btrfs_block_group_item_v2)); 3319 } else { 3320 write_extent_buffer(leaf, &bgi, bi, 3321 sizeof(struct btrfs_block_group_item)); 3322 } 3323 3324 fail: 3325 btrfs_release_path(path); 3326 /* 3327 * We didn't update the block group item, need to revert last_used 3328 * unless the block group item didn't exist yet - this is to prevent a 3329 * race with a concurrent insertion of the block group item, with 3330 * insert_block_group_item(), that happened just after we attempted to 3331 * update. In that case we would reset last_used to 0 just after the 3332 * insertion set it to a value greater than 0 - if the block group later 3333 * becomes with 0 used bytes, we would incorrectly skip its update. 3334 */ 3335 if (ret < 0 && ret != -ENOENT) { 3336 spin_lock(&cache->lock); 3337 cache->last_used = old_last_used; 3338 cache->last_remap_bytes = old_last_remap_bytes; 3339 cache->last_identity_remap_count = old_last_identity_remap_count; 3340 spin_unlock(&cache->lock); 3341 } 3342 return ret; 3343 3344 } 3345 3346 static void cache_save_setup(struct btrfs_block_group *block_group, 3347 struct btrfs_trans_handle *trans, 3348 struct btrfs_path *path) 3349 { 3350 struct btrfs_fs_info *fs_info = block_group->fs_info; 3351 struct inode *inode = NULL; 3352 struct extent_changeset *data_reserved = NULL; 3353 u64 alloc_hint = 0; 3354 int dcs = BTRFS_DC_ERROR; 3355 u64 cache_size = 0; 3356 int retries = 0; 3357 int ret = 0; 3358 3359 if (!btrfs_test_opt(fs_info, SPACE_CACHE)) 3360 return; 3361 3362 /* 3363 * If this block group is smaller than 100 megs don't bother caching the 3364 * block group. 3365 */ 3366 if (block_group->length < (100 * SZ_1M)) { 3367 spin_lock(&block_group->lock); 3368 block_group->disk_cache_state = BTRFS_DC_WRITTEN; 3369 spin_unlock(&block_group->lock); 3370 return; 3371 } 3372 3373 if (TRANS_ABORTED(trans)) 3374 return; 3375 again: 3376 inode = lookup_free_space_inode(block_group, path); 3377 if (IS_ERR(inode) && PTR_ERR(inode) != -ENOENT) { 3378 ret = PTR_ERR(inode); 3379 btrfs_release_path(path); 3380 goto out; 3381 } 3382 3383 if (IS_ERR(inode)) { 3384 if (retries) { 3385 ret = PTR_ERR(inode); 3386 btrfs_err(fs_info, 3387 "failed to lookup free space inode after creation for block group %llu: %d", 3388 block_group->start, ret); 3389 goto out_free; 3390 } 3391 retries++; 3392 3393 if (block_group->ro) 3394 goto out_free; 3395 3396 ret = create_free_space_inode(trans, block_group, path); 3397 if (ret) 3398 goto out_free; 3399 goto again; 3400 } 3401 3402 /* 3403 * We want to set the generation to 0, that way if anything goes wrong 3404 * from here on out we know not to trust this cache when we load up next 3405 * time. 3406 */ 3407 BTRFS_I(inode)->generation = 0; 3408 ret = btrfs_update_inode(trans, BTRFS_I(inode)); 3409 if (unlikely(ret)) { 3410 /* 3411 * So theoretically we could recover from this, simply set the 3412 * super cache generation to 0 so we know to invalidate the 3413 * cache, but then we'd have to keep track of the block groups 3414 * that fail this way so we know we _have_ to reset this cache 3415 * before the next commit or risk reading stale cache. So to 3416 * limit our exposure to horrible edge cases lets just abort the 3417 * transaction, this only happens in really bad situations 3418 * anyway. 3419 */ 3420 btrfs_abort_transaction(trans, ret); 3421 goto out_put; 3422 } 3423 3424 /* We've already setup this transaction, go ahead and exit */ 3425 if (block_group->cache_generation == trans->transid && 3426 i_size_read(inode)) { 3427 dcs = BTRFS_DC_SETUP; 3428 goto out_put; 3429 } 3430 3431 if (i_size_read(inode) > 0) { 3432 ret = btrfs_check_trunc_cache_free_space(fs_info, 3433 &fs_info->global_block_rsv); 3434 if (ret) 3435 goto out_put; 3436 3437 ret = btrfs_truncate_free_space_cache(trans, NULL, inode); 3438 if (ret) 3439 goto out_put; 3440 } 3441 3442 spin_lock(&block_group->lock); 3443 if (block_group->cached != BTRFS_CACHE_FINISHED || 3444 !btrfs_test_opt(fs_info, SPACE_CACHE)) { 3445 /* 3446 * don't bother trying to write stuff out _if_ 3447 * a) we're not cached, 3448 * b) we're with nospace_cache mount option, 3449 * c) we're with v2 space_cache (FREE_SPACE_TREE). 3450 */ 3451 dcs = BTRFS_DC_WRITTEN; 3452 spin_unlock(&block_group->lock); 3453 goto out_put; 3454 } 3455 spin_unlock(&block_group->lock); 3456 3457 /* 3458 * We hit an ENOSPC when setting up the cache in this transaction, just 3459 * skip doing the setup, we've already cleared the cache so we're safe. 3460 */ 3461 if (test_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags)) 3462 goto out_put; 3463 3464 /* 3465 * Try to preallocate enough space based on how big the block group is. 3466 * Keep in mind this has to include any pinned space which could end up 3467 * taking up quite a bit since it's not folded into the other space 3468 * cache. 3469 */ 3470 cache_size = div_u64(block_group->length, SZ_256M); 3471 if (!cache_size) 3472 cache_size = 1; 3473 3474 cache_size *= 16; 3475 cache_size *= fs_info->sectorsize; 3476 3477 ret = btrfs_check_data_free_space(BTRFS_I(inode), &data_reserved, 0, 3478 cache_size, false); 3479 if (ret) 3480 goto out_put; 3481 3482 ret = btrfs_prealloc_file_range_trans(inode, trans, 0, 0, cache_size, 3483 cache_size, cache_size, 3484 &alloc_hint); 3485 /* 3486 * Our cache requires contiguous chunks so that we don't modify a bunch 3487 * of metadata or split extents when writing the cache out, which means 3488 * we can enospc if we are heavily fragmented in addition to just normal 3489 * out of space conditions. So if we hit this just skip setting up any 3490 * other block groups for this transaction, maybe we'll unpin enough 3491 * space the next time around. 3492 */ 3493 if (!ret) 3494 dcs = BTRFS_DC_SETUP; 3495 else if (ret == -ENOSPC) 3496 set_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags); 3497 3498 out_put: 3499 iput(inode); 3500 out_free: 3501 btrfs_release_path(path); 3502 out: 3503 spin_lock(&block_group->lock); 3504 if (!ret && dcs == BTRFS_DC_SETUP) 3505 block_group->cache_generation = trans->transid; 3506 block_group->disk_cache_state = dcs; 3507 spin_unlock(&block_group->lock); 3508 3509 extent_changeset_free(data_reserved); 3510 } 3511 3512 int btrfs_setup_space_cache(struct btrfs_trans_handle *trans) 3513 { 3514 struct btrfs_fs_info *fs_info = trans->fs_info; 3515 struct btrfs_block_group *cache, *tmp; 3516 struct btrfs_transaction *cur_trans = trans->transaction; 3517 BTRFS_PATH_AUTO_FREE(path); 3518 3519 if (list_empty(&cur_trans->dirty_bgs) || 3520 !btrfs_test_opt(fs_info, SPACE_CACHE)) 3521 return 0; 3522 3523 path = btrfs_alloc_path(); 3524 if (!path) 3525 return -ENOMEM; 3526 3527 /* Could add new block groups, use _safe just in case */ 3528 list_for_each_entry_safe(cache, tmp, &cur_trans->dirty_bgs, 3529 dirty_list) { 3530 if (cache->disk_cache_state == BTRFS_DC_CLEAR) 3531 cache_save_setup(cache, trans, path); 3532 } 3533 3534 return 0; 3535 } 3536 3537 /* 3538 * Transaction commit does final block group cache writeback during a critical 3539 * section where nothing is allowed to change the FS. This is required in 3540 * order for the cache to actually match the block group, but can introduce a 3541 * lot of latency into the commit. 3542 * 3543 * So, btrfs_start_dirty_block_groups is here to kick off block group cache IO. 3544 * There's a chance we'll have to redo some of it if the block group changes 3545 * again during the commit, but it greatly reduces the commit latency by 3546 * getting rid of the easy block groups while we're still allowing others to 3547 * join the commit. 3548 */ 3549 int btrfs_start_dirty_block_groups(struct btrfs_trans_handle *trans) 3550 { 3551 struct btrfs_fs_info *fs_info = trans->fs_info; 3552 struct btrfs_block_group *cache; 3553 struct btrfs_transaction *cur_trans = trans->transaction; 3554 int ret = 0; 3555 int should_put; 3556 BTRFS_PATH_AUTO_FREE(path); 3557 LIST_HEAD(dirty); 3558 struct list_head *io = &cur_trans->io_bgs; 3559 int loops = 0; 3560 3561 spin_lock(&cur_trans->dirty_bgs_lock); 3562 if (list_empty(&cur_trans->dirty_bgs)) { 3563 spin_unlock(&cur_trans->dirty_bgs_lock); 3564 return 0; 3565 } 3566 list_splice_init(&cur_trans->dirty_bgs, &dirty); 3567 spin_unlock(&cur_trans->dirty_bgs_lock); 3568 3569 again: 3570 /* Make sure all the block groups on our dirty list actually exist */ 3571 btrfs_create_pending_block_groups(trans); 3572 3573 if (!path) { 3574 path = btrfs_alloc_path(); 3575 if (!path) { 3576 ret = -ENOMEM; 3577 goto out; 3578 } 3579 } 3580 3581 /* 3582 * cache_write_mutex is here only to save us from balance or automatic 3583 * removal of empty block groups deleting this block group while we are 3584 * writing out the cache 3585 */ 3586 mutex_lock(&trans->transaction->cache_write_mutex); 3587 while (!list_empty(&dirty)) { 3588 bool drop_reserve = true; 3589 3590 cache = list_first_entry(&dirty, struct btrfs_block_group, 3591 dirty_list); 3592 /* 3593 * This can happen if something re-dirties a block group that 3594 * is already under IO. Just wait for it to finish and then do 3595 * it all again 3596 */ 3597 if (!list_empty(&cache->io_list)) { 3598 list_del_init(&cache->io_list); 3599 btrfs_wait_cache_io(trans, cache, path); 3600 btrfs_put_block_group(cache); 3601 } 3602 3603 3604 /* 3605 * btrfs_wait_cache_io uses the cache->dirty_list to decide if 3606 * it should update the cache_state. Don't delete until after 3607 * we wait. 3608 * 3609 * Since we're not running in the commit critical section 3610 * we need the dirty_bgs_lock to protect from update_block_group 3611 */ 3612 spin_lock(&cur_trans->dirty_bgs_lock); 3613 list_del_init(&cache->dirty_list); 3614 spin_unlock(&cur_trans->dirty_bgs_lock); 3615 3616 should_put = 1; 3617 3618 cache_save_setup(cache, trans, path); 3619 3620 if (cache->disk_cache_state == BTRFS_DC_SETUP) { 3621 cache->io_ctl.inode = NULL; 3622 ret = btrfs_write_out_cache(trans, cache, path); 3623 if (ret == 0 && cache->io_ctl.inode) { 3624 should_put = 0; 3625 3626 /* 3627 * The cache_write_mutex is protecting the 3628 * io_list, also refer to the definition of 3629 * btrfs_transaction::io_bgs for more details 3630 */ 3631 list_add_tail(&cache->io_list, io); 3632 } else { 3633 /* 3634 * If we failed to write the cache, the 3635 * generation will be bad and life goes on 3636 */ 3637 ret = 0; 3638 } 3639 } 3640 if (!ret) { 3641 ret = update_block_group_item(trans, path, cache); 3642 /* 3643 * Our block group might still be attached to the list 3644 * of new block groups in the transaction handle of some 3645 * other task (struct btrfs_trans_handle->new_bgs). This 3646 * means its block group item isn't yet in the extent 3647 * tree. If this happens ignore the error, as we will 3648 * try again later in the critical section of the 3649 * transaction commit. 3650 */ 3651 if (ret == -ENOENT) { 3652 ret = 0; 3653 spin_lock(&cur_trans->dirty_bgs_lock); 3654 if (list_empty(&cache->dirty_list)) { 3655 list_add_tail(&cache->dirty_list, 3656 &cur_trans->dirty_bgs); 3657 btrfs_get_block_group(cache); 3658 drop_reserve = false; 3659 } 3660 spin_unlock(&cur_trans->dirty_bgs_lock); 3661 } else if (ret) { 3662 btrfs_abort_transaction(trans, ret); 3663 } 3664 } 3665 3666 /* If it's not on the io list, we need to put the block group */ 3667 if (should_put) 3668 btrfs_put_block_group(cache); 3669 if (drop_reserve) 3670 btrfs_dec_delayed_refs_rsv_bg_updates(fs_info); 3671 /* 3672 * Avoid blocking other tasks for too long. It might even save 3673 * us from writing caches for block groups that are going to be 3674 * removed. 3675 */ 3676 mutex_unlock(&trans->transaction->cache_write_mutex); 3677 if (ret) 3678 goto out; 3679 mutex_lock(&trans->transaction->cache_write_mutex); 3680 } 3681 mutex_unlock(&trans->transaction->cache_write_mutex); 3682 3683 /* 3684 * Go through delayed refs for all the stuff we've just kicked off 3685 * and then loop back (just once) 3686 */ 3687 if (!ret) 3688 ret = btrfs_run_delayed_refs(trans, 0); 3689 if (!ret && loops == 0) { 3690 loops++; 3691 spin_lock(&cur_trans->dirty_bgs_lock); 3692 list_splice_init(&cur_trans->dirty_bgs, &dirty); 3693 /* 3694 * dirty_bgs_lock protects us from concurrent block group 3695 * deletes too (not just cache_write_mutex). 3696 */ 3697 if (!list_empty(&dirty)) { 3698 spin_unlock(&cur_trans->dirty_bgs_lock); 3699 goto again; 3700 } 3701 spin_unlock(&cur_trans->dirty_bgs_lock); 3702 } 3703 out: 3704 if (ret < 0) { 3705 spin_lock(&cur_trans->dirty_bgs_lock); 3706 list_splice_init(&dirty, &cur_trans->dirty_bgs); 3707 spin_unlock(&cur_trans->dirty_bgs_lock); 3708 btrfs_cleanup_dirty_bgs(cur_trans, fs_info); 3709 } 3710 3711 return ret; 3712 } 3713 3714 int btrfs_write_dirty_block_groups(struct btrfs_trans_handle *trans) 3715 { 3716 struct btrfs_fs_info *fs_info = trans->fs_info; 3717 struct btrfs_block_group *cache; 3718 struct btrfs_transaction *cur_trans = trans->transaction; 3719 int ret = 0; 3720 int should_put; 3721 BTRFS_PATH_AUTO_FREE(path); 3722 struct list_head *io = &cur_trans->io_bgs; 3723 3724 path = btrfs_alloc_path(); 3725 if (!path) 3726 return -ENOMEM; 3727 3728 /* 3729 * Even though we are in the critical section of the transaction commit, 3730 * we can still have concurrent tasks adding elements to this 3731 * transaction's list of dirty block groups. These tasks correspond to 3732 * endio free space workers started when writeback finishes for a 3733 * space cache, which run inode.c:btrfs_finish_ordered_io(), and can 3734 * allocate new block groups as a result of COWing nodes of the root 3735 * tree when updating the free space inode. The writeback for the space 3736 * caches is triggered by an earlier call to 3737 * btrfs_start_dirty_block_groups() and iterations of the following 3738 * loop. 3739 * Also we want to do the cache_save_setup first and then run the 3740 * delayed refs to make sure we have the best chance at doing this all 3741 * in one shot. 3742 */ 3743 spin_lock(&cur_trans->dirty_bgs_lock); 3744 while (!list_empty(&cur_trans->dirty_bgs)) { 3745 cache = list_first_entry(&cur_trans->dirty_bgs, 3746 struct btrfs_block_group, 3747 dirty_list); 3748 3749 /* 3750 * This can happen if cache_save_setup re-dirties a block group 3751 * that is already under IO. Just wait for it to finish and 3752 * then do it all again 3753 */ 3754 if (!list_empty(&cache->io_list)) { 3755 spin_unlock(&cur_trans->dirty_bgs_lock); 3756 list_del_init(&cache->io_list); 3757 btrfs_wait_cache_io(trans, cache, path); 3758 btrfs_put_block_group(cache); 3759 spin_lock(&cur_trans->dirty_bgs_lock); 3760 } 3761 3762 /* 3763 * Don't remove from the dirty list until after we've waited on 3764 * any pending IO 3765 */ 3766 list_del_init(&cache->dirty_list); 3767 spin_unlock(&cur_trans->dirty_bgs_lock); 3768 should_put = 1; 3769 3770 cache_save_setup(cache, trans, path); 3771 3772 if (!ret) 3773 ret = btrfs_run_delayed_refs(trans, U64_MAX); 3774 3775 if (!ret && cache->disk_cache_state == BTRFS_DC_SETUP) { 3776 cache->io_ctl.inode = NULL; 3777 ret = btrfs_write_out_cache(trans, cache, path); 3778 if (ret == 0 && cache->io_ctl.inode) { 3779 should_put = 0; 3780 list_add_tail(&cache->io_list, io); 3781 } else { 3782 /* 3783 * If we failed to write the cache, the 3784 * generation will be bad and life goes on 3785 */ 3786 ret = 0; 3787 } 3788 } 3789 if (!ret) { 3790 ret = update_block_group_item(trans, path, cache); 3791 /* 3792 * One of the free space endio workers might have 3793 * created a new block group while updating a free space 3794 * cache's inode (at inode.c:btrfs_finish_ordered_io()) 3795 * and hasn't released its transaction handle yet, in 3796 * which case the new block group is still attached to 3797 * its transaction handle and its creation has not 3798 * finished yet (no block group item in the extent tree 3799 * yet, etc). If this is the case, wait for all free 3800 * space endio workers to finish and retry. This is a 3801 * very rare case so no need for a more efficient and 3802 * complex approach. 3803 */ 3804 if (ret == -ENOENT) { 3805 wait_event(cur_trans->writer_wait, 3806 atomic_read(&cur_trans->num_writers) == 1); 3807 ret = update_block_group_item(trans, path, cache); 3808 if (ret) 3809 btrfs_abort_transaction(trans, ret); 3810 } else if (ret) { 3811 btrfs_abort_transaction(trans, ret); 3812 } 3813 } 3814 3815 /* If its not on the io list, we need to put the block group */ 3816 if (should_put) 3817 btrfs_put_block_group(cache); 3818 btrfs_dec_delayed_refs_rsv_bg_updates(fs_info); 3819 spin_lock(&cur_trans->dirty_bgs_lock); 3820 } 3821 spin_unlock(&cur_trans->dirty_bgs_lock); 3822 3823 /* 3824 * Refer to the definition of io_bgs member for details why it's safe 3825 * to use it without any locking 3826 */ 3827 while (!list_empty(io)) { 3828 cache = list_first_entry(io, struct btrfs_block_group, 3829 io_list); 3830 list_del_init(&cache->io_list); 3831 btrfs_wait_cache_io(trans, cache, path); 3832 btrfs_put_block_group(cache); 3833 } 3834 3835 return ret; 3836 } 3837 3838 static void btrfs_maybe_reset_size_class(struct btrfs_block_group *bg) 3839 { 3840 lockdep_assert_held(&bg->lock); 3841 if (btrfs_block_group_should_use_size_class(bg) && 3842 bg->used == 0 && bg->reserved == 0) 3843 bg->size_class = BTRFS_BG_SZ_NONE; 3844 } 3845 3846 int btrfs_update_block_group(struct btrfs_trans_handle *trans, 3847 u64 bytenr, u64 num_bytes, bool alloc) 3848 { 3849 struct btrfs_fs_info *info = trans->fs_info; 3850 struct btrfs_space_info *space_info; 3851 struct btrfs_block_group *cache; 3852 u64 old_val; 3853 bool reclaim = false; 3854 bool bg_already_dirty = true; 3855 int factor; 3856 3857 /* Block accounting for super block */ 3858 spin_lock(&info->delalloc_root_lock); 3859 old_val = btrfs_super_bytes_used(info->super_copy); 3860 if (alloc) 3861 old_val += num_bytes; 3862 else 3863 old_val -= num_bytes; 3864 btrfs_set_super_bytes_used(info->super_copy, old_val); 3865 spin_unlock(&info->delalloc_root_lock); 3866 3867 cache = btrfs_lookup_block_group(info, bytenr); 3868 if (!cache) 3869 return -ENOENT; 3870 3871 /* An extent can not span multiple block groups. */ 3872 ASSERT(bytenr + num_bytes <= btrfs_block_group_end(cache)); 3873 3874 space_info = cache->space_info; 3875 factor = btrfs_bg_type_to_factor(cache->flags); 3876 3877 /* 3878 * If this block group has free space cache written out, we need to make 3879 * sure to load it if we are removing space. This is because we need 3880 * the unpinning stage to actually add the space back to the block group, 3881 * otherwise we will leak space. 3882 */ 3883 if (!alloc && !btrfs_block_group_done(cache)) 3884 btrfs_cache_block_group(cache, true); 3885 3886 spin_lock(&space_info->lock); 3887 spin_lock(&cache->lock); 3888 3889 if (btrfs_test_opt(info, SPACE_CACHE) && 3890 cache->disk_cache_state < BTRFS_DC_CLEAR) 3891 cache->disk_cache_state = BTRFS_DC_CLEAR; 3892 3893 old_val = cache->used; 3894 if (alloc) { 3895 old_val += num_bytes; 3896 cache->used = old_val; 3897 cache->reserved -= num_bytes; 3898 cache->reclaim_mark = 0; 3899 space_info->bytes_reserved -= num_bytes; 3900 space_info->bytes_used += num_bytes; 3901 space_info->disk_used += num_bytes * factor; 3902 if (READ_ONCE(space_info->periodic_reclaim)) 3903 btrfs_space_info_update_reclaimable(space_info, -num_bytes); 3904 spin_unlock(&cache->lock); 3905 spin_unlock(&space_info->lock); 3906 } else { 3907 old_val -= num_bytes; 3908 cache->used = old_val; 3909 cache->pinned += num_bytes; 3910 btrfs_maybe_reset_size_class(cache); 3911 btrfs_space_info_update_bytes_pinned(space_info, num_bytes); 3912 space_info->bytes_used -= num_bytes; 3913 space_info->disk_used -= num_bytes * factor; 3914 if (READ_ONCE(space_info->periodic_reclaim)) 3915 btrfs_space_info_update_reclaimable(space_info, num_bytes); 3916 else 3917 reclaim = should_reclaim_block_group(cache, num_bytes); 3918 3919 spin_unlock(&cache->lock); 3920 spin_unlock(&space_info->lock); 3921 3922 btrfs_set_extent_bit(&trans->transaction->pinned_extents, bytenr, 3923 bytenr + num_bytes - 1, EXTENT_DIRTY, NULL); 3924 } 3925 3926 spin_lock(&trans->transaction->dirty_bgs_lock); 3927 if (list_empty(&cache->dirty_list)) { 3928 list_add_tail(&cache->dirty_list, &trans->transaction->dirty_bgs); 3929 bg_already_dirty = false; 3930 btrfs_get_block_group(cache); 3931 } 3932 spin_unlock(&trans->transaction->dirty_bgs_lock); 3933 3934 /* 3935 * No longer have used bytes in this block group, queue it for deletion. 3936 * We do this after adding the block group to the dirty list to avoid 3937 * races between cleaner kthread and space cache writeout. 3938 */ 3939 if (!alloc && old_val == 0) { 3940 if (!btrfs_test_opt(info, DISCARD_ASYNC)) 3941 btrfs_mark_bg_unused(cache); 3942 } else if (!alloc && reclaim) { 3943 btrfs_mark_bg_to_reclaim(cache); 3944 } 3945 3946 btrfs_put_block_group(cache); 3947 3948 /* Modified block groups are accounted for in the delayed_refs_rsv. */ 3949 if (!bg_already_dirty) 3950 btrfs_inc_delayed_refs_rsv_bg_updates(info); 3951 3952 return 0; 3953 } 3954 3955 /* 3956 * Update the block_group and space info counters. 3957 * 3958 * @cache: The cache we are manipulating 3959 * @ram_bytes: The number of bytes of file content, and will be same to 3960 * @num_bytes except for the compress path. 3961 * @num_bytes: The number of bytes in question 3962 * @delalloc: The blocks are allocated for the delalloc write 3963 * 3964 * This is called by the allocator when it reserves space. If this is a 3965 * reservation and the block group has become read only we cannot make the 3966 * reservation and return -EAGAIN, otherwise this function always succeeds. 3967 */ 3968 int btrfs_add_reserved_bytes(struct btrfs_block_group *cache, 3969 u64 ram_bytes, u64 num_bytes, bool delalloc, 3970 bool force_wrong_size_class) 3971 { 3972 struct btrfs_space_info *space_info = cache->space_info; 3973 enum btrfs_block_group_size_class size_class; 3974 int ret = 0; 3975 3976 spin_lock(&space_info->lock); 3977 spin_lock(&cache->lock); 3978 if (cache->ro) { 3979 ret = -EAGAIN; 3980 goto out_error; 3981 } 3982 3983 if (btrfs_block_group_should_use_size_class(cache)) { 3984 size_class = btrfs_calc_block_group_size_class(num_bytes); 3985 ret = btrfs_use_block_group_size_class(cache, size_class, force_wrong_size_class); 3986 if (ret) 3987 goto out_error; 3988 } 3989 3990 cache->reserved += num_bytes; 3991 if (delalloc) 3992 cache->delalloc_bytes += num_bytes; 3993 3994 trace_btrfs_space_reservation(cache->fs_info, "space_info", 3995 space_info->flags, num_bytes, 1); 3996 spin_unlock(&cache->lock); 3997 3998 space_info->bytes_reserved += num_bytes; 3999 btrfs_space_info_update_bytes_may_use(space_info, -ram_bytes); 4000 4001 /* 4002 * Compression can use less space than we reserved, so wake tickets if 4003 * that happens. 4004 */ 4005 if (num_bytes < ram_bytes) 4006 btrfs_try_granting_tickets(space_info); 4007 spin_unlock(&space_info->lock); 4008 4009 return 0; 4010 4011 out_error: 4012 spin_unlock(&cache->lock); 4013 spin_unlock(&space_info->lock); 4014 return ret; 4015 } 4016 4017 /* 4018 * Update the block_group and space info counters. 4019 * 4020 * @cache: The cache we are manipulating. 4021 * @num_bytes: The number of bytes in question. 4022 * @is_delalloc: Whether the blocks are allocated for a delalloc write. 4023 * 4024 * This is called by somebody who is freeing space that was never actually used 4025 * on disk. For example if you reserve some space for a new leaf in transaction 4026 * A and before transaction A commits you free that leaf, you call this with 4027 * reserve set to 0 in order to clear the reservation. 4028 */ 4029 void btrfs_free_reserved_bytes(struct btrfs_block_group *cache, u64 num_bytes, 4030 bool is_delalloc) 4031 { 4032 struct btrfs_space_info *space_info = cache->space_info; 4033 bool bg_ro; 4034 4035 spin_lock(&space_info->lock); 4036 spin_lock(&cache->lock); 4037 bg_ro = cache->ro; 4038 cache->reserved -= num_bytes; 4039 btrfs_maybe_reset_size_class(cache); 4040 if (is_delalloc) 4041 cache->delalloc_bytes -= num_bytes; 4042 spin_unlock(&cache->lock); 4043 4044 if (bg_ro) 4045 space_info->bytes_readonly += num_bytes; 4046 else if (btrfs_is_zoned(cache->fs_info)) 4047 space_info->bytes_zone_unusable += num_bytes; 4048 4049 space_info->bytes_reserved -= num_bytes; 4050 space_info->max_extent_size = 0; 4051 4052 btrfs_try_granting_tickets(space_info); 4053 spin_unlock(&space_info->lock); 4054 } 4055 4056 static void force_metadata_allocation(struct btrfs_fs_info *info) 4057 { 4058 struct list_head *head = &info->space_info; 4059 struct btrfs_space_info *found; 4060 4061 list_for_each_entry(found, head, list) { 4062 if (found->flags & BTRFS_BLOCK_GROUP_METADATA) 4063 found->force_alloc = CHUNK_ALLOC_FORCE; 4064 } 4065 } 4066 4067 static bool should_alloc_chunk(const struct btrfs_fs_info *fs_info, 4068 const struct btrfs_space_info *sinfo, int force) 4069 { 4070 u64 bytes_used = btrfs_space_info_used(sinfo, false); 4071 u64 thresh; 4072 4073 if (force == CHUNK_ALLOC_FORCE) 4074 return true; 4075 4076 /* 4077 * in limited mode, we want to have some free space up to 4078 * about 1% of the FS size. 4079 */ 4080 if (force == CHUNK_ALLOC_LIMITED) { 4081 thresh = btrfs_super_total_bytes(fs_info->super_copy); 4082 thresh = max_t(u64, SZ_64M, mult_perc(thresh, 1)); 4083 4084 if (sinfo->total_bytes - bytes_used < thresh) 4085 return true; 4086 } 4087 4088 if (bytes_used + SZ_2M < mult_perc(sinfo->total_bytes, 80)) 4089 return false; 4090 return true; 4091 } 4092 4093 int btrfs_force_chunk_alloc(struct btrfs_trans_handle *trans, u64 type) 4094 { 4095 u64 alloc_flags = btrfs_get_alloc_profile(trans->fs_info, type); 4096 struct btrfs_space_info *space_info; 4097 4098 space_info = btrfs_find_space_info(trans->fs_info, type); 4099 if (!space_info) { 4100 DEBUG_WARN(); 4101 return -EINVAL; 4102 } 4103 4104 return btrfs_chunk_alloc(trans, space_info, alloc_flags, CHUNK_ALLOC_FORCE); 4105 } 4106 4107 static struct btrfs_block_group *do_chunk_alloc(struct btrfs_trans_handle *trans, 4108 struct btrfs_space_info *space_info, 4109 u64 flags) 4110 { 4111 struct btrfs_block_group *bg; 4112 int ret; 4113 4114 /* 4115 * Check if we have enough space in the system space info because we 4116 * will need to update device items in the chunk btree and insert a new 4117 * chunk item in the chunk btree as well. This will allocate a new 4118 * system block group if needed. 4119 */ 4120 check_system_chunk(trans, flags); 4121 4122 bg = btrfs_create_chunk(trans, space_info, flags); 4123 if (IS_ERR(bg)) { 4124 ret = PTR_ERR(bg); 4125 goto out; 4126 } 4127 4128 ret = btrfs_chunk_alloc_add_chunk_item(trans, bg); 4129 /* 4130 * Normally we are not expected to fail with -ENOSPC here, since we have 4131 * previously reserved space in the system space_info and allocated one 4132 * new system chunk if necessary. However there are three exceptions: 4133 * 4134 * 1) We may have enough free space in the system space_info but all the 4135 * existing system block groups have a profile which can not be used 4136 * for extent allocation. 4137 * 4138 * This happens when mounting in degraded mode. For example we have a 4139 * RAID1 filesystem with 2 devices, lose one device and mount the fs 4140 * using the other device in degraded mode. If we then allocate a chunk, 4141 * we may have enough free space in the existing system space_info, but 4142 * none of the block groups can be used for extent allocation since they 4143 * have a RAID1 profile, and because we are in degraded mode with a 4144 * single device, we are forced to allocate a new system chunk with a 4145 * SINGLE profile. Making check_system_chunk() iterate over all system 4146 * block groups and check if they have a usable profile and enough space 4147 * can be slow on very large filesystems, so we tolerate the -ENOSPC and 4148 * try again after forcing allocation of a new system chunk. Like this 4149 * we avoid paying the cost of that search in normal circumstances, when 4150 * we were not mounted in degraded mode; 4151 * 4152 * 2) We had enough free space info the system space_info, and one suitable 4153 * block group to allocate from when we called check_system_chunk() 4154 * above. However right after we called it, the only system block group 4155 * with enough free space got turned into RO mode by a running scrub, 4156 * and in this case we have to allocate a new one and retry. We only 4157 * need do this allocate and retry once, since we have a transaction 4158 * handle and scrub uses the commit root to search for block groups; 4159 * 4160 * 3) We had one system block group with enough free space when we called 4161 * check_system_chunk(), but after that, right before we tried to 4162 * allocate the last extent buffer we needed, a discard operation came 4163 * in and it temporarily removed the last free space entry from the 4164 * block group (discard removes a free space entry, discards it, and 4165 * then adds back the entry to the block group cache). 4166 */ 4167 if (ret == -ENOSPC) { 4168 const u64 sys_flags = btrfs_system_alloc_profile(trans->fs_info); 4169 struct btrfs_block_group *sys_bg; 4170 struct btrfs_space_info *sys_space_info; 4171 4172 sys_space_info = btrfs_find_space_info(trans->fs_info, sys_flags); 4173 if (unlikely(!sys_space_info)) { 4174 ret = -EINVAL; 4175 btrfs_abort_transaction(trans, ret); 4176 goto out; 4177 } 4178 4179 sys_bg = btrfs_create_chunk(trans, sys_space_info, sys_flags); 4180 if (IS_ERR(sys_bg)) { 4181 ret = PTR_ERR(sys_bg); 4182 btrfs_abort_transaction(trans, ret); 4183 goto out; 4184 } 4185 4186 ret = btrfs_chunk_alloc_add_chunk_item(trans, sys_bg); 4187 if (unlikely(ret)) { 4188 btrfs_abort_transaction(trans, ret); 4189 goto out; 4190 } 4191 4192 ret = btrfs_chunk_alloc_add_chunk_item(trans, bg); 4193 if (unlikely(ret)) { 4194 btrfs_abort_transaction(trans, ret); 4195 goto out; 4196 } 4197 } else if (unlikely(ret)) { 4198 btrfs_abort_transaction(trans, ret); 4199 goto out; 4200 } 4201 out: 4202 btrfs_trans_release_chunk_metadata(trans); 4203 4204 if (ret) 4205 return ERR_PTR(ret); 4206 4207 btrfs_get_block_group(bg); 4208 return bg; 4209 } 4210 4211 /* 4212 * Chunk allocation is done in 2 phases: 4213 * 4214 * 1) Phase 1 - through btrfs_chunk_alloc() we allocate device extents for 4215 * the chunk, the chunk mapping, create its block group and add the items 4216 * that belong in the chunk btree to it - more specifically, we need to 4217 * update device items in the chunk btree and add a new chunk item to it. 4218 * 4219 * 2) Phase 2 - through btrfs_create_pending_block_groups(), we add the block 4220 * group item to the extent btree and the device extent items to the devices 4221 * btree. 4222 * 4223 * This is done to prevent deadlocks. For example when COWing a node from the 4224 * extent btree we are holding a write lock on the node's parent and if we 4225 * trigger chunk allocation and attempted to insert the new block group item 4226 * in the extent btree right way, we could deadlock because the path for the 4227 * insertion can include that parent node. At first glance it seems impossible 4228 * to trigger chunk allocation after starting a transaction since tasks should 4229 * reserve enough transaction units (metadata space), however while that is true 4230 * most of the time, chunk allocation may still be triggered for several reasons: 4231 * 4232 * 1) When reserving metadata, we check if there is enough free space in the 4233 * metadata space_info and therefore don't trigger allocation of a new chunk. 4234 * However later when the task actually tries to COW an extent buffer from 4235 * the extent btree or from the device btree for example, it is forced to 4236 * allocate a new block group (chunk) because the only one that had enough 4237 * free space was just turned to RO mode by a running scrub for example (or 4238 * device replace, block group reclaim thread, etc), so we can not use it 4239 * for allocating an extent and end up being forced to allocate a new one; 4240 * 4241 * 2) Because we only check that the metadata space_info has enough free bytes, 4242 * we end up not allocating a new metadata chunk in that case. However if 4243 * the filesystem was mounted in degraded mode, none of the existing block 4244 * groups might be suitable for extent allocation due to their incompatible 4245 * profile (for e.g. mounting a 2 devices filesystem, where all block groups 4246 * use a RAID1 profile, in degraded mode using a single device). In this case 4247 * when the task attempts to COW some extent buffer of the extent btree for 4248 * example, it will trigger allocation of a new metadata block group with a 4249 * suitable profile (SINGLE profile in the example of the degraded mount of 4250 * the RAID1 filesystem); 4251 * 4252 * 3) The task has reserved enough transaction units / metadata space, but when 4253 * it attempts to COW an extent buffer from the extent or device btree for 4254 * example, it does not find any free extent in any metadata block group, 4255 * therefore forced to try to allocate a new metadata block group. 4256 * This is because some other task allocated all available extents in the 4257 * meanwhile - this typically happens with tasks that don't reserve space 4258 * properly, either intentionally or as a bug. One example where this is 4259 * done intentionally is fsync, as it does not reserve any transaction units 4260 * and ends up allocating a variable number of metadata extents for log 4261 * tree extent buffers; 4262 * 4263 * 4) The task has reserved enough transaction units / metadata space, but right 4264 * before it tries to allocate the last extent buffer it needs, a discard 4265 * operation comes in and, temporarily, removes the last free space entry from 4266 * the only metadata block group that had free space (discard starts by 4267 * removing a free space entry from a block group, then does the discard 4268 * operation and, once it's done, it adds back the free space entry to the 4269 * block group). 4270 * 4271 * We also need this 2 phases setup when adding a device to a filesystem with 4272 * a seed device - we must create new metadata and system chunks without adding 4273 * any of the block group items to the chunk, extent and device btrees. If we 4274 * did not do it this way, we would get ENOSPC when attempting to update those 4275 * btrees, since all the chunks from the seed device are read-only. 4276 * 4277 * Phase 1 does the updates and insertions to the chunk btree because if we had 4278 * it done in phase 2 and have a thundering herd of tasks allocating chunks in 4279 * parallel, we risk having too many system chunks allocated by many tasks if 4280 * many tasks reach phase 1 without the previous ones completing phase 2. In the 4281 * extreme case this leads to exhaustion of the system chunk array in the 4282 * superblock. This is easier to trigger if using a btree node/leaf size of 64K 4283 * and with RAID filesystems (so we have more device items in the chunk btree). 4284 * This has happened before and commit eafa4fd0ad0607 ("btrfs: fix exhaustion of 4285 * the system chunk array due to concurrent allocations") provides more details. 4286 * 4287 * Allocation of system chunks does not happen through this function. A task that 4288 * needs to update the chunk btree (the only btree that uses system chunks), must 4289 * preallocate chunk space by calling either check_system_chunk() or 4290 * btrfs_reserve_chunk_metadata() - the former is used when allocating a data or 4291 * metadata chunk or when removing a chunk, while the later is used before doing 4292 * a modification to the chunk btree - use cases for the later are adding, 4293 * removing and resizing a device as well as relocation of a system chunk. 4294 * See the comment below for more details. 4295 * 4296 * The reservation of system space, done through check_system_chunk(), as well 4297 * as all the updates and insertions into the chunk btree must be done while 4298 * holding fs_info->chunk_mutex. This is important to guarantee that while COWing 4299 * an extent buffer from the chunks btree we never trigger allocation of a new 4300 * system chunk, which would result in a deadlock (trying to lock twice an 4301 * extent buffer of the chunk btree, first time before triggering the chunk 4302 * allocation and the second time during chunk allocation while attempting to 4303 * update the chunks btree). The system chunk array is also updated while holding 4304 * that mutex. The same logic applies to removing chunks - we must reserve system 4305 * space, update the chunk btree and the system chunk array in the superblock 4306 * while holding fs_info->chunk_mutex. 4307 * 4308 * This function, btrfs_chunk_alloc(), belongs to phase 1. 4309 * 4310 * @space_info: specify which space_info the new chunk should belong to. 4311 * 4312 * If @force is CHUNK_ALLOC_FORCE: 4313 * - return 1 if it successfully allocates a chunk, 4314 * - return errors including -ENOSPC otherwise. 4315 * If @force is NOT CHUNK_ALLOC_FORCE: 4316 * - return 0 if it doesn't need to allocate a new chunk, 4317 * - return 1 if it successfully allocates a chunk, 4318 * - return errors including -ENOSPC otherwise. 4319 */ 4320 int btrfs_chunk_alloc(struct btrfs_trans_handle *trans, 4321 struct btrfs_space_info *space_info, u64 flags, 4322 enum btrfs_chunk_alloc_enum force) 4323 { 4324 struct btrfs_fs_info *fs_info = trans->fs_info; 4325 struct btrfs_block_group *ret_bg; 4326 bool wait_for_alloc = false; 4327 bool should_alloc = false; 4328 bool from_extent_allocation = false; 4329 int ret = 0; 4330 4331 if (force == CHUNK_ALLOC_FORCE_FOR_EXTENT) { 4332 from_extent_allocation = true; 4333 force = CHUNK_ALLOC_FORCE; 4334 } 4335 4336 /* Don't re-enter if we're already allocating a chunk */ 4337 if (trans->allocating_chunk) 4338 return -ENOSPC; 4339 /* 4340 * Allocation of system chunks can not happen through this path, as we 4341 * could end up in a deadlock if we are allocating a data or metadata 4342 * chunk and there is another task modifying the chunk btree. 4343 * 4344 * This is because while we are holding the chunk mutex, we will attempt 4345 * to add the new chunk item to the chunk btree or update an existing 4346 * device item in the chunk btree, while the other task that is modifying 4347 * the chunk btree is attempting to COW an extent buffer while holding a 4348 * lock on it and on its parent - if the COW operation triggers a system 4349 * chunk allocation, then we can deadlock because we are holding the 4350 * chunk mutex and we may need to access that extent buffer or its parent 4351 * in order to add the chunk item or update a device item. 4352 * 4353 * Tasks that want to modify the chunk tree should reserve system space 4354 * before updating the chunk btree, by calling either 4355 * btrfs_reserve_chunk_metadata() or check_system_chunk(). 4356 * It's possible that after a task reserves the space, it still ends up 4357 * here - this happens in the cases described above at do_chunk_alloc(). 4358 * The task will have to either retry or fail. 4359 */ 4360 if (flags & BTRFS_BLOCK_GROUP_SYSTEM) 4361 return -ENOSPC; 4362 4363 do { 4364 spin_lock(&space_info->lock); 4365 if (force < space_info->force_alloc) 4366 force = space_info->force_alloc; 4367 should_alloc = should_alloc_chunk(fs_info, space_info, force); 4368 if (space_info->full) { 4369 /* No more free physical space */ 4370 spin_unlock(&space_info->lock); 4371 if (should_alloc) 4372 ret = -ENOSPC; 4373 else 4374 ret = 0; 4375 return ret; 4376 } else if (!should_alloc) { 4377 spin_unlock(&space_info->lock); 4378 return 0; 4379 } else if (space_info->chunk_alloc) { 4380 /* 4381 * Someone is already allocating, so we need to block 4382 * until this someone is finished and then loop to 4383 * recheck if we should continue with our allocation 4384 * attempt. 4385 */ 4386 spin_unlock(&space_info->lock); 4387 wait_for_alloc = true; 4388 force = CHUNK_ALLOC_NO_FORCE; 4389 mutex_lock(&fs_info->chunk_mutex); 4390 mutex_unlock(&fs_info->chunk_mutex); 4391 } else { 4392 /* Proceed with allocation */ 4393 space_info->chunk_alloc = true; 4394 spin_unlock(&space_info->lock); 4395 wait_for_alloc = false; 4396 } 4397 4398 cond_resched(); 4399 } while (wait_for_alloc); 4400 4401 mutex_lock(&fs_info->chunk_mutex); 4402 trans->allocating_chunk = true; 4403 4404 /* 4405 * If we have mixed data/metadata chunks we want to make sure we keep 4406 * allocating mixed chunks instead of individual chunks. 4407 */ 4408 if (btrfs_mixed_space_info(space_info)) 4409 flags |= (BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA); 4410 4411 /* 4412 * if we're doing a data chunk, go ahead and make sure that 4413 * we keep a reasonable number of metadata chunks allocated in the 4414 * FS as well. 4415 */ 4416 if (flags & BTRFS_BLOCK_GROUP_DATA && fs_info->metadata_ratio) { 4417 fs_info->data_chunk_allocations++; 4418 if (!(fs_info->data_chunk_allocations % 4419 fs_info->metadata_ratio)) 4420 force_metadata_allocation(fs_info); 4421 } 4422 4423 ret_bg = do_chunk_alloc(trans, space_info, flags); 4424 trans->allocating_chunk = false; 4425 4426 if (IS_ERR(ret_bg)) { 4427 ret = PTR_ERR(ret_bg); 4428 } else if (from_extent_allocation && (flags & BTRFS_BLOCK_GROUP_DATA)) { 4429 /* 4430 * New block group is likely to be used soon. Try to activate 4431 * it now. Failure is OK for now. 4432 */ 4433 btrfs_zone_activate(ret_bg); 4434 } 4435 4436 if (!ret) 4437 btrfs_put_block_group(ret_bg); 4438 4439 spin_lock(&space_info->lock); 4440 if (ret < 0) { 4441 if (ret == -ENOSPC) 4442 space_info->full = true; 4443 else 4444 goto out; 4445 } else { 4446 ret = 1; 4447 space_info->max_extent_size = 0; 4448 } 4449 4450 space_info->force_alloc = CHUNK_ALLOC_NO_FORCE; 4451 out: 4452 space_info->chunk_alloc = false; 4453 spin_unlock(&space_info->lock); 4454 mutex_unlock(&fs_info->chunk_mutex); 4455 4456 return ret; 4457 } 4458 4459 static u64 get_profile_num_devs(const struct btrfs_fs_info *fs_info, u64 type) 4460 { 4461 u64 num_dev; 4462 4463 num_dev = btrfs_raid_array[btrfs_bg_flags_to_raid_index(type)].devs_max; 4464 if (!num_dev) 4465 num_dev = fs_info->fs_devices->rw_devices; 4466 4467 return num_dev; 4468 } 4469 4470 static void reserve_chunk_space(struct btrfs_trans_handle *trans, 4471 u64 bytes, 4472 u64 type) 4473 { 4474 struct btrfs_fs_info *fs_info = trans->fs_info; 4475 struct btrfs_space_info *info; 4476 u64 left; 4477 int ret = 0; 4478 4479 /* 4480 * Needed because we can end up allocating a system chunk and for an 4481 * atomic and race free space reservation in the chunk block reserve. 4482 */ 4483 lockdep_assert_held(&fs_info->chunk_mutex); 4484 4485 info = btrfs_find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM); 4486 spin_lock(&info->lock); 4487 left = info->total_bytes - btrfs_space_info_used(info, true); 4488 spin_unlock(&info->lock); 4489 4490 if (left < bytes && btrfs_test_opt(fs_info, ENOSPC_DEBUG)) { 4491 btrfs_info(fs_info, "left=%llu, need=%llu, flags=%llu", 4492 left, bytes, type); 4493 btrfs_dump_space_info(info, 0, false); 4494 } 4495 4496 if (left < bytes) { 4497 u64 flags = btrfs_system_alloc_profile(fs_info); 4498 struct btrfs_block_group *bg; 4499 struct btrfs_space_info *space_info; 4500 4501 space_info = btrfs_find_space_info(fs_info, flags); 4502 ASSERT(space_info); 4503 4504 /* 4505 * Ignore failure to create system chunk. We might end up not 4506 * needing it, as we might not need to COW all nodes/leafs from 4507 * the paths we visit in the chunk tree (they were already COWed 4508 * or created in the current transaction for example). 4509 */ 4510 bg = btrfs_create_chunk(trans, space_info, flags); 4511 if (IS_ERR(bg)) { 4512 ret = PTR_ERR(bg); 4513 } else { 4514 /* 4515 * We have a new chunk. We also need to activate it for 4516 * zoned filesystem. 4517 */ 4518 ret = btrfs_zoned_activate_one_bg(info, true); 4519 if (ret < 0) 4520 return; 4521 4522 /* 4523 * If we fail to add the chunk item here, we end up 4524 * trying again at phase 2 of chunk allocation, at 4525 * btrfs_create_pending_block_groups(). So ignore 4526 * any error here. An ENOSPC here could happen, due to 4527 * the cases described at do_chunk_alloc() - the system 4528 * block group we just created was just turned into RO 4529 * mode by a scrub for example, or a running discard 4530 * temporarily removed its free space entries, etc. 4531 */ 4532 btrfs_chunk_alloc_add_chunk_item(trans, bg); 4533 } 4534 } 4535 4536 if (!ret) { 4537 ret = btrfs_block_rsv_add(fs_info, 4538 &fs_info->chunk_block_rsv, 4539 bytes, BTRFS_RESERVE_NO_FLUSH); 4540 if (!ret) 4541 trans->chunk_bytes_reserved += bytes; 4542 } 4543 } 4544 4545 /* 4546 * Reserve space in the system space for allocating or removing a chunk. 4547 * The caller must be holding fs_info->chunk_mutex. 4548 */ 4549 void check_system_chunk(struct btrfs_trans_handle *trans, u64 type) 4550 { 4551 struct btrfs_fs_info *fs_info = trans->fs_info; 4552 const u64 num_devs = get_profile_num_devs(fs_info, type); 4553 u64 bytes; 4554 4555 /* num_devs device items to update and 1 chunk item to add or remove. */ 4556 bytes = btrfs_calc_metadata_size(fs_info, num_devs) + 4557 btrfs_calc_insert_metadata_size(fs_info, 1); 4558 4559 reserve_chunk_space(trans, bytes, type); 4560 } 4561 4562 /* 4563 * Reserve space in the system space, if needed, for doing a modification to the 4564 * chunk btree. 4565 * 4566 * @trans: A transaction handle. 4567 * @is_item_insertion: Indicate if the modification is for inserting a new item 4568 * in the chunk btree or if it's for the deletion or update 4569 * of an existing item. 4570 * 4571 * This is used in a context where we need to update the chunk btree outside 4572 * block group allocation and removal, to avoid a deadlock with a concurrent 4573 * task that is allocating a metadata or data block group and therefore needs to 4574 * update the chunk btree while holding the chunk mutex. After the update to the 4575 * chunk btree is done, btrfs_trans_release_chunk_metadata() should be called. 4576 * 4577 */ 4578 void btrfs_reserve_chunk_metadata(struct btrfs_trans_handle *trans, 4579 bool is_item_insertion) 4580 { 4581 struct btrfs_fs_info *fs_info = trans->fs_info; 4582 u64 bytes; 4583 4584 if (is_item_insertion) 4585 bytes = btrfs_calc_insert_metadata_size(fs_info, 1); 4586 else 4587 bytes = btrfs_calc_metadata_size(fs_info, 1); 4588 4589 mutex_lock(&fs_info->chunk_mutex); 4590 reserve_chunk_space(trans, bytes, BTRFS_BLOCK_GROUP_SYSTEM); 4591 mutex_unlock(&fs_info->chunk_mutex); 4592 } 4593 4594 void btrfs_put_block_group_cache(struct btrfs_fs_info *info) 4595 { 4596 struct btrfs_block_group *block_group; 4597 4598 block_group = btrfs_lookup_first_block_group(info, 0); 4599 while (block_group) { 4600 btrfs_wait_block_group_cache_done(block_group); 4601 spin_lock(&block_group->lock); 4602 if (test_and_clear_bit(BLOCK_GROUP_FLAG_IREF, 4603 &block_group->runtime_flags)) { 4604 struct btrfs_inode *inode = block_group->inode; 4605 4606 block_group->inode = NULL; 4607 spin_unlock(&block_group->lock); 4608 4609 ASSERT(block_group->io_ctl.inode == NULL); 4610 iput(&inode->vfs_inode); 4611 } else { 4612 spin_unlock(&block_group->lock); 4613 } 4614 block_group = btrfs_next_block_group(block_group); 4615 } 4616 } 4617 4618 static void check_removing_space_info(struct btrfs_space_info *space_info) 4619 { 4620 struct btrfs_fs_info *info = space_info->fs_info; 4621 4622 if (space_info->subgroup_id == BTRFS_SUB_GROUP_PRIMARY) { 4623 /* This is a top space_info, proceed with its children first. */ 4624 for (int i = 0; i < BTRFS_SPACE_INFO_SUB_GROUP_MAX; i++) { 4625 if (space_info->sub_group[i]) { 4626 check_removing_space_info(space_info->sub_group[i]); 4627 btrfs_sysfs_remove_space_info(space_info->sub_group[i]); 4628 space_info->sub_group[i] = NULL; 4629 } 4630 } 4631 } 4632 4633 /* 4634 * Do not hide this behind enospc_debug, this is actually important and 4635 * indicates a real bug if this happens. 4636 */ 4637 if (WARN_ON(space_info->bytes_pinned > 0 || space_info->bytes_may_use > 0)) 4638 btrfs_dump_space_info(space_info, 0, false); 4639 4640 /* 4641 * If there was a failure to cleanup a log tree, very likely due to an 4642 * IO failure on a writeback attempt of one or more of its extent 4643 * buffers, we could not do proper (and cheap) unaccounting of their 4644 * reserved space, so don't warn on bytes_reserved > 0 in that case. 4645 */ 4646 if (!(space_info->flags & BTRFS_BLOCK_GROUP_METADATA) || 4647 !BTRFS_FS_LOG_CLEANUP_ERROR(info)) { 4648 if (WARN_ON(space_info->bytes_reserved > 0)) 4649 btrfs_dump_space_info(space_info, 0, false); 4650 } 4651 4652 WARN_ON(space_info->reclaim_size > 0); 4653 } 4654 4655 /* 4656 * Must be called only after stopping all workers, since we could have block 4657 * group caching kthreads running, and therefore they could race with us if we 4658 * freed the block groups before stopping them. 4659 */ 4660 int btrfs_free_block_groups(struct btrfs_fs_info *info) 4661 { 4662 struct btrfs_block_group *block_group; 4663 struct btrfs_space_info *space_info; 4664 struct btrfs_caching_control *caching_ctl; 4665 struct rb_node *n; 4666 4667 if (btrfs_is_zoned(info)) { 4668 if (info->active_meta_bg) { 4669 btrfs_put_block_group(info->active_meta_bg); 4670 info->active_meta_bg = NULL; 4671 } 4672 if (info->active_system_bg) { 4673 btrfs_put_block_group(info->active_system_bg); 4674 info->active_system_bg = NULL; 4675 } 4676 } 4677 4678 write_lock(&info->block_group_cache_lock); 4679 while (!list_empty(&info->caching_block_groups)) { 4680 caching_ctl = list_first_entry(&info->caching_block_groups, 4681 struct btrfs_caching_control, list); 4682 list_del(&caching_ctl->list); 4683 btrfs_put_caching_control(caching_ctl); 4684 } 4685 write_unlock(&info->block_group_cache_lock); 4686 4687 spin_lock(&info->unused_bgs_lock); 4688 while (!list_empty(&info->unused_bgs)) { 4689 block_group = list_first_entry(&info->unused_bgs, 4690 struct btrfs_block_group, 4691 bg_list); 4692 list_del_init(&block_group->bg_list); 4693 btrfs_put_block_group(block_group); 4694 } 4695 4696 while (!list_empty(&info->reclaim_bgs)) { 4697 block_group = list_first_entry(&info->reclaim_bgs, 4698 struct btrfs_block_group, 4699 bg_list); 4700 list_del_init(&block_group->bg_list); 4701 btrfs_put_block_group(block_group); 4702 } 4703 4704 while (!list_empty(&info->fully_remapped_bgs)) { 4705 block_group = list_first_entry(&info->fully_remapped_bgs, 4706 struct btrfs_block_group, bg_list); 4707 list_del_init(&block_group->bg_list); 4708 btrfs_put_block_group(block_group); 4709 } 4710 spin_unlock(&info->unused_bgs_lock); 4711 4712 spin_lock(&info->zone_active_bgs_lock); 4713 while (!list_empty(&info->zone_active_bgs)) { 4714 block_group = list_first_entry(&info->zone_active_bgs, 4715 struct btrfs_block_group, 4716 active_bg_list); 4717 list_del_init(&block_group->active_bg_list); 4718 btrfs_put_block_group(block_group); 4719 } 4720 spin_unlock(&info->zone_active_bgs_lock); 4721 4722 write_lock(&info->block_group_cache_lock); 4723 while ((n = rb_last(&info->block_group_cache_tree.rb_root)) != NULL) { 4724 block_group = rb_entry(n, struct btrfs_block_group, 4725 cache_node); 4726 rb_erase_cached(&block_group->cache_node, 4727 &info->block_group_cache_tree); 4728 RB_CLEAR_NODE(&block_group->cache_node); 4729 write_unlock(&info->block_group_cache_lock); 4730 4731 down_write(&block_group->space_info->groups_sem); 4732 list_del(&block_group->list); 4733 up_write(&block_group->space_info->groups_sem); 4734 4735 /* 4736 * We haven't cached this block group, which means we could 4737 * possibly have excluded extents on this block group. 4738 */ 4739 if (block_group->cached == BTRFS_CACHE_NO || 4740 block_group->cached == BTRFS_CACHE_ERROR) 4741 btrfs_free_excluded_extents(block_group); 4742 4743 btrfs_remove_free_space_cache(block_group); 4744 ASSERT(block_group->cached != BTRFS_CACHE_STARTED); 4745 ASSERT(list_empty(&block_group->dirty_list)); 4746 ASSERT(list_empty(&block_group->io_list)); 4747 ASSERT(list_empty(&block_group->bg_list)); 4748 ASSERT(refcount_read(&block_group->refs) == 1); 4749 ASSERT(block_group->swap_extents == 0); 4750 btrfs_put_block_group(block_group); 4751 4752 write_lock(&info->block_group_cache_lock); 4753 } 4754 write_unlock(&info->block_group_cache_lock); 4755 4756 btrfs_release_global_block_rsv(info); 4757 4758 while (!list_empty(&info->space_info)) { 4759 space_info = list_first_entry(&info->space_info, 4760 struct btrfs_space_info, list); 4761 4762 check_removing_space_info(space_info); 4763 list_del(&space_info->list); 4764 btrfs_sysfs_remove_space_info(space_info); 4765 } 4766 return 0; 4767 } 4768 4769 void btrfs_freeze_block_group(struct btrfs_block_group *cache) 4770 { 4771 atomic_inc(&cache->frozen); 4772 } 4773 4774 void btrfs_unfreeze_block_group(struct btrfs_block_group *block_group) 4775 { 4776 struct btrfs_fs_info *fs_info = block_group->fs_info; 4777 bool cleanup; 4778 4779 spin_lock(&block_group->lock); 4780 cleanup = (atomic_dec_and_test(&block_group->frozen) && 4781 test_bit(BLOCK_GROUP_FLAG_REMOVED, &block_group->runtime_flags)); 4782 spin_unlock(&block_group->lock); 4783 4784 if (cleanup) { 4785 struct btrfs_chunk_map *map; 4786 4787 map = btrfs_find_chunk_map(fs_info, block_group->start, 1); 4788 /* Logic error, can't happen. */ 4789 ASSERT(map); 4790 4791 btrfs_remove_chunk_map(fs_info, map); 4792 4793 /* Once for our lookup reference. */ 4794 btrfs_free_chunk_map(map); 4795 4796 /* 4797 * We may have left one free space entry and other possible 4798 * tasks trimming this block group have left 1 entry each one. 4799 * Free them if any. 4800 */ 4801 btrfs_remove_free_space_cache(block_group); 4802 } 4803 } 4804 4805 bool btrfs_inc_block_group_swap_extents(struct btrfs_block_group *bg) 4806 { 4807 bool ret = true; 4808 4809 spin_lock(&bg->lock); 4810 if (bg->ro) 4811 ret = false; 4812 else 4813 bg->swap_extents++; 4814 spin_unlock(&bg->lock); 4815 4816 return ret; 4817 } 4818 4819 void btrfs_dec_block_group_swap_extents(struct btrfs_block_group *bg, int amount) 4820 { 4821 spin_lock(&bg->lock); 4822 ASSERT(!bg->ro); 4823 ASSERT(bg->swap_extents >= amount); 4824 bg->swap_extents -= amount; 4825 spin_unlock(&bg->lock); 4826 } 4827 4828 enum btrfs_block_group_size_class btrfs_calc_block_group_size_class(u64 size) 4829 { 4830 if (size <= SZ_128K) 4831 return BTRFS_BG_SZ_SMALL; 4832 if (size <= SZ_8M) 4833 return BTRFS_BG_SZ_MEDIUM; 4834 return BTRFS_BG_SZ_LARGE; 4835 } 4836 4837 /* 4838 * Handle a block group allocating an extent in a size class 4839 * 4840 * @bg: The block group we allocated in. 4841 * @size_class: The size class of the allocation. 4842 * @force_wrong_size_class: Whether we are desperate enough to allow 4843 * mismatched size classes. 4844 * 4845 * Returns: 0 if the size class was valid for this block_group, -EAGAIN in the 4846 * case of a race that leads to the wrong size class without 4847 * force_wrong_size_class set. 4848 * 4849 * find_free_extent will skip block groups with a mismatched size class until 4850 * it really needs to avoid ENOSPC. In that case it will set 4851 * force_wrong_size_class. However, if a block group is newly allocated and 4852 * doesn't yet have a size class, then it is possible for two allocations of 4853 * different sizes to race and both try to use it. The loser is caught here and 4854 * has to retry. 4855 */ 4856 int btrfs_use_block_group_size_class(struct btrfs_block_group *bg, 4857 enum btrfs_block_group_size_class size_class, 4858 bool force_wrong_size_class) 4859 { 4860 lockdep_assert_held(&bg->lock); 4861 ASSERT(size_class != BTRFS_BG_SZ_NONE); 4862 4863 /* The new allocation is in the right size class, do nothing */ 4864 if (bg->size_class == size_class) 4865 return 0; 4866 /* 4867 * The new allocation is in a mismatched size class. 4868 * This means one of two things: 4869 * 4870 * 1. Two tasks in find_free_extent for different size_classes raced 4871 * and hit the same empty block_group. Make the loser try again. 4872 * 2. A call to find_free_extent got desperate enough to set 4873 * 'force_wrong_slab'. Don't change the size_class, but allow the 4874 * allocation. 4875 */ 4876 if (bg->size_class != BTRFS_BG_SZ_NONE) { 4877 if (force_wrong_size_class) 4878 return 0; 4879 return -EAGAIN; 4880 } 4881 /* 4882 * The happy new block group case: the new allocation is the first 4883 * one in the block_group so we set size_class. 4884 */ 4885 bg->size_class = size_class; 4886 4887 return 0; 4888 } 4889 4890 bool btrfs_block_group_should_use_size_class(const struct btrfs_block_group *bg) 4891 { 4892 if (btrfs_is_zoned(bg->fs_info)) 4893 return false; 4894 if (!btrfs_is_block_group_data_only(bg)) 4895 return false; 4896 return true; 4897 } 4898 4899 void btrfs_mark_bg_fully_remapped(struct btrfs_block_group *bg, 4900 struct btrfs_trans_handle *trans) 4901 { 4902 struct btrfs_fs_info *fs_info = trans->fs_info; 4903 4904 4905 if (btrfs_test_opt(fs_info, DISCARD_ASYNC)) { 4906 spin_lock(&bg->lock); 4907 set_bit(BLOCK_GROUP_FLAG_STRIPE_REMOVAL_PENDING, &bg->runtime_flags); 4908 spin_unlock(&bg->lock); 4909 4910 btrfs_discard_queue_work(&fs_info->discard_ctl, bg); 4911 } else { 4912 spin_lock(&fs_info->unused_bgs_lock); 4913 /* 4914 * The block group might already be on the unused_bgs list, 4915 * remove it if it is. It'll get readded after 4916 * btrfs_handle_fully_remapped_bgs() finishes. 4917 */ 4918 if (!list_empty(&bg->bg_list)) 4919 list_del(&bg->bg_list); 4920 else 4921 btrfs_get_block_group(bg); 4922 4923 list_add_tail(&bg->bg_list, &fs_info->fully_remapped_bgs); 4924 spin_unlock(&fs_info->unused_bgs_lock); 4925 } 4926 } 4927 4928 /* 4929 * Compare the block group and chunk trees, and find any fully-remapped block 4930 * groups which haven't yet had their chunk stripes and device extents removed, 4931 * and put them on the fully_remapped_bgs list so this gets done. 4932 * 4933 * This happens when a block group becomes fully remapped, i.e. its last 4934 * identity mapping is removed, and the volume is unmounted before async 4935 * discard has finished. It's important this gets done as until it is the 4936 * chunk's stripes are dead space. 4937 */ 4938 int btrfs_populate_fully_remapped_bgs_list(struct btrfs_fs_info *fs_info) 4939 { 4940 struct rb_node *node_bg, *node_chunk; 4941 4942 node_bg = rb_first_cached(&fs_info->block_group_cache_tree); 4943 node_chunk = rb_first_cached(&fs_info->mapping_tree); 4944 4945 while (node_bg && node_chunk) { 4946 struct btrfs_block_group *bg; 4947 struct btrfs_chunk_map *map; 4948 4949 bg = rb_entry(node_bg, struct btrfs_block_group, cache_node); 4950 map = rb_entry(node_chunk, struct btrfs_chunk_map, rb_node); 4951 4952 ASSERT(bg->start == map->start); 4953 4954 if (!(bg->flags & BTRFS_BLOCK_GROUP_REMAPPED)) 4955 goto next; 4956 4957 if (bg->identity_remap_count != 0) 4958 goto next; 4959 4960 if (map->num_stripes == 0) 4961 goto next; 4962 4963 spin_lock(&fs_info->unused_bgs_lock); 4964 4965 if (list_empty(&bg->bg_list)) { 4966 btrfs_get_block_group(bg); 4967 list_add_tail(&bg->bg_list, &fs_info->fully_remapped_bgs); 4968 } else { 4969 list_move_tail(&bg->bg_list, &fs_info->fully_remapped_bgs); 4970 } 4971 4972 spin_unlock(&fs_info->unused_bgs_lock); 4973 4974 /* 4975 * Ideally we'd want to call btrfs_discard_queue_work() here, 4976 * but it'd do nothing as the discard worker hasn't been 4977 * started yet. 4978 * 4979 * The block group will get added to the discard list when 4980 * btrfs_handle_fully_remapped_bgs() gets called, when we 4981 * commit the first transaction. 4982 */ 4983 if (btrfs_test_opt(fs_info, DISCARD_ASYNC)) { 4984 spin_lock(&bg->lock); 4985 set_bit(BLOCK_GROUP_FLAG_STRIPE_REMOVAL_PENDING, &bg->runtime_flags); 4986 spin_unlock(&bg->lock); 4987 } 4988 4989 next: 4990 node_bg = rb_next(node_bg); 4991 node_chunk = rb_next(node_chunk); 4992 } 4993 4994 ASSERT(!node_bg && !node_chunk); 4995 4996 return 0; 4997 } 4998