1 // SPDX-License-Identifier: GPL-2.0 2 3 #include <linux/err.h> 4 #include <linux/slab.h> 5 #include <linux/spinlock.h> 6 #include "messages.h" 7 #include "ctree.h" 8 #include "extent_map.h" 9 #include "compression.h" 10 #include "btrfs_inode.h" 11 #include "disk-io.h" 12 13 14 static struct kmem_cache *extent_map_cache; 15 16 int __init extent_map_init(void) 17 { 18 extent_map_cache = kmem_cache_create("btrfs_extent_map", 19 sizeof(struct extent_map), 0, 0, NULL); 20 if (!extent_map_cache) 21 return -ENOMEM; 22 return 0; 23 } 24 25 void __cold extent_map_exit(void) 26 { 27 kmem_cache_destroy(extent_map_cache); 28 } 29 30 /* 31 * Initialize the extent tree @tree. Should be called for each new inode or 32 * other user of the extent_map interface. 33 */ 34 void extent_map_tree_init(struct extent_map_tree *tree) 35 { 36 tree->root = RB_ROOT; 37 INIT_LIST_HEAD(&tree->modified_extents); 38 rwlock_init(&tree->lock); 39 } 40 41 /* 42 * Allocate a new extent_map structure. The new structure is returned with a 43 * reference count of one and needs to be freed using free_extent_map() 44 */ 45 struct extent_map *alloc_extent_map(void) 46 { 47 struct extent_map *em; 48 em = kmem_cache_zalloc(extent_map_cache, GFP_NOFS); 49 if (!em) 50 return NULL; 51 RB_CLEAR_NODE(&em->rb_node); 52 refcount_set(&em->refs, 1); 53 INIT_LIST_HEAD(&em->list); 54 return em; 55 } 56 57 /* 58 * Drop the reference out on @em by one and free the structure if the reference 59 * count hits zero. 60 */ 61 void free_extent_map(struct extent_map *em) 62 { 63 if (!em) 64 return; 65 if (refcount_dec_and_test(&em->refs)) { 66 WARN_ON(extent_map_in_tree(em)); 67 WARN_ON(!list_empty(&em->list)); 68 kmem_cache_free(extent_map_cache, em); 69 } 70 } 71 72 /* Do the math around the end of an extent, handling wrapping. */ 73 static u64 range_end(u64 start, u64 len) 74 { 75 if (start + len < start) 76 return (u64)-1; 77 return start + len; 78 } 79 80 static void dec_evictable_extent_maps(struct btrfs_inode *inode) 81 { 82 struct btrfs_fs_info *fs_info = inode->root->fs_info; 83 84 if (!btrfs_is_testing(fs_info) && is_fstree(btrfs_root_id(inode->root))) 85 percpu_counter_dec(&fs_info->evictable_extent_maps); 86 } 87 88 static int tree_insert(struct rb_root *root, struct extent_map *em) 89 { 90 struct rb_node **p = &root->rb_node; 91 struct rb_node *parent = NULL; 92 struct extent_map *entry = NULL; 93 struct rb_node *orig_parent = NULL; 94 u64 end = range_end(em->start, em->len); 95 96 while (*p) { 97 parent = *p; 98 entry = rb_entry(parent, struct extent_map, rb_node); 99 100 if (em->start < entry->start) 101 p = &(*p)->rb_left; 102 else if (em->start >= extent_map_end(entry)) 103 p = &(*p)->rb_right; 104 else 105 return -EEXIST; 106 } 107 108 orig_parent = parent; 109 while (parent && em->start >= extent_map_end(entry)) { 110 parent = rb_next(parent); 111 entry = rb_entry(parent, struct extent_map, rb_node); 112 } 113 if (parent) 114 if (end > entry->start && em->start < extent_map_end(entry)) 115 return -EEXIST; 116 117 parent = orig_parent; 118 entry = rb_entry(parent, struct extent_map, rb_node); 119 while (parent && em->start < entry->start) { 120 parent = rb_prev(parent); 121 entry = rb_entry(parent, struct extent_map, rb_node); 122 } 123 if (parent) 124 if (end > entry->start && em->start < extent_map_end(entry)) 125 return -EEXIST; 126 127 rb_link_node(&em->rb_node, orig_parent, p); 128 rb_insert_color(&em->rb_node, root); 129 return 0; 130 } 131 132 /* 133 * Search through the tree for an extent_map with a given offset. If it can't 134 * be found, try to find some neighboring extents 135 */ 136 static struct rb_node *__tree_search(struct rb_root *root, u64 offset, 137 struct rb_node **prev_or_next_ret) 138 { 139 struct rb_node *n = root->rb_node; 140 struct rb_node *prev = NULL; 141 struct rb_node *orig_prev = NULL; 142 struct extent_map *entry; 143 struct extent_map *prev_entry = NULL; 144 145 ASSERT(prev_or_next_ret); 146 147 while (n) { 148 entry = rb_entry(n, struct extent_map, rb_node); 149 prev = n; 150 prev_entry = entry; 151 152 if (offset < entry->start) 153 n = n->rb_left; 154 else if (offset >= extent_map_end(entry)) 155 n = n->rb_right; 156 else 157 return n; 158 } 159 160 orig_prev = prev; 161 while (prev && offset >= extent_map_end(prev_entry)) { 162 prev = rb_next(prev); 163 prev_entry = rb_entry(prev, struct extent_map, rb_node); 164 } 165 166 /* 167 * Previous extent map found, return as in this case the caller does not 168 * care about the next one. 169 */ 170 if (prev) { 171 *prev_or_next_ret = prev; 172 return NULL; 173 } 174 175 prev = orig_prev; 176 prev_entry = rb_entry(prev, struct extent_map, rb_node); 177 while (prev && offset < prev_entry->start) { 178 prev = rb_prev(prev); 179 prev_entry = rb_entry(prev, struct extent_map, rb_node); 180 } 181 *prev_or_next_ret = prev; 182 183 return NULL; 184 } 185 186 static inline u64 extent_map_block_len(const struct extent_map *em) 187 { 188 if (extent_map_is_compressed(em)) 189 return em->disk_num_bytes; 190 return em->len; 191 } 192 193 static inline u64 extent_map_block_end(const struct extent_map *em) 194 { 195 const u64 block_start = extent_map_block_start(em); 196 const u64 block_end = block_start + extent_map_block_len(em); 197 198 if (block_end < block_start) 199 return (u64)-1; 200 201 return block_end; 202 } 203 204 static bool can_merge_extent_map(const struct extent_map *em) 205 { 206 if (em->flags & EXTENT_FLAG_PINNED) 207 return false; 208 209 /* Don't merge compressed extents, we need to know their actual size. */ 210 if (extent_map_is_compressed(em)) 211 return false; 212 213 if (em->flags & EXTENT_FLAG_LOGGING) 214 return false; 215 216 /* 217 * We don't want to merge stuff that hasn't been written to the log yet 218 * since it may not reflect exactly what is on disk, and that would be 219 * bad. 220 */ 221 if (!list_empty(&em->list)) 222 return false; 223 224 return true; 225 } 226 227 /* Check to see if two extent_map structs are adjacent and safe to merge. */ 228 static bool mergeable_maps(const struct extent_map *prev, const struct extent_map *next) 229 { 230 if (extent_map_end(prev) != next->start) 231 return false; 232 233 if (prev->flags != next->flags) 234 return false; 235 236 if (next->disk_bytenr < EXTENT_MAP_LAST_BYTE - 1) 237 return extent_map_block_start(next) == extent_map_block_end(prev); 238 239 /* HOLES and INLINE extents. */ 240 return next->disk_bytenr == prev->disk_bytenr; 241 } 242 243 /* 244 * Handle the on-disk data extents merge for @prev and @next. 245 * 246 * @prev: left extent to merge 247 * @next: right extent to merge 248 * @merged: the extent we will not discard after the merge; updated with new values 249 * 250 * After this, one of the two extents is the new merged extent and the other is 251 * removed from the tree and likely freed. Note that @merged is one of @prev/@next 252 * so there is const/non-const aliasing occurring here. 253 * 254 * Only touches disk_bytenr/disk_num_bytes/offset/ram_bytes. 255 * For now only uncompressed regular extent can be merged. 256 */ 257 static void merge_ondisk_extents(const struct extent_map *prev, const struct extent_map *next, 258 struct extent_map *merged) 259 { 260 u64 new_disk_bytenr; 261 u64 new_disk_num_bytes; 262 u64 new_offset; 263 264 /* @prev and @next should not be compressed. */ 265 ASSERT(!extent_map_is_compressed(prev)); 266 ASSERT(!extent_map_is_compressed(next)); 267 268 /* 269 * There are two different cases where @prev and @next can be merged. 270 * 271 * 1) They are referring to the same data extent: 272 * 273 * |<----- data extent A ----->| 274 * |<- prev ->|<- next ->| 275 * 276 * 2) They are referring to different data extents but still adjacent: 277 * 278 * |<-- data extent A -->|<-- data extent B -->| 279 * |<- prev ->|<- next ->| 280 * 281 * The calculation here always merges the data extents first, then updates 282 * @offset using the new data extents. 283 * 284 * For case 1), the merged data extent would be the same. 285 * For case 2), we just merge the two data extents into one. 286 */ 287 new_disk_bytenr = min(prev->disk_bytenr, next->disk_bytenr); 288 new_disk_num_bytes = max(prev->disk_bytenr + prev->disk_num_bytes, 289 next->disk_bytenr + next->disk_num_bytes) - 290 new_disk_bytenr; 291 new_offset = prev->disk_bytenr + prev->offset - new_disk_bytenr; 292 293 merged->disk_bytenr = new_disk_bytenr; 294 merged->disk_num_bytes = new_disk_num_bytes; 295 merged->ram_bytes = new_disk_num_bytes; 296 merged->offset = new_offset; 297 } 298 299 static void dump_extent_map(struct btrfs_fs_info *fs_info, const char *prefix, 300 struct extent_map *em) 301 { 302 if (!IS_ENABLED(CONFIG_BTRFS_DEBUG)) 303 return; 304 btrfs_crit(fs_info, 305 "%s, start=%llu len=%llu disk_bytenr=%llu disk_num_bytes=%llu ram_bytes=%llu offset=%llu flags=0x%x", 306 prefix, em->start, em->len, em->disk_bytenr, em->disk_num_bytes, 307 em->ram_bytes, em->offset, em->flags); 308 ASSERT(0); 309 } 310 311 /* Internal sanity checks for btrfs debug builds. */ 312 static void validate_extent_map(struct btrfs_fs_info *fs_info, struct extent_map *em) 313 { 314 if (!IS_ENABLED(CONFIG_BTRFS_DEBUG)) 315 return; 316 if (em->disk_bytenr < EXTENT_MAP_LAST_BYTE) { 317 if (em->disk_num_bytes == 0) 318 dump_extent_map(fs_info, "zero disk_num_bytes", em); 319 if (em->offset + em->len > em->ram_bytes) 320 dump_extent_map(fs_info, "ram_bytes too small", em); 321 if (em->offset + em->len > em->disk_num_bytes && 322 !extent_map_is_compressed(em)) 323 dump_extent_map(fs_info, "disk_num_bytes too small", em); 324 if (!extent_map_is_compressed(em) && 325 em->ram_bytes != em->disk_num_bytes) 326 dump_extent_map(fs_info, 327 "ram_bytes mismatch with disk_num_bytes for non-compressed em", 328 em); 329 } else if (em->offset) { 330 dump_extent_map(fs_info, "non-zero offset for hole/inline", em); 331 } 332 } 333 334 static void try_merge_map(struct btrfs_inode *inode, struct extent_map *em) 335 { 336 struct btrfs_fs_info *fs_info = inode->root->fs_info; 337 struct extent_map_tree *tree = &inode->extent_tree; 338 struct extent_map *merge = NULL; 339 struct rb_node *rb; 340 341 /* 342 * We can't modify an extent map that is in the tree and that is being 343 * used by another task, as it can cause that other task to see it in 344 * inconsistent state during the merging. We always have 1 reference for 345 * the tree and 1 for this task (which is unpinning the extent map or 346 * clearing the logging flag), so anything > 2 means it's being used by 347 * other tasks too. 348 */ 349 if (refcount_read(&em->refs) > 2) 350 return; 351 352 if (!can_merge_extent_map(em)) 353 return; 354 355 if (em->start != 0) { 356 rb = rb_prev(&em->rb_node); 357 if (rb) 358 merge = rb_entry(rb, struct extent_map, rb_node); 359 if (rb && can_merge_extent_map(merge) && mergeable_maps(merge, em)) { 360 em->start = merge->start; 361 em->len += merge->len; 362 em->generation = max(em->generation, merge->generation); 363 364 if (em->disk_bytenr < EXTENT_MAP_LAST_BYTE) 365 merge_ondisk_extents(merge, em, em); 366 em->flags |= EXTENT_FLAG_MERGED; 367 368 validate_extent_map(fs_info, em); 369 rb_erase(&merge->rb_node, &tree->root); 370 RB_CLEAR_NODE(&merge->rb_node); 371 free_extent_map(merge); 372 dec_evictable_extent_maps(inode); 373 } 374 } 375 376 rb = rb_next(&em->rb_node); 377 if (rb) 378 merge = rb_entry(rb, struct extent_map, rb_node); 379 if (rb && can_merge_extent_map(merge) && mergeable_maps(em, merge)) { 380 em->len += merge->len; 381 if (em->disk_bytenr < EXTENT_MAP_LAST_BYTE) 382 merge_ondisk_extents(em, merge, em); 383 validate_extent_map(fs_info, em); 384 rb_erase(&merge->rb_node, &tree->root); 385 RB_CLEAR_NODE(&merge->rb_node); 386 em->generation = max(em->generation, merge->generation); 387 em->flags |= EXTENT_FLAG_MERGED; 388 free_extent_map(merge); 389 dec_evictable_extent_maps(inode); 390 } 391 } 392 393 /* 394 * Unpin an extent from the cache. 395 * 396 * @inode: the inode from which we are unpinning an extent range 397 * @start: logical offset in the file 398 * @len: length of the extent 399 * @gen: generation that this extent has been modified in 400 * 401 * Called after an extent has been written to disk properly. Set the generation 402 * to the generation that actually added the file item to the inode so we know 403 * we need to sync this extent when we call fsync(). 404 * 405 * Returns: 0 on success 406 * -ENOENT when the extent is not found in the tree 407 * -EUCLEAN if the found extent does not match the expected start 408 */ 409 int unpin_extent_cache(struct btrfs_inode *inode, u64 start, u64 len, u64 gen) 410 { 411 struct btrfs_fs_info *fs_info = inode->root->fs_info; 412 struct extent_map_tree *tree = &inode->extent_tree; 413 int ret = 0; 414 struct extent_map *em; 415 416 write_lock(&tree->lock); 417 em = lookup_extent_mapping(tree, start, len); 418 419 if (WARN_ON(!em)) { 420 btrfs_warn(fs_info, 421 "no extent map found for inode %llu (root %lld) when unpinning extent range [%llu, %llu), generation %llu", 422 btrfs_ino(inode), btrfs_root_id(inode->root), 423 start, start + len, gen); 424 ret = -ENOENT; 425 goto out; 426 } 427 428 if (WARN_ON(em->start != start)) { 429 btrfs_warn(fs_info, 430 "found extent map for inode %llu (root %lld) with unexpected start offset %llu when unpinning extent range [%llu, %llu), generation %llu", 431 btrfs_ino(inode), btrfs_root_id(inode->root), 432 em->start, start, start + len, gen); 433 ret = -EUCLEAN; 434 goto out; 435 } 436 437 em->generation = gen; 438 em->flags &= ~EXTENT_FLAG_PINNED; 439 440 try_merge_map(inode, em); 441 442 out: 443 write_unlock(&tree->lock); 444 free_extent_map(em); 445 return ret; 446 447 } 448 449 void clear_em_logging(struct btrfs_inode *inode, struct extent_map *em) 450 { 451 lockdep_assert_held_write(&inode->extent_tree.lock); 452 453 em->flags &= ~EXTENT_FLAG_LOGGING; 454 if (extent_map_in_tree(em)) 455 try_merge_map(inode, em); 456 } 457 458 static inline void setup_extent_mapping(struct btrfs_inode *inode, 459 struct extent_map *em, 460 int modified) 461 { 462 refcount_inc(&em->refs); 463 464 ASSERT(list_empty(&em->list)); 465 466 if (modified) 467 list_add(&em->list, &inode->extent_tree.modified_extents); 468 else 469 try_merge_map(inode, em); 470 } 471 472 /* 473 * Add a new extent map to an inode's extent map tree. 474 * 475 * @inode: the target inode 476 * @em: map to insert 477 * @modified: indicate whether the given @em should be added to the 478 * modified list, which indicates the extent needs to be logged 479 * 480 * Insert @em into the @inode's extent map tree or perform a simple 481 * forward/backward merge with existing mappings. The extent_map struct passed 482 * in will be inserted into the tree directly, with an additional reference 483 * taken, or a reference dropped if the merge attempt was successful. 484 */ 485 static int add_extent_mapping(struct btrfs_inode *inode, 486 struct extent_map *em, int modified) 487 { 488 struct extent_map_tree *tree = &inode->extent_tree; 489 struct btrfs_root *root = inode->root; 490 struct btrfs_fs_info *fs_info = root->fs_info; 491 int ret; 492 493 lockdep_assert_held_write(&tree->lock); 494 495 validate_extent_map(fs_info, em); 496 ret = tree_insert(&tree->root, em); 497 if (ret) 498 return ret; 499 500 setup_extent_mapping(inode, em, modified); 501 502 if (!btrfs_is_testing(fs_info) && is_fstree(btrfs_root_id(root))) 503 percpu_counter_inc(&fs_info->evictable_extent_maps); 504 505 return 0; 506 } 507 508 static struct extent_map * 509 __lookup_extent_mapping(struct extent_map_tree *tree, 510 u64 start, u64 len, int strict) 511 { 512 struct extent_map *em; 513 struct rb_node *rb_node; 514 struct rb_node *prev_or_next = NULL; 515 u64 end = range_end(start, len); 516 517 rb_node = __tree_search(&tree->root, start, &prev_or_next); 518 if (!rb_node) { 519 if (prev_or_next) 520 rb_node = prev_or_next; 521 else 522 return NULL; 523 } 524 525 em = rb_entry(rb_node, struct extent_map, rb_node); 526 527 if (strict && !(end > em->start && start < extent_map_end(em))) 528 return NULL; 529 530 refcount_inc(&em->refs); 531 return em; 532 } 533 534 /* 535 * Lookup extent_map that intersects @start + @len range. 536 * 537 * @tree: tree to lookup in 538 * @start: byte offset to start the search 539 * @len: length of the lookup range 540 * 541 * Find and return the first extent_map struct in @tree that intersects the 542 * [start, len] range. There may be additional objects in the tree that 543 * intersect, so check the object returned carefully to make sure that no 544 * additional lookups are needed. 545 */ 546 struct extent_map *lookup_extent_mapping(struct extent_map_tree *tree, 547 u64 start, u64 len) 548 { 549 return __lookup_extent_mapping(tree, start, len, 1); 550 } 551 552 /* 553 * Find a nearby extent map intersecting @start + @len (not an exact search). 554 * 555 * @tree: tree to lookup in 556 * @start: byte offset to start the search 557 * @len: length of the lookup range 558 * 559 * Find and return the first extent_map struct in @tree that intersects the 560 * [start, len] range. 561 * 562 * If one can't be found, any nearby extent may be returned 563 */ 564 struct extent_map *search_extent_mapping(struct extent_map_tree *tree, 565 u64 start, u64 len) 566 { 567 return __lookup_extent_mapping(tree, start, len, 0); 568 } 569 570 /* 571 * Remove an extent_map from its inode's extent tree. 572 * 573 * @inode: the inode the extent map belongs to 574 * @em: extent map being removed 575 * 576 * Remove @em from the extent tree of @inode. No reference counts are dropped, 577 * and no checks are done to see if the range is in use. 578 */ 579 void remove_extent_mapping(struct btrfs_inode *inode, struct extent_map *em) 580 { 581 struct extent_map_tree *tree = &inode->extent_tree; 582 583 lockdep_assert_held_write(&tree->lock); 584 585 WARN_ON(em->flags & EXTENT_FLAG_PINNED); 586 rb_erase(&em->rb_node, &tree->root); 587 if (!(em->flags & EXTENT_FLAG_LOGGING)) 588 list_del_init(&em->list); 589 RB_CLEAR_NODE(&em->rb_node); 590 591 dec_evictable_extent_maps(inode); 592 } 593 594 static void replace_extent_mapping(struct btrfs_inode *inode, 595 struct extent_map *cur, 596 struct extent_map *new, 597 int modified) 598 { 599 struct btrfs_fs_info *fs_info = inode->root->fs_info; 600 struct extent_map_tree *tree = &inode->extent_tree; 601 602 lockdep_assert_held_write(&tree->lock); 603 604 validate_extent_map(fs_info, new); 605 606 WARN_ON(cur->flags & EXTENT_FLAG_PINNED); 607 ASSERT(extent_map_in_tree(cur)); 608 if (!(cur->flags & EXTENT_FLAG_LOGGING)) 609 list_del_init(&cur->list); 610 rb_replace_node(&cur->rb_node, &new->rb_node, &tree->root); 611 RB_CLEAR_NODE(&cur->rb_node); 612 613 setup_extent_mapping(inode, new, modified); 614 } 615 616 static struct extent_map *next_extent_map(const struct extent_map *em) 617 { 618 struct rb_node *next; 619 620 next = rb_next(&em->rb_node); 621 if (!next) 622 return NULL; 623 return container_of(next, struct extent_map, rb_node); 624 } 625 626 static struct extent_map *prev_extent_map(struct extent_map *em) 627 { 628 struct rb_node *prev; 629 630 prev = rb_prev(&em->rb_node); 631 if (!prev) 632 return NULL; 633 return container_of(prev, struct extent_map, rb_node); 634 } 635 636 /* 637 * Helper for btrfs_get_extent. Given an existing extent in the tree, 638 * the existing extent is the nearest extent to map_start, 639 * and an extent that you want to insert, deal with overlap and insert 640 * the best fitted new extent into the tree. 641 */ 642 static noinline int merge_extent_mapping(struct btrfs_inode *inode, 643 struct extent_map *existing, 644 struct extent_map *em, 645 u64 map_start) 646 { 647 struct extent_map *prev; 648 struct extent_map *next; 649 u64 start; 650 u64 end; 651 u64 start_diff; 652 653 if (map_start < em->start || map_start >= extent_map_end(em)) 654 return -EINVAL; 655 656 if (existing->start > map_start) { 657 next = existing; 658 prev = prev_extent_map(next); 659 } else { 660 prev = existing; 661 next = next_extent_map(prev); 662 } 663 664 start = prev ? extent_map_end(prev) : em->start; 665 start = max_t(u64, start, em->start); 666 end = next ? next->start : extent_map_end(em); 667 end = min_t(u64, end, extent_map_end(em)); 668 start_diff = start - em->start; 669 em->start = start; 670 em->len = end - start; 671 if (em->disk_bytenr < EXTENT_MAP_LAST_BYTE) 672 em->offset += start_diff; 673 return add_extent_mapping(inode, em, 0); 674 } 675 676 /* 677 * Add extent mapping into an inode's extent map tree. 678 * 679 * @inode: target inode 680 * @em_in: extent we are inserting 681 * @start: start of the logical range btrfs_get_extent() is requesting 682 * @len: length of the logical range btrfs_get_extent() is requesting 683 * 684 * Note that @em_in's range may be different from [start, start+len), 685 * but they must be overlapped. 686 * 687 * Insert @em_in into the inode's extent map tree. In case there is an 688 * overlapping range, handle the -EEXIST by either: 689 * a) Returning the existing extent in @em_in if @start is within the 690 * existing em. 691 * b) Merge the existing extent with @em_in passed in. 692 * 693 * Return 0 on success, otherwise -EEXIST. 694 * 695 */ 696 int btrfs_add_extent_mapping(struct btrfs_inode *inode, 697 struct extent_map **em_in, u64 start, u64 len) 698 { 699 int ret; 700 struct extent_map *em = *em_in; 701 struct btrfs_fs_info *fs_info = inode->root->fs_info; 702 703 /* 704 * Tree-checker should have rejected any inline extent with non-zero 705 * file offset. Here just do a sanity check. 706 */ 707 if (em->disk_bytenr == EXTENT_MAP_INLINE) 708 ASSERT(em->start == 0); 709 710 ret = add_extent_mapping(inode, em, 0); 711 /* it is possible that someone inserted the extent into the tree 712 * while we had the lock dropped. It is also possible that 713 * an overlapping map exists in the tree 714 */ 715 if (ret == -EEXIST) { 716 struct extent_map *existing; 717 718 existing = search_extent_mapping(&inode->extent_tree, start, len); 719 720 trace_btrfs_handle_em_exist(fs_info, existing, em, start, len); 721 722 /* 723 * existing will always be non-NULL, since there must be 724 * extent causing the -EEXIST. 725 */ 726 if (start >= existing->start && 727 start < extent_map_end(existing)) { 728 free_extent_map(em); 729 *em_in = existing; 730 ret = 0; 731 } else { 732 u64 orig_start = em->start; 733 u64 orig_len = em->len; 734 735 /* 736 * The existing extent map is the one nearest to 737 * the [start, start + len) range which overlaps 738 */ 739 ret = merge_extent_mapping(inode, existing, em, start); 740 if (WARN_ON(ret)) { 741 free_extent_map(em); 742 *em_in = NULL; 743 btrfs_warn(fs_info, 744 "extent map merge error existing [%llu, %llu) with em [%llu, %llu) start %llu", 745 existing->start, extent_map_end(existing), 746 orig_start, orig_start + orig_len, start); 747 } 748 free_extent_map(existing); 749 } 750 } 751 752 ASSERT(ret == 0 || ret == -EEXIST); 753 return ret; 754 } 755 756 /* 757 * Drop all extent maps from a tree in the fastest possible way, rescheduling 758 * if needed. This avoids searching the tree, from the root down to the first 759 * extent map, before each deletion. 760 */ 761 static void drop_all_extent_maps_fast(struct btrfs_inode *inode) 762 { 763 struct extent_map_tree *tree = &inode->extent_tree; 764 struct rb_node *node; 765 766 write_lock(&tree->lock); 767 node = rb_first(&tree->root); 768 while (node) { 769 struct extent_map *em; 770 struct rb_node *next = rb_next(node); 771 772 em = rb_entry(node, struct extent_map, rb_node); 773 em->flags &= ~(EXTENT_FLAG_PINNED | EXTENT_FLAG_LOGGING); 774 remove_extent_mapping(inode, em); 775 free_extent_map(em); 776 777 if (cond_resched_rwlock_write(&tree->lock)) 778 node = rb_first(&tree->root); 779 else 780 node = next; 781 } 782 write_unlock(&tree->lock); 783 } 784 785 /* 786 * Drop all extent maps in a given range. 787 * 788 * @inode: The target inode. 789 * @start: Start offset of the range. 790 * @end: End offset of the range (inclusive value). 791 * @skip_pinned: Indicate if pinned extent maps should be ignored or not. 792 * 793 * This drops all the extent maps that intersect the given range [@start, @end]. 794 * Extent maps that partially overlap the range and extend behind or beyond it, 795 * are split. 796 * The caller should have locked an appropriate file range in the inode's io 797 * tree before calling this function. 798 */ 799 void btrfs_drop_extent_map_range(struct btrfs_inode *inode, u64 start, u64 end, 800 bool skip_pinned) 801 { 802 struct extent_map *split; 803 struct extent_map *split2; 804 struct extent_map *em; 805 struct extent_map_tree *em_tree = &inode->extent_tree; 806 u64 len = end - start + 1; 807 808 WARN_ON(end < start); 809 if (end == (u64)-1) { 810 if (start == 0 && !skip_pinned) { 811 drop_all_extent_maps_fast(inode); 812 return; 813 } 814 len = (u64)-1; 815 } else { 816 /* Make end offset exclusive for use in the loop below. */ 817 end++; 818 } 819 820 /* 821 * It's ok if we fail to allocate the extent maps, see the comment near 822 * the bottom of the loop below. We only need two spare extent maps in 823 * the worst case, where the first extent map that intersects our range 824 * starts before the range and the last extent map that intersects our 825 * range ends after our range (and they might be the same extent map), 826 * because we need to split those two extent maps at the boundaries. 827 */ 828 split = alloc_extent_map(); 829 split2 = alloc_extent_map(); 830 831 write_lock(&em_tree->lock); 832 em = lookup_extent_mapping(em_tree, start, len); 833 834 while (em) { 835 /* extent_map_end() returns exclusive value (last byte + 1). */ 836 const u64 em_end = extent_map_end(em); 837 struct extent_map *next_em = NULL; 838 u64 gen; 839 unsigned long flags; 840 bool modified; 841 842 if (em_end < end) { 843 next_em = next_extent_map(em); 844 if (next_em) { 845 if (next_em->start < end) 846 refcount_inc(&next_em->refs); 847 else 848 next_em = NULL; 849 } 850 } 851 852 if (skip_pinned && (em->flags & EXTENT_FLAG_PINNED)) { 853 start = em_end; 854 goto next; 855 } 856 857 flags = em->flags; 858 /* 859 * In case we split the extent map, we want to preserve the 860 * EXTENT_FLAG_LOGGING flag on our extent map, but we don't want 861 * it on the new extent maps. 862 */ 863 em->flags &= ~(EXTENT_FLAG_PINNED | EXTENT_FLAG_LOGGING); 864 modified = !list_empty(&em->list); 865 866 /* 867 * The extent map does not cross our target range, so no need to 868 * split it, we can remove it directly. 869 */ 870 if (em->start >= start && em_end <= end) 871 goto remove_em; 872 873 gen = em->generation; 874 875 if (em->start < start) { 876 if (!split) { 877 split = split2; 878 split2 = NULL; 879 if (!split) 880 goto remove_em; 881 } 882 split->start = em->start; 883 split->len = start - em->start; 884 885 if (em->disk_bytenr < EXTENT_MAP_LAST_BYTE) { 886 split->disk_bytenr = em->disk_bytenr; 887 split->disk_num_bytes = em->disk_num_bytes; 888 split->offset = em->offset; 889 split->ram_bytes = em->ram_bytes; 890 } else { 891 split->disk_bytenr = em->disk_bytenr; 892 split->disk_num_bytes = 0; 893 split->offset = 0; 894 split->ram_bytes = split->len; 895 } 896 897 split->generation = gen; 898 split->flags = flags; 899 replace_extent_mapping(inode, em, split, modified); 900 free_extent_map(split); 901 split = split2; 902 split2 = NULL; 903 } 904 if (em_end > end) { 905 if (!split) { 906 split = split2; 907 split2 = NULL; 908 if (!split) 909 goto remove_em; 910 } 911 split->start = end; 912 split->len = em_end - end; 913 split->disk_bytenr = em->disk_bytenr; 914 split->flags = flags; 915 split->generation = gen; 916 917 if (em->disk_bytenr < EXTENT_MAP_LAST_BYTE) { 918 split->disk_num_bytes = em->disk_num_bytes; 919 split->offset = em->offset + end - em->start; 920 split->ram_bytes = em->ram_bytes; 921 } else { 922 split->disk_num_bytes = 0; 923 split->offset = 0; 924 split->ram_bytes = split->len; 925 } 926 927 if (extent_map_in_tree(em)) { 928 replace_extent_mapping(inode, em, split, modified); 929 } else { 930 int ret; 931 932 ret = add_extent_mapping(inode, split, modified); 933 /* Logic error, shouldn't happen. */ 934 ASSERT(ret == 0); 935 if (WARN_ON(ret != 0) && modified) 936 btrfs_set_inode_full_sync(inode); 937 } 938 free_extent_map(split); 939 split = NULL; 940 } 941 remove_em: 942 if (extent_map_in_tree(em)) { 943 /* 944 * If the extent map is still in the tree it means that 945 * either of the following is true: 946 * 947 * 1) It fits entirely in our range (doesn't end beyond 948 * it or starts before it); 949 * 950 * 2) It starts before our range and/or ends after our 951 * range, and we were not able to allocate the extent 952 * maps for split operations, @split and @split2. 953 * 954 * If we are at case 2) then we just remove the entire 955 * extent map - this is fine since if anyone needs it to 956 * access the subranges outside our range, will just 957 * load it again from the subvolume tree's file extent 958 * item. However if the extent map was in the list of 959 * modified extents, then we must mark the inode for a 960 * full fsync, otherwise a fast fsync will miss this 961 * extent if it's new and needs to be logged. 962 */ 963 if ((em->start < start || em_end > end) && modified) { 964 ASSERT(!split); 965 btrfs_set_inode_full_sync(inode); 966 } 967 remove_extent_mapping(inode, em); 968 } 969 970 /* 971 * Once for the tree reference (we replaced or removed the 972 * extent map from the tree). 973 */ 974 free_extent_map(em); 975 next: 976 /* Once for us (for our lookup reference). */ 977 free_extent_map(em); 978 979 em = next_em; 980 } 981 982 write_unlock(&em_tree->lock); 983 984 free_extent_map(split); 985 free_extent_map(split2); 986 } 987 988 /* 989 * Replace a range in the inode's extent map tree with a new extent map. 990 * 991 * @inode: The target inode. 992 * @new_em: The new extent map to add to the inode's extent map tree. 993 * @modified: Indicate if the new extent map should be added to the list of 994 * modified extents (for fast fsync tracking). 995 * 996 * Drops all the extent maps in the inode's extent map tree that intersect the 997 * range of the new extent map and adds the new extent map to the tree. 998 * The caller should have locked an appropriate file range in the inode's io 999 * tree before calling this function. 1000 */ 1001 int btrfs_replace_extent_map_range(struct btrfs_inode *inode, 1002 struct extent_map *new_em, 1003 bool modified) 1004 { 1005 const u64 end = new_em->start + new_em->len - 1; 1006 struct extent_map_tree *tree = &inode->extent_tree; 1007 int ret; 1008 1009 ASSERT(!extent_map_in_tree(new_em)); 1010 1011 /* 1012 * The caller has locked an appropriate file range in the inode's io 1013 * tree, but getting -EEXIST when adding the new extent map can still 1014 * happen in case there are extents that partially cover the range, and 1015 * this is due to two tasks operating on different parts of the extent. 1016 * See commit 18e83ac75bfe67 ("Btrfs: fix unexpected EEXIST from 1017 * btrfs_get_extent") for an example and details. 1018 */ 1019 do { 1020 btrfs_drop_extent_map_range(inode, new_em->start, end, false); 1021 write_lock(&tree->lock); 1022 ret = add_extent_mapping(inode, new_em, modified); 1023 write_unlock(&tree->lock); 1024 } while (ret == -EEXIST); 1025 1026 return ret; 1027 } 1028 1029 /* 1030 * Split off the first pre bytes from the extent_map at [start, start + len], 1031 * and set the block_start for it to new_logical. 1032 * 1033 * This function is used when an ordered_extent needs to be split. 1034 */ 1035 int split_extent_map(struct btrfs_inode *inode, u64 start, u64 len, u64 pre, 1036 u64 new_logical) 1037 { 1038 struct extent_map_tree *em_tree = &inode->extent_tree; 1039 struct extent_map *em; 1040 struct extent_map *split_pre = NULL; 1041 struct extent_map *split_mid = NULL; 1042 int ret = 0; 1043 unsigned long flags; 1044 1045 ASSERT(pre != 0); 1046 ASSERT(pre < len); 1047 1048 split_pre = alloc_extent_map(); 1049 if (!split_pre) 1050 return -ENOMEM; 1051 split_mid = alloc_extent_map(); 1052 if (!split_mid) { 1053 ret = -ENOMEM; 1054 goto out_free_pre; 1055 } 1056 1057 lock_extent(&inode->io_tree, start, start + len - 1, NULL); 1058 write_lock(&em_tree->lock); 1059 em = lookup_extent_mapping(em_tree, start, len); 1060 if (!em) { 1061 ret = -EIO; 1062 goto out_unlock; 1063 } 1064 1065 ASSERT(em->len == len); 1066 ASSERT(!extent_map_is_compressed(em)); 1067 ASSERT(em->disk_bytenr < EXTENT_MAP_LAST_BYTE); 1068 ASSERT(em->flags & EXTENT_FLAG_PINNED); 1069 ASSERT(!(em->flags & EXTENT_FLAG_LOGGING)); 1070 ASSERT(!list_empty(&em->list)); 1071 1072 flags = em->flags; 1073 em->flags &= ~EXTENT_FLAG_PINNED; 1074 1075 /* First, replace the em with a new extent_map starting from * em->start */ 1076 split_pre->start = em->start; 1077 split_pre->len = pre; 1078 split_pre->disk_bytenr = new_logical; 1079 split_pre->disk_num_bytes = split_pre->len; 1080 split_pre->offset = 0; 1081 split_pre->ram_bytes = split_pre->len; 1082 split_pre->flags = flags; 1083 split_pre->generation = em->generation; 1084 1085 replace_extent_mapping(inode, em, split_pre, 1); 1086 1087 /* 1088 * Now we only have an extent_map at: 1089 * [em->start, em->start + pre] 1090 */ 1091 1092 /* Insert the middle extent_map. */ 1093 split_mid->start = em->start + pre; 1094 split_mid->len = em->len - pre; 1095 split_mid->disk_bytenr = extent_map_block_start(em) + pre; 1096 split_mid->disk_num_bytes = split_mid->len; 1097 split_mid->offset = 0; 1098 split_mid->ram_bytes = split_mid->len; 1099 split_mid->flags = flags; 1100 split_mid->generation = em->generation; 1101 add_extent_mapping(inode, split_mid, 1); 1102 1103 /* Once for us */ 1104 free_extent_map(em); 1105 /* Once for the tree */ 1106 free_extent_map(em); 1107 1108 out_unlock: 1109 write_unlock(&em_tree->lock); 1110 unlock_extent(&inode->io_tree, start, start + len - 1, NULL); 1111 free_extent_map(split_mid); 1112 out_free_pre: 1113 free_extent_map(split_pre); 1114 return ret; 1115 } 1116 1117 struct btrfs_em_shrink_ctx { 1118 long nr_to_scan; 1119 long scanned; 1120 u64 last_ino; 1121 u64 last_root; 1122 }; 1123 1124 static long btrfs_scan_inode(struct btrfs_inode *inode, struct btrfs_em_shrink_ctx *ctx) 1125 { 1126 const u64 cur_fs_gen = btrfs_get_fs_generation(inode->root->fs_info); 1127 struct extent_map_tree *tree = &inode->extent_tree; 1128 long nr_dropped = 0; 1129 struct rb_node *node; 1130 1131 /* 1132 * Take the mmap lock so that we serialize with the inode logging phase 1133 * of fsync because we may need to set the full sync flag on the inode, 1134 * in case we have to remove extent maps in the tree's list of modified 1135 * extents. If we set the full sync flag in the inode while an fsync is 1136 * in progress, we may risk missing new extents because before the flag 1137 * is set, fsync decides to only wait for writeback to complete and then 1138 * during inode logging it sees the flag set and uses the subvolume tree 1139 * to find new extents, which may not be there yet because ordered 1140 * extents haven't completed yet. 1141 * 1142 * We also do a try lock because otherwise we could deadlock. This is 1143 * because the shrinker for this filesystem may be invoked while we are 1144 * in a path that is holding the mmap lock in write mode. For example in 1145 * a reflink operation while COWing an extent buffer, when allocating 1146 * pages for a new extent buffer and under memory pressure, the shrinker 1147 * may be invoked, and therefore we would deadlock by attempting to read 1148 * lock the mmap lock while we are holding already a write lock on it. 1149 */ 1150 if (!down_read_trylock(&inode->i_mmap_lock)) 1151 return 0; 1152 1153 /* 1154 * We want to be fast so if the lock is busy we don't want to spend time 1155 * waiting for it - either some task is about to do IO for the inode or 1156 * we may have another task shrinking extent maps, here in this code, so 1157 * skip this inode. 1158 */ 1159 if (!write_trylock(&tree->lock)) { 1160 up_read(&inode->i_mmap_lock); 1161 return 0; 1162 } 1163 1164 node = rb_first(&tree->root); 1165 while (node) { 1166 struct rb_node *next = rb_next(node); 1167 struct extent_map *em; 1168 1169 em = rb_entry(node, struct extent_map, rb_node); 1170 ctx->scanned++; 1171 1172 if (em->flags & EXTENT_FLAG_PINNED) 1173 goto next; 1174 1175 /* 1176 * If the inode is in the list of modified extents (new) and its 1177 * generation is the same (or is greater than) the current fs 1178 * generation, it means it was not yet persisted so we have to 1179 * set the full sync flag so that the next fsync will not miss 1180 * it. 1181 */ 1182 if (!list_empty(&em->list) && em->generation >= cur_fs_gen) 1183 btrfs_set_inode_full_sync(inode); 1184 1185 remove_extent_mapping(inode, em); 1186 trace_btrfs_extent_map_shrinker_remove_em(inode, em); 1187 /* Drop the reference for the tree. */ 1188 free_extent_map(em); 1189 nr_dropped++; 1190 next: 1191 if (ctx->scanned >= ctx->nr_to_scan) 1192 break; 1193 1194 /* 1195 * Stop if we need to reschedule or there's contention on the 1196 * lock. This is to avoid slowing other tasks trying to take the 1197 * lock. 1198 */ 1199 if (need_resched() || rwlock_needbreak(&tree->lock)) 1200 break; 1201 node = next; 1202 } 1203 write_unlock(&tree->lock); 1204 up_read(&inode->i_mmap_lock); 1205 1206 return nr_dropped; 1207 } 1208 1209 static long btrfs_scan_root(struct btrfs_root *root, struct btrfs_em_shrink_ctx *ctx) 1210 { 1211 struct btrfs_inode *inode; 1212 long nr_dropped = 0; 1213 u64 min_ino = ctx->last_ino + 1; 1214 1215 inode = btrfs_find_first_inode(root, min_ino); 1216 while (inode) { 1217 nr_dropped += btrfs_scan_inode(inode, ctx); 1218 1219 min_ino = btrfs_ino(inode) + 1; 1220 ctx->last_ino = btrfs_ino(inode); 1221 btrfs_add_delayed_iput(inode); 1222 1223 if (ctx->scanned >= ctx->nr_to_scan) 1224 break; 1225 1226 cond_resched(); 1227 1228 inode = btrfs_find_first_inode(root, min_ino); 1229 } 1230 1231 if (inode) { 1232 /* 1233 * There are still inodes in this root or we happened to process 1234 * the last one and reached the scan limit. In either case set 1235 * the current root to this one, so we'll resume from the next 1236 * inode if there is one or we will find out this was the last 1237 * one and move to the next root. 1238 */ 1239 ctx->last_root = btrfs_root_id(root); 1240 } else { 1241 /* 1242 * No more inodes in this root, set extent_map_shrinker_last_ino to 0 so 1243 * that when processing the next root we start from its first inode. 1244 */ 1245 ctx->last_ino = 0; 1246 ctx->last_root = btrfs_root_id(root) + 1; 1247 } 1248 1249 return nr_dropped; 1250 } 1251 1252 long btrfs_free_extent_maps(struct btrfs_fs_info *fs_info, long nr_to_scan) 1253 { 1254 struct btrfs_em_shrink_ctx ctx; 1255 u64 start_root_id; 1256 u64 next_root_id; 1257 bool cycled = false; 1258 long nr_dropped = 0; 1259 1260 ctx.scanned = 0; 1261 ctx.nr_to_scan = nr_to_scan; 1262 1263 /* 1264 * In case we have multiple tasks running this shrinker, make the next 1265 * one start from the next inode in case it starts before we finish. 1266 */ 1267 spin_lock(&fs_info->extent_map_shrinker_lock); 1268 ctx.last_ino = fs_info->extent_map_shrinker_last_ino; 1269 fs_info->extent_map_shrinker_last_ino++; 1270 ctx.last_root = fs_info->extent_map_shrinker_last_root; 1271 spin_unlock(&fs_info->extent_map_shrinker_lock); 1272 1273 start_root_id = ctx.last_root; 1274 next_root_id = ctx.last_root; 1275 1276 if (trace_btrfs_extent_map_shrinker_scan_enter_enabled()) { 1277 s64 nr = percpu_counter_sum_positive(&fs_info->evictable_extent_maps); 1278 1279 trace_btrfs_extent_map_shrinker_scan_enter(fs_info, nr_to_scan, 1280 nr, ctx.last_root, 1281 ctx.last_ino); 1282 } 1283 1284 while (ctx.scanned < ctx.nr_to_scan) { 1285 struct btrfs_root *root; 1286 unsigned long count; 1287 1288 cond_resched(); 1289 1290 spin_lock(&fs_info->fs_roots_radix_lock); 1291 count = radix_tree_gang_lookup(&fs_info->fs_roots_radix, 1292 (void **)&root, 1293 (unsigned long)next_root_id, 1); 1294 if (count == 0) { 1295 spin_unlock(&fs_info->fs_roots_radix_lock); 1296 if (start_root_id > 0 && !cycled) { 1297 next_root_id = 0; 1298 ctx.last_root = 0; 1299 ctx.last_ino = 0; 1300 cycled = true; 1301 continue; 1302 } 1303 break; 1304 } 1305 next_root_id = btrfs_root_id(root) + 1; 1306 root = btrfs_grab_root(root); 1307 spin_unlock(&fs_info->fs_roots_radix_lock); 1308 1309 if (!root) 1310 continue; 1311 1312 if (is_fstree(btrfs_root_id(root))) 1313 nr_dropped += btrfs_scan_root(root, &ctx); 1314 1315 btrfs_put_root(root); 1316 } 1317 1318 /* 1319 * In case of multiple tasks running this extent map shrinking code this 1320 * isn't perfect but it's simple and silences things like KCSAN. It's 1321 * not possible to know which task made more progress because we can 1322 * cycle back to the first root and first inode if it's not the first 1323 * time the shrinker ran, see the above logic. Also a task that started 1324 * later may finish ealier than another task and made less progress. So 1325 * make this simple and update to the progress of the last task that 1326 * finished, with the occasional possiblity of having two consecutive 1327 * runs of the shrinker process the same inodes. 1328 */ 1329 spin_lock(&fs_info->extent_map_shrinker_lock); 1330 fs_info->extent_map_shrinker_last_ino = ctx.last_ino; 1331 fs_info->extent_map_shrinker_last_root = ctx.last_root; 1332 spin_unlock(&fs_info->extent_map_shrinker_lock); 1333 1334 if (trace_btrfs_extent_map_shrinker_scan_exit_enabled()) { 1335 s64 nr = percpu_counter_sum_positive(&fs_info->evictable_extent_maps); 1336 1337 trace_btrfs_extent_map_shrinker_scan_exit(fs_info, nr_dropped, 1338 nr, ctx.last_root, 1339 ctx.last_ino); 1340 } 1341 1342 return nr_dropped; 1343 } 1344