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>
12 #include "transaction.h"
13 #include "print-tree.h"
18 static int split_node(struct btrfs_trans_handle *trans, struct btrfs_root
19 *root, struct btrfs_path *path, int level);
20 static int split_leaf(struct btrfs_trans_handle *trans, struct btrfs_root *root,
21 const struct btrfs_key *ins_key, struct btrfs_path *path,
22 int data_size, int extend);
23 static int push_node_left(struct btrfs_trans_handle *trans,
24 struct extent_buffer *dst,
25 struct extent_buffer *src, int empty);
26 static int balance_node_right(struct btrfs_trans_handle *trans,
27 struct extent_buffer *dst_buf,
28 struct extent_buffer *src_buf);
29 static void del_ptr(struct btrfs_root *root, struct btrfs_path *path,
32 static const struct btrfs_csums {
35 const char driver[12];
37 [BTRFS_CSUM_TYPE_CRC32] = { .size = 4, .name = "crc32c" },
38 [BTRFS_CSUM_TYPE_XXHASH] = { .size = 8, .name = "xxhash64" },
39 [BTRFS_CSUM_TYPE_SHA256] = { .size = 32, .name = "sha256" },
40 [BTRFS_CSUM_TYPE_BLAKE2] = { .size = 32, .name = "blake2b",
41 .driver = "blake2b-256" },
44 int btrfs_super_csum_size(const struct btrfs_super_block *s)
46 u16 t = btrfs_super_csum_type(s);
48 * csum type is validated at mount time
50 return btrfs_csums[t].size;
53 const char *btrfs_super_csum_name(u16 csum_type)
55 /* csum type is validated at mount time */
56 return btrfs_csums[csum_type].name;
60 * Return driver name if defined, otherwise the name that's also a valid driver
63 const char *btrfs_super_csum_driver(u16 csum_type)
65 /* csum type is validated at mount time */
66 return btrfs_csums[csum_type].driver[0] ?
67 btrfs_csums[csum_type].driver :
68 btrfs_csums[csum_type].name;
71 size_t __attribute_const__ btrfs_get_num_csums(void)
73 return ARRAY_SIZE(btrfs_csums);
76 struct btrfs_path *btrfs_alloc_path(void)
78 return kmem_cache_zalloc(btrfs_path_cachep, GFP_NOFS);
81 /* this also releases the path */
82 void btrfs_free_path(struct btrfs_path *p)
86 btrfs_release_path(p);
87 kmem_cache_free(btrfs_path_cachep, p);
91 * path release drops references on the extent buffers in the path
92 * and it drops any locks held by this path
94 * It is safe to call this on paths that no locks or extent buffers held.
96 noinline void btrfs_release_path(struct btrfs_path *p)
100 for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
105 btrfs_tree_unlock_rw(p->nodes[i], p->locks[i]);
108 free_extent_buffer(p->nodes[i]);
114 * safely gets a reference on the root node of a tree. A lock
115 * is not taken, so a concurrent writer may put a different node
116 * at the root of the tree. See btrfs_lock_root_node for the
119 * The extent buffer returned by this has a reference taken, so
120 * it won't disappear. It may stop being the root of the tree
121 * at any time because there are no locks held.
123 struct extent_buffer *btrfs_root_node(struct btrfs_root *root)
125 struct extent_buffer *eb;
129 eb = rcu_dereference(root->node);
132 * RCU really hurts here, we could free up the root node because
133 * it was COWed but we may not get the new root node yet so do
134 * the inc_not_zero dance and if it doesn't work then
135 * synchronize_rcu and try again.
137 if (atomic_inc_not_zero(&eb->refs)) {
148 * Cowonly root (not-shareable trees, everything not subvolume or reloc roots),
149 * just get put onto a simple dirty list. Transaction walks this list to make
150 * sure they get properly updated on disk.
152 static void add_root_to_dirty_list(struct btrfs_root *root)
154 struct btrfs_fs_info *fs_info = root->fs_info;
156 if (test_bit(BTRFS_ROOT_DIRTY, &root->state) ||
157 !test_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state))
160 spin_lock(&fs_info->trans_lock);
161 if (!test_and_set_bit(BTRFS_ROOT_DIRTY, &root->state)) {
162 /* Want the extent tree to be the last on the list */
163 if (root->root_key.objectid == BTRFS_EXTENT_TREE_OBJECTID)
164 list_move_tail(&root->dirty_list,
165 &fs_info->dirty_cowonly_roots);
167 list_move(&root->dirty_list,
168 &fs_info->dirty_cowonly_roots);
170 spin_unlock(&fs_info->trans_lock);
174 * used by snapshot creation to make a copy of a root for a tree with
175 * a given objectid. The buffer with the new root node is returned in
176 * cow_ret, and this func returns zero on success or a negative error code.
178 int btrfs_copy_root(struct btrfs_trans_handle *trans,
179 struct btrfs_root *root,
180 struct extent_buffer *buf,
181 struct extent_buffer **cow_ret, u64 new_root_objectid)
183 struct btrfs_fs_info *fs_info = root->fs_info;
184 struct extent_buffer *cow;
187 struct btrfs_disk_key disk_key;
189 WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
190 trans->transid != fs_info->running_transaction->transid);
191 WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
192 trans->transid != root->last_trans);
194 level = btrfs_header_level(buf);
196 btrfs_item_key(buf, &disk_key, 0);
198 btrfs_node_key(buf, &disk_key, 0);
200 cow = btrfs_alloc_tree_block(trans, root, 0, new_root_objectid,
201 &disk_key, level, buf->start, 0,
202 BTRFS_NESTING_NEW_ROOT);
206 copy_extent_buffer_full(cow, buf);
207 btrfs_set_header_bytenr(cow, cow->start);
208 btrfs_set_header_generation(cow, trans->transid);
209 btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
210 btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
211 BTRFS_HEADER_FLAG_RELOC);
212 if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
213 btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
215 btrfs_set_header_owner(cow, new_root_objectid);
217 write_extent_buffer_fsid(cow, fs_info->fs_devices->metadata_uuid);
219 WARN_ON(btrfs_header_generation(buf) > trans->transid);
220 if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
221 ret = btrfs_inc_ref(trans, root, cow, 1);
223 ret = btrfs_inc_ref(trans, root, cow, 0);
228 btrfs_mark_buffer_dirty(cow);
237 MOD_LOG_KEY_REMOVE_WHILE_FREEING,
238 MOD_LOG_KEY_REMOVE_WHILE_MOVING,
240 MOD_LOG_ROOT_REPLACE,
243 struct tree_mod_root {
248 struct tree_mod_elem {
254 /* this is used for MOD_LOG_KEY_* and MOD_LOG_MOVE_KEYS operations */
257 /* this is used for MOD_LOG_KEY* and MOD_LOG_ROOT_REPLACE */
260 /* those are used for op == MOD_LOG_KEY_{REPLACE,REMOVE} */
261 struct btrfs_disk_key key;
264 /* this is used for op == MOD_LOG_MOVE_KEYS */
270 /* this is used for op == MOD_LOG_ROOT_REPLACE */
271 struct tree_mod_root old_root;
275 * Pull a new tree mod seq number for our operation.
277 static inline u64 btrfs_inc_tree_mod_seq(struct btrfs_fs_info *fs_info)
279 return atomic64_inc_return(&fs_info->tree_mod_seq);
283 * This adds a new blocker to the tree mod log's blocker list if the @elem
284 * passed does not already have a sequence number set. So when a caller expects
285 * to record tree modifications, it should ensure to set elem->seq to zero
286 * before calling btrfs_get_tree_mod_seq.
287 * Returns a fresh, unused tree log modification sequence number, even if no new
290 u64 btrfs_get_tree_mod_seq(struct btrfs_fs_info *fs_info,
291 struct seq_list *elem)
293 write_lock(&fs_info->tree_mod_log_lock);
295 elem->seq = btrfs_inc_tree_mod_seq(fs_info);
296 list_add_tail(&elem->list, &fs_info->tree_mod_seq_list);
298 write_unlock(&fs_info->tree_mod_log_lock);
303 void btrfs_put_tree_mod_seq(struct btrfs_fs_info *fs_info,
304 struct seq_list *elem)
306 struct rb_root *tm_root;
307 struct rb_node *node;
308 struct rb_node *next;
309 struct tree_mod_elem *tm;
310 u64 min_seq = (u64)-1;
311 u64 seq_putting = elem->seq;
316 write_lock(&fs_info->tree_mod_log_lock);
317 list_del(&elem->list);
320 if (!list_empty(&fs_info->tree_mod_seq_list)) {
321 struct seq_list *first;
323 first = list_first_entry(&fs_info->tree_mod_seq_list,
324 struct seq_list, list);
325 if (seq_putting > first->seq) {
327 * Blocker with lower sequence number exists, we
328 * cannot remove anything from the log.
330 write_unlock(&fs_info->tree_mod_log_lock);
333 min_seq = first->seq;
337 * anything that's lower than the lowest existing (read: blocked)
338 * sequence number can be removed from the tree.
340 tm_root = &fs_info->tree_mod_log;
341 for (node = rb_first(tm_root); node; node = next) {
342 next = rb_next(node);
343 tm = rb_entry(node, struct tree_mod_elem, node);
344 if (tm->seq >= min_seq)
346 rb_erase(node, tm_root);
349 write_unlock(&fs_info->tree_mod_log_lock);
353 * key order of the log:
354 * node/leaf start address -> sequence
356 * The 'start address' is the logical address of the *new* root node
357 * for root replace operations, or the logical address of the affected
358 * block for all other operations.
361 __tree_mod_log_insert(struct btrfs_fs_info *fs_info, struct tree_mod_elem *tm)
363 struct rb_root *tm_root;
364 struct rb_node **new;
365 struct rb_node *parent = NULL;
366 struct tree_mod_elem *cur;
368 lockdep_assert_held_write(&fs_info->tree_mod_log_lock);
370 tm->seq = btrfs_inc_tree_mod_seq(fs_info);
372 tm_root = &fs_info->tree_mod_log;
373 new = &tm_root->rb_node;
375 cur = rb_entry(*new, struct tree_mod_elem, node);
377 if (cur->logical < tm->logical)
378 new = &((*new)->rb_left);
379 else if (cur->logical > tm->logical)
380 new = &((*new)->rb_right);
381 else if (cur->seq < tm->seq)
382 new = &((*new)->rb_left);
383 else if (cur->seq > tm->seq)
384 new = &((*new)->rb_right);
389 rb_link_node(&tm->node, parent, new);
390 rb_insert_color(&tm->node, tm_root);
395 * Determines if logging can be omitted. Returns 1 if it can. Otherwise, it
396 * returns zero with the tree_mod_log_lock acquired. The caller must hold
397 * this until all tree mod log insertions are recorded in the rb tree and then
398 * write unlock fs_info::tree_mod_log_lock.
400 static inline int tree_mod_dont_log(struct btrfs_fs_info *fs_info,
401 struct extent_buffer *eb) {
403 if (list_empty(&(fs_info)->tree_mod_seq_list))
405 if (eb && btrfs_header_level(eb) == 0)
408 write_lock(&fs_info->tree_mod_log_lock);
409 if (list_empty(&(fs_info)->tree_mod_seq_list)) {
410 write_unlock(&fs_info->tree_mod_log_lock);
417 /* Similar to tree_mod_dont_log, but doesn't acquire any locks. */
418 static inline int tree_mod_need_log(const struct btrfs_fs_info *fs_info,
419 struct extent_buffer *eb)
422 if (list_empty(&(fs_info)->tree_mod_seq_list))
424 if (eb && btrfs_header_level(eb) == 0)
430 static struct tree_mod_elem *
431 alloc_tree_mod_elem(struct extent_buffer *eb, int slot,
432 enum mod_log_op op, gfp_t flags)
434 struct tree_mod_elem *tm;
436 tm = kzalloc(sizeof(*tm), flags);
440 tm->logical = eb->start;
441 if (op != MOD_LOG_KEY_ADD) {
442 btrfs_node_key(eb, &tm->key, slot);
443 tm->blockptr = btrfs_node_blockptr(eb, slot);
447 tm->generation = btrfs_node_ptr_generation(eb, slot);
448 RB_CLEAR_NODE(&tm->node);
453 static noinline int tree_mod_log_insert_key(struct extent_buffer *eb, int slot,
454 enum mod_log_op op, gfp_t flags)
456 struct tree_mod_elem *tm;
459 if (!tree_mod_need_log(eb->fs_info, eb))
462 tm = alloc_tree_mod_elem(eb, slot, op, flags);
466 if (tree_mod_dont_log(eb->fs_info, eb)) {
471 ret = __tree_mod_log_insert(eb->fs_info, tm);
472 write_unlock(&eb->fs_info->tree_mod_log_lock);
479 static noinline int tree_mod_log_insert_move(struct extent_buffer *eb,
480 int dst_slot, int src_slot, int nr_items)
482 struct tree_mod_elem *tm = NULL;
483 struct tree_mod_elem **tm_list = NULL;
488 if (!tree_mod_need_log(eb->fs_info, eb))
491 tm_list = kcalloc(nr_items, sizeof(struct tree_mod_elem *), GFP_NOFS);
495 tm = kzalloc(sizeof(*tm), GFP_NOFS);
501 tm->logical = eb->start;
503 tm->move.dst_slot = dst_slot;
504 tm->move.nr_items = nr_items;
505 tm->op = MOD_LOG_MOVE_KEYS;
507 for (i = 0; i + dst_slot < src_slot && i < nr_items; i++) {
508 tm_list[i] = alloc_tree_mod_elem(eb, i + dst_slot,
509 MOD_LOG_KEY_REMOVE_WHILE_MOVING, GFP_NOFS);
516 if (tree_mod_dont_log(eb->fs_info, eb))
521 * When we override something during the move, we log these removals.
522 * This can only happen when we move towards the beginning of the
523 * buffer, i.e. dst_slot < src_slot.
525 for (i = 0; i + dst_slot < src_slot && i < nr_items; i++) {
526 ret = __tree_mod_log_insert(eb->fs_info, tm_list[i]);
531 ret = __tree_mod_log_insert(eb->fs_info, tm);
534 write_unlock(&eb->fs_info->tree_mod_log_lock);
539 for (i = 0; i < nr_items; i++) {
540 if (tm_list[i] && !RB_EMPTY_NODE(&tm_list[i]->node))
541 rb_erase(&tm_list[i]->node, &eb->fs_info->tree_mod_log);
545 write_unlock(&eb->fs_info->tree_mod_log_lock);
553 __tree_mod_log_free_eb(struct btrfs_fs_info *fs_info,
554 struct tree_mod_elem **tm_list,
560 for (i = nritems - 1; i >= 0; i--) {
561 ret = __tree_mod_log_insert(fs_info, tm_list[i]);
563 for (j = nritems - 1; j > i; j--)
564 rb_erase(&tm_list[j]->node,
565 &fs_info->tree_mod_log);
573 static noinline int tree_mod_log_insert_root(struct extent_buffer *old_root,
574 struct extent_buffer *new_root, int log_removal)
576 struct btrfs_fs_info *fs_info = old_root->fs_info;
577 struct tree_mod_elem *tm = NULL;
578 struct tree_mod_elem **tm_list = NULL;
583 if (!tree_mod_need_log(fs_info, NULL))
586 if (log_removal && btrfs_header_level(old_root) > 0) {
587 nritems = btrfs_header_nritems(old_root);
588 tm_list = kcalloc(nritems, sizeof(struct tree_mod_elem *),
594 for (i = 0; i < nritems; i++) {
595 tm_list[i] = alloc_tree_mod_elem(old_root, i,
596 MOD_LOG_KEY_REMOVE_WHILE_FREEING, GFP_NOFS);
604 tm = kzalloc(sizeof(*tm), GFP_NOFS);
610 tm->logical = new_root->start;
611 tm->old_root.logical = old_root->start;
612 tm->old_root.level = btrfs_header_level(old_root);
613 tm->generation = btrfs_header_generation(old_root);
614 tm->op = MOD_LOG_ROOT_REPLACE;
616 if (tree_mod_dont_log(fs_info, NULL))
620 ret = __tree_mod_log_free_eb(fs_info, tm_list, nritems);
622 ret = __tree_mod_log_insert(fs_info, tm);
624 write_unlock(&fs_info->tree_mod_log_lock);
633 for (i = 0; i < nritems; i++)
642 static struct tree_mod_elem *
643 __tree_mod_log_search(struct btrfs_fs_info *fs_info, u64 start, u64 min_seq,
646 struct rb_root *tm_root;
647 struct rb_node *node;
648 struct tree_mod_elem *cur = NULL;
649 struct tree_mod_elem *found = NULL;
651 read_lock(&fs_info->tree_mod_log_lock);
652 tm_root = &fs_info->tree_mod_log;
653 node = tm_root->rb_node;
655 cur = rb_entry(node, struct tree_mod_elem, node);
656 if (cur->logical < start) {
657 node = node->rb_left;
658 } else if (cur->logical > start) {
659 node = node->rb_right;
660 } else if (cur->seq < min_seq) {
661 node = node->rb_left;
662 } else if (!smallest) {
663 /* we want the node with the highest seq */
665 BUG_ON(found->seq > cur->seq);
667 node = node->rb_left;
668 } else if (cur->seq > min_seq) {
669 /* we want the node with the smallest seq */
671 BUG_ON(found->seq < cur->seq);
673 node = node->rb_right;
679 read_unlock(&fs_info->tree_mod_log_lock);
685 * this returns the element from the log with the smallest time sequence
686 * value that's in the log (the oldest log item). any element with a time
687 * sequence lower than min_seq will be ignored.
689 static struct tree_mod_elem *
690 tree_mod_log_search_oldest(struct btrfs_fs_info *fs_info, u64 start,
693 return __tree_mod_log_search(fs_info, start, min_seq, 1);
697 * this returns the element from the log with the largest time sequence
698 * value that's in the log (the most recent log item). any element with
699 * a time sequence lower than min_seq will be ignored.
701 static struct tree_mod_elem *
702 tree_mod_log_search(struct btrfs_fs_info *fs_info, u64 start, u64 min_seq)
704 return __tree_mod_log_search(fs_info, start, min_seq, 0);
707 static noinline int tree_mod_log_eb_copy(struct extent_buffer *dst,
708 struct extent_buffer *src, unsigned long dst_offset,
709 unsigned long src_offset, int nr_items)
711 struct btrfs_fs_info *fs_info = dst->fs_info;
713 struct tree_mod_elem **tm_list = NULL;
714 struct tree_mod_elem **tm_list_add, **tm_list_rem;
718 if (!tree_mod_need_log(fs_info, NULL))
721 if (btrfs_header_level(dst) == 0 && btrfs_header_level(src) == 0)
724 tm_list = kcalloc(nr_items * 2, sizeof(struct tree_mod_elem *),
729 tm_list_add = tm_list;
730 tm_list_rem = tm_list + nr_items;
731 for (i = 0; i < nr_items; i++) {
732 tm_list_rem[i] = alloc_tree_mod_elem(src, i + src_offset,
733 MOD_LOG_KEY_REMOVE, GFP_NOFS);
734 if (!tm_list_rem[i]) {
739 tm_list_add[i] = alloc_tree_mod_elem(dst, i + dst_offset,
740 MOD_LOG_KEY_ADD, GFP_NOFS);
741 if (!tm_list_add[i]) {
747 if (tree_mod_dont_log(fs_info, NULL))
751 for (i = 0; i < nr_items; i++) {
752 ret = __tree_mod_log_insert(fs_info, tm_list_rem[i]);
755 ret = __tree_mod_log_insert(fs_info, tm_list_add[i]);
760 write_unlock(&fs_info->tree_mod_log_lock);
766 for (i = 0; i < nr_items * 2; i++) {
767 if (tm_list[i] && !RB_EMPTY_NODE(&tm_list[i]->node))
768 rb_erase(&tm_list[i]->node, &fs_info->tree_mod_log);
772 write_unlock(&fs_info->tree_mod_log_lock);
778 static noinline int tree_mod_log_free_eb(struct extent_buffer *eb)
780 struct tree_mod_elem **tm_list = NULL;
785 if (btrfs_header_level(eb) == 0)
788 if (!tree_mod_need_log(eb->fs_info, NULL))
791 nritems = btrfs_header_nritems(eb);
792 tm_list = kcalloc(nritems, sizeof(struct tree_mod_elem *), GFP_NOFS);
796 for (i = 0; i < nritems; i++) {
797 tm_list[i] = alloc_tree_mod_elem(eb, i,
798 MOD_LOG_KEY_REMOVE_WHILE_FREEING, GFP_NOFS);
805 if (tree_mod_dont_log(eb->fs_info, eb))
808 ret = __tree_mod_log_free_eb(eb->fs_info, tm_list, nritems);
809 write_unlock(&eb->fs_info->tree_mod_log_lock);
817 for (i = 0; i < nritems; i++)
825 * check if the tree block can be shared by multiple trees
827 int btrfs_block_can_be_shared(struct btrfs_root *root,
828 struct extent_buffer *buf)
831 * Tree blocks not in shareable trees and tree roots are never shared.
832 * If a block was allocated after the last snapshot and the block was
833 * not allocated by tree relocation, we know the block is not shared.
835 if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
836 buf != root->node && buf != root->commit_root &&
837 (btrfs_header_generation(buf) <=
838 btrfs_root_last_snapshot(&root->root_item) ||
839 btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)))
845 static noinline int update_ref_for_cow(struct btrfs_trans_handle *trans,
846 struct btrfs_root *root,
847 struct extent_buffer *buf,
848 struct extent_buffer *cow,
851 struct btrfs_fs_info *fs_info = root->fs_info;
859 * Backrefs update rules:
861 * Always use full backrefs for extent pointers in tree block
862 * allocated by tree relocation.
864 * If a shared tree block is no longer referenced by its owner
865 * tree (btrfs_header_owner(buf) == root->root_key.objectid),
866 * use full backrefs for extent pointers in tree block.
868 * If a tree block is been relocating
869 * (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID),
870 * use full backrefs for extent pointers in tree block.
871 * The reason for this is some operations (such as drop tree)
872 * are only allowed for blocks use full backrefs.
875 if (btrfs_block_can_be_shared(root, buf)) {
876 ret = btrfs_lookup_extent_info(trans, fs_info, buf->start,
877 btrfs_header_level(buf), 1,
883 btrfs_handle_fs_error(fs_info, ret, NULL);
888 if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
889 btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
890 flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
895 owner = btrfs_header_owner(buf);
896 BUG_ON(owner == BTRFS_TREE_RELOC_OBJECTID &&
897 !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
900 if ((owner == root->root_key.objectid ||
901 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) &&
902 !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)) {
903 ret = btrfs_inc_ref(trans, root, buf, 1);
907 if (root->root_key.objectid ==
908 BTRFS_TREE_RELOC_OBJECTID) {
909 ret = btrfs_dec_ref(trans, root, buf, 0);
912 ret = btrfs_inc_ref(trans, root, cow, 1);
916 new_flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
919 if (root->root_key.objectid ==
920 BTRFS_TREE_RELOC_OBJECTID)
921 ret = btrfs_inc_ref(trans, root, cow, 1);
923 ret = btrfs_inc_ref(trans, root, cow, 0);
927 if (new_flags != 0) {
928 int level = btrfs_header_level(buf);
930 ret = btrfs_set_disk_extent_flags(trans, buf,
931 new_flags, level, 0);
936 if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
937 if (root->root_key.objectid ==
938 BTRFS_TREE_RELOC_OBJECTID)
939 ret = btrfs_inc_ref(trans, root, cow, 1);
941 ret = btrfs_inc_ref(trans, root, cow, 0);
944 ret = btrfs_dec_ref(trans, root, buf, 1);
948 btrfs_clean_tree_block(buf);
954 static struct extent_buffer *alloc_tree_block_no_bg_flush(
955 struct btrfs_trans_handle *trans,
956 struct btrfs_root *root,
958 const struct btrfs_disk_key *disk_key,
962 enum btrfs_lock_nesting nest)
964 struct btrfs_fs_info *fs_info = root->fs_info;
965 struct extent_buffer *ret;
968 * If we are COWing a node/leaf from the extent, chunk, device or free
969 * space trees, make sure that we do not finish block group creation of
970 * pending block groups. We do this to avoid a deadlock.
971 * COWing can result in allocation of a new chunk, and flushing pending
972 * block groups (btrfs_create_pending_block_groups()) can be triggered
973 * when finishing allocation of a new chunk. Creation of a pending block
974 * group modifies the extent, chunk, device and free space trees,
975 * therefore we could deadlock with ourselves since we are holding a
976 * lock on an extent buffer that btrfs_create_pending_block_groups() may
978 * For similar reasons, we also need to delay flushing pending block
979 * groups when splitting a leaf or node, from one of those trees, since
980 * we are holding a write lock on it and its parent or when inserting a
981 * new root node for one of those trees.
983 if (root == fs_info->extent_root ||
984 root == fs_info->chunk_root ||
985 root == fs_info->dev_root ||
986 root == fs_info->free_space_root)
987 trans->can_flush_pending_bgs = false;
989 ret = btrfs_alloc_tree_block(trans, root, parent_start,
990 root->root_key.objectid, disk_key, level,
991 hint, empty_size, nest);
992 trans->can_flush_pending_bgs = true;
998 * does the dirty work in cow of a single block. The parent block (if
999 * supplied) is updated to point to the new cow copy. The new buffer is marked
1000 * dirty and returned locked. If you modify the block it needs to be marked
1003 * search_start -- an allocation hint for the new block
1005 * empty_size -- a hint that you plan on doing more cow. This is the size in
1006 * bytes the allocator should try to find free next to the block it returns.
1007 * This is just a hint and may be ignored by the allocator.
1009 static noinline int __btrfs_cow_block(struct btrfs_trans_handle *trans,
1010 struct btrfs_root *root,
1011 struct extent_buffer *buf,
1012 struct extent_buffer *parent, int parent_slot,
1013 struct extent_buffer **cow_ret,
1014 u64 search_start, u64 empty_size,
1015 enum btrfs_lock_nesting nest)
1017 struct btrfs_fs_info *fs_info = root->fs_info;
1018 struct btrfs_disk_key disk_key;
1019 struct extent_buffer *cow;
1022 int unlock_orig = 0;
1023 u64 parent_start = 0;
1025 if (*cow_ret == buf)
1028 btrfs_assert_tree_locked(buf);
1030 WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
1031 trans->transid != fs_info->running_transaction->transid);
1032 WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
1033 trans->transid != root->last_trans);
1035 level = btrfs_header_level(buf);
1038 btrfs_item_key(buf, &disk_key, 0);
1040 btrfs_node_key(buf, &disk_key, 0);
1042 if ((root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) && parent)
1043 parent_start = parent->start;
1045 cow = alloc_tree_block_no_bg_flush(trans, root, parent_start, &disk_key,
1046 level, search_start, empty_size, nest);
1048 return PTR_ERR(cow);
1050 /* cow is set to blocking by btrfs_init_new_buffer */
1052 copy_extent_buffer_full(cow, buf);
1053 btrfs_set_header_bytenr(cow, cow->start);
1054 btrfs_set_header_generation(cow, trans->transid);
1055 btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
1056 btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
1057 BTRFS_HEADER_FLAG_RELOC);
1058 if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
1059 btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
1061 btrfs_set_header_owner(cow, root->root_key.objectid);
1063 write_extent_buffer_fsid(cow, fs_info->fs_devices->metadata_uuid);
1065 ret = update_ref_for_cow(trans, root, buf, cow, &last_ref);
1067 btrfs_tree_unlock(cow);
1068 free_extent_buffer(cow);
1069 btrfs_abort_transaction(trans, ret);
1073 if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state)) {
1074 ret = btrfs_reloc_cow_block(trans, root, buf, cow);
1076 btrfs_tree_unlock(cow);
1077 free_extent_buffer(cow);
1078 btrfs_abort_transaction(trans, ret);
1083 if (buf == root->node) {
1084 WARN_ON(parent && parent != buf);
1085 if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
1086 btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
1087 parent_start = buf->start;
1089 atomic_inc(&cow->refs);
1090 ret = tree_mod_log_insert_root(root->node, cow, 1);
1092 rcu_assign_pointer(root->node, cow);
1094 btrfs_free_tree_block(trans, root, buf, parent_start,
1096 free_extent_buffer(buf);
1097 add_root_to_dirty_list(root);
1099 WARN_ON(trans->transid != btrfs_header_generation(parent));
1100 tree_mod_log_insert_key(parent, parent_slot,
1101 MOD_LOG_KEY_REPLACE, GFP_NOFS);
1102 btrfs_set_node_blockptr(parent, parent_slot,
1104 btrfs_set_node_ptr_generation(parent, parent_slot,
1106 btrfs_mark_buffer_dirty(parent);
1108 ret = tree_mod_log_free_eb(buf);
1110 btrfs_tree_unlock(cow);
1111 free_extent_buffer(cow);
1112 btrfs_abort_transaction(trans, ret);
1116 btrfs_free_tree_block(trans, root, buf, parent_start,
1120 btrfs_tree_unlock(buf);
1121 free_extent_buffer_stale(buf);
1122 btrfs_mark_buffer_dirty(cow);
1128 * returns the logical address of the oldest predecessor of the given root.
1129 * entries older than time_seq are ignored.
1131 static struct tree_mod_elem *__tree_mod_log_oldest_root(
1132 struct extent_buffer *eb_root, u64 time_seq)
1134 struct tree_mod_elem *tm;
1135 struct tree_mod_elem *found = NULL;
1136 u64 root_logical = eb_root->start;
1143 * the very last operation that's logged for a root is the
1144 * replacement operation (if it is replaced at all). this has
1145 * the logical address of the *new* root, making it the very
1146 * first operation that's logged for this root.
1149 tm = tree_mod_log_search_oldest(eb_root->fs_info, root_logical,
1154 * if there are no tree operation for the oldest root, we simply
1155 * return it. this should only happen if that (old) root is at
1162 * if there's an operation that's not a root replacement, we
1163 * found the oldest version of our root. normally, we'll find a
1164 * MOD_LOG_KEY_REMOVE_WHILE_FREEING operation here.
1166 if (tm->op != MOD_LOG_ROOT_REPLACE)
1170 root_logical = tm->old_root.logical;
1174 /* if there's no old root to return, return what we found instead */
1182 * tm is a pointer to the first operation to rewind within eb. then, all
1183 * previous operations will be rewound (until we reach something older than
1187 __tree_mod_log_rewind(struct btrfs_fs_info *fs_info, struct extent_buffer *eb,
1188 u64 time_seq, struct tree_mod_elem *first_tm)
1191 struct rb_node *next;
1192 struct tree_mod_elem *tm = first_tm;
1193 unsigned long o_dst;
1194 unsigned long o_src;
1195 unsigned long p_size = sizeof(struct btrfs_key_ptr);
1197 n = btrfs_header_nritems(eb);
1198 read_lock(&fs_info->tree_mod_log_lock);
1199 while (tm && tm->seq >= time_seq) {
1201 * all the operations are recorded with the operator used for
1202 * the modification. as we're going backwards, we do the
1203 * opposite of each operation here.
1206 case MOD_LOG_KEY_REMOVE_WHILE_FREEING:
1207 BUG_ON(tm->slot < n);
1209 case MOD_LOG_KEY_REMOVE_WHILE_MOVING:
1210 case MOD_LOG_KEY_REMOVE:
1211 btrfs_set_node_key(eb, &tm->key, tm->slot);
1212 btrfs_set_node_blockptr(eb, tm->slot, tm->blockptr);
1213 btrfs_set_node_ptr_generation(eb, tm->slot,
1217 case MOD_LOG_KEY_REPLACE:
1218 BUG_ON(tm->slot >= n);
1219 btrfs_set_node_key(eb, &tm->key, tm->slot);
1220 btrfs_set_node_blockptr(eb, tm->slot, tm->blockptr);
1221 btrfs_set_node_ptr_generation(eb, tm->slot,
1224 case MOD_LOG_KEY_ADD:
1225 /* if a move operation is needed it's in the log */
1228 case MOD_LOG_MOVE_KEYS:
1229 o_dst = btrfs_node_key_ptr_offset(tm->slot);
1230 o_src = btrfs_node_key_ptr_offset(tm->move.dst_slot);
1231 memmove_extent_buffer(eb, o_dst, o_src,
1232 tm->move.nr_items * p_size);
1234 case MOD_LOG_ROOT_REPLACE:
1236 * this operation is special. for roots, this must be
1237 * handled explicitly before rewinding.
1238 * for non-roots, this operation may exist if the node
1239 * was a root: root A -> child B; then A gets empty and
1240 * B is promoted to the new root. in the mod log, we'll
1241 * have a root-replace operation for B, a tree block
1242 * that is no root. we simply ignore that operation.
1246 next = rb_next(&tm->node);
1249 tm = rb_entry(next, struct tree_mod_elem, node);
1250 if (tm->logical != first_tm->logical)
1253 read_unlock(&fs_info->tree_mod_log_lock);
1254 btrfs_set_header_nritems(eb, n);
1258 * Called with eb read locked. If the buffer cannot be rewound, the same buffer
1259 * is returned. If rewind operations happen, a fresh buffer is returned. The
1260 * returned buffer is always read-locked. If the returned buffer is not the
1261 * input buffer, the lock on the input buffer is released and the input buffer
1262 * is freed (its refcount is decremented).
1264 static struct extent_buffer *
1265 tree_mod_log_rewind(struct btrfs_fs_info *fs_info, struct btrfs_path *path,
1266 struct extent_buffer *eb, u64 time_seq)
1268 struct extent_buffer *eb_rewin;
1269 struct tree_mod_elem *tm;
1274 if (btrfs_header_level(eb) == 0)
1277 tm = tree_mod_log_search(fs_info, eb->start, time_seq);
1281 btrfs_set_path_blocking(path);
1282 btrfs_set_lock_blocking_read(eb);
1284 if (tm->op == MOD_LOG_KEY_REMOVE_WHILE_FREEING) {
1285 BUG_ON(tm->slot != 0);
1286 eb_rewin = alloc_dummy_extent_buffer(fs_info, eb->start);
1288 btrfs_tree_read_unlock_blocking(eb);
1289 free_extent_buffer(eb);
1292 btrfs_set_header_bytenr(eb_rewin, eb->start);
1293 btrfs_set_header_backref_rev(eb_rewin,
1294 btrfs_header_backref_rev(eb));
1295 btrfs_set_header_owner(eb_rewin, btrfs_header_owner(eb));
1296 btrfs_set_header_level(eb_rewin, btrfs_header_level(eb));
1298 eb_rewin = btrfs_clone_extent_buffer(eb);
1300 btrfs_tree_read_unlock_blocking(eb);
1301 free_extent_buffer(eb);
1306 btrfs_tree_read_unlock_blocking(eb);
1307 free_extent_buffer(eb);
1309 btrfs_set_buffer_lockdep_class(btrfs_header_owner(eb_rewin),
1310 eb_rewin, btrfs_header_level(eb_rewin));
1311 btrfs_tree_read_lock(eb_rewin);
1312 __tree_mod_log_rewind(fs_info, eb_rewin, time_seq, tm);
1313 WARN_ON(btrfs_header_nritems(eb_rewin) >
1314 BTRFS_NODEPTRS_PER_BLOCK(fs_info));
1320 * get_old_root() rewinds the state of @root's root node to the given @time_seq
1321 * value. If there are no changes, the current root->root_node is returned. If
1322 * anything changed in between, there's a fresh buffer allocated on which the
1323 * rewind operations are done. In any case, the returned buffer is read locked.
1324 * Returns NULL on error (with no locks held).
1326 static inline struct extent_buffer *
1327 get_old_root(struct btrfs_root *root, u64 time_seq)
1329 struct btrfs_fs_info *fs_info = root->fs_info;
1330 struct tree_mod_elem *tm;
1331 struct extent_buffer *eb = NULL;
1332 struct extent_buffer *eb_root;
1333 u64 eb_root_owner = 0;
1334 struct extent_buffer *old;
1335 struct tree_mod_root *old_root = NULL;
1336 u64 old_generation = 0;
1340 eb_root = btrfs_read_lock_root_node(root);
1341 tm = __tree_mod_log_oldest_root(eb_root, time_seq);
1345 if (tm->op == MOD_LOG_ROOT_REPLACE) {
1346 old_root = &tm->old_root;
1347 old_generation = tm->generation;
1348 logical = old_root->logical;
1349 level = old_root->level;
1351 logical = eb_root->start;
1352 level = btrfs_header_level(eb_root);
1355 tm = tree_mod_log_search(fs_info, logical, time_seq);
1356 if (old_root && tm && tm->op != MOD_LOG_KEY_REMOVE_WHILE_FREEING) {
1357 btrfs_tree_read_unlock(eb_root);
1358 free_extent_buffer(eb_root);
1359 old = read_tree_block(fs_info, logical, 0, level, NULL);
1360 if (WARN_ON(IS_ERR(old) || !extent_buffer_uptodate(old))) {
1362 free_extent_buffer(old);
1364 "failed to read tree block %llu from get_old_root",
1367 eb = btrfs_clone_extent_buffer(old);
1368 free_extent_buffer(old);
1370 } else if (old_root) {
1371 eb_root_owner = btrfs_header_owner(eb_root);
1372 btrfs_tree_read_unlock(eb_root);
1373 free_extent_buffer(eb_root);
1374 eb = alloc_dummy_extent_buffer(fs_info, logical);
1376 btrfs_set_lock_blocking_read(eb_root);
1377 eb = btrfs_clone_extent_buffer(eb_root);
1378 btrfs_tree_read_unlock_blocking(eb_root);
1379 free_extent_buffer(eb_root);
1385 btrfs_set_header_bytenr(eb, eb->start);
1386 btrfs_set_header_backref_rev(eb, BTRFS_MIXED_BACKREF_REV);
1387 btrfs_set_header_owner(eb, eb_root_owner);
1388 btrfs_set_header_level(eb, old_root->level);
1389 btrfs_set_header_generation(eb, old_generation);
1391 btrfs_set_buffer_lockdep_class(btrfs_header_owner(eb), eb,
1392 btrfs_header_level(eb));
1393 btrfs_tree_read_lock(eb);
1395 __tree_mod_log_rewind(fs_info, eb, time_seq, tm);
1397 WARN_ON(btrfs_header_level(eb) != 0);
1398 WARN_ON(btrfs_header_nritems(eb) > BTRFS_NODEPTRS_PER_BLOCK(fs_info));
1403 int btrfs_old_root_level(struct btrfs_root *root, u64 time_seq)
1405 struct tree_mod_elem *tm;
1407 struct extent_buffer *eb_root = btrfs_root_node(root);
1409 tm = __tree_mod_log_oldest_root(eb_root, time_seq);
1410 if (tm && tm->op == MOD_LOG_ROOT_REPLACE) {
1411 level = tm->old_root.level;
1413 level = btrfs_header_level(eb_root);
1415 free_extent_buffer(eb_root);
1420 static inline int should_cow_block(struct btrfs_trans_handle *trans,
1421 struct btrfs_root *root,
1422 struct extent_buffer *buf)
1424 if (btrfs_is_testing(root->fs_info))
1427 /* Ensure we can see the FORCE_COW bit */
1428 smp_mb__before_atomic();
1431 * We do not need to cow a block if
1432 * 1) this block is not created or changed in this transaction;
1433 * 2) this block does not belong to TREE_RELOC tree;
1434 * 3) the root is not forced COW.
1436 * What is forced COW:
1437 * when we create snapshot during committing the transaction,
1438 * after we've finished copying src root, we must COW the shared
1439 * block to ensure the metadata consistency.
1441 if (btrfs_header_generation(buf) == trans->transid &&
1442 !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN) &&
1443 !(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
1444 btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)) &&
1445 !test_bit(BTRFS_ROOT_FORCE_COW, &root->state))
1451 * cows a single block, see __btrfs_cow_block for the real work.
1452 * This version of it has extra checks so that a block isn't COWed more than
1453 * once per transaction, as long as it hasn't been written yet
1455 noinline int btrfs_cow_block(struct btrfs_trans_handle *trans,
1456 struct btrfs_root *root, struct extent_buffer *buf,
1457 struct extent_buffer *parent, int parent_slot,
1458 struct extent_buffer **cow_ret,
1459 enum btrfs_lock_nesting nest)
1461 struct btrfs_fs_info *fs_info = root->fs_info;
1465 if (test_bit(BTRFS_ROOT_DELETING, &root->state))
1467 "COW'ing blocks on a fs root that's being dropped");
1469 if (trans->transaction != fs_info->running_transaction)
1470 WARN(1, KERN_CRIT "trans %llu running %llu\n",
1472 fs_info->running_transaction->transid);
1474 if (trans->transid != fs_info->generation)
1475 WARN(1, KERN_CRIT "trans %llu running %llu\n",
1476 trans->transid, fs_info->generation);
1478 if (!should_cow_block(trans, root, buf)) {
1479 trans->dirty = true;
1484 search_start = buf->start & ~((u64)SZ_1G - 1);
1487 btrfs_set_lock_blocking_write(parent);
1488 btrfs_set_lock_blocking_write(buf);
1491 * Before CoWing this block for later modification, check if it's
1492 * the subtree root and do the delayed subtree trace if needed.
1494 * Also We don't care about the error, as it's handled internally.
1496 btrfs_qgroup_trace_subtree_after_cow(trans, root, buf);
1497 ret = __btrfs_cow_block(trans, root, buf, parent,
1498 parent_slot, cow_ret, search_start, 0, nest);
1500 trace_btrfs_cow_block(root, buf, *cow_ret);
1506 * helper function for defrag to decide if two blocks pointed to by a
1507 * node are actually close by
1509 static int close_blocks(u64 blocknr, u64 other, u32 blocksize)
1511 if (blocknr < other && other - (blocknr + blocksize) < 32768)
1513 if (blocknr > other && blocknr - (other + blocksize) < 32768)
1518 #ifdef __LITTLE_ENDIAN
1521 * Compare two keys, on little-endian the disk order is same as CPU order and
1522 * we can avoid the conversion.
1524 static int comp_keys(const struct btrfs_disk_key *disk_key,
1525 const struct btrfs_key *k2)
1527 const struct btrfs_key *k1 = (const struct btrfs_key *)disk_key;
1529 return btrfs_comp_cpu_keys(k1, k2);
1535 * compare two keys in a memcmp fashion
1537 static int comp_keys(const struct btrfs_disk_key *disk,
1538 const struct btrfs_key *k2)
1540 struct btrfs_key k1;
1542 btrfs_disk_key_to_cpu(&k1, disk);
1544 return btrfs_comp_cpu_keys(&k1, k2);
1549 * same as comp_keys only with two btrfs_key's
1551 int __pure btrfs_comp_cpu_keys(const struct btrfs_key *k1, const struct btrfs_key *k2)
1553 if (k1->objectid > k2->objectid)
1555 if (k1->objectid < k2->objectid)
1557 if (k1->type > k2->type)
1559 if (k1->type < k2->type)
1561 if (k1->offset > k2->offset)
1563 if (k1->offset < k2->offset)
1569 * this is used by the defrag code to go through all the
1570 * leaves pointed to by a node and reallocate them so that
1571 * disk order is close to key order
1573 int btrfs_realloc_node(struct btrfs_trans_handle *trans,
1574 struct btrfs_root *root, struct extent_buffer *parent,
1575 int start_slot, u64 *last_ret,
1576 struct btrfs_key *progress)
1578 struct btrfs_fs_info *fs_info = root->fs_info;
1579 struct extent_buffer *cur;
1582 u64 search_start = *last_ret;
1592 int progress_passed = 0;
1593 struct btrfs_disk_key disk_key;
1595 parent_level = btrfs_header_level(parent);
1597 WARN_ON(trans->transaction != fs_info->running_transaction);
1598 WARN_ON(trans->transid != fs_info->generation);
1600 parent_nritems = btrfs_header_nritems(parent);
1601 blocksize = fs_info->nodesize;
1602 end_slot = parent_nritems - 1;
1604 if (parent_nritems <= 1)
1607 btrfs_set_lock_blocking_write(parent);
1609 for (i = start_slot; i <= end_slot; i++) {
1610 struct btrfs_key first_key;
1613 btrfs_node_key(parent, &disk_key, i);
1614 if (!progress_passed && comp_keys(&disk_key, progress) < 0)
1617 progress_passed = 1;
1618 blocknr = btrfs_node_blockptr(parent, i);
1619 gen = btrfs_node_ptr_generation(parent, i);
1620 btrfs_node_key_to_cpu(parent, &first_key, i);
1621 if (last_block == 0)
1622 last_block = blocknr;
1625 other = btrfs_node_blockptr(parent, i - 1);
1626 close = close_blocks(blocknr, other, blocksize);
1628 if (!close && i < end_slot) {
1629 other = btrfs_node_blockptr(parent, i + 1);
1630 close = close_blocks(blocknr, other, blocksize);
1633 last_block = blocknr;
1637 cur = find_extent_buffer(fs_info, blocknr);
1639 uptodate = btrfs_buffer_uptodate(cur, gen, 0);
1642 if (!cur || !uptodate) {
1644 cur = read_tree_block(fs_info, blocknr, gen,
1648 return PTR_ERR(cur);
1649 } else if (!extent_buffer_uptodate(cur)) {
1650 free_extent_buffer(cur);
1653 } else if (!uptodate) {
1654 err = btrfs_read_buffer(cur, gen,
1655 parent_level - 1,&first_key);
1657 free_extent_buffer(cur);
1662 if (search_start == 0)
1663 search_start = last_block;
1665 btrfs_tree_lock(cur);
1666 btrfs_set_lock_blocking_write(cur);
1667 err = __btrfs_cow_block(trans, root, cur, parent, i,
1670 (end_slot - i) * blocksize),
1673 btrfs_tree_unlock(cur);
1674 free_extent_buffer(cur);
1677 search_start = cur->start;
1678 last_block = cur->start;
1679 *last_ret = search_start;
1680 btrfs_tree_unlock(cur);
1681 free_extent_buffer(cur);
1687 * search for key in the extent_buffer. The items start at offset p,
1688 * and they are item_size apart. There are 'max' items in p.
1690 * the slot in the array is returned via slot, and it points to
1691 * the place where you would insert key if it is not found in
1694 * slot may point to max if the key is bigger than all of the keys
1696 static noinline int generic_bin_search(struct extent_buffer *eb,
1697 unsigned long p, int item_size,
1698 const struct btrfs_key *key,
1704 const int key_size = sizeof(struct btrfs_disk_key);
1707 btrfs_err(eb->fs_info,
1708 "%s: low (%d) > high (%d) eb %llu owner %llu level %d",
1709 __func__, low, high, eb->start,
1710 btrfs_header_owner(eb), btrfs_header_level(eb));
1714 while (low < high) {
1716 unsigned long offset;
1717 struct btrfs_disk_key *tmp;
1718 struct btrfs_disk_key unaligned;
1721 mid = (low + high) / 2;
1722 offset = p + mid * item_size;
1723 oip = offset_in_page(offset);
1725 if (oip + key_size <= PAGE_SIZE) {
1726 const unsigned long idx = offset >> PAGE_SHIFT;
1727 char *kaddr = page_address(eb->pages[idx]);
1729 tmp = (struct btrfs_disk_key *)(kaddr + oip);
1731 read_extent_buffer(eb, &unaligned, offset, key_size);
1735 ret = comp_keys(tmp, key);
1751 * simple bin_search frontend that does the right thing for
1754 int btrfs_bin_search(struct extent_buffer *eb, const struct btrfs_key *key,
1757 if (btrfs_header_level(eb) == 0)
1758 return generic_bin_search(eb,
1759 offsetof(struct btrfs_leaf, items),
1760 sizeof(struct btrfs_item),
1761 key, btrfs_header_nritems(eb),
1764 return generic_bin_search(eb,
1765 offsetof(struct btrfs_node, ptrs),
1766 sizeof(struct btrfs_key_ptr),
1767 key, btrfs_header_nritems(eb),
1771 static void root_add_used(struct btrfs_root *root, u32 size)
1773 spin_lock(&root->accounting_lock);
1774 btrfs_set_root_used(&root->root_item,
1775 btrfs_root_used(&root->root_item) + size);
1776 spin_unlock(&root->accounting_lock);
1779 static void root_sub_used(struct btrfs_root *root, u32 size)
1781 spin_lock(&root->accounting_lock);
1782 btrfs_set_root_used(&root->root_item,
1783 btrfs_root_used(&root->root_item) - size);
1784 spin_unlock(&root->accounting_lock);
1787 /* given a node and slot number, this reads the blocks it points to. The
1788 * extent buffer is returned with a reference taken (but unlocked).
1790 struct extent_buffer *btrfs_read_node_slot(struct extent_buffer *parent,
1793 int level = btrfs_header_level(parent);
1794 struct extent_buffer *eb;
1795 struct btrfs_key first_key;
1797 if (slot < 0 || slot >= btrfs_header_nritems(parent))
1798 return ERR_PTR(-ENOENT);
1802 btrfs_node_key_to_cpu(parent, &first_key, slot);
1803 eb = read_tree_block(parent->fs_info, btrfs_node_blockptr(parent, slot),
1804 btrfs_node_ptr_generation(parent, slot),
1805 level - 1, &first_key);
1806 if (!IS_ERR(eb) && !extent_buffer_uptodate(eb)) {
1807 free_extent_buffer(eb);
1815 * node level balancing, used to make sure nodes are in proper order for
1816 * item deletion. We balance from the top down, so we have to make sure
1817 * that a deletion won't leave an node completely empty later on.
1819 static noinline int balance_level(struct btrfs_trans_handle *trans,
1820 struct btrfs_root *root,
1821 struct btrfs_path *path, int level)
1823 struct btrfs_fs_info *fs_info = root->fs_info;
1824 struct extent_buffer *right = NULL;
1825 struct extent_buffer *mid;
1826 struct extent_buffer *left = NULL;
1827 struct extent_buffer *parent = NULL;
1831 int orig_slot = path->slots[level];
1836 mid = path->nodes[level];
1838 WARN_ON(path->locks[level] != BTRFS_WRITE_LOCK &&
1839 path->locks[level] != BTRFS_WRITE_LOCK_BLOCKING);
1840 WARN_ON(btrfs_header_generation(mid) != trans->transid);
1842 orig_ptr = btrfs_node_blockptr(mid, orig_slot);
1844 if (level < BTRFS_MAX_LEVEL - 1) {
1845 parent = path->nodes[level + 1];
1846 pslot = path->slots[level + 1];
1850 * deal with the case where there is only one pointer in the root
1851 * by promoting the node below to a root
1854 struct extent_buffer *child;
1856 if (btrfs_header_nritems(mid) != 1)
1859 /* promote the child to a root */
1860 child = btrfs_read_node_slot(mid, 0);
1861 if (IS_ERR(child)) {
1862 ret = PTR_ERR(child);
1863 btrfs_handle_fs_error(fs_info, ret, NULL);
1867 btrfs_tree_lock(child);
1868 btrfs_set_lock_blocking_write(child);
1869 ret = btrfs_cow_block(trans, root, child, mid, 0, &child,
1872 btrfs_tree_unlock(child);
1873 free_extent_buffer(child);
1877 ret = tree_mod_log_insert_root(root->node, child, 1);
1879 rcu_assign_pointer(root->node, child);
1881 add_root_to_dirty_list(root);
1882 btrfs_tree_unlock(child);
1884 path->locks[level] = 0;
1885 path->nodes[level] = NULL;
1886 btrfs_clean_tree_block(mid);
1887 btrfs_tree_unlock(mid);
1888 /* once for the path */
1889 free_extent_buffer(mid);
1891 root_sub_used(root, mid->len);
1892 btrfs_free_tree_block(trans, root, mid, 0, 1);
1893 /* once for the root ptr */
1894 free_extent_buffer_stale(mid);
1897 if (btrfs_header_nritems(mid) >
1898 BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 4)
1901 left = btrfs_read_node_slot(parent, pslot - 1);
1906 __btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
1907 btrfs_set_lock_blocking_write(left);
1908 wret = btrfs_cow_block(trans, root, left,
1909 parent, pslot - 1, &left,
1910 BTRFS_NESTING_LEFT_COW);
1917 right = btrfs_read_node_slot(parent, pslot + 1);
1922 __btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
1923 btrfs_set_lock_blocking_write(right);
1924 wret = btrfs_cow_block(trans, root, right,
1925 parent, pslot + 1, &right,
1926 BTRFS_NESTING_RIGHT_COW);
1933 /* first, try to make some room in the middle buffer */
1935 orig_slot += btrfs_header_nritems(left);
1936 wret = push_node_left(trans, left, mid, 1);
1942 * then try to empty the right most buffer into the middle
1945 wret = push_node_left(trans, mid, right, 1);
1946 if (wret < 0 && wret != -ENOSPC)
1948 if (btrfs_header_nritems(right) == 0) {
1949 btrfs_clean_tree_block(right);
1950 btrfs_tree_unlock(right);
1951 del_ptr(root, path, level + 1, pslot + 1);
1952 root_sub_used(root, right->len);
1953 btrfs_free_tree_block(trans, root, right, 0, 1);
1954 free_extent_buffer_stale(right);
1957 struct btrfs_disk_key right_key;
1958 btrfs_node_key(right, &right_key, 0);
1959 ret = tree_mod_log_insert_key(parent, pslot + 1,
1960 MOD_LOG_KEY_REPLACE, GFP_NOFS);
1962 btrfs_set_node_key(parent, &right_key, pslot + 1);
1963 btrfs_mark_buffer_dirty(parent);
1966 if (btrfs_header_nritems(mid) == 1) {
1968 * we're not allowed to leave a node with one item in the
1969 * tree during a delete. A deletion from lower in the tree
1970 * could try to delete the only pointer in this node.
1971 * So, pull some keys from the left.
1972 * There has to be a left pointer at this point because
1973 * otherwise we would have pulled some pointers from the
1978 btrfs_handle_fs_error(fs_info, ret, NULL);
1981 wret = balance_node_right(trans, mid, left);
1987 wret = push_node_left(trans, left, mid, 1);
1993 if (btrfs_header_nritems(mid) == 0) {
1994 btrfs_clean_tree_block(mid);
1995 btrfs_tree_unlock(mid);
1996 del_ptr(root, path, level + 1, pslot);
1997 root_sub_used(root, mid->len);
1998 btrfs_free_tree_block(trans, root, mid, 0, 1);
1999 free_extent_buffer_stale(mid);
2002 /* update the parent key to reflect our changes */
2003 struct btrfs_disk_key mid_key;
2004 btrfs_node_key(mid, &mid_key, 0);
2005 ret = tree_mod_log_insert_key(parent, pslot,
2006 MOD_LOG_KEY_REPLACE, GFP_NOFS);
2008 btrfs_set_node_key(parent, &mid_key, pslot);
2009 btrfs_mark_buffer_dirty(parent);
2012 /* update the path */
2014 if (btrfs_header_nritems(left) > orig_slot) {
2015 atomic_inc(&left->refs);
2016 /* left was locked after cow */
2017 path->nodes[level] = left;
2018 path->slots[level + 1] -= 1;
2019 path->slots[level] = orig_slot;
2021 btrfs_tree_unlock(mid);
2022 free_extent_buffer(mid);
2025 orig_slot -= btrfs_header_nritems(left);
2026 path->slots[level] = orig_slot;
2029 /* double check we haven't messed things up */
2031 btrfs_node_blockptr(path->nodes[level], path->slots[level]))
2035 btrfs_tree_unlock(right);
2036 free_extent_buffer(right);
2039 if (path->nodes[level] != left)
2040 btrfs_tree_unlock(left);
2041 free_extent_buffer(left);
2046 /* Node balancing for insertion. Here we only split or push nodes around
2047 * when they are completely full. This is also done top down, so we
2048 * have to be pessimistic.
2050 static noinline int push_nodes_for_insert(struct btrfs_trans_handle *trans,
2051 struct btrfs_root *root,
2052 struct btrfs_path *path, int level)
2054 struct btrfs_fs_info *fs_info = root->fs_info;
2055 struct extent_buffer *right = NULL;
2056 struct extent_buffer *mid;
2057 struct extent_buffer *left = NULL;
2058 struct extent_buffer *parent = NULL;
2062 int orig_slot = path->slots[level];
2067 mid = path->nodes[level];
2068 WARN_ON(btrfs_header_generation(mid) != trans->transid);
2070 if (level < BTRFS_MAX_LEVEL - 1) {
2071 parent = path->nodes[level + 1];
2072 pslot = path->slots[level + 1];
2078 left = btrfs_read_node_slot(parent, pslot - 1);
2082 /* first, try to make some room in the middle buffer */
2086 __btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
2087 btrfs_set_lock_blocking_write(left);
2089 left_nr = btrfs_header_nritems(left);
2090 if (left_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
2093 ret = btrfs_cow_block(trans, root, left, parent,
2095 BTRFS_NESTING_LEFT_COW);
2099 wret = push_node_left(trans, left, mid, 0);
2105 struct btrfs_disk_key disk_key;
2106 orig_slot += left_nr;
2107 btrfs_node_key(mid, &disk_key, 0);
2108 ret = tree_mod_log_insert_key(parent, pslot,
2109 MOD_LOG_KEY_REPLACE, GFP_NOFS);
2111 btrfs_set_node_key(parent, &disk_key, pslot);
2112 btrfs_mark_buffer_dirty(parent);
2113 if (btrfs_header_nritems(left) > orig_slot) {
2114 path->nodes[level] = left;
2115 path->slots[level + 1] -= 1;
2116 path->slots[level] = orig_slot;
2117 btrfs_tree_unlock(mid);
2118 free_extent_buffer(mid);
2121 btrfs_header_nritems(left);
2122 path->slots[level] = orig_slot;
2123 btrfs_tree_unlock(left);
2124 free_extent_buffer(left);
2128 btrfs_tree_unlock(left);
2129 free_extent_buffer(left);
2131 right = btrfs_read_node_slot(parent, pslot + 1);
2136 * then try to empty the right most buffer into the middle
2141 __btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
2142 btrfs_set_lock_blocking_write(right);
2144 right_nr = btrfs_header_nritems(right);
2145 if (right_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
2148 ret = btrfs_cow_block(trans, root, right,
2150 &right, BTRFS_NESTING_RIGHT_COW);
2154 wret = balance_node_right(trans, right, mid);
2160 struct btrfs_disk_key disk_key;
2162 btrfs_node_key(right, &disk_key, 0);
2163 ret = tree_mod_log_insert_key(parent, pslot + 1,
2164 MOD_LOG_KEY_REPLACE, GFP_NOFS);
2166 btrfs_set_node_key(parent, &disk_key, pslot + 1);
2167 btrfs_mark_buffer_dirty(parent);
2169 if (btrfs_header_nritems(mid) <= orig_slot) {
2170 path->nodes[level] = right;
2171 path->slots[level + 1] += 1;
2172 path->slots[level] = orig_slot -
2173 btrfs_header_nritems(mid);
2174 btrfs_tree_unlock(mid);
2175 free_extent_buffer(mid);
2177 btrfs_tree_unlock(right);
2178 free_extent_buffer(right);
2182 btrfs_tree_unlock(right);
2183 free_extent_buffer(right);
2189 * readahead one full node of leaves, finding things that are close
2190 * to the block in 'slot', and triggering ra on them.
2192 static void reada_for_search(struct btrfs_fs_info *fs_info,
2193 struct btrfs_path *path,
2194 int level, int slot, u64 objectid)
2196 struct extent_buffer *node;
2197 struct btrfs_disk_key disk_key;
2202 struct extent_buffer *eb;
2210 if (!path->nodes[level])
2213 node = path->nodes[level];
2215 search = btrfs_node_blockptr(node, slot);
2216 blocksize = fs_info->nodesize;
2217 eb = find_extent_buffer(fs_info, search);
2219 free_extent_buffer(eb);
2225 nritems = btrfs_header_nritems(node);
2229 if (path->reada == READA_BACK) {
2233 } else if (path->reada == READA_FORWARD) {
2238 if (path->reada == READA_BACK && objectid) {
2239 btrfs_node_key(node, &disk_key, nr);
2240 if (btrfs_disk_key_objectid(&disk_key) != objectid)
2243 search = btrfs_node_blockptr(node, nr);
2244 if ((search <= target && target - search <= 65536) ||
2245 (search > target && search - target <= 65536)) {
2246 readahead_tree_block(fs_info, search);
2250 if ((nread > 65536 || nscan > 32))
2255 static noinline void reada_for_balance(struct btrfs_fs_info *fs_info,
2256 struct btrfs_path *path, int level)
2260 struct extent_buffer *parent;
2261 struct extent_buffer *eb;
2266 parent = path->nodes[level + 1];
2270 nritems = btrfs_header_nritems(parent);
2271 slot = path->slots[level + 1];
2274 block1 = btrfs_node_blockptr(parent, slot - 1);
2275 gen = btrfs_node_ptr_generation(parent, slot - 1);
2276 eb = find_extent_buffer(fs_info, block1);
2278 * if we get -eagain from btrfs_buffer_uptodate, we
2279 * don't want to return eagain here. That will loop
2282 if (eb && btrfs_buffer_uptodate(eb, gen, 1) != 0)
2284 free_extent_buffer(eb);
2286 if (slot + 1 < nritems) {
2287 block2 = btrfs_node_blockptr(parent, slot + 1);
2288 gen = btrfs_node_ptr_generation(parent, slot + 1);
2289 eb = find_extent_buffer(fs_info, block2);
2290 if (eb && btrfs_buffer_uptodate(eb, gen, 1) != 0)
2292 free_extent_buffer(eb);
2296 readahead_tree_block(fs_info, block1);
2298 readahead_tree_block(fs_info, block2);
2303 * when we walk down the tree, it is usually safe to unlock the higher layers
2304 * in the tree. The exceptions are when our path goes through slot 0, because
2305 * operations on the tree might require changing key pointers higher up in the
2308 * callers might also have set path->keep_locks, which tells this code to keep
2309 * the lock if the path points to the last slot in the block. This is part of
2310 * walking through the tree, and selecting the next slot in the higher block.
2312 * lowest_unlock sets the lowest level in the tree we're allowed to unlock. so
2313 * if lowest_unlock is 1, level 0 won't be unlocked
2315 static noinline void unlock_up(struct btrfs_path *path, int level,
2316 int lowest_unlock, int min_write_lock_level,
2317 int *write_lock_level)
2320 int skip_level = level;
2322 struct extent_buffer *t;
2324 for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2325 if (!path->nodes[i])
2327 if (!path->locks[i])
2329 if (!no_skips && path->slots[i] == 0) {
2333 if (!no_skips && path->keep_locks) {
2336 nritems = btrfs_header_nritems(t);
2337 if (nritems < 1 || path->slots[i] >= nritems - 1) {
2342 if (skip_level < i && i >= lowest_unlock)
2346 if (i >= lowest_unlock && i > skip_level) {
2347 btrfs_tree_unlock_rw(t, path->locks[i]);
2349 if (write_lock_level &&
2350 i > min_write_lock_level &&
2351 i <= *write_lock_level) {
2352 *write_lock_level = i - 1;
2359 * helper function for btrfs_search_slot. The goal is to find a block
2360 * in cache without setting the path to blocking. If we find the block
2361 * we return zero and the path is unchanged.
2363 * If we can't find the block, we set the path blocking and do some
2364 * reada. -EAGAIN is returned and the search must be repeated.
2367 read_block_for_search(struct btrfs_root *root, struct btrfs_path *p,
2368 struct extent_buffer **eb_ret, int level, int slot,
2369 const struct btrfs_key *key)
2371 struct btrfs_fs_info *fs_info = root->fs_info;
2374 struct extent_buffer *tmp;
2375 struct btrfs_key first_key;
2379 blocknr = btrfs_node_blockptr(*eb_ret, slot);
2380 gen = btrfs_node_ptr_generation(*eb_ret, slot);
2381 parent_level = btrfs_header_level(*eb_ret);
2382 btrfs_node_key_to_cpu(*eb_ret, &first_key, slot);
2384 tmp = find_extent_buffer(fs_info, blocknr);
2386 /* first we do an atomic uptodate check */
2387 if (btrfs_buffer_uptodate(tmp, gen, 1) > 0) {
2389 * Do extra check for first_key, eb can be stale due to
2390 * being cached, read from scrub, or have multiple
2391 * parents (shared tree blocks).
2393 if (btrfs_verify_level_key(tmp,
2394 parent_level - 1, &first_key, gen)) {
2395 free_extent_buffer(tmp);
2402 /* the pages were up to date, but we failed
2403 * the generation number check. Do a full
2404 * read for the generation number that is correct.
2405 * We must do this without dropping locks so
2406 * we can trust our generation number
2408 btrfs_set_path_blocking(p);
2410 /* now we're allowed to do a blocking uptodate check */
2411 ret = btrfs_read_buffer(tmp, gen, parent_level - 1, &first_key);
2416 free_extent_buffer(tmp);
2417 btrfs_release_path(p);
2422 * reduce lock contention at high levels
2423 * of the btree by dropping locks before
2424 * we read. Don't release the lock on the current
2425 * level because we need to walk this node to figure
2426 * out which blocks to read.
2428 btrfs_unlock_up_safe(p, level + 1);
2429 btrfs_set_path_blocking(p);
2431 if (p->reada != READA_NONE)
2432 reada_for_search(fs_info, p, level, slot, key->objectid);
2435 tmp = read_tree_block(fs_info, blocknr, gen, parent_level - 1,
2439 * If the read above didn't mark this buffer up to date,
2440 * it will never end up being up to date. Set ret to EIO now
2441 * and give up so that our caller doesn't loop forever
2444 if (!extent_buffer_uptodate(tmp))
2446 free_extent_buffer(tmp);
2451 btrfs_release_path(p);
2456 * helper function for btrfs_search_slot. This does all of the checks
2457 * for node-level blocks and does any balancing required based on
2460 * If no extra work was required, zero is returned. If we had to
2461 * drop the path, -EAGAIN is returned and btrfs_search_slot must
2465 setup_nodes_for_search(struct btrfs_trans_handle *trans,
2466 struct btrfs_root *root, struct btrfs_path *p,
2467 struct extent_buffer *b, int level, int ins_len,
2468 int *write_lock_level)
2470 struct btrfs_fs_info *fs_info = root->fs_info;
2473 if ((p->search_for_split || ins_len > 0) && btrfs_header_nritems(b) >=
2474 BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3) {
2477 if (*write_lock_level < level + 1) {
2478 *write_lock_level = level + 1;
2479 btrfs_release_path(p);
2483 btrfs_set_path_blocking(p);
2484 reada_for_balance(fs_info, p, level);
2485 sret = split_node(trans, root, p, level);
2492 b = p->nodes[level];
2493 } else if (ins_len < 0 && btrfs_header_nritems(b) <
2494 BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 2) {
2497 if (*write_lock_level < level + 1) {
2498 *write_lock_level = level + 1;
2499 btrfs_release_path(p);
2503 btrfs_set_path_blocking(p);
2504 reada_for_balance(fs_info, p, level);
2505 sret = balance_level(trans, root, p, level);
2511 b = p->nodes[level];
2513 btrfs_release_path(p);
2516 BUG_ON(btrfs_header_nritems(b) == 1);
2526 int btrfs_find_item(struct btrfs_root *fs_root, struct btrfs_path *path,
2527 u64 iobjectid, u64 ioff, u8 key_type,
2528 struct btrfs_key *found_key)
2531 struct btrfs_key key;
2532 struct extent_buffer *eb;
2537 key.type = key_type;
2538 key.objectid = iobjectid;
2541 ret = btrfs_search_slot(NULL, fs_root, &key, path, 0, 0);
2545 eb = path->nodes[0];
2546 if (ret && path->slots[0] >= btrfs_header_nritems(eb)) {
2547 ret = btrfs_next_leaf(fs_root, path);
2550 eb = path->nodes[0];
2553 btrfs_item_key_to_cpu(eb, found_key, path->slots[0]);
2554 if (found_key->type != key.type ||
2555 found_key->objectid != key.objectid)
2561 static struct extent_buffer *btrfs_search_slot_get_root(struct btrfs_root *root,
2562 struct btrfs_path *p,
2563 int write_lock_level)
2565 struct btrfs_fs_info *fs_info = root->fs_info;
2566 struct extent_buffer *b;
2570 /* We try very hard to do read locks on the root */
2571 root_lock = BTRFS_READ_LOCK;
2573 if (p->search_commit_root) {
2575 * The commit roots are read only so we always do read locks,
2576 * and we always must hold the commit_root_sem when doing
2577 * searches on them, the only exception is send where we don't
2578 * want to block transaction commits for a long time, so
2579 * we need to clone the commit root in order to avoid races
2580 * with transaction commits that create a snapshot of one of
2581 * the roots used by a send operation.
2583 if (p->need_commit_sem) {
2584 down_read(&fs_info->commit_root_sem);
2585 b = btrfs_clone_extent_buffer(root->commit_root);
2586 up_read(&fs_info->commit_root_sem);
2588 return ERR_PTR(-ENOMEM);
2591 b = root->commit_root;
2592 atomic_inc(&b->refs);
2594 level = btrfs_header_level(b);
2596 * Ensure that all callers have set skip_locking when
2597 * p->search_commit_root = 1.
2599 ASSERT(p->skip_locking == 1);
2604 if (p->skip_locking) {
2605 b = btrfs_root_node(root);
2606 level = btrfs_header_level(b);
2611 * If the level is set to maximum, we can skip trying to get the read
2614 if (write_lock_level < BTRFS_MAX_LEVEL) {
2616 * We don't know the level of the root node until we actually
2617 * have it read locked
2619 b = __btrfs_read_lock_root_node(root, p->recurse);
2620 level = btrfs_header_level(b);
2621 if (level > write_lock_level)
2624 /* Whoops, must trade for write lock */
2625 btrfs_tree_read_unlock(b);
2626 free_extent_buffer(b);
2629 b = btrfs_lock_root_node(root);
2630 root_lock = BTRFS_WRITE_LOCK;
2632 /* The level might have changed, check again */
2633 level = btrfs_header_level(b);
2636 p->nodes[level] = b;
2637 if (!p->skip_locking)
2638 p->locks[level] = root_lock;
2640 * Callers are responsible for dropping b's references.
2647 * btrfs_search_slot - look for a key in a tree and perform necessary
2648 * modifications to preserve tree invariants.
2650 * @trans: Handle of transaction, used when modifying the tree
2651 * @p: Holds all btree nodes along the search path
2652 * @root: The root node of the tree
2653 * @key: The key we are looking for
2654 * @ins_len: Indicates purpose of search, for inserts it is 1, for
2655 * deletions it's -1. 0 for plain searches
2656 * @cow: boolean should CoW operations be performed. Must always be 1
2657 * when modifying the tree.
2659 * If @ins_len > 0, nodes and leaves will be split as we walk down the tree.
2660 * If @ins_len < 0, nodes will be merged as we walk down the tree (if possible)
2662 * If @key is found, 0 is returned and you can find the item in the leaf level
2663 * of the path (level 0)
2665 * If @key isn't found, 1 is returned and the leaf level of the path (level 0)
2666 * points to the slot where it should be inserted
2668 * If an error is encountered while searching the tree a negative error number
2671 int btrfs_search_slot(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2672 const struct btrfs_key *key, struct btrfs_path *p,
2673 int ins_len, int cow)
2675 struct extent_buffer *b;
2680 int lowest_unlock = 1;
2681 /* everything at write_lock_level or lower must be write locked */
2682 int write_lock_level = 0;
2683 u8 lowest_level = 0;
2684 int min_write_lock_level;
2687 lowest_level = p->lowest_level;
2688 WARN_ON(lowest_level && ins_len > 0);
2689 WARN_ON(p->nodes[0] != NULL);
2690 BUG_ON(!cow && ins_len);
2695 /* when we are removing items, we might have to go up to level
2696 * two as we update tree pointers Make sure we keep write
2697 * for those levels as well
2699 write_lock_level = 2;
2700 } else if (ins_len > 0) {
2702 * for inserting items, make sure we have a write lock on
2703 * level 1 so we can update keys
2705 write_lock_level = 1;
2709 write_lock_level = -1;
2711 if (cow && (p->keep_locks || p->lowest_level))
2712 write_lock_level = BTRFS_MAX_LEVEL;
2714 min_write_lock_level = write_lock_level;
2718 b = btrfs_search_slot_get_root(root, p, write_lock_level);
2727 level = btrfs_header_level(b);
2730 bool last_level = (level == (BTRFS_MAX_LEVEL - 1));
2733 * if we don't really need to cow this block
2734 * then we don't want to set the path blocking,
2735 * so we test it here
2737 if (!should_cow_block(trans, root, b)) {
2738 trans->dirty = true;
2743 * must have write locks on this node and the
2746 if (level > write_lock_level ||
2747 (level + 1 > write_lock_level &&
2748 level + 1 < BTRFS_MAX_LEVEL &&
2749 p->nodes[level + 1])) {
2750 write_lock_level = level + 1;
2751 btrfs_release_path(p);
2755 btrfs_set_path_blocking(p);
2757 err = btrfs_cow_block(trans, root, b, NULL, 0,
2761 err = btrfs_cow_block(trans, root, b,
2762 p->nodes[level + 1],
2763 p->slots[level + 1], &b,
2771 p->nodes[level] = b;
2773 * Leave path with blocking locks to avoid massive
2774 * lock context switch, this is made on purpose.
2778 * we have a lock on b and as long as we aren't changing
2779 * the tree, there is no way to for the items in b to change.
2780 * It is safe to drop the lock on our parent before we
2781 * go through the expensive btree search on b.
2783 * If we're inserting or deleting (ins_len != 0), then we might
2784 * be changing slot zero, which may require changing the parent.
2785 * So, we can't drop the lock until after we know which slot
2786 * we're operating on.
2788 if (!ins_len && !p->keep_locks) {
2791 if (u < BTRFS_MAX_LEVEL && p->locks[u]) {
2792 btrfs_tree_unlock_rw(p->nodes[u], p->locks[u]);
2798 * If btrfs_bin_search returns an exact match (prev_cmp == 0)
2799 * we can safely assume the target key will always be in slot 0
2800 * on lower levels due to the invariants BTRFS' btree provides,
2801 * namely that a btrfs_key_ptr entry always points to the
2802 * lowest key in the child node, thus we can skip searching
2805 if (prev_cmp == 0) {
2809 ret = btrfs_bin_search(b, key, &slot);
2816 p->slots[level] = slot;
2818 btrfs_leaf_free_space(b) < ins_len) {
2819 if (write_lock_level < 1) {
2820 write_lock_level = 1;
2821 btrfs_release_path(p);
2825 btrfs_set_path_blocking(p);
2826 err = split_leaf(trans, root, key,
2827 p, ins_len, ret == 0);
2835 if (!p->search_for_split)
2836 unlock_up(p, level, lowest_unlock,
2837 min_write_lock_level, NULL);
2840 if (ret && slot > 0) {
2844 p->slots[level] = slot;
2845 err = setup_nodes_for_search(trans, root, p, b, level, ins_len,
2853 b = p->nodes[level];
2854 slot = p->slots[level];
2857 * Slot 0 is special, if we change the key we have to update
2858 * the parent pointer which means we must have a write lock on
2861 if (slot == 0 && ins_len && write_lock_level < level + 1) {
2862 write_lock_level = level + 1;
2863 btrfs_release_path(p);
2867 unlock_up(p, level, lowest_unlock, min_write_lock_level,
2870 if (level == lowest_level) {
2876 err = read_block_for_search(root, p, &b, level, slot, key);
2884 if (!p->skip_locking) {
2885 level = btrfs_header_level(b);
2886 if (level <= write_lock_level) {
2887 if (!btrfs_try_tree_write_lock(b)) {
2888 btrfs_set_path_blocking(p);
2891 p->locks[level] = BTRFS_WRITE_LOCK;
2893 if (!btrfs_tree_read_lock_atomic(b)) {
2894 btrfs_set_path_blocking(p);
2895 __btrfs_tree_read_lock(b, BTRFS_NESTING_NORMAL,
2898 p->locks[level] = BTRFS_READ_LOCK;
2900 p->nodes[level] = b;
2906 * we don't really know what they plan on doing with the path
2907 * from here on, so for now just mark it as blocking
2909 if (!p->leave_spinning)
2910 btrfs_set_path_blocking(p);
2911 if (ret < 0 && !p->skip_release_on_error)
2912 btrfs_release_path(p);
2917 * Like btrfs_search_slot, this looks for a key in the given tree. It uses the
2918 * current state of the tree together with the operations recorded in the tree
2919 * modification log to search for the key in a previous version of this tree, as
2920 * denoted by the time_seq parameter.
2922 * Naturally, there is no support for insert, delete or cow operations.
2924 * The resulting path and return value will be set up as if we called
2925 * btrfs_search_slot at that point in time with ins_len and cow both set to 0.
2927 int btrfs_search_old_slot(struct btrfs_root *root, const struct btrfs_key *key,
2928 struct btrfs_path *p, u64 time_seq)
2930 struct btrfs_fs_info *fs_info = root->fs_info;
2931 struct extent_buffer *b;
2936 int lowest_unlock = 1;
2937 u8 lowest_level = 0;
2939 lowest_level = p->lowest_level;
2940 WARN_ON(p->nodes[0] != NULL);
2942 if (p->search_commit_root) {
2944 return btrfs_search_slot(NULL, root, key, p, 0, 0);
2948 b = get_old_root(root, time_seq);
2953 level = btrfs_header_level(b);
2954 p->locks[level] = BTRFS_READ_LOCK;
2959 level = btrfs_header_level(b);
2960 p->nodes[level] = b;
2963 * we have a lock on b and as long as we aren't changing
2964 * the tree, there is no way to for the items in b to change.
2965 * It is safe to drop the lock on our parent before we
2966 * go through the expensive btree search on b.
2968 btrfs_unlock_up_safe(p, level + 1);
2970 ret = btrfs_bin_search(b, key, &slot);
2975 p->slots[level] = slot;
2976 unlock_up(p, level, lowest_unlock, 0, NULL);
2980 if (ret && slot > 0) {
2984 p->slots[level] = slot;
2985 unlock_up(p, level, lowest_unlock, 0, NULL);
2987 if (level == lowest_level) {
2993 err = read_block_for_search(root, p, &b, level, slot, key);
3001 level = btrfs_header_level(b);
3002 if (!btrfs_tree_read_lock_atomic(b)) {
3003 btrfs_set_path_blocking(p);
3004 btrfs_tree_read_lock(b);
3006 b = tree_mod_log_rewind(fs_info, p, b, time_seq);
3011 p->locks[level] = BTRFS_READ_LOCK;
3012 p->nodes[level] = b;
3016 if (!p->leave_spinning)
3017 btrfs_set_path_blocking(p);
3019 btrfs_release_path(p);
3025 * helper to use instead of search slot if no exact match is needed but
3026 * instead the next or previous item should be returned.
3027 * When find_higher is true, the next higher item is returned, the next lower
3029 * When return_any and find_higher are both true, and no higher item is found,
3030 * return the next lower instead.
3031 * When return_any is true and find_higher is false, and no lower item is found,
3032 * return the next higher instead.
3033 * It returns 0 if any item is found, 1 if none is found (tree empty), and
3036 int btrfs_search_slot_for_read(struct btrfs_root *root,
3037 const struct btrfs_key *key,
3038 struct btrfs_path *p, int find_higher,
3042 struct extent_buffer *leaf;
3045 ret = btrfs_search_slot(NULL, root, key, p, 0, 0);
3049 * a return value of 1 means the path is at the position where the
3050 * item should be inserted. Normally this is the next bigger item,
3051 * but in case the previous item is the last in a leaf, path points
3052 * to the first free slot in the previous leaf, i.e. at an invalid
3058 if (p->slots[0] >= btrfs_header_nritems(leaf)) {
3059 ret = btrfs_next_leaf(root, p);
3065 * no higher item found, return the next
3070 btrfs_release_path(p);
3074 if (p->slots[0] == 0) {
3075 ret = btrfs_prev_leaf(root, p);
3080 if (p->slots[0] == btrfs_header_nritems(leaf))
3087 * no lower item found, return the next
3092 btrfs_release_path(p);
3102 * adjust the pointers going up the tree, starting at level
3103 * making sure the right key of each node is points to 'key'.
3104 * This is used after shifting pointers to the left, so it stops
3105 * fixing up pointers when a given leaf/node is not in slot 0 of the
3109 static void fixup_low_keys(struct btrfs_path *path,
3110 struct btrfs_disk_key *key, int level)
3113 struct extent_buffer *t;
3116 for (i = level; i < BTRFS_MAX_LEVEL; i++) {
3117 int tslot = path->slots[i];
3119 if (!path->nodes[i])
3122 ret = tree_mod_log_insert_key(t, tslot, MOD_LOG_KEY_REPLACE,
3125 btrfs_set_node_key(t, key, tslot);
3126 btrfs_mark_buffer_dirty(path->nodes[i]);
3135 * This function isn't completely safe. It's the caller's responsibility
3136 * that the new key won't break the order
3138 void btrfs_set_item_key_safe(struct btrfs_fs_info *fs_info,
3139 struct btrfs_path *path,
3140 const struct btrfs_key *new_key)
3142 struct btrfs_disk_key disk_key;
3143 struct extent_buffer *eb;
3146 eb = path->nodes[0];
3147 slot = path->slots[0];
3149 btrfs_item_key(eb, &disk_key, slot - 1);
3150 if (unlikely(comp_keys(&disk_key, new_key) >= 0)) {
3152 "slot %u key (%llu %u %llu) new key (%llu %u %llu)",
3153 slot, btrfs_disk_key_objectid(&disk_key),
3154 btrfs_disk_key_type(&disk_key),
3155 btrfs_disk_key_offset(&disk_key),
3156 new_key->objectid, new_key->type,
3158 btrfs_print_leaf(eb);
3162 if (slot < btrfs_header_nritems(eb) - 1) {
3163 btrfs_item_key(eb, &disk_key, slot + 1);
3164 if (unlikely(comp_keys(&disk_key, new_key) <= 0)) {
3166 "slot %u key (%llu %u %llu) new key (%llu %u %llu)",
3167 slot, btrfs_disk_key_objectid(&disk_key),
3168 btrfs_disk_key_type(&disk_key),
3169 btrfs_disk_key_offset(&disk_key),
3170 new_key->objectid, new_key->type,
3172 btrfs_print_leaf(eb);
3177 btrfs_cpu_key_to_disk(&disk_key, new_key);
3178 btrfs_set_item_key(eb, &disk_key, slot);
3179 btrfs_mark_buffer_dirty(eb);
3181 fixup_low_keys(path, &disk_key, 1);
3185 * Check key order of two sibling extent buffers.
3187 * Return true if something is wrong.
3188 * Return false if everything is fine.
3190 * Tree-checker only works inside one tree block, thus the following
3191 * corruption can not be detected by tree-checker:
3193 * Leaf @left | Leaf @right
3194 * --------------------------------------------------------------
3195 * | 1 | 2 | 3 | 4 | 5 | f6 | | 7 | 8 |
3197 * Key f6 in leaf @left itself is valid, but not valid when the next
3198 * key in leaf @right is 7.
3199 * This can only be checked at tree block merge time.
3200 * And since tree checker has ensured all key order in each tree block
3201 * is correct, we only need to bother the last key of @left and the first
3204 static bool check_sibling_keys(struct extent_buffer *left,
3205 struct extent_buffer *right)
3207 struct btrfs_key left_last;
3208 struct btrfs_key right_first;
3209 int level = btrfs_header_level(left);
3210 int nr_left = btrfs_header_nritems(left);
3211 int nr_right = btrfs_header_nritems(right);
3213 /* No key to check in one of the tree blocks */
3214 if (!nr_left || !nr_right)
3218 btrfs_node_key_to_cpu(left, &left_last, nr_left - 1);
3219 btrfs_node_key_to_cpu(right, &right_first, 0);
3221 btrfs_item_key_to_cpu(left, &left_last, nr_left - 1);
3222 btrfs_item_key_to_cpu(right, &right_first, 0);
3225 if (btrfs_comp_cpu_keys(&left_last, &right_first) >= 0) {
3226 btrfs_crit(left->fs_info,
3227 "bad key order, sibling blocks, left last (%llu %u %llu) right first (%llu %u %llu)",
3228 left_last.objectid, left_last.type,
3229 left_last.offset, right_first.objectid,
3230 right_first.type, right_first.offset);
3237 * try to push data from one node into the next node left in the
3240 * returns 0 if some ptrs were pushed left, < 0 if there was some horrible
3241 * error, and > 0 if there was no room in the left hand block.
3243 static int push_node_left(struct btrfs_trans_handle *trans,
3244 struct extent_buffer *dst,
3245 struct extent_buffer *src, int empty)
3247 struct btrfs_fs_info *fs_info = trans->fs_info;
3253 src_nritems = btrfs_header_nritems(src);
3254 dst_nritems = btrfs_header_nritems(dst);
3255 push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
3256 WARN_ON(btrfs_header_generation(src) != trans->transid);
3257 WARN_ON(btrfs_header_generation(dst) != trans->transid);
3259 if (!empty && src_nritems <= 8)
3262 if (push_items <= 0)
3266 push_items = min(src_nritems, push_items);
3267 if (push_items < src_nritems) {
3268 /* leave at least 8 pointers in the node if
3269 * we aren't going to empty it
3271 if (src_nritems - push_items < 8) {
3272 if (push_items <= 8)
3278 push_items = min(src_nritems - 8, push_items);
3280 /* dst is the left eb, src is the middle eb */
3281 if (check_sibling_keys(dst, src)) {
3283 btrfs_abort_transaction(trans, ret);
3286 ret = tree_mod_log_eb_copy(dst, src, dst_nritems, 0, push_items);
3288 btrfs_abort_transaction(trans, ret);
3291 copy_extent_buffer(dst, src,
3292 btrfs_node_key_ptr_offset(dst_nritems),
3293 btrfs_node_key_ptr_offset(0),
3294 push_items * sizeof(struct btrfs_key_ptr));
3296 if (push_items < src_nritems) {
3298 * Don't call tree_mod_log_insert_move here, key removal was
3299 * already fully logged by tree_mod_log_eb_copy above.
3301 memmove_extent_buffer(src, btrfs_node_key_ptr_offset(0),
3302 btrfs_node_key_ptr_offset(push_items),
3303 (src_nritems - push_items) *
3304 sizeof(struct btrfs_key_ptr));
3306 btrfs_set_header_nritems(src, src_nritems - push_items);
3307 btrfs_set_header_nritems(dst, dst_nritems + push_items);
3308 btrfs_mark_buffer_dirty(src);
3309 btrfs_mark_buffer_dirty(dst);
3315 * try to push data from one node into the next node right in the
3318 * returns 0 if some ptrs were pushed, < 0 if there was some horrible
3319 * error, and > 0 if there was no room in the right hand block.
3321 * this will only push up to 1/2 the contents of the left node over
3323 static int balance_node_right(struct btrfs_trans_handle *trans,
3324 struct extent_buffer *dst,
3325 struct extent_buffer *src)
3327 struct btrfs_fs_info *fs_info = trans->fs_info;
3334 WARN_ON(btrfs_header_generation(src) != trans->transid);
3335 WARN_ON(btrfs_header_generation(dst) != trans->transid);
3337 src_nritems = btrfs_header_nritems(src);
3338 dst_nritems = btrfs_header_nritems(dst);
3339 push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
3340 if (push_items <= 0)
3343 if (src_nritems < 4)
3346 max_push = src_nritems / 2 + 1;
3347 /* don't try to empty the node */
3348 if (max_push >= src_nritems)
3351 if (max_push < push_items)
3352 push_items = max_push;
3354 /* dst is the right eb, src is the middle eb */
3355 if (check_sibling_keys(src, dst)) {
3357 btrfs_abort_transaction(trans, ret);
3360 ret = tree_mod_log_insert_move(dst, push_items, 0, dst_nritems);
3362 memmove_extent_buffer(dst, btrfs_node_key_ptr_offset(push_items),
3363 btrfs_node_key_ptr_offset(0),
3365 sizeof(struct btrfs_key_ptr));
3367 ret = tree_mod_log_eb_copy(dst, src, 0, src_nritems - push_items,
3370 btrfs_abort_transaction(trans, ret);
3373 copy_extent_buffer(dst, src,
3374 btrfs_node_key_ptr_offset(0),
3375 btrfs_node_key_ptr_offset(src_nritems - push_items),
3376 push_items * sizeof(struct btrfs_key_ptr));
3378 btrfs_set_header_nritems(src, src_nritems - push_items);
3379 btrfs_set_header_nritems(dst, dst_nritems + push_items);
3381 btrfs_mark_buffer_dirty(src);
3382 btrfs_mark_buffer_dirty(dst);
3388 * helper function to insert a new root level in the tree.
3389 * A new node is allocated, and a single item is inserted to
3390 * point to the existing root
3392 * returns zero on success or < 0 on failure.
3394 static noinline int insert_new_root(struct btrfs_trans_handle *trans,
3395 struct btrfs_root *root,
3396 struct btrfs_path *path, int level)
3398 struct btrfs_fs_info *fs_info = root->fs_info;
3400 struct extent_buffer *lower;
3401 struct extent_buffer *c;
3402 struct extent_buffer *old;
3403 struct btrfs_disk_key lower_key;
3406 BUG_ON(path->nodes[level]);
3407 BUG_ON(path->nodes[level-1] != root->node);
3409 lower = path->nodes[level-1];
3411 btrfs_item_key(lower, &lower_key, 0);
3413 btrfs_node_key(lower, &lower_key, 0);
3415 c = alloc_tree_block_no_bg_flush(trans, root, 0, &lower_key, level,
3416 root->node->start, 0,
3417 BTRFS_NESTING_NEW_ROOT);
3421 root_add_used(root, fs_info->nodesize);
3423 btrfs_set_header_nritems(c, 1);
3424 btrfs_set_node_key(c, &lower_key, 0);
3425 btrfs_set_node_blockptr(c, 0, lower->start);
3426 lower_gen = btrfs_header_generation(lower);
3427 WARN_ON(lower_gen != trans->transid);
3429 btrfs_set_node_ptr_generation(c, 0, lower_gen);
3431 btrfs_mark_buffer_dirty(c);
3434 ret = tree_mod_log_insert_root(root->node, c, 0);
3436 rcu_assign_pointer(root->node, c);
3438 /* the super has an extra ref to root->node */
3439 free_extent_buffer(old);
3441 add_root_to_dirty_list(root);
3442 atomic_inc(&c->refs);
3443 path->nodes[level] = c;
3444 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
3445 path->slots[level] = 0;
3450 * worker function to insert a single pointer in a node.
3451 * the node should have enough room for the pointer already
3453 * slot and level indicate where you want the key to go, and
3454 * blocknr is the block the key points to.
3456 static void insert_ptr(struct btrfs_trans_handle *trans,
3457 struct btrfs_path *path,
3458 struct btrfs_disk_key *key, u64 bytenr,
3459 int slot, int level)
3461 struct extent_buffer *lower;
3465 BUG_ON(!path->nodes[level]);
3466 btrfs_assert_tree_locked(path->nodes[level]);
3467 lower = path->nodes[level];
3468 nritems = btrfs_header_nritems(lower);
3469 BUG_ON(slot > nritems);
3470 BUG_ON(nritems == BTRFS_NODEPTRS_PER_BLOCK(trans->fs_info));
3471 if (slot != nritems) {
3473 ret = tree_mod_log_insert_move(lower, slot + 1, slot,
3477 memmove_extent_buffer(lower,
3478 btrfs_node_key_ptr_offset(slot + 1),
3479 btrfs_node_key_ptr_offset(slot),
3480 (nritems - slot) * sizeof(struct btrfs_key_ptr));
3483 ret = tree_mod_log_insert_key(lower, slot, MOD_LOG_KEY_ADD,
3487 btrfs_set_node_key(lower, key, slot);
3488 btrfs_set_node_blockptr(lower, slot, bytenr);
3489 WARN_ON(trans->transid == 0);
3490 btrfs_set_node_ptr_generation(lower, slot, trans->transid);
3491 btrfs_set_header_nritems(lower, nritems + 1);
3492 btrfs_mark_buffer_dirty(lower);
3496 * split the node at the specified level in path in two.
3497 * The path is corrected to point to the appropriate node after the split
3499 * Before splitting this tries to make some room in the node by pushing
3500 * left and right, if either one works, it returns right away.
3502 * returns 0 on success and < 0 on failure
3504 static noinline int split_node(struct btrfs_trans_handle *trans,
3505 struct btrfs_root *root,
3506 struct btrfs_path *path, int level)
3508 struct btrfs_fs_info *fs_info = root->fs_info;
3509 struct extent_buffer *c;
3510 struct extent_buffer *split;
3511 struct btrfs_disk_key disk_key;
3516 c = path->nodes[level];
3517 WARN_ON(btrfs_header_generation(c) != trans->transid);
3518 if (c == root->node) {
3520 * trying to split the root, lets make a new one
3522 * tree mod log: We don't log_removal old root in
3523 * insert_new_root, because that root buffer will be kept as a
3524 * normal node. We are going to log removal of half of the
3525 * elements below with tree_mod_log_eb_copy. We're holding a
3526 * tree lock on the buffer, which is why we cannot race with
3527 * other tree_mod_log users.
3529 ret = insert_new_root(trans, root, path, level + 1);
3533 ret = push_nodes_for_insert(trans, root, path, level);
3534 c = path->nodes[level];
3535 if (!ret && btrfs_header_nritems(c) <
3536 BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3)
3542 c_nritems = btrfs_header_nritems(c);
3543 mid = (c_nritems + 1) / 2;
3544 btrfs_node_key(c, &disk_key, mid);
3546 split = alloc_tree_block_no_bg_flush(trans, root, 0, &disk_key, level,
3547 c->start, 0, BTRFS_NESTING_SPLIT);
3549 return PTR_ERR(split);
3551 root_add_used(root, fs_info->nodesize);
3552 ASSERT(btrfs_header_level(c) == level);
3554 ret = tree_mod_log_eb_copy(split, c, 0, mid, c_nritems - mid);
3556 btrfs_abort_transaction(trans, ret);
3559 copy_extent_buffer(split, c,
3560 btrfs_node_key_ptr_offset(0),
3561 btrfs_node_key_ptr_offset(mid),
3562 (c_nritems - mid) * sizeof(struct btrfs_key_ptr));
3563 btrfs_set_header_nritems(split, c_nritems - mid);
3564 btrfs_set_header_nritems(c, mid);
3567 btrfs_mark_buffer_dirty(c);
3568 btrfs_mark_buffer_dirty(split);
3570 insert_ptr(trans, path, &disk_key, split->start,
3571 path->slots[level + 1] + 1, level + 1);
3573 if (path->slots[level] >= mid) {
3574 path->slots[level] -= mid;
3575 btrfs_tree_unlock(c);
3576 free_extent_buffer(c);
3577 path->nodes[level] = split;
3578 path->slots[level + 1] += 1;
3580 btrfs_tree_unlock(split);
3581 free_extent_buffer(split);
3587 * how many bytes are required to store the items in a leaf. start
3588 * and nr indicate which items in the leaf to check. This totals up the
3589 * space used both by the item structs and the item data
3591 static int leaf_space_used(struct extent_buffer *l, int start, int nr)
3593 struct btrfs_item *start_item;
3594 struct btrfs_item *end_item;
3596 int nritems = btrfs_header_nritems(l);
3597 int end = min(nritems, start + nr) - 1;
3601 start_item = btrfs_item_nr(start);
3602 end_item = btrfs_item_nr(end);
3603 data_len = btrfs_item_offset(l, start_item) +
3604 btrfs_item_size(l, start_item);
3605 data_len = data_len - btrfs_item_offset(l, end_item);
3606 data_len += sizeof(struct btrfs_item) * nr;
3607 WARN_ON(data_len < 0);
3612 * The space between the end of the leaf items and
3613 * the start of the leaf data. IOW, how much room
3614 * the leaf has left for both items and data
3616 noinline int btrfs_leaf_free_space(struct extent_buffer *leaf)
3618 struct btrfs_fs_info *fs_info = leaf->fs_info;
3619 int nritems = btrfs_header_nritems(leaf);
3622 ret = BTRFS_LEAF_DATA_SIZE(fs_info) - leaf_space_used(leaf, 0, nritems);
3625 "leaf free space ret %d, leaf data size %lu, used %d nritems %d",
3627 (unsigned long) BTRFS_LEAF_DATA_SIZE(fs_info),
3628 leaf_space_used(leaf, 0, nritems), nritems);
3634 * min slot controls the lowest index we're willing to push to the
3635 * right. We'll push up to and including min_slot, but no lower
3637 static noinline int __push_leaf_right(struct btrfs_path *path,
3638 int data_size, int empty,
3639 struct extent_buffer *right,
3640 int free_space, u32 left_nritems,
3643 struct btrfs_fs_info *fs_info = right->fs_info;
3644 struct extent_buffer *left = path->nodes[0];
3645 struct extent_buffer *upper = path->nodes[1];
3646 struct btrfs_map_token token;
3647 struct btrfs_disk_key disk_key;
3652 struct btrfs_item *item;
3661 nr = max_t(u32, 1, min_slot);
3663 if (path->slots[0] >= left_nritems)
3664 push_space += data_size;
3666 slot = path->slots[1];
3667 i = left_nritems - 1;
3669 item = btrfs_item_nr(i);
3671 if (!empty && push_items > 0) {
3672 if (path->slots[0] > i)
3674 if (path->slots[0] == i) {
3675 int space = btrfs_leaf_free_space(left);
3677 if (space + push_space * 2 > free_space)
3682 if (path->slots[0] == i)
3683 push_space += data_size;
3685 this_item_size = btrfs_item_size(left, item);
3686 if (this_item_size + sizeof(*item) + push_space > free_space)
3690 push_space += this_item_size + sizeof(*item);
3696 if (push_items == 0)
3699 WARN_ON(!empty && push_items == left_nritems);
3701 /* push left to right */
3702 right_nritems = btrfs_header_nritems(right);
3704 push_space = btrfs_item_end_nr(left, left_nritems - push_items);
3705 push_space -= leaf_data_end(left);
3707 /* make room in the right data area */
3708 data_end = leaf_data_end(right);
3709 memmove_extent_buffer(right,
3710 BTRFS_LEAF_DATA_OFFSET + data_end - push_space,
3711 BTRFS_LEAF_DATA_OFFSET + data_end,
3712 BTRFS_LEAF_DATA_SIZE(fs_info) - data_end);
3714 /* copy from the left data area */
3715 copy_extent_buffer(right, left, BTRFS_LEAF_DATA_OFFSET +
3716 BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
3717 BTRFS_LEAF_DATA_OFFSET + leaf_data_end(left),
3720 memmove_extent_buffer(right, btrfs_item_nr_offset(push_items),
3721 btrfs_item_nr_offset(0),
3722 right_nritems * sizeof(struct btrfs_item));
3724 /* copy the items from left to right */
3725 copy_extent_buffer(right, left, btrfs_item_nr_offset(0),
3726 btrfs_item_nr_offset(left_nritems - push_items),
3727 push_items * sizeof(struct btrfs_item));
3729 /* update the item pointers */
3730 btrfs_init_map_token(&token, right);
3731 right_nritems += push_items;
3732 btrfs_set_header_nritems(right, right_nritems);
3733 push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
3734 for (i = 0; i < right_nritems; i++) {
3735 item = btrfs_item_nr(i);
3736 push_space -= btrfs_token_item_size(&token, item);
3737 btrfs_set_token_item_offset(&token, item, push_space);
3740 left_nritems -= push_items;
3741 btrfs_set_header_nritems(left, left_nritems);
3744 btrfs_mark_buffer_dirty(left);
3746 btrfs_clean_tree_block(left);
3748 btrfs_mark_buffer_dirty(right);
3750 btrfs_item_key(right, &disk_key, 0);
3751 btrfs_set_node_key(upper, &disk_key, slot + 1);
3752 btrfs_mark_buffer_dirty(upper);
3754 /* then fixup the leaf pointer in the path */
3755 if (path->slots[0] >= left_nritems) {
3756 path->slots[0] -= left_nritems;
3757 if (btrfs_header_nritems(path->nodes[0]) == 0)
3758 btrfs_clean_tree_block(path->nodes[0]);
3759 btrfs_tree_unlock(path->nodes[0]);
3760 free_extent_buffer(path->nodes[0]);
3761 path->nodes[0] = right;
3762 path->slots[1] += 1;
3764 btrfs_tree_unlock(right);
3765 free_extent_buffer(right);
3770 btrfs_tree_unlock(right);
3771 free_extent_buffer(right);
3776 * push some data in the path leaf to the right, trying to free up at
3777 * least data_size bytes. returns zero if the push worked, nonzero otherwise
3779 * returns 1 if the push failed because the other node didn't have enough
3780 * room, 0 if everything worked out and < 0 if there were major errors.
3782 * this will push starting from min_slot to the end of the leaf. It won't
3783 * push any slot lower than min_slot
3785 static int push_leaf_right(struct btrfs_trans_handle *trans, struct btrfs_root
3786 *root, struct btrfs_path *path,
3787 int min_data_size, int data_size,
3788 int empty, u32 min_slot)
3790 struct extent_buffer *left = path->nodes[0];
3791 struct extent_buffer *right;
3792 struct extent_buffer *upper;
3798 if (!path->nodes[1])
3801 slot = path->slots[1];
3802 upper = path->nodes[1];
3803 if (slot >= btrfs_header_nritems(upper) - 1)
3806 btrfs_assert_tree_locked(path->nodes[1]);
3808 right = btrfs_read_node_slot(upper, slot + 1);
3810 * slot + 1 is not valid or we fail to read the right node,
3811 * no big deal, just return.
3816 __btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
3817 btrfs_set_lock_blocking_write(right);
3819 free_space = btrfs_leaf_free_space(right);
3820 if (free_space < data_size)
3823 /* cow and double check */
3824 ret = btrfs_cow_block(trans, root, right, upper,
3825 slot + 1, &right, BTRFS_NESTING_RIGHT_COW);
3829 free_space = btrfs_leaf_free_space(right);
3830 if (free_space < data_size)
3833 left_nritems = btrfs_header_nritems(left);
3834 if (left_nritems == 0)
3837 if (check_sibling_keys(left, right)) {
3839 btrfs_tree_unlock(right);
3840 free_extent_buffer(right);
3843 if (path->slots[0] == left_nritems && !empty) {
3844 /* Key greater than all keys in the leaf, right neighbor has
3845 * enough room for it and we're not emptying our leaf to delete
3846 * it, therefore use right neighbor to insert the new item and
3847 * no need to touch/dirty our left leaf. */
3848 btrfs_tree_unlock(left);
3849 free_extent_buffer(left);
3850 path->nodes[0] = right;
3856 return __push_leaf_right(path, min_data_size, empty,
3857 right, free_space, left_nritems, min_slot);
3859 btrfs_tree_unlock(right);
3860 free_extent_buffer(right);
3865 * push some data in the path leaf to the left, trying to free up at
3866 * least data_size bytes. returns zero if the push worked, nonzero otherwise
3868 * max_slot can put a limit on how far into the leaf we'll push items. The
3869 * item at 'max_slot' won't be touched. Use (u32)-1 to make us do all the
3872 static noinline int __push_leaf_left(struct btrfs_path *path, int data_size,
3873 int empty, struct extent_buffer *left,
3874 int free_space, u32 right_nritems,
3877 struct btrfs_fs_info *fs_info = left->fs_info;
3878 struct btrfs_disk_key disk_key;
3879 struct extent_buffer *right = path->nodes[0];
3883 struct btrfs_item *item;
3884 u32 old_left_nritems;
3888 u32 old_left_item_size;
3889 struct btrfs_map_token token;
3892 nr = min(right_nritems, max_slot);
3894 nr = min(right_nritems - 1, max_slot);
3896 for (i = 0; i < nr; i++) {
3897 item = btrfs_item_nr(i);
3899 if (!empty && push_items > 0) {
3900 if (path->slots[0] < i)
3902 if (path->slots[0] == i) {
3903 int space = btrfs_leaf_free_space(right);
3905 if (space + push_space * 2 > free_space)
3910 if (path->slots[0] == i)
3911 push_space += data_size;
3913 this_item_size = btrfs_item_size(right, item);
3914 if (this_item_size + sizeof(*item) + push_space > free_space)
3918 push_space += this_item_size + sizeof(*item);
3921 if (push_items == 0) {
3925 WARN_ON(!empty && push_items == btrfs_header_nritems(right));
3927 /* push data from right to left */
3928 copy_extent_buffer(left, right,
3929 btrfs_item_nr_offset(btrfs_header_nritems(left)),
3930 btrfs_item_nr_offset(0),
3931 push_items * sizeof(struct btrfs_item));
3933 push_space = BTRFS_LEAF_DATA_SIZE(fs_info) -
3934 btrfs_item_offset_nr(right, push_items - 1);
3936 copy_extent_buffer(left, right, BTRFS_LEAF_DATA_OFFSET +
3937 leaf_data_end(left) - push_space,
3938 BTRFS_LEAF_DATA_OFFSET +
3939 btrfs_item_offset_nr(right, push_items - 1),
3941 old_left_nritems = btrfs_header_nritems(left);
3942 BUG_ON(old_left_nritems <= 0);
3944 btrfs_init_map_token(&token, left);
3945 old_left_item_size = btrfs_item_offset_nr(left, old_left_nritems - 1);
3946 for (i = old_left_nritems; i < old_left_nritems + push_items; i++) {
3949 item = btrfs_item_nr(i);
3951 ioff = btrfs_token_item_offset(&token, item);
3952 btrfs_set_token_item_offset(&token, item,
3953 ioff - (BTRFS_LEAF_DATA_SIZE(fs_info) - old_left_item_size));
3955 btrfs_set_header_nritems(left, old_left_nritems + push_items);
3957 /* fixup right node */
3958 if (push_items > right_nritems)
3959 WARN(1, KERN_CRIT "push items %d nr %u\n", push_items,
3962 if (push_items < right_nritems) {
3963 push_space = btrfs_item_offset_nr(right, push_items - 1) -
3964 leaf_data_end(right);
3965 memmove_extent_buffer(right, BTRFS_LEAF_DATA_OFFSET +
3966 BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
3967 BTRFS_LEAF_DATA_OFFSET +
3968 leaf_data_end(right), push_space);
3970 memmove_extent_buffer(right, btrfs_item_nr_offset(0),
3971 btrfs_item_nr_offset(push_items),
3972 (btrfs_header_nritems(right) - push_items) *
3973 sizeof(struct btrfs_item));
3976 btrfs_init_map_token(&token, right);
3977 right_nritems -= push_items;
3978 btrfs_set_header_nritems(right, right_nritems);
3979 push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
3980 for (i = 0; i < right_nritems; i++) {
3981 item = btrfs_item_nr(i);
3983 push_space = push_space - btrfs_token_item_size(&token, item);
3984 btrfs_set_token_item_offset(&token, item, push_space);
3987 btrfs_mark_buffer_dirty(left);
3989 btrfs_mark_buffer_dirty(right);
3991 btrfs_clean_tree_block(right);
3993 btrfs_item_key(right, &disk_key, 0);
3994 fixup_low_keys(path, &disk_key, 1);
3996 /* then fixup the leaf pointer in the path */
3997 if (path->slots[0] < push_items) {
3998 path->slots[0] += old_left_nritems;
3999 btrfs_tree_unlock(path->nodes[0]);
4000 free_extent_buffer(path->nodes[0]);
4001 path->nodes[0] = left;
4002 path->slots[1] -= 1;
4004 btrfs_tree_unlock(left);
4005 free_extent_buffer(left);
4006 path->slots[0] -= push_items;
4008 BUG_ON(path->slots[0] < 0);
4011 btrfs_tree_unlock(left);
4012 free_extent_buffer(left);
4017 * push some data in the path leaf to the left, trying to free up at
4018 * least data_size bytes. returns zero if the push worked, nonzero otherwise
4020 * max_slot can put a limit on how far into the leaf we'll push items. The
4021 * item at 'max_slot' won't be touched. Use (u32)-1 to make us push all the
4024 static int push_leaf_left(struct btrfs_trans_handle *trans, struct btrfs_root
4025 *root, struct btrfs_path *path, int min_data_size,
4026 int data_size, int empty, u32 max_slot)
4028 struct extent_buffer *right = path->nodes[0];
4029 struct extent_buffer *left;
4035 slot = path->slots[1];
4038 if (!path->nodes[1])
4041 right_nritems = btrfs_header_nritems(right);
4042 if (right_nritems == 0)
4045 btrfs_assert_tree_locked(path->nodes[1]);
4047 left = btrfs_read_node_slot(path->nodes[1], slot - 1);
4049 * slot - 1 is not valid or we fail to read the left node,
4050 * no big deal, just return.
4055 __btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
4056 btrfs_set_lock_blocking_write(left);
4058 free_space = btrfs_leaf_free_space(left);
4059 if (free_space < data_size) {
4064 /* cow and double check */
4065 ret = btrfs_cow_block(trans, root, left,
4066 path->nodes[1], slot - 1, &left,
4067 BTRFS_NESTING_LEFT_COW);
4069 /* we hit -ENOSPC, but it isn't fatal here */
4075 free_space = btrfs_leaf_free_space(left);
4076 if (free_space < data_size) {
4081 if (check_sibling_keys(left, right)) {
4085 return __push_leaf_left(path, min_data_size,
4086 empty, left, free_space, right_nritems,
4089 btrfs_tree_unlock(left);
4090 free_extent_buffer(left);
4095 * split the path's leaf in two, making sure there is at least data_size
4096 * available for the resulting leaf level of the path.
4098 static noinline void copy_for_split(struct btrfs_trans_handle *trans,
4099 struct btrfs_path *path,
4100 struct extent_buffer *l,
4101 struct extent_buffer *right,
4102 int slot, int mid, int nritems)
4104 struct btrfs_fs_info *fs_info = trans->fs_info;
4108 struct btrfs_disk_key disk_key;
4109 struct btrfs_map_token token;
4111 nritems = nritems - mid;
4112 btrfs_set_header_nritems(right, nritems);
4113 data_copy_size = btrfs_item_end_nr(l, mid) - leaf_data_end(l);
4115 copy_extent_buffer(right, l, btrfs_item_nr_offset(0),
4116 btrfs_item_nr_offset(mid),
4117 nritems * sizeof(struct btrfs_item));
4119 copy_extent_buffer(right, l,
4120 BTRFS_LEAF_DATA_OFFSET + BTRFS_LEAF_DATA_SIZE(fs_info) -
4121 data_copy_size, BTRFS_LEAF_DATA_OFFSET +
4122 leaf_data_end(l), data_copy_size);
4124 rt_data_off = BTRFS_LEAF_DATA_SIZE(fs_info) - btrfs_item_end_nr(l, mid);
4126 btrfs_init_map_token(&token, right);
4127 for (i = 0; i < nritems; i++) {
4128 struct btrfs_item *item = btrfs_item_nr(i);
4131 ioff = btrfs_token_item_offset(&token, item);
4132 btrfs_set_token_item_offset(&token, item, ioff + rt_data_off);
4135 btrfs_set_header_nritems(l, mid);
4136 btrfs_item_key(right, &disk_key, 0);
4137 insert_ptr(trans, path, &disk_key, right->start, path->slots[1] + 1, 1);
4139 btrfs_mark_buffer_dirty(right);
4140 btrfs_mark_buffer_dirty(l);
4141 BUG_ON(path->slots[0] != slot);
4144 btrfs_tree_unlock(path->nodes[0]);
4145 free_extent_buffer(path->nodes[0]);
4146 path->nodes[0] = right;
4147 path->slots[0] -= mid;
4148 path->slots[1] += 1;
4150 btrfs_tree_unlock(right);
4151 free_extent_buffer(right);
4154 BUG_ON(path->slots[0] < 0);
4158 * double splits happen when we need to insert a big item in the middle
4159 * of a leaf. A double split can leave us with 3 mostly empty leaves:
4160 * leaf: [ slots 0 - N] [ our target ] [ N + 1 - total in leaf ]
4163 * We avoid this by trying to push the items on either side of our target
4164 * into the adjacent leaves. If all goes well we can avoid the double split
4167 static noinline int push_for_double_split(struct btrfs_trans_handle *trans,
4168 struct btrfs_root *root,
4169 struct btrfs_path *path,
4176 int space_needed = data_size;
4178 slot = path->slots[0];
4179 if (slot < btrfs_header_nritems(path->nodes[0]))
4180 space_needed -= btrfs_leaf_free_space(path->nodes[0]);
4183 * try to push all the items after our slot into the
4186 ret = push_leaf_right(trans, root, path, 1, space_needed, 0, slot);
4193 nritems = btrfs_header_nritems(path->nodes[0]);
4195 * our goal is to get our slot at the start or end of a leaf. If
4196 * we've done so we're done
4198 if (path->slots[0] == 0 || path->slots[0] == nritems)
4201 if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
4204 /* try to push all the items before our slot into the next leaf */
4205 slot = path->slots[0];
4206 space_needed = data_size;
4208 space_needed -= btrfs_leaf_free_space(path->nodes[0]);
4209 ret = push_leaf_left(trans, root, path, 1, space_needed, 0, slot);
4222 * split the path's leaf in two, making sure there is at least data_size
4223 * available for the resulting leaf level of the path.
4225 * returns 0 if all went well and < 0 on failure.
4227 static noinline int split_leaf(struct btrfs_trans_handle *trans,
4228 struct btrfs_root *root,
4229 const struct btrfs_key *ins_key,
4230 struct btrfs_path *path, int data_size,
4233 struct btrfs_disk_key disk_key;
4234 struct extent_buffer *l;
4238 struct extent_buffer *right;
4239 struct btrfs_fs_info *fs_info = root->fs_info;
4243 int num_doubles = 0;
4244 int tried_avoid_double = 0;
4247 slot = path->slots[0];
4248 if (extend && data_size + btrfs_item_size_nr(l, slot) +
4249 sizeof(struct btrfs_item) > BTRFS_LEAF_DATA_SIZE(fs_info))
4252 /* first try to make some room by pushing left and right */
4253 if (data_size && path->nodes[1]) {
4254 int space_needed = data_size;
4256 if (slot < btrfs_header_nritems(l))
4257 space_needed -= btrfs_leaf_free_space(l);
4259 wret = push_leaf_right(trans, root, path, space_needed,
4260 space_needed, 0, 0);
4264 space_needed = data_size;
4266 space_needed -= btrfs_leaf_free_space(l);
4267 wret = push_leaf_left(trans, root, path, space_needed,
4268 space_needed, 0, (u32)-1);
4274 /* did the pushes work? */
4275 if (btrfs_leaf_free_space(l) >= data_size)
4279 if (!path->nodes[1]) {
4280 ret = insert_new_root(trans, root, path, 1);
4287 slot = path->slots[0];
4288 nritems = btrfs_header_nritems(l);
4289 mid = (nritems + 1) / 2;
4293 leaf_space_used(l, mid, nritems - mid) + data_size >
4294 BTRFS_LEAF_DATA_SIZE(fs_info)) {
4295 if (slot >= nritems) {
4299 if (mid != nritems &&
4300 leaf_space_used(l, mid, nritems - mid) +
4301 data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
4302 if (data_size && !tried_avoid_double)
4303 goto push_for_double;
4309 if (leaf_space_used(l, 0, mid) + data_size >
4310 BTRFS_LEAF_DATA_SIZE(fs_info)) {
4311 if (!extend && data_size && slot == 0) {
4313 } else if ((extend || !data_size) && slot == 0) {
4317 if (mid != nritems &&
4318 leaf_space_used(l, mid, nritems - mid) +
4319 data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
4320 if (data_size && !tried_avoid_double)
4321 goto push_for_double;
4329 btrfs_cpu_key_to_disk(&disk_key, ins_key);
4331 btrfs_item_key(l, &disk_key, mid);
4334 * We have to about BTRFS_NESTING_NEW_ROOT here if we've done a double
4335 * split, because we're only allowed to have MAX_LOCKDEP_SUBCLASSES
4336 * subclasses, which is 8 at the time of this patch, and we've maxed it
4337 * out. In the future we could add a
4338 * BTRFS_NESTING_SPLIT_THE_SPLITTENING if we need to, but for now just
4339 * use BTRFS_NESTING_NEW_ROOT.
4341 right = alloc_tree_block_no_bg_flush(trans, root, 0, &disk_key, 0,
4342 l->start, 0, num_doubles ?
4343 BTRFS_NESTING_NEW_ROOT :
4344 BTRFS_NESTING_SPLIT);
4346 return PTR_ERR(right);
4348 root_add_used(root, fs_info->nodesize);
4352 btrfs_set_header_nritems(right, 0);
4353 insert_ptr(trans, path, &disk_key,
4354 right->start, path->slots[1] + 1, 1);
4355 btrfs_tree_unlock(path->nodes[0]);
4356 free_extent_buffer(path->nodes[0]);
4357 path->nodes[0] = right;
4359 path->slots[1] += 1;
4361 btrfs_set_header_nritems(right, 0);
4362 insert_ptr(trans, path, &disk_key,
4363 right->start, path->slots[1], 1);
4364 btrfs_tree_unlock(path->nodes[0]);
4365 free_extent_buffer(path->nodes[0]);
4366 path->nodes[0] = right;
4368 if (path->slots[1] == 0)
4369 fixup_low_keys(path, &disk_key, 1);
4372 * We create a new leaf 'right' for the required ins_len and
4373 * we'll do btrfs_mark_buffer_dirty() on this leaf after copying
4374 * the content of ins_len to 'right'.
4379 copy_for_split(trans, path, l, right, slot, mid, nritems);
4382 BUG_ON(num_doubles != 0);
4390 push_for_double_split(trans, root, path, data_size);
4391 tried_avoid_double = 1;
4392 if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
4397 static noinline int setup_leaf_for_split(struct btrfs_trans_handle *trans,
4398 struct btrfs_root *root,
4399 struct btrfs_path *path, int ins_len)
4401 struct btrfs_key key;
4402 struct extent_buffer *leaf;
4403 struct btrfs_file_extent_item *fi;
4408 leaf = path->nodes[0];
4409 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4411 BUG_ON(key.type != BTRFS_EXTENT_DATA_KEY &&
4412 key.type != BTRFS_EXTENT_CSUM_KEY);
4414 if (btrfs_leaf_free_space(leaf) >= ins_len)
4417 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
4418 if (key.type == BTRFS_EXTENT_DATA_KEY) {
4419 fi = btrfs_item_ptr(leaf, path->slots[0],
4420 struct btrfs_file_extent_item);
4421 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
4423 btrfs_release_path(path);
4425 path->keep_locks = 1;
4426 path->search_for_split = 1;
4427 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
4428 path->search_for_split = 0;
4435 leaf = path->nodes[0];
4436 /* if our item isn't there, return now */
4437 if (item_size != btrfs_item_size_nr(leaf, path->slots[0]))
4440 /* the leaf has changed, it now has room. return now */
4441 if (btrfs_leaf_free_space(path->nodes[0]) >= ins_len)
4444 if (key.type == BTRFS_EXTENT_DATA_KEY) {
4445 fi = btrfs_item_ptr(leaf, path->slots[0],
4446 struct btrfs_file_extent_item);
4447 if (extent_len != btrfs_file_extent_num_bytes(leaf, fi))
4451 btrfs_set_path_blocking(path);
4452 ret = split_leaf(trans, root, &key, path, ins_len, 1);
4456 path->keep_locks = 0;
4457 btrfs_unlock_up_safe(path, 1);
4460 path->keep_locks = 0;
4464 static noinline int split_item(struct btrfs_path *path,
4465 const struct btrfs_key *new_key,
4466 unsigned long split_offset)
4468 struct extent_buffer *leaf;
4469 struct btrfs_item *item;
4470 struct btrfs_item *new_item;
4476 struct btrfs_disk_key disk_key;
4478 leaf = path->nodes[0];
4479 BUG_ON(btrfs_leaf_free_space(leaf) < sizeof(struct btrfs_item));
4481 btrfs_set_path_blocking(path);
4483 item = btrfs_item_nr(path->slots[0]);
4484 orig_offset = btrfs_item_offset(leaf, item);
4485 item_size = btrfs_item_size(leaf, item);
4487 buf = kmalloc(item_size, GFP_NOFS);
4491 read_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf,
4492 path->slots[0]), item_size);
4494 slot = path->slots[0] + 1;
4495 nritems = btrfs_header_nritems(leaf);
4496 if (slot != nritems) {
4497 /* shift the items */
4498 memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + 1),
4499 btrfs_item_nr_offset(slot),
4500 (nritems - slot) * sizeof(struct btrfs_item));
4503 btrfs_cpu_key_to_disk(&disk_key, new_key);
4504 btrfs_set_item_key(leaf, &disk_key, slot);
4506 new_item = btrfs_item_nr(slot);
4508 btrfs_set_item_offset(leaf, new_item, orig_offset);
4509 btrfs_set_item_size(leaf, new_item, item_size - split_offset);
4511 btrfs_set_item_offset(leaf, item,
4512 orig_offset + item_size - split_offset);
4513 btrfs_set_item_size(leaf, item, split_offset);
4515 btrfs_set_header_nritems(leaf, nritems + 1);
4517 /* write the data for the start of the original item */
4518 write_extent_buffer(leaf, buf,
4519 btrfs_item_ptr_offset(leaf, path->slots[0]),
4522 /* write the data for the new item */
4523 write_extent_buffer(leaf, buf + split_offset,
4524 btrfs_item_ptr_offset(leaf, slot),
4525 item_size - split_offset);
4526 btrfs_mark_buffer_dirty(leaf);
4528 BUG_ON(btrfs_leaf_free_space(leaf) < 0);
4534 * This function splits a single item into two items,
4535 * giving 'new_key' to the new item and splitting the
4536 * old one at split_offset (from the start of the item).
4538 * The path may be released by this operation. After
4539 * the split, the path is pointing to the old item. The
4540 * new item is going to be in the same node as the old one.
4542 * Note, the item being split must be smaller enough to live alone on
4543 * a tree block with room for one extra struct btrfs_item
4545 * This allows us to split the item in place, keeping a lock on the
4546 * leaf the entire time.
4548 int btrfs_split_item(struct btrfs_trans_handle *trans,
4549 struct btrfs_root *root,
4550 struct btrfs_path *path,
4551 const struct btrfs_key *new_key,
4552 unsigned long split_offset)
4555 ret = setup_leaf_for_split(trans, root, path,
4556 sizeof(struct btrfs_item));
4560 ret = split_item(path, new_key, split_offset);
4565 * This function duplicate a item, giving 'new_key' to the new item.
4566 * It guarantees both items live in the same tree leaf and the new item
4567 * is contiguous with the original item.
4569 * This allows us to split file extent in place, keeping a lock on the
4570 * leaf the entire time.
4572 int btrfs_duplicate_item(struct btrfs_trans_handle *trans,
4573 struct btrfs_root *root,
4574 struct btrfs_path *path,
4575 const struct btrfs_key *new_key)
4577 struct extent_buffer *leaf;
4581 leaf = path->nodes[0];
4582 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
4583 ret = setup_leaf_for_split(trans, root, path,
4584 item_size + sizeof(struct btrfs_item));
4589 setup_items_for_insert(root, path, new_key, &item_size, 1);
4590 leaf = path->nodes[0];
4591 memcpy_extent_buffer(leaf,
4592 btrfs_item_ptr_offset(leaf, path->slots[0]),
4593 btrfs_item_ptr_offset(leaf, path->slots[0] - 1),
4599 * make the item pointed to by the path smaller. new_size indicates
4600 * how small to make it, and from_end tells us if we just chop bytes
4601 * off the end of the item or if we shift the item to chop bytes off
4604 void btrfs_truncate_item(struct btrfs_path *path, u32 new_size, int from_end)
4607 struct extent_buffer *leaf;
4608 struct btrfs_item *item;
4610 unsigned int data_end;
4611 unsigned int old_data_start;
4612 unsigned int old_size;
4613 unsigned int size_diff;
4615 struct btrfs_map_token token;
4617 leaf = path->nodes[0];
4618 slot = path->slots[0];
4620 old_size = btrfs_item_size_nr(leaf, slot);
4621 if (old_size == new_size)
4624 nritems = btrfs_header_nritems(leaf);
4625 data_end = leaf_data_end(leaf);
4627 old_data_start = btrfs_item_offset_nr(leaf, slot);
4629 size_diff = old_size - new_size;
4632 BUG_ON(slot >= nritems);
4635 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4637 /* first correct the data pointers */
4638 btrfs_init_map_token(&token, leaf);
4639 for (i = slot; i < nritems; i++) {
4641 item = btrfs_item_nr(i);
4643 ioff = btrfs_token_item_offset(&token, item);
4644 btrfs_set_token_item_offset(&token, item, ioff + size_diff);
4647 /* shift the data */
4649 memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
4650 data_end + size_diff, BTRFS_LEAF_DATA_OFFSET +
4651 data_end, old_data_start + new_size - data_end);
4653 struct btrfs_disk_key disk_key;
4656 btrfs_item_key(leaf, &disk_key, slot);
4658 if (btrfs_disk_key_type(&disk_key) == BTRFS_EXTENT_DATA_KEY) {
4660 struct btrfs_file_extent_item *fi;
4662 fi = btrfs_item_ptr(leaf, slot,
4663 struct btrfs_file_extent_item);
4664 fi = (struct btrfs_file_extent_item *)(
4665 (unsigned long)fi - size_diff);
4667 if (btrfs_file_extent_type(leaf, fi) ==
4668 BTRFS_FILE_EXTENT_INLINE) {
4669 ptr = btrfs_item_ptr_offset(leaf, slot);
4670 memmove_extent_buffer(leaf, ptr,
4672 BTRFS_FILE_EXTENT_INLINE_DATA_START);
4676 memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
4677 data_end + size_diff, BTRFS_LEAF_DATA_OFFSET +
4678 data_end, old_data_start - data_end);
4680 offset = btrfs_disk_key_offset(&disk_key);
4681 btrfs_set_disk_key_offset(&disk_key, offset + size_diff);
4682 btrfs_set_item_key(leaf, &disk_key, slot);
4684 fixup_low_keys(path, &disk_key, 1);
4687 item = btrfs_item_nr(slot);
4688 btrfs_set_item_size(leaf, item, new_size);
4689 btrfs_mark_buffer_dirty(leaf);
4691 if (btrfs_leaf_free_space(leaf) < 0) {
4692 btrfs_print_leaf(leaf);
4698 * make the item pointed to by the path bigger, data_size is the added size.
4700 void btrfs_extend_item(struct btrfs_path *path, u32 data_size)
4703 struct extent_buffer *leaf;
4704 struct btrfs_item *item;
4706 unsigned int data_end;
4707 unsigned int old_data;
4708 unsigned int old_size;
4710 struct btrfs_map_token token;
4712 leaf = path->nodes[0];
4714 nritems = btrfs_header_nritems(leaf);
4715 data_end = leaf_data_end(leaf);
4717 if (btrfs_leaf_free_space(leaf) < data_size) {
4718 btrfs_print_leaf(leaf);
4721 slot = path->slots[0];
4722 old_data = btrfs_item_end_nr(leaf, slot);
4725 if (slot >= nritems) {
4726 btrfs_print_leaf(leaf);
4727 btrfs_crit(leaf->fs_info, "slot %d too large, nritems %d",
4733 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4735 /* first correct the data pointers */
4736 btrfs_init_map_token(&token, leaf);
4737 for (i = slot; i < nritems; i++) {
4739 item = btrfs_item_nr(i);
4741 ioff = btrfs_token_item_offset(&token, item);
4742 btrfs_set_token_item_offset(&token, item, ioff - data_size);
4745 /* shift the data */
4746 memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
4747 data_end - data_size, BTRFS_LEAF_DATA_OFFSET +
4748 data_end, old_data - data_end);
4750 data_end = old_data;
4751 old_size = btrfs_item_size_nr(leaf, slot);
4752 item = btrfs_item_nr(slot);
4753 btrfs_set_item_size(leaf, item, old_size + data_size);
4754 btrfs_mark_buffer_dirty(leaf);
4756 if (btrfs_leaf_free_space(leaf) < 0) {
4757 btrfs_print_leaf(leaf);
4763 * setup_items_for_insert - Helper called before inserting one or more items
4764 * to a leaf. Main purpose is to save stack depth by doing the bulk of the work
4765 * in a function that doesn't call btrfs_search_slot
4767 * @root: root we are inserting items to
4768 * @path: points to the leaf/slot where we are going to insert new items
4769 * @cpu_key: array of keys for items to be inserted
4770 * @data_size: size of the body of each item we are going to insert
4771 * @nr: size of @cpu_key/@data_size arrays
4773 void setup_items_for_insert(struct btrfs_root *root, struct btrfs_path *path,
4774 const struct btrfs_key *cpu_key, u32 *data_size,
4777 struct btrfs_fs_info *fs_info = root->fs_info;
4778 struct btrfs_item *item;
4781 unsigned int data_end;
4782 struct btrfs_disk_key disk_key;
4783 struct extent_buffer *leaf;
4785 struct btrfs_map_token token;
4789 for (i = 0; i < nr; i++)
4790 total_data += data_size[i];
4791 total_size = total_data + (nr * sizeof(struct btrfs_item));
4793 if (path->slots[0] == 0) {
4794 btrfs_cpu_key_to_disk(&disk_key, cpu_key);
4795 fixup_low_keys(path, &disk_key, 1);
4797 btrfs_unlock_up_safe(path, 1);
4799 leaf = path->nodes[0];
4800 slot = path->slots[0];
4802 nritems = btrfs_header_nritems(leaf);
4803 data_end = leaf_data_end(leaf);
4805 if (btrfs_leaf_free_space(leaf) < total_size) {
4806 btrfs_print_leaf(leaf);
4807 btrfs_crit(fs_info, "not enough freespace need %u have %d",
4808 total_size, btrfs_leaf_free_space(leaf));
4812 btrfs_init_map_token(&token, leaf);
4813 if (slot != nritems) {
4814 unsigned int old_data = btrfs_item_end_nr(leaf, slot);
4816 if (old_data < data_end) {
4817 btrfs_print_leaf(leaf);
4819 "item at slot %d with data offset %u beyond data end of leaf %u",
4820 slot, old_data, data_end);
4824 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4826 /* first correct the data pointers */
4827 for (i = slot; i < nritems; i++) {
4830 item = btrfs_item_nr(i);
4831 ioff = btrfs_token_item_offset(&token, item);
4832 btrfs_set_token_item_offset(&token, item,
4835 /* shift the items */
4836 memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + nr),
4837 btrfs_item_nr_offset(slot),
4838 (nritems - slot) * sizeof(struct btrfs_item));
4840 /* shift the data */
4841 memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
4842 data_end - total_data, BTRFS_LEAF_DATA_OFFSET +
4843 data_end, old_data - data_end);
4844 data_end = old_data;
4847 /* setup the item for the new data */
4848 for (i = 0; i < nr; i++) {
4849 btrfs_cpu_key_to_disk(&disk_key, cpu_key + i);
4850 btrfs_set_item_key(leaf, &disk_key, slot + i);
4851 item = btrfs_item_nr(slot + i);
4852 data_end -= data_size[i];
4853 btrfs_set_token_item_offset(&token, item, data_end);
4854 btrfs_set_token_item_size(&token, item, data_size[i]);
4857 btrfs_set_header_nritems(leaf, nritems + nr);
4858 btrfs_mark_buffer_dirty(leaf);
4860 if (btrfs_leaf_free_space(leaf) < 0) {
4861 btrfs_print_leaf(leaf);
4867 * Given a key and some data, insert items into the tree.
4868 * This does all the path init required, making room in the tree if needed.
4870 int btrfs_insert_empty_items(struct btrfs_trans_handle *trans,
4871 struct btrfs_root *root,
4872 struct btrfs_path *path,
4873 const struct btrfs_key *cpu_key, u32 *data_size,
4882 for (i = 0; i < nr; i++)
4883 total_data += data_size[i];
4885 total_size = total_data + (nr * sizeof(struct btrfs_item));
4886 ret = btrfs_search_slot(trans, root, cpu_key, path, total_size, 1);
4892 slot = path->slots[0];
4895 setup_items_for_insert(root, path, cpu_key, data_size, nr);
4900 * Given a key and some data, insert an item into the tree.
4901 * This does all the path init required, making room in the tree if needed.
4903 int btrfs_insert_item(struct btrfs_trans_handle *trans, struct btrfs_root *root,
4904 const struct btrfs_key *cpu_key, void *data,
4908 struct btrfs_path *path;
4909 struct extent_buffer *leaf;
4912 path = btrfs_alloc_path();
4915 ret = btrfs_insert_empty_item(trans, root, path, cpu_key, data_size);
4917 leaf = path->nodes[0];
4918 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
4919 write_extent_buffer(leaf, data, ptr, data_size);
4920 btrfs_mark_buffer_dirty(leaf);
4922 btrfs_free_path(path);
4927 * delete the pointer from a given node.
4929 * the tree should have been previously balanced so the deletion does not
4932 static void del_ptr(struct btrfs_root *root, struct btrfs_path *path,
4933 int level, int slot)
4935 struct extent_buffer *parent = path->nodes[level];
4939 nritems = btrfs_header_nritems(parent);
4940 if (slot != nritems - 1) {
4942 ret = tree_mod_log_insert_move(parent, slot, slot + 1,
4943 nritems - slot - 1);
4946 memmove_extent_buffer(parent,
4947 btrfs_node_key_ptr_offset(slot),
4948 btrfs_node_key_ptr_offset(slot + 1),
4949 sizeof(struct btrfs_key_ptr) *
4950 (nritems - slot - 1));
4952 ret = tree_mod_log_insert_key(parent, slot, MOD_LOG_KEY_REMOVE,
4958 btrfs_set_header_nritems(parent, nritems);
4959 if (nritems == 0 && parent == root->node) {
4960 BUG_ON(btrfs_header_level(root->node) != 1);
4961 /* just turn the root into a leaf and break */
4962 btrfs_set_header_level(root->node, 0);
4963 } else if (slot == 0) {
4964 struct btrfs_disk_key disk_key;
4966 btrfs_node_key(parent, &disk_key, 0);
4967 fixup_low_keys(path, &disk_key, level + 1);
4969 btrfs_mark_buffer_dirty(parent);
4973 * a helper function to delete the leaf pointed to by path->slots[1] and
4976 * This deletes the pointer in path->nodes[1] and frees the leaf
4977 * block extent. zero is returned if it all worked out, < 0 otherwise.
4979 * The path must have already been setup for deleting the leaf, including
4980 * all the proper balancing. path->nodes[1] must be locked.
4982 static noinline void btrfs_del_leaf(struct btrfs_trans_handle *trans,
4983 struct btrfs_root *root,
4984 struct btrfs_path *path,
4985 struct extent_buffer *leaf)
4987 WARN_ON(btrfs_header_generation(leaf) != trans->transid);
4988 del_ptr(root, path, 1, path->slots[1]);
4991 * btrfs_free_extent is expensive, we want to make sure we
4992 * aren't holding any locks when we call it
4994 btrfs_unlock_up_safe(path, 0);
4996 root_sub_used(root, leaf->len);
4998 atomic_inc(&leaf->refs);
4999 btrfs_free_tree_block(trans, root, leaf, 0, 1);
5000 free_extent_buffer_stale(leaf);
5003 * delete the item at the leaf level in path. If that empties
5004 * the leaf, remove it from the tree
5006 int btrfs_del_items(struct btrfs_trans_handle *trans, struct btrfs_root *root,
5007 struct btrfs_path *path, int slot, int nr)
5009 struct btrfs_fs_info *fs_info = root->fs_info;
5010 struct extent_buffer *leaf;
5011 struct btrfs_item *item;
5019 leaf = path->nodes[0];
5020 last_off = btrfs_item_offset_nr(leaf, slot + nr - 1);
5022 for (i = 0; i < nr; i++)
5023 dsize += btrfs_item_size_nr(leaf, slot + i);
5025 nritems = btrfs_header_nritems(leaf);
5027 if (slot + nr != nritems) {
5028 int data_end = leaf_data_end(leaf);
5029 struct btrfs_map_token token;
5031 memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
5033 BTRFS_LEAF_DATA_OFFSET + data_end,
5034 last_off - data_end);
5036 btrfs_init_map_token(&token, leaf);
5037 for (i = slot + nr; i < nritems; i++) {
5040 item = btrfs_item_nr(i);
5041 ioff = btrfs_token_item_offset(&token, item);
5042 btrfs_set_token_item_offset(&token, item, ioff + dsize);
5045 memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot),
5046 btrfs_item_nr_offset(slot + nr),
5047 sizeof(struct btrfs_item) *
5048 (nritems - slot - nr));
5050 btrfs_set_header_nritems(leaf, nritems - nr);
5053 /* delete the leaf if we've emptied it */
5055 if (leaf == root->node) {
5056 btrfs_set_header_level(leaf, 0);
5058 btrfs_set_path_blocking(path);
5059 btrfs_clean_tree_block(leaf);
5060 btrfs_del_leaf(trans, root, path, leaf);
5063 int used = leaf_space_used(leaf, 0, nritems);
5065 struct btrfs_disk_key disk_key;
5067 btrfs_item_key(leaf, &disk_key, 0);
5068 fixup_low_keys(path, &disk_key, 1);
5071 /* delete the leaf if it is mostly empty */
5072 if (used < BTRFS_LEAF_DATA_SIZE(fs_info) / 3) {
5073 /* push_leaf_left fixes the path.
5074 * make sure the path still points to our leaf
5075 * for possible call to del_ptr below
5077 slot = path->slots[1];
5078 atomic_inc(&leaf->refs);
5080 btrfs_set_path_blocking(path);
5081 wret = push_leaf_left(trans, root, path, 1, 1,
5083 if (wret < 0 && wret != -ENOSPC)
5086 if (path->nodes[0] == leaf &&
5087 btrfs_header_nritems(leaf)) {
5088 wret = push_leaf_right(trans, root, path, 1,
5090 if (wret < 0 && wret != -ENOSPC)
5094 if (btrfs_header_nritems(leaf) == 0) {
5095 path->slots[1] = slot;
5096 btrfs_del_leaf(trans, root, path, leaf);
5097 free_extent_buffer(leaf);
5100 /* if we're still in the path, make sure
5101 * we're dirty. Otherwise, one of the
5102 * push_leaf functions must have already
5103 * dirtied this buffer
5105 if (path->nodes[0] == leaf)
5106 btrfs_mark_buffer_dirty(leaf);
5107 free_extent_buffer(leaf);
5110 btrfs_mark_buffer_dirty(leaf);
5117 * search the tree again to find a leaf with lesser keys
5118 * returns 0 if it found something or 1 if there are no lesser leaves.
5119 * returns < 0 on io errors.
5121 * This may release the path, and so you may lose any locks held at the
5124 int btrfs_prev_leaf(struct btrfs_root *root, struct btrfs_path *path)
5126 struct btrfs_key key;
5127 struct btrfs_disk_key found_key;
5130 btrfs_item_key_to_cpu(path->nodes[0], &key, 0);
5132 if (key.offset > 0) {
5134 } else if (key.type > 0) {
5136 key.offset = (u64)-1;
5137 } else if (key.objectid > 0) {
5140 key.offset = (u64)-1;
5145 btrfs_release_path(path);
5146 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5149 btrfs_item_key(path->nodes[0], &found_key, 0);
5150 ret = comp_keys(&found_key, &key);
5152 * We might have had an item with the previous key in the tree right
5153 * before we released our path. And after we released our path, that
5154 * item might have been pushed to the first slot (0) of the leaf we
5155 * were holding due to a tree balance. Alternatively, an item with the
5156 * previous key can exist as the only element of a leaf (big fat item).
5157 * Therefore account for these 2 cases, so that our callers (like
5158 * btrfs_previous_item) don't miss an existing item with a key matching
5159 * the previous key we computed above.
5167 * A helper function to walk down the tree starting at min_key, and looking
5168 * for nodes or leaves that are have a minimum transaction id.
5169 * This is used by the btree defrag code, and tree logging
5171 * This does not cow, but it does stuff the starting key it finds back
5172 * into min_key, so you can call btrfs_search_slot with cow=1 on the
5173 * key and get a writable path.
5175 * This honors path->lowest_level to prevent descent past a given level
5178 * min_trans indicates the oldest transaction that you are interested
5179 * in walking through. Any nodes or leaves older than min_trans are
5180 * skipped over (without reading them).
5182 * returns zero if something useful was found, < 0 on error and 1 if there
5183 * was nothing in the tree that matched the search criteria.
5185 int btrfs_search_forward(struct btrfs_root *root, struct btrfs_key *min_key,
5186 struct btrfs_path *path,
5189 struct extent_buffer *cur;
5190 struct btrfs_key found_key;
5196 int keep_locks = path->keep_locks;
5198 path->keep_locks = 1;
5200 cur = btrfs_read_lock_root_node(root);
5201 level = btrfs_header_level(cur);
5202 WARN_ON(path->nodes[level]);
5203 path->nodes[level] = cur;
5204 path->locks[level] = BTRFS_READ_LOCK;
5206 if (btrfs_header_generation(cur) < min_trans) {
5211 nritems = btrfs_header_nritems(cur);
5212 level = btrfs_header_level(cur);
5213 sret = btrfs_bin_search(cur, min_key, &slot);
5219 /* at the lowest level, we're done, setup the path and exit */
5220 if (level == path->lowest_level) {
5221 if (slot >= nritems)
5224 path->slots[level] = slot;
5225 btrfs_item_key_to_cpu(cur, &found_key, slot);
5228 if (sret && slot > 0)
5231 * check this node pointer against the min_trans parameters.
5232 * If it is too old, skip to the next one.
5234 while (slot < nritems) {
5237 gen = btrfs_node_ptr_generation(cur, slot);
5238 if (gen < min_trans) {
5246 * we didn't find a candidate key in this node, walk forward
5247 * and find another one
5249 if (slot >= nritems) {
5250 path->slots[level] = slot;
5251 btrfs_set_path_blocking(path);
5252 sret = btrfs_find_next_key(root, path, min_key, level,
5255 btrfs_release_path(path);
5261 /* save our key for returning back */
5262 btrfs_node_key_to_cpu(cur, &found_key, slot);
5263 path->slots[level] = slot;
5264 if (level == path->lowest_level) {
5268 btrfs_set_path_blocking(path);
5269 cur = btrfs_read_node_slot(cur, slot);
5275 btrfs_tree_read_lock(cur);
5277 path->locks[level - 1] = BTRFS_READ_LOCK;
5278 path->nodes[level - 1] = cur;
5279 unlock_up(path, level, 1, 0, NULL);
5282 path->keep_locks = keep_locks;
5284 btrfs_unlock_up_safe(path, path->lowest_level + 1);
5285 btrfs_set_path_blocking(path);
5286 memcpy(min_key, &found_key, sizeof(found_key));
5292 * this is similar to btrfs_next_leaf, but does not try to preserve
5293 * and fixup the path. It looks for and returns the next key in the
5294 * tree based on the current path and the min_trans parameters.
5296 * 0 is returned if another key is found, < 0 if there are any errors
5297 * and 1 is returned if there are no higher keys in the tree
5299 * path->keep_locks should be set to 1 on the search made before
5300 * calling this function.
5302 int btrfs_find_next_key(struct btrfs_root *root, struct btrfs_path *path,
5303 struct btrfs_key *key, int level, u64 min_trans)
5306 struct extent_buffer *c;
5308 WARN_ON(!path->keep_locks && !path->skip_locking);
5309 while (level < BTRFS_MAX_LEVEL) {
5310 if (!path->nodes[level])
5313 slot = path->slots[level] + 1;
5314 c = path->nodes[level];
5316 if (slot >= btrfs_header_nritems(c)) {
5319 struct btrfs_key cur_key;
5320 if (level + 1 >= BTRFS_MAX_LEVEL ||
5321 !path->nodes[level + 1])
5324 if (path->locks[level + 1] || path->skip_locking) {
5329 slot = btrfs_header_nritems(c) - 1;
5331 btrfs_item_key_to_cpu(c, &cur_key, slot);
5333 btrfs_node_key_to_cpu(c, &cur_key, slot);
5335 orig_lowest = path->lowest_level;
5336 btrfs_release_path(path);
5337 path->lowest_level = level;
5338 ret = btrfs_search_slot(NULL, root, &cur_key, path,
5340 path->lowest_level = orig_lowest;
5344 c = path->nodes[level];
5345 slot = path->slots[level];
5352 btrfs_item_key_to_cpu(c, key, slot);
5354 u64 gen = btrfs_node_ptr_generation(c, slot);
5356 if (gen < min_trans) {
5360 btrfs_node_key_to_cpu(c, key, slot);
5368 * search the tree again to find a leaf with greater keys
5369 * returns 0 if it found something or 1 if there are no greater leaves.
5370 * returns < 0 on io errors.
5372 int btrfs_next_leaf(struct btrfs_root *root, struct btrfs_path *path)
5374 return btrfs_next_old_leaf(root, path, 0);
5377 int btrfs_next_old_leaf(struct btrfs_root *root, struct btrfs_path *path,
5382 struct extent_buffer *c;
5383 struct extent_buffer *next;
5384 struct btrfs_key key;
5387 int old_spinning = path->leave_spinning;
5388 int next_rw_lock = 0;
5390 nritems = btrfs_header_nritems(path->nodes[0]);
5394 btrfs_item_key_to_cpu(path->nodes[0], &key, nritems - 1);
5399 btrfs_release_path(path);
5401 path->keep_locks = 1;
5402 path->leave_spinning = 1;
5405 ret = btrfs_search_old_slot(root, &key, path, time_seq);
5407 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5408 path->keep_locks = 0;
5413 nritems = btrfs_header_nritems(path->nodes[0]);
5415 * by releasing the path above we dropped all our locks. A balance
5416 * could have added more items next to the key that used to be
5417 * at the very end of the block. So, check again here and
5418 * advance the path if there are now more items available.
5420 if (nritems > 0 && path->slots[0] < nritems - 1) {
5427 * So the above check misses one case:
5428 * - after releasing the path above, someone has removed the item that
5429 * used to be at the very end of the block, and balance between leafs
5430 * gets another one with bigger key.offset to replace it.
5432 * This one should be returned as well, or we can get leaf corruption
5433 * later(esp. in __btrfs_drop_extents()).
5435 * And a bit more explanation about this check,
5436 * with ret > 0, the key isn't found, the path points to the slot
5437 * where it should be inserted, so the path->slots[0] item must be the
5440 if (nritems > 0 && ret > 0 && path->slots[0] == nritems - 1) {
5445 while (level < BTRFS_MAX_LEVEL) {
5446 if (!path->nodes[level]) {
5451 slot = path->slots[level] + 1;
5452 c = path->nodes[level];
5453 if (slot >= btrfs_header_nritems(c)) {
5455 if (level == BTRFS_MAX_LEVEL) {
5463 btrfs_tree_unlock_rw(next, next_rw_lock);
5464 free_extent_buffer(next);
5468 next_rw_lock = path->locks[level];
5469 ret = read_block_for_search(root, path, &next, level,
5475 btrfs_release_path(path);
5479 if (!path->skip_locking) {
5480 ret = btrfs_try_tree_read_lock(next);
5481 if (!ret && time_seq) {
5483 * If we don't get the lock, we may be racing
5484 * with push_leaf_left, holding that lock while
5485 * itself waiting for the leaf we've currently
5486 * locked. To solve this situation, we give up
5487 * on our lock and cycle.
5489 free_extent_buffer(next);
5490 btrfs_release_path(path);
5495 btrfs_set_path_blocking(path);
5496 __btrfs_tree_read_lock(next,
5497 BTRFS_NESTING_RIGHT,
5500 next_rw_lock = BTRFS_READ_LOCK;
5504 path->slots[level] = slot;
5507 c = path->nodes[level];
5508 if (path->locks[level])
5509 btrfs_tree_unlock_rw(c, path->locks[level]);
5511 free_extent_buffer(c);
5512 path->nodes[level] = next;
5513 path->slots[level] = 0;
5514 if (!path->skip_locking)
5515 path->locks[level] = next_rw_lock;
5519 ret = read_block_for_search(root, path, &next, level,
5525 btrfs_release_path(path);
5529 if (!path->skip_locking) {
5530 ret = btrfs_try_tree_read_lock(next);
5532 btrfs_set_path_blocking(path);
5533 __btrfs_tree_read_lock(next,
5534 BTRFS_NESTING_RIGHT,
5537 next_rw_lock = BTRFS_READ_LOCK;
5542 unlock_up(path, 0, 1, 0, NULL);
5543 path->leave_spinning = old_spinning;
5545 btrfs_set_path_blocking(path);
5551 * this uses btrfs_prev_leaf to walk backwards in the tree, and keeps
5552 * searching until it gets past min_objectid or finds an item of 'type'
5554 * returns 0 if something is found, 1 if nothing was found and < 0 on error
5556 int btrfs_previous_item(struct btrfs_root *root,
5557 struct btrfs_path *path, u64 min_objectid,
5560 struct btrfs_key found_key;
5561 struct extent_buffer *leaf;
5566 if (path->slots[0] == 0) {
5567 btrfs_set_path_blocking(path);
5568 ret = btrfs_prev_leaf(root, path);
5574 leaf = path->nodes[0];
5575 nritems = btrfs_header_nritems(leaf);
5578 if (path->slots[0] == nritems)
5581 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5582 if (found_key.objectid < min_objectid)
5584 if (found_key.type == type)
5586 if (found_key.objectid == min_objectid &&
5587 found_key.type < type)
5594 * search in extent tree to find a previous Metadata/Data extent item with
5597 * returns 0 if something is found, 1 if nothing was found and < 0 on error
5599 int btrfs_previous_extent_item(struct btrfs_root *root,
5600 struct btrfs_path *path, u64 min_objectid)
5602 struct btrfs_key found_key;
5603 struct extent_buffer *leaf;
5608 if (path->slots[0] == 0) {
5609 btrfs_set_path_blocking(path);
5610 ret = btrfs_prev_leaf(root, path);
5616 leaf = path->nodes[0];
5617 nritems = btrfs_header_nritems(leaf);
5620 if (path->slots[0] == nritems)
5623 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5624 if (found_key.objectid < min_objectid)
5626 if (found_key.type == BTRFS_EXTENT_ITEM_KEY ||
5627 found_key.type == BTRFS_METADATA_ITEM_KEY)
5629 if (found_key.objectid == min_objectid &&
5630 found_key.type < BTRFS_EXTENT_ITEM_KEY)