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);
40 static void del_ptr(struct btrfs_root *root, struct btrfs_path *path,
43 static const struct btrfs_csums {
46 const char driver[12];
48 [BTRFS_CSUM_TYPE_CRC32] = { .size = 4, .name = "crc32c" },
49 [BTRFS_CSUM_TYPE_XXHASH] = { .size = 8, .name = "xxhash64" },
50 [BTRFS_CSUM_TYPE_SHA256] = { .size = 32, .name = "sha256" },
51 [BTRFS_CSUM_TYPE_BLAKE2] = { .size = 32, .name = "blake2b",
52 .driver = "blake2b-256" },
56 * The leaf data grows from end-to-front in the node. this returns the address
57 * of the start of the last item, which is the stop of the leaf data stack.
59 static unsigned int leaf_data_end(const struct extent_buffer *leaf)
61 u32 nr = btrfs_header_nritems(leaf);
64 return BTRFS_LEAF_DATA_SIZE(leaf->fs_info);
65 return btrfs_item_offset(leaf, nr - 1);
69 * Move data in a @leaf (using memmove, safe for overlapping ranges).
71 * @leaf: leaf that we're doing a memmove on
72 * @dst_offset: item data offset we're moving to
73 * @src_offset: item data offset were' moving from
74 * @len: length of the data we're moving
76 * Wrapper around memmove_extent_buffer() that takes into account the header on
77 * the leaf. The btrfs_item offset's start directly after the header, so we
78 * have to adjust any offsets to account for the header in the leaf. This
79 * handles that math to simplify the callers.
81 static inline void memmove_leaf_data(const struct extent_buffer *leaf,
82 unsigned long dst_offset,
83 unsigned long src_offset,
86 memmove_extent_buffer(leaf, btrfs_item_nr_offset(leaf, 0) + dst_offset,
87 btrfs_item_nr_offset(leaf, 0) + src_offset, len);
91 * Copy item data from @src into @dst at the given @offset.
93 * @dst: destination leaf that we're copying into
94 * @src: source leaf that we're copying from
95 * @dst_offset: item data offset we're copying to
96 * @src_offset: item data offset were' copying from
97 * @len: length of the data we're copying
99 * Wrapper around copy_extent_buffer() that takes into account the header on
100 * the leaf. The btrfs_item offset's start directly after the header, so we
101 * have to adjust any offsets to account for the header in the leaf. This
102 * handles that math to simplify the callers.
104 static inline void copy_leaf_data(const struct extent_buffer *dst,
105 const struct extent_buffer *src,
106 unsigned long dst_offset,
107 unsigned long src_offset, unsigned long len)
109 copy_extent_buffer(dst, src, btrfs_item_nr_offset(dst, 0) + dst_offset,
110 btrfs_item_nr_offset(src, 0) + src_offset, len);
114 * Move items in a @leaf (using memmove).
116 * @dst: destination leaf for the items
117 * @dst_item: the item nr we're copying into
118 * @src_item: the item nr we're copying from
119 * @nr_items: the number of items to copy
121 * Wrapper around memmove_extent_buffer() that does the math to get the
122 * appropriate offsets into the leaf from the item numbers.
124 static inline void memmove_leaf_items(const struct extent_buffer *leaf,
125 int dst_item, int src_item, int nr_items)
127 memmove_extent_buffer(leaf, btrfs_item_nr_offset(leaf, dst_item),
128 btrfs_item_nr_offset(leaf, src_item),
129 nr_items * sizeof(struct btrfs_item));
133 * Copy items from @src into @dst at the given @offset.
135 * @dst: destination leaf for the items
136 * @src: source leaf for the items
137 * @dst_item: the item nr we're copying into
138 * @src_item: the item nr we're copying from
139 * @nr_items: the number of items to copy
141 * Wrapper around copy_extent_buffer() that does the math to get the
142 * appropriate offsets into the leaf from the item numbers.
144 static inline void copy_leaf_items(const struct extent_buffer *dst,
145 const struct extent_buffer *src,
146 int dst_item, int src_item, int nr_items)
148 copy_extent_buffer(dst, src, btrfs_item_nr_offset(dst, dst_item),
149 btrfs_item_nr_offset(src, src_item),
150 nr_items * sizeof(struct btrfs_item));
153 int btrfs_super_csum_size(const struct btrfs_super_block *s)
155 u16 t = btrfs_super_csum_type(s);
157 * csum type is validated at mount time
159 return btrfs_csums[t].size;
162 const char *btrfs_super_csum_name(u16 csum_type)
164 /* csum type is validated at mount time */
165 return btrfs_csums[csum_type].name;
169 * Return driver name if defined, otherwise the name that's also a valid driver
172 const char *btrfs_super_csum_driver(u16 csum_type)
174 /* csum type is validated at mount time */
175 return btrfs_csums[csum_type].driver[0] ?
176 btrfs_csums[csum_type].driver :
177 btrfs_csums[csum_type].name;
180 size_t __attribute_const__ btrfs_get_num_csums(void)
182 return ARRAY_SIZE(btrfs_csums);
185 struct btrfs_path *btrfs_alloc_path(void)
189 return kmem_cache_zalloc(btrfs_path_cachep, GFP_NOFS);
192 /* this also releases the path */
193 void btrfs_free_path(struct btrfs_path *p)
197 btrfs_release_path(p);
198 kmem_cache_free(btrfs_path_cachep, p);
202 * path release drops references on the extent buffers in the path
203 * and it drops any locks held by this path
205 * It is safe to call this on paths that no locks or extent buffers held.
207 noinline void btrfs_release_path(struct btrfs_path *p)
211 for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
216 btrfs_tree_unlock_rw(p->nodes[i], p->locks[i]);
219 free_extent_buffer(p->nodes[i]);
225 * We want the transaction abort to print stack trace only for errors where the
226 * cause could be a bug, eg. due to ENOSPC, and not for common errors that are
227 * caused by external factors.
229 bool __cold abort_should_print_stack(int errno)
241 * safely gets a reference on the root node of a tree. A lock
242 * is not taken, so a concurrent writer may put a different node
243 * at the root of the tree. See btrfs_lock_root_node for the
246 * The extent buffer returned by this has a reference taken, so
247 * it won't disappear. It may stop being the root of the tree
248 * at any time because there are no locks held.
250 struct extent_buffer *btrfs_root_node(struct btrfs_root *root)
252 struct extent_buffer *eb;
256 eb = rcu_dereference(root->node);
259 * RCU really hurts here, we could free up the root node because
260 * it was COWed but we may not get the new root node yet so do
261 * the inc_not_zero dance and if it doesn't work then
262 * synchronize_rcu and try again.
264 if (atomic_inc_not_zero(&eb->refs)) {
275 * Cowonly root (not-shareable trees, everything not subvolume or reloc roots),
276 * just get put onto a simple dirty list. Transaction walks this list to make
277 * sure they get properly updated on disk.
279 static void add_root_to_dirty_list(struct btrfs_root *root)
281 struct btrfs_fs_info *fs_info = root->fs_info;
283 if (test_bit(BTRFS_ROOT_DIRTY, &root->state) ||
284 !test_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state))
287 spin_lock(&fs_info->trans_lock);
288 if (!test_and_set_bit(BTRFS_ROOT_DIRTY, &root->state)) {
289 /* Want the extent tree to be the last on the list */
290 if (root->root_key.objectid == BTRFS_EXTENT_TREE_OBJECTID)
291 list_move_tail(&root->dirty_list,
292 &fs_info->dirty_cowonly_roots);
294 list_move(&root->dirty_list,
295 &fs_info->dirty_cowonly_roots);
297 spin_unlock(&fs_info->trans_lock);
301 * used by snapshot creation to make a copy of a root for a tree with
302 * a given objectid. The buffer with the new root node is returned in
303 * cow_ret, and this func returns zero on success or a negative error code.
305 int btrfs_copy_root(struct btrfs_trans_handle *trans,
306 struct btrfs_root *root,
307 struct extent_buffer *buf,
308 struct extent_buffer **cow_ret, u64 new_root_objectid)
310 struct btrfs_fs_info *fs_info = root->fs_info;
311 struct extent_buffer *cow;
314 struct btrfs_disk_key disk_key;
316 WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
317 trans->transid != fs_info->running_transaction->transid);
318 WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
319 trans->transid != root->last_trans);
321 level = btrfs_header_level(buf);
323 btrfs_item_key(buf, &disk_key, 0);
325 btrfs_node_key(buf, &disk_key, 0);
327 cow = btrfs_alloc_tree_block(trans, root, 0, new_root_objectid,
328 &disk_key, level, buf->start, 0,
329 BTRFS_NESTING_NEW_ROOT);
333 copy_extent_buffer_full(cow, buf);
334 btrfs_set_header_bytenr(cow, cow->start);
335 btrfs_set_header_generation(cow, trans->transid);
336 btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
337 btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
338 BTRFS_HEADER_FLAG_RELOC);
339 if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
340 btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
342 btrfs_set_header_owner(cow, new_root_objectid);
344 write_extent_buffer_fsid(cow, fs_info->fs_devices->metadata_uuid);
346 WARN_ON(btrfs_header_generation(buf) > trans->transid);
347 if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
348 ret = btrfs_inc_ref(trans, root, cow, 1);
350 ret = btrfs_inc_ref(trans, root, cow, 0);
352 btrfs_tree_unlock(cow);
353 free_extent_buffer(cow);
354 btrfs_abort_transaction(trans, ret);
358 btrfs_mark_buffer_dirty(cow);
364 * check if the tree block can be shared by multiple trees
366 int btrfs_block_can_be_shared(struct btrfs_root *root,
367 struct extent_buffer *buf)
370 * Tree blocks not in shareable trees and tree roots are never shared.
371 * If a block was allocated after the last snapshot and the block was
372 * not allocated by tree relocation, we know the block is not shared.
374 if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
375 buf != root->node && buf != root->commit_root &&
376 (btrfs_header_generation(buf) <=
377 btrfs_root_last_snapshot(&root->root_item) ||
378 btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)))
384 static noinline int update_ref_for_cow(struct btrfs_trans_handle *trans,
385 struct btrfs_root *root,
386 struct extent_buffer *buf,
387 struct extent_buffer *cow,
390 struct btrfs_fs_info *fs_info = root->fs_info;
398 * Backrefs update rules:
400 * Always use full backrefs for extent pointers in tree block
401 * allocated by tree relocation.
403 * If a shared tree block is no longer referenced by its owner
404 * tree (btrfs_header_owner(buf) == root->root_key.objectid),
405 * use full backrefs for extent pointers in tree block.
407 * If a tree block is been relocating
408 * (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID),
409 * use full backrefs for extent pointers in tree block.
410 * The reason for this is some operations (such as drop tree)
411 * are only allowed for blocks use full backrefs.
414 if (btrfs_block_can_be_shared(root, buf)) {
415 ret = btrfs_lookup_extent_info(trans, fs_info, buf->start,
416 btrfs_header_level(buf), 1,
422 btrfs_handle_fs_error(fs_info, ret, NULL);
427 if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
428 btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
429 flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
434 owner = btrfs_header_owner(buf);
435 BUG_ON(owner == BTRFS_TREE_RELOC_OBJECTID &&
436 !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
439 if ((owner == root->root_key.objectid ||
440 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) &&
441 !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)) {
442 ret = btrfs_inc_ref(trans, root, buf, 1);
446 if (root->root_key.objectid ==
447 BTRFS_TREE_RELOC_OBJECTID) {
448 ret = btrfs_dec_ref(trans, root, buf, 0);
451 ret = btrfs_inc_ref(trans, root, cow, 1);
455 new_flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
458 if (root->root_key.objectid ==
459 BTRFS_TREE_RELOC_OBJECTID)
460 ret = btrfs_inc_ref(trans, root, cow, 1);
462 ret = btrfs_inc_ref(trans, root, cow, 0);
466 if (new_flags != 0) {
467 int level = btrfs_header_level(buf);
469 ret = btrfs_set_disk_extent_flags(trans, buf,
475 if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
476 if (root->root_key.objectid ==
477 BTRFS_TREE_RELOC_OBJECTID)
478 ret = btrfs_inc_ref(trans, root, cow, 1);
480 ret = btrfs_inc_ref(trans, root, cow, 0);
483 ret = btrfs_dec_ref(trans, root, buf, 1);
487 btrfs_clear_buffer_dirty(trans, buf);
494 * does the dirty work in cow of a single block. The parent block (if
495 * supplied) is updated to point to the new cow copy. The new buffer is marked
496 * dirty and returned locked. If you modify the block it needs to be marked
499 * search_start -- an allocation hint for the new block
501 * empty_size -- a hint that you plan on doing more cow. This is the size in
502 * bytes the allocator should try to find free next to the block it returns.
503 * This is just a hint and may be ignored by the allocator.
505 static noinline int __btrfs_cow_block(struct btrfs_trans_handle *trans,
506 struct btrfs_root *root,
507 struct extent_buffer *buf,
508 struct extent_buffer *parent, int parent_slot,
509 struct extent_buffer **cow_ret,
510 u64 search_start, u64 empty_size,
511 enum btrfs_lock_nesting nest)
513 struct btrfs_fs_info *fs_info = root->fs_info;
514 struct btrfs_disk_key disk_key;
515 struct extent_buffer *cow;
519 u64 parent_start = 0;
524 btrfs_assert_tree_write_locked(buf);
526 WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
527 trans->transid != fs_info->running_transaction->transid);
528 WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
529 trans->transid != root->last_trans);
531 level = btrfs_header_level(buf);
534 btrfs_item_key(buf, &disk_key, 0);
536 btrfs_node_key(buf, &disk_key, 0);
538 if ((root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) && parent)
539 parent_start = parent->start;
541 cow = btrfs_alloc_tree_block(trans, root, parent_start,
542 root->root_key.objectid, &disk_key, level,
543 search_start, empty_size, nest);
547 /* cow is set to blocking by btrfs_init_new_buffer */
549 copy_extent_buffer_full(cow, buf);
550 btrfs_set_header_bytenr(cow, cow->start);
551 btrfs_set_header_generation(cow, trans->transid);
552 btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
553 btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
554 BTRFS_HEADER_FLAG_RELOC);
555 if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
556 btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
558 btrfs_set_header_owner(cow, root->root_key.objectid);
560 write_extent_buffer_fsid(cow, fs_info->fs_devices->metadata_uuid);
562 ret = update_ref_for_cow(trans, root, buf, cow, &last_ref);
564 btrfs_tree_unlock(cow);
565 free_extent_buffer(cow);
566 btrfs_abort_transaction(trans, ret);
570 if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state)) {
571 ret = btrfs_reloc_cow_block(trans, root, buf, cow);
573 btrfs_tree_unlock(cow);
574 free_extent_buffer(cow);
575 btrfs_abort_transaction(trans, ret);
580 if (buf == root->node) {
581 WARN_ON(parent && parent != buf);
582 if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
583 btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
584 parent_start = buf->start;
586 atomic_inc(&cow->refs);
587 ret = btrfs_tree_mod_log_insert_root(root->node, cow, true);
589 rcu_assign_pointer(root->node, cow);
591 btrfs_free_tree_block(trans, btrfs_root_id(root), buf,
592 parent_start, last_ref);
593 free_extent_buffer(buf);
594 add_root_to_dirty_list(root);
596 WARN_ON(trans->transid != btrfs_header_generation(parent));
597 btrfs_tree_mod_log_insert_key(parent, parent_slot,
598 BTRFS_MOD_LOG_KEY_REPLACE);
599 btrfs_set_node_blockptr(parent, parent_slot,
601 btrfs_set_node_ptr_generation(parent, parent_slot,
603 btrfs_mark_buffer_dirty(parent);
605 ret = btrfs_tree_mod_log_free_eb(buf);
607 btrfs_tree_unlock(cow);
608 free_extent_buffer(cow);
609 btrfs_abort_transaction(trans, ret);
613 btrfs_free_tree_block(trans, btrfs_root_id(root), buf,
614 parent_start, last_ref);
617 btrfs_tree_unlock(buf);
618 free_extent_buffer_stale(buf);
619 btrfs_mark_buffer_dirty(cow);
624 static inline int should_cow_block(struct btrfs_trans_handle *trans,
625 struct btrfs_root *root,
626 struct extent_buffer *buf)
628 if (btrfs_is_testing(root->fs_info))
631 /* Ensure we can see the FORCE_COW bit */
632 smp_mb__before_atomic();
635 * We do not need to cow a block if
636 * 1) this block is not created or changed in this transaction;
637 * 2) this block does not belong to TREE_RELOC tree;
638 * 3) the root is not forced COW.
640 * What is forced COW:
641 * when we create snapshot during committing the transaction,
642 * after we've finished copying src root, we must COW the shared
643 * block to ensure the metadata consistency.
645 if (btrfs_header_generation(buf) == trans->transid &&
646 !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN) &&
647 !(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
648 btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)) &&
649 !test_bit(BTRFS_ROOT_FORCE_COW, &root->state))
655 * cows a single block, see __btrfs_cow_block for the real work.
656 * This version of it has extra checks so that a block isn't COWed more than
657 * once per transaction, as long as it hasn't been written yet
659 noinline int btrfs_cow_block(struct btrfs_trans_handle *trans,
660 struct btrfs_root *root, struct extent_buffer *buf,
661 struct extent_buffer *parent, int parent_slot,
662 struct extent_buffer **cow_ret,
663 enum btrfs_lock_nesting nest)
665 struct btrfs_fs_info *fs_info = root->fs_info;
669 if (test_bit(BTRFS_ROOT_DELETING, &root->state))
671 "COW'ing blocks on a fs root that's being dropped");
673 if (trans->transaction != fs_info->running_transaction)
674 WARN(1, KERN_CRIT "trans %llu running %llu\n",
676 fs_info->running_transaction->transid);
678 if (trans->transid != fs_info->generation)
679 WARN(1, KERN_CRIT "trans %llu running %llu\n",
680 trans->transid, fs_info->generation);
682 if (!should_cow_block(trans, root, buf)) {
687 search_start = buf->start & ~((u64)SZ_1G - 1);
690 * Before CoWing this block for later modification, check if it's
691 * the subtree root and do the delayed subtree trace if needed.
693 * Also We don't care about the error, as it's handled internally.
695 btrfs_qgroup_trace_subtree_after_cow(trans, root, buf);
696 ret = __btrfs_cow_block(trans, root, buf, parent,
697 parent_slot, cow_ret, search_start, 0, nest);
699 trace_btrfs_cow_block(root, buf, *cow_ret);
703 ALLOW_ERROR_INJECTION(btrfs_cow_block, ERRNO);
706 * helper function for defrag to decide if two blocks pointed to by a
707 * node are actually close by
709 static int close_blocks(u64 blocknr, u64 other, u32 blocksize)
711 if (blocknr < other && other - (blocknr + blocksize) < 32768)
713 if (blocknr > other && blocknr - (other + blocksize) < 32768)
718 #ifdef __LITTLE_ENDIAN
721 * Compare two keys, on little-endian the disk order is same as CPU order and
722 * we can avoid the conversion.
724 static int comp_keys(const struct btrfs_disk_key *disk_key,
725 const struct btrfs_key *k2)
727 const struct btrfs_key *k1 = (const struct btrfs_key *)disk_key;
729 return btrfs_comp_cpu_keys(k1, k2);
735 * compare two keys in a memcmp fashion
737 static int comp_keys(const struct btrfs_disk_key *disk,
738 const struct btrfs_key *k2)
742 btrfs_disk_key_to_cpu(&k1, disk);
744 return btrfs_comp_cpu_keys(&k1, k2);
749 * same as comp_keys only with two btrfs_key's
751 int __pure btrfs_comp_cpu_keys(const struct btrfs_key *k1, const struct btrfs_key *k2)
753 if (k1->objectid > k2->objectid)
755 if (k1->objectid < k2->objectid)
757 if (k1->type > k2->type)
759 if (k1->type < k2->type)
761 if (k1->offset > k2->offset)
763 if (k1->offset < k2->offset)
769 * this is used by the defrag code to go through all the
770 * leaves pointed to by a node and reallocate them so that
771 * disk order is close to key order
773 int btrfs_realloc_node(struct btrfs_trans_handle *trans,
774 struct btrfs_root *root, struct extent_buffer *parent,
775 int start_slot, u64 *last_ret,
776 struct btrfs_key *progress)
778 struct btrfs_fs_info *fs_info = root->fs_info;
779 struct extent_buffer *cur;
781 u64 search_start = *last_ret;
789 int progress_passed = 0;
790 struct btrfs_disk_key disk_key;
792 WARN_ON(trans->transaction != fs_info->running_transaction);
793 WARN_ON(trans->transid != fs_info->generation);
795 parent_nritems = btrfs_header_nritems(parent);
796 blocksize = fs_info->nodesize;
797 end_slot = parent_nritems - 1;
799 if (parent_nritems <= 1)
802 for (i = start_slot; i <= end_slot; i++) {
805 btrfs_node_key(parent, &disk_key, i);
806 if (!progress_passed && comp_keys(&disk_key, progress) < 0)
810 blocknr = btrfs_node_blockptr(parent, i);
812 last_block = blocknr;
815 other = btrfs_node_blockptr(parent, i - 1);
816 close = close_blocks(blocknr, other, blocksize);
818 if (!close && i < end_slot) {
819 other = btrfs_node_blockptr(parent, i + 1);
820 close = close_blocks(blocknr, other, blocksize);
823 last_block = blocknr;
827 cur = btrfs_read_node_slot(parent, i);
830 if (search_start == 0)
831 search_start = last_block;
833 btrfs_tree_lock(cur);
834 err = __btrfs_cow_block(trans, root, cur, parent, i,
837 (end_slot - i) * blocksize),
840 btrfs_tree_unlock(cur);
841 free_extent_buffer(cur);
844 search_start = cur->start;
845 last_block = cur->start;
846 *last_ret = search_start;
847 btrfs_tree_unlock(cur);
848 free_extent_buffer(cur);
854 * Search for a key in the given extent_buffer.
856 * The lower boundary for the search is specified by the slot number @first_slot.
857 * Use a value of 0 to search over the whole extent buffer. Works for both
860 * The slot in the extent buffer is returned via @slot. If the key exists in the
861 * extent buffer, then @slot will point to the slot where the key is, otherwise
862 * it points to the slot where you would insert the key.
864 * Slot may point to the total number of items (i.e. one position beyond the last
865 * key) if the key is bigger than the last key in the extent buffer.
867 int btrfs_bin_search(struct extent_buffer *eb, int first_slot,
868 const struct btrfs_key *key, int *slot)
873 * Use unsigned types for the low and high slots, so that we get a more
874 * efficient division in the search loop below.
876 u32 low = first_slot;
877 u32 high = btrfs_header_nritems(eb);
879 const int key_size = sizeof(struct btrfs_disk_key);
881 if (unlikely(low > high)) {
882 btrfs_err(eb->fs_info,
883 "%s: low (%u) > high (%u) eb %llu owner %llu level %d",
884 __func__, low, high, eb->start,
885 btrfs_header_owner(eb), btrfs_header_level(eb));
889 if (btrfs_header_level(eb) == 0) {
890 p = offsetof(struct btrfs_leaf, items);
891 item_size = sizeof(struct btrfs_item);
893 p = offsetof(struct btrfs_node, ptrs);
894 item_size = sizeof(struct btrfs_key_ptr);
899 unsigned long offset;
900 struct btrfs_disk_key *tmp;
901 struct btrfs_disk_key unaligned;
904 mid = (low + high) / 2;
905 offset = p + mid * item_size;
906 oip = offset_in_page(offset);
908 if (oip + key_size <= PAGE_SIZE) {
909 const unsigned long idx = get_eb_page_index(offset);
910 char *kaddr = page_address(eb->pages[idx]);
912 oip = get_eb_offset_in_page(eb, offset);
913 tmp = (struct btrfs_disk_key *)(kaddr + oip);
915 read_extent_buffer(eb, &unaligned, offset, key_size);
919 ret = comp_keys(tmp, key);
934 static void root_add_used(struct btrfs_root *root, u32 size)
936 spin_lock(&root->accounting_lock);
937 btrfs_set_root_used(&root->root_item,
938 btrfs_root_used(&root->root_item) + size);
939 spin_unlock(&root->accounting_lock);
942 static void root_sub_used(struct btrfs_root *root, u32 size)
944 spin_lock(&root->accounting_lock);
945 btrfs_set_root_used(&root->root_item,
946 btrfs_root_used(&root->root_item) - size);
947 spin_unlock(&root->accounting_lock);
950 /* given a node and slot number, this reads the blocks it points to. The
951 * extent buffer is returned with a reference taken (but unlocked).
953 struct extent_buffer *btrfs_read_node_slot(struct extent_buffer *parent,
956 int level = btrfs_header_level(parent);
957 struct btrfs_tree_parent_check check = { 0 };
958 struct extent_buffer *eb;
960 if (slot < 0 || slot >= btrfs_header_nritems(parent))
961 return ERR_PTR(-ENOENT);
965 check.level = level - 1;
966 check.transid = btrfs_node_ptr_generation(parent, slot);
967 check.owner_root = btrfs_header_owner(parent);
968 check.has_first_key = true;
969 btrfs_node_key_to_cpu(parent, &check.first_key, slot);
971 eb = read_tree_block(parent->fs_info, btrfs_node_blockptr(parent, slot),
975 if (!extent_buffer_uptodate(eb)) {
976 free_extent_buffer(eb);
977 return ERR_PTR(-EIO);
984 * node level balancing, used to make sure nodes are in proper order for
985 * item deletion. We balance from the top down, so we have to make sure
986 * that a deletion won't leave an node completely empty later on.
988 static noinline int balance_level(struct btrfs_trans_handle *trans,
989 struct btrfs_root *root,
990 struct btrfs_path *path, int level)
992 struct btrfs_fs_info *fs_info = root->fs_info;
993 struct extent_buffer *right = NULL;
994 struct extent_buffer *mid;
995 struct extent_buffer *left = NULL;
996 struct extent_buffer *parent = NULL;
1000 int orig_slot = path->slots[level];
1005 mid = path->nodes[level];
1007 WARN_ON(path->locks[level] != BTRFS_WRITE_LOCK);
1008 WARN_ON(btrfs_header_generation(mid) != trans->transid);
1010 orig_ptr = btrfs_node_blockptr(mid, orig_slot);
1012 if (level < BTRFS_MAX_LEVEL - 1) {
1013 parent = path->nodes[level + 1];
1014 pslot = path->slots[level + 1];
1018 * deal with the case where there is only one pointer in the root
1019 * by promoting the node below to a root
1022 struct extent_buffer *child;
1024 if (btrfs_header_nritems(mid) != 1)
1027 /* promote the child to a root */
1028 child = btrfs_read_node_slot(mid, 0);
1029 if (IS_ERR(child)) {
1030 ret = PTR_ERR(child);
1031 btrfs_handle_fs_error(fs_info, ret, NULL);
1035 btrfs_tree_lock(child);
1036 ret = btrfs_cow_block(trans, root, child, mid, 0, &child,
1039 btrfs_tree_unlock(child);
1040 free_extent_buffer(child);
1044 ret = btrfs_tree_mod_log_insert_root(root->node, child, true);
1046 rcu_assign_pointer(root->node, child);
1048 add_root_to_dirty_list(root);
1049 btrfs_tree_unlock(child);
1051 path->locks[level] = 0;
1052 path->nodes[level] = NULL;
1053 btrfs_clear_buffer_dirty(trans, mid);
1054 btrfs_tree_unlock(mid);
1055 /* once for the path */
1056 free_extent_buffer(mid);
1058 root_sub_used(root, mid->len);
1059 btrfs_free_tree_block(trans, btrfs_root_id(root), mid, 0, 1);
1060 /* once for the root ptr */
1061 free_extent_buffer_stale(mid);
1064 if (btrfs_header_nritems(mid) >
1065 BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 4)
1069 left = btrfs_read_node_slot(parent, pslot - 1);
1071 ret = PTR_ERR(left);
1076 __btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
1077 wret = btrfs_cow_block(trans, root, left,
1078 parent, pslot - 1, &left,
1079 BTRFS_NESTING_LEFT_COW);
1086 if (pslot + 1 < btrfs_header_nritems(parent)) {
1087 right = btrfs_read_node_slot(parent, pslot + 1);
1088 if (IS_ERR(right)) {
1089 ret = PTR_ERR(right);
1094 __btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
1095 wret = btrfs_cow_block(trans, root, right,
1096 parent, pslot + 1, &right,
1097 BTRFS_NESTING_RIGHT_COW);
1104 /* first, try to make some room in the middle buffer */
1106 orig_slot += btrfs_header_nritems(left);
1107 wret = push_node_left(trans, left, mid, 1);
1113 * then try to empty the right most buffer into the middle
1116 wret = push_node_left(trans, mid, right, 1);
1117 if (wret < 0 && wret != -ENOSPC)
1119 if (btrfs_header_nritems(right) == 0) {
1120 btrfs_clear_buffer_dirty(trans, right);
1121 btrfs_tree_unlock(right);
1122 del_ptr(root, path, level + 1, pslot + 1);
1123 root_sub_used(root, right->len);
1124 btrfs_free_tree_block(trans, btrfs_root_id(root), right,
1126 free_extent_buffer_stale(right);
1129 struct btrfs_disk_key right_key;
1130 btrfs_node_key(right, &right_key, 0);
1131 ret = btrfs_tree_mod_log_insert_key(parent, pslot + 1,
1132 BTRFS_MOD_LOG_KEY_REPLACE);
1134 btrfs_set_node_key(parent, &right_key, pslot + 1);
1135 btrfs_mark_buffer_dirty(parent);
1138 if (btrfs_header_nritems(mid) == 1) {
1140 * we're not allowed to leave a node with one item in the
1141 * tree during a delete. A deletion from lower in the tree
1142 * could try to delete the only pointer in this node.
1143 * So, pull some keys from the left.
1144 * There has to be a left pointer at this point because
1145 * otherwise we would have pulled some pointers from the
1150 btrfs_handle_fs_error(fs_info, ret, NULL);
1153 wret = balance_node_right(trans, mid, left);
1159 wret = push_node_left(trans, left, mid, 1);
1165 if (btrfs_header_nritems(mid) == 0) {
1166 btrfs_clear_buffer_dirty(trans, mid);
1167 btrfs_tree_unlock(mid);
1168 del_ptr(root, path, level + 1, pslot);
1169 root_sub_used(root, mid->len);
1170 btrfs_free_tree_block(trans, btrfs_root_id(root), mid, 0, 1);
1171 free_extent_buffer_stale(mid);
1174 /* update the parent key to reflect our changes */
1175 struct btrfs_disk_key mid_key;
1176 btrfs_node_key(mid, &mid_key, 0);
1177 ret = btrfs_tree_mod_log_insert_key(parent, pslot,
1178 BTRFS_MOD_LOG_KEY_REPLACE);
1180 btrfs_set_node_key(parent, &mid_key, pslot);
1181 btrfs_mark_buffer_dirty(parent);
1184 /* update the path */
1186 if (btrfs_header_nritems(left) > orig_slot) {
1187 atomic_inc(&left->refs);
1188 /* left was locked after cow */
1189 path->nodes[level] = left;
1190 path->slots[level + 1] -= 1;
1191 path->slots[level] = orig_slot;
1193 btrfs_tree_unlock(mid);
1194 free_extent_buffer(mid);
1197 orig_slot -= btrfs_header_nritems(left);
1198 path->slots[level] = orig_slot;
1201 /* double check we haven't messed things up */
1203 btrfs_node_blockptr(path->nodes[level], path->slots[level]))
1207 btrfs_tree_unlock(right);
1208 free_extent_buffer(right);
1211 if (path->nodes[level] != left)
1212 btrfs_tree_unlock(left);
1213 free_extent_buffer(left);
1218 /* Node balancing for insertion. Here we only split or push nodes around
1219 * when they are completely full. This is also done top down, so we
1220 * have to be pessimistic.
1222 static noinline int push_nodes_for_insert(struct btrfs_trans_handle *trans,
1223 struct btrfs_root *root,
1224 struct btrfs_path *path, int level)
1226 struct btrfs_fs_info *fs_info = root->fs_info;
1227 struct extent_buffer *right = NULL;
1228 struct extent_buffer *mid;
1229 struct extent_buffer *left = NULL;
1230 struct extent_buffer *parent = NULL;
1234 int orig_slot = path->slots[level];
1239 mid = path->nodes[level];
1240 WARN_ON(btrfs_header_generation(mid) != trans->transid);
1242 if (level < BTRFS_MAX_LEVEL - 1) {
1243 parent = path->nodes[level + 1];
1244 pslot = path->slots[level + 1];
1250 /* first, try to make some room in the middle buffer */
1254 left = btrfs_read_node_slot(parent, pslot - 1);
1256 return PTR_ERR(left);
1258 __btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
1260 left_nr = btrfs_header_nritems(left);
1261 if (left_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
1264 ret = btrfs_cow_block(trans, root, left, parent,
1266 BTRFS_NESTING_LEFT_COW);
1270 wret = push_node_left(trans, left, mid, 0);
1276 struct btrfs_disk_key disk_key;
1277 orig_slot += left_nr;
1278 btrfs_node_key(mid, &disk_key, 0);
1279 ret = btrfs_tree_mod_log_insert_key(parent, pslot,
1280 BTRFS_MOD_LOG_KEY_REPLACE);
1282 btrfs_set_node_key(parent, &disk_key, pslot);
1283 btrfs_mark_buffer_dirty(parent);
1284 if (btrfs_header_nritems(left) > orig_slot) {
1285 path->nodes[level] = left;
1286 path->slots[level + 1] -= 1;
1287 path->slots[level] = orig_slot;
1288 btrfs_tree_unlock(mid);
1289 free_extent_buffer(mid);
1292 btrfs_header_nritems(left);
1293 path->slots[level] = orig_slot;
1294 btrfs_tree_unlock(left);
1295 free_extent_buffer(left);
1299 btrfs_tree_unlock(left);
1300 free_extent_buffer(left);
1304 * then try to empty the right most buffer into the middle
1306 if (pslot + 1 < btrfs_header_nritems(parent)) {
1309 right = btrfs_read_node_slot(parent, pslot + 1);
1311 return PTR_ERR(right);
1313 __btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
1315 right_nr = btrfs_header_nritems(right);
1316 if (right_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
1319 ret = btrfs_cow_block(trans, root, right,
1321 &right, BTRFS_NESTING_RIGHT_COW);
1325 wret = balance_node_right(trans, right, mid);
1331 struct btrfs_disk_key disk_key;
1333 btrfs_node_key(right, &disk_key, 0);
1334 ret = btrfs_tree_mod_log_insert_key(parent, pslot + 1,
1335 BTRFS_MOD_LOG_KEY_REPLACE);
1337 btrfs_set_node_key(parent, &disk_key, pslot + 1);
1338 btrfs_mark_buffer_dirty(parent);
1340 if (btrfs_header_nritems(mid) <= orig_slot) {
1341 path->nodes[level] = right;
1342 path->slots[level + 1] += 1;
1343 path->slots[level] = orig_slot -
1344 btrfs_header_nritems(mid);
1345 btrfs_tree_unlock(mid);
1346 free_extent_buffer(mid);
1348 btrfs_tree_unlock(right);
1349 free_extent_buffer(right);
1353 btrfs_tree_unlock(right);
1354 free_extent_buffer(right);
1360 * readahead one full node of leaves, finding things that are close
1361 * to the block in 'slot', and triggering ra on them.
1363 static void reada_for_search(struct btrfs_fs_info *fs_info,
1364 struct btrfs_path *path,
1365 int level, int slot, u64 objectid)
1367 struct extent_buffer *node;
1368 struct btrfs_disk_key disk_key;
1378 if (level != 1 && path->reada != READA_FORWARD_ALWAYS)
1381 if (!path->nodes[level])
1384 node = path->nodes[level];
1387 * Since the time between visiting leaves is much shorter than the time
1388 * between visiting nodes, limit read ahead of nodes to 1, to avoid too
1389 * much IO at once (possibly random).
1391 if (path->reada == READA_FORWARD_ALWAYS) {
1393 nread_max = node->fs_info->nodesize;
1395 nread_max = SZ_128K;
1400 search = btrfs_node_blockptr(node, slot);
1401 blocksize = fs_info->nodesize;
1402 if (path->reada != READA_FORWARD_ALWAYS) {
1403 struct extent_buffer *eb;
1405 eb = find_extent_buffer(fs_info, search);
1407 free_extent_buffer(eb);
1414 nritems = btrfs_header_nritems(node);
1418 if (path->reada == READA_BACK) {
1422 } else if (path->reada == READA_FORWARD ||
1423 path->reada == READA_FORWARD_ALWAYS) {
1428 if (path->reada == READA_BACK && objectid) {
1429 btrfs_node_key(node, &disk_key, nr);
1430 if (btrfs_disk_key_objectid(&disk_key) != objectid)
1433 search = btrfs_node_blockptr(node, nr);
1434 if (path->reada == READA_FORWARD_ALWAYS ||
1435 (search <= target && target - search <= 65536) ||
1436 (search > target && search - target <= 65536)) {
1437 btrfs_readahead_node_child(node, nr);
1441 if (nread > nread_max || nscan > 32)
1446 static noinline void reada_for_balance(struct btrfs_path *path, int level)
1448 struct extent_buffer *parent;
1452 parent = path->nodes[level + 1];
1456 nritems = btrfs_header_nritems(parent);
1457 slot = path->slots[level + 1];
1460 btrfs_readahead_node_child(parent, slot - 1);
1461 if (slot + 1 < nritems)
1462 btrfs_readahead_node_child(parent, slot + 1);
1467 * when we walk down the tree, it is usually safe to unlock the higher layers
1468 * in the tree. The exceptions are when our path goes through slot 0, because
1469 * operations on the tree might require changing key pointers higher up in the
1472 * callers might also have set path->keep_locks, which tells this code to keep
1473 * the lock if the path points to the last slot in the block. This is part of
1474 * walking through the tree, and selecting the next slot in the higher block.
1476 * lowest_unlock sets the lowest level in the tree we're allowed to unlock. so
1477 * if lowest_unlock is 1, level 0 won't be unlocked
1479 static noinline void unlock_up(struct btrfs_path *path, int level,
1480 int lowest_unlock, int min_write_lock_level,
1481 int *write_lock_level)
1484 int skip_level = level;
1485 bool check_skip = true;
1487 for (i = level; i < BTRFS_MAX_LEVEL; i++) {
1488 if (!path->nodes[i])
1490 if (!path->locks[i])
1494 if (path->slots[i] == 0) {
1499 if (path->keep_locks) {
1502 nritems = btrfs_header_nritems(path->nodes[i]);
1503 if (nritems < 1 || path->slots[i] >= nritems - 1) {
1510 if (i >= lowest_unlock && i > skip_level) {
1512 btrfs_tree_unlock_rw(path->nodes[i], path->locks[i]);
1514 if (write_lock_level &&
1515 i > min_write_lock_level &&
1516 i <= *write_lock_level) {
1517 *write_lock_level = i - 1;
1524 * Helper function for btrfs_search_slot() and other functions that do a search
1525 * on a btree. The goal is to find a tree block in the cache (the radix tree at
1526 * fs_info->buffer_radix), but if we can't find it, or it's not up to date, read
1527 * its pages from disk.
1529 * Returns -EAGAIN, with the path unlocked, if the caller needs to repeat the
1530 * whole btree search, starting again from the current root node.
1533 read_block_for_search(struct btrfs_root *root, struct btrfs_path *p,
1534 struct extent_buffer **eb_ret, int level, int slot,
1535 const struct btrfs_key *key)
1537 struct btrfs_fs_info *fs_info = root->fs_info;
1538 struct btrfs_tree_parent_check check = { 0 };
1541 struct extent_buffer *tmp;
1546 unlock_up = ((level + 1 < BTRFS_MAX_LEVEL) && p->locks[level + 1]);
1547 blocknr = btrfs_node_blockptr(*eb_ret, slot);
1548 gen = btrfs_node_ptr_generation(*eb_ret, slot);
1549 parent_level = btrfs_header_level(*eb_ret);
1550 btrfs_node_key_to_cpu(*eb_ret, &check.first_key, slot);
1551 check.has_first_key = true;
1552 check.level = parent_level - 1;
1553 check.transid = gen;
1554 check.owner_root = root->root_key.objectid;
1557 * If we need to read an extent buffer from disk and we are holding locks
1558 * on upper level nodes, we unlock all the upper nodes before reading the
1559 * extent buffer, and then return -EAGAIN to the caller as it needs to
1560 * restart the search. We don't release the lock on the current level
1561 * because we need to walk this node to figure out which blocks to read.
1563 tmp = find_extent_buffer(fs_info, blocknr);
1565 if (p->reada == READA_FORWARD_ALWAYS)
1566 reada_for_search(fs_info, p, level, slot, key->objectid);
1568 /* first we do an atomic uptodate check */
1569 if (btrfs_buffer_uptodate(tmp, gen, 1) > 0) {
1571 * Do extra check for first_key, eb can be stale due to
1572 * being cached, read from scrub, or have multiple
1573 * parents (shared tree blocks).
1575 if (btrfs_verify_level_key(tmp,
1576 parent_level - 1, &check.first_key, gen)) {
1577 free_extent_buffer(tmp);
1585 free_extent_buffer(tmp);
1590 btrfs_unlock_up_safe(p, level + 1);
1592 /* now we're allowed to do a blocking uptodate check */
1593 ret = btrfs_read_extent_buffer(tmp, &check);
1595 free_extent_buffer(tmp);
1596 btrfs_release_path(p);
1599 if (btrfs_check_eb_owner(tmp, root->root_key.objectid)) {
1600 free_extent_buffer(tmp);
1601 btrfs_release_path(p);
1609 } else if (p->nowait) {
1614 btrfs_unlock_up_safe(p, level + 1);
1620 if (p->reada != READA_NONE)
1621 reada_for_search(fs_info, p, level, slot, key->objectid);
1623 tmp = read_tree_block(fs_info, blocknr, &check);
1625 btrfs_release_path(p);
1626 return PTR_ERR(tmp);
1629 * If the read above didn't mark this buffer up to date,
1630 * it will never end up being up to date. Set ret to EIO now
1631 * and give up so that our caller doesn't loop forever
1634 if (!extent_buffer_uptodate(tmp))
1641 free_extent_buffer(tmp);
1642 btrfs_release_path(p);
1649 * helper function for btrfs_search_slot. This does all of the checks
1650 * for node-level blocks and does any balancing required based on
1653 * If no extra work was required, zero is returned. If we had to
1654 * drop the path, -EAGAIN is returned and btrfs_search_slot must
1658 setup_nodes_for_search(struct btrfs_trans_handle *trans,
1659 struct btrfs_root *root, struct btrfs_path *p,
1660 struct extent_buffer *b, int level, int ins_len,
1661 int *write_lock_level)
1663 struct btrfs_fs_info *fs_info = root->fs_info;
1666 if ((p->search_for_split || ins_len > 0) && btrfs_header_nritems(b) >=
1667 BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3) {
1669 if (*write_lock_level < level + 1) {
1670 *write_lock_level = level + 1;
1671 btrfs_release_path(p);
1675 reada_for_balance(p, level);
1676 ret = split_node(trans, root, p, level);
1678 b = p->nodes[level];
1679 } else if (ins_len < 0 && btrfs_header_nritems(b) <
1680 BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 2) {
1682 if (*write_lock_level < level + 1) {
1683 *write_lock_level = level + 1;
1684 btrfs_release_path(p);
1688 reada_for_balance(p, level);
1689 ret = balance_level(trans, root, p, level);
1693 b = p->nodes[level];
1695 btrfs_release_path(p);
1698 BUG_ON(btrfs_header_nritems(b) == 1);
1703 int btrfs_find_item(struct btrfs_root *fs_root, struct btrfs_path *path,
1704 u64 iobjectid, u64 ioff, u8 key_type,
1705 struct btrfs_key *found_key)
1708 struct btrfs_key key;
1709 struct extent_buffer *eb;
1714 key.type = key_type;
1715 key.objectid = iobjectid;
1718 ret = btrfs_search_slot(NULL, fs_root, &key, path, 0, 0);
1722 eb = path->nodes[0];
1723 if (ret && path->slots[0] >= btrfs_header_nritems(eb)) {
1724 ret = btrfs_next_leaf(fs_root, path);
1727 eb = path->nodes[0];
1730 btrfs_item_key_to_cpu(eb, found_key, path->slots[0]);
1731 if (found_key->type != key.type ||
1732 found_key->objectid != key.objectid)
1738 static struct extent_buffer *btrfs_search_slot_get_root(struct btrfs_root *root,
1739 struct btrfs_path *p,
1740 int write_lock_level)
1742 struct extent_buffer *b;
1746 if (p->search_commit_root) {
1747 b = root->commit_root;
1748 atomic_inc(&b->refs);
1749 level = btrfs_header_level(b);
1751 * Ensure that all callers have set skip_locking when
1752 * p->search_commit_root = 1.
1754 ASSERT(p->skip_locking == 1);
1759 if (p->skip_locking) {
1760 b = btrfs_root_node(root);
1761 level = btrfs_header_level(b);
1765 /* We try very hard to do read locks on the root */
1766 root_lock = BTRFS_READ_LOCK;
1769 * If the level is set to maximum, we can skip trying to get the read
1772 if (write_lock_level < BTRFS_MAX_LEVEL) {
1774 * We don't know the level of the root node until we actually
1775 * have it read locked
1778 b = btrfs_try_read_lock_root_node(root);
1782 b = btrfs_read_lock_root_node(root);
1784 level = btrfs_header_level(b);
1785 if (level > write_lock_level)
1788 /* Whoops, must trade for write lock */
1789 btrfs_tree_read_unlock(b);
1790 free_extent_buffer(b);
1793 b = btrfs_lock_root_node(root);
1794 root_lock = BTRFS_WRITE_LOCK;
1796 /* The level might have changed, check again */
1797 level = btrfs_header_level(b);
1801 * The root may have failed to write out at some point, and thus is no
1802 * longer valid, return an error in this case.
1804 if (!extent_buffer_uptodate(b)) {
1806 btrfs_tree_unlock_rw(b, root_lock);
1807 free_extent_buffer(b);
1808 return ERR_PTR(-EIO);
1811 p->nodes[level] = b;
1812 if (!p->skip_locking)
1813 p->locks[level] = root_lock;
1815 * Callers are responsible for dropping b's references.
1821 * Replace the extent buffer at the lowest level of the path with a cloned
1822 * version. The purpose is to be able to use it safely, after releasing the
1823 * commit root semaphore, even if relocation is happening in parallel, the
1824 * transaction used for relocation is committed and the extent buffer is
1825 * reallocated in the next transaction.
1827 * This is used in a context where the caller does not prevent transaction
1828 * commits from happening, either by holding a transaction handle or holding
1829 * some lock, while it's doing searches through a commit root.
1830 * At the moment it's only used for send operations.
1832 static int finish_need_commit_sem_search(struct btrfs_path *path)
1834 const int i = path->lowest_level;
1835 const int slot = path->slots[i];
1836 struct extent_buffer *lowest = path->nodes[i];
1837 struct extent_buffer *clone;
1839 ASSERT(path->need_commit_sem);
1844 lockdep_assert_held_read(&lowest->fs_info->commit_root_sem);
1846 clone = btrfs_clone_extent_buffer(lowest);
1850 btrfs_release_path(path);
1851 path->nodes[i] = clone;
1852 path->slots[i] = slot;
1857 static inline int search_for_key_slot(struct extent_buffer *eb,
1858 int search_low_slot,
1859 const struct btrfs_key *key,
1864 * If a previous call to btrfs_bin_search() on a parent node returned an
1865 * exact match (prev_cmp == 0), we can safely assume the target key will
1866 * always be at slot 0 on lower levels, since each key pointer
1867 * (struct btrfs_key_ptr) refers to the lowest key accessible from the
1868 * subtree it points to. Thus we can skip searching lower levels.
1870 if (prev_cmp == 0) {
1875 return btrfs_bin_search(eb, search_low_slot, key, slot);
1878 static int search_leaf(struct btrfs_trans_handle *trans,
1879 struct btrfs_root *root,
1880 const struct btrfs_key *key,
1881 struct btrfs_path *path,
1885 struct extent_buffer *leaf = path->nodes[0];
1886 int leaf_free_space = -1;
1887 int search_low_slot = 0;
1889 bool do_bin_search = true;
1892 * If we are doing an insertion, the leaf has enough free space and the
1893 * destination slot for the key is not slot 0, then we can unlock our
1894 * write lock on the parent, and any other upper nodes, before doing the
1895 * binary search on the leaf (with search_for_key_slot()), allowing other
1896 * tasks to lock the parent and any other upper nodes.
1900 * Cache the leaf free space, since we will need it later and it
1901 * will not change until then.
1903 leaf_free_space = btrfs_leaf_free_space(leaf);
1906 * !path->locks[1] means we have a single node tree, the leaf is
1907 * the root of the tree.
1909 if (path->locks[1] && leaf_free_space >= ins_len) {
1910 struct btrfs_disk_key first_key;
1912 ASSERT(btrfs_header_nritems(leaf) > 0);
1913 btrfs_item_key(leaf, &first_key, 0);
1916 * Doing the extra comparison with the first key is cheap,
1917 * taking into account that the first key is very likely
1918 * already in a cache line because it immediately follows
1919 * the extent buffer's header and we have recently accessed
1920 * the header's level field.
1922 ret = comp_keys(&first_key, key);
1925 * The first key is smaller than the key we want
1926 * to insert, so we are safe to unlock all upper
1927 * nodes and we have to do the binary search.
1929 * We do use btrfs_unlock_up_safe() and not
1930 * unlock_up() because the later does not unlock
1931 * nodes with a slot of 0 - we can safely unlock
1932 * any node even if its slot is 0 since in this
1933 * case the key does not end up at slot 0 of the
1934 * leaf and there's no need to split the leaf.
1936 btrfs_unlock_up_safe(path, 1);
1937 search_low_slot = 1;
1940 * The first key is >= then the key we want to
1941 * insert, so we can skip the binary search as
1942 * the target key will be at slot 0.
1944 * We can not unlock upper nodes when the key is
1945 * less than the first key, because we will need
1946 * to update the key at slot 0 of the parent node
1947 * and possibly of other upper nodes too.
1948 * If the key matches the first key, then we can
1949 * unlock all the upper nodes, using
1950 * btrfs_unlock_up_safe() instead of unlock_up()
1954 btrfs_unlock_up_safe(path, 1);
1956 * ret is already 0 or 1, matching the result of
1957 * a btrfs_bin_search() call, so there is no need
1960 do_bin_search = false;
1966 if (do_bin_search) {
1967 ret = search_for_key_slot(leaf, search_low_slot, key,
1968 prev_cmp, &path->slots[0]);
1975 * Item key already exists. In this case, if we are allowed to
1976 * insert the item (for example, in dir_item case, item key
1977 * collision is allowed), it will be merged with the original
1978 * item. Only the item size grows, no new btrfs item will be
1979 * added. If search_for_extension is not set, ins_len already
1980 * accounts the size btrfs_item, deduct it here so leaf space
1981 * check will be correct.
1983 if (ret == 0 && !path->search_for_extension) {
1984 ASSERT(ins_len >= sizeof(struct btrfs_item));
1985 ins_len -= sizeof(struct btrfs_item);
1988 ASSERT(leaf_free_space >= 0);
1990 if (leaf_free_space < ins_len) {
1993 err = split_leaf(trans, root, key, path, ins_len,
1996 if (WARN_ON(err > 0))
2007 * btrfs_search_slot - look for a key in a tree and perform necessary
2008 * modifications to preserve tree invariants.
2010 * @trans: Handle of transaction, used when modifying the tree
2011 * @p: Holds all btree nodes along the search path
2012 * @root: The root node of the tree
2013 * @key: The key we are looking for
2014 * @ins_len: Indicates purpose of search:
2015 * >0 for inserts it's size of item inserted (*)
2017 * 0 for plain searches, not modifying the tree
2019 * (*) If size of item inserted doesn't include
2020 * sizeof(struct btrfs_item), then p->search_for_extension must
2022 * @cow: boolean should CoW operations be performed. Must always be 1
2023 * when modifying the tree.
2025 * If @ins_len > 0, nodes and leaves will be split as we walk down the tree.
2026 * If @ins_len < 0, nodes will be merged as we walk down the tree (if possible)
2028 * If @key is found, 0 is returned and you can find the item in the leaf level
2029 * of the path (level 0)
2031 * If @key isn't found, 1 is returned and the leaf level of the path (level 0)
2032 * points to the slot where it should be inserted
2034 * If an error is encountered while searching the tree a negative error number
2037 int btrfs_search_slot(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2038 const struct btrfs_key *key, struct btrfs_path *p,
2039 int ins_len, int cow)
2041 struct btrfs_fs_info *fs_info = root->fs_info;
2042 struct extent_buffer *b;
2047 int lowest_unlock = 1;
2048 /* everything at write_lock_level or lower must be write locked */
2049 int write_lock_level = 0;
2050 u8 lowest_level = 0;
2051 int min_write_lock_level;
2056 lowest_level = p->lowest_level;
2057 WARN_ON(lowest_level && ins_len > 0);
2058 WARN_ON(p->nodes[0] != NULL);
2059 BUG_ON(!cow && ins_len);
2062 * For now only allow nowait for read only operations. There's no
2063 * strict reason why we can't, we just only need it for reads so it's
2064 * only implemented for reads.
2066 ASSERT(!p->nowait || !cow);
2071 /* when we are removing items, we might have to go up to level
2072 * two as we update tree pointers Make sure we keep write
2073 * for those levels as well
2075 write_lock_level = 2;
2076 } else if (ins_len > 0) {
2078 * for inserting items, make sure we have a write lock on
2079 * level 1 so we can update keys
2081 write_lock_level = 1;
2085 write_lock_level = -1;
2087 if (cow && (p->keep_locks || p->lowest_level))
2088 write_lock_level = BTRFS_MAX_LEVEL;
2090 min_write_lock_level = write_lock_level;
2092 if (p->need_commit_sem) {
2093 ASSERT(p->search_commit_root);
2095 if (!down_read_trylock(&fs_info->commit_root_sem))
2098 down_read(&fs_info->commit_root_sem);
2104 b = btrfs_search_slot_get_root(root, p, write_lock_level);
2113 level = btrfs_header_level(b);
2116 bool last_level = (level == (BTRFS_MAX_LEVEL - 1));
2119 * if we don't really need to cow this block
2120 * then we don't want to set the path blocking,
2121 * so we test it here
2123 if (!should_cow_block(trans, root, b))
2127 * must have write locks on this node and the
2130 if (level > write_lock_level ||
2131 (level + 1 > write_lock_level &&
2132 level + 1 < BTRFS_MAX_LEVEL &&
2133 p->nodes[level + 1])) {
2134 write_lock_level = level + 1;
2135 btrfs_release_path(p);
2140 err = btrfs_cow_block(trans, root, b, NULL, 0,
2144 err = btrfs_cow_block(trans, root, b,
2145 p->nodes[level + 1],
2146 p->slots[level + 1], &b,
2154 p->nodes[level] = b;
2157 * we have a lock on b and as long as we aren't changing
2158 * the tree, there is no way to for the items in b to change.
2159 * It is safe to drop the lock on our parent before we
2160 * go through the expensive btree search on b.
2162 * If we're inserting or deleting (ins_len != 0), then we might
2163 * be changing slot zero, which may require changing the parent.
2164 * So, we can't drop the lock until after we know which slot
2165 * we're operating on.
2167 if (!ins_len && !p->keep_locks) {
2170 if (u < BTRFS_MAX_LEVEL && p->locks[u]) {
2171 btrfs_tree_unlock_rw(p->nodes[u], p->locks[u]);
2178 ASSERT(write_lock_level >= 1);
2180 ret = search_leaf(trans, root, key, p, ins_len, prev_cmp);
2181 if (!p->search_for_split)
2182 unlock_up(p, level, lowest_unlock,
2183 min_write_lock_level, NULL);
2187 ret = search_for_key_slot(b, 0, key, prev_cmp, &slot);
2192 if (ret && slot > 0) {
2196 p->slots[level] = slot;
2197 err = setup_nodes_for_search(trans, root, p, b, level, ins_len,
2205 b = p->nodes[level];
2206 slot = p->slots[level];
2209 * Slot 0 is special, if we change the key we have to update
2210 * the parent pointer which means we must have a write lock on
2213 if (slot == 0 && ins_len && write_lock_level < level + 1) {
2214 write_lock_level = level + 1;
2215 btrfs_release_path(p);
2219 unlock_up(p, level, lowest_unlock, min_write_lock_level,
2222 if (level == lowest_level) {
2228 err = read_block_for_search(root, p, &b, level, slot, key);
2236 if (!p->skip_locking) {
2237 level = btrfs_header_level(b);
2239 btrfs_maybe_reset_lockdep_class(root, b);
2241 if (level <= write_lock_level) {
2243 p->locks[level] = BTRFS_WRITE_LOCK;
2246 if (!btrfs_try_tree_read_lock(b)) {
2247 free_extent_buffer(b);
2252 btrfs_tree_read_lock(b);
2254 p->locks[level] = BTRFS_READ_LOCK;
2256 p->nodes[level] = b;
2261 if (ret < 0 && !p->skip_release_on_error)
2262 btrfs_release_path(p);
2264 if (p->need_commit_sem) {
2267 ret2 = finish_need_commit_sem_search(p);
2268 up_read(&fs_info->commit_root_sem);
2275 ALLOW_ERROR_INJECTION(btrfs_search_slot, ERRNO);
2278 * Like btrfs_search_slot, this looks for a key in the given tree. It uses the
2279 * current state of the tree together with the operations recorded in the tree
2280 * modification log to search for the key in a previous version of this tree, as
2281 * denoted by the time_seq parameter.
2283 * Naturally, there is no support for insert, delete or cow operations.
2285 * The resulting path and return value will be set up as if we called
2286 * btrfs_search_slot at that point in time with ins_len and cow both set to 0.
2288 int btrfs_search_old_slot(struct btrfs_root *root, const struct btrfs_key *key,
2289 struct btrfs_path *p, u64 time_seq)
2291 struct btrfs_fs_info *fs_info = root->fs_info;
2292 struct extent_buffer *b;
2297 int lowest_unlock = 1;
2298 u8 lowest_level = 0;
2300 lowest_level = p->lowest_level;
2301 WARN_ON(p->nodes[0] != NULL);
2304 if (p->search_commit_root) {
2306 return btrfs_search_slot(NULL, root, key, p, 0, 0);
2310 b = btrfs_get_old_root(root, time_seq);
2315 level = btrfs_header_level(b);
2316 p->locks[level] = BTRFS_READ_LOCK;
2321 level = btrfs_header_level(b);
2322 p->nodes[level] = b;
2325 * we have a lock on b and as long as we aren't changing
2326 * the tree, there is no way to for the items in b to change.
2327 * It is safe to drop the lock on our parent before we
2328 * go through the expensive btree search on b.
2330 btrfs_unlock_up_safe(p, level + 1);
2332 ret = btrfs_bin_search(b, 0, key, &slot);
2337 p->slots[level] = slot;
2338 unlock_up(p, level, lowest_unlock, 0, NULL);
2342 if (ret && slot > 0) {
2346 p->slots[level] = slot;
2347 unlock_up(p, level, lowest_unlock, 0, NULL);
2349 if (level == lowest_level) {
2355 err = read_block_for_search(root, p, &b, level, slot, key);
2363 level = btrfs_header_level(b);
2364 btrfs_tree_read_lock(b);
2365 b = btrfs_tree_mod_log_rewind(fs_info, p, b, time_seq);
2370 p->locks[level] = BTRFS_READ_LOCK;
2371 p->nodes[level] = b;
2376 btrfs_release_path(p);
2382 * helper to use instead of search slot if no exact match is needed but
2383 * instead the next or previous item should be returned.
2384 * When find_higher is true, the next higher item is returned, the next lower
2386 * When return_any and find_higher are both true, and no higher item is found,
2387 * return the next lower instead.
2388 * When return_any is true and find_higher is false, and no lower item is found,
2389 * return the next higher instead.
2390 * It returns 0 if any item is found, 1 if none is found (tree empty), and
2393 int btrfs_search_slot_for_read(struct btrfs_root *root,
2394 const struct btrfs_key *key,
2395 struct btrfs_path *p, int find_higher,
2399 struct extent_buffer *leaf;
2402 ret = btrfs_search_slot(NULL, root, key, p, 0, 0);
2406 * a return value of 1 means the path is at the position where the
2407 * item should be inserted. Normally this is the next bigger item,
2408 * but in case the previous item is the last in a leaf, path points
2409 * to the first free slot in the previous leaf, i.e. at an invalid
2415 if (p->slots[0] >= btrfs_header_nritems(leaf)) {
2416 ret = btrfs_next_leaf(root, p);
2422 * no higher item found, return the next
2427 btrfs_release_path(p);
2431 if (p->slots[0] == 0) {
2432 ret = btrfs_prev_leaf(root, p);
2437 if (p->slots[0] == btrfs_header_nritems(leaf))
2444 * no lower item found, return the next
2449 btrfs_release_path(p);
2459 * Execute search and call btrfs_previous_item to traverse backwards if the item
2462 * Return 0 if found, 1 if not found and < 0 if error.
2464 int btrfs_search_backwards(struct btrfs_root *root, struct btrfs_key *key,
2465 struct btrfs_path *path)
2469 ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
2471 ret = btrfs_previous_item(root, path, key->objectid, key->type);
2474 btrfs_item_key_to_cpu(path->nodes[0], key, path->slots[0]);
2480 * Search for a valid slot for the given path.
2482 * @root: The root node of the tree.
2483 * @key: Will contain a valid item if found.
2484 * @path: The starting point to validate the slot.
2486 * Return: 0 if the item is valid
2490 int btrfs_get_next_valid_item(struct btrfs_root *root, struct btrfs_key *key,
2491 struct btrfs_path *path)
2493 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
2496 ret = btrfs_next_leaf(root, path);
2501 btrfs_item_key_to_cpu(path->nodes[0], key, path->slots[0]);
2506 * adjust the pointers going up the tree, starting at level
2507 * making sure the right key of each node is points to 'key'.
2508 * This is used after shifting pointers to the left, so it stops
2509 * fixing up pointers when a given leaf/node is not in slot 0 of the
2513 static void fixup_low_keys(struct btrfs_path *path,
2514 struct btrfs_disk_key *key, int level)
2517 struct extent_buffer *t;
2520 for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2521 int tslot = path->slots[i];
2523 if (!path->nodes[i])
2526 ret = btrfs_tree_mod_log_insert_key(t, tslot,
2527 BTRFS_MOD_LOG_KEY_REPLACE);
2529 btrfs_set_node_key(t, key, tslot);
2530 btrfs_mark_buffer_dirty(path->nodes[i]);
2539 * This function isn't completely safe. It's the caller's responsibility
2540 * that the new key won't break the order
2542 void btrfs_set_item_key_safe(struct btrfs_fs_info *fs_info,
2543 struct btrfs_path *path,
2544 const struct btrfs_key *new_key)
2546 struct btrfs_disk_key disk_key;
2547 struct extent_buffer *eb;
2550 eb = path->nodes[0];
2551 slot = path->slots[0];
2553 btrfs_item_key(eb, &disk_key, slot - 1);
2554 if (unlikely(comp_keys(&disk_key, new_key) >= 0)) {
2556 "slot %u key (%llu %u %llu) new key (%llu %u %llu)",
2557 slot, btrfs_disk_key_objectid(&disk_key),
2558 btrfs_disk_key_type(&disk_key),
2559 btrfs_disk_key_offset(&disk_key),
2560 new_key->objectid, new_key->type,
2562 btrfs_print_leaf(eb);
2566 if (slot < btrfs_header_nritems(eb) - 1) {
2567 btrfs_item_key(eb, &disk_key, slot + 1);
2568 if (unlikely(comp_keys(&disk_key, new_key) <= 0)) {
2570 "slot %u key (%llu %u %llu) new key (%llu %u %llu)",
2571 slot, btrfs_disk_key_objectid(&disk_key),
2572 btrfs_disk_key_type(&disk_key),
2573 btrfs_disk_key_offset(&disk_key),
2574 new_key->objectid, new_key->type,
2576 btrfs_print_leaf(eb);
2581 btrfs_cpu_key_to_disk(&disk_key, new_key);
2582 btrfs_set_item_key(eb, &disk_key, slot);
2583 btrfs_mark_buffer_dirty(eb);
2585 fixup_low_keys(path, &disk_key, 1);
2589 * Check key order of two sibling extent buffers.
2591 * Return true if something is wrong.
2592 * Return false if everything is fine.
2594 * Tree-checker only works inside one tree block, thus the following
2595 * corruption can not be detected by tree-checker:
2597 * Leaf @left | Leaf @right
2598 * --------------------------------------------------------------
2599 * | 1 | 2 | 3 | 4 | 5 | f6 | | 7 | 8 |
2601 * Key f6 in leaf @left itself is valid, but not valid when the next
2602 * key in leaf @right is 7.
2603 * This can only be checked at tree block merge time.
2604 * And since tree checker has ensured all key order in each tree block
2605 * is correct, we only need to bother the last key of @left and the first
2608 static bool check_sibling_keys(struct extent_buffer *left,
2609 struct extent_buffer *right)
2611 struct btrfs_key left_last;
2612 struct btrfs_key right_first;
2613 int level = btrfs_header_level(left);
2614 int nr_left = btrfs_header_nritems(left);
2615 int nr_right = btrfs_header_nritems(right);
2617 /* No key to check in one of the tree blocks */
2618 if (!nr_left || !nr_right)
2622 btrfs_node_key_to_cpu(left, &left_last, nr_left - 1);
2623 btrfs_node_key_to_cpu(right, &right_first, 0);
2625 btrfs_item_key_to_cpu(left, &left_last, nr_left - 1);
2626 btrfs_item_key_to_cpu(right, &right_first, 0);
2629 if (btrfs_comp_cpu_keys(&left_last, &right_first) >= 0) {
2630 btrfs_crit(left->fs_info, "left extent buffer:");
2631 btrfs_print_tree(left, false);
2632 btrfs_crit(left->fs_info, "right extent buffer:");
2633 btrfs_print_tree(right, false);
2634 btrfs_crit(left->fs_info,
2635 "bad key order, sibling blocks, left last (%llu %u %llu) right first (%llu %u %llu)",
2636 left_last.objectid, left_last.type,
2637 left_last.offset, right_first.objectid,
2638 right_first.type, right_first.offset);
2645 * try to push data from one node into the next node left in the
2648 * returns 0 if some ptrs were pushed left, < 0 if there was some horrible
2649 * error, and > 0 if there was no room in the left hand block.
2651 static int push_node_left(struct btrfs_trans_handle *trans,
2652 struct extent_buffer *dst,
2653 struct extent_buffer *src, int empty)
2655 struct btrfs_fs_info *fs_info = trans->fs_info;
2661 src_nritems = btrfs_header_nritems(src);
2662 dst_nritems = btrfs_header_nritems(dst);
2663 push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
2664 WARN_ON(btrfs_header_generation(src) != trans->transid);
2665 WARN_ON(btrfs_header_generation(dst) != trans->transid);
2667 if (!empty && src_nritems <= 8)
2670 if (push_items <= 0)
2674 push_items = min(src_nritems, push_items);
2675 if (push_items < src_nritems) {
2676 /* leave at least 8 pointers in the node if
2677 * we aren't going to empty it
2679 if (src_nritems - push_items < 8) {
2680 if (push_items <= 8)
2686 push_items = min(src_nritems - 8, push_items);
2688 /* dst is the left eb, src is the middle eb */
2689 if (check_sibling_keys(dst, src)) {
2691 btrfs_abort_transaction(trans, ret);
2694 ret = btrfs_tree_mod_log_eb_copy(dst, src, dst_nritems, 0, push_items);
2696 btrfs_abort_transaction(trans, ret);
2699 copy_extent_buffer(dst, src,
2700 btrfs_node_key_ptr_offset(dst, dst_nritems),
2701 btrfs_node_key_ptr_offset(src, 0),
2702 push_items * sizeof(struct btrfs_key_ptr));
2704 if (push_items < src_nritems) {
2706 * Don't call btrfs_tree_mod_log_insert_move() here, key removal
2707 * was already fully logged by btrfs_tree_mod_log_eb_copy() above.
2709 memmove_extent_buffer(src, btrfs_node_key_ptr_offset(src, 0),
2710 btrfs_node_key_ptr_offset(src, push_items),
2711 (src_nritems - push_items) *
2712 sizeof(struct btrfs_key_ptr));
2714 btrfs_set_header_nritems(src, src_nritems - push_items);
2715 btrfs_set_header_nritems(dst, dst_nritems + push_items);
2716 btrfs_mark_buffer_dirty(src);
2717 btrfs_mark_buffer_dirty(dst);
2723 * try to push data from one node into the next node right in the
2726 * returns 0 if some ptrs were pushed, < 0 if there was some horrible
2727 * error, and > 0 if there was no room in the right hand block.
2729 * this will only push up to 1/2 the contents of the left node over
2731 static int balance_node_right(struct btrfs_trans_handle *trans,
2732 struct extent_buffer *dst,
2733 struct extent_buffer *src)
2735 struct btrfs_fs_info *fs_info = trans->fs_info;
2742 WARN_ON(btrfs_header_generation(src) != trans->transid);
2743 WARN_ON(btrfs_header_generation(dst) != trans->transid);
2745 src_nritems = btrfs_header_nritems(src);
2746 dst_nritems = btrfs_header_nritems(dst);
2747 push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
2748 if (push_items <= 0)
2751 if (src_nritems < 4)
2754 max_push = src_nritems / 2 + 1;
2755 /* don't try to empty the node */
2756 if (max_push >= src_nritems)
2759 if (max_push < push_items)
2760 push_items = max_push;
2762 /* dst is the right eb, src is the middle eb */
2763 if (check_sibling_keys(src, dst)) {
2765 btrfs_abort_transaction(trans, ret);
2768 ret = btrfs_tree_mod_log_insert_move(dst, push_items, 0, dst_nritems);
2770 memmove_extent_buffer(dst, btrfs_node_key_ptr_offset(dst, push_items),
2771 btrfs_node_key_ptr_offset(dst, 0),
2773 sizeof(struct btrfs_key_ptr));
2775 ret = btrfs_tree_mod_log_eb_copy(dst, src, 0, src_nritems - push_items,
2778 btrfs_abort_transaction(trans, ret);
2781 copy_extent_buffer(dst, src,
2782 btrfs_node_key_ptr_offset(dst, 0),
2783 btrfs_node_key_ptr_offset(src, src_nritems - push_items),
2784 push_items * sizeof(struct btrfs_key_ptr));
2786 btrfs_set_header_nritems(src, src_nritems - push_items);
2787 btrfs_set_header_nritems(dst, dst_nritems + push_items);
2789 btrfs_mark_buffer_dirty(src);
2790 btrfs_mark_buffer_dirty(dst);
2796 * helper function to insert a new root level in the tree.
2797 * A new node is allocated, and a single item is inserted to
2798 * point to the existing root
2800 * returns zero on success or < 0 on failure.
2802 static noinline int insert_new_root(struct btrfs_trans_handle *trans,
2803 struct btrfs_root *root,
2804 struct btrfs_path *path, int level)
2806 struct btrfs_fs_info *fs_info = root->fs_info;
2808 struct extent_buffer *lower;
2809 struct extent_buffer *c;
2810 struct extent_buffer *old;
2811 struct btrfs_disk_key lower_key;
2814 BUG_ON(path->nodes[level]);
2815 BUG_ON(path->nodes[level-1] != root->node);
2817 lower = path->nodes[level-1];
2819 btrfs_item_key(lower, &lower_key, 0);
2821 btrfs_node_key(lower, &lower_key, 0);
2823 c = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
2824 &lower_key, level, root->node->start, 0,
2825 BTRFS_NESTING_NEW_ROOT);
2829 root_add_used(root, fs_info->nodesize);
2831 btrfs_set_header_nritems(c, 1);
2832 btrfs_set_node_key(c, &lower_key, 0);
2833 btrfs_set_node_blockptr(c, 0, lower->start);
2834 lower_gen = btrfs_header_generation(lower);
2835 WARN_ON(lower_gen != trans->transid);
2837 btrfs_set_node_ptr_generation(c, 0, lower_gen);
2839 btrfs_mark_buffer_dirty(c);
2842 ret = btrfs_tree_mod_log_insert_root(root->node, c, false);
2844 rcu_assign_pointer(root->node, c);
2846 /* the super has an extra ref to root->node */
2847 free_extent_buffer(old);
2849 add_root_to_dirty_list(root);
2850 atomic_inc(&c->refs);
2851 path->nodes[level] = c;
2852 path->locks[level] = BTRFS_WRITE_LOCK;
2853 path->slots[level] = 0;
2858 * worker function to insert a single pointer in a node.
2859 * the node should have enough room for the pointer already
2861 * slot and level indicate where you want the key to go, and
2862 * blocknr is the block the key points to.
2864 static void insert_ptr(struct btrfs_trans_handle *trans,
2865 struct btrfs_path *path,
2866 struct btrfs_disk_key *key, u64 bytenr,
2867 int slot, int level)
2869 struct extent_buffer *lower;
2873 BUG_ON(!path->nodes[level]);
2874 btrfs_assert_tree_write_locked(path->nodes[level]);
2875 lower = path->nodes[level];
2876 nritems = btrfs_header_nritems(lower);
2877 BUG_ON(slot > nritems);
2878 BUG_ON(nritems == BTRFS_NODEPTRS_PER_BLOCK(trans->fs_info));
2879 if (slot != nritems) {
2881 ret = btrfs_tree_mod_log_insert_move(lower, slot + 1,
2882 slot, nritems - slot);
2885 memmove_extent_buffer(lower,
2886 btrfs_node_key_ptr_offset(lower, slot + 1),
2887 btrfs_node_key_ptr_offset(lower, slot),
2888 (nritems - slot) * sizeof(struct btrfs_key_ptr));
2891 ret = btrfs_tree_mod_log_insert_key(lower, slot,
2892 BTRFS_MOD_LOG_KEY_ADD);
2895 btrfs_set_node_key(lower, key, slot);
2896 btrfs_set_node_blockptr(lower, slot, bytenr);
2897 WARN_ON(trans->transid == 0);
2898 btrfs_set_node_ptr_generation(lower, slot, trans->transid);
2899 btrfs_set_header_nritems(lower, nritems + 1);
2900 btrfs_mark_buffer_dirty(lower);
2904 * split the node at the specified level in path in two.
2905 * The path is corrected to point to the appropriate node after the split
2907 * Before splitting this tries to make some room in the node by pushing
2908 * left and right, if either one works, it returns right away.
2910 * returns 0 on success and < 0 on failure
2912 static noinline int split_node(struct btrfs_trans_handle *trans,
2913 struct btrfs_root *root,
2914 struct btrfs_path *path, int level)
2916 struct btrfs_fs_info *fs_info = root->fs_info;
2917 struct extent_buffer *c;
2918 struct extent_buffer *split;
2919 struct btrfs_disk_key disk_key;
2924 c = path->nodes[level];
2925 WARN_ON(btrfs_header_generation(c) != trans->transid);
2926 if (c == root->node) {
2928 * trying to split the root, lets make a new one
2930 * tree mod log: We don't log_removal old root in
2931 * insert_new_root, because that root buffer will be kept as a
2932 * normal node. We are going to log removal of half of the
2933 * elements below with btrfs_tree_mod_log_eb_copy(). We're
2934 * holding a tree lock on the buffer, which is why we cannot
2935 * race with other tree_mod_log users.
2937 ret = insert_new_root(trans, root, path, level + 1);
2941 ret = push_nodes_for_insert(trans, root, path, level);
2942 c = path->nodes[level];
2943 if (!ret && btrfs_header_nritems(c) <
2944 BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3)
2950 c_nritems = btrfs_header_nritems(c);
2951 mid = (c_nritems + 1) / 2;
2952 btrfs_node_key(c, &disk_key, mid);
2954 split = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
2955 &disk_key, level, c->start, 0,
2956 BTRFS_NESTING_SPLIT);
2958 return PTR_ERR(split);
2960 root_add_used(root, fs_info->nodesize);
2961 ASSERT(btrfs_header_level(c) == level);
2963 ret = btrfs_tree_mod_log_eb_copy(split, c, 0, mid, c_nritems - mid);
2965 btrfs_abort_transaction(trans, ret);
2968 copy_extent_buffer(split, c,
2969 btrfs_node_key_ptr_offset(split, 0),
2970 btrfs_node_key_ptr_offset(c, mid),
2971 (c_nritems - mid) * sizeof(struct btrfs_key_ptr));
2972 btrfs_set_header_nritems(split, c_nritems - mid);
2973 btrfs_set_header_nritems(c, mid);
2975 btrfs_mark_buffer_dirty(c);
2976 btrfs_mark_buffer_dirty(split);
2978 insert_ptr(trans, path, &disk_key, split->start,
2979 path->slots[level + 1] + 1, level + 1);
2981 if (path->slots[level] >= mid) {
2982 path->slots[level] -= mid;
2983 btrfs_tree_unlock(c);
2984 free_extent_buffer(c);
2985 path->nodes[level] = split;
2986 path->slots[level + 1] += 1;
2988 btrfs_tree_unlock(split);
2989 free_extent_buffer(split);
2995 * how many bytes are required to store the items in a leaf. start
2996 * and nr indicate which items in the leaf to check. This totals up the
2997 * space used both by the item structs and the item data
2999 static int leaf_space_used(struct extent_buffer *l, int start, int nr)
3002 int nritems = btrfs_header_nritems(l);
3003 int end = min(nritems, start + nr) - 1;
3007 data_len = btrfs_item_offset(l, start) + btrfs_item_size(l, start);
3008 data_len = data_len - btrfs_item_offset(l, end);
3009 data_len += sizeof(struct btrfs_item) * nr;
3010 WARN_ON(data_len < 0);
3015 * The space between the end of the leaf items and
3016 * the start of the leaf data. IOW, how much room
3017 * the leaf has left for both items and data
3019 noinline int btrfs_leaf_free_space(struct extent_buffer *leaf)
3021 struct btrfs_fs_info *fs_info = leaf->fs_info;
3022 int nritems = btrfs_header_nritems(leaf);
3025 ret = BTRFS_LEAF_DATA_SIZE(fs_info) - leaf_space_used(leaf, 0, nritems);
3028 "leaf free space ret %d, leaf data size %lu, used %d nritems %d",
3030 (unsigned long) BTRFS_LEAF_DATA_SIZE(fs_info),
3031 leaf_space_used(leaf, 0, nritems), nritems);
3037 * min slot controls the lowest index we're willing to push to the
3038 * right. We'll push up to and including min_slot, but no lower
3040 static noinline int __push_leaf_right(struct btrfs_trans_handle *trans,
3041 struct btrfs_path *path,
3042 int data_size, int empty,
3043 struct extent_buffer *right,
3044 int free_space, u32 left_nritems,
3047 struct btrfs_fs_info *fs_info = right->fs_info;
3048 struct extent_buffer *left = path->nodes[0];
3049 struct extent_buffer *upper = path->nodes[1];
3050 struct btrfs_map_token token;
3051 struct btrfs_disk_key disk_key;
3064 nr = max_t(u32, 1, min_slot);
3066 if (path->slots[0] >= left_nritems)
3067 push_space += data_size;
3069 slot = path->slots[1];
3070 i = left_nritems - 1;
3072 if (!empty && push_items > 0) {
3073 if (path->slots[0] > i)
3075 if (path->slots[0] == i) {
3076 int space = btrfs_leaf_free_space(left);
3078 if (space + push_space * 2 > free_space)
3083 if (path->slots[0] == i)
3084 push_space += data_size;
3086 this_item_size = btrfs_item_size(left, i);
3087 if (this_item_size + sizeof(struct btrfs_item) +
3088 push_space > free_space)
3092 push_space += this_item_size + sizeof(struct btrfs_item);
3098 if (push_items == 0)
3101 WARN_ON(!empty && push_items == left_nritems);
3103 /* push left to right */
3104 right_nritems = btrfs_header_nritems(right);
3106 push_space = btrfs_item_data_end(left, left_nritems - push_items);
3107 push_space -= leaf_data_end(left);
3109 /* make room in the right data area */
3110 data_end = leaf_data_end(right);
3111 memmove_leaf_data(right, data_end - push_space, data_end,
3112 BTRFS_LEAF_DATA_SIZE(fs_info) - data_end);
3114 /* copy from the left data area */
3115 copy_leaf_data(right, left, BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
3116 leaf_data_end(left), push_space);
3118 memmove_leaf_items(right, push_items, 0, right_nritems);
3120 /* copy the items from left to right */
3121 copy_leaf_items(right, left, 0, left_nritems - push_items, push_items);
3123 /* update the item pointers */
3124 btrfs_init_map_token(&token, right);
3125 right_nritems += push_items;
3126 btrfs_set_header_nritems(right, right_nritems);
3127 push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
3128 for (i = 0; i < right_nritems; i++) {
3129 push_space -= btrfs_token_item_size(&token, i);
3130 btrfs_set_token_item_offset(&token, i, push_space);
3133 left_nritems -= push_items;
3134 btrfs_set_header_nritems(left, left_nritems);
3137 btrfs_mark_buffer_dirty(left);
3139 btrfs_clear_buffer_dirty(trans, left);
3141 btrfs_mark_buffer_dirty(right);
3143 btrfs_item_key(right, &disk_key, 0);
3144 btrfs_set_node_key(upper, &disk_key, slot + 1);
3145 btrfs_mark_buffer_dirty(upper);
3147 /* then fixup the leaf pointer in the path */
3148 if (path->slots[0] >= left_nritems) {
3149 path->slots[0] -= left_nritems;
3150 if (btrfs_header_nritems(path->nodes[0]) == 0)
3151 btrfs_clear_buffer_dirty(trans, path->nodes[0]);
3152 btrfs_tree_unlock(path->nodes[0]);
3153 free_extent_buffer(path->nodes[0]);
3154 path->nodes[0] = right;
3155 path->slots[1] += 1;
3157 btrfs_tree_unlock(right);
3158 free_extent_buffer(right);
3163 btrfs_tree_unlock(right);
3164 free_extent_buffer(right);
3169 * push some data in the path leaf to the right, trying to free up at
3170 * least data_size bytes. returns zero if the push worked, nonzero otherwise
3172 * returns 1 if the push failed because the other node didn't have enough
3173 * room, 0 if everything worked out and < 0 if there were major errors.
3175 * this will push starting from min_slot to the end of the leaf. It won't
3176 * push any slot lower than min_slot
3178 static int push_leaf_right(struct btrfs_trans_handle *trans, struct btrfs_root
3179 *root, struct btrfs_path *path,
3180 int min_data_size, int data_size,
3181 int empty, u32 min_slot)
3183 struct extent_buffer *left = path->nodes[0];
3184 struct extent_buffer *right;
3185 struct extent_buffer *upper;
3191 if (!path->nodes[1])
3194 slot = path->slots[1];
3195 upper = path->nodes[1];
3196 if (slot >= btrfs_header_nritems(upper) - 1)
3199 btrfs_assert_tree_write_locked(path->nodes[1]);
3201 right = btrfs_read_node_slot(upper, slot + 1);
3203 return PTR_ERR(right);
3205 __btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
3207 free_space = btrfs_leaf_free_space(right);
3208 if (free_space < data_size)
3211 ret = btrfs_cow_block(trans, root, right, upper,
3212 slot + 1, &right, BTRFS_NESTING_RIGHT_COW);
3216 left_nritems = btrfs_header_nritems(left);
3217 if (left_nritems == 0)
3220 if (check_sibling_keys(left, right)) {
3222 btrfs_abort_transaction(trans, ret);
3223 btrfs_tree_unlock(right);
3224 free_extent_buffer(right);
3227 if (path->slots[0] == left_nritems && !empty) {
3228 /* Key greater than all keys in the leaf, right neighbor has
3229 * enough room for it and we're not emptying our leaf to delete
3230 * it, therefore use right neighbor to insert the new item and
3231 * no need to touch/dirty our left leaf. */
3232 btrfs_tree_unlock(left);
3233 free_extent_buffer(left);
3234 path->nodes[0] = right;
3240 return __push_leaf_right(trans, path, min_data_size, empty, right,
3241 free_space, left_nritems, min_slot);
3243 btrfs_tree_unlock(right);
3244 free_extent_buffer(right);
3249 * push some data in the path leaf to the left, trying to free up at
3250 * least data_size bytes. returns zero if the push worked, nonzero otherwise
3252 * max_slot can put a limit on how far into the leaf we'll push items. The
3253 * item at 'max_slot' won't be touched. Use (u32)-1 to make us do all the
3256 static noinline int __push_leaf_left(struct btrfs_trans_handle *trans,
3257 struct btrfs_path *path, int data_size,
3258 int empty, struct extent_buffer *left,
3259 int free_space, u32 right_nritems,
3262 struct btrfs_fs_info *fs_info = left->fs_info;
3263 struct btrfs_disk_key disk_key;
3264 struct extent_buffer *right = path->nodes[0];
3268 u32 old_left_nritems;
3272 u32 old_left_item_size;
3273 struct btrfs_map_token token;
3276 nr = min(right_nritems, max_slot);
3278 nr = min(right_nritems - 1, max_slot);
3280 for (i = 0; i < nr; i++) {
3281 if (!empty && push_items > 0) {
3282 if (path->slots[0] < i)
3284 if (path->slots[0] == i) {
3285 int space = btrfs_leaf_free_space(right);
3287 if (space + push_space * 2 > free_space)
3292 if (path->slots[0] == i)
3293 push_space += data_size;
3295 this_item_size = btrfs_item_size(right, i);
3296 if (this_item_size + sizeof(struct btrfs_item) + push_space >
3301 push_space += this_item_size + sizeof(struct btrfs_item);
3304 if (push_items == 0) {
3308 WARN_ON(!empty && push_items == btrfs_header_nritems(right));
3310 /* push data from right to left */
3311 copy_leaf_items(left, right, btrfs_header_nritems(left), 0, push_items);
3313 push_space = BTRFS_LEAF_DATA_SIZE(fs_info) -
3314 btrfs_item_offset(right, push_items - 1);
3316 copy_leaf_data(left, right, leaf_data_end(left) - push_space,
3317 btrfs_item_offset(right, push_items - 1), push_space);
3318 old_left_nritems = btrfs_header_nritems(left);
3319 BUG_ON(old_left_nritems <= 0);
3321 btrfs_init_map_token(&token, left);
3322 old_left_item_size = btrfs_item_offset(left, old_left_nritems - 1);
3323 for (i = old_left_nritems; i < old_left_nritems + push_items; i++) {
3326 ioff = btrfs_token_item_offset(&token, i);
3327 btrfs_set_token_item_offset(&token, i,
3328 ioff - (BTRFS_LEAF_DATA_SIZE(fs_info) - old_left_item_size));
3330 btrfs_set_header_nritems(left, old_left_nritems + push_items);
3332 /* fixup right node */
3333 if (push_items > right_nritems)
3334 WARN(1, KERN_CRIT "push items %d nr %u\n", push_items,
3337 if (push_items < right_nritems) {
3338 push_space = btrfs_item_offset(right, push_items - 1) -
3339 leaf_data_end(right);
3340 memmove_leaf_data(right,
3341 BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
3342 leaf_data_end(right), push_space);
3344 memmove_leaf_items(right, 0, push_items,
3345 btrfs_header_nritems(right) - push_items);
3348 btrfs_init_map_token(&token, right);
3349 right_nritems -= push_items;
3350 btrfs_set_header_nritems(right, right_nritems);
3351 push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
3352 for (i = 0; i < right_nritems; i++) {
3353 push_space = push_space - btrfs_token_item_size(&token, i);
3354 btrfs_set_token_item_offset(&token, i, push_space);
3357 btrfs_mark_buffer_dirty(left);
3359 btrfs_mark_buffer_dirty(right);
3361 btrfs_clear_buffer_dirty(trans, right);
3363 btrfs_item_key(right, &disk_key, 0);
3364 fixup_low_keys(path, &disk_key, 1);
3366 /* then fixup the leaf pointer in the path */
3367 if (path->slots[0] < push_items) {
3368 path->slots[0] += old_left_nritems;
3369 btrfs_tree_unlock(path->nodes[0]);
3370 free_extent_buffer(path->nodes[0]);
3371 path->nodes[0] = left;
3372 path->slots[1] -= 1;
3374 btrfs_tree_unlock(left);
3375 free_extent_buffer(left);
3376 path->slots[0] -= push_items;
3378 BUG_ON(path->slots[0] < 0);
3381 btrfs_tree_unlock(left);
3382 free_extent_buffer(left);
3387 * push some data in the path leaf to the left, trying to free up at
3388 * least data_size bytes. returns zero if the push worked, nonzero otherwise
3390 * max_slot can put a limit on how far into the leaf we'll push items. The
3391 * item at 'max_slot' won't be touched. Use (u32)-1 to make us push all the
3394 static int push_leaf_left(struct btrfs_trans_handle *trans, struct btrfs_root
3395 *root, struct btrfs_path *path, int min_data_size,
3396 int data_size, int empty, u32 max_slot)
3398 struct extent_buffer *right = path->nodes[0];
3399 struct extent_buffer *left;
3405 slot = path->slots[1];
3408 if (!path->nodes[1])
3411 right_nritems = btrfs_header_nritems(right);
3412 if (right_nritems == 0)
3415 btrfs_assert_tree_write_locked(path->nodes[1]);
3417 left = btrfs_read_node_slot(path->nodes[1], slot - 1);
3419 return PTR_ERR(left);
3421 __btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
3423 free_space = btrfs_leaf_free_space(left);
3424 if (free_space < data_size) {
3429 ret = btrfs_cow_block(trans, root, left,
3430 path->nodes[1], slot - 1, &left,
3431 BTRFS_NESTING_LEFT_COW);
3433 /* we hit -ENOSPC, but it isn't fatal here */
3439 if (check_sibling_keys(left, right)) {
3441 btrfs_abort_transaction(trans, ret);
3444 return __push_leaf_left(trans, path, min_data_size, empty, left,
3445 free_space, right_nritems, max_slot);
3447 btrfs_tree_unlock(left);
3448 free_extent_buffer(left);
3453 * split the path's leaf in two, making sure there is at least data_size
3454 * available for the resulting leaf level of the path.
3456 static noinline void copy_for_split(struct btrfs_trans_handle *trans,
3457 struct btrfs_path *path,
3458 struct extent_buffer *l,
3459 struct extent_buffer *right,
3460 int slot, int mid, int nritems)
3462 struct btrfs_fs_info *fs_info = trans->fs_info;
3466 struct btrfs_disk_key disk_key;
3467 struct btrfs_map_token token;
3469 nritems = nritems - mid;
3470 btrfs_set_header_nritems(right, nritems);
3471 data_copy_size = btrfs_item_data_end(l, mid) - leaf_data_end(l);
3473 copy_leaf_items(right, l, 0, mid, nritems);
3475 copy_leaf_data(right, l, BTRFS_LEAF_DATA_SIZE(fs_info) - data_copy_size,
3476 leaf_data_end(l), data_copy_size);
3478 rt_data_off = BTRFS_LEAF_DATA_SIZE(fs_info) - btrfs_item_data_end(l, mid);
3480 btrfs_init_map_token(&token, right);
3481 for (i = 0; i < nritems; i++) {
3484 ioff = btrfs_token_item_offset(&token, i);
3485 btrfs_set_token_item_offset(&token, i, ioff + rt_data_off);
3488 btrfs_set_header_nritems(l, mid);
3489 btrfs_item_key(right, &disk_key, 0);
3490 insert_ptr(trans, path, &disk_key, right->start, path->slots[1] + 1, 1);
3492 btrfs_mark_buffer_dirty(right);
3493 btrfs_mark_buffer_dirty(l);
3494 BUG_ON(path->slots[0] != slot);
3497 btrfs_tree_unlock(path->nodes[0]);
3498 free_extent_buffer(path->nodes[0]);
3499 path->nodes[0] = right;
3500 path->slots[0] -= mid;
3501 path->slots[1] += 1;
3503 btrfs_tree_unlock(right);
3504 free_extent_buffer(right);
3507 BUG_ON(path->slots[0] < 0);
3511 * double splits happen when we need to insert a big item in the middle
3512 * of a leaf. A double split can leave us with 3 mostly empty leaves:
3513 * leaf: [ slots 0 - N] [ our target ] [ N + 1 - total in leaf ]
3516 * We avoid this by trying to push the items on either side of our target
3517 * into the adjacent leaves. If all goes well we can avoid the double split
3520 static noinline int push_for_double_split(struct btrfs_trans_handle *trans,
3521 struct btrfs_root *root,
3522 struct btrfs_path *path,
3529 int space_needed = data_size;
3531 slot = path->slots[0];
3532 if (slot < btrfs_header_nritems(path->nodes[0]))
3533 space_needed -= btrfs_leaf_free_space(path->nodes[0]);
3536 * try to push all the items after our slot into the
3539 ret = push_leaf_right(trans, root, path, 1, space_needed, 0, slot);
3546 nritems = btrfs_header_nritems(path->nodes[0]);
3548 * our goal is to get our slot at the start or end of a leaf. If
3549 * we've done so we're done
3551 if (path->slots[0] == 0 || path->slots[0] == nritems)
3554 if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
3557 /* try to push all the items before our slot into the next leaf */
3558 slot = path->slots[0];
3559 space_needed = data_size;
3561 space_needed -= btrfs_leaf_free_space(path->nodes[0]);
3562 ret = push_leaf_left(trans, root, path, 1, space_needed, 0, slot);
3575 * split the path's leaf in two, making sure there is at least data_size
3576 * available for the resulting leaf level of the path.
3578 * returns 0 if all went well and < 0 on failure.
3580 static noinline int split_leaf(struct btrfs_trans_handle *trans,
3581 struct btrfs_root *root,
3582 const struct btrfs_key *ins_key,
3583 struct btrfs_path *path, int data_size,
3586 struct btrfs_disk_key disk_key;
3587 struct extent_buffer *l;
3591 struct extent_buffer *right;
3592 struct btrfs_fs_info *fs_info = root->fs_info;
3596 int num_doubles = 0;
3597 int tried_avoid_double = 0;
3600 slot = path->slots[0];
3601 if (extend && data_size + btrfs_item_size(l, slot) +
3602 sizeof(struct btrfs_item) > BTRFS_LEAF_DATA_SIZE(fs_info))
3605 /* first try to make some room by pushing left and right */
3606 if (data_size && path->nodes[1]) {
3607 int space_needed = data_size;
3609 if (slot < btrfs_header_nritems(l))
3610 space_needed -= btrfs_leaf_free_space(l);
3612 wret = push_leaf_right(trans, root, path, space_needed,
3613 space_needed, 0, 0);
3617 space_needed = data_size;
3619 space_needed -= btrfs_leaf_free_space(l);
3620 wret = push_leaf_left(trans, root, path, space_needed,
3621 space_needed, 0, (u32)-1);
3627 /* did the pushes work? */
3628 if (btrfs_leaf_free_space(l) >= data_size)
3632 if (!path->nodes[1]) {
3633 ret = insert_new_root(trans, root, path, 1);
3640 slot = path->slots[0];
3641 nritems = btrfs_header_nritems(l);
3642 mid = (nritems + 1) / 2;
3646 leaf_space_used(l, mid, nritems - mid) + data_size >
3647 BTRFS_LEAF_DATA_SIZE(fs_info)) {
3648 if (slot >= nritems) {
3652 if (mid != nritems &&
3653 leaf_space_used(l, mid, nritems - mid) +
3654 data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
3655 if (data_size && !tried_avoid_double)
3656 goto push_for_double;
3662 if (leaf_space_used(l, 0, mid) + data_size >
3663 BTRFS_LEAF_DATA_SIZE(fs_info)) {
3664 if (!extend && data_size && slot == 0) {
3666 } else if ((extend || !data_size) && slot == 0) {
3670 if (mid != nritems &&
3671 leaf_space_used(l, mid, nritems - mid) +
3672 data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
3673 if (data_size && !tried_avoid_double)
3674 goto push_for_double;
3682 btrfs_cpu_key_to_disk(&disk_key, ins_key);
3684 btrfs_item_key(l, &disk_key, mid);
3687 * We have to about BTRFS_NESTING_NEW_ROOT here if we've done a double
3688 * split, because we're only allowed to have MAX_LOCKDEP_SUBCLASSES
3689 * subclasses, which is 8 at the time of this patch, and we've maxed it
3690 * out. In the future we could add a
3691 * BTRFS_NESTING_SPLIT_THE_SPLITTENING if we need to, but for now just
3692 * use BTRFS_NESTING_NEW_ROOT.
3694 right = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
3695 &disk_key, 0, l->start, 0,
3696 num_doubles ? BTRFS_NESTING_NEW_ROOT :
3697 BTRFS_NESTING_SPLIT);
3699 return PTR_ERR(right);
3701 root_add_used(root, fs_info->nodesize);
3705 btrfs_set_header_nritems(right, 0);
3706 insert_ptr(trans, path, &disk_key,
3707 right->start, path->slots[1] + 1, 1);
3708 btrfs_tree_unlock(path->nodes[0]);
3709 free_extent_buffer(path->nodes[0]);
3710 path->nodes[0] = right;
3712 path->slots[1] += 1;
3714 btrfs_set_header_nritems(right, 0);
3715 insert_ptr(trans, path, &disk_key,
3716 right->start, path->slots[1], 1);
3717 btrfs_tree_unlock(path->nodes[0]);
3718 free_extent_buffer(path->nodes[0]);
3719 path->nodes[0] = right;
3721 if (path->slots[1] == 0)
3722 fixup_low_keys(path, &disk_key, 1);
3725 * We create a new leaf 'right' for the required ins_len and
3726 * we'll do btrfs_mark_buffer_dirty() on this leaf after copying
3727 * the content of ins_len to 'right'.
3732 copy_for_split(trans, path, l, right, slot, mid, nritems);
3735 BUG_ON(num_doubles != 0);
3743 push_for_double_split(trans, root, path, data_size);
3744 tried_avoid_double = 1;
3745 if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
3750 static noinline int setup_leaf_for_split(struct btrfs_trans_handle *trans,
3751 struct btrfs_root *root,
3752 struct btrfs_path *path, int ins_len)
3754 struct btrfs_key key;
3755 struct extent_buffer *leaf;
3756 struct btrfs_file_extent_item *fi;
3761 leaf = path->nodes[0];
3762 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3764 BUG_ON(key.type != BTRFS_EXTENT_DATA_KEY &&
3765 key.type != BTRFS_EXTENT_CSUM_KEY);
3767 if (btrfs_leaf_free_space(leaf) >= ins_len)
3770 item_size = btrfs_item_size(leaf, path->slots[0]);
3771 if (key.type == BTRFS_EXTENT_DATA_KEY) {
3772 fi = btrfs_item_ptr(leaf, path->slots[0],
3773 struct btrfs_file_extent_item);
3774 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
3776 btrfs_release_path(path);
3778 path->keep_locks = 1;
3779 path->search_for_split = 1;
3780 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
3781 path->search_for_split = 0;
3788 leaf = path->nodes[0];
3789 /* if our item isn't there, return now */
3790 if (item_size != btrfs_item_size(leaf, path->slots[0]))
3793 /* the leaf has changed, it now has room. return now */
3794 if (btrfs_leaf_free_space(path->nodes[0]) >= ins_len)
3797 if (key.type == BTRFS_EXTENT_DATA_KEY) {
3798 fi = btrfs_item_ptr(leaf, path->slots[0],
3799 struct btrfs_file_extent_item);
3800 if (extent_len != btrfs_file_extent_num_bytes(leaf, fi))
3804 ret = split_leaf(trans, root, &key, path, ins_len, 1);
3808 path->keep_locks = 0;
3809 btrfs_unlock_up_safe(path, 1);
3812 path->keep_locks = 0;
3816 static noinline int split_item(struct btrfs_path *path,
3817 const struct btrfs_key *new_key,
3818 unsigned long split_offset)
3820 struct extent_buffer *leaf;
3821 int orig_slot, slot;
3826 struct btrfs_disk_key disk_key;
3828 leaf = path->nodes[0];
3829 BUG_ON(btrfs_leaf_free_space(leaf) < sizeof(struct btrfs_item));
3831 orig_slot = path->slots[0];
3832 orig_offset = btrfs_item_offset(leaf, path->slots[0]);
3833 item_size = btrfs_item_size(leaf, path->slots[0]);
3835 buf = kmalloc(item_size, GFP_NOFS);
3839 read_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf,
3840 path->slots[0]), item_size);
3842 slot = path->slots[0] + 1;
3843 nritems = btrfs_header_nritems(leaf);
3844 if (slot != nritems) {
3845 /* shift the items */
3846 memmove_leaf_items(leaf, slot + 1, slot, nritems - slot);
3849 btrfs_cpu_key_to_disk(&disk_key, new_key);
3850 btrfs_set_item_key(leaf, &disk_key, slot);
3852 btrfs_set_item_offset(leaf, slot, orig_offset);
3853 btrfs_set_item_size(leaf, slot, item_size - split_offset);
3855 btrfs_set_item_offset(leaf, orig_slot,
3856 orig_offset + item_size - split_offset);
3857 btrfs_set_item_size(leaf, orig_slot, split_offset);
3859 btrfs_set_header_nritems(leaf, nritems + 1);
3861 /* write the data for the start of the original item */
3862 write_extent_buffer(leaf, buf,
3863 btrfs_item_ptr_offset(leaf, path->slots[0]),
3866 /* write the data for the new item */
3867 write_extent_buffer(leaf, buf + split_offset,
3868 btrfs_item_ptr_offset(leaf, slot),
3869 item_size - split_offset);
3870 btrfs_mark_buffer_dirty(leaf);
3872 BUG_ON(btrfs_leaf_free_space(leaf) < 0);
3878 * This function splits a single item into two items,
3879 * giving 'new_key' to the new item and splitting the
3880 * old one at split_offset (from the start of the item).
3882 * The path may be released by this operation. After
3883 * the split, the path is pointing to the old item. The
3884 * new item is going to be in the same node as the old one.
3886 * Note, the item being split must be smaller enough to live alone on
3887 * a tree block with room for one extra struct btrfs_item
3889 * This allows us to split the item in place, keeping a lock on the
3890 * leaf the entire time.
3892 int btrfs_split_item(struct btrfs_trans_handle *trans,
3893 struct btrfs_root *root,
3894 struct btrfs_path *path,
3895 const struct btrfs_key *new_key,
3896 unsigned long split_offset)
3899 ret = setup_leaf_for_split(trans, root, path,
3900 sizeof(struct btrfs_item));
3904 ret = split_item(path, new_key, split_offset);
3909 * make the item pointed to by the path smaller. new_size indicates
3910 * how small to make it, and from_end tells us if we just chop bytes
3911 * off the end of the item or if we shift the item to chop bytes off
3914 void btrfs_truncate_item(struct btrfs_path *path, u32 new_size, int from_end)
3917 struct extent_buffer *leaf;
3919 unsigned int data_end;
3920 unsigned int old_data_start;
3921 unsigned int old_size;
3922 unsigned int size_diff;
3924 struct btrfs_map_token token;
3926 leaf = path->nodes[0];
3927 slot = path->slots[0];
3929 old_size = btrfs_item_size(leaf, slot);
3930 if (old_size == new_size)
3933 nritems = btrfs_header_nritems(leaf);
3934 data_end = leaf_data_end(leaf);
3936 old_data_start = btrfs_item_offset(leaf, slot);
3938 size_diff = old_size - new_size;
3941 BUG_ON(slot >= nritems);
3944 * item0..itemN ... dataN.offset..dataN.size .. data0.size
3946 /* first correct the data pointers */
3947 btrfs_init_map_token(&token, leaf);
3948 for (i = slot; i < nritems; i++) {
3951 ioff = btrfs_token_item_offset(&token, i);
3952 btrfs_set_token_item_offset(&token, i, ioff + size_diff);
3955 /* shift the data */
3957 memmove_leaf_data(leaf, data_end + size_diff, data_end,
3958 old_data_start + new_size - data_end);
3960 struct btrfs_disk_key disk_key;
3963 btrfs_item_key(leaf, &disk_key, slot);
3965 if (btrfs_disk_key_type(&disk_key) == BTRFS_EXTENT_DATA_KEY) {
3967 struct btrfs_file_extent_item *fi;
3969 fi = btrfs_item_ptr(leaf, slot,
3970 struct btrfs_file_extent_item);
3971 fi = (struct btrfs_file_extent_item *)(
3972 (unsigned long)fi - size_diff);
3974 if (btrfs_file_extent_type(leaf, fi) ==
3975 BTRFS_FILE_EXTENT_INLINE) {
3976 ptr = btrfs_item_ptr_offset(leaf, slot);
3977 memmove_extent_buffer(leaf, ptr,
3979 BTRFS_FILE_EXTENT_INLINE_DATA_START);
3983 memmove_leaf_data(leaf, data_end + size_diff, data_end,
3984 old_data_start - data_end);
3986 offset = btrfs_disk_key_offset(&disk_key);
3987 btrfs_set_disk_key_offset(&disk_key, offset + size_diff);
3988 btrfs_set_item_key(leaf, &disk_key, slot);
3990 fixup_low_keys(path, &disk_key, 1);
3993 btrfs_set_item_size(leaf, slot, new_size);
3994 btrfs_mark_buffer_dirty(leaf);
3996 if (btrfs_leaf_free_space(leaf) < 0) {
3997 btrfs_print_leaf(leaf);
4003 * make the item pointed to by the path bigger, data_size is the added size.
4005 void btrfs_extend_item(struct btrfs_path *path, u32 data_size)
4008 struct extent_buffer *leaf;
4010 unsigned int data_end;
4011 unsigned int old_data;
4012 unsigned int old_size;
4014 struct btrfs_map_token token;
4016 leaf = path->nodes[0];
4018 nritems = btrfs_header_nritems(leaf);
4019 data_end = leaf_data_end(leaf);
4021 if (btrfs_leaf_free_space(leaf) < data_size) {
4022 btrfs_print_leaf(leaf);
4025 slot = path->slots[0];
4026 old_data = btrfs_item_data_end(leaf, slot);
4029 if (slot >= nritems) {
4030 btrfs_print_leaf(leaf);
4031 btrfs_crit(leaf->fs_info, "slot %d too large, nritems %d",
4037 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4039 /* first correct the data pointers */
4040 btrfs_init_map_token(&token, leaf);
4041 for (i = slot; i < nritems; i++) {
4044 ioff = btrfs_token_item_offset(&token, i);
4045 btrfs_set_token_item_offset(&token, i, ioff - data_size);
4048 /* shift the data */
4049 memmove_leaf_data(leaf, data_end - data_size, data_end,
4050 old_data - data_end);
4052 data_end = old_data;
4053 old_size = btrfs_item_size(leaf, slot);
4054 btrfs_set_item_size(leaf, slot, old_size + data_size);
4055 btrfs_mark_buffer_dirty(leaf);
4057 if (btrfs_leaf_free_space(leaf) < 0) {
4058 btrfs_print_leaf(leaf);
4064 * Make space in the node before inserting one or more items.
4066 * @root: root we are inserting items to
4067 * @path: points to the leaf/slot where we are going to insert new items
4068 * @batch: information about the batch of items to insert
4070 * Main purpose is to save stack depth by doing the bulk of the work in a
4071 * function that doesn't call btrfs_search_slot
4073 static void setup_items_for_insert(struct btrfs_root *root, struct btrfs_path *path,
4074 const struct btrfs_item_batch *batch)
4076 struct btrfs_fs_info *fs_info = root->fs_info;
4079 unsigned int data_end;
4080 struct btrfs_disk_key disk_key;
4081 struct extent_buffer *leaf;
4083 struct btrfs_map_token token;
4087 * Before anything else, update keys in the parent and other ancestors
4088 * if needed, then release the write locks on them, so that other tasks
4089 * can use them while we modify the leaf.
4091 if (path->slots[0] == 0) {
4092 btrfs_cpu_key_to_disk(&disk_key, &batch->keys[0]);
4093 fixup_low_keys(path, &disk_key, 1);
4095 btrfs_unlock_up_safe(path, 1);
4097 leaf = path->nodes[0];
4098 slot = path->slots[0];
4100 nritems = btrfs_header_nritems(leaf);
4101 data_end = leaf_data_end(leaf);
4102 total_size = batch->total_data_size + (batch->nr * sizeof(struct btrfs_item));
4104 if (btrfs_leaf_free_space(leaf) < total_size) {
4105 btrfs_print_leaf(leaf);
4106 btrfs_crit(fs_info, "not enough freespace need %u have %d",
4107 total_size, btrfs_leaf_free_space(leaf));
4111 btrfs_init_map_token(&token, leaf);
4112 if (slot != nritems) {
4113 unsigned int old_data = btrfs_item_data_end(leaf, slot);
4115 if (old_data < data_end) {
4116 btrfs_print_leaf(leaf);
4118 "item at slot %d with data offset %u beyond data end of leaf %u",
4119 slot, old_data, data_end);
4123 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4125 /* first correct the data pointers */
4126 for (i = slot; i < nritems; i++) {
4129 ioff = btrfs_token_item_offset(&token, i);
4130 btrfs_set_token_item_offset(&token, i,
4131 ioff - batch->total_data_size);
4133 /* shift the items */
4134 memmove_leaf_items(leaf, slot + batch->nr, slot, nritems - slot);
4136 /* shift the data */
4137 memmove_leaf_data(leaf, data_end - batch->total_data_size,
4138 data_end, old_data - data_end);
4139 data_end = old_data;
4142 /* setup the item for the new data */
4143 for (i = 0; i < batch->nr; i++) {
4144 btrfs_cpu_key_to_disk(&disk_key, &batch->keys[i]);
4145 btrfs_set_item_key(leaf, &disk_key, slot + i);
4146 data_end -= batch->data_sizes[i];
4147 btrfs_set_token_item_offset(&token, slot + i, data_end);
4148 btrfs_set_token_item_size(&token, slot + i, batch->data_sizes[i]);
4151 btrfs_set_header_nritems(leaf, nritems + batch->nr);
4152 btrfs_mark_buffer_dirty(leaf);
4154 if (btrfs_leaf_free_space(leaf) < 0) {
4155 btrfs_print_leaf(leaf);
4161 * Insert a new item into a leaf.
4163 * @root: The root of the btree.
4164 * @path: A path pointing to the target leaf and slot.
4165 * @key: The key of the new item.
4166 * @data_size: The size of the data associated with the new key.
4168 void btrfs_setup_item_for_insert(struct btrfs_root *root,
4169 struct btrfs_path *path,
4170 const struct btrfs_key *key,
4173 struct btrfs_item_batch batch;
4176 batch.data_sizes = &data_size;
4177 batch.total_data_size = data_size;
4180 setup_items_for_insert(root, path, &batch);
4184 * Given a key and some data, insert items into the tree.
4185 * This does all the path init required, making room in the tree if needed.
4187 int btrfs_insert_empty_items(struct btrfs_trans_handle *trans,
4188 struct btrfs_root *root,
4189 struct btrfs_path *path,
4190 const struct btrfs_item_batch *batch)
4196 total_size = batch->total_data_size + (batch->nr * sizeof(struct btrfs_item));
4197 ret = btrfs_search_slot(trans, root, &batch->keys[0], path, total_size, 1);
4203 slot = path->slots[0];
4206 setup_items_for_insert(root, path, batch);
4211 * Given a key and some data, insert an item into the tree.
4212 * This does all the path init required, making room in the tree if needed.
4214 int btrfs_insert_item(struct btrfs_trans_handle *trans, struct btrfs_root *root,
4215 const struct btrfs_key *cpu_key, void *data,
4219 struct btrfs_path *path;
4220 struct extent_buffer *leaf;
4223 path = btrfs_alloc_path();
4226 ret = btrfs_insert_empty_item(trans, root, path, cpu_key, data_size);
4228 leaf = path->nodes[0];
4229 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
4230 write_extent_buffer(leaf, data, ptr, data_size);
4231 btrfs_mark_buffer_dirty(leaf);
4233 btrfs_free_path(path);
4238 * This function duplicates an item, giving 'new_key' to the new item.
4239 * It guarantees both items live in the same tree leaf and the new item is
4240 * contiguous with the original item.
4242 * This allows us to split a file extent in place, keeping a lock on the leaf
4245 int btrfs_duplicate_item(struct btrfs_trans_handle *trans,
4246 struct btrfs_root *root,
4247 struct btrfs_path *path,
4248 const struct btrfs_key *new_key)
4250 struct extent_buffer *leaf;
4254 leaf = path->nodes[0];
4255 item_size = btrfs_item_size(leaf, path->slots[0]);
4256 ret = setup_leaf_for_split(trans, root, path,
4257 item_size + sizeof(struct btrfs_item));
4262 btrfs_setup_item_for_insert(root, path, new_key, item_size);
4263 leaf = path->nodes[0];
4264 memcpy_extent_buffer(leaf,
4265 btrfs_item_ptr_offset(leaf, path->slots[0]),
4266 btrfs_item_ptr_offset(leaf, path->slots[0] - 1),
4272 * delete the pointer from a given node.
4274 * the tree should have been previously balanced so the deletion does not
4277 static void del_ptr(struct btrfs_root *root, struct btrfs_path *path,
4278 int level, int slot)
4280 struct extent_buffer *parent = path->nodes[level];
4284 nritems = btrfs_header_nritems(parent);
4285 if (slot != nritems - 1) {
4287 ret = btrfs_tree_mod_log_insert_move(parent, slot,
4288 slot + 1, nritems - slot - 1);
4291 memmove_extent_buffer(parent,
4292 btrfs_node_key_ptr_offset(parent, slot),
4293 btrfs_node_key_ptr_offset(parent, slot + 1),
4294 sizeof(struct btrfs_key_ptr) *
4295 (nritems - slot - 1));
4297 ret = btrfs_tree_mod_log_insert_key(parent, slot,
4298 BTRFS_MOD_LOG_KEY_REMOVE);
4303 btrfs_set_header_nritems(parent, nritems);
4304 if (nritems == 0 && parent == root->node) {
4305 BUG_ON(btrfs_header_level(root->node) != 1);
4306 /* just turn the root into a leaf and break */
4307 btrfs_set_header_level(root->node, 0);
4308 } else if (slot == 0) {
4309 struct btrfs_disk_key disk_key;
4311 btrfs_node_key(parent, &disk_key, 0);
4312 fixup_low_keys(path, &disk_key, level + 1);
4314 btrfs_mark_buffer_dirty(parent);
4318 * a helper function to delete the leaf pointed to by path->slots[1] and
4321 * This deletes the pointer in path->nodes[1] and frees the leaf
4322 * block extent. zero is returned if it all worked out, < 0 otherwise.
4324 * The path must have already been setup for deleting the leaf, including
4325 * all the proper balancing. path->nodes[1] must be locked.
4327 static noinline void btrfs_del_leaf(struct btrfs_trans_handle *trans,
4328 struct btrfs_root *root,
4329 struct btrfs_path *path,
4330 struct extent_buffer *leaf)
4332 WARN_ON(btrfs_header_generation(leaf) != trans->transid);
4333 del_ptr(root, path, 1, path->slots[1]);
4336 * btrfs_free_extent is expensive, we want to make sure we
4337 * aren't holding any locks when we call it
4339 btrfs_unlock_up_safe(path, 0);
4341 root_sub_used(root, leaf->len);
4343 atomic_inc(&leaf->refs);
4344 btrfs_free_tree_block(trans, btrfs_root_id(root), leaf, 0, 1);
4345 free_extent_buffer_stale(leaf);
4348 * delete the item at the leaf level in path. If that empties
4349 * the leaf, remove it from the tree
4351 int btrfs_del_items(struct btrfs_trans_handle *trans, struct btrfs_root *root,
4352 struct btrfs_path *path, int slot, int nr)
4354 struct btrfs_fs_info *fs_info = root->fs_info;
4355 struct extent_buffer *leaf;
4360 leaf = path->nodes[0];
4361 nritems = btrfs_header_nritems(leaf);
4363 if (slot + nr != nritems) {
4364 const u32 last_off = btrfs_item_offset(leaf, slot + nr - 1);
4365 const int data_end = leaf_data_end(leaf);
4366 struct btrfs_map_token token;
4370 for (i = 0; i < nr; i++)
4371 dsize += btrfs_item_size(leaf, slot + i);
4373 memmove_leaf_data(leaf, data_end + dsize, data_end,
4374 last_off - data_end);
4376 btrfs_init_map_token(&token, leaf);
4377 for (i = slot + nr; i < nritems; i++) {
4380 ioff = btrfs_token_item_offset(&token, i);
4381 btrfs_set_token_item_offset(&token, i, ioff + dsize);
4384 memmove_leaf_items(leaf, slot, slot + nr, nritems - slot - nr);
4386 btrfs_set_header_nritems(leaf, nritems - nr);
4389 /* delete the leaf if we've emptied it */
4391 if (leaf == root->node) {
4392 btrfs_set_header_level(leaf, 0);
4394 btrfs_clear_buffer_dirty(trans, leaf);
4395 btrfs_del_leaf(trans, root, path, leaf);
4398 int used = leaf_space_used(leaf, 0, nritems);
4400 struct btrfs_disk_key disk_key;
4402 btrfs_item_key(leaf, &disk_key, 0);
4403 fixup_low_keys(path, &disk_key, 1);
4407 * Try to delete the leaf if it is mostly empty. We do this by
4408 * trying to move all its items into its left and right neighbours.
4409 * If we can't move all the items, then we don't delete it - it's
4410 * not ideal, but future insertions might fill the leaf with more
4411 * items, or items from other leaves might be moved later into our
4412 * leaf due to deletions on those leaves.
4414 if (used < BTRFS_LEAF_DATA_SIZE(fs_info) / 3) {
4417 /* push_leaf_left fixes the path.
4418 * make sure the path still points to our leaf
4419 * for possible call to del_ptr below
4421 slot = path->slots[1];
4422 atomic_inc(&leaf->refs);
4424 * We want to be able to at least push one item to the
4425 * left neighbour leaf, and that's the first item.
4427 min_push_space = sizeof(struct btrfs_item) +
4428 btrfs_item_size(leaf, 0);
4429 wret = push_leaf_left(trans, root, path, 0,
4430 min_push_space, 1, (u32)-1);
4431 if (wret < 0 && wret != -ENOSPC)
4434 if (path->nodes[0] == leaf &&
4435 btrfs_header_nritems(leaf)) {
4437 * If we were not able to push all items from our
4438 * leaf to its left neighbour, then attempt to
4439 * either push all the remaining items to the
4440 * right neighbour or none. There's no advantage
4441 * in pushing only some items, instead of all, as
4442 * it's pointless to end up with a leaf having
4443 * too few items while the neighbours can be full
4446 nritems = btrfs_header_nritems(leaf);
4447 min_push_space = leaf_space_used(leaf, 0, nritems);
4448 wret = push_leaf_right(trans, root, path, 0,
4449 min_push_space, 1, 0);
4450 if (wret < 0 && wret != -ENOSPC)
4454 if (btrfs_header_nritems(leaf) == 0) {
4455 path->slots[1] = slot;
4456 btrfs_del_leaf(trans, root, path, leaf);
4457 free_extent_buffer(leaf);
4460 /* if we're still in the path, make sure
4461 * we're dirty. Otherwise, one of the
4462 * push_leaf functions must have already
4463 * dirtied this buffer
4465 if (path->nodes[0] == leaf)
4466 btrfs_mark_buffer_dirty(leaf);
4467 free_extent_buffer(leaf);
4470 btrfs_mark_buffer_dirty(leaf);
4477 * search the tree again to find a leaf with lesser keys
4478 * returns 0 if it found something or 1 if there are no lesser leaves.
4479 * returns < 0 on io errors.
4481 * This may release the path, and so you may lose any locks held at the
4484 int btrfs_prev_leaf(struct btrfs_root *root, struct btrfs_path *path)
4486 struct btrfs_key key;
4487 struct btrfs_key orig_key;
4488 struct btrfs_disk_key found_key;
4491 btrfs_item_key_to_cpu(path->nodes[0], &key, 0);
4494 if (key.offset > 0) {
4496 } else if (key.type > 0) {
4498 key.offset = (u64)-1;
4499 } else if (key.objectid > 0) {
4502 key.offset = (u64)-1;
4507 btrfs_release_path(path);
4508 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4513 * Previous key not found. Even if we were at slot 0 of the leaf we had
4514 * before releasing the path and calling btrfs_search_slot(), we now may
4515 * be in a slot pointing to the same original key - this can happen if
4516 * after we released the path, one of more items were moved from a
4517 * sibling leaf into the front of the leaf we had due to an insertion
4518 * (see push_leaf_right()).
4519 * If we hit this case and our slot is > 0 and just decrement the slot
4520 * so that the caller does not process the same key again, which may or
4521 * may not break the caller, depending on its logic.
4523 if (path->slots[0] < btrfs_header_nritems(path->nodes[0])) {
4524 btrfs_item_key(path->nodes[0], &found_key, path->slots[0]);
4525 ret = comp_keys(&found_key, &orig_key);
4527 if (path->slots[0] > 0) {
4532 * At slot 0, same key as before, it means orig_key is
4533 * the lowest, leftmost, key in the tree. We're done.
4539 btrfs_item_key(path->nodes[0], &found_key, 0);
4540 ret = comp_keys(&found_key, &key);
4542 * We might have had an item with the previous key in the tree right
4543 * before we released our path. And after we released our path, that
4544 * item might have been pushed to the first slot (0) of the leaf we
4545 * were holding due to a tree balance. Alternatively, an item with the
4546 * previous key can exist as the only element of a leaf (big fat item).
4547 * Therefore account for these 2 cases, so that our callers (like
4548 * btrfs_previous_item) don't miss an existing item with a key matching
4549 * the previous key we computed above.
4557 * A helper function to walk down the tree starting at min_key, and looking
4558 * for nodes or leaves that are have a minimum transaction id.
4559 * This is used by the btree defrag code, and tree logging
4561 * This does not cow, but it does stuff the starting key it finds back
4562 * into min_key, so you can call btrfs_search_slot with cow=1 on the
4563 * key and get a writable path.
4565 * This honors path->lowest_level to prevent descent past a given level
4568 * min_trans indicates the oldest transaction that you are interested
4569 * in walking through. Any nodes or leaves older than min_trans are
4570 * skipped over (without reading them).
4572 * returns zero if something useful was found, < 0 on error and 1 if there
4573 * was nothing in the tree that matched the search criteria.
4575 int btrfs_search_forward(struct btrfs_root *root, struct btrfs_key *min_key,
4576 struct btrfs_path *path,
4579 struct extent_buffer *cur;
4580 struct btrfs_key found_key;
4586 int keep_locks = path->keep_locks;
4588 ASSERT(!path->nowait);
4589 path->keep_locks = 1;
4591 cur = btrfs_read_lock_root_node(root);
4592 level = btrfs_header_level(cur);
4593 WARN_ON(path->nodes[level]);
4594 path->nodes[level] = cur;
4595 path->locks[level] = BTRFS_READ_LOCK;
4597 if (btrfs_header_generation(cur) < min_trans) {
4602 nritems = btrfs_header_nritems(cur);
4603 level = btrfs_header_level(cur);
4604 sret = btrfs_bin_search(cur, 0, min_key, &slot);
4610 /* at the lowest level, we're done, setup the path and exit */
4611 if (level == path->lowest_level) {
4612 if (slot >= nritems)
4615 path->slots[level] = slot;
4616 btrfs_item_key_to_cpu(cur, &found_key, slot);
4619 if (sret && slot > 0)
4622 * check this node pointer against the min_trans parameters.
4623 * If it is too old, skip to the next one.
4625 while (slot < nritems) {
4628 gen = btrfs_node_ptr_generation(cur, slot);
4629 if (gen < min_trans) {
4637 * we didn't find a candidate key in this node, walk forward
4638 * and find another one
4640 if (slot >= nritems) {
4641 path->slots[level] = slot;
4642 sret = btrfs_find_next_key(root, path, min_key, level,
4645 btrfs_release_path(path);
4651 /* save our key for returning back */
4652 btrfs_node_key_to_cpu(cur, &found_key, slot);
4653 path->slots[level] = slot;
4654 if (level == path->lowest_level) {
4658 cur = btrfs_read_node_slot(cur, slot);
4664 btrfs_tree_read_lock(cur);
4666 path->locks[level - 1] = BTRFS_READ_LOCK;
4667 path->nodes[level - 1] = cur;
4668 unlock_up(path, level, 1, 0, NULL);
4671 path->keep_locks = keep_locks;
4673 btrfs_unlock_up_safe(path, path->lowest_level + 1);
4674 memcpy(min_key, &found_key, sizeof(found_key));
4680 * this is similar to btrfs_next_leaf, but does not try to preserve
4681 * and fixup the path. It looks for and returns the next key in the
4682 * tree based on the current path and the min_trans parameters.
4684 * 0 is returned if another key is found, < 0 if there are any errors
4685 * and 1 is returned if there are no higher keys in the tree
4687 * path->keep_locks should be set to 1 on the search made before
4688 * calling this function.
4690 int btrfs_find_next_key(struct btrfs_root *root, struct btrfs_path *path,
4691 struct btrfs_key *key, int level, u64 min_trans)
4694 struct extent_buffer *c;
4696 WARN_ON(!path->keep_locks && !path->skip_locking);
4697 while (level < BTRFS_MAX_LEVEL) {
4698 if (!path->nodes[level])
4701 slot = path->slots[level] + 1;
4702 c = path->nodes[level];
4704 if (slot >= btrfs_header_nritems(c)) {
4707 struct btrfs_key cur_key;
4708 if (level + 1 >= BTRFS_MAX_LEVEL ||
4709 !path->nodes[level + 1])
4712 if (path->locks[level + 1] || path->skip_locking) {
4717 slot = btrfs_header_nritems(c) - 1;
4719 btrfs_item_key_to_cpu(c, &cur_key, slot);
4721 btrfs_node_key_to_cpu(c, &cur_key, slot);
4723 orig_lowest = path->lowest_level;
4724 btrfs_release_path(path);
4725 path->lowest_level = level;
4726 ret = btrfs_search_slot(NULL, root, &cur_key, path,
4728 path->lowest_level = orig_lowest;
4732 c = path->nodes[level];
4733 slot = path->slots[level];
4740 btrfs_item_key_to_cpu(c, key, slot);
4742 u64 gen = btrfs_node_ptr_generation(c, slot);
4744 if (gen < min_trans) {
4748 btrfs_node_key_to_cpu(c, key, slot);
4755 int btrfs_next_old_leaf(struct btrfs_root *root, struct btrfs_path *path,
4760 struct extent_buffer *c;
4761 struct extent_buffer *next;
4762 struct btrfs_fs_info *fs_info = root->fs_info;
4763 struct btrfs_key key;
4764 bool need_commit_sem = false;
4770 * The nowait semantics are used only for write paths, where we don't
4771 * use the tree mod log and sequence numbers.
4774 ASSERT(!path->nowait);
4776 nritems = btrfs_header_nritems(path->nodes[0]);
4780 btrfs_item_key_to_cpu(path->nodes[0], &key, nritems - 1);
4784 btrfs_release_path(path);
4786 path->keep_locks = 1;
4789 ret = btrfs_search_old_slot(root, &key, path, time_seq);
4791 if (path->need_commit_sem) {
4792 path->need_commit_sem = 0;
4793 need_commit_sem = true;
4795 if (!down_read_trylock(&fs_info->commit_root_sem)) {
4800 down_read(&fs_info->commit_root_sem);
4803 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4805 path->keep_locks = 0;
4810 nritems = btrfs_header_nritems(path->nodes[0]);
4812 * by releasing the path above we dropped all our locks. A balance
4813 * could have added more items next to the key that used to be
4814 * at the very end of the block. So, check again here and
4815 * advance the path if there are now more items available.
4817 if (nritems > 0 && path->slots[0] < nritems - 1) {
4824 * So the above check misses one case:
4825 * - after releasing the path above, someone has removed the item that
4826 * used to be at the very end of the block, and balance between leafs
4827 * gets another one with bigger key.offset to replace it.
4829 * This one should be returned as well, or we can get leaf corruption
4830 * later(esp. in __btrfs_drop_extents()).
4832 * And a bit more explanation about this check,
4833 * with ret > 0, the key isn't found, the path points to the slot
4834 * where it should be inserted, so the path->slots[0] item must be the
4837 if (nritems > 0 && ret > 0 && path->slots[0] == nritems - 1) {
4842 while (level < BTRFS_MAX_LEVEL) {
4843 if (!path->nodes[level]) {
4848 slot = path->slots[level] + 1;
4849 c = path->nodes[level];
4850 if (slot >= btrfs_header_nritems(c)) {
4852 if (level == BTRFS_MAX_LEVEL) {
4861 * Our current level is where we're going to start from, and to
4862 * make sure lockdep doesn't complain we need to drop our locks
4863 * and nodes from 0 to our current level.
4865 for (i = 0; i < level; i++) {
4866 if (path->locks[level]) {
4867 btrfs_tree_read_unlock(path->nodes[i]);
4870 free_extent_buffer(path->nodes[i]);
4871 path->nodes[i] = NULL;
4875 ret = read_block_for_search(root, path, &next, level,
4877 if (ret == -EAGAIN && !path->nowait)
4881 btrfs_release_path(path);
4885 if (!path->skip_locking) {
4886 ret = btrfs_try_tree_read_lock(next);
4887 if (!ret && path->nowait) {
4891 if (!ret && time_seq) {
4893 * If we don't get the lock, we may be racing
4894 * with push_leaf_left, holding that lock while
4895 * itself waiting for the leaf we've currently
4896 * locked. To solve this situation, we give up
4897 * on our lock and cycle.
4899 free_extent_buffer(next);
4900 btrfs_release_path(path);
4905 btrfs_tree_read_lock(next);
4909 path->slots[level] = slot;
4912 path->nodes[level] = next;
4913 path->slots[level] = 0;
4914 if (!path->skip_locking)
4915 path->locks[level] = BTRFS_READ_LOCK;
4919 ret = read_block_for_search(root, path, &next, level,
4921 if (ret == -EAGAIN && !path->nowait)
4925 btrfs_release_path(path);
4929 if (!path->skip_locking) {
4931 if (!btrfs_try_tree_read_lock(next)) {
4936 btrfs_tree_read_lock(next);
4942 unlock_up(path, 0, 1, 0, NULL);
4943 if (need_commit_sem) {
4946 path->need_commit_sem = 1;
4947 ret2 = finish_need_commit_sem_search(path);
4948 up_read(&fs_info->commit_root_sem);
4956 int btrfs_next_old_item(struct btrfs_root *root, struct btrfs_path *path, u64 time_seq)
4959 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0]))
4960 return btrfs_next_old_leaf(root, path, time_seq);
4965 * this uses btrfs_prev_leaf to walk backwards in the tree, and keeps
4966 * searching until it gets past min_objectid or finds an item of 'type'
4968 * returns 0 if something is found, 1 if nothing was found and < 0 on error
4970 int btrfs_previous_item(struct btrfs_root *root,
4971 struct btrfs_path *path, u64 min_objectid,
4974 struct btrfs_key found_key;
4975 struct extent_buffer *leaf;
4980 if (path->slots[0] == 0) {
4981 ret = btrfs_prev_leaf(root, path);
4987 leaf = path->nodes[0];
4988 nritems = btrfs_header_nritems(leaf);
4991 if (path->slots[0] == nritems)
4994 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4995 if (found_key.objectid < min_objectid)
4997 if (found_key.type == type)
4999 if (found_key.objectid == min_objectid &&
5000 found_key.type < type)
5007 * search in extent tree to find a previous Metadata/Data extent item with
5010 * returns 0 if something is found, 1 if nothing was found and < 0 on error
5012 int btrfs_previous_extent_item(struct btrfs_root *root,
5013 struct btrfs_path *path, u64 min_objectid)
5015 struct btrfs_key found_key;
5016 struct extent_buffer *leaf;
5021 if (path->slots[0] == 0) {
5022 ret = btrfs_prev_leaf(root, path);
5028 leaf = path->nodes[0];
5029 nritems = btrfs_header_nritems(leaf);
5032 if (path->slots[0] == nritems)
5035 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5036 if (found_key.objectid < min_objectid)
5038 if (found_key.type == BTRFS_EXTENT_ITEM_KEY ||
5039 found_key.type == BTRFS_METADATA_ITEM_KEY)
5041 if (found_key.objectid == min_objectid &&
5042 found_key.type < BTRFS_EXTENT_ITEM_KEY)
5048 int __init btrfs_ctree_init(void)
5050 btrfs_path_cachep = kmem_cache_create("btrfs_path",
5051 sizeof(struct btrfs_path), 0,
5052 SLAB_MEM_SPREAD, NULL);
5053 if (!btrfs_path_cachep)
5058 void __cold btrfs_ctree_exit(void)
5060 kmem_cache_destroy(btrfs_path_cachep);