xref: /openbmc/linux/fs/btrfs/ctree.c (revision 581c1760415c48cca9349b198bba52dd38750765)
16cbd5570SChris Mason /*
2d352ac68SChris Mason  * Copyright (C) 2007,2008 Oracle.  All rights reserved.
36cbd5570SChris Mason  *
46cbd5570SChris Mason  * This program is free software; you can redistribute it and/or
56cbd5570SChris Mason  * modify it under the terms of the GNU General Public
66cbd5570SChris Mason  * License v2 as published by the Free Software Foundation.
76cbd5570SChris Mason  *
86cbd5570SChris Mason  * This program is distributed in the hope that it will be useful,
96cbd5570SChris Mason  * but WITHOUT ANY WARRANTY; without even the implied warranty of
106cbd5570SChris Mason  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
116cbd5570SChris Mason  * General Public License for more details.
126cbd5570SChris Mason  *
136cbd5570SChris Mason  * You should have received a copy of the GNU General Public
146cbd5570SChris Mason  * License along with this program; if not, write to the
156cbd5570SChris Mason  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
166cbd5570SChris Mason  * Boston, MA 021110-1307, USA.
176cbd5570SChris Mason  */
186cbd5570SChris Mason 
19a6b6e75eSChris Mason #include <linux/sched.h>
205a0e3ad6STejun Heo #include <linux/slab.h>
21bd989ba3SJan Schmidt #include <linux/rbtree.h>
22adf02123SDavid Sterba #include <linux/mm.h>
23eb60ceacSChris Mason #include "ctree.h"
24eb60ceacSChris Mason #include "disk-io.h"
257f5c1516SChris Mason #include "transaction.h"
265f39d397SChris Mason #include "print-tree.h"
27925baeddSChris Mason #include "locking.h"
289a8dd150SChris Mason 
29e089f05cSChris Mason static int split_node(struct btrfs_trans_handle *trans, struct btrfs_root
30e089f05cSChris Mason 		      *root, struct btrfs_path *path, int level);
31310712b2SOmar Sandoval static int split_leaf(struct btrfs_trans_handle *trans, struct btrfs_root *root,
32310712b2SOmar Sandoval 		      const struct btrfs_key *ins_key, struct btrfs_path *path,
33310712b2SOmar Sandoval 		      int data_size, int extend);
345f39d397SChris Mason static int push_node_left(struct btrfs_trans_handle *trans,
352ff7e61eSJeff Mahoney 			  struct btrfs_fs_info *fs_info,
362ff7e61eSJeff Mahoney 			  struct extent_buffer *dst,
37971a1f66SChris Mason 			  struct extent_buffer *src, int empty);
385f39d397SChris Mason static int balance_node_right(struct btrfs_trans_handle *trans,
392ff7e61eSJeff Mahoney 			      struct btrfs_fs_info *fs_info,
405f39d397SChris Mason 			      struct extent_buffer *dst_buf,
415f39d397SChris Mason 			      struct extent_buffer *src_buf);
42afe5fea7STsutomu Itoh static void del_ptr(struct btrfs_root *root, struct btrfs_path *path,
43afe5fea7STsutomu Itoh 		    int level, int slot);
44d97e63b6SChris Mason 
452c90e5d6SChris Mason struct btrfs_path *btrfs_alloc_path(void)
462c90e5d6SChris Mason {
47e2c89907SMasahiro Yamada 	return kmem_cache_zalloc(btrfs_path_cachep, GFP_NOFS);
482c90e5d6SChris Mason }
492c90e5d6SChris Mason 
50b4ce94deSChris Mason /*
51b4ce94deSChris Mason  * set all locked nodes in the path to blocking locks.  This should
52b4ce94deSChris Mason  * be done before scheduling
53b4ce94deSChris Mason  */
54b4ce94deSChris Mason noinline void btrfs_set_path_blocking(struct btrfs_path *p)
55b4ce94deSChris Mason {
56b4ce94deSChris Mason 	int i;
57b4ce94deSChris Mason 	for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
58bd681513SChris Mason 		if (!p->nodes[i] || !p->locks[i])
59bd681513SChris Mason 			continue;
60bd681513SChris Mason 		btrfs_set_lock_blocking_rw(p->nodes[i], p->locks[i]);
61bd681513SChris Mason 		if (p->locks[i] == BTRFS_READ_LOCK)
62bd681513SChris Mason 			p->locks[i] = BTRFS_READ_LOCK_BLOCKING;
63bd681513SChris Mason 		else if (p->locks[i] == BTRFS_WRITE_LOCK)
64bd681513SChris Mason 			p->locks[i] = BTRFS_WRITE_LOCK_BLOCKING;
65b4ce94deSChris Mason 	}
66b4ce94deSChris Mason }
67b4ce94deSChris Mason 
68b4ce94deSChris Mason /*
69b4ce94deSChris Mason  * reset all the locked nodes in the patch to spinning locks.
704008c04aSChris Mason  *
714008c04aSChris Mason  * held is used to keep lockdep happy, when lockdep is enabled
724008c04aSChris Mason  * we set held to a blocking lock before we go around and
734008c04aSChris Mason  * retake all the spinlocks in the path.  You can safely use NULL
744008c04aSChris Mason  * for held
75b4ce94deSChris Mason  */
764008c04aSChris Mason noinline void btrfs_clear_path_blocking(struct btrfs_path *p,
77bd681513SChris Mason 					struct extent_buffer *held, int held_rw)
78b4ce94deSChris Mason {
79b4ce94deSChris Mason 	int i;
804008c04aSChris Mason 
81bd681513SChris Mason 	if (held) {
82bd681513SChris Mason 		btrfs_set_lock_blocking_rw(held, held_rw);
83bd681513SChris Mason 		if (held_rw == BTRFS_WRITE_LOCK)
84bd681513SChris Mason 			held_rw = BTRFS_WRITE_LOCK_BLOCKING;
85bd681513SChris Mason 		else if (held_rw == BTRFS_READ_LOCK)
86bd681513SChris Mason 			held_rw = BTRFS_READ_LOCK_BLOCKING;
87bd681513SChris Mason 	}
884008c04aSChris Mason 	btrfs_set_path_blocking(p);
894008c04aSChris Mason 
904008c04aSChris Mason 	for (i = BTRFS_MAX_LEVEL - 1; i >= 0; i--) {
91bd681513SChris Mason 		if (p->nodes[i] && p->locks[i]) {
92bd681513SChris Mason 			btrfs_clear_lock_blocking_rw(p->nodes[i], p->locks[i]);
93bd681513SChris Mason 			if (p->locks[i] == BTRFS_WRITE_LOCK_BLOCKING)
94bd681513SChris Mason 				p->locks[i] = BTRFS_WRITE_LOCK;
95bd681513SChris Mason 			else if (p->locks[i] == BTRFS_READ_LOCK_BLOCKING)
96bd681513SChris Mason 				p->locks[i] = BTRFS_READ_LOCK;
97bd681513SChris Mason 		}
98b4ce94deSChris Mason 	}
994008c04aSChris Mason 
1004008c04aSChris Mason 	if (held)
101bd681513SChris Mason 		btrfs_clear_lock_blocking_rw(held, held_rw);
102b4ce94deSChris Mason }
103b4ce94deSChris Mason 
104d352ac68SChris Mason /* this also releases the path */
1052c90e5d6SChris Mason void btrfs_free_path(struct btrfs_path *p)
1062c90e5d6SChris Mason {
107ff175d57SJesper Juhl 	if (!p)
108ff175d57SJesper Juhl 		return;
109b3b4aa74SDavid Sterba 	btrfs_release_path(p);
1102c90e5d6SChris Mason 	kmem_cache_free(btrfs_path_cachep, p);
1112c90e5d6SChris Mason }
1122c90e5d6SChris Mason 
113d352ac68SChris Mason /*
114d352ac68SChris Mason  * path release drops references on the extent buffers in the path
115d352ac68SChris Mason  * and it drops any locks held by this path
116d352ac68SChris Mason  *
117d352ac68SChris Mason  * It is safe to call this on paths that no locks or extent buffers held.
118d352ac68SChris Mason  */
119b3b4aa74SDavid Sterba noinline void btrfs_release_path(struct btrfs_path *p)
120eb60ceacSChris Mason {
121eb60ceacSChris Mason 	int i;
122a2135011SChris Mason 
123234b63a0SChris Mason 	for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
1243f157a2fSChris Mason 		p->slots[i] = 0;
125eb60ceacSChris Mason 		if (!p->nodes[i])
126925baeddSChris Mason 			continue;
127925baeddSChris Mason 		if (p->locks[i]) {
128bd681513SChris Mason 			btrfs_tree_unlock_rw(p->nodes[i], p->locks[i]);
129925baeddSChris Mason 			p->locks[i] = 0;
130925baeddSChris Mason 		}
1315f39d397SChris Mason 		free_extent_buffer(p->nodes[i]);
1323f157a2fSChris Mason 		p->nodes[i] = NULL;
133eb60ceacSChris Mason 	}
134eb60ceacSChris Mason }
135eb60ceacSChris Mason 
136d352ac68SChris Mason /*
137d352ac68SChris Mason  * safely gets a reference on the root node of a tree.  A lock
138d352ac68SChris Mason  * is not taken, so a concurrent writer may put a different node
139d352ac68SChris Mason  * at the root of the tree.  See btrfs_lock_root_node for the
140d352ac68SChris Mason  * looping required.
141d352ac68SChris Mason  *
142d352ac68SChris Mason  * The extent buffer returned by this has a reference taken, so
143d352ac68SChris Mason  * it won't disappear.  It may stop being the root of the tree
144d352ac68SChris Mason  * at any time because there are no locks held.
145d352ac68SChris Mason  */
146925baeddSChris Mason struct extent_buffer *btrfs_root_node(struct btrfs_root *root)
147925baeddSChris Mason {
148925baeddSChris Mason 	struct extent_buffer *eb;
149240f62c8SChris Mason 
1503083ee2eSJosef Bacik 	while (1) {
151240f62c8SChris Mason 		rcu_read_lock();
152240f62c8SChris Mason 		eb = rcu_dereference(root->node);
1533083ee2eSJosef Bacik 
1543083ee2eSJosef Bacik 		/*
1553083ee2eSJosef Bacik 		 * RCU really hurts here, we could free up the root node because
15601327610SNicholas D Steeves 		 * it was COWed but we may not get the new root node yet so do
1573083ee2eSJosef Bacik 		 * the inc_not_zero dance and if it doesn't work then
1583083ee2eSJosef Bacik 		 * synchronize_rcu and try again.
1593083ee2eSJosef Bacik 		 */
1603083ee2eSJosef Bacik 		if (atomic_inc_not_zero(&eb->refs)) {
161240f62c8SChris Mason 			rcu_read_unlock();
1623083ee2eSJosef Bacik 			break;
1633083ee2eSJosef Bacik 		}
1643083ee2eSJosef Bacik 		rcu_read_unlock();
1653083ee2eSJosef Bacik 		synchronize_rcu();
1663083ee2eSJosef Bacik 	}
167925baeddSChris Mason 	return eb;
168925baeddSChris Mason }
169925baeddSChris Mason 
170d352ac68SChris Mason /* loop around taking references on and locking the root node of the
171d352ac68SChris Mason  * tree until you end up with a lock on the root.  A locked buffer
172d352ac68SChris Mason  * is returned, with a reference held.
173d352ac68SChris Mason  */
174925baeddSChris Mason struct extent_buffer *btrfs_lock_root_node(struct btrfs_root *root)
175925baeddSChris Mason {
176925baeddSChris Mason 	struct extent_buffer *eb;
177925baeddSChris Mason 
178925baeddSChris Mason 	while (1) {
179925baeddSChris Mason 		eb = btrfs_root_node(root);
180925baeddSChris Mason 		btrfs_tree_lock(eb);
181240f62c8SChris Mason 		if (eb == root->node)
182925baeddSChris Mason 			break;
183925baeddSChris Mason 		btrfs_tree_unlock(eb);
184925baeddSChris Mason 		free_extent_buffer(eb);
185925baeddSChris Mason 	}
186925baeddSChris Mason 	return eb;
187925baeddSChris Mason }
188925baeddSChris Mason 
189bd681513SChris Mason /* loop around taking references on and locking the root node of the
190bd681513SChris Mason  * tree until you end up with a lock on the root.  A locked buffer
191bd681513SChris Mason  * is returned, with a reference held.
192bd681513SChris Mason  */
19384f7d8e6SJosef Bacik struct extent_buffer *btrfs_read_lock_root_node(struct btrfs_root *root)
194bd681513SChris Mason {
195bd681513SChris Mason 	struct extent_buffer *eb;
196bd681513SChris Mason 
197bd681513SChris Mason 	while (1) {
198bd681513SChris Mason 		eb = btrfs_root_node(root);
199bd681513SChris Mason 		btrfs_tree_read_lock(eb);
200bd681513SChris Mason 		if (eb == root->node)
201bd681513SChris Mason 			break;
202bd681513SChris Mason 		btrfs_tree_read_unlock(eb);
203bd681513SChris Mason 		free_extent_buffer(eb);
204bd681513SChris Mason 	}
205bd681513SChris Mason 	return eb;
206bd681513SChris Mason }
207bd681513SChris Mason 
208d352ac68SChris Mason /* cowonly root (everything not a reference counted cow subvolume), just get
209d352ac68SChris Mason  * put onto a simple dirty list.  transaction.c walks this to make sure they
210d352ac68SChris Mason  * get properly updated on disk.
211d352ac68SChris Mason  */
2120b86a832SChris Mason static void add_root_to_dirty_list(struct btrfs_root *root)
2130b86a832SChris Mason {
2140b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
2150b246afaSJeff Mahoney 
216e7070be1SJosef Bacik 	if (test_bit(BTRFS_ROOT_DIRTY, &root->state) ||
217e7070be1SJosef Bacik 	    !test_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state))
218e7070be1SJosef Bacik 		return;
219e7070be1SJosef Bacik 
2200b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
221e7070be1SJosef Bacik 	if (!test_and_set_bit(BTRFS_ROOT_DIRTY, &root->state)) {
222e7070be1SJosef Bacik 		/* Want the extent tree to be the last on the list */
223e7070be1SJosef Bacik 		if (root->objectid == BTRFS_EXTENT_TREE_OBJECTID)
224e7070be1SJosef Bacik 			list_move_tail(&root->dirty_list,
2250b246afaSJeff Mahoney 				       &fs_info->dirty_cowonly_roots);
226e7070be1SJosef Bacik 		else
227e7070be1SJosef Bacik 			list_move(&root->dirty_list,
2280b246afaSJeff Mahoney 				  &fs_info->dirty_cowonly_roots);
2290b86a832SChris Mason 	}
2300b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
2310b86a832SChris Mason }
2320b86a832SChris Mason 
233d352ac68SChris Mason /*
234d352ac68SChris Mason  * used by snapshot creation to make a copy of a root for a tree with
235d352ac68SChris Mason  * a given objectid.  The buffer with the new root node is returned in
236d352ac68SChris Mason  * cow_ret, and this func returns zero on success or a negative error code.
237d352ac68SChris Mason  */
238be20aa9dSChris Mason int btrfs_copy_root(struct btrfs_trans_handle *trans,
239be20aa9dSChris Mason 		      struct btrfs_root *root,
240be20aa9dSChris Mason 		      struct extent_buffer *buf,
241be20aa9dSChris Mason 		      struct extent_buffer **cow_ret, u64 new_root_objectid)
242be20aa9dSChris Mason {
2430b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
244be20aa9dSChris Mason 	struct extent_buffer *cow;
245be20aa9dSChris Mason 	int ret = 0;
246be20aa9dSChris Mason 	int level;
2475d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
248be20aa9dSChris Mason 
24927cdeb70SMiao Xie 	WARN_ON(test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
2500b246afaSJeff Mahoney 		trans->transid != fs_info->running_transaction->transid);
25127cdeb70SMiao Xie 	WARN_ON(test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
25227cdeb70SMiao Xie 		trans->transid != root->last_trans);
253be20aa9dSChris Mason 
254be20aa9dSChris Mason 	level = btrfs_header_level(buf);
2555d4f98a2SYan Zheng 	if (level == 0)
2565d4f98a2SYan Zheng 		btrfs_item_key(buf, &disk_key, 0);
2575d4f98a2SYan Zheng 	else
2585d4f98a2SYan Zheng 		btrfs_node_key(buf, &disk_key, 0);
25931840ae1SZheng Yan 
2604d75f8a9SDavid Sterba 	cow = btrfs_alloc_tree_block(trans, root, 0, new_root_objectid,
2614d75f8a9SDavid Sterba 			&disk_key, level, buf->start, 0);
2625d4f98a2SYan Zheng 	if (IS_ERR(cow))
263be20aa9dSChris Mason 		return PTR_ERR(cow);
264be20aa9dSChris Mason 
26558e8012cSDavid Sterba 	copy_extent_buffer_full(cow, buf);
266be20aa9dSChris Mason 	btrfs_set_header_bytenr(cow, cow->start);
267be20aa9dSChris Mason 	btrfs_set_header_generation(cow, trans->transid);
2685d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
2695d4f98a2SYan Zheng 	btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
2705d4f98a2SYan Zheng 				     BTRFS_HEADER_FLAG_RELOC);
2715d4f98a2SYan Zheng 	if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
2725d4f98a2SYan Zheng 		btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
2735d4f98a2SYan Zheng 	else
274be20aa9dSChris Mason 		btrfs_set_header_owner(cow, new_root_objectid);
275be20aa9dSChris Mason 
2760b246afaSJeff Mahoney 	write_extent_buffer_fsid(cow, fs_info->fsid);
2772b82032cSYan Zheng 
278be20aa9dSChris Mason 	WARN_ON(btrfs_header_generation(buf) > trans->transid);
2795d4f98a2SYan Zheng 	if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
280e339a6b0SJosef Bacik 		ret = btrfs_inc_ref(trans, root, cow, 1);
2815d4f98a2SYan Zheng 	else
282e339a6b0SJosef Bacik 		ret = btrfs_inc_ref(trans, root, cow, 0);
2834aec2b52SChris Mason 
284be20aa9dSChris Mason 	if (ret)
285be20aa9dSChris Mason 		return ret;
286be20aa9dSChris Mason 
287be20aa9dSChris Mason 	btrfs_mark_buffer_dirty(cow);
288be20aa9dSChris Mason 	*cow_ret = cow;
289be20aa9dSChris Mason 	return 0;
290be20aa9dSChris Mason }
291be20aa9dSChris Mason 
292bd989ba3SJan Schmidt enum mod_log_op {
293bd989ba3SJan Schmidt 	MOD_LOG_KEY_REPLACE,
294bd989ba3SJan Schmidt 	MOD_LOG_KEY_ADD,
295bd989ba3SJan Schmidt 	MOD_LOG_KEY_REMOVE,
296bd989ba3SJan Schmidt 	MOD_LOG_KEY_REMOVE_WHILE_FREEING,
297bd989ba3SJan Schmidt 	MOD_LOG_KEY_REMOVE_WHILE_MOVING,
298bd989ba3SJan Schmidt 	MOD_LOG_MOVE_KEYS,
299bd989ba3SJan Schmidt 	MOD_LOG_ROOT_REPLACE,
300bd989ba3SJan Schmidt };
301bd989ba3SJan Schmidt 
302bd989ba3SJan Schmidt struct tree_mod_root {
303bd989ba3SJan Schmidt 	u64 logical;
304bd989ba3SJan Schmidt 	u8 level;
305bd989ba3SJan Schmidt };
306bd989ba3SJan Schmidt 
307bd989ba3SJan Schmidt struct tree_mod_elem {
308bd989ba3SJan Schmidt 	struct rb_node node;
309298cfd36SChandan Rajendra 	u64 logical;
310097b8a7cSJan Schmidt 	u64 seq;
311bd989ba3SJan Schmidt 	enum mod_log_op op;
312bd989ba3SJan Schmidt 
313bd989ba3SJan Schmidt 	/* this is used for MOD_LOG_KEY_* and MOD_LOG_MOVE_KEYS operations */
314bd989ba3SJan Schmidt 	int slot;
315bd989ba3SJan Schmidt 
316bd989ba3SJan Schmidt 	/* this is used for MOD_LOG_KEY* and MOD_LOG_ROOT_REPLACE */
317bd989ba3SJan Schmidt 	u64 generation;
318bd989ba3SJan Schmidt 
319bd989ba3SJan Schmidt 	/* those are used for op == MOD_LOG_KEY_{REPLACE,REMOVE} */
320bd989ba3SJan Schmidt 	struct btrfs_disk_key key;
321bd989ba3SJan Schmidt 	u64 blockptr;
322bd989ba3SJan Schmidt 
323bd989ba3SJan Schmidt 	/* this is used for op == MOD_LOG_MOVE_KEYS */
324b6dfa35bSDavid Sterba 	struct {
325b6dfa35bSDavid Sterba 		int dst_slot;
326b6dfa35bSDavid Sterba 		int nr_items;
327b6dfa35bSDavid Sterba 	} move;
328bd989ba3SJan Schmidt 
329bd989ba3SJan Schmidt 	/* this is used for op == MOD_LOG_ROOT_REPLACE */
330bd989ba3SJan Schmidt 	struct tree_mod_root old_root;
331bd989ba3SJan Schmidt };
332bd989ba3SJan Schmidt 
333097b8a7cSJan Schmidt /*
334fcebe456SJosef Bacik  * Pull a new tree mod seq number for our operation.
335fc36ed7eSJan Schmidt  */
336fcebe456SJosef Bacik static inline u64 btrfs_inc_tree_mod_seq(struct btrfs_fs_info *fs_info)
337fc36ed7eSJan Schmidt {
338fc36ed7eSJan Schmidt 	return atomic64_inc_return(&fs_info->tree_mod_seq);
339fc36ed7eSJan Schmidt }
340fc36ed7eSJan Schmidt 
341fc36ed7eSJan Schmidt /*
342097b8a7cSJan Schmidt  * This adds a new blocker to the tree mod log's blocker list if the @elem
343097b8a7cSJan Schmidt  * passed does not already have a sequence number set. So when a caller expects
344097b8a7cSJan Schmidt  * to record tree modifications, it should ensure to set elem->seq to zero
345097b8a7cSJan Schmidt  * before calling btrfs_get_tree_mod_seq.
346097b8a7cSJan Schmidt  * Returns a fresh, unused tree log modification sequence number, even if no new
347097b8a7cSJan Schmidt  * blocker was added.
348097b8a7cSJan Schmidt  */
349097b8a7cSJan Schmidt u64 btrfs_get_tree_mod_seq(struct btrfs_fs_info *fs_info,
350bd989ba3SJan Schmidt 			   struct seq_list *elem)
351bd989ba3SJan Schmidt {
352b1a09f1eSDavid Sterba 	write_lock(&fs_info->tree_mod_log_lock);
353bd989ba3SJan Schmidt 	spin_lock(&fs_info->tree_mod_seq_lock);
354097b8a7cSJan Schmidt 	if (!elem->seq) {
355fcebe456SJosef Bacik 		elem->seq = btrfs_inc_tree_mod_seq(fs_info);
356097b8a7cSJan Schmidt 		list_add_tail(&elem->list, &fs_info->tree_mod_seq_list);
357097b8a7cSJan Schmidt 	}
358bd989ba3SJan Schmidt 	spin_unlock(&fs_info->tree_mod_seq_lock);
359b1a09f1eSDavid Sterba 	write_unlock(&fs_info->tree_mod_log_lock);
360097b8a7cSJan Schmidt 
361fcebe456SJosef Bacik 	return elem->seq;
362bd989ba3SJan Schmidt }
363bd989ba3SJan Schmidt 
364bd989ba3SJan Schmidt void btrfs_put_tree_mod_seq(struct btrfs_fs_info *fs_info,
365bd989ba3SJan Schmidt 			    struct seq_list *elem)
366bd989ba3SJan Schmidt {
367bd989ba3SJan Schmidt 	struct rb_root *tm_root;
368bd989ba3SJan Schmidt 	struct rb_node *node;
369bd989ba3SJan Schmidt 	struct rb_node *next;
370bd989ba3SJan Schmidt 	struct seq_list *cur_elem;
371bd989ba3SJan Schmidt 	struct tree_mod_elem *tm;
372bd989ba3SJan Schmidt 	u64 min_seq = (u64)-1;
373bd989ba3SJan Schmidt 	u64 seq_putting = elem->seq;
374bd989ba3SJan Schmidt 
375bd989ba3SJan Schmidt 	if (!seq_putting)
376bd989ba3SJan Schmidt 		return;
377bd989ba3SJan Schmidt 
378bd989ba3SJan Schmidt 	spin_lock(&fs_info->tree_mod_seq_lock);
379bd989ba3SJan Schmidt 	list_del(&elem->list);
380097b8a7cSJan Schmidt 	elem->seq = 0;
381bd989ba3SJan Schmidt 
382bd989ba3SJan Schmidt 	list_for_each_entry(cur_elem, &fs_info->tree_mod_seq_list, list) {
383097b8a7cSJan Schmidt 		if (cur_elem->seq < min_seq) {
384bd989ba3SJan Schmidt 			if (seq_putting > cur_elem->seq) {
385bd989ba3SJan Schmidt 				/*
386bd989ba3SJan Schmidt 				 * blocker with lower sequence number exists, we
387bd989ba3SJan Schmidt 				 * cannot remove anything from the log
388bd989ba3SJan Schmidt 				 */
389097b8a7cSJan Schmidt 				spin_unlock(&fs_info->tree_mod_seq_lock);
390097b8a7cSJan Schmidt 				return;
391bd989ba3SJan Schmidt 			}
392bd989ba3SJan Schmidt 			min_seq = cur_elem->seq;
393bd989ba3SJan Schmidt 		}
394bd989ba3SJan Schmidt 	}
395097b8a7cSJan Schmidt 	spin_unlock(&fs_info->tree_mod_seq_lock);
396097b8a7cSJan Schmidt 
397097b8a7cSJan Schmidt 	/*
398bd989ba3SJan Schmidt 	 * anything that's lower than the lowest existing (read: blocked)
399bd989ba3SJan Schmidt 	 * sequence number can be removed from the tree.
400bd989ba3SJan Schmidt 	 */
401b1a09f1eSDavid Sterba 	write_lock(&fs_info->tree_mod_log_lock);
402bd989ba3SJan Schmidt 	tm_root = &fs_info->tree_mod_log;
403bd989ba3SJan Schmidt 	for (node = rb_first(tm_root); node; node = next) {
404bd989ba3SJan Schmidt 		next = rb_next(node);
4056b4df8b6SGeliang Tang 		tm = rb_entry(node, struct tree_mod_elem, node);
406097b8a7cSJan Schmidt 		if (tm->seq > min_seq)
407bd989ba3SJan Schmidt 			continue;
408bd989ba3SJan Schmidt 		rb_erase(node, tm_root);
409bd989ba3SJan Schmidt 		kfree(tm);
410bd989ba3SJan Schmidt 	}
411b1a09f1eSDavid Sterba 	write_unlock(&fs_info->tree_mod_log_lock);
412bd989ba3SJan Schmidt }
413bd989ba3SJan Schmidt 
414bd989ba3SJan Schmidt /*
415bd989ba3SJan Schmidt  * key order of the log:
416298cfd36SChandan Rajendra  *       node/leaf start address -> sequence
417bd989ba3SJan Schmidt  *
418298cfd36SChandan Rajendra  * The 'start address' is the logical address of the *new* root node
419298cfd36SChandan Rajendra  * for root replace operations, or the logical address of the affected
420298cfd36SChandan Rajendra  * block for all other operations.
4215de865eeSFilipe David Borba Manana  *
422b1a09f1eSDavid Sterba  * Note: must be called with write lock for fs_info::tree_mod_log_lock.
423bd989ba3SJan Schmidt  */
424bd989ba3SJan Schmidt static noinline int
425bd989ba3SJan Schmidt __tree_mod_log_insert(struct btrfs_fs_info *fs_info, struct tree_mod_elem *tm)
426bd989ba3SJan Schmidt {
427bd989ba3SJan Schmidt 	struct rb_root *tm_root;
428bd989ba3SJan Schmidt 	struct rb_node **new;
429bd989ba3SJan Schmidt 	struct rb_node *parent = NULL;
430bd989ba3SJan Schmidt 	struct tree_mod_elem *cur;
431bd989ba3SJan Schmidt 
432fcebe456SJosef Bacik 	tm->seq = btrfs_inc_tree_mod_seq(fs_info);
433bd989ba3SJan Schmidt 
434bd989ba3SJan Schmidt 	tm_root = &fs_info->tree_mod_log;
435bd989ba3SJan Schmidt 	new = &tm_root->rb_node;
436bd989ba3SJan Schmidt 	while (*new) {
4376b4df8b6SGeliang Tang 		cur = rb_entry(*new, struct tree_mod_elem, node);
438bd989ba3SJan Schmidt 		parent = *new;
439298cfd36SChandan Rajendra 		if (cur->logical < tm->logical)
440bd989ba3SJan Schmidt 			new = &((*new)->rb_left);
441298cfd36SChandan Rajendra 		else if (cur->logical > tm->logical)
442bd989ba3SJan Schmidt 			new = &((*new)->rb_right);
443097b8a7cSJan Schmidt 		else if (cur->seq < tm->seq)
444bd989ba3SJan Schmidt 			new = &((*new)->rb_left);
445097b8a7cSJan Schmidt 		else if (cur->seq > tm->seq)
446bd989ba3SJan Schmidt 			new = &((*new)->rb_right);
4475de865eeSFilipe David Borba Manana 		else
4485de865eeSFilipe David Borba Manana 			return -EEXIST;
449bd989ba3SJan Schmidt 	}
450bd989ba3SJan Schmidt 
451bd989ba3SJan Schmidt 	rb_link_node(&tm->node, parent, new);
452bd989ba3SJan Schmidt 	rb_insert_color(&tm->node, tm_root);
4535de865eeSFilipe David Borba Manana 	return 0;
454bd989ba3SJan Schmidt }
455bd989ba3SJan Schmidt 
456097b8a7cSJan Schmidt /*
457097b8a7cSJan Schmidt  * Determines if logging can be omitted. Returns 1 if it can. Otherwise, it
458097b8a7cSJan Schmidt  * returns zero with the tree_mod_log_lock acquired. The caller must hold
459097b8a7cSJan Schmidt  * this until all tree mod log insertions are recorded in the rb tree and then
460b1a09f1eSDavid Sterba  * write unlock fs_info::tree_mod_log_lock.
461097b8a7cSJan Schmidt  */
462e9b7fd4dSJan Schmidt static inline int tree_mod_dont_log(struct btrfs_fs_info *fs_info,
463e9b7fd4dSJan Schmidt 				    struct extent_buffer *eb) {
464e9b7fd4dSJan Schmidt 	smp_mb();
465e9b7fd4dSJan Schmidt 	if (list_empty(&(fs_info)->tree_mod_seq_list))
466e9b7fd4dSJan Schmidt 		return 1;
467097b8a7cSJan Schmidt 	if (eb && btrfs_header_level(eb) == 0)
468e9b7fd4dSJan Schmidt 		return 1;
4695de865eeSFilipe David Borba Manana 
470b1a09f1eSDavid Sterba 	write_lock(&fs_info->tree_mod_log_lock);
4715de865eeSFilipe David Borba Manana 	if (list_empty(&(fs_info)->tree_mod_seq_list)) {
472b1a09f1eSDavid Sterba 		write_unlock(&fs_info->tree_mod_log_lock);
4735de865eeSFilipe David Borba Manana 		return 1;
4745de865eeSFilipe David Borba Manana 	}
4755de865eeSFilipe David Borba Manana 
476e9b7fd4dSJan Schmidt 	return 0;
477e9b7fd4dSJan Schmidt }
478e9b7fd4dSJan Schmidt 
4795de865eeSFilipe David Borba Manana /* Similar to tree_mod_dont_log, but doesn't acquire any locks. */
4805de865eeSFilipe David Borba Manana static inline int tree_mod_need_log(const struct btrfs_fs_info *fs_info,
4815de865eeSFilipe David Borba Manana 				    struct extent_buffer *eb)
4825de865eeSFilipe David Borba Manana {
4835de865eeSFilipe David Borba Manana 	smp_mb();
4845de865eeSFilipe David Borba Manana 	if (list_empty(&(fs_info)->tree_mod_seq_list))
4855de865eeSFilipe David Borba Manana 		return 0;
4865de865eeSFilipe David Borba Manana 	if (eb && btrfs_header_level(eb) == 0)
4875de865eeSFilipe David Borba Manana 		return 0;
4885de865eeSFilipe David Borba Manana 
4895de865eeSFilipe David Borba Manana 	return 1;
4905de865eeSFilipe David Borba Manana }
4915de865eeSFilipe David Borba Manana 
4925de865eeSFilipe David Borba Manana static struct tree_mod_elem *
4935de865eeSFilipe David Borba Manana alloc_tree_mod_elem(struct extent_buffer *eb, int slot,
494bd989ba3SJan Schmidt 		    enum mod_log_op op, gfp_t flags)
495bd989ba3SJan Schmidt {
496097b8a7cSJan Schmidt 	struct tree_mod_elem *tm;
497bd989ba3SJan Schmidt 
498c8cc6341SJosef Bacik 	tm = kzalloc(sizeof(*tm), flags);
499c8cc6341SJosef Bacik 	if (!tm)
5005de865eeSFilipe David Borba Manana 		return NULL;
501bd989ba3SJan Schmidt 
502298cfd36SChandan Rajendra 	tm->logical = eb->start;
503bd989ba3SJan Schmidt 	if (op != MOD_LOG_KEY_ADD) {
504bd989ba3SJan Schmidt 		btrfs_node_key(eb, &tm->key, slot);
505bd989ba3SJan Schmidt 		tm->blockptr = btrfs_node_blockptr(eb, slot);
506bd989ba3SJan Schmidt 	}
507bd989ba3SJan Schmidt 	tm->op = op;
508bd989ba3SJan Schmidt 	tm->slot = slot;
509bd989ba3SJan Schmidt 	tm->generation = btrfs_node_ptr_generation(eb, slot);
5105de865eeSFilipe David Borba Manana 	RB_CLEAR_NODE(&tm->node);
511bd989ba3SJan Schmidt 
5125de865eeSFilipe David Borba Manana 	return tm;
513097b8a7cSJan Schmidt }
514097b8a7cSJan Schmidt 
515e09c2efeSDavid Sterba static noinline int tree_mod_log_insert_key(struct extent_buffer *eb, int slot,
516097b8a7cSJan Schmidt 		enum mod_log_op op, gfp_t flags)
517097b8a7cSJan Schmidt {
5185de865eeSFilipe David Borba Manana 	struct tree_mod_elem *tm;
5195de865eeSFilipe David Borba Manana 	int ret;
5205de865eeSFilipe David Borba Manana 
521e09c2efeSDavid Sterba 	if (!tree_mod_need_log(eb->fs_info, eb))
522097b8a7cSJan Schmidt 		return 0;
523097b8a7cSJan Schmidt 
5245de865eeSFilipe David Borba Manana 	tm = alloc_tree_mod_elem(eb, slot, op, flags);
5255de865eeSFilipe David Borba Manana 	if (!tm)
5265de865eeSFilipe David Borba Manana 		return -ENOMEM;
5275de865eeSFilipe David Borba Manana 
528e09c2efeSDavid Sterba 	if (tree_mod_dont_log(eb->fs_info, eb)) {
5295de865eeSFilipe David Borba Manana 		kfree(tm);
5305de865eeSFilipe David Borba Manana 		return 0;
5315de865eeSFilipe David Borba Manana 	}
5325de865eeSFilipe David Borba Manana 
533e09c2efeSDavid Sterba 	ret = __tree_mod_log_insert(eb->fs_info, tm);
534b1a09f1eSDavid Sterba 	write_unlock(&eb->fs_info->tree_mod_log_lock);
5355de865eeSFilipe David Borba Manana 	if (ret)
5365de865eeSFilipe David Borba Manana 		kfree(tm);
5375de865eeSFilipe David Borba Manana 
5385de865eeSFilipe David Borba Manana 	return ret;
539097b8a7cSJan Schmidt }
540097b8a7cSJan Schmidt 
5416074d45fSDavid Sterba static noinline int tree_mod_log_insert_move(struct extent_buffer *eb,
5426074d45fSDavid Sterba 		int dst_slot, int src_slot, int nr_items)
543bd989ba3SJan Schmidt {
5445de865eeSFilipe David Borba Manana 	struct tree_mod_elem *tm = NULL;
5455de865eeSFilipe David Borba Manana 	struct tree_mod_elem **tm_list = NULL;
5465de865eeSFilipe David Borba Manana 	int ret = 0;
547bd989ba3SJan Schmidt 	int i;
5485de865eeSFilipe David Borba Manana 	int locked = 0;
549bd989ba3SJan Schmidt 
5506074d45fSDavid Sterba 	if (!tree_mod_need_log(eb->fs_info, eb))
551f395694cSJan Schmidt 		return 0;
552bd989ba3SJan Schmidt 
553176ef8f5SDavid Sterba 	tm_list = kcalloc(nr_items, sizeof(struct tree_mod_elem *), GFP_NOFS);
5545de865eeSFilipe David Borba Manana 	if (!tm_list)
5555de865eeSFilipe David Borba Manana 		return -ENOMEM;
556bd989ba3SJan Schmidt 
557176ef8f5SDavid Sterba 	tm = kzalloc(sizeof(*tm), GFP_NOFS);
5585de865eeSFilipe David Borba Manana 	if (!tm) {
5595de865eeSFilipe David Borba Manana 		ret = -ENOMEM;
5605de865eeSFilipe David Borba Manana 		goto free_tms;
5615de865eeSFilipe David Borba Manana 	}
562f395694cSJan Schmidt 
563298cfd36SChandan Rajendra 	tm->logical = eb->start;
564bd989ba3SJan Schmidt 	tm->slot = src_slot;
565bd989ba3SJan Schmidt 	tm->move.dst_slot = dst_slot;
566bd989ba3SJan Schmidt 	tm->move.nr_items = nr_items;
567bd989ba3SJan Schmidt 	tm->op = MOD_LOG_MOVE_KEYS;
568bd989ba3SJan Schmidt 
5695de865eeSFilipe David Borba Manana 	for (i = 0; i + dst_slot < src_slot && i < nr_items; i++) {
5705de865eeSFilipe David Borba Manana 		tm_list[i] = alloc_tree_mod_elem(eb, i + dst_slot,
571176ef8f5SDavid Sterba 		    MOD_LOG_KEY_REMOVE_WHILE_MOVING, GFP_NOFS);
5725de865eeSFilipe David Borba Manana 		if (!tm_list[i]) {
5735de865eeSFilipe David Borba Manana 			ret = -ENOMEM;
5745de865eeSFilipe David Borba Manana 			goto free_tms;
5755de865eeSFilipe David Borba Manana 		}
576bd989ba3SJan Schmidt 	}
577bd989ba3SJan Schmidt 
5786074d45fSDavid Sterba 	if (tree_mod_dont_log(eb->fs_info, eb))
5795de865eeSFilipe David Borba Manana 		goto free_tms;
5805de865eeSFilipe David Borba Manana 	locked = 1;
5815de865eeSFilipe David Borba Manana 
5825de865eeSFilipe David Borba Manana 	/*
5835de865eeSFilipe David Borba Manana 	 * When we override something during the move, we log these removals.
5845de865eeSFilipe David Borba Manana 	 * This can only happen when we move towards the beginning of the
5855de865eeSFilipe David Borba Manana 	 * buffer, i.e. dst_slot < src_slot.
5865de865eeSFilipe David Borba Manana 	 */
5875de865eeSFilipe David Borba Manana 	for (i = 0; i + dst_slot < src_slot && i < nr_items; i++) {
5886074d45fSDavid Sterba 		ret = __tree_mod_log_insert(eb->fs_info, tm_list[i]);
5895de865eeSFilipe David Borba Manana 		if (ret)
5905de865eeSFilipe David Borba Manana 			goto free_tms;
5915de865eeSFilipe David Borba Manana 	}
5925de865eeSFilipe David Borba Manana 
5936074d45fSDavid Sterba 	ret = __tree_mod_log_insert(eb->fs_info, tm);
5945de865eeSFilipe David Borba Manana 	if (ret)
5955de865eeSFilipe David Borba Manana 		goto free_tms;
596b1a09f1eSDavid Sterba 	write_unlock(&eb->fs_info->tree_mod_log_lock);
5975de865eeSFilipe David Borba Manana 	kfree(tm_list);
5985de865eeSFilipe David Borba Manana 
5995de865eeSFilipe David Borba Manana 	return 0;
6005de865eeSFilipe David Borba Manana free_tms:
6015de865eeSFilipe David Borba Manana 	for (i = 0; i < nr_items; i++) {
6025de865eeSFilipe David Borba Manana 		if (tm_list[i] && !RB_EMPTY_NODE(&tm_list[i]->node))
6036074d45fSDavid Sterba 			rb_erase(&tm_list[i]->node, &eb->fs_info->tree_mod_log);
6045de865eeSFilipe David Borba Manana 		kfree(tm_list[i]);
6055de865eeSFilipe David Borba Manana 	}
6065de865eeSFilipe David Borba Manana 	if (locked)
607b1a09f1eSDavid Sterba 		write_unlock(&eb->fs_info->tree_mod_log_lock);
6085de865eeSFilipe David Borba Manana 	kfree(tm_list);
6095de865eeSFilipe David Borba Manana 	kfree(tm);
6105de865eeSFilipe David Borba Manana 
6115de865eeSFilipe David Borba Manana 	return ret;
6125de865eeSFilipe David Borba Manana }
6135de865eeSFilipe David Borba Manana 
6145de865eeSFilipe David Borba Manana static inline int
6155de865eeSFilipe David Borba Manana __tree_mod_log_free_eb(struct btrfs_fs_info *fs_info,
6165de865eeSFilipe David Borba Manana 		       struct tree_mod_elem **tm_list,
6175de865eeSFilipe David Borba Manana 		       int nritems)
618097b8a7cSJan Schmidt {
6195de865eeSFilipe David Borba Manana 	int i, j;
620097b8a7cSJan Schmidt 	int ret;
621097b8a7cSJan Schmidt 
622097b8a7cSJan Schmidt 	for (i = nritems - 1; i >= 0; i--) {
6235de865eeSFilipe David Borba Manana 		ret = __tree_mod_log_insert(fs_info, tm_list[i]);
6245de865eeSFilipe David Borba Manana 		if (ret) {
6255de865eeSFilipe David Borba Manana 			for (j = nritems - 1; j > i; j--)
6265de865eeSFilipe David Borba Manana 				rb_erase(&tm_list[j]->node,
6275de865eeSFilipe David Borba Manana 					 &fs_info->tree_mod_log);
6285de865eeSFilipe David Borba Manana 			return ret;
629097b8a7cSJan Schmidt 		}
630097b8a7cSJan Schmidt 	}
631097b8a7cSJan Schmidt 
6325de865eeSFilipe David Borba Manana 	return 0;
6335de865eeSFilipe David Borba Manana }
6345de865eeSFilipe David Borba Manana 
63595b757c1SDavid Sterba static noinline int tree_mod_log_insert_root(struct extent_buffer *old_root,
63695b757c1SDavid Sterba 			 struct extent_buffer *new_root, int log_removal)
637bd989ba3SJan Schmidt {
63895b757c1SDavid Sterba 	struct btrfs_fs_info *fs_info = old_root->fs_info;
6395de865eeSFilipe David Borba Manana 	struct tree_mod_elem *tm = NULL;
6405de865eeSFilipe David Borba Manana 	struct tree_mod_elem **tm_list = NULL;
6415de865eeSFilipe David Borba Manana 	int nritems = 0;
6425de865eeSFilipe David Borba Manana 	int ret = 0;
6435de865eeSFilipe David Borba Manana 	int i;
644bd989ba3SJan Schmidt 
6455de865eeSFilipe David Borba Manana 	if (!tree_mod_need_log(fs_info, NULL))
646097b8a7cSJan Schmidt 		return 0;
647097b8a7cSJan Schmidt 
6485de865eeSFilipe David Borba Manana 	if (log_removal && btrfs_header_level(old_root) > 0) {
6495de865eeSFilipe David Borba Manana 		nritems = btrfs_header_nritems(old_root);
65031e818feSDavid Sterba 		tm_list = kcalloc(nritems, sizeof(struct tree_mod_elem *),
651bcc8e07fSDavid Sterba 				  GFP_NOFS);
6525de865eeSFilipe David Borba Manana 		if (!tm_list) {
6535de865eeSFilipe David Borba Manana 			ret = -ENOMEM;
6545de865eeSFilipe David Borba Manana 			goto free_tms;
6555de865eeSFilipe David Borba Manana 		}
6565de865eeSFilipe David Borba Manana 		for (i = 0; i < nritems; i++) {
6575de865eeSFilipe David Borba Manana 			tm_list[i] = alloc_tree_mod_elem(old_root, i,
658bcc8e07fSDavid Sterba 			    MOD_LOG_KEY_REMOVE_WHILE_FREEING, GFP_NOFS);
6595de865eeSFilipe David Borba Manana 			if (!tm_list[i]) {
6605de865eeSFilipe David Borba Manana 				ret = -ENOMEM;
6615de865eeSFilipe David Borba Manana 				goto free_tms;
6625de865eeSFilipe David Borba Manana 			}
6635de865eeSFilipe David Borba Manana 		}
6645de865eeSFilipe David Borba Manana 	}
665d9abbf1cSJan Schmidt 
666bcc8e07fSDavid Sterba 	tm = kzalloc(sizeof(*tm), GFP_NOFS);
6675de865eeSFilipe David Borba Manana 	if (!tm) {
6685de865eeSFilipe David Borba Manana 		ret = -ENOMEM;
6695de865eeSFilipe David Borba Manana 		goto free_tms;
6705de865eeSFilipe David Borba Manana 	}
671bd989ba3SJan Schmidt 
672298cfd36SChandan Rajendra 	tm->logical = new_root->start;
673bd989ba3SJan Schmidt 	tm->old_root.logical = old_root->start;
674bd989ba3SJan Schmidt 	tm->old_root.level = btrfs_header_level(old_root);
675bd989ba3SJan Schmidt 	tm->generation = btrfs_header_generation(old_root);
676bd989ba3SJan Schmidt 	tm->op = MOD_LOG_ROOT_REPLACE;
677bd989ba3SJan Schmidt 
6785de865eeSFilipe David Borba Manana 	if (tree_mod_dont_log(fs_info, NULL))
6795de865eeSFilipe David Borba Manana 		goto free_tms;
6805de865eeSFilipe David Borba Manana 
6815de865eeSFilipe David Borba Manana 	if (tm_list)
6825de865eeSFilipe David Borba Manana 		ret = __tree_mod_log_free_eb(fs_info, tm_list, nritems);
6835de865eeSFilipe David Borba Manana 	if (!ret)
6845de865eeSFilipe David Borba Manana 		ret = __tree_mod_log_insert(fs_info, tm);
6855de865eeSFilipe David Borba Manana 
686b1a09f1eSDavid Sterba 	write_unlock(&fs_info->tree_mod_log_lock);
6875de865eeSFilipe David Borba Manana 	if (ret)
6885de865eeSFilipe David Borba Manana 		goto free_tms;
6895de865eeSFilipe David Borba Manana 	kfree(tm_list);
6905de865eeSFilipe David Borba Manana 
6915de865eeSFilipe David Borba Manana 	return ret;
6925de865eeSFilipe David Borba Manana 
6935de865eeSFilipe David Borba Manana free_tms:
6945de865eeSFilipe David Borba Manana 	if (tm_list) {
6955de865eeSFilipe David Borba Manana 		for (i = 0; i < nritems; i++)
6965de865eeSFilipe David Borba Manana 			kfree(tm_list[i]);
6975de865eeSFilipe David Borba Manana 		kfree(tm_list);
6985de865eeSFilipe David Borba Manana 	}
6995de865eeSFilipe David Borba Manana 	kfree(tm);
7005de865eeSFilipe David Borba Manana 
7015de865eeSFilipe David Borba Manana 	return ret;
702bd989ba3SJan Schmidt }
703bd989ba3SJan Schmidt 
704bd989ba3SJan Schmidt static struct tree_mod_elem *
705bd989ba3SJan Schmidt __tree_mod_log_search(struct btrfs_fs_info *fs_info, u64 start, u64 min_seq,
706bd989ba3SJan Schmidt 		      int smallest)
707bd989ba3SJan Schmidt {
708bd989ba3SJan Schmidt 	struct rb_root *tm_root;
709bd989ba3SJan Schmidt 	struct rb_node *node;
710bd989ba3SJan Schmidt 	struct tree_mod_elem *cur = NULL;
711bd989ba3SJan Schmidt 	struct tree_mod_elem *found = NULL;
712bd989ba3SJan Schmidt 
713b1a09f1eSDavid Sterba 	read_lock(&fs_info->tree_mod_log_lock);
714bd989ba3SJan Schmidt 	tm_root = &fs_info->tree_mod_log;
715bd989ba3SJan Schmidt 	node = tm_root->rb_node;
716bd989ba3SJan Schmidt 	while (node) {
7176b4df8b6SGeliang Tang 		cur = rb_entry(node, struct tree_mod_elem, node);
718298cfd36SChandan Rajendra 		if (cur->logical < start) {
719bd989ba3SJan Schmidt 			node = node->rb_left;
720298cfd36SChandan Rajendra 		} else if (cur->logical > start) {
721bd989ba3SJan Schmidt 			node = node->rb_right;
722097b8a7cSJan Schmidt 		} else if (cur->seq < min_seq) {
723bd989ba3SJan Schmidt 			node = node->rb_left;
724bd989ba3SJan Schmidt 		} else if (!smallest) {
725bd989ba3SJan Schmidt 			/* we want the node with the highest seq */
726bd989ba3SJan Schmidt 			if (found)
727097b8a7cSJan Schmidt 				BUG_ON(found->seq > cur->seq);
728bd989ba3SJan Schmidt 			found = cur;
729bd989ba3SJan Schmidt 			node = node->rb_left;
730097b8a7cSJan Schmidt 		} else if (cur->seq > min_seq) {
731bd989ba3SJan Schmidt 			/* we want the node with the smallest seq */
732bd989ba3SJan Schmidt 			if (found)
733097b8a7cSJan Schmidt 				BUG_ON(found->seq < cur->seq);
734bd989ba3SJan Schmidt 			found = cur;
735bd989ba3SJan Schmidt 			node = node->rb_right;
736bd989ba3SJan Schmidt 		} else {
737bd989ba3SJan Schmidt 			found = cur;
738bd989ba3SJan Schmidt 			break;
739bd989ba3SJan Schmidt 		}
740bd989ba3SJan Schmidt 	}
741b1a09f1eSDavid Sterba 	read_unlock(&fs_info->tree_mod_log_lock);
742bd989ba3SJan Schmidt 
743bd989ba3SJan Schmidt 	return found;
744bd989ba3SJan Schmidt }
745bd989ba3SJan Schmidt 
746bd989ba3SJan Schmidt /*
747bd989ba3SJan Schmidt  * this returns the element from the log with the smallest time sequence
748bd989ba3SJan Schmidt  * value that's in the log (the oldest log item). any element with a time
749bd989ba3SJan Schmidt  * sequence lower than min_seq will be ignored.
750bd989ba3SJan Schmidt  */
751bd989ba3SJan Schmidt static struct tree_mod_elem *
752bd989ba3SJan Schmidt tree_mod_log_search_oldest(struct btrfs_fs_info *fs_info, u64 start,
753bd989ba3SJan Schmidt 			   u64 min_seq)
754bd989ba3SJan Schmidt {
755bd989ba3SJan Schmidt 	return __tree_mod_log_search(fs_info, start, min_seq, 1);
756bd989ba3SJan Schmidt }
757bd989ba3SJan Schmidt 
758bd989ba3SJan Schmidt /*
759bd989ba3SJan Schmidt  * this returns the element from the log with the largest time sequence
760bd989ba3SJan Schmidt  * value that's in the log (the most recent log item). any element with
761bd989ba3SJan Schmidt  * a time sequence lower than min_seq will be ignored.
762bd989ba3SJan Schmidt  */
763bd989ba3SJan Schmidt static struct tree_mod_elem *
764bd989ba3SJan Schmidt tree_mod_log_search(struct btrfs_fs_info *fs_info, u64 start, u64 min_seq)
765bd989ba3SJan Schmidt {
766bd989ba3SJan Schmidt 	return __tree_mod_log_search(fs_info, start, min_seq, 0);
767bd989ba3SJan Schmidt }
768bd989ba3SJan Schmidt 
7695de865eeSFilipe David Borba Manana static noinline int
770bd989ba3SJan Schmidt tree_mod_log_eb_copy(struct btrfs_fs_info *fs_info, struct extent_buffer *dst,
771bd989ba3SJan Schmidt 		     struct extent_buffer *src, unsigned long dst_offset,
77290f8d62eSJan Schmidt 		     unsigned long src_offset, int nr_items)
773bd989ba3SJan Schmidt {
7745de865eeSFilipe David Borba Manana 	int ret = 0;
7755de865eeSFilipe David Borba Manana 	struct tree_mod_elem **tm_list = NULL;
7765de865eeSFilipe David Borba Manana 	struct tree_mod_elem **tm_list_add, **tm_list_rem;
777bd989ba3SJan Schmidt 	int i;
7785de865eeSFilipe David Borba Manana 	int locked = 0;
779bd989ba3SJan Schmidt 
7805de865eeSFilipe David Borba Manana 	if (!tree_mod_need_log(fs_info, NULL))
7815de865eeSFilipe David Borba Manana 		return 0;
782bd989ba3SJan Schmidt 
783c8cc6341SJosef Bacik 	if (btrfs_header_level(dst) == 0 && btrfs_header_level(src) == 0)
7845de865eeSFilipe David Borba Manana 		return 0;
7855de865eeSFilipe David Borba Manana 
78631e818feSDavid Sterba 	tm_list = kcalloc(nr_items * 2, sizeof(struct tree_mod_elem *),
7875de865eeSFilipe David Borba Manana 			  GFP_NOFS);
7885de865eeSFilipe David Borba Manana 	if (!tm_list)
7895de865eeSFilipe David Borba Manana 		return -ENOMEM;
7905de865eeSFilipe David Borba Manana 
7915de865eeSFilipe David Borba Manana 	tm_list_add = tm_list;
7925de865eeSFilipe David Borba Manana 	tm_list_rem = tm_list + nr_items;
7935de865eeSFilipe David Borba Manana 	for (i = 0; i < nr_items; i++) {
7945de865eeSFilipe David Borba Manana 		tm_list_rem[i] = alloc_tree_mod_elem(src, i + src_offset,
7955de865eeSFilipe David Borba Manana 		    MOD_LOG_KEY_REMOVE, GFP_NOFS);
7965de865eeSFilipe David Borba Manana 		if (!tm_list_rem[i]) {
7975de865eeSFilipe David Borba Manana 			ret = -ENOMEM;
7985de865eeSFilipe David Borba Manana 			goto free_tms;
7995de865eeSFilipe David Borba Manana 		}
8005de865eeSFilipe David Borba Manana 
8015de865eeSFilipe David Borba Manana 		tm_list_add[i] = alloc_tree_mod_elem(dst, i + dst_offset,
8025de865eeSFilipe David Borba Manana 		    MOD_LOG_KEY_ADD, GFP_NOFS);
8035de865eeSFilipe David Borba Manana 		if (!tm_list_add[i]) {
8045de865eeSFilipe David Borba Manana 			ret = -ENOMEM;
8055de865eeSFilipe David Borba Manana 			goto free_tms;
8065de865eeSFilipe David Borba Manana 		}
8075de865eeSFilipe David Borba Manana 	}
8085de865eeSFilipe David Borba Manana 
8095de865eeSFilipe David Borba Manana 	if (tree_mod_dont_log(fs_info, NULL))
8105de865eeSFilipe David Borba Manana 		goto free_tms;
8115de865eeSFilipe David Borba Manana 	locked = 1;
812bd989ba3SJan Schmidt 
813bd989ba3SJan Schmidt 	for (i = 0; i < nr_items; i++) {
8145de865eeSFilipe David Borba Manana 		ret = __tree_mod_log_insert(fs_info, tm_list_rem[i]);
8155de865eeSFilipe David Borba Manana 		if (ret)
8165de865eeSFilipe David Borba Manana 			goto free_tms;
8175de865eeSFilipe David Borba Manana 		ret = __tree_mod_log_insert(fs_info, tm_list_add[i]);
8185de865eeSFilipe David Borba Manana 		if (ret)
8195de865eeSFilipe David Borba Manana 			goto free_tms;
820bd989ba3SJan Schmidt 	}
8215de865eeSFilipe David Borba Manana 
822b1a09f1eSDavid Sterba 	write_unlock(&fs_info->tree_mod_log_lock);
8235de865eeSFilipe David Borba Manana 	kfree(tm_list);
8245de865eeSFilipe David Borba Manana 
8255de865eeSFilipe David Borba Manana 	return 0;
8265de865eeSFilipe David Borba Manana 
8275de865eeSFilipe David Borba Manana free_tms:
8285de865eeSFilipe David Borba Manana 	for (i = 0; i < nr_items * 2; i++) {
8295de865eeSFilipe David Borba Manana 		if (tm_list[i] && !RB_EMPTY_NODE(&tm_list[i]->node))
8305de865eeSFilipe David Borba Manana 			rb_erase(&tm_list[i]->node, &fs_info->tree_mod_log);
8315de865eeSFilipe David Borba Manana 		kfree(tm_list[i]);
8325de865eeSFilipe David Borba Manana 	}
8335de865eeSFilipe David Borba Manana 	if (locked)
834b1a09f1eSDavid Sterba 		write_unlock(&fs_info->tree_mod_log_lock);
8355de865eeSFilipe David Borba Manana 	kfree(tm_list);
8365de865eeSFilipe David Borba Manana 
8375de865eeSFilipe David Borba Manana 	return ret;
838bd989ba3SJan Schmidt }
839bd989ba3SJan Schmidt 
840db7279a2SDavid Sterba static noinline int tree_mod_log_free_eb(struct extent_buffer *eb)
841bd989ba3SJan Schmidt {
8425de865eeSFilipe David Borba Manana 	struct tree_mod_elem **tm_list = NULL;
8435de865eeSFilipe David Borba Manana 	int nritems = 0;
8445de865eeSFilipe David Borba Manana 	int i;
8455de865eeSFilipe David Borba Manana 	int ret = 0;
8465de865eeSFilipe David Borba Manana 
8475de865eeSFilipe David Borba Manana 	if (btrfs_header_level(eb) == 0)
8485de865eeSFilipe David Borba Manana 		return 0;
8495de865eeSFilipe David Borba Manana 
850db7279a2SDavid Sterba 	if (!tree_mod_need_log(eb->fs_info, NULL))
8515de865eeSFilipe David Borba Manana 		return 0;
8525de865eeSFilipe David Borba Manana 
8535de865eeSFilipe David Borba Manana 	nritems = btrfs_header_nritems(eb);
85431e818feSDavid Sterba 	tm_list = kcalloc(nritems, sizeof(struct tree_mod_elem *), GFP_NOFS);
8555de865eeSFilipe David Borba Manana 	if (!tm_list)
8565de865eeSFilipe David Borba Manana 		return -ENOMEM;
8575de865eeSFilipe David Borba Manana 
8585de865eeSFilipe David Borba Manana 	for (i = 0; i < nritems; i++) {
8595de865eeSFilipe David Borba Manana 		tm_list[i] = alloc_tree_mod_elem(eb, i,
8605de865eeSFilipe David Borba Manana 		    MOD_LOG_KEY_REMOVE_WHILE_FREEING, GFP_NOFS);
8615de865eeSFilipe David Borba Manana 		if (!tm_list[i]) {
8625de865eeSFilipe David Borba Manana 			ret = -ENOMEM;
8635de865eeSFilipe David Borba Manana 			goto free_tms;
8645de865eeSFilipe David Borba Manana 		}
8655de865eeSFilipe David Borba Manana 	}
8665de865eeSFilipe David Borba Manana 
867db7279a2SDavid Sterba 	if (tree_mod_dont_log(eb->fs_info, eb))
8685de865eeSFilipe David Borba Manana 		goto free_tms;
8695de865eeSFilipe David Borba Manana 
870db7279a2SDavid Sterba 	ret = __tree_mod_log_free_eb(eb->fs_info, tm_list, nritems);
871b1a09f1eSDavid Sterba 	write_unlock(&eb->fs_info->tree_mod_log_lock);
8725de865eeSFilipe David Borba Manana 	if (ret)
8735de865eeSFilipe David Borba Manana 		goto free_tms;
8745de865eeSFilipe David Borba Manana 	kfree(tm_list);
8755de865eeSFilipe David Borba Manana 
8765de865eeSFilipe David Borba Manana 	return 0;
8775de865eeSFilipe David Borba Manana 
8785de865eeSFilipe David Borba Manana free_tms:
8795de865eeSFilipe David Borba Manana 	for (i = 0; i < nritems; i++)
8805de865eeSFilipe David Borba Manana 		kfree(tm_list[i]);
8815de865eeSFilipe David Borba Manana 	kfree(tm_list);
8825de865eeSFilipe David Borba Manana 
8835de865eeSFilipe David Borba Manana 	return ret;
884bd989ba3SJan Schmidt }
885bd989ba3SJan Schmidt 
886d352ac68SChris Mason /*
8875d4f98a2SYan Zheng  * check if the tree block can be shared by multiple trees
8885d4f98a2SYan Zheng  */
8895d4f98a2SYan Zheng int btrfs_block_can_be_shared(struct btrfs_root *root,
8905d4f98a2SYan Zheng 			      struct extent_buffer *buf)
8915d4f98a2SYan Zheng {
8925d4f98a2SYan Zheng 	/*
89301327610SNicholas D Steeves 	 * Tree blocks not in reference counted trees and tree roots
8945d4f98a2SYan Zheng 	 * are never shared. If a block was allocated after the last
8955d4f98a2SYan Zheng 	 * snapshot and the block was not allocated by tree relocation,
8965d4f98a2SYan Zheng 	 * we know the block is not shared.
8975d4f98a2SYan Zheng 	 */
89827cdeb70SMiao Xie 	if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
8995d4f98a2SYan Zheng 	    buf != root->node && buf != root->commit_root &&
9005d4f98a2SYan Zheng 	    (btrfs_header_generation(buf) <=
9015d4f98a2SYan Zheng 	     btrfs_root_last_snapshot(&root->root_item) ||
9025d4f98a2SYan Zheng 	     btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)))
9035d4f98a2SYan Zheng 		return 1;
9045d4f98a2SYan Zheng #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
90527cdeb70SMiao Xie 	if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
9065d4f98a2SYan Zheng 	    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
9075d4f98a2SYan Zheng 		return 1;
9085d4f98a2SYan Zheng #endif
9095d4f98a2SYan Zheng 	return 0;
9105d4f98a2SYan Zheng }
9115d4f98a2SYan Zheng 
9125d4f98a2SYan Zheng static noinline int update_ref_for_cow(struct btrfs_trans_handle *trans,
9135d4f98a2SYan Zheng 				       struct btrfs_root *root,
9145d4f98a2SYan Zheng 				       struct extent_buffer *buf,
915f0486c68SYan, Zheng 				       struct extent_buffer *cow,
916f0486c68SYan, Zheng 				       int *last_ref)
9175d4f98a2SYan Zheng {
9180b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
9195d4f98a2SYan Zheng 	u64 refs;
9205d4f98a2SYan Zheng 	u64 owner;
9215d4f98a2SYan Zheng 	u64 flags;
9225d4f98a2SYan Zheng 	u64 new_flags = 0;
9235d4f98a2SYan Zheng 	int ret;
9245d4f98a2SYan Zheng 
9255d4f98a2SYan Zheng 	/*
9265d4f98a2SYan Zheng 	 * Backrefs update rules:
9275d4f98a2SYan Zheng 	 *
9285d4f98a2SYan Zheng 	 * Always use full backrefs for extent pointers in tree block
9295d4f98a2SYan Zheng 	 * allocated by tree relocation.
9305d4f98a2SYan Zheng 	 *
9315d4f98a2SYan Zheng 	 * If a shared tree block is no longer referenced by its owner
9325d4f98a2SYan Zheng 	 * tree (btrfs_header_owner(buf) == root->root_key.objectid),
9335d4f98a2SYan Zheng 	 * use full backrefs for extent pointers in tree block.
9345d4f98a2SYan Zheng 	 *
9355d4f98a2SYan Zheng 	 * If a tree block is been relocating
9365d4f98a2SYan Zheng 	 * (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID),
9375d4f98a2SYan Zheng 	 * use full backrefs for extent pointers in tree block.
9385d4f98a2SYan Zheng 	 * The reason for this is some operations (such as drop tree)
9395d4f98a2SYan Zheng 	 * are only allowed for blocks use full backrefs.
9405d4f98a2SYan Zheng 	 */
9415d4f98a2SYan Zheng 
9425d4f98a2SYan Zheng 	if (btrfs_block_can_be_shared(root, buf)) {
9432ff7e61eSJeff Mahoney 		ret = btrfs_lookup_extent_info(trans, fs_info, buf->start,
9443173a18fSJosef Bacik 					       btrfs_header_level(buf), 1,
9453173a18fSJosef Bacik 					       &refs, &flags);
946be1a5564SMark Fasheh 		if (ret)
947be1a5564SMark Fasheh 			return ret;
948e5df9573SMark Fasheh 		if (refs == 0) {
949e5df9573SMark Fasheh 			ret = -EROFS;
9500b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
951e5df9573SMark Fasheh 			return ret;
952e5df9573SMark Fasheh 		}
9535d4f98a2SYan Zheng 	} else {
9545d4f98a2SYan Zheng 		refs = 1;
9555d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
9565d4f98a2SYan Zheng 		    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
9575d4f98a2SYan Zheng 			flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
9585d4f98a2SYan Zheng 		else
9595d4f98a2SYan Zheng 			flags = 0;
9605d4f98a2SYan Zheng 	}
9615d4f98a2SYan Zheng 
9625d4f98a2SYan Zheng 	owner = btrfs_header_owner(buf);
9635d4f98a2SYan Zheng 	BUG_ON(owner == BTRFS_TREE_RELOC_OBJECTID &&
9645d4f98a2SYan Zheng 	       !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
9655d4f98a2SYan Zheng 
9665d4f98a2SYan Zheng 	if (refs > 1) {
9675d4f98a2SYan Zheng 		if ((owner == root->root_key.objectid ||
9685d4f98a2SYan Zheng 		     root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) &&
9695d4f98a2SYan Zheng 		    !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)) {
970e339a6b0SJosef Bacik 			ret = btrfs_inc_ref(trans, root, buf, 1);
971692826b2SJeff Mahoney 			if (ret)
972692826b2SJeff Mahoney 				return ret;
9735d4f98a2SYan Zheng 
9745d4f98a2SYan Zheng 			if (root->root_key.objectid ==
9755d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID) {
976e339a6b0SJosef Bacik 				ret = btrfs_dec_ref(trans, root, buf, 0);
977692826b2SJeff Mahoney 				if (ret)
978692826b2SJeff Mahoney 					return ret;
979e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
980692826b2SJeff Mahoney 				if (ret)
981692826b2SJeff Mahoney 					return ret;
9825d4f98a2SYan Zheng 			}
9835d4f98a2SYan Zheng 			new_flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
9845d4f98a2SYan Zheng 		} else {
9855d4f98a2SYan Zheng 
9865d4f98a2SYan Zheng 			if (root->root_key.objectid ==
9875d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID)
988e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
9895d4f98a2SYan Zheng 			else
990e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 0);
991692826b2SJeff Mahoney 			if (ret)
992692826b2SJeff Mahoney 				return ret;
9935d4f98a2SYan Zheng 		}
9945d4f98a2SYan Zheng 		if (new_flags != 0) {
995b1c79e09SJosef Bacik 			int level = btrfs_header_level(buf);
996b1c79e09SJosef Bacik 
9972ff7e61eSJeff Mahoney 			ret = btrfs_set_disk_extent_flags(trans, fs_info,
9985d4f98a2SYan Zheng 							  buf->start,
9995d4f98a2SYan Zheng 							  buf->len,
1000b1c79e09SJosef Bacik 							  new_flags, level, 0);
1001be1a5564SMark Fasheh 			if (ret)
1002be1a5564SMark Fasheh 				return ret;
10035d4f98a2SYan Zheng 		}
10045d4f98a2SYan Zheng 	} else {
10055d4f98a2SYan Zheng 		if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
10065d4f98a2SYan Zheng 			if (root->root_key.objectid ==
10075d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID)
1008e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
10095d4f98a2SYan Zheng 			else
1010e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 0);
1011692826b2SJeff Mahoney 			if (ret)
1012692826b2SJeff Mahoney 				return ret;
1013e339a6b0SJosef Bacik 			ret = btrfs_dec_ref(trans, root, buf, 1);
1014692826b2SJeff Mahoney 			if (ret)
1015692826b2SJeff Mahoney 				return ret;
10165d4f98a2SYan Zheng 		}
10177c302b49SDavid Sterba 		clean_tree_block(fs_info, buf);
1018f0486c68SYan, Zheng 		*last_ref = 1;
10195d4f98a2SYan Zheng 	}
10205d4f98a2SYan Zheng 	return 0;
10215d4f98a2SYan Zheng }
10225d4f98a2SYan Zheng 
10235d4f98a2SYan Zheng /*
1024d397712bSChris Mason  * does the dirty work in cow of a single block.  The parent block (if
1025d397712bSChris Mason  * supplied) is updated to point to the new cow copy.  The new buffer is marked
1026d397712bSChris Mason  * dirty and returned locked.  If you modify the block it needs to be marked
1027d397712bSChris Mason  * dirty again.
1028d352ac68SChris Mason  *
1029d352ac68SChris Mason  * search_start -- an allocation hint for the new block
1030d352ac68SChris Mason  *
1031d397712bSChris Mason  * empty_size -- a hint that you plan on doing more cow.  This is the size in
1032d397712bSChris Mason  * bytes the allocator should try to find free next to the block it returns.
1033d397712bSChris Mason  * This is just a hint and may be ignored by the allocator.
1034d352ac68SChris Mason  */
1035d397712bSChris Mason static noinline int __btrfs_cow_block(struct btrfs_trans_handle *trans,
10365f39d397SChris Mason 			     struct btrfs_root *root,
10375f39d397SChris Mason 			     struct extent_buffer *buf,
10385f39d397SChris Mason 			     struct extent_buffer *parent, int parent_slot,
10395f39d397SChris Mason 			     struct extent_buffer **cow_ret,
10409fa8cfe7SChris Mason 			     u64 search_start, u64 empty_size)
10416702ed49SChris Mason {
10420b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
10435d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
10445f39d397SChris Mason 	struct extent_buffer *cow;
1045be1a5564SMark Fasheh 	int level, ret;
1046f0486c68SYan, Zheng 	int last_ref = 0;
1047925baeddSChris Mason 	int unlock_orig = 0;
10480f5053ebSGoldwyn Rodrigues 	u64 parent_start = 0;
10496702ed49SChris Mason 
1050925baeddSChris Mason 	if (*cow_ret == buf)
1051925baeddSChris Mason 		unlock_orig = 1;
1052925baeddSChris Mason 
1053b9447ef8SChris Mason 	btrfs_assert_tree_locked(buf);
1054925baeddSChris Mason 
105527cdeb70SMiao Xie 	WARN_ON(test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
10560b246afaSJeff Mahoney 		trans->transid != fs_info->running_transaction->transid);
105727cdeb70SMiao Xie 	WARN_ON(test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
105827cdeb70SMiao Xie 		trans->transid != root->last_trans);
10595f39d397SChris Mason 
10607bb86316SChris Mason 	level = btrfs_header_level(buf);
106131840ae1SZheng Yan 
10625d4f98a2SYan Zheng 	if (level == 0)
10635d4f98a2SYan Zheng 		btrfs_item_key(buf, &disk_key, 0);
10645d4f98a2SYan Zheng 	else
10655d4f98a2SYan Zheng 		btrfs_node_key(buf, &disk_key, 0);
10665d4f98a2SYan Zheng 
10670f5053ebSGoldwyn Rodrigues 	if ((root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) && parent)
10685d4f98a2SYan Zheng 		parent_start = parent->start;
10695d4f98a2SYan Zheng 
10704d75f8a9SDavid Sterba 	cow = btrfs_alloc_tree_block(trans, root, parent_start,
10714d75f8a9SDavid Sterba 			root->root_key.objectid, &disk_key, level,
10724d75f8a9SDavid Sterba 			search_start, empty_size);
10736702ed49SChris Mason 	if (IS_ERR(cow))
10746702ed49SChris Mason 		return PTR_ERR(cow);
10756702ed49SChris Mason 
1076b4ce94deSChris Mason 	/* cow is set to blocking by btrfs_init_new_buffer */
1077b4ce94deSChris Mason 
107858e8012cSDavid Sterba 	copy_extent_buffer_full(cow, buf);
1079db94535dSChris Mason 	btrfs_set_header_bytenr(cow, cow->start);
10805f39d397SChris Mason 	btrfs_set_header_generation(cow, trans->transid);
10815d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
10825d4f98a2SYan Zheng 	btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
10835d4f98a2SYan Zheng 				     BTRFS_HEADER_FLAG_RELOC);
10845d4f98a2SYan Zheng 	if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
10855d4f98a2SYan Zheng 		btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
10865d4f98a2SYan Zheng 	else
10875f39d397SChris Mason 		btrfs_set_header_owner(cow, root->root_key.objectid);
10886702ed49SChris Mason 
10890b246afaSJeff Mahoney 	write_extent_buffer_fsid(cow, fs_info->fsid);
10902b82032cSYan Zheng 
1091be1a5564SMark Fasheh 	ret = update_ref_for_cow(trans, root, buf, cow, &last_ref);
1092b68dc2a9SMark Fasheh 	if (ret) {
109366642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
1094b68dc2a9SMark Fasheh 		return ret;
1095b68dc2a9SMark Fasheh 	}
10961a40e23bSZheng Yan 
109727cdeb70SMiao Xie 	if (test_bit(BTRFS_ROOT_REF_COWS, &root->state)) {
109883d4cfd4SJosef Bacik 		ret = btrfs_reloc_cow_block(trans, root, buf, cow);
109993314e3bSZhaolei 		if (ret) {
110066642832SJeff Mahoney 			btrfs_abort_transaction(trans, ret);
110183d4cfd4SJosef Bacik 			return ret;
110283d4cfd4SJosef Bacik 		}
110393314e3bSZhaolei 	}
11043fd0a558SYan, Zheng 
11056702ed49SChris Mason 	if (buf == root->node) {
1106925baeddSChris Mason 		WARN_ON(parent && parent != buf);
11075d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
11085d4f98a2SYan Zheng 		    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
11095d4f98a2SYan Zheng 			parent_start = buf->start;
1110925baeddSChris Mason 
11115f39d397SChris Mason 		extent_buffer_get(cow);
1112d9d19a01SDavid Sterba 		ret = tree_mod_log_insert_root(root->node, cow, 1);
1113d9d19a01SDavid Sterba 		BUG_ON(ret < 0);
1114240f62c8SChris Mason 		rcu_assign_pointer(root->node, cow);
1115925baeddSChris Mason 
1116f0486c68SYan, Zheng 		btrfs_free_tree_block(trans, root, buf, parent_start,
11175581a51aSJan Schmidt 				      last_ref);
11185f39d397SChris Mason 		free_extent_buffer(buf);
11190b86a832SChris Mason 		add_root_to_dirty_list(root);
11206702ed49SChris Mason 	} else {
11215d4f98a2SYan Zheng 		WARN_ON(trans->transid != btrfs_header_generation(parent));
1122e09c2efeSDavid Sterba 		tree_mod_log_insert_key(parent, parent_slot,
1123c8cc6341SJosef Bacik 					MOD_LOG_KEY_REPLACE, GFP_NOFS);
11245f39d397SChris Mason 		btrfs_set_node_blockptr(parent, parent_slot,
1125db94535dSChris Mason 					cow->start);
112674493f7aSChris Mason 		btrfs_set_node_ptr_generation(parent, parent_slot,
112774493f7aSChris Mason 					      trans->transid);
11286702ed49SChris Mason 		btrfs_mark_buffer_dirty(parent);
11295de865eeSFilipe David Borba Manana 		if (last_ref) {
1130db7279a2SDavid Sterba 			ret = tree_mod_log_free_eb(buf);
11315de865eeSFilipe David Borba Manana 			if (ret) {
113266642832SJeff Mahoney 				btrfs_abort_transaction(trans, ret);
11335de865eeSFilipe David Borba Manana 				return ret;
11345de865eeSFilipe David Borba Manana 			}
11355de865eeSFilipe David Borba Manana 		}
1136f0486c68SYan, Zheng 		btrfs_free_tree_block(trans, root, buf, parent_start,
11375581a51aSJan Schmidt 				      last_ref);
11386702ed49SChris Mason 	}
1139925baeddSChris Mason 	if (unlock_orig)
1140925baeddSChris Mason 		btrfs_tree_unlock(buf);
11413083ee2eSJosef Bacik 	free_extent_buffer_stale(buf);
11426702ed49SChris Mason 	btrfs_mark_buffer_dirty(cow);
11436702ed49SChris Mason 	*cow_ret = cow;
11446702ed49SChris Mason 	return 0;
11456702ed49SChris Mason }
11466702ed49SChris Mason 
11475d9e75c4SJan Schmidt /*
11485d9e75c4SJan Schmidt  * returns the logical address of the oldest predecessor of the given root.
11495d9e75c4SJan Schmidt  * entries older than time_seq are ignored.
11505d9e75c4SJan Schmidt  */
1151bcd24dabSDavid Sterba static struct tree_mod_elem *__tree_mod_log_oldest_root(
115230b0463aSJan Schmidt 		struct extent_buffer *eb_root, u64 time_seq)
11535d9e75c4SJan Schmidt {
11545d9e75c4SJan Schmidt 	struct tree_mod_elem *tm;
11555d9e75c4SJan Schmidt 	struct tree_mod_elem *found = NULL;
115630b0463aSJan Schmidt 	u64 root_logical = eb_root->start;
11575d9e75c4SJan Schmidt 	int looped = 0;
11585d9e75c4SJan Schmidt 
11595d9e75c4SJan Schmidt 	if (!time_seq)
116035a3621bSStefan Behrens 		return NULL;
11615d9e75c4SJan Schmidt 
11625d9e75c4SJan Schmidt 	/*
1163298cfd36SChandan Rajendra 	 * the very last operation that's logged for a root is the
1164298cfd36SChandan Rajendra 	 * replacement operation (if it is replaced at all). this has
1165298cfd36SChandan Rajendra 	 * the logical address of the *new* root, making it the very
1166298cfd36SChandan Rajendra 	 * first operation that's logged for this root.
11675d9e75c4SJan Schmidt 	 */
11685d9e75c4SJan Schmidt 	while (1) {
1169bcd24dabSDavid Sterba 		tm = tree_mod_log_search_oldest(eb_root->fs_info, root_logical,
11705d9e75c4SJan Schmidt 						time_seq);
11715d9e75c4SJan Schmidt 		if (!looped && !tm)
117235a3621bSStefan Behrens 			return NULL;
11735d9e75c4SJan Schmidt 		/*
117428da9fb4SJan Schmidt 		 * if there are no tree operation for the oldest root, we simply
117528da9fb4SJan Schmidt 		 * return it. this should only happen if that (old) root is at
117628da9fb4SJan Schmidt 		 * level 0.
11775d9e75c4SJan Schmidt 		 */
117828da9fb4SJan Schmidt 		if (!tm)
117928da9fb4SJan Schmidt 			break;
11805d9e75c4SJan Schmidt 
118128da9fb4SJan Schmidt 		/*
118228da9fb4SJan Schmidt 		 * if there's an operation that's not a root replacement, we
118328da9fb4SJan Schmidt 		 * found the oldest version of our root. normally, we'll find a
118428da9fb4SJan Schmidt 		 * MOD_LOG_KEY_REMOVE_WHILE_FREEING operation here.
118528da9fb4SJan Schmidt 		 */
11865d9e75c4SJan Schmidt 		if (tm->op != MOD_LOG_ROOT_REPLACE)
11875d9e75c4SJan Schmidt 			break;
11885d9e75c4SJan Schmidt 
11895d9e75c4SJan Schmidt 		found = tm;
11905d9e75c4SJan Schmidt 		root_logical = tm->old_root.logical;
11915d9e75c4SJan Schmidt 		looped = 1;
11925d9e75c4SJan Schmidt 	}
11935d9e75c4SJan Schmidt 
1194a95236d9SJan Schmidt 	/* if there's no old root to return, return what we found instead */
1195a95236d9SJan Schmidt 	if (!found)
1196a95236d9SJan Schmidt 		found = tm;
1197a95236d9SJan Schmidt 
11985d9e75c4SJan Schmidt 	return found;
11995d9e75c4SJan Schmidt }
12005d9e75c4SJan Schmidt 
12015d9e75c4SJan Schmidt /*
12025d9e75c4SJan Schmidt  * tm is a pointer to the first operation to rewind within eb. then, all
120301327610SNicholas D Steeves  * previous operations will be rewound (until we reach something older than
12045d9e75c4SJan Schmidt  * time_seq).
12055d9e75c4SJan Schmidt  */
12065d9e75c4SJan Schmidt static void
1207f1ca7e98SJosef Bacik __tree_mod_log_rewind(struct btrfs_fs_info *fs_info, struct extent_buffer *eb,
1208f1ca7e98SJosef Bacik 		      u64 time_seq, struct tree_mod_elem *first_tm)
12095d9e75c4SJan Schmidt {
12105d9e75c4SJan Schmidt 	u32 n;
12115d9e75c4SJan Schmidt 	struct rb_node *next;
12125d9e75c4SJan Schmidt 	struct tree_mod_elem *tm = first_tm;
12135d9e75c4SJan Schmidt 	unsigned long o_dst;
12145d9e75c4SJan Schmidt 	unsigned long o_src;
12155d9e75c4SJan Schmidt 	unsigned long p_size = sizeof(struct btrfs_key_ptr);
12165d9e75c4SJan Schmidt 
12175d9e75c4SJan Schmidt 	n = btrfs_header_nritems(eb);
1218b1a09f1eSDavid Sterba 	read_lock(&fs_info->tree_mod_log_lock);
1219097b8a7cSJan Schmidt 	while (tm && tm->seq >= time_seq) {
12205d9e75c4SJan Schmidt 		/*
12215d9e75c4SJan Schmidt 		 * all the operations are recorded with the operator used for
12225d9e75c4SJan Schmidt 		 * the modification. as we're going backwards, we do the
12235d9e75c4SJan Schmidt 		 * opposite of each operation here.
12245d9e75c4SJan Schmidt 		 */
12255d9e75c4SJan Schmidt 		switch (tm->op) {
12265d9e75c4SJan Schmidt 		case MOD_LOG_KEY_REMOVE_WHILE_FREEING:
12275d9e75c4SJan Schmidt 			BUG_ON(tm->slot < n);
12281c697d4aSEric Sandeen 			/* Fallthrough */
122995c80bb1SLiu Bo 		case MOD_LOG_KEY_REMOVE_WHILE_MOVING:
12304c3e6969SChris Mason 		case MOD_LOG_KEY_REMOVE:
12315d9e75c4SJan Schmidt 			btrfs_set_node_key(eb, &tm->key, tm->slot);
12325d9e75c4SJan Schmidt 			btrfs_set_node_blockptr(eb, tm->slot, tm->blockptr);
12335d9e75c4SJan Schmidt 			btrfs_set_node_ptr_generation(eb, tm->slot,
12345d9e75c4SJan Schmidt 						      tm->generation);
12354c3e6969SChris Mason 			n++;
12365d9e75c4SJan Schmidt 			break;
12375d9e75c4SJan Schmidt 		case MOD_LOG_KEY_REPLACE:
12385d9e75c4SJan Schmidt 			BUG_ON(tm->slot >= n);
12395d9e75c4SJan Schmidt 			btrfs_set_node_key(eb, &tm->key, tm->slot);
12405d9e75c4SJan Schmidt 			btrfs_set_node_blockptr(eb, tm->slot, tm->blockptr);
12415d9e75c4SJan Schmidt 			btrfs_set_node_ptr_generation(eb, tm->slot,
12425d9e75c4SJan Schmidt 						      tm->generation);
12435d9e75c4SJan Schmidt 			break;
12445d9e75c4SJan Schmidt 		case MOD_LOG_KEY_ADD:
124519956c7eSJan Schmidt 			/* if a move operation is needed it's in the log */
12465d9e75c4SJan Schmidt 			n--;
12475d9e75c4SJan Schmidt 			break;
12485d9e75c4SJan Schmidt 		case MOD_LOG_MOVE_KEYS:
1249c3193108SJan Schmidt 			o_dst = btrfs_node_key_ptr_offset(tm->slot);
1250c3193108SJan Schmidt 			o_src = btrfs_node_key_ptr_offset(tm->move.dst_slot);
1251c3193108SJan Schmidt 			memmove_extent_buffer(eb, o_dst, o_src,
12525d9e75c4SJan Schmidt 					      tm->move.nr_items * p_size);
12535d9e75c4SJan Schmidt 			break;
12545d9e75c4SJan Schmidt 		case MOD_LOG_ROOT_REPLACE:
12555d9e75c4SJan Schmidt 			/*
12565d9e75c4SJan Schmidt 			 * this operation is special. for roots, this must be
12575d9e75c4SJan Schmidt 			 * handled explicitly before rewinding.
12585d9e75c4SJan Schmidt 			 * for non-roots, this operation may exist if the node
12595d9e75c4SJan Schmidt 			 * was a root: root A -> child B; then A gets empty and
12605d9e75c4SJan Schmidt 			 * B is promoted to the new root. in the mod log, we'll
12615d9e75c4SJan Schmidt 			 * have a root-replace operation for B, a tree block
12625d9e75c4SJan Schmidt 			 * that is no root. we simply ignore that operation.
12635d9e75c4SJan Schmidt 			 */
12645d9e75c4SJan Schmidt 			break;
12655d9e75c4SJan Schmidt 		}
12665d9e75c4SJan Schmidt 		next = rb_next(&tm->node);
12675d9e75c4SJan Schmidt 		if (!next)
12685d9e75c4SJan Schmidt 			break;
12696b4df8b6SGeliang Tang 		tm = rb_entry(next, struct tree_mod_elem, node);
1270298cfd36SChandan Rajendra 		if (tm->logical != first_tm->logical)
12715d9e75c4SJan Schmidt 			break;
12725d9e75c4SJan Schmidt 	}
1273b1a09f1eSDavid Sterba 	read_unlock(&fs_info->tree_mod_log_lock);
12745d9e75c4SJan Schmidt 	btrfs_set_header_nritems(eb, n);
12755d9e75c4SJan Schmidt }
12765d9e75c4SJan Schmidt 
127747fb091fSJan Schmidt /*
127801327610SNicholas D Steeves  * Called with eb read locked. If the buffer cannot be rewound, the same buffer
127947fb091fSJan Schmidt  * is returned. If rewind operations happen, a fresh buffer is returned. The
128047fb091fSJan Schmidt  * returned buffer is always read-locked. If the returned buffer is not the
128147fb091fSJan Schmidt  * input buffer, the lock on the input buffer is released and the input buffer
128247fb091fSJan Schmidt  * is freed (its refcount is decremented).
128347fb091fSJan Schmidt  */
12845d9e75c4SJan Schmidt static struct extent_buffer *
12859ec72677SJosef Bacik tree_mod_log_rewind(struct btrfs_fs_info *fs_info, struct btrfs_path *path,
12869ec72677SJosef Bacik 		    struct extent_buffer *eb, u64 time_seq)
12875d9e75c4SJan Schmidt {
12885d9e75c4SJan Schmidt 	struct extent_buffer *eb_rewin;
12895d9e75c4SJan Schmidt 	struct tree_mod_elem *tm;
12905d9e75c4SJan Schmidt 
12915d9e75c4SJan Schmidt 	if (!time_seq)
12925d9e75c4SJan Schmidt 		return eb;
12935d9e75c4SJan Schmidt 
12945d9e75c4SJan Schmidt 	if (btrfs_header_level(eb) == 0)
12955d9e75c4SJan Schmidt 		return eb;
12965d9e75c4SJan Schmidt 
12975d9e75c4SJan Schmidt 	tm = tree_mod_log_search(fs_info, eb->start, time_seq);
12985d9e75c4SJan Schmidt 	if (!tm)
12995d9e75c4SJan Schmidt 		return eb;
13005d9e75c4SJan Schmidt 
13019ec72677SJosef Bacik 	btrfs_set_path_blocking(path);
13029ec72677SJosef Bacik 	btrfs_set_lock_blocking_rw(eb, BTRFS_READ_LOCK);
13039ec72677SJosef Bacik 
13045d9e75c4SJan Schmidt 	if (tm->op == MOD_LOG_KEY_REMOVE_WHILE_FREEING) {
13055d9e75c4SJan Schmidt 		BUG_ON(tm->slot != 0);
1306da17066cSJeff Mahoney 		eb_rewin = alloc_dummy_extent_buffer(fs_info, eb->start);
1307db7f3436SJosef Bacik 		if (!eb_rewin) {
13089ec72677SJosef Bacik 			btrfs_tree_read_unlock_blocking(eb);
1309db7f3436SJosef Bacik 			free_extent_buffer(eb);
1310db7f3436SJosef Bacik 			return NULL;
1311db7f3436SJosef Bacik 		}
13125d9e75c4SJan Schmidt 		btrfs_set_header_bytenr(eb_rewin, eb->start);
13135d9e75c4SJan Schmidt 		btrfs_set_header_backref_rev(eb_rewin,
13145d9e75c4SJan Schmidt 					     btrfs_header_backref_rev(eb));
13155d9e75c4SJan Schmidt 		btrfs_set_header_owner(eb_rewin, btrfs_header_owner(eb));
1316c3193108SJan Schmidt 		btrfs_set_header_level(eb_rewin, btrfs_header_level(eb));
13175d9e75c4SJan Schmidt 	} else {
13185d9e75c4SJan Schmidt 		eb_rewin = btrfs_clone_extent_buffer(eb);
1319db7f3436SJosef Bacik 		if (!eb_rewin) {
13209ec72677SJosef Bacik 			btrfs_tree_read_unlock_blocking(eb);
1321db7f3436SJosef Bacik 			free_extent_buffer(eb);
1322db7f3436SJosef Bacik 			return NULL;
1323db7f3436SJosef Bacik 		}
13245d9e75c4SJan Schmidt 	}
13255d9e75c4SJan Schmidt 
13269ec72677SJosef Bacik 	btrfs_clear_path_blocking(path, NULL, BTRFS_READ_LOCK);
13279ec72677SJosef Bacik 	btrfs_tree_read_unlock_blocking(eb);
13285d9e75c4SJan Schmidt 	free_extent_buffer(eb);
13295d9e75c4SJan Schmidt 
133047fb091fSJan Schmidt 	extent_buffer_get(eb_rewin);
133147fb091fSJan Schmidt 	btrfs_tree_read_lock(eb_rewin);
1332f1ca7e98SJosef Bacik 	__tree_mod_log_rewind(fs_info, eb_rewin, time_seq, tm);
133357911b8bSJan Schmidt 	WARN_ON(btrfs_header_nritems(eb_rewin) >
1334da17066cSJeff Mahoney 		BTRFS_NODEPTRS_PER_BLOCK(fs_info));
13355d9e75c4SJan Schmidt 
13365d9e75c4SJan Schmidt 	return eb_rewin;
13375d9e75c4SJan Schmidt }
13385d9e75c4SJan Schmidt 
13398ba97a15SJan Schmidt /*
13408ba97a15SJan Schmidt  * get_old_root() rewinds the state of @root's root node to the given @time_seq
13418ba97a15SJan Schmidt  * value. If there are no changes, the current root->root_node is returned. If
13428ba97a15SJan Schmidt  * anything changed in between, there's a fresh buffer allocated on which the
13438ba97a15SJan Schmidt  * rewind operations are done. In any case, the returned buffer is read locked.
13448ba97a15SJan Schmidt  * Returns NULL on error (with no locks held).
13458ba97a15SJan Schmidt  */
13465d9e75c4SJan Schmidt static inline struct extent_buffer *
13475d9e75c4SJan Schmidt get_old_root(struct btrfs_root *root, u64 time_seq)
13485d9e75c4SJan Schmidt {
13490b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
13505d9e75c4SJan Schmidt 	struct tree_mod_elem *tm;
135130b0463aSJan Schmidt 	struct extent_buffer *eb = NULL;
135230b0463aSJan Schmidt 	struct extent_buffer *eb_root;
13537bfdcf7fSLiu Bo 	struct extent_buffer *old;
1354a95236d9SJan Schmidt 	struct tree_mod_root *old_root = NULL;
13554325edd0SChris Mason 	u64 old_generation = 0;
1356a95236d9SJan Schmidt 	u64 logical;
1357*581c1760SQu Wenruo 	int level;
13585d9e75c4SJan Schmidt 
135930b0463aSJan Schmidt 	eb_root = btrfs_read_lock_root_node(root);
1360bcd24dabSDavid Sterba 	tm = __tree_mod_log_oldest_root(eb_root, time_seq);
13615d9e75c4SJan Schmidt 	if (!tm)
136230b0463aSJan Schmidt 		return eb_root;
13635d9e75c4SJan Schmidt 
1364a95236d9SJan Schmidt 	if (tm->op == MOD_LOG_ROOT_REPLACE) {
13655d9e75c4SJan Schmidt 		old_root = &tm->old_root;
13665d9e75c4SJan Schmidt 		old_generation = tm->generation;
1367a95236d9SJan Schmidt 		logical = old_root->logical;
1368*581c1760SQu Wenruo 		level = old_root->level;
1369a95236d9SJan Schmidt 	} else {
137030b0463aSJan Schmidt 		logical = eb_root->start;
1371*581c1760SQu Wenruo 		level = btrfs_header_level(eb_root);
1372a95236d9SJan Schmidt 	}
13735d9e75c4SJan Schmidt 
13740b246afaSJeff Mahoney 	tm = tree_mod_log_search(fs_info, logical, time_seq);
1375834328a8SJan Schmidt 	if (old_root && tm && tm->op != MOD_LOG_KEY_REMOVE_WHILE_FREEING) {
137630b0463aSJan Schmidt 		btrfs_tree_read_unlock(eb_root);
137730b0463aSJan Schmidt 		free_extent_buffer(eb_root);
1378*581c1760SQu Wenruo 		old = read_tree_block(fs_info, logical, 0, level, NULL);
137964c043deSLiu Bo 		if (WARN_ON(IS_ERR(old) || !extent_buffer_uptodate(old))) {
138064c043deSLiu Bo 			if (!IS_ERR(old))
1381416bc658SJosef Bacik 				free_extent_buffer(old);
13820b246afaSJeff Mahoney 			btrfs_warn(fs_info,
13830b246afaSJeff Mahoney 				   "failed to read tree block %llu from get_old_root",
13840b246afaSJeff Mahoney 				   logical);
1385834328a8SJan Schmidt 		} else {
13867bfdcf7fSLiu Bo 			eb = btrfs_clone_extent_buffer(old);
13877bfdcf7fSLiu Bo 			free_extent_buffer(old);
1388834328a8SJan Schmidt 		}
1389834328a8SJan Schmidt 	} else if (old_root) {
139030b0463aSJan Schmidt 		btrfs_tree_read_unlock(eb_root);
139130b0463aSJan Schmidt 		free_extent_buffer(eb_root);
13920b246afaSJeff Mahoney 		eb = alloc_dummy_extent_buffer(fs_info, logical);
1393834328a8SJan Schmidt 	} else {
13949ec72677SJosef Bacik 		btrfs_set_lock_blocking_rw(eb_root, BTRFS_READ_LOCK);
139530b0463aSJan Schmidt 		eb = btrfs_clone_extent_buffer(eb_root);
13969ec72677SJosef Bacik 		btrfs_tree_read_unlock_blocking(eb_root);
139730b0463aSJan Schmidt 		free_extent_buffer(eb_root);
1398834328a8SJan Schmidt 	}
1399834328a8SJan Schmidt 
14008ba97a15SJan Schmidt 	if (!eb)
14018ba97a15SJan Schmidt 		return NULL;
1402d6381084SJan Schmidt 	extent_buffer_get(eb);
14038ba97a15SJan Schmidt 	btrfs_tree_read_lock(eb);
1404a95236d9SJan Schmidt 	if (old_root) {
14055d9e75c4SJan Schmidt 		btrfs_set_header_bytenr(eb, eb->start);
14065d9e75c4SJan Schmidt 		btrfs_set_header_backref_rev(eb, BTRFS_MIXED_BACKREF_REV);
140730b0463aSJan Schmidt 		btrfs_set_header_owner(eb, btrfs_header_owner(eb_root));
14085d9e75c4SJan Schmidt 		btrfs_set_header_level(eb, old_root->level);
14095d9e75c4SJan Schmidt 		btrfs_set_header_generation(eb, old_generation);
1410a95236d9SJan Schmidt 	}
141128da9fb4SJan Schmidt 	if (tm)
14120b246afaSJeff Mahoney 		__tree_mod_log_rewind(fs_info, eb, time_seq, tm);
141328da9fb4SJan Schmidt 	else
141428da9fb4SJan Schmidt 		WARN_ON(btrfs_header_level(eb) != 0);
14150b246afaSJeff Mahoney 	WARN_ON(btrfs_header_nritems(eb) > BTRFS_NODEPTRS_PER_BLOCK(fs_info));
14165d9e75c4SJan Schmidt 
14175d9e75c4SJan Schmidt 	return eb;
14185d9e75c4SJan Schmidt }
14195d9e75c4SJan Schmidt 
14205b6602e7SJan Schmidt int btrfs_old_root_level(struct btrfs_root *root, u64 time_seq)
14215b6602e7SJan Schmidt {
14225b6602e7SJan Schmidt 	struct tree_mod_elem *tm;
14235b6602e7SJan Schmidt 	int level;
142430b0463aSJan Schmidt 	struct extent_buffer *eb_root = btrfs_root_node(root);
14255b6602e7SJan Schmidt 
1426bcd24dabSDavid Sterba 	tm = __tree_mod_log_oldest_root(eb_root, time_seq);
14275b6602e7SJan Schmidt 	if (tm && tm->op == MOD_LOG_ROOT_REPLACE) {
14285b6602e7SJan Schmidt 		level = tm->old_root.level;
14295b6602e7SJan Schmidt 	} else {
143030b0463aSJan Schmidt 		level = btrfs_header_level(eb_root);
14315b6602e7SJan Schmidt 	}
143230b0463aSJan Schmidt 	free_extent_buffer(eb_root);
14335b6602e7SJan Schmidt 
14345b6602e7SJan Schmidt 	return level;
14355b6602e7SJan Schmidt }
14365b6602e7SJan Schmidt 
14375d4f98a2SYan Zheng static inline int should_cow_block(struct btrfs_trans_handle *trans,
14385d4f98a2SYan Zheng 				   struct btrfs_root *root,
14395d4f98a2SYan Zheng 				   struct extent_buffer *buf)
14405d4f98a2SYan Zheng {
1441f5ee5c9aSJeff Mahoney 	if (btrfs_is_testing(root->fs_info))
1442faa2dbf0SJosef Bacik 		return 0;
1443fccb84c9SDavid Sterba 
1444f1ebcc74SLiu Bo 	/* ensure we can see the force_cow */
1445f1ebcc74SLiu Bo 	smp_rmb();
1446f1ebcc74SLiu Bo 
1447f1ebcc74SLiu Bo 	/*
1448f1ebcc74SLiu Bo 	 * We do not need to cow a block if
1449f1ebcc74SLiu Bo 	 * 1) this block is not created or changed in this transaction;
1450f1ebcc74SLiu Bo 	 * 2) this block does not belong to TREE_RELOC tree;
1451f1ebcc74SLiu Bo 	 * 3) the root is not forced COW.
1452f1ebcc74SLiu Bo 	 *
1453f1ebcc74SLiu Bo 	 * What is forced COW:
145401327610SNicholas D Steeves 	 *    when we create snapshot during committing the transaction,
1455f1ebcc74SLiu Bo 	 *    after we've finished coping src root, we must COW the shared
1456f1ebcc74SLiu Bo 	 *    block to ensure the metadata consistency.
1457f1ebcc74SLiu Bo 	 */
14585d4f98a2SYan Zheng 	if (btrfs_header_generation(buf) == trans->transid &&
14595d4f98a2SYan Zheng 	    !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN) &&
14605d4f98a2SYan Zheng 	    !(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
1461f1ebcc74SLiu Bo 	      btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)) &&
146227cdeb70SMiao Xie 	    !test_bit(BTRFS_ROOT_FORCE_COW, &root->state))
14635d4f98a2SYan Zheng 		return 0;
14645d4f98a2SYan Zheng 	return 1;
14655d4f98a2SYan Zheng }
14665d4f98a2SYan Zheng 
1467d352ac68SChris Mason /*
1468d352ac68SChris Mason  * cows a single block, see __btrfs_cow_block for the real work.
146901327610SNicholas D Steeves  * This version of it has extra checks so that a block isn't COWed more than
1470d352ac68SChris Mason  * once per transaction, as long as it hasn't been written yet
1471d352ac68SChris Mason  */
1472d397712bSChris Mason noinline int btrfs_cow_block(struct btrfs_trans_handle *trans,
14735f39d397SChris Mason 		    struct btrfs_root *root, struct extent_buffer *buf,
14745f39d397SChris Mason 		    struct extent_buffer *parent, int parent_slot,
14759fa8cfe7SChris Mason 		    struct extent_buffer **cow_ret)
147602217ed2SChris Mason {
14770b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
14786702ed49SChris Mason 	u64 search_start;
1479f510cfecSChris Mason 	int ret;
1480dc17ff8fSChris Mason 
14810b246afaSJeff Mahoney 	if (trans->transaction != fs_info->running_transaction)
148231b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "trans %llu running %llu\n",
1483c1c9ff7cSGeert Uytterhoeven 		       trans->transid,
14840b246afaSJeff Mahoney 		       fs_info->running_transaction->transid);
148531b1a2bdSJulia Lawall 
14860b246afaSJeff Mahoney 	if (trans->transid != fs_info->generation)
148731b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "trans %llu running %llu\n",
14880b246afaSJeff Mahoney 		       trans->transid, fs_info->generation);
1489dc17ff8fSChris Mason 
14905d4f98a2SYan Zheng 	if (!should_cow_block(trans, root, buf)) {
149164c12921SJeff Mahoney 		trans->dirty = true;
149202217ed2SChris Mason 		*cow_ret = buf;
149302217ed2SChris Mason 		return 0;
149402217ed2SChris Mason 	}
1495c487685dSChris Mason 
1496ee22184bSByongho Lee 	search_start = buf->start & ~((u64)SZ_1G - 1);
1497b4ce94deSChris Mason 
1498b4ce94deSChris Mason 	if (parent)
1499b4ce94deSChris Mason 		btrfs_set_lock_blocking(parent);
1500b4ce94deSChris Mason 	btrfs_set_lock_blocking(buf);
1501b4ce94deSChris Mason 
1502f510cfecSChris Mason 	ret = __btrfs_cow_block(trans, root, buf, parent,
15039fa8cfe7SChris Mason 				 parent_slot, cow_ret, search_start, 0);
15041abe9b8aSliubo 
15051abe9b8aSliubo 	trace_btrfs_cow_block(root, buf, *cow_ret);
15061abe9b8aSliubo 
1507f510cfecSChris Mason 	return ret;
15082c90e5d6SChris Mason }
15096702ed49SChris Mason 
1510d352ac68SChris Mason /*
1511d352ac68SChris Mason  * helper function for defrag to decide if two blocks pointed to by a
1512d352ac68SChris Mason  * node are actually close by
1513d352ac68SChris Mason  */
15146b80053dSChris Mason static int close_blocks(u64 blocknr, u64 other, u32 blocksize)
15156702ed49SChris Mason {
15166b80053dSChris Mason 	if (blocknr < other && other - (blocknr + blocksize) < 32768)
15176702ed49SChris Mason 		return 1;
15186b80053dSChris Mason 	if (blocknr > other && blocknr - (other + blocksize) < 32768)
15196702ed49SChris Mason 		return 1;
152002217ed2SChris Mason 	return 0;
152102217ed2SChris Mason }
152202217ed2SChris Mason 
1523081e9573SChris Mason /*
1524081e9573SChris Mason  * compare two keys in a memcmp fashion
1525081e9573SChris Mason  */
1526310712b2SOmar Sandoval static int comp_keys(const struct btrfs_disk_key *disk,
1527310712b2SOmar Sandoval 		     const struct btrfs_key *k2)
1528081e9573SChris Mason {
1529081e9573SChris Mason 	struct btrfs_key k1;
1530081e9573SChris Mason 
1531081e9573SChris Mason 	btrfs_disk_key_to_cpu(&k1, disk);
1532081e9573SChris Mason 
153320736abaSDiego Calleja 	return btrfs_comp_cpu_keys(&k1, k2);
1534081e9573SChris Mason }
1535081e9573SChris Mason 
1536f3465ca4SJosef Bacik /*
1537f3465ca4SJosef Bacik  * same as comp_keys only with two btrfs_key's
1538f3465ca4SJosef Bacik  */
1539310712b2SOmar Sandoval int btrfs_comp_cpu_keys(const struct btrfs_key *k1, const struct btrfs_key *k2)
1540f3465ca4SJosef Bacik {
1541f3465ca4SJosef Bacik 	if (k1->objectid > k2->objectid)
1542f3465ca4SJosef Bacik 		return 1;
1543f3465ca4SJosef Bacik 	if (k1->objectid < k2->objectid)
1544f3465ca4SJosef Bacik 		return -1;
1545f3465ca4SJosef Bacik 	if (k1->type > k2->type)
1546f3465ca4SJosef Bacik 		return 1;
1547f3465ca4SJosef Bacik 	if (k1->type < k2->type)
1548f3465ca4SJosef Bacik 		return -1;
1549f3465ca4SJosef Bacik 	if (k1->offset > k2->offset)
1550f3465ca4SJosef Bacik 		return 1;
1551f3465ca4SJosef Bacik 	if (k1->offset < k2->offset)
1552f3465ca4SJosef Bacik 		return -1;
1553f3465ca4SJosef Bacik 	return 0;
1554f3465ca4SJosef Bacik }
1555081e9573SChris Mason 
1556d352ac68SChris Mason /*
1557d352ac68SChris Mason  * this is used by the defrag code to go through all the
1558d352ac68SChris Mason  * leaves pointed to by a node and reallocate them so that
1559d352ac68SChris Mason  * disk order is close to key order
1560d352ac68SChris Mason  */
15616702ed49SChris Mason int btrfs_realloc_node(struct btrfs_trans_handle *trans,
15625f39d397SChris Mason 		       struct btrfs_root *root, struct extent_buffer *parent,
1563de78b51aSEric Sandeen 		       int start_slot, u64 *last_ret,
1564a6b6e75eSChris Mason 		       struct btrfs_key *progress)
15656702ed49SChris Mason {
15660b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
15676b80053dSChris Mason 	struct extent_buffer *cur;
15686702ed49SChris Mason 	u64 blocknr;
1569ca7a79adSChris Mason 	u64 gen;
1570e9d0b13bSChris Mason 	u64 search_start = *last_ret;
1571e9d0b13bSChris Mason 	u64 last_block = 0;
15726702ed49SChris Mason 	u64 other;
15736702ed49SChris Mason 	u32 parent_nritems;
15746702ed49SChris Mason 	int end_slot;
15756702ed49SChris Mason 	int i;
15766702ed49SChris Mason 	int err = 0;
1577f2183bdeSChris Mason 	int parent_level;
15786b80053dSChris Mason 	int uptodate;
15796b80053dSChris Mason 	u32 blocksize;
1580081e9573SChris Mason 	int progress_passed = 0;
1581081e9573SChris Mason 	struct btrfs_disk_key disk_key;
15826702ed49SChris Mason 
15835708b959SChris Mason 	parent_level = btrfs_header_level(parent);
15845708b959SChris Mason 
15850b246afaSJeff Mahoney 	WARN_ON(trans->transaction != fs_info->running_transaction);
15860b246afaSJeff Mahoney 	WARN_ON(trans->transid != fs_info->generation);
158786479a04SChris Mason 
15886b80053dSChris Mason 	parent_nritems = btrfs_header_nritems(parent);
15890b246afaSJeff Mahoney 	blocksize = fs_info->nodesize;
15905dfe2be7SFilipe Manana 	end_slot = parent_nritems - 1;
15916702ed49SChris Mason 
15925dfe2be7SFilipe Manana 	if (parent_nritems <= 1)
15936702ed49SChris Mason 		return 0;
15946702ed49SChris Mason 
1595b4ce94deSChris Mason 	btrfs_set_lock_blocking(parent);
1596b4ce94deSChris Mason 
15975dfe2be7SFilipe Manana 	for (i = start_slot; i <= end_slot; i++) {
1598*581c1760SQu Wenruo 		struct btrfs_key first_key;
15996702ed49SChris Mason 		int close = 1;
1600a6b6e75eSChris Mason 
1601081e9573SChris Mason 		btrfs_node_key(parent, &disk_key, i);
1602081e9573SChris Mason 		if (!progress_passed && comp_keys(&disk_key, progress) < 0)
1603081e9573SChris Mason 			continue;
1604081e9573SChris Mason 
1605081e9573SChris Mason 		progress_passed = 1;
16066b80053dSChris Mason 		blocknr = btrfs_node_blockptr(parent, i);
1607ca7a79adSChris Mason 		gen = btrfs_node_ptr_generation(parent, i);
1608*581c1760SQu Wenruo 		btrfs_node_key_to_cpu(parent, &first_key, i);
1609e9d0b13bSChris Mason 		if (last_block == 0)
1610e9d0b13bSChris Mason 			last_block = blocknr;
16115708b959SChris Mason 
16126702ed49SChris Mason 		if (i > 0) {
16136b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i - 1);
16146b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
16156702ed49SChris Mason 		}
16165dfe2be7SFilipe Manana 		if (!close && i < end_slot) {
16176b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i + 1);
16186b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
16196702ed49SChris Mason 		}
1620e9d0b13bSChris Mason 		if (close) {
1621e9d0b13bSChris Mason 			last_block = blocknr;
16226702ed49SChris Mason 			continue;
1623e9d0b13bSChris Mason 		}
16246702ed49SChris Mason 
16250b246afaSJeff Mahoney 		cur = find_extent_buffer(fs_info, blocknr);
16266b80053dSChris Mason 		if (cur)
1627b9fab919SChris Mason 			uptodate = btrfs_buffer_uptodate(cur, gen, 0);
16286b80053dSChris Mason 		else
16296b80053dSChris Mason 			uptodate = 0;
16305708b959SChris Mason 		if (!cur || !uptodate) {
16316b80053dSChris Mason 			if (!cur) {
1632*581c1760SQu Wenruo 				cur = read_tree_block(fs_info, blocknr, gen,
1633*581c1760SQu Wenruo 						      parent_level - 1,
1634*581c1760SQu Wenruo 						      &first_key);
163564c043deSLiu Bo 				if (IS_ERR(cur)) {
163664c043deSLiu Bo 					return PTR_ERR(cur);
163764c043deSLiu Bo 				} else if (!extent_buffer_uptodate(cur)) {
1638416bc658SJosef Bacik 					free_extent_buffer(cur);
163997d9a8a4STsutomu Itoh 					return -EIO;
1640416bc658SJosef Bacik 				}
16416b80053dSChris Mason 			} else if (!uptodate) {
1642*581c1760SQu Wenruo 				err = btrfs_read_buffer(cur, gen,
1643*581c1760SQu Wenruo 						parent_level - 1,&first_key);
1644018642a1STsutomu Itoh 				if (err) {
1645018642a1STsutomu Itoh 					free_extent_buffer(cur);
1646018642a1STsutomu Itoh 					return err;
1647018642a1STsutomu Itoh 				}
16486702ed49SChris Mason 			}
1649f2183bdeSChris Mason 		}
1650e9d0b13bSChris Mason 		if (search_start == 0)
16516b80053dSChris Mason 			search_start = last_block;
1652e9d0b13bSChris Mason 
1653e7a84565SChris Mason 		btrfs_tree_lock(cur);
1654b4ce94deSChris Mason 		btrfs_set_lock_blocking(cur);
16556b80053dSChris Mason 		err = __btrfs_cow_block(trans, root, cur, parent, i,
1656e7a84565SChris Mason 					&cur, search_start,
16576b80053dSChris Mason 					min(16 * blocksize,
16589fa8cfe7SChris Mason 					    (end_slot - i) * blocksize));
1659252c38f0SYan 		if (err) {
1660e7a84565SChris Mason 			btrfs_tree_unlock(cur);
16616b80053dSChris Mason 			free_extent_buffer(cur);
16626702ed49SChris Mason 			break;
1663252c38f0SYan 		}
1664e7a84565SChris Mason 		search_start = cur->start;
1665e7a84565SChris Mason 		last_block = cur->start;
1666f2183bdeSChris Mason 		*last_ret = search_start;
1667e7a84565SChris Mason 		btrfs_tree_unlock(cur);
1668e7a84565SChris Mason 		free_extent_buffer(cur);
16696702ed49SChris Mason 	}
16706702ed49SChris Mason 	return err;
16716702ed49SChris Mason }
16726702ed49SChris Mason 
167374123bd7SChris Mason /*
16745f39d397SChris Mason  * search for key in the extent_buffer.  The items start at offset p,
16755f39d397SChris Mason  * and they are item_size apart.  There are 'max' items in p.
16765f39d397SChris Mason  *
167774123bd7SChris Mason  * the slot in the array is returned via slot, and it points to
167874123bd7SChris Mason  * the place where you would insert key if it is not found in
167974123bd7SChris Mason  * the array.
168074123bd7SChris Mason  *
168174123bd7SChris Mason  * slot may point to max if the key is bigger than all of the keys
168274123bd7SChris Mason  */
1683e02119d5SChris Mason static noinline int generic_bin_search(struct extent_buffer *eb,
1684310712b2SOmar Sandoval 				       unsigned long p, int item_size,
1685310712b2SOmar Sandoval 				       const struct btrfs_key *key,
1686be0e5c09SChris Mason 				       int max, int *slot)
1687be0e5c09SChris Mason {
1688be0e5c09SChris Mason 	int low = 0;
1689be0e5c09SChris Mason 	int high = max;
1690be0e5c09SChris Mason 	int mid;
1691be0e5c09SChris Mason 	int ret;
1692479965d6SChris Mason 	struct btrfs_disk_key *tmp = NULL;
16935f39d397SChris Mason 	struct btrfs_disk_key unaligned;
16945f39d397SChris Mason 	unsigned long offset;
16955f39d397SChris Mason 	char *kaddr = NULL;
16965f39d397SChris Mason 	unsigned long map_start = 0;
16975f39d397SChris Mason 	unsigned long map_len = 0;
1698479965d6SChris Mason 	int err;
1699be0e5c09SChris Mason 
17005e24e9afSLiu Bo 	if (low > high) {
17015e24e9afSLiu Bo 		btrfs_err(eb->fs_info,
17025e24e9afSLiu Bo 		 "%s: low (%d) > high (%d) eb %llu owner %llu level %d",
17035e24e9afSLiu Bo 			  __func__, low, high, eb->start,
17045e24e9afSLiu Bo 			  btrfs_header_owner(eb), btrfs_header_level(eb));
17055e24e9afSLiu Bo 		return -EINVAL;
17065e24e9afSLiu Bo 	}
17075e24e9afSLiu Bo 
1708be0e5c09SChris Mason 	while (low < high) {
1709be0e5c09SChris Mason 		mid = (low + high) / 2;
17105f39d397SChris Mason 		offset = p + mid * item_size;
17115f39d397SChris Mason 
1712a6591715SChris Mason 		if (!kaddr || offset < map_start ||
17135f39d397SChris Mason 		    (offset + sizeof(struct btrfs_disk_key)) >
17145f39d397SChris Mason 		    map_start + map_len) {
1715934d375bSChris Mason 
1716934d375bSChris Mason 			err = map_private_extent_buffer(eb, offset,
1717479965d6SChris Mason 						sizeof(struct btrfs_disk_key),
1718a6591715SChris Mason 						&kaddr, &map_start, &map_len);
17195f39d397SChris Mason 
1720479965d6SChris Mason 			if (!err) {
1721479965d6SChris Mason 				tmp = (struct btrfs_disk_key *)(kaddr + offset -
1722479965d6SChris Mason 							map_start);
1723415b35a5SLiu Bo 			} else if (err == 1) {
17245f39d397SChris Mason 				read_extent_buffer(eb, &unaligned,
17255f39d397SChris Mason 						   offset, sizeof(unaligned));
17265f39d397SChris Mason 				tmp = &unaligned;
1727415b35a5SLiu Bo 			} else {
1728415b35a5SLiu Bo 				return err;
1729479965d6SChris Mason 			}
1730479965d6SChris Mason 
17315f39d397SChris Mason 		} else {
17325f39d397SChris Mason 			tmp = (struct btrfs_disk_key *)(kaddr + offset -
17335f39d397SChris Mason 							map_start);
17345f39d397SChris Mason 		}
1735be0e5c09SChris Mason 		ret = comp_keys(tmp, key);
1736be0e5c09SChris Mason 
1737be0e5c09SChris Mason 		if (ret < 0)
1738be0e5c09SChris Mason 			low = mid + 1;
1739be0e5c09SChris Mason 		else if (ret > 0)
1740be0e5c09SChris Mason 			high = mid;
1741be0e5c09SChris Mason 		else {
1742be0e5c09SChris Mason 			*slot = mid;
1743be0e5c09SChris Mason 			return 0;
1744be0e5c09SChris Mason 		}
1745be0e5c09SChris Mason 	}
1746be0e5c09SChris Mason 	*slot = low;
1747be0e5c09SChris Mason 	return 1;
1748be0e5c09SChris Mason }
1749be0e5c09SChris Mason 
175097571fd0SChris Mason /*
175197571fd0SChris Mason  * simple bin_search frontend that does the right thing for
175297571fd0SChris Mason  * leaves vs nodes
175397571fd0SChris Mason  */
1754a74b35ecSNikolay Borisov int btrfs_bin_search(struct extent_buffer *eb, const struct btrfs_key *key,
17555f39d397SChris Mason 		     int level, int *slot)
1756be0e5c09SChris Mason {
1757f775738fSWang Sheng-Hui 	if (level == 0)
17585f39d397SChris Mason 		return generic_bin_search(eb,
17595f39d397SChris Mason 					  offsetof(struct btrfs_leaf, items),
17600783fcfcSChris Mason 					  sizeof(struct btrfs_item),
17615f39d397SChris Mason 					  key, btrfs_header_nritems(eb),
17627518a238SChris Mason 					  slot);
1763f775738fSWang Sheng-Hui 	else
17645f39d397SChris Mason 		return generic_bin_search(eb,
17655f39d397SChris Mason 					  offsetof(struct btrfs_node, ptrs),
1766123abc88SChris Mason 					  sizeof(struct btrfs_key_ptr),
17675f39d397SChris Mason 					  key, btrfs_header_nritems(eb),
17687518a238SChris Mason 					  slot);
1769be0e5c09SChris Mason }
1770be0e5c09SChris Mason 
1771f0486c68SYan, Zheng static void root_add_used(struct btrfs_root *root, u32 size)
1772f0486c68SYan, Zheng {
1773f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
1774f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
1775f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) + size);
1776f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
1777f0486c68SYan, Zheng }
1778f0486c68SYan, Zheng 
1779f0486c68SYan, Zheng static void root_sub_used(struct btrfs_root *root, u32 size)
1780f0486c68SYan, Zheng {
1781f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
1782f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
1783f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) - size);
1784f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
1785f0486c68SYan, Zheng }
1786f0486c68SYan, Zheng 
1787d352ac68SChris Mason /* given a node and slot number, this reads the blocks it points to.  The
1788d352ac68SChris Mason  * extent buffer is returned with a reference taken (but unlocked).
1789d352ac68SChris Mason  */
17902ff7e61eSJeff Mahoney static noinline struct extent_buffer *
17912ff7e61eSJeff Mahoney read_node_slot(struct btrfs_fs_info *fs_info, struct extent_buffer *parent,
17922ff7e61eSJeff Mahoney 	       int slot)
1793bb803951SChris Mason {
1794ca7a79adSChris Mason 	int level = btrfs_header_level(parent);
1795416bc658SJosef Bacik 	struct extent_buffer *eb;
1796*581c1760SQu Wenruo 	struct btrfs_key first_key;
1797416bc658SJosef Bacik 
1798fb770ae4SLiu Bo 	if (slot < 0 || slot >= btrfs_header_nritems(parent))
1799fb770ae4SLiu Bo 		return ERR_PTR(-ENOENT);
1800ca7a79adSChris Mason 
1801ca7a79adSChris Mason 	BUG_ON(level == 0);
1802ca7a79adSChris Mason 
1803*581c1760SQu Wenruo 	btrfs_node_key_to_cpu(parent, &first_key, slot);
18042ff7e61eSJeff Mahoney 	eb = read_tree_block(fs_info, btrfs_node_blockptr(parent, slot),
1805*581c1760SQu Wenruo 			     btrfs_node_ptr_generation(parent, slot),
1806*581c1760SQu Wenruo 			     level - 1, &first_key);
1807fb770ae4SLiu Bo 	if (!IS_ERR(eb) && !extent_buffer_uptodate(eb)) {
1808416bc658SJosef Bacik 		free_extent_buffer(eb);
1809fb770ae4SLiu Bo 		eb = ERR_PTR(-EIO);
1810416bc658SJosef Bacik 	}
1811416bc658SJosef Bacik 
1812416bc658SJosef Bacik 	return eb;
1813bb803951SChris Mason }
1814bb803951SChris Mason 
1815d352ac68SChris Mason /*
1816d352ac68SChris Mason  * node level balancing, used to make sure nodes are in proper order for
1817d352ac68SChris Mason  * item deletion.  We balance from the top down, so we have to make sure
1818d352ac68SChris Mason  * that a deletion won't leave an node completely empty later on.
1819d352ac68SChris Mason  */
1820e02119d5SChris Mason static noinline int balance_level(struct btrfs_trans_handle *trans,
182198ed5174SChris Mason 			 struct btrfs_root *root,
182298ed5174SChris Mason 			 struct btrfs_path *path, int level)
1823bb803951SChris Mason {
18240b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
18255f39d397SChris Mason 	struct extent_buffer *right = NULL;
18265f39d397SChris Mason 	struct extent_buffer *mid;
18275f39d397SChris Mason 	struct extent_buffer *left = NULL;
18285f39d397SChris Mason 	struct extent_buffer *parent = NULL;
1829bb803951SChris Mason 	int ret = 0;
1830bb803951SChris Mason 	int wret;
1831bb803951SChris Mason 	int pslot;
1832bb803951SChris Mason 	int orig_slot = path->slots[level];
183379f95c82SChris Mason 	u64 orig_ptr;
1834bb803951SChris Mason 
1835bb803951SChris Mason 	if (level == 0)
1836bb803951SChris Mason 		return 0;
1837bb803951SChris Mason 
18385f39d397SChris Mason 	mid = path->nodes[level];
1839b4ce94deSChris Mason 
1840bd681513SChris Mason 	WARN_ON(path->locks[level] != BTRFS_WRITE_LOCK &&
1841bd681513SChris Mason 		path->locks[level] != BTRFS_WRITE_LOCK_BLOCKING);
18427bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
18437bb86316SChris Mason 
18441d4f8a0cSChris Mason 	orig_ptr = btrfs_node_blockptr(mid, orig_slot);
184579f95c82SChris Mason 
1846a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
18475f39d397SChris Mason 		parent = path->nodes[level + 1];
1848bb803951SChris Mason 		pslot = path->slots[level + 1];
1849a05a9bb1SLi Zefan 	}
1850bb803951SChris Mason 
185140689478SChris Mason 	/*
185240689478SChris Mason 	 * deal with the case where there is only one pointer in the root
185340689478SChris Mason 	 * by promoting the node below to a root
185440689478SChris Mason 	 */
18555f39d397SChris Mason 	if (!parent) {
18565f39d397SChris Mason 		struct extent_buffer *child;
1857bb803951SChris Mason 
18585f39d397SChris Mason 		if (btrfs_header_nritems(mid) != 1)
1859bb803951SChris Mason 			return 0;
1860bb803951SChris Mason 
1861bb803951SChris Mason 		/* promote the child to a root */
18622ff7e61eSJeff Mahoney 		child = read_node_slot(fs_info, mid, 0);
1863fb770ae4SLiu Bo 		if (IS_ERR(child)) {
1864fb770ae4SLiu Bo 			ret = PTR_ERR(child);
18650b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
1866305a26afSMark Fasheh 			goto enospc;
1867305a26afSMark Fasheh 		}
1868305a26afSMark Fasheh 
1869925baeddSChris Mason 		btrfs_tree_lock(child);
1870b4ce94deSChris Mason 		btrfs_set_lock_blocking(child);
18719fa8cfe7SChris Mason 		ret = btrfs_cow_block(trans, root, child, mid, 0, &child);
1872f0486c68SYan, Zheng 		if (ret) {
1873f0486c68SYan, Zheng 			btrfs_tree_unlock(child);
1874f0486c68SYan, Zheng 			free_extent_buffer(child);
1875f0486c68SYan, Zheng 			goto enospc;
1876f0486c68SYan, Zheng 		}
18772f375ab9SYan 
1878d9d19a01SDavid Sterba 		ret = tree_mod_log_insert_root(root->node, child, 1);
1879d9d19a01SDavid Sterba 		BUG_ON(ret < 0);
1880240f62c8SChris Mason 		rcu_assign_pointer(root->node, child);
1881925baeddSChris Mason 
18820b86a832SChris Mason 		add_root_to_dirty_list(root);
1883925baeddSChris Mason 		btrfs_tree_unlock(child);
1884b4ce94deSChris Mason 
1885925baeddSChris Mason 		path->locks[level] = 0;
1886bb803951SChris Mason 		path->nodes[level] = NULL;
18877c302b49SDavid Sterba 		clean_tree_block(fs_info, mid);
1888925baeddSChris Mason 		btrfs_tree_unlock(mid);
1889bb803951SChris Mason 		/* once for the path */
18905f39d397SChris Mason 		free_extent_buffer(mid);
1891f0486c68SYan, Zheng 
1892f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
18935581a51aSJan Schmidt 		btrfs_free_tree_block(trans, root, mid, 0, 1);
1894bb803951SChris Mason 		/* once for the root ptr */
18953083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
1896f0486c68SYan, Zheng 		return 0;
1897bb803951SChris Mason 	}
18985f39d397SChris Mason 	if (btrfs_header_nritems(mid) >
18990b246afaSJeff Mahoney 	    BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 4)
1900bb803951SChris Mason 		return 0;
1901bb803951SChris Mason 
19022ff7e61eSJeff Mahoney 	left = read_node_slot(fs_info, parent, pslot - 1);
1903fb770ae4SLiu Bo 	if (IS_ERR(left))
1904fb770ae4SLiu Bo 		left = NULL;
1905fb770ae4SLiu Bo 
19065f39d397SChris Mason 	if (left) {
1907925baeddSChris Mason 		btrfs_tree_lock(left);
1908b4ce94deSChris Mason 		btrfs_set_lock_blocking(left);
19095f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, left,
19109fa8cfe7SChris Mason 				       parent, pslot - 1, &left);
191154aa1f4dSChris Mason 		if (wret) {
191254aa1f4dSChris Mason 			ret = wret;
191354aa1f4dSChris Mason 			goto enospc;
191454aa1f4dSChris Mason 		}
19152cc58cf2SChris Mason 	}
1916fb770ae4SLiu Bo 
19172ff7e61eSJeff Mahoney 	right = read_node_slot(fs_info, parent, pslot + 1);
1918fb770ae4SLiu Bo 	if (IS_ERR(right))
1919fb770ae4SLiu Bo 		right = NULL;
1920fb770ae4SLiu Bo 
19215f39d397SChris Mason 	if (right) {
1922925baeddSChris Mason 		btrfs_tree_lock(right);
1923b4ce94deSChris Mason 		btrfs_set_lock_blocking(right);
19245f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, right,
19259fa8cfe7SChris Mason 				       parent, pslot + 1, &right);
19262cc58cf2SChris Mason 		if (wret) {
19272cc58cf2SChris Mason 			ret = wret;
19282cc58cf2SChris Mason 			goto enospc;
19292cc58cf2SChris Mason 		}
19302cc58cf2SChris Mason 	}
19312cc58cf2SChris Mason 
19322cc58cf2SChris Mason 	/* first, try to make some room in the middle buffer */
19335f39d397SChris Mason 	if (left) {
19345f39d397SChris Mason 		orig_slot += btrfs_header_nritems(left);
19352ff7e61eSJeff Mahoney 		wret = push_node_left(trans, fs_info, left, mid, 1);
193679f95c82SChris Mason 		if (wret < 0)
193779f95c82SChris Mason 			ret = wret;
1938bb803951SChris Mason 	}
193979f95c82SChris Mason 
194079f95c82SChris Mason 	/*
194179f95c82SChris Mason 	 * then try to empty the right most buffer into the middle
194279f95c82SChris Mason 	 */
19435f39d397SChris Mason 	if (right) {
19442ff7e61eSJeff Mahoney 		wret = push_node_left(trans, fs_info, mid, right, 1);
194554aa1f4dSChris Mason 		if (wret < 0 && wret != -ENOSPC)
194679f95c82SChris Mason 			ret = wret;
19475f39d397SChris Mason 		if (btrfs_header_nritems(right) == 0) {
19487c302b49SDavid Sterba 			clean_tree_block(fs_info, right);
1949925baeddSChris Mason 			btrfs_tree_unlock(right);
1950afe5fea7STsutomu Itoh 			del_ptr(root, path, level + 1, pslot + 1);
1951f0486c68SYan, Zheng 			root_sub_used(root, right->len);
19525581a51aSJan Schmidt 			btrfs_free_tree_block(trans, root, right, 0, 1);
19533083ee2eSJosef Bacik 			free_extent_buffer_stale(right);
1954f0486c68SYan, Zheng 			right = NULL;
1955bb803951SChris Mason 		} else {
19565f39d397SChris Mason 			struct btrfs_disk_key right_key;
19575f39d397SChris Mason 			btrfs_node_key(right, &right_key, 0);
19580e82bcfeSDavid Sterba 			ret = tree_mod_log_insert_key(parent, pslot + 1,
19590e82bcfeSDavid Sterba 					MOD_LOG_KEY_REPLACE, GFP_NOFS);
19600e82bcfeSDavid Sterba 			BUG_ON(ret < 0);
19615f39d397SChris Mason 			btrfs_set_node_key(parent, &right_key, pslot + 1);
19625f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
1963bb803951SChris Mason 		}
1964bb803951SChris Mason 	}
19655f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 1) {
196679f95c82SChris Mason 		/*
196779f95c82SChris Mason 		 * we're not allowed to leave a node with one item in the
196879f95c82SChris Mason 		 * tree during a delete.  A deletion from lower in the tree
196979f95c82SChris Mason 		 * could try to delete the only pointer in this node.
197079f95c82SChris Mason 		 * So, pull some keys from the left.
197179f95c82SChris Mason 		 * There has to be a left pointer at this point because
197279f95c82SChris Mason 		 * otherwise we would have pulled some pointers from the
197379f95c82SChris Mason 		 * right
197479f95c82SChris Mason 		 */
1975305a26afSMark Fasheh 		if (!left) {
1976305a26afSMark Fasheh 			ret = -EROFS;
19770b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
1978305a26afSMark Fasheh 			goto enospc;
1979305a26afSMark Fasheh 		}
19802ff7e61eSJeff Mahoney 		wret = balance_node_right(trans, fs_info, mid, left);
198154aa1f4dSChris Mason 		if (wret < 0) {
198279f95c82SChris Mason 			ret = wret;
198354aa1f4dSChris Mason 			goto enospc;
198454aa1f4dSChris Mason 		}
1985bce4eae9SChris Mason 		if (wret == 1) {
19862ff7e61eSJeff Mahoney 			wret = push_node_left(trans, fs_info, left, mid, 1);
1987bce4eae9SChris Mason 			if (wret < 0)
1988bce4eae9SChris Mason 				ret = wret;
1989bce4eae9SChris Mason 		}
199079f95c82SChris Mason 		BUG_ON(wret == 1);
199179f95c82SChris Mason 	}
19925f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 0) {
19937c302b49SDavid Sterba 		clean_tree_block(fs_info, mid);
1994925baeddSChris Mason 		btrfs_tree_unlock(mid);
1995afe5fea7STsutomu Itoh 		del_ptr(root, path, level + 1, pslot);
1996f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
19975581a51aSJan Schmidt 		btrfs_free_tree_block(trans, root, mid, 0, 1);
19983083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
1999f0486c68SYan, Zheng 		mid = NULL;
200079f95c82SChris Mason 	} else {
200179f95c82SChris Mason 		/* update the parent key to reflect our changes */
20025f39d397SChris Mason 		struct btrfs_disk_key mid_key;
20035f39d397SChris Mason 		btrfs_node_key(mid, &mid_key, 0);
20040e82bcfeSDavid Sterba 		ret = tree_mod_log_insert_key(parent, pslot,
20050e82bcfeSDavid Sterba 				MOD_LOG_KEY_REPLACE, GFP_NOFS);
20060e82bcfeSDavid Sterba 		BUG_ON(ret < 0);
20075f39d397SChris Mason 		btrfs_set_node_key(parent, &mid_key, pslot);
20085f39d397SChris Mason 		btrfs_mark_buffer_dirty(parent);
200979f95c82SChris Mason 	}
2010bb803951SChris Mason 
201179f95c82SChris Mason 	/* update the path */
20125f39d397SChris Mason 	if (left) {
20135f39d397SChris Mason 		if (btrfs_header_nritems(left) > orig_slot) {
20145f39d397SChris Mason 			extent_buffer_get(left);
2015925baeddSChris Mason 			/* left was locked after cow */
20165f39d397SChris Mason 			path->nodes[level] = left;
2017bb803951SChris Mason 			path->slots[level + 1] -= 1;
2018bb803951SChris Mason 			path->slots[level] = orig_slot;
2019925baeddSChris Mason 			if (mid) {
2020925baeddSChris Mason 				btrfs_tree_unlock(mid);
20215f39d397SChris Mason 				free_extent_buffer(mid);
2022925baeddSChris Mason 			}
2023bb803951SChris Mason 		} else {
20245f39d397SChris Mason 			orig_slot -= btrfs_header_nritems(left);
2025bb803951SChris Mason 			path->slots[level] = orig_slot;
2026bb803951SChris Mason 		}
2027bb803951SChris Mason 	}
202879f95c82SChris Mason 	/* double check we haven't messed things up */
2029e20d96d6SChris Mason 	if (orig_ptr !=
20305f39d397SChris Mason 	    btrfs_node_blockptr(path->nodes[level], path->slots[level]))
203179f95c82SChris Mason 		BUG();
203254aa1f4dSChris Mason enospc:
2033925baeddSChris Mason 	if (right) {
2034925baeddSChris Mason 		btrfs_tree_unlock(right);
20355f39d397SChris Mason 		free_extent_buffer(right);
2036925baeddSChris Mason 	}
2037925baeddSChris Mason 	if (left) {
2038925baeddSChris Mason 		if (path->nodes[level] != left)
2039925baeddSChris Mason 			btrfs_tree_unlock(left);
20405f39d397SChris Mason 		free_extent_buffer(left);
2041925baeddSChris Mason 	}
2042bb803951SChris Mason 	return ret;
2043bb803951SChris Mason }
2044bb803951SChris Mason 
2045d352ac68SChris Mason /* Node balancing for insertion.  Here we only split or push nodes around
2046d352ac68SChris Mason  * when they are completely full.  This is also done top down, so we
2047d352ac68SChris Mason  * have to be pessimistic.
2048d352ac68SChris Mason  */
2049d397712bSChris Mason static noinline int push_nodes_for_insert(struct btrfs_trans_handle *trans,
2050e66f709bSChris Mason 					  struct btrfs_root *root,
2051e66f709bSChris Mason 					  struct btrfs_path *path, int level)
2052e66f709bSChris Mason {
20530b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
20545f39d397SChris Mason 	struct extent_buffer *right = NULL;
20555f39d397SChris Mason 	struct extent_buffer *mid;
20565f39d397SChris Mason 	struct extent_buffer *left = NULL;
20575f39d397SChris Mason 	struct extent_buffer *parent = NULL;
2058e66f709bSChris Mason 	int ret = 0;
2059e66f709bSChris Mason 	int wret;
2060e66f709bSChris Mason 	int pslot;
2061e66f709bSChris Mason 	int orig_slot = path->slots[level];
2062e66f709bSChris Mason 
2063e66f709bSChris Mason 	if (level == 0)
2064e66f709bSChris Mason 		return 1;
2065e66f709bSChris Mason 
20665f39d397SChris Mason 	mid = path->nodes[level];
20677bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
2068e66f709bSChris Mason 
2069a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
20705f39d397SChris Mason 		parent = path->nodes[level + 1];
2071e66f709bSChris Mason 		pslot = path->slots[level + 1];
2072a05a9bb1SLi Zefan 	}
2073e66f709bSChris Mason 
20745f39d397SChris Mason 	if (!parent)
2075e66f709bSChris Mason 		return 1;
2076e66f709bSChris Mason 
20772ff7e61eSJeff Mahoney 	left = read_node_slot(fs_info, parent, pslot - 1);
2078fb770ae4SLiu Bo 	if (IS_ERR(left))
2079fb770ae4SLiu Bo 		left = NULL;
2080e66f709bSChris Mason 
2081e66f709bSChris Mason 	/* first, try to make some room in the middle buffer */
20825f39d397SChris Mason 	if (left) {
2083e66f709bSChris Mason 		u32 left_nr;
2084925baeddSChris Mason 
2085925baeddSChris Mason 		btrfs_tree_lock(left);
2086b4ce94deSChris Mason 		btrfs_set_lock_blocking(left);
2087b4ce94deSChris Mason 
20885f39d397SChris Mason 		left_nr = btrfs_header_nritems(left);
20890b246afaSJeff Mahoney 		if (left_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
209033ade1f8SChris Mason 			wret = 1;
209133ade1f8SChris Mason 		} else {
20925f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, left, parent,
20939fa8cfe7SChris Mason 					      pslot - 1, &left);
209454aa1f4dSChris Mason 			if (ret)
209554aa1f4dSChris Mason 				wret = 1;
209654aa1f4dSChris Mason 			else {
20972ff7e61eSJeff Mahoney 				wret = push_node_left(trans, fs_info,
2098971a1f66SChris Mason 						      left, mid, 0);
209954aa1f4dSChris Mason 			}
210033ade1f8SChris Mason 		}
2101e66f709bSChris Mason 		if (wret < 0)
2102e66f709bSChris Mason 			ret = wret;
2103e66f709bSChris Mason 		if (wret == 0) {
21045f39d397SChris Mason 			struct btrfs_disk_key disk_key;
2105e66f709bSChris Mason 			orig_slot += left_nr;
21065f39d397SChris Mason 			btrfs_node_key(mid, &disk_key, 0);
21070e82bcfeSDavid Sterba 			ret = tree_mod_log_insert_key(parent, pslot,
21080e82bcfeSDavid Sterba 					MOD_LOG_KEY_REPLACE, GFP_NOFS);
21090e82bcfeSDavid Sterba 			BUG_ON(ret < 0);
21105f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot);
21115f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
21125f39d397SChris Mason 			if (btrfs_header_nritems(left) > orig_slot) {
21135f39d397SChris Mason 				path->nodes[level] = left;
2114e66f709bSChris Mason 				path->slots[level + 1] -= 1;
2115e66f709bSChris Mason 				path->slots[level] = orig_slot;
2116925baeddSChris Mason 				btrfs_tree_unlock(mid);
21175f39d397SChris Mason 				free_extent_buffer(mid);
2118e66f709bSChris Mason 			} else {
2119e66f709bSChris Mason 				orig_slot -=
21205f39d397SChris Mason 					btrfs_header_nritems(left);
2121e66f709bSChris Mason 				path->slots[level] = orig_slot;
2122925baeddSChris Mason 				btrfs_tree_unlock(left);
21235f39d397SChris Mason 				free_extent_buffer(left);
2124e66f709bSChris Mason 			}
2125e66f709bSChris Mason 			return 0;
2126e66f709bSChris Mason 		}
2127925baeddSChris Mason 		btrfs_tree_unlock(left);
21285f39d397SChris Mason 		free_extent_buffer(left);
2129e66f709bSChris Mason 	}
21302ff7e61eSJeff Mahoney 	right = read_node_slot(fs_info, parent, pslot + 1);
2131fb770ae4SLiu Bo 	if (IS_ERR(right))
2132fb770ae4SLiu Bo 		right = NULL;
2133e66f709bSChris Mason 
2134e66f709bSChris Mason 	/*
2135e66f709bSChris Mason 	 * then try to empty the right most buffer into the middle
2136e66f709bSChris Mason 	 */
21375f39d397SChris Mason 	if (right) {
213833ade1f8SChris Mason 		u32 right_nr;
2139b4ce94deSChris Mason 
2140925baeddSChris Mason 		btrfs_tree_lock(right);
2141b4ce94deSChris Mason 		btrfs_set_lock_blocking(right);
2142b4ce94deSChris Mason 
21435f39d397SChris Mason 		right_nr = btrfs_header_nritems(right);
21440b246afaSJeff Mahoney 		if (right_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
214533ade1f8SChris Mason 			wret = 1;
214633ade1f8SChris Mason 		} else {
21475f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, right,
21485f39d397SChris Mason 					      parent, pslot + 1,
21499fa8cfe7SChris Mason 					      &right);
215054aa1f4dSChris Mason 			if (ret)
215154aa1f4dSChris Mason 				wret = 1;
215254aa1f4dSChris Mason 			else {
21532ff7e61eSJeff Mahoney 				wret = balance_node_right(trans, fs_info,
21545f39d397SChris Mason 							  right, mid);
215533ade1f8SChris Mason 			}
215654aa1f4dSChris Mason 		}
2157e66f709bSChris Mason 		if (wret < 0)
2158e66f709bSChris Mason 			ret = wret;
2159e66f709bSChris Mason 		if (wret == 0) {
21605f39d397SChris Mason 			struct btrfs_disk_key disk_key;
21615f39d397SChris Mason 
21625f39d397SChris Mason 			btrfs_node_key(right, &disk_key, 0);
21630e82bcfeSDavid Sterba 			ret = tree_mod_log_insert_key(parent, pslot + 1,
21640e82bcfeSDavid Sterba 					MOD_LOG_KEY_REPLACE, GFP_NOFS);
21650e82bcfeSDavid Sterba 			BUG_ON(ret < 0);
21665f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot + 1);
21675f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
21685f39d397SChris Mason 
21695f39d397SChris Mason 			if (btrfs_header_nritems(mid) <= orig_slot) {
21705f39d397SChris Mason 				path->nodes[level] = right;
2171e66f709bSChris Mason 				path->slots[level + 1] += 1;
2172e66f709bSChris Mason 				path->slots[level] = orig_slot -
21735f39d397SChris Mason 					btrfs_header_nritems(mid);
2174925baeddSChris Mason 				btrfs_tree_unlock(mid);
21755f39d397SChris Mason 				free_extent_buffer(mid);
2176e66f709bSChris Mason 			} else {
2177925baeddSChris Mason 				btrfs_tree_unlock(right);
21785f39d397SChris Mason 				free_extent_buffer(right);
2179e66f709bSChris Mason 			}
2180e66f709bSChris Mason 			return 0;
2181e66f709bSChris Mason 		}
2182925baeddSChris Mason 		btrfs_tree_unlock(right);
21835f39d397SChris Mason 		free_extent_buffer(right);
2184e66f709bSChris Mason 	}
2185e66f709bSChris Mason 	return 1;
2186e66f709bSChris Mason }
2187e66f709bSChris Mason 
218874123bd7SChris Mason /*
2189d352ac68SChris Mason  * readahead one full node of leaves, finding things that are close
2190d352ac68SChris Mason  * to the block in 'slot', and triggering ra on them.
21913c69faecSChris Mason  */
21922ff7e61eSJeff Mahoney static void reada_for_search(struct btrfs_fs_info *fs_info,
2193e02119d5SChris Mason 			     struct btrfs_path *path,
219401f46658SChris Mason 			     int level, int slot, u64 objectid)
21953c69faecSChris Mason {
21965f39d397SChris Mason 	struct extent_buffer *node;
219701f46658SChris Mason 	struct btrfs_disk_key disk_key;
21983c69faecSChris Mason 	u32 nritems;
21993c69faecSChris Mason 	u64 search;
2200a7175319SChris Mason 	u64 target;
22016b80053dSChris Mason 	u64 nread = 0;
22025f39d397SChris Mason 	struct extent_buffer *eb;
22036b80053dSChris Mason 	u32 nr;
22046b80053dSChris Mason 	u32 blocksize;
22056b80053dSChris Mason 	u32 nscan = 0;
2206db94535dSChris Mason 
2207a6b6e75eSChris Mason 	if (level != 1)
22083c69faecSChris Mason 		return;
22093c69faecSChris Mason 
22106702ed49SChris Mason 	if (!path->nodes[level])
22116702ed49SChris Mason 		return;
22126702ed49SChris Mason 
22135f39d397SChris Mason 	node = path->nodes[level];
2214925baeddSChris Mason 
22153c69faecSChris Mason 	search = btrfs_node_blockptr(node, slot);
22160b246afaSJeff Mahoney 	blocksize = fs_info->nodesize;
22170b246afaSJeff Mahoney 	eb = find_extent_buffer(fs_info, search);
22185f39d397SChris Mason 	if (eb) {
22195f39d397SChris Mason 		free_extent_buffer(eb);
22203c69faecSChris Mason 		return;
22213c69faecSChris Mason 	}
22223c69faecSChris Mason 
2223a7175319SChris Mason 	target = search;
22246b80053dSChris Mason 
22255f39d397SChris Mason 	nritems = btrfs_header_nritems(node);
22266b80053dSChris Mason 	nr = slot;
222725b8b936SJosef Bacik 
22283c69faecSChris Mason 	while (1) {
2229e4058b54SDavid Sterba 		if (path->reada == READA_BACK) {
22306b80053dSChris Mason 			if (nr == 0)
22313c69faecSChris Mason 				break;
22326b80053dSChris Mason 			nr--;
2233e4058b54SDavid Sterba 		} else if (path->reada == READA_FORWARD) {
22346b80053dSChris Mason 			nr++;
22356b80053dSChris Mason 			if (nr >= nritems)
22366b80053dSChris Mason 				break;
22373c69faecSChris Mason 		}
2238e4058b54SDavid Sterba 		if (path->reada == READA_BACK && objectid) {
223901f46658SChris Mason 			btrfs_node_key(node, &disk_key, nr);
224001f46658SChris Mason 			if (btrfs_disk_key_objectid(&disk_key) != objectid)
224101f46658SChris Mason 				break;
224201f46658SChris Mason 		}
22436b80053dSChris Mason 		search = btrfs_node_blockptr(node, nr);
2244a7175319SChris Mason 		if ((search <= target && target - search <= 65536) ||
2245a7175319SChris Mason 		    (search > target && search - target <= 65536)) {
22462ff7e61eSJeff Mahoney 			readahead_tree_block(fs_info, search);
22476b80053dSChris Mason 			nread += blocksize;
22483c69faecSChris Mason 		}
22496b80053dSChris Mason 		nscan++;
2250a7175319SChris Mason 		if ((nread > 65536 || nscan > 32))
22516b80053dSChris Mason 			break;
22523c69faecSChris Mason 	}
22533c69faecSChris Mason }
2254925baeddSChris Mason 
22552ff7e61eSJeff Mahoney static noinline void reada_for_balance(struct btrfs_fs_info *fs_info,
2256b4ce94deSChris Mason 				       struct btrfs_path *path, int level)
2257b4ce94deSChris Mason {
2258b4ce94deSChris Mason 	int slot;
2259b4ce94deSChris Mason 	int nritems;
2260b4ce94deSChris Mason 	struct extent_buffer *parent;
2261b4ce94deSChris Mason 	struct extent_buffer *eb;
2262b4ce94deSChris Mason 	u64 gen;
2263b4ce94deSChris Mason 	u64 block1 = 0;
2264b4ce94deSChris Mason 	u64 block2 = 0;
2265b4ce94deSChris Mason 
22668c594ea8SChris Mason 	parent = path->nodes[level + 1];
2267b4ce94deSChris Mason 	if (!parent)
22680b08851fSJosef Bacik 		return;
2269b4ce94deSChris Mason 
2270b4ce94deSChris Mason 	nritems = btrfs_header_nritems(parent);
22718c594ea8SChris Mason 	slot = path->slots[level + 1];
2272b4ce94deSChris Mason 
2273b4ce94deSChris Mason 	if (slot > 0) {
2274b4ce94deSChris Mason 		block1 = btrfs_node_blockptr(parent, slot - 1);
2275b4ce94deSChris Mason 		gen = btrfs_node_ptr_generation(parent, slot - 1);
22760b246afaSJeff Mahoney 		eb = find_extent_buffer(fs_info, block1);
2277b9fab919SChris Mason 		/*
2278b9fab919SChris Mason 		 * if we get -eagain from btrfs_buffer_uptodate, we
2279b9fab919SChris Mason 		 * don't want to return eagain here.  That will loop
2280b9fab919SChris Mason 		 * forever
2281b9fab919SChris Mason 		 */
2282b9fab919SChris Mason 		if (eb && btrfs_buffer_uptodate(eb, gen, 1) != 0)
2283b4ce94deSChris Mason 			block1 = 0;
2284b4ce94deSChris Mason 		free_extent_buffer(eb);
2285b4ce94deSChris Mason 	}
22868c594ea8SChris Mason 	if (slot + 1 < nritems) {
2287b4ce94deSChris Mason 		block2 = btrfs_node_blockptr(parent, slot + 1);
2288b4ce94deSChris Mason 		gen = btrfs_node_ptr_generation(parent, slot + 1);
22890b246afaSJeff Mahoney 		eb = find_extent_buffer(fs_info, block2);
2290b9fab919SChris Mason 		if (eb && btrfs_buffer_uptodate(eb, gen, 1) != 0)
2291b4ce94deSChris Mason 			block2 = 0;
2292b4ce94deSChris Mason 		free_extent_buffer(eb);
2293b4ce94deSChris Mason 	}
22948c594ea8SChris Mason 
2295b4ce94deSChris Mason 	if (block1)
22962ff7e61eSJeff Mahoney 		readahead_tree_block(fs_info, block1);
2297b4ce94deSChris Mason 	if (block2)
22982ff7e61eSJeff Mahoney 		readahead_tree_block(fs_info, block2);
2299b4ce94deSChris Mason }
2300b4ce94deSChris Mason 
2301b4ce94deSChris Mason 
2302b4ce94deSChris Mason /*
2303d397712bSChris Mason  * when we walk down the tree, it is usually safe to unlock the higher layers
2304d397712bSChris Mason  * in the tree.  The exceptions are when our path goes through slot 0, because
2305d397712bSChris Mason  * operations on the tree might require changing key pointers higher up in the
2306d397712bSChris Mason  * tree.
2307d352ac68SChris Mason  *
2308d397712bSChris Mason  * callers might also have set path->keep_locks, which tells this code to keep
2309d397712bSChris Mason  * the lock if the path points to the last slot in the block.  This is part of
2310d397712bSChris Mason  * walking through the tree, and selecting the next slot in the higher block.
2311d352ac68SChris Mason  *
2312d397712bSChris Mason  * lowest_unlock sets the lowest level in the tree we're allowed to unlock.  so
2313d397712bSChris Mason  * if lowest_unlock is 1, level 0 won't be unlocked
2314d352ac68SChris Mason  */
2315e02119d5SChris Mason static noinline void unlock_up(struct btrfs_path *path, int level,
2316f7c79f30SChris Mason 			       int lowest_unlock, int min_write_lock_level,
2317f7c79f30SChris Mason 			       int *write_lock_level)
2318925baeddSChris Mason {
2319925baeddSChris Mason 	int i;
2320925baeddSChris Mason 	int skip_level = level;
2321051e1b9fSChris Mason 	int no_skips = 0;
2322925baeddSChris Mason 	struct extent_buffer *t;
2323925baeddSChris Mason 
2324925baeddSChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2325925baeddSChris Mason 		if (!path->nodes[i])
2326925baeddSChris Mason 			break;
2327925baeddSChris Mason 		if (!path->locks[i])
2328925baeddSChris Mason 			break;
2329051e1b9fSChris Mason 		if (!no_skips && path->slots[i] == 0) {
2330925baeddSChris Mason 			skip_level = i + 1;
2331925baeddSChris Mason 			continue;
2332925baeddSChris Mason 		}
2333051e1b9fSChris Mason 		if (!no_skips && path->keep_locks) {
2334925baeddSChris Mason 			u32 nritems;
2335925baeddSChris Mason 			t = path->nodes[i];
2336925baeddSChris Mason 			nritems = btrfs_header_nritems(t);
2337051e1b9fSChris Mason 			if (nritems < 1 || path->slots[i] >= nritems - 1) {
2338925baeddSChris Mason 				skip_level = i + 1;
2339925baeddSChris Mason 				continue;
2340925baeddSChris Mason 			}
2341925baeddSChris Mason 		}
2342051e1b9fSChris Mason 		if (skip_level < i && i >= lowest_unlock)
2343051e1b9fSChris Mason 			no_skips = 1;
2344051e1b9fSChris Mason 
2345925baeddSChris Mason 		t = path->nodes[i];
2346925baeddSChris Mason 		if (i >= lowest_unlock && i > skip_level && path->locks[i]) {
2347bd681513SChris Mason 			btrfs_tree_unlock_rw(t, path->locks[i]);
2348925baeddSChris Mason 			path->locks[i] = 0;
2349f7c79f30SChris Mason 			if (write_lock_level &&
2350f7c79f30SChris Mason 			    i > min_write_lock_level &&
2351f7c79f30SChris Mason 			    i <= *write_lock_level) {
2352f7c79f30SChris Mason 				*write_lock_level = i - 1;
2353f7c79f30SChris Mason 			}
2354925baeddSChris Mason 		}
2355925baeddSChris Mason 	}
2356925baeddSChris Mason }
2357925baeddSChris Mason 
23583c69faecSChris Mason /*
2359b4ce94deSChris Mason  * This releases any locks held in the path starting at level and
2360b4ce94deSChris Mason  * going all the way up to the root.
2361b4ce94deSChris Mason  *
2362b4ce94deSChris Mason  * btrfs_search_slot will keep the lock held on higher nodes in a few
2363b4ce94deSChris Mason  * corner cases, such as COW of the block at slot zero in the node.  This
2364b4ce94deSChris Mason  * ignores those rules, and it should only be called when there are no
2365b4ce94deSChris Mason  * more updates to be done higher up in the tree.
2366b4ce94deSChris Mason  */
2367b4ce94deSChris Mason noinline void btrfs_unlock_up_safe(struct btrfs_path *path, int level)
2368b4ce94deSChris Mason {
2369b4ce94deSChris Mason 	int i;
2370b4ce94deSChris Mason 
237109a2a8f9SJosef Bacik 	if (path->keep_locks)
2372b4ce94deSChris Mason 		return;
2373b4ce94deSChris Mason 
2374b4ce94deSChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2375b4ce94deSChris Mason 		if (!path->nodes[i])
237612f4daccSChris Mason 			continue;
2377b4ce94deSChris Mason 		if (!path->locks[i])
237812f4daccSChris Mason 			continue;
2379bd681513SChris Mason 		btrfs_tree_unlock_rw(path->nodes[i], path->locks[i]);
2380b4ce94deSChris Mason 		path->locks[i] = 0;
2381b4ce94deSChris Mason 	}
2382b4ce94deSChris Mason }
2383b4ce94deSChris Mason 
2384b4ce94deSChris Mason /*
2385c8c42864SChris Mason  * helper function for btrfs_search_slot.  The goal is to find a block
2386c8c42864SChris Mason  * in cache without setting the path to blocking.  If we find the block
2387c8c42864SChris Mason  * we return zero and the path is unchanged.
2388c8c42864SChris Mason  *
2389c8c42864SChris Mason  * If we can't find the block, we set the path blocking and do some
2390c8c42864SChris Mason  * reada.  -EAGAIN is returned and the search must be repeated.
2391c8c42864SChris Mason  */
2392c8c42864SChris Mason static int
2393d07b8528SLiu Bo read_block_for_search(struct btrfs_root *root, struct btrfs_path *p,
2394c8c42864SChris Mason 		      struct extent_buffer **eb_ret, int level, int slot,
2395cda79c54SDavid Sterba 		      const struct btrfs_key *key)
2396c8c42864SChris Mason {
23970b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
2398c8c42864SChris Mason 	u64 blocknr;
2399c8c42864SChris Mason 	u64 gen;
2400c8c42864SChris Mason 	struct extent_buffer *b = *eb_ret;
2401c8c42864SChris Mason 	struct extent_buffer *tmp;
2402*581c1760SQu Wenruo 	struct btrfs_key first_key;
240376a05b35SChris Mason 	int ret;
2404*581c1760SQu Wenruo 	int parent_level;
2405c8c42864SChris Mason 
2406c8c42864SChris Mason 	blocknr = btrfs_node_blockptr(b, slot);
2407c8c42864SChris Mason 	gen = btrfs_node_ptr_generation(b, slot);
2408*581c1760SQu Wenruo 	parent_level = btrfs_header_level(b);
2409*581c1760SQu Wenruo 	btrfs_node_key_to_cpu(b, &first_key, slot);
2410c8c42864SChris Mason 
24110b246afaSJeff Mahoney 	tmp = find_extent_buffer(fs_info, blocknr);
2412cb44921aSChris Mason 	if (tmp) {
2413b9fab919SChris Mason 		/* first we do an atomic uptodate check */
2414b9fab919SChris Mason 		if (btrfs_buffer_uptodate(tmp, gen, 1) > 0) {
2415c8c42864SChris Mason 			*eb_ret = tmp;
2416c8c42864SChris Mason 			return 0;
2417c8c42864SChris Mason 		}
2418bdf7c00eSJosef Bacik 
2419cb44921aSChris Mason 		/* the pages were up to date, but we failed
2420cb44921aSChris Mason 		 * the generation number check.  Do a full
2421cb44921aSChris Mason 		 * read for the generation number that is correct.
2422cb44921aSChris Mason 		 * We must do this without dropping locks so
2423cb44921aSChris Mason 		 * we can trust our generation number
2424cb44921aSChris Mason 		 */
2425bd681513SChris Mason 		btrfs_set_path_blocking(p);
2426bd681513SChris Mason 
2427b9fab919SChris Mason 		/* now we're allowed to do a blocking uptodate check */
2428*581c1760SQu Wenruo 		ret = btrfs_read_buffer(tmp, gen, parent_level - 1, &first_key);
2429bdf7c00eSJosef Bacik 		if (!ret) {
2430cb44921aSChris Mason 			*eb_ret = tmp;
2431cb44921aSChris Mason 			return 0;
2432cb44921aSChris Mason 		}
2433cb44921aSChris Mason 		free_extent_buffer(tmp);
2434b3b4aa74SDavid Sterba 		btrfs_release_path(p);
2435cb44921aSChris Mason 		return -EIO;
2436cb44921aSChris Mason 	}
2437c8c42864SChris Mason 
2438c8c42864SChris Mason 	/*
2439c8c42864SChris Mason 	 * reduce lock contention at high levels
2440c8c42864SChris Mason 	 * of the btree by dropping locks before
244176a05b35SChris Mason 	 * we read.  Don't release the lock on the current
244276a05b35SChris Mason 	 * level because we need to walk this node to figure
244376a05b35SChris Mason 	 * out which blocks to read.
2444c8c42864SChris Mason 	 */
24458c594ea8SChris Mason 	btrfs_unlock_up_safe(p, level + 1);
24468c594ea8SChris Mason 	btrfs_set_path_blocking(p);
24478c594ea8SChris Mason 
2448c8c42864SChris Mason 	free_extent_buffer(tmp);
2449e4058b54SDavid Sterba 	if (p->reada != READA_NONE)
24502ff7e61eSJeff Mahoney 		reada_for_search(fs_info, p, level, slot, key->objectid);
2451c8c42864SChris Mason 
2452b3b4aa74SDavid Sterba 	btrfs_release_path(p);
245376a05b35SChris Mason 
245476a05b35SChris Mason 	ret = -EAGAIN;
2455*581c1760SQu Wenruo 	tmp = read_tree_block(fs_info, blocknr, 0, parent_level - 1,
2456*581c1760SQu Wenruo 			      &first_key);
245764c043deSLiu Bo 	if (!IS_ERR(tmp)) {
245876a05b35SChris Mason 		/*
245976a05b35SChris Mason 		 * If the read above didn't mark this buffer up to date,
246076a05b35SChris Mason 		 * it will never end up being up to date.  Set ret to EIO now
246176a05b35SChris Mason 		 * and give up so that our caller doesn't loop forever
246276a05b35SChris Mason 		 * on our EAGAINs.
246376a05b35SChris Mason 		 */
2464b9fab919SChris Mason 		if (!btrfs_buffer_uptodate(tmp, 0, 0))
246576a05b35SChris Mason 			ret = -EIO;
2466c8c42864SChris Mason 		free_extent_buffer(tmp);
2467c871b0f2SLiu Bo 	} else {
2468c871b0f2SLiu Bo 		ret = PTR_ERR(tmp);
246976a05b35SChris Mason 	}
247076a05b35SChris Mason 	return ret;
2471c8c42864SChris Mason }
2472c8c42864SChris Mason 
2473c8c42864SChris Mason /*
2474c8c42864SChris Mason  * helper function for btrfs_search_slot.  This does all of the checks
2475c8c42864SChris Mason  * for node-level blocks and does any balancing required based on
2476c8c42864SChris Mason  * the ins_len.
2477c8c42864SChris Mason  *
2478c8c42864SChris Mason  * If no extra work was required, zero is returned.  If we had to
2479c8c42864SChris Mason  * drop the path, -EAGAIN is returned and btrfs_search_slot must
2480c8c42864SChris Mason  * start over
2481c8c42864SChris Mason  */
2482c8c42864SChris Mason static int
2483c8c42864SChris Mason setup_nodes_for_search(struct btrfs_trans_handle *trans,
2484c8c42864SChris Mason 		       struct btrfs_root *root, struct btrfs_path *p,
2485bd681513SChris Mason 		       struct extent_buffer *b, int level, int ins_len,
2486bd681513SChris Mason 		       int *write_lock_level)
2487c8c42864SChris Mason {
24880b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
2489c8c42864SChris Mason 	int ret;
24900b246afaSJeff Mahoney 
2491c8c42864SChris Mason 	if ((p->search_for_split || ins_len > 0) && btrfs_header_nritems(b) >=
24920b246afaSJeff Mahoney 	    BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3) {
2493c8c42864SChris Mason 		int sret;
2494c8c42864SChris Mason 
2495bd681513SChris Mason 		if (*write_lock_level < level + 1) {
2496bd681513SChris Mason 			*write_lock_level = level + 1;
2497bd681513SChris Mason 			btrfs_release_path(p);
2498bd681513SChris Mason 			goto again;
2499bd681513SChris Mason 		}
2500bd681513SChris Mason 
2501c8c42864SChris Mason 		btrfs_set_path_blocking(p);
25022ff7e61eSJeff Mahoney 		reada_for_balance(fs_info, p, level);
2503c8c42864SChris Mason 		sret = split_node(trans, root, p, level);
2504bd681513SChris Mason 		btrfs_clear_path_blocking(p, NULL, 0);
2505c8c42864SChris Mason 
2506c8c42864SChris Mason 		BUG_ON(sret > 0);
2507c8c42864SChris Mason 		if (sret) {
2508c8c42864SChris Mason 			ret = sret;
2509c8c42864SChris Mason 			goto done;
2510c8c42864SChris Mason 		}
2511c8c42864SChris Mason 		b = p->nodes[level];
2512c8c42864SChris Mason 	} else if (ins_len < 0 && btrfs_header_nritems(b) <
25130b246afaSJeff Mahoney 		   BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 2) {
2514c8c42864SChris Mason 		int sret;
2515c8c42864SChris Mason 
2516bd681513SChris Mason 		if (*write_lock_level < level + 1) {
2517bd681513SChris Mason 			*write_lock_level = level + 1;
2518bd681513SChris Mason 			btrfs_release_path(p);
2519bd681513SChris Mason 			goto again;
2520bd681513SChris Mason 		}
2521bd681513SChris Mason 
2522c8c42864SChris Mason 		btrfs_set_path_blocking(p);
25232ff7e61eSJeff Mahoney 		reada_for_balance(fs_info, p, level);
2524c8c42864SChris Mason 		sret = balance_level(trans, root, p, level);
2525bd681513SChris Mason 		btrfs_clear_path_blocking(p, NULL, 0);
2526c8c42864SChris Mason 
2527c8c42864SChris Mason 		if (sret) {
2528c8c42864SChris Mason 			ret = sret;
2529c8c42864SChris Mason 			goto done;
2530c8c42864SChris Mason 		}
2531c8c42864SChris Mason 		b = p->nodes[level];
2532c8c42864SChris Mason 		if (!b) {
2533b3b4aa74SDavid Sterba 			btrfs_release_path(p);
2534c8c42864SChris Mason 			goto again;
2535c8c42864SChris Mason 		}
2536c8c42864SChris Mason 		BUG_ON(btrfs_header_nritems(b) == 1);
2537c8c42864SChris Mason 	}
2538c8c42864SChris Mason 	return 0;
2539c8c42864SChris Mason 
2540c8c42864SChris Mason again:
2541c8c42864SChris Mason 	ret = -EAGAIN;
2542c8c42864SChris Mason done:
2543c8c42864SChris Mason 	return ret;
2544c8c42864SChris Mason }
2545c8c42864SChris Mason 
2546d7396f07SFilipe David Borba Manana static void key_search_validate(struct extent_buffer *b,
2547310712b2SOmar Sandoval 				const struct btrfs_key *key,
2548d7396f07SFilipe David Borba Manana 				int level)
2549d7396f07SFilipe David Borba Manana {
2550d7396f07SFilipe David Borba Manana #ifdef CONFIG_BTRFS_ASSERT
2551d7396f07SFilipe David Borba Manana 	struct btrfs_disk_key disk_key;
2552d7396f07SFilipe David Borba Manana 
2553d7396f07SFilipe David Borba Manana 	btrfs_cpu_key_to_disk(&disk_key, key);
2554d7396f07SFilipe David Borba Manana 
2555d7396f07SFilipe David Borba Manana 	if (level == 0)
2556d7396f07SFilipe David Borba Manana 		ASSERT(!memcmp_extent_buffer(b, &disk_key,
2557d7396f07SFilipe David Borba Manana 		    offsetof(struct btrfs_leaf, items[0].key),
2558d7396f07SFilipe David Borba Manana 		    sizeof(disk_key)));
2559d7396f07SFilipe David Borba Manana 	else
2560d7396f07SFilipe David Borba Manana 		ASSERT(!memcmp_extent_buffer(b, &disk_key,
2561d7396f07SFilipe David Borba Manana 		    offsetof(struct btrfs_node, ptrs[0].key),
2562d7396f07SFilipe David Borba Manana 		    sizeof(disk_key)));
2563d7396f07SFilipe David Borba Manana #endif
2564d7396f07SFilipe David Borba Manana }
2565d7396f07SFilipe David Borba Manana 
2566310712b2SOmar Sandoval static int key_search(struct extent_buffer *b, const struct btrfs_key *key,
2567d7396f07SFilipe David Borba Manana 		      int level, int *prev_cmp, int *slot)
2568d7396f07SFilipe David Borba Manana {
2569d7396f07SFilipe David Borba Manana 	if (*prev_cmp != 0) {
2570a74b35ecSNikolay Borisov 		*prev_cmp = btrfs_bin_search(b, key, level, slot);
2571d7396f07SFilipe David Borba Manana 		return *prev_cmp;
2572d7396f07SFilipe David Borba Manana 	}
2573d7396f07SFilipe David Borba Manana 
2574d7396f07SFilipe David Borba Manana 	key_search_validate(b, key, level);
2575d7396f07SFilipe David Borba Manana 	*slot = 0;
2576d7396f07SFilipe David Borba Manana 
2577d7396f07SFilipe David Borba Manana 	return 0;
2578d7396f07SFilipe David Borba Manana }
2579d7396f07SFilipe David Borba Manana 
2580381cf658SDavid Sterba int btrfs_find_item(struct btrfs_root *fs_root, struct btrfs_path *path,
2581e33d5c3dSKelley Nielsen 		u64 iobjectid, u64 ioff, u8 key_type,
2582e33d5c3dSKelley Nielsen 		struct btrfs_key *found_key)
2583e33d5c3dSKelley Nielsen {
2584e33d5c3dSKelley Nielsen 	int ret;
2585e33d5c3dSKelley Nielsen 	struct btrfs_key key;
2586e33d5c3dSKelley Nielsen 	struct extent_buffer *eb;
2587381cf658SDavid Sterba 
2588381cf658SDavid Sterba 	ASSERT(path);
25891d4c08e0SDavid Sterba 	ASSERT(found_key);
2590e33d5c3dSKelley Nielsen 
2591e33d5c3dSKelley Nielsen 	key.type = key_type;
2592e33d5c3dSKelley Nielsen 	key.objectid = iobjectid;
2593e33d5c3dSKelley Nielsen 	key.offset = ioff;
2594e33d5c3dSKelley Nielsen 
2595e33d5c3dSKelley Nielsen 	ret = btrfs_search_slot(NULL, fs_root, &key, path, 0, 0);
25961d4c08e0SDavid Sterba 	if (ret < 0)
2597e33d5c3dSKelley Nielsen 		return ret;
2598e33d5c3dSKelley Nielsen 
2599e33d5c3dSKelley Nielsen 	eb = path->nodes[0];
2600e33d5c3dSKelley Nielsen 	if (ret && path->slots[0] >= btrfs_header_nritems(eb)) {
2601e33d5c3dSKelley Nielsen 		ret = btrfs_next_leaf(fs_root, path);
2602e33d5c3dSKelley Nielsen 		if (ret)
2603e33d5c3dSKelley Nielsen 			return ret;
2604e33d5c3dSKelley Nielsen 		eb = path->nodes[0];
2605e33d5c3dSKelley Nielsen 	}
2606e33d5c3dSKelley Nielsen 
2607e33d5c3dSKelley Nielsen 	btrfs_item_key_to_cpu(eb, found_key, path->slots[0]);
2608e33d5c3dSKelley Nielsen 	if (found_key->type != key.type ||
2609e33d5c3dSKelley Nielsen 			found_key->objectid != key.objectid)
2610e33d5c3dSKelley Nielsen 		return 1;
2611e33d5c3dSKelley Nielsen 
2612e33d5c3dSKelley Nielsen 	return 0;
2613e33d5c3dSKelley Nielsen }
2614e33d5c3dSKelley Nielsen 
2615c8c42864SChris Mason /*
26164271eceaSNikolay Borisov  * btrfs_search_slot - look for a key in a tree and perform necessary
26174271eceaSNikolay Borisov  * modifications to preserve tree invariants.
261874123bd7SChris Mason  *
26194271eceaSNikolay Borisov  * @trans:	Handle of transaction, used when modifying the tree
26204271eceaSNikolay Borisov  * @p:		Holds all btree nodes along the search path
26214271eceaSNikolay Borisov  * @root:	The root node of the tree
26224271eceaSNikolay Borisov  * @key:	The key we are looking for
26234271eceaSNikolay Borisov  * @ins_len:	Indicates purpose of search, for inserts it is 1, for
26244271eceaSNikolay Borisov  *		deletions it's -1. 0 for plain searches
26254271eceaSNikolay Borisov  * @cow:	boolean should CoW operations be performed. Must always be 1
26264271eceaSNikolay Borisov  *		when modifying the tree.
262797571fd0SChris Mason  *
26284271eceaSNikolay Borisov  * If @ins_len > 0, nodes and leaves will be split as we walk down the tree.
26294271eceaSNikolay Borisov  * If @ins_len < 0, nodes will be merged as we walk down the tree (if possible)
26304271eceaSNikolay Borisov  *
26314271eceaSNikolay Borisov  * If @key is found, 0 is returned and you can find the item in the leaf level
26324271eceaSNikolay Borisov  * of the path (level 0)
26334271eceaSNikolay Borisov  *
26344271eceaSNikolay Borisov  * If @key isn't found, 1 is returned and the leaf level of the path (level 0)
26354271eceaSNikolay Borisov  * points to the slot where it should be inserted
26364271eceaSNikolay Borisov  *
26374271eceaSNikolay Borisov  * If an error is encountered while searching the tree a negative error number
26384271eceaSNikolay Borisov  * is returned
263974123bd7SChris Mason  */
2640310712b2SOmar Sandoval int btrfs_search_slot(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2641310712b2SOmar Sandoval 		      const struct btrfs_key *key, struct btrfs_path *p,
2642310712b2SOmar Sandoval 		      int ins_len, int cow)
2643be0e5c09SChris Mason {
26440b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
26455f39d397SChris Mason 	struct extent_buffer *b;
2646be0e5c09SChris Mason 	int slot;
2647be0e5c09SChris Mason 	int ret;
264833c66f43SYan Zheng 	int err;
2649be0e5c09SChris Mason 	int level;
2650925baeddSChris Mason 	int lowest_unlock = 1;
2651bd681513SChris Mason 	int root_lock;
2652bd681513SChris Mason 	/* everything at write_lock_level or lower must be write locked */
2653bd681513SChris Mason 	int write_lock_level = 0;
26549f3a7427SChris Mason 	u8 lowest_level = 0;
2655f7c79f30SChris Mason 	int min_write_lock_level;
2656d7396f07SFilipe David Borba Manana 	int prev_cmp;
26579f3a7427SChris Mason 
26586702ed49SChris Mason 	lowest_level = p->lowest_level;
2659323ac95bSChris Mason 	WARN_ON(lowest_level && ins_len > 0);
266022b0ebdaSChris Mason 	WARN_ON(p->nodes[0] != NULL);
2661eb653de1SFilipe David Borba Manana 	BUG_ON(!cow && ins_len);
266225179201SJosef Bacik 
2663bd681513SChris Mason 	if (ins_len < 0) {
2664925baeddSChris Mason 		lowest_unlock = 2;
266565b51a00SChris Mason 
2666bd681513SChris Mason 		/* when we are removing items, we might have to go up to level
2667bd681513SChris Mason 		 * two as we update tree pointers  Make sure we keep write
2668bd681513SChris Mason 		 * for those levels as well
2669bd681513SChris Mason 		 */
2670bd681513SChris Mason 		write_lock_level = 2;
2671bd681513SChris Mason 	} else if (ins_len > 0) {
2672bd681513SChris Mason 		/*
2673bd681513SChris Mason 		 * for inserting items, make sure we have a write lock on
2674bd681513SChris Mason 		 * level 1 so we can update keys
2675bd681513SChris Mason 		 */
2676bd681513SChris Mason 		write_lock_level = 1;
2677bd681513SChris Mason 	}
2678bd681513SChris Mason 
2679bd681513SChris Mason 	if (!cow)
2680bd681513SChris Mason 		write_lock_level = -1;
2681bd681513SChris Mason 
268209a2a8f9SJosef Bacik 	if (cow && (p->keep_locks || p->lowest_level))
2683bd681513SChris Mason 		write_lock_level = BTRFS_MAX_LEVEL;
2684bd681513SChris Mason 
2685f7c79f30SChris Mason 	min_write_lock_level = write_lock_level;
2686f7c79f30SChris Mason 
2687bb803951SChris Mason again:
2688d7396f07SFilipe David Borba Manana 	prev_cmp = -1;
2689bd681513SChris Mason 	/*
2690bd681513SChris Mason 	 * we try very hard to do read locks on the root
2691bd681513SChris Mason 	 */
2692bd681513SChris Mason 	root_lock = BTRFS_READ_LOCK;
2693bd681513SChris Mason 	level = 0;
26945d4f98a2SYan Zheng 	if (p->search_commit_root) {
2695bd681513SChris Mason 		/*
2696bd681513SChris Mason 		 * the commit roots are read only
2697bd681513SChris Mason 		 * so we always do read locks
2698bd681513SChris Mason 		 */
26993f8a18ccSJosef Bacik 		if (p->need_commit_sem)
27000b246afaSJeff Mahoney 			down_read(&fs_info->commit_root_sem);
27015d4f98a2SYan Zheng 		b = root->commit_root;
27025d4f98a2SYan Zheng 		extent_buffer_get(b);
2703bd681513SChris Mason 		level = btrfs_header_level(b);
27043f8a18ccSJosef Bacik 		if (p->need_commit_sem)
27050b246afaSJeff Mahoney 			up_read(&fs_info->commit_root_sem);
27065d4f98a2SYan Zheng 		if (!p->skip_locking)
2707bd681513SChris Mason 			btrfs_tree_read_lock(b);
27085d4f98a2SYan Zheng 	} else {
2709bd681513SChris Mason 		if (p->skip_locking) {
27105cd57b2cSChris Mason 			b = btrfs_root_node(root);
2711bd681513SChris Mason 			level = btrfs_header_level(b);
2712bd681513SChris Mason 		} else {
2713bd681513SChris Mason 			/* we don't know the level of the root node
2714bd681513SChris Mason 			 * until we actually have it read locked
2715bd681513SChris Mason 			 */
2716bd681513SChris Mason 			b = btrfs_read_lock_root_node(root);
2717bd681513SChris Mason 			level = btrfs_header_level(b);
2718bd681513SChris Mason 			if (level <= write_lock_level) {
2719bd681513SChris Mason 				/* whoops, must trade for write lock */
2720bd681513SChris Mason 				btrfs_tree_read_unlock(b);
2721bd681513SChris Mason 				free_extent_buffer(b);
2722925baeddSChris Mason 				b = btrfs_lock_root_node(root);
2723bd681513SChris Mason 				root_lock = BTRFS_WRITE_LOCK;
2724bd681513SChris Mason 
2725bd681513SChris Mason 				/* the level might have changed, check again */
2726bd681513SChris Mason 				level = btrfs_header_level(b);
27275d4f98a2SYan Zheng 			}
2728bd681513SChris Mason 		}
2729bd681513SChris Mason 	}
2730bd681513SChris Mason 	p->nodes[level] = b;
2731bd681513SChris Mason 	if (!p->skip_locking)
2732bd681513SChris Mason 		p->locks[level] = root_lock;
2733925baeddSChris Mason 
2734eb60ceacSChris Mason 	while (b) {
27355f39d397SChris Mason 		level = btrfs_header_level(b);
273665b51a00SChris Mason 
273765b51a00SChris Mason 		/*
273865b51a00SChris Mason 		 * setup the path here so we can release it under lock
273965b51a00SChris Mason 		 * contention with the cow code
274065b51a00SChris Mason 		 */
274102217ed2SChris Mason 		if (cow) {
27429ea2c7c9SNikolay Borisov 			bool last_level = (level == (BTRFS_MAX_LEVEL - 1));
27439ea2c7c9SNikolay Borisov 
2744c8c42864SChris Mason 			/*
2745c8c42864SChris Mason 			 * if we don't really need to cow this block
2746c8c42864SChris Mason 			 * then we don't want to set the path blocking,
2747c8c42864SChris Mason 			 * so we test it here
2748c8c42864SChris Mason 			 */
274964c12921SJeff Mahoney 			if (!should_cow_block(trans, root, b)) {
275064c12921SJeff Mahoney 				trans->dirty = true;
275165b51a00SChris Mason 				goto cow_done;
275264c12921SJeff Mahoney 			}
27535d4f98a2SYan Zheng 
2754bd681513SChris Mason 			/*
2755bd681513SChris Mason 			 * must have write locks on this node and the
2756bd681513SChris Mason 			 * parent
2757bd681513SChris Mason 			 */
27585124e00eSJosef Bacik 			if (level > write_lock_level ||
27595124e00eSJosef Bacik 			    (level + 1 > write_lock_level &&
27605124e00eSJosef Bacik 			    level + 1 < BTRFS_MAX_LEVEL &&
27615124e00eSJosef Bacik 			    p->nodes[level + 1])) {
2762bd681513SChris Mason 				write_lock_level = level + 1;
2763bd681513SChris Mason 				btrfs_release_path(p);
2764bd681513SChris Mason 				goto again;
2765bd681513SChris Mason 			}
2766bd681513SChris Mason 
2767160f4089SFilipe Manana 			btrfs_set_path_blocking(p);
27689ea2c7c9SNikolay Borisov 			if (last_level)
27699ea2c7c9SNikolay Borisov 				err = btrfs_cow_block(trans, root, b, NULL, 0,
27709ea2c7c9SNikolay Borisov 						      &b);
27719ea2c7c9SNikolay Borisov 			else
277233c66f43SYan Zheng 				err = btrfs_cow_block(trans, root, b,
2773e20d96d6SChris Mason 						      p->nodes[level + 1],
27749fa8cfe7SChris Mason 						      p->slots[level + 1], &b);
277533c66f43SYan Zheng 			if (err) {
277633c66f43SYan Zheng 				ret = err;
277765b51a00SChris Mason 				goto done;
277854aa1f4dSChris Mason 			}
277902217ed2SChris Mason 		}
278065b51a00SChris Mason cow_done:
2781eb60ceacSChris Mason 		p->nodes[level] = b;
2782bd681513SChris Mason 		btrfs_clear_path_blocking(p, NULL, 0);
2783b4ce94deSChris Mason 
2784b4ce94deSChris Mason 		/*
2785b4ce94deSChris Mason 		 * we have a lock on b and as long as we aren't changing
2786b4ce94deSChris Mason 		 * the tree, there is no way to for the items in b to change.
2787b4ce94deSChris Mason 		 * It is safe to drop the lock on our parent before we
2788b4ce94deSChris Mason 		 * go through the expensive btree search on b.
2789b4ce94deSChris Mason 		 *
2790eb653de1SFilipe David Borba Manana 		 * If we're inserting or deleting (ins_len != 0), then we might
2791eb653de1SFilipe David Borba Manana 		 * be changing slot zero, which may require changing the parent.
2792eb653de1SFilipe David Borba Manana 		 * So, we can't drop the lock until after we know which slot
2793eb653de1SFilipe David Borba Manana 		 * we're operating on.
2794b4ce94deSChris Mason 		 */
2795eb653de1SFilipe David Borba Manana 		if (!ins_len && !p->keep_locks) {
2796eb653de1SFilipe David Borba Manana 			int u = level + 1;
2797eb653de1SFilipe David Borba Manana 
2798eb653de1SFilipe David Borba Manana 			if (u < BTRFS_MAX_LEVEL && p->locks[u]) {
2799eb653de1SFilipe David Borba Manana 				btrfs_tree_unlock_rw(p->nodes[u], p->locks[u]);
2800eb653de1SFilipe David Borba Manana 				p->locks[u] = 0;
2801eb653de1SFilipe David Borba Manana 			}
2802eb653de1SFilipe David Borba Manana 		}
2803b4ce94deSChris Mason 
2804d7396f07SFilipe David Borba Manana 		ret = key_search(b, key, level, &prev_cmp, &slot);
2805415b35a5SLiu Bo 		if (ret < 0)
2806415b35a5SLiu Bo 			goto done;
2807b4ce94deSChris Mason 
28085f39d397SChris Mason 		if (level != 0) {
280933c66f43SYan Zheng 			int dec = 0;
281033c66f43SYan Zheng 			if (ret && slot > 0) {
281133c66f43SYan Zheng 				dec = 1;
2812be0e5c09SChris Mason 				slot -= 1;
281333c66f43SYan Zheng 			}
2814be0e5c09SChris Mason 			p->slots[level] = slot;
281533c66f43SYan Zheng 			err = setup_nodes_for_search(trans, root, p, b, level,
2816bd681513SChris Mason 					     ins_len, &write_lock_level);
281733c66f43SYan Zheng 			if (err == -EAGAIN)
2818b4ce94deSChris Mason 				goto again;
281933c66f43SYan Zheng 			if (err) {
282033c66f43SYan Zheng 				ret = err;
282165b51a00SChris Mason 				goto done;
282233c66f43SYan Zheng 			}
28235c680ed6SChris Mason 			b = p->nodes[level];
28245c680ed6SChris Mason 			slot = p->slots[level];
2825b4ce94deSChris Mason 
2826bd681513SChris Mason 			/*
2827bd681513SChris Mason 			 * slot 0 is special, if we change the key
2828bd681513SChris Mason 			 * we have to update the parent pointer
2829bd681513SChris Mason 			 * which means we must have a write lock
2830bd681513SChris Mason 			 * on the parent
2831bd681513SChris Mason 			 */
2832eb653de1SFilipe David Borba Manana 			if (slot == 0 && ins_len &&
2833bd681513SChris Mason 			    write_lock_level < level + 1) {
2834bd681513SChris Mason 				write_lock_level = level + 1;
2835bd681513SChris Mason 				btrfs_release_path(p);
2836bd681513SChris Mason 				goto again;
2837bd681513SChris Mason 			}
2838bd681513SChris Mason 
2839f7c79f30SChris Mason 			unlock_up(p, level, lowest_unlock,
2840f7c79f30SChris Mason 				  min_write_lock_level, &write_lock_level);
2841f9efa9c7SChris Mason 
2842925baeddSChris Mason 			if (level == lowest_level) {
284333c66f43SYan Zheng 				if (dec)
284433c66f43SYan Zheng 					p->slots[level]++;
28455b21f2edSZheng Yan 				goto done;
2846925baeddSChris Mason 			}
2847ca7a79adSChris Mason 
2848d07b8528SLiu Bo 			err = read_block_for_search(root, p, &b, level,
2849cda79c54SDavid Sterba 						    slot, key);
285033c66f43SYan Zheng 			if (err == -EAGAIN)
2851051e1b9fSChris Mason 				goto again;
285233c66f43SYan Zheng 			if (err) {
285333c66f43SYan Zheng 				ret = err;
285476a05b35SChris Mason 				goto done;
285533c66f43SYan Zheng 			}
285676a05b35SChris Mason 
2857b4ce94deSChris Mason 			if (!p->skip_locking) {
2858bd681513SChris Mason 				level = btrfs_header_level(b);
2859bd681513SChris Mason 				if (level <= write_lock_level) {
2860bd681513SChris Mason 					err = btrfs_try_tree_write_lock(b);
286133c66f43SYan Zheng 					if (!err) {
2862b4ce94deSChris Mason 						btrfs_set_path_blocking(p);
2863925baeddSChris Mason 						btrfs_tree_lock(b);
2864bd681513SChris Mason 						btrfs_clear_path_blocking(p, b,
2865bd681513SChris Mason 								  BTRFS_WRITE_LOCK);
2866b4ce94deSChris Mason 					}
2867bd681513SChris Mason 					p->locks[level] = BTRFS_WRITE_LOCK;
2868bd681513SChris Mason 				} else {
2869f82c458aSChris Mason 					err = btrfs_tree_read_lock_atomic(b);
2870bd681513SChris Mason 					if (!err) {
2871bd681513SChris Mason 						btrfs_set_path_blocking(p);
2872bd681513SChris Mason 						btrfs_tree_read_lock(b);
2873bd681513SChris Mason 						btrfs_clear_path_blocking(p, b,
2874bd681513SChris Mason 								  BTRFS_READ_LOCK);
2875bd681513SChris Mason 					}
2876bd681513SChris Mason 					p->locks[level] = BTRFS_READ_LOCK;
2877bd681513SChris Mason 				}
2878bd681513SChris Mason 				p->nodes[level] = b;
2879b4ce94deSChris Mason 			}
2880be0e5c09SChris Mason 		} else {
2881be0e5c09SChris Mason 			p->slots[level] = slot;
288287b29b20SYan Zheng 			if (ins_len > 0 &&
28832ff7e61eSJeff Mahoney 			    btrfs_leaf_free_space(fs_info, b) < ins_len) {
2884bd681513SChris Mason 				if (write_lock_level < 1) {
2885bd681513SChris Mason 					write_lock_level = 1;
2886bd681513SChris Mason 					btrfs_release_path(p);
2887bd681513SChris Mason 					goto again;
2888bd681513SChris Mason 				}
2889bd681513SChris Mason 
2890b4ce94deSChris Mason 				btrfs_set_path_blocking(p);
289133c66f43SYan Zheng 				err = split_leaf(trans, root, key,
2892cc0c5538SChris Mason 						 p, ins_len, ret == 0);
2893bd681513SChris Mason 				btrfs_clear_path_blocking(p, NULL, 0);
2894b4ce94deSChris Mason 
289533c66f43SYan Zheng 				BUG_ON(err > 0);
289633c66f43SYan Zheng 				if (err) {
289733c66f43SYan Zheng 					ret = err;
289865b51a00SChris Mason 					goto done;
289965b51a00SChris Mason 				}
29005c680ed6SChris Mason 			}
2901459931ecSChris Mason 			if (!p->search_for_split)
2902f7c79f30SChris Mason 				unlock_up(p, level, lowest_unlock,
2903f7c79f30SChris Mason 					  min_write_lock_level, &write_lock_level);
290465b51a00SChris Mason 			goto done;
290565b51a00SChris Mason 		}
290665b51a00SChris Mason 	}
290765b51a00SChris Mason 	ret = 1;
290865b51a00SChris Mason done:
2909b4ce94deSChris Mason 	/*
2910b4ce94deSChris Mason 	 * we don't really know what they plan on doing with the path
2911b4ce94deSChris Mason 	 * from here on, so for now just mark it as blocking
2912b4ce94deSChris Mason 	 */
2913b9473439SChris Mason 	if (!p->leave_spinning)
2914b4ce94deSChris Mason 		btrfs_set_path_blocking(p);
29155f5bc6b1SFilipe Manana 	if (ret < 0 && !p->skip_release_on_error)
2916b3b4aa74SDavid Sterba 		btrfs_release_path(p);
2917be0e5c09SChris Mason 	return ret;
2918be0e5c09SChris Mason }
2919be0e5c09SChris Mason 
292074123bd7SChris Mason /*
29215d9e75c4SJan Schmidt  * Like btrfs_search_slot, this looks for a key in the given tree. It uses the
29225d9e75c4SJan Schmidt  * current state of the tree together with the operations recorded in the tree
29235d9e75c4SJan Schmidt  * modification log to search for the key in a previous version of this tree, as
29245d9e75c4SJan Schmidt  * denoted by the time_seq parameter.
29255d9e75c4SJan Schmidt  *
29265d9e75c4SJan Schmidt  * Naturally, there is no support for insert, delete or cow operations.
29275d9e75c4SJan Schmidt  *
29285d9e75c4SJan Schmidt  * The resulting path and return value will be set up as if we called
29295d9e75c4SJan Schmidt  * btrfs_search_slot at that point in time with ins_len and cow both set to 0.
29305d9e75c4SJan Schmidt  */
2931310712b2SOmar Sandoval int btrfs_search_old_slot(struct btrfs_root *root, const struct btrfs_key *key,
29325d9e75c4SJan Schmidt 			  struct btrfs_path *p, u64 time_seq)
29335d9e75c4SJan Schmidt {
29340b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
29355d9e75c4SJan Schmidt 	struct extent_buffer *b;
29365d9e75c4SJan Schmidt 	int slot;
29375d9e75c4SJan Schmidt 	int ret;
29385d9e75c4SJan Schmidt 	int err;
29395d9e75c4SJan Schmidt 	int level;
29405d9e75c4SJan Schmidt 	int lowest_unlock = 1;
29415d9e75c4SJan Schmidt 	u8 lowest_level = 0;
2942d4b4087cSJosef Bacik 	int prev_cmp = -1;
29435d9e75c4SJan Schmidt 
29445d9e75c4SJan Schmidt 	lowest_level = p->lowest_level;
29455d9e75c4SJan Schmidt 	WARN_ON(p->nodes[0] != NULL);
29465d9e75c4SJan Schmidt 
29475d9e75c4SJan Schmidt 	if (p->search_commit_root) {
29485d9e75c4SJan Schmidt 		BUG_ON(time_seq);
29495d9e75c4SJan Schmidt 		return btrfs_search_slot(NULL, root, key, p, 0, 0);
29505d9e75c4SJan Schmidt 	}
29515d9e75c4SJan Schmidt 
29525d9e75c4SJan Schmidt again:
29535d9e75c4SJan Schmidt 	b = get_old_root(root, time_seq);
29545d9e75c4SJan Schmidt 	level = btrfs_header_level(b);
29555d9e75c4SJan Schmidt 	p->locks[level] = BTRFS_READ_LOCK;
29565d9e75c4SJan Schmidt 
29575d9e75c4SJan Schmidt 	while (b) {
29585d9e75c4SJan Schmidt 		level = btrfs_header_level(b);
29595d9e75c4SJan Schmidt 		p->nodes[level] = b;
29605d9e75c4SJan Schmidt 		btrfs_clear_path_blocking(p, NULL, 0);
29615d9e75c4SJan Schmidt 
29625d9e75c4SJan Schmidt 		/*
29635d9e75c4SJan Schmidt 		 * we have a lock on b and as long as we aren't changing
29645d9e75c4SJan Schmidt 		 * the tree, there is no way to for the items in b to change.
29655d9e75c4SJan Schmidt 		 * It is safe to drop the lock on our parent before we
29665d9e75c4SJan Schmidt 		 * go through the expensive btree search on b.
29675d9e75c4SJan Schmidt 		 */
29685d9e75c4SJan Schmidt 		btrfs_unlock_up_safe(p, level + 1);
29695d9e75c4SJan Schmidt 
2970d4b4087cSJosef Bacik 		/*
297101327610SNicholas D Steeves 		 * Since we can unwind ebs we want to do a real search every
2972d4b4087cSJosef Bacik 		 * time.
2973d4b4087cSJosef Bacik 		 */
2974d4b4087cSJosef Bacik 		prev_cmp = -1;
2975d7396f07SFilipe David Borba Manana 		ret = key_search(b, key, level, &prev_cmp, &slot);
29765d9e75c4SJan Schmidt 
29775d9e75c4SJan Schmidt 		if (level != 0) {
29785d9e75c4SJan Schmidt 			int dec = 0;
29795d9e75c4SJan Schmidt 			if (ret && slot > 0) {
29805d9e75c4SJan Schmidt 				dec = 1;
29815d9e75c4SJan Schmidt 				slot -= 1;
29825d9e75c4SJan Schmidt 			}
29835d9e75c4SJan Schmidt 			p->slots[level] = slot;
29845d9e75c4SJan Schmidt 			unlock_up(p, level, lowest_unlock, 0, NULL);
29855d9e75c4SJan Schmidt 
29865d9e75c4SJan Schmidt 			if (level == lowest_level) {
29875d9e75c4SJan Schmidt 				if (dec)
29885d9e75c4SJan Schmidt 					p->slots[level]++;
29895d9e75c4SJan Schmidt 				goto done;
29905d9e75c4SJan Schmidt 			}
29915d9e75c4SJan Schmidt 
2992d07b8528SLiu Bo 			err = read_block_for_search(root, p, &b, level,
2993cda79c54SDavid Sterba 						    slot, key);
29945d9e75c4SJan Schmidt 			if (err == -EAGAIN)
29955d9e75c4SJan Schmidt 				goto again;
29965d9e75c4SJan Schmidt 			if (err) {
29975d9e75c4SJan Schmidt 				ret = err;
29985d9e75c4SJan Schmidt 				goto done;
29995d9e75c4SJan Schmidt 			}
30005d9e75c4SJan Schmidt 
30015d9e75c4SJan Schmidt 			level = btrfs_header_level(b);
3002f82c458aSChris Mason 			err = btrfs_tree_read_lock_atomic(b);
30035d9e75c4SJan Schmidt 			if (!err) {
30045d9e75c4SJan Schmidt 				btrfs_set_path_blocking(p);
30055d9e75c4SJan Schmidt 				btrfs_tree_read_lock(b);
30065d9e75c4SJan Schmidt 				btrfs_clear_path_blocking(p, b,
30075d9e75c4SJan Schmidt 							  BTRFS_READ_LOCK);
30085d9e75c4SJan Schmidt 			}
30090b246afaSJeff Mahoney 			b = tree_mod_log_rewind(fs_info, p, b, time_seq);
3010db7f3436SJosef Bacik 			if (!b) {
3011db7f3436SJosef Bacik 				ret = -ENOMEM;
3012db7f3436SJosef Bacik 				goto done;
3013db7f3436SJosef Bacik 			}
30145d9e75c4SJan Schmidt 			p->locks[level] = BTRFS_READ_LOCK;
30155d9e75c4SJan Schmidt 			p->nodes[level] = b;
30165d9e75c4SJan Schmidt 		} else {
30175d9e75c4SJan Schmidt 			p->slots[level] = slot;
30185d9e75c4SJan Schmidt 			unlock_up(p, level, lowest_unlock, 0, NULL);
30195d9e75c4SJan Schmidt 			goto done;
30205d9e75c4SJan Schmidt 		}
30215d9e75c4SJan Schmidt 	}
30225d9e75c4SJan Schmidt 	ret = 1;
30235d9e75c4SJan Schmidt done:
30245d9e75c4SJan Schmidt 	if (!p->leave_spinning)
30255d9e75c4SJan Schmidt 		btrfs_set_path_blocking(p);
30265d9e75c4SJan Schmidt 	if (ret < 0)
30275d9e75c4SJan Schmidt 		btrfs_release_path(p);
30285d9e75c4SJan Schmidt 
30295d9e75c4SJan Schmidt 	return ret;
30305d9e75c4SJan Schmidt }
30315d9e75c4SJan Schmidt 
30325d9e75c4SJan Schmidt /*
30332f38b3e1SArne Jansen  * helper to use instead of search slot if no exact match is needed but
30342f38b3e1SArne Jansen  * instead the next or previous item should be returned.
30352f38b3e1SArne Jansen  * When find_higher is true, the next higher item is returned, the next lower
30362f38b3e1SArne Jansen  * otherwise.
30372f38b3e1SArne Jansen  * When return_any and find_higher are both true, and no higher item is found,
30382f38b3e1SArne Jansen  * return the next lower instead.
30392f38b3e1SArne Jansen  * When return_any is true and find_higher is false, and no lower item is found,
30402f38b3e1SArne Jansen  * return the next higher instead.
30412f38b3e1SArne Jansen  * It returns 0 if any item is found, 1 if none is found (tree empty), and
30422f38b3e1SArne Jansen  * < 0 on error
30432f38b3e1SArne Jansen  */
30442f38b3e1SArne Jansen int btrfs_search_slot_for_read(struct btrfs_root *root,
3045310712b2SOmar Sandoval 			       const struct btrfs_key *key,
3046310712b2SOmar Sandoval 			       struct btrfs_path *p, int find_higher,
3047310712b2SOmar Sandoval 			       int return_any)
30482f38b3e1SArne Jansen {
30492f38b3e1SArne Jansen 	int ret;
30502f38b3e1SArne Jansen 	struct extent_buffer *leaf;
30512f38b3e1SArne Jansen 
30522f38b3e1SArne Jansen again:
30532f38b3e1SArne Jansen 	ret = btrfs_search_slot(NULL, root, key, p, 0, 0);
30542f38b3e1SArne Jansen 	if (ret <= 0)
30552f38b3e1SArne Jansen 		return ret;
30562f38b3e1SArne Jansen 	/*
30572f38b3e1SArne Jansen 	 * a return value of 1 means the path is at the position where the
30582f38b3e1SArne Jansen 	 * item should be inserted. Normally this is the next bigger item,
30592f38b3e1SArne Jansen 	 * but in case the previous item is the last in a leaf, path points
30602f38b3e1SArne Jansen 	 * to the first free slot in the previous leaf, i.e. at an invalid
30612f38b3e1SArne Jansen 	 * item.
30622f38b3e1SArne Jansen 	 */
30632f38b3e1SArne Jansen 	leaf = p->nodes[0];
30642f38b3e1SArne Jansen 
30652f38b3e1SArne Jansen 	if (find_higher) {
30662f38b3e1SArne Jansen 		if (p->slots[0] >= btrfs_header_nritems(leaf)) {
30672f38b3e1SArne Jansen 			ret = btrfs_next_leaf(root, p);
30682f38b3e1SArne Jansen 			if (ret <= 0)
30692f38b3e1SArne Jansen 				return ret;
30702f38b3e1SArne Jansen 			if (!return_any)
30712f38b3e1SArne Jansen 				return 1;
30722f38b3e1SArne Jansen 			/*
30732f38b3e1SArne Jansen 			 * no higher item found, return the next
30742f38b3e1SArne Jansen 			 * lower instead
30752f38b3e1SArne Jansen 			 */
30762f38b3e1SArne Jansen 			return_any = 0;
30772f38b3e1SArne Jansen 			find_higher = 0;
30782f38b3e1SArne Jansen 			btrfs_release_path(p);
30792f38b3e1SArne Jansen 			goto again;
30802f38b3e1SArne Jansen 		}
30812f38b3e1SArne Jansen 	} else {
30822f38b3e1SArne Jansen 		if (p->slots[0] == 0) {
30832f38b3e1SArne Jansen 			ret = btrfs_prev_leaf(root, p);
3084e6793769SArne Jansen 			if (ret < 0)
30852f38b3e1SArne Jansen 				return ret;
3086e6793769SArne Jansen 			if (!ret) {
308723c6bf6aSFilipe David Borba Manana 				leaf = p->nodes[0];
308823c6bf6aSFilipe David Borba Manana 				if (p->slots[0] == btrfs_header_nritems(leaf))
308923c6bf6aSFilipe David Borba Manana 					p->slots[0]--;
3090e6793769SArne Jansen 				return 0;
3091e6793769SArne Jansen 			}
30922f38b3e1SArne Jansen 			if (!return_any)
30932f38b3e1SArne Jansen 				return 1;
30942f38b3e1SArne Jansen 			/*
30952f38b3e1SArne Jansen 			 * no lower item found, return the next
30962f38b3e1SArne Jansen 			 * higher instead
30972f38b3e1SArne Jansen 			 */
30982f38b3e1SArne Jansen 			return_any = 0;
30992f38b3e1SArne Jansen 			find_higher = 1;
31002f38b3e1SArne Jansen 			btrfs_release_path(p);
31012f38b3e1SArne Jansen 			goto again;
3102e6793769SArne Jansen 		} else {
31032f38b3e1SArne Jansen 			--p->slots[0];
31042f38b3e1SArne Jansen 		}
31052f38b3e1SArne Jansen 	}
31062f38b3e1SArne Jansen 	return 0;
31072f38b3e1SArne Jansen }
31082f38b3e1SArne Jansen 
31092f38b3e1SArne Jansen /*
311074123bd7SChris Mason  * adjust the pointers going up the tree, starting at level
311174123bd7SChris Mason  * making sure the right key of each node is points to 'key'.
311274123bd7SChris Mason  * This is used after shifting pointers to the left, so it stops
311374123bd7SChris Mason  * fixing up pointers when a given leaf/node is not in slot 0 of the
311474123bd7SChris Mason  * higher levels
3115aa5d6bedSChris Mason  *
311674123bd7SChris Mason  */
3117b7a0365eSDaniel Dressler static void fixup_low_keys(struct btrfs_fs_info *fs_info,
3118b7a0365eSDaniel Dressler 			   struct btrfs_path *path,
31195f39d397SChris Mason 			   struct btrfs_disk_key *key, int level)
3120be0e5c09SChris Mason {
3121be0e5c09SChris Mason 	int i;
31225f39d397SChris Mason 	struct extent_buffer *t;
31230e82bcfeSDavid Sterba 	int ret;
31245f39d397SChris Mason 
3125234b63a0SChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
3126be0e5c09SChris Mason 		int tslot = path->slots[i];
31270e82bcfeSDavid Sterba 
3128eb60ceacSChris Mason 		if (!path->nodes[i])
3129be0e5c09SChris Mason 			break;
31305f39d397SChris Mason 		t = path->nodes[i];
31310e82bcfeSDavid Sterba 		ret = tree_mod_log_insert_key(t, tslot, MOD_LOG_KEY_REPLACE,
31320e82bcfeSDavid Sterba 				GFP_ATOMIC);
31330e82bcfeSDavid Sterba 		BUG_ON(ret < 0);
31345f39d397SChris Mason 		btrfs_set_node_key(t, key, tslot);
3135d6025579SChris Mason 		btrfs_mark_buffer_dirty(path->nodes[i]);
3136be0e5c09SChris Mason 		if (tslot != 0)
3137be0e5c09SChris Mason 			break;
3138be0e5c09SChris Mason 	}
3139be0e5c09SChris Mason }
3140be0e5c09SChris Mason 
314174123bd7SChris Mason /*
314231840ae1SZheng Yan  * update item key.
314331840ae1SZheng Yan  *
314431840ae1SZheng Yan  * This function isn't completely safe. It's the caller's responsibility
314531840ae1SZheng Yan  * that the new key won't break the order
314631840ae1SZheng Yan  */
3147b7a0365eSDaniel Dressler void btrfs_set_item_key_safe(struct btrfs_fs_info *fs_info,
3148b7a0365eSDaniel Dressler 			     struct btrfs_path *path,
3149310712b2SOmar Sandoval 			     const struct btrfs_key *new_key)
315031840ae1SZheng Yan {
315131840ae1SZheng Yan 	struct btrfs_disk_key disk_key;
315231840ae1SZheng Yan 	struct extent_buffer *eb;
315331840ae1SZheng Yan 	int slot;
315431840ae1SZheng Yan 
315531840ae1SZheng Yan 	eb = path->nodes[0];
315631840ae1SZheng Yan 	slot = path->slots[0];
315731840ae1SZheng Yan 	if (slot > 0) {
315831840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot - 1);
3159143bede5SJeff Mahoney 		BUG_ON(comp_keys(&disk_key, new_key) >= 0);
316031840ae1SZheng Yan 	}
316131840ae1SZheng Yan 	if (slot < btrfs_header_nritems(eb) - 1) {
316231840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot + 1);
3163143bede5SJeff Mahoney 		BUG_ON(comp_keys(&disk_key, new_key) <= 0);
316431840ae1SZheng Yan 	}
316531840ae1SZheng Yan 
316631840ae1SZheng Yan 	btrfs_cpu_key_to_disk(&disk_key, new_key);
316731840ae1SZheng Yan 	btrfs_set_item_key(eb, &disk_key, slot);
316831840ae1SZheng Yan 	btrfs_mark_buffer_dirty(eb);
316931840ae1SZheng Yan 	if (slot == 0)
3170b7a0365eSDaniel Dressler 		fixup_low_keys(fs_info, path, &disk_key, 1);
317131840ae1SZheng Yan }
317231840ae1SZheng Yan 
317331840ae1SZheng Yan /*
317474123bd7SChris Mason  * try to push data from one node into the next node left in the
317579f95c82SChris Mason  * tree.
3176aa5d6bedSChris Mason  *
3177aa5d6bedSChris Mason  * returns 0 if some ptrs were pushed left, < 0 if there was some horrible
3178aa5d6bedSChris Mason  * error, and > 0 if there was no room in the left hand block.
317974123bd7SChris Mason  */
318098ed5174SChris Mason static int push_node_left(struct btrfs_trans_handle *trans,
31812ff7e61eSJeff Mahoney 			  struct btrfs_fs_info *fs_info,
31822ff7e61eSJeff Mahoney 			  struct extent_buffer *dst,
3183971a1f66SChris Mason 			  struct extent_buffer *src, int empty)
3184be0e5c09SChris Mason {
3185be0e5c09SChris Mason 	int push_items = 0;
3186bb803951SChris Mason 	int src_nritems;
3187bb803951SChris Mason 	int dst_nritems;
3188aa5d6bedSChris Mason 	int ret = 0;
3189be0e5c09SChris Mason 
31905f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
31915f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
31920b246afaSJeff Mahoney 	push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
31937bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
31947bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
319554aa1f4dSChris Mason 
3196bce4eae9SChris Mason 	if (!empty && src_nritems <= 8)
3197971a1f66SChris Mason 		return 1;
3198971a1f66SChris Mason 
3199d397712bSChris Mason 	if (push_items <= 0)
3200be0e5c09SChris Mason 		return 1;
3201be0e5c09SChris Mason 
3202bce4eae9SChris Mason 	if (empty) {
3203971a1f66SChris Mason 		push_items = min(src_nritems, push_items);
3204bce4eae9SChris Mason 		if (push_items < src_nritems) {
3205bce4eae9SChris Mason 			/* leave at least 8 pointers in the node if
3206bce4eae9SChris Mason 			 * we aren't going to empty it
3207bce4eae9SChris Mason 			 */
3208bce4eae9SChris Mason 			if (src_nritems - push_items < 8) {
3209bce4eae9SChris Mason 				if (push_items <= 8)
3210bce4eae9SChris Mason 					return 1;
3211bce4eae9SChris Mason 				push_items -= 8;
3212bce4eae9SChris Mason 			}
3213bce4eae9SChris Mason 		}
3214bce4eae9SChris Mason 	} else
3215bce4eae9SChris Mason 		push_items = min(src_nritems - 8, push_items);
321679f95c82SChris Mason 
32170b246afaSJeff Mahoney 	ret = tree_mod_log_eb_copy(fs_info, dst, src, dst_nritems, 0,
321890f8d62eSJan Schmidt 				   push_items);
32195de865eeSFilipe David Borba Manana 	if (ret) {
322066642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
32215de865eeSFilipe David Borba Manana 		return ret;
32225de865eeSFilipe David Borba Manana 	}
32235f39d397SChris Mason 	copy_extent_buffer(dst, src,
32245f39d397SChris Mason 			   btrfs_node_key_ptr_offset(dst_nritems),
32255f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
3226123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
32275f39d397SChris Mason 
3228bb803951SChris Mason 	if (push_items < src_nritems) {
322957911b8bSJan Schmidt 		/*
3230bf1d3425SDavid Sterba 		 * Don't call tree_mod_log_insert_move here, key removal was
3231bf1d3425SDavid Sterba 		 * already fully logged by tree_mod_log_eb_copy above.
323257911b8bSJan Schmidt 		 */
32335f39d397SChris Mason 		memmove_extent_buffer(src, btrfs_node_key_ptr_offset(0),
32345f39d397SChris Mason 				      btrfs_node_key_ptr_offset(push_items),
3235e2fa7227SChris Mason 				      (src_nritems - push_items) *
3236123abc88SChris Mason 				      sizeof(struct btrfs_key_ptr));
3237bb803951SChris Mason 	}
32385f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
32395f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
32405f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
32415f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
324231840ae1SZheng Yan 
3243bb803951SChris Mason 	return ret;
3244be0e5c09SChris Mason }
3245be0e5c09SChris Mason 
324697571fd0SChris Mason /*
324779f95c82SChris Mason  * try to push data from one node into the next node right in the
324879f95c82SChris Mason  * tree.
324979f95c82SChris Mason  *
325079f95c82SChris Mason  * returns 0 if some ptrs were pushed, < 0 if there was some horrible
325179f95c82SChris Mason  * error, and > 0 if there was no room in the right hand block.
325279f95c82SChris Mason  *
325379f95c82SChris Mason  * this will  only push up to 1/2 the contents of the left node over
325479f95c82SChris Mason  */
32555f39d397SChris Mason static int balance_node_right(struct btrfs_trans_handle *trans,
32562ff7e61eSJeff Mahoney 			      struct btrfs_fs_info *fs_info,
32575f39d397SChris Mason 			      struct extent_buffer *dst,
32585f39d397SChris Mason 			      struct extent_buffer *src)
325979f95c82SChris Mason {
326079f95c82SChris Mason 	int push_items = 0;
326179f95c82SChris Mason 	int max_push;
326279f95c82SChris Mason 	int src_nritems;
326379f95c82SChris Mason 	int dst_nritems;
326479f95c82SChris Mason 	int ret = 0;
326579f95c82SChris Mason 
32667bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
32677bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
32687bb86316SChris Mason 
32695f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
32705f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
32710b246afaSJeff Mahoney 	push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
3272d397712bSChris Mason 	if (push_items <= 0)
327379f95c82SChris Mason 		return 1;
3274bce4eae9SChris Mason 
3275d397712bSChris Mason 	if (src_nritems < 4)
3276bce4eae9SChris Mason 		return 1;
327779f95c82SChris Mason 
327879f95c82SChris Mason 	max_push = src_nritems / 2 + 1;
327979f95c82SChris Mason 	/* don't try to empty the node */
3280d397712bSChris Mason 	if (max_push >= src_nritems)
328179f95c82SChris Mason 		return 1;
3282252c38f0SYan 
328379f95c82SChris Mason 	if (max_push < push_items)
328479f95c82SChris Mason 		push_items = max_push;
328579f95c82SChris Mason 
3286bf1d3425SDavid Sterba 	ret = tree_mod_log_insert_move(dst, push_items, 0, dst_nritems);
3287bf1d3425SDavid Sterba 	BUG_ON(ret < 0);
32885f39d397SChris Mason 	memmove_extent_buffer(dst, btrfs_node_key_ptr_offset(push_items),
32895f39d397SChris Mason 				      btrfs_node_key_ptr_offset(0),
32905f39d397SChris Mason 				      (dst_nritems) *
32915f39d397SChris Mason 				      sizeof(struct btrfs_key_ptr));
3292d6025579SChris Mason 
32930b246afaSJeff Mahoney 	ret = tree_mod_log_eb_copy(fs_info, dst, src, 0,
329490f8d62eSJan Schmidt 				   src_nritems - push_items, push_items);
32955de865eeSFilipe David Borba Manana 	if (ret) {
329666642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
32975de865eeSFilipe David Borba Manana 		return ret;
32985de865eeSFilipe David Borba Manana 	}
32995f39d397SChris Mason 	copy_extent_buffer(dst, src,
33005f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
33015f39d397SChris Mason 			   btrfs_node_key_ptr_offset(src_nritems - push_items),
3302123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
330379f95c82SChris Mason 
33045f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
33055f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
330679f95c82SChris Mason 
33075f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
33085f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
330931840ae1SZheng Yan 
331079f95c82SChris Mason 	return ret;
331179f95c82SChris Mason }
331279f95c82SChris Mason 
331379f95c82SChris Mason /*
331497571fd0SChris Mason  * helper function to insert a new root level in the tree.
331597571fd0SChris Mason  * A new node is allocated, and a single item is inserted to
331697571fd0SChris Mason  * point to the existing root
3317aa5d6bedSChris Mason  *
3318aa5d6bedSChris Mason  * returns zero on success or < 0 on failure.
331997571fd0SChris Mason  */
3320d397712bSChris Mason static noinline int insert_new_root(struct btrfs_trans_handle *trans,
33215f39d397SChris Mason 			   struct btrfs_root *root,
3322fdd99c72SLiu Bo 			   struct btrfs_path *path, int level)
332374123bd7SChris Mason {
33240b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
33257bb86316SChris Mason 	u64 lower_gen;
33265f39d397SChris Mason 	struct extent_buffer *lower;
33275f39d397SChris Mason 	struct extent_buffer *c;
3328925baeddSChris Mason 	struct extent_buffer *old;
33295f39d397SChris Mason 	struct btrfs_disk_key lower_key;
3330d9d19a01SDavid Sterba 	int ret;
33315c680ed6SChris Mason 
33325c680ed6SChris Mason 	BUG_ON(path->nodes[level]);
33335c680ed6SChris Mason 	BUG_ON(path->nodes[level-1] != root->node);
33345c680ed6SChris Mason 
33357bb86316SChris Mason 	lower = path->nodes[level-1];
33367bb86316SChris Mason 	if (level == 1)
33377bb86316SChris Mason 		btrfs_item_key(lower, &lower_key, 0);
33387bb86316SChris Mason 	else
33397bb86316SChris Mason 		btrfs_node_key(lower, &lower_key, 0);
33407bb86316SChris Mason 
33414d75f8a9SDavid Sterba 	c = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
33424d75f8a9SDavid Sterba 				   &lower_key, level, root->node->start, 0);
33435f39d397SChris Mason 	if (IS_ERR(c))
33445f39d397SChris Mason 		return PTR_ERR(c);
3345925baeddSChris Mason 
33460b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
3347f0486c68SYan, Zheng 
3348b159fa28SDavid Sterba 	memzero_extent_buffer(c, 0, sizeof(struct btrfs_header));
33495f39d397SChris Mason 	btrfs_set_header_nritems(c, 1);
33505f39d397SChris Mason 	btrfs_set_header_level(c, level);
3351db94535dSChris Mason 	btrfs_set_header_bytenr(c, c->start);
33525f39d397SChris Mason 	btrfs_set_header_generation(c, trans->transid);
33535d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(c, BTRFS_MIXED_BACKREF_REV);
33545f39d397SChris Mason 	btrfs_set_header_owner(c, root->root_key.objectid);
3355d5719762SChris Mason 
33560b246afaSJeff Mahoney 	write_extent_buffer_fsid(c, fs_info->fsid);
33570b246afaSJeff Mahoney 	write_extent_buffer_chunk_tree_uuid(c, fs_info->chunk_tree_uuid);
3358e17cade2SChris Mason 
33595f39d397SChris Mason 	btrfs_set_node_key(c, &lower_key, 0);
3360db94535dSChris Mason 	btrfs_set_node_blockptr(c, 0, lower->start);
33617bb86316SChris Mason 	lower_gen = btrfs_header_generation(lower);
336231840ae1SZheng Yan 	WARN_ON(lower_gen != trans->transid);
33637bb86316SChris Mason 
33647bb86316SChris Mason 	btrfs_set_node_ptr_generation(c, 0, lower_gen);
33655f39d397SChris Mason 
33665f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
3367d5719762SChris Mason 
3368925baeddSChris Mason 	old = root->node;
3369d9d19a01SDavid Sterba 	ret = tree_mod_log_insert_root(root->node, c, 0);
3370d9d19a01SDavid Sterba 	BUG_ON(ret < 0);
3371240f62c8SChris Mason 	rcu_assign_pointer(root->node, c);
3372925baeddSChris Mason 
3373925baeddSChris Mason 	/* the super has an extra ref to root->node */
3374925baeddSChris Mason 	free_extent_buffer(old);
3375925baeddSChris Mason 
33760b86a832SChris Mason 	add_root_to_dirty_list(root);
33775f39d397SChris Mason 	extent_buffer_get(c);
33785f39d397SChris Mason 	path->nodes[level] = c;
337995449a16Schandan 	path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
338074123bd7SChris Mason 	path->slots[level] = 0;
338174123bd7SChris Mason 	return 0;
338274123bd7SChris Mason }
33835c680ed6SChris Mason 
33845c680ed6SChris Mason /*
33855c680ed6SChris Mason  * worker function to insert a single pointer in a node.
33865c680ed6SChris Mason  * the node should have enough room for the pointer already
338797571fd0SChris Mason  *
33885c680ed6SChris Mason  * slot and level indicate where you want the key to go, and
33895c680ed6SChris Mason  * blocknr is the block the key points to.
33905c680ed6SChris Mason  */
3391143bede5SJeff Mahoney static void insert_ptr(struct btrfs_trans_handle *trans,
33922ff7e61eSJeff Mahoney 		       struct btrfs_fs_info *fs_info, struct btrfs_path *path,
3393143bede5SJeff Mahoney 		       struct btrfs_disk_key *key, u64 bytenr,
3394c3e06965SJan Schmidt 		       int slot, int level)
33955c680ed6SChris Mason {
33965f39d397SChris Mason 	struct extent_buffer *lower;
33975c680ed6SChris Mason 	int nritems;
3398f3ea38daSJan Schmidt 	int ret;
33995c680ed6SChris Mason 
34005c680ed6SChris Mason 	BUG_ON(!path->nodes[level]);
3401f0486c68SYan, Zheng 	btrfs_assert_tree_locked(path->nodes[level]);
34025f39d397SChris Mason 	lower = path->nodes[level];
34035f39d397SChris Mason 	nritems = btrfs_header_nritems(lower);
3404c293498bSStoyan Gaydarov 	BUG_ON(slot > nritems);
34050b246afaSJeff Mahoney 	BUG_ON(nritems == BTRFS_NODEPTRS_PER_BLOCK(fs_info));
340674123bd7SChris Mason 	if (slot != nritems) {
3407bf1d3425SDavid Sterba 		if (level) {
3408bf1d3425SDavid Sterba 			ret = tree_mod_log_insert_move(lower, slot + 1, slot,
3409a446a979SDavid Sterba 					nritems - slot);
3410bf1d3425SDavid Sterba 			BUG_ON(ret < 0);
3411bf1d3425SDavid Sterba 		}
34125f39d397SChris Mason 		memmove_extent_buffer(lower,
34135f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot + 1),
34145f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot),
3415123abc88SChris Mason 			      (nritems - slot) * sizeof(struct btrfs_key_ptr));
341674123bd7SChris Mason 	}
3417c3e06965SJan Schmidt 	if (level) {
3418e09c2efeSDavid Sterba 		ret = tree_mod_log_insert_key(lower, slot, MOD_LOG_KEY_ADD,
3419e09c2efeSDavid Sterba 				GFP_NOFS);
3420f3ea38daSJan Schmidt 		BUG_ON(ret < 0);
3421f3ea38daSJan Schmidt 	}
34225f39d397SChris Mason 	btrfs_set_node_key(lower, key, slot);
3423db94535dSChris Mason 	btrfs_set_node_blockptr(lower, slot, bytenr);
342474493f7aSChris Mason 	WARN_ON(trans->transid == 0);
342574493f7aSChris Mason 	btrfs_set_node_ptr_generation(lower, slot, trans->transid);
34265f39d397SChris Mason 	btrfs_set_header_nritems(lower, nritems + 1);
34275f39d397SChris Mason 	btrfs_mark_buffer_dirty(lower);
342874123bd7SChris Mason }
342974123bd7SChris Mason 
343097571fd0SChris Mason /*
343197571fd0SChris Mason  * split the node at the specified level in path in two.
343297571fd0SChris Mason  * The path is corrected to point to the appropriate node after the split
343397571fd0SChris Mason  *
343497571fd0SChris Mason  * Before splitting this tries to make some room in the node by pushing
343597571fd0SChris Mason  * left and right, if either one works, it returns right away.
3436aa5d6bedSChris Mason  *
3437aa5d6bedSChris Mason  * returns 0 on success and < 0 on failure
343897571fd0SChris Mason  */
3439e02119d5SChris Mason static noinline int split_node(struct btrfs_trans_handle *trans,
3440e02119d5SChris Mason 			       struct btrfs_root *root,
3441e02119d5SChris Mason 			       struct btrfs_path *path, int level)
3442be0e5c09SChris Mason {
34430b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
34445f39d397SChris Mason 	struct extent_buffer *c;
34455f39d397SChris Mason 	struct extent_buffer *split;
34465f39d397SChris Mason 	struct btrfs_disk_key disk_key;
3447be0e5c09SChris Mason 	int mid;
34485c680ed6SChris Mason 	int ret;
34497518a238SChris Mason 	u32 c_nritems;
3450be0e5c09SChris Mason 
34515f39d397SChris Mason 	c = path->nodes[level];
34527bb86316SChris Mason 	WARN_ON(btrfs_header_generation(c) != trans->transid);
34535f39d397SChris Mason 	if (c == root->node) {
3454d9abbf1cSJan Schmidt 		/*
345590f8d62eSJan Schmidt 		 * trying to split the root, lets make a new one
345690f8d62eSJan Schmidt 		 *
3457fdd99c72SLiu Bo 		 * tree mod log: We don't log_removal old root in
345890f8d62eSJan Schmidt 		 * insert_new_root, because that root buffer will be kept as a
345990f8d62eSJan Schmidt 		 * normal node. We are going to log removal of half of the
346090f8d62eSJan Schmidt 		 * elements below with tree_mod_log_eb_copy. We're holding a
346190f8d62eSJan Schmidt 		 * tree lock on the buffer, which is why we cannot race with
346290f8d62eSJan Schmidt 		 * other tree_mod_log users.
3463d9abbf1cSJan Schmidt 		 */
3464fdd99c72SLiu Bo 		ret = insert_new_root(trans, root, path, level + 1);
34655c680ed6SChris Mason 		if (ret)
34665c680ed6SChris Mason 			return ret;
3467b3612421SChris Mason 	} else {
3468e66f709bSChris Mason 		ret = push_nodes_for_insert(trans, root, path, level);
34695f39d397SChris Mason 		c = path->nodes[level];
34705f39d397SChris Mason 		if (!ret && btrfs_header_nritems(c) <
34710b246afaSJeff Mahoney 		    BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3)
3472e66f709bSChris Mason 			return 0;
347354aa1f4dSChris Mason 		if (ret < 0)
347454aa1f4dSChris Mason 			return ret;
34755c680ed6SChris Mason 	}
3476e66f709bSChris Mason 
34775f39d397SChris Mason 	c_nritems = btrfs_header_nritems(c);
34785d4f98a2SYan Zheng 	mid = (c_nritems + 1) / 2;
34795d4f98a2SYan Zheng 	btrfs_node_key(c, &disk_key, mid);
34807bb86316SChris Mason 
34814d75f8a9SDavid Sterba 	split = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
34825581a51aSJan Schmidt 			&disk_key, level, c->start, 0);
34835f39d397SChris Mason 	if (IS_ERR(split))
34845f39d397SChris Mason 		return PTR_ERR(split);
348554aa1f4dSChris Mason 
34860b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
3487f0486c68SYan, Zheng 
3488b159fa28SDavid Sterba 	memzero_extent_buffer(split, 0, sizeof(struct btrfs_header));
34895f39d397SChris Mason 	btrfs_set_header_level(split, btrfs_header_level(c));
3490db94535dSChris Mason 	btrfs_set_header_bytenr(split, split->start);
34915f39d397SChris Mason 	btrfs_set_header_generation(split, trans->transid);
34925d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(split, BTRFS_MIXED_BACKREF_REV);
34935f39d397SChris Mason 	btrfs_set_header_owner(split, root->root_key.objectid);
34940b246afaSJeff Mahoney 	write_extent_buffer_fsid(split, fs_info->fsid);
34950b246afaSJeff Mahoney 	write_extent_buffer_chunk_tree_uuid(split, fs_info->chunk_tree_uuid);
34965f39d397SChris Mason 
34970b246afaSJeff Mahoney 	ret = tree_mod_log_eb_copy(fs_info, split, c, 0, mid, c_nritems - mid);
34985de865eeSFilipe David Borba Manana 	if (ret) {
349966642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
35005de865eeSFilipe David Borba Manana 		return ret;
35015de865eeSFilipe David Borba Manana 	}
35025f39d397SChris Mason 	copy_extent_buffer(split, c,
35035f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
35045f39d397SChris Mason 			   btrfs_node_key_ptr_offset(mid),
3505123abc88SChris Mason 			   (c_nritems - mid) * sizeof(struct btrfs_key_ptr));
35065f39d397SChris Mason 	btrfs_set_header_nritems(split, c_nritems - mid);
35075f39d397SChris Mason 	btrfs_set_header_nritems(c, mid);
3508aa5d6bedSChris Mason 	ret = 0;
3509aa5d6bedSChris Mason 
35105f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
35115f39d397SChris Mason 	btrfs_mark_buffer_dirty(split);
35125f39d397SChris Mason 
35132ff7e61eSJeff Mahoney 	insert_ptr(trans, fs_info, path, &disk_key, split->start,
3514c3e06965SJan Schmidt 		   path->slots[level + 1] + 1, level + 1);
3515aa5d6bedSChris Mason 
35165de08d7dSChris Mason 	if (path->slots[level] >= mid) {
35175c680ed6SChris Mason 		path->slots[level] -= mid;
3518925baeddSChris Mason 		btrfs_tree_unlock(c);
35195f39d397SChris Mason 		free_extent_buffer(c);
35205f39d397SChris Mason 		path->nodes[level] = split;
35215c680ed6SChris Mason 		path->slots[level + 1] += 1;
3522eb60ceacSChris Mason 	} else {
3523925baeddSChris Mason 		btrfs_tree_unlock(split);
35245f39d397SChris Mason 		free_extent_buffer(split);
3525be0e5c09SChris Mason 	}
3526aa5d6bedSChris Mason 	return ret;
3527be0e5c09SChris Mason }
3528be0e5c09SChris Mason 
352974123bd7SChris Mason /*
353074123bd7SChris Mason  * how many bytes are required to store the items in a leaf.  start
353174123bd7SChris Mason  * and nr indicate which items in the leaf to check.  This totals up the
353274123bd7SChris Mason  * space used both by the item structs and the item data
353374123bd7SChris Mason  */
35345f39d397SChris Mason static int leaf_space_used(struct extent_buffer *l, int start, int nr)
3535be0e5c09SChris Mason {
353641be1f3bSJosef Bacik 	struct btrfs_item *start_item;
353741be1f3bSJosef Bacik 	struct btrfs_item *end_item;
353841be1f3bSJosef Bacik 	struct btrfs_map_token token;
3539be0e5c09SChris Mason 	int data_len;
35405f39d397SChris Mason 	int nritems = btrfs_header_nritems(l);
3541d4dbff95SChris Mason 	int end = min(nritems, start + nr) - 1;
3542be0e5c09SChris Mason 
3543be0e5c09SChris Mason 	if (!nr)
3544be0e5c09SChris Mason 		return 0;
354541be1f3bSJosef Bacik 	btrfs_init_map_token(&token);
3546dd3cc16bSRoss Kirk 	start_item = btrfs_item_nr(start);
3547dd3cc16bSRoss Kirk 	end_item = btrfs_item_nr(end);
354841be1f3bSJosef Bacik 	data_len = btrfs_token_item_offset(l, start_item, &token) +
354941be1f3bSJosef Bacik 		btrfs_token_item_size(l, start_item, &token);
355041be1f3bSJosef Bacik 	data_len = data_len - btrfs_token_item_offset(l, end_item, &token);
35510783fcfcSChris Mason 	data_len += sizeof(struct btrfs_item) * nr;
3552d4dbff95SChris Mason 	WARN_ON(data_len < 0);
3553be0e5c09SChris Mason 	return data_len;
3554be0e5c09SChris Mason }
3555be0e5c09SChris Mason 
355674123bd7SChris Mason /*
3557d4dbff95SChris Mason  * The space between the end of the leaf items and
3558d4dbff95SChris Mason  * the start of the leaf data.  IOW, how much room
3559d4dbff95SChris Mason  * the leaf has left for both items and data
3560d4dbff95SChris Mason  */
35612ff7e61eSJeff Mahoney noinline int btrfs_leaf_free_space(struct btrfs_fs_info *fs_info,
3562e02119d5SChris Mason 				   struct extent_buffer *leaf)
3563d4dbff95SChris Mason {
35645f39d397SChris Mason 	int nritems = btrfs_header_nritems(leaf);
35655f39d397SChris Mason 	int ret;
35660b246afaSJeff Mahoney 
35670b246afaSJeff Mahoney 	ret = BTRFS_LEAF_DATA_SIZE(fs_info) - leaf_space_used(leaf, 0, nritems);
35685f39d397SChris Mason 	if (ret < 0) {
35690b246afaSJeff Mahoney 		btrfs_crit(fs_info,
3570efe120a0SFrank Holton 			   "leaf free space ret %d, leaf data size %lu, used %d nritems %d",
3571da17066cSJeff Mahoney 			   ret,
35720b246afaSJeff Mahoney 			   (unsigned long) BTRFS_LEAF_DATA_SIZE(fs_info),
35735f39d397SChris Mason 			   leaf_space_used(leaf, 0, nritems), nritems);
35745f39d397SChris Mason 	}
35755f39d397SChris Mason 	return ret;
3576d4dbff95SChris Mason }
3577d4dbff95SChris Mason 
357899d8f83cSChris Mason /*
357999d8f83cSChris Mason  * min slot controls the lowest index we're willing to push to the
358099d8f83cSChris Mason  * right.  We'll push up to and including min_slot, but no lower
358199d8f83cSChris Mason  */
35821e47eef2SDavid Sterba static noinline int __push_leaf_right(struct btrfs_fs_info *fs_info,
358344871b1bSChris Mason 				      struct btrfs_path *path,
358444871b1bSChris Mason 				      int data_size, int empty,
358544871b1bSChris Mason 				      struct extent_buffer *right,
358699d8f83cSChris Mason 				      int free_space, u32 left_nritems,
358799d8f83cSChris Mason 				      u32 min_slot)
358800ec4c51SChris Mason {
35895f39d397SChris Mason 	struct extent_buffer *left = path->nodes[0];
359044871b1bSChris Mason 	struct extent_buffer *upper = path->nodes[1];
3591cfed81a0SChris Mason 	struct btrfs_map_token token;
35925f39d397SChris Mason 	struct btrfs_disk_key disk_key;
359300ec4c51SChris Mason 	int slot;
359434a38218SChris Mason 	u32 i;
359500ec4c51SChris Mason 	int push_space = 0;
359600ec4c51SChris Mason 	int push_items = 0;
35970783fcfcSChris Mason 	struct btrfs_item *item;
359834a38218SChris Mason 	u32 nr;
35997518a238SChris Mason 	u32 right_nritems;
36005f39d397SChris Mason 	u32 data_end;
3601db94535dSChris Mason 	u32 this_item_size;
360200ec4c51SChris Mason 
3603cfed81a0SChris Mason 	btrfs_init_map_token(&token);
3604cfed81a0SChris Mason 
360534a38218SChris Mason 	if (empty)
360634a38218SChris Mason 		nr = 0;
360734a38218SChris Mason 	else
360899d8f83cSChris Mason 		nr = max_t(u32, 1, min_slot);
360934a38218SChris Mason 
361031840ae1SZheng Yan 	if (path->slots[0] >= left_nritems)
361187b29b20SYan Zheng 		push_space += data_size;
361231840ae1SZheng Yan 
361344871b1bSChris Mason 	slot = path->slots[1];
361434a38218SChris Mason 	i = left_nritems - 1;
361534a38218SChris Mason 	while (i >= nr) {
3616dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
3617db94535dSChris Mason 
361831840ae1SZheng Yan 		if (!empty && push_items > 0) {
361931840ae1SZheng Yan 			if (path->slots[0] > i)
362031840ae1SZheng Yan 				break;
362131840ae1SZheng Yan 			if (path->slots[0] == i) {
36222ff7e61eSJeff Mahoney 				int space = btrfs_leaf_free_space(fs_info, left);
362331840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
362431840ae1SZheng Yan 					break;
362531840ae1SZheng Yan 			}
362631840ae1SZheng Yan 		}
362731840ae1SZheng Yan 
362800ec4c51SChris Mason 		if (path->slots[0] == i)
362987b29b20SYan Zheng 			push_space += data_size;
3630db94535dSChris Mason 
3631db94535dSChris Mason 		this_item_size = btrfs_item_size(left, item);
3632db94535dSChris Mason 		if (this_item_size + sizeof(*item) + push_space > free_space)
363300ec4c51SChris Mason 			break;
363431840ae1SZheng Yan 
363500ec4c51SChris Mason 		push_items++;
3636db94535dSChris Mason 		push_space += this_item_size + sizeof(*item);
363734a38218SChris Mason 		if (i == 0)
363834a38218SChris Mason 			break;
363934a38218SChris Mason 		i--;
3640db94535dSChris Mason 	}
36415f39d397SChris Mason 
3642925baeddSChris Mason 	if (push_items == 0)
3643925baeddSChris Mason 		goto out_unlock;
36445f39d397SChris Mason 
36456c1500f2SJulia Lawall 	WARN_ON(!empty && push_items == left_nritems);
36465f39d397SChris Mason 
364700ec4c51SChris Mason 	/* push left to right */
36485f39d397SChris Mason 	right_nritems = btrfs_header_nritems(right);
364934a38218SChris Mason 
36505f39d397SChris Mason 	push_space = btrfs_item_end_nr(left, left_nritems - push_items);
36512ff7e61eSJeff Mahoney 	push_space -= leaf_data_end(fs_info, left);
36525f39d397SChris Mason 
365300ec4c51SChris Mason 	/* make room in the right data area */
36542ff7e61eSJeff Mahoney 	data_end = leaf_data_end(fs_info, right);
36555f39d397SChris Mason 	memmove_extent_buffer(right,
36563d9ec8c4SNikolay Borisov 			      BTRFS_LEAF_DATA_OFFSET + data_end - push_space,
36573d9ec8c4SNikolay Borisov 			      BTRFS_LEAF_DATA_OFFSET + data_end,
36580b246afaSJeff Mahoney 			      BTRFS_LEAF_DATA_SIZE(fs_info) - data_end);
36595f39d397SChris Mason 
366000ec4c51SChris Mason 	/* copy from the left data area */
36613d9ec8c4SNikolay Borisov 	copy_extent_buffer(right, left, BTRFS_LEAF_DATA_OFFSET +
36620b246afaSJeff Mahoney 		     BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
36633d9ec8c4SNikolay Borisov 		     BTRFS_LEAF_DATA_OFFSET + leaf_data_end(fs_info, left),
3664d6025579SChris Mason 		     push_space);
36655f39d397SChris Mason 
36665f39d397SChris Mason 	memmove_extent_buffer(right, btrfs_item_nr_offset(push_items),
36675f39d397SChris Mason 			      btrfs_item_nr_offset(0),
36680783fcfcSChris Mason 			      right_nritems * sizeof(struct btrfs_item));
36695f39d397SChris Mason 
367000ec4c51SChris Mason 	/* copy the items from left to right */
36715f39d397SChris Mason 	copy_extent_buffer(right, left, btrfs_item_nr_offset(0),
36725f39d397SChris Mason 		   btrfs_item_nr_offset(left_nritems - push_items),
36730783fcfcSChris Mason 		   push_items * sizeof(struct btrfs_item));
367400ec4c51SChris Mason 
367500ec4c51SChris Mason 	/* update the item pointers */
36767518a238SChris Mason 	right_nritems += push_items;
36775f39d397SChris Mason 	btrfs_set_header_nritems(right, right_nritems);
36780b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
36797518a238SChris Mason 	for (i = 0; i < right_nritems; i++) {
3680dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
3681cfed81a0SChris Mason 		push_space -= btrfs_token_item_size(right, item, &token);
3682cfed81a0SChris Mason 		btrfs_set_token_item_offset(right, item, push_space, &token);
3683db94535dSChris Mason 	}
3684db94535dSChris Mason 
36857518a238SChris Mason 	left_nritems -= push_items;
36865f39d397SChris Mason 	btrfs_set_header_nritems(left, left_nritems);
368700ec4c51SChris Mason 
368834a38218SChris Mason 	if (left_nritems)
36895f39d397SChris Mason 		btrfs_mark_buffer_dirty(left);
3690f0486c68SYan, Zheng 	else
36917c302b49SDavid Sterba 		clean_tree_block(fs_info, left);
3692f0486c68SYan, Zheng 
36935f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
3694a429e513SChris Mason 
36955f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
36965f39d397SChris Mason 	btrfs_set_node_key(upper, &disk_key, slot + 1);
3697d6025579SChris Mason 	btrfs_mark_buffer_dirty(upper);
369802217ed2SChris Mason 
369900ec4c51SChris Mason 	/* then fixup the leaf pointer in the path */
37007518a238SChris Mason 	if (path->slots[0] >= left_nritems) {
37017518a238SChris Mason 		path->slots[0] -= left_nritems;
3702925baeddSChris Mason 		if (btrfs_header_nritems(path->nodes[0]) == 0)
37037c302b49SDavid Sterba 			clean_tree_block(fs_info, path->nodes[0]);
3704925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
37055f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
37065f39d397SChris Mason 		path->nodes[0] = right;
370700ec4c51SChris Mason 		path->slots[1] += 1;
370800ec4c51SChris Mason 	} else {
3709925baeddSChris Mason 		btrfs_tree_unlock(right);
37105f39d397SChris Mason 		free_extent_buffer(right);
371100ec4c51SChris Mason 	}
371200ec4c51SChris Mason 	return 0;
3713925baeddSChris Mason 
3714925baeddSChris Mason out_unlock:
3715925baeddSChris Mason 	btrfs_tree_unlock(right);
3716925baeddSChris Mason 	free_extent_buffer(right);
3717925baeddSChris Mason 	return 1;
371800ec4c51SChris Mason }
3719925baeddSChris Mason 
372000ec4c51SChris Mason /*
372144871b1bSChris Mason  * push some data in the path leaf to the right, trying to free up at
372274123bd7SChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
372344871b1bSChris Mason  *
372444871b1bSChris Mason  * returns 1 if the push failed because the other node didn't have enough
372544871b1bSChris Mason  * room, 0 if everything worked out and < 0 if there were major errors.
372699d8f83cSChris Mason  *
372799d8f83cSChris Mason  * this will push starting from min_slot to the end of the leaf.  It won't
372899d8f83cSChris Mason  * push any slot lower than min_slot
372974123bd7SChris Mason  */
373044871b1bSChris Mason static int push_leaf_right(struct btrfs_trans_handle *trans, struct btrfs_root
373199d8f83cSChris Mason 			   *root, struct btrfs_path *path,
373299d8f83cSChris Mason 			   int min_data_size, int data_size,
373399d8f83cSChris Mason 			   int empty, u32 min_slot)
3734be0e5c09SChris Mason {
37352ff7e61eSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
373644871b1bSChris Mason 	struct extent_buffer *left = path->nodes[0];
373744871b1bSChris Mason 	struct extent_buffer *right;
373844871b1bSChris Mason 	struct extent_buffer *upper;
373944871b1bSChris Mason 	int slot;
374044871b1bSChris Mason 	int free_space;
374144871b1bSChris Mason 	u32 left_nritems;
374244871b1bSChris Mason 	int ret;
374344871b1bSChris Mason 
374444871b1bSChris Mason 	if (!path->nodes[1])
374544871b1bSChris Mason 		return 1;
374644871b1bSChris Mason 
374744871b1bSChris Mason 	slot = path->slots[1];
374844871b1bSChris Mason 	upper = path->nodes[1];
374944871b1bSChris Mason 	if (slot >= btrfs_header_nritems(upper) - 1)
375044871b1bSChris Mason 		return 1;
375144871b1bSChris Mason 
375244871b1bSChris Mason 	btrfs_assert_tree_locked(path->nodes[1]);
375344871b1bSChris Mason 
37542ff7e61eSJeff Mahoney 	right = read_node_slot(fs_info, upper, slot + 1);
3755fb770ae4SLiu Bo 	/*
3756fb770ae4SLiu Bo 	 * slot + 1 is not valid or we fail to read the right node,
3757fb770ae4SLiu Bo 	 * no big deal, just return.
3758fb770ae4SLiu Bo 	 */
3759fb770ae4SLiu Bo 	if (IS_ERR(right))
376091ca338dSTsutomu Itoh 		return 1;
376191ca338dSTsutomu Itoh 
376244871b1bSChris Mason 	btrfs_tree_lock(right);
376344871b1bSChris Mason 	btrfs_set_lock_blocking(right);
376444871b1bSChris Mason 
37652ff7e61eSJeff Mahoney 	free_space = btrfs_leaf_free_space(fs_info, right);
376644871b1bSChris Mason 	if (free_space < data_size)
376744871b1bSChris Mason 		goto out_unlock;
376844871b1bSChris Mason 
376944871b1bSChris Mason 	/* cow and double check */
377044871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, right, upper,
377144871b1bSChris Mason 			      slot + 1, &right);
377244871b1bSChris Mason 	if (ret)
377344871b1bSChris Mason 		goto out_unlock;
377444871b1bSChris Mason 
37752ff7e61eSJeff Mahoney 	free_space = btrfs_leaf_free_space(fs_info, right);
377644871b1bSChris Mason 	if (free_space < data_size)
377744871b1bSChris Mason 		goto out_unlock;
377844871b1bSChris Mason 
377944871b1bSChris Mason 	left_nritems = btrfs_header_nritems(left);
378044871b1bSChris Mason 	if (left_nritems == 0)
378144871b1bSChris Mason 		goto out_unlock;
378244871b1bSChris Mason 
37832ef1fed2SFilipe David Borba Manana 	if (path->slots[0] == left_nritems && !empty) {
37842ef1fed2SFilipe David Borba Manana 		/* Key greater than all keys in the leaf, right neighbor has
37852ef1fed2SFilipe David Borba Manana 		 * enough room for it and we're not emptying our leaf to delete
37862ef1fed2SFilipe David Borba Manana 		 * it, therefore use right neighbor to insert the new item and
37872ef1fed2SFilipe David Borba Manana 		 * no need to touch/dirty our left leaft. */
37882ef1fed2SFilipe David Borba Manana 		btrfs_tree_unlock(left);
37892ef1fed2SFilipe David Borba Manana 		free_extent_buffer(left);
37902ef1fed2SFilipe David Borba Manana 		path->nodes[0] = right;
37912ef1fed2SFilipe David Borba Manana 		path->slots[0] = 0;
37922ef1fed2SFilipe David Borba Manana 		path->slots[1]++;
37932ef1fed2SFilipe David Borba Manana 		return 0;
37942ef1fed2SFilipe David Borba Manana 	}
37952ef1fed2SFilipe David Borba Manana 
37961e47eef2SDavid Sterba 	return __push_leaf_right(fs_info, path, min_data_size, empty,
379799d8f83cSChris Mason 				right, free_space, left_nritems, min_slot);
379844871b1bSChris Mason out_unlock:
379944871b1bSChris Mason 	btrfs_tree_unlock(right);
380044871b1bSChris Mason 	free_extent_buffer(right);
380144871b1bSChris Mason 	return 1;
380244871b1bSChris Mason }
380344871b1bSChris Mason 
380444871b1bSChris Mason /*
380544871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
380644871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
380799d8f83cSChris Mason  *
380899d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
380999d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us do all the
381099d8f83cSChris Mason  * items
381144871b1bSChris Mason  */
381266cb7ddbSDavid Sterba static noinline int __push_leaf_left(struct btrfs_fs_info *fs_info,
381344871b1bSChris Mason 				     struct btrfs_path *path, int data_size,
381444871b1bSChris Mason 				     int empty, struct extent_buffer *left,
381599d8f83cSChris Mason 				     int free_space, u32 right_nritems,
381699d8f83cSChris Mason 				     u32 max_slot)
381744871b1bSChris Mason {
38185f39d397SChris Mason 	struct btrfs_disk_key disk_key;
38195f39d397SChris Mason 	struct extent_buffer *right = path->nodes[0];
3820be0e5c09SChris Mason 	int i;
3821be0e5c09SChris Mason 	int push_space = 0;
3822be0e5c09SChris Mason 	int push_items = 0;
38230783fcfcSChris Mason 	struct btrfs_item *item;
38247518a238SChris Mason 	u32 old_left_nritems;
382534a38218SChris Mason 	u32 nr;
3826aa5d6bedSChris Mason 	int ret = 0;
3827db94535dSChris Mason 	u32 this_item_size;
3828db94535dSChris Mason 	u32 old_left_item_size;
3829cfed81a0SChris Mason 	struct btrfs_map_token token;
3830cfed81a0SChris Mason 
3831cfed81a0SChris Mason 	btrfs_init_map_token(&token);
3832be0e5c09SChris Mason 
383334a38218SChris Mason 	if (empty)
383499d8f83cSChris Mason 		nr = min(right_nritems, max_slot);
383534a38218SChris Mason 	else
383699d8f83cSChris Mason 		nr = min(right_nritems - 1, max_slot);
383734a38218SChris Mason 
383834a38218SChris Mason 	for (i = 0; i < nr; i++) {
3839dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
3840db94535dSChris Mason 
384131840ae1SZheng Yan 		if (!empty && push_items > 0) {
384231840ae1SZheng Yan 			if (path->slots[0] < i)
384331840ae1SZheng Yan 				break;
384431840ae1SZheng Yan 			if (path->slots[0] == i) {
38452ff7e61eSJeff Mahoney 				int space = btrfs_leaf_free_space(fs_info, right);
384631840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
384731840ae1SZheng Yan 					break;
384831840ae1SZheng Yan 			}
384931840ae1SZheng Yan 		}
385031840ae1SZheng Yan 
3851be0e5c09SChris Mason 		if (path->slots[0] == i)
385287b29b20SYan Zheng 			push_space += data_size;
3853db94535dSChris Mason 
3854db94535dSChris Mason 		this_item_size = btrfs_item_size(right, item);
3855db94535dSChris Mason 		if (this_item_size + sizeof(*item) + push_space > free_space)
3856be0e5c09SChris Mason 			break;
3857db94535dSChris Mason 
3858be0e5c09SChris Mason 		push_items++;
3859db94535dSChris Mason 		push_space += this_item_size + sizeof(*item);
3860be0e5c09SChris Mason 	}
3861db94535dSChris Mason 
3862be0e5c09SChris Mason 	if (push_items == 0) {
3863925baeddSChris Mason 		ret = 1;
3864925baeddSChris Mason 		goto out;
3865be0e5c09SChris Mason 	}
3866fae7f21cSDulshani Gunawardhana 	WARN_ON(!empty && push_items == btrfs_header_nritems(right));
38675f39d397SChris Mason 
3868be0e5c09SChris Mason 	/* push data from right to left */
38695f39d397SChris Mason 	copy_extent_buffer(left, right,
38705f39d397SChris Mason 			   btrfs_item_nr_offset(btrfs_header_nritems(left)),
38715f39d397SChris Mason 			   btrfs_item_nr_offset(0),
38725f39d397SChris Mason 			   push_items * sizeof(struct btrfs_item));
38735f39d397SChris Mason 
38740b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info) -
38755f39d397SChris Mason 		     btrfs_item_offset_nr(right, push_items - 1);
38765f39d397SChris Mason 
38773d9ec8c4SNikolay Borisov 	copy_extent_buffer(left, right, BTRFS_LEAF_DATA_OFFSET +
38782ff7e61eSJeff Mahoney 		     leaf_data_end(fs_info, left) - push_space,
38793d9ec8c4SNikolay Borisov 		     BTRFS_LEAF_DATA_OFFSET +
38805f39d397SChris Mason 		     btrfs_item_offset_nr(right, push_items - 1),
3881be0e5c09SChris Mason 		     push_space);
38825f39d397SChris Mason 	old_left_nritems = btrfs_header_nritems(left);
388387b29b20SYan Zheng 	BUG_ON(old_left_nritems <= 0);
3884eb60ceacSChris Mason 
3885db94535dSChris Mason 	old_left_item_size = btrfs_item_offset_nr(left, old_left_nritems - 1);
3886be0e5c09SChris Mason 	for (i = old_left_nritems; i < old_left_nritems + push_items; i++) {
38875f39d397SChris Mason 		u32 ioff;
3888db94535dSChris Mason 
3889dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
3890db94535dSChris Mason 
3891cfed81a0SChris Mason 		ioff = btrfs_token_item_offset(left, item, &token);
3892cfed81a0SChris Mason 		btrfs_set_token_item_offset(left, item,
38930b246afaSJeff Mahoney 		      ioff - (BTRFS_LEAF_DATA_SIZE(fs_info) - old_left_item_size),
3894cfed81a0SChris Mason 		      &token);
3895be0e5c09SChris Mason 	}
38965f39d397SChris Mason 	btrfs_set_header_nritems(left, old_left_nritems + push_items);
3897be0e5c09SChris Mason 
3898be0e5c09SChris Mason 	/* fixup right node */
389931b1a2bdSJulia Lawall 	if (push_items > right_nritems)
390031b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "push items %d nr %u\n", push_items,
3901d397712bSChris Mason 		       right_nritems);
390234a38218SChris Mason 
390334a38218SChris Mason 	if (push_items < right_nritems) {
39045f39d397SChris Mason 		push_space = btrfs_item_offset_nr(right, push_items - 1) -
39052ff7e61eSJeff Mahoney 						  leaf_data_end(fs_info, right);
39063d9ec8c4SNikolay Borisov 		memmove_extent_buffer(right, BTRFS_LEAF_DATA_OFFSET +
39070b246afaSJeff Mahoney 				      BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
39083d9ec8c4SNikolay Borisov 				      BTRFS_LEAF_DATA_OFFSET +
39092ff7e61eSJeff Mahoney 				      leaf_data_end(fs_info, right), push_space);
39105f39d397SChris Mason 
39115f39d397SChris Mason 		memmove_extent_buffer(right, btrfs_item_nr_offset(0),
39125f39d397SChris Mason 			      btrfs_item_nr_offset(push_items),
39135f39d397SChris Mason 			     (btrfs_header_nritems(right) - push_items) *
39140783fcfcSChris Mason 			     sizeof(struct btrfs_item));
391534a38218SChris Mason 	}
3916eef1c494SYan 	right_nritems -= push_items;
3917eef1c494SYan 	btrfs_set_header_nritems(right, right_nritems);
39180b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
39195f39d397SChris Mason 	for (i = 0; i < right_nritems; i++) {
3920dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
3921db94535dSChris Mason 
3922cfed81a0SChris Mason 		push_space = push_space - btrfs_token_item_size(right,
3923cfed81a0SChris Mason 								item, &token);
3924cfed81a0SChris Mason 		btrfs_set_token_item_offset(right, item, push_space, &token);
3925db94535dSChris Mason 	}
3926eb60ceacSChris Mason 
39275f39d397SChris Mason 	btrfs_mark_buffer_dirty(left);
392834a38218SChris Mason 	if (right_nritems)
39295f39d397SChris Mason 		btrfs_mark_buffer_dirty(right);
3930f0486c68SYan, Zheng 	else
39317c302b49SDavid Sterba 		clean_tree_block(fs_info, right);
3932098f59c2SChris Mason 
39335f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
39340b246afaSJeff Mahoney 	fixup_low_keys(fs_info, path, &disk_key, 1);
3935be0e5c09SChris Mason 
3936be0e5c09SChris Mason 	/* then fixup the leaf pointer in the path */
3937be0e5c09SChris Mason 	if (path->slots[0] < push_items) {
3938be0e5c09SChris Mason 		path->slots[0] += old_left_nritems;
3939925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
39405f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
39415f39d397SChris Mason 		path->nodes[0] = left;
3942be0e5c09SChris Mason 		path->slots[1] -= 1;
3943be0e5c09SChris Mason 	} else {
3944925baeddSChris Mason 		btrfs_tree_unlock(left);
39455f39d397SChris Mason 		free_extent_buffer(left);
3946be0e5c09SChris Mason 		path->slots[0] -= push_items;
3947be0e5c09SChris Mason 	}
3948eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
3949aa5d6bedSChris Mason 	return ret;
3950925baeddSChris Mason out:
3951925baeddSChris Mason 	btrfs_tree_unlock(left);
3952925baeddSChris Mason 	free_extent_buffer(left);
3953925baeddSChris Mason 	return ret;
3954be0e5c09SChris Mason }
3955be0e5c09SChris Mason 
395674123bd7SChris Mason /*
395744871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
395844871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
395999d8f83cSChris Mason  *
396099d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
396199d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us push all the
396299d8f83cSChris Mason  * items
396344871b1bSChris Mason  */
396444871b1bSChris Mason static int push_leaf_left(struct btrfs_trans_handle *trans, struct btrfs_root
396599d8f83cSChris Mason 			  *root, struct btrfs_path *path, int min_data_size,
396699d8f83cSChris Mason 			  int data_size, int empty, u32 max_slot)
396744871b1bSChris Mason {
39682ff7e61eSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
396944871b1bSChris Mason 	struct extent_buffer *right = path->nodes[0];
397044871b1bSChris Mason 	struct extent_buffer *left;
397144871b1bSChris Mason 	int slot;
397244871b1bSChris Mason 	int free_space;
397344871b1bSChris Mason 	u32 right_nritems;
397444871b1bSChris Mason 	int ret = 0;
397544871b1bSChris Mason 
397644871b1bSChris Mason 	slot = path->slots[1];
397744871b1bSChris Mason 	if (slot == 0)
397844871b1bSChris Mason 		return 1;
397944871b1bSChris Mason 	if (!path->nodes[1])
398044871b1bSChris Mason 		return 1;
398144871b1bSChris Mason 
398244871b1bSChris Mason 	right_nritems = btrfs_header_nritems(right);
398344871b1bSChris Mason 	if (right_nritems == 0)
398444871b1bSChris Mason 		return 1;
398544871b1bSChris Mason 
398644871b1bSChris Mason 	btrfs_assert_tree_locked(path->nodes[1]);
398744871b1bSChris Mason 
39882ff7e61eSJeff Mahoney 	left = read_node_slot(fs_info, path->nodes[1], slot - 1);
3989fb770ae4SLiu Bo 	/*
3990fb770ae4SLiu Bo 	 * slot - 1 is not valid or we fail to read the left node,
3991fb770ae4SLiu Bo 	 * no big deal, just return.
3992fb770ae4SLiu Bo 	 */
3993fb770ae4SLiu Bo 	if (IS_ERR(left))
399491ca338dSTsutomu Itoh 		return 1;
399591ca338dSTsutomu Itoh 
399644871b1bSChris Mason 	btrfs_tree_lock(left);
399744871b1bSChris Mason 	btrfs_set_lock_blocking(left);
399844871b1bSChris Mason 
39992ff7e61eSJeff Mahoney 	free_space = btrfs_leaf_free_space(fs_info, left);
400044871b1bSChris Mason 	if (free_space < data_size) {
400144871b1bSChris Mason 		ret = 1;
400244871b1bSChris Mason 		goto out;
400344871b1bSChris Mason 	}
400444871b1bSChris Mason 
400544871b1bSChris Mason 	/* cow and double check */
400644871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, left,
400744871b1bSChris Mason 			      path->nodes[1], slot - 1, &left);
400844871b1bSChris Mason 	if (ret) {
400944871b1bSChris Mason 		/* we hit -ENOSPC, but it isn't fatal here */
401079787eaaSJeff Mahoney 		if (ret == -ENOSPC)
401144871b1bSChris Mason 			ret = 1;
401244871b1bSChris Mason 		goto out;
401344871b1bSChris Mason 	}
401444871b1bSChris Mason 
40152ff7e61eSJeff Mahoney 	free_space = btrfs_leaf_free_space(fs_info, left);
401644871b1bSChris Mason 	if (free_space < data_size) {
401744871b1bSChris Mason 		ret = 1;
401844871b1bSChris Mason 		goto out;
401944871b1bSChris Mason 	}
402044871b1bSChris Mason 
402166cb7ddbSDavid Sterba 	return __push_leaf_left(fs_info, path, min_data_size,
402299d8f83cSChris Mason 			       empty, left, free_space, right_nritems,
402399d8f83cSChris Mason 			       max_slot);
402444871b1bSChris Mason out:
402544871b1bSChris Mason 	btrfs_tree_unlock(left);
402644871b1bSChris Mason 	free_extent_buffer(left);
402744871b1bSChris Mason 	return ret;
402844871b1bSChris Mason }
402944871b1bSChris Mason 
403044871b1bSChris Mason /*
403174123bd7SChris Mason  * split the path's leaf in two, making sure there is at least data_size
403274123bd7SChris Mason  * available for the resulting leaf level of the path.
403374123bd7SChris Mason  */
4034143bede5SJeff Mahoney static noinline void copy_for_split(struct btrfs_trans_handle *trans,
40352ff7e61eSJeff Mahoney 				    struct btrfs_fs_info *fs_info,
403644871b1bSChris Mason 				    struct btrfs_path *path,
403744871b1bSChris Mason 				    struct extent_buffer *l,
403844871b1bSChris Mason 				    struct extent_buffer *right,
403944871b1bSChris Mason 				    int slot, int mid, int nritems)
4040be0e5c09SChris Mason {
4041be0e5c09SChris Mason 	int data_copy_size;
4042be0e5c09SChris Mason 	int rt_data_off;
4043be0e5c09SChris Mason 	int i;
4044d4dbff95SChris Mason 	struct btrfs_disk_key disk_key;
4045cfed81a0SChris Mason 	struct btrfs_map_token token;
4046cfed81a0SChris Mason 
4047cfed81a0SChris Mason 	btrfs_init_map_token(&token);
4048be0e5c09SChris Mason 
40495f39d397SChris Mason 	nritems = nritems - mid;
40505f39d397SChris Mason 	btrfs_set_header_nritems(right, nritems);
40512ff7e61eSJeff Mahoney 	data_copy_size = btrfs_item_end_nr(l, mid) - leaf_data_end(fs_info, l);
40525f39d397SChris Mason 
40535f39d397SChris Mason 	copy_extent_buffer(right, l, btrfs_item_nr_offset(0),
40545f39d397SChris Mason 			   btrfs_item_nr_offset(mid),
40555f39d397SChris Mason 			   nritems * sizeof(struct btrfs_item));
40565f39d397SChris Mason 
40575f39d397SChris Mason 	copy_extent_buffer(right, l,
40583d9ec8c4SNikolay Borisov 		     BTRFS_LEAF_DATA_OFFSET + BTRFS_LEAF_DATA_SIZE(fs_info) -
40593d9ec8c4SNikolay Borisov 		     data_copy_size, BTRFS_LEAF_DATA_OFFSET +
40602ff7e61eSJeff Mahoney 		     leaf_data_end(fs_info, l), data_copy_size);
406174123bd7SChris Mason 
40620b246afaSJeff Mahoney 	rt_data_off = BTRFS_LEAF_DATA_SIZE(fs_info) - btrfs_item_end_nr(l, mid);
40635f39d397SChris Mason 
40645f39d397SChris Mason 	for (i = 0; i < nritems; i++) {
4065dd3cc16bSRoss Kirk 		struct btrfs_item *item = btrfs_item_nr(i);
4066db94535dSChris Mason 		u32 ioff;
4067db94535dSChris Mason 
4068cfed81a0SChris Mason 		ioff = btrfs_token_item_offset(right, item, &token);
4069cfed81a0SChris Mason 		btrfs_set_token_item_offset(right, item,
4070cfed81a0SChris Mason 					    ioff + rt_data_off, &token);
40710783fcfcSChris Mason 	}
407274123bd7SChris Mason 
40735f39d397SChris Mason 	btrfs_set_header_nritems(l, mid);
40745f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
40752ff7e61eSJeff Mahoney 	insert_ptr(trans, fs_info, path, &disk_key, right->start,
4076c3e06965SJan Schmidt 		   path->slots[1] + 1, 1);
40775f39d397SChris Mason 
40785f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
40795f39d397SChris Mason 	btrfs_mark_buffer_dirty(l);
4080eb60ceacSChris Mason 	BUG_ON(path->slots[0] != slot);
40815f39d397SChris Mason 
4082be0e5c09SChris Mason 	if (mid <= slot) {
4083925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
40845f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
40855f39d397SChris Mason 		path->nodes[0] = right;
4086be0e5c09SChris Mason 		path->slots[0] -= mid;
4087be0e5c09SChris Mason 		path->slots[1] += 1;
4088925baeddSChris Mason 	} else {
4089925baeddSChris Mason 		btrfs_tree_unlock(right);
40905f39d397SChris Mason 		free_extent_buffer(right);
4091925baeddSChris Mason 	}
40925f39d397SChris Mason 
4093eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
409444871b1bSChris Mason }
409544871b1bSChris Mason 
409644871b1bSChris Mason /*
409799d8f83cSChris Mason  * double splits happen when we need to insert a big item in the middle
409899d8f83cSChris Mason  * of a leaf.  A double split can leave us with 3 mostly empty leaves:
409999d8f83cSChris Mason  * leaf: [ slots 0 - N] [ our target ] [ N + 1 - total in leaf ]
410099d8f83cSChris Mason  *          A                 B                 C
410199d8f83cSChris Mason  *
410299d8f83cSChris Mason  * We avoid this by trying to push the items on either side of our target
410399d8f83cSChris Mason  * into the adjacent leaves.  If all goes well we can avoid the double split
410499d8f83cSChris Mason  * completely.
410599d8f83cSChris Mason  */
410699d8f83cSChris Mason static noinline int push_for_double_split(struct btrfs_trans_handle *trans,
410799d8f83cSChris Mason 					  struct btrfs_root *root,
410899d8f83cSChris Mason 					  struct btrfs_path *path,
410999d8f83cSChris Mason 					  int data_size)
411099d8f83cSChris Mason {
41112ff7e61eSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
411299d8f83cSChris Mason 	int ret;
411399d8f83cSChris Mason 	int progress = 0;
411499d8f83cSChris Mason 	int slot;
411599d8f83cSChris Mason 	u32 nritems;
41165a4267caSFilipe David Borba Manana 	int space_needed = data_size;
411799d8f83cSChris Mason 
411899d8f83cSChris Mason 	slot = path->slots[0];
41195a4267caSFilipe David Borba Manana 	if (slot < btrfs_header_nritems(path->nodes[0]))
41202ff7e61eSJeff Mahoney 		space_needed -= btrfs_leaf_free_space(fs_info, path->nodes[0]);
412199d8f83cSChris Mason 
412299d8f83cSChris Mason 	/*
412399d8f83cSChris Mason 	 * try to push all the items after our slot into the
412499d8f83cSChris Mason 	 * right leaf
412599d8f83cSChris Mason 	 */
41265a4267caSFilipe David Borba Manana 	ret = push_leaf_right(trans, root, path, 1, space_needed, 0, slot);
412799d8f83cSChris Mason 	if (ret < 0)
412899d8f83cSChris Mason 		return ret;
412999d8f83cSChris Mason 
413099d8f83cSChris Mason 	if (ret == 0)
413199d8f83cSChris Mason 		progress++;
413299d8f83cSChris Mason 
413399d8f83cSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
413499d8f83cSChris Mason 	/*
413599d8f83cSChris Mason 	 * our goal is to get our slot at the start or end of a leaf.  If
413699d8f83cSChris Mason 	 * we've done so we're done
413799d8f83cSChris Mason 	 */
413899d8f83cSChris Mason 	if (path->slots[0] == 0 || path->slots[0] == nritems)
413999d8f83cSChris Mason 		return 0;
414099d8f83cSChris Mason 
41412ff7e61eSJeff Mahoney 	if (btrfs_leaf_free_space(fs_info, path->nodes[0]) >= data_size)
414299d8f83cSChris Mason 		return 0;
414399d8f83cSChris Mason 
414499d8f83cSChris Mason 	/* try to push all the items before our slot into the next leaf */
414599d8f83cSChris Mason 	slot = path->slots[0];
4146263d3995SFilipe Manana 	space_needed = data_size;
4147263d3995SFilipe Manana 	if (slot > 0)
4148263d3995SFilipe Manana 		space_needed -= btrfs_leaf_free_space(fs_info, path->nodes[0]);
41495a4267caSFilipe David Borba Manana 	ret = push_leaf_left(trans, root, path, 1, space_needed, 0, slot);
415099d8f83cSChris Mason 	if (ret < 0)
415199d8f83cSChris Mason 		return ret;
415299d8f83cSChris Mason 
415399d8f83cSChris Mason 	if (ret == 0)
415499d8f83cSChris Mason 		progress++;
415599d8f83cSChris Mason 
415699d8f83cSChris Mason 	if (progress)
415799d8f83cSChris Mason 		return 0;
415899d8f83cSChris Mason 	return 1;
415999d8f83cSChris Mason }
416099d8f83cSChris Mason 
416199d8f83cSChris Mason /*
416244871b1bSChris Mason  * split the path's leaf in two, making sure there is at least data_size
416344871b1bSChris Mason  * available for the resulting leaf level of the path.
416444871b1bSChris Mason  *
416544871b1bSChris Mason  * returns 0 if all went well and < 0 on failure.
416644871b1bSChris Mason  */
416744871b1bSChris Mason static noinline int split_leaf(struct btrfs_trans_handle *trans,
416844871b1bSChris Mason 			       struct btrfs_root *root,
4169310712b2SOmar Sandoval 			       const struct btrfs_key *ins_key,
417044871b1bSChris Mason 			       struct btrfs_path *path, int data_size,
417144871b1bSChris Mason 			       int extend)
417244871b1bSChris Mason {
41735d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
417444871b1bSChris Mason 	struct extent_buffer *l;
417544871b1bSChris Mason 	u32 nritems;
417644871b1bSChris Mason 	int mid;
417744871b1bSChris Mason 	int slot;
417844871b1bSChris Mason 	struct extent_buffer *right;
4179b7a0365eSDaniel Dressler 	struct btrfs_fs_info *fs_info = root->fs_info;
418044871b1bSChris Mason 	int ret = 0;
418144871b1bSChris Mason 	int wret;
41825d4f98a2SYan Zheng 	int split;
418344871b1bSChris Mason 	int num_doubles = 0;
418499d8f83cSChris Mason 	int tried_avoid_double = 0;
418544871b1bSChris Mason 
4186a5719521SYan, Zheng 	l = path->nodes[0];
4187a5719521SYan, Zheng 	slot = path->slots[0];
4188a5719521SYan, Zheng 	if (extend && data_size + btrfs_item_size_nr(l, slot) +
41890b246afaSJeff Mahoney 	    sizeof(struct btrfs_item) > BTRFS_LEAF_DATA_SIZE(fs_info))
4190a5719521SYan, Zheng 		return -EOVERFLOW;
4191a5719521SYan, Zheng 
419244871b1bSChris Mason 	/* first try to make some room by pushing left and right */
419333157e05SLiu Bo 	if (data_size && path->nodes[1]) {
41945a4267caSFilipe David Borba Manana 		int space_needed = data_size;
41955a4267caSFilipe David Borba Manana 
41965a4267caSFilipe David Borba Manana 		if (slot < btrfs_header_nritems(l))
41972ff7e61eSJeff Mahoney 			space_needed -= btrfs_leaf_free_space(fs_info, l);
41985a4267caSFilipe David Borba Manana 
41995a4267caSFilipe David Borba Manana 		wret = push_leaf_right(trans, root, path, space_needed,
42005a4267caSFilipe David Borba Manana 				       space_needed, 0, 0);
420144871b1bSChris Mason 		if (wret < 0)
420244871b1bSChris Mason 			return wret;
420344871b1bSChris Mason 		if (wret) {
4204263d3995SFilipe Manana 			space_needed = data_size;
4205263d3995SFilipe Manana 			if (slot > 0)
4206263d3995SFilipe Manana 				space_needed -= btrfs_leaf_free_space(fs_info,
4207263d3995SFilipe Manana 								      l);
42085a4267caSFilipe David Borba Manana 			wret = push_leaf_left(trans, root, path, space_needed,
42095a4267caSFilipe David Borba Manana 					      space_needed, 0, (u32)-1);
421044871b1bSChris Mason 			if (wret < 0)
421144871b1bSChris Mason 				return wret;
421244871b1bSChris Mason 		}
421344871b1bSChris Mason 		l = path->nodes[0];
421444871b1bSChris Mason 
421544871b1bSChris Mason 		/* did the pushes work? */
42162ff7e61eSJeff Mahoney 		if (btrfs_leaf_free_space(fs_info, l) >= data_size)
421744871b1bSChris Mason 			return 0;
421844871b1bSChris Mason 	}
421944871b1bSChris Mason 
422044871b1bSChris Mason 	if (!path->nodes[1]) {
4221fdd99c72SLiu Bo 		ret = insert_new_root(trans, root, path, 1);
422244871b1bSChris Mason 		if (ret)
422344871b1bSChris Mason 			return ret;
422444871b1bSChris Mason 	}
422544871b1bSChris Mason again:
42265d4f98a2SYan Zheng 	split = 1;
422744871b1bSChris Mason 	l = path->nodes[0];
422844871b1bSChris Mason 	slot = path->slots[0];
422944871b1bSChris Mason 	nritems = btrfs_header_nritems(l);
423044871b1bSChris Mason 	mid = (nritems + 1) / 2;
423144871b1bSChris Mason 
42325d4f98a2SYan Zheng 	if (mid <= slot) {
42335d4f98a2SYan Zheng 		if (nritems == 1 ||
42345d4f98a2SYan Zheng 		    leaf_space_used(l, mid, nritems - mid) + data_size >
42350b246afaSJeff Mahoney 			BTRFS_LEAF_DATA_SIZE(fs_info)) {
42365d4f98a2SYan Zheng 			if (slot >= nritems) {
42375d4f98a2SYan Zheng 				split = 0;
42385d4f98a2SYan Zheng 			} else {
42395d4f98a2SYan Zheng 				mid = slot;
42405d4f98a2SYan Zheng 				if (mid != nritems &&
42415d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
42420b246afaSJeff Mahoney 				    data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
424399d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
424499d8f83cSChris Mason 						goto push_for_double;
42455d4f98a2SYan Zheng 					split = 2;
42465d4f98a2SYan Zheng 				}
42475d4f98a2SYan Zheng 			}
42485d4f98a2SYan Zheng 		}
42495d4f98a2SYan Zheng 	} else {
42505d4f98a2SYan Zheng 		if (leaf_space_used(l, 0, mid) + data_size >
42510b246afaSJeff Mahoney 			BTRFS_LEAF_DATA_SIZE(fs_info)) {
42525d4f98a2SYan Zheng 			if (!extend && data_size && slot == 0) {
42535d4f98a2SYan Zheng 				split = 0;
42545d4f98a2SYan Zheng 			} else if ((extend || !data_size) && slot == 0) {
42555d4f98a2SYan Zheng 				mid = 1;
42565d4f98a2SYan Zheng 			} else {
42575d4f98a2SYan Zheng 				mid = slot;
42585d4f98a2SYan Zheng 				if (mid != nritems &&
42595d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
42600b246afaSJeff Mahoney 				    data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
426199d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
426299d8f83cSChris Mason 						goto push_for_double;
42635d4f98a2SYan Zheng 					split = 2;
42645d4f98a2SYan Zheng 				}
42655d4f98a2SYan Zheng 			}
42665d4f98a2SYan Zheng 		}
42675d4f98a2SYan Zheng 	}
42685d4f98a2SYan Zheng 
42695d4f98a2SYan Zheng 	if (split == 0)
42705d4f98a2SYan Zheng 		btrfs_cpu_key_to_disk(&disk_key, ins_key);
42715d4f98a2SYan Zheng 	else
42725d4f98a2SYan Zheng 		btrfs_item_key(l, &disk_key, mid);
42735d4f98a2SYan Zheng 
42744d75f8a9SDavid Sterba 	right = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
42755581a51aSJan Schmidt 			&disk_key, 0, l->start, 0);
4276f0486c68SYan, Zheng 	if (IS_ERR(right))
427744871b1bSChris Mason 		return PTR_ERR(right);
4278f0486c68SYan, Zheng 
42790b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
428044871b1bSChris Mason 
4281b159fa28SDavid Sterba 	memzero_extent_buffer(right, 0, sizeof(struct btrfs_header));
428244871b1bSChris Mason 	btrfs_set_header_bytenr(right, right->start);
428344871b1bSChris Mason 	btrfs_set_header_generation(right, trans->transid);
42845d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(right, BTRFS_MIXED_BACKREF_REV);
428544871b1bSChris Mason 	btrfs_set_header_owner(right, root->root_key.objectid);
428644871b1bSChris Mason 	btrfs_set_header_level(right, 0);
4287d24ee97bSDavid Sterba 	write_extent_buffer_fsid(right, fs_info->fsid);
4288d24ee97bSDavid Sterba 	write_extent_buffer_chunk_tree_uuid(right, fs_info->chunk_tree_uuid);
428944871b1bSChris Mason 
42905d4f98a2SYan Zheng 	if (split == 0) {
429144871b1bSChris Mason 		if (mid <= slot) {
429244871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
42932ff7e61eSJeff Mahoney 			insert_ptr(trans, fs_info, path, &disk_key,
42942ff7e61eSJeff Mahoney 				   right->start, path->slots[1] + 1, 1);
429544871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
429644871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
429744871b1bSChris Mason 			path->nodes[0] = right;
429844871b1bSChris Mason 			path->slots[0] = 0;
429944871b1bSChris Mason 			path->slots[1] += 1;
430044871b1bSChris Mason 		} else {
430144871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
43022ff7e61eSJeff Mahoney 			insert_ptr(trans, fs_info, path, &disk_key,
43032ff7e61eSJeff Mahoney 				   right->start, path->slots[1], 1);
430444871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
430544871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
430644871b1bSChris Mason 			path->nodes[0] = right;
430744871b1bSChris Mason 			path->slots[0] = 0;
4308143bede5SJeff Mahoney 			if (path->slots[1] == 0)
4309b7a0365eSDaniel Dressler 				fixup_low_keys(fs_info, path, &disk_key, 1);
43105d4f98a2SYan Zheng 		}
4311196e0249SLiu Bo 		/*
4312196e0249SLiu Bo 		 * We create a new leaf 'right' for the required ins_len and
4313196e0249SLiu Bo 		 * we'll do btrfs_mark_buffer_dirty() on this leaf after copying
4314196e0249SLiu Bo 		 * the content of ins_len to 'right'.
4315196e0249SLiu Bo 		 */
431644871b1bSChris Mason 		return ret;
431744871b1bSChris Mason 	}
431844871b1bSChris Mason 
43192ff7e61eSJeff Mahoney 	copy_for_split(trans, fs_info, path, l, right, slot, mid, nritems);
432044871b1bSChris Mason 
43215d4f98a2SYan Zheng 	if (split == 2) {
4322cc0c5538SChris Mason 		BUG_ON(num_doubles != 0);
4323cc0c5538SChris Mason 		num_doubles++;
4324cc0c5538SChris Mason 		goto again;
43253326d1b0SChris Mason 	}
432644871b1bSChris Mason 
4327143bede5SJeff Mahoney 	return 0;
432899d8f83cSChris Mason 
432999d8f83cSChris Mason push_for_double:
433099d8f83cSChris Mason 	push_for_double_split(trans, root, path, data_size);
433199d8f83cSChris Mason 	tried_avoid_double = 1;
43322ff7e61eSJeff Mahoney 	if (btrfs_leaf_free_space(fs_info, path->nodes[0]) >= data_size)
433399d8f83cSChris Mason 		return 0;
433499d8f83cSChris Mason 	goto again;
4335be0e5c09SChris Mason }
4336be0e5c09SChris Mason 
4337ad48fd75SYan, Zheng static noinline int setup_leaf_for_split(struct btrfs_trans_handle *trans,
4338ad48fd75SYan, Zheng 					 struct btrfs_root *root,
4339ad48fd75SYan, Zheng 					 struct btrfs_path *path, int ins_len)
4340ad48fd75SYan, Zheng {
43412ff7e61eSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
4342ad48fd75SYan, Zheng 	struct btrfs_key key;
4343ad48fd75SYan, Zheng 	struct extent_buffer *leaf;
4344ad48fd75SYan, Zheng 	struct btrfs_file_extent_item *fi;
4345ad48fd75SYan, Zheng 	u64 extent_len = 0;
4346ad48fd75SYan, Zheng 	u32 item_size;
4347ad48fd75SYan, Zheng 	int ret;
4348ad48fd75SYan, Zheng 
4349ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4350ad48fd75SYan, Zheng 	btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4351ad48fd75SYan, Zheng 
4352ad48fd75SYan, Zheng 	BUG_ON(key.type != BTRFS_EXTENT_DATA_KEY &&
4353ad48fd75SYan, Zheng 	       key.type != BTRFS_EXTENT_CSUM_KEY);
4354ad48fd75SYan, Zheng 
43552ff7e61eSJeff Mahoney 	if (btrfs_leaf_free_space(fs_info, leaf) >= ins_len)
4356ad48fd75SYan, Zheng 		return 0;
4357ad48fd75SYan, Zheng 
4358ad48fd75SYan, Zheng 	item_size = btrfs_item_size_nr(leaf, path->slots[0]);
4359ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
4360ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
4361ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
4362ad48fd75SYan, Zheng 		extent_len = btrfs_file_extent_num_bytes(leaf, fi);
4363ad48fd75SYan, Zheng 	}
4364b3b4aa74SDavid Sterba 	btrfs_release_path(path);
4365ad48fd75SYan, Zheng 
4366ad48fd75SYan, Zheng 	path->keep_locks = 1;
4367ad48fd75SYan, Zheng 	path->search_for_split = 1;
4368ad48fd75SYan, Zheng 	ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
4369ad48fd75SYan, Zheng 	path->search_for_split = 0;
4370a8df6fe6SFilipe Manana 	if (ret > 0)
4371a8df6fe6SFilipe Manana 		ret = -EAGAIN;
4372ad48fd75SYan, Zheng 	if (ret < 0)
4373ad48fd75SYan, Zheng 		goto err;
4374ad48fd75SYan, Zheng 
4375ad48fd75SYan, Zheng 	ret = -EAGAIN;
4376ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4377a8df6fe6SFilipe Manana 	/* if our item isn't there, return now */
4378a8df6fe6SFilipe Manana 	if (item_size != btrfs_item_size_nr(leaf, path->slots[0]))
4379ad48fd75SYan, Zheng 		goto err;
4380ad48fd75SYan, Zheng 
4381109f6aefSChris Mason 	/* the leaf has  changed, it now has room.  return now */
43822ff7e61eSJeff Mahoney 	if (btrfs_leaf_free_space(fs_info, path->nodes[0]) >= ins_len)
4383109f6aefSChris Mason 		goto err;
4384109f6aefSChris Mason 
4385ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
4386ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
4387ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
4388ad48fd75SYan, Zheng 		if (extent_len != btrfs_file_extent_num_bytes(leaf, fi))
4389ad48fd75SYan, Zheng 			goto err;
4390ad48fd75SYan, Zheng 	}
4391ad48fd75SYan, Zheng 
4392ad48fd75SYan, Zheng 	btrfs_set_path_blocking(path);
4393ad48fd75SYan, Zheng 	ret = split_leaf(trans, root, &key, path, ins_len, 1);
4394f0486c68SYan, Zheng 	if (ret)
4395f0486c68SYan, Zheng 		goto err;
4396ad48fd75SYan, Zheng 
4397ad48fd75SYan, Zheng 	path->keep_locks = 0;
4398ad48fd75SYan, Zheng 	btrfs_unlock_up_safe(path, 1);
4399ad48fd75SYan, Zheng 	return 0;
4400ad48fd75SYan, Zheng err:
4401ad48fd75SYan, Zheng 	path->keep_locks = 0;
4402ad48fd75SYan, Zheng 	return ret;
4403ad48fd75SYan, Zheng }
4404ad48fd75SYan, Zheng 
44054961e293SDavid Sterba static noinline int split_item(struct btrfs_fs_info *fs_info,
4406459931ecSChris Mason 			       struct btrfs_path *path,
4407310712b2SOmar Sandoval 			       const struct btrfs_key *new_key,
4408459931ecSChris Mason 			       unsigned long split_offset)
4409459931ecSChris Mason {
4410459931ecSChris Mason 	struct extent_buffer *leaf;
4411459931ecSChris Mason 	struct btrfs_item *item;
4412459931ecSChris Mason 	struct btrfs_item *new_item;
4413459931ecSChris Mason 	int slot;
4414ad48fd75SYan, Zheng 	char *buf;
4415459931ecSChris Mason 	u32 nritems;
4416ad48fd75SYan, Zheng 	u32 item_size;
4417459931ecSChris Mason 	u32 orig_offset;
4418459931ecSChris Mason 	struct btrfs_disk_key disk_key;
4419459931ecSChris Mason 
4420459931ecSChris Mason 	leaf = path->nodes[0];
44212ff7e61eSJeff Mahoney 	BUG_ON(btrfs_leaf_free_space(fs_info, leaf) < sizeof(struct btrfs_item));
4422b9473439SChris Mason 
4423b4ce94deSChris Mason 	btrfs_set_path_blocking(path);
4424b4ce94deSChris Mason 
4425dd3cc16bSRoss Kirk 	item = btrfs_item_nr(path->slots[0]);
4426459931ecSChris Mason 	orig_offset = btrfs_item_offset(leaf, item);
4427459931ecSChris Mason 	item_size = btrfs_item_size(leaf, item);
4428459931ecSChris Mason 
4429459931ecSChris Mason 	buf = kmalloc(item_size, GFP_NOFS);
4430ad48fd75SYan, Zheng 	if (!buf)
4431ad48fd75SYan, Zheng 		return -ENOMEM;
4432ad48fd75SYan, Zheng 
4433459931ecSChris Mason 	read_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf,
4434459931ecSChris Mason 			    path->slots[0]), item_size);
4435ad48fd75SYan, Zheng 
4436459931ecSChris Mason 	slot = path->slots[0] + 1;
4437459931ecSChris Mason 	nritems = btrfs_header_nritems(leaf);
4438459931ecSChris Mason 	if (slot != nritems) {
4439459931ecSChris Mason 		/* shift the items */
4440459931ecSChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + 1),
4441459931ecSChris Mason 				btrfs_item_nr_offset(slot),
4442459931ecSChris Mason 				(nritems - slot) * sizeof(struct btrfs_item));
4443459931ecSChris Mason 	}
4444459931ecSChris Mason 
4445459931ecSChris Mason 	btrfs_cpu_key_to_disk(&disk_key, new_key);
4446459931ecSChris Mason 	btrfs_set_item_key(leaf, &disk_key, slot);
4447459931ecSChris Mason 
4448dd3cc16bSRoss Kirk 	new_item = btrfs_item_nr(slot);
4449459931ecSChris Mason 
4450459931ecSChris Mason 	btrfs_set_item_offset(leaf, new_item, orig_offset);
4451459931ecSChris Mason 	btrfs_set_item_size(leaf, new_item, item_size - split_offset);
4452459931ecSChris Mason 
4453459931ecSChris Mason 	btrfs_set_item_offset(leaf, item,
4454459931ecSChris Mason 			      orig_offset + item_size - split_offset);
4455459931ecSChris Mason 	btrfs_set_item_size(leaf, item, split_offset);
4456459931ecSChris Mason 
4457459931ecSChris Mason 	btrfs_set_header_nritems(leaf, nritems + 1);
4458459931ecSChris Mason 
4459459931ecSChris Mason 	/* write the data for the start of the original item */
4460459931ecSChris Mason 	write_extent_buffer(leaf, buf,
4461459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, path->slots[0]),
4462459931ecSChris Mason 			    split_offset);
4463459931ecSChris Mason 
4464459931ecSChris Mason 	/* write the data for the new item */
4465459931ecSChris Mason 	write_extent_buffer(leaf, buf + split_offset,
4466459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, slot),
4467459931ecSChris Mason 			    item_size - split_offset);
4468459931ecSChris Mason 	btrfs_mark_buffer_dirty(leaf);
4469459931ecSChris Mason 
44702ff7e61eSJeff Mahoney 	BUG_ON(btrfs_leaf_free_space(fs_info, leaf) < 0);
4471459931ecSChris Mason 	kfree(buf);
4472ad48fd75SYan, Zheng 	return 0;
4473ad48fd75SYan, Zheng }
4474ad48fd75SYan, Zheng 
4475ad48fd75SYan, Zheng /*
4476ad48fd75SYan, Zheng  * This function splits a single item into two items,
4477ad48fd75SYan, Zheng  * giving 'new_key' to the new item and splitting the
4478ad48fd75SYan, Zheng  * old one at split_offset (from the start of the item).
4479ad48fd75SYan, Zheng  *
4480ad48fd75SYan, Zheng  * The path may be released by this operation.  After
4481ad48fd75SYan, Zheng  * the split, the path is pointing to the old item.  The
4482ad48fd75SYan, Zheng  * new item is going to be in the same node as the old one.
4483ad48fd75SYan, Zheng  *
4484ad48fd75SYan, Zheng  * Note, the item being split must be smaller enough to live alone on
4485ad48fd75SYan, Zheng  * a tree block with room for one extra struct btrfs_item
4486ad48fd75SYan, Zheng  *
4487ad48fd75SYan, Zheng  * This allows us to split the item in place, keeping a lock on the
4488ad48fd75SYan, Zheng  * leaf the entire time.
4489ad48fd75SYan, Zheng  */
4490ad48fd75SYan, Zheng int btrfs_split_item(struct btrfs_trans_handle *trans,
4491ad48fd75SYan, Zheng 		     struct btrfs_root *root,
4492ad48fd75SYan, Zheng 		     struct btrfs_path *path,
4493310712b2SOmar Sandoval 		     const struct btrfs_key *new_key,
4494ad48fd75SYan, Zheng 		     unsigned long split_offset)
4495ad48fd75SYan, Zheng {
4496ad48fd75SYan, Zheng 	int ret;
4497ad48fd75SYan, Zheng 	ret = setup_leaf_for_split(trans, root, path,
4498ad48fd75SYan, Zheng 				   sizeof(struct btrfs_item));
4499ad48fd75SYan, Zheng 	if (ret)
4500459931ecSChris Mason 		return ret;
4501ad48fd75SYan, Zheng 
45024961e293SDavid Sterba 	ret = split_item(root->fs_info, path, new_key, split_offset);
4503ad48fd75SYan, Zheng 	return ret;
4504ad48fd75SYan, Zheng }
4505ad48fd75SYan, Zheng 
4506ad48fd75SYan, Zheng /*
4507ad48fd75SYan, Zheng  * This function duplicate a item, giving 'new_key' to the new item.
4508ad48fd75SYan, Zheng  * It guarantees both items live in the same tree leaf and the new item
4509ad48fd75SYan, Zheng  * is contiguous with the original item.
4510ad48fd75SYan, Zheng  *
4511ad48fd75SYan, Zheng  * This allows us to split file extent in place, keeping a lock on the
4512ad48fd75SYan, Zheng  * leaf the entire time.
4513ad48fd75SYan, Zheng  */
4514ad48fd75SYan, Zheng int btrfs_duplicate_item(struct btrfs_trans_handle *trans,
4515ad48fd75SYan, Zheng 			 struct btrfs_root *root,
4516ad48fd75SYan, Zheng 			 struct btrfs_path *path,
4517310712b2SOmar Sandoval 			 const struct btrfs_key *new_key)
4518ad48fd75SYan, Zheng {
4519ad48fd75SYan, Zheng 	struct extent_buffer *leaf;
4520ad48fd75SYan, Zheng 	int ret;
4521ad48fd75SYan, Zheng 	u32 item_size;
4522ad48fd75SYan, Zheng 
4523ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4524ad48fd75SYan, Zheng 	item_size = btrfs_item_size_nr(leaf, path->slots[0]);
4525ad48fd75SYan, Zheng 	ret = setup_leaf_for_split(trans, root, path,
4526ad48fd75SYan, Zheng 				   item_size + sizeof(struct btrfs_item));
4527ad48fd75SYan, Zheng 	if (ret)
4528ad48fd75SYan, Zheng 		return ret;
4529ad48fd75SYan, Zheng 
4530ad48fd75SYan, Zheng 	path->slots[0]++;
4531afe5fea7STsutomu Itoh 	setup_items_for_insert(root, path, new_key, &item_size,
4532ad48fd75SYan, Zheng 			       item_size, item_size +
4533ad48fd75SYan, Zheng 			       sizeof(struct btrfs_item), 1);
4534ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4535ad48fd75SYan, Zheng 	memcpy_extent_buffer(leaf,
4536ad48fd75SYan, Zheng 			     btrfs_item_ptr_offset(leaf, path->slots[0]),
4537ad48fd75SYan, Zheng 			     btrfs_item_ptr_offset(leaf, path->slots[0] - 1),
4538ad48fd75SYan, Zheng 			     item_size);
4539ad48fd75SYan, Zheng 	return 0;
4540459931ecSChris Mason }
4541459931ecSChris Mason 
4542459931ecSChris Mason /*
4543d352ac68SChris Mason  * make the item pointed to by the path smaller.  new_size indicates
4544d352ac68SChris Mason  * how small to make it, and from_end tells us if we just chop bytes
4545d352ac68SChris Mason  * off the end of the item or if we shift the item to chop bytes off
4546d352ac68SChris Mason  * the front.
4547d352ac68SChris Mason  */
45482ff7e61eSJeff Mahoney void btrfs_truncate_item(struct btrfs_fs_info *fs_info,
45492ff7e61eSJeff Mahoney 			 struct btrfs_path *path, u32 new_size, int from_end)
4550b18c6685SChris Mason {
4551b18c6685SChris Mason 	int slot;
45525f39d397SChris Mason 	struct extent_buffer *leaf;
45535f39d397SChris Mason 	struct btrfs_item *item;
4554b18c6685SChris Mason 	u32 nritems;
4555b18c6685SChris Mason 	unsigned int data_end;
4556b18c6685SChris Mason 	unsigned int old_data_start;
4557b18c6685SChris Mason 	unsigned int old_size;
4558b18c6685SChris Mason 	unsigned int size_diff;
4559b18c6685SChris Mason 	int i;
4560cfed81a0SChris Mason 	struct btrfs_map_token token;
4561cfed81a0SChris Mason 
4562cfed81a0SChris Mason 	btrfs_init_map_token(&token);
4563b18c6685SChris Mason 
45645f39d397SChris Mason 	leaf = path->nodes[0];
4565179e29e4SChris Mason 	slot = path->slots[0];
4566179e29e4SChris Mason 
4567179e29e4SChris Mason 	old_size = btrfs_item_size_nr(leaf, slot);
4568179e29e4SChris Mason 	if (old_size == new_size)
4569143bede5SJeff Mahoney 		return;
4570b18c6685SChris Mason 
45715f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
45722ff7e61eSJeff Mahoney 	data_end = leaf_data_end(fs_info, leaf);
4573b18c6685SChris Mason 
45745f39d397SChris Mason 	old_data_start = btrfs_item_offset_nr(leaf, slot);
4575179e29e4SChris Mason 
4576b18c6685SChris Mason 	size_diff = old_size - new_size;
4577b18c6685SChris Mason 
4578b18c6685SChris Mason 	BUG_ON(slot < 0);
4579b18c6685SChris Mason 	BUG_ON(slot >= nritems);
4580b18c6685SChris Mason 
4581b18c6685SChris Mason 	/*
4582b18c6685SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4583b18c6685SChris Mason 	 */
4584b18c6685SChris Mason 	/* first correct the data pointers */
4585b18c6685SChris Mason 	for (i = slot; i < nritems; i++) {
45865f39d397SChris Mason 		u32 ioff;
4587dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
4588db94535dSChris Mason 
4589cfed81a0SChris Mason 		ioff = btrfs_token_item_offset(leaf, item, &token);
4590cfed81a0SChris Mason 		btrfs_set_token_item_offset(leaf, item,
4591cfed81a0SChris Mason 					    ioff + size_diff, &token);
4592b18c6685SChris Mason 	}
4593db94535dSChris Mason 
4594b18c6685SChris Mason 	/* shift the data */
4595179e29e4SChris Mason 	if (from_end) {
45963d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
45973d9ec8c4SNikolay Borisov 			      data_end + size_diff, BTRFS_LEAF_DATA_OFFSET +
4598b18c6685SChris Mason 			      data_end, old_data_start + new_size - data_end);
4599179e29e4SChris Mason 	} else {
4600179e29e4SChris Mason 		struct btrfs_disk_key disk_key;
4601179e29e4SChris Mason 		u64 offset;
4602179e29e4SChris Mason 
4603179e29e4SChris Mason 		btrfs_item_key(leaf, &disk_key, slot);
4604179e29e4SChris Mason 
4605179e29e4SChris Mason 		if (btrfs_disk_key_type(&disk_key) == BTRFS_EXTENT_DATA_KEY) {
4606179e29e4SChris Mason 			unsigned long ptr;
4607179e29e4SChris Mason 			struct btrfs_file_extent_item *fi;
4608179e29e4SChris Mason 
4609179e29e4SChris Mason 			fi = btrfs_item_ptr(leaf, slot,
4610179e29e4SChris Mason 					    struct btrfs_file_extent_item);
4611179e29e4SChris Mason 			fi = (struct btrfs_file_extent_item *)(
4612179e29e4SChris Mason 			     (unsigned long)fi - size_diff);
4613179e29e4SChris Mason 
4614179e29e4SChris Mason 			if (btrfs_file_extent_type(leaf, fi) ==
4615179e29e4SChris Mason 			    BTRFS_FILE_EXTENT_INLINE) {
4616179e29e4SChris Mason 				ptr = btrfs_item_ptr_offset(leaf, slot);
4617179e29e4SChris Mason 				memmove_extent_buffer(leaf, ptr,
4618179e29e4SChris Mason 				      (unsigned long)fi,
46197ec20afbSDavid Sterba 				      BTRFS_FILE_EXTENT_INLINE_DATA_START);
4620179e29e4SChris Mason 			}
4621179e29e4SChris Mason 		}
4622179e29e4SChris Mason 
46233d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
46243d9ec8c4SNikolay Borisov 			      data_end + size_diff, BTRFS_LEAF_DATA_OFFSET +
4625179e29e4SChris Mason 			      data_end, old_data_start - data_end);
4626179e29e4SChris Mason 
4627179e29e4SChris Mason 		offset = btrfs_disk_key_offset(&disk_key);
4628179e29e4SChris Mason 		btrfs_set_disk_key_offset(&disk_key, offset + size_diff);
4629179e29e4SChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot);
4630179e29e4SChris Mason 		if (slot == 0)
46310b246afaSJeff Mahoney 			fixup_low_keys(fs_info, path, &disk_key, 1);
4632179e29e4SChris Mason 	}
46335f39d397SChris Mason 
4634dd3cc16bSRoss Kirk 	item = btrfs_item_nr(slot);
46355f39d397SChris Mason 	btrfs_set_item_size(leaf, item, new_size);
46365f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
4637b18c6685SChris Mason 
46382ff7e61eSJeff Mahoney 	if (btrfs_leaf_free_space(fs_info, leaf) < 0) {
4639a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
4640b18c6685SChris Mason 		BUG();
46415f39d397SChris Mason 	}
4642b18c6685SChris Mason }
4643b18c6685SChris Mason 
4644d352ac68SChris Mason /*
46458f69dbd2SStefan Behrens  * make the item pointed to by the path bigger, data_size is the added size.
4646d352ac68SChris Mason  */
46472ff7e61eSJeff Mahoney void btrfs_extend_item(struct btrfs_fs_info *fs_info, struct btrfs_path *path,
46485f39d397SChris Mason 		       u32 data_size)
46496567e837SChris Mason {
46506567e837SChris Mason 	int slot;
46515f39d397SChris Mason 	struct extent_buffer *leaf;
46525f39d397SChris Mason 	struct btrfs_item *item;
46536567e837SChris Mason 	u32 nritems;
46546567e837SChris Mason 	unsigned int data_end;
46556567e837SChris Mason 	unsigned int old_data;
46566567e837SChris Mason 	unsigned int old_size;
46576567e837SChris Mason 	int i;
4658cfed81a0SChris Mason 	struct btrfs_map_token token;
4659cfed81a0SChris Mason 
4660cfed81a0SChris Mason 	btrfs_init_map_token(&token);
46616567e837SChris Mason 
46625f39d397SChris Mason 	leaf = path->nodes[0];
46636567e837SChris Mason 
46645f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
46652ff7e61eSJeff Mahoney 	data_end = leaf_data_end(fs_info, leaf);
46666567e837SChris Mason 
46672ff7e61eSJeff Mahoney 	if (btrfs_leaf_free_space(fs_info, leaf) < data_size) {
4668a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
46696567e837SChris Mason 		BUG();
46705f39d397SChris Mason 	}
46716567e837SChris Mason 	slot = path->slots[0];
46725f39d397SChris Mason 	old_data = btrfs_item_end_nr(leaf, slot);
46736567e837SChris Mason 
46746567e837SChris Mason 	BUG_ON(slot < 0);
46753326d1b0SChris Mason 	if (slot >= nritems) {
4676a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
46770b246afaSJeff Mahoney 		btrfs_crit(fs_info, "slot %d too large, nritems %d",
4678d397712bSChris Mason 			   slot, nritems);
46793326d1b0SChris Mason 		BUG_ON(1);
46803326d1b0SChris Mason 	}
46816567e837SChris Mason 
46826567e837SChris Mason 	/*
46836567e837SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
46846567e837SChris Mason 	 */
46856567e837SChris Mason 	/* first correct the data pointers */
46866567e837SChris Mason 	for (i = slot; i < nritems; i++) {
46875f39d397SChris Mason 		u32 ioff;
4688dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
4689db94535dSChris Mason 
4690cfed81a0SChris Mason 		ioff = btrfs_token_item_offset(leaf, item, &token);
4691cfed81a0SChris Mason 		btrfs_set_token_item_offset(leaf, item,
4692cfed81a0SChris Mason 					    ioff - data_size, &token);
46936567e837SChris Mason 	}
46945f39d397SChris Mason 
46956567e837SChris Mason 	/* shift the data */
46963d9ec8c4SNikolay Borisov 	memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
46973d9ec8c4SNikolay Borisov 		      data_end - data_size, BTRFS_LEAF_DATA_OFFSET +
46986567e837SChris Mason 		      data_end, old_data - data_end);
46995f39d397SChris Mason 
47006567e837SChris Mason 	data_end = old_data;
47015f39d397SChris Mason 	old_size = btrfs_item_size_nr(leaf, slot);
4702dd3cc16bSRoss Kirk 	item = btrfs_item_nr(slot);
47035f39d397SChris Mason 	btrfs_set_item_size(leaf, item, old_size + data_size);
47045f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
47056567e837SChris Mason 
47062ff7e61eSJeff Mahoney 	if (btrfs_leaf_free_space(fs_info, leaf) < 0) {
4707a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
47086567e837SChris Mason 		BUG();
47095f39d397SChris Mason 	}
47106567e837SChris Mason }
47116567e837SChris Mason 
471274123bd7SChris Mason /*
471344871b1bSChris Mason  * this is a helper for btrfs_insert_empty_items, the main goal here is
471444871b1bSChris Mason  * to save stack depth by doing the bulk of the work in a function
471544871b1bSChris Mason  * that doesn't call btrfs_search_slot
471674123bd7SChris Mason  */
4717afe5fea7STsutomu Itoh void setup_items_for_insert(struct btrfs_root *root, struct btrfs_path *path,
4718310712b2SOmar Sandoval 			    const struct btrfs_key *cpu_key, u32 *data_size,
471944871b1bSChris Mason 			    u32 total_data, u32 total_size, int nr)
4720be0e5c09SChris Mason {
47210b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
47225f39d397SChris Mason 	struct btrfs_item *item;
47239c58309dSChris Mason 	int i;
47247518a238SChris Mason 	u32 nritems;
4725be0e5c09SChris Mason 	unsigned int data_end;
4726e2fa7227SChris Mason 	struct btrfs_disk_key disk_key;
472744871b1bSChris Mason 	struct extent_buffer *leaf;
472844871b1bSChris Mason 	int slot;
4729cfed81a0SChris Mason 	struct btrfs_map_token token;
4730cfed81a0SChris Mason 
473124cdc847SFilipe Manana 	if (path->slots[0] == 0) {
473224cdc847SFilipe Manana 		btrfs_cpu_key_to_disk(&disk_key, cpu_key);
47330b246afaSJeff Mahoney 		fixup_low_keys(fs_info, path, &disk_key, 1);
473424cdc847SFilipe Manana 	}
473524cdc847SFilipe Manana 	btrfs_unlock_up_safe(path, 1);
473624cdc847SFilipe Manana 
4737cfed81a0SChris Mason 	btrfs_init_map_token(&token);
4738e2fa7227SChris Mason 
47395f39d397SChris Mason 	leaf = path->nodes[0];
474044871b1bSChris Mason 	slot = path->slots[0];
474174123bd7SChris Mason 
47425f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
47432ff7e61eSJeff Mahoney 	data_end = leaf_data_end(fs_info, leaf);
4744eb60ceacSChris Mason 
47452ff7e61eSJeff Mahoney 	if (btrfs_leaf_free_space(fs_info, leaf) < total_size) {
4746a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
47470b246afaSJeff Mahoney 		btrfs_crit(fs_info, "not enough freespace need %u have %d",
47482ff7e61eSJeff Mahoney 			   total_size, btrfs_leaf_free_space(fs_info, leaf));
4749be0e5c09SChris Mason 		BUG();
4750d4dbff95SChris Mason 	}
47515f39d397SChris Mason 
4752be0e5c09SChris Mason 	if (slot != nritems) {
47535f39d397SChris Mason 		unsigned int old_data = btrfs_item_end_nr(leaf, slot);
4754be0e5c09SChris Mason 
47555f39d397SChris Mason 		if (old_data < data_end) {
4756a4f78750SDavid Sterba 			btrfs_print_leaf(leaf);
47570b246afaSJeff Mahoney 			btrfs_crit(fs_info, "slot %d old_data %d data_end %d",
47585f39d397SChris Mason 				   slot, old_data, data_end);
47595f39d397SChris Mason 			BUG_ON(1);
47605f39d397SChris Mason 		}
4761be0e5c09SChris Mason 		/*
4762be0e5c09SChris Mason 		 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4763be0e5c09SChris Mason 		 */
4764be0e5c09SChris Mason 		/* first correct the data pointers */
47650783fcfcSChris Mason 		for (i = slot; i < nritems; i++) {
47665f39d397SChris Mason 			u32 ioff;
4767db94535dSChris Mason 
4768dd3cc16bSRoss Kirk 			item = btrfs_item_nr(i);
4769cfed81a0SChris Mason 			ioff = btrfs_token_item_offset(leaf, item, &token);
4770cfed81a0SChris Mason 			btrfs_set_token_item_offset(leaf, item,
4771cfed81a0SChris Mason 						    ioff - total_data, &token);
47720783fcfcSChris Mason 		}
4773be0e5c09SChris Mason 		/* shift the items */
47749c58309dSChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + nr),
47755f39d397SChris Mason 			      btrfs_item_nr_offset(slot),
47760783fcfcSChris Mason 			      (nritems - slot) * sizeof(struct btrfs_item));
4777be0e5c09SChris Mason 
4778be0e5c09SChris Mason 		/* shift the data */
47793d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
47803d9ec8c4SNikolay Borisov 			      data_end - total_data, BTRFS_LEAF_DATA_OFFSET +
4781be0e5c09SChris Mason 			      data_end, old_data - data_end);
4782be0e5c09SChris Mason 		data_end = old_data;
4783be0e5c09SChris Mason 	}
47845f39d397SChris Mason 
478562e2749eSChris Mason 	/* setup the item for the new data */
47869c58309dSChris Mason 	for (i = 0; i < nr; i++) {
47879c58309dSChris Mason 		btrfs_cpu_key_to_disk(&disk_key, cpu_key + i);
47889c58309dSChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot + i);
4789dd3cc16bSRoss Kirk 		item = btrfs_item_nr(slot + i);
4790cfed81a0SChris Mason 		btrfs_set_token_item_offset(leaf, item,
4791cfed81a0SChris Mason 					    data_end - data_size[i], &token);
47929c58309dSChris Mason 		data_end -= data_size[i];
4793cfed81a0SChris Mason 		btrfs_set_token_item_size(leaf, item, data_size[i], &token);
47949c58309dSChris Mason 	}
479544871b1bSChris Mason 
47969c58309dSChris Mason 	btrfs_set_header_nritems(leaf, nritems + nr);
4797b9473439SChris Mason 	btrfs_mark_buffer_dirty(leaf);
4798aa5d6bedSChris Mason 
47992ff7e61eSJeff Mahoney 	if (btrfs_leaf_free_space(fs_info, leaf) < 0) {
4800a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
4801be0e5c09SChris Mason 		BUG();
48025f39d397SChris Mason 	}
480344871b1bSChris Mason }
480444871b1bSChris Mason 
480544871b1bSChris Mason /*
480644871b1bSChris Mason  * Given a key and some data, insert items into the tree.
480744871b1bSChris Mason  * This does all the path init required, making room in the tree if needed.
480844871b1bSChris Mason  */
480944871b1bSChris Mason int btrfs_insert_empty_items(struct btrfs_trans_handle *trans,
481044871b1bSChris Mason 			    struct btrfs_root *root,
481144871b1bSChris Mason 			    struct btrfs_path *path,
4812310712b2SOmar Sandoval 			    const struct btrfs_key *cpu_key, u32 *data_size,
481344871b1bSChris Mason 			    int nr)
481444871b1bSChris Mason {
481544871b1bSChris Mason 	int ret = 0;
481644871b1bSChris Mason 	int slot;
481744871b1bSChris Mason 	int i;
481844871b1bSChris Mason 	u32 total_size = 0;
481944871b1bSChris Mason 	u32 total_data = 0;
482044871b1bSChris Mason 
482144871b1bSChris Mason 	for (i = 0; i < nr; i++)
482244871b1bSChris Mason 		total_data += data_size[i];
482344871b1bSChris Mason 
482444871b1bSChris Mason 	total_size = total_data + (nr * sizeof(struct btrfs_item));
482544871b1bSChris Mason 	ret = btrfs_search_slot(trans, root, cpu_key, path, total_size, 1);
482644871b1bSChris Mason 	if (ret == 0)
482744871b1bSChris Mason 		return -EEXIST;
482844871b1bSChris Mason 	if (ret < 0)
4829143bede5SJeff Mahoney 		return ret;
483044871b1bSChris Mason 
483144871b1bSChris Mason 	slot = path->slots[0];
483244871b1bSChris Mason 	BUG_ON(slot < 0);
483344871b1bSChris Mason 
4834afe5fea7STsutomu Itoh 	setup_items_for_insert(root, path, cpu_key, data_size,
483544871b1bSChris Mason 			       total_data, total_size, nr);
4836143bede5SJeff Mahoney 	return 0;
483762e2749eSChris Mason }
483862e2749eSChris Mason 
483962e2749eSChris Mason /*
484062e2749eSChris Mason  * Given a key and some data, insert an item into the tree.
484162e2749eSChris Mason  * This does all the path init required, making room in the tree if needed.
484262e2749eSChris Mason  */
4843310712b2SOmar Sandoval int btrfs_insert_item(struct btrfs_trans_handle *trans, struct btrfs_root *root,
4844310712b2SOmar Sandoval 		      const struct btrfs_key *cpu_key, void *data,
4845310712b2SOmar Sandoval 		      u32 data_size)
484662e2749eSChris Mason {
484762e2749eSChris Mason 	int ret = 0;
48482c90e5d6SChris Mason 	struct btrfs_path *path;
48495f39d397SChris Mason 	struct extent_buffer *leaf;
48505f39d397SChris Mason 	unsigned long ptr;
485162e2749eSChris Mason 
48522c90e5d6SChris Mason 	path = btrfs_alloc_path();
4853db5b493aSTsutomu Itoh 	if (!path)
4854db5b493aSTsutomu Itoh 		return -ENOMEM;
48552c90e5d6SChris Mason 	ret = btrfs_insert_empty_item(trans, root, path, cpu_key, data_size);
485662e2749eSChris Mason 	if (!ret) {
48575f39d397SChris Mason 		leaf = path->nodes[0];
48585f39d397SChris Mason 		ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
48595f39d397SChris Mason 		write_extent_buffer(leaf, data, ptr, data_size);
48605f39d397SChris Mason 		btrfs_mark_buffer_dirty(leaf);
486162e2749eSChris Mason 	}
48622c90e5d6SChris Mason 	btrfs_free_path(path);
4863aa5d6bedSChris Mason 	return ret;
4864be0e5c09SChris Mason }
4865be0e5c09SChris Mason 
486674123bd7SChris Mason /*
48675de08d7dSChris Mason  * delete the pointer from a given node.
486874123bd7SChris Mason  *
4869d352ac68SChris Mason  * the tree should have been previously balanced so the deletion does not
4870d352ac68SChris Mason  * empty a node.
487174123bd7SChris Mason  */
4872afe5fea7STsutomu Itoh static void del_ptr(struct btrfs_root *root, struct btrfs_path *path,
4873afe5fea7STsutomu Itoh 		    int level, int slot)
4874be0e5c09SChris Mason {
48750b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
48765f39d397SChris Mason 	struct extent_buffer *parent = path->nodes[level];
48777518a238SChris Mason 	u32 nritems;
4878f3ea38daSJan Schmidt 	int ret;
4879be0e5c09SChris Mason 
48805f39d397SChris Mason 	nritems = btrfs_header_nritems(parent);
4881be0e5c09SChris Mason 	if (slot != nritems - 1) {
4882bf1d3425SDavid Sterba 		if (level) {
4883bf1d3425SDavid Sterba 			ret = tree_mod_log_insert_move(parent, slot, slot + 1,
4884a446a979SDavid Sterba 					nritems - slot - 1);
4885bf1d3425SDavid Sterba 			BUG_ON(ret < 0);
4886bf1d3425SDavid Sterba 		}
48875f39d397SChris Mason 		memmove_extent_buffer(parent,
48885f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot),
48895f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot + 1),
4890d6025579SChris Mason 			      sizeof(struct btrfs_key_ptr) *
4891d6025579SChris Mason 			      (nritems - slot - 1));
489257ba86c0SChris Mason 	} else if (level) {
4893e09c2efeSDavid Sterba 		ret = tree_mod_log_insert_key(parent, slot, MOD_LOG_KEY_REMOVE,
4894e09c2efeSDavid Sterba 				GFP_NOFS);
489557ba86c0SChris Mason 		BUG_ON(ret < 0);
4896be0e5c09SChris Mason 	}
4897f3ea38daSJan Schmidt 
48987518a238SChris Mason 	nritems--;
48995f39d397SChris Mason 	btrfs_set_header_nritems(parent, nritems);
49007518a238SChris Mason 	if (nritems == 0 && parent == root->node) {
49015f39d397SChris Mason 		BUG_ON(btrfs_header_level(root->node) != 1);
4902eb60ceacSChris Mason 		/* just turn the root into a leaf and break */
49035f39d397SChris Mason 		btrfs_set_header_level(root->node, 0);
4904bb803951SChris Mason 	} else if (slot == 0) {
49055f39d397SChris Mason 		struct btrfs_disk_key disk_key;
49065f39d397SChris Mason 
49075f39d397SChris Mason 		btrfs_node_key(parent, &disk_key, 0);
49080b246afaSJeff Mahoney 		fixup_low_keys(fs_info, path, &disk_key, level + 1);
4909be0e5c09SChris Mason 	}
4910d6025579SChris Mason 	btrfs_mark_buffer_dirty(parent);
4911be0e5c09SChris Mason }
4912be0e5c09SChris Mason 
491374123bd7SChris Mason /*
4914323ac95bSChris Mason  * a helper function to delete the leaf pointed to by path->slots[1] and
49155d4f98a2SYan Zheng  * path->nodes[1].
4916323ac95bSChris Mason  *
4917323ac95bSChris Mason  * This deletes the pointer in path->nodes[1] and frees the leaf
4918323ac95bSChris Mason  * block extent.  zero is returned if it all worked out, < 0 otherwise.
4919323ac95bSChris Mason  *
4920323ac95bSChris Mason  * The path must have already been setup for deleting the leaf, including
4921323ac95bSChris Mason  * all the proper balancing.  path->nodes[1] must be locked.
4922323ac95bSChris Mason  */
4923143bede5SJeff Mahoney static noinline void btrfs_del_leaf(struct btrfs_trans_handle *trans,
4924323ac95bSChris Mason 				    struct btrfs_root *root,
49255d4f98a2SYan Zheng 				    struct btrfs_path *path,
49265d4f98a2SYan Zheng 				    struct extent_buffer *leaf)
4927323ac95bSChris Mason {
49285d4f98a2SYan Zheng 	WARN_ON(btrfs_header_generation(leaf) != trans->transid);
4929afe5fea7STsutomu Itoh 	del_ptr(root, path, 1, path->slots[1]);
4930323ac95bSChris Mason 
49314d081c41SChris Mason 	/*
49324d081c41SChris Mason 	 * btrfs_free_extent is expensive, we want to make sure we
49334d081c41SChris Mason 	 * aren't holding any locks when we call it
49344d081c41SChris Mason 	 */
49354d081c41SChris Mason 	btrfs_unlock_up_safe(path, 0);
49364d081c41SChris Mason 
4937f0486c68SYan, Zheng 	root_sub_used(root, leaf->len);
4938f0486c68SYan, Zheng 
49393083ee2eSJosef Bacik 	extent_buffer_get(leaf);
49405581a51aSJan Schmidt 	btrfs_free_tree_block(trans, root, leaf, 0, 1);
49413083ee2eSJosef Bacik 	free_extent_buffer_stale(leaf);
4942323ac95bSChris Mason }
4943323ac95bSChris Mason /*
494474123bd7SChris Mason  * delete the item at the leaf level in path.  If that empties
494574123bd7SChris Mason  * the leaf, remove it from the tree
494674123bd7SChris Mason  */
494785e21bacSChris Mason int btrfs_del_items(struct btrfs_trans_handle *trans, struct btrfs_root *root,
494885e21bacSChris Mason 		    struct btrfs_path *path, int slot, int nr)
4949be0e5c09SChris Mason {
49500b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
49515f39d397SChris Mason 	struct extent_buffer *leaf;
49525f39d397SChris Mason 	struct btrfs_item *item;
4953ce0eac2aSAlexandru Moise 	u32 last_off;
4954ce0eac2aSAlexandru Moise 	u32 dsize = 0;
4955aa5d6bedSChris Mason 	int ret = 0;
4956aa5d6bedSChris Mason 	int wret;
495785e21bacSChris Mason 	int i;
49587518a238SChris Mason 	u32 nritems;
4959cfed81a0SChris Mason 	struct btrfs_map_token token;
4960cfed81a0SChris Mason 
4961cfed81a0SChris Mason 	btrfs_init_map_token(&token);
4962be0e5c09SChris Mason 
49635f39d397SChris Mason 	leaf = path->nodes[0];
496485e21bacSChris Mason 	last_off = btrfs_item_offset_nr(leaf, slot + nr - 1);
496585e21bacSChris Mason 
496685e21bacSChris Mason 	for (i = 0; i < nr; i++)
496785e21bacSChris Mason 		dsize += btrfs_item_size_nr(leaf, slot + i);
496885e21bacSChris Mason 
49695f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
4970be0e5c09SChris Mason 
497185e21bacSChris Mason 	if (slot + nr != nritems) {
49722ff7e61eSJeff Mahoney 		int data_end = leaf_data_end(fs_info, leaf);
49735f39d397SChris Mason 
49743d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
4975d6025579SChris Mason 			      data_end + dsize,
49763d9ec8c4SNikolay Borisov 			      BTRFS_LEAF_DATA_OFFSET + data_end,
497785e21bacSChris Mason 			      last_off - data_end);
49785f39d397SChris Mason 
497985e21bacSChris Mason 		for (i = slot + nr; i < nritems; i++) {
49805f39d397SChris Mason 			u32 ioff;
4981db94535dSChris Mason 
4982dd3cc16bSRoss Kirk 			item = btrfs_item_nr(i);
4983cfed81a0SChris Mason 			ioff = btrfs_token_item_offset(leaf, item, &token);
4984cfed81a0SChris Mason 			btrfs_set_token_item_offset(leaf, item,
4985cfed81a0SChris Mason 						    ioff + dsize, &token);
49860783fcfcSChris Mason 		}
4987db94535dSChris Mason 
49885f39d397SChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot),
498985e21bacSChris Mason 			      btrfs_item_nr_offset(slot + nr),
49900783fcfcSChris Mason 			      sizeof(struct btrfs_item) *
499185e21bacSChris Mason 			      (nritems - slot - nr));
4992be0e5c09SChris Mason 	}
499385e21bacSChris Mason 	btrfs_set_header_nritems(leaf, nritems - nr);
499485e21bacSChris Mason 	nritems -= nr;
49955f39d397SChris Mason 
499674123bd7SChris Mason 	/* delete the leaf if we've emptied it */
49977518a238SChris Mason 	if (nritems == 0) {
49985f39d397SChris Mason 		if (leaf == root->node) {
49995f39d397SChris Mason 			btrfs_set_header_level(leaf, 0);
50009a8dd150SChris Mason 		} else {
5001f0486c68SYan, Zheng 			btrfs_set_path_blocking(path);
50027c302b49SDavid Sterba 			clean_tree_block(fs_info, leaf);
5003143bede5SJeff Mahoney 			btrfs_del_leaf(trans, root, path, leaf);
50049a8dd150SChris Mason 		}
5005be0e5c09SChris Mason 	} else {
50067518a238SChris Mason 		int used = leaf_space_used(leaf, 0, nritems);
5007aa5d6bedSChris Mason 		if (slot == 0) {
50085f39d397SChris Mason 			struct btrfs_disk_key disk_key;
50095f39d397SChris Mason 
50105f39d397SChris Mason 			btrfs_item_key(leaf, &disk_key, 0);
50110b246afaSJeff Mahoney 			fixup_low_keys(fs_info, path, &disk_key, 1);
5012aa5d6bedSChris Mason 		}
5013aa5d6bedSChris Mason 
501474123bd7SChris Mason 		/* delete the leaf if it is mostly empty */
50150b246afaSJeff Mahoney 		if (used < BTRFS_LEAF_DATA_SIZE(fs_info) / 3) {
5016be0e5c09SChris Mason 			/* push_leaf_left fixes the path.
5017be0e5c09SChris Mason 			 * make sure the path still points to our leaf
5018be0e5c09SChris Mason 			 * for possible call to del_ptr below
5019be0e5c09SChris Mason 			 */
50204920c9acSChris Mason 			slot = path->slots[1];
50215f39d397SChris Mason 			extent_buffer_get(leaf);
50225f39d397SChris Mason 
5023b9473439SChris Mason 			btrfs_set_path_blocking(path);
502499d8f83cSChris Mason 			wret = push_leaf_left(trans, root, path, 1, 1,
502599d8f83cSChris Mason 					      1, (u32)-1);
502654aa1f4dSChris Mason 			if (wret < 0 && wret != -ENOSPC)
5027aa5d6bedSChris Mason 				ret = wret;
50285f39d397SChris Mason 
50295f39d397SChris Mason 			if (path->nodes[0] == leaf &&
50305f39d397SChris Mason 			    btrfs_header_nritems(leaf)) {
503199d8f83cSChris Mason 				wret = push_leaf_right(trans, root, path, 1,
503299d8f83cSChris Mason 						       1, 1, 0);
503354aa1f4dSChris Mason 				if (wret < 0 && wret != -ENOSPC)
5034aa5d6bedSChris Mason 					ret = wret;
5035aa5d6bedSChris Mason 			}
50365f39d397SChris Mason 
50375f39d397SChris Mason 			if (btrfs_header_nritems(leaf) == 0) {
5038323ac95bSChris Mason 				path->slots[1] = slot;
5039143bede5SJeff Mahoney 				btrfs_del_leaf(trans, root, path, leaf);
50405f39d397SChris Mason 				free_extent_buffer(leaf);
5041143bede5SJeff Mahoney 				ret = 0;
50425de08d7dSChris Mason 			} else {
5043925baeddSChris Mason 				/* if we're still in the path, make sure
5044925baeddSChris Mason 				 * we're dirty.  Otherwise, one of the
5045925baeddSChris Mason 				 * push_leaf functions must have already
5046925baeddSChris Mason 				 * dirtied this buffer
5047925baeddSChris Mason 				 */
5048925baeddSChris Mason 				if (path->nodes[0] == leaf)
50495f39d397SChris Mason 					btrfs_mark_buffer_dirty(leaf);
50505f39d397SChris Mason 				free_extent_buffer(leaf);
5051be0e5c09SChris Mason 			}
5052d5719762SChris Mason 		} else {
50535f39d397SChris Mason 			btrfs_mark_buffer_dirty(leaf);
5054be0e5c09SChris Mason 		}
50559a8dd150SChris Mason 	}
5056aa5d6bedSChris Mason 	return ret;
50579a8dd150SChris Mason }
50589a8dd150SChris Mason 
505997571fd0SChris Mason /*
5060925baeddSChris Mason  * search the tree again to find a leaf with lesser keys
50617bb86316SChris Mason  * returns 0 if it found something or 1 if there are no lesser leaves.
50627bb86316SChris Mason  * returns < 0 on io errors.
5063d352ac68SChris Mason  *
5064d352ac68SChris Mason  * This may release the path, and so you may lose any locks held at the
5065d352ac68SChris Mason  * time you call it.
50667bb86316SChris Mason  */
506716e7549fSJosef Bacik int btrfs_prev_leaf(struct btrfs_root *root, struct btrfs_path *path)
50687bb86316SChris Mason {
5069925baeddSChris Mason 	struct btrfs_key key;
5070925baeddSChris Mason 	struct btrfs_disk_key found_key;
5071925baeddSChris Mason 	int ret;
50727bb86316SChris Mason 
5073925baeddSChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, 0);
5074925baeddSChris Mason 
5075e8b0d724SFilipe David Borba Manana 	if (key.offset > 0) {
5076925baeddSChris Mason 		key.offset--;
5077e8b0d724SFilipe David Borba Manana 	} else if (key.type > 0) {
5078925baeddSChris Mason 		key.type--;
5079e8b0d724SFilipe David Borba Manana 		key.offset = (u64)-1;
5080e8b0d724SFilipe David Borba Manana 	} else if (key.objectid > 0) {
5081925baeddSChris Mason 		key.objectid--;
5082e8b0d724SFilipe David Borba Manana 		key.type = (u8)-1;
5083e8b0d724SFilipe David Borba Manana 		key.offset = (u64)-1;
5084e8b0d724SFilipe David Borba Manana 	} else {
50857bb86316SChris Mason 		return 1;
5086e8b0d724SFilipe David Borba Manana 	}
50877bb86316SChris Mason 
5088b3b4aa74SDavid Sterba 	btrfs_release_path(path);
5089925baeddSChris Mason 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5090925baeddSChris Mason 	if (ret < 0)
5091925baeddSChris Mason 		return ret;
5092925baeddSChris Mason 	btrfs_item_key(path->nodes[0], &found_key, 0);
5093925baeddSChris Mason 	ret = comp_keys(&found_key, &key);
5094337c6f68SFilipe Manana 	/*
5095337c6f68SFilipe Manana 	 * We might have had an item with the previous key in the tree right
5096337c6f68SFilipe Manana 	 * before we released our path. And after we released our path, that
5097337c6f68SFilipe Manana 	 * item might have been pushed to the first slot (0) of the leaf we
5098337c6f68SFilipe Manana 	 * were holding due to a tree balance. Alternatively, an item with the
5099337c6f68SFilipe Manana 	 * previous key can exist as the only element of a leaf (big fat item).
5100337c6f68SFilipe Manana 	 * Therefore account for these 2 cases, so that our callers (like
5101337c6f68SFilipe Manana 	 * btrfs_previous_item) don't miss an existing item with a key matching
5102337c6f68SFilipe Manana 	 * the previous key we computed above.
5103337c6f68SFilipe Manana 	 */
5104337c6f68SFilipe Manana 	if (ret <= 0)
51057bb86316SChris Mason 		return 0;
5106925baeddSChris Mason 	return 1;
51077bb86316SChris Mason }
51087bb86316SChris Mason 
51093f157a2fSChris Mason /*
51103f157a2fSChris Mason  * A helper function to walk down the tree starting at min_key, and looking
5111de78b51aSEric Sandeen  * for nodes or leaves that are have a minimum transaction id.
5112de78b51aSEric Sandeen  * This is used by the btree defrag code, and tree logging
51133f157a2fSChris Mason  *
51143f157a2fSChris Mason  * This does not cow, but it does stuff the starting key it finds back
51153f157a2fSChris Mason  * into min_key, so you can call btrfs_search_slot with cow=1 on the
51163f157a2fSChris Mason  * key and get a writable path.
51173f157a2fSChris Mason  *
51183f157a2fSChris Mason  * This honors path->lowest_level to prevent descent past a given level
51193f157a2fSChris Mason  * of the tree.
51203f157a2fSChris Mason  *
5121d352ac68SChris Mason  * min_trans indicates the oldest transaction that you are interested
5122d352ac68SChris Mason  * in walking through.  Any nodes or leaves older than min_trans are
5123d352ac68SChris Mason  * skipped over (without reading them).
5124d352ac68SChris Mason  *
51253f157a2fSChris Mason  * returns zero if something useful was found, < 0 on error and 1 if there
51263f157a2fSChris Mason  * was nothing in the tree that matched the search criteria.
51273f157a2fSChris Mason  */
51283f157a2fSChris Mason int btrfs_search_forward(struct btrfs_root *root, struct btrfs_key *min_key,
5129de78b51aSEric Sandeen 			 struct btrfs_path *path,
51303f157a2fSChris Mason 			 u64 min_trans)
51313f157a2fSChris Mason {
51322ff7e61eSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
51333f157a2fSChris Mason 	struct extent_buffer *cur;
51343f157a2fSChris Mason 	struct btrfs_key found_key;
51353f157a2fSChris Mason 	int slot;
51369652480bSYan 	int sret;
51373f157a2fSChris Mason 	u32 nritems;
51383f157a2fSChris Mason 	int level;
51393f157a2fSChris Mason 	int ret = 1;
5140f98de9b9SFilipe Manana 	int keep_locks = path->keep_locks;
51413f157a2fSChris Mason 
5142f98de9b9SFilipe Manana 	path->keep_locks = 1;
51433f157a2fSChris Mason again:
5144bd681513SChris Mason 	cur = btrfs_read_lock_root_node(root);
51453f157a2fSChris Mason 	level = btrfs_header_level(cur);
5146e02119d5SChris Mason 	WARN_ON(path->nodes[level]);
51473f157a2fSChris Mason 	path->nodes[level] = cur;
5148bd681513SChris Mason 	path->locks[level] = BTRFS_READ_LOCK;
51493f157a2fSChris Mason 
51503f157a2fSChris Mason 	if (btrfs_header_generation(cur) < min_trans) {
51513f157a2fSChris Mason 		ret = 1;
51523f157a2fSChris Mason 		goto out;
51533f157a2fSChris Mason 	}
51543f157a2fSChris Mason 	while (1) {
51553f157a2fSChris Mason 		nritems = btrfs_header_nritems(cur);
51563f157a2fSChris Mason 		level = btrfs_header_level(cur);
5157a74b35ecSNikolay Borisov 		sret = btrfs_bin_search(cur, min_key, level, &slot);
51583f157a2fSChris Mason 
5159323ac95bSChris Mason 		/* at the lowest level, we're done, setup the path and exit */
5160323ac95bSChris Mason 		if (level == path->lowest_level) {
5161e02119d5SChris Mason 			if (slot >= nritems)
5162e02119d5SChris Mason 				goto find_next_key;
51633f157a2fSChris Mason 			ret = 0;
51643f157a2fSChris Mason 			path->slots[level] = slot;
51653f157a2fSChris Mason 			btrfs_item_key_to_cpu(cur, &found_key, slot);
51663f157a2fSChris Mason 			goto out;
51673f157a2fSChris Mason 		}
51689652480bSYan 		if (sret && slot > 0)
51699652480bSYan 			slot--;
51703f157a2fSChris Mason 		/*
5171de78b51aSEric Sandeen 		 * check this node pointer against the min_trans parameters.
5172de78b51aSEric Sandeen 		 * If it is too old, old, skip to the next one.
51733f157a2fSChris Mason 		 */
51743f157a2fSChris Mason 		while (slot < nritems) {
51753f157a2fSChris Mason 			u64 gen;
5176e02119d5SChris Mason 
51773f157a2fSChris Mason 			gen = btrfs_node_ptr_generation(cur, slot);
51783f157a2fSChris Mason 			if (gen < min_trans) {
51793f157a2fSChris Mason 				slot++;
51803f157a2fSChris Mason 				continue;
51813f157a2fSChris Mason 			}
51823f157a2fSChris Mason 			break;
51833f157a2fSChris Mason 		}
5184e02119d5SChris Mason find_next_key:
51853f157a2fSChris Mason 		/*
51863f157a2fSChris Mason 		 * we didn't find a candidate key in this node, walk forward
51873f157a2fSChris Mason 		 * and find another one
51883f157a2fSChris Mason 		 */
51893f157a2fSChris Mason 		if (slot >= nritems) {
5190e02119d5SChris Mason 			path->slots[level] = slot;
5191b4ce94deSChris Mason 			btrfs_set_path_blocking(path);
5192e02119d5SChris Mason 			sret = btrfs_find_next_key(root, path, min_key, level,
5193de78b51aSEric Sandeen 						  min_trans);
5194e02119d5SChris Mason 			if (sret == 0) {
5195b3b4aa74SDavid Sterba 				btrfs_release_path(path);
51963f157a2fSChris Mason 				goto again;
51973f157a2fSChris Mason 			} else {
51983f157a2fSChris Mason 				goto out;
51993f157a2fSChris Mason 			}
52003f157a2fSChris Mason 		}
52013f157a2fSChris Mason 		/* save our key for returning back */
52023f157a2fSChris Mason 		btrfs_node_key_to_cpu(cur, &found_key, slot);
52033f157a2fSChris Mason 		path->slots[level] = slot;
52043f157a2fSChris Mason 		if (level == path->lowest_level) {
52053f157a2fSChris Mason 			ret = 0;
52063f157a2fSChris Mason 			goto out;
52073f157a2fSChris Mason 		}
5208b4ce94deSChris Mason 		btrfs_set_path_blocking(path);
52092ff7e61eSJeff Mahoney 		cur = read_node_slot(fs_info, cur, slot);
5210fb770ae4SLiu Bo 		if (IS_ERR(cur)) {
5211fb770ae4SLiu Bo 			ret = PTR_ERR(cur);
5212fb770ae4SLiu Bo 			goto out;
5213fb770ae4SLiu Bo 		}
52143f157a2fSChris Mason 
5215bd681513SChris Mason 		btrfs_tree_read_lock(cur);
5216b4ce94deSChris Mason 
5217bd681513SChris Mason 		path->locks[level - 1] = BTRFS_READ_LOCK;
52183f157a2fSChris Mason 		path->nodes[level - 1] = cur;
5219f7c79f30SChris Mason 		unlock_up(path, level, 1, 0, NULL);
5220bd681513SChris Mason 		btrfs_clear_path_blocking(path, NULL, 0);
52213f157a2fSChris Mason 	}
52223f157a2fSChris Mason out:
5223f98de9b9SFilipe Manana 	path->keep_locks = keep_locks;
5224f98de9b9SFilipe Manana 	if (ret == 0) {
5225f98de9b9SFilipe Manana 		btrfs_unlock_up_safe(path, path->lowest_level + 1);
5226b4ce94deSChris Mason 		btrfs_set_path_blocking(path);
5227f98de9b9SFilipe Manana 		memcpy(min_key, &found_key, sizeof(found_key));
5228f98de9b9SFilipe Manana 	}
52293f157a2fSChris Mason 	return ret;
52303f157a2fSChris Mason }
52313f157a2fSChris Mason 
52322ff7e61eSJeff Mahoney static int tree_move_down(struct btrfs_fs_info *fs_info,
52337069830aSAlexander Block 			   struct btrfs_path *path,
5234ab6a43e1SDavid Sterba 			   int *level)
52357069830aSAlexander Block {
5236fb770ae4SLiu Bo 	struct extent_buffer *eb;
5237fb770ae4SLiu Bo 
523874dd17fbSChris Mason 	BUG_ON(*level == 0);
52392ff7e61eSJeff Mahoney 	eb = read_node_slot(fs_info, path->nodes[*level], path->slots[*level]);
5240fb770ae4SLiu Bo 	if (IS_ERR(eb))
5241fb770ae4SLiu Bo 		return PTR_ERR(eb);
5242fb770ae4SLiu Bo 
5243fb770ae4SLiu Bo 	path->nodes[*level - 1] = eb;
52447069830aSAlexander Block 	path->slots[*level - 1] = 0;
52457069830aSAlexander Block 	(*level)--;
5246fb770ae4SLiu Bo 	return 0;
52477069830aSAlexander Block }
52487069830aSAlexander Block 
5249f1e30261SDavid Sterba static int tree_move_next_or_upnext(struct btrfs_path *path,
52507069830aSAlexander Block 				    int *level, int root_level)
52517069830aSAlexander Block {
52527069830aSAlexander Block 	int ret = 0;
52537069830aSAlexander Block 	int nritems;
52547069830aSAlexander Block 	nritems = btrfs_header_nritems(path->nodes[*level]);
52557069830aSAlexander Block 
52567069830aSAlexander Block 	path->slots[*level]++;
52577069830aSAlexander Block 
525874dd17fbSChris Mason 	while (path->slots[*level] >= nritems) {
52597069830aSAlexander Block 		if (*level == root_level)
52607069830aSAlexander Block 			return -1;
52617069830aSAlexander Block 
52627069830aSAlexander Block 		/* move upnext */
52637069830aSAlexander Block 		path->slots[*level] = 0;
52647069830aSAlexander Block 		free_extent_buffer(path->nodes[*level]);
52657069830aSAlexander Block 		path->nodes[*level] = NULL;
52667069830aSAlexander Block 		(*level)++;
52677069830aSAlexander Block 		path->slots[*level]++;
52687069830aSAlexander Block 
52697069830aSAlexander Block 		nritems = btrfs_header_nritems(path->nodes[*level]);
52707069830aSAlexander Block 		ret = 1;
52717069830aSAlexander Block 	}
52727069830aSAlexander Block 	return ret;
52737069830aSAlexander Block }
52747069830aSAlexander Block 
52757069830aSAlexander Block /*
52767069830aSAlexander Block  * Returns 1 if it had to move up and next. 0 is returned if it moved only next
52777069830aSAlexander Block  * or down.
52787069830aSAlexander Block  */
52792ff7e61eSJeff Mahoney static int tree_advance(struct btrfs_fs_info *fs_info,
52807069830aSAlexander Block 			struct btrfs_path *path,
52817069830aSAlexander Block 			int *level, int root_level,
52827069830aSAlexander Block 			int allow_down,
52837069830aSAlexander Block 			struct btrfs_key *key)
52847069830aSAlexander Block {
52857069830aSAlexander Block 	int ret;
52867069830aSAlexander Block 
52877069830aSAlexander Block 	if (*level == 0 || !allow_down) {
5288f1e30261SDavid Sterba 		ret = tree_move_next_or_upnext(path, level, root_level);
52897069830aSAlexander Block 	} else {
5290ab6a43e1SDavid Sterba 		ret = tree_move_down(fs_info, path, level);
52917069830aSAlexander Block 	}
52927069830aSAlexander Block 	if (ret >= 0) {
52937069830aSAlexander Block 		if (*level == 0)
52947069830aSAlexander Block 			btrfs_item_key_to_cpu(path->nodes[*level], key,
52957069830aSAlexander Block 					path->slots[*level]);
52967069830aSAlexander Block 		else
52977069830aSAlexander Block 			btrfs_node_key_to_cpu(path->nodes[*level], key,
52987069830aSAlexander Block 					path->slots[*level]);
52997069830aSAlexander Block 	}
53007069830aSAlexander Block 	return ret;
53017069830aSAlexander Block }
53027069830aSAlexander Block 
53032ff7e61eSJeff Mahoney static int tree_compare_item(struct btrfs_path *left_path,
53047069830aSAlexander Block 			     struct btrfs_path *right_path,
53057069830aSAlexander Block 			     char *tmp_buf)
53067069830aSAlexander Block {
53077069830aSAlexander Block 	int cmp;
53087069830aSAlexander Block 	int len1, len2;
53097069830aSAlexander Block 	unsigned long off1, off2;
53107069830aSAlexander Block 
53117069830aSAlexander Block 	len1 = btrfs_item_size_nr(left_path->nodes[0], left_path->slots[0]);
53127069830aSAlexander Block 	len2 = btrfs_item_size_nr(right_path->nodes[0], right_path->slots[0]);
53137069830aSAlexander Block 	if (len1 != len2)
53147069830aSAlexander Block 		return 1;
53157069830aSAlexander Block 
53167069830aSAlexander Block 	off1 = btrfs_item_ptr_offset(left_path->nodes[0], left_path->slots[0]);
53177069830aSAlexander Block 	off2 = btrfs_item_ptr_offset(right_path->nodes[0],
53187069830aSAlexander Block 				right_path->slots[0]);
53197069830aSAlexander Block 
53207069830aSAlexander Block 	read_extent_buffer(left_path->nodes[0], tmp_buf, off1, len1);
53217069830aSAlexander Block 
53227069830aSAlexander Block 	cmp = memcmp_extent_buffer(right_path->nodes[0], tmp_buf, off2, len1);
53237069830aSAlexander Block 	if (cmp)
53247069830aSAlexander Block 		return 1;
53257069830aSAlexander Block 	return 0;
53267069830aSAlexander Block }
53277069830aSAlexander Block 
53287069830aSAlexander Block #define ADVANCE 1
53297069830aSAlexander Block #define ADVANCE_ONLY_NEXT -1
53307069830aSAlexander Block 
53317069830aSAlexander Block /*
53327069830aSAlexander Block  * This function compares two trees and calls the provided callback for
53337069830aSAlexander Block  * every changed/new/deleted item it finds.
53347069830aSAlexander Block  * If shared tree blocks are encountered, whole subtrees are skipped, making
53357069830aSAlexander Block  * the compare pretty fast on snapshotted subvolumes.
53367069830aSAlexander Block  *
53377069830aSAlexander Block  * This currently works on commit roots only. As commit roots are read only,
53387069830aSAlexander Block  * we don't do any locking. The commit roots are protected with transactions.
53397069830aSAlexander Block  * Transactions are ended and rejoined when a commit is tried in between.
53407069830aSAlexander Block  *
53417069830aSAlexander Block  * This function checks for modifications done to the trees while comparing.
53427069830aSAlexander Block  * If it detects a change, it aborts immediately.
53437069830aSAlexander Block  */
53447069830aSAlexander Block int btrfs_compare_trees(struct btrfs_root *left_root,
53457069830aSAlexander Block 			struct btrfs_root *right_root,
53467069830aSAlexander Block 			btrfs_changed_cb_t changed_cb, void *ctx)
53477069830aSAlexander Block {
53480b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = left_root->fs_info;
53497069830aSAlexander Block 	int ret;
53507069830aSAlexander Block 	int cmp;
53517069830aSAlexander Block 	struct btrfs_path *left_path = NULL;
53527069830aSAlexander Block 	struct btrfs_path *right_path = NULL;
53537069830aSAlexander Block 	struct btrfs_key left_key;
53547069830aSAlexander Block 	struct btrfs_key right_key;
53557069830aSAlexander Block 	char *tmp_buf = NULL;
53567069830aSAlexander Block 	int left_root_level;
53577069830aSAlexander Block 	int right_root_level;
53587069830aSAlexander Block 	int left_level;
53597069830aSAlexander Block 	int right_level;
53607069830aSAlexander Block 	int left_end_reached;
53617069830aSAlexander Block 	int right_end_reached;
53627069830aSAlexander Block 	int advance_left;
53637069830aSAlexander Block 	int advance_right;
53647069830aSAlexander Block 	u64 left_blockptr;
53657069830aSAlexander Block 	u64 right_blockptr;
53666baa4293SFilipe Manana 	u64 left_gen;
53676baa4293SFilipe Manana 	u64 right_gen;
53687069830aSAlexander Block 
53697069830aSAlexander Block 	left_path = btrfs_alloc_path();
53707069830aSAlexander Block 	if (!left_path) {
53717069830aSAlexander Block 		ret = -ENOMEM;
53727069830aSAlexander Block 		goto out;
53737069830aSAlexander Block 	}
53747069830aSAlexander Block 	right_path = btrfs_alloc_path();
53757069830aSAlexander Block 	if (!right_path) {
53767069830aSAlexander Block 		ret = -ENOMEM;
53777069830aSAlexander Block 		goto out;
53787069830aSAlexander Block 	}
53797069830aSAlexander Block 
5380752ade68SMichal Hocko 	tmp_buf = kvmalloc(fs_info->nodesize, GFP_KERNEL);
53817069830aSAlexander Block 	if (!tmp_buf) {
53827069830aSAlexander Block 		ret = -ENOMEM;
53837069830aSAlexander Block 		goto out;
53847069830aSAlexander Block 	}
53857069830aSAlexander Block 
53867069830aSAlexander Block 	left_path->search_commit_root = 1;
53877069830aSAlexander Block 	left_path->skip_locking = 1;
53887069830aSAlexander Block 	right_path->search_commit_root = 1;
53897069830aSAlexander Block 	right_path->skip_locking = 1;
53907069830aSAlexander Block 
53917069830aSAlexander Block 	/*
53927069830aSAlexander Block 	 * Strategy: Go to the first items of both trees. Then do
53937069830aSAlexander Block 	 *
53947069830aSAlexander Block 	 * If both trees are at level 0
53957069830aSAlexander Block 	 *   Compare keys of current items
53967069830aSAlexander Block 	 *     If left < right treat left item as new, advance left tree
53977069830aSAlexander Block 	 *       and repeat
53987069830aSAlexander Block 	 *     If left > right treat right item as deleted, advance right tree
53997069830aSAlexander Block 	 *       and repeat
54007069830aSAlexander Block 	 *     If left == right do deep compare of items, treat as changed if
54017069830aSAlexander Block 	 *       needed, advance both trees and repeat
54027069830aSAlexander Block 	 * If both trees are at the same level but not at level 0
54037069830aSAlexander Block 	 *   Compare keys of current nodes/leafs
54047069830aSAlexander Block 	 *     If left < right advance left tree and repeat
54057069830aSAlexander Block 	 *     If left > right advance right tree and repeat
54067069830aSAlexander Block 	 *     If left == right compare blockptrs of the next nodes/leafs
54077069830aSAlexander Block 	 *       If they match advance both trees but stay at the same level
54087069830aSAlexander Block 	 *         and repeat
54097069830aSAlexander Block 	 *       If they don't match advance both trees while allowing to go
54107069830aSAlexander Block 	 *         deeper and repeat
54117069830aSAlexander Block 	 * If tree levels are different
54127069830aSAlexander Block 	 *   Advance the tree that needs it and repeat
54137069830aSAlexander Block 	 *
54147069830aSAlexander Block 	 * Advancing a tree means:
54157069830aSAlexander Block 	 *   If we are at level 0, try to go to the next slot. If that's not
54167069830aSAlexander Block 	 *   possible, go one level up and repeat. Stop when we found a level
54177069830aSAlexander Block 	 *   where we could go to the next slot. We may at this point be on a
54187069830aSAlexander Block 	 *   node or a leaf.
54197069830aSAlexander Block 	 *
54207069830aSAlexander Block 	 *   If we are not at level 0 and not on shared tree blocks, go one
54217069830aSAlexander Block 	 *   level deeper.
54227069830aSAlexander Block 	 *
54237069830aSAlexander Block 	 *   If we are not at level 0 and on shared tree blocks, go one slot to
54247069830aSAlexander Block 	 *   the right if possible or go up and right.
54257069830aSAlexander Block 	 */
54267069830aSAlexander Block 
54270b246afaSJeff Mahoney 	down_read(&fs_info->commit_root_sem);
54287069830aSAlexander Block 	left_level = btrfs_header_level(left_root->commit_root);
54297069830aSAlexander Block 	left_root_level = left_level;
54307069830aSAlexander Block 	left_path->nodes[left_level] = left_root->commit_root;
54317069830aSAlexander Block 	extent_buffer_get(left_path->nodes[left_level]);
54327069830aSAlexander Block 
54337069830aSAlexander Block 	right_level = btrfs_header_level(right_root->commit_root);
54347069830aSAlexander Block 	right_root_level = right_level;
54357069830aSAlexander Block 	right_path->nodes[right_level] = right_root->commit_root;
54367069830aSAlexander Block 	extent_buffer_get(right_path->nodes[right_level]);
54370b246afaSJeff Mahoney 	up_read(&fs_info->commit_root_sem);
54387069830aSAlexander Block 
54397069830aSAlexander Block 	if (left_level == 0)
54407069830aSAlexander Block 		btrfs_item_key_to_cpu(left_path->nodes[left_level],
54417069830aSAlexander Block 				&left_key, left_path->slots[left_level]);
54427069830aSAlexander Block 	else
54437069830aSAlexander Block 		btrfs_node_key_to_cpu(left_path->nodes[left_level],
54447069830aSAlexander Block 				&left_key, left_path->slots[left_level]);
54457069830aSAlexander Block 	if (right_level == 0)
54467069830aSAlexander Block 		btrfs_item_key_to_cpu(right_path->nodes[right_level],
54477069830aSAlexander Block 				&right_key, right_path->slots[right_level]);
54487069830aSAlexander Block 	else
54497069830aSAlexander Block 		btrfs_node_key_to_cpu(right_path->nodes[right_level],
54507069830aSAlexander Block 				&right_key, right_path->slots[right_level]);
54517069830aSAlexander Block 
54527069830aSAlexander Block 	left_end_reached = right_end_reached = 0;
54537069830aSAlexander Block 	advance_left = advance_right = 0;
54547069830aSAlexander Block 
54557069830aSAlexander Block 	while (1) {
54567069830aSAlexander Block 		if (advance_left && !left_end_reached) {
54572ff7e61eSJeff Mahoney 			ret = tree_advance(fs_info, left_path, &left_level,
54587069830aSAlexander Block 					left_root_level,
54597069830aSAlexander Block 					advance_left != ADVANCE_ONLY_NEXT,
54607069830aSAlexander Block 					&left_key);
5461fb770ae4SLiu Bo 			if (ret == -1)
54627069830aSAlexander Block 				left_end_reached = ADVANCE;
5463fb770ae4SLiu Bo 			else if (ret < 0)
5464fb770ae4SLiu Bo 				goto out;
54657069830aSAlexander Block 			advance_left = 0;
54667069830aSAlexander Block 		}
54677069830aSAlexander Block 		if (advance_right && !right_end_reached) {
54682ff7e61eSJeff Mahoney 			ret = tree_advance(fs_info, right_path, &right_level,
54697069830aSAlexander Block 					right_root_level,
54707069830aSAlexander Block 					advance_right != ADVANCE_ONLY_NEXT,
54717069830aSAlexander Block 					&right_key);
5472fb770ae4SLiu Bo 			if (ret == -1)
54737069830aSAlexander Block 				right_end_reached = ADVANCE;
5474fb770ae4SLiu Bo 			else if (ret < 0)
5475fb770ae4SLiu Bo 				goto out;
54767069830aSAlexander Block 			advance_right = 0;
54777069830aSAlexander Block 		}
54787069830aSAlexander Block 
54797069830aSAlexander Block 		if (left_end_reached && right_end_reached) {
54807069830aSAlexander Block 			ret = 0;
54817069830aSAlexander Block 			goto out;
54827069830aSAlexander Block 		} else if (left_end_reached) {
54837069830aSAlexander Block 			if (right_level == 0) {
5484ee8c494fSNikolay Borisov 				ret = changed_cb(left_path, right_path,
54857069830aSAlexander Block 						&right_key,
54867069830aSAlexander Block 						BTRFS_COMPARE_TREE_DELETED,
54877069830aSAlexander Block 						ctx);
54887069830aSAlexander Block 				if (ret < 0)
54897069830aSAlexander Block 					goto out;
54907069830aSAlexander Block 			}
54917069830aSAlexander Block 			advance_right = ADVANCE;
54927069830aSAlexander Block 			continue;
54937069830aSAlexander Block 		} else if (right_end_reached) {
54947069830aSAlexander Block 			if (left_level == 0) {
5495ee8c494fSNikolay Borisov 				ret = changed_cb(left_path, right_path,
54967069830aSAlexander Block 						&left_key,
54977069830aSAlexander Block 						BTRFS_COMPARE_TREE_NEW,
54987069830aSAlexander Block 						ctx);
54997069830aSAlexander Block 				if (ret < 0)
55007069830aSAlexander Block 					goto out;
55017069830aSAlexander Block 			}
55027069830aSAlexander Block 			advance_left = ADVANCE;
55037069830aSAlexander Block 			continue;
55047069830aSAlexander Block 		}
55057069830aSAlexander Block 
55067069830aSAlexander Block 		if (left_level == 0 && right_level == 0) {
55077069830aSAlexander Block 			cmp = btrfs_comp_cpu_keys(&left_key, &right_key);
55087069830aSAlexander Block 			if (cmp < 0) {
5509ee8c494fSNikolay Borisov 				ret = changed_cb(left_path, right_path,
55107069830aSAlexander Block 						&left_key,
55117069830aSAlexander Block 						BTRFS_COMPARE_TREE_NEW,
55127069830aSAlexander Block 						ctx);
55137069830aSAlexander Block 				if (ret < 0)
55147069830aSAlexander Block 					goto out;
55157069830aSAlexander Block 				advance_left = ADVANCE;
55167069830aSAlexander Block 			} else if (cmp > 0) {
5517ee8c494fSNikolay Borisov 				ret = changed_cb(left_path, right_path,
55187069830aSAlexander Block 						&right_key,
55197069830aSAlexander Block 						BTRFS_COMPARE_TREE_DELETED,
55207069830aSAlexander Block 						ctx);
55217069830aSAlexander Block 				if (ret < 0)
55227069830aSAlexander Block 					goto out;
55237069830aSAlexander Block 				advance_right = ADVANCE;
55247069830aSAlexander Block 			} else {
5525b99d9a6aSFabian Frederick 				enum btrfs_compare_tree_result result;
5526ba5e8f2eSJosef Bacik 
552774dd17fbSChris Mason 				WARN_ON(!extent_buffer_uptodate(left_path->nodes[0]));
55282ff7e61eSJeff Mahoney 				ret = tree_compare_item(left_path, right_path,
55292ff7e61eSJeff Mahoney 							tmp_buf);
5530ba5e8f2eSJosef Bacik 				if (ret)
5531b99d9a6aSFabian Frederick 					result = BTRFS_COMPARE_TREE_CHANGED;
5532ba5e8f2eSJosef Bacik 				else
5533b99d9a6aSFabian Frederick 					result = BTRFS_COMPARE_TREE_SAME;
5534ee8c494fSNikolay Borisov 				ret = changed_cb(left_path, right_path,
5535b99d9a6aSFabian Frederick 						 &left_key, result, ctx);
55367069830aSAlexander Block 				if (ret < 0)
55377069830aSAlexander Block 					goto out;
55387069830aSAlexander Block 				advance_left = ADVANCE;
55397069830aSAlexander Block 				advance_right = ADVANCE;
55407069830aSAlexander Block 			}
55417069830aSAlexander Block 		} else if (left_level == right_level) {
55427069830aSAlexander Block 			cmp = btrfs_comp_cpu_keys(&left_key, &right_key);
55437069830aSAlexander Block 			if (cmp < 0) {
55447069830aSAlexander Block 				advance_left = ADVANCE;
55457069830aSAlexander Block 			} else if (cmp > 0) {
55467069830aSAlexander Block 				advance_right = ADVANCE;
55477069830aSAlexander Block 			} else {
55487069830aSAlexander Block 				left_blockptr = btrfs_node_blockptr(
55497069830aSAlexander Block 						left_path->nodes[left_level],
55507069830aSAlexander Block 						left_path->slots[left_level]);
55517069830aSAlexander Block 				right_blockptr = btrfs_node_blockptr(
55527069830aSAlexander Block 						right_path->nodes[right_level],
55537069830aSAlexander Block 						right_path->slots[right_level]);
55546baa4293SFilipe Manana 				left_gen = btrfs_node_ptr_generation(
55556baa4293SFilipe Manana 						left_path->nodes[left_level],
55566baa4293SFilipe Manana 						left_path->slots[left_level]);
55576baa4293SFilipe Manana 				right_gen = btrfs_node_ptr_generation(
55586baa4293SFilipe Manana 						right_path->nodes[right_level],
55596baa4293SFilipe Manana 						right_path->slots[right_level]);
55606baa4293SFilipe Manana 				if (left_blockptr == right_blockptr &&
55616baa4293SFilipe Manana 				    left_gen == right_gen) {
55627069830aSAlexander Block 					/*
55637069830aSAlexander Block 					 * As we're on a shared block, don't
55647069830aSAlexander Block 					 * allow to go deeper.
55657069830aSAlexander Block 					 */
55667069830aSAlexander Block 					advance_left = ADVANCE_ONLY_NEXT;
55677069830aSAlexander Block 					advance_right = ADVANCE_ONLY_NEXT;
55687069830aSAlexander Block 				} else {
55697069830aSAlexander Block 					advance_left = ADVANCE;
55707069830aSAlexander Block 					advance_right = ADVANCE;
55717069830aSAlexander Block 				}
55727069830aSAlexander Block 			}
55737069830aSAlexander Block 		} else if (left_level < right_level) {
55747069830aSAlexander Block 			advance_right = ADVANCE;
55757069830aSAlexander Block 		} else {
55767069830aSAlexander Block 			advance_left = ADVANCE;
55777069830aSAlexander Block 		}
55787069830aSAlexander Block 	}
55797069830aSAlexander Block 
55807069830aSAlexander Block out:
55817069830aSAlexander Block 	btrfs_free_path(left_path);
55827069830aSAlexander Block 	btrfs_free_path(right_path);
55838f282f71SDavid Sterba 	kvfree(tmp_buf);
55847069830aSAlexander Block 	return ret;
55857069830aSAlexander Block }
55867069830aSAlexander Block 
55873f157a2fSChris Mason /*
55883f157a2fSChris Mason  * this is similar to btrfs_next_leaf, but does not try to preserve
55893f157a2fSChris Mason  * and fixup the path.  It looks for and returns the next key in the
5590de78b51aSEric Sandeen  * tree based on the current path and the min_trans parameters.
55913f157a2fSChris Mason  *
55923f157a2fSChris Mason  * 0 is returned if another key is found, < 0 if there are any errors
55933f157a2fSChris Mason  * and 1 is returned if there are no higher keys in the tree
55943f157a2fSChris Mason  *
55953f157a2fSChris Mason  * path->keep_locks should be set to 1 on the search made before
55963f157a2fSChris Mason  * calling this function.
55973f157a2fSChris Mason  */
5598e7a84565SChris Mason int btrfs_find_next_key(struct btrfs_root *root, struct btrfs_path *path,
5599de78b51aSEric Sandeen 			struct btrfs_key *key, int level, u64 min_trans)
5600e7a84565SChris Mason {
5601e7a84565SChris Mason 	int slot;
5602e7a84565SChris Mason 	struct extent_buffer *c;
5603e7a84565SChris Mason 
5604934d375bSChris Mason 	WARN_ON(!path->keep_locks);
5605e7a84565SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
5606e7a84565SChris Mason 		if (!path->nodes[level])
5607e7a84565SChris Mason 			return 1;
5608e7a84565SChris Mason 
5609e7a84565SChris Mason 		slot = path->slots[level] + 1;
5610e7a84565SChris Mason 		c = path->nodes[level];
56113f157a2fSChris Mason next:
5612e7a84565SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
561333c66f43SYan Zheng 			int ret;
561433c66f43SYan Zheng 			int orig_lowest;
561533c66f43SYan Zheng 			struct btrfs_key cur_key;
561633c66f43SYan Zheng 			if (level + 1 >= BTRFS_MAX_LEVEL ||
561733c66f43SYan Zheng 			    !path->nodes[level + 1])
5618e7a84565SChris Mason 				return 1;
561933c66f43SYan Zheng 
562033c66f43SYan Zheng 			if (path->locks[level + 1]) {
562133c66f43SYan Zheng 				level++;
5622e7a84565SChris Mason 				continue;
5623e7a84565SChris Mason 			}
562433c66f43SYan Zheng 
562533c66f43SYan Zheng 			slot = btrfs_header_nritems(c) - 1;
562633c66f43SYan Zheng 			if (level == 0)
562733c66f43SYan Zheng 				btrfs_item_key_to_cpu(c, &cur_key, slot);
562833c66f43SYan Zheng 			else
562933c66f43SYan Zheng 				btrfs_node_key_to_cpu(c, &cur_key, slot);
563033c66f43SYan Zheng 
563133c66f43SYan Zheng 			orig_lowest = path->lowest_level;
5632b3b4aa74SDavid Sterba 			btrfs_release_path(path);
563333c66f43SYan Zheng 			path->lowest_level = level;
563433c66f43SYan Zheng 			ret = btrfs_search_slot(NULL, root, &cur_key, path,
563533c66f43SYan Zheng 						0, 0);
563633c66f43SYan Zheng 			path->lowest_level = orig_lowest;
563733c66f43SYan Zheng 			if (ret < 0)
563833c66f43SYan Zheng 				return ret;
563933c66f43SYan Zheng 
564033c66f43SYan Zheng 			c = path->nodes[level];
564133c66f43SYan Zheng 			slot = path->slots[level];
564233c66f43SYan Zheng 			if (ret == 0)
564333c66f43SYan Zheng 				slot++;
564433c66f43SYan Zheng 			goto next;
564533c66f43SYan Zheng 		}
564633c66f43SYan Zheng 
5647e7a84565SChris Mason 		if (level == 0)
5648e7a84565SChris Mason 			btrfs_item_key_to_cpu(c, key, slot);
56493f157a2fSChris Mason 		else {
56503f157a2fSChris Mason 			u64 gen = btrfs_node_ptr_generation(c, slot);
56513f157a2fSChris Mason 
56523f157a2fSChris Mason 			if (gen < min_trans) {
56533f157a2fSChris Mason 				slot++;
56543f157a2fSChris Mason 				goto next;
56553f157a2fSChris Mason 			}
5656e7a84565SChris Mason 			btrfs_node_key_to_cpu(c, key, slot);
56573f157a2fSChris Mason 		}
5658e7a84565SChris Mason 		return 0;
5659e7a84565SChris Mason 	}
5660e7a84565SChris Mason 	return 1;
5661e7a84565SChris Mason }
5662e7a84565SChris Mason 
56637bb86316SChris Mason /*
5664925baeddSChris Mason  * search the tree again to find a leaf with greater keys
56650f70abe2SChris Mason  * returns 0 if it found something or 1 if there are no greater leaves.
56660f70abe2SChris Mason  * returns < 0 on io errors.
566797571fd0SChris Mason  */
5668234b63a0SChris Mason int btrfs_next_leaf(struct btrfs_root *root, struct btrfs_path *path)
5669d97e63b6SChris Mason {
56703d7806ecSJan Schmidt 	return btrfs_next_old_leaf(root, path, 0);
56713d7806ecSJan Schmidt }
56723d7806ecSJan Schmidt 
56733d7806ecSJan Schmidt int btrfs_next_old_leaf(struct btrfs_root *root, struct btrfs_path *path,
56743d7806ecSJan Schmidt 			u64 time_seq)
56753d7806ecSJan Schmidt {
5676d97e63b6SChris Mason 	int slot;
56778e73f275SChris Mason 	int level;
56785f39d397SChris Mason 	struct extent_buffer *c;
56798e73f275SChris Mason 	struct extent_buffer *next;
5680925baeddSChris Mason 	struct btrfs_key key;
5681925baeddSChris Mason 	u32 nritems;
5682925baeddSChris Mason 	int ret;
56838e73f275SChris Mason 	int old_spinning = path->leave_spinning;
5684bd681513SChris Mason 	int next_rw_lock = 0;
5685925baeddSChris Mason 
5686925baeddSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
5687d397712bSChris Mason 	if (nritems == 0)
5688925baeddSChris Mason 		return 1;
5689925baeddSChris Mason 
56908e73f275SChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, nritems - 1);
56918e73f275SChris Mason again:
56928e73f275SChris Mason 	level = 1;
56938e73f275SChris Mason 	next = NULL;
5694bd681513SChris Mason 	next_rw_lock = 0;
5695b3b4aa74SDavid Sterba 	btrfs_release_path(path);
56968e73f275SChris Mason 
5697a2135011SChris Mason 	path->keep_locks = 1;
56988e73f275SChris Mason 	path->leave_spinning = 1;
56998e73f275SChris Mason 
57003d7806ecSJan Schmidt 	if (time_seq)
57013d7806ecSJan Schmidt 		ret = btrfs_search_old_slot(root, &key, path, time_seq);
57023d7806ecSJan Schmidt 	else
5703925baeddSChris Mason 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5704925baeddSChris Mason 	path->keep_locks = 0;
5705925baeddSChris Mason 
5706925baeddSChris Mason 	if (ret < 0)
5707925baeddSChris Mason 		return ret;
5708925baeddSChris Mason 
5709a2135011SChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
5710168fd7d2SChris Mason 	/*
5711168fd7d2SChris Mason 	 * by releasing the path above we dropped all our locks.  A balance
5712168fd7d2SChris Mason 	 * could have added more items next to the key that used to be
5713168fd7d2SChris Mason 	 * at the very end of the block.  So, check again here and
5714168fd7d2SChris Mason 	 * advance the path if there are now more items available.
5715168fd7d2SChris Mason 	 */
5716a2135011SChris Mason 	if (nritems > 0 && path->slots[0] < nritems - 1) {
5717e457afecSYan Zheng 		if (ret == 0)
5718168fd7d2SChris Mason 			path->slots[0]++;
57198e73f275SChris Mason 		ret = 0;
5720925baeddSChris Mason 		goto done;
5721925baeddSChris Mason 	}
57220b43e04fSLiu Bo 	/*
57230b43e04fSLiu Bo 	 * So the above check misses one case:
57240b43e04fSLiu Bo 	 * - after releasing the path above, someone has removed the item that
57250b43e04fSLiu Bo 	 *   used to be at the very end of the block, and balance between leafs
57260b43e04fSLiu Bo 	 *   gets another one with bigger key.offset to replace it.
57270b43e04fSLiu Bo 	 *
57280b43e04fSLiu Bo 	 * This one should be returned as well, or we can get leaf corruption
57290b43e04fSLiu Bo 	 * later(esp. in __btrfs_drop_extents()).
57300b43e04fSLiu Bo 	 *
57310b43e04fSLiu Bo 	 * And a bit more explanation about this check,
57320b43e04fSLiu Bo 	 * with ret > 0, the key isn't found, the path points to the slot
57330b43e04fSLiu Bo 	 * where it should be inserted, so the path->slots[0] item must be the
57340b43e04fSLiu Bo 	 * bigger one.
57350b43e04fSLiu Bo 	 */
57360b43e04fSLiu Bo 	if (nritems > 0 && ret > 0 && path->slots[0] == nritems - 1) {
57370b43e04fSLiu Bo 		ret = 0;
57380b43e04fSLiu Bo 		goto done;
57390b43e04fSLiu Bo 	}
5740d97e63b6SChris Mason 
5741234b63a0SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
57428e73f275SChris Mason 		if (!path->nodes[level]) {
57438e73f275SChris Mason 			ret = 1;
57448e73f275SChris Mason 			goto done;
57458e73f275SChris Mason 		}
57465f39d397SChris Mason 
5747d97e63b6SChris Mason 		slot = path->slots[level] + 1;
5748d97e63b6SChris Mason 		c = path->nodes[level];
57495f39d397SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
5750d97e63b6SChris Mason 			level++;
57518e73f275SChris Mason 			if (level == BTRFS_MAX_LEVEL) {
57528e73f275SChris Mason 				ret = 1;
57538e73f275SChris Mason 				goto done;
57548e73f275SChris Mason 			}
5755d97e63b6SChris Mason 			continue;
5756d97e63b6SChris Mason 		}
57575f39d397SChris Mason 
5758925baeddSChris Mason 		if (next) {
5759bd681513SChris Mason 			btrfs_tree_unlock_rw(next, next_rw_lock);
57605f39d397SChris Mason 			free_extent_buffer(next);
5761925baeddSChris Mason 		}
57625f39d397SChris Mason 
57638e73f275SChris Mason 		next = c;
5764bd681513SChris Mason 		next_rw_lock = path->locks[level];
5765d07b8528SLiu Bo 		ret = read_block_for_search(root, path, &next, level,
5766cda79c54SDavid Sterba 					    slot, &key);
57678e73f275SChris Mason 		if (ret == -EAGAIN)
57688e73f275SChris Mason 			goto again;
57695f39d397SChris Mason 
577076a05b35SChris Mason 		if (ret < 0) {
5771b3b4aa74SDavid Sterba 			btrfs_release_path(path);
577276a05b35SChris Mason 			goto done;
577376a05b35SChris Mason 		}
577476a05b35SChris Mason 
57755cd57b2cSChris Mason 		if (!path->skip_locking) {
5776bd681513SChris Mason 			ret = btrfs_try_tree_read_lock(next);
5777d42244a0SJan Schmidt 			if (!ret && time_seq) {
5778d42244a0SJan Schmidt 				/*
5779d42244a0SJan Schmidt 				 * If we don't get the lock, we may be racing
5780d42244a0SJan Schmidt 				 * with push_leaf_left, holding that lock while
5781d42244a0SJan Schmidt 				 * itself waiting for the leaf we've currently
5782d42244a0SJan Schmidt 				 * locked. To solve this situation, we give up
5783d42244a0SJan Schmidt 				 * on our lock and cycle.
5784d42244a0SJan Schmidt 				 */
5785cf538830SJan Schmidt 				free_extent_buffer(next);
5786d42244a0SJan Schmidt 				btrfs_release_path(path);
5787d42244a0SJan Schmidt 				cond_resched();
5788d42244a0SJan Schmidt 				goto again;
5789d42244a0SJan Schmidt 			}
57908e73f275SChris Mason 			if (!ret) {
57918e73f275SChris Mason 				btrfs_set_path_blocking(path);
5792bd681513SChris Mason 				btrfs_tree_read_lock(next);
5793bd681513SChris Mason 				btrfs_clear_path_blocking(path, next,
5794bd681513SChris Mason 							  BTRFS_READ_LOCK);
57958e73f275SChris Mason 			}
5796bd681513SChris Mason 			next_rw_lock = BTRFS_READ_LOCK;
5797bd681513SChris Mason 		}
5798d97e63b6SChris Mason 		break;
5799d97e63b6SChris Mason 	}
5800d97e63b6SChris Mason 	path->slots[level] = slot;
5801d97e63b6SChris Mason 	while (1) {
5802d97e63b6SChris Mason 		level--;
5803d97e63b6SChris Mason 		c = path->nodes[level];
5804925baeddSChris Mason 		if (path->locks[level])
5805bd681513SChris Mason 			btrfs_tree_unlock_rw(c, path->locks[level]);
58068e73f275SChris Mason 
58075f39d397SChris Mason 		free_extent_buffer(c);
5808d97e63b6SChris Mason 		path->nodes[level] = next;
5809d97e63b6SChris Mason 		path->slots[level] = 0;
5810a74a4b97SChris Mason 		if (!path->skip_locking)
5811bd681513SChris Mason 			path->locks[level] = next_rw_lock;
5812d97e63b6SChris Mason 		if (!level)
5813d97e63b6SChris Mason 			break;
5814b4ce94deSChris Mason 
5815d07b8528SLiu Bo 		ret = read_block_for_search(root, path, &next, level,
5816cda79c54SDavid Sterba 					    0, &key);
58178e73f275SChris Mason 		if (ret == -EAGAIN)
58188e73f275SChris Mason 			goto again;
58198e73f275SChris Mason 
582076a05b35SChris Mason 		if (ret < 0) {
5821b3b4aa74SDavid Sterba 			btrfs_release_path(path);
582276a05b35SChris Mason 			goto done;
582376a05b35SChris Mason 		}
582476a05b35SChris Mason 
58255cd57b2cSChris Mason 		if (!path->skip_locking) {
5826bd681513SChris Mason 			ret = btrfs_try_tree_read_lock(next);
58278e73f275SChris Mason 			if (!ret) {
58288e73f275SChris Mason 				btrfs_set_path_blocking(path);
5829bd681513SChris Mason 				btrfs_tree_read_lock(next);
5830bd681513SChris Mason 				btrfs_clear_path_blocking(path, next,
5831bd681513SChris Mason 							  BTRFS_READ_LOCK);
58328e73f275SChris Mason 			}
5833bd681513SChris Mason 			next_rw_lock = BTRFS_READ_LOCK;
5834bd681513SChris Mason 		}
5835d97e63b6SChris Mason 	}
58368e73f275SChris Mason 	ret = 0;
5837925baeddSChris Mason done:
5838f7c79f30SChris Mason 	unlock_up(path, 0, 1, 0, NULL);
58398e73f275SChris Mason 	path->leave_spinning = old_spinning;
58408e73f275SChris Mason 	if (!old_spinning)
58418e73f275SChris Mason 		btrfs_set_path_blocking(path);
58428e73f275SChris Mason 
58438e73f275SChris Mason 	return ret;
5844d97e63b6SChris Mason }
58450b86a832SChris Mason 
58463f157a2fSChris Mason /*
58473f157a2fSChris Mason  * this uses btrfs_prev_leaf to walk backwards in the tree, and keeps
58483f157a2fSChris Mason  * searching until it gets past min_objectid or finds an item of 'type'
58493f157a2fSChris Mason  *
58503f157a2fSChris Mason  * returns 0 if something is found, 1 if nothing was found and < 0 on error
58513f157a2fSChris Mason  */
58520b86a832SChris Mason int btrfs_previous_item(struct btrfs_root *root,
58530b86a832SChris Mason 			struct btrfs_path *path, u64 min_objectid,
58540b86a832SChris Mason 			int type)
58550b86a832SChris Mason {
58560b86a832SChris Mason 	struct btrfs_key found_key;
58570b86a832SChris Mason 	struct extent_buffer *leaf;
5858e02119d5SChris Mason 	u32 nritems;
58590b86a832SChris Mason 	int ret;
58600b86a832SChris Mason 
58610b86a832SChris Mason 	while (1) {
58620b86a832SChris Mason 		if (path->slots[0] == 0) {
5863b4ce94deSChris Mason 			btrfs_set_path_blocking(path);
58640b86a832SChris Mason 			ret = btrfs_prev_leaf(root, path);
58650b86a832SChris Mason 			if (ret != 0)
58660b86a832SChris Mason 				return ret;
58670b86a832SChris Mason 		} else {
58680b86a832SChris Mason 			path->slots[0]--;
58690b86a832SChris Mason 		}
58700b86a832SChris Mason 		leaf = path->nodes[0];
5871e02119d5SChris Mason 		nritems = btrfs_header_nritems(leaf);
5872e02119d5SChris Mason 		if (nritems == 0)
5873e02119d5SChris Mason 			return 1;
5874e02119d5SChris Mason 		if (path->slots[0] == nritems)
5875e02119d5SChris Mason 			path->slots[0]--;
5876e02119d5SChris Mason 
58770b86a832SChris Mason 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5878e02119d5SChris Mason 		if (found_key.objectid < min_objectid)
5879e02119d5SChris Mason 			break;
58800a4eefbbSYan Zheng 		if (found_key.type == type)
58810a4eefbbSYan Zheng 			return 0;
5882e02119d5SChris Mason 		if (found_key.objectid == min_objectid &&
5883e02119d5SChris Mason 		    found_key.type < type)
5884e02119d5SChris Mason 			break;
58850b86a832SChris Mason 	}
58860b86a832SChris Mason 	return 1;
58870b86a832SChris Mason }
5888ade2e0b3SWang Shilong 
5889ade2e0b3SWang Shilong /*
5890ade2e0b3SWang Shilong  * search in extent tree to find a previous Metadata/Data extent item with
5891ade2e0b3SWang Shilong  * min objecitd.
5892ade2e0b3SWang Shilong  *
5893ade2e0b3SWang Shilong  * returns 0 if something is found, 1 if nothing was found and < 0 on error
5894ade2e0b3SWang Shilong  */
5895ade2e0b3SWang Shilong int btrfs_previous_extent_item(struct btrfs_root *root,
5896ade2e0b3SWang Shilong 			struct btrfs_path *path, u64 min_objectid)
5897ade2e0b3SWang Shilong {
5898ade2e0b3SWang Shilong 	struct btrfs_key found_key;
5899ade2e0b3SWang Shilong 	struct extent_buffer *leaf;
5900ade2e0b3SWang Shilong 	u32 nritems;
5901ade2e0b3SWang Shilong 	int ret;
5902ade2e0b3SWang Shilong 
5903ade2e0b3SWang Shilong 	while (1) {
5904ade2e0b3SWang Shilong 		if (path->slots[0] == 0) {
5905ade2e0b3SWang Shilong 			btrfs_set_path_blocking(path);
5906ade2e0b3SWang Shilong 			ret = btrfs_prev_leaf(root, path);
5907ade2e0b3SWang Shilong 			if (ret != 0)
5908ade2e0b3SWang Shilong 				return ret;
5909ade2e0b3SWang Shilong 		} else {
5910ade2e0b3SWang Shilong 			path->slots[0]--;
5911ade2e0b3SWang Shilong 		}
5912ade2e0b3SWang Shilong 		leaf = path->nodes[0];
5913ade2e0b3SWang Shilong 		nritems = btrfs_header_nritems(leaf);
5914ade2e0b3SWang Shilong 		if (nritems == 0)
5915ade2e0b3SWang Shilong 			return 1;
5916ade2e0b3SWang Shilong 		if (path->slots[0] == nritems)
5917ade2e0b3SWang Shilong 			path->slots[0]--;
5918ade2e0b3SWang Shilong 
5919ade2e0b3SWang Shilong 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5920ade2e0b3SWang Shilong 		if (found_key.objectid < min_objectid)
5921ade2e0b3SWang Shilong 			break;
5922ade2e0b3SWang Shilong 		if (found_key.type == BTRFS_EXTENT_ITEM_KEY ||
5923ade2e0b3SWang Shilong 		    found_key.type == BTRFS_METADATA_ITEM_KEY)
5924ade2e0b3SWang Shilong 			return 0;
5925ade2e0b3SWang Shilong 		if (found_key.objectid == min_objectid &&
5926ade2e0b3SWang Shilong 		    found_key.type < BTRFS_EXTENT_ITEM_KEY)
5927ade2e0b3SWang Shilong 			break;
5928ade2e0b3SWang Shilong 	}
5929ade2e0b3SWang Shilong 	return 1;
5930ade2e0b3SWang Shilong }
5931