1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 2007,2008 Oracle. All rights reserved.
6 #include <linux/sched.h>
7 #include <linux/slab.h>
8 #include <linux/rbtree.h>
10 #include <linux/error-injection.h>
14 #include "transaction.h"
15 #include "print-tree.h"
19 #include "tree-mod-log.h"
20 #include "tree-checker.h"
22 #include "accessors.h"
23 #include "extent-tree.h"
24 #include "relocation.h"
25 #include "file-item.h"
27 static struct kmem_cache *btrfs_path_cachep;
29 static int split_node(struct btrfs_trans_handle *trans, struct btrfs_root
30 *root, struct btrfs_path *path, int level);
31 static int split_leaf(struct btrfs_trans_handle *trans, struct btrfs_root *root,
32 const struct btrfs_key *ins_key, struct btrfs_path *path,
33 int data_size, int extend);
34 static int push_node_left(struct btrfs_trans_handle *trans,
35 struct extent_buffer *dst,
36 struct extent_buffer *src, int empty);
37 static int balance_node_right(struct btrfs_trans_handle *trans,
38 struct extent_buffer *dst_buf,
39 struct extent_buffer *src_buf);
41 static const struct btrfs_csums {
44 const char driver[12];
46 [BTRFS_CSUM_TYPE_CRC32] = { .size = 4, .name = "crc32c" },
47 [BTRFS_CSUM_TYPE_XXHASH] = { .size = 8, .name = "xxhash64" },
48 [BTRFS_CSUM_TYPE_SHA256] = { .size = 32, .name = "sha256" },
49 [BTRFS_CSUM_TYPE_BLAKE2] = { .size = 32, .name = "blake2b",
50 .driver = "blake2b-256" },
54 * The leaf data grows from end-to-front in the node. this returns the address
55 * of the start of the last item, which is the stop of the leaf data stack.
57 static unsigned int leaf_data_end(const struct extent_buffer *leaf)
59 u32 nr = btrfs_header_nritems(leaf);
62 return BTRFS_LEAF_DATA_SIZE(leaf->fs_info);
63 return btrfs_item_offset(leaf, nr - 1);
67 * Move data in a @leaf (using memmove, safe for overlapping ranges).
69 * @leaf: leaf that we're doing a memmove on
70 * @dst_offset: item data offset we're moving to
71 * @src_offset: item data offset were' moving from
72 * @len: length of the data we're moving
74 * Wrapper around memmove_extent_buffer() that takes into account the header on
75 * the leaf. The btrfs_item offset's start directly after the header, so we
76 * have to adjust any offsets to account for the header in the leaf. This
77 * handles that math to simplify the callers.
79 static inline void memmove_leaf_data(const struct extent_buffer *leaf,
80 unsigned long dst_offset,
81 unsigned long src_offset,
84 memmove_extent_buffer(leaf, btrfs_item_nr_offset(leaf, 0) + dst_offset,
85 btrfs_item_nr_offset(leaf, 0) + src_offset, len);
89 * Copy item data from @src into @dst at the given @offset.
91 * @dst: destination leaf that we're copying into
92 * @src: source leaf that we're copying from
93 * @dst_offset: item data offset we're copying to
94 * @src_offset: item data offset were' copying from
95 * @len: length of the data we're copying
97 * Wrapper around copy_extent_buffer() that takes into account the header on
98 * the leaf. The btrfs_item offset's start directly after the header, so we
99 * have to adjust any offsets to account for the header in the leaf. This
100 * handles that math to simplify the callers.
102 static inline void copy_leaf_data(const struct extent_buffer *dst,
103 const struct extent_buffer *src,
104 unsigned long dst_offset,
105 unsigned long src_offset, unsigned long len)
107 copy_extent_buffer(dst, src, btrfs_item_nr_offset(dst, 0) + dst_offset,
108 btrfs_item_nr_offset(src, 0) + src_offset, len);
112 * Move items in a @leaf (using memmove).
114 * @dst: destination leaf for the items
115 * @dst_item: the item nr we're copying into
116 * @src_item: the item nr we're copying from
117 * @nr_items: the number of items to copy
119 * Wrapper around memmove_extent_buffer() that does the math to get the
120 * appropriate offsets into the leaf from the item numbers.
122 static inline void memmove_leaf_items(const struct extent_buffer *leaf,
123 int dst_item, int src_item, int nr_items)
125 memmove_extent_buffer(leaf, btrfs_item_nr_offset(leaf, dst_item),
126 btrfs_item_nr_offset(leaf, src_item),
127 nr_items * sizeof(struct btrfs_item));
131 * Copy items from @src into @dst at the given @offset.
133 * @dst: destination leaf for the items
134 * @src: source leaf for the items
135 * @dst_item: the item nr we're copying into
136 * @src_item: the item nr we're copying from
137 * @nr_items: the number of items to copy
139 * Wrapper around copy_extent_buffer() that does the math to get the
140 * appropriate offsets into the leaf from the item numbers.
142 static inline void copy_leaf_items(const struct extent_buffer *dst,
143 const struct extent_buffer *src,
144 int dst_item, int src_item, int nr_items)
146 copy_extent_buffer(dst, src, btrfs_item_nr_offset(dst, dst_item),
147 btrfs_item_nr_offset(src, src_item),
148 nr_items * sizeof(struct btrfs_item));
151 /* This exists for btrfs-progs usages. */
152 u16 btrfs_csum_type_size(u16 type)
154 return btrfs_csums[type].size;
157 int btrfs_super_csum_size(const struct btrfs_super_block *s)
159 u16 t = btrfs_super_csum_type(s);
161 * csum type is validated at mount time
163 return btrfs_csum_type_size(t);
166 const char *btrfs_super_csum_name(u16 csum_type)
168 /* csum type is validated at mount time */
169 return btrfs_csums[csum_type].name;
173 * Return driver name if defined, otherwise the name that's also a valid driver
176 const char *btrfs_super_csum_driver(u16 csum_type)
178 /* csum type is validated at mount time */
179 return btrfs_csums[csum_type].driver[0] ?
180 btrfs_csums[csum_type].driver :
181 btrfs_csums[csum_type].name;
184 size_t __attribute_const__ btrfs_get_num_csums(void)
186 return ARRAY_SIZE(btrfs_csums);
189 struct btrfs_path *btrfs_alloc_path(void)
193 return kmem_cache_zalloc(btrfs_path_cachep, GFP_NOFS);
196 /* this also releases the path */
197 void btrfs_free_path(struct btrfs_path *p)
201 btrfs_release_path(p);
202 kmem_cache_free(btrfs_path_cachep, p);
206 * path release drops references on the extent buffers in the path
207 * and it drops any locks held by this path
209 * It is safe to call this on paths that no locks or extent buffers held.
211 noinline void btrfs_release_path(struct btrfs_path *p)
215 for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
220 btrfs_tree_unlock_rw(p->nodes[i], p->locks[i]);
223 free_extent_buffer(p->nodes[i]);
229 * We want the transaction abort to print stack trace only for errors where the
230 * cause could be a bug, eg. due to ENOSPC, and not for common errors that are
231 * caused by external factors.
233 bool __cold abort_should_print_stack(int error)
245 * safely gets a reference on the root node of a tree. A lock
246 * is not taken, so a concurrent writer may put a different node
247 * at the root of the tree. See btrfs_lock_root_node for the
250 * The extent buffer returned by this has a reference taken, so
251 * it won't disappear. It may stop being the root of the tree
252 * at any time because there are no locks held.
254 struct extent_buffer *btrfs_root_node(struct btrfs_root *root)
256 struct extent_buffer *eb;
260 eb = rcu_dereference(root->node);
263 * RCU really hurts here, we could free up the root node because
264 * it was COWed but we may not get the new root node yet so do
265 * the inc_not_zero dance and if it doesn't work then
266 * synchronize_rcu and try again.
268 if (atomic_inc_not_zero(&eb->refs)) {
279 * Cowonly root (not-shareable trees, everything not subvolume or reloc roots),
280 * just get put onto a simple dirty list. Transaction walks this list to make
281 * sure they get properly updated on disk.
283 static void add_root_to_dirty_list(struct btrfs_root *root)
285 struct btrfs_fs_info *fs_info = root->fs_info;
287 if (test_bit(BTRFS_ROOT_DIRTY, &root->state) ||
288 !test_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state))
291 spin_lock(&fs_info->trans_lock);
292 if (!test_and_set_bit(BTRFS_ROOT_DIRTY, &root->state)) {
293 /* Want the extent tree to be the last on the list */
294 if (btrfs_root_id(root) == BTRFS_EXTENT_TREE_OBJECTID)
295 list_move_tail(&root->dirty_list,
296 &fs_info->dirty_cowonly_roots);
298 list_move(&root->dirty_list,
299 &fs_info->dirty_cowonly_roots);
301 spin_unlock(&fs_info->trans_lock);
305 * used by snapshot creation to make a copy of a root for a tree with
306 * a given objectid. The buffer with the new root node is returned in
307 * cow_ret, and this func returns zero on success or a negative error code.
309 int btrfs_copy_root(struct btrfs_trans_handle *trans,
310 struct btrfs_root *root,
311 struct extent_buffer *buf,
312 struct extent_buffer **cow_ret, u64 new_root_objectid)
314 struct btrfs_fs_info *fs_info = root->fs_info;
315 struct extent_buffer *cow;
318 struct btrfs_disk_key disk_key;
319 u64 reloc_src_root = 0;
321 WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
322 trans->transid != fs_info->running_transaction->transid);
323 WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
324 trans->transid != root->last_trans);
326 level = btrfs_header_level(buf);
328 btrfs_item_key(buf, &disk_key, 0);
330 btrfs_node_key(buf, &disk_key, 0);
332 if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
333 reloc_src_root = btrfs_header_owner(buf);
334 cow = btrfs_alloc_tree_block(trans, root, 0, new_root_objectid,
335 &disk_key, level, buf->start, 0,
336 reloc_src_root, BTRFS_NESTING_NEW_ROOT);
340 copy_extent_buffer_full(cow, buf);
341 btrfs_set_header_bytenr(cow, cow->start);
342 btrfs_set_header_generation(cow, trans->transid);
343 btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
344 btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
345 BTRFS_HEADER_FLAG_RELOC);
346 if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
347 btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
349 btrfs_set_header_owner(cow, new_root_objectid);
351 write_extent_buffer_fsid(cow, fs_info->fs_devices->metadata_uuid);
353 WARN_ON(btrfs_header_generation(buf) > trans->transid);
354 if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
355 ret = btrfs_inc_ref(trans, root, cow, 1);
357 ret = btrfs_inc_ref(trans, root, cow, 0);
359 btrfs_tree_unlock(cow);
360 free_extent_buffer(cow);
361 btrfs_abort_transaction(trans, ret);
365 btrfs_mark_buffer_dirty(trans, cow);
371 * check if the tree block can be shared by multiple trees
373 bool btrfs_block_can_be_shared(struct btrfs_trans_handle *trans,
374 struct btrfs_root *root,
375 struct extent_buffer *buf)
377 const u64 buf_gen = btrfs_header_generation(buf);
380 * Tree blocks not in shareable trees and tree roots are never shared.
381 * If a block was allocated after the last snapshot and the block was
382 * not allocated by tree relocation, we know the block is not shared.
385 if (!test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
388 if (buf == root->node)
391 if (buf_gen > btrfs_root_last_snapshot(&root->root_item) &&
392 !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC))
395 if (buf != root->commit_root)
399 * An extent buffer that used to be the commit root may still be shared
400 * because the tree height may have increased and it became a child of a
401 * higher level root. This can happen when snapshotting a subvolume
402 * created in the current transaction.
404 if (buf_gen == trans->transid)
410 static noinline int update_ref_for_cow(struct btrfs_trans_handle *trans,
411 struct btrfs_root *root,
412 struct extent_buffer *buf,
413 struct extent_buffer *cow,
416 struct btrfs_fs_info *fs_info = root->fs_info;
424 * Backrefs update rules:
426 * Always use full backrefs for extent pointers in tree block
427 * allocated by tree relocation.
429 * If a shared tree block is no longer referenced by its owner
430 * tree (btrfs_header_owner(buf) == root->root_key.objectid),
431 * use full backrefs for extent pointers in tree block.
433 * If a tree block is been relocating
434 * (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID),
435 * use full backrefs for extent pointers in tree block.
436 * The reason for this is some operations (such as drop tree)
437 * are only allowed for blocks use full backrefs.
440 if (btrfs_block_can_be_shared(trans, root, buf)) {
441 ret = btrfs_lookup_extent_info(trans, fs_info, buf->start,
442 btrfs_header_level(buf), 1,
443 &refs, &flags, NULL);
446 if (unlikely(refs == 0)) {
448 "found 0 references for tree block at bytenr %llu level %d root %llu",
449 buf->start, btrfs_header_level(buf),
450 btrfs_root_id(root));
452 btrfs_abort_transaction(trans, ret);
457 if (btrfs_root_id(root) == BTRFS_TREE_RELOC_OBJECTID ||
458 btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
459 flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
464 owner = btrfs_header_owner(buf);
465 BUG_ON(owner == BTRFS_TREE_RELOC_OBJECTID &&
466 !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
469 if ((owner == btrfs_root_id(root) ||
470 btrfs_root_id(root) == BTRFS_TREE_RELOC_OBJECTID) &&
471 !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)) {
472 ret = btrfs_inc_ref(trans, root, buf, 1);
476 if (btrfs_root_id(root) == BTRFS_TREE_RELOC_OBJECTID) {
477 ret = btrfs_dec_ref(trans, root, buf, 0);
480 ret = btrfs_inc_ref(trans, root, cow, 1);
484 new_flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
487 if (btrfs_root_id(root) == BTRFS_TREE_RELOC_OBJECTID)
488 ret = btrfs_inc_ref(trans, root, cow, 1);
490 ret = btrfs_inc_ref(trans, root, cow, 0);
494 if (new_flags != 0) {
495 ret = btrfs_set_disk_extent_flags(trans, buf, new_flags);
500 if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
501 if (btrfs_root_id(root) == BTRFS_TREE_RELOC_OBJECTID)
502 ret = btrfs_inc_ref(trans, root, cow, 1);
504 ret = btrfs_inc_ref(trans, root, cow, 0);
507 ret = btrfs_dec_ref(trans, root, buf, 1);
511 btrfs_clear_buffer_dirty(trans, buf);
518 * does the dirty work in cow of a single block. The parent block (if
519 * supplied) is updated to point to the new cow copy. The new buffer is marked
520 * dirty and returned locked. If you modify the block it needs to be marked
523 * search_start -- an allocation hint for the new block
525 * empty_size -- a hint that you plan on doing more cow. This is the size in
526 * bytes the allocator should try to find free next to the block it returns.
527 * This is just a hint and may be ignored by the allocator.
529 int btrfs_force_cow_block(struct btrfs_trans_handle *trans,
530 struct btrfs_root *root,
531 struct extent_buffer *buf,
532 struct extent_buffer *parent, int parent_slot,
533 struct extent_buffer **cow_ret,
534 u64 search_start, u64 empty_size,
535 enum btrfs_lock_nesting nest)
537 struct btrfs_fs_info *fs_info = root->fs_info;
538 struct btrfs_disk_key disk_key;
539 struct extent_buffer *cow;
543 u64 parent_start = 0;
544 u64 reloc_src_root = 0;
549 btrfs_assert_tree_write_locked(buf);
551 WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
552 trans->transid != fs_info->running_transaction->transid);
553 WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
554 trans->transid != root->last_trans);
556 level = btrfs_header_level(buf);
559 btrfs_item_key(buf, &disk_key, 0);
561 btrfs_node_key(buf, &disk_key, 0);
563 if (btrfs_root_id(root) == BTRFS_TREE_RELOC_OBJECTID) {
565 parent_start = parent->start;
566 reloc_src_root = btrfs_header_owner(buf);
568 cow = btrfs_alloc_tree_block(trans, root, parent_start,
569 btrfs_root_id(root), &disk_key, level,
570 search_start, empty_size, reloc_src_root, nest);
574 /* cow is set to blocking by btrfs_init_new_buffer */
576 copy_extent_buffer_full(cow, buf);
577 btrfs_set_header_bytenr(cow, cow->start);
578 btrfs_set_header_generation(cow, trans->transid);
579 btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
580 btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
581 BTRFS_HEADER_FLAG_RELOC);
582 if (btrfs_root_id(root) == BTRFS_TREE_RELOC_OBJECTID)
583 btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
585 btrfs_set_header_owner(cow, btrfs_root_id(root));
587 write_extent_buffer_fsid(cow, fs_info->fs_devices->metadata_uuid);
589 ret = update_ref_for_cow(trans, root, buf, cow, &last_ref);
591 btrfs_tree_unlock(cow);
592 free_extent_buffer(cow);
593 btrfs_abort_transaction(trans, ret);
597 if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state)) {
598 ret = btrfs_reloc_cow_block(trans, root, buf, cow);
600 btrfs_tree_unlock(cow);
601 free_extent_buffer(cow);
602 btrfs_abort_transaction(trans, ret);
607 if (buf == root->node) {
608 WARN_ON(parent && parent != buf);
609 if (btrfs_root_id(root) == BTRFS_TREE_RELOC_OBJECTID ||
610 btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
611 parent_start = buf->start;
613 ret = btrfs_tree_mod_log_insert_root(root->node, cow, true);
615 btrfs_tree_unlock(cow);
616 free_extent_buffer(cow);
617 btrfs_abort_transaction(trans, ret);
620 atomic_inc(&cow->refs);
621 rcu_assign_pointer(root->node, cow);
623 btrfs_free_tree_block(trans, btrfs_root_id(root), buf,
624 parent_start, last_ref);
625 free_extent_buffer(buf);
626 add_root_to_dirty_list(root);
628 WARN_ON(trans->transid != btrfs_header_generation(parent));
629 ret = btrfs_tree_mod_log_insert_key(parent, parent_slot,
630 BTRFS_MOD_LOG_KEY_REPLACE);
632 btrfs_tree_unlock(cow);
633 free_extent_buffer(cow);
634 btrfs_abort_transaction(trans, ret);
637 btrfs_set_node_blockptr(parent, parent_slot,
639 btrfs_set_node_ptr_generation(parent, parent_slot,
641 btrfs_mark_buffer_dirty(trans, parent);
643 ret = btrfs_tree_mod_log_free_eb(buf);
645 btrfs_tree_unlock(cow);
646 free_extent_buffer(cow);
647 btrfs_abort_transaction(trans, ret);
651 btrfs_free_tree_block(trans, btrfs_root_id(root), buf,
652 parent_start, last_ref);
655 btrfs_tree_unlock(buf);
656 free_extent_buffer_stale(buf);
657 btrfs_mark_buffer_dirty(trans, cow);
662 static inline int should_cow_block(struct btrfs_trans_handle *trans,
663 struct btrfs_root *root,
664 struct extent_buffer *buf)
666 if (btrfs_is_testing(root->fs_info))
669 /* Ensure we can see the FORCE_COW bit */
670 smp_mb__before_atomic();
673 * We do not need to cow a block if
674 * 1) this block is not created or changed in this transaction;
675 * 2) this block does not belong to TREE_RELOC tree;
676 * 3) the root is not forced COW.
678 * What is forced COW:
679 * when we create snapshot during committing the transaction,
680 * after we've finished copying src root, we must COW the shared
681 * block to ensure the metadata consistency.
683 if (btrfs_header_generation(buf) == trans->transid &&
684 !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN) &&
685 !(btrfs_root_id(root) != BTRFS_TREE_RELOC_OBJECTID &&
686 btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)) &&
687 !test_bit(BTRFS_ROOT_FORCE_COW, &root->state))
693 * COWs a single block, see btrfs_force_cow_block() for the real work.
694 * This version of it has extra checks so that a block isn't COWed more than
695 * once per transaction, as long as it hasn't been written yet
697 int btrfs_cow_block(struct btrfs_trans_handle *trans,
698 struct btrfs_root *root, struct extent_buffer *buf,
699 struct extent_buffer *parent, int parent_slot,
700 struct extent_buffer **cow_ret,
701 enum btrfs_lock_nesting nest)
703 struct btrfs_fs_info *fs_info = root->fs_info;
707 if (unlikely(test_bit(BTRFS_ROOT_DELETING, &root->state))) {
708 btrfs_abort_transaction(trans, -EUCLEAN);
710 "attempt to COW block %llu on root %llu that is being deleted",
711 buf->start, btrfs_root_id(root));
716 * COWing must happen through a running transaction, which always
717 * matches the current fs generation (it's a transaction with a state
718 * less than TRANS_STATE_UNBLOCKED). If it doesn't, then turn the fs
719 * into error state to prevent the commit of any transaction.
721 if (unlikely(trans->transaction != fs_info->running_transaction ||
722 trans->transid != fs_info->generation)) {
723 btrfs_abort_transaction(trans, -EUCLEAN);
725 "unexpected transaction when attempting to COW block %llu on root %llu, transaction %llu running transaction %llu fs generation %llu",
726 buf->start, btrfs_root_id(root), trans->transid,
727 fs_info->running_transaction->transid,
728 fs_info->generation);
732 if (!should_cow_block(trans, root, buf)) {
737 search_start = round_down(buf->start, SZ_1G);
740 * Before CoWing this block for later modification, check if it's
741 * the subtree root and do the delayed subtree trace if needed.
743 * Also We don't care about the error, as it's handled internally.
745 btrfs_qgroup_trace_subtree_after_cow(trans, root, buf);
746 ret = btrfs_force_cow_block(trans, root, buf, parent, parent_slot,
747 cow_ret, search_start, 0, nest);
749 trace_btrfs_cow_block(root, buf, *cow_ret);
753 ALLOW_ERROR_INJECTION(btrfs_cow_block, ERRNO);
756 * same as comp_keys only with two btrfs_key's
758 int __pure btrfs_comp_cpu_keys(const struct btrfs_key *k1, const struct btrfs_key *k2)
760 if (k1->objectid > k2->objectid)
762 if (k1->objectid < k2->objectid)
764 if (k1->type > k2->type)
766 if (k1->type < k2->type)
768 if (k1->offset > k2->offset)
770 if (k1->offset < k2->offset)
776 * Search for a key in the given extent_buffer.
778 * The lower boundary for the search is specified by the slot number @first_slot.
779 * Use a value of 0 to search over the whole extent buffer. Works for both
782 * The slot in the extent buffer is returned via @slot. If the key exists in the
783 * extent buffer, then @slot will point to the slot where the key is, otherwise
784 * it points to the slot where you would insert the key.
786 * Slot may point to the total number of items (i.e. one position beyond the last
787 * key) if the key is bigger than the last key in the extent buffer.
789 int btrfs_bin_search(struct extent_buffer *eb, int first_slot,
790 const struct btrfs_key *key, int *slot)
795 * Use unsigned types for the low and high slots, so that we get a more
796 * efficient division in the search loop below.
798 u32 low = first_slot;
799 u32 high = btrfs_header_nritems(eb);
801 const int key_size = sizeof(struct btrfs_disk_key);
803 if (unlikely(low > high)) {
804 btrfs_err(eb->fs_info,
805 "%s: low (%u) > high (%u) eb %llu owner %llu level %d",
806 __func__, low, high, eb->start,
807 btrfs_header_owner(eb), btrfs_header_level(eb));
811 if (btrfs_header_level(eb) == 0) {
812 p = offsetof(struct btrfs_leaf, items);
813 item_size = sizeof(struct btrfs_item);
815 p = offsetof(struct btrfs_node, ptrs);
816 item_size = sizeof(struct btrfs_key_ptr);
820 const int unit_size = eb->folio_size;
822 unsigned long offset;
823 struct btrfs_disk_key *tmp;
824 struct btrfs_disk_key unaligned;
827 mid = (low + high) / 2;
828 offset = p + mid * item_size;
829 oil = get_eb_offset_in_folio(eb, offset);
831 if (oil + key_size <= unit_size) {
832 const unsigned long idx = get_eb_folio_index(eb, offset);
833 char *kaddr = folio_address(eb->folios[idx]);
835 oil = get_eb_offset_in_folio(eb, offset);
836 tmp = (struct btrfs_disk_key *)(kaddr + oil);
838 read_extent_buffer(eb, &unaligned, offset, key_size);
842 ret = btrfs_comp_keys(tmp, key);
857 static void root_add_used_bytes(struct btrfs_root *root)
859 spin_lock(&root->accounting_lock);
860 btrfs_set_root_used(&root->root_item,
861 btrfs_root_used(&root->root_item) + root->fs_info->nodesize);
862 spin_unlock(&root->accounting_lock);
865 static void root_sub_used_bytes(struct btrfs_root *root)
867 spin_lock(&root->accounting_lock);
868 btrfs_set_root_used(&root->root_item,
869 btrfs_root_used(&root->root_item) - root->fs_info->nodesize);
870 spin_unlock(&root->accounting_lock);
873 /* given a node and slot number, this reads the blocks it points to. The
874 * extent buffer is returned with a reference taken (but unlocked).
876 struct extent_buffer *btrfs_read_node_slot(struct extent_buffer *parent,
879 int level = btrfs_header_level(parent);
880 struct btrfs_tree_parent_check check = { 0 };
881 struct extent_buffer *eb;
883 if (slot < 0 || slot >= btrfs_header_nritems(parent))
884 return ERR_PTR(-ENOENT);
888 check.level = level - 1;
889 check.transid = btrfs_node_ptr_generation(parent, slot);
890 check.owner_root = btrfs_header_owner(parent);
891 check.has_first_key = true;
892 btrfs_node_key_to_cpu(parent, &check.first_key, slot);
894 eb = read_tree_block(parent->fs_info, btrfs_node_blockptr(parent, slot),
898 if (!extent_buffer_uptodate(eb)) {
899 free_extent_buffer(eb);
900 return ERR_PTR(-EIO);
907 * node level balancing, used to make sure nodes are in proper order for
908 * item deletion. We balance from the top down, so we have to make sure
909 * that a deletion won't leave an node completely empty later on.
911 static noinline int balance_level(struct btrfs_trans_handle *trans,
912 struct btrfs_root *root,
913 struct btrfs_path *path, int level)
915 struct btrfs_fs_info *fs_info = root->fs_info;
916 struct extent_buffer *right = NULL;
917 struct extent_buffer *mid;
918 struct extent_buffer *left = NULL;
919 struct extent_buffer *parent = NULL;
923 int orig_slot = path->slots[level];
928 mid = path->nodes[level];
930 WARN_ON(path->locks[level] != BTRFS_WRITE_LOCK);
931 WARN_ON(btrfs_header_generation(mid) != trans->transid);
933 orig_ptr = btrfs_node_blockptr(mid, orig_slot);
935 if (level < BTRFS_MAX_LEVEL - 1) {
936 parent = path->nodes[level + 1];
937 pslot = path->slots[level + 1];
941 * deal with the case where there is only one pointer in the root
942 * by promoting the node below to a root
945 struct extent_buffer *child;
947 if (btrfs_header_nritems(mid) != 1)
950 /* promote the child to a root */
951 child = btrfs_read_node_slot(mid, 0);
953 ret = PTR_ERR(child);
957 btrfs_tree_lock(child);
958 ret = btrfs_cow_block(trans, root, child, mid, 0, &child,
961 btrfs_tree_unlock(child);
962 free_extent_buffer(child);
966 ret = btrfs_tree_mod_log_insert_root(root->node, child, true);
968 btrfs_tree_unlock(child);
969 free_extent_buffer(child);
970 btrfs_abort_transaction(trans, ret);
973 rcu_assign_pointer(root->node, child);
975 add_root_to_dirty_list(root);
976 btrfs_tree_unlock(child);
978 path->locks[level] = 0;
979 path->nodes[level] = NULL;
980 btrfs_clear_buffer_dirty(trans, mid);
981 btrfs_tree_unlock(mid);
982 /* once for the path */
983 free_extent_buffer(mid);
985 root_sub_used_bytes(root);
986 btrfs_free_tree_block(trans, btrfs_root_id(root), mid, 0, 1);
987 /* once for the root ptr */
988 free_extent_buffer_stale(mid);
991 if (btrfs_header_nritems(mid) >
992 BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 4)
996 left = btrfs_read_node_slot(parent, pslot - 1);
1003 btrfs_tree_lock_nested(left, BTRFS_NESTING_LEFT);
1004 wret = btrfs_cow_block(trans, root, left,
1005 parent, pslot - 1, &left,
1006 BTRFS_NESTING_LEFT_COW);
1013 if (pslot + 1 < btrfs_header_nritems(parent)) {
1014 right = btrfs_read_node_slot(parent, pslot + 1);
1015 if (IS_ERR(right)) {
1016 ret = PTR_ERR(right);
1021 btrfs_tree_lock_nested(right, BTRFS_NESTING_RIGHT);
1022 wret = btrfs_cow_block(trans, root, right,
1023 parent, pslot + 1, &right,
1024 BTRFS_NESTING_RIGHT_COW);
1031 /* first, try to make some room in the middle buffer */
1033 orig_slot += btrfs_header_nritems(left);
1034 wret = push_node_left(trans, left, mid, 1);
1040 * then try to empty the right most buffer into the middle
1043 wret = push_node_left(trans, mid, right, 1);
1044 if (wret < 0 && wret != -ENOSPC)
1046 if (btrfs_header_nritems(right) == 0) {
1047 btrfs_clear_buffer_dirty(trans, right);
1048 btrfs_tree_unlock(right);
1049 ret = btrfs_del_ptr(trans, root, path, level + 1, pslot + 1);
1051 free_extent_buffer_stale(right);
1055 root_sub_used_bytes(root);
1056 btrfs_free_tree_block(trans, btrfs_root_id(root), right,
1058 free_extent_buffer_stale(right);
1061 struct btrfs_disk_key right_key;
1062 btrfs_node_key(right, &right_key, 0);
1063 ret = btrfs_tree_mod_log_insert_key(parent, pslot + 1,
1064 BTRFS_MOD_LOG_KEY_REPLACE);
1066 btrfs_abort_transaction(trans, ret);
1069 btrfs_set_node_key(parent, &right_key, pslot + 1);
1070 btrfs_mark_buffer_dirty(trans, parent);
1073 if (btrfs_header_nritems(mid) == 1) {
1075 * we're not allowed to leave a node with one item in the
1076 * tree during a delete. A deletion from lower in the tree
1077 * could try to delete the only pointer in this node.
1078 * So, pull some keys from the left.
1079 * There has to be a left pointer at this point because
1080 * otherwise we would have pulled some pointers from the
1083 if (unlikely(!left)) {
1085 "missing left child when middle child only has 1 item, parent bytenr %llu level %d mid bytenr %llu root %llu",
1086 parent->start, btrfs_header_level(parent),
1087 mid->start, btrfs_root_id(root));
1089 btrfs_abort_transaction(trans, ret);
1092 wret = balance_node_right(trans, mid, left);
1098 wret = push_node_left(trans, left, mid, 1);
1104 if (btrfs_header_nritems(mid) == 0) {
1105 btrfs_clear_buffer_dirty(trans, mid);
1106 btrfs_tree_unlock(mid);
1107 ret = btrfs_del_ptr(trans, root, path, level + 1, pslot);
1109 free_extent_buffer_stale(mid);
1113 root_sub_used_bytes(root);
1114 btrfs_free_tree_block(trans, btrfs_root_id(root), mid, 0, 1);
1115 free_extent_buffer_stale(mid);
1118 /* update the parent key to reflect our changes */
1119 struct btrfs_disk_key mid_key;
1120 btrfs_node_key(mid, &mid_key, 0);
1121 ret = btrfs_tree_mod_log_insert_key(parent, pslot,
1122 BTRFS_MOD_LOG_KEY_REPLACE);
1124 btrfs_abort_transaction(trans, ret);
1127 btrfs_set_node_key(parent, &mid_key, pslot);
1128 btrfs_mark_buffer_dirty(trans, parent);
1131 /* update the path */
1133 if (btrfs_header_nritems(left) > orig_slot) {
1134 atomic_inc(&left->refs);
1135 /* left was locked after cow */
1136 path->nodes[level] = left;
1137 path->slots[level + 1] -= 1;
1138 path->slots[level] = orig_slot;
1140 btrfs_tree_unlock(mid);
1141 free_extent_buffer(mid);
1144 orig_slot -= btrfs_header_nritems(left);
1145 path->slots[level] = orig_slot;
1148 /* double check we haven't messed things up */
1150 btrfs_node_blockptr(path->nodes[level], path->slots[level]))
1154 btrfs_tree_unlock(right);
1155 free_extent_buffer(right);
1158 if (path->nodes[level] != left)
1159 btrfs_tree_unlock(left);
1160 free_extent_buffer(left);
1165 /* Node balancing for insertion. Here we only split or push nodes around
1166 * when they are completely full. This is also done top down, so we
1167 * have to be pessimistic.
1169 static noinline int push_nodes_for_insert(struct btrfs_trans_handle *trans,
1170 struct btrfs_root *root,
1171 struct btrfs_path *path, int level)
1173 struct btrfs_fs_info *fs_info = root->fs_info;
1174 struct extent_buffer *right = NULL;
1175 struct extent_buffer *mid;
1176 struct extent_buffer *left = NULL;
1177 struct extent_buffer *parent = NULL;
1181 int orig_slot = path->slots[level];
1186 mid = path->nodes[level];
1187 WARN_ON(btrfs_header_generation(mid) != trans->transid);
1189 if (level < BTRFS_MAX_LEVEL - 1) {
1190 parent = path->nodes[level + 1];
1191 pslot = path->slots[level + 1];
1197 /* first, try to make some room in the middle buffer */
1201 left = btrfs_read_node_slot(parent, pslot - 1);
1203 return PTR_ERR(left);
1205 btrfs_tree_lock_nested(left, BTRFS_NESTING_LEFT);
1207 left_nr = btrfs_header_nritems(left);
1208 if (left_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
1211 ret = btrfs_cow_block(trans, root, left, parent,
1213 BTRFS_NESTING_LEFT_COW);
1217 wret = push_node_left(trans, left, mid, 0);
1223 struct btrfs_disk_key disk_key;
1224 orig_slot += left_nr;
1225 btrfs_node_key(mid, &disk_key, 0);
1226 ret = btrfs_tree_mod_log_insert_key(parent, pslot,
1227 BTRFS_MOD_LOG_KEY_REPLACE);
1229 btrfs_tree_unlock(left);
1230 free_extent_buffer(left);
1231 btrfs_abort_transaction(trans, ret);
1234 btrfs_set_node_key(parent, &disk_key, pslot);
1235 btrfs_mark_buffer_dirty(trans, parent);
1236 if (btrfs_header_nritems(left) > orig_slot) {
1237 path->nodes[level] = left;
1238 path->slots[level + 1] -= 1;
1239 path->slots[level] = orig_slot;
1240 btrfs_tree_unlock(mid);
1241 free_extent_buffer(mid);
1244 btrfs_header_nritems(left);
1245 path->slots[level] = orig_slot;
1246 btrfs_tree_unlock(left);
1247 free_extent_buffer(left);
1251 btrfs_tree_unlock(left);
1252 free_extent_buffer(left);
1256 * then try to empty the right most buffer into the middle
1258 if (pslot + 1 < btrfs_header_nritems(parent)) {
1261 right = btrfs_read_node_slot(parent, pslot + 1);
1263 return PTR_ERR(right);
1265 btrfs_tree_lock_nested(right, BTRFS_NESTING_RIGHT);
1267 right_nr = btrfs_header_nritems(right);
1268 if (right_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
1271 ret = btrfs_cow_block(trans, root, right,
1273 &right, BTRFS_NESTING_RIGHT_COW);
1277 wret = balance_node_right(trans, right, mid);
1283 struct btrfs_disk_key disk_key;
1285 btrfs_node_key(right, &disk_key, 0);
1286 ret = btrfs_tree_mod_log_insert_key(parent, pslot + 1,
1287 BTRFS_MOD_LOG_KEY_REPLACE);
1289 btrfs_tree_unlock(right);
1290 free_extent_buffer(right);
1291 btrfs_abort_transaction(trans, ret);
1294 btrfs_set_node_key(parent, &disk_key, pslot + 1);
1295 btrfs_mark_buffer_dirty(trans, parent);
1297 if (btrfs_header_nritems(mid) <= orig_slot) {
1298 path->nodes[level] = right;
1299 path->slots[level + 1] += 1;
1300 path->slots[level] = orig_slot -
1301 btrfs_header_nritems(mid);
1302 btrfs_tree_unlock(mid);
1303 free_extent_buffer(mid);
1305 btrfs_tree_unlock(right);
1306 free_extent_buffer(right);
1310 btrfs_tree_unlock(right);
1311 free_extent_buffer(right);
1317 * readahead one full node of leaves, finding things that are close
1318 * to the block in 'slot', and triggering ra on them.
1320 static void reada_for_search(struct btrfs_fs_info *fs_info,
1321 struct btrfs_path *path,
1322 int level, int slot, u64 objectid)
1324 struct extent_buffer *node;
1325 struct btrfs_disk_key disk_key;
1335 if (level != 1 && path->reada != READA_FORWARD_ALWAYS)
1338 if (!path->nodes[level])
1341 node = path->nodes[level];
1344 * Since the time between visiting leaves is much shorter than the time
1345 * between visiting nodes, limit read ahead of nodes to 1, to avoid too
1346 * much IO at once (possibly random).
1348 if (path->reada == READA_FORWARD_ALWAYS) {
1350 nread_max = node->fs_info->nodesize;
1352 nread_max = SZ_128K;
1357 search = btrfs_node_blockptr(node, slot);
1358 blocksize = fs_info->nodesize;
1359 if (path->reada != READA_FORWARD_ALWAYS) {
1360 struct extent_buffer *eb;
1362 eb = find_extent_buffer(fs_info, search);
1364 free_extent_buffer(eb);
1371 nritems = btrfs_header_nritems(node);
1375 if (path->reada == READA_BACK) {
1379 } else if (path->reada == READA_FORWARD ||
1380 path->reada == READA_FORWARD_ALWAYS) {
1385 if (path->reada == READA_BACK && objectid) {
1386 btrfs_node_key(node, &disk_key, nr);
1387 if (btrfs_disk_key_objectid(&disk_key) != objectid)
1390 search = btrfs_node_blockptr(node, nr);
1391 if (path->reada == READA_FORWARD_ALWAYS ||
1392 (search <= target && target - search <= 65536) ||
1393 (search > target && search - target <= 65536)) {
1394 btrfs_readahead_node_child(node, nr);
1398 if (nread > nread_max || nscan > 32)
1403 static noinline void reada_for_balance(struct btrfs_path *path, int level)
1405 struct extent_buffer *parent;
1409 parent = path->nodes[level + 1];
1413 nritems = btrfs_header_nritems(parent);
1414 slot = path->slots[level + 1];
1417 btrfs_readahead_node_child(parent, slot - 1);
1418 if (slot + 1 < nritems)
1419 btrfs_readahead_node_child(parent, slot + 1);
1424 * when we walk down the tree, it is usually safe to unlock the higher layers
1425 * in the tree. The exceptions are when our path goes through slot 0, because
1426 * operations on the tree might require changing key pointers higher up in the
1429 * callers might also have set path->keep_locks, which tells this code to keep
1430 * the lock if the path points to the last slot in the block. This is part of
1431 * walking through the tree, and selecting the next slot in the higher block.
1433 * lowest_unlock sets the lowest level in the tree we're allowed to unlock. so
1434 * if lowest_unlock is 1, level 0 won't be unlocked
1436 static noinline void unlock_up(struct btrfs_path *path, int level,
1437 int lowest_unlock, int min_write_lock_level,
1438 int *write_lock_level)
1441 int skip_level = level;
1442 bool check_skip = true;
1444 for (i = level; i < BTRFS_MAX_LEVEL; i++) {
1445 if (!path->nodes[i])
1447 if (!path->locks[i])
1451 if (path->slots[i] == 0) {
1456 if (path->keep_locks) {
1459 nritems = btrfs_header_nritems(path->nodes[i]);
1460 if (nritems < 1 || path->slots[i] >= nritems - 1) {
1467 if (i >= lowest_unlock && i > skip_level) {
1469 btrfs_tree_unlock_rw(path->nodes[i], path->locks[i]);
1471 if (write_lock_level &&
1472 i > min_write_lock_level &&
1473 i <= *write_lock_level) {
1474 *write_lock_level = i - 1;
1481 * Helper function for btrfs_search_slot() and other functions that do a search
1482 * on a btree. The goal is to find a tree block in the cache (the radix tree at
1483 * fs_info->buffer_radix), but if we can't find it, or it's not up to date, read
1484 * its pages from disk.
1486 * Returns -EAGAIN, with the path unlocked, if the caller needs to repeat the
1487 * whole btree search, starting again from the current root node.
1490 read_block_for_search(struct btrfs_root *root, struct btrfs_path *p,
1491 struct extent_buffer **eb_ret, int level, int slot,
1492 const struct btrfs_key *key)
1494 struct btrfs_fs_info *fs_info = root->fs_info;
1495 struct btrfs_tree_parent_check check = { 0 };
1498 struct extent_buffer *tmp;
1503 unlock_up = ((level + 1 < BTRFS_MAX_LEVEL) && p->locks[level + 1]);
1504 blocknr = btrfs_node_blockptr(*eb_ret, slot);
1505 gen = btrfs_node_ptr_generation(*eb_ret, slot);
1506 parent_level = btrfs_header_level(*eb_ret);
1507 btrfs_node_key_to_cpu(*eb_ret, &check.first_key, slot);
1508 check.has_first_key = true;
1509 check.level = parent_level - 1;
1510 check.transid = gen;
1511 check.owner_root = btrfs_root_id(root);
1514 * If we need to read an extent buffer from disk and we are holding locks
1515 * on upper level nodes, we unlock all the upper nodes before reading the
1516 * extent buffer, and then return -EAGAIN to the caller as it needs to
1517 * restart the search. We don't release the lock on the current level
1518 * because we need to walk this node to figure out which blocks to read.
1520 tmp = find_extent_buffer(fs_info, blocknr);
1522 if (p->reada == READA_FORWARD_ALWAYS)
1523 reada_for_search(fs_info, p, level, slot, key->objectid);
1525 /* first we do an atomic uptodate check */
1526 if (btrfs_buffer_uptodate(tmp, gen, 1) > 0) {
1528 * Do extra check for first_key, eb can be stale due to
1529 * being cached, read from scrub, or have multiple
1530 * parents (shared tree blocks).
1532 if (btrfs_verify_level_key(tmp,
1533 parent_level - 1, &check.first_key, gen)) {
1534 free_extent_buffer(tmp);
1542 free_extent_buffer(tmp);
1547 btrfs_unlock_up_safe(p, level + 1);
1549 /* now we're allowed to do a blocking uptodate check */
1550 ret = btrfs_read_extent_buffer(tmp, &check);
1552 free_extent_buffer(tmp);
1553 btrfs_release_path(p);
1556 if (btrfs_check_eb_owner(tmp, btrfs_root_id(root))) {
1557 free_extent_buffer(tmp);
1558 btrfs_release_path(p);
1566 } else if (p->nowait) {
1571 btrfs_unlock_up_safe(p, level + 1);
1577 if (p->reada != READA_NONE)
1578 reada_for_search(fs_info, p, level, slot, key->objectid);
1580 tmp = read_tree_block(fs_info, blocknr, &check);
1582 btrfs_release_path(p);
1583 return PTR_ERR(tmp);
1586 * If the read above didn't mark this buffer up to date,
1587 * it will never end up being up to date. Set ret to EIO now
1588 * and give up so that our caller doesn't loop forever
1591 if (!extent_buffer_uptodate(tmp))
1598 free_extent_buffer(tmp);
1599 btrfs_release_path(p);
1606 * helper function for btrfs_search_slot. This does all of the checks
1607 * for node-level blocks and does any balancing required based on
1610 * If no extra work was required, zero is returned. If we had to
1611 * drop the path, -EAGAIN is returned and btrfs_search_slot must
1615 setup_nodes_for_search(struct btrfs_trans_handle *trans,
1616 struct btrfs_root *root, struct btrfs_path *p,
1617 struct extent_buffer *b, int level, int ins_len,
1618 int *write_lock_level)
1620 struct btrfs_fs_info *fs_info = root->fs_info;
1623 if ((p->search_for_split || ins_len > 0) && btrfs_header_nritems(b) >=
1624 BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3) {
1626 if (*write_lock_level < level + 1) {
1627 *write_lock_level = level + 1;
1628 btrfs_release_path(p);
1632 reada_for_balance(p, level);
1633 ret = split_node(trans, root, p, level);
1635 b = p->nodes[level];
1636 } else if (ins_len < 0 && btrfs_header_nritems(b) <
1637 BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 2) {
1639 if (*write_lock_level < level + 1) {
1640 *write_lock_level = level + 1;
1641 btrfs_release_path(p);
1645 reada_for_balance(p, level);
1646 ret = balance_level(trans, root, p, level);
1650 b = p->nodes[level];
1652 btrfs_release_path(p);
1655 BUG_ON(btrfs_header_nritems(b) == 1);
1660 int btrfs_find_item(struct btrfs_root *fs_root, struct btrfs_path *path,
1661 u64 iobjectid, u64 ioff, u8 key_type,
1662 struct btrfs_key *found_key)
1665 struct btrfs_key key;
1666 struct extent_buffer *eb;
1671 key.type = key_type;
1672 key.objectid = iobjectid;
1675 ret = btrfs_search_slot(NULL, fs_root, &key, path, 0, 0);
1679 eb = path->nodes[0];
1680 if (ret && path->slots[0] >= btrfs_header_nritems(eb)) {
1681 ret = btrfs_next_leaf(fs_root, path);
1684 eb = path->nodes[0];
1687 btrfs_item_key_to_cpu(eb, found_key, path->slots[0]);
1688 if (found_key->type != key.type ||
1689 found_key->objectid != key.objectid)
1695 static struct extent_buffer *btrfs_search_slot_get_root(struct btrfs_root *root,
1696 struct btrfs_path *p,
1697 int write_lock_level)
1699 struct extent_buffer *b;
1703 if (p->search_commit_root) {
1704 b = root->commit_root;
1705 atomic_inc(&b->refs);
1706 level = btrfs_header_level(b);
1708 * Ensure that all callers have set skip_locking when
1709 * p->search_commit_root = 1.
1711 ASSERT(p->skip_locking == 1);
1716 if (p->skip_locking) {
1717 b = btrfs_root_node(root);
1718 level = btrfs_header_level(b);
1722 /* We try very hard to do read locks on the root */
1723 root_lock = BTRFS_READ_LOCK;
1726 * If the level is set to maximum, we can skip trying to get the read
1729 if (write_lock_level < BTRFS_MAX_LEVEL) {
1731 * We don't know the level of the root node until we actually
1732 * have it read locked
1735 b = btrfs_try_read_lock_root_node(root);
1739 b = btrfs_read_lock_root_node(root);
1741 level = btrfs_header_level(b);
1742 if (level > write_lock_level)
1745 /* Whoops, must trade for write lock */
1746 btrfs_tree_read_unlock(b);
1747 free_extent_buffer(b);
1750 b = btrfs_lock_root_node(root);
1751 root_lock = BTRFS_WRITE_LOCK;
1753 /* The level might have changed, check again */
1754 level = btrfs_header_level(b);
1758 * The root may have failed to write out at some point, and thus is no
1759 * longer valid, return an error in this case.
1761 if (!extent_buffer_uptodate(b)) {
1763 btrfs_tree_unlock_rw(b, root_lock);
1764 free_extent_buffer(b);
1765 return ERR_PTR(-EIO);
1768 p->nodes[level] = b;
1769 if (!p->skip_locking)
1770 p->locks[level] = root_lock;
1772 * Callers are responsible for dropping b's references.
1778 * Replace the extent buffer at the lowest level of the path with a cloned
1779 * version. The purpose is to be able to use it safely, after releasing the
1780 * commit root semaphore, even if relocation is happening in parallel, the
1781 * transaction used for relocation is committed and the extent buffer is
1782 * reallocated in the next transaction.
1784 * This is used in a context where the caller does not prevent transaction
1785 * commits from happening, either by holding a transaction handle or holding
1786 * some lock, while it's doing searches through a commit root.
1787 * At the moment it's only used for send operations.
1789 static int finish_need_commit_sem_search(struct btrfs_path *path)
1791 const int i = path->lowest_level;
1792 const int slot = path->slots[i];
1793 struct extent_buffer *lowest = path->nodes[i];
1794 struct extent_buffer *clone;
1796 ASSERT(path->need_commit_sem);
1801 lockdep_assert_held_read(&lowest->fs_info->commit_root_sem);
1803 clone = btrfs_clone_extent_buffer(lowest);
1807 btrfs_release_path(path);
1808 path->nodes[i] = clone;
1809 path->slots[i] = slot;
1814 static inline int search_for_key_slot(struct extent_buffer *eb,
1815 int search_low_slot,
1816 const struct btrfs_key *key,
1821 * If a previous call to btrfs_bin_search() on a parent node returned an
1822 * exact match (prev_cmp == 0), we can safely assume the target key will
1823 * always be at slot 0 on lower levels, since each key pointer
1824 * (struct btrfs_key_ptr) refers to the lowest key accessible from the
1825 * subtree it points to. Thus we can skip searching lower levels.
1827 if (prev_cmp == 0) {
1832 return btrfs_bin_search(eb, search_low_slot, key, slot);
1835 static int search_leaf(struct btrfs_trans_handle *trans,
1836 struct btrfs_root *root,
1837 const struct btrfs_key *key,
1838 struct btrfs_path *path,
1842 struct extent_buffer *leaf = path->nodes[0];
1843 int leaf_free_space = -1;
1844 int search_low_slot = 0;
1846 bool do_bin_search = true;
1849 * If we are doing an insertion, the leaf has enough free space and the
1850 * destination slot for the key is not slot 0, then we can unlock our
1851 * write lock on the parent, and any other upper nodes, before doing the
1852 * binary search on the leaf (with search_for_key_slot()), allowing other
1853 * tasks to lock the parent and any other upper nodes.
1857 * Cache the leaf free space, since we will need it later and it
1858 * will not change until then.
1860 leaf_free_space = btrfs_leaf_free_space(leaf);
1863 * !path->locks[1] means we have a single node tree, the leaf is
1864 * the root of the tree.
1866 if (path->locks[1] && leaf_free_space >= ins_len) {
1867 struct btrfs_disk_key first_key;
1869 ASSERT(btrfs_header_nritems(leaf) > 0);
1870 btrfs_item_key(leaf, &first_key, 0);
1873 * Doing the extra comparison with the first key is cheap,
1874 * taking into account that the first key is very likely
1875 * already in a cache line because it immediately follows
1876 * the extent buffer's header and we have recently accessed
1877 * the header's level field.
1879 ret = btrfs_comp_keys(&first_key, key);
1882 * The first key is smaller than the key we want
1883 * to insert, so we are safe to unlock all upper
1884 * nodes and we have to do the binary search.
1886 * We do use btrfs_unlock_up_safe() and not
1887 * unlock_up() because the later does not unlock
1888 * nodes with a slot of 0 - we can safely unlock
1889 * any node even if its slot is 0 since in this
1890 * case the key does not end up at slot 0 of the
1891 * leaf and there's no need to split the leaf.
1893 btrfs_unlock_up_safe(path, 1);
1894 search_low_slot = 1;
1897 * The first key is >= then the key we want to
1898 * insert, so we can skip the binary search as
1899 * the target key will be at slot 0.
1901 * We can not unlock upper nodes when the key is
1902 * less than the first key, because we will need
1903 * to update the key at slot 0 of the parent node
1904 * and possibly of other upper nodes too.
1905 * If the key matches the first key, then we can
1906 * unlock all the upper nodes, using
1907 * btrfs_unlock_up_safe() instead of unlock_up()
1911 btrfs_unlock_up_safe(path, 1);
1913 * ret is already 0 or 1, matching the result of
1914 * a btrfs_bin_search() call, so there is no need
1917 do_bin_search = false;
1923 if (do_bin_search) {
1924 ret = search_for_key_slot(leaf, search_low_slot, key,
1925 prev_cmp, &path->slots[0]);
1932 * Item key already exists. In this case, if we are allowed to
1933 * insert the item (for example, in dir_item case, item key
1934 * collision is allowed), it will be merged with the original
1935 * item. Only the item size grows, no new btrfs item will be
1936 * added. If search_for_extension is not set, ins_len already
1937 * accounts the size btrfs_item, deduct it here so leaf space
1938 * check will be correct.
1940 if (ret == 0 && !path->search_for_extension) {
1941 ASSERT(ins_len >= sizeof(struct btrfs_item));
1942 ins_len -= sizeof(struct btrfs_item);
1945 ASSERT(leaf_free_space >= 0);
1947 if (leaf_free_space < ins_len) {
1950 err = split_leaf(trans, root, key, path, ins_len,
1953 if (WARN_ON(err > 0))
1964 * Look for a key in a tree and perform necessary modifications to preserve
1967 * @trans: Handle of transaction, used when modifying the tree
1968 * @p: Holds all btree nodes along the search path
1969 * @root: The root node of the tree
1970 * @key: The key we are looking for
1971 * @ins_len: Indicates purpose of search:
1972 * >0 for inserts it's size of item inserted (*)
1974 * 0 for plain searches, not modifying the tree
1976 * (*) If size of item inserted doesn't include
1977 * sizeof(struct btrfs_item), then p->search_for_extension must
1979 * @cow: boolean should CoW operations be performed. Must always be 1
1980 * when modifying the tree.
1982 * If @ins_len > 0, nodes and leaves will be split as we walk down the tree.
1983 * If @ins_len < 0, nodes will be merged as we walk down the tree (if possible)
1985 * If @key is found, 0 is returned and you can find the item in the leaf level
1986 * of the path (level 0)
1988 * If @key isn't found, 1 is returned and the leaf level of the path (level 0)
1989 * points to the slot where it should be inserted
1991 * If an error is encountered while searching the tree a negative error number
1994 int btrfs_search_slot(struct btrfs_trans_handle *trans, struct btrfs_root *root,
1995 const struct btrfs_key *key, struct btrfs_path *p,
1996 int ins_len, int cow)
1998 struct btrfs_fs_info *fs_info = root->fs_info;
1999 struct extent_buffer *b;
2004 int lowest_unlock = 1;
2005 /* everything at write_lock_level or lower must be write locked */
2006 int write_lock_level = 0;
2007 u8 lowest_level = 0;
2008 int min_write_lock_level;
2013 lowest_level = p->lowest_level;
2014 WARN_ON(lowest_level && ins_len > 0);
2015 WARN_ON(p->nodes[0] != NULL);
2016 BUG_ON(!cow && ins_len);
2019 * For now only allow nowait for read only operations. There's no
2020 * strict reason why we can't, we just only need it for reads so it's
2021 * only implemented for reads.
2023 ASSERT(!p->nowait || !cow);
2028 /* when we are removing items, we might have to go up to level
2029 * two as we update tree pointers Make sure we keep write
2030 * for those levels as well
2032 write_lock_level = 2;
2033 } else if (ins_len > 0) {
2035 * for inserting items, make sure we have a write lock on
2036 * level 1 so we can update keys
2038 write_lock_level = 1;
2042 write_lock_level = -1;
2044 if (cow && (p->keep_locks || p->lowest_level))
2045 write_lock_level = BTRFS_MAX_LEVEL;
2047 min_write_lock_level = write_lock_level;
2049 if (p->need_commit_sem) {
2050 ASSERT(p->search_commit_root);
2052 if (!down_read_trylock(&fs_info->commit_root_sem))
2055 down_read(&fs_info->commit_root_sem);
2061 b = btrfs_search_slot_get_root(root, p, write_lock_level);
2070 level = btrfs_header_level(b);
2073 bool last_level = (level == (BTRFS_MAX_LEVEL - 1));
2076 * if we don't really need to cow this block
2077 * then we don't want to set the path blocking,
2078 * so we test it here
2080 if (!should_cow_block(trans, root, b))
2084 * must have write locks on this node and the
2087 if (level > write_lock_level ||
2088 (level + 1 > write_lock_level &&
2089 level + 1 < BTRFS_MAX_LEVEL &&
2090 p->nodes[level + 1])) {
2091 write_lock_level = level + 1;
2092 btrfs_release_path(p);
2097 err = btrfs_cow_block(trans, root, b, NULL, 0,
2101 err = btrfs_cow_block(trans, root, b,
2102 p->nodes[level + 1],
2103 p->slots[level + 1], &b,
2111 p->nodes[level] = b;
2114 * we have a lock on b and as long as we aren't changing
2115 * the tree, there is no way to for the items in b to change.
2116 * It is safe to drop the lock on our parent before we
2117 * go through the expensive btree search on b.
2119 * If we're inserting or deleting (ins_len != 0), then we might
2120 * be changing slot zero, which may require changing the parent.
2121 * So, we can't drop the lock until after we know which slot
2122 * we're operating on.
2124 if (!ins_len && !p->keep_locks) {
2127 if (u < BTRFS_MAX_LEVEL && p->locks[u]) {
2128 btrfs_tree_unlock_rw(p->nodes[u], p->locks[u]);
2135 ASSERT(write_lock_level >= 1);
2137 ret = search_leaf(trans, root, key, p, ins_len, prev_cmp);
2138 if (!p->search_for_split)
2139 unlock_up(p, level, lowest_unlock,
2140 min_write_lock_level, NULL);
2144 ret = search_for_key_slot(b, 0, key, prev_cmp, &slot);
2149 if (ret && slot > 0) {
2153 p->slots[level] = slot;
2154 err = setup_nodes_for_search(trans, root, p, b, level, ins_len,
2162 b = p->nodes[level];
2163 slot = p->slots[level];
2166 * Slot 0 is special, if we change the key we have to update
2167 * the parent pointer which means we must have a write lock on
2170 if (slot == 0 && ins_len && write_lock_level < level + 1) {
2171 write_lock_level = level + 1;
2172 btrfs_release_path(p);
2176 unlock_up(p, level, lowest_unlock, min_write_lock_level,
2179 if (level == lowest_level) {
2185 err = read_block_for_search(root, p, &b, level, slot, key);
2193 if (!p->skip_locking) {
2194 level = btrfs_header_level(b);
2196 btrfs_maybe_reset_lockdep_class(root, b);
2198 if (level <= write_lock_level) {
2200 p->locks[level] = BTRFS_WRITE_LOCK;
2203 if (!btrfs_try_tree_read_lock(b)) {
2204 free_extent_buffer(b);
2209 btrfs_tree_read_lock(b);
2211 p->locks[level] = BTRFS_READ_LOCK;
2213 p->nodes[level] = b;
2218 if (ret < 0 && !p->skip_release_on_error)
2219 btrfs_release_path(p);
2221 if (p->need_commit_sem) {
2224 ret2 = finish_need_commit_sem_search(p);
2225 up_read(&fs_info->commit_root_sem);
2232 ALLOW_ERROR_INJECTION(btrfs_search_slot, ERRNO);
2235 * Like btrfs_search_slot, this looks for a key in the given tree. It uses the
2236 * current state of the tree together with the operations recorded in the tree
2237 * modification log to search for the key in a previous version of this tree, as
2238 * denoted by the time_seq parameter.
2240 * Naturally, there is no support for insert, delete or cow operations.
2242 * The resulting path and return value will be set up as if we called
2243 * btrfs_search_slot at that point in time with ins_len and cow both set to 0.
2245 int btrfs_search_old_slot(struct btrfs_root *root, const struct btrfs_key *key,
2246 struct btrfs_path *p, u64 time_seq)
2248 struct btrfs_fs_info *fs_info = root->fs_info;
2249 struct extent_buffer *b;
2254 int lowest_unlock = 1;
2255 u8 lowest_level = 0;
2257 lowest_level = p->lowest_level;
2258 WARN_ON(p->nodes[0] != NULL);
2261 if (p->search_commit_root) {
2263 return btrfs_search_slot(NULL, root, key, p, 0, 0);
2267 b = btrfs_get_old_root(root, time_seq);
2272 level = btrfs_header_level(b);
2273 p->locks[level] = BTRFS_READ_LOCK;
2278 level = btrfs_header_level(b);
2279 p->nodes[level] = b;
2282 * we have a lock on b and as long as we aren't changing
2283 * the tree, there is no way to for the items in b to change.
2284 * It is safe to drop the lock on our parent before we
2285 * go through the expensive btree search on b.
2287 btrfs_unlock_up_safe(p, level + 1);
2289 ret = btrfs_bin_search(b, 0, key, &slot);
2294 p->slots[level] = slot;
2295 unlock_up(p, level, lowest_unlock, 0, NULL);
2299 if (ret && slot > 0) {
2303 p->slots[level] = slot;
2304 unlock_up(p, level, lowest_unlock, 0, NULL);
2306 if (level == lowest_level) {
2312 err = read_block_for_search(root, p, &b, level, slot, key);
2320 level = btrfs_header_level(b);
2321 btrfs_tree_read_lock(b);
2322 b = btrfs_tree_mod_log_rewind(fs_info, p, b, time_seq);
2327 p->locks[level] = BTRFS_READ_LOCK;
2328 p->nodes[level] = b;
2333 btrfs_release_path(p);
2339 * Search the tree again to find a leaf with smaller keys.
2340 * Returns 0 if it found something.
2341 * Returns 1 if there are no smaller keys.
2342 * Returns < 0 on error.
2344 * This may release the path, and so you may lose any locks held at the
2347 static int btrfs_prev_leaf(struct btrfs_root *root, struct btrfs_path *path)
2349 struct btrfs_key key;
2350 struct btrfs_key orig_key;
2351 struct btrfs_disk_key found_key;
2354 btrfs_item_key_to_cpu(path->nodes[0], &key, 0);
2357 if (key.offset > 0) {
2359 } else if (key.type > 0) {
2361 key.offset = (u64)-1;
2362 } else if (key.objectid > 0) {
2365 key.offset = (u64)-1;
2370 btrfs_release_path(path);
2371 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2376 * Previous key not found. Even if we were at slot 0 of the leaf we had
2377 * before releasing the path and calling btrfs_search_slot(), we now may
2378 * be in a slot pointing to the same original key - this can happen if
2379 * after we released the path, one of more items were moved from a
2380 * sibling leaf into the front of the leaf we had due to an insertion
2381 * (see push_leaf_right()).
2382 * If we hit this case and our slot is > 0 and just decrement the slot
2383 * so that the caller does not process the same key again, which may or
2384 * may not break the caller, depending on its logic.
2386 if (path->slots[0] < btrfs_header_nritems(path->nodes[0])) {
2387 btrfs_item_key(path->nodes[0], &found_key, path->slots[0]);
2388 ret = btrfs_comp_keys(&found_key, &orig_key);
2390 if (path->slots[0] > 0) {
2395 * At slot 0, same key as before, it means orig_key is
2396 * the lowest, leftmost, key in the tree. We're done.
2402 btrfs_item_key(path->nodes[0], &found_key, 0);
2403 ret = btrfs_comp_keys(&found_key, &key);
2405 * We might have had an item with the previous key in the tree right
2406 * before we released our path. And after we released our path, that
2407 * item might have been pushed to the first slot (0) of the leaf we
2408 * were holding due to a tree balance. Alternatively, an item with the
2409 * previous key can exist as the only element of a leaf (big fat item).
2410 * Therefore account for these 2 cases, so that our callers (like
2411 * btrfs_previous_item) don't miss an existing item with a key matching
2412 * the previous key we computed above.
2420 * helper to use instead of search slot if no exact match is needed but
2421 * instead the next or previous item should be returned.
2422 * When find_higher is true, the next higher item is returned, the next lower
2424 * When return_any and find_higher are both true, and no higher item is found,
2425 * return the next lower instead.
2426 * When return_any is true and find_higher is false, and no lower item is found,
2427 * return the next higher instead.
2428 * It returns 0 if any item is found, 1 if none is found (tree empty), and
2431 int btrfs_search_slot_for_read(struct btrfs_root *root,
2432 const struct btrfs_key *key,
2433 struct btrfs_path *p, int find_higher,
2437 struct extent_buffer *leaf;
2440 ret = btrfs_search_slot(NULL, root, key, p, 0, 0);
2444 * a return value of 1 means the path is at the position where the
2445 * item should be inserted. Normally this is the next bigger item,
2446 * but in case the previous item is the last in a leaf, path points
2447 * to the first free slot in the previous leaf, i.e. at an invalid
2453 if (p->slots[0] >= btrfs_header_nritems(leaf)) {
2454 ret = btrfs_next_leaf(root, p);
2460 * no higher item found, return the next
2465 btrfs_release_path(p);
2469 if (p->slots[0] == 0) {
2470 ret = btrfs_prev_leaf(root, p);
2475 if (p->slots[0] == btrfs_header_nritems(leaf))
2482 * no lower item found, return the next
2487 btrfs_release_path(p);
2497 * Execute search and call btrfs_previous_item to traverse backwards if the item
2500 * Return 0 if found, 1 if not found and < 0 if error.
2502 int btrfs_search_backwards(struct btrfs_root *root, struct btrfs_key *key,
2503 struct btrfs_path *path)
2507 ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
2509 ret = btrfs_previous_item(root, path, key->objectid, key->type);
2512 btrfs_item_key_to_cpu(path->nodes[0], key, path->slots[0]);
2518 * Search for a valid slot for the given path.
2520 * @root: The root node of the tree.
2521 * @key: Will contain a valid item if found.
2522 * @path: The starting point to validate the slot.
2524 * Return: 0 if the item is valid
2528 int btrfs_get_next_valid_item(struct btrfs_root *root, struct btrfs_key *key,
2529 struct btrfs_path *path)
2531 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
2534 ret = btrfs_next_leaf(root, path);
2539 btrfs_item_key_to_cpu(path->nodes[0], key, path->slots[0]);
2544 * adjust the pointers going up the tree, starting at level
2545 * making sure the right key of each node is points to 'key'.
2546 * This is used after shifting pointers to the left, so it stops
2547 * fixing up pointers when a given leaf/node is not in slot 0 of the
2551 static void fixup_low_keys(struct btrfs_trans_handle *trans,
2552 struct btrfs_path *path,
2553 struct btrfs_disk_key *key, int level)
2556 struct extent_buffer *t;
2559 for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2560 int tslot = path->slots[i];
2562 if (!path->nodes[i])
2565 ret = btrfs_tree_mod_log_insert_key(t, tslot,
2566 BTRFS_MOD_LOG_KEY_REPLACE);
2568 btrfs_set_node_key(t, key, tslot);
2569 btrfs_mark_buffer_dirty(trans, path->nodes[i]);
2578 * This function isn't completely safe. It's the caller's responsibility
2579 * that the new key won't break the order
2581 void btrfs_set_item_key_safe(struct btrfs_trans_handle *trans,
2582 struct btrfs_path *path,
2583 const struct btrfs_key *new_key)
2585 struct btrfs_fs_info *fs_info = trans->fs_info;
2586 struct btrfs_disk_key disk_key;
2587 struct extent_buffer *eb;
2590 eb = path->nodes[0];
2591 slot = path->slots[0];
2593 btrfs_item_key(eb, &disk_key, slot - 1);
2594 if (unlikely(btrfs_comp_keys(&disk_key, new_key) >= 0)) {
2595 btrfs_print_leaf(eb);
2597 "slot %u key (%llu %u %llu) new key (%llu %u %llu)",
2598 slot, btrfs_disk_key_objectid(&disk_key),
2599 btrfs_disk_key_type(&disk_key),
2600 btrfs_disk_key_offset(&disk_key),
2601 new_key->objectid, new_key->type,
2606 if (slot < btrfs_header_nritems(eb) - 1) {
2607 btrfs_item_key(eb, &disk_key, slot + 1);
2608 if (unlikely(btrfs_comp_keys(&disk_key, new_key) <= 0)) {
2609 btrfs_print_leaf(eb);
2611 "slot %u key (%llu %u %llu) new key (%llu %u %llu)",
2612 slot, btrfs_disk_key_objectid(&disk_key),
2613 btrfs_disk_key_type(&disk_key),
2614 btrfs_disk_key_offset(&disk_key),
2615 new_key->objectid, new_key->type,
2621 btrfs_cpu_key_to_disk(&disk_key, new_key);
2622 btrfs_set_item_key(eb, &disk_key, slot);
2623 btrfs_mark_buffer_dirty(trans, eb);
2625 fixup_low_keys(trans, path, &disk_key, 1);
2629 * Check key order of two sibling extent buffers.
2631 * Return true if something is wrong.
2632 * Return false if everything is fine.
2634 * Tree-checker only works inside one tree block, thus the following
2635 * corruption can not be detected by tree-checker:
2637 * Leaf @left | Leaf @right
2638 * --------------------------------------------------------------
2639 * | 1 | 2 | 3 | 4 | 5 | f6 | | 7 | 8 |
2641 * Key f6 in leaf @left itself is valid, but not valid when the next
2642 * key in leaf @right is 7.
2643 * This can only be checked at tree block merge time.
2644 * And since tree checker has ensured all key order in each tree block
2645 * is correct, we only need to bother the last key of @left and the first
2648 static bool check_sibling_keys(struct extent_buffer *left,
2649 struct extent_buffer *right)
2651 struct btrfs_key left_last;
2652 struct btrfs_key right_first;
2653 int level = btrfs_header_level(left);
2654 int nr_left = btrfs_header_nritems(left);
2655 int nr_right = btrfs_header_nritems(right);
2657 /* No key to check in one of the tree blocks */
2658 if (!nr_left || !nr_right)
2662 btrfs_node_key_to_cpu(left, &left_last, nr_left - 1);
2663 btrfs_node_key_to_cpu(right, &right_first, 0);
2665 btrfs_item_key_to_cpu(left, &left_last, nr_left - 1);
2666 btrfs_item_key_to_cpu(right, &right_first, 0);
2669 if (unlikely(btrfs_comp_cpu_keys(&left_last, &right_first) >= 0)) {
2670 btrfs_crit(left->fs_info, "left extent buffer:");
2671 btrfs_print_tree(left, false);
2672 btrfs_crit(left->fs_info, "right extent buffer:");
2673 btrfs_print_tree(right, false);
2674 btrfs_crit(left->fs_info,
2675 "bad key order, sibling blocks, left last (%llu %u %llu) right first (%llu %u %llu)",
2676 left_last.objectid, left_last.type,
2677 left_last.offset, right_first.objectid,
2678 right_first.type, right_first.offset);
2685 * try to push data from one node into the next node left in the
2688 * returns 0 if some ptrs were pushed left, < 0 if there was some horrible
2689 * error, and > 0 if there was no room in the left hand block.
2691 static int push_node_left(struct btrfs_trans_handle *trans,
2692 struct extent_buffer *dst,
2693 struct extent_buffer *src, int empty)
2695 struct btrfs_fs_info *fs_info = trans->fs_info;
2701 src_nritems = btrfs_header_nritems(src);
2702 dst_nritems = btrfs_header_nritems(dst);
2703 push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
2704 WARN_ON(btrfs_header_generation(src) != trans->transid);
2705 WARN_ON(btrfs_header_generation(dst) != trans->transid);
2707 if (!empty && src_nritems <= 8)
2710 if (push_items <= 0)
2714 push_items = min(src_nritems, push_items);
2715 if (push_items < src_nritems) {
2716 /* leave at least 8 pointers in the node if
2717 * we aren't going to empty it
2719 if (src_nritems - push_items < 8) {
2720 if (push_items <= 8)
2726 push_items = min(src_nritems - 8, push_items);
2728 /* dst is the left eb, src is the middle eb */
2729 if (check_sibling_keys(dst, src)) {
2731 btrfs_abort_transaction(trans, ret);
2734 ret = btrfs_tree_mod_log_eb_copy(dst, src, dst_nritems, 0, push_items);
2736 btrfs_abort_transaction(trans, ret);
2739 copy_extent_buffer(dst, src,
2740 btrfs_node_key_ptr_offset(dst, dst_nritems),
2741 btrfs_node_key_ptr_offset(src, 0),
2742 push_items * sizeof(struct btrfs_key_ptr));
2744 if (push_items < src_nritems) {
2746 * btrfs_tree_mod_log_eb_copy handles logging the move, so we
2747 * don't need to do an explicit tree mod log operation for it.
2749 memmove_extent_buffer(src, btrfs_node_key_ptr_offset(src, 0),
2750 btrfs_node_key_ptr_offset(src, push_items),
2751 (src_nritems - push_items) *
2752 sizeof(struct btrfs_key_ptr));
2754 btrfs_set_header_nritems(src, src_nritems - push_items);
2755 btrfs_set_header_nritems(dst, dst_nritems + push_items);
2756 btrfs_mark_buffer_dirty(trans, src);
2757 btrfs_mark_buffer_dirty(trans, dst);
2763 * try to push data from one node into the next node right in the
2766 * returns 0 if some ptrs were pushed, < 0 if there was some horrible
2767 * error, and > 0 if there was no room in the right hand block.
2769 * this will only push up to 1/2 the contents of the left node over
2771 static int balance_node_right(struct btrfs_trans_handle *trans,
2772 struct extent_buffer *dst,
2773 struct extent_buffer *src)
2775 struct btrfs_fs_info *fs_info = trans->fs_info;
2782 WARN_ON(btrfs_header_generation(src) != trans->transid);
2783 WARN_ON(btrfs_header_generation(dst) != trans->transid);
2785 src_nritems = btrfs_header_nritems(src);
2786 dst_nritems = btrfs_header_nritems(dst);
2787 push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
2788 if (push_items <= 0)
2791 if (src_nritems < 4)
2794 max_push = src_nritems / 2 + 1;
2795 /* don't try to empty the node */
2796 if (max_push >= src_nritems)
2799 if (max_push < push_items)
2800 push_items = max_push;
2802 /* dst is the right eb, src is the middle eb */
2803 if (check_sibling_keys(src, dst)) {
2805 btrfs_abort_transaction(trans, ret);
2810 * btrfs_tree_mod_log_eb_copy handles logging the move, so we don't
2811 * need to do an explicit tree mod log operation for it.
2813 memmove_extent_buffer(dst, btrfs_node_key_ptr_offset(dst, push_items),
2814 btrfs_node_key_ptr_offset(dst, 0),
2816 sizeof(struct btrfs_key_ptr));
2818 ret = btrfs_tree_mod_log_eb_copy(dst, src, 0, src_nritems - push_items,
2821 btrfs_abort_transaction(trans, ret);
2824 copy_extent_buffer(dst, src,
2825 btrfs_node_key_ptr_offset(dst, 0),
2826 btrfs_node_key_ptr_offset(src, src_nritems - push_items),
2827 push_items * sizeof(struct btrfs_key_ptr));
2829 btrfs_set_header_nritems(src, src_nritems - push_items);
2830 btrfs_set_header_nritems(dst, dst_nritems + push_items);
2832 btrfs_mark_buffer_dirty(trans, src);
2833 btrfs_mark_buffer_dirty(trans, dst);
2839 * helper function to insert a new root level in the tree.
2840 * A new node is allocated, and a single item is inserted to
2841 * point to the existing root
2843 * returns zero on success or < 0 on failure.
2845 static noinline int insert_new_root(struct btrfs_trans_handle *trans,
2846 struct btrfs_root *root,
2847 struct btrfs_path *path, int level)
2850 struct extent_buffer *lower;
2851 struct extent_buffer *c;
2852 struct extent_buffer *old;
2853 struct btrfs_disk_key lower_key;
2856 BUG_ON(path->nodes[level]);
2857 BUG_ON(path->nodes[level-1] != root->node);
2859 lower = path->nodes[level-1];
2861 btrfs_item_key(lower, &lower_key, 0);
2863 btrfs_node_key(lower, &lower_key, 0);
2865 c = btrfs_alloc_tree_block(trans, root, 0, btrfs_root_id(root),
2866 &lower_key, level, root->node->start, 0,
2867 0, BTRFS_NESTING_NEW_ROOT);
2871 root_add_used_bytes(root);
2873 btrfs_set_header_nritems(c, 1);
2874 btrfs_set_node_key(c, &lower_key, 0);
2875 btrfs_set_node_blockptr(c, 0, lower->start);
2876 lower_gen = btrfs_header_generation(lower);
2877 WARN_ON(lower_gen != trans->transid);
2879 btrfs_set_node_ptr_generation(c, 0, lower_gen);
2881 btrfs_mark_buffer_dirty(trans, c);
2884 ret = btrfs_tree_mod_log_insert_root(root->node, c, false);
2886 btrfs_free_tree_block(trans, btrfs_root_id(root), c, 0, 1);
2887 btrfs_tree_unlock(c);
2888 free_extent_buffer(c);
2891 rcu_assign_pointer(root->node, c);
2893 /* the super has an extra ref to root->node */
2894 free_extent_buffer(old);
2896 add_root_to_dirty_list(root);
2897 atomic_inc(&c->refs);
2898 path->nodes[level] = c;
2899 path->locks[level] = BTRFS_WRITE_LOCK;
2900 path->slots[level] = 0;
2905 * worker function to insert a single pointer in a node.
2906 * the node should have enough room for the pointer already
2908 * slot and level indicate where you want the key to go, and
2909 * blocknr is the block the key points to.
2911 static int insert_ptr(struct btrfs_trans_handle *trans,
2912 struct btrfs_path *path,
2913 struct btrfs_disk_key *key, u64 bytenr,
2914 int slot, int level)
2916 struct extent_buffer *lower;
2920 BUG_ON(!path->nodes[level]);
2921 btrfs_assert_tree_write_locked(path->nodes[level]);
2922 lower = path->nodes[level];
2923 nritems = btrfs_header_nritems(lower);
2924 BUG_ON(slot > nritems);
2925 BUG_ON(nritems == BTRFS_NODEPTRS_PER_BLOCK(trans->fs_info));
2926 if (slot != nritems) {
2928 ret = btrfs_tree_mod_log_insert_move(lower, slot + 1,
2929 slot, nritems - slot);
2931 btrfs_abort_transaction(trans, ret);
2935 memmove_extent_buffer(lower,
2936 btrfs_node_key_ptr_offset(lower, slot + 1),
2937 btrfs_node_key_ptr_offset(lower, slot),
2938 (nritems - slot) * sizeof(struct btrfs_key_ptr));
2941 ret = btrfs_tree_mod_log_insert_key(lower, slot,
2942 BTRFS_MOD_LOG_KEY_ADD);
2944 btrfs_abort_transaction(trans, ret);
2948 btrfs_set_node_key(lower, key, slot);
2949 btrfs_set_node_blockptr(lower, slot, bytenr);
2950 WARN_ON(trans->transid == 0);
2951 btrfs_set_node_ptr_generation(lower, slot, trans->transid);
2952 btrfs_set_header_nritems(lower, nritems + 1);
2953 btrfs_mark_buffer_dirty(trans, lower);
2959 * split the node at the specified level in path in two.
2960 * The path is corrected to point to the appropriate node after the split
2962 * Before splitting this tries to make some room in the node by pushing
2963 * left and right, if either one works, it returns right away.
2965 * returns 0 on success and < 0 on failure
2967 static noinline int split_node(struct btrfs_trans_handle *trans,
2968 struct btrfs_root *root,
2969 struct btrfs_path *path, int level)
2971 struct btrfs_fs_info *fs_info = root->fs_info;
2972 struct extent_buffer *c;
2973 struct extent_buffer *split;
2974 struct btrfs_disk_key disk_key;
2979 c = path->nodes[level];
2980 WARN_ON(btrfs_header_generation(c) != trans->transid);
2981 if (c == root->node) {
2983 * trying to split the root, lets make a new one
2985 * tree mod log: We don't log_removal old root in
2986 * insert_new_root, because that root buffer will be kept as a
2987 * normal node. We are going to log removal of half of the
2988 * elements below with btrfs_tree_mod_log_eb_copy(). We're
2989 * holding a tree lock on the buffer, which is why we cannot
2990 * race with other tree_mod_log users.
2992 ret = insert_new_root(trans, root, path, level + 1);
2996 ret = push_nodes_for_insert(trans, root, path, level);
2997 c = path->nodes[level];
2998 if (!ret && btrfs_header_nritems(c) <
2999 BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3)
3005 c_nritems = btrfs_header_nritems(c);
3006 mid = (c_nritems + 1) / 2;
3007 btrfs_node_key(c, &disk_key, mid);
3009 split = btrfs_alloc_tree_block(trans, root, 0, btrfs_root_id(root),
3010 &disk_key, level, c->start, 0,
3011 0, BTRFS_NESTING_SPLIT);
3013 return PTR_ERR(split);
3015 root_add_used_bytes(root);
3016 ASSERT(btrfs_header_level(c) == level);
3018 ret = btrfs_tree_mod_log_eb_copy(split, c, 0, mid, c_nritems - mid);
3020 btrfs_tree_unlock(split);
3021 free_extent_buffer(split);
3022 btrfs_abort_transaction(trans, ret);
3025 copy_extent_buffer(split, c,
3026 btrfs_node_key_ptr_offset(split, 0),
3027 btrfs_node_key_ptr_offset(c, mid),
3028 (c_nritems - mid) * sizeof(struct btrfs_key_ptr));
3029 btrfs_set_header_nritems(split, c_nritems - mid);
3030 btrfs_set_header_nritems(c, mid);
3032 btrfs_mark_buffer_dirty(trans, c);
3033 btrfs_mark_buffer_dirty(trans, split);
3035 ret = insert_ptr(trans, path, &disk_key, split->start,
3036 path->slots[level + 1] + 1, level + 1);
3038 btrfs_tree_unlock(split);
3039 free_extent_buffer(split);
3043 if (path->slots[level] >= mid) {
3044 path->slots[level] -= mid;
3045 btrfs_tree_unlock(c);
3046 free_extent_buffer(c);
3047 path->nodes[level] = split;
3048 path->slots[level + 1] += 1;
3050 btrfs_tree_unlock(split);
3051 free_extent_buffer(split);
3057 * how many bytes are required to store the items in a leaf. start
3058 * and nr indicate which items in the leaf to check. This totals up the
3059 * space used both by the item structs and the item data
3061 static int leaf_space_used(const struct extent_buffer *l, int start, int nr)
3064 int nritems = btrfs_header_nritems(l);
3065 int end = min(nritems, start + nr) - 1;
3069 data_len = btrfs_item_offset(l, start) + btrfs_item_size(l, start);
3070 data_len = data_len - btrfs_item_offset(l, end);
3071 data_len += sizeof(struct btrfs_item) * nr;
3072 WARN_ON(data_len < 0);
3077 * The space between the end of the leaf items and
3078 * the start of the leaf data. IOW, how much room
3079 * the leaf has left for both items and data
3081 int btrfs_leaf_free_space(const struct extent_buffer *leaf)
3083 struct btrfs_fs_info *fs_info = leaf->fs_info;
3084 int nritems = btrfs_header_nritems(leaf);
3087 ret = BTRFS_LEAF_DATA_SIZE(fs_info) - leaf_space_used(leaf, 0, nritems);
3090 "leaf free space ret %d, leaf data size %lu, used %d nritems %d",
3092 (unsigned long) BTRFS_LEAF_DATA_SIZE(fs_info),
3093 leaf_space_used(leaf, 0, nritems), nritems);
3099 * min slot controls the lowest index we're willing to push to the
3100 * right. We'll push up to and including min_slot, but no lower
3102 static noinline int __push_leaf_right(struct btrfs_trans_handle *trans,
3103 struct btrfs_path *path,
3104 int data_size, int empty,
3105 struct extent_buffer *right,
3106 int free_space, u32 left_nritems,
3109 struct btrfs_fs_info *fs_info = right->fs_info;
3110 struct extent_buffer *left = path->nodes[0];
3111 struct extent_buffer *upper = path->nodes[1];
3112 struct btrfs_map_token token;
3113 struct btrfs_disk_key disk_key;
3126 nr = max_t(u32, 1, min_slot);
3128 if (path->slots[0] >= left_nritems)
3129 push_space += data_size;
3131 slot = path->slots[1];
3132 i = left_nritems - 1;
3134 if (!empty && push_items > 0) {
3135 if (path->slots[0] > i)
3137 if (path->slots[0] == i) {
3138 int space = btrfs_leaf_free_space(left);
3140 if (space + push_space * 2 > free_space)
3145 if (path->slots[0] == i)
3146 push_space += data_size;
3148 this_item_size = btrfs_item_size(left, i);
3149 if (this_item_size + sizeof(struct btrfs_item) +
3150 push_space > free_space)
3154 push_space += this_item_size + sizeof(struct btrfs_item);
3160 if (push_items == 0)
3163 WARN_ON(!empty && push_items == left_nritems);
3165 /* push left to right */
3166 right_nritems = btrfs_header_nritems(right);
3168 push_space = btrfs_item_data_end(left, left_nritems - push_items);
3169 push_space -= leaf_data_end(left);
3171 /* make room in the right data area */
3172 data_end = leaf_data_end(right);
3173 memmove_leaf_data(right, data_end - push_space, data_end,
3174 BTRFS_LEAF_DATA_SIZE(fs_info) - data_end);
3176 /* copy from the left data area */
3177 copy_leaf_data(right, left, BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
3178 leaf_data_end(left), push_space);
3180 memmove_leaf_items(right, push_items, 0, right_nritems);
3182 /* copy the items from left to right */
3183 copy_leaf_items(right, left, 0, left_nritems - push_items, push_items);
3185 /* update the item pointers */
3186 btrfs_init_map_token(&token, right);
3187 right_nritems += push_items;
3188 btrfs_set_header_nritems(right, right_nritems);
3189 push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
3190 for (i = 0; i < right_nritems; i++) {
3191 push_space -= btrfs_token_item_size(&token, i);
3192 btrfs_set_token_item_offset(&token, i, push_space);
3195 left_nritems -= push_items;
3196 btrfs_set_header_nritems(left, left_nritems);
3199 btrfs_mark_buffer_dirty(trans, left);
3201 btrfs_clear_buffer_dirty(trans, left);
3203 btrfs_mark_buffer_dirty(trans, right);
3205 btrfs_item_key(right, &disk_key, 0);
3206 btrfs_set_node_key(upper, &disk_key, slot + 1);
3207 btrfs_mark_buffer_dirty(trans, upper);
3209 /* then fixup the leaf pointer in the path */
3210 if (path->slots[0] >= left_nritems) {
3211 path->slots[0] -= left_nritems;
3212 if (btrfs_header_nritems(path->nodes[0]) == 0)
3213 btrfs_clear_buffer_dirty(trans, path->nodes[0]);
3214 btrfs_tree_unlock(path->nodes[0]);
3215 free_extent_buffer(path->nodes[0]);
3216 path->nodes[0] = right;
3217 path->slots[1] += 1;
3219 btrfs_tree_unlock(right);
3220 free_extent_buffer(right);
3225 btrfs_tree_unlock(right);
3226 free_extent_buffer(right);
3231 * push some data in the path leaf to the right, trying to free up at
3232 * least data_size bytes. returns zero if the push worked, nonzero otherwise
3234 * returns 1 if the push failed because the other node didn't have enough
3235 * room, 0 if everything worked out and < 0 if there were major errors.
3237 * this will push starting from min_slot to the end of the leaf. It won't
3238 * push any slot lower than min_slot
3240 static int push_leaf_right(struct btrfs_trans_handle *trans, struct btrfs_root
3241 *root, struct btrfs_path *path,
3242 int min_data_size, int data_size,
3243 int empty, u32 min_slot)
3245 struct extent_buffer *left = path->nodes[0];
3246 struct extent_buffer *right;
3247 struct extent_buffer *upper;
3253 if (!path->nodes[1])
3256 slot = path->slots[1];
3257 upper = path->nodes[1];
3258 if (slot >= btrfs_header_nritems(upper) - 1)
3261 btrfs_assert_tree_write_locked(path->nodes[1]);
3263 right = btrfs_read_node_slot(upper, slot + 1);
3265 return PTR_ERR(right);
3267 btrfs_tree_lock_nested(right, BTRFS_NESTING_RIGHT);
3269 free_space = btrfs_leaf_free_space(right);
3270 if (free_space < data_size)
3273 ret = btrfs_cow_block(trans, root, right, upper,
3274 slot + 1, &right, BTRFS_NESTING_RIGHT_COW);
3278 left_nritems = btrfs_header_nritems(left);
3279 if (left_nritems == 0)
3282 if (check_sibling_keys(left, right)) {
3284 btrfs_abort_transaction(trans, ret);
3285 btrfs_tree_unlock(right);
3286 free_extent_buffer(right);
3289 if (path->slots[0] == left_nritems && !empty) {
3290 /* Key greater than all keys in the leaf, right neighbor has
3291 * enough room for it and we're not emptying our leaf to delete
3292 * it, therefore use right neighbor to insert the new item and
3293 * no need to touch/dirty our left leaf. */
3294 btrfs_tree_unlock(left);
3295 free_extent_buffer(left);
3296 path->nodes[0] = right;
3302 return __push_leaf_right(trans, path, min_data_size, empty, right,
3303 free_space, left_nritems, min_slot);
3305 btrfs_tree_unlock(right);
3306 free_extent_buffer(right);
3311 * push some data in the path leaf to the left, trying to free up at
3312 * least data_size bytes. returns zero if the push worked, nonzero otherwise
3314 * max_slot can put a limit on how far into the leaf we'll push items. The
3315 * item at 'max_slot' won't be touched. Use (u32)-1 to make us do all the
3318 static noinline int __push_leaf_left(struct btrfs_trans_handle *trans,
3319 struct btrfs_path *path, int data_size,
3320 int empty, struct extent_buffer *left,
3321 int free_space, u32 right_nritems,
3324 struct btrfs_fs_info *fs_info = left->fs_info;
3325 struct btrfs_disk_key disk_key;
3326 struct extent_buffer *right = path->nodes[0];
3330 u32 old_left_nritems;
3334 u32 old_left_item_size;
3335 struct btrfs_map_token token;
3338 nr = min(right_nritems, max_slot);
3340 nr = min(right_nritems - 1, max_slot);
3342 for (i = 0; i < nr; i++) {
3343 if (!empty && push_items > 0) {
3344 if (path->slots[0] < i)
3346 if (path->slots[0] == i) {
3347 int space = btrfs_leaf_free_space(right);
3349 if (space + push_space * 2 > free_space)
3354 if (path->slots[0] == i)
3355 push_space += data_size;
3357 this_item_size = btrfs_item_size(right, i);
3358 if (this_item_size + sizeof(struct btrfs_item) + push_space >
3363 push_space += this_item_size + sizeof(struct btrfs_item);
3366 if (push_items == 0) {
3370 WARN_ON(!empty && push_items == btrfs_header_nritems(right));
3372 /* push data from right to left */
3373 copy_leaf_items(left, right, btrfs_header_nritems(left), 0, push_items);
3375 push_space = BTRFS_LEAF_DATA_SIZE(fs_info) -
3376 btrfs_item_offset(right, push_items - 1);
3378 copy_leaf_data(left, right, leaf_data_end(left) - push_space,
3379 btrfs_item_offset(right, push_items - 1), push_space);
3380 old_left_nritems = btrfs_header_nritems(left);
3381 BUG_ON(old_left_nritems <= 0);
3383 btrfs_init_map_token(&token, left);
3384 old_left_item_size = btrfs_item_offset(left, old_left_nritems - 1);
3385 for (i = old_left_nritems; i < old_left_nritems + push_items; i++) {
3388 ioff = btrfs_token_item_offset(&token, i);
3389 btrfs_set_token_item_offset(&token, i,
3390 ioff - (BTRFS_LEAF_DATA_SIZE(fs_info) - old_left_item_size));
3392 btrfs_set_header_nritems(left, old_left_nritems + push_items);
3394 /* fixup right node */
3395 if (push_items > right_nritems)
3396 WARN(1, KERN_CRIT "push items %d nr %u\n", push_items,
3399 if (push_items < right_nritems) {
3400 push_space = btrfs_item_offset(right, push_items - 1) -
3401 leaf_data_end(right);
3402 memmove_leaf_data(right,
3403 BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
3404 leaf_data_end(right), push_space);
3406 memmove_leaf_items(right, 0, push_items,
3407 btrfs_header_nritems(right) - push_items);
3410 btrfs_init_map_token(&token, right);
3411 right_nritems -= push_items;
3412 btrfs_set_header_nritems(right, right_nritems);
3413 push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
3414 for (i = 0; i < right_nritems; i++) {
3415 push_space = push_space - btrfs_token_item_size(&token, i);
3416 btrfs_set_token_item_offset(&token, i, push_space);
3419 btrfs_mark_buffer_dirty(trans, left);
3421 btrfs_mark_buffer_dirty(trans, right);
3423 btrfs_clear_buffer_dirty(trans, right);
3425 btrfs_item_key(right, &disk_key, 0);
3426 fixup_low_keys(trans, path, &disk_key, 1);
3428 /* then fixup the leaf pointer in the path */
3429 if (path->slots[0] < push_items) {
3430 path->slots[0] += old_left_nritems;
3431 btrfs_tree_unlock(path->nodes[0]);
3432 free_extent_buffer(path->nodes[0]);
3433 path->nodes[0] = left;
3434 path->slots[1] -= 1;
3436 btrfs_tree_unlock(left);
3437 free_extent_buffer(left);
3438 path->slots[0] -= push_items;
3440 BUG_ON(path->slots[0] < 0);
3443 btrfs_tree_unlock(left);
3444 free_extent_buffer(left);
3449 * push some data in the path leaf to the left, trying to free up at
3450 * least data_size bytes. returns zero if the push worked, nonzero otherwise
3452 * max_slot can put a limit on how far into the leaf we'll push items. The
3453 * item at 'max_slot' won't be touched. Use (u32)-1 to make us push all the
3456 static int push_leaf_left(struct btrfs_trans_handle *trans, struct btrfs_root
3457 *root, struct btrfs_path *path, int min_data_size,
3458 int data_size, int empty, u32 max_slot)
3460 struct extent_buffer *right = path->nodes[0];
3461 struct extent_buffer *left;
3467 slot = path->slots[1];
3470 if (!path->nodes[1])
3473 right_nritems = btrfs_header_nritems(right);
3474 if (right_nritems == 0)
3477 btrfs_assert_tree_write_locked(path->nodes[1]);
3479 left = btrfs_read_node_slot(path->nodes[1], slot - 1);
3481 return PTR_ERR(left);
3483 btrfs_tree_lock_nested(left, BTRFS_NESTING_LEFT);
3485 free_space = btrfs_leaf_free_space(left);
3486 if (free_space < data_size) {
3491 ret = btrfs_cow_block(trans, root, left,
3492 path->nodes[1], slot - 1, &left,
3493 BTRFS_NESTING_LEFT_COW);
3495 /* we hit -ENOSPC, but it isn't fatal here */
3501 if (check_sibling_keys(left, right)) {
3503 btrfs_abort_transaction(trans, ret);
3506 return __push_leaf_left(trans, path, min_data_size, empty, left,
3507 free_space, right_nritems, max_slot);
3509 btrfs_tree_unlock(left);
3510 free_extent_buffer(left);
3515 * split the path's leaf in two, making sure there is at least data_size
3516 * available for the resulting leaf level of the path.
3518 static noinline int copy_for_split(struct btrfs_trans_handle *trans,
3519 struct btrfs_path *path,
3520 struct extent_buffer *l,
3521 struct extent_buffer *right,
3522 int slot, int mid, int nritems)
3524 struct btrfs_fs_info *fs_info = trans->fs_info;
3529 struct btrfs_disk_key disk_key;
3530 struct btrfs_map_token token;
3532 nritems = nritems - mid;
3533 btrfs_set_header_nritems(right, nritems);
3534 data_copy_size = btrfs_item_data_end(l, mid) - leaf_data_end(l);
3536 copy_leaf_items(right, l, 0, mid, nritems);
3538 copy_leaf_data(right, l, BTRFS_LEAF_DATA_SIZE(fs_info) - data_copy_size,
3539 leaf_data_end(l), data_copy_size);
3541 rt_data_off = BTRFS_LEAF_DATA_SIZE(fs_info) - btrfs_item_data_end(l, mid);
3543 btrfs_init_map_token(&token, right);
3544 for (i = 0; i < nritems; i++) {
3547 ioff = btrfs_token_item_offset(&token, i);
3548 btrfs_set_token_item_offset(&token, i, ioff + rt_data_off);
3551 btrfs_set_header_nritems(l, mid);
3552 btrfs_item_key(right, &disk_key, 0);
3553 ret = insert_ptr(trans, path, &disk_key, right->start, path->slots[1] + 1, 1);
3557 btrfs_mark_buffer_dirty(trans, right);
3558 btrfs_mark_buffer_dirty(trans, l);
3559 BUG_ON(path->slots[0] != slot);
3562 btrfs_tree_unlock(path->nodes[0]);
3563 free_extent_buffer(path->nodes[0]);
3564 path->nodes[0] = right;
3565 path->slots[0] -= mid;
3566 path->slots[1] += 1;
3568 btrfs_tree_unlock(right);
3569 free_extent_buffer(right);
3572 BUG_ON(path->slots[0] < 0);
3578 * double splits happen when we need to insert a big item in the middle
3579 * of a leaf. A double split can leave us with 3 mostly empty leaves:
3580 * leaf: [ slots 0 - N] [ our target ] [ N + 1 - total in leaf ]
3583 * We avoid this by trying to push the items on either side of our target
3584 * into the adjacent leaves. If all goes well we can avoid the double split
3587 static noinline int push_for_double_split(struct btrfs_trans_handle *trans,
3588 struct btrfs_root *root,
3589 struct btrfs_path *path,
3596 int space_needed = data_size;
3598 slot = path->slots[0];
3599 if (slot < btrfs_header_nritems(path->nodes[0]))
3600 space_needed -= btrfs_leaf_free_space(path->nodes[0]);
3603 * try to push all the items after our slot into the
3606 ret = push_leaf_right(trans, root, path, 1, space_needed, 0, slot);
3613 nritems = btrfs_header_nritems(path->nodes[0]);
3615 * our goal is to get our slot at the start or end of a leaf. If
3616 * we've done so we're done
3618 if (path->slots[0] == 0 || path->slots[0] == nritems)
3621 if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
3624 /* try to push all the items before our slot into the next leaf */
3625 slot = path->slots[0];
3626 space_needed = data_size;
3628 space_needed -= btrfs_leaf_free_space(path->nodes[0]);
3629 ret = push_leaf_left(trans, root, path, 1, space_needed, 0, slot);
3642 * split the path's leaf in two, making sure there is at least data_size
3643 * available for the resulting leaf level of the path.
3645 * returns 0 if all went well and < 0 on failure.
3647 static noinline int split_leaf(struct btrfs_trans_handle *trans,
3648 struct btrfs_root *root,
3649 const struct btrfs_key *ins_key,
3650 struct btrfs_path *path, int data_size,
3653 struct btrfs_disk_key disk_key;
3654 struct extent_buffer *l;
3658 struct extent_buffer *right;
3659 struct btrfs_fs_info *fs_info = root->fs_info;
3663 int num_doubles = 0;
3664 int tried_avoid_double = 0;
3667 slot = path->slots[0];
3668 if (extend && data_size + btrfs_item_size(l, slot) +
3669 sizeof(struct btrfs_item) > BTRFS_LEAF_DATA_SIZE(fs_info))
3672 /* first try to make some room by pushing left and right */
3673 if (data_size && path->nodes[1]) {
3674 int space_needed = data_size;
3676 if (slot < btrfs_header_nritems(l))
3677 space_needed -= btrfs_leaf_free_space(l);
3679 wret = push_leaf_right(trans, root, path, space_needed,
3680 space_needed, 0, 0);
3684 space_needed = data_size;
3686 space_needed -= btrfs_leaf_free_space(l);
3687 wret = push_leaf_left(trans, root, path, space_needed,
3688 space_needed, 0, (u32)-1);
3694 /* did the pushes work? */
3695 if (btrfs_leaf_free_space(l) >= data_size)
3699 if (!path->nodes[1]) {
3700 ret = insert_new_root(trans, root, path, 1);
3707 slot = path->slots[0];
3708 nritems = btrfs_header_nritems(l);
3709 mid = (nritems + 1) / 2;
3713 leaf_space_used(l, mid, nritems - mid) + data_size >
3714 BTRFS_LEAF_DATA_SIZE(fs_info)) {
3715 if (slot >= nritems) {
3719 if (mid != nritems &&
3720 leaf_space_used(l, mid, nritems - mid) +
3721 data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
3722 if (data_size && !tried_avoid_double)
3723 goto push_for_double;
3729 if (leaf_space_used(l, 0, mid) + data_size >
3730 BTRFS_LEAF_DATA_SIZE(fs_info)) {
3731 if (!extend && data_size && slot == 0) {
3733 } else if ((extend || !data_size) && slot == 0) {
3737 if (mid != nritems &&
3738 leaf_space_used(l, mid, nritems - mid) +
3739 data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
3740 if (data_size && !tried_avoid_double)
3741 goto push_for_double;
3749 btrfs_cpu_key_to_disk(&disk_key, ins_key);
3751 btrfs_item_key(l, &disk_key, mid);
3754 * We have to about BTRFS_NESTING_NEW_ROOT here if we've done a double
3755 * split, because we're only allowed to have MAX_LOCKDEP_SUBCLASSES
3756 * subclasses, which is 8 at the time of this patch, and we've maxed it
3757 * out. In the future we could add a
3758 * BTRFS_NESTING_SPLIT_THE_SPLITTENING if we need to, but for now just
3759 * use BTRFS_NESTING_NEW_ROOT.
3761 right = btrfs_alloc_tree_block(trans, root, 0, btrfs_root_id(root),
3762 &disk_key, 0, l->start, 0, 0,
3763 num_doubles ? BTRFS_NESTING_NEW_ROOT :
3764 BTRFS_NESTING_SPLIT);
3766 return PTR_ERR(right);
3768 root_add_used_bytes(root);
3772 btrfs_set_header_nritems(right, 0);
3773 ret = insert_ptr(trans, path, &disk_key,
3774 right->start, path->slots[1] + 1, 1);
3776 btrfs_tree_unlock(right);
3777 free_extent_buffer(right);
3780 btrfs_tree_unlock(path->nodes[0]);
3781 free_extent_buffer(path->nodes[0]);
3782 path->nodes[0] = right;
3784 path->slots[1] += 1;
3786 btrfs_set_header_nritems(right, 0);
3787 ret = insert_ptr(trans, path, &disk_key,
3788 right->start, path->slots[1], 1);
3790 btrfs_tree_unlock(right);
3791 free_extent_buffer(right);
3794 btrfs_tree_unlock(path->nodes[0]);
3795 free_extent_buffer(path->nodes[0]);
3796 path->nodes[0] = right;
3798 if (path->slots[1] == 0)
3799 fixup_low_keys(trans, path, &disk_key, 1);
3802 * We create a new leaf 'right' for the required ins_len and
3803 * we'll do btrfs_mark_buffer_dirty() on this leaf after copying
3804 * the content of ins_len to 'right'.
3809 ret = copy_for_split(trans, path, l, right, slot, mid, nritems);
3811 btrfs_tree_unlock(right);
3812 free_extent_buffer(right);
3817 BUG_ON(num_doubles != 0);
3825 push_for_double_split(trans, root, path, data_size);
3826 tried_avoid_double = 1;
3827 if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
3832 static noinline int setup_leaf_for_split(struct btrfs_trans_handle *trans,
3833 struct btrfs_root *root,
3834 struct btrfs_path *path, int ins_len)
3836 struct btrfs_key key;
3837 struct extent_buffer *leaf;
3838 struct btrfs_file_extent_item *fi;
3843 leaf = path->nodes[0];
3844 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3846 BUG_ON(key.type != BTRFS_EXTENT_DATA_KEY &&
3847 key.type != BTRFS_EXTENT_CSUM_KEY);
3849 if (btrfs_leaf_free_space(leaf) >= ins_len)
3852 item_size = btrfs_item_size(leaf, path->slots[0]);
3853 if (key.type == BTRFS_EXTENT_DATA_KEY) {
3854 fi = btrfs_item_ptr(leaf, path->slots[0],
3855 struct btrfs_file_extent_item);
3856 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
3858 btrfs_release_path(path);
3860 path->keep_locks = 1;
3861 path->search_for_split = 1;
3862 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
3863 path->search_for_split = 0;
3870 leaf = path->nodes[0];
3871 /* if our item isn't there, return now */
3872 if (item_size != btrfs_item_size(leaf, path->slots[0]))
3875 /* the leaf has changed, it now has room. return now */
3876 if (btrfs_leaf_free_space(path->nodes[0]) >= ins_len)
3879 if (key.type == BTRFS_EXTENT_DATA_KEY) {
3880 fi = btrfs_item_ptr(leaf, path->slots[0],
3881 struct btrfs_file_extent_item);
3882 if (extent_len != btrfs_file_extent_num_bytes(leaf, fi))
3886 ret = split_leaf(trans, root, &key, path, ins_len, 1);
3890 path->keep_locks = 0;
3891 btrfs_unlock_up_safe(path, 1);
3894 path->keep_locks = 0;
3898 static noinline int split_item(struct btrfs_trans_handle *trans,
3899 struct btrfs_path *path,
3900 const struct btrfs_key *new_key,
3901 unsigned long split_offset)
3903 struct extent_buffer *leaf;
3904 int orig_slot, slot;
3909 struct btrfs_disk_key disk_key;
3911 leaf = path->nodes[0];
3913 * Shouldn't happen because the caller must have previously called
3914 * setup_leaf_for_split() to make room for the new item in the leaf.
3916 if (WARN_ON(btrfs_leaf_free_space(leaf) < sizeof(struct btrfs_item)))
3919 orig_slot = path->slots[0];
3920 orig_offset = btrfs_item_offset(leaf, path->slots[0]);
3921 item_size = btrfs_item_size(leaf, path->slots[0]);
3923 buf = kmalloc(item_size, GFP_NOFS);
3927 read_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf,
3928 path->slots[0]), item_size);
3930 slot = path->slots[0] + 1;
3931 nritems = btrfs_header_nritems(leaf);
3932 if (slot != nritems) {
3933 /* shift the items */
3934 memmove_leaf_items(leaf, slot + 1, slot, nritems - slot);
3937 btrfs_cpu_key_to_disk(&disk_key, new_key);
3938 btrfs_set_item_key(leaf, &disk_key, slot);
3940 btrfs_set_item_offset(leaf, slot, orig_offset);
3941 btrfs_set_item_size(leaf, slot, item_size - split_offset);
3943 btrfs_set_item_offset(leaf, orig_slot,
3944 orig_offset + item_size - split_offset);
3945 btrfs_set_item_size(leaf, orig_slot, split_offset);
3947 btrfs_set_header_nritems(leaf, nritems + 1);
3949 /* write the data for the start of the original item */
3950 write_extent_buffer(leaf, buf,
3951 btrfs_item_ptr_offset(leaf, path->slots[0]),
3954 /* write the data for the new item */
3955 write_extent_buffer(leaf, buf + split_offset,
3956 btrfs_item_ptr_offset(leaf, slot),
3957 item_size - split_offset);
3958 btrfs_mark_buffer_dirty(trans, leaf);
3960 BUG_ON(btrfs_leaf_free_space(leaf) < 0);
3966 * This function splits a single item into two items,
3967 * giving 'new_key' to the new item and splitting the
3968 * old one at split_offset (from the start of the item).
3970 * The path may be released by this operation. After
3971 * the split, the path is pointing to the old item. The
3972 * new item is going to be in the same node as the old one.
3974 * Note, the item being split must be smaller enough to live alone on
3975 * a tree block with room for one extra struct btrfs_item
3977 * This allows us to split the item in place, keeping a lock on the
3978 * leaf the entire time.
3980 int btrfs_split_item(struct btrfs_trans_handle *trans,
3981 struct btrfs_root *root,
3982 struct btrfs_path *path,
3983 const struct btrfs_key *new_key,
3984 unsigned long split_offset)
3987 ret = setup_leaf_for_split(trans, root, path,
3988 sizeof(struct btrfs_item));
3992 ret = split_item(trans, path, new_key, split_offset);
3997 * make the item pointed to by the path smaller. new_size indicates
3998 * how small to make it, and from_end tells us if we just chop bytes
3999 * off the end of the item or if we shift the item to chop bytes off
4002 void btrfs_truncate_item(struct btrfs_trans_handle *trans,
4003 struct btrfs_path *path, u32 new_size, int from_end)
4006 struct extent_buffer *leaf;
4008 unsigned int data_end;
4009 unsigned int old_data_start;
4010 unsigned int old_size;
4011 unsigned int size_diff;
4013 struct btrfs_map_token token;
4015 leaf = path->nodes[0];
4016 slot = path->slots[0];
4018 old_size = btrfs_item_size(leaf, slot);
4019 if (old_size == new_size)
4022 nritems = btrfs_header_nritems(leaf);
4023 data_end = leaf_data_end(leaf);
4025 old_data_start = btrfs_item_offset(leaf, slot);
4027 size_diff = old_size - new_size;
4030 BUG_ON(slot >= nritems);
4033 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4035 /* first correct the data pointers */
4036 btrfs_init_map_token(&token, leaf);
4037 for (i = slot; i < nritems; i++) {
4040 ioff = btrfs_token_item_offset(&token, i);
4041 btrfs_set_token_item_offset(&token, i, ioff + size_diff);
4044 /* shift the data */
4046 memmove_leaf_data(leaf, data_end + size_diff, data_end,
4047 old_data_start + new_size - data_end);
4049 struct btrfs_disk_key disk_key;
4052 btrfs_item_key(leaf, &disk_key, slot);
4054 if (btrfs_disk_key_type(&disk_key) == BTRFS_EXTENT_DATA_KEY) {
4056 struct btrfs_file_extent_item *fi;
4058 fi = btrfs_item_ptr(leaf, slot,
4059 struct btrfs_file_extent_item);
4060 fi = (struct btrfs_file_extent_item *)(
4061 (unsigned long)fi - size_diff);
4063 if (btrfs_file_extent_type(leaf, fi) ==
4064 BTRFS_FILE_EXTENT_INLINE) {
4065 ptr = btrfs_item_ptr_offset(leaf, slot);
4066 memmove_extent_buffer(leaf, ptr,
4068 BTRFS_FILE_EXTENT_INLINE_DATA_START);
4072 memmove_leaf_data(leaf, data_end + size_diff, data_end,
4073 old_data_start - data_end);
4075 offset = btrfs_disk_key_offset(&disk_key);
4076 btrfs_set_disk_key_offset(&disk_key, offset + size_diff);
4077 btrfs_set_item_key(leaf, &disk_key, slot);
4079 fixup_low_keys(trans, path, &disk_key, 1);
4082 btrfs_set_item_size(leaf, slot, new_size);
4083 btrfs_mark_buffer_dirty(trans, leaf);
4085 if (btrfs_leaf_free_space(leaf) < 0) {
4086 btrfs_print_leaf(leaf);
4092 * make the item pointed to by the path bigger, data_size is the added size.
4094 void btrfs_extend_item(struct btrfs_trans_handle *trans,
4095 struct btrfs_path *path, u32 data_size)
4098 struct extent_buffer *leaf;
4100 unsigned int data_end;
4101 unsigned int old_data;
4102 unsigned int old_size;
4104 struct btrfs_map_token token;
4106 leaf = path->nodes[0];
4108 nritems = btrfs_header_nritems(leaf);
4109 data_end = leaf_data_end(leaf);
4111 if (btrfs_leaf_free_space(leaf) < data_size) {
4112 btrfs_print_leaf(leaf);
4115 slot = path->slots[0];
4116 old_data = btrfs_item_data_end(leaf, slot);
4119 if (slot >= nritems) {
4120 btrfs_print_leaf(leaf);
4121 btrfs_crit(leaf->fs_info, "slot %d too large, nritems %d",
4127 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4129 /* first correct the data pointers */
4130 btrfs_init_map_token(&token, leaf);
4131 for (i = slot; i < nritems; i++) {
4134 ioff = btrfs_token_item_offset(&token, i);
4135 btrfs_set_token_item_offset(&token, i, ioff - data_size);
4138 /* shift the data */
4139 memmove_leaf_data(leaf, data_end - data_size, data_end,
4140 old_data - data_end);
4142 data_end = old_data;
4143 old_size = btrfs_item_size(leaf, slot);
4144 btrfs_set_item_size(leaf, slot, old_size + data_size);
4145 btrfs_mark_buffer_dirty(trans, leaf);
4147 if (btrfs_leaf_free_space(leaf) < 0) {
4148 btrfs_print_leaf(leaf);
4154 * Make space in the node before inserting one or more items.
4156 * @trans: transaction handle
4157 * @root: root we are inserting items to
4158 * @path: points to the leaf/slot where we are going to insert new items
4159 * @batch: information about the batch of items to insert
4161 * Main purpose is to save stack depth by doing the bulk of the work in a
4162 * function that doesn't call btrfs_search_slot
4164 static void setup_items_for_insert(struct btrfs_trans_handle *trans,
4165 struct btrfs_root *root, struct btrfs_path *path,
4166 const struct btrfs_item_batch *batch)
4168 struct btrfs_fs_info *fs_info = root->fs_info;
4171 unsigned int data_end;
4172 struct btrfs_disk_key disk_key;
4173 struct extent_buffer *leaf;
4175 struct btrfs_map_token token;
4179 * Before anything else, update keys in the parent and other ancestors
4180 * if needed, then release the write locks on them, so that other tasks
4181 * can use them while we modify the leaf.
4183 if (path->slots[0] == 0) {
4184 btrfs_cpu_key_to_disk(&disk_key, &batch->keys[0]);
4185 fixup_low_keys(trans, path, &disk_key, 1);
4187 btrfs_unlock_up_safe(path, 1);
4189 leaf = path->nodes[0];
4190 slot = path->slots[0];
4192 nritems = btrfs_header_nritems(leaf);
4193 data_end = leaf_data_end(leaf);
4194 total_size = batch->total_data_size + (batch->nr * sizeof(struct btrfs_item));
4196 if (btrfs_leaf_free_space(leaf) < total_size) {
4197 btrfs_print_leaf(leaf);
4198 btrfs_crit(fs_info, "not enough freespace need %u have %d",
4199 total_size, btrfs_leaf_free_space(leaf));
4203 btrfs_init_map_token(&token, leaf);
4204 if (slot != nritems) {
4205 unsigned int old_data = btrfs_item_data_end(leaf, slot);
4207 if (old_data < data_end) {
4208 btrfs_print_leaf(leaf);
4210 "item at slot %d with data offset %u beyond data end of leaf %u",
4211 slot, old_data, data_end);
4215 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4217 /* first correct the data pointers */
4218 for (i = slot; i < nritems; i++) {
4221 ioff = btrfs_token_item_offset(&token, i);
4222 btrfs_set_token_item_offset(&token, i,
4223 ioff - batch->total_data_size);
4225 /* shift the items */
4226 memmove_leaf_items(leaf, slot + batch->nr, slot, nritems - slot);
4228 /* shift the data */
4229 memmove_leaf_data(leaf, data_end - batch->total_data_size,
4230 data_end, old_data - data_end);
4231 data_end = old_data;
4234 /* setup the item for the new data */
4235 for (i = 0; i < batch->nr; i++) {
4236 btrfs_cpu_key_to_disk(&disk_key, &batch->keys[i]);
4237 btrfs_set_item_key(leaf, &disk_key, slot + i);
4238 data_end -= batch->data_sizes[i];
4239 btrfs_set_token_item_offset(&token, slot + i, data_end);
4240 btrfs_set_token_item_size(&token, slot + i, batch->data_sizes[i]);
4243 btrfs_set_header_nritems(leaf, nritems + batch->nr);
4244 btrfs_mark_buffer_dirty(trans, leaf);
4246 if (btrfs_leaf_free_space(leaf) < 0) {
4247 btrfs_print_leaf(leaf);
4253 * Insert a new item into a leaf.
4255 * @trans: Transaction handle.
4256 * @root: The root of the btree.
4257 * @path: A path pointing to the target leaf and slot.
4258 * @key: The key of the new item.
4259 * @data_size: The size of the data associated with the new key.
4261 void btrfs_setup_item_for_insert(struct btrfs_trans_handle *trans,
4262 struct btrfs_root *root,
4263 struct btrfs_path *path,
4264 const struct btrfs_key *key,
4267 struct btrfs_item_batch batch;
4270 batch.data_sizes = &data_size;
4271 batch.total_data_size = data_size;
4274 setup_items_for_insert(trans, root, path, &batch);
4278 * Given a key and some data, insert items into the tree.
4279 * This does all the path init required, making room in the tree if needed.
4281 * Returns: 0 on success
4282 * -EEXIST if the first key already exists
4283 * < 0 on other errors
4285 int btrfs_insert_empty_items(struct btrfs_trans_handle *trans,
4286 struct btrfs_root *root,
4287 struct btrfs_path *path,
4288 const struct btrfs_item_batch *batch)
4294 total_size = batch->total_data_size + (batch->nr * sizeof(struct btrfs_item));
4295 ret = btrfs_search_slot(trans, root, &batch->keys[0], path, total_size, 1);
4301 slot = path->slots[0];
4304 setup_items_for_insert(trans, root, path, batch);
4309 * Given a key and some data, insert an item into the tree.
4310 * This does all the path init required, making room in the tree if needed.
4312 int btrfs_insert_item(struct btrfs_trans_handle *trans, struct btrfs_root *root,
4313 const struct btrfs_key *cpu_key, void *data,
4317 struct btrfs_path *path;
4318 struct extent_buffer *leaf;
4321 path = btrfs_alloc_path();
4324 ret = btrfs_insert_empty_item(trans, root, path, cpu_key, data_size);
4326 leaf = path->nodes[0];
4327 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
4328 write_extent_buffer(leaf, data, ptr, data_size);
4329 btrfs_mark_buffer_dirty(trans, leaf);
4331 btrfs_free_path(path);
4336 * This function duplicates an item, giving 'new_key' to the new item.
4337 * It guarantees both items live in the same tree leaf and the new item is
4338 * contiguous with the original item.
4340 * This allows us to split a file extent in place, keeping a lock on the leaf
4343 int btrfs_duplicate_item(struct btrfs_trans_handle *trans,
4344 struct btrfs_root *root,
4345 struct btrfs_path *path,
4346 const struct btrfs_key *new_key)
4348 struct extent_buffer *leaf;
4352 leaf = path->nodes[0];
4353 item_size = btrfs_item_size(leaf, path->slots[0]);
4354 ret = setup_leaf_for_split(trans, root, path,
4355 item_size + sizeof(struct btrfs_item));
4360 btrfs_setup_item_for_insert(trans, root, path, new_key, item_size);
4361 leaf = path->nodes[0];
4362 memcpy_extent_buffer(leaf,
4363 btrfs_item_ptr_offset(leaf, path->slots[0]),
4364 btrfs_item_ptr_offset(leaf, path->slots[0] - 1),
4370 * delete the pointer from a given node.
4372 * the tree should have been previously balanced so the deletion does not
4375 * This is exported for use inside btrfs-progs, don't un-export it.
4377 int btrfs_del_ptr(struct btrfs_trans_handle *trans, struct btrfs_root *root,
4378 struct btrfs_path *path, int level, int slot)
4380 struct extent_buffer *parent = path->nodes[level];
4384 nritems = btrfs_header_nritems(parent);
4385 if (slot != nritems - 1) {
4387 ret = btrfs_tree_mod_log_insert_move(parent, slot,
4388 slot + 1, nritems - slot - 1);
4390 btrfs_abort_transaction(trans, ret);
4394 memmove_extent_buffer(parent,
4395 btrfs_node_key_ptr_offset(parent, slot),
4396 btrfs_node_key_ptr_offset(parent, slot + 1),
4397 sizeof(struct btrfs_key_ptr) *
4398 (nritems - slot - 1));
4400 ret = btrfs_tree_mod_log_insert_key(parent, slot,
4401 BTRFS_MOD_LOG_KEY_REMOVE);
4403 btrfs_abort_transaction(trans, ret);
4409 btrfs_set_header_nritems(parent, nritems);
4410 if (nritems == 0 && parent == root->node) {
4411 BUG_ON(btrfs_header_level(root->node) != 1);
4412 /* just turn the root into a leaf and break */
4413 btrfs_set_header_level(root->node, 0);
4414 } else if (slot == 0) {
4415 struct btrfs_disk_key disk_key;
4417 btrfs_node_key(parent, &disk_key, 0);
4418 fixup_low_keys(trans, path, &disk_key, level + 1);
4420 btrfs_mark_buffer_dirty(trans, parent);
4425 * a helper function to delete the leaf pointed to by path->slots[1] and
4428 * This deletes the pointer in path->nodes[1] and frees the leaf
4429 * block extent. zero is returned if it all worked out, < 0 otherwise.
4431 * The path must have already been setup for deleting the leaf, including
4432 * all the proper balancing. path->nodes[1] must be locked.
4434 static noinline int btrfs_del_leaf(struct btrfs_trans_handle *trans,
4435 struct btrfs_root *root,
4436 struct btrfs_path *path,
4437 struct extent_buffer *leaf)
4441 WARN_ON(btrfs_header_generation(leaf) != trans->transid);
4442 ret = btrfs_del_ptr(trans, root, path, 1, path->slots[1]);
4447 * btrfs_free_extent is expensive, we want to make sure we
4448 * aren't holding any locks when we call it
4450 btrfs_unlock_up_safe(path, 0);
4452 root_sub_used_bytes(root);
4454 atomic_inc(&leaf->refs);
4455 btrfs_free_tree_block(trans, btrfs_root_id(root), leaf, 0, 1);
4456 free_extent_buffer_stale(leaf);
4460 * delete the item at the leaf level in path. If that empties
4461 * the leaf, remove it from the tree
4463 int btrfs_del_items(struct btrfs_trans_handle *trans, struct btrfs_root *root,
4464 struct btrfs_path *path, int slot, int nr)
4466 struct btrfs_fs_info *fs_info = root->fs_info;
4467 struct extent_buffer *leaf;
4472 leaf = path->nodes[0];
4473 nritems = btrfs_header_nritems(leaf);
4475 if (slot + nr != nritems) {
4476 const u32 last_off = btrfs_item_offset(leaf, slot + nr - 1);
4477 const int data_end = leaf_data_end(leaf);
4478 struct btrfs_map_token token;
4482 for (i = 0; i < nr; i++)
4483 dsize += btrfs_item_size(leaf, slot + i);
4485 memmove_leaf_data(leaf, data_end + dsize, data_end,
4486 last_off - data_end);
4488 btrfs_init_map_token(&token, leaf);
4489 for (i = slot + nr; i < nritems; i++) {
4492 ioff = btrfs_token_item_offset(&token, i);
4493 btrfs_set_token_item_offset(&token, i, ioff + dsize);
4496 memmove_leaf_items(leaf, slot, slot + nr, nritems - slot - nr);
4498 btrfs_set_header_nritems(leaf, nritems - nr);
4501 /* delete the leaf if we've emptied it */
4503 if (leaf == root->node) {
4504 btrfs_set_header_level(leaf, 0);
4506 btrfs_clear_buffer_dirty(trans, leaf);
4507 ret = btrfs_del_leaf(trans, root, path, leaf);
4512 int used = leaf_space_used(leaf, 0, nritems);
4514 struct btrfs_disk_key disk_key;
4516 btrfs_item_key(leaf, &disk_key, 0);
4517 fixup_low_keys(trans, path, &disk_key, 1);
4521 * Try to delete the leaf if it is mostly empty. We do this by
4522 * trying to move all its items into its left and right neighbours.
4523 * If we can't move all the items, then we don't delete it - it's
4524 * not ideal, but future insertions might fill the leaf with more
4525 * items, or items from other leaves might be moved later into our
4526 * leaf due to deletions on those leaves.
4528 if (used < BTRFS_LEAF_DATA_SIZE(fs_info) / 3) {
4531 /* push_leaf_left fixes the path.
4532 * make sure the path still points to our leaf
4533 * for possible call to btrfs_del_ptr below
4535 slot = path->slots[1];
4536 atomic_inc(&leaf->refs);
4538 * We want to be able to at least push one item to the
4539 * left neighbour leaf, and that's the first item.
4541 min_push_space = sizeof(struct btrfs_item) +
4542 btrfs_item_size(leaf, 0);
4543 wret = push_leaf_left(trans, root, path, 0,
4544 min_push_space, 1, (u32)-1);
4545 if (wret < 0 && wret != -ENOSPC)
4548 if (path->nodes[0] == leaf &&
4549 btrfs_header_nritems(leaf)) {
4551 * If we were not able to push all items from our
4552 * leaf to its left neighbour, then attempt to
4553 * either push all the remaining items to the
4554 * right neighbour or none. There's no advantage
4555 * in pushing only some items, instead of all, as
4556 * it's pointless to end up with a leaf having
4557 * too few items while the neighbours can be full
4560 nritems = btrfs_header_nritems(leaf);
4561 min_push_space = leaf_space_used(leaf, 0, nritems);
4562 wret = push_leaf_right(trans, root, path, 0,
4563 min_push_space, 1, 0);
4564 if (wret < 0 && wret != -ENOSPC)
4568 if (btrfs_header_nritems(leaf) == 0) {
4569 path->slots[1] = slot;
4570 ret = btrfs_del_leaf(trans, root, path, leaf);
4573 free_extent_buffer(leaf);
4576 /* if we're still in the path, make sure
4577 * we're dirty. Otherwise, one of the
4578 * push_leaf functions must have already
4579 * dirtied this buffer
4581 if (path->nodes[0] == leaf)
4582 btrfs_mark_buffer_dirty(trans, leaf);
4583 free_extent_buffer(leaf);
4586 btrfs_mark_buffer_dirty(trans, leaf);
4593 * A helper function to walk down the tree starting at min_key, and looking
4594 * for nodes or leaves that are have a minimum transaction id.
4595 * This is used by the btree defrag code, and tree logging
4597 * This does not cow, but it does stuff the starting key it finds back
4598 * into min_key, so you can call btrfs_search_slot with cow=1 on the
4599 * key and get a writable path.
4601 * This honors path->lowest_level to prevent descent past a given level
4604 * min_trans indicates the oldest transaction that you are interested
4605 * in walking through. Any nodes or leaves older than min_trans are
4606 * skipped over (without reading them).
4608 * returns zero if something useful was found, < 0 on error and 1 if there
4609 * was nothing in the tree that matched the search criteria.
4611 int btrfs_search_forward(struct btrfs_root *root, struct btrfs_key *min_key,
4612 struct btrfs_path *path,
4615 struct extent_buffer *cur;
4616 struct btrfs_key found_key;
4622 int keep_locks = path->keep_locks;
4624 ASSERT(!path->nowait);
4625 path->keep_locks = 1;
4627 cur = btrfs_read_lock_root_node(root);
4628 level = btrfs_header_level(cur);
4629 WARN_ON(path->nodes[level]);
4630 path->nodes[level] = cur;
4631 path->locks[level] = BTRFS_READ_LOCK;
4633 if (btrfs_header_generation(cur) < min_trans) {
4638 nritems = btrfs_header_nritems(cur);
4639 level = btrfs_header_level(cur);
4640 sret = btrfs_bin_search(cur, 0, min_key, &slot);
4646 /* at the lowest level, we're done, setup the path and exit */
4647 if (level == path->lowest_level) {
4648 if (slot >= nritems)
4651 path->slots[level] = slot;
4652 btrfs_item_key_to_cpu(cur, &found_key, slot);
4655 if (sret && slot > 0)
4658 * check this node pointer against the min_trans parameters.
4659 * If it is too old, skip to the next one.
4661 while (slot < nritems) {
4664 gen = btrfs_node_ptr_generation(cur, slot);
4665 if (gen < min_trans) {
4673 * we didn't find a candidate key in this node, walk forward
4674 * and find another one
4676 if (slot >= nritems) {
4677 path->slots[level] = slot;
4678 sret = btrfs_find_next_key(root, path, min_key, level,
4681 btrfs_release_path(path);
4687 /* save our key for returning back */
4688 btrfs_node_key_to_cpu(cur, &found_key, slot);
4689 path->slots[level] = slot;
4690 if (level == path->lowest_level) {
4694 cur = btrfs_read_node_slot(cur, slot);
4700 btrfs_tree_read_lock(cur);
4702 path->locks[level - 1] = BTRFS_READ_LOCK;
4703 path->nodes[level - 1] = cur;
4704 unlock_up(path, level, 1, 0, NULL);
4707 path->keep_locks = keep_locks;
4709 btrfs_unlock_up_safe(path, path->lowest_level + 1);
4710 memcpy(min_key, &found_key, sizeof(found_key));
4716 * this is similar to btrfs_next_leaf, but does not try to preserve
4717 * and fixup the path. It looks for and returns the next key in the
4718 * tree based on the current path and the min_trans parameters.
4720 * 0 is returned if another key is found, < 0 if there are any errors
4721 * and 1 is returned if there are no higher keys in the tree
4723 * path->keep_locks should be set to 1 on the search made before
4724 * calling this function.
4726 int btrfs_find_next_key(struct btrfs_root *root, struct btrfs_path *path,
4727 struct btrfs_key *key, int level, u64 min_trans)
4730 struct extent_buffer *c;
4732 WARN_ON(!path->keep_locks && !path->skip_locking);
4733 while (level < BTRFS_MAX_LEVEL) {
4734 if (!path->nodes[level])
4737 slot = path->slots[level] + 1;
4738 c = path->nodes[level];
4740 if (slot >= btrfs_header_nritems(c)) {
4743 struct btrfs_key cur_key;
4744 if (level + 1 >= BTRFS_MAX_LEVEL ||
4745 !path->nodes[level + 1])
4748 if (path->locks[level + 1] || path->skip_locking) {
4753 slot = btrfs_header_nritems(c) - 1;
4755 btrfs_item_key_to_cpu(c, &cur_key, slot);
4757 btrfs_node_key_to_cpu(c, &cur_key, slot);
4759 orig_lowest = path->lowest_level;
4760 btrfs_release_path(path);
4761 path->lowest_level = level;
4762 ret = btrfs_search_slot(NULL, root, &cur_key, path,
4764 path->lowest_level = orig_lowest;
4768 c = path->nodes[level];
4769 slot = path->slots[level];
4776 btrfs_item_key_to_cpu(c, key, slot);
4778 u64 gen = btrfs_node_ptr_generation(c, slot);
4780 if (gen < min_trans) {
4784 btrfs_node_key_to_cpu(c, key, slot);
4791 int btrfs_next_old_leaf(struct btrfs_root *root, struct btrfs_path *path,
4796 struct extent_buffer *c;
4797 struct extent_buffer *next;
4798 struct btrfs_fs_info *fs_info = root->fs_info;
4799 struct btrfs_key key;
4800 bool need_commit_sem = false;
4806 * The nowait semantics are used only for write paths, where we don't
4807 * use the tree mod log and sequence numbers.
4810 ASSERT(!path->nowait);
4812 nritems = btrfs_header_nritems(path->nodes[0]);
4816 btrfs_item_key_to_cpu(path->nodes[0], &key, nritems - 1);
4820 btrfs_release_path(path);
4822 path->keep_locks = 1;
4825 ret = btrfs_search_old_slot(root, &key, path, time_seq);
4827 if (path->need_commit_sem) {
4828 path->need_commit_sem = 0;
4829 need_commit_sem = true;
4831 if (!down_read_trylock(&fs_info->commit_root_sem)) {
4836 down_read(&fs_info->commit_root_sem);
4839 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4841 path->keep_locks = 0;
4846 nritems = btrfs_header_nritems(path->nodes[0]);
4848 * by releasing the path above we dropped all our locks. A balance
4849 * could have added more items next to the key that used to be
4850 * at the very end of the block. So, check again here and
4851 * advance the path if there are now more items available.
4853 if (nritems > 0 && path->slots[0] < nritems - 1) {
4860 * So the above check misses one case:
4861 * - after releasing the path above, someone has removed the item that
4862 * used to be at the very end of the block, and balance between leafs
4863 * gets another one with bigger key.offset to replace it.
4865 * This one should be returned as well, or we can get leaf corruption
4866 * later(esp. in __btrfs_drop_extents()).
4868 * And a bit more explanation about this check,
4869 * with ret > 0, the key isn't found, the path points to the slot
4870 * where it should be inserted, so the path->slots[0] item must be the
4873 if (nritems > 0 && ret > 0 && path->slots[0] == nritems - 1) {
4878 while (level < BTRFS_MAX_LEVEL) {
4879 if (!path->nodes[level]) {
4884 slot = path->slots[level] + 1;
4885 c = path->nodes[level];
4886 if (slot >= btrfs_header_nritems(c)) {
4888 if (level == BTRFS_MAX_LEVEL) {
4897 * Our current level is where we're going to start from, and to
4898 * make sure lockdep doesn't complain we need to drop our locks
4899 * and nodes from 0 to our current level.
4901 for (i = 0; i < level; i++) {
4902 if (path->locks[level]) {
4903 btrfs_tree_read_unlock(path->nodes[i]);
4906 free_extent_buffer(path->nodes[i]);
4907 path->nodes[i] = NULL;
4911 ret = read_block_for_search(root, path, &next, level,
4913 if (ret == -EAGAIN && !path->nowait)
4917 btrfs_release_path(path);
4921 if (!path->skip_locking) {
4922 ret = btrfs_try_tree_read_lock(next);
4923 if (!ret && path->nowait) {
4927 if (!ret && time_seq) {
4929 * If we don't get the lock, we may be racing
4930 * with push_leaf_left, holding that lock while
4931 * itself waiting for the leaf we've currently
4932 * locked. To solve this situation, we give up
4933 * on our lock and cycle.
4935 free_extent_buffer(next);
4936 btrfs_release_path(path);
4941 btrfs_tree_read_lock(next);
4945 path->slots[level] = slot;
4948 path->nodes[level] = next;
4949 path->slots[level] = 0;
4950 if (!path->skip_locking)
4951 path->locks[level] = BTRFS_READ_LOCK;
4955 ret = read_block_for_search(root, path, &next, level,
4957 if (ret == -EAGAIN && !path->nowait)
4961 btrfs_release_path(path);
4965 if (!path->skip_locking) {
4967 if (!btrfs_try_tree_read_lock(next)) {
4972 btrfs_tree_read_lock(next);
4978 unlock_up(path, 0, 1, 0, NULL);
4979 if (need_commit_sem) {
4982 path->need_commit_sem = 1;
4983 ret2 = finish_need_commit_sem_search(path);
4984 up_read(&fs_info->commit_root_sem);
4992 int btrfs_next_old_item(struct btrfs_root *root, struct btrfs_path *path, u64 time_seq)
4995 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0]))
4996 return btrfs_next_old_leaf(root, path, time_seq);
5001 * this uses btrfs_prev_leaf to walk backwards in the tree, and keeps
5002 * searching until it gets past min_objectid or finds an item of 'type'
5004 * returns 0 if something is found, 1 if nothing was found and < 0 on error
5006 int btrfs_previous_item(struct btrfs_root *root,
5007 struct btrfs_path *path, u64 min_objectid,
5010 struct btrfs_key found_key;
5011 struct extent_buffer *leaf;
5016 if (path->slots[0] == 0) {
5017 ret = btrfs_prev_leaf(root, path);
5023 leaf = path->nodes[0];
5024 nritems = btrfs_header_nritems(leaf);
5027 if (path->slots[0] == nritems)
5030 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5031 if (found_key.objectid < min_objectid)
5033 if (found_key.type == type)
5035 if (found_key.objectid == min_objectid &&
5036 found_key.type < type)
5043 * search in extent tree to find a previous Metadata/Data extent item with
5046 * returns 0 if something is found, 1 if nothing was found and < 0 on error
5048 int btrfs_previous_extent_item(struct btrfs_root *root,
5049 struct btrfs_path *path, u64 min_objectid)
5051 struct btrfs_key found_key;
5052 struct extent_buffer *leaf;
5057 if (path->slots[0] == 0) {
5058 ret = btrfs_prev_leaf(root, path);
5064 leaf = path->nodes[0];
5065 nritems = btrfs_header_nritems(leaf);
5068 if (path->slots[0] == nritems)
5071 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5072 if (found_key.objectid < min_objectid)
5074 if (found_key.type == BTRFS_EXTENT_ITEM_KEY ||
5075 found_key.type == BTRFS_METADATA_ITEM_KEY)
5077 if (found_key.objectid == min_objectid &&
5078 found_key.type < BTRFS_EXTENT_ITEM_KEY)
5084 int __init btrfs_ctree_init(void)
5086 btrfs_path_cachep = KMEM_CACHE(btrfs_path, 0);
5087 if (!btrfs_path_cachep)
5092 void __cold btrfs_ctree_exit(void)
5094 kmem_cache_destroy(btrfs_path_cachep);