1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 2007,2008 Oracle. All rights reserved.
6 #include <linux/sched.h>
7 #include <linux/slab.h>
8 #include <linux/rbtree.h>
10 #include <linux/error-injection.h>
14 #include "transaction.h"
15 #include "print-tree.h"
19 #include "tree-mod-log.h"
20 #include "tree-checker.h"
22 #include "accessors.h"
23 #include "extent-tree.h"
25 static struct kmem_cache *btrfs_path_cachep;
27 static int split_node(struct btrfs_trans_handle *trans, struct btrfs_root
28 *root, struct btrfs_path *path, int level);
29 static int split_leaf(struct btrfs_trans_handle *trans, struct btrfs_root *root,
30 const struct btrfs_key *ins_key, struct btrfs_path *path,
31 int data_size, int extend);
32 static int push_node_left(struct btrfs_trans_handle *trans,
33 struct extent_buffer *dst,
34 struct extent_buffer *src, int empty);
35 static int balance_node_right(struct btrfs_trans_handle *trans,
36 struct extent_buffer *dst_buf,
37 struct extent_buffer *src_buf);
38 static void del_ptr(struct btrfs_root *root, struct btrfs_path *path,
41 static const struct btrfs_csums {
44 const char driver[12];
46 [BTRFS_CSUM_TYPE_CRC32] = { .size = 4, .name = "crc32c" },
47 [BTRFS_CSUM_TYPE_XXHASH] = { .size = 8, .name = "xxhash64" },
48 [BTRFS_CSUM_TYPE_SHA256] = { .size = 32, .name = "sha256" },
49 [BTRFS_CSUM_TYPE_BLAKE2] = { .size = 32, .name = "blake2b",
50 .driver = "blake2b-256" },
53 int btrfs_super_csum_size(const struct btrfs_super_block *s)
55 u16 t = btrfs_super_csum_type(s);
57 * csum type is validated at mount time
59 return btrfs_csums[t].size;
62 const char *btrfs_super_csum_name(u16 csum_type)
64 /* csum type is validated at mount time */
65 return btrfs_csums[csum_type].name;
69 * Return driver name if defined, otherwise the name that's also a valid driver
72 const char *btrfs_super_csum_driver(u16 csum_type)
74 /* csum type is validated at mount time */
75 return btrfs_csums[csum_type].driver[0] ?
76 btrfs_csums[csum_type].driver :
77 btrfs_csums[csum_type].name;
80 size_t __attribute_const__ btrfs_get_num_csums(void)
82 return ARRAY_SIZE(btrfs_csums);
85 struct btrfs_path *btrfs_alloc_path(void)
87 return kmem_cache_zalloc(btrfs_path_cachep, GFP_NOFS);
90 /* this also releases the path */
91 void btrfs_free_path(struct btrfs_path *p)
95 btrfs_release_path(p);
96 kmem_cache_free(btrfs_path_cachep, p);
100 * path release drops references on the extent buffers in the path
101 * and it drops any locks held by this path
103 * It is safe to call this on paths that no locks or extent buffers held.
105 noinline void btrfs_release_path(struct btrfs_path *p)
109 for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
114 btrfs_tree_unlock_rw(p->nodes[i], p->locks[i]);
117 free_extent_buffer(p->nodes[i]);
123 * We want the transaction abort to print stack trace only for errors where the
124 * cause could be a bug, eg. due to ENOSPC, and not for common errors that are
125 * caused by external factors.
127 bool __cold abort_should_print_stack(int errno)
139 * safely gets a reference on the root node of a tree. A lock
140 * is not taken, so a concurrent writer may put a different node
141 * at the root of the tree. See btrfs_lock_root_node for the
144 * The extent buffer returned by this has a reference taken, so
145 * it won't disappear. It may stop being the root of the tree
146 * at any time because there are no locks held.
148 struct extent_buffer *btrfs_root_node(struct btrfs_root *root)
150 struct extent_buffer *eb;
154 eb = rcu_dereference(root->node);
157 * RCU really hurts here, we could free up the root node because
158 * it was COWed but we may not get the new root node yet so do
159 * the inc_not_zero dance and if it doesn't work then
160 * synchronize_rcu and try again.
162 if (atomic_inc_not_zero(&eb->refs)) {
173 * Cowonly root (not-shareable trees, everything not subvolume or reloc roots),
174 * just get put onto a simple dirty list. Transaction walks this list to make
175 * sure they get properly updated on disk.
177 static void add_root_to_dirty_list(struct btrfs_root *root)
179 struct btrfs_fs_info *fs_info = root->fs_info;
181 if (test_bit(BTRFS_ROOT_DIRTY, &root->state) ||
182 !test_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state))
185 spin_lock(&fs_info->trans_lock);
186 if (!test_and_set_bit(BTRFS_ROOT_DIRTY, &root->state)) {
187 /* Want the extent tree to be the last on the list */
188 if (root->root_key.objectid == BTRFS_EXTENT_TREE_OBJECTID)
189 list_move_tail(&root->dirty_list,
190 &fs_info->dirty_cowonly_roots);
192 list_move(&root->dirty_list,
193 &fs_info->dirty_cowonly_roots);
195 spin_unlock(&fs_info->trans_lock);
199 * used by snapshot creation to make a copy of a root for a tree with
200 * a given objectid. The buffer with the new root node is returned in
201 * cow_ret, and this func returns zero on success or a negative error code.
203 int btrfs_copy_root(struct btrfs_trans_handle *trans,
204 struct btrfs_root *root,
205 struct extent_buffer *buf,
206 struct extent_buffer **cow_ret, u64 new_root_objectid)
208 struct btrfs_fs_info *fs_info = root->fs_info;
209 struct extent_buffer *cow;
212 struct btrfs_disk_key disk_key;
214 WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
215 trans->transid != fs_info->running_transaction->transid);
216 WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
217 trans->transid != root->last_trans);
219 level = btrfs_header_level(buf);
221 btrfs_item_key(buf, &disk_key, 0);
223 btrfs_node_key(buf, &disk_key, 0);
225 cow = btrfs_alloc_tree_block(trans, root, 0, new_root_objectid,
226 &disk_key, level, buf->start, 0,
227 BTRFS_NESTING_NEW_ROOT);
231 copy_extent_buffer_full(cow, buf);
232 btrfs_set_header_bytenr(cow, cow->start);
233 btrfs_set_header_generation(cow, trans->transid);
234 btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
235 btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
236 BTRFS_HEADER_FLAG_RELOC);
237 if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
238 btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
240 btrfs_set_header_owner(cow, new_root_objectid);
242 write_extent_buffer_fsid(cow, fs_info->fs_devices->metadata_uuid);
244 WARN_ON(btrfs_header_generation(buf) > trans->transid);
245 if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
246 ret = btrfs_inc_ref(trans, root, cow, 1);
248 ret = btrfs_inc_ref(trans, root, cow, 0);
250 btrfs_tree_unlock(cow);
251 free_extent_buffer(cow);
252 btrfs_abort_transaction(trans, ret);
256 btrfs_mark_buffer_dirty(cow);
262 * check if the tree block can be shared by multiple trees
264 int btrfs_block_can_be_shared(struct btrfs_root *root,
265 struct extent_buffer *buf)
268 * Tree blocks not in shareable trees and tree roots are never shared.
269 * If a block was allocated after the last snapshot and the block was
270 * not allocated by tree relocation, we know the block is not shared.
272 if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
273 buf != root->node && buf != root->commit_root &&
274 (btrfs_header_generation(buf) <=
275 btrfs_root_last_snapshot(&root->root_item) ||
276 btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)))
282 static noinline int update_ref_for_cow(struct btrfs_trans_handle *trans,
283 struct btrfs_root *root,
284 struct extent_buffer *buf,
285 struct extent_buffer *cow,
288 struct btrfs_fs_info *fs_info = root->fs_info;
296 * Backrefs update rules:
298 * Always use full backrefs for extent pointers in tree block
299 * allocated by tree relocation.
301 * If a shared tree block is no longer referenced by its owner
302 * tree (btrfs_header_owner(buf) == root->root_key.objectid),
303 * use full backrefs for extent pointers in tree block.
305 * If a tree block is been relocating
306 * (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID),
307 * use full backrefs for extent pointers in tree block.
308 * The reason for this is some operations (such as drop tree)
309 * are only allowed for blocks use full backrefs.
312 if (btrfs_block_can_be_shared(root, buf)) {
313 ret = btrfs_lookup_extent_info(trans, fs_info, buf->start,
314 btrfs_header_level(buf), 1,
320 btrfs_handle_fs_error(fs_info, ret, NULL);
325 if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
326 btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
327 flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
332 owner = btrfs_header_owner(buf);
333 BUG_ON(owner == BTRFS_TREE_RELOC_OBJECTID &&
334 !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
337 if ((owner == root->root_key.objectid ||
338 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) &&
339 !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)) {
340 ret = btrfs_inc_ref(trans, root, buf, 1);
344 if (root->root_key.objectid ==
345 BTRFS_TREE_RELOC_OBJECTID) {
346 ret = btrfs_dec_ref(trans, root, buf, 0);
349 ret = btrfs_inc_ref(trans, root, cow, 1);
353 new_flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
356 if (root->root_key.objectid ==
357 BTRFS_TREE_RELOC_OBJECTID)
358 ret = btrfs_inc_ref(trans, root, cow, 1);
360 ret = btrfs_inc_ref(trans, root, cow, 0);
364 if (new_flags != 0) {
365 int level = btrfs_header_level(buf);
367 ret = btrfs_set_disk_extent_flags(trans, buf,
373 if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
374 if (root->root_key.objectid ==
375 BTRFS_TREE_RELOC_OBJECTID)
376 ret = btrfs_inc_ref(trans, root, cow, 1);
378 ret = btrfs_inc_ref(trans, root, cow, 0);
381 ret = btrfs_dec_ref(trans, root, buf, 1);
385 btrfs_clean_tree_block(buf);
392 * does the dirty work in cow of a single block. The parent block (if
393 * supplied) is updated to point to the new cow copy. The new buffer is marked
394 * dirty and returned locked. If you modify the block it needs to be marked
397 * search_start -- an allocation hint for the new block
399 * empty_size -- a hint that you plan on doing more cow. This is the size in
400 * bytes the allocator should try to find free next to the block it returns.
401 * This is just a hint and may be ignored by the allocator.
403 static noinline int __btrfs_cow_block(struct btrfs_trans_handle *trans,
404 struct btrfs_root *root,
405 struct extent_buffer *buf,
406 struct extent_buffer *parent, int parent_slot,
407 struct extent_buffer **cow_ret,
408 u64 search_start, u64 empty_size,
409 enum btrfs_lock_nesting nest)
411 struct btrfs_fs_info *fs_info = root->fs_info;
412 struct btrfs_disk_key disk_key;
413 struct extent_buffer *cow;
417 u64 parent_start = 0;
422 btrfs_assert_tree_write_locked(buf);
424 WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
425 trans->transid != fs_info->running_transaction->transid);
426 WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
427 trans->transid != root->last_trans);
429 level = btrfs_header_level(buf);
432 btrfs_item_key(buf, &disk_key, 0);
434 btrfs_node_key(buf, &disk_key, 0);
436 if ((root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) && parent)
437 parent_start = parent->start;
439 cow = btrfs_alloc_tree_block(trans, root, parent_start,
440 root->root_key.objectid, &disk_key, level,
441 search_start, empty_size, nest);
445 /* cow is set to blocking by btrfs_init_new_buffer */
447 copy_extent_buffer_full(cow, buf);
448 btrfs_set_header_bytenr(cow, cow->start);
449 btrfs_set_header_generation(cow, trans->transid);
450 btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
451 btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
452 BTRFS_HEADER_FLAG_RELOC);
453 if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
454 btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
456 btrfs_set_header_owner(cow, root->root_key.objectid);
458 write_extent_buffer_fsid(cow, fs_info->fs_devices->metadata_uuid);
460 ret = update_ref_for_cow(trans, root, buf, cow, &last_ref);
462 btrfs_tree_unlock(cow);
463 free_extent_buffer(cow);
464 btrfs_abort_transaction(trans, ret);
468 if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state)) {
469 ret = btrfs_reloc_cow_block(trans, root, buf, cow);
471 btrfs_tree_unlock(cow);
472 free_extent_buffer(cow);
473 btrfs_abort_transaction(trans, ret);
478 if (buf == root->node) {
479 WARN_ON(parent && parent != buf);
480 if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
481 btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
482 parent_start = buf->start;
484 atomic_inc(&cow->refs);
485 ret = btrfs_tree_mod_log_insert_root(root->node, cow, true);
487 rcu_assign_pointer(root->node, cow);
489 btrfs_free_tree_block(trans, btrfs_root_id(root), buf,
490 parent_start, last_ref);
491 free_extent_buffer(buf);
492 add_root_to_dirty_list(root);
494 WARN_ON(trans->transid != btrfs_header_generation(parent));
495 btrfs_tree_mod_log_insert_key(parent, parent_slot,
496 BTRFS_MOD_LOG_KEY_REPLACE);
497 btrfs_set_node_blockptr(parent, parent_slot,
499 btrfs_set_node_ptr_generation(parent, parent_slot,
501 btrfs_mark_buffer_dirty(parent);
503 ret = btrfs_tree_mod_log_free_eb(buf);
505 btrfs_tree_unlock(cow);
506 free_extent_buffer(cow);
507 btrfs_abort_transaction(trans, ret);
511 btrfs_free_tree_block(trans, btrfs_root_id(root), buf,
512 parent_start, last_ref);
515 btrfs_tree_unlock(buf);
516 free_extent_buffer_stale(buf);
517 btrfs_mark_buffer_dirty(cow);
522 static inline int should_cow_block(struct btrfs_trans_handle *trans,
523 struct btrfs_root *root,
524 struct extent_buffer *buf)
526 if (btrfs_is_testing(root->fs_info))
529 /* Ensure we can see the FORCE_COW bit */
530 smp_mb__before_atomic();
533 * We do not need to cow a block if
534 * 1) this block is not created or changed in this transaction;
535 * 2) this block does not belong to TREE_RELOC tree;
536 * 3) the root is not forced COW.
538 * What is forced COW:
539 * when we create snapshot during committing the transaction,
540 * after we've finished copying src root, we must COW the shared
541 * block to ensure the metadata consistency.
543 if (btrfs_header_generation(buf) == trans->transid &&
544 !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN) &&
545 !(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
546 btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)) &&
547 !test_bit(BTRFS_ROOT_FORCE_COW, &root->state))
553 * cows a single block, see __btrfs_cow_block for the real work.
554 * This version of it has extra checks so that a block isn't COWed more than
555 * once per transaction, as long as it hasn't been written yet
557 noinline int btrfs_cow_block(struct btrfs_trans_handle *trans,
558 struct btrfs_root *root, struct extent_buffer *buf,
559 struct extent_buffer *parent, int parent_slot,
560 struct extent_buffer **cow_ret,
561 enum btrfs_lock_nesting nest)
563 struct btrfs_fs_info *fs_info = root->fs_info;
567 if (test_bit(BTRFS_ROOT_DELETING, &root->state))
569 "COW'ing blocks on a fs root that's being dropped");
571 if (trans->transaction != fs_info->running_transaction)
572 WARN(1, KERN_CRIT "trans %llu running %llu\n",
574 fs_info->running_transaction->transid);
576 if (trans->transid != fs_info->generation)
577 WARN(1, KERN_CRIT "trans %llu running %llu\n",
578 trans->transid, fs_info->generation);
580 if (!should_cow_block(trans, root, buf)) {
585 search_start = buf->start & ~((u64)SZ_1G - 1);
588 * Before CoWing this block for later modification, check if it's
589 * the subtree root and do the delayed subtree trace if needed.
591 * Also We don't care about the error, as it's handled internally.
593 btrfs_qgroup_trace_subtree_after_cow(trans, root, buf);
594 ret = __btrfs_cow_block(trans, root, buf, parent,
595 parent_slot, cow_ret, search_start, 0, nest);
597 trace_btrfs_cow_block(root, buf, *cow_ret);
601 ALLOW_ERROR_INJECTION(btrfs_cow_block, ERRNO);
604 * helper function for defrag to decide if two blocks pointed to by a
605 * node are actually close by
607 static int close_blocks(u64 blocknr, u64 other, u32 blocksize)
609 if (blocknr < other && other - (blocknr + blocksize) < 32768)
611 if (blocknr > other && blocknr - (other + blocksize) < 32768)
616 #ifdef __LITTLE_ENDIAN
619 * Compare two keys, on little-endian the disk order is same as CPU order and
620 * we can avoid the conversion.
622 static int comp_keys(const struct btrfs_disk_key *disk_key,
623 const struct btrfs_key *k2)
625 const struct btrfs_key *k1 = (const struct btrfs_key *)disk_key;
627 return btrfs_comp_cpu_keys(k1, k2);
633 * compare two keys in a memcmp fashion
635 static int comp_keys(const struct btrfs_disk_key *disk,
636 const struct btrfs_key *k2)
640 btrfs_disk_key_to_cpu(&k1, disk);
642 return btrfs_comp_cpu_keys(&k1, k2);
647 * same as comp_keys only with two btrfs_key's
649 int __pure btrfs_comp_cpu_keys(const struct btrfs_key *k1, const struct btrfs_key *k2)
651 if (k1->objectid > k2->objectid)
653 if (k1->objectid < k2->objectid)
655 if (k1->type > k2->type)
657 if (k1->type < k2->type)
659 if (k1->offset > k2->offset)
661 if (k1->offset < k2->offset)
667 * this is used by the defrag code to go through all the
668 * leaves pointed to by a node and reallocate them so that
669 * disk order is close to key order
671 int btrfs_realloc_node(struct btrfs_trans_handle *trans,
672 struct btrfs_root *root, struct extent_buffer *parent,
673 int start_slot, u64 *last_ret,
674 struct btrfs_key *progress)
676 struct btrfs_fs_info *fs_info = root->fs_info;
677 struct extent_buffer *cur;
679 u64 search_start = *last_ret;
687 int progress_passed = 0;
688 struct btrfs_disk_key disk_key;
690 WARN_ON(trans->transaction != fs_info->running_transaction);
691 WARN_ON(trans->transid != fs_info->generation);
693 parent_nritems = btrfs_header_nritems(parent);
694 blocksize = fs_info->nodesize;
695 end_slot = parent_nritems - 1;
697 if (parent_nritems <= 1)
700 for (i = start_slot; i <= end_slot; i++) {
703 btrfs_node_key(parent, &disk_key, i);
704 if (!progress_passed && comp_keys(&disk_key, progress) < 0)
708 blocknr = btrfs_node_blockptr(parent, i);
710 last_block = blocknr;
713 other = btrfs_node_blockptr(parent, i - 1);
714 close = close_blocks(blocknr, other, blocksize);
716 if (!close && i < end_slot) {
717 other = btrfs_node_blockptr(parent, i + 1);
718 close = close_blocks(blocknr, other, blocksize);
721 last_block = blocknr;
725 cur = btrfs_read_node_slot(parent, i);
728 if (search_start == 0)
729 search_start = last_block;
731 btrfs_tree_lock(cur);
732 err = __btrfs_cow_block(trans, root, cur, parent, i,
735 (end_slot - i) * blocksize),
738 btrfs_tree_unlock(cur);
739 free_extent_buffer(cur);
742 search_start = cur->start;
743 last_block = cur->start;
744 *last_ret = search_start;
745 btrfs_tree_unlock(cur);
746 free_extent_buffer(cur);
752 * Search for a key in the given extent_buffer.
754 * The lower boundary for the search is specified by the slot number @low. Use a
755 * value of 0 to search over the whole extent buffer.
757 * The slot in the extent buffer is returned via @slot. If the key exists in the
758 * extent buffer, then @slot will point to the slot where the key is, otherwise
759 * it points to the slot where you would insert the key.
761 * Slot may point to the total number of items (i.e. one position beyond the last
762 * key) if the key is bigger than the last key in the extent buffer.
764 static noinline int generic_bin_search(struct extent_buffer *eb, int low,
765 const struct btrfs_key *key, int *slot)
769 int high = btrfs_header_nritems(eb);
771 const int key_size = sizeof(struct btrfs_disk_key);
774 btrfs_err(eb->fs_info,
775 "%s: low (%d) > high (%d) eb %llu owner %llu level %d",
776 __func__, low, high, eb->start,
777 btrfs_header_owner(eb), btrfs_header_level(eb));
781 if (btrfs_header_level(eb) == 0) {
782 p = offsetof(struct btrfs_leaf, items);
783 item_size = sizeof(struct btrfs_item);
785 p = offsetof(struct btrfs_node, ptrs);
786 item_size = sizeof(struct btrfs_key_ptr);
791 unsigned long offset;
792 struct btrfs_disk_key *tmp;
793 struct btrfs_disk_key unaligned;
796 mid = (low + high) / 2;
797 offset = p + mid * item_size;
798 oip = offset_in_page(offset);
800 if (oip + key_size <= PAGE_SIZE) {
801 const unsigned long idx = get_eb_page_index(offset);
802 char *kaddr = page_address(eb->pages[idx]);
804 oip = get_eb_offset_in_page(eb, offset);
805 tmp = (struct btrfs_disk_key *)(kaddr + oip);
807 read_extent_buffer(eb, &unaligned, offset, key_size);
811 ret = comp_keys(tmp, key);
827 * Simple binary search on an extent buffer. Works for both leaves and nodes, and
828 * always searches over the whole range of keys (slot 0 to slot 'nritems - 1').
830 int btrfs_bin_search(struct extent_buffer *eb, const struct btrfs_key *key,
833 return generic_bin_search(eb, 0, key, slot);
836 static void root_add_used(struct btrfs_root *root, u32 size)
838 spin_lock(&root->accounting_lock);
839 btrfs_set_root_used(&root->root_item,
840 btrfs_root_used(&root->root_item) + size);
841 spin_unlock(&root->accounting_lock);
844 static void root_sub_used(struct btrfs_root *root, u32 size)
846 spin_lock(&root->accounting_lock);
847 btrfs_set_root_used(&root->root_item,
848 btrfs_root_used(&root->root_item) - size);
849 spin_unlock(&root->accounting_lock);
852 /* given a node and slot number, this reads the blocks it points to. The
853 * extent buffer is returned with a reference taken (but unlocked).
855 struct extent_buffer *btrfs_read_node_slot(struct extent_buffer *parent,
858 int level = btrfs_header_level(parent);
859 struct extent_buffer *eb;
860 struct btrfs_key first_key;
862 if (slot < 0 || slot >= btrfs_header_nritems(parent))
863 return ERR_PTR(-ENOENT);
867 btrfs_node_key_to_cpu(parent, &first_key, slot);
868 eb = read_tree_block(parent->fs_info, btrfs_node_blockptr(parent, slot),
869 btrfs_header_owner(parent),
870 btrfs_node_ptr_generation(parent, slot),
871 level - 1, &first_key);
874 if (!extent_buffer_uptodate(eb)) {
875 free_extent_buffer(eb);
876 return ERR_PTR(-EIO);
883 * node level balancing, used to make sure nodes are in proper order for
884 * item deletion. We balance from the top down, so we have to make sure
885 * that a deletion won't leave an node completely empty later on.
887 static noinline int balance_level(struct btrfs_trans_handle *trans,
888 struct btrfs_root *root,
889 struct btrfs_path *path, int level)
891 struct btrfs_fs_info *fs_info = root->fs_info;
892 struct extent_buffer *right = NULL;
893 struct extent_buffer *mid;
894 struct extent_buffer *left = NULL;
895 struct extent_buffer *parent = NULL;
899 int orig_slot = path->slots[level];
904 mid = path->nodes[level];
906 WARN_ON(path->locks[level] != BTRFS_WRITE_LOCK);
907 WARN_ON(btrfs_header_generation(mid) != trans->transid);
909 orig_ptr = btrfs_node_blockptr(mid, orig_slot);
911 if (level < BTRFS_MAX_LEVEL - 1) {
912 parent = path->nodes[level + 1];
913 pslot = path->slots[level + 1];
917 * deal with the case where there is only one pointer in the root
918 * by promoting the node below to a root
921 struct extent_buffer *child;
923 if (btrfs_header_nritems(mid) != 1)
926 /* promote the child to a root */
927 child = btrfs_read_node_slot(mid, 0);
929 ret = PTR_ERR(child);
930 btrfs_handle_fs_error(fs_info, ret, NULL);
934 btrfs_tree_lock(child);
935 ret = btrfs_cow_block(trans, root, child, mid, 0, &child,
938 btrfs_tree_unlock(child);
939 free_extent_buffer(child);
943 ret = btrfs_tree_mod_log_insert_root(root->node, child, true);
945 rcu_assign_pointer(root->node, child);
947 add_root_to_dirty_list(root);
948 btrfs_tree_unlock(child);
950 path->locks[level] = 0;
951 path->nodes[level] = NULL;
952 btrfs_clean_tree_block(mid);
953 btrfs_tree_unlock(mid);
954 /* once for the path */
955 free_extent_buffer(mid);
957 root_sub_used(root, mid->len);
958 btrfs_free_tree_block(trans, btrfs_root_id(root), mid, 0, 1);
959 /* once for the root ptr */
960 free_extent_buffer_stale(mid);
963 if (btrfs_header_nritems(mid) >
964 BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 4)
967 left = btrfs_read_node_slot(parent, pslot - 1);
972 __btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
973 wret = btrfs_cow_block(trans, root, left,
974 parent, pslot - 1, &left,
975 BTRFS_NESTING_LEFT_COW);
982 right = btrfs_read_node_slot(parent, pslot + 1);
987 __btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
988 wret = btrfs_cow_block(trans, root, right,
989 parent, pslot + 1, &right,
990 BTRFS_NESTING_RIGHT_COW);
997 /* first, try to make some room in the middle buffer */
999 orig_slot += btrfs_header_nritems(left);
1000 wret = push_node_left(trans, left, mid, 1);
1006 * then try to empty the right most buffer into the middle
1009 wret = push_node_left(trans, mid, right, 1);
1010 if (wret < 0 && wret != -ENOSPC)
1012 if (btrfs_header_nritems(right) == 0) {
1013 btrfs_clean_tree_block(right);
1014 btrfs_tree_unlock(right);
1015 del_ptr(root, path, level + 1, pslot + 1);
1016 root_sub_used(root, right->len);
1017 btrfs_free_tree_block(trans, btrfs_root_id(root), right,
1019 free_extent_buffer_stale(right);
1022 struct btrfs_disk_key right_key;
1023 btrfs_node_key(right, &right_key, 0);
1024 ret = btrfs_tree_mod_log_insert_key(parent, pslot + 1,
1025 BTRFS_MOD_LOG_KEY_REPLACE);
1027 btrfs_set_node_key(parent, &right_key, pslot + 1);
1028 btrfs_mark_buffer_dirty(parent);
1031 if (btrfs_header_nritems(mid) == 1) {
1033 * we're not allowed to leave a node with one item in the
1034 * tree during a delete. A deletion from lower in the tree
1035 * could try to delete the only pointer in this node.
1036 * So, pull some keys from the left.
1037 * There has to be a left pointer at this point because
1038 * otherwise we would have pulled some pointers from the
1043 btrfs_handle_fs_error(fs_info, ret, NULL);
1046 wret = balance_node_right(trans, mid, left);
1052 wret = push_node_left(trans, left, mid, 1);
1058 if (btrfs_header_nritems(mid) == 0) {
1059 btrfs_clean_tree_block(mid);
1060 btrfs_tree_unlock(mid);
1061 del_ptr(root, path, level + 1, pslot);
1062 root_sub_used(root, mid->len);
1063 btrfs_free_tree_block(trans, btrfs_root_id(root), mid, 0, 1);
1064 free_extent_buffer_stale(mid);
1067 /* update the parent key to reflect our changes */
1068 struct btrfs_disk_key mid_key;
1069 btrfs_node_key(mid, &mid_key, 0);
1070 ret = btrfs_tree_mod_log_insert_key(parent, pslot,
1071 BTRFS_MOD_LOG_KEY_REPLACE);
1073 btrfs_set_node_key(parent, &mid_key, pslot);
1074 btrfs_mark_buffer_dirty(parent);
1077 /* update the path */
1079 if (btrfs_header_nritems(left) > orig_slot) {
1080 atomic_inc(&left->refs);
1081 /* left was locked after cow */
1082 path->nodes[level] = left;
1083 path->slots[level + 1] -= 1;
1084 path->slots[level] = orig_slot;
1086 btrfs_tree_unlock(mid);
1087 free_extent_buffer(mid);
1090 orig_slot -= btrfs_header_nritems(left);
1091 path->slots[level] = orig_slot;
1094 /* double check we haven't messed things up */
1096 btrfs_node_blockptr(path->nodes[level], path->slots[level]))
1100 btrfs_tree_unlock(right);
1101 free_extent_buffer(right);
1104 if (path->nodes[level] != left)
1105 btrfs_tree_unlock(left);
1106 free_extent_buffer(left);
1111 /* Node balancing for insertion. Here we only split or push nodes around
1112 * when they are completely full. This is also done top down, so we
1113 * have to be pessimistic.
1115 static noinline int push_nodes_for_insert(struct btrfs_trans_handle *trans,
1116 struct btrfs_root *root,
1117 struct btrfs_path *path, int level)
1119 struct btrfs_fs_info *fs_info = root->fs_info;
1120 struct extent_buffer *right = NULL;
1121 struct extent_buffer *mid;
1122 struct extent_buffer *left = NULL;
1123 struct extent_buffer *parent = NULL;
1127 int orig_slot = path->slots[level];
1132 mid = path->nodes[level];
1133 WARN_ON(btrfs_header_generation(mid) != trans->transid);
1135 if (level < BTRFS_MAX_LEVEL - 1) {
1136 parent = path->nodes[level + 1];
1137 pslot = path->slots[level + 1];
1143 left = btrfs_read_node_slot(parent, pslot - 1);
1147 /* first, try to make some room in the middle buffer */
1151 __btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
1153 left_nr = btrfs_header_nritems(left);
1154 if (left_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
1157 ret = btrfs_cow_block(trans, root, left, parent,
1159 BTRFS_NESTING_LEFT_COW);
1163 wret = push_node_left(trans, left, mid, 0);
1169 struct btrfs_disk_key disk_key;
1170 orig_slot += left_nr;
1171 btrfs_node_key(mid, &disk_key, 0);
1172 ret = btrfs_tree_mod_log_insert_key(parent, pslot,
1173 BTRFS_MOD_LOG_KEY_REPLACE);
1175 btrfs_set_node_key(parent, &disk_key, pslot);
1176 btrfs_mark_buffer_dirty(parent);
1177 if (btrfs_header_nritems(left) > orig_slot) {
1178 path->nodes[level] = left;
1179 path->slots[level + 1] -= 1;
1180 path->slots[level] = orig_slot;
1181 btrfs_tree_unlock(mid);
1182 free_extent_buffer(mid);
1185 btrfs_header_nritems(left);
1186 path->slots[level] = orig_slot;
1187 btrfs_tree_unlock(left);
1188 free_extent_buffer(left);
1192 btrfs_tree_unlock(left);
1193 free_extent_buffer(left);
1195 right = btrfs_read_node_slot(parent, pslot + 1);
1200 * then try to empty the right most buffer into the middle
1205 __btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
1207 right_nr = btrfs_header_nritems(right);
1208 if (right_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
1211 ret = btrfs_cow_block(trans, root, right,
1213 &right, BTRFS_NESTING_RIGHT_COW);
1217 wret = balance_node_right(trans, right, mid);
1223 struct btrfs_disk_key disk_key;
1225 btrfs_node_key(right, &disk_key, 0);
1226 ret = btrfs_tree_mod_log_insert_key(parent, pslot + 1,
1227 BTRFS_MOD_LOG_KEY_REPLACE);
1229 btrfs_set_node_key(parent, &disk_key, pslot + 1);
1230 btrfs_mark_buffer_dirty(parent);
1232 if (btrfs_header_nritems(mid) <= orig_slot) {
1233 path->nodes[level] = right;
1234 path->slots[level + 1] += 1;
1235 path->slots[level] = orig_slot -
1236 btrfs_header_nritems(mid);
1237 btrfs_tree_unlock(mid);
1238 free_extent_buffer(mid);
1240 btrfs_tree_unlock(right);
1241 free_extent_buffer(right);
1245 btrfs_tree_unlock(right);
1246 free_extent_buffer(right);
1252 * readahead one full node of leaves, finding things that are close
1253 * to the block in 'slot', and triggering ra on them.
1255 static void reada_for_search(struct btrfs_fs_info *fs_info,
1256 struct btrfs_path *path,
1257 int level, int slot, u64 objectid)
1259 struct extent_buffer *node;
1260 struct btrfs_disk_key disk_key;
1270 if (level != 1 && path->reada != READA_FORWARD_ALWAYS)
1273 if (!path->nodes[level])
1276 node = path->nodes[level];
1279 * Since the time between visiting leaves is much shorter than the time
1280 * between visiting nodes, limit read ahead of nodes to 1, to avoid too
1281 * much IO at once (possibly random).
1283 if (path->reada == READA_FORWARD_ALWAYS) {
1285 nread_max = node->fs_info->nodesize;
1287 nread_max = SZ_128K;
1292 search = btrfs_node_blockptr(node, slot);
1293 blocksize = fs_info->nodesize;
1294 if (path->reada != READA_FORWARD_ALWAYS) {
1295 struct extent_buffer *eb;
1297 eb = find_extent_buffer(fs_info, search);
1299 free_extent_buffer(eb);
1306 nritems = btrfs_header_nritems(node);
1310 if (path->reada == READA_BACK) {
1314 } else if (path->reada == READA_FORWARD ||
1315 path->reada == READA_FORWARD_ALWAYS) {
1320 if (path->reada == READA_BACK && objectid) {
1321 btrfs_node_key(node, &disk_key, nr);
1322 if (btrfs_disk_key_objectid(&disk_key) != objectid)
1325 search = btrfs_node_blockptr(node, nr);
1326 if (path->reada == READA_FORWARD_ALWAYS ||
1327 (search <= target && target - search <= 65536) ||
1328 (search > target && search - target <= 65536)) {
1329 btrfs_readahead_node_child(node, nr);
1333 if (nread > nread_max || nscan > 32)
1338 static noinline void reada_for_balance(struct btrfs_path *path, int level)
1340 struct extent_buffer *parent;
1344 parent = path->nodes[level + 1];
1348 nritems = btrfs_header_nritems(parent);
1349 slot = path->slots[level + 1];
1352 btrfs_readahead_node_child(parent, slot - 1);
1353 if (slot + 1 < nritems)
1354 btrfs_readahead_node_child(parent, slot + 1);
1359 * when we walk down the tree, it is usually safe to unlock the higher layers
1360 * in the tree. The exceptions are when our path goes through slot 0, because
1361 * operations on the tree might require changing key pointers higher up in the
1364 * callers might also have set path->keep_locks, which tells this code to keep
1365 * the lock if the path points to the last slot in the block. This is part of
1366 * walking through the tree, and selecting the next slot in the higher block.
1368 * lowest_unlock sets the lowest level in the tree we're allowed to unlock. so
1369 * if lowest_unlock is 1, level 0 won't be unlocked
1371 static noinline void unlock_up(struct btrfs_path *path, int level,
1372 int lowest_unlock, int min_write_lock_level,
1373 int *write_lock_level)
1376 int skip_level = level;
1377 bool check_skip = true;
1379 for (i = level; i < BTRFS_MAX_LEVEL; i++) {
1380 if (!path->nodes[i])
1382 if (!path->locks[i])
1386 if (path->slots[i] == 0) {
1391 if (path->keep_locks) {
1394 nritems = btrfs_header_nritems(path->nodes[i]);
1395 if (nritems < 1 || path->slots[i] >= nritems - 1) {
1402 if (i >= lowest_unlock && i > skip_level) {
1404 btrfs_tree_unlock_rw(path->nodes[i], path->locks[i]);
1406 if (write_lock_level &&
1407 i > min_write_lock_level &&
1408 i <= *write_lock_level) {
1409 *write_lock_level = i - 1;
1416 * Helper function for btrfs_search_slot() and other functions that do a search
1417 * on a btree. The goal is to find a tree block in the cache (the radix tree at
1418 * fs_info->buffer_radix), but if we can't find it, or it's not up to date, read
1419 * its pages from disk.
1421 * Returns -EAGAIN, with the path unlocked, if the caller needs to repeat the
1422 * whole btree search, starting again from the current root node.
1425 read_block_for_search(struct btrfs_root *root, struct btrfs_path *p,
1426 struct extent_buffer **eb_ret, int level, int slot,
1427 const struct btrfs_key *key)
1429 struct btrfs_fs_info *fs_info = root->fs_info;
1432 struct extent_buffer *tmp;
1433 struct btrfs_key first_key;
1438 unlock_up = ((level + 1 < BTRFS_MAX_LEVEL) && p->locks[level + 1]);
1439 blocknr = btrfs_node_blockptr(*eb_ret, slot);
1440 gen = btrfs_node_ptr_generation(*eb_ret, slot);
1441 parent_level = btrfs_header_level(*eb_ret);
1442 btrfs_node_key_to_cpu(*eb_ret, &first_key, slot);
1445 * If we need to read an extent buffer from disk and we are holding locks
1446 * on upper level nodes, we unlock all the upper nodes before reading the
1447 * extent buffer, and then return -EAGAIN to the caller as it needs to
1448 * restart the search. We don't release the lock on the current level
1449 * because we need to walk this node to figure out which blocks to read.
1451 tmp = find_extent_buffer(fs_info, blocknr);
1453 if (p->reada == READA_FORWARD_ALWAYS)
1454 reada_for_search(fs_info, p, level, slot, key->objectid);
1456 /* first we do an atomic uptodate check */
1457 if (btrfs_buffer_uptodate(tmp, gen, 1) > 0) {
1459 * Do extra check for first_key, eb can be stale due to
1460 * being cached, read from scrub, or have multiple
1461 * parents (shared tree blocks).
1463 if (btrfs_verify_level_key(tmp,
1464 parent_level - 1, &first_key, gen)) {
1465 free_extent_buffer(tmp);
1473 free_extent_buffer(tmp);
1478 btrfs_unlock_up_safe(p, level + 1);
1480 /* now we're allowed to do a blocking uptodate check */
1481 ret = btrfs_read_extent_buffer(tmp, gen, parent_level - 1, &first_key);
1483 free_extent_buffer(tmp);
1484 btrfs_release_path(p);
1487 if (btrfs_check_eb_owner(tmp, root->root_key.objectid)) {
1488 free_extent_buffer(tmp);
1489 btrfs_release_path(p);
1497 } else if (p->nowait) {
1502 btrfs_unlock_up_safe(p, level + 1);
1508 if (p->reada != READA_NONE)
1509 reada_for_search(fs_info, p, level, slot, key->objectid);
1511 tmp = read_tree_block(fs_info, blocknr, root->root_key.objectid,
1512 gen, parent_level - 1, &first_key);
1514 btrfs_release_path(p);
1515 return PTR_ERR(tmp);
1518 * If the read above didn't mark this buffer up to date,
1519 * it will never end up being up to date. Set ret to EIO now
1520 * and give up so that our caller doesn't loop forever
1523 if (!extent_buffer_uptodate(tmp))
1530 free_extent_buffer(tmp);
1531 btrfs_release_path(p);
1538 * helper function for btrfs_search_slot. This does all of the checks
1539 * for node-level blocks and does any balancing required based on
1542 * If no extra work was required, zero is returned. If we had to
1543 * drop the path, -EAGAIN is returned and btrfs_search_slot must
1547 setup_nodes_for_search(struct btrfs_trans_handle *trans,
1548 struct btrfs_root *root, struct btrfs_path *p,
1549 struct extent_buffer *b, int level, int ins_len,
1550 int *write_lock_level)
1552 struct btrfs_fs_info *fs_info = root->fs_info;
1555 if ((p->search_for_split || ins_len > 0) && btrfs_header_nritems(b) >=
1556 BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3) {
1558 if (*write_lock_level < level + 1) {
1559 *write_lock_level = level + 1;
1560 btrfs_release_path(p);
1564 reada_for_balance(p, level);
1565 ret = split_node(trans, root, p, level);
1567 b = p->nodes[level];
1568 } else if (ins_len < 0 && btrfs_header_nritems(b) <
1569 BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 2) {
1571 if (*write_lock_level < level + 1) {
1572 *write_lock_level = level + 1;
1573 btrfs_release_path(p);
1577 reada_for_balance(p, level);
1578 ret = balance_level(trans, root, p, level);
1582 b = p->nodes[level];
1584 btrfs_release_path(p);
1587 BUG_ON(btrfs_header_nritems(b) == 1);
1592 int btrfs_find_item(struct btrfs_root *fs_root, struct btrfs_path *path,
1593 u64 iobjectid, u64 ioff, u8 key_type,
1594 struct btrfs_key *found_key)
1597 struct btrfs_key key;
1598 struct extent_buffer *eb;
1603 key.type = key_type;
1604 key.objectid = iobjectid;
1607 ret = btrfs_search_slot(NULL, fs_root, &key, path, 0, 0);
1611 eb = path->nodes[0];
1612 if (ret && path->slots[0] >= btrfs_header_nritems(eb)) {
1613 ret = btrfs_next_leaf(fs_root, path);
1616 eb = path->nodes[0];
1619 btrfs_item_key_to_cpu(eb, found_key, path->slots[0]);
1620 if (found_key->type != key.type ||
1621 found_key->objectid != key.objectid)
1627 static struct extent_buffer *btrfs_search_slot_get_root(struct btrfs_root *root,
1628 struct btrfs_path *p,
1629 int write_lock_level)
1631 struct extent_buffer *b;
1635 if (p->search_commit_root) {
1636 b = root->commit_root;
1637 atomic_inc(&b->refs);
1638 level = btrfs_header_level(b);
1640 * Ensure that all callers have set skip_locking when
1641 * p->search_commit_root = 1.
1643 ASSERT(p->skip_locking == 1);
1648 if (p->skip_locking) {
1649 b = btrfs_root_node(root);
1650 level = btrfs_header_level(b);
1654 /* We try very hard to do read locks on the root */
1655 root_lock = BTRFS_READ_LOCK;
1658 * If the level is set to maximum, we can skip trying to get the read
1661 if (write_lock_level < BTRFS_MAX_LEVEL) {
1663 * We don't know the level of the root node until we actually
1664 * have it read locked
1667 b = btrfs_try_read_lock_root_node(root);
1671 b = btrfs_read_lock_root_node(root);
1673 level = btrfs_header_level(b);
1674 if (level > write_lock_level)
1677 /* Whoops, must trade for write lock */
1678 btrfs_tree_read_unlock(b);
1679 free_extent_buffer(b);
1682 b = btrfs_lock_root_node(root);
1683 root_lock = BTRFS_WRITE_LOCK;
1685 /* The level might have changed, check again */
1686 level = btrfs_header_level(b);
1690 * The root may have failed to write out at some point, and thus is no
1691 * longer valid, return an error in this case.
1693 if (!extent_buffer_uptodate(b)) {
1695 btrfs_tree_unlock_rw(b, root_lock);
1696 free_extent_buffer(b);
1697 return ERR_PTR(-EIO);
1700 p->nodes[level] = b;
1701 if (!p->skip_locking)
1702 p->locks[level] = root_lock;
1704 * Callers are responsible for dropping b's references.
1710 * Replace the extent buffer at the lowest level of the path with a cloned
1711 * version. The purpose is to be able to use it safely, after releasing the
1712 * commit root semaphore, even if relocation is happening in parallel, the
1713 * transaction used for relocation is committed and the extent buffer is
1714 * reallocated in the next transaction.
1716 * This is used in a context where the caller does not prevent transaction
1717 * commits from happening, either by holding a transaction handle or holding
1718 * some lock, while it's doing searches through a commit root.
1719 * At the moment it's only used for send operations.
1721 static int finish_need_commit_sem_search(struct btrfs_path *path)
1723 const int i = path->lowest_level;
1724 const int slot = path->slots[i];
1725 struct extent_buffer *lowest = path->nodes[i];
1726 struct extent_buffer *clone;
1728 ASSERT(path->need_commit_sem);
1733 lockdep_assert_held_read(&lowest->fs_info->commit_root_sem);
1735 clone = btrfs_clone_extent_buffer(lowest);
1739 btrfs_release_path(path);
1740 path->nodes[i] = clone;
1741 path->slots[i] = slot;
1746 static inline int search_for_key_slot(struct extent_buffer *eb,
1747 int search_low_slot,
1748 const struct btrfs_key *key,
1753 * If a previous call to btrfs_bin_search() on a parent node returned an
1754 * exact match (prev_cmp == 0), we can safely assume the target key will
1755 * always be at slot 0 on lower levels, since each key pointer
1756 * (struct btrfs_key_ptr) refers to the lowest key accessible from the
1757 * subtree it points to. Thus we can skip searching lower levels.
1759 if (prev_cmp == 0) {
1764 return generic_bin_search(eb, search_low_slot, key, slot);
1767 static int search_leaf(struct btrfs_trans_handle *trans,
1768 struct btrfs_root *root,
1769 const struct btrfs_key *key,
1770 struct btrfs_path *path,
1774 struct extent_buffer *leaf = path->nodes[0];
1775 int leaf_free_space = -1;
1776 int search_low_slot = 0;
1778 bool do_bin_search = true;
1781 * If we are doing an insertion, the leaf has enough free space and the
1782 * destination slot for the key is not slot 0, then we can unlock our
1783 * write lock on the parent, and any other upper nodes, before doing the
1784 * binary search on the leaf (with search_for_key_slot()), allowing other
1785 * tasks to lock the parent and any other upper nodes.
1789 * Cache the leaf free space, since we will need it later and it
1790 * will not change until then.
1792 leaf_free_space = btrfs_leaf_free_space(leaf);
1795 * !path->locks[1] means we have a single node tree, the leaf is
1796 * the root of the tree.
1798 if (path->locks[1] && leaf_free_space >= ins_len) {
1799 struct btrfs_disk_key first_key;
1801 ASSERT(btrfs_header_nritems(leaf) > 0);
1802 btrfs_item_key(leaf, &first_key, 0);
1805 * Doing the extra comparison with the first key is cheap,
1806 * taking into account that the first key is very likely
1807 * already in a cache line because it immediately follows
1808 * the extent buffer's header and we have recently accessed
1809 * the header's level field.
1811 ret = comp_keys(&first_key, key);
1814 * The first key is smaller than the key we want
1815 * to insert, so we are safe to unlock all upper
1816 * nodes and we have to do the binary search.
1818 * We do use btrfs_unlock_up_safe() and not
1819 * unlock_up() because the later does not unlock
1820 * nodes with a slot of 0 - we can safely unlock
1821 * any node even if its slot is 0 since in this
1822 * case the key does not end up at slot 0 of the
1823 * leaf and there's no need to split the leaf.
1825 btrfs_unlock_up_safe(path, 1);
1826 search_low_slot = 1;
1829 * The first key is >= then the key we want to
1830 * insert, so we can skip the binary search as
1831 * the target key will be at slot 0.
1833 * We can not unlock upper nodes when the key is
1834 * less than the first key, because we will need
1835 * to update the key at slot 0 of the parent node
1836 * and possibly of other upper nodes too.
1837 * If the key matches the first key, then we can
1838 * unlock all the upper nodes, using
1839 * btrfs_unlock_up_safe() instead of unlock_up()
1843 btrfs_unlock_up_safe(path, 1);
1845 * ret is already 0 or 1, matching the result of
1846 * a btrfs_bin_search() call, so there is no need
1849 do_bin_search = false;
1855 if (do_bin_search) {
1856 ret = search_for_key_slot(leaf, search_low_slot, key,
1857 prev_cmp, &path->slots[0]);
1864 * Item key already exists. In this case, if we are allowed to
1865 * insert the item (for example, in dir_item case, item key
1866 * collision is allowed), it will be merged with the original
1867 * item. Only the item size grows, no new btrfs item will be
1868 * added. If search_for_extension is not set, ins_len already
1869 * accounts the size btrfs_item, deduct it here so leaf space
1870 * check will be correct.
1872 if (ret == 0 && !path->search_for_extension) {
1873 ASSERT(ins_len >= sizeof(struct btrfs_item));
1874 ins_len -= sizeof(struct btrfs_item);
1877 ASSERT(leaf_free_space >= 0);
1879 if (leaf_free_space < ins_len) {
1882 err = split_leaf(trans, root, key, path, ins_len,
1885 if (WARN_ON(err > 0))
1896 * btrfs_search_slot - look for a key in a tree and perform necessary
1897 * modifications to preserve tree invariants.
1899 * @trans: Handle of transaction, used when modifying the tree
1900 * @p: Holds all btree nodes along the search path
1901 * @root: The root node of the tree
1902 * @key: The key we are looking for
1903 * @ins_len: Indicates purpose of search:
1904 * >0 for inserts it's size of item inserted (*)
1906 * 0 for plain searches, not modifying the tree
1908 * (*) If size of item inserted doesn't include
1909 * sizeof(struct btrfs_item), then p->search_for_extension must
1911 * @cow: boolean should CoW operations be performed. Must always be 1
1912 * when modifying the tree.
1914 * If @ins_len > 0, nodes and leaves will be split as we walk down the tree.
1915 * If @ins_len < 0, nodes will be merged as we walk down the tree (if possible)
1917 * If @key is found, 0 is returned and you can find the item in the leaf level
1918 * of the path (level 0)
1920 * If @key isn't found, 1 is returned and the leaf level of the path (level 0)
1921 * points to the slot where it should be inserted
1923 * If an error is encountered while searching the tree a negative error number
1926 int btrfs_search_slot(struct btrfs_trans_handle *trans, struct btrfs_root *root,
1927 const struct btrfs_key *key, struct btrfs_path *p,
1928 int ins_len, int cow)
1930 struct btrfs_fs_info *fs_info = root->fs_info;
1931 struct extent_buffer *b;
1936 int lowest_unlock = 1;
1937 /* everything at write_lock_level or lower must be write locked */
1938 int write_lock_level = 0;
1939 u8 lowest_level = 0;
1940 int min_write_lock_level;
1943 lowest_level = p->lowest_level;
1944 WARN_ON(lowest_level && ins_len > 0);
1945 WARN_ON(p->nodes[0] != NULL);
1946 BUG_ON(!cow && ins_len);
1949 * For now only allow nowait for read only operations. There's no
1950 * strict reason why we can't, we just only need it for reads so it's
1951 * only implemented for reads.
1953 ASSERT(!p->nowait || !cow);
1958 /* when we are removing items, we might have to go up to level
1959 * two as we update tree pointers Make sure we keep write
1960 * for those levels as well
1962 write_lock_level = 2;
1963 } else if (ins_len > 0) {
1965 * for inserting items, make sure we have a write lock on
1966 * level 1 so we can update keys
1968 write_lock_level = 1;
1972 write_lock_level = -1;
1974 if (cow && (p->keep_locks || p->lowest_level))
1975 write_lock_level = BTRFS_MAX_LEVEL;
1977 min_write_lock_level = write_lock_level;
1979 if (p->need_commit_sem) {
1980 ASSERT(p->search_commit_root);
1982 if (!down_read_trylock(&fs_info->commit_root_sem))
1985 down_read(&fs_info->commit_root_sem);
1991 b = btrfs_search_slot_get_root(root, p, write_lock_level);
2000 level = btrfs_header_level(b);
2003 bool last_level = (level == (BTRFS_MAX_LEVEL - 1));
2006 * if we don't really need to cow this block
2007 * then we don't want to set the path blocking,
2008 * so we test it here
2010 if (!should_cow_block(trans, root, b))
2014 * must have write locks on this node and the
2017 if (level > write_lock_level ||
2018 (level + 1 > write_lock_level &&
2019 level + 1 < BTRFS_MAX_LEVEL &&
2020 p->nodes[level + 1])) {
2021 write_lock_level = level + 1;
2022 btrfs_release_path(p);
2027 err = btrfs_cow_block(trans, root, b, NULL, 0,
2031 err = btrfs_cow_block(trans, root, b,
2032 p->nodes[level + 1],
2033 p->slots[level + 1], &b,
2041 p->nodes[level] = b;
2044 * we have a lock on b and as long as we aren't changing
2045 * the tree, there is no way to for the items in b to change.
2046 * It is safe to drop the lock on our parent before we
2047 * go through the expensive btree search on b.
2049 * If we're inserting or deleting (ins_len != 0), then we might
2050 * be changing slot zero, which may require changing the parent.
2051 * So, we can't drop the lock until after we know which slot
2052 * we're operating on.
2054 if (!ins_len && !p->keep_locks) {
2057 if (u < BTRFS_MAX_LEVEL && p->locks[u]) {
2058 btrfs_tree_unlock_rw(p->nodes[u], p->locks[u]);
2065 ASSERT(write_lock_level >= 1);
2067 ret = search_leaf(trans, root, key, p, ins_len, prev_cmp);
2068 if (!p->search_for_split)
2069 unlock_up(p, level, lowest_unlock,
2070 min_write_lock_level, NULL);
2074 ret = search_for_key_slot(b, 0, key, prev_cmp, &slot);
2079 if (ret && slot > 0) {
2083 p->slots[level] = slot;
2084 err = setup_nodes_for_search(trans, root, p, b, level, ins_len,
2092 b = p->nodes[level];
2093 slot = p->slots[level];
2096 * Slot 0 is special, if we change the key we have to update
2097 * the parent pointer which means we must have a write lock on
2100 if (slot == 0 && ins_len && write_lock_level < level + 1) {
2101 write_lock_level = level + 1;
2102 btrfs_release_path(p);
2106 unlock_up(p, level, lowest_unlock, min_write_lock_level,
2109 if (level == lowest_level) {
2115 err = read_block_for_search(root, p, &b, level, slot, key);
2123 if (!p->skip_locking) {
2124 level = btrfs_header_level(b);
2126 btrfs_maybe_reset_lockdep_class(root, b);
2128 if (level <= write_lock_level) {
2130 p->locks[level] = BTRFS_WRITE_LOCK;
2133 if (!btrfs_try_tree_read_lock(b)) {
2134 free_extent_buffer(b);
2139 btrfs_tree_read_lock(b);
2141 p->locks[level] = BTRFS_READ_LOCK;
2143 p->nodes[level] = b;
2148 if (ret < 0 && !p->skip_release_on_error)
2149 btrfs_release_path(p);
2151 if (p->need_commit_sem) {
2154 ret2 = finish_need_commit_sem_search(p);
2155 up_read(&fs_info->commit_root_sem);
2162 ALLOW_ERROR_INJECTION(btrfs_search_slot, ERRNO);
2165 * Like btrfs_search_slot, this looks for a key in the given tree. It uses the
2166 * current state of the tree together with the operations recorded in the tree
2167 * modification log to search for the key in a previous version of this tree, as
2168 * denoted by the time_seq parameter.
2170 * Naturally, there is no support for insert, delete or cow operations.
2172 * The resulting path and return value will be set up as if we called
2173 * btrfs_search_slot at that point in time with ins_len and cow both set to 0.
2175 int btrfs_search_old_slot(struct btrfs_root *root, const struct btrfs_key *key,
2176 struct btrfs_path *p, u64 time_seq)
2178 struct btrfs_fs_info *fs_info = root->fs_info;
2179 struct extent_buffer *b;
2184 int lowest_unlock = 1;
2185 u8 lowest_level = 0;
2187 lowest_level = p->lowest_level;
2188 WARN_ON(p->nodes[0] != NULL);
2191 if (p->search_commit_root) {
2193 return btrfs_search_slot(NULL, root, key, p, 0, 0);
2197 b = btrfs_get_old_root(root, time_seq);
2202 level = btrfs_header_level(b);
2203 p->locks[level] = BTRFS_READ_LOCK;
2208 level = btrfs_header_level(b);
2209 p->nodes[level] = b;
2212 * we have a lock on b and as long as we aren't changing
2213 * the tree, there is no way to for the items in b to change.
2214 * It is safe to drop the lock on our parent before we
2215 * go through the expensive btree search on b.
2217 btrfs_unlock_up_safe(p, level + 1);
2219 ret = btrfs_bin_search(b, key, &slot);
2224 p->slots[level] = slot;
2225 unlock_up(p, level, lowest_unlock, 0, NULL);
2229 if (ret && slot > 0) {
2233 p->slots[level] = slot;
2234 unlock_up(p, level, lowest_unlock, 0, NULL);
2236 if (level == lowest_level) {
2242 err = read_block_for_search(root, p, &b, level, slot, key);
2250 level = btrfs_header_level(b);
2251 btrfs_tree_read_lock(b);
2252 b = btrfs_tree_mod_log_rewind(fs_info, p, b, time_seq);
2257 p->locks[level] = BTRFS_READ_LOCK;
2258 p->nodes[level] = b;
2263 btrfs_release_path(p);
2269 * helper to use instead of search slot if no exact match is needed but
2270 * instead the next or previous item should be returned.
2271 * When find_higher is true, the next higher item is returned, the next lower
2273 * When return_any and find_higher are both true, and no higher item is found,
2274 * return the next lower instead.
2275 * When return_any is true and find_higher is false, and no lower item is found,
2276 * return the next higher instead.
2277 * It returns 0 if any item is found, 1 if none is found (tree empty), and
2280 int btrfs_search_slot_for_read(struct btrfs_root *root,
2281 const struct btrfs_key *key,
2282 struct btrfs_path *p, int find_higher,
2286 struct extent_buffer *leaf;
2289 ret = btrfs_search_slot(NULL, root, key, p, 0, 0);
2293 * a return value of 1 means the path is at the position where the
2294 * item should be inserted. Normally this is the next bigger item,
2295 * but in case the previous item is the last in a leaf, path points
2296 * to the first free slot in the previous leaf, i.e. at an invalid
2302 if (p->slots[0] >= btrfs_header_nritems(leaf)) {
2303 ret = btrfs_next_leaf(root, p);
2309 * no higher item found, return the next
2314 btrfs_release_path(p);
2318 if (p->slots[0] == 0) {
2319 ret = btrfs_prev_leaf(root, p);
2324 if (p->slots[0] == btrfs_header_nritems(leaf))
2331 * no lower item found, return the next
2336 btrfs_release_path(p);
2346 * Execute search and call btrfs_previous_item to traverse backwards if the item
2349 * Return 0 if found, 1 if not found and < 0 if error.
2351 int btrfs_search_backwards(struct btrfs_root *root, struct btrfs_key *key,
2352 struct btrfs_path *path)
2356 ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
2358 ret = btrfs_previous_item(root, path, key->objectid, key->type);
2361 btrfs_item_key_to_cpu(path->nodes[0], key, path->slots[0]);
2367 * Search for a valid slot for the given path.
2369 * @root: The root node of the tree.
2370 * @key: Will contain a valid item if found.
2371 * @path: The starting point to validate the slot.
2373 * Return: 0 if the item is valid
2377 int btrfs_get_next_valid_item(struct btrfs_root *root, struct btrfs_key *key,
2378 struct btrfs_path *path)
2382 const int slot = path->slots[0];
2383 const struct extent_buffer *leaf = path->nodes[0];
2385 /* This is where we start walking the path. */
2386 if (slot >= btrfs_header_nritems(leaf)) {
2388 * If we've reached the last slot in this leaf we need
2389 * to go to the next leaf and reset the path.
2391 ret = btrfs_next_leaf(root, path);
2396 /* Store the found, valid item in @key. */
2397 btrfs_item_key_to_cpu(leaf, key, slot);
2404 * adjust the pointers going up the tree, starting at level
2405 * making sure the right key of each node is points to 'key'.
2406 * This is used after shifting pointers to the left, so it stops
2407 * fixing up pointers when a given leaf/node is not in slot 0 of the
2411 static void fixup_low_keys(struct btrfs_path *path,
2412 struct btrfs_disk_key *key, int level)
2415 struct extent_buffer *t;
2418 for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2419 int tslot = path->slots[i];
2421 if (!path->nodes[i])
2424 ret = btrfs_tree_mod_log_insert_key(t, tslot,
2425 BTRFS_MOD_LOG_KEY_REPLACE);
2427 btrfs_set_node_key(t, key, tslot);
2428 btrfs_mark_buffer_dirty(path->nodes[i]);
2437 * This function isn't completely safe. It's the caller's responsibility
2438 * that the new key won't break the order
2440 void btrfs_set_item_key_safe(struct btrfs_fs_info *fs_info,
2441 struct btrfs_path *path,
2442 const struct btrfs_key *new_key)
2444 struct btrfs_disk_key disk_key;
2445 struct extent_buffer *eb;
2448 eb = path->nodes[0];
2449 slot = path->slots[0];
2451 btrfs_item_key(eb, &disk_key, slot - 1);
2452 if (unlikely(comp_keys(&disk_key, new_key) >= 0)) {
2454 "slot %u key (%llu %u %llu) new key (%llu %u %llu)",
2455 slot, btrfs_disk_key_objectid(&disk_key),
2456 btrfs_disk_key_type(&disk_key),
2457 btrfs_disk_key_offset(&disk_key),
2458 new_key->objectid, new_key->type,
2460 btrfs_print_leaf(eb);
2464 if (slot < btrfs_header_nritems(eb) - 1) {
2465 btrfs_item_key(eb, &disk_key, slot + 1);
2466 if (unlikely(comp_keys(&disk_key, new_key) <= 0)) {
2468 "slot %u key (%llu %u %llu) new key (%llu %u %llu)",
2469 slot, btrfs_disk_key_objectid(&disk_key),
2470 btrfs_disk_key_type(&disk_key),
2471 btrfs_disk_key_offset(&disk_key),
2472 new_key->objectid, new_key->type,
2474 btrfs_print_leaf(eb);
2479 btrfs_cpu_key_to_disk(&disk_key, new_key);
2480 btrfs_set_item_key(eb, &disk_key, slot);
2481 btrfs_mark_buffer_dirty(eb);
2483 fixup_low_keys(path, &disk_key, 1);
2487 * Check key order of two sibling extent buffers.
2489 * Return true if something is wrong.
2490 * Return false if everything is fine.
2492 * Tree-checker only works inside one tree block, thus the following
2493 * corruption can not be detected by tree-checker:
2495 * Leaf @left | Leaf @right
2496 * --------------------------------------------------------------
2497 * | 1 | 2 | 3 | 4 | 5 | f6 | | 7 | 8 |
2499 * Key f6 in leaf @left itself is valid, but not valid when the next
2500 * key in leaf @right is 7.
2501 * This can only be checked at tree block merge time.
2502 * And since tree checker has ensured all key order in each tree block
2503 * is correct, we only need to bother the last key of @left and the first
2506 static bool check_sibling_keys(struct extent_buffer *left,
2507 struct extent_buffer *right)
2509 struct btrfs_key left_last;
2510 struct btrfs_key right_first;
2511 int level = btrfs_header_level(left);
2512 int nr_left = btrfs_header_nritems(left);
2513 int nr_right = btrfs_header_nritems(right);
2515 /* No key to check in one of the tree blocks */
2516 if (!nr_left || !nr_right)
2520 btrfs_node_key_to_cpu(left, &left_last, nr_left - 1);
2521 btrfs_node_key_to_cpu(right, &right_first, 0);
2523 btrfs_item_key_to_cpu(left, &left_last, nr_left - 1);
2524 btrfs_item_key_to_cpu(right, &right_first, 0);
2527 if (btrfs_comp_cpu_keys(&left_last, &right_first) >= 0) {
2528 btrfs_crit(left->fs_info,
2529 "bad key order, sibling blocks, left last (%llu %u %llu) right first (%llu %u %llu)",
2530 left_last.objectid, left_last.type,
2531 left_last.offset, right_first.objectid,
2532 right_first.type, right_first.offset);
2539 * try to push data from one node into the next node left in the
2542 * returns 0 if some ptrs were pushed left, < 0 if there was some horrible
2543 * error, and > 0 if there was no room in the left hand block.
2545 static int push_node_left(struct btrfs_trans_handle *trans,
2546 struct extent_buffer *dst,
2547 struct extent_buffer *src, int empty)
2549 struct btrfs_fs_info *fs_info = trans->fs_info;
2555 src_nritems = btrfs_header_nritems(src);
2556 dst_nritems = btrfs_header_nritems(dst);
2557 push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
2558 WARN_ON(btrfs_header_generation(src) != trans->transid);
2559 WARN_ON(btrfs_header_generation(dst) != trans->transid);
2561 if (!empty && src_nritems <= 8)
2564 if (push_items <= 0)
2568 push_items = min(src_nritems, push_items);
2569 if (push_items < src_nritems) {
2570 /* leave at least 8 pointers in the node if
2571 * we aren't going to empty it
2573 if (src_nritems - push_items < 8) {
2574 if (push_items <= 8)
2580 push_items = min(src_nritems - 8, push_items);
2582 /* dst is the left eb, src is the middle eb */
2583 if (check_sibling_keys(dst, src)) {
2585 btrfs_abort_transaction(trans, ret);
2588 ret = btrfs_tree_mod_log_eb_copy(dst, src, dst_nritems, 0, push_items);
2590 btrfs_abort_transaction(trans, ret);
2593 copy_extent_buffer(dst, src,
2594 btrfs_node_key_ptr_offset(dst_nritems),
2595 btrfs_node_key_ptr_offset(0),
2596 push_items * sizeof(struct btrfs_key_ptr));
2598 if (push_items < src_nritems) {
2600 * Don't call btrfs_tree_mod_log_insert_move() here, key removal
2601 * was already fully logged by btrfs_tree_mod_log_eb_copy() above.
2603 memmove_extent_buffer(src, btrfs_node_key_ptr_offset(0),
2604 btrfs_node_key_ptr_offset(push_items),
2605 (src_nritems - push_items) *
2606 sizeof(struct btrfs_key_ptr));
2608 btrfs_set_header_nritems(src, src_nritems - push_items);
2609 btrfs_set_header_nritems(dst, dst_nritems + push_items);
2610 btrfs_mark_buffer_dirty(src);
2611 btrfs_mark_buffer_dirty(dst);
2617 * try to push data from one node into the next node right in the
2620 * returns 0 if some ptrs were pushed, < 0 if there was some horrible
2621 * error, and > 0 if there was no room in the right hand block.
2623 * this will only push up to 1/2 the contents of the left node over
2625 static int balance_node_right(struct btrfs_trans_handle *trans,
2626 struct extent_buffer *dst,
2627 struct extent_buffer *src)
2629 struct btrfs_fs_info *fs_info = trans->fs_info;
2636 WARN_ON(btrfs_header_generation(src) != trans->transid);
2637 WARN_ON(btrfs_header_generation(dst) != trans->transid);
2639 src_nritems = btrfs_header_nritems(src);
2640 dst_nritems = btrfs_header_nritems(dst);
2641 push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
2642 if (push_items <= 0)
2645 if (src_nritems < 4)
2648 max_push = src_nritems / 2 + 1;
2649 /* don't try to empty the node */
2650 if (max_push >= src_nritems)
2653 if (max_push < push_items)
2654 push_items = max_push;
2656 /* dst is the right eb, src is the middle eb */
2657 if (check_sibling_keys(src, dst)) {
2659 btrfs_abort_transaction(trans, ret);
2662 ret = btrfs_tree_mod_log_insert_move(dst, push_items, 0, dst_nritems);
2664 memmove_extent_buffer(dst, btrfs_node_key_ptr_offset(push_items),
2665 btrfs_node_key_ptr_offset(0),
2667 sizeof(struct btrfs_key_ptr));
2669 ret = btrfs_tree_mod_log_eb_copy(dst, src, 0, src_nritems - push_items,
2672 btrfs_abort_transaction(trans, ret);
2675 copy_extent_buffer(dst, src,
2676 btrfs_node_key_ptr_offset(0),
2677 btrfs_node_key_ptr_offset(src_nritems - push_items),
2678 push_items * sizeof(struct btrfs_key_ptr));
2680 btrfs_set_header_nritems(src, src_nritems - push_items);
2681 btrfs_set_header_nritems(dst, dst_nritems + push_items);
2683 btrfs_mark_buffer_dirty(src);
2684 btrfs_mark_buffer_dirty(dst);
2690 * helper function to insert a new root level in the tree.
2691 * A new node is allocated, and a single item is inserted to
2692 * point to the existing root
2694 * returns zero on success or < 0 on failure.
2696 static noinline int insert_new_root(struct btrfs_trans_handle *trans,
2697 struct btrfs_root *root,
2698 struct btrfs_path *path, int level)
2700 struct btrfs_fs_info *fs_info = root->fs_info;
2702 struct extent_buffer *lower;
2703 struct extent_buffer *c;
2704 struct extent_buffer *old;
2705 struct btrfs_disk_key lower_key;
2708 BUG_ON(path->nodes[level]);
2709 BUG_ON(path->nodes[level-1] != root->node);
2711 lower = path->nodes[level-1];
2713 btrfs_item_key(lower, &lower_key, 0);
2715 btrfs_node_key(lower, &lower_key, 0);
2717 c = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
2718 &lower_key, level, root->node->start, 0,
2719 BTRFS_NESTING_NEW_ROOT);
2723 root_add_used(root, fs_info->nodesize);
2725 btrfs_set_header_nritems(c, 1);
2726 btrfs_set_node_key(c, &lower_key, 0);
2727 btrfs_set_node_blockptr(c, 0, lower->start);
2728 lower_gen = btrfs_header_generation(lower);
2729 WARN_ON(lower_gen != trans->transid);
2731 btrfs_set_node_ptr_generation(c, 0, lower_gen);
2733 btrfs_mark_buffer_dirty(c);
2736 ret = btrfs_tree_mod_log_insert_root(root->node, c, false);
2738 rcu_assign_pointer(root->node, c);
2740 /* the super has an extra ref to root->node */
2741 free_extent_buffer(old);
2743 add_root_to_dirty_list(root);
2744 atomic_inc(&c->refs);
2745 path->nodes[level] = c;
2746 path->locks[level] = BTRFS_WRITE_LOCK;
2747 path->slots[level] = 0;
2752 * worker function to insert a single pointer in a node.
2753 * the node should have enough room for the pointer already
2755 * slot and level indicate where you want the key to go, and
2756 * blocknr is the block the key points to.
2758 static void insert_ptr(struct btrfs_trans_handle *trans,
2759 struct btrfs_path *path,
2760 struct btrfs_disk_key *key, u64 bytenr,
2761 int slot, int level)
2763 struct extent_buffer *lower;
2767 BUG_ON(!path->nodes[level]);
2768 btrfs_assert_tree_write_locked(path->nodes[level]);
2769 lower = path->nodes[level];
2770 nritems = btrfs_header_nritems(lower);
2771 BUG_ON(slot > nritems);
2772 BUG_ON(nritems == BTRFS_NODEPTRS_PER_BLOCK(trans->fs_info));
2773 if (slot != nritems) {
2775 ret = btrfs_tree_mod_log_insert_move(lower, slot + 1,
2776 slot, nritems - slot);
2779 memmove_extent_buffer(lower,
2780 btrfs_node_key_ptr_offset(slot + 1),
2781 btrfs_node_key_ptr_offset(slot),
2782 (nritems - slot) * sizeof(struct btrfs_key_ptr));
2785 ret = btrfs_tree_mod_log_insert_key(lower, slot,
2786 BTRFS_MOD_LOG_KEY_ADD);
2789 btrfs_set_node_key(lower, key, slot);
2790 btrfs_set_node_blockptr(lower, slot, bytenr);
2791 WARN_ON(trans->transid == 0);
2792 btrfs_set_node_ptr_generation(lower, slot, trans->transid);
2793 btrfs_set_header_nritems(lower, nritems + 1);
2794 btrfs_mark_buffer_dirty(lower);
2798 * split the node at the specified level in path in two.
2799 * The path is corrected to point to the appropriate node after the split
2801 * Before splitting this tries to make some room in the node by pushing
2802 * left and right, if either one works, it returns right away.
2804 * returns 0 on success and < 0 on failure
2806 static noinline int split_node(struct btrfs_trans_handle *trans,
2807 struct btrfs_root *root,
2808 struct btrfs_path *path, int level)
2810 struct btrfs_fs_info *fs_info = root->fs_info;
2811 struct extent_buffer *c;
2812 struct extent_buffer *split;
2813 struct btrfs_disk_key disk_key;
2818 c = path->nodes[level];
2819 WARN_ON(btrfs_header_generation(c) != trans->transid);
2820 if (c == root->node) {
2822 * trying to split the root, lets make a new one
2824 * tree mod log: We don't log_removal old root in
2825 * insert_new_root, because that root buffer will be kept as a
2826 * normal node. We are going to log removal of half of the
2827 * elements below with btrfs_tree_mod_log_eb_copy(). We're
2828 * holding a tree lock on the buffer, which is why we cannot
2829 * race with other tree_mod_log users.
2831 ret = insert_new_root(trans, root, path, level + 1);
2835 ret = push_nodes_for_insert(trans, root, path, level);
2836 c = path->nodes[level];
2837 if (!ret && btrfs_header_nritems(c) <
2838 BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3)
2844 c_nritems = btrfs_header_nritems(c);
2845 mid = (c_nritems + 1) / 2;
2846 btrfs_node_key(c, &disk_key, mid);
2848 split = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
2849 &disk_key, level, c->start, 0,
2850 BTRFS_NESTING_SPLIT);
2852 return PTR_ERR(split);
2854 root_add_used(root, fs_info->nodesize);
2855 ASSERT(btrfs_header_level(c) == level);
2857 ret = btrfs_tree_mod_log_eb_copy(split, c, 0, mid, c_nritems - mid);
2859 btrfs_abort_transaction(trans, ret);
2862 copy_extent_buffer(split, c,
2863 btrfs_node_key_ptr_offset(0),
2864 btrfs_node_key_ptr_offset(mid),
2865 (c_nritems - mid) * sizeof(struct btrfs_key_ptr));
2866 btrfs_set_header_nritems(split, c_nritems - mid);
2867 btrfs_set_header_nritems(c, mid);
2869 btrfs_mark_buffer_dirty(c);
2870 btrfs_mark_buffer_dirty(split);
2872 insert_ptr(trans, path, &disk_key, split->start,
2873 path->slots[level + 1] + 1, level + 1);
2875 if (path->slots[level] >= mid) {
2876 path->slots[level] -= mid;
2877 btrfs_tree_unlock(c);
2878 free_extent_buffer(c);
2879 path->nodes[level] = split;
2880 path->slots[level + 1] += 1;
2882 btrfs_tree_unlock(split);
2883 free_extent_buffer(split);
2889 * how many bytes are required to store the items in a leaf. start
2890 * and nr indicate which items in the leaf to check. This totals up the
2891 * space used both by the item structs and the item data
2893 static int leaf_space_used(struct extent_buffer *l, int start, int nr)
2896 int nritems = btrfs_header_nritems(l);
2897 int end = min(nritems, start + nr) - 1;
2901 data_len = btrfs_item_offset(l, start) + btrfs_item_size(l, start);
2902 data_len = data_len - btrfs_item_offset(l, end);
2903 data_len += sizeof(struct btrfs_item) * nr;
2904 WARN_ON(data_len < 0);
2909 * The space between the end of the leaf items and
2910 * the start of the leaf data. IOW, how much room
2911 * the leaf has left for both items and data
2913 noinline int btrfs_leaf_free_space(struct extent_buffer *leaf)
2915 struct btrfs_fs_info *fs_info = leaf->fs_info;
2916 int nritems = btrfs_header_nritems(leaf);
2919 ret = BTRFS_LEAF_DATA_SIZE(fs_info) - leaf_space_used(leaf, 0, nritems);
2922 "leaf free space ret %d, leaf data size %lu, used %d nritems %d",
2924 (unsigned long) BTRFS_LEAF_DATA_SIZE(fs_info),
2925 leaf_space_used(leaf, 0, nritems), nritems);
2931 * min slot controls the lowest index we're willing to push to the
2932 * right. We'll push up to and including min_slot, but no lower
2934 static noinline int __push_leaf_right(struct btrfs_path *path,
2935 int data_size, int empty,
2936 struct extent_buffer *right,
2937 int free_space, u32 left_nritems,
2940 struct btrfs_fs_info *fs_info = right->fs_info;
2941 struct extent_buffer *left = path->nodes[0];
2942 struct extent_buffer *upper = path->nodes[1];
2943 struct btrfs_map_token token;
2944 struct btrfs_disk_key disk_key;
2957 nr = max_t(u32, 1, min_slot);
2959 if (path->slots[0] >= left_nritems)
2960 push_space += data_size;
2962 slot = path->slots[1];
2963 i = left_nritems - 1;
2965 if (!empty && push_items > 0) {
2966 if (path->slots[0] > i)
2968 if (path->slots[0] == i) {
2969 int space = btrfs_leaf_free_space(left);
2971 if (space + push_space * 2 > free_space)
2976 if (path->slots[0] == i)
2977 push_space += data_size;
2979 this_item_size = btrfs_item_size(left, i);
2980 if (this_item_size + sizeof(struct btrfs_item) +
2981 push_space > free_space)
2985 push_space += this_item_size + sizeof(struct btrfs_item);
2991 if (push_items == 0)
2994 WARN_ON(!empty && push_items == left_nritems);
2996 /* push left to right */
2997 right_nritems = btrfs_header_nritems(right);
2999 push_space = btrfs_item_data_end(left, left_nritems - push_items);
3000 push_space -= leaf_data_end(left);
3002 /* make room in the right data area */
3003 data_end = leaf_data_end(right);
3004 memmove_extent_buffer(right,
3005 BTRFS_LEAF_DATA_OFFSET + data_end - push_space,
3006 BTRFS_LEAF_DATA_OFFSET + data_end,
3007 BTRFS_LEAF_DATA_SIZE(fs_info) - data_end);
3009 /* copy from the left data area */
3010 copy_extent_buffer(right, left, BTRFS_LEAF_DATA_OFFSET +
3011 BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
3012 BTRFS_LEAF_DATA_OFFSET + leaf_data_end(left),
3015 memmove_extent_buffer(right, btrfs_item_nr_offset(push_items),
3016 btrfs_item_nr_offset(0),
3017 right_nritems * sizeof(struct btrfs_item));
3019 /* copy the items from left to right */
3020 copy_extent_buffer(right, left, btrfs_item_nr_offset(0),
3021 btrfs_item_nr_offset(left_nritems - push_items),
3022 push_items * sizeof(struct btrfs_item));
3024 /* update the item pointers */
3025 btrfs_init_map_token(&token, right);
3026 right_nritems += push_items;
3027 btrfs_set_header_nritems(right, right_nritems);
3028 push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
3029 for (i = 0; i < right_nritems; i++) {
3030 push_space -= btrfs_token_item_size(&token, i);
3031 btrfs_set_token_item_offset(&token, i, push_space);
3034 left_nritems -= push_items;
3035 btrfs_set_header_nritems(left, left_nritems);
3038 btrfs_mark_buffer_dirty(left);
3040 btrfs_clean_tree_block(left);
3042 btrfs_mark_buffer_dirty(right);
3044 btrfs_item_key(right, &disk_key, 0);
3045 btrfs_set_node_key(upper, &disk_key, slot + 1);
3046 btrfs_mark_buffer_dirty(upper);
3048 /* then fixup the leaf pointer in the path */
3049 if (path->slots[0] >= left_nritems) {
3050 path->slots[0] -= left_nritems;
3051 if (btrfs_header_nritems(path->nodes[0]) == 0)
3052 btrfs_clean_tree_block(path->nodes[0]);
3053 btrfs_tree_unlock(path->nodes[0]);
3054 free_extent_buffer(path->nodes[0]);
3055 path->nodes[0] = right;
3056 path->slots[1] += 1;
3058 btrfs_tree_unlock(right);
3059 free_extent_buffer(right);
3064 btrfs_tree_unlock(right);
3065 free_extent_buffer(right);
3070 * push some data in the path leaf to the right, trying to free up at
3071 * least data_size bytes. returns zero if the push worked, nonzero otherwise
3073 * returns 1 if the push failed because the other node didn't have enough
3074 * room, 0 if everything worked out and < 0 if there were major errors.
3076 * this will push starting from min_slot to the end of the leaf. It won't
3077 * push any slot lower than min_slot
3079 static int push_leaf_right(struct btrfs_trans_handle *trans, struct btrfs_root
3080 *root, struct btrfs_path *path,
3081 int min_data_size, int data_size,
3082 int empty, u32 min_slot)
3084 struct extent_buffer *left = path->nodes[0];
3085 struct extent_buffer *right;
3086 struct extent_buffer *upper;
3092 if (!path->nodes[1])
3095 slot = path->slots[1];
3096 upper = path->nodes[1];
3097 if (slot >= btrfs_header_nritems(upper) - 1)
3100 btrfs_assert_tree_write_locked(path->nodes[1]);
3102 right = btrfs_read_node_slot(upper, slot + 1);
3104 * slot + 1 is not valid or we fail to read the right node,
3105 * no big deal, just return.
3110 __btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
3112 free_space = btrfs_leaf_free_space(right);
3113 if (free_space < data_size)
3116 ret = btrfs_cow_block(trans, root, right, upper,
3117 slot + 1, &right, BTRFS_NESTING_RIGHT_COW);
3121 left_nritems = btrfs_header_nritems(left);
3122 if (left_nritems == 0)
3125 if (check_sibling_keys(left, right)) {
3127 btrfs_tree_unlock(right);
3128 free_extent_buffer(right);
3131 if (path->slots[0] == left_nritems && !empty) {
3132 /* Key greater than all keys in the leaf, right neighbor has
3133 * enough room for it and we're not emptying our leaf to delete
3134 * it, therefore use right neighbor to insert the new item and
3135 * no need to touch/dirty our left leaf. */
3136 btrfs_tree_unlock(left);
3137 free_extent_buffer(left);
3138 path->nodes[0] = right;
3144 return __push_leaf_right(path, min_data_size, empty,
3145 right, free_space, left_nritems, min_slot);
3147 btrfs_tree_unlock(right);
3148 free_extent_buffer(right);
3153 * push some data in the path leaf to the left, trying to free up at
3154 * least data_size bytes. returns zero if the push worked, nonzero otherwise
3156 * max_slot can put a limit on how far into the leaf we'll push items. The
3157 * item at 'max_slot' won't be touched. Use (u32)-1 to make us do all the
3160 static noinline int __push_leaf_left(struct btrfs_path *path, int data_size,
3161 int empty, struct extent_buffer *left,
3162 int free_space, u32 right_nritems,
3165 struct btrfs_fs_info *fs_info = left->fs_info;
3166 struct btrfs_disk_key disk_key;
3167 struct extent_buffer *right = path->nodes[0];
3171 u32 old_left_nritems;
3175 u32 old_left_item_size;
3176 struct btrfs_map_token token;
3179 nr = min(right_nritems, max_slot);
3181 nr = min(right_nritems - 1, max_slot);
3183 for (i = 0; i < nr; i++) {
3184 if (!empty && push_items > 0) {
3185 if (path->slots[0] < i)
3187 if (path->slots[0] == i) {
3188 int space = btrfs_leaf_free_space(right);
3190 if (space + push_space * 2 > free_space)
3195 if (path->slots[0] == i)
3196 push_space += data_size;
3198 this_item_size = btrfs_item_size(right, i);
3199 if (this_item_size + sizeof(struct btrfs_item) + push_space >
3204 push_space += this_item_size + sizeof(struct btrfs_item);
3207 if (push_items == 0) {
3211 WARN_ON(!empty && push_items == btrfs_header_nritems(right));
3213 /* push data from right to left */
3214 copy_extent_buffer(left, right,
3215 btrfs_item_nr_offset(btrfs_header_nritems(left)),
3216 btrfs_item_nr_offset(0),
3217 push_items * sizeof(struct btrfs_item));
3219 push_space = BTRFS_LEAF_DATA_SIZE(fs_info) -
3220 btrfs_item_offset(right, push_items - 1);
3222 copy_extent_buffer(left, right, BTRFS_LEAF_DATA_OFFSET +
3223 leaf_data_end(left) - push_space,
3224 BTRFS_LEAF_DATA_OFFSET +
3225 btrfs_item_offset(right, push_items - 1),
3227 old_left_nritems = btrfs_header_nritems(left);
3228 BUG_ON(old_left_nritems <= 0);
3230 btrfs_init_map_token(&token, left);
3231 old_left_item_size = btrfs_item_offset(left, old_left_nritems - 1);
3232 for (i = old_left_nritems; i < old_left_nritems + push_items; i++) {
3235 ioff = btrfs_token_item_offset(&token, i);
3236 btrfs_set_token_item_offset(&token, i,
3237 ioff - (BTRFS_LEAF_DATA_SIZE(fs_info) - old_left_item_size));
3239 btrfs_set_header_nritems(left, old_left_nritems + push_items);
3241 /* fixup right node */
3242 if (push_items > right_nritems)
3243 WARN(1, KERN_CRIT "push items %d nr %u\n", push_items,
3246 if (push_items < right_nritems) {
3247 push_space = btrfs_item_offset(right, push_items - 1) -
3248 leaf_data_end(right);
3249 memmove_extent_buffer(right, BTRFS_LEAF_DATA_OFFSET +
3250 BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
3251 BTRFS_LEAF_DATA_OFFSET +
3252 leaf_data_end(right), push_space);
3254 memmove_extent_buffer(right, btrfs_item_nr_offset(0),
3255 btrfs_item_nr_offset(push_items),
3256 (btrfs_header_nritems(right) - push_items) *
3257 sizeof(struct btrfs_item));
3260 btrfs_init_map_token(&token, right);
3261 right_nritems -= push_items;
3262 btrfs_set_header_nritems(right, right_nritems);
3263 push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
3264 for (i = 0; i < right_nritems; i++) {
3265 push_space = push_space - btrfs_token_item_size(&token, i);
3266 btrfs_set_token_item_offset(&token, i, push_space);
3269 btrfs_mark_buffer_dirty(left);
3271 btrfs_mark_buffer_dirty(right);
3273 btrfs_clean_tree_block(right);
3275 btrfs_item_key(right, &disk_key, 0);
3276 fixup_low_keys(path, &disk_key, 1);
3278 /* then fixup the leaf pointer in the path */
3279 if (path->slots[0] < push_items) {
3280 path->slots[0] += old_left_nritems;
3281 btrfs_tree_unlock(path->nodes[0]);
3282 free_extent_buffer(path->nodes[0]);
3283 path->nodes[0] = left;
3284 path->slots[1] -= 1;
3286 btrfs_tree_unlock(left);
3287 free_extent_buffer(left);
3288 path->slots[0] -= push_items;
3290 BUG_ON(path->slots[0] < 0);
3293 btrfs_tree_unlock(left);
3294 free_extent_buffer(left);
3299 * push some data in the path leaf to the left, trying to free up at
3300 * least data_size bytes. returns zero if the push worked, nonzero otherwise
3302 * max_slot can put a limit on how far into the leaf we'll push items. The
3303 * item at 'max_slot' won't be touched. Use (u32)-1 to make us push all the
3306 static int push_leaf_left(struct btrfs_trans_handle *trans, struct btrfs_root
3307 *root, struct btrfs_path *path, int min_data_size,
3308 int data_size, int empty, u32 max_slot)
3310 struct extent_buffer *right = path->nodes[0];
3311 struct extent_buffer *left;
3317 slot = path->slots[1];
3320 if (!path->nodes[1])
3323 right_nritems = btrfs_header_nritems(right);
3324 if (right_nritems == 0)
3327 btrfs_assert_tree_write_locked(path->nodes[1]);
3329 left = btrfs_read_node_slot(path->nodes[1], slot - 1);
3331 * slot - 1 is not valid or we fail to read the left node,
3332 * no big deal, just return.
3337 __btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
3339 free_space = btrfs_leaf_free_space(left);
3340 if (free_space < data_size) {
3345 ret = btrfs_cow_block(trans, root, left,
3346 path->nodes[1], slot - 1, &left,
3347 BTRFS_NESTING_LEFT_COW);
3349 /* we hit -ENOSPC, but it isn't fatal here */
3355 if (check_sibling_keys(left, right)) {
3359 return __push_leaf_left(path, min_data_size,
3360 empty, left, free_space, right_nritems,
3363 btrfs_tree_unlock(left);
3364 free_extent_buffer(left);
3369 * split the path's leaf in two, making sure there is at least data_size
3370 * available for the resulting leaf level of the path.
3372 static noinline void copy_for_split(struct btrfs_trans_handle *trans,
3373 struct btrfs_path *path,
3374 struct extent_buffer *l,
3375 struct extent_buffer *right,
3376 int slot, int mid, int nritems)
3378 struct btrfs_fs_info *fs_info = trans->fs_info;
3382 struct btrfs_disk_key disk_key;
3383 struct btrfs_map_token token;
3385 nritems = nritems - mid;
3386 btrfs_set_header_nritems(right, nritems);
3387 data_copy_size = btrfs_item_data_end(l, mid) - leaf_data_end(l);
3389 copy_extent_buffer(right, l, btrfs_item_nr_offset(0),
3390 btrfs_item_nr_offset(mid),
3391 nritems * sizeof(struct btrfs_item));
3393 copy_extent_buffer(right, l,
3394 BTRFS_LEAF_DATA_OFFSET + BTRFS_LEAF_DATA_SIZE(fs_info) -
3395 data_copy_size, BTRFS_LEAF_DATA_OFFSET +
3396 leaf_data_end(l), data_copy_size);
3398 rt_data_off = BTRFS_LEAF_DATA_SIZE(fs_info) - btrfs_item_data_end(l, mid);
3400 btrfs_init_map_token(&token, right);
3401 for (i = 0; i < nritems; i++) {
3404 ioff = btrfs_token_item_offset(&token, i);
3405 btrfs_set_token_item_offset(&token, i, ioff + rt_data_off);
3408 btrfs_set_header_nritems(l, mid);
3409 btrfs_item_key(right, &disk_key, 0);
3410 insert_ptr(trans, path, &disk_key, right->start, path->slots[1] + 1, 1);
3412 btrfs_mark_buffer_dirty(right);
3413 btrfs_mark_buffer_dirty(l);
3414 BUG_ON(path->slots[0] != slot);
3417 btrfs_tree_unlock(path->nodes[0]);
3418 free_extent_buffer(path->nodes[0]);
3419 path->nodes[0] = right;
3420 path->slots[0] -= mid;
3421 path->slots[1] += 1;
3423 btrfs_tree_unlock(right);
3424 free_extent_buffer(right);
3427 BUG_ON(path->slots[0] < 0);
3431 * double splits happen when we need to insert a big item in the middle
3432 * of a leaf. A double split can leave us with 3 mostly empty leaves:
3433 * leaf: [ slots 0 - N] [ our target ] [ N + 1 - total in leaf ]
3436 * We avoid this by trying to push the items on either side of our target
3437 * into the adjacent leaves. If all goes well we can avoid the double split
3440 static noinline int push_for_double_split(struct btrfs_trans_handle *trans,
3441 struct btrfs_root *root,
3442 struct btrfs_path *path,
3449 int space_needed = data_size;
3451 slot = path->slots[0];
3452 if (slot < btrfs_header_nritems(path->nodes[0]))
3453 space_needed -= btrfs_leaf_free_space(path->nodes[0]);
3456 * try to push all the items after our slot into the
3459 ret = push_leaf_right(trans, root, path, 1, space_needed, 0, slot);
3466 nritems = btrfs_header_nritems(path->nodes[0]);
3468 * our goal is to get our slot at the start or end of a leaf. If
3469 * we've done so we're done
3471 if (path->slots[0] == 0 || path->slots[0] == nritems)
3474 if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
3477 /* try to push all the items before our slot into the next leaf */
3478 slot = path->slots[0];
3479 space_needed = data_size;
3481 space_needed -= btrfs_leaf_free_space(path->nodes[0]);
3482 ret = push_leaf_left(trans, root, path, 1, space_needed, 0, slot);
3495 * split the path's leaf in two, making sure there is at least data_size
3496 * available for the resulting leaf level of the path.
3498 * returns 0 if all went well and < 0 on failure.
3500 static noinline int split_leaf(struct btrfs_trans_handle *trans,
3501 struct btrfs_root *root,
3502 const struct btrfs_key *ins_key,
3503 struct btrfs_path *path, int data_size,
3506 struct btrfs_disk_key disk_key;
3507 struct extent_buffer *l;
3511 struct extent_buffer *right;
3512 struct btrfs_fs_info *fs_info = root->fs_info;
3516 int num_doubles = 0;
3517 int tried_avoid_double = 0;
3520 slot = path->slots[0];
3521 if (extend && data_size + btrfs_item_size(l, slot) +
3522 sizeof(struct btrfs_item) > BTRFS_LEAF_DATA_SIZE(fs_info))
3525 /* first try to make some room by pushing left and right */
3526 if (data_size && path->nodes[1]) {
3527 int space_needed = data_size;
3529 if (slot < btrfs_header_nritems(l))
3530 space_needed -= btrfs_leaf_free_space(l);
3532 wret = push_leaf_right(trans, root, path, space_needed,
3533 space_needed, 0, 0);
3537 space_needed = data_size;
3539 space_needed -= btrfs_leaf_free_space(l);
3540 wret = push_leaf_left(trans, root, path, space_needed,
3541 space_needed, 0, (u32)-1);
3547 /* did the pushes work? */
3548 if (btrfs_leaf_free_space(l) >= data_size)
3552 if (!path->nodes[1]) {
3553 ret = insert_new_root(trans, root, path, 1);
3560 slot = path->slots[0];
3561 nritems = btrfs_header_nritems(l);
3562 mid = (nritems + 1) / 2;
3566 leaf_space_used(l, mid, nritems - mid) + data_size >
3567 BTRFS_LEAF_DATA_SIZE(fs_info)) {
3568 if (slot >= nritems) {
3572 if (mid != nritems &&
3573 leaf_space_used(l, mid, nritems - mid) +
3574 data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
3575 if (data_size && !tried_avoid_double)
3576 goto push_for_double;
3582 if (leaf_space_used(l, 0, mid) + data_size >
3583 BTRFS_LEAF_DATA_SIZE(fs_info)) {
3584 if (!extend && data_size && slot == 0) {
3586 } else if ((extend || !data_size) && slot == 0) {
3590 if (mid != nritems &&
3591 leaf_space_used(l, mid, nritems - mid) +
3592 data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
3593 if (data_size && !tried_avoid_double)
3594 goto push_for_double;
3602 btrfs_cpu_key_to_disk(&disk_key, ins_key);
3604 btrfs_item_key(l, &disk_key, mid);
3607 * We have to about BTRFS_NESTING_NEW_ROOT here if we've done a double
3608 * split, because we're only allowed to have MAX_LOCKDEP_SUBCLASSES
3609 * subclasses, which is 8 at the time of this patch, and we've maxed it
3610 * out. In the future we could add a
3611 * BTRFS_NESTING_SPLIT_THE_SPLITTENING if we need to, but for now just
3612 * use BTRFS_NESTING_NEW_ROOT.
3614 right = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
3615 &disk_key, 0, l->start, 0,
3616 num_doubles ? BTRFS_NESTING_NEW_ROOT :
3617 BTRFS_NESTING_SPLIT);
3619 return PTR_ERR(right);
3621 root_add_used(root, fs_info->nodesize);
3625 btrfs_set_header_nritems(right, 0);
3626 insert_ptr(trans, path, &disk_key,
3627 right->start, path->slots[1] + 1, 1);
3628 btrfs_tree_unlock(path->nodes[0]);
3629 free_extent_buffer(path->nodes[0]);
3630 path->nodes[0] = right;
3632 path->slots[1] += 1;
3634 btrfs_set_header_nritems(right, 0);
3635 insert_ptr(trans, path, &disk_key,
3636 right->start, path->slots[1], 1);
3637 btrfs_tree_unlock(path->nodes[0]);
3638 free_extent_buffer(path->nodes[0]);
3639 path->nodes[0] = right;
3641 if (path->slots[1] == 0)
3642 fixup_low_keys(path, &disk_key, 1);
3645 * We create a new leaf 'right' for the required ins_len and
3646 * we'll do btrfs_mark_buffer_dirty() on this leaf after copying
3647 * the content of ins_len to 'right'.
3652 copy_for_split(trans, path, l, right, slot, mid, nritems);
3655 BUG_ON(num_doubles != 0);
3663 push_for_double_split(trans, root, path, data_size);
3664 tried_avoid_double = 1;
3665 if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
3670 static noinline int setup_leaf_for_split(struct btrfs_trans_handle *trans,
3671 struct btrfs_root *root,
3672 struct btrfs_path *path, int ins_len)
3674 struct btrfs_key key;
3675 struct extent_buffer *leaf;
3676 struct btrfs_file_extent_item *fi;
3681 leaf = path->nodes[0];
3682 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3684 BUG_ON(key.type != BTRFS_EXTENT_DATA_KEY &&
3685 key.type != BTRFS_EXTENT_CSUM_KEY);
3687 if (btrfs_leaf_free_space(leaf) >= ins_len)
3690 item_size = btrfs_item_size(leaf, path->slots[0]);
3691 if (key.type == BTRFS_EXTENT_DATA_KEY) {
3692 fi = btrfs_item_ptr(leaf, path->slots[0],
3693 struct btrfs_file_extent_item);
3694 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
3696 btrfs_release_path(path);
3698 path->keep_locks = 1;
3699 path->search_for_split = 1;
3700 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
3701 path->search_for_split = 0;
3708 leaf = path->nodes[0];
3709 /* if our item isn't there, return now */
3710 if (item_size != btrfs_item_size(leaf, path->slots[0]))
3713 /* the leaf has changed, it now has room. return now */
3714 if (btrfs_leaf_free_space(path->nodes[0]) >= ins_len)
3717 if (key.type == BTRFS_EXTENT_DATA_KEY) {
3718 fi = btrfs_item_ptr(leaf, path->slots[0],
3719 struct btrfs_file_extent_item);
3720 if (extent_len != btrfs_file_extent_num_bytes(leaf, fi))
3724 ret = split_leaf(trans, root, &key, path, ins_len, 1);
3728 path->keep_locks = 0;
3729 btrfs_unlock_up_safe(path, 1);
3732 path->keep_locks = 0;
3736 static noinline int split_item(struct btrfs_path *path,
3737 const struct btrfs_key *new_key,
3738 unsigned long split_offset)
3740 struct extent_buffer *leaf;
3741 int orig_slot, slot;
3746 struct btrfs_disk_key disk_key;
3748 leaf = path->nodes[0];
3749 BUG_ON(btrfs_leaf_free_space(leaf) < sizeof(struct btrfs_item));
3751 orig_slot = path->slots[0];
3752 orig_offset = btrfs_item_offset(leaf, path->slots[0]);
3753 item_size = btrfs_item_size(leaf, path->slots[0]);
3755 buf = kmalloc(item_size, GFP_NOFS);
3759 read_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf,
3760 path->slots[0]), item_size);
3762 slot = path->slots[0] + 1;
3763 nritems = btrfs_header_nritems(leaf);
3764 if (slot != nritems) {
3765 /* shift the items */
3766 memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + 1),
3767 btrfs_item_nr_offset(slot),
3768 (nritems - slot) * sizeof(struct btrfs_item));
3771 btrfs_cpu_key_to_disk(&disk_key, new_key);
3772 btrfs_set_item_key(leaf, &disk_key, slot);
3774 btrfs_set_item_offset(leaf, slot, orig_offset);
3775 btrfs_set_item_size(leaf, slot, item_size - split_offset);
3777 btrfs_set_item_offset(leaf, orig_slot,
3778 orig_offset + item_size - split_offset);
3779 btrfs_set_item_size(leaf, orig_slot, split_offset);
3781 btrfs_set_header_nritems(leaf, nritems + 1);
3783 /* write the data for the start of the original item */
3784 write_extent_buffer(leaf, buf,
3785 btrfs_item_ptr_offset(leaf, path->slots[0]),
3788 /* write the data for the new item */
3789 write_extent_buffer(leaf, buf + split_offset,
3790 btrfs_item_ptr_offset(leaf, slot),
3791 item_size - split_offset);
3792 btrfs_mark_buffer_dirty(leaf);
3794 BUG_ON(btrfs_leaf_free_space(leaf) < 0);
3800 * This function splits a single item into two items,
3801 * giving 'new_key' to the new item and splitting the
3802 * old one at split_offset (from the start of the item).
3804 * The path may be released by this operation. After
3805 * the split, the path is pointing to the old item. The
3806 * new item is going to be in the same node as the old one.
3808 * Note, the item being split must be smaller enough to live alone on
3809 * a tree block with room for one extra struct btrfs_item
3811 * This allows us to split the item in place, keeping a lock on the
3812 * leaf the entire time.
3814 int btrfs_split_item(struct btrfs_trans_handle *trans,
3815 struct btrfs_root *root,
3816 struct btrfs_path *path,
3817 const struct btrfs_key *new_key,
3818 unsigned long split_offset)
3821 ret = setup_leaf_for_split(trans, root, path,
3822 sizeof(struct btrfs_item));
3826 ret = split_item(path, new_key, split_offset);
3831 * make the item pointed to by the path smaller. new_size indicates
3832 * how small to make it, and from_end tells us if we just chop bytes
3833 * off the end of the item or if we shift the item to chop bytes off
3836 void btrfs_truncate_item(struct btrfs_path *path, u32 new_size, int from_end)
3839 struct extent_buffer *leaf;
3841 unsigned int data_end;
3842 unsigned int old_data_start;
3843 unsigned int old_size;
3844 unsigned int size_diff;
3846 struct btrfs_map_token token;
3848 leaf = path->nodes[0];
3849 slot = path->slots[0];
3851 old_size = btrfs_item_size(leaf, slot);
3852 if (old_size == new_size)
3855 nritems = btrfs_header_nritems(leaf);
3856 data_end = leaf_data_end(leaf);
3858 old_data_start = btrfs_item_offset(leaf, slot);
3860 size_diff = old_size - new_size;
3863 BUG_ON(slot >= nritems);
3866 * item0..itemN ... dataN.offset..dataN.size .. data0.size
3868 /* first correct the data pointers */
3869 btrfs_init_map_token(&token, leaf);
3870 for (i = slot; i < nritems; i++) {
3873 ioff = btrfs_token_item_offset(&token, i);
3874 btrfs_set_token_item_offset(&token, i, ioff + size_diff);
3877 /* shift the data */
3879 memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
3880 data_end + size_diff, BTRFS_LEAF_DATA_OFFSET +
3881 data_end, old_data_start + new_size - data_end);
3883 struct btrfs_disk_key disk_key;
3886 btrfs_item_key(leaf, &disk_key, slot);
3888 if (btrfs_disk_key_type(&disk_key) == BTRFS_EXTENT_DATA_KEY) {
3890 struct btrfs_file_extent_item *fi;
3892 fi = btrfs_item_ptr(leaf, slot,
3893 struct btrfs_file_extent_item);
3894 fi = (struct btrfs_file_extent_item *)(
3895 (unsigned long)fi - size_diff);
3897 if (btrfs_file_extent_type(leaf, fi) ==
3898 BTRFS_FILE_EXTENT_INLINE) {
3899 ptr = btrfs_item_ptr_offset(leaf, slot);
3900 memmove_extent_buffer(leaf, ptr,
3902 BTRFS_FILE_EXTENT_INLINE_DATA_START);
3906 memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
3907 data_end + size_diff, BTRFS_LEAF_DATA_OFFSET +
3908 data_end, old_data_start - data_end);
3910 offset = btrfs_disk_key_offset(&disk_key);
3911 btrfs_set_disk_key_offset(&disk_key, offset + size_diff);
3912 btrfs_set_item_key(leaf, &disk_key, slot);
3914 fixup_low_keys(path, &disk_key, 1);
3917 btrfs_set_item_size(leaf, slot, new_size);
3918 btrfs_mark_buffer_dirty(leaf);
3920 if (btrfs_leaf_free_space(leaf) < 0) {
3921 btrfs_print_leaf(leaf);
3927 * make the item pointed to by the path bigger, data_size is the added size.
3929 void btrfs_extend_item(struct btrfs_path *path, u32 data_size)
3932 struct extent_buffer *leaf;
3934 unsigned int data_end;
3935 unsigned int old_data;
3936 unsigned int old_size;
3938 struct btrfs_map_token token;
3940 leaf = path->nodes[0];
3942 nritems = btrfs_header_nritems(leaf);
3943 data_end = leaf_data_end(leaf);
3945 if (btrfs_leaf_free_space(leaf) < data_size) {
3946 btrfs_print_leaf(leaf);
3949 slot = path->slots[0];
3950 old_data = btrfs_item_data_end(leaf, slot);
3953 if (slot >= nritems) {
3954 btrfs_print_leaf(leaf);
3955 btrfs_crit(leaf->fs_info, "slot %d too large, nritems %d",
3961 * item0..itemN ... dataN.offset..dataN.size .. data0.size
3963 /* first correct the data pointers */
3964 btrfs_init_map_token(&token, leaf);
3965 for (i = slot; i < nritems; i++) {
3968 ioff = btrfs_token_item_offset(&token, i);
3969 btrfs_set_token_item_offset(&token, i, ioff - data_size);
3972 /* shift the data */
3973 memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
3974 data_end - data_size, BTRFS_LEAF_DATA_OFFSET +
3975 data_end, old_data - data_end);
3977 data_end = old_data;
3978 old_size = btrfs_item_size(leaf, slot);
3979 btrfs_set_item_size(leaf, slot, old_size + data_size);
3980 btrfs_mark_buffer_dirty(leaf);
3982 if (btrfs_leaf_free_space(leaf) < 0) {
3983 btrfs_print_leaf(leaf);
3989 * setup_items_for_insert - Helper called before inserting one or more items
3990 * to a leaf. Main purpose is to save stack depth by doing the bulk of the work
3991 * in a function that doesn't call btrfs_search_slot
3993 * @root: root we are inserting items to
3994 * @path: points to the leaf/slot where we are going to insert new items
3995 * @batch: information about the batch of items to insert
3997 static void setup_items_for_insert(struct btrfs_root *root, struct btrfs_path *path,
3998 const struct btrfs_item_batch *batch)
4000 struct btrfs_fs_info *fs_info = root->fs_info;
4003 unsigned int data_end;
4004 struct btrfs_disk_key disk_key;
4005 struct extent_buffer *leaf;
4007 struct btrfs_map_token token;
4011 * Before anything else, update keys in the parent and other ancestors
4012 * if needed, then release the write locks on them, so that other tasks
4013 * can use them while we modify the leaf.
4015 if (path->slots[0] == 0) {
4016 btrfs_cpu_key_to_disk(&disk_key, &batch->keys[0]);
4017 fixup_low_keys(path, &disk_key, 1);
4019 btrfs_unlock_up_safe(path, 1);
4021 leaf = path->nodes[0];
4022 slot = path->slots[0];
4024 nritems = btrfs_header_nritems(leaf);
4025 data_end = leaf_data_end(leaf);
4026 total_size = batch->total_data_size + (batch->nr * sizeof(struct btrfs_item));
4028 if (btrfs_leaf_free_space(leaf) < total_size) {
4029 btrfs_print_leaf(leaf);
4030 btrfs_crit(fs_info, "not enough freespace need %u have %d",
4031 total_size, btrfs_leaf_free_space(leaf));
4035 btrfs_init_map_token(&token, leaf);
4036 if (slot != nritems) {
4037 unsigned int old_data = btrfs_item_data_end(leaf, slot);
4039 if (old_data < data_end) {
4040 btrfs_print_leaf(leaf);
4042 "item at slot %d with data offset %u beyond data end of leaf %u",
4043 slot, old_data, data_end);
4047 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4049 /* first correct the data pointers */
4050 for (i = slot; i < nritems; i++) {
4053 ioff = btrfs_token_item_offset(&token, i);
4054 btrfs_set_token_item_offset(&token, i,
4055 ioff - batch->total_data_size);
4057 /* shift the items */
4058 memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + batch->nr),
4059 btrfs_item_nr_offset(slot),
4060 (nritems - slot) * sizeof(struct btrfs_item));
4062 /* shift the data */
4063 memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
4064 data_end - batch->total_data_size,
4065 BTRFS_LEAF_DATA_OFFSET + data_end,
4066 old_data - data_end);
4067 data_end = old_data;
4070 /* setup the item for the new data */
4071 for (i = 0; i < batch->nr; i++) {
4072 btrfs_cpu_key_to_disk(&disk_key, &batch->keys[i]);
4073 btrfs_set_item_key(leaf, &disk_key, slot + i);
4074 data_end -= batch->data_sizes[i];
4075 btrfs_set_token_item_offset(&token, slot + i, data_end);
4076 btrfs_set_token_item_size(&token, slot + i, batch->data_sizes[i]);
4079 btrfs_set_header_nritems(leaf, nritems + batch->nr);
4080 btrfs_mark_buffer_dirty(leaf);
4082 if (btrfs_leaf_free_space(leaf) < 0) {
4083 btrfs_print_leaf(leaf);
4089 * Insert a new item into a leaf.
4091 * @root: The root of the btree.
4092 * @path: A path pointing to the target leaf and slot.
4093 * @key: The key of the new item.
4094 * @data_size: The size of the data associated with the new key.
4096 void btrfs_setup_item_for_insert(struct btrfs_root *root,
4097 struct btrfs_path *path,
4098 const struct btrfs_key *key,
4101 struct btrfs_item_batch batch;
4104 batch.data_sizes = &data_size;
4105 batch.total_data_size = data_size;
4108 setup_items_for_insert(root, path, &batch);
4112 * Given a key and some data, insert items into the tree.
4113 * This does all the path init required, making room in the tree if needed.
4115 int btrfs_insert_empty_items(struct btrfs_trans_handle *trans,
4116 struct btrfs_root *root,
4117 struct btrfs_path *path,
4118 const struct btrfs_item_batch *batch)
4124 total_size = batch->total_data_size + (batch->nr * sizeof(struct btrfs_item));
4125 ret = btrfs_search_slot(trans, root, &batch->keys[0], path, total_size, 1);
4131 slot = path->slots[0];
4134 setup_items_for_insert(root, path, batch);
4139 * Given a key and some data, insert an item into the tree.
4140 * This does all the path init required, making room in the tree if needed.
4142 int btrfs_insert_item(struct btrfs_trans_handle *trans, struct btrfs_root *root,
4143 const struct btrfs_key *cpu_key, void *data,
4147 struct btrfs_path *path;
4148 struct extent_buffer *leaf;
4151 path = btrfs_alloc_path();
4154 ret = btrfs_insert_empty_item(trans, root, path, cpu_key, data_size);
4156 leaf = path->nodes[0];
4157 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
4158 write_extent_buffer(leaf, data, ptr, data_size);
4159 btrfs_mark_buffer_dirty(leaf);
4161 btrfs_free_path(path);
4166 * This function duplicates an item, giving 'new_key' to the new item.
4167 * It guarantees both items live in the same tree leaf and the new item is
4168 * contiguous with the original item.
4170 * This allows us to split a file extent in place, keeping a lock on the leaf
4173 int btrfs_duplicate_item(struct btrfs_trans_handle *trans,
4174 struct btrfs_root *root,
4175 struct btrfs_path *path,
4176 const struct btrfs_key *new_key)
4178 struct extent_buffer *leaf;
4182 leaf = path->nodes[0];
4183 item_size = btrfs_item_size(leaf, path->slots[0]);
4184 ret = setup_leaf_for_split(trans, root, path,
4185 item_size + sizeof(struct btrfs_item));
4190 btrfs_setup_item_for_insert(root, path, new_key, item_size);
4191 leaf = path->nodes[0];
4192 memcpy_extent_buffer(leaf,
4193 btrfs_item_ptr_offset(leaf, path->slots[0]),
4194 btrfs_item_ptr_offset(leaf, path->slots[0] - 1),
4200 * delete the pointer from a given node.
4202 * the tree should have been previously balanced so the deletion does not
4205 static void del_ptr(struct btrfs_root *root, struct btrfs_path *path,
4206 int level, int slot)
4208 struct extent_buffer *parent = path->nodes[level];
4212 nritems = btrfs_header_nritems(parent);
4213 if (slot != nritems - 1) {
4215 ret = btrfs_tree_mod_log_insert_move(parent, slot,
4216 slot + 1, nritems - slot - 1);
4219 memmove_extent_buffer(parent,
4220 btrfs_node_key_ptr_offset(slot),
4221 btrfs_node_key_ptr_offset(slot + 1),
4222 sizeof(struct btrfs_key_ptr) *
4223 (nritems - slot - 1));
4225 ret = btrfs_tree_mod_log_insert_key(parent, slot,
4226 BTRFS_MOD_LOG_KEY_REMOVE);
4231 btrfs_set_header_nritems(parent, nritems);
4232 if (nritems == 0 && parent == root->node) {
4233 BUG_ON(btrfs_header_level(root->node) != 1);
4234 /* just turn the root into a leaf and break */
4235 btrfs_set_header_level(root->node, 0);
4236 } else if (slot == 0) {
4237 struct btrfs_disk_key disk_key;
4239 btrfs_node_key(parent, &disk_key, 0);
4240 fixup_low_keys(path, &disk_key, level + 1);
4242 btrfs_mark_buffer_dirty(parent);
4246 * a helper function to delete the leaf pointed to by path->slots[1] and
4249 * This deletes the pointer in path->nodes[1] and frees the leaf
4250 * block extent. zero is returned if it all worked out, < 0 otherwise.
4252 * The path must have already been setup for deleting the leaf, including
4253 * all the proper balancing. path->nodes[1] must be locked.
4255 static noinline void btrfs_del_leaf(struct btrfs_trans_handle *trans,
4256 struct btrfs_root *root,
4257 struct btrfs_path *path,
4258 struct extent_buffer *leaf)
4260 WARN_ON(btrfs_header_generation(leaf) != trans->transid);
4261 del_ptr(root, path, 1, path->slots[1]);
4264 * btrfs_free_extent is expensive, we want to make sure we
4265 * aren't holding any locks when we call it
4267 btrfs_unlock_up_safe(path, 0);
4269 root_sub_used(root, leaf->len);
4271 atomic_inc(&leaf->refs);
4272 btrfs_free_tree_block(trans, btrfs_root_id(root), leaf, 0, 1);
4273 free_extent_buffer_stale(leaf);
4276 * delete the item at the leaf level in path. If that empties
4277 * the leaf, remove it from the tree
4279 int btrfs_del_items(struct btrfs_trans_handle *trans, struct btrfs_root *root,
4280 struct btrfs_path *path, int slot, int nr)
4282 struct btrfs_fs_info *fs_info = root->fs_info;
4283 struct extent_buffer *leaf;
4288 leaf = path->nodes[0];
4289 nritems = btrfs_header_nritems(leaf);
4291 if (slot + nr != nritems) {
4292 const u32 last_off = btrfs_item_offset(leaf, slot + nr - 1);
4293 const int data_end = leaf_data_end(leaf);
4294 struct btrfs_map_token token;
4298 for (i = 0; i < nr; i++)
4299 dsize += btrfs_item_size(leaf, slot + i);
4301 memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
4303 BTRFS_LEAF_DATA_OFFSET + data_end,
4304 last_off - data_end);
4306 btrfs_init_map_token(&token, leaf);
4307 for (i = slot + nr; i < nritems; i++) {
4310 ioff = btrfs_token_item_offset(&token, i);
4311 btrfs_set_token_item_offset(&token, i, ioff + dsize);
4314 memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot),
4315 btrfs_item_nr_offset(slot + nr),
4316 sizeof(struct btrfs_item) *
4317 (nritems - slot - nr));
4319 btrfs_set_header_nritems(leaf, nritems - nr);
4322 /* delete the leaf if we've emptied it */
4324 if (leaf == root->node) {
4325 btrfs_set_header_level(leaf, 0);
4327 btrfs_clean_tree_block(leaf);
4328 btrfs_del_leaf(trans, root, path, leaf);
4331 int used = leaf_space_used(leaf, 0, nritems);
4333 struct btrfs_disk_key disk_key;
4335 btrfs_item_key(leaf, &disk_key, 0);
4336 fixup_low_keys(path, &disk_key, 1);
4340 * Try to delete the leaf if it is mostly empty. We do this by
4341 * trying to move all its items into its left and right neighbours.
4342 * If we can't move all the items, then we don't delete it - it's
4343 * not ideal, but future insertions might fill the leaf with more
4344 * items, or items from other leaves might be moved later into our
4345 * leaf due to deletions on those leaves.
4347 if (used < BTRFS_LEAF_DATA_SIZE(fs_info) / 3) {
4350 /* push_leaf_left fixes the path.
4351 * make sure the path still points to our leaf
4352 * for possible call to del_ptr below
4354 slot = path->slots[1];
4355 atomic_inc(&leaf->refs);
4357 * We want to be able to at least push one item to the
4358 * left neighbour leaf, and that's the first item.
4360 min_push_space = sizeof(struct btrfs_item) +
4361 btrfs_item_size(leaf, 0);
4362 wret = push_leaf_left(trans, root, path, 0,
4363 min_push_space, 1, (u32)-1);
4364 if (wret < 0 && wret != -ENOSPC)
4367 if (path->nodes[0] == leaf &&
4368 btrfs_header_nritems(leaf)) {
4370 * If we were not able to push all items from our
4371 * leaf to its left neighbour, then attempt to
4372 * either push all the remaining items to the
4373 * right neighbour or none. There's no advantage
4374 * in pushing only some items, instead of all, as
4375 * it's pointless to end up with a leaf having
4376 * too few items while the neighbours can be full
4379 nritems = btrfs_header_nritems(leaf);
4380 min_push_space = leaf_space_used(leaf, 0, nritems);
4381 wret = push_leaf_right(trans, root, path, 0,
4382 min_push_space, 1, 0);
4383 if (wret < 0 && wret != -ENOSPC)
4387 if (btrfs_header_nritems(leaf) == 0) {
4388 path->slots[1] = slot;
4389 btrfs_del_leaf(trans, root, path, leaf);
4390 free_extent_buffer(leaf);
4393 /* if we're still in the path, make sure
4394 * we're dirty. Otherwise, one of the
4395 * push_leaf functions must have already
4396 * dirtied this buffer
4398 if (path->nodes[0] == leaf)
4399 btrfs_mark_buffer_dirty(leaf);
4400 free_extent_buffer(leaf);
4403 btrfs_mark_buffer_dirty(leaf);
4410 * search the tree again to find a leaf with lesser keys
4411 * returns 0 if it found something or 1 if there are no lesser leaves.
4412 * returns < 0 on io errors.
4414 * This may release the path, and so you may lose any locks held at the
4417 int btrfs_prev_leaf(struct btrfs_root *root, struct btrfs_path *path)
4419 struct btrfs_key key;
4420 struct btrfs_disk_key found_key;
4423 btrfs_item_key_to_cpu(path->nodes[0], &key, 0);
4425 if (key.offset > 0) {
4427 } else if (key.type > 0) {
4429 key.offset = (u64)-1;
4430 } else if (key.objectid > 0) {
4433 key.offset = (u64)-1;
4438 btrfs_release_path(path);
4439 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4442 btrfs_item_key(path->nodes[0], &found_key, 0);
4443 ret = comp_keys(&found_key, &key);
4445 * We might have had an item with the previous key in the tree right
4446 * before we released our path. And after we released our path, that
4447 * item might have been pushed to the first slot (0) of the leaf we
4448 * were holding due to a tree balance. Alternatively, an item with the
4449 * previous key can exist as the only element of a leaf (big fat item).
4450 * Therefore account for these 2 cases, so that our callers (like
4451 * btrfs_previous_item) don't miss an existing item with a key matching
4452 * the previous key we computed above.
4460 * A helper function to walk down the tree starting at min_key, and looking
4461 * for nodes or leaves that are have a minimum transaction id.
4462 * This is used by the btree defrag code, and tree logging
4464 * This does not cow, but it does stuff the starting key it finds back
4465 * into min_key, so you can call btrfs_search_slot with cow=1 on the
4466 * key and get a writable path.
4468 * This honors path->lowest_level to prevent descent past a given level
4471 * min_trans indicates the oldest transaction that you are interested
4472 * in walking through. Any nodes or leaves older than min_trans are
4473 * skipped over (without reading them).
4475 * returns zero if something useful was found, < 0 on error and 1 if there
4476 * was nothing in the tree that matched the search criteria.
4478 int btrfs_search_forward(struct btrfs_root *root, struct btrfs_key *min_key,
4479 struct btrfs_path *path,
4482 struct extent_buffer *cur;
4483 struct btrfs_key found_key;
4489 int keep_locks = path->keep_locks;
4491 ASSERT(!path->nowait);
4492 path->keep_locks = 1;
4494 cur = btrfs_read_lock_root_node(root);
4495 level = btrfs_header_level(cur);
4496 WARN_ON(path->nodes[level]);
4497 path->nodes[level] = cur;
4498 path->locks[level] = BTRFS_READ_LOCK;
4500 if (btrfs_header_generation(cur) < min_trans) {
4505 nritems = btrfs_header_nritems(cur);
4506 level = btrfs_header_level(cur);
4507 sret = btrfs_bin_search(cur, min_key, &slot);
4513 /* at the lowest level, we're done, setup the path and exit */
4514 if (level == path->lowest_level) {
4515 if (slot >= nritems)
4518 path->slots[level] = slot;
4519 btrfs_item_key_to_cpu(cur, &found_key, slot);
4522 if (sret && slot > 0)
4525 * check this node pointer against the min_trans parameters.
4526 * If it is too old, skip to the next one.
4528 while (slot < nritems) {
4531 gen = btrfs_node_ptr_generation(cur, slot);
4532 if (gen < min_trans) {
4540 * we didn't find a candidate key in this node, walk forward
4541 * and find another one
4543 if (slot >= nritems) {
4544 path->slots[level] = slot;
4545 sret = btrfs_find_next_key(root, path, min_key, level,
4548 btrfs_release_path(path);
4554 /* save our key for returning back */
4555 btrfs_node_key_to_cpu(cur, &found_key, slot);
4556 path->slots[level] = slot;
4557 if (level == path->lowest_level) {
4561 cur = btrfs_read_node_slot(cur, slot);
4567 btrfs_tree_read_lock(cur);
4569 path->locks[level - 1] = BTRFS_READ_LOCK;
4570 path->nodes[level - 1] = cur;
4571 unlock_up(path, level, 1, 0, NULL);
4574 path->keep_locks = keep_locks;
4576 btrfs_unlock_up_safe(path, path->lowest_level + 1);
4577 memcpy(min_key, &found_key, sizeof(found_key));
4583 * this is similar to btrfs_next_leaf, but does not try to preserve
4584 * and fixup the path. It looks for and returns the next key in the
4585 * tree based on the current path and the min_trans parameters.
4587 * 0 is returned if another key is found, < 0 if there are any errors
4588 * and 1 is returned if there are no higher keys in the tree
4590 * path->keep_locks should be set to 1 on the search made before
4591 * calling this function.
4593 int btrfs_find_next_key(struct btrfs_root *root, struct btrfs_path *path,
4594 struct btrfs_key *key, int level, u64 min_trans)
4597 struct extent_buffer *c;
4599 WARN_ON(!path->keep_locks && !path->skip_locking);
4600 while (level < BTRFS_MAX_LEVEL) {
4601 if (!path->nodes[level])
4604 slot = path->slots[level] + 1;
4605 c = path->nodes[level];
4607 if (slot >= btrfs_header_nritems(c)) {
4610 struct btrfs_key cur_key;
4611 if (level + 1 >= BTRFS_MAX_LEVEL ||
4612 !path->nodes[level + 1])
4615 if (path->locks[level + 1] || path->skip_locking) {
4620 slot = btrfs_header_nritems(c) - 1;
4622 btrfs_item_key_to_cpu(c, &cur_key, slot);
4624 btrfs_node_key_to_cpu(c, &cur_key, slot);
4626 orig_lowest = path->lowest_level;
4627 btrfs_release_path(path);
4628 path->lowest_level = level;
4629 ret = btrfs_search_slot(NULL, root, &cur_key, path,
4631 path->lowest_level = orig_lowest;
4635 c = path->nodes[level];
4636 slot = path->slots[level];
4643 btrfs_item_key_to_cpu(c, key, slot);
4645 u64 gen = btrfs_node_ptr_generation(c, slot);
4647 if (gen < min_trans) {
4651 btrfs_node_key_to_cpu(c, key, slot);
4658 int btrfs_next_old_leaf(struct btrfs_root *root, struct btrfs_path *path,
4663 struct extent_buffer *c;
4664 struct extent_buffer *next;
4665 struct btrfs_fs_info *fs_info = root->fs_info;
4666 struct btrfs_key key;
4667 bool need_commit_sem = false;
4673 * The nowait semantics are used only for write paths, where we don't
4674 * use the tree mod log and sequence numbers.
4677 ASSERT(!path->nowait);
4679 nritems = btrfs_header_nritems(path->nodes[0]);
4683 btrfs_item_key_to_cpu(path->nodes[0], &key, nritems - 1);
4687 btrfs_release_path(path);
4689 path->keep_locks = 1;
4692 ret = btrfs_search_old_slot(root, &key, path, time_seq);
4694 if (path->need_commit_sem) {
4695 path->need_commit_sem = 0;
4696 need_commit_sem = true;
4698 if (!down_read_trylock(&fs_info->commit_root_sem)) {
4703 down_read(&fs_info->commit_root_sem);
4706 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4708 path->keep_locks = 0;
4713 nritems = btrfs_header_nritems(path->nodes[0]);
4715 * by releasing the path above we dropped all our locks. A balance
4716 * could have added more items next to the key that used to be
4717 * at the very end of the block. So, check again here and
4718 * advance the path if there are now more items available.
4720 if (nritems > 0 && path->slots[0] < nritems - 1) {
4727 * So the above check misses one case:
4728 * - after releasing the path above, someone has removed the item that
4729 * used to be at the very end of the block, and balance between leafs
4730 * gets another one with bigger key.offset to replace it.
4732 * This one should be returned as well, or we can get leaf corruption
4733 * later(esp. in __btrfs_drop_extents()).
4735 * And a bit more explanation about this check,
4736 * with ret > 0, the key isn't found, the path points to the slot
4737 * where it should be inserted, so the path->slots[0] item must be the
4740 if (nritems > 0 && ret > 0 && path->slots[0] == nritems - 1) {
4745 while (level < BTRFS_MAX_LEVEL) {
4746 if (!path->nodes[level]) {
4751 slot = path->slots[level] + 1;
4752 c = path->nodes[level];
4753 if (slot >= btrfs_header_nritems(c)) {
4755 if (level == BTRFS_MAX_LEVEL) {
4764 * Our current level is where we're going to start from, and to
4765 * make sure lockdep doesn't complain we need to drop our locks
4766 * and nodes from 0 to our current level.
4768 for (i = 0; i < level; i++) {
4769 if (path->locks[level]) {
4770 btrfs_tree_read_unlock(path->nodes[i]);
4773 free_extent_buffer(path->nodes[i]);
4774 path->nodes[i] = NULL;
4778 ret = read_block_for_search(root, path, &next, level,
4780 if (ret == -EAGAIN && !path->nowait)
4784 btrfs_release_path(path);
4788 if (!path->skip_locking) {
4789 ret = btrfs_try_tree_read_lock(next);
4790 if (!ret && path->nowait) {
4794 if (!ret && time_seq) {
4796 * If we don't get the lock, we may be racing
4797 * with push_leaf_left, holding that lock while
4798 * itself waiting for the leaf we've currently
4799 * locked. To solve this situation, we give up
4800 * on our lock and cycle.
4802 free_extent_buffer(next);
4803 btrfs_release_path(path);
4808 btrfs_tree_read_lock(next);
4812 path->slots[level] = slot;
4815 path->nodes[level] = next;
4816 path->slots[level] = 0;
4817 if (!path->skip_locking)
4818 path->locks[level] = BTRFS_READ_LOCK;
4822 ret = read_block_for_search(root, path, &next, level,
4824 if (ret == -EAGAIN && !path->nowait)
4828 btrfs_release_path(path);
4832 if (!path->skip_locking) {
4834 if (!btrfs_try_tree_read_lock(next)) {
4839 btrfs_tree_read_lock(next);
4845 unlock_up(path, 0, 1, 0, NULL);
4846 if (need_commit_sem) {
4849 path->need_commit_sem = 1;
4850 ret2 = finish_need_commit_sem_search(path);
4851 up_read(&fs_info->commit_root_sem);
4859 int btrfs_next_old_item(struct btrfs_root *root, struct btrfs_path *path, u64 time_seq)
4862 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0]))
4863 return btrfs_next_old_leaf(root, path, time_seq);
4868 * this uses btrfs_prev_leaf to walk backwards in the tree, and keeps
4869 * searching until it gets past min_objectid or finds an item of 'type'
4871 * returns 0 if something is found, 1 if nothing was found and < 0 on error
4873 int btrfs_previous_item(struct btrfs_root *root,
4874 struct btrfs_path *path, u64 min_objectid,
4877 struct btrfs_key found_key;
4878 struct extent_buffer *leaf;
4883 if (path->slots[0] == 0) {
4884 ret = btrfs_prev_leaf(root, path);
4890 leaf = path->nodes[0];
4891 nritems = btrfs_header_nritems(leaf);
4894 if (path->slots[0] == nritems)
4897 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4898 if (found_key.objectid < min_objectid)
4900 if (found_key.type == type)
4902 if (found_key.objectid == min_objectid &&
4903 found_key.type < type)
4910 * search in extent tree to find a previous Metadata/Data extent item with
4913 * returns 0 if something is found, 1 if nothing was found and < 0 on error
4915 int btrfs_previous_extent_item(struct btrfs_root *root,
4916 struct btrfs_path *path, u64 min_objectid)
4918 struct btrfs_key found_key;
4919 struct extent_buffer *leaf;
4924 if (path->slots[0] == 0) {
4925 ret = btrfs_prev_leaf(root, path);
4931 leaf = path->nodes[0];
4932 nritems = btrfs_header_nritems(leaf);
4935 if (path->slots[0] == nritems)
4938 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4939 if (found_key.objectid < min_objectid)
4941 if (found_key.type == BTRFS_EXTENT_ITEM_KEY ||
4942 found_key.type == BTRFS_METADATA_ITEM_KEY)
4944 if (found_key.objectid == min_objectid &&
4945 found_key.type < BTRFS_EXTENT_ITEM_KEY)
4951 int __init btrfs_ctree_init(void)
4953 btrfs_path_cachep = kmem_cache_create("btrfs_path",
4954 sizeof(struct btrfs_path), 0,
4955 SLAB_MEM_SPREAD, NULL);
4956 if (!btrfs_path_cachep)
4961 void __cold btrfs_ctree_exit(void)
4963 kmem_cache_destroy(btrfs_path_cachep);