xref: /openbmc/linux/fs/btrfs/ctree.c (revision ce86cd59179279a6fe673d2a105d24fb7e70aef3)
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>
22eb60ceacSChris Mason #include "ctree.h"
23eb60ceacSChris Mason #include "disk-io.h"
247f5c1516SChris Mason #include "transaction.h"
255f39d397SChris Mason #include "print-tree.h"
26925baeddSChris Mason #include "locking.h"
279a8dd150SChris Mason 
28e089f05cSChris Mason static int split_node(struct btrfs_trans_handle *trans, struct btrfs_root
29e089f05cSChris Mason 		      *root, struct btrfs_path *path, int level);
30e089f05cSChris Mason static int split_leaf(struct btrfs_trans_handle *trans, struct btrfs_root
31d4dbff95SChris Mason 		      *root, struct btrfs_key *ins_key,
32cc0c5538SChris Mason 		      struct btrfs_path *path, int data_size, int extend);
335f39d397SChris Mason static int push_node_left(struct btrfs_trans_handle *trans,
345f39d397SChris Mason 			  struct btrfs_root *root, struct extent_buffer *dst,
35971a1f66SChris Mason 			  struct extent_buffer *src, int empty);
365f39d397SChris Mason static int balance_node_right(struct btrfs_trans_handle *trans,
375f39d397SChris Mason 			      struct btrfs_root *root,
385f39d397SChris Mason 			      struct extent_buffer *dst_buf,
395f39d397SChris Mason 			      struct extent_buffer *src_buf);
40afe5fea7STsutomu Itoh static void del_ptr(struct btrfs_root *root, struct btrfs_path *path,
41afe5fea7STsutomu Itoh 		    int level, int slot);
425de865eeSFilipe David Borba Manana static int tree_mod_log_free_eb(struct btrfs_fs_info *fs_info,
43f230475eSJan Schmidt 				 struct extent_buffer *eb);
44d97e63b6SChris Mason 
452c90e5d6SChris Mason struct btrfs_path *btrfs_alloc_path(void)
462c90e5d6SChris Mason {
47df24a2b9SChris Mason 	struct btrfs_path *path;
48e00f7308SJeff Mahoney 	path = kmem_cache_zalloc(btrfs_path_cachep, GFP_NOFS);
49df24a2b9SChris Mason 	return path;
502c90e5d6SChris Mason }
512c90e5d6SChris Mason 
52b4ce94deSChris Mason /*
53b4ce94deSChris Mason  * set all locked nodes in the path to blocking locks.  This should
54b4ce94deSChris Mason  * be done before scheduling
55b4ce94deSChris Mason  */
56b4ce94deSChris Mason noinline void btrfs_set_path_blocking(struct btrfs_path *p)
57b4ce94deSChris Mason {
58b4ce94deSChris Mason 	int i;
59b4ce94deSChris Mason 	for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
60bd681513SChris Mason 		if (!p->nodes[i] || !p->locks[i])
61bd681513SChris Mason 			continue;
62bd681513SChris Mason 		btrfs_set_lock_blocking_rw(p->nodes[i], p->locks[i]);
63bd681513SChris Mason 		if (p->locks[i] == BTRFS_READ_LOCK)
64bd681513SChris Mason 			p->locks[i] = BTRFS_READ_LOCK_BLOCKING;
65bd681513SChris Mason 		else if (p->locks[i] == BTRFS_WRITE_LOCK)
66bd681513SChris Mason 			p->locks[i] = BTRFS_WRITE_LOCK_BLOCKING;
67b4ce94deSChris Mason 	}
68b4ce94deSChris Mason }
69b4ce94deSChris Mason 
70b4ce94deSChris Mason /*
71b4ce94deSChris Mason  * reset all the locked nodes in the patch to spinning locks.
724008c04aSChris Mason  *
734008c04aSChris Mason  * held is used to keep lockdep happy, when lockdep is enabled
744008c04aSChris Mason  * we set held to a blocking lock before we go around and
754008c04aSChris Mason  * retake all the spinlocks in the path.  You can safely use NULL
764008c04aSChris Mason  * for held
77b4ce94deSChris Mason  */
784008c04aSChris Mason noinline void btrfs_clear_path_blocking(struct btrfs_path *p,
79bd681513SChris Mason 					struct extent_buffer *held, int held_rw)
80b4ce94deSChris Mason {
81b4ce94deSChris Mason 	int i;
824008c04aSChris Mason 
834008c04aSChris Mason #ifdef CONFIG_DEBUG_LOCK_ALLOC
844008c04aSChris Mason 	/* lockdep really cares that we take all of these spinlocks
854008c04aSChris Mason 	 * in the right order.  If any of the locks in the path are not
864008c04aSChris Mason 	 * currently blocking, it is going to complain.  So, make really
874008c04aSChris Mason 	 * really sure by forcing the path to blocking before we clear
884008c04aSChris Mason 	 * the path blocking.
894008c04aSChris Mason 	 */
90bd681513SChris Mason 	if (held) {
91bd681513SChris Mason 		btrfs_set_lock_blocking_rw(held, held_rw);
92bd681513SChris Mason 		if (held_rw == BTRFS_WRITE_LOCK)
93bd681513SChris Mason 			held_rw = BTRFS_WRITE_LOCK_BLOCKING;
94bd681513SChris Mason 		else if (held_rw == BTRFS_READ_LOCK)
95bd681513SChris Mason 			held_rw = BTRFS_READ_LOCK_BLOCKING;
96bd681513SChris Mason 	}
974008c04aSChris Mason 	btrfs_set_path_blocking(p);
984008c04aSChris Mason #endif
994008c04aSChris Mason 
1004008c04aSChris Mason 	for (i = BTRFS_MAX_LEVEL - 1; i >= 0; i--) {
101bd681513SChris Mason 		if (p->nodes[i] && p->locks[i]) {
102bd681513SChris Mason 			btrfs_clear_lock_blocking_rw(p->nodes[i], p->locks[i]);
103bd681513SChris Mason 			if (p->locks[i] == BTRFS_WRITE_LOCK_BLOCKING)
104bd681513SChris Mason 				p->locks[i] = BTRFS_WRITE_LOCK;
105bd681513SChris Mason 			else if (p->locks[i] == BTRFS_READ_LOCK_BLOCKING)
106bd681513SChris Mason 				p->locks[i] = BTRFS_READ_LOCK;
107bd681513SChris Mason 		}
108b4ce94deSChris Mason 	}
1094008c04aSChris Mason 
1104008c04aSChris Mason #ifdef CONFIG_DEBUG_LOCK_ALLOC
1114008c04aSChris Mason 	if (held)
112bd681513SChris Mason 		btrfs_clear_lock_blocking_rw(held, held_rw);
1134008c04aSChris Mason #endif
114b4ce94deSChris Mason }
115b4ce94deSChris Mason 
116d352ac68SChris Mason /* this also releases the path */
1172c90e5d6SChris Mason void btrfs_free_path(struct btrfs_path *p)
1182c90e5d6SChris Mason {
119ff175d57SJesper Juhl 	if (!p)
120ff175d57SJesper Juhl 		return;
121b3b4aa74SDavid Sterba 	btrfs_release_path(p);
1222c90e5d6SChris Mason 	kmem_cache_free(btrfs_path_cachep, p);
1232c90e5d6SChris Mason }
1242c90e5d6SChris Mason 
125d352ac68SChris Mason /*
126d352ac68SChris Mason  * path release drops references on the extent buffers in the path
127d352ac68SChris Mason  * and it drops any locks held by this path
128d352ac68SChris Mason  *
129d352ac68SChris Mason  * It is safe to call this on paths that no locks or extent buffers held.
130d352ac68SChris Mason  */
131b3b4aa74SDavid Sterba noinline void btrfs_release_path(struct btrfs_path *p)
132eb60ceacSChris Mason {
133eb60ceacSChris Mason 	int i;
134a2135011SChris Mason 
135234b63a0SChris Mason 	for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
1363f157a2fSChris Mason 		p->slots[i] = 0;
137eb60ceacSChris Mason 		if (!p->nodes[i])
138925baeddSChris Mason 			continue;
139925baeddSChris Mason 		if (p->locks[i]) {
140bd681513SChris Mason 			btrfs_tree_unlock_rw(p->nodes[i], p->locks[i]);
141925baeddSChris Mason 			p->locks[i] = 0;
142925baeddSChris Mason 		}
1435f39d397SChris Mason 		free_extent_buffer(p->nodes[i]);
1443f157a2fSChris Mason 		p->nodes[i] = NULL;
145eb60ceacSChris Mason 	}
146eb60ceacSChris Mason }
147eb60ceacSChris Mason 
148d352ac68SChris Mason /*
149d352ac68SChris Mason  * safely gets a reference on the root node of a tree.  A lock
150d352ac68SChris Mason  * is not taken, so a concurrent writer may put a different node
151d352ac68SChris Mason  * at the root of the tree.  See btrfs_lock_root_node for the
152d352ac68SChris Mason  * looping required.
153d352ac68SChris Mason  *
154d352ac68SChris Mason  * The extent buffer returned by this has a reference taken, so
155d352ac68SChris Mason  * it won't disappear.  It may stop being the root of the tree
156d352ac68SChris Mason  * at any time because there are no locks held.
157d352ac68SChris Mason  */
158925baeddSChris Mason struct extent_buffer *btrfs_root_node(struct btrfs_root *root)
159925baeddSChris Mason {
160925baeddSChris Mason 	struct extent_buffer *eb;
161240f62c8SChris Mason 
1623083ee2eSJosef Bacik 	while (1) {
163240f62c8SChris Mason 		rcu_read_lock();
164240f62c8SChris Mason 		eb = rcu_dereference(root->node);
1653083ee2eSJosef Bacik 
1663083ee2eSJosef Bacik 		/*
1673083ee2eSJosef Bacik 		 * RCU really hurts here, we could free up the root node because
1683083ee2eSJosef Bacik 		 * it was cow'ed but we may not get the new root node yet so do
1693083ee2eSJosef Bacik 		 * the inc_not_zero dance and if it doesn't work then
1703083ee2eSJosef Bacik 		 * synchronize_rcu and try again.
1713083ee2eSJosef Bacik 		 */
1723083ee2eSJosef Bacik 		if (atomic_inc_not_zero(&eb->refs)) {
173240f62c8SChris Mason 			rcu_read_unlock();
1743083ee2eSJosef Bacik 			break;
1753083ee2eSJosef Bacik 		}
1763083ee2eSJosef Bacik 		rcu_read_unlock();
1773083ee2eSJosef Bacik 		synchronize_rcu();
1783083ee2eSJosef Bacik 	}
179925baeddSChris Mason 	return eb;
180925baeddSChris Mason }
181925baeddSChris Mason 
182d352ac68SChris Mason /* loop around taking references on and locking the root node of the
183d352ac68SChris Mason  * tree until you end up with a lock on the root.  A locked buffer
184d352ac68SChris Mason  * is returned, with a reference held.
185d352ac68SChris Mason  */
186925baeddSChris Mason struct extent_buffer *btrfs_lock_root_node(struct btrfs_root *root)
187925baeddSChris Mason {
188925baeddSChris Mason 	struct extent_buffer *eb;
189925baeddSChris Mason 
190925baeddSChris Mason 	while (1) {
191925baeddSChris Mason 		eb = btrfs_root_node(root);
192925baeddSChris Mason 		btrfs_tree_lock(eb);
193240f62c8SChris Mason 		if (eb == root->node)
194925baeddSChris Mason 			break;
195925baeddSChris Mason 		btrfs_tree_unlock(eb);
196925baeddSChris Mason 		free_extent_buffer(eb);
197925baeddSChris Mason 	}
198925baeddSChris Mason 	return eb;
199925baeddSChris Mason }
200925baeddSChris Mason 
201bd681513SChris Mason /* loop around taking references on and locking the root node of the
202bd681513SChris Mason  * tree until you end up with a lock on the root.  A locked buffer
203bd681513SChris Mason  * is returned, with a reference held.
204bd681513SChris Mason  */
20548a3b636SEric Sandeen static struct extent_buffer *btrfs_read_lock_root_node(struct btrfs_root *root)
206bd681513SChris Mason {
207bd681513SChris Mason 	struct extent_buffer *eb;
208bd681513SChris Mason 
209bd681513SChris Mason 	while (1) {
210bd681513SChris Mason 		eb = btrfs_root_node(root);
211bd681513SChris Mason 		btrfs_tree_read_lock(eb);
212bd681513SChris Mason 		if (eb == root->node)
213bd681513SChris Mason 			break;
214bd681513SChris Mason 		btrfs_tree_read_unlock(eb);
215bd681513SChris Mason 		free_extent_buffer(eb);
216bd681513SChris Mason 	}
217bd681513SChris Mason 	return eb;
218bd681513SChris Mason }
219bd681513SChris Mason 
220d352ac68SChris Mason /* cowonly root (everything not a reference counted cow subvolume), just get
221d352ac68SChris Mason  * put onto a simple dirty list.  transaction.c walks this to make sure they
222d352ac68SChris Mason  * get properly updated on disk.
223d352ac68SChris Mason  */
2240b86a832SChris Mason static void add_root_to_dirty_list(struct btrfs_root *root)
2250b86a832SChris Mason {
226e5846fc6SChris Mason 	spin_lock(&root->fs_info->trans_lock);
22727cdeb70SMiao Xie 	if (test_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state) &&
22827cdeb70SMiao Xie 	    list_empty(&root->dirty_list)) {
2290b86a832SChris Mason 		list_add(&root->dirty_list,
2300b86a832SChris Mason 			 &root->fs_info->dirty_cowonly_roots);
2310b86a832SChris Mason 	}
232e5846fc6SChris Mason 	spin_unlock(&root->fs_info->trans_lock);
2330b86a832SChris Mason }
2340b86a832SChris Mason 
235d352ac68SChris Mason /*
236d352ac68SChris Mason  * used by snapshot creation to make a copy of a root for a tree with
237d352ac68SChris Mason  * a given objectid.  The buffer with the new root node is returned in
238d352ac68SChris Mason  * cow_ret, and this func returns zero on success or a negative error code.
239d352ac68SChris Mason  */
240be20aa9dSChris Mason int btrfs_copy_root(struct btrfs_trans_handle *trans,
241be20aa9dSChris Mason 		      struct btrfs_root *root,
242be20aa9dSChris Mason 		      struct extent_buffer *buf,
243be20aa9dSChris Mason 		      struct extent_buffer **cow_ret, u64 new_root_objectid)
244be20aa9dSChris Mason {
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) &&
25127cdeb70SMiao Xie 		trans->transid != root->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 
2615d4f98a2SYan Zheng 	cow = btrfs_alloc_free_block(trans, root, buf->len, 0,
2625d4f98a2SYan Zheng 				     new_root_objectid, &disk_key, level,
2635581a51aSJan Schmidt 				     buf->start, 0);
2645d4f98a2SYan Zheng 	if (IS_ERR(cow))
265be20aa9dSChris Mason 		return PTR_ERR(cow);
266be20aa9dSChris Mason 
267be20aa9dSChris Mason 	copy_extent_buffer(cow, buf, 0, 0, cow->len);
268be20aa9dSChris Mason 	btrfs_set_header_bytenr(cow, cow->start);
269be20aa9dSChris Mason 	btrfs_set_header_generation(cow, trans->transid);
2705d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
2715d4f98a2SYan Zheng 	btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
2725d4f98a2SYan Zheng 				     BTRFS_HEADER_FLAG_RELOC);
2735d4f98a2SYan Zheng 	if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
2745d4f98a2SYan Zheng 		btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
2755d4f98a2SYan Zheng 	else
276be20aa9dSChris Mason 		btrfs_set_header_owner(cow, new_root_objectid);
277be20aa9dSChris Mason 
2780a4e5586SRoss Kirk 	write_extent_buffer(cow, root->fs_info->fsid, btrfs_header_fsid(),
2792b82032cSYan Zheng 			    BTRFS_FSID_SIZE);
2802b82032cSYan Zheng 
281be20aa9dSChris Mason 	WARN_ON(btrfs_header_generation(buf) > trans->transid);
2825d4f98a2SYan Zheng 	if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
283e339a6b0SJosef Bacik 		ret = btrfs_inc_ref(trans, root, cow, 1);
2845d4f98a2SYan Zheng 	else
285e339a6b0SJosef Bacik 		ret = btrfs_inc_ref(trans, root, cow, 0);
2864aec2b52SChris Mason 
287be20aa9dSChris Mason 	if (ret)
288be20aa9dSChris Mason 		return ret;
289be20aa9dSChris Mason 
290be20aa9dSChris Mason 	btrfs_mark_buffer_dirty(cow);
291be20aa9dSChris Mason 	*cow_ret = cow;
292be20aa9dSChris Mason 	return 0;
293be20aa9dSChris Mason }
294be20aa9dSChris Mason 
295bd989ba3SJan Schmidt enum mod_log_op {
296bd989ba3SJan Schmidt 	MOD_LOG_KEY_REPLACE,
297bd989ba3SJan Schmidt 	MOD_LOG_KEY_ADD,
298bd989ba3SJan Schmidt 	MOD_LOG_KEY_REMOVE,
299bd989ba3SJan Schmidt 	MOD_LOG_KEY_REMOVE_WHILE_FREEING,
300bd989ba3SJan Schmidt 	MOD_LOG_KEY_REMOVE_WHILE_MOVING,
301bd989ba3SJan Schmidt 	MOD_LOG_MOVE_KEYS,
302bd989ba3SJan Schmidt 	MOD_LOG_ROOT_REPLACE,
303bd989ba3SJan Schmidt };
304bd989ba3SJan Schmidt 
305bd989ba3SJan Schmidt struct tree_mod_move {
306bd989ba3SJan Schmidt 	int dst_slot;
307bd989ba3SJan Schmidt 	int nr_items;
308bd989ba3SJan Schmidt };
309bd989ba3SJan Schmidt 
310bd989ba3SJan Schmidt struct tree_mod_root {
311bd989ba3SJan Schmidt 	u64 logical;
312bd989ba3SJan Schmidt 	u8 level;
313bd989ba3SJan Schmidt };
314bd989ba3SJan Schmidt 
315bd989ba3SJan Schmidt struct tree_mod_elem {
316bd989ba3SJan Schmidt 	struct rb_node node;
317bd989ba3SJan Schmidt 	u64 index;		/* shifted logical */
318097b8a7cSJan Schmidt 	u64 seq;
319bd989ba3SJan Schmidt 	enum mod_log_op op;
320bd989ba3SJan Schmidt 
321bd989ba3SJan Schmidt 	/* this is used for MOD_LOG_KEY_* and MOD_LOG_MOVE_KEYS operations */
322bd989ba3SJan Schmidt 	int slot;
323bd989ba3SJan Schmidt 
324bd989ba3SJan Schmidt 	/* this is used for MOD_LOG_KEY* and MOD_LOG_ROOT_REPLACE */
325bd989ba3SJan Schmidt 	u64 generation;
326bd989ba3SJan Schmidt 
327bd989ba3SJan Schmidt 	/* those are used for op == MOD_LOG_KEY_{REPLACE,REMOVE} */
328bd989ba3SJan Schmidt 	struct btrfs_disk_key key;
329bd989ba3SJan Schmidt 	u64 blockptr;
330bd989ba3SJan Schmidt 
331bd989ba3SJan Schmidt 	/* this is used for op == MOD_LOG_MOVE_KEYS */
332bd989ba3SJan Schmidt 	struct tree_mod_move move;
333bd989ba3SJan Schmidt 
334bd989ba3SJan Schmidt 	/* this is used for op == MOD_LOG_ROOT_REPLACE */
335bd989ba3SJan Schmidt 	struct tree_mod_root old_root;
336bd989ba3SJan Schmidt };
337bd989ba3SJan Schmidt 
338097b8a7cSJan Schmidt static inline void tree_mod_log_read_lock(struct btrfs_fs_info *fs_info)
339bd989ba3SJan Schmidt {
340097b8a7cSJan Schmidt 	read_lock(&fs_info->tree_mod_log_lock);
341bd989ba3SJan Schmidt }
342bd989ba3SJan Schmidt 
343097b8a7cSJan Schmidt static inline void tree_mod_log_read_unlock(struct btrfs_fs_info *fs_info)
344097b8a7cSJan Schmidt {
345097b8a7cSJan Schmidt 	read_unlock(&fs_info->tree_mod_log_lock);
346097b8a7cSJan Schmidt }
347097b8a7cSJan Schmidt 
348097b8a7cSJan Schmidt static inline void tree_mod_log_write_lock(struct btrfs_fs_info *fs_info)
349097b8a7cSJan Schmidt {
350097b8a7cSJan Schmidt 	write_lock(&fs_info->tree_mod_log_lock);
351097b8a7cSJan Schmidt }
352097b8a7cSJan Schmidt 
353097b8a7cSJan Schmidt static inline void tree_mod_log_write_unlock(struct btrfs_fs_info *fs_info)
354097b8a7cSJan Schmidt {
355097b8a7cSJan Schmidt 	write_unlock(&fs_info->tree_mod_log_lock);
356097b8a7cSJan Schmidt }
357097b8a7cSJan Schmidt 
358097b8a7cSJan Schmidt /*
359fcebe456SJosef Bacik  * Pull a new tree mod seq number for our operation.
360fc36ed7eSJan Schmidt  */
361fcebe456SJosef Bacik static inline u64 btrfs_inc_tree_mod_seq(struct btrfs_fs_info *fs_info)
362fc36ed7eSJan Schmidt {
363fc36ed7eSJan Schmidt 	return atomic64_inc_return(&fs_info->tree_mod_seq);
364fc36ed7eSJan Schmidt }
365fc36ed7eSJan Schmidt 
366fc36ed7eSJan Schmidt /*
367097b8a7cSJan Schmidt  * This adds a new blocker to the tree mod log's blocker list if the @elem
368097b8a7cSJan Schmidt  * passed does not already have a sequence number set. So when a caller expects
369097b8a7cSJan Schmidt  * to record tree modifications, it should ensure to set elem->seq to zero
370097b8a7cSJan Schmidt  * before calling btrfs_get_tree_mod_seq.
371097b8a7cSJan Schmidt  * Returns a fresh, unused tree log modification sequence number, even if no new
372097b8a7cSJan Schmidt  * blocker was added.
373097b8a7cSJan Schmidt  */
374097b8a7cSJan Schmidt u64 btrfs_get_tree_mod_seq(struct btrfs_fs_info *fs_info,
375bd989ba3SJan Schmidt 			   struct seq_list *elem)
376bd989ba3SJan Schmidt {
377097b8a7cSJan Schmidt 	tree_mod_log_write_lock(fs_info);
378bd989ba3SJan Schmidt 	spin_lock(&fs_info->tree_mod_seq_lock);
379097b8a7cSJan Schmidt 	if (!elem->seq) {
380fcebe456SJosef Bacik 		elem->seq = btrfs_inc_tree_mod_seq(fs_info);
381097b8a7cSJan Schmidt 		list_add_tail(&elem->list, &fs_info->tree_mod_seq_list);
382097b8a7cSJan Schmidt 	}
383bd989ba3SJan Schmidt 	spin_unlock(&fs_info->tree_mod_seq_lock);
384097b8a7cSJan Schmidt 	tree_mod_log_write_unlock(fs_info);
385097b8a7cSJan Schmidt 
386fcebe456SJosef Bacik 	return elem->seq;
387bd989ba3SJan Schmidt }
388bd989ba3SJan Schmidt 
389bd989ba3SJan Schmidt void btrfs_put_tree_mod_seq(struct btrfs_fs_info *fs_info,
390bd989ba3SJan Schmidt 			    struct seq_list *elem)
391bd989ba3SJan Schmidt {
392bd989ba3SJan Schmidt 	struct rb_root *tm_root;
393bd989ba3SJan Schmidt 	struct rb_node *node;
394bd989ba3SJan Schmidt 	struct rb_node *next;
395bd989ba3SJan Schmidt 	struct seq_list *cur_elem;
396bd989ba3SJan Schmidt 	struct tree_mod_elem *tm;
397bd989ba3SJan Schmidt 	u64 min_seq = (u64)-1;
398bd989ba3SJan Schmidt 	u64 seq_putting = elem->seq;
399bd989ba3SJan Schmidt 
400bd989ba3SJan Schmidt 	if (!seq_putting)
401bd989ba3SJan Schmidt 		return;
402bd989ba3SJan Schmidt 
403bd989ba3SJan Schmidt 	spin_lock(&fs_info->tree_mod_seq_lock);
404bd989ba3SJan Schmidt 	list_del(&elem->list);
405097b8a7cSJan Schmidt 	elem->seq = 0;
406bd989ba3SJan Schmidt 
407bd989ba3SJan Schmidt 	list_for_each_entry(cur_elem, &fs_info->tree_mod_seq_list, list) {
408097b8a7cSJan Schmidt 		if (cur_elem->seq < min_seq) {
409bd989ba3SJan Schmidt 			if (seq_putting > cur_elem->seq) {
410bd989ba3SJan Schmidt 				/*
411bd989ba3SJan Schmidt 				 * blocker with lower sequence number exists, we
412bd989ba3SJan Schmidt 				 * cannot remove anything from the log
413bd989ba3SJan Schmidt 				 */
414097b8a7cSJan Schmidt 				spin_unlock(&fs_info->tree_mod_seq_lock);
415097b8a7cSJan Schmidt 				return;
416bd989ba3SJan Schmidt 			}
417bd989ba3SJan Schmidt 			min_seq = cur_elem->seq;
418bd989ba3SJan Schmidt 		}
419bd989ba3SJan Schmidt 	}
420097b8a7cSJan Schmidt 	spin_unlock(&fs_info->tree_mod_seq_lock);
421097b8a7cSJan Schmidt 
422097b8a7cSJan Schmidt 	/*
423bd989ba3SJan Schmidt 	 * anything that's lower than the lowest existing (read: blocked)
424bd989ba3SJan Schmidt 	 * sequence number can be removed from the tree.
425bd989ba3SJan Schmidt 	 */
426097b8a7cSJan Schmidt 	tree_mod_log_write_lock(fs_info);
427bd989ba3SJan Schmidt 	tm_root = &fs_info->tree_mod_log;
428bd989ba3SJan Schmidt 	for (node = rb_first(tm_root); node; node = next) {
429bd989ba3SJan Schmidt 		next = rb_next(node);
430bd989ba3SJan Schmidt 		tm = container_of(node, struct tree_mod_elem, node);
431097b8a7cSJan Schmidt 		if (tm->seq > min_seq)
432bd989ba3SJan Schmidt 			continue;
433bd989ba3SJan Schmidt 		rb_erase(node, tm_root);
434bd989ba3SJan Schmidt 		kfree(tm);
435bd989ba3SJan Schmidt 	}
436097b8a7cSJan Schmidt 	tree_mod_log_write_unlock(fs_info);
437bd989ba3SJan Schmidt }
438bd989ba3SJan Schmidt 
439bd989ba3SJan Schmidt /*
440bd989ba3SJan Schmidt  * key order of the log:
441bd989ba3SJan Schmidt  *       index -> sequence
442bd989ba3SJan Schmidt  *
443bd989ba3SJan Schmidt  * the index is the shifted logical of the *new* root node for root replace
444bd989ba3SJan Schmidt  * operations, or the shifted logical of the affected block for all other
445bd989ba3SJan Schmidt  * operations.
4465de865eeSFilipe David Borba Manana  *
4475de865eeSFilipe David Borba Manana  * Note: must be called with write lock (tree_mod_log_write_lock).
448bd989ba3SJan Schmidt  */
449bd989ba3SJan Schmidt static noinline int
450bd989ba3SJan Schmidt __tree_mod_log_insert(struct btrfs_fs_info *fs_info, struct tree_mod_elem *tm)
451bd989ba3SJan Schmidt {
452bd989ba3SJan Schmidt 	struct rb_root *tm_root;
453bd989ba3SJan Schmidt 	struct rb_node **new;
454bd989ba3SJan Schmidt 	struct rb_node *parent = NULL;
455bd989ba3SJan Schmidt 	struct tree_mod_elem *cur;
456bd989ba3SJan Schmidt 
457c8cc6341SJosef Bacik 	BUG_ON(!tm);
458c8cc6341SJosef Bacik 
459fcebe456SJosef Bacik 	tm->seq = btrfs_inc_tree_mod_seq(fs_info);
460bd989ba3SJan Schmidt 
461bd989ba3SJan Schmidt 	tm_root = &fs_info->tree_mod_log;
462bd989ba3SJan Schmidt 	new = &tm_root->rb_node;
463bd989ba3SJan Schmidt 	while (*new) {
464bd989ba3SJan Schmidt 		cur = container_of(*new, struct tree_mod_elem, node);
465bd989ba3SJan Schmidt 		parent = *new;
466bd989ba3SJan Schmidt 		if (cur->index < tm->index)
467bd989ba3SJan Schmidt 			new = &((*new)->rb_left);
468bd989ba3SJan Schmidt 		else if (cur->index > tm->index)
469bd989ba3SJan Schmidt 			new = &((*new)->rb_right);
470097b8a7cSJan Schmidt 		else if (cur->seq < tm->seq)
471bd989ba3SJan Schmidt 			new = &((*new)->rb_left);
472097b8a7cSJan Schmidt 		else if (cur->seq > tm->seq)
473bd989ba3SJan Schmidt 			new = &((*new)->rb_right);
4745de865eeSFilipe David Borba Manana 		else
4755de865eeSFilipe David Borba Manana 			return -EEXIST;
476bd989ba3SJan Schmidt 	}
477bd989ba3SJan Schmidt 
478bd989ba3SJan Schmidt 	rb_link_node(&tm->node, parent, new);
479bd989ba3SJan Schmidt 	rb_insert_color(&tm->node, tm_root);
4805de865eeSFilipe David Borba Manana 	return 0;
481bd989ba3SJan Schmidt }
482bd989ba3SJan Schmidt 
483097b8a7cSJan Schmidt /*
484097b8a7cSJan Schmidt  * Determines if logging can be omitted. Returns 1 if it can. Otherwise, it
485097b8a7cSJan Schmidt  * returns zero with the tree_mod_log_lock acquired. The caller must hold
486097b8a7cSJan Schmidt  * this until all tree mod log insertions are recorded in the rb tree and then
487097b8a7cSJan Schmidt  * call tree_mod_log_write_unlock() to release.
488097b8a7cSJan Schmidt  */
489e9b7fd4dSJan Schmidt static inline int tree_mod_dont_log(struct btrfs_fs_info *fs_info,
490e9b7fd4dSJan Schmidt 				    struct extent_buffer *eb) {
491e9b7fd4dSJan Schmidt 	smp_mb();
492e9b7fd4dSJan Schmidt 	if (list_empty(&(fs_info)->tree_mod_seq_list))
493e9b7fd4dSJan Schmidt 		return 1;
494097b8a7cSJan Schmidt 	if (eb && btrfs_header_level(eb) == 0)
495e9b7fd4dSJan Schmidt 		return 1;
4965de865eeSFilipe David Borba Manana 
4975de865eeSFilipe David Borba Manana 	tree_mod_log_write_lock(fs_info);
4985de865eeSFilipe David Borba Manana 	if (list_empty(&(fs_info)->tree_mod_seq_list)) {
4995de865eeSFilipe David Borba Manana 		tree_mod_log_write_unlock(fs_info);
5005de865eeSFilipe David Borba Manana 		return 1;
5015de865eeSFilipe David Borba Manana 	}
5025de865eeSFilipe David Borba Manana 
503e9b7fd4dSJan Schmidt 	return 0;
504e9b7fd4dSJan Schmidt }
505e9b7fd4dSJan Schmidt 
5065de865eeSFilipe David Borba Manana /* Similar to tree_mod_dont_log, but doesn't acquire any locks. */
5075de865eeSFilipe David Borba Manana static inline int tree_mod_need_log(const struct btrfs_fs_info *fs_info,
5085de865eeSFilipe David Borba Manana 				    struct extent_buffer *eb)
5095de865eeSFilipe David Borba Manana {
5105de865eeSFilipe David Borba Manana 	smp_mb();
5115de865eeSFilipe David Borba Manana 	if (list_empty(&(fs_info)->tree_mod_seq_list))
5125de865eeSFilipe David Borba Manana 		return 0;
5135de865eeSFilipe David Borba Manana 	if (eb && btrfs_header_level(eb) == 0)
5145de865eeSFilipe David Borba Manana 		return 0;
5155de865eeSFilipe David Borba Manana 
5165de865eeSFilipe David Borba Manana 	return 1;
5175de865eeSFilipe David Borba Manana }
5185de865eeSFilipe David Borba Manana 
5195de865eeSFilipe David Borba Manana static struct tree_mod_elem *
5205de865eeSFilipe David Borba Manana alloc_tree_mod_elem(struct extent_buffer *eb, int slot,
521bd989ba3SJan Schmidt 		    enum mod_log_op op, gfp_t flags)
522bd989ba3SJan Schmidt {
523097b8a7cSJan Schmidt 	struct tree_mod_elem *tm;
524bd989ba3SJan Schmidt 
525c8cc6341SJosef Bacik 	tm = kzalloc(sizeof(*tm), flags);
526c8cc6341SJosef Bacik 	if (!tm)
5275de865eeSFilipe David Borba Manana 		return NULL;
528bd989ba3SJan Schmidt 
529bd989ba3SJan Schmidt 	tm->index = eb->start >> PAGE_CACHE_SHIFT;
530bd989ba3SJan Schmidt 	if (op != MOD_LOG_KEY_ADD) {
531bd989ba3SJan Schmidt 		btrfs_node_key(eb, &tm->key, slot);
532bd989ba3SJan Schmidt 		tm->blockptr = btrfs_node_blockptr(eb, slot);
533bd989ba3SJan Schmidt 	}
534bd989ba3SJan Schmidt 	tm->op = op;
535bd989ba3SJan Schmidt 	tm->slot = slot;
536bd989ba3SJan Schmidt 	tm->generation = btrfs_node_ptr_generation(eb, slot);
5375de865eeSFilipe David Borba Manana 	RB_CLEAR_NODE(&tm->node);
538bd989ba3SJan Schmidt 
5395de865eeSFilipe David Borba Manana 	return tm;
540097b8a7cSJan Schmidt }
541097b8a7cSJan Schmidt 
542097b8a7cSJan Schmidt static noinline int
543c8cc6341SJosef Bacik tree_mod_log_insert_key(struct btrfs_fs_info *fs_info,
544097b8a7cSJan Schmidt 			struct extent_buffer *eb, int slot,
545097b8a7cSJan Schmidt 			enum mod_log_op op, gfp_t flags)
546097b8a7cSJan Schmidt {
5475de865eeSFilipe David Borba Manana 	struct tree_mod_elem *tm;
5485de865eeSFilipe David Borba Manana 	int ret;
5495de865eeSFilipe David Borba Manana 
5505de865eeSFilipe David Borba Manana 	if (!tree_mod_need_log(fs_info, eb))
551097b8a7cSJan Schmidt 		return 0;
552097b8a7cSJan Schmidt 
5535de865eeSFilipe David Borba Manana 	tm = alloc_tree_mod_elem(eb, slot, op, flags);
5545de865eeSFilipe David Borba Manana 	if (!tm)
5555de865eeSFilipe David Borba Manana 		return -ENOMEM;
5565de865eeSFilipe David Borba Manana 
5575de865eeSFilipe David Borba Manana 	if (tree_mod_dont_log(fs_info, eb)) {
5585de865eeSFilipe David Borba Manana 		kfree(tm);
5595de865eeSFilipe David Borba Manana 		return 0;
5605de865eeSFilipe David Borba Manana 	}
5615de865eeSFilipe David Borba Manana 
5625de865eeSFilipe David Borba Manana 	ret = __tree_mod_log_insert(fs_info, tm);
5635de865eeSFilipe David Borba Manana 	tree_mod_log_write_unlock(fs_info);
5645de865eeSFilipe David Borba Manana 	if (ret)
5655de865eeSFilipe David Borba Manana 		kfree(tm);
5665de865eeSFilipe David Borba Manana 
5675de865eeSFilipe David Borba Manana 	return ret;
568097b8a7cSJan Schmidt }
569097b8a7cSJan Schmidt 
570097b8a7cSJan Schmidt static noinline int
571bd989ba3SJan Schmidt tree_mod_log_insert_move(struct btrfs_fs_info *fs_info,
572bd989ba3SJan Schmidt 			 struct extent_buffer *eb, int dst_slot, int src_slot,
573bd989ba3SJan Schmidt 			 int nr_items, gfp_t flags)
574bd989ba3SJan Schmidt {
5755de865eeSFilipe David Borba Manana 	struct tree_mod_elem *tm = NULL;
5765de865eeSFilipe David Borba Manana 	struct tree_mod_elem **tm_list = NULL;
5775de865eeSFilipe David Borba Manana 	int ret = 0;
578bd989ba3SJan Schmidt 	int i;
5795de865eeSFilipe David Borba Manana 	int locked = 0;
580bd989ba3SJan Schmidt 
5815de865eeSFilipe David Borba Manana 	if (!tree_mod_need_log(fs_info, eb))
582f395694cSJan Schmidt 		return 0;
583bd989ba3SJan Schmidt 
5845de865eeSFilipe David Borba Manana 	tm_list = kzalloc(nr_items * sizeof(struct tree_mod_elem *), flags);
5855de865eeSFilipe David Borba Manana 	if (!tm_list)
5865de865eeSFilipe David Borba Manana 		return -ENOMEM;
587bd989ba3SJan Schmidt 
588c8cc6341SJosef Bacik 	tm = kzalloc(sizeof(*tm), flags);
5895de865eeSFilipe David Borba Manana 	if (!tm) {
5905de865eeSFilipe David Borba Manana 		ret = -ENOMEM;
5915de865eeSFilipe David Borba Manana 		goto free_tms;
5925de865eeSFilipe David Borba Manana 	}
593f395694cSJan Schmidt 
594bd989ba3SJan Schmidt 	tm->index = eb->start >> PAGE_CACHE_SHIFT;
595bd989ba3SJan Schmidt 	tm->slot = src_slot;
596bd989ba3SJan Schmidt 	tm->move.dst_slot = dst_slot;
597bd989ba3SJan Schmidt 	tm->move.nr_items = nr_items;
598bd989ba3SJan Schmidt 	tm->op = MOD_LOG_MOVE_KEYS;
599bd989ba3SJan Schmidt 
6005de865eeSFilipe David Borba Manana 	for (i = 0; i + dst_slot < src_slot && i < nr_items; i++) {
6015de865eeSFilipe David Borba Manana 		tm_list[i] = alloc_tree_mod_elem(eb, i + dst_slot,
6025de865eeSFilipe David Borba Manana 		    MOD_LOG_KEY_REMOVE_WHILE_MOVING, flags);
6035de865eeSFilipe David Borba Manana 		if (!tm_list[i]) {
6045de865eeSFilipe David Borba Manana 			ret = -ENOMEM;
6055de865eeSFilipe David Borba Manana 			goto free_tms;
6065de865eeSFilipe David Borba Manana 		}
607bd989ba3SJan Schmidt 	}
608bd989ba3SJan Schmidt 
6095de865eeSFilipe David Borba Manana 	if (tree_mod_dont_log(fs_info, eb))
6105de865eeSFilipe David Borba Manana 		goto free_tms;
6115de865eeSFilipe David Borba Manana 	locked = 1;
6125de865eeSFilipe David Borba Manana 
6135de865eeSFilipe David Borba Manana 	/*
6145de865eeSFilipe David Borba Manana 	 * When we override something during the move, we log these removals.
6155de865eeSFilipe David Borba Manana 	 * This can only happen when we move towards the beginning of the
6165de865eeSFilipe David Borba Manana 	 * buffer, i.e. dst_slot < src_slot.
6175de865eeSFilipe David Borba Manana 	 */
6185de865eeSFilipe David Borba Manana 	for (i = 0; i + dst_slot < src_slot && i < nr_items; i++) {
6195de865eeSFilipe David Borba Manana 		ret = __tree_mod_log_insert(fs_info, tm_list[i]);
6205de865eeSFilipe David Borba Manana 		if (ret)
6215de865eeSFilipe David Borba Manana 			goto free_tms;
6225de865eeSFilipe David Borba Manana 	}
6235de865eeSFilipe David Borba Manana 
6245de865eeSFilipe David Borba Manana 	ret = __tree_mod_log_insert(fs_info, tm);
6255de865eeSFilipe David Borba Manana 	if (ret)
6265de865eeSFilipe David Borba Manana 		goto free_tms;
6275de865eeSFilipe David Borba Manana 	tree_mod_log_write_unlock(fs_info);
6285de865eeSFilipe David Borba Manana 	kfree(tm_list);
6295de865eeSFilipe David Borba Manana 
6305de865eeSFilipe David Borba Manana 	return 0;
6315de865eeSFilipe David Borba Manana free_tms:
6325de865eeSFilipe David Borba Manana 	for (i = 0; i < nr_items; i++) {
6335de865eeSFilipe David Borba Manana 		if (tm_list[i] && !RB_EMPTY_NODE(&tm_list[i]->node))
6345de865eeSFilipe David Borba Manana 			rb_erase(&tm_list[i]->node, &fs_info->tree_mod_log);
6355de865eeSFilipe David Borba Manana 		kfree(tm_list[i]);
6365de865eeSFilipe David Borba Manana 	}
6375de865eeSFilipe David Borba Manana 	if (locked)
6385de865eeSFilipe David Borba Manana 		tree_mod_log_write_unlock(fs_info);
6395de865eeSFilipe David Borba Manana 	kfree(tm_list);
6405de865eeSFilipe David Borba Manana 	kfree(tm);
6415de865eeSFilipe David Borba Manana 
6425de865eeSFilipe David Borba Manana 	return ret;
6435de865eeSFilipe David Borba Manana }
6445de865eeSFilipe David Borba Manana 
6455de865eeSFilipe David Borba Manana static inline int
6465de865eeSFilipe David Borba Manana __tree_mod_log_free_eb(struct btrfs_fs_info *fs_info,
6475de865eeSFilipe David Borba Manana 		       struct tree_mod_elem **tm_list,
6485de865eeSFilipe David Borba Manana 		       int nritems)
649097b8a7cSJan Schmidt {
6505de865eeSFilipe David Borba Manana 	int i, j;
651097b8a7cSJan Schmidt 	int ret;
652097b8a7cSJan Schmidt 
653097b8a7cSJan Schmidt 	for (i = nritems - 1; i >= 0; i--) {
6545de865eeSFilipe David Borba Manana 		ret = __tree_mod_log_insert(fs_info, tm_list[i]);
6555de865eeSFilipe David Borba Manana 		if (ret) {
6565de865eeSFilipe David Borba Manana 			for (j = nritems - 1; j > i; j--)
6575de865eeSFilipe David Borba Manana 				rb_erase(&tm_list[j]->node,
6585de865eeSFilipe David Borba Manana 					 &fs_info->tree_mod_log);
6595de865eeSFilipe David Borba Manana 			return ret;
660097b8a7cSJan Schmidt 		}
661097b8a7cSJan Schmidt 	}
662097b8a7cSJan Schmidt 
6635de865eeSFilipe David Borba Manana 	return 0;
6645de865eeSFilipe David Borba Manana }
6655de865eeSFilipe David Borba Manana 
666bd989ba3SJan Schmidt static noinline int
667bd989ba3SJan Schmidt tree_mod_log_insert_root(struct btrfs_fs_info *fs_info,
668bd989ba3SJan Schmidt 			 struct extent_buffer *old_root,
66990f8d62eSJan Schmidt 			 struct extent_buffer *new_root, gfp_t flags,
67090f8d62eSJan Schmidt 			 int log_removal)
671bd989ba3SJan Schmidt {
6725de865eeSFilipe David Borba Manana 	struct tree_mod_elem *tm = NULL;
6735de865eeSFilipe David Borba Manana 	struct tree_mod_elem **tm_list = NULL;
6745de865eeSFilipe David Borba Manana 	int nritems = 0;
6755de865eeSFilipe David Borba Manana 	int ret = 0;
6765de865eeSFilipe David Borba Manana 	int i;
677bd989ba3SJan Schmidt 
6785de865eeSFilipe David Borba Manana 	if (!tree_mod_need_log(fs_info, NULL))
679097b8a7cSJan Schmidt 		return 0;
680097b8a7cSJan Schmidt 
6815de865eeSFilipe David Borba Manana 	if (log_removal && btrfs_header_level(old_root) > 0) {
6825de865eeSFilipe David Borba Manana 		nritems = btrfs_header_nritems(old_root);
6835de865eeSFilipe David Borba Manana 		tm_list = kzalloc(nritems * sizeof(struct tree_mod_elem *),
6845de865eeSFilipe David Borba Manana 				  flags);
6855de865eeSFilipe David Borba Manana 		if (!tm_list) {
6865de865eeSFilipe David Borba Manana 			ret = -ENOMEM;
6875de865eeSFilipe David Borba Manana 			goto free_tms;
6885de865eeSFilipe David Borba Manana 		}
6895de865eeSFilipe David Borba Manana 		for (i = 0; i < nritems; i++) {
6905de865eeSFilipe David Borba Manana 			tm_list[i] = alloc_tree_mod_elem(old_root, i,
6915de865eeSFilipe David Borba Manana 			    MOD_LOG_KEY_REMOVE_WHILE_FREEING, flags);
6925de865eeSFilipe David Borba Manana 			if (!tm_list[i]) {
6935de865eeSFilipe David Borba Manana 				ret = -ENOMEM;
6945de865eeSFilipe David Borba Manana 				goto free_tms;
6955de865eeSFilipe David Borba Manana 			}
6965de865eeSFilipe David Borba Manana 		}
6975de865eeSFilipe David Borba Manana 	}
698d9abbf1cSJan Schmidt 
699c8cc6341SJosef Bacik 	tm = kzalloc(sizeof(*tm), flags);
7005de865eeSFilipe David Borba Manana 	if (!tm) {
7015de865eeSFilipe David Borba Manana 		ret = -ENOMEM;
7025de865eeSFilipe David Borba Manana 		goto free_tms;
7035de865eeSFilipe David Borba Manana 	}
704bd989ba3SJan Schmidt 
705bd989ba3SJan Schmidt 	tm->index = new_root->start >> PAGE_CACHE_SHIFT;
706bd989ba3SJan Schmidt 	tm->old_root.logical = old_root->start;
707bd989ba3SJan Schmidt 	tm->old_root.level = btrfs_header_level(old_root);
708bd989ba3SJan Schmidt 	tm->generation = btrfs_header_generation(old_root);
709bd989ba3SJan Schmidt 	tm->op = MOD_LOG_ROOT_REPLACE;
710bd989ba3SJan Schmidt 
7115de865eeSFilipe David Borba Manana 	if (tree_mod_dont_log(fs_info, NULL))
7125de865eeSFilipe David Borba Manana 		goto free_tms;
7135de865eeSFilipe David Borba Manana 
7145de865eeSFilipe David Borba Manana 	if (tm_list)
7155de865eeSFilipe David Borba Manana 		ret = __tree_mod_log_free_eb(fs_info, tm_list, nritems);
7165de865eeSFilipe David Borba Manana 	if (!ret)
7175de865eeSFilipe David Borba Manana 		ret = __tree_mod_log_insert(fs_info, tm);
7185de865eeSFilipe David Borba Manana 
7195de865eeSFilipe David Borba Manana 	tree_mod_log_write_unlock(fs_info);
7205de865eeSFilipe David Borba Manana 	if (ret)
7215de865eeSFilipe David Borba Manana 		goto free_tms;
7225de865eeSFilipe David Borba Manana 	kfree(tm_list);
7235de865eeSFilipe David Borba Manana 
7245de865eeSFilipe David Borba Manana 	return ret;
7255de865eeSFilipe David Borba Manana 
7265de865eeSFilipe David Borba Manana free_tms:
7275de865eeSFilipe David Borba Manana 	if (tm_list) {
7285de865eeSFilipe David Borba Manana 		for (i = 0; i < nritems; i++)
7295de865eeSFilipe David Borba Manana 			kfree(tm_list[i]);
7305de865eeSFilipe David Borba Manana 		kfree(tm_list);
7315de865eeSFilipe David Borba Manana 	}
7325de865eeSFilipe David Borba Manana 	kfree(tm);
7335de865eeSFilipe David Borba Manana 
7345de865eeSFilipe David Borba Manana 	return ret;
735bd989ba3SJan Schmidt }
736bd989ba3SJan Schmidt 
737bd989ba3SJan Schmidt static struct tree_mod_elem *
738bd989ba3SJan Schmidt __tree_mod_log_search(struct btrfs_fs_info *fs_info, u64 start, u64 min_seq,
739bd989ba3SJan Schmidt 		      int smallest)
740bd989ba3SJan Schmidt {
741bd989ba3SJan Schmidt 	struct rb_root *tm_root;
742bd989ba3SJan Schmidt 	struct rb_node *node;
743bd989ba3SJan Schmidt 	struct tree_mod_elem *cur = NULL;
744bd989ba3SJan Schmidt 	struct tree_mod_elem *found = NULL;
745bd989ba3SJan Schmidt 	u64 index = start >> PAGE_CACHE_SHIFT;
746bd989ba3SJan Schmidt 
747097b8a7cSJan Schmidt 	tree_mod_log_read_lock(fs_info);
748bd989ba3SJan Schmidt 	tm_root = &fs_info->tree_mod_log;
749bd989ba3SJan Schmidt 	node = tm_root->rb_node;
750bd989ba3SJan Schmidt 	while (node) {
751bd989ba3SJan Schmidt 		cur = container_of(node, struct tree_mod_elem, node);
752bd989ba3SJan Schmidt 		if (cur->index < index) {
753bd989ba3SJan Schmidt 			node = node->rb_left;
754bd989ba3SJan Schmidt 		} else if (cur->index > index) {
755bd989ba3SJan Schmidt 			node = node->rb_right;
756097b8a7cSJan Schmidt 		} else if (cur->seq < min_seq) {
757bd989ba3SJan Schmidt 			node = node->rb_left;
758bd989ba3SJan Schmidt 		} else if (!smallest) {
759bd989ba3SJan Schmidt 			/* we want the node with the highest seq */
760bd989ba3SJan Schmidt 			if (found)
761097b8a7cSJan Schmidt 				BUG_ON(found->seq > cur->seq);
762bd989ba3SJan Schmidt 			found = cur;
763bd989ba3SJan Schmidt 			node = node->rb_left;
764097b8a7cSJan Schmidt 		} else if (cur->seq > min_seq) {
765bd989ba3SJan Schmidt 			/* we want the node with the smallest seq */
766bd989ba3SJan Schmidt 			if (found)
767097b8a7cSJan Schmidt 				BUG_ON(found->seq < cur->seq);
768bd989ba3SJan Schmidt 			found = cur;
769bd989ba3SJan Schmidt 			node = node->rb_right;
770bd989ba3SJan Schmidt 		} else {
771bd989ba3SJan Schmidt 			found = cur;
772bd989ba3SJan Schmidt 			break;
773bd989ba3SJan Schmidt 		}
774bd989ba3SJan Schmidt 	}
775097b8a7cSJan Schmidt 	tree_mod_log_read_unlock(fs_info);
776bd989ba3SJan Schmidt 
777bd989ba3SJan Schmidt 	return found;
778bd989ba3SJan Schmidt }
779bd989ba3SJan Schmidt 
780bd989ba3SJan Schmidt /*
781bd989ba3SJan Schmidt  * this returns the element from the log with the smallest time sequence
782bd989ba3SJan Schmidt  * value that's in the log (the oldest log item). any element with a time
783bd989ba3SJan Schmidt  * sequence lower than min_seq will be ignored.
784bd989ba3SJan Schmidt  */
785bd989ba3SJan Schmidt static struct tree_mod_elem *
786bd989ba3SJan Schmidt tree_mod_log_search_oldest(struct btrfs_fs_info *fs_info, u64 start,
787bd989ba3SJan Schmidt 			   u64 min_seq)
788bd989ba3SJan Schmidt {
789bd989ba3SJan Schmidt 	return __tree_mod_log_search(fs_info, start, min_seq, 1);
790bd989ba3SJan Schmidt }
791bd989ba3SJan Schmidt 
792bd989ba3SJan Schmidt /*
793bd989ba3SJan Schmidt  * this returns the element from the log with the largest time sequence
794bd989ba3SJan Schmidt  * value that's in the log (the most recent log item). any element with
795bd989ba3SJan Schmidt  * a time sequence lower than min_seq will be ignored.
796bd989ba3SJan Schmidt  */
797bd989ba3SJan Schmidt static struct tree_mod_elem *
798bd989ba3SJan Schmidt tree_mod_log_search(struct btrfs_fs_info *fs_info, u64 start, u64 min_seq)
799bd989ba3SJan Schmidt {
800bd989ba3SJan Schmidt 	return __tree_mod_log_search(fs_info, start, min_seq, 0);
801bd989ba3SJan Schmidt }
802bd989ba3SJan Schmidt 
8035de865eeSFilipe David Borba Manana static noinline int
804bd989ba3SJan Schmidt tree_mod_log_eb_copy(struct btrfs_fs_info *fs_info, struct extent_buffer *dst,
805bd989ba3SJan Schmidt 		     struct extent_buffer *src, unsigned long dst_offset,
80690f8d62eSJan Schmidt 		     unsigned long src_offset, int nr_items)
807bd989ba3SJan Schmidt {
8085de865eeSFilipe David Borba Manana 	int ret = 0;
8095de865eeSFilipe David Borba Manana 	struct tree_mod_elem **tm_list = NULL;
8105de865eeSFilipe David Borba Manana 	struct tree_mod_elem **tm_list_add, **tm_list_rem;
811bd989ba3SJan Schmidt 	int i;
8125de865eeSFilipe David Borba Manana 	int locked = 0;
813bd989ba3SJan Schmidt 
8145de865eeSFilipe David Borba Manana 	if (!tree_mod_need_log(fs_info, NULL))
8155de865eeSFilipe David Borba Manana 		return 0;
816bd989ba3SJan Schmidt 
817c8cc6341SJosef Bacik 	if (btrfs_header_level(dst) == 0 && btrfs_header_level(src) == 0)
8185de865eeSFilipe David Borba Manana 		return 0;
8195de865eeSFilipe David Borba Manana 
8205de865eeSFilipe David Borba Manana 	tm_list = kzalloc(nr_items * 2 * sizeof(struct tree_mod_elem *),
8215de865eeSFilipe David Borba Manana 			  GFP_NOFS);
8225de865eeSFilipe David Borba Manana 	if (!tm_list)
8235de865eeSFilipe David Borba Manana 		return -ENOMEM;
8245de865eeSFilipe David Borba Manana 
8255de865eeSFilipe David Borba Manana 	tm_list_add = tm_list;
8265de865eeSFilipe David Borba Manana 	tm_list_rem = tm_list + nr_items;
8275de865eeSFilipe David Borba Manana 	for (i = 0; i < nr_items; i++) {
8285de865eeSFilipe David Borba Manana 		tm_list_rem[i] = alloc_tree_mod_elem(src, i + src_offset,
8295de865eeSFilipe David Borba Manana 		    MOD_LOG_KEY_REMOVE, GFP_NOFS);
8305de865eeSFilipe David Borba Manana 		if (!tm_list_rem[i]) {
8315de865eeSFilipe David Borba Manana 			ret = -ENOMEM;
8325de865eeSFilipe David Borba Manana 			goto free_tms;
8335de865eeSFilipe David Borba Manana 		}
8345de865eeSFilipe David Borba Manana 
8355de865eeSFilipe David Borba Manana 		tm_list_add[i] = alloc_tree_mod_elem(dst, i + dst_offset,
8365de865eeSFilipe David Borba Manana 		    MOD_LOG_KEY_ADD, GFP_NOFS);
8375de865eeSFilipe David Borba Manana 		if (!tm_list_add[i]) {
8385de865eeSFilipe David Borba Manana 			ret = -ENOMEM;
8395de865eeSFilipe David Borba Manana 			goto free_tms;
8405de865eeSFilipe David Borba Manana 		}
8415de865eeSFilipe David Borba Manana 	}
8425de865eeSFilipe David Borba Manana 
8435de865eeSFilipe David Borba Manana 	if (tree_mod_dont_log(fs_info, NULL))
8445de865eeSFilipe David Borba Manana 		goto free_tms;
8455de865eeSFilipe David Borba Manana 	locked = 1;
846bd989ba3SJan Schmidt 
847bd989ba3SJan Schmidt 	for (i = 0; i < nr_items; i++) {
8485de865eeSFilipe David Borba Manana 		ret = __tree_mod_log_insert(fs_info, tm_list_rem[i]);
8495de865eeSFilipe David Borba Manana 		if (ret)
8505de865eeSFilipe David Borba Manana 			goto free_tms;
8515de865eeSFilipe David Borba Manana 		ret = __tree_mod_log_insert(fs_info, tm_list_add[i]);
8525de865eeSFilipe David Borba Manana 		if (ret)
8535de865eeSFilipe David Borba Manana 			goto free_tms;
854bd989ba3SJan Schmidt 	}
8555de865eeSFilipe David Borba Manana 
8565de865eeSFilipe David Borba Manana 	tree_mod_log_write_unlock(fs_info);
8575de865eeSFilipe David Borba Manana 	kfree(tm_list);
8585de865eeSFilipe David Borba Manana 
8595de865eeSFilipe David Borba Manana 	return 0;
8605de865eeSFilipe David Borba Manana 
8615de865eeSFilipe David Borba Manana free_tms:
8625de865eeSFilipe David Borba Manana 	for (i = 0; i < nr_items * 2; i++) {
8635de865eeSFilipe David Borba Manana 		if (tm_list[i] && !RB_EMPTY_NODE(&tm_list[i]->node))
8645de865eeSFilipe David Borba Manana 			rb_erase(&tm_list[i]->node, &fs_info->tree_mod_log);
8655de865eeSFilipe David Borba Manana 		kfree(tm_list[i]);
8665de865eeSFilipe David Borba Manana 	}
8675de865eeSFilipe David Borba Manana 	if (locked)
8685de865eeSFilipe David Borba Manana 		tree_mod_log_write_unlock(fs_info);
8695de865eeSFilipe David Borba Manana 	kfree(tm_list);
8705de865eeSFilipe David Borba Manana 
8715de865eeSFilipe David Borba Manana 	return ret;
872bd989ba3SJan Schmidt }
873bd989ba3SJan Schmidt 
874bd989ba3SJan Schmidt static inline void
875bd989ba3SJan Schmidt tree_mod_log_eb_move(struct btrfs_fs_info *fs_info, struct extent_buffer *dst,
876bd989ba3SJan Schmidt 		     int dst_offset, int src_offset, int nr_items)
877bd989ba3SJan Schmidt {
878bd989ba3SJan Schmidt 	int ret;
879bd989ba3SJan Schmidt 	ret = tree_mod_log_insert_move(fs_info, dst, dst_offset, src_offset,
880bd989ba3SJan Schmidt 				       nr_items, GFP_NOFS);
881bd989ba3SJan Schmidt 	BUG_ON(ret < 0);
882bd989ba3SJan Schmidt }
883bd989ba3SJan Schmidt 
884097b8a7cSJan Schmidt static noinline void
885bd989ba3SJan Schmidt tree_mod_log_set_node_key(struct btrfs_fs_info *fs_info,
88632adf090SLiu Bo 			  struct extent_buffer *eb, int slot, int atomic)
887bd989ba3SJan Schmidt {
888bd989ba3SJan Schmidt 	int ret;
889bd989ba3SJan Schmidt 
89078357766SFilipe David Borba Manana 	ret = tree_mod_log_insert_key(fs_info, eb, slot,
891bd989ba3SJan Schmidt 					MOD_LOG_KEY_REPLACE,
892bd989ba3SJan Schmidt 					atomic ? GFP_ATOMIC : GFP_NOFS);
893bd989ba3SJan Schmidt 	BUG_ON(ret < 0);
894bd989ba3SJan Schmidt }
895bd989ba3SJan Schmidt 
8965de865eeSFilipe David Borba Manana static noinline int
897097b8a7cSJan Schmidt tree_mod_log_free_eb(struct btrfs_fs_info *fs_info, struct extent_buffer *eb)
898bd989ba3SJan Schmidt {
8995de865eeSFilipe David Borba Manana 	struct tree_mod_elem **tm_list = NULL;
9005de865eeSFilipe David Borba Manana 	int nritems = 0;
9015de865eeSFilipe David Borba Manana 	int i;
9025de865eeSFilipe David Borba Manana 	int ret = 0;
9035de865eeSFilipe David Borba Manana 
9045de865eeSFilipe David Borba Manana 	if (btrfs_header_level(eb) == 0)
9055de865eeSFilipe David Borba Manana 		return 0;
9065de865eeSFilipe David Borba Manana 
9075de865eeSFilipe David Borba Manana 	if (!tree_mod_need_log(fs_info, NULL))
9085de865eeSFilipe David Borba Manana 		return 0;
9095de865eeSFilipe David Borba Manana 
9105de865eeSFilipe David Borba Manana 	nritems = btrfs_header_nritems(eb);
9115de865eeSFilipe David Borba Manana 	tm_list = kzalloc(nritems * sizeof(struct tree_mod_elem *),
9125de865eeSFilipe David Borba Manana 			  GFP_NOFS);
9135de865eeSFilipe David Borba Manana 	if (!tm_list)
9145de865eeSFilipe David Borba Manana 		return -ENOMEM;
9155de865eeSFilipe David Borba Manana 
9165de865eeSFilipe David Borba Manana 	for (i = 0; i < nritems; i++) {
9175de865eeSFilipe David Borba Manana 		tm_list[i] = alloc_tree_mod_elem(eb, i,
9185de865eeSFilipe David Borba Manana 		    MOD_LOG_KEY_REMOVE_WHILE_FREEING, GFP_NOFS);
9195de865eeSFilipe David Borba Manana 		if (!tm_list[i]) {
9205de865eeSFilipe David Borba Manana 			ret = -ENOMEM;
9215de865eeSFilipe David Borba Manana 			goto free_tms;
9225de865eeSFilipe David Borba Manana 		}
9235de865eeSFilipe David Borba Manana 	}
9245de865eeSFilipe David Borba Manana 
925e9b7fd4dSJan Schmidt 	if (tree_mod_dont_log(fs_info, eb))
9265de865eeSFilipe David Borba Manana 		goto free_tms;
9275de865eeSFilipe David Borba Manana 
9285de865eeSFilipe David Borba Manana 	ret = __tree_mod_log_free_eb(fs_info, tm_list, nritems);
9295de865eeSFilipe David Borba Manana 	tree_mod_log_write_unlock(fs_info);
9305de865eeSFilipe David Borba Manana 	if (ret)
9315de865eeSFilipe David Borba Manana 		goto free_tms;
9325de865eeSFilipe David Borba Manana 	kfree(tm_list);
9335de865eeSFilipe David Borba Manana 
9345de865eeSFilipe David Borba Manana 	return 0;
9355de865eeSFilipe David Borba Manana 
9365de865eeSFilipe David Borba Manana free_tms:
9375de865eeSFilipe David Borba Manana 	for (i = 0; i < nritems; i++)
9385de865eeSFilipe David Borba Manana 		kfree(tm_list[i]);
9395de865eeSFilipe David Borba Manana 	kfree(tm_list);
9405de865eeSFilipe David Borba Manana 
9415de865eeSFilipe David Borba Manana 	return ret;
942bd989ba3SJan Schmidt }
943bd989ba3SJan Schmidt 
944097b8a7cSJan Schmidt static noinline void
945bd989ba3SJan Schmidt tree_mod_log_set_root_pointer(struct btrfs_root *root,
94690f8d62eSJan Schmidt 			      struct extent_buffer *new_root_node,
94790f8d62eSJan Schmidt 			      int log_removal)
948bd989ba3SJan Schmidt {
949bd989ba3SJan Schmidt 	int ret;
950bd989ba3SJan Schmidt 	ret = tree_mod_log_insert_root(root->fs_info, root->node,
95190f8d62eSJan Schmidt 				       new_root_node, GFP_NOFS, log_removal);
952bd989ba3SJan Schmidt 	BUG_ON(ret < 0);
953bd989ba3SJan Schmidt }
954bd989ba3SJan Schmidt 
955d352ac68SChris Mason /*
9565d4f98a2SYan Zheng  * check if the tree block can be shared by multiple trees
9575d4f98a2SYan Zheng  */
9585d4f98a2SYan Zheng int btrfs_block_can_be_shared(struct btrfs_root *root,
9595d4f98a2SYan Zheng 			      struct extent_buffer *buf)
9605d4f98a2SYan Zheng {
9615d4f98a2SYan Zheng 	/*
9625d4f98a2SYan Zheng 	 * Tree blocks not in refernece counted trees and tree roots
9635d4f98a2SYan Zheng 	 * are never shared. If a block was allocated after the last
9645d4f98a2SYan Zheng 	 * snapshot and the block was not allocated by tree relocation,
9655d4f98a2SYan Zheng 	 * we know the block is not shared.
9665d4f98a2SYan Zheng 	 */
96727cdeb70SMiao Xie 	if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
9685d4f98a2SYan Zheng 	    buf != root->node && buf != root->commit_root &&
9695d4f98a2SYan Zheng 	    (btrfs_header_generation(buf) <=
9705d4f98a2SYan Zheng 	     btrfs_root_last_snapshot(&root->root_item) ||
9715d4f98a2SYan Zheng 	     btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)))
9725d4f98a2SYan Zheng 		return 1;
9735d4f98a2SYan Zheng #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
97427cdeb70SMiao Xie 	if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
9755d4f98a2SYan Zheng 	    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
9765d4f98a2SYan Zheng 		return 1;
9775d4f98a2SYan Zheng #endif
9785d4f98a2SYan Zheng 	return 0;
9795d4f98a2SYan Zheng }
9805d4f98a2SYan Zheng 
9815d4f98a2SYan Zheng static noinline int update_ref_for_cow(struct btrfs_trans_handle *trans,
9825d4f98a2SYan Zheng 				       struct btrfs_root *root,
9835d4f98a2SYan Zheng 				       struct extent_buffer *buf,
984f0486c68SYan, Zheng 				       struct extent_buffer *cow,
985f0486c68SYan, Zheng 				       int *last_ref)
9865d4f98a2SYan Zheng {
9875d4f98a2SYan Zheng 	u64 refs;
9885d4f98a2SYan Zheng 	u64 owner;
9895d4f98a2SYan Zheng 	u64 flags;
9905d4f98a2SYan Zheng 	u64 new_flags = 0;
9915d4f98a2SYan Zheng 	int ret;
9925d4f98a2SYan Zheng 
9935d4f98a2SYan Zheng 	/*
9945d4f98a2SYan Zheng 	 * Backrefs update rules:
9955d4f98a2SYan Zheng 	 *
9965d4f98a2SYan Zheng 	 * Always use full backrefs for extent pointers in tree block
9975d4f98a2SYan Zheng 	 * allocated by tree relocation.
9985d4f98a2SYan Zheng 	 *
9995d4f98a2SYan Zheng 	 * If a shared tree block is no longer referenced by its owner
10005d4f98a2SYan Zheng 	 * tree (btrfs_header_owner(buf) == root->root_key.objectid),
10015d4f98a2SYan Zheng 	 * use full backrefs for extent pointers in tree block.
10025d4f98a2SYan Zheng 	 *
10035d4f98a2SYan Zheng 	 * If a tree block is been relocating
10045d4f98a2SYan Zheng 	 * (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID),
10055d4f98a2SYan Zheng 	 * use full backrefs for extent pointers in tree block.
10065d4f98a2SYan Zheng 	 * The reason for this is some operations (such as drop tree)
10075d4f98a2SYan Zheng 	 * are only allowed for blocks use full backrefs.
10085d4f98a2SYan Zheng 	 */
10095d4f98a2SYan Zheng 
10105d4f98a2SYan Zheng 	if (btrfs_block_can_be_shared(root, buf)) {
10115d4f98a2SYan Zheng 		ret = btrfs_lookup_extent_info(trans, root, buf->start,
10123173a18fSJosef Bacik 					       btrfs_header_level(buf), 1,
10133173a18fSJosef Bacik 					       &refs, &flags);
1014be1a5564SMark Fasheh 		if (ret)
1015be1a5564SMark Fasheh 			return ret;
1016e5df9573SMark Fasheh 		if (refs == 0) {
1017e5df9573SMark Fasheh 			ret = -EROFS;
1018e5df9573SMark Fasheh 			btrfs_std_error(root->fs_info, ret);
1019e5df9573SMark Fasheh 			return ret;
1020e5df9573SMark Fasheh 		}
10215d4f98a2SYan Zheng 	} else {
10225d4f98a2SYan Zheng 		refs = 1;
10235d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
10245d4f98a2SYan Zheng 		    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
10255d4f98a2SYan Zheng 			flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
10265d4f98a2SYan Zheng 		else
10275d4f98a2SYan Zheng 			flags = 0;
10285d4f98a2SYan Zheng 	}
10295d4f98a2SYan Zheng 
10305d4f98a2SYan Zheng 	owner = btrfs_header_owner(buf);
10315d4f98a2SYan Zheng 	BUG_ON(owner == BTRFS_TREE_RELOC_OBJECTID &&
10325d4f98a2SYan Zheng 	       !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
10335d4f98a2SYan Zheng 
10345d4f98a2SYan Zheng 	if (refs > 1) {
10355d4f98a2SYan Zheng 		if ((owner == root->root_key.objectid ||
10365d4f98a2SYan Zheng 		     root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) &&
10375d4f98a2SYan Zheng 		    !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)) {
1038e339a6b0SJosef Bacik 			ret = btrfs_inc_ref(trans, root, buf, 1);
103979787eaaSJeff Mahoney 			BUG_ON(ret); /* -ENOMEM */
10405d4f98a2SYan Zheng 
10415d4f98a2SYan Zheng 			if (root->root_key.objectid ==
10425d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID) {
1043e339a6b0SJosef Bacik 				ret = btrfs_dec_ref(trans, root, buf, 0);
104479787eaaSJeff Mahoney 				BUG_ON(ret); /* -ENOMEM */
1045e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
104679787eaaSJeff Mahoney 				BUG_ON(ret); /* -ENOMEM */
10475d4f98a2SYan Zheng 			}
10485d4f98a2SYan Zheng 			new_flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
10495d4f98a2SYan Zheng 		} else {
10505d4f98a2SYan Zheng 
10515d4f98a2SYan Zheng 			if (root->root_key.objectid ==
10525d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID)
1053e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
10545d4f98a2SYan Zheng 			else
1055e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 0);
105679787eaaSJeff Mahoney 			BUG_ON(ret); /* -ENOMEM */
10575d4f98a2SYan Zheng 		}
10585d4f98a2SYan Zheng 		if (new_flags != 0) {
1059b1c79e09SJosef Bacik 			int level = btrfs_header_level(buf);
1060b1c79e09SJosef Bacik 
10615d4f98a2SYan Zheng 			ret = btrfs_set_disk_extent_flags(trans, root,
10625d4f98a2SYan Zheng 							  buf->start,
10635d4f98a2SYan Zheng 							  buf->len,
1064b1c79e09SJosef Bacik 							  new_flags, level, 0);
1065be1a5564SMark Fasheh 			if (ret)
1066be1a5564SMark Fasheh 				return ret;
10675d4f98a2SYan Zheng 		}
10685d4f98a2SYan Zheng 	} else {
10695d4f98a2SYan Zheng 		if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
10705d4f98a2SYan Zheng 			if (root->root_key.objectid ==
10715d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID)
1072e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
10735d4f98a2SYan Zheng 			else
1074e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 0);
107579787eaaSJeff Mahoney 			BUG_ON(ret); /* -ENOMEM */
1076e339a6b0SJosef Bacik 			ret = btrfs_dec_ref(trans, root, buf, 1);
107779787eaaSJeff Mahoney 			BUG_ON(ret); /* -ENOMEM */
10785d4f98a2SYan Zheng 		}
10795d4f98a2SYan Zheng 		clean_tree_block(trans, root, buf);
1080f0486c68SYan, Zheng 		*last_ref = 1;
10815d4f98a2SYan Zheng 	}
10825d4f98a2SYan Zheng 	return 0;
10835d4f98a2SYan Zheng }
10845d4f98a2SYan Zheng 
10855d4f98a2SYan Zheng /*
1086d397712bSChris Mason  * does the dirty work in cow of a single block.  The parent block (if
1087d397712bSChris Mason  * supplied) is updated to point to the new cow copy.  The new buffer is marked
1088d397712bSChris Mason  * dirty and returned locked.  If you modify the block it needs to be marked
1089d397712bSChris Mason  * dirty again.
1090d352ac68SChris Mason  *
1091d352ac68SChris Mason  * search_start -- an allocation hint for the new block
1092d352ac68SChris Mason  *
1093d397712bSChris Mason  * empty_size -- a hint that you plan on doing more cow.  This is the size in
1094d397712bSChris Mason  * bytes the allocator should try to find free next to the block it returns.
1095d397712bSChris Mason  * This is just a hint and may be ignored by the allocator.
1096d352ac68SChris Mason  */
1097d397712bSChris Mason static noinline int __btrfs_cow_block(struct btrfs_trans_handle *trans,
10985f39d397SChris Mason 			     struct btrfs_root *root,
10995f39d397SChris Mason 			     struct extent_buffer *buf,
11005f39d397SChris Mason 			     struct extent_buffer *parent, int parent_slot,
11015f39d397SChris Mason 			     struct extent_buffer **cow_ret,
11029fa8cfe7SChris Mason 			     u64 search_start, u64 empty_size)
11036702ed49SChris Mason {
11045d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
11055f39d397SChris Mason 	struct extent_buffer *cow;
1106be1a5564SMark Fasheh 	int level, ret;
1107f0486c68SYan, Zheng 	int last_ref = 0;
1108925baeddSChris Mason 	int unlock_orig = 0;
11095d4f98a2SYan Zheng 	u64 parent_start;
11106702ed49SChris Mason 
1111925baeddSChris Mason 	if (*cow_ret == buf)
1112925baeddSChris Mason 		unlock_orig = 1;
1113925baeddSChris Mason 
1114b9447ef8SChris Mason 	btrfs_assert_tree_locked(buf);
1115925baeddSChris Mason 
111627cdeb70SMiao Xie 	WARN_ON(test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
111727cdeb70SMiao Xie 		trans->transid != root->fs_info->running_transaction->transid);
111827cdeb70SMiao Xie 	WARN_ON(test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
111927cdeb70SMiao Xie 		trans->transid != root->last_trans);
11205f39d397SChris Mason 
11217bb86316SChris Mason 	level = btrfs_header_level(buf);
112231840ae1SZheng Yan 
11235d4f98a2SYan Zheng 	if (level == 0)
11245d4f98a2SYan Zheng 		btrfs_item_key(buf, &disk_key, 0);
11255d4f98a2SYan Zheng 	else
11265d4f98a2SYan Zheng 		btrfs_node_key(buf, &disk_key, 0);
11275d4f98a2SYan Zheng 
11285d4f98a2SYan Zheng 	if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) {
11295d4f98a2SYan Zheng 		if (parent)
11305d4f98a2SYan Zheng 			parent_start = parent->start;
11315d4f98a2SYan Zheng 		else
11325d4f98a2SYan Zheng 			parent_start = 0;
11335d4f98a2SYan Zheng 	} else
11345d4f98a2SYan Zheng 		parent_start = 0;
11355d4f98a2SYan Zheng 
11365d4f98a2SYan Zheng 	cow = btrfs_alloc_free_block(trans, root, buf->len, parent_start,
11375d4f98a2SYan Zheng 				     root->root_key.objectid, &disk_key,
11385581a51aSJan Schmidt 				     level, search_start, empty_size);
11396702ed49SChris Mason 	if (IS_ERR(cow))
11406702ed49SChris Mason 		return PTR_ERR(cow);
11416702ed49SChris Mason 
1142b4ce94deSChris Mason 	/* cow is set to blocking by btrfs_init_new_buffer */
1143b4ce94deSChris Mason 
11445f39d397SChris Mason 	copy_extent_buffer(cow, buf, 0, 0, cow->len);
1145db94535dSChris Mason 	btrfs_set_header_bytenr(cow, cow->start);
11465f39d397SChris Mason 	btrfs_set_header_generation(cow, trans->transid);
11475d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
11485d4f98a2SYan Zheng 	btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
11495d4f98a2SYan Zheng 				     BTRFS_HEADER_FLAG_RELOC);
11505d4f98a2SYan Zheng 	if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
11515d4f98a2SYan Zheng 		btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
11525d4f98a2SYan Zheng 	else
11535f39d397SChris Mason 		btrfs_set_header_owner(cow, root->root_key.objectid);
11546702ed49SChris Mason 
11550a4e5586SRoss Kirk 	write_extent_buffer(cow, root->fs_info->fsid, btrfs_header_fsid(),
11562b82032cSYan Zheng 			    BTRFS_FSID_SIZE);
11572b82032cSYan Zheng 
1158be1a5564SMark Fasheh 	ret = update_ref_for_cow(trans, root, buf, cow, &last_ref);
1159b68dc2a9SMark Fasheh 	if (ret) {
116079787eaaSJeff Mahoney 		btrfs_abort_transaction(trans, root, ret);
1161b68dc2a9SMark Fasheh 		return ret;
1162b68dc2a9SMark Fasheh 	}
11631a40e23bSZheng Yan 
116427cdeb70SMiao Xie 	if (test_bit(BTRFS_ROOT_REF_COWS, &root->state)) {
116583d4cfd4SJosef Bacik 		ret = btrfs_reloc_cow_block(trans, root, buf, cow);
116683d4cfd4SJosef Bacik 		if (ret)
116783d4cfd4SJosef Bacik 			return ret;
116883d4cfd4SJosef Bacik 	}
11693fd0a558SYan, Zheng 
11706702ed49SChris Mason 	if (buf == root->node) {
1171925baeddSChris Mason 		WARN_ON(parent && parent != buf);
11725d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
11735d4f98a2SYan Zheng 		    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
11745d4f98a2SYan Zheng 			parent_start = buf->start;
11755d4f98a2SYan Zheng 		else
11765d4f98a2SYan Zheng 			parent_start = 0;
1177925baeddSChris Mason 
11785f39d397SChris Mason 		extent_buffer_get(cow);
117990f8d62eSJan Schmidt 		tree_mod_log_set_root_pointer(root, cow, 1);
1180240f62c8SChris Mason 		rcu_assign_pointer(root->node, cow);
1181925baeddSChris Mason 
1182f0486c68SYan, Zheng 		btrfs_free_tree_block(trans, root, buf, parent_start,
11835581a51aSJan Schmidt 				      last_ref);
11845f39d397SChris Mason 		free_extent_buffer(buf);
11850b86a832SChris Mason 		add_root_to_dirty_list(root);
11866702ed49SChris Mason 	} else {
11875d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
11885d4f98a2SYan Zheng 			parent_start = parent->start;
11895d4f98a2SYan Zheng 		else
11905d4f98a2SYan Zheng 			parent_start = 0;
11915d4f98a2SYan Zheng 
11925d4f98a2SYan Zheng 		WARN_ON(trans->transid != btrfs_header_generation(parent));
1193f230475eSJan Schmidt 		tree_mod_log_insert_key(root->fs_info, parent, parent_slot,
1194c8cc6341SJosef Bacik 					MOD_LOG_KEY_REPLACE, GFP_NOFS);
11955f39d397SChris Mason 		btrfs_set_node_blockptr(parent, parent_slot,
1196db94535dSChris Mason 					cow->start);
119774493f7aSChris Mason 		btrfs_set_node_ptr_generation(parent, parent_slot,
119874493f7aSChris Mason 					      trans->transid);
11996702ed49SChris Mason 		btrfs_mark_buffer_dirty(parent);
12005de865eeSFilipe David Borba Manana 		if (last_ref) {
12015de865eeSFilipe David Borba Manana 			ret = tree_mod_log_free_eb(root->fs_info, buf);
12025de865eeSFilipe David Borba Manana 			if (ret) {
12035de865eeSFilipe David Borba Manana 				btrfs_abort_transaction(trans, root, ret);
12045de865eeSFilipe David Borba Manana 				return ret;
12055de865eeSFilipe David Borba Manana 			}
12065de865eeSFilipe David Borba Manana 		}
1207f0486c68SYan, Zheng 		btrfs_free_tree_block(trans, root, buf, parent_start,
12085581a51aSJan Schmidt 				      last_ref);
12096702ed49SChris Mason 	}
1210925baeddSChris Mason 	if (unlock_orig)
1211925baeddSChris Mason 		btrfs_tree_unlock(buf);
12123083ee2eSJosef Bacik 	free_extent_buffer_stale(buf);
12136702ed49SChris Mason 	btrfs_mark_buffer_dirty(cow);
12146702ed49SChris Mason 	*cow_ret = cow;
12156702ed49SChris Mason 	return 0;
12166702ed49SChris Mason }
12176702ed49SChris Mason 
12185d9e75c4SJan Schmidt /*
12195d9e75c4SJan Schmidt  * returns the logical address of the oldest predecessor of the given root.
12205d9e75c4SJan Schmidt  * entries older than time_seq are ignored.
12215d9e75c4SJan Schmidt  */
12225d9e75c4SJan Schmidt static struct tree_mod_elem *
12235d9e75c4SJan Schmidt __tree_mod_log_oldest_root(struct btrfs_fs_info *fs_info,
122430b0463aSJan Schmidt 			   struct extent_buffer *eb_root, u64 time_seq)
12255d9e75c4SJan Schmidt {
12265d9e75c4SJan Schmidt 	struct tree_mod_elem *tm;
12275d9e75c4SJan Schmidt 	struct tree_mod_elem *found = NULL;
122830b0463aSJan Schmidt 	u64 root_logical = eb_root->start;
12295d9e75c4SJan Schmidt 	int looped = 0;
12305d9e75c4SJan Schmidt 
12315d9e75c4SJan Schmidt 	if (!time_seq)
123235a3621bSStefan Behrens 		return NULL;
12335d9e75c4SJan Schmidt 
12345d9e75c4SJan Schmidt 	/*
12355d9e75c4SJan Schmidt 	 * the very last operation that's logged for a root is the replacement
12365d9e75c4SJan Schmidt 	 * operation (if it is replaced at all). this has the index of the *new*
12375d9e75c4SJan Schmidt 	 * root, making it the very first operation that's logged for this root.
12385d9e75c4SJan Schmidt 	 */
12395d9e75c4SJan Schmidt 	while (1) {
12405d9e75c4SJan Schmidt 		tm = tree_mod_log_search_oldest(fs_info, root_logical,
12415d9e75c4SJan Schmidt 						time_seq);
12425d9e75c4SJan Schmidt 		if (!looped && !tm)
124335a3621bSStefan Behrens 			return NULL;
12445d9e75c4SJan Schmidt 		/*
124528da9fb4SJan Schmidt 		 * if there are no tree operation for the oldest root, we simply
124628da9fb4SJan Schmidt 		 * return it. this should only happen if that (old) root is at
124728da9fb4SJan Schmidt 		 * level 0.
12485d9e75c4SJan Schmidt 		 */
124928da9fb4SJan Schmidt 		if (!tm)
125028da9fb4SJan Schmidt 			break;
12515d9e75c4SJan Schmidt 
125228da9fb4SJan Schmidt 		/*
125328da9fb4SJan Schmidt 		 * if there's an operation that's not a root replacement, we
125428da9fb4SJan Schmidt 		 * found the oldest version of our root. normally, we'll find a
125528da9fb4SJan Schmidt 		 * MOD_LOG_KEY_REMOVE_WHILE_FREEING operation here.
125628da9fb4SJan Schmidt 		 */
12575d9e75c4SJan Schmidt 		if (tm->op != MOD_LOG_ROOT_REPLACE)
12585d9e75c4SJan Schmidt 			break;
12595d9e75c4SJan Schmidt 
12605d9e75c4SJan Schmidt 		found = tm;
12615d9e75c4SJan Schmidt 		root_logical = tm->old_root.logical;
12625d9e75c4SJan Schmidt 		looped = 1;
12635d9e75c4SJan Schmidt 	}
12645d9e75c4SJan Schmidt 
1265a95236d9SJan Schmidt 	/* if there's no old root to return, return what we found instead */
1266a95236d9SJan Schmidt 	if (!found)
1267a95236d9SJan Schmidt 		found = tm;
1268a95236d9SJan Schmidt 
12695d9e75c4SJan Schmidt 	return found;
12705d9e75c4SJan Schmidt }
12715d9e75c4SJan Schmidt 
12725d9e75c4SJan Schmidt /*
12735d9e75c4SJan Schmidt  * tm is a pointer to the first operation to rewind within eb. then, all
12745d9e75c4SJan Schmidt  * previous operations will be rewinded (until we reach something older than
12755d9e75c4SJan Schmidt  * time_seq).
12765d9e75c4SJan Schmidt  */
12775d9e75c4SJan Schmidt static void
1278f1ca7e98SJosef Bacik __tree_mod_log_rewind(struct btrfs_fs_info *fs_info, struct extent_buffer *eb,
1279f1ca7e98SJosef Bacik 		      u64 time_seq, struct tree_mod_elem *first_tm)
12805d9e75c4SJan Schmidt {
12815d9e75c4SJan Schmidt 	u32 n;
12825d9e75c4SJan Schmidt 	struct rb_node *next;
12835d9e75c4SJan Schmidt 	struct tree_mod_elem *tm = first_tm;
12845d9e75c4SJan Schmidt 	unsigned long o_dst;
12855d9e75c4SJan Schmidt 	unsigned long o_src;
12865d9e75c4SJan Schmidt 	unsigned long p_size = sizeof(struct btrfs_key_ptr);
12875d9e75c4SJan Schmidt 
12885d9e75c4SJan Schmidt 	n = btrfs_header_nritems(eb);
1289f1ca7e98SJosef Bacik 	tree_mod_log_read_lock(fs_info);
1290097b8a7cSJan Schmidt 	while (tm && tm->seq >= time_seq) {
12915d9e75c4SJan Schmidt 		/*
12925d9e75c4SJan Schmidt 		 * all the operations are recorded with the operator used for
12935d9e75c4SJan Schmidt 		 * the modification. as we're going backwards, we do the
12945d9e75c4SJan Schmidt 		 * opposite of each operation here.
12955d9e75c4SJan Schmidt 		 */
12965d9e75c4SJan Schmidt 		switch (tm->op) {
12975d9e75c4SJan Schmidt 		case MOD_LOG_KEY_REMOVE_WHILE_FREEING:
12985d9e75c4SJan Schmidt 			BUG_ON(tm->slot < n);
12991c697d4aSEric Sandeen 			/* Fallthrough */
130095c80bb1SLiu Bo 		case MOD_LOG_KEY_REMOVE_WHILE_MOVING:
13014c3e6969SChris Mason 		case MOD_LOG_KEY_REMOVE:
13025d9e75c4SJan Schmidt 			btrfs_set_node_key(eb, &tm->key, tm->slot);
13035d9e75c4SJan Schmidt 			btrfs_set_node_blockptr(eb, tm->slot, tm->blockptr);
13045d9e75c4SJan Schmidt 			btrfs_set_node_ptr_generation(eb, tm->slot,
13055d9e75c4SJan Schmidt 						      tm->generation);
13064c3e6969SChris Mason 			n++;
13075d9e75c4SJan Schmidt 			break;
13085d9e75c4SJan Schmidt 		case MOD_LOG_KEY_REPLACE:
13095d9e75c4SJan Schmidt 			BUG_ON(tm->slot >= n);
13105d9e75c4SJan Schmidt 			btrfs_set_node_key(eb, &tm->key, tm->slot);
13115d9e75c4SJan Schmidt 			btrfs_set_node_blockptr(eb, tm->slot, tm->blockptr);
13125d9e75c4SJan Schmidt 			btrfs_set_node_ptr_generation(eb, tm->slot,
13135d9e75c4SJan Schmidt 						      tm->generation);
13145d9e75c4SJan Schmidt 			break;
13155d9e75c4SJan Schmidt 		case MOD_LOG_KEY_ADD:
131619956c7eSJan Schmidt 			/* if a move operation is needed it's in the log */
13175d9e75c4SJan Schmidt 			n--;
13185d9e75c4SJan Schmidt 			break;
13195d9e75c4SJan Schmidt 		case MOD_LOG_MOVE_KEYS:
1320c3193108SJan Schmidt 			o_dst = btrfs_node_key_ptr_offset(tm->slot);
1321c3193108SJan Schmidt 			o_src = btrfs_node_key_ptr_offset(tm->move.dst_slot);
1322c3193108SJan Schmidt 			memmove_extent_buffer(eb, o_dst, o_src,
13235d9e75c4SJan Schmidt 					      tm->move.nr_items * p_size);
13245d9e75c4SJan Schmidt 			break;
13255d9e75c4SJan Schmidt 		case MOD_LOG_ROOT_REPLACE:
13265d9e75c4SJan Schmidt 			/*
13275d9e75c4SJan Schmidt 			 * this operation is special. for roots, this must be
13285d9e75c4SJan Schmidt 			 * handled explicitly before rewinding.
13295d9e75c4SJan Schmidt 			 * for non-roots, this operation may exist if the node
13305d9e75c4SJan Schmidt 			 * was a root: root A -> child B; then A gets empty and
13315d9e75c4SJan Schmidt 			 * B is promoted to the new root. in the mod log, we'll
13325d9e75c4SJan Schmidt 			 * have a root-replace operation for B, a tree block
13335d9e75c4SJan Schmidt 			 * that is no root. we simply ignore that operation.
13345d9e75c4SJan Schmidt 			 */
13355d9e75c4SJan Schmidt 			break;
13365d9e75c4SJan Schmidt 		}
13375d9e75c4SJan Schmidt 		next = rb_next(&tm->node);
13385d9e75c4SJan Schmidt 		if (!next)
13395d9e75c4SJan Schmidt 			break;
13405d9e75c4SJan Schmidt 		tm = container_of(next, struct tree_mod_elem, node);
13415d9e75c4SJan Schmidt 		if (tm->index != first_tm->index)
13425d9e75c4SJan Schmidt 			break;
13435d9e75c4SJan Schmidt 	}
1344f1ca7e98SJosef Bacik 	tree_mod_log_read_unlock(fs_info);
13455d9e75c4SJan Schmidt 	btrfs_set_header_nritems(eb, n);
13465d9e75c4SJan Schmidt }
13475d9e75c4SJan Schmidt 
134847fb091fSJan Schmidt /*
134947fb091fSJan Schmidt  * Called with eb read locked. If the buffer cannot be rewinded, the same buffer
135047fb091fSJan Schmidt  * is returned. If rewind operations happen, a fresh buffer is returned. The
135147fb091fSJan Schmidt  * returned buffer is always read-locked. If the returned buffer is not the
135247fb091fSJan Schmidt  * input buffer, the lock on the input buffer is released and the input buffer
135347fb091fSJan Schmidt  * is freed (its refcount is decremented).
135447fb091fSJan Schmidt  */
13555d9e75c4SJan Schmidt static struct extent_buffer *
13569ec72677SJosef Bacik tree_mod_log_rewind(struct btrfs_fs_info *fs_info, struct btrfs_path *path,
13579ec72677SJosef Bacik 		    struct extent_buffer *eb, u64 time_seq)
13585d9e75c4SJan Schmidt {
13595d9e75c4SJan Schmidt 	struct extent_buffer *eb_rewin;
13605d9e75c4SJan Schmidt 	struct tree_mod_elem *tm;
13615d9e75c4SJan Schmidt 
13625d9e75c4SJan Schmidt 	if (!time_seq)
13635d9e75c4SJan Schmidt 		return eb;
13645d9e75c4SJan Schmidt 
13655d9e75c4SJan Schmidt 	if (btrfs_header_level(eb) == 0)
13665d9e75c4SJan Schmidt 		return eb;
13675d9e75c4SJan Schmidt 
13685d9e75c4SJan Schmidt 	tm = tree_mod_log_search(fs_info, eb->start, time_seq);
13695d9e75c4SJan Schmidt 	if (!tm)
13705d9e75c4SJan Schmidt 		return eb;
13715d9e75c4SJan Schmidt 
13729ec72677SJosef Bacik 	btrfs_set_path_blocking(path);
13739ec72677SJosef Bacik 	btrfs_set_lock_blocking_rw(eb, BTRFS_READ_LOCK);
13749ec72677SJosef Bacik 
13755d9e75c4SJan Schmidt 	if (tm->op == MOD_LOG_KEY_REMOVE_WHILE_FREEING) {
13765d9e75c4SJan Schmidt 		BUG_ON(tm->slot != 0);
13775d9e75c4SJan Schmidt 		eb_rewin = alloc_dummy_extent_buffer(eb->start,
13785d9e75c4SJan Schmidt 						fs_info->tree_root->nodesize);
1379db7f3436SJosef Bacik 		if (!eb_rewin) {
13809ec72677SJosef Bacik 			btrfs_tree_read_unlock_blocking(eb);
1381db7f3436SJosef Bacik 			free_extent_buffer(eb);
1382db7f3436SJosef Bacik 			return NULL;
1383db7f3436SJosef Bacik 		}
13845d9e75c4SJan Schmidt 		btrfs_set_header_bytenr(eb_rewin, eb->start);
13855d9e75c4SJan Schmidt 		btrfs_set_header_backref_rev(eb_rewin,
13865d9e75c4SJan Schmidt 					     btrfs_header_backref_rev(eb));
13875d9e75c4SJan Schmidt 		btrfs_set_header_owner(eb_rewin, btrfs_header_owner(eb));
1388c3193108SJan Schmidt 		btrfs_set_header_level(eb_rewin, btrfs_header_level(eb));
13895d9e75c4SJan Schmidt 	} else {
13905d9e75c4SJan Schmidt 		eb_rewin = btrfs_clone_extent_buffer(eb);
1391db7f3436SJosef Bacik 		if (!eb_rewin) {
13929ec72677SJosef Bacik 			btrfs_tree_read_unlock_blocking(eb);
1393db7f3436SJosef Bacik 			free_extent_buffer(eb);
1394db7f3436SJosef Bacik 			return NULL;
1395db7f3436SJosef Bacik 		}
13965d9e75c4SJan Schmidt 	}
13975d9e75c4SJan Schmidt 
13989ec72677SJosef Bacik 	btrfs_clear_path_blocking(path, NULL, BTRFS_READ_LOCK);
13999ec72677SJosef Bacik 	btrfs_tree_read_unlock_blocking(eb);
14005d9e75c4SJan Schmidt 	free_extent_buffer(eb);
14015d9e75c4SJan Schmidt 
140247fb091fSJan Schmidt 	extent_buffer_get(eb_rewin);
140347fb091fSJan Schmidt 	btrfs_tree_read_lock(eb_rewin);
1404f1ca7e98SJosef Bacik 	__tree_mod_log_rewind(fs_info, eb_rewin, time_seq, tm);
140557911b8bSJan Schmidt 	WARN_ON(btrfs_header_nritems(eb_rewin) >
14062a745b14SArne Jansen 		BTRFS_NODEPTRS_PER_BLOCK(fs_info->tree_root));
14075d9e75c4SJan Schmidt 
14085d9e75c4SJan Schmidt 	return eb_rewin;
14095d9e75c4SJan Schmidt }
14105d9e75c4SJan Schmidt 
14118ba97a15SJan Schmidt /*
14128ba97a15SJan Schmidt  * get_old_root() rewinds the state of @root's root node to the given @time_seq
14138ba97a15SJan Schmidt  * value. If there are no changes, the current root->root_node is returned. If
14148ba97a15SJan Schmidt  * anything changed in between, there's a fresh buffer allocated on which the
14158ba97a15SJan Schmidt  * rewind operations are done. In any case, the returned buffer is read locked.
14168ba97a15SJan Schmidt  * Returns NULL on error (with no locks held).
14178ba97a15SJan Schmidt  */
14185d9e75c4SJan Schmidt static inline struct extent_buffer *
14195d9e75c4SJan Schmidt get_old_root(struct btrfs_root *root, u64 time_seq)
14205d9e75c4SJan Schmidt {
14215d9e75c4SJan Schmidt 	struct tree_mod_elem *tm;
142230b0463aSJan Schmidt 	struct extent_buffer *eb = NULL;
142330b0463aSJan Schmidt 	struct extent_buffer *eb_root;
14247bfdcf7fSLiu Bo 	struct extent_buffer *old;
1425a95236d9SJan Schmidt 	struct tree_mod_root *old_root = NULL;
14264325edd0SChris Mason 	u64 old_generation = 0;
1427a95236d9SJan Schmidt 	u64 logical;
14285d9e75c4SJan Schmidt 
142930b0463aSJan Schmidt 	eb_root = btrfs_read_lock_root_node(root);
143030b0463aSJan Schmidt 	tm = __tree_mod_log_oldest_root(root->fs_info, eb_root, time_seq);
14315d9e75c4SJan Schmidt 	if (!tm)
143230b0463aSJan Schmidt 		return eb_root;
14335d9e75c4SJan Schmidt 
1434a95236d9SJan Schmidt 	if (tm->op == MOD_LOG_ROOT_REPLACE) {
14355d9e75c4SJan Schmidt 		old_root = &tm->old_root;
14365d9e75c4SJan Schmidt 		old_generation = tm->generation;
1437a95236d9SJan Schmidt 		logical = old_root->logical;
1438a95236d9SJan Schmidt 	} else {
143930b0463aSJan Schmidt 		logical = eb_root->start;
1440a95236d9SJan Schmidt 	}
14415d9e75c4SJan Schmidt 
1442a95236d9SJan Schmidt 	tm = tree_mod_log_search(root->fs_info, logical, time_seq);
1443834328a8SJan Schmidt 	if (old_root && tm && tm->op != MOD_LOG_KEY_REMOVE_WHILE_FREEING) {
144430b0463aSJan Schmidt 		btrfs_tree_read_unlock(eb_root);
144530b0463aSJan Schmidt 		free_extent_buffer(eb_root);
1446*ce86cd59SDavid Sterba 		old = read_tree_block(root, logical, 0);
1447fae7f21cSDulshani Gunawardhana 		if (WARN_ON(!old || !extent_buffer_uptodate(old))) {
1448416bc658SJosef Bacik 			free_extent_buffer(old);
1449efe120a0SFrank Holton 			btrfs_warn(root->fs_info,
1450efe120a0SFrank Holton 				"failed to read tree block %llu from get_old_root", logical);
1451834328a8SJan Schmidt 		} else {
14527bfdcf7fSLiu Bo 			eb = btrfs_clone_extent_buffer(old);
14537bfdcf7fSLiu Bo 			free_extent_buffer(old);
1454834328a8SJan Schmidt 		}
1455834328a8SJan Schmidt 	} else if (old_root) {
145630b0463aSJan Schmidt 		btrfs_tree_read_unlock(eb_root);
145730b0463aSJan Schmidt 		free_extent_buffer(eb_root);
145828da9fb4SJan Schmidt 		eb = alloc_dummy_extent_buffer(logical, root->nodesize);
1459834328a8SJan Schmidt 	} else {
14609ec72677SJosef Bacik 		btrfs_set_lock_blocking_rw(eb_root, BTRFS_READ_LOCK);
146130b0463aSJan Schmidt 		eb = btrfs_clone_extent_buffer(eb_root);
14629ec72677SJosef Bacik 		btrfs_tree_read_unlock_blocking(eb_root);
146330b0463aSJan Schmidt 		free_extent_buffer(eb_root);
1464834328a8SJan Schmidt 	}
1465834328a8SJan Schmidt 
14668ba97a15SJan Schmidt 	if (!eb)
14678ba97a15SJan Schmidt 		return NULL;
1468d6381084SJan Schmidt 	extent_buffer_get(eb);
14698ba97a15SJan Schmidt 	btrfs_tree_read_lock(eb);
1470a95236d9SJan Schmidt 	if (old_root) {
14715d9e75c4SJan Schmidt 		btrfs_set_header_bytenr(eb, eb->start);
14725d9e75c4SJan Schmidt 		btrfs_set_header_backref_rev(eb, BTRFS_MIXED_BACKREF_REV);
147330b0463aSJan Schmidt 		btrfs_set_header_owner(eb, btrfs_header_owner(eb_root));
14745d9e75c4SJan Schmidt 		btrfs_set_header_level(eb, old_root->level);
14755d9e75c4SJan Schmidt 		btrfs_set_header_generation(eb, old_generation);
1476a95236d9SJan Schmidt 	}
147728da9fb4SJan Schmidt 	if (tm)
1478f1ca7e98SJosef Bacik 		__tree_mod_log_rewind(root->fs_info, eb, time_seq, tm);
147928da9fb4SJan Schmidt 	else
148028da9fb4SJan Schmidt 		WARN_ON(btrfs_header_level(eb) != 0);
148157911b8bSJan Schmidt 	WARN_ON(btrfs_header_nritems(eb) > BTRFS_NODEPTRS_PER_BLOCK(root));
14825d9e75c4SJan Schmidt 
14835d9e75c4SJan Schmidt 	return eb;
14845d9e75c4SJan Schmidt }
14855d9e75c4SJan Schmidt 
14865b6602e7SJan Schmidt int btrfs_old_root_level(struct btrfs_root *root, u64 time_seq)
14875b6602e7SJan Schmidt {
14885b6602e7SJan Schmidt 	struct tree_mod_elem *tm;
14895b6602e7SJan Schmidt 	int level;
149030b0463aSJan Schmidt 	struct extent_buffer *eb_root = btrfs_root_node(root);
14915b6602e7SJan Schmidt 
149230b0463aSJan Schmidt 	tm = __tree_mod_log_oldest_root(root->fs_info, eb_root, time_seq);
14935b6602e7SJan Schmidt 	if (tm && tm->op == MOD_LOG_ROOT_REPLACE) {
14945b6602e7SJan Schmidt 		level = tm->old_root.level;
14955b6602e7SJan Schmidt 	} else {
149630b0463aSJan Schmidt 		level = btrfs_header_level(eb_root);
14975b6602e7SJan Schmidt 	}
149830b0463aSJan Schmidt 	free_extent_buffer(eb_root);
14995b6602e7SJan Schmidt 
15005b6602e7SJan Schmidt 	return level;
15015b6602e7SJan Schmidt }
15025b6602e7SJan Schmidt 
15035d4f98a2SYan Zheng static inline int should_cow_block(struct btrfs_trans_handle *trans,
15045d4f98a2SYan Zheng 				   struct btrfs_root *root,
15055d4f98a2SYan Zheng 				   struct extent_buffer *buf)
15065d4f98a2SYan Zheng {
1507faa2dbf0SJosef Bacik #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
1508faa2dbf0SJosef Bacik 	if (unlikely(test_bit(BTRFS_ROOT_DUMMY_ROOT, &root->state)))
1509faa2dbf0SJosef Bacik 		return 0;
1510faa2dbf0SJosef Bacik #endif
1511f1ebcc74SLiu Bo 	/* ensure we can see the force_cow */
1512f1ebcc74SLiu Bo 	smp_rmb();
1513f1ebcc74SLiu Bo 
1514f1ebcc74SLiu Bo 	/*
1515f1ebcc74SLiu Bo 	 * We do not need to cow a block if
1516f1ebcc74SLiu Bo 	 * 1) this block is not created or changed in this transaction;
1517f1ebcc74SLiu Bo 	 * 2) this block does not belong to TREE_RELOC tree;
1518f1ebcc74SLiu Bo 	 * 3) the root is not forced COW.
1519f1ebcc74SLiu Bo 	 *
1520f1ebcc74SLiu Bo 	 * What is forced COW:
1521f1ebcc74SLiu Bo 	 *    when we create snapshot during commiting the transaction,
1522f1ebcc74SLiu Bo 	 *    after we've finished coping src root, we must COW the shared
1523f1ebcc74SLiu Bo 	 *    block to ensure the metadata consistency.
1524f1ebcc74SLiu Bo 	 */
15255d4f98a2SYan Zheng 	if (btrfs_header_generation(buf) == trans->transid &&
15265d4f98a2SYan Zheng 	    !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN) &&
15275d4f98a2SYan Zheng 	    !(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
1528f1ebcc74SLiu Bo 	      btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)) &&
152927cdeb70SMiao Xie 	    !test_bit(BTRFS_ROOT_FORCE_COW, &root->state))
15305d4f98a2SYan Zheng 		return 0;
15315d4f98a2SYan Zheng 	return 1;
15325d4f98a2SYan Zheng }
15335d4f98a2SYan Zheng 
1534d352ac68SChris Mason /*
1535d352ac68SChris Mason  * cows a single block, see __btrfs_cow_block for the real work.
1536d352ac68SChris Mason  * This version of it has extra checks so that a block isn't cow'd more than
1537d352ac68SChris Mason  * once per transaction, as long as it hasn't been written yet
1538d352ac68SChris Mason  */
1539d397712bSChris Mason noinline int btrfs_cow_block(struct btrfs_trans_handle *trans,
15405f39d397SChris Mason 		    struct btrfs_root *root, struct extent_buffer *buf,
15415f39d397SChris Mason 		    struct extent_buffer *parent, int parent_slot,
15429fa8cfe7SChris Mason 		    struct extent_buffer **cow_ret)
154302217ed2SChris Mason {
15446702ed49SChris Mason 	u64 search_start;
1545f510cfecSChris Mason 	int ret;
1546dc17ff8fSChris Mason 
154731b1a2bdSJulia Lawall 	if (trans->transaction != root->fs_info->running_transaction)
154831b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "trans %llu running %llu\n",
1549c1c9ff7cSGeert Uytterhoeven 		       trans->transid,
1550ccd467d6SChris Mason 		       root->fs_info->running_transaction->transid);
155131b1a2bdSJulia Lawall 
155231b1a2bdSJulia Lawall 	if (trans->transid != root->fs_info->generation)
155331b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "trans %llu running %llu\n",
1554c1c9ff7cSGeert Uytterhoeven 		       trans->transid, root->fs_info->generation);
1555dc17ff8fSChris Mason 
15565d4f98a2SYan Zheng 	if (!should_cow_block(trans, root, buf)) {
155702217ed2SChris Mason 		*cow_ret = buf;
155802217ed2SChris Mason 		return 0;
155902217ed2SChris Mason 	}
1560c487685dSChris Mason 
15610b86a832SChris Mason 	search_start = buf->start & ~((u64)(1024 * 1024 * 1024) - 1);
1562b4ce94deSChris Mason 
1563b4ce94deSChris Mason 	if (parent)
1564b4ce94deSChris Mason 		btrfs_set_lock_blocking(parent);
1565b4ce94deSChris Mason 	btrfs_set_lock_blocking(buf);
1566b4ce94deSChris Mason 
1567f510cfecSChris Mason 	ret = __btrfs_cow_block(trans, root, buf, parent,
15689fa8cfe7SChris Mason 				 parent_slot, cow_ret, search_start, 0);
15691abe9b8aSliubo 
15701abe9b8aSliubo 	trace_btrfs_cow_block(root, buf, *cow_ret);
15711abe9b8aSliubo 
1572f510cfecSChris Mason 	return ret;
15732c90e5d6SChris Mason }
15746702ed49SChris Mason 
1575d352ac68SChris Mason /*
1576d352ac68SChris Mason  * helper function for defrag to decide if two blocks pointed to by a
1577d352ac68SChris Mason  * node are actually close by
1578d352ac68SChris Mason  */
15796b80053dSChris Mason static int close_blocks(u64 blocknr, u64 other, u32 blocksize)
15806702ed49SChris Mason {
15816b80053dSChris Mason 	if (blocknr < other && other - (blocknr + blocksize) < 32768)
15826702ed49SChris Mason 		return 1;
15836b80053dSChris Mason 	if (blocknr > other && blocknr - (other + blocksize) < 32768)
15846702ed49SChris Mason 		return 1;
158502217ed2SChris Mason 	return 0;
158602217ed2SChris Mason }
158702217ed2SChris Mason 
1588081e9573SChris Mason /*
1589081e9573SChris Mason  * compare two keys in a memcmp fashion
1590081e9573SChris Mason  */
1591081e9573SChris Mason static int comp_keys(struct btrfs_disk_key *disk, struct btrfs_key *k2)
1592081e9573SChris Mason {
1593081e9573SChris Mason 	struct btrfs_key k1;
1594081e9573SChris Mason 
1595081e9573SChris Mason 	btrfs_disk_key_to_cpu(&k1, disk);
1596081e9573SChris Mason 
159720736abaSDiego Calleja 	return btrfs_comp_cpu_keys(&k1, k2);
1598081e9573SChris Mason }
1599081e9573SChris Mason 
1600f3465ca4SJosef Bacik /*
1601f3465ca4SJosef Bacik  * same as comp_keys only with two btrfs_key's
1602f3465ca4SJosef Bacik  */
16035d4f98a2SYan Zheng int btrfs_comp_cpu_keys(struct btrfs_key *k1, struct btrfs_key *k2)
1604f3465ca4SJosef Bacik {
1605f3465ca4SJosef Bacik 	if (k1->objectid > k2->objectid)
1606f3465ca4SJosef Bacik 		return 1;
1607f3465ca4SJosef Bacik 	if (k1->objectid < k2->objectid)
1608f3465ca4SJosef Bacik 		return -1;
1609f3465ca4SJosef Bacik 	if (k1->type > k2->type)
1610f3465ca4SJosef Bacik 		return 1;
1611f3465ca4SJosef Bacik 	if (k1->type < k2->type)
1612f3465ca4SJosef Bacik 		return -1;
1613f3465ca4SJosef Bacik 	if (k1->offset > k2->offset)
1614f3465ca4SJosef Bacik 		return 1;
1615f3465ca4SJosef Bacik 	if (k1->offset < k2->offset)
1616f3465ca4SJosef Bacik 		return -1;
1617f3465ca4SJosef Bacik 	return 0;
1618f3465ca4SJosef Bacik }
1619081e9573SChris Mason 
1620d352ac68SChris Mason /*
1621d352ac68SChris Mason  * this is used by the defrag code to go through all the
1622d352ac68SChris Mason  * leaves pointed to by a node and reallocate them so that
1623d352ac68SChris Mason  * disk order is close to key order
1624d352ac68SChris Mason  */
16256702ed49SChris Mason int btrfs_realloc_node(struct btrfs_trans_handle *trans,
16265f39d397SChris Mason 		       struct btrfs_root *root, struct extent_buffer *parent,
1627de78b51aSEric Sandeen 		       int start_slot, u64 *last_ret,
1628a6b6e75eSChris Mason 		       struct btrfs_key *progress)
16296702ed49SChris Mason {
16306b80053dSChris Mason 	struct extent_buffer *cur;
16316702ed49SChris Mason 	u64 blocknr;
1632ca7a79adSChris Mason 	u64 gen;
1633e9d0b13bSChris Mason 	u64 search_start = *last_ret;
1634e9d0b13bSChris Mason 	u64 last_block = 0;
16356702ed49SChris Mason 	u64 other;
16366702ed49SChris Mason 	u32 parent_nritems;
16376702ed49SChris Mason 	int end_slot;
16386702ed49SChris Mason 	int i;
16396702ed49SChris Mason 	int err = 0;
1640f2183bdeSChris Mason 	int parent_level;
16416b80053dSChris Mason 	int uptodate;
16426b80053dSChris Mason 	u32 blocksize;
1643081e9573SChris Mason 	int progress_passed = 0;
1644081e9573SChris Mason 	struct btrfs_disk_key disk_key;
16456702ed49SChris Mason 
16465708b959SChris Mason 	parent_level = btrfs_header_level(parent);
16475708b959SChris Mason 
16486c1500f2SJulia Lawall 	WARN_ON(trans->transaction != root->fs_info->running_transaction);
16496c1500f2SJulia Lawall 	WARN_ON(trans->transid != root->fs_info->generation);
165086479a04SChris Mason 
16516b80053dSChris Mason 	parent_nritems = btrfs_header_nritems(parent);
1652707e8a07SDavid Sterba 	blocksize = root->nodesize;
16536702ed49SChris Mason 	end_slot = parent_nritems;
16546702ed49SChris Mason 
16556702ed49SChris Mason 	if (parent_nritems == 1)
16566702ed49SChris Mason 		return 0;
16576702ed49SChris Mason 
1658b4ce94deSChris Mason 	btrfs_set_lock_blocking(parent);
1659b4ce94deSChris Mason 
16606702ed49SChris Mason 	for (i = start_slot; i < end_slot; i++) {
16616702ed49SChris Mason 		int close = 1;
1662a6b6e75eSChris Mason 
1663081e9573SChris Mason 		btrfs_node_key(parent, &disk_key, i);
1664081e9573SChris Mason 		if (!progress_passed && comp_keys(&disk_key, progress) < 0)
1665081e9573SChris Mason 			continue;
1666081e9573SChris Mason 
1667081e9573SChris Mason 		progress_passed = 1;
16686b80053dSChris Mason 		blocknr = btrfs_node_blockptr(parent, i);
1669ca7a79adSChris Mason 		gen = btrfs_node_ptr_generation(parent, i);
1670e9d0b13bSChris Mason 		if (last_block == 0)
1671e9d0b13bSChris Mason 			last_block = blocknr;
16725708b959SChris Mason 
16736702ed49SChris Mason 		if (i > 0) {
16746b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i - 1);
16756b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
16766702ed49SChris Mason 		}
16770ef3e66bSChris Mason 		if (!close && i < end_slot - 2) {
16786b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i + 1);
16796b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
16806702ed49SChris Mason 		}
1681e9d0b13bSChris Mason 		if (close) {
1682e9d0b13bSChris Mason 			last_block = blocknr;
16836702ed49SChris Mason 			continue;
1684e9d0b13bSChris Mason 		}
16856702ed49SChris Mason 
16866b80053dSChris Mason 		cur = btrfs_find_tree_block(root, blocknr, blocksize);
16876b80053dSChris Mason 		if (cur)
1688b9fab919SChris Mason 			uptodate = btrfs_buffer_uptodate(cur, gen, 0);
16896b80053dSChris Mason 		else
16906b80053dSChris Mason 			uptodate = 0;
16915708b959SChris Mason 		if (!cur || !uptodate) {
16926b80053dSChris Mason 			if (!cur) {
1693*ce86cd59SDavid Sterba 				cur = read_tree_block(root, blocknr, gen);
1694416bc658SJosef Bacik 				if (!cur || !extent_buffer_uptodate(cur)) {
1695416bc658SJosef Bacik 					free_extent_buffer(cur);
169697d9a8a4STsutomu Itoh 					return -EIO;
1697416bc658SJosef Bacik 				}
16986b80053dSChris Mason 			} else if (!uptodate) {
1699018642a1STsutomu Itoh 				err = btrfs_read_buffer(cur, gen);
1700018642a1STsutomu Itoh 				if (err) {
1701018642a1STsutomu Itoh 					free_extent_buffer(cur);
1702018642a1STsutomu Itoh 					return err;
1703018642a1STsutomu Itoh 				}
17046702ed49SChris Mason 			}
1705f2183bdeSChris Mason 		}
1706e9d0b13bSChris Mason 		if (search_start == 0)
17076b80053dSChris Mason 			search_start = last_block;
1708e9d0b13bSChris Mason 
1709e7a84565SChris Mason 		btrfs_tree_lock(cur);
1710b4ce94deSChris Mason 		btrfs_set_lock_blocking(cur);
17116b80053dSChris Mason 		err = __btrfs_cow_block(trans, root, cur, parent, i,
1712e7a84565SChris Mason 					&cur, search_start,
17136b80053dSChris Mason 					min(16 * blocksize,
17149fa8cfe7SChris Mason 					    (end_slot - i) * blocksize));
1715252c38f0SYan 		if (err) {
1716e7a84565SChris Mason 			btrfs_tree_unlock(cur);
17176b80053dSChris Mason 			free_extent_buffer(cur);
17186702ed49SChris Mason 			break;
1719252c38f0SYan 		}
1720e7a84565SChris Mason 		search_start = cur->start;
1721e7a84565SChris Mason 		last_block = cur->start;
1722f2183bdeSChris Mason 		*last_ret = search_start;
1723e7a84565SChris Mason 		btrfs_tree_unlock(cur);
1724e7a84565SChris Mason 		free_extent_buffer(cur);
17256702ed49SChris Mason 	}
17266702ed49SChris Mason 	return err;
17276702ed49SChris Mason }
17286702ed49SChris Mason 
172974123bd7SChris Mason /*
173074123bd7SChris Mason  * The leaf data grows from end-to-front in the node.
173174123bd7SChris Mason  * this returns the address of the start of the last item,
173274123bd7SChris Mason  * which is the stop of the leaf data stack
173374123bd7SChris Mason  */
1734123abc88SChris Mason static inline unsigned int leaf_data_end(struct btrfs_root *root,
17355f39d397SChris Mason 					 struct extent_buffer *leaf)
1736be0e5c09SChris Mason {
17375f39d397SChris Mason 	u32 nr = btrfs_header_nritems(leaf);
1738be0e5c09SChris Mason 	if (nr == 0)
1739123abc88SChris Mason 		return BTRFS_LEAF_DATA_SIZE(root);
17405f39d397SChris Mason 	return btrfs_item_offset_nr(leaf, nr - 1);
1741be0e5c09SChris Mason }
1742be0e5c09SChris Mason 
1743aa5d6bedSChris Mason 
174474123bd7SChris Mason /*
17455f39d397SChris Mason  * search for key in the extent_buffer.  The items start at offset p,
17465f39d397SChris Mason  * and they are item_size apart.  There are 'max' items in p.
17475f39d397SChris Mason  *
174874123bd7SChris Mason  * the slot in the array is returned via slot, and it points to
174974123bd7SChris Mason  * the place where you would insert key if it is not found in
175074123bd7SChris Mason  * the array.
175174123bd7SChris Mason  *
175274123bd7SChris Mason  * slot may point to max if the key is bigger than all of the keys
175374123bd7SChris Mason  */
1754e02119d5SChris Mason static noinline int generic_bin_search(struct extent_buffer *eb,
1755e02119d5SChris Mason 				       unsigned long p,
17565f39d397SChris Mason 				       int item_size, struct btrfs_key *key,
1757be0e5c09SChris Mason 				       int max, int *slot)
1758be0e5c09SChris Mason {
1759be0e5c09SChris Mason 	int low = 0;
1760be0e5c09SChris Mason 	int high = max;
1761be0e5c09SChris Mason 	int mid;
1762be0e5c09SChris Mason 	int ret;
1763479965d6SChris Mason 	struct btrfs_disk_key *tmp = NULL;
17645f39d397SChris Mason 	struct btrfs_disk_key unaligned;
17655f39d397SChris Mason 	unsigned long offset;
17665f39d397SChris Mason 	char *kaddr = NULL;
17675f39d397SChris Mason 	unsigned long map_start = 0;
17685f39d397SChris Mason 	unsigned long map_len = 0;
1769479965d6SChris Mason 	int err;
1770be0e5c09SChris Mason 
1771be0e5c09SChris Mason 	while (low < high) {
1772be0e5c09SChris Mason 		mid = (low + high) / 2;
17735f39d397SChris Mason 		offset = p + mid * item_size;
17745f39d397SChris Mason 
1775a6591715SChris Mason 		if (!kaddr || offset < map_start ||
17765f39d397SChris Mason 		    (offset + sizeof(struct btrfs_disk_key)) >
17775f39d397SChris Mason 		    map_start + map_len) {
1778934d375bSChris Mason 
1779934d375bSChris Mason 			err = map_private_extent_buffer(eb, offset,
1780479965d6SChris Mason 						sizeof(struct btrfs_disk_key),
1781a6591715SChris Mason 						&kaddr, &map_start, &map_len);
17825f39d397SChris Mason 
1783479965d6SChris Mason 			if (!err) {
1784479965d6SChris Mason 				tmp = (struct btrfs_disk_key *)(kaddr + offset -
1785479965d6SChris Mason 							map_start);
1786479965d6SChris Mason 			} else {
17875f39d397SChris Mason 				read_extent_buffer(eb, &unaligned,
17885f39d397SChris Mason 						   offset, sizeof(unaligned));
17895f39d397SChris Mason 				tmp = &unaligned;
1790479965d6SChris Mason 			}
1791479965d6SChris Mason 
17925f39d397SChris Mason 		} else {
17935f39d397SChris Mason 			tmp = (struct btrfs_disk_key *)(kaddr + offset -
17945f39d397SChris Mason 							map_start);
17955f39d397SChris Mason 		}
1796be0e5c09SChris Mason 		ret = comp_keys(tmp, key);
1797be0e5c09SChris Mason 
1798be0e5c09SChris Mason 		if (ret < 0)
1799be0e5c09SChris Mason 			low = mid + 1;
1800be0e5c09SChris Mason 		else if (ret > 0)
1801be0e5c09SChris Mason 			high = mid;
1802be0e5c09SChris Mason 		else {
1803be0e5c09SChris Mason 			*slot = mid;
1804be0e5c09SChris Mason 			return 0;
1805be0e5c09SChris Mason 		}
1806be0e5c09SChris Mason 	}
1807be0e5c09SChris Mason 	*slot = low;
1808be0e5c09SChris Mason 	return 1;
1809be0e5c09SChris Mason }
1810be0e5c09SChris Mason 
181197571fd0SChris Mason /*
181297571fd0SChris Mason  * simple bin_search frontend that does the right thing for
181397571fd0SChris Mason  * leaves vs nodes
181497571fd0SChris Mason  */
18155f39d397SChris Mason static int bin_search(struct extent_buffer *eb, struct btrfs_key *key,
18165f39d397SChris Mason 		      int level, int *slot)
1817be0e5c09SChris Mason {
1818f775738fSWang Sheng-Hui 	if (level == 0)
18195f39d397SChris Mason 		return generic_bin_search(eb,
18205f39d397SChris Mason 					  offsetof(struct btrfs_leaf, items),
18210783fcfcSChris Mason 					  sizeof(struct btrfs_item),
18225f39d397SChris Mason 					  key, btrfs_header_nritems(eb),
18237518a238SChris Mason 					  slot);
1824f775738fSWang Sheng-Hui 	else
18255f39d397SChris Mason 		return generic_bin_search(eb,
18265f39d397SChris Mason 					  offsetof(struct btrfs_node, ptrs),
1827123abc88SChris Mason 					  sizeof(struct btrfs_key_ptr),
18285f39d397SChris Mason 					  key, btrfs_header_nritems(eb),
18297518a238SChris Mason 					  slot);
1830be0e5c09SChris Mason }
1831be0e5c09SChris Mason 
18325d4f98a2SYan Zheng int btrfs_bin_search(struct extent_buffer *eb, struct btrfs_key *key,
18335d4f98a2SYan Zheng 		     int level, int *slot)
18345d4f98a2SYan Zheng {
18355d4f98a2SYan Zheng 	return bin_search(eb, key, level, slot);
18365d4f98a2SYan Zheng }
18375d4f98a2SYan Zheng 
1838f0486c68SYan, Zheng static void root_add_used(struct btrfs_root *root, u32 size)
1839f0486c68SYan, Zheng {
1840f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
1841f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
1842f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) + size);
1843f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
1844f0486c68SYan, Zheng }
1845f0486c68SYan, Zheng 
1846f0486c68SYan, Zheng static void root_sub_used(struct btrfs_root *root, u32 size)
1847f0486c68SYan, Zheng {
1848f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
1849f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
1850f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) - size);
1851f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
1852f0486c68SYan, Zheng }
1853f0486c68SYan, Zheng 
1854d352ac68SChris Mason /* given a node and slot number, this reads the blocks it points to.  The
1855d352ac68SChris Mason  * extent buffer is returned with a reference taken (but unlocked).
1856d352ac68SChris Mason  * NULL is returned on error.
1857d352ac68SChris Mason  */
1858e02119d5SChris Mason static noinline struct extent_buffer *read_node_slot(struct btrfs_root *root,
18595f39d397SChris Mason 				   struct extent_buffer *parent, int slot)
1860bb803951SChris Mason {
1861ca7a79adSChris Mason 	int level = btrfs_header_level(parent);
1862416bc658SJosef Bacik 	struct extent_buffer *eb;
1863416bc658SJosef Bacik 
1864bb803951SChris Mason 	if (slot < 0)
1865bb803951SChris Mason 		return NULL;
18665f39d397SChris Mason 	if (slot >= btrfs_header_nritems(parent))
1867bb803951SChris Mason 		return NULL;
1868ca7a79adSChris Mason 
1869ca7a79adSChris Mason 	BUG_ON(level == 0);
1870ca7a79adSChris Mason 
1871416bc658SJosef Bacik 	eb = read_tree_block(root, btrfs_node_blockptr(parent, slot),
1872ca7a79adSChris Mason 			     btrfs_node_ptr_generation(parent, slot));
1873416bc658SJosef Bacik 	if (eb && !extent_buffer_uptodate(eb)) {
1874416bc658SJosef Bacik 		free_extent_buffer(eb);
1875416bc658SJosef Bacik 		eb = NULL;
1876416bc658SJosef Bacik 	}
1877416bc658SJosef Bacik 
1878416bc658SJosef Bacik 	return eb;
1879bb803951SChris Mason }
1880bb803951SChris Mason 
1881d352ac68SChris Mason /*
1882d352ac68SChris Mason  * node level balancing, used to make sure nodes are in proper order for
1883d352ac68SChris Mason  * item deletion.  We balance from the top down, so we have to make sure
1884d352ac68SChris Mason  * that a deletion won't leave an node completely empty later on.
1885d352ac68SChris Mason  */
1886e02119d5SChris Mason static noinline int balance_level(struct btrfs_trans_handle *trans,
188798ed5174SChris Mason 			 struct btrfs_root *root,
188898ed5174SChris Mason 			 struct btrfs_path *path, int level)
1889bb803951SChris Mason {
18905f39d397SChris Mason 	struct extent_buffer *right = NULL;
18915f39d397SChris Mason 	struct extent_buffer *mid;
18925f39d397SChris Mason 	struct extent_buffer *left = NULL;
18935f39d397SChris Mason 	struct extent_buffer *parent = NULL;
1894bb803951SChris Mason 	int ret = 0;
1895bb803951SChris Mason 	int wret;
1896bb803951SChris Mason 	int pslot;
1897bb803951SChris Mason 	int orig_slot = path->slots[level];
189879f95c82SChris Mason 	u64 orig_ptr;
1899bb803951SChris Mason 
1900bb803951SChris Mason 	if (level == 0)
1901bb803951SChris Mason 		return 0;
1902bb803951SChris Mason 
19035f39d397SChris Mason 	mid = path->nodes[level];
1904b4ce94deSChris Mason 
1905bd681513SChris Mason 	WARN_ON(path->locks[level] != BTRFS_WRITE_LOCK &&
1906bd681513SChris Mason 		path->locks[level] != BTRFS_WRITE_LOCK_BLOCKING);
19077bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
19087bb86316SChris Mason 
19091d4f8a0cSChris Mason 	orig_ptr = btrfs_node_blockptr(mid, orig_slot);
191079f95c82SChris Mason 
1911a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
19125f39d397SChris Mason 		parent = path->nodes[level + 1];
1913bb803951SChris Mason 		pslot = path->slots[level + 1];
1914a05a9bb1SLi Zefan 	}
1915bb803951SChris Mason 
191640689478SChris Mason 	/*
191740689478SChris Mason 	 * deal with the case where there is only one pointer in the root
191840689478SChris Mason 	 * by promoting the node below to a root
191940689478SChris Mason 	 */
19205f39d397SChris Mason 	if (!parent) {
19215f39d397SChris Mason 		struct extent_buffer *child;
1922bb803951SChris Mason 
19235f39d397SChris Mason 		if (btrfs_header_nritems(mid) != 1)
1924bb803951SChris Mason 			return 0;
1925bb803951SChris Mason 
1926bb803951SChris Mason 		/* promote the child to a root */
19275f39d397SChris Mason 		child = read_node_slot(root, mid, 0);
1928305a26afSMark Fasheh 		if (!child) {
1929305a26afSMark Fasheh 			ret = -EROFS;
1930305a26afSMark Fasheh 			btrfs_std_error(root->fs_info, ret);
1931305a26afSMark Fasheh 			goto enospc;
1932305a26afSMark Fasheh 		}
1933305a26afSMark Fasheh 
1934925baeddSChris Mason 		btrfs_tree_lock(child);
1935b4ce94deSChris Mason 		btrfs_set_lock_blocking(child);
19369fa8cfe7SChris Mason 		ret = btrfs_cow_block(trans, root, child, mid, 0, &child);
1937f0486c68SYan, Zheng 		if (ret) {
1938f0486c68SYan, Zheng 			btrfs_tree_unlock(child);
1939f0486c68SYan, Zheng 			free_extent_buffer(child);
1940f0486c68SYan, Zheng 			goto enospc;
1941f0486c68SYan, Zheng 		}
19422f375ab9SYan 
194390f8d62eSJan Schmidt 		tree_mod_log_set_root_pointer(root, child, 1);
1944240f62c8SChris Mason 		rcu_assign_pointer(root->node, child);
1945925baeddSChris Mason 
19460b86a832SChris Mason 		add_root_to_dirty_list(root);
1947925baeddSChris Mason 		btrfs_tree_unlock(child);
1948b4ce94deSChris Mason 
1949925baeddSChris Mason 		path->locks[level] = 0;
1950bb803951SChris Mason 		path->nodes[level] = NULL;
19515f39d397SChris Mason 		clean_tree_block(trans, root, mid);
1952925baeddSChris Mason 		btrfs_tree_unlock(mid);
1953bb803951SChris Mason 		/* once for the path */
19545f39d397SChris Mason 		free_extent_buffer(mid);
1955f0486c68SYan, Zheng 
1956f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
19575581a51aSJan Schmidt 		btrfs_free_tree_block(trans, root, mid, 0, 1);
1958bb803951SChris Mason 		/* once for the root ptr */
19593083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
1960f0486c68SYan, Zheng 		return 0;
1961bb803951SChris Mason 	}
19625f39d397SChris Mason 	if (btrfs_header_nritems(mid) >
1963123abc88SChris Mason 	    BTRFS_NODEPTRS_PER_BLOCK(root) / 4)
1964bb803951SChris Mason 		return 0;
1965bb803951SChris Mason 
19665f39d397SChris Mason 	left = read_node_slot(root, parent, pslot - 1);
19675f39d397SChris Mason 	if (left) {
1968925baeddSChris Mason 		btrfs_tree_lock(left);
1969b4ce94deSChris Mason 		btrfs_set_lock_blocking(left);
19705f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, left,
19719fa8cfe7SChris Mason 				       parent, pslot - 1, &left);
197254aa1f4dSChris Mason 		if (wret) {
197354aa1f4dSChris Mason 			ret = wret;
197454aa1f4dSChris Mason 			goto enospc;
197554aa1f4dSChris Mason 		}
19762cc58cf2SChris Mason 	}
19775f39d397SChris Mason 	right = read_node_slot(root, parent, pslot + 1);
19785f39d397SChris Mason 	if (right) {
1979925baeddSChris Mason 		btrfs_tree_lock(right);
1980b4ce94deSChris Mason 		btrfs_set_lock_blocking(right);
19815f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, right,
19829fa8cfe7SChris Mason 				       parent, pslot + 1, &right);
19832cc58cf2SChris Mason 		if (wret) {
19842cc58cf2SChris Mason 			ret = wret;
19852cc58cf2SChris Mason 			goto enospc;
19862cc58cf2SChris Mason 		}
19872cc58cf2SChris Mason 	}
19882cc58cf2SChris Mason 
19892cc58cf2SChris Mason 	/* first, try to make some room in the middle buffer */
19905f39d397SChris Mason 	if (left) {
19915f39d397SChris Mason 		orig_slot += btrfs_header_nritems(left);
1992bce4eae9SChris Mason 		wret = push_node_left(trans, root, left, mid, 1);
199379f95c82SChris Mason 		if (wret < 0)
199479f95c82SChris Mason 			ret = wret;
1995bb803951SChris Mason 	}
199679f95c82SChris Mason 
199779f95c82SChris Mason 	/*
199879f95c82SChris Mason 	 * then try to empty the right most buffer into the middle
199979f95c82SChris Mason 	 */
20005f39d397SChris Mason 	if (right) {
2001971a1f66SChris Mason 		wret = push_node_left(trans, root, mid, right, 1);
200254aa1f4dSChris Mason 		if (wret < 0 && wret != -ENOSPC)
200379f95c82SChris Mason 			ret = wret;
20045f39d397SChris Mason 		if (btrfs_header_nritems(right) == 0) {
20055f39d397SChris Mason 			clean_tree_block(trans, root, right);
2006925baeddSChris Mason 			btrfs_tree_unlock(right);
2007afe5fea7STsutomu Itoh 			del_ptr(root, path, level + 1, pslot + 1);
2008f0486c68SYan, Zheng 			root_sub_used(root, right->len);
20095581a51aSJan Schmidt 			btrfs_free_tree_block(trans, root, right, 0, 1);
20103083ee2eSJosef Bacik 			free_extent_buffer_stale(right);
2011f0486c68SYan, Zheng 			right = NULL;
2012bb803951SChris Mason 		} else {
20135f39d397SChris Mason 			struct btrfs_disk_key right_key;
20145f39d397SChris Mason 			btrfs_node_key(right, &right_key, 0);
2015f230475eSJan Schmidt 			tree_mod_log_set_node_key(root->fs_info, parent,
201632adf090SLiu Bo 						  pslot + 1, 0);
20175f39d397SChris Mason 			btrfs_set_node_key(parent, &right_key, pslot + 1);
20185f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
2019bb803951SChris Mason 		}
2020bb803951SChris Mason 	}
20215f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 1) {
202279f95c82SChris Mason 		/*
202379f95c82SChris Mason 		 * we're not allowed to leave a node with one item in the
202479f95c82SChris Mason 		 * tree during a delete.  A deletion from lower in the tree
202579f95c82SChris Mason 		 * could try to delete the only pointer in this node.
202679f95c82SChris Mason 		 * So, pull some keys from the left.
202779f95c82SChris Mason 		 * There has to be a left pointer at this point because
202879f95c82SChris Mason 		 * otherwise we would have pulled some pointers from the
202979f95c82SChris Mason 		 * right
203079f95c82SChris Mason 		 */
2031305a26afSMark Fasheh 		if (!left) {
2032305a26afSMark Fasheh 			ret = -EROFS;
2033305a26afSMark Fasheh 			btrfs_std_error(root->fs_info, ret);
2034305a26afSMark Fasheh 			goto enospc;
2035305a26afSMark Fasheh 		}
20365f39d397SChris Mason 		wret = balance_node_right(trans, root, mid, left);
203754aa1f4dSChris Mason 		if (wret < 0) {
203879f95c82SChris Mason 			ret = wret;
203954aa1f4dSChris Mason 			goto enospc;
204054aa1f4dSChris Mason 		}
2041bce4eae9SChris Mason 		if (wret == 1) {
2042bce4eae9SChris Mason 			wret = push_node_left(trans, root, left, mid, 1);
2043bce4eae9SChris Mason 			if (wret < 0)
2044bce4eae9SChris Mason 				ret = wret;
2045bce4eae9SChris Mason 		}
204679f95c82SChris Mason 		BUG_ON(wret == 1);
204779f95c82SChris Mason 	}
20485f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 0) {
20495f39d397SChris Mason 		clean_tree_block(trans, root, mid);
2050925baeddSChris Mason 		btrfs_tree_unlock(mid);
2051afe5fea7STsutomu Itoh 		del_ptr(root, path, level + 1, pslot);
2052f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
20535581a51aSJan Schmidt 		btrfs_free_tree_block(trans, root, mid, 0, 1);
20543083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
2055f0486c68SYan, Zheng 		mid = NULL;
205679f95c82SChris Mason 	} else {
205779f95c82SChris Mason 		/* update the parent key to reflect our changes */
20585f39d397SChris Mason 		struct btrfs_disk_key mid_key;
20595f39d397SChris Mason 		btrfs_node_key(mid, &mid_key, 0);
206032adf090SLiu Bo 		tree_mod_log_set_node_key(root->fs_info, parent,
2061f230475eSJan Schmidt 					  pslot, 0);
20625f39d397SChris Mason 		btrfs_set_node_key(parent, &mid_key, pslot);
20635f39d397SChris Mason 		btrfs_mark_buffer_dirty(parent);
206479f95c82SChris Mason 	}
2065bb803951SChris Mason 
206679f95c82SChris Mason 	/* update the path */
20675f39d397SChris Mason 	if (left) {
20685f39d397SChris Mason 		if (btrfs_header_nritems(left) > orig_slot) {
20695f39d397SChris Mason 			extent_buffer_get(left);
2070925baeddSChris Mason 			/* left was locked after cow */
20715f39d397SChris Mason 			path->nodes[level] = left;
2072bb803951SChris Mason 			path->slots[level + 1] -= 1;
2073bb803951SChris Mason 			path->slots[level] = orig_slot;
2074925baeddSChris Mason 			if (mid) {
2075925baeddSChris Mason 				btrfs_tree_unlock(mid);
20765f39d397SChris Mason 				free_extent_buffer(mid);
2077925baeddSChris Mason 			}
2078bb803951SChris Mason 		} else {
20795f39d397SChris Mason 			orig_slot -= btrfs_header_nritems(left);
2080bb803951SChris Mason 			path->slots[level] = orig_slot;
2081bb803951SChris Mason 		}
2082bb803951SChris Mason 	}
208379f95c82SChris Mason 	/* double check we haven't messed things up */
2084e20d96d6SChris Mason 	if (orig_ptr !=
20855f39d397SChris Mason 	    btrfs_node_blockptr(path->nodes[level], path->slots[level]))
208679f95c82SChris Mason 		BUG();
208754aa1f4dSChris Mason enospc:
2088925baeddSChris Mason 	if (right) {
2089925baeddSChris Mason 		btrfs_tree_unlock(right);
20905f39d397SChris Mason 		free_extent_buffer(right);
2091925baeddSChris Mason 	}
2092925baeddSChris Mason 	if (left) {
2093925baeddSChris Mason 		if (path->nodes[level] != left)
2094925baeddSChris Mason 			btrfs_tree_unlock(left);
20955f39d397SChris Mason 		free_extent_buffer(left);
2096925baeddSChris Mason 	}
2097bb803951SChris Mason 	return ret;
2098bb803951SChris Mason }
2099bb803951SChris Mason 
2100d352ac68SChris Mason /* Node balancing for insertion.  Here we only split or push nodes around
2101d352ac68SChris Mason  * when they are completely full.  This is also done top down, so we
2102d352ac68SChris Mason  * have to be pessimistic.
2103d352ac68SChris Mason  */
2104d397712bSChris Mason static noinline int push_nodes_for_insert(struct btrfs_trans_handle *trans,
2105e66f709bSChris Mason 					  struct btrfs_root *root,
2106e66f709bSChris Mason 					  struct btrfs_path *path, int level)
2107e66f709bSChris Mason {
21085f39d397SChris Mason 	struct extent_buffer *right = NULL;
21095f39d397SChris Mason 	struct extent_buffer *mid;
21105f39d397SChris Mason 	struct extent_buffer *left = NULL;
21115f39d397SChris Mason 	struct extent_buffer *parent = NULL;
2112e66f709bSChris Mason 	int ret = 0;
2113e66f709bSChris Mason 	int wret;
2114e66f709bSChris Mason 	int pslot;
2115e66f709bSChris Mason 	int orig_slot = path->slots[level];
2116e66f709bSChris Mason 
2117e66f709bSChris Mason 	if (level == 0)
2118e66f709bSChris Mason 		return 1;
2119e66f709bSChris Mason 
21205f39d397SChris Mason 	mid = path->nodes[level];
21217bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
2122e66f709bSChris Mason 
2123a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
21245f39d397SChris Mason 		parent = path->nodes[level + 1];
2125e66f709bSChris Mason 		pslot = path->slots[level + 1];
2126a05a9bb1SLi Zefan 	}
2127e66f709bSChris Mason 
21285f39d397SChris Mason 	if (!parent)
2129e66f709bSChris Mason 		return 1;
2130e66f709bSChris Mason 
21315f39d397SChris Mason 	left = read_node_slot(root, parent, pslot - 1);
2132e66f709bSChris Mason 
2133e66f709bSChris Mason 	/* first, try to make some room in the middle buffer */
21345f39d397SChris Mason 	if (left) {
2135e66f709bSChris Mason 		u32 left_nr;
2136925baeddSChris Mason 
2137925baeddSChris Mason 		btrfs_tree_lock(left);
2138b4ce94deSChris Mason 		btrfs_set_lock_blocking(left);
2139b4ce94deSChris Mason 
21405f39d397SChris Mason 		left_nr = btrfs_header_nritems(left);
214133ade1f8SChris Mason 		if (left_nr >= BTRFS_NODEPTRS_PER_BLOCK(root) - 1) {
214233ade1f8SChris Mason 			wret = 1;
214333ade1f8SChris Mason 		} else {
21445f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, left, parent,
21459fa8cfe7SChris Mason 					      pslot - 1, &left);
214654aa1f4dSChris Mason 			if (ret)
214754aa1f4dSChris Mason 				wret = 1;
214854aa1f4dSChris Mason 			else {
214954aa1f4dSChris Mason 				wret = push_node_left(trans, root,
2150971a1f66SChris Mason 						      left, mid, 0);
215154aa1f4dSChris Mason 			}
215233ade1f8SChris Mason 		}
2153e66f709bSChris Mason 		if (wret < 0)
2154e66f709bSChris Mason 			ret = wret;
2155e66f709bSChris Mason 		if (wret == 0) {
21565f39d397SChris Mason 			struct btrfs_disk_key disk_key;
2157e66f709bSChris Mason 			orig_slot += left_nr;
21585f39d397SChris Mason 			btrfs_node_key(mid, &disk_key, 0);
2159f230475eSJan Schmidt 			tree_mod_log_set_node_key(root->fs_info, parent,
216032adf090SLiu Bo 						  pslot, 0);
21615f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot);
21625f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
21635f39d397SChris Mason 			if (btrfs_header_nritems(left) > orig_slot) {
21645f39d397SChris Mason 				path->nodes[level] = left;
2165e66f709bSChris Mason 				path->slots[level + 1] -= 1;
2166e66f709bSChris Mason 				path->slots[level] = orig_slot;
2167925baeddSChris Mason 				btrfs_tree_unlock(mid);
21685f39d397SChris Mason 				free_extent_buffer(mid);
2169e66f709bSChris Mason 			} else {
2170e66f709bSChris Mason 				orig_slot -=
21715f39d397SChris Mason 					btrfs_header_nritems(left);
2172e66f709bSChris Mason 				path->slots[level] = orig_slot;
2173925baeddSChris Mason 				btrfs_tree_unlock(left);
21745f39d397SChris Mason 				free_extent_buffer(left);
2175e66f709bSChris Mason 			}
2176e66f709bSChris Mason 			return 0;
2177e66f709bSChris Mason 		}
2178925baeddSChris Mason 		btrfs_tree_unlock(left);
21795f39d397SChris Mason 		free_extent_buffer(left);
2180e66f709bSChris Mason 	}
21815f39d397SChris Mason 	right = read_node_slot(root, parent, pslot + 1);
2182e66f709bSChris Mason 
2183e66f709bSChris Mason 	/*
2184e66f709bSChris Mason 	 * then try to empty the right most buffer into the middle
2185e66f709bSChris Mason 	 */
21865f39d397SChris Mason 	if (right) {
218733ade1f8SChris Mason 		u32 right_nr;
2188b4ce94deSChris Mason 
2189925baeddSChris Mason 		btrfs_tree_lock(right);
2190b4ce94deSChris Mason 		btrfs_set_lock_blocking(right);
2191b4ce94deSChris Mason 
21925f39d397SChris Mason 		right_nr = btrfs_header_nritems(right);
219333ade1f8SChris Mason 		if (right_nr >= BTRFS_NODEPTRS_PER_BLOCK(root) - 1) {
219433ade1f8SChris Mason 			wret = 1;
219533ade1f8SChris Mason 		} else {
21965f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, right,
21975f39d397SChris Mason 					      parent, pslot + 1,
21989fa8cfe7SChris Mason 					      &right);
219954aa1f4dSChris Mason 			if (ret)
220054aa1f4dSChris Mason 				wret = 1;
220154aa1f4dSChris Mason 			else {
220233ade1f8SChris Mason 				wret = balance_node_right(trans, root,
22035f39d397SChris Mason 							  right, mid);
220433ade1f8SChris Mason 			}
220554aa1f4dSChris Mason 		}
2206e66f709bSChris Mason 		if (wret < 0)
2207e66f709bSChris Mason 			ret = wret;
2208e66f709bSChris Mason 		if (wret == 0) {
22095f39d397SChris Mason 			struct btrfs_disk_key disk_key;
22105f39d397SChris Mason 
22115f39d397SChris Mason 			btrfs_node_key(right, &disk_key, 0);
2212f230475eSJan Schmidt 			tree_mod_log_set_node_key(root->fs_info, parent,
221332adf090SLiu Bo 						  pslot + 1, 0);
22145f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot + 1);
22155f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
22165f39d397SChris Mason 
22175f39d397SChris Mason 			if (btrfs_header_nritems(mid) <= orig_slot) {
22185f39d397SChris Mason 				path->nodes[level] = right;
2219e66f709bSChris Mason 				path->slots[level + 1] += 1;
2220e66f709bSChris Mason 				path->slots[level] = orig_slot -
22215f39d397SChris Mason 					btrfs_header_nritems(mid);
2222925baeddSChris Mason 				btrfs_tree_unlock(mid);
22235f39d397SChris Mason 				free_extent_buffer(mid);
2224e66f709bSChris Mason 			} else {
2225925baeddSChris Mason 				btrfs_tree_unlock(right);
22265f39d397SChris Mason 				free_extent_buffer(right);
2227e66f709bSChris Mason 			}
2228e66f709bSChris Mason 			return 0;
2229e66f709bSChris Mason 		}
2230925baeddSChris Mason 		btrfs_tree_unlock(right);
22315f39d397SChris Mason 		free_extent_buffer(right);
2232e66f709bSChris Mason 	}
2233e66f709bSChris Mason 	return 1;
2234e66f709bSChris Mason }
2235e66f709bSChris Mason 
223674123bd7SChris Mason /*
2237d352ac68SChris Mason  * readahead one full node of leaves, finding things that are close
2238d352ac68SChris Mason  * to the block in 'slot', and triggering ra on them.
22393c69faecSChris Mason  */
2240c8c42864SChris Mason static void reada_for_search(struct btrfs_root *root,
2241e02119d5SChris Mason 			     struct btrfs_path *path,
224201f46658SChris Mason 			     int level, int slot, u64 objectid)
22433c69faecSChris Mason {
22445f39d397SChris Mason 	struct extent_buffer *node;
224501f46658SChris Mason 	struct btrfs_disk_key disk_key;
22463c69faecSChris Mason 	u32 nritems;
22473c69faecSChris Mason 	u64 search;
2248a7175319SChris Mason 	u64 target;
22496b80053dSChris Mason 	u64 nread = 0;
2250cb25c2eaSJosef Bacik 	u64 gen;
22513c69faecSChris Mason 	int direction = path->reada;
22525f39d397SChris Mason 	struct extent_buffer *eb;
22536b80053dSChris Mason 	u32 nr;
22546b80053dSChris Mason 	u32 blocksize;
22556b80053dSChris Mason 	u32 nscan = 0;
2256db94535dSChris Mason 
2257a6b6e75eSChris Mason 	if (level != 1)
22583c69faecSChris Mason 		return;
22593c69faecSChris Mason 
22606702ed49SChris Mason 	if (!path->nodes[level])
22616702ed49SChris Mason 		return;
22626702ed49SChris Mason 
22635f39d397SChris Mason 	node = path->nodes[level];
2264925baeddSChris Mason 
22653c69faecSChris Mason 	search = btrfs_node_blockptr(node, slot);
2266707e8a07SDavid Sterba 	blocksize = root->nodesize;
22676b80053dSChris Mason 	eb = btrfs_find_tree_block(root, search, blocksize);
22685f39d397SChris Mason 	if (eb) {
22695f39d397SChris Mason 		free_extent_buffer(eb);
22703c69faecSChris Mason 		return;
22713c69faecSChris Mason 	}
22723c69faecSChris Mason 
2273a7175319SChris Mason 	target = search;
22746b80053dSChris Mason 
22755f39d397SChris Mason 	nritems = btrfs_header_nritems(node);
22766b80053dSChris Mason 	nr = slot;
227725b8b936SJosef Bacik 
22783c69faecSChris Mason 	while (1) {
22796b80053dSChris Mason 		if (direction < 0) {
22806b80053dSChris Mason 			if (nr == 0)
22813c69faecSChris Mason 				break;
22826b80053dSChris Mason 			nr--;
22836b80053dSChris Mason 		} else if (direction > 0) {
22846b80053dSChris Mason 			nr++;
22856b80053dSChris Mason 			if (nr >= nritems)
22866b80053dSChris Mason 				break;
22873c69faecSChris Mason 		}
228801f46658SChris Mason 		if (path->reada < 0 && objectid) {
228901f46658SChris Mason 			btrfs_node_key(node, &disk_key, nr);
229001f46658SChris Mason 			if (btrfs_disk_key_objectid(&disk_key) != objectid)
229101f46658SChris Mason 				break;
229201f46658SChris Mason 		}
22936b80053dSChris Mason 		search = btrfs_node_blockptr(node, nr);
2294a7175319SChris Mason 		if ((search <= target && target - search <= 65536) ||
2295a7175319SChris Mason 		    (search > target && search - target <= 65536)) {
2296cb25c2eaSJosef Bacik 			gen = btrfs_node_ptr_generation(node, nr);
229758dc4ce4SDavid Sterba 			readahead_tree_block(root, search, blocksize);
22986b80053dSChris Mason 			nread += blocksize;
22993c69faecSChris Mason 		}
23006b80053dSChris Mason 		nscan++;
2301a7175319SChris Mason 		if ((nread > 65536 || nscan > 32))
23026b80053dSChris Mason 			break;
23033c69faecSChris Mason 	}
23043c69faecSChris Mason }
2305925baeddSChris Mason 
23060b08851fSJosef Bacik static noinline void reada_for_balance(struct btrfs_root *root,
2307b4ce94deSChris Mason 				       struct btrfs_path *path, int level)
2308b4ce94deSChris Mason {
2309b4ce94deSChris Mason 	int slot;
2310b4ce94deSChris Mason 	int nritems;
2311b4ce94deSChris Mason 	struct extent_buffer *parent;
2312b4ce94deSChris Mason 	struct extent_buffer *eb;
2313b4ce94deSChris Mason 	u64 gen;
2314b4ce94deSChris Mason 	u64 block1 = 0;
2315b4ce94deSChris Mason 	u64 block2 = 0;
2316b4ce94deSChris Mason 	int blocksize;
2317b4ce94deSChris Mason 
23188c594ea8SChris Mason 	parent = path->nodes[level + 1];
2319b4ce94deSChris Mason 	if (!parent)
23200b08851fSJosef Bacik 		return;
2321b4ce94deSChris Mason 
2322b4ce94deSChris Mason 	nritems = btrfs_header_nritems(parent);
23238c594ea8SChris Mason 	slot = path->slots[level + 1];
2324707e8a07SDavid Sterba 	blocksize = root->nodesize;
2325b4ce94deSChris Mason 
2326b4ce94deSChris Mason 	if (slot > 0) {
2327b4ce94deSChris Mason 		block1 = btrfs_node_blockptr(parent, slot - 1);
2328b4ce94deSChris Mason 		gen = btrfs_node_ptr_generation(parent, slot - 1);
2329b4ce94deSChris Mason 		eb = btrfs_find_tree_block(root, block1, blocksize);
2330b9fab919SChris Mason 		/*
2331b9fab919SChris Mason 		 * if we get -eagain from btrfs_buffer_uptodate, we
2332b9fab919SChris Mason 		 * don't want to return eagain here.  That will loop
2333b9fab919SChris Mason 		 * forever
2334b9fab919SChris Mason 		 */
2335b9fab919SChris Mason 		if (eb && btrfs_buffer_uptodate(eb, gen, 1) != 0)
2336b4ce94deSChris Mason 			block1 = 0;
2337b4ce94deSChris Mason 		free_extent_buffer(eb);
2338b4ce94deSChris Mason 	}
23398c594ea8SChris Mason 	if (slot + 1 < nritems) {
2340b4ce94deSChris Mason 		block2 = btrfs_node_blockptr(parent, slot + 1);
2341b4ce94deSChris Mason 		gen = btrfs_node_ptr_generation(parent, slot + 1);
2342b4ce94deSChris Mason 		eb = btrfs_find_tree_block(root, block2, blocksize);
2343b9fab919SChris Mason 		if (eb && btrfs_buffer_uptodate(eb, gen, 1) != 0)
2344b4ce94deSChris Mason 			block2 = 0;
2345b4ce94deSChris Mason 		free_extent_buffer(eb);
2346b4ce94deSChris Mason 	}
23478c594ea8SChris Mason 
2348b4ce94deSChris Mason 	if (block1)
234958dc4ce4SDavid Sterba 		readahead_tree_block(root, block1, blocksize);
2350b4ce94deSChris Mason 	if (block2)
235158dc4ce4SDavid Sterba 		readahead_tree_block(root, block2, blocksize);
2352b4ce94deSChris Mason }
2353b4ce94deSChris Mason 
2354b4ce94deSChris Mason 
2355b4ce94deSChris Mason /*
2356d397712bSChris Mason  * when we walk down the tree, it is usually safe to unlock the higher layers
2357d397712bSChris Mason  * in the tree.  The exceptions are when our path goes through slot 0, because
2358d397712bSChris Mason  * operations on the tree might require changing key pointers higher up in the
2359d397712bSChris Mason  * tree.
2360d352ac68SChris Mason  *
2361d397712bSChris Mason  * callers might also have set path->keep_locks, which tells this code to keep
2362d397712bSChris Mason  * the lock if the path points to the last slot in the block.  This is part of
2363d397712bSChris Mason  * walking through the tree, and selecting the next slot in the higher block.
2364d352ac68SChris Mason  *
2365d397712bSChris Mason  * lowest_unlock sets the lowest level in the tree we're allowed to unlock.  so
2366d397712bSChris Mason  * if lowest_unlock is 1, level 0 won't be unlocked
2367d352ac68SChris Mason  */
2368e02119d5SChris Mason static noinline void unlock_up(struct btrfs_path *path, int level,
2369f7c79f30SChris Mason 			       int lowest_unlock, int min_write_lock_level,
2370f7c79f30SChris Mason 			       int *write_lock_level)
2371925baeddSChris Mason {
2372925baeddSChris Mason 	int i;
2373925baeddSChris Mason 	int skip_level = level;
2374051e1b9fSChris Mason 	int no_skips = 0;
2375925baeddSChris Mason 	struct extent_buffer *t;
2376925baeddSChris Mason 
2377925baeddSChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2378925baeddSChris Mason 		if (!path->nodes[i])
2379925baeddSChris Mason 			break;
2380925baeddSChris Mason 		if (!path->locks[i])
2381925baeddSChris Mason 			break;
2382051e1b9fSChris Mason 		if (!no_skips && path->slots[i] == 0) {
2383925baeddSChris Mason 			skip_level = i + 1;
2384925baeddSChris Mason 			continue;
2385925baeddSChris Mason 		}
2386051e1b9fSChris Mason 		if (!no_skips && path->keep_locks) {
2387925baeddSChris Mason 			u32 nritems;
2388925baeddSChris Mason 			t = path->nodes[i];
2389925baeddSChris Mason 			nritems = btrfs_header_nritems(t);
2390051e1b9fSChris Mason 			if (nritems < 1 || path->slots[i] >= nritems - 1) {
2391925baeddSChris Mason 				skip_level = i + 1;
2392925baeddSChris Mason 				continue;
2393925baeddSChris Mason 			}
2394925baeddSChris Mason 		}
2395051e1b9fSChris Mason 		if (skip_level < i && i >= lowest_unlock)
2396051e1b9fSChris Mason 			no_skips = 1;
2397051e1b9fSChris Mason 
2398925baeddSChris Mason 		t = path->nodes[i];
2399925baeddSChris Mason 		if (i >= lowest_unlock && i > skip_level && path->locks[i]) {
2400bd681513SChris Mason 			btrfs_tree_unlock_rw(t, path->locks[i]);
2401925baeddSChris Mason 			path->locks[i] = 0;
2402f7c79f30SChris Mason 			if (write_lock_level &&
2403f7c79f30SChris Mason 			    i > min_write_lock_level &&
2404f7c79f30SChris Mason 			    i <= *write_lock_level) {
2405f7c79f30SChris Mason 				*write_lock_level = i - 1;
2406f7c79f30SChris Mason 			}
2407925baeddSChris Mason 		}
2408925baeddSChris Mason 	}
2409925baeddSChris Mason }
2410925baeddSChris Mason 
24113c69faecSChris Mason /*
2412b4ce94deSChris Mason  * This releases any locks held in the path starting at level and
2413b4ce94deSChris Mason  * going all the way up to the root.
2414b4ce94deSChris Mason  *
2415b4ce94deSChris Mason  * btrfs_search_slot will keep the lock held on higher nodes in a few
2416b4ce94deSChris Mason  * corner cases, such as COW of the block at slot zero in the node.  This
2417b4ce94deSChris Mason  * ignores those rules, and it should only be called when there are no
2418b4ce94deSChris Mason  * more updates to be done higher up in the tree.
2419b4ce94deSChris Mason  */
2420b4ce94deSChris Mason noinline void btrfs_unlock_up_safe(struct btrfs_path *path, int level)
2421b4ce94deSChris Mason {
2422b4ce94deSChris Mason 	int i;
2423b4ce94deSChris Mason 
242409a2a8f9SJosef Bacik 	if (path->keep_locks)
2425b4ce94deSChris Mason 		return;
2426b4ce94deSChris Mason 
2427b4ce94deSChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2428b4ce94deSChris Mason 		if (!path->nodes[i])
242912f4daccSChris Mason 			continue;
2430b4ce94deSChris Mason 		if (!path->locks[i])
243112f4daccSChris Mason 			continue;
2432bd681513SChris Mason 		btrfs_tree_unlock_rw(path->nodes[i], path->locks[i]);
2433b4ce94deSChris Mason 		path->locks[i] = 0;
2434b4ce94deSChris Mason 	}
2435b4ce94deSChris Mason }
2436b4ce94deSChris Mason 
2437b4ce94deSChris Mason /*
2438c8c42864SChris Mason  * helper function for btrfs_search_slot.  The goal is to find a block
2439c8c42864SChris Mason  * in cache without setting the path to blocking.  If we find the block
2440c8c42864SChris Mason  * we return zero and the path is unchanged.
2441c8c42864SChris Mason  *
2442c8c42864SChris Mason  * If we can't find the block, we set the path blocking and do some
2443c8c42864SChris Mason  * reada.  -EAGAIN is returned and the search must be repeated.
2444c8c42864SChris Mason  */
2445c8c42864SChris Mason static int
2446c8c42864SChris Mason read_block_for_search(struct btrfs_trans_handle *trans,
2447c8c42864SChris Mason 		       struct btrfs_root *root, struct btrfs_path *p,
2448c8c42864SChris Mason 		       struct extent_buffer **eb_ret, int level, int slot,
24495d9e75c4SJan Schmidt 		       struct btrfs_key *key, u64 time_seq)
2450c8c42864SChris Mason {
2451c8c42864SChris Mason 	u64 blocknr;
2452c8c42864SChris Mason 	u64 gen;
2453c8c42864SChris Mason 	u32 blocksize;
2454c8c42864SChris Mason 	struct extent_buffer *b = *eb_ret;
2455c8c42864SChris Mason 	struct extent_buffer *tmp;
245676a05b35SChris Mason 	int ret;
2457c8c42864SChris Mason 
2458c8c42864SChris Mason 	blocknr = btrfs_node_blockptr(b, slot);
2459c8c42864SChris Mason 	gen = btrfs_node_ptr_generation(b, slot);
2460707e8a07SDavid Sterba 	blocksize = root->nodesize;
2461c8c42864SChris Mason 
2462c8c42864SChris Mason 	tmp = btrfs_find_tree_block(root, blocknr, blocksize);
2463cb44921aSChris Mason 	if (tmp) {
2464b9fab919SChris Mason 		/* first we do an atomic uptodate check */
2465b9fab919SChris Mason 		if (btrfs_buffer_uptodate(tmp, gen, 1) > 0) {
2466c8c42864SChris Mason 			*eb_ret = tmp;
2467c8c42864SChris Mason 			return 0;
2468c8c42864SChris Mason 		}
2469bdf7c00eSJosef Bacik 
2470cb44921aSChris Mason 		/* the pages were up to date, but we failed
2471cb44921aSChris Mason 		 * the generation number check.  Do a full
2472cb44921aSChris Mason 		 * read for the generation number that is correct.
2473cb44921aSChris Mason 		 * We must do this without dropping locks so
2474cb44921aSChris Mason 		 * we can trust our generation number
2475cb44921aSChris Mason 		 */
2476bd681513SChris Mason 		btrfs_set_path_blocking(p);
2477bd681513SChris Mason 
2478b9fab919SChris Mason 		/* now we're allowed to do a blocking uptodate check */
2479bdf7c00eSJosef Bacik 		ret = btrfs_read_buffer(tmp, gen);
2480bdf7c00eSJosef Bacik 		if (!ret) {
2481cb44921aSChris Mason 			*eb_ret = tmp;
2482cb44921aSChris Mason 			return 0;
2483cb44921aSChris Mason 		}
2484cb44921aSChris Mason 		free_extent_buffer(tmp);
2485b3b4aa74SDavid Sterba 		btrfs_release_path(p);
2486cb44921aSChris Mason 		return -EIO;
2487cb44921aSChris Mason 	}
2488c8c42864SChris Mason 
2489c8c42864SChris Mason 	/*
2490c8c42864SChris Mason 	 * reduce lock contention at high levels
2491c8c42864SChris Mason 	 * of the btree by dropping locks before
249276a05b35SChris Mason 	 * we read.  Don't release the lock on the current
249376a05b35SChris Mason 	 * level because we need to walk this node to figure
249476a05b35SChris Mason 	 * out which blocks to read.
2495c8c42864SChris Mason 	 */
24968c594ea8SChris Mason 	btrfs_unlock_up_safe(p, level + 1);
24978c594ea8SChris Mason 	btrfs_set_path_blocking(p);
24988c594ea8SChris Mason 
2499c8c42864SChris Mason 	free_extent_buffer(tmp);
2500c8c42864SChris Mason 	if (p->reada)
2501c8c42864SChris Mason 		reada_for_search(root, p, level, slot, key->objectid);
2502c8c42864SChris Mason 
2503b3b4aa74SDavid Sterba 	btrfs_release_path(p);
250476a05b35SChris Mason 
250576a05b35SChris Mason 	ret = -EAGAIN;
2506*ce86cd59SDavid Sterba 	tmp = read_tree_block(root, blocknr, 0);
250776a05b35SChris Mason 	if (tmp) {
250876a05b35SChris Mason 		/*
250976a05b35SChris Mason 		 * If the read above didn't mark this buffer up to date,
251076a05b35SChris Mason 		 * it will never end up being up to date.  Set ret to EIO now
251176a05b35SChris Mason 		 * and give up so that our caller doesn't loop forever
251276a05b35SChris Mason 		 * on our EAGAINs.
251376a05b35SChris Mason 		 */
2514b9fab919SChris Mason 		if (!btrfs_buffer_uptodate(tmp, 0, 0))
251576a05b35SChris Mason 			ret = -EIO;
2516c8c42864SChris Mason 		free_extent_buffer(tmp);
251776a05b35SChris Mason 	}
251876a05b35SChris Mason 	return ret;
2519c8c42864SChris Mason }
2520c8c42864SChris Mason 
2521c8c42864SChris Mason /*
2522c8c42864SChris Mason  * helper function for btrfs_search_slot.  This does all of the checks
2523c8c42864SChris Mason  * for node-level blocks and does any balancing required based on
2524c8c42864SChris Mason  * the ins_len.
2525c8c42864SChris Mason  *
2526c8c42864SChris Mason  * If no extra work was required, zero is returned.  If we had to
2527c8c42864SChris Mason  * drop the path, -EAGAIN is returned and btrfs_search_slot must
2528c8c42864SChris Mason  * start over
2529c8c42864SChris Mason  */
2530c8c42864SChris Mason static int
2531c8c42864SChris Mason setup_nodes_for_search(struct btrfs_trans_handle *trans,
2532c8c42864SChris Mason 		       struct btrfs_root *root, struct btrfs_path *p,
2533bd681513SChris Mason 		       struct extent_buffer *b, int level, int ins_len,
2534bd681513SChris Mason 		       int *write_lock_level)
2535c8c42864SChris Mason {
2536c8c42864SChris Mason 	int ret;
2537c8c42864SChris Mason 	if ((p->search_for_split || ins_len > 0) && btrfs_header_nritems(b) >=
2538c8c42864SChris Mason 	    BTRFS_NODEPTRS_PER_BLOCK(root) - 3) {
2539c8c42864SChris Mason 		int sret;
2540c8c42864SChris Mason 
2541bd681513SChris Mason 		if (*write_lock_level < level + 1) {
2542bd681513SChris Mason 			*write_lock_level = level + 1;
2543bd681513SChris Mason 			btrfs_release_path(p);
2544bd681513SChris Mason 			goto again;
2545bd681513SChris Mason 		}
2546bd681513SChris Mason 
2547c8c42864SChris Mason 		btrfs_set_path_blocking(p);
25480b08851fSJosef Bacik 		reada_for_balance(root, p, level);
2549c8c42864SChris Mason 		sret = split_node(trans, root, p, level);
2550bd681513SChris Mason 		btrfs_clear_path_blocking(p, NULL, 0);
2551c8c42864SChris Mason 
2552c8c42864SChris Mason 		BUG_ON(sret > 0);
2553c8c42864SChris Mason 		if (sret) {
2554c8c42864SChris Mason 			ret = sret;
2555c8c42864SChris Mason 			goto done;
2556c8c42864SChris Mason 		}
2557c8c42864SChris Mason 		b = p->nodes[level];
2558c8c42864SChris Mason 	} else if (ins_len < 0 && btrfs_header_nritems(b) <
2559cfbb9308SChris Mason 		   BTRFS_NODEPTRS_PER_BLOCK(root) / 2) {
2560c8c42864SChris Mason 		int sret;
2561c8c42864SChris Mason 
2562bd681513SChris Mason 		if (*write_lock_level < level + 1) {
2563bd681513SChris Mason 			*write_lock_level = level + 1;
2564bd681513SChris Mason 			btrfs_release_path(p);
2565bd681513SChris Mason 			goto again;
2566bd681513SChris Mason 		}
2567bd681513SChris Mason 
2568c8c42864SChris Mason 		btrfs_set_path_blocking(p);
25690b08851fSJosef Bacik 		reada_for_balance(root, p, level);
2570c8c42864SChris Mason 		sret = balance_level(trans, root, p, level);
2571bd681513SChris Mason 		btrfs_clear_path_blocking(p, NULL, 0);
2572c8c42864SChris Mason 
2573c8c42864SChris Mason 		if (sret) {
2574c8c42864SChris Mason 			ret = sret;
2575c8c42864SChris Mason 			goto done;
2576c8c42864SChris Mason 		}
2577c8c42864SChris Mason 		b = p->nodes[level];
2578c8c42864SChris Mason 		if (!b) {
2579b3b4aa74SDavid Sterba 			btrfs_release_path(p);
2580c8c42864SChris Mason 			goto again;
2581c8c42864SChris Mason 		}
2582c8c42864SChris Mason 		BUG_ON(btrfs_header_nritems(b) == 1);
2583c8c42864SChris Mason 	}
2584c8c42864SChris Mason 	return 0;
2585c8c42864SChris Mason 
2586c8c42864SChris Mason again:
2587c8c42864SChris Mason 	ret = -EAGAIN;
2588c8c42864SChris Mason done:
2589c8c42864SChris Mason 	return ret;
2590c8c42864SChris Mason }
2591c8c42864SChris Mason 
2592d7396f07SFilipe David Borba Manana static void key_search_validate(struct extent_buffer *b,
2593d7396f07SFilipe David Borba Manana 				struct btrfs_key *key,
2594d7396f07SFilipe David Borba Manana 				int level)
2595d7396f07SFilipe David Borba Manana {
2596d7396f07SFilipe David Borba Manana #ifdef CONFIG_BTRFS_ASSERT
2597d7396f07SFilipe David Borba Manana 	struct btrfs_disk_key disk_key;
2598d7396f07SFilipe David Borba Manana 
2599d7396f07SFilipe David Borba Manana 	btrfs_cpu_key_to_disk(&disk_key, key);
2600d7396f07SFilipe David Borba Manana 
2601d7396f07SFilipe David Borba Manana 	if (level == 0)
2602d7396f07SFilipe David Borba Manana 		ASSERT(!memcmp_extent_buffer(b, &disk_key,
2603d7396f07SFilipe David Borba Manana 		    offsetof(struct btrfs_leaf, items[0].key),
2604d7396f07SFilipe David Borba Manana 		    sizeof(disk_key)));
2605d7396f07SFilipe David Borba Manana 	else
2606d7396f07SFilipe David Borba Manana 		ASSERT(!memcmp_extent_buffer(b, &disk_key,
2607d7396f07SFilipe David Borba Manana 		    offsetof(struct btrfs_node, ptrs[0].key),
2608d7396f07SFilipe David Borba Manana 		    sizeof(disk_key)));
2609d7396f07SFilipe David Borba Manana #endif
2610d7396f07SFilipe David Borba Manana }
2611d7396f07SFilipe David Borba Manana 
2612d7396f07SFilipe David Borba Manana static int key_search(struct extent_buffer *b, struct btrfs_key *key,
2613d7396f07SFilipe David Borba Manana 		      int level, int *prev_cmp, int *slot)
2614d7396f07SFilipe David Borba Manana {
2615d7396f07SFilipe David Borba Manana 	if (*prev_cmp != 0) {
2616d7396f07SFilipe David Borba Manana 		*prev_cmp = bin_search(b, key, level, slot);
2617d7396f07SFilipe David Borba Manana 		return *prev_cmp;
2618d7396f07SFilipe David Borba Manana 	}
2619d7396f07SFilipe David Borba Manana 
2620d7396f07SFilipe David Borba Manana 	key_search_validate(b, key, level);
2621d7396f07SFilipe David Borba Manana 	*slot = 0;
2622d7396f07SFilipe David Borba Manana 
2623d7396f07SFilipe David Borba Manana 	return 0;
2624d7396f07SFilipe David Borba Manana }
2625d7396f07SFilipe David Borba Manana 
26263f870c28SKelley Nielsen int btrfs_find_item(struct btrfs_root *fs_root, struct btrfs_path *found_path,
2627e33d5c3dSKelley Nielsen 		u64 iobjectid, u64 ioff, u8 key_type,
2628e33d5c3dSKelley Nielsen 		struct btrfs_key *found_key)
2629e33d5c3dSKelley Nielsen {
2630e33d5c3dSKelley Nielsen 	int ret;
2631e33d5c3dSKelley Nielsen 	struct btrfs_key key;
2632e33d5c3dSKelley Nielsen 	struct extent_buffer *eb;
26333f870c28SKelley Nielsen 	struct btrfs_path *path;
2634e33d5c3dSKelley Nielsen 
2635e33d5c3dSKelley Nielsen 	key.type = key_type;
2636e33d5c3dSKelley Nielsen 	key.objectid = iobjectid;
2637e33d5c3dSKelley Nielsen 	key.offset = ioff;
2638e33d5c3dSKelley Nielsen 
26393f870c28SKelley Nielsen 	if (found_path == NULL) {
26403f870c28SKelley Nielsen 		path = btrfs_alloc_path();
26413f870c28SKelley Nielsen 		if (!path)
26423f870c28SKelley Nielsen 			return -ENOMEM;
26433f870c28SKelley Nielsen 	} else
26443f870c28SKelley Nielsen 		path = found_path;
26453f870c28SKelley Nielsen 
2646e33d5c3dSKelley Nielsen 	ret = btrfs_search_slot(NULL, fs_root, &key, path, 0, 0);
26473f870c28SKelley Nielsen 	if ((ret < 0) || (found_key == NULL)) {
26483f870c28SKelley Nielsen 		if (path != found_path)
26493f870c28SKelley Nielsen 			btrfs_free_path(path);
2650e33d5c3dSKelley Nielsen 		return ret;
26513f870c28SKelley Nielsen 	}
2652e33d5c3dSKelley Nielsen 
2653e33d5c3dSKelley Nielsen 	eb = path->nodes[0];
2654e33d5c3dSKelley Nielsen 	if (ret && path->slots[0] >= btrfs_header_nritems(eb)) {
2655e33d5c3dSKelley Nielsen 		ret = btrfs_next_leaf(fs_root, path);
2656e33d5c3dSKelley Nielsen 		if (ret)
2657e33d5c3dSKelley Nielsen 			return ret;
2658e33d5c3dSKelley Nielsen 		eb = path->nodes[0];
2659e33d5c3dSKelley Nielsen 	}
2660e33d5c3dSKelley Nielsen 
2661e33d5c3dSKelley Nielsen 	btrfs_item_key_to_cpu(eb, found_key, path->slots[0]);
2662e33d5c3dSKelley Nielsen 	if (found_key->type != key.type ||
2663e33d5c3dSKelley Nielsen 			found_key->objectid != key.objectid)
2664e33d5c3dSKelley Nielsen 		return 1;
2665e33d5c3dSKelley Nielsen 
2666e33d5c3dSKelley Nielsen 	return 0;
2667e33d5c3dSKelley Nielsen }
2668e33d5c3dSKelley Nielsen 
2669c8c42864SChris Mason /*
267074123bd7SChris Mason  * look for key in the tree.  path is filled in with nodes along the way
267174123bd7SChris Mason  * if key is found, we return zero and you can find the item in the leaf
267274123bd7SChris Mason  * level of the path (level 0)
267374123bd7SChris Mason  *
267474123bd7SChris Mason  * If the key isn't found, the path points to the slot where it should
2675aa5d6bedSChris Mason  * be inserted, and 1 is returned.  If there are other errors during the
2676aa5d6bedSChris Mason  * search a negative error number is returned.
267797571fd0SChris Mason  *
267897571fd0SChris Mason  * if ins_len > 0, nodes and leaves will be split as we walk down the
267997571fd0SChris Mason  * tree.  if ins_len < 0, nodes will be merged as we walk down the tree (if
268097571fd0SChris Mason  * possible)
268174123bd7SChris Mason  */
2682e089f05cSChris Mason int btrfs_search_slot(struct btrfs_trans_handle *trans, struct btrfs_root
2683e089f05cSChris Mason 		      *root, struct btrfs_key *key, struct btrfs_path *p, int
2684e089f05cSChris Mason 		      ins_len, int cow)
2685be0e5c09SChris Mason {
26865f39d397SChris Mason 	struct extent_buffer *b;
2687be0e5c09SChris Mason 	int slot;
2688be0e5c09SChris Mason 	int ret;
268933c66f43SYan Zheng 	int err;
2690be0e5c09SChris Mason 	int level;
2691925baeddSChris Mason 	int lowest_unlock = 1;
2692bd681513SChris Mason 	int root_lock;
2693bd681513SChris Mason 	/* everything at write_lock_level or lower must be write locked */
2694bd681513SChris Mason 	int write_lock_level = 0;
26959f3a7427SChris Mason 	u8 lowest_level = 0;
2696f7c79f30SChris Mason 	int min_write_lock_level;
2697d7396f07SFilipe David Borba Manana 	int prev_cmp;
26989f3a7427SChris Mason 
26996702ed49SChris Mason 	lowest_level = p->lowest_level;
2700323ac95bSChris Mason 	WARN_ON(lowest_level && ins_len > 0);
270122b0ebdaSChris Mason 	WARN_ON(p->nodes[0] != NULL);
2702eb653de1SFilipe David Borba Manana 	BUG_ON(!cow && ins_len);
270325179201SJosef Bacik 
2704bd681513SChris Mason 	if (ins_len < 0) {
2705925baeddSChris Mason 		lowest_unlock = 2;
270665b51a00SChris Mason 
2707bd681513SChris Mason 		/* when we are removing items, we might have to go up to level
2708bd681513SChris Mason 		 * two as we update tree pointers  Make sure we keep write
2709bd681513SChris Mason 		 * for those levels as well
2710bd681513SChris Mason 		 */
2711bd681513SChris Mason 		write_lock_level = 2;
2712bd681513SChris Mason 	} else if (ins_len > 0) {
2713bd681513SChris Mason 		/*
2714bd681513SChris Mason 		 * for inserting items, make sure we have a write lock on
2715bd681513SChris Mason 		 * level 1 so we can update keys
2716bd681513SChris Mason 		 */
2717bd681513SChris Mason 		write_lock_level = 1;
2718bd681513SChris Mason 	}
2719bd681513SChris Mason 
2720bd681513SChris Mason 	if (!cow)
2721bd681513SChris Mason 		write_lock_level = -1;
2722bd681513SChris Mason 
272309a2a8f9SJosef Bacik 	if (cow && (p->keep_locks || p->lowest_level))
2724bd681513SChris Mason 		write_lock_level = BTRFS_MAX_LEVEL;
2725bd681513SChris Mason 
2726f7c79f30SChris Mason 	min_write_lock_level = write_lock_level;
2727f7c79f30SChris Mason 
2728bb803951SChris Mason again:
2729d7396f07SFilipe David Borba Manana 	prev_cmp = -1;
2730bd681513SChris Mason 	/*
2731bd681513SChris Mason 	 * we try very hard to do read locks on the root
2732bd681513SChris Mason 	 */
2733bd681513SChris Mason 	root_lock = BTRFS_READ_LOCK;
2734bd681513SChris Mason 	level = 0;
27355d4f98a2SYan Zheng 	if (p->search_commit_root) {
2736bd681513SChris Mason 		/*
2737bd681513SChris Mason 		 * the commit roots are read only
2738bd681513SChris Mason 		 * so we always do read locks
2739bd681513SChris Mason 		 */
27403f8a18ccSJosef Bacik 		if (p->need_commit_sem)
27413f8a18ccSJosef Bacik 			down_read(&root->fs_info->commit_root_sem);
27425d4f98a2SYan Zheng 		b = root->commit_root;
27435d4f98a2SYan Zheng 		extent_buffer_get(b);
2744bd681513SChris Mason 		level = btrfs_header_level(b);
27453f8a18ccSJosef Bacik 		if (p->need_commit_sem)
27463f8a18ccSJosef Bacik 			up_read(&root->fs_info->commit_root_sem);
27475d4f98a2SYan Zheng 		if (!p->skip_locking)
2748bd681513SChris Mason 			btrfs_tree_read_lock(b);
27495d4f98a2SYan Zheng 	} else {
2750bd681513SChris Mason 		if (p->skip_locking) {
27515cd57b2cSChris Mason 			b = btrfs_root_node(root);
2752bd681513SChris Mason 			level = btrfs_header_level(b);
2753bd681513SChris Mason 		} else {
2754bd681513SChris Mason 			/* we don't know the level of the root node
2755bd681513SChris Mason 			 * until we actually have it read locked
2756bd681513SChris Mason 			 */
2757bd681513SChris Mason 			b = btrfs_read_lock_root_node(root);
2758bd681513SChris Mason 			level = btrfs_header_level(b);
2759bd681513SChris Mason 			if (level <= write_lock_level) {
2760bd681513SChris Mason 				/* whoops, must trade for write lock */
2761bd681513SChris Mason 				btrfs_tree_read_unlock(b);
2762bd681513SChris Mason 				free_extent_buffer(b);
2763925baeddSChris Mason 				b = btrfs_lock_root_node(root);
2764bd681513SChris Mason 				root_lock = BTRFS_WRITE_LOCK;
2765bd681513SChris Mason 
2766bd681513SChris Mason 				/* the level might have changed, check again */
2767bd681513SChris Mason 				level = btrfs_header_level(b);
27685d4f98a2SYan Zheng 			}
2769bd681513SChris Mason 		}
2770bd681513SChris Mason 	}
2771bd681513SChris Mason 	p->nodes[level] = b;
2772bd681513SChris Mason 	if (!p->skip_locking)
2773bd681513SChris Mason 		p->locks[level] = root_lock;
2774925baeddSChris Mason 
2775eb60ceacSChris Mason 	while (b) {
27765f39d397SChris Mason 		level = btrfs_header_level(b);
277765b51a00SChris Mason 
277865b51a00SChris Mason 		/*
277965b51a00SChris Mason 		 * setup the path here so we can release it under lock
278065b51a00SChris Mason 		 * contention with the cow code
278165b51a00SChris Mason 		 */
278202217ed2SChris Mason 		if (cow) {
2783c8c42864SChris Mason 			/*
2784c8c42864SChris Mason 			 * if we don't really need to cow this block
2785c8c42864SChris Mason 			 * then we don't want to set the path blocking,
2786c8c42864SChris Mason 			 * so we test it here
2787c8c42864SChris Mason 			 */
27885d4f98a2SYan Zheng 			if (!should_cow_block(trans, root, b))
278965b51a00SChris Mason 				goto cow_done;
27905d4f98a2SYan Zheng 
2791bd681513SChris Mason 			/*
2792bd681513SChris Mason 			 * must have write locks on this node and the
2793bd681513SChris Mason 			 * parent
2794bd681513SChris Mason 			 */
27955124e00eSJosef Bacik 			if (level > write_lock_level ||
27965124e00eSJosef Bacik 			    (level + 1 > write_lock_level &&
27975124e00eSJosef Bacik 			    level + 1 < BTRFS_MAX_LEVEL &&
27985124e00eSJosef Bacik 			    p->nodes[level + 1])) {
2799bd681513SChris Mason 				write_lock_level = level + 1;
2800bd681513SChris Mason 				btrfs_release_path(p);
2801bd681513SChris Mason 				goto again;
2802bd681513SChris Mason 			}
2803bd681513SChris Mason 
2804160f4089SFilipe Manana 			btrfs_set_path_blocking(p);
280533c66f43SYan Zheng 			err = btrfs_cow_block(trans, root, b,
2806e20d96d6SChris Mason 					      p->nodes[level + 1],
28079fa8cfe7SChris Mason 					      p->slots[level + 1], &b);
280833c66f43SYan Zheng 			if (err) {
280933c66f43SYan Zheng 				ret = err;
281065b51a00SChris Mason 				goto done;
281154aa1f4dSChris Mason 			}
281202217ed2SChris Mason 		}
281365b51a00SChris Mason cow_done:
2814eb60ceacSChris Mason 		p->nodes[level] = b;
2815bd681513SChris Mason 		btrfs_clear_path_blocking(p, NULL, 0);
2816b4ce94deSChris Mason 
2817b4ce94deSChris Mason 		/*
2818b4ce94deSChris Mason 		 * we have a lock on b and as long as we aren't changing
2819b4ce94deSChris Mason 		 * the tree, there is no way to for the items in b to change.
2820b4ce94deSChris Mason 		 * It is safe to drop the lock on our parent before we
2821b4ce94deSChris Mason 		 * go through the expensive btree search on b.
2822b4ce94deSChris Mason 		 *
2823eb653de1SFilipe David Borba Manana 		 * If we're inserting or deleting (ins_len != 0), then we might
2824eb653de1SFilipe David Borba Manana 		 * be changing slot zero, which may require changing the parent.
2825eb653de1SFilipe David Borba Manana 		 * So, we can't drop the lock until after we know which slot
2826eb653de1SFilipe David Borba Manana 		 * we're operating on.
2827b4ce94deSChris Mason 		 */
2828eb653de1SFilipe David Borba Manana 		if (!ins_len && !p->keep_locks) {
2829eb653de1SFilipe David Borba Manana 			int u = level + 1;
2830eb653de1SFilipe David Borba Manana 
2831eb653de1SFilipe David Borba Manana 			if (u < BTRFS_MAX_LEVEL && p->locks[u]) {
2832eb653de1SFilipe David Borba Manana 				btrfs_tree_unlock_rw(p->nodes[u], p->locks[u]);
2833eb653de1SFilipe David Borba Manana 				p->locks[u] = 0;
2834eb653de1SFilipe David Borba Manana 			}
2835eb653de1SFilipe David Borba Manana 		}
2836b4ce94deSChris Mason 
2837d7396f07SFilipe David Borba Manana 		ret = key_search(b, key, level, &prev_cmp, &slot);
2838b4ce94deSChris Mason 
28395f39d397SChris Mason 		if (level != 0) {
284033c66f43SYan Zheng 			int dec = 0;
284133c66f43SYan Zheng 			if (ret && slot > 0) {
284233c66f43SYan Zheng 				dec = 1;
2843be0e5c09SChris Mason 				slot -= 1;
284433c66f43SYan Zheng 			}
2845be0e5c09SChris Mason 			p->slots[level] = slot;
284633c66f43SYan Zheng 			err = setup_nodes_for_search(trans, root, p, b, level,
2847bd681513SChris Mason 					     ins_len, &write_lock_level);
284833c66f43SYan Zheng 			if (err == -EAGAIN)
2849b4ce94deSChris Mason 				goto again;
285033c66f43SYan Zheng 			if (err) {
285133c66f43SYan Zheng 				ret = err;
285265b51a00SChris Mason 				goto done;
285333c66f43SYan Zheng 			}
28545c680ed6SChris Mason 			b = p->nodes[level];
28555c680ed6SChris Mason 			slot = p->slots[level];
2856b4ce94deSChris Mason 
2857bd681513SChris Mason 			/*
2858bd681513SChris Mason 			 * slot 0 is special, if we change the key
2859bd681513SChris Mason 			 * we have to update the parent pointer
2860bd681513SChris Mason 			 * which means we must have a write lock
2861bd681513SChris Mason 			 * on the parent
2862bd681513SChris Mason 			 */
2863eb653de1SFilipe David Borba Manana 			if (slot == 0 && ins_len &&
2864bd681513SChris Mason 			    write_lock_level < level + 1) {
2865bd681513SChris Mason 				write_lock_level = level + 1;
2866bd681513SChris Mason 				btrfs_release_path(p);
2867bd681513SChris Mason 				goto again;
2868bd681513SChris Mason 			}
2869bd681513SChris Mason 
2870f7c79f30SChris Mason 			unlock_up(p, level, lowest_unlock,
2871f7c79f30SChris Mason 				  min_write_lock_level, &write_lock_level);
2872f9efa9c7SChris Mason 
2873925baeddSChris Mason 			if (level == lowest_level) {
287433c66f43SYan Zheng 				if (dec)
287533c66f43SYan Zheng 					p->slots[level]++;
28765b21f2edSZheng Yan 				goto done;
2877925baeddSChris Mason 			}
2878ca7a79adSChris Mason 
287933c66f43SYan Zheng 			err = read_block_for_search(trans, root, p,
28805d9e75c4SJan Schmidt 						    &b, level, slot, key, 0);
288133c66f43SYan Zheng 			if (err == -EAGAIN)
2882051e1b9fSChris Mason 				goto again;
288333c66f43SYan Zheng 			if (err) {
288433c66f43SYan Zheng 				ret = err;
288576a05b35SChris Mason 				goto done;
288633c66f43SYan Zheng 			}
288776a05b35SChris Mason 
2888b4ce94deSChris Mason 			if (!p->skip_locking) {
2889bd681513SChris Mason 				level = btrfs_header_level(b);
2890bd681513SChris Mason 				if (level <= write_lock_level) {
2891bd681513SChris Mason 					err = btrfs_try_tree_write_lock(b);
289233c66f43SYan Zheng 					if (!err) {
2893b4ce94deSChris Mason 						btrfs_set_path_blocking(p);
2894925baeddSChris Mason 						btrfs_tree_lock(b);
2895bd681513SChris Mason 						btrfs_clear_path_blocking(p, b,
2896bd681513SChris Mason 								  BTRFS_WRITE_LOCK);
2897b4ce94deSChris Mason 					}
2898bd681513SChris Mason 					p->locks[level] = BTRFS_WRITE_LOCK;
2899bd681513SChris Mason 				} else {
2900bd681513SChris Mason 					err = btrfs_try_tree_read_lock(b);
2901bd681513SChris Mason 					if (!err) {
2902bd681513SChris Mason 						btrfs_set_path_blocking(p);
2903bd681513SChris Mason 						btrfs_tree_read_lock(b);
2904bd681513SChris Mason 						btrfs_clear_path_blocking(p, b,
2905bd681513SChris Mason 								  BTRFS_READ_LOCK);
2906bd681513SChris Mason 					}
2907bd681513SChris Mason 					p->locks[level] = BTRFS_READ_LOCK;
2908bd681513SChris Mason 				}
2909bd681513SChris Mason 				p->nodes[level] = b;
2910b4ce94deSChris Mason 			}
2911be0e5c09SChris Mason 		} else {
2912be0e5c09SChris Mason 			p->slots[level] = slot;
291387b29b20SYan Zheng 			if (ins_len > 0 &&
291487b29b20SYan Zheng 			    btrfs_leaf_free_space(root, b) < ins_len) {
2915bd681513SChris Mason 				if (write_lock_level < 1) {
2916bd681513SChris Mason 					write_lock_level = 1;
2917bd681513SChris Mason 					btrfs_release_path(p);
2918bd681513SChris Mason 					goto again;
2919bd681513SChris Mason 				}
2920bd681513SChris Mason 
2921b4ce94deSChris Mason 				btrfs_set_path_blocking(p);
292233c66f43SYan Zheng 				err = split_leaf(trans, root, key,
2923cc0c5538SChris Mason 						 p, ins_len, ret == 0);
2924bd681513SChris Mason 				btrfs_clear_path_blocking(p, NULL, 0);
2925b4ce94deSChris Mason 
292633c66f43SYan Zheng 				BUG_ON(err > 0);
292733c66f43SYan Zheng 				if (err) {
292833c66f43SYan Zheng 					ret = err;
292965b51a00SChris Mason 					goto done;
293065b51a00SChris Mason 				}
29315c680ed6SChris Mason 			}
2932459931ecSChris Mason 			if (!p->search_for_split)
2933f7c79f30SChris Mason 				unlock_up(p, level, lowest_unlock,
2934f7c79f30SChris Mason 					  min_write_lock_level, &write_lock_level);
293565b51a00SChris Mason 			goto done;
293665b51a00SChris Mason 		}
293765b51a00SChris Mason 	}
293865b51a00SChris Mason 	ret = 1;
293965b51a00SChris Mason done:
2940b4ce94deSChris Mason 	/*
2941b4ce94deSChris Mason 	 * we don't really know what they plan on doing with the path
2942b4ce94deSChris Mason 	 * from here on, so for now just mark it as blocking
2943b4ce94deSChris Mason 	 */
2944b9473439SChris Mason 	if (!p->leave_spinning)
2945b4ce94deSChris Mason 		btrfs_set_path_blocking(p);
294676a05b35SChris Mason 	if (ret < 0)
2947b3b4aa74SDavid Sterba 		btrfs_release_path(p);
2948be0e5c09SChris Mason 	return ret;
2949be0e5c09SChris Mason }
2950be0e5c09SChris Mason 
295174123bd7SChris Mason /*
29525d9e75c4SJan Schmidt  * Like btrfs_search_slot, this looks for a key in the given tree. It uses the
29535d9e75c4SJan Schmidt  * current state of the tree together with the operations recorded in the tree
29545d9e75c4SJan Schmidt  * modification log to search for the key in a previous version of this tree, as
29555d9e75c4SJan Schmidt  * denoted by the time_seq parameter.
29565d9e75c4SJan Schmidt  *
29575d9e75c4SJan Schmidt  * Naturally, there is no support for insert, delete or cow operations.
29585d9e75c4SJan Schmidt  *
29595d9e75c4SJan Schmidt  * The resulting path and return value will be set up as if we called
29605d9e75c4SJan Schmidt  * btrfs_search_slot at that point in time with ins_len and cow both set to 0.
29615d9e75c4SJan Schmidt  */
29625d9e75c4SJan Schmidt int btrfs_search_old_slot(struct btrfs_root *root, struct btrfs_key *key,
29635d9e75c4SJan Schmidt 			  struct btrfs_path *p, u64 time_seq)
29645d9e75c4SJan Schmidt {
29655d9e75c4SJan Schmidt 	struct extent_buffer *b;
29665d9e75c4SJan Schmidt 	int slot;
29675d9e75c4SJan Schmidt 	int ret;
29685d9e75c4SJan Schmidt 	int err;
29695d9e75c4SJan Schmidt 	int level;
29705d9e75c4SJan Schmidt 	int lowest_unlock = 1;
29715d9e75c4SJan Schmidt 	u8 lowest_level = 0;
2972d4b4087cSJosef Bacik 	int prev_cmp = -1;
29735d9e75c4SJan Schmidt 
29745d9e75c4SJan Schmidt 	lowest_level = p->lowest_level;
29755d9e75c4SJan Schmidt 	WARN_ON(p->nodes[0] != NULL);
29765d9e75c4SJan Schmidt 
29775d9e75c4SJan Schmidt 	if (p->search_commit_root) {
29785d9e75c4SJan Schmidt 		BUG_ON(time_seq);
29795d9e75c4SJan Schmidt 		return btrfs_search_slot(NULL, root, key, p, 0, 0);
29805d9e75c4SJan Schmidt 	}
29815d9e75c4SJan Schmidt 
29825d9e75c4SJan Schmidt again:
29835d9e75c4SJan Schmidt 	b = get_old_root(root, time_seq);
29845d9e75c4SJan Schmidt 	level = btrfs_header_level(b);
29855d9e75c4SJan Schmidt 	p->locks[level] = BTRFS_READ_LOCK;
29865d9e75c4SJan Schmidt 
29875d9e75c4SJan Schmidt 	while (b) {
29885d9e75c4SJan Schmidt 		level = btrfs_header_level(b);
29895d9e75c4SJan Schmidt 		p->nodes[level] = b;
29905d9e75c4SJan Schmidt 		btrfs_clear_path_blocking(p, NULL, 0);
29915d9e75c4SJan Schmidt 
29925d9e75c4SJan Schmidt 		/*
29935d9e75c4SJan Schmidt 		 * we have a lock on b and as long as we aren't changing
29945d9e75c4SJan Schmidt 		 * the tree, there is no way to for the items in b to change.
29955d9e75c4SJan Schmidt 		 * It is safe to drop the lock on our parent before we
29965d9e75c4SJan Schmidt 		 * go through the expensive btree search on b.
29975d9e75c4SJan Schmidt 		 */
29985d9e75c4SJan Schmidt 		btrfs_unlock_up_safe(p, level + 1);
29995d9e75c4SJan Schmidt 
3000d4b4087cSJosef Bacik 		/*
3001d4b4087cSJosef Bacik 		 * Since we can unwind eb's we want to do a real search every
3002d4b4087cSJosef Bacik 		 * time.
3003d4b4087cSJosef Bacik 		 */
3004d4b4087cSJosef Bacik 		prev_cmp = -1;
3005d7396f07SFilipe David Borba Manana 		ret = key_search(b, key, level, &prev_cmp, &slot);
30065d9e75c4SJan Schmidt 
30075d9e75c4SJan Schmidt 		if (level != 0) {
30085d9e75c4SJan Schmidt 			int dec = 0;
30095d9e75c4SJan Schmidt 			if (ret && slot > 0) {
30105d9e75c4SJan Schmidt 				dec = 1;
30115d9e75c4SJan Schmidt 				slot -= 1;
30125d9e75c4SJan Schmidt 			}
30135d9e75c4SJan Schmidt 			p->slots[level] = slot;
30145d9e75c4SJan Schmidt 			unlock_up(p, level, lowest_unlock, 0, NULL);
30155d9e75c4SJan Schmidt 
30165d9e75c4SJan Schmidt 			if (level == lowest_level) {
30175d9e75c4SJan Schmidt 				if (dec)
30185d9e75c4SJan Schmidt 					p->slots[level]++;
30195d9e75c4SJan Schmidt 				goto done;
30205d9e75c4SJan Schmidt 			}
30215d9e75c4SJan Schmidt 
30225d9e75c4SJan Schmidt 			err = read_block_for_search(NULL, root, p, &b, level,
30235d9e75c4SJan Schmidt 						    slot, key, time_seq);
30245d9e75c4SJan Schmidt 			if (err == -EAGAIN)
30255d9e75c4SJan Schmidt 				goto again;
30265d9e75c4SJan Schmidt 			if (err) {
30275d9e75c4SJan Schmidt 				ret = err;
30285d9e75c4SJan Schmidt 				goto done;
30295d9e75c4SJan Schmidt 			}
30305d9e75c4SJan Schmidt 
30315d9e75c4SJan Schmidt 			level = btrfs_header_level(b);
30325d9e75c4SJan Schmidt 			err = btrfs_try_tree_read_lock(b);
30335d9e75c4SJan Schmidt 			if (!err) {
30345d9e75c4SJan Schmidt 				btrfs_set_path_blocking(p);
30355d9e75c4SJan Schmidt 				btrfs_tree_read_lock(b);
30365d9e75c4SJan Schmidt 				btrfs_clear_path_blocking(p, b,
30375d9e75c4SJan Schmidt 							  BTRFS_READ_LOCK);
30385d9e75c4SJan Schmidt 			}
30399ec72677SJosef Bacik 			b = tree_mod_log_rewind(root->fs_info, p, b, time_seq);
3040db7f3436SJosef Bacik 			if (!b) {
3041db7f3436SJosef Bacik 				ret = -ENOMEM;
3042db7f3436SJosef Bacik 				goto done;
3043db7f3436SJosef Bacik 			}
30445d9e75c4SJan Schmidt 			p->locks[level] = BTRFS_READ_LOCK;
30455d9e75c4SJan Schmidt 			p->nodes[level] = b;
30465d9e75c4SJan Schmidt 		} else {
30475d9e75c4SJan Schmidt 			p->slots[level] = slot;
30485d9e75c4SJan Schmidt 			unlock_up(p, level, lowest_unlock, 0, NULL);
30495d9e75c4SJan Schmidt 			goto done;
30505d9e75c4SJan Schmidt 		}
30515d9e75c4SJan Schmidt 	}
30525d9e75c4SJan Schmidt 	ret = 1;
30535d9e75c4SJan Schmidt done:
30545d9e75c4SJan Schmidt 	if (!p->leave_spinning)
30555d9e75c4SJan Schmidt 		btrfs_set_path_blocking(p);
30565d9e75c4SJan Schmidt 	if (ret < 0)
30575d9e75c4SJan Schmidt 		btrfs_release_path(p);
30585d9e75c4SJan Schmidt 
30595d9e75c4SJan Schmidt 	return ret;
30605d9e75c4SJan Schmidt }
30615d9e75c4SJan Schmidt 
30625d9e75c4SJan Schmidt /*
30632f38b3e1SArne Jansen  * helper to use instead of search slot if no exact match is needed but
30642f38b3e1SArne Jansen  * instead the next or previous item should be returned.
30652f38b3e1SArne Jansen  * When find_higher is true, the next higher item is returned, the next lower
30662f38b3e1SArne Jansen  * otherwise.
30672f38b3e1SArne Jansen  * When return_any and find_higher are both true, and no higher item is found,
30682f38b3e1SArne Jansen  * return the next lower instead.
30692f38b3e1SArne Jansen  * When return_any is true and find_higher is false, and no lower item is found,
30702f38b3e1SArne Jansen  * return the next higher instead.
30712f38b3e1SArne Jansen  * It returns 0 if any item is found, 1 if none is found (tree empty), and
30722f38b3e1SArne Jansen  * < 0 on error
30732f38b3e1SArne Jansen  */
30742f38b3e1SArne Jansen int btrfs_search_slot_for_read(struct btrfs_root *root,
30752f38b3e1SArne Jansen 			       struct btrfs_key *key, struct btrfs_path *p,
30762f38b3e1SArne Jansen 			       int find_higher, int return_any)
30772f38b3e1SArne Jansen {
30782f38b3e1SArne Jansen 	int ret;
30792f38b3e1SArne Jansen 	struct extent_buffer *leaf;
30802f38b3e1SArne Jansen 
30812f38b3e1SArne Jansen again:
30822f38b3e1SArne Jansen 	ret = btrfs_search_slot(NULL, root, key, p, 0, 0);
30832f38b3e1SArne Jansen 	if (ret <= 0)
30842f38b3e1SArne Jansen 		return ret;
30852f38b3e1SArne Jansen 	/*
30862f38b3e1SArne Jansen 	 * a return value of 1 means the path is at the position where the
30872f38b3e1SArne Jansen 	 * item should be inserted. Normally this is the next bigger item,
30882f38b3e1SArne Jansen 	 * but in case the previous item is the last in a leaf, path points
30892f38b3e1SArne Jansen 	 * to the first free slot in the previous leaf, i.e. at an invalid
30902f38b3e1SArne Jansen 	 * item.
30912f38b3e1SArne Jansen 	 */
30922f38b3e1SArne Jansen 	leaf = p->nodes[0];
30932f38b3e1SArne Jansen 
30942f38b3e1SArne Jansen 	if (find_higher) {
30952f38b3e1SArne Jansen 		if (p->slots[0] >= btrfs_header_nritems(leaf)) {
30962f38b3e1SArne Jansen 			ret = btrfs_next_leaf(root, p);
30972f38b3e1SArne Jansen 			if (ret <= 0)
30982f38b3e1SArne Jansen 				return ret;
30992f38b3e1SArne Jansen 			if (!return_any)
31002f38b3e1SArne Jansen 				return 1;
31012f38b3e1SArne Jansen 			/*
31022f38b3e1SArne Jansen 			 * no higher item found, return the next
31032f38b3e1SArne Jansen 			 * lower instead
31042f38b3e1SArne Jansen 			 */
31052f38b3e1SArne Jansen 			return_any = 0;
31062f38b3e1SArne Jansen 			find_higher = 0;
31072f38b3e1SArne Jansen 			btrfs_release_path(p);
31082f38b3e1SArne Jansen 			goto again;
31092f38b3e1SArne Jansen 		}
31102f38b3e1SArne Jansen 	} else {
31112f38b3e1SArne Jansen 		if (p->slots[0] == 0) {
31122f38b3e1SArne Jansen 			ret = btrfs_prev_leaf(root, p);
3113e6793769SArne Jansen 			if (ret < 0)
31142f38b3e1SArne Jansen 				return ret;
3115e6793769SArne Jansen 			if (!ret) {
311623c6bf6aSFilipe David Borba Manana 				leaf = p->nodes[0];
311723c6bf6aSFilipe David Borba Manana 				if (p->slots[0] == btrfs_header_nritems(leaf))
311823c6bf6aSFilipe David Borba Manana 					p->slots[0]--;
3119e6793769SArne Jansen 				return 0;
3120e6793769SArne Jansen 			}
31212f38b3e1SArne Jansen 			if (!return_any)
31222f38b3e1SArne Jansen 				return 1;
31232f38b3e1SArne Jansen 			/*
31242f38b3e1SArne Jansen 			 * no lower item found, return the next
31252f38b3e1SArne Jansen 			 * higher instead
31262f38b3e1SArne Jansen 			 */
31272f38b3e1SArne Jansen 			return_any = 0;
31282f38b3e1SArne Jansen 			find_higher = 1;
31292f38b3e1SArne Jansen 			btrfs_release_path(p);
31302f38b3e1SArne Jansen 			goto again;
3131e6793769SArne Jansen 		} else {
31322f38b3e1SArne Jansen 			--p->slots[0];
31332f38b3e1SArne Jansen 		}
31342f38b3e1SArne Jansen 	}
31352f38b3e1SArne Jansen 	return 0;
31362f38b3e1SArne Jansen }
31372f38b3e1SArne Jansen 
31382f38b3e1SArne Jansen /*
313974123bd7SChris Mason  * adjust the pointers going up the tree, starting at level
314074123bd7SChris Mason  * making sure the right key of each node is points to 'key'.
314174123bd7SChris Mason  * This is used after shifting pointers to the left, so it stops
314274123bd7SChris Mason  * fixing up pointers when a given leaf/node is not in slot 0 of the
314374123bd7SChris Mason  * higher levels
3144aa5d6bedSChris Mason  *
314574123bd7SChris Mason  */
3146d6a0a126STsutomu Itoh static void fixup_low_keys(struct btrfs_root *root, struct btrfs_path *path,
31475f39d397SChris Mason 			   struct btrfs_disk_key *key, int level)
3148be0e5c09SChris Mason {
3149be0e5c09SChris Mason 	int i;
31505f39d397SChris Mason 	struct extent_buffer *t;
31515f39d397SChris Mason 
3152234b63a0SChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
3153be0e5c09SChris Mason 		int tslot = path->slots[i];
3154eb60ceacSChris Mason 		if (!path->nodes[i])
3155be0e5c09SChris Mason 			break;
31565f39d397SChris Mason 		t = path->nodes[i];
315732adf090SLiu Bo 		tree_mod_log_set_node_key(root->fs_info, t, tslot, 1);
31585f39d397SChris Mason 		btrfs_set_node_key(t, key, tslot);
3159d6025579SChris Mason 		btrfs_mark_buffer_dirty(path->nodes[i]);
3160be0e5c09SChris Mason 		if (tslot != 0)
3161be0e5c09SChris Mason 			break;
3162be0e5c09SChris Mason 	}
3163be0e5c09SChris Mason }
3164be0e5c09SChris Mason 
316574123bd7SChris Mason /*
316631840ae1SZheng Yan  * update item key.
316731840ae1SZheng Yan  *
316831840ae1SZheng Yan  * This function isn't completely safe. It's the caller's responsibility
316931840ae1SZheng Yan  * that the new key won't break the order
317031840ae1SZheng Yan  */
3171afe5fea7STsutomu Itoh void btrfs_set_item_key_safe(struct btrfs_root *root, struct btrfs_path *path,
317231840ae1SZheng Yan 			     struct btrfs_key *new_key)
317331840ae1SZheng Yan {
317431840ae1SZheng Yan 	struct btrfs_disk_key disk_key;
317531840ae1SZheng Yan 	struct extent_buffer *eb;
317631840ae1SZheng Yan 	int slot;
317731840ae1SZheng Yan 
317831840ae1SZheng Yan 	eb = path->nodes[0];
317931840ae1SZheng Yan 	slot = path->slots[0];
318031840ae1SZheng Yan 	if (slot > 0) {
318131840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot - 1);
3182143bede5SJeff Mahoney 		BUG_ON(comp_keys(&disk_key, new_key) >= 0);
318331840ae1SZheng Yan 	}
318431840ae1SZheng Yan 	if (slot < btrfs_header_nritems(eb) - 1) {
318531840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot + 1);
3186143bede5SJeff Mahoney 		BUG_ON(comp_keys(&disk_key, new_key) <= 0);
318731840ae1SZheng Yan 	}
318831840ae1SZheng Yan 
318931840ae1SZheng Yan 	btrfs_cpu_key_to_disk(&disk_key, new_key);
319031840ae1SZheng Yan 	btrfs_set_item_key(eb, &disk_key, slot);
319131840ae1SZheng Yan 	btrfs_mark_buffer_dirty(eb);
319231840ae1SZheng Yan 	if (slot == 0)
3193d6a0a126STsutomu Itoh 		fixup_low_keys(root, path, &disk_key, 1);
319431840ae1SZheng Yan }
319531840ae1SZheng Yan 
319631840ae1SZheng Yan /*
319774123bd7SChris Mason  * try to push data from one node into the next node left in the
319879f95c82SChris Mason  * tree.
3199aa5d6bedSChris Mason  *
3200aa5d6bedSChris Mason  * returns 0 if some ptrs were pushed left, < 0 if there was some horrible
3201aa5d6bedSChris Mason  * error, and > 0 if there was no room in the left hand block.
320274123bd7SChris Mason  */
320398ed5174SChris Mason static int push_node_left(struct btrfs_trans_handle *trans,
320498ed5174SChris Mason 			  struct btrfs_root *root, struct extent_buffer *dst,
3205971a1f66SChris Mason 			  struct extent_buffer *src, int empty)
3206be0e5c09SChris Mason {
3207be0e5c09SChris Mason 	int push_items = 0;
3208bb803951SChris Mason 	int src_nritems;
3209bb803951SChris Mason 	int dst_nritems;
3210aa5d6bedSChris Mason 	int ret = 0;
3211be0e5c09SChris Mason 
32125f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
32135f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
3214123abc88SChris Mason 	push_items = BTRFS_NODEPTRS_PER_BLOCK(root) - dst_nritems;
32157bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
32167bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
321754aa1f4dSChris Mason 
3218bce4eae9SChris Mason 	if (!empty && src_nritems <= 8)
3219971a1f66SChris Mason 		return 1;
3220971a1f66SChris Mason 
3221d397712bSChris Mason 	if (push_items <= 0)
3222be0e5c09SChris Mason 		return 1;
3223be0e5c09SChris Mason 
3224bce4eae9SChris Mason 	if (empty) {
3225971a1f66SChris Mason 		push_items = min(src_nritems, push_items);
3226bce4eae9SChris Mason 		if (push_items < src_nritems) {
3227bce4eae9SChris Mason 			/* leave at least 8 pointers in the node if
3228bce4eae9SChris Mason 			 * we aren't going to empty it
3229bce4eae9SChris Mason 			 */
3230bce4eae9SChris Mason 			if (src_nritems - push_items < 8) {
3231bce4eae9SChris Mason 				if (push_items <= 8)
3232bce4eae9SChris Mason 					return 1;
3233bce4eae9SChris Mason 				push_items -= 8;
3234bce4eae9SChris Mason 			}
3235bce4eae9SChris Mason 		}
3236bce4eae9SChris Mason 	} else
3237bce4eae9SChris Mason 		push_items = min(src_nritems - 8, push_items);
323879f95c82SChris Mason 
32395de865eeSFilipe David Borba Manana 	ret = tree_mod_log_eb_copy(root->fs_info, dst, src, dst_nritems, 0,
324090f8d62eSJan Schmidt 				   push_items);
32415de865eeSFilipe David Borba Manana 	if (ret) {
32425de865eeSFilipe David Borba Manana 		btrfs_abort_transaction(trans, root, ret);
32435de865eeSFilipe David Borba Manana 		return ret;
32445de865eeSFilipe David Borba Manana 	}
32455f39d397SChris Mason 	copy_extent_buffer(dst, src,
32465f39d397SChris Mason 			   btrfs_node_key_ptr_offset(dst_nritems),
32475f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
3248123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
32495f39d397SChris Mason 
3250bb803951SChris Mason 	if (push_items < src_nritems) {
325157911b8bSJan Schmidt 		/*
325257911b8bSJan Schmidt 		 * don't call tree_mod_log_eb_move here, key removal was already
325357911b8bSJan Schmidt 		 * fully logged by tree_mod_log_eb_copy above.
325457911b8bSJan Schmidt 		 */
32555f39d397SChris Mason 		memmove_extent_buffer(src, btrfs_node_key_ptr_offset(0),
32565f39d397SChris Mason 				      btrfs_node_key_ptr_offset(push_items),
3257e2fa7227SChris Mason 				      (src_nritems - push_items) *
3258123abc88SChris Mason 				      sizeof(struct btrfs_key_ptr));
3259bb803951SChris Mason 	}
32605f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
32615f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
32625f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
32635f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
326431840ae1SZheng Yan 
3265bb803951SChris Mason 	return ret;
3266be0e5c09SChris Mason }
3267be0e5c09SChris Mason 
326897571fd0SChris Mason /*
326979f95c82SChris Mason  * try to push data from one node into the next node right in the
327079f95c82SChris Mason  * tree.
327179f95c82SChris Mason  *
327279f95c82SChris Mason  * returns 0 if some ptrs were pushed, < 0 if there was some horrible
327379f95c82SChris Mason  * error, and > 0 if there was no room in the right hand block.
327479f95c82SChris Mason  *
327579f95c82SChris Mason  * this will  only push up to 1/2 the contents of the left node over
327679f95c82SChris Mason  */
32775f39d397SChris Mason static int balance_node_right(struct btrfs_trans_handle *trans,
32785f39d397SChris Mason 			      struct btrfs_root *root,
32795f39d397SChris Mason 			      struct extent_buffer *dst,
32805f39d397SChris Mason 			      struct extent_buffer *src)
328179f95c82SChris Mason {
328279f95c82SChris Mason 	int push_items = 0;
328379f95c82SChris Mason 	int max_push;
328479f95c82SChris Mason 	int src_nritems;
328579f95c82SChris Mason 	int dst_nritems;
328679f95c82SChris Mason 	int ret = 0;
328779f95c82SChris Mason 
32887bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
32897bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
32907bb86316SChris Mason 
32915f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
32925f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
3293123abc88SChris Mason 	push_items = BTRFS_NODEPTRS_PER_BLOCK(root) - dst_nritems;
3294d397712bSChris Mason 	if (push_items <= 0)
329579f95c82SChris Mason 		return 1;
3296bce4eae9SChris Mason 
3297d397712bSChris Mason 	if (src_nritems < 4)
3298bce4eae9SChris Mason 		return 1;
329979f95c82SChris Mason 
330079f95c82SChris Mason 	max_push = src_nritems / 2 + 1;
330179f95c82SChris Mason 	/* don't try to empty the node */
3302d397712bSChris Mason 	if (max_push >= src_nritems)
330379f95c82SChris Mason 		return 1;
3304252c38f0SYan 
330579f95c82SChris Mason 	if (max_push < push_items)
330679f95c82SChris Mason 		push_items = max_push;
330779f95c82SChris Mason 
3308f230475eSJan Schmidt 	tree_mod_log_eb_move(root->fs_info, dst, push_items, 0, dst_nritems);
33095f39d397SChris Mason 	memmove_extent_buffer(dst, btrfs_node_key_ptr_offset(push_items),
33105f39d397SChris Mason 				      btrfs_node_key_ptr_offset(0),
33115f39d397SChris Mason 				      (dst_nritems) *
33125f39d397SChris Mason 				      sizeof(struct btrfs_key_ptr));
3313d6025579SChris Mason 
33145de865eeSFilipe David Borba Manana 	ret = tree_mod_log_eb_copy(root->fs_info, dst, src, 0,
331590f8d62eSJan Schmidt 				   src_nritems - push_items, push_items);
33165de865eeSFilipe David Borba Manana 	if (ret) {
33175de865eeSFilipe David Borba Manana 		btrfs_abort_transaction(trans, root, ret);
33185de865eeSFilipe David Borba Manana 		return ret;
33195de865eeSFilipe David Borba Manana 	}
33205f39d397SChris Mason 	copy_extent_buffer(dst, src,
33215f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
33225f39d397SChris Mason 			   btrfs_node_key_ptr_offset(src_nritems - push_items),
3323123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
332479f95c82SChris Mason 
33255f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
33265f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
332779f95c82SChris Mason 
33285f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
33295f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
333031840ae1SZheng Yan 
333179f95c82SChris Mason 	return ret;
333279f95c82SChris Mason }
333379f95c82SChris Mason 
333479f95c82SChris Mason /*
333597571fd0SChris Mason  * helper function to insert a new root level in the tree.
333697571fd0SChris Mason  * A new node is allocated, and a single item is inserted to
333797571fd0SChris Mason  * point to the existing root
3338aa5d6bedSChris Mason  *
3339aa5d6bedSChris Mason  * returns zero on success or < 0 on failure.
334097571fd0SChris Mason  */
3341d397712bSChris Mason static noinline int insert_new_root(struct btrfs_trans_handle *trans,
33425f39d397SChris Mason 			   struct btrfs_root *root,
3343fdd99c72SLiu Bo 			   struct btrfs_path *path, int level)
334474123bd7SChris Mason {
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 
336031840ae1SZheng Yan 	c = btrfs_alloc_free_block(trans, root, root->nodesize, 0,
33615d4f98a2SYan Zheng 				   root->root_key.objectid, &lower_key,
33625581a51aSJan Schmidt 				   level, root->node->start, 0);
33635f39d397SChris Mason 	if (IS_ERR(c))
33645f39d397SChris Mason 		return PTR_ERR(c);
3365925baeddSChris Mason 
3366f0486c68SYan, Zheng 	root_add_used(root, root->nodesize);
3367f0486c68SYan, Zheng 
33685d4f98a2SYan Zheng 	memset_extent_buffer(c, 0, 0, sizeof(struct btrfs_header));
33695f39d397SChris Mason 	btrfs_set_header_nritems(c, 1);
33705f39d397SChris Mason 	btrfs_set_header_level(c, level);
3371db94535dSChris Mason 	btrfs_set_header_bytenr(c, c->start);
33725f39d397SChris Mason 	btrfs_set_header_generation(c, trans->transid);
33735d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(c, BTRFS_MIXED_BACKREF_REV);
33745f39d397SChris Mason 	btrfs_set_header_owner(c, root->root_key.objectid);
3375d5719762SChris Mason 
33760a4e5586SRoss Kirk 	write_extent_buffer(c, root->fs_info->fsid, btrfs_header_fsid(),
33775f39d397SChris Mason 			    BTRFS_FSID_SIZE);
3378e17cade2SChris Mason 
3379e17cade2SChris Mason 	write_extent_buffer(c, root->fs_info->chunk_tree_uuid,
3380b308bc2fSGeert Uytterhoeven 			    btrfs_header_chunk_tree_uuid(c), BTRFS_UUID_SIZE);
3381e17cade2SChris Mason 
33825f39d397SChris Mason 	btrfs_set_node_key(c, &lower_key, 0);
3383db94535dSChris Mason 	btrfs_set_node_blockptr(c, 0, lower->start);
33847bb86316SChris Mason 	lower_gen = btrfs_header_generation(lower);
338531840ae1SZheng Yan 	WARN_ON(lower_gen != trans->transid);
33867bb86316SChris Mason 
33877bb86316SChris Mason 	btrfs_set_node_ptr_generation(c, 0, lower_gen);
33885f39d397SChris Mason 
33895f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
3390d5719762SChris Mason 
3391925baeddSChris Mason 	old = root->node;
3392fdd99c72SLiu Bo 	tree_mod_log_set_root_pointer(root, c, 0);
3393240f62c8SChris Mason 	rcu_assign_pointer(root->node, c);
3394925baeddSChris Mason 
3395925baeddSChris Mason 	/* the super has an extra ref to root->node */
3396925baeddSChris Mason 	free_extent_buffer(old);
3397925baeddSChris Mason 
33980b86a832SChris Mason 	add_root_to_dirty_list(root);
33995f39d397SChris Mason 	extent_buffer_get(c);
34005f39d397SChris Mason 	path->nodes[level] = c;
3401bd681513SChris Mason 	path->locks[level] = BTRFS_WRITE_LOCK;
340274123bd7SChris Mason 	path->slots[level] = 0;
340374123bd7SChris Mason 	return 0;
340474123bd7SChris Mason }
34055c680ed6SChris Mason 
34065c680ed6SChris Mason /*
34075c680ed6SChris Mason  * worker function to insert a single pointer in a node.
34085c680ed6SChris Mason  * the node should have enough room for the pointer already
340997571fd0SChris Mason  *
34105c680ed6SChris Mason  * slot and level indicate where you want the key to go, and
34115c680ed6SChris Mason  * blocknr is the block the key points to.
34125c680ed6SChris Mason  */
3413143bede5SJeff Mahoney static void insert_ptr(struct btrfs_trans_handle *trans,
3414143bede5SJeff Mahoney 		       struct btrfs_root *root, struct btrfs_path *path,
3415143bede5SJeff Mahoney 		       struct btrfs_disk_key *key, u64 bytenr,
3416c3e06965SJan Schmidt 		       int slot, int level)
34175c680ed6SChris Mason {
34185f39d397SChris Mason 	struct extent_buffer *lower;
34195c680ed6SChris Mason 	int nritems;
3420f3ea38daSJan Schmidt 	int ret;
34215c680ed6SChris Mason 
34225c680ed6SChris Mason 	BUG_ON(!path->nodes[level]);
3423f0486c68SYan, Zheng 	btrfs_assert_tree_locked(path->nodes[level]);
34245f39d397SChris Mason 	lower = path->nodes[level];
34255f39d397SChris Mason 	nritems = btrfs_header_nritems(lower);
3426c293498bSStoyan Gaydarov 	BUG_ON(slot > nritems);
3427143bede5SJeff Mahoney 	BUG_ON(nritems == BTRFS_NODEPTRS_PER_BLOCK(root));
342874123bd7SChris Mason 	if (slot != nritems) {
3429c3e06965SJan Schmidt 		if (level)
3430f3ea38daSJan Schmidt 			tree_mod_log_eb_move(root->fs_info, lower, slot + 1,
3431f3ea38daSJan Schmidt 					     slot, nritems - slot);
34325f39d397SChris Mason 		memmove_extent_buffer(lower,
34335f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot + 1),
34345f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot),
3435123abc88SChris Mason 			      (nritems - slot) * sizeof(struct btrfs_key_ptr));
343674123bd7SChris Mason 	}
3437c3e06965SJan Schmidt 	if (level) {
3438f3ea38daSJan Schmidt 		ret = tree_mod_log_insert_key(root->fs_info, lower, slot,
3439c8cc6341SJosef Bacik 					      MOD_LOG_KEY_ADD, GFP_NOFS);
3440f3ea38daSJan Schmidt 		BUG_ON(ret < 0);
3441f3ea38daSJan Schmidt 	}
34425f39d397SChris Mason 	btrfs_set_node_key(lower, key, slot);
3443db94535dSChris Mason 	btrfs_set_node_blockptr(lower, slot, bytenr);
344474493f7aSChris Mason 	WARN_ON(trans->transid == 0);
344574493f7aSChris Mason 	btrfs_set_node_ptr_generation(lower, slot, trans->transid);
34465f39d397SChris Mason 	btrfs_set_header_nritems(lower, nritems + 1);
34475f39d397SChris Mason 	btrfs_mark_buffer_dirty(lower);
344874123bd7SChris Mason }
344974123bd7SChris Mason 
345097571fd0SChris Mason /*
345197571fd0SChris Mason  * split the node at the specified level in path in two.
345297571fd0SChris Mason  * The path is corrected to point to the appropriate node after the split
345397571fd0SChris Mason  *
345497571fd0SChris Mason  * Before splitting this tries to make some room in the node by pushing
345597571fd0SChris Mason  * left and right, if either one works, it returns right away.
3456aa5d6bedSChris Mason  *
3457aa5d6bedSChris Mason  * returns 0 on success and < 0 on failure
345897571fd0SChris Mason  */
3459e02119d5SChris Mason static noinline int split_node(struct btrfs_trans_handle *trans,
3460e02119d5SChris Mason 			       struct btrfs_root *root,
3461e02119d5SChris Mason 			       struct btrfs_path *path, int level)
3462be0e5c09SChris Mason {
34635f39d397SChris Mason 	struct extent_buffer *c;
34645f39d397SChris Mason 	struct extent_buffer *split;
34655f39d397SChris Mason 	struct btrfs_disk_key disk_key;
3466be0e5c09SChris Mason 	int mid;
34675c680ed6SChris Mason 	int ret;
34687518a238SChris Mason 	u32 c_nritems;
3469be0e5c09SChris Mason 
34705f39d397SChris Mason 	c = path->nodes[level];
34717bb86316SChris Mason 	WARN_ON(btrfs_header_generation(c) != trans->transid);
34725f39d397SChris Mason 	if (c == root->node) {
3473d9abbf1cSJan Schmidt 		/*
347490f8d62eSJan Schmidt 		 * trying to split the root, lets make a new one
347590f8d62eSJan Schmidt 		 *
3476fdd99c72SLiu Bo 		 * tree mod log: We don't log_removal old root in
347790f8d62eSJan Schmidt 		 * insert_new_root, because that root buffer will be kept as a
347890f8d62eSJan Schmidt 		 * normal node. We are going to log removal of half of the
347990f8d62eSJan Schmidt 		 * elements below with tree_mod_log_eb_copy. We're holding a
348090f8d62eSJan Schmidt 		 * tree lock on the buffer, which is why we cannot race with
348190f8d62eSJan Schmidt 		 * other tree_mod_log users.
3482d9abbf1cSJan Schmidt 		 */
3483fdd99c72SLiu Bo 		ret = insert_new_root(trans, root, path, level + 1);
34845c680ed6SChris Mason 		if (ret)
34855c680ed6SChris Mason 			return ret;
3486b3612421SChris Mason 	} else {
3487e66f709bSChris Mason 		ret = push_nodes_for_insert(trans, root, path, level);
34885f39d397SChris Mason 		c = path->nodes[level];
34895f39d397SChris Mason 		if (!ret && btrfs_header_nritems(c) <
3490c448acf0SChris Mason 		    BTRFS_NODEPTRS_PER_BLOCK(root) - 3)
3491e66f709bSChris Mason 			return 0;
349254aa1f4dSChris Mason 		if (ret < 0)
349354aa1f4dSChris Mason 			return ret;
34945c680ed6SChris Mason 	}
3495e66f709bSChris Mason 
34965f39d397SChris Mason 	c_nritems = btrfs_header_nritems(c);
34975d4f98a2SYan Zheng 	mid = (c_nritems + 1) / 2;
34985d4f98a2SYan Zheng 	btrfs_node_key(c, &disk_key, mid);
34997bb86316SChris Mason 
35005d4f98a2SYan Zheng 	split = btrfs_alloc_free_block(trans, root, root->nodesize, 0,
35017bb86316SChris Mason 					root->root_key.objectid,
35025581a51aSJan Schmidt 					&disk_key, level, c->start, 0);
35035f39d397SChris Mason 	if (IS_ERR(split))
35045f39d397SChris Mason 		return PTR_ERR(split);
350554aa1f4dSChris Mason 
3506f0486c68SYan, Zheng 	root_add_used(root, root->nodesize);
3507f0486c68SYan, Zheng 
35085d4f98a2SYan Zheng 	memset_extent_buffer(split, 0, 0, sizeof(struct btrfs_header));
35095f39d397SChris Mason 	btrfs_set_header_level(split, btrfs_header_level(c));
3510db94535dSChris Mason 	btrfs_set_header_bytenr(split, split->start);
35115f39d397SChris Mason 	btrfs_set_header_generation(split, trans->transid);
35125d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(split, BTRFS_MIXED_BACKREF_REV);
35135f39d397SChris Mason 	btrfs_set_header_owner(split, root->root_key.objectid);
35145f39d397SChris Mason 	write_extent_buffer(split, root->fs_info->fsid,
35150a4e5586SRoss Kirk 			    btrfs_header_fsid(), BTRFS_FSID_SIZE);
3516e17cade2SChris Mason 	write_extent_buffer(split, root->fs_info->chunk_tree_uuid,
3517b308bc2fSGeert Uytterhoeven 			    btrfs_header_chunk_tree_uuid(split),
3518e17cade2SChris Mason 			    BTRFS_UUID_SIZE);
35195f39d397SChris Mason 
35205de865eeSFilipe David Borba Manana 	ret = tree_mod_log_eb_copy(root->fs_info, split, c, 0,
35215de865eeSFilipe David Borba Manana 				   mid, c_nritems - mid);
35225de865eeSFilipe David Borba Manana 	if (ret) {
35235de865eeSFilipe David Borba Manana 		btrfs_abort_transaction(trans, root, ret);
35245de865eeSFilipe David Borba Manana 		return ret;
35255de865eeSFilipe David Borba Manana 	}
35265f39d397SChris Mason 	copy_extent_buffer(split, c,
35275f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
35285f39d397SChris Mason 			   btrfs_node_key_ptr_offset(mid),
3529123abc88SChris Mason 			   (c_nritems - mid) * sizeof(struct btrfs_key_ptr));
35305f39d397SChris Mason 	btrfs_set_header_nritems(split, c_nritems - mid);
35315f39d397SChris Mason 	btrfs_set_header_nritems(c, mid);
3532aa5d6bedSChris Mason 	ret = 0;
3533aa5d6bedSChris Mason 
35345f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
35355f39d397SChris Mason 	btrfs_mark_buffer_dirty(split);
35365f39d397SChris Mason 
3537143bede5SJeff Mahoney 	insert_ptr(trans, root, path, &disk_key, split->start,
3538c3e06965SJan Schmidt 		   path->slots[level + 1] + 1, level + 1);
3539aa5d6bedSChris Mason 
35405de08d7dSChris Mason 	if (path->slots[level] >= mid) {
35415c680ed6SChris Mason 		path->slots[level] -= mid;
3542925baeddSChris Mason 		btrfs_tree_unlock(c);
35435f39d397SChris Mason 		free_extent_buffer(c);
35445f39d397SChris Mason 		path->nodes[level] = split;
35455c680ed6SChris Mason 		path->slots[level + 1] += 1;
3546eb60ceacSChris Mason 	} else {
3547925baeddSChris Mason 		btrfs_tree_unlock(split);
35485f39d397SChris Mason 		free_extent_buffer(split);
3549be0e5c09SChris Mason 	}
3550aa5d6bedSChris Mason 	return ret;
3551be0e5c09SChris Mason }
3552be0e5c09SChris Mason 
355374123bd7SChris Mason /*
355474123bd7SChris Mason  * how many bytes are required to store the items in a leaf.  start
355574123bd7SChris Mason  * and nr indicate which items in the leaf to check.  This totals up the
355674123bd7SChris Mason  * space used both by the item structs and the item data
355774123bd7SChris Mason  */
35585f39d397SChris Mason static int leaf_space_used(struct extent_buffer *l, int start, int nr)
3559be0e5c09SChris Mason {
356041be1f3bSJosef Bacik 	struct btrfs_item *start_item;
356141be1f3bSJosef Bacik 	struct btrfs_item *end_item;
356241be1f3bSJosef Bacik 	struct btrfs_map_token token;
3563be0e5c09SChris Mason 	int data_len;
35645f39d397SChris Mason 	int nritems = btrfs_header_nritems(l);
3565d4dbff95SChris Mason 	int end = min(nritems, start + nr) - 1;
3566be0e5c09SChris Mason 
3567be0e5c09SChris Mason 	if (!nr)
3568be0e5c09SChris Mason 		return 0;
356941be1f3bSJosef Bacik 	btrfs_init_map_token(&token);
3570dd3cc16bSRoss Kirk 	start_item = btrfs_item_nr(start);
3571dd3cc16bSRoss Kirk 	end_item = btrfs_item_nr(end);
357241be1f3bSJosef Bacik 	data_len = btrfs_token_item_offset(l, start_item, &token) +
357341be1f3bSJosef Bacik 		btrfs_token_item_size(l, start_item, &token);
357441be1f3bSJosef Bacik 	data_len = data_len - btrfs_token_item_offset(l, end_item, &token);
35750783fcfcSChris Mason 	data_len += sizeof(struct btrfs_item) * nr;
3576d4dbff95SChris Mason 	WARN_ON(data_len < 0);
3577be0e5c09SChris Mason 	return data_len;
3578be0e5c09SChris Mason }
3579be0e5c09SChris Mason 
358074123bd7SChris Mason /*
3581d4dbff95SChris Mason  * The space between the end of the leaf items and
3582d4dbff95SChris Mason  * the start of the leaf data.  IOW, how much room
3583d4dbff95SChris Mason  * the leaf has left for both items and data
3584d4dbff95SChris Mason  */
3585d397712bSChris Mason noinline int btrfs_leaf_free_space(struct btrfs_root *root,
3586e02119d5SChris Mason 				   struct extent_buffer *leaf)
3587d4dbff95SChris Mason {
35885f39d397SChris Mason 	int nritems = btrfs_header_nritems(leaf);
35895f39d397SChris Mason 	int ret;
35905f39d397SChris Mason 	ret = BTRFS_LEAF_DATA_SIZE(root) - leaf_space_used(leaf, 0, nritems);
35915f39d397SChris Mason 	if (ret < 0) {
3592efe120a0SFrank Holton 		btrfs_crit(root->fs_info,
3593efe120a0SFrank Holton 			"leaf free space ret %d, leaf data size %lu, used %d nritems %d",
3594ae2f5411SJens Axboe 		       ret, (unsigned long) BTRFS_LEAF_DATA_SIZE(root),
35955f39d397SChris Mason 		       leaf_space_used(leaf, 0, nritems), nritems);
35965f39d397SChris Mason 	}
35975f39d397SChris Mason 	return ret;
3598d4dbff95SChris Mason }
3599d4dbff95SChris Mason 
360099d8f83cSChris Mason /*
360199d8f83cSChris Mason  * min slot controls the lowest index we're willing to push to the
360299d8f83cSChris Mason  * right.  We'll push up to and including min_slot, but no lower
360399d8f83cSChris Mason  */
360444871b1bSChris Mason static noinline int __push_leaf_right(struct btrfs_trans_handle *trans,
360544871b1bSChris Mason 				      struct btrfs_root *root,
360644871b1bSChris Mason 				      struct btrfs_path *path,
360744871b1bSChris Mason 				      int data_size, int empty,
360844871b1bSChris Mason 				      struct extent_buffer *right,
360999d8f83cSChris Mason 				      int free_space, u32 left_nritems,
361099d8f83cSChris Mason 				      u32 min_slot)
361100ec4c51SChris Mason {
36125f39d397SChris Mason 	struct extent_buffer *left = path->nodes[0];
361344871b1bSChris Mason 	struct extent_buffer *upper = path->nodes[1];
3614cfed81a0SChris Mason 	struct btrfs_map_token token;
36155f39d397SChris Mason 	struct btrfs_disk_key disk_key;
361600ec4c51SChris Mason 	int slot;
361734a38218SChris Mason 	u32 i;
361800ec4c51SChris Mason 	int push_space = 0;
361900ec4c51SChris Mason 	int push_items = 0;
36200783fcfcSChris Mason 	struct btrfs_item *item;
362134a38218SChris Mason 	u32 nr;
36227518a238SChris Mason 	u32 right_nritems;
36235f39d397SChris Mason 	u32 data_end;
3624db94535dSChris Mason 	u32 this_item_size;
362500ec4c51SChris Mason 
3626cfed81a0SChris Mason 	btrfs_init_map_token(&token);
3627cfed81a0SChris Mason 
362834a38218SChris Mason 	if (empty)
362934a38218SChris Mason 		nr = 0;
363034a38218SChris Mason 	else
363199d8f83cSChris Mason 		nr = max_t(u32, 1, min_slot);
363234a38218SChris Mason 
363331840ae1SZheng Yan 	if (path->slots[0] >= left_nritems)
363487b29b20SYan Zheng 		push_space += data_size;
363531840ae1SZheng Yan 
363644871b1bSChris Mason 	slot = path->slots[1];
363734a38218SChris Mason 	i = left_nritems - 1;
363834a38218SChris Mason 	while (i >= nr) {
3639dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
3640db94535dSChris Mason 
364131840ae1SZheng Yan 		if (!empty && push_items > 0) {
364231840ae1SZheng Yan 			if (path->slots[0] > i)
364331840ae1SZheng Yan 				break;
364431840ae1SZheng Yan 			if (path->slots[0] == i) {
364531840ae1SZheng Yan 				int space = btrfs_leaf_free_space(root, left);
364631840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
364731840ae1SZheng Yan 					break;
364831840ae1SZheng Yan 			}
364931840ae1SZheng Yan 		}
365031840ae1SZheng Yan 
365100ec4c51SChris Mason 		if (path->slots[0] == i)
365287b29b20SYan Zheng 			push_space += data_size;
3653db94535dSChris Mason 
3654db94535dSChris Mason 		this_item_size = btrfs_item_size(left, item);
3655db94535dSChris Mason 		if (this_item_size + sizeof(*item) + push_space > free_space)
365600ec4c51SChris Mason 			break;
365731840ae1SZheng Yan 
365800ec4c51SChris Mason 		push_items++;
3659db94535dSChris Mason 		push_space += this_item_size + sizeof(*item);
366034a38218SChris Mason 		if (i == 0)
366134a38218SChris Mason 			break;
366234a38218SChris Mason 		i--;
3663db94535dSChris Mason 	}
36645f39d397SChris Mason 
3665925baeddSChris Mason 	if (push_items == 0)
3666925baeddSChris Mason 		goto out_unlock;
36675f39d397SChris Mason 
36686c1500f2SJulia Lawall 	WARN_ON(!empty && push_items == left_nritems);
36695f39d397SChris Mason 
367000ec4c51SChris Mason 	/* push left to right */
36715f39d397SChris Mason 	right_nritems = btrfs_header_nritems(right);
367234a38218SChris Mason 
36735f39d397SChris Mason 	push_space = btrfs_item_end_nr(left, left_nritems - push_items);
3674123abc88SChris Mason 	push_space -= leaf_data_end(root, left);
36755f39d397SChris Mason 
367600ec4c51SChris Mason 	/* make room in the right data area */
36775f39d397SChris Mason 	data_end = leaf_data_end(root, right);
36785f39d397SChris Mason 	memmove_extent_buffer(right,
36795f39d397SChris Mason 			      btrfs_leaf_data(right) + data_end - push_space,
36805f39d397SChris Mason 			      btrfs_leaf_data(right) + data_end,
36815f39d397SChris Mason 			      BTRFS_LEAF_DATA_SIZE(root) - data_end);
36825f39d397SChris Mason 
368300ec4c51SChris Mason 	/* copy from the left data area */
36845f39d397SChris Mason 	copy_extent_buffer(right, left, btrfs_leaf_data(right) +
3685d6025579SChris Mason 		     BTRFS_LEAF_DATA_SIZE(root) - push_space,
3686d6025579SChris Mason 		     btrfs_leaf_data(left) + leaf_data_end(root, left),
3687d6025579SChris Mason 		     push_space);
36885f39d397SChris Mason 
36895f39d397SChris Mason 	memmove_extent_buffer(right, btrfs_item_nr_offset(push_items),
36905f39d397SChris Mason 			      btrfs_item_nr_offset(0),
36910783fcfcSChris Mason 			      right_nritems * sizeof(struct btrfs_item));
36925f39d397SChris Mason 
369300ec4c51SChris Mason 	/* copy the items from left to right */
36945f39d397SChris Mason 	copy_extent_buffer(right, left, btrfs_item_nr_offset(0),
36955f39d397SChris Mason 		   btrfs_item_nr_offset(left_nritems - push_items),
36960783fcfcSChris Mason 		   push_items * sizeof(struct btrfs_item));
369700ec4c51SChris Mason 
369800ec4c51SChris Mason 	/* update the item pointers */
36997518a238SChris Mason 	right_nritems += push_items;
37005f39d397SChris Mason 	btrfs_set_header_nritems(right, right_nritems);
3701123abc88SChris Mason 	push_space = BTRFS_LEAF_DATA_SIZE(root);
37027518a238SChris Mason 	for (i = 0; i < right_nritems; i++) {
3703dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
3704cfed81a0SChris Mason 		push_space -= btrfs_token_item_size(right, item, &token);
3705cfed81a0SChris Mason 		btrfs_set_token_item_offset(right, item, push_space, &token);
3706db94535dSChris Mason 	}
3707db94535dSChris Mason 
37087518a238SChris Mason 	left_nritems -= push_items;
37095f39d397SChris Mason 	btrfs_set_header_nritems(left, left_nritems);
371000ec4c51SChris Mason 
371134a38218SChris Mason 	if (left_nritems)
37125f39d397SChris Mason 		btrfs_mark_buffer_dirty(left);
3713f0486c68SYan, Zheng 	else
3714f0486c68SYan, Zheng 		clean_tree_block(trans, root, left);
3715f0486c68SYan, Zheng 
37165f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
3717a429e513SChris Mason 
37185f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
37195f39d397SChris Mason 	btrfs_set_node_key(upper, &disk_key, slot + 1);
3720d6025579SChris Mason 	btrfs_mark_buffer_dirty(upper);
372102217ed2SChris Mason 
372200ec4c51SChris Mason 	/* then fixup the leaf pointer in the path */
37237518a238SChris Mason 	if (path->slots[0] >= left_nritems) {
37247518a238SChris Mason 		path->slots[0] -= left_nritems;
3725925baeddSChris Mason 		if (btrfs_header_nritems(path->nodes[0]) == 0)
3726925baeddSChris Mason 			clean_tree_block(trans, root, path->nodes[0]);
3727925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
37285f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
37295f39d397SChris Mason 		path->nodes[0] = right;
373000ec4c51SChris Mason 		path->slots[1] += 1;
373100ec4c51SChris Mason 	} else {
3732925baeddSChris Mason 		btrfs_tree_unlock(right);
37335f39d397SChris Mason 		free_extent_buffer(right);
373400ec4c51SChris Mason 	}
373500ec4c51SChris Mason 	return 0;
3736925baeddSChris Mason 
3737925baeddSChris Mason out_unlock:
3738925baeddSChris Mason 	btrfs_tree_unlock(right);
3739925baeddSChris Mason 	free_extent_buffer(right);
3740925baeddSChris Mason 	return 1;
374100ec4c51SChris Mason }
3742925baeddSChris Mason 
374300ec4c51SChris Mason /*
374444871b1bSChris Mason  * push some data in the path leaf to the right, trying to free up at
374574123bd7SChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
374644871b1bSChris Mason  *
374744871b1bSChris Mason  * returns 1 if the push failed because the other node didn't have enough
374844871b1bSChris Mason  * room, 0 if everything worked out and < 0 if there were major errors.
374999d8f83cSChris Mason  *
375099d8f83cSChris Mason  * this will push starting from min_slot to the end of the leaf.  It won't
375199d8f83cSChris Mason  * push any slot lower than min_slot
375274123bd7SChris Mason  */
375344871b1bSChris Mason static int push_leaf_right(struct btrfs_trans_handle *trans, struct btrfs_root
375499d8f83cSChris Mason 			   *root, struct btrfs_path *path,
375599d8f83cSChris Mason 			   int min_data_size, int data_size,
375699d8f83cSChris Mason 			   int empty, u32 min_slot)
3757be0e5c09SChris Mason {
375844871b1bSChris Mason 	struct extent_buffer *left = path->nodes[0];
375944871b1bSChris Mason 	struct extent_buffer *right;
376044871b1bSChris Mason 	struct extent_buffer *upper;
376144871b1bSChris Mason 	int slot;
376244871b1bSChris Mason 	int free_space;
376344871b1bSChris Mason 	u32 left_nritems;
376444871b1bSChris Mason 	int ret;
376544871b1bSChris Mason 
376644871b1bSChris Mason 	if (!path->nodes[1])
376744871b1bSChris Mason 		return 1;
376844871b1bSChris Mason 
376944871b1bSChris Mason 	slot = path->slots[1];
377044871b1bSChris Mason 	upper = path->nodes[1];
377144871b1bSChris Mason 	if (slot >= btrfs_header_nritems(upper) - 1)
377244871b1bSChris Mason 		return 1;
377344871b1bSChris Mason 
377444871b1bSChris Mason 	btrfs_assert_tree_locked(path->nodes[1]);
377544871b1bSChris Mason 
377644871b1bSChris Mason 	right = read_node_slot(root, upper, slot + 1);
377791ca338dSTsutomu Itoh 	if (right == NULL)
377891ca338dSTsutomu Itoh 		return 1;
377991ca338dSTsutomu Itoh 
378044871b1bSChris Mason 	btrfs_tree_lock(right);
378144871b1bSChris Mason 	btrfs_set_lock_blocking(right);
378244871b1bSChris Mason 
378344871b1bSChris Mason 	free_space = btrfs_leaf_free_space(root, right);
378444871b1bSChris Mason 	if (free_space < data_size)
378544871b1bSChris Mason 		goto out_unlock;
378644871b1bSChris Mason 
378744871b1bSChris Mason 	/* cow and double check */
378844871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, right, upper,
378944871b1bSChris Mason 			      slot + 1, &right);
379044871b1bSChris Mason 	if (ret)
379144871b1bSChris Mason 		goto out_unlock;
379244871b1bSChris Mason 
379344871b1bSChris Mason 	free_space = btrfs_leaf_free_space(root, right);
379444871b1bSChris Mason 	if (free_space < data_size)
379544871b1bSChris Mason 		goto out_unlock;
379644871b1bSChris Mason 
379744871b1bSChris Mason 	left_nritems = btrfs_header_nritems(left);
379844871b1bSChris Mason 	if (left_nritems == 0)
379944871b1bSChris Mason 		goto out_unlock;
380044871b1bSChris Mason 
38012ef1fed2SFilipe David Borba Manana 	if (path->slots[0] == left_nritems && !empty) {
38022ef1fed2SFilipe David Borba Manana 		/* Key greater than all keys in the leaf, right neighbor has
38032ef1fed2SFilipe David Borba Manana 		 * enough room for it and we're not emptying our leaf to delete
38042ef1fed2SFilipe David Borba Manana 		 * it, therefore use right neighbor to insert the new item and
38052ef1fed2SFilipe David Borba Manana 		 * no need to touch/dirty our left leaft. */
38062ef1fed2SFilipe David Borba Manana 		btrfs_tree_unlock(left);
38072ef1fed2SFilipe David Borba Manana 		free_extent_buffer(left);
38082ef1fed2SFilipe David Borba Manana 		path->nodes[0] = right;
38092ef1fed2SFilipe David Borba Manana 		path->slots[0] = 0;
38102ef1fed2SFilipe David Borba Manana 		path->slots[1]++;
38112ef1fed2SFilipe David Borba Manana 		return 0;
38122ef1fed2SFilipe David Borba Manana 	}
38132ef1fed2SFilipe David Borba Manana 
381499d8f83cSChris Mason 	return __push_leaf_right(trans, root, path, min_data_size, empty,
381599d8f83cSChris Mason 				right, free_space, left_nritems, min_slot);
381644871b1bSChris Mason out_unlock:
381744871b1bSChris Mason 	btrfs_tree_unlock(right);
381844871b1bSChris Mason 	free_extent_buffer(right);
381944871b1bSChris Mason 	return 1;
382044871b1bSChris Mason }
382144871b1bSChris Mason 
382244871b1bSChris Mason /*
382344871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
382444871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
382599d8f83cSChris Mason  *
382699d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
382799d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us do all the
382899d8f83cSChris Mason  * items
382944871b1bSChris Mason  */
383044871b1bSChris Mason static noinline int __push_leaf_left(struct btrfs_trans_handle *trans,
383144871b1bSChris Mason 				     struct btrfs_root *root,
383244871b1bSChris Mason 				     struct btrfs_path *path, int data_size,
383344871b1bSChris Mason 				     int empty, struct extent_buffer *left,
383499d8f83cSChris Mason 				     int free_space, u32 right_nritems,
383599d8f83cSChris Mason 				     u32 max_slot)
383644871b1bSChris Mason {
38375f39d397SChris Mason 	struct btrfs_disk_key disk_key;
38385f39d397SChris Mason 	struct extent_buffer *right = path->nodes[0];
3839be0e5c09SChris Mason 	int i;
3840be0e5c09SChris Mason 	int push_space = 0;
3841be0e5c09SChris Mason 	int push_items = 0;
38420783fcfcSChris Mason 	struct btrfs_item *item;
38437518a238SChris Mason 	u32 old_left_nritems;
384434a38218SChris Mason 	u32 nr;
3845aa5d6bedSChris Mason 	int ret = 0;
3846db94535dSChris Mason 	u32 this_item_size;
3847db94535dSChris Mason 	u32 old_left_item_size;
3848cfed81a0SChris Mason 	struct btrfs_map_token token;
3849cfed81a0SChris Mason 
3850cfed81a0SChris Mason 	btrfs_init_map_token(&token);
3851be0e5c09SChris Mason 
385234a38218SChris Mason 	if (empty)
385399d8f83cSChris Mason 		nr = min(right_nritems, max_slot);
385434a38218SChris Mason 	else
385599d8f83cSChris Mason 		nr = min(right_nritems - 1, max_slot);
385634a38218SChris Mason 
385734a38218SChris Mason 	for (i = 0; i < nr; i++) {
3858dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
3859db94535dSChris Mason 
386031840ae1SZheng Yan 		if (!empty && push_items > 0) {
386131840ae1SZheng Yan 			if (path->slots[0] < i)
386231840ae1SZheng Yan 				break;
386331840ae1SZheng Yan 			if (path->slots[0] == i) {
386431840ae1SZheng Yan 				int space = btrfs_leaf_free_space(root, right);
386531840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
386631840ae1SZheng Yan 					break;
386731840ae1SZheng Yan 			}
386831840ae1SZheng Yan 		}
386931840ae1SZheng Yan 
3870be0e5c09SChris Mason 		if (path->slots[0] == i)
387187b29b20SYan Zheng 			push_space += data_size;
3872db94535dSChris Mason 
3873db94535dSChris Mason 		this_item_size = btrfs_item_size(right, item);
3874db94535dSChris Mason 		if (this_item_size + sizeof(*item) + push_space > free_space)
3875be0e5c09SChris Mason 			break;
3876db94535dSChris Mason 
3877be0e5c09SChris Mason 		push_items++;
3878db94535dSChris Mason 		push_space += this_item_size + sizeof(*item);
3879be0e5c09SChris Mason 	}
3880db94535dSChris Mason 
3881be0e5c09SChris Mason 	if (push_items == 0) {
3882925baeddSChris Mason 		ret = 1;
3883925baeddSChris Mason 		goto out;
3884be0e5c09SChris Mason 	}
3885fae7f21cSDulshani Gunawardhana 	WARN_ON(!empty && push_items == btrfs_header_nritems(right));
38865f39d397SChris Mason 
3887be0e5c09SChris Mason 	/* push data from right to left */
38885f39d397SChris Mason 	copy_extent_buffer(left, right,
38895f39d397SChris Mason 			   btrfs_item_nr_offset(btrfs_header_nritems(left)),
38905f39d397SChris Mason 			   btrfs_item_nr_offset(0),
38915f39d397SChris Mason 			   push_items * sizeof(struct btrfs_item));
38925f39d397SChris Mason 
3893123abc88SChris Mason 	push_space = BTRFS_LEAF_DATA_SIZE(root) -
38945f39d397SChris Mason 		     btrfs_item_offset_nr(right, push_items - 1);
38955f39d397SChris Mason 
38965f39d397SChris Mason 	copy_extent_buffer(left, right, btrfs_leaf_data(left) +
3897d6025579SChris Mason 		     leaf_data_end(root, left) - push_space,
3898123abc88SChris Mason 		     btrfs_leaf_data(right) +
38995f39d397SChris Mason 		     btrfs_item_offset_nr(right, push_items - 1),
3900be0e5c09SChris Mason 		     push_space);
39015f39d397SChris Mason 	old_left_nritems = btrfs_header_nritems(left);
390287b29b20SYan Zheng 	BUG_ON(old_left_nritems <= 0);
3903eb60ceacSChris Mason 
3904db94535dSChris Mason 	old_left_item_size = btrfs_item_offset_nr(left, old_left_nritems - 1);
3905be0e5c09SChris Mason 	for (i = old_left_nritems; i < old_left_nritems + push_items; i++) {
39065f39d397SChris Mason 		u32 ioff;
3907db94535dSChris Mason 
3908dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
3909db94535dSChris Mason 
3910cfed81a0SChris Mason 		ioff = btrfs_token_item_offset(left, item, &token);
3911cfed81a0SChris Mason 		btrfs_set_token_item_offset(left, item,
3912cfed81a0SChris Mason 		      ioff - (BTRFS_LEAF_DATA_SIZE(root) - old_left_item_size),
3913cfed81a0SChris Mason 		      &token);
3914be0e5c09SChris Mason 	}
39155f39d397SChris Mason 	btrfs_set_header_nritems(left, old_left_nritems + push_items);
3916be0e5c09SChris Mason 
3917be0e5c09SChris Mason 	/* fixup right node */
391831b1a2bdSJulia Lawall 	if (push_items > right_nritems)
391931b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "push items %d nr %u\n", push_items,
3920d397712bSChris Mason 		       right_nritems);
392134a38218SChris Mason 
392234a38218SChris Mason 	if (push_items < right_nritems) {
39235f39d397SChris Mason 		push_space = btrfs_item_offset_nr(right, push_items - 1) -
3924123abc88SChris Mason 						  leaf_data_end(root, right);
39255f39d397SChris Mason 		memmove_extent_buffer(right, btrfs_leaf_data(right) +
3926d6025579SChris Mason 				      BTRFS_LEAF_DATA_SIZE(root) - push_space,
3927d6025579SChris Mason 				      btrfs_leaf_data(right) +
3928123abc88SChris Mason 				      leaf_data_end(root, right), push_space);
39295f39d397SChris Mason 
39305f39d397SChris Mason 		memmove_extent_buffer(right, btrfs_item_nr_offset(0),
39315f39d397SChris Mason 			      btrfs_item_nr_offset(push_items),
39325f39d397SChris Mason 			     (btrfs_header_nritems(right) - push_items) *
39330783fcfcSChris Mason 			     sizeof(struct btrfs_item));
393434a38218SChris Mason 	}
3935eef1c494SYan 	right_nritems -= push_items;
3936eef1c494SYan 	btrfs_set_header_nritems(right, right_nritems);
3937123abc88SChris Mason 	push_space = BTRFS_LEAF_DATA_SIZE(root);
39385f39d397SChris Mason 	for (i = 0; i < right_nritems; i++) {
3939dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
3940db94535dSChris Mason 
3941cfed81a0SChris Mason 		push_space = push_space - btrfs_token_item_size(right,
3942cfed81a0SChris Mason 								item, &token);
3943cfed81a0SChris Mason 		btrfs_set_token_item_offset(right, item, push_space, &token);
3944db94535dSChris Mason 	}
3945eb60ceacSChris Mason 
39465f39d397SChris Mason 	btrfs_mark_buffer_dirty(left);
394734a38218SChris Mason 	if (right_nritems)
39485f39d397SChris Mason 		btrfs_mark_buffer_dirty(right);
3949f0486c68SYan, Zheng 	else
3950f0486c68SYan, Zheng 		clean_tree_block(trans, root, right);
3951098f59c2SChris Mason 
39525f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
3953d6a0a126STsutomu Itoh 	fixup_low_keys(root, path, &disk_key, 1);
3954be0e5c09SChris Mason 
3955be0e5c09SChris Mason 	/* then fixup the leaf pointer in the path */
3956be0e5c09SChris Mason 	if (path->slots[0] < push_items) {
3957be0e5c09SChris Mason 		path->slots[0] += old_left_nritems;
3958925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
39595f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
39605f39d397SChris Mason 		path->nodes[0] = left;
3961be0e5c09SChris Mason 		path->slots[1] -= 1;
3962be0e5c09SChris Mason 	} else {
3963925baeddSChris Mason 		btrfs_tree_unlock(left);
39645f39d397SChris Mason 		free_extent_buffer(left);
3965be0e5c09SChris Mason 		path->slots[0] -= push_items;
3966be0e5c09SChris Mason 	}
3967eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
3968aa5d6bedSChris Mason 	return ret;
3969925baeddSChris Mason out:
3970925baeddSChris Mason 	btrfs_tree_unlock(left);
3971925baeddSChris Mason 	free_extent_buffer(left);
3972925baeddSChris Mason 	return ret;
3973be0e5c09SChris Mason }
3974be0e5c09SChris Mason 
397574123bd7SChris Mason /*
397644871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
397744871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
397899d8f83cSChris Mason  *
397999d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
398099d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us push all the
398199d8f83cSChris Mason  * items
398244871b1bSChris Mason  */
398344871b1bSChris Mason static int push_leaf_left(struct btrfs_trans_handle *trans, struct btrfs_root
398499d8f83cSChris Mason 			  *root, struct btrfs_path *path, int min_data_size,
398599d8f83cSChris Mason 			  int data_size, int empty, u32 max_slot)
398644871b1bSChris Mason {
398744871b1bSChris Mason 	struct extent_buffer *right = path->nodes[0];
398844871b1bSChris Mason 	struct extent_buffer *left;
398944871b1bSChris Mason 	int slot;
399044871b1bSChris Mason 	int free_space;
399144871b1bSChris Mason 	u32 right_nritems;
399244871b1bSChris Mason 	int ret = 0;
399344871b1bSChris Mason 
399444871b1bSChris Mason 	slot = path->slots[1];
399544871b1bSChris Mason 	if (slot == 0)
399644871b1bSChris Mason 		return 1;
399744871b1bSChris Mason 	if (!path->nodes[1])
399844871b1bSChris Mason 		return 1;
399944871b1bSChris Mason 
400044871b1bSChris Mason 	right_nritems = btrfs_header_nritems(right);
400144871b1bSChris Mason 	if (right_nritems == 0)
400244871b1bSChris Mason 		return 1;
400344871b1bSChris Mason 
400444871b1bSChris Mason 	btrfs_assert_tree_locked(path->nodes[1]);
400544871b1bSChris Mason 
400644871b1bSChris Mason 	left = read_node_slot(root, path->nodes[1], slot - 1);
400791ca338dSTsutomu Itoh 	if (left == NULL)
400891ca338dSTsutomu Itoh 		return 1;
400991ca338dSTsutomu Itoh 
401044871b1bSChris Mason 	btrfs_tree_lock(left);
401144871b1bSChris Mason 	btrfs_set_lock_blocking(left);
401244871b1bSChris Mason 
401344871b1bSChris Mason 	free_space = btrfs_leaf_free_space(root, left);
401444871b1bSChris Mason 	if (free_space < data_size) {
401544871b1bSChris Mason 		ret = 1;
401644871b1bSChris Mason 		goto out;
401744871b1bSChris Mason 	}
401844871b1bSChris Mason 
401944871b1bSChris Mason 	/* cow and double check */
402044871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, left,
402144871b1bSChris Mason 			      path->nodes[1], slot - 1, &left);
402244871b1bSChris Mason 	if (ret) {
402344871b1bSChris Mason 		/* we hit -ENOSPC, but it isn't fatal here */
402479787eaaSJeff Mahoney 		if (ret == -ENOSPC)
402544871b1bSChris Mason 			ret = 1;
402644871b1bSChris Mason 		goto out;
402744871b1bSChris Mason 	}
402844871b1bSChris Mason 
402944871b1bSChris Mason 	free_space = btrfs_leaf_free_space(root, left);
403044871b1bSChris Mason 	if (free_space < data_size) {
403144871b1bSChris Mason 		ret = 1;
403244871b1bSChris Mason 		goto out;
403344871b1bSChris Mason 	}
403444871b1bSChris Mason 
403599d8f83cSChris Mason 	return __push_leaf_left(trans, root, path, min_data_size,
403699d8f83cSChris Mason 			       empty, left, free_space, right_nritems,
403799d8f83cSChris Mason 			       max_slot);
403844871b1bSChris Mason out:
403944871b1bSChris Mason 	btrfs_tree_unlock(left);
404044871b1bSChris Mason 	free_extent_buffer(left);
404144871b1bSChris Mason 	return ret;
404244871b1bSChris Mason }
404344871b1bSChris Mason 
404444871b1bSChris Mason /*
404574123bd7SChris Mason  * split the path's leaf in two, making sure there is at least data_size
404674123bd7SChris Mason  * available for the resulting leaf level of the path.
404774123bd7SChris Mason  */
4048143bede5SJeff Mahoney static noinline void copy_for_split(struct btrfs_trans_handle *trans,
4049e02119d5SChris Mason 				    struct btrfs_root *root,
405044871b1bSChris Mason 				    struct btrfs_path *path,
405144871b1bSChris Mason 				    struct extent_buffer *l,
405244871b1bSChris Mason 				    struct extent_buffer *right,
405344871b1bSChris Mason 				    int slot, int mid, int nritems)
4054be0e5c09SChris Mason {
4055be0e5c09SChris Mason 	int data_copy_size;
4056be0e5c09SChris Mason 	int rt_data_off;
4057be0e5c09SChris Mason 	int i;
4058d4dbff95SChris Mason 	struct btrfs_disk_key disk_key;
4059cfed81a0SChris Mason 	struct btrfs_map_token token;
4060cfed81a0SChris Mason 
4061cfed81a0SChris Mason 	btrfs_init_map_token(&token);
4062be0e5c09SChris Mason 
40635f39d397SChris Mason 	nritems = nritems - mid;
40645f39d397SChris Mason 	btrfs_set_header_nritems(right, nritems);
40655f39d397SChris Mason 	data_copy_size = btrfs_item_end_nr(l, mid) - leaf_data_end(root, l);
40665f39d397SChris Mason 
40675f39d397SChris Mason 	copy_extent_buffer(right, l, btrfs_item_nr_offset(0),
40685f39d397SChris Mason 			   btrfs_item_nr_offset(mid),
40695f39d397SChris Mason 			   nritems * sizeof(struct btrfs_item));
40705f39d397SChris Mason 
40715f39d397SChris Mason 	copy_extent_buffer(right, l,
4072d6025579SChris Mason 		     btrfs_leaf_data(right) + BTRFS_LEAF_DATA_SIZE(root) -
4073123abc88SChris Mason 		     data_copy_size, btrfs_leaf_data(l) +
4074123abc88SChris Mason 		     leaf_data_end(root, l), data_copy_size);
407574123bd7SChris Mason 
40765f39d397SChris Mason 	rt_data_off = BTRFS_LEAF_DATA_SIZE(root) -
40775f39d397SChris Mason 		      btrfs_item_end_nr(l, mid);
40785f39d397SChris Mason 
40795f39d397SChris Mason 	for (i = 0; i < nritems; i++) {
4080dd3cc16bSRoss Kirk 		struct btrfs_item *item = btrfs_item_nr(i);
4081db94535dSChris Mason 		u32 ioff;
4082db94535dSChris Mason 
4083cfed81a0SChris Mason 		ioff = btrfs_token_item_offset(right, item, &token);
4084cfed81a0SChris Mason 		btrfs_set_token_item_offset(right, item,
4085cfed81a0SChris Mason 					    ioff + rt_data_off, &token);
40860783fcfcSChris Mason 	}
408774123bd7SChris Mason 
40885f39d397SChris Mason 	btrfs_set_header_nritems(l, mid);
40895f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
4090143bede5SJeff Mahoney 	insert_ptr(trans, root, path, &disk_key, right->start,
4091c3e06965SJan Schmidt 		   path->slots[1] + 1, 1);
40925f39d397SChris Mason 
40935f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
40945f39d397SChris Mason 	btrfs_mark_buffer_dirty(l);
4095eb60ceacSChris Mason 	BUG_ON(path->slots[0] != slot);
40965f39d397SChris Mason 
4097be0e5c09SChris Mason 	if (mid <= slot) {
4098925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
40995f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
41005f39d397SChris Mason 		path->nodes[0] = right;
4101be0e5c09SChris Mason 		path->slots[0] -= mid;
4102be0e5c09SChris Mason 		path->slots[1] += 1;
4103925baeddSChris Mason 	} else {
4104925baeddSChris Mason 		btrfs_tree_unlock(right);
41055f39d397SChris Mason 		free_extent_buffer(right);
4106925baeddSChris Mason 	}
41075f39d397SChris Mason 
4108eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
410944871b1bSChris Mason }
411044871b1bSChris Mason 
411144871b1bSChris Mason /*
411299d8f83cSChris Mason  * double splits happen when we need to insert a big item in the middle
411399d8f83cSChris Mason  * of a leaf.  A double split can leave us with 3 mostly empty leaves:
411499d8f83cSChris Mason  * leaf: [ slots 0 - N] [ our target ] [ N + 1 - total in leaf ]
411599d8f83cSChris Mason  *          A                 B                 C
411699d8f83cSChris Mason  *
411799d8f83cSChris Mason  * We avoid this by trying to push the items on either side of our target
411899d8f83cSChris Mason  * into the adjacent leaves.  If all goes well we can avoid the double split
411999d8f83cSChris Mason  * completely.
412099d8f83cSChris Mason  */
412199d8f83cSChris Mason static noinline int push_for_double_split(struct btrfs_trans_handle *trans,
412299d8f83cSChris Mason 					  struct btrfs_root *root,
412399d8f83cSChris Mason 					  struct btrfs_path *path,
412499d8f83cSChris Mason 					  int data_size)
412599d8f83cSChris Mason {
412699d8f83cSChris Mason 	int ret;
412799d8f83cSChris Mason 	int progress = 0;
412899d8f83cSChris Mason 	int slot;
412999d8f83cSChris Mason 	u32 nritems;
41305a4267caSFilipe David Borba Manana 	int space_needed = data_size;
413199d8f83cSChris Mason 
413299d8f83cSChris Mason 	slot = path->slots[0];
41335a4267caSFilipe David Borba Manana 	if (slot < btrfs_header_nritems(path->nodes[0]))
41345a4267caSFilipe David Borba Manana 		space_needed -= btrfs_leaf_free_space(root, path->nodes[0]);
413599d8f83cSChris Mason 
413699d8f83cSChris Mason 	/*
413799d8f83cSChris Mason 	 * try to push all the items after our slot into the
413899d8f83cSChris Mason 	 * right leaf
413999d8f83cSChris Mason 	 */
41405a4267caSFilipe David Borba Manana 	ret = push_leaf_right(trans, root, path, 1, space_needed, 0, slot);
414199d8f83cSChris Mason 	if (ret < 0)
414299d8f83cSChris Mason 		return ret;
414399d8f83cSChris Mason 
414499d8f83cSChris Mason 	if (ret == 0)
414599d8f83cSChris Mason 		progress++;
414699d8f83cSChris Mason 
414799d8f83cSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
414899d8f83cSChris Mason 	/*
414999d8f83cSChris Mason 	 * our goal is to get our slot at the start or end of a leaf.  If
415099d8f83cSChris Mason 	 * we've done so we're done
415199d8f83cSChris Mason 	 */
415299d8f83cSChris Mason 	if (path->slots[0] == 0 || path->slots[0] == nritems)
415399d8f83cSChris Mason 		return 0;
415499d8f83cSChris Mason 
415599d8f83cSChris Mason 	if (btrfs_leaf_free_space(root, path->nodes[0]) >= data_size)
415699d8f83cSChris Mason 		return 0;
415799d8f83cSChris Mason 
415899d8f83cSChris Mason 	/* try to push all the items before our slot into the next leaf */
415999d8f83cSChris Mason 	slot = path->slots[0];
41605a4267caSFilipe David Borba Manana 	ret = push_leaf_left(trans, root, path, 1, space_needed, 0, slot);
416199d8f83cSChris Mason 	if (ret < 0)
416299d8f83cSChris Mason 		return ret;
416399d8f83cSChris Mason 
416499d8f83cSChris Mason 	if (ret == 0)
416599d8f83cSChris Mason 		progress++;
416699d8f83cSChris Mason 
416799d8f83cSChris Mason 	if (progress)
416899d8f83cSChris Mason 		return 0;
416999d8f83cSChris Mason 	return 1;
417099d8f83cSChris Mason }
417199d8f83cSChris Mason 
417299d8f83cSChris Mason /*
417344871b1bSChris Mason  * split the path's leaf in two, making sure there is at least data_size
417444871b1bSChris Mason  * available for the resulting leaf level of the path.
417544871b1bSChris Mason  *
417644871b1bSChris Mason  * returns 0 if all went well and < 0 on failure.
417744871b1bSChris Mason  */
417844871b1bSChris Mason static noinline int split_leaf(struct btrfs_trans_handle *trans,
417944871b1bSChris Mason 			       struct btrfs_root *root,
418044871b1bSChris Mason 			       struct btrfs_key *ins_key,
418144871b1bSChris Mason 			       struct btrfs_path *path, int data_size,
418244871b1bSChris Mason 			       int extend)
418344871b1bSChris Mason {
41845d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
418544871b1bSChris Mason 	struct extent_buffer *l;
418644871b1bSChris Mason 	u32 nritems;
418744871b1bSChris Mason 	int mid;
418844871b1bSChris Mason 	int slot;
418944871b1bSChris Mason 	struct extent_buffer *right;
419044871b1bSChris Mason 	int ret = 0;
419144871b1bSChris Mason 	int wret;
41925d4f98a2SYan Zheng 	int split;
419344871b1bSChris Mason 	int num_doubles = 0;
419499d8f83cSChris Mason 	int tried_avoid_double = 0;
419544871b1bSChris Mason 
4196a5719521SYan, Zheng 	l = path->nodes[0];
4197a5719521SYan, Zheng 	slot = path->slots[0];
4198a5719521SYan, Zheng 	if (extend && data_size + btrfs_item_size_nr(l, slot) +
4199a5719521SYan, Zheng 	    sizeof(struct btrfs_item) > BTRFS_LEAF_DATA_SIZE(root))
4200a5719521SYan, Zheng 		return -EOVERFLOW;
4201a5719521SYan, Zheng 
420244871b1bSChris Mason 	/* first try to make some room by pushing left and right */
420333157e05SLiu Bo 	if (data_size && path->nodes[1]) {
42045a4267caSFilipe David Borba Manana 		int space_needed = data_size;
42055a4267caSFilipe David Borba Manana 
42065a4267caSFilipe David Borba Manana 		if (slot < btrfs_header_nritems(l))
42075a4267caSFilipe David Borba Manana 			space_needed -= btrfs_leaf_free_space(root, l);
42085a4267caSFilipe David Borba Manana 
42095a4267caSFilipe David Borba Manana 		wret = push_leaf_right(trans, root, path, space_needed,
42105a4267caSFilipe David Borba Manana 				       space_needed, 0, 0);
421144871b1bSChris Mason 		if (wret < 0)
421244871b1bSChris Mason 			return wret;
421344871b1bSChris Mason 		if (wret) {
42145a4267caSFilipe David Borba Manana 			wret = push_leaf_left(trans, root, path, space_needed,
42155a4267caSFilipe David Borba Manana 					      space_needed, 0, (u32)-1);
421644871b1bSChris Mason 			if (wret < 0)
421744871b1bSChris Mason 				return wret;
421844871b1bSChris Mason 		}
421944871b1bSChris Mason 		l = path->nodes[0];
422044871b1bSChris Mason 
422144871b1bSChris Mason 		/* did the pushes work? */
422244871b1bSChris Mason 		if (btrfs_leaf_free_space(root, l) >= data_size)
422344871b1bSChris Mason 			return 0;
422444871b1bSChris Mason 	}
422544871b1bSChris Mason 
422644871b1bSChris Mason 	if (!path->nodes[1]) {
4227fdd99c72SLiu Bo 		ret = insert_new_root(trans, root, path, 1);
422844871b1bSChris Mason 		if (ret)
422944871b1bSChris Mason 			return ret;
423044871b1bSChris Mason 	}
423144871b1bSChris Mason again:
42325d4f98a2SYan Zheng 	split = 1;
423344871b1bSChris Mason 	l = path->nodes[0];
423444871b1bSChris Mason 	slot = path->slots[0];
423544871b1bSChris Mason 	nritems = btrfs_header_nritems(l);
423644871b1bSChris Mason 	mid = (nritems + 1) / 2;
423744871b1bSChris Mason 
42385d4f98a2SYan Zheng 	if (mid <= slot) {
42395d4f98a2SYan Zheng 		if (nritems == 1 ||
42405d4f98a2SYan Zheng 		    leaf_space_used(l, mid, nritems - mid) + data_size >
42415d4f98a2SYan Zheng 			BTRFS_LEAF_DATA_SIZE(root)) {
42425d4f98a2SYan Zheng 			if (slot >= nritems) {
42435d4f98a2SYan Zheng 				split = 0;
42445d4f98a2SYan Zheng 			} else {
42455d4f98a2SYan Zheng 				mid = slot;
42465d4f98a2SYan Zheng 				if (mid != nritems &&
42475d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
42485d4f98a2SYan Zheng 				    data_size > BTRFS_LEAF_DATA_SIZE(root)) {
424999d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
425099d8f83cSChris Mason 						goto push_for_double;
42515d4f98a2SYan Zheng 					split = 2;
42525d4f98a2SYan Zheng 				}
42535d4f98a2SYan Zheng 			}
42545d4f98a2SYan Zheng 		}
42555d4f98a2SYan Zheng 	} else {
42565d4f98a2SYan Zheng 		if (leaf_space_used(l, 0, mid) + data_size >
42575d4f98a2SYan Zheng 			BTRFS_LEAF_DATA_SIZE(root)) {
42585d4f98a2SYan Zheng 			if (!extend && data_size && slot == 0) {
42595d4f98a2SYan Zheng 				split = 0;
42605d4f98a2SYan Zheng 			} else if ((extend || !data_size) && slot == 0) {
42615d4f98a2SYan Zheng 				mid = 1;
42625d4f98a2SYan Zheng 			} else {
42635d4f98a2SYan Zheng 				mid = slot;
42645d4f98a2SYan Zheng 				if (mid != nritems &&
42655d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
42665d4f98a2SYan Zheng 				    data_size > BTRFS_LEAF_DATA_SIZE(root)) {
426799d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
426899d8f83cSChris Mason 						goto push_for_double;
42695d4f98a2SYan Zheng 					split = 2;
42705d4f98a2SYan Zheng 				}
42715d4f98a2SYan Zheng 			}
42725d4f98a2SYan Zheng 		}
42735d4f98a2SYan Zheng 	}
42745d4f98a2SYan Zheng 
42755d4f98a2SYan Zheng 	if (split == 0)
42765d4f98a2SYan Zheng 		btrfs_cpu_key_to_disk(&disk_key, ins_key);
42775d4f98a2SYan Zheng 	else
42785d4f98a2SYan Zheng 		btrfs_item_key(l, &disk_key, mid);
42795d4f98a2SYan Zheng 
4280707e8a07SDavid Sterba 	right = btrfs_alloc_free_block(trans, root, root->nodesize, 0,
428144871b1bSChris Mason 					root->root_key.objectid,
42825581a51aSJan Schmidt 					&disk_key, 0, l->start, 0);
4283f0486c68SYan, Zheng 	if (IS_ERR(right))
428444871b1bSChris Mason 		return PTR_ERR(right);
4285f0486c68SYan, Zheng 
4286707e8a07SDavid Sterba 	root_add_used(root, root->nodesize);
428744871b1bSChris Mason 
428844871b1bSChris Mason 	memset_extent_buffer(right, 0, 0, sizeof(struct btrfs_header));
428944871b1bSChris Mason 	btrfs_set_header_bytenr(right, right->start);
429044871b1bSChris Mason 	btrfs_set_header_generation(right, trans->transid);
42915d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(right, BTRFS_MIXED_BACKREF_REV);
429244871b1bSChris Mason 	btrfs_set_header_owner(right, root->root_key.objectid);
429344871b1bSChris Mason 	btrfs_set_header_level(right, 0);
429444871b1bSChris Mason 	write_extent_buffer(right, root->fs_info->fsid,
42950a4e5586SRoss Kirk 			    btrfs_header_fsid(), BTRFS_FSID_SIZE);
429644871b1bSChris Mason 
429744871b1bSChris Mason 	write_extent_buffer(right, root->fs_info->chunk_tree_uuid,
4298b308bc2fSGeert Uytterhoeven 			    btrfs_header_chunk_tree_uuid(right),
429944871b1bSChris Mason 			    BTRFS_UUID_SIZE);
430044871b1bSChris Mason 
43015d4f98a2SYan Zheng 	if (split == 0) {
430244871b1bSChris Mason 		if (mid <= slot) {
430344871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
4304143bede5SJeff Mahoney 			insert_ptr(trans, root, path, &disk_key, right->start,
4305c3e06965SJan Schmidt 				   path->slots[1] + 1, 1);
430644871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
430744871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
430844871b1bSChris Mason 			path->nodes[0] = right;
430944871b1bSChris Mason 			path->slots[0] = 0;
431044871b1bSChris Mason 			path->slots[1] += 1;
431144871b1bSChris Mason 		} else {
431244871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
4313143bede5SJeff Mahoney 			insert_ptr(trans, root, path, &disk_key, right->start,
4314c3e06965SJan Schmidt 					  path->slots[1], 1);
431544871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
431644871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
431744871b1bSChris Mason 			path->nodes[0] = right;
431844871b1bSChris Mason 			path->slots[0] = 0;
4319143bede5SJeff Mahoney 			if (path->slots[1] == 0)
4320d6a0a126STsutomu Itoh 				fixup_low_keys(root, path, &disk_key, 1);
43215d4f98a2SYan Zheng 		}
432244871b1bSChris Mason 		btrfs_mark_buffer_dirty(right);
432344871b1bSChris Mason 		return ret;
432444871b1bSChris Mason 	}
432544871b1bSChris Mason 
4326143bede5SJeff Mahoney 	copy_for_split(trans, root, path, l, right, slot, mid, nritems);
432744871b1bSChris Mason 
43285d4f98a2SYan Zheng 	if (split == 2) {
4329cc0c5538SChris Mason 		BUG_ON(num_doubles != 0);
4330cc0c5538SChris Mason 		num_doubles++;
4331cc0c5538SChris Mason 		goto again;
43323326d1b0SChris Mason 	}
433344871b1bSChris Mason 
4334143bede5SJeff Mahoney 	return 0;
433599d8f83cSChris Mason 
433699d8f83cSChris Mason push_for_double:
433799d8f83cSChris Mason 	push_for_double_split(trans, root, path, data_size);
433899d8f83cSChris Mason 	tried_avoid_double = 1;
433999d8f83cSChris Mason 	if (btrfs_leaf_free_space(root, path->nodes[0]) >= data_size)
434099d8f83cSChris Mason 		return 0;
434199d8f83cSChris Mason 	goto again;
4342be0e5c09SChris Mason }
4343be0e5c09SChris Mason 
4344ad48fd75SYan, Zheng static noinline int setup_leaf_for_split(struct btrfs_trans_handle *trans,
4345ad48fd75SYan, Zheng 					 struct btrfs_root *root,
4346ad48fd75SYan, Zheng 					 struct btrfs_path *path, int ins_len)
4347ad48fd75SYan, Zheng {
4348ad48fd75SYan, Zheng 	struct btrfs_key key;
4349ad48fd75SYan, Zheng 	struct extent_buffer *leaf;
4350ad48fd75SYan, Zheng 	struct btrfs_file_extent_item *fi;
4351ad48fd75SYan, Zheng 	u64 extent_len = 0;
4352ad48fd75SYan, Zheng 	u32 item_size;
4353ad48fd75SYan, Zheng 	int ret;
4354ad48fd75SYan, Zheng 
4355ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4356ad48fd75SYan, Zheng 	btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4357ad48fd75SYan, Zheng 
4358ad48fd75SYan, Zheng 	BUG_ON(key.type != BTRFS_EXTENT_DATA_KEY &&
4359ad48fd75SYan, Zheng 	       key.type != BTRFS_EXTENT_CSUM_KEY);
4360ad48fd75SYan, Zheng 
4361ad48fd75SYan, Zheng 	if (btrfs_leaf_free_space(root, leaf) >= ins_len)
4362ad48fd75SYan, Zheng 		return 0;
4363ad48fd75SYan, Zheng 
4364ad48fd75SYan, Zheng 	item_size = btrfs_item_size_nr(leaf, path->slots[0]);
4365ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
4366ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
4367ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
4368ad48fd75SYan, Zheng 		extent_len = btrfs_file_extent_num_bytes(leaf, fi);
4369ad48fd75SYan, Zheng 	}
4370b3b4aa74SDavid Sterba 	btrfs_release_path(path);
4371ad48fd75SYan, Zheng 
4372ad48fd75SYan, Zheng 	path->keep_locks = 1;
4373ad48fd75SYan, Zheng 	path->search_for_split = 1;
4374ad48fd75SYan, Zheng 	ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
4375ad48fd75SYan, Zheng 	path->search_for_split = 0;
4376ad48fd75SYan, Zheng 	if (ret < 0)
4377ad48fd75SYan, Zheng 		goto err;
4378ad48fd75SYan, Zheng 
4379ad48fd75SYan, Zheng 	ret = -EAGAIN;
4380ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4381ad48fd75SYan, Zheng 	/* if our item isn't there or got smaller, return now */
4382ad48fd75SYan, Zheng 	if (ret > 0 || item_size != btrfs_item_size_nr(leaf, path->slots[0]))
4383ad48fd75SYan, Zheng 		goto err;
4384ad48fd75SYan, Zheng 
4385109f6aefSChris Mason 	/* the leaf has  changed, it now has room.  return now */
4386109f6aefSChris Mason 	if (btrfs_leaf_free_space(root, path->nodes[0]) >= ins_len)
4387109f6aefSChris Mason 		goto err;
4388109f6aefSChris Mason 
4389ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
4390ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
4391ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
4392ad48fd75SYan, Zheng 		if (extent_len != btrfs_file_extent_num_bytes(leaf, fi))
4393ad48fd75SYan, Zheng 			goto err;
4394ad48fd75SYan, Zheng 	}
4395ad48fd75SYan, Zheng 
4396ad48fd75SYan, Zheng 	btrfs_set_path_blocking(path);
4397ad48fd75SYan, Zheng 	ret = split_leaf(trans, root, &key, path, ins_len, 1);
4398f0486c68SYan, Zheng 	if (ret)
4399f0486c68SYan, Zheng 		goto err;
4400ad48fd75SYan, Zheng 
4401ad48fd75SYan, Zheng 	path->keep_locks = 0;
4402ad48fd75SYan, Zheng 	btrfs_unlock_up_safe(path, 1);
4403ad48fd75SYan, Zheng 	return 0;
4404ad48fd75SYan, Zheng err:
4405ad48fd75SYan, Zheng 	path->keep_locks = 0;
4406ad48fd75SYan, Zheng 	return ret;
4407ad48fd75SYan, Zheng }
4408ad48fd75SYan, Zheng 
4409ad48fd75SYan, Zheng static noinline int split_item(struct btrfs_trans_handle *trans,
4410459931ecSChris Mason 			       struct btrfs_root *root,
4411459931ecSChris Mason 			       struct btrfs_path *path,
4412459931ecSChris Mason 			       struct btrfs_key *new_key,
4413459931ecSChris Mason 			       unsigned long split_offset)
4414459931ecSChris Mason {
4415459931ecSChris Mason 	struct extent_buffer *leaf;
4416459931ecSChris Mason 	struct btrfs_item *item;
4417459931ecSChris Mason 	struct btrfs_item *new_item;
4418459931ecSChris Mason 	int slot;
4419ad48fd75SYan, Zheng 	char *buf;
4420459931ecSChris Mason 	u32 nritems;
4421ad48fd75SYan, Zheng 	u32 item_size;
4422459931ecSChris Mason 	u32 orig_offset;
4423459931ecSChris Mason 	struct btrfs_disk_key disk_key;
4424459931ecSChris Mason 
4425459931ecSChris Mason 	leaf = path->nodes[0];
4426b9473439SChris Mason 	BUG_ON(btrfs_leaf_free_space(root, leaf) < sizeof(struct btrfs_item));
4427b9473439SChris Mason 
4428b4ce94deSChris Mason 	btrfs_set_path_blocking(path);
4429b4ce94deSChris Mason 
4430dd3cc16bSRoss Kirk 	item = btrfs_item_nr(path->slots[0]);
4431459931ecSChris Mason 	orig_offset = btrfs_item_offset(leaf, item);
4432459931ecSChris Mason 	item_size = btrfs_item_size(leaf, item);
4433459931ecSChris Mason 
4434459931ecSChris Mason 	buf = kmalloc(item_size, GFP_NOFS);
4435ad48fd75SYan, Zheng 	if (!buf)
4436ad48fd75SYan, Zheng 		return -ENOMEM;
4437ad48fd75SYan, Zheng 
4438459931ecSChris Mason 	read_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf,
4439459931ecSChris Mason 			    path->slots[0]), item_size);
4440ad48fd75SYan, Zheng 
4441459931ecSChris Mason 	slot = path->slots[0] + 1;
4442459931ecSChris Mason 	nritems = btrfs_header_nritems(leaf);
4443459931ecSChris Mason 	if (slot != nritems) {
4444459931ecSChris Mason 		/* shift the items */
4445459931ecSChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + 1),
4446459931ecSChris Mason 				btrfs_item_nr_offset(slot),
4447459931ecSChris Mason 				(nritems - slot) * sizeof(struct btrfs_item));
4448459931ecSChris Mason 	}
4449459931ecSChris Mason 
4450459931ecSChris Mason 	btrfs_cpu_key_to_disk(&disk_key, new_key);
4451459931ecSChris Mason 	btrfs_set_item_key(leaf, &disk_key, slot);
4452459931ecSChris Mason 
4453dd3cc16bSRoss Kirk 	new_item = btrfs_item_nr(slot);
4454459931ecSChris Mason 
4455459931ecSChris Mason 	btrfs_set_item_offset(leaf, new_item, orig_offset);
4456459931ecSChris Mason 	btrfs_set_item_size(leaf, new_item, item_size - split_offset);
4457459931ecSChris Mason 
4458459931ecSChris Mason 	btrfs_set_item_offset(leaf, item,
4459459931ecSChris Mason 			      orig_offset + item_size - split_offset);
4460459931ecSChris Mason 	btrfs_set_item_size(leaf, item, split_offset);
4461459931ecSChris Mason 
4462459931ecSChris Mason 	btrfs_set_header_nritems(leaf, nritems + 1);
4463459931ecSChris Mason 
4464459931ecSChris Mason 	/* write the data for the start of the original item */
4465459931ecSChris Mason 	write_extent_buffer(leaf, buf,
4466459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, path->slots[0]),
4467459931ecSChris Mason 			    split_offset);
4468459931ecSChris Mason 
4469459931ecSChris Mason 	/* write the data for the new item */
4470459931ecSChris Mason 	write_extent_buffer(leaf, buf + split_offset,
4471459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, slot),
4472459931ecSChris Mason 			    item_size - split_offset);
4473459931ecSChris Mason 	btrfs_mark_buffer_dirty(leaf);
4474459931ecSChris Mason 
4475ad48fd75SYan, Zheng 	BUG_ON(btrfs_leaf_free_space(root, leaf) < 0);
4476459931ecSChris Mason 	kfree(buf);
4477ad48fd75SYan, Zheng 	return 0;
4478ad48fd75SYan, Zheng }
4479ad48fd75SYan, Zheng 
4480ad48fd75SYan, Zheng /*
4481ad48fd75SYan, Zheng  * This function splits a single item into two items,
4482ad48fd75SYan, Zheng  * giving 'new_key' to the new item and splitting the
4483ad48fd75SYan, Zheng  * old one at split_offset (from the start of the item).
4484ad48fd75SYan, Zheng  *
4485ad48fd75SYan, Zheng  * The path may be released by this operation.  After
4486ad48fd75SYan, Zheng  * the split, the path is pointing to the old item.  The
4487ad48fd75SYan, Zheng  * new item is going to be in the same node as the old one.
4488ad48fd75SYan, Zheng  *
4489ad48fd75SYan, Zheng  * Note, the item being split must be smaller enough to live alone on
4490ad48fd75SYan, Zheng  * a tree block with room for one extra struct btrfs_item
4491ad48fd75SYan, Zheng  *
4492ad48fd75SYan, Zheng  * This allows us to split the item in place, keeping a lock on the
4493ad48fd75SYan, Zheng  * leaf the entire time.
4494ad48fd75SYan, Zheng  */
4495ad48fd75SYan, Zheng int btrfs_split_item(struct btrfs_trans_handle *trans,
4496ad48fd75SYan, Zheng 		     struct btrfs_root *root,
4497ad48fd75SYan, Zheng 		     struct btrfs_path *path,
4498ad48fd75SYan, Zheng 		     struct btrfs_key *new_key,
4499ad48fd75SYan, Zheng 		     unsigned long split_offset)
4500ad48fd75SYan, Zheng {
4501ad48fd75SYan, Zheng 	int ret;
4502ad48fd75SYan, Zheng 	ret = setup_leaf_for_split(trans, root, path,
4503ad48fd75SYan, Zheng 				   sizeof(struct btrfs_item));
4504ad48fd75SYan, Zheng 	if (ret)
4505459931ecSChris Mason 		return ret;
4506ad48fd75SYan, Zheng 
4507ad48fd75SYan, Zheng 	ret = split_item(trans, root, path, new_key, split_offset);
4508ad48fd75SYan, Zheng 	return ret;
4509ad48fd75SYan, Zheng }
4510ad48fd75SYan, Zheng 
4511ad48fd75SYan, Zheng /*
4512ad48fd75SYan, Zheng  * This function duplicate a item, giving 'new_key' to the new item.
4513ad48fd75SYan, Zheng  * It guarantees both items live in the same tree leaf and the new item
4514ad48fd75SYan, Zheng  * is contiguous with the original item.
4515ad48fd75SYan, Zheng  *
4516ad48fd75SYan, Zheng  * This allows us to split file extent in place, keeping a lock on the
4517ad48fd75SYan, Zheng  * leaf the entire time.
4518ad48fd75SYan, Zheng  */
4519ad48fd75SYan, Zheng int btrfs_duplicate_item(struct btrfs_trans_handle *trans,
4520ad48fd75SYan, Zheng 			 struct btrfs_root *root,
4521ad48fd75SYan, Zheng 			 struct btrfs_path *path,
4522ad48fd75SYan, Zheng 			 struct btrfs_key *new_key)
4523ad48fd75SYan, Zheng {
4524ad48fd75SYan, Zheng 	struct extent_buffer *leaf;
4525ad48fd75SYan, Zheng 	int ret;
4526ad48fd75SYan, Zheng 	u32 item_size;
4527ad48fd75SYan, Zheng 
4528ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4529ad48fd75SYan, Zheng 	item_size = btrfs_item_size_nr(leaf, path->slots[0]);
4530ad48fd75SYan, Zheng 	ret = setup_leaf_for_split(trans, root, path,
4531ad48fd75SYan, Zheng 				   item_size + sizeof(struct btrfs_item));
4532ad48fd75SYan, Zheng 	if (ret)
4533ad48fd75SYan, Zheng 		return ret;
4534ad48fd75SYan, Zheng 
4535ad48fd75SYan, Zheng 	path->slots[0]++;
4536afe5fea7STsutomu Itoh 	setup_items_for_insert(root, path, new_key, &item_size,
4537ad48fd75SYan, Zheng 			       item_size, item_size +
4538ad48fd75SYan, Zheng 			       sizeof(struct btrfs_item), 1);
4539ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4540ad48fd75SYan, Zheng 	memcpy_extent_buffer(leaf,
4541ad48fd75SYan, Zheng 			     btrfs_item_ptr_offset(leaf, path->slots[0]),
4542ad48fd75SYan, Zheng 			     btrfs_item_ptr_offset(leaf, path->slots[0] - 1),
4543ad48fd75SYan, Zheng 			     item_size);
4544ad48fd75SYan, Zheng 	return 0;
4545459931ecSChris Mason }
4546459931ecSChris Mason 
4547459931ecSChris Mason /*
4548d352ac68SChris Mason  * make the item pointed to by the path smaller.  new_size indicates
4549d352ac68SChris Mason  * how small to make it, and from_end tells us if we just chop bytes
4550d352ac68SChris Mason  * off the end of the item or if we shift the item to chop bytes off
4551d352ac68SChris Mason  * the front.
4552d352ac68SChris Mason  */
4553afe5fea7STsutomu Itoh void btrfs_truncate_item(struct btrfs_root *root, struct btrfs_path *path,
4554179e29e4SChris Mason 			 u32 new_size, int from_end)
4555b18c6685SChris Mason {
4556b18c6685SChris Mason 	int slot;
45575f39d397SChris Mason 	struct extent_buffer *leaf;
45585f39d397SChris Mason 	struct btrfs_item *item;
4559b18c6685SChris Mason 	u32 nritems;
4560b18c6685SChris Mason 	unsigned int data_end;
4561b18c6685SChris Mason 	unsigned int old_data_start;
4562b18c6685SChris Mason 	unsigned int old_size;
4563b18c6685SChris Mason 	unsigned int size_diff;
4564b18c6685SChris Mason 	int i;
4565cfed81a0SChris Mason 	struct btrfs_map_token token;
4566cfed81a0SChris Mason 
4567cfed81a0SChris Mason 	btrfs_init_map_token(&token);
4568b18c6685SChris Mason 
45695f39d397SChris Mason 	leaf = path->nodes[0];
4570179e29e4SChris Mason 	slot = path->slots[0];
4571179e29e4SChris Mason 
4572179e29e4SChris Mason 	old_size = btrfs_item_size_nr(leaf, slot);
4573179e29e4SChris Mason 	if (old_size == new_size)
4574143bede5SJeff Mahoney 		return;
4575b18c6685SChris Mason 
45765f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
4577b18c6685SChris Mason 	data_end = leaf_data_end(root, leaf);
4578b18c6685SChris Mason 
45795f39d397SChris Mason 	old_data_start = btrfs_item_offset_nr(leaf, slot);
4580179e29e4SChris Mason 
4581b18c6685SChris Mason 	size_diff = old_size - new_size;
4582b18c6685SChris Mason 
4583b18c6685SChris Mason 	BUG_ON(slot < 0);
4584b18c6685SChris Mason 	BUG_ON(slot >= nritems);
4585b18c6685SChris Mason 
4586b18c6685SChris Mason 	/*
4587b18c6685SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4588b18c6685SChris Mason 	 */
4589b18c6685SChris Mason 	/* first correct the data pointers */
4590b18c6685SChris Mason 	for (i = slot; i < nritems; i++) {
45915f39d397SChris Mason 		u32 ioff;
4592dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
4593db94535dSChris Mason 
4594cfed81a0SChris Mason 		ioff = btrfs_token_item_offset(leaf, item, &token);
4595cfed81a0SChris Mason 		btrfs_set_token_item_offset(leaf, item,
4596cfed81a0SChris Mason 					    ioff + size_diff, &token);
4597b18c6685SChris Mason 	}
4598db94535dSChris Mason 
4599b18c6685SChris Mason 	/* shift the data */
4600179e29e4SChris Mason 	if (from_end) {
46015f39d397SChris Mason 		memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
4602b18c6685SChris Mason 			      data_end + size_diff, btrfs_leaf_data(leaf) +
4603b18c6685SChris Mason 			      data_end, old_data_start + new_size - data_end);
4604179e29e4SChris Mason 	} else {
4605179e29e4SChris Mason 		struct btrfs_disk_key disk_key;
4606179e29e4SChris Mason 		u64 offset;
4607179e29e4SChris Mason 
4608179e29e4SChris Mason 		btrfs_item_key(leaf, &disk_key, slot);
4609179e29e4SChris Mason 
4610179e29e4SChris Mason 		if (btrfs_disk_key_type(&disk_key) == BTRFS_EXTENT_DATA_KEY) {
4611179e29e4SChris Mason 			unsigned long ptr;
4612179e29e4SChris Mason 			struct btrfs_file_extent_item *fi;
4613179e29e4SChris Mason 
4614179e29e4SChris Mason 			fi = btrfs_item_ptr(leaf, slot,
4615179e29e4SChris Mason 					    struct btrfs_file_extent_item);
4616179e29e4SChris Mason 			fi = (struct btrfs_file_extent_item *)(
4617179e29e4SChris Mason 			     (unsigned long)fi - size_diff);
4618179e29e4SChris Mason 
4619179e29e4SChris Mason 			if (btrfs_file_extent_type(leaf, fi) ==
4620179e29e4SChris Mason 			    BTRFS_FILE_EXTENT_INLINE) {
4621179e29e4SChris Mason 				ptr = btrfs_item_ptr_offset(leaf, slot);
4622179e29e4SChris Mason 				memmove_extent_buffer(leaf, ptr,
4623179e29e4SChris Mason 				      (unsigned long)fi,
4624179e29e4SChris Mason 				      offsetof(struct btrfs_file_extent_item,
4625179e29e4SChris Mason 						 disk_bytenr));
4626179e29e4SChris Mason 			}
4627179e29e4SChris Mason 		}
4628179e29e4SChris Mason 
4629179e29e4SChris Mason 		memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
4630179e29e4SChris Mason 			      data_end + size_diff, btrfs_leaf_data(leaf) +
4631179e29e4SChris Mason 			      data_end, old_data_start - data_end);
4632179e29e4SChris Mason 
4633179e29e4SChris Mason 		offset = btrfs_disk_key_offset(&disk_key);
4634179e29e4SChris Mason 		btrfs_set_disk_key_offset(&disk_key, offset + size_diff);
4635179e29e4SChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot);
4636179e29e4SChris Mason 		if (slot == 0)
4637d6a0a126STsutomu Itoh 			fixup_low_keys(root, path, &disk_key, 1);
4638179e29e4SChris Mason 	}
46395f39d397SChris Mason 
4640dd3cc16bSRoss Kirk 	item = btrfs_item_nr(slot);
46415f39d397SChris Mason 	btrfs_set_item_size(leaf, item, new_size);
46425f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
4643b18c6685SChris Mason 
46445f39d397SChris Mason 	if (btrfs_leaf_free_space(root, leaf) < 0) {
46455f39d397SChris Mason 		btrfs_print_leaf(root, leaf);
4646b18c6685SChris Mason 		BUG();
46475f39d397SChris Mason 	}
4648b18c6685SChris Mason }
4649b18c6685SChris Mason 
4650d352ac68SChris Mason /*
46518f69dbd2SStefan Behrens  * make the item pointed to by the path bigger, data_size is the added size.
4652d352ac68SChris Mason  */
46534b90c680STsutomu Itoh void btrfs_extend_item(struct btrfs_root *root, struct btrfs_path *path,
46545f39d397SChris Mason 		       u32 data_size)
46556567e837SChris Mason {
46566567e837SChris Mason 	int slot;
46575f39d397SChris Mason 	struct extent_buffer *leaf;
46585f39d397SChris Mason 	struct btrfs_item *item;
46596567e837SChris Mason 	u32 nritems;
46606567e837SChris Mason 	unsigned int data_end;
46616567e837SChris Mason 	unsigned int old_data;
46626567e837SChris Mason 	unsigned int old_size;
46636567e837SChris Mason 	int i;
4664cfed81a0SChris Mason 	struct btrfs_map_token token;
4665cfed81a0SChris Mason 
4666cfed81a0SChris Mason 	btrfs_init_map_token(&token);
46676567e837SChris Mason 
46685f39d397SChris Mason 	leaf = path->nodes[0];
46696567e837SChris Mason 
46705f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
46716567e837SChris Mason 	data_end = leaf_data_end(root, leaf);
46726567e837SChris Mason 
46735f39d397SChris Mason 	if (btrfs_leaf_free_space(root, leaf) < data_size) {
46745f39d397SChris Mason 		btrfs_print_leaf(root, leaf);
46756567e837SChris Mason 		BUG();
46765f39d397SChris Mason 	}
46776567e837SChris Mason 	slot = path->slots[0];
46785f39d397SChris Mason 	old_data = btrfs_item_end_nr(leaf, slot);
46796567e837SChris Mason 
46806567e837SChris Mason 	BUG_ON(slot < 0);
46813326d1b0SChris Mason 	if (slot >= nritems) {
46823326d1b0SChris Mason 		btrfs_print_leaf(root, leaf);
4683efe120a0SFrank Holton 		btrfs_crit(root->fs_info, "slot %d too large, nritems %d",
4684d397712bSChris Mason 		       slot, nritems);
46853326d1b0SChris Mason 		BUG_ON(1);
46863326d1b0SChris Mason 	}
46876567e837SChris Mason 
46886567e837SChris Mason 	/*
46896567e837SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
46906567e837SChris Mason 	 */
46916567e837SChris Mason 	/* first correct the data pointers */
46926567e837SChris Mason 	for (i = slot; i < nritems; i++) {
46935f39d397SChris Mason 		u32 ioff;
4694dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
4695db94535dSChris Mason 
4696cfed81a0SChris Mason 		ioff = btrfs_token_item_offset(leaf, item, &token);
4697cfed81a0SChris Mason 		btrfs_set_token_item_offset(leaf, item,
4698cfed81a0SChris Mason 					    ioff - data_size, &token);
46996567e837SChris Mason 	}
47005f39d397SChris Mason 
47016567e837SChris Mason 	/* shift the data */
47025f39d397SChris Mason 	memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
47036567e837SChris Mason 		      data_end - data_size, btrfs_leaf_data(leaf) +
47046567e837SChris Mason 		      data_end, old_data - data_end);
47055f39d397SChris Mason 
47066567e837SChris Mason 	data_end = old_data;
47075f39d397SChris Mason 	old_size = btrfs_item_size_nr(leaf, slot);
4708dd3cc16bSRoss Kirk 	item = btrfs_item_nr(slot);
47095f39d397SChris Mason 	btrfs_set_item_size(leaf, item, old_size + data_size);
47105f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
47116567e837SChris Mason 
47125f39d397SChris Mason 	if (btrfs_leaf_free_space(root, leaf) < 0) {
47135f39d397SChris Mason 		btrfs_print_leaf(root, leaf);
47146567e837SChris Mason 		BUG();
47155f39d397SChris Mason 	}
47166567e837SChris Mason }
47176567e837SChris Mason 
471874123bd7SChris Mason /*
471944871b1bSChris Mason  * this is a helper for btrfs_insert_empty_items, the main goal here is
472044871b1bSChris Mason  * to save stack depth by doing the bulk of the work in a function
472144871b1bSChris Mason  * that doesn't call btrfs_search_slot
472274123bd7SChris Mason  */
4723afe5fea7STsutomu Itoh void setup_items_for_insert(struct btrfs_root *root, struct btrfs_path *path,
47249c58309dSChris Mason 			    struct btrfs_key *cpu_key, u32 *data_size,
472544871b1bSChris Mason 			    u32 total_data, u32 total_size, int nr)
4726be0e5c09SChris Mason {
47275f39d397SChris Mason 	struct btrfs_item *item;
47289c58309dSChris Mason 	int i;
47297518a238SChris Mason 	u32 nritems;
4730be0e5c09SChris Mason 	unsigned int data_end;
4731e2fa7227SChris Mason 	struct btrfs_disk_key disk_key;
473244871b1bSChris Mason 	struct extent_buffer *leaf;
473344871b1bSChris Mason 	int slot;
4734cfed81a0SChris Mason 	struct btrfs_map_token token;
4735cfed81a0SChris Mason 
473624cdc847SFilipe Manana 	if (path->slots[0] == 0) {
473724cdc847SFilipe Manana 		btrfs_cpu_key_to_disk(&disk_key, cpu_key);
473824cdc847SFilipe Manana 		fixup_low_keys(root, path, &disk_key, 1);
473924cdc847SFilipe Manana 	}
474024cdc847SFilipe Manana 	btrfs_unlock_up_safe(path, 1);
474124cdc847SFilipe Manana 
4742cfed81a0SChris Mason 	btrfs_init_map_token(&token);
4743e2fa7227SChris Mason 
47445f39d397SChris Mason 	leaf = path->nodes[0];
474544871b1bSChris Mason 	slot = path->slots[0];
474674123bd7SChris Mason 
47475f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
4748123abc88SChris Mason 	data_end = leaf_data_end(root, leaf);
4749eb60ceacSChris Mason 
4750f25956ccSChris Mason 	if (btrfs_leaf_free_space(root, leaf) < total_size) {
47513326d1b0SChris Mason 		btrfs_print_leaf(root, leaf);
4752efe120a0SFrank Holton 		btrfs_crit(root->fs_info, "not enough freespace need %u have %d",
47539c58309dSChris Mason 		       total_size, btrfs_leaf_free_space(root, leaf));
4754be0e5c09SChris Mason 		BUG();
4755d4dbff95SChris Mason 	}
47565f39d397SChris Mason 
4757be0e5c09SChris Mason 	if (slot != nritems) {
47585f39d397SChris Mason 		unsigned int old_data = btrfs_item_end_nr(leaf, slot);
4759be0e5c09SChris Mason 
47605f39d397SChris Mason 		if (old_data < data_end) {
47615f39d397SChris Mason 			btrfs_print_leaf(root, leaf);
4762efe120a0SFrank Holton 			btrfs_crit(root->fs_info, "slot %d old_data %d data_end %d",
47635f39d397SChris Mason 			       slot, old_data, data_end);
47645f39d397SChris Mason 			BUG_ON(1);
47655f39d397SChris Mason 		}
4766be0e5c09SChris Mason 		/*
4767be0e5c09SChris Mason 		 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4768be0e5c09SChris Mason 		 */
4769be0e5c09SChris Mason 		/* first correct the data pointers */
47700783fcfcSChris Mason 		for (i = slot; i < nritems; i++) {
47715f39d397SChris Mason 			u32 ioff;
4772db94535dSChris Mason 
4773dd3cc16bSRoss Kirk 			item = btrfs_item_nr( i);
4774cfed81a0SChris Mason 			ioff = btrfs_token_item_offset(leaf, item, &token);
4775cfed81a0SChris Mason 			btrfs_set_token_item_offset(leaf, item,
4776cfed81a0SChris Mason 						    ioff - total_data, &token);
47770783fcfcSChris Mason 		}
4778be0e5c09SChris Mason 		/* shift the items */
47799c58309dSChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + nr),
47805f39d397SChris Mason 			      btrfs_item_nr_offset(slot),
47810783fcfcSChris Mason 			      (nritems - slot) * sizeof(struct btrfs_item));
4782be0e5c09SChris Mason 
4783be0e5c09SChris Mason 		/* shift the data */
47845f39d397SChris Mason 		memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
47859c58309dSChris Mason 			      data_end - total_data, btrfs_leaf_data(leaf) +
4786be0e5c09SChris Mason 			      data_end, old_data - data_end);
4787be0e5c09SChris Mason 		data_end = old_data;
4788be0e5c09SChris Mason 	}
47895f39d397SChris Mason 
479062e2749eSChris Mason 	/* setup the item for the new data */
47919c58309dSChris Mason 	for (i = 0; i < nr; i++) {
47929c58309dSChris Mason 		btrfs_cpu_key_to_disk(&disk_key, cpu_key + i);
47939c58309dSChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot + i);
4794dd3cc16bSRoss Kirk 		item = btrfs_item_nr(slot + i);
4795cfed81a0SChris Mason 		btrfs_set_token_item_offset(leaf, item,
4796cfed81a0SChris Mason 					    data_end - data_size[i], &token);
47979c58309dSChris Mason 		data_end -= data_size[i];
4798cfed81a0SChris Mason 		btrfs_set_token_item_size(leaf, item, data_size[i], &token);
47999c58309dSChris Mason 	}
480044871b1bSChris Mason 
48019c58309dSChris Mason 	btrfs_set_header_nritems(leaf, nritems + nr);
4802b9473439SChris Mason 	btrfs_mark_buffer_dirty(leaf);
4803aa5d6bedSChris Mason 
48045f39d397SChris Mason 	if (btrfs_leaf_free_space(root, leaf) < 0) {
48055f39d397SChris Mason 		btrfs_print_leaf(root, leaf);
4806be0e5c09SChris Mason 		BUG();
48075f39d397SChris Mason 	}
480844871b1bSChris Mason }
480944871b1bSChris Mason 
481044871b1bSChris Mason /*
481144871b1bSChris Mason  * Given a key and some data, insert items into the tree.
481244871b1bSChris Mason  * This does all the path init required, making room in the tree if needed.
481344871b1bSChris Mason  */
481444871b1bSChris Mason int btrfs_insert_empty_items(struct btrfs_trans_handle *trans,
481544871b1bSChris Mason 			    struct btrfs_root *root,
481644871b1bSChris Mason 			    struct btrfs_path *path,
481744871b1bSChris Mason 			    struct btrfs_key *cpu_key, u32 *data_size,
481844871b1bSChris Mason 			    int nr)
481944871b1bSChris Mason {
482044871b1bSChris Mason 	int ret = 0;
482144871b1bSChris Mason 	int slot;
482244871b1bSChris Mason 	int i;
482344871b1bSChris Mason 	u32 total_size = 0;
482444871b1bSChris Mason 	u32 total_data = 0;
482544871b1bSChris Mason 
482644871b1bSChris Mason 	for (i = 0; i < nr; i++)
482744871b1bSChris Mason 		total_data += data_size[i];
482844871b1bSChris Mason 
482944871b1bSChris Mason 	total_size = total_data + (nr * sizeof(struct btrfs_item));
483044871b1bSChris Mason 	ret = btrfs_search_slot(trans, root, cpu_key, path, total_size, 1);
483144871b1bSChris Mason 	if (ret == 0)
483244871b1bSChris Mason 		return -EEXIST;
483344871b1bSChris Mason 	if (ret < 0)
4834143bede5SJeff Mahoney 		return ret;
483544871b1bSChris Mason 
483644871b1bSChris Mason 	slot = path->slots[0];
483744871b1bSChris Mason 	BUG_ON(slot < 0);
483844871b1bSChris Mason 
4839afe5fea7STsutomu Itoh 	setup_items_for_insert(root, path, cpu_key, data_size,
484044871b1bSChris Mason 			       total_data, total_size, nr);
4841143bede5SJeff Mahoney 	return 0;
484262e2749eSChris Mason }
484362e2749eSChris Mason 
484462e2749eSChris Mason /*
484562e2749eSChris Mason  * Given a key and some data, insert an item into the tree.
484662e2749eSChris Mason  * This does all the path init required, making room in the tree if needed.
484762e2749eSChris Mason  */
4848e089f05cSChris Mason int btrfs_insert_item(struct btrfs_trans_handle *trans, struct btrfs_root
4849e089f05cSChris Mason 		      *root, struct btrfs_key *cpu_key, void *data, u32
4850e089f05cSChris Mason 		      data_size)
485162e2749eSChris Mason {
485262e2749eSChris Mason 	int ret = 0;
48532c90e5d6SChris Mason 	struct btrfs_path *path;
48545f39d397SChris Mason 	struct extent_buffer *leaf;
48555f39d397SChris Mason 	unsigned long ptr;
485662e2749eSChris Mason 
48572c90e5d6SChris Mason 	path = btrfs_alloc_path();
4858db5b493aSTsutomu Itoh 	if (!path)
4859db5b493aSTsutomu Itoh 		return -ENOMEM;
48602c90e5d6SChris Mason 	ret = btrfs_insert_empty_item(trans, root, path, cpu_key, data_size);
486162e2749eSChris Mason 	if (!ret) {
48625f39d397SChris Mason 		leaf = path->nodes[0];
48635f39d397SChris Mason 		ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
48645f39d397SChris Mason 		write_extent_buffer(leaf, data, ptr, data_size);
48655f39d397SChris Mason 		btrfs_mark_buffer_dirty(leaf);
486662e2749eSChris Mason 	}
48672c90e5d6SChris Mason 	btrfs_free_path(path);
4868aa5d6bedSChris Mason 	return ret;
4869be0e5c09SChris Mason }
4870be0e5c09SChris Mason 
487174123bd7SChris Mason /*
48725de08d7dSChris Mason  * delete the pointer from a given node.
487374123bd7SChris Mason  *
4874d352ac68SChris Mason  * the tree should have been previously balanced so the deletion does not
4875d352ac68SChris Mason  * empty a node.
487674123bd7SChris Mason  */
4877afe5fea7STsutomu Itoh static void del_ptr(struct btrfs_root *root, struct btrfs_path *path,
4878afe5fea7STsutomu Itoh 		    int level, int slot)
4879be0e5c09SChris Mason {
48805f39d397SChris Mason 	struct extent_buffer *parent = path->nodes[level];
48817518a238SChris Mason 	u32 nritems;
4882f3ea38daSJan Schmidt 	int ret;
4883be0e5c09SChris Mason 
48845f39d397SChris Mason 	nritems = btrfs_header_nritems(parent);
4885be0e5c09SChris Mason 	if (slot != nritems - 1) {
48860e411eceSLiu Bo 		if (level)
4887f3ea38daSJan Schmidt 			tree_mod_log_eb_move(root->fs_info, parent, slot,
4888f3ea38daSJan Schmidt 					     slot + 1, nritems - slot - 1);
48895f39d397SChris Mason 		memmove_extent_buffer(parent,
48905f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot),
48915f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot + 1),
4892d6025579SChris Mason 			      sizeof(struct btrfs_key_ptr) *
4893d6025579SChris Mason 			      (nritems - slot - 1));
489457ba86c0SChris Mason 	} else if (level) {
489557ba86c0SChris Mason 		ret = tree_mod_log_insert_key(root->fs_info, parent, slot,
4896c8cc6341SJosef Bacik 					      MOD_LOG_KEY_REMOVE, GFP_NOFS);
489757ba86c0SChris Mason 		BUG_ON(ret < 0);
4898be0e5c09SChris Mason 	}
4899f3ea38daSJan Schmidt 
49007518a238SChris Mason 	nritems--;
49015f39d397SChris Mason 	btrfs_set_header_nritems(parent, nritems);
49027518a238SChris Mason 	if (nritems == 0 && parent == root->node) {
49035f39d397SChris Mason 		BUG_ON(btrfs_header_level(root->node) != 1);
4904eb60ceacSChris Mason 		/* just turn the root into a leaf and break */
49055f39d397SChris Mason 		btrfs_set_header_level(root->node, 0);
4906bb803951SChris Mason 	} else if (slot == 0) {
49075f39d397SChris Mason 		struct btrfs_disk_key disk_key;
49085f39d397SChris Mason 
49095f39d397SChris Mason 		btrfs_node_key(parent, &disk_key, 0);
4910d6a0a126STsutomu Itoh 		fixup_low_keys(root, path, &disk_key, level + 1);
4911be0e5c09SChris Mason 	}
4912d6025579SChris Mason 	btrfs_mark_buffer_dirty(parent);
4913be0e5c09SChris Mason }
4914be0e5c09SChris Mason 
491574123bd7SChris Mason /*
4916323ac95bSChris Mason  * a helper function to delete the leaf pointed to by path->slots[1] and
49175d4f98a2SYan Zheng  * path->nodes[1].
4918323ac95bSChris Mason  *
4919323ac95bSChris Mason  * This deletes the pointer in path->nodes[1] and frees the leaf
4920323ac95bSChris Mason  * block extent.  zero is returned if it all worked out, < 0 otherwise.
4921323ac95bSChris Mason  *
4922323ac95bSChris Mason  * The path must have already been setup for deleting the leaf, including
4923323ac95bSChris Mason  * all the proper balancing.  path->nodes[1] must be locked.
4924323ac95bSChris Mason  */
4925143bede5SJeff Mahoney static noinline void btrfs_del_leaf(struct btrfs_trans_handle *trans,
4926323ac95bSChris Mason 				    struct btrfs_root *root,
49275d4f98a2SYan Zheng 				    struct btrfs_path *path,
49285d4f98a2SYan Zheng 				    struct extent_buffer *leaf)
4929323ac95bSChris Mason {
49305d4f98a2SYan Zheng 	WARN_ON(btrfs_header_generation(leaf) != trans->transid);
4931afe5fea7STsutomu Itoh 	del_ptr(root, path, 1, path->slots[1]);
4932323ac95bSChris Mason 
49334d081c41SChris Mason 	/*
49344d081c41SChris Mason 	 * btrfs_free_extent is expensive, we want to make sure we
49354d081c41SChris Mason 	 * aren't holding any locks when we call it
49364d081c41SChris Mason 	 */
49374d081c41SChris Mason 	btrfs_unlock_up_safe(path, 0);
49384d081c41SChris Mason 
4939f0486c68SYan, Zheng 	root_sub_used(root, leaf->len);
4940f0486c68SYan, Zheng 
49413083ee2eSJosef Bacik 	extent_buffer_get(leaf);
49425581a51aSJan Schmidt 	btrfs_free_tree_block(trans, root, leaf, 0, 1);
49433083ee2eSJosef Bacik 	free_extent_buffer_stale(leaf);
4944323ac95bSChris Mason }
4945323ac95bSChris Mason /*
494674123bd7SChris Mason  * delete the item at the leaf level in path.  If that empties
494774123bd7SChris Mason  * the leaf, remove it from the tree
494874123bd7SChris Mason  */
494985e21bacSChris Mason int btrfs_del_items(struct btrfs_trans_handle *trans, struct btrfs_root *root,
495085e21bacSChris Mason 		    struct btrfs_path *path, int slot, int nr)
4951be0e5c09SChris Mason {
49525f39d397SChris Mason 	struct extent_buffer *leaf;
49535f39d397SChris Mason 	struct btrfs_item *item;
495485e21bacSChris Mason 	int last_off;
495585e21bacSChris Mason 	int dsize = 0;
4956aa5d6bedSChris Mason 	int ret = 0;
4957aa5d6bedSChris Mason 	int wret;
495885e21bacSChris Mason 	int i;
49597518a238SChris Mason 	u32 nritems;
4960cfed81a0SChris Mason 	struct btrfs_map_token token;
4961cfed81a0SChris Mason 
4962cfed81a0SChris Mason 	btrfs_init_map_token(&token);
4963be0e5c09SChris Mason 
49645f39d397SChris Mason 	leaf = path->nodes[0];
496585e21bacSChris Mason 	last_off = btrfs_item_offset_nr(leaf, slot + nr - 1);
496685e21bacSChris Mason 
496785e21bacSChris Mason 	for (i = 0; i < nr; i++)
496885e21bacSChris Mason 		dsize += btrfs_item_size_nr(leaf, slot + i);
496985e21bacSChris Mason 
49705f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
4971be0e5c09SChris Mason 
497285e21bacSChris Mason 	if (slot + nr != nritems) {
4973123abc88SChris Mason 		int data_end = leaf_data_end(root, leaf);
49745f39d397SChris Mason 
49755f39d397SChris Mason 		memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
4976d6025579SChris Mason 			      data_end + dsize,
4977123abc88SChris Mason 			      btrfs_leaf_data(leaf) + data_end,
497885e21bacSChris Mason 			      last_off - data_end);
49795f39d397SChris Mason 
498085e21bacSChris Mason 		for (i = slot + nr; i < nritems; i++) {
49815f39d397SChris Mason 			u32 ioff;
4982db94535dSChris Mason 
4983dd3cc16bSRoss Kirk 			item = btrfs_item_nr(i);
4984cfed81a0SChris Mason 			ioff = btrfs_token_item_offset(leaf, item, &token);
4985cfed81a0SChris Mason 			btrfs_set_token_item_offset(leaf, item,
4986cfed81a0SChris Mason 						    ioff + dsize, &token);
49870783fcfcSChris Mason 		}
4988db94535dSChris Mason 
49895f39d397SChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot),
499085e21bacSChris Mason 			      btrfs_item_nr_offset(slot + nr),
49910783fcfcSChris Mason 			      sizeof(struct btrfs_item) *
499285e21bacSChris Mason 			      (nritems - slot - nr));
4993be0e5c09SChris Mason 	}
499485e21bacSChris Mason 	btrfs_set_header_nritems(leaf, nritems - nr);
499585e21bacSChris Mason 	nritems -= nr;
49965f39d397SChris Mason 
499774123bd7SChris Mason 	/* delete the leaf if we've emptied it */
49987518a238SChris Mason 	if (nritems == 0) {
49995f39d397SChris Mason 		if (leaf == root->node) {
50005f39d397SChris Mason 			btrfs_set_header_level(leaf, 0);
50019a8dd150SChris Mason 		} else {
5002f0486c68SYan, Zheng 			btrfs_set_path_blocking(path);
5003f0486c68SYan, Zheng 			clean_tree_block(trans, root, leaf);
5004143bede5SJeff Mahoney 			btrfs_del_leaf(trans, root, path, leaf);
50059a8dd150SChris Mason 		}
5006be0e5c09SChris Mason 	} else {
50077518a238SChris Mason 		int used = leaf_space_used(leaf, 0, nritems);
5008aa5d6bedSChris Mason 		if (slot == 0) {
50095f39d397SChris Mason 			struct btrfs_disk_key disk_key;
50105f39d397SChris Mason 
50115f39d397SChris Mason 			btrfs_item_key(leaf, &disk_key, 0);
5012d6a0a126STsutomu Itoh 			fixup_low_keys(root, path, &disk_key, 1);
5013aa5d6bedSChris Mason 		}
5014aa5d6bedSChris Mason 
501574123bd7SChris Mason 		/* delete the leaf if it is mostly empty */
5016d717aa1dSYan Zheng 		if (used < BTRFS_LEAF_DATA_SIZE(root) / 3) {
5017be0e5c09SChris Mason 			/* push_leaf_left fixes the path.
5018be0e5c09SChris Mason 			 * make sure the path still points to our leaf
5019be0e5c09SChris Mason 			 * for possible call to del_ptr below
5020be0e5c09SChris Mason 			 */
50214920c9acSChris Mason 			slot = path->slots[1];
50225f39d397SChris Mason 			extent_buffer_get(leaf);
50235f39d397SChris Mason 
5024b9473439SChris Mason 			btrfs_set_path_blocking(path);
502599d8f83cSChris Mason 			wret = push_leaf_left(trans, root, path, 1, 1,
502699d8f83cSChris Mason 					      1, (u32)-1);
502754aa1f4dSChris Mason 			if (wret < 0 && wret != -ENOSPC)
5028aa5d6bedSChris Mason 				ret = wret;
50295f39d397SChris Mason 
50305f39d397SChris Mason 			if (path->nodes[0] == leaf &&
50315f39d397SChris Mason 			    btrfs_header_nritems(leaf)) {
503299d8f83cSChris Mason 				wret = push_leaf_right(trans, root, path, 1,
503399d8f83cSChris Mason 						       1, 1, 0);
503454aa1f4dSChris Mason 				if (wret < 0 && wret != -ENOSPC)
5035aa5d6bedSChris Mason 					ret = wret;
5036aa5d6bedSChris Mason 			}
50375f39d397SChris Mason 
50385f39d397SChris Mason 			if (btrfs_header_nritems(leaf) == 0) {
5039323ac95bSChris Mason 				path->slots[1] = slot;
5040143bede5SJeff Mahoney 				btrfs_del_leaf(trans, root, path, leaf);
50415f39d397SChris Mason 				free_extent_buffer(leaf);
5042143bede5SJeff Mahoney 				ret = 0;
50435de08d7dSChris Mason 			} else {
5044925baeddSChris Mason 				/* if we're still in the path, make sure
5045925baeddSChris Mason 				 * we're dirty.  Otherwise, one of the
5046925baeddSChris Mason 				 * push_leaf functions must have already
5047925baeddSChris Mason 				 * dirtied this buffer
5048925baeddSChris Mason 				 */
5049925baeddSChris Mason 				if (path->nodes[0] == leaf)
50505f39d397SChris Mason 					btrfs_mark_buffer_dirty(leaf);
50515f39d397SChris Mason 				free_extent_buffer(leaf);
5052be0e5c09SChris Mason 			}
5053d5719762SChris Mason 		} else {
50545f39d397SChris Mason 			btrfs_mark_buffer_dirty(leaf);
5055be0e5c09SChris Mason 		}
50569a8dd150SChris Mason 	}
5057aa5d6bedSChris Mason 	return ret;
50589a8dd150SChris Mason }
50599a8dd150SChris Mason 
506097571fd0SChris Mason /*
5061925baeddSChris Mason  * search the tree again to find a leaf with lesser keys
50627bb86316SChris Mason  * returns 0 if it found something or 1 if there are no lesser leaves.
50637bb86316SChris Mason  * returns < 0 on io errors.
5064d352ac68SChris Mason  *
5065d352ac68SChris Mason  * This may release the path, and so you may lose any locks held at the
5066d352ac68SChris Mason  * time you call it.
50677bb86316SChris Mason  */
506816e7549fSJosef Bacik int btrfs_prev_leaf(struct btrfs_root *root, struct btrfs_path *path)
50697bb86316SChris Mason {
5070925baeddSChris Mason 	struct btrfs_key key;
5071925baeddSChris Mason 	struct btrfs_disk_key found_key;
5072925baeddSChris Mason 	int ret;
50737bb86316SChris Mason 
5074925baeddSChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, 0);
5075925baeddSChris Mason 
5076e8b0d724SFilipe David Borba Manana 	if (key.offset > 0) {
5077925baeddSChris Mason 		key.offset--;
5078e8b0d724SFilipe David Borba Manana 	} else if (key.type > 0) {
5079925baeddSChris Mason 		key.type--;
5080e8b0d724SFilipe David Borba Manana 		key.offset = (u64)-1;
5081e8b0d724SFilipe David Borba Manana 	} else if (key.objectid > 0) {
5082925baeddSChris Mason 		key.objectid--;
5083e8b0d724SFilipe David Borba Manana 		key.type = (u8)-1;
5084e8b0d724SFilipe David Borba Manana 		key.offset = (u64)-1;
5085e8b0d724SFilipe David Borba Manana 	} else {
50867bb86316SChris Mason 		return 1;
5087e8b0d724SFilipe David Borba Manana 	}
50887bb86316SChris Mason 
5089b3b4aa74SDavid Sterba 	btrfs_release_path(path);
5090925baeddSChris Mason 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5091925baeddSChris Mason 	if (ret < 0)
5092925baeddSChris Mason 		return ret;
5093925baeddSChris Mason 	btrfs_item_key(path->nodes[0], &found_key, 0);
5094925baeddSChris Mason 	ret = comp_keys(&found_key, &key);
5095337c6f68SFilipe Manana 	/*
5096337c6f68SFilipe Manana 	 * We might have had an item with the previous key in the tree right
5097337c6f68SFilipe Manana 	 * before we released our path. And after we released our path, that
5098337c6f68SFilipe Manana 	 * item might have been pushed to the first slot (0) of the leaf we
5099337c6f68SFilipe Manana 	 * were holding due to a tree balance. Alternatively, an item with the
5100337c6f68SFilipe Manana 	 * previous key can exist as the only element of a leaf (big fat item).
5101337c6f68SFilipe Manana 	 * Therefore account for these 2 cases, so that our callers (like
5102337c6f68SFilipe Manana 	 * btrfs_previous_item) don't miss an existing item with a key matching
5103337c6f68SFilipe Manana 	 * the previous key we computed above.
5104337c6f68SFilipe Manana 	 */
5105337c6f68SFilipe Manana 	if (ret <= 0)
51067bb86316SChris Mason 		return 0;
5107925baeddSChris Mason 	return 1;
51087bb86316SChris Mason }
51097bb86316SChris Mason 
51103f157a2fSChris Mason /*
51113f157a2fSChris Mason  * A helper function to walk down the tree starting at min_key, and looking
5112de78b51aSEric Sandeen  * for nodes or leaves that are have a minimum transaction id.
5113de78b51aSEric Sandeen  * This is used by the btree defrag code, and tree logging
51143f157a2fSChris Mason  *
51153f157a2fSChris Mason  * This does not cow, but it does stuff the starting key it finds back
51163f157a2fSChris Mason  * into min_key, so you can call btrfs_search_slot with cow=1 on the
51173f157a2fSChris Mason  * key and get a writable path.
51183f157a2fSChris Mason  *
51193f157a2fSChris Mason  * This does lock as it descends, and path->keep_locks should be set
51203f157a2fSChris Mason  * to 1 by the caller.
51213f157a2fSChris Mason  *
51223f157a2fSChris Mason  * This honors path->lowest_level to prevent descent past a given level
51233f157a2fSChris Mason  * of the tree.
51243f157a2fSChris Mason  *
5125d352ac68SChris Mason  * min_trans indicates the oldest transaction that you are interested
5126d352ac68SChris Mason  * in walking through.  Any nodes or leaves older than min_trans are
5127d352ac68SChris Mason  * skipped over (without reading them).
5128d352ac68SChris Mason  *
51293f157a2fSChris Mason  * returns zero if something useful was found, < 0 on error and 1 if there
51303f157a2fSChris Mason  * was nothing in the tree that matched the search criteria.
51313f157a2fSChris Mason  */
51323f157a2fSChris Mason int btrfs_search_forward(struct btrfs_root *root, struct btrfs_key *min_key,
5133de78b51aSEric Sandeen 			 struct btrfs_path *path,
51343f157a2fSChris Mason 			 u64 min_trans)
51353f157a2fSChris Mason {
51363f157a2fSChris Mason 	struct extent_buffer *cur;
51373f157a2fSChris Mason 	struct btrfs_key found_key;
51383f157a2fSChris Mason 	int slot;
51399652480bSYan 	int sret;
51403f157a2fSChris Mason 	u32 nritems;
51413f157a2fSChris Mason 	int level;
51423f157a2fSChris Mason 	int ret = 1;
5143f98de9b9SFilipe Manana 	int keep_locks = path->keep_locks;
51443f157a2fSChris Mason 
5145f98de9b9SFilipe Manana 	path->keep_locks = 1;
51463f157a2fSChris Mason again:
5147bd681513SChris Mason 	cur = btrfs_read_lock_root_node(root);
51483f157a2fSChris Mason 	level = btrfs_header_level(cur);
5149e02119d5SChris Mason 	WARN_ON(path->nodes[level]);
51503f157a2fSChris Mason 	path->nodes[level] = cur;
5151bd681513SChris Mason 	path->locks[level] = BTRFS_READ_LOCK;
51523f157a2fSChris Mason 
51533f157a2fSChris Mason 	if (btrfs_header_generation(cur) < min_trans) {
51543f157a2fSChris Mason 		ret = 1;
51553f157a2fSChris Mason 		goto out;
51563f157a2fSChris Mason 	}
51573f157a2fSChris Mason 	while (1) {
51583f157a2fSChris Mason 		nritems = btrfs_header_nritems(cur);
51593f157a2fSChris Mason 		level = btrfs_header_level(cur);
51609652480bSYan 		sret = bin_search(cur, min_key, level, &slot);
51613f157a2fSChris Mason 
5162323ac95bSChris Mason 		/* at the lowest level, we're done, setup the path and exit */
5163323ac95bSChris Mason 		if (level == path->lowest_level) {
5164e02119d5SChris Mason 			if (slot >= nritems)
5165e02119d5SChris Mason 				goto find_next_key;
51663f157a2fSChris Mason 			ret = 0;
51673f157a2fSChris Mason 			path->slots[level] = slot;
51683f157a2fSChris Mason 			btrfs_item_key_to_cpu(cur, &found_key, slot);
51693f157a2fSChris Mason 			goto out;
51703f157a2fSChris Mason 		}
51719652480bSYan 		if (sret && slot > 0)
51729652480bSYan 			slot--;
51733f157a2fSChris Mason 		/*
5174de78b51aSEric Sandeen 		 * check this node pointer against the min_trans parameters.
5175de78b51aSEric Sandeen 		 * If it is too old, old, skip to the next one.
51763f157a2fSChris Mason 		 */
51773f157a2fSChris Mason 		while (slot < nritems) {
51783f157a2fSChris Mason 			u64 gen;
5179e02119d5SChris Mason 
51803f157a2fSChris Mason 			gen = btrfs_node_ptr_generation(cur, slot);
51813f157a2fSChris Mason 			if (gen < min_trans) {
51823f157a2fSChris Mason 				slot++;
51833f157a2fSChris Mason 				continue;
51843f157a2fSChris Mason 			}
51853f157a2fSChris Mason 			break;
51863f157a2fSChris Mason 		}
5187e02119d5SChris Mason find_next_key:
51883f157a2fSChris Mason 		/*
51893f157a2fSChris Mason 		 * we didn't find a candidate key in this node, walk forward
51903f157a2fSChris Mason 		 * and find another one
51913f157a2fSChris Mason 		 */
51923f157a2fSChris Mason 		if (slot >= nritems) {
5193e02119d5SChris Mason 			path->slots[level] = slot;
5194b4ce94deSChris Mason 			btrfs_set_path_blocking(path);
5195e02119d5SChris Mason 			sret = btrfs_find_next_key(root, path, min_key, level,
5196de78b51aSEric Sandeen 						  min_trans);
5197e02119d5SChris Mason 			if (sret == 0) {
5198b3b4aa74SDavid Sterba 				btrfs_release_path(path);
51993f157a2fSChris Mason 				goto again;
52003f157a2fSChris Mason 			} else {
52013f157a2fSChris Mason 				goto out;
52023f157a2fSChris Mason 			}
52033f157a2fSChris Mason 		}
52043f157a2fSChris Mason 		/* save our key for returning back */
52053f157a2fSChris Mason 		btrfs_node_key_to_cpu(cur, &found_key, slot);
52063f157a2fSChris Mason 		path->slots[level] = slot;
52073f157a2fSChris Mason 		if (level == path->lowest_level) {
52083f157a2fSChris Mason 			ret = 0;
52093f157a2fSChris Mason 			goto out;
52103f157a2fSChris Mason 		}
5211b4ce94deSChris Mason 		btrfs_set_path_blocking(path);
52123f157a2fSChris Mason 		cur = read_node_slot(root, cur, slot);
521379787eaaSJeff Mahoney 		BUG_ON(!cur); /* -ENOMEM */
52143f157a2fSChris Mason 
5215bd681513SChris Mason 		btrfs_tree_read_lock(cur);
5216b4ce94deSChris Mason 
5217bd681513SChris Mason 		path->locks[level - 1] = BTRFS_READ_LOCK;
52183f157a2fSChris Mason 		path->nodes[level - 1] = cur;
5219f7c79f30SChris Mason 		unlock_up(path, level, 1, 0, NULL);
5220bd681513SChris Mason 		btrfs_clear_path_blocking(path, NULL, 0);
52213f157a2fSChris Mason 	}
52223f157a2fSChris Mason out:
5223f98de9b9SFilipe Manana 	path->keep_locks = keep_locks;
5224f98de9b9SFilipe Manana 	if (ret == 0) {
5225f98de9b9SFilipe Manana 		btrfs_unlock_up_safe(path, path->lowest_level + 1);
5226b4ce94deSChris Mason 		btrfs_set_path_blocking(path);
5227f98de9b9SFilipe Manana 		memcpy(min_key, &found_key, sizeof(found_key));
5228f98de9b9SFilipe Manana 	}
52293f157a2fSChris Mason 	return ret;
52303f157a2fSChris Mason }
52313f157a2fSChris Mason 
52327069830aSAlexander Block static void tree_move_down(struct btrfs_root *root,
52337069830aSAlexander Block 			   struct btrfs_path *path,
52347069830aSAlexander Block 			   int *level, int root_level)
52357069830aSAlexander Block {
523674dd17fbSChris Mason 	BUG_ON(*level == 0);
52377069830aSAlexander Block 	path->nodes[*level - 1] = read_node_slot(root, path->nodes[*level],
52387069830aSAlexander Block 					path->slots[*level]);
52397069830aSAlexander Block 	path->slots[*level - 1] = 0;
52407069830aSAlexander Block 	(*level)--;
52417069830aSAlexander Block }
52427069830aSAlexander Block 
52437069830aSAlexander Block static int tree_move_next_or_upnext(struct btrfs_root *root,
52447069830aSAlexander Block 				    struct btrfs_path *path,
52457069830aSAlexander Block 				    int *level, int root_level)
52467069830aSAlexander Block {
52477069830aSAlexander Block 	int ret = 0;
52487069830aSAlexander Block 	int nritems;
52497069830aSAlexander Block 	nritems = btrfs_header_nritems(path->nodes[*level]);
52507069830aSAlexander Block 
52517069830aSAlexander Block 	path->slots[*level]++;
52527069830aSAlexander Block 
525374dd17fbSChris Mason 	while (path->slots[*level] >= nritems) {
52547069830aSAlexander Block 		if (*level == root_level)
52557069830aSAlexander Block 			return -1;
52567069830aSAlexander Block 
52577069830aSAlexander Block 		/* move upnext */
52587069830aSAlexander Block 		path->slots[*level] = 0;
52597069830aSAlexander Block 		free_extent_buffer(path->nodes[*level]);
52607069830aSAlexander Block 		path->nodes[*level] = NULL;
52617069830aSAlexander Block 		(*level)++;
52627069830aSAlexander Block 		path->slots[*level]++;
52637069830aSAlexander Block 
52647069830aSAlexander Block 		nritems = btrfs_header_nritems(path->nodes[*level]);
52657069830aSAlexander Block 		ret = 1;
52667069830aSAlexander Block 	}
52677069830aSAlexander Block 	return ret;
52687069830aSAlexander Block }
52697069830aSAlexander Block 
52707069830aSAlexander Block /*
52717069830aSAlexander Block  * Returns 1 if it had to move up and next. 0 is returned if it moved only next
52727069830aSAlexander Block  * or down.
52737069830aSAlexander Block  */
52747069830aSAlexander Block static int tree_advance(struct btrfs_root *root,
52757069830aSAlexander Block 			struct btrfs_path *path,
52767069830aSAlexander Block 			int *level, int root_level,
52777069830aSAlexander Block 			int allow_down,
52787069830aSAlexander Block 			struct btrfs_key *key)
52797069830aSAlexander Block {
52807069830aSAlexander Block 	int ret;
52817069830aSAlexander Block 
52827069830aSAlexander Block 	if (*level == 0 || !allow_down) {
52837069830aSAlexander Block 		ret = tree_move_next_or_upnext(root, path, level, root_level);
52847069830aSAlexander Block 	} else {
52857069830aSAlexander Block 		tree_move_down(root, path, level, root_level);
52867069830aSAlexander Block 		ret = 0;
52877069830aSAlexander Block 	}
52887069830aSAlexander Block 	if (ret >= 0) {
52897069830aSAlexander Block 		if (*level == 0)
52907069830aSAlexander Block 			btrfs_item_key_to_cpu(path->nodes[*level], key,
52917069830aSAlexander Block 					path->slots[*level]);
52927069830aSAlexander Block 		else
52937069830aSAlexander Block 			btrfs_node_key_to_cpu(path->nodes[*level], key,
52947069830aSAlexander Block 					path->slots[*level]);
52957069830aSAlexander Block 	}
52967069830aSAlexander Block 	return ret;
52977069830aSAlexander Block }
52987069830aSAlexander Block 
52997069830aSAlexander Block static int tree_compare_item(struct btrfs_root *left_root,
53007069830aSAlexander Block 			     struct btrfs_path *left_path,
53017069830aSAlexander Block 			     struct btrfs_path *right_path,
53027069830aSAlexander Block 			     char *tmp_buf)
53037069830aSAlexander Block {
53047069830aSAlexander Block 	int cmp;
53057069830aSAlexander Block 	int len1, len2;
53067069830aSAlexander Block 	unsigned long off1, off2;
53077069830aSAlexander Block 
53087069830aSAlexander Block 	len1 = btrfs_item_size_nr(left_path->nodes[0], left_path->slots[0]);
53097069830aSAlexander Block 	len2 = btrfs_item_size_nr(right_path->nodes[0], right_path->slots[0]);
53107069830aSAlexander Block 	if (len1 != len2)
53117069830aSAlexander Block 		return 1;
53127069830aSAlexander Block 
53137069830aSAlexander Block 	off1 = btrfs_item_ptr_offset(left_path->nodes[0], left_path->slots[0]);
53147069830aSAlexander Block 	off2 = btrfs_item_ptr_offset(right_path->nodes[0],
53157069830aSAlexander Block 				right_path->slots[0]);
53167069830aSAlexander Block 
53177069830aSAlexander Block 	read_extent_buffer(left_path->nodes[0], tmp_buf, off1, len1);
53187069830aSAlexander Block 
53197069830aSAlexander Block 	cmp = memcmp_extent_buffer(right_path->nodes[0], tmp_buf, off2, len1);
53207069830aSAlexander Block 	if (cmp)
53217069830aSAlexander Block 		return 1;
53227069830aSAlexander Block 	return 0;
53237069830aSAlexander Block }
53247069830aSAlexander Block 
53257069830aSAlexander Block #define ADVANCE 1
53267069830aSAlexander Block #define ADVANCE_ONLY_NEXT -1
53277069830aSAlexander Block 
53287069830aSAlexander Block /*
53297069830aSAlexander Block  * This function compares two trees and calls the provided callback for
53307069830aSAlexander Block  * every changed/new/deleted item it finds.
53317069830aSAlexander Block  * If shared tree blocks are encountered, whole subtrees are skipped, making
53327069830aSAlexander Block  * the compare pretty fast on snapshotted subvolumes.
53337069830aSAlexander Block  *
53347069830aSAlexander Block  * This currently works on commit roots only. As commit roots are read only,
53357069830aSAlexander Block  * we don't do any locking. The commit roots are protected with transactions.
53367069830aSAlexander Block  * Transactions are ended and rejoined when a commit is tried in between.
53377069830aSAlexander Block  *
53387069830aSAlexander Block  * This function checks for modifications done to the trees while comparing.
53397069830aSAlexander Block  * If it detects a change, it aborts immediately.
53407069830aSAlexander Block  */
53417069830aSAlexander Block int btrfs_compare_trees(struct btrfs_root *left_root,
53427069830aSAlexander Block 			struct btrfs_root *right_root,
53437069830aSAlexander Block 			btrfs_changed_cb_t changed_cb, void *ctx)
53447069830aSAlexander Block {
53457069830aSAlexander Block 	int ret;
53467069830aSAlexander Block 	int cmp;
53477069830aSAlexander Block 	struct btrfs_path *left_path = NULL;
53487069830aSAlexander Block 	struct btrfs_path *right_path = NULL;
53497069830aSAlexander Block 	struct btrfs_key left_key;
53507069830aSAlexander Block 	struct btrfs_key right_key;
53517069830aSAlexander Block 	char *tmp_buf = NULL;
53527069830aSAlexander Block 	int left_root_level;
53537069830aSAlexander Block 	int right_root_level;
53547069830aSAlexander Block 	int left_level;
53557069830aSAlexander Block 	int right_level;
53567069830aSAlexander Block 	int left_end_reached;
53577069830aSAlexander Block 	int right_end_reached;
53587069830aSAlexander Block 	int advance_left;
53597069830aSAlexander Block 	int advance_right;
53607069830aSAlexander Block 	u64 left_blockptr;
53617069830aSAlexander Block 	u64 right_blockptr;
53626baa4293SFilipe Manana 	u64 left_gen;
53636baa4293SFilipe Manana 	u64 right_gen;
53647069830aSAlexander Block 
53657069830aSAlexander Block 	left_path = btrfs_alloc_path();
53667069830aSAlexander Block 	if (!left_path) {
53677069830aSAlexander Block 		ret = -ENOMEM;
53687069830aSAlexander Block 		goto out;
53697069830aSAlexander Block 	}
53707069830aSAlexander Block 	right_path = btrfs_alloc_path();
53717069830aSAlexander Block 	if (!right_path) {
53727069830aSAlexander Block 		ret = -ENOMEM;
53737069830aSAlexander Block 		goto out;
53747069830aSAlexander Block 	}
53757069830aSAlexander Block 
5376707e8a07SDavid Sterba 	tmp_buf = kmalloc(left_root->nodesize, GFP_NOFS);
53777069830aSAlexander Block 	if (!tmp_buf) {
53787069830aSAlexander Block 		ret = -ENOMEM;
53797069830aSAlexander Block 		goto out;
53807069830aSAlexander Block 	}
53817069830aSAlexander Block 
53827069830aSAlexander Block 	left_path->search_commit_root = 1;
53837069830aSAlexander Block 	left_path->skip_locking = 1;
53847069830aSAlexander Block 	right_path->search_commit_root = 1;
53857069830aSAlexander Block 	right_path->skip_locking = 1;
53867069830aSAlexander Block 
53877069830aSAlexander Block 	/*
53887069830aSAlexander Block 	 * Strategy: Go to the first items of both trees. Then do
53897069830aSAlexander Block 	 *
53907069830aSAlexander Block 	 * If both trees are at level 0
53917069830aSAlexander Block 	 *   Compare keys of current items
53927069830aSAlexander Block 	 *     If left < right treat left item as new, advance left tree
53937069830aSAlexander Block 	 *       and repeat
53947069830aSAlexander Block 	 *     If left > right treat right item as deleted, advance right tree
53957069830aSAlexander Block 	 *       and repeat
53967069830aSAlexander Block 	 *     If left == right do deep compare of items, treat as changed if
53977069830aSAlexander Block 	 *       needed, advance both trees and repeat
53987069830aSAlexander Block 	 * If both trees are at the same level but not at level 0
53997069830aSAlexander Block 	 *   Compare keys of current nodes/leafs
54007069830aSAlexander Block 	 *     If left < right advance left tree and repeat
54017069830aSAlexander Block 	 *     If left > right advance right tree and repeat
54027069830aSAlexander Block 	 *     If left == right compare blockptrs of the next nodes/leafs
54037069830aSAlexander Block 	 *       If they match advance both trees but stay at the same level
54047069830aSAlexander Block 	 *         and repeat
54057069830aSAlexander Block 	 *       If they don't match advance both trees while allowing to go
54067069830aSAlexander Block 	 *         deeper and repeat
54077069830aSAlexander Block 	 * If tree levels are different
54087069830aSAlexander Block 	 *   Advance the tree that needs it and repeat
54097069830aSAlexander Block 	 *
54107069830aSAlexander Block 	 * Advancing a tree means:
54117069830aSAlexander Block 	 *   If we are at level 0, try to go to the next slot. If that's not
54127069830aSAlexander Block 	 *   possible, go one level up and repeat. Stop when we found a level
54137069830aSAlexander Block 	 *   where we could go to the next slot. We may at this point be on a
54147069830aSAlexander Block 	 *   node or a leaf.
54157069830aSAlexander Block 	 *
54167069830aSAlexander Block 	 *   If we are not at level 0 and not on shared tree blocks, go one
54177069830aSAlexander Block 	 *   level deeper.
54187069830aSAlexander Block 	 *
54197069830aSAlexander Block 	 *   If we are not at level 0 and on shared tree blocks, go one slot to
54207069830aSAlexander Block 	 *   the right if possible or go up and right.
54217069830aSAlexander Block 	 */
54227069830aSAlexander Block 
54233f8a18ccSJosef Bacik 	down_read(&left_root->fs_info->commit_root_sem);
54247069830aSAlexander Block 	left_level = btrfs_header_level(left_root->commit_root);
54257069830aSAlexander Block 	left_root_level = left_level;
54267069830aSAlexander Block 	left_path->nodes[left_level] = left_root->commit_root;
54277069830aSAlexander Block 	extent_buffer_get(left_path->nodes[left_level]);
54287069830aSAlexander Block 
54297069830aSAlexander Block 	right_level = btrfs_header_level(right_root->commit_root);
54307069830aSAlexander Block 	right_root_level = right_level;
54317069830aSAlexander Block 	right_path->nodes[right_level] = right_root->commit_root;
54327069830aSAlexander Block 	extent_buffer_get(right_path->nodes[right_level]);
54333f8a18ccSJosef Bacik 	up_read(&left_root->fs_info->commit_root_sem);
54347069830aSAlexander Block 
54357069830aSAlexander Block 	if (left_level == 0)
54367069830aSAlexander Block 		btrfs_item_key_to_cpu(left_path->nodes[left_level],
54377069830aSAlexander Block 				&left_key, left_path->slots[left_level]);
54387069830aSAlexander Block 	else
54397069830aSAlexander Block 		btrfs_node_key_to_cpu(left_path->nodes[left_level],
54407069830aSAlexander Block 				&left_key, left_path->slots[left_level]);
54417069830aSAlexander Block 	if (right_level == 0)
54427069830aSAlexander Block 		btrfs_item_key_to_cpu(right_path->nodes[right_level],
54437069830aSAlexander Block 				&right_key, right_path->slots[right_level]);
54447069830aSAlexander Block 	else
54457069830aSAlexander Block 		btrfs_node_key_to_cpu(right_path->nodes[right_level],
54467069830aSAlexander Block 				&right_key, right_path->slots[right_level]);
54477069830aSAlexander Block 
54487069830aSAlexander Block 	left_end_reached = right_end_reached = 0;
54497069830aSAlexander Block 	advance_left = advance_right = 0;
54507069830aSAlexander Block 
54517069830aSAlexander Block 	while (1) {
54527069830aSAlexander Block 		if (advance_left && !left_end_reached) {
54537069830aSAlexander Block 			ret = tree_advance(left_root, left_path, &left_level,
54547069830aSAlexander Block 					left_root_level,
54557069830aSAlexander Block 					advance_left != ADVANCE_ONLY_NEXT,
54567069830aSAlexander Block 					&left_key);
54577069830aSAlexander Block 			if (ret < 0)
54587069830aSAlexander Block 				left_end_reached = ADVANCE;
54597069830aSAlexander Block 			advance_left = 0;
54607069830aSAlexander Block 		}
54617069830aSAlexander Block 		if (advance_right && !right_end_reached) {
54627069830aSAlexander Block 			ret = tree_advance(right_root, right_path, &right_level,
54637069830aSAlexander Block 					right_root_level,
54647069830aSAlexander Block 					advance_right != ADVANCE_ONLY_NEXT,
54657069830aSAlexander Block 					&right_key);
54667069830aSAlexander Block 			if (ret < 0)
54677069830aSAlexander Block 				right_end_reached = ADVANCE;
54687069830aSAlexander Block 			advance_right = 0;
54697069830aSAlexander Block 		}
54707069830aSAlexander Block 
54717069830aSAlexander Block 		if (left_end_reached && right_end_reached) {
54727069830aSAlexander Block 			ret = 0;
54737069830aSAlexander Block 			goto out;
54747069830aSAlexander Block 		} else if (left_end_reached) {
54757069830aSAlexander Block 			if (right_level == 0) {
54767069830aSAlexander Block 				ret = changed_cb(left_root, right_root,
54777069830aSAlexander Block 						left_path, right_path,
54787069830aSAlexander Block 						&right_key,
54797069830aSAlexander Block 						BTRFS_COMPARE_TREE_DELETED,
54807069830aSAlexander Block 						ctx);
54817069830aSAlexander Block 				if (ret < 0)
54827069830aSAlexander Block 					goto out;
54837069830aSAlexander Block 			}
54847069830aSAlexander Block 			advance_right = ADVANCE;
54857069830aSAlexander Block 			continue;
54867069830aSAlexander Block 		} else if (right_end_reached) {
54877069830aSAlexander Block 			if (left_level == 0) {
54887069830aSAlexander Block 				ret = changed_cb(left_root, right_root,
54897069830aSAlexander Block 						left_path, right_path,
54907069830aSAlexander Block 						&left_key,
54917069830aSAlexander Block 						BTRFS_COMPARE_TREE_NEW,
54927069830aSAlexander Block 						ctx);
54937069830aSAlexander Block 				if (ret < 0)
54947069830aSAlexander Block 					goto out;
54957069830aSAlexander Block 			}
54967069830aSAlexander Block 			advance_left = ADVANCE;
54977069830aSAlexander Block 			continue;
54987069830aSAlexander Block 		}
54997069830aSAlexander Block 
55007069830aSAlexander Block 		if (left_level == 0 && right_level == 0) {
55017069830aSAlexander Block 			cmp = btrfs_comp_cpu_keys(&left_key, &right_key);
55027069830aSAlexander Block 			if (cmp < 0) {
55037069830aSAlexander Block 				ret = changed_cb(left_root, right_root,
55047069830aSAlexander Block 						left_path, right_path,
55057069830aSAlexander Block 						&left_key,
55067069830aSAlexander Block 						BTRFS_COMPARE_TREE_NEW,
55077069830aSAlexander Block 						ctx);
55087069830aSAlexander Block 				if (ret < 0)
55097069830aSAlexander Block 					goto out;
55107069830aSAlexander Block 				advance_left = ADVANCE;
55117069830aSAlexander Block 			} else if (cmp > 0) {
55127069830aSAlexander Block 				ret = changed_cb(left_root, right_root,
55137069830aSAlexander Block 						left_path, right_path,
55147069830aSAlexander Block 						&right_key,
55157069830aSAlexander Block 						BTRFS_COMPARE_TREE_DELETED,
55167069830aSAlexander Block 						ctx);
55177069830aSAlexander Block 				if (ret < 0)
55187069830aSAlexander Block 					goto out;
55197069830aSAlexander Block 				advance_right = ADVANCE;
55207069830aSAlexander Block 			} else {
5521ba5e8f2eSJosef Bacik 				enum btrfs_compare_tree_result cmp;
5522ba5e8f2eSJosef Bacik 
552374dd17fbSChris Mason 				WARN_ON(!extent_buffer_uptodate(left_path->nodes[0]));
55247069830aSAlexander Block 				ret = tree_compare_item(left_root, left_path,
55257069830aSAlexander Block 						right_path, tmp_buf);
5526ba5e8f2eSJosef Bacik 				if (ret)
5527ba5e8f2eSJosef Bacik 					cmp = BTRFS_COMPARE_TREE_CHANGED;
5528ba5e8f2eSJosef Bacik 				else
5529ba5e8f2eSJosef Bacik 					cmp = BTRFS_COMPARE_TREE_SAME;
55307069830aSAlexander Block 				ret = changed_cb(left_root, right_root,
55317069830aSAlexander Block 						 left_path, right_path,
5532ba5e8f2eSJosef Bacik 						 &left_key, cmp, ctx);
55337069830aSAlexander Block 				if (ret < 0)
55347069830aSAlexander Block 					goto out;
55357069830aSAlexander Block 				advance_left = ADVANCE;
55367069830aSAlexander Block 				advance_right = ADVANCE;
55377069830aSAlexander Block 			}
55387069830aSAlexander Block 		} else if (left_level == right_level) {
55397069830aSAlexander Block 			cmp = btrfs_comp_cpu_keys(&left_key, &right_key);
55407069830aSAlexander Block 			if (cmp < 0) {
55417069830aSAlexander Block 				advance_left = ADVANCE;
55427069830aSAlexander Block 			} else if (cmp > 0) {
55437069830aSAlexander Block 				advance_right = ADVANCE;
55447069830aSAlexander Block 			} else {
55457069830aSAlexander Block 				left_blockptr = btrfs_node_blockptr(
55467069830aSAlexander Block 						left_path->nodes[left_level],
55477069830aSAlexander Block 						left_path->slots[left_level]);
55487069830aSAlexander Block 				right_blockptr = btrfs_node_blockptr(
55497069830aSAlexander Block 						right_path->nodes[right_level],
55507069830aSAlexander Block 						right_path->slots[right_level]);
55516baa4293SFilipe Manana 				left_gen = btrfs_node_ptr_generation(
55526baa4293SFilipe Manana 						left_path->nodes[left_level],
55536baa4293SFilipe Manana 						left_path->slots[left_level]);
55546baa4293SFilipe Manana 				right_gen = btrfs_node_ptr_generation(
55556baa4293SFilipe Manana 						right_path->nodes[right_level],
55566baa4293SFilipe Manana 						right_path->slots[right_level]);
55576baa4293SFilipe Manana 				if (left_blockptr == right_blockptr &&
55586baa4293SFilipe Manana 				    left_gen == right_gen) {
55597069830aSAlexander Block 					/*
55607069830aSAlexander Block 					 * As we're on a shared block, don't
55617069830aSAlexander Block 					 * allow to go deeper.
55627069830aSAlexander Block 					 */
55637069830aSAlexander Block 					advance_left = ADVANCE_ONLY_NEXT;
55647069830aSAlexander Block 					advance_right = ADVANCE_ONLY_NEXT;
55657069830aSAlexander Block 				} else {
55667069830aSAlexander Block 					advance_left = ADVANCE;
55677069830aSAlexander Block 					advance_right = ADVANCE;
55687069830aSAlexander Block 				}
55697069830aSAlexander Block 			}
55707069830aSAlexander Block 		} else if (left_level < right_level) {
55717069830aSAlexander Block 			advance_right = ADVANCE;
55727069830aSAlexander Block 		} else {
55737069830aSAlexander Block 			advance_left = ADVANCE;
55747069830aSAlexander Block 		}
55757069830aSAlexander Block 	}
55767069830aSAlexander Block 
55777069830aSAlexander Block out:
55787069830aSAlexander Block 	btrfs_free_path(left_path);
55797069830aSAlexander Block 	btrfs_free_path(right_path);
55807069830aSAlexander Block 	kfree(tmp_buf);
55817069830aSAlexander Block 	return ret;
55827069830aSAlexander Block }
55837069830aSAlexander Block 
55843f157a2fSChris Mason /*
55853f157a2fSChris Mason  * this is similar to btrfs_next_leaf, but does not try to preserve
55863f157a2fSChris Mason  * and fixup the path.  It looks for and returns the next key in the
5587de78b51aSEric Sandeen  * tree based on the current path and the min_trans parameters.
55883f157a2fSChris Mason  *
55893f157a2fSChris Mason  * 0 is returned if another key is found, < 0 if there are any errors
55903f157a2fSChris Mason  * and 1 is returned if there are no higher keys in the tree
55913f157a2fSChris Mason  *
55923f157a2fSChris Mason  * path->keep_locks should be set to 1 on the search made before
55933f157a2fSChris Mason  * calling this function.
55943f157a2fSChris Mason  */
5595e7a84565SChris Mason int btrfs_find_next_key(struct btrfs_root *root, struct btrfs_path *path,
5596de78b51aSEric Sandeen 			struct btrfs_key *key, int level, u64 min_trans)
5597e7a84565SChris Mason {
5598e7a84565SChris Mason 	int slot;
5599e7a84565SChris Mason 	struct extent_buffer *c;
5600e7a84565SChris Mason 
5601934d375bSChris Mason 	WARN_ON(!path->keep_locks);
5602e7a84565SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
5603e7a84565SChris Mason 		if (!path->nodes[level])
5604e7a84565SChris Mason 			return 1;
5605e7a84565SChris Mason 
5606e7a84565SChris Mason 		slot = path->slots[level] + 1;
5607e7a84565SChris Mason 		c = path->nodes[level];
56083f157a2fSChris Mason next:
5609e7a84565SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
561033c66f43SYan Zheng 			int ret;
561133c66f43SYan Zheng 			int orig_lowest;
561233c66f43SYan Zheng 			struct btrfs_key cur_key;
561333c66f43SYan Zheng 			if (level + 1 >= BTRFS_MAX_LEVEL ||
561433c66f43SYan Zheng 			    !path->nodes[level + 1])
5615e7a84565SChris Mason 				return 1;
561633c66f43SYan Zheng 
561733c66f43SYan Zheng 			if (path->locks[level + 1]) {
561833c66f43SYan Zheng 				level++;
5619e7a84565SChris Mason 				continue;
5620e7a84565SChris Mason 			}
562133c66f43SYan Zheng 
562233c66f43SYan Zheng 			slot = btrfs_header_nritems(c) - 1;
562333c66f43SYan Zheng 			if (level == 0)
562433c66f43SYan Zheng 				btrfs_item_key_to_cpu(c, &cur_key, slot);
562533c66f43SYan Zheng 			else
562633c66f43SYan Zheng 				btrfs_node_key_to_cpu(c, &cur_key, slot);
562733c66f43SYan Zheng 
562833c66f43SYan Zheng 			orig_lowest = path->lowest_level;
5629b3b4aa74SDavid Sterba 			btrfs_release_path(path);
563033c66f43SYan Zheng 			path->lowest_level = level;
563133c66f43SYan Zheng 			ret = btrfs_search_slot(NULL, root, &cur_key, path,
563233c66f43SYan Zheng 						0, 0);
563333c66f43SYan Zheng 			path->lowest_level = orig_lowest;
563433c66f43SYan Zheng 			if (ret < 0)
563533c66f43SYan Zheng 				return ret;
563633c66f43SYan Zheng 
563733c66f43SYan Zheng 			c = path->nodes[level];
563833c66f43SYan Zheng 			slot = path->slots[level];
563933c66f43SYan Zheng 			if (ret == 0)
564033c66f43SYan Zheng 				slot++;
564133c66f43SYan Zheng 			goto next;
564233c66f43SYan Zheng 		}
564333c66f43SYan Zheng 
5644e7a84565SChris Mason 		if (level == 0)
5645e7a84565SChris Mason 			btrfs_item_key_to_cpu(c, key, slot);
56463f157a2fSChris Mason 		else {
56473f157a2fSChris Mason 			u64 gen = btrfs_node_ptr_generation(c, slot);
56483f157a2fSChris Mason 
56493f157a2fSChris Mason 			if (gen < min_trans) {
56503f157a2fSChris Mason 				slot++;
56513f157a2fSChris Mason 				goto next;
56523f157a2fSChris Mason 			}
5653e7a84565SChris Mason 			btrfs_node_key_to_cpu(c, key, slot);
56543f157a2fSChris Mason 		}
5655e7a84565SChris Mason 		return 0;
5656e7a84565SChris Mason 	}
5657e7a84565SChris Mason 	return 1;
5658e7a84565SChris Mason }
5659e7a84565SChris Mason 
56607bb86316SChris Mason /*
5661925baeddSChris Mason  * search the tree again to find a leaf with greater keys
56620f70abe2SChris Mason  * returns 0 if it found something or 1 if there are no greater leaves.
56630f70abe2SChris Mason  * returns < 0 on io errors.
566497571fd0SChris Mason  */
5665234b63a0SChris Mason int btrfs_next_leaf(struct btrfs_root *root, struct btrfs_path *path)
5666d97e63b6SChris Mason {
56673d7806ecSJan Schmidt 	return btrfs_next_old_leaf(root, path, 0);
56683d7806ecSJan Schmidt }
56693d7806ecSJan Schmidt 
56703d7806ecSJan Schmidt int btrfs_next_old_leaf(struct btrfs_root *root, struct btrfs_path *path,
56713d7806ecSJan Schmidt 			u64 time_seq)
56723d7806ecSJan Schmidt {
5673d97e63b6SChris Mason 	int slot;
56748e73f275SChris Mason 	int level;
56755f39d397SChris Mason 	struct extent_buffer *c;
56768e73f275SChris Mason 	struct extent_buffer *next;
5677925baeddSChris Mason 	struct btrfs_key key;
5678925baeddSChris Mason 	u32 nritems;
5679925baeddSChris Mason 	int ret;
56808e73f275SChris Mason 	int old_spinning = path->leave_spinning;
5681bd681513SChris Mason 	int next_rw_lock = 0;
5682925baeddSChris Mason 
5683925baeddSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
5684d397712bSChris Mason 	if (nritems == 0)
5685925baeddSChris Mason 		return 1;
5686925baeddSChris Mason 
56878e73f275SChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, nritems - 1);
56888e73f275SChris Mason again:
56898e73f275SChris Mason 	level = 1;
56908e73f275SChris Mason 	next = NULL;
5691bd681513SChris Mason 	next_rw_lock = 0;
5692b3b4aa74SDavid Sterba 	btrfs_release_path(path);
56938e73f275SChris Mason 
5694a2135011SChris Mason 	path->keep_locks = 1;
56958e73f275SChris Mason 	path->leave_spinning = 1;
56968e73f275SChris Mason 
56973d7806ecSJan Schmidt 	if (time_seq)
56983d7806ecSJan Schmidt 		ret = btrfs_search_old_slot(root, &key, path, time_seq);
56993d7806ecSJan Schmidt 	else
5700925baeddSChris Mason 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5701925baeddSChris Mason 	path->keep_locks = 0;
5702925baeddSChris Mason 
5703925baeddSChris Mason 	if (ret < 0)
5704925baeddSChris Mason 		return ret;
5705925baeddSChris Mason 
5706a2135011SChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
5707168fd7d2SChris Mason 	/*
5708168fd7d2SChris Mason 	 * by releasing the path above we dropped all our locks.  A balance
5709168fd7d2SChris Mason 	 * could have added more items next to the key that used to be
5710168fd7d2SChris Mason 	 * at the very end of the block.  So, check again here and
5711168fd7d2SChris Mason 	 * advance the path if there are now more items available.
5712168fd7d2SChris Mason 	 */
5713a2135011SChris Mason 	if (nritems > 0 && path->slots[0] < nritems - 1) {
5714e457afecSYan Zheng 		if (ret == 0)
5715168fd7d2SChris Mason 			path->slots[0]++;
57168e73f275SChris Mason 		ret = 0;
5717925baeddSChris Mason 		goto done;
5718925baeddSChris Mason 	}
57190b43e04fSLiu Bo 	/*
57200b43e04fSLiu Bo 	 * So the above check misses one case:
57210b43e04fSLiu Bo 	 * - after releasing the path above, someone has removed the item that
57220b43e04fSLiu Bo 	 *   used to be at the very end of the block, and balance between leafs
57230b43e04fSLiu Bo 	 *   gets another one with bigger key.offset to replace it.
57240b43e04fSLiu Bo 	 *
57250b43e04fSLiu Bo 	 * This one should be returned as well, or we can get leaf corruption
57260b43e04fSLiu Bo 	 * later(esp. in __btrfs_drop_extents()).
57270b43e04fSLiu Bo 	 *
57280b43e04fSLiu Bo 	 * And a bit more explanation about this check,
57290b43e04fSLiu Bo 	 * with ret > 0, the key isn't found, the path points to the slot
57300b43e04fSLiu Bo 	 * where it should be inserted, so the path->slots[0] item must be the
57310b43e04fSLiu Bo 	 * bigger one.
57320b43e04fSLiu Bo 	 */
57330b43e04fSLiu Bo 	if (nritems > 0 && ret > 0 && path->slots[0] == nritems - 1) {
57340b43e04fSLiu Bo 		ret = 0;
57350b43e04fSLiu Bo 		goto done;
57360b43e04fSLiu Bo 	}
5737d97e63b6SChris Mason 
5738234b63a0SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
57398e73f275SChris Mason 		if (!path->nodes[level]) {
57408e73f275SChris Mason 			ret = 1;
57418e73f275SChris Mason 			goto done;
57428e73f275SChris Mason 		}
57435f39d397SChris Mason 
5744d97e63b6SChris Mason 		slot = path->slots[level] + 1;
5745d97e63b6SChris Mason 		c = path->nodes[level];
57465f39d397SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
5747d97e63b6SChris Mason 			level++;
57488e73f275SChris Mason 			if (level == BTRFS_MAX_LEVEL) {
57498e73f275SChris Mason 				ret = 1;
57508e73f275SChris Mason 				goto done;
57518e73f275SChris Mason 			}
5752d97e63b6SChris Mason 			continue;
5753d97e63b6SChris Mason 		}
57545f39d397SChris Mason 
5755925baeddSChris Mason 		if (next) {
5756bd681513SChris Mason 			btrfs_tree_unlock_rw(next, next_rw_lock);
57575f39d397SChris Mason 			free_extent_buffer(next);
5758925baeddSChris Mason 		}
57595f39d397SChris Mason 
57608e73f275SChris Mason 		next = c;
5761bd681513SChris Mason 		next_rw_lock = path->locks[level];
57628e73f275SChris Mason 		ret = read_block_for_search(NULL, root, path, &next, level,
57635d9e75c4SJan Schmidt 					    slot, &key, 0);
57648e73f275SChris Mason 		if (ret == -EAGAIN)
57658e73f275SChris Mason 			goto again;
57665f39d397SChris Mason 
576776a05b35SChris Mason 		if (ret < 0) {
5768b3b4aa74SDavid Sterba 			btrfs_release_path(path);
576976a05b35SChris Mason 			goto done;
577076a05b35SChris Mason 		}
577176a05b35SChris Mason 
57725cd57b2cSChris Mason 		if (!path->skip_locking) {
5773bd681513SChris Mason 			ret = btrfs_try_tree_read_lock(next);
5774d42244a0SJan Schmidt 			if (!ret && time_seq) {
5775d42244a0SJan Schmidt 				/*
5776d42244a0SJan Schmidt 				 * If we don't get the lock, we may be racing
5777d42244a0SJan Schmidt 				 * with push_leaf_left, holding that lock while
5778d42244a0SJan Schmidt 				 * itself waiting for the leaf we've currently
5779d42244a0SJan Schmidt 				 * locked. To solve this situation, we give up
5780d42244a0SJan Schmidt 				 * on our lock and cycle.
5781d42244a0SJan Schmidt 				 */
5782cf538830SJan Schmidt 				free_extent_buffer(next);
5783d42244a0SJan Schmidt 				btrfs_release_path(path);
5784d42244a0SJan Schmidt 				cond_resched();
5785d42244a0SJan Schmidt 				goto again;
5786d42244a0SJan Schmidt 			}
57878e73f275SChris Mason 			if (!ret) {
57888e73f275SChris Mason 				btrfs_set_path_blocking(path);
5789bd681513SChris Mason 				btrfs_tree_read_lock(next);
5790bd681513SChris Mason 				btrfs_clear_path_blocking(path, next,
5791bd681513SChris Mason 							  BTRFS_READ_LOCK);
57928e73f275SChris Mason 			}
5793bd681513SChris Mason 			next_rw_lock = BTRFS_READ_LOCK;
5794bd681513SChris Mason 		}
5795d97e63b6SChris Mason 		break;
5796d97e63b6SChris Mason 	}
5797d97e63b6SChris Mason 	path->slots[level] = slot;
5798d97e63b6SChris Mason 	while (1) {
5799d97e63b6SChris Mason 		level--;
5800d97e63b6SChris Mason 		c = path->nodes[level];
5801925baeddSChris Mason 		if (path->locks[level])
5802bd681513SChris Mason 			btrfs_tree_unlock_rw(c, path->locks[level]);
58038e73f275SChris Mason 
58045f39d397SChris Mason 		free_extent_buffer(c);
5805d97e63b6SChris Mason 		path->nodes[level] = next;
5806d97e63b6SChris Mason 		path->slots[level] = 0;
5807a74a4b97SChris Mason 		if (!path->skip_locking)
5808bd681513SChris Mason 			path->locks[level] = next_rw_lock;
5809d97e63b6SChris Mason 		if (!level)
5810d97e63b6SChris Mason 			break;
5811b4ce94deSChris Mason 
58128e73f275SChris Mason 		ret = read_block_for_search(NULL, root, path, &next, level,
58135d9e75c4SJan Schmidt 					    0, &key, 0);
58148e73f275SChris Mason 		if (ret == -EAGAIN)
58158e73f275SChris Mason 			goto again;
58168e73f275SChris Mason 
581776a05b35SChris Mason 		if (ret < 0) {
5818b3b4aa74SDavid Sterba 			btrfs_release_path(path);
581976a05b35SChris Mason 			goto done;
582076a05b35SChris Mason 		}
582176a05b35SChris Mason 
58225cd57b2cSChris Mason 		if (!path->skip_locking) {
5823bd681513SChris Mason 			ret = btrfs_try_tree_read_lock(next);
58248e73f275SChris Mason 			if (!ret) {
58258e73f275SChris Mason 				btrfs_set_path_blocking(path);
5826bd681513SChris Mason 				btrfs_tree_read_lock(next);
5827bd681513SChris Mason 				btrfs_clear_path_blocking(path, next,
5828bd681513SChris Mason 							  BTRFS_READ_LOCK);
58298e73f275SChris Mason 			}
5830bd681513SChris Mason 			next_rw_lock = BTRFS_READ_LOCK;
5831bd681513SChris Mason 		}
5832d97e63b6SChris Mason 	}
58338e73f275SChris Mason 	ret = 0;
5834925baeddSChris Mason done:
5835f7c79f30SChris Mason 	unlock_up(path, 0, 1, 0, NULL);
58368e73f275SChris Mason 	path->leave_spinning = old_spinning;
58378e73f275SChris Mason 	if (!old_spinning)
58388e73f275SChris Mason 		btrfs_set_path_blocking(path);
58398e73f275SChris Mason 
58408e73f275SChris Mason 	return ret;
5841d97e63b6SChris Mason }
58420b86a832SChris Mason 
58433f157a2fSChris Mason /*
58443f157a2fSChris Mason  * this uses btrfs_prev_leaf to walk backwards in the tree, and keeps
58453f157a2fSChris Mason  * searching until it gets past min_objectid or finds an item of 'type'
58463f157a2fSChris Mason  *
58473f157a2fSChris Mason  * returns 0 if something is found, 1 if nothing was found and < 0 on error
58483f157a2fSChris Mason  */
58490b86a832SChris Mason int btrfs_previous_item(struct btrfs_root *root,
58500b86a832SChris Mason 			struct btrfs_path *path, u64 min_objectid,
58510b86a832SChris Mason 			int type)
58520b86a832SChris Mason {
58530b86a832SChris Mason 	struct btrfs_key found_key;
58540b86a832SChris Mason 	struct extent_buffer *leaf;
5855e02119d5SChris Mason 	u32 nritems;
58560b86a832SChris Mason 	int ret;
58570b86a832SChris Mason 
58580b86a832SChris Mason 	while (1) {
58590b86a832SChris Mason 		if (path->slots[0] == 0) {
5860b4ce94deSChris Mason 			btrfs_set_path_blocking(path);
58610b86a832SChris Mason 			ret = btrfs_prev_leaf(root, path);
58620b86a832SChris Mason 			if (ret != 0)
58630b86a832SChris Mason 				return ret;
58640b86a832SChris Mason 		} else {
58650b86a832SChris Mason 			path->slots[0]--;
58660b86a832SChris Mason 		}
58670b86a832SChris Mason 		leaf = path->nodes[0];
5868e02119d5SChris Mason 		nritems = btrfs_header_nritems(leaf);
5869e02119d5SChris Mason 		if (nritems == 0)
5870e02119d5SChris Mason 			return 1;
5871e02119d5SChris Mason 		if (path->slots[0] == nritems)
5872e02119d5SChris Mason 			path->slots[0]--;
5873e02119d5SChris Mason 
58740b86a832SChris Mason 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5875e02119d5SChris Mason 		if (found_key.objectid < min_objectid)
5876e02119d5SChris Mason 			break;
58770a4eefbbSYan Zheng 		if (found_key.type == type)
58780a4eefbbSYan Zheng 			return 0;
5879e02119d5SChris Mason 		if (found_key.objectid == min_objectid &&
5880e02119d5SChris Mason 		    found_key.type < type)
5881e02119d5SChris Mason 			break;
58820b86a832SChris Mason 	}
58830b86a832SChris Mason 	return 1;
58840b86a832SChris Mason }
5885ade2e0b3SWang Shilong 
5886ade2e0b3SWang Shilong /*
5887ade2e0b3SWang Shilong  * search in extent tree to find a previous Metadata/Data extent item with
5888ade2e0b3SWang Shilong  * min objecitd.
5889ade2e0b3SWang Shilong  *
5890ade2e0b3SWang Shilong  * returns 0 if something is found, 1 if nothing was found and < 0 on error
5891ade2e0b3SWang Shilong  */
5892ade2e0b3SWang Shilong int btrfs_previous_extent_item(struct btrfs_root *root,
5893ade2e0b3SWang Shilong 			struct btrfs_path *path, u64 min_objectid)
5894ade2e0b3SWang Shilong {
5895ade2e0b3SWang Shilong 	struct btrfs_key found_key;
5896ade2e0b3SWang Shilong 	struct extent_buffer *leaf;
5897ade2e0b3SWang Shilong 	u32 nritems;
5898ade2e0b3SWang Shilong 	int ret;
5899ade2e0b3SWang Shilong 
5900ade2e0b3SWang Shilong 	while (1) {
5901ade2e0b3SWang Shilong 		if (path->slots[0] == 0) {
5902ade2e0b3SWang Shilong 			btrfs_set_path_blocking(path);
5903ade2e0b3SWang Shilong 			ret = btrfs_prev_leaf(root, path);
5904ade2e0b3SWang Shilong 			if (ret != 0)
5905ade2e0b3SWang Shilong 				return ret;
5906ade2e0b3SWang Shilong 		} else {
5907ade2e0b3SWang Shilong 			path->slots[0]--;
5908ade2e0b3SWang Shilong 		}
5909ade2e0b3SWang Shilong 		leaf = path->nodes[0];
5910ade2e0b3SWang Shilong 		nritems = btrfs_header_nritems(leaf);
5911ade2e0b3SWang Shilong 		if (nritems == 0)
5912ade2e0b3SWang Shilong 			return 1;
5913ade2e0b3SWang Shilong 		if (path->slots[0] == nritems)
5914ade2e0b3SWang Shilong 			path->slots[0]--;
5915ade2e0b3SWang Shilong 
5916ade2e0b3SWang Shilong 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5917ade2e0b3SWang Shilong 		if (found_key.objectid < min_objectid)
5918ade2e0b3SWang Shilong 			break;
5919ade2e0b3SWang Shilong 		if (found_key.type == BTRFS_EXTENT_ITEM_KEY ||
5920ade2e0b3SWang Shilong 		    found_key.type == BTRFS_METADATA_ITEM_KEY)
5921ade2e0b3SWang Shilong 			return 0;
5922ade2e0b3SWang Shilong 		if (found_key.objectid == min_objectid &&
5923ade2e0b3SWang Shilong 		    found_key.type < BTRFS_EXTENT_ITEM_KEY)
5924ade2e0b3SWang Shilong 			break;
5925ade2e0b3SWang Shilong 	}
5926ade2e0b3SWang Shilong 	return 1;
5927ade2e0b3SWang Shilong }
5928