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);
225 btrfs_tree_unlock(cow);
226 free_extent_buffer(cow);
227 btrfs_abort_transaction(trans, ret);
231 btrfs_mark_buffer_dirty(cow);
240 MOD_LOG_KEY_REMOVE_WHILE_FREEING,
241 MOD_LOG_KEY_REMOVE_WHILE_MOVING,
243 MOD_LOG_ROOT_REPLACE,
246 struct tree_mod_root {
251 struct tree_mod_elem {
257 /* this is used for MOD_LOG_KEY_* and MOD_LOG_MOVE_KEYS operations */
260 /* this is used for MOD_LOG_KEY* and MOD_LOG_ROOT_REPLACE */
263 /* those are used for op == MOD_LOG_KEY_{REPLACE,REMOVE} */
264 struct btrfs_disk_key key;
267 /* this is used for op == MOD_LOG_MOVE_KEYS */
273 /* this is used for op == MOD_LOG_ROOT_REPLACE */
274 struct tree_mod_root old_root;
278 * Pull a new tree mod seq number for our operation.
280 static inline u64 btrfs_inc_tree_mod_seq(struct btrfs_fs_info *fs_info)
282 return atomic64_inc_return(&fs_info->tree_mod_seq);
286 * This adds a new blocker to the tree mod log's blocker list if the @elem
287 * passed does not already have a sequence number set. So when a caller expects
288 * to record tree modifications, it should ensure to set elem->seq to zero
289 * before calling btrfs_get_tree_mod_seq.
290 * Returns a fresh, unused tree log modification sequence number, even if no new
293 u64 btrfs_get_tree_mod_seq(struct btrfs_fs_info *fs_info,
294 struct seq_list *elem)
296 write_lock(&fs_info->tree_mod_log_lock);
298 elem->seq = btrfs_inc_tree_mod_seq(fs_info);
299 list_add_tail(&elem->list, &fs_info->tree_mod_seq_list);
301 write_unlock(&fs_info->tree_mod_log_lock);
306 void btrfs_put_tree_mod_seq(struct btrfs_fs_info *fs_info,
307 struct seq_list *elem)
309 struct rb_root *tm_root;
310 struct rb_node *node;
311 struct rb_node *next;
312 struct tree_mod_elem *tm;
313 u64 min_seq = (u64)-1;
314 u64 seq_putting = elem->seq;
319 write_lock(&fs_info->tree_mod_log_lock);
320 list_del(&elem->list);
323 if (!list_empty(&fs_info->tree_mod_seq_list)) {
324 struct seq_list *first;
326 first = list_first_entry(&fs_info->tree_mod_seq_list,
327 struct seq_list, list);
328 if (seq_putting > first->seq) {
330 * Blocker with lower sequence number exists, we
331 * cannot remove anything from the log.
333 write_unlock(&fs_info->tree_mod_log_lock);
336 min_seq = first->seq;
340 * anything that's lower than the lowest existing (read: blocked)
341 * sequence number can be removed from the tree.
343 tm_root = &fs_info->tree_mod_log;
344 for (node = rb_first(tm_root); node; node = next) {
345 next = rb_next(node);
346 tm = rb_entry(node, struct tree_mod_elem, node);
347 if (tm->seq >= min_seq)
349 rb_erase(node, tm_root);
352 write_unlock(&fs_info->tree_mod_log_lock);
356 * key order of the log:
357 * node/leaf start address -> sequence
359 * The 'start address' is the logical address of the *new* root node
360 * for root replace operations, or the logical address of the affected
361 * block for all other operations.
364 __tree_mod_log_insert(struct btrfs_fs_info *fs_info, struct tree_mod_elem *tm)
366 struct rb_root *tm_root;
367 struct rb_node **new;
368 struct rb_node *parent = NULL;
369 struct tree_mod_elem *cur;
371 lockdep_assert_held_write(&fs_info->tree_mod_log_lock);
373 tm->seq = btrfs_inc_tree_mod_seq(fs_info);
375 tm_root = &fs_info->tree_mod_log;
376 new = &tm_root->rb_node;
378 cur = rb_entry(*new, struct tree_mod_elem, node);
380 if (cur->logical < tm->logical)
381 new = &((*new)->rb_left);
382 else if (cur->logical > tm->logical)
383 new = &((*new)->rb_right);
384 else if (cur->seq < tm->seq)
385 new = &((*new)->rb_left);
386 else if (cur->seq > tm->seq)
387 new = &((*new)->rb_right);
392 rb_link_node(&tm->node, parent, new);
393 rb_insert_color(&tm->node, tm_root);
398 * Determines if logging can be omitted. Returns 1 if it can. Otherwise, it
399 * returns zero with the tree_mod_log_lock acquired. The caller must hold
400 * this until all tree mod log insertions are recorded in the rb tree and then
401 * write unlock fs_info::tree_mod_log_lock.
403 static inline int tree_mod_dont_log(struct btrfs_fs_info *fs_info,
404 struct extent_buffer *eb) {
406 if (list_empty(&(fs_info)->tree_mod_seq_list))
408 if (eb && btrfs_header_level(eb) == 0)
411 write_lock(&fs_info->tree_mod_log_lock);
412 if (list_empty(&(fs_info)->tree_mod_seq_list)) {
413 write_unlock(&fs_info->tree_mod_log_lock);
420 /* Similar to tree_mod_dont_log, but doesn't acquire any locks. */
421 static inline int tree_mod_need_log(const struct btrfs_fs_info *fs_info,
422 struct extent_buffer *eb)
425 if (list_empty(&(fs_info)->tree_mod_seq_list))
427 if (eb && btrfs_header_level(eb) == 0)
433 static struct tree_mod_elem *
434 alloc_tree_mod_elem(struct extent_buffer *eb, int slot,
435 enum mod_log_op op, gfp_t flags)
437 struct tree_mod_elem *tm;
439 tm = kzalloc(sizeof(*tm), flags);
443 tm->logical = eb->start;
444 if (op != MOD_LOG_KEY_ADD) {
445 btrfs_node_key(eb, &tm->key, slot);
446 tm->blockptr = btrfs_node_blockptr(eb, slot);
450 tm->generation = btrfs_node_ptr_generation(eb, slot);
451 RB_CLEAR_NODE(&tm->node);
456 static noinline int tree_mod_log_insert_key(struct extent_buffer *eb, int slot,
457 enum mod_log_op op, gfp_t flags)
459 struct tree_mod_elem *tm;
462 if (!tree_mod_need_log(eb->fs_info, eb))
465 tm = alloc_tree_mod_elem(eb, slot, op, flags);
469 if (tree_mod_dont_log(eb->fs_info, eb)) {
474 ret = __tree_mod_log_insert(eb->fs_info, tm);
475 write_unlock(&eb->fs_info->tree_mod_log_lock);
482 static noinline int tree_mod_log_insert_move(struct extent_buffer *eb,
483 int dst_slot, int src_slot, int nr_items)
485 struct tree_mod_elem *tm = NULL;
486 struct tree_mod_elem **tm_list = NULL;
491 if (!tree_mod_need_log(eb->fs_info, eb))
494 tm_list = kcalloc(nr_items, sizeof(struct tree_mod_elem *), GFP_NOFS);
498 tm = kzalloc(sizeof(*tm), GFP_NOFS);
504 tm->logical = eb->start;
506 tm->move.dst_slot = dst_slot;
507 tm->move.nr_items = nr_items;
508 tm->op = MOD_LOG_MOVE_KEYS;
510 for (i = 0; i + dst_slot < src_slot && i < nr_items; i++) {
511 tm_list[i] = alloc_tree_mod_elem(eb, i + dst_slot,
512 MOD_LOG_KEY_REMOVE_WHILE_MOVING, GFP_NOFS);
519 if (tree_mod_dont_log(eb->fs_info, eb))
524 * When we override something during the move, we log these removals.
525 * This can only happen when we move towards the beginning of the
526 * buffer, i.e. dst_slot < src_slot.
528 for (i = 0; i + dst_slot < src_slot && i < nr_items; i++) {
529 ret = __tree_mod_log_insert(eb->fs_info, tm_list[i]);
534 ret = __tree_mod_log_insert(eb->fs_info, tm);
537 write_unlock(&eb->fs_info->tree_mod_log_lock);
542 for (i = 0; i < nr_items; i++) {
543 if (tm_list[i] && !RB_EMPTY_NODE(&tm_list[i]->node))
544 rb_erase(&tm_list[i]->node, &eb->fs_info->tree_mod_log);
548 write_unlock(&eb->fs_info->tree_mod_log_lock);
556 __tree_mod_log_free_eb(struct btrfs_fs_info *fs_info,
557 struct tree_mod_elem **tm_list,
563 for (i = nritems - 1; i >= 0; i--) {
564 ret = __tree_mod_log_insert(fs_info, tm_list[i]);
566 for (j = nritems - 1; j > i; j--)
567 rb_erase(&tm_list[j]->node,
568 &fs_info->tree_mod_log);
576 static noinline int tree_mod_log_insert_root(struct extent_buffer *old_root,
577 struct extent_buffer *new_root, int log_removal)
579 struct btrfs_fs_info *fs_info = old_root->fs_info;
580 struct tree_mod_elem *tm = NULL;
581 struct tree_mod_elem **tm_list = NULL;
586 if (!tree_mod_need_log(fs_info, NULL))
589 if (log_removal && btrfs_header_level(old_root) > 0) {
590 nritems = btrfs_header_nritems(old_root);
591 tm_list = kcalloc(nritems, sizeof(struct tree_mod_elem *),
597 for (i = 0; i < nritems; i++) {
598 tm_list[i] = alloc_tree_mod_elem(old_root, i,
599 MOD_LOG_KEY_REMOVE_WHILE_FREEING, GFP_NOFS);
607 tm = kzalloc(sizeof(*tm), GFP_NOFS);
613 tm->logical = new_root->start;
614 tm->old_root.logical = old_root->start;
615 tm->old_root.level = btrfs_header_level(old_root);
616 tm->generation = btrfs_header_generation(old_root);
617 tm->op = MOD_LOG_ROOT_REPLACE;
619 if (tree_mod_dont_log(fs_info, NULL))
623 ret = __tree_mod_log_free_eb(fs_info, tm_list, nritems);
625 ret = __tree_mod_log_insert(fs_info, tm);
627 write_unlock(&fs_info->tree_mod_log_lock);
636 for (i = 0; i < nritems; i++)
645 static struct tree_mod_elem *
646 __tree_mod_log_search(struct btrfs_fs_info *fs_info, u64 start, u64 min_seq,
649 struct rb_root *tm_root;
650 struct rb_node *node;
651 struct tree_mod_elem *cur = NULL;
652 struct tree_mod_elem *found = NULL;
654 read_lock(&fs_info->tree_mod_log_lock);
655 tm_root = &fs_info->tree_mod_log;
656 node = tm_root->rb_node;
658 cur = rb_entry(node, struct tree_mod_elem, node);
659 if (cur->logical < start) {
660 node = node->rb_left;
661 } else if (cur->logical > start) {
662 node = node->rb_right;
663 } else if (cur->seq < min_seq) {
664 node = node->rb_left;
665 } else if (!smallest) {
666 /* we want the node with the highest seq */
668 BUG_ON(found->seq > cur->seq);
670 node = node->rb_left;
671 } else if (cur->seq > min_seq) {
672 /* we want the node with the smallest seq */
674 BUG_ON(found->seq < cur->seq);
676 node = node->rb_right;
682 read_unlock(&fs_info->tree_mod_log_lock);
688 * this returns the element from the log with the smallest time sequence
689 * value that's in the log (the oldest log item). any element with a time
690 * sequence lower than min_seq will be ignored.
692 static struct tree_mod_elem *
693 tree_mod_log_search_oldest(struct btrfs_fs_info *fs_info, u64 start,
696 return __tree_mod_log_search(fs_info, start, min_seq, 1);
700 * this returns the element from the log with the largest time sequence
701 * value that's in the log (the most recent log item). any element with
702 * a time sequence lower than min_seq will be ignored.
704 static struct tree_mod_elem *
705 tree_mod_log_search(struct btrfs_fs_info *fs_info, u64 start, u64 min_seq)
707 return __tree_mod_log_search(fs_info, start, min_seq, 0);
710 static noinline int tree_mod_log_eb_copy(struct extent_buffer *dst,
711 struct extent_buffer *src, unsigned long dst_offset,
712 unsigned long src_offset, int nr_items)
714 struct btrfs_fs_info *fs_info = dst->fs_info;
716 struct tree_mod_elem **tm_list = NULL;
717 struct tree_mod_elem **tm_list_add, **tm_list_rem;
721 if (!tree_mod_need_log(fs_info, NULL))
724 if (btrfs_header_level(dst) == 0 && btrfs_header_level(src) == 0)
727 tm_list = kcalloc(nr_items * 2, sizeof(struct tree_mod_elem *),
732 tm_list_add = tm_list;
733 tm_list_rem = tm_list + nr_items;
734 for (i = 0; i < nr_items; i++) {
735 tm_list_rem[i] = alloc_tree_mod_elem(src, i + src_offset,
736 MOD_LOG_KEY_REMOVE, GFP_NOFS);
737 if (!tm_list_rem[i]) {
742 tm_list_add[i] = alloc_tree_mod_elem(dst, i + dst_offset,
743 MOD_LOG_KEY_ADD, GFP_NOFS);
744 if (!tm_list_add[i]) {
750 if (tree_mod_dont_log(fs_info, NULL))
754 for (i = 0; i < nr_items; i++) {
755 ret = __tree_mod_log_insert(fs_info, tm_list_rem[i]);
758 ret = __tree_mod_log_insert(fs_info, tm_list_add[i]);
763 write_unlock(&fs_info->tree_mod_log_lock);
769 for (i = 0; i < nr_items * 2; i++) {
770 if (tm_list[i] && !RB_EMPTY_NODE(&tm_list[i]->node))
771 rb_erase(&tm_list[i]->node, &fs_info->tree_mod_log);
775 write_unlock(&fs_info->tree_mod_log_lock);
781 static noinline int tree_mod_log_free_eb(struct extent_buffer *eb)
783 struct tree_mod_elem **tm_list = NULL;
788 if (btrfs_header_level(eb) == 0)
791 if (!tree_mod_need_log(eb->fs_info, NULL))
794 nritems = btrfs_header_nritems(eb);
795 tm_list = kcalloc(nritems, sizeof(struct tree_mod_elem *), GFP_NOFS);
799 for (i = 0; i < nritems; i++) {
800 tm_list[i] = alloc_tree_mod_elem(eb, i,
801 MOD_LOG_KEY_REMOVE_WHILE_FREEING, GFP_NOFS);
808 if (tree_mod_dont_log(eb->fs_info, eb))
811 ret = __tree_mod_log_free_eb(eb->fs_info, tm_list, nritems);
812 write_unlock(&eb->fs_info->tree_mod_log_lock);
820 for (i = 0; i < nritems; i++)
828 * check if the tree block can be shared by multiple trees
830 int btrfs_block_can_be_shared(struct btrfs_root *root,
831 struct extent_buffer *buf)
834 * Tree blocks not in shareable trees and tree roots are never shared.
835 * If a block was allocated after the last snapshot and the block was
836 * not allocated by tree relocation, we know the block is not shared.
838 if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
839 buf != root->node && buf != root->commit_root &&
840 (btrfs_header_generation(buf) <=
841 btrfs_root_last_snapshot(&root->root_item) ||
842 btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)))
848 static noinline int update_ref_for_cow(struct btrfs_trans_handle *trans,
849 struct btrfs_root *root,
850 struct extent_buffer *buf,
851 struct extent_buffer *cow,
854 struct btrfs_fs_info *fs_info = root->fs_info;
862 * Backrefs update rules:
864 * Always use full backrefs for extent pointers in tree block
865 * allocated by tree relocation.
867 * If a shared tree block is no longer referenced by its owner
868 * tree (btrfs_header_owner(buf) == root->root_key.objectid),
869 * use full backrefs for extent pointers in tree block.
871 * If a tree block is been relocating
872 * (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID),
873 * use full backrefs for extent pointers in tree block.
874 * The reason for this is some operations (such as drop tree)
875 * are only allowed for blocks use full backrefs.
878 if (btrfs_block_can_be_shared(root, buf)) {
879 ret = btrfs_lookup_extent_info(trans, fs_info, buf->start,
880 btrfs_header_level(buf), 1,
886 btrfs_handle_fs_error(fs_info, ret, NULL);
891 if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
892 btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
893 flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
898 owner = btrfs_header_owner(buf);
899 BUG_ON(owner == BTRFS_TREE_RELOC_OBJECTID &&
900 !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
903 if ((owner == root->root_key.objectid ||
904 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) &&
905 !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)) {
906 ret = btrfs_inc_ref(trans, root, buf, 1);
910 if (root->root_key.objectid ==
911 BTRFS_TREE_RELOC_OBJECTID) {
912 ret = btrfs_dec_ref(trans, root, buf, 0);
915 ret = btrfs_inc_ref(trans, root, cow, 1);
919 new_flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
922 if (root->root_key.objectid ==
923 BTRFS_TREE_RELOC_OBJECTID)
924 ret = btrfs_inc_ref(trans, root, cow, 1);
926 ret = btrfs_inc_ref(trans, root, cow, 0);
930 if (new_flags != 0) {
931 int level = btrfs_header_level(buf);
933 ret = btrfs_set_disk_extent_flags(trans, buf,
934 new_flags, level, 0);
939 if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
940 if (root->root_key.objectid ==
941 BTRFS_TREE_RELOC_OBJECTID)
942 ret = btrfs_inc_ref(trans, root, cow, 1);
944 ret = btrfs_inc_ref(trans, root, cow, 0);
947 ret = btrfs_dec_ref(trans, root, buf, 1);
951 btrfs_clean_tree_block(buf);
957 static struct extent_buffer *alloc_tree_block_no_bg_flush(
958 struct btrfs_trans_handle *trans,
959 struct btrfs_root *root,
961 const struct btrfs_disk_key *disk_key,
965 enum btrfs_lock_nesting nest)
967 struct btrfs_fs_info *fs_info = root->fs_info;
968 struct extent_buffer *ret;
971 * If we are COWing a node/leaf from the extent, chunk, device or free
972 * space trees, make sure that we do not finish block group creation of
973 * pending block groups. We do this to avoid a deadlock.
974 * COWing can result in allocation of a new chunk, and flushing pending
975 * block groups (btrfs_create_pending_block_groups()) can be triggered
976 * when finishing allocation of a new chunk. Creation of a pending block
977 * group modifies the extent, chunk, device and free space trees,
978 * therefore we could deadlock with ourselves since we are holding a
979 * lock on an extent buffer that btrfs_create_pending_block_groups() may
981 * For similar reasons, we also need to delay flushing pending block
982 * groups when splitting a leaf or node, from one of those trees, since
983 * we are holding a write lock on it and its parent or when inserting a
984 * new root node for one of those trees.
986 if (root == fs_info->extent_root ||
987 root == fs_info->chunk_root ||
988 root == fs_info->dev_root ||
989 root == fs_info->free_space_root)
990 trans->can_flush_pending_bgs = false;
992 ret = btrfs_alloc_tree_block(trans, root, parent_start,
993 root->root_key.objectid, disk_key, level,
994 hint, empty_size, nest);
995 trans->can_flush_pending_bgs = true;
1001 * does the dirty work in cow of a single block. The parent block (if
1002 * supplied) is updated to point to the new cow copy. The new buffer is marked
1003 * dirty and returned locked. If you modify the block it needs to be marked
1006 * search_start -- an allocation hint for the new block
1008 * empty_size -- a hint that you plan on doing more cow. This is the size in
1009 * bytes the allocator should try to find free next to the block it returns.
1010 * This is just a hint and may be ignored by the allocator.
1012 static noinline int __btrfs_cow_block(struct btrfs_trans_handle *trans,
1013 struct btrfs_root *root,
1014 struct extent_buffer *buf,
1015 struct extent_buffer *parent, int parent_slot,
1016 struct extent_buffer **cow_ret,
1017 u64 search_start, u64 empty_size,
1018 enum btrfs_lock_nesting nest)
1020 struct btrfs_fs_info *fs_info = root->fs_info;
1021 struct btrfs_disk_key disk_key;
1022 struct extent_buffer *cow;
1025 int unlock_orig = 0;
1026 u64 parent_start = 0;
1028 if (*cow_ret == buf)
1031 btrfs_assert_tree_locked(buf);
1033 WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
1034 trans->transid != fs_info->running_transaction->transid);
1035 WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
1036 trans->transid != root->last_trans);
1038 level = btrfs_header_level(buf);
1041 btrfs_item_key(buf, &disk_key, 0);
1043 btrfs_node_key(buf, &disk_key, 0);
1045 if ((root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) && parent)
1046 parent_start = parent->start;
1048 cow = alloc_tree_block_no_bg_flush(trans, root, parent_start, &disk_key,
1049 level, search_start, empty_size, nest);
1051 return PTR_ERR(cow);
1053 /* cow is set to blocking by btrfs_init_new_buffer */
1055 copy_extent_buffer_full(cow, buf);
1056 btrfs_set_header_bytenr(cow, cow->start);
1057 btrfs_set_header_generation(cow, trans->transid);
1058 btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
1059 btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
1060 BTRFS_HEADER_FLAG_RELOC);
1061 if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
1062 btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
1064 btrfs_set_header_owner(cow, root->root_key.objectid);
1066 write_extent_buffer_fsid(cow, fs_info->fs_devices->metadata_uuid);
1068 ret = update_ref_for_cow(trans, root, buf, cow, &last_ref);
1070 btrfs_tree_unlock(cow);
1071 free_extent_buffer(cow);
1072 btrfs_abort_transaction(trans, ret);
1076 if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state)) {
1077 ret = btrfs_reloc_cow_block(trans, root, buf, cow);
1079 btrfs_tree_unlock(cow);
1080 free_extent_buffer(cow);
1081 btrfs_abort_transaction(trans, ret);
1086 if (buf == root->node) {
1087 WARN_ON(parent && parent != buf);
1088 if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
1089 btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
1090 parent_start = buf->start;
1092 atomic_inc(&cow->refs);
1093 ret = tree_mod_log_insert_root(root->node, cow, 1);
1095 rcu_assign_pointer(root->node, cow);
1097 btrfs_free_tree_block(trans, root, buf, parent_start,
1099 free_extent_buffer(buf);
1100 add_root_to_dirty_list(root);
1102 WARN_ON(trans->transid != btrfs_header_generation(parent));
1103 tree_mod_log_insert_key(parent, parent_slot,
1104 MOD_LOG_KEY_REPLACE, GFP_NOFS);
1105 btrfs_set_node_blockptr(parent, parent_slot,
1107 btrfs_set_node_ptr_generation(parent, parent_slot,
1109 btrfs_mark_buffer_dirty(parent);
1111 ret = tree_mod_log_free_eb(buf);
1113 btrfs_tree_unlock(cow);
1114 free_extent_buffer(cow);
1115 btrfs_abort_transaction(trans, ret);
1119 btrfs_free_tree_block(trans, root, buf, parent_start,
1123 btrfs_tree_unlock(buf);
1124 free_extent_buffer_stale(buf);
1125 btrfs_mark_buffer_dirty(cow);
1131 * returns the logical address of the oldest predecessor of the given root.
1132 * entries older than time_seq are ignored.
1134 static struct tree_mod_elem *__tree_mod_log_oldest_root(
1135 struct extent_buffer *eb_root, u64 time_seq)
1137 struct tree_mod_elem *tm;
1138 struct tree_mod_elem *found = NULL;
1139 u64 root_logical = eb_root->start;
1146 * the very last operation that's logged for a root is the
1147 * replacement operation (if it is replaced at all). this has
1148 * the logical address of the *new* root, making it the very
1149 * first operation that's logged for this root.
1152 tm = tree_mod_log_search_oldest(eb_root->fs_info, root_logical,
1157 * if there are no tree operation for the oldest root, we simply
1158 * return it. this should only happen if that (old) root is at
1165 * if there's an operation that's not a root replacement, we
1166 * found the oldest version of our root. normally, we'll find a
1167 * MOD_LOG_KEY_REMOVE_WHILE_FREEING operation here.
1169 if (tm->op != MOD_LOG_ROOT_REPLACE)
1173 root_logical = tm->old_root.logical;
1177 /* if there's no old root to return, return what we found instead */
1185 * tm is a pointer to the first operation to rewind within eb. then, all
1186 * previous operations will be rewound (until we reach something older than
1190 __tree_mod_log_rewind(struct btrfs_fs_info *fs_info, struct extent_buffer *eb,
1191 u64 time_seq, struct tree_mod_elem *first_tm)
1194 struct rb_node *next;
1195 struct tree_mod_elem *tm = first_tm;
1196 unsigned long o_dst;
1197 unsigned long o_src;
1198 unsigned long p_size = sizeof(struct btrfs_key_ptr);
1200 n = btrfs_header_nritems(eb);
1201 read_lock(&fs_info->tree_mod_log_lock);
1202 while (tm && tm->seq >= time_seq) {
1204 * all the operations are recorded with the operator used for
1205 * the modification. as we're going backwards, we do the
1206 * opposite of each operation here.
1209 case MOD_LOG_KEY_REMOVE_WHILE_FREEING:
1210 BUG_ON(tm->slot < n);
1212 case MOD_LOG_KEY_REMOVE_WHILE_MOVING:
1213 case MOD_LOG_KEY_REMOVE:
1214 btrfs_set_node_key(eb, &tm->key, tm->slot);
1215 btrfs_set_node_blockptr(eb, tm->slot, tm->blockptr);
1216 btrfs_set_node_ptr_generation(eb, tm->slot,
1220 case MOD_LOG_KEY_REPLACE:
1221 BUG_ON(tm->slot >= n);
1222 btrfs_set_node_key(eb, &tm->key, tm->slot);
1223 btrfs_set_node_blockptr(eb, tm->slot, tm->blockptr);
1224 btrfs_set_node_ptr_generation(eb, tm->slot,
1227 case MOD_LOG_KEY_ADD:
1228 /* if a move operation is needed it's in the log */
1231 case MOD_LOG_MOVE_KEYS:
1232 o_dst = btrfs_node_key_ptr_offset(tm->slot);
1233 o_src = btrfs_node_key_ptr_offset(tm->move.dst_slot);
1234 memmove_extent_buffer(eb, o_dst, o_src,
1235 tm->move.nr_items * p_size);
1237 case MOD_LOG_ROOT_REPLACE:
1239 * this operation is special. for roots, this must be
1240 * handled explicitly before rewinding.
1241 * for non-roots, this operation may exist if the node
1242 * was a root: root A -> child B; then A gets empty and
1243 * B is promoted to the new root. in the mod log, we'll
1244 * have a root-replace operation for B, a tree block
1245 * that is no root. we simply ignore that operation.
1249 next = rb_next(&tm->node);
1252 tm = rb_entry(next, struct tree_mod_elem, node);
1253 if (tm->logical != first_tm->logical)
1256 read_unlock(&fs_info->tree_mod_log_lock);
1257 btrfs_set_header_nritems(eb, n);
1261 * Called with eb read locked. If the buffer cannot be rewound, the same buffer
1262 * is returned. If rewind operations happen, a fresh buffer is returned. The
1263 * returned buffer is always read-locked. If the returned buffer is not the
1264 * input buffer, the lock on the input buffer is released and the input buffer
1265 * is freed (its refcount is decremented).
1267 static struct extent_buffer *
1268 tree_mod_log_rewind(struct btrfs_fs_info *fs_info, struct btrfs_path *path,
1269 struct extent_buffer *eb, u64 time_seq)
1271 struct extent_buffer *eb_rewin;
1272 struct tree_mod_elem *tm;
1277 if (btrfs_header_level(eb) == 0)
1280 tm = tree_mod_log_search(fs_info, eb->start, time_seq);
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(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(eb);
1301 free_extent_buffer(eb);
1306 btrfs_tree_read_unlock(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, root->root_key.objectid,
1361 if (WARN_ON(IS_ERR(old) || !extent_buffer_uptodate(old))) {
1363 free_extent_buffer(old);
1365 "failed to read tree block %llu from get_old_root",
1368 btrfs_tree_read_lock(old);
1369 eb = btrfs_clone_extent_buffer(old);
1370 btrfs_tree_read_unlock(old);
1371 free_extent_buffer(old);
1373 } else if (old_root) {
1374 eb_root_owner = btrfs_header_owner(eb_root);
1375 btrfs_tree_read_unlock(eb_root);
1376 free_extent_buffer(eb_root);
1377 eb = alloc_dummy_extent_buffer(fs_info, logical);
1379 eb = btrfs_clone_extent_buffer(eb_root);
1380 btrfs_tree_read_unlock(eb_root);
1381 free_extent_buffer(eb_root);
1387 btrfs_set_header_bytenr(eb, eb->start);
1388 btrfs_set_header_backref_rev(eb, BTRFS_MIXED_BACKREF_REV);
1389 btrfs_set_header_owner(eb, eb_root_owner);
1390 btrfs_set_header_level(eb, old_root->level);
1391 btrfs_set_header_generation(eb, old_generation);
1393 btrfs_set_buffer_lockdep_class(btrfs_header_owner(eb), eb,
1394 btrfs_header_level(eb));
1395 btrfs_tree_read_lock(eb);
1397 __tree_mod_log_rewind(fs_info, eb, time_seq, tm);
1399 WARN_ON(btrfs_header_level(eb) != 0);
1400 WARN_ON(btrfs_header_nritems(eb) > BTRFS_NODEPTRS_PER_BLOCK(fs_info));
1405 int btrfs_old_root_level(struct btrfs_root *root, u64 time_seq)
1407 struct tree_mod_elem *tm;
1409 struct extent_buffer *eb_root = btrfs_root_node(root);
1411 tm = __tree_mod_log_oldest_root(eb_root, time_seq);
1412 if (tm && tm->op == MOD_LOG_ROOT_REPLACE) {
1413 level = tm->old_root.level;
1415 level = btrfs_header_level(eb_root);
1417 free_extent_buffer(eb_root);
1422 static inline int should_cow_block(struct btrfs_trans_handle *trans,
1423 struct btrfs_root *root,
1424 struct extent_buffer *buf)
1426 if (btrfs_is_testing(root->fs_info))
1429 /* Ensure we can see the FORCE_COW bit */
1430 smp_mb__before_atomic();
1433 * We do not need to cow a block if
1434 * 1) this block is not created or changed in this transaction;
1435 * 2) this block does not belong to TREE_RELOC tree;
1436 * 3) the root is not forced COW.
1438 * What is forced COW:
1439 * when we create snapshot during committing the transaction,
1440 * after we've finished copying src root, we must COW the shared
1441 * block to ensure the metadata consistency.
1443 if (btrfs_header_generation(buf) == trans->transid &&
1444 !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN) &&
1445 !(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
1446 btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)) &&
1447 !test_bit(BTRFS_ROOT_FORCE_COW, &root->state))
1453 * cows a single block, see __btrfs_cow_block for the real work.
1454 * This version of it has extra checks so that a block isn't COWed more than
1455 * once per transaction, as long as it hasn't been written yet
1457 noinline int btrfs_cow_block(struct btrfs_trans_handle *trans,
1458 struct btrfs_root *root, struct extent_buffer *buf,
1459 struct extent_buffer *parent, int parent_slot,
1460 struct extent_buffer **cow_ret,
1461 enum btrfs_lock_nesting nest)
1463 struct btrfs_fs_info *fs_info = root->fs_info;
1467 if (test_bit(BTRFS_ROOT_DELETING, &root->state))
1469 "COW'ing blocks on a fs root that's being dropped");
1471 if (trans->transaction != fs_info->running_transaction)
1472 WARN(1, KERN_CRIT "trans %llu running %llu\n",
1474 fs_info->running_transaction->transid);
1476 if (trans->transid != fs_info->generation)
1477 WARN(1, KERN_CRIT "trans %llu running %llu\n",
1478 trans->transid, fs_info->generation);
1480 if (!should_cow_block(trans, root, buf)) {
1481 trans->dirty = true;
1486 search_start = buf->start & ~((u64)SZ_1G - 1);
1489 * Before CoWing this block for later modification, check if it's
1490 * the subtree root and do the delayed subtree trace if needed.
1492 * Also We don't care about the error, as it's handled internally.
1494 btrfs_qgroup_trace_subtree_after_cow(trans, root, buf);
1495 ret = __btrfs_cow_block(trans, root, buf, parent,
1496 parent_slot, cow_ret, search_start, 0, nest);
1498 trace_btrfs_cow_block(root, buf, *cow_ret);
1502 ALLOW_ERROR_INJECTION(btrfs_cow_block, ERRNO);
1505 * helper function for defrag to decide if two blocks pointed to by a
1506 * node are actually close by
1508 static int close_blocks(u64 blocknr, u64 other, u32 blocksize)
1510 if (blocknr < other && other - (blocknr + blocksize) < 32768)
1512 if (blocknr > other && blocknr - (other + blocksize) < 32768)
1517 #ifdef __LITTLE_ENDIAN
1520 * Compare two keys, on little-endian the disk order is same as CPU order and
1521 * we can avoid the conversion.
1523 static int comp_keys(const struct btrfs_disk_key *disk_key,
1524 const struct btrfs_key *k2)
1526 const struct btrfs_key *k1 = (const struct btrfs_key *)disk_key;
1528 return btrfs_comp_cpu_keys(k1, k2);
1534 * compare two keys in a memcmp fashion
1536 static int comp_keys(const struct btrfs_disk_key *disk,
1537 const struct btrfs_key *k2)
1539 struct btrfs_key k1;
1541 btrfs_disk_key_to_cpu(&k1, disk);
1543 return btrfs_comp_cpu_keys(&k1, k2);
1548 * same as comp_keys only with two btrfs_key's
1550 int __pure btrfs_comp_cpu_keys(const struct btrfs_key *k1, const struct btrfs_key *k2)
1552 if (k1->objectid > k2->objectid)
1554 if (k1->objectid < k2->objectid)
1556 if (k1->type > k2->type)
1558 if (k1->type < k2->type)
1560 if (k1->offset > k2->offset)
1562 if (k1->offset < k2->offset)
1568 * this is used by the defrag code to go through all the
1569 * leaves pointed to by a node and reallocate them so that
1570 * disk order is close to key order
1572 int btrfs_realloc_node(struct btrfs_trans_handle *trans,
1573 struct btrfs_root *root, struct extent_buffer *parent,
1574 int start_slot, u64 *last_ret,
1575 struct btrfs_key *progress)
1577 struct btrfs_fs_info *fs_info = root->fs_info;
1578 struct extent_buffer *cur;
1580 u64 search_start = *last_ret;
1588 int progress_passed = 0;
1589 struct btrfs_disk_key disk_key;
1591 WARN_ON(trans->transaction != fs_info->running_transaction);
1592 WARN_ON(trans->transid != fs_info->generation);
1594 parent_nritems = btrfs_header_nritems(parent);
1595 blocksize = fs_info->nodesize;
1596 end_slot = parent_nritems - 1;
1598 if (parent_nritems <= 1)
1601 for (i = start_slot; i <= end_slot; i++) {
1604 btrfs_node_key(parent, &disk_key, i);
1605 if (!progress_passed && comp_keys(&disk_key, progress) < 0)
1608 progress_passed = 1;
1609 blocknr = btrfs_node_blockptr(parent, i);
1610 if (last_block == 0)
1611 last_block = blocknr;
1614 other = btrfs_node_blockptr(parent, i - 1);
1615 close = close_blocks(blocknr, other, blocksize);
1617 if (!close && i < end_slot) {
1618 other = btrfs_node_blockptr(parent, i + 1);
1619 close = close_blocks(blocknr, other, blocksize);
1622 last_block = blocknr;
1626 cur = btrfs_read_node_slot(parent, i);
1628 return PTR_ERR(cur);
1629 if (search_start == 0)
1630 search_start = last_block;
1632 btrfs_tree_lock(cur);
1633 err = __btrfs_cow_block(trans, root, cur, parent, i,
1636 (end_slot - i) * blocksize),
1639 btrfs_tree_unlock(cur);
1640 free_extent_buffer(cur);
1643 search_start = cur->start;
1644 last_block = cur->start;
1645 *last_ret = search_start;
1646 btrfs_tree_unlock(cur);
1647 free_extent_buffer(cur);
1653 * search for key in the extent_buffer. The items start at offset p,
1654 * and they are item_size apart. There are 'max' items in p.
1656 * the slot in the array is returned via slot, and it points to
1657 * the place where you would insert key if it is not found in
1660 * slot may point to max if the key is bigger than all of the keys
1662 static noinline int generic_bin_search(struct extent_buffer *eb,
1663 unsigned long p, int item_size,
1664 const struct btrfs_key *key,
1670 const int key_size = sizeof(struct btrfs_disk_key);
1673 btrfs_err(eb->fs_info,
1674 "%s: low (%d) > high (%d) eb %llu owner %llu level %d",
1675 __func__, low, high, eb->start,
1676 btrfs_header_owner(eb), btrfs_header_level(eb));
1680 while (low < high) {
1682 unsigned long offset;
1683 struct btrfs_disk_key *tmp;
1684 struct btrfs_disk_key unaligned;
1687 mid = (low + high) / 2;
1688 offset = p + mid * item_size;
1689 oip = offset_in_page(offset);
1691 if (oip + key_size <= PAGE_SIZE) {
1692 const unsigned long idx = get_eb_page_index(offset);
1693 char *kaddr = page_address(eb->pages[idx]);
1695 oip = get_eb_offset_in_page(eb, offset);
1696 tmp = (struct btrfs_disk_key *)(kaddr + oip);
1698 read_extent_buffer(eb, &unaligned, offset, key_size);
1702 ret = comp_keys(tmp, key);
1718 * simple bin_search frontend that does the right thing for
1721 int btrfs_bin_search(struct extent_buffer *eb, const struct btrfs_key *key,
1724 if (btrfs_header_level(eb) == 0)
1725 return generic_bin_search(eb,
1726 offsetof(struct btrfs_leaf, items),
1727 sizeof(struct btrfs_item),
1728 key, btrfs_header_nritems(eb),
1731 return generic_bin_search(eb,
1732 offsetof(struct btrfs_node, ptrs),
1733 sizeof(struct btrfs_key_ptr),
1734 key, btrfs_header_nritems(eb),
1738 static void root_add_used(struct btrfs_root *root, u32 size)
1740 spin_lock(&root->accounting_lock);
1741 btrfs_set_root_used(&root->root_item,
1742 btrfs_root_used(&root->root_item) + size);
1743 spin_unlock(&root->accounting_lock);
1746 static void root_sub_used(struct btrfs_root *root, u32 size)
1748 spin_lock(&root->accounting_lock);
1749 btrfs_set_root_used(&root->root_item,
1750 btrfs_root_used(&root->root_item) - size);
1751 spin_unlock(&root->accounting_lock);
1754 /* given a node and slot number, this reads the blocks it points to. The
1755 * extent buffer is returned with a reference taken (but unlocked).
1757 struct extent_buffer *btrfs_read_node_slot(struct extent_buffer *parent,
1760 int level = btrfs_header_level(parent);
1761 struct extent_buffer *eb;
1762 struct btrfs_key first_key;
1764 if (slot < 0 || slot >= btrfs_header_nritems(parent))
1765 return ERR_PTR(-ENOENT);
1769 btrfs_node_key_to_cpu(parent, &first_key, slot);
1770 eb = read_tree_block(parent->fs_info, btrfs_node_blockptr(parent, slot),
1771 btrfs_header_owner(parent),
1772 btrfs_node_ptr_generation(parent, slot),
1773 level - 1, &first_key);
1774 if (!IS_ERR(eb) && !extent_buffer_uptodate(eb)) {
1775 free_extent_buffer(eb);
1783 * node level balancing, used to make sure nodes are in proper order for
1784 * item deletion. We balance from the top down, so we have to make sure
1785 * that a deletion won't leave an node completely empty later on.
1787 static noinline int balance_level(struct btrfs_trans_handle *trans,
1788 struct btrfs_root *root,
1789 struct btrfs_path *path, int level)
1791 struct btrfs_fs_info *fs_info = root->fs_info;
1792 struct extent_buffer *right = NULL;
1793 struct extent_buffer *mid;
1794 struct extent_buffer *left = NULL;
1795 struct extent_buffer *parent = NULL;
1799 int orig_slot = path->slots[level];
1804 mid = path->nodes[level];
1806 WARN_ON(path->locks[level] != BTRFS_WRITE_LOCK);
1807 WARN_ON(btrfs_header_generation(mid) != trans->transid);
1809 orig_ptr = btrfs_node_blockptr(mid, orig_slot);
1811 if (level < BTRFS_MAX_LEVEL - 1) {
1812 parent = path->nodes[level + 1];
1813 pslot = path->slots[level + 1];
1817 * deal with the case where there is only one pointer in the root
1818 * by promoting the node below to a root
1821 struct extent_buffer *child;
1823 if (btrfs_header_nritems(mid) != 1)
1826 /* promote the child to a root */
1827 child = btrfs_read_node_slot(mid, 0);
1828 if (IS_ERR(child)) {
1829 ret = PTR_ERR(child);
1830 btrfs_handle_fs_error(fs_info, ret, NULL);
1834 btrfs_tree_lock(child);
1835 ret = btrfs_cow_block(trans, root, child, mid, 0, &child,
1838 btrfs_tree_unlock(child);
1839 free_extent_buffer(child);
1843 ret = tree_mod_log_insert_root(root->node, child, 1);
1845 rcu_assign_pointer(root->node, child);
1847 add_root_to_dirty_list(root);
1848 btrfs_tree_unlock(child);
1850 path->locks[level] = 0;
1851 path->nodes[level] = NULL;
1852 btrfs_clean_tree_block(mid);
1853 btrfs_tree_unlock(mid);
1854 /* once for the path */
1855 free_extent_buffer(mid);
1857 root_sub_used(root, mid->len);
1858 btrfs_free_tree_block(trans, root, mid, 0, 1);
1859 /* once for the root ptr */
1860 free_extent_buffer_stale(mid);
1863 if (btrfs_header_nritems(mid) >
1864 BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 4)
1867 left = btrfs_read_node_slot(parent, pslot - 1);
1872 __btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
1873 wret = btrfs_cow_block(trans, root, left,
1874 parent, pslot - 1, &left,
1875 BTRFS_NESTING_LEFT_COW);
1882 right = btrfs_read_node_slot(parent, pslot + 1);
1887 __btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
1888 wret = btrfs_cow_block(trans, root, right,
1889 parent, pslot + 1, &right,
1890 BTRFS_NESTING_RIGHT_COW);
1897 /* first, try to make some room in the middle buffer */
1899 orig_slot += btrfs_header_nritems(left);
1900 wret = push_node_left(trans, left, mid, 1);
1906 * then try to empty the right most buffer into the middle
1909 wret = push_node_left(trans, mid, right, 1);
1910 if (wret < 0 && wret != -ENOSPC)
1912 if (btrfs_header_nritems(right) == 0) {
1913 btrfs_clean_tree_block(right);
1914 btrfs_tree_unlock(right);
1915 del_ptr(root, path, level + 1, pslot + 1);
1916 root_sub_used(root, right->len);
1917 btrfs_free_tree_block(trans, root, right, 0, 1);
1918 free_extent_buffer_stale(right);
1921 struct btrfs_disk_key right_key;
1922 btrfs_node_key(right, &right_key, 0);
1923 ret = tree_mod_log_insert_key(parent, pslot + 1,
1924 MOD_LOG_KEY_REPLACE, GFP_NOFS);
1926 btrfs_set_node_key(parent, &right_key, pslot + 1);
1927 btrfs_mark_buffer_dirty(parent);
1930 if (btrfs_header_nritems(mid) == 1) {
1932 * we're not allowed to leave a node with one item in the
1933 * tree during a delete. A deletion from lower in the tree
1934 * could try to delete the only pointer in this node.
1935 * So, pull some keys from the left.
1936 * There has to be a left pointer at this point because
1937 * otherwise we would have pulled some pointers from the
1942 btrfs_handle_fs_error(fs_info, ret, NULL);
1945 wret = balance_node_right(trans, mid, left);
1951 wret = push_node_left(trans, left, mid, 1);
1957 if (btrfs_header_nritems(mid) == 0) {
1958 btrfs_clean_tree_block(mid);
1959 btrfs_tree_unlock(mid);
1960 del_ptr(root, path, level + 1, pslot);
1961 root_sub_used(root, mid->len);
1962 btrfs_free_tree_block(trans, root, mid, 0, 1);
1963 free_extent_buffer_stale(mid);
1966 /* update the parent key to reflect our changes */
1967 struct btrfs_disk_key mid_key;
1968 btrfs_node_key(mid, &mid_key, 0);
1969 ret = tree_mod_log_insert_key(parent, pslot,
1970 MOD_LOG_KEY_REPLACE, GFP_NOFS);
1972 btrfs_set_node_key(parent, &mid_key, pslot);
1973 btrfs_mark_buffer_dirty(parent);
1976 /* update the path */
1978 if (btrfs_header_nritems(left) > orig_slot) {
1979 atomic_inc(&left->refs);
1980 /* left was locked after cow */
1981 path->nodes[level] = left;
1982 path->slots[level + 1] -= 1;
1983 path->slots[level] = orig_slot;
1985 btrfs_tree_unlock(mid);
1986 free_extent_buffer(mid);
1989 orig_slot -= btrfs_header_nritems(left);
1990 path->slots[level] = orig_slot;
1993 /* double check we haven't messed things up */
1995 btrfs_node_blockptr(path->nodes[level], path->slots[level]))
1999 btrfs_tree_unlock(right);
2000 free_extent_buffer(right);
2003 if (path->nodes[level] != left)
2004 btrfs_tree_unlock(left);
2005 free_extent_buffer(left);
2010 /* Node balancing for insertion. Here we only split or push nodes around
2011 * when they are completely full. This is also done top down, so we
2012 * have to be pessimistic.
2014 static noinline int push_nodes_for_insert(struct btrfs_trans_handle *trans,
2015 struct btrfs_root *root,
2016 struct btrfs_path *path, int level)
2018 struct btrfs_fs_info *fs_info = root->fs_info;
2019 struct extent_buffer *right = NULL;
2020 struct extent_buffer *mid;
2021 struct extent_buffer *left = NULL;
2022 struct extent_buffer *parent = NULL;
2026 int orig_slot = path->slots[level];
2031 mid = path->nodes[level];
2032 WARN_ON(btrfs_header_generation(mid) != trans->transid);
2034 if (level < BTRFS_MAX_LEVEL - 1) {
2035 parent = path->nodes[level + 1];
2036 pslot = path->slots[level + 1];
2042 left = btrfs_read_node_slot(parent, pslot - 1);
2046 /* first, try to make some room in the middle buffer */
2050 __btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
2052 left_nr = btrfs_header_nritems(left);
2053 if (left_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
2056 ret = btrfs_cow_block(trans, root, left, parent,
2058 BTRFS_NESTING_LEFT_COW);
2062 wret = push_node_left(trans, left, mid, 0);
2068 struct btrfs_disk_key disk_key;
2069 orig_slot += left_nr;
2070 btrfs_node_key(mid, &disk_key, 0);
2071 ret = tree_mod_log_insert_key(parent, pslot,
2072 MOD_LOG_KEY_REPLACE, GFP_NOFS);
2074 btrfs_set_node_key(parent, &disk_key, pslot);
2075 btrfs_mark_buffer_dirty(parent);
2076 if (btrfs_header_nritems(left) > orig_slot) {
2077 path->nodes[level] = left;
2078 path->slots[level + 1] -= 1;
2079 path->slots[level] = orig_slot;
2080 btrfs_tree_unlock(mid);
2081 free_extent_buffer(mid);
2084 btrfs_header_nritems(left);
2085 path->slots[level] = orig_slot;
2086 btrfs_tree_unlock(left);
2087 free_extent_buffer(left);
2091 btrfs_tree_unlock(left);
2092 free_extent_buffer(left);
2094 right = btrfs_read_node_slot(parent, pslot + 1);
2099 * then try to empty the right most buffer into the middle
2104 __btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
2106 right_nr = btrfs_header_nritems(right);
2107 if (right_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
2110 ret = btrfs_cow_block(trans, root, right,
2112 &right, BTRFS_NESTING_RIGHT_COW);
2116 wret = balance_node_right(trans, right, mid);
2122 struct btrfs_disk_key disk_key;
2124 btrfs_node_key(right, &disk_key, 0);
2125 ret = tree_mod_log_insert_key(parent, pslot + 1,
2126 MOD_LOG_KEY_REPLACE, GFP_NOFS);
2128 btrfs_set_node_key(parent, &disk_key, pslot + 1);
2129 btrfs_mark_buffer_dirty(parent);
2131 if (btrfs_header_nritems(mid) <= orig_slot) {
2132 path->nodes[level] = right;
2133 path->slots[level + 1] += 1;
2134 path->slots[level] = orig_slot -
2135 btrfs_header_nritems(mid);
2136 btrfs_tree_unlock(mid);
2137 free_extent_buffer(mid);
2139 btrfs_tree_unlock(right);
2140 free_extent_buffer(right);
2144 btrfs_tree_unlock(right);
2145 free_extent_buffer(right);
2151 * readahead one full node of leaves, finding things that are close
2152 * to the block in 'slot', and triggering ra on them.
2154 static void reada_for_search(struct btrfs_fs_info *fs_info,
2155 struct btrfs_path *path,
2156 int level, int slot, u64 objectid)
2158 struct extent_buffer *node;
2159 struct btrfs_disk_key disk_key;
2164 struct extent_buffer *eb;
2172 if (!path->nodes[level])
2175 node = path->nodes[level];
2177 search = btrfs_node_blockptr(node, slot);
2178 blocksize = fs_info->nodesize;
2179 eb = find_extent_buffer(fs_info, search);
2181 free_extent_buffer(eb);
2187 nritems = btrfs_header_nritems(node);
2191 if (path->reada == READA_BACK) {
2195 } else if (path->reada == READA_FORWARD) {
2200 if (path->reada == READA_BACK && objectid) {
2201 btrfs_node_key(node, &disk_key, nr);
2202 if (btrfs_disk_key_objectid(&disk_key) != objectid)
2205 search = btrfs_node_blockptr(node, nr);
2206 if ((search <= target && target - search <= 65536) ||
2207 (search > target && search - target <= 65536)) {
2208 btrfs_readahead_node_child(node, nr);
2212 if ((nread > 65536 || nscan > 32))
2217 static noinline void reada_for_balance(struct btrfs_path *path, int level)
2219 struct extent_buffer *parent;
2223 parent = path->nodes[level + 1];
2227 nritems = btrfs_header_nritems(parent);
2228 slot = path->slots[level + 1];
2231 btrfs_readahead_node_child(parent, slot - 1);
2232 if (slot + 1 < nritems)
2233 btrfs_readahead_node_child(parent, slot + 1);
2238 * when we walk down the tree, it is usually safe to unlock the higher layers
2239 * in the tree. The exceptions are when our path goes through slot 0, because
2240 * operations on the tree might require changing key pointers higher up in the
2243 * callers might also have set path->keep_locks, which tells this code to keep
2244 * the lock if the path points to the last slot in the block. This is part of
2245 * walking through the tree, and selecting the next slot in the higher block.
2247 * lowest_unlock sets the lowest level in the tree we're allowed to unlock. so
2248 * if lowest_unlock is 1, level 0 won't be unlocked
2250 static noinline void unlock_up(struct btrfs_path *path, int level,
2251 int lowest_unlock, int min_write_lock_level,
2252 int *write_lock_level)
2255 int skip_level = level;
2257 struct extent_buffer *t;
2259 for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2260 if (!path->nodes[i])
2262 if (!path->locks[i])
2264 if (!no_skips && path->slots[i] == 0) {
2268 if (!no_skips && path->keep_locks) {
2271 nritems = btrfs_header_nritems(t);
2272 if (nritems < 1 || path->slots[i] >= nritems - 1) {
2277 if (skip_level < i && i >= lowest_unlock)
2281 if (i >= lowest_unlock && i > skip_level) {
2282 btrfs_tree_unlock_rw(t, path->locks[i]);
2284 if (write_lock_level &&
2285 i > min_write_lock_level &&
2286 i <= *write_lock_level) {
2287 *write_lock_level = i - 1;
2294 * helper function for btrfs_search_slot. The goal is to find a block
2295 * in cache without setting the path to blocking. If we find the block
2296 * we return zero and the path is unchanged.
2298 * If we can't find the block, we set the path blocking and do some
2299 * reada. -EAGAIN is returned and the search must be repeated.
2302 read_block_for_search(struct btrfs_root *root, struct btrfs_path *p,
2303 struct extent_buffer **eb_ret, int level, int slot,
2304 const struct btrfs_key *key)
2306 struct btrfs_fs_info *fs_info = root->fs_info;
2309 struct extent_buffer *tmp;
2310 struct btrfs_key first_key;
2314 blocknr = btrfs_node_blockptr(*eb_ret, slot);
2315 gen = btrfs_node_ptr_generation(*eb_ret, slot);
2316 parent_level = btrfs_header_level(*eb_ret);
2317 btrfs_node_key_to_cpu(*eb_ret, &first_key, slot);
2319 tmp = find_extent_buffer(fs_info, blocknr);
2321 /* first we do an atomic uptodate check */
2322 if (btrfs_buffer_uptodate(tmp, gen, 1) > 0) {
2324 * Do extra check for first_key, eb can be stale due to
2325 * being cached, read from scrub, or have multiple
2326 * parents (shared tree blocks).
2328 if (btrfs_verify_level_key(tmp,
2329 parent_level - 1, &first_key, gen)) {
2330 free_extent_buffer(tmp);
2337 /* now we're allowed to do a blocking uptodate check */
2338 ret = btrfs_read_buffer(tmp, gen, parent_level - 1, &first_key);
2343 free_extent_buffer(tmp);
2344 btrfs_release_path(p);
2349 * reduce lock contention at high levels
2350 * of the btree by dropping locks before
2351 * we read. Don't release the lock on the current
2352 * level because we need to walk this node to figure
2353 * out which blocks to read.
2355 btrfs_unlock_up_safe(p, level + 1);
2357 if (p->reada != READA_NONE)
2358 reada_for_search(fs_info, p, level, slot, key->objectid);
2361 tmp = read_tree_block(fs_info, blocknr, root->root_key.objectid,
2362 gen, parent_level - 1, &first_key);
2365 * If the read above didn't mark this buffer up to date,
2366 * it will never end up being up to date. Set ret to EIO now
2367 * and give up so that our caller doesn't loop forever
2370 if (!extent_buffer_uptodate(tmp))
2372 free_extent_buffer(tmp);
2377 btrfs_release_path(p);
2382 * helper function for btrfs_search_slot. This does all of the checks
2383 * for node-level blocks and does any balancing required based on
2386 * If no extra work was required, zero is returned. If we had to
2387 * drop the path, -EAGAIN is returned and btrfs_search_slot must
2391 setup_nodes_for_search(struct btrfs_trans_handle *trans,
2392 struct btrfs_root *root, struct btrfs_path *p,
2393 struct extent_buffer *b, int level, int ins_len,
2394 int *write_lock_level)
2396 struct btrfs_fs_info *fs_info = root->fs_info;
2399 if ((p->search_for_split || ins_len > 0) && btrfs_header_nritems(b) >=
2400 BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3) {
2402 if (*write_lock_level < level + 1) {
2403 *write_lock_level = level + 1;
2404 btrfs_release_path(p);
2408 reada_for_balance(p, level);
2409 ret = split_node(trans, root, p, level);
2411 b = p->nodes[level];
2412 } else if (ins_len < 0 && btrfs_header_nritems(b) <
2413 BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 2) {
2415 if (*write_lock_level < level + 1) {
2416 *write_lock_level = level + 1;
2417 btrfs_release_path(p);
2421 reada_for_balance(p, level);
2422 ret = balance_level(trans, root, p, level);
2426 b = p->nodes[level];
2428 btrfs_release_path(p);
2431 BUG_ON(btrfs_header_nritems(b) == 1);
2436 int btrfs_find_item(struct btrfs_root *fs_root, struct btrfs_path *path,
2437 u64 iobjectid, u64 ioff, u8 key_type,
2438 struct btrfs_key *found_key)
2441 struct btrfs_key key;
2442 struct extent_buffer *eb;
2447 key.type = key_type;
2448 key.objectid = iobjectid;
2451 ret = btrfs_search_slot(NULL, fs_root, &key, path, 0, 0);
2455 eb = path->nodes[0];
2456 if (ret && path->slots[0] >= btrfs_header_nritems(eb)) {
2457 ret = btrfs_next_leaf(fs_root, path);
2460 eb = path->nodes[0];
2463 btrfs_item_key_to_cpu(eb, found_key, path->slots[0]);
2464 if (found_key->type != key.type ||
2465 found_key->objectid != key.objectid)
2471 static struct extent_buffer *btrfs_search_slot_get_root(struct btrfs_root *root,
2472 struct btrfs_path *p,
2473 int write_lock_level)
2475 struct btrfs_fs_info *fs_info = root->fs_info;
2476 struct extent_buffer *b;
2480 /* We try very hard to do read locks on the root */
2481 root_lock = BTRFS_READ_LOCK;
2483 if (p->search_commit_root) {
2485 * The commit roots are read only so we always do read locks,
2486 * and we always must hold the commit_root_sem when doing
2487 * searches on them, the only exception is send where we don't
2488 * want to block transaction commits for a long time, so
2489 * we need to clone the commit root in order to avoid races
2490 * with transaction commits that create a snapshot of one of
2491 * the roots used by a send operation.
2493 if (p->need_commit_sem) {
2494 down_read(&fs_info->commit_root_sem);
2495 b = btrfs_clone_extent_buffer(root->commit_root);
2496 up_read(&fs_info->commit_root_sem);
2498 return ERR_PTR(-ENOMEM);
2501 b = root->commit_root;
2502 atomic_inc(&b->refs);
2504 level = btrfs_header_level(b);
2506 * Ensure that all callers have set skip_locking when
2507 * p->search_commit_root = 1.
2509 ASSERT(p->skip_locking == 1);
2514 if (p->skip_locking) {
2515 b = btrfs_root_node(root);
2516 level = btrfs_header_level(b);
2521 * If the level is set to maximum, we can skip trying to get the read
2524 if (write_lock_level < BTRFS_MAX_LEVEL) {
2526 * We don't know the level of the root node until we actually
2527 * have it read locked
2529 b = btrfs_read_lock_root_node(root);
2530 level = btrfs_header_level(b);
2531 if (level > write_lock_level)
2534 /* Whoops, must trade for write lock */
2535 btrfs_tree_read_unlock(b);
2536 free_extent_buffer(b);
2539 b = btrfs_lock_root_node(root);
2540 root_lock = BTRFS_WRITE_LOCK;
2542 /* The level might have changed, check again */
2543 level = btrfs_header_level(b);
2546 p->nodes[level] = b;
2547 if (!p->skip_locking)
2548 p->locks[level] = root_lock;
2550 * Callers are responsible for dropping b's references.
2557 * btrfs_search_slot - look for a key in a tree and perform necessary
2558 * modifications to preserve tree invariants.
2560 * @trans: Handle of transaction, used when modifying the tree
2561 * @p: Holds all btree nodes along the search path
2562 * @root: The root node of the tree
2563 * @key: The key we are looking for
2564 * @ins_len: Indicates purpose of search:
2565 * >0 for inserts it's size of item inserted (*)
2567 * 0 for plain searches, not modifying the tree
2569 * (*) If size of item inserted doesn't include
2570 * sizeof(struct btrfs_item), then p->search_for_extension must
2572 * @cow: boolean should CoW operations be performed. Must always be 1
2573 * when modifying the tree.
2575 * If @ins_len > 0, nodes and leaves will be split as we walk down the tree.
2576 * If @ins_len < 0, nodes will be merged as we walk down the tree (if possible)
2578 * If @key is found, 0 is returned and you can find the item in the leaf level
2579 * of the path (level 0)
2581 * If @key isn't found, 1 is returned and the leaf level of the path (level 0)
2582 * points to the slot where it should be inserted
2584 * If an error is encountered while searching the tree a negative error number
2587 int btrfs_search_slot(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2588 const struct btrfs_key *key, struct btrfs_path *p,
2589 int ins_len, int cow)
2591 struct extent_buffer *b;
2596 int lowest_unlock = 1;
2597 /* everything at write_lock_level or lower must be write locked */
2598 int write_lock_level = 0;
2599 u8 lowest_level = 0;
2600 int min_write_lock_level;
2603 lowest_level = p->lowest_level;
2604 WARN_ON(lowest_level && ins_len > 0);
2605 WARN_ON(p->nodes[0] != NULL);
2606 BUG_ON(!cow && ins_len);
2611 /* when we are removing items, we might have to go up to level
2612 * two as we update tree pointers Make sure we keep write
2613 * for those levels as well
2615 write_lock_level = 2;
2616 } else if (ins_len > 0) {
2618 * for inserting items, make sure we have a write lock on
2619 * level 1 so we can update keys
2621 write_lock_level = 1;
2625 write_lock_level = -1;
2627 if (cow && (p->keep_locks || p->lowest_level))
2628 write_lock_level = BTRFS_MAX_LEVEL;
2630 min_write_lock_level = write_lock_level;
2634 b = btrfs_search_slot_get_root(root, p, write_lock_level);
2643 level = btrfs_header_level(b);
2646 bool last_level = (level == (BTRFS_MAX_LEVEL - 1));
2649 * if we don't really need to cow this block
2650 * then we don't want to set the path blocking,
2651 * so we test it here
2653 if (!should_cow_block(trans, root, b)) {
2654 trans->dirty = true;
2659 * must have write locks on this node and the
2662 if (level > write_lock_level ||
2663 (level + 1 > write_lock_level &&
2664 level + 1 < BTRFS_MAX_LEVEL &&
2665 p->nodes[level + 1])) {
2666 write_lock_level = level + 1;
2667 btrfs_release_path(p);
2672 err = btrfs_cow_block(trans, root, b, NULL, 0,
2676 err = btrfs_cow_block(trans, root, b,
2677 p->nodes[level + 1],
2678 p->slots[level + 1], &b,
2686 p->nodes[level] = b;
2688 * Leave path with blocking locks to avoid massive
2689 * lock context switch, this is made on purpose.
2693 * we have a lock on b and as long as we aren't changing
2694 * the tree, there is no way to for the items in b to change.
2695 * It is safe to drop the lock on our parent before we
2696 * go through the expensive btree search on b.
2698 * If we're inserting or deleting (ins_len != 0), then we might
2699 * be changing slot zero, which may require changing the parent.
2700 * So, we can't drop the lock until after we know which slot
2701 * we're operating on.
2703 if (!ins_len && !p->keep_locks) {
2706 if (u < BTRFS_MAX_LEVEL && p->locks[u]) {
2707 btrfs_tree_unlock_rw(p->nodes[u], p->locks[u]);
2713 * If btrfs_bin_search returns an exact match (prev_cmp == 0)
2714 * we can safely assume the target key will always be in slot 0
2715 * on lower levels due to the invariants BTRFS' btree provides,
2716 * namely that a btrfs_key_ptr entry always points to the
2717 * lowest key in the child node, thus we can skip searching
2720 if (prev_cmp == 0) {
2724 ret = btrfs_bin_search(b, key, &slot);
2731 p->slots[level] = slot;
2733 * Item key already exists. In this case, if we are
2734 * allowed to insert the item (for example, in dir_item
2735 * case, item key collision is allowed), it will be
2736 * merged with the original item. Only the item size
2737 * grows, no new btrfs item will be added. If
2738 * search_for_extension is not set, ins_len already
2739 * accounts the size btrfs_item, deduct it here so leaf
2740 * space check will be correct.
2742 if (ret == 0 && ins_len > 0 && !p->search_for_extension) {
2743 ASSERT(ins_len >= sizeof(struct btrfs_item));
2744 ins_len -= sizeof(struct btrfs_item);
2747 btrfs_leaf_free_space(b) < ins_len) {
2748 if (write_lock_level < 1) {
2749 write_lock_level = 1;
2750 btrfs_release_path(p);
2754 err = split_leaf(trans, root, key,
2755 p, ins_len, ret == 0);
2763 if (!p->search_for_split)
2764 unlock_up(p, level, lowest_unlock,
2765 min_write_lock_level, NULL);
2768 if (ret && slot > 0) {
2772 p->slots[level] = slot;
2773 err = setup_nodes_for_search(trans, root, p, b, level, ins_len,
2781 b = p->nodes[level];
2782 slot = p->slots[level];
2785 * Slot 0 is special, if we change the key we have to update
2786 * the parent pointer which means we must have a write lock on
2789 if (slot == 0 && ins_len && write_lock_level < level + 1) {
2790 write_lock_level = level + 1;
2791 btrfs_release_path(p);
2795 unlock_up(p, level, lowest_unlock, min_write_lock_level,
2798 if (level == lowest_level) {
2804 err = read_block_for_search(root, p, &b, level, slot, key);
2812 if (!p->skip_locking) {
2813 level = btrfs_header_level(b);
2814 if (level <= write_lock_level) {
2816 p->locks[level] = BTRFS_WRITE_LOCK;
2818 btrfs_tree_read_lock(b);
2819 p->locks[level] = BTRFS_READ_LOCK;
2821 p->nodes[level] = b;
2826 if (ret < 0 && !p->skip_release_on_error)
2827 btrfs_release_path(p);
2830 ALLOW_ERROR_INJECTION(btrfs_search_slot, ERRNO);
2833 * Like btrfs_search_slot, this looks for a key in the given tree. It uses the
2834 * current state of the tree together with the operations recorded in the tree
2835 * modification log to search for the key in a previous version of this tree, as
2836 * denoted by the time_seq parameter.
2838 * Naturally, there is no support for insert, delete or cow operations.
2840 * The resulting path and return value will be set up as if we called
2841 * btrfs_search_slot at that point in time with ins_len and cow both set to 0.
2843 int btrfs_search_old_slot(struct btrfs_root *root, const struct btrfs_key *key,
2844 struct btrfs_path *p, u64 time_seq)
2846 struct btrfs_fs_info *fs_info = root->fs_info;
2847 struct extent_buffer *b;
2852 int lowest_unlock = 1;
2853 u8 lowest_level = 0;
2855 lowest_level = p->lowest_level;
2856 WARN_ON(p->nodes[0] != NULL);
2858 if (p->search_commit_root) {
2860 return btrfs_search_slot(NULL, root, key, p, 0, 0);
2864 b = get_old_root(root, time_seq);
2869 level = btrfs_header_level(b);
2870 p->locks[level] = BTRFS_READ_LOCK;
2875 level = btrfs_header_level(b);
2876 p->nodes[level] = b;
2879 * we have a lock on b and as long as we aren't changing
2880 * the tree, there is no way to for the items in b to change.
2881 * It is safe to drop the lock on our parent before we
2882 * go through the expensive btree search on b.
2884 btrfs_unlock_up_safe(p, level + 1);
2886 ret = btrfs_bin_search(b, key, &slot);
2891 p->slots[level] = slot;
2892 unlock_up(p, level, lowest_unlock, 0, NULL);
2896 if (ret && slot > 0) {
2900 p->slots[level] = slot;
2901 unlock_up(p, level, lowest_unlock, 0, NULL);
2903 if (level == lowest_level) {
2909 err = read_block_for_search(root, p, &b, level, slot, key);
2917 level = btrfs_header_level(b);
2918 btrfs_tree_read_lock(b);
2919 b = tree_mod_log_rewind(fs_info, p, b, time_seq);
2924 p->locks[level] = BTRFS_READ_LOCK;
2925 p->nodes[level] = b;
2930 btrfs_release_path(p);
2936 * helper to use instead of search slot if no exact match is needed but
2937 * instead the next or previous item should be returned.
2938 * When find_higher is true, the next higher item is returned, the next lower
2940 * When return_any and find_higher are both true, and no higher item is found,
2941 * return the next lower instead.
2942 * When return_any is true and find_higher is false, and no lower item is found,
2943 * return the next higher instead.
2944 * It returns 0 if any item is found, 1 if none is found (tree empty), and
2947 int btrfs_search_slot_for_read(struct btrfs_root *root,
2948 const struct btrfs_key *key,
2949 struct btrfs_path *p, int find_higher,
2953 struct extent_buffer *leaf;
2956 ret = btrfs_search_slot(NULL, root, key, p, 0, 0);
2960 * a return value of 1 means the path is at the position where the
2961 * item should be inserted. Normally this is the next bigger item,
2962 * but in case the previous item is the last in a leaf, path points
2963 * to the first free slot in the previous leaf, i.e. at an invalid
2969 if (p->slots[0] >= btrfs_header_nritems(leaf)) {
2970 ret = btrfs_next_leaf(root, p);
2976 * no higher item found, return the next
2981 btrfs_release_path(p);
2985 if (p->slots[0] == 0) {
2986 ret = btrfs_prev_leaf(root, p);
2991 if (p->slots[0] == btrfs_header_nritems(leaf))
2998 * no lower item found, return the next
3003 btrfs_release_path(p);
3013 * adjust the pointers going up the tree, starting at level
3014 * making sure the right key of each node is points to 'key'.
3015 * This is used after shifting pointers to the left, so it stops
3016 * fixing up pointers when a given leaf/node is not in slot 0 of the
3020 static void fixup_low_keys(struct btrfs_path *path,
3021 struct btrfs_disk_key *key, int level)
3024 struct extent_buffer *t;
3027 for (i = level; i < BTRFS_MAX_LEVEL; i++) {
3028 int tslot = path->slots[i];
3030 if (!path->nodes[i])
3033 ret = tree_mod_log_insert_key(t, tslot, MOD_LOG_KEY_REPLACE,
3036 btrfs_set_node_key(t, key, tslot);
3037 btrfs_mark_buffer_dirty(path->nodes[i]);
3046 * This function isn't completely safe. It's the caller's responsibility
3047 * that the new key won't break the order
3049 void btrfs_set_item_key_safe(struct btrfs_fs_info *fs_info,
3050 struct btrfs_path *path,
3051 const struct btrfs_key *new_key)
3053 struct btrfs_disk_key disk_key;
3054 struct extent_buffer *eb;
3057 eb = path->nodes[0];
3058 slot = path->slots[0];
3060 btrfs_item_key(eb, &disk_key, slot - 1);
3061 if (unlikely(comp_keys(&disk_key, new_key) >= 0)) {
3063 "slot %u key (%llu %u %llu) new key (%llu %u %llu)",
3064 slot, btrfs_disk_key_objectid(&disk_key),
3065 btrfs_disk_key_type(&disk_key),
3066 btrfs_disk_key_offset(&disk_key),
3067 new_key->objectid, new_key->type,
3069 btrfs_print_leaf(eb);
3073 if (slot < btrfs_header_nritems(eb) - 1) {
3074 btrfs_item_key(eb, &disk_key, slot + 1);
3075 if (unlikely(comp_keys(&disk_key, new_key) <= 0)) {
3077 "slot %u key (%llu %u %llu) new key (%llu %u %llu)",
3078 slot, btrfs_disk_key_objectid(&disk_key),
3079 btrfs_disk_key_type(&disk_key),
3080 btrfs_disk_key_offset(&disk_key),
3081 new_key->objectid, new_key->type,
3083 btrfs_print_leaf(eb);
3088 btrfs_cpu_key_to_disk(&disk_key, new_key);
3089 btrfs_set_item_key(eb, &disk_key, slot);
3090 btrfs_mark_buffer_dirty(eb);
3092 fixup_low_keys(path, &disk_key, 1);
3096 * Check key order of two sibling extent buffers.
3098 * Return true if something is wrong.
3099 * Return false if everything is fine.
3101 * Tree-checker only works inside one tree block, thus the following
3102 * corruption can not be detected by tree-checker:
3104 * Leaf @left | Leaf @right
3105 * --------------------------------------------------------------
3106 * | 1 | 2 | 3 | 4 | 5 | f6 | | 7 | 8 |
3108 * Key f6 in leaf @left itself is valid, but not valid when the next
3109 * key in leaf @right is 7.
3110 * This can only be checked at tree block merge time.
3111 * And since tree checker has ensured all key order in each tree block
3112 * is correct, we only need to bother the last key of @left and the first
3115 static bool check_sibling_keys(struct extent_buffer *left,
3116 struct extent_buffer *right)
3118 struct btrfs_key left_last;
3119 struct btrfs_key right_first;
3120 int level = btrfs_header_level(left);
3121 int nr_left = btrfs_header_nritems(left);
3122 int nr_right = btrfs_header_nritems(right);
3124 /* No key to check in one of the tree blocks */
3125 if (!nr_left || !nr_right)
3129 btrfs_node_key_to_cpu(left, &left_last, nr_left - 1);
3130 btrfs_node_key_to_cpu(right, &right_first, 0);
3132 btrfs_item_key_to_cpu(left, &left_last, nr_left - 1);
3133 btrfs_item_key_to_cpu(right, &right_first, 0);
3136 if (btrfs_comp_cpu_keys(&left_last, &right_first) >= 0) {
3137 btrfs_crit(left->fs_info,
3138 "bad key order, sibling blocks, left last (%llu %u %llu) right first (%llu %u %llu)",
3139 left_last.objectid, left_last.type,
3140 left_last.offset, right_first.objectid,
3141 right_first.type, right_first.offset);
3148 * try to push data from one node into the next node left in the
3151 * returns 0 if some ptrs were pushed left, < 0 if there was some horrible
3152 * error, and > 0 if there was no room in the left hand block.
3154 static int push_node_left(struct btrfs_trans_handle *trans,
3155 struct extent_buffer *dst,
3156 struct extent_buffer *src, int empty)
3158 struct btrfs_fs_info *fs_info = trans->fs_info;
3164 src_nritems = btrfs_header_nritems(src);
3165 dst_nritems = btrfs_header_nritems(dst);
3166 push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
3167 WARN_ON(btrfs_header_generation(src) != trans->transid);
3168 WARN_ON(btrfs_header_generation(dst) != trans->transid);
3170 if (!empty && src_nritems <= 8)
3173 if (push_items <= 0)
3177 push_items = min(src_nritems, push_items);
3178 if (push_items < src_nritems) {
3179 /* leave at least 8 pointers in the node if
3180 * we aren't going to empty it
3182 if (src_nritems - push_items < 8) {
3183 if (push_items <= 8)
3189 push_items = min(src_nritems - 8, push_items);
3191 /* dst is the left eb, src is the middle eb */
3192 if (check_sibling_keys(dst, src)) {
3194 btrfs_abort_transaction(trans, ret);
3197 ret = tree_mod_log_eb_copy(dst, src, dst_nritems, 0, push_items);
3199 btrfs_abort_transaction(trans, ret);
3202 copy_extent_buffer(dst, src,
3203 btrfs_node_key_ptr_offset(dst_nritems),
3204 btrfs_node_key_ptr_offset(0),
3205 push_items * sizeof(struct btrfs_key_ptr));
3207 if (push_items < src_nritems) {
3209 * Don't call tree_mod_log_insert_move here, key removal was
3210 * already fully logged by tree_mod_log_eb_copy above.
3212 memmove_extent_buffer(src, btrfs_node_key_ptr_offset(0),
3213 btrfs_node_key_ptr_offset(push_items),
3214 (src_nritems - push_items) *
3215 sizeof(struct btrfs_key_ptr));
3217 btrfs_set_header_nritems(src, src_nritems - push_items);
3218 btrfs_set_header_nritems(dst, dst_nritems + push_items);
3219 btrfs_mark_buffer_dirty(src);
3220 btrfs_mark_buffer_dirty(dst);
3226 * try to push data from one node into the next node right in the
3229 * returns 0 if some ptrs were pushed, < 0 if there was some horrible
3230 * error, and > 0 if there was no room in the right hand block.
3232 * this will only push up to 1/2 the contents of the left node over
3234 static int balance_node_right(struct btrfs_trans_handle *trans,
3235 struct extent_buffer *dst,
3236 struct extent_buffer *src)
3238 struct btrfs_fs_info *fs_info = trans->fs_info;
3245 WARN_ON(btrfs_header_generation(src) != trans->transid);
3246 WARN_ON(btrfs_header_generation(dst) != trans->transid);
3248 src_nritems = btrfs_header_nritems(src);
3249 dst_nritems = btrfs_header_nritems(dst);
3250 push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
3251 if (push_items <= 0)
3254 if (src_nritems < 4)
3257 max_push = src_nritems / 2 + 1;
3258 /* don't try to empty the node */
3259 if (max_push >= src_nritems)
3262 if (max_push < push_items)
3263 push_items = max_push;
3265 /* dst is the right eb, src is the middle eb */
3266 if (check_sibling_keys(src, dst)) {
3268 btrfs_abort_transaction(trans, ret);
3271 ret = tree_mod_log_insert_move(dst, push_items, 0, dst_nritems);
3273 memmove_extent_buffer(dst, btrfs_node_key_ptr_offset(push_items),
3274 btrfs_node_key_ptr_offset(0),
3276 sizeof(struct btrfs_key_ptr));
3278 ret = tree_mod_log_eb_copy(dst, src, 0, src_nritems - push_items,
3281 btrfs_abort_transaction(trans, ret);
3284 copy_extent_buffer(dst, src,
3285 btrfs_node_key_ptr_offset(0),
3286 btrfs_node_key_ptr_offset(src_nritems - push_items),
3287 push_items * sizeof(struct btrfs_key_ptr));
3289 btrfs_set_header_nritems(src, src_nritems - push_items);
3290 btrfs_set_header_nritems(dst, dst_nritems + push_items);
3292 btrfs_mark_buffer_dirty(src);
3293 btrfs_mark_buffer_dirty(dst);
3299 * helper function to insert a new root level in the tree.
3300 * A new node is allocated, and a single item is inserted to
3301 * point to the existing root
3303 * returns zero on success or < 0 on failure.
3305 static noinline int insert_new_root(struct btrfs_trans_handle *trans,
3306 struct btrfs_root *root,
3307 struct btrfs_path *path, int level)
3309 struct btrfs_fs_info *fs_info = root->fs_info;
3311 struct extent_buffer *lower;
3312 struct extent_buffer *c;
3313 struct extent_buffer *old;
3314 struct btrfs_disk_key lower_key;
3317 BUG_ON(path->nodes[level]);
3318 BUG_ON(path->nodes[level-1] != root->node);
3320 lower = path->nodes[level-1];
3322 btrfs_item_key(lower, &lower_key, 0);
3324 btrfs_node_key(lower, &lower_key, 0);
3326 c = alloc_tree_block_no_bg_flush(trans, root, 0, &lower_key, level,
3327 root->node->start, 0,
3328 BTRFS_NESTING_NEW_ROOT);
3332 root_add_used(root, fs_info->nodesize);
3334 btrfs_set_header_nritems(c, 1);
3335 btrfs_set_node_key(c, &lower_key, 0);
3336 btrfs_set_node_blockptr(c, 0, lower->start);
3337 lower_gen = btrfs_header_generation(lower);
3338 WARN_ON(lower_gen != trans->transid);
3340 btrfs_set_node_ptr_generation(c, 0, lower_gen);
3342 btrfs_mark_buffer_dirty(c);
3345 ret = tree_mod_log_insert_root(root->node, c, 0);
3347 rcu_assign_pointer(root->node, c);
3349 /* the super has an extra ref to root->node */
3350 free_extent_buffer(old);
3352 add_root_to_dirty_list(root);
3353 atomic_inc(&c->refs);
3354 path->nodes[level] = c;
3355 path->locks[level] = BTRFS_WRITE_LOCK;
3356 path->slots[level] = 0;
3361 * worker function to insert a single pointer in a node.
3362 * the node should have enough room for the pointer already
3364 * slot and level indicate where you want the key to go, and
3365 * blocknr is the block the key points to.
3367 static void insert_ptr(struct btrfs_trans_handle *trans,
3368 struct btrfs_path *path,
3369 struct btrfs_disk_key *key, u64 bytenr,
3370 int slot, int level)
3372 struct extent_buffer *lower;
3376 BUG_ON(!path->nodes[level]);
3377 btrfs_assert_tree_locked(path->nodes[level]);
3378 lower = path->nodes[level];
3379 nritems = btrfs_header_nritems(lower);
3380 BUG_ON(slot > nritems);
3381 BUG_ON(nritems == BTRFS_NODEPTRS_PER_BLOCK(trans->fs_info));
3382 if (slot != nritems) {
3384 ret = tree_mod_log_insert_move(lower, slot + 1, slot,
3388 memmove_extent_buffer(lower,
3389 btrfs_node_key_ptr_offset(slot + 1),
3390 btrfs_node_key_ptr_offset(slot),
3391 (nritems - slot) * sizeof(struct btrfs_key_ptr));
3394 ret = tree_mod_log_insert_key(lower, slot, MOD_LOG_KEY_ADD,
3398 btrfs_set_node_key(lower, key, slot);
3399 btrfs_set_node_blockptr(lower, slot, bytenr);
3400 WARN_ON(trans->transid == 0);
3401 btrfs_set_node_ptr_generation(lower, slot, trans->transid);
3402 btrfs_set_header_nritems(lower, nritems + 1);
3403 btrfs_mark_buffer_dirty(lower);
3407 * split the node at the specified level in path in two.
3408 * The path is corrected to point to the appropriate node after the split
3410 * Before splitting this tries to make some room in the node by pushing
3411 * left and right, if either one works, it returns right away.
3413 * returns 0 on success and < 0 on failure
3415 static noinline int split_node(struct btrfs_trans_handle *trans,
3416 struct btrfs_root *root,
3417 struct btrfs_path *path, int level)
3419 struct btrfs_fs_info *fs_info = root->fs_info;
3420 struct extent_buffer *c;
3421 struct extent_buffer *split;
3422 struct btrfs_disk_key disk_key;
3427 c = path->nodes[level];
3428 WARN_ON(btrfs_header_generation(c) != trans->transid);
3429 if (c == root->node) {
3431 * trying to split the root, lets make a new one
3433 * tree mod log: We don't log_removal old root in
3434 * insert_new_root, because that root buffer will be kept as a
3435 * normal node. We are going to log removal of half of the
3436 * elements below with tree_mod_log_eb_copy. We're holding a
3437 * tree lock on the buffer, which is why we cannot race with
3438 * other tree_mod_log users.
3440 ret = insert_new_root(trans, root, path, level + 1);
3444 ret = push_nodes_for_insert(trans, root, path, level);
3445 c = path->nodes[level];
3446 if (!ret && btrfs_header_nritems(c) <
3447 BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3)
3453 c_nritems = btrfs_header_nritems(c);
3454 mid = (c_nritems + 1) / 2;
3455 btrfs_node_key(c, &disk_key, mid);
3457 split = alloc_tree_block_no_bg_flush(trans, root, 0, &disk_key, level,
3458 c->start, 0, BTRFS_NESTING_SPLIT);
3460 return PTR_ERR(split);
3462 root_add_used(root, fs_info->nodesize);
3463 ASSERT(btrfs_header_level(c) == level);
3465 ret = tree_mod_log_eb_copy(split, c, 0, mid, c_nritems - mid);
3467 btrfs_abort_transaction(trans, ret);
3470 copy_extent_buffer(split, c,
3471 btrfs_node_key_ptr_offset(0),
3472 btrfs_node_key_ptr_offset(mid),
3473 (c_nritems - mid) * sizeof(struct btrfs_key_ptr));
3474 btrfs_set_header_nritems(split, c_nritems - mid);
3475 btrfs_set_header_nritems(c, mid);
3477 btrfs_mark_buffer_dirty(c);
3478 btrfs_mark_buffer_dirty(split);
3480 insert_ptr(trans, path, &disk_key, split->start,
3481 path->slots[level + 1] + 1, level + 1);
3483 if (path->slots[level] >= mid) {
3484 path->slots[level] -= mid;
3485 btrfs_tree_unlock(c);
3486 free_extent_buffer(c);
3487 path->nodes[level] = split;
3488 path->slots[level + 1] += 1;
3490 btrfs_tree_unlock(split);
3491 free_extent_buffer(split);
3497 * how many bytes are required to store the items in a leaf. start
3498 * and nr indicate which items in the leaf to check. This totals up the
3499 * space used both by the item structs and the item data
3501 static int leaf_space_used(struct extent_buffer *l, int start, int nr)
3503 struct btrfs_item *start_item;
3504 struct btrfs_item *end_item;
3506 int nritems = btrfs_header_nritems(l);
3507 int end = min(nritems, start + nr) - 1;
3511 start_item = btrfs_item_nr(start);
3512 end_item = btrfs_item_nr(end);
3513 data_len = btrfs_item_offset(l, start_item) +
3514 btrfs_item_size(l, start_item);
3515 data_len = data_len - btrfs_item_offset(l, end_item);
3516 data_len += sizeof(struct btrfs_item) * nr;
3517 WARN_ON(data_len < 0);
3522 * The space between the end of the leaf items and
3523 * the start of the leaf data. IOW, how much room
3524 * the leaf has left for both items and data
3526 noinline int btrfs_leaf_free_space(struct extent_buffer *leaf)
3528 struct btrfs_fs_info *fs_info = leaf->fs_info;
3529 int nritems = btrfs_header_nritems(leaf);
3532 ret = BTRFS_LEAF_DATA_SIZE(fs_info) - leaf_space_used(leaf, 0, nritems);
3535 "leaf free space ret %d, leaf data size %lu, used %d nritems %d",
3537 (unsigned long) BTRFS_LEAF_DATA_SIZE(fs_info),
3538 leaf_space_used(leaf, 0, nritems), nritems);
3544 * min slot controls the lowest index we're willing to push to the
3545 * right. We'll push up to and including min_slot, but no lower
3547 static noinline int __push_leaf_right(struct btrfs_path *path,
3548 int data_size, int empty,
3549 struct extent_buffer *right,
3550 int free_space, u32 left_nritems,
3553 struct btrfs_fs_info *fs_info = right->fs_info;
3554 struct extent_buffer *left = path->nodes[0];
3555 struct extent_buffer *upper = path->nodes[1];
3556 struct btrfs_map_token token;
3557 struct btrfs_disk_key disk_key;
3562 struct btrfs_item *item;
3571 nr = max_t(u32, 1, min_slot);
3573 if (path->slots[0] >= left_nritems)
3574 push_space += data_size;
3576 slot = path->slots[1];
3577 i = left_nritems - 1;
3579 item = btrfs_item_nr(i);
3581 if (!empty && push_items > 0) {
3582 if (path->slots[0] > i)
3584 if (path->slots[0] == i) {
3585 int space = btrfs_leaf_free_space(left);
3587 if (space + push_space * 2 > free_space)
3592 if (path->slots[0] == i)
3593 push_space += data_size;
3595 this_item_size = btrfs_item_size(left, item);
3596 if (this_item_size + sizeof(*item) + push_space > free_space)
3600 push_space += this_item_size + sizeof(*item);
3606 if (push_items == 0)
3609 WARN_ON(!empty && push_items == left_nritems);
3611 /* push left to right */
3612 right_nritems = btrfs_header_nritems(right);
3614 push_space = btrfs_item_end_nr(left, left_nritems - push_items);
3615 push_space -= leaf_data_end(left);
3617 /* make room in the right data area */
3618 data_end = leaf_data_end(right);
3619 memmove_extent_buffer(right,
3620 BTRFS_LEAF_DATA_OFFSET + data_end - push_space,
3621 BTRFS_LEAF_DATA_OFFSET + data_end,
3622 BTRFS_LEAF_DATA_SIZE(fs_info) - data_end);
3624 /* copy from the left data area */
3625 copy_extent_buffer(right, left, BTRFS_LEAF_DATA_OFFSET +
3626 BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
3627 BTRFS_LEAF_DATA_OFFSET + leaf_data_end(left),
3630 memmove_extent_buffer(right, btrfs_item_nr_offset(push_items),
3631 btrfs_item_nr_offset(0),
3632 right_nritems * sizeof(struct btrfs_item));
3634 /* copy the items from left to right */
3635 copy_extent_buffer(right, left, btrfs_item_nr_offset(0),
3636 btrfs_item_nr_offset(left_nritems - push_items),
3637 push_items * sizeof(struct btrfs_item));
3639 /* update the item pointers */
3640 btrfs_init_map_token(&token, right);
3641 right_nritems += push_items;
3642 btrfs_set_header_nritems(right, right_nritems);
3643 push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
3644 for (i = 0; i < right_nritems; i++) {
3645 item = btrfs_item_nr(i);
3646 push_space -= btrfs_token_item_size(&token, item);
3647 btrfs_set_token_item_offset(&token, item, push_space);
3650 left_nritems -= push_items;
3651 btrfs_set_header_nritems(left, left_nritems);
3654 btrfs_mark_buffer_dirty(left);
3656 btrfs_clean_tree_block(left);
3658 btrfs_mark_buffer_dirty(right);
3660 btrfs_item_key(right, &disk_key, 0);
3661 btrfs_set_node_key(upper, &disk_key, slot + 1);
3662 btrfs_mark_buffer_dirty(upper);
3664 /* then fixup the leaf pointer in the path */
3665 if (path->slots[0] >= left_nritems) {
3666 path->slots[0] -= left_nritems;
3667 if (btrfs_header_nritems(path->nodes[0]) == 0)
3668 btrfs_clean_tree_block(path->nodes[0]);
3669 btrfs_tree_unlock(path->nodes[0]);
3670 free_extent_buffer(path->nodes[0]);
3671 path->nodes[0] = right;
3672 path->slots[1] += 1;
3674 btrfs_tree_unlock(right);
3675 free_extent_buffer(right);
3680 btrfs_tree_unlock(right);
3681 free_extent_buffer(right);
3686 * push some data in the path leaf to the right, trying to free up at
3687 * least data_size bytes. returns zero if the push worked, nonzero otherwise
3689 * returns 1 if the push failed because the other node didn't have enough
3690 * room, 0 if everything worked out and < 0 if there were major errors.
3692 * this will push starting from min_slot to the end of the leaf. It won't
3693 * push any slot lower than min_slot
3695 static int push_leaf_right(struct btrfs_trans_handle *trans, struct btrfs_root
3696 *root, struct btrfs_path *path,
3697 int min_data_size, int data_size,
3698 int empty, u32 min_slot)
3700 struct extent_buffer *left = path->nodes[0];
3701 struct extent_buffer *right;
3702 struct extent_buffer *upper;
3708 if (!path->nodes[1])
3711 slot = path->slots[1];
3712 upper = path->nodes[1];
3713 if (slot >= btrfs_header_nritems(upper) - 1)
3716 btrfs_assert_tree_locked(path->nodes[1]);
3718 right = btrfs_read_node_slot(upper, slot + 1);
3720 * slot + 1 is not valid or we fail to read the right node,
3721 * no big deal, just return.
3726 __btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
3728 free_space = btrfs_leaf_free_space(right);
3729 if (free_space < data_size)
3732 /* cow and double check */
3733 ret = btrfs_cow_block(trans, root, right, upper,
3734 slot + 1, &right, BTRFS_NESTING_RIGHT_COW);
3738 free_space = btrfs_leaf_free_space(right);
3739 if (free_space < data_size)
3742 left_nritems = btrfs_header_nritems(left);
3743 if (left_nritems == 0)
3746 if (check_sibling_keys(left, right)) {
3748 btrfs_tree_unlock(right);
3749 free_extent_buffer(right);
3752 if (path->slots[0] == left_nritems && !empty) {
3753 /* Key greater than all keys in the leaf, right neighbor has
3754 * enough room for it and we're not emptying our leaf to delete
3755 * it, therefore use right neighbor to insert the new item and
3756 * no need to touch/dirty our left leaf. */
3757 btrfs_tree_unlock(left);
3758 free_extent_buffer(left);
3759 path->nodes[0] = right;
3765 return __push_leaf_right(path, min_data_size, empty,
3766 right, free_space, left_nritems, min_slot);
3768 btrfs_tree_unlock(right);
3769 free_extent_buffer(right);
3774 * push some data in the path leaf to the left, trying to free up at
3775 * least data_size bytes. returns zero if the push worked, nonzero otherwise
3777 * max_slot can put a limit on how far into the leaf we'll push items. The
3778 * item at 'max_slot' won't be touched. Use (u32)-1 to make us do all the
3781 static noinline int __push_leaf_left(struct btrfs_path *path, int data_size,
3782 int empty, struct extent_buffer *left,
3783 int free_space, u32 right_nritems,
3786 struct btrfs_fs_info *fs_info = left->fs_info;
3787 struct btrfs_disk_key disk_key;
3788 struct extent_buffer *right = path->nodes[0];
3792 struct btrfs_item *item;
3793 u32 old_left_nritems;
3797 u32 old_left_item_size;
3798 struct btrfs_map_token token;
3801 nr = min(right_nritems, max_slot);
3803 nr = min(right_nritems - 1, max_slot);
3805 for (i = 0; i < nr; i++) {
3806 item = btrfs_item_nr(i);
3808 if (!empty && push_items > 0) {
3809 if (path->slots[0] < i)
3811 if (path->slots[0] == i) {
3812 int space = btrfs_leaf_free_space(right);
3814 if (space + push_space * 2 > free_space)
3819 if (path->slots[0] == i)
3820 push_space += data_size;
3822 this_item_size = btrfs_item_size(right, item);
3823 if (this_item_size + sizeof(*item) + push_space > free_space)
3827 push_space += this_item_size + sizeof(*item);
3830 if (push_items == 0) {
3834 WARN_ON(!empty && push_items == btrfs_header_nritems(right));
3836 /* push data from right to left */
3837 copy_extent_buffer(left, right,
3838 btrfs_item_nr_offset(btrfs_header_nritems(left)),
3839 btrfs_item_nr_offset(0),
3840 push_items * sizeof(struct btrfs_item));
3842 push_space = BTRFS_LEAF_DATA_SIZE(fs_info) -
3843 btrfs_item_offset_nr(right, push_items - 1);
3845 copy_extent_buffer(left, right, BTRFS_LEAF_DATA_OFFSET +
3846 leaf_data_end(left) - push_space,
3847 BTRFS_LEAF_DATA_OFFSET +
3848 btrfs_item_offset_nr(right, push_items - 1),
3850 old_left_nritems = btrfs_header_nritems(left);
3851 BUG_ON(old_left_nritems <= 0);
3853 btrfs_init_map_token(&token, left);
3854 old_left_item_size = btrfs_item_offset_nr(left, old_left_nritems - 1);
3855 for (i = old_left_nritems; i < old_left_nritems + push_items; i++) {
3858 item = btrfs_item_nr(i);
3860 ioff = btrfs_token_item_offset(&token, item);
3861 btrfs_set_token_item_offset(&token, item,
3862 ioff - (BTRFS_LEAF_DATA_SIZE(fs_info) - old_left_item_size));
3864 btrfs_set_header_nritems(left, old_left_nritems + push_items);
3866 /* fixup right node */
3867 if (push_items > right_nritems)
3868 WARN(1, KERN_CRIT "push items %d nr %u\n", push_items,
3871 if (push_items < right_nritems) {
3872 push_space = btrfs_item_offset_nr(right, push_items - 1) -
3873 leaf_data_end(right);
3874 memmove_extent_buffer(right, BTRFS_LEAF_DATA_OFFSET +
3875 BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
3876 BTRFS_LEAF_DATA_OFFSET +
3877 leaf_data_end(right), push_space);
3879 memmove_extent_buffer(right, btrfs_item_nr_offset(0),
3880 btrfs_item_nr_offset(push_items),
3881 (btrfs_header_nritems(right) - push_items) *
3882 sizeof(struct btrfs_item));
3885 btrfs_init_map_token(&token, right);
3886 right_nritems -= push_items;
3887 btrfs_set_header_nritems(right, right_nritems);
3888 push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
3889 for (i = 0; i < right_nritems; i++) {
3890 item = btrfs_item_nr(i);
3892 push_space = push_space - btrfs_token_item_size(&token, item);
3893 btrfs_set_token_item_offset(&token, item, push_space);
3896 btrfs_mark_buffer_dirty(left);
3898 btrfs_mark_buffer_dirty(right);
3900 btrfs_clean_tree_block(right);
3902 btrfs_item_key(right, &disk_key, 0);
3903 fixup_low_keys(path, &disk_key, 1);
3905 /* then fixup the leaf pointer in the path */
3906 if (path->slots[0] < push_items) {
3907 path->slots[0] += old_left_nritems;
3908 btrfs_tree_unlock(path->nodes[0]);
3909 free_extent_buffer(path->nodes[0]);
3910 path->nodes[0] = left;
3911 path->slots[1] -= 1;
3913 btrfs_tree_unlock(left);
3914 free_extent_buffer(left);
3915 path->slots[0] -= push_items;
3917 BUG_ON(path->slots[0] < 0);
3920 btrfs_tree_unlock(left);
3921 free_extent_buffer(left);
3926 * push some data in the path leaf to the left, trying to free up at
3927 * least data_size bytes. returns zero if the push worked, nonzero otherwise
3929 * max_slot can put a limit on how far into the leaf we'll push items. The
3930 * item at 'max_slot' won't be touched. Use (u32)-1 to make us push all the
3933 static int push_leaf_left(struct btrfs_trans_handle *trans, struct btrfs_root
3934 *root, struct btrfs_path *path, int min_data_size,
3935 int data_size, int empty, u32 max_slot)
3937 struct extent_buffer *right = path->nodes[0];
3938 struct extent_buffer *left;
3944 slot = path->slots[1];
3947 if (!path->nodes[1])
3950 right_nritems = btrfs_header_nritems(right);
3951 if (right_nritems == 0)
3954 btrfs_assert_tree_locked(path->nodes[1]);
3956 left = btrfs_read_node_slot(path->nodes[1], slot - 1);
3958 * slot - 1 is not valid or we fail to read the left node,
3959 * no big deal, just return.
3964 __btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
3966 free_space = btrfs_leaf_free_space(left);
3967 if (free_space < data_size) {
3972 /* cow and double check */
3973 ret = btrfs_cow_block(trans, root, left,
3974 path->nodes[1], slot - 1, &left,
3975 BTRFS_NESTING_LEFT_COW);
3977 /* we hit -ENOSPC, but it isn't fatal here */
3983 free_space = btrfs_leaf_free_space(left);
3984 if (free_space < data_size) {
3989 if (check_sibling_keys(left, right)) {
3993 return __push_leaf_left(path, min_data_size,
3994 empty, left, free_space, right_nritems,
3997 btrfs_tree_unlock(left);
3998 free_extent_buffer(left);
4003 * split the path's leaf in two, making sure there is at least data_size
4004 * available for the resulting leaf level of the path.
4006 static noinline void copy_for_split(struct btrfs_trans_handle *trans,
4007 struct btrfs_path *path,
4008 struct extent_buffer *l,
4009 struct extent_buffer *right,
4010 int slot, int mid, int nritems)
4012 struct btrfs_fs_info *fs_info = trans->fs_info;
4016 struct btrfs_disk_key disk_key;
4017 struct btrfs_map_token token;
4019 nritems = nritems - mid;
4020 btrfs_set_header_nritems(right, nritems);
4021 data_copy_size = btrfs_item_end_nr(l, mid) - leaf_data_end(l);
4023 copy_extent_buffer(right, l, btrfs_item_nr_offset(0),
4024 btrfs_item_nr_offset(mid),
4025 nritems * sizeof(struct btrfs_item));
4027 copy_extent_buffer(right, l,
4028 BTRFS_LEAF_DATA_OFFSET + BTRFS_LEAF_DATA_SIZE(fs_info) -
4029 data_copy_size, BTRFS_LEAF_DATA_OFFSET +
4030 leaf_data_end(l), data_copy_size);
4032 rt_data_off = BTRFS_LEAF_DATA_SIZE(fs_info) - btrfs_item_end_nr(l, mid);
4034 btrfs_init_map_token(&token, right);
4035 for (i = 0; i < nritems; i++) {
4036 struct btrfs_item *item = btrfs_item_nr(i);
4039 ioff = btrfs_token_item_offset(&token, item);
4040 btrfs_set_token_item_offset(&token, item, ioff + rt_data_off);
4043 btrfs_set_header_nritems(l, mid);
4044 btrfs_item_key(right, &disk_key, 0);
4045 insert_ptr(trans, path, &disk_key, right->start, path->slots[1] + 1, 1);
4047 btrfs_mark_buffer_dirty(right);
4048 btrfs_mark_buffer_dirty(l);
4049 BUG_ON(path->slots[0] != slot);
4052 btrfs_tree_unlock(path->nodes[0]);
4053 free_extent_buffer(path->nodes[0]);
4054 path->nodes[0] = right;
4055 path->slots[0] -= mid;
4056 path->slots[1] += 1;
4058 btrfs_tree_unlock(right);
4059 free_extent_buffer(right);
4062 BUG_ON(path->slots[0] < 0);
4066 * double splits happen when we need to insert a big item in the middle
4067 * of a leaf. A double split can leave us with 3 mostly empty leaves:
4068 * leaf: [ slots 0 - N] [ our target ] [ N + 1 - total in leaf ]
4071 * We avoid this by trying to push the items on either side of our target
4072 * into the adjacent leaves. If all goes well we can avoid the double split
4075 static noinline int push_for_double_split(struct btrfs_trans_handle *trans,
4076 struct btrfs_root *root,
4077 struct btrfs_path *path,
4084 int space_needed = data_size;
4086 slot = path->slots[0];
4087 if (slot < btrfs_header_nritems(path->nodes[0]))
4088 space_needed -= btrfs_leaf_free_space(path->nodes[0]);
4091 * try to push all the items after our slot into the
4094 ret = push_leaf_right(trans, root, path, 1, space_needed, 0, slot);
4101 nritems = btrfs_header_nritems(path->nodes[0]);
4103 * our goal is to get our slot at the start or end of a leaf. If
4104 * we've done so we're done
4106 if (path->slots[0] == 0 || path->slots[0] == nritems)
4109 if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
4112 /* try to push all the items before our slot into the next leaf */
4113 slot = path->slots[0];
4114 space_needed = data_size;
4116 space_needed -= btrfs_leaf_free_space(path->nodes[0]);
4117 ret = push_leaf_left(trans, root, path, 1, space_needed, 0, slot);
4130 * split the path's leaf in two, making sure there is at least data_size
4131 * available for the resulting leaf level of the path.
4133 * returns 0 if all went well and < 0 on failure.
4135 static noinline int split_leaf(struct btrfs_trans_handle *trans,
4136 struct btrfs_root *root,
4137 const struct btrfs_key *ins_key,
4138 struct btrfs_path *path, int data_size,
4141 struct btrfs_disk_key disk_key;
4142 struct extent_buffer *l;
4146 struct extent_buffer *right;
4147 struct btrfs_fs_info *fs_info = root->fs_info;
4151 int num_doubles = 0;
4152 int tried_avoid_double = 0;
4155 slot = path->slots[0];
4156 if (extend && data_size + btrfs_item_size_nr(l, slot) +
4157 sizeof(struct btrfs_item) > BTRFS_LEAF_DATA_SIZE(fs_info))
4160 /* first try to make some room by pushing left and right */
4161 if (data_size && path->nodes[1]) {
4162 int space_needed = data_size;
4164 if (slot < btrfs_header_nritems(l))
4165 space_needed -= btrfs_leaf_free_space(l);
4167 wret = push_leaf_right(trans, root, path, space_needed,
4168 space_needed, 0, 0);
4172 space_needed = data_size;
4174 space_needed -= btrfs_leaf_free_space(l);
4175 wret = push_leaf_left(trans, root, path, space_needed,
4176 space_needed, 0, (u32)-1);
4182 /* did the pushes work? */
4183 if (btrfs_leaf_free_space(l) >= data_size)
4187 if (!path->nodes[1]) {
4188 ret = insert_new_root(trans, root, path, 1);
4195 slot = path->slots[0];
4196 nritems = btrfs_header_nritems(l);
4197 mid = (nritems + 1) / 2;
4201 leaf_space_used(l, mid, nritems - mid) + data_size >
4202 BTRFS_LEAF_DATA_SIZE(fs_info)) {
4203 if (slot >= nritems) {
4207 if (mid != nritems &&
4208 leaf_space_used(l, mid, nritems - mid) +
4209 data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
4210 if (data_size && !tried_avoid_double)
4211 goto push_for_double;
4217 if (leaf_space_used(l, 0, mid) + data_size >
4218 BTRFS_LEAF_DATA_SIZE(fs_info)) {
4219 if (!extend && data_size && slot == 0) {
4221 } else if ((extend || !data_size) && slot == 0) {
4225 if (mid != nritems &&
4226 leaf_space_used(l, mid, nritems - mid) +
4227 data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
4228 if (data_size && !tried_avoid_double)
4229 goto push_for_double;
4237 btrfs_cpu_key_to_disk(&disk_key, ins_key);
4239 btrfs_item_key(l, &disk_key, mid);
4242 * We have to about BTRFS_NESTING_NEW_ROOT here if we've done a double
4243 * split, because we're only allowed to have MAX_LOCKDEP_SUBCLASSES
4244 * subclasses, which is 8 at the time of this patch, and we've maxed it
4245 * out. In the future we could add a
4246 * BTRFS_NESTING_SPLIT_THE_SPLITTENING if we need to, but for now just
4247 * use BTRFS_NESTING_NEW_ROOT.
4249 right = alloc_tree_block_no_bg_flush(trans, root, 0, &disk_key, 0,
4250 l->start, 0, num_doubles ?
4251 BTRFS_NESTING_NEW_ROOT :
4252 BTRFS_NESTING_SPLIT);
4254 return PTR_ERR(right);
4256 root_add_used(root, fs_info->nodesize);
4260 btrfs_set_header_nritems(right, 0);
4261 insert_ptr(trans, path, &disk_key,
4262 right->start, path->slots[1] + 1, 1);
4263 btrfs_tree_unlock(path->nodes[0]);
4264 free_extent_buffer(path->nodes[0]);
4265 path->nodes[0] = right;
4267 path->slots[1] += 1;
4269 btrfs_set_header_nritems(right, 0);
4270 insert_ptr(trans, path, &disk_key,
4271 right->start, path->slots[1], 1);
4272 btrfs_tree_unlock(path->nodes[0]);
4273 free_extent_buffer(path->nodes[0]);
4274 path->nodes[0] = right;
4276 if (path->slots[1] == 0)
4277 fixup_low_keys(path, &disk_key, 1);
4280 * We create a new leaf 'right' for the required ins_len and
4281 * we'll do btrfs_mark_buffer_dirty() on this leaf after copying
4282 * the content of ins_len to 'right'.
4287 copy_for_split(trans, path, l, right, slot, mid, nritems);
4290 BUG_ON(num_doubles != 0);
4298 push_for_double_split(trans, root, path, data_size);
4299 tried_avoid_double = 1;
4300 if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
4305 static noinline int setup_leaf_for_split(struct btrfs_trans_handle *trans,
4306 struct btrfs_root *root,
4307 struct btrfs_path *path, int ins_len)
4309 struct btrfs_key key;
4310 struct extent_buffer *leaf;
4311 struct btrfs_file_extent_item *fi;
4316 leaf = path->nodes[0];
4317 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4319 BUG_ON(key.type != BTRFS_EXTENT_DATA_KEY &&
4320 key.type != BTRFS_EXTENT_CSUM_KEY);
4322 if (btrfs_leaf_free_space(leaf) >= ins_len)
4325 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
4326 if (key.type == BTRFS_EXTENT_DATA_KEY) {
4327 fi = btrfs_item_ptr(leaf, path->slots[0],
4328 struct btrfs_file_extent_item);
4329 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
4331 btrfs_release_path(path);
4333 path->keep_locks = 1;
4334 path->search_for_split = 1;
4335 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
4336 path->search_for_split = 0;
4343 leaf = path->nodes[0];
4344 /* if our item isn't there, return now */
4345 if (item_size != btrfs_item_size_nr(leaf, path->slots[0]))
4348 /* the leaf has changed, it now has room. return now */
4349 if (btrfs_leaf_free_space(path->nodes[0]) >= ins_len)
4352 if (key.type == BTRFS_EXTENT_DATA_KEY) {
4353 fi = btrfs_item_ptr(leaf, path->slots[0],
4354 struct btrfs_file_extent_item);
4355 if (extent_len != btrfs_file_extent_num_bytes(leaf, fi))
4359 ret = split_leaf(trans, root, &key, path, ins_len, 1);
4363 path->keep_locks = 0;
4364 btrfs_unlock_up_safe(path, 1);
4367 path->keep_locks = 0;
4371 static noinline int split_item(struct btrfs_path *path,
4372 const struct btrfs_key *new_key,
4373 unsigned long split_offset)
4375 struct extent_buffer *leaf;
4376 struct btrfs_item *item;
4377 struct btrfs_item *new_item;
4383 struct btrfs_disk_key disk_key;
4385 leaf = path->nodes[0];
4386 BUG_ON(btrfs_leaf_free_space(leaf) < sizeof(struct btrfs_item));
4388 item = btrfs_item_nr(path->slots[0]);
4389 orig_offset = btrfs_item_offset(leaf, item);
4390 item_size = btrfs_item_size(leaf, item);
4392 buf = kmalloc(item_size, GFP_NOFS);
4396 read_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf,
4397 path->slots[0]), item_size);
4399 slot = path->slots[0] + 1;
4400 nritems = btrfs_header_nritems(leaf);
4401 if (slot != nritems) {
4402 /* shift the items */
4403 memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + 1),
4404 btrfs_item_nr_offset(slot),
4405 (nritems - slot) * sizeof(struct btrfs_item));
4408 btrfs_cpu_key_to_disk(&disk_key, new_key);
4409 btrfs_set_item_key(leaf, &disk_key, slot);
4411 new_item = btrfs_item_nr(slot);
4413 btrfs_set_item_offset(leaf, new_item, orig_offset);
4414 btrfs_set_item_size(leaf, new_item, item_size - split_offset);
4416 btrfs_set_item_offset(leaf, item,
4417 orig_offset + item_size - split_offset);
4418 btrfs_set_item_size(leaf, item, split_offset);
4420 btrfs_set_header_nritems(leaf, nritems + 1);
4422 /* write the data for the start of the original item */
4423 write_extent_buffer(leaf, buf,
4424 btrfs_item_ptr_offset(leaf, path->slots[0]),
4427 /* write the data for the new item */
4428 write_extent_buffer(leaf, buf + split_offset,
4429 btrfs_item_ptr_offset(leaf, slot),
4430 item_size - split_offset);
4431 btrfs_mark_buffer_dirty(leaf);
4433 BUG_ON(btrfs_leaf_free_space(leaf) < 0);
4439 * This function splits a single item into two items,
4440 * giving 'new_key' to the new item and splitting the
4441 * old one at split_offset (from the start of the item).
4443 * The path may be released by this operation. After
4444 * the split, the path is pointing to the old item. The
4445 * new item is going to be in the same node as the old one.
4447 * Note, the item being split must be smaller enough to live alone on
4448 * a tree block with room for one extra struct btrfs_item
4450 * This allows us to split the item in place, keeping a lock on the
4451 * leaf the entire time.
4453 int btrfs_split_item(struct btrfs_trans_handle *trans,
4454 struct btrfs_root *root,
4455 struct btrfs_path *path,
4456 const struct btrfs_key *new_key,
4457 unsigned long split_offset)
4460 ret = setup_leaf_for_split(trans, root, path,
4461 sizeof(struct btrfs_item));
4465 ret = split_item(path, new_key, split_offset);
4470 * This function duplicate a item, giving 'new_key' to the new item.
4471 * It guarantees both items live in the same tree leaf and the new item
4472 * is contiguous with the original item.
4474 * This allows us to split file extent in place, keeping a lock on the
4475 * leaf the entire time.
4477 int btrfs_duplicate_item(struct btrfs_trans_handle *trans,
4478 struct btrfs_root *root,
4479 struct btrfs_path *path,
4480 const struct btrfs_key *new_key)
4482 struct extent_buffer *leaf;
4486 leaf = path->nodes[0];
4487 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
4488 ret = setup_leaf_for_split(trans, root, path,
4489 item_size + sizeof(struct btrfs_item));
4494 setup_items_for_insert(root, path, new_key, &item_size, 1);
4495 leaf = path->nodes[0];
4496 memcpy_extent_buffer(leaf,
4497 btrfs_item_ptr_offset(leaf, path->slots[0]),
4498 btrfs_item_ptr_offset(leaf, path->slots[0] - 1),
4504 * make the item pointed to by the path smaller. new_size indicates
4505 * how small to make it, and from_end tells us if we just chop bytes
4506 * off the end of the item or if we shift the item to chop bytes off
4509 void btrfs_truncate_item(struct btrfs_path *path, u32 new_size, int from_end)
4512 struct extent_buffer *leaf;
4513 struct btrfs_item *item;
4515 unsigned int data_end;
4516 unsigned int old_data_start;
4517 unsigned int old_size;
4518 unsigned int size_diff;
4520 struct btrfs_map_token token;
4522 leaf = path->nodes[0];
4523 slot = path->slots[0];
4525 old_size = btrfs_item_size_nr(leaf, slot);
4526 if (old_size == new_size)
4529 nritems = btrfs_header_nritems(leaf);
4530 data_end = leaf_data_end(leaf);
4532 old_data_start = btrfs_item_offset_nr(leaf, slot);
4534 size_diff = old_size - new_size;
4537 BUG_ON(slot >= nritems);
4540 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4542 /* first correct the data pointers */
4543 btrfs_init_map_token(&token, leaf);
4544 for (i = slot; i < nritems; i++) {
4546 item = btrfs_item_nr(i);
4548 ioff = btrfs_token_item_offset(&token, item);
4549 btrfs_set_token_item_offset(&token, item, ioff + size_diff);
4552 /* shift the data */
4554 memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
4555 data_end + size_diff, BTRFS_LEAF_DATA_OFFSET +
4556 data_end, old_data_start + new_size - data_end);
4558 struct btrfs_disk_key disk_key;
4561 btrfs_item_key(leaf, &disk_key, slot);
4563 if (btrfs_disk_key_type(&disk_key) == BTRFS_EXTENT_DATA_KEY) {
4565 struct btrfs_file_extent_item *fi;
4567 fi = btrfs_item_ptr(leaf, slot,
4568 struct btrfs_file_extent_item);
4569 fi = (struct btrfs_file_extent_item *)(
4570 (unsigned long)fi - size_diff);
4572 if (btrfs_file_extent_type(leaf, fi) ==
4573 BTRFS_FILE_EXTENT_INLINE) {
4574 ptr = btrfs_item_ptr_offset(leaf, slot);
4575 memmove_extent_buffer(leaf, ptr,
4577 BTRFS_FILE_EXTENT_INLINE_DATA_START);
4581 memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
4582 data_end + size_diff, BTRFS_LEAF_DATA_OFFSET +
4583 data_end, old_data_start - data_end);
4585 offset = btrfs_disk_key_offset(&disk_key);
4586 btrfs_set_disk_key_offset(&disk_key, offset + size_diff);
4587 btrfs_set_item_key(leaf, &disk_key, slot);
4589 fixup_low_keys(path, &disk_key, 1);
4592 item = btrfs_item_nr(slot);
4593 btrfs_set_item_size(leaf, item, new_size);
4594 btrfs_mark_buffer_dirty(leaf);
4596 if (btrfs_leaf_free_space(leaf) < 0) {
4597 btrfs_print_leaf(leaf);
4603 * make the item pointed to by the path bigger, data_size is the added size.
4605 void btrfs_extend_item(struct btrfs_path *path, u32 data_size)
4608 struct extent_buffer *leaf;
4609 struct btrfs_item *item;
4611 unsigned int data_end;
4612 unsigned int old_data;
4613 unsigned int old_size;
4615 struct btrfs_map_token token;
4617 leaf = path->nodes[0];
4619 nritems = btrfs_header_nritems(leaf);
4620 data_end = leaf_data_end(leaf);
4622 if (btrfs_leaf_free_space(leaf) < data_size) {
4623 btrfs_print_leaf(leaf);
4626 slot = path->slots[0];
4627 old_data = btrfs_item_end_nr(leaf, slot);
4630 if (slot >= nritems) {
4631 btrfs_print_leaf(leaf);
4632 btrfs_crit(leaf->fs_info, "slot %d too large, nritems %d",
4638 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4640 /* first correct the data pointers */
4641 btrfs_init_map_token(&token, leaf);
4642 for (i = slot; i < nritems; i++) {
4644 item = btrfs_item_nr(i);
4646 ioff = btrfs_token_item_offset(&token, item);
4647 btrfs_set_token_item_offset(&token, item, ioff - data_size);
4650 /* shift the data */
4651 memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
4652 data_end - data_size, BTRFS_LEAF_DATA_OFFSET +
4653 data_end, old_data - data_end);
4655 data_end = old_data;
4656 old_size = btrfs_item_size_nr(leaf, slot);
4657 item = btrfs_item_nr(slot);
4658 btrfs_set_item_size(leaf, item, old_size + data_size);
4659 btrfs_mark_buffer_dirty(leaf);
4661 if (btrfs_leaf_free_space(leaf) < 0) {
4662 btrfs_print_leaf(leaf);
4668 * setup_items_for_insert - Helper called before inserting one or more items
4669 * to a leaf. Main purpose is to save stack depth by doing the bulk of the work
4670 * in a function that doesn't call btrfs_search_slot
4672 * @root: root we are inserting items to
4673 * @path: points to the leaf/slot where we are going to insert new items
4674 * @cpu_key: array of keys for items to be inserted
4675 * @data_size: size of the body of each item we are going to insert
4676 * @nr: size of @cpu_key/@data_size arrays
4678 void setup_items_for_insert(struct btrfs_root *root, struct btrfs_path *path,
4679 const struct btrfs_key *cpu_key, u32 *data_size,
4682 struct btrfs_fs_info *fs_info = root->fs_info;
4683 struct btrfs_item *item;
4686 unsigned int data_end;
4687 struct btrfs_disk_key disk_key;
4688 struct extent_buffer *leaf;
4690 struct btrfs_map_token token;
4694 for (i = 0; i < nr; i++)
4695 total_data += data_size[i];
4696 total_size = total_data + (nr * sizeof(struct btrfs_item));
4698 if (path->slots[0] == 0) {
4699 btrfs_cpu_key_to_disk(&disk_key, cpu_key);
4700 fixup_low_keys(path, &disk_key, 1);
4702 btrfs_unlock_up_safe(path, 1);
4704 leaf = path->nodes[0];
4705 slot = path->slots[0];
4707 nritems = btrfs_header_nritems(leaf);
4708 data_end = leaf_data_end(leaf);
4710 if (btrfs_leaf_free_space(leaf) < total_size) {
4711 btrfs_print_leaf(leaf);
4712 btrfs_crit(fs_info, "not enough freespace need %u have %d",
4713 total_size, btrfs_leaf_free_space(leaf));
4717 btrfs_init_map_token(&token, leaf);
4718 if (slot != nritems) {
4719 unsigned int old_data = btrfs_item_end_nr(leaf, slot);
4721 if (old_data < data_end) {
4722 btrfs_print_leaf(leaf);
4724 "item at slot %d with data offset %u beyond data end of leaf %u",
4725 slot, old_data, data_end);
4729 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4731 /* first correct the data pointers */
4732 for (i = slot; i < nritems; i++) {
4735 item = btrfs_item_nr(i);
4736 ioff = btrfs_token_item_offset(&token, item);
4737 btrfs_set_token_item_offset(&token, item,
4740 /* shift the items */
4741 memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + nr),
4742 btrfs_item_nr_offset(slot),
4743 (nritems - slot) * sizeof(struct btrfs_item));
4745 /* shift the data */
4746 memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
4747 data_end - total_data, BTRFS_LEAF_DATA_OFFSET +
4748 data_end, old_data - data_end);
4749 data_end = old_data;
4752 /* setup the item for the new data */
4753 for (i = 0; i < nr; i++) {
4754 btrfs_cpu_key_to_disk(&disk_key, cpu_key + i);
4755 btrfs_set_item_key(leaf, &disk_key, slot + i);
4756 item = btrfs_item_nr(slot + i);
4757 data_end -= data_size[i];
4758 btrfs_set_token_item_offset(&token, item, data_end);
4759 btrfs_set_token_item_size(&token, item, data_size[i]);
4762 btrfs_set_header_nritems(leaf, nritems + nr);
4763 btrfs_mark_buffer_dirty(leaf);
4765 if (btrfs_leaf_free_space(leaf) < 0) {
4766 btrfs_print_leaf(leaf);
4772 * Given a key and some data, insert items into the tree.
4773 * This does all the path init required, making room in the tree if needed.
4775 int btrfs_insert_empty_items(struct btrfs_trans_handle *trans,
4776 struct btrfs_root *root,
4777 struct btrfs_path *path,
4778 const struct btrfs_key *cpu_key, u32 *data_size,
4787 for (i = 0; i < nr; i++)
4788 total_data += data_size[i];
4790 total_size = total_data + (nr * sizeof(struct btrfs_item));
4791 ret = btrfs_search_slot(trans, root, cpu_key, path, total_size, 1);
4797 slot = path->slots[0];
4800 setup_items_for_insert(root, path, cpu_key, data_size, nr);
4805 * Given a key and some data, insert an item into the tree.
4806 * This does all the path init required, making room in the tree if needed.
4808 int btrfs_insert_item(struct btrfs_trans_handle *trans, struct btrfs_root *root,
4809 const struct btrfs_key *cpu_key, void *data,
4813 struct btrfs_path *path;
4814 struct extent_buffer *leaf;
4817 path = btrfs_alloc_path();
4820 ret = btrfs_insert_empty_item(trans, root, path, cpu_key, data_size);
4822 leaf = path->nodes[0];
4823 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
4824 write_extent_buffer(leaf, data, ptr, data_size);
4825 btrfs_mark_buffer_dirty(leaf);
4827 btrfs_free_path(path);
4832 * delete the pointer from a given node.
4834 * the tree should have been previously balanced so the deletion does not
4837 static void del_ptr(struct btrfs_root *root, struct btrfs_path *path,
4838 int level, int slot)
4840 struct extent_buffer *parent = path->nodes[level];
4844 nritems = btrfs_header_nritems(parent);
4845 if (slot != nritems - 1) {
4847 ret = tree_mod_log_insert_move(parent, slot, slot + 1,
4848 nritems - slot - 1);
4851 memmove_extent_buffer(parent,
4852 btrfs_node_key_ptr_offset(slot),
4853 btrfs_node_key_ptr_offset(slot + 1),
4854 sizeof(struct btrfs_key_ptr) *
4855 (nritems - slot - 1));
4857 ret = tree_mod_log_insert_key(parent, slot, MOD_LOG_KEY_REMOVE,
4863 btrfs_set_header_nritems(parent, nritems);
4864 if (nritems == 0 && parent == root->node) {
4865 BUG_ON(btrfs_header_level(root->node) != 1);
4866 /* just turn the root into a leaf and break */
4867 btrfs_set_header_level(root->node, 0);
4868 } else if (slot == 0) {
4869 struct btrfs_disk_key disk_key;
4871 btrfs_node_key(parent, &disk_key, 0);
4872 fixup_low_keys(path, &disk_key, level + 1);
4874 btrfs_mark_buffer_dirty(parent);
4878 * a helper function to delete the leaf pointed to by path->slots[1] and
4881 * This deletes the pointer in path->nodes[1] and frees the leaf
4882 * block extent. zero is returned if it all worked out, < 0 otherwise.
4884 * The path must have already been setup for deleting the leaf, including
4885 * all the proper balancing. path->nodes[1] must be locked.
4887 static noinline void btrfs_del_leaf(struct btrfs_trans_handle *trans,
4888 struct btrfs_root *root,
4889 struct btrfs_path *path,
4890 struct extent_buffer *leaf)
4892 WARN_ON(btrfs_header_generation(leaf) != trans->transid);
4893 del_ptr(root, path, 1, path->slots[1]);
4896 * btrfs_free_extent is expensive, we want to make sure we
4897 * aren't holding any locks when we call it
4899 btrfs_unlock_up_safe(path, 0);
4901 root_sub_used(root, leaf->len);
4903 atomic_inc(&leaf->refs);
4904 btrfs_free_tree_block(trans, root, leaf, 0, 1);
4905 free_extent_buffer_stale(leaf);
4908 * delete the item at the leaf level in path. If that empties
4909 * the leaf, remove it from the tree
4911 int btrfs_del_items(struct btrfs_trans_handle *trans, struct btrfs_root *root,
4912 struct btrfs_path *path, int slot, int nr)
4914 struct btrfs_fs_info *fs_info = root->fs_info;
4915 struct extent_buffer *leaf;
4916 struct btrfs_item *item;
4924 leaf = path->nodes[0];
4925 last_off = btrfs_item_offset_nr(leaf, slot + nr - 1);
4927 for (i = 0; i < nr; i++)
4928 dsize += btrfs_item_size_nr(leaf, slot + i);
4930 nritems = btrfs_header_nritems(leaf);
4932 if (slot + nr != nritems) {
4933 int data_end = leaf_data_end(leaf);
4934 struct btrfs_map_token token;
4936 memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
4938 BTRFS_LEAF_DATA_OFFSET + data_end,
4939 last_off - data_end);
4941 btrfs_init_map_token(&token, leaf);
4942 for (i = slot + nr; i < nritems; i++) {
4945 item = btrfs_item_nr(i);
4946 ioff = btrfs_token_item_offset(&token, item);
4947 btrfs_set_token_item_offset(&token, item, ioff + dsize);
4950 memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot),
4951 btrfs_item_nr_offset(slot + nr),
4952 sizeof(struct btrfs_item) *
4953 (nritems - slot - nr));
4955 btrfs_set_header_nritems(leaf, nritems - nr);
4958 /* delete the leaf if we've emptied it */
4960 if (leaf == root->node) {
4961 btrfs_set_header_level(leaf, 0);
4963 btrfs_clean_tree_block(leaf);
4964 btrfs_del_leaf(trans, root, path, leaf);
4967 int used = leaf_space_used(leaf, 0, nritems);
4969 struct btrfs_disk_key disk_key;
4971 btrfs_item_key(leaf, &disk_key, 0);
4972 fixup_low_keys(path, &disk_key, 1);
4975 /* delete the leaf if it is mostly empty */
4976 if (used < BTRFS_LEAF_DATA_SIZE(fs_info) / 3) {
4977 /* push_leaf_left fixes the path.
4978 * make sure the path still points to our leaf
4979 * for possible call to del_ptr below
4981 slot = path->slots[1];
4982 atomic_inc(&leaf->refs);
4984 wret = push_leaf_left(trans, root, path, 1, 1,
4986 if (wret < 0 && wret != -ENOSPC)
4989 if (path->nodes[0] == leaf &&
4990 btrfs_header_nritems(leaf)) {
4991 wret = push_leaf_right(trans, root, path, 1,
4993 if (wret < 0 && wret != -ENOSPC)
4997 if (btrfs_header_nritems(leaf) == 0) {
4998 path->slots[1] = slot;
4999 btrfs_del_leaf(trans, root, path, leaf);
5000 free_extent_buffer(leaf);
5003 /* if we're still in the path, make sure
5004 * we're dirty. Otherwise, one of the
5005 * push_leaf functions must have already
5006 * dirtied this buffer
5008 if (path->nodes[0] == leaf)
5009 btrfs_mark_buffer_dirty(leaf);
5010 free_extent_buffer(leaf);
5013 btrfs_mark_buffer_dirty(leaf);
5020 * search the tree again to find a leaf with lesser keys
5021 * returns 0 if it found something or 1 if there are no lesser leaves.
5022 * returns < 0 on io errors.
5024 * This may release the path, and so you may lose any locks held at the
5027 int btrfs_prev_leaf(struct btrfs_root *root, struct btrfs_path *path)
5029 struct btrfs_key key;
5030 struct btrfs_disk_key found_key;
5033 btrfs_item_key_to_cpu(path->nodes[0], &key, 0);
5035 if (key.offset > 0) {
5037 } else if (key.type > 0) {
5039 key.offset = (u64)-1;
5040 } else if (key.objectid > 0) {
5043 key.offset = (u64)-1;
5048 btrfs_release_path(path);
5049 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5052 btrfs_item_key(path->nodes[0], &found_key, 0);
5053 ret = comp_keys(&found_key, &key);
5055 * We might have had an item with the previous key in the tree right
5056 * before we released our path. And after we released our path, that
5057 * item might have been pushed to the first slot (0) of the leaf we
5058 * were holding due to a tree balance. Alternatively, an item with the
5059 * previous key can exist as the only element of a leaf (big fat item).
5060 * Therefore account for these 2 cases, so that our callers (like
5061 * btrfs_previous_item) don't miss an existing item with a key matching
5062 * the previous key we computed above.
5070 * A helper function to walk down the tree starting at min_key, and looking
5071 * for nodes or leaves that are have a minimum transaction id.
5072 * This is used by the btree defrag code, and tree logging
5074 * This does not cow, but it does stuff the starting key it finds back
5075 * into min_key, so you can call btrfs_search_slot with cow=1 on the
5076 * key and get a writable path.
5078 * This honors path->lowest_level to prevent descent past a given level
5081 * min_trans indicates the oldest transaction that you are interested
5082 * in walking through. Any nodes or leaves older than min_trans are
5083 * skipped over (without reading them).
5085 * returns zero if something useful was found, < 0 on error and 1 if there
5086 * was nothing in the tree that matched the search criteria.
5088 int btrfs_search_forward(struct btrfs_root *root, struct btrfs_key *min_key,
5089 struct btrfs_path *path,
5092 struct extent_buffer *cur;
5093 struct btrfs_key found_key;
5099 int keep_locks = path->keep_locks;
5101 path->keep_locks = 1;
5103 cur = btrfs_read_lock_root_node(root);
5104 level = btrfs_header_level(cur);
5105 WARN_ON(path->nodes[level]);
5106 path->nodes[level] = cur;
5107 path->locks[level] = BTRFS_READ_LOCK;
5109 if (btrfs_header_generation(cur) < min_trans) {
5114 nritems = btrfs_header_nritems(cur);
5115 level = btrfs_header_level(cur);
5116 sret = btrfs_bin_search(cur, min_key, &slot);
5122 /* at the lowest level, we're done, setup the path and exit */
5123 if (level == path->lowest_level) {
5124 if (slot >= nritems)
5127 path->slots[level] = slot;
5128 btrfs_item_key_to_cpu(cur, &found_key, slot);
5131 if (sret && slot > 0)
5134 * check this node pointer against the min_trans parameters.
5135 * If it is too old, skip to the next one.
5137 while (slot < nritems) {
5140 gen = btrfs_node_ptr_generation(cur, slot);
5141 if (gen < min_trans) {
5149 * we didn't find a candidate key in this node, walk forward
5150 * and find another one
5152 if (slot >= nritems) {
5153 path->slots[level] = slot;
5154 sret = btrfs_find_next_key(root, path, min_key, level,
5157 btrfs_release_path(path);
5163 /* save our key for returning back */
5164 btrfs_node_key_to_cpu(cur, &found_key, slot);
5165 path->slots[level] = slot;
5166 if (level == path->lowest_level) {
5170 cur = btrfs_read_node_slot(cur, slot);
5176 btrfs_tree_read_lock(cur);
5178 path->locks[level - 1] = BTRFS_READ_LOCK;
5179 path->nodes[level - 1] = cur;
5180 unlock_up(path, level, 1, 0, NULL);
5183 path->keep_locks = keep_locks;
5185 btrfs_unlock_up_safe(path, path->lowest_level + 1);
5186 memcpy(min_key, &found_key, sizeof(found_key));
5192 * this is similar to btrfs_next_leaf, but does not try to preserve
5193 * and fixup the path. It looks for and returns the next key in the
5194 * tree based on the current path and the min_trans parameters.
5196 * 0 is returned if another key is found, < 0 if there are any errors
5197 * and 1 is returned if there are no higher keys in the tree
5199 * path->keep_locks should be set to 1 on the search made before
5200 * calling this function.
5202 int btrfs_find_next_key(struct btrfs_root *root, struct btrfs_path *path,
5203 struct btrfs_key *key, int level, u64 min_trans)
5206 struct extent_buffer *c;
5208 WARN_ON(!path->keep_locks && !path->skip_locking);
5209 while (level < BTRFS_MAX_LEVEL) {
5210 if (!path->nodes[level])
5213 slot = path->slots[level] + 1;
5214 c = path->nodes[level];
5216 if (slot >= btrfs_header_nritems(c)) {
5219 struct btrfs_key cur_key;
5220 if (level + 1 >= BTRFS_MAX_LEVEL ||
5221 !path->nodes[level + 1])
5224 if (path->locks[level + 1] || path->skip_locking) {
5229 slot = btrfs_header_nritems(c) - 1;
5231 btrfs_item_key_to_cpu(c, &cur_key, slot);
5233 btrfs_node_key_to_cpu(c, &cur_key, slot);
5235 orig_lowest = path->lowest_level;
5236 btrfs_release_path(path);
5237 path->lowest_level = level;
5238 ret = btrfs_search_slot(NULL, root, &cur_key, path,
5240 path->lowest_level = orig_lowest;
5244 c = path->nodes[level];
5245 slot = path->slots[level];
5252 btrfs_item_key_to_cpu(c, key, slot);
5254 u64 gen = btrfs_node_ptr_generation(c, slot);
5256 if (gen < min_trans) {
5260 btrfs_node_key_to_cpu(c, key, slot);
5268 * search the tree again to find a leaf with greater keys
5269 * returns 0 if it found something or 1 if there are no greater leaves.
5270 * returns < 0 on io errors.
5272 int btrfs_next_leaf(struct btrfs_root *root, struct btrfs_path *path)
5274 return btrfs_next_old_leaf(root, path, 0);
5277 int btrfs_next_old_leaf(struct btrfs_root *root, struct btrfs_path *path,
5282 struct extent_buffer *c;
5283 struct extent_buffer *next;
5284 struct btrfs_key key;
5289 nritems = btrfs_header_nritems(path->nodes[0]);
5293 btrfs_item_key_to_cpu(path->nodes[0], &key, nritems - 1);
5297 btrfs_release_path(path);
5299 path->keep_locks = 1;
5302 ret = btrfs_search_old_slot(root, &key, path, time_seq);
5304 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5305 path->keep_locks = 0;
5310 nritems = btrfs_header_nritems(path->nodes[0]);
5312 * by releasing the path above we dropped all our locks. A balance
5313 * could have added more items next to the key that used to be
5314 * at the very end of the block. So, check again here and
5315 * advance the path if there are now more items available.
5317 if (nritems > 0 && path->slots[0] < nritems - 1) {
5324 * So the above check misses one case:
5325 * - after releasing the path above, someone has removed the item that
5326 * used to be at the very end of the block, and balance between leafs
5327 * gets another one with bigger key.offset to replace it.
5329 * This one should be returned as well, or we can get leaf corruption
5330 * later(esp. in __btrfs_drop_extents()).
5332 * And a bit more explanation about this check,
5333 * with ret > 0, the key isn't found, the path points to the slot
5334 * where it should be inserted, so the path->slots[0] item must be the
5337 if (nritems > 0 && ret > 0 && path->slots[0] == nritems - 1) {
5342 while (level < BTRFS_MAX_LEVEL) {
5343 if (!path->nodes[level]) {
5348 slot = path->slots[level] + 1;
5349 c = path->nodes[level];
5350 if (slot >= btrfs_header_nritems(c)) {
5352 if (level == BTRFS_MAX_LEVEL) {
5361 * Our current level is where we're going to start from, and to
5362 * make sure lockdep doesn't complain we need to drop our locks
5363 * and nodes from 0 to our current level.
5365 for (i = 0; i < level; i++) {
5366 if (path->locks[level]) {
5367 btrfs_tree_read_unlock(path->nodes[i]);
5370 free_extent_buffer(path->nodes[i]);
5371 path->nodes[i] = NULL;
5375 ret = read_block_for_search(root, path, &next, level,
5381 btrfs_release_path(path);
5385 if (!path->skip_locking) {
5386 ret = btrfs_try_tree_read_lock(next);
5387 if (!ret && time_seq) {
5389 * If we don't get the lock, we may be racing
5390 * with push_leaf_left, holding that lock while
5391 * itself waiting for the leaf we've currently
5392 * locked. To solve this situation, we give up
5393 * on our lock and cycle.
5395 free_extent_buffer(next);
5396 btrfs_release_path(path);
5401 btrfs_tree_read_lock(next);
5405 path->slots[level] = slot;
5408 path->nodes[level] = next;
5409 path->slots[level] = 0;
5410 if (!path->skip_locking)
5411 path->locks[level] = BTRFS_READ_LOCK;
5415 ret = read_block_for_search(root, path, &next, level,
5421 btrfs_release_path(path);
5425 if (!path->skip_locking)
5426 btrfs_tree_read_lock(next);
5430 unlock_up(path, 0, 1, 0, NULL);
5436 * this uses btrfs_prev_leaf to walk backwards in the tree, and keeps
5437 * searching until it gets past min_objectid or finds an item of 'type'
5439 * returns 0 if something is found, 1 if nothing was found and < 0 on error
5441 int btrfs_previous_item(struct btrfs_root *root,
5442 struct btrfs_path *path, u64 min_objectid,
5445 struct btrfs_key found_key;
5446 struct extent_buffer *leaf;
5451 if (path->slots[0] == 0) {
5452 ret = btrfs_prev_leaf(root, path);
5458 leaf = path->nodes[0];
5459 nritems = btrfs_header_nritems(leaf);
5462 if (path->slots[0] == nritems)
5465 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5466 if (found_key.objectid < min_objectid)
5468 if (found_key.type == type)
5470 if (found_key.objectid == min_objectid &&
5471 found_key.type < type)
5478 * search in extent tree to find a previous Metadata/Data extent item with
5481 * returns 0 if something is found, 1 if nothing was found and < 0 on error
5483 int btrfs_previous_extent_item(struct btrfs_root *root,
5484 struct btrfs_path *path, u64 min_objectid)
5486 struct btrfs_key found_key;
5487 struct extent_buffer *leaf;
5492 if (path->slots[0] == 0) {
5493 ret = btrfs_prev_leaf(root, path);
5499 leaf = path->nodes[0];
5500 nritems = btrfs_header_nritems(leaf);
5503 if (path->slots[0] == nritems)
5506 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5507 if (found_key.objectid < min_objectid)
5509 if (found_key.type == BTRFS_EXTENT_ITEM_KEY ||
5510 found_key.type == BTRFS_METADATA_ITEM_KEY)
5512 if (found_key.objectid == min_objectid &&
5513 found_key.type < BTRFS_EXTENT_ITEM_KEY)