1 // SPDX-License-Identifier: GPL-2.0 2 /* 3 * Copyright (C) 2007 Oracle. All rights reserved. 4 */ 5 6 #include <linux/sched.h> 7 #include <linux/sched/signal.h> 8 #include <linux/pagemap.h> 9 #include <linux/writeback.h> 10 #include <linux/blkdev.h> 11 #include <linux/sort.h> 12 #include <linux/rcupdate.h> 13 #include <linux/kthread.h> 14 #include <linux/slab.h> 15 #include <linux/ratelimit.h> 16 #include <linux/percpu_counter.h> 17 #include <linux/lockdep.h> 18 #include <linux/crc32c.h> 19 #include "ctree.h" 20 #include "extent-tree.h" 21 #include "transaction.h" 22 #include "disk-io.h" 23 #include "print-tree.h" 24 #include "volumes.h" 25 #include "raid56.h" 26 #include "locking.h" 27 #include "free-space-cache.h" 28 #include "free-space-tree.h" 29 #include "qgroup.h" 30 #include "ref-verify.h" 31 #include "space-info.h" 32 #include "block-rsv.h" 33 #include "discard.h" 34 #include "zoned.h" 35 #include "dev-replace.h" 36 #include "fs.h" 37 #include "accessors.h" 38 #include "root-tree.h" 39 #include "file-item.h" 40 #include "orphan.h" 41 #include "tree-checker.h" 42 #include "raid-stripe-tree.h" 43 #include "delayed-inode.h" 44 #include "relocation.h" 45 46 #undef SCRAMBLE_DELAYED_REFS 47 48 49 static int __btrfs_free_extent(struct btrfs_trans_handle *trans, 50 struct btrfs_delayed_ref_head *href, 51 const struct btrfs_delayed_ref_node *node, 52 struct btrfs_delayed_extent_op *extra_op); 53 static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op, 54 struct extent_buffer *leaf, 55 struct btrfs_extent_item *ei); 56 static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans, 57 u64 parent, u64 root_objectid, 58 u64 flags, u64 owner, u64 offset, 59 struct btrfs_key *ins, int ref_mod, u64 oref_root); 60 static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans, 61 const struct btrfs_delayed_ref_node *node, 62 struct btrfs_delayed_extent_op *extent_op); 63 static int find_next_key(const struct btrfs_path *path, int level, 64 struct btrfs_key *key); 65 66 static int block_group_bits(const struct btrfs_block_group *cache, u64 bits) 67 { 68 return (cache->flags & bits) == bits; 69 } 70 71 /* simple helper to search for an existing data extent at a given offset */ 72 int btrfs_lookup_data_extent(struct btrfs_fs_info *fs_info, u64 start, u64 len) 73 { 74 struct btrfs_root *root = btrfs_extent_root(fs_info, start); 75 struct btrfs_key key; 76 BTRFS_PATH_AUTO_FREE(path); 77 78 if (unlikely(!root)) { 79 btrfs_err(fs_info, 80 "missing extent root for extent at bytenr %llu", start); 81 return -EUCLEAN; 82 } 83 84 path = btrfs_alloc_path(); 85 if (!path) 86 return -ENOMEM; 87 88 key.objectid = start; 89 key.type = BTRFS_EXTENT_ITEM_KEY; 90 key.offset = len; 91 return btrfs_search_slot(NULL, root, &key, path, 0, 0); 92 } 93 94 /* 95 * helper function to lookup reference count and flags of a tree block. 96 * 97 * the head node for delayed ref is used to store the sum of all the 98 * reference count modifications queued up in the rbtree. the head 99 * node may also store the extent flags to set. This way you can check 100 * to see what the reference count and extent flags would be if all of 101 * the delayed refs are not processed. 102 */ 103 int btrfs_lookup_extent_info(struct btrfs_trans_handle *trans, 104 struct btrfs_fs_info *fs_info, u64 bytenr, 105 u64 offset, int metadata, u64 *refs, u64 *flags, 106 u64 *owning_root) 107 { 108 struct btrfs_root *extent_root; 109 struct btrfs_delayed_ref_head *head; 110 struct btrfs_delayed_ref_root *delayed_refs; 111 BTRFS_PATH_AUTO_FREE(path); 112 struct btrfs_key key; 113 u64 num_refs; 114 u64 extent_flags; 115 u64 owner = 0; 116 int ret; 117 118 /* 119 * If we don't have skinny metadata, don't bother doing anything 120 * different 121 */ 122 if (metadata && !btrfs_fs_incompat(fs_info, SKINNY_METADATA)) { 123 offset = fs_info->nodesize; 124 metadata = 0; 125 } 126 127 path = btrfs_alloc_path(); 128 if (!path) 129 return -ENOMEM; 130 131 search_again: 132 key.objectid = bytenr; 133 if (metadata) 134 key.type = BTRFS_METADATA_ITEM_KEY; 135 else 136 key.type = BTRFS_EXTENT_ITEM_KEY; 137 key.offset = offset; 138 139 extent_root = btrfs_extent_root(fs_info, bytenr); 140 if (unlikely(!extent_root)) { 141 btrfs_err(fs_info, 142 "missing extent root for extent at bytenr %llu", bytenr); 143 return -EUCLEAN; 144 } 145 146 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0); 147 if (ret < 0) 148 return ret; 149 150 if (ret > 0 && key.type == BTRFS_METADATA_ITEM_KEY) { 151 if (path->slots[0]) { 152 path->slots[0]--; 153 btrfs_item_key_to_cpu(path->nodes[0], &key, 154 path->slots[0]); 155 if (key.objectid == bytenr && 156 key.type == BTRFS_EXTENT_ITEM_KEY && 157 key.offset == fs_info->nodesize) 158 ret = 0; 159 } 160 } 161 162 if (ret == 0) { 163 struct extent_buffer *leaf = path->nodes[0]; 164 struct btrfs_extent_item *ei; 165 const u32 item_size = btrfs_item_size(leaf, path->slots[0]); 166 167 if (unlikely(item_size < sizeof(*ei))) { 168 ret = -EUCLEAN; 169 btrfs_err(fs_info, 170 "unexpected extent item size, has %u expect >= %zu", 171 item_size, sizeof(*ei)); 172 btrfs_abort_transaction(trans, ret); 173 return ret; 174 } 175 176 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item); 177 num_refs = btrfs_extent_refs(leaf, ei); 178 if (unlikely(num_refs == 0)) { 179 ret = -EUCLEAN; 180 btrfs_err(fs_info, 181 "unexpected zero reference count for extent item " BTRFS_KEY_FMT, 182 BTRFS_KEY_FMT_VALUE(&key)); 183 btrfs_abort_transaction(trans, ret); 184 return ret; 185 } 186 extent_flags = btrfs_extent_flags(leaf, ei); 187 owner = btrfs_get_extent_owner_root(fs_info, leaf, path->slots[0]); 188 } else { 189 num_refs = 0; 190 extent_flags = 0; 191 ret = 0; 192 } 193 194 delayed_refs = &trans->transaction->delayed_refs; 195 spin_lock(&delayed_refs->lock); 196 head = btrfs_find_delayed_ref_head(fs_info, delayed_refs, bytenr); 197 if (head) { 198 if (!mutex_trylock(&head->mutex)) { 199 refcount_inc(&head->refs); 200 spin_unlock(&delayed_refs->lock); 201 202 btrfs_release_path(path); 203 204 /* 205 * Mutex was contended, block until it's released and try 206 * again 207 */ 208 mutex_lock(&head->mutex); 209 mutex_unlock(&head->mutex); 210 btrfs_put_delayed_ref_head(head); 211 goto search_again; 212 } 213 spin_lock(&head->lock); 214 if (head->extent_op && head->extent_op->update_flags) 215 extent_flags |= head->extent_op->flags_to_set; 216 217 num_refs += head->ref_mod; 218 spin_unlock(&head->lock); 219 mutex_unlock(&head->mutex); 220 } 221 spin_unlock(&delayed_refs->lock); 222 223 WARN_ON(num_refs == 0); 224 if (refs) 225 *refs = num_refs; 226 if (flags) 227 *flags = extent_flags; 228 if (owning_root) 229 *owning_root = owner; 230 231 return ret; 232 } 233 234 /* 235 * Back reference rules. Back refs have three main goals: 236 * 237 * 1) differentiate between all holders of references to an extent so that 238 * when a reference is dropped we can make sure it was a valid reference 239 * before freeing the extent. 240 * 241 * 2) Provide enough information to quickly find the holders of an extent 242 * if we notice a given block is corrupted or bad. 243 * 244 * 3) Make it easy to migrate blocks for FS shrinking or storage pool 245 * maintenance. This is actually the same as #2, but with a slightly 246 * different use case. 247 * 248 * There are two kinds of back refs. The implicit back refs is optimized 249 * for pointers in non-shared tree blocks. For a given pointer in a block, 250 * back refs of this kind provide information about the block's owner tree 251 * and the pointer's key. These information allow us to find the block by 252 * b-tree searching. The full back refs is for pointers in tree blocks not 253 * referenced by their owner trees. The location of tree block is recorded 254 * in the back refs. Actually the full back refs is generic, and can be 255 * used in all cases the implicit back refs is used. The major shortcoming 256 * of the full back refs is its overhead. Every time a tree block gets 257 * COWed, we have to update back refs entry for all pointers in it. 258 * 259 * For a newly allocated tree block, we use implicit back refs for 260 * pointers in it. This means most tree related operations only involve 261 * implicit back refs. For a tree block created in old transaction, the 262 * only way to drop a reference to it is COW it. So we can detect the 263 * event that tree block loses its owner tree's reference and do the 264 * back refs conversion. 265 * 266 * When a tree block is COWed through a tree, there are four cases: 267 * 268 * The reference count of the block is one and the tree is the block's 269 * owner tree. Nothing to do in this case. 270 * 271 * The reference count of the block is one and the tree is not the 272 * block's owner tree. In this case, full back refs is used for pointers 273 * in the block. Remove these full back refs, add implicit back refs for 274 * every pointers in the new block. 275 * 276 * The reference count of the block is greater than one and the tree is 277 * the block's owner tree. In this case, implicit back refs is used for 278 * pointers in the block. Add full back refs for every pointers in the 279 * block, increase lower level extents' reference counts. The original 280 * implicit back refs are entailed to the new block. 281 * 282 * The reference count of the block is greater than one and the tree is 283 * not the block's owner tree. Add implicit back refs for every pointer in 284 * the new block, increase lower level extents' reference count. 285 * 286 * Back Reference Key composing: 287 * 288 * The key objectid corresponds to the first byte in the extent, 289 * The key type is used to differentiate between types of back refs. 290 * There are different meanings of the key offset for different types 291 * of back refs. 292 * 293 * File extents can be referenced by: 294 * 295 * - multiple snapshots, subvolumes, or different generations in one subvol 296 * - different files inside a single subvolume 297 * - different offsets inside a file (bookend extents in file.c) 298 * 299 * The extent ref structure for the implicit back refs has fields for: 300 * 301 * - Objectid of the subvolume root 302 * - objectid of the file holding the reference 303 * - original offset in the file 304 * - how many bookend extents 305 * 306 * The key offset for the implicit back refs is hash of the first 307 * three fields. 308 * 309 * The extent ref structure for the full back refs has field for: 310 * 311 * - number of pointers in the tree leaf 312 * 313 * The key offset for the implicit back refs is the first byte of 314 * the tree leaf 315 * 316 * When a file extent is allocated, The implicit back refs is used. 317 * the fields are filled in: 318 * 319 * (root_key.objectid, inode objectid, offset in file, 1) 320 * 321 * When a file extent is removed file truncation, we find the 322 * corresponding implicit back refs and check the following fields: 323 * 324 * (btrfs_header_owner(leaf), inode objectid, offset in file) 325 * 326 * Btree extents can be referenced by: 327 * 328 * - Different subvolumes 329 * 330 * Both the implicit back refs and the full back refs for tree blocks 331 * only consist of key. The key offset for the implicit back refs is 332 * objectid of block's owner tree. The key offset for the full back refs 333 * is the first byte of parent block. 334 * 335 * When implicit back refs is used, information about the lowest key and 336 * level of the tree block are required. These information are stored in 337 * tree block info structure. 338 */ 339 340 /* 341 * is_data == BTRFS_REF_TYPE_BLOCK, tree block type is required, 342 * is_data == BTRFS_REF_TYPE_DATA, data type is required, 343 * is_data == BTRFS_REF_TYPE_ANY, either type is OK. 344 */ 345 int btrfs_get_extent_inline_ref_type(const struct extent_buffer *eb, 346 const struct btrfs_extent_inline_ref *iref, 347 enum btrfs_inline_ref_type is_data) 348 { 349 struct btrfs_fs_info *fs_info = eb->fs_info; 350 int type = btrfs_extent_inline_ref_type(eb, iref); 351 u64 offset = btrfs_extent_inline_ref_offset(eb, iref); 352 353 if (type == BTRFS_EXTENT_OWNER_REF_KEY) { 354 ASSERT(btrfs_fs_incompat(fs_info, SIMPLE_QUOTA)); 355 return type; 356 } 357 358 if (type == BTRFS_TREE_BLOCK_REF_KEY || 359 type == BTRFS_SHARED_BLOCK_REF_KEY || 360 type == BTRFS_SHARED_DATA_REF_KEY || 361 type == BTRFS_EXTENT_DATA_REF_KEY) { 362 if (is_data == BTRFS_REF_TYPE_BLOCK) { 363 if (type == BTRFS_TREE_BLOCK_REF_KEY) 364 return type; 365 if (type == BTRFS_SHARED_BLOCK_REF_KEY) { 366 ASSERT(fs_info); 367 /* 368 * Every shared one has parent tree block, 369 * which must be aligned to sector size. 370 */ 371 if (offset && IS_ALIGNED(offset, fs_info->sectorsize)) 372 return type; 373 } 374 } else if (is_data == BTRFS_REF_TYPE_DATA) { 375 if (type == BTRFS_EXTENT_DATA_REF_KEY) 376 return type; 377 if (type == BTRFS_SHARED_DATA_REF_KEY) { 378 ASSERT(fs_info); 379 /* 380 * Every shared one has parent tree block, 381 * which must be aligned to sector size. 382 */ 383 if (offset && 384 IS_ALIGNED(offset, fs_info->sectorsize)) 385 return type; 386 } 387 } else { 388 ASSERT(is_data == BTRFS_REF_TYPE_ANY); 389 return type; 390 } 391 } 392 393 WARN_ON(1); 394 btrfs_print_leaf(eb); 395 btrfs_err(fs_info, 396 "eb %llu iref 0x%lx invalid extent inline ref type %d", 397 eb->start, (unsigned long)iref, type); 398 399 return BTRFS_REF_TYPE_INVALID; 400 } 401 402 u64 hash_extent_data_ref(u64 root_objectid, u64 owner, u64 offset) 403 { 404 u32 high_crc = ~(u32)0; 405 u32 low_crc = ~(u32)0; 406 __le64 lenum; 407 408 lenum = cpu_to_le64(root_objectid); 409 high_crc = crc32c(high_crc, &lenum, sizeof(lenum)); 410 lenum = cpu_to_le64(owner); 411 low_crc = crc32c(low_crc, &lenum, sizeof(lenum)); 412 lenum = cpu_to_le64(offset); 413 low_crc = crc32c(low_crc, &lenum, sizeof(lenum)); 414 415 return ((u64)high_crc << 31) ^ (u64)low_crc; 416 } 417 418 static u64 hash_extent_data_ref_item(const struct extent_buffer *leaf, 419 const struct btrfs_extent_data_ref *ref) 420 { 421 return hash_extent_data_ref(btrfs_extent_data_ref_root(leaf, ref), 422 btrfs_extent_data_ref_objectid(leaf, ref), 423 btrfs_extent_data_ref_offset(leaf, ref)); 424 } 425 426 static bool match_extent_data_ref(const struct extent_buffer *leaf, 427 const struct btrfs_extent_data_ref *ref, 428 u64 root_objectid, u64 owner, u64 offset) 429 { 430 if (btrfs_extent_data_ref_root(leaf, ref) != root_objectid || 431 btrfs_extent_data_ref_objectid(leaf, ref) != owner || 432 btrfs_extent_data_ref_offset(leaf, ref) != offset) 433 return false; 434 return true; 435 } 436 437 static noinline int lookup_extent_data_ref(struct btrfs_trans_handle *trans, 438 struct btrfs_path *path, 439 u64 bytenr, u64 parent, 440 u64 root_objectid, 441 u64 owner, u64 offset) 442 { 443 struct btrfs_root *root = btrfs_extent_root(trans->fs_info, bytenr); 444 struct btrfs_key key; 445 struct btrfs_extent_data_ref *ref; 446 struct extent_buffer *leaf; 447 u32 nritems; 448 int recow; 449 int ret; 450 451 if (unlikely(!root)) { 452 btrfs_err(trans->fs_info, 453 "missing extent root for extent at bytenr %llu", bytenr); 454 return -EUCLEAN; 455 } 456 457 key.objectid = bytenr; 458 if (parent) { 459 key.type = BTRFS_SHARED_DATA_REF_KEY; 460 key.offset = parent; 461 } else { 462 key.type = BTRFS_EXTENT_DATA_REF_KEY; 463 key.offset = hash_extent_data_ref(root_objectid, 464 owner, offset); 465 } 466 again: 467 recow = 0; 468 ret = btrfs_search_slot(trans, root, &key, path, -1, 1); 469 if (ret < 0) 470 return ret; 471 472 if (parent) { 473 if (ret) 474 return -ENOENT; 475 return 0; 476 } 477 478 ret = -ENOENT; 479 leaf = path->nodes[0]; 480 nritems = btrfs_header_nritems(leaf); 481 while (1) { 482 if (path->slots[0] >= nritems) { 483 ret = btrfs_next_leaf(root, path); 484 if (ret) { 485 if (ret > 0) 486 return -ENOENT; 487 return ret; 488 } 489 490 leaf = path->nodes[0]; 491 nritems = btrfs_header_nritems(leaf); 492 recow = 1; 493 } 494 495 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]); 496 if (key.objectid != bytenr || 497 key.type != BTRFS_EXTENT_DATA_REF_KEY) 498 return -ENOENT; 499 500 ref = btrfs_item_ptr(leaf, path->slots[0], 501 struct btrfs_extent_data_ref); 502 503 if (match_extent_data_ref(leaf, ref, root_objectid, 504 owner, offset)) { 505 if (recow) { 506 btrfs_release_path(path); 507 goto again; 508 } 509 return 0; 510 } 511 path->slots[0]++; 512 } 513 514 return ret; 515 } 516 517 static noinline int insert_extent_data_ref(struct btrfs_trans_handle *trans, 518 struct btrfs_path *path, 519 const struct btrfs_delayed_ref_node *node, 520 u64 bytenr) 521 { 522 struct btrfs_root *root = btrfs_extent_root(trans->fs_info, bytenr); 523 struct btrfs_key key; 524 struct extent_buffer *leaf; 525 u64 owner = btrfs_delayed_ref_owner(node); 526 u64 offset = btrfs_delayed_ref_offset(node); 527 u32 size; 528 u32 num_refs; 529 int ret; 530 531 if (unlikely(!root)) { 532 btrfs_err(trans->fs_info, 533 "missing extent root for extent at bytenr %llu", bytenr); 534 return -EUCLEAN; 535 } 536 537 key.objectid = bytenr; 538 if (node->parent) { 539 key.type = BTRFS_SHARED_DATA_REF_KEY; 540 key.offset = node->parent; 541 size = sizeof(struct btrfs_shared_data_ref); 542 } else { 543 key.type = BTRFS_EXTENT_DATA_REF_KEY; 544 key.offset = hash_extent_data_ref(node->ref_root, owner, offset); 545 size = sizeof(struct btrfs_extent_data_ref); 546 } 547 548 ret = btrfs_insert_empty_item(trans, root, path, &key, size); 549 if (ret && ret != -EEXIST) 550 goto fail; 551 552 leaf = path->nodes[0]; 553 if (node->parent) { 554 struct btrfs_shared_data_ref *ref; 555 ref = btrfs_item_ptr(leaf, path->slots[0], 556 struct btrfs_shared_data_ref); 557 if (ret == 0) { 558 btrfs_set_shared_data_ref_count(leaf, ref, node->ref_mod); 559 } else { 560 num_refs = btrfs_shared_data_ref_count(leaf, ref); 561 num_refs += node->ref_mod; 562 btrfs_set_shared_data_ref_count(leaf, ref, num_refs); 563 } 564 } else { 565 struct btrfs_extent_data_ref *ref; 566 while (ret == -EEXIST) { 567 ref = btrfs_item_ptr(leaf, path->slots[0], 568 struct btrfs_extent_data_ref); 569 if (match_extent_data_ref(leaf, ref, node->ref_root, 570 owner, offset)) 571 break; 572 btrfs_release_path(path); 573 key.offset++; 574 ret = btrfs_insert_empty_item(trans, root, path, &key, 575 size); 576 if (ret && ret != -EEXIST) 577 goto fail; 578 579 leaf = path->nodes[0]; 580 } 581 ref = btrfs_item_ptr(leaf, path->slots[0], 582 struct btrfs_extent_data_ref); 583 if (ret == 0) { 584 btrfs_set_extent_data_ref_root(leaf, ref, node->ref_root); 585 btrfs_set_extent_data_ref_objectid(leaf, ref, owner); 586 btrfs_set_extent_data_ref_offset(leaf, ref, offset); 587 btrfs_set_extent_data_ref_count(leaf, ref, node->ref_mod); 588 } else { 589 num_refs = btrfs_extent_data_ref_count(leaf, ref); 590 num_refs += node->ref_mod; 591 btrfs_set_extent_data_ref_count(leaf, ref, num_refs); 592 } 593 } 594 ret = 0; 595 fail: 596 btrfs_release_path(path); 597 return ret; 598 } 599 600 static noinline int remove_extent_data_ref(struct btrfs_trans_handle *trans, 601 struct btrfs_root *root, 602 struct btrfs_path *path, 603 int refs_to_drop) 604 { 605 struct btrfs_key key; 606 struct btrfs_extent_data_ref *ref1 = NULL; 607 struct btrfs_shared_data_ref *ref2 = NULL; 608 struct extent_buffer *leaf; 609 u32 num_refs = 0; 610 int ret = 0; 611 612 leaf = path->nodes[0]; 613 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]); 614 615 if (key.type == BTRFS_EXTENT_DATA_REF_KEY) { 616 ref1 = btrfs_item_ptr(leaf, path->slots[0], 617 struct btrfs_extent_data_ref); 618 num_refs = btrfs_extent_data_ref_count(leaf, ref1); 619 } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) { 620 ref2 = btrfs_item_ptr(leaf, path->slots[0], 621 struct btrfs_shared_data_ref); 622 num_refs = btrfs_shared_data_ref_count(leaf, ref2); 623 } else { 624 btrfs_err(trans->fs_info, 625 "unrecognized backref key " BTRFS_KEY_FMT, 626 BTRFS_KEY_FMT_VALUE(&key)); 627 btrfs_abort_transaction(trans, -EUCLEAN); 628 return -EUCLEAN; 629 } 630 631 BUG_ON(num_refs < refs_to_drop); 632 num_refs -= refs_to_drop; 633 634 if (num_refs == 0) { 635 ret = btrfs_del_item(trans, root, path); 636 } else { 637 if (key.type == BTRFS_EXTENT_DATA_REF_KEY) 638 btrfs_set_extent_data_ref_count(leaf, ref1, num_refs); 639 else if (key.type == BTRFS_SHARED_DATA_REF_KEY) 640 btrfs_set_shared_data_ref_count(leaf, ref2, num_refs); 641 } 642 return ret; 643 } 644 645 static noinline u32 extent_data_ref_count(const struct btrfs_path *path, 646 const struct btrfs_extent_inline_ref *iref) 647 { 648 struct btrfs_key key; 649 struct extent_buffer *leaf; 650 const struct btrfs_extent_data_ref *ref1; 651 const struct btrfs_shared_data_ref *ref2; 652 u32 num_refs = 0; 653 int type; 654 655 leaf = path->nodes[0]; 656 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]); 657 658 if (iref) { 659 /* 660 * If type is invalid, we should have bailed out earlier than 661 * this call. 662 */ 663 type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_DATA); 664 ASSERT(type != BTRFS_REF_TYPE_INVALID); 665 if (type == BTRFS_EXTENT_DATA_REF_KEY) { 666 ref1 = (const struct btrfs_extent_data_ref *)(&iref->offset); 667 num_refs = btrfs_extent_data_ref_count(leaf, ref1); 668 } else { 669 ref2 = (const struct btrfs_shared_data_ref *)(iref + 1); 670 num_refs = btrfs_shared_data_ref_count(leaf, ref2); 671 } 672 } else if (key.type == BTRFS_EXTENT_DATA_REF_KEY) { 673 ref1 = btrfs_item_ptr(leaf, path->slots[0], 674 struct btrfs_extent_data_ref); 675 num_refs = btrfs_extent_data_ref_count(leaf, ref1); 676 } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) { 677 ref2 = btrfs_item_ptr(leaf, path->slots[0], 678 struct btrfs_shared_data_ref); 679 num_refs = btrfs_shared_data_ref_count(leaf, ref2); 680 } else { 681 WARN_ON(1); 682 } 683 return num_refs; 684 } 685 686 static noinline int lookup_tree_block_ref(struct btrfs_trans_handle *trans, 687 struct btrfs_path *path, 688 u64 bytenr, u64 parent, 689 u64 root_objectid) 690 { 691 struct btrfs_root *root = btrfs_extent_root(trans->fs_info, bytenr); 692 struct btrfs_key key; 693 int ret; 694 695 if (unlikely(!root)) { 696 btrfs_err(trans->fs_info, 697 "missing extent root for extent at bytenr %llu", bytenr); 698 return -EUCLEAN; 699 } 700 701 key.objectid = bytenr; 702 if (parent) { 703 key.type = BTRFS_SHARED_BLOCK_REF_KEY; 704 key.offset = parent; 705 } else { 706 key.type = BTRFS_TREE_BLOCK_REF_KEY; 707 key.offset = root_objectid; 708 } 709 710 ret = btrfs_search_slot(trans, root, &key, path, -1, 1); 711 if (ret > 0) 712 ret = -ENOENT; 713 return ret; 714 } 715 716 static noinline int insert_tree_block_ref(struct btrfs_trans_handle *trans, 717 struct btrfs_path *path, 718 const struct btrfs_delayed_ref_node *node, 719 u64 bytenr) 720 { 721 struct btrfs_root *root = btrfs_extent_root(trans->fs_info, bytenr); 722 struct btrfs_key key; 723 int ret; 724 725 if (unlikely(!root)) { 726 btrfs_err(trans->fs_info, 727 "missing extent root for extent at bytenr %llu", bytenr); 728 return -EUCLEAN; 729 } 730 731 key.objectid = bytenr; 732 if (node->parent) { 733 key.type = BTRFS_SHARED_BLOCK_REF_KEY; 734 key.offset = node->parent; 735 } else { 736 key.type = BTRFS_TREE_BLOCK_REF_KEY; 737 key.offset = node->ref_root; 738 } 739 740 ret = btrfs_insert_empty_item(trans, root, path, &key, 0); 741 btrfs_release_path(path); 742 return ret; 743 } 744 745 static inline int extent_ref_type(u64 parent, u64 owner) 746 { 747 int type; 748 if (owner < BTRFS_FIRST_FREE_OBJECTID) { 749 if (parent > 0) 750 type = BTRFS_SHARED_BLOCK_REF_KEY; 751 else 752 type = BTRFS_TREE_BLOCK_REF_KEY; 753 } else { 754 if (parent > 0) 755 type = BTRFS_SHARED_DATA_REF_KEY; 756 else 757 type = BTRFS_EXTENT_DATA_REF_KEY; 758 } 759 return type; 760 } 761 762 static int find_next_key(const struct btrfs_path *path, int level, 763 struct btrfs_key *key) 764 765 { 766 for (; level < BTRFS_MAX_LEVEL; level++) { 767 if (!path->nodes[level]) 768 break; 769 if (path->slots[level] + 1 >= 770 btrfs_header_nritems(path->nodes[level])) 771 continue; 772 if (level == 0) 773 btrfs_item_key_to_cpu(path->nodes[level], key, 774 path->slots[level] + 1); 775 else 776 btrfs_node_key_to_cpu(path->nodes[level], key, 777 path->slots[level] + 1); 778 return 0; 779 } 780 return 1; 781 } 782 783 /* 784 * look for inline back ref. if back ref is found, *ref_ret is set 785 * to the address of inline back ref, and 0 is returned. 786 * 787 * if back ref isn't found, *ref_ret is set to the address where it 788 * should be inserted, and -ENOENT is returned. 789 * 790 * if insert is true and there are too many inline back refs, the path 791 * points to the extent item, and -EAGAIN is returned. 792 * 793 * NOTE: inline back refs are ordered in the same way that back ref 794 * items in the tree are ordered. 795 */ 796 static noinline_for_stack 797 int lookup_inline_extent_backref(struct btrfs_trans_handle *trans, 798 struct btrfs_path *path, 799 struct btrfs_extent_inline_ref **ref_ret, 800 u64 bytenr, u64 num_bytes, 801 u64 parent, u64 root_objectid, 802 u64 owner, u64 offset, int insert) 803 { 804 struct btrfs_fs_info *fs_info = trans->fs_info; 805 struct btrfs_root *root = btrfs_extent_root(fs_info, bytenr); 806 struct btrfs_key key; 807 struct extent_buffer *leaf; 808 struct btrfs_extent_item *ei; 809 struct btrfs_extent_inline_ref *iref; 810 u64 flags; 811 u64 item_size; 812 unsigned long ptr; 813 unsigned long end; 814 int extra_size; 815 int type; 816 int want; 817 int ret; 818 bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA); 819 int needed; 820 821 if (unlikely(!root)) { 822 btrfs_err(fs_info, 823 "missing extent root for extent at bytenr %llu", bytenr); 824 return -EUCLEAN; 825 } 826 827 key.objectid = bytenr; 828 key.type = BTRFS_EXTENT_ITEM_KEY; 829 key.offset = num_bytes; 830 831 want = extent_ref_type(parent, owner); 832 if (insert) { 833 extra_size = btrfs_extent_inline_ref_size(want); 834 path->search_for_extension = true; 835 } else 836 extra_size = -1; 837 838 /* 839 * Owner is our level, so we can just add one to get the level for the 840 * block we are interested in. 841 */ 842 if (skinny_metadata && owner < BTRFS_FIRST_FREE_OBJECTID) { 843 key.type = BTRFS_METADATA_ITEM_KEY; 844 key.offset = owner; 845 } 846 847 again: 848 ret = btrfs_search_slot(trans, root, &key, path, extra_size, 1); 849 if (ret < 0) 850 goto out; 851 852 /* 853 * We may be a newly converted file system which still has the old fat 854 * extent entries for metadata, so try and see if we have one of those. 855 */ 856 if (ret > 0 && skinny_metadata) { 857 skinny_metadata = false; 858 if (path->slots[0]) { 859 path->slots[0]--; 860 btrfs_item_key_to_cpu(path->nodes[0], &key, 861 path->slots[0]); 862 if (key.objectid == bytenr && 863 key.type == BTRFS_EXTENT_ITEM_KEY && 864 key.offset == num_bytes) 865 ret = 0; 866 } 867 if (ret) { 868 key.objectid = bytenr; 869 key.type = BTRFS_EXTENT_ITEM_KEY; 870 key.offset = num_bytes; 871 btrfs_release_path(path); 872 goto again; 873 } 874 } 875 876 if (ret && !insert) { 877 ret = -ENOENT; 878 goto out; 879 } else if (WARN_ON(ret)) { 880 btrfs_print_leaf(path->nodes[0]); 881 btrfs_err(fs_info, 882 "extent item not found for insert, bytenr %llu num_bytes %llu parent %llu root_objectid %llu owner %llu offset %llu", 883 bytenr, num_bytes, parent, root_objectid, owner, 884 offset); 885 ret = -EUCLEAN; 886 goto out; 887 } 888 889 leaf = path->nodes[0]; 890 item_size = btrfs_item_size(leaf, path->slots[0]); 891 if (unlikely(item_size < sizeof(*ei))) { 892 ret = -EUCLEAN; 893 btrfs_err(fs_info, 894 "unexpected extent item size, has %llu expect >= %zu", 895 item_size, sizeof(*ei)); 896 btrfs_abort_transaction(trans, ret); 897 goto out; 898 } 899 900 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item); 901 flags = btrfs_extent_flags(leaf, ei); 902 903 ptr = (unsigned long)(ei + 1); 904 end = (unsigned long)ei + item_size; 905 906 if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK && !skinny_metadata) { 907 ptr += sizeof(struct btrfs_tree_block_info); 908 BUG_ON(ptr > end); 909 } 910 911 if (owner >= BTRFS_FIRST_FREE_OBJECTID) 912 needed = BTRFS_REF_TYPE_DATA; 913 else 914 needed = BTRFS_REF_TYPE_BLOCK; 915 916 ret = -ENOENT; 917 while (ptr < end) { 918 iref = (struct btrfs_extent_inline_ref *)ptr; 919 type = btrfs_get_extent_inline_ref_type(leaf, iref, needed); 920 if (type == BTRFS_EXTENT_OWNER_REF_KEY) { 921 ASSERT(btrfs_fs_incompat(fs_info, SIMPLE_QUOTA)); 922 ptr += btrfs_extent_inline_ref_size(type); 923 continue; 924 } 925 if (unlikely(type == BTRFS_REF_TYPE_INVALID)) { 926 ret = -EUCLEAN; 927 goto out; 928 } 929 930 if (want < type) 931 break; 932 if (want > type) { 933 ptr += btrfs_extent_inline_ref_size(type); 934 continue; 935 } 936 937 if (type == BTRFS_EXTENT_DATA_REF_KEY) { 938 struct btrfs_extent_data_ref *dref; 939 dref = (struct btrfs_extent_data_ref *)(&iref->offset); 940 if (match_extent_data_ref(leaf, dref, root_objectid, 941 owner, offset)) { 942 ret = 0; 943 break; 944 } 945 if (hash_extent_data_ref_item(leaf, dref) < 946 hash_extent_data_ref(root_objectid, owner, offset)) 947 break; 948 } else { 949 u64 ref_offset; 950 ref_offset = btrfs_extent_inline_ref_offset(leaf, iref); 951 if (parent > 0) { 952 if (parent == ref_offset) { 953 ret = 0; 954 break; 955 } 956 if (ref_offset < parent) 957 break; 958 } else { 959 if (root_objectid == ref_offset) { 960 ret = 0; 961 break; 962 } 963 if (ref_offset < root_objectid) 964 break; 965 } 966 } 967 ptr += btrfs_extent_inline_ref_size(type); 968 } 969 970 if (unlikely(ptr > end)) { 971 ret = -EUCLEAN; 972 btrfs_print_leaf(path->nodes[0]); 973 btrfs_crit(fs_info, 974 "overrun extent record at slot %d while looking for inline extent for root %llu owner %llu offset %llu parent %llu", 975 path->slots[0], root_objectid, owner, offset, parent); 976 goto out; 977 } 978 979 if (ret == -ENOENT && insert) { 980 if (item_size + extra_size >= 981 BTRFS_MAX_EXTENT_ITEM_SIZE(root)) { 982 ret = -EAGAIN; 983 goto out; 984 } 985 986 if (path->slots[0] + 1 < btrfs_header_nritems(path->nodes[0])) { 987 struct btrfs_key tmp_key; 988 989 btrfs_item_key_to_cpu(path->nodes[0], &tmp_key, path->slots[0] + 1); 990 if (tmp_key.objectid == bytenr && 991 tmp_key.type < BTRFS_BLOCK_GROUP_ITEM_KEY) { 992 ret = -EAGAIN; 993 goto out; 994 } 995 goto out_no_entry; 996 } 997 998 if (!path->keep_locks) { 999 btrfs_release_path(path); 1000 path->keep_locks = true; 1001 goto again; 1002 } 1003 1004 /* 1005 * To add new inline back ref, we have to make sure 1006 * there is no corresponding back ref item. 1007 * For simplicity, we just do not add new inline back 1008 * ref if there is any kind of item for this block 1009 */ 1010 if (find_next_key(path, 0, &key) == 0 && 1011 key.objectid == bytenr && 1012 key.type < BTRFS_BLOCK_GROUP_ITEM_KEY) { 1013 ret = -EAGAIN; 1014 goto out; 1015 } 1016 } 1017 out_no_entry: 1018 *ref_ret = (struct btrfs_extent_inline_ref *)ptr; 1019 out: 1020 if (path->keep_locks) { 1021 path->keep_locks = false; 1022 btrfs_unlock_up_safe(path, 1); 1023 } 1024 if (insert) 1025 path->search_for_extension = false; 1026 return ret; 1027 } 1028 1029 /* 1030 * helper to add new inline back ref 1031 */ 1032 static noinline_for_stack 1033 void setup_inline_extent_backref(struct btrfs_trans_handle *trans, 1034 struct btrfs_path *path, 1035 struct btrfs_extent_inline_ref *iref, 1036 u64 parent, u64 root_objectid, 1037 u64 owner, u64 offset, int refs_to_add, 1038 struct btrfs_delayed_extent_op *extent_op) 1039 { 1040 struct extent_buffer *leaf; 1041 struct btrfs_extent_item *ei; 1042 unsigned long ptr; 1043 unsigned long end; 1044 unsigned long item_offset; 1045 u64 refs; 1046 int size; 1047 int type; 1048 1049 leaf = path->nodes[0]; 1050 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item); 1051 item_offset = (unsigned long)iref - (unsigned long)ei; 1052 1053 type = extent_ref_type(parent, owner); 1054 size = btrfs_extent_inline_ref_size(type); 1055 1056 btrfs_extend_item(trans, path, size); 1057 1058 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item); 1059 refs = btrfs_extent_refs(leaf, ei); 1060 refs += refs_to_add; 1061 btrfs_set_extent_refs(leaf, ei, refs); 1062 if (extent_op) 1063 __run_delayed_extent_op(extent_op, leaf, ei); 1064 1065 ptr = (unsigned long)ei + item_offset; 1066 end = (unsigned long)ei + btrfs_item_size(leaf, path->slots[0]); 1067 if (ptr < end - size) 1068 memmove_extent_buffer(leaf, ptr + size, ptr, 1069 end - size - ptr); 1070 1071 iref = (struct btrfs_extent_inline_ref *)ptr; 1072 btrfs_set_extent_inline_ref_type(leaf, iref, type); 1073 if (type == BTRFS_EXTENT_DATA_REF_KEY) { 1074 struct btrfs_extent_data_ref *dref; 1075 dref = (struct btrfs_extent_data_ref *)(&iref->offset); 1076 btrfs_set_extent_data_ref_root(leaf, dref, root_objectid); 1077 btrfs_set_extent_data_ref_objectid(leaf, dref, owner); 1078 btrfs_set_extent_data_ref_offset(leaf, dref, offset); 1079 btrfs_set_extent_data_ref_count(leaf, dref, refs_to_add); 1080 } else if (type == BTRFS_SHARED_DATA_REF_KEY) { 1081 struct btrfs_shared_data_ref *sref; 1082 sref = (struct btrfs_shared_data_ref *)(iref + 1); 1083 btrfs_set_shared_data_ref_count(leaf, sref, refs_to_add); 1084 btrfs_set_extent_inline_ref_offset(leaf, iref, parent); 1085 } else if (type == BTRFS_SHARED_BLOCK_REF_KEY) { 1086 btrfs_set_extent_inline_ref_offset(leaf, iref, parent); 1087 } else { 1088 btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid); 1089 } 1090 } 1091 1092 static int lookup_extent_backref(struct btrfs_trans_handle *trans, 1093 struct btrfs_path *path, 1094 struct btrfs_extent_inline_ref **ref_ret, 1095 u64 bytenr, u64 num_bytes, u64 parent, 1096 u64 root_objectid, u64 owner, u64 offset) 1097 { 1098 int ret; 1099 1100 ret = lookup_inline_extent_backref(trans, path, ref_ret, bytenr, 1101 num_bytes, parent, root_objectid, 1102 owner, offset, 0); 1103 if (ret != -ENOENT) 1104 return ret; 1105 1106 btrfs_release_path(path); 1107 *ref_ret = NULL; 1108 1109 if (owner < BTRFS_FIRST_FREE_OBJECTID) { 1110 ret = lookup_tree_block_ref(trans, path, bytenr, parent, 1111 root_objectid); 1112 } else { 1113 ret = lookup_extent_data_ref(trans, path, bytenr, parent, 1114 root_objectid, owner, offset); 1115 } 1116 return ret; 1117 } 1118 1119 /* 1120 * helper to update/remove inline back ref 1121 */ 1122 static noinline_for_stack int update_inline_extent_backref( 1123 struct btrfs_trans_handle *trans, 1124 struct btrfs_path *path, 1125 struct btrfs_extent_inline_ref *iref, 1126 int refs_to_mod, 1127 struct btrfs_delayed_extent_op *extent_op) 1128 { 1129 struct extent_buffer *leaf = path->nodes[0]; 1130 struct btrfs_fs_info *fs_info = leaf->fs_info; 1131 struct btrfs_extent_item *ei; 1132 struct btrfs_extent_data_ref *dref = NULL; 1133 struct btrfs_shared_data_ref *sref = NULL; 1134 unsigned long ptr; 1135 unsigned long end; 1136 u32 item_size; 1137 int size; 1138 int type; 1139 u64 refs; 1140 1141 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item); 1142 refs = btrfs_extent_refs(leaf, ei); 1143 if (unlikely(refs_to_mod < 0 && refs + refs_to_mod <= 0)) { 1144 struct btrfs_key key; 1145 u32 extent_size; 1146 1147 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]); 1148 if (key.type == BTRFS_METADATA_ITEM_KEY) 1149 extent_size = fs_info->nodesize; 1150 else 1151 extent_size = key.offset; 1152 btrfs_print_leaf(leaf); 1153 btrfs_err(fs_info, 1154 "invalid refs_to_mod for extent %llu num_bytes %u, has %d expect >= -%llu", 1155 key.objectid, extent_size, refs_to_mod, refs); 1156 return -EUCLEAN; 1157 } 1158 refs += refs_to_mod; 1159 btrfs_set_extent_refs(leaf, ei, refs); 1160 if (extent_op) 1161 __run_delayed_extent_op(extent_op, leaf, ei); 1162 1163 type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_ANY); 1164 /* 1165 * Function btrfs_get_extent_inline_ref_type() has already printed 1166 * error messages. 1167 */ 1168 if (unlikely(type == BTRFS_REF_TYPE_INVALID)) 1169 return -EUCLEAN; 1170 1171 if (type == BTRFS_EXTENT_DATA_REF_KEY) { 1172 dref = (struct btrfs_extent_data_ref *)(&iref->offset); 1173 refs = btrfs_extent_data_ref_count(leaf, dref); 1174 } else if (type == BTRFS_SHARED_DATA_REF_KEY) { 1175 sref = (struct btrfs_shared_data_ref *)(iref + 1); 1176 refs = btrfs_shared_data_ref_count(leaf, sref); 1177 } else { 1178 refs = 1; 1179 /* 1180 * For tree blocks we can only drop one ref for it, and tree 1181 * blocks should not have refs > 1. 1182 * 1183 * Furthermore if we're inserting a new inline backref, we 1184 * won't reach this path either. That would be 1185 * setup_inline_extent_backref(). 1186 */ 1187 if (unlikely(refs_to_mod != -1)) { 1188 struct btrfs_key key; 1189 1190 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]); 1191 1192 btrfs_print_leaf(leaf); 1193 btrfs_err(fs_info, 1194 "invalid refs_to_mod for tree block %llu, has %d expect -1", 1195 key.objectid, refs_to_mod); 1196 return -EUCLEAN; 1197 } 1198 } 1199 1200 if (unlikely(refs_to_mod < 0 && refs < -refs_to_mod)) { 1201 struct btrfs_key key; 1202 u32 extent_size; 1203 1204 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]); 1205 if (key.type == BTRFS_METADATA_ITEM_KEY) 1206 extent_size = fs_info->nodesize; 1207 else 1208 extent_size = key.offset; 1209 btrfs_print_leaf(leaf); 1210 btrfs_err(fs_info, 1211 "invalid refs_to_mod for backref entry, iref %lu extent %llu num_bytes %u, has %d expect >= -%llu", 1212 (unsigned long)iref, key.objectid, extent_size, 1213 refs_to_mod, refs); 1214 return -EUCLEAN; 1215 } 1216 refs += refs_to_mod; 1217 1218 if (refs > 0) { 1219 if (type == BTRFS_EXTENT_DATA_REF_KEY) 1220 btrfs_set_extent_data_ref_count(leaf, dref, refs); 1221 else 1222 btrfs_set_shared_data_ref_count(leaf, sref, refs); 1223 } else { 1224 size = btrfs_extent_inline_ref_size(type); 1225 item_size = btrfs_item_size(leaf, path->slots[0]); 1226 ptr = (unsigned long)iref; 1227 end = (unsigned long)ei + item_size; 1228 if (ptr + size < end) 1229 memmove_extent_buffer(leaf, ptr, ptr + size, 1230 end - ptr - size); 1231 item_size -= size; 1232 btrfs_truncate_item(trans, path, item_size, 1); 1233 } 1234 return 0; 1235 } 1236 1237 static noinline_for_stack 1238 int insert_inline_extent_backref(struct btrfs_trans_handle *trans, 1239 struct btrfs_path *path, 1240 u64 bytenr, u64 num_bytes, u64 parent, 1241 u64 root_objectid, u64 owner, 1242 u64 offset, int refs_to_add, 1243 struct btrfs_delayed_extent_op *extent_op) 1244 { 1245 struct btrfs_extent_inline_ref *iref; 1246 int ret; 1247 1248 ret = lookup_inline_extent_backref(trans, path, &iref, bytenr, 1249 num_bytes, parent, root_objectid, 1250 owner, offset, 1); 1251 if (ret == 0) { 1252 /* 1253 * We're adding refs to a tree block we already own, this 1254 * should not happen at all. 1255 */ 1256 if (unlikely(owner < BTRFS_FIRST_FREE_OBJECTID)) { 1257 btrfs_print_leaf(path->nodes[0]); 1258 btrfs_crit(trans->fs_info, 1259 "adding refs to an existing tree ref, bytenr %llu num_bytes %llu root_objectid %llu slot %u", 1260 bytenr, num_bytes, root_objectid, path->slots[0]); 1261 return -EUCLEAN; 1262 } 1263 ret = update_inline_extent_backref(trans, path, iref, 1264 refs_to_add, extent_op); 1265 } else if (ret == -ENOENT) { 1266 setup_inline_extent_backref(trans, path, iref, parent, 1267 root_objectid, owner, offset, 1268 refs_to_add, extent_op); 1269 ret = 0; 1270 } 1271 return ret; 1272 } 1273 1274 static int remove_extent_backref(struct btrfs_trans_handle *trans, 1275 struct btrfs_root *root, 1276 struct btrfs_path *path, 1277 struct btrfs_extent_inline_ref *iref, 1278 int refs_to_drop, int is_data) 1279 { 1280 int ret = 0; 1281 1282 BUG_ON(!is_data && refs_to_drop != 1); 1283 if (iref) 1284 ret = update_inline_extent_backref(trans, path, iref, 1285 -refs_to_drop, NULL); 1286 else if (is_data) 1287 ret = remove_extent_data_ref(trans, root, path, refs_to_drop); 1288 else 1289 ret = btrfs_del_item(trans, root, path); 1290 return ret; 1291 } 1292 1293 static int btrfs_issue_discard(struct block_device *bdev, u64 start, u64 len, 1294 u64 *discarded_bytes) 1295 { 1296 int j, ret = 0; 1297 u64 bytes_left, end; 1298 u64 aligned_start = ALIGN(start, SECTOR_SIZE); 1299 1300 /* Adjust the range to be aligned to 512B sectors if necessary. */ 1301 if (start != aligned_start) { 1302 len -= aligned_start - start; 1303 len = round_down(len, SECTOR_SIZE); 1304 start = aligned_start; 1305 } 1306 1307 *discarded_bytes = 0; 1308 1309 if (!len) 1310 return 0; 1311 1312 end = start + len; 1313 bytes_left = len; 1314 1315 /* Skip any superblocks on this device. */ 1316 for (j = 0; j < BTRFS_SUPER_MIRROR_MAX; j++) { 1317 u64 sb_start = btrfs_sb_offset(j); 1318 u64 sb_end = sb_start + BTRFS_SUPER_INFO_SIZE; 1319 u64 size = sb_start - start; 1320 1321 if (!in_range(sb_start, start, bytes_left) && 1322 !in_range(sb_end, start, bytes_left) && 1323 !in_range(start, sb_start, BTRFS_SUPER_INFO_SIZE)) 1324 continue; 1325 1326 /* 1327 * Superblock spans beginning of range. Adjust start and 1328 * try again. 1329 */ 1330 if (sb_start <= start) { 1331 start += sb_end - start; 1332 if (start > end) { 1333 bytes_left = 0; 1334 break; 1335 } 1336 bytes_left = end - start; 1337 continue; 1338 } 1339 1340 if (size) { 1341 ret = blkdev_issue_discard(bdev, start >> SECTOR_SHIFT, 1342 size >> SECTOR_SHIFT, 1343 GFP_NOFS); 1344 if (!ret) 1345 *discarded_bytes += size; 1346 else if (ret != -EOPNOTSUPP) 1347 return ret; 1348 } 1349 1350 start = sb_end; 1351 if (start > end) { 1352 bytes_left = 0; 1353 break; 1354 } 1355 bytes_left = end - start; 1356 } 1357 1358 while (bytes_left) { 1359 u64 bytes_to_discard = min(BTRFS_MAX_DISCARD_CHUNK_SIZE, bytes_left); 1360 1361 ret = blkdev_issue_discard(bdev, start >> SECTOR_SHIFT, 1362 bytes_to_discard >> SECTOR_SHIFT, 1363 GFP_NOFS); 1364 1365 if (ret) { 1366 if (ret != -EOPNOTSUPP) 1367 break; 1368 continue; 1369 } 1370 1371 start += bytes_to_discard; 1372 bytes_left -= bytes_to_discard; 1373 *discarded_bytes += bytes_to_discard; 1374 1375 if (btrfs_trim_interrupted()) { 1376 ret = -ERESTARTSYS; 1377 break; 1378 } 1379 } 1380 1381 return ret; 1382 } 1383 1384 static int do_discard_extent(struct btrfs_discard_stripe *stripe, u64 *bytes) 1385 { 1386 struct btrfs_device *dev = stripe->dev; 1387 struct btrfs_fs_info *fs_info = dev->fs_info; 1388 struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace; 1389 u64 phys = stripe->physical; 1390 u64 len = stripe->length; 1391 u64 discarded = 0; 1392 int ret = 0; 1393 1394 /* Zone reset on a zoned filesystem */ 1395 if (btrfs_can_zone_reset(dev, phys, len)) { 1396 u64 src_disc; 1397 1398 ret = btrfs_reset_device_zone(dev, phys, len, &discarded); 1399 if (ret) 1400 goto out; 1401 1402 if (!btrfs_dev_replace_is_ongoing(dev_replace) || 1403 dev != dev_replace->srcdev) 1404 goto out; 1405 1406 src_disc = discarded; 1407 1408 /* Send to replace target as well */ 1409 ret = btrfs_reset_device_zone(dev_replace->tgtdev, phys, len, 1410 &discarded); 1411 discarded += src_disc; 1412 } else if (bdev_max_discard_sectors(stripe->dev->bdev)) { 1413 ret = btrfs_issue_discard(dev->bdev, phys, len, &discarded); 1414 } else { 1415 ret = 0; 1416 *bytes = 0; 1417 } 1418 1419 out: 1420 *bytes = discarded; 1421 return ret; 1422 } 1423 1424 int btrfs_discard_extent(struct btrfs_fs_info *fs_info, u64 bytenr, 1425 u64 num_bytes, u64 *actual_bytes, bool do_remap) 1426 { 1427 int ret = 0; 1428 u64 discarded_bytes = 0; 1429 u64 end = bytenr + num_bytes; 1430 u64 cur = bytenr; 1431 1432 /* 1433 * Avoid races with device replace and make sure the devices in the 1434 * stripes don't go away while we are discarding. 1435 */ 1436 btrfs_bio_counter_inc_blocked(fs_info); 1437 while (cur < end) { 1438 struct btrfs_discard_stripe *stripes; 1439 unsigned int num_stripes; 1440 int i; 1441 1442 num_bytes = end - cur; 1443 stripes = btrfs_map_discard(fs_info, cur, &num_bytes, &num_stripes, 1444 do_remap); 1445 if (IS_ERR(stripes)) { 1446 ret = PTR_ERR(stripes); 1447 if (ret == -EOPNOTSUPP) 1448 ret = 0; 1449 break; 1450 } 1451 1452 for (i = 0; i < num_stripes; i++) { 1453 struct btrfs_discard_stripe *stripe = stripes + i; 1454 u64 bytes; 1455 1456 if (!stripe->dev->bdev) { 1457 ASSERT(btrfs_test_opt(fs_info, DEGRADED)); 1458 continue; 1459 } 1460 1461 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, 1462 &stripe->dev->dev_state)) 1463 continue; 1464 1465 ret = do_discard_extent(stripe, &bytes); 1466 if (ret) { 1467 /* 1468 * Keep going if discard is not supported by the 1469 * device. 1470 */ 1471 if (ret != -EOPNOTSUPP) 1472 break; 1473 ret = 0; 1474 } else { 1475 discarded_bytes += bytes; 1476 } 1477 } 1478 kfree(stripes); 1479 if (ret) 1480 break; 1481 cur += num_bytes; 1482 } 1483 btrfs_bio_counter_dec(fs_info); 1484 if (actual_bytes) 1485 *actual_bytes = discarded_bytes; 1486 return ret; 1487 } 1488 1489 /* Can return -ENOMEM */ 1490 int btrfs_inc_extent_ref(struct btrfs_trans_handle *trans, 1491 struct btrfs_ref *generic_ref) 1492 { 1493 struct btrfs_fs_info *fs_info = trans->fs_info; 1494 int ret; 1495 1496 ASSERT(generic_ref->type != BTRFS_REF_NOT_SET && 1497 generic_ref->action); 1498 BUG_ON(generic_ref->type == BTRFS_REF_METADATA && 1499 generic_ref->ref_root == BTRFS_TREE_LOG_OBJECTID); 1500 1501 if (generic_ref->type == BTRFS_REF_METADATA) 1502 ret = btrfs_add_delayed_tree_ref(trans, generic_ref, NULL); 1503 else 1504 ret = btrfs_add_delayed_data_ref(trans, generic_ref, 0); 1505 1506 btrfs_ref_tree_mod(fs_info, generic_ref); 1507 1508 return ret; 1509 } 1510 1511 /* 1512 * Insert backreference for a given extent. 1513 * 1514 * The counterpart is in __btrfs_free_extent(), with examples and more details 1515 * how it works. 1516 * 1517 * @trans: Handle of transaction 1518 * 1519 * @node: The delayed ref node used to get the bytenr/length for 1520 * extent whose references are incremented. 1521 * 1522 * @extent_op Pointer to a structure, holding information necessary when 1523 * updating a tree block's flags 1524 * 1525 */ 1526 static int __btrfs_inc_extent_ref(struct btrfs_trans_handle *trans, 1527 const struct btrfs_delayed_ref_node *node, 1528 struct btrfs_delayed_extent_op *extent_op) 1529 { 1530 BTRFS_PATH_AUTO_FREE(path); 1531 struct extent_buffer *leaf; 1532 struct btrfs_extent_item *item; 1533 struct btrfs_key key; 1534 u64 bytenr = node->bytenr; 1535 u64 num_bytes = node->num_bytes; 1536 u64 owner = btrfs_delayed_ref_owner(node); 1537 u64 offset = btrfs_delayed_ref_offset(node); 1538 u64 refs; 1539 int refs_to_add = node->ref_mod; 1540 int ret; 1541 1542 path = btrfs_alloc_path(); 1543 if (!path) 1544 return -ENOMEM; 1545 1546 /* this will setup the path even if it fails to insert the back ref */ 1547 ret = insert_inline_extent_backref(trans, path, bytenr, num_bytes, 1548 node->parent, node->ref_root, owner, 1549 offset, refs_to_add, extent_op); 1550 if ((ret < 0 && ret != -EAGAIN) || !ret) 1551 return ret; 1552 1553 /* 1554 * Ok we had -EAGAIN which means we didn't have space to insert and 1555 * inline extent ref, so just update the reference count and add a 1556 * normal backref. 1557 */ 1558 leaf = path->nodes[0]; 1559 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]); 1560 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item); 1561 refs = btrfs_extent_refs(leaf, item); 1562 btrfs_set_extent_refs(leaf, item, refs + refs_to_add); 1563 if (extent_op) 1564 __run_delayed_extent_op(extent_op, leaf, item); 1565 1566 btrfs_release_path(path); 1567 1568 /* now insert the actual backref */ 1569 if (owner < BTRFS_FIRST_FREE_OBJECTID) { 1570 ret = insert_tree_block_ref(trans, path, node, bytenr); 1571 if (ret) 1572 btrfs_abort_transaction(trans, ret); 1573 } else { 1574 ret = insert_extent_data_ref(trans, path, node, bytenr); 1575 if (ret) 1576 btrfs_abort_transaction(trans, ret); 1577 } 1578 1579 return ret; 1580 } 1581 1582 static void free_head_ref_squota_rsv(struct btrfs_fs_info *fs_info, 1583 const struct btrfs_delayed_ref_head *href) 1584 { 1585 u64 root = href->owning_root; 1586 1587 /* 1588 * Don't check must_insert_reserved, as this is called from contexts 1589 * where it has already been unset. 1590 */ 1591 if (btrfs_qgroup_mode(fs_info) != BTRFS_QGROUP_MODE_SIMPLE || 1592 !href->is_data || !btrfs_is_fstree(root)) 1593 return; 1594 1595 btrfs_qgroup_free_refroot(fs_info, root, href->reserved_bytes, 1596 BTRFS_QGROUP_RSV_DATA); 1597 } 1598 1599 static int drop_remap_tree_ref(struct btrfs_trans_handle *trans, 1600 const struct btrfs_delayed_ref_node *node) 1601 { 1602 u64 bytenr = node->bytenr; 1603 u64 num_bytes = node->num_bytes; 1604 int ret; 1605 1606 ret = btrfs_add_to_free_space_tree(trans, bytenr, num_bytes); 1607 if (unlikely(ret)) { 1608 btrfs_abort_transaction(trans, ret); 1609 return ret; 1610 } 1611 1612 ret = btrfs_update_block_group(trans, bytenr, num_bytes, false); 1613 if (unlikely(ret)) { 1614 btrfs_abort_transaction(trans, ret); 1615 return ret; 1616 } 1617 1618 return 0; 1619 } 1620 1621 static int run_delayed_data_ref(struct btrfs_trans_handle *trans, 1622 struct btrfs_delayed_ref_head *href, 1623 const struct btrfs_delayed_ref_node *node, 1624 struct btrfs_delayed_extent_op *extent_op, 1625 bool insert_reserved) 1626 { 1627 int ret = 0; 1628 u64 parent = 0; 1629 u64 flags = 0; 1630 1631 trace_run_delayed_data_ref(trans->fs_info, node); 1632 1633 if (node->type == BTRFS_SHARED_DATA_REF_KEY) 1634 parent = node->parent; 1635 1636 if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) { 1637 struct btrfs_key key; 1638 struct btrfs_squota_delta delta = { 1639 .root = href->owning_root, 1640 .num_bytes = node->num_bytes, 1641 .is_data = true, 1642 .is_inc = true, 1643 .generation = trans->transid, 1644 }; 1645 u64 owner = btrfs_delayed_ref_owner(node); 1646 u64 offset = btrfs_delayed_ref_offset(node); 1647 1648 if (extent_op) 1649 flags |= extent_op->flags_to_set; 1650 1651 key.objectid = node->bytenr; 1652 key.type = BTRFS_EXTENT_ITEM_KEY; 1653 key.offset = node->num_bytes; 1654 1655 ret = alloc_reserved_file_extent(trans, parent, node->ref_root, 1656 flags, owner, offset, &key, 1657 node->ref_mod, 1658 href->owning_root); 1659 free_head_ref_squota_rsv(trans->fs_info, href); 1660 if (!ret) 1661 ret = btrfs_record_squota_delta(trans->fs_info, &delta); 1662 } else if (node->action == BTRFS_ADD_DELAYED_REF) { 1663 ret = __btrfs_inc_extent_ref(trans, node, extent_op); 1664 } else if (node->action == BTRFS_DROP_DELAYED_REF) { 1665 ret = __btrfs_free_extent(trans, href, node, extent_op); 1666 } else { 1667 BUG(); 1668 } 1669 return ret; 1670 } 1671 1672 static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op, 1673 struct extent_buffer *leaf, 1674 struct btrfs_extent_item *ei) 1675 { 1676 u64 flags = btrfs_extent_flags(leaf, ei); 1677 if (extent_op->update_flags) { 1678 flags |= extent_op->flags_to_set; 1679 btrfs_set_extent_flags(leaf, ei, flags); 1680 } 1681 1682 if (extent_op->update_key) { 1683 struct btrfs_tree_block_info *bi; 1684 BUG_ON(!(flags & BTRFS_EXTENT_FLAG_TREE_BLOCK)); 1685 bi = (struct btrfs_tree_block_info *)(ei + 1); 1686 btrfs_set_tree_block_key(leaf, bi, &extent_op->key); 1687 } 1688 } 1689 1690 static int run_delayed_extent_op(struct btrfs_trans_handle *trans, 1691 const struct btrfs_delayed_ref_head *head, 1692 struct btrfs_delayed_extent_op *extent_op) 1693 { 1694 struct btrfs_fs_info *fs_info = trans->fs_info; 1695 struct btrfs_root *root; 1696 struct btrfs_key key; 1697 BTRFS_PATH_AUTO_FREE(path); 1698 struct btrfs_extent_item *ei; 1699 struct extent_buffer *leaf; 1700 u32 item_size; 1701 int ret; 1702 int metadata = 1; 1703 1704 if (TRANS_ABORTED(trans)) 1705 return 0; 1706 1707 if (!btrfs_fs_incompat(fs_info, SKINNY_METADATA)) 1708 metadata = 0; 1709 1710 path = btrfs_alloc_path(); 1711 if (!path) 1712 return -ENOMEM; 1713 1714 key.objectid = head->bytenr; 1715 1716 if (metadata) { 1717 key.type = BTRFS_METADATA_ITEM_KEY; 1718 key.offset = head->level; 1719 } else { 1720 key.type = BTRFS_EXTENT_ITEM_KEY; 1721 key.offset = head->num_bytes; 1722 } 1723 1724 root = btrfs_extent_root(fs_info, key.objectid); 1725 if (unlikely(!root)) { 1726 btrfs_err(fs_info, 1727 "missing extent root for extent at bytenr %llu", 1728 key.objectid); 1729 return -EUCLEAN; 1730 } 1731 again: 1732 ret = btrfs_search_slot(trans, root, &key, path, 0, 1); 1733 if (ret < 0) { 1734 return ret; 1735 } else if (ret > 0) { 1736 if (metadata) { 1737 if (path->slots[0] > 0) { 1738 path->slots[0]--; 1739 btrfs_item_key_to_cpu(path->nodes[0], &key, 1740 path->slots[0]); 1741 if (key.objectid == head->bytenr && 1742 key.type == BTRFS_EXTENT_ITEM_KEY && 1743 key.offset == head->num_bytes) 1744 ret = 0; 1745 } 1746 if (ret > 0) { 1747 btrfs_release_path(path); 1748 metadata = 0; 1749 1750 key.objectid = head->bytenr; 1751 key.type = BTRFS_EXTENT_ITEM_KEY; 1752 key.offset = head->num_bytes; 1753 goto again; 1754 } 1755 } else { 1756 ret = -EUCLEAN; 1757 btrfs_err(fs_info, 1758 "missing extent item for extent %llu num_bytes %llu level %d", 1759 head->bytenr, head->num_bytes, head->level); 1760 return ret; 1761 } 1762 } 1763 1764 leaf = path->nodes[0]; 1765 item_size = btrfs_item_size(leaf, path->slots[0]); 1766 1767 if (unlikely(item_size < sizeof(*ei))) { 1768 ret = -EUCLEAN; 1769 btrfs_err(fs_info, 1770 "unexpected extent item size, has %u expect >= %zu", 1771 item_size, sizeof(*ei)); 1772 btrfs_abort_transaction(trans, ret); 1773 return ret; 1774 } 1775 1776 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item); 1777 __run_delayed_extent_op(extent_op, leaf, ei); 1778 1779 return ret; 1780 } 1781 1782 static int run_delayed_tree_ref(struct btrfs_trans_handle *trans, 1783 struct btrfs_delayed_ref_head *href, 1784 const struct btrfs_delayed_ref_node *node, 1785 struct btrfs_delayed_extent_op *extent_op, 1786 bool insert_reserved) 1787 { 1788 int ret = 0; 1789 struct btrfs_fs_info *fs_info = trans->fs_info; 1790 u64 parent = 0; 1791 u64 ref_root = 0; 1792 1793 trace_run_delayed_tree_ref(trans->fs_info, node); 1794 1795 if (node->type == BTRFS_SHARED_BLOCK_REF_KEY) 1796 parent = node->parent; 1797 ref_root = node->ref_root; 1798 1799 if (unlikely(node->ref_mod != 1)) { 1800 btrfs_err(trans->fs_info, 1801 "btree block %llu has %d references rather than 1: action %d ref_root %llu parent %llu", 1802 node->bytenr, node->ref_mod, node->action, ref_root, 1803 parent); 1804 return -EUCLEAN; 1805 } 1806 if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) { 1807 struct btrfs_squota_delta delta = { 1808 .root = href->owning_root, 1809 .num_bytes = fs_info->nodesize, 1810 .is_data = false, 1811 .is_inc = true, 1812 .generation = trans->transid, 1813 }; 1814 1815 ret = alloc_reserved_tree_block(trans, node, extent_op); 1816 if (!ret) 1817 btrfs_record_squota_delta(fs_info, &delta); 1818 } else if (node->action == BTRFS_ADD_DELAYED_REF) { 1819 ret = __btrfs_inc_extent_ref(trans, node, extent_op); 1820 } else if (node->action == BTRFS_DROP_DELAYED_REF) { 1821 if (node->ref_root == BTRFS_REMAP_TREE_OBJECTID) 1822 ret = drop_remap_tree_ref(trans, node); 1823 else 1824 ret = __btrfs_free_extent(trans, href, node, extent_op); 1825 } else { 1826 BUG(); 1827 } 1828 return ret; 1829 } 1830 1831 /* helper function to actually process a single delayed ref entry */ 1832 static int run_one_delayed_ref(struct btrfs_trans_handle *trans, 1833 struct btrfs_delayed_ref_head *href, 1834 const struct btrfs_delayed_ref_node *node, 1835 struct btrfs_delayed_extent_op *extent_op, 1836 bool insert_reserved) 1837 { 1838 struct btrfs_fs_info *fs_info = trans->fs_info; 1839 int ret = 0; 1840 1841 if (TRANS_ABORTED(trans)) { 1842 if (insert_reserved) { 1843 btrfs_pin_extent(trans, node->bytenr, node->num_bytes); 1844 free_head_ref_squota_rsv(fs_info, href); 1845 } 1846 return 0; 1847 } 1848 1849 if (node->type == BTRFS_TREE_BLOCK_REF_KEY || 1850 node->type == BTRFS_SHARED_BLOCK_REF_KEY) { 1851 ret = run_delayed_tree_ref(trans, href, node, extent_op, 1852 insert_reserved); 1853 } else if (node->type == BTRFS_EXTENT_DATA_REF_KEY || 1854 node->type == BTRFS_SHARED_DATA_REF_KEY) { 1855 ret = run_delayed_data_ref(trans, href, node, extent_op, 1856 insert_reserved); 1857 } else if (unlikely(node->type != BTRFS_EXTENT_OWNER_REF_KEY)) { 1858 ret = -EUCLEAN; 1859 btrfs_err(fs_info, "unexpected delayed ref node type: %u", node->type); 1860 } 1861 1862 if (unlikely(ret)) { 1863 if (insert_reserved) 1864 btrfs_pin_extent(trans, node->bytenr, node->num_bytes); 1865 btrfs_err(fs_info, 1866 "failed to run delayed ref for logical %llu num_bytes %llu type %u action %u ref_mod %d: %d", 1867 node->bytenr, node->num_bytes, node->type, 1868 node->action, node->ref_mod, ret); 1869 } 1870 1871 return ret; 1872 } 1873 1874 static struct btrfs_delayed_extent_op *cleanup_extent_op( 1875 struct btrfs_delayed_ref_head *head) 1876 { 1877 struct btrfs_delayed_extent_op *extent_op = head->extent_op; 1878 1879 if (!extent_op) 1880 return NULL; 1881 1882 if (head->must_insert_reserved) { 1883 head->extent_op = NULL; 1884 btrfs_free_delayed_extent_op(extent_op); 1885 return NULL; 1886 } 1887 return extent_op; 1888 } 1889 1890 static int run_and_cleanup_extent_op(struct btrfs_trans_handle *trans, 1891 struct btrfs_delayed_ref_head *head) 1892 { 1893 struct btrfs_delayed_extent_op *extent_op; 1894 int ret; 1895 1896 extent_op = cleanup_extent_op(head); 1897 if (!extent_op) 1898 return 0; 1899 head->extent_op = NULL; 1900 spin_unlock(&head->lock); 1901 ret = run_delayed_extent_op(trans, head, extent_op); 1902 btrfs_free_delayed_extent_op(extent_op); 1903 return ret ? ret : 1; 1904 } 1905 1906 u64 btrfs_cleanup_ref_head_accounting(struct btrfs_fs_info *fs_info, 1907 struct btrfs_delayed_ref_root *delayed_refs, 1908 struct btrfs_delayed_ref_head *head) 1909 { 1910 u64 ret = 0; 1911 1912 /* 1913 * We had csum deletions accounted for in our delayed refs rsv, we need 1914 * to drop the csum leaves for this update from our delayed_refs_rsv. 1915 */ 1916 if (head->total_ref_mod < 0 && head->is_data) { 1917 int nr_csums; 1918 1919 spin_lock(&delayed_refs->lock); 1920 delayed_refs->pending_csums -= head->num_bytes; 1921 spin_unlock(&delayed_refs->lock); 1922 nr_csums = btrfs_csum_bytes_to_leaves(fs_info, head->num_bytes); 1923 1924 btrfs_delayed_refs_rsv_release(fs_info, 0, nr_csums); 1925 1926 ret = btrfs_calc_delayed_ref_csum_bytes(fs_info, nr_csums); 1927 } 1928 /* must_insert_reserved can be set only if we didn't run the head ref. */ 1929 if (head->must_insert_reserved) 1930 free_head_ref_squota_rsv(fs_info, head); 1931 1932 return ret; 1933 } 1934 1935 static int cleanup_ref_head(struct btrfs_trans_handle *trans, 1936 struct btrfs_delayed_ref_head *head, 1937 u64 *bytes_released) 1938 { 1939 1940 struct btrfs_fs_info *fs_info = trans->fs_info; 1941 struct btrfs_delayed_ref_root *delayed_refs; 1942 int ret; 1943 1944 delayed_refs = &trans->transaction->delayed_refs; 1945 1946 ret = run_and_cleanup_extent_op(trans, head); 1947 if (ret < 0) { 1948 btrfs_unselect_ref_head(delayed_refs, head); 1949 btrfs_debug(fs_info, "run_delayed_extent_op returned %d", ret); 1950 return ret; 1951 } else if (ret) { 1952 return ret; 1953 } 1954 1955 /* 1956 * Need to drop our head ref lock and re-acquire the delayed ref lock 1957 * and then re-check to make sure nobody got added. 1958 */ 1959 spin_unlock(&head->lock); 1960 spin_lock(&delayed_refs->lock); 1961 spin_lock(&head->lock); 1962 if (!RB_EMPTY_ROOT(&head->ref_tree.rb_root) || head->extent_op) { 1963 spin_unlock(&head->lock); 1964 spin_unlock(&delayed_refs->lock); 1965 return 1; 1966 } 1967 btrfs_delete_ref_head(fs_info, delayed_refs, head); 1968 spin_unlock(&head->lock); 1969 spin_unlock(&delayed_refs->lock); 1970 1971 if (head->must_insert_reserved) { 1972 btrfs_pin_extent(trans, head->bytenr, head->num_bytes); 1973 if (head->is_data) { 1974 struct btrfs_root *csum_root; 1975 1976 csum_root = btrfs_csum_root(fs_info, head->bytenr); 1977 if (unlikely(!csum_root)) { 1978 btrfs_err(fs_info, 1979 "missing csum root for extent at bytenr %llu", 1980 head->bytenr); 1981 ret = -EUCLEAN; 1982 } else { 1983 ret = btrfs_del_csums(trans, csum_root, head->bytenr, 1984 head->num_bytes); 1985 } 1986 } 1987 } 1988 1989 *bytes_released += btrfs_cleanup_ref_head_accounting(fs_info, delayed_refs, head); 1990 1991 trace_run_delayed_ref_head(fs_info, head, 0); 1992 btrfs_delayed_ref_unlock(head); 1993 btrfs_put_delayed_ref_head(head); 1994 return ret; 1995 } 1996 1997 static int btrfs_run_delayed_refs_for_head(struct btrfs_trans_handle *trans, 1998 struct btrfs_delayed_ref_head *locked_ref, 1999 u64 *bytes_released) 2000 { 2001 struct btrfs_fs_info *fs_info = trans->fs_info; 2002 struct btrfs_delayed_ref_root *delayed_refs; 2003 struct btrfs_delayed_extent_op *extent_op; 2004 struct btrfs_delayed_ref_node *ref; 2005 bool must_insert_reserved; 2006 int ret; 2007 2008 delayed_refs = &trans->transaction->delayed_refs; 2009 2010 lockdep_assert_held(&locked_ref->mutex); 2011 lockdep_assert_held(&locked_ref->lock); 2012 2013 while ((ref = btrfs_select_delayed_ref(locked_ref))) { 2014 if (ref->seq && 2015 btrfs_check_delayed_seq(fs_info, ref->seq)) { 2016 spin_unlock(&locked_ref->lock); 2017 btrfs_unselect_ref_head(delayed_refs, locked_ref); 2018 return -EAGAIN; 2019 } 2020 2021 rb_erase_cached(&ref->ref_node, &locked_ref->ref_tree); 2022 RB_CLEAR_NODE(&ref->ref_node); 2023 if (!list_empty(&ref->add_list)) 2024 list_del(&ref->add_list); 2025 /* 2026 * When we play the delayed ref, also correct the ref_mod on 2027 * head 2028 */ 2029 switch (ref->action) { 2030 case BTRFS_ADD_DELAYED_REF: 2031 case BTRFS_ADD_DELAYED_EXTENT: 2032 locked_ref->ref_mod -= ref->ref_mod; 2033 break; 2034 case BTRFS_DROP_DELAYED_REF: 2035 locked_ref->ref_mod += ref->ref_mod; 2036 break; 2037 default: 2038 WARN_ON(1); 2039 } 2040 2041 /* 2042 * Record the must_insert_reserved flag before we drop the 2043 * spin lock. 2044 */ 2045 must_insert_reserved = locked_ref->must_insert_reserved; 2046 /* 2047 * Unsetting this on the head ref relinquishes ownership of 2048 * the rsv_bytes, so it is critical that every possible code 2049 * path from here forward frees all reserves including qgroup 2050 * reserve. 2051 */ 2052 locked_ref->must_insert_reserved = false; 2053 2054 extent_op = locked_ref->extent_op; 2055 locked_ref->extent_op = NULL; 2056 spin_unlock(&locked_ref->lock); 2057 2058 ret = run_one_delayed_ref(trans, locked_ref, ref, extent_op, 2059 must_insert_reserved); 2060 btrfs_delayed_refs_rsv_release(fs_info, 1, 0); 2061 *bytes_released += btrfs_calc_delayed_ref_bytes(fs_info, 1); 2062 2063 btrfs_free_delayed_extent_op(extent_op); 2064 if (ret) { 2065 btrfs_unselect_ref_head(delayed_refs, locked_ref); 2066 btrfs_put_delayed_ref(ref); 2067 return ret; 2068 } 2069 2070 btrfs_put_delayed_ref(ref); 2071 cond_resched(); 2072 2073 spin_lock(&locked_ref->lock); 2074 btrfs_merge_delayed_refs(fs_info, delayed_refs, locked_ref); 2075 } 2076 2077 return 0; 2078 } 2079 2080 /* 2081 * Returns 0 on success or if called with an already aborted transaction. 2082 * Returns -ENOMEM or -EIO on failure and will abort the transaction. 2083 */ 2084 static noinline int __btrfs_run_delayed_refs(struct btrfs_trans_handle *trans, 2085 u64 min_bytes) 2086 { 2087 struct btrfs_fs_info *fs_info = trans->fs_info; 2088 struct btrfs_delayed_ref_root *delayed_refs; 2089 struct btrfs_delayed_ref_head *locked_ref = NULL; 2090 int ret; 2091 unsigned long count = 0; 2092 unsigned long max_count = 0; 2093 u64 bytes_processed = 0; 2094 2095 delayed_refs = &trans->transaction->delayed_refs; 2096 if (min_bytes == 0) { 2097 /* 2098 * We may be subject to a harmless race if some task is 2099 * concurrently adding or removing a delayed ref, so silence 2100 * KCSAN and similar tools. 2101 */ 2102 max_count = data_race(delayed_refs->num_heads_ready); 2103 min_bytes = U64_MAX; 2104 } 2105 2106 do { 2107 if (!locked_ref) { 2108 locked_ref = btrfs_select_ref_head(fs_info, delayed_refs); 2109 if (IS_ERR_OR_NULL(locked_ref)) { 2110 if (PTR_ERR(locked_ref) == -EAGAIN) { 2111 continue; 2112 } else { 2113 break; 2114 } 2115 } 2116 count++; 2117 } 2118 /* 2119 * We need to try and merge add/drops of the same ref since we 2120 * can run into issues with relocate dropping the implicit ref 2121 * and then it being added back again before the drop can 2122 * finish. If we merged anything we need to re-loop so we can 2123 * get a good ref. 2124 * Or we can get node references of the same type that weren't 2125 * merged when created due to bumps in the tree mod seq, and 2126 * we need to merge them to prevent adding an inline extent 2127 * backref before dropping it (triggering a BUG_ON at 2128 * insert_inline_extent_backref()). 2129 */ 2130 spin_lock(&locked_ref->lock); 2131 btrfs_merge_delayed_refs(fs_info, delayed_refs, locked_ref); 2132 2133 ret = btrfs_run_delayed_refs_for_head(trans, locked_ref, &bytes_processed); 2134 if (ret < 0 && ret != -EAGAIN) { 2135 /* 2136 * Error, btrfs_run_delayed_refs_for_head already 2137 * unlocked everything so just bail out 2138 */ 2139 return ret; 2140 } else if (!ret) { 2141 /* 2142 * Success, perform the usual cleanup of a processed 2143 * head 2144 */ 2145 ret = cleanup_ref_head(trans, locked_ref, &bytes_processed); 2146 if (ret > 0 ) { 2147 /* We dropped our lock, we need to loop. */ 2148 ret = 0; 2149 continue; 2150 } else if (ret) { 2151 return ret; 2152 } 2153 } 2154 2155 /* 2156 * Either success case or btrfs_run_delayed_refs_for_head 2157 * returned -EAGAIN, meaning we need to select another head 2158 */ 2159 2160 locked_ref = NULL; 2161 cond_resched(); 2162 } while ((min_bytes != U64_MAX && bytes_processed < min_bytes) || 2163 (max_count > 0 && count < max_count) || 2164 locked_ref); 2165 2166 return 0; 2167 } 2168 2169 #ifdef SCRAMBLE_DELAYED_REFS 2170 /* 2171 * Normally delayed refs get processed in ascending bytenr order. This 2172 * correlates in most cases to the order added. To expose dependencies on this 2173 * order, we start to process the tree in the middle instead of the beginning 2174 */ 2175 static u64 find_middle(struct rb_root *root) 2176 { 2177 struct rb_node *n = root->rb_node; 2178 struct btrfs_delayed_ref_node *entry; 2179 int alt = 1; 2180 u64 middle; 2181 u64 first = 0, last = 0; 2182 2183 n = rb_first(root); 2184 if (n) { 2185 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node); 2186 first = entry->bytenr; 2187 } 2188 n = rb_last(root); 2189 if (n) { 2190 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node); 2191 last = entry->bytenr; 2192 } 2193 n = root->rb_node; 2194 2195 while (n) { 2196 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node); 2197 WARN_ON(!entry->in_tree); 2198 2199 middle = entry->bytenr; 2200 2201 if (alt) 2202 n = n->rb_left; 2203 else 2204 n = n->rb_right; 2205 2206 alt = 1 - alt; 2207 } 2208 return middle; 2209 } 2210 #endif 2211 2212 /* 2213 * Start processing the delayed reference count updates and extent insertions 2214 * we have queued up so far. 2215 * 2216 * @trans: Transaction handle. 2217 * @min_bytes: How many bytes of delayed references to process. After this 2218 * many bytes we stop processing delayed references if there are 2219 * any more. If 0 it means to run all existing delayed references, 2220 * but not new ones added after running all existing ones. 2221 * Use (u64)-1 (U64_MAX) to run all existing delayed references 2222 * plus any new ones that are added. 2223 * 2224 * Returns 0 on success or if called with an aborted transaction 2225 * Returns <0 on error and aborts the transaction 2226 */ 2227 int btrfs_run_delayed_refs(struct btrfs_trans_handle *trans, u64 min_bytes) 2228 { 2229 struct btrfs_fs_info *fs_info = trans->fs_info; 2230 struct btrfs_delayed_ref_root *delayed_refs; 2231 int ret; 2232 2233 /* We'll clean this up in btrfs_cleanup_transaction */ 2234 if (TRANS_ABORTED(trans)) 2235 return 0; 2236 2237 if (test_bit(BTRFS_FS_CREATING_FREE_SPACE_TREE, &fs_info->flags)) 2238 return 0; 2239 2240 delayed_refs = &trans->transaction->delayed_refs; 2241 again: 2242 #ifdef SCRAMBLE_DELAYED_REFS 2243 delayed_refs->run_delayed_start = find_middle(&delayed_refs->root); 2244 #endif 2245 ret = __btrfs_run_delayed_refs(trans, min_bytes); 2246 if (unlikely(ret < 0)) { 2247 btrfs_abort_transaction(trans, ret); 2248 return ret; 2249 } 2250 2251 if (min_bytes == U64_MAX) { 2252 btrfs_create_pending_block_groups(trans); 2253 2254 spin_lock(&delayed_refs->lock); 2255 if (xa_empty(&delayed_refs->head_refs)) { 2256 spin_unlock(&delayed_refs->lock); 2257 return 0; 2258 } 2259 spin_unlock(&delayed_refs->lock); 2260 2261 cond_resched(); 2262 goto again; 2263 } 2264 2265 return 0; 2266 } 2267 2268 int btrfs_set_disk_extent_flags(struct btrfs_trans_handle *trans, 2269 struct extent_buffer *eb, u64 flags) 2270 { 2271 struct btrfs_delayed_extent_op *extent_op; 2272 int ret; 2273 2274 extent_op = btrfs_alloc_delayed_extent_op(); 2275 if (!extent_op) 2276 return -ENOMEM; 2277 2278 extent_op->flags_to_set = flags; 2279 extent_op->update_flags = true; 2280 extent_op->update_key = false; 2281 2282 ret = btrfs_add_delayed_extent_op(trans, eb->start, eb->len, 2283 btrfs_header_level(eb), extent_op); 2284 if (ret) 2285 btrfs_free_delayed_extent_op(extent_op); 2286 return ret; 2287 } 2288 2289 static noinline int check_delayed_ref(struct btrfs_inode *inode, 2290 struct btrfs_path *path, 2291 u64 offset, u64 bytenr) 2292 { 2293 struct btrfs_root *root = inode->root; 2294 struct btrfs_delayed_ref_head *head; 2295 struct btrfs_delayed_ref_node *ref; 2296 struct btrfs_delayed_ref_root *delayed_refs; 2297 struct btrfs_transaction *cur_trans; 2298 struct rb_node *node; 2299 int ret = 0; 2300 2301 spin_lock(&root->fs_info->trans_lock); 2302 cur_trans = root->fs_info->running_transaction; 2303 if (cur_trans) 2304 refcount_inc(&cur_trans->use_count); 2305 spin_unlock(&root->fs_info->trans_lock); 2306 if (!cur_trans) 2307 return 0; 2308 2309 delayed_refs = &cur_trans->delayed_refs; 2310 spin_lock(&delayed_refs->lock); 2311 head = btrfs_find_delayed_ref_head(root->fs_info, delayed_refs, bytenr); 2312 if (!head) { 2313 spin_unlock(&delayed_refs->lock); 2314 btrfs_put_transaction(cur_trans); 2315 return 0; 2316 } 2317 2318 if (!mutex_trylock(&head->mutex)) { 2319 if (path->nowait) { 2320 spin_unlock(&delayed_refs->lock); 2321 btrfs_put_transaction(cur_trans); 2322 return -EAGAIN; 2323 } 2324 2325 refcount_inc(&head->refs); 2326 spin_unlock(&delayed_refs->lock); 2327 2328 btrfs_release_path(path); 2329 2330 /* 2331 * Mutex was contended, block until it's released and let 2332 * caller try again 2333 */ 2334 mutex_lock(&head->mutex); 2335 mutex_unlock(&head->mutex); 2336 btrfs_put_delayed_ref_head(head); 2337 btrfs_put_transaction(cur_trans); 2338 return -EAGAIN; 2339 } 2340 spin_unlock(&delayed_refs->lock); 2341 2342 spin_lock(&head->lock); 2343 /* 2344 * XXX: We should replace this with a proper search function in the 2345 * future. 2346 */ 2347 for (node = rb_first_cached(&head->ref_tree); node; 2348 node = rb_next(node)) { 2349 u64 ref_owner; 2350 u64 ref_offset; 2351 2352 ref = rb_entry(node, struct btrfs_delayed_ref_node, ref_node); 2353 /* If it's a shared ref we know a cross reference exists */ 2354 if (ref->type != BTRFS_EXTENT_DATA_REF_KEY) { 2355 ret = 1; 2356 break; 2357 } 2358 2359 ref_owner = btrfs_delayed_ref_owner(ref); 2360 ref_offset = btrfs_delayed_ref_offset(ref); 2361 2362 /* 2363 * If our ref doesn't match the one we're currently looking at 2364 * then we have a cross reference. 2365 */ 2366 if (ref->ref_root != btrfs_root_id(root) || 2367 ref_owner != btrfs_ino(inode) || ref_offset != offset) { 2368 ret = 1; 2369 break; 2370 } 2371 } 2372 spin_unlock(&head->lock); 2373 mutex_unlock(&head->mutex); 2374 btrfs_put_transaction(cur_trans); 2375 return ret; 2376 } 2377 2378 /* 2379 * Check if there are references for a data extent other than the one belonging 2380 * to the given inode and offset. 2381 * 2382 * @inode: The only inode we expect to find associated with the data extent. 2383 * @path: A path to use for searching the extent tree. 2384 * @offset: The only offset we expect to find associated with the data extent. 2385 * @bytenr: The logical address of the data extent. 2386 * 2387 * When the extent does not have any other references other than the one we 2388 * expect to find, we always return a value of 0 with the path having a locked 2389 * leaf that contains the extent's extent item - this is necessary to ensure 2390 * we don't race with a task running delayed references, and our caller must 2391 * have such a path when calling check_delayed_ref() - it must lock a delayed 2392 * ref head while holding the leaf locked. In case the extent item is not found 2393 * in the extent tree, we return -ENOENT with the path having the leaf (locked) 2394 * where the extent item should be, in order to prevent races with another task 2395 * running delayed references, so that we don't miss any reference when calling 2396 * check_delayed_ref(). 2397 * 2398 * Note: this may return false positives, and this is because we want to be 2399 * quick here as we're called in write paths (when flushing delalloc and 2400 * in the direct IO write path). For example we can have an extent with 2401 * a single reference but that reference is not inlined, or we may have 2402 * many references in the extent tree but we also have delayed references 2403 * that cancel all the reference except the one for our inode and offset, 2404 * but it would be expensive to do such checks and complex due to all 2405 * locking to avoid races between the checks and flushing delayed refs, 2406 * plus non-inline references may be located on leaves other than the one 2407 * that contains the extent item in the extent tree. The important thing 2408 * here is to not return false negatives and that the false positives are 2409 * not very common. 2410 * 2411 * Returns: 0 if there are no cross references and with the path having a locked 2412 * leaf from the extent tree that contains the extent's extent item. 2413 * 2414 * 1 if there are cross references (false positives can happen). 2415 * 2416 * < 0 in case of an error. In case of -ENOENT the leaf in the extent 2417 * tree where the extent item should be located at is read locked and 2418 * accessible in the given path. 2419 */ 2420 static noinline int check_committed_ref(struct btrfs_inode *inode, 2421 struct btrfs_path *path, 2422 u64 offset, u64 bytenr) 2423 { 2424 struct btrfs_root *root = inode->root; 2425 struct btrfs_fs_info *fs_info = root->fs_info; 2426 struct btrfs_root *extent_root = btrfs_extent_root(fs_info, bytenr); 2427 struct extent_buffer *leaf; 2428 struct btrfs_extent_data_ref *ref; 2429 struct btrfs_extent_inline_ref *iref; 2430 struct btrfs_extent_item *ei; 2431 struct btrfs_key key; 2432 u32 item_size; 2433 u32 expected_size; 2434 int type; 2435 int ret; 2436 2437 if (unlikely(!extent_root)) { 2438 btrfs_err(fs_info, 2439 "missing extent root for extent at bytenr %llu", bytenr); 2440 return -EUCLEAN; 2441 } 2442 2443 key.objectid = bytenr; 2444 key.type = BTRFS_EXTENT_ITEM_KEY; 2445 key.offset = (u64)-1; 2446 2447 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0); 2448 if (ret < 0) 2449 return ret; 2450 if (unlikely(ret == 0)) { 2451 /* 2452 * Key with offset -1 found, there would have to exist an extent 2453 * item with such offset, but this is out of the valid range. 2454 */ 2455 return -EUCLEAN; 2456 } 2457 2458 if (path->slots[0] == 0) 2459 return -ENOENT; 2460 2461 path->slots[0]--; 2462 leaf = path->nodes[0]; 2463 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]); 2464 2465 if (key.objectid != bytenr || key.type != BTRFS_EXTENT_ITEM_KEY) 2466 return -ENOENT; 2467 2468 item_size = btrfs_item_size(leaf, path->slots[0]); 2469 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item); 2470 expected_size = sizeof(*ei) + btrfs_extent_inline_ref_size(BTRFS_EXTENT_DATA_REF_KEY); 2471 2472 /* No inline refs; we need to bail before checking for owner ref. */ 2473 if (item_size == sizeof(*ei)) 2474 return 1; 2475 2476 /* Check for an owner ref; skip over it to the real inline refs. */ 2477 iref = (struct btrfs_extent_inline_ref *)(ei + 1); 2478 type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_DATA); 2479 if (btrfs_fs_incompat(fs_info, SIMPLE_QUOTA) && type == BTRFS_EXTENT_OWNER_REF_KEY) { 2480 expected_size += btrfs_extent_inline_ref_size(BTRFS_EXTENT_OWNER_REF_KEY); 2481 iref = (struct btrfs_extent_inline_ref *)(iref + 1); 2482 type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_DATA); 2483 } 2484 2485 /* If extent item has more than 1 inline ref then it's shared */ 2486 if (item_size != expected_size) 2487 return 1; 2488 2489 /* If this extent has SHARED_DATA_REF then it's shared */ 2490 if (type != BTRFS_EXTENT_DATA_REF_KEY) 2491 return 1; 2492 2493 ref = (struct btrfs_extent_data_ref *)(&iref->offset); 2494 if (btrfs_extent_refs(leaf, ei) != 2495 btrfs_extent_data_ref_count(leaf, ref) || 2496 btrfs_extent_data_ref_root(leaf, ref) != btrfs_root_id(root) || 2497 btrfs_extent_data_ref_objectid(leaf, ref) != btrfs_ino(inode) || 2498 btrfs_extent_data_ref_offset(leaf, ref) != offset) 2499 return 1; 2500 2501 return 0; 2502 } 2503 2504 int btrfs_cross_ref_exist(struct btrfs_inode *inode, u64 offset, 2505 u64 bytenr, struct btrfs_path *path) 2506 { 2507 int ret; 2508 2509 do { 2510 ret = check_committed_ref(inode, path, offset, bytenr); 2511 if (ret && ret != -ENOENT) 2512 goto out; 2513 2514 /* 2515 * The path must have a locked leaf from the extent tree where 2516 * the extent item for our extent is located, in case it exists, 2517 * or where it should be located in case it doesn't exist yet 2518 * because it's new and its delayed ref was not yet flushed. 2519 * We need to lock the delayed ref head at check_delayed_ref(), 2520 * if one exists, while holding the leaf locked in order to not 2521 * race with delayed ref flushing, missing references and 2522 * incorrectly reporting that the extent is not shared. 2523 */ 2524 if (IS_ENABLED(CONFIG_BTRFS_ASSERT)) { 2525 struct extent_buffer *leaf = path->nodes[0]; 2526 2527 ASSERT(leaf != NULL); 2528 btrfs_assert_tree_read_locked(leaf); 2529 2530 if (ret != -ENOENT) { 2531 struct btrfs_key key; 2532 2533 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]); 2534 ASSERT(key.objectid == bytenr); 2535 ASSERT(key.type == BTRFS_EXTENT_ITEM_KEY); 2536 } 2537 } 2538 2539 ret = check_delayed_ref(inode, path, offset, bytenr); 2540 } while (ret == -EAGAIN && !path->nowait); 2541 2542 out: 2543 btrfs_release_path(path); 2544 if (btrfs_is_data_reloc_root(inode->root)) 2545 WARN_ON(ret > 0); 2546 return ret; 2547 } 2548 2549 static int __btrfs_mod_ref(struct btrfs_trans_handle *trans, 2550 struct btrfs_root *root, 2551 struct extent_buffer *buf, 2552 bool full_backref, bool inc) 2553 { 2554 struct btrfs_fs_info *fs_info = root->fs_info; 2555 u64 parent; 2556 u64 ref_root; 2557 u32 nritems; 2558 struct btrfs_key key; 2559 struct btrfs_file_extent_item *fi; 2560 bool for_reloc = btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC); 2561 int i; 2562 int action; 2563 int level; 2564 int ret; 2565 2566 if (btrfs_is_testing(fs_info)) 2567 return 0; 2568 2569 ref_root = btrfs_header_owner(buf); 2570 nritems = btrfs_header_nritems(buf); 2571 level = btrfs_header_level(buf); 2572 2573 if (!test_bit(BTRFS_ROOT_SHAREABLE, &root->state) && level == 0) 2574 return 0; 2575 2576 if (full_backref) 2577 parent = buf->start; 2578 else 2579 parent = 0; 2580 if (inc) 2581 action = BTRFS_ADD_DELAYED_REF; 2582 else 2583 action = BTRFS_DROP_DELAYED_REF; 2584 2585 for (i = 0; i < nritems; i++) { 2586 struct btrfs_ref ref = { 2587 .action = action, 2588 .parent = parent, 2589 .ref_root = ref_root, 2590 }; 2591 2592 if (level == 0) { 2593 btrfs_item_key_to_cpu(buf, &key, i); 2594 if (key.type != BTRFS_EXTENT_DATA_KEY) 2595 continue; 2596 fi = btrfs_item_ptr(buf, i, 2597 struct btrfs_file_extent_item); 2598 if (btrfs_file_extent_type(buf, fi) == 2599 BTRFS_FILE_EXTENT_INLINE) 2600 continue; 2601 ref.bytenr = btrfs_file_extent_disk_bytenr(buf, fi); 2602 if (ref.bytenr == 0) 2603 continue; 2604 2605 ref.num_bytes = btrfs_file_extent_disk_num_bytes(buf, fi); 2606 ref.owning_root = ref_root; 2607 2608 key.offset -= btrfs_file_extent_offset(buf, fi); 2609 btrfs_init_data_ref(&ref, key.objectid, key.offset, 2610 btrfs_root_id(root), for_reloc); 2611 if (inc) 2612 ret = btrfs_inc_extent_ref(trans, &ref); 2613 else 2614 ret = btrfs_free_extent(trans, &ref); 2615 if (ret) 2616 return ret; 2617 } else { 2618 /* We don't know the owning_root, leave as 0. */ 2619 ref.bytenr = btrfs_node_blockptr(buf, i); 2620 ref.num_bytes = fs_info->nodesize; 2621 2622 btrfs_init_tree_ref(&ref, level - 1, 2623 btrfs_root_id(root), for_reloc); 2624 if (inc) 2625 ret = btrfs_inc_extent_ref(trans, &ref); 2626 else 2627 ret = btrfs_free_extent(trans, &ref); 2628 if (ret) 2629 return ret; 2630 } 2631 } 2632 return 0; 2633 } 2634 2635 int btrfs_inc_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root, 2636 struct extent_buffer *buf, bool full_backref) 2637 { 2638 return __btrfs_mod_ref(trans, root, buf, full_backref, true); 2639 } 2640 2641 int btrfs_dec_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root, 2642 struct extent_buffer *buf, bool full_backref) 2643 { 2644 return __btrfs_mod_ref(trans, root, buf, full_backref, false); 2645 } 2646 2647 static u64 get_alloc_profile_by_root(struct btrfs_root *root, int data) 2648 { 2649 struct btrfs_fs_info *fs_info = root->fs_info; 2650 u64 flags; 2651 2652 if (data) 2653 flags = BTRFS_BLOCK_GROUP_DATA; 2654 else if (root == fs_info->chunk_root) 2655 flags = BTRFS_BLOCK_GROUP_SYSTEM; 2656 else if (root == fs_info->remap_root) 2657 flags = BTRFS_BLOCK_GROUP_METADATA_REMAP; 2658 else 2659 flags = BTRFS_BLOCK_GROUP_METADATA; 2660 2661 return btrfs_get_alloc_profile(fs_info, flags); 2662 } 2663 2664 static u64 first_logical_byte(struct btrfs_fs_info *fs_info) 2665 { 2666 struct rb_node *leftmost; 2667 u64 bytenr = 0; 2668 2669 read_lock(&fs_info->block_group_cache_lock); 2670 /* Get the block group with the lowest logical start address. */ 2671 leftmost = rb_first_cached(&fs_info->block_group_cache_tree); 2672 if (leftmost) { 2673 struct btrfs_block_group *bg; 2674 2675 bg = rb_entry(leftmost, struct btrfs_block_group, cache_node); 2676 bytenr = bg->start; 2677 } 2678 read_unlock(&fs_info->block_group_cache_lock); 2679 2680 return bytenr; 2681 } 2682 2683 static int pin_down_extent(struct btrfs_trans_handle *trans, 2684 struct btrfs_block_group *bg, 2685 u64 bytenr, u64 num_bytes, bool reserved) 2686 { 2687 struct btrfs_space_info *space_info = bg->space_info; 2688 const u64 reserved_bytes = (reserved ? num_bytes : 0); 2689 2690 spin_lock(&space_info->lock); 2691 spin_lock(&bg->lock); 2692 bg->pinned += num_bytes; 2693 bg->reserved -= reserved_bytes; 2694 spin_unlock(&bg->lock); 2695 space_info->bytes_reserved -= reserved_bytes; 2696 btrfs_space_info_update_bytes_pinned(space_info, num_bytes); 2697 spin_unlock(&space_info->lock); 2698 2699 btrfs_set_extent_bit(&trans->transaction->pinned_extents, bytenr, 2700 bytenr + num_bytes - 1, EXTENT_DIRTY, NULL); 2701 return 0; 2702 } 2703 2704 int btrfs_pin_extent(struct btrfs_trans_handle *trans, u64 bytenr, u64 num_bytes) 2705 { 2706 struct btrfs_block_group *cache; 2707 2708 cache = btrfs_lookup_block_group(trans->fs_info, bytenr); 2709 BUG_ON(!cache); /* Logic error */ 2710 2711 pin_down_extent(trans, cache, bytenr, num_bytes, true); 2712 2713 btrfs_put_block_group(cache); 2714 return 0; 2715 } 2716 2717 int btrfs_pin_extent_for_log_replay(struct btrfs_trans_handle *trans, 2718 const struct extent_buffer *eb) 2719 { 2720 struct btrfs_block_group *cache; 2721 int ret; 2722 2723 cache = btrfs_lookup_block_group(trans->fs_info, eb->start); 2724 if (!cache) 2725 return -EINVAL; 2726 2727 /* 2728 * Fully cache the free space first so that our pin removes the free space 2729 * from the cache. 2730 */ 2731 ret = btrfs_cache_block_group(cache, true); 2732 if (ret) 2733 goto out; 2734 2735 pin_down_extent(trans, cache, eb->start, eb->len, false); 2736 2737 /* remove us from the free space cache (if we're there at all) */ 2738 ret = btrfs_remove_free_space(cache, eb->start, eb->len); 2739 out: 2740 btrfs_put_block_group(cache); 2741 return ret; 2742 } 2743 2744 static int __exclude_logged_extent(struct btrfs_fs_info *fs_info, 2745 u64 start, u64 num_bytes) 2746 { 2747 int ret; 2748 struct btrfs_block_group *block_group; 2749 2750 block_group = btrfs_lookup_block_group(fs_info, start); 2751 if (!block_group) 2752 return -EINVAL; 2753 2754 ret = btrfs_cache_block_group(block_group, true); 2755 if (ret) 2756 goto out; 2757 2758 ret = btrfs_remove_free_space(block_group, start, num_bytes); 2759 out: 2760 btrfs_put_block_group(block_group); 2761 return ret; 2762 } 2763 2764 int btrfs_exclude_logged_extents(struct extent_buffer *eb) 2765 { 2766 struct btrfs_fs_info *fs_info = eb->fs_info; 2767 struct btrfs_file_extent_item *item; 2768 struct btrfs_key key; 2769 int found_type; 2770 int i; 2771 int ret = 0; 2772 2773 if (!btrfs_fs_incompat(fs_info, MIXED_GROUPS)) 2774 return 0; 2775 2776 for (i = 0; i < btrfs_header_nritems(eb); i++) { 2777 btrfs_item_key_to_cpu(eb, &key, i); 2778 if (key.type != BTRFS_EXTENT_DATA_KEY) 2779 continue; 2780 item = btrfs_item_ptr(eb, i, struct btrfs_file_extent_item); 2781 found_type = btrfs_file_extent_type(eb, item); 2782 if (found_type == BTRFS_FILE_EXTENT_INLINE) 2783 continue; 2784 if (btrfs_file_extent_disk_bytenr(eb, item) == 0) 2785 continue; 2786 key.objectid = btrfs_file_extent_disk_bytenr(eb, item); 2787 key.offset = btrfs_file_extent_disk_num_bytes(eb, item); 2788 ret = __exclude_logged_extent(fs_info, key.objectid, key.offset); 2789 if (ret) 2790 break; 2791 } 2792 2793 return ret; 2794 } 2795 2796 static void 2797 btrfs_inc_block_group_reservations(struct btrfs_block_group *bg) 2798 { 2799 atomic_inc(&bg->reservations); 2800 } 2801 2802 /* 2803 * Returns the free cluster for the given space info and sets empty_cluster to 2804 * what it should be based on the mount options. 2805 */ 2806 static struct btrfs_free_cluster * 2807 fetch_cluster_info(struct btrfs_fs_info *fs_info, 2808 struct btrfs_space_info *space_info, u64 *empty_cluster) 2809 { 2810 struct btrfs_free_cluster *ret = NULL; 2811 2812 *empty_cluster = 0; 2813 if (btrfs_mixed_space_info(space_info)) 2814 return ret; 2815 2816 if (space_info->flags & BTRFS_BLOCK_GROUP_METADATA) { 2817 ret = &fs_info->meta_alloc_cluster; 2818 if (btrfs_test_opt(fs_info, SSD)) 2819 *empty_cluster = SZ_2M; 2820 else 2821 *empty_cluster = SZ_64K; 2822 } else if ((space_info->flags & BTRFS_BLOCK_GROUP_DATA) && 2823 btrfs_test_opt(fs_info, SSD_SPREAD)) { 2824 *empty_cluster = SZ_2M; 2825 ret = &fs_info->data_alloc_cluster; 2826 } 2827 2828 return ret; 2829 } 2830 2831 static int unpin_extent_range(struct btrfs_fs_info *fs_info, 2832 u64 start, u64 end, 2833 const bool return_free_space) 2834 { 2835 struct btrfs_block_group *cache = NULL; 2836 struct btrfs_space_info *space_info; 2837 struct btrfs_free_cluster *cluster = NULL; 2838 u64 total_unpinned = 0; 2839 u64 empty_cluster = 0; 2840 2841 while (start <= end) { 2842 u64 len; 2843 bool readonly; 2844 2845 if (!cache || start >= btrfs_block_group_end(cache)) { 2846 if (cache) 2847 btrfs_put_block_group(cache); 2848 total_unpinned = 0; 2849 cache = btrfs_lookup_block_group(fs_info, start); 2850 if (unlikely(cache == NULL)) { 2851 /* Logic error, something removed the block group. */ 2852 return -EUCLEAN; 2853 } 2854 2855 cluster = fetch_cluster_info(fs_info, 2856 cache->space_info, 2857 &empty_cluster); 2858 empty_cluster <<= 1; 2859 } 2860 2861 len = btrfs_block_group_end(cache) - start; 2862 len = min(len, end + 1 - start); 2863 2864 if (return_free_space) 2865 btrfs_add_free_space(cache, start, len); 2866 2867 start += len; 2868 total_unpinned += len; 2869 space_info = cache->space_info; 2870 2871 /* 2872 * If this space cluster has been marked as fragmented and we've 2873 * unpinned enough in this block group to potentially allow a 2874 * cluster to be created inside of it go ahead and clear the 2875 * fragmented check. 2876 */ 2877 if (cluster && cluster->fragmented && 2878 total_unpinned > empty_cluster) { 2879 spin_lock(&cluster->lock); 2880 cluster->fragmented = 0; 2881 spin_unlock(&cluster->lock); 2882 } 2883 2884 spin_lock(&space_info->lock); 2885 spin_lock(&cache->lock); 2886 readonly = cache->ro; 2887 cache->pinned -= len; 2888 spin_unlock(&cache->lock); 2889 2890 btrfs_space_info_update_bytes_pinned(space_info, -len); 2891 space_info->max_extent_size = 0; 2892 2893 if (readonly) { 2894 space_info->bytes_readonly += len; 2895 } else if (btrfs_is_zoned(fs_info)) { 2896 /* Need reset before reusing in a zoned block group */ 2897 btrfs_space_info_update_bytes_zone_unusable(space_info, len); 2898 } else if (return_free_space) { 2899 btrfs_return_free_space(space_info, len); 2900 } 2901 spin_unlock(&space_info->lock); 2902 } 2903 2904 if (cache) 2905 btrfs_put_block_group(cache); 2906 2907 return 0; 2908 } 2909 2910 /* 2911 * Complete the remapping of a block group by removing its chunk stripes and 2912 * device extents, and adding it to the unused list if there's no longer any 2913 * extents nominally within it. 2914 */ 2915 int btrfs_complete_bg_remapping(struct btrfs_block_group *bg) 2916 { 2917 struct btrfs_fs_info *fs_info = bg->fs_info; 2918 struct btrfs_chunk_map *map; 2919 int ret; 2920 2921 map = btrfs_get_chunk_map(fs_info, bg->start, 1); 2922 if (IS_ERR(map)) 2923 return PTR_ERR(map); 2924 2925 ret = btrfs_last_identity_remap_gone(map, bg); 2926 if (ret) { 2927 btrfs_free_chunk_map(map); 2928 return ret; 2929 } 2930 2931 /* 2932 * Set num_stripes to 0, so that btrfs_remove_dev_extents() won't run a 2933 * second time. 2934 */ 2935 map->num_stripes = 0; 2936 2937 btrfs_free_chunk_map(map); 2938 2939 if (bg->used == 0) { 2940 spin_lock(&fs_info->unused_bgs_lock); 2941 if (!list_empty(&bg->bg_list)) { 2942 list_del_init(&bg->bg_list); 2943 btrfs_put_block_group(bg); 2944 } 2945 spin_unlock(&fs_info->unused_bgs_lock); 2946 2947 btrfs_mark_bg_unused(bg); 2948 } 2949 2950 return 0; 2951 } 2952 2953 void btrfs_handle_fully_remapped_bgs(struct btrfs_fs_info *fs_info) 2954 { 2955 struct btrfs_block_group *bg; 2956 int ret; 2957 2958 spin_lock(&fs_info->unused_bgs_lock); 2959 while (!list_empty(&fs_info->fully_remapped_bgs)) { 2960 bg = list_first_entry(&fs_info->fully_remapped_bgs, 2961 struct btrfs_block_group, bg_list); 2962 list_del_init(&bg->bg_list); 2963 spin_unlock(&fs_info->unused_bgs_lock); 2964 2965 btrfs_discard_extent(fs_info, bg->start, bg->length, NULL, false); 2966 2967 ret = btrfs_complete_bg_remapping(bg); 2968 if (ret) { 2969 btrfs_put_block_group(bg); 2970 return; 2971 } 2972 2973 btrfs_put_block_group(bg); 2974 spin_lock(&fs_info->unused_bgs_lock); 2975 } 2976 spin_unlock(&fs_info->unused_bgs_lock); 2977 } 2978 2979 int btrfs_finish_extent_commit(struct btrfs_trans_handle *trans) 2980 { 2981 struct btrfs_fs_info *fs_info = trans->fs_info; 2982 struct btrfs_block_group *block_group, *tmp; 2983 struct list_head *deleted_bgs; 2984 struct extent_io_tree *unpin = &trans->transaction->pinned_extents; 2985 struct extent_state *cached_state = NULL; 2986 u64 start; 2987 u64 end; 2988 int unpin_error = 0; 2989 int ret; 2990 2991 mutex_lock(&fs_info->unused_bg_unpin_mutex); 2992 btrfs_find_first_extent_bit(unpin, 0, &start, &end, EXTENT_DIRTY, &cached_state); 2993 2994 while (!TRANS_ABORTED(trans) && cached_state) { 2995 struct extent_state *next_state; 2996 2997 if (btrfs_test_opt(fs_info, DISCARD_SYNC)) { 2998 ret = btrfs_discard_extent(fs_info, start, 2999 end + 1 - start, NULL, true); 3000 if (ret) { 3001 btrfs_warn(fs_info, 3002 "discard failed for extent [%llu, %llu]: errno=%d %s", 3003 start, end, ret, btrfs_decode_error(ret)); 3004 } 3005 } 3006 3007 next_state = btrfs_next_extent_state(unpin, cached_state); 3008 btrfs_clear_extent_dirty(unpin, start, end, &cached_state); 3009 ret = unpin_extent_range(fs_info, start, end, true); 3010 /* 3011 * If we get an error unpinning an extent range, store the first 3012 * error to return later after trying to unpin all ranges and do 3013 * the sync discards. Our caller will abort the transaction 3014 * (which already wrote new superblocks) and on the next mount 3015 * the space will be available as it was pinned by in-memory 3016 * only structures in this phase. 3017 */ 3018 if (ret) { 3019 btrfs_err_rl(fs_info, 3020 "failed to unpin extent range [%llu, %llu] when committing transaction %llu: %s (%d)", 3021 start, end, trans->transid, 3022 btrfs_decode_error(ret), ret); 3023 if (!unpin_error) 3024 unpin_error = ret; 3025 } 3026 3027 btrfs_free_extent_state(cached_state); 3028 3029 if (need_resched()) { 3030 btrfs_free_extent_state(next_state); 3031 mutex_unlock(&fs_info->unused_bg_unpin_mutex); 3032 cond_resched(); 3033 cached_state = NULL; 3034 mutex_lock(&fs_info->unused_bg_unpin_mutex); 3035 btrfs_find_first_extent_bit(unpin, 0, &start, &end, 3036 EXTENT_DIRTY, &cached_state); 3037 } else { 3038 cached_state = next_state; 3039 if (cached_state) { 3040 start = cached_state->start; 3041 end = cached_state->end; 3042 } 3043 } 3044 } 3045 mutex_unlock(&fs_info->unused_bg_unpin_mutex); 3046 btrfs_free_extent_state(cached_state); 3047 3048 if (btrfs_test_opt(fs_info, DISCARD_ASYNC)) { 3049 btrfs_discard_calc_delay(&fs_info->discard_ctl); 3050 btrfs_discard_schedule_work(&fs_info->discard_ctl, true); 3051 } 3052 3053 /* 3054 * Transaction is finished. We don't need the lock anymore. We 3055 * do need to clean up the block groups in case of a transaction 3056 * abort. 3057 */ 3058 deleted_bgs = &trans->transaction->deleted_bgs; 3059 list_for_each_entry_safe(block_group, tmp, deleted_bgs, bg_list) { 3060 ret = -EROFS; 3061 if (!TRANS_ABORTED(trans)) 3062 ret = btrfs_discard_extent(fs_info, block_group->start, 3063 block_group->length, NULL, true); 3064 3065 /* 3066 * Not strictly necessary to lock, as the block_group should be 3067 * read-only from btrfs_delete_unused_bgs(). 3068 */ 3069 ASSERT(block_group->ro); 3070 spin_lock(&fs_info->unused_bgs_lock); 3071 list_del_init(&block_group->bg_list); 3072 spin_unlock(&fs_info->unused_bgs_lock); 3073 3074 btrfs_unfreeze_block_group(block_group); 3075 btrfs_put_block_group(block_group); 3076 3077 if (ret) { 3078 const char *errstr = btrfs_decode_error(ret); 3079 btrfs_warn(fs_info, 3080 "discard failed while removing blockgroup: errno=%d %s", 3081 ret, errstr); 3082 } 3083 } 3084 3085 return unpin_error; 3086 } 3087 3088 /* 3089 * Parse an extent item's inline extents looking for a simple quotas owner ref. 3090 * 3091 * @fs_info: the btrfs_fs_info for this mount 3092 * @leaf: a leaf in the extent tree containing the extent item 3093 * @slot: the slot in the leaf where the extent item is found 3094 * 3095 * Returns the objectid of the root that originally allocated the extent item 3096 * if the inline owner ref is expected and present, otherwise 0. 3097 * 3098 * If an extent item has an owner ref item, it will be the first inline ref 3099 * item. Therefore the logic is to check whether there are any inline ref 3100 * items, then check the type of the first one. 3101 */ 3102 u64 btrfs_get_extent_owner_root(struct btrfs_fs_info *fs_info, 3103 struct extent_buffer *leaf, int slot) 3104 { 3105 struct btrfs_extent_item *ei; 3106 struct btrfs_extent_inline_ref *iref; 3107 struct btrfs_extent_owner_ref *oref; 3108 unsigned long ptr; 3109 unsigned long end; 3110 int type; 3111 3112 if (!btrfs_fs_incompat(fs_info, SIMPLE_QUOTA)) 3113 return 0; 3114 3115 ei = btrfs_item_ptr(leaf, slot, struct btrfs_extent_item); 3116 ptr = (unsigned long)(ei + 1); 3117 end = (unsigned long)ei + btrfs_item_size(leaf, slot); 3118 3119 /* No inline ref items of any kind, can't check type. */ 3120 if (ptr == end) 3121 return 0; 3122 3123 iref = (struct btrfs_extent_inline_ref *)ptr; 3124 type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_ANY); 3125 3126 /* We found an owner ref, get the root out of it. */ 3127 if (type == BTRFS_EXTENT_OWNER_REF_KEY) { 3128 oref = (struct btrfs_extent_owner_ref *)(&iref->offset); 3129 return btrfs_extent_owner_ref_root_id(leaf, oref); 3130 } 3131 3132 /* We have inline refs, but not an owner ref. */ 3133 return 0; 3134 } 3135 3136 static int do_free_extent_accounting(struct btrfs_trans_handle *trans, 3137 u64 bytenr, struct btrfs_squota_delta *delta, 3138 struct btrfs_path *path) 3139 { 3140 int ret; 3141 bool remapped = false; 3142 u64 num_bytes = delta->num_bytes; 3143 3144 /* Returns 1 on success and 0 on no-op. */ 3145 ret = btrfs_remove_extent_from_remap_tree(trans, path, bytenr, num_bytes); 3146 if (unlikely(ret < 0)) { 3147 btrfs_abort_transaction(trans, ret); 3148 return ret; 3149 } else if (ret == 1) { 3150 remapped = true; 3151 } 3152 3153 if (delta->is_data) { 3154 struct btrfs_root *csum_root; 3155 3156 csum_root = btrfs_csum_root(trans->fs_info, bytenr); 3157 if (unlikely(!csum_root)) { 3158 ret = -EUCLEAN; 3159 btrfs_abort_transaction(trans, ret); 3160 btrfs_err(trans->fs_info, 3161 "missing csum root for extent at bytenr %llu", 3162 bytenr); 3163 return ret; 3164 } 3165 3166 ret = btrfs_del_csums(trans, csum_root, bytenr, num_bytes); 3167 if (unlikely(ret)) { 3168 btrfs_abort_transaction(trans, ret); 3169 return ret; 3170 } 3171 3172 ret = btrfs_delete_raid_extent(trans, bytenr, num_bytes); 3173 if (unlikely(ret)) { 3174 btrfs_abort_transaction(trans, ret); 3175 return ret; 3176 } 3177 } 3178 3179 ret = btrfs_record_squota_delta(trans->fs_info, delta); 3180 if (unlikely(ret)) { 3181 btrfs_abort_transaction(trans, ret); 3182 return ret; 3183 } 3184 3185 /* If remapped, FST has already been taken care of in remove_range_from_remap_tree(). */ 3186 if (!remapped) { 3187 ret = btrfs_add_to_free_space_tree(trans, bytenr, num_bytes); 3188 if (unlikely(ret)) { 3189 btrfs_abort_transaction(trans, ret); 3190 return ret; 3191 } 3192 } 3193 3194 ret = btrfs_update_block_group(trans, bytenr, num_bytes, false); 3195 if (ret) 3196 btrfs_abort_transaction(trans, ret); 3197 3198 return ret; 3199 } 3200 3201 #define abort_and_dump(trans, path, fmt, args...) \ 3202 ({ \ 3203 btrfs_abort_transaction(trans, -EUCLEAN); \ 3204 btrfs_print_leaf(path->nodes[0]); \ 3205 btrfs_crit(trans->fs_info, fmt, ##args); \ 3206 }) 3207 3208 /* 3209 * Drop one or more refs of @node. 3210 * 3211 * 1. Locate the extent refs. 3212 * It's either inline in EXTENT/METADATA_ITEM or in keyed SHARED_* item. 3213 * Locate it, then reduce the refs number or remove the ref line completely. 3214 * 3215 * 2. Update the refs count in EXTENT/METADATA_ITEM 3216 * 3217 * Inline backref case: 3218 * 3219 * in extent tree we have: 3220 * 3221 * item 0 key (13631488 EXTENT_ITEM 1048576) itemoff 16201 itemsize 82 3222 * refs 2 gen 6 flags DATA 3223 * extent data backref root FS_TREE objectid 258 offset 0 count 1 3224 * extent data backref root FS_TREE objectid 257 offset 0 count 1 3225 * 3226 * This function gets called with: 3227 * 3228 * node->bytenr = 13631488 3229 * node->num_bytes = 1048576 3230 * root_objectid = FS_TREE 3231 * owner_objectid = 257 3232 * owner_offset = 0 3233 * refs_to_drop = 1 3234 * 3235 * Then we should get some like: 3236 * 3237 * item 0 key (13631488 EXTENT_ITEM 1048576) itemoff 16201 itemsize 82 3238 * refs 1 gen 6 flags DATA 3239 * extent data backref root FS_TREE objectid 258 offset 0 count 1 3240 * 3241 * Keyed backref case: 3242 * 3243 * in extent tree we have: 3244 * 3245 * item 0 key (13631488 EXTENT_ITEM 1048576) itemoff 3971 itemsize 24 3246 * refs 754 gen 6 flags DATA 3247 * [...] 3248 * item 2 key (13631488 EXTENT_DATA_REF <HASH>) itemoff 3915 itemsize 28 3249 * extent data backref root FS_TREE objectid 866 offset 0 count 1 3250 * 3251 * This function get called with: 3252 * 3253 * node->bytenr = 13631488 3254 * node->num_bytes = 1048576 3255 * root_objectid = FS_TREE 3256 * owner_objectid = 866 3257 * owner_offset = 0 3258 * refs_to_drop = 1 3259 * 3260 * Then we should get some like: 3261 * 3262 * item 0 key (13631488 EXTENT_ITEM 1048576) itemoff 3971 itemsize 24 3263 * refs 753 gen 6 flags DATA 3264 * 3265 * And that (13631488 EXTENT_DATA_REF <HASH>) gets removed. 3266 */ 3267 static int __btrfs_free_extent(struct btrfs_trans_handle *trans, 3268 struct btrfs_delayed_ref_head *href, 3269 const struct btrfs_delayed_ref_node *node, 3270 struct btrfs_delayed_extent_op *extent_op) 3271 { 3272 struct btrfs_fs_info *info = trans->fs_info; 3273 struct btrfs_key key; 3274 BTRFS_PATH_AUTO_FREE(path); 3275 struct btrfs_root *extent_root; 3276 struct extent_buffer *leaf; 3277 struct btrfs_extent_item *ei; 3278 struct btrfs_extent_inline_ref *iref; 3279 int ret; 3280 int is_data; 3281 int extent_slot = 0; 3282 int found_extent = 0; 3283 int num_to_del = 1; 3284 int refs_to_drop = node->ref_mod; 3285 u32 item_size; 3286 u64 refs; 3287 u64 bytenr = node->bytenr; 3288 u64 num_bytes = node->num_bytes; 3289 u64 owner_objectid = btrfs_delayed_ref_owner(node); 3290 u64 owner_offset = btrfs_delayed_ref_offset(node); 3291 bool skinny_metadata = btrfs_fs_incompat(info, SKINNY_METADATA); 3292 u64 delayed_ref_root = href->owning_root; 3293 3294 extent_root = btrfs_extent_root(info, bytenr); 3295 if (unlikely(!extent_root)) { 3296 btrfs_err(info, 3297 "missing extent root for extent at bytenr %llu", bytenr); 3298 return -EUCLEAN; 3299 } 3300 3301 path = btrfs_alloc_path(); 3302 if (!path) 3303 return -ENOMEM; 3304 3305 is_data = owner_objectid >= BTRFS_FIRST_FREE_OBJECTID; 3306 3307 if (unlikely(!is_data && refs_to_drop != 1)) { 3308 btrfs_crit(info, 3309 "invalid refs_to_drop, dropping more than 1 refs for tree block %llu refs_to_drop %u", 3310 node->bytenr, refs_to_drop); 3311 ret = -EINVAL; 3312 btrfs_abort_transaction(trans, ret); 3313 return ret; 3314 } 3315 3316 if (is_data) 3317 skinny_metadata = false; 3318 3319 ret = lookup_extent_backref(trans, path, &iref, bytenr, num_bytes, 3320 node->parent, node->ref_root, owner_objectid, 3321 owner_offset); 3322 if (ret == 0) { 3323 /* 3324 * Either the inline backref or the SHARED_DATA_REF/ 3325 * SHARED_BLOCK_REF is found 3326 * 3327 * Here is a quick path to locate EXTENT/METADATA_ITEM. 3328 * It's possible the EXTENT/METADATA_ITEM is near current slot. 3329 */ 3330 extent_slot = path->slots[0]; 3331 while (extent_slot >= 0) { 3332 btrfs_item_key_to_cpu(path->nodes[0], &key, 3333 extent_slot); 3334 if (key.objectid != bytenr) 3335 break; 3336 if (key.type == BTRFS_EXTENT_ITEM_KEY && 3337 key.offset == num_bytes) { 3338 found_extent = 1; 3339 break; 3340 } 3341 if (key.type == BTRFS_METADATA_ITEM_KEY && 3342 key.offset == owner_objectid) { 3343 found_extent = 1; 3344 break; 3345 } 3346 3347 /* Quick path didn't find the EXTENT/METADATA_ITEM */ 3348 if (path->slots[0] - extent_slot > 5) 3349 break; 3350 extent_slot--; 3351 } 3352 3353 if (!found_extent) { 3354 if (unlikely(iref)) { 3355 abort_and_dump(trans, path, 3356 "invalid iref slot %u, no EXTENT/METADATA_ITEM found but has inline extent ref", 3357 path->slots[0]); 3358 return -EUCLEAN; 3359 } 3360 /* Must be SHARED_* item, remove the backref first */ 3361 ret = remove_extent_backref(trans, extent_root, path, 3362 NULL, refs_to_drop, is_data); 3363 if (unlikely(ret)) { 3364 btrfs_abort_transaction(trans, ret); 3365 return ret; 3366 } 3367 btrfs_release_path(path); 3368 3369 /* Slow path to locate EXTENT/METADATA_ITEM */ 3370 key.objectid = bytenr; 3371 key.type = BTRFS_EXTENT_ITEM_KEY; 3372 key.offset = num_bytes; 3373 3374 if (!is_data && skinny_metadata) { 3375 key.type = BTRFS_METADATA_ITEM_KEY; 3376 key.offset = owner_objectid; 3377 } 3378 3379 ret = btrfs_search_slot(trans, extent_root, 3380 &key, path, -1, 1); 3381 if (ret > 0 && skinny_metadata && path->slots[0]) { 3382 /* 3383 * Couldn't find our skinny metadata item, 3384 * see if we have ye olde extent item. 3385 */ 3386 path->slots[0]--; 3387 btrfs_item_key_to_cpu(path->nodes[0], &key, 3388 path->slots[0]); 3389 if (key.objectid == bytenr && 3390 key.type == BTRFS_EXTENT_ITEM_KEY && 3391 key.offset == num_bytes) 3392 ret = 0; 3393 } 3394 3395 if (ret > 0 && skinny_metadata) { 3396 skinny_metadata = false; 3397 key.objectid = bytenr; 3398 key.type = BTRFS_EXTENT_ITEM_KEY; 3399 key.offset = num_bytes; 3400 btrfs_release_path(path); 3401 ret = btrfs_search_slot(trans, extent_root, 3402 &key, path, -1, 1); 3403 } 3404 3405 if (ret) { 3406 if (ret > 0) 3407 btrfs_print_leaf(path->nodes[0]); 3408 btrfs_err(info, 3409 "umm, got %d back from search, was looking for %llu, slot %d", 3410 ret, bytenr, path->slots[0]); 3411 } 3412 if (unlikely(ret < 0)) { 3413 btrfs_abort_transaction(trans, ret); 3414 return ret; 3415 } 3416 extent_slot = path->slots[0]; 3417 } 3418 } else if (WARN_ON(ret == -ENOENT)) { 3419 abort_and_dump(trans, path, 3420 "unable to find ref byte nr %llu parent %llu root %llu owner %llu offset %llu slot %d", 3421 bytenr, node->parent, node->ref_root, owner_objectid, 3422 owner_offset, path->slots[0]); 3423 return ret; 3424 } else { 3425 btrfs_abort_transaction(trans, ret); 3426 return ret; 3427 } 3428 3429 leaf = path->nodes[0]; 3430 item_size = btrfs_item_size(leaf, extent_slot); 3431 if (unlikely(item_size < sizeof(*ei))) { 3432 ret = -EUCLEAN; 3433 btrfs_err(trans->fs_info, 3434 "unexpected extent item size, has %u expect >= %zu", 3435 item_size, sizeof(*ei)); 3436 btrfs_abort_transaction(trans, ret); 3437 return ret; 3438 } 3439 ei = btrfs_item_ptr(leaf, extent_slot, 3440 struct btrfs_extent_item); 3441 if (owner_objectid < BTRFS_FIRST_FREE_OBJECTID && 3442 key.type == BTRFS_EXTENT_ITEM_KEY) { 3443 struct btrfs_tree_block_info *bi; 3444 3445 if (unlikely(item_size < sizeof(*ei) + sizeof(*bi))) { 3446 abort_and_dump(trans, path, 3447 "invalid extent item size for key (%llu, %u, %llu) slot %u owner %llu, has %u expect >= %zu", 3448 key.objectid, key.type, key.offset, 3449 path->slots[0], owner_objectid, item_size, 3450 sizeof(*ei) + sizeof(*bi)); 3451 return -EUCLEAN; 3452 } 3453 bi = (struct btrfs_tree_block_info *)(ei + 1); 3454 WARN_ON(owner_objectid != btrfs_tree_block_level(leaf, bi)); 3455 } 3456 3457 refs = btrfs_extent_refs(leaf, ei); 3458 if (unlikely(refs < refs_to_drop)) { 3459 abort_and_dump(trans, path, 3460 "trying to drop %d refs but we only have %llu for bytenr %llu slot %u", 3461 refs_to_drop, refs, bytenr, path->slots[0]); 3462 return -EUCLEAN; 3463 } 3464 refs -= refs_to_drop; 3465 3466 if (refs > 0) { 3467 if (extent_op) 3468 __run_delayed_extent_op(extent_op, leaf, ei); 3469 /* 3470 * In the case of inline back ref, reference count will 3471 * be updated by remove_extent_backref 3472 */ 3473 if (iref) { 3474 if (unlikely(!found_extent)) { 3475 abort_and_dump(trans, path, 3476 "invalid iref, got inlined extent ref but no EXTENT/METADATA_ITEM found, slot %u", 3477 path->slots[0]); 3478 return -EUCLEAN; 3479 } 3480 } else { 3481 btrfs_set_extent_refs(leaf, ei, refs); 3482 } 3483 if (found_extent) { 3484 ret = remove_extent_backref(trans, extent_root, path, 3485 iref, refs_to_drop, is_data); 3486 if (unlikely(ret)) { 3487 btrfs_abort_transaction(trans, ret); 3488 return ret; 3489 } 3490 } 3491 } else { 3492 struct btrfs_squota_delta delta = { 3493 .root = delayed_ref_root, 3494 .num_bytes = num_bytes, 3495 .is_data = is_data, 3496 .is_inc = false, 3497 .generation = btrfs_extent_generation(leaf, ei), 3498 }; 3499 3500 /* In this branch refs == 1 */ 3501 if (found_extent) { 3502 if (unlikely(is_data && refs_to_drop != 3503 extent_data_ref_count(path, iref))) { 3504 abort_and_dump(trans, path, 3505 "invalid refs_to_drop, current refs %u refs_to_drop %u slot %u", 3506 extent_data_ref_count(path, iref), 3507 refs_to_drop, path->slots[0]); 3508 return -EUCLEAN; 3509 } 3510 if (iref) { 3511 if (unlikely(path->slots[0] != extent_slot)) { 3512 abort_and_dump(trans, path, 3513 "invalid iref, extent item key " BTRFS_KEY_FMT " slot %u doesn't have wanted iref", 3514 BTRFS_KEY_FMT_VALUE(&key), 3515 path->slots[0]); 3516 return -EUCLEAN; 3517 } 3518 } else { 3519 /* 3520 * No inline ref, we must be at SHARED_* item, 3521 * And it's single ref, it must be: 3522 * | extent_slot ||extent_slot + 1| 3523 * [ EXTENT/METADATA_ITEM ][ SHARED_* ITEM ] 3524 */ 3525 if (unlikely(path->slots[0] != extent_slot + 1)) { 3526 abort_and_dump(trans, path, 3527 "invalid SHARED_* item slot %u, previous item is not EXTENT/METADATA_ITEM", 3528 path->slots[0]); 3529 return -EUCLEAN; 3530 } 3531 path->slots[0] = extent_slot; 3532 num_to_del = 2; 3533 } 3534 } 3535 /* 3536 * We can't infer the data owner from the delayed ref, so we need 3537 * to try to get it from the owning ref item. 3538 * 3539 * If it is not present, then that extent was not written under 3540 * simple quotas mode, so we don't need to account for its deletion. 3541 */ 3542 if (is_data) 3543 delta.root = btrfs_get_extent_owner_root(trans->fs_info, 3544 leaf, extent_slot); 3545 3546 ret = btrfs_del_items(trans, extent_root, path, path->slots[0], 3547 num_to_del); 3548 if (unlikely(ret)) { 3549 btrfs_abort_transaction(trans, ret); 3550 return ret; 3551 } 3552 btrfs_release_path(path); 3553 3554 ret = do_free_extent_accounting(trans, bytenr, &delta, path); 3555 } 3556 btrfs_release_path(path); 3557 3558 return ret; 3559 } 3560 3561 /* 3562 * when we free an block, it is possible (and likely) that we free the last 3563 * delayed ref for that extent as well. This searches the delayed ref tree for 3564 * a given extent, and if there are no other delayed refs to be processed, it 3565 * removes it from the tree. 3566 */ 3567 static noinline int check_ref_cleanup(struct btrfs_trans_handle *trans, 3568 u64 bytenr) 3569 { 3570 struct btrfs_fs_info *fs_info = trans->fs_info; 3571 struct btrfs_delayed_ref_head *head; 3572 struct btrfs_delayed_ref_root *delayed_refs; 3573 int ret = 0; 3574 3575 delayed_refs = &trans->transaction->delayed_refs; 3576 spin_lock(&delayed_refs->lock); 3577 head = btrfs_find_delayed_ref_head(fs_info, delayed_refs, bytenr); 3578 if (!head) 3579 goto out_delayed_unlock; 3580 3581 spin_lock(&head->lock); 3582 if (!RB_EMPTY_ROOT(&head->ref_tree.rb_root)) 3583 goto out; 3584 3585 if (cleanup_extent_op(head) != NULL) 3586 goto out; 3587 3588 /* 3589 * waiting for the lock here would deadlock. If someone else has it 3590 * locked they are already in the process of dropping it anyway 3591 */ 3592 if (!mutex_trylock(&head->mutex)) 3593 goto out; 3594 3595 btrfs_delete_ref_head(fs_info, delayed_refs, head); 3596 head->processing = false; 3597 3598 spin_unlock(&head->lock); 3599 spin_unlock(&delayed_refs->lock); 3600 3601 BUG_ON(head->extent_op); 3602 if (head->must_insert_reserved) 3603 ret = 1; 3604 3605 btrfs_cleanup_ref_head_accounting(fs_info, delayed_refs, head); 3606 mutex_unlock(&head->mutex); 3607 btrfs_put_delayed_ref_head(head); 3608 return ret; 3609 out: 3610 spin_unlock(&head->lock); 3611 3612 out_delayed_unlock: 3613 spin_unlock(&delayed_refs->lock); 3614 return 0; 3615 } 3616 3617 int btrfs_free_tree_block(struct btrfs_trans_handle *trans, 3618 u64 root_id, 3619 struct extent_buffer *buf, 3620 u64 parent, int last_ref) 3621 { 3622 struct btrfs_fs_info *fs_info = trans->fs_info; 3623 struct btrfs_block_group *bg; 3624 int ret; 3625 3626 if (root_id != BTRFS_TREE_LOG_OBJECTID) { 3627 struct btrfs_ref generic_ref = { 3628 .action = BTRFS_DROP_DELAYED_REF, 3629 .bytenr = buf->start, 3630 .num_bytes = buf->len, 3631 .parent = parent, 3632 .owning_root = btrfs_header_owner(buf), 3633 .ref_root = root_id, 3634 }; 3635 3636 /* 3637 * Assert that the extent buffer is not cleared due to 3638 * EXTENT_BUFFER_ZONED_ZEROOUT. Please refer 3639 * btrfs_clear_buffer_dirty() and btree_csum_one_bio() for 3640 * detail. 3641 */ 3642 ASSERT(btrfs_header_bytenr(buf) != 0); 3643 3644 btrfs_init_tree_ref(&generic_ref, btrfs_header_level(buf), 0, false); 3645 btrfs_ref_tree_mod(fs_info, &generic_ref); 3646 ret = btrfs_add_delayed_tree_ref(trans, &generic_ref, NULL); 3647 if (ret < 0) 3648 return ret; 3649 } 3650 3651 if (!last_ref) 3652 return 0; 3653 3654 if (btrfs_header_generation(buf) != trans->transid) 3655 return 0; 3656 3657 if (root_id != BTRFS_TREE_LOG_OBJECTID) { 3658 ret = check_ref_cleanup(trans, buf->start); 3659 if (!ret) 3660 return 0; 3661 } 3662 3663 bg = btrfs_lookup_block_group(fs_info, buf->start); 3664 3665 if (btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN)) { 3666 pin_down_extent(trans, bg, buf->start, buf->len, true); 3667 btrfs_put_block_group(bg); 3668 return 0; 3669 } 3670 3671 /* 3672 * If there are tree mod log users we may have recorded mod log 3673 * operations for this node. If we re-allocate this node we 3674 * could replay operations on this node that happened when it 3675 * existed in a completely different root. For example if it 3676 * was part of root A, then was reallocated to root B, and we 3677 * are doing a btrfs_old_search_slot(root b), we could replay 3678 * operations that happened when the block was part of root A, 3679 * giving us an inconsistent view of the btree. 3680 * 3681 * We are safe from races here because at this point no other 3682 * node or root points to this extent buffer, so if after this 3683 * check a new tree mod log user joins we will not have an 3684 * existing log of operations on this node that we have to 3685 * contend with. 3686 */ 3687 3688 if (test_bit(BTRFS_FS_TREE_MOD_LOG_USERS, &fs_info->flags) 3689 || btrfs_is_zoned(fs_info)) { 3690 pin_down_extent(trans, bg, buf->start, buf->len, true); 3691 btrfs_put_block_group(bg); 3692 return 0; 3693 } 3694 3695 WARN_ON(test_bit(EXTENT_BUFFER_DIRTY, &buf->bflags)); 3696 3697 btrfs_add_free_space(bg, buf->start, buf->len); 3698 btrfs_free_reserved_bytes(bg, buf->len, false); 3699 btrfs_put_block_group(bg); 3700 trace_btrfs_reserved_extent_free(fs_info, buf->start, buf->len); 3701 3702 return 0; 3703 } 3704 3705 /* Can return -ENOMEM */ 3706 int btrfs_free_extent(struct btrfs_trans_handle *trans, struct btrfs_ref *ref) 3707 { 3708 struct btrfs_fs_info *fs_info = trans->fs_info; 3709 int ret; 3710 3711 if (btrfs_is_testing(fs_info)) 3712 return 0; 3713 3714 /* 3715 * tree log blocks never actually go into the extent allocation 3716 * tree, just update pinning info and exit early. 3717 */ 3718 if (ref->ref_root == BTRFS_TREE_LOG_OBJECTID) { 3719 btrfs_pin_extent(trans, ref->bytenr, ref->num_bytes); 3720 ret = 0; 3721 } else if (ref->type == BTRFS_REF_METADATA) { 3722 ret = btrfs_add_delayed_tree_ref(trans, ref, NULL); 3723 } else { 3724 ret = btrfs_add_delayed_data_ref(trans, ref, 0); 3725 } 3726 3727 if (ref->ref_root != BTRFS_TREE_LOG_OBJECTID) 3728 btrfs_ref_tree_mod(fs_info, ref); 3729 3730 return ret; 3731 } 3732 3733 enum btrfs_loop_type { 3734 /* 3735 * Start caching block groups but do not wait for progress or for them 3736 * to be done. 3737 */ 3738 LOOP_CACHING_NOWAIT, 3739 3740 /* 3741 * Wait for the block group free_space >= the space we're waiting for if 3742 * the block group isn't cached. 3743 */ 3744 LOOP_CACHING_WAIT, 3745 3746 /* 3747 * Allow allocations to happen from block groups that do not yet have a 3748 * size classification. 3749 */ 3750 LOOP_UNSET_SIZE_CLASS, 3751 3752 /* 3753 * Allocate a chunk and then retry the allocation. 3754 */ 3755 LOOP_ALLOC_CHUNK, 3756 3757 /* 3758 * Ignore the size class restrictions for this allocation. 3759 */ 3760 LOOP_WRONG_SIZE_CLASS, 3761 3762 /* 3763 * Ignore the empty size, only try to allocate the number of bytes 3764 * needed for this allocation. 3765 */ 3766 LOOP_NO_EMPTY_SIZE, 3767 }; 3768 3769 static inline void 3770 btrfs_lock_block_group(struct btrfs_block_group *cache, bool delalloc) 3771 { 3772 if (delalloc) 3773 down_read(&cache->data_rwsem); 3774 } 3775 3776 static inline void btrfs_grab_block_group(struct btrfs_block_group *cache, 3777 bool delalloc) 3778 { 3779 btrfs_get_block_group(cache); 3780 if (delalloc) 3781 down_read(&cache->data_rwsem); 3782 } 3783 3784 static struct btrfs_block_group *btrfs_lock_cluster( 3785 struct btrfs_block_group *block_group, 3786 struct btrfs_free_cluster *cluster, 3787 bool delalloc) 3788 __acquires(&cluster->refill_lock) 3789 { 3790 struct btrfs_block_group *used_bg = NULL; 3791 3792 spin_lock(&cluster->refill_lock); 3793 while (1) { 3794 used_bg = cluster->block_group; 3795 if (!used_bg) 3796 return NULL; 3797 3798 if (used_bg == block_group) 3799 return used_bg; 3800 3801 btrfs_get_block_group(used_bg); 3802 3803 if (!delalloc) 3804 return used_bg; 3805 3806 if (down_read_trylock(&used_bg->data_rwsem)) 3807 return used_bg; 3808 3809 spin_unlock(&cluster->refill_lock); 3810 3811 /* We should only have one-level nested. */ 3812 down_read_nested(&used_bg->data_rwsem, SINGLE_DEPTH_NESTING); 3813 3814 spin_lock(&cluster->refill_lock); 3815 if (used_bg == cluster->block_group) 3816 return used_bg; 3817 3818 up_read(&used_bg->data_rwsem); 3819 btrfs_put_block_group(used_bg); 3820 } 3821 } 3822 3823 static inline void 3824 btrfs_release_block_group(struct btrfs_block_group *cache, bool delalloc) 3825 { 3826 if (delalloc) 3827 up_read(&cache->data_rwsem); 3828 btrfs_put_block_group(cache); 3829 } 3830 3831 static bool find_free_extent_check_size_class(const struct find_free_extent_ctl *ffe_ctl, 3832 const struct btrfs_block_group *bg) 3833 { 3834 if (ffe_ctl->policy == BTRFS_EXTENT_ALLOC_ZONED) 3835 return true; 3836 if (!btrfs_block_group_should_use_size_class(bg)) 3837 return true; 3838 if (ffe_ctl->loop >= LOOP_WRONG_SIZE_CLASS) 3839 return true; 3840 if (ffe_ctl->loop >= LOOP_UNSET_SIZE_CLASS && 3841 bg->size_class == BTRFS_BG_SZ_NONE) 3842 return true; 3843 return ffe_ctl->size_class == bg->size_class; 3844 } 3845 3846 /* 3847 * Helper function for find_free_extent(). 3848 * 3849 * Return -ENOENT to inform caller that we need fallback to unclustered mode. 3850 * Return >0 to inform caller that we find nothing 3851 * Return 0 means we have found a location and set ffe_ctl->found_offset. 3852 */ 3853 static int find_free_extent_clustered(struct btrfs_block_group *bg, 3854 struct find_free_extent_ctl *ffe_ctl, 3855 struct btrfs_block_group **cluster_bg_ret) 3856 { 3857 struct btrfs_block_group *cluster_bg; 3858 struct btrfs_free_cluster *last_ptr = ffe_ctl->last_ptr; 3859 u64 aligned_cluster; 3860 u64 offset; 3861 int ret; 3862 3863 cluster_bg = btrfs_lock_cluster(bg, last_ptr, ffe_ctl->delalloc); 3864 if (!cluster_bg) 3865 goto refill_cluster; 3866 if (cluster_bg != bg && (cluster_bg->ro || 3867 !block_group_bits(cluster_bg, ffe_ctl->flags) || 3868 !find_free_extent_check_size_class(ffe_ctl, cluster_bg))) 3869 goto release_cluster; 3870 3871 offset = btrfs_alloc_from_cluster(cluster_bg, last_ptr, 3872 ffe_ctl->num_bytes, cluster_bg->start, 3873 &ffe_ctl->max_extent_size); 3874 if (offset) { 3875 /* We have a block, we're done */ 3876 spin_unlock(&last_ptr->refill_lock); 3877 trace_btrfs_reserve_extent_cluster(cluster_bg, ffe_ctl); 3878 *cluster_bg_ret = cluster_bg; 3879 ffe_ctl->found_offset = offset; 3880 return 0; 3881 } 3882 WARN_ON(last_ptr->block_group != cluster_bg); 3883 3884 release_cluster: 3885 /* 3886 * If we are on LOOP_NO_EMPTY_SIZE, we can't set up a new clusters, so 3887 * lets just skip it and let the allocator find whatever block it can 3888 * find. If we reach this point, we will have tried the cluster 3889 * allocator plenty of times and not have found anything, so we are 3890 * likely way too fragmented for the clustering stuff to find anything. 3891 * 3892 * However, if the cluster is taken from the current block group, 3893 * release the cluster first, so that we stand a better chance of 3894 * succeeding in the unclustered allocation. 3895 */ 3896 if (ffe_ctl->loop >= LOOP_NO_EMPTY_SIZE && cluster_bg != bg) { 3897 spin_unlock(&last_ptr->refill_lock); 3898 btrfs_release_block_group(cluster_bg, ffe_ctl->delalloc); 3899 return -ENOENT; 3900 } 3901 3902 /* This cluster didn't work out, free it and start over */ 3903 btrfs_return_cluster_to_free_space(NULL, last_ptr); 3904 3905 if (cluster_bg != bg) 3906 btrfs_release_block_group(cluster_bg, ffe_ctl->delalloc); 3907 3908 refill_cluster: 3909 if (ffe_ctl->loop >= LOOP_NO_EMPTY_SIZE) { 3910 spin_unlock(&last_ptr->refill_lock); 3911 return -ENOENT; 3912 } 3913 3914 aligned_cluster = max_t(u64, 3915 ffe_ctl->empty_cluster + ffe_ctl->empty_size, 3916 bg->full_stripe_len); 3917 ret = btrfs_find_space_cluster(bg, last_ptr, ffe_ctl->search_start, 3918 ffe_ctl->num_bytes, aligned_cluster); 3919 if (ret == 0) { 3920 /* Now pull our allocation out of this cluster */ 3921 offset = btrfs_alloc_from_cluster(bg, last_ptr, 3922 ffe_ctl->num_bytes, ffe_ctl->search_start, 3923 &ffe_ctl->max_extent_size); 3924 if (offset) { 3925 /* We found one, proceed */ 3926 spin_unlock(&last_ptr->refill_lock); 3927 ffe_ctl->found_offset = offset; 3928 trace_btrfs_reserve_extent_cluster(bg, ffe_ctl); 3929 return 0; 3930 } 3931 } 3932 /* 3933 * At this point we either didn't find a cluster or we weren't able to 3934 * allocate a block from our cluster. Free the cluster we've been 3935 * trying to use, and go to the next block group. 3936 */ 3937 btrfs_return_cluster_to_free_space(NULL, last_ptr); 3938 spin_unlock(&last_ptr->refill_lock); 3939 return 1; 3940 } 3941 3942 /* 3943 * Return >0 to inform caller that we find nothing 3944 * Return 0 when we found an free extent and set ffe_ctrl->found_offset 3945 */ 3946 static int find_free_extent_unclustered(struct btrfs_block_group *bg, 3947 struct find_free_extent_ctl *ffe_ctl) 3948 { 3949 struct btrfs_free_cluster *last_ptr = ffe_ctl->last_ptr; 3950 u64 offset; 3951 3952 /* 3953 * We are doing an unclustered allocation, set the fragmented flag so 3954 * we don't bother trying to setup a cluster again until we get more 3955 * space. 3956 */ 3957 if (unlikely(last_ptr)) { 3958 spin_lock(&last_ptr->lock); 3959 last_ptr->fragmented = 1; 3960 spin_unlock(&last_ptr->lock); 3961 } 3962 if (ffe_ctl->cached) { 3963 struct btrfs_free_space_ctl *free_space_ctl; 3964 3965 free_space_ctl = bg->free_space_ctl; 3966 spin_lock(&free_space_ctl->tree_lock); 3967 if (free_space_ctl->free_space < 3968 ffe_ctl->num_bytes + ffe_ctl->empty_cluster + 3969 ffe_ctl->empty_size) { 3970 ffe_ctl->total_free_space = max_t(u64, 3971 ffe_ctl->total_free_space, 3972 free_space_ctl->free_space); 3973 spin_unlock(&free_space_ctl->tree_lock); 3974 return 1; 3975 } 3976 spin_unlock(&free_space_ctl->tree_lock); 3977 } 3978 3979 offset = btrfs_find_space_for_alloc(bg, ffe_ctl->search_start, 3980 ffe_ctl->num_bytes, ffe_ctl->empty_size, 3981 &ffe_ctl->max_extent_size); 3982 if (!offset) 3983 return 1; 3984 ffe_ctl->found_offset = offset; 3985 return 0; 3986 } 3987 3988 static int do_allocation_clustered(struct btrfs_block_group *block_group, 3989 struct find_free_extent_ctl *ffe_ctl, 3990 struct btrfs_block_group **bg_ret) 3991 { 3992 int ret; 3993 3994 /* We want to try and use the cluster allocator, so lets look there */ 3995 if (ffe_ctl->last_ptr && ffe_ctl->use_cluster) { 3996 ret = find_free_extent_clustered(block_group, ffe_ctl, bg_ret); 3997 if (ret >= 0) 3998 return ret; 3999 /* ret == -ENOENT case falls through */ 4000 } 4001 4002 return find_free_extent_unclustered(block_group, ffe_ctl); 4003 } 4004 4005 /* 4006 * Tree-log block group locking 4007 * ============================ 4008 * 4009 * fs_info::treelog_bg_lock protects the fs_info::treelog_bg which 4010 * indicates the starting address of a block group, which is reserved only 4011 * for tree-log metadata. 4012 * 4013 * Lock nesting 4014 * ============ 4015 * 4016 * block_group::lock 4017 * fs_info::treelog_bg_lock 4018 */ 4019 4020 /* 4021 * Simple allocator for sequential-only block group. It only allows sequential 4022 * allocation. No need to play with trees. This function also reserves the 4023 * bytes as in btrfs_add_reserved_bytes. 4024 */ 4025 static int do_allocation_zoned(struct btrfs_block_group *block_group, 4026 struct find_free_extent_ctl *ffe_ctl, 4027 struct btrfs_block_group **bg_ret) 4028 { 4029 struct btrfs_fs_info *fs_info = block_group->fs_info; 4030 struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl; 4031 u64 start = block_group->start; 4032 u64 num_bytes = ffe_ctl->num_bytes; 4033 u64 avail; 4034 u64 bytenr = block_group->start; 4035 u64 log_bytenr; 4036 u64 data_reloc_bytenr; 4037 int ret = 0; 4038 bool skip = false; 4039 4040 ASSERT(btrfs_is_zoned(block_group->fs_info)); 4041 4042 /* 4043 * Do not allow non-tree-log blocks in the dedicated tree-log block 4044 * group, and vice versa. 4045 */ 4046 spin_lock(&fs_info->treelog_bg_lock); 4047 log_bytenr = fs_info->treelog_bg; 4048 if (log_bytenr && ((ffe_ctl->for_treelog && bytenr != log_bytenr) || 4049 (!ffe_ctl->for_treelog && bytenr == log_bytenr))) 4050 skip = true; 4051 spin_unlock(&fs_info->treelog_bg_lock); 4052 if (skip) 4053 return 1; 4054 4055 /* 4056 * Do not allow non-relocation blocks in the dedicated relocation block 4057 * group, and vice versa. 4058 */ 4059 spin_lock(&fs_info->relocation_bg_lock); 4060 data_reloc_bytenr = fs_info->data_reloc_bg; 4061 if (data_reloc_bytenr && 4062 ((ffe_ctl->for_data_reloc && bytenr != data_reloc_bytenr) || 4063 (!ffe_ctl->for_data_reloc && bytenr == data_reloc_bytenr))) 4064 skip = true; 4065 spin_unlock(&fs_info->relocation_bg_lock); 4066 if (skip) 4067 return 1; 4068 4069 /* Check RO and no space case before trying to activate it */ 4070 spin_lock(&block_group->lock); 4071 if (block_group->ro || btrfs_zoned_bg_is_full(block_group)) { 4072 ret = 1; 4073 /* 4074 * May need to clear fs_info->{treelog,data_reloc}_bg. 4075 * Return the error after taking the locks. 4076 */ 4077 } 4078 spin_unlock(&block_group->lock); 4079 4080 /* Metadata block group is activated at write time. */ 4081 if (!ret && (block_group->flags & BTRFS_BLOCK_GROUP_DATA) && 4082 !btrfs_zone_activate(block_group)) { 4083 ret = 1; 4084 /* 4085 * May need to clear fs_info->{treelog,data_reloc}_bg. 4086 * Return the error after taking the locks. 4087 */ 4088 } 4089 4090 spin_lock(&block_group->lock); 4091 spin_lock(&fs_info->treelog_bg_lock); 4092 spin_lock(&fs_info->relocation_bg_lock); 4093 4094 if (ret) 4095 goto out; 4096 4097 ASSERT(!ffe_ctl->for_treelog || 4098 block_group->start == fs_info->treelog_bg || 4099 fs_info->treelog_bg == 0); 4100 ASSERT(!ffe_ctl->for_data_reloc || 4101 block_group->start == fs_info->data_reloc_bg || 4102 fs_info->data_reloc_bg == 0); 4103 4104 if (block_group->ro || 4105 (!ffe_ctl->for_data_reloc && 4106 test_bit(BLOCK_GROUP_FLAG_ZONED_DATA_RELOC, &block_group->runtime_flags))) { 4107 ret = 1; 4108 goto out; 4109 } 4110 4111 /* 4112 * Do not allow currently using block group to be tree-log dedicated 4113 * block group. 4114 */ 4115 if (ffe_ctl->for_treelog && !fs_info->treelog_bg && 4116 (block_group->used || block_group->reserved)) { 4117 ret = 1; 4118 goto out; 4119 } 4120 4121 /* 4122 * Do not allow currently used block group to be the data relocation 4123 * dedicated block group. 4124 */ 4125 if (ffe_ctl->for_data_reloc && !fs_info->data_reloc_bg && 4126 (block_group->used || block_group->reserved)) { 4127 ret = 1; 4128 goto out; 4129 } 4130 4131 WARN_ON_ONCE(block_group->alloc_offset > block_group->zone_capacity); 4132 avail = block_group->zone_capacity - block_group->alloc_offset; 4133 if (avail < num_bytes) { 4134 if (ffe_ctl->max_extent_size < avail) { 4135 /* 4136 * With sequential allocator, free space is always 4137 * contiguous 4138 */ 4139 ffe_ctl->max_extent_size = avail; 4140 ffe_ctl->total_free_space = avail; 4141 } 4142 ret = 1; 4143 goto out; 4144 } 4145 4146 if (ffe_ctl->for_treelog && !fs_info->treelog_bg) 4147 fs_info->treelog_bg = block_group->start; 4148 4149 if (ffe_ctl->for_data_reloc) { 4150 if (!fs_info->data_reloc_bg) 4151 fs_info->data_reloc_bg = block_group->start; 4152 /* 4153 * Do not allow allocations from this block group, unless it is 4154 * for data relocation. Compared to increasing the ->ro, setting 4155 * the ->zoned_data_reloc_ongoing flag still allows nocow 4156 * writers to come in. See btrfs_inc_nocow_writers(). 4157 * 4158 * We need to disable an allocation to avoid an allocation of 4159 * regular (non-relocation data) extent. With mix of relocation 4160 * extents and regular extents, we can dispatch WRITE commands 4161 * (for relocation extents) and ZONE APPEND commands (for 4162 * regular extents) at the same time to the same zone, which 4163 * easily break the write pointer. 4164 * 4165 * Also, this flag avoids this block group to be zone finished. 4166 */ 4167 set_bit(BLOCK_GROUP_FLAG_ZONED_DATA_RELOC, &block_group->runtime_flags); 4168 } 4169 4170 ffe_ctl->found_offset = start + block_group->alloc_offset; 4171 block_group->alloc_offset += num_bytes; 4172 spin_lock(&ctl->tree_lock); 4173 ctl->free_space -= num_bytes; 4174 spin_unlock(&ctl->tree_lock); 4175 4176 /* 4177 * We do not check if found_offset is aligned to stripesize. The 4178 * address is anyway rewritten when using zone append writing. 4179 */ 4180 4181 ffe_ctl->search_start = ffe_ctl->found_offset; 4182 4183 out: 4184 if (ret && ffe_ctl->for_treelog) 4185 fs_info->treelog_bg = 0; 4186 if (ret && ffe_ctl->for_data_reloc) 4187 fs_info->data_reloc_bg = 0; 4188 spin_unlock(&fs_info->relocation_bg_lock); 4189 spin_unlock(&fs_info->treelog_bg_lock); 4190 spin_unlock(&block_group->lock); 4191 return ret; 4192 } 4193 4194 static int do_allocation(struct btrfs_block_group *block_group, 4195 struct find_free_extent_ctl *ffe_ctl, 4196 struct btrfs_block_group **bg_ret) 4197 { 4198 switch (ffe_ctl->policy) { 4199 case BTRFS_EXTENT_ALLOC_CLUSTERED: 4200 return do_allocation_clustered(block_group, ffe_ctl, bg_ret); 4201 case BTRFS_EXTENT_ALLOC_ZONED: 4202 return do_allocation_zoned(block_group, ffe_ctl, bg_ret); 4203 default: 4204 BUG(); 4205 } 4206 } 4207 4208 static void release_block_group(struct btrfs_block_group *block_group, 4209 struct find_free_extent_ctl *ffe_ctl, 4210 bool delalloc) 4211 { 4212 switch (ffe_ctl->policy) { 4213 case BTRFS_EXTENT_ALLOC_CLUSTERED: 4214 ffe_ctl->retry_uncached = false; 4215 break; 4216 case BTRFS_EXTENT_ALLOC_ZONED: 4217 /* Nothing to do */ 4218 break; 4219 default: 4220 BUG(); 4221 } 4222 4223 BUG_ON(btrfs_bg_flags_to_raid_index(block_group->flags) != 4224 ffe_ctl->index); 4225 btrfs_release_block_group(block_group, delalloc); 4226 } 4227 4228 static void found_extent_clustered(struct find_free_extent_ctl *ffe_ctl, 4229 struct btrfs_key *ins) 4230 { 4231 struct btrfs_free_cluster *last_ptr = ffe_ctl->last_ptr; 4232 4233 if (!ffe_ctl->use_cluster && last_ptr) { 4234 spin_lock(&last_ptr->lock); 4235 last_ptr->window_start = ins->objectid; 4236 spin_unlock(&last_ptr->lock); 4237 } 4238 } 4239 4240 static void found_extent(struct find_free_extent_ctl *ffe_ctl, 4241 struct btrfs_key *ins) 4242 { 4243 switch (ffe_ctl->policy) { 4244 case BTRFS_EXTENT_ALLOC_CLUSTERED: 4245 found_extent_clustered(ffe_ctl, ins); 4246 break; 4247 case BTRFS_EXTENT_ALLOC_ZONED: 4248 /* Nothing to do */ 4249 break; 4250 default: 4251 BUG(); 4252 } 4253 } 4254 4255 static int can_allocate_chunk_zoned(struct btrfs_fs_info *fs_info, 4256 struct find_free_extent_ctl *ffe_ctl) 4257 { 4258 /* Block group's activeness is not a requirement for METADATA block groups. */ 4259 if (!(ffe_ctl->flags & BTRFS_BLOCK_GROUP_DATA)) 4260 return 0; 4261 4262 /* If we can activate new zone, just allocate a chunk and use it */ 4263 if (btrfs_can_activate_zone(fs_info->fs_devices, ffe_ctl->flags)) 4264 return 0; 4265 4266 /* 4267 * We already reached the max active zones. Try to finish one block 4268 * group to make a room for a new block group. This is only possible 4269 * for a data block group because btrfs_zone_finish() may need to wait 4270 * for a running transaction which can cause a deadlock for metadata 4271 * allocation. 4272 */ 4273 if (ffe_ctl->flags & BTRFS_BLOCK_GROUP_DATA) { 4274 int ret = btrfs_zone_finish_one_bg(fs_info); 4275 4276 if (ret == 1) 4277 return 0; 4278 else if (ret < 0) 4279 return ret; 4280 } 4281 4282 /* 4283 * If we have enough free space left in an already active block group 4284 * and we can't activate any other zone now, do not allow allocating a 4285 * new chunk and let find_free_extent() retry with a smaller size. 4286 */ 4287 if (ffe_ctl->max_extent_size >= ffe_ctl->min_alloc_size) 4288 return -ENOSPC; 4289 4290 /* 4291 * Even min_alloc_size is not left in any block groups. Since we cannot 4292 * activate a new block group, allocating it may not help. Let's tell a 4293 * caller to try again and hope it progress something by writing some 4294 * parts of the region. That is only possible for data block groups, 4295 * where a part of the region can be written. 4296 */ 4297 if (ffe_ctl->flags & BTRFS_BLOCK_GROUP_DATA) 4298 return -EAGAIN; 4299 4300 /* 4301 * We cannot activate a new block group and no enough space left in any 4302 * block groups. So, allocating a new block group may not help. But, 4303 * there is nothing to do anyway, so let's go with it. 4304 */ 4305 return 0; 4306 } 4307 4308 static int can_allocate_chunk(struct btrfs_fs_info *fs_info, 4309 struct find_free_extent_ctl *ffe_ctl) 4310 { 4311 switch (ffe_ctl->policy) { 4312 case BTRFS_EXTENT_ALLOC_CLUSTERED: 4313 return 0; 4314 case BTRFS_EXTENT_ALLOC_ZONED: 4315 return can_allocate_chunk_zoned(fs_info, ffe_ctl); 4316 default: 4317 BUG(); 4318 } 4319 } 4320 4321 /* 4322 * Return >0 means caller needs to re-search for free extent 4323 * Return 0 means we have the needed free extent. 4324 * Return <0 means we failed to locate any free extent. 4325 */ 4326 static int find_free_extent_update_loop(struct btrfs_fs_info *fs_info, 4327 struct btrfs_key *ins, 4328 struct find_free_extent_ctl *ffe_ctl, 4329 struct btrfs_space_info *space_info, 4330 bool full_search) 4331 { 4332 struct btrfs_root *root = fs_info->chunk_root; 4333 int ret; 4334 4335 if ((ffe_ctl->loop == LOOP_CACHING_NOWAIT) && 4336 ffe_ctl->have_caching_bg && !ffe_ctl->orig_have_caching_bg) 4337 ffe_ctl->orig_have_caching_bg = true; 4338 4339 if (ins->objectid) { 4340 found_extent(ffe_ctl, ins); 4341 return 0; 4342 } 4343 4344 if (ffe_ctl->loop >= LOOP_CACHING_WAIT && ffe_ctl->have_caching_bg) 4345 return 1; 4346 4347 ffe_ctl->index++; 4348 if (ffe_ctl->index < BTRFS_NR_RAID_TYPES) 4349 return 1; 4350 4351 /* See the comments for btrfs_loop_type for an explanation of the phases. */ 4352 if (ffe_ctl->loop == LOOP_NO_EMPTY_SIZE) 4353 return -ENOSPC; 4354 4355 ffe_ctl->index = 0; 4356 /* 4357 * We want to skip the LOOP_CACHING_WAIT step if we don't have any 4358 * uncached bgs and we've already done a full search through. 4359 */ 4360 if (ffe_ctl->loop == LOOP_CACHING_NOWAIT && 4361 (!ffe_ctl->orig_have_caching_bg && full_search)) 4362 ffe_ctl->loop++; 4363 ffe_ctl->loop++; 4364 4365 if (ffe_ctl->loop == LOOP_ALLOC_CHUNK) { 4366 struct btrfs_trans_handle *trans; 4367 bool have_trans = false; 4368 4369 /* Check if allocation policy allows to create a new chunk. */ 4370 ret = can_allocate_chunk(fs_info, ffe_ctl); 4371 if (ret) 4372 return ret; 4373 4374 trans = current->journal_info; 4375 if (trans) 4376 have_trans = true; 4377 else 4378 trans = btrfs_join_transaction(root); 4379 4380 if (IS_ERR(trans)) 4381 return PTR_ERR(trans); 4382 4383 ret = btrfs_chunk_alloc(trans, space_info, ffe_ctl->flags, 4384 CHUNK_ALLOC_FORCE_FOR_EXTENT); 4385 4386 /* Do not bail out on ENOSPC since we can do more. */ 4387 if (ret == -ENOSPC) { 4388 ret = 0; 4389 ffe_ctl->loop++; 4390 } else if (ret < 0) { 4391 btrfs_abort_transaction(trans, ret); 4392 } else { 4393 ret = 0; 4394 } 4395 4396 if (!have_trans) 4397 btrfs_end_transaction(trans); 4398 4399 if (ret) 4400 return ret; 4401 } 4402 4403 if (ffe_ctl->loop == LOOP_NO_EMPTY_SIZE) { 4404 if (ffe_ctl->policy != BTRFS_EXTENT_ALLOC_CLUSTERED) 4405 return -ENOSPC; 4406 4407 /* 4408 * Don't loop again if we already have no empty_size and 4409 * no empty_cluster. 4410 */ 4411 if (ffe_ctl->empty_size == 0 && ffe_ctl->empty_cluster == 0) 4412 return -ENOSPC; 4413 ffe_ctl->empty_size = 0; 4414 ffe_ctl->empty_cluster = 0; 4415 } 4416 4417 return 1; 4418 } 4419 4420 static int prepare_allocation_clustered(struct btrfs_fs_info *fs_info, 4421 struct find_free_extent_ctl *ffe_ctl, 4422 struct btrfs_space_info *space_info, 4423 struct btrfs_key *ins) 4424 { 4425 /* 4426 * If our free space is heavily fragmented we may not be able to make 4427 * big contiguous allocations, so instead of doing the expensive search 4428 * for free space, simply return ENOSPC with our max_extent_size so we 4429 * can go ahead and search for a more manageable chunk. 4430 * 4431 * If our max_extent_size is large enough for our allocation simply 4432 * disable clustering since we will likely not be able to find enough 4433 * space to create a cluster and induce latency trying. 4434 */ 4435 if (space_info->max_extent_size) { 4436 spin_lock(&space_info->lock); 4437 if (space_info->max_extent_size && 4438 ffe_ctl->num_bytes > space_info->max_extent_size) { 4439 ins->offset = space_info->max_extent_size; 4440 spin_unlock(&space_info->lock); 4441 return -ENOSPC; 4442 } else if (space_info->max_extent_size) { 4443 ffe_ctl->use_cluster = false; 4444 } 4445 spin_unlock(&space_info->lock); 4446 } 4447 4448 ffe_ctl->last_ptr = fetch_cluster_info(fs_info, space_info, 4449 &ffe_ctl->empty_cluster); 4450 if (ffe_ctl->last_ptr) { 4451 struct btrfs_free_cluster *last_ptr = ffe_ctl->last_ptr; 4452 4453 spin_lock(&last_ptr->lock); 4454 if (last_ptr->block_group) 4455 ffe_ctl->hint_byte = last_ptr->window_start; 4456 if (last_ptr->fragmented) { 4457 /* 4458 * We still set window_start so we can keep track of the 4459 * last place we found an allocation to try and save 4460 * some time. 4461 */ 4462 ffe_ctl->hint_byte = last_ptr->window_start; 4463 ffe_ctl->use_cluster = false; 4464 } 4465 spin_unlock(&last_ptr->lock); 4466 } 4467 4468 return 0; 4469 } 4470 4471 static int prepare_allocation_zoned(struct btrfs_fs_info *fs_info, 4472 struct find_free_extent_ctl *ffe_ctl, 4473 struct btrfs_space_info *space_info) 4474 { 4475 struct btrfs_block_group *block_group; 4476 4477 if (ffe_ctl->for_treelog) { 4478 spin_lock(&fs_info->treelog_bg_lock); 4479 if (fs_info->treelog_bg) 4480 ffe_ctl->hint_byte = fs_info->treelog_bg; 4481 spin_unlock(&fs_info->treelog_bg_lock); 4482 return 0; 4483 } 4484 4485 if (ffe_ctl->for_data_reloc) { 4486 spin_lock(&fs_info->relocation_bg_lock); 4487 if (fs_info->data_reloc_bg) 4488 ffe_ctl->hint_byte = fs_info->data_reloc_bg; 4489 spin_unlock(&fs_info->relocation_bg_lock); 4490 return 0; 4491 } 4492 4493 if (!(ffe_ctl->flags & BTRFS_BLOCK_GROUP_DATA)) 4494 return 0; 4495 4496 spin_lock(&fs_info->zone_active_bgs_lock); 4497 list_for_each_entry(block_group, &fs_info->zone_active_bgs, active_bg_list) { 4498 /* 4499 * No lock is OK here because avail is monotonically 4500 * decreasing, and this is just a hint. 4501 */ 4502 u64 avail = block_group->zone_capacity - block_group->alloc_offset; 4503 4504 if (block_group_bits(block_group, ffe_ctl->flags) && 4505 block_group->space_info == space_info && 4506 avail >= ffe_ctl->num_bytes) { 4507 ffe_ctl->hint_byte = block_group->start; 4508 break; 4509 } 4510 } 4511 spin_unlock(&fs_info->zone_active_bgs_lock); 4512 4513 return 0; 4514 } 4515 4516 static int prepare_allocation(struct btrfs_fs_info *fs_info, 4517 struct find_free_extent_ctl *ffe_ctl, 4518 struct btrfs_space_info *space_info, 4519 struct btrfs_key *ins) 4520 { 4521 switch (ffe_ctl->policy) { 4522 case BTRFS_EXTENT_ALLOC_CLUSTERED: 4523 return prepare_allocation_clustered(fs_info, ffe_ctl, 4524 space_info, ins); 4525 case BTRFS_EXTENT_ALLOC_ZONED: 4526 return prepare_allocation_zoned(fs_info, ffe_ctl, space_info); 4527 default: 4528 BUG(); 4529 } 4530 } 4531 4532 /* 4533 * walks the btree of allocated extents and find a hole of a given size. 4534 * The key ins is changed to record the hole: 4535 * ins->objectid == start position 4536 * ins->flags = BTRFS_EXTENT_ITEM_KEY 4537 * ins->offset == the size of the hole. 4538 * Any available blocks before search_start are skipped. 4539 * 4540 * If there is no suitable free space, we will record the max size of 4541 * the free space extent currently. 4542 * 4543 * The overall logic and call chain: 4544 * 4545 * find_free_extent() 4546 * |- Iterate through all block groups 4547 * | |- Get a valid block group 4548 * | |- Try to do clustered allocation in that block group 4549 * | |- Try to do unclustered allocation in that block group 4550 * | |- Check if the result is valid 4551 * | | |- If valid, then exit 4552 * | |- Jump to next block group 4553 * | 4554 * |- Push harder to find free extents 4555 * |- If not found, re-iterate all block groups 4556 */ 4557 static noinline int find_free_extent(struct btrfs_root *root, 4558 struct btrfs_key *ins, 4559 struct find_free_extent_ctl *ffe_ctl) 4560 { 4561 struct btrfs_fs_info *fs_info = root->fs_info; 4562 int ret = 0; 4563 int cache_block_group_error = 0; 4564 struct btrfs_block_group *block_group = NULL; 4565 struct btrfs_space_info *space_info; 4566 bool full_search = false; 4567 4568 WARN_ON(ffe_ctl->num_bytes < fs_info->sectorsize); 4569 4570 ffe_ctl->search_start = 0; 4571 /* For clustered allocation */ 4572 ffe_ctl->empty_cluster = 0; 4573 ffe_ctl->last_ptr = NULL; 4574 ffe_ctl->use_cluster = true; 4575 ffe_ctl->have_caching_bg = false; 4576 ffe_ctl->orig_have_caching_bg = false; 4577 ffe_ctl->index = btrfs_bg_flags_to_raid_index(ffe_ctl->flags); 4578 ffe_ctl->loop = 0; 4579 ffe_ctl->retry_uncached = false; 4580 ffe_ctl->cached = 0; 4581 ffe_ctl->max_extent_size = 0; 4582 ffe_ctl->total_free_space = 0; 4583 ffe_ctl->found_offset = 0; 4584 ffe_ctl->policy = BTRFS_EXTENT_ALLOC_CLUSTERED; 4585 ffe_ctl->size_class = btrfs_calc_block_group_size_class(ffe_ctl->num_bytes); 4586 4587 if (btrfs_is_zoned(fs_info)) 4588 ffe_ctl->policy = BTRFS_EXTENT_ALLOC_ZONED; 4589 4590 ins->type = BTRFS_EXTENT_ITEM_KEY; 4591 ins->objectid = 0; 4592 ins->offset = 0; 4593 4594 trace_btrfs_find_free_extent(root, ffe_ctl); 4595 4596 space_info = btrfs_find_space_info(fs_info, ffe_ctl->flags); 4597 if (btrfs_is_zoned(fs_info) && space_info) { 4598 /* Use dedicated sub-space_info for dedicated block group users. */ 4599 if (ffe_ctl->for_data_reloc) { 4600 space_info = space_info->sub_group[0]; 4601 ASSERT(space_info->subgroup_id == BTRFS_SUB_GROUP_DATA_RELOC); 4602 } else if (ffe_ctl->for_treelog) { 4603 space_info = space_info->sub_group[0]; 4604 ASSERT(space_info->subgroup_id == BTRFS_SUB_GROUP_TREELOG); 4605 } 4606 } 4607 if (!space_info) { 4608 btrfs_err(fs_info, "no space info for %llu, tree-log %d, relocation %d", 4609 ffe_ctl->flags, ffe_ctl->for_treelog, ffe_ctl->for_data_reloc); 4610 return -ENOSPC; 4611 } 4612 4613 ret = prepare_allocation(fs_info, ffe_ctl, space_info, ins); 4614 if (ret < 0) 4615 return ret; 4616 4617 ffe_ctl->search_start = max(ffe_ctl->search_start, 4618 first_logical_byte(fs_info)); 4619 ffe_ctl->search_start = max(ffe_ctl->search_start, ffe_ctl->hint_byte); 4620 if (ffe_ctl->search_start == ffe_ctl->hint_byte) { 4621 block_group = btrfs_lookup_block_group(fs_info, 4622 ffe_ctl->search_start); 4623 /* 4624 * we don't want to use the block group if it doesn't match our 4625 * allocation bits, or if its not cached. 4626 * 4627 * However if we are re-searching with an ideal block group 4628 * picked out then we don't care that the block group is cached. 4629 */ 4630 if (block_group && block_group_bits(block_group, ffe_ctl->flags) && 4631 block_group->space_info == space_info && 4632 block_group->cached != BTRFS_CACHE_NO) { 4633 down_read(&space_info->groups_sem); 4634 if (list_empty(&block_group->list) || 4635 block_group->ro || 4636 (block_group->flags & BTRFS_BLOCK_GROUP_REMAPPED)) { 4637 /* 4638 * someone is removing this block group, 4639 * we can't jump into the have_block_group 4640 * target because our list pointers are not 4641 * valid 4642 */ 4643 btrfs_put_block_group(block_group); 4644 up_read(&space_info->groups_sem); 4645 } else { 4646 ffe_ctl->index = btrfs_bg_flags_to_raid_index( 4647 block_group->flags); 4648 btrfs_lock_block_group(block_group, 4649 ffe_ctl->delalloc); 4650 ffe_ctl->hinted = true; 4651 goto have_block_group; 4652 } 4653 } else if (block_group) { 4654 btrfs_put_block_group(block_group); 4655 } 4656 } 4657 search: 4658 trace_btrfs_find_free_extent_search_loop(root, ffe_ctl); 4659 ffe_ctl->have_caching_bg = false; 4660 if (ffe_ctl->index == btrfs_bg_flags_to_raid_index(ffe_ctl->flags) || 4661 ffe_ctl->index == 0) 4662 full_search = true; 4663 down_read(&space_info->groups_sem); 4664 list_for_each_entry(block_group, 4665 &space_info->block_groups[ffe_ctl->index], list) { 4666 struct btrfs_block_group *bg_ret; 4667 4668 ffe_ctl->hinted = false; 4669 /* If the block group is read-only, we can skip it entirely. */ 4670 if (unlikely(block_group->ro || 4671 (block_group->flags & BTRFS_BLOCK_GROUP_REMAPPED))) { 4672 if (ffe_ctl->for_treelog) 4673 btrfs_clear_treelog_bg(block_group); 4674 if (ffe_ctl->for_data_reloc) 4675 btrfs_clear_data_reloc_bg(block_group); 4676 continue; 4677 } 4678 4679 btrfs_grab_block_group(block_group, ffe_ctl->delalloc); 4680 ffe_ctl->search_start = block_group->start; 4681 4682 /* 4683 * this can happen if we end up cycling through all the 4684 * raid types, but we want to make sure we only allocate 4685 * for the proper type. 4686 */ 4687 if (!block_group_bits(block_group, ffe_ctl->flags)) { 4688 u64 extra = BTRFS_BLOCK_GROUP_DUP | 4689 BTRFS_BLOCK_GROUP_RAID1_MASK | 4690 BTRFS_BLOCK_GROUP_RAID56_MASK | 4691 BTRFS_BLOCK_GROUP_RAID10; 4692 4693 /* 4694 * if they asked for extra copies and this block group 4695 * doesn't provide them, bail. This does allow us to 4696 * fill raid0 from raid1. 4697 */ 4698 if ((ffe_ctl->flags & extra) && !(block_group->flags & extra)) 4699 goto loop; 4700 4701 /* 4702 * This block group has different flags than we want. 4703 * It's possible that we have MIXED_GROUP flag but no 4704 * block group is mixed. Just skip such block group. 4705 */ 4706 btrfs_release_block_group(block_group, ffe_ctl->delalloc); 4707 continue; 4708 } 4709 4710 have_block_group: 4711 trace_btrfs_find_free_extent_have_block_group(root, ffe_ctl, block_group); 4712 ffe_ctl->cached = btrfs_block_group_done(block_group); 4713 if (unlikely(!ffe_ctl->cached)) { 4714 ffe_ctl->have_caching_bg = true; 4715 ret = btrfs_cache_block_group(block_group, false); 4716 4717 /* 4718 * If we get ENOMEM here or something else we want to 4719 * try other block groups, because it may not be fatal. 4720 * However if we can't find anything else we need to 4721 * save our return here so that we return the actual 4722 * error that caused problems, not ENOSPC. 4723 */ 4724 if (ret < 0) { 4725 if (!cache_block_group_error) 4726 cache_block_group_error = ret; 4727 ret = 0; 4728 goto loop; 4729 } 4730 ret = 0; 4731 } 4732 4733 if (unlikely(block_group->cached == BTRFS_CACHE_ERROR)) { 4734 if (!cache_block_group_error) 4735 cache_block_group_error = -EIO; 4736 goto loop; 4737 } 4738 4739 if (!find_free_extent_check_size_class(ffe_ctl, block_group)) 4740 goto loop; 4741 4742 bg_ret = NULL; 4743 ret = do_allocation(block_group, ffe_ctl, &bg_ret); 4744 if (ret > 0) 4745 goto loop; 4746 4747 if (bg_ret && bg_ret != block_group) { 4748 btrfs_release_block_group(block_group, ffe_ctl->delalloc); 4749 block_group = bg_ret; 4750 } 4751 4752 /* Checks */ 4753 ffe_ctl->search_start = round_up(ffe_ctl->found_offset, 4754 fs_info->stripesize); 4755 4756 /* move on to the next group */ 4757 if (ffe_ctl->search_start + ffe_ctl->num_bytes > 4758 btrfs_block_group_end(block_group)) { 4759 btrfs_add_free_space_unused(block_group, 4760 ffe_ctl->found_offset, 4761 ffe_ctl->num_bytes); 4762 goto loop; 4763 } 4764 4765 if (ffe_ctl->found_offset < ffe_ctl->search_start) 4766 btrfs_add_free_space_unused(block_group, 4767 ffe_ctl->found_offset, 4768 ffe_ctl->search_start - ffe_ctl->found_offset); 4769 4770 ret = btrfs_add_reserved_bytes(block_group, ffe_ctl->ram_bytes, 4771 ffe_ctl->num_bytes, 4772 ffe_ctl->delalloc, 4773 ffe_ctl->loop >= LOOP_WRONG_SIZE_CLASS); 4774 if (ret == -EAGAIN) { 4775 btrfs_add_free_space_unused(block_group, 4776 ffe_ctl->found_offset, 4777 ffe_ctl->num_bytes); 4778 goto loop; 4779 } 4780 btrfs_inc_block_group_reservations(block_group); 4781 4782 /* we are all good, lets return */ 4783 ins->objectid = ffe_ctl->search_start; 4784 ins->offset = ffe_ctl->num_bytes; 4785 4786 trace_btrfs_reserve_extent(block_group, ffe_ctl); 4787 btrfs_release_block_group(block_group, ffe_ctl->delalloc); 4788 break; 4789 loop: 4790 if (!ffe_ctl->cached && ffe_ctl->loop > LOOP_CACHING_NOWAIT && 4791 !ffe_ctl->retry_uncached) { 4792 ffe_ctl->retry_uncached = true; 4793 btrfs_wait_block_group_cache_progress(block_group, 4794 ffe_ctl->num_bytes + 4795 ffe_ctl->empty_cluster + 4796 ffe_ctl->empty_size); 4797 goto have_block_group; 4798 } 4799 release_block_group(block_group, ffe_ctl, ffe_ctl->delalloc); 4800 cond_resched(); 4801 } 4802 up_read(&space_info->groups_sem); 4803 4804 ret = find_free_extent_update_loop(fs_info, ins, ffe_ctl, space_info, 4805 full_search); 4806 if (ret > 0) 4807 goto search; 4808 4809 if (ret == -ENOSPC && !cache_block_group_error) { 4810 /* 4811 * Use ffe_ctl->total_free_space as fallback if we can't find 4812 * any contiguous hole. 4813 */ 4814 if (!ffe_ctl->max_extent_size) 4815 ffe_ctl->max_extent_size = ffe_ctl->total_free_space; 4816 spin_lock(&space_info->lock); 4817 space_info->max_extent_size = ffe_ctl->max_extent_size; 4818 spin_unlock(&space_info->lock); 4819 ins->offset = ffe_ctl->max_extent_size; 4820 } else if (ret == -ENOSPC) { 4821 ret = cache_block_group_error; 4822 } 4823 return ret; 4824 } 4825 4826 /* 4827 * Entry point to the extent allocator. Tries to find a hole that is at least 4828 * as big as @num_bytes. 4829 * 4830 * @root - The root that will contain this extent 4831 * 4832 * @ram_bytes - The amount of space in ram that @num_bytes take. This 4833 * is used for accounting purposes. This value differs 4834 * from @num_bytes only in the case of compressed extents. 4835 * 4836 * @num_bytes - Number of bytes to allocate on-disk. 4837 * 4838 * @min_alloc_size - Indicates the minimum amount of space that the 4839 * allocator should try to satisfy. In some cases 4840 * @num_bytes may be larger than what is required and if 4841 * the filesystem is fragmented then allocation fails. 4842 * However, the presence of @min_alloc_size gives a 4843 * chance to try and satisfy the smaller allocation. 4844 * 4845 * @empty_size - A hint that you plan on doing more COW. This is the 4846 * size in bytes the allocator should try to find free 4847 * next to the block it returns. This is just a hint and 4848 * may be ignored by the allocator. 4849 * 4850 * @hint_byte - Hint to the allocator to start searching above the byte 4851 * address passed. It might be ignored. 4852 * 4853 * @ins - This key is modified to record the found hole. It will 4854 * have the following values: 4855 * ins->objectid == start position 4856 * ins->flags = BTRFS_EXTENT_ITEM_KEY 4857 * ins->offset == the size of the hole. 4858 * 4859 * @is_data - Boolean flag indicating whether an extent is 4860 * allocated for data (true) or metadata (false) 4861 * 4862 * @delalloc - Boolean flag indicating whether this allocation is for 4863 * delalloc or not. If 'true' data_rwsem of block groups 4864 * is going to be acquired. 4865 * 4866 * 4867 * Returns 0 when an allocation succeeded or < 0 when an error occurred. In 4868 * case -ENOSPC is returned then @ins->offset will contain the size of the 4869 * largest available hole the allocator managed to find. 4870 */ 4871 int btrfs_reserve_extent(struct btrfs_root *root, u64 ram_bytes, 4872 u64 num_bytes, u64 min_alloc_size, 4873 u64 empty_size, u64 hint_byte, 4874 struct btrfs_key *ins, bool is_data, bool delalloc) 4875 { 4876 struct btrfs_fs_info *fs_info = root->fs_info; 4877 struct find_free_extent_ctl ffe_ctl = {}; 4878 bool final_tried = num_bytes == min_alloc_size; 4879 u64 flags; 4880 int ret; 4881 bool for_treelog = (btrfs_root_id(root) == BTRFS_TREE_LOG_OBJECTID); 4882 bool for_data_reloc = (btrfs_is_data_reloc_root(root) && is_data); 4883 4884 flags = get_alloc_profile_by_root(root, is_data); 4885 again: 4886 WARN_ON(num_bytes < fs_info->sectorsize); 4887 4888 ffe_ctl.ram_bytes = ram_bytes; 4889 ffe_ctl.num_bytes = num_bytes; 4890 ffe_ctl.min_alloc_size = min_alloc_size; 4891 ffe_ctl.empty_size = empty_size; 4892 ffe_ctl.flags = flags; 4893 ffe_ctl.delalloc = delalloc; 4894 ffe_ctl.hint_byte = hint_byte; 4895 ffe_ctl.for_treelog = for_treelog; 4896 ffe_ctl.for_data_reloc = for_data_reloc; 4897 4898 ret = find_free_extent(root, ins, &ffe_ctl); 4899 if (!ret && !is_data) { 4900 btrfs_dec_block_group_reservations(fs_info, ins->objectid); 4901 } else if (ret == -ENOSPC) { 4902 if (!final_tried && ins->offset) { 4903 num_bytes = min(num_bytes >> 1, ins->offset); 4904 num_bytes = round_down(num_bytes, 4905 fs_info->sectorsize); 4906 num_bytes = max(num_bytes, min_alloc_size); 4907 ram_bytes = num_bytes; 4908 if (num_bytes == min_alloc_size) 4909 final_tried = true; 4910 goto again; 4911 } else if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) { 4912 struct btrfs_space_info *sinfo; 4913 4914 sinfo = btrfs_find_space_info(fs_info, flags); 4915 btrfs_err(fs_info, 4916 "allocation failed flags %llu, wanted %llu tree-log %d, relocation: %d", 4917 flags, num_bytes, for_treelog, for_data_reloc); 4918 if (sinfo) 4919 btrfs_dump_space_info(sinfo, num_bytes, 1); 4920 } 4921 } 4922 4923 return ret; 4924 } 4925 4926 int btrfs_free_reserved_extent(struct btrfs_fs_info *fs_info, u64 start, u64 len, 4927 bool is_delalloc) 4928 { 4929 struct btrfs_block_group *cache; 4930 4931 cache = btrfs_lookup_block_group(fs_info, start); 4932 if (!cache) { 4933 btrfs_err(fs_info, "Unable to find block group for %llu", 4934 start); 4935 return -ENOSPC; 4936 } 4937 4938 btrfs_add_free_space(cache, start, len); 4939 btrfs_free_reserved_bytes(cache, len, is_delalloc); 4940 trace_btrfs_reserved_extent_free(fs_info, start, len); 4941 4942 btrfs_put_block_group(cache); 4943 return 0; 4944 } 4945 4946 int btrfs_pin_reserved_extent(struct btrfs_trans_handle *trans, 4947 const struct extent_buffer *eb) 4948 { 4949 struct btrfs_block_group *cache; 4950 int ret = 0; 4951 4952 cache = btrfs_lookup_block_group(trans->fs_info, eb->start); 4953 if (!cache) { 4954 btrfs_err(trans->fs_info, "unable to find block group for %llu", 4955 eb->start); 4956 return -ENOSPC; 4957 } 4958 4959 ret = pin_down_extent(trans, cache, eb->start, eb->len, true); 4960 btrfs_put_block_group(cache); 4961 return ret; 4962 } 4963 4964 static int alloc_reserved_extent(struct btrfs_trans_handle *trans, u64 bytenr, 4965 u64 num_bytes) 4966 { 4967 struct btrfs_fs_info *fs_info = trans->fs_info; 4968 int ret; 4969 4970 ret = btrfs_remove_from_free_space_tree(trans, bytenr, num_bytes); 4971 if (ret) 4972 return ret; 4973 4974 ret = btrfs_update_block_group(trans, bytenr, num_bytes, true); 4975 if (ret) { 4976 ASSERT(!ret); 4977 btrfs_err(fs_info, "update block group failed for %llu %llu", 4978 bytenr, num_bytes); 4979 return ret; 4980 } 4981 4982 trace_btrfs_reserved_extent_alloc(fs_info, bytenr, num_bytes); 4983 return 0; 4984 } 4985 4986 static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans, 4987 u64 parent, u64 root_objectid, 4988 u64 flags, u64 owner, u64 offset, 4989 struct btrfs_key *ins, int ref_mod, u64 oref_root) 4990 { 4991 struct btrfs_fs_info *fs_info = trans->fs_info; 4992 struct btrfs_root *extent_root; 4993 int ret; 4994 struct btrfs_extent_item *extent_item; 4995 struct btrfs_extent_owner_ref *oref; 4996 struct btrfs_extent_inline_ref *iref; 4997 struct btrfs_path *path; 4998 struct extent_buffer *leaf; 4999 int type; 5000 u32 size; 5001 const bool simple_quota = (btrfs_qgroup_mode(fs_info) == BTRFS_QGROUP_MODE_SIMPLE); 5002 5003 if (parent > 0) 5004 type = BTRFS_SHARED_DATA_REF_KEY; 5005 else 5006 type = BTRFS_EXTENT_DATA_REF_KEY; 5007 5008 size = sizeof(*extent_item); 5009 if (simple_quota) 5010 size += btrfs_extent_inline_ref_size(BTRFS_EXTENT_OWNER_REF_KEY); 5011 size += btrfs_extent_inline_ref_size(type); 5012 5013 extent_root = btrfs_extent_root(fs_info, ins->objectid); 5014 if (unlikely(!extent_root)) { 5015 btrfs_err(fs_info, 5016 "missing extent root for extent at bytenr %llu", 5017 ins->objectid); 5018 return -EUCLEAN; 5019 } 5020 5021 path = btrfs_alloc_path(); 5022 if (!path) 5023 return -ENOMEM; 5024 5025 ret = btrfs_insert_empty_item(trans, extent_root, path, ins, size); 5026 if (ret) { 5027 btrfs_free_path(path); 5028 return ret; 5029 } 5030 5031 leaf = path->nodes[0]; 5032 extent_item = btrfs_item_ptr(leaf, path->slots[0], 5033 struct btrfs_extent_item); 5034 btrfs_set_extent_refs(leaf, extent_item, ref_mod); 5035 btrfs_set_extent_generation(leaf, extent_item, trans->transid); 5036 btrfs_set_extent_flags(leaf, extent_item, 5037 flags | BTRFS_EXTENT_FLAG_DATA); 5038 5039 iref = (struct btrfs_extent_inline_ref *)(extent_item + 1); 5040 if (simple_quota) { 5041 btrfs_set_extent_inline_ref_type(leaf, iref, BTRFS_EXTENT_OWNER_REF_KEY); 5042 oref = (struct btrfs_extent_owner_ref *)(&iref->offset); 5043 btrfs_set_extent_owner_ref_root_id(leaf, oref, oref_root); 5044 iref = (struct btrfs_extent_inline_ref *)(oref + 1); 5045 } 5046 btrfs_set_extent_inline_ref_type(leaf, iref, type); 5047 5048 if (parent > 0) { 5049 struct btrfs_shared_data_ref *ref; 5050 ref = (struct btrfs_shared_data_ref *)(iref + 1); 5051 btrfs_set_extent_inline_ref_offset(leaf, iref, parent); 5052 btrfs_set_shared_data_ref_count(leaf, ref, ref_mod); 5053 } else { 5054 struct btrfs_extent_data_ref *ref; 5055 ref = (struct btrfs_extent_data_ref *)(&iref->offset); 5056 btrfs_set_extent_data_ref_root(leaf, ref, root_objectid); 5057 btrfs_set_extent_data_ref_objectid(leaf, ref, owner); 5058 btrfs_set_extent_data_ref_offset(leaf, ref, offset); 5059 btrfs_set_extent_data_ref_count(leaf, ref, ref_mod); 5060 } 5061 5062 btrfs_free_path(path); 5063 5064 return alloc_reserved_extent(trans, ins->objectid, ins->offset); 5065 } 5066 5067 static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans, 5068 const struct btrfs_delayed_ref_node *node, 5069 struct btrfs_delayed_extent_op *extent_op) 5070 { 5071 struct btrfs_fs_info *fs_info = trans->fs_info; 5072 struct btrfs_root *extent_root; 5073 int ret; 5074 struct btrfs_extent_item *extent_item; 5075 struct btrfs_key extent_key; 5076 struct btrfs_tree_block_info *block_info; 5077 struct btrfs_extent_inline_ref *iref; 5078 struct btrfs_path *path; 5079 struct extent_buffer *leaf; 5080 u32 size = sizeof(*extent_item) + sizeof(*iref); 5081 const u64 flags = (extent_op ? extent_op->flags_to_set : 0); 5082 /* The owner of a tree block is the level. */ 5083 int level = btrfs_delayed_ref_owner(node); 5084 bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA); 5085 5086 if (unlikely(node->ref_root == BTRFS_REMAP_TREE_OBJECTID)) 5087 goto skip; 5088 5089 extent_key.objectid = node->bytenr; 5090 if (skinny_metadata) { 5091 /* The owner of a tree block is the level. */ 5092 extent_key.offset = level; 5093 extent_key.type = BTRFS_METADATA_ITEM_KEY; 5094 } else { 5095 extent_key.offset = node->num_bytes; 5096 extent_key.type = BTRFS_EXTENT_ITEM_KEY; 5097 size += sizeof(*block_info); 5098 } 5099 5100 extent_root = btrfs_extent_root(fs_info, extent_key.objectid); 5101 if (unlikely(!extent_root)) { 5102 btrfs_err(fs_info, 5103 "missing extent root for extent at bytenr %llu", 5104 extent_key.objectid); 5105 return -EUCLEAN; 5106 } 5107 5108 path = btrfs_alloc_path(); 5109 if (!path) 5110 return -ENOMEM; 5111 5112 ret = btrfs_insert_empty_item(trans, extent_root, path, &extent_key, 5113 size); 5114 if (ret) { 5115 btrfs_free_path(path); 5116 return ret; 5117 } 5118 5119 leaf = path->nodes[0]; 5120 extent_item = btrfs_item_ptr(leaf, path->slots[0], 5121 struct btrfs_extent_item); 5122 btrfs_set_extent_refs(leaf, extent_item, 1); 5123 btrfs_set_extent_generation(leaf, extent_item, trans->transid); 5124 btrfs_set_extent_flags(leaf, extent_item, 5125 flags | BTRFS_EXTENT_FLAG_TREE_BLOCK); 5126 5127 if (skinny_metadata) { 5128 iref = (struct btrfs_extent_inline_ref *)(extent_item + 1); 5129 } else { 5130 block_info = (struct btrfs_tree_block_info *)(extent_item + 1); 5131 btrfs_set_tree_block_key(leaf, block_info, &extent_op->key); 5132 btrfs_set_tree_block_level(leaf, block_info, level); 5133 iref = (struct btrfs_extent_inline_ref *)(block_info + 1); 5134 } 5135 5136 if (node->type == BTRFS_SHARED_BLOCK_REF_KEY) { 5137 btrfs_set_extent_inline_ref_type(leaf, iref, 5138 BTRFS_SHARED_BLOCK_REF_KEY); 5139 btrfs_set_extent_inline_ref_offset(leaf, iref, node->parent); 5140 } else { 5141 btrfs_set_extent_inline_ref_type(leaf, iref, 5142 BTRFS_TREE_BLOCK_REF_KEY); 5143 btrfs_set_extent_inline_ref_offset(leaf, iref, node->ref_root); 5144 } 5145 5146 btrfs_free_path(path); 5147 5148 skip: 5149 return alloc_reserved_extent(trans, node->bytenr, fs_info->nodesize); 5150 } 5151 5152 int btrfs_alloc_reserved_file_extent(struct btrfs_trans_handle *trans, 5153 struct btrfs_root *root, u64 owner, 5154 u64 offset, u64 ram_bytes, 5155 struct btrfs_key *ins) 5156 { 5157 struct btrfs_ref generic_ref = { 5158 .action = BTRFS_ADD_DELAYED_EXTENT, 5159 .bytenr = ins->objectid, 5160 .num_bytes = ins->offset, 5161 .owning_root = btrfs_root_id(root), 5162 .ref_root = btrfs_root_id(root), 5163 }; 5164 5165 ASSERT(generic_ref.ref_root != BTRFS_TREE_LOG_OBJECTID); 5166 5167 if (btrfs_is_data_reloc_root(root) && btrfs_is_fstree(root->relocation_src_root)) 5168 generic_ref.owning_root = root->relocation_src_root; 5169 5170 btrfs_init_data_ref(&generic_ref, owner, offset, 0, false); 5171 btrfs_ref_tree_mod(root->fs_info, &generic_ref); 5172 5173 return btrfs_add_delayed_data_ref(trans, &generic_ref, ram_bytes); 5174 } 5175 5176 /* 5177 * this is used by the tree logging recovery code. It records that 5178 * an extent has been allocated and makes sure to clear the free 5179 * space cache bits as well 5180 */ 5181 int btrfs_alloc_logged_file_extent(struct btrfs_trans_handle *trans, 5182 u64 root_objectid, u64 owner, u64 offset, 5183 struct btrfs_key *ins) 5184 { 5185 struct btrfs_fs_info *fs_info = trans->fs_info; 5186 int ret; 5187 struct btrfs_block_group *block_group; 5188 struct btrfs_space_info *space_info; 5189 const struct btrfs_squota_delta delta = { 5190 .root = root_objectid, 5191 .num_bytes = ins->offset, 5192 .generation = trans->transid, 5193 .is_data = true, 5194 .is_inc = true, 5195 }; 5196 5197 /* 5198 * Mixed block groups will exclude before processing the log so we only 5199 * need to do the exclude dance if this fs isn't mixed. 5200 */ 5201 if (!btrfs_fs_incompat(fs_info, MIXED_GROUPS)) { 5202 ret = __exclude_logged_extent(fs_info, ins->objectid, 5203 ins->offset); 5204 if (ret) 5205 return ret; 5206 } 5207 5208 block_group = btrfs_lookup_block_group(fs_info, ins->objectid); 5209 if (!block_group) 5210 return -EINVAL; 5211 5212 space_info = block_group->space_info; 5213 spin_lock(&space_info->lock); 5214 spin_lock(&block_group->lock); 5215 space_info->bytes_reserved += ins->offset; 5216 block_group->reserved += ins->offset; 5217 spin_unlock(&block_group->lock); 5218 spin_unlock(&space_info->lock); 5219 5220 ret = alloc_reserved_file_extent(trans, 0, root_objectid, 0, owner, 5221 offset, ins, 1, root_objectid); 5222 if (ret) 5223 btrfs_pin_extent(trans, ins->objectid, ins->offset); 5224 ret = btrfs_record_squota_delta(fs_info, &delta); 5225 btrfs_put_block_group(block_group); 5226 return ret; 5227 } 5228 5229 #ifdef CONFIG_BTRFS_DEBUG 5230 /* 5231 * Extra safety check in case the extent tree is corrupted and extent allocator 5232 * chooses to use a tree block which is already used and locked. 5233 */ 5234 static bool check_eb_lock_owner(const struct extent_buffer *eb) 5235 { 5236 if (eb->lock_owner == current->pid) { 5237 btrfs_err_rl(eb->fs_info, 5238 "tree block %llu owner %llu already locked by pid=%d, extent tree corruption detected", 5239 eb->start, btrfs_header_owner(eb), current->pid); 5240 return true; 5241 } 5242 return false; 5243 } 5244 #else 5245 static bool check_eb_lock_owner(struct extent_buffer *eb) 5246 { 5247 return false; 5248 } 5249 #endif 5250 5251 static struct extent_buffer * 5252 btrfs_init_new_buffer(struct btrfs_trans_handle *trans, struct btrfs_root *root, 5253 u64 bytenr, int level, u64 owner, 5254 enum btrfs_lock_nesting nest) 5255 { 5256 struct btrfs_fs_info *fs_info = root->fs_info; 5257 struct extent_buffer *buf; 5258 u64 lockdep_owner = owner; 5259 5260 buf = btrfs_find_create_tree_block(fs_info, bytenr, owner, level); 5261 if (IS_ERR(buf)) 5262 return buf; 5263 5264 if (unlikely(check_eb_lock_owner(buf))) { 5265 free_extent_buffer(buf); 5266 return ERR_PTR(-EUCLEAN); 5267 } 5268 5269 /* 5270 * The reloc trees are just snapshots, so we need them to appear to be 5271 * just like any other fs tree WRT lockdep. 5272 * 5273 * The exception however is in replace_path() in relocation, where we 5274 * hold the lock on the original fs root and then search for the reloc 5275 * root. At that point we need to make sure any reloc root buffers are 5276 * set to the BTRFS_TREE_RELOC_OBJECTID lockdep class in order to make 5277 * lockdep happy. 5278 */ 5279 if (lockdep_owner == BTRFS_TREE_RELOC_OBJECTID && 5280 !test_bit(BTRFS_ROOT_RESET_LOCKDEP_CLASS, &root->state)) 5281 lockdep_owner = BTRFS_FS_TREE_OBJECTID; 5282 5283 /* btrfs_clear_buffer_dirty() accesses generation field. */ 5284 btrfs_set_header_generation(buf, trans->transid); 5285 5286 /* 5287 * This needs to stay, because we could allocate a freed block from an 5288 * old tree into a new tree, so we need to make sure this new block is 5289 * set to the appropriate level and owner. 5290 */ 5291 btrfs_set_buffer_lockdep_class(lockdep_owner, buf, level); 5292 5293 btrfs_tree_lock_nested(buf, nest); 5294 btrfs_clear_buffer_dirty(trans, buf); 5295 clear_bit(EXTENT_BUFFER_STALE, &buf->bflags); 5296 clear_bit(EXTENT_BUFFER_ZONED_ZEROOUT, &buf->bflags); 5297 5298 set_extent_buffer_uptodate(buf); 5299 5300 memzero_extent_buffer(buf, 0, sizeof(struct btrfs_header)); 5301 btrfs_set_header_level(buf, level); 5302 btrfs_set_header_bytenr(buf, buf->start); 5303 btrfs_set_header_generation(buf, trans->transid); 5304 btrfs_set_header_backref_rev(buf, BTRFS_MIXED_BACKREF_REV); 5305 btrfs_set_header_owner(buf, owner); 5306 write_extent_buffer_fsid(buf, fs_info->fs_devices->metadata_uuid); 5307 write_extent_buffer_chunk_tree_uuid(buf, fs_info->chunk_tree_uuid); 5308 if (btrfs_root_id(root) == BTRFS_TREE_LOG_OBJECTID) { 5309 buf->log_index = root->log_transid % 2; 5310 /* 5311 * we allow two log transactions at a time, use different 5312 * EXTENT bit to differentiate dirty pages. 5313 */ 5314 if (buf->log_index == 0) 5315 btrfs_set_extent_bit(&root->dirty_log_pages, buf->start, 5316 buf->start + buf->len - 1, 5317 EXTENT_DIRTY_LOG1, NULL); 5318 else 5319 btrfs_set_extent_bit(&root->dirty_log_pages, buf->start, 5320 buf->start + buf->len - 1, 5321 EXTENT_DIRTY_LOG2, NULL); 5322 } else { 5323 buf->log_index = -1; 5324 btrfs_set_extent_bit(&trans->transaction->dirty_pages, buf->start, 5325 buf->start + buf->len - 1, EXTENT_DIRTY, NULL); 5326 } 5327 /* this returns a buffer locked for blocking */ 5328 return buf; 5329 } 5330 5331 /* 5332 * finds a free extent and does all the dirty work required for allocation 5333 * returns the tree buffer or an ERR_PTR on error. 5334 */ 5335 struct extent_buffer *btrfs_alloc_tree_block(struct btrfs_trans_handle *trans, 5336 struct btrfs_root *root, 5337 u64 parent, u64 root_objectid, 5338 const struct btrfs_disk_key *key, 5339 int level, u64 hint, 5340 u64 empty_size, 5341 u64 reloc_src_root, 5342 enum btrfs_lock_nesting nest) 5343 { 5344 struct btrfs_fs_info *fs_info = root->fs_info; 5345 struct btrfs_key ins; 5346 struct btrfs_block_rsv *block_rsv; 5347 struct extent_buffer *buf; 5348 u64 flags = 0; 5349 int ret; 5350 u32 blocksize = fs_info->nodesize; 5351 bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA); 5352 u64 owning_root; 5353 5354 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS 5355 if (btrfs_is_testing(fs_info)) { 5356 buf = btrfs_init_new_buffer(trans, root, root->alloc_bytenr, 5357 level, root_objectid, nest); 5358 if (!IS_ERR(buf)) 5359 root->alloc_bytenr += blocksize; 5360 return buf; 5361 } 5362 #endif 5363 5364 block_rsv = btrfs_use_block_rsv(trans, root, blocksize); 5365 if (IS_ERR(block_rsv)) 5366 return ERR_CAST(block_rsv); 5367 5368 ret = btrfs_reserve_extent(root, blocksize, blocksize, blocksize, 5369 empty_size, hint, &ins, false, false); 5370 if (ret) 5371 goto out_unuse; 5372 5373 buf = btrfs_init_new_buffer(trans, root, ins.objectid, level, 5374 root_objectid, nest); 5375 if (IS_ERR(buf)) { 5376 ret = PTR_ERR(buf); 5377 goto out_free_reserved; 5378 } 5379 owning_root = btrfs_header_owner(buf); 5380 5381 if (root_objectid == BTRFS_TREE_RELOC_OBJECTID) { 5382 if (parent == 0) 5383 parent = ins.objectid; 5384 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF; 5385 owning_root = reloc_src_root; 5386 } else 5387 BUG_ON(parent > 0); 5388 5389 if (root_objectid != BTRFS_TREE_LOG_OBJECTID) { 5390 struct btrfs_delayed_extent_op *extent_op; 5391 struct btrfs_ref generic_ref = { 5392 .action = BTRFS_ADD_DELAYED_EXTENT, 5393 .bytenr = ins.objectid, 5394 .num_bytes = ins.offset, 5395 .parent = parent, 5396 .owning_root = owning_root, 5397 .ref_root = root_objectid, 5398 }; 5399 5400 if (!skinny_metadata || flags != 0) { 5401 extent_op = btrfs_alloc_delayed_extent_op(); 5402 if (!extent_op) { 5403 ret = -ENOMEM; 5404 goto out_free_buf; 5405 } 5406 if (key) 5407 memcpy(&extent_op->key, key, sizeof(extent_op->key)); 5408 else 5409 memset(&extent_op->key, 0, sizeof(extent_op->key)); 5410 extent_op->flags_to_set = flags; 5411 extent_op->update_key = (skinny_metadata ? false : true); 5412 extent_op->update_flags = (flags != 0); 5413 } else { 5414 extent_op = NULL; 5415 } 5416 5417 btrfs_init_tree_ref(&generic_ref, level, btrfs_root_id(root), false); 5418 btrfs_ref_tree_mod(fs_info, &generic_ref); 5419 ret = btrfs_add_delayed_tree_ref(trans, &generic_ref, extent_op); 5420 if (ret) { 5421 btrfs_free_delayed_extent_op(extent_op); 5422 goto out_free_buf; 5423 } 5424 } 5425 return buf; 5426 5427 out_free_buf: 5428 btrfs_tree_unlock(buf); 5429 free_extent_buffer(buf); 5430 out_free_reserved: 5431 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, false); 5432 out_unuse: 5433 btrfs_unuse_block_rsv(fs_info, block_rsv, blocksize); 5434 return ERR_PTR(ret); 5435 } 5436 5437 struct walk_control { 5438 u64 refs[BTRFS_MAX_LEVEL]; 5439 u64 flags[BTRFS_MAX_LEVEL]; 5440 struct btrfs_key update_progress; 5441 struct btrfs_key drop_progress; 5442 int drop_level; 5443 int stage; 5444 int level; 5445 int shared_level; 5446 int update_ref; 5447 int keep_locks; 5448 int reada_slot; 5449 int reada_count; 5450 int restarted; 5451 /* Indicate that extent info needs to be looked up when walking the tree. */ 5452 int lookup_info; 5453 }; 5454 5455 /* 5456 * This is our normal stage. We are traversing blocks the current snapshot owns 5457 * and we are dropping any of our references to any children we are able to, and 5458 * then freeing the block once we've processed all of the children. 5459 */ 5460 #define DROP_REFERENCE 1 5461 5462 /* 5463 * We enter this stage when we have to walk into a child block (meaning we can't 5464 * simply drop our reference to it from our current parent node) and there are 5465 * more than one reference on it. If we are the owner of any of the children 5466 * blocks from the current parent node then we have to do the FULL_BACKREF dance 5467 * on them in order to drop our normal ref and add the shared ref. 5468 */ 5469 #define UPDATE_BACKREF 2 5470 5471 /* 5472 * Decide if we need to walk down into this node to adjust the references. 5473 * 5474 * @root: the root we are currently deleting 5475 * @wc: the walk control for this deletion 5476 * @eb: the parent eb that we're currently visiting 5477 * @flags: the flags for wc->level - 1 5478 * @slot: the slot in the eb that we're currently checking 5479 * 5480 * This is meant to be called when we're evaluating if a node we point to at 5481 * wc->level should be read and walked into, or if we can simply delete our 5482 * reference to it. We return true if we should walk into the node, false if we 5483 * can skip it. 5484 * 5485 * We have assertions in here to make sure this is called correctly. We assume 5486 * that sanity checking on the blocks read to this point has been done, so any 5487 * corrupted file systems must have been caught before calling this function. 5488 */ 5489 static bool visit_node_for_delete(struct btrfs_root *root, struct walk_control *wc, 5490 struct extent_buffer *eb, u64 flags, int slot) 5491 { 5492 struct btrfs_key key; 5493 u64 generation; 5494 int level = wc->level; 5495 5496 ASSERT(level > 0); 5497 ASSERT(wc->refs[level - 1] > 0); 5498 5499 /* 5500 * The update backref stage we only want to skip if we already have 5501 * FULL_BACKREF set, otherwise we need to read. 5502 */ 5503 if (wc->stage == UPDATE_BACKREF) { 5504 if (level == 1 && flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) 5505 return false; 5506 return true; 5507 } 5508 5509 /* 5510 * We're the last ref on this block, we must walk into it and process 5511 * any refs it's pointing at. 5512 */ 5513 if (wc->refs[level - 1] == 1) 5514 return true; 5515 5516 /* 5517 * If we're already FULL_BACKREF then we know we can just drop our 5518 * current reference. 5519 */ 5520 if (level == 1 && flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) 5521 return false; 5522 5523 /* 5524 * This block is older than our creation generation, we can drop our 5525 * reference to it. 5526 */ 5527 generation = btrfs_node_ptr_generation(eb, slot); 5528 if (!wc->update_ref || generation <= btrfs_root_origin_generation(root)) 5529 return false; 5530 5531 /* 5532 * This block was processed from a previous snapshot deletion run, we 5533 * can skip it. 5534 */ 5535 btrfs_node_key_to_cpu(eb, &key, slot); 5536 if (btrfs_comp_cpu_keys(&key, &wc->update_progress) < 0) 5537 return false; 5538 5539 /* All other cases we need to wander into the node. */ 5540 return true; 5541 } 5542 5543 static noinline void reada_walk_down(struct btrfs_trans_handle *trans, 5544 struct btrfs_root *root, 5545 struct walk_control *wc, 5546 struct btrfs_path *path) 5547 { 5548 struct btrfs_fs_info *fs_info = root->fs_info; 5549 u64 bytenr; 5550 u64 generation; 5551 u64 refs; 5552 u64 flags; 5553 u32 nritems; 5554 struct extent_buffer *eb; 5555 int ret; 5556 int slot; 5557 int nread = 0; 5558 5559 if (path->slots[wc->level] < wc->reada_slot) { 5560 wc->reada_count = wc->reada_count * 2 / 3; 5561 wc->reada_count = max(wc->reada_count, 2); 5562 } else { 5563 wc->reada_count = wc->reada_count * 3 / 2; 5564 wc->reada_count = min_t(int, wc->reada_count, 5565 BTRFS_NODEPTRS_PER_BLOCK(fs_info)); 5566 } 5567 5568 eb = path->nodes[wc->level]; 5569 nritems = btrfs_header_nritems(eb); 5570 5571 for (slot = path->slots[wc->level]; slot < nritems; slot++) { 5572 if (nread >= wc->reada_count) 5573 break; 5574 5575 cond_resched(); 5576 bytenr = btrfs_node_blockptr(eb, slot); 5577 generation = btrfs_node_ptr_generation(eb, slot); 5578 5579 if (slot == path->slots[wc->level]) 5580 goto reada; 5581 5582 if (wc->stage == UPDATE_BACKREF && 5583 generation <= btrfs_root_origin_generation(root)) 5584 continue; 5585 5586 /* We don't lock the tree block, it's OK to be racy here */ 5587 ret = btrfs_lookup_extent_info(trans, fs_info, bytenr, 5588 wc->level - 1, 1, &refs, 5589 &flags, NULL); 5590 /* We don't care about errors in readahead. */ 5591 if (ret < 0) 5592 continue; 5593 5594 /* 5595 * This could be racey, it's conceivable that we raced and end 5596 * up with a bogus refs count, if that's the case just skip, if 5597 * we are actually corrupt we will notice when we look up 5598 * everything again with our locks. 5599 */ 5600 if (refs == 0) 5601 continue; 5602 5603 /* If we don't need to visit this node don't reada. */ 5604 if (!visit_node_for_delete(root, wc, eb, flags, slot)) 5605 continue; 5606 reada: 5607 btrfs_readahead_node_child(eb, slot); 5608 nread++; 5609 } 5610 wc->reada_slot = slot; 5611 } 5612 5613 /* 5614 * helper to process tree block while walking down the tree. 5615 * 5616 * when wc->stage == UPDATE_BACKREF, this function updates 5617 * back refs for pointers in the block. 5618 * 5619 * NOTE: return value 1 means we should stop walking down. 5620 */ 5621 static noinline int walk_down_proc(struct btrfs_trans_handle *trans, 5622 struct btrfs_root *root, 5623 struct btrfs_path *path, 5624 struct walk_control *wc) 5625 { 5626 struct btrfs_fs_info *fs_info = root->fs_info; 5627 int level = wc->level; 5628 struct extent_buffer *eb = path->nodes[level]; 5629 u64 flag = BTRFS_BLOCK_FLAG_FULL_BACKREF; 5630 int ret; 5631 5632 if (wc->stage == UPDATE_BACKREF && btrfs_header_owner(eb) != btrfs_root_id(root)) 5633 return 1; 5634 5635 /* 5636 * when reference count of tree block is 1, it won't increase 5637 * again. once full backref flag is set, we never clear it. 5638 */ 5639 if (wc->lookup_info && 5640 ((wc->stage == DROP_REFERENCE && wc->refs[level] != 1) || 5641 (wc->stage == UPDATE_BACKREF && !(wc->flags[level] & flag)))) { 5642 ASSERT(path->locks[level]); 5643 ret = btrfs_lookup_extent_info(trans, fs_info, 5644 eb->start, level, 1, 5645 &wc->refs[level], 5646 &wc->flags[level], 5647 NULL); 5648 if (ret) 5649 return ret; 5650 if (unlikely(wc->refs[level] == 0)) { 5651 btrfs_err(fs_info, "bytenr %llu has 0 references, expect > 0", 5652 eb->start); 5653 return -EUCLEAN; 5654 } 5655 } 5656 5657 if (wc->stage == DROP_REFERENCE) { 5658 if (wc->refs[level] > 1) 5659 return 1; 5660 5661 if (path->locks[level] && !wc->keep_locks) { 5662 btrfs_tree_unlock_rw(eb, path->locks[level]); 5663 path->locks[level] = 0; 5664 } 5665 return 0; 5666 } 5667 5668 /* wc->stage == UPDATE_BACKREF */ 5669 if (!(wc->flags[level] & flag)) { 5670 ASSERT(path->locks[level]); 5671 ret = btrfs_inc_ref(trans, root, eb, true); 5672 if (unlikely(ret)) { 5673 btrfs_abort_transaction(trans, ret); 5674 return ret; 5675 } 5676 ret = btrfs_dec_ref(trans, root, eb, false); 5677 if (unlikely(ret)) { 5678 btrfs_abort_transaction(trans, ret); 5679 return ret; 5680 } 5681 ret = btrfs_set_disk_extent_flags(trans, eb, flag); 5682 if (unlikely(ret)) { 5683 btrfs_abort_transaction(trans, ret); 5684 return ret; 5685 } 5686 wc->flags[level] |= flag; 5687 } 5688 5689 /* 5690 * the block is shared by multiple trees, so it's not good to 5691 * keep the tree lock 5692 */ 5693 if (path->locks[level] && level > 0) { 5694 btrfs_tree_unlock_rw(eb, path->locks[level]); 5695 path->locks[level] = 0; 5696 } 5697 return 0; 5698 } 5699 5700 /* 5701 * This is used to verify a ref exists for this root to deal with a bug where we 5702 * would have a drop_progress key that hadn't been updated properly. 5703 */ 5704 static int check_ref_exists(struct btrfs_trans_handle *trans, 5705 struct btrfs_root *root, u64 bytenr, u64 parent, 5706 int level) 5707 { 5708 struct btrfs_delayed_ref_root *delayed_refs; 5709 struct btrfs_delayed_ref_head *head; 5710 BTRFS_PATH_AUTO_FREE(path); 5711 struct btrfs_extent_inline_ref *iref; 5712 int ret; 5713 bool exists = false; 5714 5715 path = btrfs_alloc_path(); 5716 if (!path) 5717 return -ENOMEM; 5718 again: 5719 ret = lookup_extent_backref(trans, path, &iref, bytenr, 5720 root->fs_info->nodesize, parent, 5721 btrfs_root_id(root), level, 0); 5722 if (ret != -ENOENT) { 5723 /* 5724 * If we get 0 then we found our reference, return 1, else 5725 * return the error if it's not -ENOENT; 5726 */ 5727 return (ret < 0 ) ? ret : 1; 5728 } 5729 5730 /* 5731 * We could have a delayed ref with this reference, so look it up while 5732 * we're holding the path open to make sure we don't race with the 5733 * delayed ref running. 5734 */ 5735 delayed_refs = &trans->transaction->delayed_refs; 5736 spin_lock(&delayed_refs->lock); 5737 head = btrfs_find_delayed_ref_head(root->fs_info, delayed_refs, bytenr); 5738 if (!head) 5739 goto out; 5740 if (!mutex_trylock(&head->mutex)) { 5741 /* 5742 * We're contended, means that the delayed ref is running, get a 5743 * reference and wait for the ref head to be complete and then 5744 * try again. 5745 */ 5746 refcount_inc(&head->refs); 5747 spin_unlock(&delayed_refs->lock); 5748 5749 btrfs_release_path(path); 5750 5751 mutex_lock(&head->mutex); 5752 mutex_unlock(&head->mutex); 5753 btrfs_put_delayed_ref_head(head); 5754 goto again; 5755 } 5756 5757 exists = btrfs_find_delayed_tree_ref(head, btrfs_root_id(root), parent); 5758 mutex_unlock(&head->mutex); 5759 out: 5760 spin_unlock(&delayed_refs->lock); 5761 return exists ? 1 : 0; 5762 } 5763 5764 /* 5765 * We may not have an uptodate block, so if we are going to walk down into this 5766 * block we need to drop the lock, read it off of the disk, re-lock it and 5767 * return to continue dropping the snapshot. 5768 */ 5769 static int check_next_block_uptodate(struct btrfs_trans_handle *trans, 5770 struct btrfs_root *root, 5771 struct btrfs_path *path, 5772 struct walk_control *wc, 5773 struct extent_buffer *next) 5774 { 5775 struct btrfs_tree_parent_check check = { 0 }; 5776 u64 generation; 5777 int level = wc->level; 5778 int ret; 5779 5780 btrfs_assert_tree_write_locked(next); 5781 5782 generation = btrfs_node_ptr_generation(path->nodes[level], path->slots[level]); 5783 5784 if (btrfs_buffer_uptodate(next, generation, NULL)) 5785 return 0; 5786 5787 check.level = level - 1; 5788 check.transid = generation; 5789 check.owner_root = btrfs_root_id(root); 5790 check.has_first_key = true; 5791 btrfs_node_key_to_cpu(path->nodes[level], &check.first_key, path->slots[level]); 5792 5793 btrfs_tree_unlock(next); 5794 if (level == 1) 5795 reada_walk_down(trans, root, wc, path); 5796 ret = btrfs_read_extent_buffer(next, &check); 5797 if (ret) { 5798 free_extent_buffer(next); 5799 return ret; 5800 } 5801 btrfs_tree_lock(next); 5802 wc->lookup_info = 1; 5803 return 0; 5804 } 5805 5806 /* 5807 * If we determine that we don't have to visit wc->level - 1 then we need to 5808 * determine if we can drop our reference. 5809 * 5810 * If we are UPDATE_BACKREF then we will not, we need to update our backrefs. 5811 * 5812 * If we are DROP_REFERENCE this will figure out if we need to drop our current 5813 * reference, skipping it if we dropped it from a previous uncompleted drop, or 5814 * dropping it if we still have a reference to it. 5815 */ 5816 static int maybe_drop_reference(struct btrfs_trans_handle *trans, struct btrfs_root *root, 5817 struct btrfs_path *path, struct walk_control *wc, 5818 struct extent_buffer *next, u64 owner_root) 5819 { 5820 struct btrfs_ref ref = { 5821 .action = BTRFS_DROP_DELAYED_REF, 5822 .bytenr = next->start, 5823 .num_bytes = root->fs_info->nodesize, 5824 .owning_root = owner_root, 5825 .ref_root = btrfs_root_id(root), 5826 }; 5827 int level = wc->level; 5828 int ret; 5829 5830 /* We are UPDATE_BACKREF, we're not dropping anything. */ 5831 if (wc->stage == UPDATE_BACKREF) 5832 return 0; 5833 5834 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF) { 5835 ref.parent = path->nodes[level]->start; 5836 } else { 5837 ASSERT(btrfs_root_id(root) == btrfs_header_owner(path->nodes[level])); 5838 if (unlikely(btrfs_root_id(root) != btrfs_header_owner(path->nodes[level]))) { 5839 btrfs_err(root->fs_info, "mismatched block owner"); 5840 return -EIO; 5841 } 5842 } 5843 5844 /* 5845 * If we had a drop_progress we need to verify the refs are set as 5846 * expected. If we find our ref then we know that from here on out 5847 * everything should be correct, and we can clear the 5848 * ->restarted flag. 5849 */ 5850 if (wc->restarted) { 5851 ret = check_ref_exists(trans, root, next->start, ref.parent, 5852 level - 1); 5853 if (ret <= 0) 5854 return ret; 5855 ret = 0; 5856 wc->restarted = 0; 5857 } 5858 5859 /* 5860 * Reloc tree doesn't contribute to qgroup numbers, and we have already 5861 * accounted them at merge time (replace_path), thus we could skip 5862 * expensive subtree trace here. 5863 */ 5864 if (btrfs_root_id(root) != BTRFS_TREE_RELOC_OBJECTID && 5865 wc->refs[level - 1] > 1) { 5866 u64 generation = btrfs_node_ptr_generation(path->nodes[level], 5867 path->slots[level]); 5868 5869 ret = btrfs_qgroup_trace_subtree(trans, next, generation, level - 1); 5870 if (ret) { 5871 btrfs_err_rl(root->fs_info, 5872 "error %d accounting shared subtree, quota is out of sync, rescan required", 5873 ret); 5874 } 5875 } 5876 5877 /* 5878 * We need to update the next key in our walk control so we can update 5879 * the drop_progress key accordingly. We don't care if find_next_key 5880 * doesn't find a key because that means we're at the end and are going 5881 * to clean up now. 5882 */ 5883 wc->drop_level = level; 5884 find_next_key(path, level, &wc->drop_progress); 5885 5886 btrfs_init_tree_ref(&ref, level - 1, 0, false); 5887 return btrfs_free_extent(trans, &ref); 5888 } 5889 5890 /* 5891 * helper to process tree block pointer. 5892 * 5893 * when wc->stage == DROP_REFERENCE, this function checks 5894 * reference count of the block pointed to. if the block 5895 * is shared and we need update back refs for the subtree 5896 * rooted at the block, this function changes wc->stage to 5897 * UPDATE_BACKREF. if the block is shared and there is no 5898 * need to update back, this function drops the reference 5899 * to the block. 5900 * 5901 * NOTE: return value 1 means we should stop walking down. 5902 */ 5903 static noinline int do_walk_down(struct btrfs_trans_handle *trans, 5904 struct btrfs_root *root, 5905 struct btrfs_path *path, 5906 struct walk_control *wc) 5907 { 5908 struct btrfs_fs_info *fs_info = root->fs_info; 5909 u64 bytenr; 5910 u64 generation; 5911 u64 owner_root = 0; 5912 struct extent_buffer *next; 5913 int level = wc->level; 5914 int ret = 0; 5915 5916 generation = btrfs_node_ptr_generation(path->nodes[level], 5917 path->slots[level]); 5918 /* 5919 * if the lower level block was created before the snapshot 5920 * was created, we know there is no need to update back refs 5921 * for the subtree 5922 */ 5923 if (wc->stage == UPDATE_BACKREF && 5924 generation <= btrfs_root_origin_generation(root)) { 5925 wc->lookup_info = 1; 5926 return 1; 5927 } 5928 5929 bytenr = btrfs_node_blockptr(path->nodes[level], path->slots[level]); 5930 5931 next = btrfs_find_create_tree_block(fs_info, bytenr, btrfs_root_id(root), 5932 level - 1); 5933 if (IS_ERR(next)) 5934 return PTR_ERR(next); 5935 5936 btrfs_tree_lock(next); 5937 5938 ret = btrfs_lookup_extent_info(trans, fs_info, bytenr, level - 1, 1, 5939 &wc->refs[level - 1], 5940 &wc->flags[level - 1], 5941 &owner_root); 5942 if (ret < 0) 5943 goto out_unlock; 5944 5945 if (unlikely(wc->refs[level - 1] == 0)) { 5946 btrfs_err(fs_info, "bytenr %llu has 0 references, expect > 0", 5947 bytenr); 5948 ret = -EUCLEAN; 5949 goto out_unlock; 5950 } 5951 wc->lookup_info = 0; 5952 5953 /* If we don't have to walk into this node skip it. */ 5954 if (!visit_node_for_delete(root, wc, path->nodes[level], 5955 wc->flags[level - 1], path->slots[level])) 5956 goto skip; 5957 5958 /* 5959 * We have to walk down into this node, and if we're currently at the 5960 * DROP_REFERENCE stage and this block is shared then we need to switch 5961 * to the UPDATE_BACKREF stage in order to convert to FULL_BACKREF. 5962 */ 5963 if (wc->stage == DROP_REFERENCE && wc->refs[level - 1] > 1) { 5964 wc->stage = UPDATE_BACKREF; 5965 wc->shared_level = level - 1; 5966 } 5967 5968 ret = check_next_block_uptodate(trans, root, path, wc, next); 5969 if (ret) 5970 return ret; 5971 5972 level--; 5973 ASSERT(level == btrfs_header_level(next)); 5974 if (unlikely(level != btrfs_header_level(next))) { 5975 btrfs_err(root->fs_info, "mismatched level"); 5976 ret = -EIO; 5977 goto out_unlock; 5978 } 5979 path->nodes[level] = next; 5980 path->slots[level] = 0; 5981 path->locks[level] = BTRFS_WRITE_LOCK; 5982 wc->level = level; 5983 if (wc->level == 1) 5984 wc->reada_slot = 0; 5985 return 0; 5986 skip: 5987 ret = maybe_drop_reference(trans, root, path, wc, next, owner_root); 5988 if (ret) 5989 goto out_unlock; 5990 wc->refs[level - 1] = 0; 5991 wc->flags[level - 1] = 0; 5992 wc->lookup_info = 1; 5993 ret = 1; 5994 5995 out_unlock: 5996 btrfs_tree_unlock(next); 5997 free_extent_buffer(next); 5998 5999 return ret; 6000 } 6001 6002 /* 6003 * helper to process tree block while walking up the tree. 6004 * 6005 * when wc->stage == DROP_REFERENCE, this function drops 6006 * reference count on the block. 6007 * 6008 * when wc->stage == UPDATE_BACKREF, this function changes 6009 * wc->stage back to DROP_REFERENCE if we changed wc->stage 6010 * to UPDATE_BACKREF previously while processing the block. 6011 * 6012 * NOTE: return value 1 means we should stop walking up. 6013 */ 6014 static noinline int walk_up_proc(struct btrfs_trans_handle *trans, 6015 struct btrfs_root *root, 6016 struct btrfs_path *path, 6017 struct walk_control *wc) 6018 { 6019 struct btrfs_fs_info *fs_info = root->fs_info; 6020 int ret = 0; 6021 int level = wc->level; 6022 struct extent_buffer *eb = path->nodes[level]; 6023 u64 parent = 0; 6024 6025 if (wc->stage == UPDATE_BACKREF) { 6026 ASSERT(wc->shared_level >= level); 6027 if (level < wc->shared_level) 6028 goto out; 6029 6030 ret = find_next_key(path, level + 1, &wc->update_progress); 6031 if (ret > 0) 6032 wc->update_ref = 0; 6033 6034 wc->stage = DROP_REFERENCE; 6035 wc->shared_level = -1; 6036 path->slots[level] = 0; 6037 6038 /* 6039 * check reference count again if the block isn't locked. 6040 * we should start walking down the tree again if reference 6041 * count is one. 6042 */ 6043 if (!path->locks[level]) { 6044 ASSERT(level > 0); 6045 btrfs_tree_lock(eb); 6046 path->locks[level] = BTRFS_WRITE_LOCK; 6047 6048 ret = btrfs_lookup_extent_info(trans, fs_info, 6049 eb->start, level, 1, 6050 &wc->refs[level], 6051 &wc->flags[level], 6052 NULL); 6053 if (ret < 0) { 6054 btrfs_tree_unlock_rw(eb, path->locks[level]); 6055 path->locks[level] = 0; 6056 return ret; 6057 } 6058 if (unlikely(wc->refs[level] == 0)) { 6059 btrfs_tree_unlock_rw(eb, path->locks[level]); 6060 btrfs_err(fs_info, "bytenr %llu has 0 references, expect > 0", 6061 eb->start); 6062 return -EUCLEAN; 6063 } 6064 if (wc->refs[level] == 1) { 6065 btrfs_tree_unlock_rw(eb, path->locks[level]); 6066 path->locks[level] = 0; 6067 return 1; 6068 } 6069 } 6070 } 6071 6072 /* wc->stage == DROP_REFERENCE */ 6073 ASSERT(path->locks[level] || wc->refs[level] == 1); 6074 6075 if (wc->refs[level] == 1) { 6076 if (level == 0) { 6077 const bool full_backref = (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF); 6078 6079 ret = btrfs_dec_ref(trans, root, eb, full_backref); 6080 if (unlikely(ret)) { 6081 btrfs_abort_transaction(trans, ret); 6082 return ret; 6083 } 6084 if (btrfs_is_fstree(btrfs_root_id(root))) { 6085 ret = btrfs_qgroup_trace_leaf_items(trans, eb); 6086 if (ret) { 6087 btrfs_err_rl(fs_info, 6088 "error %d accounting leaf items, quota is out of sync, rescan required", 6089 ret); 6090 } 6091 } 6092 } 6093 /* Make block locked assertion in btrfs_clear_buffer_dirty happy. */ 6094 if (!path->locks[level]) { 6095 btrfs_tree_lock(eb); 6096 path->locks[level] = BTRFS_WRITE_LOCK; 6097 } 6098 btrfs_clear_buffer_dirty(trans, eb); 6099 } 6100 6101 if (eb == root->node) { 6102 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF) 6103 parent = eb->start; 6104 else if (unlikely(btrfs_root_id(root) != btrfs_header_owner(eb))) 6105 goto owner_mismatch; 6106 } else { 6107 if (wc->flags[level + 1] & BTRFS_BLOCK_FLAG_FULL_BACKREF) 6108 parent = path->nodes[level + 1]->start; 6109 else if (unlikely(btrfs_root_id(root) != 6110 btrfs_header_owner(path->nodes[level + 1]))) 6111 goto owner_mismatch; 6112 } 6113 6114 ret = btrfs_free_tree_block(trans, btrfs_root_id(root), eb, parent, 6115 wc->refs[level] == 1); 6116 if (ret < 0) 6117 btrfs_abort_transaction(trans, ret); 6118 out: 6119 wc->refs[level] = 0; 6120 wc->flags[level] = 0; 6121 return ret; 6122 6123 owner_mismatch: 6124 btrfs_err_rl(fs_info, "unexpected tree owner, have %llu expect %llu", 6125 btrfs_header_owner(eb), btrfs_root_id(root)); 6126 return -EUCLEAN; 6127 } 6128 6129 /* 6130 * walk_down_tree consists of two steps. 6131 * 6132 * walk_down_proc(). Look up the reference count and reference of our current 6133 * wc->level. At this point path->nodes[wc->level] should be populated and 6134 * uptodate, and in most cases should already be locked. If we are in 6135 * DROP_REFERENCE and our refcount is > 1 then we've entered a shared node and 6136 * we can walk back up the tree. If we are UPDATE_BACKREF we have to set 6137 * FULL_BACKREF on this node if it's not already set, and then do the 6138 * FULL_BACKREF conversion dance, which is to drop the root reference and add 6139 * the shared reference to all of this nodes children. 6140 * 6141 * do_walk_down(). This is where we actually start iterating on the children of 6142 * our current path->nodes[wc->level]. For DROP_REFERENCE that means dropping 6143 * our reference to the children that return false from visit_node_for_delete(), 6144 * which has various conditions where we know we can just drop our reference 6145 * without visiting the node. For UPDATE_BACKREF we will skip any children that 6146 * visit_node_for_delete() returns false for, only walking down when necessary. 6147 * The bulk of the work for UPDATE_BACKREF occurs in the walk_up_tree() part of 6148 * snapshot deletion. 6149 */ 6150 static noinline int walk_down_tree(struct btrfs_trans_handle *trans, 6151 struct btrfs_root *root, 6152 struct btrfs_path *path, 6153 struct walk_control *wc) 6154 { 6155 int level = wc->level; 6156 int ret = 0; 6157 6158 wc->lookup_info = 1; 6159 while (level >= 0) { 6160 ret = walk_down_proc(trans, root, path, wc); 6161 if (ret) 6162 break; 6163 6164 if (level == 0) 6165 break; 6166 6167 if (path->slots[level] >= 6168 btrfs_header_nritems(path->nodes[level])) 6169 break; 6170 6171 ret = do_walk_down(trans, root, path, wc); 6172 if (ret > 0) { 6173 path->slots[level]++; 6174 continue; 6175 } else if (ret < 0) 6176 break; 6177 level = wc->level; 6178 } 6179 return (ret == 1) ? 0 : ret; 6180 } 6181 6182 /* 6183 * walk_up_tree() is responsible for making sure we visit every slot on our 6184 * current node, and if we're at the end of that node then we call 6185 * walk_up_proc() on our current node which will do one of a few things based on 6186 * our stage. 6187 * 6188 * UPDATE_BACKREF. If we wc->level is currently less than our wc->shared_level 6189 * then we need to walk back up the tree, and then going back down into the 6190 * other slots via walk_down_tree to update any other children from our original 6191 * wc->shared_level. Once we're at or above our wc->shared_level we can switch 6192 * back to DROP_REFERENCE, lookup the current nodes refs and flags, and carry on. 6193 * 6194 * DROP_REFERENCE. If our refs == 1 then we're going to free this tree block. 6195 * If we're level 0 then we need to btrfs_dec_ref() on all of the data extents 6196 * in our current leaf. After that we call btrfs_free_tree_block() on the 6197 * current node and walk up to the next node to walk down the next slot. 6198 */ 6199 static noinline int walk_up_tree(struct btrfs_trans_handle *trans, 6200 struct btrfs_root *root, 6201 struct btrfs_path *path, 6202 struct walk_control *wc, int max_level) 6203 { 6204 int level = wc->level; 6205 int ret; 6206 6207 path->slots[level] = btrfs_header_nritems(path->nodes[level]); 6208 while (level < max_level && path->nodes[level]) { 6209 wc->level = level; 6210 if (path->slots[level] + 1 < 6211 btrfs_header_nritems(path->nodes[level])) { 6212 path->slots[level]++; 6213 return 0; 6214 } else { 6215 ret = walk_up_proc(trans, root, path, wc); 6216 if (ret > 0) 6217 return 0; 6218 if (ret < 0) 6219 return ret; 6220 6221 if (path->locks[level]) { 6222 btrfs_tree_unlock_rw(path->nodes[level], 6223 path->locks[level]); 6224 path->locks[level] = 0; 6225 } 6226 free_extent_buffer(path->nodes[level]); 6227 path->nodes[level] = NULL; 6228 level++; 6229 } 6230 } 6231 return 1; 6232 } 6233 6234 /* 6235 * drop a subvolume tree. 6236 * 6237 * this function traverses the tree freeing any blocks that only 6238 * referenced by the tree. 6239 * 6240 * when a shared tree block is found. this function decreases its 6241 * reference count by one. if update_ref is true, this function 6242 * also make sure backrefs for the shared block and all lower level 6243 * blocks are properly updated. 6244 * 6245 * If called with for_reloc set, may exit early with -EAGAIN 6246 */ 6247 int btrfs_drop_snapshot(struct btrfs_root *root, bool update_ref, bool for_reloc) 6248 { 6249 const bool is_reloc_root = (btrfs_root_id(root) == BTRFS_TREE_RELOC_OBJECTID); 6250 struct btrfs_fs_info *fs_info = root->fs_info; 6251 struct btrfs_path *path; 6252 struct btrfs_trans_handle *trans; 6253 struct btrfs_root *tree_root = fs_info->tree_root; 6254 struct btrfs_root_item *root_item = &root->root_item; 6255 struct walk_control AUTO_KFREE(wc); 6256 struct btrfs_key key; 6257 const u64 rootid = btrfs_root_id(root); 6258 int ret = 0; 6259 int level; 6260 bool root_dropped = false; 6261 bool unfinished_drop = false; 6262 6263 btrfs_debug(fs_info, "Drop subvolume %llu", btrfs_root_id(root)); 6264 6265 path = btrfs_alloc_path(); 6266 if (!path) { 6267 ret = -ENOMEM; 6268 goto out; 6269 } 6270 6271 wc = kzalloc(sizeof(*wc), GFP_NOFS); 6272 if (!wc) { 6273 ret = -ENOMEM; 6274 goto out_free; 6275 } 6276 6277 /* 6278 * Use join to avoid potential EINTR from transaction start. See 6279 * wait_reserve_ticket and the whole reservation callchain. 6280 */ 6281 if (for_reloc) 6282 trans = btrfs_join_transaction(tree_root); 6283 else 6284 trans = btrfs_start_transaction(tree_root, 0); 6285 if (IS_ERR(trans)) { 6286 ret = PTR_ERR(trans); 6287 goto out_free; 6288 } 6289 6290 ret = btrfs_run_delayed_items(trans); 6291 if (ret) 6292 goto out_end_trans; 6293 6294 /* 6295 * This will help us catch people modifying the fs tree while we're 6296 * dropping it. It is unsafe to mess with the fs tree while it's being 6297 * dropped as we unlock the root node and parent nodes as we walk down 6298 * the tree, assuming nothing will change. If something does change 6299 * then we'll have stale information and drop references to blocks we've 6300 * already dropped. 6301 */ 6302 set_bit(BTRFS_ROOT_DELETING, &root->state); 6303 unfinished_drop = test_bit(BTRFS_ROOT_UNFINISHED_DROP, &root->state); 6304 6305 if (btrfs_disk_key_objectid(&root_item->drop_progress) == 0) { 6306 level = btrfs_header_level(root->node); 6307 path->nodes[level] = btrfs_lock_root_node(root); 6308 path->slots[level] = 0; 6309 path->locks[level] = BTRFS_WRITE_LOCK; 6310 memset(&wc->update_progress, 0, 6311 sizeof(wc->update_progress)); 6312 } else { 6313 btrfs_disk_key_to_cpu(&key, &root_item->drop_progress); 6314 memcpy(&wc->update_progress, &key, 6315 sizeof(wc->update_progress)); 6316 6317 level = btrfs_root_drop_level(root_item); 6318 BUG_ON(level == 0); 6319 path->lowest_level = level; 6320 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0); 6321 path->lowest_level = 0; 6322 if (ret < 0) 6323 goto out_end_trans; 6324 6325 WARN_ON(ret > 0); 6326 ret = 0; 6327 6328 /* 6329 * unlock our path, this is safe because only this 6330 * function is allowed to delete this snapshot 6331 */ 6332 btrfs_unlock_up_safe(path, 0); 6333 6334 level = btrfs_header_level(root->node); 6335 while (1) { 6336 btrfs_tree_lock(path->nodes[level]); 6337 path->locks[level] = BTRFS_WRITE_LOCK; 6338 6339 /* 6340 * btrfs_lookup_extent_info() returns 0 for success, 6341 * or < 0 for error. 6342 */ 6343 ret = btrfs_lookup_extent_info(trans, fs_info, 6344 path->nodes[level]->start, 6345 level, 1, &wc->refs[level], 6346 &wc->flags[level], NULL); 6347 if (ret < 0) 6348 goto out_end_trans; 6349 6350 BUG_ON(wc->refs[level] == 0); 6351 6352 if (level == btrfs_root_drop_level(root_item)) 6353 break; 6354 6355 btrfs_tree_unlock(path->nodes[level]); 6356 path->locks[level] = 0; 6357 WARN_ON(wc->refs[level] != 1); 6358 level--; 6359 } 6360 } 6361 6362 wc->restarted = test_bit(BTRFS_ROOT_DEAD_TREE, &root->state); 6363 wc->level = level; 6364 wc->shared_level = -1; 6365 wc->stage = DROP_REFERENCE; 6366 wc->update_ref = update_ref; 6367 wc->keep_locks = 0; 6368 wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(fs_info); 6369 6370 while (1) { 6371 6372 ret = walk_down_tree(trans, root, path, wc); 6373 if (unlikely(ret < 0)) { 6374 btrfs_abort_transaction(trans, ret); 6375 break; 6376 } 6377 6378 ret = walk_up_tree(trans, root, path, wc, BTRFS_MAX_LEVEL); 6379 if (unlikely(ret < 0)) { 6380 btrfs_abort_transaction(trans, ret); 6381 break; 6382 } 6383 6384 if (ret > 0) { 6385 BUG_ON(wc->stage != DROP_REFERENCE); 6386 ret = 0; 6387 break; 6388 } 6389 6390 if (wc->stage == DROP_REFERENCE) { 6391 wc->drop_level = wc->level; 6392 btrfs_node_key_to_cpu(path->nodes[wc->drop_level], 6393 &wc->drop_progress, 6394 path->slots[wc->drop_level]); 6395 } 6396 btrfs_cpu_key_to_disk(&root_item->drop_progress, 6397 &wc->drop_progress); 6398 btrfs_set_root_drop_level(root_item, wc->drop_level); 6399 6400 BUG_ON(wc->level == 0); 6401 if (btrfs_should_end_transaction(trans) || 6402 (!for_reloc && btrfs_need_cleaner_sleep(fs_info))) { 6403 ret = btrfs_update_root(trans, tree_root, 6404 &root->root_key, 6405 root_item); 6406 if (unlikely(ret)) { 6407 btrfs_abort_transaction(trans, ret); 6408 goto out_end_trans; 6409 } 6410 6411 if (!is_reloc_root) 6412 btrfs_set_last_root_drop_gen(fs_info, trans->transid); 6413 6414 btrfs_end_transaction_throttle(trans); 6415 if (!for_reloc && btrfs_need_cleaner_sleep(fs_info)) { 6416 btrfs_debug(fs_info, 6417 "drop snapshot early exit"); 6418 ret = -EAGAIN; 6419 goto out_free; 6420 } 6421 6422 /* 6423 * Use join to avoid potential EINTR from transaction 6424 * start. See wait_reserve_ticket and the whole 6425 * reservation callchain. 6426 */ 6427 if (for_reloc) 6428 trans = btrfs_join_transaction(tree_root); 6429 else 6430 trans = btrfs_start_transaction(tree_root, 0); 6431 if (IS_ERR(trans)) { 6432 ret = PTR_ERR(trans); 6433 goto out_free; 6434 } 6435 } 6436 } 6437 btrfs_release_path(path); 6438 if (ret) 6439 goto out_end_trans; 6440 6441 ret = btrfs_del_root(trans, &root->root_key); 6442 if (unlikely(ret)) { 6443 btrfs_abort_transaction(trans, ret); 6444 goto out_end_trans; 6445 } 6446 6447 if (!is_reloc_root) { 6448 ret = btrfs_find_root(tree_root, &root->root_key, path, 6449 NULL, NULL); 6450 if (unlikely(ret < 0)) { 6451 btrfs_abort_transaction(trans, ret); 6452 goto out_end_trans; 6453 } else if (ret > 0) { 6454 ret = 0; 6455 /* 6456 * If we fail to delete the orphan item this time 6457 * around, it'll get picked up the next time. 6458 * 6459 * The most common failure here is just -ENOENT. 6460 */ 6461 btrfs_del_orphan_item(trans, tree_root, btrfs_root_id(root)); 6462 } 6463 } 6464 6465 /* 6466 * This subvolume is going to be completely dropped, and won't be 6467 * recorded as dirty roots, thus pertrans meta rsv will not be freed at 6468 * commit transaction time. So free it here manually. 6469 */ 6470 btrfs_qgroup_convert_reserved_meta(root, INT_MAX); 6471 btrfs_qgroup_free_meta_all_pertrans(root); 6472 6473 if (test_bit(BTRFS_ROOT_IN_RADIX, &root->state)) 6474 btrfs_add_dropped_root(trans, root); 6475 else 6476 btrfs_put_root(root); 6477 root_dropped = true; 6478 out_end_trans: 6479 if (!is_reloc_root) 6480 btrfs_set_last_root_drop_gen(fs_info, trans->transid); 6481 6482 btrfs_end_transaction_throttle(trans); 6483 out_free: 6484 btrfs_free_path(path); 6485 out: 6486 if (!ret && root_dropped) { 6487 ret = btrfs_qgroup_cleanup_dropped_subvolume(fs_info, rootid); 6488 if (ret < 0) 6489 btrfs_warn_rl(fs_info, 6490 "failed to cleanup qgroup 0/%llu: %d", 6491 rootid, ret); 6492 ret = 0; 6493 } 6494 /* 6495 * We were an unfinished drop root, check to see if there are any 6496 * pending, and if not clear and wake up any waiters. 6497 */ 6498 if (!ret && unfinished_drop) 6499 btrfs_maybe_wake_unfinished_drop(fs_info); 6500 6501 /* 6502 * So if we need to stop dropping the snapshot for whatever reason we 6503 * need to make sure to add it back to the dead root list so that we 6504 * keep trying to do the work later. This also cleans up roots if we 6505 * don't have it in the radix (like when we recover after a power fail 6506 * or unmount) so we don't leak memory. 6507 */ 6508 if (!for_reloc && !root_dropped) 6509 btrfs_add_dead_root(root); 6510 return ret; 6511 } 6512 6513 /* 6514 * drop subtree rooted at tree block 'node'. 6515 * 6516 * NOTE: this function will unlock and release tree block 'node' 6517 * only used by relocation code 6518 */ 6519 int btrfs_drop_subtree(struct btrfs_trans_handle *trans, 6520 struct btrfs_root *root, 6521 struct extent_buffer *node, 6522 struct extent_buffer *parent) 6523 { 6524 struct btrfs_fs_info *fs_info = root->fs_info; 6525 BTRFS_PATH_AUTO_FREE(path); 6526 struct walk_control AUTO_KFREE(wc); 6527 int level; 6528 int parent_level; 6529 int ret = 0; 6530 6531 BUG_ON(btrfs_root_id(root) != BTRFS_TREE_RELOC_OBJECTID); 6532 6533 path = btrfs_alloc_path(); 6534 if (!path) 6535 return -ENOMEM; 6536 6537 wc = kzalloc(sizeof(*wc), GFP_NOFS); 6538 if (!wc) 6539 return -ENOMEM; 6540 6541 btrfs_assert_tree_write_locked(parent); 6542 parent_level = btrfs_header_level(parent); 6543 refcount_inc(&parent->refs); 6544 path->nodes[parent_level] = parent; 6545 path->slots[parent_level] = btrfs_header_nritems(parent); 6546 6547 btrfs_assert_tree_write_locked(node); 6548 level = btrfs_header_level(node); 6549 path->nodes[level] = node; 6550 path->slots[level] = 0; 6551 path->locks[level] = BTRFS_WRITE_LOCK; 6552 6553 wc->refs[parent_level] = 1; 6554 wc->flags[parent_level] = BTRFS_BLOCK_FLAG_FULL_BACKREF; 6555 wc->level = level; 6556 wc->shared_level = -1; 6557 wc->stage = DROP_REFERENCE; 6558 wc->update_ref = 0; 6559 wc->keep_locks = 1; 6560 wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(fs_info); 6561 6562 while (1) { 6563 ret = walk_down_tree(trans, root, path, wc); 6564 if (ret < 0) 6565 return ret; 6566 6567 ret = walk_up_tree(trans, root, path, wc, parent_level); 6568 if (ret) { 6569 if (ret < 0) 6570 return ret; 6571 break; 6572 } 6573 } 6574 6575 return 0; 6576 } 6577 6578 /* 6579 * Unpin the extent range in an error context and don't add the space back. 6580 * Errors are not propagated further. 6581 */ 6582 void btrfs_error_unpin_extent_range(struct btrfs_fs_info *fs_info, u64 start, u64 end) 6583 { 6584 unpin_extent_range(fs_info, start, end, false); 6585 } 6586 6587 /* 6588 * It used to be that old block groups would be left around forever. 6589 * Iterating over them would be enough to trim unused space. Since we 6590 * now automatically remove them, we also need to iterate over unallocated 6591 * space. 6592 * 6593 * We don't want a transaction for this since the discard may take a 6594 * substantial amount of time. We don't require that a transaction be 6595 * running, but we do need to take a running transaction into account 6596 * to ensure that we're not discarding chunks that were released or 6597 * allocated in the current transaction. 6598 * 6599 * Holding the chunks lock will prevent other threads from allocating 6600 * or releasing chunks, but it won't prevent a running transaction 6601 * from committing and releasing the memory that the pending chunks 6602 * list head uses. For that, we need to take a reference to the 6603 * transaction and hold the commit root sem. We only need to hold 6604 * it while performing the free space search since we have already 6605 * held back allocations. 6606 */ 6607 static int btrfs_trim_free_extents_throttle(struct btrfs_device *device, 6608 u64 *trimmed, u64 pos, u64 *ret_next_pos) 6609 { 6610 int ret; 6611 u64 start = pos; 6612 u64 trim_len = 0; 6613 6614 *trimmed = 0; 6615 6616 /* Discard not supported = nothing to do. */ 6617 if (!bdev_max_discard_sectors(device->bdev)) 6618 return 0; 6619 6620 /* Not writable = nothing to do. */ 6621 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) 6622 return 0; 6623 6624 /* No free space = nothing to do. */ 6625 if (device->total_bytes <= device->bytes_used) 6626 return 0; 6627 6628 ret = 0; 6629 6630 while (1) { 6631 struct btrfs_fs_info *fs_info = device->fs_info; 6632 u64 cur_start; 6633 u64 end; 6634 u64 len; 6635 u64 bytes; 6636 6637 ret = mutex_lock_interruptible(&fs_info->chunk_mutex); 6638 if (ret) 6639 break; 6640 6641 cur_start = start; 6642 btrfs_find_first_clear_extent_bit(&device->alloc_state, start, 6643 &start, &end, 6644 CHUNK_TRIMMED | CHUNK_ALLOCATED); 6645 start = max(start, cur_start); 6646 6647 /* Check if there are any CHUNK_* bits left */ 6648 if (start > device->total_bytes) { 6649 DEBUG_WARN(); 6650 btrfs_warn(fs_info, 6651 "ignoring attempt to trim beyond device size: offset %llu length %llu device %s device size %llu", 6652 start, end - start + 1, 6653 btrfs_dev_name(device), 6654 device->total_bytes); 6655 mutex_unlock(&fs_info->chunk_mutex); 6656 ret = 0; 6657 break; 6658 } 6659 6660 /* Ensure we skip the reserved space on each device. */ 6661 start = max_t(u64, start, BTRFS_DEVICE_RANGE_RESERVED); 6662 6663 /* 6664 * If find_first_clear_extent_bit find a range that spans the 6665 * end of the device it will set end to -1, in this case it's up 6666 * to the caller to trim the value to the size of the device. 6667 */ 6668 end = min(end, device->total_bytes - 1); 6669 6670 len = end - start + 1; 6671 len = min(len, BTRFS_MAX_TRIM_LENGTH); 6672 6673 /* We didn't find any extents */ 6674 if (!len) { 6675 mutex_unlock(&fs_info->chunk_mutex); 6676 ret = 0; 6677 break; 6678 } 6679 6680 ret = btrfs_issue_discard(device->bdev, start, len, 6681 &bytes); 6682 if (!ret) 6683 btrfs_set_extent_bit(&device->alloc_state, start, 6684 start + bytes - 1, CHUNK_TRIMMED, NULL); 6685 mutex_unlock(&fs_info->chunk_mutex); 6686 6687 if (ret) 6688 break; 6689 6690 start += len; 6691 *trimmed += bytes; 6692 trim_len += len; 6693 if (trim_len >= BTRFS_MAX_TRIM_LENGTH) { 6694 *ret_next_pos = start; 6695 ret = -EAGAIN; 6696 break; 6697 } 6698 6699 if (btrfs_trim_interrupted()) { 6700 ret = -ERESTARTSYS; 6701 break; 6702 } 6703 6704 cond_resched(); 6705 } 6706 6707 return ret; 6708 } 6709 6710 static int btrfs_trim_free_extents(struct btrfs_fs_info *fs_info, u64 *trimmed, 6711 u64 *dev_failed, int *dev_ret) 6712 { 6713 struct btrfs_device *dev; 6714 struct btrfs_device *working_dev = NULL; 6715 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices; 6716 u8 uuid[BTRFS_UUID_SIZE]; 6717 u64 start = BTRFS_DEVICE_RANGE_RESERVED; 6718 6719 *trimmed = 0; 6720 *dev_failed = 0; 6721 *dev_ret = 0; 6722 6723 /* Find the device with the smallest UUID to start. */ 6724 mutex_lock(&fs_devices->device_list_mutex); 6725 list_for_each_entry(dev, &fs_devices->devices, dev_list) { 6726 if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state)) 6727 continue; 6728 if (!working_dev || 6729 memcmp(dev->uuid, working_dev->uuid, BTRFS_UUID_SIZE) < 0) 6730 working_dev = dev; 6731 } 6732 if (working_dev) 6733 memcpy(uuid, working_dev->uuid, BTRFS_UUID_SIZE); 6734 mutex_unlock(&fs_devices->device_list_mutex); 6735 6736 if (!working_dev) 6737 return 0; 6738 6739 while (1) { 6740 u64 group_trimmed = 0; 6741 u64 next_pos = 0; 6742 int ret = 0; 6743 6744 mutex_lock(&fs_devices->device_list_mutex); 6745 6746 /* Find and trim the current device. */ 6747 list_for_each_entry(dev, &fs_devices->devices, dev_list) { 6748 if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state)) 6749 continue; 6750 if (dev == working_dev) { 6751 ret = btrfs_trim_free_extents_throttle(working_dev, 6752 &group_trimmed, start, &next_pos); 6753 break; 6754 } 6755 } 6756 6757 /* Throttle: continue the same device from the new position. */ 6758 if (ret == -EAGAIN && next_pos > start) { 6759 mutex_unlock(&fs_devices->device_list_mutex); 6760 *trimmed += group_trimmed; 6761 start = next_pos; 6762 cond_resched(); 6763 continue; 6764 } 6765 6766 /* User interrupted. */ 6767 if (ret == -ERESTARTSYS || ret == -EINTR) { 6768 mutex_unlock(&fs_devices->device_list_mutex); 6769 *trimmed += group_trimmed; 6770 return ret; 6771 } 6772 6773 /* 6774 * Device completed (ret == 0), failed, or EAGAIN with no progress. 6775 * Record error if any, then move to next device. 6776 */ 6777 if (ret == -EAGAIN) { 6778 /* No progress - log and skip device. */ 6779 btrfs_warn(fs_info, 6780 "trim throttle: no progress, offset=%llu device %s, skipping", 6781 start, btrfs_dev_name(working_dev)); 6782 (*dev_failed)++; 6783 if (!*dev_ret) 6784 *dev_ret = ret; 6785 } else if (ret) { 6786 /* Device failed with error. */ 6787 (*dev_failed)++; 6788 if (!*dev_ret) 6789 *dev_ret = ret; 6790 } 6791 6792 /* 6793 * Find next device: smallest UUID larger than current. 6794 * Devices added during trim with smaller UUID will be skipped. 6795 */ 6796 working_dev = NULL; 6797 list_for_each_entry(dev, &fs_devices->devices, dev_list) { 6798 if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state)) 6799 continue; 6800 /* Must larger than current UUID. */ 6801 if (memcmp(dev->uuid, uuid, BTRFS_UUID_SIZE) <= 0) 6802 continue; 6803 /* Find the smallest. */ 6804 if (!working_dev || 6805 memcmp(dev->uuid, working_dev->uuid, BTRFS_UUID_SIZE) < 0) 6806 working_dev = dev; 6807 } 6808 if (working_dev) 6809 memcpy(uuid, working_dev->uuid, BTRFS_UUID_SIZE); 6810 6811 mutex_unlock(&fs_devices->device_list_mutex); 6812 6813 *trimmed += group_trimmed; 6814 start = BTRFS_DEVICE_RANGE_RESERVED; 6815 6816 /* No more devices. */ 6817 if (!working_dev) 6818 break; 6819 6820 cond_resched(); 6821 } 6822 6823 return 0; 6824 } 6825 6826 /* 6827 * Trim the whole filesystem by: 6828 * 1) trimming the free space in each block group 6829 * 2) trimming the unallocated space on each device 6830 * 6831 * This will also continue trimming even if a block group or device encounters 6832 * an error. The return value will be the first error, or 0 if nothing bad 6833 * happens. 6834 */ 6835 int btrfs_trim_fs(struct btrfs_fs_info *fs_info, struct fstrim_range *range) 6836 { 6837 struct btrfs_block_group *cache = NULL; 6838 u64 group_trimmed; 6839 u64 range_end = U64_MAX; 6840 u64 start; 6841 u64 end; 6842 u64 trimmed = 0; 6843 u64 bg_failed = 0; 6844 u64 dev_failed = 0; 6845 int bg_ret = 0; 6846 int dev_ret = 0; 6847 int ret = 0; 6848 6849 if (range->start == U64_MAX) 6850 return -EINVAL; 6851 6852 /* 6853 * Check range overflow if range->len is set. 6854 * The default range->len is U64_MAX. 6855 */ 6856 if (range->len != U64_MAX && 6857 check_add_overflow(range->start, range->len, &range_end)) 6858 return -EINVAL; 6859 6860 cache = btrfs_lookup_first_block_group(fs_info, range->start); 6861 for (; cache; cache = btrfs_next_block_group(cache)) { 6862 if (cache->start >= range_end) { 6863 btrfs_put_block_group(cache); 6864 break; 6865 } 6866 6867 start = max(range->start, cache->start); 6868 end = min(range_end, btrfs_block_group_end(cache)); 6869 6870 if (end - start >= range->minlen) { 6871 if (!btrfs_block_group_done(cache)) { 6872 ret = btrfs_cache_block_group(cache, true); 6873 if (ret) { 6874 bg_failed++; 6875 if (!bg_ret) 6876 bg_ret = ret; 6877 continue; 6878 } 6879 } 6880 ret = btrfs_trim_block_group(cache, 6881 &group_trimmed, 6882 start, 6883 end, 6884 range->minlen); 6885 6886 trimmed += group_trimmed; 6887 if (ret == -ERESTARTSYS || ret == -EINTR) { 6888 btrfs_put_block_group(cache); 6889 break; 6890 } 6891 if (ret) { 6892 bg_failed++; 6893 if (!bg_ret) 6894 bg_ret = ret; 6895 continue; 6896 } 6897 } 6898 } 6899 6900 if (bg_failed) 6901 btrfs_warn(fs_info, 6902 "failed to trim %llu block group(s), first error %d", 6903 bg_failed, bg_ret); 6904 6905 if (ret == -ERESTARTSYS || ret == -EINTR) 6906 return ret; 6907 6908 ret = btrfs_trim_free_extents(fs_info, &group_trimmed, &dev_failed, &dev_ret); 6909 trimmed += group_trimmed; 6910 6911 if (dev_failed) 6912 btrfs_warn(fs_info, 6913 "failed to trim %llu device(s), first error %d", 6914 dev_failed, dev_ret); 6915 range->len = trimmed; 6916 if (ret == -ERESTARTSYS || ret == -EINTR) 6917 return ret; 6918 if (bg_ret) 6919 return bg_ret; 6920 return dev_ret; 6921 } 6922