xref: /openbmc/linux/fs/btrfs/ctree.c (revision 0b246afa62b0cf5b09d078121f543135f28492ad)
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>
228f282f71SDavid Sterba #include <linux/vmalloc.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);
31e089f05cSChris Mason static int split_leaf(struct btrfs_trans_handle *trans, struct btrfs_root
32d4dbff95SChris Mason 		      *root, struct btrfs_key *ins_key,
33cc0c5538SChris Mason 		      struct btrfs_path *path, int data_size, int extend);
345f39d397SChris Mason static int push_node_left(struct btrfs_trans_handle *trans,
355f39d397SChris Mason 			  struct btrfs_root *root, struct extent_buffer *dst,
36971a1f66SChris Mason 			  struct extent_buffer *src, int empty);
375f39d397SChris Mason static int balance_node_right(struct btrfs_trans_handle *trans,
385f39d397SChris Mason 			      struct btrfs_root *root,
395f39d397SChris Mason 			      struct extent_buffer *dst_buf,
405f39d397SChris Mason 			      struct extent_buffer *src_buf);
41afe5fea7STsutomu Itoh static void del_ptr(struct btrfs_root *root, struct btrfs_path *path,
42afe5fea7STsutomu Itoh 		    int level, int slot);
435de865eeSFilipe David Borba Manana static int tree_mod_log_free_eb(struct btrfs_fs_info *fs_info,
44f230475eSJan Schmidt 				 struct extent_buffer *eb);
45d97e63b6SChris Mason 
462c90e5d6SChris Mason struct btrfs_path *btrfs_alloc_path(void)
472c90e5d6SChris Mason {
48e2c89907SMasahiro Yamada 	return kmem_cache_zalloc(btrfs_path_cachep, GFP_NOFS);
492c90e5d6SChris Mason }
502c90e5d6SChris Mason 
51b4ce94deSChris Mason /*
52b4ce94deSChris Mason  * set all locked nodes in the path to blocking locks.  This should
53b4ce94deSChris Mason  * be done before scheduling
54b4ce94deSChris Mason  */
55b4ce94deSChris Mason noinline void btrfs_set_path_blocking(struct btrfs_path *p)
56b4ce94deSChris Mason {
57b4ce94deSChris Mason 	int i;
58b4ce94deSChris Mason 	for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
59bd681513SChris Mason 		if (!p->nodes[i] || !p->locks[i])
60bd681513SChris Mason 			continue;
61bd681513SChris Mason 		btrfs_set_lock_blocking_rw(p->nodes[i], p->locks[i]);
62bd681513SChris Mason 		if (p->locks[i] == BTRFS_READ_LOCK)
63bd681513SChris Mason 			p->locks[i] = BTRFS_READ_LOCK_BLOCKING;
64bd681513SChris Mason 		else if (p->locks[i] == BTRFS_WRITE_LOCK)
65bd681513SChris Mason 			p->locks[i] = BTRFS_WRITE_LOCK_BLOCKING;
66b4ce94deSChris Mason 	}
67b4ce94deSChris Mason }
68b4ce94deSChris Mason 
69b4ce94deSChris Mason /*
70b4ce94deSChris Mason  * reset all the locked nodes in the patch to spinning locks.
714008c04aSChris Mason  *
724008c04aSChris Mason  * held is used to keep lockdep happy, when lockdep is enabled
734008c04aSChris Mason  * we set held to a blocking lock before we go around and
744008c04aSChris Mason  * retake all the spinlocks in the path.  You can safely use NULL
754008c04aSChris Mason  * for held
76b4ce94deSChris Mason  */
774008c04aSChris Mason noinline void btrfs_clear_path_blocking(struct btrfs_path *p,
78bd681513SChris Mason 					struct extent_buffer *held, int held_rw)
79b4ce94deSChris Mason {
80b4ce94deSChris Mason 	int i;
814008c04aSChris Mason 
82bd681513SChris Mason 	if (held) {
83bd681513SChris Mason 		btrfs_set_lock_blocking_rw(held, held_rw);
84bd681513SChris Mason 		if (held_rw == BTRFS_WRITE_LOCK)
85bd681513SChris Mason 			held_rw = BTRFS_WRITE_LOCK_BLOCKING;
86bd681513SChris Mason 		else if (held_rw == BTRFS_READ_LOCK)
87bd681513SChris Mason 			held_rw = BTRFS_READ_LOCK_BLOCKING;
88bd681513SChris Mason 	}
894008c04aSChris Mason 	btrfs_set_path_blocking(p);
904008c04aSChris Mason 
914008c04aSChris Mason 	for (i = BTRFS_MAX_LEVEL - 1; i >= 0; i--) {
92bd681513SChris Mason 		if (p->nodes[i] && p->locks[i]) {
93bd681513SChris Mason 			btrfs_clear_lock_blocking_rw(p->nodes[i], p->locks[i]);
94bd681513SChris Mason 			if (p->locks[i] == BTRFS_WRITE_LOCK_BLOCKING)
95bd681513SChris Mason 				p->locks[i] = BTRFS_WRITE_LOCK;
96bd681513SChris Mason 			else if (p->locks[i] == BTRFS_READ_LOCK_BLOCKING)
97bd681513SChris Mason 				p->locks[i] = BTRFS_READ_LOCK;
98bd681513SChris Mason 		}
99b4ce94deSChris Mason 	}
1004008c04aSChris Mason 
1014008c04aSChris Mason 	if (held)
102bd681513SChris Mason 		btrfs_clear_lock_blocking_rw(held, held_rw);
103b4ce94deSChris Mason }
104b4ce94deSChris Mason 
105d352ac68SChris Mason /* this also releases the path */
1062c90e5d6SChris Mason void btrfs_free_path(struct btrfs_path *p)
1072c90e5d6SChris Mason {
108ff175d57SJesper Juhl 	if (!p)
109ff175d57SJesper Juhl 		return;
110b3b4aa74SDavid Sterba 	btrfs_release_path(p);
1112c90e5d6SChris Mason 	kmem_cache_free(btrfs_path_cachep, p);
1122c90e5d6SChris Mason }
1132c90e5d6SChris Mason 
114d352ac68SChris Mason /*
115d352ac68SChris Mason  * path release drops references on the extent buffers in the path
116d352ac68SChris Mason  * and it drops any locks held by this path
117d352ac68SChris Mason  *
118d352ac68SChris Mason  * It is safe to call this on paths that no locks or extent buffers held.
119d352ac68SChris Mason  */
120b3b4aa74SDavid Sterba noinline void btrfs_release_path(struct btrfs_path *p)
121eb60ceacSChris Mason {
122eb60ceacSChris Mason 	int i;
123a2135011SChris Mason 
124234b63a0SChris Mason 	for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
1253f157a2fSChris Mason 		p->slots[i] = 0;
126eb60ceacSChris Mason 		if (!p->nodes[i])
127925baeddSChris Mason 			continue;
128925baeddSChris Mason 		if (p->locks[i]) {
129bd681513SChris Mason 			btrfs_tree_unlock_rw(p->nodes[i], p->locks[i]);
130925baeddSChris Mason 			p->locks[i] = 0;
131925baeddSChris Mason 		}
1325f39d397SChris Mason 		free_extent_buffer(p->nodes[i]);
1333f157a2fSChris Mason 		p->nodes[i] = NULL;
134eb60ceacSChris Mason 	}
135eb60ceacSChris Mason }
136eb60ceacSChris Mason 
137d352ac68SChris Mason /*
138d352ac68SChris Mason  * safely gets a reference on the root node of a tree.  A lock
139d352ac68SChris Mason  * is not taken, so a concurrent writer may put a different node
140d352ac68SChris Mason  * at the root of the tree.  See btrfs_lock_root_node for the
141d352ac68SChris Mason  * looping required.
142d352ac68SChris Mason  *
143d352ac68SChris Mason  * The extent buffer returned by this has a reference taken, so
144d352ac68SChris Mason  * it won't disappear.  It may stop being the root of the tree
145d352ac68SChris Mason  * at any time because there are no locks held.
146d352ac68SChris Mason  */
147925baeddSChris Mason struct extent_buffer *btrfs_root_node(struct btrfs_root *root)
148925baeddSChris Mason {
149925baeddSChris Mason 	struct extent_buffer *eb;
150240f62c8SChris Mason 
1513083ee2eSJosef Bacik 	while (1) {
152240f62c8SChris Mason 		rcu_read_lock();
153240f62c8SChris Mason 		eb = rcu_dereference(root->node);
1543083ee2eSJosef Bacik 
1553083ee2eSJosef Bacik 		/*
1563083ee2eSJosef Bacik 		 * RCU really hurts here, we could free up the root node because
15701327610SNicholas D Steeves 		 * it was COWed but we may not get the new root node yet so do
1583083ee2eSJosef Bacik 		 * the inc_not_zero dance and if it doesn't work then
1593083ee2eSJosef Bacik 		 * synchronize_rcu and try again.
1603083ee2eSJosef Bacik 		 */
1613083ee2eSJosef Bacik 		if (atomic_inc_not_zero(&eb->refs)) {
162240f62c8SChris Mason 			rcu_read_unlock();
1633083ee2eSJosef Bacik 			break;
1643083ee2eSJosef Bacik 		}
1653083ee2eSJosef Bacik 		rcu_read_unlock();
1663083ee2eSJosef Bacik 		synchronize_rcu();
1673083ee2eSJosef Bacik 	}
168925baeddSChris Mason 	return eb;
169925baeddSChris Mason }
170925baeddSChris Mason 
171d352ac68SChris Mason /* loop around taking references on and locking the root node of the
172d352ac68SChris Mason  * tree until you end up with a lock on the root.  A locked buffer
173d352ac68SChris Mason  * is returned, with a reference held.
174d352ac68SChris Mason  */
175925baeddSChris Mason struct extent_buffer *btrfs_lock_root_node(struct btrfs_root *root)
176925baeddSChris Mason {
177925baeddSChris Mason 	struct extent_buffer *eb;
178925baeddSChris Mason 
179925baeddSChris Mason 	while (1) {
180925baeddSChris Mason 		eb = btrfs_root_node(root);
181925baeddSChris Mason 		btrfs_tree_lock(eb);
182240f62c8SChris Mason 		if (eb == root->node)
183925baeddSChris Mason 			break;
184925baeddSChris Mason 		btrfs_tree_unlock(eb);
185925baeddSChris Mason 		free_extent_buffer(eb);
186925baeddSChris Mason 	}
187925baeddSChris Mason 	return eb;
188925baeddSChris Mason }
189925baeddSChris Mason 
190bd681513SChris Mason /* loop around taking references on and locking the root node of the
191bd681513SChris Mason  * tree until you end up with a lock on the root.  A locked buffer
192bd681513SChris Mason  * is returned, with a reference held.
193bd681513SChris Mason  */
19448a3b636SEric Sandeen static struct extent_buffer *btrfs_read_lock_root_node(struct btrfs_root *root)
195bd681513SChris Mason {
196bd681513SChris Mason 	struct extent_buffer *eb;
197bd681513SChris Mason 
198bd681513SChris Mason 	while (1) {
199bd681513SChris Mason 		eb = btrfs_root_node(root);
200bd681513SChris Mason 		btrfs_tree_read_lock(eb);
201bd681513SChris Mason 		if (eb == root->node)
202bd681513SChris Mason 			break;
203bd681513SChris Mason 		btrfs_tree_read_unlock(eb);
204bd681513SChris Mason 		free_extent_buffer(eb);
205bd681513SChris Mason 	}
206bd681513SChris Mason 	return eb;
207bd681513SChris Mason }
208bd681513SChris Mason 
209d352ac68SChris Mason /* cowonly root (everything not a reference counted cow subvolume), just get
210d352ac68SChris Mason  * put onto a simple dirty list.  transaction.c walks this to make sure they
211d352ac68SChris Mason  * get properly updated on disk.
212d352ac68SChris Mason  */
2130b86a832SChris Mason static void add_root_to_dirty_list(struct btrfs_root *root)
2140b86a832SChris Mason {
215*0b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
216*0b246afaSJeff Mahoney 
217e7070be1SJosef Bacik 	if (test_bit(BTRFS_ROOT_DIRTY, &root->state) ||
218e7070be1SJosef Bacik 	    !test_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state))
219e7070be1SJosef Bacik 		return;
220e7070be1SJosef Bacik 
221*0b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
222e7070be1SJosef Bacik 	if (!test_and_set_bit(BTRFS_ROOT_DIRTY, &root->state)) {
223e7070be1SJosef Bacik 		/* Want the extent tree to be the last on the list */
224e7070be1SJosef Bacik 		if (root->objectid == BTRFS_EXTENT_TREE_OBJECTID)
225e7070be1SJosef Bacik 			list_move_tail(&root->dirty_list,
226*0b246afaSJeff Mahoney 				       &fs_info->dirty_cowonly_roots);
227e7070be1SJosef Bacik 		else
228e7070be1SJosef Bacik 			list_move(&root->dirty_list,
229*0b246afaSJeff Mahoney 				  &fs_info->dirty_cowonly_roots);
2300b86a832SChris Mason 	}
231*0b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
2320b86a832SChris Mason }
2330b86a832SChris Mason 
234d352ac68SChris Mason /*
235d352ac68SChris Mason  * used by snapshot creation to make a copy of a root for a tree with
236d352ac68SChris Mason  * a given objectid.  The buffer with the new root node is returned in
237d352ac68SChris Mason  * cow_ret, and this func returns zero on success or a negative error code.
238d352ac68SChris Mason  */
239be20aa9dSChris Mason int btrfs_copy_root(struct btrfs_trans_handle *trans,
240be20aa9dSChris Mason 		      struct btrfs_root *root,
241be20aa9dSChris Mason 		      struct extent_buffer *buf,
242be20aa9dSChris Mason 		      struct extent_buffer **cow_ret, u64 new_root_objectid)
243be20aa9dSChris Mason {
244*0b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
245be20aa9dSChris Mason 	struct extent_buffer *cow;
246be20aa9dSChris Mason 	int ret = 0;
247be20aa9dSChris Mason 	int level;
2485d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
249be20aa9dSChris Mason 
25027cdeb70SMiao Xie 	WARN_ON(test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
251*0b246afaSJeff Mahoney 		trans->transid != fs_info->running_transaction->transid);
25227cdeb70SMiao Xie 	WARN_ON(test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
25327cdeb70SMiao Xie 		trans->transid != root->last_trans);
254be20aa9dSChris Mason 
255be20aa9dSChris Mason 	level = btrfs_header_level(buf);
2565d4f98a2SYan Zheng 	if (level == 0)
2575d4f98a2SYan Zheng 		btrfs_item_key(buf, &disk_key, 0);
2585d4f98a2SYan Zheng 	else
2595d4f98a2SYan Zheng 		btrfs_node_key(buf, &disk_key, 0);
26031840ae1SZheng Yan 
2614d75f8a9SDavid Sterba 	cow = btrfs_alloc_tree_block(trans, root, 0, new_root_objectid,
2624d75f8a9SDavid Sterba 			&disk_key, level, buf->start, 0);
2635d4f98a2SYan Zheng 	if (IS_ERR(cow))
264be20aa9dSChris Mason 		return PTR_ERR(cow);
265be20aa9dSChris Mason 
26658e8012cSDavid Sterba 	copy_extent_buffer_full(cow, buf);
267be20aa9dSChris Mason 	btrfs_set_header_bytenr(cow, cow->start);
268be20aa9dSChris Mason 	btrfs_set_header_generation(cow, trans->transid);
2695d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
2705d4f98a2SYan Zheng 	btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
2715d4f98a2SYan Zheng 				     BTRFS_HEADER_FLAG_RELOC);
2725d4f98a2SYan Zheng 	if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
2735d4f98a2SYan Zheng 		btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
2745d4f98a2SYan Zheng 	else
275be20aa9dSChris Mason 		btrfs_set_header_owner(cow, new_root_objectid);
276be20aa9dSChris Mason 
277*0b246afaSJeff Mahoney 	write_extent_buffer_fsid(cow, fs_info->fsid);
2782b82032cSYan Zheng 
279be20aa9dSChris Mason 	WARN_ON(btrfs_header_generation(buf) > trans->transid);
2805d4f98a2SYan Zheng 	if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
281e339a6b0SJosef Bacik 		ret = btrfs_inc_ref(trans, root, cow, 1);
2825d4f98a2SYan Zheng 	else
283e339a6b0SJosef Bacik 		ret = btrfs_inc_ref(trans, root, cow, 0);
2844aec2b52SChris Mason 
285be20aa9dSChris Mason 	if (ret)
286be20aa9dSChris Mason 		return ret;
287be20aa9dSChris Mason 
288be20aa9dSChris Mason 	btrfs_mark_buffer_dirty(cow);
289be20aa9dSChris Mason 	*cow_ret = cow;
290be20aa9dSChris Mason 	return 0;
291be20aa9dSChris Mason }
292be20aa9dSChris Mason 
293bd989ba3SJan Schmidt enum mod_log_op {
294bd989ba3SJan Schmidt 	MOD_LOG_KEY_REPLACE,
295bd989ba3SJan Schmidt 	MOD_LOG_KEY_ADD,
296bd989ba3SJan Schmidt 	MOD_LOG_KEY_REMOVE,
297bd989ba3SJan Schmidt 	MOD_LOG_KEY_REMOVE_WHILE_FREEING,
298bd989ba3SJan Schmidt 	MOD_LOG_KEY_REMOVE_WHILE_MOVING,
299bd989ba3SJan Schmidt 	MOD_LOG_MOVE_KEYS,
300bd989ba3SJan Schmidt 	MOD_LOG_ROOT_REPLACE,
301bd989ba3SJan Schmidt };
302bd989ba3SJan Schmidt 
303bd989ba3SJan Schmidt struct tree_mod_move {
304bd989ba3SJan Schmidt 	int dst_slot;
305bd989ba3SJan Schmidt 	int nr_items;
306bd989ba3SJan Schmidt };
307bd989ba3SJan Schmidt 
308bd989ba3SJan Schmidt struct tree_mod_root {
309bd989ba3SJan Schmidt 	u64 logical;
310bd989ba3SJan Schmidt 	u8 level;
311bd989ba3SJan Schmidt };
312bd989ba3SJan Schmidt 
313bd989ba3SJan Schmidt struct tree_mod_elem {
314bd989ba3SJan Schmidt 	struct rb_node node;
315298cfd36SChandan Rajendra 	u64 logical;
316097b8a7cSJan Schmidt 	u64 seq;
317bd989ba3SJan Schmidt 	enum mod_log_op op;
318bd989ba3SJan Schmidt 
319bd989ba3SJan Schmidt 	/* this is used for MOD_LOG_KEY_* and MOD_LOG_MOVE_KEYS operations */
320bd989ba3SJan Schmidt 	int slot;
321bd989ba3SJan Schmidt 
322bd989ba3SJan Schmidt 	/* this is used for MOD_LOG_KEY* and MOD_LOG_ROOT_REPLACE */
323bd989ba3SJan Schmidt 	u64 generation;
324bd989ba3SJan Schmidt 
325bd989ba3SJan Schmidt 	/* those are used for op == MOD_LOG_KEY_{REPLACE,REMOVE} */
326bd989ba3SJan Schmidt 	struct btrfs_disk_key key;
327bd989ba3SJan Schmidt 	u64 blockptr;
328bd989ba3SJan Schmidt 
329bd989ba3SJan Schmidt 	/* this is used for op == MOD_LOG_MOVE_KEYS */
330bd989ba3SJan Schmidt 	struct tree_mod_move move;
331bd989ba3SJan Schmidt 
332bd989ba3SJan Schmidt 	/* this is used for op == MOD_LOG_ROOT_REPLACE */
333bd989ba3SJan Schmidt 	struct tree_mod_root old_root;
334bd989ba3SJan Schmidt };
335bd989ba3SJan Schmidt 
336097b8a7cSJan Schmidt static inline void tree_mod_log_read_lock(struct btrfs_fs_info *fs_info)
337bd989ba3SJan Schmidt {
338097b8a7cSJan Schmidt 	read_lock(&fs_info->tree_mod_log_lock);
339bd989ba3SJan Schmidt }
340bd989ba3SJan Schmidt 
341097b8a7cSJan Schmidt static inline void tree_mod_log_read_unlock(struct btrfs_fs_info *fs_info)
342097b8a7cSJan Schmidt {
343097b8a7cSJan Schmidt 	read_unlock(&fs_info->tree_mod_log_lock);
344097b8a7cSJan Schmidt }
345097b8a7cSJan Schmidt 
346097b8a7cSJan Schmidt static inline void tree_mod_log_write_lock(struct btrfs_fs_info *fs_info)
347097b8a7cSJan Schmidt {
348097b8a7cSJan Schmidt 	write_lock(&fs_info->tree_mod_log_lock);
349097b8a7cSJan Schmidt }
350097b8a7cSJan Schmidt 
351097b8a7cSJan Schmidt static inline void tree_mod_log_write_unlock(struct btrfs_fs_info *fs_info)
352097b8a7cSJan Schmidt {
353097b8a7cSJan Schmidt 	write_unlock(&fs_info->tree_mod_log_lock);
354097b8a7cSJan Schmidt }
355097b8a7cSJan Schmidt 
356097b8a7cSJan Schmidt /*
357fcebe456SJosef Bacik  * Pull a new tree mod seq number for our operation.
358fc36ed7eSJan Schmidt  */
359fcebe456SJosef Bacik static inline u64 btrfs_inc_tree_mod_seq(struct btrfs_fs_info *fs_info)
360fc36ed7eSJan Schmidt {
361fc36ed7eSJan Schmidt 	return atomic64_inc_return(&fs_info->tree_mod_seq);
362fc36ed7eSJan Schmidt }
363fc36ed7eSJan Schmidt 
364fc36ed7eSJan Schmidt /*
365097b8a7cSJan Schmidt  * This adds a new blocker to the tree mod log's blocker list if the @elem
366097b8a7cSJan Schmidt  * passed does not already have a sequence number set. So when a caller expects
367097b8a7cSJan Schmidt  * to record tree modifications, it should ensure to set elem->seq to zero
368097b8a7cSJan Schmidt  * before calling btrfs_get_tree_mod_seq.
369097b8a7cSJan Schmidt  * Returns a fresh, unused tree log modification sequence number, even if no new
370097b8a7cSJan Schmidt  * blocker was added.
371097b8a7cSJan Schmidt  */
372097b8a7cSJan Schmidt u64 btrfs_get_tree_mod_seq(struct btrfs_fs_info *fs_info,
373bd989ba3SJan Schmidt 			   struct seq_list *elem)
374bd989ba3SJan Schmidt {
375097b8a7cSJan Schmidt 	tree_mod_log_write_lock(fs_info);
376bd989ba3SJan Schmidt 	spin_lock(&fs_info->tree_mod_seq_lock);
377097b8a7cSJan Schmidt 	if (!elem->seq) {
378fcebe456SJosef Bacik 		elem->seq = btrfs_inc_tree_mod_seq(fs_info);
379097b8a7cSJan Schmidt 		list_add_tail(&elem->list, &fs_info->tree_mod_seq_list);
380097b8a7cSJan Schmidt 	}
381bd989ba3SJan Schmidt 	spin_unlock(&fs_info->tree_mod_seq_lock);
382097b8a7cSJan Schmidt 	tree_mod_log_write_unlock(fs_info);
383097b8a7cSJan Schmidt 
384fcebe456SJosef Bacik 	return elem->seq;
385bd989ba3SJan Schmidt }
386bd989ba3SJan Schmidt 
387bd989ba3SJan Schmidt void btrfs_put_tree_mod_seq(struct btrfs_fs_info *fs_info,
388bd989ba3SJan Schmidt 			    struct seq_list *elem)
389bd989ba3SJan Schmidt {
390bd989ba3SJan Schmidt 	struct rb_root *tm_root;
391bd989ba3SJan Schmidt 	struct rb_node *node;
392bd989ba3SJan Schmidt 	struct rb_node *next;
393bd989ba3SJan Schmidt 	struct seq_list *cur_elem;
394bd989ba3SJan Schmidt 	struct tree_mod_elem *tm;
395bd989ba3SJan Schmidt 	u64 min_seq = (u64)-1;
396bd989ba3SJan Schmidt 	u64 seq_putting = elem->seq;
397bd989ba3SJan Schmidt 
398bd989ba3SJan Schmidt 	if (!seq_putting)
399bd989ba3SJan Schmidt 		return;
400bd989ba3SJan Schmidt 
401bd989ba3SJan Schmidt 	spin_lock(&fs_info->tree_mod_seq_lock);
402bd989ba3SJan Schmidt 	list_del(&elem->list);
403097b8a7cSJan Schmidt 	elem->seq = 0;
404bd989ba3SJan Schmidt 
405bd989ba3SJan Schmidt 	list_for_each_entry(cur_elem, &fs_info->tree_mod_seq_list, list) {
406097b8a7cSJan Schmidt 		if (cur_elem->seq < min_seq) {
407bd989ba3SJan Schmidt 			if (seq_putting > cur_elem->seq) {
408bd989ba3SJan Schmidt 				/*
409bd989ba3SJan Schmidt 				 * blocker with lower sequence number exists, we
410bd989ba3SJan Schmidt 				 * cannot remove anything from the log
411bd989ba3SJan Schmidt 				 */
412097b8a7cSJan Schmidt 				spin_unlock(&fs_info->tree_mod_seq_lock);
413097b8a7cSJan Schmidt 				return;
414bd989ba3SJan Schmidt 			}
415bd989ba3SJan Schmidt 			min_seq = cur_elem->seq;
416bd989ba3SJan Schmidt 		}
417bd989ba3SJan Schmidt 	}
418097b8a7cSJan Schmidt 	spin_unlock(&fs_info->tree_mod_seq_lock);
419097b8a7cSJan Schmidt 
420097b8a7cSJan Schmidt 	/*
421bd989ba3SJan Schmidt 	 * anything that's lower than the lowest existing (read: blocked)
422bd989ba3SJan Schmidt 	 * sequence number can be removed from the tree.
423bd989ba3SJan Schmidt 	 */
424097b8a7cSJan Schmidt 	tree_mod_log_write_lock(fs_info);
425bd989ba3SJan Schmidt 	tm_root = &fs_info->tree_mod_log;
426bd989ba3SJan Schmidt 	for (node = rb_first(tm_root); node; node = next) {
427bd989ba3SJan Schmidt 		next = rb_next(node);
428bd989ba3SJan Schmidt 		tm = container_of(node, struct tree_mod_elem, node);
429097b8a7cSJan Schmidt 		if (tm->seq > min_seq)
430bd989ba3SJan Schmidt 			continue;
431bd989ba3SJan Schmidt 		rb_erase(node, tm_root);
432bd989ba3SJan Schmidt 		kfree(tm);
433bd989ba3SJan Schmidt 	}
434097b8a7cSJan Schmidt 	tree_mod_log_write_unlock(fs_info);
435bd989ba3SJan Schmidt }
436bd989ba3SJan Schmidt 
437bd989ba3SJan Schmidt /*
438bd989ba3SJan Schmidt  * key order of the log:
439298cfd36SChandan Rajendra  *       node/leaf start address -> sequence
440bd989ba3SJan Schmidt  *
441298cfd36SChandan Rajendra  * The 'start address' is the logical address of the *new* root node
442298cfd36SChandan Rajendra  * for root replace operations, or the logical address of the affected
443298cfd36SChandan Rajendra  * block for all other operations.
4445de865eeSFilipe David Borba Manana  *
4455de865eeSFilipe David Borba Manana  * Note: must be called with write lock (tree_mod_log_write_lock).
446bd989ba3SJan Schmidt  */
447bd989ba3SJan Schmidt static noinline int
448bd989ba3SJan Schmidt __tree_mod_log_insert(struct btrfs_fs_info *fs_info, struct tree_mod_elem *tm)
449bd989ba3SJan Schmidt {
450bd989ba3SJan Schmidt 	struct rb_root *tm_root;
451bd989ba3SJan Schmidt 	struct rb_node **new;
452bd989ba3SJan Schmidt 	struct rb_node *parent = NULL;
453bd989ba3SJan Schmidt 	struct tree_mod_elem *cur;
454bd989ba3SJan Schmidt 
455c8cc6341SJosef Bacik 	BUG_ON(!tm);
456c8cc6341SJosef Bacik 
457fcebe456SJosef Bacik 	tm->seq = btrfs_inc_tree_mod_seq(fs_info);
458bd989ba3SJan Schmidt 
459bd989ba3SJan Schmidt 	tm_root = &fs_info->tree_mod_log;
460bd989ba3SJan Schmidt 	new = &tm_root->rb_node;
461bd989ba3SJan Schmidt 	while (*new) {
462bd989ba3SJan Schmidt 		cur = container_of(*new, struct tree_mod_elem, node);
463bd989ba3SJan Schmidt 		parent = *new;
464298cfd36SChandan Rajendra 		if (cur->logical < tm->logical)
465bd989ba3SJan Schmidt 			new = &((*new)->rb_left);
466298cfd36SChandan Rajendra 		else if (cur->logical > tm->logical)
467bd989ba3SJan Schmidt 			new = &((*new)->rb_right);
468097b8a7cSJan Schmidt 		else if (cur->seq < tm->seq)
469bd989ba3SJan Schmidt 			new = &((*new)->rb_left);
470097b8a7cSJan Schmidt 		else if (cur->seq > tm->seq)
471bd989ba3SJan Schmidt 			new = &((*new)->rb_right);
4725de865eeSFilipe David Borba Manana 		else
4735de865eeSFilipe David Borba Manana 			return -EEXIST;
474bd989ba3SJan Schmidt 	}
475bd989ba3SJan Schmidt 
476bd989ba3SJan Schmidt 	rb_link_node(&tm->node, parent, new);
477bd989ba3SJan Schmidt 	rb_insert_color(&tm->node, tm_root);
4785de865eeSFilipe David Borba Manana 	return 0;
479bd989ba3SJan Schmidt }
480bd989ba3SJan Schmidt 
481097b8a7cSJan Schmidt /*
482097b8a7cSJan Schmidt  * Determines if logging can be omitted. Returns 1 if it can. Otherwise, it
483097b8a7cSJan Schmidt  * returns zero with the tree_mod_log_lock acquired. The caller must hold
484097b8a7cSJan Schmidt  * this until all tree mod log insertions are recorded in the rb tree and then
485097b8a7cSJan Schmidt  * call tree_mod_log_write_unlock() to release.
486097b8a7cSJan Schmidt  */
487e9b7fd4dSJan Schmidt static inline int tree_mod_dont_log(struct btrfs_fs_info *fs_info,
488e9b7fd4dSJan Schmidt 				    struct extent_buffer *eb) {
489e9b7fd4dSJan Schmidt 	smp_mb();
490e9b7fd4dSJan Schmidt 	if (list_empty(&(fs_info)->tree_mod_seq_list))
491e9b7fd4dSJan Schmidt 		return 1;
492097b8a7cSJan Schmidt 	if (eb && btrfs_header_level(eb) == 0)
493e9b7fd4dSJan Schmidt 		return 1;
4945de865eeSFilipe David Borba Manana 
4955de865eeSFilipe David Borba Manana 	tree_mod_log_write_lock(fs_info);
4965de865eeSFilipe David Borba Manana 	if (list_empty(&(fs_info)->tree_mod_seq_list)) {
4975de865eeSFilipe David Borba Manana 		tree_mod_log_write_unlock(fs_info);
4985de865eeSFilipe David Borba Manana 		return 1;
4995de865eeSFilipe David Borba Manana 	}
5005de865eeSFilipe David Borba Manana 
501e9b7fd4dSJan Schmidt 	return 0;
502e9b7fd4dSJan Schmidt }
503e9b7fd4dSJan Schmidt 
5045de865eeSFilipe David Borba Manana /* Similar to tree_mod_dont_log, but doesn't acquire any locks. */
5055de865eeSFilipe David Borba Manana static inline int tree_mod_need_log(const struct btrfs_fs_info *fs_info,
5065de865eeSFilipe David Borba Manana 				    struct extent_buffer *eb)
5075de865eeSFilipe David Borba Manana {
5085de865eeSFilipe David Borba Manana 	smp_mb();
5095de865eeSFilipe David Borba Manana 	if (list_empty(&(fs_info)->tree_mod_seq_list))
5105de865eeSFilipe David Borba Manana 		return 0;
5115de865eeSFilipe David Borba Manana 	if (eb && btrfs_header_level(eb) == 0)
5125de865eeSFilipe David Borba Manana 		return 0;
5135de865eeSFilipe David Borba Manana 
5145de865eeSFilipe David Borba Manana 	return 1;
5155de865eeSFilipe David Borba Manana }
5165de865eeSFilipe David Borba Manana 
5175de865eeSFilipe David Borba Manana static struct tree_mod_elem *
5185de865eeSFilipe David Borba Manana alloc_tree_mod_elem(struct extent_buffer *eb, int slot,
519bd989ba3SJan Schmidt 		    enum mod_log_op op, gfp_t flags)
520bd989ba3SJan Schmidt {
521097b8a7cSJan Schmidt 	struct tree_mod_elem *tm;
522bd989ba3SJan Schmidt 
523c8cc6341SJosef Bacik 	tm = kzalloc(sizeof(*tm), flags);
524c8cc6341SJosef Bacik 	if (!tm)
5255de865eeSFilipe David Borba Manana 		return NULL;
526bd989ba3SJan Schmidt 
527298cfd36SChandan Rajendra 	tm->logical = eb->start;
528bd989ba3SJan Schmidt 	if (op != MOD_LOG_KEY_ADD) {
529bd989ba3SJan Schmidt 		btrfs_node_key(eb, &tm->key, slot);
530bd989ba3SJan Schmidt 		tm->blockptr = btrfs_node_blockptr(eb, slot);
531bd989ba3SJan Schmidt 	}
532bd989ba3SJan Schmidt 	tm->op = op;
533bd989ba3SJan Schmidt 	tm->slot = slot;
534bd989ba3SJan Schmidt 	tm->generation = btrfs_node_ptr_generation(eb, slot);
5355de865eeSFilipe David Borba Manana 	RB_CLEAR_NODE(&tm->node);
536bd989ba3SJan Schmidt 
5375de865eeSFilipe David Borba Manana 	return tm;
538097b8a7cSJan Schmidt }
539097b8a7cSJan Schmidt 
540097b8a7cSJan Schmidt static noinline int
541c8cc6341SJosef Bacik tree_mod_log_insert_key(struct btrfs_fs_info *fs_info,
542097b8a7cSJan Schmidt 			struct extent_buffer *eb, int slot,
543097b8a7cSJan Schmidt 			enum mod_log_op op, gfp_t flags)
544097b8a7cSJan Schmidt {
5455de865eeSFilipe David Borba Manana 	struct tree_mod_elem *tm;
5465de865eeSFilipe David Borba Manana 	int ret;
5475de865eeSFilipe David Borba Manana 
5485de865eeSFilipe David Borba Manana 	if (!tree_mod_need_log(fs_info, eb))
549097b8a7cSJan Schmidt 		return 0;
550097b8a7cSJan Schmidt 
5515de865eeSFilipe David Borba Manana 	tm = alloc_tree_mod_elem(eb, slot, op, flags);
5525de865eeSFilipe David Borba Manana 	if (!tm)
5535de865eeSFilipe David Borba Manana 		return -ENOMEM;
5545de865eeSFilipe David Borba Manana 
5555de865eeSFilipe David Borba Manana 	if (tree_mod_dont_log(fs_info, eb)) {
5565de865eeSFilipe David Borba Manana 		kfree(tm);
5575de865eeSFilipe David Borba Manana 		return 0;
5585de865eeSFilipe David Borba Manana 	}
5595de865eeSFilipe David Borba Manana 
5605de865eeSFilipe David Borba Manana 	ret = __tree_mod_log_insert(fs_info, tm);
5615de865eeSFilipe David Borba Manana 	tree_mod_log_write_unlock(fs_info);
5625de865eeSFilipe David Borba Manana 	if (ret)
5635de865eeSFilipe David Borba Manana 		kfree(tm);
5645de865eeSFilipe David Borba Manana 
5655de865eeSFilipe David Borba Manana 	return ret;
566097b8a7cSJan Schmidt }
567097b8a7cSJan Schmidt 
568097b8a7cSJan Schmidt static noinline int
569bd989ba3SJan Schmidt tree_mod_log_insert_move(struct btrfs_fs_info *fs_info,
570bd989ba3SJan Schmidt 			 struct extent_buffer *eb, int dst_slot, int src_slot,
571bd989ba3SJan Schmidt 			 int nr_items, gfp_t flags)
572bd989ba3SJan Schmidt {
5735de865eeSFilipe David Borba Manana 	struct tree_mod_elem *tm = NULL;
5745de865eeSFilipe David Borba Manana 	struct tree_mod_elem **tm_list = NULL;
5755de865eeSFilipe David Borba Manana 	int ret = 0;
576bd989ba3SJan Schmidt 	int i;
5775de865eeSFilipe David Borba Manana 	int locked = 0;
578bd989ba3SJan Schmidt 
5795de865eeSFilipe David Borba Manana 	if (!tree_mod_need_log(fs_info, eb))
580f395694cSJan Schmidt 		return 0;
581bd989ba3SJan Schmidt 
58231e818feSDavid Sterba 	tm_list = kcalloc(nr_items, sizeof(struct tree_mod_elem *), flags);
5835de865eeSFilipe David Borba Manana 	if (!tm_list)
5845de865eeSFilipe David Borba Manana 		return -ENOMEM;
585bd989ba3SJan Schmidt 
586c8cc6341SJosef Bacik 	tm = kzalloc(sizeof(*tm), flags);
5875de865eeSFilipe David Borba Manana 	if (!tm) {
5885de865eeSFilipe David Borba Manana 		ret = -ENOMEM;
5895de865eeSFilipe David Borba Manana 		goto free_tms;
5905de865eeSFilipe David Borba Manana 	}
591f395694cSJan Schmidt 
592298cfd36SChandan Rajendra 	tm->logical = eb->start;
593bd989ba3SJan Schmidt 	tm->slot = src_slot;
594bd989ba3SJan Schmidt 	tm->move.dst_slot = dst_slot;
595bd989ba3SJan Schmidt 	tm->move.nr_items = nr_items;
596bd989ba3SJan Schmidt 	tm->op = MOD_LOG_MOVE_KEYS;
597bd989ba3SJan Schmidt 
5985de865eeSFilipe David Borba Manana 	for (i = 0; i + dst_slot < src_slot && i < nr_items; i++) {
5995de865eeSFilipe David Borba Manana 		tm_list[i] = alloc_tree_mod_elem(eb, i + dst_slot,
6005de865eeSFilipe David Borba Manana 		    MOD_LOG_KEY_REMOVE_WHILE_MOVING, flags);
6015de865eeSFilipe David Borba Manana 		if (!tm_list[i]) {
6025de865eeSFilipe David Borba Manana 			ret = -ENOMEM;
6035de865eeSFilipe David Borba Manana 			goto free_tms;
6045de865eeSFilipe David Borba Manana 		}
605bd989ba3SJan Schmidt 	}
606bd989ba3SJan Schmidt 
6075de865eeSFilipe David Borba Manana 	if (tree_mod_dont_log(fs_info, eb))
6085de865eeSFilipe David Borba Manana 		goto free_tms;
6095de865eeSFilipe David Borba Manana 	locked = 1;
6105de865eeSFilipe David Borba Manana 
6115de865eeSFilipe David Borba Manana 	/*
6125de865eeSFilipe David Borba Manana 	 * When we override something during the move, we log these removals.
6135de865eeSFilipe David Borba Manana 	 * This can only happen when we move towards the beginning of the
6145de865eeSFilipe David Borba Manana 	 * buffer, i.e. dst_slot < src_slot.
6155de865eeSFilipe David Borba Manana 	 */
6165de865eeSFilipe David Borba Manana 	for (i = 0; i + dst_slot < src_slot && i < nr_items; i++) {
6175de865eeSFilipe David Borba Manana 		ret = __tree_mod_log_insert(fs_info, tm_list[i]);
6185de865eeSFilipe David Borba Manana 		if (ret)
6195de865eeSFilipe David Borba Manana 			goto free_tms;
6205de865eeSFilipe David Borba Manana 	}
6215de865eeSFilipe David Borba Manana 
6225de865eeSFilipe David Borba Manana 	ret = __tree_mod_log_insert(fs_info, tm);
6235de865eeSFilipe David Borba Manana 	if (ret)
6245de865eeSFilipe David Borba Manana 		goto free_tms;
6255de865eeSFilipe David Borba Manana 	tree_mod_log_write_unlock(fs_info);
6265de865eeSFilipe David Borba Manana 	kfree(tm_list);
6275de865eeSFilipe David Borba Manana 
6285de865eeSFilipe David Borba Manana 	return 0;
6295de865eeSFilipe David Borba Manana free_tms:
6305de865eeSFilipe David Borba Manana 	for (i = 0; i < nr_items; i++) {
6315de865eeSFilipe David Borba Manana 		if (tm_list[i] && !RB_EMPTY_NODE(&tm_list[i]->node))
6325de865eeSFilipe David Borba Manana 			rb_erase(&tm_list[i]->node, &fs_info->tree_mod_log);
6335de865eeSFilipe David Borba Manana 		kfree(tm_list[i]);
6345de865eeSFilipe David Borba Manana 	}
6355de865eeSFilipe David Borba Manana 	if (locked)
6365de865eeSFilipe David Borba Manana 		tree_mod_log_write_unlock(fs_info);
6375de865eeSFilipe David Borba Manana 	kfree(tm_list);
6385de865eeSFilipe David Borba Manana 	kfree(tm);
6395de865eeSFilipe David Borba Manana 
6405de865eeSFilipe David Borba Manana 	return ret;
6415de865eeSFilipe David Borba Manana }
6425de865eeSFilipe David Borba Manana 
6435de865eeSFilipe David Borba Manana static inline int
6445de865eeSFilipe David Borba Manana __tree_mod_log_free_eb(struct btrfs_fs_info *fs_info,
6455de865eeSFilipe David Borba Manana 		       struct tree_mod_elem **tm_list,
6465de865eeSFilipe David Borba Manana 		       int nritems)
647097b8a7cSJan Schmidt {
6485de865eeSFilipe David Borba Manana 	int i, j;
649097b8a7cSJan Schmidt 	int ret;
650097b8a7cSJan Schmidt 
651097b8a7cSJan Schmidt 	for (i = nritems - 1; i >= 0; i--) {
6525de865eeSFilipe David Borba Manana 		ret = __tree_mod_log_insert(fs_info, tm_list[i]);
6535de865eeSFilipe David Borba Manana 		if (ret) {
6545de865eeSFilipe David Borba Manana 			for (j = nritems - 1; j > i; j--)
6555de865eeSFilipe David Borba Manana 				rb_erase(&tm_list[j]->node,
6565de865eeSFilipe David Borba Manana 					 &fs_info->tree_mod_log);
6575de865eeSFilipe David Borba Manana 			return ret;
658097b8a7cSJan Schmidt 		}
659097b8a7cSJan Schmidt 	}
660097b8a7cSJan Schmidt 
6615de865eeSFilipe David Borba Manana 	return 0;
6625de865eeSFilipe David Borba Manana }
6635de865eeSFilipe David Borba Manana 
664bd989ba3SJan Schmidt static noinline int
665bd989ba3SJan Schmidt tree_mod_log_insert_root(struct btrfs_fs_info *fs_info,
666bd989ba3SJan Schmidt 			 struct extent_buffer *old_root,
66790f8d62eSJan Schmidt 			 struct extent_buffer *new_root, gfp_t flags,
66890f8d62eSJan Schmidt 			 int log_removal)
669bd989ba3SJan Schmidt {
6705de865eeSFilipe David Borba Manana 	struct tree_mod_elem *tm = NULL;
6715de865eeSFilipe David Borba Manana 	struct tree_mod_elem **tm_list = NULL;
6725de865eeSFilipe David Borba Manana 	int nritems = 0;
6735de865eeSFilipe David Borba Manana 	int ret = 0;
6745de865eeSFilipe David Borba Manana 	int i;
675bd989ba3SJan Schmidt 
6765de865eeSFilipe David Borba Manana 	if (!tree_mod_need_log(fs_info, NULL))
677097b8a7cSJan Schmidt 		return 0;
678097b8a7cSJan Schmidt 
6795de865eeSFilipe David Borba Manana 	if (log_removal && btrfs_header_level(old_root) > 0) {
6805de865eeSFilipe David Borba Manana 		nritems = btrfs_header_nritems(old_root);
68131e818feSDavid Sterba 		tm_list = kcalloc(nritems, sizeof(struct tree_mod_elem *),
6825de865eeSFilipe David Borba Manana 				  flags);
6835de865eeSFilipe David Borba Manana 		if (!tm_list) {
6845de865eeSFilipe David Borba Manana 			ret = -ENOMEM;
6855de865eeSFilipe David Borba Manana 			goto free_tms;
6865de865eeSFilipe David Borba Manana 		}
6875de865eeSFilipe David Borba Manana 		for (i = 0; i < nritems; i++) {
6885de865eeSFilipe David Borba Manana 			tm_list[i] = alloc_tree_mod_elem(old_root, i,
6895de865eeSFilipe David Borba Manana 			    MOD_LOG_KEY_REMOVE_WHILE_FREEING, flags);
6905de865eeSFilipe David Borba Manana 			if (!tm_list[i]) {
6915de865eeSFilipe David Borba Manana 				ret = -ENOMEM;
6925de865eeSFilipe David Borba Manana 				goto free_tms;
6935de865eeSFilipe David Borba Manana 			}
6945de865eeSFilipe David Borba Manana 		}
6955de865eeSFilipe David Borba Manana 	}
696d9abbf1cSJan Schmidt 
697c8cc6341SJosef Bacik 	tm = kzalloc(sizeof(*tm), flags);
6985de865eeSFilipe David Borba Manana 	if (!tm) {
6995de865eeSFilipe David Borba Manana 		ret = -ENOMEM;
7005de865eeSFilipe David Borba Manana 		goto free_tms;
7015de865eeSFilipe David Borba Manana 	}
702bd989ba3SJan Schmidt 
703298cfd36SChandan Rajendra 	tm->logical = new_root->start;
704bd989ba3SJan Schmidt 	tm->old_root.logical = old_root->start;
705bd989ba3SJan Schmidt 	tm->old_root.level = btrfs_header_level(old_root);
706bd989ba3SJan Schmidt 	tm->generation = btrfs_header_generation(old_root);
707bd989ba3SJan Schmidt 	tm->op = MOD_LOG_ROOT_REPLACE;
708bd989ba3SJan Schmidt 
7095de865eeSFilipe David Borba Manana 	if (tree_mod_dont_log(fs_info, NULL))
7105de865eeSFilipe David Borba Manana 		goto free_tms;
7115de865eeSFilipe David Borba Manana 
7125de865eeSFilipe David Borba Manana 	if (tm_list)
7135de865eeSFilipe David Borba Manana 		ret = __tree_mod_log_free_eb(fs_info, tm_list, nritems);
7145de865eeSFilipe David Borba Manana 	if (!ret)
7155de865eeSFilipe David Borba Manana 		ret = __tree_mod_log_insert(fs_info, tm);
7165de865eeSFilipe David Borba Manana 
7175de865eeSFilipe David Borba Manana 	tree_mod_log_write_unlock(fs_info);
7185de865eeSFilipe David Borba Manana 	if (ret)
7195de865eeSFilipe David Borba Manana 		goto free_tms;
7205de865eeSFilipe David Borba Manana 	kfree(tm_list);
7215de865eeSFilipe David Borba Manana 
7225de865eeSFilipe David Borba Manana 	return ret;
7235de865eeSFilipe David Borba Manana 
7245de865eeSFilipe David Borba Manana free_tms:
7255de865eeSFilipe David Borba Manana 	if (tm_list) {
7265de865eeSFilipe David Borba Manana 		for (i = 0; i < nritems; i++)
7275de865eeSFilipe David Borba Manana 			kfree(tm_list[i]);
7285de865eeSFilipe David Borba Manana 		kfree(tm_list);
7295de865eeSFilipe David Borba Manana 	}
7305de865eeSFilipe David Borba Manana 	kfree(tm);
7315de865eeSFilipe David Borba Manana 
7325de865eeSFilipe David Borba Manana 	return ret;
733bd989ba3SJan Schmidt }
734bd989ba3SJan Schmidt 
735bd989ba3SJan Schmidt static struct tree_mod_elem *
736bd989ba3SJan Schmidt __tree_mod_log_search(struct btrfs_fs_info *fs_info, u64 start, u64 min_seq,
737bd989ba3SJan Schmidt 		      int smallest)
738bd989ba3SJan Schmidt {
739bd989ba3SJan Schmidt 	struct rb_root *tm_root;
740bd989ba3SJan Schmidt 	struct rb_node *node;
741bd989ba3SJan Schmidt 	struct tree_mod_elem *cur = NULL;
742bd989ba3SJan Schmidt 	struct tree_mod_elem *found = NULL;
743bd989ba3SJan Schmidt 
744097b8a7cSJan Schmidt 	tree_mod_log_read_lock(fs_info);
745bd989ba3SJan Schmidt 	tm_root = &fs_info->tree_mod_log;
746bd989ba3SJan Schmidt 	node = tm_root->rb_node;
747bd989ba3SJan Schmidt 	while (node) {
748bd989ba3SJan Schmidt 		cur = container_of(node, struct tree_mod_elem, node);
749298cfd36SChandan Rajendra 		if (cur->logical < start) {
750bd989ba3SJan Schmidt 			node = node->rb_left;
751298cfd36SChandan Rajendra 		} else if (cur->logical > start) {
752bd989ba3SJan Schmidt 			node = node->rb_right;
753097b8a7cSJan Schmidt 		} else if (cur->seq < min_seq) {
754bd989ba3SJan Schmidt 			node = node->rb_left;
755bd989ba3SJan Schmidt 		} else if (!smallest) {
756bd989ba3SJan Schmidt 			/* we want the node with the highest seq */
757bd989ba3SJan Schmidt 			if (found)
758097b8a7cSJan Schmidt 				BUG_ON(found->seq > cur->seq);
759bd989ba3SJan Schmidt 			found = cur;
760bd989ba3SJan Schmidt 			node = node->rb_left;
761097b8a7cSJan Schmidt 		} else if (cur->seq > min_seq) {
762bd989ba3SJan Schmidt 			/* we want the node with the smallest seq */
763bd989ba3SJan Schmidt 			if (found)
764097b8a7cSJan Schmidt 				BUG_ON(found->seq < cur->seq);
765bd989ba3SJan Schmidt 			found = cur;
766bd989ba3SJan Schmidt 			node = node->rb_right;
767bd989ba3SJan Schmidt 		} else {
768bd989ba3SJan Schmidt 			found = cur;
769bd989ba3SJan Schmidt 			break;
770bd989ba3SJan Schmidt 		}
771bd989ba3SJan Schmidt 	}
772097b8a7cSJan Schmidt 	tree_mod_log_read_unlock(fs_info);
773bd989ba3SJan Schmidt 
774bd989ba3SJan Schmidt 	return found;
775bd989ba3SJan Schmidt }
776bd989ba3SJan Schmidt 
777bd989ba3SJan Schmidt /*
778bd989ba3SJan Schmidt  * this returns the element from the log with the smallest time sequence
779bd989ba3SJan Schmidt  * value that's in the log (the oldest log item). any element with a time
780bd989ba3SJan Schmidt  * sequence lower than min_seq will be ignored.
781bd989ba3SJan Schmidt  */
782bd989ba3SJan Schmidt static struct tree_mod_elem *
783bd989ba3SJan Schmidt tree_mod_log_search_oldest(struct btrfs_fs_info *fs_info, u64 start,
784bd989ba3SJan Schmidt 			   u64 min_seq)
785bd989ba3SJan Schmidt {
786bd989ba3SJan Schmidt 	return __tree_mod_log_search(fs_info, start, min_seq, 1);
787bd989ba3SJan Schmidt }
788bd989ba3SJan Schmidt 
789bd989ba3SJan Schmidt /*
790bd989ba3SJan Schmidt  * this returns the element from the log with the largest time sequence
791bd989ba3SJan Schmidt  * value that's in the log (the most recent log item). any element with
792bd989ba3SJan Schmidt  * a time sequence lower than min_seq will be ignored.
793bd989ba3SJan Schmidt  */
794bd989ba3SJan Schmidt static struct tree_mod_elem *
795bd989ba3SJan Schmidt tree_mod_log_search(struct btrfs_fs_info *fs_info, u64 start, u64 min_seq)
796bd989ba3SJan Schmidt {
797bd989ba3SJan Schmidt 	return __tree_mod_log_search(fs_info, start, min_seq, 0);
798bd989ba3SJan Schmidt }
799bd989ba3SJan Schmidt 
8005de865eeSFilipe David Borba Manana static noinline int
801bd989ba3SJan Schmidt tree_mod_log_eb_copy(struct btrfs_fs_info *fs_info, struct extent_buffer *dst,
802bd989ba3SJan Schmidt 		     struct extent_buffer *src, unsigned long dst_offset,
80390f8d62eSJan Schmidt 		     unsigned long src_offset, int nr_items)
804bd989ba3SJan Schmidt {
8055de865eeSFilipe David Borba Manana 	int ret = 0;
8065de865eeSFilipe David Borba Manana 	struct tree_mod_elem **tm_list = NULL;
8075de865eeSFilipe David Borba Manana 	struct tree_mod_elem **tm_list_add, **tm_list_rem;
808bd989ba3SJan Schmidt 	int i;
8095de865eeSFilipe David Borba Manana 	int locked = 0;
810bd989ba3SJan Schmidt 
8115de865eeSFilipe David Borba Manana 	if (!tree_mod_need_log(fs_info, NULL))
8125de865eeSFilipe David Borba Manana 		return 0;
813bd989ba3SJan Schmidt 
814c8cc6341SJosef Bacik 	if (btrfs_header_level(dst) == 0 && btrfs_header_level(src) == 0)
8155de865eeSFilipe David Borba Manana 		return 0;
8165de865eeSFilipe David Borba Manana 
81731e818feSDavid Sterba 	tm_list = kcalloc(nr_items * 2, sizeof(struct tree_mod_elem *),
8185de865eeSFilipe David Borba Manana 			  GFP_NOFS);
8195de865eeSFilipe David Borba Manana 	if (!tm_list)
8205de865eeSFilipe David Borba Manana 		return -ENOMEM;
8215de865eeSFilipe David Borba Manana 
8225de865eeSFilipe David Borba Manana 	tm_list_add = tm_list;
8235de865eeSFilipe David Borba Manana 	tm_list_rem = tm_list + nr_items;
8245de865eeSFilipe David Borba Manana 	for (i = 0; i < nr_items; i++) {
8255de865eeSFilipe David Borba Manana 		tm_list_rem[i] = alloc_tree_mod_elem(src, i + src_offset,
8265de865eeSFilipe David Borba Manana 		    MOD_LOG_KEY_REMOVE, GFP_NOFS);
8275de865eeSFilipe David Borba Manana 		if (!tm_list_rem[i]) {
8285de865eeSFilipe David Borba Manana 			ret = -ENOMEM;
8295de865eeSFilipe David Borba Manana 			goto free_tms;
8305de865eeSFilipe David Borba Manana 		}
8315de865eeSFilipe David Borba Manana 
8325de865eeSFilipe David Borba Manana 		tm_list_add[i] = alloc_tree_mod_elem(dst, i + dst_offset,
8335de865eeSFilipe David Borba Manana 		    MOD_LOG_KEY_ADD, GFP_NOFS);
8345de865eeSFilipe David Borba Manana 		if (!tm_list_add[i]) {
8355de865eeSFilipe David Borba Manana 			ret = -ENOMEM;
8365de865eeSFilipe David Borba Manana 			goto free_tms;
8375de865eeSFilipe David Borba Manana 		}
8385de865eeSFilipe David Borba Manana 	}
8395de865eeSFilipe David Borba Manana 
8405de865eeSFilipe David Borba Manana 	if (tree_mod_dont_log(fs_info, NULL))
8415de865eeSFilipe David Borba Manana 		goto free_tms;
8425de865eeSFilipe David Borba Manana 	locked = 1;
843bd989ba3SJan Schmidt 
844bd989ba3SJan Schmidt 	for (i = 0; i < nr_items; i++) {
8455de865eeSFilipe David Borba Manana 		ret = __tree_mod_log_insert(fs_info, tm_list_rem[i]);
8465de865eeSFilipe David Borba Manana 		if (ret)
8475de865eeSFilipe David Borba Manana 			goto free_tms;
8485de865eeSFilipe David Borba Manana 		ret = __tree_mod_log_insert(fs_info, tm_list_add[i]);
8495de865eeSFilipe David Borba Manana 		if (ret)
8505de865eeSFilipe David Borba Manana 			goto free_tms;
851bd989ba3SJan Schmidt 	}
8525de865eeSFilipe David Borba Manana 
8535de865eeSFilipe David Borba Manana 	tree_mod_log_write_unlock(fs_info);
8545de865eeSFilipe David Borba Manana 	kfree(tm_list);
8555de865eeSFilipe David Borba Manana 
8565de865eeSFilipe David Borba Manana 	return 0;
8575de865eeSFilipe David Borba Manana 
8585de865eeSFilipe David Borba Manana free_tms:
8595de865eeSFilipe David Borba Manana 	for (i = 0; i < nr_items * 2; i++) {
8605de865eeSFilipe David Borba Manana 		if (tm_list[i] && !RB_EMPTY_NODE(&tm_list[i]->node))
8615de865eeSFilipe David Borba Manana 			rb_erase(&tm_list[i]->node, &fs_info->tree_mod_log);
8625de865eeSFilipe David Borba Manana 		kfree(tm_list[i]);
8635de865eeSFilipe David Borba Manana 	}
8645de865eeSFilipe David Borba Manana 	if (locked)
8655de865eeSFilipe David Borba Manana 		tree_mod_log_write_unlock(fs_info);
8665de865eeSFilipe David Borba Manana 	kfree(tm_list);
8675de865eeSFilipe David Borba Manana 
8685de865eeSFilipe David Borba Manana 	return ret;
869bd989ba3SJan Schmidt }
870bd989ba3SJan Schmidt 
871bd989ba3SJan Schmidt static inline void
872bd989ba3SJan Schmidt tree_mod_log_eb_move(struct btrfs_fs_info *fs_info, struct extent_buffer *dst,
873bd989ba3SJan Schmidt 		     int dst_offset, int src_offset, int nr_items)
874bd989ba3SJan Schmidt {
875bd989ba3SJan Schmidt 	int ret;
876bd989ba3SJan Schmidt 	ret = tree_mod_log_insert_move(fs_info, dst, dst_offset, src_offset,
877bd989ba3SJan Schmidt 				       nr_items, GFP_NOFS);
878bd989ba3SJan Schmidt 	BUG_ON(ret < 0);
879bd989ba3SJan Schmidt }
880bd989ba3SJan Schmidt 
881097b8a7cSJan Schmidt static noinline void
882bd989ba3SJan Schmidt tree_mod_log_set_node_key(struct btrfs_fs_info *fs_info,
88332adf090SLiu Bo 			  struct extent_buffer *eb, int slot, int atomic)
884bd989ba3SJan Schmidt {
885bd989ba3SJan Schmidt 	int ret;
886bd989ba3SJan Schmidt 
88778357766SFilipe David Borba Manana 	ret = tree_mod_log_insert_key(fs_info, eb, slot,
888bd989ba3SJan Schmidt 					MOD_LOG_KEY_REPLACE,
889bd989ba3SJan Schmidt 					atomic ? GFP_ATOMIC : GFP_NOFS);
890bd989ba3SJan Schmidt 	BUG_ON(ret < 0);
891bd989ba3SJan Schmidt }
892bd989ba3SJan Schmidt 
8935de865eeSFilipe David Borba Manana static noinline int
894097b8a7cSJan Schmidt tree_mod_log_free_eb(struct btrfs_fs_info *fs_info, struct extent_buffer *eb)
895bd989ba3SJan Schmidt {
8965de865eeSFilipe David Borba Manana 	struct tree_mod_elem **tm_list = NULL;
8975de865eeSFilipe David Borba Manana 	int nritems = 0;
8985de865eeSFilipe David Borba Manana 	int i;
8995de865eeSFilipe David Borba Manana 	int ret = 0;
9005de865eeSFilipe David Borba Manana 
9015de865eeSFilipe David Borba Manana 	if (btrfs_header_level(eb) == 0)
9025de865eeSFilipe David Borba Manana 		return 0;
9035de865eeSFilipe David Borba Manana 
9045de865eeSFilipe David Borba Manana 	if (!tree_mod_need_log(fs_info, NULL))
9055de865eeSFilipe David Borba Manana 		return 0;
9065de865eeSFilipe David Borba Manana 
9075de865eeSFilipe David Borba Manana 	nritems = btrfs_header_nritems(eb);
90831e818feSDavid Sterba 	tm_list = kcalloc(nritems, sizeof(struct tree_mod_elem *), GFP_NOFS);
9095de865eeSFilipe David Borba Manana 	if (!tm_list)
9105de865eeSFilipe David Borba Manana 		return -ENOMEM;
9115de865eeSFilipe David Borba Manana 
9125de865eeSFilipe David Borba Manana 	for (i = 0; i < nritems; i++) {
9135de865eeSFilipe David Borba Manana 		tm_list[i] = alloc_tree_mod_elem(eb, i,
9145de865eeSFilipe David Borba Manana 		    MOD_LOG_KEY_REMOVE_WHILE_FREEING, GFP_NOFS);
9155de865eeSFilipe David Borba Manana 		if (!tm_list[i]) {
9165de865eeSFilipe David Borba Manana 			ret = -ENOMEM;
9175de865eeSFilipe David Borba Manana 			goto free_tms;
9185de865eeSFilipe David Borba Manana 		}
9195de865eeSFilipe David Borba Manana 	}
9205de865eeSFilipe David Borba Manana 
921e9b7fd4dSJan Schmidt 	if (tree_mod_dont_log(fs_info, eb))
9225de865eeSFilipe David Borba Manana 		goto free_tms;
9235de865eeSFilipe David Borba Manana 
9245de865eeSFilipe David Borba Manana 	ret = __tree_mod_log_free_eb(fs_info, tm_list, nritems);
9255de865eeSFilipe David Borba Manana 	tree_mod_log_write_unlock(fs_info);
9265de865eeSFilipe David Borba Manana 	if (ret)
9275de865eeSFilipe David Borba Manana 		goto free_tms;
9285de865eeSFilipe David Borba Manana 	kfree(tm_list);
9295de865eeSFilipe David Borba Manana 
9305de865eeSFilipe David Borba Manana 	return 0;
9315de865eeSFilipe David Borba Manana 
9325de865eeSFilipe David Borba Manana free_tms:
9335de865eeSFilipe David Borba Manana 	for (i = 0; i < nritems; i++)
9345de865eeSFilipe David Borba Manana 		kfree(tm_list[i]);
9355de865eeSFilipe David Borba Manana 	kfree(tm_list);
9365de865eeSFilipe David Borba Manana 
9375de865eeSFilipe David Borba Manana 	return ret;
938bd989ba3SJan Schmidt }
939bd989ba3SJan Schmidt 
940097b8a7cSJan Schmidt static noinline void
941bd989ba3SJan Schmidt tree_mod_log_set_root_pointer(struct btrfs_root *root,
94290f8d62eSJan Schmidt 			      struct extent_buffer *new_root_node,
94390f8d62eSJan Schmidt 			      int log_removal)
944bd989ba3SJan Schmidt {
945bd989ba3SJan Schmidt 	int ret;
946bd989ba3SJan Schmidt 	ret = tree_mod_log_insert_root(root->fs_info, root->node,
94790f8d62eSJan Schmidt 				       new_root_node, GFP_NOFS, log_removal);
948bd989ba3SJan Schmidt 	BUG_ON(ret < 0);
949bd989ba3SJan Schmidt }
950bd989ba3SJan Schmidt 
951d352ac68SChris Mason /*
9525d4f98a2SYan Zheng  * check if the tree block can be shared by multiple trees
9535d4f98a2SYan Zheng  */
9545d4f98a2SYan Zheng int btrfs_block_can_be_shared(struct btrfs_root *root,
9555d4f98a2SYan Zheng 			      struct extent_buffer *buf)
9565d4f98a2SYan Zheng {
9575d4f98a2SYan Zheng 	/*
95801327610SNicholas D Steeves 	 * Tree blocks not in reference counted trees and tree roots
9595d4f98a2SYan Zheng 	 * are never shared. If a block was allocated after the last
9605d4f98a2SYan Zheng 	 * snapshot and the block was not allocated by tree relocation,
9615d4f98a2SYan Zheng 	 * we know the block is not shared.
9625d4f98a2SYan Zheng 	 */
96327cdeb70SMiao Xie 	if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
9645d4f98a2SYan Zheng 	    buf != root->node && buf != root->commit_root &&
9655d4f98a2SYan Zheng 	    (btrfs_header_generation(buf) <=
9665d4f98a2SYan Zheng 	     btrfs_root_last_snapshot(&root->root_item) ||
9675d4f98a2SYan Zheng 	     btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)))
9685d4f98a2SYan Zheng 		return 1;
9695d4f98a2SYan Zheng #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
97027cdeb70SMiao Xie 	if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
9715d4f98a2SYan Zheng 	    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
9725d4f98a2SYan Zheng 		return 1;
9735d4f98a2SYan Zheng #endif
9745d4f98a2SYan Zheng 	return 0;
9755d4f98a2SYan Zheng }
9765d4f98a2SYan Zheng 
9775d4f98a2SYan Zheng static noinline int update_ref_for_cow(struct btrfs_trans_handle *trans,
9785d4f98a2SYan Zheng 				       struct btrfs_root *root,
9795d4f98a2SYan Zheng 				       struct extent_buffer *buf,
980f0486c68SYan, Zheng 				       struct extent_buffer *cow,
981f0486c68SYan, Zheng 				       int *last_ref)
9825d4f98a2SYan Zheng {
983*0b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
9845d4f98a2SYan Zheng 	u64 refs;
9855d4f98a2SYan Zheng 	u64 owner;
9865d4f98a2SYan Zheng 	u64 flags;
9875d4f98a2SYan Zheng 	u64 new_flags = 0;
9885d4f98a2SYan Zheng 	int ret;
9895d4f98a2SYan Zheng 
9905d4f98a2SYan Zheng 	/*
9915d4f98a2SYan Zheng 	 * Backrefs update rules:
9925d4f98a2SYan Zheng 	 *
9935d4f98a2SYan Zheng 	 * Always use full backrefs for extent pointers in tree block
9945d4f98a2SYan Zheng 	 * allocated by tree relocation.
9955d4f98a2SYan Zheng 	 *
9965d4f98a2SYan Zheng 	 * If a shared tree block is no longer referenced by its owner
9975d4f98a2SYan Zheng 	 * tree (btrfs_header_owner(buf) == root->root_key.objectid),
9985d4f98a2SYan Zheng 	 * use full backrefs for extent pointers in tree block.
9995d4f98a2SYan Zheng 	 *
10005d4f98a2SYan Zheng 	 * If a tree block is been relocating
10015d4f98a2SYan Zheng 	 * (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID),
10025d4f98a2SYan Zheng 	 * use full backrefs for extent pointers in tree block.
10035d4f98a2SYan Zheng 	 * The reason for this is some operations (such as drop tree)
10045d4f98a2SYan Zheng 	 * are only allowed for blocks use full backrefs.
10055d4f98a2SYan Zheng 	 */
10065d4f98a2SYan Zheng 
10075d4f98a2SYan Zheng 	if (btrfs_block_can_be_shared(root, buf)) {
10085d4f98a2SYan Zheng 		ret = btrfs_lookup_extent_info(trans, root, buf->start,
10093173a18fSJosef Bacik 					       btrfs_header_level(buf), 1,
10103173a18fSJosef Bacik 					       &refs, &flags);
1011be1a5564SMark Fasheh 		if (ret)
1012be1a5564SMark Fasheh 			return ret;
1013e5df9573SMark Fasheh 		if (refs == 0) {
1014e5df9573SMark Fasheh 			ret = -EROFS;
1015*0b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
1016e5df9573SMark Fasheh 			return ret;
1017e5df9573SMark Fasheh 		}
10185d4f98a2SYan Zheng 	} else {
10195d4f98a2SYan Zheng 		refs = 1;
10205d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
10215d4f98a2SYan Zheng 		    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
10225d4f98a2SYan Zheng 			flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
10235d4f98a2SYan Zheng 		else
10245d4f98a2SYan Zheng 			flags = 0;
10255d4f98a2SYan Zheng 	}
10265d4f98a2SYan Zheng 
10275d4f98a2SYan Zheng 	owner = btrfs_header_owner(buf);
10285d4f98a2SYan Zheng 	BUG_ON(owner == BTRFS_TREE_RELOC_OBJECTID &&
10295d4f98a2SYan Zheng 	       !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
10305d4f98a2SYan Zheng 
10315d4f98a2SYan Zheng 	if (refs > 1) {
10325d4f98a2SYan Zheng 		if ((owner == root->root_key.objectid ||
10335d4f98a2SYan Zheng 		     root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) &&
10345d4f98a2SYan Zheng 		    !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)) {
1035e339a6b0SJosef Bacik 			ret = btrfs_inc_ref(trans, root, buf, 1);
103679787eaaSJeff Mahoney 			BUG_ON(ret); /* -ENOMEM */
10375d4f98a2SYan Zheng 
10385d4f98a2SYan Zheng 			if (root->root_key.objectid ==
10395d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID) {
1040e339a6b0SJosef Bacik 				ret = btrfs_dec_ref(trans, root, buf, 0);
104179787eaaSJeff Mahoney 				BUG_ON(ret); /* -ENOMEM */
1042e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
104379787eaaSJeff Mahoney 				BUG_ON(ret); /* -ENOMEM */
10445d4f98a2SYan Zheng 			}
10455d4f98a2SYan Zheng 			new_flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
10465d4f98a2SYan Zheng 		} else {
10475d4f98a2SYan Zheng 
10485d4f98a2SYan Zheng 			if (root->root_key.objectid ==
10495d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID)
1050e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
10515d4f98a2SYan Zheng 			else
1052e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 0);
105379787eaaSJeff Mahoney 			BUG_ON(ret); /* -ENOMEM */
10545d4f98a2SYan Zheng 		}
10555d4f98a2SYan Zheng 		if (new_flags != 0) {
1056b1c79e09SJosef Bacik 			int level = btrfs_header_level(buf);
1057b1c79e09SJosef Bacik 
10585d4f98a2SYan Zheng 			ret = btrfs_set_disk_extent_flags(trans, root,
10595d4f98a2SYan Zheng 							  buf->start,
10605d4f98a2SYan Zheng 							  buf->len,
1061b1c79e09SJosef Bacik 							  new_flags, level, 0);
1062be1a5564SMark Fasheh 			if (ret)
1063be1a5564SMark Fasheh 				return ret;
10645d4f98a2SYan Zheng 		}
10655d4f98a2SYan Zheng 	} else {
10665d4f98a2SYan Zheng 		if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
10675d4f98a2SYan Zheng 			if (root->root_key.objectid ==
10685d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID)
1069e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
10705d4f98a2SYan Zheng 			else
1071e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 0);
107279787eaaSJeff Mahoney 			BUG_ON(ret); /* -ENOMEM */
1073e339a6b0SJosef Bacik 			ret = btrfs_dec_ref(trans, root, buf, 1);
107479787eaaSJeff Mahoney 			BUG_ON(ret); /* -ENOMEM */
10755d4f98a2SYan Zheng 		}
1076*0b246afaSJeff Mahoney 		clean_tree_block(trans, fs_info, buf);
1077f0486c68SYan, Zheng 		*last_ref = 1;
10785d4f98a2SYan Zheng 	}
10795d4f98a2SYan Zheng 	return 0;
10805d4f98a2SYan Zheng }
10815d4f98a2SYan Zheng 
10825d4f98a2SYan Zheng /*
1083d397712bSChris Mason  * does the dirty work in cow of a single block.  The parent block (if
1084d397712bSChris Mason  * supplied) is updated to point to the new cow copy.  The new buffer is marked
1085d397712bSChris Mason  * dirty and returned locked.  If you modify the block it needs to be marked
1086d397712bSChris Mason  * dirty again.
1087d352ac68SChris Mason  *
1088d352ac68SChris Mason  * search_start -- an allocation hint for the new block
1089d352ac68SChris Mason  *
1090d397712bSChris Mason  * empty_size -- a hint that you plan on doing more cow.  This is the size in
1091d397712bSChris Mason  * bytes the allocator should try to find free next to the block it returns.
1092d397712bSChris Mason  * This is just a hint and may be ignored by the allocator.
1093d352ac68SChris Mason  */
1094d397712bSChris Mason static noinline int __btrfs_cow_block(struct btrfs_trans_handle *trans,
10955f39d397SChris Mason 			     struct btrfs_root *root,
10965f39d397SChris Mason 			     struct extent_buffer *buf,
10975f39d397SChris Mason 			     struct extent_buffer *parent, int parent_slot,
10985f39d397SChris Mason 			     struct extent_buffer **cow_ret,
10999fa8cfe7SChris Mason 			     u64 search_start, u64 empty_size)
11006702ed49SChris Mason {
1101*0b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
11025d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
11035f39d397SChris Mason 	struct extent_buffer *cow;
1104be1a5564SMark Fasheh 	int level, ret;
1105f0486c68SYan, Zheng 	int last_ref = 0;
1106925baeddSChris Mason 	int unlock_orig = 0;
11070f5053ebSGoldwyn Rodrigues 	u64 parent_start = 0;
11086702ed49SChris Mason 
1109925baeddSChris Mason 	if (*cow_ret == buf)
1110925baeddSChris Mason 		unlock_orig = 1;
1111925baeddSChris Mason 
1112b9447ef8SChris Mason 	btrfs_assert_tree_locked(buf);
1113925baeddSChris Mason 
111427cdeb70SMiao Xie 	WARN_ON(test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
1115*0b246afaSJeff Mahoney 		trans->transid != fs_info->running_transaction->transid);
111627cdeb70SMiao Xie 	WARN_ON(test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
111727cdeb70SMiao Xie 		trans->transid != root->last_trans);
11185f39d397SChris Mason 
11197bb86316SChris Mason 	level = btrfs_header_level(buf);
112031840ae1SZheng Yan 
11215d4f98a2SYan Zheng 	if (level == 0)
11225d4f98a2SYan Zheng 		btrfs_item_key(buf, &disk_key, 0);
11235d4f98a2SYan Zheng 	else
11245d4f98a2SYan Zheng 		btrfs_node_key(buf, &disk_key, 0);
11255d4f98a2SYan Zheng 
11260f5053ebSGoldwyn Rodrigues 	if ((root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) && parent)
11275d4f98a2SYan Zheng 		parent_start = parent->start;
11285d4f98a2SYan Zheng 
11294d75f8a9SDavid Sterba 	cow = btrfs_alloc_tree_block(trans, root, parent_start,
11304d75f8a9SDavid Sterba 			root->root_key.objectid, &disk_key, level,
11314d75f8a9SDavid Sterba 			search_start, empty_size);
11326702ed49SChris Mason 	if (IS_ERR(cow))
11336702ed49SChris Mason 		return PTR_ERR(cow);
11346702ed49SChris Mason 
1135b4ce94deSChris Mason 	/* cow is set to blocking by btrfs_init_new_buffer */
1136b4ce94deSChris Mason 
113758e8012cSDavid Sterba 	copy_extent_buffer_full(cow, buf);
1138db94535dSChris Mason 	btrfs_set_header_bytenr(cow, cow->start);
11395f39d397SChris Mason 	btrfs_set_header_generation(cow, trans->transid);
11405d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
11415d4f98a2SYan Zheng 	btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
11425d4f98a2SYan Zheng 				     BTRFS_HEADER_FLAG_RELOC);
11435d4f98a2SYan Zheng 	if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
11445d4f98a2SYan Zheng 		btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
11455d4f98a2SYan Zheng 	else
11465f39d397SChris Mason 		btrfs_set_header_owner(cow, root->root_key.objectid);
11476702ed49SChris Mason 
1148*0b246afaSJeff Mahoney 	write_extent_buffer_fsid(cow, fs_info->fsid);
11492b82032cSYan Zheng 
1150be1a5564SMark Fasheh 	ret = update_ref_for_cow(trans, root, buf, cow, &last_ref);
1151b68dc2a9SMark Fasheh 	if (ret) {
115266642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
1153b68dc2a9SMark Fasheh 		return ret;
1154b68dc2a9SMark Fasheh 	}
11551a40e23bSZheng Yan 
115627cdeb70SMiao Xie 	if (test_bit(BTRFS_ROOT_REF_COWS, &root->state)) {
115783d4cfd4SJosef Bacik 		ret = btrfs_reloc_cow_block(trans, root, buf, cow);
115893314e3bSZhaolei 		if (ret) {
115966642832SJeff Mahoney 			btrfs_abort_transaction(trans, ret);
116083d4cfd4SJosef Bacik 			return ret;
116183d4cfd4SJosef Bacik 		}
116293314e3bSZhaolei 	}
11633fd0a558SYan, Zheng 
11646702ed49SChris Mason 	if (buf == root->node) {
1165925baeddSChris Mason 		WARN_ON(parent && parent != buf);
11665d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
11675d4f98a2SYan Zheng 		    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
11685d4f98a2SYan Zheng 			parent_start = buf->start;
1169925baeddSChris Mason 
11705f39d397SChris Mason 		extent_buffer_get(cow);
117190f8d62eSJan Schmidt 		tree_mod_log_set_root_pointer(root, cow, 1);
1172240f62c8SChris Mason 		rcu_assign_pointer(root->node, cow);
1173925baeddSChris Mason 
1174f0486c68SYan, Zheng 		btrfs_free_tree_block(trans, root, buf, parent_start,
11755581a51aSJan Schmidt 				      last_ref);
11765f39d397SChris Mason 		free_extent_buffer(buf);
11770b86a832SChris Mason 		add_root_to_dirty_list(root);
11786702ed49SChris Mason 	} else {
11795d4f98a2SYan Zheng 		WARN_ON(trans->transid != btrfs_header_generation(parent));
1180*0b246afaSJeff Mahoney 		tree_mod_log_insert_key(fs_info, parent, parent_slot,
1181c8cc6341SJosef Bacik 					MOD_LOG_KEY_REPLACE, GFP_NOFS);
11825f39d397SChris Mason 		btrfs_set_node_blockptr(parent, parent_slot,
1183db94535dSChris Mason 					cow->start);
118474493f7aSChris Mason 		btrfs_set_node_ptr_generation(parent, parent_slot,
118574493f7aSChris Mason 					      trans->transid);
11866702ed49SChris Mason 		btrfs_mark_buffer_dirty(parent);
11875de865eeSFilipe David Borba Manana 		if (last_ref) {
1188*0b246afaSJeff Mahoney 			ret = tree_mod_log_free_eb(fs_info, buf);
11895de865eeSFilipe David Borba Manana 			if (ret) {
119066642832SJeff Mahoney 				btrfs_abort_transaction(trans, ret);
11915de865eeSFilipe David Borba Manana 				return ret;
11925de865eeSFilipe David Borba Manana 			}
11935de865eeSFilipe David Borba Manana 		}
1194f0486c68SYan, Zheng 		btrfs_free_tree_block(trans, root, buf, parent_start,
11955581a51aSJan Schmidt 				      last_ref);
11966702ed49SChris Mason 	}
1197925baeddSChris Mason 	if (unlock_orig)
1198925baeddSChris Mason 		btrfs_tree_unlock(buf);
11993083ee2eSJosef Bacik 	free_extent_buffer_stale(buf);
12006702ed49SChris Mason 	btrfs_mark_buffer_dirty(cow);
12016702ed49SChris Mason 	*cow_ret = cow;
12026702ed49SChris Mason 	return 0;
12036702ed49SChris Mason }
12046702ed49SChris Mason 
12055d9e75c4SJan Schmidt /*
12065d9e75c4SJan Schmidt  * returns the logical address of the oldest predecessor of the given root.
12075d9e75c4SJan Schmidt  * entries older than time_seq are ignored.
12085d9e75c4SJan Schmidt  */
12095d9e75c4SJan Schmidt static struct tree_mod_elem *
12105d9e75c4SJan Schmidt __tree_mod_log_oldest_root(struct btrfs_fs_info *fs_info,
121130b0463aSJan Schmidt 			   struct extent_buffer *eb_root, u64 time_seq)
12125d9e75c4SJan Schmidt {
12135d9e75c4SJan Schmidt 	struct tree_mod_elem *tm;
12145d9e75c4SJan Schmidt 	struct tree_mod_elem *found = NULL;
121530b0463aSJan Schmidt 	u64 root_logical = eb_root->start;
12165d9e75c4SJan Schmidt 	int looped = 0;
12175d9e75c4SJan Schmidt 
12185d9e75c4SJan Schmidt 	if (!time_seq)
121935a3621bSStefan Behrens 		return NULL;
12205d9e75c4SJan Schmidt 
12215d9e75c4SJan Schmidt 	/*
1222298cfd36SChandan Rajendra 	 * the very last operation that's logged for a root is the
1223298cfd36SChandan Rajendra 	 * replacement operation (if it is replaced at all). this has
1224298cfd36SChandan Rajendra 	 * the logical address of the *new* root, making it the very
1225298cfd36SChandan Rajendra 	 * first operation that's logged for this root.
12265d9e75c4SJan Schmidt 	 */
12275d9e75c4SJan Schmidt 	while (1) {
12285d9e75c4SJan Schmidt 		tm = tree_mod_log_search_oldest(fs_info, root_logical,
12295d9e75c4SJan Schmidt 						time_seq);
12305d9e75c4SJan Schmidt 		if (!looped && !tm)
123135a3621bSStefan Behrens 			return NULL;
12325d9e75c4SJan Schmidt 		/*
123328da9fb4SJan Schmidt 		 * if there are no tree operation for the oldest root, we simply
123428da9fb4SJan Schmidt 		 * return it. this should only happen if that (old) root is at
123528da9fb4SJan Schmidt 		 * level 0.
12365d9e75c4SJan Schmidt 		 */
123728da9fb4SJan Schmidt 		if (!tm)
123828da9fb4SJan Schmidt 			break;
12395d9e75c4SJan Schmidt 
124028da9fb4SJan Schmidt 		/*
124128da9fb4SJan Schmidt 		 * if there's an operation that's not a root replacement, we
124228da9fb4SJan Schmidt 		 * found the oldest version of our root. normally, we'll find a
124328da9fb4SJan Schmidt 		 * MOD_LOG_KEY_REMOVE_WHILE_FREEING operation here.
124428da9fb4SJan Schmidt 		 */
12455d9e75c4SJan Schmidt 		if (tm->op != MOD_LOG_ROOT_REPLACE)
12465d9e75c4SJan Schmidt 			break;
12475d9e75c4SJan Schmidt 
12485d9e75c4SJan Schmidt 		found = tm;
12495d9e75c4SJan Schmidt 		root_logical = tm->old_root.logical;
12505d9e75c4SJan Schmidt 		looped = 1;
12515d9e75c4SJan Schmidt 	}
12525d9e75c4SJan Schmidt 
1253a95236d9SJan Schmidt 	/* if there's no old root to return, return what we found instead */
1254a95236d9SJan Schmidt 	if (!found)
1255a95236d9SJan Schmidt 		found = tm;
1256a95236d9SJan Schmidt 
12575d9e75c4SJan Schmidt 	return found;
12585d9e75c4SJan Schmidt }
12595d9e75c4SJan Schmidt 
12605d9e75c4SJan Schmidt /*
12615d9e75c4SJan Schmidt  * tm is a pointer to the first operation to rewind within eb. then, all
126201327610SNicholas D Steeves  * previous operations will be rewound (until we reach something older than
12635d9e75c4SJan Schmidt  * time_seq).
12645d9e75c4SJan Schmidt  */
12655d9e75c4SJan Schmidt static void
1266f1ca7e98SJosef Bacik __tree_mod_log_rewind(struct btrfs_fs_info *fs_info, struct extent_buffer *eb,
1267f1ca7e98SJosef Bacik 		      u64 time_seq, struct tree_mod_elem *first_tm)
12685d9e75c4SJan Schmidt {
12695d9e75c4SJan Schmidt 	u32 n;
12705d9e75c4SJan Schmidt 	struct rb_node *next;
12715d9e75c4SJan Schmidt 	struct tree_mod_elem *tm = first_tm;
12725d9e75c4SJan Schmidt 	unsigned long o_dst;
12735d9e75c4SJan Schmidt 	unsigned long o_src;
12745d9e75c4SJan Schmidt 	unsigned long p_size = sizeof(struct btrfs_key_ptr);
12755d9e75c4SJan Schmidt 
12765d9e75c4SJan Schmidt 	n = btrfs_header_nritems(eb);
1277f1ca7e98SJosef Bacik 	tree_mod_log_read_lock(fs_info);
1278097b8a7cSJan Schmidt 	while (tm && tm->seq >= time_seq) {
12795d9e75c4SJan Schmidt 		/*
12805d9e75c4SJan Schmidt 		 * all the operations are recorded with the operator used for
12815d9e75c4SJan Schmidt 		 * the modification. as we're going backwards, we do the
12825d9e75c4SJan Schmidt 		 * opposite of each operation here.
12835d9e75c4SJan Schmidt 		 */
12845d9e75c4SJan Schmidt 		switch (tm->op) {
12855d9e75c4SJan Schmidt 		case MOD_LOG_KEY_REMOVE_WHILE_FREEING:
12865d9e75c4SJan Schmidt 			BUG_ON(tm->slot < n);
12871c697d4aSEric Sandeen 			/* Fallthrough */
128895c80bb1SLiu Bo 		case MOD_LOG_KEY_REMOVE_WHILE_MOVING:
12894c3e6969SChris Mason 		case MOD_LOG_KEY_REMOVE:
12905d9e75c4SJan Schmidt 			btrfs_set_node_key(eb, &tm->key, tm->slot);
12915d9e75c4SJan Schmidt 			btrfs_set_node_blockptr(eb, tm->slot, tm->blockptr);
12925d9e75c4SJan Schmidt 			btrfs_set_node_ptr_generation(eb, tm->slot,
12935d9e75c4SJan Schmidt 						      tm->generation);
12944c3e6969SChris Mason 			n++;
12955d9e75c4SJan Schmidt 			break;
12965d9e75c4SJan Schmidt 		case MOD_LOG_KEY_REPLACE:
12975d9e75c4SJan Schmidt 			BUG_ON(tm->slot >= n);
12985d9e75c4SJan Schmidt 			btrfs_set_node_key(eb, &tm->key, tm->slot);
12995d9e75c4SJan Schmidt 			btrfs_set_node_blockptr(eb, tm->slot, tm->blockptr);
13005d9e75c4SJan Schmidt 			btrfs_set_node_ptr_generation(eb, tm->slot,
13015d9e75c4SJan Schmidt 						      tm->generation);
13025d9e75c4SJan Schmidt 			break;
13035d9e75c4SJan Schmidt 		case MOD_LOG_KEY_ADD:
130419956c7eSJan Schmidt 			/* if a move operation is needed it's in the log */
13055d9e75c4SJan Schmidt 			n--;
13065d9e75c4SJan Schmidt 			break;
13075d9e75c4SJan Schmidt 		case MOD_LOG_MOVE_KEYS:
1308c3193108SJan Schmidt 			o_dst = btrfs_node_key_ptr_offset(tm->slot);
1309c3193108SJan Schmidt 			o_src = btrfs_node_key_ptr_offset(tm->move.dst_slot);
1310c3193108SJan Schmidt 			memmove_extent_buffer(eb, o_dst, o_src,
13115d9e75c4SJan Schmidt 					      tm->move.nr_items * p_size);
13125d9e75c4SJan Schmidt 			break;
13135d9e75c4SJan Schmidt 		case MOD_LOG_ROOT_REPLACE:
13145d9e75c4SJan Schmidt 			/*
13155d9e75c4SJan Schmidt 			 * this operation is special. for roots, this must be
13165d9e75c4SJan Schmidt 			 * handled explicitly before rewinding.
13175d9e75c4SJan Schmidt 			 * for non-roots, this operation may exist if the node
13185d9e75c4SJan Schmidt 			 * was a root: root A -> child B; then A gets empty and
13195d9e75c4SJan Schmidt 			 * B is promoted to the new root. in the mod log, we'll
13205d9e75c4SJan Schmidt 			 * have a root-replace operation for B, a tree block
13215d9e75c4SJan Schmidt 			 * that is no root. we simply ignore that operation.
13225d9e75c4SJan Schmidt 			 */
13235d9e75c4SJan Schmidt 			break;
13245d9e75c4SJan Schmidt 		}
13255d9e75c4SJan Schmidt 		next = rb_next(&tm->node);
13265d9e75c4SJan Schmidt 		if (!next)
13275d9e75c4SJan Schmidt 			break;
13285d9e75c4SJan Schmidt 		tm = container_of(next, struct tree_mod_elem, node);
1329298cfd36SChandan Rajendra 		if (tm->logical != first_tm->logical)
13305d9e75c4SJan Schmidt 			break;
13315d9e75c4SJan Schmidt 	}
1332f1ca7e98SJosef Bacik 	tree_mod_log_read_unlock(fs_info);
13335d9e75c4SJan Schmidt 	btrfs_set_header_nritems(eb, n);
13345d9e75c4SJan Schmidt }
13355d9e75c4SJan Schmidt 
133647fb091fSJan Schmidt /*
133701327610SNicholas D Steeves  * Called with eb read locked. If the buffer cannot be rewound, the same buffer
133847fb091fSJan Schmidt  * is returned. If rewind operations happen, a fresh buffer is returned. The
133947fb091fSJan Schmidt  * returned buffer is always read-locked. If the returned buffer is not the
134047fb091fSJan Schmidt  * input buffer, the lock on the input buffer is released and the input buffer
134147fb091fSJan Schmidt  * is freed (its refcount is decremented).
134247fb091fSJan Schmidt  */
13435d9e75c4SJan Schmidt static struct extent_buffer *
13449ec72677SJosef Bacik tree_mod_log_rewind(struct btrfs_fs_info *fs_info, struct btrfs_path *path,
13459ec72677SJosef Bacik 		    struct extent_buffer *eb, u64 time_seq)
13465d9e75c4SJan Schmidt {
13475d9e75c4SJan Schmidt 	struct extent_buffer *eb_rewin;
13485d9e75c4SJan Schmidt 	struct tree_mod_elem *tm;
13495d9e75c4SJan Schmidt 
13505d9e75c4SJan Schmidt 	if (!time_seq)
13515d9e75c4SJan Schmidt 		return eb;
13525d9e75c4SJan Schmidt 
13535d9e75c4SJan Schmidt 	if (btrfs_header_level(eb) == 0)
13545d9e75c4SJan Schmidt 		return eb;
13555d9e75c4SJan Schmidt 
13565d9e75c4SJan Schmidt 	tm = tree_mod_log_search(fs_info, eb->start, time_seq);
13575d9e75c4SJan Schmidt 	if (!tm)
13585d9e75c4SJan Schmidt 		return eb;
13595d9e75c4SJan Schmidt 
13609ec72677SJosef Bacik 	btrfs_set_path_blocking(path);
13619ec72677SJosef Bacik 	btrfs_set_lock_blocking_rw(eb, BTRFS_READ_LOCK);
13629ec72677SJosef Bacik 
13635d9e75c4SJan Schmidt 	if (tm->op == MOD_LOG_KEY_REMOVE_WHILE_FREEING) {
13645d9e75c4SJan Schmidt 		BUG_ON(tm->slot != 0);
1365da17066cSJeff Mahoney 		eb_rewin = alloc_dummy_extent_buffer(fs_info, eb->start);
1366db7f3436SJosef Bacik 		if (!eb_rewin) {
13679ec72677SJosef Bacik 			btrfs_tree_read_unlock_blocking(eb);
1368db7f3436SJosef Bacik 			free_extent_buffer(eb);
1369db7f3436SJosef Bacik 			return NULL;
1370db7f3436SJosef Bacik 		}
13715d9e75c4SJan Schmidt 		btrfs_set_header_bytenr(eb_rewin, eb->start);
13725d9e75c4SJan Schmidt 		btrfs_set_header_backref_rev(eb_rewin,
13735d9e75c4SJan Schmidt 					     btrfs_header_backref_rev(eb));
13745d9e75c4SJan Schmidt 		btrfs_set_header_owner(eb_rewin, btrfs_header_owner(eb));
1375c3193108SJan Schmidt 		btrfs_set_header_level(eb_rewin, btrfs_header_level(eb));
13765d9e75c4SJan Schmidt 	} else {
13775d9e75c4SJan Schmidt 		eb_rewin = btrfs_clone_extent_buffer(eb);
1378db7f3436SJosef Bacik 		if (!eb_rewin) {
13799ec72677SJosef Bacik 			btrfs_tree_read_unlock_blocking(eb);
1380db7f3436SJosef Bacik 			free_extent_buffer(eb);
1381db7f3436SJosef Bacik 			return NULL;
1382db7f3436SJosef Bacik 		}
13835d9e75c4SJan Schmidt 	}
13845d9e75c4SJan Schmidt 
13859ec72677SJosef Bacik 	btrfs_clear_path_blocking(path, NULL, BTRFS_READ_LOCK);
13869ec72677SJosef Bacik 	btrfs_tree_read_unlock_blocking(eb);
13875d9e75c4SJan Schmidt 	free_extent_buffer(eb);
13885d9e75c4SJan Schmidt 
138947fb091fSJan Schmidt 	extent_buffer_get(eb_rewin);
139047fb091fSJan Schmidt 	btrfs_tree_read_lock(eb_rewin);
1391f1ca7e98SJosef Bacik 	__tree_mod_log_rewind(fs_info, eb_rewin, time_seq, tm);
139257911b8bSJan Schmidt 	WARN_ON(btrfs_header_nritems(eb_rewin) >
1393da17066cSJeff Mahoney 		BTRFS_NODEPTRS_PER_BLOCK(fs_info));
13945d9e75c4SJan Schmidt 
13955d9e75c4SJan Schmidt 	return eb_rewin;
13965d9e75c4SJan Schmidt }
13975d9e75c4SJan Schmidt 
13988ba97a15SJan Schmidt /*
13998ba97a15SJan Schmidt  * get_old_root() rewinds the state of @root's root node to the given @time_seq
14008ba97a15SJan Schmidt  * value. If there are no changes, the current root->root_node is returned. If
14018ba97a15SJan Schmidt  * anything changed in between, there's a fresh buffer allocated on which the
14028ba97a15SJan Schmidt  * rewind operations are done. In any case, the returned buffer is read locked.
14038ba97a15SJan Schmidt  * Returns NULL on error (with no locks held).
14048ba97a15SJan Schmidt  */
14055d9e75c4SJan Schmidt static inline struct extent_buffer *
14065d9e75c4SJan Schmidt get_old_root(struct btrfs_root *root, u64 time_seq)
14075d9e75c4SJan Schmidt {
1408*0b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
14095d9e75c4SJan Schmidt 	struct tree_mod_elem *tm;
141030b0463aSJan Schmidt 	struct extent_buffer *eb = NULL;
141130b0463aSJan Schmidt 	struct extent_buffer *eb_root;
14127bfdcf7fSLiu Bo 	struct extent_buffer *old;
1413a95236d9SJan Schmidt 	struct tree_mod_root *old_root = NULL;
14144325edd0SChris Mason 	u64 old_generation = 0;
1415a95236d9SJan Schmidt 	u64 logical;
14165d9e75c4SJan Schmidt 
141730b0463aSJan Schmidt 	eb_root = btrfs_read_lock_root_node(root);
1418*0b246afaSJeff Mahoney 	tm = __tree_mod_log_oldest_root(fs_info, eb_root, time_seq);
14195d9e75c4SJan Schmidt 	if (!tm)
142030b0463aSJan Schmidt 		return eb_root;
14215d9e75c4SJan Schmidt 
1422a95236d9SJan Schmidt 	if (tm->op == MOD_LOG_ROOT_REPLACE) {
14235d9e75c4SJan Schmidt 		old_root = &tm->old_root;
14245d9e75c4SJan Schmidt 		old_generation = tm->generation;
1425a95236d9SJan Schmidt 		logical = old_root->logical;
1426a95236d9SJan Schmidt 	} else {
142730b0463aSJan Schmidt 		logical = eb_root->start;
1428a95236d9SJan Schmidt 	}
14295d9e75c4SJan Schmidt 
1430*0b246afaSJeff Mahoney 	tm = tree_mod_log_search(fs_info, logical, time_seq);
1431834328a8SJan Schmidt 	if (old_root && tm && tm->op != MOD_LOG_KEY_REMOVE_WHILE_FREEING) {
143230b0463aSJan Schmidt 		btrfs_tree_read_unlock(eb_root);
143330b0463aSJan Schmidt 		free_extent_buffer(eb_root);
1434ce86cd59SDavid Sterba 		old = read_tree_block(root, logical, 0);
143564c043deSLiu Bo 		if (WARN_ON(IS_ERR(old) || !extent_buffer_uptodate(old))) {
143664c043deSLiu Bo 			if (!IS_ERR(old))
1437416bc658SJosef Bacik 				free_extent_buffer(old);
1438*0b246afaSJeff Mahoney 			btrfs_warn(fs_info,
1439*0b246afaSJeff Mahoney 				   "failed to read tree block %llu from get_old_root",
1440*0b246afaSJeff Mahoney 				   logical);
1441834328a8SJan Schmidt 		} else {
14427bfdcf7fSLiu Bo 			eb = btrfs_clone_extent_buffer(old);
14437bfdcf7fSLiu Bo 			free_extent_buffer(old);
1444834328a8SJan Schmidt 		}
1445834328a8SJan Schmidt 	} else if (old_root) {
144630b0463aSJan Schmidt 		btrfs_tree_read_unlock(eb_root);
144730b0463aSJan Schmidt 		free_extent_buffer(eb_root);
1448*0b246afaSJeff Mahoney 		eb = alloc_dummy_extent_buffer(fs_info, logical);
1449834328a8SJan Schmidt 	} else {
14509ec72677SJosef Bacik 		btrfs_set_lock_blocking_rw(eb_root, BTRFS_READ_LOCK);
145130b0463aSJan Schmidt 		eb = btrfs_clone_extent_buffer(eb_root);
14529ec72677SJosef Bacik 		btrfs_tree_read_unlock_blocking(eb_root);
145330b0463aSJan Schmidt 		free_extent_buffer(eb_root);
1454834328a8SJan Schmidt 	}
1455834328a8SJan Schmidt 
14568ba97a15SJan Schmidt 	if (!eb)
14578ba97a15SJan Schmidt 		return NULL;
1458d6381084SJan Schmidt 	extent_buffer_get(eb);
14598ba97a15SJan Schmidt 	btrfs_tree_read_lock(eb);
1460a95236d9SJan Schmidt 	if (old_root) {
14615d9e75c4SJan Schmidt 		btrfs_set_header_bytenr(eb, eb->start);
14625d9e75c4SJan Schmidt 		btrfs_set_header_backref_rev(eb, BTRFS_MIXED_BACKREF_REV);
146330b0463aSJan Schmidt 		btrfs_set_header_owner(eb, btrfs_header_owner(eb_root));
14645d9e75c4SJan Schmidt 		btrfs_set_header_level(eb, old_root->level);
14655d9e75c4SJan Schmidt 		btrfs_set_header_generation(eb, old_generation);
1466a95236d9SJan Schmidt 	}
146728da9fb4SJan Schmidt 	if (tm)
1468*0b246afaSJeff Mahoney 		__tree_mod_log_rewind(fs_info, eb, time_seq, tm);
146928da9fb4SJan Schmidt 	else
147028da9fb4SJan Schmidt 		WARN_ON(btrfs_header_level(eb) != 0);
1471*0b246afaSJeff Mahoney 	WARN_ON(btrfs_header_nritems(eb) > BTRFS_NODEPTRS_PER_BLOCK(fs_info));
14725d9e75c4SJan Schmidt 
14735d9e75c4SJan Schmidt 	return eb;
14745d9e75c4SJan Schmidt }
14755d9e75c4SJan Schmidt 
14765b6602e7SJan Schmidt int btrfs_old_root_level(struct btrfs_root *root, u64 time_seq)
14775b6602e7SJan Schmidt {
14785b6602e7SJan Schmidt 	struct tree_mod_elem *tm;
14795b6602e7SJan Schmidt 	int level;
148030b0463aSJan Schmidt 	struct extent_buffer *eb_root = btrfs_root_node(root);
14815b6602e7SJan Schmidt 
148230b0463aSJan Schmidt 	tm = __tree_mod_log_oldest_root(root->fs_info, eb_root, time_seq);
14835b6602e7SJan Schmidt 	if (tm && tm->op == MOD_LOG_ROOT_REPLACE) {
14845b6602e7SJan Schmidt 		level = tm->old_root.level;
14855b6602e7SJan Schmidt 	} else {
148630b0463aSJan Schmidt 		level = btrfs_header_level(eb_root);
14875b6602e7SJan Schmidt 	}
148830b0463aSJan Schmidt 	free_extent_buffer(eb_root);
14895b6602e7SJan Schmidt 
14905b6602e7SJan Schmidt 	return level;
14915b6602e7SJan Schmidt }
14925b6602e7SJan Schmidt 
14935d4f98a2SYan Zheng static inline int should_cow_block(struct btrfs_trans_handle *trans,
14945d4f98a2SYan Zheng 				   struct btrfs_root *root,
14955d4f98a2SYan Zheng 				   struct extent_buffer *buf)
14965d4f98a2SYan Zheng {
1497f5ee5c9aSJeff Mahoney 	if (btrfs_is_testing(root->fs_info))
1498faa2dbf0SJosef Bacik 		return 0;
1499fccb84c9SDavid Sterba 
1500f1ebcc74SLiu Bo 	/* ensure we can see the force_cow */
1501f1ebcc74SLiu Bo 	smp_rmb();
1502f1ebcc74SLiu Bo 
1503f1ebcc74SLiu Bo 	/*
1504f1ebcc74SLiu Bo 	 * We do not need to cow a block if
1505f1ebcc74SLiu Bo 	 * 1) this block is not created or changed in this transaction;
1506f1ebcc74SLiu Bo 	 * 2) this block does not belong to TREE_RELOC tree;
1507f1ebcc74SLiu Bo 	 * 3) the root is not forced COW.
1508f1ebcc74SLiu Bo 	 *
1509f1ebcc74SLiu Bo 	 * What is forced COW:
151001327610SNicholas D Steeves 	 *    when we create snapshot during committing the transaction,
1511f1ebcc74SLiu Bo 	 *    after we've finished coping src root, we must COW the shared
1512f1ebcc74SLiu Bo 	 *    block to ensure the metadata consistency.
1513f1ebcc74SLiu Bo 	 */
15145d4f98a2SYan Zheng 	if (btrfs_header_generation(buf) == trans->transid &&
15155d4f98a2SYan Zheng 	    !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN) &&
15165d4f98a2SYan Zheng 	    !(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
1517f1ebcc74SLiu Bo 	      btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)) &&
151827cdeb70SMiao Xie 	    !test_bit(BTRFS_ROOT_FORCE_COW, &root->state))
15195d4f98a2SYan Zheng 		return 0;
15205d4f98a2SYan Zheng 	return 1;
15215d4f98a2SYan Zheng }
15225d4f98a2SYan Zheng 
1523d352ac68SChris Mason /*
1524d352ac68SChris Mason  * cows a single block, see __btrfs_cow_block for the real work.
152501327610SNicholas D Steeves  * This version of it has extra checks so that a block isn't COWed more than
1526d352ac68SChris Mason  * once per transaction, as long as it hasn't been written yet
1527d352ac68SChris Mason  */
1528d397712bSChris Mason noinline int btrfs_cow_block(struct btrfs_trans_handle *trans,
15295f39d397SChris Mason 		    struct btrfs_root *root, struct extent_buffer *buf,
15305f39d397SChris Mason 		    struct extent_buffer *parent, int parent_slot,
15319fa8cfe7SChris Mason 		    struct extent_buffer **cow_ret)
153202217ed2SChris Mason {
1533*0b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
15346702ed49SChris Mason 	u64 search_start;
1535f510cfecSChris Mason 	int ret;
1536dc17ff8fSChris Mason 
1537*0b246afaSJeff Mahoney 	if (trans->transaction != fs_info->running_transaction)
153831b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "trans %llu running %llu\n",
1539c1c9ff7cSGeert Uytterhoeven 		       trans->transid,
1540*0b246afaSJeff Mahoney 		       fs_info->running_transaction->transid);
154131b1a2bdSJulia Lawall 
1542*0b246afaSJeff Mahoney 	if (trans->transid != fs_info->generation)
154331b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "trans %llu running %llu\n",
1544*0b246afaSJeff Mahoney 		       trans->transid, fs_info->generation);
1545dc17ff8fSChris Mason 
15465d4f98a2SYan Zheng 	if (!should_cow_block(trans, root, buf)) {
154764c12921SJeff Mahoney 		trans->dirty = true;
154802217ed2SChris Mason 		*cow_ret = buf;
154902217ed2SChris Mason 		return 0;
155002217ed2SChris Mason 	}
1551c487685dSChris Mason 
1552ee22184bSByongho Lee 	search_start = buf->start & ~((u64)SZ_1G - 1);
1553b4ce94deSChris Mason 
1554b4ce94deSChris Mason 	if (parent)
1555b4ce94deSChris Mason 		btrfs_set_lock_blocking(parent);
1556b4ce94deSChris Mason 	btrfs_set_lock_blocking(buf);
1557b4ce94deSChris Mason 
1558f510cfecSChris Mason 	ret = __btrfs_cow_block(trans, root, buf, parent,
15599fa8cfe7SChris Mason 				 parent_slot, cow_ret, search_start, 0);
15601abe9b8aSliubo 
15611abe9b8aSliubo 	trace_btrfs_cow_block(root, buf, *cow_ret);
15621abe9b8aSliubo 
1563f510cfecSChris Mason 	return ret;
15642c90e5d6SChris Mason }
15656702ed49SChris Mason 
1566d352ac68SChris Mason /*
1567d352ac68SChris Mason  * helper function for defrag to decide if two blocks pointed to by a
1568d352ac68SChris Mason  * node are actually close by
1569d352ac68SChris Mason  */
15706b80053dSChris Mason static int close_blocks(u64 blocknr, u64 other, u32 blocksize)
15716702ed49SChris Mason {
15726b80053dSChris Mason 	if (blocknr < other && other - (blocknr + blocksize) < 32768)
15736702ed49SChris Mason 		return 1;
15746b80053dSChris Mason 	if (blocknr > other && blocknr - (other + blocksize) < 32768)
15756702ed49SChris Mason 		return 1;
157602217ed2SChris Mason 	return 0;
157702217ed2SChris Mason }
157802217ed2SChris Mason 
1579081e9573SChris Mason /*
1580081e9573SChris Mason  * compare two keys in a memcmp fashion
1581081e9573SChris Mason  */
1582081e9573SChris Mason static int comp_keys(struct btrfs_disk_key *disk, struct btrfs_key *k2)
1583081e9573SChris Mason {
1584081e9573SChris Mason 	struct btrfs_key k1;
1585081e9573SChris Mason 
1586081e9573SChris Mason 	btrfs_disk_key_to_cpu(&k1, disk);
1587081e9573SChris Mason 
158820736abaSDiego Calleja 	return btrfs_comp_cpu_keys(&k1, k2);
1589081e9573SChris Mason }
1590081e9573SChris Mason 
1591f3465ca4SJosef Bacik /*
1592f3465ca4SJosef Bacik  * same as comp_keys only with two btrfs_key's
1593f3465ca4SJosef Bacik  */
15945d4f98a2SYan Zheng int btrfs_comp_cpu_keys(struct btrfs_key *k1, struct btrfs_key *k2)
1595f3465ca4SJosef Bacik {
1596f3465ca4SJosef Bacik 	if (k1->objectid > k2->objectid)
1597f3465ca4SJosef Bacik 		return 1;
1598f3465ca4SJosef Bacik 	if (k1->objectid < k2->objectid)
1599f3465ca4SJosef Bacik 		return -1;
1600f3465ca4SJosef Bacik 	if (k1->type > k2->type)
1601f3465ca4SJosef Bacik 		return 1;
1602f3465ca4SJosef Bacik 	if (k1->type < k2->type)
1603f3465ca4SJosef Bacik 		return -1;
1604f3465ca4SJosef Bacik 	if (k1->offset > k2->offset)
1605f3465ca4SJosef Bacik 		return 1;
1606f3465ca4SJosef Bacik 	if (k1->offset < k2->offset)
1607f3465ca4SJosef Bacik 		return -1;
1608f3465ca4SJosef Bacik 	return 0;
1609f3465ca4SJosef Bacik }
1610081e9573SChris Mason 
1611d352ac68SChris Mason /*
1612d352ac68SChris Mason  * this is used by the defrag code to go through all the
1613d352ac68SChris Mason  * leaves pointed to by a node and reallocate them so that
1614d352ac68SChris Mason  * disk order is close to key order
1615d352ac68SChris Mason  */
16166702ed49SChris Mason int btrfs_realloc_node(struct btrfs_trans_handle *trans,
16175f39d397SChris Mason 		       struct btrfs_root *root, struct extent_buffer *parent,
1618de78b51aSEric Sandeen 		       int start_slot, u64 *last_ret,
1619a6b6e75eSChris Mason 		       struct btrfs_key *progress)
16206702ed49SChris Mason {
1621*0b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
16226b80053dSChris Mason 	struct extent_buffer *cur;
16236702ed49SChris Mason 	u64 blocknr;
1624ca7a79adSChris Mason 	u64 gen;
1625e9d0b13bSChris Mason 	u64 search_start = *last_ret;
1626e9d0b13bSChris Mason 	u64 last_block = 0;
16276702ed49SChris Mason 	u64 other;
16286702ed49SChris Mason 	u32 parent_nritems;
16296702ed49SChris Mason 	int end_slot;
16306702ed49SChris Mason 	int i;
16316702ed49SChris Mason 	int err = 0;
1632f2183bdeSChris Mason 	int parent_level;
16336b80053dSChris Mason 	int uptodate;
16346b80053dSChris Mason 	u32 blocksize;
1635081e9573SChris Mason 	int progress_passed = 0;
1636081e9573SChris Mason 	struct btrfs_disk_key disk_key;
16376702ed49SChris Mason 
16385708b959SChris Mason 	parent_level = btrfs_header_level(parent);
16395708b959SChris Mason 
1640*0b246afaSJeff Mahoney 	WARN_ON(trans->transaction != fs_info->running_transaction);
1641*0b246afaSJeff Mahoney 	WARN_ON(trans->transid != fs_info->generation);
164286479a04SChris Mason 
16436b80053dSChris Mason 	parent_nritems = btrfs_header_nritems(parent);
1644*0b246afaSJeff Mahoney 	blocksize = fs_info->nodesize;
16455dfe2be7SFilipe Manana 	end_slot = parent_nritems - 1;
16466702ed49SChris Mason 
16475dfe2be7SFilipe Manana 	if (parent_nritems <= 1)
16486702ed49SChris Mason 		return 0;
16496702ed49SChris Mason 
1650b4ce94deSChris Mason 	btrfs_set_lock_blocking(parent);
1651b4ce94deSChris Mason 
16525dfe2be7SFilipe Manana 	for (i = start_slot; i <= end_slot; i++) {
16536702ed49SChris Mason 		int close = 1;
1654a6b6e75eSChris Mason 
1655081e9573SChris Mason 		btrfs_node_key(parent, &disk_key, i);
1656081e9573SChris Mason 		if (!progress_passed && comp_keys(&disk_key, progress) < 0)
1657081e9573SChris Mason 			continue;
1658081e9573SChris Mason 
1659081e9573SChris Mason 		progress_passed = 1;
16606b80053dSChris Mason 		blocknr = btrfs_node_blockptr(parent, i);
1661ca7a79adSChris Mason 		gen = btrfs_node_ptr_generation(parent, i);
1662e9d0b13bSChris Mason 		if (last_block == 0)
1663e9d0b13bSChris Mason 			last_block = blocknr;
16645708b959SChris Mason 
16656702ed49SChris Mason 		if (i > 0) {
16666b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i - 1);
16676b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
16686702ed49SChris Mason 		}
16695dfe2be7SFilipe Manana 		if (!close && i < end_slot) {
16706b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i + 1);
16716b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
16726702ed49SChris Mason 		}
1673e9d0b13bSChris Mason 		if (close) {
1674e9d0b13bSChris Mason 			last_block = blocknr;
16756702ed49SChris Mason 			continue;
1676e9d0b13bSChris Mason 		}
16776702ed49SChris Mason 
1678*0b246afaSJeff Mahoney 		cur = find_extent_buffer(fs_info, blocknr);
16796b80053dSChris Mason 		if (cur)
1680b9fab919SChris Mason 			uptodate = btrfs_buffer_uptodate(cur, gen, 0);
16816b80053dSChris Mason 		else
16826b80053dSChris Mason 			uptodate = 0;
16835708b959SChris Mason 		if (!cur || !uptodate) {
16846b80053dSChris Mason 			if (!cur) {
1685ce86cd59SDavid Sterba 				cur = read_tree_block(root, blocknr, gen);
168664c043deSLiu Bo 				if (IS_ERR(cur)) {
168764c043deSLiu Bo 					return PTR_ERR(cur);
168864c043deSLiu Bo 				} else if (!extent_buffer_uptodate(cur)) {
1689416bc658SJosef Bacik 					free_extent_buffer(cur);
169097d9a8a4STsutomu Itoh 					return -EIO;
1691416bc658SJosef Bacik 				}
16926b80053dSChris Mason 			} else if (!uptodate) {
1693018642a1STsutomu Itoh 				err = btrfs_read_buffer(cur, gen);
1694018642a1STsutomu Itoh 				if (err) {
1695018642a1STsutomu Itoh 					free_extent_buffer(cur);
1696018642a1STsutomu Itoh 					return err;
1697018642a1STsutomu Itoh 				}
16986702ed49SChris Mason 			}
1699f2183bdeSChris Mason 		}
1700e9d0b13bSChris Mason 		if (search_start == 0)
17016b80053dSChris Mason 			search_start = last_block;
1702e9d0b13bSChris Mason 
1703e7a84565SChris Mason 		btrfs_tree_lock(cur);
1704b4ce94deSChris Mason 		btrfs_set_lock_blocking(cur);
17056b80053dSChris Mason 		err = __btrfs_cow_block(trans, root, cur, parent, i,
1706e7a84565SChris Mason 					&cur, search_start,
17076b80053dSChris Mason 					min(16 * blocksize,
17089fa8cfe7SChris Mason 					    (end_slot - i) * blocksize));
1709252c38f0SYan 		if (err) {
1710e7a84565SChris Mason 			btrfs_tree_unlock(cur);
17116b80053dSChris Mason 			free_extent_buffer(cur);
17126702ed49SChris Mason 			break;
1713252c38f0SYan 		}
1714e7a84565SChris Mason 		search_start = cur->start;
1715e7a84565SChris Mason 		last_block = cur->start;
1716f2183bdeSChris Mason 		*last_ret = search_start;
1717e7a84565SChris Mason 		btrfs_tree_unlock(cur);
1718e7a84565SChris Mason 		free_extent_buffer(cur);
17196702ed49SChris Mason 	}
17206702ed49SChris Mason 	return err;
17216702ed49SChris Mason }
17226702ed49SChris Mason 
172374123bd7SChris Mason /*
17245f39d397SChris Mason  * search for key in the extent_buffer.  The items start at offset p,
17255f39d397SChris Mason  * and they are item_size apart.  There are 'max' items in p.
17265f39d397SChris Mason  *
172774123bd7SChris Mason  * the slot in the array is returned via slot, and it points to
172874123bd7SChris Mason  * the place where you would insert key if it is not found in
172974123bd7SChris Mason  * the array.
173074123bd7SChris Mason  *
173174123bd7SChris Mason  * slot may point to max if the key is bigger than all of the keys
173274123bd7SChris Mason  */
1733e02119d5SChris Mason static noinline int generic_bin_search(struct extent_buffer *eb,
1734e02119d5SChris Mason 				       unsigned long p,
17355f39d397SChris Mason 				       int item_size, struct btrfs_key *key,
1736be0e5c09SChris Mason 				       int max, int *slot)
1737be0e5c09SChris Mason {
1738be0e5c09SChris Mason 	int low = 0;
1739be0e5c09SChris Mason 	int high = max;
1740be0e5c09SChris Mason 	int mid;
1741be0e5c09SChris Mason 	int ret;
1742479965d6SChris Mason 	struct btrfs_disk_key *tmp = NULL;
17435f39d397SChris Mason 	struct btrfs_disk_key unaligned;
17445f39d397SChris Mason 	unsigned long offset;
17455f39d397SChris Mason 	char *kaddr = NULL;
17465f39d397SChris Mason 	unsigned long map_start = 0;
17475f39d397SChris Mason 	unsigned long map_len = 0;
1748479965d6SChris Mason 	int err;
1749be0e5c09SChris Mason 
17505e24e9afSLiu Bo 	if (low > high) {
17515e24e9afSLiu Bo 		btrfs_err(eb->fs_info,
17525e24e9afSLiu Bo 		 "%s: low (%d) > high (%d) eb %llu owner %llu level %d",
17535e24e9afSLiu Bo 			  __func__, low, high, eb->start,
17545e24e9afSLiu Bo 			  btrfs_header_owner(eb), btrfs_header_level(eb));
17555e24e9afSLiu Bo 		return -EINVAL;
17565e24e9afSLiu Bo 	}
17575e24e9afSLiu Bo 
1758be0e5c09SChris Mason 	while (low < high) {
1759be0e5c09SChris Mason 		mid = (low + high) / 2;
17605f39d397SChris Mason 		offset = p + mid * item_size;
17615f39d397SChris Mason 
1762a6591715SChris Mason 		if (!kaddr || offset < map_start ||
17635f39d397SChris Mason 		    (offset + sizeof(struct btrfs_disk_key)) >
17645f39d397SChris Mason 		    map_start + map_len) {
1765934d375bSChris Mason 
1766934d375bSChris Mason 			err = map_private_extent_buffer(eb, offset,
1767479965d6SChris Mason 						sizeof(struct btrfs_disk_key),
1768a6591715SChris Mason 						&kaddr, &map_start, &map_len);
17695f39d397SChris Mason 
1770479965d6SChris Mason 			if (!err) {
1771479965d6SChris Mason 				tmp = (struct btrfs_disk_key *)(kaddr + offset -
1772479965d6SChris Mason 							map_start);
1773415b35a5SLiu Bo 			} else if (err == 1) {
17745f39d397SChris Mason 				read_extent_buffer(eb, &unaligned,
17755f39d397SChris Mason 						   offset, sizeof(unaligned));
17765f39d397SChris Mason 				tmp = &unaligned;
1777415b35a5SLiu Bo 			} else {
1778415b35a5SLiu Bo 				return err;
1779479965d6SChris Mason 			}
1780479965d6SChris Mason 
17815f39d397SChris Mason 		} else {
17825f39d397SChris Mason 			tmp = (struct btrfs_disk_key *)(kaddr + offset -
17835f39d397SChris Mason 							map_start);
17845f39d397SChris Mason 		}
1785be0e5c09SChris Mason 		ret = comp_keys(tmp, key);
1786be0e5c09SChris Mason 
1787be0e5c09SChris Mason 		if (ret < 0)
1788be0e5c09SChris Mason 			low = mid + 1;
1789be0e5c09SChris Mason 		else if (ret > 0)
1790be0e5c09SChris Mason 			high = mid;
1791be0e5c09SChris Mason 		else {
1792be0e5c09SChris Mason 			*slot = mid;
1793be0e5c09SChris Mason 			return 0;
1794be0e5c09SChris Mason 		}
1795be0e5c09SChris Mason 	}
1796be0e5c09SChris Mason 	*slot = low;
1797be0e5c09SChris Mason 	return 1;
1798be0e5c09SChris Mason }
1799be0e5c09SChris Mason 
180097571fd0SChris Mason /*
180197571fd0SChris Mason  * simple bin_search frontend that does the right thing for
180297571fd0SChris Mason  * leaves vs nodes
180397571fd0SChris Mason  */
18045f39d397SChris Mason static int bin_search(struct extent_buffer *eb, struct btrfs_key *key,
18055f39d397SChris Mason 		      int level, int *slot)
1806be0e5c09SChris Mason {
1807f775738fSWang Sheng-Hui 	if (level == 0)
18085f39d397SChris Mason 		return generic_bin_search(eb,
18095f39d397SChris Mason 					  offsetof(struct btrfs_leaf, items),
18100783fcfcSChris Mason 					  sizeof(struct btrfs_item),
18115f39d397SChris Mason 					  key, btrfs_header_nritems(eb),
18127518a238SChris Mason 					  slot);
1813f775738fSWang Sheng-Hui 	else
18145f39d397SChris Mason 		return generic_bin_search(eb,
18155f39d397SChris Mason 					  offsetof(struct btrfs_node, ptrs),
1816123abc88SChris Mason 					  sizeof(struct btrfs_key_ptr),
18175f39d397SChris Mason 					  key, btrfs_header_nritems(eb),
18187518a238SChris Mason 					  slot);
1819be0e5c09SChris Mason }
1820be0e5c09SChris Mason 
18215d4f98a2SYan Zheng int btrfs_bin_search(struct extent_buffer *eb, struct btrfs_key *key,
18225d4f98a2SYan Zheng 		     int level, int *slot)
18235d4f98a2SYan Zheng {
18245d4f98a2SYan Zheng 	return bin_search(eb, key, level, slot);
18255d4f98a2SYan Zheng }
18265d4f98a2SYan Zheng 
1827f0486c68SYan, Zheng static void root_add_used(struct btrfs_root *root, u32 size)
1828f0486c68SYan, Zheng {
1829f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
1830f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
1831f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) + size);
1832f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
1833f0486c68SYan, Zheng }
1834f0486c68SYan, Zheng 
1835f0486c68SYan, Zheng static void root_sub_used(struct btrfs_root *root, u32 size)
1836f0486c68SYan, Zheng {
1837f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
1838f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
1839f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) - size);
1840f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
1841f0486c68SYan, Zheng }
1842f0486c68SYan, Zheng 
1843d352ac68SChris Mason /* given a node and slot number, this reads the blocks it points to.  The
1844d352ac68SChris Mason  * extent buffer is returned with a reference taken (but unlocked).
1845d352ac68SChris Mason  */
1846e02119d5SChris Mason static noinline struct extent_buffer *read_node_slot(struct btrfs_root *root,
18475f39d397SChris Mason 				   struct extent_buffer *parent, int slot)
1848bb803951SChris Mason {
1849ca7a79adSChris Mason 	int level = btrfs_header_level(parent);
1850416bc658SJosef Bacik 	struct extent_buffer *eb;
1851416bc658SJosef Bacik 
1852fb770ae4SLiu Bo 	if (slot < 0 || slot >= btrfs_header_nritems(parent))
1853fb770ae4SLiu Bo 		return ERR_PTR(-ENOENT);
1854ca7a79adSChris Mason 
1855ca7a79adSChris Mason 	BUG_ON(level == 0);
1856ca7a79adSChris Mason 
1857416bc658SJosef Bacik 	eb = read_tree_block(root, btrfs_node_blockptr(parent, slot),
1858ca7a79adSChris Mason 			     btrfs_node_ptr_generation(parent, slot));
1859fb770ae4SLiu Bo 	if (!IS_ERR(eb) && !extent_buffer_uptodate(eb)) {
1860416bc658SJosef Bacik 		free_extent_buffer(eb);
1861fb770ae4SLiu Bo 		eb = ERR_PTR(-EIO);
1862416bc658SJosef Bacik 	}
1863416bc658SJosef Bacik 
1864416bc658SJosef Bacik 	return eb;
1865bb803951SChris Mason }
1866bb803951SChris Mason 
1867d352ac68SChris Mason /*
1868d352ac68SChris Mason  * node level balancing, used to make sure nodes are in proper order for
1869d352ac68SChris Mason  * item deletion.  We balance from the top down, so we have to make sure
1870d352ac68SChris Mason  * that a deletion won't leave an node completely empty later on.
1871d352ac68SChris Mason  */
1872e02119d5SChris Mason static noinline int balance_level(struct btrfs_trans_handle *trans,
187398ed5174SChris Mason 			 struct btrfs_root *root,
187498ed5174SChris Mason 			 struct btrfs_path *path, int level)
1875bb803951SChris Mason {
1876*0b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
18775f39d397SChris Mason 	struct extent_buffer *right = NULL;
18785f39d397SChris Mason 	struct extent_buffer *mid;
18795f39d397SChris Mason 	struct extent_buffer *left = NULL;
18805f39d397SChris Mason 	struct extent_buffer *parent = NULL;
1881bb803951SChris Mason 	int ret = 0;
1882bb803951SChris Mason 	int wret;
1883bb803951SChris Mason 	int pslot;
1884bb803951SChris Mason 	int orig_slot = path->slots[level];
188579f95c82SChris Mason 	u64 orig_ptr;
1886bb803951SChris Mason 
1887bb803951SChris Mason 	if (level == 0)
1888bb803951SChris Mason 		return 0;
1889bb803951SChris Mason 
18905f39d397SChris Mason 	mid = path->nodes[level];
1891b4ce94deSChris Mason 
1892bd681513SChris Mason 	WARN_ON(path->locks[level] != BTRFS_WRITE_LOCK &&
1893bd681513SChris Mason 		path->locks[level] != BTRFS_WRITE_LOCK_BLOCKING);
18947bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
18957bb86316SChris Mason 
18961d4f8a0cSChris Mason 	orig_ptr = btrfs_node_blockptr(mid, orig_slot);
189779f95c82SChris Mason 
1898a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
18995f39d397SChris Mason 		parent = path->nodes[level + 1];
1900bb803951SChris Mason 		pslot = path->slots[level + 1];
1901a05a9bb1SLi Zefan 	}
1902bb803951SChris Mason 
190340689478SChris Mason 	/*
190440689478SChris Mason 	 * deal with the case where there is only one pointer in the root
190540689478SChris Mason 	 * by promoting the node below to a root
190640689478SChris Mason 	 */
19075f39d397SChris Mason 	if (!parent) {
19085f39d397SChris Mason 		struct extent_buffer *child;
1909bb803951SChris Mason 
19105f39d397SChris Mason 		if (btrfs_header_nritems(mid) != 1)
1911bb803951SChris Mason 			return 0;
1912bb803951SChris Mason 
1913bb803951SChris Mason 		/* promote the child to a root */
19145f39d397SChris Mason 		child = read_node_slot(root, mid, 0);
1915fb770ae4SLiu Bo 		if (IS_ERR(child)) {
1916fb770ae4SLiu Bo 			ret = PTR_ERR(child);
1917*0b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
1918305a26afSMark Fasheh 			goto enospc;
1919305a26afSMark Fasheh 		}
1920305a26afSMark Fasheh 
1921925baeddSChris Mason 		btrfs_tree_lock(child);
1922b4ce94deSChris Mason 		btrfs_set_lock_blocking(child);
19239fa8cfe7SChris Mason 		ret = btrfs_cow_block(trans, root, child, mid, 0, &child);
1924f0486c68SYan, Zheng 		if (ret) {
1925f0486c68SYan, Zheng 			btrfs_tree_unlock(child);
1926f0486c68SYan, Zheng 			free_extent_buffer(child);
1927f0486c68SYan, Zheng 			goto enospc;
1928f0486c68SYan, Zheng 		}
19292f375ab9SYan 
193090f8d62eSJan Schmidt 		tree_mod_log_set_root_pointer(root, child, 1);
1931240f62c8SChris Mason 		rcu_assign_pointer(root->node, child);
1932925baeddSChris Mason 
19330b86a832SChris Mason 		add_root_to_dirty_list(root);
1934925baeddSChris Mason 		btrfs_tree_unlock(child);
1935b4ce94deSChris Mason 
1936925baeddSChris Mason 		path->locks[level] = 0;
1937bb803951SChris Mason 		path->nodes[level] = NULL;
1938*0b246afaSJeff Mahoney 		clean_tree_block(trans, fs_info, mid);
1939925baeddSChris Mason 		btrfs_tree_unlock(mid);
1940bb803951SChris Mason 		/* once for the path */
19415f39d397SChris Mason 		free_extent_buffer(mid);
1942f0486c68SYan, Zheng 
1943f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
19445581a51aSJan Schmidt 		btrfs_free_tree_block(trans, root, mid, 0, 1);
1945bb803951SChris Mason 		/* once for the root ptr */
19463083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
1947f0486c68SYan, Zheng 		return 0;
1948bb803951SChris Mason 	}
19495f39d397SChris Mason 	if (btrfs_header_nritems(mid) >
1950*0b246afaSJeff Mahoney 	    BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 4)
1951bb803951SChris Mason 		return 0;
1952bb803951SChris Mason 
19535f39d397SChris Mason 	left = read_node_slot(root, parent, pslot - 1);
1954fb770ae4SLiu Bo 	if (IS_ERR(left))
1955fb770ae4SLiu Bo 		left = NULL;
1956fb770ae4SLiu Bo 
19575f39d397SChris Mason 	if (left) {
1958925baeddSChris Mason 		btrfs_tree_lock(left);
1959b4ce94deSChris Mason 		btrfs_set_lock_blocking(left);
19605f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, left,
19619fa8cfe7SChris Mason 				       parent, pslot - 1, &left);
196254aa1f4dSChris Mason 		if (wret) {
196354aa1f4dSChris Mason 			ret = wret;
196454aa1f4dSChris Mason 			goto enospc;
196554aa1f4dSChris Mason 		}
19662cc58cf2SChris Mason 	}
1967fb770ae4SLiu Bo 
19685f39d397SChris Mason 	right = read_node_slot(root, parent, pslot + 1);
1969fb770ae4SLiu Bo 	if (IS_ERR(right))
1970fb770ae4SLiu Bo 		right = NULL;
1971fb770ae4SLiu Bo 
19725f39d397SChris Mason 	if (right) {
1973925baeddSChris Mason 		btrfs_tree_lock(right);
1974b4ce94deSChris Mason 		btrfs_set_lock_blocking(right);
19755f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, right,
19769fa8cfe7SChris Mason 				       parent, pslot + 1, &right);
19772cc58cf2SChris Mason 		if (wret) {
19782cc58cf2SChris Mason 			ret = wret;
19792cc58cf2SChris Mason 			goto enospc;
19802cc58cf2SChris Mason 		}
19812cc58cf2SChris Mason 	}
19822cc58cf2SChris Mason 
19832cc58cf2SChris Mason 	/* first, try to make some room in the middle buffer */
19845f39d397SChris Mason 	if (left) {
19855f39d397SChris Mason 		orig_slot += btrfs_header_nritems(left);
1986bce4eae9SChris Mason 		wret = push_node_left(trans, root, left, mid, 1);
198779f95c82SChris Mason 		if (wret < 0)
198879f95c82SChris Mason 			ret = wret;
1989bb803951SChris Mason 	}
199079f95c82SChris Mason 
199179f95c82SChris Mason 	/*
199279f95c82SChris Mason 	 * then try to empty the right most buffer into the middle
199379f95c82SChris Mason 	 */
19945f39d397SChris Mason 	if (right) {
1995971a1f66SChris Mason 		wret = push_node_left(trans, root, mid, right, 1);
199654aa1f4dSChris Mason 		if (wret < 0 && wret != -ENOSPC)
199779f95c82SChris Mason 			ret = wret;
19985f39d397SChris Mason 		if (btrfs_header_nritems(right) == 0) {
1999*0b246afaSJeff Mahoney 			clean_tree_block(trans, fs_info, right);
2000925baeddSChris Mason 			btrfs_tree_unlock(right);
2001afe5fea7STsutomu Itoh 			del_ptr(root, path, level + 1, pslot + 1);
2002f0486c68SYan, Zheng 			root_sub_used(root, right->len);
20035581a51aSJan Schmidt 			btrfs_free_tree_block(trans, root, right, 0, 1);
20043083ee2eSJosef Bacik 			free_extent_buffer_stale(right);
2005f0486c68SYan, Zheng 			right = NULL;
2006bb803951SChris Mason 		} else {
20075f39d397SChris Mason 			struct btrfs_disk_key right_key;
20085f39d397SChris Mason 			btrfs_node_key(right, &right_key, 0);
2009*0b246afaSJeff Mahoney 			tree_mod_log_set_node_key(fs_info, parent,
201032adf090SLiu Bo 						  pslot + 1, 0);
20115f39d397SChris Mason 			btrfs_set_node_key(parent, &right_key, pslot + 1);
20125f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
2013bb803951SChris Mason 		}
2014bb803951SChris Mason 	}
20155f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 1) {
201679f95c82SChris Mason 		/*
201779f95c82SChris Mason 		 * we're not allowed to leave a node with one item in the
201879f95c82SChris Mason 		 * tree during a delete.  A deletion from lower in the tree
201979f95c82SChris Mason 		 * could try to delete the only pointer in this node.
202079f95c82SChris Mason 		 * So, pull some keys from the left.
202179f95c82SChris Mason 		 * There has to be a left pointer at this point because
202279f95c82SChris Mason 		 * otherwise we would have pulled some pointers from the
202379f95c82SChris Mason 		 * right
202479f95c82SChris Mason 		 */
2025305a26afSMark Fasheh 		if (!left) {
2026305a26afSMark Fasheh 			ret = -EROFS;
2027*0b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
2028305a26afSMark Fasheh 			goto enospc;
2029305a26afSMark Fasheh 		}
20305f39d397SChris Mason 		wret = balance_node_right(trans, root, mid, left);
203154aa1f4dSChris Mason 		if (wret < 0) {
203279f95c82SChris Mason 			ret = wret;
203354aa1f4dSChris Mason 			goto enospc;
203454aa1f4dSChris Mason 		}
2035bce4eae9SChris Mason 		if (wret == 1) {
2036bce4eae9SChris Mason 			wret = push_node_left(trans, root, left, mid, 1);
2037bce4eae9SChris Mason 			if (wret < 0)
2038bce4eae9SChris Mason 				ret = wret;
2039bce4eae9SChris Mason 		}
204079f95c82SChris Mason 		BUG_ON(wret == 1);
204179f95c82SChris Mason 	}
20425f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 0) {
2043*0b246afaSJeff Mahoney 		clean_tree_block(trans, fs_info, mid);
2044925baeddSChris Mason 		btrfs_tree_unlock(mid);
2045afe5fea7STsutomu Itoh 		del_ptr(root, path, level + 1, pslot);
2046f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
20475581a51aSJan Schmidt 		btrfs_free_tree_block(trans, root, mid, 0, 1);
20483083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
2049f0486c68SYan, Zheng 		mid = NULL;
205079f95c82SChris Mason 	} else {
205179f95c82SChris Mason 		/* update the parent key to reflect our changes */
20525f39d397SChris Mason 		struct btrfs_disk_key mid_key;
20535f39d397SChris Mason 		btrfs_node_key(mid, &mid_key, 0);
2054*0b246afaSJeff Mahoney 		tree_mod_log_set_node_key(fs_info, parent, pslot, 0);
20555f39d397SChris Mason 		btrfs_set_node_key(parent, &mid_key, pslot);
20565f39d397SChris Mason 		btrfs_mark_buffer_dirty(parent);
205779f95c82SChris Mason 	}
2058bb803951SChris Mason 
205979f95c82SChris Mason 	/* update the path */
20605f39d397SChris Mason 	if (left) {
20615f39d397SChris Mason 		if (btrfs_header_nritems(left) > orig_slot) {
20625f39d397SChris Mason 			extent_buffer_get(left);
2063925baeddSChris Mason 			/* left was locked after cow */
20645f39d397SChris Mason 			path->nodes[level] = left;
2065bb803951SChris Mason 			path->slots[level + 1] -= 1;
2066bb803951SChris Mason 			path->slots[level] = orig_slot;
2067925baeddSChris Mason 			if (mid) {
2068925baeddSChris Mason 				btrfs_tree_unlock(mid);
20695f39d397SChris Mason 				free_extent_buffer(mid);
2070925baeddSChris Mason 			}
2071bb803951SChris Mason 		} else {
20725f39d397SChris Mason 			orig_slot -= btrfs_header_nritems(left);
2073bb803951SChris Mason 			path->slots[level] = orig_slot;
2074bb803951SChris Mason 		}
2075bb803951SChris Mason 	}
207679f95c82SChris Mason 	/* double check we haven't messed things up */
2077e20d96d6SChris Mason 	if (orig_ptr !=
20785f39d397SChris Mason 	    btrfs_node_blockptr(path->nodes[level], path->slots[level]))
207979f95c82SChris Mason 		BUG();
208054aa1f4dSChris Mason enospc:
2081925baeddSChris Mason 	if (right) {
2082925baeddSChris Mason 		btrfs_tree_unlock(right);
20835f39d397SChris Mason 		free_extent_buffer(right);
2084925baeddSChris Mason 	}
2085925baeddSChris Mason 	if (left) {
2086925baeddSChris Mason 		if (path->nodes[level] != left)
2087925baeddSChris Mason 			btrfs_tree_unlock(left);
20885f39d397SChris Mason 		free_extent_buffer(left);
2089925baeddSChris Mason 	}
2090bb803951SChris Mason 	return ret;
2091bb803951SChris Mason }
2092bb803951SChris Mason 
2093d352ac68SChris Mason /* Node balancing for insertion.  Here we only split or push nodes around
2094d352ac68SChris Mason  * when they are completely full.  This is also done top down, so we
2095d352ac68SChris Mason  * have to be pessimistic.
2096d352ac68SChris Mason  */
2097d397712bSChris Mason static noinline int push_nodes_for_insert(struct btrfs_trans_handle *trans,
2098e66f709bSChris Mason 					  struct btrfs_root *root,
2099e66f709bSChris Mason 					  struct btrfs_path *path, int level)
2100e66f709bSChris Mason {
2101*0b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
21025f39d397SChris Mason 	struct extent_buffer *right = NULL;
21035f39d397SChris Mason 	struct extent_buffer *mid;
21045f39d397SChris Mason 	struct extent_buffer *left = NULL;
21055f39d397SChris Mason 	struct extent_buffer *parent = NULL;
2106e66f709bSChris Mason 	int ret = 0;
2107e66f709bSChris Mason 	int wret;
2108e66f709bSChris Mason 	int pslot;
2109e66f709bSChris Mason 	int orig_slot = path->slots[level];
2110e66f709bSChris Mason 
2111e66f709bSChris Mason 	if (level == 0)
2112e66f709bSChris Mason 		return 1;
2113e66f709bSChris Mason 
21145f39d397SChris Mason 	mid = path->nodes[level];
21157bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
2116e66f709bSChris Mason 
2117a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
21185f39d397SChris Mason 		parent = path->nodes[level + 1];
2119e66f709bSChris Mason 		pslot = path->slots[level + 1];
2120a05a9bb1SLi Zefan 	}
2121e66f709bSChris Mason 
21225f39d397SChris Mason 	if (!parent)
2123e66f709bSChris Mason 		return 1;
2124e66f709bSChris Mason 
21255f39d397SChris Mason 	left = read_node_slot(root, parent, pslot - 1);
2126fb770ae4SLiu Bo 	if (IS_ERR(left))
2127fb770ae4SLiu Bo 		left = NULL;
2128e66f709bSChris Mason 
2129e66f709bSChris Mason 	/* first, try to make some room in the middle buffer */
21305f39d397SChris Mason 	if (left) {
2131e66f709bSChris Mason 		u32 left_nr;
2132925baeddSChris Mason 
2133925baeddSChris Mason 		btrfs_tree_lock(left);
2134b4ce94deSChris Mason 		btrfs_set_lock_blocking(left);
2135b4ce94deSChris Mason 
21365f39d397SChris Mason 		left_nr = btrfs_header_nritems(left);
2137*0b246afaSJeff Mahoney 		if (left_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
213833ade1f8SChris Mason 			wret = 1;
213933ade1f8SChris Mason 		} else {
21405f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, left, parent,
21419fa8cfe7SChris Mason 					      pslot - 1, &left);
214254aa1f4dSChris Mason 			if (ret)
214354aa1f4dSChris Mason 				wret = 1;
214454aa1f4dSChris Mason 			else {
214554aa1f4dSChris Mason 				wret = push_node_left(trans, root,
2146971a1f66SChris Mason 						      left, mid, 0);
214754aa1f4dSChris Mason 			}
214833ade1f8SChris Mason 		}
2149e66f709bSChris Mason 		if (wret < 0)
2150e66f709bSChris Mason 			ret = wret;
2151e66f709bSChris Mason 		if (wret == 0) {
21525f39d397SChris Mason 			struct btrfs_disk_key disk_key;
2153e66f709bSChris Mason 			orig_slot += left_nr;
21545f39d397SChris Mason 			btrfs_node_key(mid, &disk_key, 0);
2155*0b246afaSJeff Mahoney 			tree_mod_log_set_node_key(fs_info, parent, pslot, 0);
21565f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot);
21575f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
21585f39d397SChris Mason 			if (btrfs_header_nritems(left) > orig_slot) {
21595f39d397SChris Mason 				path->nodes[level] = left;
2160e66f709bSChris Mason 				path->slots[level + 1] -= 1;
2161e66f709bSChris Mason 				path->slots[level] = orig_slot;
2162925baeddSChris Mason 				btrfs_tree_unlock(mid);
21635f39d397SChris Mason 				free_extent_buffer(mid);
2164e66f709bSChris Mason 			} else {
2165e66f709bSChris Mason 				orig_slot -=
21665f39d397SChris Mason 					btrfs_header_nritems(left);
2167e66f709bSChris Mason 				path->slots[level] = orig_slot;
2168925baeddSChris Mason 				btrfs_tree_unlock(left);
21695f39d397SChris Mason 				free_extent_buffer(left);
2170e66f709bSChris Mason 			}
2171e66f709bSChris Mason 			return 0;
2172e66f709bSChris Mason 		}
2173925baeddSChris Mason 		btrfs_tree_unlock(left);
21745f39d397SChris Mason 		free_extent_buffer(left);
2175e66f709bSChris Mason 	}
21765f39d397SChris Mason 	right = read_node_slot(root, parent, pslot + 1);
2177fb770ae4SLiu Bo 	if (IS_ERR(right))
2178fb770ae4SLiu Bo 		right = NULL;
2179e66f709bSChris Mason 
2180e66f709bSChris Mason 	/*
2181e66f709bSChris Mason 	 * then try to empty the right most buffer into the middle
2182e66f709bSChris Mason 	 */
21835f39d397SChris Mason 	if (right) {
218433ade1f8SChris Mason 		u32 right_nr;
2185b4ce94deSChris Mason 
2186925baeddSChris Mason 		btrfs_tree_lock(right);
2187b4ce94deSChris Mason 		btrfs_set_lock_blocking(right);
2188b4ce94deSChris Mason 
21895f39d397SChris Mason 		right_nr = btrfs_header_nritems(right);
2190*0b246afaSJeff Mahoney 		if (right_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
219133ade1f8SChris Mason 			wret = 1;
219233ade1f8SChris Mason 		} else {
21935f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, right,
21945f39d397SChris Mason 					      parent, pslot + 1,
21959fa8cfe7SChris Mason 					      &right);
219654aa1f4dSChris Mason 			if (ret)
219754aa1f4dSChris Mason 				wret = 1;
219854aa1f4dSChris Mason 			else {
219933ade1f8SChris Mason 				wret = balance_node_right(trans, root,
22005f39d397SChris Mason 							  right, mid);
220133ade1f8SChris Mason 			}
220254aa1f4dSChris Mason 		}
2203e66f709bSChris Mason 		if (wret < 0)
2204e66f709bSChris Mason 			ret = wret;
2205e66f709bSChris Mason 		if (wret == 0) {
22065f39d397SChris Mason 			struct btrfs_disk_key disk_key;
22075f39d397SChris Mason 
22085f39d397SChris Mason 			btrfs_node_key(right, &disk_key, 0);
2209*0b246afaSJeff Mahoney 			tree_mod_log_set_node_key(fs_info, parent,
221032adf090SLiu Bo 						  pslot + 1, 0);
22115f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot + 1);
22125f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
22135f39d397SChris Mason 
22145f39d397SChris Mason 			if (btrfs_header_nritems(mid) <= orig_slot) {
22155f39d397SChris Mason 				path->nodes[level] = right;
2216e66f709bSChris Mason 				path->slots[level + 1] += 1;
2217e66f709bSChris Mason 				path->slots[level] = orig_slot -
22185f39d397SChris Mason 					btrfs_header_nritems(mid);
2219925baeddSChris Mason 				btrfs_tree_unlock(mid);
22205f39d397SChris Mason 				free_extent_buffer(mid);
2221e66f709bSChris Mason 			} else {
2222925baeddSChris Mason 				btrfs_tree_unlock(right);
22235f39d397SChris Mason 				free_extent_buffer(right);
2224e66f709bSChris Mason 			}
2225e66f709bSChris Mason 			return 0;
2226e66f709bSChris Mason 		}
2227925baeddSChris Mason 		btrfs_tree_unlock(right);
22285f39d397SChris Mason 		free_extent_buffer(right);
2229e66f709bSChris Mason 	}
2230e66f709bSChris Mason 	return 1;
2231e66f709bSChris Mason }
2232e66f709bSChris Mason 
223374123bd7SChris Mason /*
2234d352ac68SChris Mason  * readahead one full node of leaves, finding things that are close
2235d352ac68SChris Mason  * to the block in 'slot', and triggering ra on them.
22363c69faecSChris Mason  */
2237c8c42864SChris Mason static void reada_for_search(struct btrfs_root *root,
2238e02119d5SChris Mason 			     struct btrfs_path *path,
223901f46658SChris Mason 			     int level, int slot, u64 objectid)
22403c69faecSChris Mason {
2241*0b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
22425f39d397SChris Mason 	struct extent_buffer *node;
224301f46658SChris Mason 	struct btrfs_disk_key disk_key;
22443c69faecSChris Mason 	u32 nritems;
22453c69faecSChris Mason 	u64 search;
2246a7175319SChris Mason 	u64 target;
22476b80053dSChris Mason 	u64 nread = 0;
22485f39d397SChris Mason 	struct extent_buffer *eb;
22496b80053dSChris Mason 	u32 nr;
22506b80053dSChris Mason 	u32 blocksize;
22516b80053dSChris Mason 	u32 nscan = 0;
2252db94535dSChris Mason 
2253a6b6e75eSChris Mason 	if (level != 1)
22543c69faecSChris Mason 		return;
22553c69faecSChris Mason 
22566702ed49SChris Mason 	if (!path->nodes[level])
22576702ed49SChris Mason 		return;
22586702ed49SChris Mason 
22595f39d397SChris Mason 	node = path->nodes[level];
2260925baeddSChris Mason 
22613c69faecSChris Mason 	search = btrfs_node_blockptr(node, slot);
2262*0b246afaSJeff Mahoney 	blocksize = fs_info->nodesize;
2263*0b246afaSJeff Mahoney 	eb = find_extent_buffer(fs_info, search);
22645f39d397SChris Mason 	if (eb) {
22655f39d397SChris Mason 		free_extent_buffer(eb);
22663c69faecSChris Mason 		return;
22673c69faecSChris Mason 	}
22683c69faecSChris Mason 
2269a7175319SChris Mason 	target = search;
22706b80053dSChris Mason 
22715f39d397SChris Mason 	nritems = btrfs_header_nritems(node);
22726b80053dSChris Mason 	nr = slot;
227325b8b936SJosef Bacik 
22743c69faecSChris Mason 	while (1) {
2275e4058b54SDavid Sterba 		if (path->reada == READA_BACK) {
22766b80053dSChris Mason 			if (nr == 0)
22773c69faecSChris Mason 				break;
22786b80053dSChris Mason 			nr--;
2279e4058b54SDavid Sterba 		} else if (path->reada == READA_FORWARD) {
22806b80053dSChris Mason 			nr++;
22816b80053dSChris Mason 			if (nr >= nritems)
22826b80053dSChris Mason 				break;
22833c69faecSChris Mason 		}
2284e4058b54SDavid Sterba 		if (path->reada == READA_BACK && objectid) {
228501f46658SChris Mason 			btrfs_node_key(node, &disk_key, nr);
228601f46658SChris Mason 			if (btrfs_disk_key_objectid(&disk_key) != objectid)
228701f46658SChris Mason 				break;
228801f46658SChris Mason 		}
22896b80053dSChris Mason 		search = btrfs_node_blockptr(node, nr);
2290a7175319SChris Mason 		if ((search <= target && target - search <= 65536) ||
2291a7175319SChris Mason 		    (search > target && search - target <= 65536)) {
2292d3e46feaSDavid Sterba 			readahead_tree_block(root, search);
22936b80053dSChris Mason 			nread += blocksize;
22943c69faecSChris Mason 		}
22956b80053dSChris Mason 		nscan++;
2296a7175319SChris Mason 		if ((nread > 65536 || nscan > 32))
22976b80053dSChris Mason 			break;
22983c69faecSChris Mason 	}
22993c69faecSChris Mason }
2300925baeddSChris Mason 
23010b08851fSJosef Bacik static noinline void reada_for_balance(struct btrfs_root *root,
2302b4ce94deSChris Mason 				       struct btrfs_path *path, int level)
2303b4ce94deSChris Mason {
2304*0b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
2305b4ce94deSChris Mason 	int slot;
2306b4ce94deSChris Mason 	int nritems;
2307b4ce94deSChris Mason 	struct extent_buffer *parent;
2308b4ce94deSChris Mason 	struct extent_buffer *eb;
2309b4ce94deSChris Mason 	u64 gen;
2310b4ce94deSChris Mason 	u64 block1 = 0;
2311b4ce94deSChris Mason 	u64 block2 = 0;
2312b4ce94deSChris Mason 
23138c594ea8SChris Mason 	parent = path->nodes[level + 1];
2314b4ce94deSChris Mason 	if (!parent)
23150b08851fSJosef Bacik 		return;
2316b4ce94deSChris Mason 
2317b4ce94deSChris Mason 	nritems = btrfs_header_nritems(parent);
23188c594ea8SChris Mason 	slot = path->slots[level + 1];
2319b4ce94deSChris Mason 
2320b4ce94deSChris Mason 	if (slot > 0) {
2321b4ce94deSChris Mason 		block1 = btrfs_node_blockptr(parent, slot - 1);
2322b4ce94deSChris Mason 		gen = btrfs_node_ptr_generation(parent, slot - 1);
2323*0b246afaSJeff Mahoney 		eb = find_extent_buffer(fs_info, block1);
2324b9fab919SChris Mason 		/*
2325b9fab919SChris Mason 		 * if we get -eagain from btrfs_buffer_uptodate, we
2326b9fab919SChris Mason 		 * don't want to return eagain here.  That will loop
2327b9fab919SChris Mason 		 * forever
2328b9fab919SChris Mason 		 */
2329b9fab919SChris Mason 		if (eb && btrfs_buffer_uptodate(eb, gen, 1) != 0)
2330b4ce94deSChris Mason 			block1 = 0;
2331b4ce94deSChris Mason 		free_extent_buffer(eb);
2332b4ce94deSChris Mason 	}
23338c594ea8SChris Mason 	if (slot + 1 < nritems) {
2334b4ce94deSChris Mason 		block2 = btrfs_node_blockptr(parent, slot + 1);
2335b4ce94deSChris Mason 		gen = btrfs_node_ptr_generation(parent, slot + 1);
2336*0b246afaSJeff Mahoney 		eb = find_extent_buffer(fs_info, block2);
2337b9fab919SChris Mason 		if (eb && btrfs_buffer_uptodate(eb, gen, 1) != 0)
2338b4ce94deSChris Mason 			block2 = 0;
2339b4ce94deSChris Mason 		free_extent_buffer(eb);
2340b4ce94deSChris Mason 	}
23418c594ea8SChris Mason 
2342b4ce94deSChris Mason 	if (block1)
2343d3e46feaSDavid Sterba 		readahead_tree_block(root, block1);
2344b4ce94deSChris Mason 	if (block2)
2345d3e46feaSDavid Sterba 		readahead_tree_block(root, block2);
2346b4ce94deSChris Mason }
2347b4ce94deSChris Mason 
2348b4ce94deSChris Mason 
2349b4ce94deSChris Mason /*
2350d397712bSChris Mason  * when we walk down the tree, it is usually safe to unlock the higher layers
2351d397712bSChris Mason  * in the tree.  The exceptions are when our path goes through slot 0, because
2352d397712bSChris Mason  * operations on the tree might require changing key pointers higher up in the
2353d397712bSChris Mason  * tree.
2354d352ac68SChris Mason  *
2355d397712bSChris Mason  * callers might also have set path->keep_locks, which tells this code to keep
2356d397712bSChris Mason  * the lock if the path points to the last slot in the block.  This is part of
2357d397712bSChris Mason  * walking through the tree, and selecting the next slot in the higher block.
2358d352ac68SChris Mason  *
2359d397712bSChris Mason  * lowest_unlock sets the lowest level in the tree we're allowed to unlock.  so
2360d397712bSChris Mason  * if lowest_unlock is 1, level 0 won't be unlocked
2361d352ac68SChris Mason  */
2362e02119d5SChris Mason static noinline void unlock_up(struct btrfs_path *path, int level,
2363f7c79f30SChris Mason 			       int lowest_unlock, int min_write_lock_level,
2364f7c79f30SChris Mason 			       int *write_lock_level)
2365925baeddSChris Mason {
2366925baeddSChris Mason 	int i;
2367925baeddSChris Mason 	int skip_level = level;
2368051e1b9fSChris Mason 	int no_skips = 0;
2369925baeddSChris Mason 	struct extent_buffer *t;
2370925baeddSChris Mason 
2371925baeddSChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2372925baeddSChris Mason 		if (!path->nodes[i])
2373925baeddSChris Mason 			break;
2374925baeddSChris Mason 		if (!path->locks[i])
2375925baeddSChris Mason 			break;
2376051e1b9fSChris Mason 		if (!no_skips && path->slots[i] == 0) {
2377925baeddSChris Mason 			skip_level = i + 1;
2378925baeddSChris Mason 			continue;
2379925baeddSChris Mason 		}
2380051e1b9fSChris Mason 		if (!no_skips && path->keep_locks) {
2381925baeddSChris Mason 			u32 nritems;
2382925baeddSChris Mason 			t = path->nodes[i];
2383925baeddSChris Mason 			nritems = btrfs_header_nritems(t);
2384051e1b9fSChris Mason 			if (nritems < 1 || path->slots[i] >= nritems - 1) {
2385925baeddSChris Mason 				skip_level = i + 1;
2386925baeddSChris Mason 				continue;
2387925baeddSChris Mason 			}
2388925baeddSChris Mason 		}
2389051e1b9fSChris Mason 		if (skip_level < i && i >= lowest_unlock)
2390051e1b9fSChris Mason 			no_skips = 1;
2391051e1b9fSChris Mason 
2392925baeddSChris Mason 		t = path->nodes[i];
2393925baeddSChris Mason 		if (i >= lowest_unlock && i > skip_level && path->locks[i]) {
2394bd681513SChris Mason 			btrfs_tree_unlock_rw(t, path->locks[i]);
2395925baeddSChris Mason 			path->locks[i] = 0;
2396f7c79f30SChris Mason 			if (write_lock_level &&
2397f7c79f30SChris Mason 			    i > min_write_lock_level &&
2398f7c79f30SChris Mason 			    i <= *write_lock_level) {
2399f7c79f30SChris Mason 				*write_lock_level = i - 1;
2400f7c79f30SChris Mason 			}
2401925baeddSChris Mason 		}
2402925baeddSChris Mason 	}
2403925baeddSChris Mason }
2404925baeddSChris Mason 
24053c69faecSChris Mason /*
2406b4ce94deSChris Mason  * This releases any locks held in the path starting at level and
2407b4ce94deSChris Mason  * going all the way up to the root.
2408b4ce94deSChris Mason  *
2409b4ce94deSChris Mason  * btrfs_search_slot will keep the lock held on higher nodes in a few
2410b4ce94deSChris Mason  * corner cases, such as COW of the block at slot zero in the node.  This
2411b4ce94deSChris Mason  * ignores those rules, and it should only be called when there are no
2412b4ce94deSChris Mason  * more updates to be done higher up in the tree.
2413b4ce94deSChris Mason  */
2414b4ce94deSChris Mason noinline void btrfs_unlock_up_safe(struct btrfs_path *path, int level)
2415b4ce94deSChris Mason {
2416b4ce94deSChris Mason 	int i;
2417b4ce94deSChris Mason 
241809a2a8f9SJosef Bacik 	if (path->keep_locks)
2419b4ce94deSChris Mason 		return;
2420b4ce94deSChris Mason 
2421b4ce94deSChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2422b4ce94deSChris Mason 		if (!path->nodes[i])
242312f4daccSChris Mason 			continue;
2424b4ce94deSChris Mason 		if (!path->locks[i])
242512f4daccSChris Mason 			continue;
2426bd681513SChris Mason 		btrfs_tree_unlock_rw(path->nodes[i], path->locks[i]);
2427b4ce94deSChris Mason 		path->locks[i] = 0;
2428b4ce94deSChris Mason 	}
2429b4ce94deSChris Mason }
2430b4ce94deSChris Mason 
2431b4ce94deSChris Mason /*
2432c8c42864SChris Mason  * helper function for btrfs_search_slot.  The goal is to find a block
2433c8c42864SChris Mason  * in cache without setting the path to blocking.  If we find the block
2434c8c42864SChris Mason  * we return zero and the path is unchanged.
2435c8c42864SChris Mason  *
2436c8c42864SChris Mason  * If we can't find the block, we set the path blocking and do some
2437c8c42864SChris Mason  * reada.  -EAGAIN is returned and the search must be repeated.
2438c8c42864SChris Mason  */
2439c8c42864SChris Mason static int
2440c8c42864SChris Mason read_block_for_search(struct btrfs_trans_handle *trans,
2441c8c42864SChris Mason 		       struct btrfs_root *root, struct btrfs_path *p,
2442c8c42864SChris Mason 		       struct extent_buffer **eb_ret, int level, int slot,
24435d9e75c4SJan Schmidt 		       struct btrfs_key *key, u64 time_seq)
2444c8c42864SChris Mason {
2445*0b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
2446c8c42864SChris Mason 	u64 blocknr;
2447c8c42864SChris Mason 	u64 gen;
2448c8c42864SChris Mason 	struct extent_buffer *b = *eb_ret;
2449c8c42864SChris Mason 	struct extent_buffer *tmp;
245076a05b35SChris Mason 	int ret;
2451c8c42864SChris Mason 
2452c8c42864SChris Mason 	blocknr = btrfs_node_blockptr(b, slot);
2453c8c42864SChris Mason 	gen = btrfs_node_ptr_generation(b, slot);
2454c8c42864SChris Mason 
2455*0b246afaSJeff Mahoney 	tmp = find_extent_buffer(fs_info, blocknr);
2456cb44921aSChris Mason 	if (tmp) {
2457b9fab919SChris Mason 		/* first we do an atomic uptodate check */
2458b9fab919SChris Mason 		if (btrfs_buffer_uptodate(tmp, gen, 1) > 0) {
2459c8c42864SChris Mason 			*eb_ret = tmp;
2460c8c42864SChris Mason 			return 0;
2461c8c42864SChris Mason 		}
2462bdf7c00eSJosef Bacik 
2463cb44921aSChris Mason 		/* the pages were up to date, but we failed
2464cb44921aSChris Mason 		 * the generation number check.  Do a full
2465cb44921aSChris Mason 		 * read for the generation number that is correct.
2466cb44921aSChris Mason 		 * We must do this without dropping locks so
2467cb44921aSChris Mason 		 * we can trust our generation number
2468cb44921aSChris Mason 		 */
2469bd681513SChris Mason 		btrfs_set_path_blocking(p);
2470bd681513SChris Mason 
2471b9fab919SChris Mason 		/* now we're allowed to do a blocking uptodate check */
2472bdf7c00eSJosef Bacik 		ret = btrfs_read_buffer(tmp, gen);
2473bdf7c00eSJosef Bacik 		if (!ret) {
2474cb44921aSChris Mason 			*eb_ret = tmp;
2475cb44921aSChris Mason 			return 0;
2476cb44921aSChris Mason 		}
2477cb44921aSChris Mason 		free_extent_buffer(tmp);
2478b3b4aa74SDavid Sterba 		btrfs_release_path(p);
2479cb44921aSChris Mason 		return -EIO;
2480cb44921aSChris Mason 	}
2481c8c42864SChris Mason 
2482c8c42864SChris Mason 	/*
2483c8c42864SChris Mason 	 * reduce lock contention at high levels
2484c8c42864SChris Mason 	 * of the btree by dropping locks before
248576a05b35SChris Mason 	 * we read.  Don't release the lock on the current
248676a05b35SChris Mason 	 * level because we need to walk this node to figure
248776a05b35SChris Mason 	 * out which blocks to read.
2488c8c42864SChris Mason 	 */
24898c594ea8SChris Mason 	btrfs_unlock_up_safe(p, level + 1);
24908c594ea8SChris Mason 	btrfs_set_path_blocking(p);
24918c594ea8SChris Mason 
2492c8c42864SChris Mason 	free_extent_buffer(tmp);
2493e4058b54SDavid Sterba 	if (p->reada != READA_NONE)
2494c8c42864SChris Mason 		reada_for_search(root, p, level, slot, key->objectid);
2495c8c42864SChris Mason 
2496b3b4aa74SDavid Sterba 	btrfs_release_path(p);
249776a05b35SChris Mason 
249876a05b35SChris Mason 	ret = -EAGAIN;
2499ce86cd59SDavid Sterba 	tmp = read_tree_block(root, blocknr, 0);
250064c043deSLiu Bo 	if (!IS_ERR(tmp)) {
250176a05b35SChris Mason 		/*
250276a05b35SChris Mason 		 * If the read above didn't mark this buffer up to date,
250376a05b35SChris Mason 		 * it will never end up being up to date.  Set ret to EIO now
250476a05b35SChris Mason 		 * and give up so that our caller doesn't loop forever
250576a05b35SChris Mason 		 * on our EAGAINs.
250676a05b35SChris Mason 		 */
2507b9fab919SChris Mason 		if (!btrfs_buffer_uptodate(tmp, 0, 0))
250876a05b35SChris Mason 			ret = -EIO;
2509c8c42864SChris Mason 		free_extent_buffer(tmp);
2510c871b0f2SLiu Bo 	} else {
2511c871b0f2SLiu Bo 		ret = PTR_ERR(tmp);
251276a05b35SChris Mason 	}
251376a05b35SChris Mason 	return ret;
2514c8c42864SChris Mason }
2515c8c42864SChris Mason 
2516c8c42864SChris Mason /*
2517c8c42864SChris Mason  * helper function for btrfs_search_slot.  This does all of the checks
2518c8c42864SChris Mason  * for node-level blocks and does any balancing required based on
2519c8c42864SChris Mason  * the ins_len.
2520c8c42864SChris Mason  *
2521c8c42864SChris Mason  * If no extra work was required, zero is returned.  If we had to
2522c8c42864SChris Mason  * drop the path, -EAGAIN is returned and btrfs_search_slot must
2523c8c42864SChris Mason  * start over
2524c8c42864SChris Mason  */
2525c8c42864SChris Mason static int
2526c8c42864SChris Mason setup_nodes_for_search(struct btrfs_trans_handle *trans,
2527c8c42864SChris Mason 		       struct btrfs_root *root, struct btrfs_path *p,
2528bd681513SChris Mason 		       struct extent_buffer *b, int level, int ins_len,
2529bd681513SChris Mason 		       int *write_lock_level)
2530c8c42864SChris Mason {
2531*0b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
2532c8c42864SChris Mason 	int ret;
2533*0b246afaSJeff Mahoney 
2534c8c42864SChris Mason 	if ((p->search_for_split || ins_len > 0) && btrfs_header_nritems(b) >=
2535*0b246afaSJeff Mahoney 	    BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3) {
2536c8c42864SChris Mason 		int sret;
2537c8c42864SChris Mason 
2538bd681513SChris Mason 		if (*write_lock_level < level + 1) {
2539bd681513SChris Mason 			*write_lock_level = level + 1;
2540bd681513SChris Mason 			btrfs_release_path(p);
2541bd681513SChris Mason 			goto again;
2542bd681513SChris Mason 		}
2543bd681513SChris Mason 
2544c8c42864SChris Mason 		btrfs_set_path_blocking(p);
25450b08851fSJosef Bacik 		reada_for_balance(root, p, level);
2546c8c42864SChris Mason 		sret = split_node(trans, root, p, level);
2547bd681513SChris Mason 		btrfs_clear_path_blocking(p, NULL, 0);
2548c8c42864SChris Mason 
2549c8c42864SChris Mason 		BUG_ON(sret > 0);
2550c8c42864SChris Mason 		if (sret) {
2551c8c42864SChris Mason 			ret = sret;
2552c8c42864SChris Mason 			goto done;
2553c8c42864SChris Mason 		}
2554c8c42864SChris Mason 		b = p->nodes[level];
2555c8c42864SChris Mason 	} else if (ins_len < 0 && btrfs_header_nritems(b) <
2556*0b246afaSJeff Mahoney 		   BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 2) {
2557c8c42864SChris Mason 		int sret;
2558c8c42864SChris Mason 
2559bd681513SChris Mason 		if (*write_lock_level < level + 1) {
2560bd681513SChris Mason 			*write_lock_level = level + 1;
2561bd681513SChris Mason 			btrfs_release_path(p);
2562bd681513SChris Mason 			goto again;
2563bd681513SChris Mason 		}
2564bd681513SChris Mason 
2565c8c42864SChris Mason 		btrfs_set_path_blocking(p);
25660b08851fSJosef Bacik 		reada_for_balance(root, p, level);
2567c8c42864SChris Mason 		sret = balance_level(trans, root, p, level);
2568bd681513SChris Mason 		btrfs_clear_path_blocking(p, NULL, 0);
2569c8c42864SChris Mason 
2570c8c42864SChris Mason 		if (sret) {
2571c8c42864SChris Mason 			ret = sret;
2572c8c42864SChris Mason 			goto done;
2573c8c42864SChris Mason 		}
2574c8c42864SChris Mason 		b = p->nodes[level];
2575c8c42864SChris Mason 		if (!b) {
2576b3b4aa74SDavid Sterba 			btrfs_release_path(p);
2577c8c42864SChris Mason 			goto again;
2578c8c42864SChris Mason 		}
2579c8c42864SChris Mason 		BUG_ON(btrfs_header_nritems(b) == 1);
2580c8c42864SChris Mason 	}
2581c8c42864SChris Mason 	return 0;
2582c8c42864SChris Mason 
2583c8c42864SChris Mason again:
2584c8c42864SChris Mason 	ret = -EAGAIN;
2585c8c42864SChris Mason done:
2586c8c42864SChris Mason 	return ret;
2587c8c42864SChris Mason }
2588c8c42864SChris Mason 
2589d7396f07SFilipe David Borba Manana static void key_search_validate(struct extent_buffer *b,
2590d7396f07SFilipe David Borba Manana 				struct btrfs_key *key,
2591d7396f07SFilipe David Borba Manana 				int level)
2592d7396f07SFilipe David Borba Manana {
2593d7396f07SFilipe David Borba Manana #ifdef CONFIG_BTRFS_ASSERT
2594d7396f07SFilipe David Borba Manana 	struct btrfs_disk_key disk_key;
2595d7396f07SFilipe David Borba Manana 
2596d7396f07SFilipe David Borba Manana 	btrfs_cpu_key_to_disk(&disk_key, key);
2597d7396f07SFilipe David Borba Manana 
2598d7396f07SFilipe David Borba Manana 	if (level == 0)
2599d7396f07SFilipe David Borba Manana 		ASSERT(!memcmp_extent_buffer(b, &disk_key,
2600d7396f07SFilipe David Borba Manana 		    offsetof(struct btrfs_leaf, items[0].key),
2601d7396f07SFilipe David Borba Manana 		    sizeof(disk_key)));
2602d7396f07SFilipe David Borba Manana 	else
2603d7396f07SFilipe David Borba Manana 		ASSERT(!memcmp_extent_buffer(b, &disk_key,
2604d7396f07SFilipe David Borba Manana 		    offsetof(struct btrfs_node, ptrs[0].key),
2605d7396f07SFilipe David Borba Manana 		    sizeof(disk_key)));
2606d7396f07SFilipe David Borba Manana #endif
2607d7396f07SFilipe David Borba Manana }
2608d7396f07SFilipe David Borba Manana 
2609d7396f07SFilipe David Borba Manana static int key_search(struct extent_buffer *b, struct btrfs_key *key,
2610d7396f07SFilipe David Borba Manana 		      int level, int *prev_cmp, int *slot)
2611d7396f07SFilipe David Borba Manana {
2612d7396f07SFilipe David Borba Manana 	if (*prev_cmp != 0) {
2613d7396f07SFilipe David Borba Manana 		*prev_cmp = bin_search(b, key, level, slot);
2614d7396f07SFilipe David Borba Manana 		return *prev_cmp;
2615d7396f07SFilipe David Borba Manana 	}
2616d7396f07SFilipe David Borba Manana 
2617d7396f07SFilipe David Borba Manana 	key_search_validate(b, key, level);
2618d7396f07SFilipe David Borba Manana 	*slot = 0;
2619d7396f07SFilipe David Borba Manana 
2620d7396f07SFilipe David Borba Manana 	return 0;
2621d7396f07SFilipe David Borba Manana }
2622d7396f07SFilipe David Borba Manana 
2623381cf658SDavid Sterba int btrfs_find_item(struct btrfs_root *fs_root, struct btrfs_path *path,
2624e33d5c3dSKelley Nielsen 		u64 iobjectid, u64 ioff, u8 key_type,
2625e33d5c3dSKelley Nielsen 		struct btrfs_key *found_key)
2626e33d5c3dSKelley Nielsen {
2627e33d5c3dSKelley Nielsen 	int ret;
2628e33d5c3dSKelley Nielsen 	struct btrfs_key key;
2629e33d5c3dSKelley Nielsen 	struct extent_buffer *eb;
2630381cf658SDavid Sterba 
2631381cf658SDavid Sterba 	ASSERT(path);
26321d4c08e0SDavid Sterba 	ASSERT(found_key);
2633e33d5c3dSKelley Nielsen 
2634e33d5c3dSKelley Nielsen 	key.type = key_type;
2635e33d5c3dSKelley Nielsen 	key.objectid = iobjectid;
2636e33d5c3dSKelley Nielsen 	key.offset = ioff;
2637e33d5c3dSKelley Nielsen 
2638e33d5c3dSKelley Nielsen 	ret = btrfs_search_slot(NULL, fs_root, &key, path, 0, 0);
26391d4c08e0SDavid Sterba 	if (ret < 0)
2640e33d5c3dSKelley Nielsen 		return ret;
2641e33d5c3dSKelley Nielsen 
2642e33d5c3dSKelley Nielsen 	eb = path->nodes[0];
2643e33d5c3dSKelley Nielsen 	if (ret && path->slots[0] >= btrfs_header_nritems(eb)) {
2644e33d5c3dSKelley Nielsen 		ret = btrfs_next_leaf(fs_root, path);
2645e33d5c3dSKelley Nielsen 		if (ret)
2646e33d5c3dSKelley Nielsen 			return ret;
2647e33d5c3dSKelley Nielsen 		eb = path->nodes[0];
2648e33d5c3dSKelley Nielsen 	}
2649e33d5c3dSKelley Nielsen 
2650e33d5c3dSKelley Nielsen 	btrfs_item_key_to_cpu(eb, found_key, path->slots[0]);
2651e33d5c3dSKelley Nielsen 	if (found_key->type != key.type ||
2652e33d5c3dSKelley Nielsen 			found_key->objectid != key.objectid)
2653e33d5c3dSKelley Nielsen 		return 1;
2654e33d5c3dSKelley Nielsen 
2655e33d5c3dSKelley Nielsen 	return 0;
2656e33d5c3dSKelley Nielsen }
2657e33d5c3dSKelley Nielsen 
2658c8c42864SChris Mason /*
265974123bd7SChris Mason  * look for key in the tree.  path is filled in with nodes along the way
266074123bd7SChris Mason  * if key is found, we return zero and you can find the item in the leaf
266174123bd7SChris Mason  * level of the path (level 0)
266274123bd7SChris Mason  *
266374123bd7SChris Mason  * If the key isn't found, the path points to the slot where it should
2664aa5d6bedSChris Mason  * be inserted, and 1 is returned.  If there are other errors during the
2665aa5d6bedSChris Mason  * search a negative error number is returned.
266697571fd0SChris Mason  *
266797571fd0SChris Mason  * if ins_len > 0, nodes and leaves will be split as we walk down the
266897571fd0SChris Mason  * tree.  if ins_len < 0, nodes will be merged as we walk down the tree (if
266997571fd0SChris Mason  * possible)
267074123bd7SChris Mason  */
2671e089f05cSChris Mason int btrfs_search_slot(struct btrfs_trans_handle *trans, struct btrfs_root
2672e089f05cSChris Mason 		      *root, struct btrfs_key *key, struct btrfs_path *p, int
2673e089f05cSChris Mason 		      ins_len, int cow)
2674be0e5c09SChris Mason {
2675*0b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
26765f39d397SChris Mason 	struct extent_buffer *b;
2677be0e5c09SChris Mason 	int slot;
2678be0e5c09SChris Mason 	int ret;
267933c66f43SYan Zheng 	int err;
2680be0e5c09SChris Mason 	int level;
2681925baeddSChris Mason 	int lowest_unlock = 1;
2682bd681513SChris Mason 	int root_lock;
2683bd681513SChris Mason 	/* everything at write_lock_level or lower must be write locked */
2684bd681513SChris Mason 	int write_lock_level = 0;
26859f3a7427SChris Mason 	u8 lowest_level = 0;
2686f7c79f30SChris Mason 	int min_write_lock_level;
2687d7396f07SFilipe David Borba Manana 	int prev_cmp;
26889f3a7427SChris Mason 
26896702ed49SChris Mason 	lowest_level = p->lowest_level;
2690323ac95bSChris Mason 	WARN_ON(lowest_level && ins_len > 0);
269122b0ebdaSChris Mason 	WARN_ON(p->nodes[0] != NULL);
2692eb653de1SFilipe David Borba Manana 	BUG_ON(!cow && ins_len);
269325179201SJosef Bacik 
2694bd681513SChris Mason 	if (ins_len < 0) {
2695925baeddSChris Mason 		lowest_unlock = 2;
269665b51a00SChris Mason 
2697bd681513SChris Mason 		/* when we are removing items, we might have to go up to level
2698bd681513SChris Mason 		 * two as we update tree pointers  Make sure we keep write
2699bd681513SChris Mason 		 * for those levels as well
2700bd681513SChris Mason 		 */
2701bd681513SChris Mason 		write_lock_level = 2;
2702bd681513SChris Mason 	} else if (ins_len > 0) {
2703bd681513SChris Mason 		/*
2704bd681513SChris Mason 		 * for inserting items, make sure we have a write lock on
2705bd681513SChris Mason 		 * level 1 so we can update keys
2706bd681513SChris Mason 		 */
2707bd681513SChris Mason 		write_lock_level = 1;
2708bd681513SChris Mason 	}
2709bd681513SChris Mason 
2710bd681513SChris Mason 	if (!cow)
2711bd681513SChris Mason 		write_lock_level = -1;
2712bd681513SChris Mason 
271309a2a8f9SJosef Bacik 	if (cow && (p->keep_locks || p->lowest_level))
2714bd681513SChris Mason 		write_lock_level = BTRFS_MAX_LEVEL;
2715bd681513SChris Mason 
2716f7c79f30SChris Mason 	min_write_lock_level = write_lock_level;
2717f7c79f30SChris Mason 
2718bb803951SChris Mason again:
2719d7396f07SFilipe David Borba Manana 	prev_cmp = -1;
2720bd681513SChris Mason 	/*
2721bd681513SChris Mason 	 * we try very hard to do read locks on the root
2722bd681513SChris Mason 	 */
2723bd681513SChris Mason 	root_lock = BTRFS_READ_LOCK;
2724bd681513SChris Mason 	level = 0;
27255d4f98a2SYan Zheng 	if (p->search_commit_root) {
2726bd681513SChris Mason 		/*
2727bd681513SChris Mason 		 * the commit roots are read only
2728bd681513SChris Mason 		 * so we always do read locks
2729bd681513SChris Mason 		 */
27303f8a18ccSJosef Bacik 		if (p->need_commit_sem)
2731*0b246afaSJeff Mahoney 			down_read(&fs_info->commit_root_sem);
27325d4f98a2SYan Zheng 		b = root->commit_root;
27335d4f98a2SYan Zheng 		extent_buffer_get(b);
2734bd681513SChris Mason 		level = btrfs_header_level(b);
27353f8a18ccSJosef Bacik 		if (p->need_commit_sem)
2736*0b246afaSJeff Mahoney 			up_read(&fs_info->commit_root_sem);
27375d4f98a2SYan Zheng 		if (!p->skip_locking)
2738bd681513SChris Mason 			btrfs_tree_read_lock(b);
27395d4f98a2SYan Zheng 	} else {
2740bd681513SChris Mason 		if (p->skip_locking) {
27415cd57b2cSChris Mason 			b = btrfs_root_node(root);
2742bd681513SChris Mason 			level = btrfs_header_level(b);
2743bd681513SChris Mason 		} else {
2744bd681513SChris Mason 			/* we don't know the level of the root node
2745bd681513SChris Mason 			 * until we actually have it read locked
2746bd681513SChris Mason 			 */
2747bd681513SChris Mason 			b = btrfs_read_lock_root_node(root);
2748bd681513SChris Mason 			level = btrfs_header_level(b);
2749bd681513SChris Mason 			if (level <= write_lock_level) {
2750bd681513SChris Mason 				/* whoops, must trade for write lock */
2751bd681513SChris Mason 				btrfs_tree_read_unlock(b);
2752bd681513SChris Mason 				free_extent_buffer(b);
2753925baeddSChris Mason 				b = btrfs_lock_root_node(root);
2754bd681513SChris Mason 				root_lock = BTRFS_WRITE_LOCK;
2755bd681513SChris Mason 
2756bd681513SChris Mason 				/* the level might have changed, check again */
2757bd681513SChris Mason 				level = btrfs_header_level(b);
27585d4f98a2SYan Zheng 			}
2759bd681513SChris Mason 		}
2760bd681513SChris Mason 	}
2761bd681513SChris Mason 	p->nodes[level] = b;
2762bd681513SChris Mason 	if (!p->skip_locking)
2763bd681513SChris Mason 		p->locks[level] = root_lock;
2764925baeddSChris Mason 
2765eb60ceacSChris Mason 	while (b) {
27665f39d397SChris Mason 		level = btrfs_header_level(b);
276765b51a00SChris Mason 
276865b51a00SChris Mason 		/*
276965b51a00SChris Mason 		 * setup the path here so we can release it under lock
277065b51a00SChris Mason 		 * contention with the cow code
277165b51a00SChris Mason 		 */
277202217ed2SChris Mason 		if (cow) {
2773c8c42864SChris Mason 			/*
2774c8c42864SChris Mason 			 * if we don't really need to cow this block
2775c8c42864SChris Mason 			 * then we don't want to set the path blocking,
2776c8c42864SChris Mason 			 * so we test it here
2777c8c42864SChris Mason 			 */
277864c12921SJeff Mahoney 			if (!should_cow_block(trans, root, b)) {
277964c12921SJeff Mahoney 				trans->dirty = true;
278065b51a00SChris Mason 				goto cow_done;
278164c12921SJeff Mahoney 			}
27825d4f98a2SYan Zheng 
2783bd681513SChris Mason 			/*
2784bd681513SChris Mason 			 * must have write locks on this node and the
2785bd681513SChris Mason 			 * parent
2786bd681513SChris Mason 			 */
27875124e00eSJosef Bacik 			if (level > write_lock_level ||
27885124e00eSJosef Bacik 			    (level + 1 > write_lock_level &&
27895124e00eSJosef Bacik 			    level + 1 < BTRFS_MAX_LEVEL &&
27905124e00eSJosef Bacik 			    p->nodes[level + 1])) {
2791bd681513SChris Mason 				write_lock_level = level + 1;
2792bd681513SChris Mason 				btrfs_release_path(p);
2793bd681513SChris Mason 				goto again;
2794bd681513SChris Mason 			}
2795bd681513SChris Mason 
2796160f4089SFilipe Manana 			btrfs_set_path_blocking(p);
279733c66f43SYan Zheng 			err = btrfs_cow_block(trans, root, b,
2798e20d96d6SChris Mason 					      p->nodes[level + 1],
27999fa8cfe7SChris Mason 					      p->slots[level + 1], &b);
280033c66f43SYan Zheng 			if (err) {
280133c66f43SYan Zheng 				ret = err;
280265b51a00SChris Mason 				goto done;
280354aa1f4dSChris Mason 			}
280402217ed2SChris Mason 		}
280565b51a00SChris Mason cow_done:
2806eb60ceacSChris Mason 		p->nodes[level] = b;
2807bd681513SChris Mason 		btrfs_clear_path_blocking(p, NULL, 0);
2808b4ce94deSChris Mason 
2809b4ce94deSChris Mason 		/*
2810b4ce94deSChris Mason 		 * we have a lock on b and as long as we aren't changing
2811b4ce94deSChris Mason 		 * the tree, there is no way to for the items in b to change.
2812b4ce94deSChris Mason 		 * It is safe to drop the lock on our parent before we
2813b4ce94deSChris Mason 		 * go through the expensive btree search on b.
2814b4ce94deSChris Mason 		 *
2815eb653de1SFilipe David Borba Manana 		 * If we're inserting or deleting (ins_len != 0), then we might
2816eb653de1SFilipe David Borba Manana 		 * be changing slot zero, which may require changing the parent.
2817eb653de1SFilipe David Borba Manana 		 * So, we can't drop the lock until after we know which slot
2818eb653de1SFilipe David Borba Manana 		 * we're operating on.
2819b4ce94deSChris Mason 		 */
2820eb653de1SFilipe David Borba Manana 		if (!ins_len && !p->keep_locks) {
2821eb653de1SFilipe David Borba Manana 			int u = level + 1;
2822eb653de1SFilipe David Borba Manana 
2823eb653de1SFilipe David Borba Manana 			if (u < BTRFS_MAX_LEVEL && p->locks[u]) {
2824eb653de1SFilipe David Borba Manana 				btrfs_tree_unlock_rw(p->nodes[u], p->locks[u]);
2825eb653de1SFilipe David Borba Manana 				p->locks[u] = 0;
2826eb653de1SFilipe David Borba Manana 			}
2827eb653de1SFilipe David Borba Manana 		}
2828b4ce94deSChris Mason 
2829d7396f07SFilipe David Borba Manana 		ret = key_search(b, key, level, &prev_cmp, &slot);
2830415b35a5SLiu Bo 		if (ret < 0)
2831415b35a5SLiu Bo 			goto done;
2832b4ce94deSChris Mason 
28335f39d397SChris Mason 		if (level != 0) {
283433c66f43SYan Zheng 			int dec = 0;
283533c66f43SYan Zheng 			if (ret && slot > 0) {
283633c66f43SYan Zheng 				dec = 1;
2837be0e5c09SChris Mason 				slot -= 1;
283833c66f43SYan Zheng 			}
2839be0e5c09SChris Mason 			p->slots[level] = slot;
284033c66f43SYan Zheng 			err = setup_nodes_for_search(trans, root, p, b, level,
2841bd681513SChris Mason 					     ins_len, &write_lock_level);
284233c66f43SYan Zheng 			if (err == -EAGAIN)
2843b4ce94deSChris Mason 				goto again;
284433c66f43SYan Zheng 			if (err) {
284533c66f43SYan Zheng 				ret = err;
284665b51a00SChris Mason 				goto done;
284733c66f43SYan Zheng 			}
28485c680ed6SChris Mason 			b = p->nodes[level];
28495c680ed6SChris Mason 			slot = p->slots[level];
2850b4ce94deSChris Mason 
2851bd681513SChris Mason 			/*
2852bd681513SChris Mason 			 * slot 0 is special, if we change the key
2853bd681513SChris Mason 			 * we have to update the parent pointer
2854bd681513SChris Mason 			 * which means we must have a write lock
2855bd681513SChris Mason 			 * on the parent
2856bd681513SChris Mason 			 */
2857eb653de1SFilipe David Borba Manana 			if (slot == 0 && ins_len &&
2858bd681513SChris Mason 			    write_lock_level < level + 1) {
2859bd681513SChris Mason 				write_lock_level = level + 1;
2860bd681513SChris Mason 				btrfs_release_path(p);
2861bd681513SChris Mason 				goto again;
2862bd681513SChris Mason 			}
2863bd681513SChris Mason 
2864f7c79f30SChris Mason 			unlock_up(p, level, lowest_unlock,
2865f7c79f30SChris Mason 				  min_write_lock_level, &write_lock_level);
2866f9efa9c7SChris Mason 
2867925baeddSChris Mason 			if (level == lowest_level) {
286833c66f43SYan Zheng 				if (dec)
286933c66f43SYan Zheng 					p->slots[level]++;
28705b21f2edSZheng Yan 				goto done;
2871925baeddSChris Mason 			}
2872ca7a79adSChris Mason 
287333c66f43SYan Zheng 			err = read_block_for_search(trans, root, p,
28745d9e75c4SJan Schmidt 						    &b, level, slot, key, 0);
287533c66f43SYan Zheng 			if (err == -EAGAIN)
2876051e1b9fSChris Mason 				goto again;
287733c66f43SYan Zheng 			if (err) {
287833c66f43SYan Zheng 				ret = err;
287976a05b35SChris Mason 				goto done;
288033c66f43SYan Zheng 			}
288176a05b35SChris Mason 
2882b4ce94deSChris Mason 			if (!p->skip_locking) {
2883bd681513SChris Mason 				level = btrfs_header_level(b);
2884bd681513SChris Mason 				if (level <= write_lock_level) {
2885bd681513SChris Mason 					err = btrfs_try_tree_write_lock(b);
288633c66f43SYan Zheng 					if (!err) {
2887b4ce94deSChris Mason 						btrfs_set_path_blocking(p);
2888925baeddSChris Mason 						btrfs_tree_lock(b);
2889bd681513SChris Mason 						btrfs_clear_path_blocking(p, b,
2890bd681513SChris Mason 								  BTRFS_WRITE_LOCK);
2891b4ce94deSChris Mason 					}
2892bd681513SChris Mason 					p->locks[level] = BTRFS_WRITE_LOCK;
2893bd681513SChris Mason 				} else {
2894f82c458aSChris Mason 					err = btrfs_tree_read_lock_atomic(b);
2895bd681513SChris Mason 					if (!err) {
2896bd681513SChris Mason 						btrfs_set_path_blocking(p);
2897bd681513SChris Mason 						btrfs_tree_read_lock(b);
2898bd681513SChris Mason 						btrfs_clear_path_blocking(p, b,
2899bd681513SChris Mason 								  BTRFS_READ_LOCK);
2900bd681513SChris Mason 					}
2901bd681513SChris Mason 					p->locks[level] = BTRFS_READ_LOCK;
2902bd681513SChris Mason 				}
2903bd681513SChris Mason 				p->nodes[level] = b;
2904b4ce94deSChris Mason 			}
2905be0e5c09SChris Mason 		} else {
2906be0e5c09SChris Mason 			p->slots[level] = slot;
290787b29b20SYan Zheng 			if (ins_len > 0 &&
290887b29b20SYan Zheng 			    btrfs_leaf_free_space(root, b) < ins_len) {
2909bd681513SChris Mason 				if (write_lock_level < 1) {
2910bd681513SChris Mason 					write_lock_level = 1;
2911bd681513SChris Mason 					btrfs_release_path(p);
2912bd681513SChris Mason 					goto again;
2913bd681513SChris Mason 				}
2914bd681513SChris Mason 
2915b4ce94deSChris Mason 				btrfs_set_path_blocking(p);
291633c66f43SYan Zheng 				err = split_leaf(trans, root, key,
2917cc0c5538SChris Mason 						 p, ins_len, ret == 0);
2918bd681513SChris Mason 				btrfs_clear_path_blocking(p, NULL, 0);
2919b4ce94deSChris Mason 
292033c66f43SYan Zheng 				BUG_ON(err > 0);
292133c66f43SYan Zheng 				if (err) {
292233c66f43SYan Zheng 					ret = err;
292365b51a00SChris Mason 					goto done;
292465b51a00SChris Mason 				}
29255c680ed6SChris Mason 			}
2926459931ecSChris Mason 			if (!p->search_for_split)
2927f7c79f30SChris Mason 				unlock_up(p, level, lowest_unlock,
2928f7c79f30SChris Mason 					  min_write_lock_level, &write_lock_level);
292965b51a00SChris Mason 			goto done;
293065b51a00SChris Mason 		}
293165b51a00SChris Mason 	}
293265b51a00SChris Mason 	ret = 1;
293365b51a00SChris Mason done:
2934b4ce94deSChris Mason 	/*
2935b4ce94deSChris Mason 	 * we don't really know what they plan on doing with the path
2936b4ce94deSChris Mason 	 * from here on, so for now just mark it as blocking
2937b4ce94deSChris Mason 	 */
2938b9473439SChris Mason 	if (!p->leave_spinning)
2939b4ce94deSChris Mason 		btrfs_set_path_blocking(p);
29405f5bc6b1SFilipe Manana 	if (ret < 0 && !p->skip_release_on_error)
2941b3b4aa74SDavid Sterba 		btrfs_release_path(p);
2942be0e5c09SChris Mason 	return ret;
2943be0e5c09SChris Mason }
2944be0e5c09SChris Mason 
294574123bd7SChris Mason /*
29465d9e75c4SJan Schmidt  * Like btrfs_search_slot, this looks for a key in the given tree. It uses the
29475d9e75c4SJan Schmidt  * current state of the tree together with the operations recorded in the tree
29485d9e75c4SJan Schmidt  * modification log to search for the key in a previous version of this tree, as
29495d9e75c4SJan Schmidt  * denoted by the time_seq parameter.
29505d9e75c4SJan Schmidt  *
29515d9e75c4SJan Schmidt  * Naturally, there is no support for insert, delete or cow operations.
29525d9e75c4SJan Schmidt  *
29535d9e75c4SJan Schmidt  * The resulting path and return value will be set up as if we called
29545d9e75c4SJan Schmidt  * btrfs_search_slot at that point in time with ins_len and cow both set to 0.
29555d9e75c4SJan Schmidt  */
29565d9e75c4SJan Schmidt int btrfs_search_old_slot(struct btrfs_root *root, struct btrfs_key *key,
29575d9e75c4SJan Schmidt 			  struct btrfs_path *p, u64 time_seq)
29585d9e75c4SJan Schmidt {
2959*0b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
29605d9e75c4SJan Schmidt 	struct extent_buffer *b;
29615d9e75c4SJan Schmidt 	int slot;
29625d9e75c4SJan Schmidt 	int ret;
29635d9e75c4SJan Schmidt 	int err;
29645d9e75c4SJan Schmidt 	int level;
29655d9e75c4SJan Schmidt 	int lowest_unlock = 1;
29665d9e75c4SJan Schmidt 	u8 lowest_level = 0;
2967d4b4087cSJosef Bacik 	int prev_cmp = -1;
29685d9e75c4SJan Schmidt 
29695d9e75c4SJan Schmidt 	lowest_level = p->lowest_level;
29705d9e75c4SJan Schmidt 	WARN_ON(p->nodes[0] != NULL);
29715d9e75c4SJan Schmidt 
29725d9e75c4SJan Schmidt 	if (p->search_commit_root) {
29735d9e75c4SJan Schmidt 		BUG_ON(time_seq);
29745d9e75c4SJan Schmidt 		return btrfs_search_slot(NULL, root, key, p, 0, 0);
29755d9e75c4SJan Schmidt 	}
29765d9e75c4SJan Schmidt 
29775d9e75c4SJan Schmidt again:
29785d9e75c4SJan Schmidt 	b = get_old_root(root, time_seq);
29795d9e75c4SJan Schmidt 	level = btrfs_header_level(b);
29805d9e75c4SJan Schmidt 	p->locks[level] = BTRFS_READ_LOCK;
29815d9e75c4SJan Schmidt 
29825d9e75c4SJan Schmidt 	while (b) {
29835d9e75c4SJan Schmidt 		level = btrfs_header_level(b);
29845d9e75c4SJan Schmidt 		p->nodes[level] = b;
29855d9e75c4SJan Schmidt 		btrfs_clear_path_blocking(p, NULL, 0);
29865d9e75c4SJan Schmidt 
29875d9e75c4SJan Schmidt 		/*
29885d9e75c4SJan Schmidt 		 * we have a lock on b and as long as we aren't changing
29895d9e75c4SJan Schmidt 		 * the tree, there is no way to for the items in b to change.
29905d9e75c4SJan Schmidt 		 * It is safe to drop the lock on our parent before we
29915d9e75c4SJan Schmidt 		 * go through the expensive btree search on b.
29925d9e75c4SJan Schmidt 		 */
29935d9e75c4SJan Schmidt 		btrfs_unlock_up_safe(p, level + 1);
29945d9e75c4SJan Schmidt 
2995d4b4087cSJosef Bacik 		/*
299601327610SNicholas D Steeves 		 * Since we can unwind ebs we want to do a real search every
2997d4b4087cSJosef Bacik 		 * time.
2998d4b4087cSJosef Bacik 		 */
2999d4b4087cSJosef Bacik 		prev_cmp = -1;
3000d7396f07SFilipe David Borba Manana 		ret = key_search(b, key, level, &prev_cmp, &slot);
30015d9e75c4SJan Schmidt 
30025d9e75c4SJan Schmidt 		if (level != 0) {
30035d9e75c4SJan Schmidt 			int dec = 0;
30045d9e75c4SJan Schmidt 			if (ret && slot > 0) {
30055d9e75c4SJan Schmidt 				dec = 1;
30065d9e75c4SJan Schmidt 				slot -= 1;
30075d9e75c4SJan Schmidt 			}
30085d9e75c4SJan Schmidt 			p->slots[level] = slot;
30095d9e75c4SJan Schmidt 			unlock_up(p, level, lowest_unlock, 0, NULL);
30105d9e75c4SJan Schmidt 
30115d9e75c4SJan Schmidt 			if (level == lowest_level) {
30125d9e75c4SJan Schmidt 				if (dec)
30135d9e75c4SJan Schmidt 					p->slots[level]++;
30145d9e75c4SJan Schmidt 				goto done;
30155d9e75c4SJan Schmidt 			}
30165d9e75c4SJan Schmidt 
30175d9e75c4SJan Schmidt 			err = read_block_for_search(NULL, root, p, &b, level,
30185d9e75c4SJan Schmidt 						    slot, key, time_seq);
30195d9e75c4SJan Schmidt 			if (err == -EAGAIN)
30205d9e75c4SJan Schmidt 				goto again;
30215d9e75c4SJan Schmidt 			if (err) {
30225d9e75c4SJan Schmidt 				ret = err;
30235d9e75c4SJan Schmidt 				goto done;
30245d9e75c4SJan Schmidt 			}
30255d9e75c4SJan Schmidt 
30265d9e75c4SJan Schmidt 			level = btrfs_header_level(b);
3027f82c458aSChris Mason 			err = btrfs_tree_read_lock_atomic(b);
30285d9e75c4SJan Schmidt 			if (!err) {
30295d9e75c4SJan Schmidt 				btrfs_set_path_blocking(p);
30305d9e75c4SJan Schmidt 				btrfs_tree_read_lock(b);
30315d9e75c4SJan Schmidt 				btrfs_clear_path_blocking(p, b,
30325d9e75c4SJan Schmidt 							  BTRFS_READ_LOCK);
30335d9e75c4SJan Schmidt 			}
3034*0b246afaSJeff Mahoney 			b = tree_mod_log_rewind(fs_info, p, b, time_seq);
3035db7f3436SJosef Bacik 			if (!b) {
3036db7f3436SJosef Bacik 				ret = -ENOMEM;
3037db7f3436SJosef Bacik 				goto done;
3038db7f3436SJosef Bacik 			}
30395d9e75c4SJan Schmidt 			p->locks[level] = BTRFS_READ_LOCK;
30405d9e75c4SJan Schmidt 			p->nodes[level] = b;
30415d9e75c4SJan Schmidt 		} else {
30425d9e75c4SJan Schmidt 			p->slots[level] = slot;
30435d9e75c4SJan Schmidt 			unlock_up(p, level, lowest_unlock, 0, NULL);
30445d9e75c4SJan Schmidt 			goto done;
30455d9e75c4SJan Schmidt 		}
30465d9e75c4SJan Schmidt 	}
30475d9e75c4SJan Schmidt 	ret = 1;
30485d9e75c4SJan Schmidt done:
30495d9e75c4SJan Schmidt 	if (!p->leave_spinning)
30505d9e75c4SJan Schmidt 		btrfs_set_path_blocking(p);
30515d9e75c4SJan Schmidt 	if (ret < 0)
30525d9e75c4SJan Schmidt 		btrfs_release_path(p);
30535d9e75c4SJan Schmidt 
30545d9e75c4SJan Schmidt 	return ret;
30555d9e75c4SJan Schmidt }
30565d9e75c4SJan Schmidt 
30575d9e75c4SJan Schmidt /*
30582f38b3e1SArne Jansen  * helper to use instead of search slot if no exact match is needed but
30592f38b3e1SArne Jansen  * instead the next or previous item should be returned.
30602f38b3e1SArne Jansen  * When find_higher is true, the next higher item is returned, the next lower
30612f38b3e1SArne Jansen  * otherwise.
30622f38b3e1SArne Jansen  * When return_any and find_higher are both true, and no higher item is found,
30632f38b3e1SArne Jansen  * return the next lower instead.
30642f38b3e1SArne Jansen  * When return_any is true and find_higher is false, and no lower item is found,
30652f38b3e1SArne Jansen  * return the next higher instead.
30662f38b3e1SArne Jansen  * It returns 0 if any item is found, 1 if none is found (tree empty), and
30672f38b3e1SArne Jansen  * < 0 on error
30682f38b3e1SArne Jansen  */
30692f38b3e1SArne Jansen int btrfs_search_slot_for_read(struct btrfs_root *root,
30702f38b3e1SArne Jansen 			       struct btrfs_key *key, struct btrfs_path *p,
30712f38b3e1SArne Jansen 			       int find_higher, int return_any)
30722f38b3e1SArne Jansen {
30732f38b3e1SArne Jansen 	int ret;
30742f38b3e1SArne Jansen 	struct extent_buffer *leaf;
30752f38b3e1SArne Jansen 
30762f38b3e1SArne Jansen again:
30772f38b3e1SArne Jansen 	ret = btrfs_search_slot(NULL, root, key, p, 0, 0);
30782f38b3e1SArne Jansen 	if (ret <= 0)
30792f38b3e1SArne Jansen 		return ret;
30802f38b3e1SArne Jansen 	/*
30812f38b3e1SArne Jansen 	 * a return value of 1 means the path is at the position where the
30822f38b3e1SArne Jansen 	 * item should be inserted. Normally this is the next bigger item,
30832f38b3e1SArne Jansen 	 * but in case the previous item is the last in a leaf, path points
30842f38b3e1SArne Jansen 	 * to the first free slot in the previous leaf, i.e. at an invalid
30852f38b3e1SArne Jansen 	 * item.
30862f38b3e1SArne Jansen 	 */
30872f38b3e1SArne Jansen 	leaf = p->nodes[0];
30882f38b3e1SArne Jansen 
30892f38b3e1SArne Jansen 	if (find_higher) {
30902f38b3e1SArne Jansen 		if (p->slots[0] >= btrfs_header_nritems(leaf)) {
30912f38b3e1SArne Jansen 			ret = btrfs_next_leaf(root, p);
30922f38b3e1SArne Jansen 			if (ret <= 0)
30932f38b3e1SArne Jansen 				return ret;
30942f38b3e1SArne Jansen 			if (!return_any)
30952f38b3e1SArne Jansen 				return 1;
30962f38b3e1SArne Jansen 			/*
30972f38b3e1SArne Jansen 			 * no higher item found, return the next
30982f38b3e1SArne Jansen 			 * lower instead
30992f38b3e1SArne Jansen 			 */
31002f38b3e1SArne Jansen 			return_any = 0;
31012f38b3e1SArne Jansen 			find_higher = 0;
31022f38b3e1SArne Jansen 			btrfs_release_path(p);
31032f38b3e1SArne Jansen 			goto again;
31042f38b3e1SArne Jansen 		}
31052f38b3e1SArne Jansen 	} else {
31062f38b3e1SArne Jansen 		if (p->slots[0] == 0) {
31072f38b3e1SArne Jansen 			ret = btrfs_prev_leaf(root, p);
3108e6793769SArne Jansen 			if (ret < 0)
31092f38b3e1SArne Jansen 				return ret;
3110e6793769SArne Jansen 			if (!ret) {
311123c6bf6aSFilipe David Borba Manana 				leaf = p->nodes[0];
311223c6bf6aSFilipe David Borba Manana 				if (p->slots[0] == btrfs_header_nritems(leaf))
311323c6bf6aSFilipe David Borba Manana 					p->slots[0]--;
3114e6793769SArne Jansen 				return 0;
3115e6793769SArne Jansen 			}
31162f38b3e1SArne Jansen 			if (!return_any)
31172f38b3e1SArne Jansen 				return 1;
31182f38b3e1SArne Jansen 			/*
31192f38b3e1SArne Jansen 			 * no lower item found, return the next
31202f38b3e1SArne Jansen 			 * higher instead
31212f38b3e1SArne Jansen 			 */
31222f38b3e1SArne Jansen 			return_any = 0;
31232f38b3e1SArne Jansen 			find_higher = 1;
31242f38b3e1SArne Jansen 			btrfs_release_path(p);
31252f38b3e1SArne Jansen 			goto again;
3126e6793769SArne Jansen 		} else {
31272f38b3e1SArne Jansen 			--p->slots[0];
31282f38b3e1SArne Jansen 		}
31292f38b3e1SArne Jansen 	}
31302f38b3e1SArne Jansen 	return 0;
31312f38b3e1SArne Jansen }
31322f38b3e1SArne Jansen 
31332f38b3e1SArne Jansen /*
313474123bd7SChris Mason  * adjust the pointers going up the tree, starting at level
313574123bd7SChris Mason  * making sure the right key of each node is points to 'key'.
313674123bd7SChris Mason  * This is used after shifting pointers to the left, so it stops
313774123bd7SChris Mason  * fixing up pointers when a given leaf/node is not in slot 0 of the
313874123bd7SChris Mason  * higher levels
3139aa5d6bedSChris Mason  *
314074123bd7SChris Mason  */
3141b7a0365eSDaniel Dressler static void fixup_low_keys(struct btrfs_fs_info *fs_info,
3142b7a0365eSDaniel Dressler 			   struct btrfs_path *path,
31435f39d397SChris Mason 			   struct btrfs_disk_key *key, int level)
3144be0e5c09SChris Mason {
3145be0e5c09SChris Mason 	int i;
31465f39d397SChris Mason 	struct extent_buffer *t;
31475f39d397SChris Mason 
3148234b63a0SChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
3149be0e5c09SChris Mason 		int tslot = path->slots[i];
3150eb60ceacSChris Mason 		if (!path->nodes[i])
3151be0e5c09SChris Mason 			break;
31525f39d397SChris Mason 		t = path->nodes[i];
3153b7a0365eSDaniel Dressler 		tree_mod_log_set_node_key(fs_info, t, tslot, 1);
31545f39d397SChris Mason 		btrfs_set_node_key(t, key, tslot);
3155d6025579SChris Mason 		btrfs_mark_buffer_dirty(path->nodes[i]);
3156be0e5c09SChris Mason 		if (tslot != 0)
3157be0e5c09SChris Mason 			break;
3158be0e5c09SChris Mason 	}
3159be0e5c09SChris Mason }
3160be0e5c09SChris Mason 
316174123bd7SChris Mason /*
316231840ae1SZheng Yan  * update item key.
316331840ae1SZheng Yan  *
316431840ae1SZheng Yan  * This function isn't completely safe. It's the caller's responsibility
316531840ae1SZheng Yan  * that the new key won't break the order
316631840ae1SZheng Yan  */
3167b7a0365eSDaniel Dressler void btrfs_set_item_key_safe(struct btrfs_fs_info *fs_info,
3168b7a0365eSDaniel Dressler 			     struct btrfs_path *path,
316931840ae1SZheng Yan 			     struct btrfs_key *new_key)
317031840ae1SZheng Yan {
317131840ae1SZheng Yan 	struct btrfs_disk_key disk_key;
317231840ae1SZheng Yan 	struct extent_buffer *eb;
317331840ae1SZheng Yan 	int slot;
317431840ae1SZheng Yan 
317531840ae1SZheng Yan 	eb = path->nodes[0];
317631840ae1SZheng Yan 	slot = path->slots[0];
317731840ae1SZheng Yan 	if (slot > 0) {
317831840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot - 1);
3179143bede5SJeff Mahoney 		BUG_ON(comp_keys(&disk_key, new_key) >= 0);
318031840ae1SZheng Yan 	}
318131840ae1SZheng Yan 	if (slot < btrfs_header_nritems(eb) - 1) {
318231840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot + 1);
3183143bede5SJeff Mahoney 		BUG_ON(comp_keys(&disk_key, new_key) <= 0);
318431840ae1SZheng Yan 	}
318531840ae1SZheng Yan 
318631840ae1SZheng Yan 	btrfs_cpu_key_to_disk(&disk_key, new_key);
318731840ae1SZheng Yan 	btrfs_set_item_key(eb, &disk_key, slot);
318831840ae1SZheng Yan 	btrfs_mark_buffer_dirty(eb);
318931840ae1SZheng Yan 	if (slot == 0)
3190b7a0365eSDaniel Dressler 		fixup_low_keys(fs_info, path, &disk_key, 1);
319131840ae1SZheng Yan }
319231840ae1SZheng Yan 
319331840ae1SZheng Yan /*
319474123bd7SChris Mason  * try to push data from one node into the next node left in the
319579f95c82SChris Mason  * tree.
3196aa5d6bedSChris Mason  *
3197aa5d6bedSChris Mason  * returns 0 if some ptrs were pushed left, < 0 if there was some horrible
3198aa5d6bedSChris Mason  * error, and > 0 if there was no room in the left hand block.
319974123bd7SChris Mason  */
320098ed5174SChris Mason static int push_node_left(struct btrfs_trans_handle *trans,
320198ed5174SChris Mason 			  struct btrfs_root *root, struct extent_buffer *dst,
3202971a1f66SChris Mason 			  struct extent_buffer *src, int empty)
3203be0e5c09SChris Mason {
3204*0b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
3205be0e5c09SChris Mason 	int push_items = 0;
3206bb803951SChris Mason 	int src_nritems;
3207bb803951SChris Mason 	int dst_nritems;
3208aa5d6bedSChris Mason 	int ret = 0;
3209be0e5c09SChris Mason 
32105f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
32115f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
3212*0b246afaSJeff Mahoney 	push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
32137bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
32147bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
321554aa1f4dSChris Mason 
3216bce4eae9SChris Mason 	if (!empty && src_nritems <= 8)
3217971a1f66SChris Mason 		return 1;
3218971a1f66SChris Mason 
3219d397712bSChris Mason 	if (push_items <= 0)
3220be0e5c09SChris Mason 		return 1;
3221be0e5c09SChris Mason 
3222bce4eae9SChris Mason 	if (empty) {
3223971a1f66SChris Mason 		push_items = min(src_nritems, push_items);
3224bce4eae9SChris Mason 		if (push_items < src_nritems) {
3225bce4eae9SChris Mason 			/* leave at least 8 pointers in the node if
3226bce4eae9SChris Mason 			 * we aren't going to empty it
3227bce4eae9SChris Mason 			 */
3228bce4eae9SChris Mason 			if (src_nritems - push_items < 8) {
3229bce4eae9SChris Mason 				if (push_items <= 8)
3230bce4eae9SChris Mason 					return 1;
3231bce4eae9SChris Mason 				push_items -= 8;
3232bce4eae9SChris Mason 			}
3233bce4eae9SChris Mason 		}
3234bce4eae9SChris Mason 	} else
3235bce4eae9SChris Mason 		push_items = min(src_nritems - 8, push_items);
323679f95c82SChris Mason 
3237*0b246afaSJeff Mahoney 	ret = tree_mod_log_eb_copy(fs_info, dst, src, dst_nritems, 0,
323890f8d62eSJan Schmidt 				   push_items);
32395de865eeSFilipe David Borba Manana 	if (ret) {
324066642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
32415de865eeSFilipe David Borba Manana 		return ret;
32425de865eeSFilipe David Borba Manana 	}
32435f39d397SChris Mason 	copy_extent_buffer(dst, src,
32445f39d397SChris Mason 			   btrfs_node_key_ptr_offset(dst_nritems),
32455f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
3246123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
32475f39d397SChris Mason 
3248bb803951SChris Mason 	if (push_items < src_nritems) {
324957911b8bSJan Schmidt 		/*
325057911b8bSJan Schmidt 		 * don't call tree_mod_log_eb_move here, key removal was already
325157911b8bSJan Schmidt 		 * fully logged by tree_mod_log_eb_copy above.
325257911b8bSJan Schmidt 		 */
32535f39d397SChris Mason 		memmove_extent_buffer(src, btrfs_node_key_ptr_offset(0),
32545f39d397SChris Mason 				      btrfs_node_key_ptr_offset(push_items),
3255e2fa7227SChris Mason 				      (src_nritems - push_items) *
3256123abc88SChris Mason 				      sizeof(struct btrfs_key_ptr));
3257bb803951SChris Mason 	}
32585f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
32595f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
32605f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
32615f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
326231840ae1SZheng Yan 
3263bb803951SChris Mason 	return ret;
3264be0e5c09SChris Mason }
3265be0e5c09SChris Mason 
326697571fd0SChris Mason /*
326779f95c82SChris Mason  * try to push data from one node into the next node right in the
326879f95c82SChris Mason  * tree.
326979f95c82SChris Mason  *
327079f95c82SChris Mason  * returns 0 if some ptrs were pushed, < 0 if there was some horrible
327179f95c82SChris Mason  * error, and > 0 if there was no room in the right hand block.
327279f95c82SChris Mason  *
327379f95c82SChris Mason  * this will  only push up to 1/2 the contents of the left node over
327479f95c82SChris Mason  */
32755f39d397SChris Mason static int balance_node_right(struct btrfs_trans_handle *trans,
32765f39d397SChris Mason 			      struct btrfs_root *root,
32775f39d397SChris Mason 			      struct extent_buffer *dst,
32785f39d397SChris Mason 			      struct extent_buffer *src)
327979f95c82SChris Mason {
3280*0b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
328179f95c82SChris Mason 	int push_items = 0;
328279f95c82SChris Mason 	int max_push;
328379f95c82SChris Mason 	int src_nritems;
328479f95c82SChris Mason 	int dst_nritems;
328579f95c82SChris Mason 	int ret = 0;
328679f95c82SChris Mason 
32877bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
32887bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
32897bb86316SChris Mason 
32905f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
32915f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
3292*0b246afaSJeff Mahoney 	push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
3293d397712bSChris Mason 	if (push_items <= 0)
329479f95c82SChris Mason 		return 1;
3295bce4eae9SChris Mason 
3296d397712bSChris Mason 	if (src_nritems < 4)
3297bce4eae9SChris Mason 		return 1;
329879f95c82SChris Mason 
329979f95c82SChris Mason 	max_push = src_nritems / 2 + 1;
330079f95c82SChris Mason 	/* don't try to empty the node */
3301d397712bSChris Mason 	if (max_push >= src_nritems)
330279f95c82SChris Mason 		return 1;
3303252c38f0SYan 
330479f95c82SChris Mason 	if (max_push < push_items)
330579f95c82SChris Mason 		push_items = max_push;
330679f95c82SChris Mason 
3307*0b246afaSJeff Mahoney 	tree_mod_log_eb_move(fs_info, dst, push_items, 0, dst_nritems);
33085f39d397SChris Mason 	memmove_extent_buffer(dst, btrfs_node_key_ptr_offset(push_items),
33095f39d397SChris Mason 				      btrfs_node_key_ptr_offset(0),
33105f39d397SChris Mason 				      (dst_nritems) *
33115f39d397SChris Mason 				      sizeof(struct btrfs_key_ptr));
3312d6025579SChris Mason 
3313*0b246afaSJeff Mahoney 	ret = tree_mod_log_eb_copy(fs_info, dst, src, 0,
331490f8d62eSJan Schmidt 				   src_nritems - push_items, push_items);
33155de865eeSFilipe David Borba Manana 	if (ret) {
331666642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
33175de865eeSFilipe David Borba Manana 		return ret;
33185de865eeSFilipe David Borba Manana 	}
33195f39d397SChris Mason 	copy_extent_buffer(dst, src,
33205f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
33215f39d397SChris Mason 			   btrfs_node_key_ptr_offset(src_nritems - push_items),
3322123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
332379f95c82SChris Mason 
33245f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
33255f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
332679f95c82SChris Mason 
33275f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
33285f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
332931840ae1SZheng Yan 
333079f95c82SChris Mason 	return ret;
333179f95c82SChris Mason }
333279f95c82SChris Mason 
333379f95c82SChris Mason /*
333497571fd0SChris Mason  * helper function to insert a new root level in the tree.
333597571fd0SChris Mason  * A new node is allocated, and a single item is inserted to
333697571fd0SChris Mason  * point to the existing root
3337aa5d6bedSChris Mason  *
3338aa5d6bedSChris Mason  * returns zero on success or < 0 on failure.
333997571fd0SChris Mason  */
3340d397712bSChris Mason static noinline int insert_new_root(struct btrfs_trans_handle *trans,
33415f39d397SChris Mason 			   struct btrfs_root *root,
3342fdd99c72SLiu Bo 			   struct btrfs_path *path, int level)
334374123bd7SChris Mason {
3344*0b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
33457bb86316SChris Mason 	u64 lower_gen;
33465f39d397SChris Mason 	struct extent_buffer *lower;
33475f39d397SChris Mason 	struct extent_buffer *c;
3348925baeddSChris Mason 	struct extent_buffer *old;
33495f39d397SChris Mason 	struct btrfs_disk_key lower_key;
33505c680ed6SChris Mason 
33515c680ed6SChris Mason 	BUG_ON(path->nodes[level]);
33525c680ed6SChris Mason 	BUG_ON(path->nodes[level-1] != root->node);
33535c680ed6SChris Mason 
33547bb86316SChris Mason 	lower = path->nodes[level-1];
33557bb86316SChris Mason 	if (level == 1)
33567bb86316SChris Mason 		btrfs_item_key(lower, &lower_key, 0);
33577bb86316SChris Mason 	else
33587bb86316SChris Mason 		btrfs_node_key(lower, &lower_key, 0);
33597bb86316SChris Mason 
33604d75f8a9SDavid Sterba 	c = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
33614d75f8a9SDavid Sterba 				   &lower_key, level, root->node->start, 0);
33625f39d397SChris Mason 	if (IS_ERR(c))
33635f39d397SChris Mason 		return PTR_ERR(c);
3364925baeddSChris Mason 
3365*0b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
3366f0486c68SYan, Zheng 
3367b159fa28SDavid Sterba 	memzero_extent_buffer(c, 0, sizeof(struct btrfs_header));
33685f39d397SChris Mason 	btrfs_set_header_nritems(c, 1);
33695f39d397SChris Mason 	btrfs_set_header_level(c, level);
3370db94535dSChris Mason 	btrfs_set_header_bytenr(c, c->start);
33715f39d397SChris Mason 	btrfs_set_header_generation(c, trans->transid);
33725d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(c, BTRFS_MIXED_BACKREF_REV);
33735f39d397SChris Mason 	btrfs_set_header_owner(c, root->root_key.objectid);
3374d5719762SChris Mason 
3375*0b246afaSJeff Mahoney 	write_extent_buffer_fsid(c, fs_info->fsid);
3376*0b246afaSJeff Mahoney 	write_extent_buffer_chunk_tree_uuid(c, fs_info->chunk_tree_uuid);
3377e17cade2SChris Mason 
33785f39d397SChris Mason 	btrfs_set_node_key(c, &lower_key, 0);
3379db94535dSChris Mason 	btrfs_set_node_blockptr(c, 0, lower->start);
33807bb86316SChris Mason 	lower_gen = btrfs_header_generation(lower);
338131840ae1SZheng Yan 	WARN_ON(lower_gen != trans->transid);
33827bb86316SChris Mason 
33837bb86316SChris Mason 	btrfs_set_node_ptr_generation(c, 0, lower_gen);
33845f39d397SChris Mason 
33855f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
3386d5719762SChris Mason 
3387925baeddSChris Mason 	old = root->node;
3388fdd99c72SLiu Bo 	tree_mod_log_set_root_pointer(root, c, 0);
3389240f62c8SChris Mason 	rcu_assign_pointer(root->node, c);
3390925baeddSChris Mason 
3391925baeddSChris Mason 	/* the super has an extra ref to root->node */
3392925baeddSChris Mason 	free_extent_buffer(old);
3393925baeddSChris Mason 
33940b86a832SChris Mason 	add_root_to_dirty_list(root);
33955f39d397SChris Mason 	extent_buffer_get(c);
33965f39d397SChris Mason 	path->nodes[level] = c;
339795449a16Schandan 	path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
339874123bd7SChris Mason 	path->slots[level] = 0;
339974123bd7SChris Mason 	return 0;
340074123bd7SChris Mason }
34015c680ed6SChris Mason 
34025c680ed6SChris Mason /*
34035c680ed6SChris Mason  * worker function to insert a single pointer in a node.
34045c680ed6SChris Mason  * the node should have enough room for the pointer already
340597571fd0SChris Mason  *
34065c680ed6SChris Mason  * slot and level indicate where you want the key to go, and
34075c680ed6SChris Mason  * blocknr is the block the key points to.
34085c680ed6SChris Mason  */
3409143bede5SJeff Mahoney static void insert_ptr(struct btrfs_trans_handle *trans,
3410143bede5SJeff Mahoney 		       struct btrfs_root *root, struct btrfs_path *path,
3411143bede5SJeff Mahoney 		       struct btrfs_disk_key *key, u64 bytenr,
3412c3e06965SJan Schmidt 		       int slot, int level)
34135c680ed6SChris Mason {
3414*0b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
34155f39d397SChris Mason 	struct extent_buffer *lower;
34165c680ed6SChris Mason 	int nritems;
3417f3ea38daSJan Schmidt 	int ret;
34185c680ed6SChris Mason 
34195c680ed6SChris Mason 	BUG_ON(!path->nodes[level]);
3420f0486c68SYan, Zheng 	btrfs_assert_tree_locked(path->nodes[level]);
34215f39d397SChris Mason 	lower = path->nodes[level];
34225f39d397SChris Mason 	nritems = btrfs_header_nritems(lower);
3423c293498bSStoyan Gaydarov 	BUG_ON(slot > nritems);
3424*0b246afaSJeff Mahoney 	BUG_ON(nritems == BTRFS_NODEPTRS_PER_BLOCK(fs_info));
342574123bd7SChris Mason 	if (slot != nritems) {
3426c3e06965SJan Schmidt 		if (level)
3427*0b246afaSJeff Mahoney 			tree_mod_log_eb_move(fs_info, lower, slot + 1,
3428f3ea38daSJan Schmidt 					     slot, nritems - slot);
34295f39d397SChris Mason 		memmove_extent_buffer(lower,
34305f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot + 1),
34315f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot),
3432123abc88SChris Mason 			      (nritems - slot) * sizeof(struct btrfs_key_ptr));
343374123bd7SChris Mason 	}
3434c3e06965SJan Schmidt 	if (level) {
3435*0b246afaSJeff Mahoney 		ret = tree_mod_log_insert_key(fs_info, lower, slot,
3436c8cc6341SJosef Bacik 					      MOD_LOG_KEY_ADD, GFP_NOFS);
3437f3ea38daSJan Schmidt 		BUG_ON(ret < 0);
3438f3ea38daSJan Schmidt 	}
34395f39d397SChris Mason 	btrfs_set_node_key(lower, key, slot);
3440db94535dSChris Mason 	btrfs_set_node_blockptr(lower, slot, bytenr);
344174493f7aSChris Mason 	WARN_ON(trans->transid == 0);
344274493f7aSChris Mason 	btrfs_set_node_ptr_generation(lower, slot, trans->transid);
34435f39d397SChris Mason 	btrfs_set_header_nritems(lower, nritems + 1);
34445f39d397SChris Mason 	btrfs_mark_buffer_dirty(lower);
344574123bd7SChris Mason }
344674123bd7SChris Mason 
344797571fd0SChris Mason /*
344897571fd0SChris Mason  * split the node at the specified level in path in two.
344997571fd0SChris Mason  * The path is corrected to point to the appropriate node after the split
345097571fd0SChris Mason  *
345197571fd0SChris Mason  * Before splitting this tries to make some room in the node by pushing
345297571fd0SChris Mason  * left and right, if either one works, it returns right away.
3453aa5d6bedSChris Mason  *
3454aa5d6bedSChris Mason  * returns 0 on success and < 0 on failure
345597571fd0SChris Mason  */
3456e02119d5SChris Mason static noinline int split_node(struct btrfs_trans_handle *trans,
3457e02119d5SChris Mason 			       struct btrfs_root *root,
3458e02119d5SChris Mason 			       struct btrfs_path *path, int level)
3459be0e5c09SChris Mason {
3460*0b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
34615f39d397SChris Mason 	struct extent_buffer *c;
34625f39d397SChris Mason 	struct extent_buffer *split;
34635f39d397SChris Mason 	struct btrfs_disk_key disk_key;
3464be0e5c09SChris Mason 	int mid;
34655c680ed6SChris Mason 	int ret;
34667518a238SChris Mason 	u32 c_nritems;
3467be0e5c09SChris Mason 
34685f39d397SChris Mason 	c = path->nodes[level];
34697bb86316SChris Mason 	WARN_ON(btrfs_header_generation(c) != trans->transid);
34705f39d397SChris Mason 	if (c == root->node) {
3471d9abbf1cSJan Schmidt 		/*
347290f8d62eSJan Schmidt 		 * trying to split the root, lets make a new one
347390f8d62eSJan Schmidt 		 *
3474fdd99c72SLiu Bo 		 * tree mod log: We don't log_removal old root in
347590f8d62eSJan Schmidt 		 * insert_new_root, because that root buffer will be kept as a
347690f8d62eSJan Schmidt 		 * normal node. We are going to log removal of half of the
347790f8d62eSJan Schmidt 		 * elements below with tree_mod_log_eb_copy. We're holding a
347890f8d62eSJan Schmidt 		 * tree lock on the buffer, which is why we cannot race with
347990f8d62eSJan Schmidt 		 * other tree_mod_log users.
3480d9abbf1cSJan Schmidt 		 */
3481fdd99c72SLiu Bo 		ret = insert_new_root(trans, root, path, level + 1);
34825c680ed6SChris Mason 		if (ret)
34835c680ed6SChris Mason 			return ret;
3484b3612421SChris Mason 	} else {
3485e66f709bSChris Mason 		ret = push_nodes_for_insert(trans, root, path, level);
34865f39d397SChris Mason 		c = path->nodes[level];
34875f39d397SChris Mason 		if (!ret && btrfs_header_nritems(c) <
3488*0b246afaSJeff Mahoney 		    BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3)
3489e66f709bSChris Mason 			return 0;
349054aa1f4dSChris Mason 		if (ret < 0)
349154aa1f4dSChris Mason 			return ret;
34925c680ed6SChris Mason 	}
3493e66f709bSChris Mason 
34945f39d397SChris Mason 	c_nritems = btrfs_header_nritems(c);
34955d4f98a2SYan Zheng 	mid = (c_nritems + 1) / 2;
34965d4f98a2SYan Zheng 	btrfs_node_key(c, &disk_key, mid);
34977bb86316SChris Mason 
34984d75f8a9SDavid Sterba 	split = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
34995581a51aSJan Schmidt 			&disk_key, level, c->start, 0);
35005f39d397SChris Mason 	if (IS_ERR(split))
35015f39d397SChris Mason 		return PTR_ERR(split);
350254aa1f4dSChris Mason 
3503*0b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
3504f0486c68SYan, Zheng 
3505b159fa28SDavid Sterba 	memzero_extent_buffer(split, 0, sizeof(struct btrfs_header));
35065f39d397SChris Mason 	btrfs_set_header_level(split, btrfs_header_level(c));
3507db94535dSChris Mason 	btrfs_set_header_bytenr(split, split->start);
35085f39d397SChris Mason 	btrfs_set_header_generation(split, trans->transid);
35095d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(split, BTRFS_MIXED_BACKREF_REV);
35105f39d397SChris Mason 	btrfs_set_header_owner(split, root->root_key.objectid);
3511*0b246afaSJeff Mahoney 	write_extent_buffer_fsid(split, fs_info->fsid);
3512*0b246afaSJeff Mahoney 	write_extent_buffer_chunk_tree_uuid(split, fs_info->chunk_tree_uuid);
35135f39d397SChris Mason 
3514*0b246afaSJeff Mahoney 	ret = tree_mod_log_eb_copy(fs_info, split, c, 0, mid, c_nritems - mid);
35155de865eeSFilipe David Borba Manana 	if (ret) {
351666642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
35175de865eeSFilipe David Borba Manana 		return ret;
35185de865eeSFilipe David Borba Manana 	}
35195f39d397SChris Mason 	copy_extent_buffer(split, c,
35205f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
35215f39d397SChris Mason 			   btrfs_node_key_ptr_offset(mid),
3522123abc88SChris Mason 			   (c_nritems - mid) * sizeof(struct btrfs_key_ptr));
35235f39d397SChris Mason 	btrfs_set_header_nritems(split, c_nritems - mid);
35245f39d397SChris Mason 	btrfs_set_header_nritems(c, mid);
3525aa5d6bedSChris Mason 	ret = 0;
3526aa5d6bedSChris Mason 
35275f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
35285f39d397SChris Mason 	btrfs_mark_buffer_dirty(split);
35295f39d397SChris Mason 
3530143bede5SJeff Mahoney 	insert_ptr(trans, root, path, &disk_key, split->start,
3531c3e06965SJan Schmidt 		   path->slots[level + 1] + 1, level + 1);
3532aa5d6bedSChris Mason 
35335de08d7dSChris Mason 	if (path->slots[level] >= mid) {
35345c680ed6SChris Mason 		path->slots[level] -= mid;
3535925baeddSChris Mason 		btrfs_tree_unlock(c);
35365f39d397SChris Mason 		free_extent_buffer(c);
35375f39d397SChris Mason 		path->nodes[level] = split;
35385c680ed6SChris Mason 		path->slots[level + 1] += 1;
3539eb60ceacSChris Mason 	} else {
3540925baeddSChris Mason 		btrfs_tree_unlock(split);
35415f39d397SChris Mason 		free_extent_buffer(split);
3542be0e5c09SChris Mason 	}
3543aa5d6bedSChris Mason 	return ret;
3544be0e5c09SChris Mason }
3545be0e5c09SChris Mason 
354674123bd7SChris Mason /*
354774123bd7SChris Mason  * how many bytes are required to store the items in a leaf.  start
354874123bd7SChris Mason  * and nr indicate which items in the leaf to check.  This totals up the
354974123bd7SChris Mason  * space used both by the item structs and the item data
355074123bd7SChris Mason  */
35515f39d397SChris Mason static int leaf_space_used(struct extent_buffer *l, int start, int nr)
3552be0e5c09SChris Mason {
355341be1f3bSJosef Bacik 	struct btrfs_item *start_item;
355441be1f3bSJosef Bacik 	struct btrfs_item *end_item;
355541be1f3bSJosef Bacik 	struct btrfs_map_token token;
3556be0e5c09SChris Mason 	int data_len;
35575f39d397SChris Mason 	int nritems = btrfs_header_nritems(l);
3558d4dbff95SChris Mason 	int end = min(nritems, start + nr) - 1;
3559be0e5c09SChris Mason 
3560be0e5c09SChris Mason 	if (!nr)
3561be0e5c09SChris Mason 		return 0;
356241be1f3bSJosef Bacik 	btrfs_init_map_token(&token);
3563dd3cc16bSRoss Kirk 	start_item = btrfs_item_nr(start);
3564dd3cc16bSRoss Kirk 	end_item = btrfs_item_nr(end);
356541be1f3bSJosef Bacik 	data_len = btrfs_token_item_offset(l, start_item, &token) +
356641be1f3bSJosef Bacik 		btrfs_token_item_size(l, start_item, &token);
356741be1f3bSJosef Bacik 	data_len = data_len - btrfs_token_item_offset(l, end_item, &token);
35680783fcfcSChris Mason 	data_len += sizeof(struct btrfs_item) * nr;
3569d4dbff95SChris Mason 	WARN_ON(data_len < 0);
3570be0e5c09SChris Mason 	return data_len;
3571be0e5c09SChris Mason }
3572be0e5c09SChris Mason 
357374123bd7SChris Mason /*
3574d4dbff95SChris Mason  * The space between the end of the leaf items and
3575d4dbff95SChris Mason  * the start of the leaf data.  IOW, how much room
3576d4dbff95SChris Mason  * the leaf has left for both items and data
3577d4dbff95SChris Mason  */
3578d397712bSChris Mason noinline int btrfs_leaf_free_space(struct btrfs_root *root,
3579e02119d5SChris Mason 				   struct extent_buffer *leaf)
3580d4dbff95SChris Mason {
3581*0b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
35825f39d397SChris Mason 	int nritems = btrfs_header_nritems(leaf);
35835f39d397SChris Mason 	int ret;
3584*0b246afaSJeff Mahoney 
3585*0b246afaSJeff Mahoney 	ret = BTRFS_LEAF_DATA_SIZE(fs_info) - leaf_space_used(leaf, 0, nritems);
35865f39d397SChris Mason 	if (ret < 0) {
3587*0b246afaSJeff Mahoney 		btrfs_crit(fs_info,
3588efe120a0SFrank Holton 			   "leaf free space ret %d, leaf data size %lu, used %d nritems %d",
3589da17066cSJeff Mahoney 			   ret,
3590*0b246afaSJeff Mahoney 			   (unsigned long) BTRFS_LEAF_DATA_SIZE(fs_info),
35915f39d397SChris Mason 			   leaf_space_used(leaf, 0, nritems), nritems);
35925f39d397SChris Mason 	}
35935f39d397SChris Mason 	return ret;
3594d4dbff95SChris Mason }
3595d4dbff95SChris Mason 
359699d8f83cSChris Mason /*
359799d8f83cSChris Mason  * min slot controls the lowest index we're willing to push to the
359899d8f83cSChris Mason  * right.  We'll push up to and including min_slot, but no lower
359999d8f83cSChris Mason  */
360044871b1bSChris Mason static noinline int __push_leaf_right(struct btrfs_trans_handle *trans,
360144871b1bSChris Mason 				      struct btrfs_root *root,
360244871b1bSChris Mason 				      struct btrfs_path *path,
360344871b1bSChris Mason 				      int data_size, int empty,
360444871b1bSChris Mason 				      struct extent_buffer *right,
360599d8f83cSChris Mason 				      int free_space, u32 left_nritems,
360699d8f83cSChris Mason 				      u32 min_slot)
360700ec4c51SChris Mason {
3608*0b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
36095f39d397SChris Mason 	struct extent_buffer *left = path->nodes[0];
361044871b1bSChris Mason 	struct extent_buffer *upper = path->nodes[1];
3611cfed81a0SChris Mason 	struct btrfs_map_token token;
36125f39d397SChris Mason 	struct btrfs_disk_key disk_key;
361300ec4c51SChris Mason 	int slot;
361434a38218SChris Mason 	u32 i;
361500ec4c51SChris Mason 	int push_space = 0;
361600ec4c51SChris Mason 	int push_items = 0;
36170783fcfcSChris Mason 	struct btrfs_item *item;
361834a38218SChris Mason 	u32 nr;
36197518a238SChris Mason 	u32 right_nritems;
36205f39d397SChris Mason 	u32 data_end;
3621db94535dSChris Mason 	u32 this_item_size;
362200ec4c51SChris Mason 
3623cfed81a0SChris Mason 	btrfs_init_map_token(&token);
3624cfed81a0SChris Mason 
362534a38218SChris Mason 	if (empty)
362634a38218SChris Mason 		nr = 0;
362734a38218SChris Mason 	else
362899d8f83cSChris Mason 		nr = max_t(u32, 1, min_slot);
362934a38218SChris Mason 
363031840ae1SZheng Yan 	if (path->slots[0] >= left_nritems)
363187b29b20SYan Zheng 		push_space += data_size;
363231840ae1SZheng Yan 
363344871b1bSChris Mason 	slot = path->slots[1];
363434a38218SChris Mason 	i = left_nritems - 1;
363534a38218SChris Mason 	while (i >= nr) {
3636dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
3637db94535dSChris Mason 
363831840ae1SZheng Yan 		if (!empty && push_items > 0) {
363931840ae1SZheng Yan 			if (path->slots[0] > i)
364031840ae1SZheng Yan 				break;
364131840ae1SZheng Yan 			if (path->slots[0] == i) {
364231840ae1SZheng Yan 				int space = btrfs_leaf_free_space(root, left);
364331840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
364431840ae1SZheng Yan 					break;
364531840ae1SZheng Yan 			}
364631840ae1SZheng Yan 		}
364731840ae1SZheng Yan 
364800ec4c51SChris Mason 		if (path->slots[0] == i)
364987b29b20SYan Zheng 			push_space += data_size;
3650db94535dSChris Mason 
3651db94535dSChris Mason 		this_item_size = btrfs_item_size(left, item);
3652db94535dSChris Mason 		if (this_item_size + sizeof(*item) + push_space > free_space)
365300ec4c51SChris Mason 			break;
365431840ae1SZheng Yan 
365500ec4c51SChris Mason 		push_items++;
3656db94535dSChris Mason 		push_space += this_item_size + sizeof(*item);
365734a38218SChris Mason 		if (i == 0)
365834a38218SChris Mason 			break;
365934a38218SChris Mason 		i--;
3660db94535dSChris Mason 	}
36615f39d397SChris Mason 
3662925baeddSChris Mason 	if (push_items == 0)
3663925baeddSChris Mason 		goto out_unlock;
36645f39d397SChris Mason 
36656c1500f2SJulia Lawall 	WARN_ON(!empty && push_items == left_nritems);
36665f39d397SChris Mason 
366700ec4c51SChris Mason 	/* push left to right */
36685f39d397SChris Mason 	right_nritems = btrfs_header_nritems(right);
366934a38218SChris Mason 
36705f39d397SChris Mason 	push_space = btrfs_item_end_nr(left, left_nritems - push_items);
3671123abc88SChris Mason 	push_space -= leaf_data_end(root, left);
36725f39d397SChris Mason 
367300ec4c51SChris Mason 	/* make room in the right data area */
36745f39d397SChris Mason 	data_end = leaf_data_end(root, right);
36755f39d397SChris Mason 	memmove_extent_buffer(right,
36765f39d397SChris Mason 			      btrfs_leaf_data(right) + data_end - push_space,
36775f39d397SChris Mason 			      btrfs_leaf_data(right) + data_end,
3678*0b246afaSJeff Mahoney 			      BTRFS_LEAF_DATA_SIZE(fs_info) - data_end);
36795f39d397SChris Mason 
368000ec4c51SChris Mason 	/* copy from the left data area */
36815f39d397SChris Mason 	copy_extent_buffer(right, left, btrfs_leaf_data(right) +
3682*0b246afaSJeff Mahoney 		     BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
3683d6025579SChris Mason 		     btrfs_leaf_data(left) + leaf_data_end(root, left),
3684d6025579SChris Mason 		     push_space);
36855f39d397SChris Mason 
36865f39d397SChris Mason 	memmove_extent_buffer(right, btrfs_item_nr_offset(push_items),
36875f39d397SChris Mason 			      btrfs_item_nr_offset(0),
36880783fcfcSChris Mason 			      right_nritems * sizeof(struct btrfs_item));
36895f39d397SChris Mason 
369000ec4c51SChris Mason 	/* copy the items from left to right */
36915f39d397SChris Mason 	copy_extent_buffer(right, left, btrfs_item_nr_offset(0),
36925f39d397SChris Mason 		   btrfs_item_nr_offset(left_nritems - push_items),
36930783fcfcSChris Mason 		   push_items * sizeof(struct btrfs_item));
369400ec4c51SChris Mason 
369500ec4c51SChris Mason 	/* update the item pointers */
36967518a238SChris Mason 	right_nritems += push_items;
36975f39d397SChris Mason 	btrfs_set_header_nritems(right, right_nritems);
3698*0b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
36997518a238SChris Mason 	for (i = 0; i < right_nritems; i++) {
3700dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
3701cfed81a0SChris Mason 		push_space -= btrfs_token_item_size(right, item, &token);
3702cfed81a0SChris Mason 		btrfs_set_token_item_offset(right, item, push_space, &token);
3703db94535dSChris Mason 	}
3704db94535dSChris Mason 
37057518a238SChris Mason 	left_nritems -= push_items;
37065f39d397SChris Mason 	btrfs_set_header_nritems(left, left_nritems);
370700ec4c51SChris Mason 
370834a38218SChris Mason 	if (left_nritems)
37095f39d397SChris Mason 		btrfs_mark_buffer_dirty(left);
3710f0486c68SYan, Zheng 	else
3711*0b246afaSJeff Mahoney 		clean_tree_block(trans, fs_info, left);
3712f0486c68SYan, Zheng 
37135f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
3714a429e513SChris Mason 
37155f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
37165f39d397SChris Mason 	btrfs_set_node_key(upper, &disk_key, slot + 1);
3717d6025579SChris Mason 	btrfs_mark_buffer_dirty(upper);
371802217ed2SChris Mason 
371900ec4c51SChris Mason 	/* then fixup the leaf pointer in the path */
37207518a238SChris Mason 	if (path->slots[0] >= left_nritems) {
37217518a238SChris Mason 		path->slots[0] -= left_nritems;
3722925baeddSChris Mason 		if (btrfs_header_nritems(path->nodes[0]) == 0)
3723*0b246afaSJeff Mahoney 			clean_tree_block(trans, fs_info, path->nodes[0]);
3724925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
37255f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
37265f39d397SChris Mason 		path->nodes[0] = right;
372700ec4c51SChris Mason 		path->slots[1] += 1;
372800ec4c51SChris Mason 	} else {
3729925baeddSChris Mason 		btrfs_tree_unlock(right);
37305f39d397SChris Mason 		free_extent_buffer(right);
373100ec4c51SChris Mason 	}
373200ec4c51SChris Mason 	return 0;
3733925baeddSChris Mason 
3734925baeddSChris Mason out_unlock:
3735925baeddSChris Mason 	btrfs_tree_unlock(right);
3736925baeddSChris Mason 	free_extent_buffer(right);
3737925baeddSChris Mason 	return 1;
373800ec4c51SChris Mason }
3739925baeddSChris Mason 
374000ec4c51SChris Mason /*
374144871b1bSChris Mason  * push some data in the path leaf to the right, trying to free up at
374274123bd7SChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
374344871b1bSChris Mason  *
374444871b1bSChris Mason  * returns 1 if the push failed because the other node didn't have enough
374544871b1bSChris Mason  * room, 0 if everything worked out and < 0 if there were major errors.
374699d8f83cSChris Mason  *
374799d8f83cSChris Mason  * this will push starting from min_slot to the end of the leaf.  It won't
374899d8f83cSChris Mason  * push any slot lower than min_slot
374974123bd7SChris Mason  */
375044871b1bSChris Mason static int push_leaf_right(struct btrfs_trans_handle *trans, struct btrfs_root
375199d8f83cSChris Mason 			   *root, struct btrfs_path *path,
375299d8f83cSChris Mason 			   int min_data_size, int data_size,
375399d8f83cSChris Mason 			   int empty, u32 min_slot)
3754be0e5c09SChris Mason {
375544871b1bSChris Mason 	struct extent_buffer *left = path->nodes[0];
375644871b1bSChris Mason 	struct extent_buffer *right;
375744871b1bSChris Mason 	struct extent_buffer *upper;
375844871b1bSChris Mason 	int slot;
375944871b1bSChris Mason 	int free_space;
376044871b1bSChris Mason 	u32 left_nritems;
376144871b1bSChris Mason 	int ret;
376244871b1bSChris Mason 
376344871b1bSChris Mason 	if (!path->nodes[1])
376444871b1bSChris Mason 		return 1;
376544871b1bSChris Mason 
376644871b1bSChris Mason 	slot = path->slots[1];
376744871b1bSChris Mason 	upper = path->nodes[1];
376844871b1bSChris Mason 	if (slot >= btrfs_header_nritems(upper) - 1)
376944871b1bSChris Mason 		return 1;
377044871b1bSChris Mason 
377144871b1bSChris Mason 	btrfs_assert_tree_locked(path->nodes[1]);
377244871b1bSChris Mason 
377344871b1bSChris Mason 	right = read_node_slot(root, upper, slot + 1);
3774fb770ae4SLiu Bo 	/*
3775fb770ae4SLiu Bo 	 * slot + 1 is not valid or we fail to read the right node,
3776fb770ae4SLiu Bo 	 * no big deal, just return.
3777fb770ae4SLiu Bo 	 */
3778fb770ae4SLiu Bo 	if (IS_ERR(right))
377991ca338dSTsutomu Itoh 		return 1;
378091ca338dSTsutomu Itoh 
378144871b1bSChris Mason 	btrfs_tree_lock(right);
378244871b1bSChris Mason 	btrfs_set_lock_blocking(right);
378344871b1bSChris Mason 
378444871b1bSChris Mason 	free_space = btrfs_leaf_free_space(root, right);
378544871b1bSChris Mason 	if (free_space < data_size)
378644871b1bSChris Mason 		goto out_unlock;
378744871b1bSChris Mason 
378844871b1bSChris Mason 	/* cow and double check */
378944871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, right, upper,
379044871b1bSChris Mason 			      slot + 1, &right);
379144871b1bSChris Mason 	if (ret)
379244871b1bSChris Mason 		goto out_unlock;
379344871b1bSChris Mason 
379444871b1bSChris Mason 	free_space = btrfs_leaf_free_space(root, right);
379544871b1bSChris Mason 	if (free_space < data_size)
379644871b1bSChris Mason 		goto out_unlock;
379744871b1bSChris Mason 
379844871b1bSChris Mason 	left_nritems = btrfs_header_nritems(left);
379944871b1bSChris Mason 	if (left_nritems == 0)
380044871b1bSChris Mason 		goto out_unlock;
380144871b1bSChris Mason 
38022ef1fed2SFilipe David Borba Manana 	if (path->slots[0] == left_nritems && !empty) {
38032ef1fed2SFilipe David Borba Manana 		/* Key greater than all keys in the leaf, right neighbor has
38042ef1fed2SFilipe David Borba Manana 		 * enough room for it and we're not emptying our leaf to delete
38052ef1fed2SFilipe David Borba Manana 		 * it, therefore use right neighbor to insert the new item and
38062ef1fed2SFilipe David Borba Manana 		 * no need to touch/dirty our left leaft. */
38072ef1fed2SFilipe David Borba Manana 		btrfs_tree_unlock(left);
38082ef1fed2SFilipe David Borba Manana 		free_extent_buffer(left);
38092ef1fed2SFilipe David Borba Manana 		path->nodes[0] = right;
38102ef1fed2SFilipe David Borba Manana 		path->slots[0] = 0;
38112ef1fed2SFilipe David Borba Manana 		path->slots[1]++;
38122ef1fed2SFilipe David Borba Manana 		return 0;
38132ef1fed2SFilipe David Borba Manana 	}
38142ef1fed2SFilipe David Borba Manana 
381599d8f83cSChris Mason 	return __push_leaf_right(trans, root, path, min_data_size, empty,
381699d8f83cSChris Mason 				right, free_space, left_nritems, min_slot);
381744871b1bSChris Mason out_unlock:
381844871b1bSChris Mason 	btrfs_tree_unlock(right);
381944871b1bSChris Mason 	free_extent_buffer(right);
382044871b1bSChris Mason 	return 1;
382144871b1bSChris Mason }
382244871b1bSChris Mason 
382344871b1bSChris Mason /*
382444871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
382544871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
382699d8f83cSChris Mason  *
382799d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
382899d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us do all the
382999d8f83cSChris Mason  * items
383044871b1bSChris Mason  */
383144871b1bSChris Mason static noinline int __push_leaf_left(struct btrfs_trans_handle *trans,
383244871b1bSChris Mason 				     struct btrfs_root *root,
383344871b1bSChris Mason 				     struct btrfs_path *path, int data_size,
383444871b1bSChris Mason 				     int empty, struct extent_buffer *left,
383599d8f83cSChris Mason 				     int free_space, u32 right_nritems,
383699d8f83cSChris Mason 				     u32 max_slot)
383744871b1bSChris Mason {
3838*0b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
38395f39d397SChris Mason 	struct btrfs_disk_key disk_key;
38405f39d397SChris Mason 	struct extent_buffer *right = path->nodes[0];
3841be0e5c09SChris Mason 	int i;
3842be0e5c09SChris Mason 	int push_space = 0;
3843be0e5c09SChris Mason 	int push_items = 0;
38440783fcfcSChris Mason 	struct btrfs_item *item;
38457518a238SChris Mason 	u32 old_left_nritems;
384634a38218SChris Mason 	u32 nr;
3847aa5d6bedSChris Mason 	int ret = 0;
3848db94535dSChris Mason 	u32 this_item_size;
3849db94535dSChris Mason 	u32 old_left_item_size;
3850cfed81a0SChris Mason 	struct btrfs_map_token token;
3851cfed81a0SChris Mason 
3852cfed81a0SChris Mason 	btrfs_init_map_token(&token);
3853be0e5c09SChris Mason 
385434a38218SChris Mason 	if (empty)
385599d8f83cSChris Mason 		nr = min(right_nritems, max_slot);
385634a38218SChris Mason 	else
385799d8f83cSChris Mason 		nr = min(right_nritems - 1, max_slot);
385834a38218SChris Mason 
385934a38218SChris Mason 	for (i = 0; i < nr; i++) {
3860dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
3861db94535dSChris Mason 
386231840ae1SZheng Yan 		if (!empty && push_items > 0) {
386331840ae1SZheng Yan 			if (path->slots[0] < i)
386431840ae1SZheng Yan 				break;
386531840ae1SZheng Yan 			if (path->slots[0] == i) {
386631840ae1SZheng Yan 				int space = btrfs_leaf_free_space(root, right);
386731840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
386831840ae1SZheng Yan 					break;
386931840ae1SZheng Yan 			}
387031840ae1SZheng Yan 		}
387131840ae1SZheng Yan 
3872be0e5c09SChris Mason 		if (path->slots[0] == i)
387387b29b20SYan Zheng 			push_space += data_size;
3874db94535dSChris Mason 
3875db94535dSChris Mason 		this_item_size = btrfs_item_size(right, item);
3876db94535dSChris Mason 		if (this_item_size + sizeof(*item) + push_space > free_space)
3877be0e5c09SChris Mason 			break;
3878db94535dSChris Mason 
3879be0e5c09SChris Mason 		push_items++;
3880db94535dSChris Mason 		push_space += this_item_size + sizeof(*item);
3881be0e5c09SChris Mason 	}
3882db94535dSChris Mason 
3883be0e5c09SChris Mason 	if (push_items == 0) {
3884925baeddSChris Mason 		ret = 1;
3885925baeddSChris Mason 		goto out;
3886be0e5c09SChris Mason 	}
3887fae7f21cSDulshani Gunawardhana 	WARN_ON(!empty && push_items == btrfs_header_nritems(right));
38885f39d397SChris Mason 
3889be0e5c09SChris Mason 	/* push data from right to left */
38905f39d397SChris Mason 	copy_extent_buffer(left, right,
38915f39d397SChris Mason 			   btrfs_item_nr_offset(btrfs_header_nritems(left)),
38925f39d397SChris Mason 			   btrfs_item_nr_offset(0),
38935f39d397SChris Mason 			   push_items * sizeof(struct btrfs_item));
38945f39d397SChris Mason 
3895*0b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info) -
38965f39d397SChris Mason 		     btrfs_item_offset_nr(right, push_items - 1);
38975f39d397SChris Mason 
38985f39d397SChris Mason 	copy_extent_buffer(left, right, btrfs_leaf_data(left) +
3899d6025579SChris Mason 		     leaf_data_end(root, left) - push_space,
3900123abc88SChris Mason 		     btrfs_leaf_data(right) +
39015f39d397SChris Mason 		     btrfs_item_offset_nr(right, push_items - 1),
3902be0e5c09SChris Mason 		     push_space);
39035f39d397SChris Mason 	old_left_nritems = btrfs_header_nritems(left);
390487b29b20SYan Zheng 	BUG_ON(old_left_nritems <= 0);
3905eb60ceacSChris Mason 
3906db94535dSChris Mason 	old_left_item_size = btrfs_item_offset_nr(left, old_left_nritems - 1);
3907be0e5c09SChris Mason 	for (i = old_left_nritems; i < old_left_nritems + push_items; i++) {
39085f39d397SChris Mason 		u32 ioff;
3909db94535dSChris Mason 
3910dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
3911db94535dSChris Mason 
3912cfed81a0SChris Mason 		ioff = btrfs_token_item_offset(left, item, &token);
3913cfed81a0SChris Mason 		btrfs_set_token_item_offset(left, item,
3914*0b246afaSJeff Mahoney 		      ioff - (BTRFS_LEAF_DATA_SIZE(fs_info) - old_left_item_size),
3915cfed81a0SChris Mason 		      &token);
3916be0e5c09SChris Mason 	}
39175f39d397SChris Mason 	btrfs_set_header_nritems(left, old_left_nritems + push_items);
3918be0e5c09SChris Mason 
3919be0e5c09SChris Mason 	/* fixup right node */
392031b1a2bdSJulia Lawall 	if (push_items > right_nritems)
392131b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "push items %d nr %u\n", push_items,
3922d397712bSChris Mason 		       right_nritems);
392334a38218SChris Mason 
392434a38218SChris Mason 	if (push_items < right_nritems) {
39255f39d397SChris Mason 		push_space = btrfs_item_offset_nr(right, push_items - 1) -
3926123abc88SChris Mason 						  leaf_data_end(root, right);
39275f39d397SChris Mason 		memmove_extent_buffer(right, btrfs_leaf_data(right) +
3928*0b246afaSJeff Mahoney 				      BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
3929d6025579SChris Mason 				      btrfs_leaf_data(right) +
3930123abc88SChris Mason 				      leaf_data_end(root, right), push_space);
39315f39d397SChris Mason 
39325f39d397SChris Mason 		memmove_extent_buffer(right, btrfs_item_nr_offset(0),
39335f39d397SChris Mason 			      btrfs_item_nr_offset(push_items),
39345f39d397SChris Mason 			     (btrfs_header_nritems(right) - push_items) *
39350783fcfcSChris Mason 			     sizeof(struct btrfs_item));
393634a38218SChris Mason 	}
3937eef1c494SYan 	right_nritems -= push_items;
3938eef1c494SYan 	btrfs_set_header_nritems(right, right_nritems);
3939*0b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
39405f39d397SChris Mason 	for (i = 0; i < right_nritems; i++) {
3941dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
3942db94535dSChris Mason 
3943cfed81a0SChris Mason 		push_space = push_space - btrfs_token_item_size(right,
3944cfed81a0SChris Mason 								item, &token);
3945cfed81a0SChris Mason 		btrfs_set_token_item_offset(right, item, push_space, &token);
3946db94535dSChris Mason 	}
3947eb60ceacSChris Mason 
39485f39d397SChris Mason 	btrfs_mark_buffer_dirty(left);
394934a38218SChris Mason 	if (right_nritems)
39505f39d397SChris Mason 		btrfs_mark_buffer_dirty(right);
3951f0486c68SYan, Zheng 	else
3952*0b246afaSJeff Mahoney 		clean_tree_block(trans, fs_info, right);
3953098f59c2SChris Mason 
39545f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
3955*0b246afaSJeff Mahoney 	fixup_low_keys(fs_info, path, &disk_key, 1);
3956be0e5c09SChris Mason 
3957be0e5c09SChris Mason 	/* then fixup the leaf pointer in the path */
3958be0e5c09SChris Mason 	if (path->slots[0] < push_items) {
3959be0e5c09SChris Mason 		path->slots[0] += old_left_nritems;
3960925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
39615f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
39625f39d397SChris Mason 		path->nodes[0] = left;
3963be0e5c09SChris Mason 		path->slots[1] -= 1;
3964be0e5c09SChris Mason 	} else {
3965925baeddSChris Mason 		btrfs_tree_unlock(left);
39665f39d397SChris Mason 		free_extent_buffer(left);
3967be0e5c09SChris Mason 		path->slots[0] -= push_items;
3968be0e5c09SChris Mason 	}
3969eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
3970aa5d6bedSChris Mason 	return ret;
3971925baeddSChris Mason out:
3972925baeddSChris Mason 	btrfs_tree_unlock(left);
3973925baeddSChris Mason 	free_extent_buffer(left);
3974925baeddSChris Mason 	return ret;
3975be0e5c09SChris Mason }
3976be0e5c09SChris Mason 
397774123bd7SChris Mason /*
397844871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
397944871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
398099d8f83cSChris Mason  *
398199d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
398299d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us push all the
398399d8f83cSChris Mason  * items
398444871b1bSChris Mason  */
398544871b1bSChris Mason static int push_leaf_left(struct btrfs_trans_handle *trans, struct btrfs_root
398699d8f83cSChris Mason 			  *root, struct btrfs_path *path, int min_data_size,
398799d8f83cSChris Mason 			  int data_size, int empty, u32 max_slot)
398844871b1bSChris Mason {
398944871b1bSChris Mason 	struct extent_buffer *right = path->nodes[0];
399044871b1bSChris Mason 	struct extent_buffer *left;
399144871b1bSChris Mason 	int slot;
399244871b1bSChris Mason 	int free_space;
399344871b1bSChris Mason 	u32 right_nritems;
399444871b1bSChris Mason 	int ret = 0;
399544871b1bSChris Mason 
399644871b1bSChris Mason 	slot = path->slots[1];
399744871b1bSChris Mason 	if (slot == 0)
399844871b1bSChris Mason 		return 1;
399944871b1bSChris Mason 	if (!path->nodes[1])
400044871b1bSChris Mason 		return 1;
400144871b1bSChris Mason 
400244871b1bSChris Mason 	right_nritems = btrfs_header_nritems(right);
400344871b1bSChris Mason 	if (right_nritems == 0)
400444871b1bSChris Mason 		return 1;
400544871b1bSChris Mason 
400644871b1bSChris Mason 	btrfs_assert_tree_locked(path->nodes[1]);
400744871b1bSChris Mason 
400844871b1bSChris Mason 	left = read_node_slot(root, path->nodes[1], slot - 1);
4009fb770ae4SLiu Bo 	/*
4010fb770ae4SLiu Bo 	 * slot - 1 is not valid or we fail to read the left node,
4011fb770ae4SLiu Bo 	 * no big deal, just return.
4012fb770ae4SLiu Bo 	 */
4013fb770ae4SLiu Bo 	if (IS_ERR(left))
401491ca338dSTsutomu Itoh 		return 1;
401591ca338dSTsutomu Itoh 
401644871b1bSChris Mason 	btrfs_tree_lock(left);
401744871b1bSChris Mason 	btrfs_set_lock_blocking(left);
401844871b1bSChris Mason 
401944871b1bSChris Mason 	free_space = btrfs_leaf_free_space(root, left);
402044871b1bSChris Mason 	if (free_space < data_size) {
402144871b1bSChris Mason 		ret = 1;
402244871b1bSChris Mason 		goto out;
402344871b1bSChris Mason 	}
402444871b1bSChris Mason 
402544871b1bSChris Mason 	/* cow and double check */
402644871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, left,
402744871b1bSChris Mason 			      path->nodes[1], slot - 1, &left);
402844871b1bSChris Mason 	if (ret) {
402944871b1bSChris Mason 		/* we hit -ENOSPC, but it isn't fatal here */
403079787eaaSJeff Mahoney 		if (ret == -ENOSPC)
403144871b1bSChris Mason 			ret = 1;
403244871b1bSChris Mason 		goto out;
403344871b1bSChris Mason 	}
403444871b1bSChris Mason 
403544871b1bSChris Mason 	free_space = btrfs_leaf_free_space(root, left);
403644871b1bSChris Mason 	if (free_space < data_size) {
403744871b1bSChris Mason 		ret = 1;
403844871b1bSChris Mason 		goto out;
403944871b1bSChris Mason 	}
404044871b1bSChris Mason 
404199d8f83cSChris Mason 	return __push_leaf_left(trans, root, path, min_data_size,
404299d8f83cSChris Mason 			       empty, left, free_space, right_nritems,
404399d8f83cSChris Mason 			       max_slot);
404444871b1bSChris Mason out:
404544871b1bSChris Mason 	btrfs_tree_unlock(left);
404644871b1bSChris Mason 	free_extent_buffer(left);
404744871b1bSChris Mason 	return ret;
404844871b1bSChris Mason }
404944871b1bSChris Mason 
405044871b1bSChris Mason /*
405174123bd7SChris Mason  * split the path's leaf in two, making sure there is at least data_size
405274123bd7SChris Mason  * available for the resulting leaf level of the path.
405374123bd7SChris Mason  */
4054143bede5SJeff Mahoney static noinline void copy_for_split(struct btrfs_trans_handle *trans,
4055e02119d5SChris Mason 				    struct btrfs_root *root,
405644871b1bSChris Mason 				    struct btrfs_path *path,
405744871b1bSChris Mason 				    struct extent_buffer *l,
405844871b1bSChris Mason 				    struct extent_buffer *right,
405944871b1bSChris Mason 				    int slot, int mid, int nritems)
4060be0e5c09SChris Mason {
4061*0b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
4062be0e5c09SChris Mason 	int data_copy_size;
4063be0e5c09SChris Mason 	int rt_data_off;
4064be0e5c09SChris Mason 	int i;
4065d4dbff95SChris Mason 	struct btrfs_disk_key disk_key;
4066cfed81a0SChris Mason 	struct btrfs_map_token token;
4067cfed81a0SChris Mason 
4068cfed81a0SChris Mason 	btrfs_init_map_token(&token);
4069be0e5c09SChris Mason 
40705f39d397SChris Mason 	nritems = nritems - mid;
40715f39d397SChris Mason 	btrfs_set_header_nritems(right, nritems);
40725f39d397SChris Mason 	data_copy_size = btrfs_item_end_nr(l, mid) - leaf_data_end(root, l);
40735f39d397SChris Mason 
40745f39d397SChris Mason 	copy_extent_buffer(right, l, btrfs_item_nr_offset(0),
40755f39d397SChris Mason 			   btrfs_item_nr_offset(mid),
40765f39d397SChris Mason 			   nritems * sizeof(struct btrfs_item));
40775f39d397SChris Mason 
40785f39d397SChris Mason 	copy_extent_buffer(right, l,
4079*0b246afaSJeff Mahoney 		     btrfs_leaf_data(right) + BTRFS_LEAF_DATA_SIZE(fs_info) -
4080123abc88SChris Mason 		     data_copy_size, btrfs_leaf_data(l) +
4081123abc88SChris Mason 		     leaf_data_end(root, l), data_copy_size);
408274123bd7SChris Mason 
4083*0b246afaSJeff Mahoney 	rt_data_off = BTRFS_LEAF_DATA_SIZE(fs_info) - btrfs_item_end_nr(l, mid);
40845f39d397SChris Mason 
40855f39d397SChris Mason 	for (i = 0; i < nritems; i++) {
4086dd3cc16bSRoss Kirk 		struct btrfs_item *item = btrfs_item_nr(i);
4087db94535dSChris Mason 		u32 ioff;
4088db94535dSChris Mason 
4089cfed81a0SChris Mason 		ioff = btrfs_token_item_offset(right, item, &token);
4090cfed81a0SChris Mason 		btrfs_set_token_item_offset(right, item,
4091cfed81a0SChris Mason 					    ioff + rt_data_off, &token);
40920783fcfcSChris Mason 	}
409374123bd7SChris Mason 
40945f39d397SChris Mason 	btrfs_set_header_nritems(l, mid);
40955f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
4096143bede5SJeff Mahoney 	insert_ptr(trans, root, path, &disk_key, right->start,
4097c3e06965SJan Schmidt 		   path->slots[1] + 1, 1);
40985f39d397SChris Mason 
40995f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
41005f39d397SChris Mason 	btrfs_mark_buffer_dirty(l);
4101eb60ceacSChris Mason 	BUG_ON(path->slots[0] != slot);
41025f39d397SChris Mason 
4103be0e5c09SChris Mason 	if (mid <= slot) {
4104925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
41055f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
41065f39d397SChris Mason 		path->nodes[0] = right;
4107be0e5c09SChris Mason 		path->slots[0] -= mid;
4108be0e5c09SChris Mason 		path->slots[1] += 1;
4109925baeddSChris Mason 	} else {
4110925baeddSChris Mason 		btrfs_tree_unlock(right);
41115f39d397SChris Mason 		free_extent_buffer(right);
4112925baeddSChris Mason 	}
41135f39d397SChris Mason 
4114eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
411544871b1bSChris Mason }
411644871b1bSChris Mason 
411744871b1bSChris Mason /*
411899d8f83cSChris Mason  * double splits happen when we need to insert a big item in the middle
411999d8f83cSChris Mason  * of a leaf.  A double split can leave us with 3 mostly empty leaves:
412099d8f83cSChris Mason  * leaf: [ slots 0 - N] [ our target ] [ N + 1 - total in leaf ]
412199d8f83cSChris Mason  *          A                 B                 C
412299d8f83cSChris Mason  *
412399d8f83cSChris Mason  * We avoid this by trying to push the items on either side of our target
412499d8f83cSChris Mason  * into the adjacent leaves.  If all goes well we can avoid the double split
412599d8f83cSChris Mason  * completely.
412699d8f83cSChris Mason  */
412799d8f83cSChris Mason static noinline int push_for_double_split(struct btrfs_trans_handle *trans,
412899d8f83cSChris Mason 					  struct btrfs_root *root,
412999d8f83cSChris Mason 					  struct btrfs_path *path,
413099d8f83cSChris Mason 					  int data_size)
413199d8f83cSChris Mason {
413299d8f83cSChris Mason 	int ret;
413399d8f83cSChris Mason 	int progress = 0;
413499d8f83cSChris Mason 	int slot;
413599d8f83cSChris Mason 	u32 nritems;
41365a4267caSFilipe David Borba Manana 	int space_needed = data_size;
413799d8f83cSChris Mason 
413899d8f83cSChris Mason 	slot = path->slots[0];
41395a4267caSFilipe David Borba Manana 	if (slot < btrfs_header_nritems(path->nodes[0]))
41405a4267caSFilipe David Borba Manana 		space_needed -= btrfs_leaf_free_space(root, path->nodes[0]);
414199d8f83cSChris Mason 
414299d8f83cSChris Mason 	/*
414399d8f83cSChris Mason 	 * try to push all the items after our slot into the
414499d8f83cSChris Mason 	 * right leaf
414599d8f83cSChris Mason 	 */
41465a4267caSFilipe David Borba Manana 	ret = push_leaf_right(trans, root, path, 1, space_needed, 0, slot);
414799d8f83cSChris Mason 	if (ret < 0)
414899d8f83cSChris Mason 		return ret;
414999d8f83cSChris Mason 
415099d8f83cSChris Mason 	if (ret == 0)
415199d8f83cSChris Mason 		progress++;
415299d8f83cSChris Mason 
415399d8f83cSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
415499d8f83cSChris Mason 	/*
415599d8f83cSChris Mason 	 * our goal is to get our slot at the start or end of a leaf.  If
415699d8f83cSChris Mason 	 * we've done so we're done
415799d8f83cSChris Mason 	 */
415899d8f83cSChris Mason 	if (path->slots[0] == 0 || path->slots[0] == nritems)
415999d8f83cSChris Mason 		return 0;
416099d8f83cSChris Mason 
416199d8f83cSChris Mason 	if (btrfs_leaf_free_space(root, path->nodes[0]) >= data_size)
416299d8f83cSChris Mason 		return 0;
416399d8f83cSChris Mason 
416499d8f83cSChris Mason 	/* try to push all the items before our slot into the next leaf */
416599d8f83cSChris Mason 	slot = path->slots[0];
41665a4267caSFilipe David Borba Manana 	ret = push_leaf_left(trans, root, path, 1, space_needed, 0, slot);
416799d8f83cSChris Mason 	if (ret < 0)
416899d8f83cSChris Mason 		return ret;
416999d8f83cSChris Mason 
417099d8f83cSChris Mason 	if (ret == 0)
417199d8f83cSChris Mason 		progress++;
417299d8f83cSChris Mason 
417399d8f83cSChris Mason 	if (progress)
417499d8f83cSChris Mason 		return 0;
417599d8f83cSChris Mason 	return 1;
417699d8f83cSChris Mason }
417799d8f83cSChris Mason 
417899d8f83cSChris Mason /*
417944871b1bSChris Mason  * split the path's leaf in two, making sure there is at least data_size
418044871b1bSChris Mason  * available for the resulting leaf level of the path.
418144871b1bSChris Mason  *
418244871b1bSChris Mason  * returns 0 if all went well and < 0 on failure.
418344871b1bSChris Mason  */
418444871b1bSChris Mason static noinline int split_leaf(struct btrfs_trans_handle *trans,
418544871b1bSChris Mason 			       struct btrfs_root *root,
418644871b1bSChris Mason 			       struct btrfs_key *ins_key,
418744871b1bSChris Mason 			       struct btrfs_path *path, int data_size,
418844871b1bSChris Mason 			       int extend)
418944871b1bSChris Mason {
41905d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
419144871b1bSChris Mason 	struct extent_buffer *l;
419244871b1bSChris Mason 	u32 nritems;
419344871b1bSChris Mason 	int mid;
419444871b1bSChris Mason 	int slot;
419544871b1bSChris Mason 	struct extent_buffer *right;
4196b7a0365eSDaniel Dressler 	struct btrfs_fs_info *fs_info = root->fs_info;
419744871b1bSChris Mason 	int ret = 0;
419844871b1bSChris Mason 	int wret;
41995d4f98a2SYan Zheng 	int split;
420044871b1bSChris Mason 	int num_doubles = 0;
420199d8f83cSChris Mason 	int tried_avoid_double = 0;
420244871b1bSChris Mason 
4203a5719521SYan, Zheng 	l = path->nodes[0];
4204a5719521SYan, Zheng 	slot = path->slots[0];
4205a5719521SYan, Zheng 	if (extend && data_size + btrfs_item_size_nr(l, slot) +
4206*0b246afaSJeff Mahoney 	    sizeof(struct btrfs_item) > BTRFS_LEAF_DATA_SIZE(fs_info))
4207a5719521SYan, Zheng 		return -EOVERFLOW;
4208a5719521SYan, Zheng 
420944871b1bSChris Mason 	/* first try to make some room by pushing left and right */
421033157e05SLiu Bo 	if (data_size && path->nodes[1]) {
42115a4267caSFilipe David Borba Manana 		int space_needed = data_size;
42125a4267caSFilipe David Borba Manana 
42135a4267caSFilipe David Borba Manana 		if (slot < btrfs_header_nritems(l))
42145a4267caSFilipe David Borba Manana 			space_needed -= btrfs_leaf_free_space(root, l);
42155a4267caSFilipe David Borba Manana 
42165a4267caSFilipe David Borba Manana 		wret = push_leaf_right(trans, root, path, space_needed,
42175a4267caSFilipe David Borba Manana 				       space_needed, 0, 0);
421844871b1bSChris Mason 		if (wret < 0)
421944871b1bSChris Mason 			return wret;
422044871b1bSChris Mason 		if (wret) {
42215a4267caSFilipe David Borba Manana 			wret = push_leaf_left(trans, root, path, space_needed,
42225a4267caSFilipe David Borba Manana 					      space_needed, 0, (u32)-1);
422344871b1bSChris Mason 			if (wret < 0)
422444871b1bSChris Mason 				return wret;
422544871b1bSChris Mason 		}
422644871b1bSChris Mason 		l = path->nodes[0];
422744871b1bSChris Mason 
422844871b1bSChris Mason 		/* did the pushes work? */
422944871b1bSChris Mason 		if (btrfs_leaf_free_space(root, l) >= data_size)
423044871b1bSChris Mason 			return 0;
423144871b1bSChris Mason 	}
423244871b1bSChris Mason 
423344871b1bSChris Mason 	if (!path->nodes[1]) {
4234fdd99c72SLiu Bo 		ret = insert_new_root(trans, root, path, 1);
423544871b1bSChris Mason 		if (ret)
423644871b1bSChris Mason 			return ret;
423744871b1bSChris Mason 	}
423844871b1bSChris Mason again:
42395d4f98a2SYan Zheng 	split = 1;
424044871b1bSChris Mason 	l = path->nodes[0];
424144871b1bSChris Mason 	slot = path->slots[0];
424244871b1bSChris Mason 	nritems = btrfs_header_nritems(l);
424344871b1bSChris Mason 	mid = (nritems + 1) / 2;
424444871b1bSChris Mason 
42455d4f98a2SYan Zheng 	if (mid <= slot) {
42465d4f98a2SYan Zheng 		if (nritems == 1 ||
42475d4f98a2SYan Zheng 		    leaf_space_used(l, mid, nritems - mid) + data_size >
4248*0b246afaSJeff Mahoney 			BTRFS_LEAF_DATA_SIZE(fs_info)) {
42495d4f98a2SYan Zheng 			if (slot >= nritems) {
42505d4f98a2SYan Zheng 				split = 0;
42515d4f98a2SYan Zheng 			} else {
42525d4f98a2SYan Zheng 				mid = slot;
42535d4f98a2SYan Zheng 				if (mid != nritems &&
42545d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
4255*0b246afaSJeff Mahoney 				    data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
425699d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
425799d8f83cSChris Mason 						goto push_for_double;
42585d4f98a2SYan Zheng 					split = 2;
42595d4f98a2SYan Zheng 				}
42605d4f98a2SYan Zheng 			}
42615d4f98a2SYan Zheng 		}
42625d4f98a2SYan Zheng 	} else {
42635d4f98a2SYan Zheng 		if (leaf_space_used(l, 0, mid) + data_size >
4264*0b246afaSJeff Mahoney 			BTRFS_LEAF_DATA_SIZE(fs_info)) {
42655d4f98a2SYan Zheng 			if (!extend && data_size && slot == 0) {
42665d4f98a2SYan Zheng 				split = 0;
42675d4f98a2SYan Zheng 			} else if ((extend || !data_size) && slot == 0) {
42685d4f98a2SYan Zheng 				mid = 1;
42695d4f98a2SYan Zheng 			} else {
42705d4f98a2SYan Zheng 				mid = slot;
42715d4f98a2SYan Zheng 				if (mid != nritems &&
42725d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
4273*0b246afaSJeff Mahoney 				    data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
427499d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
427599d8f83cSChris Mason 						goto push_for_double;
42765d4f98a2SYan Zheng 					split = 2;
42775d4f98a2SYan Zheng 				}
42785d4f98a2SYan Zheng 			}
42795d4f98a2SYan Zheng 		}
42805d4f98a2SYan Zheng 	}
42815d4f98a2SYan Zheng 
42825d4f98a2SYan Zheng 	if (split == 0)
42835d4f98a2SYan Zheng 		btrfs_cpu_key_to_disk(&disk_key, ins_key);
42845d4f98a2SYan Zheng 	else
42855d4f98a2SYan Zheng 		btrfs_item_key(l, &disk_key, mid);
42865d4f98a2SYan Zheng 
42874d75f8a9SDavid Sterba 	right = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
42885581a51aSJan Schmidt 			&disk_key, 0, l->start, 0);
4289f0486c68SYan, Zheng 	if (IS_ERR(right))
429044871b1bSChris Mason 		return PTR_ERR(right);
4291f0486c68SYan, Zheng 
4292*0b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
429344871b1bSChris Mason 
4294b159fa28SDavid Sterba 	memzero_extent_buffer(right, 0, sizeof(struct btrfs_header));
429544871b1bSChris Mason 	btrfs_set_header_bytenr(right, right->start);
429644871b1bSChris Mason 	btrfs_set_header_generation(right, trans->transid);
42975d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(right, BTRFS_MIXED_BACKREF_REV);
429844871b1bSChris Mason 	btrfs_set_header_owner(right, root->root_key.objectid);
429944871b1bSChris Mason 	btrfs_set_header_level(right, 0);
4300d24ee97bSDavid Sterba 	write_extent_buffer_fsid(right, fs_info->fsid);
4301d24ee97bSDavid Sterba 	write_extent_buffer_chunk_tree_uuid(right, fs_info->chunk_tree_uuid);
430244871b1bSChris Mason 
43035d4f98a2SYan Zheng 	if (split == 0) {
430444871b1bSChris Mason 		if (mid <= slot) {
430544871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
4306143bede5SJeff Mahoney 			insert_ptr(trans, root, path, &disk_key, right->start,
4307c3e06965SJan Schmidt 				   path->slots[1] + 1, 1);
430844871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
430944871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
431044871b1bSChris Mason 			path->nodes[0] = right;
431144871b1bSChris Mason 			path->slots[0] = 0;
431244871b1bSChris Mason 			path->slots[1] += 1;
431344871b1bSChris Mason 		} else {
431444871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
4315143bede5SJeff Mahoney 			insert_ptr(trans, root, path, &disk_key, right->start,
4316c3e06965SJan Schmidt 					  path->slots[1], 1);
431744871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
431844871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
431944871b1bSChris Mason 			path->nodes[0] = right;
432044871b1bSChris Mason 			path->slots[0] = 0;
4321143bede5SJeff Mahoney 			if (path->slots[1] == 0)
4322b7a0365eSDaniel Dressler 				fixup_low_keys(fs_info, path, &disk_key, 1);
43235d4f98a2SYan Zheng 		}
4324196e0249SLiu Bo 		/*
4325196e0249SLiu Bo 		 * We create a new leaf 'right' for the required ins_len and
4326196e0249SLiu Bo 		 * we'll do btrfs_mark_buffer_dirty() on this leaf after copying
4327196e0249SLiu Bo 		 * the content of ins_len to 'right'.
4328196e0249SLiu Bo 		 */
432944871b1bSChris Mason 		return ret;
433044871b1bSChris Mason 	}
433144871b1bSChris Mason 
4332143bede5SJeff Mahoney 	copy_for_split(trans, root, path, l, right, slot, mid, nritems);
433344871b1bSChris Mason 
43345d4f98a2SYan Zheng 	if (split == 2) {
4335cc0c5538SChris Mason 		BUG_ON(num_doubles != 0);
4336cc0c5538SChris Mason 		num_doubles++;
4337cc0c5538SChris Mason 		goto again;
43383326d1b0SChris Mason 	}
433944871b1bSChris Mason 
4340143bede5SJeff Mahoney 	return 0;
434199d8f83cSChris Mason 
434299d8f83cSChris Mason push_for_double:
434399d8f83cSChris Mason 	push_for_double_split(trans, root, path, data_size);
434499d8f83cSChris Mason 	tried_avoid_double = 1;
434599d8f83cSChris Mason 	if (btrfs_leaf_free_space(root, path->nodes[0]) >= data_size)
434699d8f83cSChris Mason 		return 0;
434799d8f83cSChris Mason 	goto again;
4348be0e5c09SChris Mason }
4349be0e5c09SChris Mason 
4350ad48fd75SYan, Zheng static noinline int setup_leaf_for_split(struct btrfs_trans_handle *trans,
4351ad48fd75SYan, Zheng 					 struct btrfs_root *root,
4352ad48fd75SYan, Zheng 					 struct btrfs_path *path, int ins_len)
4353ad48fd75SYan, Zheng {
4354ad48fd75SYan, Zheng 	struct btrfs_key key;
4355ad48fd75SYan, Zheng 	struct extent_buffer *leaf;
4356ad48fd75SYan, Zheng 	struct btrfs_file_extent_item *fi;
4357ad48fd75SYan, Zheng 	u64 extent_len = 0;
4358ad48fd75SYan, Zheng 	u32 item_size;
4359ad48fd75SYan, Zheng 	int ret;
4360ad48fd75SYan, Zheng 
4361ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4362ad48fd75SYan, Zheng 	btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4363ad48fd75SYan, Zheng 
4364ad48fd75SYan, Zheng 	BUG_ON(key.type != BTRFS_EXTENT_DATA_KEY &&
4365ad48fd75SYan, Zheng 	       key.type != BTRFS_EXTENT_CSUM_KEY);
4366ad48fd75SYan, Zheng 
4367ad48fd75SYan, Zheng 	if (btrfs_leaf_free_space(root, leaf) >= ins_len)
4368ad48fd75SYan, Zheng 		return 0;
4369ad48fd75SYan, Zheng 
4370ad48fd75SYan, Zheng 	item_size = btrfs_item_size_nr(leaf, path->slots[0]);
4371ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
4372ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
4373ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
4374ad48fd75SYan, Zheng 		extent_len = btrfs_file_extent_num_bytes(leaf, fi);
4375ad48fd75SYan, Zheng 	}
4376b3b4aa74SDavid Sterba 	btrfs_release_path(path);
4377ad48fd75SYan, Zheng 
4378ad48fd75SYan, Zheng 	path->keep_locks = 1;
4379ad48fd75SYan, Zheng 	path->search_for_split = 1;
4380ad48fd75SYan, Zheng 	ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
4381ad48fd75SYan, Zheng 	path->search_for_split = 0;
4382a8df6fe6SFilipe Manana 	if (ret > 0)
4383a8df6fe6SFilipe Manana 		ret = -EAGAIN;
4384ad48fd75SYan, Zheng 	if (ret < 0)
4385ad48fd75SYan, Zheng 		goto err;
4386ad48fd75SYan, Zheng 
4387ad48fd75SYan, Zheng 	ret = -EAGAIN;
4388ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4389a8df6fe6SFilipe Manana 	/* if our item isn't there, return now */
4390a8df6fe6SFilipe Manana 	if (item_size != btrfs_item_size_nr(leaf, path->slots[0]))
4391ad48fd75SYan, Zheng 		goto err;
4392ad48fd75SYan, Zheng 
4393109f6aefSChris Mason 	/* the leaf has  changed, it now has room.  return now */
4394109f6aefSChris Mason 	if (btrfs_leaf_free_space(root, path->nodes[0]) >= ins_len)
4395109f6aefSChris Mason 		goto err;
4396109f6aefSChris Mason 
4397ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
4398ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
4399ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
4400ad48fd75SYan, Zheng 		if (extent_len != btrfs_file_extent_num_bytes(leaf, fi))
4401ad48fd75SYan, Zheng 			goto err;
4402ad48fd75SYan, Zheng 	}
4403ad48fd75SYan, Zheng 
4404ad48fd75SYan, Zheng 	btrfs_set_path_blocking(path);
4405ad48fd75SYan, Zheng 	ret = split_leaf(trans, root, &key, path, ins_len, 1);
4406f0486c68SYan, Zheng 	if (ret)
4407f0486c68SYan, Zheng 		goto err;
4408ad48fd75SYan, Zheng 
4409ad48fd75SYan, Zheng 	path->keep_locks = 0;
4410ad48fd75SYan, Zheng 	btrfs_unlock_up_safe(path, 1);
4411ad48fd75SYan, Zheng 	return 0;
4412ad48fd75SYan, Zheng err:
4413ad48fd75SYan, Zheng 	path->keep_locks = 0;
4414ad48fd75SYan, Zheng 	return ret;
4415ad48fd75SYan, Zheng }
4416ad48fd75SYan, Zheng 
4417ad48fd75SYan, Zheng static noinline int split_item(struct btrfs_trans_handle *trans,
4418459931ecSChris Mason 			       struct btrfs_root *root,
4419459931ecSChris Mason 			       struct btrfs_path *path,
4420459931ecSChris Mason 			       struct btrfs_key *new_key,
4421459931ecSChris Mason 			       unsigned long split_offset)
4422459931ecSChris Mason {
4423459931ecSChris Mason 	struct extent_buffer *leaf;
4424459931ecSChris Mason 	struct btrfs_item *item;
4425459931ecSChris Mason 	struct btrfs_item *new_item;
4426459931ecSChris Mason 	int slot;
4427ad48fd75SYan, Zheng 	char *buf;
4428459931ecSChris Mason 	u32 nritems;
4429ad48fd75SYan, Zheng 	u32 item_size;
4430459931ecSChris Mason 	u32 orig_offset;
4431459931ecSChris Mason 	struct btrfs_disk_key disk_key;
4432459931ecSChris Mason 
4433459931ecSChris Mason 	leaf = path->nodes[0];
4434b9473439SChris Mason 	BUG_ON(btrfs_leaf_free_space(root, leaf) < sizeof(struct btrfs_item));
4435b9473439SChris Mason 
4436b4ce94deSChris Mason 	btrfs_set_path_blocking(path);
4437b4ce94deSChris Mason 
4438dd3cc16bSRoss Kirk 	item = btrfs_item_nr(path->slots[0]);
4439459931ecSChris Mason 	orig_offset = btrfs_item_offset(leaf, item);
4440459931ecSChris Mason 	item_size = btrfs_item_size(leaf, item);
4441459931ecSChris Mason 
4442459931ecSChris Mason 	buf = kmalloc(item_size, GFP_NOFS);
4443ad48fd75SYan, Zheng 	if (!buf)
4444ad48fd75SYan, Zheng 		return -ENOMEM;
4445ad48fd75SYan, Zheng 
4446459931ecSChris Mason 	read_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf,
4447459931ecSChris Mason 			    path->slots[0]), item_size);
4448ad48fd75SYan, Zheng 
4449459931ecSChris Mason 	slot = path->slots[0] + 1;
4450459931ecSChris Mason 	nritems = btrfs_header_nritems(leaf);
4451459931ecSChris Mason 	if (slot != nritems) {
4452459931ecSChris Mason 		/* shift the items */
4453459931ecSChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + 1),
4454459931ecSChris Mason 				btrfs_item_nr_offset(slot),
4455459931ecSChris Mason 				(nritems - slot) * sizeof(struct btrfs_item));
4456459931ecSChris Mason 	}
4457459931ecSChris Mason 
4458459931ecSChris Mason 	btrfs_cpu_key_to_disk(&disk_key, new_key);
4459459931ecSChris Mason 	btrfs_set_item_key(leaf, &disk_key, slot);
4460459931ecSChris Mason 
4461dd3cc16bSRoss Kirk 	new_item = btrfs_item_nr(slot);
4462459931ecSChris Mason 
4463459931ecSChris Mason 	btrfs_set_item_offset(leaf, new_item, orig_offset);
4464459931ecSChris Mason 	btrfs_set_item_size(leaf, new_item, item_size - split_offset);
4465459931ecSChris Mason 
4466459931ecSChris Mason 	btrfs_set_item_offset(leaf, item,
4467459931ecSChris Mason 			      orig_offset + item_size - split_offset);
4468459931ecSChris Mason 	btrfs_set_item_size(leaf, item, split_offset);
4469459931ecSChris Mason 
4470459931ecSChris Mason 	btrfs_set_header_nritems(leaf, nritems + 1);
4471459931ecSChris Mason 
4472459931ecSChris Mason 	/* write the data for the start of the original item */
4473459931ecSChris Mason 	write_extent_buffer(leaf, buf,
4474459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, path->slots[0]),
4475459931ecSChris Mason 			    split_offset);
4476459931ecSChris Mason 
4477459931ecSChris Mason 	/* write the data for the new item */
4478459931ecSChris Mason 	write_extent_buffer(leaf, buf + split_offset,
4479459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, slot),
4480459931ecSChris Mason 			    item_size - split_offset);
4481459931ecSChris Mason 	btrfs_mark_buffer_dirty(leaf);
4482459931ecSChris Mason 
4483ad48fd75SYan, Zheng 	BUG_ON(btrfs_leaf_free_space(root, leaf) < 0);
4484459931ecSChris Mason 	kfree(buf);
4485ad48fd75SYan, Zheng 	return 0;
4486ad48fd75SYan, Zheng }
4487ad48fd75SYan, Zheng 
4488ad48fd75SYan, Zheng /*
4489ad48fd75SYan, Zheng  * This function splits a single item into two items,
4490ad48fd75SYan, Zheng  * giving 'new_key' to the new item and splitting the
4491ad48fd75SYan, Zheng  * old one at split_offset (from the start of the item).
4492ad48fd75SYan, Zheng  *
4493ad48fd75SYan, Zheng  * The path may be released by this operation.  After
4494ad48fd75SYan, Zheng  * the split, the path is pointing to the old item.  The
4495ad48fd75SYan, Zheng  * new item is going to be in the same node as the old one.
4496ad48fd75SYan, Zheng  *
4497ad48fd75SYan, Zheng  * Note, the item being split must be smaller enough to live alone on
4498ad48fd75SYan, Zheng  * a tree block with room for one extra struct btrfs_item
4499ad48fd75SYan, Zheng  *
4500ad48fd75SYan, Zheng  * This allows us to split the item in place, keeping a lock on the
4501ad48fd75SYan, Zheng  * leaf the entire time.
4502ad48fd75SYan, Zheng  */
4503ad48fd75SYan, Zheng int btrfs_split_item(struct btrfs_trans_handle *trans,
4504ad48fd75SYan, Zheng 		     struct btrfs_root *root,
4505ad48fd75SYan, Zheng 		     struct btrfs_path *path,
4506ad48fd75SYan, Zheng 		     struct btrfs_key *new_key,
4507ad48fd75SYan, Zheng 		     unsigned long split_offset)
4508ad48fd75SYan, Zheng {
4509ad48fd75SYan, Zheng 	int ret;
4510ad48fd75SYan, Zheng 	ret = setup_leaf_for_split(trans, root, path,
4511ad48fd75SYan, Zheng 				   sizeof(struct btrfs_item));
4512ad48fd75SYan, Zheng 	if (ret)
4513459931ecSChris Mason 		return ret;
4514ad48fd75SYan, Zheng 
4515ad48fd75SYan, Zheng 	ret = split_item(trans, root, path, new_key, split_offset);
4516ad48fd75SYan, Zheng 	return ret;
4517ad48fd75SYan, Zheng }
4518ad48fd75SYan, Zheng 
4519ad48fd75SYan, Zheng /*
4520ad48fd75SYan, Zheng  * This function duplicate a item, giving 'new_key' to the new item.
4521ad48fd75SYan, Zheng  * It guarantees both items live in the same tree leaf and the new item
4522ad48fd75SYan, Zheng  * is contiguous with the original item.
4523ad48fd75SYan, Zheng  *
4524ad48fd75SYan, Zheng  * This allows us to split file extent in place, keeping a lock on the
4525ad48fd75SYan, Zheng  * leaf the entire time.
4526ad48fd75SYan, Zheng  */
4527ad48fd75SYan, Zheng int btrfs_duplicate_item(struct btrfs_trans_handle *trans,
4528ad48fd75SYan, Zheng 			 struct btrfs_root *root,
4529ad48fd75SYan, Zheng 			 struct btrfs_path *path,
4530ad48fd75SYan, Zheng 			 struct btrfs_key *new_key)
4531ad48fd75SYan, Zheng {
4532ad48fd75SYan, Zheng 	struct extent_buffer *leaf;
4533ad48fd75SYan, Zheng 	int ret;
4534ad48fd75SYan, Zheng 	u32 item_size;
4535ad48fd75SYan, Zheng 
4536ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4537ad48fd75SYan, Zheng 	item_size = btrfs_item_size_nr(leaf, path->slots[0]);
4538ad48fd75SYan, Zheng 	ret = setup_leaf_for_split(trans, root, path,
4539ad48fd75SYan, Zheng 				   item_size + sizeof(struct btrfs_item));
4540ad48fd75SYan, Zheng 	if (ret)
4541ad48fd75SYan, Zheng 		return ret;
4542ad48fd75SYan, Zheng 
4543ad48fd75SYan, Zheng 	path->slots[0]++;
4544afe5fea7STsutomu Itoh 	setup_items_for_insert(root, path, new_key, &item_size,
4545ad48fd75SYan, Zheng 			       item_size, item_size +
4546ad48fd75SYan, Zheng 			       sizeof(struct btrfs_item), 1);
4547ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4548ad48fd75SYan, Zheng 	memcpy_extent_buffer(leaf,
4549ad48fd75SYan, Zheng 			     btrfs_item_ptr_offset(leaf, path->slots[0]),
4550ad48fd75SYan, Zheng 			     btrfs_item_ptr_offset(leaf, path->slots[0] - 1),
4551ad48fd75SYan, Zheng 			     item_size);
4552ad48fd75SYan, Zheng 	return 0;
4553459931ecSChris Mason }
4554459931ecSChris Mason 
4555459931ecSChris Mason /*
4556d352ac68SChris Mason  * make the item pointed to by the path smaller.  new_size indicates
4557d352ac68SChris Mason  * how small to make it, and from_end tells us if we just chop bytes
4558d352ac68SChris Mason  * off the end of the item or if we shift the item to chop bytes off
4559d352ac68SChris Mason  * the front.
4560d352ac68SChris Mason  */
4561afe5fea7STsutomu Itoh void btrfs_truncate_item(struct btrfs_root *root, struct btrfs_path *path,
4562179e29e4SChris Mason 			 u32 new_size, int from_end)
4563b18c6685SChris Mason {
4564*0b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
4565b18c6685SChris Mason 	int slot;
45665f39d397SChris Mason 	struct extent_buffer *leaf;
45675f39d397SChris Mason 	struct btrfs_item *item;
4568b18c6685SChris Mason 	u32 nritems;
4569b18c6685SChris Mason 	unsigned int data_end;
4570b18c6685SChris Mason 	unsigned int old_data_start;
4571b18c6685SChris Mason 	unsigned int old_size;
4572b18c6685SChris Mason 	unsigned int size_diff;
4573b18c6685SChris Mason 	int i;
4574cfed81a0SChris Mason 	struct btrfs_map_token token;
4575cfed81a0SChris Mason 
4576cfed81a0SChris Mason 	btrfs_init_map_token(&token);
4577b18c6685SChris Mason 
45785f39d397SChris Mason 	leaf = path->nodes[0];
4579179e29e4SChris Mason 	slot = path->slots[0];
4580179e29e4SChris Mason 
4581179e29e4SChris Mason 	old_size = btrfs_item_size_nr(leaf, slot);
4582179e29e4SChris Mason 	if (old_size == new_size)
4583143bede5SJeff Mahoney 		return;
4584b18c6685SChris Mason 
45855f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
4586b18c6685SChris Mason 	data_end = leaf_data_end(root, leaf);
4587b18c6685SChris Mason 
45885f39d397SChris Mason 	old_data_start = btrfs_item_offset_nr(leaf, slot);
4589179e29e4SChris Mason 
4590b18c6685SChris Mason 	size_diff = old_size - new_size;
4591b18c6685SChris Mason 
4592b18c6685SChris Mason 	BUG_ON(slot < 0);
4593b18c6685SChris Mason 	BUG_ON(slot >= nritems);
4594b18c6685SChris Mason 
4595b18c6685SChris Mason 	/*
4596b18c6685SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4597b18c6685SChris Mason 	 */
4598b18c6685SChris Mason 	/* first correct the data pointers */
4599b18c6685SChris Mason 	for (i = slot; i < nritems; i++) {
46005f39d397SChris Mason 		u32 ioff;
4601dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
4602db94535dSChris Mason 
4603cfed81a0SChris Mason 		ioff = btrfs_token_item_offset(leaf, item, &token);
4604cfed81a0SChris Mason 		btrfs_set_token_item_offset(leaf, item,
4605cfed81a0SChris Mason 					    ioff + size_diff, &token);
4606b18c6685SChris Mason 	}
4607db94535dSChris Mason 
4608b18c6685SChris Mason 	/* shift the data */
4609179e29e4SChris Mason 	if (from_end) {
46105f39d397SChris Mason 		memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
4611b18c6685SChris Mason 			      data_end + size_diff, btrfs_leaf_data(leaf) +
4612b18c6685SChris Mason 			      data_end, old_data_start + new_size - data_end);
4613179e29e4SChris Mason 	} else {
4614179e29e4SChris Mason 		struct btrfs_disk_key disk_key;
4615179e29e4SChris Mason 		u64 offset;
4616179e29e4SChris Mason 
4617179e29e4SChris Mason 		btrfs_item_key(leaf, &disk_key, slot);
4618179e29e4SChris Mason 
4619179e29e4SChris Mason 		if (btrfs_disk_key_type(&disk_key) == BTRFS_EXTENT_DATA_KEY) {
4620179e29e4SChris Mason 			unsigned long ptr;
4621179e29e4SChris Mason 			struct btrfs_file_extent_item *fi;
4622179e29e4SChris Mason 
4623179e29e4SChris Mason 			fi = btrfs_item_ptr(leaf, slot,
4624179e29e4SChris Mason 					    struct btrfs_file_extent_item);
4625179e29e4SChris Mason 			fi = (struct btrfs_file_extent_item *)(
4626179e29e4SChris Mason 			     (unsigned long)fi - size_diff);
4627179e29e4SChris Mason 
4628179e29e4SChris Mason 			if (btrfs_file_extent_type(leaf, fi) ==
4629179e29e4SChris Mason 			    BTRFS_FILE_EXTENT_INLINE) {
4630179e29e4SChris Mason 				ptr = btrfs_item_ptr_offset(leaf, slot);
4631179e29e4SChris Mason 				memmove_extent_buffer(leaf, ptr,
4632179e29e4SChris Mason 				      (unsigned long)fi,
46337ec20afbSDavid Sterba 				      BTRFS_FILE_EXTENT_INLINE_DATA_START);
4634179e29e4SChris Mason 			}
4635179e29e4SChris Mason 		}
4636179e29e4SChris Mason 
4637179e29e4SChris Mason 		memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
4638179e29e4SChris Mason 			      data_end + size_diff, btrfs_leaf_data(leaf) +
4639179e29e4SChris Mason 			      data_end, old_data_start - data_end);
4640179e29e4SChris Mason 
4641179e29e4SChris Mason 		offset = btrfs_disk_key_offset(&disk_key);
4642179e29e4SChris Mason 		btrfs_set_disk_key_offset(&disk_key, offset + size_diff);
4643179e29e4SChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot);
4644179e29e4SChris Mason 		if (slot == 0)
4645*0b246afaSJeff Mahoney 			fixup_low_keys(fs_info, path, &disk_key, 1);
4646179e29e4SChris Mason 	}
46475f39d397SChris Mason 
4648dd3cc16bSRoss Kirk 	item = btrfs_item_nr(slot);
46495f39d397SChris Mason 	btrfs_set_item_size(leaf, item, new_size);
46505f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
4651b18c6685SChris Mason 
46525f39d397SChris Mason 	if (btrfs_leaf_free_space(root, leaf) < 0) {
46535f39d397SChris Mason 		btrfs_print_leaf(root, leaf);
4654b18c6685SChris Mason 		BUG();
46555f39d397SChris Mason 	}
4656b18c6685SChris Mason }
4657b18c6685SChris Mason 
4658d352ac68SChris Mason /*
46598f69dbd2SStefan Behrens  * make the item pointed to by the path bigger, data_size is the added size.
4660d352ac68SChris Mason  */
46614b90c680STsutomu Itoh void btrfs_extend_item(struct btrfs_root *root, struct btrfs_path *path,
46625f39d397SChris Mason 		       u32 data_size)
46636567e837SChris Mason {
4664*0b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
46656567e837SChris Mason 	int slot;
46665f39d397SChris Mason 	struct extent_buffer *leaf;
46675f39d397SChris Mason 	struct btrfs_item *item;
46686567e837SChris Mason 	u32 nritems;
46696567e837SChris Mason 	unsigned int data_end;
46706567e837SChris Mason 	unsigned int old_data;
46716567e837SChris Mason 	unsigned int old_size;
46726567e837SChris Mason 	int i;
4673cfed81a0SChris Mason 	struct btrfs_map_token token;
4674cfed81a0SChris Mason 
4675cfed81a0SChris Mason 	btrfs_init_map_token(&token);
46766567e837SChris Mason 
46775f39d397SChris Mason 	leaf = path->nodes[0];
46786567e837SChris Mason 
46795f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
46806567e837SChris Mason 	data_end = leaf_data_end(root, leaf);
46816567e837SChris Mason 
46825f39d397SChris Mason 	if (btrfs_leaf_free_space(root, leaf) < data_size) {
46835f39d397SChris Mason 		btrfs_print_leaf(root, leaf);
46846567e837SChris Mason 		BUG();
46855f39d397SChris Mason 	}
46866567e837SChris Mason 	slot = path->slots[0];
46875f39d397SChris Mason 	old_data = btrfs_item_end_nr(leaf, slot);
46886567e837SChris Mason 
46896567e837SChris Mason 	BUG_ON(slot < 0);
46903326d1b0SChris Mason 	if (slot >= nritems) {
46913326d1b0SChris Mason 		btrfs_print_leaf(root, leaf);
4692*0b246afaSJeff Mahoney 		btrfs_crit(fs_info, "slot %d too large, nritems %d",
4693d397712bSChris Mason 			   slot, nritems);
46943326d1b0SChris Mason 		BUG_ON(1);
46953326d1b0SChris Mason 	}
46966567e837SChris Mason 
46976567e837SChris Mason 	/*
46986567e837SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
46996567e837SChris Mason 	 */
47006567e837SChris Mason 	/* first correct the data pointers */
47016567e837SChris Mason 	for (i = slot; i < nritems; i++) {
47025f39d397SChris Mason 		u32 ioff;
4703dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
4704db94535dSChris Mason 
4705cfed81a0SChris Mason 		ioff = btrfs_token_item_offset(leaf, item, &token);
4706cfed81a0SChris Mason 		btrfs_set_token_item_offset(leaf, item,
4707cfed81a0SChris Mason 					    ioff - data_size, &token);
47086567e837SChris Mason 	}
47095f39d397SChris Mason 
47106567e837SChris Mason 	/* shift the data */
47115f39d397SChris Mason 	memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
47126567e837SChris Mason 		      data_end - data_size, btrfs_leaf_data(leaf) +
47136567e837SChris Mason 		      data_end, old_data - data_end);
47145f39d397SChris Mason 
47156567e837SChris Mason 	data_end = old_data;
47165f39d397SChris Mason 	old_size = btrfs_item_size_nr(leaf, slot);
4717dd3cc16bSRoss Kirk 	item = btrfs_item_nr(slot);
47185f39d397SChris Mason 	btrfs_set_item_size(leaf, item, old_size + data_size);
47195f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
47206567e837SChris Mason 
47215f39d397SChris Mason 	if (btrfs_leaf_free_space(root, leaf) < 0) {
47225f39d397SChris Mason 		btrfs_print_leaf(root, leaf);
47236567e837SChris Mason 		BUG();
47245f39d397SChris Mason 	}
47256567e837SChris Mason }
47266567e837SChris Mason 
472774123bd7SChris Mason /*
472844871b1bSChris Mason  * this is a helper for btrfs_insert_empty_items, the main goal here is
472944871b1bSChris Mason  * to save stack depth by doing the bulk of the work in a function
473044871b1bSChris Mason  * that doesn't call btrfs_search_slot
473174123bd7SChris Mason  */
4732afe5fea7STsutomu Itoh void setup_items_for_insert(struct btrfs_root *root, struct btrfs_path *path,
47339c58309dSChris Mason 			    struct btrfs_key *cpu_key, u32 *data_size,
473444871b1bSChris Mason 			    u32 total_data, u32 total_size, int nr)
4735be0e5c09SChris Mason {
4736*0b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
47375f39d397SChris Mason 	struct btrfs_item *item;
47389c58309dSChris Mason 	int i;
47397518a238SChris Mason 	u32 nritems;
4740be0e5c09SChris Mason 	unsigned int data_end;
4741e2fa7227SChris Mason 	struct btrfs_disk_key disk_key;
474244871b1bSChris Mason 	struct extent_buffer *leaf;
474344871b1bSChris Mason 	int slot;
4744cfed81a0SChris Mason 	struct btrfs_map_token token;
4745cfed81a0SChris Mason 
474624cdc847SFilipe Manana 	if (path->slots[0] == 0) {
474724cdc847SFilipe Manana 		btrfs_cpu_key_to_disk(&disk_key, cpu_key);
4748*0b246afaSJeff Mahoney 		fixup_low_keys(fs_info, path, &disk_key, 1);
474924cdc847SFilipe Manana 	}
475024cdc847SFilipe Manana 	btrfs_unlock_up_safe(path, 1);
475124cdc847SFilipe Manana 
4752cfed81a0SChris Mason 	btrfs_init_map_token(&token);
4753e2fa7227SChris Mason 
47545f39d397SChris Mason 	leaf = path->nodes[0];
475544871b1bSChris Mason 	slot = path->slots[0];
475674123bd7SChris Mason 
47575f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
4758123abc88SChris Mason 	data_end = leaf_data_end(root, leaf);
4759eb60ceacSChris Mason 
4760f25956ccSChris Mason 	if (btrfs_leaf_free_space(root, leaf) < total_size) {
47613326d1b0SChris Mason 		btrfs_print_leaf(root, leaf);
4762*0b246afaSJeff Mahoney 		btrfs_crit(fs_info, "not enough freespace need %u have %d",
47639c58309dSChris Mason 			   total_size, btrfs_leaf_free_space(root, leaf));
4764be0e5c09SChris Mason 		BUG();
4765d4dbff95SChris Mason 	}
47665f39d397SChris Mason 
4767be0e5c09SChris Mason 	if (slot != nritems) {
47685f39d397SChris Mason 		unsigned int old_data = btrfs_item_end_nr(leaf, slot);
4769be0e5c09SChris Mason 
47705f39d397SChris Mason 		if (old_data < data_end) {
47715f39d397SChris Mason 			btrfs_print_leaf(root, leaf);
4772*0b246afaSJeff Mahoney 			btrfs_crit(fs_info, "slot %d old_data %d data_end %d",
47735f39d397SChris Mason 				   slot, old_data, data_end);
47745f39d397SChris Mason 			BUG_ON(1);
47755f39d397SChris Mason 		}
4776be0e5c09SChris Mason 		/*
4777be0e5c09SChris Mason 		 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4778be0e5c09SChris Mason 		 */
4779be0e5c09SChris Mason 		/* first correct the data pointers */
47800783fcfcSChris Mason 		for (i = slot; i < nritems; i++) {
47815f39d397SChris Mason 			u32 ioff;
4782db94535dSChris Mason 
4783dd3cc16bSRoss Kirk 			item = btrfs_item_nr(i);
4784cfed81a0SChris Mason 			ioff = btrfs_token_item_offset(leaf, item, &token);
4785cfed81a0SChris Mason 			btrfs_set_token_item_offset(leaf, item,
4786cfed81a0SChris Mason 						    ioff - total_data, &token);
47870783fcfcSChris Mason 		}
4788be0e5c09SChris Mason 		/* shift the items */
47899c58309dSChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + nr),
47905f39d397SChris Mason 			      btrfs_item_nr_offset(slot),
47910783fcfcSChris Mason 			      (nritems - slot) * sizeof(struct btrfs_item));
4792be0e5c09SChris Mason 
4793be0e5c09SChris Mason 		/* shift the data */
47945f39d397SChris Mason 		memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
47959c58309dSChris Mason 			      data_end - total_data, btrfs_leaf_data(leaf) +
4796be0e5c09SChris Mason 			      data_end, old_data - data_end);
4797be0e5c09SChris Mason 		data_end = old_data;
4798be0e5c09SChris Mason 	}
47995f39d397SChris Mason 
480062e2749eSChris Mason 	/* setup the item for the new data */
48019c58309dSChris Mason 	for (i = 0; i < nr; i++) {
48029c58309dSChris Mason 		btrfs_cpu_key_to_disk(&disk_key, cpu_key + i);
48039c58309dSChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot + i);
4804dd3cc16bSRoss Kirk 		item = btrfs_item_nr(slot + i);
4805cfed81a0SChris Mason 		btrfs_set_token_item_offset(leaf, item,
4806cfed81a0SChris Mason 					    data_end - data_size[i], &token);
48079c58309dSChris Mason 		data_end -= data_size[i];
4808cfed81a0SChris Mason 		btrfs_set_token_item_size(leaf, item, data_size[i], &token);
48099c58309dSChris Mason 	}
481044871b1bSChris Mason 
48119c58309dSChris Mason 	btrfs_set_header_nritems(leaf, nritems + nr);
4812b9473439SChris Mason 	btrfs_mark_buffer_dirty(leaf);
4813aa5d6bedSChris Mason 
48145f39d397SChris Mason 	if (btrfs_leaf_free_space(root, leaf) < 0) {
48155f39d397SChris Mason 		btrfs_print_leaf(root, leaf);
4816be0e5c09SChris Mason 		BUG();
48175f39d397SChris Mason 	}
481844871b1bSChris Mason }
481944871b1bSChris Mason 
482044871b1bSChris Mason /*
482144871b1bSChris Mason  * Given a key and some data, insert items into the tree.
482244871b1bSChris Mason  * This does all the path init required, making room in the tree if needed.
482344871b1bSChris Mason  */
482444871b1bSChris Mason int btrfs_insert_empty_items(struct btrfs_trans_handle *trans,
482544871b1bSChris Mason 			    struct btrfs_root *root,
482644871b1bSChris Mason 			    struct btrfs_path *path,
482744871b1bSChris Mason 			    struct btrfs_key *cpu_key, u32 *data_size,
482844871b1bSChris Mason 			    int nr)
482944871b1bSChris Mason {
483044871b1bSChris Mason 	int ret = 0;
483144871b1bSChris Mason 	int slot;
483244871b1bSChris Mason 	int i;
483344871b1bSChris Mason 	u32 total_size = 0;
483444871b1bSChris Mason 	u32 total_data = 0;
483544871b1bSChris Mason 
483644871b1bSChris Mason 	for (i = 0; i < nr; i++)
483744871b1bSChris Mason 		total_data += data_size[i];
483844871b1bSChris Mason 
483944871b1bSChris Mason 	total_size = total_data + (nr * sizeof(struct btrfs_item));
484044871b1bSChris Mason 	ret = btrfs_search_slot(trans, root, cpu_key, path, total_size, 1);
484144871b1bSChris Mason 	if (ret == 0)
484244871b1bSChris Mason 		return -EEXIST;
484344871b1bSChris Mason 	if (ret < 0)
4844143bede5SJeff Mahoney 		return ret;
484544871b1bSChris Mason 
484644871b1bSChris Mason 	slot = path->slots[0];
484744871b1bSChris Mason 	BUG_ON(slot < 0);
484844871b1bSChris Mason 
4849afe5fea7STsutomu Itoh 	setup_items_for_insert(root, path, cpu_key, data_size,
485044871b1bSChris Mason 			       total_data, total_size, nr);
4851143bede5SJeff Mahoney 	return 0;
485262e2749eSChris Mason }
485362e2749eSChris Mason 
485462e2749eSChris Mason /*
485562e2749eSChris Mason  * Given a key and some data, insert an item into the tree.
485662e2749eSChris Mason  * This does all the path init required, making room in the tree if needed.
485762e2749eSChris Mason  */
4858e089f05cSChris Mason int btrfs_insert_item(struct btrfs_trans_handle *trans, struct btrfs_root
4859e089f05cSChris Mason 		      *root, struct btrfs_key *cpu_key, void *data, u32
4860e089f05cSChris Mason 		      data_size)
486162e2749eSChris Mason {
486262e2749eSChris Mason 	int ret = 0;
48632c90e5d6SChris Mason 	struct btrfs_path *path;
48645f39d397SChris Mason 	struct extent_buffer *leaf;
48655f39d397SChris Mason 	unsigned long ptr;
486662e2749eSChris Mason 
48672c90e5d6SChris Mason 	path = btrfs_alloc_path();
4868db5b493aSTsutomu Itoh 	if (!path)
4869db5b493aSTsutomu Itoh 		return -ENOMEM;
48702c90e5d6SChris Mason 	ret = btrfs_insert_empty_item(trans, root, path, cpu_key, data_size);
487162e2749eSChris Mason 	if (!ret) {
48725f39d397SChris Mason 		leaf = path->nodes[0];
48735f39d397SChris Mason 		ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
48745f39d397SChris Mason 		write_extent_buffer(leaf, data, ptr, data_size);
48755f39d397SChris Mason 		btrfs_mark_buffer_dirty(leaf);
487662e2749eSChris Mason 	}
48772c90e5d6SChris Mason 	btrfs_free_path(path);
4878aa5d6bedSChris Mason 	return ret;
4879be0e5c09SChris Mason }
4880be0e5c09SChris Mason 
488174123bd7SChris Mason /*
48825de08d7dSChris Mason  * delete the pointer from a given node.
488374123bd7SChris Mason  *
4884d352ac68SChris Mason  * the tree should have been previously balanced so the deletion does not
4885d352ac68SChris Mason  * empty a node.
488674123bd7SChris Mason  */
4887afe5fea7STsutomu Itoh static void del_ptr(struct btrfs_root *root, struct btrfs_path *path,
4888afe5fea7STsutomu Itoh 		    int level, int slot)
4889be0e5c09SChris Mason {
4890*0b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
48915f39d397SChris Mason 	struct extent_buffer *parent = path->nodes[level];
48927518a238SChris Mason 	u32 nritems;
4893f3ea38daSJan Schmidt 	int ret;
4894be0e5c09SChris Mason 
48955f39d397SChris Mason 	nritems = btrfs_header_nritems(parent);
4896be0e5c09SChris Mason 	if (slot != nritems - 1) {
48970e411eceSLiu Bo 		if (level)
4898*0b246afaSJeff Mahoney 			tree_mod_log_eb_move(fs_info, parent, slot,
4899f3ea38daSJan Schmidt 					     slot + 1, nritems - slot - 1);
49005f39d397SChris Mason 		memmove_extent_buffer(parent,
49015f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot),
49025f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot + 1),
4903d6025579SChris Mason 			      sizeof(struct btrfs_key_ptr) *
4904d6025579SChris Mason 			      (nritems - slot - 1));
490557ba86c0SChris Mason 	} else if (level) {
4906*0b246afaSJeff Mahoney 		ret = tree_mod_log_insert_key(fs_info, parent, slot,
4907c8cc6341SJosef Bacik 					      MOD_LOG_KEY_REMOVE, GFP_NOFS);
490857ba86c0SChris Mason 		BUG_ON(ret < 0);
4909be0e5c09SChris Mason 	}
4910f3ea38daSJan Schmidt 
49117518a238SChris Mason 	nritems--;
49125f39d397SChris Mason 	btrfs_set_header_nritems(parent, nritems);
49137518a238SChris Mason 	if (nritems == 0 && parent == root->node) {
49145f39d397SChris Mason 		BUG_ON(btrfs_header_level(root->node) != 1);
4915eb60ceacSChris Mason 		/* just turn the root into a leaf and break */
49165f39d397SChris Mason 		btrfs_set_header_level(root->node, 0);
4917bb803951SChris Mason 	} else if (slot == 0) {
49185f39d397SChris Mason 		struct btrfs_disk_key disk_key;
49195f39d397SChris Mason 
49205f39d397SChris Mason 		btrfs_node_key(parent, &disk_key, 0);
4921*0b246afaSJeff Mahoney 		fixup_low_keys(fs_info, path, &disk_key, level + 1);
4922be0e5c09SChris Mason 	}
4923d6025579SChris Mason 	btrfs_mark_buffer_dirty(parent);
4924be0e5c09SChris Mason }
4925be0e5c09SChris Mason 
492674123bd7SChris Mason /*
4927323ac95bSChris Mason  * a helper function to delete the leaf pointed to by path->slots[1] and
49285d4f98a2SYan Zheng  * path->nodes[1].
4929323ac95bSChris Mason  *
4930323ac95bSChris Mason  * This deletes the pointer in path->nodes[1] and frees the leaf
4931323ac95bSChris Mason  * block extent.  zero is returned if it all worked out, < 0 otherwise.
4932323ac95bSChris Mason  *
4933323ac95bSChris Mason  * The path must have already been setup for deleting the leaf, including
4934323ac95bSChris Mason  * all the proper balancing.  path->nodes[1] must be locked.
4935323ac95bSChris Mason  */
4936143bede5SJeff Mahoney static noinline void btrfs_del_leaf(struct btrfs_trans_handle *trans,
4937323ac95bSChris Mason 				    struct btrfs_root *root,
49385d4f98a2SYan Zheng 				    struct btrfs_path *path,
49395d4f98a2SYan Zheng 				    struct extent_buffer *leaf)
4940323ac95bSChris Mason {
49415d4f98a2SYan Zheng 	WARN_ON(btrfs_header_generation(leaf) != trans->transid);
4942afe5fea7STsutomu Itoh 	del_ptr(root, path, 1, path->slots[1]);
4943323ac95bSChris Mason 
49444d081c41SChris Mason 	/*
49454d081c41SChris Mason 	 * btrfs_free_extent is expensive, we want to make sure we
49464d081c41SChris Mason 	 * aren't holding any locks when we call it
49474d081c41SChris Mason 	 */
49484d081c41SChris Mason 	btrfs_unlock_up_safe(path, 0);
49494d081c41SChris Mason 
4950f0486c68SYan, Zheng 	root_sub_used(root, leaf->len);
4951f0486c68SYan, Zheng 
49523083ee2eSJosef Bacik 	extent_buffer_get(leaf);
49535581a51aSJan Schmidt 	btrfs_free_tree_block(trans, root, leaf, 0, 1);
49543083ee2eSJosef Bacik 	free_extent_buffer_stale(leaf);
4955323ac95bSChris Mason }
4956323ac95bSChris Mason /*
495774123bd7SChris Mason  * delete the item at the leaf level in path.  If that empties
495874123bd7SChris Mason  * the leaf, remove it from the tree
495974123bd7SChris Mason  */
496085e21bacSChris Mason int btrfs_del_items(struct btrfs_trans_handle *trans, struct btrfs_root *root,
496185e21bacSChris Mason 		    struct btrfs_path *path, int slot, int nr)
4962be0e5c09SChris Mason {
4963*0b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
49645f39d397SChris Mason 	struct extent_buffer *leaf;
49655f39d397SChris Mason 	struct btrfs_item *item;
4966ce0eac2aSAlexandru Moise 	u32 last_off;
4967ce0eac2aSAlexandru Moise 	u32 dsize = 0;
4968aa5d6bedSChris Mason 	int ret = 0;
4969aa5d6bedSChris Mason 	int wret;
497085e21bacSChris Mason 	int i;
49717518a238SChris Mason 	u32 nritems;
4972cfed81a0SChris Mason 	struct btrfs_map_token token;
4973cfed81a0SChris Mason 
4974cfed81a0SChris Mason 	btrfs_init_map_token(&token);
4975be0e5c09SChris Mason 
49765f39d397SChris Mason 	leaf = path->nodes[0];
497785e21bacSChris Mason 	last_off = btrfs_item_offset_nr(leaf, slot + nr - 1);
497885e21bacSChris Mason 
497985e21bacSChris Mason 	for (i = 0; i < nr; i++)
498085e21bacSChris Mason 		dsize += btrfs_item_size_nr(leaf, slot + i);
498185e21bacSChris Mason 
49825f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
4983be0e5c09SChris Mason 
498485e21bacSChris Mason 	if (slot + nr != nritems) {
4985123abc88SChris Mason 		int data_end = leaf_data_end(root, leaf);
49865f39d397SChris Mason 
49875f39d397SChris Mason 		memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
4988d6025579SChris Mason 			      data_end + dsize,
4989123abc88SChris Mason 			      btrfs_leaf_data(leaf) + data_end,
499085e21bacSChris Mason 			      last_off - data_end);
49915f39d397SChris Mason 
499285e21bacSChris Mason 		for (i = slot + nr; i < nritems; i++) {
49935f39d397SChris Mason 			u32 ioff;
4994db94535dSChris Mason 
4995dd3cc16bSRoss Kirk 			item = btrfs_item_nr(i);
4996cfed81a0SChris Mason 			ioff = btrfs_token_item_offset(leaf, item, &token);
4997cfed81a0SChris Mason 			btrfs_set_token_item_offset(leaf, item,
4998cfed81a0SChris Mason 						    ioff + dsize, &token);
49990783fcfcSChris Mason 		}
5000db94535dSChris Mason 
50015f39d397SChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot),
500285e21bacSChris Mason 			      btrfs_item_nr_offset(slot + nr),
50030783fcfcSChris Mason 			      sizeof(struct btrfs_item) *
500485e21bacSChris Mason 			      (nritems - slot - nr));
5005be0e5c09SChris Mason 	}
500685e21bacSChris Mason 	btrfs_set_header_nritems(leaf, nritems - nr);
500785e21bacSChris Mason 	nritems -= nr;
50085f39d397SChris Mason 
500974123bd7SChris Mason 	/* delete the leaf if we've emptied it */
50107518a238SChris Mason 	if (nritems == 0) {
50115f39d397SChris Mason 		if (leaf == root->node) {
50125f39d397SChris Mason 			btrfs_set_header_level(leaf, 0);
50139a8dd150SChris Mason 		} else {
5014f0486c68SYan, Zheng 			btrfs_set_path_blocking(path);
5015*0b246afaSJeff Mahoney 			clean_tree_block(trans, fs_info, leaf);
5016143bede5SJeff Mahoney 			btrfs_del_leaf(trans, root, path, leaf);
50179a8dd150SChris Mason 		}
5018be0e5c09SChris Mason 	} else {
50197518a238SChris Mason 		int used = leaf_space_used(leaf, 0, nritems);
5020aa5d6bedSChris Mason 		if (slot == 0) {
50215f39d397SChris Mason 			struct btrfs_disk_key disk_key;
50225f39d397SChris Mason 
50235f39d397SChris Mason 			btrfs_item_key(leaf, &disk_key, 0);
5024*0b246afaSJeff Mahoney 			fixup_low_keys(fs_info, path, &disk_key, 1);
5025aa5d6bedSChris Mason 		}
5026aa5d6bedSChris Mason 
502774123bd7SChris Mason 		/* delete the leaf if it is mostly empty */
5028*0b246afaSJeff Mahoney 		if (used < BTRFS_LEAF_DATA_SIZE(fs_info) / 3) {
5029be0e5c09SChris Mason 			/* push_leaf_left fixes the path.
5030be0e5c09SChris Mason 			 * make sure the path still points to our leaf
5031be0e5c09SChris Mason 			 * for possible call to del_ptr below
5032be0e5c09SChris Mason 			 */
50334920c9acSChris Mason 			slot = path->slots[1];
50345f39d397SChris Mason 			extent_buffer_get(leaf);
50355f39d397SChris Mason 
5036b9473439SChris Mason 			btrfs_set_path_blocking(path);
503799d8f83cSChris Mason 			wret = push_leaf_left(trans, root, path, 1, 1,
503899d8f83cSChris Mason 					      1, (u32)-1);
503954aa1f4dSChris Mason 			if (wret < 0 && wret != -ENOSPC)
5040aa5d6bedSChris Mason 				ret = wret;
50415f39d397SChris Mason 
50425f39d397SChris Mason 			if (path->nodes[0] == leaf &&
50435f39d397SChris Mason 			    btrfs_header_nritems(leaf)) {
504499d8f83cSChris Mason 				wret = push_leaf_right(trans, root, path, 1,
504599d8f83cSChris Mason 						       1, 1, 0);
504654aa1f4dSChris Mason 				if (wret < 0 && wret != -ENOSPC)
5047aa5d6bedSChris Mason 					ret = wret;
5048aa5d6bedSChris Mason 			}
50495f39d397SChris Mason 
50505f39d397SChris Mason 			if (btrfs_header_nritems(leaf) == 0) {
5051323ac95bSChris Mason 				path->slots[1] = slot;
5052143bede5SJeff Mahoney 				btrfs_del_leaf(trans, root, path, leaf);
50535f39d397SChris Mason 				free_extent_buffer(leaf);
5054143bede5SJeff Mahoney 				ret = 0;
50555de08d7dSChris Mason 			} else {
5056925baeddSChris Mason 				/* if we're still in the path, make sure
5057925baeddSChris Mason 				 * we're dirty.  Otherwise, one of the
5058925baeddSChris Mason 				 * push_leaf functions must have already
5059925baeddSChris Mason 				 * dirtied this buffer
5060925baeddSChris Mason 				 */
5061925baeddSChris Mason 				if (path->nodes[0] == leaf)
50625f39d397SChris Mason 					btrfs_mark_buffer_dirty(leaf);
50635f39d397SChris Mason 				free_extent_buffer(leaf);
5064be0e5c09SChris Mason 			}
5065d5719762SChris Mason 		} else {
50665f39d397SChris Mason 			btrfs_mark_buffer_dirty(leaf);
5067be0e5c09SChris Mason 		}
50689a8dd150SChris Mason 	}
5069aa5d6bedSChris Mason 	return ret;
50709a8dd150SChris Mason }
50719a8dd150SChris Mason 
507297571fd0SChris Mason /*
5073925baeddSChris Mason  * search the tree again to find a leaf with lesser keys
50747bb86316SChris Mason  * returns 0 if it found something or 1 if there are no lesser leaves.
50757bb86316SChris Mason  * returns < 0 on io errors.
5076d352ac68SChris Mason  *
5077d352ac68SChris Mason  * This may release the path, and so you may lose any locks held at the
5078d352ac68SChris Mason  * time you call it.
50797bb86316SChris Mason  */
508016e7549fSJosef Bacik int btrfs_prev_leaf(struct btrfs_root *root, struct btrfs_path *path)
50817bb86316SChris Mason {
5082925baeddSChris Mason 	struct btrfs_key key;
5083925baeddSChris Mason 	struct btrfs_disk_key found_key;
5084925baeddSChris Mason 	int ret;
50857bb86316SChris Mason 
5086925baeddSChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, 0);
5087925baeddSChris Mason 
5088e8b0d724SFilipe David Borba Manana 	if (key.offset > 0) {
5089925baeddSChris Mason 		key.offset--;
5090e8b0d724SFilipe David Borba Manana 	} else if (key.type > 0) {
5091925baeddSChris Mason 		key.type--;
5092e8b0d724SFilipe David Borba Manana 		key.offset = (u64)-1;
5093e8b0d724SFilipe David Borba Manana 	} else if (key.objectid > 0) {
5094925baeddSChris Mason 		key.objectid--;
5095e8b0d724SFilipe David Borba Manana 		key.type = (u8)-1;
5096e8b0d724SFilipe David Borba Manana 		key.offset = (u64)-1;
5097e8b0d724SFilipe David Borba Manana 	} else {
50987bb86316SChris Mason 		return 1;
5099e8b0d724SFilipe David Borba Manana 	}
51007bb86316SChris Mason 
5101b3b4aa74SDavid Sterba 	btrfs_release_path(path);
5102925baeddSChris Mason 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5103925baeddSChris Mason 	if (ret < 0)
5104925baeddSChris Mason 		return ret;
5105925baeddSChris Mason 	btrfs_item_key(path->nodes[0], &found_key, 0);
5106925baeddSChris Mason 	ret = comp_keys(&found_key, &key);
5107337c6f68SFilipe Manana 	/*
5108337c6f68SFilipe Manana 	 * We might have had an item with the previous key in the tree right
5109337c6f68SFilipe Manana 	 * before we released our path. And after we released our path, that
5110337c6f68SFilipe Manana 	 * item might have been pushed to the first slot (0) of the leaf we
5111337c6f68SFilipe Manana 	 * were holding due to a tree balance. Alternatively, an item with the
5112337c6f68SFilipe Manana 	 * previous key can exist as the only element of a leaf (big fat item).
5113337c6f68SFilipe Manana 	 * Therefore account for these 2 cases, so that our callers (like
5114337c6f68SFilipe Manana 	 * btrfs_previous_item) don't miss an existing item with a key matching
5115337c6f68SFilipe Manana 	 * the previous key we computed above.
5116337c6f68SFilipe Manana 	 */
5117337c6f68SFilipe Manana 	if (ret <= 0)
51187bb86316SChris Mason 		return 0;
5119925baeddSChris Mason 	return 1;
51207bb86316SChris Mason }
51217bb86316SChris Mason 
51223f157a2fSChris Mason /*
51233f157a2fSChris Mason  * A helper function to walk down the tree starting at min_key, and looking
5124de78b51aSEric Sandeen  * for nodes or leaves that are have a minimum transaction id.
5125de78b51aSEric Sandeen  * This is used by the btree defrag code, and tree logging
51263f157a2fSChris Mason  *
51273f157a2fSChris Mason  * This does not cow, but it does stuff the starting key it finds back
51283f157a2fSChris Mason  * into min_key, so you can call btrfs_search_slot with cow=1 on the
51293f157a2fSChris Mason  * key and get a writable path.
51303f157a2fSChris Mason  *
51313f157a2fSChris Mason  * This does lock as it descends, and path->keep_locks should be set
51323f157a2fSChris Mason  * to 1 by the caller.
51333f157a2fSChris Mason  *
51343f157a2fSChris Mason  * This honors path->lowest_level to prevent descent past a given level
51353f157a2fSChris Mason  * of the tree.
51363f157a2fSChris Mason  *
5137d352ac68SChris Mason  * min_trans indicates the oldest transaction that you are interested
5138d352ac68SChris Mason  * in walking through.  Any nodes or leaves older than min_trans are
5139d352ac68SChris Mason  * skipped over (without reading them).
5140d352ac68SChris Mason  *
51413f157a2fSChris Mason  * returns zero if something useful was found, < 0 on error and 1 if there
51423f157a2fSChris Mason  * was nothing in the tree that matched the search criteria.
51433f157a2fSChris Mason  */
51443f157a2fSChris Mason int btrfs_search_forward(struct btrfs_root *root, struct btrfs_key *min_key,
5145de78b51aSEric Sandeen 			 struct btrfs_path *path,
51463f157a2fSChris Mason 			 u64 min_trans)
51473f157a2fSChris Mason {
51483f157a2fSChris Mason 	struct extent_buffer *cur;
51493f157a2fSChris Mason 	struct btrfs_key found_key;
51503f157a2fSChris Mason 	int slot;
51519652480bSYan 	int sret;
51523f157a2fSChris Mason 	u32 nritems;
51533f157a2fSChris Mason 	int level;
51543f157a2fSChris Mason 	int ret = 1;
5155f98de9b9SFilipe Manana 	int keep_locks = path->keep_locks;
51563f157a2fSChris Mason 
5157f98de9b9SFilipe Manana 	path->keep_locks = 1;
51583f157a2fSChris Mason again:
5159bd681513SChris Mason 	cur = btrfs_read_lock_root_node(root);
51603f157a2fSChris Mason 	level = btrfs_header_level(cur);
5161e02119d5SChris Mason 	WARN_ON(path->nodes[level]);
51623f157a2fSChris Mason 	path->nodes[level] = cur;
5163bd681513SChris Mason 	path->locks[level] = BTRFS_READ_LOCK;
51643f157a2fSChris Mason 
51653f157a2fSChris Mason 	if (btrfs_header_generation(cur) < min_trans) {
51663f157a2fSChris Mason 		ret = 1;
51673f157a2fSChris Mason 		goto out;
51683f157a2fSChris Mason 	}
51693f157a2fSChris Mason 	while (1) {
51703f157a2fSChris Mason 		nritems = btrfs_header_nritems(cur);
51713f157a2fSChris Mason 		level = btrfs_header_level(cur);
51729652480bSYan 		sret = bin_search(cur, min_key, level, &slot);
51733f157a2fSChris Mason 
5174323ac95bSChris Mason 		/* at the lowest level, we're done, setup the path and exit */
5175323ac95bSChris Mason 		if (level == path->lowest_level) {
5176e02119d5SChris Mason 			if (slot >= nritems)
5177e02119d5SChris Mason 				goto find_next_key;
51783f157a2fSChris Mason 			ret = 0;
51793f157a2fSChris Mason 			path->slots[level] = slot;
51803f157a2fSChris Mason 			btrfs_item_key_to_cpu(cur, &found_key, slot);
51813f157a2fSChris Mason 			goto out;
51823f157a2fSChris Mason 		}
51839652480bSYan 		if (sret && slot > 0)
51849652480bSYan 			slot--;
51853f157a2fSChris Mason 		/*
5186de78b51aSEric Sandeen 		 * check this node pointer against the min_trans parameters.
5187de78b51aSEric Sandeen 		 * If it is too old, old, skip to the next one.
51883f157a2fSChris Mason 		 */
51893f157a2fSChris Mason 		while (slot < nritems) {
51903f157a2fSChris Mason 			u64 gen;
5191e02119d5SChris Mason 
51923f157a2fSChris Mason 			gen = btrfs_node_ptr_generation(cur, slot);
51933f157a2fSChris Mason 			if (gen < min_trans) {
51943f157a2fSChris Mason 				slot++;
51953f157a2fSChris Mason 				continue;
51963f157a2fSChris Mason 			}
51973f157a2fSChris Mason 			break;
51983f157a2fSChris Mason 		}
5199e02119d5SChris Mason find_next_key:
52003f157a2fSChris Mason 		/*
52013f157a2fSChris Mason 		 * we didn't find a candidate key in this node, walk forward
52023f157a2fSChris Mason 		 * and find another one
52033f157a2fSChris Mason 		 */
52043f157a2fSChris Mason 		if (slot >= nritems) {
5205e02119d5SChris Mason 			path->slots[level] = slot;
5206b4ce94deSChris Mason 			btrfs_set_path_blocking(path);
5207e02119d5SChris Mason 			sret = btrfs_find_next_key(root, path, min_key, level,
5208de78b51aSEric Sandeen 						  min_trans);
5209e02119d5SChris Mason 			if (sret == 0) {
5210b3b4aa74SDavid Sterba 				btrfs_release_path(path);
52113f157a2fSChris Mason 				goto again;
52123f157a2fSChris Mason 			} else {
52133f157a2fSChris Mason 				goto out;
52143f157a2fSChris Mason 			}
52153f157a2fSChris Mason 		}
52163f157a2fSChris Mason 		/* save our key for returning back */
52173f157a2fSChris Mason 		btrfs_node_key_to_cpu(cur, &found_key, slot);
52183f157a2fSChris Mason 		path->slots[level] = slot;
52193f157a2fSChris Mason 		if (level == path->lowest_level) {
52203f157a2fSChris Mason 			ret = 0;
52213f157a2fSChris Mason 			goto out;
52223f157a2fSChris Mason 		}
5223b4ce94deSChris Mason 		btrfs_set_path_blocking(path);
52243f157a2fSChris Mason 		cur = read_node_slot(root, cur, slot);
5225fb770ae4SLiu Bo 		if (IS_ERR(cur)) {
5226fb770ae4SLiu Bo 			ret = PTR_ERR(cur);
5227fb770ae4SLiu Bo 			goto out;
5228fb770ae4SLiu Bo 		}
52293f157a2fSChris Mason 
5230bd681513SChris Mason 		btrfs_tree_read_lock(cur);
5231b4ce94deSChris Mason 
5232bd681513SChris Mason 		path->locks[level - 1] = BTRFS_READ_LOCK;
52333f157a2fSChris Mason 		path->nodes[level - 1] = cur;
5234f7c79f30SChris Mason 		unlock_up(path, level, 1, 0, NULL);
5235bd681513SChris Mason 		btrfs_clear_path_blocking(path, NULL, 0);
52363f157a2fSChris Mason 	}
52373f157a2fSChris Mason out:
5238f98de9b9SFilipe Manana 	path->keep_locks = keep_locks;
5239f98de9b9SFilipe Manana 	if (ret == 0) {
5240f98de9b9SFilipe Manana 		btrfs_unlock_up_safe(path, path->lowest_level + 1);
5241b4ce94deSChris Mason 		btrfs_set_path_blocking(path);
5242f98de9b9SFilipe Manana 		memcpy(min_key, &found_key, sizeof(found_key));
5243f98de9b9SFilipe Manana 	}
52443f157a2fSChris Mason 	return ret;
52453f157a2fSChris Mason }
52463f157a2fSChris Mason 
5247fb770ae4SLiu Bo static int tree_move_down(struct btrfs_root *root,
52487069830aSAlexander Block 			   struct btrfs_path *path,
52497069830aSAlexander Block 			   int *level, int root_level)
52507069830aSAlexander Block {
5251fb770ae4SLiu Bo 	struct extent_buffer *eb;
5252fb770ae4SLiu Bo 
525374dd17fbSChris Mason 	BUG_ON(*level == 0);
5254fb770ae4SLiu Bo 	eb = read_node_slot(root, path->nodes[*level], path->slots[*level]);
5255fb770ae4SLiu Bo 	if (IS_ERR(eb))
5256fb770ae4SLiu Bo 		return PTR_ERR(eb);
5257fb770ae4SLiu Bo 
5258fb770ae4SLiu Bo 	path->nodes[*level - 1] = eb;
52597069830aSAlexander Block 	path->slots[*level - 1] = 0;
52607069830aSAlexander Block 	(*level)--;
5261fb770ae4SLiu Bo 	return 0;
52627069830aSAlexander Block }
52637069830aSAlexander Block 
52647069830aSAlexander Block static int tree_move_next_or_upnext(struct btrfs_root *root,
52657069830aSAlexander Block 				    struct btrfs_path *path,
52667069830aSAlexander Block 				    int *level, int root_level)
52677069830aSAlexander Block {
52687069830aSAlexander Block 	int ret = 0;
52697069830aSAlexander Block 	int nritems;
52707069830aSAlexander Block 	nritems = btrfs_header_nritems(path->nodes[*level]);
52717069830aSAlexander Block 
52727069830aSAlexander Block 	path->slots[*level]++;
52737069830aSAlexander Block 
527474dd17fbSChris Mason 	while (path->slots[*level] >= nritems) {
52757069830aSAlexander Block 		if (*level == root_level)
52767069830aSAlexander Block 			return -1;
52777069830aSAlexander Block 
52787069830aSAlexander Block 		/* move upnext */
52797069830aSAlexander Block 		path->slots[*level] = 0;
52807069830aSAlexander Block 		free_extent_buffer(path->nodes[*level]);
52817069830aSAlexander Block 		path->nodes[*level] = NULL;
52827069830aSAlexander Block 		(*level)++;
52837069830aSAlexander Block 		path->slots[*level]++;
52847069830aSAlexander Block 
52857069830aSAlexander Block 		nritems = btrfs_header_nritems(path->nodes[*level]);
52867069830aSAlexander Block 		ret = 1;
52877069830aSAlexander Block 	}
52887069830aSAlexander Block 	return ret;
52897069830aSAlexander Block }
52907069830aSAlexander Block 
52917069830aSAlexander Block /*
52927069830aSAlexander Block  * Returns 1 if it had to move up and next. 0 is returned if it moved only next
52937069830aSAlexander Block  * or down.
52947069830aSAlexander Block  */
52957069830aSAlexander Block static int tree_advance(struct btrfs_root *root,
52967069830aSAlexander Block 			struct btrfs_path *path,
52977069830aSAlexander Block 			int *level, int root_level,
52987069830aSAlexander Block 			int allow_down,
52997069830aSAlexander Block 			struct btrfs_key *key)
53007069830aSAlexander Block {
53017069830aSAlexander Block 	int ret;
53027069830aSAlexander Block 
53037069830aSAlexander Block 	if (*level == 0 || !allow_down) {
53047069830aSAlexander Block 		ret = tree_move_next_or_upnext(root, path, level, root_level);
53057069830aSAlexander Block 	} else {
5306fb770ae4SLiu Bo 		ret = tree_move_down(root, path, level, root_level);
53077069830aSAlexander Block 	}
53087069830aSAlexander Block 	if (ret >= 0) {
53097069830aSAlexander Block 		if (*level == 0)
53107069830aSAlexander Block 			btrfs_item_key_to_cpu(path->nodes[*level], key,
53117069830aSAlexander Block 					path->slots[*level]);
53127069830aSAlexander Block 		else
53137069830aSAlexander Block 			btrfs_node_key_to_cpu(path->nodes[*level], key,
53147069830aSAlexander Block 					path->slots[*level]);
53157069830aSAlexander Block 	}
53167069830aSAlexander Block 	return ret;
53177069830aSAlexander Block }
53187069830aSAlexander Block 
53197069830aSAlexander Block static int tree_compare_item(struct btrfs_root *left_root,
53207069830aSAlexander Block 			     struct btrfs_path *left_path,
53217069830aSAlexander Block 			     struct btrfs_path *right_path,
53227069830aSAlexander Block 			     char *tmp_buf)
53237069830aSAlexander Block {
53247069830aSAlexander Block 	int cmp;
53257069830aSAlexander Block 	int len1, len2;
53267069830aSAlexander Block 	unsigned long off1, off2;
53277069830aSAlexander Block 
53287069830aSAlexander Block 	len1 = btrfs_item_size_nr(left_path->nodes[0], left_path->slots[0]);
53297069830aSAlexander Block 	len2 = btrfs_item_size_nr(right_path->nodes[0], right_path->slots[0]);
53307069830aSAlexander Block 	if (len1 != len2)
53317069830aSAlexander Block 		return 1;
53327069830aSAlexander Block 
53337069830aSAlexander Block 	off1 = btrfs_item_ptr_offset(left_path->nodes[0], left_path->slots[0]);
53347069830aSAlexander Block 	off2 = btrfs_item_ptr_offset(right_path->nodes[0],
53357069830aSAlexander Block 				right_path->slots[0]);
53367069830aSAlexander Block 
53377069830aSAlexander Block 	read_extent_buffer(left_path->nodes[0], tmp_buf, off1, len1);
53387069830aSAlexander Block 
53397069830aSAlexander Block 	cmp = memcmp_extent_buffer(right_path->nodes[0], tmp_buf, off2, len1);
53407069830aSAlexander Block 	if (cmp)
53417069830aSAlexander Block 		return 1;
53427069830aSAlexander Block 	return 0;
53437069830aSAlexander Block }
53447069830aSAlexander Block 
53457069830aSAlexander Block #define ADVANCE 1
53467069830aSAlexander Block #define ADVANCE_ONLY_NEXT -1
53477069830aSAlexander Block 
53487069830aSAlexander Block /*
53497069830aSAlexander Block  * This function compares two trees and calls the provided callback for
53507069830aSAlexander Block  * every changed/new/deleted item it finds.
53517069830aSAlexander Block  * If shared tree blocks are encountered, whole subtrees are skipped, making
53527069830aSAlexander Block  * the compare pretty fast on snapshotted subvolumes.
53537069830aSAlexander Block  *
53547069830aSAlexander Block  * This currently works on commit roots only. As commit roots are read only,
53557069830aSAlexander Block  * we don't do any locking. The commit roots are protected with transactions.
53567069830aSAlexander Block  * Transactions are ended and rejoined when a commit is tried in between.
53577069830aSAlexander Block  *
53587069830aSAlexander Block  * This function checks for modifications done to the trees while comparing.
53597069830aSAlexander Block  * If it detects a change, it aborts immediately.
53607069830aSAlexander Block  */
53617069830aSAlexander Block int btrfs_compare_trees(struct btrfs_root *left_root,
53627069830aSAlexander Block 			struct btrfs_root *right_root,
53637069830aSAlexander Block 			btrfs_changed_cb_t changed_cb, void *ctx)
53647069830aSAlexander Block {
5365*0b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = left_root->fs_info;
53667069830aSAlexander Block 	int ret;
53677069830aSAlexander Block 	int cmp;
53687069830aSAlexander Block 	struct btrfs_path *left_path = NULL;
53697069830aSAlexander Block 	struct btrfs_path *right_path = NULL;
53707069830aSAlexander Block 	struct btrfs_key left_key;
53717069830aSAlexander Block 	struct btrfs_key right_key;
53727069830aSAlexander Block 	char *tmp_buf = NULL;
53737069830aSAlexander Block 	int left_root_level;
53747069830aSAlexander Block 	int right_root_level;
53757069830aSAlexander Block 	int left_level;
53767069830aSAlexander Block 	int right_level;
53777069830aSAlexander Block 	int left_end_reached;
53787069830aSAlexander Block 	int right_end_reached;
53797069830aSAlexander Block 	int advance_left;
53807069830aSAlexander Block 	int advance_right;
53817069830aSAlexander Block 	u64 left_blockptr;
53827069830aSAlexander Block 	u64 right_blockptr;
53836baa4293SFilipe Manana 	u64 left_gen;
53846baa4293SFilipe Manana 	u64 right_gen;
53857069830aSAlexander Block 
53867069830aSAlexander Block 	left_path = btrfs_alloc_path();
53877069830aSAlexander Block 	if (!left_path) {
53887069830aSAlexander Block 		ret = -ENOMEM;
53897069830aSAlexander Block 		goto out;
53907069830aSAlexander Block 	}
53917069830aSAlexander Block 	right_path = btrfs_alloc_path();
53927069830aSAlexander Block 	if (!right_path) {
53937069830aSAlexander Block 		ret = -ENOMEM;
53947069830aSAlexander Block 		goto out;
53957069830aSAlexander Block 	}
53967069830aSAlexander Block 
5397*0b246afaSJeff Mahoney 	tmp_buf = kmalloc(fs_info->nodesize, GFP_KERNEL | __GFP_NOWARN);
53988f282f71SDavid Sterba 	if (!tmp_buf) {
5399*0b246afaSJeff Mahoney 		tmp_buf = vmalloc(fs_info->nodesize);
54007069830aSAlexander Block 		if (!tmp_buf) {
54017069830aSAlexander Block 			ret = -ENOMEM;
54027069830aSAlexander Block 			goto out;
54037069830aSAlexander Block 		}
54048f282f71SDavid Sterba 	}
54057069830aSAlexander Block 
54067069830aSAlexander Block 	left_path->search_commit_root = 1;
54077069830aSAlexander Block 	left_path->skip_locking = 1;
54087069830aSAlexander Block 	right_path->search_commit_root = 1;
54097069830aSAlexander Block 	right_path->skip_locking = 1;
54107069830aSAlexander Block 
54117069830aSAlexander Block 	/*
54127069830aSAlexander Block 	 * Strategy: Go to the first items of both trees. Then do
54137069830aSAlexander Block 	 *
54147069830aSAlexander Block 	 * If both trees are at level 0
54157069830aSAlexander Block 	 *   Compare keys of current items
54167069830aSAlexander Block 	 *     If left < right treat left item as new, advance left tree
54177069830aSAlexander Block 	 *       and repeat
54187069830aSAlexander Block 	 *     If left > right treat right item as deleted, advance right tree
54197069830aSAlexander Block 	 *       and repeat
54207069830aSAlexander Block 	 *     If left == right do deep compare of items, treat as changed if
54217069830aSAlexander Block 	 *       needed, advance both trees and repeat
54227069830aSAlexander Block 	 * If both trees are at the same level but not at level 0
54237069830aSAlexander Block 	 *   Compare keys of current nodes/leafs
54247069830aSAlexander Block 	 *     If left < right advance left tree and repeat
54257069830aSAlexander Block 	 *     If left > right advance right tree and repeat
54267069830aSAlexander Block 	 *     If left == right compare blockptrs of the next nodes/leafs
54277069830aSAlexander Block 	 *       If they match advance both trees but stay at the same level
54287069830aSAlexander Block 	 *         and repeat
54297069830aSAlexander Block 	 *       If they don't match advance both trees while allowing to go
54307069830aSAlexander Block 	 *         deeper and repeat
54317069830aSAlexander Block 	 * If tree levels are different
54327069830aSAlexander Block 	 *   Advance the tree that needs it and repeat
54337069830aSAlexander Block 	 *
54347069830aSAlexander Block 	 * Advancing a tree means:
54357069830aSAlexander Block 	 *   If we are at level 0, try to go to the next slot. If that's not
54367069830aSAlexander Block 	 *   possible, go one level up and repeat. Stop when we found a level
54377069830aSAlexander Block 	 *   where we could go to the next slot. We may at this point be on a
54387069830aSAlexander Block 	 *   node or a leaf.
54397069830aSAlexander Block 	 *
54407069830aSAlexander Block 	 *   If we are not at level 0 and not on shared tree blocks, go one
54417069830aSAlexander Block 	 *   level deeper.
54427069830aSAlexander Block 	 *
54437069830aSAlexander Block 	 *   If we are not at level 0 and on shared tree blocks, go one slot to
54447069830aSAlexander Block 	 *   the right if possible or go up and right.
54457069830aSAlexander Block 	 */
54467069830aSAlexander Block 
5447*0b246afaSJeff Mahoney 	down_read(&fs_info->commit_root_sem);
54487069830aSAlexander Block 	left_level = btrfs_header_level(left_root->commit_root);
54497069830aSAlexander Block 	left_root_level = left_level;
54507069830aSAlexander Block 	left_path->nodes[left_level] = left_root->commit_root;
54517069830aSAlexander Block 	extent_buffer_get(left_path->nodes[left_level]);
54527069830aSAlexander Block 
54537069830aSAlexander Block 	right_level = btrfs_header_level(right_root->commit_root);
54547069830aSAlexander Block 	right_root_level = right_level;
54557069830aSAlexander Block 	right_path->nodes[right_level] = right_root->commit_root;
54567069830aSAlexander Block 	extent_buffer_get(right_path->nodes[right_level]);
5457*0b246afaSJeff Mahoney 	up_read(&fs_info->commit_root_sem);
54587069830aSAlexander Block 
54597069830aSAlexander Block 	if (left_level == 0)
54607069830aSAlexander Block 		btrfs_item_key_to_cpu(left_path->nodes[left_level],
54617069830aSAlexander Block 				&left_key, left_path->slots[left_level]);
54627069830aSAlexander Block 	else
54637069830aSAlexander Block 		btrfs_node_key_to_cpu(left_path->nodes[left_level],
54647069830aSAlexander Block 				&left_key, left_path->slots[left_level]);
54657069830aSAlexander Block 	if (right_level == 0)
54667069830aSAlexander Block 		btrfs_item_key_to_cpu(right_path->nodes[right_level],
54677069830aSAlexander Block 				&right_key, right_path->slots[right_level]);
54687069830aSAlexander Block 	else
54697069830aSAlexander Block 		btrfs_node_key_to_cpu(right_path->nodes[right_level],
54707069830aSAlexander Block 				&right_key, right_path->slots[right_level]);
54717069830aSAlexander Block 
54727069830aSAlexander Block 	left_end_reached = right_end_reached = 0;
54737069830aSAlexander Block 	advance_left = advance_right = 0;
54747069830aSAlexander Block 
54757069830aSAlexander Block 	while (1) {
54767069830aSAlexander Block 		if (advance_left && !left_end_reached) {
54777069830aSAlexander Block 			ret = tree_advance(left_root, left_path, &left_level,
54787069830aSAlexander Block 					left_root_level,
54797069830aSAlexander Block 					advance_left != ADVANCE_ONLY_NEXT,
54807069830aSAlexander Block 					&left_key);
5481fb770ae4SLiu Bo 			if (ret == -1)
54827069830aSAlexander Block 				left_end_reached = ADVANCE;
5483fb770ae4SLiu Bo 			else if (ret < 0)
5484fb770ae4SLiu Bo 				goto out;
54857069830aSAlexander Block 			advance_left = 0;
54867069830aSAlexander Block 		}
54877069830aSAlexander Block 		if (advance_right && !right_end_reached) {
54887069830aSAlexander Block 			ret = tree_advance(right_root, right_path, &right_level,
54897069830aSAlexander Block 					right_root_level,
54907069830aSAlexander Block 					advance_right != ADVANCE_ONLY_NEXT,
54917069830aSAlexander Block 					&right_key);
5492fb770ae4SLiu Bo 			if (ret == -1)
54937069830aSAlexander Block 				right_end_reached = ADVANCE;
5494fb770ae4SLiu Bo 			else if (ret < 0)
5495fb770ae4SLiu Bo 				goto out;
54967069830aSAlexander Block 			advance_right = 0;
54977069830aSAlexander Block 		}
54987069830aSAlexander Block 
54997069830aSAlexander Block 		if (left_end_reached && right_end_reached) {
55007069830aSAlexander Block 			ret = 0;
55017069830aSAlexander Block 			goto out;
55027069830aSAlexander Block 		} else if (left_end_reached) {
55037069830aSAlexander Block 			if (right_level == 0) {
55047069830aSAlexander Block 				ret = changed_cb(left_root, right_root,
55057069830aSAlexander Block 						left_path, right_path,
55067069830aSAlexander Block 						&right_key,
55077069830aSAlexander Block 						BTRFS_COMPARE_TREE_DELETED,
55087069830aSAlexander Block 						ctx);
55097069830aSAlexander Block 				if (ret < 0)
55107069830aSAlexander Block 					goto out;
55117069830aSAlexander Block 			}
55127069830aSAlexander Block 			advance_right = ADVANCE;
55137069830aSAlexander Block 			continue;
55147069830aSAlexander Block 		} else if (right_end_reached) {
55157069830aSAlexander Block 			if (left_level == 0) {
55167069830aSAlexander Block 				ret = changed_cb(left_root, right_root,
55177069830aSAlexander Block 						left_path, right_path,
55187069830aSAlexander Block 						&left_key,
55197069830aSAlexander Block 						BTRFS_COMPARE_TREE_NEW,
55207069830aSAlexander Block 						ctx);
55217069830aSAlexander Block 				if (ret < 0)
55227069830aSAlexander Block 					goto out;
55237069830aSAlexander Block 			}
55247069830aSAlexander Block 			advance_left = ADVANCE;
55257069830aSAlexander Block 			continue;
55267069830aSAlexander Block 		}
55277069830aSAlexander Block 
55287069830aSAlexander Block 		if (left_level == 0 && right_level == 0) {
55297069830aSAlexander Block 			cmp = btrfs_comp_cpu_keys(&left_key, &right_key);
55307069830aSAlexander Block 			if (cmp < 0) {
55317069830aSAlexander Block 				ret = changed_cb(left_root, right_root,
55327069830aSAlexander Block 						left_path, right_path,
55337069830aSAlexander Block 						&left_key,
55347069830aSAlexander Block 						BTRFS_COMPARE_TREE_NEW,
55357069830aSAlexander Block 						ctx);
55367069830aSAlexander Block 				if (ret < 0)
55377069830aSAlexander Block 					goto out;
55387069830aSAlexander Block 				advance_left = ADVANCE;
55397069830aSAlexander Block 			} else if (cmp > 0) {
55407069830aSAlexander Block 				ret = changed_cb(left_root, right_root,
55417069830aSAlexander Block 						left_path, right_path,
55427069830aSAlexander Block 						&right_key,
55437069830aSAlexander Block 						BTRFS_COMPARE_TREE_DELETED,
55447069830aSAlexander Block 						ctx);
55457069830aSAlexander Block 				if (ret < 0)
55467069830aSAlexander Block 					goto out;
55477069830aSAlexander Block 				advance_right = ADVANCE;
55487069830aSAlexander Block 			} else {
5549b99d9a6aSFabian Frederick 				enum btrfs_compare_tree_result result;
5550ba5e8f2eSJosef Bacik 
555174dd17fbSChris Mason 				WARN_ON(!extent_buffer_uptodate(left_path->nodes[0]));
55527069830aSAlexander Block 				ret = tree_compare_item(left_root, left_path,
55537069830aSAlexander Block 						right_path, tmp_buf);
5554ba5e8f2eSJosef Bacik 				if (ret)
5555b99d9a6aSFabian Frederick 					result = BTRFS_COMPARE_TREE_CHANGED;
5556ba5e8f2eSJosef Bacik 				else
5557b99d9a6aSFabian Frederick 					result = BTRFS_COMPARE_TREE_SAME;
55587069830aSAlexander Block 				ret = changed_cb(left_root, right_root,
55597069830aSAlexander Block 						 left_path, right_path,
5560b99d9a6aSFabian Frederick 						 &left_key, result, ctx);
55617069830aSAlexander Block 				if (ret < 0)
55627069830aSAlexander Block 					goto out;
55637069830aSAlexander Block 				advance_left = ADVANCE;
55647069830aSAlexander Block 				advance_right = ADVANCE;
55657069830aSAlexander Block 			}
55667069830aSAlexander Block 		} else if (left_level == right_level) {
55677069830aSAlexander Block 			cmp = btrfs_comp_cpu_keys(&left_key, &right_key);
55687069830aSAlexander Block 			if (cmp < 0) {
55697069830aSAlexander Block 				advance_left = ADVANCE;
55707069830aSAlexander Block 			} else if (cmp > 0) {
55717069830aSAlexander Block 				advance_right = ADVANCE;
55727069830aSAlexander Block 			} else {
55737069830aSAlexander Block 				left_blockptr = btrfs_node_blockptr(
55747069830aSAlexander Block 						left_path->nodes[left_level],
55757069830aSAlexander Block 						left_path->slots[left_level]);
55767069830aSAlexander Block 				right_blockptr = btrfs_node_blockptr(
55777069830aSAlexander Block 						right_path->nodes[right_level],
55787069830aSAlexander Block 						right_path->slots[right_level]);
55796baa4293SFilipe Manana 				left_gen = btrfs_node_ptr_generation(
55806baa4293SFilipe Manana 						left_path->nodes[left_level],
55816baa4293SFilipe Manana 						left_path->slots[left_level]);
55826baa4293SFilipe Manana 				right_gen = btrfs_node_ptr_generation(
55836baa4293SFilipe Manana 						right_path->nodes[right_level],
55846baa4293SFilipe Manana 						right_path->slots[right_level]);
55856baa4293SFilipe Manana 				if (left_blockptr == right_blockptr &&
55866baa4293SFilipe Manana 				    left_gen == right_gen) {
55877069830aSAlexander Block 					/*
55887069830aSAlexander Block 					 * As we're on a shared block, don't
55897069830aSAlexander Block 					 * allow to go deeper.
55907069830aSAlexander Block 					 */
55917069830aSAlexander Block 					advance_left = ADVANCE_ONLY_NEXT;
55927069830aSAlexander Block 					advance_right = ADVANCE_ONLY_NEXT;
55937069830aSAlexander Block 				} else {
55947069830aSAlexander Block 					advance_left = ADVANCE;
55957069830aSAlexander Block 					advance_right = ADVANCE;
55967069830aSAlexander Block 				}
55977069830aSAlexander Block 			}
55987069830aSAlexander Block 		} else if (left_level < right_level) {
55997069830aSAlexander Block 			advance_right = ADVANCE;
56007069830aSAlexander Block 		} else {
56017069830aSAlexander Block 			advance_left = ADVANCE;
56027069830aSAlexander Block 		}
56037069830aSAlexander Block 	}
56047069830aSAlexander Block 
56057069830aSAlexander Block out:
56067069830aSAlexander Block 	btrfs_free_path(left_path);
56077069830aSAlexander Block 	btrfs_free_path(right_path);
56088f282f71SDavid Sterba 	kvfree(tmp_buf);
56097069830aSAlexander Block 	return ret;
56107069830aSAlexander Block }
56117069830aSAlexander Block 
56123f157a2fSChris Mason /*
56133f157a2fSChris Mason  * this is similar to btrfs_next_leaf, but does not try to preserve
56143f157a2fSChris Mason  * and fixup the path.  It looks for and returns the next key in the
5615de78b51aSEric Sandeen  * tree based on the current path and the min_trans parameters.
56163f157a2fSChris Mason  *
56173f157a2fSChris Mason  * 0 is returned if another key is found, < 0 if there are any errors
56183f157a2fSChris Mason  * and 1 is returned if there are no higher keys in the tree
56193f157a2fSChris Mason  *
56203f157a2fSChris Mason  * path->keep_locks should be set to 1 on the search made before
56213f157a2fSChris Mason  * calling this function.
56223f157a2fSChris Mason  */
5623e7a84565SChris Mason int btrfs_find_next_key(struct btrfs_root *root, struct btrfs_path *path,
5624de78b51aSEric Sandeen 			struct btrfs_key *key, int level, u64 min_trans)
5625e7a84565SChris Mason {
5626e7a84565SChris Mason 	int slot;
5627e7a84565SChris Mason 	struct extent_buffer *c;
5628e7a84565SChris Mason 
5629934d375bSChris Mason 	WARN_ON(!path->keep_locks);
5630e7a84565SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
5631e7a84565SChris Mason 		if (!path->nodes[level])
5632e7a84565SChris Mason 			return 1;
5633e7a84565SChris Mason 
5634e7a84565SChris Mason 		slot = path->slots[level] + 1;
5635e7a84565SChris Mason 		c = path->nodes[level];
56363f157a2fSChris Mason next:
5637e7a84565SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
563833c66f43SYan Zheng 			int ret;
563933c66f43SYan Zheng 			int orig_lowest;
564033c66f43SYan Zheng 			struct btrfs_key cur_key;
564133c66f43SYan Zheng 			if (level + 1 >= BTRFS_MAX_LEVEL ||
564233c66f43SYan Zheng 			    !path->nodes[level + 1])
5643e7a84565SChris Mason 				return 1;
564433c66f43SYan Zheng 
564533c66f43SYan Zheng 			if (path->locks[level + 1]) {
564633c66f43SYan Zheng 				level++;
5647e7a84565SChris Mason 				continue;
5648e7a84565SChris Mason 			}
564933c66f43SYan Zheng 
565033c66f43SYan Zheng 			slot = btrfs_header_nritems(c) - 1;
565133c66f43SYan Zheng 			if (level == 0)
565233c66f43SYan Zheng 				btrfs_item_key_to_cpu(c, &cur_key, slot);
565333c66f43SYan Zheng 			else
565433c66f43SYan Zheng 				btrfs_node_key_to_cpu(c, &cur_key, slot);
565533c66f43SYan Zheng 
565633c66f43SYan Zheng 			orig_lowest = path->lowest_level;
5657b3b4aa74SDavid Sterba 			btrfs_release_path(path);
565833c66f43SYan Zheng 			path->lowest_level = level;
565933c66f43SYan Zheng 			ret = btrfs_search_slot(NULL, root, &cur_key, path,
566033c66f43SYan Zheng 						0, 0);
566133c66f43SYan Zheng 			path->lowest_level = orig_lowest;
566233c66f43SYan Zheng 			if (ret < 0)
566333c66f43SYan Zheng 				return ret;
566433c66f43SYan Zheng 
566533c66f43SYan Zheng 			c = path->nodes[level];
566633c66f43SYan Zheng 			slot = path->slots[level];
566733c66f43SYan Zheng 			if (ret == 0)
566833c66f43SYan Zheng 				slot++;
566933c66f43SYan Zheng 			goto next;
567033c66f43SYan Zheng 		}
567133c66f43SYan Zheng 
5672e7a84565SChris Mason 		if (level == 0)
5673e7a84565SChris Mason 			btrfs_item_key_to_cpu(c, key, slot);
56743f157a2fSChris Mason 		else {
56753f157a2fSChris Mason 			u64 gen = btrfs_node_ptr_generation(c, slot);
56763f157a2fSChris Mason 
56773f157a2fSChris Mason 			if (gen < min_trans) {
56783f157a2fSChris Mason 				slot++;
56793f157a2fSChris Mason 				goto next;
56803f157a2fSChris Mason 			}
5681e7a84565SChris Mason 			btrfs_node_key_to_cpu(c, key, slot);
56823f157a2fSChris Mason 		}
5683e7a84565SChris Mason 		return 0;
5684e7a84565SChris Mason 	}
5685e7a84565SChris Mason 	return 1;
5686e7a84565SChris Mason }
5687e7a84565SChris Mason 
56887bb86316SChris Mason /*
5689925baeddSChris Mason  * search the tree again to find a leaf with greater keys
56900f70abe2SChris Mason  * returns 0 if it found something or 1 if there are no greater leaves.
56910f70abe2SChris Mason  * returns < 0 on io errors.
569297571fd0SChris Mason  */
5693234b63a0SChris Mason int btrfs_next_leaf(struct btrfs_root *root, struct btrfs_path *path)
5694d97e63b6SChris Mason {
56953d7806ecSJan Schmidt 	return btrfs_next_old_leaf(root, path, 0);
56963d7806ecSJan Schmidt }
56973d7806ecSJan Schmidt 
56983d7806ecSJan Schmidt int btrfs_next_old_leaf(struct btrfs_root *root, struct btrfs_path *path,
56993d7806ecSJan Schmidt 			u64 time_seq)
57003d7806ecSJan Schmidt {
5701d97e63b6SChris Mason 	int slot;
57028e73f275SChris Mason 	int level;
57035f39d397SChris Mason 	struct extent_buffer *c;
57048e73f275SChris Mason 	struct extent_buffer *next;
5705925baeddSChris Mason 	struct btrfs_key key;
5706925baeddSChris Mason 	u32 nritems;
5707925baeddSChris Mason 	int ret;
57088e73f275SChris Mason 	int old_spinning = path->leave_spinning;
5709bd681513SChris Mason 	int next_rw_lock = 0;
5710925baeddSChris Mason 
5711925baeddSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
5712d397712bSChris Mason 	if (nritems == 0)
5713925baeddSChris Mason 		return 1;
5714925baeddSChris Mason 
57158e73f275SChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, nritems - 1);
57168e73f275SChris Mason again:
57178e73f275SChris Mason 	level = 1;
57188e73f275SChris Mason 	next = NULL;
5719bd681513SChris Mason 	next_rw_lock = 0;
5720b3b4aa74SDavid Sterba 	btrfs_release_path(path);
57218e73f275SChris Mason 
5722a2135011SChris Mason 	path->keep_locks = 1;
57238e73f275SChris Mason 	path->leave_spinning = 1;
57248e73f275SChris Mason 
57253d7806ecSJan Schmidt 	if (time_seq)
57263d7806ecSJan Schmidt 		ret = btrfs_search_old_slot(root, &key, path, time_seq);
57273d7806ecSJan Schmidt 	else
5728925baeddSChris Mason 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5729925baeddSChris Mason 	path->keep_locks = 0;
5730925baeddSChris Mason 
5731925baeddSChris Mason 	if (ret < 0)
5732925baeddSChris Mason 		return ret;
5733925baeddSChris Mason 
5734a2135011SChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
5735168fd7d2SChris Mason 	/*
5736168fd7d2SChris Mason 	 * by releasing the path above we dropped all our locks.  A balance
5737168fd7d2SChris Mason 	 * could have added more items next to the key that used to be
5738168fd7d2SChris Mason 	 * at the very end of the block.  So, check again here and
5739168fd7d2SChris Mason 	 * advance the path if there are now more items available.
5740168fd7d2SChris Mason 	 */
5741a2135011SChris Mason 	if (nritems > 0 && path->slots[0] < nritems - 1) {
5742e457afecSYan Zheng 		if (ret == 0)
5743168fd7d2SChris Mason 			path->slots[0]++;
57448e73f275SChris Mason 		ret = 0;
5745925baeddSChris Mason 		goto done;
5746925baeddSChris Mason 	}
57470b43e04fSLiu Bo 	/*
57480b43e04fSLiu Bo 	 * So the above check misses one case:
57490b43e04fSLiu Bo 	 * - after releasing the path above, someone has removed the item that
57500b43e04fSLiu Bo 	 *   used to be at the very end of the block, and balance between leafs
57510b43e04fSLiu Bo 	 *   gets another one with bigger key.offset to replace it.
57520b43e04fSLiu Bo 	 *
57530b43e04fSLiu Bo 	 * This one should be returned as well, or we can get leaf corruption
57540b43e04fSLiu Bo 	 * later(esp. in __btrfs_drop_extents()).
57550b43e04fSLiu Bo 	 *
57560b43e04fSLiu Bo 	 * And a bit more explanation about this check,
57570b43e04fSLiu Bo 	 * with ret > 0, the key isn't found, the path points to the slot
57580b43e04fSLiu Bo 	 * where it should be inserted, so the path->slots[0] item must be the
57590b43e04fSLiu Bo 	 * bigger one.
57600b43e04fSLiu Bo 	 */
57610b43e04fSLiu Bo 	if (nritems > 0 && ret > 0 && path->slots[0] == nritems - 1) {
57620b43e04fSLiu Bo 		ret = 0;
57630b43e04fSLiu Bo 		goto done;
57640b43e04fSLiu Bo 	}
5765d97e63b6SChris Mason 
5766234b63a0SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
57678e73f275SChris Mason 		if (!path->nodes[level]) {
57688e73f275SChris Mason 			ret = 1;
57698e73f275SChris Mason 			goto done;
57708e73f275SChris Mason 		}
57715f39d397SChris Mason 
5772d97e63b6SChris Mason 		slot = path->slots[level] + 1;
5773d97e63b6SChris Mason 		c = path->nodes[level];
57745f39d397SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
5775d97e63b6SChris Mason 			level++;
57768e73f275SChris Mason 			if (level == BTRFS_MAX_LEVEL) {
57778e73f275SChris Mason 				ret = 1;
57788e73f275SChris Mason 				goto done;
57798e73f275SChris Mason 			}
5780d97e63b6SChris Mason 			continue;
5781d97e63b6SChris Mason 		}
57825f39d397SChris Mason 
5783925baeddSChris Mason 		if (next) {
5784bd681513SChris Mason 			btrfs_tree_unlock_rw(next, next_rw_lock);
57855f39d397SChris Mason 			free_extent_buffer(next);
5786925baeddSChris Mason 		}
57875f39d397SChris Mason 
57888e73f275SChris Mason 		next = c;
5789bd681513SChris Mason 		next_rw_lock = path->locks[level];
57908e73f275SChris Mason 		ret = read_block_for_search(NULL, root, path, &next, level,
57915d9e75c4SJan Schmidt 					    slot, &key, 0);
57928e73f275SChris Mason 		if (ret == -EAGAIN)
57938e73f275SChris Mason 			goto again;
57945f39d397SChris Mason 
579576a05b35SChris Mason 		if (ret < 0) {
5796b3b4aa74SDavid Sterba 			btrfs_release_path(path);
579776a05b35SChris Mason 			goto done;
579876a05b35SChris Mason 		}
579976a05b35SChris Mason 
58005cd57b2cSChris Mason 		if (!path->skip_locking) {
5801bd681513SChris Mason 			ret = btrfs_try_tree_read_lock(next);
5802d42244a0SJan Schmidt 			if (!ret && time_seq) {
5803d42244a0SJan Schmidt 				/*
5804d42244a0SJan Schmidt 				 * If we don't get the lock, we may be racing
5805d42244a0SJan Schmidt 				 * with push_leaf_left, holding that lock while
5806d42244a0SJan Schmidt 				 * itself waiting for the leaf we've currently
5807d42244a0SJan Schmidt 				 * locked. To solve this situation, we give up
5808d42244a0SJan Schmidt 				 * on our lock and cycle.
5809d42244a0SJan Schmidt 				 */
5810cf538830SJan Schmidt 				free_extent_buffer(next);
5811d42244a0SJan Schmidt 				btrfs_release_path(path);
5812d42244a0SJan Schmidt 				cond_resched();
5813d42244a0SJan Schmidt 				goto again;
5814d42244a0SJan Schmidt 			}
58158e73f275SChris Mason 			if (!ret) {
58168e73f275SChris Mason 				btrfs_set_path_blocking(path);
5817bd681513SChris Mason 				btrfs_tree_read_lock(next);
5818bd681513SChris Mason 				btrfs_clear_path_blocking(path, next,
5819bd681513SChris Mason 							  BTRFS_READ_LOCK);
58208e73f275SChris Mason 			}
5821bd681513SChris Mason 			next_rw_lock = BTRFS_READ_LOCK;
5822bd681513SChris Mason 		}
5823d97e63b6SChris Mason 		break;
5824d97e63b6SChris Mason 	}
5825d97e63b6SChris Mason 	path->slots[level] = slot;
5826d97e63b6SChris Mason 	while (1) {
5827d97e63b6SChris Mason 		level--;
5828d97e63b6SChris Mason 		c = path->nodes[level];
5829925baeddSChris Mason 		if (path->locks[level])
5830bd681513SChris Mason 			btrfs_tree_unlock_rw(c, path->locks[level]);
58318e73f275SChris Mason 
58325f39d397SChris Mason 		free_extent_buffer(c);
5833d97e63b6SChris Mason 		path->nodes[level] = next;
5834d97e63b6SChris Mason 		path->slots[level] = 0;
5835a74a4b97SChris Mason 		if (!path->skip_locking)
5836bd681513SChris Mason 			path->locks[level] = next_rw_lock;
5837d97e63b6SChris Mason 		if (!level)
5838d97e63b6SChris Mason 			break;
5839b4ce94deSChris Mason 
58408e73f275SChris Mason 		ret = read_block_for_search(NULL, root, path, &next, level,
58415d9e75c4SJan Schmidt 					    0, &key, 0);
58428e73f275SChris Mason 		if (ret == -EAGAIN)
58438e73f275SChris Mason 			goto again;
58448e73f275SChris Mason 
584576a05b35SChris Mason 		if (ret < 0) {
5846b3b4aa74SDavid Sterba 			btrfs_release_path(path);
584776a05b35SChris Mason 			goto done;
584876a05b35SChris Mason 		}
584976a05b35SChris Mason 
58505cd57b2cSChris Mason 		if (!path->skip_locking) {
5851bd681513SChris Mason 			ret = btrfs_try_tree_read_lock(next);
58528e73f275SChris Mason 			if (!ret) {
58538e73f275SChris Mason 				btrfs_set_path_blocking(path);
5854bd681513SChris Mason 				btrfs_tree_read_lock(next);
5855bd681513SChris Mason 				btrfs_clear_path_blocking(path, next,
5856bd681513SChris Mason 							  BTRFS_READ_LOCK);
58578e73f275SChris Mason 			}
5858bd681513SChris Mason 			next_rw_lock = BTRFS_READ_LOCK;
5859bd681513SChris Mason 		}
5860d97e63b6SChris Mason 	}
58618e73f275SChris Mason 	ret = 0;
5862925baeddSChris Mason done:
5863f7c79f30SChris Mason 	unlock_up(path, 0, 1, 0, NULL);
58648e73f275SChris Mason 	path->leave_spinning = old_spinning;
58658e73f275SChris Mason 	if (!old_spinning)
58668e73f275SChris Mason 		btrfs_set_path_blocking(path);
58678e73f275SChris Mason 
58688e73f275SChris Mason 	return ret;
5869d97e63b6SChris Mason }
58700b86a832SChris Mason 
58713f157a2fSChris Mason /*
58723f157a2fSChris Mason  * this uses btrfs_prev_leaf to walk backwards in the tree, and keeps
58733f157a2fSChris Mason  * searching until it gets past min_objectid or finds an item of 'type'
58743f157a2fSChris Mason  *
58753f157a2fSChris Mason  * returns 0 if something is found, 1 if nothing was found and < 0 on error
58763f157a2fSChris Mason  */
58770b86a832SChris Mason int btrfs_previous_item(struct btrfs_root *root,
58780b86a832SChris Mason 			struct btrfs_path *path, u64 min_objectid,
58790b86a832SChris Mason 			int type)
58800b86a832SChris Mason {
58810b86a832SChris Mason 	struct btrfs_key found_key;
58820b86a832SChris Mason 	struct extent_buffer *leaf;
5883e02119d5SChris Mason 	u32 nritems;
58840b86a832SChris Mason 	int ret;
58850b86a832SChris Mason 
58860b86a832SChris Mason 	while (1) {
58870b86a832SChris Mason 		if (path->slots[0] == 0) {
5888b4ce94deSChris Mason 			btrfs_set_path_blocking(path);
58890b86a832SChris Mason 			ret = btrfs_prev_leaf(root, path);
58900b86a832SChris Mason 			if (ret != 0)
58910b86a832SChris Mason 				return ret;
58920b86a832SChris Mason 		} else {
58930b86a832SChris Mason 			path->slots[0]--;
58940b86a832SChris Mason 		}
58950b86a832SChris Mason 		leaf = path->nodes[0];
5896e02119d5SChris Mason 		nritems = btrfs_header_nritems(leaf);
5897e02119d5SChris Mason 		if (nritems == 0)
5898e02119d5SChris Mason 			return 1;
5899e02119d5SChris Mason 		if (path->slots[0] == nritems)
5900e02119d5SChris Mason 			path->slots[0]--;
5901e02119d5SChris Mason 
59020b86a832SChris Mason 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5903e02119d5SChris Mason 		if (found_key.objectid < min_objectid)
5904e02119d5SChris Mason 			break;
59050a4eefbbSYan Zheng 		if (found_key.type == type)
59060a4eefbbSYan Zheng 			return 0;
5907e02119d5SChris Mason 		if (found_key.objectid == min_objectid &&
5908e02119d5SChris Mason 		    found_key.type < type)
5909e02119d5SChris Mason 			break;
59100b86a832SChris Mason 	}
59110b86a832SChris Mason 	return 1;
59120b86a832SChris Mason }
5913ade2e0b3SWang Shilong 
5914ade2e0b3SWang Shilong /*
5915ade2e0b3SWang Shilong  * search in extent tree to find a previous Metadata/Data extent item with
5916ade2e0b3SWang Shilong  * min objecitd.
5917ade2e0b3SWang Shilong  *
5918ade2e0b3SWang Shilong  * returns 0 if something is found, 1 if nothing was found and < 0 on error
5919ade2e0b3SWang Shilong  */
5920ade2e0b3SWang Shilong int btrfs_previous_extent_item(struct btrfs_root *root,
5921ade2e0b3SWang Shilong 			struct btrfs_path *path, u64 min_objectid)
5922ade2e0b3SWang Shilong {
5923ade2e0b3SWang Shilong 	struct btrfs_key found_key;
5924ade2e0b3SWang Shilong 	struct extent_buffer *leaf;
5925ade2e0b3SWang Shilong 	u32 nritems;
5926ade2e0b3SWang Shilong 	int ret;
5927ade2e0b3SWang Shilong 
5928ade2e0b3SWang Shilong 	while (1) {
5929ade2e0b3SWang Shilong 		if (path->slots[0] == 0) {
5930ade2e0b3SWang Shilong 			btrfs_set_path_blocking(path);
5931ade2e0b3SWang Shilong 			ret = btrfs_prev_leaf(root, path);
5932ade2e0b3SWang Shilong 			if (ret != 0)
5933ade2e0b3SWang Shilong 				return ret;
5934ade2e0b3SWang Shilong 		} else {
5935ade2e0b3SWang Shilong 			path->slots[0]--;
5936ade2e0b3SWang Shilong 		}
5937ade2e0b3SWang Shilong 		leaf = path->nodes[0];
5938ade2e0b3SWang Shilong 		nritems = btrfs_header_nritems(leaf);
5939ade2e0b3SWang Shilong 		if (nritems == 0)
5940ade2e0b3SWang Shilong 			return 1;
5941ade2e0b3SWang Shilong 		if (path->slots[0] == nritems)
5942ade2e0b3SWang Shilong 			path->slots[0]--;
5943ade2e0b3SWang Shilong 
5944ade2e0b3SWang Shilong 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5945ade2e0b3SWang Shilong 		if (found_key.objectid < min_objectid)
5946ade2e0b3SWang Shilong 			break;
5947ade2e0b3SWang Shilong 		if (found_key.type == BTRFS_EXTENT_ITEM_KEY ||
5948ade2e0b3SWang Shilong 		    found_key.type == BTRFS_METADATA_ITEM_KEY)
5949ade2e0b3SWang Shilong 			return 0;
5950ade2e0b3SWang Shilong 		if (found_key.objectid == min_objectid &&
5951ade2e0b3SWang Shilong 		    found_key.type < BTRFS_EXTENT_ITEM_KEY)
5952ade2e0b3SWang Shilong 			break;
5953ade2e0b3SWang Shilong 	}
5954ade2e0b3SWang Shilong 	return 1;
5955ade2e0b3SWang Shilong }
5956