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>
13 #include "transaction.h"
14 #include "print-tree.h"
18 #include "tree-mod-log.h"
19 #include "tree-checker.h"
21 static int split_node(struct btrfs_trans_handle *trans, struct btrfs_root
22 *root, struct btrfs_path *path, int level);
23 static int split_leaf(struct btrfs_trans_handle *trans, struct btrfs_root *root,
24 const struct btrfs_key *ins_key, struct btrfs_path *path,
25 int data_size, int extend);
26 static int push_node_left(struct btrfs_trans_handle *trans,
27 struct extent_buffer *dst,
28 struct extent_buffer *src, int empty);
29 static int balance_node_right(struct btrfs_trans_handle *trans,
30 struct extent_buffer *dst_buf,
31 struct extent_buffer *src_buf);
32 static void del_ptr(struct btrfs_root *root, struct btrfs_path *path,
35 static const struct btrfs_csums {
38 const char driver[12];
40 [BTRFS_CSUM_TYPE_CRC32] = { .size = 4, .name = "crc32c" },
41 [BTRFS_CSUM_TYPE_XXHASH] = { .size = 8, .name = "xxhash64" },
42 [BTRFS_CSUM_TYPE_SHA256] = { .size = 32, .name = "sha256" },
43 [BTRFS_CSUM_TYPE_BLAKE2] = { .size = 32, .name = "blake2b",
44 .driver = "blake2b-256" },
47 int btrfs_super_csum_size(const struct btrfs_super_block *s)
49 u16 t = btrfs_super_csum_type(s);
51 * csum type is validated at mount time
53 return btrfs_csums[t].size;
56 const char *btrfs_super_csum_name(u16 csum_type)
58 /* csum type is validated at mount time */
59 return btrfs_csums[csum_type].name;
63 * Return driver name if defined, otherwise the name that's also a valid driver
66 const char *btrfs_super_csum_driver(u16 csum_type)
68 /* csum type is validated at mount time */
69 return btrfs_csums[csum_type].driver[0] ?
70 btrfs_csums[csum_type].driver :
71 btrfs_csums[csum_type].name;
74 size_t __attribute_const__ btrfs_get_num_csums(void)
76 return ARRAY_SIZE(btrfs_csums);
79 struct btrfs_path *btrfs_alloc_path(void)
81 return kmem_cache_zalloc(btrfs_path_cachep, GFP_NOFS);
84 /* this also releases the path */
85 void btrfs_free_path(struct btrfs_path *p)
89 btrfs_release_path(p);
90 kmem_cache_free(btrfs_path_cachep, p);
94 * path release drops references on the extent buffers in the path
95 * and it drops any locks held by this path
97 * It is safe to call this on paths that no locks or extent buffers held.
99 noinline void btrfs_release_path(struct btrfs_path *p)
103 for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
108 btrfs_tree_unlock_rw(p->nodes[i], p->locks[i]);
111 free_extent_buffer(p->nodes[i]);
117 * We want the transaction abort to print stack trace only for errors where the
118 * cause could be a bug, eg. due to ENOSPC, and not for common errors that are
119 * caused by external factors.
121 bool __cold abort_should_print_stack(int errno)
133 * safely gets a reference on the root node of a tree. A lock
134 * is not taken, so a concurrent writer may put a different node
135 * at the root of the tree. See btrfs_lock_root_node for the
138 * The extent buffer returned by this has a reference taken, so
139 * it won't disappear. It may stop being the root of the tree
140 * at any time because there are no locks held.
142 struct extent_buffer *btrfs_root_node(struct btrfs_root *root)
144 struct extent_buffer *eb;
148 eb = rcu_dereference(root->node);
151 * RCU really hurts here, we could free up the root node because
152 * it was COWed but we may not get the new root node yet so do
153 * the inc_not_zero dance and if it doesn't work then
154 * synchronize_rcu and try again.
156 if (atomic_inc_not_zero(&eb->refs)) {
167 * Cowonly root (not-shareable trees, everything not subvolume or reloc roots),
168 * just get put onto a simple dirty list. Transaction walks this list to make
169 * sure they get properly updated on disk.
171 static void add_root_to_dirty_list(struct btrfs_root *root)
173 struct btrfs_fs_info *fs_info = root->fs_info;
175 if (test_bit(BTRFS_ROOT_DIRTY, &root->state) ||
176 !test_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state))
179 spin_lock(&fs_info->trans_lock);
180 if (!test_and_set_bit(BTRFS_ROOT_DIRTY, &root->state)) {
181 /* Want the extent tree to be the last on the list */
182 if (root->root_key.objectid == BTRFS_EXTENT_TREE_OBJECTID)
183 list_move_tail(&root->dirty_list,
184 &fs_info->dirty_cowonly_roots);
186 list_move(&root->dirty_list,
187 &fs_info->dirty_cowonly_roots);
189 spin_unlock(&fs_info->trans_lock);
193 * used by snapshot creation to make a copy of a root for a tree with
194 * a given objectid. The buffer with the new root node is returned in
195 * cow_ret, and this func returns zero on success or a negative error code.
197 int btrfs_copy_root(struct btrfs_trans_handle *trans,
198 struct btrfs_root *root,
199 struct extent_buffer *buf,
200 struct extent_buffer **cow_ret, u64 new_root_objectid)
202 struct btrfs_fs_info *fs_info = root->fs_info;
203 struct extent_buffer *cow;
206 struct btrfs_disk_key disk_key;
208 WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
209 trans->transid != fs_info->running_transaction->transid);
210 WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
211 trans->transid != root->last_trans);
213 level = btrfs_header_level(buf);
215 btrfs_item_key(buf, &disk_key, 0);
217 btrfs_node_key(buf, &disk_key, 0);
219 cow = btrfs_alloc_tree_block(trans, root, 0, new_root_objectid,
220 &disk_key, level, buf->start, 0,
221 BTRFS_NESTING_NEW_ROOT);
225 copy_extent_buffer_full(cow, buf);
226 btrfs_set_header_bytenr(cow, cow->start);
227 btrfs_set_header_generation(cow, trans->transid);
228 btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
229 btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
230 BTRFS_HEADER_FLAG_RELOC);
231 if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
232 btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
234 btrfs_set_header_owner(cow, new_root_objectid);
236 write_extent_buffer_fsid(cow, fs_info->fs_devices->metadata_uuid);
238 WARN_ON(btrfs_header_generation(buf) > trans->transid);
239 if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
240 ret = btrfs_inc_ref(trans, root, cow, 1);
242 ret = btrfs_inc_ref(trans, root, cow, 0);
244 btrfs_tree_unlock(cow);
245 free_extent_buffer(cow);
246 btrfs_abort_transaction(trans, ret);
250 btrfs_mark_buffer_dirty(cow);
256 * check if the tree block can be shared by multiple trees
258 int btrfs_block_can_be_shared(struct btrfs_root *root,
259 struct extent_buffer *buf)
262 * Tree blocks not in shareable trees and tree roots are never shared.
263 * If a block was allocated after the last snapshot and the block was
264 * not allocated by tree relocation, we know the block is not shared.
266 if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
267 buf != root->node && buf != root->commit_root &&
268 (btrfs_header_generation(buf) <=
269 btrfs_root_last_snapshot(&root->root_item) ||
270 btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)))
276 static noinline int update_ref_for_cow(struct btrfs_trans_handle *trans,
277 struct btrfs_root *root,
278 struct extent_buffer *buf,
279 struct extent_buffer *cow,
282 struct btrfs_fs_info *fs_info = root->fs_info;
290 * Backrefs update rules:
292 * Always use full backrefs for extent pointers in tree block
293 * allocated by tree relocation.
295 * If a shared tree block is no longer referenced by its owner
296 * tree (btrfs_header_owner(buf) == root->root_key.objectid),
297 * use full backrefs for extent pointers in tree block.
299 * If a tree block is been relocating
300 * (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID),
301 * use full backrefs for extent pointers in tree block.
302 * The reason for this is some operations (such as drop tree)
303 * are only allowed for blocks use full backrefs.
306 if (btrfs_block_can_be_shared(root, buf)) {
307 ret = btrfs_lookup_extent_info(trans, fs_info, buf->start,
308 btrfs_header_level(buf), 1,
314 btrfs_handle_fs_error(fs_info, ret, NULL);
319 if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
320 btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
321 flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
326 owner = btrfs_header_owner(buf);
327 BUG_ON(owner == BTRFS_TREE_RELOC_OBJECTID &&
328 !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
331 if ((owner == root->root_key.objectid ||
332 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) &&
333 !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)) {
334 ret = btrfs_inc_ref(trans, root, buf, 1);
338 if (root->root_key.objectid ==
339 BTRFS_TREE_RELOC_OBJECTID) {
340 ret = btrfs_dec_ref(trans, root, buf, 0);
343 ret = btrfs_inc_ref(trans, root, cow, 1);
347 new_flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
350 if (root->root_key.objectid ==
351 BTRFS_TREE_RELOC_OBJECTID)
352 ret = btrfs_inc_ref(trans, root, cow, 1);
354 ret = btrfs_inc_ref(trans, root, cow, 0);
358 if (new_flags != 0) {
359 int level = btrfs_header_level(buf);
361 ret = btrfs_set_disk_extent_flags(trans, buf,
367 if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
368 if (root->root_key.objectid ==
369 BTRFS_TREE_RELOC_OBJECTID)
370 ret = btrfs_inc_ref(trans, root, cow, 1);
372 ret = btrfs_inc_ref(trans, root, cow, 0);
375 ret = btrfs_dec_ref(trans, root, buf, 1);
379 btrfs_clean_tree_block(buf);
386 * does the dirty work in cow of a single block. The parent block (if
387 * supplied) is updated to point to the new cow copy. The new buffer is marked
388 * dirty and returned locked. If you modify the block it needs to be marked
391 * search_start -- an allocation hint for the new block
393 * empty_size -- a hint that you plan on doing more cow. This is the size in
394 * bytes the allocator should try to find free next to the block it returns.
395 * This is just a hint and may be ignored by the allocator.
397 static noinline int __btrfs_cow_block(struct btrfs_trans_handle *trans,
398 struct btrfs_root *root,
399 struct extent_buffer *buf,
400 struct extent_buffer *parent, int parent_slot,
401 struct extent_buffer **cow_ret,
402 u64 search_start, u64 empty_size,
403 enum btrfs_lock_nesting nest)
405 struct btrfs_fs_info *fs_info = root->fs_info;
406 struct btrfs_disk_key disk_key;
407 struct extent_buffer *cow;
411 u64 parent_start = 0;
416 btrfs_assert_tree_write_locked(buf);
418 WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
419 trans->transid != fs_info->running_transaction->transid);
420 WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
421 trans->transid != root->last_trans);
423 level = btrfs_header_level(buf);
426 btrfs_item_key(buf, &disk_key, 0);
428 btrfs_node_key(buf, &disk_key, 0);
430 if ((root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) && parent)
431 parent_start = parent->start;
433 cow = btrfs_alloc_tree_block(trans, root, parent_start,
434 root->root_key.objectid, &disk_key, level,
435 search_start, empty_size, nest);
439 /* cow is set to blocking by btrfs_init_new_buffer */
441 copy_extent_buffer_full(cow, buf);
442 btrfs_set_header_bytenr(cow, cow->start);
443 btrfs_set_header_generation(cow, trans->transid);
444 btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
445 btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
446 BTRFS_HEADER_FLAG_RELOC);
447 if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
448 btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
450 btrfs_set_header_owner(cow, root->root_key.objectid);
452 write_extent_buffer_fsid(cow, fs_info->fs_devices->metadata_uuid);
454 ret = update_ref_for_cow(trans, root, buf, cow, &last_ref);
456 btrfs_tree_unlock(cow);
457 free_extent_buffer(cow);
458 btrfs_abort_transaction(trans, ret);
462 if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state)) {
463 ret = btrfs_reloc_cow_block(trans, root, buf, cow);
465 btrfs_tree_unlock(cow);
466 free_extent_buffer(cow);
467 btrfs_abort_transaction(trans, ret);
472 if (buf == root->node) {
473 WARN_ON(parent && parent != buf);
474 if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
475 btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
476 parent_start = buf->start;
478 ret = btrfs_tree_mod_log_insert_root(root->node, cow, true);
480 btrfs_tree_unlock(cow);
481 free_extent_buffer(cow);
482 btrfs_abort_transaction(trans, ret);
485 atomic_inc(&cow->refs);
486 rcu_assign_pointer(root->node, cow);
488 btrfs_free_tree_block(trans, btrfs_root_id(root), buf,
489 parent_start, last_ref);
490 free_extent_buffer(buf);
491 add_root_to_dirty_list(root);
493 WARN_ON(trans->transid != btrfs_header_generation(parent));
494 btrfs_tree_mod_log_insert_key(parent, parent_slot,
495 BTRFS_MOD_LOG_KEY_REPLACE, GFP_NOFS);
496 btrfs_set_node_blockptr(parent, parent_slot,
498 btrfs_set_node_ptr_generation(parent, parent_slot,
500 btrfs_mark_buffer_dirty(parent);
502 ret = btrfs_tree_mod_log_free_eb(buf);
504 btrfs_tree_unlock(cow);
505 free_extent_buffer(cow);
506 btrfs_abort_transaction(trans, ret);
510 btrfs_free_tree_block(trans, btrfs_root_id(root), buf,
511 parent_start, last_ref);
514 btrfs_tree_unlock(buf);
515 free_extent_buffer_stale(buf);
516 btrfs_mark_buffer_dirty(cow);
521 static inline int should_cow_block(struct btrfs_trans_handle *trans,
522 struct btrfs_root *root,
523 struct extent_buffer *buf)
525 if (btrfs_is_testing(root->fs_info))
528 /* Ensure we can see the FORCE_COW bit */
529 smp_mb__before_atomic();
532 * We do not need to cow a block if
533 * 1) this block is not created or changed in this transaction;
534 * 2) this block does not belong to TREE_RELOC tree;
535 * 3) the root is not forced COW.
537 * What is forced COW:
538 * when we create snapshot during committing the transaction,
539 * after we've finished copying src root, we must COW the shared
540 * block to ensure the metadata consistency.
542 if (btrfs_header_generation(buf) == trans->transid &&
543 !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN) &&
544 !(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
545 btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)) &&
546 !test_bit(BTRFS_ROOT_FORCE_COW, &root->state))
552 * cows a single block, see __btrfs_cow_block for the real work.
553 * This version of it has extra checks so that a block isn't COWed more than
554 * once per transaction, as long as it hasn't been written yet
556 noinline int btrfs_cow_block(struct btrfs_trans_handle *trans,
557 struct btrfs_root *root, struct extent_buffer *buf,
558 struct extent_buffer *parent, int parent_slot,
559 struct extent_buffer **cow_ret,
560 enum btrfs_lock_nesting nest)
562 struct btrfs_fs_info *fs_info = root->fs_info;
566 if (test_bit(BTRFS_ROOT_DELETING, &root->state))
568 "COW'ing blocks on a fs root that's being dropped");
570 if (trans->transaction != fs_info->running_transaction)
571 WARN(1, KERN_CRIT "trans %llu running %llu\n",
573 fs_info->running_transaction->transid);
575 if (trans->transid != fs_info->generation)
576 WARN(1, KERN_CRIT "trans %llu running %llu\n",
577 trans->transid, fs_info->generation);
579 if (!should_cow_block(trans, root, buf)) {
584 search_start = buf->start & ~((u64)SZ_1G - 1);
587 * Before CoWing this block for later modification, check if it's
588 * the subtree root and do the delayed subtree trace if needed.
590 * Also We don't care about the error, as it's handled internally.
592 btrfs_qgroup_trace_subtree_after_cow(trans, root, buf);
593 ret = __btrfs_cow_block(trans, root, buf, parent,
594 parent_slot, cow_ret, search_start, 0, nest);
596 trace_btrfs_cow_block(root, buf, *cow_ret);
600 ALLOW_ERROR_INJECTION(btrfs_cow_block, ERRNO);
603 * helper function for defrag to decide if two blocks pointed to by a
604 * node are actually close by
606 static int close_blocks(u64 blocknr, u64 other, u32 blocksize)
608 if (blocknr < other && other - (blocknr + blocksize) < 32768)
610 if (blocknr > other && blocknr - (other + blocksize) < 32768)
615 #ifdef __LITTLE_ENDIAN
618 * Compare two keys, on little-endian the disk order is same as CPU order and
619 * we can avoid the conversion.
621 static int comp_keys(const struct btrfs_disk_key *disk_key,
622 const struct btrfs_key *k2)
624 const struct btrfs_key *k1 = (const struct btrfs_key *)disk_key;
626 return btrfs_comp_cpu_keys(k1, k2);
632 * compare two keys in a memcmp fashion
634 static int comp_keys(const struct btrfs_disk_key *disk,
635 const struct btrfs_key *k2)
639 btrfs_disk_key_to_cpu(&k1, disk);
641 return btrfs_comp_cpu_keys(&k1, k2);
646 * same as comp_keys only with two btrfs_key's
648 int __pure btrfs_comp_cpu_keys(const struct btrfs_key *k1, const struct btrfs_key *k2)
650 if (k1->objectid > k2->objectid)
652 if (k1->objectid < k2->objectid)
654 if (k1->type > k2->type)
656 if (k1->type < k2->type)
658 if (k1->offset > k2->offset)
660 if (k1->offset < k2->offset)
666 * this is used by the defrag code to go through all the
667 * leaves pointed to by a node and reallocate them so that
668 * disk order is close to key order
670 int btrfs_realloc_node(struct btrfs_trans_handle *trans,
671 struct btrfs_root *root, struct extent_buffer *parent,
672 int start_slot, u64 *last_ret,
673 struct btrfs_key *progress)
675 struct btrfs_fs_info *fs_info = root->fs_info;
676 struct extent_buffer *cur;
678 u64 search_start = *last_ret;
686 int progress_passed = 0;
687 struct btrfs_disk_key disk_key;
689 WARN_ON(trans->transaction != fs_info->running_transaction);
690 WARN_ON(trans->transid != fs_info->generation);
692 parent_nritems = btrfs_header_nritems(parent);
693 blocksize = fs_info->nodesize;
694 end_slot = parent_nritems - 1;
696 if (parent_nritems <= 1)
699 for (i = start_slot; i <= end_slot; i++) {
702 btrfs_node_key(parent, &disk_key, i);
703 if (!progress_passed && comp_keys(&disk_key, progress) < 0)
707 blocknr = btrfs_node_blockptr(parent, i);
709 last_block = blocknr;
712 other = btrfs_node_blockptr(parent, i - 1);
713 close = close_blocks(blocknr, other, blocksize);
715 if (!close && i < end_slot) {
716 other = btrfs_node_blockptr(parent, i + 1);
717 close = close_blocks(blocknr, other, blocksize);
720 last_block = blocknr;
724 cur = btrfs_read_node_slot(parent, i);
727 if (search_start == 0)
728 search_start = last_block;
730 btrfs_tree_lock(cur);
731 err = __btrfs_cow_block(trans, root, cur, parent, i,
734 (end_slot - i) * blocksize),
737 btrfs_tree_unlock(cur);
738 free_extent_buffer(cur);
741 search_start = cur->start;
742 last_block = cur->start;
743 *last_ret = search_start;
744 btrfs_tree_unlock(cur);
745 free_extent_buffer(cur);
751 * Search for a key in the given extent_buffer.
753 * The lower boundary for the search is specified by the slot number @low. Use a
754 * value of 0 to search over the whole extent buffer.
756 * The slot in the extent buffer is returned via @slot. If the key exists in the
757 * extent buffer, then @slot will point to the slot where the key is, otherwise
758 * it points to the slot where you would insert the key.
760 * Slot may point to the total number of items (i.e. one position beyond the last
761 * key) if the key is bigger than the last key in the extent buffer.
763 static noinline int generic_bin_search(struct extent_buffer *eb, int low,
764 const struct btrfs_key *key, int *slot)
768 int high = btrfs_header_nritems(eb);
770 const int key_size = sizeof(struct btrfs_disk_key);
773 btrfs_err(eb->fs_info,
774 "%s: low (%d) > high (%d) eb %llu owner %llu level %d",
775 __func__, low, high, eb->start,
776 btrfs_header_owner(eb), btrfs_header_level(eb));
780 if (btrfs_header_level(eb) == 0) {
781 p = offsetof(struct btrfs_leaf, items);
782 item_size = sizeof(struct btrfs_item);
784 p = offsetof(struct btrfs_node, ptrs);
785 item_size = sizeof(struct btrfs_key_ptr);
790 unsigned long offset;
791 struct btrfs_disk_key *tmp;
792 struct btrfs_disk_key unaligned;
795 mid = (low + high) / 2;
796 offset = p + mid * item_size;
797 oip = offset_in_page(offset);
799 if (oip + key_size <= PAGE_SIZE) {
800 const unsigned long idx = get_eb_page_index(offset);
801 char *kaddr = page_address(eb->pages[idx]);
803 oip = get_eb_offset_in_page(eb, offset);
804 tmp = (struct btrfs_disk_key *)(kaddr + oip);
806 read_extent_buffer(eb, &unaligned, offset, key_size);
810 ret = comp_keys(tmp, key);
826 * Simple binary search on an extent buffer. Works for both leaves and nodes, and
827 * always searches over the whole range of keys (slot 0 to slot 'nritems - 1').
829 int btrfs_bin_search(struct extent_buffer *eb, const struct btrfs_key *key,
832 return generic_bin_search(eb, 0, key, slot);
835 static void root_add_used(struct btrfs_root *root, u32 size)
837 spin_lock(&root->accounting_lock);
838 btrfs_set_root_used(&root->root_item,
839 btrfs_root_used(&root->root_item) + size);
840 spin_unlock(&root->accounting_lock);
843 static void root_sub_used(struct btrfs_root *root, u32 size)
845 spin_lock(&root->accounting_lock);
846 btrfs_set_root_used(&root->root_item,
847 btrfs_root_used(&root->root_item) - size);
848 spin_unlock(&root->accounting_lock);
851 /* given a node and slot number, this reads the blocks it points to. The
852 * extent buffer is returned with a reference taken (but unlocked).
854 struct extent_buffer *btrfs_read_node_slot(struct extent_buffer *parent,
857 int level = btrfs_header_level(parent);
858 struct extent_buffer *eb;
859 struct btrfs_key first_key;
861 if (slot < 0 || slot >= btrfs_header_nritems(parent))
862 return ERR_PTR(-ENOENT);
866 btrfs_node_key_to_cpu(parent, &first_key, slot);
867 eb = read_tree_block(parent->fs_info, btrfs_node_blockptr(parent, slot),
868 btrfs_header_owner(parent),
869 btrfs_node_ptr_generation(parent, slot),
870 level - 1, &first_key);
873 if (!extent_buffer_uptodate(eb)) {
874 free_extent_buffer(eb);
875 return ERR_PTR(-EIO);
882 * node level balancing, used to make sure nodes are in proper order for
883 * item deletion. We balance from the top down, so we have to make sure
884 * that a deletion won't leave an node completely empty later on.
886 static noinline int balance_level(struct btrfs_trans_handle *trans,
887 struct btrfs_root *root,
888 struct btrfs_path *path, int level)
890 struct btrfs_fs_info *fs_info = root->fs_info;
891 struct extent_buffer *right = NULL;
892 struct extent_buffer *mid;
893 struct extent_buffer *left = NULL;
894 struct extent_buffer *parent = NULL;
898 int orig_slot = path->slots[level];
903 mid = path->nodes[level];
905 WARN_ON(path->locks[level] != BTRFS_WRITE_LOCK);
906 WARN_ON(btrfs_header_generation(mid) != trans->transid);
908 orig_ptr = btrfs_node_blockptr(mid, orig_slot);
910 if (level < BTRFS_MAX_LEVEL - 1) {
911 parent = path->nodes[level + 1];
912 pslot = path->slots[level + 1];
916 * deal with the case where there is only one pointer in the root
917 * by promoting the node below to a root
920 struct extent_buffer *child;
922 if (btrfs_header_nritems(mid) != 1)
925 /* promote the child to a root */
926 child = btrfs_read_node_slot(mid, 0);
928 ret = PTR_ERR(child);
929 btrfs_handle_fs_error(fs_info, ret, NULL);
933 btrfs_tree_lock(child);
934 ret = btrfs_cow_block(trans, root, child, mid, 0, &child,
937 btrfs_tree_unlock(child);
938 free_extent_buffer(child);
942 ret = btrfs_tree_mod_log_insert_root(root->node, child, true);
944 btrfs_tree_unlock(child);
945 free_extent_buffer(child);
946 btrfs_abort_transaction(trans, ret);
949 rcu_assign_pointer(root->node, child);
951 add_root_to_dirty_list(root);
952 btrfs_tree_unlock(child);
954 path->locks[level] = 0;
955 path->nodes[level] = NULL;
956 btrfs_clean_tree_block(mid);
957 btrfs_tree_unlock(mid);
958 /* once for the path */
959 free_extent_buffer(mid);
961 root_sub_used(root, mid->len);
962 btrfs_free_tree_block(trans, btrfs_root_id(root), mid, 0, 1);
963 /* once for the root ptr */
964 free_extent_buffer_stale(mid);
967 if (btrfs_header_nritems(mid) >
968 BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 4)
971 left = btrfs_read_node_slot(parent, pslot - 1);
976 __btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
977 wret = btrfs_cow_block(trans, root, left,
978 parent, pslot - 1, &left,
979 BTRFS_NESTING_LEFT_COW);
986 right = btrfs_read_node_slot(parent, pslot + 1);
991 __btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
992 wret = btrfs_cow_block(trans, root, right,
993 parent, pslot + 1, &right,
994 BTRFS_NESTING_RIGHT_COW);
1001 /* first, try to make some room in the middle buffer */
1003 orig_slot += btrfs_header_nritems(left);
1004 wret = push_node_left(trans, left, mid, 1);
1010 * then try to empty the right most buffer into the middle
1013 wret = push_node_left(trans, mid, right, 1);
1014 if (wret < 0 && wret != -ENOSPC)
1016 if (btrfs_header_nritems(right) == 0) {
1017 btrfs_clean_tree_block(right);
1018 btrfs_tree_unlock(right);
1019 del_ptr(root, path, level + 1, pslot + 1);
1020 root_sub_used(root, right->len);
1021 btrfs_free_tree_block(trans, btrfs_root_id(root), right,
1023 free_extent_buffer_stale(right);
1026 struct btrfs_disk_key right_key;
1027 btrfs_node_key(right, &right_key, 0);
1028 ret = btrfs_tree_mod_log_insert_key(parent, pslot + 1,
1029 BTRFS_MOD_LOG_KEY_REPLACE, GFP_NOFS);
1031 btrfs_abort_transaction(trans, ret);
1034 btrfs_set_node_key(parent, &right_key, pslot + 1);
1035 btrfs_mark_buffer_dirty(parent);
1038 if (btrfs_header_nritems(mid) == 1) {
1040 * we're not allowed to leave a node with one item in the
1041 * tree during a delete. A deletion from lower in the tree
1042 * could try to delete the only pointer in this node.
1043 * So, pull some keys from the left.
1044 * There has to be a left pointer at this point because
1045 * otherwise we would have pulled some pointers from the
1050 btrfs_handle_fs_error(fs_info, ret, NULL);
1053 wret = balance_node_right(trans, mid, left);
1059 wret = push_node_left(trans, left, mid, 1);
1065 if (btrfs_header_nritems(mid) == 0) {
1066 btrfs_clean_tree_block(mid);
1067 btrfs_tree_unlock(mid);
1068 del_ptr(root, path, level + 1, pslot);
1069 root_sub_used(root, mid->len);
1070 btrfs_free_tree_block(trans, btrfs_root_id(root), mid, 0, 1);
1071 free_extent_buffer_stale(mid);
1074 /* update the parent key to reflect our changes */
1075 struct btrfs_disk_key mid_key;
1076 btrfs_node_key(mid, &mid_key, 0);
1077 ret = btrfs_tree_mod_log_insert_key(parent, pslot,
1078 BTRFS_MOD_LOG_KEY_REPLACE, GFP_NOFS);
1080 btrfs_abort_transaction(trans, ret);
1083 btrfs_set_node_key(parent, &mid_key, pslot);
1084 btrfs_mark_buffer_dirty(parent);
1087 /* update the path */
1089 if (btrfs_header_nritems(left) > orig_slot) {
1090 atomic_inc(&left->refs);
1091 /* left was locked after cow */
1092 path->nodes[level] = left;
1093 path->slots[level + 1] -= 1;
1094 path->slots[level] = orig_slot;
1096 btrfs_tree_unlock(mid);
1097 free_extent_buffer(mid);
1100 orig_slot -= btrfs_header_nritems(left);
1101 path->slots[level] = orig_slot;
1104 /* double check we haven't messed things up */
1106 btrfs_node_blockptr(path->nodes[level], path->slots[level]))
1110 btrfs_tree_unlock(right);
1111 free_extent_buffer(right);
1114 if (path->nodes[level] != left)
1115 btrfs_tree_unlock(left);
1116 free_extent_buffer(left);
1121 /* Node balancing for insertion. Here we only split or push nodes around
1122 * when they are completely full. This is also done top down, so we
1123 * have to be pessimistic.
1125 static noinline int push_nodes_for_insert(struct btrfs_trans_handle *trans,
1126 struct btrfs_root *root,
1127 struct btrfs_path *path, int level)
1129 struct btrfs_fs_info *fs_info = root->fs_info;
1130 struct extent_buffer *right = NULL;
1131 struct extent_buffer *mid;
1132 struct extent_buffer *left = NULL;
1133 struct extent_buffer *parent = NULL;
1137 int orig_slot = path->slots[level];
1142 mid = path->nodes[level];
1143 WARN_ON(btrfs_header_generation(mid) != trans->transid);
1145 if (level < BTRFS_MAX_LEVEL - 1) {
1146 parent = path->nodes[level + 1];
1147 pslot = path->slots[level + 1];
1153 left = btrfs_read_node_slot(parent, pslot - 1);
1157 /* first, try to make some room in the middle buffer */
1161 __btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
1163 left_nr = btrfs_header_nritems(left);
1164 if (left_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
1167 ret = btrfs_cow_block(trans, root, left, parent,
1169 BTRFS_NESTING_LEFT_COW);
1173 wret = push_node_left(trans, left, mid, 0);
1179 struct btrfs_disk_key disk_key;
1180 orig_slot += left_nr;
1181 btrfs_node_key(mid, &disk_key, 0);
1182 ret = btrfs_tree_mod_log_insert_key(parent, pslot,
1183 BTRFS_MOD_LOG_KEY_REPLACE, GFP_NOFS);
1185 btrfs_set_node_key(parent, &disk_key, pslot);
1186 btrfs_mark_buffer_dirty(parent);
1187 if (btrfs_header_nritems(left) > orig_slot) {
1188 path->nodes[level] = left;
1189 path->slots[level + 1] -= 1;
1190 path->slots[level] = orig_slot;
1191 btrfs_tree_unlock(mid);
1192 free_extent_buffer(mid);
1195 btrfs_header_nritems(left);
1196 path->slots[level] = orig_slot;
1197 btrfs_tree_unlock(left);
1198 free_extent_buffer(left);
1202 btrfs_tree_unlock(left);
1203 free_extent_buffer(left);
1205 right = btrfs_read_node_slot(parent, pslot + 1);
1210 * then try to empty the right most buffer into the middle
1215 __btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
1217 right_nr = btrfs_header_nritems(right);
1218 if (right_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
1221 ret = btrfs_cow_block(trans, root, right,
1223 &right, BTRFS_NESTING_RIGHT_COW);
1227 wret = balance_node_right(trans, right, mid);
1233 struct btrfs_disk_key disk_key;
1235 btrfs_node_key(right, &disk_key, 0);
1236 ret = btrfs_tree_mod_log_insert_key(parent, pslot + 1,
1237 BTRFS_MOD_LOG_KEY_REPLACE, GFP_NOFS);
1239 btrfs_set_node_key(parent, &disk_key, pslot + 1);
1240 btrfs_mark_buffer_dirty(parent);
1242 if (btrfs_header_nritems(mid) <= orig_slot) {
1243 path->nodes[level] = right;
1244 path->slots[level + 1] += 1;
1245 path->slots[level] = orig_slot -
1246 btrfs_header_nritems(mid);
1247 btrfs_tree_unlock(mid);
1248 free_extent_buffer(mid);
1250 btrfs_tree_unlock(right);
1251 free_extent_buffer(right);
1255 btrfs_tree_unlock(right);
1256 free_extent_buffer(right);
1262 * readahead one full node of leaves, finding things that are close
1263 * to the block in 'slot', and triggering ra on them.
1265 static void reada_for_search(struct btrfs_fs_info *fs_info,
1266 struct btrfs_path *path,
1267 int level, int slot, u64 objectid)
1269 struct extent_buffer *node;
1270 struct btrfs_disk_key disk_key;
1280 if (level != 1 && path->reada != READA_FORWARD_ALWAYS)
1283 if (!path->nodes[level])
1286 node = path->nodes[level];
1289 * Since the time between visiting leaves is much shorter than the time
1290 * between visiting nodes, limit read ahead of nodes to 1, to avoid too
1291 * much IO at once (possibly random).
1293 if (path->reada == READA_FORWARD_ALWAYS) {
1295 nread_max = node->fs_info->nodesize;
1297 nread_max = SZ_128K;
1302 search = btrfs_node_blockptr(node, slot);
1303 blocksize = fs_info->nodesize;
1304 if (path->reada != READA_FORWARD_ALWAYS) {
1305 struct extent_buffer *eb;
1307 eb = find_extent_buffer(fs_info, search);
1309 free_extent_buffer(eb);
1316 nritems = btrfs_header_nritems(node);
1320 if (path->reada == READA_BACK) {
1324 } else if (path->reada == READA_FORWARD ||
1325 path->reada == READA_FORWARD_ALWAYS) {
1330 if (path->reada == READA_BACK && objectid) {
1331 btrfs_node_key(node, &disk_key, nr);
1332 if (btrfs_disk_key_objectid(&disk_key) != objectid)
1335 search = btrfs_node_blockptr(node, nr);
1336 if (path->reada == READA_FORWARD_ALWAYS ||
1337 (search <= target && target - search <= 65536) ||
1338 (search > target && search - target <= 65536)) {
1339 btrfs_readahead_node_child(node, nr);
1343 if (nread > nread_max || nscan > 32)
1348 static noinline void reada_for_balance(struct btrfs_path *path, int level)
1350 struct extent_buffer *parent;
1354 parent = path->nodes[level + 1];
1358 nritems = btrfs_header_nritems(parent);
1359 slot = path->slots[level + 1];
1362 btrfs_readahead_node_child(parent, slot - 1);
1363 if (slot + 1 < nritems)
1364 btrfs_readahead_node_child(parent, slot + 1);
1369 * when we walk down the tree, it is usually safe to unlock the higher layers
1370 * in the tree. The exceptions are when our path goes through slot 0, because
1371 * operations on the tree might require changing key pointers higher up in the
1374 * callers might also have set path->keep_locks, which tells this code to keep
1375 * the lock if the path points to the last slot in the block. This is part of
1376 * walking through the tree, and selecting the next slot in the higher block.
1378 * lowest_unlock sets the lowest level in the tree we're allowed to unlock. so
1379 * if lowest_unlock is 1, level 0 won't be unlocked
1381 static noinline void unlock_up(struct btrfs_path *path, int level,
1382 int lowest_unlock, int min_write_lock_level,
1383 int *write_lock_level)
1386 int skip_level = level;
1387 bool check_skip = true;
1389 for (i = level; i < BTRFS_MAX_LEVEL; i++) {
1390 if (!path->nodes[i])
1392 if (!path->locks[i])
1396 if (path->slots[i] == 0) {
1401 if (path->keep_locks) {
1404 nritems = btrfs_header_nritems(path->nodes[i]);
1405 if (nritems < 1 || path->slots[i] >= nritems - 1) {
1412 if (i >= lowest_unlock && i > skip_level) {
1414 btrfs_tree_unlock_rw(path->nodes[i], path->locks[i]);
1416 if (write_lock_level &&
1417 i > min_write_lock_level &&
1418 i <= *write_lock_level) {
1419 *write_lock_level = i - 1;
1426 * Helper function for btrfs_search_slot() and other functions that do a search
1427 * on a btree. The goal is to find a tree block in the cache (the radix tree at
1428 * fs_info->buffer_radix), but if we can't find it, or it's not up to date, read
1429 * its pages from disk.
1431 * Returns -EAGAIN, with the path unlocked, if the caller needs to repeat the
1432 * whole btree search, starting again from the current root node.
1435 read_block_for_search(struct btrfs_root *root, struct btrfs_path *p,
1436 struct extent_buffer **eb_ret, int level, int slot,
1437 const struct btrfs_key *key)
1439 struct btrfs_fs_info *fs_info = root->fs_info;
1442 struct extent_buffer *tmp;
1443 struct btrfs_key first_key;
1448 unlock_up = ((level + 1 < BTRFS_MAX_LEVEL) && p->locks[level + 1]);
1449 blocknr = btrfs_node_blockptr(*eb_ret, slot);
1450 gen = btrfs_node_ptr_generation(*eb_ret, slot);
1451 parent_level = btrfs_header_level(*eb_ret);
1452 btrfs_node_key_to_cpu(*eb_ret, &first_key, slot);
1455 * If we need to read an extent buffer from disk and we are holding locks
1456 * on upper level nodes, we unlock all the upper nodes before reading the
1457 * extent buffer, and then return -EAGAIN to the caller as it needs to
1458 * restart the search. We don't release the lock on the current level
1459 * because we need to walk this node to figure out which blocks to read.
1461 tmp = find_extent_buffer(fs_info, blocknr);
1463 if (p->reada == READA_FORWARD_ALWAYS)
1464 reada_for_search(fs_info, p, level, slot, key->objectid);
1466 /* first we do an atomic uptodate check */
1467 if (btrfs_buffer_uptodate(tmp, gen, 1) > 0) {
1469 * Do extra check for first_key, eb can be stale due to
1470 * being cached, read from scrub, or have multiple
1471 * parents (shared tree blocks).
1473 if (btrfs_verify_level_key(tmp,
1474 parent_level - 1, &first_key, gen)) {
1475 free_extent_buffer(tmp);
1483 free_extent_buffer(tmp);
1488 btrfs_unlock_up_safe(p, level + 1);
1490 /* now we're allowed to do a blocking uptodate check */
1491 ret = btrfs_read_extent_buffer(tmp, gen, parent_level - 1, &first_key);
1493 free_extent_buffer(tmp);
1494 btrfs_release_path(p);
1497 if (btrfs_check_eb_owner(tmp, root->root_key.objectid)) {
1498 free_extent_buffer(tmp);
1499 btrfs_release_path(p);
1507 } else if (p->nowait) {
1512 btrfs_unlock_up_safe(p, level + 1);
1518 if (p->reada != READA_NONE)
1519 reada_for_search(fs_info, p, level, slot, key->objectid);
1521 tmp = read_tree_block(fs_info, blocknr, root->root_key.objectid,
1522 gen, parent_level - 1, &first_key);
1524 btrfs_release_path(p);
1525 return PTR_ERR(tmp);
1528 * If the read above didn't mark this buffer up to date,
1529 * it will never end up being up to date. Set ret to EIO now
1530 * and give up so that our caller doesn't loop forever
1533 if (!extent_buffer_uptodate(tmp))
1540 free_extent_buffer(tmp);
1541 btrfs_release_path(p);
1548 * helper function for btrfs_search_slot. This does all of the checks
1549 * for node-level blocks and does any balancing required based on
1552 * If no extra work was required, zero is returned. If we had to
1553 * drop the path, -EAGAIN is returned and btrfs_search_slot must
1557 setup_nodes_for_search(struct btrfs_trans_handle *trans,
1558 struct btrfs_root *root, struct btrfs_path *p,
1559 struct extent_buffer *b, int level, int ins_len,
1560 int *write_lock_level)
1562 struct btrfs_fs_info *fs_info = root->fs_info;
1565 if ((p->search_for_split || ins_len > 0) && btrfs_header_nritems(b) >=
1566 BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3) {
1568 if (*write_lock_level < level + 1) {
1569 *write_lock_level = level + 1;
1570 btrfs_release_path(p);
1574 reada_for_balance(p, level);
1575 ret = split_node(trans, root, p, level);
1577 b = p->nodes[level];
1578 } else if (ins_len < 0 && btrfs_header_nritems(b) <
1579 BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 2) {
1581 if (*write_lock_level < level + 1) {
1582 *write_lock_level = level + 1;
1583 btrfs_release_path(p);
1587 reada_for_balance(p, level);
1588 ret = balance_level(trans, root, p, level);
1592 b = p->nodes[level];
1594 btrfs_release_path(p);
1597 BUG_ON(btrfs_header_nritems(b) == 1);
1602 int btrfs_find_item(struct btrfs_root *fs_root, struct btrfs_path *path,
1603 u64 iobjectid, u64 ioff, u8 key_type,
1604 struct btrfs_key *found_key)
1607 struct btrfs_key key;
1608 struct extent_buffer *eb;
1613 key.type = key_type;
1614 key.objectid = iobjectid;
1617 ret = btrfs_search_slot(NULL, fs_root, &key, path, 0, 0);
1621 eb = path->nodes[0];
1622 if (ret && path->slots[0] >= btrfs_header_nritems(eb)) {
1623 ret = btrfs_next_leaf(fs_root, path);
1626 eb = path->nodes[0];
1629 btrfs_item_key_to_cpu(eb, found_key, path->slots[0]);
1630 if (found_key->type != key.type ||
1631 found_key->objectid != key.objectid)
1637 static struct extent_buffer *btrfs_search_slot_get_root(struct btrfs_root *root,
1638 struct btrfs_path *p,
1639 int write_lock_level)
1641 struct extent_buffer *b;
1645 if (p->search_commit_root) {
1646 b = root->commit_root;
1647 atomic_inc(&b->refs);
1648 level = btrfs_header_level(b);
1650 * Ensure that all callers have set skip_locking when
1651 * p->search_commit_root = 1.
1653 ASSERT(p->skip_locking == 1);
1658 if (p->skip_locking) {
1659 b = btrfs_root_node(root);
1660 level = btrfs_header_level(b);
1664 /* We try very hard to do read locks on the root */
1665 root_lock = BTRFS_READ_LOCK;
1668 * If the level is set to maximum, we can skip trying to get the read
1671 if (write_lock_level < BTRFS_MAX_LEVEL) {
1673 * We don't know the level of the root node until we actually
1674 * have it read locked
1677 b = btrfs_try_read_lock_root_node(root);
1681 b = btrfs_read_lock_root_node(root);
1683 level = btrfs_header_level(b);
1684 if (level > write_lock_level)
1687 /* Whoops, must trade for write lock */
1688 btrfs_tree_read_unlock(b);
1689 free_extent_buffer(b);
1692 b = btrfs_lock_root_node(root);
1693 root_lock = BTRFS_WRITE_LOCK;
1695 /* The level might have changed, check again */
1696 level = btrfs_header_level(b);
1700 * The root may have failed to write out at some point, and thus is no
1701 * longer valid, return an error in this case.
1703 if (!extent_buffer_uptodate(b)) {
1705 btrfs_tree_unlock_rw(b, root_lock);
1706 free_extent_buffer(b);
1707 return ERR_PTR(-EIO);
1710 p->nodes[level] = b;
1711 if (!p->skip_locking)
1712 p->locks[level] = root_lock;
1714 * Callers are responsible for dropping b's references.
1720 * Replace the extent buffer at the lowest level of the path with a cloned
1721 * version. The purpose is to be able to use it safely, after releasing the
1722 * commit root semaphore, even if relocation is happening in parallel, the
1723 * transaction used for relocation is committed and the extent buffer is
1724 * reallocated in the next transaction.
1726 * This is used in a context where the caller does not prevent transaction
1727 * commits from happening, either by holding a transaction handle or holding
1728 * some lock, while it's doing searches through a commit root.
1729 * At the moment it's only used for send operations.
1731 static int finish_need_commit_sem_search(struct btrfs_path *path)
1733 const int i = path->lowest_level;
1734 const int slot = path->slots[i];
1735 struct extent_buffer *lowest = path->nodes[i];
1736 struct extent_buffer *clone;
1738 ASSERT(path->need_commit_sem);
1743 lockdep_assert_held_read(&lowest->fs_info->commit_root_sem);
1745 clone = btrfs_clone_extent_buffer(lowest);
1749 btrfs_release_path(path);
1750 path->nodes[i] = clone;
1751 path->slots[i] = slot;
1756 static inline int search_for_key_slot(struct extent_buffer *eb,
1757 int search_low_slot,
1758 const struct btrfs_key *key,
1763 * If a previous call to btrfs_bin_search() on a parent node returned an
1764 * exact match (prev_cmp == 0), we can safely assume the target key will
1765 * always be at slot 0 on lower levels, since each key pointer
1766 * (struct btrfs_key_ptr) refers to the lowest key accessible from the
1767 * subtree it points to. Thus we can skip searching lower levels.
1769 if (prev_cmp == 0) {
1774 return generic_bin_search(eb, search_low_slot, key, slot);
1777 static int search_leaf(struct btrfs_trans_handle *trans,
1778 struct btrfs_root *root,
1779 const struct btrfs_key *key,
1780 struct btrfs_path *path,
1784 struct extent_buffer *leaf = path->nodes[0];
1785 int leaf_free_space = -1;
1786 int search_low_slot = 0;
1788 bool do_bin_search = true;
1791 * If we are doing an insertion, the leaf has enough free space and the
1792 * destination slot for the key is not slot 0, then we can unlock our
1793 * write lock on the parent, and any other upper nodes, before doing the
1794 * binary search on the leaf (with search_for_key_slot()), allowing other
1795 * tasks to lock the parent and any other upper nodes.
1799 * Cache the leaf free space, since we will need it later and it
1800 * will not change until then.
1802 leaf_free_space = btrfs_leaf_free_space(leaf);
1805 * !path->locks[1] means we have a single node tree, the leaf is
1806 * the root of the tree.
1808 if (path->locks[1] && leaf_free_space >= ins_len) {
1809 struct btrfs_disk_key first_key;
1811 ASSERT(btrfs_header_nritems(leaf) > 0);
1812 btrfs_item_key(leaf, &first_key, 0);
1815 * Doing the extra comparison with the first key is cheap,
1816 * taking into account that the first key is very likely
1817 * already in a cache line because it immediately follows
1818 * the extent buffer's header and we have recently accessed
1819 * the header's level field.
1821 ret = comp_keys(&first_key, key);
1824 * The first key is smaller than the key we want
1825 * to insert, so we are safe to unlock all upper
1826 * nodes and we have to do the binary search.
1828 * We do use btrfs_unlock_up_safe() and not
1829 * unlock_up() because the later does not unlock
1830 * nodes with a slot of 0 - we can safely unlock
1831 * any node even if its slot is 0 since in this
1832 * case the key does not end up at slot 0 of the
1833 * leaf and there's no need to split the leaf.
1835 btrfs_unlock_up_safe(path, 1);
1836 search_low_slot = 1;
1839 * The first key is >= then the key we want to
1840 * insert, so we can skip the binary search as
1841 * the target key will be at slot 0.
1843 * We can not unlock upper nodes when the key is
1844 * less than the first key, because we will need
1845 * to update the key at slot 0 of the parent node
1846 * and possibly of other upper nodes too.
1847 * If the key matches the first key, then we can
1848 * unlock all the upper nodes, using
1849 * btrfs_unlock_up_safe() instead of unlock_up()
1853 btrfs_unlock_up_safe(path, 1);
1855 * ret is already 0 or 1, matching the result of
1856 * a btrfs_bin_search() call, so there is no need
1859 do_bin_search = false;
1865 if (do_bin_search) {
1866 ret = search_for_key_slot(leaf, search_low_slot, key,
1867 prev_cmp, &path->slots[0]);
1874 * Item key already exists. In this case, if we are allowed to
1875 * insert the item (for example, in dir_item case, item key
1876 * collision is allowed), it will be merged with the original
1877 * item. Only the item size grows, no new btrfs item will be
1878 * added. If search_for_extension is not set, ins_len already
1879 * accounts the size btrfs_item, deduct it here so leaf space
1880 * check will be correct.
1882 if (ret == 0 && !path->search_for_extension) {
1883 ASSERT(ins_len >= sizeof(struct btrfs_item));
1884 ins_len -= sizeof(struct btrfs_item);
1887 ASSERT(leaf_free_space >= 0);
1889 if (leaf_free_space < ins_len) {
1892 err = split_leaf(trans, root, key, path, ins_len,
1895 if (WARN_ON(err > 0))
1906 * btrfs_search_slot - look for a key in a tree and perform necessary
1907 * modifications to preserve tree invariants.
1909 * @trans: Handle of transaction, used when modifying the tree
1910 * @p: Holds all btree nodes along the search path
1911 * @root: The root node of the tree
1912 * @key: The key we are looking for
1913 * @ins_len: Indicates purpose of search:
1914 * >0 for inserts it's size of item inserted (*)
1916 * 0 for plain searches, not modifying the tree
1918 * (*) If size of item inserted doesn't include
1919 * sizeof(struct btrfs_item), then p->search_for_extension must
1921 * @cow: boolean should CoW operations be performed. Must always be 1
1922 * when modifying the tree.
1924 * If @ins_len > 0, nodes and leaves will be split as we walk down the tree.
1925 * If @ins_len < 0, nodes will be merged as we walk down the tree (if possible)
1927 * If @key is found, 0 is returned and you can find the item in the leaf level
1928 * of the path (level 0)
1930 * If @key isn't found, 1 is returned and the leaf level of the path (level 0)
1931 * points to the slot where it should be inserted
1933 * If an error is encountered while searching the tree a negative error number
1936 int btrfs_search_slot(struct btrfs_trans_handle *trans, struct btrfs_root *root,
1937 const struct btrfs_key *key, struct btrfs_path *p,
1938 int ins_len, int cow)
1940 struct btrfs_fs_info *fs_info = root->fs_info;
1941 struct extent_buffer *b;
1946 int lowest_unlock = 1;
1947 /* everything at write_lock_level or lower must be write locked */
1948 int write_lock_level = 0;
1949 u8 lowest_level = 0;
1950 int min_write_lock_level;
1953 lowest_level = p->lowest_level;
1954 WARN_ON(lowest_level && ins_len > 0);
1955 WARN_ON(p->nodes[0] != NULL);
1956 BUG_ON(!cow && ins_len);
1959 * For now only allow nowait for read only operations. There's no
1960 * strict reason why we can't, we just only need it for reads so it's
1961 * only implemented for reads.
1963 ASSERT(!p->nowait || !cow);
1968 /* when we are removing items, we might have to go up to level
1969 * two as we update tree pointers Make sure we keep write
1970 * for those levels as well
1972 write_lock_level = 2;
1973 } else if (ins_len > 0) {
1975 * for inserting items, make sure we have a write lock on
1976 * level 1 so we can update keys
1978 write_lock_level = 1;
1982 write_lock_level = -1;
1984 if (cow && (p->keep_locks || p->lowest_level))
1985 write_lock_level = BTRFS_MAX_LEVEL;
1987 min_write_lock_level = write_lock_level;
1989 if (p->need_commit_sem) {
1990 ASSERT(p->search_commit_root);
1992 if (!down_read_trylock(&fs_info->commit_root_sem))
1995 down_read(&fs_info->commit_root_sem);
2001 b = btrfs_search_slot_get_root(root, p, write_lock_level);
2010 level = btrfs_header_level(b);
2013 bool last_level = (level == (BTRFS_MAX_LEVEL - 1));
2016 * if we don't really need to cow this block
2017 * then we don't want to set the path blocking,
2018 * so we test it here
2020 if (!should_cow_block(trans, root, b))
2024 * must have write locks on this node and the
2027 if (level > write_lock_level ||
2028 (level + 1 > write_lock_level &&
2029 level + 1 < BTRFS_MAX_LEVEL &&
2030 p->nodes[level + 1])) {
2031 write_lock_level = level + 1;
2032 btrfs_release_path(p);
2037 err = btrfs_cow_block(trans, root, b, NULL, 0,
2041 err = btrfs_cow_block(trans, root, b,
2042 p->nodes[level + 1],
2043 p->slots[level + 1], &b,
2051 p->nodes[level] = b;
2054 * we have a lock on b and as long as we aren't changing
2055 * the tree, there is no way to for the items in b to change.
2056 * It is safe to drop the lock on our parent before we
2057 * go through the expensive btree search on b.
2059 * If we're inserting or deleting (ins_len != 0), then we might
2060 * be changing slot zero, which may require changing the parent.
2061 * So, we can't drop the lock until after we know which slot
2062 * we're operating on.
2064 if (!ins_len && !p->keep_locks) {
2067 if (u < BTRFS_MAX_LEVEL && p->locks[u]) {
2068 btrfs_tree_unlock_rw(p->nodes[u], p->locks[u]);
2075 ASSERT(write_lock_level >= 1);
2077 ret = search_leaf(trans, root, key, p, ins_len, prev_cmp);
2078 if (!p->search_for_split)
2079 unlock_up(p, level, lowest_unlock,
2080 min_write_lock_level, NULL);
2084 ret = search_for_key_slot(b, 0, key, prev_cmp, &slot);
2089 if (ret && slot > 0) {
2093 p->slots[level] = slot;
2094 err = setup_nodes_for_search(trans, root, p, b, level, ins_len,
2102 b = p->nodes[level];
2103 slot = p->slots[level];
2106 * Slot 0 is special, if we change the key we have to update
2107 * the parent pointer which means we must have a write lock on
2110 if (slot == 0 && ins_len && write_lock_level < level + 1) {
2111 write_lock_level = level + 1;
2112 btrfs_release_path(p);
2116 unlock_up(p, level, lowest_unlock, min_write_lock_level,
2119 if (level == lowest_level) {
2125 err = read_block_for_search(root, p, &b, level, slot, key);
2133 if (!p->skip_locking) {
2134 level = btrfs_header_level(b);
2136 btrfs_maybe_reset_lockdep_class(root, b);
2138 if (level <= write_lock_level) {
2140 p->locks[level] = BTRFS_WRITE_LOCK;
2143 if (!btrfs_try_tree_read_lock(b)) {
2144 free_extent_buffer(b);
2149 btrfs_tree_read_lock(b);
2151 p->locks[level] = BTRFS_READ_LOCK;
2153 p->nodes[level] = b;
2158 if (ret < 0 && !p->skip_release_on_error)
2159 btrfs_release_path(p);
2161 if (p->need_commit_sem) {
2164 ret2 = finish_need_commit_sem_search(p);
2165 up_read(&fs_info->commit_root_sem);
2172 ALLOW_ERROR_INJECTION(btrfs_search_slot, ERRNO);
2175 * Like btrfs_search_slot, this looks for a key in the given tree. It uses the
2176 * current state of the tree together with the operations recorded in the tree
2177 * modification log to search for the key in a previous version of this tree, as
2178 * denoted by the time_seq parameter.
2180 * Naturally, there is no support for insert, delete or cow operations.
2182 * The resulting path and return value will be set up as if we called
2183 * btrfs_search_slot at that point in time with ins_len and cow both set to 0.
2185 int btrfs_search_old_slot(struct btrfs_root *root, const struct btrfs_key *key,
2186 struct btrfs_path *p, u64 time_seq)
2188 struct btrfs_fs_info *fs_info = root->fs_info;
2189 struct extent_buffer *b;
2194 int lowest_unlock = 1;
2195 u8 lowest_level = 0;
2197 lowest_level = p->lowest_level;
2198 WARN_ON(p->nodes[0] != NULL);
2201 if (p->search_commit_root) {
2203 return btrfs_search_slot(NULL, root, key, p, 0, 0);
2207 b = btrfs_get_old_root(root, time_seq);
2212 level = btrfs_header_level(b);
2213 p->locks[level] = BTRFS_READ_LOCK;
2218 level = btrfs_header_level(b);
2219 p->nodes[level] = b;
2222 * we have a lock on b and as long as we aren't changing
2223 * the tree, there is no way to for the items in b to change.
2224 * It is safe to drop the lock on our parent before we
2225 * go through the expensive btree search on b.
2227 btrfs_unlock_up_safe(p, level + 1);
2229 ret = btrfs_bin_search(b, key, &slot);
2234 p->slots[level] = slot;
2235 unlock_up(p, level, lowest_unlock, 0, NULL);
2239 if (ret && slot > 0) {
2243 p->slots[level] = slot;
2244 unlock_up(p, level, lowest_unlock, 0, NULL);
2246 if (level == lowest_level) {
2252 err = read_block_for_search(root, p, &b, level, slot, key);
2260 level = btrfs_header_level(b);
2261 btrfs_tree_read_lock(b);
2262 b = btrfs_tree_mod_log_rewind(fs_info, p, b, time_seq);
2267 p->locks[level] = BTRFS_READ_LOCK;
2268 p->nodes[level] = b;
2273 btrfs_release_path(p);
2279 * helper to use instead of search slot if no exact match is needed but
2280 * instead the next or previous item should be returned.
2281 * When find_higher is true, the next higher item is returned, the next lower
2283 * When return_any and find_higher are both true, and no higher item is found,
2284 * return the next lower instead.
2285 * When return_any is true and find_higher is false, and no lower item is found,
2286 * return the next higher instead.
2287 * It returns 0 if any item is found, 1 if none is found (tree empty), and
2290 int btrfs_search_slot_for_read(struct btrfs_root *root,
2291 const struct btrfs_key *key,
2292 struct btrfs_path *p, int find_higher,
2296 struct extent_buffer *leaf;
2299 ret = btrfs_search_slot(NULL, root, key, p, 0, 0);
2303 * a return value of 1 means the path is at the position where the
2304 * item should be inserted. Normally this is the next bigger item,
2305 * but in case the previous item is the last in a leaf, path points
2306 * to the first free slot in the previous leaf, i.e. at an invalid
2312 if (p->slots[0] >= btrfs_header_nritems(leaf)) {
2313 ret = btrfs_next_leaf(root, p);
2319 * no higher item found, return the next
2324 btrfs_release_path(p);
2328 if (p->slots[0] == 0) {
2329 ret = btrfs_prev_leaf(root, p);
2334 if (p->slots[0] == btrfs_header_nritems(leaf))
2341 * no lower item found, return the next
2346 btrfs_release_path(p);
2356 * Execute search and call btrfs_previous_item to traverse backwards if the item
2359 * Return 0 if found, 1 if not found and < 0 if error.
2361 int btrfs_search_backwards(struct btrfs_root *root, struct btrfs_key *key,
2362 struct btrfs_path *path)
2366 ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
2368 ret = btrfs_previous_item(root, path, key->objectid, key->type);
2371 btrfs_item_key_to_cpu(path->nodes[0], key, path->slots[0]);
2377 * Search for a valid slot for the given path.
2379 * @root: The root node of the tree.
2380 * @key: Will contain a valid item if found.
2381 * @path: The starting point to validate the slot.
2383 * Return: 0 if the item is valid
2387 int btrfs_get_next_valid_item(struct btrfs_root *root, struct btrfs_key *key,
2388 struct btrfs_path *path)
2392 const int slot = path->slots[0];
2393 const struct extent_buffer *leaf = path->nodes[0];
2395 /* This is where we start walking the path. */
2396 if (slot >= btrfs_header_nritems(leaf)) {
2398 * If we've reached the last slot in this leaf we need
2399 * to go to the next leaf and reset the path.
2401 ret = btrfs_next_leaf(root, path);
2406 /* Store the found, valid item in @key. */
2407 btrfs_item_key_to_cpu(leaf, key, slot);
2414 * adjust the pointers going up the tree, starting at level
2415 * making sure the right key of each node is points to 'key'.
2416 * This is used after shifting pointers to the left, so it stops
2417 * fixing up pointers when a given leaf/node is not in slot 0 of the
2421 static void fixup_low_keys(struct btrfs_path *path,
2422 struct btrfs_disk_key *key, int level)
2425 struct extent_buffer *t;
2428 for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2429 int tslot = path->slots[i];
2431 if (!path->nodes[i])
2434 ret = btrfs_tree_mod_log_insert_key(t, tslot,
2435 BTRFS_MOD_LOG_KEY_REPLACE, GFP_ATOMIC);
2437 btrfs_set_node_key(t, key, tslot);
2438 btrfs_mark_buffer_dirty(path->nodes[i]);
2447 * This function isn't completely safe. It's the caller's responsibility
2448 * that the new key won't break the order
2450 void btrfs_set_item_key_safe(struct btrfs_fs_info *fs_info,
2451 struct btrfs_path *path,
2452 const struct btrfs_key *new_key)
2454 struct btrfs_disk_key disk_key;
2455 struct extent_buffer *eb;
2458 eb = path->nodes[0];
2459 slot = path->slots[0];
2461 btrfs_item_key(eb, &disk_key, slot - 1);
2462 if (unlikely(comp_keys(&disk_key, new_key) >= 0)) {
2464 "slot %u key (%llu %u %llu) new key (%llu %u %llu)",
2465 slot, btrfs_disk_key_objectid(&disk_key),
2466 btrfs_disk_key_type(&disk_key),
2467 btrfs_disk_key_offset(&disk_key),
2468 new_key->objectid, new_key->type,
2470 btrfs_print_leaf(eb);
2474 if (slot < btrfs_header_nritems(eb) - 1) {
2475 btrfs_item_key(eb, &disk_key, slot + 1);
2476 if (unlikely(comp_keys(&disk_key, new_key) <= 0)) {
2478 "slot %u key (%llu %u %llu) new key (%llu %u %llu)",
2479 slot, btrfs_disk_key_objectid(&disk_key),
2480 btrfs_disk_key_type(&disk_key),
2481 btrfs_disk_key_offset(&disk_key),
2482 new_key->objectid, new_key->type,
2484 btrfs_print_leaf(eb);
2489 btrfs_cpu_key_to_disk(&disk_key, new_key);
2490 btrfs_set_item_key(eb, &disk_key, slot);
2491 btrfs_mark_buffer_dirty(eb);
2493 fixup_low_keys(path, &disk_key, 1);
2497 * Check key order of two sibling extent buffers.
2499 * Return true if something is wrong.
2500 * Return false if everything is fine.
2502 * Tree-checker only works inside one tree block, thus the following
2503 * corruption can not be detected by tree-checker:
2505 * Leaf @left | Leaf @right
2506 * --------------------------------------------------------------
2507 * | 1 | 2 | 3 | 4 | 5 | f6 | | 7 | 8 |
2509 * Key f6 in leaf @left itself is valid, but not valid when the next
2510 * key in leaf @right is 7.
2511 * This can only be checked at tree block merge time.
2512 * And since tree checker has ensured all key order in each tree block
2513 * is correct, we only need to bother the last key of @left and the first
2516 static bool check_sibling_keys(struct extent_buffer *left,
2517 struct extent_buffer *right)
2519 struct btrfs_key left_last;
2520 struct btrfs_key right_first;
2521 int level = btrfs_header_level(left);
2522 int nr_left = btrfs_header_nritems(left);
2523 int nr_right = btrfs_header_nritems(right);
2525 /* No key to check in one of the tree blocks */
2526 if (!nr_left || !nr_right)
2530 btrfs_node_key_to_cpu(left, &left_last, nr_left - 1);
2531 btrfs_node_key_to_cpu(right, &right_first, 0);
2533 btrfs_item_key_to_cpu(left, &left_last, nr_left - 1);
2534 btrfs_item_key_to_cpu(right, &right_first, 0);
2537 if (btrfs_comp_cpu_keys(&left_last, &right_first) >= 0) {
2538 btrfs_crit(left->fs_info,
2539 "bad key order, sibling blocks, left last (%llu %u %llu) right first (%llu %u %llu)",
2540 left_last.objectid, left_last.type,
2541 left_last.offset, right_first.objectid,
2542 right_first.type, right_first.offset);
2549 * try to push data from one node into the next node left in the
2552 * returns 0 if some ptrs were pushed left, < 0 if there was some horrible
2553 * error, and > 0 if there was no room in the left hand block.
2555 static int push_node_left(struct btrfs_trans_handle *trans,
2556 struct extent_buffer *dst,
2557 struct extent_buffer *src, int empty)
2559 struct btrfs_fs_info *fs_info = trans->fs_info;
2565 src_nritems = btrfs_header_nritems(src);
2566 dst_nritems = btrfs_header_nritems(dst);
2567 push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
2568 WARN_ON(btrfs_header_generation(src) != trans->transid);
2569 WARN_ON(btrfs_header_generation(dst) != trans->transid);
2571 if (!empty && src_nritems <= 8)
2574 if (push_items <= 0)
2578 push_items = min(src_nritems, push_items);
2579 if (push_items < src_nritems) {
2580 /* leave at least 8 pointers in the node if
2581 * we aren't going to empty it
2583 if (src_nritems - push_items < 8) {
2584 if (push_items <= 8)
2590 push_items = min(src_nritems - 8, push_items);
2592 /* dst is the left eb, src is the middle eb */
2593 if (check_sibling_keys(dst, src)) {
2595 btrfs_abort_transaction(trans, ret);
2598 ret = btrfs_tree_mod_log_eb_copy(dst, src, dst_nritems, 0, push_items);
2600 btrfs_abort_transaction(trans, ret);
2603 copy_extent_buffer(dst, src,
2604 btrfs_node_key_ptr_offset(dst_nritems),
2605 btrfs_node_key_ptr_offset(0),
2606 push_items * sizeof(struct btrfs_key_ptr));
2608 if (push_items < src_nritems) {
2610 * Don't call btrfs_tree_mod_log_insert_move() here, key removal
2611 * was already fully logged by btrfs_tree_mod_log_eb_copy() above.
2613 memmove_extent_buffer(src, btrfs_node_key_ptr_offset(0),
2614 btrfs_node_key_ptr_offset(push_items),
2615 (src_nritems - push_items) *
2616 sizeof(struct btrfs_key_ptr));
2618 btrfs_set_header_nritems(src, src_nritems - push_items);
2619 btrfs_set_header_nritems(dst, dst_nritems + push_items);
2620 btrfs_mark_buffer_dirty(src);
2621 btrfs_mark_buffer_dirty(dst);
2627 * try to push data from one node into the next node right in the
2630 * returns 0 if some ptrs were pushed, < 0 if there was some horrible
2631 * error, and > 0 if there was no room in the right hand block.
2633 * this will only push up to 1/2 the contents of the left node over
2635 static int balance_node_right(struct btrfs_trans_handle *trans,
2636 struct extent_buffer *dst,
2637 struct extent_buffer *src)
2639 struct btrfs_fs_info *fs_info = trans->fs_info;
2646 WARN_ON(btrfs_header_generation(src) != trans->transid);
2647 WARN_ON(btrfs_header_generation(dst) != trans->transid);
2649 src_nritems = btrfs_header_nritems(src);
2650 dst_nritems = btrfs_header_nritems(dst);
2651 push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
2652 if (push_items <= 0)
2655 if (src_nritems < 4)
2658 max_push = src_nritems / 2 + 1;
2659 /* don't try to empty the node */
2660 if (max_push >= src_nritems)
2663 if (max_push < push_items)
2664 push_items = max_push;
2666 /* dst is the right eb, src is the middle eb */
2667 if (check_sibling_keys(src, dst)) {
2669 btrfs_abort_transaction(trans, ret);
2672 ret = btrfs_tree_mod_log_insert_move(dst, push_items, 0, dst_nritems);
2674 memmove_extent_buffer(dst, btrfs_node_key_ptr_offset(push_items),
2675 btrfs_node_key_ptr_offset(0),
2677 sizeof(struct btrfs_key_ptr));
2679 ret = btrfs_tree_mod_log_eb_copy(dst, src, 0, src_nritems - push_items,
2682 btrfs_abort_transaction(trans, ret);
2685 copy_extent_buffer(dst, src,
2686 btrfs_node_key_ptr_offset(0),
2687 btrfs_node_key_ptr_offset(src_nritems - push_items),
2688 push_items * sizeof(struct btrfs_key_ptr));
2690 btrfs_set_header_nritems(src, src_nritems - push_items);
2691 btrfs_set_header_nritems(dst, dst_nritems + push_items);
2693 btrfs_mark_buffer_dirty(src);
2694 btrfs_mark_buffer_dirty(dst);
2700 * helper function to insert a new root level in the tree.
2701 * A new node is allocated, and a single item is inserted to
2702 * point to the existing root
2704 * returns zero on success or < 0 on failure.
2706 static noinline int insert_new_root(struct btrfs_trans_handle *trans,
2707 struct btrfs_root *root,
2708 struct btrfs_path *path, int level)
2710 struct btrfs_fs_info *fs_info = root->fs_info;
2712 struct extent_buffer *lower;
2713 struct extent_buffer *c;
2714 struct extent_buffer *old;
2715 struct btrfs_disk_key lower_key;
2718 BUG_ON(path->nodes[level]);
2719 BUG_ON(path->nodes[level-1] != root->node);
2721 lower = path->nodes[level-1];
2723 btrfs_item_key(lower, &lower_key, 0);
2725 btrfs_node_key(lower, &lower_key, 0);
2727 c = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
2728 &lower_key, level, root->node->start, 0,
2729 BTRFS_NESTING_NEW_ROOT);
2733 root_add_used(root, fs_info->nodesize);
2735 btrfs_set_header_nritems(c, 1);
2736 btrfs_set_node_key(c, &lower_key, 0);
2737 btrfs_set_node_blockptr(c, 0, lower->start);
2738 lower_gen = btrfs_header_generation(lower);
2739 WARN_ON(lower_gen != trans->transid);
2741 btrfs_set_node_ptr_generation(c, 0, lower_gen);
2743 btrfs_mark_buffer_dirty(c);
2746 ret = btrfs_tree_mod_log_insert_root(root->node, c, false);
2748 rcu_assign_pointer(root->node, c);
2750 /* the super has an extra ref to root->node */
2751 free_extent_buffer(old);
2753 add_root_to_dirty_list(root);
2754 atomic_inc(&c->refs);
2755 path->nodes[level] = c;
2756 path->locks[level] = BTRFS_WRITE_LOCK;
2757 path->slots[level] = 0;
2762 * worker function to insert a single pointer in a node.
2763 * the node should have enough room for the pointer already
2765 * slot and level indicate where you want the key to go, and
2766 * blocknr is the block the key points to.
2768 static void insert_ptr(struct btrfs_trans_handle *trans,
2769 struct btrfs_path *path,
2770 struct btrfs_disk_key *key, u64 bytenr,
2771 int slot, int level)
2773 struct extent_buffer *lower;
2777 BUG_ON(!path->nodes[level]);
2778 btrfs_assert_tree_write_locked(path->nodes[level]);
2779 lower = path->nodes[level];
2780 nritems = btrfs_header_nritems(lower);
2781 BUG_ON(slot > nritems);
2782 BUG_ON(nritems == BTRFS_NODEPTRS_PER_BLOCK(trans->fs_info));
2783 if (slot != nritems) {
2785 ret = btrfs_tree_mod_log_insert_move(lower, slot + 1,
2786 slot, nritems - slot);
2789 memmove_extent_buffer(lower,
2790 btrfs_node_key_ptr_offset(slot + 1),
2791 btrfs_node_key_ptr_offset(slot),
2792 (nritems - slot) * sizeof(struct btrfs_key_ptr));
2795 ret = btrfs_tree_mod_log_insert_key(lower, slot,
2796 BTRFS_MOD_LOG_KEY_ADD, GFP_NOFS);
2799 btrfs_set_node_key(lower, key, slot);
2800 btrfs_set_node_blockptr(lower, slot, bytenr);
2801 WARN_ON(trans->transid == 0);
2802 btrfs_set_node_ptr_generation(lower, slot, trans->transid);
2803 btrfs_set_header_nritems(lower, nritems + 1);
2804 btrfs_mark_buffer_dirty(lower);
2808 * split the node at the specified level in path in two.
2809 * The path is corrected to point to the appropriate node after the split
2811 * Before splitting this tries to make some room in the node by pushing
2812 * left and right, if either one works, it returns right away.
2814 * returns 0 on success and < 0 on failure
2816 static noinline int split_node(struct btrfs_trans_handle *trans,
2817 struct btrfs_root *root,
2818 struct btrfs_path *path, int level)
2820 struct btrfs_fs_info *fs_info = root->fs_info;
2821 struct extent_buffer *c;
2822 struct extent_buffer *split;
2823 struct btrfs_disk_key disk_key;
2828 c = path->nodes[level];
2829 WARN_ON(btrfs_header_generation(c) != trans->transid);
2830 if (c == root->node) {
2832 * trying to split the root, lets make a new one
2834 * tree mod log: We don't log_removal old root in
2835 * insert_new_root, because that root buffer will be kept as a
2836 * normal node. We are going to log removal of half of the
2837 * elements below with btrfs_tree_mod_log_eb_copy(). We're
2838 * holding a tree lock on the buffer, which is why we cannot
2839 * race with other tree_mod_log users.
2841 ret = insert_new_root(trans, root, path, level + 1);
2845 ret = push_nodes_for_insert(trans, root, path, level);
2846 c = path->nodes[level];
2847 if (!ret && btrfs_header_nritems(c) <
2848 BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3)
2854 c_nritems = btrfs_header_nritems(c);
2855 mid = (c_nritems + 1) / 2;
2856 btrfs_node_key(c, &disk_key, mid);
2858 split = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
2859 &disk_key, level, c->start, 0,
2860 BTRFS_NESTING_SPLIT);
2862 return PTR_ERR(split);
2864 root_add_used(root, fs_info->nodesize);
2865 ASSERT(btrfs_header_level(c) == level);
2867 ret = btrfs_tree_mod_log_eb_copy(split, c, 0, mid, c_nritems - mid);
2869 btrfs_tree_unlock(split);
2870 free_extent_buffer(split);
2871 btrfs_abort_transaction(trans, ret);
2874 copy_extent_buffer(split, c,
2875 btrfs_node_key_ptr_offset(0),
2876 btrfs_node_key_ptr_offset(mid),
2877 (c_nritems - mid) * sizeof(struct btrfs_key_ptr));
2878 btrfs_set_header_nritems(split, c_nritems - mid);
2879 btrfs_set_header_nritems(c, mid);
2881 btrfs_mark_buffer_dirty(c);
2882 btrfs_mark_buffer_dirty(split);
2884 insert_ptr(trans, path, &disk_key, split->start,
2885 path->slots[level + 1] + 1, level + 1);
2887 if (path->slots[level] >= mid) {
2888 path->slots[level] -= mid;
2889 btrfs_tree_unlock(c);
2890 free_extent_buffer(c);
2891 path->nodes[level] = split;
2892 path->slots[level + 1] += 1;
2894 btrfs_tree_unlock(split);
2895 free_extent_buffer(split);
2901 * how many bytes are required to store the items in a leaf. start
2902 * and nr indicate which items in the leaf to check. This totals up the
2903 * space used both by the item structs and the item data
2905 static int leaf_space_used(struct extent_buffer *l, int start, int nr)
2908 int nritems = btrfs_header_nritems(l);
2909 int end = min(nritems, start + nr) - 1;
2913 data_len = btrfs_item_offset(l, start) + btrfs_item_size(l, start);
2914 data_len = data_len - btrfs_item_offset(l, end);
2915 data_len += sizeof(struct btrfs_item) * nr;
2916 WARN_ON(data_len < 0);
2921 * The space between the end of the leaf items and
2922 * the start of the leaf data. IOW, how much room
2923 * the leaf has left for both items and data
2925 noinline int btrfs_leaf_free_space(struct extent_buffer *leaf)
2927 struct btrfs_fs_info *fs_info = leaf->fs_info;
2928 int nritems = btrfs_header_nritems(leaf);
2931 ret = BTRFS_LEAF_DATA_SIZE(fs_info) - leaf_space_used(leaf, 0, nritems);
2934 "leaf free space ret %d, leaf data size %lu, used %d nritems %d",
2936 (unsigned long) BTRFS_LEAF_DATA_SIZE(fs_info),
2937 leaf_space_used(leaf, 0, nritems), nritems);
2943 * min slot controls the lowest index we're willing to push to the
2944 * right. We'll push up to and including min_slot, but no lower
2946 static noinline int __push_leaf_right(struct btrfs_path *path,
2947 int data_size, int empty,
2948 struct extent_buffer *right,
2949 int free_space, u32 left_nritems,
2952 struct btrfs_fs_info *fs_info = right->fs_info;
2953 struct extent_buffer *left = path->nodes[0];
2954 struct extent_buffer *upper = path->nodes[1];
2955 struct btrfs_map_token token;
2956 struct btrfs_disk_key disk_key;
2969 nr = max_t(u32, 1, min_slot);
2971 if (path->slots[0] >= left_nritems)
2972 push_space += data_size;
2974 slot = path->slots[1];
2975 i = left_nritems - 1;
2977 if (!empty && push_items > 0) {
2978 if (path->slots[0] > i)
2980 if (path->slots[0] == i) {
2981 int space = btrfs_leaf_free_space(left);
2983 if (space + push_space * 2 > free_space)
2988 if (path->slots[0] == i)
2989 push_space += data_size;
2991 this_item_size = btrfs_item_size(left, i);
2992 if (this_item_size + sizeof(struct btrfs_item) +
2993 push_space > free_space)
2997 push_space += this_item_size + sizeof(struct btrfs_item);
3003 if (push_items == 0)
3006 WARN_ON(!empty && push_items == left_nritems);
3008 /* push left to right */
3009 right_nritems = btrfs_header_nritems(right);
3011 push_space = btrfs_item_data_end(left, left_nritems - push_items);
3012 push_space -= leaf_data_end(left);
3014 /* make room in the right data area */
3015 data_end = leaf_data_end(right);
3016 memmove_extent_buffer(right,
3017 BTRFS_LEAF_DATA_OFFSET + data_end - push_space,
3018 BTRFS_LEAF_DATA_OFFSET + data_end,
3019 BTRFS_LEAF_DATA_SIZE(fs_info) - data_end);
3021 /* copy from the left data area */
3022 copy_extent_buffer(right, left, BTRFS_LEAF_DATA_OFFSET +
3023 BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
3024 BTRFS_LEAF_DATA_OFFSET + leaf_data_end(left),
3027 memmove_extent_buffer(right, btrfs_item_nr_offset(push_items),
3028 btrfs_item_nr_offset(0),
3029 right_nritems * sizeof(struct btrfs_item));
3031 /* copy the items from left to right */
3032 copy_extent_buffer(right, left, btrfs_item_nr_offset(0),
3033 btrfs_item_nr_offset(left_nritems - push_items),
3034 push_items * sizeof(struct btrfs_item));
3036 /* update the item pointers */
3037 btrfs_init_map_token(&token, right);
3038 right_nritems += push_items;
3039 btrfs_set_header_nritems(right, right_nritems);
3040 push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
3041 for (i = 0; i < right_nritems; i++) {
3042 push_space -= btrfs_token_item_size(&token, i);
3043 btrfs_set_token_item_offset(&token, i, push_space);
3046 left_nritems -= push_items;
3047 btrfs_set_header_nritems(left, left_nritems);
3050 btrfs_mark_buffer_dirty(left);
3052 btrfs_clean_tree_block(left);
3054 btrfs_mark_buffer_dirty(right);
3056 btrfs_item_key(right, &disk_key, 0);
3057 btrfs_set_node_key(upper, &disk_key, slot + 1);
3058 btrfs_mark_buffer_dirty(upper);
3060 /* then fixup the leaf pointer in the path */
3061 if (path->slots[0] >= left_nritems) {
3062 path->slots[0] -= left_nritems;
3063 if (btrfs_header_nritems(path->nodes[0]) == 0)
3064 btrfs_clean_tree_block(path->nodes[0]);
3065 btrfs_tree_unlock(path->nodes[0]);
3066 free_extent_buffer(path->nodes[0]);
3067 path->nodes[0] = right;
3068 path->slots[1] += 1;
3070 btrfs_tree_unlock(right);
3071 free_extent_buffer(right);
3076 btrfs_tree_unlock(right);
3077 free_extent_buffer(right);
3082 * push some data in the path leaf to the right, trying to free up at
3083 * least data_size bytes. returns zero if the push worked, nonzero otherwise
3085 * returns 1 if the push failed because the other node didn't have enough
3086 * room, 0 if everything worked out and < 0 if there were major errors.
3088 * this will push starting from min_slot to the end of the leaf. It won't
3089 * push any slot lower than min_slot
3091 static int push_leaf_right(struct btrfs_trans_handle *trans, struct btrfs_root
3092 *root, struct btrfs_path *path,
3093 int min_data_size, int data_size,
3094 int empty, u32 min_slot)
3096 struct extent_buffer *left = path->nodes[0];
3097 struct extent_buffer *right;
3098 struct extent_buffer *upper;
3104 if (!path->nodes[1])
3107 slot = path->slots[1];
3108 upper = path->nodes[1];
3109 if (slot >= btrfs_header_nritems(upper) - 1)
3112 btrfs_assert_tree_write_locked(path->nodes[1]);
3114 right = btrfs_read_node_slot(upper, slot + 1);
3116 * slot + 1 is not valid or we fail to read the right node,
3117 * no big deal, just return.
3122 __btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
3124 free_space = btrfs_leaf_free_space(right);
3125 if (free_space < data_size)
3128 ret = btrfs_cow_block(trans, root, right, upper,
3129 slot + 1, &right, BTRFS_NESTING_RIGHT_COW);
3133 left_nritems = btrfs_header_nritems(left);
3134 if (left_nritems == 0)
3137 if (check_sibling_keys(left, right)) {
3139 btrfs_abort_transaction(trans, ret);
3140 btrfs_tree_unlock(right);
3141 free_extent_buffer(right);
3144 if (path->slots[0] == left_nritems && !empty) {
3145 /* Key greater than all keys in the leaf, right neighbor has
3146 * enough room for it and we're not emptying our leaf to delete
3147 * it, therefore use right neighbor to insert the new item and
3148 * no need to touch/dirty our left leaf. */
3149 btrfs_tree_unlock(left);
3150 free_extent_buffer(left);
3151 path->nodes[0] = right;
3157 return __push_leaf_right(path, min_data_size, empty,
3158 right, free_space, left_nritems, min_slot);
3160 btrfs_tree_unlock(right);
3161 free_extent_buffer(right);
3166 * push some data in the path leaf to the left, trying to free up at
3167 * least data_size bytes. returns zero if the push worked, nonzero otherwise
3169 * max_slot can put a limit on how far into the leaf we'll push items. The
3170 * item at 'max_slot' won't be touched. Use (u32)-1 to make us do all the
3173 static noinline int __push_leaf_left(struct btrfs_path *path, int data_size,
3174 int empty, struct extent_buffer *left,
3175 int free_space, u32 right_nritems,
3178 struct btrfs_fs_info *fs_info = left->fs_info;
3179 struct btrfs_disk_key disk_key;
3180 struct extent_buffer *right = path->nodes[0];
3184 u32 old_left_nritems;
3188 u32 old_left_item_size;
3189 struct btrfs_map_token token;
3192 nr = min(right_nritems, max_slot);
3194 nr = min(right_nritems - 1, max_slot);
3196 for (i = 0; i < nr; i++) {
3197 if (!empty && push_items > 0) {
3198 if (path->slots[0] < i)
3200 if (path->slots[0] == i) {
3201 int space = btrfs_leaf_free_space(right);
3203 if (space + push_space * 2 > free_space)
3208 if (path->slots[0] == i)
3209 push_space += data_size;
3211 this_item_size = btrfs_item_size(right, i);
3212 if (this_item_size + sizeof(struct btrfs_item) + push_space >
3217 push_space += this_item_size + sizeof(struct btrfs_item);
3220 if (push_items == 0) {
3224 WARN_ON(!empty && push_items == btrfs_header_nritems(right));
3226 /* push data from right to left */
3227 copy_extent_buffer(left, right,
3228 btrfs_item_nr_offset(btrfs_header_nritems(left)),
3229 btrfs_item_nr_offset(0),
3230 push_items * sizeof(struct btrfs_item));
3232 push_space = BTRFS_LEAF_DATA_SIZE(fs_info) -
3233 btrfs_item_offset(right, push_items - 1);
3235 copy_extent_buffer(left, right, BTRFS_LEAF_DATA_OFFSET +
3236 leaf_data_end(left) - push_space,
3237 BTRFS_LEAF_DATA_OFFSET +
3238 btrfs_item_offset(right, push_items - 1),
3240 old_left_nritems = btrfs_header_nritems(left);
3241 BUG_ON(old_left_nritems <= 0);
3243 btrfs_init_map_token(&token, left);
3244 old_left_item_size = btrfs_item_offset(left, old_left_nritems - 1);
3245 for (i = old_left_nritems; i < old_left_nritems + push_items; i++) {
3248 ioff = btrfs_token_item_offset(&token, i);
3249 btrfs_set_token_item_offset(&token, i,
3250 ioff - (BTRFS_LEAF_DATA_SIZE(fs_info) - old_left_item_size));
3252 btrfs_set_header_nritems(left, old_left_nritems + push_items);
3254 /* fixup right node */
3255 if (push_items > right_nritems)
3256 WARN(1, KERN_CRIT "push items %d nr %u\n", push_items,
3259 if (push_items < right_nritems) {
3260 push_space = btrfs_item_offset(right, push_items - 1) -
3261 leaf_data_end(right);
3262 memmove_extent_buffer(right, BTRFS_LEAF_DATA_OFFSET +
3263 BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
3264 BTRFS_LEAF_DATA_OFFSET +
3265 leaf_data_end(right), push_space);
3267 memmove_extent_buffer(right, btrfs_item_nr_offset(0),
3268 btrfs_item_nr_offset(push_items),
3269 (btrfs_header_nritems(right) - push_items) *
3270 sizeof(struct btrfs_item));
3273 btrfs_init_map_token(&token, right);
3274 right_nritems -= push_items;
3275 btrfs_set_header_nritems(right, right_nritems);
3276 push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
3277 for (i = 0; i < right_nritems; i++) {
3278 push_space = push_space - btrfs_token_item_size(&token, i);
3279 btrfs_set_token_item_offset(&token, i, push_space);
3282 btrfs_mark_buffer_dirty(left);
3284 btrfs_mark_buffer_dirty(right);
3286 btrfs_clean_tree_block(right);
3288 btrfs_item_key(right, &disk_key, 0);
3289 fixup_low_keys(path, &disk_key, 1);
3291 /* then fixup the leaf pointer in the path */
3292 if (path->slots[0] < push_items) {
3293 path->slots[0] += old_left_nritems;
3294 btrfs_tree_unlock(path->nodes[0]);
3295 free_extent_buffer(path->nodes[0]);
3296 path->nodes[0] = left;
3297 path->slots[1] -= 1;
3299 btrfs_tree_unlock(left);
3300 free_extent_buffer(left);
3301 path->slots[0] -= push_items;
3303 BUG_ON(path->slots[0] < 0);
3306 btrfs_tree_unlock(left);
3307 free_extent_buffer(left);
3312 * push some data in the path leaf to the left, trying to free up at
3313 * least data_size bytes. returns zero if the push worked, nonzero otherwise
3315 * max_slot can put a limit on how far into the leaf we'll push items. The
3316 * item at 'max_slot' won't be touched. Use (u32)-1 to make us push all the
3319 static int push_leaf_left(struct btrfs_trans_handle *trans, struct btrfs_root
3320 *root, struct btrfs_path *path, int min_data_size,
3321 int data_size, int empty, u32 max_slot)
3323 struct extent_buffer *right = path->nodes[0];
3324 struct extent_buffer *left;
3330 slot = path->slots[1];
3333 if (!path->nodes[1])
3336 right_nritems = btrfs_header_nritems(right);
3337 if (right_nritems == 0)
3340 btrfs_assert_tree_write_locked(path->nodes[1]);
3342 left = btrfs_read_node_slot(path->nodes[1], slot - 1);
3344 * slot - 1 is not valid or we fail to read the left node,
3345 * no big deal, just return.
3350 __btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
3352 free_space = btrfs_leaf_free_space(left);
3353 if (free_space < data_size) {
3358 ret = btrfs_cow_block(trans, root, left,
3359 path->nodes[1], slot - 1, &left,
3360 BTRFS_NESTING_LEFT_COW);
3362 /* we hit -ENOSPC, but it isn't fatal here */
3368 if (check_sibling_keys(left, right)) {
3370 btrfs_abort_transaction(trans, ret);
3373 return __push_leaf_left(path, min_data_size,
3374 empty, left, free_space, right_nritems,
3377 btrfs_tree_unlock(left);
3378 free_extent_buffer(left);
3383 * split the path's leaf in two, making sure there is at least data_size
3384 * available for the resulting leaf level of the path.
3386 static noinline void copy_for_split(struct btrfs_trans_handle *trans,
3387 struct btrfs_path *path,
3388 struct extent_buffer *l,
3389 struct extent_buffer *right,
3390 int slot, int mid, int nritems)
3392 struct btrfs_fs_info *fs_info = trans->fs_info;
3396 struct btrfs_disk_key disk_key;
3397 struct btrfs_map_token token;
3399 nritems = nritems - mid;
3400 btrfs_set_header_nritems(right, nritems);
3401 data_copy_size = btrfs_item_data_end(l, mid) - leaf_data_end(l);
3403 copy_extent_buffer(right, l, btrfs_item_nr_offset(0),
3404 btrfs_item_nr_offset(mid),
3405 nritems * sizeof(struct btrfs_item));
3407 copy_extent_buffer(right, l,
3408 BTRFS_LEAF_DATA_OFFSET + BTRFS_LEAF_DATA_SIZE(fs_info) -
3409 data_copy_size, BTRFS_LEAF_DATA_OFFSET +
3410 leaf_data_end(l), data_copy_size);
3412 rt_data_off = BTRFS_LEAF_DATA_SIZE(fs_info) - btrfs_item_data_end(l, mid);
3414 btrfs_init_map_token(&token, right);
3415 for (i = 0; i < nritems; i++) {
3418 ioff = btrfs_token_item_offset(&token, i);
3419 btrfs_set_token_item_offset(&token, i, ioff + rt_data_off);
3422 btrfs_set_header_nritems(l, mid);
3423 btrfs_item_key(right, &disk_key, 0);
3424 insert_ptr(trans, path, &disk_key, right->start, path->slots[1] + 1, 1);
3426 btrfs_mark_buffer_dirty(right);
3427 btrfs_mark_buffer_dirty(l);
3428 BUG_ON(path->slots[0] != slot);
3431 btrfs_tree_unlock(path->nodes[0]);
3432 free_extent_buffer(path->nodes[0]);
3433 path->nodes[0] = right;
3434 path->slots[0] -= mid;
3435 path->slots[1] += 1;
3437 btrfs_tree_unlock(right);
3438 free_extent_buffer(right);
3441 BUG_ON(path->slots[0] < 0);
3445 * double splits happen when we need to insert a big item in the middle
3446 * of a leaf. A double split can leave us with 3 mostly empty leaves:
3447 * leaf: [ slots 0 - N] [ our target ] [ N + 1 - total in leaf ]
3450 * We avoid this by trying to push the items on either side of our target
3451 * into the adjacent leaves. If all goes well we can avoid the double split
3454 static noinline int push_for_double_split(struct btrfs_trans_handle *trans,
3455 struct btrfs_root *root,
3456 struct btrfs_path *path,
3463 int space_needed = data_size;
3465 slot = path->slots[0];
3466 if (slot < btrfs_header_nritems(path->nodes[0]))
3467 space_needed -= btrfs_leaf_free_space(path->nodes[0]);
3470 * try to push all the items after our slot into the
3473 ret = push_leaf_right(trans, root, path, 1, space_needed, 0, slot);
3480 nritems = btrfs_header_nritems(path->nodes[0]);
3482 * our goal is to get our slot at the start or end of a leaf. If
3483 * we've done so we're done
3485 if (path->slots[0] == 0 || path->slots[0] == nritems)
3488 if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
3491 /* try to push all the items before our slot into the next leaf */
3492 slot = path->slots[0];
3493 space_needed = data_size;
3495 space_needed -= btrfs_leaf_free_space(path->nodes[0]);
3496 ret = push_leaf_left(trans, root, path, 1, space_needed, 0, slot);
3509 * split the path's leaf in two, making sure there is at least data_size
3510 * available for the resulting leaf level of the path.
3512 * returns 0 if all went well and < 0 on failure.
3514 static noinline int split_leaf(struct btrfs_trans_handle *trans,
3515 struct btrfs_root *root,
3516 const struct btrfs_key *ins_key,
3517 struct btrfs_path *path, int data_size,
3520 struct btrfs_disk_key disk_key;
3521 struct extent_buffer *l;
3525 struct extent_buffer *right;
3526 struct btrfs_fs_info *fs_info = root->fs_info;
3530 int num_doubles = 0;
3531 int tried_avoid_double = 0;
3534 slot = path->slots[0];
3535 if (extend && data_size + btrfs_item_size(l, slot) +
3536 sizeof(struct btrfs_item) > BTRFS_LEAF_DATA_SIZE(fs_info))
3539 /* first try to make some room by pushing left and right */
3540 if (data_size && path->nodes[1]) {
3541 int space_needed = data_size;
3543 if (slot < btrfs_header_nritems(l))
3544 space_needed -= btrfs_leaf_free_space(l);
3546 wret = push_leaf_right(trans, root, path, space_needed,
3547 space_needed, 0, 0);
3551 space_needed = data_size;
3553 space_needed -= btrfs_leaf_free_space(l);
3554 wret = push_leaf_left(trans, root, path, space_needed,
3555 space_needed, 0, (u32)-1);
3561 /* did the pushes work? */
3562 if (btrfs_leaf_free_space(l) >= data_size)
3566 if (!path->nodes[1]) {
3567 ret = insert_new_root(trans, root, path, 1);
3574 slot = path->slots[0];
3575 nritems = btrfs_header_nritems(l);
3576 mid = (nritems + 1) / 2;
3580 leaf_space_used(l, mid, nritems - mid) + data_size >
3581 BTRFS_LEAF_DATA_SIZE(fs_info)) {
3582 if (slot >= nritems) {
3586 if (mid != nritems &&
3587 leaf_space_used(l, mid, nritems - mid) +
3588 data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
3589 if (data_size && !tried_avoid_double)
3590 goto push_for_double;
3596 if (leaf_space_used(l, 0, mid) + data_size >
3597 BTRFS_LEAF_DATA_SIZE(fs_info)) {
3598 if (!extend && data_size && slot == 0) {
3600 } else if ((extend || !data_size) && slot == 0) {
3604 if (mid != nritems &&
3605 leaf_space_used(l, mid, nritems - mid) +
3606 data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
3607 if (data_size && !tried_avoid_double)
3608 goto push_for_double;
3616 btrfs_cpu_key_to_disk(&disk_key, ins_key);
3618 btrfs_item_key(l, &disk_key, mid);
3621 * We have to about BTRFS_NESTING_NEW_ROOT here if we've done a double
3622 * split, because we're only allowed to have MAX_LOCKDEP_SUBCLASSES
3623 * subclasses, which is 8 at the time of this patch, and we've maxed it
3624 * out. In the future we could add a
3625 * BTRFS_NESTING_SPLIT_THE_SPLITTENING if we need to, but for now just
3626 * use BTRFS_NESTING_NEW_ROOT.
3628 right = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
3629 &disk_key, 0, l->start, 0,
3630 num_doubles ? BTRFS_NESTING_NEW_ROOT :
3631 BTRFS_NESTING_SPLIT);
3633 return PTR_ERR(right);
3635 root_add_used(root, fs_info->nodesize);
3639 btrfs_set_header_nritems(right, 0);
3640 insert_ptr(trans, path, &disk_key,
3641 right->start, path->slots[1] + 1, 1);
3642 btrfs_tree_unlock(path->nodes[0]);
3643 free_extent_buffer(path->nodes[0]);
3644 path->nodes[0] = right;
3646 path->slots[1] += 1;
3648 btrfs_set_header_nritems(right, 0);
3649 insert_ptr(trans, path, &disk_key,
3650 right->start, path->slots[1], 1);
3651 btrfs_tree_unlock(path->nodes[0]);
3652 free_extent_buffer(path->nodes[0]);
3653 path->nodes[0] = right;
3655 if (path->slots[1] == 0)
3656 fixup_low_keys(path, &disk_key, 1);
3659 * We create a new leaf 'right' for the required ins_len and
3660 * we'll do btrfs_mark_buffer_dirty() on this leaf after copying
3661 * the content of ins_len to 'right'.
3666 copy_for_split(trans, path, l, right, slot, mid, nritems);
3669 BUG_ON(num_doubles != 0);
3677 push_for_double_split(trans, root, path, data_size);
3678 tried_avoid_double = 1;
3679 if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
3684 static noinline int setup_leaf_for_split(struct btrfs_trans_handle *trans,
3685 struct btrfs_root *root,
3686 struct btrfs_path *path, int ins_len)
3688 struct btrfs_key key;
3689 struct extent_buffer *leaf;
3690 struct btrfs_file_extent_item *fi;
3695 leaf = path->nodes[0];
3696 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3698 BUG_ON(key.type != BTRFS_EXTENT_DATA_KEY &&
3699 key.type != BTRFS_EXTENT_CSUM_KEY);
3701 if (btrfs_leaf_free_space(leaf) >= ins_len)
3704 item_size = btrfs_item_size(leaf, path->slots[0]);
3705 if (key.type == BTRFS_EXTENT_DATA_KEY) {
3706 fi = btrfs_item_ptr(leaf, path->slots[0],
3707 struct btrfs_file_extent_item);
3708 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
3710 btrfs_release_path(path);
3712 path->keep_locks = 1;
3713 path->search_for_split = 1;
3714 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
3715 path->search_for_split = 0;
3722 leaf = path->nodes[0];
3723 /* if our item isn't there, return now */
3724 if (item_size != btrfs_item_size(leaf, path->slots[0]))
3727 /* the leaf has changed, it now has room. return now */
3728 if (btrfs_leaf_free_space(path->nodes[0]) >= ins_len)
3731 if (key.type == BTRFS_EXTENT_DATA_KEY) {
3732 fi = btrfs_item_ptr(leaf, path->slots[0],
3733 struct btrfs_file_extent_item);
3734 if (extent_len != btrfs_file_extent_num_bytes(leaf, fi))
3738 ret = split_leaf(trans, root, &key, path, ins_len, 1);
3742 path->keep_locks = 0;
3743 btrfs_unlock_up_safe(path, 1);
3746 path->keep_locks = 0;
3750 static noinline int split_item(struct btrfs_path *path,
3751 const struct btrfs_key *new_key,
3752 unsigned long split_offset)
3754 struct extent_buffer *leaf;
3755 int orig_slot, slot;
3760 struct btrfs_disk_key disk_key;
3762 leaf = path->nodes[0];
3763 BUG_ON(btrfs_leaf_free_space(leaf) < sizeof(struct btrfs_item));
3765 orig_slot = path->slots[0];
3766 orig_offset = btrfs_item_offset(leaf, path->slots[0]);
3767 item_size = btrfs_item_size(leaf, path->slots[0]);
3769 buf = kmalloc(item_size, GFP_NOFS);
3773 read_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf,
3774 path->slots[0]), item_size);
3776 slot = path->slots[0] + 1;
3777 nritems = btrfs_header_nritems(leaf);
3778 if (slot != nritems) {
3779 /* shift the items */
3780 memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + 1),
3781 btrfs_item_nr_offset(slot),
3782 (nritems - slot) * sizeof(struct btrfs_item));
3785 btrfs_cpu_key_to_disk(&disk_key, new_key);
3786 btrfs_set_item_key(leaf, &disk_key, slot);
3788 btrfs_set_item_offset(leaf, slot, orig_offset);
3789 btrfs_set_item_size(leaf, slot, item_size - split_offset);
3791 btrfs_set_item_offset(leaf, orig_slot,
3792 orig_offset + item_size - split_offset);
3793 btrfs_set_item_size(leaf, orig_slot, split_offset);
3795 btrfs_set_header_nritems(leaf, nritems + 1);
3797 /* write the data for the start of the original item */
3798 write_extent_buffer(leaf, buf,
3799 btrfs_item_ptr_offset(leaf, path->slots[0]),
3802 /* write the data for the new item */
3803 write_extent_buffer(leaf, buf + split_offset,
3804 btrfs_item_ptr_offset(leaf, slot),
3805 item_size - split_offset);
3806 btrfs_mark_buffer_dirty(leaf);
3808 BUG_ON(btrfs_leaf_free_space(leaf) < 0);
3814 * This function splits a single item into two items,
3815 * giving 'new_key' to the new item and splitting the
3816 * old one at split_offset (from the start of the item).
3818 * The path may be released by this operation. After
3819 * the split, the path is pointing to the old item. The
3820 * new item is going to be in the same node as the old one.
3822 * Note, the item being split must be smaller enough to live alone on
3823 * a tree block with room for one extra struct btrfs_item
3825 * This allows us to split the item in place, keeping a lock on the
3826 * leaf the entire time.
3828 int btrfs_split_item(struct btrfs_trans_handle *trans,
3829 struct btrfs_root *root,
3830 struct btrfs_path *path,
3831 const struct btrfs_key *new_key,
3832 unsigned long split_offset)
3835 ret = setup_leaf_for_split(trans, root, path,
3836 sizeof(struct btrfs_item));
3840 ret = split_item(path, new_key, split_offset);
3845 * make the item pointed to by the path smaller. new_size indicates
3846 * how small to make it, and from_end tells us if we just chop bytes
3847 * off the end of the item or if we shift the item to chop bytes off
3850 void btrfs_truncate_item(struct btrfs_path *path, u32 new_size, int from_end)
3853 struct extent_buffer *leaf;
3855 unsigned int data_end;
3856 unsigned int old_data_start;
3857 unsigned int old_size;
3858 unsigned int size_diff;
3860 struct btrfs_map_token token;
3862 leaf = path->nodes[0];
3863 slot = path->slots[0];
3865 old_size = btrfs_item_size(leaf, slot);
3866 if (old_size == new_size)
3869 nritems = btrfs_header_nritems(leaf);
3870 data_end = leaf_data_end(leaf);
3872 old_data_start = btrfs_item_offset(leaf, slot);
3874 size_diff = old_size - new_size;
3877 BUG_ON(slot >= nritems);
3880 * item0..itemN ... dataN.offset..dataN.size .. data0.size
3882 /* first correct the data pointers */
3883 btrfs_init_map_token(&token, leaf);
3884 for (i = slot; i < nritems; i++) {
3887 ioff = btrfs_token_item_offset(&token, i);
3888 btrfs_set_token_item_offset(&token, i, ioff + size_diff);
3891 /* shift the data */
3893 memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
3894 data_end + size_diff, BTRFS_LEAF_DATA_OFFSET +
3895 data_end, old_data_start + new_size - data_end);
3897 struct btrfs_disk_key disk_key;
3900 btrfs_item_key(leaf, &disk_key, slot);
3902 if (btrfs_disk_key_type(&disk_key) == BTRFS_EXTENT_DATA_KEY) {
3904 struct btrfs_file_extent_item *fi;
3906 fi = btrfs_item_ptr(leaf, slot,
3907 struct btrfs_file_extent_item);
3908 fi = (struct btrfs_file_extent_item *)(
3909 (unsigned long)fi - size_diff);
3911 if (btrfs_file_extent_type(leaf, fi) ==
3912 BTRFS_FILE_EXTENT_INLINE) {
3913 ptr = btrfs_item_ptr_offset(leaf, slot);
3914 memmove_extent_buffer(leaf, ptr,
3916 BTRFS_FILE_EXTENT_INLINE_DATA_START);
3920 memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
3921 data_end + size_diff, BTRFS_LEAF_DATA_OFFSET +
3922 data_end, old_data_start - data_end);
3924 offset = btrfs_disk_key_offset(&disk_key);
3925 btrfs_set_disk_key_offset(&disk_key, offset + size_diff);
3926 btrfs_set_item_key(leaf, &disk_key, slot);
3928 fixup_low_keys(path, &disk_key, 1);
3931 btrfs_set_item_size(leaf, slot, new_size);
3932 btrfs_mark_buffer_dirty(leaf);
3934 if (btrfs_leaf_free_space(leaf) < 0) {
3935 btrfs_print_leaf(leaf);
3941 * make the item pointed to by the path bigger, data_size is the added size.
3943 void btrfs_extend_item(struct btrfs_path *path, u32 data_size)
3946 struct extent_buffer *leaf;
3948 unsigned int data_end;
3949 unsigned int old_data;
3950 unsigned int old_size;
3952 struct btrfs_map_token token;
3954 leaf = path->nodes[0];
3956 nritems = btrfs_header_nritems(leaf);
3957 data_end = leaf_data_end(leaf);
3959 if (btrfs_leaf_free_space(leaf) < data_size) {
3960 btrfs_print_leaf(leaf);
3963 slot = path->slots[0];
3964 old_data = btrfs_item_data_end(leaf, slot);
3967 if (slot >= nritems) {
3968 btrfs_print_leaf(leaf);
3969 btrfs_crit(leaf->fs_info, "slot %d too large, nritems %d",
3975 * item0..itemN ... dataN.offset..dataN.size .. data0.size
3977 /* first correct the data pointers */
3978 btrfs_init_map_token(&token, leaf);
3979 for (i = slot; i < nritems; i++) {
3982 ioff = btrfs_token_item_offset(&token, i);
3983 btrfs_set_token_item_offset(&token, i, ioff - data_size);
3986 /* shift the data */
3987 memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
3988 data_end - data_size, BTRFS_LEAF_DATA_OFFSET +
3989 data_end, old_data - data_end);
3991 data_end = old_data;
3992 old_size = btrfs_item_size(leaf, slot);
3993 btrfs_set_item_size(leaf, slot, old_size + data_size);
3994 btrfs_mark_buffer_dirty(leaf);
3996 if (btrfs_leaf_free_space(leaf) < 0) {
3997 btrfs_print_leaf(leaf);
4003 * setup_items_for_insert - Helper called before inserting one or more items
4004 * to a leaf. Main purpose is to save stack depth by doing the bulk of the work
4005 * in a function that doesn't call btrfs_search_slot
4007 * @root: root we are inserting items to
4008 * @path: points to the leaf/slot where we are going to insert new items
4009 * @batch: information about the batch of items to insert
4011 static void setup_items_for_insert(struct btrfs_root *root, struct btrfs_path *path,
4012 const struct btrfs_item_batch *batch)
4014 struct btrfs_fs_info *fs_info = root->fs_info;
4017 unsigned int data_end;
4018 struct btrfs_disk_key disk_key;
4019 struct extent_buffer *leaf;
4021 struct btrfs_map_token token;
4025 * Before anything else, update keys in the parent and other ancestors
4026 * if needed, then release the write locks on them, so that other tasks
4027 * can use them while we modify the leaf.
4029 if (path->slots[0] == 0) {
4030 btrfs_cpu_key_to_disk(&disk_key, &batch->keys[0]);
4031 fixup_low_keys(path, &disk_key, 1);
4033 btrfs_unlock_up_safe(path, 1);
4035 leaf = path->nodes[0];
4036 slot = path->slots[0];
4038 nritems = btrfs_header_nritems(leaf);
4039 data_end = leaf_data_end(leaf);
4040 total_size = batch->total_data_size + (batch->nr * sizeof(struct btrfs_item));
4042 if (btrfs_leaf_free_space(leaf) < total_size) {
4043 btrfs_print_leaf(leaf);
4044 btrfs_crit(fs_info, "not enough freespace need %u have %d",
4045 total_size, btrfs_leaf_free_space(leaf));
4049 btrfs_init_map_token(&token, leaf);
4050 if (slot != nritems) {
4051 unsigned int old_data = btrfs_item_data_end(leaf, slot);
4053 if (old_data < data_end) {
4054 btrfs_print_leaf(leaf);
4056 "item at slot %d with data offset %u beyond data end of leaf %u",
4057 slot, old_data, data_end);
4061 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4063 /* first correct the data pointers */
4064 for (i = slot; i < nritems; i++) {
4067 ioff = btrfs_token_item_offset(&token, i);
4068 btrfs_set_token_item_offset(&token, i,
4069 ioff - batch->total_data_size);
4071 /* shift the items */
4072 memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + batch->nr),
4073 btrfs_item_nr_offset(slot),
4074 (nritems - slot) * sizeof(struct btrfs_item));
4076 /* shift the data */
4077 memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
4078 data_end - batch->total_data_size,
4079 BTRFS_LEAF_DATA_OFFSET + data_end,
4080 old_data - data_end);
4081 data_end = old_data;
4084 /* setup the item for the new data */
4085 for (i = 0; i < batch->nr; i++) {
4086 btrfs_cpu_key_to_disk(&disk_key, &batch->keys[i]);
4087 btrfs_set_item_key(leaf, &disk_key, slot + i);
4088 data_end -= batch->data_sizes[i];
4089 btrfs_set_token_item_offset(&token, slot + i, data_end);
4090 btrfs_set_token_item_size(&token, slot + i, batch->data_sizes[i]);
4093 btrfs_set_header_nritems(leaf, nritems + batch->nr);
4094 btrfs_mark_buffer_dirty(leaf);
4096 if (btrfs_leaf_free_space(leaf) < 0) {
4097 btrfs_print_leaf(leaf);
4103 * Insert a new item into a leaf.
4105 * @root: The root of the btree.
4106 * @path: A path pointing to the target leaf and slot.
4107 * @key: The key of the new item.
4108 * @data_size: The size of the data associated with the new key.
4110 void btrfs_setup_item_for_insert(struct btrfs_root *root,
4111 struct btrfs_path *path,
4112 const struct btrfs_key *key,
4115 struct btrfs_item_batch batch;
4118 batch.data_sizes = &data_size;
4119 batch.total_data_size = data_size;
4122 setup_items_for_insert(root, path, &batch);
4126 * Given a key and some data, insert items into the tree.
4127 * This does all the path init required, making room in the tree if needed.
4129 int btrfs_insert_empty_items(struct btrfs_trans_handle *trans,
4130 struct btrfs_root *root,
4131 struct btrfs_path *path,
4132 const struct btrfs_item_batch *batch)
4138 total_size = batch->total_data_size + (batch->nr * sizeof(struct btrfs_item));
4139 ret = btrfs_search_slot(trans, root, &batch->keys[0], path, total_size, 1);
4145 slot = path->slots[0];
4148 setup_items_for_insert(root, path, batch);
4153 * Given a key and some data, insert an item into the tree.
4154 * This does all the path init required, making room in the tree if needed.
4156 int btrfs_insert_item(struct btrfs_trans_handle *trans, struct btrfs_root *root,
4157 const struct btrfs_key *cpu_key, void *data,
4161 struct btrfs_path *path;
4162 struct extent_buffer *leaf;
4165 path = btrfs_alloc_path();
4168 ret = btrfs_insert_empty_item(trans, root, path, cpu_key, data_size);
4170 leaf = path->nodes[0];
4171 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
4172 write_extent_buffer(leaf, data, ptr, data_size);
4173 btrfs_mark_buffer_dirty(leaf);
4175 btrfs_free_path(path);
4180 * This function duplicates an item, giving 'new_key' to the new item.
4181 * It guarantees both items live in the same tree leaf and the new item is
4182 * contiguous with the original item.
4184 * This allows us to split a file extent in place, keeping a lock on the leaf
4187 int btrfs_duplicate_item(struct btrfs_trans_handle *trans,
4188 struct btrfs_root *root,
4189 struct btrfs_path *path,
4190 const struct btrfs_key *new_key)
4192 struct extent_buffer *leaf;
4196 leaf = path->nodes[0];
4197 item_size = btrfs_item_size(leaf, path->slots[0]);
4198 ret = setup_leaf_for_split(trans, root, path,
4199 item_size + sizeof(struct btrfs_item));
4204 btrfs_setup_item_for_insert(root, path, new_key, item_size);
4205 leaf = path->nodes[0];
4206 memcpy_extent_buffer(leaf,
4207 btrfs_item_ptr_offset(leaf, path->slots[0]),
4208 btrfs_item_ptr_offset(leaf, path->slots[0] - 1),
4214 * delete the pointer from a given node.
4216 * the tree should have been previously balanced so the deletion does not
4219 static void del_ptr(struct btrfs_root *root, struct btrfs_path *path,
4220 int level, int slot)
4222 struct extent_buffer *parent = path->nodes[level];
4226 nritems = btrfs_header_nritems(parent);
4227 if (slot != nritems - 1) {
4229 ret = btrfs_tree_mod_log_insert_move(parent, slot,
4230 slot + 1, nritems - slot - 1);
4233 memmove_extent_buffer(parent,
4234 btrfs_node_key_ptr_offset(slot),
4235 btrfs_node_key_ptr_offset(slot + 1),
4236 sizeof(struct btrfs_key_ptr) *
4237 (nritems - slot - 1));
4239 ret = btrfs_tree_mod_log_insert_key(parent, slot,
4240 BTRFS_MOD_LOG_KEY_REMOVE, GFP_NOFS);
4245 btrfs_set_header_nritems(parent, nritems);
4246 if (nritems == 0 && parent == root->node) {
4247 BUG_ON(btrfs_header_level(root->node) != 1);
4248 /* just turn the root into a leaf and break */
4249 btrfs_set_header_level(root->node, 0);
4250 } else if (slot == 0) {
4251 struct btrfs_disk_key disk_key;
4253 btrfs_node_key(parent, &disk_key, 0);
4254 fixup_low_keys(path, &disk_key, level + 1);
4256 btrfs_mark_buffer_dirty(parent);
4260 * a helper function to delete the leaf pointed to by path->slots[1] and
4263 * This deletes the pointer in path->nodes[1] and frees the leaf
4264 * block extent. zero is returned if it all worked out, < 0 otherwise.
4266 * The path must have already been setup for deleting the leaf, including
4267 * all the proper balancing. path->nodes[1] must be locked.
4269 static noinline void btrfs_del_leaf(struct btrfs_trans_handle *trans,
4270 struct btrfs_root *root,
4271 struct btrfs_path *path,
4272 struct extent_buffer *leaf)
4274 WARN_ON(btrfs_header_generation(leaf) != trans->transid);
4275 del_ptr(root, path, 1, path->slots[1]);
4278 * btrfs_free_extent is expensive, we want to make sure we
4279 * aren't holding any locks when we call it
4281 btrfs_unlock_up_safe(path, 0);
4283 root_sub_used(root, leaf->len);
4285 atomic_inc(&leaf->refs);
4286 btrfs_free_tree_block(trans, btrfs_root_id(root), leaf, 0, 1);
4287 free_extent_buffer_stale(leaf);
4290 * delete the item at the leaf level in path. If that empties
4291 * the leaf, remove it from the tree
4293 int btrfs_del_items(struct btrfs_trans_handle *trans, struct btrfs_root *root,
4294 struct btrfs_path *path, int slot, int nr)
4296 struct btrfs_fs_info *fs_info = root->fs_info;
4297 struct extent_buffer *leaf;
4302 leaf = path->nodes[0];
4303 nritems = btrfs_header_nritems(leaf);
4305 if (slot + nr != nritems) {
4306 const u32 last_off = btrfs_item_offset(leaf, slot + nr - 1);
4307 const int data_end = leaf_data_end(leaf);
4308 struct btrfs_map_token token;
4312 for (i = 0; i < nr; i++)
4313 dsize += btrfs_item_size(leaf, slot + i);
4315 memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
4317 BTRFS_LEAF_DATA_OFFSET + data_end,
4318 last_off - data_end);
4320 btrfs_init_map_token(&token, leaf);
4321 for (i = slot + nr; i < nritems; i++) {
4324 ioff = btrfs_token_item_offset(&token, i);
4325 btrfs_set_token_item_offset(&token, i, ioff + dsize);
4328 memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot),
4329 btrfs_item_nr_offset(slot + nr),
4330 sizeof(struct btrfs_item) *
4331 (nritems - slot - nr));
4333 btrfs_set_header_nritems(leaf, nritems - nr);
4336 /* delete the leaf if we've emptied it */
4338 if (leaf == root->node) {
4339 btrfs_set_header_level(leaf, 0);
4341 btrfs_clean_tree_block(leaf);
4342 btrfs_del_leaf(trans, root, path, leaf);
4345 int used = leaf_space_used(leaf, 0, nritems);
4347 struct btrfs_disk_key disk_key;
4349 btrfs_item_key(leaf, &disk_key, 0);
4350 fixup_low_keys(path, &disk_key, 1);
4354 * Try to delete the leaf if it is mostly empty. We do this by
4355 * trying to move all its items into its left and right neighbours.
4356 * If we can't move all the items, then we don't delete it - it's
4357 * not ideal, but future insertions might fill the leaf with more
4358 * items, or items from other leaves might be moved later into our
4359 * leaf due to deletions on those leaves.
4361 if (used < BTRFS_LEAF_DATA_SIZE(fs_info) / 3) {
4364 /* push_leaf_left fixes the path.
4365 * make sure the path still points to our leaf
4366 * for possible call to del_ptr below
4368 slot = path->slots[1];
4369 atomic_inc(&leaf->refs);
4371 * We want to be able to at least push one item to the
4372 * left neighbour leaf, and that's the first item.
4374 min_push_space = sizeof(struct btrfs_item) +
4375 btrfs_item_size(leaf, 0);
4376 wret = push_leaf_left(trans, root, path, 0,
4377 min_push_space, 1, (u32)-1);
4378 if (wret < 0 && wret != -ENOSPC)
4381 if (path->nodes[0] == leaf &&
4382 btrfs_header_nritems(leaf)) {
4384 * If we were not able to push all items from our
4385 * leaf to its left neighbour, then attempt to
4386 * either push all the remaining items to the
4387 * right neighbour or none. There's no advantage
4388 * in pushing only some items, instead of all, as
4389 * it's pointless to end up with a leaf having
4390 * too few items while the neighbours can be full
4393 nritems = btrfs_header_nritems(leaf);
4394 min_push_space = leaf_space_used(leaf, 0, nritems);
4395 wret = push_leaf_right(trans, root, path, 0,
4396 min_push_space, 1, 0);
4397 if (wret < 0 && wret != -ENOSPC)
4401 if (btrfs_header_nritems(leaf) == 0) {
4402 path->slots[1] = slot;
4403 btrfs_del_leaf(trans, root, path, leaf);
4404 free_extent_buffer(leaf);
4407 /* if we're still in the path, make sure
4408 * we're dirty. Otherwise, one of the
4409 * push_leaf functions must have already
4410 * dirtied this buffer
4412 if (path->nodes[0] == leaf)
4413 btrfs_mark_buffer_dirty(leaf);
4414 free_extent_buffer(leaf);
4417 btrfs_mark_buffer_dirty(leaf);
4424 * search the tree again to find a leaf with lesser keys
4425 * returns 0 if it found something or 1 if there are no lesser leaves.
4426 * returns < 0 on io errors.
4428 * This may release the path, and so you may lose any locks held at the
4431 int btrfs_prev_leaf(struct btrfs_root *root, struct btrfs_path *path)
4433 struct btrfs_key key;
4434 struct btrfs_key orig_key;
4435 struct btrfs_disk_key found_key;
4438 btrfs_item_key_to_cpu(path->nodes[0], &key, 0);
4441 if (key.offset > 0) {
4443 } else if (key.type > 0) {
4445 key.offset = (u64)-1;
4446 } else if (key.objectid > 0) {
4449 key.offset = (u64)-1;
4454 btrfs_release_path(path);
4455 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4460 * Previous key not found. Even if we were at slot 0 of the leaf we had
4461 * before releasing the path and calling btrfs_search_slot(), we now may
4462 * be in a slot pointing to the same original key - this can happen if
4463 * after we released the path, one of more items were moved from a
4464 * sibling leaf into the front of the leaf we had due to an insertion
4465 * (see push_leaf_right()).
4466 * If we hit this case and our slot is > 0 and just decrement the slot
4467 * so that the caller does not process the same key again, which may or
4468 * may not break the caller, depending on its logic.
4470 if (path->slots[0] < btrfs_header_nritems(path->nodes[0])) {
4471 btrfs_item_key(path->nodes[0], &found_key, path->slots[0]);
4472 ret = comp_keys(&found_key, &orig_key);
4474 if (path->slots[0] > 0) {
4479 * At slot 0, same key as before, it means orig_key is
4480 * the lowest, leftmost, key in the tree. We're done.
4486 btrfs_item_key(path->nodes[0], &found_key, 0);
4487 ret = comp_keys(&found_key, &key);
4489 * We might have had an item with the previous key in the tree right
4490 * before we released our path. And after we released our path, that
4491 * item might have been pushed to the first slot (0) of the leaf we
4492 * were holding due to a tree balance. Alternatively, an item with the
4493 * previous key can exist as the only element of a leaf (big fat item).
4494 * Therefore account for these 2 cases, so that our callers (like
4495 * btrfs_previous_item) don't miss an existing item with a key matching
4496 * the previous key we computed above.
4504 * A helper function to walk down the tree starting at min_key, and looking
4505 * for nodes or leaves that are have a minimum transaction id.
4506 * This is used by the btree defrag code, and tree logging
4508 * This does not cow, but it does stuff the starting key it finds back
4509 * into min_key, so you can call btrfs_search_slot with cow=1 on the
4510 * key and get a writable path.
4512 * This honors path->lowest_level to prevent descent past a given level
4515 * min_trans indicates the oldest transaction that you are interested
4516 * in walking through. Any nodes or leaves older than min_trans are
4517 * skipped over (without reading them).
4519 * returns zero if something useful was found, < 0 on error and 1 if there
4520 * was nothing in the tree that matched the search criteria.
4522 int btrfs_search_forward(struct btrfs_root *root, struct btrfs_key *min_key,
4523 struct btrfs_path *path,
4526 struct extent_buffer *cur;
4527 struct btrfs_key found_key;
4533 int keep_locks = path->keep_locks;
4535 ASSERT(!path->nowait);
4536 path->keep_locks = 1;
4538 cur = btrfs_read_lock_root_node(root);
4539 level = btrfs_header_level(cur);
4540 WARN_ON(path->nodes[level]);
4541 path->nodes[level] = cur;
4542 path->locks[level] = BTRFS_READ_LOCK;
4544 if (btrfs_header_generation(cur) < min_trans) {
4549 nritems = btrfs_header_nritems(cur);
4550 level = btrfs_header_level(cur);
4551 sret = btrfs_bin_search(cur, min_key, &slot);
4557 /* at the lowest level, we're done, setup the path and exit */
4558 if (level == path->lowest_level) {
4559 if (slot >= nritems)
4562 path->slots[level] = slot;
4563 btrfs_item_key_to_cpu(cur, &found_key, slot);
4566 if (sret && slot > 0)
4569 * check this node pointer against the min_trans parameters.
4570 * If it is too old, skip to the next one.
4572 while (slot < nritems) {
4575 gen = btrfs_node_ptr_generation(cur, slot);
4576 if (gen < min_trans) {
4584 * we didn't find a candidate key in this node, walk forward
4585 * and find another one
4587 if (slot >= nritems) {
4588 path->slots[level] = slot;
4589 sret = btrfs_find_next_key(root, path, min_key, level,
4592 btrfs_release_path(path);
4598 /* save our key for returning back */
4599 btrfs_node_key_to_cpu(cur, &found_key, slot);
4600 path->slots[level] = slot;
4601 if (level == path->lowest_level) {
4605 cur = btrfs_read_node_slot(cur, slot);
4611 btrfs_tree_read_lock(cur);
4613 path->locks[level - 1] = BTRFS_READ_LOCK;
4614 path->nodes[level - 1] = cur;
4615 unlock_up(path, level, 1, 0, NULL);
4618 path->keep_locks = keep_locks;
4620 btrfs_unlock_up_safe(path, path->lowest_level + 1);
4621 memcpy(min_key, &found_key, sizeof(found_key));
4627 * this is similar to btrfs_next_leaf, but does not try to preserve
4628 * and fixup the path. It looks for and returns the next key in the
4629 * tree based on the current path and the min_trans parameters.
4631 * 0 is returned if another key is found, < 0 if there are any errors
4632 * and 1 is returned if there are no higher keys in the tree
4634 * path->keep_locks should be set to 1 on the search made before
4635 * calling this function.
4637 int btrfs_find_next_key(struct btrfs_root *root, struct btrfs_path *path,
4638 struct btrfs_key *key, int level, u64 min_trans)
4641 struct extent_buffer *c;
4643 WARN_ON(!path->keep_locks && !path->skip_locking);
4644 while (level < BTRFS_MAX_LEVEL) {
4645 if (!path->nodes[level])
4648 slot = path->slots[level] + 1;
4649 c = path->nodes[level];
4651 if (slot >= btrfs_header_nritems(c)) {
4654 struct btrfs_key cur_key;
4655 if (level + 1 >= BTRFS_MAX_LEVEL ||
4656 !path->nodes[level + 1])
4659 if (path->locks[level + 1] || path->skip_locking) {
4664 slot = btrfs_header_nritems(c) - 1;
4666 btrfs_item_key_to_cpu(c, &cur_key, slot);
4668 btrfs_node_key_to_cpu(c, &cur_key, slot);
4670 orig_lowest = path->lowest_level;
4671 btrfs_release_path(path);
4672 path->lowest_level = level;
4673 ret = btrfs_search_slot(NULL, root, &cur_key, path,
4675 path->lowest_level = orig_lowest;
4679 c = path->nodes[level];
4680 slot = path->slots[level];
4687 btrfs_item_key_to_cpu(c, key, slot);
4689 u64 gen = btrfs_node_ptr_generation(c, slot);
4691 if (gen < min_trans) {
4695 btrfs_node_key_to_cpu(c, key, slot);
4702 int btrfs_next_old_leaf(struct btrfs_root *root, struct btrfs_path *path,
4707 struct extent_buffer *c;
4708 struct extent_buffer *next;
4709 struct btrfs_fs_info *fs_info = root->fs_info;
4710 struct btrfs_key key;
4711 bool need_commit_sem = false;
4717 * The nowait semantics are used only for write paths, where we don't
4718 * use the tree mod log and sequence numbers.
4721 ASSERT(!path->nowait);
4723 nritems = btrfs_header_nritems(path->nodes[0]);
4727 btrfs_item_key_to_cpu(path->nodes[0], &key, nritems - 1);
4731 btrfs_release_path(path);
4733 path->keep_locks = 1;
4736 ret = btrfs_search_old_slot(root, &key, path, time_seq);
4738 if (path->need_commit_sem) {
4739 path->need_commit_sem = 0;
4740 need_commit_sem = true;
4742 if (!down_read_trylock(&fs_info->commit_root_sem)) {
4747 down_read(&fs_info->commit_root_sem);
4750 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4752 path->keep_locks = 0;
4757 nritems = btrfs_header_nritems(path->nodes[0]);
4759 * by releasing the path above we dropped all our locks. A balance
4760 * could have added more items next to the key that used to be
4761 * at the very end of the block. So, check again here and
4762 * advance the path if there are now more items available.
4764 if (nritems > 0 && path->slots[0] < nritems - 1) {
4771 * So the above check misses one case:
4772 * - after releasing the path above, someone has removed the item that
4773 * used to be at the very end of the block, and balance between leafs
4774 * gets another one with bigger key.offset to replace it.
4776 * This one should be returned as well, or we can get leaf corruption
4777 * later(esp. in __btrfs_drop_extents()).
4779 * And a bit more explanation about this check,
4780 * with ret > 0, the key isn't found, the path points to the slot
4781 * where it should be inserted, so the path->slots[0] item must be the
4784 if (nritems > 0 && ret > 0 && path->slots[0] == nritems - 1) {
4789 while (level < BTRFS_MAX_LEVEL) {
4790 if (!path->nodes[level]) {
4795 slot = path->slots[level] + 1;
4796 c = path->nodes[level];
4797 if (slot >= btrfs_header_nritems(c)) {
4799 if (level == BTRFS_MAX_LEVEL) {
4808 * Our current level is where we're going to start from, and to
4809 * make sure lockdep doesn't complain we need to drop our locks
4810 * and nodes from 0 to our current level.
4812 for (i = 0; i < level; i++) {
4813 if (path->locks[level]) {
4814 btrfs_tree_read_unlock(path->nodes[i]);
4817 free_extent_buffer(path->nodes[i]);
4818 path->nodes[i] = NULL;
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) {
4833 ret = btrfs_try_tree_read_lock(next);
4834 if (!ret && path->nowait) {
4838 if (!ret && time_seq) {
4840 * If we don't get the lock, we may be racing
4841 * with push_leaf_left, holding that lock while
4842 * itself waiting for the leaf we've currently
4843 * locked. To solve this situation, we give up
4844 * on our lock and cycle.
4846 free_extent_buffer(next);
4847 btrfs_release_path(path);
4852 btrfs_tree_read_lock(next);
4856 path->slots[level] = slot;
4859 path->nodes[level] = next;
4860 path->slots[level] = 0;
4861 if (!path->skip_locking)
4862 path->locks[level] = BTRFS_READ_LOCK;
4866 ret = read_block_for_search(root, path, &next, level,
4868 if (ret == -EAGAIN && !path->nowait)
4872 btrfs_release_path(path);
4876 if (!path->skip_locking) {
4878 if (!btrfs_try_tree_read_lock(next)) {
4883 btrfs_tree_read_lock(next);
4889 unlock_up(path, 0, 1, 0, NULL);
4890 if (need_commit_sem) {
4893 path->need_commit_sem = 1;
4894 ret2 = finish_need_commit_sem_search(path);
4895 up_read(&fs_info->commit_root_sem);
4904 * this uses btrfs_prev_leaf to walk backwards in the tree, and keeps
4905 * searching until it gets past min_objectid or finds an item of 'type'
4907 * returns 0 if something is found, 1 if nothing was found and < 0 on error
4909 int btrfs_previous_item(struct btrfs_root *root,
4910 struct btrfs_path *path, u64 min_objectid,
4913 struct btrfs_key found_key;
4914 struct extent_buffer *leaf;
4919 if (path->slots[0] == 0) {
4920 ret = btrfs_prev_leaf(root, path);
4926 leaf = path->nodes[0];
4927 nritems = btrfs_header_nritems(leaf);
4930 if (path->slots[0] == nritems)
4933 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4934 if (found_key.objectid < min_objectid)
4936 if (found_key.type == type)
4938 if (found_key.objectid == min_objectid &&
4939 found_key.type < type)
4946 * search in extent tree to find a previous Metadata/Data extent item with
4949 * returns 0 if something is found, 1 if nothing was found and < 0 on error
4951 int btrfs_previous_extent_item(struct btrfs_root *root,
4952 struct btrfs_path *path, u64 min_objectid)
4954 struct btrfs_key found_key;
4955 struct extent_buffer *leaf;
4960 if (path->slots[0] == 0) {
4961 ret = btrfs_prev_leaf(root, path);
4967 leaf = path->nodes[0];
4968 nritems = btrfs_header_nritems(leaf);
4971 if (path->slots[0] == nritems)
4974 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4975 if (found_key.objectid < min_objectid)
4977 if (found_key.type == BTRFS_EXTENT_ITEM_KEY ||
4978 found_key.type == BTRFS_METADATA_ITEM_KEY)
4980 if (found_key.objectid == min_objectid &&
4981 found_key.type < BTRFS_EXTENT_ITEM_KEY)