1 // SPDX-License-Identifier: GPL-2.0 2 3 #include "misc.h" 4 #include "ctree.h" 5 #include "space-info.h" 6 #include "sysfs.h" 7 #include "volumes.h" 8 #include "free-space-cache.h" 9 #include "ordered-data.h" 10 #include "transaction.h" 11 #include "block-group.h" 12 #include "zoned.h" 13 #include "fs.h" 14 #include "accessors.h" 15 #include "extent-tree.h" 16 17 /* 18 * HOW DOES SPACE RESERVATION WORK 19 * 20 * If you want to know about delalloc specifically, there is a separate comment 21 * for that with the delalloc code. This comment is about how the whole system 22 * works generally. 23 * 24 * BASIC CONCEPTS 25 * 26 * 1) space_info. This is the ultimate arbiter of how much space we can use. 27 * There's a description of the bytes_ fields with the struct declaration, 28 * refer to that for specifics on each field. Suffice it to say that for 29 * reservations we care about total_bytes - SUM(space_info->bytes_) when 30 * determining if there is space to make an allocation. There is a space_info 31 * for METADATA, SYSTEM, and DATA areas. 32 * 33 * 2) block_rsv's. These are basically buckets for every different type of 34 * metadata reservation we have. You can see the comment in the block_rsv 35 * code on the rules for each type, but generally block_rsv->reserved is how 36 * much space is accounted for in space_info->bytes_may_use. 37 * 38 * 3) btrfs_calc*_size. These are the worst case calculations we used based 39 * on the number of items we will want to modify. We have one for changing 40 * items, and one for inserting new items. Generally we use these helpers to 41 * determine the size of the block reserves, and then use the actual bytes 42 * values to adjust the space_info counters. 43 * 44 * MAKING RESERVATIONS, THE NORMAL CASE 45 * 46 * We call into either btrfs_reserve_data_bytes() or 47 * btrfs_reserve_metadata_bytes(), depending on which we're looking for, with 48 * num_bytes we want to reserve. 49 * 50 * ->reserve 51 * space_info->bytes_may_reserve += num_bytes 52 * 53 * ->extent allocation 54 * Call btrfs_add_reserved_bytes() which does 55 * space_info->bytes_may_reserve -= num_bytes 56 * space_info->bytes_reserved += extent_bytes 57 * 58 * ->insert reference 59 * Call btrfs_update_block_group() which does 60 * space_info->bytes_reserved -= extent_bytes 61 * space_info->bytes_used += extent_bytes 62 * 63 * MAKING RESERVATIONS, FLUSHING NORMALLY (non-priority) 64 * 65 * Assume we are unable to simply make the reservation because we do not have 66 * enough space 67 * 68 * -> __reserve_bytes 69 * create a reserve_ticket with ->bytes set to our reservation, add it to 70 * the tail of space_info->tickets, kick async flush thread 71 * 72 * ->handle_reserve_ticket 73 * wait on ticket->wait for ->bytes to be reduced to 0, or ->error to be set 74 * on the ticket. 75 * 76 * -> btrfs_async_reclaim_metadata_space/btrfs_async_reclaim_data_space 77 * Flushes various things attempting to free up space. 78 * 79 * -> btrfs_try_granting_tickets() 80 * This is called by anything that either subtracts space from 81 * space_info->bytes_may_use, ->bytes_pinned, etc, or adds to the 82 * space_info->total_bytes. This loops through the ->priority_tickets and 83 * then the ->tickets list checking to see if the reservation can be 84 * completed. If it can the space is added to space_info->bytes_may_use and 85 * the ticket is woken up. 86 * 87 * -> ticket wakeup 88 * Check if ->bytes == 0, if it does we got our reservation and we can carry 89 * on, if not return the appropriate error (ENOSPC, but can be EINTR if we 90 * were interrupted.) 91 * 92 * MAKING RESERVATIONS, FLUSHING HIGH PRIORITY 93 * 94 * Same as the above, except we add ourselves to the 95 * space_info->priority_tickets, and we do not use ticket->wait, we simply 96 * call flush_space() ourselves for the states that are safe for us to call 97 * without deadlocking and hope for the best. 98 * 99 * THE FLUSHING STATES 100 * 101 * Generally speaking we will have two cases for each state, a "nice" state 102 * and a "ALL THE THINGS" state. In btrfs we delay a lot of work in order to 103 * reduce the locking over head on the various trees, and even to keep from 104 * doing any work at all in the case of delayed refs. Each of these delayed 105 * things however hold reservations, and so letting them run allows us to 106 * reclaim space so we can make new reservations. 107 * 108 * FLUSH_DELAYED_ITEMS 109 * Every inode has a delayed item to update the inode. Take a simple write 110 * for example, we would update the inode item at write time to update the 111 * mtime, and then again at finish_ordered_io() time in order to update the 112 * isize or bytes. We keep these delayed items to coalesce these operations 113 * into a single operation done on demand. These are an easy way to reclaim 114 * metadata space. 115 * 116 * FLUSH_DELALLOC 117 * Look at the delalloc comment to get an idea of how much space is reserved 118 * for delayed allocation. We can reclaim some of this space simply by 119 * running delalloc, but usually we need to wait for ordered extents to 120 * reclaim the bulk of this space. 121 * 122 * FLUSH_DELAYED_REFS 123 * We have a block reserve for the outstanding delayed refs space, and every 124 * delayed ref operation holds a reservation. Running these is a quick way 125 * to reclaim space, but we want to hold this until the end because COW can 126 * churn a lot and we can avoid making some extent tree modifications if we 127 * are able to delay for as long as possible. 128 * 129 * ALLOC_CHUNK 130 * We will skip this the first time through space reservation, because of 131 * overcommit and we don't want to have a lot of useless metadata space when 132 * our worst case reservations will likely never come true. 133 * 134 * RUN_DELAYED_IPUTS 135 * If we're freeing inodes we're likely freeing checksums, file extent 136 * items, and extent tree items. Loads of space could be freed up by these 137 * operations, however they won't be usable until the transaction commits. 138 * 139 * COMMIT_TRANS 140 * This will commit the transaction. Historically we had a lot of logic 141 * surrounding whether or not we'd commit the transaction, but this waits born 142 * out of a pre-tickets era where we could end up committing the transaction 143 * thousands of times in a row without making progress. Now thanks to our 144 * ticketing system we know if we're not making progress and can error 145 * everybody out after a few commits rather than burning the disk hoping for 146 * a different answer. 147 * 148 * OVERCOMMIT 149 * 150 * Because we hold so many reservations for metadata we will allow you to 151 * reserve more space than is currently free in the currently allocate 152 * metadata space. This only happens with metadata, data does not allow 153 * overcommitting. 154 * 155 * You can see the current logic for when we allow overcommit in 156 * btrfs_can_overcommit(), but it only applies to unallocated space. If there 157 * is no unallocated space to be had, all reservations are kept within the 158 * free space in the allocated metadata chunks. 159 * 160 * Because of overcommitting, you generally want to use the 161 * btrfs_can_overcommit() logic for metadata allocations, as it does the right 162 * thing with or without extra unallocated space. 163 */ 164 165 u64 __pure btrfs_space_info_used(struct btrfs_space_info *s_info, 166 bool may_use_included) 167 { 168 ASSERT(s_info); 169 return s_info->bytes_used + s_info->bytes_reserved + 170 s_info->bytes_pinned + s_info->bytes_readonly + 171 s_info->bytes_zone_unusable + 172 (may_use_included ? s_info->bytes_may_use : 0); 173 } 174 175 /* 176 * after adding space to the filesystem, we need to clear the full flags 177 * on all the space infos. 178 */ 179 void btrfs_clear_space_info_full(struct btrfs_fs_info *info) 180 { 181 struct list_head *head = &info->space_info; 182 struct btrfs_space_info *found; 183 184 list_for_each_entry(found, head, list) 185 found->full = 0; 186 } 187 188 /* 189 * Block groups with more than this value (percents) of unusable space will be 190 * scheduled for background reclaim. 191 */ 192 #define BTRFS_DEFAULT_ZONED_RECLAIM_THRESH (75) 193 194 /* 195 * Calculate chunk size depending on volume type (regular or zoned). 196 */ 197 static u64 calc_chunk_size(const struct btrfs_fs_info *fs_info, u64 flags) 198 { 199 if (btrfs_is_zoned(fs_info)) 200 return fs_info->zone_size; 201 202 ASSERT(flags & BTRFS_BLOCK_GROUP_TYPE_MASK); 203 204 if (flags & BTRFS_BLOCK_GROUP_DATA) 205 return BTRFS_MAX_DATA_CHUNK_SIZE; 206 else if (flags & BTRFS_BLOCK_GROUP_SYSTEM) 207 return SZ_32M; 208 209 /* Handle BTRFS_BLOCK_GROUP_METADATA */ 210 if (fs_info->fs_devices->total_rw_bytes > 50ULL * SZ_1G) 211 return SZ_1G; 212 213 return SZ_256M; 214 } 215 216 /* 217 * Update default chunk size. 218 */ 219 void btrfs_update_space_info_chunk_size(struct btrfs_space_info *space_info, 220 u64 chunk_size) 221 { 222 WRITE_ONCE(space_info->chunk_size, chunk_size); 223 } 224 225 static int create_space_info(struct btrfs_fs_info *info, u64 flags) 226 { 227 228 struct btrfs_space_info *space_info; 229 int i; 230 int ret; 231 232 space_info = kzalloc(sizeof(*space_info), GFP_NOFS); 233 if (!space_info) 234 return -ENOMEM; 235 236 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) 237 INIT_LIST_HEAD(&space_info->block_groups[i]); 238 init_rwsem(&space_info->groups_sem); 239 spin_lock_init(&space_info->lock); 240 space_info->flags = flags & BTRFS_BLOCK_GROUP_TYPE_MASK; 241 space_info->force_alloc = CHUNK_ALLOC_NO_FORCE; 242 INIT_LIST_HEAD(&space_info->ro_bgs); 243 INIT_LIST_HEAD(&space_info->tickets); 244 INIT_LIST_HEAD(&space_info->priority_tickets); 245 space_info->clamp = 1; 246 btrfs_update_space_info_chunk_size(space_info, calc_chunk_size(info, flags)); 247 248 if (btrfs_is_zoned(info)) 249 space_info->bg_reclaim_threshold = BTRFS_DEFAULT_ZONED_RECLAIM_THRESH; 250 251 ret = btrfs_sysfs_add_space_info_type(info, space_info); 252 if (ret) 253 return ret; 254 255 list_add(&space_info->list, &info->space_info); 256 if (flags & BTRFS_BLOCK_GROUP_DATA) 257 info->data_sinfo = space_info; 258 259 return ret; 260 } 261 262 int btrfs_init_space_info(struct btrfs_fs_info *fs_info) 263 { 264 struct btrfs_super_block *disk_super; 265 u64 features; 266 u64 flags; 267 int mixed = 0; 268 int ret; 269 270 disk_super = fs_info->super_copy; 271 if (!btrfs_super_root(disk_super)) 272 return -EINVAL; 273 274 features = btrfs_super_incompat_flags(disk_super); 275 if (features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS) 276 mixed = 1; 277 278 flags = BTRFS_BLOCK_GROUP_SYSTEM; 279 ret = create_space_info(fs_info, flags); 280 if (ret) 281 goto out; 282 283 if (mixed) { 284 flags = BTRFS_BLOCK_GROUP_METADATA | BTRFS_BLOCK_GROUP_DATA; 285 ret = create_space_info(fs_info, flags); 286 } else { 287 flags = BTRFS_BLOCK_GROUP_METADATA; 288 ret = create_space_info(fs_info, flags); 289 if (ret) 290 goto out; 291 292 flags = BTRFS_BLOCK_GROUP_DATA; 293 ret = create_space_info(fs_info, flags); 294 } 295 out: 296 return ret; 297 } 298 299 void btrfs_add_bg_to_space_info(struct btrfs_fs_info *info, 300 struct btrfs_block_group *block_group) 301 { 302 struct btrfs_space_info *found; 303 int factor, index; 304 305 factor = btrfs_bg_type_to_factor(block_group->flags); 306 307 found = btrfs_find_space_info(info, block_group->flags); 308 ASSERT(found); 309 spin_lock(&found->lock); 310 found->total_bytes += block_group->length; 311 found->disk_total += block_group->length * factor; 312 found->bytes_used += block_group->used; 313 found->disk_used += block_group->used * factor; 314 found->bytes_readonly += block_group->bytes_super; 315 found->bytes_zone_unusable += block_group->zone_unusable; 316 if (block_group->length > 0) 317 found->full = 0; 318 btrfs_try_granting_tickets(info, found); 319 spin_unlock(&found->lock); 320 321 block_group->space_info = found; 322 323 index = btrfs_bg_flags_to_raid_index(block_group->flags); 324 down_write(&found->groups_sem); 325 list_add_tail(&block_group->list, &found->block_groups[index]); 326 up_write(&found->groups_sem); 327 } 328 329 struct btrfs_space_info *btrfs_find_space_info(struct btrfs_fs_info *info, 330 u64 flags) 331 { 332 struct list_head *head = &info->space_info; 333 struct btrfs_space_info *found; 334 335 flags &= BTRFS_BLOCK_GROUP_TYPE_MASK; 336 337 list_for_each_entry(found, head, list) { 338 if (found->flags & flags) 339 return found; 340 } 341 return NULL; 342 } 343 344 static u64 calc_available_free_space(struct btrfs_fs_info *fs_info, 345 struct btrfs_space_info *space_info, 346 enum btrfs_reserve_flush_enum flush) 347 { 348 u64 profile; 349 u64 avail; 350 int factor; 351 352 if (space_info->flags & BTRFS_BLOCK_GROUP_SYSTEM) 353 profile = btrfs_system_alloc_profile(fs_info); 354 else 355 profile = btrfs_metadata_alloc_profile(fs_info); 356 357 avail = atomic64_read(&fs_info->free_chunk_space); 358 359 /* 360 * If we have dup, raid1 or raid10 then only half of the free 361 * space is actually usable. For raid56, the space info used 362 * doesn't include the parity drive, so we don't have to 363 * change the math 364 */ 365 factor = btrfs_bg_type_to_factor(profile); 366 avail = div_u64(avail, factor); 367 368 /* 369 * If we aren't flushing all things, let us overcommit up to 370 * 1/2th of the space. If we can flush, don't let us overcommit 371 * too much, let it overcommit up to 1/8 of the space. 372 */ 373 if (flush == BTRFS_RESERVE_FLUSH_ALL) 374 avail >>= 3; 375 else 376 avail >>= 1; 377 return avail; 378 } 379 380 int btrfs_can_overcommit(struct btrfs_fs_info *fs_info, 381 struct btrfs_space_info *space_info, u64 bytes, 382 enum btrfs_reserve_flush_enum flush) 383 { 384 u64 avail; 385 u64 used; 386 387 /* Don't overcommit when in mixed mode */ 388 if (space_info->flags & BTRFS_BLOCK_GROUP_DATA) 389 return 0; 390 391 used = btrfs_space_info_used(space_info, true); 392 if (test_bit(BTRFS_FS_ACTIVE_ZONE_TRACKING, &fs_info->flags) && 393 (space_info->flags & BTRFS_BLOCK_GROUP_METADATA)) 394 avail = 0; 395 else 396 avail = calc_available_free_space(fs_info, space_info, flush); 397 398 if (used + bytes < space_info->total_bytes + avail) 399 return 1; 400 return 0; 401 } 402 403 static void remove_ticket(struct btrfs_space_info *space_info, 404 struct reserve_ticket *ticket) 405 { 406 if (!list_empty(&ticket->list)) { 407 list_del_init(&ticket->list); 408 ASSERT(space_info->reclaim_size >= ticket->bytes); 409 space_info->reclaim_size -= ticket->bytes; 410 } 411 } 412 413 /* 414 * This is for space we already have accounted in space_info->bytes_may_use, so 415 * basically when we're returning space from block_rsv's. 416 */ 417 void btrfs_try_granting_tickets(struct btrfs_fs_info *fs_info, 418 struct btrfs_space_info *space_info) 419 { 420 struct list_head *head; 421 enum btrfs_reserve_flush_enum flush = BTRFS_RESERVE_NO_FLUSH; 422 423 lockdep_assert_held(&space_info->lock); 424 425 head = &space_info->priority_tickets; 426 again: 427 while (!list_empty(head)) { 428 struct reserve_ticket *ticket; 429 u64 used = btrfs_space_info_used(space_info, true); 430 431 ticket = list_first_entry(head, struct reserve_ticket, list); 432 433 /* Check and see if our ticket can be satisfied now. */ 434 if ((used + ticket->bytes <= space_info->total_bytes) || 435 btrfs_can_overcommit(fs_info, space_info, ticket->bytes, 436 flush)) { 437 btrfs_space_info_update_bytes_may_use(fs_info, 438 space_info, 439 ticket->bytes); 440 remove_ticket(space_info, ticket); 441 ticket->bytes = 0; 442 space_info->tickets_id++; 443 wake_up(&ticket->wait); 444 } else { 445 break; 446 } 447 } 448 449 if (head == &space_info->priority_tickets) { 450 head = &space_info->tickets; 451 flush = BTRFS_RESERVE_FLUSH_ALL; 452 goto again; 453 } 454 } 455 456 #define DUMP_BLOCK_RSV(fs_info, rsv_name) \ 457 do { \ 458 struct btrfs_block_rsv *__rsv = &(fs_info)->rsv_name; \ 459 spin_lock(&__rsv->lock); \ 460 btrfs_info(fs_info, #rsv_name ": size %llu reserved %llu", \ 461 __rsv->size, __rsv->reserved); \ 462 spin_unlock(&__rsv->lock); \ 463 } while (0) 464 465 static const char *space_info_flag_to_str(const struct btrfs_space_info *space_info) 466 { 467 switch (space_info->flags) { 468 case BTRFS_BLOCK_GROUP_SYSTEM: 469 return "SYSTEM"; 470 case BTRFS_BLOCK_GROUP_METADATA | BTRFS_BLOCK_GROUP_DATA: 471 return "DATA+METADATA"; 472 case BTRFS_BLOCK_GROUP_DATA: 473 return "DATA"; 474 case BTRFS_BLOCK_GROUP_METADATA: 475 return "METADATA"; 476 default: 477 return "UNKNOWN"; 478 } 479 } 480 481 static void dump_global_block_rsv(struct btrfs_fs_info *fs_info) 482 { 483 DUMP_BLOCK_RSV(fs_info, global_block_rsv); 484 DUMP_BLOCK_RSV(fs_info, trans_block_rsv); 485 DUMP_BLOCK_RSV(fs_info, chunk_block_rsv); 486 DUMP_BLOCK_RSV(fs_info, delayed_block_rsv); 487 DUMP_BLOCK_RSV(fs_info, delayed_refs_rsv); 488 } 489 490 static void __btrfs_dump_space_info(struct btrfs_fs_info *fs_info, 491 struct btrfs_space_info *info) 492 { 493 const char *flag_str = space_info_flag_to_str(info); 494 lockdep_assert_held(&info->lock); 495 496 /* The free space could be negative in case of overcommit */ 497 btrfs_info(fs_info, "space_info %s has %lld free, is %sfull", 498 flag_str, 499 (s64)(info->total_bytes - btrfs_space_info_used(info, true)), 500 info->full ? "" : "not "); 501 btrfs_info(fs_info, 502 "space_info total=%llu, used=%llu, pinned=%llu, reserved=%llu, may_use=%llu, readonly=%llu zone_unusable=%llu", 503 info->total_bytes, info->bytes_used, info->bytes_pinned, 504 info->bytes_reserved, info->bytes_may_use, 505 info->bytes_readonly, info->bytes_zone_unusable); 506 } 507 508 void btrfs_dump_space_info(struct btrfs_fs_info *fs_info, 509 struct btrfs_space_info *info, u64 bytes, 510 int dump_block_groups) 511 { 512 struct btrfs_block_group *cache; 513 int index = 0; 514 515 spin_lock(&info->lock); 516 __btrfs_dump_space_info(fs_info, info); 517 dump_global_block_rsv(fs_info); 518 spin_unlock(&info->lock); 519 520 if (!dump_block_groups) 521 return; 522 523 down_read(&info->groups_sem); 524 again: 525 list_for_each_entry(cache, &info->block_groups[index], list) { 526 spin_lock(&cache->lock); 527 btrfs_info(fs_info, 528 "block group %llu has %llu bytes, %llu used %llu pinned %llu reserved %llu zone_unusable %s", 529 cache->start, cache->length, cache->used, cache->pinned, 530 cache->reserved, cache->zone_unusable, 531 cache->ro ? "[readonly]" : ""); 532 spin_unlock(&cache->lock); 533 btrfs_dump_free_space(cache, bytes); 534 } 535 if (++index < BTRFS_NR_RAID_TYPES) 536 goto again; 537 up_read(&info->groups_sem); 538 } 539 540 static inline u64 calc_reclaim_items_nr(struct btrfs_fs_info *fs_info, 541 u64 to_reclaim) 542 { 543 u64 bytes; 544 u64 nr; 545 546 bytes = btrfs_calc_insert_metadata_size(fs_info, 1); 547 nr = div64_u64(to_reclaim, bytes); 548 if (!nr) 549 nr = 1; 550 return nr; 551 } 552 553 static inline u64 calc_delayed_refs_nr(struct btrfs_fs_info *fs_info, 554 u64 to_reclaim) 555 { 556 u64 bytes; 557 u64 nr; 558 559 bytes = btrfs_calc_insert_metadata_size(fs_info, 1); 560 /* 561 * We have to check the mount option here because we could be enabling 562 * the free space tree for the first time and don't have the compat_ro 563 * option set yet. 564 * 565 * We need extra reservations if we have the free space tree because 566 * we'll have to modify that tree as well. 567 */ 568 if (btrfs_test_opt(fs_info, FREE_SPACE_TREE)) 569 bytes *= 2; 570 571 nr = div64_u64(to_reclaim, bytes); 572 if (!nr) 573 nr = 1; 574 return nr; 575 } 576 577 #define EXTENT_SIZE_PER_ITEM SZ_256K 578 579 /* 580 * shrink metadata reservation for delalloc 581 */ 582 static void shrink_delalloc(struct btrfs_fs_info *fs_info, 583 struct btrfs_space_info *space_info, 584 u64 to_reclaim, bool wait_ordered, 585 bool for_preempt) 586 { 587 struct btrfs_trans_handle *trans; 588 u64 delalloc_bytes; 589 u64 ordered_bytes; 590 u64 items; 591 long time_left; 592 int loops; 593 594 delalloc_bytes = percpu_counter_sum_positive(&fs_info->delalloc_bytes); 595 ordered_bytes = percpu_counter_sum_positive(&fs_info->ordered_bytes); 596 if (delalloc_bytes == 0 && ordered_bytes == 0) 597 return; 598 599 /* Calc the number of the pages we need flush for space reservation */ 600 if (to_reclaim == U64_MAX) { 601 items = U64_MAX; 602 } else { 603 /* 604 * to_reclaim is set to however much metadata we need to 605 * reclaim, but reclaiming that much data doesn't really track 606 * exactly. What we really want to do is reclaim full inode's 607 * worth of reservations, however that's not available to us 608 * here. We will take a fraction of the delalloc bytes for our 609 * flushing loops and hope for the best. Delalloc will expand 610 * the amount we write to cover an entire dirty extent, which 611 * will reclaim the metadata reservation for that range. If 612 * it's not enough subsequent flush stages will be more 613 * aggressive. 614 */ 615 to_reclaim = max(to_reclaim, delalloc_bytes >> 3); 616 items = calc_reclaim_items_nr(fs_info, to_reclaim) * 2; 617 } 618 619 trans = current->journal_info; 620 621 /* 622 * If we are doing more ordered than delalloc we need to just wait on 623 * ordered extents, otherwise we'll waste time trying to flush delalloc 624 * that likely won't give us the space back we need. 625 */ 626 if (ordered_bytes > delalloc_bytes && !for_preempt) 627 wait_ordered = true; 628 629 loops = 0; 630 while ((delalloc_bytes || ordered_bytes) && loops < 3) { 631 u64 temp = min(delalloc_bytes, to_reclaim) >> PAGE_SHIFT; 632 long nr_pages = min_t(u64, temp, LONG_MAX); 633 int async_pages; 634 635 btrfs_start_delalloc_roots(fs_info, nr_pages, true); 636 637 /* 638 * We need to make sure any outstanding async pages are now 639 * processed before we continue. This is because things like 640 * sync_inode() try to be smart and skip writing if the inode is 641 * marked clean. We don't use filemap_fwrite for flushing 642 * because we want to control how many pages we write out at a 643 * time, thus this is the only safe way to make sure we've 644 * waited for outstanding compressed workers to have started 645 * their jobs and thus have ordered extents set up properly. 646 * 647 * This exists because we do not want to wait for each 648 * individual inode to finish its async work, we simply want to 649 * start the IO on everybody, and then come back here and wait 650 * for all of the async work to catch up. Once we're done with 651 * that we know we'll have ordered extents for everything and we 652 * can decide if we wait for that or not. 653 * 654 * If we choose to replace this in the future, make absolutely 655 * sure that the proper waiting is being done in the async case, 656 * as there have been bugs in that area before. 657 */ 658 async_pages = atomic_read(&fs_info->async_delalloc_pages); 659 if (!async_pages) 660 goto skip_async; 661 662 /* 663 * We don't want to wait forever, if we wrote less pages in this 664 * loop than we have outstanding, only wait for that number of 665 * pages, otherwise we can wait for all async pages to finish 666 * before continuing. 667 */ 668 if (async_pages > nr_pages) 669 async_pages -= nr_pages; 670 else 671 async_pages = 0; 672 wait_event(fs_info->async_submit_wait, 673 atomic_read(&fs_info->async_delalloc_pages) <= 674 async_pages); 675 skip_async: 676 loops++; 677 if (wait_ordered && !trans) { 678 btrfs_wait_ordered_roots(fs_info, items, 0, (u64)-1); 679 } else { 680 time_left = schedule_timeout_killable(1); 681 if (time_left) 682 break; 683 } 684 685 /* 686 * If we are for preemption we just want a one-shot of delalloc 687 * flushing so we can stop flushing if we decide we don't need 688 * to anymore. 689 */ 690 if (for_preempt) 691 break; 692 693 spin_lock(&space_info->lock); 694 if (list_empty(&space_info->tickets) && 695 list_empty(&space_info->priority_tickets)) { 696 spin_unlock(&space_info->lock); 697 break; 698 } 699 spin_unlock(&space_info->lock); 700 701 delalloc_bytes = percpu_counter_sum_positive( 702 &fs_info->delalloc_bytes); 703 ordered_bytes = percpu_counter_sum_positive( 704 &fs_info->ordered_bytes); 705 } 706 } 707 708 /* 709 * Try to flush some data based on policy set by @state. This is only advisory 710 * and may fail for various reasons. The caller is supposed to examine the 711 * state of @space_info to detect the outcome. 712 */ 713 static void flush_space(struct btrfs_fs_info *fs_info, 714 struct btrfs_space_info *space_info, u64 num_bytes, 715 enum btrfs_flush_state state, bool for_preempt) 716 { 717 struct btrfs_root *root = fs_info->tree_root; 718 struct btrfs_trans_handle *trans; 719 int nr; 720 int ret = 0; 721 722 switch (state) { 723 case FLUSH_DELAYED_ITEMS_NR: 724 case FLUSH_DELAYED_ITEMS: 725 if (state == FLUSH_DELAYED_ITEMS_NR) 726 nr = calc_reclaim_items_nr(fs_info, num_bytes) * 2; 727 else 728 nr = -1; 729 730 trans = btrfs_join_transaction(root); 731 if (IS_ERR(trans)) { 732 ret = PTR_ERR(trans); 733 break; 734 } 735 ret = btrfs_run_delayed_items_nr(trans, nr); 736 btrfs_end_transaction(trans); 737 break; 738 case FLUSH_DELALLOC: 739 case FLUSH_DELALLOC_WAIT: 740 case FLUSH_DELALLOC_FULL: 741 if (state == FLUSH_DELALLOC_FULL) 742 num_bytes = U64_MAX; 743 shrink_delalloc(fs_info, space_info, num_bytes, 744 state != FLUSH_DELALLOC, for_preempt); 745 break; 746 case FLUSH_DELAYED_REFS_NR: 747 case FLUSH_DELAYED_REFS: 748 trans = btrfs_join_transaction(root); 749 if (IS_ERR(trans)) { 750 ret = PTR_ERR(trans); 751 break; 752 } 753 if (state == FLUSH_DELAYED_REFS_NR) 754 nr = calc_delayed_refs_nr(fs_info, num_bytes); 755 else 756 nr = 0; 757 btrfs_run_delayed_refs(trans, nr); 758 btrfs_end_transaction(trans); 759 break; 760 case ALLOC_CHUNK: 761 case ALLOC_CHUNK_FORCE: 762 /* 763 * For metadata space on zoned filesystem, reaching here means we 764 * don't have enough space left in active_total_bytes. Try to 765 * activate a block group first, because we may have inactive 766 * block group already allocated. 767 */ 768 ret = btrfs_zoned_activate_one_bg(fs_info, space_info, false); 769 if (ret < 0) 770 break; 771 else if (ret == 1) 772 break; 773 774 trans = btrfs_join_transaction(root); 775 if (IS_ERR(trans)) { 776 ret = PTR_ERR(trans); 777 break; 778 } 779 ret = btrfs_chunk_alloc(trans, 780 btrfs_get_alloc_profile(fs_info, space_info->flags), 781 (state == ALLOC_CHUNK) ? CHUNK_ALLOC_NO_FORCE : 782 CHUNK_ALLOC_FORCE); 783 btrfs_end_transaction(trans); 784 785 /* 786 * For metadata space on zoned filesystem, allocating a new chunk 787 * is not enough. We still need to activate the block * group. 788 * Active the newly allocated block group by (maybe) finishing 789 * a block group. 790 */ 791 if (ret == 1) { 792 ret = btrfs_zoned_activate_one_bg(fs_info, space_info, true); 793 /* 794 * Revert to the original ret regardless we could finish 795 * one block group or not. 796 */ 797 if (ret >= 0) 798 ret = 1; 799 } 800 801 if (ret > 0 || ret == -ENOSPC) 802 ret = 0; 803 break; 804 case RUN_DELAYED_IPUTS: 805 /* 806 * If we have pending delayed iputs then we could free up a 807 * bunch of pinned space, so make sure we run the iputs before 808 * we do our pinned bytes check below. 809 */ 810 btrfs_run_delayed_iputs(fs_info); 811 btrfs_wait_on_delayed_iputs(fs_info); 812 break; 813 case COMMIT_TRANS: 814 ASSERT(current->journal_info == NULL); 815 trans = btrfs_join_transaction(root); 816 if (IS_ERR(trans)) { 817 ret = PTR_ERR(trans); 818 break; 819 } 820 ret = btrfs_commit_transaction(trans); 821 break; 822 default: 823 ret = -ENOSPC; 824 break; 825 } 826 827 trace_btrfs_flush_space(fs_info, space_info->flags, num_bytes, state, 828 ret, for_preempt); 829 return; 830 } 831 832 static inline u64 833 btrfs_calc_reclaim_metadata_size(struct btrfs_fs_info *fs_info, 834 struct btrfs_space_info *space_info) 835 { 836 u64 used; 837 u64 avail; 838 u64 to_reclaim = space_info->reclaim_size; 839 840 lockdep_assert_held(&space_info->lock); 841 842 avail = calc_available_free_space(fs_info, space_info, 843 BTRFS_RESERVE_FLUSH_ALL); 844 used = btrfs_space_info_used(space_info, true); 845 846 /* 847 * We may be flushing because suddenly we have less space than we had 848 * before, and now we're well over-committed based on our current free 849 * space. If that's the case add in our overage so we make sure to put 850 * appropriate pressure on the flushing state machine. 851 */ 852 if (space_info->total_bytes + avail < used) 853 to_reclaim += used - (space_info->total_bytes + avail); 854 855 return to_reclaim; 856 } 857 858 static bool need_preemptive_reclaim(struct btrfs_fs_info *fs_info, 859 struct btrfs_space_info *space_info) 860 { 861 u64 global_rsv_size = fs_info->global_block_rsv.reserved; 862 u64 ordered, delalloc; 863 u64 thresh; 864 u64 used; 865 866 thresh = mult_perc(space_info->total_bytes, 90); 867 868 lockdep_assert_held(&space_info->lock); 869 870 /* If we're just plain full then async reclaim just slows us down. */ 871 if ((space_info->bytes_used + space_info->bytes_reserved + 872 global_rsv_size) >= thresh) 873 return false; 874 875 used = space_info->bytes_may_use + space_info->bytes_pinned; 876 877 /* The total flushable belongs to the global rsv, don't flush. */ 878 if (global_rsv_size >= used) 879 return false; 880 881 /* 882 * 128MiB is 1/4 of the maximum global rsv size. If we have less than 883 * that devoted to other reservations then there's no sense in flushing, 884 * we don't have a lot of things that need flushing. 885 */ 886 if (used - global_rsv_size <= SZ_128M) 887 return false; 888 889 /* 890 * We have tickets queued, bail so we don't compete with the async 891 * flushers. 892 */ 893 if (space_info->reclaim_size) 894 return false; 895 896 /* 897 * If we have over half of the free space occupied by reservations or 898 * pinned then we want to start flushing. 899 * 900 * We do not do the traditional thing here, which is to say 901 * 902 * if (used >= ((total_bytes + avail) / 2)) 903 * return 1; 904 * 905 * because this doesn't quite work how we want. If we had more than 50% 906 * of the space_info used by bytes_used and we had 0 available we'd just 907 * constantly run the background flusher. Instead we want it to kick in 908 * if our reclaimable space exceeds our clamped free space. 909 * 910 * Our clamping range is 2^1 -> 2^8. Practically speaking that means 911 * the following: 912 * 913 * Amount of RAM Minimum threshold Maximum threshold 914 * 915 * 256GiB 1GiB 128GiB 916 * 128GiB 512MiB 64GiB 917 * 64GiB 256MiB 32GiB 918 * 32GiB 128MiB 16GiB 919 * 16GiB 64MiB 8GiB 920 * 921 * These are the range our thresholds will fall in, corresponding to how 922 * much delalloc we need for the background flusher to kick in. 923 */ 924 925 thresh = calc_available_free_space(fs_info, space_info, 926 BTRFS_RESERVE_FLUSH_ALL); 927 used = space_info->bytes_used + space_info->bytes_reserved + 928 space_info->bytes_readonly + global_rsv_size; 929 if (used < space_info->total_bytes) 930 thresh += space_info->total_bytes - used; 931 thresh >>= space_info->clamp; 932 933 used = space_info->bytes_pinned; 934 935 /* 936 * If we have more ordered bytes than delalloc bytes then we're either 937 * doing a lot of DIO, or we simply don't have a lot of delalloc waiting 938 * around. Preemptive flushing is only useful in that it can free up 939 * space before tickets need to wait for things to finish. In the case 940 * of ordered extents, preemptively waiting on ordered extents gets us 941 * nothing, if our reservations are tied up in ordered extents we'll 942 * simply have to slow down writers by forcing them to wait on ordered 943 * extents. 944 * 945 * In the case that ordered is larger than delalloc, only include the 946 * block reserves that we would actually be able to directly reclaim 947 * from. In this case if we're heavy on metadata operations this will 948 * clearly be heavy enough to warrant preemptive flushing. In the case 949 * of heavy DIO or ordered reservations, preemptive flushing will just 950 * waste time and cause us to slow down. 951 * 952 * We want to make sure we truly are maxed out on ordered however, so 953 * cut ordered in half, and if it's still higher than delalloc then we 954 * can keep flushing. This is to avoid the case where we start 955 * flushing, and now delalloc == ordered and we stop preemptively 956 * flushing when we could still have several gigs of delalloc to flush. 957 */ 958 ordered = percpu_counter_read_positive(&fs_info->ordered_bytes) >> 1; 959 delalloc = percpu_counter_read_positive(&fs_info->delalloc_bytes); 960 if (ordered >= delalloc) 961 used += fs_info->delayed_refs_rsv.reserved + 962 fs_info->delayed_block_rsv.reserved; 963 else 964 used += space_info->bytes_may_use - global_rsv_size; 965 966 return (used >= thresh && !btrfs_fs_closing(fs_info) && 967 !test_bit(BTRFS_FS_STATE_REMOUNTING, &fs_info->fs_state)); 968 } 969 970 static bool steal_from_global_rsv(struct btrfs_fs_info *fs_info, 971 struct btrfs_space_info *space_info, 972 struct reserve_ticket *ticket) 973 { 974 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv; 975 u64 min_bytes; 976 977 if (!ticket->steal) 978 return false; 979 980 if (global_rsv->space_info != space_info) 981 return false; 982 983 spin_lock(&global_rsv->lock); 984 min_bytes = mult_perc(global_rsv->size, 10); 985 if (global_rsv->reserved < min_bytes + ticket->bytes) { 986 spin_unlock(&global_rsv->lock); 987 return false; 988 } 989 global_rsv->reserved -= ticket->bytes; 990 remove_ticket(space_info, ticket); 991 ticket->bytes = 0; 992 wake_up(&ticket->wait); 993 space_info->tickets_id++; 994 if (global_rsv->reserved < global_rsv->size) 995 global_rsv->full = 0; 996 spin_unlock(&global_rsv->lock); 997 998 return true; 999 } 1000 1001 /* 1002 * maybe_fail_all_tickets - we've exhausted our flushing, start failing tickets 1003 * @fs_info - fs_info for this fs 1004 * @space_info - the space info we were flushing 1005 * 1006 * We call this when we've exhausted our flushing ability and haven't made 1007 * progress in satisfying tickets. The reservation code handles tickets in 1008 * order, so if there is a large ticket first and then smaller ones we could 1009 * very well satisfy the smaller tickets. This will attempt to wake up any 1010 * tickets in the list to catch this case. 1011 * 1012 * This function returns true if it was able to make progress by clearing out 1013 * other tickets, or if it stumbles across a ticket that was smaller than the 1014 * first ticket. 1015 */ 1016 static bool maybe_fail_all_tickets(struct btrfs_fs_info *fs_info, 1017 struct btrfs_space_info *space_info) 1018 { 1019 struct reserve_ticket *ticket; 1020 u64 tickets_id = space_info->tickets_id; 1021 const bool aborted = BTRFS_FS_ERROR(fs_info); 1022 1023 trace_btrfs_fail_all_tickets(fs_info, space_info); 1024 1025 if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) { 1026 btrfs_info(fs_info, "cannot satisfy tickets, dumping space info"); 1027 __btrfs_dump_space_info(fs_info, space_info); 1028 } 1029 1030 while (!list_empty(&space_info->tickets) && 1031 tickets_id == space_info->tickets_id) { 1032 ticket = list_first_entry(&space_info->tickets, 1033 struct reserve_ticket, list); 1034 1035 if (!aborted && steal_from_global_rsv(fs_info, space_info, ticket)) 1036 return true; 1037 1038 if (!aborted && btrfs_test_opt(fs_info, ENOSPC_DEBUG)) 1039 btrfs_info(fs_info, "failing ticket with %llu bytes", 1040 ticket->bytes); 1041 1042 remove_ticket(space_info, ticket); 1043 if (aborted) 1044 ticket->error = -EIO; 1045 else 1046 ticket->error = -ENOSPC; 1047 wake_up(&ticket->wait); 1048 1049 /* 1050 * We're just throwing tickets away, so more flushing may not 1051 * trip over btrfs_try_granting_tickets, so we need to call it 1052 * here to see if we can make progress with the next ticket in 1053 * the list. 1054 */ 1055 if (!aborted) 1056 btrfs_try_granting_tickets(fs_info, space_info); 1057 } 1058 return (tickets_id != space_info->tickets_id); 1059 } 1060 1061 /* 1062 * This is for normal flushers, we can wait all goddamned day if we want to. We 1063 * will loop and continuously try to flush as long as we are making progress. 1064 * We count progress as clearing off tickets each time we have to loop. 1065 */ 1066 static void btrfs_async_reclaim_metadata_space(struct work_struct *work) 1067 { 1068 struct btrfs_fs_info *fs_info; 1069 struct btrfs_space_info *space_info; 1070 u64 to_reclaim; 1071 enum btrfs_flush_state flush_state; 1072 int commit_cycles = 0; 1073 u64 last_tickets_id; 1074 1075 fs_info = container_of(work, struct btrfs_fs_info, async_reclaim_work); 1076 space_info = btrfs_find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA); 1077 1078 spin_lock(&space_info->lock); 1079 to_reclaim = btrfs_calc_reclaim_metadata_size(fs_info, space_info); 1080 if (!to_reclaim) { 1081 space_info->flush = 0; 1082 spin_unlock(&space_info->lock); 1083 return; 1084 } 1085 last_tickets_id = space_info->tickets_id; 1086 spin_unlock(&space_info->lock); 1087 1088 flush_state = FLUSH_DELAYED_ITEMS_NR; 1089 do { 1090 flush_space(fs_info, space_info, to_reclaim, flush_state, false); 1091 spin_lock(&space_info->lock); 1092 if (list_empty(&space_info->tickets)) { 1093 space_info->flush = 0; 1094 spin_unlock(&space_info->lock); 1095 return; 1096 } 1097 to_reclaim = btrfs_calc_reclaim_metadata_size(fs_info, 1098 space_info); 1099 if (last_tickets_id == space_info->tickets_id) { 1100 flush_state++; 1101 } else { 1102 last_tickets_id = space_info->tickets_id; 1103 flush_state = FLUSH_DELAYED_ITEMS_NR; 1104 if (commit_cycles) 1105 commit_cycles--; 1106 } 1107 1108 /* 1109 * We do not want to empty the system of delalloc unless we're 1110 * under heavy pressure, so allow one trip through the flushing 1111 * logic before we start doing a FLUSH_DELALLOC_FULL. 1112 */ 1113 if (flush_state == FLUSH_DELALLOC_FULL && !commit_cycles) 1114 flush_state++; 1115 1116 /* 1117 * We don't want to force a chunk allocation until we've tried 1118 * pretty hard to reclaim space. Think of the case where we 1119 * freed up a bunch of space and so have a lot of pinned space 1120 * to reclaim. We would rather use that than possibly create a 1121 * underutilized metadata chunk. So if this is our first run 1122 * through the flushing state machine skip ALLOC_CHUNK_FORCE and 1123 * commit the transaction. If nothing has changed the next go 1124 * around then we can force a chunk allocation. 1125 */ 1126 if (flush_state == ALLOC_CHUNK_FORCE && !commit_cycles) 1127 flush_state++; 1128 1129 if (flush_state > COMMIT_TRANS) { 1130 commit_cycles++; 1131 if (commit_cycles > 2) { 1132 if (maybe_fail_all_tickets(fs_info, space_info)) { 1133 flush_state = FLUSH_DELAYED_ITEMS_NR; 1134 commit_cycles--; 1135 } else { 1136 space_info->flush = 0; 1137 } 1138 } else { 1139 flush_state = FLUSH_DELAYED_ITEMS_NR; 1140 } 1141 } 1142 spin_unlock(&space_info->lock); 1143 } while (flush_state <= COMMIT_TRANS); 1144 } 1145 1146 /* 1147 * This handles pre-flushing of metadata space before we get to the point that 1148 * we need to start blocking threads on tickets. The logic here is different 1149 * from the other flush paths because it doesn't rely on tickets to tell us how 1150 * much we need to flush, instead it attempts to keep us below the 80% full 1151 * watermark of space by flushing whichever reservation pool is currently the 1152 * largest. 1153 */ 1154 static void btrfs_preempt_reclaim_metadata_space(struct work_struct *work) 1155 { 1156 struct btrfs_fs_info *fs_info; 1157 struct btrfs_space_info *space_info; 1158 struct btrfs_block_rsv *delayed_block_rsv; 1159 struct btrfs_block_rsv *delayed_refs_rsv; 1160 struct btrfs_block_rsv *global_rsv; 1161 struct btrfs_block_rsv *trans_rsv; 1162 int loops = 0; 1163 1164 fs_info = container_of(work, struct btrfs_fs_info, 1165 preempt_reclaim_work); 1166 space_info = btrfs_find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA); 1167 delayed_block_rsv = &fs_info->delayed_block_rsv; 1168 delayed_refs_rsv = &fs_info->delayed_refs_rsv; 1169 global_rsv = &fs_info->global_block_rsv; 1170 trans_rsv = &fs_info->trans_block_rsv; 1171 1172 spin_lock(&space_info->lock); 1173 while (need_preemptive_reclaim(fs_info, space_info)) { 1174 enum btrfs_flush_state flush; 1175 u64 delalloc_size = 0; 1176 u64 to_reclaim, block_rsv_size; 1177 u64 global_rsv_size = global_rsv->reserved; 1178 1179 loops++; 1180 1181 /* 1182 * We don't have a precise counter for the metadata being 1183 * reserved for delalloc, so we'll approximate it by subtracting 1184 * out the block rsv's space from the bytes_may_use. If that 1185 * amount is higher than the individual reserves, then we can 1186 * assume it's tied up in delalloc reservations. 1187 */ 1188 block_rsv_size = global_rsv_size + 1189 delayed_block_rsv->reserved + 1190 delayed_refs_rsv->reserved + 1191 trans_rsv->reserved; 1192 if (block_rsv_size < space_info->bytes_may_use) 1193 delalloc_size = space_info->bytes_may_use - block_rsv_size; 1194 1195 /* 1196 * We don't want to include the global_rsv in our calculation, 1197 * because that's space we can't touch. Subtract it from the 1198 * block_rsv_size for the next checks. 1199 */ 1200 block_rsv_size -= global_rsv_size; 1201 1202 /* 1203 * We really want to avoid flushing delalloc too much, as it 1204 * could result in poor allocation patterns, so only flush it if 1205 * it's larger than the rest of the pools combined. 1206 */ 1207 if (delalloc_size > block_rsv_size) { 1208 to_reclaim = delalloc_size; 1209 flush = FLUSH_DELALLOC; 1210 } else if (space_info->bytes_pinned > 1211 (delayed_block_rsv->reserved + 1212 delayed_refs_rsv->reserved)) { 1213 to_reclaim = space_info->bytes_pinned; 1214 flush = COMMIT_TRANS; 1215 } else if (delayed_block_rsv->reserved > 1216 delayed_refs_rsv->reserved) { 1217 to_reclaim = delayed_block_rsv->reserved; 1218 flush = FLUSH_DELAYED_ITEMS_NR; 1219 } else { 1220 to_reclaim = delayed_refs_rsv->reserved; 1221 flush = FLUSH_DELAYED_REFS_NR; 1222 } 1223 1224 spin_unlock(&space_info->lock); 1225 1226 /* 1227 * We don't want to reclaim everything, just a portion, so scale 1228 * down the to_reclaim by 1/4. If it takes us down to 0, 1229 * reclaim 1 items worth. 1230 */ 1231 to_reclaim >>= 2; 1232 if (!to_reclaim) 1233 to_reclaim = btrfs_calc_insert_metadata_size(fs_info, 1); 1234 flush_space(fs_info, space_info, to_reclaim, flush, true); 1235 cond_resched(); 1236 spin_lock(&space_info->lock); 1237 } 1238 1239 /* We only went through once, back off our clamping. */ 1240 if (loops == 1 && !space_info->reclaim_size) 1241 space_info->clamp = max(1, space_info->clamp - 1); 1242 trace_btrfs_done_preemptive_reclaim(fs_info, space_info); 1243 spin_unlock(&space_info->lock); 1244 } 1245 1246 /* 1247 * FLUSH_DELALLOC_WAIT: 1248 * Space is freed from flushing delalloc in one of two ways. 1249 * 1250 * 1) compression is on and we allocate less space than we reserved 1251 * 2) we are overwriting existing space 1252 * 1253 * For #1 that extra space is reclaimed as soon as the delalloc pages are 1254 * COWed, by way of btrfs_add_reserved_bytes() which adds the actual extent 1255 * length to ->bytes_reserved, and subtracts the reserved space from 1256 * ->bytes_may_use. 1257 * 1258 * For #2 this is trickier. Once the ordered extent runs we will drop the 1259 * extent in the range we are overwriting, which creates a delayed ref for 1260 * that freed extent. This however is not reclaimed until the transaction 1261 * commits, thus the next stages. 1262 * 1263 * RUN_DELAYED_IPUTS 1264 * If we are freeing inodes, we want to make sure all delayed iputs have 1265 * completed, because they could have been on an inode with i_nlink == 0, and 1266 * thus have been truncated and freed up space. But again this space is not 1267 * immediately re-usable, it comes in the form of a delayed ref, which must be 1268 * run and then the transaction must be committed. 1269 * 1270 * COMMIT_TRANS 1271 * This is where we reclaim all of the pinned space generated by running the 1272 * iputs 1273 * 1274 * ALLOC_CHUNK_FORCE 1275 * For data we start with alloc chunk force, however we could have been full 1276 * before, and then the transaction commit could have freed new block groups, 1277 * so if we now have space to allocate do the force chunk allocation. 1278 */ 1279 static const enum btrfs_flush_state data_flush_states[] = { 1280 FLUSH_DELALLOC_FULL, 1281 RUN_DELAYED_IPUTS, 1282 COMMIT_TRANS, 1283 ALLOC_CHUNK_FORCE, 1284 }; 1285 1286 static void btrfs_async_reclaim_data_space(struct work_struct *work) 1287 { 1288 struct btrfs_fs_info *fs_info; 1289 struct btrfs_space_info *space_info; 1290 u64 last_tickets_id; 1291 enum btrfs_flush_state flush_state = 0; 1292 1293 fs_info = container_of(work, struct btrfs_fs_info, async_data_reclaim_work); 1294 space_info = fs_info->data_sinfo; 1295 1296 spin_lock(&space_info->lock); 1297 if (list_empty(&space_info->tickets)) { 1298 space_info->flush = 0; 1299 spin_unlock(&space_info->lock); 1300 return; 1301 } 1302 last_tickets_id = space_info->tickets_id; 1303 spin_unlock(&space_info->lock); 1304 1305 while (!space_info->full) { 1306 flush_space(fs_info, space_info, U64_MAX, ALLOC_CHUNK_FORCE, false); 1307 spin_lock(&space_info->lock); 1308 if (list_empty(&space_info->tickets)) { 1309 space_info->flush = 0; 1310 spin_unlock(&space_info->lock); 1311 return; 1312 } 1313 1314 /* Something happened, fail everything and bail. */ 1315 if (BTRFS_FS_ERROR(fs_info)) 1316 goto aborted_fs; 1317 last_tickets_id = space_info->tickets_id; 1318 spin_unlock(&space_info->lock); 1319 } 1320 1321 while (flush_state < ARRAY_SIZE(data_flush_states)) { 1322 flush_space(fs_info, space_info, U64_MAX, 1323 data_flush_states[flush_state], false); 1324 spin_lock(&space_info->lock); 1325 if (list_empty(&space_info->tickets)) { 1326 space_info->flush = 0; 1327 spin_unlock(&space_info->lock); 1328 return; 1329 } 1330 1331 if (last_tickets_id == space_info->tickets_id) { 1332 flush_state++; 1333 } else { 1334 last_tickets_id = space_info->tickets_id; 1335 flush_state = 0; 1336 } 1337 1338 if (flush_state >= ARRAY_SIZE(data_flush_states)) { 1339 if (space_info->full) { 1340 if (maybe_fail_all_tickets(fs_info, space_info)) 1341 flush_state = 0; 1342 else 1343 space_info->flush = 0; 1344 } else { 1345 flush_state = 0; 1346 } 1347 1348 /* Something happened, fail everything and bail. */ 1349 if (BTRFS_FS_ERROR(fs_info)) 1350 goto aborted_fs; 1351 1352 } 1353 spin_unlock(&space_info->lock); 1354 } 1355 return; 1356 1357 aborted_fs: 1358 maybe_fail_all_tickets(fs_info, space_info); 1359 space_info->flush = 0; 1360 spin_unlock(&space_info->lock); 1361 } 1362 1363 void btrfs_init_async_reclaim_work(struct btrfs_fs_info *fs_info) 1364 { 1365 INIT_WORK(&fs_info->async_reclaim_work, btrfs_async_reclaim_metadata_space); 1366 INIT_WORK(&fs_info->async_data_reclaim_work, btrfs_async_reclaim_data_space); 1367 INIT_WORK(&fs_info->preempt_reclaim_work, 1368 btrfs_preempt_reclaim_metadata_space); 1369 } 1370 1371 static const enum btrfs_flush_state priority_flush_states[] = { 1372 FLUSH_DELAYED_ITEMS_NR, 1373 FLUSH_DELAYED_ITEMS, 1374 ALLOC_CHUNK, 1375 }; 1376 1377 static const enum btrfs_flush_state evict_flush_states[] = { 1378 FLUSH_DELAYED_ITEMS_NR, 1379 FLUSH_DELAYED_ITEMS, 1380 FLUSH_DELAYED_REFS_NR, 1381 FLUSH_DELAYED_REFS, 1382 FLUSH_DELALLOC, 1383 FLUSH_DELALLOC_WAIT, 1384 FLUSH_DELALLOC_FULL, 1385 ALLOC_CHUNK, 1386 COMMIT_TRANS, 1387 }; 1388 1389 static void priority_reclaim_metadata_space(struct btrfs_fs_info *fs_info, 1390 struct btrfs_space_info *space_info, 1391 struct reserve_ticket *ticket, 1392 const enum btrfs_flush_state *states, 1393 int states_nr) 1394 { 1395 u64 to_reclaim; 1396 int flush_state = 0; 1397 1398 spin_lock(&space_info->lock); 1399 to_reclaim = btrfs_calc_reclaim_metadata_size(fs_info, space_info); 1400 /* 1401 * This is the priority reclaim path, so to_reclaim could be >0 still 1402 * because we may have only satisfied the priority tickets and still 1403 * left non priority tickets on the list. We would then have 1404 * to_reclaim but ->bytes == 0. 1405 */ 1406 if (ticket->bytes == 0) { 1407 spin_unlock(&space_info->lock); 1408 return; 1409 } 1410 1411 while (flush_state < states_nr) { 1412 spin_unlock(&space_info->lock); 1413 flush_space(fs_info, space_info, to_reclaim, states[flush_state], 1414 false); 1415 flush_state++; 1416 spin_lock(&space_info->lock); 1417 if (ticket->bytes == 0) { 1418 spin_unlock(&space_info->lock); 1419 return; 1420 } 1421 } 1422 1423 /* Attempt to steal from the global rsv if we can. */ 1424 if (!steal_from_global_rsv(fs_info, space_info, ticket)) { 1425 ticket->error = -ENOSPC; 1426 remove_ticket(space_info, ticket); 1427 } 1428 1429 /* 1430 * We must run try_granting_tickets here because we could be a large 1431 * ticket in front of a smaller ticket that can now be satisfied with 1432 * the available space. 1433 */ 1434 btrfs_try_granting_tickets(fs_info, space_info); 1435 spin_unlock(&space_info->lock); 1436 } 1437 1438 static void priority_reclaim_data_space(struct btrfs_fs_info *fs_info, 1439 struct btrfs_space_info *space_info, 1440 struct reserve_ticket *ticket) 1441 { 1442 spin_lock(&space_info->lock); 1443 1444 /* We could have been granted before we got here. */ 1445 if (ticket->bytes == 0) { 1446 spin_unlock(&space_info->lock); 1447 return; 1448 } 1449 1450 while (!space_info->full) { 1451 spin_unlock(&space_info->lock); 1452 flush_space(fs_info, space_info, U64_MAX, ALLOC_CHUNK_FORCE, false); 1453 spin_lock(&space_info->lock); 1454 if (ticket->bytes == 0) { 1455 spin_unlock(&space_info->lock); 1456 return; 1457 } 1458 } 1459 1460 ticket->error = -ENOSPC; 1461 remove_ticket(space_info, ticket); 1462 btrfs_try_granting_tickets(fs_info, space_info); 1463 spin_unlock(&space_info->lock); 1464 } 1465 1466 static void wait_reserve_ticket(struct btrfs_fs_info *fs_info, 1467 struct btrfs_space_info *space_info, 1468 struct reserve_ticket *ticket) 1469 1470 { 1471 DEFINE_WAIT(wait); 1472 int ret = 0; 1473 1474 spin_lock(&space_info->lock); 1475 while (ticket->bytes > 0 && ticket->error == 0) { 1476 ret = prepare_to_wait_event(&ticket->wait, &wait, TASK_KILLABLE); 1477 if (ret) { 1478 /* 1479 * Delete us from the list. After we unlock the space 1480 * info, we don't want the async reclaim job to reserve 1481 * space for this ticket. If that would happen, then the 1482 * ticket's task would not known that space was reserved 1483 * despite getting an error, resulting in a space leak 1484 * (bytes_may_use counter of our space_info). 1485 */ 1486 remove_ticket(space_info, ticket); 1487 ticket->error = -EINTR; 1488 break; 1489 } 1490 spin_unlock(&space_info->lock); 1491 1492 schedule(); 1493 1494 finish_wait(&ticket->wait, &wait); 1495 spin_lock(&space_info->lock); 1496 } 1497 spin_unlock(&space_info->lock); 1498 } 1499 1500 /* 1501 * Do the appropriate flushing and waiting for a ticket. 1502 * 1503 * @fs_info: the filesystem 1504 * @space_info: space info for the reservation 1505 * @ticket: ticket for the reservation 1506 * @start_ns: timestamp when the reservation started 1507 * @orig_bytes: amount of bytes originally reserved 1508 * @flush: how much we can flush 1509 * 1510 * This does the work of figuring out how to flush for the ticket, waiting for 1511 * the reservation, and returning the appropriate error if there is one. 1512 */ 1513 static int handle_reserve_ticket(struct btrfs_fs_info *fs_info, 1514 struct btrfs_space_info *space_info, 1515 struct reserve_ticket *ticket, 1516 u64 start_ns, u64 orig_bytes, 1517 enum btrfs_reserve_flush_enum flush) 1518 { 1519 int ret; 1520 1521 switch (flush) { 1522 case BTRFS_RESERVE_FLUSH_DATA: 1523 case BTRFS_RESERVE_FLUSH_ALL: 1524 case BTRFS_RESERVE_FLUSH_ALL_STEAL: 1525 wait_reserve_ticket(fs_info, space_info, ticket); 1526 break; 1527 case BTRFS_RESERVE_FLUSH_LIMIT: 1528 priority_reclaim_metadata_space(fs_info, space_info, ticket, 1529 priority_flush_states, 1530 ARRAY_SIZE(priority_flush_states)); 1531 break; 1532 case BTRFS_RESERVE_FLUSH_EVICT: 1533 priority_reclaim_metadata_space(fs_info, space_info, ticket, 1534 evict_flush_states, 1535 ARRAY_SIZE(evict_flush_states)); 1536 break; 1537 case BTRFS_RESERVE_FLUSH_FREE_SPACE_INODE: 1538 priority_reclaim_data_space(fs_info, space_info, ticket); 1539 break; 1540 default: 1541 ASSERT(0); 1542 break; 1543 } 1544 1545 ret = ticket->error; 1546 ASSERT(list_empty(&ticket->list)); 1547 /* 1548 * Check that we can't have an error set if the reservation succeeded, 1549 * as that would confuse tasks and lead them to error out without 1550 * releasing reserved space (if an error happens the expectation is that 1551 * space wasn't reserved at all). 1552 */ 1553 ASSERT(!(ticket->bytes == 0 && ticket->error)); 1554 trace_btrfs_reserve_ticket(fs_info, space_info->flags, orig_bytes, 1555 start_ns, flush, ticket->error); 1556 return ret; 1557 } 1558 1559 /* 1560 * This returns true if this flush state will go through the ordinary flushing 1561 * code. 1562 */ 1563 static inline bool is_normal_flushing(enum btrfs_reserve_flush_enum flush) 1564 { 1565 return (flush == BTRFS_RESERVE_FLUSH_ALL) || 1566 (flush == BTRFS_RESERVE_FLUSH_ALL_STEAL); 1567 } 1568 1569 static inline void maybe_clamp_preempt(struct btrfs_fs_info *fs_info, 1570 struct btrfs_space_info *space_info) 1571 { 1572 u64 ordered = percpu_counter_sum_positive(&fs_info->ordered_bytes); 1573 u64 delalloc = percpu_counter_sum_positive(&fs_info->delalloc_bytes); 1574 1575 /* 1576 * If we're heavy on ordered operations then clamping won't help us. We 1577 * need to clamp specifically to keep up with dirty'ing buffered 1578 * writers, because there's not a 1:1 correlation of writing delalloc 1579 * and freeing space, like there is with flushing delayed refs or 1580 * delayed nodes. If we're already more ordered than delalloc then 1581 * we're keeping up, otherwise we aren't and should probably clamp. 1582 */ 1583 if (ordered < delalloc) 1584 space_info->clamp = min(space_info->clamp + 1, 8); 1585 } 1586 1587 static inline bool can_steal(enum btrfs_reserve_flush_enum flush) 1588 { 1589 return (flush == BTRFS_RESERVE_FLUSH_ALL_STEAL || 1590 flush == BTRFS_RESERVE_FLUSH_EVICT); 1591 } 1592 1593 /* 1594 * NO_FLUSH and FLUSH_EMERGENCY don't want to create a ticket, they just want to 1595 * fail as quickly as possible. 1596 */ 1597 static inline bool can_ticket(enum btrfs_reserve_flush_enum flush) 1598 { 1599 return (flush != BTRFS_RESERVE_NO_FLUSH && 1600 flush != BTRFS_RESERVE_FLUSH_EMERGENCY); 1601 } 1602 1603 /* 1604 * Try to reserve bytes from the block_rsv's space. 1605 * 1606 * @fs_info: the filesystem 1607 * @space_info: space info we want to allocate from 1608 * @orig_bytes: number of bytes we want 1609 * @flush: whether or not we can flush to make our reservation 1610 * 1611 * This will reserve orig_bytes number of bytes from the space info associated 1612 * with the block_rsv. If there is not enough space it will make an attempt to 1613 * flush out space to make room. It will do this by flushing delalloc if 1614 * possible or committing the transaction. If flush is 0 then no attempts to 1615 * regain reservations will be made and this will fail if there is not enough 1616 * space already. 1617 */ 1618 static int __reserve_bytes(struct btrfs_fs_info *fs_info, 1619 struct btrfs_space_info *space_info, u64 orig_bytes, 1620 enum btrfs_reserve_flush_enum flush) 1621 { 1622 struct work_struct *async_work; 1623 struct reserve_ticket ticket; 1624 u64 start_ns = 0; 1625 u64 used; 1626 int ret = -ENOSPC; 1627 bool pending_tickets; 1628 1629 ASSERT(orig_bytes); 1630 /* 1631 * If have a transaction handle (current->journal_info != NULL), then 1632 * the flush method can not be neither BTRFS_RESERVE_FLUSH_ALL* nor 1633 * BTRFS_RESERVE_FLUSH_EVICT, as we could deadlock because those 1634 * flushing methods can trigger transaction commits. 1635 */ 1636 if (current->journal_info) { 1637 /* One assert per line for easier debugging. */ 1638 ASSERT(flush != BTRFS_RESERVE_FLUSH_ALL); 1639 ASSERT(flush != BTRFS_RESERVE_FLUSH_ALL_STEAL); 1640 ASSERT(flush != BTRFS_RESERVE_FLUSH_EVICT); 1641 } 1642 1643 if (flush == BTRFS_RESERVE_FLUSH_DATA) 1644 async_work = &fs_info->async_data_reclaim_work; 1645 else 1646 async_work = &fs_info->async_reclaim_work; 1647 1648 spin_lock(&space_info->lock); 1649 used = btrfs_space_info_used(space_info, true); 1650 1651 /* 1652 * We don't want NO_FLUSH allocations to jump everybody, they can 1653 * generally handle ENOSPC in a different way, so treat them the same as 1654 * normal flushers when it comes to skipping pending tickets. 1655 */ 1656 if (is_normal_flushing(flush) || (flush == BTRFS_RESERVE_NO_FLUSH)) 1657 pending_tickets = !list_empty(&space_info->tickets) || 1658 !list_empty(&space_info->priority_tickets); 1659 else 1660 pending_tickets = !list_empty(&space_info->priority_tickets); 1661 1662 /* 1663 * Carry on if we have enough space (short-circuit) OR call 1664 * can_overcommit() to ensure we can overcommit to continue. 1665 */ 1666 if (!pending_tickets && 1667 ((used + orig_bytes <= space_info->total_bytes) || 1668 btrfs_can_overcommit(fs_info, space_info, orig_bytes, flush))) { 1669 btrfs_space_info_update_bytes_may_use(fs_info, space_info, 1670 orig_bytes); 1671 ret = 0; 1672 } 1673 1674 /* 1675 * Things are dire, we need to make a reservation so we don't abort. We 1676 * will let this reservation go through as long as we have actual space 1677 * left to allocate for the block. 1678 */ 1679 if (ret && unlikely(flush == BTRFS_RESERVE_FLUSH_EMERGENCY)) { 1680 used = btrfs_space_info_used(space_info, false); 1681 if (used + orig_bytes <= space_info->total_bytes) { 1682 btrfs_space_info_update_bytes_may_use(fs_info, space_info, 1683 orig_bytes); 1684 ret = 0; 1685 } 1686 } 1687 1688 /* 1689 * If we couldn't make a reservation then setup our reservation ticket 1690 * and kick the async worker if it's not already running. 1691 * 1692 * If we are a priority flusher then we just need to add our ticket to 1693 * the list and we will do our own flushing further down. 1694 */ 1695 if (ret && can_ticket(flush)) { 1696 ticket.bytes = orig_bytes; 1697 ticket.error = 0; 1698 space_info->reclaim_size += ticket.bytes; 1699 init_waitqueue_head(&ticket.wait); 1700 ticket.steal = can_steal(flush); 1701 if (trace_btrfs_reserve_ticket_enabled()) 1702 start_ns = ktime_get_ns(); 1703 1704 if (flush == BTRFS_RESERVE_FLUSH_ALL || 1705 flush == BTRFS_RESERVE_FLUSH_ALL_STEAL || 1706 flush == BTRFS_RESERVE_FLUSH_DATA) { 1707 list_add_tail(&ticket.list, &space_info->tickets); 1708 if (!space_info->flush) { 1709 /* 1710 * We were forced to add a reserve ticket, so 1711 * our preemptive flushing is unable to keep 1712 * up. Clamp down on the threshold for the 1713 * preemptive flushing in order to keep up with 1714 * the workload. 1715 */ 1716 maybe_clamp_preempt(fs_info, space_info); 1717 1718 space_info->flush = 1; 1719 trace_btrfs_trigger_flush(fs_info, 1720 space_info->flags, 1721 orig_bytes, flush, 1722 "enospc"); 1723 queue_work(system_unbound_wq, async_work); 1724 } 1725 } else { 1726 list_add_tail(&ticket.list, 1727 &space_info->priority_tickets); 1728 } 1729 } else if (!ret && space_info->flags & BTRFS_BLOCK_GROUP_METADATA) { 1730 /* 1731 * We will do the space reservation dance during log replay, 1732 * which means we won't have fs_info->fs_root set, so don't do 1733 * the async reclaim as we will panic. 1734 */ 1735 if (!test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags) && 1736 !work_busy(&fs_info->preempt_reclaim_work) && 1737 need_preemptive_reclaim(fs_info, space_info)) { 1738 trace_btrfs_trigger_flush(fs_info, space_info->flags, 1739 orig_bytes, flush, "preempt"); 1740 queue_work(system_unbound_wq, 1741 &fs_info->preempt_reclaim_work); 1742 } 1743 } 1744 spin_unlock(&space_info->lock); 1745 if (!ret || !can_ticket(flush)) 1746 return ret; 1747 1748 return handle_reserve_ticket(fs_info, space_info, &ticket, start_ns, 1749 orig_bytes, flush); 1750 } 1751 1752 /* 1753 * Try to reserve metadata bytes from the block_rsv's space. 1754 * 1755 * @fs_info: the filesystem 1756 * @block_rsv: block_rsv we're allocating for 1757 * @orig_bytes: number of bytes we want 1758 * @flush: whether or not we can flush to make our reservation 1759 * 1760 * This will reserve orig_bytes number of bytes from the space info associated 1761 * with the block_rsv. If there is not enough space it will make an attempt to 1762 * flush out space to make room. It will do this by flushing delalloc if 1763 * possible or committing the transaction. If flush is 0 then no attempts to 1764 * regain reservations will be made and this will fail if there is not enough 1765 * space already. 1766 */ 1767 int btrfs_reserve_metadata_bytes(struct btrfs_fs_info *fs_info, 1768 struct btrfs_block_rsv *block_rsv, 1769 u64 orig_bytes, 1770 enum btrfs_reserve_flush_enum flush) 1771 { 1772 int ret; 1773 1774 ret = __reserve_bytes(fs_info, block_rsv->space_info, orig_bytes, flush); 1775 if (ret == -ENOSPC) { 1776 trace_btrfs_space_reservation(fs_info, "space_info:enospc", 1777 block_rsv->space_info->flags, 1778 orig_bytes, 1); 1779 1780 if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) 1781 btrfs_dump_space_info(fs_info, block_rsv->space_info, 1782 orig_bytes, 0); 1783 } 1784 return ret; 1785 } 1786 1787 /* 1788 * Try to reserve data bytes for an allocation. 1789 * 1790 * @fs_info: the filesystem 1791 * @bytes: number of bytes we need 1792 * @flush: how we are allowed to flush 1793 * 1794 * This will reserve bytes from the data space info. If there is not enough 1795 * space then we will attempt to flush space as specified by flush. 1796 */ 1797 int btrfs_reserve_data_bytes(struct btrfs_fs_info *fs_info, u64 bytes, 1798 enum btrfs_reserve_flush_enum flush) 1799 { 1800 struct btrfs_space_info *data_sinfo = fs_info->data_sinfo; 1801 int ret; 1802 1803 ASSERT(flush == BTRFS_RESERVE_FLUSH_DATA || 1804 flush == BTRFS_RESERVE_FLUSH_FREE_SPACE_INODE || 1805 flush == BTRFS_RESERVE_NO_FLUSH); 1806 ASSERT(!current->journal_info || flush != BTRFS_RESERVE_FLUSH_DATA); 1807 1808 ret = __reserve_bytes(fs_info, data_sinfo, bytes, flush); 1809 if (ret == -ENOSPC) { 1810 trace_btrfs_space_reservation(fs_info, "space_info:enospc", 1811 data_sinfo->flags, bytes, 1); 1812 if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) 1813 btrfs_dump_space_info(fs_info, data_sinfo, bytes, 0); 1814 } 1815 return ret; 1816 } 1817 1818 /* Dump all the space infos when we abort a transaction due to ENOSPC. */ 1819 __cold void btrfs_dump_space_info_for_trans_abort(struct btrfs_fs_info *fs_info) 1820 { 1821 struct btrfs_space_info *space_info; 1822 1823 btrfs_info(fs_info, "dumping space info:"); 1824 list_for_each_entry(space_info, &fs_info->space_info, list) { 1825 spin_lock(&space_info->lock); 1826 __btrfs_dump_space_info(fs_info, space_info); 1827 spin_unlock(&space_info->lock); 1828 } 1829 dump_global_block_rsv(fs_info); 1830 } 1831 1832 /* 1833 * Account the unused space of all the readonly block group in the space_info. 1834 * takes mirrors into account. 1835 */ 1836 u64 btrfs_account_ro_block_groups_free_space(struct btrfs_space_info *sinfo) 1837 { 1838 struct btrfs_block_group *block_group; 1839 u64 free_bytes = 0; 1840 int factor; 1841 1842 /* It's df, we don't care if it's racy */ 1843 if (list_empty(&sinfo->ro_bgs)) 1844 return 0; 1845 1846 spin_lock(&sinfo->lock); 1847 list_for_each_entry(block_group, &sinfo->ro_bgs, ro_list) { 1848 spin_lock(&block_group->lock); 1849 1850 if (!block_group->ro) { 1851 spin_unlock(&block_group->lock); 1852 continue; 1853 } 1854 1855 factor = btrfs_bg_type_to_factor(block_group->flags); 1856 free_bytes += (block_group->length - 1857 block_group->used) * factor; 1858 1859 spin_unlock(&block_group->lock); 1860 } 1861 spin_unlock(&sinfo->lock); 1862 1863 return free_bytes; 1864 } 1865