1 // SPDX-License-Identifier: GPL-2.0 2 /* 3 * Copyright (C) 2008 Red Hat. All rights reserved. 4 */ 5 6 #include <linux/pagemap.h> 7 #include <linux/sched.h> 8 #include <linux/sched/signal.h> 9 #include <linux/slab.h> 10 #include <linux/math64.h> 11 #include <linux/ratelimit.h> 12 #include <linux/error-injection.h> 13 #include <linux/sched/mm.h> 14 #include <linux/string_choices.h> 15 #include "extent-tree.h" 16 #include "fs.h" 17 #include "messages.h" 18 #include "misc.h" 19 #include "free-space-cache.h" 20 #include "transaction.h" 21 #include "disk-io.h" 22 #include "extent_io.h" 23 #include "space-info.h" 24 #include "block-group.h" 25 #include "discard.h" 26 #include "subpage.h" 27 #include "inode-item.h" 28 #include "accessors.h" 29 #include "file-item.h" 30 #include "file.h" 31 #include "super.h" 32 #include "relocation.h" 33 34 #define BITS_PER_BITMAP (PAGE_SIZE * 8UL) 35 #define MAX_CACHE_BYTES_PER_GIG SZ_64K 36 #define FORCE_EXTENT_THRESHOLD SZ_1M 37 38 static struct kmem_cache *btrfs_free_space_cachep; 39 static struct kmem_cache *btrfs_free_space_bitmap_cachep; 40 41 struct btrfs_trim_range { 42 u64 start; 43 u64 bytes; 44 struct list_head list; 45 }; 46 47 static int link_free_space(struct btrfs_free_space_ctl *ctl, 48 struct btrfs_free_space *info); 49 static void unlink_free_space(struct btrfs_free_space_ctl *ctl, 50 struct btrfs_free_space *info, bool update_stat); 51 static int search_bitmap(struct btrfs_free_space_ctl *ctl, 52 struct btrfs_free_space *bitmap_info, u64 *offset, 53 u64 *bytes, bool for_alloc); 54 static void free_bitmap(struct btrfs_free_space_ctl *ctl, 55 struct btrfs_free_space *bitmap_info); 56 static void bitmap_clear_bits(struct btrfs_free_space_ctl *ctl, 57 struct btrfs_free_space *info, u64 offset, 58 u64 bytes, bool update_stats); 59 60 static void btrfs_crc32c_final(u32 crc, u8 *result) 61 { 62 put_unaligned_le32(~crc, result); 63 } 64 65 static void __btrfs_remove_free_space_cache(struct btrfs_free_space_ctl *ctl) 66 { 67 struct btrfs_free_space *info; 68 struct rb_node *node; 69 70 while ((node = rb_last(&ctl->free_space_offset)) != NULL) { 71 info = rb_entry(node, struct btrfs_free_space, offset_index); 72 if (!info->bitmap) { 73 unlink_free_space(ctl, info, true); 74 kmem_cache_free(btrfs_free_space_cachep, info); 75 } else { 76 free_bitmap(ctl, info); 77 } 78 79 cond_resched_lock(&ctl->tree_lock); 80 } 81 } 82 83 static struct inode *__lookup_free_space_inode(struct btrfs_root *root, 84 struct btrfs_path *path, 85 u64 offset) 86 { 87 struct btrfs_key key; 88 struct btrfs_key location; 89 struct btrfs_disk_key disk_key; 90 struct btrfs_free_space_header *header; 91 struct extent_buffer *leaf; 92 struct btrfs_inode *inode; 93 unsigned nofs_flag; 94 int ret; 95 96 key.objectid = BTRFS_FREE_SPACE_OBJECTID; 97 key.type = 0; 98 key.offset = offset; 99 100 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0); 101 if (ret < 0) 102 return ERR_PTR(ret); 103 if (ret > 0) { 104 btrfs_release_path(path); 105 return ERR_PTR(-ENOENT); 106 } 107 108 leaf = path->nodes[0]; 109 header = btrfs_item_ptr(leaf, path->slots[0], 110 struct btrfs_free_space_header); 111 btrfs_free_space_key(leaf, header, &disk_key); 112 btrfs_disk_key_to_cpu(&location, &disk_key); 113 btrfs_release_path(path); 114 115 /* 116 * We are often under a trans handle at this point, so we need to make 117 * sure NOFS is set to keep us from deadlocking. 118 */ 119 nofs_flag = memalloc_nofs_save(); 120 inode = btrfs_iget_path(location.objectid, root, path); 121 btrfs_release_path(path); 122 memalloc_nofs_restore(nofs_flag); 123 if (IS_ERR(inode)) 124 return ERR_CAST(inode); 125 126 mapping_set_gfp_mask(inode->vfs_inode.i_mapping, 127 mapping_gfp_constraint(inode->vfs_inode.i_mapping, 128 ~(__GFP_FS | __GFP_HIGHMEM))); 129 130 return &inode->vfs_inode; 131 } 132 133 struct inode *lookup_free_space_inode(struct btrfs_block_group *block_group, 134 struct btrfs_path *path) 135 { 136 struct btrfs_fs_info *fs_info = block_group->fs_info; 137 struct inode *inode = NULL; 138 u32 flags = BTRFS_INODE_NODATASUM | BTRFS_INODE_NODATACOW; 139 140 spin_lock(&block_group->lock); 141 if (block_group->inode) 142 inode = igrab(&block_group->inode->vfs_inode); 143 spin_unlock(&block_group->lock); 144 if (inode) 145 return inode; 146 147 inode = __lookup_free_space_inode(fs_info->tree_root, path, 148 block_group->start); 149 if (IS_ERR(inode)) 150 return inode; 151 152 spin_lock(&block_group->lock); 153 if (!((BTRFS_I(inode)->flags & flags) == flags)) { 154 btrfs_info(fs_info, "Old style space inode found, converting."); 155 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM | 156 BTRFS_INODE_NODATACOW; 157 block_group->disk_cache_state = BTRFS_DC_CLEAR; 158 } 159 160 if (!test_and_set_bit(BLOCK_GROUP_FLAG_IREF, &block_group->runtime_flags)) 161 block_group->inode = BTRFS_I(igrab(inode)); 162 spin_unlock(&block_group->lock); 163 164 return inode; 165 } 166 167 static int __create_free_space_inode(struct btrfs_root *root, 168 struct btrfs_trans_handle *trans, 169 struct btrfs_path *path, 170 u64 ino, u64 offset) 171 { 172 struct btrfs_key key; 173 struct btrfs_disk_key disk_key; 174 struct btrfs_free_space_header *header; 175 struct btrfs_inode_item *inode_item; 176 struct extent_buffer *leaf; 177 /* We inline CRCs for the free disk space cache */ 178 const u64 flags = BTRFS_INODE_NOCOMPRESS | BTRFS_INODE_PREALLOC | 179 BTRFS_INODE_NODATASUM | BTRFS_INODE_NODATACOW; 180 int ret; 181 182 ret = btrfs_insert_empty_inode(trans, root, path, ino); 183 if (ret) 184 return ret; 185 186 leaf = path->nodes[0]; 187 inode_item = btrfs_item_ptr(leaf, path->slots[0], 188 struct btrfs_inode_item); 189 btrfs_item_key(leaf, &disk_key, path->slots[0]); 190 memzero_extent_buffer(leaf, (unsigned long)inode_item, 191 sizeof(*inode_item)); 192 btrfs_set_inode_generation(leaf, inode_item, trans->transid); 193 btrfs_set_inode_size(leaf, inode_item, 0); 194 btrfs_set_inode_nbytes(leaf, inode_item, 0); 195 btrfs_set_inode_uid(leaf, inode_item, 0); 196 btrfs_set_inode_gid(leaf, inode_item, 0); 197 btrfs_set_inode_mode(leaf, inode_item, S_IFREG | 0600); 198 btrfs_set_inode_flags(leaf, inode_item, flags); 199 btrfs_set_inode_nlink(leaf, inode_item, 1); 200 btrfs_set_inode_transid(leaf, inode_item, trans->transid); 201 btrfs_set_inode_block_group(leaf, inode_item, offset); 202 btrfs_release_path(path); 203 204 key.objectid = BTRFS_FREE_SPACE_OBJECTID; 205 key.type = 0; 206 key.offset = offset; 207 ret = btrfs_insert_empty_item(trans, root, path, &key, 208 sizeof(struct btrfs_free_space_header)); 209 if (ret < 0) { 210 btrfs_release_path(path); 211 return ret; 212 } 213 214 leaf = path->nodes[0]; 215 header = btrfs_item_ptr(leaf, path->slots[0], 216 struct btrfs_free_space_header); 217 memzero_extent_buffer(leaf, (unsigned long)header, sizeof(*header)); 218 btrfs_set_free_space_key(leaf, header, &disk_key); 219 btrfs_release_path(path); 220 221 return 0; 222 } 223 224 int create_free_space_inode(struct btrfs_trans_handle *trans, 225 struct btrfs_block_group *block_group, 226 struct btrfs_path *path) 227 { 228 int ret; 229 u64 ino; 230 231 ret = btrfs_get_free_objectid(trans->fs_info->tree_root, &ino); 232 if (ret < 0) 233 return ret; 234 235 return __create_free_space_inode(trans->fs_info->tree_root, trans, path, 236 ino, block_group->start); 237 } 238 239 /* 240 * inode is an optional sink: if it is NULL, btrfs_remove_free_space_inode 241 * handles lookup, otherwise it takes ownership and iputs the inode. 242 * Don't reuse an inode pointer after passing it into this function. 243 */ 244 int btrfs_remove_free_space_inode(struct btrfs_trans_handle *trans, 245 struct inode *inode, 246 struct btrfs_block_group *block_group) 247 { 248 BTRFS_PATH_AUTO_FREE(path); 249 struct btrfs_key key; 250 int ret = 0; 251 252 path = btrfs_alloc_path(); 253 if (!path) 254 return -ENOMEM; 255 256 if (!inode) 257 inode = lookup_free_space_inode(block_group, path); 258 if (IS_ERR(inode)) { 259 if (PTR_ERR(inode) != -ENOENT) 260 ret = PTR_ERR(inode); 261 return ret; 262 } 263 ret = btrfs_orphan_add(trans, BTRFS_I(inode)); 264 if (ret) { 265 btrfs_add_delayed_iput(BTRFS_I(inode)); 266 return ret; 267 } 268 clear_nlink(inode); 269 /* One for the block groups ref */ 270 spin_lock(&block_group->lock); 271 if (test_and_clear_bit(BLOCK_GROUP_FLAG_IREF, &block_group->runtime_flags)) { 272 block_group->inode = NULL; 273 spin_unlock(&block_group->lock); 274 iput(inode); 275 } else { 276 spin_unlock(&block_group->lock); 277 } 278 /* One for the lookup ref */ 279 btrfs_add_delayed_iput(BTRFS_I(inode)); 280 281 key.objectid = BTRFS_FREE_SPACE_OBJECTID; 282 key.type = 0; 283 key.offset = block_group->start; 284 ret = btrfs_search_slot(trans, trans->fs_info->tree_root, &key, path, 285 -1, 1); 286 if (ret) { 287 if (ret > 0) 288 ret = 0; 289 return ret; 290 } 291 return btrfs_del_item(trans, trans->fs_info->tree_root, path); 292 } 293 294 int btrfs_truncate_free_space_cache(struct btrfs_trans_handle *trans, 295 struct btrfs_block_group *block_group, 296 struct inode *vfs_inode) 297 { 298 struct btrfs_truncate_control control = { 299 .inode = BTRFS_I(vfs_inode), 300 .new_size = 0, 301 .ino = btrfs_ino(BTRFS_I(vfs_inode)), 302 .min_type = BTRFS_EXTENT_DATA_KEY, 303 .clear_extent_range = true, 304 }; 305 struct btrfs_inode *inode = BTRFS_I(vfs_inode); 306 struct btrfs_root *root = inode->root; 307 struct extent_state *cached_state = NULL; 308 int ret = 0; 309 bool locked = false; 310 311 if (block_group) { 312 BTRFS_PATH_AUTO_FREE(path); 313 314 path = btrfs_alloc_path(); 315 if (!path) { 316 ret = -ENOMEM; 317 goto fail; 318 } 319 locked = true; 320 mutex_lock(&trans->transaction->cache_write_mutex); 321 if (!list_empty(&block_group->io_list)) { 322 list_del_init(&block_group->io_list); 323 324 btrfs_wait_cache_io(trans, block_group, path); 325 btrfs_put_block_group(block_group); 326 } 327 328 /* 329 * now that we've truncated the cache away, its no longer 330 * setup or written 331 */ 332 spin_lock(&block_group->lock); 333 block_group->disk_cache_state = BTRFS_DC_CLEAR; 334 spin_unlock(&block_group->lock); 335 } 336 337 btrfs_i_size_write(inode, 0); 338 truncate_pagecache(vfs_inode, 0); 339 340 btrfs_lock_extent(&inode->io_tree, 0, (u64)-1, &cached_state); 341 btrfs_drop_extent_map_range(inode, 0, (u64)-1, false); 342 343 /* 344 * We skip the throttling logic for free space cache inodes, so we don't 345 * need to check for -EAGAIN. 346 */ 347 ret = btrfs_truncate_inode_items(trans, root, &control); 348 349 inode_sub_bytes(&inode->vfs_inode, control.sub_bytes); 350 btrfs_inode_safe_disk_i_size_write(inode, control.last_size); 351 352 btrfs_unlock_extent(&inode->io_tree, 0, (u64)-1, &cached_state); 353 if (ret) 354 goto fail; 355 356 ret = btrfs_update_inode(trans, inode); 357 358 fail: 359 if (locked) 360 mutex_unlock(&trans->transaction->cache_write_mutex); 361 if (ret) 362 btrfs_abort_transaction(trans, ret); 363 364 return ret; 365 } 366 367 static void readahead_cache(struct inode *inode) 368 { 369 struct file_ra_state ra; 370 pgoff_t last_index; 371 372 file_ra_state_init(&ra, inode->i_mapping); 373 last_index = (i_size_read(inode) - 1) >> PAGE_SHIFT; 374 375 page_cache_sync_readahead(inode->i_mapping, &ra, NULL, 0, last_index); 376 } 377 378 static int io_ctl_init(struct btrfs_io_ctl *io_ctl, struct inode *inode, 379 int write) 380 { 381 int num_pages; 382 383 num_pages = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE); 384 385 /* Make sure we can fit our crcs and generation into the first page */ 386 if (write && (num_pages * sizeof(u32) + sizeof(u64)) > PAGE_SIZE) 387 return -ENOSPC; 388 389 memset(io_ctl, 0, sizeof(struct btrfs_io_ctl)); 390 391 io_ctl->pages = kzalloc_objs(struct page *, num_pages, GFP_NOFS); 392 if (!io_ctl->pages) 393 return -ENOMEM; 394 395 io_ctl->num_pages = num_pages; 396 io_ctl->fs_info = inode_to_fs_info(inode); 397 io_ctl->inode = inode; 398 399 return 0; 400 } 401 ALLOW_ERROR_INJECTION(io_ctl_init, ERRNO); 402 403 static void io_ctl_free(struct btrfs_io_ctl *io_ctl) 404 { 405 kfree(io_ctl->pages); 406 io_ctl->pages = NULL; 407 } 408 409 static void io_ctl_unmap_page(struct btrfs_io_ctl *io_ctl) 410 { 411 if (io_ctl->cur) { 412 io_ctl->cur = NULL; 413 io_ctl->orig = NULL; 414 } 415 } 416 417 static void io_ctl_map_page(struct btrfs_io_ctl *io_ctl, int clear) 418 { 419 ASSERT(io_ctl->index < io_ctl->num_pages); 420 io_ctl->page = io_ctl->pages[io_ctl->index++]; 421 io_ctl->cur = page_address(io_ctl->page); 422 io_ctl->orig = io_ctl->cur; 423 io_ctl->size = PAGE_SIZE; 424 if (clear) 425 clear_page(io_ctl->cur); 426 } 427 428 static void io_ctl_drop_pages(struct btrfs_io_ctl *io_ctl) 429 { 430 int i; 431 432 io_ctl_unmap_page(io_ctl); 433 434 for (i = 0; i < io_ctl->num_pages; i++) { 435 if (io_ctl->pages[i]) { 436 unlock_page(io_ctl->pages[i]); 437 put_page(io_ctl->pages[i]); 438 } 439 } 440 } 441 442 static int io_ctl_prepare_pages(struct btrfs_io_ctl *io_ctl, bool uptodate) 443 { 444 struct folio *folio; 445 struct inode *inode = io_ctl->inode; 446 gfp_t mask = btrfs_alloc_write_mask(inode->i_mapping); 447 int i; 448 449 for (i = 0; i < io_ctl->num_pages; i++) { 450 int ret; 451 452 folio = __filemap_get_folio(inode->i_mapping, i, 453 FGP_LOCK | FGP_ACCESSED | FGP_CREAT, 454 mask); 455 if (IS_ERR(folio)) { 456 io_ctl_drop_pages(io_ctl); 457 return PTR_ERR(folio); 458 } 459 460 ret = set_folio_extent_mapped(folio); 461 if (ret < 0) { 462 folio_unlock(folio); 463 folio_put(folio); 464 io_ctl_drop_pages(io_ctl); 465 return ret; 466 } 467 468 io_ctl->pages[i] = &folio->page; 469 if (uptodate && !folio_test_uptodate(folio)) { 470 btrfs_read_folio(NULL, folio); 471 folio_lock(folio); 472 if (folio->mapping != inode->i_mapping) { 473 btrfs_err(BTRFS_I(inode)->root->fs_info, 474 "free space cache page truncated"); 475 io_ctl_drop_pages(io_ctl); 476 return -EIO; 477 } 478 if (!folio_test_uptodate(folio)) { 479 btrfs_err(BTRFS_I(inode)->root->fs_info, 480 "error reading free space cache"); 481 io_ctl_drop_pages(io_ctl); 482 return -EIO; 483 } 484 } 485 } 486 487 for (i = 0; i < io_ctl->num_pages; i++) 488 clear_page_dirty_for_io(io_ctl->pages[i]); 489 490 return 0; 491 } 492 493 static void io_ctl_set_generation(struct btrfs_io_ctl *io_ctl, u64 generation) 494 { 495 io_ctl_map_page(io_ctl, 1); 496 497 /* 498 * Skip the csum areas. If we don't check crcs then we just have a 499 * 64bit chunk at the front of the first page. 500 */ 501 io_ctl->cur += (sizeof(u32) * io_ctl->num_pages); 502 io_ctl->size -= sizeof(u64) + (sizeof(u32) * io_ctl->num_pages); 503 504 put_unaligned_le64(generation, io_ctl->cur); 505 io_ctl->cur += sizeof(u64); 506 } 507 508 static int io_ctl_check_generation(struct btrfs_io_ctl *io_ctl, u64 generation) 509 { 510 u64 cache_gen; 511 512 /* 513 * Skip the crc area. If we don't check crcs then we just have a 64bit 514 * chunk at the front of the first page. 515 */ 516 io_ctl->cur += sizeof(u32) * io_ctl->num_pages; 517 io_ctl->size -= sizeof(u64) + (sizeof(u32) * io_ctl->num_pages); 518 519 cache_gen = get_unaligned_le64(io_ctl->cur); 520 if (cache_gen != generation) { 521 btrfs_err_rl(io_ctl->fs_info, 522 "space cache generation (%llu) does not match inode (%llu)", 523 cache_gen, generation); 524 io_ctl_unmap_page(io_ctl); 525 return -EIO; 526 } 527 io_ctl->cur += sizeof(u64); 528 return 0; 529 } 530 531 static void io_ctl_set_crc(struct btrfs_io_ctl *io_ctl, int index) 532 { 533 u32 *tmp; 534 u32 crc = ~(u32)0; 535 unsigned offset = 0; 536 537 if (index == 0) 538 offset = sizeof(u32) * io_ctl->num_pages; 539 540 crc = crc32c(crc, io_ctl->orig + offset, PAGE_SIZE - offset); 541 btrfs_crc32c_final(crc, (u8 *)&crc); 542 io_ctl_unmap_page(io_ctl); 543 tmp = page_address(io_ctl->pages[0]); 544 tmp += index; 545 *tmp = crc; 546 } 547 548 static int io_ctl_check_crc(struct btrfs_io_ctl *io_ctl, int index) 549 { 550 u32 *tmp, val; 551 u32 crc = ~(u32)0; 552 unsigned offset = 0; 553 554 if (index >= io_ctl->num_pages) 555 return -EIO; 556 557 if (index == 0) 558 offset = sizeof(u32) * io_ctl->num_pages; 559 560 tmp = page_address(io_ctl->pages[0]); 561 tmp += index; 562 val = *tmp; 563 564 io_ctl_map_page(io_ctl, 0); 565 crc = crc32c(crc, io_ctl->orig + offset, PAGE_SIZE - offset); 566 btrfs_crc32c_final(crc, (u8 *)&crc); 567 if (val != crc) { 568 btrfs_err_rl(io_ctl->fs_info, 569 "csum mismatch on free space cache"); 570 io_ctl_unmap_page(io_ctl); 571 return -EIO; 572 } 573 574 return 0; 575 } 576 577 static int io_ctl_add_entry(struct btrfs_io_ctl *io_ctl, u64 offset, u64 bytes, 578 void *bitmap) 579 { 580 struct btrfs_free_space_entry *entry; 581 582 if (!io_ctl->cur) 583 return -ENOSPC; 584 585 entry = io_ctl->cur; 586 put_unaligned_le64(offset, &entry->offset); 587 put_unaligned_le64(bytes, &entry->bytes); 588 entry->type = (bitmap) ? BTRFS_FREE_SPACE_BITMAP : 589 BTRFS_FREE_SPACE_EXTENT; 590 io_ctl->cur += sizeof(struct btrfs_free_space_entry); 591 io_ctl->size -= sizeof(struct btrfs_free_space_entry); 592 593 if (io_ctl->size >= sizeof(struct btrfs_free_space_entry)) 594 return 0; 595 596 io_ctl_set_crc(io_ctl, io_ctl->index - 1); 597 598 /* No more pages to map */ 599 if (io_ctl->index >= io_ctl->num_pages) 600 return 0; 601 602 /* map the next page */ 603 io_ctl_map_page(io_ctl, 1); 604 return 0; 605 } 606 607 static int io_ctl_add_bitmap(struct btrfs_io_ctl *io_ctl, void *bitmap) 608 { 609 if (!io_ctl->cur) 610 return -ENOSPC; 611 612 /* 613 * If we aren't at the start of the current page, unmap this one and 614 * map the next one if there is any left. 615 */ 616 if (io_ctl->cur != io_ctl->orig) { 617 io_ctl_set_crc(io_ctl, io_ctl->index - 1); 618 if (io_ctl->index >= io_ctl->num_pages) 619 return -ENOSPC; 620 io_ctl_map_page(io_ctl, 0); 621 } 622 623 copy_page(io_ctl->cur, bitmap); 624 io_ctl_set_crc(io_ctl, io_ctl->index - 1); 625 if (io_ctl->index < io_ctl->num_pages) 626 io_ctl_map_page(io_ctl, 0); 627 return 0; 628 } 629 630 static void io_ctl_zero_remaining_pages(struct btrfs_io_ctl *io_ctl) 631 { 632 /* 633 * If we're not on the boundary we know we've modified the page and we 634 * need to crc the page. 635 */ 636 if (io_ctl->cur != io_ctl->orig) 637 io_ctl_set_crc(io_ctl, io_ctl->index - 1); 638 else 639 io_ctl_unmap_page(io_ctl); 640 641 while (io_ctl->index < io_ctl->num_pages) { 642 io_ctl_map_page(io_ctl, 1); 643 io_ctl_set_crc(io_ctl, io_ctl->index - 1); 644 } 645 } 646 647 static int io_ctl_read_entry(struct btrfs_io_ctl *io_ctl, 648 struct btrfs_free_space *entry, u8 *type) 649 { 650 struct btrfs_free_space_entry *e; 651 int ret; 652 653 if (!io_ctl->cur) { 654 ret = io_ctl_check_crc(io_ctl, io_ctl->index); 655 if (ret) 656 return ret; 657 } 658 659 e = io_ctl->cur; 660 entry->offset = get_unaligned_le64(&e->offset); 661 entry->bytes = get_unaligned_le64(&e->bytes); 662 *type = e->type; 663 io_ctl->cur += sizeof(struct btrfs_free_space_entry); 664 io_ctl->size -= sizeof(struct btrfs_free_space_entry); 665 666 if (io_ctl->size >= sizeof(struct btrfs_free_space_entry)) 667 return 0; 668 669 io_ctl_unmap_page(io_ctl); 670 671 return 0; 672 } 673 674 static int io_ctl_read_bitmap(struct btrfs_io_ctl *io_ctl, 675 struct btrfs_free_space *entry) 676 { 677 int ret; 678 679 ret = io_ctl_check_crc(io_ctl, io_ctl->index); 680 if (ret) 681 return ret; 682 683 copy_page(entry->bitmap, io_ctl->cur); 684 io_ctl_unmap_page(io_ctl); 685 686 return 0; 687 } 688 689 static void recalculate_thresholds(struct btrfs_free_space_ctl *ctl) 690 { 691 struct btrfs_block_group *block_group = ctl->block_group; 692 const int unit = block_group->fs_info->sectorsize; 693 u64 max_bytes; 694 u64 bitmap_bytes; 695 u64 extent_bytes; 696 u64 size = block_group->length; 697 u64 bytes_per_bg = BITS_PER_BITMAP * unit; 698 u64 max_bitmaps = div64_u64(size + bytes_per_bg - 1, bytes_per_bg); 699 700 max_bitmaps = max_t(u64, max_bitmaps, 1); 701 702 if (ctl->total_bitmaps > max_bitmaps) 703 btrfs_err(block_group->fs_info, 704 "invalid free space control: bg start=%llu len=%llu total_bitmaps=%u unit=%u max_bitmaps=%llu bytes_per_bg=%llu", 705 block_group->start, block_group->length, 706 ctl->total_bitmaps, unit, max_bitmaps, 707 bytes_per_bg); 708 ASSERT(ctl->total_bitmaps <= max_bitmaps); 709 710 /* 711 * We are trying to keep the total amount of memory used per 1GiB of 712 * space to be MAX_CACHE_BYTES_PER_GIG. However, with a reclamation 713 * mechanism of pulling extents >= FORCE_EXTENT_THRESHOLD out of 714 * bitmaps, we may end up using more memory than this. 715 */ 716 if (size < SZ_1G) 717 max_bytes = MAX_CACHE_BYTES_PER_GIG; 718 else 719 max_bytes = MAX_CACHE_BYTES_PER_GIG * div_u64(size, SZ_1G); 720 721 bitmap_bytes = ctl->total_bitmaps * unit; 722 723 /* 724 * we want the extent entry threshold to always be at most 1/2 the max 725 * bytes we can have, or whatever is less than that. 726 */ 727 extent_bytes = max_bytes - bitmap_bytes; 728 extent_bytes = min_t(u64, extent_bytes, max_bytes >> 1); 729 730 ctl->extents_thresh = 731 div_u64(extent_bytes, sizeof(struct btrfs_free_space)); 732 } 733 734 static int __load_free_space_cache(struct btrfs_root *root, struct inode *inode, 735 struct btrfs_free_space_ctl *ctl, 736 struct btrfs_path *path, u64 offset) 737 { 738 struct btrfs_fs_info *fs_info = root->fs_info; 739 struct btrfs_free_space_header *header; 740 struct extent_buffer *leaf; 741 struct btrfs_io_ctl io_ctl; 742 struct btrfs_key key; 743 struct btrfs_free_space *e, *n; 744 LIST_HEAD(bitmaps); 745 u64 num_entries; 746 u64 num_bitmaps; 747 u64 generation; 748 u8 type; 749 int ret = 0; 750 751 /* Nothing in the space cache, goodbye */ 752 if (!i_size_read(inode)) 753 return 0; 754 755 key.objectid = BTRFS_FREE_SPACE_OBJECTID; 756 key.type = 0; 757 key.offset = offset; 758 759 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0); 760 if (ret < 0) 761 return 0; 762 else if (ret > 0) { 763 btrfs_release_path(path); 764 return 0; 765 } 766 767 ret = -1; 768 769 leaf = path->nodes[0]; 770 header = btrfs_item_ptr(leaf, path->slots[0], 771 struct btrfs_free_space_header); 772 num_entries = btrfs_free_space_entries(leaf, header); 773 num_bitmaps = btrfs_free_space_bitmaps(leaf, header); 774 generation = btrfs_free_space_generation(leaf, header); 775 btrfs_release_path(path); 776 777 if (!BTRFS_I(inode)->generation) { 778 btrfs_info(fs_info, 779 "the free space cache file (%llu) is invalid, skip it", 780 offset); 781 return 0; 782 } 783 784 if (BTRFS_I(inode)->generation != generation) { 785 btrfs_err(fs_info, 786 "free space inode generation (%llu) did not match free space cache generation (%llu)", 787 BTRFS_I(inode)->generation, generation); 788 return 0; 789 } 790 791 if (!num_entries) 792 return 0; 793 794 ret = io_ctl_init(&io_ctl, inode, 0); 795 if (ret) 796 return ret; 797 798 readahead_cache(inode); 799 800 ret = io_ctl_prepare_pages(&io_ctl, true); 801 if (ret) 802 goto out; 803 804 ret = io_ctl_check_crc(&io_ctl, 0); 805 if (ret) 806 goto free_cache; 807 808 ret = io_ctl_check_generation(&io_ctl, generation); 809 if (ret) 810 goto free_cache; 811 812 while (num_entries) { 813 e = kmem_cache_zalloc(btrfs_free_space_cachep, 814 GFP_NOFS); 815 if (!e) { 816 ret = -ENOMEM; 817 goto free_cache; 818 } 819 820 ret = io_ctl_read_entry(&io_ctl, e, &type); 821 if (ret) { 822 kmem_cache_free(btrfs_free_space_cachep, e); 823 goto free_cache; 824 } 825 826 if (!e->bytes) { 827 ret = -1; 828 kmem_cache_free(btrfs_free_space_cachep, e); 829 goto free_cache; 830 } 831 832 if (type == BTRFS_FREE_SPACE_EXTENT) { 833 spin_lock(&ctl->tree_lock); 834 ret = link_free_space(ctl, e); 835 spin_unlock(&ctl->tree_lock); 836 if (ret) { 837 btrfs_err(fs_info, 838 "Duplicate entries in free space cache, dumping"); 839 kmem_cache_free(btrfs_free_space_cachep, e); 840 goto free_cache; 841 } 842 } else { 843 ASSERT(num_bitmaps); 844 num_bitmaps--; 845 e->bitmap = kmem_cache_zalloc( 846 btrfs_free_space_bitmap_cachep, GFP_NOFS); 847 if (!e->bitmap) { 848 ret = -ENOMEM; 849 kmem_cache_free( 850 btrfs_free_space_cachep, e); 851 goto free_cache; 852 } 853 spin_lock(&ctl->tree_lock); 854 ret = link_free_space(ctl, e); 855 if (ret) { 856 spin_unlock(&ctl->tree_lock); 857 btrfs_err(fs_info, 858 "Duplicate entries in free space cache, dumping"); 859 kmem_cache_free(btrfs_free_space_bitmap_cachep, e->bitmap); 860 kmem_cache_free(btrfs_free_space_cachep, e); 861 goto free_cache; 862 } 863 ctl->total_bitmaps++; 864 recalculate_thresholds(ctl); 865 spin_unlock(&ctl->tree_lock); 866 list_add_tail(&e->list, &bitmaps); 867 } 868 869 num_entries--; 870 } 871 872 io_ctl_unmap_page(&io_ctl); 873 874 /* 875 * We add the bitmaps at the end of the entries in order that 876 * the bitmap entries are added to the cache. 877 */ 878 list_for_each_entry_safe(e, n, &bitmaps, list) { 879 list_del_init(&e->list); 880 ret = io_ctl_read_bitmap(&io_ctl, e); 881 if (ret) 882 goto free_cache; 883 } 884 885 io_ctl_drop_pages(&io_ctl); 886 ret = 1; 887 out: 888 io_ctl_free(&io_ctl); 889 return ret; 890 free_cache: 891 io_ctl_drop_pages(&io_ctl); 892 893 spin_lock(&ctl->tree_lock); 894 __btrfs_remove_free_space_cache(ctl); 895 spin_unlock(&ctl->tree_lock); 896 goto out; 897 } 898 899 static int copy_free_space_cache(struct btrfs_free_space_ctl *ctl) 900 { 901 struct btrfs_free_space *info; 902 struct rb_node *n; 903 int ret = 0; 904 905 while (!ret && (n = rb_first(&ctl->free_space_offset)) != NULL) { 906 info = rb_entry(n, struct btrfs_free_space, offset_index); 907 if (!info->bitmap) { 908 const u64 offset = info->offset; 909 const u64 bytes = info->bytes; 910 911 unlink_free_space(ctl, info, true); 912 spin_unlock(&ctl->tree_lock); 913 kmem_cache_free(btrfs_free_space_cachep, info); 914 ret = btrfs_add_free_space(ctl->block_group, offset, bytes); 915 spin_lock(&ctl->tree_lock); 916 } else { 917 u64 offset = info->offset; 918 u64 bytes = ctl->block_group->fs_info->sectorsize; 919 920 ret = search_bitmap(ctl, info, &offset, &bytes, false); 921 if (ret == 0) { 922 bitmap_clear_bits(ctl, info, offset, bytes, true); 923 spin_unlock(&ctl->tree_lock); 924 ret = btrfs_add_free_space(ctl->block_group, offset, 925 bytes); 926 spin_lock(&ctl->tree_lock); 927 } else { 928 free_bitmap(ctl, info); 929 ret = 0; 930 } 931 } 932 cond_resched_lock(&ctl->tree_lock); 933 } 934 return ret; 935 } 936 937 static struct lock_class_key btrfs_free_space_inode_key; 938 939 int load_free_space_cache(struct btrfs_block_group *block_group) 940 { 941 struct btrfs_fs_info *fs_info = block_group->fs_info; 942 struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl; 943 struct btrfs_free_space_ctl tmp_ctl = {}; 944 struct inode *inode; 945 struct btrfs_path *path; 946 int ret = 0; 947 bool matched; 948 u64 used = block_group->used; 949 950 /* 951 * Because we could potentially discard our loaded free space, we want 952 * to load everything into a temporary structure first, and then if it's 953 * valid copy it all into the actual free space ctl. 954 */ 955 btrfs_init_free_space_ctl(block_group, &tmp_ctl); 956 957 /* 958 * If this block group has been marked to be cleared for one reason or 959 * another then we can't trust the on disk cache, so just return. 960 */ 961 spin_lock(&block_group->lock); 962 if (block_group->disk_cache_state != BTRFS_DC_WRITTEN) { 963 spin_unlock(&block_group->lock); 964 return 0; 965 } 966 spin_unlock(&block_group->lock); 967 968 path = btrfs_alloc_path(); 969 if (!path) 970 return 0; 971 path->search_commit_root = true; 972 path->skip_locking = true; 973 974 /* 975 * We must pass a path with search_commit_root set to btrfs_iget in 976 * order to avoid a deadlock when allocating extents for the tree root. 977 * 978 * When we are COWing an extent buffer from the tree root, when looking 979 * for a free extent, at extent-tree.c:find_free_extent(), we can find 980 * block group without its free space cache loaded. When we find one 981 * we must load its space cache which requires reading its free space 982 * cache's inode item from the root tree. If this inode item is located 983 * in the same leaf that we started COWing before, then we end up in 984 * deadlock on the extent buffer (trying to read lock it when we 985 * previously write locked it). 986 * 987 * It's safe to read the inode item using the commit root because 988 * block groups, once loaded, stay in memory forever (until they are 989 * removed) as well as their space caches once loaded. New block groups 990 * once created get their ->cached field set to BTRFS_CACHE_FINISHED so 991 * we will never try to read their inode item while the fs is mounted. 992 */ 993 inode = lookup_free_space_inode(block_group, path); 994 if (IS_ERR(inode)) { 995 btrfs_free_path(path); 996 return 0; 997 } 998 999 /* We may have converted the inode and made the cache invalid. */ 1000 spin_lock(&block_group->lock); 1001 if (block_group->disk_cache_state != BTRFS_DC_WRITTEN) { 1002 spin_unlock(&block_group->lock); 1003 btrfs_free_path(path); 1004 goto out; 1005 } 1006 spin_unlock(&block_group->lock); 1007 1008 /* 1009 * Reinitialize the class of struct inode's mapping->invalidate_lock for 1010 * free space inodes to prevent false positives related to locks for normal 1011 * inodes. 1012 */ 1013 lockdep_set_class(&(&inode->i_data)->invalidate_lock, 1014 &btrfs_free_space_inode_key); 1015 1016 ret = __load_free_space_cache(fs_info->tree_root, inode, &tmp_ctl, 1017 path, block_group->start); 1018 btrfs_free_path(path); 1019 if (ret <= 0) 1020 goto out; 1021 1022 matched = (tmp_ctl.free_space == (block_group->length - used - 1023 block_group->bytes_super)); 1024 1025 if (matched) { 1026 spin_lock(&tmp_ctl.tree_lock); 1027 ret = copy_free_space_cache(&tmp_ctl); 1028 spin_unlock(&tmp_ctl.tree_lock); 1029 /* 1030 * ret == 1 means we successfully loaded the free space cache, 1031 * so we need to re-set it here. 1032 */ 1033 if (ret == 0) 1034 ret = 1; 1035 } else { 1036 /* 1037 * We need to call the _locked variant so we don't try to update 1038 * the discard counters. 1039 */ 1040 spin_lock(&tmp_ctl.tree_lock); 1041 __btrfs_remove_free_space_cache(&tmp_ctl); 1042 spin_unlock(&tmp_ctl.tree_lock); 1043 btrfs_warn(fs_info, 1044 "block group %llu has wrong amount of free space", 1045 block_group->start); 1046 ret = -1; 1047 } 1048 out: 1049 if (ret < 0) { 1050 /* This cache is bogus, make sure it gets cleared */ 1051 spin_lock(&block_group->lock); 1052 block_group->disk_cache_state = BTRFS_DC_CLEAR; 1053 spin_unlock(&block_group->lock); 1054 ret = 0; 1055 1056 btrfs_warn(fs_info, 1057 "failed to load free space cache for block group %llu, rebuilding it now", 1058 block_group->start); 1059 } 1060 1061 spin_lock(&ctl->tree_lock); 1062 btrfs_discard_update_discardable(block_group); 1063 spin_unlock(&ctl->tree_lock); 1064 iput(inode); 1065 return ret; 1066 } 1067 1068 static noinline_for_stack 1069 int write_cache_extent_entries(struct btrfs_io_ctl *io_ctl, 1070 struct btrfs_block_group *block_group, 1071 int *entries, int *bitmaps, 1072 struct list_head *bitmap_list) 1073 { 1074 int ret; 1075 struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl; 1076 struct btrfs_free_cluster *cluster = NULL; 1077 struct btrfs_free_cluster *cluster_locked = NULL; 1078 struct rb_node *node = rb_first(&ctl->free_space_offset); 1079 struct btrfs_trim_range *trim_entry; 1080 1081 /* Get the cluster for this block_group if it exists */ 1082 if (!list_empty(&block_group->cluster_list)) { 1083 cluster = list_first_entry(&block_group->cluster_list, 1084 struct btrfs_free_cluster, block_group_list); 1085 } 1086 1087 if (!node && cluster) { 1088 cluster_locked = cluster; 1089 spin_lock(&cluster_locked->lock); 1090 node = rb_first(&cluster->root); 1091 cluster = NULL; 1092 } 1093 1094 /* Write out the extent entries */ 1095 while (node) { 1096 struct btrfs_free_space *e; 1097 1098 e = rb_entry(node, struct btrfs_free_space, offset_index); 1099 *entries += 1; 1100 1101 ret = io_ctl_add_entry(io_ctl, e->offset, e->bytes, 1102 e->bitmap); 1103 if (ret) 1104 goto fail; 1105 1106 if (e->bitmap) { 1107 list_add_tail(&e->list, bitmap_list); 1108 *bitmaps += 1; 1109 } 1110 node = rb_next(node); 1111 if (!node && cluster) { 1112 node = rb_first(&cluster->root); 1113 cluster_locked = cluster; 1114 spin_lock(&cluster_locked->lock); 1115 cluster = NULL; 1116 } 1117 } 1118 if (cluster_locked) { 1119 spin_unlock(&cluster_locked->lock); 1120 cluster_locked = NULL; 1121 } 1122 1123 /* 1124 * Make sure we don't miss any range that was removed from our rbtree 1125 * because trimming is running. Otherwise after a umount+mount (or crash 1126 * after committing the transaction) we would leak free space and get 1127 * an inconsistent free space cache report from fsck. 1128 */ 1129 list_for_each_entry(trim_entry, &ctl->trimming_ranges, list) { 1130 ret = io_ctl_add_entry(io_ctl, trim_entry->start, 1131 trim_entry->bytes, NULL); 1132 if (ret) 1133 goto fail; 1134 *entries += 1; 1135 } 1136 1137 return 0; 1138 fail: 1139 if (cluster_locked) 1140 spin_unlock(&cluster_locked->lock); 1141 return -ENOSPC; 1142 } 1143 1144 static noinline_for_stack int 1145 update_cache_item(struct btrfs_trans_handle *trans, 1146 struct btrfs_root *root, 1147 struct inode *inode, 1148 struct btrfs_path *path, u64 offset, 1149 int entries, int bitmaps) 1150 { 1151 struct btrfs_key key; 1152 struct btrfs_free_space_header *header; 1153 struct extent_buffer *leaf; 1154 int ret; 1155 1156 key.objectid = BTRFS_FREE_SPACE_OBJECTID; 1157 key.type = 0; 1158 key.offset = offset; 1159 1160 ret = btrfs_search_slot(trans, root, &key, path, 0, 1); 1161 if (ret < 0) { 1162 btrfs_clear_extent_bit(&BTRFS_I(inode)->io_tree, 0, inode->i_size - 1, 1163 EXTENT_DELALLOC, NULL); 1164 return ret; 1165 } 1166 leaf = path->nodes[0]; 1167 if (ret > 0) { 1168 struct btrfs_key found_key; 1169 ASSERT(path->slots[0]); 1170 path->slots[0]--; 1171 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]); 1172 if (found_key.objectid != BTRFS_FREE_SPACE_OBJECTID || 1173 found_key.offset != offset) { 1174 btrfs_clear_extent_bit(&BTRFS_I(inode)->io_tree, 0, 1175 inode->i_size - 1, EXTENT_DELALLOC, 1176 NULL); 1177 btrfs_release_path(path); 1178 return -ENOENT; 1179 } 1180 } 1181 1182 BTRFS_I(inode)->generation = trans->transid; 1183 header = btrfs_item_ptr(leaf, path->slots[0], 1184 struct btrfs_free_space_header); 1185 btrfs_set_free_space_entries(leaf, header, entries); 1186 btrfs_set_free_space_bitmaps(leaf, header, bitmaps); 1187 btrfs_set_free_space_generation(leaf, header, trans->transid); 1188 btrfs_release_path(path); 1189 1190 return 0; 1191 } 1192 1193 static noinline_for_stack int write_pinned_extent_entries( 1194 struct btrfs_trans_handle *trans, 1195 struct btrfs_block_group *block_group, 1196 struct btrfs_io_ctl *io_ctl, 1197 int *entries) 1198 { 1199 u64 start, extent_start, extent_end, len; 1200 const u64 block_group_end = btrfs_block_group_end(block_group); 1201 struct extent_io_tree *unpin = NULL; 1202 int ret; 1203 1204 /* 1205 * We want to add any pinned extents to our free space cache 1206 * so we don't leak the space 1207 * 1208 * We shouldn't have switched the pinned extents yet so this is the 1209 * right one 1210 */ 1211 unpin = &trans->transaction->pinned_extents; 1212 1213 start = block_group->start; 1214 1215 while (start < block_group_end) { 1216 if (!btrfs_find_first_extent_bit(unpin, start, 1217 &extent_start, &extent_end, 1218 EXTENT_DIRTY, NULL)) 1219 return 0; 1220 1221 /* This pinned extent is out of our range */ 1222 if (extent_start >= block_group_end) 1223 return 0; 1224 1225 extent_start = max(extent_start, start); 1226 extent_end = min(block_group_end, extent_end + 1); 1227 len = extent_end - extent_start; 1228 1229 *entries += 1; 1230 ret = io_ctl_add_entry(io_ctl, extent_start, len, NULL); 1231 if (ret) 1232 return -ENOSPC; 1233 1234 start = extent_end; 1235 } 1236 1237 return 0; 1238 } 1239 1240 static noinline_for_stack int 1241 write_bitmap_entries(struct btrfs_io_ctl *io_ctl, struct list_head *bitmap_list) 1242 { 1243 struct btrfs_free_space *entry, *next; 1244 int ret; 1245 1246 /* Write out the bitmaps */ 1247 list_for_each_entry_safe(entry, next, bitmap_list, list) { 1248 ret = io_ctl_add_bitmap(io_ctl, entry->bitmap); 1249 if (ret) 1250 return -ENOSPC; 1251 list_del_init(&entry->list); 1252 } 1253 1254 return 0; 1255 } 1256 1257 static int flush_dirty_cache(struct inode *inode) 1258 { 1259 int ret; 1260 1261 ret = btrfs_wait_ordered_range(BTRFS_I(inode), 0, (u64)-1); 1262 if (ret) 1263 btrfs_clear_extent_bit(&BTRFS_I(inode)->io_tree, 0, inode->i_size - 1, 1264 EXTENT_DELALLOC, NULL); 1265 1266 return ret; 1267 } 1268 1269 static void noinline_for_stack 1270 cleanup_bitmap_list(struct list_head *bitmap_list) 1271 { 1272 struct btrfs_free_space *entry, *next; 1273 1274 list_for_each_entry_safe(entry, next, bitmap_list, list) 1275 list_del_init(&entry->list); 1276 } 1277 1278 static void noinline_for_stack 1279 cleanup_write_cache_enospc(struct inode *inode, 1280 struct btrfs_io_ctl *io_ctl, 1281 struct extent_state **cached_state) 1282 { 1283 io_ctl_drop_pages(io_ctl); 1284 btrfs_unlock_extent(&BTRFS_I(inode)->io_tree, 0, i_size_read(inode) - 1, 1285 cached_state); 1286 } 1287 1288 static int __btrfs_wait_cache_io(struct btrfs_root *root, 1289 struct btrfs_trans_handle *trans, 1290 struct btrfs_block_group *block_group, 1291 struct btrfs_io_ctl *io_ctl, 1292 struct btrfs_path *path, u64 offset) 1293 { 1294 int ret; 1295 struct inode *inode = io_ctl->inode; 1296 1297 if (!inode) 1298 return 0; 1299 1300 /* Flush the dirty pages in the cache file. */ 1301 ret = flush_dirty_cache(inode); 1302 if (ret) 1303 goto out; 1304 1305 /* Update the cache item to tell everyone this cache file is valid. */ 1306 ret = update_cache_item(trans, root, inode, path, offset, 1307 io_ctl->entries, io_ctl->bitmaps); 1308 out: 1309 if (ret) { 1310 invalidate_inode_pages2(inode->i_mapping); 1311 BTRFS_I(inode)->generation = 0; 1312 if (block_group) 1313 btrfs_debug(root->fs_info, 1314 "failed to write free space cache for block group %llu error %d", 1315 block_group->start, ret); 1316 } 1317 btrfs_update_inode(trans, BTRFS_I(inode)); 1318 1319 if (block_group) { 1320 /* the dirty list is protected by the dirty_bgs_lock */ 1321 spin_lock(&trans->transaction->dirty_bgs_lock); 1322 1323 /* the disk_cache_state is protected by the block group lock */ 1324 spin_lock(&block_group->lock); 1325 1326 /* 1327 * only mark this as written if we didn't get put back on 1328 * the dirty list while waiting for IO. Otherwise our 1329 * cache state won't be right, and we won't get written again 1330 */ 1331 if (!ret && list_empty(&block_group->dirty_list)) 1332 block_group->disk_cache_state = BTRFS_DC_WRITTEN; 1333 else if (ret) 1334 block_group->disk_cache_state = BTRFS_DC_ERROR; 1335 1336 spin_unlock(&block_group->lock); 1337 spin_unlock(&trans->transaction->dirty_bgs_lock); 1338 io_ctl->inode = NULL; 1339 iput(inode); 1340 } 1341 1342 return ret; 1343 1344 } 1345 1346 int btrfs_wait_cache_io(struct btrfs_trans_handle *trans, 1347 struct btrfs_block_group *block_group, 1348 struct btrfs_path *path) 1349 { 1350 return __btrfs_wait_cache_io(block_group->fs_info->tree_root, trans, 1351 block_group, &block_group->io_ctl, 1352 path, block_group->start); 1353 } 1354 1355 /* 1356 * Write out cached info to an inode. 1357 * 1358 * @inode: freespace inode we are writing out 1359 * @ctl: free space cache we are going to write out 1360 * @block_group: block_group for this cache if it belongs to a block_group 1361 * @io_ctl: holds context for the io 1362 * @trans: the trans handle 1363 * 1364 * This function writes out a free space cache struct to disk for quick recovery 1365 * on mount. This will return 0 if it was successful in writing the cache out, 1366 * or an errno if it was not. 1367 */ 1368 static int __btrfs_write_out_cache(struct inode *inode, 1369 struct btrfs_block_group *block_group, 1370 struct btrfs_trans_handle *trans) 1371 { 1372 struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl; 1373 struct btrfs_io_ctl *io_ctl = &block_group->io_ctl; 1374 struct extent_state *cached_state = NULL; 1375 LIST_HEAD(bitmap_list); 1376 int entries = 0; 1377 int bitmaps = 0; 1378 int ret; 1379 bool must_iput = false; 1380 int i_size; 1381 1382 if (!i_size_read(inode)) 1383 return -EIO; 1384 1385 WARN_ON(io_ctl->pages); 1386 ret = io_ctl_init(io_ctl, inode, 1); 1387 if (ret) 1388 return ret; 1389 1390 if (block_group->flags & BTRFS_BLOCK_GROUP_DATA) { 1391 down_write(&block_group->data_rwsem); 1392 spin_lock(&block_group->lock); 1393 if (block_group->delalloc_bytes) { 1394 block_group->disk_cache_state = BTRFS_DC_WRITTEN; 1395 spin_unlock(&block_group->lock); 1396 up_write(&block_group->data_rwsem); 1397 BTRFS_I(inode)->generation = 0; 1398 ret = 0; 1399 must_iput = true; 1400 goto out; 1401 } 1402 spin_unlock(&block_group->lock); 1403 } 1404 1405 /* Lock all pages first so we can lock the extent safely. */ 1406 ret = io_ctl_prepare_pages(io_ctl, false); 1407 if (ret) 1408 goto out_unlock; 1409 1410 btrfs_lock_extent(&BTRFS_I(inode)->io_tree, 0, i_size_read(inode) - 1, 1411 &cached_state); 1412 1413 io_ctl_set_generation(io_ctl, trans->transid); 1414 1415 mutex_lock(&ctl->cache_writeout_mutex); 1416 /* Write out the extent entries in the free space cache */ 1417 spin_lock(&ctl->tree_lock); 1418 ret = write_cache_extent_entries(io_ctl, block_group, &entries, &bitmaps, 1419 &bitmap_list); 1420 if (ret) 1421 goto out_nospc_locked; 1422 1423 /* 1424 * Some spaces that are freed in the current transaction are pinned, 1425 * they will be added into free space cache after the transaction is 1426 * committed, we shouldn't lose them. 1427 * 1428 * If this changes while we are working we'll get added back to 1429 * the dirty list and redo it. No locking needed 1430 */ 1431 ret = write_pinned_extent_entries(trans, block_group, io_ctl, &entries); 1432 if (ret) 1433 goto out_nospc_locked; 1434 1435 /* 1436 * At last, we write out all the bitmaps and keep cache_writeout_mutex 1437 * locked while doing it because a concurrent trim can be manipulating 1438 * or freeing the bitmap. 1439 */ 1440 ret = write_bitmap_entries(io_ctl, &bitmap_list); 1441 spin_unlock(&ctl->tree_lock); 1442 mutex_unlock(&ctl->cache_writeout_mutex); 1443 if (ret) 1444 goto out_nospc; 1445 1446 /* Zero out the rest of the pages just to make sure */ 1447 io_ctl_zero_remaining_pages(io_ctl); 1448 1449 /* Everything is written out, now we dirty the pages in the file. */ 1450 i_size = i_size_read(inode); 1451 for (int i = 0; i < round_up(i_size, PAGE_SIZE) / PAGE_SIZE; i++) { 1452 u64 dirty_start = i * PAGE_SIZE; 1453 u64 dirty_len = min_t(u64, dirty_start + PAGE_SIZE, i_size) - dirty_start; 1454 1455 ret = btrfs_dirty_folio(BTRFS_I(inode), page_folio(io_ctl->pages[i]), 1456 dirty_start, dirty_len, &cached_state, false); 1457 if (ret < 0) 1458 goto out_nospc; 1459 } 1460 1461 if (block_group->flags & BTRFS_BLOCK_GROUP_DATA) 1462 up_write(&block_group->data_rwsem); 1463 /* 1464 * Release the pages and unlock the extent, we will flush 1465 * them out later 1466 */ 1467 io_ctl_drop_pages(io_ctl); 1468 io_ctl_free(io_ctl); 1469 1470 btrfs_unlock_extent(&BTRFS_I(inode)->io_tree, 0, i_size_read(inode) - 1, 1471 &cached_state); 1472 1473 /* 1474 * at this point the pages are under IO and we're happy, 1475 * The caller is responsible for waiting on them and updating 1476 * the cache and the inode 1477 */ 1478 io_ctl->entries = entries; 1479 io_ctl->bitmaps = bitmaps; 1480 1481 ret = btrfs_fdatawrite_range(BTRFS_I(inode), 0, (u64)-1); 1482 if (ret) 1483 goto out; 1484 1485 return 0; 1486 1487 out_nospc_locked: 1488 cleanup_bitmap_list(&bitmap_list); 1489 spin_unlock(&ctl->tree_lock); 1490 mutex_unlock(&ctl->cache_writeout_mutex); 1491 1492 out_nospc: 1493 cleanup_write_cache_enospc(inode, io_ctl, &cached_state); 1494 1495 out_unlock: 1496 if (block_group->flags & BTRFS_BLOCK_GROUP_DATA) 1497 up_write(&block_group->data_rwsem); 1498 1499 out: 1500 io_ctl->inode = NULL; 1501 io_ctl_free(io_ctl); 1502 if (ret) { 1503 invalidate_inode_pages2(inode->i_mapping); 1504 BTRFS_I(inode)->generation = 0; 1505 } 1506 btrfs_update_inode(trans, BTRFS_I(inode)); 1507 if (must_iput) 1508 iput(inode); 1509 return ret; 1510 } 1511 1512 int btrfs_write_out_cache(struct btrfs_trans_handle *trans, 1513 struct btrfs_block_group *block_group, 1514 struct btrfs_path *path) 1515 { 1516 struct btrfs_fs_info *fs_info = trans->fs_info; 1517 struct inode *inode; 1518 int ret = 0; 1519 1520 spin_lock(&block_group->lock); 1521 if (block_group->disk_cache_state < BTRFS_DC_SETUP) { 1522 spin_unlock(&block_group->lock); 1523 return 0; 1524 } 1525 spin_unlock(&block_group->lock); 1526 1527 inode = lookup_free_space_inode(block_group, path); 1528 if (IS_ERR(inode)) 1529 return 0; 1530 1531 ret = __btrfs_write_out_cache(inode, block_group, trans); 1532 if (ret) { 1533 btrfs_debug(fs_info, 1534 "failed to write free space cache for block group %llu error %d", 1535 block_group->start, ret); 1536 spin_lock(&block_group->lock); 1537 block_group->disk_cache_state = BTRFS_DC_ERROR; 1538 spin_unlock(&block_group->lock); 1539 1540 block_group->io_ctl.inode = NULL; 1541 iput(inode); 1542 } 1543 1544 /* 1545 * if ret == 0 the caller is expected to call btrfs_wait_cache_io 1546 * to wait for IO and put the inode 1547 */ 1548 1549 return ret; 1550 } 1551 1552 static inline unsigned long offset_to_bit(u64 bitmap_start, u32 unit, 1553 u64 offset) 1554 { 1555 ASSERT(offset >= bitmap_start); 1556 offset -= bitmap_start; 1557 return (unsigned long)(div_u64(offset, unit)); 1558 } 1559 1560 static inline unsigned long bytes_to_bits(u64 bytes, u32 unit) 1561 { 1562 return (unsigned long)(div_u64(bytes, unit)); 1563 } 1564 1565 static inline u64 offset_to_bitmap(struct btrfs_free_space_ctl *ctl, 1566 u64 offset) 1567 { 1568 u64 bitmap_start; 1569 u64 bytes_per_bitmap; 1570 1571 bytes_per_bitmap = BITS_PER_BITMAP * ctl->block_group->fs_info->sectorsize; 1572 bitmap_start = offset - ctl->block_group->start; 1573 bitmap_start = div64_u64(bitmap_start, bytes_per_bitmap); 1574 bitmap_start *= bytes_per_bitmap; 1575 bitmap_start += ctl->block_group->start; 1576 1577 return bitmap_start; 1578 } 1579 1580 static int tree_insert_offset(struct btrfs_free_space_ctl *ctl, 1581 struct btrfs_free_cluster *cluster, 1582 struct btrfs_free_space *new_entry) 1583 { 1584 struct rb_root *root; 1585 struct rb_node **p; 1586 struct rb_node *parent = NULL; 1587 1588 lockdep_assert_held(&ctl->tree_lock); 1589 1590 if (cluster) { 1591 lockdep_assert_held(&cluster->lock); 1592 root = &cluster->root; 1593 } else { 1594 root = &ctl->free_space_offset; 1595 } 1596 1597 p = &root->rb_node; 1598 1599 while (*p) { 1600 struct btrfs_free_space *info; 1601 1602 parent = *p; 1603 info = rb_entry(parent, struct btrfs_free_space, offset_index); 1604 1605 if (new_entry->offset < info->offset) { 1606 p = &(*p)->rb_left; 1607 } else if (new_entry->offset > info->offset) { 1608 p = &(*p)->rb_right; 1609 } else { 1610 /* 1611 * we could have a bitmap entry and an extent entry 1612 * share the same offset. If this is the case, we want 1613 * the extent entry to always be found first if we do a 1614 * linear search through the tree, since we want to have 1615 * the quickest allocation time, and allocating from an 1616 * extent is faster than allocating from a bitmap. So 1617 * if we're inserting a bitmap and we find an entry at 1618 * this offset, we want to go right, or after this entry 1619 * logically. If we are inserting an extent and we've 1620 * found a bitmap, we want to go left, or before 1621 * logically. 1622 */ 1623 if (new_entry->bitmap) { 1624 if (info->bitmap) { 1625 WARN_ON_ONCE(1); 1626 return -EEXIST; 1627 } 1628 p = &(*p)->rb_right; 1629 } else { 1630 if (!info->bitmap) { 1631 WARN_ON_ONCE(1); 1632 return -EEXIST; 1633 } 1634 p = &(*p)->rb_left; 1635 } 1636 } 1637 } 1638 1639 rb_link_node(&new_entry->offset_index, parent, p); 1640 rb_insert_color(&new_entry->offset_index, root); 1641 1642 return 0; 1643 } 1644 1645 /* 1646 * This is a little subtle. We *only* have ->max_extent_size set if we actually 1647 * searched through the bitmap and figured out the largest ->max_extent_size, 1648 * otherwise it's 0. In the case that it's 0 we don't want to tell the 1649 * allocator the wrong thing, we want to use the actual real max_extent_size 1650 * we've found already if it's larger, or we want to use ->bytes. 1651 * 1652 * This matters because find_free_space() will skip entries who's ->bytes is 1653 * less than the required bytes. So if we didn't search down this bitmap, we 1654 * may pick some previous entry that has a smaller ->max_extent_size than we 1655 * have. For example, assume we have two entries, one that has 1656 * ->max_extent_size set to 4K and ->bytes set to 1M. A second entry hasn't set 1657 * ->max_extent_size yet, has ->bytes set to 8K and it's contiguous. We will 1658 * call into find_free_space(), and return with max_extent_size == 4K, because 1659 * that first bitmap entry had ->max_extent_size set, but the second one did 1660 * not. If instead we returned 8K we'd come in searching for 8K, and find the 1661 * 8K contiguous range. 1662 * 1663 * Consider the other case, we have 2 8K chunks in that second entry and still 1664 * don't have ->max_extent_size set. We'll return 16K, and the next time the 1665 * allocator comes in it'll fully search our second bitmap, and this time it'll 1666 * get an uptodate value of 8K as the maximum chunk size. Then we'll get the 1667 * right allocation the next loop through. 1668 */ 1669 static inline u64 get_max_extent_size(const struct btrfs_free_space *entry) 1670 { 1671 if (entry->bitmap && entry->max_extent_size) 1672 return entry->max_extent_size; 1673 return entry->bytes; 1674 } 1675 1676 /* 1677 * We want the largest entry to be leftmost, so this is inverted from what you'd 1678 * normally expect. 1679 */ 1680 static bool entry_less(struct rb_node *node, const struct rb_node *parent) 1681 { 1682 const struct btrfs_free_space *entry, *exist; 1683 1684 entry = rb_entry(node, struct btrfs_free_space, bytes_index); 1685 exist = rb_entry(parent, struct btrfs_free_space, bytes_index); 1686 return get_max_extent_size(exist) < get_max_extent_size(entry); 1687 } 1688 1689 /* 1690 * searches the tree for the given offset. 1691 * 1692 * fuzzy - If this is set, then we are trying to make an allocation, and we just 1693 * want a section that has at least bytes size and comes at or after the given 1694 * offset. 1695 */ 1696 static struct btrfs_free_space * 1697 tree_search_offset(struct btrfs_free_space_ctl *ctl, 1698 u64 offset, int bitmap_only, int fuzzy) 1699 { 1700 struct rb_node *n = ctl->free_space_offset.rb_node; 1701 struct btrfs_free_space *entry = NULL, *prev = NULL; 1702 const int unit = ctl->block_group->fs_info->sectorsize; 1703 1704 lockdep_assert_held(&ctl->tree_lock); 1705 1706 /* find entry that is closest to the 'offset' */ 1707 while (n) { 1708 entry = rb_entry(n, struct btrfs_free_space, offset_index); 1709 prev = entry; 1710 1711 if (offset < entry->offset) 1712 n = n->rb_left; 1713 else if (offset > entry->offset) 1714 n = n->rb_right; 1715 else 1716 break; 1717 1718 entry = NULL; 1719 } 1720 1721 if (bitmap_only) { 1722 if (!entry) 1723 return NULL; 1724 if (entry->bitmap) 1725 return entry; 1726 1727 /* 1728 * bitmap entry and extent entry may share same offset, 1729 * in that case, bitmap entry comes after extent entry. 1730 */ 1731 n = rb_next(n); 1732 if (!n) 1733 return NULL; 1734 entry = rb_entry(n, struct btrfs_free_space, offset_index); 1735 if (entry->offset != offset) 1736 return NULL; 1737 1738 WARN_ON(!entry->bitmap); 1739 return entry; 1740 } else if (entry) { 1741 if (entry->bitmap) { 1742 /* 1743 * if previous extent entry covers the offset, 1744 * we should return it instead of the bitmap entry 1745 */ 1746 n = rb_prev(&entry->offset_index); 1747 if (n) { 1748 prev = rb_entry(n, struct btrfs_free_space, 1749 offset_index); 1750 if (!prev->bitmap && 1751 prev->offset + prev->bytes > offset) 1752 entry = prev; 1753 } 1754 } 1755 return entry; 1756 } 1757 1758 if (!prev) 1759 return NULL; 1760 1761 /* find last entry before the 'offset' */ 1762 entry = prev; 1763 if (entry->offset > offset) { 1764 n = rb_prev(&entry->offset_index); 1765 if (n) { 1766 entry = rb_entry(n, struct btrfs_free_space, 1767 offset_index); 1768 ASSERT(entry->offset <= offset); 1769 } else { 1770 if (fuzzy) 1771 return entry; 1772 else 1773 return NULL; 1774 } 1775 } 1776 1777 if (entry->bitmap) { 1778 n = rb_prev(&entry->offset_index); 1779 if (n) { 1780 prev = rb_entry(n, struct btrfs_free_space, 1781 offset_index); 1782 if (!prev->bitmap && 1783 prev->offset + prev->bytes > offset) 1784 return prev; 1785 } 1786 if (entry->offset + BITS_PER_BITMAP * unit > offset) 1787 return entry; 1788 } else if (entry->offset + entry->bytes > offset) 1789 return entry; 1790 1791 if (!fuzzy) 1792 return NULL; 1793 1794 while (1) { 1795 n = rb_next(&entry->offset_index); 1796 if (!n) 1797 return NULL; 1798 entry = rb_entry(n, struct btrfs_free_space, offset_index); 1799 if (entry->bitmap) { 1800 if (entry->offset + BITS_PER_BITMAP * unit > offset) 1801 break; 1802 } else { 1803 if (entry->offset + entry->bytes > offset) 1804 break; 1805 } 1806 } 1807 return entry; 1808 } 1809 1810 static inline void unlink_free_space(struct btrfs_free_space_ctl *ctl, 1811 struct btrfs_free_space *info, 1812 bool update_stat) 1813 { 1814 lockdep_assert_held(&ctl->tree_lock); 1815 1816 rb_erase(&info->offset_index, &ctl->free_space_offset); 1817 rb_erase_cached(&info->bytes_index, &ctl->free_space_bytes); 1818 ctl->free_extents--; 1819 1820 if (!info->bitmap && !btrfs_free_space_trimmed(info)) { 1821 ctl->discardable_extents[BTRFS_STAT_CURR]--; 1822 ctl->discardable_bytes[BTRFS_STAT_CURR] -= info->bytes; 1823 } 1824 1825 if (update_stat) 1826 ctl->free_space -= info->bytes; 1827 } 1828 1829 static int link_free_space(struct btrfs_free_space_ctl *ctl, 1830 struct btrfs_free_space *info) 1831 { 1832 int ret = 0; 1833 1834 lockdep_assert_held(&ctl->tree_lock); 1835 1836 ASSERT(info->bytes || info->bitmap); 1837 ret = tree_insert_offset(ctl, NULL, info); 1838 if (ret) 1839 return ret; 1840 1841 rb_add_cached(&info->bytes_index, &ctl->free_space_bytes, entry_less); 1842 1843 if (!info->bitmap && !btrfs_free_space_trimmed(info)) { 1844 ctl->discardable_extents[BTRFS_STAT_CURR]++; 1845 ctl->discardable_bytes[BTRFS_STAT_CURR] += info->bytes; 1846 } 1847 1848 ctl->free_space += info->bytes; 1849 ctl->free_extents++; 1850 return ret; 1851 } 1852 1853 static void relink_bitmap_entry(struct btrfs_free_space_ctl *ctl, 1854 struct btrfs_free_space *info) 1855 { 1856 ASSERT(info->bitmap); 1857 1858 /* 1859 * If our entry is empty it's because we're on a cluster and we don't 1860 * want to re-link it into our ctl bytes index. 1861 */ 1862 if (RB_EMPTY_NODE(&info->bytes_index)) 1863 return; 1864 1865 lockdep_assert_held(&ctl->tree_lock); 1866 1867 rb_erase_cached(&info->bytes_index, &ctl->free_space_bytes); 1868 rb_add_cached(&info->bytes_index, &ctl->free_space_bytes, entry_less); 1869 } 1870 1871 static inline void bitmap_clear_bits(struct btrfs_free_space_ctl *ctl, 1872 struct btrfs_free_space *info, 1873 u64 offset, u64 bytes, bool update_stat) 1874 { 1875 const int unit = ctl->block_group->fs_info->sectorsize; 1876 unsigned long start, count, end; 1877 int extent_delta = -1; 1878 1879 start = offset_to_bit(info->offset, unit, offset); 1880 count = bytes_to_bits(bytes, unit); 1881 end = start + count; 1882 ASSERT(end <= BITS_PER_BITMAP); 1883 1884 bitmap_clear(info->bitmap, start, count); 1885 1886 info->bytes -= bytes; 1887 if (info->max_extent_size > unit) 1888 info->max_extent_size = 0; 1889 1890 relink_bitmap_entry(ctl, info); 1891 1892 if (start && test_bit(start - 1, info->bitmap)) 1893 extent_delta++; 1894 1895 if (end < BITS_PER_BITMAP && test_bit(end, info->bitmap)) 1896 extent_delta++; 1897 1898 info->bitmap_extents += extent_delta; 1899 if (!btrfs_free_space_trimmed(info)) { 1900 ctl->discardable_extents[BTRFS_STAT_CURR] += extent_delta; 1901 ctl->discardable_bytes[BTRFS_STAT_CURR] -= bytes; 1902 } 1903 1904 if (update_stat) 1905 ctl->free_space -= bytes; 1906 } 1907 1908 static void btrfs_bitmap_set_bits(struct btrfs_free_space_ctl *ctl, 1909 struct btrfs_free_space *info, u64 offset, 1910 u64 bytes) 1911 { 1912 const int unit = ctl->block_group->fs_info->sectorsize; 1913 unsigned long start, count, end; 1914 int extent_delta = 1; 1915 1916 start = offset_to_bit(info->offset, unit, offset); 1917 count = bytes_to_bits(bytes, unit); 1918 end = start + count; 1919 ASSERT(end <= BITS_PER_BITMAP); 1920 1921 bitmap_set(info->bitmap, start, count); 1922 1923 /* 1924 * We set some bytes, we have no idea what the max extent size is 1925 * anymore. 1926 */ 1927 info->max_extent_size = 0; 1928 info->bytes += bytes; 1929 ctl->free_space += bytes; 1930 1931 relink_bitmap_entry(ctl, info); 1932 1933 if (start && test_bit(start - 1, info->bitmap)) 1934 extent_delta--; 1935 1936 if (end < BITS_PER_BITMAP && test_bit(end, info->bitmap)) 1937 extent_delta--; 1938 1939 info->bitmap_extents += extent_delta; 1940 if (!btrfs_free_space_trimmed(info)) { 1941 ctl->discardable_extents[BTRFS_STAT_CURR] += extent_delta; 1942 ctl->discardable_bytes[BTRFS_STAT_CURR] += bytes; 1943 } 1944 } 1945 1946 /* 1947 * If we can not find suitable extent, we will use bytes to record 1948 * the size of the max extent. 1949 */ 1950 static int search_bitmap(struct btrfs_free_space_ctl *ctl, 1951 struct btrfs_free_space *bitmap_info, u64 *offset, 1952 u64 *bytes, bool for_alloc) 1953 { 1954 const int unit = ctl->block_group->fs_info->sectorsize; 1955 unsigned long found_bits = 0; 1956 unsigned long max_bits = 0; 1957 unsigned long bits, i; 1958 unsigned long next_zero; 1959 unsigned long extent_bits; 1960 1961 /* 1962 * Skip searching the bitmap if we don't have a contiguous section that 1963 * is large enough for this allocation. 1964 */ 1965 if (for_alloc && 1966 bitmap_info->max_extent_size && 1967 bitmap_info->max_extent_size < *bytes) { 1968 *bytes = bitmap_info->max_extent_size; 1969 return -1; 1970 } 1971 1972 i = offset_to_bit(bitmap_info->offset, unit, 1973 max_t(u64, *offset, bitmap_info->offset)); 1974 bits = bytes_to_bits(*bytes, unit); 1975 1976 for_each_set_bit_from(i, bitmap_info->bitmap, BITS_PER_BITMAP) { 1977 if (for_alloc && bits == 1) { 1978 found_bits = 1; 1979 break; 1980 } 1981 next_zero = find_next_zero_bit(bitmap_info->bitmap, 1982 BITS_PER_BITMAP, i); 1983 extent_bits = next_zero - i; 1984 if (extent_bits >= bits) { 1985 found_bits = extent_bits; 1986 break; 1987 } else if (extent_bits > max_bits) { 1988 max_bits = extent_bits; 1989 } 1990 i = next_zero; 1991 } 1992 1993 if (found_bits) { 1994 *offset = (u64)(i * unit) + bitmap_info->offset; 1995 *bytes = (u64)(found_bits) * unit; 1996 return 0; 1997 } 1998 1999 *bytes = (u64)(max_bits) * unit; 2000 bitmap_info->max_extent_size = *bytes; 2001 relink_bitmap_entry(ctl, bitmap_info); 2002 return -1; 2003 } 2004 2005 /* Cache the size of the max extent in bytes */ 2006 static struct btrfs_free_space * 2007 find_free_space(struct btrfs_free_space_ctl *ctl, u64 *offset, u64 *bytes, 2008 unsigned long align, u64 *max_extent_size, bool use_bytes_index) 2009 { 2010 struct btrfs_free_space *entry; 2011 struct rb_node *node; 2012 u64 tmp; 2013 u64 align_off; 2014 int ret; 2015 2016 if (!ctl->free_space_offset.rb_node) 2017 return NULL; 2018 again: 2019 if (use_bytes_index) { 2020 node = rb_first_cached(&ctl->free_space_bytes); 2021 } else { 2022 entry = tree_search_offset(ctl, offset_to_bitmap(ctl, *offset), 2023 0, 1); 2024 if (!entry) 2025 return NULL; 2026 node = &entry->offset_index; 2027 } 2028 2029 for (; node; node = rb_next(node)) { 2030 if (use_bytes_index) 2031 entry = rb_entry(node, struct btrfs_free_space, 2032 bytes_index); 2033 else 2034 entry = rb_entry(node, struct btrfs_free_space, 2035 offset_index); 2036 2037 /* 2038 * If we are using the bytes index then all subsequent entries 2039 * in this tree are going to be < bytes, so simply set the max 2040 * extent size and exit the loop. 2041 * 2042 * If we're using the offset index then we need to keep going 2043 * through the rest of the tree. 2044 */ 2045 if (entry->bytes < *bytes) { 2046 *max_extent_size = max(get_max_extent_size(entry), 2047 *max_extent_size); 2048 if (use_bytes_index) 2049 break; 2050 continue; 2051 } 2052 2053 /* make sure the space returned is big enough 2054 * to match our requested alignment 2055 */ 2056 if (*bytes >= align) { 2057 tmp = entry->offset - ctl->block_group->start + align - 1; 2058 tmp = div64_u64(tmp, align); 2059 tmp = tmp * align + ctl->block_group->start; 2060 align_off = tmp - entry->offset; 2061 } else { 2062 align_off = 0; 2063 tmp = entry->offset; 2064 } 2065 2066 /* 2067 * We don't break here if we're using the bytes index because we 2068 * may have another entry that has the correct alignment that is 2069 * the right size, so we don't want to miss that possibility. 2070 * At worst this adds another loop through the logic, but if we 2071 * broke here we could prematurely ENOSPC. 2072 */ 2073 if (entry->bytes < *bytes + align_off) { 2074 *max_extent_size = max(get_max_extent_size(entry), 2075 *max_extent_size); 2076 continue; 2077 } 2078 2079 if (entry->bitmap) { 2080 struct rb_node *old_next = rb_next(node); 2081 u64 size = *bytes; 2082 2083 ret = search_bitmap(ctl, entry, &tmp, &size, true); 2084 if (!ret) { 2085 *offset = tmp; 2086 *bytes = size; 2087 return entry; 2088 } else { 2089 *max_extent_size = 2090 max(get_max_extent_size(entry), 2091 *max_extent_size); 2092 } 2093 2094 /* 2095 * The bitmap may have gotten re-arranged in the space 2096 * index here because the max_extent_size may have been 2097 * updated. Start from the beginning again if this 2098 * happened. 2099 */ 2100 if (use_bytes_index && old_next != rb_next(node)) 2101 goto again; 2102 continue; 2103 } 2104 2105 *offset = tmp; 2106 *bytes = entry->bytes - align_off; 2107 return entry; 2108 } 2109 2110 return NULL; 2111 } 2112 2113 static void add_new_bitmap(struct btrfs_free_space_ctl *ctl, 2114 struct btrfs_free_space *info, u64 offset) 2115 { 2116 info->offset = offset_to_bitmap(ctl, offset); 2117 info->bytes = 0; 2118 info->bitmap_extents = 0; 2119 INIT_LIST_HEAD(&info->list); 2120 link_free_space(ctl, info); 2121 ctl->total_bitmaps++; 2122 recalculate_thresholds(ctl); 2123 } 2124 2125 static void free_bitmap(struct btrfs_free_space_ctl *ctl, 2126 struct btrfs_free_space *bitmap_info) 2127 { 2128 /* 2129 * Normally when this is called, the bitmap is completely empty. However, 2130 * if we are blowing up the free space cache for one reason or another 2131 * via __btrfs_remove_free_space_cache(), then it may not be freed and 2132 * we may leave stats on the table. 2133 */ 2134 if (bitmap_info->bytes && !btrfs_free_space_trimmed(bitmap_info)) { 2135 ctl->discardable_extents[BTRFS_STAT_CURR] -= 2136 bitmap_info->bitmap_extents; 2137 ctl->discardable_bytes[BTRFS_STAT_CURR] -= bitmap_info->bytes; 2138 2139 } 2140 unlink_free_space(ctl, bitmap_info, true); 2141 kmem_cache_free(btrfs_free_space_bitmap_cachep, bitmap_info->bitmap); 2142 kmem_cache_free(btrfs_free_space_cachep, bitmap_info); 2143 ctl->total_bitmaps--; 2144 recalculate_thresholds(ctl); 2145 } 2146 2147 static noinline int remove_from_bitmap(struct btrfs_free_space_ctl *ctl, 2148 struct btrfs_free_space *bitmap_info, 2149 u64 *offset, u64 *bytes) 2150 { 2151 const int unit = ctl->block_group->fs_info->sectorsize; 2152 u64 end; 2153 u64 search_start, search_bytes; 2154 int ret; 2155 2156 again: 2157 end = bitmap_info->offset + (u64)(BITS_PER_BITMAP * unit) - 1; 2158 2159 /* 2160 * We need to search for bits in this bitmap. We could only cover some 2161 * of the extent in this bitmap thanks to how we add space, so we need 2162 * to search for as much as it as we can and clear that amount, and then 2163 * go searching for the next bit. 2164 */ 2165 search_start = *offset; 2166 search_bytes = unit; 2167 search_bytes = min(search_bytes, end - search_start + 1); 2168 ret = search_bitmap(ctl, bitmap_info, &search_start, &search_bytes, 2169 false); 2170 if (ret < 0 || search_start != *offset) 2171 return -EINVAL; 2172 2173 /* We may have found more bits than what we need */ 2174 search_bytes = min(search_bytes, *bytes); 2175 2176 /* Cannot clear past the end of the bitmap */ 2177 search_bytes = min(search_bytes, end - search_start + 1); 2178 2179 bitmap_clear_bits(ctl, bitmap_info, search_start, search_bytes, true); 2180 *offset += search_bytes; 2181 *bytes -= search_bytes; 2182 2183 if (*bytes) { 2184 struct rb_node *next = rb_next(&bitmap_info->offset_index); 2185 if (!bitmap_info->bytes) 2186 free_bitmap(ctl, bitmap_info); 2187 2188 /* 2189 * no entry after this bitmap, but we still have bytes to 2190 * remove, so something has gone wrong. 2191 */ 2192 if (!next) 2193 return -EINVAL; 2194 2195 bitmap_info = rb_entry(next, struct btrfs_free_space, 2196 offset_index); 2197 2198 /* 2199 * if the next entry isn't a bitmap we need to return to let the 2200 * extent stuff do its work. 2201 */ 2202 if (!bitmap_info->bitmap) 2203 return -EAGAIN; 2204 2205 /* 2206 * Ok the next item is a bitmap, but it may not actually hold 2207 * the information for the rest of this free space stuff, so 2208 * look for it, and if we don't find it return so we can try 2209 * everything over again. 2210 */ 2211 search_start = *offset; 2212 search_bytes = unit; 2213 ret = search_bitmap(ctl, bitmap_info, &search_start, 2214 &search_bytes, false); 2215 if (ret < 0 || search_start != *offset) 2216 return -EAGAIN; 2217 2218 goto again; 2219 } else if (!bitmap_info->bytes) 2220 free_bitmap(ctl, bitmap_info); 2221 2222 return 0; 2223 } 2224 2225 static u64 add_bytes_to_bitmap(struct btrfs_free_space_ctl *ctl, 2226 struct btrfs_free_space *info, u64 offset, 2227 u64 bytes, enum btrfs_trim_state trim_state) 2228 { 2229 const int unit = ctl->block_group->fs_info->sectorsize; 2230 u64 bytes_to_set = 0; 2231 u64 end; 2232 2233 /* 2234 * This is a tradeoff to make bitmap trim state minimal. We mark the 2235 * whole bitmap untrimmed if at any point we add untrimmed regions. 2236 */ 2237 if (trim_state == BTRFS_TRIM_STATE_UNTRIMMED) { 2238 if (btrfs_free_space_trimmed(info)) { 2239 ctl->discardable_extents[BTRFS_STAT_CURR] += 2240 info->bitmap_extents; 2241 ctl->discardable_bytes[BTRFS_STAT_CURR] += info->bytes; 2242 } 2243 info->trim_state = BTRFS_TRIM_STATE_UNTRIMMED; 2244 } 2245 2246 end = info->offset + (u64)(BITS_PER_BITMAP * unit); 2247 2248 bytes_to_set = min(end - offset, bytes); 2249 2250 btrfs_bitmap_set_bits(ctl, info, offset, bytes_to_set); 2251 2252 return bytes_to_set; 2253 2254 } 2255 2256 EXPORT_FOR_TESTS 2257 bool btrfs_use_bitmap(struct btrfs_free_space_ctl *ctl, 2258 struct btrfs_free_space *info) 2259 { 2260 struct btrfs_block_group *block_group = ctl->block_group; 2261 struct btrfs_fs_info *fs_info = block_group->fs_info; 2262 bool forced = false; 2263 2264 #ifdef CONFIG_BTRFS_DEBUG 2265 if (btrfs_should_fragment_free_space(block_group)) 2266 forced = true; 2267 #endif 2268 2269 /* This is a way to reclaim large regions from the bitmaps. */ 2270 if (!forced && info->bytes >= FORCE_EXTENT_THRESHOLD) 2271 return false; 2272 2273 /* 2274 * If we are below the extents threshold then we can add this as an 2275 * extent, and don't have to deal with the bitmap 2276 */ 2277 if (!forced && ctl->free_extents < ctl->extents_thresh) { 2278 /* 2279 * If this block group has some small extents we don't want to 2280 * use up all of our free slots in the cache with them, we want 2281 * to reserve them to larger extents, however if we have plenty 2282 * of cache left then go ahead and add them, no sense in adding 2283 * the overhead of a bitmap if we don't have to. 2284 */ 2285 if (info->bytes <= fs_info->sectorsize * 8) { 2286 if (ctl->free_extents * 3 <= ctl->extents_thresh) 2287 return false; 2288 } else { 2289 return false; 2290 } 2291 } 2292 2293 /* 2294 * The original block groups from mkfs can be really small, like 8 2295 * megabytes, so don't bother with a bitmap for those entries. However 2296 * some block groups can be smaller than what a bitmap would cover but 2297 * are still large enough that they could overflow the 32k memory limit, 2298 * so allow those block groups to still be allowed to have a bitmap 2299 * entry. 2300 */ 2301 if (((BITS_PER_BITMAP * fs_info->sectorsize) >> 1) > block_group->length) 2302 return false; 2303 2304 return true; 2305 } 2306 2307 static int insert_into_bitmap(struct btrfs_free_space_ctl *ctl, 2308 struct btrfs_free_space *info) 2309 { 2310 struct btrfs_free_space *bitmap_info; 2311 struct btrfs_block_group *block_group = ctl->block_group; 2312 bool added = false; 2313 u64 bytes, offset, bytes_added; 2314 enum btrfs_trim_state trim_state; 2315 int ret; 2316 2317 bytes = info->bytes; 2318 offset = info->offset; 2319 trim_state = info->trim_state; 2320 2321 if (btrfs_is_testing(block_group->fs_info)) { 2322 if (!block_group->fs_info->use_bitmap(ctl, info)) 2323 return 0; 2324 } else { 2325 if (!btrfs_use_bitmap(ctl, info)) 2326 return 0; 2327 } 2328 again: 2329 /* 2330 * Since we link bitmaps right into the cluster we need to see if we 2331 * have a cluster here, and if so and it has our bitmap we need to add 2332 * the free space to that bitmap. 2333 */ 2334 if (!list_empty(&block_group->cluster_list)) { 2335 struct btrfs_free_cluster *cluster; 2336 struct rb_node *node; 2337 struct btrfs_free_space *entry; 2338 2339 cluster = list_first_entry(&block_group->cluster_list, 2340 struct btrfs_free_cluster, block_group_list); 2341 spin_lock(&cluster->lock); 2342 node = rb_first(&cluster->root); 2343 if (!node) { 2344 spin_unlock(&cluster->lock); 2345 goto no_cluster_bitmap; 2346 } 2347 2348 entry = rb_entry(node, struct btrfs_free_space, offset_index); 2349 if (!entry->bitmap) { 2350 spin_unlock(&cluster->lock); 2351 goto no_cluster_bitmap; 2352 } 2353 2354 if (entry->offset == offset_to_bitmap(ctl, offset)) { 2355 bytes_added = add_bytes_to_bitmap(ctl, entry, offset, 2356 bytes, trim_state); 2357 bytes -= bytes_added; 2358 offset += bytes_added; 2359 } 2360 spin_unlock(&cluster->lock); 2361 if (!bytes) { 2362 ret = 1; 2363 goto out; 2364 } 2365 } 2366 2367 no_cluster_bitmap: 2368 bitmap_info = tree_search_offset(ctl, offset_to_bitmap(ctl, offset), 2369 1, 0); 2370 if (!bitmap_info) { 2371 ASSERT(!added); 2372 goto new_bitmap; 2373 } 2374 2375 bytes_added = add_bytes_to_bitmap(ctl, bitmap_info, offset, bytes, 2376 trim_state); 2377 bytes -= bytes_added; 2378 offset += bytes_added; 2379 added = false; 2380 2381 if (!bytes) { 2382 ret = 1; 2383 goto out; 2384 } else 2385 goto again; 2386 2387 new_bitmap: 2388 if (info && info->bitmap) { 2389 add_new_bitmap(ctl, info, offset); 2390 added = true; 2391 info = NULL; 2392 goto again; 2393 } else { 2394 spin_unlock(&ctl->tree_lock); 2395 2396 /* no pre-allocated info, allocate a new one */ 2397 if (!info) { 2398 info = kmem_cache_zalloc(btrfs_free_space_cachep, 2399 GFP_NOFS); 2400 if (!info) { 2401 spin_lock(&ctl->tree_lock); 2402 ret = -ENOMEM; 2403 goto out; 2404 } 2405 } 2406 2407 /* allocate the bitmap */ 2408 info->bitmap = kmem_cache_zalloc(btrfs_free_space_bitmap_cachep, 2409 GFP_NOFS); 2410 info->trim_state = BTRFS_TRIM_STATE_TRIMMED; 2411 spin_lock(&ctl->tree_lock); 2412 if (!info->bitmap) { 2413 ret = -ENOMEM; 2414 goto out; 2415 } 2416 goto again; 2417 } 2418 2419 out: 2420 if (info) { 2421 if (info->bitmap) 2422 kmem_cache_free(btrfs_free_space_bitmap_cachep, 2423 info->bitmap); 2424 kmem_cache_free(btrfs_free_space_cachep, info); 2425 } 2426 2427 return ret; 2428 } 2429 2430 /* 2431 * Free space merging rules: 2432 * 1) Merge trimmed areas together 2433 * 2) Let untrimmed areas coalesce with trimmed areas 2434 * 3) Always pull neighboring regions from bitmaps 2435 * 2436 * The above rules are for when we merge free space based on btrfs_trim_state. 2437 * Rules 2 and 3 are subtle because they are suboptimal, but are done for the 2438 * same reason: to promote larger extent regions which makes life easier for 2439 * find_free_extent(). Rule 2 enables coalescing based on the common path 2440 * being returning free space from btrfs_finish_extent_commit(). So when free 2441 * space is trimmed, it will prevent aggregating trimmed new region and 2442 * untrimmed regions in the rb_tree. Rule 3 is purely to obtain larger extents 2443 * and provide find_free_extent() with the largest extents possible hoping for 2444 * the reuse path. 2445 */ 2446 static bool try_merge_free_space(struct btrfs_free_space_ctl *ctl, 2447 struct btrfs_free_space *info, bool update_stat) 2448 { 2449 struct btrfs_free_space *left_info = NULL; 2450 struct btrfs_free_space *right_info; 2451 bool merged = false; 2452 u64 offset = info->offset; 2453 u64 bytes = info->bytes; 2454 const bool is_trimmed = btrfs_free_space_trimmed(info); 2455 struct rb_node *right_prev = NULL; 2456 2457 /* 2458 * first we want to see if there is free space adjacent to the range we 2459 * are adding, if there is remove that struct and add a new one to 2460 * cover the entire range 2461 */ 2462 right_info = tree_search_offset(ctl, offset + bytes, 0, 0); 2463 if (right_info) 2464 right_prev = rb_prev(&right_info->offset_index); 2465 2466 if (right_prev) 2467 left_info = rb_entry(right_prev, struct btrfs_free_space, offset_index); 2468 else if (!right_info) 2469 left_info = tree_search_offset(ctl, offset - 1, 0, 0); 2470 2471 /* See try_merge_free_space() comment. */ 2472 if (right_info && !right_info->bitmap && 2473 (!is_trimmed || btrfs_free_space_trimmed(right_info))) { 2474 unlink_free_space(ctl, right_info, update_stat); 2475 info->bytes += right_info->bytes; 2476 kmem_cache_free(btrfs_free_space_cachep, right_info); 2477 merged = true; 2478 } 2479 2480 /* See try_merge_free_space() comment. */ 2481 if (left_info && !left_info->bitmap && 2482 left_info->offset + left_info->bytes == offset && 2483 (!is_trimmed || btrfs_free_space_trimmed(left_info))) { 2484 unlink_free_space(ctl, left_info, update_stat); 2485 info->offset = left_info->offset; 2486 info->bytes += left_info->bytes; 2487 kmem_cache_free(btrfs_free_space_cachep, left_info); 2488 merged = true; 2489 } 2490 2491 return merged; 2492 } 2493 2494 static bool steal_from_bitmap_to_end(struct btrfs_free_space_ctl *ctl, 2495 struct btrfs_free_space *info, 2496 bool update_stat) 2497 { 2498 const int unit = ctl->block_group->fs_info->sectorsize; 2499 struct btrfs_free_space *bitmap; 2500 unsigned long i; 2501 unsigned long j; 2502 const u64 end = info->offset + info->bytes; 2503 const u64 bitmap_offset = offset_to_bitmap(ctl, end); 2504 u64 bytes; 2505 2506 bitmap = tree_search_offset(ctl, bitmap_offset, 1, 0); 2507 if (!bitmap) 2508 return false; 2509 2510 i = offset_to_bit(bitmap->offset, unit, end); 2511 j = find_next_zero_bit(bitmap->bitmap, BITS_PER_BITMAP, i); 2512 if (j == i) 2513 return false; 2514 bytes = (j - i) * unit; 2515 info->bytes += bytes; 2516 2517 /* See try_merge_free_space() comment. */ 2518 if (!btrfs_free_space_trimmed(bitmap)) 2519 info->trim_state = BTRFS_TRIM_STATE_UNTRIMMED; 2520 2521 bitmap_clear_bits(ctl, bitmap, end, bytes, update_stat); 2522 2523 if (!bitmap->bytes) 2524 free_bitmap(ctl, bitmap); 2525 2526 return true; 2527 } 2528 2529 static bool steal_from_bitmap_to_front(struct btrfs_free_space_ctl *ctl, 2530 struct btrfs_free_space *info, 2531 bool update_stat) 2532 { 2533 const int unit = ctl->block_group->fs_info->sectorsize; 2534 struct btrfs_free_space *bitmap; 2535 u64 bitmap_offset; 2536 unsigned long i; 2537 unsigned long j; 2538 unsigned long prev_j; 2539 u64 bytes; 2540 2541 bitmap_offset = offset_to_bitmap(ctl, info->offset); 2542 /* If we're on a boundary, try the previous logical bitmap. */ 2543 if (bitmap_offset == info->offset) { 2544 if (info->offset == 0) 2545 return false; 2546 bitmap_offset = offset_to_bitmap(ctl, info->offset - 1); 2547 } 2548 2549 bitmap = tree_search_offset(ctl, bitmap_offset, 1, 0); 2550 if (!bitmap) 2551 return false; 2552 2553 i = offset_to_bit(bitmap->offset, unit, info->offset) - 1; 2554 j = 0; 2555 prev_j = (unsigned long)-1; 2556 for_each_clear_bit_from(j, bitmap->bitmap, BITS_PER_BITMAP) { 2557 if (j > i) 2558 break; 2559 prev_j = j; 2560 } 2561 if (prev_j == i) 2562 return false; 2563 2564 if (prev_j == (unsigned long)-1) 2565 bytes = (i + 1) * unit; 2566 else 2567 bytes = (i - prev_j) * unit; 2568 2569 info->offset -= bytes; 2570 info->bytes += bytes; 2571 2572 /* See try_merge_free_space() comment. */ 2573 if (!btrfs_free_space_trimmed(bitmap)) 2574 info->trim_state = BTRFS_TRIM_STATE_UNTRIMMED; 2575 2576 bitmap_clear_bits(ctl, bitmap, info->offset, bytes, update_stat); 2577 2578 if (!bitmap->bytes) 2579 free_bitmap(ctl, bitmap); 2580 2581 return true; 2582 } 2583 2584 /* 2585 * We prefer always to allocate from extent entries, both for clustered and 2586 * non-clustered allocation requests. So when attempting to add a new extent 2587 * entry, try to see if there's adjacent free space in bitmap entries, and if 2588 * there is, migrate that space from the bitmaps to the extent. 2589 * Like this we get better chances of satisfying space allocation requests 2590 * because we attempt to satisfy them based on a single cache entry, and never 2591 * on 2 or more entries - even if the entries represent a contiguous free space 2592 * region (e.g. 1 extent entry + 1 bitmap entry starting where the extent entry 2593 * ends). 2594 */ 2595 static void steal_from_bitmap(struct btrfs_free_space_ctl *ctl, 2596 struct btrfs_free_space *info, 2597 bool update_stat) 2598 { 2599 /* 2600 * Only work with disconnected entries, as we can change their offset, 2601 * and must be extent entries. 2602 */ 2603 ASSERT(!info->bitmap); 2604 ASSERT(RB_EMPTY_NODE(&info->offset_index)); 2605 2606 if (ctl->total_bitmaps > 0) { 2607 bool stole_end; 2608 bool stole_front = false; 2609 2610 stole_end = steal_from_bitmap_to_end(ctl, info, update_stat); 2611 if (ctl->total_bitmaps > 0) 2612 stole_front = steal_from_bitmap_to_front(ctl, info, 2613 update_stat); 2614 2615 if (stole_end || stole_front) 2616 try_merge_free_space(ctl, info, update_stat); 2617 } 2618 } 2619 2620 static int __btrfs_add_free_space(struct btrfs_block_group *block_group, 2621 u64 offset, u64 bytes, 2622 enum btrfs_trim_state trim_state) 2623 { 2624 struct btrfs_fs_info *fs_info = block_group->fs_info; 2625 struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl; 2626 struct btrfs_free_space *info; 2627 int ret = 0; 2628 u64 filter_bytes = bytes; 2629 2630 ASSERT(!btrfs_is_zoned(fs_info)); 2631 2632 info = kmem_cache_zalloc(btrfs_free_space_cachep, GFP_NOFS); 2633 if (!info) 2634 return -ENOMEM; 2635 2636 info->offset = offset; 2637 info->bytes = bytes; 2638 info->trim_state = trim_state; 2639 RB_CLEAR_NODE(&info->offset_index); 2640 RB_CLEAR_NODE(&info->bytes_index); 2641 2642 spin_lock(&ctl->tree_lock); 2643 2644 if (try_merge_free_space(ctl, info, true)) 2645 goto link; 2646 2647 /* 2648 * There was no extent directly to the left or right of this new 2649 * extent then we know we're going to have to allocate a new extent, so 2650 * before we do that see if we need to drop this into a bitmap 2651 */ 2652 ret = insert_into_bitmap(ctl, info); 2653 if (ret < 0) { 2654 goto out; 2655 } else if (ret) { 2656 ret = 0; 2657 goto out; 2658 } 2659 link: 2660 /* 2661 * Only steal free space from adjacent bitmaps if we're sure we're not 2662 * going to add the new free space to existing bitmap entries - because 2663 * that would mean unnecessary work that would be reverted. Therefore 2664 * attempt to steal space from bitmaps if we're adding an extent entry. 2665 */ 2666 steal_from_bitmap(ctl, info, true); 2667 2668 filter_bytes = max(filter_bytes, info->bytes); 2669 2670 ret = link_free_space(ctl, info); 2671 if (ret) 2672 kmem_cache_free(btrfs_free_space_cachep, info); 2673 out: 2674 btrfs_discard_update_discardable(block_group); 2675 spin_unlock(&ctl->tree_lock); 2676 2677 if (ret) { 2678 btrfs_crit(fs_info, "unable to add free space :%d", ret); 2679 ASSERT(ret != -EEXIST); 2680 } 2681 2682 if (trim_state != BTRFS_TRIM_STATE_TRIMMED) { 2683 btrfs_discard_check_filter(block_group, filter_bytes); 2684 btrfs_discard_queue_work(&fs_info->discard_ctl, block_group); 2685 } 2686 2687 return ret; 2688 } 2689 2690 static int __btrfs_add_free_space_zoned(struct btrfs_block_group *block_group, 2691 u64 bytenr, u64 size, bool used) 2692 { 2693 struct btrfs_space_info *sinfo = block_group->space_info; 2694 struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl; 2695 u64 offset = bytenr - block_group->start; 2696 u64 to_free, to_unusable; 2697 int bg_reclaim_threshold = 0; 2698 bool initial; 2699 u64 reclaimable_unusable; 2700 2701 spin_lock(&block_group->lock); 2702 2703 initial = ((size == block_group->length) && (block_group->alloc_offset == 0)); 2704 WARN_ON(!initial && offset + size > block_group->zone_capacity); 2705 if (!initial) 2706 bg_reclaim_threshold = READ_ONCE(sinfo->bg_reclaim_threshold); 2707 2708 if (!used) 2709 to_free = size; 2710 else if (initial) 2711 to_free = block_group->zone_capacity; 2712 else if (offset >= block_group->alloc_offset) 2713 to_free = size; 2714 else if (offset + size <= block_group->alloc_offset) 2715 to_free = 0; 2716 else 2717 to_free = offset + size - block_group->alloc_offset; 2718 to_unusable = size - to_free; 2719 2720 spin_lock(&ctl->tree_lock); 2721 ctl->free_space += to_free; 2722 spin_unlock(&ctl->tree_lock); 2723 /* 2724 * If the block group is read-only, we should account freed space into 2725 * bytes_readonly. 2726 */ 2727 if (!block_group->ro) { 2728 block_group->zone_unusable += to_unusable; 2729 WARN_ON(block_group->zone_unusable > block_group->length); 2730 } 2731 if (!used) { 2732 block_group->alloc_offset -= size; 2733 } 2734 2735 reclaimable_unusable = block_group->zone_unusable - 2736 (block_group->length - block_group->zone_capacity); 2737 /* All the region is now unusable. Mark it as unused and reclaim */ 2738 if (block_group->zone_unusable == block_group->length) { 2739 btrfs_mark_bg_unused(block_group); 2740 } else if (bg_reclaim_threshold && 2741 reclaimable_unusable >= 2742 mult_perc(block_group->zone_capacity, bg_reclaim_threshold)) { 2743 btrfs_mark_bg_to_reclaim(block_group); 2744 } 2745 2746 spin_unlock(&block_group->lock); 2747 2748 return 0; 2749 } 2750 2751 int btrfs_add_free_space(struct btrfs_block_group *block_group, 2752 u64 bytenr, u64 size) 2753 { 2754 enum btrfs_trim_state trim_state = BTRFS_TRIM_STATE_UNTRIMMED; 2755 2756 if (block_group->flags & BTRFS_BLOCK_GROUP_REMAPPED) 2757 return 0; 2758 2759 if (btrfs_is_zoned(block_group->fs_info)) 2760 return __btrfs_add_free_space_zoned(block_group, bytenr, size, 2761 true); 2762 2763 if (btrfs_test_opt(block_group->fs_info, DISCARD_SYNC)) 2764 trim_state = BTRFS_TRIM_STATE_TRIMMED; 2765 2766 return __btrfs_add_free_space(block_group, bytenr, size, trim_state); 2767 } 2768 2769 int btrfs_add_free_space_unused(struct btrfs_block_group *block_group, 2770 u64 bytenr, u64 size) 2771 { 2772 if (btrfs_is_zoned(block_group->fs_info)) 2773 return __btrfs_add_free_space_zoned(block_group, bytenr, size, 2774 false); 2775 2776 return btrfs_add_free_space(block_group, bytenr, size); 2777 } 2778 2779 /* 2780 * This is a subtle distinction because when adding free space back in general, 2781 * we want it to be added as untrimmed for async. But in the case where we add 2782 * it on loading of a block group, we want to consider it trimmed. 2783 */ 2784 int btrfs_add_free_space_async_trimmed(struct btrfs_block_group *block_group, 2785 u64 bytenr, u64 size) 2786 { 2787 enum btrfs_trim_state trim_state = BTRFS_TRIM_STATE_UNTRIMMED; 2788 2789 if (btrfs_is_zoned(block_group->fs_info)) 2790 return __btrfs_add_free_space_zoned(block_group, bytenr, size, 2791 true); 2792 2793 if (btrfs_test_opt(block_group->fs_info, DISCARD_SYNC) || 2794 btrfs_test_opt(block_group->fs_info, DISCARD_ASYNC)) 2795 trim_state = BTRFS_TRIM_STATE_TRIMMED; 2796 2797 return __btrfs_add_free_space(block_group, bytenr, size, trim_state); 2798 } 2799 2800 int btrfs_remove_free_space(struct btrfs_block_group *block_group, 2801 u64 offset, u64 bytes) 2802 { 2803 struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl; 2804 struct btrfs_free_space *info; 2805 int ret; 2806 bool re_search = false; 2807 2808 if (btrfs_is_zoned(block_group->fs_info)) { 2809 /* 2810 * This can happen with conventional zones when replaying log. 2811 * Since the allocation info of tree-log nodes are not recorded 2812 * to the extent-tree, calculate_alloc_pointer() failed to 2813 * advance the allocation pointer after last allocated tree log 2814 * node blocks. 2815 * 2816 * This function is called from 2817 * btrfs_pin_extent_for_log_replay() when replaying the log. 2818 * Advance the pointer not to overwrite the tree-log nodes. 2819 */ 2820 if (block_group->start + block_group->alloc_offset < 2821 offset + bytes) { 2822 block_group->alloc_offset = 2823 offset + bytes - block_group->start; 2824 } 2825 return 0; 2826 } 2827 2828 spin_lock(&ctl->tree_lock); 2829 2830 again: 2831 ret = 0; 2832 if (!bytes) 2833 goto out_lock; 2834 2835 info = tree_search_offset(ctl, offset, 0, 0); 2836 if (!info) { 2837 /* 2838 * oops didn't find an extent that matched the space we wanted 2839 * to remove, look for a bitmap instead 2840 */ 2841 info = tree_search_offset(ctl, offset_to_bitmap(ctl, offset), 2842 1, 0); 2843 if (!info) { 2844 /* 2845 * If we found a partial bit of our free space in a 2846 * bitmap but then couldn't find the other part this may 2847 * be a problem, so WARN about it. 2848 */ 2849 WARN_ON(re_search); 2850 goto out_lock; 2851 } 2852 } 2853 2854 re_search = false; 2855 if (!info->bitmap) { 2856 unlink_free_space(ctl, info, true); 2857 if (offset == info->offset) { 2858 u64 to_free = min(bytes, info->bytes); 2859 2860 info->bytes -= to_free; 2861 info->offset += to_free; 2862 if (info->bytes) { 2863 ret = link_free_space(ctl, info); 2864 WARN_ON(ret); 2865 } else { 2866 kmem_cache_free(btrfs_free_space_cachep, info); 2867 } 2868 2869 offset += to_free; 2870 bytes -= to_free; 2871 goto again; 2872 } else { 2873 u64 old_end = info->bytes + info->offset; 2874 2875 info->bytes = offset - info->offset; 2876 ret = link_free_space(ctl, info); 2877 WARN_ON(ret); 2878 if (ret) 2879 goto out_lock; 2880 2881 /* Not enough bytes in this entry to satisfy us */ 2882 if (old_end < offset + bytes) { 2883 bytes -= old_end - offset; 2884 offset = old_end; 2885 goto again; 2886 } else if (old_end == offset + bytes) { 2887 /* all done */ 2888 goto out_lock; 2889 } 2890 spin_unlock(&ctl->tree_lock); 2891 2892 ret = __btrfs_add_free_space(block_group, 2893 offset + bytes, 2894 old_end - (offset + bytes), 2895 info->trim_state); 2896 WARN_ON(ret); 2897 return ret; 2898 } 2899 } 2900 2901 ret = remove_from_bitmap(ctl, info, &offset, &bytes); 2902 if (ret == -EAGAIN) { 2903 re_search = true; 2904 goto again; 2905 } 2906 out_lock: 2907 btrfs_discard_update_discardable(block_group); 2908 spin_unlock(&ctl->tree_lock); 2909 2910 return ret; 2911 } 2912 2913 void btrfs_dump_free_space(struct btrfs_block_group *block_group, 2914 u64 bytes) 2915 { 2916 struct btrfs_fs_info *fs_info = block_group->fs_info; 2917 struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl; 2918 struct btrfs_free_space *info; 2919 struct rb_node *n; 2920 int count = 0; 2921 2922 /* 2923 * Zoned btrfs does not use free space tree and cluster. Just print 2924 * out the free space after the allocation offset. 2925 */ 2926 if (btrfs_is_zoned(fs_info)) { 2927 btrfs_info(fs_info, "free space %llu active %d", 2928 block_group->zone_capacity - block_group->alloc_offset, 2929 test_bit(BLOCK_GROUP_FLAG_ZONE_IS_ACTIVE, 2930 &block_group->runtime_flags)); 2931 return; 2932 } 2933 2934 spin_lock(&ctl->tree_lock); 2935 for (n = rb_first(&ctl->free_space_offset); n; n = rb_next(n)) { 2936 info = rb_entry(n, struct btrfs_free_space, offset_index); 2937 if (info->bytes >= bytes && !block_group->ro) 2938 count++; 2939 btrfs_crit(fs_info, "entry offset %llu, bytes %llu, bitmap %s", 2940 info->offset, info->bytes, str_yes_no(info->bitmap)); 2941 } 2942 spin_unlock(&ctl->tree_lock); 2943 btrfs_info(fs_info, "block group has cluster?: %s", 2944 str_no_yes(list_empty(&block_group->cluster_list))); 2945 btrfs_info(fs_info, 2946 "%d free space entries at or bigger than %llu bytes", 2947 count, bytes); 2948 } 2949 2950 void btrfs_init_free_space_ctl(struct btrfs_block_group *block_group, 2951 struct btrfs_free_space_ctl *ctl) 2952 { 2953 spin_lock_init(&ctl->tree_lock); 2954 ctl->block_group = block_group; 2955 ctl->free_space_bytes = RB_ROOT_CACHED; 2956 INIT_LIST_HEAD(&ctl->trimming_ranges); 2957 mutex_init(&ctl->cache_writeout_mutex); 2958 2959 /* 2960 * we only want to have 32k of ram per block group for keeping 2961 * track of free space, and if we pass 1/2 of that we want to 2962 * start converting things over to using bitmaps 2963 */ 2964 ctl->extents_thresh = (SZ_32K / 2) / sizeof(struct btrfs_free_space); 2965 } 2966 2967 /* 2968 * for a given cluster, put all of its extents back into the free 2969 * space cache. If the block group passed doesn't match the block group 2970 * pointed to by the cluster, someone else raced in and freed the 2971 * cluster already. In that case, we just return without changing anything 2972 */ 2973 static void __btrfs_return_cluster_to_free_space( 2974 struct btrfs_block_group *block_group, 2975 struct btrfs_free_cluster *cluster) 2976 { 2977 struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl; 2978 struct rb_node *node; 2979 2980 lockdep_assert_held(&ctl->tree_lock); 2981 2982 spin_lock(&cluster->lock); 2983 if (cluster->block_group != block_group) { 2984 spin_unlock(&cluster->lock); 2985 return; 2986 } 2987 2988 cluster->block_group = NULL; 2989 cluster->window_start = 0; 2990 list_del_init(&cluster->block_group_list); 2991 2992 node = rb_first(&cluster->root); 2993 while (node) { 2994 struct btrfs_free_space *entry; 2995 2996 entry = rb_entry(node, struct btrfs_free_space, offset_index); 2997 node = rb_next(&entry->offset_index); 2998 rb_erase(&entry->offset_index, &cluster->root); 2999 RB_CLEAR_NODE(&entry->offset_index); 3000 3001 if (!entry->bitmap) { 3002 /* Merging treats extents as if they were new */ 3003 if (!btrfs_free_space_trimmed(entry)) { 3004 ctl->discardable_extents[BTRFS_STAT_CURR]--; 3005 ctl->discardable_bytes[BTRFS_STAT_CURR] -= 3006 entry->bytes; 3007 } 3008 3009 try_merge_free_space(ctl, entry, false); 3010 steal_from_bitmap(ctl, entry, false); 3011 3012 /* As we insert directly, update these statistics */ 3013 if (!btrfs_free_space_trimmed(entry)) { 3014 ctl->discardable_extents[BTRFS_STAT_CURR]++; 3015 ctl->discardable_bytes[BTRFS_STAT_CURR] += 3016 entry->bytes; 3017 } 3018 } 3019 tree_insert_offset(ctl, NULL, entry); 3020 rb_add_cached(&entry->bytes_index, &ctl->free_space_bytes, 3021 entry_less); 3022 } 3023 cluster->root = RB_ROOT; 3024 spin_unlock(&cluster->lock); 3025 btrfs_put_block_group(block_group); 3026 } 3027 3028 void btrfs_remove_free_space_cache(struct btrfs_block_group *block_group) 3029 { 3030 struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl; 3031 struct btrfs_free_cluster *cluster; 3032 struct list_head *head; 3033 3034 spin_lock(&ctl->tree_lock); 3035 while ((head = block_group->cluster_list.next) != 3036 &block_group->cluster_list) { 3037 cluster = list_entry(head, struct btrfs_free_cluster, 3038 block_group_list); 3039 3040 WARN_ON(cluster->block_group != block_group); 3041 __btrfs_return_cluster_to_free_space(block_group, cluster); 3042 3043 cond_resched_lock(&ctl->tree_lock); 3044 } 3045 __btrfs_remove_free_space_cache(ctl); 3046 btrfs_discard_update_discardable(block_group); 3047 spin_unlock(&ctl->tree_lock); 3048 3049 } 3050 3051 /* 3052 * Walk @block_group's free space rb_tree to determine if everything is trimmed. 3053 */ 3054 bool btrfs_is_free_space_trimmed(struct btrfs_block_group *block_group) 3055 { 3056 struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl; 3057 struct btrfs_free_space *info; 3058 struct rb_node *node; 3059 bool ret = true; 3060 3061 if (block_group->flags & BTRFS_BLOCK_GROUP_REMAPPED && 3062 !test_bit(BLOCK_GROUP_FLAG_STRIPE_REMOVAL_PENDING, &block_group->runtime_flags) && 3063 block_group->identity_remap_count == 0) { 3064 return true; 3065 } 3066 3067 spin_lock(&ctl->tree_lock); 3068 node = rb_first(&ctl->free_space_offset); 3069 3070 while (node) { 3071 info = rb_entry(node, struct btrfs_free_space, offset_index); 3072 3073 if (!btrfs_free_space_trimmed(info)) { 3074 ret = false; 3075 break; 3076 } 3077 3078 node = rb_next(node); 3079 } 3080 3081 spin_unlock(&ctl->tree_lock); 3082 return ret; 3083 } 3084 3085 u64 btrfs_find_space_for_alloc(struct btrfs_block_group *block_group, 3086 u64 offset, u64 bytes, u64 empty_size, 3087 u64 *max_extent_size) 3088 { 3089 struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl; 3090 struct btrfs_discard_ctl *discard_ctl = 3091 &block_group->fs_info->discard_ctl; 3092 struct btrfs_free_space *entry = NULL; 3093 u64 bytes_search = bytes + empty_size; 3094 u64 ret = 0; 3095 u64 align_gap = 0; 3096 u64 align_gap_len = 0; 3097 enum btrfs_trim_state align_gap_trim_state = BTRFS_TRIM_STATE_UNTRIMMED; 3098 bool use_bytes_index = (offset == block_group->start); 3099 3100 ASSERT(!btrfs_is_zoned(block_group->fs_info)); 3101 3102 spin_lock(&ctl->tree_lock); 3103 entry = find_free_space(ctl, &offset, &bytes_search, 3104 block_group->full_stripe_len, max_extent_size, 3105 use_bytes_index); 3106 if (!entry) 3107 goto out; 3108 3109 ret = offset; 3110 if (entry->bitmap) { 3111 bitmap_clear_bits(ctl, entry, offset, bytes, true); 3112 3113 if (!btrfs_free_space_trimmed(entry)) 3114 atomic64_add(bytes, &discard_ctl->discard_bytes_saved); 3115 3116 if (!entry->bytes) 3117 free_bitmap(ctl, entry); 3118 } else { 3119 unlink_free_space(ctl, entry, true); 3120 align_gap_len = offset - entry->offset; 3121 align_gap = entry->offset; 3122 align_gap_trim_state = entry->trim_state; 3123 3124 if (!btrfs_free_space_trimmed(entry)) 3125 atomic64_add(bytes, &discard_ctl->discard_bytes_saved); 3126 3127 entry->offset = offset + bytes; 3128 WARN_ON(entry->bytes < bytes + align_gap_len); 3129 3130 entry->bytes -= bytes + align_gap_len; 3131 if (!entry->bytes) 3132 kmem_cache_free(btrfs_free_space_cachep, entry); 3133 else 3134 link_free_space(ctl, entry); 3135 } 3136 out: 3137 btrfs_discard_update_discardable(block_group); 3138 spin_unlock(&ctl->tree_lock); 3139 3140 if (align_gap_len) 3141 __btrfs_add_free_space(block_group, align_gap, align_gap_len, 3142 align_gap_trim_state); 3143 return ret; 3144 } 3145 3146 /* 3147 * given a cluster, put all of its extents back into the free space 3148 * cache. If a block group is passed, this function will only free 3149 * a cluster that belongs to the passed block group. 3150 * 3151 * Otherwise, it'll get a reference on the block group pointed to by the 3152 * cluster and remove the cluster from it. 3153 */ 3154 void btrfs_return_cluster_to_free_space( 3155 struct btrfs_block_group *block_group, 3156 struct btrfs_free_cluster *cluster) 3157 { 3158 struct btrfs_free_space_ctl *ctl; 3159 3160 /* first, get a safe pointer to the block group */ 3161 spin_lock(&cluster->lock); 3162 if (!block_group) { 3163 block_group = cluster->block_group; 3164 if (!block_group) { 3165 spin_unlock(&cluster->lock); 3166 return; 3167 } 3168 } else if (cluster->block_group != block_group) { 3169 /* someone else has already freed it don't redo their work */ 3170 spin_unlock(&cluster->lock); 3171 return; 3172 } 3173 btrfs_get_block_group(block_group); 3174 spin_unlock(&cluster->lock); 3175 3176 ctl = block_group->free_space_ctl; 3177 3178 /* now return any extents the cluster had on it */ 3179 spin_lock(&ctl->tree_lock); 3180 __btrfs_return_cluster_to_free_space(block_group, cluster); 3181 spin_unlock(&ctl->tree_lock); 3182 3183 btrfs_discard_queue_work(&block_group->fs_info->discard_ctl, block_group); 3184 3185 /* finally drop our ref */ 3186 btrfs_put_block_group(block_group); 3187 } 3188 3189 static u64 btrfs_alloc_from_bitmap(struct btrfs_block_group *block_group, 3190 struct btrfs_free_cluster *cluster, 3191 struct btrfs_free_space *entry, 3192 u64 bytes, u64 min_start, 3193 u64 *max_extent_size) 3194 { 3195 struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl; 3196 int ret2; 3197 u64 search_start = cluster->window_start; 3198 u64 search_bytes = bytes; 3199 u64 ret = 0; 3200 3201 search_start = min_start; 3202 search_bytes = bytes; 3203 3204 ret2 = search_bitmap(ctl, entry, &search_start, &search_bytes, true); 3205 if (ret2) { 3206 *max_extent_size = max(get_max_extent_size(entry), 3207 *max_extent_size); 3208 return 0; 3209 } 3210 3211 ret = search_start; 3212 bitmap_clear_bits(ctl, entry, ret, bytes, false); 3213 3214 return ret; 3215 } 3216 3217 /* 3218 * given a cluster, try to allocate 'bytes' from it, returns 0 3219 * if it couldn't find anything suitably large, or a logical disk offset 3220 * if things worked out 3221 */ 3222 u64 btrfs_alloc_from_cluster(struct btrfs_block_group *block_group, 3223 struct btrfs_free_cluster *cluster, u64 bytes, 3224 u64 min_start, u64 *max_extent_size) 3225 { 3226 struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl; 3227 struct btrfs_discard_ctl *discard_ctl = 3228 &block_group->fs_info->discard_ctl; 3229 struct btrfs_free_space *entry = NULL; 3230 struct rb_node *node; 3231 u64 ret = 0; 3232 3233 ASSERT(!btrfs_is_zoned(block_group->fs_info)); 3234 3235 spin_lock(&cluster->lock); 3236 if (bytes > cluster->max_size) 3237 goto out; 3238 3239 if (cluster->block_group != block_group) 3240 goto out; 3241 3242 node = rb_first(&cluster->root); 3243 if (!node) 3244 goto out; 3245 3246 entry = rb_entry(node, struct btrfs_free_space, offset_index); 3247 while (1) { 3248 if (entry->bytes < bytes) 3249 *max_extent_size = max(get_max_extent_size(entry), 3250 *max_extent_size); 3251 3252 if (entry->bytes < bytes || 3253 (!entry->bitmap && entry->offset < min_start)) { 3254 node = rb_next(&entry->offset_index); 3255 if (!node) 3256 break; 3257 entry = rb_entry(node, struct btrfs_free_space, 3258 offset_index); 3259 continue; 3260 } 3261 3262 if (entry->bitmap) { 3263 ret = btrfs_alloc_from_bitmap(block_group, 3264 cluster, entry, bytes, 3265 cluster->window_start, 3266 max_extent_size); 3267 if (ret == 0) { 3268 node = rb_next(&entry->offset_index); 3269 if (!node) 3270 break; 3271 entry = rb_entry(node, struct btrfs_free_space, 3272 offset_index); 3273 continue; 3274 } 3275 cluster->window_start += bytes; 3276 } else { 3277 ret = entry->offset; 3278 3279 entry->offset += bytes; 3280 entry->bytes -= bytes; 3281 } 3282 3283 break; 3284 } 3285 out: 3286 spin_unlock(&cluster->lock); 3287 3288 if (!ret) 3289 return 0; 3290 3291 spin_lock(&ctl->tree_lock); 3292 3293 if (!btrfs_free_space_trimmed(entry)) 3294 atomic64_add(bytes, &discard_ctl->discard_bytes_saved); 3295 3296 ctl->free_space -= bytes; 3297 if (!entry->bitmap && !btrfs_free_space_trimmed(entry)) 3298 ctl->discardable_bytes[BTRFS_STAT_CURR] -= bytes; 3299 3300 spin_lock(&cluster->lock); 3301 if (entry->bytes == 0) { 3302 rb_erase(&entry->offset_index, &cluster->root); 3303 ctl->free_extents--; 3304 if (entry->bitmap) { 3305 kmem_cache_free(btrfs_free_space_bitmap_cachep, 3306 entry->bitmap); 3307 ctl->total_bitmaps--; 3308 recalculate_thresholds(ctl); 3309 } else if (!btrfs_free_space_trimmed(entry)) { 3310 ctl->discardable_extents[BTRFS_STAT_CURR]--; 3311 } 3312 kmem_cache_free(btrfs_free_space_cachep, entry); 3313 } 3314 3315 spin_unlock(&cluster->lock); 3316 spin_unlock(&ctl->tree_lock); 3317 3318 return ret; 3319 } 3320 3321 static int btrfs_bitmap_cluster(struct btrfs_block_group *block_group, 3322 struct btrfs_free_space *entry, 3323 struct btrfs_free_cluster *cluster, 3324 u64 offset, u64 bytes, 3325 u64 cont1_bytes, u64 min_bytes) 3326 { 3327 struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl; 3328 const int unit = block_group->fs_info->sectorsize; 3329 unsigned long next_zero; 3330 unsigned long i; 3331 unsigned long want_bits; 3332 unsigned long min_bits; 3333 unsigned long found_bits; 3334 unsigned long max_bits = 0; 3335 unsigned long start = 0; 3336 unsigned long total_found = 0; 3337 int ret; 3338 3339 lockdep_assert_held(&ctl->tree_lock); 3340 3341 i = offset_to_bit(entry->offset, unit, 3342 max_t(u64, offset, entry->offset)); 3343 want_bits = bytes_to_bits(bytes, unit); 3344 min_bits = bytes_to_bits(min_bytes, unit); 3345 3346 /* 3347 * Don't bother looking for a cluster in this bitmap if it's heavily 3348 * fragmented. 3349 */ 3350 if (entry->max_extent_size && 3351 entry->max_extent_size < cont1_bytes) 3352 return -ENOSPC; 3353 again: 3354 found_bits = 0; 3355 for_each_set_bit_from(i, entry->bitmap, BITS_PER_BITMAP) { 3356 next_zero = find_next_zero_bit(entry->bitmap, 3357 BITS_PER_BITMAP, i); 3358 if (next_zero - i >= min_bits) { 3359 found_bits = next_zero - i; 3360 if (found_bits > max_bits) 3361 max_bits = found_bits; 3362 break; 3363 } 3364 if (next_zero - i > max_bits) 3365 max_bits = next_zero - i; 3366 i = next_zero; 3367 } 3368 3369 if (!found_bits) { 3370 entry->max_extent_size = (u64)max_bits * unit; 3371 return -ENOSPC; 3372 } 3373 3374 if (!total_found) { 3375 start = i; 3376 cluster->max_size = 0; 3377 } 3378 3379 total_found += found_bits; 3380 3381 if (cluster->max_size < found_bits * unit) 3382 cluster->max_size = found_bits * unit; 3383 3384 if (total_found < want_bits || cluster->max_size < cont1_bytes) { 3385 i = next_zero + 1; 3386 goto again; 3387 } 3388 3389 cluster->window_start = start * unit + entry->offset; 3390 rb_erase(&entry->offset_index, &ctl->free_space_offset); 3391 rb_erase_cached(&entry->bytes_index, &ctl->free_space_bytes); 3392 3393 /* 3394 * We need to know if we're currently on the normal space index when we 3395 * manipulate the bitmap so that we know we need to remove and re-insert 3396 * it into the space_index tree. Clear the bytes_index node here so the 3397 * bitmap manipulation helpers know not to mess with the space_index 3398 * until this bitmap entry is added back into the normal cache. 3399 */ 3400 RB_CLEAR_NODE(&entry->bytes_index); 3401 3402 ret = tree_insert_offset(ctl, cluster, entry); 3403 ASSERT(!ret); /* -EEXIST; Logic error */ 3404 3405 trace_btrfs_setup_cluster(block_group, cluster, total_found * unit, 1); 3406 return 0; 3407 } 3408 3409 /* 3410 * This searches the block group for just extents to fill the cluster with. 3411 * Try to find a cluster with at least bytes total bytes, at least one 3412 * extent of cont1_bytes, and other clusters of at least min_bytes. 3413 */ 3414 static noinline int 3415 setup_cluster_no_bitmap(struct btrfs_block_group *block_group, 3416 struct btrfs_free_cluster *cluster, 3417 struct list_head *bitmaps, u64 offset, u64 bytes, 3418 u64 cont1_bytes, u64 min_bytes) 3419 { 3420 struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl; 3421 struct btrfs_free_space *first = NULL; 3422 struct btrfs_free_space *entry = NULL; 3423 struct btrfs_free_space *last; 3424 struct rb_node *node; 3425 u64 window_free; 3426 u64 max_extent; 3427 u64 total_size = 0; 3428 3429 lockdep_assert_held(&ctl->tree_lock); 3430 3431 entry = tree_search_offset(ctl, offset, 0, 1); 3432 if (!entry) 3433 return -ENOSPC; 3434 3435 /* 3436 * We don't want bitmaps, so just move along until we find a normal 3437 * extent entry. 3438 */ 3439 while (entry->bitmap || entry->bytes < min_bytes) { 3440 if (entry->bitmap && list_empty(&entry->list)) 3441 list_add_tail(&entry->list, bitmaps); 3442 node = rb_next(&entry->offset_index); 3443 if (!node) 3444 return -ENOSPC; 3445 entry = rb_entry(node, struct btrfs_free_space, offset_index); 3446 } 3447 3448 window_free = entry->bytes; 3449 max_extent = entry->bytes; 3450 first = entry; 3451 last = entry; 3452 3453 for (node = rb_next(&entry->offset_index); node; 3454 node = rb_next(&entry->offset_index)) { 3455 entry = rb_entry(node, struct btrfs_free_space, offset_index); 3456 3457 if (entry->bitmap) { 3458 if (list_empty(&entry->list)) 3459 list_add_tail(&entry->list, bitmaps); 3460 continue; 3461 } 3462 3463 if (entry->bytes < min_bytes) 3464 continue; 3465 3466 last = entry; 3467 window_free += entry->bytes; 3468 if (entry->bytes > max_extent) 3469 max_extent = entry->bytes; 3470 } 3471 3472 if (window_free < bytes || max_extent < cont1_bytes) 3473 return -ENOSPC; 3474 3475 cluster->window_start = first->offset; 3476 3477 node = &first->offset_index; 3478 3479 /* 3480 * now we've found our entries, pull them out of the free space 3481 * cache and put them into the cluster rbtree 3482 */ 3483 do { 3484 int ret; 3485 3486 entry = rb_entry(node, struct btrfs_free_space, offset_index); 3487 node = rb_next(&entry->offset_index); 3488 if (entry->bitmap || entry->bytes < min_bytes) 3489 continue; 3490 3491 rb_erase(&entry->offset_index, &ctl->free_space_offset); 3492 rb_erase_cached(&entry->bytes_index, &ctl->free_space_bytes); 3493 ret = tree_insert_offset(ctl, cluster, entry); 3494 total_size += entry->bytes; 3495 ASSERT(!ret); /* -EEXIST; Logic error */ 3496 } while (node && entry != last); 3497 3498 cluster->max_size = max_extent; 3499 trace_btrfs_setup_cluster(block_group, cluster, total_size, 0); 3500 return 0; 3501 } 3502 3503 /* 3504 * This specifically looks for bitmaps that may work in the cluster, we assume 3505 * that we have already failed to find extents that will work. 3506 */ 3507 static noinline int 3508 setup_cluster_bitmap(struct btrfs_block_group *block_group, 3509 struct btrfs_free_cluster *cluster, 3510 struct list_head *bitmaps, u64 offset, u64 bytes, 3511 u64 cont1_bytes, u64 min_bytes) 3512 { 3513 struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl; 3514 struct btrfs_free_space *entry = NULL; 3515 int ret = -ENOSPC; 3516 u64 bitmap_offset = offset_to_bitmap(ctl, offset); 3517 3518 if (ctl->total_bitmaps == 0) 3519 return -ENOSPC; 3520 3521 /* 3522 * The bitmap that covers offset won't be in the list unless offset 3523 * is just its start offset. 3524 */ 3525 if (!list_empty(bitmaps)) 3526 entry = list_first_entry(bitmaps, struct btrfs_free_space, list); 3527 3528 if (!entry || entry->offset != bitmap_offset) { 3529 entry = tree_search_offset(ctl, bitmap_offset, 1, 0); 3530 if (entry && list_empty(&entry->list)) 3531 list_add(&entry->list, bitmaps); 3532 } 3533 3534 list_for_each_entry(entry, bitmaps, list) { 3535 if (entry->bytes < bytes) 3536 continue; 3537 ret = btrfs_bitmap_cluster(block_group, entry, cluster, offset, 3538 bytes, cont1_bytes, min_bytes); 3539 if (!ret) 3540 return 0; 3541 } 3542 3543 /* 3544 * The bitmaps list has all the bitmaps that record free space 3545 * starting after offset, so no more search is required. 3546 */ 3547 return -ENOSPC; 3548 } 3549 3550 /* 3551 * here we try to find a cluster of blocks in a block group. The goal 3552 * is to find at least bytes+empty_size. 3553 * We might not find them all in one contiguous area. 3554 * 3555 * returns zero and sets up cluster if things worked out, otherwise 3556 * it returns -enospc 3557 */ 3558 int btrfs_find_space_cluster(struct btrfs_block_group *block_group, 3559 struct btrfs_free_cluster *cluster, 3560 u64 offset, u64 bytes, u64 empty_size) 3561 { 3562 struct btrfs_fs_info *fs_info = block_group->fs_info; 3563 struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl; 3564 struct btrfs_free_space *entry, *tmp; 3565 LIST_HEAD(bitmaps); 3566 u64 min_bytes; 3567 u64 cont1_bytes; 3568 int ret; 3569 3570 /* 3571 * Choose the minimum extent size we'll require for this 3572 * cluster. For SSD_SPREAD, don't allow any fragmentation. 3573 * For metadata, allow allocates with smaller extents. For 3574 * data, keep it dense. 3575 */ 3576 if (btrfs_test_opt(fs_info, SSD_SPREAD)) { 3577 cont1_bytes = bytes + empty_size; 3578 min_bytes = cont1_bytes; 3579 } else if (block_group->flags & BTRFS_BLOCK_GROUP_METADATA) { 3580 cont1_bytes = bytes; 3581 min_bytes = fs_info->sectorsize; 3582 } else { 3583 cont1_bytes = max(bytes, (bytes + empty_size) >> 2); 3584 min_bytes = fs_info->sectorsize; 3585 } 3586 3587 spin_lock(&ctl->tree_lock); 3588 3589 /* 3590 * If we know we don't have enough space to make a cluster don't even 3591 * bother doing all the work to try and find one. 3592 */ 3593 if (ctl->free_space < bytes) { 3594 spin_unlock(&ctl->tree_lock); 3595 return -ENOSPC; 3596 } 3597 3598 spin_lock(&cluster->lock); 3599 3600 /* someone already found a cluster, hooray */ 3601 if (cluster->block_group) { 3602 ret = 0; 3603 goto out; 3604 } 3605 3606 trace_btrfs_find_cluster(block_group, offset, bytes, empty_size, 3607 min_bytes); 3608 3609 ret = setup_cluster_no_bitmap(block_group, cluster, &bitmaps, offset, 3610 bytes + empty_size, 3611 cont1_bytes, min_bytes); 3612 if (ret) 3613 ret = setup_cluster_bitmap(block_group, cluster, &bitmaps, 3614 offset, bytes + empty_size, 3615 cont1_bytes, min_bytes); 3616 3617 /* Clear our temporary list */ 3618 list_for_each_entry_safe(entry, tmp, &bitmaps, list) 3619 list_del_init(&entry->list); 3620 3621 if (!ret) { 3622 btrfs_get_block_group(block_group); 3623 list_add_tail(&cluster->block_group_list, 3624 &block_group->cluster_list); 3625 cluster->block_group = block_group; 3626 } else { 3627 trace_btrfs_failed_cluster_setup(block_group); 3628 } 3629 out: 3630 spin_unlock(&cluster->lock); 3631 spin_unlock(&ctl->tree_lock); 3632 3633 return ret; 3634 } 3635 3636 /* 3637 * simple code to zero out a cluster 3638 */ 3639 void btrfs_init_free_cluster(struct btrfs_free_cluster *cluster) 3640 { 3641 spin_lock_init(&cluster->lock); 3642 spin_lock_init(&cluster->refill_lock); 3643 cluster->root = RB_ROOT; 3644 cluster->max_size = 0; 3645 cluster->fragmented = false; 3646 INIT_LIST_HEAD(&cluster->block_group_list); 3647 cluster->block_group = NULL; 3648 } 3649 3650 static int do_trimming(struct btrfs_block_group *block_group, 3651 u64 *total_trimmed, u64 start, u64 bytes, 3652 u64 reserved_start, u64 reserved_bytes, 3653 enum btrfs_trim_state reserved_trim_state, 3654 struct btrfs_trim_range *trim_entry) 3655 { 3656 struct btrfs_space_info *space_info = block_group->space_info; 3657 struct btrfs_fs_info *fs_info = block_group->fs_info; 3658 struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl; 3659 int ret; 3660 bool bg_ro; 3661 const u64 end = start + bytes; 3662 const u64 reserved_end = reserved_start + reserved_bytes; 3663 enum btrfs_trim_state trim_state = BTRFS_TRIM_STATE_UNTRIMMED; 3664 u64 trimmed = 0; 3665 3666 spin_lock(&space_info->lock); 3667 spin_lock(&block_group->lock); 3668 bg_ro = block_group->ro; 3669 if (!bg_ro) { 3670 block_group->reserved += reserved_bytes; 3671 spin_unlock(&block_group->lock); 3672 space_info->bytes_reserved += reserved_bytes; 3673 } else { 3674 spin_unlock(&block_group->lock); 3675 } 3676 spin_unlock(&space_info->lock); 3677 3678 ret = btrfs_discard_extent(fs_info, start, bytes, &trimmed, false); 3679 if (!ret) { 3680 *total_trimmed += trimmed; 3681 trim_state = BTRFS_TRIM_STATE_TRIMMED; 3682 } 3683 3684 mutex_lock(&ctl->cache_writeout_mutex); 3685 if (reserved_start < start) 3686 __btrfs_add_free_space(block_group, reserved_start, 3687 start - reserved_start, 3688 reserved_trim_state); 3689 if (end < reserved_end) 3690 __btrfs_add_free_space(block_group, end, reserved_end - end, 3691 reserved_trim_state); 3692 __btrfs_add_free_space(block_group, start, bytes, trim_state); 3693 list_del(&trim_entry->list); 3694 mutex_unlock(&ctl->cache_writeout_mutex); 3695 3696 if (!bg_ro) { 3697 spin_lock(&space_info->lock); 3698 spin_lock(&block_group->lock); 3699 bg_ro = block_group->ro; 3700 block_group->reserved -= reserved_bytes; 3701 spin_unlock(&block_group->lock); 3702 3703 space_info->bytes_reserved -= reserved_bytes; 3704 if (bg_ro) 3705 space_info->bytes_readonly += reserved_bytes; 3706 spin_unlock(&space_info->lock); 3707 } 3708 3709 return ret; 3710 } 3711 3712 /* 3713 * If @async is set, then we will trim 1 region and return. 3714 */ 3715 static int trim_no_bitmap(struct btrfs_block_group *block_group, 3716 u64 *total_trimmed, u64 start, u64 end, u64 minlen, 3717 bool async) 3718 { 3719 struct btrfs_discard_ctl *discard_ctl = 3720 &block_group->fs_info->discard_ctl; 3721 struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl; 3722 struct btrfs_free_space *entry; 3723 struct rb_node *node; 3724 int ret = 0; 3725 u64 extent_start; 3726 u64 extent_bytes; 3727 enum btrfs_trim_state extent_trim_state; 3728 u64 bytes; 3729 const u64 max_discard_size = READ_ONCE(discard_ctl->max_discard_size); 3730 3731 while (start < end) { 3732 struct btrfs_trim_range trim_entry; 3733 3734 mutex_lock(&ctl->cache_writeout_mutex); 3735 spin_lock(&ctl->tree_lock); 3736 3737 if (ctl->free_space < minlen) 3738 goto out_unlock; 3739 3740 entry = tree_search_offset(ctl, start, 0, 1); 3741 if (!entry) 3742 goto out_unlock; 3743 3744 /* Skip bitmaps and if async, already trimmed entries */ 3745 while (entry->bitmap || 3746 (async && btrfs_free_space_trimmed(entry))) { 3747 node = rb_next(&entry->offset_index); 3748 if (!node) 3749 goto out_unlock; 3750 entry = rb_entry(node, struct btrfs_free_space, 3751 offset_index); 3752 } 3753 3754 if (entry->offset >= end) 3755 goto out_unlock; 3756 3757 extent_start = entry->offset; 3758 extent_bytes = entry->bytes; 3759 extent_trim_state = entry->trim_state; 3760 if (async) { 3761 start = entry->offset; 3762 bytes = entry->bytes; 3763 if (bytes < minlen) { 3764 spin_unlock(&ctl->tree_lock); 3765 mutex_unlock(&ctl->cache_writeout_mutex); 3766 goto next; 3767 } 3768 unlink_free_space(ctl, entry, true); 3769 /* 3770 * Let bytes = BTRFS_MAX_DISCARD_SIZE + X. 3771 * If X < BTRFS_ASYNC_DISCARD_MIN_FILTER, we won't trim 3772 * X when we come back around. So trim it now. 3773 */ 3774 if (max_discard_size && 3775 bytes >= (max_discard_size + 3776 BTRFS_ASYNC_DISCARD_MIN_FILTER)) { 3777 bytes = max_discard_size; 3778 extent_bytes = max_discard_size; 3779 entry->offset += max_discard_size; 3780 entry->bytes -= max_discard_size; 3781 link_free_space(ctl, entry); 3782 } else { 3783 kmem_cache_free(btrfs_free_space_cachep, entry); 3784 } 3785 } else { 3786 start = max(start, extent_start); 3787 bytes = min(extent_start + extent_bytes, end) - start; 3788 if (bytes < minlen) { 3789 spin_unlock(&ctl->tree_lock); 3790 mutex_unlock(&ctl->cache_writeout_mutex); 3791 goto next; 3792 } 3793 3794 unlink_free_space(ctl, entry, true); 3795 kmem_cache_free(btrfs_free_space_cachep, entry); 3796 } 3797 3798 spin_unlock(&ctl->tree_lock); 3799 trim_entry.start = extent_start; 3800 trim_entry.bytes = extent_bytes; 3801 list_add_tail(&trim_entry.list, &ctl->trimming_ranges); 3802 mutex_unlock(&ctl->cache_writeout_mutex); 3803 3804 ret = do_trimming(block_group, total_trimmed, start, bytes, 3805 extent_start, extent_bytes, extent_trim_state, 3806 &trim_entry); 3807 if (ret) { 3808 block_group->discard_cursor = start + bytes; 3809 break; 3810 } 3811 next: 3812 start += bytes; 3813 block_group->discard_cursor = start; 3814 if (async && *total_trimmed) 3815 break; 3816 3817 if (btrfs_trim_interrupted()) { 3818 ret = -ERESTARTSYS; 3819 break; 3820 } 3821 3822 cond_resched(); 3823 } 3824 3825 return ret; 3826 3827 out_unlock: 3828 block_group->discard_cursor = btrfs_block_group_end(block_group); 3829 spin_unlock(&ctl->tree_lock); 3830 mutex_unlock(&ctl->cache_writeout_mutex); 3831 3832 return ret; 3833 } 3834 3835 void btrfs_trim_fully_remapped_block_group(struct btrfs_block_group *bg) 3836 { 3837 struct btrfs_fs_info *fs_info = bg->fs_info; 3838 struct btrfs_discard_ctl *discard_ctl = &fs_info->discard_ctl; 3839 int ret = 0; 3840 u64 bytes, trimmed; 3841 const u64 max_discard_size = READ_ONCE(discard_ctl->max_discard_size); 3842 u64 end = btrfs_block_group_end(bg); 3843 3844 if (!test_bit(BLOCK_GROUP_FLAG_STRIPE_REMOVAL_PENDING, &bg->runtime_flags)) { 3845 bg->discard_cursor = end; 3846 3847 if (bg->used == 0) { 3848 spin_lock(&fs_info->unused_bgs_lock); 3849 if (!list_empty(&bg->bg_list)) { 3850 list_del_init(&bg->bg_list); 3851 btrfs_put_block_group(bg); 3852 } 3853 spin_unlock(&fs_info->unused_bgs_lock); 3854 3855 btrfs_mark_bg_unused(bg); 3856 } 3857 3858 return; 3859 } 3860 3861 bytes = end - bg->discard_cursor; 3862 3863 if (max_discard_size && 3864 bytes >= (max_discard_size + BTRFS_ASYNC_DISCARD_MIN_FILTER)) 3865 bytes = max_discard_size; 3866 3867 ret = btrfs_discard_extent(fs_info, bg->discard_cursor, bytes, &trimmed, false); 3868 if (ret) 3869 return; 3870 3871 bg->discard_cursor += trimmed; 3872 3873 if (bg->discard_cursor < end) 3874 return; 3875 3876 btrfs_complete_bg_remapping(bg); 3877 } 3878 3879 /* 3880 * If we break out of trimming a bitmap prematurely, we should reset the 3881 * trimming bit. In a rather contrived case, it's possible to race here so 3882 * reset the state to BTRFS_TRIM_STATE_UNTRIMMED. 3883 * 3884 * start = start of bitmap 3885 * end = near end of bitmap 3886 * 3887 * Thread 1: Thread 2: 3888 * trim_bitmaps(start) 3889 * trim_bitmaps(end) 3890 * end_trimming_bitmap() 3891 * reset_trimming_bitmap() 3892 */ 3893 static void reset_trimming_bitmap(struct btrfs_free_space_ctl *ctl, u64 offset) 3894 { 3895 struct btrfs_free_space *entry; 3896 3897 spin_lock(&ctl->tree_lock); 3898 entry = tree_search_offset(ctl, offset, 1, 0); 3899 if (entry) { 3900 if (btrfs_free_space_trimmed(entry)) { 3901 ctl->discardable_extents[BTRFS_STAT_CURR] += 3902 entry->bitmap_extents; 3903 ctl->discardable_bytes[BTRFS_STAT_CURR] += entry->bytes; 3904 } 3905 entry->trim_state = BTRFS_TRIM_STATE_UNTRIMMED; 3906 } 3907 3908 spin_unlock(&ctl->tree_lock); 3909 } 3910 3911 static void end_trimming_bitmap(struct btrfs_free_space_ctl *ctl, 3912 struct btrfs_free_space *entry) 3913 { 3914 if (btrfs_free_space_trimming_bitmap(entry)) { 3915 entry->trim_state = BTRFS_TRIM_STATE_TRIMMED; 3916 ctl->discardable_extents[BTRFS_STAT_CURR] -= 3917 entry->bitmap_extents; 3918 ctl->discardable_bytes[BTRFS_STAT_CURR] -= entry->bytes; 3919 } 3920 } 3921 3922 /* 3923 * If @async is set, then we will trim 1 region and return. 3924 */ 3925 static int trim_bitmaps(struct btrfs_block_group *block_group, 3926 u64 *total_trimmed, u64 start, u64 end, u64 minlen, 3927 u64 maxlen, bool async) 3928 { 3929 struct btrfs_discard_ctl *discard_ctl = 3930 &block_group->fs_info->discard_ctl; 3931 struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl; 3932 struct btrfs_free_space *entry; 3933 int ret = 0; 3934 int ret2; 3935 u64 bytes; 3936 u64 offset = offset_to_bitmap(ctl, start); 3937 const u64 max_discard_size = READ_ONCE(discard_ctl->max_discard_size); 3938 3939 while (offset < end) { 3940 bool next_bitmap = false; 3941 struct btrfs_trim_range trim_entry; 3942 3943 mutex_lock(&ctl->cache_writeout_mutex); 3944 spin_lock(&ctl->tree_lock); 3945 3946 if (ctl->free_space < minlen) { 3947 block_group->discard_cursor = 3948 btrfs_block_group_end(block_group); 3949 spin_unlock(&ctl->tree_lock); 3950 mutex_unlock(&ctl->cache_writeout_mutex); 3951 break; 3952 } 3953 3954 entry = tree_search_offset(ctl, offset, 1, 0); 3955 /* 3956 * Bitmaps are marked trimmed lossily now to prevent constant 3957 * discarding of the same bitmap (the reason why we are bound 3958 * by the filters). So, retrim the block group bitmaps when we 3959 * are preparing to punt to the unused_bgs list. This uses 3960 * @minlen to determine if we are in BTRFS_DISCARD_INDEX_UNUSED 3961 * which is the only discard index which sets minlen to 0. 3962 */ 3963 if (!entry || (async && minlen && start == offset && 3964 btrfs_free_space_trimmed(entry))) { 3965 spin_unlock(&ctl->tree_lock); 3966 mutex_unlock(&ctl->cache_writeout_mutex); 3967 next_bitmap = true; 3968 goto next; 3969 } 3970 3971 /* 3972 * Async discard bitmap trimming begins at by setting the start 3973 * to be key.objectid and the offset_to_bitmap() aligns to the 3974 * start of the bitmap. This lets us know we are fully 3975 * scanning the bitmap rather than only some portion of it. 3976 */ 3977 if (start == offset) 3978 entry->trim_state = BTRFS_TRIM_STATE_TRIMMING; 3979 3980 bytes = minlen; 3981 ret2 = search_bitmap(ctl, entry, &start, &bytes, false); 3982 if (ret2 || start >= end) { 3983 /* 3984 * We lossily consider a bitmap trimmed if we only skip 3985 * over regions <= BTRFS_ASYNC_DISCARD_MIN_FILTER. 3986 */ 3987 if (ret2 && minlen <= BTRFS_ASYNC_DISCARD_MIN_FILTER) 3988 end_trimming_bitmap(ctl, entry); 3989 else 3990 entry->trim_state = BTRFS_TRIM_STATE_UNTRIMMED; 3991 spin_unlock(&ctl->tree_lock); 3992 mutex_unlock(&ctl->cache_writeout_mutex); 3993 next_bitmap = true; 3994 goto next; 3995 } 3996 3997 /* 3998 * We already trimmed a region, but are using the locking above 3999 * to reset the trim_state. 4000 */ 4001 if (async && *total_trimmed) { 4002 spin_unlock(&ctl->tree_lock); 4003 mutex_unlock(&ctl->cache_writeout_mutex); 4004 return ret; 4005 } 4006 4007 bytes = min(bytes, end - start); 4008 if (bytes < minlen || (async && maxlen && bytes > maxlen)) { 4009 spin_unlock(&ctl->tree_lock); 4010 mutex_unlock(&ctl->cache_writeout_mutex); 4011 goto next; 4012 } 4013 4014 /* 4015 * Let bytes = BTRFS_MAX_DISCARD_SIZE + X. 4016 * If X < @minlen, we won't trim X when we come back around. 4017 * So trim it now. We differ here from trimming extents as we 4018 * don't keep individual state per bit. 4019 */ 4020 if (async && 4021 max_discard_size && 4022 bytes > (max_discard_size + minlen)) 4023 bytes = max_discard_size; 4024 4025 bitmap_clear_bits(ctl, entry, start, bytes, true); 4026 if (entry->bytes == 0) 4027 free_bitmap(ctl, entry); 4028 4029 spin_unlock(&ctl->tree_lock); 4030 trim_entry.start = start; 4031 trim_entry.bytes = bytes; 4032 list_add_tail(&trim_entry.list, &ctl->trimming_ranges); 4033 mutex_unlock(&ctl->cache_writeout_mutex); 4034 4035 ret = do_trimming(block_group, total_trimmed, start, bytes, 4036 start, bytes, 0, &trim_entry); 4037 if (ret) { 4038 reset_trimming_bitmap(ctl, offset); 4039 block_group->discard_cursor = 4040 btrfs_block_group_end(block_group); 4041 break; 4042 } 4043 next: 4044 if (next_bitmap) { 4045 const int unit = block_group->fs_info->sectorsize; 4046 4047 offset += BITS_PER_BITMAP * unit; 4048 start = offset; 4049 } else { 4050 start += bytes; 4051 } 4052 block_group->discard_cursor = start; 4053 4054 if (btrfs_trim_interrupted()) { 4055 if (start != offset) 4056 reset_trimming_bitmap(ctl, offset); 4057 ret = -ERESTARTSYS; 4058 break; 4059 } 4060 4061 cond_resched(); 4062 } 4063 4064 if (offset >= end) 4065 block_group->discard_cursor = end; 4066 4067 return ret; 4068 } 4069 4070 int btrfs_trim_block_group(struct btrfs_block_group *block_group, 4071 u64 *trimmed, u64 start, u64 end, u64 minlen) 4072 { 4073 struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl; 4074 const int unit = block_group->fs_info->sectorsize; 4075 int ret; 4076 u64 rem = 0; 4077 4078 ASSERT(!btrfs_is_zoned(block_group->fs_info)); 4079 4080 *trimmed = 0; 4081 4082 spin_lock(&block_group->lock); 4083 if (test_bit(BLOCK_GROUP_FLAG_REMOVED, &block_group->runtime_flags)) { 4084 spin_unlock(&block_group->lock); 4085 return 0; 4086 } 4087 btrfs_freeze_block_group(block_group); 4088 spin_unlock(&block_group->lock); 4089 4090 ret = trim_no_bitmap(block_group, trimmed, start, end, minlen, false); 4091 if (ret) 4092 goto out; 4093 4094 ret = trim_bitmaps(block_group, trimmed, start, end, minlen, 0, false); 4095 div64_u64_rem(end, BITS_PER_BITMAP * unit, &rem); 4096 /* If we ended in the middle of a bitmap, reset the trimming flag */ 4097 if (rem) 4098 reset_trimming_bitmap(ctl, offset_to_bitmap(ctl, end)); 4099 out: 4100 btrfs_unfreeze_block_group(block_group); 4101 return ret; 4102 } 4103 4104 int btrfs_trim_block_group_extents(struct btrfs_block_group *block_group, 4105 u64 *trimmed, u64 start, u64 end, u64 minlen, 4106 bool async) 4107 { 4108 int ret; 4109 4110 *trimmed = 0; 4111 4112 spin_lock(&block_group->lock); 4113 if (test_bit(BLOCK_GROUP_FLAG_REMOVED, &block_group->runtime_flags)) { 4114 spin_unlock(&block_group->lock); 4115 return 0; 4116 } 4117 btrfs_freeze_block_group(block_group); 4118 spin_unlock(&block_group->lock); 4119 4120 ret = trim_no_bitmap(block_group, trimmed, start, end, minlen, async); 4121 btrfs_unfreeze_block_group(block_group); 4122 4123 return ret; 4124 } 4125 4126 int btrfs_trim_block_group_bitmaps(struct btrfs_block_group *block_group, 4127 u64 *trimmed, u64 start, u64 end, u64 minlen, 4128 u64 maxlen, bool async) 4129 { 4130 int ret; 4131 4132 *trimmed = 0; 4133 4134 spin_lock(&block_group->lock); 4135 if (test_bit(BLOCK_GROUP_FLAG_REMOVED, &block_group->runtime_flags)) { 4136 spin_unlock(&block_group->lock); 4137 return 0; 4138 } 4139 btrfs_freeze_block_group(block_group); 4140 spin_unlock(&block_group->lock); 4141 4142 ret = trim_bitmaps(block_group, trimmed, start, end, minlen, maxlen, 4143 async); 4144 4145 btrfs_unfreeze_block_group(block_group); 4146 4147 return ret; 4148 } 4149 4150 bool btrfs_free_space_cache_v1_active(struct btrfs_fs_info *fs_info) 4151 { 4152 return btrfs_super_cache_generation(fs_info->super_copy); 4153 } 4154 4155 static int cleanup_free_space_cache_v1(struct btrfs_fs_info *fs_info, 4156 struct btrfs_trans_handle *trans) 4157 { 4158 struct btrfs_block_group *block_group; 4159 struct rb_node *node; 4160 4161 btrfs_info(fs_info, "cleaning free space cache v1"); 4162 4163 node = rb_first_cached(&fs_info->block_group_cache_tree); 4164 while (node) { 4165 int ret; 4166 4167 block_group = rb_entry(node, struct btrfs_block_group, cache_node); 4168 ret = btrfs_remove_free_space_inode(trans, NULL, block_group); 4169 if (ret) 4170 return ret; 4171 node = rb_next(node); 4172 } 4173 return 0; 4174 } 4175 4176 int btrfs_set_free_space_cache_v1_active(struct btrfs_fs_info *fs_info, bool active) 4177 { 4178 struct btrfs_trans_handle *trans; 4179 int ret; 4180 4181 /* 4182 * update_super_roots will appropriately set or unset 4183 * super_copy->cache_generation based on SPACE_CACHE and 4184 * BTRFS_FS_CLEANUP_SPACE_CACHE_V1. For this reason, we need a 4185 * transaction commit whether we are enabling space cache v1 and don't 4186 * have any other work to do, or are disabling it and removing free 4187 * space inodes. 4188 */ 4189 trans = btrfs_start_transaction(fs_info->tree_root, 0); 4190 if (IS_ERR(trans)) 4191 return PTR_ERR(trans); 4192 4193 if (!active) { 4194 set_bit(BTRFS_FS_CLEANUP_SPACE_CACHE_V1, &fs_info->flags); 4195 ret = cleanup_free_space_cache_v1(fs_info, trans); 4196 if (unlikely(ret)) { 4197 btrfs_abort_transaction(trans, ret); 4198 btrfs_end_transaction(trans); 4199 goto out; 4200 } 4201 } 4202 4203 ret = btrfs_commit_transaction(trans); 4204 out: 4205 clear_bit(BTRFS_FS_CLEANUP_SPACE_CACHE_V1, &fs_info->flags); 4206 4207 return ret; 4208 } 4209 4210 int __init btrfs_free_space_init(void) 4211 { 4212 btrfs_free_space_cachep = KMEM_CACHE(btrfs_free_space, 0); 4213 if (!btrfs_free_space_cachep) 4214 return -ENOMEM; 4215 4216 btrfs_free_space_bitmap_cachep = kmem_cache_create("btrfs_free_space_bitmap", 4217 PAGE_SIZE, PAGE_SIZE, 4218 0, NULL); 4219 if (!btrfs_free_space_bitmap_cachep) { 4220 kmem_cache_destroy(btrfs_free_space_cachep); 4221 return -ENOMEM; 4222 } 4223 4224 return 0; 4225 } 4226 4227 void __cold btrfs_free_space_exit(void) 4228 { 4229 kmem_cache_destroy(btrfs_free_space_cachep); 4230 kmem_cache_destroy(btrfs_free_space_bitmap_cachep); 4231 } 4232 4233 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS 4234 /* 4235 * Use this if you need to make a bitmap or extent entry specifically, it 4236 * doesn't do any of the merging that add_free_space does, this acts a lot like 4237 * how the free space cache loading stuff works, so you can get really weird 4238 * configurations. 4239 */ 4240 int test_add_free_space_entry(struct btrfs_block_group *cache, 4241 u64 offset, u64 bytes, bool bitmap) 4242 { 4243 struct btrfs_free_space_ctl *ctl = cache->free_space_ctl; 4244 struct btrfs_free_space *info = NULL, *bitmap_info; 4245 void *map = NULL; 4246 enum btrfs_trim_state trim_state = BTRFS_TRIM_STATE_TRIMMED; 4247 u64 bytes_added; 4248 int ret; 4249 4250 again: 4251 if (!info) { 4252 info = kmem_cache_zalloc(btrfs_free_space_cachep, GFP_NOFS); 4253 if (!info) 4254 return -ENOMEM; 4255 } 4256 4257 if (!bitmap) { 4258 spin_lock(&ctl->tree_lock); 4259 info->offset = offset; 4260 info->bytes = bytes; 4261 info->max_extent_size = 0; 4262 ret = link_free_space(ctl, info); 4263 spin_unlock(&ctl->tree_lock); 4264 if (ret) 4265 kmem_cache_free(btrfs_free_space_cachep, info); 4266 return ret; 4267 } 4268 4269 if (!map) { 4270 map = kmem_cache_zalloc(btrfs_free_space_bitmap_cachep, GFP_NOFS); 4271 if (!map) { 4272 kmem_cache_free(btrfs_free_space_cachep, info); 4273 return -ENOMEM; 4274 } 4275 } 4276 4277 spin_lock(&ctl->tree_lock); 4278 bitmap_info = tree_search_offset(ctl, offset_to_bitmap(ctl, offset), 4279 1, 0); 4280 if (!bitmap_info) { 4281 info->bitmap = map; 4282 map = NULL; 4283 add_new_bitmap(ctl, info, offset); 4284 bitmap_info = info; 4285 info = NULL; 4286 } 4287 4288 bytes_added = add_bytes_to_bitmap(ctl, bitmap_info, offset, bytes, 4289 trim_state); 4290 4291 bytes -= bytes_added; 4292 offset += bytes_added; 4293 spin_unlock(&ctl->tree_lock); 4294 4295 if (bytes) 4296 goto again; 4297 4298 if (info) 4299 kmem_cache_free(btrfs_free_space_cachep, info); 4300 if (map) 4301 kmem_cache_free(btrfs_free_space_bitmap_cachep, map); 4302 return 0; 4303 } 4304 4305 /* 4306 * Checks to see if the given range is in the free space cache. This is really 4307 * just used to check the absence of space, so if there is free space in the 4308 * range at all we will return 1. 4309 */ 4310 int test_check_exists(struct btrfs_block_group *cache, 4311 u64 offset, u64 bytes) 4312 { 4313 struct btrfs_free_space_ctl *ctl = cache->free_space_ctl; 4314 const int unit = cache->fs_info->sectorsize; 4315 struct btrfs_free_space *info; 4316 int ret = 0; 4317 4318 spin_lock(&ctl->tree_lock); 4319 info = tree_search_offset(ctl, offset, 0, 0); 4320 if (!info) { 4321 info = tree_search_offset(ctl, offset_to_bitmap(ctl, offset), 4322 1, 0); 4323 if (!info) 4324 goto out; 4325 } 4326 4327 have_info: 4328 if (info->bitmap) { 4329 u64 bit_off, bit_bytes; 4330 struct rb_node *n; 4331 struct btrfs_free_space *tmp; 4332 4333 bit_off = offset; 4334 bit_bytes = unit; 4335 ret = search_bitmap(ctl, info, &bit_off, &bit_bytes, false); 4336 if (!ret) { 4337 if (bit_off == offset) { 4338 ret = 1; 4339 goto out; 4340 } else if (bit_off > offset && 4341 offset + bytes > bit_off) { 4342 ret = 1; 4343 goto out; 4344 } 4345 } 4346 4347 n = rb_prev(&info->offset_index); 4348 while (n) { 4349 tmp = rb_entry(n, struct btrfs_free_space, 4350 offset_index); 4351 if (tmp->offset + tmp->bytes < offset) 4352 break; 4353 if (offset + bytes < tmp->offset) { 4354 n = rb_prev(&tmp->offset_index); 4355 continue; 4356 } 4357 info = tmp; 4358 goto have_info; 4359 } 4360 4361 n = rb_next(&info->offset_index); 4362 while (n) { 4363 tmp = rb_entry(n, struct btrfs_free_space, 4364 offset_index); 4365 if (offset + bytes < tmp->offset) 4366 break; 4367 if (tmp->offset + tmp->bytes < offset) { 4368 n = rb_next(&tmp->offset_index); 4369 continue; 4370 } 4371 info = tmp; 4372 goto have_info; 4373 } 4374 4375 ret = 0; 4376 goto out; 4377 } 4378 4379 if (info->offset == offset) { 4380 ret = 1; 4381 goto out; 4382 } 4383 4384 if (offset > info->offset && offset < info->offset + info->bytes) 4385 ret = 1; 4386 out: 4387 spin_unlock(&ctl->tree_lock); 4388 return ret; 4389 } 4390 #endif /* CONFIG_BTRFS_FS_RUN_SANITY_TESTS */ 4391