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"
16 static int split_node(struct btrfs_trans_handle *trans, struct btrfs_root
17 *root, struct btrfs_path *path, int level);
18 static int split_leaf(struct btrfs_trans_handle *trans, struct btrfs_root *root,
19 const struct btrfs_key *ins_key, struct btrfs_path *path,
20 int data_size, int extend);
21 static int push_node_left(struct btrfs_trans_handle *trans,
22 struct btrfs_fs_info *fs_info,
23 struct extent_buffer *dst,
24 struct extent_buffer *src, int empty);
25 static int balance_node_right(struct btrfs_trans_handle *trans,
26 struct btrfs_fs_info *fs_info,
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 struct btrfs_path *btrfs_alloc_path(void)
34 return kmem_cache_zalloc(btrfs_path_cachep, GFP_NOFS);
38 * set all locked nodes in the path to blocking locks. This should
39 * be done before scheduling
41 noinline void btrfs_set_path_blocking(struct btrfs_path *p)
44 for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
45 if (!p->nodes[i] || !p->locks[i])
47 btrfs_set_lock_blocking_rw(p->nodes[i], p->locks[i]);
48 if (p->locks[i] == BTRFS_READ_LOCK)
49 p->locks[i] = BTRFS_READ_LOCK_BLOCKING;
50 else if (p->locks[i] == BTRFS_WRITE_LOCK)
51 p->locks[i] = BTRFS_WRITE_LOCK_BLOCKING;
56 * reset all the locked nodes in the patch to spinning locks.
58 * held is used to keep lockdep happy, when lockdep is enabled
59 * we set held to a blocking lock before we go around and
60 * retake all the spinlocks in the path. You can safely use NULL
63 noinline void btrfs_clear_path_blocking(struct btrfs_path *p,
64 struct extent_buffer *held, int held_rw)
69 btrfs_set_lock_blocking_rw(held, held_rw);
70 if (held_rw == BTRFS_WRITE_LOCK)
71 held_rw = BTRFS_WRITE_LOCK_BLOCKING;
72 else if (held_rw == BTRFS_READ_LOCK)
73 held_rw = BTRFS_READ_LOCK_BLOCKING;
75 btrfs_set_path_blocking(p);
77 for (i = BTRFS_MAX_LEVEL - 1; i >= 0; i--) {
78 if (p->nodes[i] && p->locks[i]) {
79 btrfs_clear_lock_blocking_rw(p->nodes[i], p->locks[i]);
80 if (p->locks[i] == BTRFS_WRITE_LOCK_BLOCKING)
81 p->locks[i] = BTRFS_WRITE_LOCK;
82 else if (p->locks[i] == BTRFS_READ_LOCK_BLOCKING)
83 p->locks[i] = BTRFS_READ_LOCK;
88 btrfs_clear_lock_blocking_rw(held, held_rw);
91 /* this also releases the path */
92 void btrfs_free_path(struct btrfs_path *p)
96 btrfs_release_path(p);
97 kmem_cache_free(btrfs_path_cachep, p);
101 * path release drops references on the extent buffers in the path
102 * and it drops any locks held by this path
104 * It is safe to call this on paths that no locks or extent buffers held.
106 noinline void btrfs_release_path(struct btrfs_path *p)
110 for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
115 btrfs_tree_unlock_rw(p->nodes[i], p->locks[i]);
118 free_extent_buffer(p->nodes[i]);
124 * safely gets a reference on the root node of a tree. A lock
125 * is not taken, so a concurrent writer may put a different node
126 * at the root of the tree. See btrfs_lock_root_node for the
129 * The extent buffer returned by this has a reference taken, so
130 * it won't disappear. It may stop being the root of the tree
131 * at any time because there are no locks held.
133 struct extent_buffer *btrfs_root_node(struct btrfs_root *root)
135 struct extent_buffer *eb;
139 eb = rcu_dereference(root->node);
142 * RCU really hurts here, we could free up the root node because
143 * it was COWed but we may not get the new root node yet so do
144 * the inc_not_zero dance and if it doesn't work then
145 * synchronize_rcu and try again.
147 if (atomic_inc_not_zero(&eb->refs)) {
157 /* loop around taking references on and locking the root node of the
158 * tree until you end up with a lock on the root. A locked buffer
159 * is returned, with a reference held.
161 struct extent_buffer *btrfs_lock_root_node(struct btrfs_root *root)
163 struct extent_buffer *eb;
166 eb = btrfs_root_node(root);
168 if (eb == root->node)
170 btrfs_tree_unlock(eb);
171 free_extent_buffer(eb);
176 /* loop around taking references on and locking the root node of the
177 * tree until you end up with a lock on the root. A locked buffer
178 * is returned, with a reference held.
180 struct extent_buffer *btrfs_read_lock_root_node(struct btrfs_root *root)
182 struct extent_buffer *eb;
185 eb = btrfs_root_node(root);
186 btrfs_tree_read_lock(eb);
187 if (eb == root->node)
189 btrfs_tree_read_unlock(eb);
190 free_extent_buffer(eb);
195 /* cowonly root (everything not a reference counted cow subvolume), just get
196 * put onto a simple dirty list. transaction.c walks this to make sure they
197 * get properly updated on disk.
199 static void add_root_to_dirty_list(struct btrfs_root *root)
201 struct btrfs_fs_info *fs_info = root->fs_info;
203 if (test_bit(BTRFS_ROOT_DIRTY, &root->state) ||
204 !test_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state))
207 spin_lock(&fs_info->trans_lock);
208 if (!test_and_set_bit(BTRFS_ROOT_DIRTY, &root->state)) {
209 /* Want the extent tree to be the last on the list */
210 if (root->objectid == BTRFS_EXTENT_TREE_OBJECTID)
211 list_move_tail(&root->dirty_list,
212 &fs_info->dirty_cowonly_roots);
214 list_move(&root->dirty_list,
215 &fs_info->dirty_cowonly_roots);
217 spin_unlock(&fs_info->trans_lock);
221 * used by snapshot creation to make a copy of a root for a tree with
222 * a given objectid. The buffer with the new root node is returned in
223 * cow_ret, and this func returns zero on success or a negative error code.
225 int btrfs_copy_root(struct btrfs_trans_handle *trans,
226 struct btrfs_root *root,
227 struct extent_buffer *buf,
228 struct extent_buffer **cow_ret, u64 new_root_objectid)
230 struct btrfs_fs_info *fs_info = root->fs_info;
231 struct extent_buffer *cow;
234 struct btrfs_disk_key disk_key;
236 WARN_ON(test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
237 trans->transid != fs_info->running_transaction->transid);
238 WARN_ON(test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
239 trans->transid != root->last_trans);
241 level = btrfs_header_level(buf);
243 btrfs_item_key(buf, &disk_key, 0);
245 btrfs_node_key(buf, &disk_key, 0);
247 cow = btrfs_alloc_tree_block(trans, root, 0, new_root_objectid,
248 &disk_key, level, buf->start, 0);
252 copy_extent_buffer_full(cow, buf);
253 btrfs_set_header_bytenr(cow, cow->start);
254 btrfs_set_header_generation(cow, trans->transid);
255 btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
256 btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
257 BTRFS_HEADER_FLAG_RELOC);
258 if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
259 btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
261 btrfs_set_header_owner(cow, new_root_objectid);
263 write_extent_buffer_fsid(cow, fs_info->fsid);
265 WARN_ON(btrfs_header_generation(buf) > trans->transid);
266 if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
267 ret = btrfs_inc_ref(trans, root, cow, 1);
269 ret = btrfs_inc_ref(trans, root, cow, 0);
271 btrfs_tree_unlock(cow);
272 free_extent_buffer(cow);
273 btrfs_abort_transaction(trans, ret);
277 btrfs_mark_buffer_dirty(cow);
286 MOD_LOG_KEY_REMOVE_WHILE_FREEING,
287 MOD_LOG_KEY_REMOVE_WHILE_MOVING,
289 MOD_LOG_ROOT_REPLACE,
292 struct tree_mod_root {
297 struct tree_mod_elem {
303 /* this is used for MOD_LOG_KEY_* and MOD_LOG_MOVE_KEYS operations */
306 /* this is used for MOD_LOG_KEY* and MOD_LOG_ROOT_REPLACE */
309 /* those are used for op == MOD_LOG_KEY_{REPLACE,REMOVE} */
310 struct btrfs_disk_key key;
313 /* this is used for op == MOD_LOG_MOVE_KEYS */
319 /* this is used for op == MOD_LOG_ROOT_REPLACE */
320 struct tree_mod_root old_root;
324 * Pull a new tree mod seq number for our operation.
326 static inline u64 btrfs_inc_tree_mod_seq(struct btrfs_fs_info *fs_info)
328 return atomic64_inc_return(&fs_info->tree_mod_seq);
332 * This adds a new blocker to the tree mod log's blocker list if the @elem
333 * passed does not already have a sequence number set. So when a caller expects
334 * to record tree modifications, it should ensure to set elem->seq to zero
335 * before calling btrfs_get_tree_mod_seq.
336 * Returns a fresh, unused tree log modification sequence number, even if no new
339 u64 btrfs_get_tree_mod_seq(struct btrfs_fs_info *fs_info,
340 struct seq_list *elem)
342 write_lock(&fs_info->tree_mod_log_lock);
344 elem->seq = btrfs_inc_tree_mod_seq(fs_info);
345 list_add_tail(&elem->list, &fs_info->tree_mod_seq_list);
347 write_unlock(&fs_info->tree_mod_log_lock);
352 void btrfs_put_tree_mod_seq(struct btrfs_fs_info *fs_info,
353 struct seq_list *elem)
355 struct rb_root *tm_root;
356 struct rb_node *node;
357 struct rb_node *next;
358 struct seq_list *cur_elem;
359 struct tree_mod_elem *tm;
360 u64 min_seq = (u64)-1;
361 u64 seq_putting = elem->seq;
366 write_lock(&fs_info->tree_mod_log_lock);
367 list_del(&elem->list);
370 list_for_each_entry(cur_elem, &fs_info->tree_mod_seq_list, list) {
371 if (cur_elem->seq < min_seq) {
372 if (seq_putting > cur_elem->seq) {
374 * blocker with lower sequence number exists, we
375 * cannot remove anything from the log
377 write_unlock(&fs_info->tree_mod_log_lock);
380 min_seq = cur_elem->seq;
385 * anything that's lower than the lowest existing (read: blocked)
386 * sequence number can be removed from the tree.
388 tm_root = &fs_info->tree_mod_log;
389 for (node = rb_first(tm_root); node; node = next) {
390 next = rb_next(node);
391 tm = rb_entry(node, struct tree_mod_elem, node);
392 if (tm->seq >= min_seq)
394 rb_erase(node, tm_root);
397 write_unlock(&fs_info->tree_mod_log_lock);
401 * key order of the log:
402 * node/leaf start address -> sequence
404 * The 'start address' is the logical address of the *new* root node
405 * for root replace operations, or the logical address of the affected
406 * block for all other operations.
408 * Note: must be called with write lock for fs_info::tree_mod_log_lock.
411 __tree_mod_log_insert(struct btrfs_fs_info *fs_info, struct tree_mod_elem *tm)
413 struct rb_root *tm_root;
414 struct rb_node **new;
415 struct rb_node *parent = NULL;
416 struct tree_mod_elem *cur;
418 tm->seq = btrfs_inc_tree_mod_seq(fs_info);
420 tm_root = &fs_info->tree_mod_log;
421 new = &tm_root->rb_node;
423 cur = rb_entry(*new, struct tree_mod_elem, node);
425 if (cur->logical < tm->logical)
426 new = &((*new)->rb_left);
427 else if (cur->logical > tm->logical)
428 new = &((*new)->rb_right);
429 else if (cur->seq < tm->seq)
430 new = &((*new)->rb_left);
431 else if (cur->seq > tm->seq)
432 new = &((*new)->rb_right);
437 rb_link_node(&tm->node, parent, new);
438 rb_insert_color(&tm->node, tm_root);
443 * Determines if logging can be omitted. Returns 1 if it can. Otherwise, it
444 * returns zero with the tree_mod_log_lock acquired. The caller must hold
445 * this until all tree mod log insertions are recorded in the rb tree and then
446 * write unlock fs_info::tree_mod_log_lock.
448 static inline int tree_mod_dont_log(struct btrfs_fs_info *fs_info,
449 struct extent_buffer *eb) {
451 if (list_empty(&(fs_info)->tree_mod_seq_list))
453 if (eb && btrfs_header_level(eb) == 0)
456 write_lock(&fs_info->tree_mod_log_lock);
457 if (list_empty(&(fs_info)->tree_mod_seq_list)) {
458 write_unlock(&fs_info->tree_mod_log_lock);
465 /* Similar to tree_mod_dont_log, but doesn't acquire any locks. */
466 static inline int tree_mod_need_log(const struct btrfs_fs_info *fs_info,
467 struct extent_buffer *eb)
470 if (list_empty(&(fs_info)->tree_mod_seq_list))
472 if (eb && btrfs_header_level(eb) == 0)
478 static struct tree_mod_elem *
479 alloc_tree_mod_elem(struct extent_buffer *eb, int slot,
480 enum mod_log_op op, gfp_t flags)
482 struct tree_mod_elem *tm;
484 tm = kzalloc(sizeof(*tm), flags);
488 tm->logical = eb->start;
489 if (op != MOD_LOG_KEY_ADD) {
490 btrfs_node_key(eb, &tm->key, slot);
491 tm->blockptr = btrfs_node_blockptr(eb, slot);
495 tm->generation = btrfs_node_ptr_generation(eb, slot);
496 RB_CLEAR_NODE(&tm->node);
501 static noinline int tree_mod_log_insert_key(struct extent_buffer *eb, int slot,
502 enum mod_log_op op, gfp_t flags)
504 struct tree_mod_elem *tm;
507 if (!tree_mod_need_log(eb->fs_info, eb))
510 tm = alloc_tree_mod_elem(eb, slot, op, flags);
514 if (tree_mod_dont_log(eb->fs_info, eb)) {
519 ret = __tree_mod_log_insert(eb->fs_info, tm);
520 write_unlock(&eb->fs_info->tree_mod_log_lock);
527 static noinline int tree_mod_log_insert_move(struct extent_buffer *eb,
528 int dst_slot, int src_slot, int nr_items)
530 struct tree_mod_elem *tm = NULL;
531 struct tree_mod_elem **tm_list = NULL;
536 if (!tree_mod_need_log(eb->fs_info, eb))
539 tm_list = kcalloc(nr_items, sizeof(struct tree_mod_elem *), GFP_NOFS);
543 tm = kzalloc(sizeof(*tm), GFP_NOFS);
549 tm->logical = eb->start;
551 tm->move.dst_slot = dst_slot;
552 tm->move.nr_items = nr_items;
553 tm->op = MOD_LOG_MOVE_KEYS;
555 for (i = 0; i + dst_slot < src_slot && i < nr_items; i++) {
556 tm_list[i] = alloc_tree_mod_elem(eb, i + dst_slot,
557 MOD_LOG_KEY_REMOVE_WHILE_MOVING, GFP_NOFS);
564 if (tree_mod_dont_log(eb->fs_info, eb))
569 * When we override something during the move, we log these removals.
570 * This can only happen when we move towards the beginning of the
571 * buffer, i.e. dst_slot < src_slot.
573 for (i = 0; i + dst_slot < src_slot && i < nr_items; i++) {
574 ret = __tree_mod_log_insert(eb->fs_info, tm_list[i]);
579 ret = __tree_mod_log_insert(eb->fs_info, tm);
582 write_unlock(&eb->fs_info->tree_mod_log_lock);
587 for (i = 0; i < nr_items; i++) {
588 if (tm_list[i] && !RB_EMPTY_NODE(&tm_list[i]->node))
589 rb_erase(&tm_list[i]->node, &eb->fs_info->tree_mod_log);
593 write_unlock(&eb->fs_info->tree_mod_log_lock);
601 __tree_mod_log_free_eb(struct btrfs_fs_info *fs_info,
602 struct tree_mod_elem **tm_list,
608 for (i = nritems - 1; i >= 0; i--) {
609 ret = __tree_mod_log_insert(fs_info, tm_list[i]);
611 for (j = nritems - 1; j > i; j--)
612 rb_erase(&tm_list[j]->node,
613 &fs_info->tree_mod_log);
621 static noinline int tree_mod_log_insert_root(struct extent_buffer *old_root,
622 struct extent_buffer *new_root, int log_removal)
624 struct btrfs_fs_info *fs_info = old_root->fs_info;
625 struct tree_mod_elem *tm = NULL;
626 struct tree_mod_elem **tm_list = NULL;
631 if (!tree_mod_need_log(fs_info, NULL))
634 if (log_removal && btrfs_header_level(old_root) > 0) {
635 nritems = btrfs_header_nritems(old_root);
636 tm_list = kcalloc(nritems, sizeof(struct tree_mod_elem *),
642 for (i = 0; i < nritems; i++) {
643 tm_list[i] = alloc_tree_mod_elem(old_root, i,
644 MOD_LOG_KEY_REMOVE_WHILE_FREEING, GFP_NOFS);
652 tm = kzalloc(sizeof(*tm), GFP_NOFS);
658 tm->logical = new_root->start;
659 tm->old_root.logical = old_root->start;
660 tm->old_root.level = btrfs_header_level(old_root);
661 tm->generation = btrfs_header_generation(old_root);
662 tm->op = MOD_LOG_ROOT_REPLACE;
664 if (tree_mod_dont_log(fs_info, NULL))
668 ret = __tree_mod_log_free_eb(fs_info, tm_list, nritems);
670 ret = __tree_mod_log_insert(fs_info, tm);
672 write_unlock(&fs_info->tree_mod_log_lock);
681 for (i = 0; i < nritems; i++)
690 static struct tree_mod_elem *
691 __tree_mod_log_search(struct btrfs_fs_info *fs_info, u64 start, u64 min_seq,
694 struct rb_root *tm_root;
695 struct rb_node *node;
696 struct tree_mod_elem *cur = NULL;
697 struct tree_mod_elem *found = NULL;
699 read_lock(&fs_info->tree_mod_log_lock);
700 tm_root = &fs_info->tree_mod_log;
701 node = tm_root->rb_node;
703 cur = rb_entry(node, struct tree_mod_elem, node);
704 if (cur->logical < start) {
705 node = node->rb_left;
706 } else if (cur->logical > start) {
707 node = node->rb_right;
708 } else if (cur->seq < min_seq) {
709 node = node->rb_left;
710 } else if (!smallest) {
711 /* we want the node with the highest seq */
713 BUG_ON(found->seq > cur->seq);
715 node = node->rb_left;
716 } else if (cur->seq > min_seq) {
717 /* we want the node with the smallest seq */
719 BUG_ON(found->seq < cur->seq);
721 node = node->rb_right;
727 read_unlock(&fs_info->tree_mod_log_lock);
733 * this returns the element from the log with the smallest time sequence
734 * value that's in the log (the oldest log item). any element with a time
735 * sequence lower than min_seq will be ignored.
737 static struct tree_mod_elem *
738 tree_mod_log_search_oldest(struct btrfs_fs_info *fs_info, u64 start,
741 return __tree_mod_log_search(fs_info, start, min_seq, 1);
745 * this returns the element from the log with the largest time sequence
746 * value that's in the log (the most recent log item). any element with
747 * a time sequence lower than min_seq will be ignored.
749 static struct tree_mod_elem *
750 tree_mod_log_search(struct btrfs_fs_info *fs_info, u64 start, u64 min_seq)
752 return __tree_mod_log_search(fs_info, start, min_seq, 0);
756 tree_mod_log_eb_copy(struct btrfs_fs_info *fs_info, struct extent_buffer *dst,
757 struct extent_buffer *src, unsigned long dst_offset,
758 unsigned long src_offset, int nr_items)
761 struct tree_mod_elem **tm_list = NULL;
762 struct tree_mod_elem **tm_list_add, **tm_list_rem;
766 if (!tree_mod_need_log(fs_info, NULL))
769 if (btrfs_header_level(dst) == 0 && btrfs_header_level(src) == 0)
772 tm_list = kcalloc(nr_items * 2, sizeof(struct tree_mod_elem *),
777 tm_list_add = tm_list;
778 tm_list_rem = tm_list + nr_items;
779 for (i = 0; i < nr_items; i++) {
780 tm_list_rem[i] = alloc_tree_mod_elem(src, i + src_offset,
781 MOD_LOG_KEY_REMOVE, GFP_NOFS);
782 if (!tm_list_rem[i]) {
787 tm_list_add[i] = alloc_tree_mod_elem(dst, i + dst_offset,
788 MOD_LOG_KEY_ADD, GFP_NOFS);
789 if (!tm_list_add[i]) {
795 if (tree_mod_dont_log(fs_info, NULL))
799 for (i = 0; i < nr_items; i++) {
800 ret = __tree_mod_log_insert(fs_info, tm_list_rem[i]);
803 ret = __tree_mod_log_insert(fs_info, tm_list_add[i]);
808 write_unlock(&fs_info->tree_mod_log_lock);
814 for (i = 0; i < nr_items * 2; i++) {
815 if (tm_list[i] && !RB_EMPTY_NODE(&tm_list[i]->node))
816 rb_erase(&tm_list[i]->node, &fs_info->tree_mod_log);
820 write_unlock(&fs_info->tree_mod_log_lock);
826 static noinline int tree_mod_log_free_eb(struct extent_buffer *eb)
828 struct tree_mod_elem **tm_list = NULL;
833 if (btrfs_header_level(eb) == 0)
836 if (!tree_mod_need_log(eb->fs_info, NULL))
839 nritems = btrfs_header_nritems(eb);
840 tm_list = kcalloc(nritems, sizeof(struct tree_mod_elem *), GFP_NOFS);
844 for (i = 0; i < nritems; i++) {
845 tm_list[i] = alloc_tree_mod_elem(eb, i,
846 MOD_LOG_KEY_REMOVE_WHILE_FREEING, GFP_NOFS);
853 if (tree_mod_dont_log(eb->fs_info, eb))
856 ret = __tree_mod_log_free_eb(eb->fs_info, tm_list, nritems);
857 write_unlock(&eb->fs_info->tree_mod_log_lock);
865 for (i = 0; i < nritems; i++)
873 * check if the tree block can be shared by multiple trees
875 int btrfs_block_can_be_shared(struct btrfs_root *root,
876 struct extent_buffer *buf)
879 * Tree blocks not in reference counted trees and tree roots
880 * are never shared. If a block was allocated after the last
881 * snapshot and the block was not allocated by tree relocation,
882 * we know the block is not shared.
884 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
885 buf != root->node && buf != root->commit_root &&
886 (btrfs_header_generation(buf) <=
887 btrfs_root_last_snapshot(&root->root_item) ||
888 btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)))
894 static noinline int update_ref_for_cow(struct btrfs_trans_handle *trans,
895 struct btrfs_root *root,
896 struct extent_buffer *buf,
897 struct extent_buffer *cow,
900 struct btrfs_fs_info *fs_info = root->fs_info;
908 * Backrefs update rules:
910 * Always use full backrefs for extent pointers in tree block
911 * allocated by tree relocation.
913 * If a shared tree block is no longer referenced by its owner
914 * tree (btrfs_header_owner(buf) == root->root_key.objectid),
915 * use full backrefs for extent pointers in tree block.
917 * If a tree block is been relocating
918 * (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID),
919 * use full backrefs for extent pointers in tree block.
920 * The reason for this is some operations (such as drop tree)
921 * are only allowed for blocks use full backrefs.
924 if (btrfs_block_can_be_shared(root, buf)) {
925 ret = btrfs_lookup_extent_info(trans, fs_info, buf->start,
926 btrfs_header_level(buf), 1,
932 btrfs_handle_fs_error(fs_info, ret, NULL);
937 if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
938 btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
939 flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
944 owner = btrfs_header_owner(buf);
945 BUG_ON(owner == BTRFS_TREE_RELOC_OBJECTID &&
946 !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
949 if ((owner == root->root_key.objectid ||
950 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) &&
951 !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)) {
952 ret = btrfs_inc_ref(trans, root, buf, 1);
956 if (root->root_key.objectid ==
957 BTRFS_TREE_RELOC_OBJECTID) {
958 ret = btrfs_dec_ref(trans, root, buf, 0);
961 ret = btrfs_inc_ref(trans, root, cow, 1);
965 new_flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
968 if (root->root_key.objectid ==
969 BTRFS_TREE_RELOC_OBJECTID)
970 ret = btrfs_inc_ref(trans, root, cow, 1);
972 ret = btrfs_inc_ref(trans, root, cow, 0);
976 if (new_flags != 0) {
977 int level = btrfs_header_level(buf);
979 ret = btrfs_set_disk_extent_flags(trans, fs_info,
982 new_flags, level, 0);
987 if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
988 if (root->root_key.objectid ==
989 BTRFS_TREE_RELOC_OBJECTID)
990 ret = btrfs_inc_ref(trans, root, cow, 1);
992 ret = btrfs_inc_ref(trans, root, cow, 0);
995 ret = btrfs_dec_ref(trans, root, buf, 1);
999 clean_tree_block(fs_info, buf);
1005 static struct extent_buffer *alloc_tree_block_no_bg_flush(
1006 struct btrfs_trans_handle *trans,
1007 struct btrfs_root *root,
1009 const struct btrfs_disk_key *disk_key,
1014 struct btrfs_fs_info *fs_info = root->fs_info;
1015 struct extent_buffer *ret;
1018 * If we are COWing a node/leaf from the extent, chunk, device or free
1019 * space trees, make sure that we do not finish block group creation of
1020 * pending block groups. We do this to avoid a deadlock.
1021 * COWing can result in allocation of a new chunk, and flushing pending
1022 * block groups (btrfs_create_pending_block_groups()) can be triggered
1023 * when finishing allocation of a new chunk. Creation of a pending block
1024 * group modifies the extent, chunk, device and free space trees,
1025 * therefore we could deadlock with ourselves since we are holding a
1026 * lock on an extent buffer that btrfs_create_pending_block_groups() may
1028 * For similar reasons, we also need to delay flushing pending block
1029 * groups when splitting a leaf or node, from one of those trees, since
1030 * we are holding a write lock on it and its parent or when inserting a
1031 * new root node for one of those trees.
1033 if (root == fs_info->extent_root ||
1034 root == fs_info->chunk_root ||
1035 root == fs_info->dev_root ||
1036 root == fs_info->free_space_root)
1037 trans->can_flush_pending_bgs = false;
1039 ret = btrfs_alloc_tree_block(trans, root, parent_start,
1040 root->root_key.objectid, disk_key, level,
1042 trans->can_flush_pending_bgs = true;
1048 * does the dirty work in cow of a single block. The parent block (if
1049 * supplied) is updated to point to the new cow copy. The new buffer is marked
1050 * dirty and returned locked. If you modify the block it needs to be marked
1053 * search_start -- an allocation hint for the new block
1055 * empty_size -- a hint that you plan on doing more cow. This is the size in
1056 * bytes the allocator should try to find free next to the block it returns.
1057 * This is just a hint and may be ignored by the allocator.
1059 static noinline int __btrfs_cow_block(struct btrfs_trans_handle *trans,
1060 struct btrfs_root *root,
1061 struct extent_buffer *buf,
1062 struct extent_buffer *parent, int parent_slot,
1063 struct extent_buffer **cow_ret,
1064 u64 search_start, u64 empty_size)
1066 struct btrfs_fs_info *fs_info = root->fs_info;
1067 struct btrfs_disk_key disk_key;
1068 struct extent_buffer *cow;
1071 int unlock_orig = 0;
1072 u64 parent_start = 0;
1074 if (*cow_ret == buf)
1077 btrfs_assert_tree_locked(buf);
1079 WARN_ON(test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
1080 trans->transid != fs_info->running_transaction->transid);
1081 WARN_ON(test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
1082 trans->transid != root->last_trans);
1084 level = btrfs_header_level(buf);
1087 btrfs_item_key(buf, &disk_key, 0);
1089 btrfs_node_key(buf, &disk_key, 0);
1091 if ((root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) && parent)
1092 parent_start = parent->start;
1094 cow = alloc_tree_block_no_bg_flush(trans, root, parent_start, &disk_key,
1095 level, search_start, empty_size);
1097 return PTR_ERR(cow);
1099 /* cow is set to blocking by btrfs_init_new_buffer */
1101 copy_extent_buffer_full(cow, buf);
1102 btrfs_set_header_bytenr(cow, cow->start);
1103 btrfs_set_header_generation(cow, trans->transid);
1104 btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
1105 btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
1106 BTRFS_HEADER_FLAG_RELOC);
1107 if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
1108 btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
1110 btrfs_set_header_owner(cow, root->root_key.objectid);
1112 write_extent_buffer_fsid(cow, fs_info->fsid);
1114 ret = update_ref_for_cow(trans, root, buf, cow, &last_ref);
1116 btrfs_tree_unlock(cow);
1117 free_extent_buffer(cow);
1118 btrfs_abort_transaction(trans, ret);
1122 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state)) {
1123 ret = btrfs_reloc_cow_block(trans, root, buf, cow);
1125 btrfs_tree_unlock(cow);
1126 free_extent_buffer(cow);
1127 btrfs_abort_transaction(trans, ret);
1132 if (buf == root->node) {
1133 WARN_ON(parent && parent != buf);
1134 if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
1135 btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
1136 parent_start = buf->start;
1138 extent_buffer_get(cow);
1139 ret = tree_mod_log_insert_root(root->node, cow, 1);
1141 rcu_assign_pointer(root->node, cow);
1143 btrfs_free_tree_block(trans, root, buf, parent_start,
1145 free_extent_buffer(buf);
1146 add_root_to_dirty_list(root);
1148 WARN_ON(trans->transid != btrfs_header_generation(parent));
1149 tree_mod_log_insert_key(parent, parent_slot,
1150 MOD_LOG_KEY_REPLACE, GFP_NOFS);
1151 btrfs_set_node_blockptr(parent, parent_slot,
1153 btrfs_set_node_ptr_generation(parent, parent_slot,
1155 btrfs_mark_buffer_dirty(parent);
1157 ret = tree_mod_log_free_eb(buf);
1159 btrfs_tree_unlock(cow);
1160 free_extent_buffer(cow);
1161 btrfs_abort_transaction(trans, ret);
1165 btrfs_free_tree_block(trans, root, buf, parent_start,
1169 btrfs_tree_unlock(buf);
1170 free_extent_buffer_stale(buf);
1171 btrfs_mark_buffer_dirty(cow);
1177 * returns the logical address of the oldest predecessor of the given root.
1178 * entries older than time_seq are ignored.
1180 static struct tree_mod_elem *__tree_mod_log_oldest_root(
1181 struct extent_buffer *eb_root, u64 time_seq)
1183 struct tree_mod_elem *tm;
1184 struct tree_mod_elem *found = NULL;
1185 u64 root_logical = eb_root->start;
1192 * the very last operation that's logged for a root is the
1193 * replacement operation (if it is replaced at all). this has
1194 * the logical address of the *new* root, making it the very
1195 * first operation that's logged for this root.
1198 tm = tree_mod_log_search_oldest(eb_root->fs_info, root_logical,
1203 * if there are no tree operation for the oldest root, we simply
1204 * return it. this should only happen if that (old) root is at
1211 * if there's an operation that's not a root replacement, we
1212 * found the oldest version of our root. normally, we'll find a
1213 * MOD_LOG_KEY_REMOVE_WHILE_FREEING operation here.
1215 if (tm->op != MOD_LOG_ROOT_REPLACE)
1219 root_logical = tm->old_root.logical;
1223 /* if there's no old root to return, return what we found instead */
1231 * tm is a pointer to the first operation to rewind within eb. then, all
1232 * previous operations will be rewound (until we reach something older than
1236 __tree_mod_log_rewind(struct btrfs_fs_info *fs_info, struct extent_buffer *eb,
1237 u64 time_seq, struct tree_mod_elem *first_tm)
1240 struct rb_node *next;
1241 struct tree_mod_elem *tm = first_tm;
1242 unsigned long o_dst;
1243 unsigned long o_src;
1244 unsigned long p_size = sizeof(struct btrfs_key_ptr);
1246 n = btrfs_header_nritems(eb);
1247 read_lock(&fs_info->tree_mod_log_lock);
1248 while (tm && tm->seq >= time_seq) {
1250 * all the operations are recorded with the operator used for
1251 * the modification. as we're going backwards, we do the
1252 * opposite of each operation here.
1255 case MOD_LOG_KEY_REMOVE_WHILE_FREEING:
1256 BUG_ON(tm->slot < n);
1258 case MOD_LOG_KEY_REMOVE_WHILE_MOVING:
1259 case MOD_LOG_KEY_REMOVE:
1260 btrfs_set_node_key(eb, &tm->key, tm->slot);
1261 btrfs_set_node_blockptr(eb, tm->slot, tm->blockptr);
1262 btrfs_set_node_ptr_generation(eb, tm->slot,
1266 case MOD_LOG_KEY_REPLACE:
1267 BUG_ON(tm->slot >= n);
1268 btrfs_set_node_key(eb, &tm->key, tm->slot);
1269 btrfs_set_node_blockptr(eb, tm->slot, tm->blockptr);
1270 btrfs_set_node_ptr_generation(eb, tm->slot,
1273 case MOD_LOG_KEY_ADD:
1274 /* if a move operation is needed it's in the log */
1277 case MOD_LOG_MOVE_KEYS:
1278 o_dst = btrfs_node_key_ptr_offset(tm->slot);
1279 o_src = btrfs_node_key_ptr_offset(tm->move.dst_slot);
1280 memmove_extent_buffer(eb, o_dst, o_src,
1281 tm->move.nr_items * p_size);
1283 case MOD_LOG_ROOT_REPLACE:
1285 * this operation is special. for roots, this must be
1286 * handled explicitly before rewinding.
1287 * for non-roots, this operation may exist if the node
1288 * was a root: root A -> child B; then A gets empty and
1289 * B is promoted to the new root. in the mod log, we'll
1290 * have a root-replace operation for B, a tree block
1291 * that is no root. we simply ignore that operation.
1295 next = rb_next(&tm->node);
1298 tm = rb_entry(next, struct tree_mod_elem, node);
1299 if (tm->logical != first_tm->logical)
1302 read_unlock(&fs_info->tree_mod_log_lock);
1303 btrfs_set_header_nritems(eb, n);
1307 * Called with eb read locked. If the buffer cannot be rewound, the same buffer
1308 * is returned. If rewind operations happen, a fresh buffer is returned. The
1309 * returned buffer is always read-locked. If the returned buffer is not the
1310 * input buffer, the lock on the input buffer is released and the input buffer
1311 * is freed (its refcount is decremented).
1313 static struct extent_buffer *
1314 tree_mod_log_rewind(struct btrfs_fs_info *fs_info, struct btrfs_path *path,
1315 struct extent_buffer *eb, u64 time_seq)
1317 struct extent_buffer *eb_rewin;
1318 struct tree_mod_elem *tm;
1323 if (btrfs_header_level(eb) == 0)
1326 tm = tree_mod_log_search(fs_info, eb->start, time_seq);
1330 btrfs_set_path_blocking(path);
1331 btrfs_set_lock_blocking_rw(eb, BTRFS_READ_LOCK);
1333 if (tm->op == MOD_LOG_KEY_REMOVE_WHILE_FREEING) {
1334 BUG_ON(tm->slot != 0);
1335 eb_rewin = alloc_dummy_extent_buffer(fs_info, eb->start);
1337 btrfs_tree_read_unlock_blocking(eb);
1338 free_extent_buffer(eb);
1341 btrfs_set_header_bytenr(eb_rewin, eb->start);
1342 btrfs_set_header_backref_rev(eb_rewin,
1343 btrfs_header_backref_rev(eb));
1344 btrfs_set_header_owner(eb_rewin, btrfs_header_owner(eb));
1345 btrfs_set_header_level(eb_rewin, btrfs_header_level(eb));
1347 eb_rewin = btrfs_clone_extent_buffer(eb);
1349 btrfs_tree_read_unlock_blocking(eb);
1350 free_extent_buffer(eb);
1355 btrfs_clear_path_blocking(path, NULL, BTRFS_READ_LOCK);
1356 btrfs_tree_read_unlock_blocking(eb);
1357 free_extent_buffer(eb);
1359 btrfs_set_buffer_lockdep_class(btrfs_header_owner(eb_rewin),
1360 eb_rewin, btrfs_header_level(eb_rewin));
1361 btrfs_tree_read_lock(eb_rewin);
1362 __tree_mod_log_rewind(fs_info, eb_rewin, time_seq, tm);
1363 WARN_ON(btrfs_header_nritems(eb_rewin) >
1364 BTRFS_NODEPTRS_PER_BLOCK(fs_info));
1370 * get_old_root() rewinds the state of @root's root node to the given @time_seq
1371 * value. If there are no changes, the current root->root_node is returned. If
1372 * anything changed in between, there's a fresh buffer allocated on which the
1373 * rewind operations are done. In any case, the returned buffer is read locked.
1374 * Returns NULL on error (with no locks held).
1376 static inline struct extent_buffer *
1377 get_old_root(struct btrfs_root *root, u64 time_seq)
1379 struct btrfs_fs_info *fs_info = root->fs_info;
1380 struct tree_mod_elem *tm;
1381 struct extent_buffer *eb = NULL;
1382 struct extent_buffer *eb_root;
1383 u64 eb_root_owner = 0;
1384 struct extent_buffer *old;
1385 struct tree_mod_root *old_root = NULL;
1386 u64 old_generation = 0;
1390 eb_root = btrfs_read_lock_root_node(root);
1391 tm = __tree_mod_log_oldest_root(eb_root, time_seq);
1395 if (tm->op == MOD_LOG_ROOT_REPLACE) {
1396 old_root = &tm->old_root;
1397 old_generation = tm->generation;
1398 logical = old_root->logical;
1399 level = old_root->level;
1401 logical = eb_root->start;
1402 level = btrfs_header_level(eb_root);
1405 tm = tree_mod_log_search(fs_info, logical, time_seq);
1406 if (old_root && tm && tm->op != MOD_LOG_KEY_REMOVE_WHILE_FREEING) {
1407 btrfs_tree_read_unlock(eb_root);
1408 free_extent_buffer(eb_root);
1409 old = read_tree_block(fs_info, logical, 0, level, NULL);
1410 if (WARN_ON(IS_ERR(old) || !extent_buffer_uptodate(old))) {
1412 free_extent_buffer(old);
1414 "failed to read tree block %llu from get_old_root",
1417 struct tree_mod_elem *tm2;
1419 btrfs_tree_read_lock(old);
1420 eb = btrfs_clone_extent_buffer(old);
1422 * After the lookup for the most recent tree mod operation
1423 * above and before we locked and cloned the extent buffer
1424 * 'old', a new tree mod log operation may have been added.
1425 * So lookup for a more recent one to make sure the number
1426 * of mod log operations we replay is consistent with the
1427 * number of items we have in the cloned extent buffer,
1428 * otherwise we can hit a BUG_ON when rewinding the extent
1431 tm2 = tree_mod_log_search(fs_info, logical, time_seq);
1432 btrfs_tree_read_unlock(old);
1433 free_extent_buffer(old);
1435 ASSERT(tm2 == tm || tm2->seq > tm->seq);
1436 if (!tm2 || tm2->seq < tm->seq) {
1437 free_extent_buffer(eb);
1442 } else if (old_root) {
1443 eb_root_owner = btrfs_header_owner(eb_root);
1444 btrfs_tree_read_unlock(eb_root);
1445 free_extent_buffer(eb_root);
1446 eb = alloc_dummy_extent_buffer(fs_info, logical);
1448 btrfs_set_lock_blocking_rw(eb_root, BTRFS_READ_LOCK);
1449 eb = btrfs_clone_extent_buffer(eb_root);
1450 btrfs_tree_read_unlock_blocking(eb_root);
1451 free_extent_buffer(eb_root);
1457 btrfs_set_header_bytenr(eb, eb->start);
1458 btrfs_set_header_backref_rev(eb, BTRFS_MIXED_BACKREF_REV);
1459 btrfs_set_header_owner(eb, eb_root_owner);
1460 btrfs_set_header_level(eb, old_root->level);
1461 btrfs_set_header_generation(eb, old_generation);
1463 btrfs_set_buffer_lockdep_class(btrfs_header_owner(eb), eb,
1464 btrfs_header_level(eb));
1465 btrfs_tree_read_lock(eb);
1467 __tree_mod_log_rewind(fs_info, eb, time_seq, tm);
1469 WARN_ON(btrfs_header_level(eb) != 0);
1470 WARN_ON(btrfs_header_nritems(eb) > BTRFS_NODEPTRS_PER_BLOCK(fs_info));
1475 int btrfs_old_root_level(struct btrfs_root *root, u64 time_seq)
1477 struct tree_mod_elem *tm;
1479 struct extent_buffer *eb_root = btrfs_root_node(root);
1481 tm = __tree_mod_log_oldest_root(eb_root, time_seq);
1482 if (tm && tm->op == MOD_LOG_ROOT_REPLACE) {
1483 level = tm->old_root.level;
1485 level = btrfs_header_level(eb_root);
1487 free_extent_buffer(eb_root);
1492 static inline int should_cow_block(struct btrfs_trans_handle *trans,
1493 struct btrfs_root *root,
1494 struct extent_buffer *buf)
1496 if (btrfs_is_testing(root->fs_info))
1499 /* Ensure we can see the FORCE_COW bit */
1500 smp_mb__before_atomic();
1503 * We do not need to cow a block if
1504 * 1) this block is not created or changed in this transaction;
1505 * 2) this block does not belong to TREE_RELOC tree;
1506 * 3) the root is not forced COW.
1508 * What is forced COW:
1509 * when we create snapshot during committing the transaction,
1510 * after we've finished coping src root, we must COW the shared
1511 * block to ensure the metadata consistency.
1513 if (btrfs_header_generation(buf) == trans->transid &&
1514 !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN) &&
1515 !(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
1516 btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)) &&
1517 !test_bit(BTRFS_ROOT_FORCE_COW, &root->state))
1523 * cows a single block, see __btrfs_cow_block for the real work.
1524 * This version of it has extra checks so that a block isn't COWed more than
1525 * once per transaction, as long as it hasn't been written yet
1527 noinline int btrfs_cow_block(struct btrfs_trans_handle *trans,
1528 struct btrfs_root *root, struct extent_buffer *buf,
1529 struct extent_buffer *parent, int parent_slot,
1530 struct extent_buffer **cow_ret)
1532 struct btrfs_fs_info *fs_info = root->fs_info;
1536 if (trans->transaction != fs_info->running_transaction)
1537 WARN(1, KERN_CRIT "trans %llu running %llu\n",
1539 fs_info->running_transaction->transid);
1541 if (trans->transid != fs_info->generation)
1542 WARN(1, KERN_CRIT "trans %llu running %llu\n",
1543 trans->transid, fs_info->generation);
1545 if (!should_cow_block(trans, root, buf)) {
1546 trans->dirty = true;
1551 search_start = buf->start & ~((u64)SZ_1G - 1);
1554 btrfs_set_lock_blocking(parent);
1555 btrfs_set_lock_blocking(buf);
1557 ret = __btrfs_cow_block(trans, root, buf, parent,
1558 parent_slot, cow_ret, search_start, 0);
1560 trace_btrfs_cow_block(root, buf, *cow_ret);
1566 * helper function for defrag to decide if two blocks pointed to by a
1567 * node are actually close by
1569 static int close_blocks(u64 blocknr, u64 other, u32 blocksize)
1571 if (blocknr < other && other - (blocknr + blocksize) < 32768)
1573 if (blocknr > other && blocknr - (other + blocksize) < 32768)
1579 * compare two keys in a memcmp fashion
1581 static int comp_keys(const struct btrfs_disk_key *disk,
1582 const struct btrfs_key *k2)
1584 struct btrfs_key k1;
1586 btrfs_disk_key_to_cpu(&k1, disk);
1588 return btrfs_comp_cpu_keys(&k1, k2);
1592 * same as comp_keys only with two btrfs_key's
1594 int btrfs_comp_cpu_keys(const struct btrfs_key *k1, const struct btrfs_key *k2)
1596 if (k1->objectid > k2->objectid)
1598 if (k1->objectid < k2->objectid)
1600 if (k1->type > k2->type)
1602 if (k1->type < k2->type)
1604 if (k1->offset > k2->offset)
1606 if (k1->offset < k2->offset)
1612 * this is used by the defrag code to go through all the
1613 * leaves pointed to by a node and reallocate them so that
1614 * disk order is close to key order
1616 int btrfs_realloc_node(struct btrfs_trans_handle *trans,
1617 struct btrfs_root *root, struct extent_buffer *parent,
1618 int start_slot, u64 *last_ret,
1619 struct btrfs_key *progress)
1621 struct btrfs_fs_info *fs_info = root->fs_info;
1622 struct extent_buffer *cur;
1625 u64 search_start = *last_ret;
1635 int progress_passed = 0;
1636 struct btrfs_disk_key disk_key;
1638 parent_level = btrfs_header_level(parent);
1640 WARN_ON(trans->transaction != fs_info->running_transaction);
1641 WARN_ON(trans->transid != fs_info->generation);
1643 parent_nritems = btrfs_header_nritems(parent);
1644 blocksize = fs_info->nodesize;
1645 end_slot = parent_nritems - 1;
1647 if (parent_nritems <= 1)
1650 btrfs_set_lock_blocking(parent);
1652 for (i = start_slot; i <= end_slot; i++) {
1653 struct btrfs_key first_key;
1656 btrfs_node_key(parent, &disk_key, i);
1657 if (!progress_passed && comp_keys(&disk_key, progress) < 0)
1660 progress_passed = 1;
1661 blocknr = btrfs_node_blockptr(parent, i);
1662 gen = btrfs_node_ptr_generation(parent, i);
1663 btrfs_node_key_to_cpu(parent, &first_key, i);
1664 if (last_block == 0)
1665 last_block = blocknr;
1668 other = btrfs_node_blockptr(parent, i - 1);
1669 close = close_blocks(blocknr, other, blocksize);
1671 if (!close && i < end_slot) {
1672 other = btrfs_node_blockptr(parent, i + 1);
1673 close = close_blocks(blocknr, other, blocksize);
1676 last_block = blocknr;
1680 cur = find_extent_buffer(fs_info, blocknr);
1682 uptodate = btrfs_buffer_uptodate(cur, gen, 0);
1685 if (!cur || !uptodate) {
1687 cur = read_tree_block(fs_info, blocknr, gen,
1691 return PTR_ERR(cur);
1692 } else if (!extent_buffer_uptodate(cur)) {
1693 free_extent_buffer(cur);
1696 } else if (!uptodate) {
1697 err = btrfs_read_buffer(cur, gen,
1698 parent_level - 1,&first_key);
1700 free_extent_buffer(cur);
1705 if (search_start == 0)
1706 search_start = last_block;
1708 btrfs_tree_lock(cur);
1709 btrfs_set_lock_blocking(cur);
1710 err = __btrfs_cow_block(trans, root, cur, parent, i,
1713 (end_slot - i) * blocksize));
1715 btrfs_tree_unlock(cur);
1716 free_extent_buffer(cur);
1719 search_start = cur->start;
1720 last_block = cur->start;
1721 *last_ret = search_start;
1722 btrfs_tree_unlock(cur);
1723 free_extent_buffer(cur);
1729 * search for key in the extent_buffer. The items start at offset p,
1730 * and they are item_size apart. There are 'max' items in p.
1732 * the slot in the array is returned via slot, and it points to
1733 * the place where you would insert key if it is not found in
1736 * slot may point to max if the key is bigger than all of the keys
1738 static noinline int generic_bin_search(struct extent_buffer *eb,
1739 unsigned long p, int item_size,
1740 const struct btrfs_key *key,
1747 struct btrfs_disk_key *tmp = NULL;
1748 struct btrfs_disk_key unaligned;
1749 unsigned long offset;
1751 unsigned long map_start = 0;
1752 unsigned long map_len = 0;
1756 btrfs_err(eb->fs_info,
1757 "%s: low (%d) > high (%d) eb %llu owner %llu level %d",
1758 __func__, low, high, eb->start,
1759 btrfs_header_owner(eb), btrfs_header_level(eb));
1763 while (low < high) {
1764 mid = (low + high) / 2;
1765 offset = p + mid * item_size;
1767 if (!kaddr || offset < map_start ||
1768 (offset + sizeof(struct btrfs_disk_key)) >
1769 map_start + map_len) {
1771 err = map_private_extent_buffer(eb, offset,
1772 sizeof(struct btrfs_disk_key),
1773 &kaddr, &map_start, &map_len);
1776 tmp = (struct btrfs_disk_key *)(kaddr + offset -
1778 } else if (err == 1) {
1779 read_extent_buffer(eb, &unaligned,
1780 offset, sizeof(unaligned));
1787 tmp = (struct btrfs_disk_key *)(kaddr + offset -
1790 ret = comp_keys(tmp, key);
1806 * simple bin_search frontend that does the right thing for
1809 int btrfs_bin_search(struct extent_buffer *eb, const struct btrfs_key *key,
1810 int level, int *slot)
1813 return generic_bin_search(eb,
1814 offsetof(struct btrfs_leaf, items),
1815 sizeof(struct btrfs_item),
1816 key, btrfs_header_nritems(eb),
1819 return generic_bin_search(eb,
1820 offsetof(struct btrfs_node, ptrs),
1821 sizeof(struct btrfs_key_ptr),
1822 key, btrfs_header_nritems(eb),
1826 static void root_add_used(struct btrfs_root *root, u32 size)
1828 spin_lock(&root->accounting_lock);
1829 btrfs_set_root_used(&root->root_item,
1830 btrfs_root_used(&root->root_item) + size);
1831 spin_unlock(&root->accounting_lock);
1834 static void root_sub_used(struct btrfs_root *root, u32 size)
1836 spin_lock(&root->accounting_lock);
1837 btrfs_set_root_used(&root->root_item,
1838 btrfs_root_used(&root->root_item) - size);
1839 spin_unlock(&root->accounting_lock);
1842 /* given a node and slot number, this reads the blocks it points to. The
1843 * extent buffer is returned with a reference taken (but unlocked).
1845 static noinline struct extent_buffer *
1846 read_node_slot(struct btrfs_fs_info *fs_info, struct extent_buffer *parent,
1849 int level = btrfs_header_level(parent);
1850 struct extent_buffer *eb;
1851 struct btrfs_key first_key;
1853 if (slot < 0 || slot >= btrfs_header_nritems(parent))
1854 return ERR_PTR(-ENOENT);
1858 btrfs_node_key_to_cpu(parent, &first_key, slot);
1859 eb = read_tree_block(fs_info, btrfs_node_blockptr(parent, slot),
1860 btrfs_node_ptr_generation(parent, slot),
1861 level - 1, &first_key);
1862 if (!IS_ERR(eb) && !extent_buffer_uptodate(eb)) {
1863 free_extent_buffer(eb);
1871 * node level balancing, used to make sure nodes are in proper order for
1872 * item deletion. We balance from the top down, so we have to make sure
1873 * that a deletion won't leave an node completely empty later on.
1875 static noinline int balance_level(struct btrfs_trans_handle *trans,
1876 struct btrfs_root *root,
1877 struct btrfs_path *path, int level)
1879 struct btrfs_fs_info *fs_info = root->fs_info;
1880 struct extent_buffer *right = NULL;
1881 struct extent_buffer *mid;
1882 struct extent_buffer *left = NULL;
1883 struct extent_buffer *parent = NULL;
1887 int orig_slot = path->slots[level];
1893 mid = path->nodes[level];
1895 WARN_ON(path->locks[level] != BTRFS_WRITE_LOCK &&
1896 path->locks[level] != BTRFS_WRITE_LOCK_BLOCKING);
1897 WARN_ON(btrfs_header_generation(mid) != trans->transid);
1899 orig_ptr = btrfs_node_blockptr(mid, orig_slot);
1901 if (level < BTRFS_MAX_LEVEL - 1) {
1902 parent = path->nodes[level + 1];
1903 pslot = path->slots[level + 1];
1907 * deal with the case where there is only one pointer in the root
1908 * by promoting the node below to a root
1911 struct extent_buffer *child;
1913 if (btrfs_header_nritems(mid) != 1)
1916 /* promote the child to a root */
1917 child = read_node_slot(fs_info, mid, 0);
1918 if (IS_ERR(child)) {
1919 ret = PTR_ERR(child);
1920 btrfs_handle_fs_error(fs_info, ret, NULL);
1924 btrfs_tree_lock(child);
1925 btrfs_set_lock_blocking(child);
1926 ret = btrfs_cow_block(trans, root, child, mid, 0, &child);
1928 btrfs_tree_unlock(child);
1929 free_extent_buffer(child);
1933 ret = tree_mod_log_insert_root(root->node, child, 1);
1935 rcu_assign_pointer(root->node, child);
1937 add_root_to_dirty_list(root);
1938 btrfs_tree_unlock(child);
1940 path->locks[level] = 0;
1941 path->nodes[level] = NULL;
1942 clean_tree_block(fs_info, mid);
1943 btrfs_tree_unlock(mid);
1944 /* once for the path */
1945 free_extent_buffer(mid);
1947 root_sub_used(root, mid->len);
1948 btrfs_free_tree_block(trans, root, mid, 0, 1);
1949 /* once for the root ptr */
1950 free_extent_buffer_stale(mid);
1953 if (btrfs_header_nritems(mid) >
1954 BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 4)
1957 left = read_node_slot(fs_info, parent, pslot - 1);
1962 btrfs_tree_lock(left);
1963 btrfs_set_lock_blocking(left);
1964 wret = btrfs_cow_block(trans, root, left,
1965 parent, pslot - 1, &left);
1972 right = read_node_slot(fs_info, parent, pslot + 1);
1977 btrfs_tree_lock(right);
1978 btrfs_set_lock_blocking(right);
1979 wret = btrfs_cow_block(trans, root, right,
1980 parent, pslot + 1, &right);
1987 /* first, try to make some room in the middle buffer */
1989 orig_slot += btrfs_header_nritems(left);
1990 wret = push_node_left(trans, fs_info, left, mid, 1);
1996 * then try to empty the right most buffer into the middle
1999 wret = push_node_left(trans, fs_info, mid, right, 1);
2000 if (wret < 0 && wret != -ENOSPC)
2002 if (btrfs_header_nritems(right) == 0) {
2003 clean_tree_block(fs_info, right);
2004 btrfs_tree_unlock(right);
2005 del_ptr(root, path, level + 1, pslot + 1);
2006 root_sub_used(root, right->len);
2007 btrfs_free_tree_block(trans, root, right, 0, 1);
2008 free_extent_buffer_stale(right);
2011 struct btrfs_disk_key right_key;
2012 btrfs_node_key(right, &right_key, 0);
2013 ret = tree_mod_log_insert_key(parent, pslot + 1,
2014 MOD_LOG_KEY_REPLACE, GFP_NOFS);
2016 btrfs_set_node_key(parent, &right_key, pslot + 1);
2017 btrfs_mark_buffer_dirty(parent);
2020 if (btrfs_header_nritems(mid) == 1) {
2022 * we're not allowed to leave a node with one item in the
2023 * tree during a delete. A deletion from lower in the tree
2024 * could try to delete the only pointer in this node.
2025 * So, pull some keys from the left.
2026 * There has to be a left pointer at this point because
2027 * otherwise we would have pulled some pointers from the
2032 btrfs_handle_fs_error(fs_info, ret, NULL);
2035 wret = balance_node_right(trans, fs_info, mid, left);
2041 wret = push_node_left(trans, fs_info, left, mid, 1);
2047 if (btrfs_header_nritems(mid) == 0) {
2048 clean_tree_block(fs_info, mid);
2049 btrfs_tree_unlock(mid);
2050 del_ptr(root, path, level + 1, pslot);
2051 root_sub_used(root, mid->len);
2052 btrfs_free_tree_block(trans, root, mid, 0, 1);
2053 free_extent_buffer_stale(mid);
2056 /* update the parent key to reflect our changes */
2057 struct btrfs_disk_key mid_key;
2058 btrfs_node_key(mid, &mid_key, 0);
2059 ret = tree_mod_log_insert_key(parent, pslot,
2060 MOD_LOG_KEY_REPLACE, GFP_NOFS);
2062 btrfs_set_node_key(parent, &mid_key, pslot);
2063 btrfs_mark_buffer_dirty(parent);
2066 /* update the path */
2068 if (btrfs_header_nritems(left) > orig_slot) {
2069 extent_buffer_get(left);
2070 /* left was locked after cow */
2071 path->nodes[level] = left;
2072 path->slots[level + 1] -= 1;
2073 path->slots[level] = orig_slot;
2075 btrfs_tree_unlock(mid);
2076 free_extent_buffer(mid);
2079 orig_slot -= btrfs_header_nritems(left);
2080 path->slots[level] = orig_slot;
2083 /* double check we haven't messed things up */
2085 btrfs_node_blockptr(path->nodes[level], path->slots[level]))
2089 btrfs_tree_unlock(right);
2090 free_extent_buffer(right);
2093 if (path->nodes[level] != left)
2094 btrfs_tree_unlock(left);
2095 free_extent_buffer(left);
2100 /* Node balancing for insertion. Here we only split or push nodes around
2101 * when they are completely full. This is also done top down, so we
2102 * have to be pessimistic.
2104 static noinline int push_nodes_for_insert(struct btrfs_trans_handle *trans,
2105 struct btrfs_root *root,
2106 struct btrfs_path *path, int level)
2108 struct btrfs_fs_info *fs_info = root->fs_info;
2109 struct extent_buffer *right = NULL;
2110 struct extent_buffer *mid;
2111 struct extent_buffer *left = NULL;
2112 struct extent_buffer *parent = NULL;
2116 int orig_slot = path->slots[level];
2121 mid = path->nodes[level];
2122 WARN_ON(btrfs_header_generation(mid) != trans->transid);
2124 if (level < BTRFS_MAX_LEVEL - 1) {
2125 parent = path->nodes[level + 1];
2126 pslot = path->slots[level + 1];
2132 left = read_node_slot(fs_info, parent, pslot - 1);
2136 /* first, try to make some room in the middle buffer */
2140 btrfs_tree_lock(left);
2141 btrfs_set_lock_blocking(left);
2143 left_nr = btrfs_header_nritems(left);
2144 if (left_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
2147 ret = btrfs_cow_block(trans, root, left, parent,
2152 wret = push_node_left(trans, fs_info,
2159 struct btrfs_disk_key disk_key;
2160 orig_slot += left_nr;
2161 btrfs_node_key(mid, &disk_key, 0);
2162 ret = tree_mod_log_insert_key(parent, pslot,
2163 MOD_LOG_KEY_REPLACE, GFP_NOFS);
2165 btrfs_set_node_key(parent, &disk_key, pslot);
2166 btrfs_mark_buffer_dirty(parent);
2167 if (btrfs_header_nritems(left) > orig_slot) {
2168 path->nodes[level] = left;
2169 path->slots[level + 1] -= 1;
2170 path->slots[level] = orig_slot;
2171 btrfs_tree_unlock(mid);
2172 free_extent_buffer(mid);
2175 btrfs_header_nritems(left);
2176 path->slots[level] = orig_slot;
2177 btrfs_tree_unlock(left);
2178 free_extent_buffer(left);
2182 btrfs_tree_unlock(left);
2183 free_extent_buffer(left);
2185 right = read_node_slot(fs_info, parent, pslot + 1);
2190 * then try to empty the right most buffer into the middle
2195 btrfs_tree_lock(right);
2196 btrfs_set_lock_blocking(right);
2198 right_nr = btrfs_header_nritems(right);
2199 if (right_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
2202 ret = btrfs_cow_block(trans, root, right,
2208 wret = balance_node_right(trans, fs_info,
2215 struct btrfs_disk_key disk_key;
2217 btrfs_node_key(right, &disk_key, 0);
2218 ret = tree_mod_log_insert_key(parent, pslot + 1,
2219 MOD_LOG_KEY_REPLACE, GFP_NOFS);
2221 btrfs_set_node_key(parent, &disk_key, pslot + 1);
2222 btrfs_mark_buffer_dirty(parent);
2224 if (btrfs_header_nritems(mid) <= orig_slot) {
2225 path->nodes[level] = right;
2226 path->slots[level + 1] += 1;
2227 path->slots[level] = orig_slot -
2228 btrfs_header_nritems(mid);
2229 btrfs_tree_unlock(mid);
2230 free_extent_buffer(mid);
2232 btrfs_tree_unlock(right);
2233 free_extent_buffer(right);
2237 btrfs_tree_unlock(right);
2238 free_extent_buffer(right);
2244 * readahead one full node of leaves, finding things that are close
2245 * to the block in 'slot', and triggering ra on them.
2247 static void reada_for_search(struct btrfs_fs_info *fs_info,
2248 struct btrfs_path *path,
2249 int level, int slot, u64 objectid)
2251 struct extent_buffer *node;
2252 struct btrfs_disk_key disk_key;
2257 struct extent_buffer *eb;
2265 if (!path->nodes[level])
2268 node = path->nodes[level];
2270 search = btrfs_node_blockptr(node, slot);
2271 blocksize = fs_info->nodesize;
2272 eb = find_extent_buffer(fs_info, search);
2274 free_extent_buffer(eb);
2280 nritems = btrfs_header_nritems(node);
2284 if (path->reada == READA_BACK) {
2288 } else if (path->reada == READA_FORWARD) {
2293 if (path->reada == READA_BACK && objectid) {
2294 btrfs_node_key(node, &disk_key, nr);
2295 if (btrfs_disk_key_objectid(&disk_key) != objectid)
2298 search = btrfs_node_blockptr(node, nr);
2299 if ((search <= target && target - search <= 65536) ||
2300 (search > target && search - target <= 65536)) {
2301 readahead_tree_block(fs_info, search);
2305 if ((nread > 65536 || nscan > 32))
2310 static noinline void reada_for_balance(struct btrfs_fs_info *fs_info,
2311 struct btrfs_path *path, int level)
2315 struct extent_buffer *parent;
2316 struct extent_buffer *eb;
2321 parent = path->nodes[level + 1];
2325 nritems = btrfs_header_nritems(parent);
2326 slot = path->slots[level + 1];
2329 block1 = btrfs_node_blockptr(parent, slot - 1);
2330 gen = btrfs_node_ptr_generation(parent, slot - 1);
2331 eb = find_extent_buffer(fs_info, block1);
2333 * if we get -eagain from btrfs_buffer_uptodate, we
2334 * don't want to return eagain here. That will loop
2337 if (eb && btrfs_buffer_uptodate(eb, gen, 1) != 0)
2339 free_extent_buffer(eb);
2341 if (slot + 1 < nritems) {
2342 block2 = btrfs_node_blockptr(parent, slot + 1);
2343 gen = btrfs_node_ptr_generation(parent, slot + 1);
2344 eb = find_extent_buffer(fs_info, block2);
2345 if (eb && btrfs_buffer_uptodate(eb, gen, 1) != 0)
2347 free_extent_buffer(eb);
2351 readahead_tree_block(fs_info, block1);
2353 readahead_tree_block(fs_info, block2);
2358 * when we walk down the tree, it is usually safe to unlock the higher layers
2359 * in the tree. The exceptions are when our path goes through slot 0, because
2360 * operations on the tree might require changing key pointers higher up in the
2363 * callers might also have set path->keep_locks, which tells this code to keep
2364 * the lock if the path points to the last slot in the block. This is part of
2365 * walking through the tree, and selecting the next slot in the higher block.
2367 * lowest_unlock sets the lowest level in the tree we're allowed to unlock. so
2368 * if lowest_unlock is 1, level 0 won't be unlocked
2370 static noinline void unlock_up(struct btrfs_path *path, int level,
2371 int lowest_unlock, int min_write_lock_level,
2372 int *write_lock_level)
2375 int skip_level = level;
2377 struct extent_buffer *t;
2379 for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2380 if (!path->nodes[i])
2382 if (!path->locks[i])
2384 if (!no_skips && path->slots[i] == 0) {
2388 if (!no_skips && path->keep_locks) {
2391 nritems = btrfs_header_nritems(t);
2392 if (nritems < 1 || path->slots[i] >= nritems - 1) {
2397 if (skip_level < i && i >= lowest_unlock)
2401 if (i >= lowest_unlock && i > skip_level) {
2402 btrfs_tree_unlock_rw(t, path->locks[i]);
2404 if (write_lock_level &&
2405 i > min_write_lock_level &&
2406 i <= *write_lock_level) {
2407 *write_lock_level = i - 1;
2414 * This releases any locks held in the path starting at level and
2415 * going all the way up to the root.
2417 * btrfs_search_slot will keep the lock held on higher nodes in a few
2418 * corner cases, such as COW of the block at slot zero in the node. This
2419 * ignores those rules, and it should only be called when there are no
2420 * more updates to be done higher up in the tree.
2422 noinline void btrfs_unlock_up_safe(struct btrfs_path *path, int level)
2426 if (path->keep_locks)
2429 for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2430 if (!path->nodes[i])
2432 if (!path->locks[i])
2434 btrfs_tree_unlock_rw(path->nodes[i], path->locks[i]);
2440 * helper function for btrfs_search_slot. The goal is to find a block
2441 * in cache without setting the path to blocking. If we find the block
2442 * we return zero and the path is unchanged.
2444 * If we can't find the block, we set the path blocking and do some
2445 * reada. -EAGAIN is returned and the search must be repeated.
2448 read_block_for_search(struct btrfs_root *root, struct btrfs_path *p,
2449 struct extent_buffer **eb_ret, int level, int slot,
2450 const struct btrfs_key *key)
2452 struct btrfs_fs_info *fs_info = root->fs_info;
2455 struct extent_buffer *b = *eb_ret;
2456 struct extent_buffer *tmp;
2457 struct btrfs_key first_key;
2461 blocknr = btrfs_node_blockptr(b, slot);
2462 gen = btrfs_node_ptr_generation(b, slot);
2463 parent_level = btrfs_header_level(b);
2464 btrfs_node_key_to_cpu(b, &first_key, slot);
2466 tmp = find_extent_buffer(fs_info, blocknr);
2468 /* first we do an atomic uptodate check */
2469 if (btrfs_buffer_uptodate(tmp, gen, 1) > 0) {
2471 * Do extra check for first_key, eb can be stale due to
2472 * being cached, read from scrub, or have multiple
2473 * parents (shared tree blocks).
2475 if (btrfs_verify_level_key(fs_info, tmp,
2476 parent_level - 1, &first_key, gen)) {
2477 free_extent_buffer(tmp);
2484 /* the pages were up to date, but we failed
2485 * the generation number check. Do a full
2486 * read for the generation number that is correct.
2487 * We must do this without dropping locks so
2488 * we can trust our generation number
2490 btrfs_set_path_blocking(p);
2492 /* now we're allowed to do a blocking uptodate check */
2493 ret = btrfs_read_buffer(tmp, gen, parent_level - 1, &first_key);
2498 free_extent_buffer(tmp);
2499 btrfs_release_path(p);
2504 * reduce lock contention at high levels
2505 * of the btree by dropping locks before
2506 * we read. Don't release the lock on the current
2507 * level because we need to walk this node to figure
2508 * out which blocks to read.
2510 btrfs_unlock_up_safe(p, level + 1);
2511 btrfs_set_path_blocking(p);
2513 if (p->reada != READA_NONE)
2514 reada_for_search(fs_info, p, level, slot, key->objectid);
2517 tmp = read_tree_block(fs_info, blocknr, gen, parent_level - 1,
2521 * If the read above didn't mark this buffer up to date,
2522 * it will never end up being up to date. Set ret to EIO now
2523 * and give up so that our caller doesn't loop forever
2526 if (!extent_buffer_uptodate(tmp))
2528 free_extent_buffer(tmp);
2533 btrfs_release_path(p);
2538 * helper function for btrfs_search_slot. This does all of the checks
2539 * for node-level blocks and does any balancing required based on
2542 * If no extra work was required, zero is returned. If we had to
2543 * drop the path, -EAGAIN is returned and btrfs_search_slot must
2547 setup_nodes_for_search(struct btrfs_trans_handle *trans,
2548 struct btrfs_root *root, struct btrfs_path *p,
2549 struct extent_buffer *b, int level, int ins_len,
2550 int *write_lock_level)
2552 struct btrfs_fs_info *fs_info = root->fs_info;
2555 if ((p->search_for_split || ins_len > 0) && btrfs_header_nritems(b) >=
2556 BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3) {
2559 if (*write_lock_level < level + 1) {
2560 *write_lock_level = level + 1;
2561 btrfs_release_path(p);
2565 btrfs_set_path_blocking(p);
2566 reada_for_balance(fs_info, p, level);
2567 sret = split_node(trans, root, p, level);
2568 btrfs_clear_path_blocking(p, NULL, 0);
2575 b = p->nodes[level];
2576 } else if (ins_len < 0 && btrfs_header_nritems(b) <
2577 BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 2) {
2580 if (*write_lock_level < level + 1) {
2581 *write_lock_level = level + 1;
2582 btrfs_release_path(p);
2586 btrfs_set_path_blocking(p);
2587 reada_for_balance(fs_info, p, level);
2588 sret = balance_level(trans, root, p, level);
2589 btrfs_clear_path_blocking(p, NULL, 0);
2595 b = p->nodes[level];
2597 btrfs_release_path(p);
2600 BUG_ON(btrfs_header_nritems(b) == 1);
2610 static void key_search_validate(struct extent_buffer *b,
2611 const struct btrfs_key *key,
2614 #ifdef CONFIG_BTRFS_ASSERT
2615 struct btrfs_disk_key disk_key;
2617 btrfs_cpu_key_to_disk(&disk_key, key);
2620 ASSERT(!memcmp_extent_buffer(b, &disk_key,
2621 offsetof(struct btrfs_leaf, items[0].key),
2624 ASSERT(!memcmp_extent_buffer(b, &disk_key,
2625 offsetof(struct btrfs_node, ptrs[0].key),
2630 static int key_search(struct extent_buffer *b, const struct btrfs_key *key,
2631 int level, int *prev_cmp, int *slot)
2633 if (*prev_cmp != 0) {
2634 *prev_cmp = btrfs_bin_search(b, key, level, slot);
2638 key_search_validate(b, key, level);
2644 int btrfs_find_item(struct btrfs_root *fs_root, struct btrfs_path *path,
2645 u64 iobjectid, u64 ioff, u8 key_type,
2646 struct btrfs_key *found_key)
2649 struct btrfs_key key;
2650 struct extent_buffer *eb;
2655 key.type = key_type;
2656 key.objectid = iobjectid;
2659 ret = btrfs_search_slot(NULL, fs_root, &key, path, 0, 0);
2663 eb = path->nodes[0];
2664 if (ret && path->slots[0] >= btrfs_header_nritems(eb)) {
2665 ret = btrfs_next_leaf(fs_root, path);
2668 eb = path->nodes[0];
2671 btrfs_item_key_to_cpu(eb, found_key, path->slots[0]);
2672 if (found_key->type != key.type ||
2673 found_key->objectid != key.objectid)
2679 static struct extent_buffer *btrfs_search_slot_get_root(struct btrfs_root *root,
2680 struct btrfs_path *p,
2681 int write_lock_level)
2683 struct btrfs_fs_info *fs_info = root->fs_info;
2684 struct extent_buffer *b;
2688 /* We try very hard to do read locks on the root */
2689 root_lock = BTRFS_READ_LOCK;
2691 if (p->search_commit_root) {
2693 * The commit roots are read only so we always do read locks,
2694 * and we always must hold the commit_root_sem when doing
2695 * searches on them, the only exception is send where we don't
2696 * want to block transaction commits for a long time, so
2697 * we need to clone the commit root in order to avoid races
2698 * with transaction commits that create a snapshot of one of
2699 * the roots used by a send operation.
2701 if (p->need_commit_sem) {
2702 down_read(&fs_info->commit_root_sem);
2703 b = btrfs_clone_extent_buffer(root->commit_root);
2704 up_read(&fs_info->commit_root_sem);
2706 return ERR_PTR(-ENOMEM);
2709 b = root->commit_root;
2710 extent_buffer_get(b);
2712 level = btrfs_header_level(b);
2714 * Ensure that all callers have set skip_locking when
2715 * p->search_commit_root = 1.
2717 ASSERT(p->skip_locking == 1);
2722 if (p->skip_locking) {
2723 b = btrfs_root_node(root);
2724 level = btrfs_header_level(b);
2729 * If the level is set to maximum, we can skip trying to get the read
2732 if (write_lock_level < BTRFS_MAX_LEVEL) {
2734 * We don't know the level of the root node until we actually
2735 * have it read locked
2737 b = btrfs_read_lock_root_node(root);
2738 level = btrfs_header_level(b);
2739 if (level > write_lock_level)
2742 /* Whoops, must trade for write lock */
2743 btrfs_tree_read_unlock(b);
2744 free_extent_buffer(b);
2747 b = btrfs_lock_root_node(root);
2748 root_lock = BTRFS_WRITE_LOCK;
2750 /* The level might have changed, check again */
2751 level = btrfs_header_level(b);
2754 p->nodes[level] = b;
2755 if (!p->skip_locking)
2756 p->locks[level] = root_lock;
2758 * Callers are responsible for dropping b's references.
2765 * btrfs_search_slot - look for a key in a tree and perform necessary
2766 * modifications to preserve tree invariants.
2768 * @trans: Handle of transaction, used when modifying the tree
2769 * @p: Holds all btree nodes along the search path
2770 * @root: The root node of the tree
2771 * @key: The key we are looking for
2772 * @ins_len: Indicates purpose of search, for inserts it is 1, for
2773 * deletions it's -1. 0 for plain searches
2774 * @cow: boolean should CoW operations be performed. Must always be 1
2775 * when modifying the tree.
2777 * If @ins_len > 0, nodes and leaves will be split as we walk down the tree.
2778 * If @ins_len < 0, nodes will be merged as we walk down the tree (if possible)
2780 * If @key is found, 0 is returned and you can find the item in the leaf level
2781 * of the path (level 0)
2783 * If @key isn't found, 1 is returned and the leaf level of the path (level 0)
2784 * points to the slot where it should be inserted
2786 * If an error is encountered while searching the tree a negative error number
2789 int btrfs_search_slot(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2790 const struct btrfs_key *key, struct btrfs_path *p,
2791 int ins_len, int cow)
2793 struct btrfs_fs_info *fs_info = root->fs_info;
2794 struct extent_buffer *b;
2799 int lowest_unlock = 1;
2800 /* everything at write_lock_level or lower must be write locked */
2801 int write_lock_level = 0;
2802 u8 lowest_level = 0;
2803 int min_write_lock_level;
2806 lowest_level = p->lowest_level;
2807 WARN_ON(lowest_level && ins_len > 0);
2808 WARN_ON(p->nodes[0] != NULL);
2809 BUG_ON(!cow && ins_len);
2814 /* when we are removing items, we might have to go up to level
2815 * two as we update tree pointers Make sure we keep write
2816 * for those levels as well
2818 write_lock_level = 2;
2819 } else if (ins_len > 0) {
2821 * for inserting items, make sure we have a write lock on
2822 * level 1 so we can update keys
2824 write_lock_level = 1;
2828 write_lock_level = -1;
2830 if (cow && (p->keep_locks || p->lowest_level))
2831 write_lock_level = BTRFS_MAX_LEVEL;
2833 min_write_lock_level = write_lock_level;
2837 b = btrfs_search_slot_get_root(root, p, write_lock_level);
2844 level = btrfs_header_level(b);
2847 * setup the path here so we can release it under lock
2848 * contention with the cow code
2851 bool last_level = (level == (BTRFS_MAX_LEVEL - 1));
2854 * if we don't really need to cow this block
2855 * then we don't want to set the path blocking,
2856 * so we test it here
2858 if (!should_cow_block(trans, root, b)) {
2859 trans->dirty = true;
2864 * must have write locks on this node and the
2867 if (level > write_lock_level ||
2868 (level + 1 > write_lock_level &&
2869 level + 1 < BTRFS_MAX_LEVEL &&
2870 p->nodes[level + 1])) {
2871 write_lock_level = level + 1;
2872 btrfs_release_path(p);
2876 btrfs_set_path_blocking(p);
2878 err = btrfs_cow_block(trans, root, b, NULL, 0,
2881 err = btrfs_cow_block(trans, root, b,
2882 p->nodes[level + 1],
2883 p->slots[level + 1], &b);
2890 p->nodes[level] = b;
2891 btrfs_clear_path_blocking(p, NULL, 0);
2894 * we have a lock on b and as long as we aren't changing
2895 * the tree, there is no way to for the items in b to change.
2896 * It is safe to drop the lock on our parent before we
2897 * go through the expensive btree search on b.
2899 * If we're inserting or deleting (ins_len != 0), then we might
2900 * be changing slot zero, which may require changing the parent.
2901 * So, we can't drop the lock until after we know which slot
2902 * we're operating on.
2904 if (!ins_len && !p->keep_locks) {
2907 if (u < BTRFS_MAX_LEVEL && p->locks[u]) {
2908 btrfs_tree_unlock_rw(p->nodes[u], p->locks[u]);
2913 ret = key_search(b, key, level, &prev_cmp, &slot);
2919 if (ret && slot > 0) {
2923 p->slots[level] = slot;
2924 err = setup_nodes_for_search(trans, root, p, b, level,
2925 ins_len, &write_lock_level);
2932 b = p->nodes[level];
2933 slot = p->slots[level];
2936 * slot 0 is special, if we change the key
2937 * we have to update the parent pointer
2938 * which means we must have a write lock
2941 if (slot == 0 && ins_len &&
2942 write_lock_level < level + 1) {
2943 write_lock_level = level + 1;
2944 btrfs_release_path(p);
2948 unlock_up(p, level, lowest_unlock,
2949 min_write_lock_level, &write_lock_level);
2951 if (level == lowest_level) {
2957 err = read_block_for_search(root, p, &b, level,
2966 if (!p->skip_locking) {
2967 level = btrfs_header_level(b);
2968 if (level <= write_lock_level) {
2969 err = btrfs_try_tree_write_lock(b);
2971 btrfs_set_path_blocking(p);
2973 btrfs_clear_path_blocking(p, b,
2976 p->locks[level] = BTRFS_WRITE_LOCK;
2978 err = btrfs_tree_read_lock_atomic(b);
2980 btrfs_set_path_blocking(p);
2981 btrfs_tree_read_lock(b);
2982 btrfs_clear_path_blocking(p, b,
2985 p->locks[level] = BTRFS_READ_LOCK;
2987 p->nodes[level] = b;
2990 p->slots[level] = slot;
2992 btrfs_leaf_free_space(fs_info, b) < ins_len) {
2993 if (write_lock_level < 1) {
2994 write_lock_level = 1;
2995 btrfs_release_path(p);
2999 btrfs_set_path_blocking(p);
3000 err = split_leaf(trans, root, key,
3001 p, ins_len, ret == 0);
3002 btrfs_clear_path_blocking(p, NULL, 0);
3010 if (!p->search_for_split)
3011 unlock_up(p, level, lowest_unlock,
3012 min_write_lock_level, &write_lock_level);
3019 * we don't really know what they plan on doing with the path
3020 * from here on, so for now just mark it as blocking
3022 if (!p->leave_spinning)
3023 btrfs_set_path_blocking(p);
3024 if (ret < 0 && !p->skip_release_on_error)
3025 btrfs_release_path(p);
3030 * Like btrfs_search_slot, this looks for a key in the given tree. It uses the
3031 * current state of the tree together with the operations recorded in the tree
3032 * modification log to search for the key in a previous version of this tree, as
3033 * denoted by the time_seq parameter.
3035 * Naturally, there is no support for insert, delete or cow operations.
3037 * The resulting path and return value will be set up as if we called
3038 * btrfs_search_slot at that point in time with ins_len and cow both set to 0.
3040 int btrfs_search_old_slot(struct btrfs_root *root, const struct btrfs_key *key,
3041 struct btrfs_path *p, u64 time_seq)
3043 struct btrfs_fs_info *fs_info = root->fs_info;
3044 struct extent_buffer *b;
3049 int lowest_unlock = 1;
3050 u8 lowest_level = 0;
3053 lowest_level = p->lowest_level;
3054 WARN_ON(p->nodes[0] != NULL);
3056 if (p->search_commit_root) {
3058 return btrfs_search_slot(NULL, root, key, p, 0, 0);
3062 b = get_old_root(root, time_seq);
3067 level = btrfs_header_level(b);
3068 p->locks[level] = BTRFS_READ_LOCK;
3071 level = btrfs_header_level(b);
3072 p->nodes[level] = b;
3073 btrfs_clear_path_blocking(p, NULL, 0);
3076 * we have a lock on b and as long as we aren't changing
3077 * the tree, there is no way to for the items in b to change.
3078 * It is safe to drop the lock on our parent before we
3079 * go through the expensive btree search on b.
3081 btrfs_unlock_up_safe(p, level + 1);
3084 * Since we can unwind ebs we want to do a real search every
3088 ret = key_search(b, key, level, &prev_cmp, &slot);
3092 if (ret && slot > 0) {
3096 p->slots[level] = slot;
3097 unlock_up(p, level, lowest_unlock, 0, NULL);
3099 if (level == lowest_level) {
3105 err = read_block_for_search(root, p, &b, level,
3114 level = btrfs_header_level(b);
3115 err = btrfs_tree_read_lock_atomic(b);
3117 btrfs_set_path_blocking(p);
3118 btrfs_tree_read_lock(b);
3119 btrfs_clear_path_blocking(p, b,
3122 b = tree_mod_log_rewind(fs_info, p, b, time_seq);
3127 p->locks[level] = BTRFS_READ_LOCK;
3128 p->nodes[level] = b;
3130 p->slots[level] = slot;
3131 unlock_up(p, level, lowest_unlock, 0, NULL);
3137 if (!p->leave_spinning)
3138 btrfs_set_path_blocking(p);
3140 btrfs_release_path(p);
3146 * helper to use instead of search slot if no exact match is needed but
3147 * instead the next or previous item should be returned.
3148 * When find_higher is true, the next higher item is returned, the next lower
3150 * When return_any and find_higher are both true, and no higher item is found,
3151 * return the next lower instead.
3152 * When return_any is true and find_higher is false, and no lower item is found,
3153 * return the next higher instead.
3154 * It returns 0 if any item is found, 1 if none is found (tree empty), and
3157 int btrfs_search_slot_for_read(struct btrfs_root *root,
3158 const struct btrfs_key *key,
3159 struct btrfs_path *p, int find_higher,
3163 struct extent_buffer *leaf;
3166 ret = btrfs_search_slot(NULL, root, key, p, 0, 0);
3170 * a return value of 1 means the path is at the position where the
3171 * item should be inserted. Normally this is the next bigger item,
3172 * but in case the previous item is the last in a leaf, path points
3173 * to the first free slot in the previous leaf, i.e. at an invalid
3179 if (p->slots[0] >= btrfs_header_nritems(leaf)) {
3180 ret = btrfs_next_leaf(root, p);
3186 * no higher item found, return the next
3191 btrfs_release_path(p);
3195 if (p->slots[0] == 0) {
3196 ret = btrfs_prev_leaf(root, p);
3201 if (p->slots[0] == btrfs_header_nritems(leaf))
3208 * no lower item found, return the next
3213 btrfs_release_path(p);
3223 * adjust the pointers going up the tree, starting at level
3224 * making sure the right key of each node is points to 'key'.
3225 * This is used after shifting pointers to the left, so it stops
3226 * fixing up pointers when a given leaf/node is not in slot 0 of the
3230 static void fixup_low_keys(struct btrfs_path *path,
3231 struct btrfs_disk_key *key, int level)
3234 struct extent_buffer *t;
3237 for (i = level; i < BTRFS_MAX_LEVEL; i++) {
3238 int tslot = path->slots[i];
3240 if (!path->nodes[i])
3243 ret = tree_mod_log_insert_key(t, tslot, MOD_LOG_KEY_REPLACE,
3246 btrfs_set_node_key(t, key, tslot);
3247 btrfs_mark_buffer_dirty(path->nodes[i]);
3256 * This function isn't completely safe. It's the caller's responsibility
3257 * that the new key won't break the order
3259 void btrfs_set_item_key_safe(struct btrfs_fs_info *fs_info,
3260 struct btrfs_path *path,
3261 const struct btrfs_key *new_key)
3263 struct btrfs_disk_key disk_key;
3264 struct extent_buffer *eb;
3267 eb = path->nodes[0];
3268 slot = path->slots[0];
3270 btrfs_item_key(eb, &disk_key, slot - 1);
3271 BUG_ON(comp_keys(&disk_key, new_key) >= 0);
3273 if (slot < btrfs_header_nritems(eb) - 1) {
3274 btrfs_item_key(eb, &disk_key, slot + 1);
3275 BUG_ON(comp_keys(&disk_key, new_key) <= 0);
3278 btrfs_cpu_key_to_disk(&disk_key, new_key);
3279 btrfs_set_item_key(eb, &disk_key, slot);
3280 btrfs_mark_buffer_dirty(eb);
3282 fixup_low_keys(path, &disk_key, 1);
3286 * try to push data from one node into the next node left in the
3289 * returns 0 if some ptrs were pushed left, < 0 if there was some horrible
3290 * error, and > 0 if there was no room in the left hand block.
3292 static int push_node_left(struct btrfs_trans_handle *trans,
3293 struct btrfs_fs_info *fs_info,
3294 struct extent_buffer *dst,
3295 struct extent_buffer *src, int empty)
3302 src_nritems = btrfs_header_nritems(src);
3303 dst_nritems = btrfs_header_nritems(dst);
3304 push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
3305 WARN_ON(btrfs_header_generation(src) != trans->transid);
3306 WARN_ON(btrfs_header_generation(dst) != trans->transid);
3308 if (!empty && src_nritems <= 8)
3311 if (push_items <= 0)
3315 push_items = min(src_nritems, push_items);
3316 if (push_items < src_nritems) {
3317 /* leave at least 8 pointers in the node if
3318 * we aren't going to empty it
3320 if (src_nritems - push_items < 8) {
3321 if (push_items <= 8)
3327 push_items = min(src_nritems - 8, push_items);
3329 ret = tree_mod_log_eb_copy(fs_info, dst, src, dst_nritems, 0,
3332 btrfs_abort_transaction(trans, ret);
3335 copy_extent_buffer(dst, src,
3336 btrfs_node_key_ptr_offset(dst_nritems),
3337 btrfs_node_key_ptr_offset(0),
3338 push_items * sizeof(struct btrfs_key_ptr));
3340 if (push_items < src_nritems) {
3342 * Don't call tree_mod_log_insert_move here, key removal was
3343 * already fully logged by tree_mod_log_eb_copy above.
3345 memmove_extent_buffer(src, btrfs_node_key_ptr_offset(0),
3346 btrfs_node_key_ptr_offset(push_items),
3347 (src_nritems - push_items) *
3348 sizeof(struct btrfs_key_ptr));
3350 btrfs_set_header_nritems(src, src_nritems - push_items);
3351 btrfs_set_header_nritems(dst, dst_nritems + push_items);
3352 btrfs_mark_buffer_dirty(src);
3353 btrfs_mark_buffer_dirty(dst);
3359 * try to push data from one node into the next node right in the
3362 * returns 0 if some ptrs were pushed, < 0 if there was some horrible
3363 * error, and > 0 if there was no room in the right hand block.
3365 * this will only push up to 1/2 the contents of the left node over
3367 static int balance_node_right(struct btrfs_trans_handle *trans,
3368 struct btrfs_fs_info *fs_info,
3369 struct extent_buffer *dst,
3370 struct extent_buffer *src)
3378 WARN_ON(btrfs_header_generation(src) != trans->transid);
3379 WARN_ON(btrfs_header_generation(dst) != trans->transid);
3381 src_nritems = btrfs_header_nritems(src);
3382 dst_nritems = btrfs_header_nritems(dst);
3383 push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
3384 if (push_items <= 0)
3387 if (src_nritems < 4)
3390 max_push = src_nritems / 2 + 1;
3391 /* don't try to empty the node */
3392 if (max_push >= src_nritems)
3395 if (max_push < push_items)
3396 push_items = max_push;
3398 ret = tree_mod_log_insert_move(dst, push_items, 0, dst_nritems);
3400 memmove_extent_buffer(dst, btrfs_node_key_ptr_offset(push_items),
3401 btrfs_node_key_ptr_offset(0),
3403 sizeof(struct btrfs_key_ptr));
3405 ret = tree_mod_log_eb_copy(fs_info, dst, src, 0,
3406 src_nritems - push_items, push_items);
3408 btrfs_abort_transaction(trans, ret);
3411 copy_extent_buffer(dst, src,
3412 btrfs_node_key_ptr_offset(0),
3413 btrfs_node_key_ptr_offset(src_nritems - push_items),
3414 push_items * sizeof(struct btrfs_key_ptr));
3416 btrfs_set_header_nritems(src, src_nritems - push_items);
3417 btrfs_set_header_nritems(dst, dst_nritems + push_items);
3419 btrfs_mark_buffer_dirty(src);
3420 btrfs_mark_buffer_dirty(dst);
3426 * helper function to insert a new root level in the tree.
3427 * A new node is allocated, and a single item is inserted to
3428 * point to the existing root
3430 * returns zero on success or < 0 on failure.
3432 static noinline int insert_new_root(struct btrfs_trans_handle *trans,
3433 struct btrfs_root *root,
3434 struct btrfs_path *path, int level)
3436 struct btrfs_fs_info *fs_info = root->fs_info;
3438 struct extent_buffer *lower;
3439 struct extent_buffer *c;
3440 struct extent_buffer *old;
3441 struct btrfs_disk_key lower_key;
3444 BUG_ON(path->nodes[level]);
3445 BUG_ON(path->nodes[level-1] != root->node);
3447 lower = path->nodes[level-1];
3449 btrfs_item_key(lower, &lower_key, 0);
3451 btrfs_node_key(lower, &lower_key, 0);
3453 c = alloc_tree_block_no_bg_flush(trans, root, 0, &lower_key, level,
3454 root->node->start, 0);
3458 root_add_used(root, fs_info->nodesize);
3460 btrfs_set_header_nritems(c, 1);
3461 btrfs_set_node_key(c, &lower_key, 0);
3462 btrfs_set_node_blockptr(c, 0, lower->start);
3463 lower_gen = btrfs_header_generation(lower);
3464 WARN_ON(lower_gen != trans->transid);
3466 btrfs_set_node_ptr_generation(c, 0, lower_gen);
3468 btrfs_mark_buffer_dirty(c);
3471 ret = tree_mod_log_insert_root(root->node, c, 0);
3473 rcu_assign_pointer(root->node, c);
3475 /* the super has an extra ref to root->node */
3476 free_extent_buffer(old);
3478 add_root_to_dirty_list(root);
3479 extent_buffer_get(c);
3480 path->nodes[level] = c;
3481 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
3482 path->slots[level] = 0;
3487 * worker function to insert a single pointer in a node.
3488 * the node should have enough room for the pointer already
3490 * slot and level indicate where you want the key to go, and
3491 * blocknr is the block the key points to.
3493 static void insert_ptr(struct btrfs_trans_handle *trans,
3494 struct btrfs_fs_info *fs_info, struct btrfs_path *path,
3495 struct btrfs_disk_key *key, u64 bytenr,
3496 int slot, int level)
3498 struct extent_buffer *lower;
3502 BUG_ON(!path->nodes[level]);
3503 btrfs_assert_tree_locked(path->nodes[level]);
3504 lower = path->nodes[level];
3505 nritems = btrfs_header_nritems(lower);
3506 BUG_ON(slot > nritems);
3507 BUG_ON(nritems == BTRFS_NODEPTRS_PER_BLOCK(fs_info));
3508 if (slot != nritems) {
3510 ret = tree_mod_log_insert_move(lower, slot + 1, slot,
3514 memmove_extent_buffer(lower,
3515 btrfs_node_key_ptr_offset(slot + 1),
3516 btrfs_node_key_ptr_offset(slot),
3517 (nritems - slot) * sizeof(struct btrfs_key_ptr));
3520 ret = tree_mod_log_insert_key(lower, slot, MOD_LOG_KEY_ADD,
3524 btrfs_set_node_key(lower, key, slot);
3525 btrfs_set_node_blockptr(lower, slot, bytenr);
3526 WARN_ON(trans->transid == 0);
3527 btrfs_set_node_ptr_generation(lower, slot, trans->transid);
3528 btrfs_set_header_nritems(lower, nritems + 1);
3529 btrfs_mark_buffer_dirty(lower);
3533 * split the node at the specified level in path in two.
3534 * The path is corrected to point to the appropriate node after the split
3536 * Before splitting this tries to make some room in the node by pushing
3537 * left and right, if either one works, it returns right away.
3539 * returns 0 on success and < 0 on failure
3541 static noinline int split_node(struct btrfs_trans_handle *trans,
3542 struct btrfs_root *root,
3543 struct btrfs_path *path, int level)
3545 struct btrfs_fs_info *fs_info = root->fs_info;
3546 struct extent_buffer *c;
3547 struct extent_buffer *split;
3548 struct btrfs_disk_key disk_key;
3553 c = path->nodes[level];
3554 WARN_ON(btrfs_header_generation(c) != trans->transid);
3555 if (c == root->node) {
3557 * trying to split the root, lets make a new one
3559 * tree mod log: We don't log_removal old root in
3560 * insert_new_root, because that root buffer will be kept as a
3561 * normal node. We are going to log removal of half of the
3562 * elements below with tree_mod_log_eb_copy. We're holding a
3563 * tree lock on the buffer, which is why we cannot race with
3564 * other tree_mod_log users.
3566 ret = insert_new_root(trans, root, path, level + 1);
3570 ret = push_nodes_for_insert(trans, root, path, level);
3571 c = path->nodes[level];
3572 if (!ret && btrfs_header_nritems(c) <
3573 BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3)
3579 c_nritems = btrfs_header_nritems(c);
3580 mid = (c_nritems + 1) / 2;
3581 btrfs_node_key(c, &disk_key, mid);
3583 split = alloc_tree_block_no_bg_flush(trans, root, 0, &disk_key, level,
3586 return PTR_ERR(split);
3588 root_add_used(root, fs_info->nodesize);
3589 ASSERT(btrfs_header_level(c) == level);
3591 ret = tree_mod_log_eb_copy(fs_info, split, c, 0, mid, c_nritems - mid);
3593 btrfs_abort_transaction(trans, ret);
3596 copy_extent_buffer(split, c,
3597 btrfs_node_key_ptr_offset(0),
3598 btrfs_node_key_ptr_offset(mid),
3599 (c_nritems - mid) * sizeof(struct btrfs_key_ptr));
3600 btrfs_set_header_nritems(split, c_nritems - mid);
3601 btrfs_set_header_nritems(c, mid);
3604 btrfs_mark_buffer_dirty(c);
3605 btrfs_mark_buffer_dirty(split);
3607 insert_ptr(trans, fs_info, path, &disk_key, split->start,
3608 path->slots[level + 1] + 1, level + 1);
3610 if (path->slots[level] >= mid) {
3611 path->slots[level] -= mid;
3612 btrfs_tree_unlock(c);
3613 free_extent_buffer(c);
3614 path->nodes[level] = split;
3615 path->slots[level + 1] += 1;
3617 btrfs_tree_unlock(split);
3618 free_extent_buffer(split);
3624 * how many bytes are required to store the items in a leaf. start
3625 * and nr indicate which items in the leaf to check. This totals up the
3626 * space used both by the item structs and the item data
3628 static int leaf_space_used(struct extent_buffer *l, int start, int nr)
3630 struct btrfs_item *start_item;
3631 struct btrfs_item *end_item;
3632 struct btrfs_map_token token;
3634 int nritems = btrfs_header_nritems(l);
3635 int end = min(nritems, start + nr) - 1;
3639 btrfs_init_map_token(&token);
3640 start_item = btrfs_item_nr(start);
3641 end_item = btrfs_item_nr(end);
3642 data_len = btrfs_token_item_offset(l, start_item, &token) +
3643 btrfs_token_item_size(l, start_item, &token);
3644 data_len = data_len - btrfs_token_item_offset(l, end_item, &token);
3645 data_len += sizeof(struct btrfs_item) * nr;
3646 WARN_ON(data_len < 0);
3651 * The space between the end of the leaf items and
3652 * the start of the leaf data. IOW, how much room
3653 * the leaf has left for both items and data
3655 noinline int btrfs_leaf_free_space(struct btrfs_fs_info *fs_info,
3656 struct extent_buffer *leaf)
3658 int nritems = btrfs_header_nritems(leaf);
3661 ret = BTRFS_LEAF_DATA_SIZE(fs_info) - leaf_space_used(leaf, 0, nritems);
3664 "leaf free space ret %d, leaf data size %lu, used %d nritems %d",
3666 (unsigned long) BTRFS_LEAF_DATA_SIZE(fs_info),
3667 leaf_space_used(leaf, 0, nritems), nritems);
3673 * min slot controls the lowest index we're willing to push to the
3674 * right. We'll push up to and including min_slot, but no lower
3676 static noinline int __push_leaf_right(struct btrfs_fs_info *fs_info,
3677 struct btrfs_path *path,
3678 int data_size, int empty,
3679 struct extent_buffer *right,
3680 int free_space, u32 left_nritems,
3683 struct extent_buffer *left = path->nodes[0];
3684 struct extent_buffer *upper = path->nodes[1];
3685 struct btrfs_map_token token;
3686 struct btrfs_disk_key disk_key;
3691 struct btrfs_item *item;
3697 btrfs_init_map_token(&token);
3702 nr = max_t(u32, 1, min_slot);
3704 if (path->slots[0] >= left_nritems)
3705 push_space += data_size;
3707 slot = path->slots[1];
3708 i = left_nritems - 1;
3710 item = btrfs_item_nr(i);
3712 if (!empty && push_items > 0) {
3713 if (path->slots[0] > i)
3715 if (path->slots[0] == i) {
3716 int space = btrfs_leaf_free_space(fs_info, left);
3717 if (space + push_space * 2 > free_space)
3722 if (path->slots[0] == i)
3723 push_space += data_size;
3725 this_item_size = btrfs_item_size(left, item);
3726 if (this_item_size + sizeof(*item) + push_space > free_space)
3730 push_space += this_item_size + sizeof(*item);
3736 if (push_items == 0)
3739 WARN_ON(!empty && push_items == left_nritems);
3741 /* push left to right */
3742 right_nritems = btrfs_header_nritems(right);
3744 push_space = btrfs_item_end_nr(left, left_nritems - push_items);
3745 push_space -= leaf_data_end(fs_info, left);
3747 /* make room in the right data area */
3748 data_end = leaf_data_end(fs_info, right);
3749 memmove_extent_buffer(right,
3750 BTRFS_LEAF_DATA_OFFSET + data_end - push_space,
3751 BTRFS_LEAF_DATA_OFFSET + data_end,
3752 BTRFS_LEAF_DATA_SIZE(fs_info) - data_end);
3754 /* copy from the left data area */
3755 copy_extent_buffer(right, left, BTRFS_LEAF_DATA_OFFSET +
3756 BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
3757 BTRFS_LEAF_DATA_OFFSET + leaf_data_end(fs_info, left),
3760 memmove_extent_buffer(right, btrfs_item_nr_offset(push_items),
3761 btrfs_item_nr_offset(0),
3762 right_nritems * sizeof(struct btrfs_item));
3764 /* copy the items from left to right */
3765 copy_extent_buffer(right, left, btrfs_item_nr_offset(0),
3766 btrfs_item_nr_offset(left_nritems - push_items),
3767 push_items * sizeof(struct btrfs_item));
3769 /* update the item pointers */
3770 right_nritems += push_items;
3771 btrfs_set_header_nritems(right, right_nritems);
3772 push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
3773 for (i = 0; i < right_nritems; i++) {
3774 item = btrfs_item_nr(i);
3775 push_space -= btrfs_token_item_size(right, item, &token);
3776 btrfs_set_token_item_offset(right, item, push_space, &token);
3779 left_nritems -= push_items;
3780 btrfs_set_header_nritems(left, left_nritems);
3783 btrfs_mark_buffer_dirty(left);
3785 clean_tree_block(fs_info, left);
3787 btrfs_mark_buffer_dirty(right);
3789 btrfs_item_key(right, &disk_key, 0);
3790 btrfs_set_node_key(upper, &disk_key, slot + 1);
3791 btrfs_mark_buffer_dirty(upper);
3793 /* then fixup the leaf pointer in the path */
3794 if (path->slots[0] >= left_nritems) {
3795 path->slots[0] -= left_nritems;
3796 if (btrfs_header_nritems(path->nodes[0]) == 0)
3797 clean_tree_block(fs_info, path->nodes[0]);
3798 btrfs_tree_unlock(path->nodes[0]);
3799 free_extent_buffer(path->nodes[0]);
3800 path->nodes[0] = right;
3801 path->slots[1] += 1;
3803 btrfs_tree_unlock(right);
3804 free_extent_buffer(right);
3809 btrfs_tree_unlock(right);
3810 free_extent_buffer(right);
3815 * push some data in the path leaf to the right, trying to free up at
3816 * least data_size bytes. returns zero if the push worked, nonzero otherwise
3818 * returns 1 if the push failed because the other node didn't have enough
3819 * room, 0 if everything worked out and < 0 if there were major errors.
3821 * this will push starting from min_slot to the end of the leaf. It won't
3822 * push any slot lower than min_slot
3824 static int push_leaf_right(struct btrfs_trans_handle *trans, struct btrfs_root
3825 *root, struct btrfs_path *path,
3826 int min_data_size, int data_size,
3827 int empty, u32 min_slot)
3829 struct btrfs_fs_info *fs_info = root->fs_info;
3830 struct extent_buffer *left = path->nodes[0];
3831 struct extent_buffer *right;
3832 struct extent_buffer *upper;
3838 if (!path->nodes[1])
3841 slot = path->slots[1];
3842 upper = path->nodes[1];
3843 if (slot >= btrfs_header_nritems(upper) - 1)
3846 btrfs_assert_tree_locked(path->nodes[1]);
3848 right = read_node_slot(fs_info, upper, slot + 1);
3850 * slot + 1 is not valid or we fail to read the right node,
3851 * no big deal, just return.
3856 btrfs_tree_lock(right);
3857 btrfs_set_lock_blocking(right);
3859 free_space = btrfs_leaf_free_space(fs_info, right);
3860 if (free_space < data_size)
3863 /* cow and double check */
3864 ret = btrfs_cow_block(trans, root, right, upper,
3869 free_space = btrfs_leaf_free_space(fs_info, right);
3870 if (free_space < data_size)
3873 left_nritems = btrfs_header_nritems(left);
3874 if (left_nritems == 0)
3877 if (path->slots[0] == left_nritems && !empty) {
3878 /* Key greater than all keys in the leaf, right neighbor has
3879 * enough room for it and we're not emptying our leaf to delete
3880 * it, therefore use right neighbor to insert the new item and
3881 * no need to touch/dirty our left leaft. */
3882 btrfs_tree_unlock(left);
3883 free_extent_buffer(left);
3884 path->nodes[0] = right;
3890 return __push_leaf_right(fs_info, path, min_data_size, empty,
3891 right, free_space, left_nritems, min_slot);
3893 btrfs_tree_unlock(right);
3894 free_extent_buffer(right);
3899 * push some data in the path leaf to the left, trying to free up at
3900 * least data_size bytes. returns zero if the push worked, nonzero otherwise
3902 * max_slot can put a limit on how far into the leaf we'll push items. The
3903 * item at 'max_slot' won't be touched. Use (u32)-1 to make us do all the
3906 static noinline int __push_leaf_left(struct btrfs_fs_info *fs_info,
3907 struct btrfs_path *path, int data_size,
3908 int empty, struct extent_buffer *left,
3909 int free_space, u32 right_nritems,
3912 struct btrfs_disk_key disk_key;
3913 struct extent_buffer *right = path->nodes[0];
3917 struct btrfs_item *item;
3918 u32 old_left_nritems;
3922 u32 old_left_item_size;
3923 struct btrfs_map_token token;
3925 btrfs_init_map_token(&token);
3928 nr = min(right_nritems, max_slot);
3930 nr = min(right_nritems - 1, max_slot);
3932 for (i = 0; i < nr; i++) {
3933 item = btrfs_item_nr(i);
3935 if (!empty && push_items > 0) {
3936 if (path->slots[0] < i)
3938 if (path->slots[0] == i) {
3939 int space = btrfs_leaf_free_space(fs_info, right);
3940 if (space + push_space * 2 > free_space)
3945 if (path->slots[0] == i)
3946 push_space += data_size;
3948 this_item_size = btrfs_item_size(right, item);
3949 if (this_item_size + sizeof(*item) + push_space > free_space)
3953 push_space += this_item_size + sizeof(*item);
3956 if (push_items == 0) {
3960 WARN_ON(!empty && push_items == btrfs_header_nritems(right));
3962 /* push data from right to left */
3963 copy_extent_buffer(left, right,
3964 btrfs_item_nr_offset(btrfs_header_nritems(left)),
3965 btrfs_item_nr_offset(0),
3966 push_items * sizeof(struct btrfs_item));
3968 push_space = BTRFS_LEAF_DATA_SIZE(fs_info) -
3969 btrfs_item_offset_nr(right, push_items - 1);
3971 copy_extent_buffer(left, right, BTRFS_LEAF_DATA_OFFSET +
3972 leaf_data_end(fs_info, left) - push_space,
3973 BTRFS_LEAF_DATA_OFFSET +
3974 btrfs_item_offset_nr(right, push_items - 1),
3976 old_left_nritems = btrfs_header_nritems(left);
3977 BUG_ON(old_left_nritems <= 0);
3979 old_left_item_size = btrfs_item_offset_nr(left, old_left_nritems - 1);
3980 for (i = old_left_nritems; i < old_left_nritems + push_items; i++) {
3983 item = btrfs_item_nr(i);
3985 ioff = btrfs_token_item_offset(left, item, &token);
3986 btrfs_set_token_item_offset(left, item,
3987 ioff - (BTRFS_LEAF_DATA_SIZE(fs_info) - old_left_item_size),
3990 btrfs_set_header_nritems(left, old_left_nritems + push_items);
3992 /* fixup right node */
3993 if (push_items > right_nritems)
3994 WARN(1, KERN_CRIT "push items %d nr %u\n", push_items,
3997 if (push_items < right_nritems) {
3998 push_space = btrfs_item_offset_nr(right, push_items - 1) -
3999 leaf_data_end(fs_info, right);
4000 memmove_extent_buffer(right, BTRFS_LEAF_DATA_OFFSET +
4001 BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
4002 BTRFS_LEAF_DATA_OFFSET +
4003 leaf_data_end(fs_info, right), push_space);
4005 memmove_extent_buffer(right, btrfs_item_nr_offset(0),
4006 btrfs_item_nr_offset(push_items),
4007 (btrfs_header_nritems(right) - push_items) *
4008 sizeof(struct btrfs_item));
4010 right_nritems -= push_items;
4011 btrfs_set_header_nritems(right, right_nritems);
4012 push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
4013 for (i = 0; i < right_nritems; i++) {
4014 item = btrfs_item_nr(i);
4016 push_space = push_space - btrfs_token_item_size(right,
4018 btrfs_set_token_item_offset(right, item, push_space, &token);
4021 btrfs_mark_buffer_dirty(left);
4023 btrfs_mark_buffer_dirty(right);
4025 clean_tree_block(fs_info, right);
4027 btrfs_item_key(right, &disk_key, 0);
4028 fixup_low_keys(path, &disk_key, 1);
4030 /* then fixup the leaf pointer in the path */
4031 if (path->slots[0] < push_items) {
4032 path->slots[0] += old_left_nritems;
4033 btrfs_tree_unlock(path->nodes[0]);
4034 free_extent_buffer(path->nodes[0]);
4035 path->nodes[0] = left;
4036 path->slots[1] -= 1;
4038 btrfs_tree_unlock(left);
4039 free_extent_buffer(left);
4040 path->slots[0] -= push_items;
4042 BUG_ON(path->slots[0] < 0);
4045 btrfs_tree_unlock(left);
4046 free_extent_buffer(left);
4051 * push some data in the path leaf to the left, trying to free up at
4052 * least data_size bytes. returns zero if the push worked, nonzero otherwise
4054 * max_slot can put a limit on how far into the leaf we'll push items. The
4055 * item at 'max_slot' won't be touched. Use (u32)-1 to make us push all the
4058 static int push_leaf_left(struct btrfs_trans_handle *trans, struct btrfs_root
4059 *root, struct btrfs_path *path, int min_data_size,
4060 int data_size, int empty, u32 max_slot)
4062 struct btrfs_fs_info *fs_info = root->fs_info;
4063 struct extent_buffer *right = path->nodes[0];
4064 struct extent_buffer *left;
4070 slot = path->slots[1];
4073 if (!path->nodes[1])
4076 right_nritems = btrfs_header_nritems(right);
4077 if (right_nritems == 0)
4080 btrfs_assert_tree_locked(path->nodes[1]);
4082 left = read_node_slot(fs_info, path->nodes[1], slot - 1);
4084 * slot - 1 is not valid or we fail to read the left node,
4085 * no big deal, just return.
4090 btrfs_tree_lock(left);
4091 btrfs_set_lock_blocking(left);
4093 free_space = btrfs_leaf_free_space(fs_info, left);
4094 if (free_space < data_size) {
4099 /* cow and double check */
4100 ret = btrfs_cow_block(trans, root, left,
4101 path->nodes[1], slot - 1, &left);
4103 /* we hit -ENOSPC, but it isn't fatal here */
4109 free_space = btrfs_leaf_free_space(fs_info, left);
4110 if (free_space < data_size) {
4115 return __push_leaf_left(fs_info, path, min_data_size,
4116 empty, left, free_space, right_nritems,
4119 btrfs_tree_unlock(left);
4120 free_extent_buffer(left);
4125 * split the path's leaf in two, making sure there is at least data_size
4126 * available for the resulting leaf level of the path.
4128 static noinline void copy_for_split(struct btrfs_trans_handle *trans,
4129 struct btrfs_fs_info *fs_info,
4130 struct btrfs_path *path,
4131 struct extent_buffer *l,
4132 struct extent_buffer *right,
4133 int slot, int mid, int nritems)
4138 struct btrfs_disk_key disk_key;
4139 struct btrfs_map_token token;
4141 btrfs_init_map_token(&token);
4143 nritems = nritems - mid;
4144 btrfs_set_header_nritems(right, nritems);
4145 data_copy_size = btrfs_item_end_nr(l, mid) - leaf_data_end(fs_info, l);
4147 copy_extent_buffer(right, l, btrfs_item_nr_offset(0),
4148 btrfs_item_nr_offset(mid),
4149 nritems * sizeof(struct btrfs_item));
4151 copy_extent_buffer(right, l,
4152 BTRFS_LEAF_DATA_OFFSET + BTRFS_LEAF_DATA_SIZE(fs_info) -
4153 data_copy_size, BTRFS_LEAF_DATA_OFFSET +
4154 leaf_data_end(fs_info, l), data_copy_size);
4156 rt_data_off = BTRFS_LEAF_DATA_SIZE(fs_info) - btrfs_item_end_nr(l, mid);
4158 for (i = 0; i < nritems; i++) {
4159 struct btrfs_item *item = btrfs_item_nr(i);
4162 ioff = btrfs_token_item_offset(right, item, &token);
4163 btrfs_set_token_item_offset(right, item,
4164 ioff + rt_data_off, &token);
4167 btrfs_set_header_nritems(l, mid);
4168 btrfs_item_key(right, &disk_key, 0);
4169 insert_ptr(trans, fs_info, path, &disk_key, right->start,
4170 path->slots[1] + 1, 1);
4172 btrfs_mark_buffer_dirty(right);
4173 btrfs_mark_buffer_dirty(l);
4174 BUG_ON(path->slots[0] != slot);
4177 btrfs_tree_unlock(path->nodes[0]);
4178 free_extent_buffer(path->nodes[0]);
4179 path->nodes[0] = right;
4180 path->slots[0] -= mid;
4181 path->slots[1] += 1;
4183 btrfs_tree_unlock(right);
4184 free_extent_buffer(right);
4187 BUG_ON(path->slots[0] < 0);
4191 * double splits happen when we need to insert a big item in the middle
4192 * of a leaf. A double split can leave us with 3 mostly empty leaves:
4193 * leaf: [ slots 0 - N] [ our target ] [ N + 1 - total in leaf ]
4196 * We avoid this by trying to push the items on either side of our target
4197 * into the adjacent leaves. If all goes well we can avoid the double split
4200 static noinline int push_for_double_split(struct btrfs_trans_handle *trans,
4201 struct btrfs_root *root,
4202 struct btrfs_path *path,
4205 struct btrfs_fs_info *fs_info = root->fs_info;
4210 int space_needed = data_size;
4212 slot = path->slots[0];
4213 if (slot < btrfs_header_nritems(path->nodes[0]))
4214 space_needed -= btrfs_leaf_free_space(fs_info, path->nodes[0]);
4217 * try to push all the items after our slot into the
4220 ret = push_leaf_right(trans, root, path, 1, space_needed, 0, slot);
4227 nritems = btrfs_header_nritems(path->nodes[0]);
4229 * our goal is to get our slot at the start or end of a leaf. If
4230 * we've done so we're done
4232 if (path->slots[0] == 0 || path->slots[0] == nritems)
4235 if (btrfs_leaf_free_space(fs_info, path->nodes[0]) >= data_size)
4238 /* try to push all the items before our slot into the next leaf */
4239 slot = path->slots[0];
4240 space_needed = data_size;
4242 space_needed -= btrfs_leaf_free_space(fs_info, path->nodes[0]);
4243 ret = push_leaf_left(trans, root, path, 1, space_needed, 0, slot);
4256 * split the path's leaf in two, making sure there is at least data_size
4257 * available for the resulting leaf level of the path.
4259 * returns 0 if all went well and < 0 on failure.
4261 static noinline int split_leaf(struct btrfs_trans_handle *trans,
4262 struct btrfs_root *root,
4263 const struct btrfs_key *ins_key,
4264 struct btrfs_path *path, int data_size,
4267 struct btrfs_disk_key disk_key;
4268 struct extent_buffer *l;
4272 struct extent_buffer *right;
4273 struct btrfs_fs_info *fs_info = root->fs_info;
4277 int num_doubles = 0;
4278 int tried_avoid_double = 0;
4281 slot = path->slots[0];
4282 if (extend && data_size + btrfs_item_size_nr(l, slot) +
4283 sizeof(struct btrfs_item) > BTRFS_LEAF_DATA_SIZE(fs_info))
4286 /* first try to make some room by pushing left and right */
4287 if (data_size && path->nodes[1]) {
4288 int space_needed = data_size;
4290 if (slot < btrfs_header_nritems(l))
4291 space_needed -= btrfs_leaf_free_space(fs_info, l);
4293 wret = push_leaf_right(trans, root, path, space_needed,
4294 space_needed, 0, 0);
4298 space_needed = data_size;
4300 space_needed -= btrfs_leaf_free_space(fs_info,
4302 wret = push_leaf_left(trans, root, path, space_needed,
4303 space_needed, 0, (u32)-1);
4309 /* did the pushes work? */
4310 if (btrfs_leaf_free_space(fs_info, l) >= data_size)
4314 if (!path->nodes[1]) {
4315 ret = insert_new_root(trans, root, path, 1);
4322 slot = path->slots[0];
4323 nritems = btrfs_header_nritems(l);
4324 mid = (nritems + 1) / 2;
4328 leaf_space_used(l, mid, nritems - mid) + data_size >
4329 BTRFS_LEAF_DATA_SIZE(fs_info)) {
4330 if (slot >= nritems) {
4334 if (mid != nritems &&
4335 leaf_space_used(l, mid, nritems - mid) +
4336 data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
4337 if (data_size && !tried_avoid_double)
4338 goto push_for_double;
4344 if (leaf_space_used(l, 0, mid) + data_size >
4345 BTRFS_LEAF_DATA_SIZE(fs_info)) {
4346 if (!extend && data_size && slot == 0) {
4348 } else if ((extend || !data_size) && slot == 0) {
4352 if (mid != nritems &&
4353 leaf_space_used(l, mid, nritems - mid) +
4354 data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
4355 if (data_size && !tried_avoid_double)
4356 goto push_for_double;
4364 btrfs_cpu_key_to_disk(&disk_key, ins_key);
4366 btrfs_item_key(l, &disk_key, mid);
4368 right = alloc_tree_block_no_bg_flush(trans, root, 0, &disk_key, 0,
4371 return PTR_ERR(right);
4373 root_add_used(root, fs_info->nodesize);
4377 btrfs_set_header_nritems(right, 0);
4378 insert_ptr(trans, fs_info, path, &disk_key,
4379 right->start, path->slots[1] + 1, 1);
4380 btrfs_tree_unlock(path->nodes[0]);
4381 free_extent_buffer(path->nodes[0]);
4382 path->nodes[0] = right;
4384 path->slots[1] += 1;
4386 btrfs_set_header_nritems(right, 0);
4387 insert_ptr(trans, fs_info, path, &disk_key,
4388 right->start, path->slots[1], 1);
4389 btrfs_tree_unlock(path->nodes[0]);
4390 free_extent_buffer(path->nodes[0]);
4391 path->nodes[0] = right;
4393 if (path->slots[1] == 0)
4394 fixup_low_keys(path, &disk_key, 1);
4397 * We create a new leaf 'right' for the required ins_len and
4398 * we'll do btrfs_mark_buffer_dirty() on this leaf after copying
4399 * the content of ins_len to 'right'.
4404 copy_for_split(trans, fs_info, path, l, right, slot, mid, nritems);
4407 BUG_ON(num_doubles != 0);
4415 push_for_double_split(trans, root, path, data_size);
4416 tried_avoid_double = 1;
4417 if (btrfs_leaf_free_space(fs_info, path->nodes[0]) >= data_size)
4422 static noinline int setup_leaf_for_split(struct btrfs_trans_handle *trans,
4423 struct btrfs_root *root,
4424 struct btrfs_path *path, int ins_len)
4426 struct btrfs_fs_info *fs_info = root->fs_info;
4427 struct btrfs_key key;
4428 struct extent_buffer *leaf;
4429 struct btrfs_file_extent_item *fi;
4434 leaf = path->nodes[0];
4435 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4437 BUG_ON(key.type != BTRFS_EXTENT_DATA_KEY &&
4438 key.type != BTRFS_EXTENT_CSUM_KEY);
4440 if (btrfs_leaf_free_space(fs_info, leaf) >= ins_len)
4443 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
4444 if (key.type == BTRFS_EXTENT_DATA_KEY) {
4445 fi = btrfs_item_ptr(leaf, path->slots[0],
4446 struct btrfs_file_extent_item);
4447 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
4449 btrfs_release_path(path);
4451 path->keep_locks = 1;
4452 path->search_for_split = 1;
4453 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
4454 path->search_for_split = 0;
4461 leaf = path->nodes[0];
4462 /* if our item isn't there, return now */
4463 if (item_size != btrfs_item_size_nr(leaf, path->slots[0]))
4466 /* the leaf has changed, it now has room. return now */
4467 if (btrfs_leaf_free_space(fs_info, path->nodes[0]) >= ins_len)
4470 if (key.type == BTRFS_EXTENT_DATA_KEY) {
4471 fi = btrfs_item_ptr(leaf, path->slots[0],
4472 struct btrfs_file_extent_item);
4473 if (extent_len != btrfs_file_extent_num_bytes(leaf, fi))
4477 btrfs_set_path_blocking(path);
4478 ret = split_leaf(trans, root, &key, path, ins_len, 1);
4482 path->keep_locks = 0;
4483 btrfs_unlock_up_safe(path, 1);
4486 path->keep_locks = 0;
4490 static noinline int split_item(struct btrfs_fs_info *fs_info,
4491 struct btrfs_path *path,
4492 const struct btrfs_key *new_key,
4493 unsigned long split_offset)
4495 struct extent_buffer *leaf;
4496 struct btrfs_item *item;
4497 struct btrfs_item *new_item;
4503 struct btrfs_disk_key disk_key;
4505 leaf = path->nodes[0];
4506 BUG_ON(btrfs_leaf_free_space(fs_info, leaf) < sizeof(struct btrfs_item));
4508 btrfs_set_path_blocking(path);
4510 item = btrfs_item_nr(path->slots[0]);
4511 orig_offset = btrfs_item_offset(leaf, item);
4512 item_size = btrfs_item_size(leaf, item);
4514 buf = kmalloc(item_size, GFP_NOFS);
4518 read_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf,
4519 path->slots[0]), item_size);
4521 slot = path->slots[0] + 1;
4522 nritems = btrfs_header_nritems(leaf);
4523 if (slot != nritems) {
4524 /* shift the items */
4525 memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + 1),
4526 btrfs_item_nr_offset(slot),
4527 (nritems - slot) * sizeof(struct btrfs_item));
4530 btrfs_cpu_key_to_disk(&disk_key, new_key);
4531 btrfs_set_item_key(leaf, &disk_key, slot);
4533 new_item = btrfs_item_nr(slot);
4535 btrfs_set_item_offset(leaf, new_item, orig_offset);
4536 btrfs_set_item_size(leaf, new_item, item_size - split_offset);
4538 btrfs_set_item_offset(leaf, item,
4539 orig_offset + item_size - split_offset);
4540 btrfs_set_item_size(leaf, item, split_offset);
4542 btrfs_set_header_nritems(leaf, nritems + 1);
4544 /* write the data for the start of the original item */
4545 write_extent_buffer(leaf, buf,
4546 btrfs_item_ptr_offset(leaf, path->slots[0]),
4549 /* write the data for the new item */
4550 write_extent_buffer(leaf, buf + split_offset,
4551 btrfs_item_ptr_offset(leaf, slot),
4552 item_size - split_offset);
4553 btrfs_mark_buffer_dirty(leaf);
4555 BUG_ON(btrfs_leaf_free_space(fs_info, leaf) < 0);
4561 * This function splits a single item into two items,
4562 * giving 'new_key' to the new item and splitting the
4563 * old one at split_offset (from the start of the item).
4565 * The path may be released by this operation. After
4566 * the split, the path is pointing to the old item. The
4567 * new item is going to be in the same node as the old one.
4569 * Note, the item being split must be smaller enough to live alone on
4570 * a tree block with room for one extra struct btrfs_item
4572 * This allows us to split the item in place, keeping a lock on the
4573 * leaf the entire time.
4575 int btrfs_split_item(struct btrfs_trans_handle *trans,
4576 struct btrfs_root *root,
4577 struct btrfs_path *path,
4578 const struct btrfs_key *new_key,
4579 unsigned long split_offset)
4582 ret = setup_leaf_for_split(trans, root, path,
4583 sizeof(struct btrfs_item));
4587 ret = split_item(root->fs_info, path, new_key, split_offset);
4592 * This function duplicate a item, giving 'new_key' to the new item.
4593 * It guarantees both items live in the same tree leaf and the new item
4594 * is contiguous with the original item.
4596 * This allows us to split file extent in place, keeping a lock on the
4597 * leaf the entire time.
4599 int btrfs_duplicate_item(struct btrfs_trans_handle *trans,
4600 struct btrfs_root *root,
4601 struct btrfs_path *path,
4602 const struct btrfs_key *new_key)
4604 struct extent_buffer *leaf;
4608 leaf = path->nodes[0];
4609 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
4610 ret = setup_leaf_for_split(trans, root, path,
4611 item_size + sizeof(struct btrfs_item));
4616 setup_items_for_insert(root, path, new_key, &item_size,
4617 item_size, item_size +
4618 sizeof(struct btrfs_item), 1);
4619 leaf = path->nodes[0];
4620 memcpy_extent_buffer(leaf,
4621 btrfs_item_ptr_offset(leaf, path->slots[0]),
4622 btrfs_item_ptr_offset(leaf, path->slots[0] - 1),
4628 * make the item pointed to by the path smaller. new_size indicates
4629 * how small to make it, and from_end tells us if we just chop bytes
4630 * off the end of the item or if we shift the item to chop bytes off
4633 void btrfs_truncate_item(struct btrfs_fs_info *fs_info,
4634 struct btrfs_path *path, u32 new_size, int from_end)
4637 struct extent_buffer *leaf;
4638 struct btrfs_item *item;
4640 unsigned int data_end;
4641 unsigned int old_data_start;
4642 unsigned int old_size;
4643 unsigned int size_diff;
4645 struct btrfs_map_token token;
4647 btrfs_init_map_token(&token);
4649 leaf = path->nodes[0];
4650 slot = path->slots[0];
4652 old_size = btrfs_item_size_nr(leaf, slot);
4653 if (old_size == new_size)
4656 nritems = btrfs_header_nritems(leaf);
4657 data_end = leaf_data_end(fs_info, leaf);
4659 old_data_start = btrfs_item_offset_nr(leaf, slot);
4661 size_diff = old_size - new_size;
4664 BUG_ON(slot >= nritems);
4667 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4669 /* first correct the data pointers */
4670 for (i = slot; i < nritems; i++) {
4672 item = btrfs_item_nr(i);
4674 ioff = btrfs_token_item_offset(leaf, item, &token);
4675 btrfs_set_token_item_offset(leaf, item,
4676 ioff + size_diff, &token);
4679 /* shift the data */
4681 memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
4682 data_end + size_diff, BTRFS_LEAF_DATA_OFFSET +
4683 data_end, old_data_start + new_size - data_end);
4685 struct btrfs_disk_key disk_key;
4688 btrfs_item_key(leaf, &disk_key, slot);
4690 if (btrfs_disk_key_type(&disk_key) == BTRFS_EXTENT_DATA_KEY) {
4692 struct btrfs_file_extent_item *fi;
4694 fi = btrfs_item_ptr(leaf, slot,
4695 struct btrfs_file_extent_item);
4696 fi = (struct btrfs_file_extent_item *)(
4697 (unsigned long)fi - size_diff);
4699 if (btrfs_file_extent_type(leaf, fi) ==
4700 BTRFS_FILE_EXTENT_INLINE) {
4701 ptr = btrfs_item_ptr_offset(leaf, slot);
4702 memmove_extent_buffer(leaf, ptr,
4704 BTRFS_FILE_EXTENT_INLINE_DATA_START);
4708 memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
4709 data_end + size_diff, BTRFS_LEAF_DATA_OFFSET +
4710 data_end, old_data_start - data_end);
4712 offset = btrfs_disk_key_offset(&disk_key);
4713 btrfs_set_disk_key_offset(&disk_key, offset + size_diff);
4714 btrfs_set_item_key(leaf, &disk_key, slot);
4716 fixup_low_keys(path, &disk_key, 1);
4719 item = btrfs_item_nr(slot);
4720 btrfs_set_item_size(leaf, item, new_size);
4721 btrfs_mark_buffer_dirty(leaf);
4723 if (btrfs_leaf_free_space(fs_info, leaf) < 0) {
4724 btrfs_print_leaf(leaf);
4730 * make the item pointed to by the path bigger, data_size is the added size.
4732 void btrfs_extend_item(struct btrfs_fs_info *fs_info, struct btrfs_path *path,
4736 struct extent_buffer *leaf;
4737 struct btrfs_item *item;
4739 unsigned int data_end;
4740 unsigned int old_data;
4741 unsigned int old_size;
4743 struct btrfs_map_token token;
4745 btrfs_init_map_token(&token);
4747 leaf = path->nodes[0];
4749 nritems = btrfs_header_nritems(leaf);
4750 data_end = leaf_data_end(fs_info, leaf);
4752 if (btrfs_leaf_free_space(fs_info, leaf) < data_size) {
4753 btrfs_print_leaf(leaf);
4756 slot = path->slots[0];
4757 old_data = btrfs_item_end_nr(leaf, slot);
4760 if (slot >= nritems) {
4761 btrfs_print_leaf(leaf);
4762 btrfs_crit(fs_info, "slot %d too large, nritems %d",
4768 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4770 /* first correct the data pointers */
4771 for (i = slot; i < nritems; i++) {
4773 item = btrfs_item_nr(i);
4775 ioff = btrfs_token_item_offset(leaf, item, &token);
4776 btrfs_set_token_item_offset(leaf, item,
4777 ioff - data_size, &token);
4780 /* shift the data */
4781 memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
4782 data_end - data_size, BTRFS_LEAF_DATA_OFFSET +
4783 data_end, old_data - data_end);
4785 data_end = old_data;
4786 old_size = btrfs_item_size_nr(leaf, slot);
4787 item = btrfs_item_nr(slot);
4788 btrfs_set_item_size(leaf, item, old_size + data_size);
4789 btrfs_mark_buffer_dirty(leaf);
4791 if (btrfs_leaf_free_space(fs_info, leaf) < 0) {
4792 btrfs_print_leaf(leaf);
4798 * this is a helper for btrfs_insert_empty_items, the main goal here is
4799 * to save stack depth by doing the bulk of the work in a function
4800 * that doesn't call btrfs_search_slot
4802 void setup_items_for_insert(struct btrfs_root *root, struct btrfs_path *path,
4803 const struct btrfs_key *cpu_key, u32 *data_size,
4804 u32 total_data, u32 total_size, int nr)
4806 struct btrfs_fs_info *fs_info = root->fs_info;
4807 struct btrfs_item *item;
4810 unsigned int data_end;
4811 struct btrfs_disk_key disk_key;
4812 struct extent_buffer *leaf;
4814 struct btrfs_map_token token;
4816 if (path->slots[0] == 0) {
4817 btrfs_cpu_key_to_disk(&disk_key, cpu_key);
4818 fixup_low_keys(path, &disk_key, 1);
4820 btrfs_unlock_up_safe(path, 1);
4822 btrfs_init_map_token(&token);
4824 leaf = path->nodes[0];
4825 slot = path->slots[0];
4827 nritems = btrfs_header_nritems(leaf);
4828 data_end = leaf_data_end(fs_info, leaf);
4830 if (btrfs_leaf_free_space(fs_info, leaf) < total_size) {
4831 btrfs_print_leaf(leaf);
4832 btrfs_crit(fs_info, "not enough freespace need %u have %d",
4833 total_size, btrfs_leaf_free_space(fs_info, leaf));
4837 if (slot != nritems) {
4838 unsigned int old_data = btrfs_item_end_nr(leaf, slot);
4840 if (old_data < data_end) {
4841 btrfs_print_leaf(leaf);
4842 btrfs_crit(fs_info, "slot %d old_data %d data_end %d",
4843 slot, old_data, data_end);
4847 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4849 /* first correct the data pointers */
4850 for (i = slot; i < nritems; i++) {
4853 item = btrfs_item_nr(i);
4854 ioff = btrfs_token_item_offset(leaf, item, &token);
4855 btrfs_set_token_item_offset(leaf, item,
4856 ioff - total_data, &token);
4858 /* shift the items */
4859 memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + nr),
4860 btrfs_item_nr_offset(slot),
4861 (nritems - slot) * sizeof(struct btrfs_item));
4863 /* shift the data */
4864 memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
4865 data_end - total_data, BTRFS_LEAF_DATA_OFFSET +
4866 data_end, old_data - data_end);
4867 data_end = old_data;
4870 /* setup the item for the new data */
4871 for (i = 0; i < nr; i++) {
4872 btrfs_cpu_key_to_disk(&disk_key, cpu_key + i);
4873 btrfs_set_item_key(leaf, &disk_key, slot + i);
4874 item = btrfs_item_nr(slot + i);
4875 btrfs_set_token_item_offset(leaf, item,
4876 data_end - data_size[i], &token);
4877 data_end -= data_size[i];
4878 btrfs_set_token_item_size(leaf, item, data_size[i], &token);
4881 btrfs_set_header_nritems(leaf, nritems + nr);
4882 btrfs_mark_buffer_dirty(leaf);
4884 if (btrfs_leaf_free_space(fs_info, leaf) < 0) {
4885 btrfs_print_leaf(leaf);
4891 * Given a key and some data, insert items into the tree.
4892 * This does all the path init required, making room in the tree if needed.
4894 int btrfs_insert_empty_items(struct btrfs_trans_handle *trans,
4895 struct btrfs_root *root,
4896 struct btrfs_path *path,
4897 const struct btrfs_key *cpu_key, u32 *data_size,
4906 for (i = 0; i < nr; i++)
4907 total_data += data_size[i];
4909 total_size = total_data + (nr * sizeof(struct btrfs_item));
4910 ret = btrfs_search_slot(trans, root, cpu_key, path, total_size, 1);
4916 slot = path->slots[0];
4919 setup_items_for_insert(root, path, cpu_key, data_size,
4920 total_data, total_size, nr);
4925 * Given a key and some data, insert an item into the tree.
4926 * This does all the path init required, making room in the tree if needed.
4928 int btrfs_insert_item(struct btrfs_trans_handle *trans, struct btrfs_root *root,
4929 const struct btrfs_key *cpu_key, void *data,
4933 struct btrfs_path *path;
4934 struct extent_buffer *leaf;
4937 path = btrfs_alloc_path();
4940 ret = btrfs_insert_empty_item(trans, root, path, cpu_key, data_size);
4942 leaf = path->nodes[0];
4943 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
4944 write_extent_buffer(leaf, data, ptr, data_size);
4945 btrfs_mark_buffer_dirty(leaf);
4947 btrfs_free_path(path);
4952 * delete the pointer from a given node.
4954 * the tree should have been previously balanced so the deletion does not
4957 static void del_ptr(struct btrfs_root *root, struct btrfs_path *path,
4958 int level, int slot)
4960 struct extent_buffer *parent = path->nodes[level];
4964 nritems = btrfs_header_nritems(parent);
4965 if (slot != nritems - 1) {
4967 ret = tree_mod_log_insert_move(parent, slot, slot + 1,
4968 nritems - slot - 1);
4971 memmove_extent_buffer(parent,
4972 btrfs_node_key_ptr_offset(slot),
4973 btrfs_node_key_ptr_offset(slot + 1),
4974 sizeof(struct btrfs_key_ptr) *
4975 (nritems - slot - 1));
4977 ret = tree_mod_log_insert_key(parent, slot, MOD_LOG_KEY_REMOVE,
4983 btrfs_set_header_nritems(parent, nritems);
4984 if (nritems == 0 && parent == root->node) {
4985 BUG_ON(btrfs_header_level(root->node) != 1);
4986 /* just turn the root into a leaf and break */
4987 btrfs_set_header_level(root->node, 0);
4988 } else if (slot == 0) {
4989 struct btrfs_disk_key disk_key;
4991 btrfs_node_key(parent, &disk_key, 0);
4992 fixup_low_keys(path, &disk_key, level + 1);
4994 btrfs_mark_buffer_dirty(parent);
4998 * a helper function to delete the leaf pointed to by path->slots[1] and
5001 * This deletes the pointer in path->nodes[1] and frees the leaf
5002 * block extent. zero is returned if it all worked out, < 0 otherwise.
5004 * The path must have already been setup for deleting the leaf, including
5005 * all the proper balancing. path->nodes[1] must be locked.
5007 static noinline void btrfs_del_leaf(struct btrfs_trans_handle *trans,
5008 struct btrfs_root *root,
5009 struct btrfs_path *path,
5010 struct extent_buffer *leaf)
5012 WARN_ON(btrfs_header_generation(leaf) != trans->transid);
5013 del_ptr(root, path, 1, path->slots[1]);
5016 * btrfs_free_extent is expensive, we want to make sure we
5017 * aren't holding any locks when we call it
5019 btrfs_unlock_up_safe(path, 0);
5021 root_sub_used(root, leaf->len);
5023 extent_buffer_get(leaf);
5024 btrfs_free_tree_block(trans, root, leaf, 0, 1);
5025 free_extent_buffer_stale(leaf);
5028 * delete the item at the leaf level in path. If that empties
5029 * the leaf, remove it from the tree
5031 int btrfs_del_items(struct btrfs_trans_handle *trans, struct btrfs_root *root,
5032 struct btrfs_path *path, int slot, int nr)
5034 struct btrfs_fs_info *fs_info = root->fs_info;
5035 struct extent_buffer *leaf;
5036 struct btrfs_item *item;
5043 struct btrfs_map_token token;
5045 btrfs_init_map_token(&token);
5047 leaf = path->nodes[0];
5048 last_off = btrfs_item_offset_nr(leaf, slot + nr - 1);
5050 for (i = 0; i < nr; i++)
5051 dsize += btrfs_item_size_nr(leaf, slot + i);
5053 nritems = btrfs_header_nritems(leaf);
5055 if (slot + nr != nritems) {
5056 int data_end = leaf_data_end(fs_info, leaf);
5058 memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
5060 BTRFS_LEAF_DATA_OFFSET + data_end,
5061 last_off - data_end);
5063 for (i = slot + nr; i < nritems; i++) {
5066 item = btrfs_item_nr(i);
5067 ioff = btrfs_token_item_offset(leaf, item, &token);
5068 btrfs_set_token_item_offset(leaf, item,
5069 ioff + dsize, &token);
5072 memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot),
5073 btrfs_item_nr_offset(slot + nr),
5074 sizeof(struct btrfs_item) *
5075 (nritems - slot - nr));
5077 btrfs_set_header_nritems(leaf, nritems - nr);
5080 /* delete the leaf if we've emptied it */
5082 if (leaf == root->node) {
5083 btrfs_set_header_level(leaf, 0);
5085 btrfs_set_path_blocking(path);
5086 clean_tree_block(fs_info, leaf);
5087 btrfs_del_leaf(trans, root, path, leaf);
5090 int used = leaf_space_used(leaf, 0, nritems);
5092 struct btrfs_disk_key disk_key;
5094 btrfs_item_key(leaf, &disk_key, 0);
5095 fixup_low_keys(path, &disk_key, 1);
5098 /* delete the leaf if it is mostly empty */
5099 if (used < BTRFS_LEAF_DATA_SIZE(fs_info) / 3) {
5100 /* push_leaf_left fixes the path.
5101 * make sure the path still points to our leaf
5102 * for possible call to del_ptr below
5104 slot = path->slots[1];
5105 extent_buffer_get(leaf);
5107 btrfs_set_path_blocking(path);
5108 wret = push_leaf_left(trans, root, path, 1, 1,
5110 if (wret < 0 && wret != -ENOSPC)
5113 if (path->nodes[0] == leaf &&
5114 btrfs_header_nritems(leaf)) {
5115 wret = push_leaf_right(trans, root, path, 1,
5117 if (wret < 0 && wret != -ENOSPC)
5121 if (btrfs_header_nritems(leaf) == 0) {
5122 path->slots[1] = slot;
5123 btrfs_del_leaf(trans, root, path, leaf);
5124 free_extent_buffer(leaf);
5127 /* if we're still in the path, make sure
5128 * we're dirty. Otherwise, one of the
5129 * push_leaf functions must have already
5130 * dirtied this buffer
5132 if (path->nodes[0] == leaf)
5133 btrfs_mark_buffer_dirty(leaf);
5134 free_extent_buffer(leaf);
5137 btrfs_mark_buffer_dirty(leaf);
5144 * search the tree again to find a leaf with lesser keys
5145 * returns 0 if it found something or 1 if there are no lesser leaves.
5146 * returns < 0 on io errors.
5148 * This may release the path, and so you may lose any locks held at the
5151 int btrfs_prev_leaf(struct btrfs_root *root, struct btrfs_path *path)
5153 struct btrfs_key key;
5154 struct btrfs_disk_key found_key;
5157 btrfs_item_key_to_cpu(path->nodes[0], &key, 0);
5159 if (key.offset > 0) {
5161 } else if (key.type > 0) {
5163 key.offset = (u64)-1;
5164 } else if (key.objectid > 0) {
5167 key.offset = (u64)-1;
5172 btrfs_release_path(path);
5173 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5176 btrfs_item_key(path->nodes[0], &found_key, 0);
5177 ret = comp_keys(&found_key, &key);
5179 * We might have had an item with the previous key in the tree right
5180 * before we released our path. And after we released our path, that
5181 * item might have been pushed to the first slot (0) of the leaf we
5182 * were holding due to a tree balance. Alternatively, an item with the
5183 * previous key can exist as the only element of a leaf (big fat item).
5184 * Therefore account for these 2 cases, so that our callers (like
5185 * btrfs_previous_item) don't miss an existing item with a key matching
5186 * the previous key we computed above.
5194 * A helper function to walk down the tree starting at min_key, and looking
5195 * for nodes or leaves that are have a minimum transaction id.
5196 * This is used by the btree defrag code, and tree logging
5198 * This does not cow, but it does stuff the starting key it finds back
5199 * into min_key, so you can call btrfs_search_slot with cow=1 on the
5200 * key and get a writable path.
5202 * This honors path->lowest_level to prevent descent past a given level
5205 * min_trans indicates the oldest transaction that you are interested
5206 * in walking through. Any nodes or leaves older than min_trans are
5207 * skipped over (without reading them).
5209 * returns zero if something useful was found, < 0 on error and 1 if there
5210 * was nothing in the tree that matched the search criteria.
5212 int btrfs_search_forward(struct btrfs_root *root, struct btrfs_key *min_key,
5213 struct btrfs_path *path,
5216 struct btrfs_fs_info *fs_info = root->fs_info;
5217 struct extent_buffer *cur;
5218 struct btrfs_key found_key;
5224 int keep_locks = path->keep_locks;
5226 path->keep_locks = 1;
5228 cur = btrfs_read_lock_root_node(root);
5229 level = btrfs_header_level(cur);
5230 WARN_ON(path->nodes[level]);
5231 path->nodes[level] = cur;
5232 path->locks[level] = BTRFS_READ_LOCK;
5234 if (btrfs_header_generation(cur) < min_trans) {
5239 nritems = btrfs_header_nritems(cur);
5240 level = btrfs_header_level(cur);
5241 sret = btrfs_bin_search(cur, min_key, level, &slot);
5243 /* at the lowest level, we're done, setup the path and exit */
5244 if (level == path->lowest_level) {
5245 if (slot >= nritems)
5248 path->slots[level] = slot;
5249 btrfs_item_key_to_cpu(cur, &found_key, slot);
5252 if (sret && slot > 0)
5255 * check this node pointer against the min_trans parameters.
5256 * If it is too old, old, skip to the next one.
5258 while (slot < nritems) {
5261 gen = btrfs_node_ptr_generation(cur, slot);
5262 if (gen < min_trans) {
5270 * we didn't find a candidate key in this node, walk forward
5271 * and find another one
5273 if (slot >= nritems) {
5274 path->slots[level] = slot;
5275 btrfs_set_path_blocking(path);
5276 sret = btrfs_find_next_key(root, path, min_key, level,
5279 btrfs_release_path(path);
5285 /* save our key for returning back */
5286 btrfs_node_key_to_cpu(cur, &found_key, slot);
5287 path->slots[level] = slot;
5288 if (level == path->lowest_level) {
5292 btrfs_set_path_blocking(path);
5293 cur = read_node_slot(fs_info, cur, slot);
5299 btrfs_tree_read_lock(cur);
5301 path->locks[level - 1] = BTRFS_READ_LOCK;
5302 path->nodes[level - 1] = cur;
5303 unlock_up(path, level, 1, 0, NULL);
5304 btrfs_clear_path_blocking(path, NULL, 0);
5307 path->keep_locks = keep_locks;
5309 btrfs_unlock_up_safe(path, path->lowest_level + 1);
5310 btrfs_set_path_blocking(path);
5311 memcpy(min_key, &found_key, sizeof(found_key));
5316 static int tree_move_down(struct btrfs_fs_info *fs_info,
5317 struct btrfs_path *path,
5320 struct extent_buffer *eb;
5322 BUG_ON(*level == 0);
5323 eb = read_node_slot(fs_info, path->nodes[*level], path->slots[*level]);
5327 path->nodes[*level - 1] = eb;
5328 path->slots[*level - 1] = 0;
5333 static int tree_move_next_or_upnext(struct btrfs_path *path,
5334 int *level, int root_level)
5338 nritems = btrfs_header_nritems(path->nodes[*level]);
5340 path->slots[*level]++;
5342 while (path->slots[*level] >= nritems) {
5343 if (*level == root_level)
5347 path->slots[*level] = 0;
5348 free_extent_buffer(path->nodes[*level]);
5349 path->nodes[*level] = NULL;
5351 path->slots[*level]++;
5353 nritems = btrfs_header_nritems(path->nodes[*level]);
5360 * Returns 1 if it had to move up and next. 0 is returned if it moved only next
5363 static int tree_advance(struct btrfs_fs_info *fs_info,
5364 struct btrfs_path *path,
5365 int *level, int root_level,
5367 struct btrfs_key *key)
5371 if (*level == 0 || !allow_down) {
5372 ret = tree_move_next_or_upnext(path, level, root_level);
5374 ret = tree_move_down(fs_info, path, level);
5378 btrfs_item_key_to_cpu(path->nodes[*level], key,
5379 path->slots[*level]);
5381 btrfs_node_key_to_cpu(path->nodes[*level], key,
5382 path->slots[*level]);
5387 static int tree_compare_item(struct btrfs_path *left_path,
5388 struct btrfs_path *right_path,
5393 unsigned long off1, off2;
5395 len1 = btrfs_item_size_nr(left_path->nodes[0], left_path->slots[0]);
5396 len2 = btrfs_item_size_nr(right_path->nodes[0], right_path->slots[0]);
5400 off1 = btrfs_item_ptr_offset(left_path->nodes[0], left_path->slots[0]);
5401 off2 = btrfs_item_ptr_offset(right_path->nodes[0],
5402 right_path->slots[0]);
5404 read_extent_buffer(left_path->nodes[0], tmp_buf, off1, len1);
5406 cmp = memcmp_extent_buffer(right_path->nodes[0], tmp_buf, off2, len1);
5413 #define ADVANCE_ONLY_NEXT -1
5416 * This function compares two trees and calls the provided callback for
5417 * every changed/new/deleted item it finds.
5418 * If shared tree blocks are encountered, whole subtrees are skipped, making
5419 * the compare pretty fast on snapshotted subvolumes.
5421 * This currently works on commit roots only. As commit roots are read only,
5422 * we don't do any locking. The commit roots are protected with transactions.
5423 * Transactions are ended and rejoined when a commit is tried in between.
5425 * This function checks for modifications done to the trees while comparing.
5426 * If it detects a change, it aborts immediately.
5428 int btrfs_compare_trees(struct btrfs_root *left_root,
5429 struct btrfs_root *right_root,
5430 btrfs_changed_cb_t changed_cb, void *ctx)
5432 struct btrfs_fs_info *fs_info = left_root->fs_info;
5435 struct btrfs_path *left_path = NULL;
5436 struct btrfs_path *right_path = NULL;
5437 struct btrfs_key left_key;
5438 struct btrfs_key right_key;
5439 char *tmp_buf = NULL;
5440 int left_root_level;
5441 int right_root_level;
5444 int left_end_reached;
5445 int right_end_reached;
5453 left_path = btrfs_alloc_path();
5458 right_path = btrfs_alloc_path();
5464 tmp_buf = kvmalloc(fs_info->nodesize, GFP_KERNEL);
5470 left_path->search_commit_root = 1;
5471 left_path->skip_locking = 1;
5472 right_path->search_commit_root = 1;
5473 right_path->skip_locking = 1;
5476 * Strategy: Go to the first items of both trees. Then do
5478 * If both trees are at level 0
5479 * Compare keys of current items
5480 * If left < right treat left item as new, advance left tree
5482 * If left > right treat right item as deleted, advance right tree
5484 * If left == right do deep compare of items, treat as changed if
5485 * needed, advance both trees and repeat
5486 * If both trees are at the same level but not at level 0
5487 * Compare keys of current nodes/leafs
5488 * If left < right advance left tree and repeat
5489 * If left > right advance right tree and repeat
5490 * If left == right compare blockptrs of the next nodes/leafs
5491 * If they match advance both trees but stay at the same level
5493 * If they don't match advance both trees while allowing to go
5495 * If tree levels are different
5496 * Advance the tree that needs it and repeat
5498 * Advancing a tree means:
5499 * If we are at level 0, try to go to the next slot. If that's not
5500 * possible, go one level up and repeat. Stop when we found a level
5501 * where we could go to the next slot. We may at this point be on a
5504 * If we are not at level 0 and not on shared tree blocks, go one
5507 * If we are not at level 0 and on shared tree blocks, go one slot to
5508 * the right if possible or go up and right.
5511 down_read(&fs_info->commit_root_sem);
5512 left_level = btrfs_header_level(left_root->commit_root);
5513 left_root_level = left_level;
5514 left_path->nodes[left_level] =
5515 btrfs_clone_extent_buffer(left_root->commit_root);
5516 if (!left_path->nodes[left_level]) {
5517 up_read(&fs_info->commit_root_sem);
5521 extent_buffer_get(left_path->nodes[left_level]);
5523 right_level = btrfs_header_level(right_root->commit_root);
5524 right_root_level = right_level;
5525 right_path->nodes[right_level] =
5526 btrfs_clone_extent_buffer(right_root->commit_root);
5527 if (!right_path->nodes[right_level]) {
5528 up_read(&fs_info->commit_root_sem);
5532 extent_buffer_get(right_path->nodes[right_level]);
5533 up_read(&fs_info->commit_root_sem);
5535 if (left_level == 0)
5536 btrfs_item_key_to_cpu(left_path->nodes[left_level],
5537 &left_key, left_path->slots[left_level]);
5539 btrfs_node_key_to_cpu(left_path->nodes[left_level],
5540 &left_key, left_path->slots[left_level]);
5541 if (right_level == 0)
5542 btrfs_item_key_to_cpu(right_path->nodes[right_level],
5543 &right_key, right_path->slots[right_level]);
5545 btrfs_node_key_to_cpu(right_path->nodes[right_level],
5546 &right_key, right_path->slots[right_level]);
5548 left_end_reached = right_end_reached = 0;
5549 advance_left = advance_right = 0;
5553 if (advance_left && !left_end_reached) {
5554 ret = tree_advance(fs_info, left_path, &left_level,
5556 advance_left != ADVANCE_ONLY_NEXT,
5559 left_end_reached = ADVANCE;
5564 if (advance_right && !right_end_reached) {
5565 ret = tree_advance(fs_info, right_path, &right_level,
5567 advance_right != ADVANCE_ONLY_NEXT,
5570 right_end_reached = ADVANCE;
5576 if (left_end_reached && right_end_reached) {
5579 } else if (left_end_reached) {
5580 if (right_level == 0) {
5581 ret = changed_cb(left_path, right_path,
5583 BTRFS_COMPARE_TREE_DELETED,
5588 advance_right = ADVANCE;
5590 } else if (right_end_reached) {
5591 if (left_level == 0) {
5592 ret = changed_cb(left_path, right_path,
5594 BTRFS_COMPARE_TREE_NEW,
5599 advance_left = ADVANCE;
5603 if (left_level == 0 && right_level == 0) {
5604 cmp = btrfs_comp_cpu_keys(&left_key, &right_key);
5606 ret = changed_cb(left_path, right_path,
5608 BTRFS_COMPARE_TREE_NEW,
5612 advance_left = ADVANCE;
5613 } else if (cmp > 0) {
5614 ret = changed_cb(left_path, right_path,
5616 BTRFS_COMPARE_TREE_DELETED,
5620 advance_right = ADVANCE;
5622 enum btrfs_compare_tree_result result;
5624 WARN_ON(!extent_buffer_uptodate(left_path->nodes[0]));
5625 ret = tree_compare_item(left_path, right_path,
5628 result = BTRFS_COMPARE_TREE_CHANGED;
5630 result = BTRFS_COMPARE_TREE_SAME;
5631 ret = changed_cb(left_path, right_path,
5632 &left_key, result, ctx);
5635 advance_left = ADVANCE;
5636 advance_right = ADVANCE;
5638 } else if (left_level == right_level) {
5639 cmp = btrfs_comp_cpu_keys(&left_key, &right_key);
5641 advance_left = ADVANCE;
5642 } else if (cmp > 0) {
5643 advance_right = ADVANCE;
5645 left_blockptr = btrfs_node_blockptr(
5646 left_path->nodes[left_level],
5647 left_path->slots[left_level]);
5648 right_blockptr = btrfs_node_blockptr(
5649 right_path->nodes[right_level],
5650 right_path->slots[right_level]);
5651 left_gen = btrfs_node_ptr_generation(
5652 left_path->nodes[left_level],
5653 left_path->slots[left_level]);
5654 right_gen = btrfs_node_ptr_generation(
5655 right_path->nodes[right_level],
5656 right_path->slots[right_level]);
5657 if (left_blockptr == right_blockptr &&
5658 left_gen == right_gen) {
5660 * As we're on a shared block, don't
5661 * allow to go deeper.
5663 advance_left = ADVANCE_ONLY_NEXT;
5664 advance_right = ADVANCE_ONLY_NEXT;
5666 advance_left = ADVANCE;
5667 advance_right = ADVANCE;
5670 } else if (left_level < right_level) {
5671 advance_right = ADVANCE;
5673 advance_left = ADVANCE;
5678 btrfs_free_path(left_path);
5679 btrfs_free_path(right_path);
5685 * this is similar to btrfs_next_leaf, but does not try to preserve
5686 * and fixup the path. It looks for and returns the next key in the
5687 * tree based on the current path and the min_trans parameters.
5689 * 0 is returned if another key is found, < 0 if there are any errors
5690 * and 1 is returned if there are no higher keys in the tree
5692 * path->keep_locks should be set to 1 on the search made before
5693 * calling this function.
5695 int btrfs_find_next_key(struct btrfs_root *root, struct btrfs_path *path,
5696 struct btrfs_key *key, int level, u64 min_trans)
5699 struct extent_buffer *c;
5701 WARN_ON(!path->keep_locks);
5702 while (level < BTRFS_MAX_LEVEL) {
5703 if (!path->nodes[level])
5706 slot = path->slots[level] + 1;
5707 c = path->nodes[level];
5709 if (slot >= btrfs_header_nritems(c)) {
5712 struct btrfs_key cur_key;
5713 if (level + 1 >= BTRFS_MAX_LEVEL ||
5714 !path->nodes[level + 1])
5717 if (path->locks[level + 1]) {
5722 slot = btrfs_header_nritems(c) - 1;
5724 btrfs_item_key_to_cpu(c, &cur_key, slot);
5726 btrfs_node_key_to_cpu(c, &cur_key, slot);
5728 orig_lowest = path->lowest_level;
5729 btrfs_release_path(path);
5730 path->lowest_level = level;
5731 ret = btrfs_search_slot(NULL, root, &cur_key, path,
5733 path->lowest_level = orig_lowest;
5737 c = path->nodes[level];
5738 slot = path->slots[level];
5745 btrfs_item_key_to_cpu(c, key, slot);
5747 u64 gen = btrfs_node_ptr_generation(c, slot);
5749 if (gen < min_trans) {
5753 btrfs_node_key_to_cpu(c, key, slot);
5761 * search the tree again to find a leaf with greater keys
5762 * returns 0 if it found something or 1 if there are no greater leaves.
5763 * returns < 0 on io errors.
5765 int btrfs_next_leaf(struct btrfs_root *root, struct btrfs_path *path)
5767 return btrfs_next_old_leaf(root, path, 0);
5770 int btrfs_next_old_leaf(struct btrfs_root *root, struct btrfs_path *path,
5775 struct extent_buffer *c;
5776 struct extent_buffer *next;
5777 struct btrfs_key key;
5780 int old_spinning = path->leave_spinning;
5781 int next_rw_lock = 0;
5783 nritems = btrfs_header_nritems(path->nodes[0]);
5787 btrfs_item_key_to_cpu(path->nodes[0], &key, nritems - 1);
5792 btrfs_release_path(path);
5794 path->keep_locks = 1;
5795 path->leave_spinning = 1;
5798 ret = btrfs_search_old_slot(root, &key, path, time_seq);
5800 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5801 path->keep_locks = 0;
5806 nritems = btrfs_header_nritems(path->nodes[0]);
5808 * by releasing the path above we dropped all our locks. A balance
5809 * could have added more items next to the key that used to be
5810 * at the very end of the block. So, check again here and
5811 * advance the path if there are now more items available.
5813 if (nritems > 0 && path->slots[0] < nritems - 1) {
5820 * So the above check misses one case:
5821 * - after releasing the path above, someone has removed the item that
5822 * used to be at the very end of the block, and balance between leafs
5823 * gets another one with bigger key.offset to replace it.
5825 * This one should be returned as well, or we can get leaf corruption
5826 * later(esp. in __btrfs_drop_extents()).
5828 * And a bit more explanation about this check,
5829 * with ret > 0, the key isn't found, the path points to the slot
5830 * where it should be inserted, so the path->slots[0] item must be the
5833 if (nritems > 0 && ret > 0 && path->slots[0] == nritems - 1) {
5838 while (level < BTRFS_MAX_LEVEL) {
5839 if (!path->nodes[level]) {
5844 slot = path->slots[level] + 1;
5845 c = path->nodes[level];
5846 if (slot >= btrfs_header_nritems(c)) {
5848 if (level == BTRFS_MAX_LEVEL) {
5856 btrfs_tree_unlock_rw(next, next_rw_lock);
5857 free_extent_buffer(next);
5861 next_rw_lock = path->locks[level];
5862 ret = read_block_for_search(root, path, &next, level,
5868 btrfs_release_path(path);
5872 if (!path->skip_locking) {
5873 ret = btrfs_try_tree_read_lock(next);
5874 if (!ret && time_seq) {
5876 * If we don't get the lock, we may be racing
5877 * with push_leaf_left, holding that lock while
5878 * itself waiting for the leaf we've currently
5879 * locked. To solve this situation, we give up
5880 * on our lock and cycle.
5882 free_extent_buffer(next);
5883 btrfs_release_path(path);
5888 btrfs_set_path_blocking(path);
5889 btrfs_tree_read_lock(next);
5890 btrfs_clear_path_blocking(path, next,
5893 next_rw_lock = BTRFS_READ_LOCK;
5897 path->slots[level] = slot;
5900 c = path->nodes[level];
5901 if (path->locks[level])
5902 btrfs_tree_unlock_rw(c, path->locks[level]);
5904 free_extent_buffer(c);
5905 path->nodes[level] = next;
5906 path->slots[level] = 0;
5907 if (!path->skip_locking)
5908 path->locks[level] = next_rw_lock;
5912 ret = read_block_for_search(root, path, &next, level,
5918 btrfs_release_path(path);
5922 if (!path->skip_locking) {
5923 ret = btrfs_try_tree_read_lock(next);
5925 btrfs_set_path_blocking(path);
5926 btrfs_tree_read_lock(next);
5927 btrfs_clear_path_blocking(path, next,
5930 next_rw_lock = BTRFS_READ_LOCK;
5935 unlock_up(path, 0, 1, 0, NULL);
5936 path->leave_spinning = old_spinning;
5938 btrfs_set_path_blocking(path);
5944 * this uses btrfs_prev_leaf to walk backwards in the tree, and keeps
5945 * searching until it gets past min_objectid or finds an item of 'type'
5947 * returns 0 if something is found, 1 if nothing was found and < 0 on error
5949 int btrfs_previous_item(struct btrfs_root *root,
5950 struct btrfs_path *path, u64 min_objectid,
5953 struct btrfs_key found_key;
5954 struct extent_buffer *leaf;
5959 if (path->slots[0] == 0) {
5960 btrfs_set_path_blocking(path);
5961 ret = btrfs_prev_leaf(root, path);
5967 leaf = path->nodes[0];
5968 nritems = btrfs_header_nritems(leaf);
5971 if (path->slots[0] == nritems)
5974 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5975 if (found_key.objectid < min_objectid)
5977 if (found_key.type == type)
5979 if (found_key.objectid == min_objectid &&
5980 found_key.type < type)
5987 * search in extent tree to find a previous Metadata/Data extent item with
5990 * returns 0 if something is found, 1 if nothing was found and < 0 on error
5992 int btrfs_previous_extent_item(struct btrfs_root *root,
5993 struct btrfs_path *path, u64 min_objectid)
5995 struct btrfs_key found_key;
5996 struct extent_buffer *leaf;
6001 if (path->slots[0] == 0) {
6002 btrfs_set_path_blocking(path);
6003 ret = btrfs_prev_leaf(root, path);
6009 leaf = path->nodes[0];
6010 nritems = btrfs_header_nritems(leaf);
6013 if (path->slots[0] == nritems)
6016 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6017 if (found_key.objectid < min_objectid)
6019 if (found_key.type == BTRFS_EXTENT_ITEM_KEY ||
6020 found_key.type == BTRFS_METADATA_ITEM_KEY)
6022 if (found_key.objectid == min_objectid &&
6023 found_key.type < BTRFS_EXTENT_ITEM_KEY)