xref: /openbmc/linux/fs/btrfs/ctree.c (revision 83d4cfd4da57b6ff16296875a962de2158799de6)
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);
42f230475eSJan Schmidt static void tree_mod_log_free_eb(struct btrfs_fs_info *fs_info,
43f230475eSJan Schmidt 				 struct extent_buffer *eb);
4448a3b636SEric Sandeen static int btrfs_prev_leaf(struct btrfs_root *root, struct btrfs_path *path);
45d97e63b6SChris Mason 
462c90e5d6SChris Mason struct btrfs_path *btrfs_alloc_path(void)
472c90e5d6SChris Mason {
48df24a2b9SChris Mason 	struct btrfs_path *path;
49e00f7308SJeff Mahoney 	path = kmem_cache_zalloc(btrfs_path_cachep, GFP_NOFS);
50df24a2b9SChris Mason 	return path;
512c90e5d6SChris Mason }
522c90e5d6SChris Mason 
53b4ce94deSChris Mason /*
54b4ce94deSChris Mason  * set all locked nodes in the path to blocking locks.  This should
55b4ce94deSChris Mason  * be done before scheduling
56b4ce94deSChris Mason  */
57b4ce94deSChris Mason noinline void btrfs_set_path_blocking(struct btrfs_path *p)
58b4ce94deSChris Mason {
59b4ce94deSChris Mason 	int i;
60b4ce94deSChris Mason 	for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
61bd681513SChris Mason 		if (!p->nodes[i] || !p->locks[i])
62bd681513SChris Mason 			continue;
63bd681513SChris Mason 		btrfs_set_lock_blocking_rw(p->nodes[i], p->locks[i]);
64bd681513SChris Mason 		if (p->locks[i] == BTRFS_READ_LOCK)
65bd681513SChris Mason 			p->locks[i] = BTRFS_READ_LOCK_BLOCKING;
66bd681513SChris Mason 		else if (p->locks[i] == BTRFS_WRITE_LOCK)
67bd681513SChris Mason 			p->locks[i] = BTRFS_WRITE_LOCK_BLOCKING;
68b4ce94deSChris Mason 	}
69b4ce94deSChris Mason }
70b4ce94deSChris Mason 
71b4ce94deSChris Mason /*
72b4ce94deSChris Mason  * reset all the locked nodes in the patch to spinning locks.
734008c04aSChris Mason  *
744008c04aSChris Mason  * held is used to keep lockdep happy, when lockdep is enabled
754008c04aSChris Mason  * we set held to a blocking lock before we go around and
764008c04aSChris Mason  * retake all the spinlocks in the path.  You can safely use NULL
774008c04aSChris Mason  * for held
78b4ce94deSChris Mason  */
794008c04aSChris Mason noinline void btrfs_clear_path_blocking(struct btrfs_path *p,
80bd681513SChris Mason 					struct extent_buffer *held, int held_rw)
81b4ce94deSChris Mason {
82b4ce94deSChris Mason 	int i;
834008c04aSChris Mason 
844008c04aSChris Mason #ifdef CONFIG_DEBUG_LOCK_ALLOC
854008c04aSChris Mason 	/* lockdep really cares that we take all of these spinlocks
864008c04aSChris Mason 	 * in the right order.  If any of the locks in the path are not
874008c04aSChris Mason 	 * currently blocking, it is going to complain.  So, make really
884008c04aSChris Mason 	 * really sure by forcing the path to blocking before we clear
894008c04aSChris Mason 	 * the path blocking.
904008c04aSChris Mason 	 */
91bd681513SChris Mason 	if (held) {
92bd681513SChris Mason 		btrfs_set_lock_blocking_rw(held, held_rw);
93bd681513SChris Mason 		if (held_rw == BTRFS_WRITE_LOCK)
94bd681513SChris Mason 			held_rw = BTRFS_WRITE_LOCK_BLOCKING;
95bd681513SChris Mason 		else if (held_rw == BTRFS_READ_LOCK)
96bd681513SChris Mason 			held_rw = BTRFS_READ_LOCK_BLOCKING;
97bd681513SChris Mason 	}
984008c04aSChris Mason 	btrfs_set_path_blocking(p);
994008c04aSChris Mason #endif
1004008c04aSChris Mason 
1014008c04aSChris Mason 	for (i = BTRFS_MAX_LEVEL - 1; i >= 0; i--) {
102bd681513SChris Mason 		if (p->nodes[i] && p->locks[i]) {
103bd681513SChris Mason 			btrfs_clear_lock_blocking_rw(p->nodes[i], p->locks[i]);
104bd681513SChris Mason 			if (p->locks[i] == BTRFS_WRITE_LOCK_BLOCKING)
105bd681513SChris Mason 				p->locks[i] = BTRFS_WRITE_LOCK;
106bd681513SChris Mason 			else if (p->locks[i] == BTRFS_READ_LOCK_BLOCKING)
107bd681513SChris Mason 				p->locks[i] = BTRFS_READ_LOCK;
108bd681513SChris Mason 		}
109b4ce94deSChris Mason 	}
1104008c04aSChris Mason 
1114008c04aSChris Mason #ifdef CONFIG_DEBUG_LOCK_ALLOC
1124008c04aSChris Mason 	if (held)
113bd681513SChris Mason 		btrfs_clear_lock_blocking_rw(held, held_rw);
1144008c04aSChris Mason #endif
115b4ce94deSChris Mason }
116b4ce94deSChris Mason 
117d352ac68SChris Mason /* this also releases the path */
1182c90e5d6SChris Mason void btrfs_free_path(struct btrfs_path *p)
1192c90e5d6SChris Mason {
120ff175d57SJesper Juhl 	if (!p)
121ff175d57SJesper Juhl 		return;
122b3b4aa74SDavid Sterba 	btrfs_release_path(p);
1232c90e5d6SChris Mason 	kmem_cache_free(btrfs_path_cachep, p);
1242c90e5d6SChris Mason }
1252c90e5d6SChris Mason 
126d352ac68SChris Mason /*
127d352ac68SChris Mason  * path release drops references on the extent buffers in the path
128d352ac68SChris Mason  * and it drops any locks held by this path
129d352ac68SChris Mason  *
130d352ac68SChris Mason  * It is safe to call this on paths that no locks or extent buffers held.
131d352ac68SChris Mason  */
132b3b4aa74SDavid Sterba noinline void btrfs_release_path(struct btrfs_path *p)
133eb60ceacSChris Mason {
134eb60ceacSChris Mason 	int i;
135a2135011SChris Mason 
136234b63a0SChris Mason 	for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
1373f157a2fSChris Mason 		p->slots[i] = 0;
138eb60ceacSChris Mason 		if (!p->nodes[i])
139925baeddSChris Mason 			continue;
140925baeddSChris Mason 		if (p->locks[i]) {
141bd681513SChris Mason 			btrfs_tree_unlock_rw(p->nodes[i], p->locks[i]);
142925baeddSChris Mason 			p->locks[i] = 0;
143925baeddSChris Mason 		}
1445f39d397SChris Mason 		free_extent_buffer(p->nodes[i]);
1453f157a2fSChris Mason 		p->nodes[i] = NULL;
146eb60ceacSChris Mason 	}
147eb60ceacSChris Mason }
148eb60ceacSChris Mason 
149d352ac68SChris Mason /*
150d352ac68SChris Mason  * safely gets a reference on the root node of a tree.  A lock
151d352ac68SChris Mason  * is not taken, so a concurrent writer may put a different node
152d352ac68SChris Mason  * at the root of the tree.  See btrfs_lock_root_node for the
153d352ac68SChris Mason  * looping required.
154d352ac68SChris Mason  *
155d352ac68SChris Mason  * The extent buffer returned by this has a reference taken, so
156d352ac68SChris Mason  * it won't disappear.  It may stop being the root of the tree
157d352ac68SChris Mason  * at any time because there are no locks held.
158d352ac68SChris Mason  */
159925baeddSChris Mason struct extent_buffer *btrfs_root_node(struct btrfs_root *root)
160925baeddSChris Mason {
161925baeddSChris Mason 	struct extent_buffer *eb;
162240f62c8SChris Mason 
1633083ee2eSJosef Bacik 	while (1) {
164240f62c8SChris Mason 		rcu_read_lock();
165240f62c8SChris Mason 		eb = rcu_dereference(root->node);
1663083ee2eSJosef Bacik 
1673083ee2eSJosef Bacik 		/*
1683083ee2eSJosef Bacik 		 * RCU really hurts here, we could free up the root node because
1693083ee2eSJosef Bacik 		 * it was cow'ed but we may not get the new root node yet so do
1703083ee2eSJosef Bacik 		 * the inc_not_zero dance and if it doesn't work then
1713083ee2eSJosef Bacik 		 * synchronize_rcu and try again.
1723083ee2eSJosef Bacik 		 */
1733083ee2eSJosef Bacik 		if (atomic_inc_not_zero(&eb->refs)) {
174240f62c8SChris Mason 			rcu_read_unlock();
1753083ee2eSJosef Bacik 			break;
1763083ee2eSJosef Bacik 		}
1773083ee2eSJosef Bacik 		rcu_read_unlock();
1783083ee2eSJosef Bacik 		synchronize_rcu();
1793083ee2eSJosef Bacik 	}
180925baeddSChris Mason 	return eb;
181925baeddSChris Mason }
182925baeddSChris Mason 
183d352ac68SChris Mason /* loop around taking references on and locking the root node of the
184d352ac68SChris Mason  * tree until you end up with a lock on the root.  A locked buffer
185d352ac68SChris Mason  * is returned, with a reference held.
186d352ac68SChris Mason  */
187925baeddSChris Mason struct extent_buffer *btrfs_lock_root_node(struct btrfs_root *root)
188925baeddSChris Mason {
189925baeddSChris Mason 	struct extent_buffer *eb;
190925baeddSChris Mason 
191925baeddSChris Mason 	while (1) {
192925baeddSChris Mason 		eb = btrfs_root_node(root);
193925baeddSChris Mason 		btrfs_tree_lock(eb);
194240f62c8SChris Mason 		if (eb == root->node)
195925baeddSChris Mason 			break;
196925baeddSChris Mason 		btrfs_tree_unlock(eb);
197925baeddSChris Mason 		free_extent_buffer(eb);
198925baeddSChris Mason 	}
199925baeddSChris Mason 	return eb;
200925baeddSChris Mason }
201925baeddSChris Mason 
202bd681513SChris Mason /* loop around taking references on and locking the root node of the
203bd681513SChris Mason  * tree until you end up with a lock on the root.  A locked buffer
204bd681513SChris Mason  * is returned, with a reference held.
205bd681513SChris Mason  */
20648a3b636SEric Sandeen static struct extent_buffer *btrfs_read_lock_root_node(struct btrfs_root *root)
207bd681513SChris Mason {
208bd681513SChris Mason 	struct extent_buffer *eb;
209bd681513SChris Mason 
210bd681513SChris Mason 	while (1) {
211bd681513SChris Mason 		eb = btrfs_root_node(root);
212bd681513SChris Mason 		btrfs_tree_read_lock(eb);
213bd681513SChris Mason 		if (eb == root->node)
214bd681513SChris Mason 			break;
215bd681513SChris Mason 		btrfs_tree_read_unlock(eb);
216bd681513SChris Mason 		free_extent_buffer(eb);
217bd681513SChris Mason 	}
218bd681513SChris Mason 	return eb;
219bd681513SChris Mason }
220bd681513SChris Mason 
221d352ac68SChris Mason /* cowonly root (everything not a reference counted cow subvolume), just get
222d352ac68SChris Mason  * put onto a simple dirty list.  transaction.c walks this to make sure they
223d352ac68SChris Mason  * get properly updated on disk.
224d352ac68SChris Mason  */
2250b86a832SChris Mason static void add_root_to_dirty_list(struct btrfs_root *root)
2260b86a832SChris Mason {
227e5846fc6SChris Mason 	spin_lock(&root->fs_info->trans_lock);
2280b86a832SChris Mason 	if (root->track_dirty && 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 
250be20aa9dSChris Mason 	WARN_ON(root->ref_cows && trans->transid !=
251be20aa9dSChris Mason 		root->fs_info->running_transaction->transid);
252be20aa9dSChris Mason 	WARN_ON(root->ref_cows && trans->transid != root->last_trans);
253be20aa9dSChris Mason 
254be20aa9dSChris Mason 	level = btrfs_header_level(buf);
2555d4f98a2SYan Zheng 	if (level == 0)
2565d4f98a2SYan Zheng 		btrfs_item_key(buf, &disk_key, 0);
2575d4f98a2SYan Zheng 	else
2585d4f98a2SYan Zheng 		btrfs_node_key(buf, &disk_key, 0);
25931840ae1SZheng Yan 
2605d4f98a2SYan Zheng 	cow = btrfs_alloc_free_block(trans, root, buf->len, 0,
2615d4f98a2SYan Zheng 				     new_root_objectid, &disk_key, level,
2625581a51aSJan Schmidt 				     buf->start, 0);
2635d4f98a2SYan Zheng 	if (IS_ERR(cow))
264be20aa9dSChris Mason 		return PTR_ERR(cow);
265be20aa9dSChris Mason 
266be20aa9dSChris Mason 	copy_extent_buffer(cow, buf, 0, 0, cow->len);
267be20aa9dSChris Mason 	btrfs_set_header_bytenr(cow, cow->start);
268be20aa9dSChris Mason 	btrfs_set_header_generation(cow, trans->transid);
2695d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
2705d4f98a2SYan Zheng 	btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
2715d4f98a2SYan Zheng 				     BTRFS_HEADER_FLAG_RELOC);
2725d4f98a2SYan Zheng 	if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
2735d4f98a2SYan Zheng 		btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
2745d4f98a2SYan Zheng 	else
275be20aa9dSChris Mason 		btrfs_set_header_owner(cow, new_root_objectid);
276be20aa9dSChris Mason 
277fba6aa75SGeert Uytterhoeven 	write_extent_buffer(cow, root->fs_info->fsid, btrfs_header_fsid(cow),
2782b82032cSYan Zheng 			    BTRFS_FSID_SIZE);
2792b82032cSYan Zheng 
280be20aa9dSChris Mason 	WARN_ON(btrfs_header_generation(buf) > trans->transid);
2815d4f98a2SYan Zheng 	if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
28266d7e7f0SArne Jansen 		ret = btrfs_inc_ref(trans, root, cow, 1, 1);
2835d4f98a2SYan Zheng 	else
28466d7e7f0SArne Jansen 		ret = btrfs_inc_ref(trans, root, cow, 0, 1);
2854aec2b52SChris Mason 
286be20aa9dSChris Mason 	if (ret)
287be20aa9dSChris Mason 		return ret;
288be20aa9dSChris Mason 
289be20aa9dSChris Mason 	btrfs_mark_buffer_dirty(cow);
290be20aa9dSChris Mason 	*cow_ret = cow;
291be20aa9dSChris Mason 	return 0;
292be20aa9dSChris Mason }
293be20aa9dSChris Mason 
294bd989ba3SJan Schmidt enum mod_log_op {
295bd989ba3SJan Schmidt 	MOD_LOG_KEY_REPLACE,
296bd989ba3SJan Schmidt 	MOD_LOG_KEY_ADD,
297bd989ba3SJan Schmidt 	MOD_LOG_KEY_REMOVE,
298bd989ba3SJan Schmidt 	MOD_LOG_KEY_REMOVE_WHILE_FREEING,
299bd989ba3SJan Schmidt 	MOD_LOG_KEY_REMOVE_WHILE_MOVING,
300bd989ba3SJan Schmidt 	MOD_LOG_MOVE_KEYS,
301bd989ba3SJan Schmidt 	MOD_LOG_ROOT_REPLACE,
302bd989ba3SJan Schmidt };
303bd989ba3SJan Schmidt 
304bd989ba3SJan Schmidt struct tree_mod_move {
305bd989ba3SJan Schmidt 	int dst_slot;
306bd989ba3SJan Schmidt 	int nr_items;
307bd989ba3SJan Schmidt };
308bd989ba3SJan Schmidt 
309bd989ba3SJan Schmidt struct tree_mod_root {
310bd989ba3SJan Schmidt 	u64 logical;
311bd989ba3SJan Schmidt 	u8 level;
312bd989ba3SJan Schmidt };
313bd989ba3SJan Schmidt 
314bd989ba3SJan Schmidt struct tree_mod_elem {
315bd989ba3SJan Schmidt 	struct rb_node node;
316bd989ba3SJan Schmidt 	u64 index;		/* shifted logical */
317097b8a7cSJan Schmidt 	u64 seq;
318bd989ba3SJan Schmidt 	enum mod_log_op op;
319bd989ba3SJan Schmidt 
320bd989ba3SJan Schmidt 	/* this is used for MOD_LOG_KEY_* and MOD_LOG_MOVE_KEYS operations */
321bd989ba3SJan Schmidt 	int slot;
322bd989ba3SJan Schmidt 
323bd989ba3SJan Schmidt 	/* this is used for MOD_LOG_KEY* and MOD_LOG_ROOT_REPLACE */
324bd989ba3SJan Schmidt 	u64 generation;
325bd989ba3SJan Schmidt 
326bd989ba3SJan Schmidt 	/* those are used for op == MOD_LOG_KEY_{REPLACE,REMOVE} */
327bd989ba3SJan Schmidt 	struct btrfs_disk_key key;
328bd989ba3SJan Schmidt 	u64 blockptr;
329bd989ba3SJan Schmidt 
330bd989ba3SJan Schmidt 	/* this is used for op == MOD_LOG_MOVE_KEYS */
331bd989ba3SJan Schmidt 	struct tree_mod_move move;
332bd989ba3SJan Schmidt 
333bd989ba3SJan Schmidt 	/* this is used for op == MOD_LOG_ROOT_REPLACE */
334bd989ba3SJan Schmidt 	struct tree_mod_root old_root;
335bd989ba3SJan Schmidt };
336bd989ba3SJan Schmidt 
337097b8a7cSJan Schmidt static inline void tree_mod_log_read_lock(struct btrfs_fs_info *fs_info)
338bd989ba3SJan Schmidt {
339097b8a7cSJan Schmidt 	read_lock(&fs_info->tree_mod_log_lock);
340bd989ba3SJan Schmidt }
341bd989ba3SJan Schmidt 
342097b8a7cSJan Schmidt static inline void tree_mod_log_read_unlock(struct btrfs_fs_info *fs_info)
343097b8a7cSJan Schmidt {
344097b8a7cSJan Schmidt 	read_unlock(&fs_info->tree_mod_log_lock);
345097b8a7cSJan Schmidt }
346097b8a7cSJan Schmidt 
347097b8a7cSJan Schmidt static inline void tree_mod_log_write_lock(struct btrfs_fs_info *fs_info)
348097b8a7cSJan Schmidt {
349097b8a7cSJan Schmidt 	write_lock(&fs_info->tree_mod_log_lock);
350097b8a7cSJan Schmidt }
351097b8a7cSJan Schmidt 
352097b8a7cSJan Schmidt static inline void tree_mod_log_write_unlock(struct btrfs_fs_info *fs_info)
353097b8a7cSJan Schmidt {
354097b8a7cSJan Schmidt 	write_unlock(&fs_info->tree_mod_log_lock);
355097b8a7cSJan Schmidt }
356097b8a7cSJan Schmidt 
357097b8a7cSJan Schmidt /*
358fc36ed7eSJan Schmidt  * Increment the upper half of tree_mod_seq, set lower half zero.
359fc36ed7eSJan Schmidt  *
360fc36ed7eSJan Schmidt  * Must be called with fs_info->tree_mod_seq_lock held.
361fc36ed7eSJan Schmidt  */
362fc36ed7eSJan Schmidt static inline u64 btrfs_inc_tree_mod_seq_major(struct btrfs_fs_info *fs_info)
363fc36ed7eSJan Schmidt {
364fc36ed7eSJan Schmidt 	u64 seq = atomic64_read(&fs_info->tree_mod_seq);
365fc36ed7eSJan Schmidt 	seq &= 0xffffffff00000000ull;
366fc36ed7eSJan Schmidt 	seq += 1ull << 32;
367fc36ed7eSJan Schmidt 	atomic64_set(&fs_info->tree_mod_seq, seq);
368fc36ed7eSJan Schmidt 	return seq;
369fc36ed7eSJan Schmidt }
370fc36ed7eSJan Schmidt 
371fc36ed7eSJan Schmidt /*
372fc36ed7eSJan Schmidt  * Increment the lower half of tree_mod_seq.
373fc36ed7eSJan Schmidt  *
374fc36ed7eSJan Schmidt  * Must be called with fs_info->tree_mod_seq_lock held. The way major numbers
375fc36ed7eSJan Schmidt  * are generated should not technically require a spin lock here. (Rationale:
376fc36ed7eSJan Schmidt  * incrementing the minor while incrementing the major seq number is between its
377fc36ed7eSJan Schmidt  * atomic64_read and atomic64_set calls doesn't duplicate sequence numbers, it
378fc36ed7eSJan Schmidt  * just returns a unique sequence number as usual.) We have decided to leave
379fc36ed7eSJan Schmidt  * that requirement in here and rethink it once we notice it really imposes a
380fc36ed7eSJan Schmidt  * problem on some workload.
381fc36ed7eSJan Schmidt  */
382fc36ed7eSJan Schmidt static inline u64 btrfs_inc_tree_mod_seq_minor(struct btrfs_fs_info *fs_info)
383fc36ed7eSJan Schmidt {
384fc36ed7eSJan Schmidt 	return atomic64_inc_return(&fs_info->tree_mod_seq);
385fc36ed7eSJan Schmidt }
386fc36ed7eSJan Schmidt 
387fc36ed7eSJan Schmidt /*
388fc36ed7eSJan Schmidt  * return the last minor in the previous major tree_mod_seq number
389fc36ed7eSJan Schmidt  */
390fc36ed7eSJan Schmidt u64 btrfs_tree_mod_seq_prev(u64 seq)
391fc36ed7eSJan Schmidt {
392fc36ed7eSJan Schmidt 	return (seq & 0xffffffff00000000ull) - 1ull;
393fc36ed7eSJan Schmidt }
394fc36ed7eSJan Schmidt 
395fc36ed7eSJan Schmidt /*
396097b8a7cSJan Schmidt  * This adds a new blocker to the tree mod log's blocker list if the @elem
397097b8a7cSJan Schmidt  * passed does not already have a sequence number set. So when a caller expects
398097b8a7cSJan Schmidt  * to record tree modifications, it should ensure to set elem->seq to zero
399097b8a7cSJan Schmidt  * before calling btrfs_get_tree_mod_seq.
400097b8a7cSJan Schmidt  * Returns a fresh, unused tree log modification sequence number, even if no new
401097b8a7cSJan Schmidt  * blocker was added.
402097b8a7cSJan Schmidt  */
403097b8a7cSJan Schmidt u64 btrfs_get_tree_mod_seq(struct btrfs_fs_info *fs_info,
404bd989ba3SJan Schmidt 			   struct seq_list *elem)
405bd989ba3SJan Schmidt {
406097b8a7cSJan Schmidt 	u64 seq;
407097b8a7cSJan Schmidt 
408097b8a7cSJan Schmidt 	tree_mod_log_write_lock(fs_info);
409bd989ba3SJan Schmidt 	spin_lock(&fs_info->tree_mod_seq_lock);
410097b8a7cSJan Schmidt 	if (!elem->seq) {
411fc36ed7eSJan Schmidt 		elem->seq = btrfs_inc_tree_mod_seq_major(fs_info);
412097b8a7cSJan Schmidt 		list_add_tail(&elem->list, &fs_info->tree_mod_seq_list);
413097b8a7cSJan Schmidt 	}
414fc36ed7eSJan Schmidt 	seq = btrfs_inc_tree_mod_seq_minor(fs_info);
415bd989ba3SJan Schmidt 	spin_unlock(&fs_info->tree_mod_seq_lock);
416097b8a7cSJan Schmidt 	tree_mod_log_write_unlock(fs_info);
417097b8a7cSJan Schmidt 
418097b8a7cSJan Schmidt 	return seq;
419bd989ba3SJan Schmidt }
420bd989ba3SJan Schmidt 
421bd989ba3SJan Schmidt void btrfs_put_tree_mod_seq(struct btrfs_fs_info *fs_info,
422bd989ba3SJan Schmidt 			    struct seq_list *elem)
423bd989ba3SJan Schmidt {
424bd989ba3SJan Schmidt 	struct rb_root *tm_root;
425bd989ba3SJan Schmidt 	struct rb_node *node;
426bd989ba3SJan Schmidt 	struct rb_node *next;
427bd989ba3SJan Schmidt 	struct seq_list *cur_elem;
428bd989ba3SJan Schmidt 	struct tree_mod_elem *tm;
429bd989ba3SJan Schmidt 	u64 min_seq = (u64)-1;
430bd989ba3SJan Schmidt 	u64 seq_putting = elem->seq;
431bd989ba3SJan Schmidt 
432bd989ba3SJan Schmidt 	if (!seq_putting)
433bd989ba3SJan Schmidt 		return;
434bd989ba3SJan Schmidt 
435bd989ba3SJan Schmidt 	spin_lock(&fs_info->tree_mod_seq_lock);
436bd989ba3SJan Schmidt 	list_del(&elem->list);
437097b8a7cSJan Schmidt 	elem->seq = 0;
438bd989ba3SJan Schmidt 
439bd989ba3SJan Schmidt 	list_for_each_entry(cur_elem, &fs_info->tree_mod_seq_list, list) {
440097b8a7cSJan Schmidt 		if (cur_elem->seq < min_seq) {
441bd989ba3SJan Schmidt 			if (seq_putting > cur_elem->seq) {
442bd989ba3SJan Schmidt 				/*
443bd989ba3SJan Schmidt 				 * blocker with lower sequence number exists, we
444bd989ba3SJan Schmidt 				 * cannot remove anything from the log
445bd989ba3SJan Schmidt 				 */
446097b8a7cSJan Schmidt 				spin_unlock(&fs_info->tree_mod_seq_lock);
447097b8a7cSJan Schmidt 				return;
448bd989ba3SJan Schmidt 			}
449bd989ba3SJan Schmidt 			min_seq = cur_elem->seq;
450bd989ba3SJan Schmidt 		}
451bd989ba3SJan Schmidt 	}
452097b8a7cSJan Schmidt 	spin_unlock(&fs_info->tree_mod_seq_lock);
453097b8a7cSJan Schmidt 
454097b8a7cSJan Schmidt 	/*
455bd989ba3SJan Schmidt 	 * anything that's lower than the lowest existing (read: blocked)
456bd989ba3SJan Schmidt 	 * sequence number can be removed from the tree.
457bd989ba3SJan Schmidt 	 */
458097b8a7cSJan Schmidt 	tree_mod_log_write_lock(fs_info);
459bd989ba3SJan Schmidt 	tm_root = &fs_info->tree_mod_log;
460bd989ba3SJan Schmidt 	for (node = rb_first(tm_root); node; node = next) {
461bd989ba3SJan Schmidt 		next = rb_next(node);
462bd989ba3SJan Schmidt 		tm = container_of(node, struct tree_mod_elem, node);
463097b8a7cSJan Schmidt 		if (tm->seq > min_seq)
464bd989ba3SJan Schmidt 			continue;
465bd989ba3SJan Schmidt 		rb_erase(node, tm_root);
466bd989ba3SJan Schmidt 		kfree(tm);
467bd989ba3SJan Schmidt 	}
468097b8a7cSJan Schmidt 	tree_mod_log_write_unlock(fs_info);
469bd989ba3SJan Schmidt }
470bd989ba3SJan Schmidt 
471bd989ba3SJan Schmidt /*
472bd989ba3SJan Schmidt  * key order of the log:
473bd989ba3SJan Schmidt  *       index -> sequence
474bd989ba3SJan Schmidt  *
475bd989ba3SJan Schmidt  * the index is the shifted logical of the *new* root node for root replace
476bd989ba3SJan Schmidt  * operations, or the shifted logical of the affected block for all other
477bd989ba3SJan Schmidt  * operations.
478bd989ba3SJan Schmidt  */
479bd989ba3SJan Schmidt static noinline int
480bd989ba3SJan Schmidt __tree_mod_log_insert(struct btrfs_fs_info *fs_info, struct tree_mod_elem *tm)
481bd989ba3SJan Schmidt {
482bd989ba3SJan Schmidt 	struct rb_root *tm_root;
483bd989ba3SJan Schmidt 	struct rb_node **new;
484bd989ba3SJan Schmidt 	struct rb_node *parent = NULL;
485bd989ba3SJan Schmidt 	struct tree_mod_elem *cur;
486c8cc6341SJosef Bacik 	int ret = 0;
487bd989ba3SJan Schmidt 
488c8cc6341SJosef Bacik 	BUG_ON(!tm);
489c8cc6341SJosef Bacik 
490c8cc6341SJosef Bacik 	tree_mod_log_write_lock(fs_info);
491c8cc6341SJosef Bacik 	if (list_empty(&fs_info->tree_mod_seq_list)) {
492c8cc6341SJosef Bacik 		tree_mod_log_write_unlock(fs_info);
493c8cc6341SJosef Bacik 		/*
494c8cc6341SJosef Bacik 		 * Ok we no longer care about logging modifications, free up tm
495c8cc6341SJosef Bacik 		 * and return 0.  Any callers shouldn't be using tm after
496c8cc6341SJosef Bacik 		 * calling tree_mod_log_insert, but if they do we can just
497c8cc6341SJosef Bacik 		 * change this to return a special error code to let the callers
498c8cc6341SJosef Bacik 		 * do their own thing.
499c8cc6341SJosef Bacik 		 */
500c8cc6341SJosef Bacik 		kfree(tm);
501c8cc6341SJosef Bacik 		return 0;
502c8cc6341SJosef Bacik 	}
503c8cc6341SJosef Bacik 
504c8cc6341SJosef Bacik 	spin_lock(&fs_info->tree_mod_seq_lock);
505c8cc6341SJosef Bacik 	tm->seq = btrfs_inc_tree_mod_seq_minor(fs_info);
506c8cc6341SJosef Bacik 	spin_unlock(&fs_info->tree_mod_seq_lock);
507bd989ba3SJan Schmidt 
508bd989ba3SJan Schmidt 	tm_root = &fs_info->tree_mod_log;
509bd989ba3SJan Schmidt 	new = &tm_root->rb_node;
510bd989ba3SJan Schmidt 	while (*new) {
511bd989ba3SJan Schmidt 		cur = container_of(*new, struct tree_mod_elem, node);
512bd989ba3SJan Schmidt 		parent = *new;
513bd989ba3SJan Schmidt 		if (cur->index < tm->index)
514bd989ba3SJan Schmidt 			new = &((*new)->rb_left);
515bd989ba3SJan Schmidt 		else if (cur->index > tm->index)
516bd989ba3SJan Schmidt 			new = &((*new)->rb_right);
517097b8a7cSJan Schmidt 		else if (cur->seq < tm->seq)
518bd989ba3SJan Schmidt 			new = &((*new)->rb_left);
519097b8a7cSJan Schmidt 		else if (cur->seq > tm->seq)
520bd989ba3SJan Schmidt 			new = &((*new)->rb_right);
521bd989ba3SJan Schmidt 		else {
522c8cc6341SJosef Bacik 			ret = -EEXIST;
523bd989ba3SJan Schmidt 			kfree(tm);
524c8cc6341SJosef Bacik 			goto out;
525bd989ba3SJan Schmidt 		}
526bd989ba3SJan Schmidt 	}
527bd989ba3SJan Schmidt 
528bd989ba3SJan Schmidt 	rb_link_node(&tm->node, parent, new);
529bd989ba3SJan Schmidt 	rb_insert_color(&tm->node, tm_root);
530c8cc6341SJosef Bacik out:
531c8cc6341SJosef Bacik 	tree_mod_log_write_unlock(fs_info);
532c8cc6341SJosef Bacik 	return ret;
533bd989ba3SJan Schmidt }
534bd989ba3SJan Schmidt 
535097b8a7cSJan Schmidt /*
536097b8a7cSJan Schmidt  * Determines if logging can be omitted. Returns 1 if it can. Otherwise, it
537097b8a7cSJan Schmidt  * returns zero with the tree_mod_log_lock acquired. The caller must hold
538097b8a7cSJan Schmidt  * this until all tree mod log insertions are recorded in the rb tree and then
539097b8a7cSJan Schmidt  * call tree_mod_log_write_unlock() to release.
540097b8a7cSJan Schmidt  */
541e9b7fd4dSJan Schmidt static inline int tree_mod_dont_log(struct btrfs_fs_info *fs_info,
542e9b7fd4dSJan Schmidt 				    struct extent_buffer *eb) {
543e9b7fd4dSJan Schmidt 	smp_mb();
544e9b7fd4dSJan Schmidt 	if (list_empty(&(fs_info)->tree_mod_seq_list))
545e9b7fd4dSJan Schmidt 		return 1;
546097b8a7cSJan Schmidt 	if (eb && btrfs_header_level(eb) == 0)
547e9b7fd4dSJan Schmidt 		return 1;
548e9b7fd4dSJan Schmidt 	return 0;
549e9b7fd4dSJan Schmidt }
550e9b7fd4dSJan Schmidt 
551097b8a7cSJan Schmidt static inline int
552097b8a7cSJan Schmidt __tree_mod_log_insert_key(struct btrfs_fs_info *fs_info,
553bd989ba3SJan Schmidt 			  struct extent_buffer *eb, int slot,
554bd989ba3SJan Schmidt 			  enum mod_log_op op, gfp_t flags)
555bd989ba3SJan Schmidt {
556097b8a7cSJan Schmidt 	struct tree_mod_elem *tm;
557bd989ba3SJan Schmidt 
558c8cc6341SJosef Bacik 	tm = kzalloc(sizeof(*tm), flags);
559c8cc6341SJosef Bacik 	if (!tm)
560c8cc6341SJosef Bacik 		return -ENOMEM;
561bd989ba3SJan Schmidt 
562bd989ba3SJan Schmidt 	tm->index = eb->start >> PAGE_CACHE_SHIFT;
563bd989ba3SJan Schmidt 	if (op != MOD_LOG_KEY_ADD) {
564bd989ba3SJan Schmidt 		btrfs_node_key(eb, &tm->key, slot);
565bd989ba3SJan Schmidt 		tm->blockptr = btrfs_node_blockptr(eb, slot);
566bd989ba3SJan Schmidt 	}
567bd989ba3SJan Schmidt 	tm->op = op;
568bd989ba3SJan Schmidt 	tm->slot = slot;
569bd989ba3SJan Schmidt 	tm->generation = btrfs_node_ptr_generation(eb, slot);
570bd989ba3SJan Schmidt 
571097b8a7cSJan Schmidt 	return __tree_mod_log_insert(fs_info, tm);
572097b8a7cSJan Schmidt }
573097b8a7cSJan Schmidt 
574097b8a7cSJan Schmidt static noinline int
575c8cc6341SJosef Bacik tree_mod_log_insert_key(struct btrfs_fs_info *fs_info,
576097b8a7cSJan Schmidt 			struct extent_buffer *eb, int slot,
577097b8a7cSJan Schmidt 			enum mod_log_op op, gfp_t flags)
578097b8a7cSJan Schmidt {
579097b8a7cSJan Schmidt 	if (tree_mod_dont_log(fs_info, eb))
580097b8a7cSJan Schmidt 		return 0;
581097b8a7cSJan Schmidt 
582c8cc6341SJosef Bacik 	return __tree_mod_log_insert_key(fs_info, eb, slot, op, flags);
583097b8a7cSJan Schmidt }
584097b8a7cSJan Schmidt 
585097b8a7cSJan Schmidt static noinline int
586bd989ba3SJan Schmidt tree_mod_log_insert_move(struct btrfs_fs_info *fs_info,
587bd989ba3SJan Schmidt 			 struct extent_buffer *eb, int dst_slot, int src_slot,
588bd989ba3SJan Schmidt 			 int nr_items, gfp_t flags)
589bd989ba3SJan Schmidt {
590bd989ba3SJan Schmidt 	struct tree_mod_elem *tm;
591bd989ba3SJan Schmidt 	int ret;
592bd989ba3SJan Schmidt 	int i;
593bd989ba3SJan Schmidt 
594f395694cSJan Schmidt 	if (tree_mod_dont_log(fs_info, eb))
595f395694cSJan Schmidt 		return 0;
596bd989ba3SJan Schmidt 
59701763a2eSJan Schmidt 	/*
59801763a2eSJan Schmidt 	 * When we override something during the move, we log these removals.
59901763a2eSJan Schmidt 	 * This can only happen when we move towards the beginning of the
60001763a2eSJan Schmidt 	 * buffer, i.e. dst_slot < src_slot.
60101763a2eSJan Schmidt 	 */
602bd989ba3SJan Schmidt 	for (i = 0; i + dst_slot < src_slot && i < nr_items; i++) {
603c8cc6341SJosef Bacik 		ret = __tree_mod_log_insert_key(fs_info, eb, i + dst_slot,
604c8cc6341SJosef Bacik 				MOD_LOG_KEY_REMOVE_WHILE_MOVING, GFP_NOFS);
605bd989ba3SJan Schmidt 		BUG_ON(ret < 0);
606bd989ba3SJan Schmidt 	}
607bd989ba3SJan Schmidt 
608c8cc6341SJosef Bacik 	tm = kzalloc(sizeof(*tm), flags);
609c8cc6341SJosef Bacik 	if (!tm)
610c8cc6341SJosef Bacik 		return -ENOMEM;
611f395694cSJan Schmidt 
612bd989ba3SJan Schmidt 	tm->index = eb->start >> PAGE_CACHE_SHIFT;
613bd989ba3SJan Schmidt 	tm->slot = src_slot;
614bd989ba3SJan Schmidt 	tm->move.dst_slot = dst_slot;
615bd989ba3SJan Schmidt 	tm->move.nr_items = nr_items;
616bd989ba3SJan Schmidt 	tm->op = MOD_LOG_MOVE_KEYS;
617bd989ba3SJan Schmidt 
618c8cc6341SJosef Bacik 	return __tree_mod_log_insert(fs_info, tm);
619bd989ba3SJan Schmidt }
620bd989ba3SJan Schmidt 
621097b8a7cSJan Schmidt static inline void
622097b8a7cSJan Schmidt __tree_mod_log_free_eb(struct btrfs_fs_info *fs_info, struct extent_buffer *eb)
623097b8a7cSJan Schmidt {
624097b8a7cSJan Schmidt 	int i;
625097b8a7cSJan Schmidt 	u32 nritems;
626097b8a7cSJan Schmidt 	int ret;
627097b8a7cSJan Schmidt 
628b12a3b1eSChris Mason 	if (btrfs_header_level(eb) == 0)
629b12a3b1eSChris Mason 		return;
630b12a3b1eSChris Mason 
631097b8a7cSJan Schmidt 	nritems = btrfs_header_nritems(eb);
632097b8a7cSJan Schmidt 	for (i = nritems - 1; i >= 0; i--) {
633c8cc6341SJosef Bacik 		ret = __tree_mod_log_insert_key(fs_info, eb, i,
634c8cc6341SJosef Bacik 				MOD_LOG_KEY_REMOVE_WHILE_FREEING, GFP_NOFS);
635097b8a7cSJan Schmidt 		BUG_ON(ret < 0);
636097b8a7cSJan Schmidt 	}
637097b8a7cSJan Schmidt }
638097b8a7cSJan Schmidt 
639bd989ba3SJan Schmidt static noinline int
640bd989ba3SJan Schmidt tree_mod_log_insert_root(struct btrfs_fs_info *fs_info,
641bd989ba3SJan Schmidt 			 struct extent_buffer *old_root,
64290f8d62eSJan Schmidt 			 struct extent_buffer *new_root, gfp_t flags,
64390f8d62eSJan Schmidt 			 int log_removal)
644bd989ba3SJan Schmidt {
645bd989ba3SJan Schmidt 	struct tree_mod_elem *tm;
646bd989ba3SJan Schmidt 
647097b8a7cSJan Schmidt 	if (tree_mod_dont_log(fs_info, NULL))
648097b8a7cSJan Schmidt 		return 0;
649097b8a7cSJan Schmidt 
65090f8d62eSJan Schmidt 	if (log_removal)
651d9abbf1cSJan Schmidt 		__tree_mod_log_free_eb(fs_info, old_root);
652d9abbf1cSJan Schmidt 
653c8cc6341SJosef Bacik 	tm = kzalloc(sizeof(*tm), flags);
654c8cc6341SJosef Bacik 	if (!tm)
655c8cc6341SJosef Bacik 		return -ENOMEM;
656bd989ba3SJan Schmidt 
657bd989ba3SJan Schmidt 	tm->index = new_root->start >> PAGE_CACHE_SHIFT;
658bd989ba3SJan Schmidt 	tm->old_root.logical = old_root->start;
659bd989ba3SJan Schmidt 	tm->old_root.level = btrfs_header_level(old_root);
660bd989ba3SJan Schmidt 	tm->generation = btrfs_header_generation(old_root);
661bd989ba3SJan Schmidt 	tm->op = MOD_LOG_ROOT_REPLACE;
662bd989ba3SJan Schmidt 
663c8cc6341SJosef Bacik 	return __tree_mod_log_insert(fs_info, tm);
664bd989ba3SJan Schmidt }
665bd989ba3SJan Schmidt 
666bd989ba3SJan Schmidt static struct tree_mod_elem *
667bd989ba3SJan Schmidt __tree_mod_log_search(struct btrfs_fs_info *fs_info, u64 start, u64 min_seq,
668bd989ba3SJan Schmidt 		      int smallest)
669bd989ba3SJan Schmidt {
670bd989ba3SJan Schmidt 	struct rb_root *tm_root;
671bd989ba3SJan Schmidt 	struct rb_node *node;
672bd989ba3SJan Schmidt 	struct tree_mod_elem *cur = NULL;
673bd989ba3SJan Schmidt 	struct tree_mod_elem *found = NULL;
674bd989ba3SJan Schmidt 	u64 index = start >> PAGE_CACHE_SHIFT;
675bd989ba3SJan Schmidt 
676097b8a7cSJan Schmidt 	tree_mod_log_read_lock(fs_info);
677bd989ba3SJan Schmidt 	tm_root = &fs_info->tree_mod_log;
678bd989ba3SJan Schmidt 	node = tm_root->rb_node;
679bd989ba3SJan Schmidt 	while (node) {
680bd989ba3SJan Schmidt 		cur = container_of(node, struct tree_mod_elem, node);
681bd989ba3SJan Schmidt 		if (cur->index < index) {
682bd989ba3SJan Schmidt 			node = node->rb_left;
683bd989ba3SJan Schmidt 		} else if (cur->index > index) {
684bd989ba3SJan Schmidt 			node = node->rb_right;
685097b8a7cSJan Schmidt 		} else if (cur->seq < min_seq) {
686bd989ba3SJan Schmidt 			node = node->rb_left;
687bd989ba3SJan Schmidt 		} else if (!smallest) {
688bd989ba3SJan Schmidt 			/* we want the node with the highest seq */
689bd989ba3SJan Schmidt 			if (found)
690097b8a7cSJan Schmidt 				BUG_ON(found->seq > cur->seq);
691bd989ba3SJan Schmidt 			found = cur;
692bd989ba3SJan Schmidt 			node = node->rb_left;
693097b8a7cSJan Schmidt 		} else if (cur->seq > min_seq) {
694bd989ba3SJan Schmidt 			/* we want the node with the smallest seq */
695bd989ba3SJan Schmidt 			if (found)
696097b8a7cSJan Schmidt 				BUG_ON(found->seq < cur->seq);
697bd989ba3SJan Schmidt 			found = cur;
698bd989ba3SJan Schmidt 			node = node->rb_right;
699bd989ba3SJan Schmidt 		} else {
700bd989ba3SJan Schmidt 			found = cur;
701bd989ba3SJan Schmidt 			break;
702bd989ba3SJan Schmidt 		}
703bd989ba3SJan Schmidt 	}
704097b8a7cSJan Schmidt 	tree_mod_log_read_unlock(fs_info);
705bd989ba3SJan Schmidt 
706bd989ba3SJan Schmidt 	return found;
707bd989ba3SJan Schmidt }
708bd989ba3SJan Schmidt 
709bd989ba3SJan Schmidt /*
710bd989ba3SJan Schmidt  * this returns the element from the log with the smallest time sequence
711bd989ba3SJan Schmidt  * value that's in the log (the oldest log item). any element with a time
712bd989ba3SJan Schmidt  * sequence lower than min_seq will be ignored.
713bd989ba3SJan Schmidt  */
714bd989ba3SJan Schmidt static struct tree_mod_elem *
715bd989ba3SJan Schmidt tree_mod_log_search_oldest(struct btrfs_fs_info *fs_info, u64 start,
716bd989ba3SJan Schmidt 			   u64 min_seq)
717bd989ba3SJan Schmidt {
718bd989ba3SJan Schmidt 	return __tree_mod_log_search(fs_info, start, min_seq, 1);
719bd989ba3SJan Schmidt }
720bd989ba3SJan Schmidt 
721bd989ba3SJan Schmidt /*
722bd989ba3SJan Schmidt  * this returns the element from the log with the largest time sequence
723bd989ba3SJan Schmidt  * value that's in the log (the most recent log item). any element with
724bd989ba3SJan Schmidt  * a time sequence lower than min_seq will be ignored.
725bd989ba3SJan Schmidt  */
726bd989ba3SJan Schmidt static struct tree_mod_elem *
727bd989ba3SJan Schmidt tree_mod_log_search(struct btrfs_fs_info *fs_info, u64 start, u64 min_seq)
728bd989ba3SJan Schmidt {
729bd989ba3SJan Schmidt 	return __tree_mod_log_search(fs_info, start, min_seq, 0);
730bd989ba3SJan Schmidt }
731bd989ba3SJan Schmidt 
732097b8a7cSJan Schmidt static noinline void
733bd989ba3SJan Schmidt tree_mod_log_eb_copy(struct btrfs_fs_info *fs_info, struct extent_buffer *dst,
734bd989ba3SJan Schmidt 		     struct extent_buffer *src, unsigned long dst_offset,
73590f8d62eSJan Schmidt 		     unsigned long src_offset, int nr_items)
736bd989ba3SJan Schmidt {
737bd989ba3SJan Schmidt 	int ret;
738bd989ba3SJan Schmidt 	int i;
739bd989ba3SJan Schmidt 
740e9b7fd4dSJan Schmidt 	if (tree_mod_dont_log(fs_info, NULL))
741bd989ba3SJan Schmidt 		return;
742bd989ba3SJan Schmidt 
743c8cc6341SJosef Bacik 	if (btrfs_header_level(dst) == 0 && btrfs_header_level(src) == 0)
744bd989ba3SJan Schmidt 		return;
745bd989ba3SJan Schmidt 
746bd989ba3SJan Schmidt 	for (i = 0; i < nr_items; i++) {
747c8cc6341SJosef Bacik 		ret = __tree_mod_log_insert_key(fs_info, src,
748097b8a7cSJan Schmidt 						i + src_offset,
749c8cc6341SJosef Bacik 						MOD_LOG_KEY_REMOVE, GFP_NOFS);
750bd989ba3SJan Schmidt 		BUG_ON(ret < 0);
751c8cc6341SJosef Bacik 		ret = __tree_mod_log_insert_key(fs_info, dst,
752097b8a7cSJan Schmidt 						     i + dst_offset,
753c8cc6341SJosef Bacik 						     MOD_LOG_KEY_ADD,
754c8cc6341SJosef Bacik 						     GFP_NOFS);
755bd989ba3SJan Schmidt 		BUG_ON(ret < 0);
756bd989ba3SJan Schmidt 	}
757bd989ba3SJan Schmidt }
758bd989ba3SJan Schmidt 
759bd989ba3SJan Schmidt static inline void
760bd989ba3SJan Schmidt tree_mod_log_eb_move(struct btrfs_fs_info *fs_info, struct extent_buffer *dst,
761bd989ba3SJan Schmidt 		     int dst_offset, int src_offset, int nr_items)
762bd989ba3SJan Schmidt {
763bd989ba3SJan Schmidt 	int ret;
764bd989ba3SJan Schmidt 	ret = tree_mod_log_insert_move(fs_info, dst, dst_offset, src_offset,
765bd989ba3SJan Schmidt 				       nr_items, GFP_NOFS);
766bd989ba3SJan Schmidt 	BUG_ON(ret < 0);
767bd989ba3SJan Schmidt }
768bd989ba3SJan Schmidt 
769097b8a7cSJan Schmidt static noinline void
770bd989ba3SJan Schmidt tree_mod_log_set_node_key(struct btrfs_fs_info *fs_info,
77132adf090SLiu Bo 			  struct extent_buffer *eb, int slot, int atomic)
772bd989ba3SJan Schmidt {
773bd989ba3SJan Schmidt 	int ret;
774bd989ba3SJan Schmidt 
775c8cc6341SJosef Bacik 	ret = __tree_mod_log_insert_key(fs_info, eb, slot,
776bd989ba3SJan Schmidt 					MOD_LOG_KEY_REPLACE,
777bd989ba3SJan Schmidt 					atomic ? GFP_ATOMIC : GFP_NOFS);
778bd989ba3SJan Schmidt 	BUG_ON(ret < 0);
779bd989ba3SJan Schmidt }
780bd989ba3SJan Schmidt 
781097b8a7cSJan Schmidt static noinline void
782097b8a7cSJan Schmidt tree_mod_log_free_eb(struct btrfs_fs_info *fs_info, struct extent_buffer *eb)
783bd989ba3SJan Schmidt {
784e9b7fd4dSJan Schmidt 	if (tree_mod_dont_log(fs_info, eb))
785bd989ba3SJan Schmidt 		return;
786097b8a7cSJan Schmidt 	__tree_mod_log_free_eb(fs_info, eb);
787bd989ba3SJan Schmidt }
788bd989ba3SJan Schmidt 
789097b8a7cSJan Schmidt static noinline void
790bd989ba3SJan Schmidt tree_mod_log_set_root_pointer(struct btrfs_root *root,
79190f8d62eSJan Schmidt 			      struct extent_buffer *new_root_node,
79290f8d62eSJan Schmidt 			      int log_removal)
793bd989ba3SJan Schmidt {
794bd989ba3SJan Schmidt 	int ret;
795bd989ba3SJan Schmidt 	ret = tree_mod_log_insert_root(root->fs_info, root->node,
79690f8d62eSJan Schmidt 				       new_root_node, GFP_NOFS, log_removal);
797bd989ba3SJan Schmidt 	BUG_ON(ret < 0);
798bd989ba3SJan Schmidt }
799bd989ba3SJan Schmidt 
800d352ac68SChris Mason /*
8015d4f98a2SYan Zheng  * check if the tree block can be shared by multiple trees
8025d4f98a2SYan Zheng  */
8035d4f98a2SYan Zheng int btrfs_block_can_be_shared(struct btrfs_root *root,
8045d4f98a2SYan Zheng 			      struct extent_buffer *buf)
8055d4f98a2SYan Zheng {
8065d4f98a2SYan Zheng 	/*
8075d4f98a2SYan Zheng 	 * Tree blocks not in refernece counted trees and tree roots
8085d4f98a2SYan Zheng 	 * are never shared. If a block was allocated after the last
8095d4f98a2SYan Zheng 	 * snapshot and the block was not allocated by tree relocation,
8105d4f98a2SYan Zheng 	 * we know the block is not shared.
8115d4f98a2SYan Zheng 	 */
8125d4f98a2SYan Zheng 	if (root->ref_cows &&
8135d4f98a2SYan Zheng 	    buf != root->node && buf != root->commit_root &&
8145d4f98a2SYan Zheng 	    (btrfs_header_generation(buf) <=
8155d4f98a2SYan Zheng 	     btrfs_root_last_snapshot(&root->root_item) ||
8165d4f98a2SYan Zheng 	     btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)))
8175d4f98a2SYan Zheng 		return 1;
8185d4f98a2SYan Zheng #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
8195d4f98a2SYan Zheng 	if (root->ref_cows &&
8205d4f98a2SYan Zheng 	    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
8215d4f98a2SYan Zheng 		return 1;
8225d4f98a2SYan Zheng #endif
8235d4f98a2SYan Zheng 	return 0;
8245d4f98a2SYan Zheng }
8255d4f98a2SYan Zheng 
8265d4f98a2SYan Zheng static noinline int update_ref_for_cow(struct btrfs_trans_handle *trans,
8275d4f98a2SYan Zheng 				       struct btrfs_root *root,
8285d4f98a2SYan Zheng 				       struct extent_buffer *buf,
829f0486c68SYan, Zheng 				       struct extent_buffer *cow,
830f0486c68SYan, Zheng 				       int *last_ref)
8315d4f98a2SYan Zheng {
8325d4f98a2SYan Zheng 	u64 refs;
8335d4f98a2SYan Zheng 	u64 owner;
8345d4f98a2SYan Zheng 	u64 flags;
8355d4f98a2SYan Zheng 	u64 new_flags = 0;
8365d4f98a2SYan Zheng 	int ret;
8375d4f98a2SYan Zheng 
8385d4f98a2SYan Zheng 	/*
8395d4f98a2SYan Zheng 	 * Backrefs update rules:
8405d4f98a2SYan Zheng 	 *
8415d4f98a2SYan Zheng 	 * Always use full backrefs for extent pointers in tree block
8425d4f98a2SYan Zheng 	 * allocated by tree relocation.
8435d4f98a2SYan Zheng 	 *
8445d4f98a2SYan Zheng 	 * If a shared tree block is no longer referenced by its owner
8455d4f98a2SYan Zheng 	 * tree (btrfs_header_owner(buf) == root->root_key.objectid),
8465d4f98a2SYan Zheng 	 * use full backrefs for extent pointers in tree block.
8475d4f98a2SYan Zheng 	 *
8485d4f98a2SYan Zheng 	 * If a tree block is been relocating
8495d4f98a2SYan Zheng 	 * (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID),
8505d4f98a2SYan Zheng 	 * use full backrefs for extent pointers in tree block.
8515d4f98a2SYan Zheng 	 * The reason for this is some operations (such as drop tree)
8525d4f98a2SYan Zheng 	 * are only allowed for blocks use full backrefs.
8535d4f98a2SYan Zheng 	 */
8545d4f98a2SYan Zheng 
8555d4f98a2SYan Zheng 	if (btrfs_block_can_be_shared(root, buf)) {
8565d4f98a2SYan Zheng 		ret = btrfs_lookup_extent_info(trans, root, buf->start,
8573173a18fSJosef Bacik 					       btrfs_header_level(buf), 1,
8583173a18fSJosef Bacik 					       &refs, &flags);
859be1a5564SMark Fasheh 		if (ret)
860be1a5564SMark Fasheh 			return ret;
861e5df9573SMark Fasheh 		if (refs == 0) {
862e5df9573SMark Fasheh 			ret = -EROFS;
863e5df9573SMark Fasheh 			btrfs_std_error(root->fs_info, ret);
864e5df9573SMark Fasheh 			return ret;
865e5df9573SMark Fasheh 		}
8665d4f98a2SYan Zheng 	} else {
8675d4f98a2SYan Zheng 		refs = 1;
8685d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
8695d4f98a2SYan Zheng 		    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
8705d4f98a2SYan Zheng 			flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
8715d4f98a2SYan Zheng 		else
8725d4f98a2SYan Zheng 			flags = 0;
8735d4f98a2SYan Zheng 	}
8745d4f98a2SYan Zheng 
8755d4f98a2SYan Zheng 	owner = btrfs_header_owner(buf);
8765d4f98a2SYan Zheng 	BUG_ON(owner == BTRFS_TREE_RELOC_OBJECTID &&
8775d4f98a2SYan Zheng 	       !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
8785d4f98a2SYan Zheng 
8795d4f98a2SYan Zheng 	if (refs > 1) {
8805d4f98a2SYan Zheng 		if ((owner == root->root_key.objectid ||
8815d4f98a2SYan Zheng 		     root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) &&
8825d4f98a2SYan Zheng 		    !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)) {
88366d7e7f0SArne Jansen 			ret = btrfs_inc_ref(trans, root, buf, 1, 1);
88479787eaaSJeff Mahoney 			BUG_ON(ret); /* -ENOMEM */
8855d4f98a2SYan Zheng 
8865d4f98a2SYan Zheng 			if (root->root_key.objectid ==
8875d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID) {
88866d7e7f0SArne Jansen 				ret = btrfs_dec_ref(trans, root, buf, 0, 1);
88979787eaaSJeff Mahoney 				BUG_ON(ret); /* -ENOMEM */
89066d7e7f0SArne Jansen 				ret = btrfs_inc_ref(trans, root, cow, 1, 1);
89179787eaaSJeff Mahoney 				BUG_ON(ret); /* -ENOMEM */
8925d4f98a2SYan Zheng 			}
8935d4f98a2SYan Zheng 			new_flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
8945d4f98a2SYan Zheng 		} else {
8955d4f98a2SYan Zheng 
8965d4f98a2SYan Zheng 			if (root->root_key.objectid ==
8975d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID)
89866d7e7f0SArne Jansen 				ret = btrfs_inc_ref(trans, root, cow, 1, 1);
8995d4f98a2SYan Zheng 			else
90066d7e7f0SArne Jansen 				ret = btrfs_inc_ref(trans, root, cow, 0, 1);
90179787eaaSJeff Mahoney 			BUG_ON(ret); /* -ENOMEM */
9025d4f98a2SYan Zheng 		}
9035d4f98a2SYan Zheng 		if (new_flags != 0) {
904b1c79e09SJosef Bacik 			int level = btrfs_header_level(buf);
905b1c79e09SJosef Bacik 
9065d4f98a2SYan Zheng 			ret = btrfs_set_disk_extent_flags(trans, root,
9075d4f98a2SYan Zheng 							  buf->start,
9085d4f98a2SYan Zheng 							  buf->len,
909b1c79e09SJosef Bacik 							  new_flags, level, 0);
910be1a5564SMark Fasheh 			if (ret)
911be1a5564SMark Fasheh 				return ret;
9125d4f98a2SYan Zheng 		}
9135d4f98a2SYan Zheng 	} else {
9145d4f98a2SYan Zheng 		if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
9155d4f98a2SYan Zheng 			if (root->root_key.objectid ==
9165d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID)
91766d7e7f0SArne Jansen 				ret = btrfs_inc_ref(trans, root, cow, 1, 1);
9185d4f98a2SYan Zheng 			else
91966d7e7f0SArne Jansen 				ret = btrfs_inc_ref(trans, root, cow, 0, 1);
92079787eaaSJeff Mahoney 			BUG_ON(ret); /* -ENOMEM */
92166d7e7f0SArne Jansen 			ret = btrfs_dec_ref(trans, root, buf, 1, 1);
92279787eaaSJeff Mahoney 			BUG_ON(ret); /* -ENOMEM */
9235d4f98a2SYan Zheng 		}
9245d4f98a2SYan Zheng 		clean_tree_block(trans, root, buf);
925f0486c68SYan, Zheng 		*last_ref = 1;
9265d4f98a2SYan Zheng 	}
9275d4f98a2SYan Zheng 	return 0;
9285d4f98a2SYan Zheng }
9295d4f98a2SYan Zheng 
9305d4f98a2SYan Zheng /*
931d397712bSChris Mason  * does the dirty work in cow of a single block.  The parent block (if
932d397712bSChris Mason  * supplied) is updated to point to the new cow copy.  The new buffer is marked
933d397712bSChris Mason  * dirty and returned locked.  If you modify the block it needs to be marked
934d397712bSChris Mason  * dirty again.
935d352ac68SChris Mason  *
936d352ac68SChris Mason  * search_start -- an allocation hint for the new block
937d352ac68SChris Mason  *
938d397712bSChris Mason  * empty_size -- a hint that you plan on doing more cow.  This is the size in
939d397712bSChris Mason  * bytes the allocator should try to find free next to the block it returns.
940d397712bSChris Mason  * This is just a hint and may be ignored by the allocator.
941d352ac68SChris Mason  */
942d397712bSChris Mason static noinline int __btrfs_cow_block(struct btrfs_trans_handle *trans,
9435f39d397SChris Mason 			     struct btrfs_root *root,
9445f39d397SChris Mason 			     struct extent_buffer *buf,
9455f39d397SChris Mason 			     struct extent_buffer *parent, int parent_slot,
9465f39d397SChris Mason 			     struct extent_buffer **cow_ret,
9479fa8cfe7SChris Mason 			     u64 search_start, u64 empty_size)
9486702ed49SChris Mason {
9495d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
9505f39d397SChris Mason 	struct extent_buffer *cow;
951be1a5564SMark Fasheh 	int level, ret;
952f0486c68SYan, Zheng 	int last_ref = 0;
953925baeddSChris Mason 	int unlock_orig = 0;
9545d4f98a2SYan Zheng 	u64 parent_start;
9556702ed49SChris Mason 
956925baeddSChris Mason 	if (*cow_ret == buf)
957925baeddSChris Mason 		unlock_orig = 1;
958925baeddSChris Mason 
959b9447ef8SChris Mason 	btrfs_assert_tree_locked(buf);
960925baeddSChris Mason 
9617bb86316SChris Mason 	WARN_ON(root->ref_cows && trans->transid !=
9627bb86316SChris Mason 		root->fs_info->running_transaction->transid);
9636702ed49SChris Mason 	WARN_ON(root->ref_cows && trans->transid != root->last_trans);
9645f39d397SChris Mason 
9657bb86316SChris Mason 	level = btrfs_header_level(buf);
96631840ae1SZheng Yan 
9675d4f98a2SYan Zheng 	if (level == 0)
9685d4f98a2SYan Zheng 		btrfs_item_key(buf, &disk_key, 0);
9695d4f98a2SYan Zheng 	else
9705d4f98a2SYan Zheng 		btrfs_node_key(buf, &disk_key, 0);
9715d4f98a2SYan Zheng 
9725d4f98a2SYan Zheng 	if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) {
9735d4f98a2SYan Zheng 		if (parent)
9745d4f98a2SYan Zheng 			parent_start = parent->start;
9755d4f98a2SYan Zheng 		else
9765d4f98a2SYan Zheng 			parent_start = 0;
9775d4f98a2SYan Zheng 	} else
9785d4f98a2SYan Zheng 		parent_start = 0;
9795d4f98a2SYan Zheng 
9805d4f98a2SYan Zheng 	cow = btrfs_alloc_free_block(trans, root, buf->len, parent_start,
9815d4f98a2SYan Zheng 				     root->root_key.objectid, &disk_key,
9825581a51aSJan Schmidt 				     level, search_start, empty_size);
9836702ed49SChris Mason 	if (IS_ERR(cow))
9846702ed49SChris Mason 		return PTR_ERR(cow);
9856702ed49SChris Mason 
986b4ce94deSChris Mason 	/* cow is set to blocking by btrfs_init_new_buffer */
987b4ce94deSChris Mason 
9885f39d397SChris Mason 	copy_extent_buffer(cow, buf, 0, 0, cow->len);
989db94535dSChris Mason 	btrfs_set_header_bytenr(cow, cow->start);
9905f39d397SChris Mason 	btrfs_set_header_generation(cow, trans->transid);
9915d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
9925d4f98a2SYan Zheng 	btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
9935d4f98a2SYan Zheng 				     BTRFS_HEADER_FLAG_RELOC);
9945d4f98a2SYan Zheng 	if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
9955d4f98a2SYan Zheng 		btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
9965d4f98a2SYan Zheng 	else
9975f39d397SChris Mason 		btrfs_set_header_owner(cow, root->root_key.objectid);
9986702ed49SChris Mason 
999fba6aa75SGeert Uytterhoeven 	write_extent_buffer(cow, root->fs_info->fsid, btrfs_header_fsid(cow),
10002b82032cSYan Zheng 			    BTRFS_FSID_SIZE);
10012b82032cSYan Zheng 
1002be1a5564SMark Fasheh 	ret = update_ref_for_cow(trans, root, buf, cow, &last_ref);
1003b68dc2a9SMark Fasheh 	if (ret) {
100479787eaaSJeff Mahoney 		btrfs_abort_transaction(trans, root, ret);
1005b68dc2a9SMark Fasheh 		return ret;
1006b68dc2a9SMark Fasheh 	}
10071a40e23bSZheng Yan 
1008*83d4cfd4SJosef Bacik 	if (root->ref_cows) {
1009*83d4cfd4SJosef Bacik 		ret = btrfs_reloc_cow_block(trans, root, buf, cow);
1010*83d4cfd4SJosef Bacik 		if (ret)
1011*83d4cfd4SJosef Bacik 			return ret;
1012*83d4cfd4SJosef Bacik 	}
10133fd0a558SYan, Zheng 
10146702ed49SChris Mason 	if (buf == root->node) {
1015925baeddSChris Mason 		WARN_ON(parent && parent != buf);
10165d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
10175d4f98a2SYan Zheng 		    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
10185d4f98a2SYan Zheng 			parent_start = buf->start;
10195d4f98a2SYan Zheng 		else
10205d4f98a2SYan Zheng 			parent_start = 0;
1021925baeddSChris Mason 
10225f39d397SChris Mason 		extent_buffer_get(cow);
102390f8d62eSJan Schmidt 		tree_mod_log_set_root_pointer(root, cow, 1);
1024240f62c8SChris Mason 		rcu_assign_pointer(root->node, cow);
1025925baeddSChris Mason 
1026f0486c68SYan, Zheng 		btrfs_free_tree_block(trans, root, buf, parent_start,
10275581a51aSJan Schmidt 				      last_ref);
10285f39d397SChris Mason 		free_extent_buffer(buf);
10290b86a832SChris Mason 		add_root_to_dirty_list(root);
10306702ed49SChris Mason 	} else {
10315d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
10325d4f98a2SYan Zheng 			parent_start = parent->start;
10335d4f98a2SYan Zheng 		else
10345d4f98a2SYan Zheng 			parent_start = 0;
10355d4f98a2SYan Zheng 
10365d4f98a2SYan Zheng 		WARN_ON(trans->transid != btrfs_header_generation(parent));
1037f230475eSJan Schmidt 		tree_mod_log_insert_key(root->fs_info, parent, parent_slot,
1038c8cc6341SJosef Bacik 					MOD_LOG_KEY_REPLACE, GFP_NOFS);
10395f39d397SChris Mason 		btrfs_set_node_blockptr(parent, parent_slot,
1040db94535dSChris Mason 					cow->start);
104174493f7aSChris Mason 		btrfs_set_node_ptr_generation(parent, parent_slot,
104274493f7aSChris Mason 					      trans->transid);
10436702ed49SChris Mason 		btrfs_mark_buffer_dirty(parent);
10447fb7d76fSJosef Bacik 		if (last_ref)
1045d9abbf1cSJan Schmidt 			tree_mod_log_free_eb(root->fs_info, buf);
1046f0486c68SYan, Zheng 		btrfs_free_tree_block(trans, root, buf, parent_start,
10475581a51aSJan Schmidt 				      last_ref);
10486702ed49SChris Mason 	}
1049925baeddSChris Mason 	if (unlock_orig)
1050925baeddSChris Mason 		btrfs_tree_unlock(buf);
10513083ee2eSJosef Bacik 	free_extent_buffer_stale(buf);
10526702ed49SChris Mason 	btrfs_mark_buffer_dirty(cow);
10536702ed49SChris Mason 	*cow_ret = cow;
10546702ed49SChris Mason 	return 0;
10556702ed49SChris Mason }
10566702ed49SChris Mason 
10575d9e75c4SJan Schmidt /*
10585d9e75c4SJan Schmidt  * returns the logical address of the oldest predecessor of the given root.
10595d9e75c4SJan Schmidt  * entries older than time_seq are ignored.
10605d9e75c4SJan Schmidt  */
10615d9e75c4SJan Schmidt static struct tree_mod_elem *
10625d9e75c4SJan Schmidt __tree_mod_log_oldest_root(struct btrfs_fs_info *fs_info,
106330b0463aSJan Schmidt 			   struct extent_buffer *eb_root, u64 time_seq)
10645d9e75c4SJan Schmidt {
10655d9e75c4SJan Schmidt 	struct tree_mod_elem *tm;
10665d9e75c4SJan Schmidt 	struct tree_mod_elem *found = NULL;
106730b0463aSJan Schmidt 	u64 root_logical = eb_root->start;
10685d9e75c4SJan Schmidt 	int looped = 0;
10695d9e75c4SJan Schmidt 
10705d9e75c4SJan Schmidt 	if (!time_seq)
107135a3621bSStefan Behrens 		return NULL;
10725d9e75c4SJan Schmidt 
10735d9e75c4SJan Schmidt 	/*
10745d9e75c4SJan Schmidt 	 * the very last operation that's logged for a root is the replacement
10755d9e75c4SJan Schmidt 	 * operation (if it is replaced at all). this has the index of the *new*
10765d9e75c4SJan Schmidt 	 * root, making it the very first operation that's logged for this root.
10775d9e75c4SJan Schmidt 	 */
10785d9e75c4SJan Schmidt 	while (1) {
10795d9e75c4SJan Schmidt 		tm = tree_mod_log_search_oldest(fs_info, root_logical,
10805d9e75c4SJan Schmidt 						time_seq);
10815d9e75c4SJan Schmidt 		if (!looped && !tm)
108235a3621bSStefan Behrens 			return NULL;
10835d9e75c4SJan Schmidt 		/*
108428da9fb4SJan Schmidt 		 * if there are no tree operation for the oldest root, we simply
108528da9fb4SJan Schmidt 		 * return it. this should only happen if that (old) root is at
108628da9fb4SJan Schmidt 		 * level 0.
10875d9e75c4SJan Schmidt 		 */
108828da9fb4SJan Schmidt 		if (!tm)
108928da9fb4SJan Schmidt 			break;
10905d9e75c4SJan Schmidt 
109128da9fb4SJan Schmidt 		/*
109228da9fb4SJan Schmidt 		 * if there's an operation that's not a root replacement, we
109328da9fb4SJan Schmidt 		 * found the oldest version of our root. normally, we'll find a
109428da9fb4SJan Schmidt 		 * MOD_LOG_KEY_REMOVE_WHILE_FREEING operation here.
109528da9fb4SJan Schmidt 		 */
10965d9e75c4SJan Schmidt 		if (tm->op != MOD_LOG_ROOT_REPLACE)
10975d9e75c4SJan Schmidt 			break;
10985d9e75c4SJan Schmidt 
10995d9e75c4SJan Schmidt 		found = tm;
11005d9e75c4SJan Schmidt 		root_logical = tm->old_root.logical;
11015d9e75c4SJan Schmidt 		looped = 1;
11025d9e75c4SJan Schmidt 	}
11035d9e75c4SJan Schmidt 
1104a95236d9SJan Schmidt 	/* if there's no old root to return, return what we found instead */
1105a95236d9SJan Schmidt 	if (!found)
1106a95236d9SJan Schmidt 		found = tm;
1107a95236d9SJan Schmidt 
11085d9e75c4SJan Schmidt 	return found;
11095d9e75c4SJan Schmidt }
11105d9e75c4SJan Schmidt 
11115d9e75c4SJan Schmidt /*
11125d9e75c4SJan Schmidt  * tm is a pointer to the first operation to rewind within eb. then, all
11135d9e75c4SJan Schmidt  * previous operations will be rewinded (until we reach something older than
11145d9e75c4SJan Schmidt  * time_seq).
11155d9e75c4SJan Schmidt  */
11165d9e75c4SJan Schmidt static void
1117f1ca7e98SJosef Bacik __tree_mod_log_rewind(struct btrfs_fs_info *fs_info, struct extent_buffer *eb,
1118f1ca7e98SJosef Bacik 		      u64 time_seq, struct tree_mod_elem *first_tm)
11195d9e75c4SJan Schmidt {
11205d9e75c4SJan Schmidt 	u32 n;
11215d9e75c4SJan Schmidt 	struct rb_node *next;
11225d9e75c4SJan Schmidt 	struct tree_mod_elem *tm = first_tm;
11235d9e75c4SJan Schmidt 	unsigned long o_dst;
11245d9e75c4SJan Schmidt 	unsigned long o_src;
11255d9e75c4SJan Schmidt 	unsigned long p_size = sizeof(struct btrfs_key_ptr);
11265d9e75c4SJan Schmidt 
11275d9e75c4SJan Schmidt 	n = btrfs_header_nritems(eb);
1128f1ca7e98SJosef Bacik 	tree_mod_log_read_lock(fs_info);
1129097b8a7cSJan Schmidt 	while (tm && tm->seq >= time_seq) {
11305d9e75c4SJan Schmidt 		/*
11315d9e75c4SJan Schmidt 		 * all the operations are recorded with the operator used for
11325d9e75c4SJan Schmidt 		 * the modification. as we're going backwards, we do the
11335d9e75c4SJan Schmidt 		 * opposite of each operation here.
11345d9e75c4SJan Schmidt 		 */
11355d9e75c4SJan Schmidt 		switch (tm->op) {
11365d9e75c4SJan Schmidt 		case MOD_LOG_KEY_REMOVE_WHILE_FREEING:
11375d9e75c4SJan Schmidt 			BUG_ON(tm->slot < n);
11381c697d4aSEric Sandeen 			/* Fallthrough */
113995c80bb1SLiu Bo 		case MOD_LOG_KEY_REMOVE_WHILE_MOVING:
11404c3e6969SChris Mason 		case MOD_LOG_KEY_REMOVE:
11415d9e75c4SJan Schmidt 			btrfs_set_node_key(eb, &tm->key, tm->slot);
11425d9e75c4SJan Schmidt 			btrfs_set_node_blockptr(eb, tm->slot, tm->blockptr);
11435d9e75c4SJan Schmidt 			btrfs_set_node_ptr_generation(eb, tm->slot,
11445d9e75c4SJan Schmidt 						      tm->generation);
11454c3e6969SChris Mason 			n++;
11465d9e75c4SJan Schmidt 			break;
11475d9e75c4SJan Schmidt 		case MOD_LOG_KEY_REPLACE:
11485d9e75c4SJan Schmidt 			BUG_ON(tm->slot >= n);
11495d9e75c4SJan Schmidt 			btrfs_set_node_key(eb, &tm->key, tm->slot);
11505d9e75c4SJan Schmidt 			btrfs_set_node_blockptr(eb, tm->slot, tm->blockptr);
11515d9e75c4SJan Schmidt 			btrfs_set_node_ptr_generation(eb, tm->slot,
11525d9e75c4SJan Schmidt 						      tm->generation);
11535d9e75c4SJan Schmidt 			break;
11545d9e75c4SJan Schmidt 		case MOD_LOG_KEY_ADD:
115519956c7eSJan Schmidt 			/* if a move operation is needed it's in the log */
11565d9e75c4SJan Schmidt 			n--;
11575d9e75c4SJan Schmidt 			break;
11585d9e75c4SJan Schmidt 		case MOD_LOG_MOVE_KEYS:
1159c3193108SJan Schmidt 			o_dst = btrfs_node_key_ptr_offset(tm->slot);
1160c3193108SJan Schmidt 			o_src = btrfs_node_key_ptr_offset(tm->move.dst_slot);
1161c3193108SJan Schmidt 			memmove_extent_buffer(eb, o_dst, o_src,
11625d9e75c4SJan Schmidt 					      tm->move.nr_items * p_size);
11635d9e75c4SJan Schmidt 			break;
11645d9e75c4SJan Schmidt 		case MOD_LOG_ROOT_REPLACE:
11655d9e75c4SJan Schmidt 			/*
11665d9e75c4SJan Schmidt 			 * this operation is special. for roots, this must be
11675d9e75c4SJan Schmidt 			 * handled explicitly before rewinding.
11685d9e75c4SJan Schmidt 			 * for non-roots, this operation may exist if the node
11695d9e75c4SJan Schmidt 			 * was a root: root A -> child B; then A gets empty and
11705d9e75c4SJan Schmidt 			 * B is promoted to the new root. in the mod log, we'll
11715d9e75c4SJan Schmidt 			 * have a root-replace operation for B, a tree block
11725d9e75c4SJan Schmidt 			 * that is no root. we simply ignore that operation.
11735d9e75c4SJan Schmidt 			 */
11745d9e75c4SJan Schmidt 			break;
11755d9e75c4SJan Schmidt 		}
11765d9e75c4SJan Schmidt 		next = rb_next(&tm->node);
11775d9e75c4SJan Schmidt 		if (!next)
11785d9e75c4SJan Schmidt 			break;
11795d9e75c4SJan Schmidt 		tm = container_of(next, struct tree_mod_elem, node);
11805d9e75c4SJan Schmidt 		if (tm->index != first_tm->index)
11815d9e75c4SJan Schmidt 			break;
11825d9e75c4SJan Schmidt 	}
1183f1ca7e98SJosef Bacik 	tree_mod_log_read_unlock(fs_info);
11845d9e75c4SJan Schmidt 	btrfs_set_header_nritems(eb, n);
11855d9e75c4SJan Schmidt }
11865d9e75c4SJan Schmidt 
118747fb091fSJan Schmidt /*
118847fb091fSJan Schmidt  * Called with eb read locked. If the buffer cannot be rewinded, the same buffer
118947fb091fSJan Schmidt  * is returned. If rewind operations happen, a fresh buffer is returned. The
119047fb091fSJan Schmidt  * returned buffer is always read-locked. If the returned buffer is not the
119147fb091fSJan Schmidt  * input buffer, the lock on the input buffer is released and the input buffer
119247fb091fSJan Schmidt  * is freed (its refcount is decremented).
119347fb091fSJan Schmidt  */
11945d9e75c4SJan Schmidt static struct extent_buffer *
11959ec72677SJosef Bacik tree_mod_log_rewind(struct btrfs_fs_info *fs_info, struct btrfs_path *path,
11969ec72677SJosef Bacik 		    struct extent_buffer *eb, u64 time_seq)
11975d9e75c4SJan Schmidt {
11985d9e75c4SJan Schmidt 	struct extent_buffer *eb_rewin;
11995d9e75c4SJan Schmidt 	struct tree_mod_elem *tm;
12005d9e75c4SJan Schmidt 
12015d9e75c4SJan Schmidt 	if (!time_seq)
12025d9e75c4SJan Schmidt 		return eb;
12035d9e75c4SJan Schmidt 
12045d9e75c4SJan Schmidt 	if (btrfs_header_level(eb) == 0)
12055d9e75c4SJan Schmidt 		return eb;
12065d9e75c4SJan Schmidt 
12075d9e75c4SJan Schmidt 	tm = tree_mod_log_search(fs_info, eb->start, time_seq);
12085d9e75c4SJan Schmidt 	if (!tm)
12095d9e75c4SJan Schmidt 		return eb;
12105d9e75c4SJan Schmidt 
12119ec72677SJosef Bacik 	btrfs_set_path_blocking(path);
12129ec72677SJosef Bacik 	btrfs_set_lock_blocking_rw(eb, BTRFS_READ_LOCK);
12139ec72677SJosef Bacik 
12145d9e75c4SJan Schmidt 	if (tm->op == MOD_LOG_KEY_REMOVE_WHILE_FREEING) {
12155d9e75c4SJan Schmidt 		BUG_ON(tm->slot != 0);
12165d9e75c4SJan Schmidt 		eb_rewin = alloc_dummy_extent_buffer(eb->start,
12175d9e75c4SJan Schmidt 						fs_info->tree_root->nodesize);
1218db7f3436SJosef Bacik 		if (!eb_rewin) {
12199ec72677SJosef Bacik 			btrfs_tree_read_unlock_blocking(eb);
1220db7f3436SJosef Bacik 			free_extent_buffer(eb);
1221db7f3436SJosef Bacik 			return NULL;
1222db7f3436SJosef Bacik 		}
12235d9e75c4SJan Schmidt 		btrfs_set_header_bytenr(eb_rewin, eb->start);
12245d9e75c4SJan Schmidt 		btrfs_set_header_backref_rev(eb_rewin,
12255d9e75c4SJan Schmidt 					     btrfs_header_backref_rev(eb));
12265d9e75c4SJan Schmidt 		btrfs_set_header_owner(eb_rewin, btrfs_header_owner(eb));
1227c3193108SJan Schmidt 		btrfs_set_header_level(eb_rewin, btrfs_header_level(eb));
12285d9e75c4SJan Schmidt 	} else {
12295d9e75c4SJan Schmidt 		eb_rewin = btrfs_clone_extent_buffer(eb);
1230db7f3436SJosef Bacik 		if (!eb_rewin) {
12319ec72677SJosef Bacik 			btrfs_tree_read_unlock_blocking(eb);
1232db7f3436SJosef Bacik 			free_extent_buffer(eb);
1233db7f3436SJosef Bacik 			return NULL;
1234db7f3436SJosef Bacik 		}
12355d9e75c4SJan Schmidt 	}
12365d9e75c4SJan Schmidt 
12379ec72677SJosef Bacik 	btrfs_clear_path_blocking(path, NULL, BTRFS_READ_LOCK);
12389ec72677SJosef Bacik 	btrfs_tree_read_unlock_blocking(eb);
12395d9e75c4SJan Schmidt 	free_extent_buffer(eb);
12405d9e75c4SJan Schmidt 
124147fb091fSJan Schmidt 	extent_buffer_get(eb_rewin);
124247fb091fSJan Schmidt 	btrfs_tree_read_lock(eb_rewin);
1243f1ca7e98SJosef Bacik 	__tree_mod_log_rewind(fs_info, eb_rewin, time_seq, tm);
124457911b8bSJan Schmidt 	WARN_ON(btrfs_header_nritems(eb_rewin) >
12452a745b14SArne Jansen 		BTRFS_NODEPTRS_PER_BLOCK(fs_info->tree_root));
12465d9e75c4SJan Schmidt 
12475d9e75c4SJan Schmidt 	return eb_rewin;
12485d9e75c4SJan Schmidt }
12495d9e75c4SJan Schmidt 
12508ba97a15SJan Schmidt /*
12518ba97a15SJan Schmidt  * get_old_root() rewinds the state of @root's root node to the given @time_seq
12528ba97a15SJan Schmidt  * value. If there are no changes, the current root->root_node is returned. If
12538ba97a15SJan Schmidt  * anything changed in between, there's a fresh buffer allocated on which the
12548ba97a15SJan Schmidt  * rewind operations are done. In any case, the returned buffer is read locked.
12558ba97a15SJan Schmidt  * Returns NULL on error (with no locks held).
12568ba97a15SJan Schmidt  */
12575d9e75c4SJan Schmidt static inline struct extent_buffer *
12585d9e75c4SJan Schmidt get_old_root(struct btrfs_root *root, u64 time_seq)
12595d9e75c4SJan Schmidt {
12605d9e75c4SJan Schmidt 	struct tree_mod_elem *tm;
126130b0463aSJan Schmidt 	struct extent_buffer *eb = NULL;
126230b0463aSJan Schmidt 	struct extent_buffer *eb_root;
12637bfdcf7fSLiu Bo 	struct extent_buffer *old;
1264a95236d9SJan Schmidt 	struct tree_mod_root *old_root = NULL;
12654325edd0SChris Mason 	u64 old_generation = 0;
1266a95236d9SJan Schmidt 	u64 logical;
1267834328a8SJan Schmidt 	u32 blocksize;
12685d9e75c4SJan Schmidt 
126930b0463aSJan Schmidt 	eb_root = btrfs_read_lock_root_node(root);
127030b0463aSJan Schmidt 	tm = __tree_mod_log_oldest_root(root->fs_info, eb_root, time_seq);
12715d9e75c4SJan Schmidt 	if (!tm)
127230b0463aSJan Schmidt 		return eb_root;
12735d9e75c4SJan Schmidt 
1274a95236d9SJan Schmidt 	if (tm->op == MOD_LOG_ROOT_REPLACE) {
12755d9e75c4SJan Schmidt 		old_root = &tm->old_root;
12765d9e75c4SJan Schmidt 		old_generation = tm->generation;
1277a95236d9SJan Schmidt 		logical = old_root->logical;
1278a95236d9SJan Schmidt 	} else {
127930b0463aSJan Schmidt 		logical = eb_root->start;
1280a95236d9SJan Schmidt 	}
12815d9e75c4SJan Schmidt 
1282a95236d9SJan Schmidt 	tm = tree_mod_log_search(root->fs_info, logical, time_seq);
1283834328a8SJan Schmidt 	if (old_root && tm && tm->op != MOD_LOG_KEY_REMOVE_WHILE_FREEING) {
128430b0463aSJan Schmidt 		btrfs_tree_read_unlock(eb_root);
128530b0463aSJan Schmidt 		free_extent_buffer(eb_root);
1286834328a8SJan Schmidt 		blocksize = btrfs_level_size(root, old_root->level);
12877bfdcf7fSLiu Bo 		old = read_tree_block(root, logical, blocksize, 0);
1288416bc658SJosef Bacik 		if (!old || !extent_buffer_uptodate(old)) {
1289416bc658SJosef Bacik 			free_extent_buffer(old);
1290834328a8SJan Schmidt 			pr_warn("btrfs: failed to read tree block %llu from get_old_root\n",
1291834328a8SJan Schmidt 				logical);
1292834328a8SJan Schmidt 			WARN_ON(1);
1293834328a8SJan Schmidt 		} else {
12947bfdcf7fSLiu Bo 			eb = btrfs_clone_extent_buffer(old);
12957bfdcf7fSLiu Bo 			free_extent_buffer(old);
1296834328a8SJan Schmidt 		}
1297834328a8SJan Schmidt 	} else if (old_root) {
129830b0463aSJan Schmidt 		btrfs_tree_read_unlock(eb_root);
129930b0463aSJan Schmidt 		free_extent_buffer(eb_root);
130028da9fb4SJan Schmidt 		eb = alloc_dummy_extent_buffer(logical, root->nodesize);
1301834328a8SJan Schmidt 	} else {
13029ec72677SJosef Bacik 		btrfs_set_lock_blocking_rw(eb_root, BTRFS_READ_LOCK);
130330b0463aSJan Schmidt 		eb = btrfs_clone_extent_buffer(eb_root);
13049ec72677SJosef Bacik 		btrfs_tree_read_unlock_blocking(eb_root);
130530b0463aSJan Schmidt 		free_extent_buffer(eb_root);
1306834328a8SJan Schmidt 	}
1307834328a8SJan Schmidt 
13088ba97a15SJan Schmidt 	if (!eb)
13098ba97a15SJan Schmidt 		return NULL;
1310d6381084SJan Schmidt 	extent_buffer_get(eb);
13118ba97a15SJan Schmidt 	btrfs_tree_read_lock(eb);
1312a95236d9SJan Schmidt 	if (old_root) {
13135d9e75c4SJan Schmidt 		btrfs_set_header_bytenr(eb, eb->start);
13145d9e75c4SJan Schmidt 		btrfs_set_header_backref_rev(eb, BTRFS_MIXED_BACKREF_REV);
131530b0463aSJan Schmidt 		btrfs_set_header_owner(eb, btrfs_header_owner(eb_root));
13165d9e75c4SJan Schmidt 		btrfs_set_header_level(eb, old_root->level);
13175d9e75c4SJan Schmidt 		btrfs_set_header_generation(eb, old_generation);
1318a95236d9SJan Schmidt 	}
131928da9fb4SJan Schmidt 	if (tm)
1320f1ca7e98SJosef Bacik 		__tree_mod_log_rewind(root->fs_info, eb, time_seq, tm);
132128da9fb4SJan Schmidt 	else
132228da9fb4SJan Schmidt 		WARN_ON(btrfs_header_level(eb) != 0);
132357911b8bSJan Schmidt 	WARN_ON(btrfs_header_nritems(eb) > BTRFS_NODEPTRS_PER_BLOCK(root));
13245d9e75c4SJan Schmidt 
13255d9e75c4SJan Schmidt 	return eb;
13265d9e75c4SJan Schmidt }
13275d9e75c4SJan Schmidt 
13285b6602e7SJan Schmidt int btrfs_old_root_level(struct btrfs_root *root, u64 time_seq)
13295b6602e7SJan Schmidt {
13305b6602e7SJan Schmidt 	struct tree_mod_elem *tm;
13315b6602e7SJan Schmidt 	int level;
133230b0463aSJan Schmidt 	struct extent_buffer *eb_root = btrfs_root_node(root);
13335b6602e7SJan Schmidt 
133430b0463aSJan Schmidt 	tm = __tree_mod_log_oldest_root(root->fs_info, eb_root, time_seq);
13355b6602e7SJan Schmidt 	if (tm && tm->op == MOD_LOG_ROOT_REPLACE) {
13365b6602e7SJan Schmidt 		level = tm->old_root.level;
13375b6602e7SJan Schmidt 	} else {
133830b0463aSJan Schmidt 		level = btrfs_header_level(eb_root);
13395b6602e7SJan Schmidt 	}
134030b0463aSJan Schmidt 	free_extent_buffer(eb_root);
13415b6602e7SJan Schmidt 
13425b6602e7SJan Schmidt 	return level;
13435b6602e7SJan Schmidt }
13445b6602e7SJan Schmidt 
13455d4f98a2SYan Zheng static inline int should_cow_block(struct btrfs_trans_handle *trans,
13465d4f98a2SYan Zheng 				   struct btrfs_root *root,
13475d4f98a2SYan Zheng 				   struct extent_buffer *buf)
13485d4f98a2SYan Zheng {
1349f1ebcc74SLiu Bo 	/* ensure we can see the force_cow */
1350f1ebcc74SLiu Bo 	smp_rmb();
1351f1ebcc74SLiu Bo 
1352f1ebcc74SLiu Bo 	/*
1353f1ebcc74SLiu Bo 	 * We do not need to cow a block if
1354f1ebcc74SLiu Bo 	 * 1) this block is not created or changed in this transaction;
1355f1ebcc74SLiu Bo 	 * 2) this block does not belong to TREE_RELOC tree;
1356f1ebcc74SLiu Bo 	 * 3) the root is not forced COW.
1357f1ebcc74SLiu Bo 	 *
1358f1ebcc74SLiu Bo 	 * What is forced COW:
1359f1ebcc74SLiu Bo 	 *    when we create snapshot during commiting the transaction,
1360f1ebcc74SLiu Bo 	 *    after we've finished coping src root, we must COW the shared
1361f1ebcc74SLiu Bo 	 *    block to ensure the metadata consistency.
1362f1ebcc74SLiu Bo 	 */
13635d4f98a2SYan Zheng 	if (btrfs_header_generation(buf) == trans->transid &&
13645d4f98a2SYan Zheng 	    !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN) &&
13655d4f98a2SYan Zheng 	    !(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
1366f1ebcc74SLiu Bo 	      btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)) &&
1367f1ebcc74SLiu Bo 	    !root->force_cow)
13685d4f98a2SYan Zheng 		return 0;
13695d4f98a2SYan Zheng 	return 1;
13705d4f98a2SYan Zheng }
13715d4f98a2SYan Zheng 
1372d352ac68SChris Mason /*
1373d352ac68SChris Mason  * cows a single block, see __btrfs_cow_block for the real work.
1374d352ac68SChris Mason  * This version of it has extra checks so that a block isn't cow'd more than
1375d352ac68SChris Mason  * once per transaction, as long as it hasn't been written yet
1376d352ac68SChris Mason  */
1377d397712bSChris Mason noinline int btrfs_cow_block(struct btrfs_trans_handle *trans,
13785f39d397SChris Mason 		    struct btrfs_root *root, struct extent_buffer *buf,
13795f39d397SChris Mason 		    struct extent_buffer *parent, int parent_slot,
13809fa8cfe7SChris Mason 		    struct extent_buffer **cow_ret)
138102217ed2SChris Mason {
13826702ed49SChris Mason 	u64 search_start;
1383f510cfecSChris Mason 	int ret;
1384dc17ff8fSChris Mason 
138531b1a2bdSJulia Lawall 	if (trans->transaction != root->fs_info->running_transaction)
138631b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "trans %llu running %llu\n",
1387c1c9ff7cSGeert Uytterhoeven 		       trans->transid,
1388ccd467d6SChris Mason 		       root->fs_info->running_transaction->transid);
138931b1a2bdSJulia Lawall 
139031b1a2bdSJulia Lawall 	if (trans->transid != root->fs_info->generation)
139131b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "trans %llu running %llu\n",
1392c1c9ff7cSGeert Uytterhoeven 		       trans->transid, root->fs_info->generation);
1393dc17ff8fSChris Mason 
13945d4f98a2SYan Zheng 	if (!should_cow_block(trans, root, buf)) {
139502217ed2SChris Mason 		*cow_ret = buf;
139602217ed2SChris Mason 		return 0;
139702217ed2SChris Mason 	}
1398c487685dSChris Mason 
13990b86a832SChris Mason 	search_start = buf->start & ~((u64)(1024 * 1024 * 1024) - 1);
1400b4ce94deSChris Mason 
1401b4ce94deSChris Mason 	if (parent)
1402b4ce94deSChris Mason 		btrfs_set_lock_blocking(parent);
1403b4ce94deSChris Mason 	btrfs_set_lock_blocking(buf);
1404b4ce94deSChris Mason 
1405f510cfecSChris Mason 	ret = __btrfs_cow_block(trans, root, buf, parent,
14069fa8cfe7SChris Mason 				 parent_slot, cow_ret, search_start, 0);
14071abe9b8aSliubo 
14081abe9b8aSliubo 	trace_btrfs_cow_block(root, buf, *cow_ret);
14091abe9b8aSliubo 
1410f510cfecSChris Mason 	return ret;
14112c90e5d6SChris Mason }
14126702ed49SChris Mason 
1413d352ac68SChris Mason /*
1414d352ac68SChris Mason  * helper function for defrag to decide if two blocks pointed to by a
1415d352ac68SChris Mason  * node are actually close by
1416d352ac68SChris Mason  */
14176b80053dSChris Mason static int close_blocks(u64 blocknr, u64 other, u32 blocksize)
14186702ed49SChris Mason {
14196b80053dSChris Mason 	if (blocknr < other && other - (blocknr + blocksize) < 32768)
14206702ed49SChris Mason 		return 1;
14216b80053dSChris Mason 	if (blocknr > other && blocknr - (other + blocksize) < 32768)
14226702ed49SChris Mason 		return 1;
142302217ed2SChris Mason 	return 0;
142402217ed2SChris Mason }
142502217ed2SChris Mason 
1426081e9573SChris Mason /*
1427081e9573SChris Mason  * compare two keys in a memcmp fashion
1428081e9573SChris Mason  */
1429081e9573SChris Mason static int comp_keys(struct btrfs_disk_key *disk, struct btrfs_key *k2)
1430081e9573SChris Mason {
1431081e9573SChris Mason 	struct btrfs_key k1;
1432081e9573SChris Mason 
1433081e9573SChris Mason 	btrfs_disk_key_to_cpu(&k1, disk);
1434081e9573SChris Mason 
143520736abaSDiego Calleja 	return btrfs_comp_cpu_keys(&k1, k2);
1436081e9573SChris Mason }
1437081e9573SChris Mason 
1438f3465ca4SJosef Bacik /*
1439f3465ca4SJosef Bacik  * same as comp_keys only with two btrfs_key's
1440f3465ca4SJosef Bacik  */
14415d4f98a2SYan Zheng int btrfs_comp_cpu_keys(struct btrfs_key *k1, struct btrfs_key *k2)
1442f3465ca4SJosef Bacik {
1443f3465ca4SJosef Bacik 	if (k1->objectid > k2->objectid)
1444f3465ca4SJosef Bacik 		return 1;
1445f3465ca4SJosef Bacik 	if (k1->objectid < k2->objectid)
1446f3465ca4SJosef Bacik 		return -1;
1447f3465ca4SJosef Bacik 	if (k1->type > k2->type)
1448f3465ca4SJosef Bacik 		return 1;
1449f3465ca4SJosef Bacik 	if (k1->type < k2->type)
1450f3465ca4SJosef Bacik 		return -1;
1451f3465ca4SJosef Bacik 	if (k1->offset > k2->offset)
1452f3465ca4SJosef Bacik 		return 1;
1453f3465ca4SJosef Bacik 	if (k1->offset < k2->offset)
1454f3465ca4SJosef Bacik 		return -1;
1455f3465ca4SJosef Bacik 	return 0;
1456f3465ca4SJosef Bacik }
1457081e9573SChris Mason 
1458d352ac68SChris Mason /*
1459d352ac68SChris Mason  * this is used by the defrag code to go through all the
1460d352ac68SChris Mason  * leaves pointed to by a node and reallocate them so that
1461d352ac68SChris Mason  * disk order is close to key order
1462d352ac68SChris Mason  */
14636702ed49SChris Mason int btrfs_realloc_node(struct btrfs_trans_handle *trans,
14645f39d397SChris Mason 		       struct btrfs_root *root, struct extent_buffer *parent,
1465de78b51aSEric Sandeen 		       int start_slot, u64 *last_ret,
1466a6b6e75eSChris Mason 		       struct btrfs_key *progress)
14676702ed49SChris Mason {
14686b80053dSChris Mason 	struct extent_buffer *cur;
14696702ed49SChris Mason 	u64 blocknr;
1470ca7a79adSChris Mason 	u64 gen;
1471e9d0b13bSChris Mason 	u64 search_start = *last_ret;
1472e9d0b13bSChris Mason 	u64 last_block = 0;
14736702ed49SChris Mason 	u64 other;
14746702ed49SChris Mason 	u32 parent_nritems;
14756702ed49SChris Mason 	int end_slot;
14766702ed49SChris Mason 	int i;
14776702ed49SChris Mason 	int err = 0;
1478f2183bdeSChris Mason 	int parent_level;
14796b80053dSChris Mason 	int uptodate;
14806b80053dSChris Mason 	u32 blocksize;
1481081e9573SChris Mason 	int progress_passed = 0;
1482081e9573SChris Mason 	struct btrfs_disk_key disk_key;
14836702ed49SChris Mason 
14845708b959SChris Mason 	parent_level = btrfs_header_level(parent);
14855708b959SChris Mason 
14866c1500f2SJulia Lawall 	WARN_ON(trans->transaction != root->fs_info->running_transaction);
14876c1500f2SJulia Lawall 	WARN_ON(trans->transid != root->fs_info->generation);
148886479a04SChris Mason 
14896b80053dSChris Mason 	parent_nritems = btrfs_header_nritems(parent);
14906b80053dSChris Mason 	blocksize = btrfs_level_size(root, parent_level - 1);
14916702ed49SChris Mason 	end_slot = parent_nritems;
14926702ed49SChris Mason 
14936702ed49SChris Mason 	if (parent_nritems == 1)
14946702ed49SChris Mason 		return 0;
14956702ed49SChris Mason 
1496b4ce94deSChris Mason 	btrfs_set_lock_blocking(parent);
1497b4ce94deSChris Mason 
14986702ed49SChris Mason 	for (i = start_slot; i < end_slot; i++) {
14996702ed49SChris Mason 		int close = 1;
1500a6b6e75eSChris Mason 
1501081e9573SChris Mason 		btrfs_node_key(parent, &disk_key, i);
1502081e9573SChris Mason 		if (!progress_passed && comp_keys(&disk_key, progress) < 0)
1503081e9573SChris Mason 			continue;
1504081e9573SChris Mason 
1505081e9573SChris Mason 		progress_passed = 1;
15066b80053dSChris Mason 		blocknr = btrfs_node_blockptr(parent, i);
1507ca7a79adSChris Mason 		gen = btrfs_node_ptr_generation(parent, i);
1508e9d0b13bSChris Mason 		if (last_block == 0)
1509e9d0b13bSChris Mason 			last_block = blocknr;
15105708b959SChris Mason 
15116702ed49SChris Mason 		if (i > 0) {
15126b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i - 1);
15136b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
15146702ed49SChris Mason 		}
15150ef3e66bSChris Mason 		if (!close && i < end_slot - 2) {
15166b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i + 1);
15176b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
15186702ed49SChris Mason 		}
1519e9d0b13bSChris Mason 		if (close) {
1520e9d0b13bSChris Mason 			last_block = blocknr;
15216702ed49SChris Mason 			continue;
1522e9d0b13bSChris Mason 		}
15236702ed49SChris Mason 
15246b80053dSChris Mason 		cur = btrfs_find_tree_block(root, blocknr, blocksize);
15256b80053dSChris Mason 		if (cur)
1526b9fab919SChris Mason 			uptodate = btrfs_buffer_uptodate(cur, gen, 0);
15276b80053dSChris Mason 		else
15286b80053dSChris Mason 			uptodate = 0;
15295708b959SChris Mason 		if (!cur || !uptodate) {
15306b80053dSChris Mason 			if (!cur) {
15316b80053dSChris Mason 				cur = read_tree_block(root, blocknr,
1532ca7a79adSChris Mason 							 blocksize, gen);
1533416bc658SJosef Bacik 				if (!cur || !extent_buffer_uptodate(cur)) {
1534416bc658SJosef Bacik 					free_extent_buffer(cur);
153597d9a8a4STsutomu Itoh 					return -EIO;
1536416bc658SJosef Bacik 				}
15376b80053dSChris Mason 			} else if (!uptodate) {
1538018642a1STsutomu Itoh 				err = btrfs_read_buffer(cur, gen);
1539018642a1STsutomu Itoh 				if (err) {
1540018642a1STsutomu Itoh 					free_extent_buffer(cur);
1541018642a1STsutomu Itoh 					return err;
1542018642a1STsutomu Itoh 				}
15436702ed49SChris Mason 			}
1544f2183bdeSChris Mason 		}
1545e9d0b13bSChris Mason 		if (search_start == 0)
15466b80053dSChris Mason 			search_start = last_block;
1547e9d0b13bSChris Mason 
1548e7a84565SChris Mason 		btrfs_tree_lock(cur);
1549b4ce94deSChris Mason 		btrfs_set_lock_blocking(cur);
15506b80053dSChris Mason 		err = __btrfs_cow_block(trans, root, cur, parent, i,
1551e7a84565SChris Mason 					&cur, search_start,
15526b80053dSChris Mason 					min(16 * blocksize,
15539fa8cfe7SChris Mason 					    (end_slot - i) * blocksize));
1554252c38f0SYan 		if (err) {
1555e7a84565SChris Mason 			btrfs_tree_unlock(cur);
15566b80053dSChris Mason 			free_extent_buffer(cur);
15576702ed49SChris Mason 			break;
1558252c38f0SYan 		}
1559e7a84565SChris Mason 		search_start = cur->start;
1560e7a84565SChris Mason 		last_block = cur->start;
1561f2183bdeSChris Mason 		*last_ret = search_start;
1562e7a84565SChris Mason 		btrfs_tree_unlock(cur);
1563e7a84565SChris Mason 		free_extent_buffer(cur);
15646702ed49SChris Mason 	}
15656702ed49SChris Mason 	return err;
15666702ed49SChris Mason }
15676702ed49SChris Mason 
156874123bd7SChris Mason /*
156974123bd7SChris Mason  * The leaf data grows from end-to-front in the node.
157074123bd7SChris Mason  * this returns the address of the start of the last item,
157174123bd7SChris Mason  * which is the stop of the leaf data stack
157274123bd7SChris Mason  */
1573123abc88SChris Mason static inline unsigned int leaf_data_end(struct btrfs_root *root,
15745f39d397SChris Mason 					 struct extent_buffer *leaf)
1575be0e5c09SChris Mason {
15765f39d397SChris Mason 	u32 nr = btrfs_header_nritems(leaf);
1577be0e5c09SChris Mason 	if (nr == 0)
1578123abc88SChris Mason 		return BTRFS_LEAF_DATA_SIZE(root);
15795f39d397SChris Mason 	return btrfs_item_offset_nr(leaf, nr - 1);
1580be0e5c09SChris Mason }
1581be0e5c09SChris Mason 
1582aa5d6bedSChris Mason 
158374123bd7SChris Mason /*
15845f39d397SChris Mason  * search for key in the extent_buffer.  The items start at offset p,
15855f39d397SChris Mason  * and they are item_size apart.  There are 'max' items in p.
15865f39d397SChris Mason  *
158774123bd7SChris Mason  * the slot in the array is returned via slot, and it points to
158874123bd7SChris Mason  * the place where you would insert key if it is not found in
158974123bd7SChris Mason  * the array.
159074123bd7SChris Mason  *
159174123bd7SChris Mason  * slot may point to max if the key is bigger than all of the keys
159274123bd7SChris Mason  */
1593e02119d5SChris Mason static noinline int generic_bin_search(struct extent_buffer *eb,
1594e02119d5SChris Mason 				       unsigned long p,
15955f39d397SChris Mason 				       int item_size, struct btrfs_key *key,
1596be0e5c09SChris Mason 				       int max, int *slot)
1597be0e5c09SChris Mason {
1598be0e5c09SChris Mason 	int low = 0;
1599be0e5c09SChris Mason 	int high = max;
1600be0e5c09SChris Mason 	int mid;
1601be0e5c09SChris Mason 	int ret;
1602479965d6SChris Mason 	struct btrfs_disk_key *tmp = NULL;
16035f39d397SChris Mason 	struct btrfs_disk_key unaligned;
16045f39d397SChris Mason 	unsigned long offset;
16055f39d397SChris Mason 	char *kaddr = NULL;
16065f39d397SChris Mason 	unsigned long map_start = 0;
16075f39d397SChris Mason 	unsigned long map_len = 0;
1608479965d6SChris Mason 	int err;
1609be0e5c09SChris Mason 
1610be0e5c09SChris Mason 	while (low < high) {
1611be0e5c09SChris Mason 		mid = (low + high) / 2;
16125f39d397SChris Mason 		offset = p + mid * item_size;
16135f39d397SChris Mason 
1614a6591715SChris Mason 		if (!kaddr || offset < map_start ||
16155f39d397SChris Mason 		    (offset + sizeof(struct btrfs_disk_key)) >
16165f39d397SChris Mason 		    map_start + map_len) {
1617934d375bSChris Mason 
1618934d375bSChris Mason 			err = map_private_extent_buffer(eb, offset,
1619479965d6SChris Mason 						sizeof(struct btrfs_disk_key),
1620a6591715SChris Mason 						&kaddr, &map_start, &map_len);
16215f39d397SChris Mason 
1622479965d6SChris Mason 			if (!err) {
1623479965d6SChris Mason 				tmp = (struct btrfs_disk_key *)(kaddr + offset -
1624479965d6SChris Mason 							map_start);
1625479965d6SChris Mason 			} else {
16265f39d397SChris Mason 				read_extent_buffer(eb, &unaligned,
16275f39d397SChris Mason 						   offset, sizeof(unaligned));
16285f39d397SChris Mason 				tmp = &unaligned;
1629479965d6SChris Mason 			}
1630479965d6SChris Mason 
16315f39d397SChris Mason 		} else {
16325f39d397SChris Mason 			tmp = (struct btrfs_disk_key *)(kaddr + offset -
16335f39d397SChris Mason 							map_start);
16345f39d397SChris Mason 		}
1635be0e5c09SChris Mason 		ret = comp_keys(tmp, key);
1636be0e5c09SChris Mason 
1637be0e5c09SChris Mason 		if (ret < 0)
1638be0e5c09SChris Mason 			low = mid + 1;
1639be0e5c09SChris Mason 		else if (ret > 0)
1640be0e5c09SChris Mason 			high = mid;
1641be0e5c09SChris Mason 		else {
1642be0e5c09SChris Mason 			*slot = mid;
1643be0e5c09SChris Mason 			return 0;
1644be0e5c09SChris Mason 		}
1645be0e5c09SChris Mason 	}
1646be0e5c09SChris Mason 	*slot = low;
1647be0e5c09SChris Mason 	return 1;
1648be0e5c09SChris Mason }
1649be0e5c09SChris Mason 
165097571fd0SChris Mason /*
165197571fd0SChris Mason  * simple bin_search frontend that does the right thing for
165297571fd0SChris Mason  * leaves vs nodes
165397571fd0SChris Mason  */
16545f39d397SChris Mason static int bin_search(struct extent_buffer *eb, struct btrfs_key *key,
16555f39d397SChris Mason 		      int level, int *slot)
1656be0e5c09SChris Mason {
1657f775738fSWang Sheng-Hui 	if (level == 0)
16585f39d397SChris Mason 		return generic_bin_search(eb,
16595f39d397SChris Mason 					  offsetof(struct btrfs_leaf, items),
16600783fcfcSChris Mason 					  sizeof(struct btrfs_item),
16615f39d397SChris Mason 					  key, btrfs_header_nritems(eb),
16627518a238SChris Mason 					  slot);
1663f775738fSWang Sheng-Hui 	else
16645f39d397SChris Mason 		return generic_bin_search(eb,
16655f39d397SChris Mason 					  offsetof(struct btrfs_node, ptrs),
1666123abc88SChris Mason 					  sizeof(struct btrfs_key_ptr),
16675f39d397SChris Mason 					  key, btrfs_header_nritems(eb),
16687518a238SChris Mason 					  slot);
1669be0e5c09SChris Mason }
1670be0e5c09SChris Mason 
16715d4f98a2SYan Zheng int btrfs_bin_search(struct extent_buffer *eb, struct btrfs_key *key,
16725d4f98a2SYan Zheng 		     int level, int *slot)
16735d4f98a2SYan Zheng {
16745d4f98a2SYan Zheng 	return bin_search(eb, key, level, slot);
16755d4f98a2SYan Zheng }
16765d4f98a2SYan Zheng 
1677f0486c68SYan, Zheng static void root_add_used(struct btrfs_root *root, u32 size)
1678f0486c68SYan, Zheng {
1679f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
1680f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
1681f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) + size);
1682f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
1683f0486c68SYan, Zheng }
1684f0486c68SYan, Zheng 
1685f0486c68SYan, Zheng static void root_sub_used(struct btrfs_root *root, u32 size)
1686f0486c68SYan, Zheng {
1687f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
1688f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
1689f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) - size);
1690f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
1691f0486c68SYan, Zheng }
1692f0486c68SYan, Zheng 
1693d352ac68SChris Mason /* given a node and slot number, this reads the blocks it points to.  The
1694d352ac68SChris Mason  * extent buffer is returned with a reference taken (but unlocked).
1695d352ac68SChris Mason  * NULL is returned on error.
1696d352ac68SChris Mason  */
1697e02119d5SChris Mason static noinline struct extent_buffer *read_node_slot(struct btrfs_root *root,
16985f39d397SChris Mason 				   struct extent_buffer *parent, int slot)
1699bb803951SChris Mason {
1700ca7a79adSChris Mason 	int level = btrfs_header_level(parent);
1701416bc658SJosef Bacik 	struct extent_buffer *eb;
1702416bc658SJosef Bacik 
1703bb803951SChris Mason 	if (slot < 0)
1704bb803951SChris Mason 		return NULL;
17055f39d397SChris Mason 	if (slot >= btrfs_header_nritems(parent))
1706bb803951SChris Mason 		return NULL;
1707ca7a79adSChris Mason 
1708ca7a79adSChris Mason 	BUG_ON(level == 0);
1709ca7a79adSChris Mason 
1710416bc658SJosef Bacik 	eb = read_tree_block(root, btrfs_node_blockptr(parent, slot),
1711ca7a79adSChris Mason 			     btrfs_level_size(root, level - 1),
1712ca7a79adSChris Mason 			     btrfs_node_ptr_generation(parent, slot));
1713416bc658SJosef Bacik 	if (eb && !extent_buffer_uptodate(eb)) {
1714416bc658SJosef Bacik 		free_extent_buffer(eb);
1715416bc658SJosef Bacik 		eb = NULL;
1716416bc658SJosef Bacik 	}
1717416bc658SJosef Bacik 
1718416bc658SJosef Bacik 	return eb;
1719bb803951SChris Mason }
1720bb803951SChris Mason 
1721d352ac68SChris Mason /*
1722d352ac68SChris Mason  * node level balancing, used to make sure nodes are in proper order for
1723d352ac68SChris Mason  * item deletion.  We balance from the top down, so we have to make sure
1724d352ac68SChris Mason  * that a deletion won't leave an node completely empty later on.
1725d352ac68SChris Mason  */
1726e02119d5SChris Mason static noinline int balance_level(struct btrfs_trans_handle *trans,
172798ed5174SChris Mason 			 struct btrfs_root *root,
172898ed5174SChris Mason 			 struct btrfs_path *path, int level)
1729bb803951SChris Mason {
17305f39d397SChris Mason 	struct extent_buffer *right = NULL;
17315f39d397SChris Mason 	struct extent_buffer *mid;
17325f39d397SChris Mason 	struct extent_buffer *left = NULL;
17335f39d397SChris Mason 	struct extent_buffer *parent = NULL;
1734bb803951SChris Mason 	int ret = 0;
1735bb803951SChris Mason 	int wret;
1736bb803951SChris Mason 	int pslot;
1737bb803951SChris Mason 	int orig_slot = path->slots[level];
173879f95c82SChris Mason 	u64 orig_ptr;
1739bb803951SChris Mason 
1740bb803951SChris Mason 	if (level == 0)
1741bb803951SChris Mason 		return 0;
1742bb803951SChris Mason 
17435f39d397SChris Mason 	mid = path->nodes[level];
1744b4ce94deSChris Mason 
1745bd681513SChris Mason 	WARN_ON(path->locks[level] != BTRFS_WRITE_LOCK &&
1746bd681513SChris Mason 		path->locks[level] != BTRFS_WRITE_LOCK_BLOCKING);
17477bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
17487bb86316SChris Mason 
17491d4f8a0cSChris Mason 	orig_ptr = btrfs_node_blockptr(mid, orig_slot);
175079f95c82SChris Mason 
1751a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
17525f39d397SChris Mason 		parent = path->nodes[level + 1];
1753bb803951SChris Mason 		pslot = path->slots[level + 1];
1754a05a9bb1SLi Zefan 	}
1755bb803951SChris Mason 
175640689478SChris Mason 	/*
175740689478SChris Mason 	 * deal with the case where there is only one pointer in the root
175840689478SChris Mason 	 * by promoting the node below to a root
175940689478SChris Mason 	 */
17605f39d397SChris Mason 	if (!parent) {
17615f39d397SChris Mason 		struct extent_buffer *child;
1762bb803951SChris Mason 
17635f39d397SChris Mason 		if (btrfs_header_nritems(mid) != 1)
1764bb803951SChris Mason 			return 0;
1765bb803951SChris Mason 
1766bb803951SChris Mason 		/* promote the child to a root */
17675f39d397SChris Mason 		child = read_node_slot(root, mid, 0);
1768305a26afSMark Fasheh 		if (!child) {
1769305a26afSMark Fasheh 			ret = -EROFS;
1770305a26afSMark Fasheh 			btrfs_std_error(root->fs_info, ret);
1771305a26afSMark Fasheh 			goto enospc;
1772305a26afSMark Fasheh 		}
1773305a26afSMark Fasheh 
1774925baeddSChris Mason 		btrfs_tree_lock(child);
1775b4ce94deSChris Mason 		btrfs_set_lock_blocking(child);
17769fa8cfe7SChris Mason 		ret = btrfs_cow_block(trans, root, child, mid, 0, &child);
1777f0486c68SYan, Zheng 		if (ret) {
1778f0486c68SYan, Zheng 			btrfs_tree_unlock(child);
1779f0486c68SYan, Zheng 			free_extent_buffer(child);
1780f0486c68SYan, Zheng 			goto enospc;
1781f0486c68SYan, Zheng 		}
17822f375ab9SYan 
178390f8d62eSJan Schmidt 		tree_mod_log_set_root_pointer(root, child, 1);
1784240f62c8SChris Mason 		rcu_assign_pointer(root->node, child);
1785925baeddSChris Mason 
17860b86a832SChris Mason 		add_root_to_dirty_list(root);
1787925baeddSChris Mason 		btrfs_tree_unlock(child);
1788b4ce94deSChris Mason 
1789925baeddSChris Mason 		path->locks[level] = 0;
1790bb803951SChris Mason 		path->nodes[level] = NULL;
17915f39d397SChris Mason 		clean_tree_block(trans, root, mid);
1792925baeddSChris Mason 		btrfs_tree_unlock(mid);
1793bb803951SChris Mason 		/* once for the path */
17945f39d397SChris Mason 		free_extent_buffer(mid);
1795f0486c68SYan, Zheng 
1796f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
17975581a51aSJan Schmidt 		btrfs_free_tree_block(trans, root, mid, 0, 1);
1798bb803951SChris Mason 		/* once for the root ptr */
17993083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
1800f0486c68SYan, Zheng 		return 0;
1801bb803951SChris Mason 	}
18025f39d397SChris Mason 	if (btrfs_header_nritems(mid) >
1803123abc88SChris Mason 	    BTRFS_NODEPTRS_PER_BLOCK(root) / 4)
1804bb803951SChris Mason 		return 0;
1805bb803951SChris Mason 
18065f39d397SChris Mason 	left = read_node_slot(root, parent, pslot - 1);
18075f39d397SChris Mason 	if (left) {
1808925baeddSChris Mason 		btrfs_tree_lock(left);
1809b4ce94deSChris Mason 		btrfs_set_lock_blocking(left);
18105f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, left,
18119fa8cfe7SChris Mason 				       parent, pslot - 1, &left);
181254aa1f4dSChris Mason 		if (wret) {
181354aa1f4dSChris Mason 			ret = wret;
181454aa1f4dSChris Mason 			goto enospc;
181554aa1f4dSChris Mason 		}
18162cc58cf2SChris Mason 	}
18175f39d397SChris Mason 	right = read_node_slot(root, parent, pslot + 1);
18185f39d397SChris Mason 	if (right) {
1819925baeddSChris Mason 		btrfs_tree_lock(right);
1820b4ce94deSChris Mason 		btrfs_set_lock_blocking(right);
18215f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, right,
18229fa8cfe7SChris Mason 				       parent, pslot + 1, &right);
18232cc58cf2SChris Mason 		if (wret) {
18242cc58cf2SChris Mason 			ret = wret;
18252cc58cf2SChris Mason 			goto enospc;
18262cc58cf2SChris Mason 		}
18272cc58cf2SChris Mason 	}
18282cc58cf2SChris Mason 
18292cc58cf2SChris Mason 	/* first, try to make some room in the middle buffer */
18305f39d397SChris Mason 	if (left) {
18315f39d397SChris Mason 		orig_slot += btrfs_header_nritems(left);
1832bce4eae9SChris Mason 		wret = push_node_left(trans, root, left, mid, 1);
183379f95c82SChris Mason 		if (wret < 0)
183479f95c82SChris Mason 			ret = wret;
1835bb803951SChris Mason 	}
183679f95c82SChris Mason 
183779f95c82SChris Mason 	/*
183879f95c82SChris Mason 	 * then try to empty the right most buffer into the middle
183979f95c82SChris Mason 	 */
18405f39d397SChris Mason 	if (right) {
1841971a1f66SChris Mason 		wret = push_node_left(trans, root, mid, right, 1);
184254aa1f4dSChris Mason 		if (wret < 0 && wret != -ENOSPC)
184379f95c82SChris Mason 			ret = wret;
18445f39d397SChris Mason 		if (btrfs_header_nritems(right) == 0) {
18455f39d397SChris Mason 			clean_tree_block(trans, root, right);
1846925baeddSChris Mason 			btrfs_tree_unlock(right);
1847afe5fea7STsutomu Itoh 			del_ptr(root, path, level + 1, pslot + 1);
1848f0486c68SYan, Zheng 			root_sub_used(root, right->len);
18495581a51aSJan Schmidt 			btrfs_free_tree_block(trans, root, right, 0, 1);
18503083ee2eSJosef Bacik 			free_extent_buffer_stale(right);
1851f0486c68SYan, Zheng 			right = NULL;
1852bb803951SChris Mason 		} else {
18535f39d397SChris Mason 			struct btrfs_disk_key right_key;
18545f39d397SChris Mason 			btrfs_node_key(right, &right_key, 0);
1855f230475eSJan Schmidt 			tree_mod_log_set_node_key(root->fs_info, parent,
185632adf090SLiu Bo 						  pslot + 1, 0);
18575f39d397SChris Mason 			btrfs_set_node_key(parent, &right_key, pslot + 1);
18585f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
1859bb803951SChris Mason 		}
1860bb803951SChris Mason 	}
18615f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 1) {
186279f95c82SChris Mason 		/*
186379f95c82SChris Mason 		 * we're not allowed to leave a node with one item in the
186479f95c82SChris Mason 		 * tree during a delete.  A deletion from lower in the tree
186579f95c82SChris Mason 		 * could try to delete the only pointer in this node.
186679f95c82SChris Mason 		 * So, pull some keys from the left.
186779f95c82SChris Mason 		 * There has to be a left pointer at this point because
186879f95c82SChris Mason 		 * otherwise we would have pulled some pointers from the
186979f95c82SChris Mason 		 * right
187079f95c82SChris Mason 		 */
1871305a26afSMark Fasheh 		if (!left) {
1872305a26afSMark Fasheh 			ret = -EROFS;
1873305a26afSMark Fasheh 			btrfs_std_error(root->fs_info, ret);
1874305a26afSMark Fasheh 			goto enospc;
1875305a26afSMark Fasheh 		}
18765f39d397SChris Mason 		wret = balance_node_right(trans, root, mid, left);
187754aa1f4dSChris Mason 		if (wret < 0) {
187879f95c82SChris Mason 			ret = wret;
187954aa1f4dSChris Mason 			goto enospc;
188054aa1f4dSChris Mason 		}
1881bce4eae9SChris Mason 		if (wret == 1) {
1882bce4eae9SChris Mason 			wret = push_node_left(trans, root, left, mid, 1);
1883bce4eae9SChris Mason 			if (wret < 0)
1884bce4eae9SChris Mason 				ret = wret;
1885bce4eae9SChris Mason 		}
188679f95c82SChris Mason 		BUG_ON(wret == 1);
188779f95c82SChris Mason 	}
18885f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 0) {
18895f39d397SChris Mason 		clean_tree_block(trans, root, mid);
1890925baeddSChris Mason 		btrfs_tree_unlock(mid);
1891afe5fea7STsutomu Itoh 		del_ptr(root, path, level + 1, pslot);
1892f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
18935581a51aSJan Schmidt 		btrfs_free_tree_block(trans, root, mid, 0, 1);
18943083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
1895f0486c68SYan, Zheng 		mid = NULL;
189679f95c82SChris Mason 	} else {
189779f95c82SChris Mason 		/* update the parent key to reflect our changes */
18985f39d397SChris Mason 		struct btrfs_disk_key mid_key;
18995f39d397SChris Mason 		btrfs_node_key(mid, &mid_key, 0);
190032adf090SLiu Bo 		tree_mod_log_set_node_key(root->fs_info, parent,
1901f230475eSJan Schmidt 					  pslot, 0);
19025f39d397SChris Mason 		btrfs_set_node_key(parent, &mid_key, pslot);
19035f39d397SChris Mason 		btrfs_mark_buffer_dirty(parent);
190479f95c82SChris Mason 	}
1905bb803951SChris Mason 
190679f95c82SChris Mason 	/* update the path */
19075f39d397SChris Mason 	if (left) {
19085f39d397SChris Mason 		if (btrfs_header_nritems(left) > orig_slot) {
19095f39d397SChris Mason 			extent_buffer_get(left);
1910925baeddSChris Mason 			/* left was locked after cow */
19115f39d397SChris Mason 			path->nodes[level] = left;
1912bb803951SChris Mason 			path->slots[level + 1] -= 1;
1913bb803951SChris Mason 			path->slots[level] = orig_slot;
1914925baeddSChris Mason 			if (mid) {
1915925baeddSChris Mason 				btrfs_tree_unlock(mid);
19165f39d397SChris Mason 				free_extent_buffer(mid);
1917925baeddSChris Mason 			}
1918bb803951SChris Mason 		} else {
19195f39d397SChris Mason 			orig_slot -= btrfs_header_nritems(left);
1920bb803951SChris Mason 			path->slots[level] = orig_slot;
1921bb803951SChris Mason 		}
1922bb803951SChris Mason 	}
192379f95c82SChris Mason 	/* double check we haven't messed things up */
1924e20d96d6SChris Mason 	if (orig_ptr !=
19255f39d397SChris Mason 	    btrfs_node_blockptr(path->nodes[level], path->slots[level]))
192679f95c82SChris Mason 		BUG();
192754aa1f4dSChris Mason enospc:
1928925baeddSChris Mason 	if (right) {
1929925baeddSChris Mason 		btrfs_tree_unlock(right);
19305f39d397SChris Mason 		free_extent_buffer(right);
1931925baeddSChris Mason 	}
1932925baeddSChris Mason 	if (left) {
1933925baeddSChris Mason 		if (path->nodes[level] != left)
1934925baeddSChris Mason 			btrfs_tree_unlock(left);
19355f39d397SChris Mason 		free_extent_buffer(left);
1936925baeddSChris Mason 	}
1937bb803951SChris Mason 	return ret;
1938bb803951SChris Mason }
1939bb803951SChris Mason 
1940d352ac68SChris Mason /* Node balancing for insertion.  Here we only split or push nodes around
1941d352ac68SChris Mason  * when they are completely full.  This is also done top down, so we
1942d352ac68SChris Mason  * have to be pessimistic.
1943d352ac68SChris Mason  */
1944d397712bSChris Mason static noinline int push_nodes_for_insert(struct btrfs_trans_handle *trans,
1945e66f709bSChris Mason 					  struct btrfs_root *root,
1946e66f709bSChris Mason 					  struct btrfs_path *path, int level)
1947e66f709bSChris Mason {
19485f39d397SChris Mason 	struct extent_buffer *right = NULL;
19495f39d397SChris Mason 	struct extent_buffer *mid;
19505f39d397SChris Mason 	struct extent_buffer *left = NULL;
19515f39d397SChris Mason 	struct extent_buffer *parent = NULL;
1952e66f709bSChris Mason 	int ret = 0;
1953e66f709bSChris Mason 	int wret;
1954e66f709bSChris Mason 	int pslot;
1955e66f709bSChris Mason 	int orig_slot = path->slots[level];
1956e66f709bSChris Mason 
1957e66f709bSChris Mason 	if (level == 0)
1958e66f709bSChris Mason 		return 1;
1959e66f709bSChris Mason 
19605f39d397SChris Mason 	mid = path->nodes[level];
19617bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
1962e66f709bSChris Mason 
1963a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
19645f39d397SChris Mason 		parent = path->nodes[level + 1];
1965e66f709bSChris Mason 		pslot = path->slots[level + 1];
1966a05a9bb1SLi Zefan 	}
1967e66f709bSChris Mason 
19685f39d397SChris Mason 	if (!parent)
1969e66f709bSChris Mason 		return 1;
1970e66f709bSChris Mason 
19715f39d397SChris Mason 	left = read_node_slot(root, parent, pslot - 1);
1972e66f709bSChris Mason 
1973e66f709bSChris Mason 	/* first, try to make some room in the middle buffer */
19745f39d397SChris Mason 	if (left) {
1975e66f709bSChris Mason 		u32 left_nr;
1976925baeddSChris Mason 
1977925baeddSChris Mason 		btrfs_tree_lock(left);
1978b4ce94deSChris Mason 		btrfs_set_lock_blocking(left);
1979b4ce94deSChris Mason 
19805f39d397SChris Mason 		left_nr = btrfs_header_nritems(left);
198133ade1f8SChris Mason 		if (left_nr >= BTRFS_NODEPTRS_PER_BLOCK(root) - 1) {
198233ade1f8SChris Mason 			wret = 1;
198333ade1f8SChris Mason 		} else {
19845f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, left, parent,
19859fa8cfe7SChris Mason 					      pslot - 1, &left);
198654aa1f4dSChris Mason 			if (ret)
198754aa1f4dSChris Mason 				wret = 1;
198854aa1f4dSChris Mason 			else {
198954aa1f4dSChris Mason 				wret = push_node_left(trans, root,
1990971a1f66SChris Mason 						      left, mid, 0);
199154aa1f4dSChris Mason 			}
199233ade1f8SChris Mason 		}
1993e66f709bSChris Mason 		if (wret < 0)
1994e66f709bSChris Mason 			ret = wret;
1995e66f709bSChris Mason 		if (wret == 0) {
19965f39d397SChris Mason 			struct btrfs_disk_key disk_key;
1997e66f709bSChris Mason 			orig_slot += left_nr;
19985f39d397SChris Mason 			btrfs_node_key(mid, &disk_key, 0);
1999f230475eSJan Schmidt 			tree_mod_log_set_node_key(root->fs_info, parent,
200032adf090SLiu Bo 						  pslot, 0);
20015f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot);
20025f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
20035f39d397SChris Mason 			if (btrfs_header_nritems(left) > orig_slot) {
20045f39d397SChris Mason 				path->nodes[level] = left;
2005e66f709bSChris Mason 				path->slots[level + 1] -= 1;
2006e66f709bSChris Mason 				path->slots[level] = orig_slot;
2007925baeddSChris Mason 				btrfs_tree_unlock(mid);
20085f39d397SChris Mason 				free_extent_buffer(mid);
2009e66f709bSChris Mason 			} else {
2010e66f709bSChris Mason 				orig_slot -=
20115f39d397SChris Mason 					btrfs_header_nritems(left);
2012e66f709bSChris Mason 				path->slots[level] = orig_slot;
2013925baeddSChris Mason 				btrfs_tree_unlock(left);
20145f39d397SChris Mason 				free_extent_buffer(left);
2015e66f709bSChris Mason 			}
2016e66f709bSChris Mason 			return 0;
2017e66f709bSChris Mason 		}
2018925baeddSChris Mason 		btrfs_tree_unlock(left);
20195f39d397SChris Mason 		free_extent_buffer(left);
2020e66f709bSChris Mason 	}
20215f39d397SChris Mason 	right = read_node_slot(root, parent, pslot + 1);
2022e66f709bSChris Mason 
2023e66f709bSChris Mason 	/*
2024e66f709bSChris Mason 	 * then try to empty the right most buffer into the middle
2025e66f709bSChris Mason 	 */
20265f39d397SChris Mason 	if (right) {
202733ade1f8SChris Mason 		u32 right_nr;
2028b4ce94deSChris Mason 
2029925baeddSChris Mason 		btrfs_tree_lock(right);
2030b4ce94deSChris Mason 		btrfs_set_lock_blocking(right);
2031b4ce94deSChris Mason 
20325f39d397SChris Mason 		right_nr = btrfs_header_nritems(right);
203333ade1f8SChris Mason 		if (right_nr >= BTRFS_NODEPTRS_PER_BLOCK(root) - 1) {
203433ade1f8SChris Mason 			wret = 1;
203533ade1f8SChris Mason 		} else {
20365f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, right,
20375f39d397SChris Mason 					      parent, pslot + 1,
20389fa8cfe7SChris Mason 					      &right);
203954aa1f4dSChris Mason 			if (ret)
204054aa1f4dSChris Mason 				wret = 1;
204154aa1f4dSChris Mason 			else {
204233ade1f8SChris Mason 				wret = balance_node_right(trans, root,
20435f39d397SChris Mason 							  right, mid);
204433ade1f8SChris Mason 			}
204554aa1f4dSChris Mason 		}
2046e66f709bSChris Mason 		if (wret < 0)
2047e66f709bSChris Mason 			ret = wret;
2048e66f709bSChris Mason 		if (wret == 0) {
20495f39d397SChris Mason 			struct btrfs_disk_key disk_key;
20505f39d397SChris Mason 
20515f39d397SChris Mason 			btrfs_node_key(right, &disk_key, 0);
2052f230475eSJan Schmidt 			tree_mod_log_set_node_key(root->fs_info, parent,
205332adf090SLiu Bo 						  pslot + 1, 0);
20545f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot + 1);
20555f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
20565f39d397SChris Mason 
20575f39d397SChris Mason 			if (btrfs_header_nritems(mid) <= orig_slot) {
20585f39d397SChris Mason 				path->nodes[level] = right;
2059e66f709bSChris Mason 				path->slots[level + 1] += 1;
2060e66f709bSChris Mason 				path->slots[level] = orig_slot -
20615f39d397SChris Mason 					btrfs_header_nritems(mid);
2062925baeddSChris Mason 				btrfs_tree_unlock(mid);
20635f39d397SChris Mason 				free_extent_buffer(mid);
2064e66f709bSChris Mason 			} else {
2065925baeddSChris Mason 				btrfs_tree_unlock(right);
20665f39d397SChris Mason 				free_extent_buffer(right);
2067e66f709bSChris Mason 			}
2068e66f709bSChris Mason 			return 0;
2069e66f709bSChris Mason 		}
2070925baeddSChris Mason 		btrfs_tree_unlock(right);
20715f39d397SChris Mason 		free_extent_buffer(right);
2072e66f709bSChris Mason 	}
2073e66f709bSChris Mason 	return 1;
2074e66f709bSChris Mason }
2075e66f709bSChris Mason 
207674123bd7SChris Mason /*
2077d352ac68SChris Mason  * readahead one full node of leaves, finding things that are close
2078d352ac68SChris Mason  * to the block in 'slot', and triggering ra on them.
20793c69faecSChris Mason  */
2080c8c42864SChris Mason static void reada_for_search(struct btrfs_root *root,
2081e02119d5SChris Mason 			     struct btrfs_path *path,
208201f46658SChris Mason 			     int level, int slot, u64 objectid)
20833c69faecSChris Mason {
20845f39d397SChris Mason 	struct extent_buffer *node;
208501f46658SChris Mason 	struct btrfs_disk_key disk_key;
20863c69faecSChris Mason 	u32 nritems;
20873c69faecSChris Mason 	u64 search;
2088a7175319SChris Mason 	u64 target;
20896b80053dSChris Mason 	u64 nread = 0;
2090cb25c2eaSJosef Bacik 	u64 gen;
20913c69faecSChris Mason 	int direction = path->reada;
20925f39d397SChris Mason 	struct extent_buffer *eb;
20936b80053dSChris Mason 	u32 nr;
20946b80053dSChris Mason 	u32 blocksize;
20956b80053dSChris Mason 	u32 nscan = 0;
2096db94535dSChris Mason 
2097a6b6e75eSChris Mason 	if (level != 1)
20983c69faecSChris Mason 		return;
20993c69faecSChris Mason 
21006702ed49SChris Mason 	if (!path->nodes[level])
21016702ed49SChris Mason 		return;
21026702ed49SChris Mason 
21035f39d397SChris Mason 	node = path->nodes[level];
2104925baeddSChris Mason 
21053c69faecSChris Mason 	search = btrfs_node_blockptr(node, slot);
21066b80053dSChris Mason 	blocksize = btrfs_level_size(root, level - 1);
21076b80053dSChris Mason 	eb = btrfs_find_tree_block(root, search, blocksize);
21085f39d397SChris Mason 	if (eb) {
21095f39d397SChris Mason 		free_extent_buffer(eb);
21103c69faecSChris Mason 		return;
21113c69faecSChris Mason 	}
21123c69faecSChris Mason 
2113a7175319SChris Mason 	target = search;
21146b80053dSChris Mason 
21155f39d397SChris Mason 	nritems = btrfs_header_nritems(node);
21166b80053dSChris Mason 	nr = slot;
211725b8b936SJosef Bacik 
21183c69faecSChris Mason 	while (1) {
21196b80053dSChris Mason 		if (direction < 0) {
21206b80053dSChris Mason 			if (nr == 0)
21213c69faecSChris Mason 				break;
21226b80053dSChris Mason 			nr--;
21236b80053dSChris Mason 		} else if (direction > 0) {
21246b80053dSChris Mason 			nr++;
21256b80053dSChris Mason 			if (nr >= nritems)
21266b80053dSChris Mason 				break;
21273c69faecSChris Mason 		}
212801f46658SChris Mason 		if (path->reada < 0 && objectid) {
212901f46658SChris Mason 			btrfs_node_key(node, &disk_key, nr);
213001f46658SChris Mason 			if (btrfs_disk_key_objectid(&disk_key) != objectid)
213101f46658SChris Mason 				break;
213201f46658SChris Mason 		}
21336b80053dSChris Mason 		search = btrfs_node_blockptr(node, nr);
2134a7175319SChris Mason 		if ((search <= target && target - search <= 65536) ||
2135a7175319SChris Mason 		    (search > target && search - target <= 65536)) {
2136cb25c2eaSJosef Bacik 			gen = btrfs_node_ptr_generation(node, nr);
2137cb25c2eaSJosef Bacik 			readahead_tree_block(root, search, blocksize, gen);
21386b80053dSChris Mason 			nread += blocksize;
21393c69faecSChris Mason 		}
21406b80053dSChris Mason 		nscan++;
2141a7175319SChris Mason 		if ((nread > 65536 || nscan > 32))
21426b80053dSChris Mason 			break;
21433c69faecSChris Mason 	}
21443c69faecSChris Mason }
2145925baeddSChris Mason 
21460b08851fSJosef Bacik static noinline void reada_for_balance(struct btrfs_root *root,
2147b4ce94deSChris Mason 				       struct btrfs_path *path, int level)
2148b4ce94deSChris Mason {
2149b4ce94deSChris Mason 	int slot;
2150b4ce94deSChris Mason 	int nritems;
2151b4ce94deSChris Mason 	struct extent_buffer *parent;
2152b4ce94deSChris Mason 	struct extent_buffer *eb;
2153b4ce94deSChris Mason 	u64 gen;
2154b4ce94deSChris Mason 	u64 block1 = 0;
2155b4ce94deSChris Mason 	u64 block2 = 0;
2156b4ce94deSChris Mason 	int blocksize;
2157b4ce94deSChris Mason 
21588c594ea8SChris Mason 	parent = path->nodes[level + 1];
2159b4ce94deSChris Mason 	if (!parent)
21600b08851fSJosef Bacik 		return;
2161b4ce94deSChris Mason 
2162b4ce94deSChris Mason 	nritems = btrfs_header_nritems(parent);
21638c594ea8SChris Mason 	slot = path->slots[level + 1];
2164b4ce94deSChris Mason 	blocksize = btrfs_level_size(root, level);
2165b4ce94deSChris Mason 
2166b4ce94deSChris Mason 	if (slot > 0) {
2167b4ce94deSChris Mason 		block1 = btrfs_node_blockptr(parent, slot - 1);
2168b4ce94deSChris Mason 		gen = btrfs_node_ptr_generation(parent, slot - 1);
2169b4ce94deSChris Mason 		eb = btrfs_find_tree_block(root, block1, blocksize);
2170b9fab919SChris Mason 		/*
2171b9fab919SChris Mason 		 * if we get -eagain from btrfs_buffer_uptodate, we
2172b9fab919SChris Mason 		 * don't want to return eagain here.  That will loop
2173b9fab919SChris Mason 		 * forever
2174b9fab919SChris Mason 		 */
2175b9fab919SChris Mason 		if (eb && btrfs_buffer_uptodate(eb, gen, 1) != 0)
2176b4ce94deSChris Mason 			block1 = 0;
2177b4ce94deSChris Mason 		free_extent_buffer(eb);
2178b4ce94deSChris Mason 	}
21798c594ea8SChris Mason 	if (slot + 1 < nritems) {
2180b4ce94deSChris Mason 		block2 = btrfs_node_blockptr(parent, slot + 1);
2181b4ce94deSChris Mason 		gen = btrfs_node_ptr_generation(parent, slot + 1);
2182b4ce94deSChris Mason 		eb = btrfs_find_tree_block(root, block2, blocksize);
2183b9fab919SChris Mason 		if (eb && btrfs_buffer_uptodate(eb, gen, 1) != 0)
2184b4ce94deSChris Mason 			block2 = 0;
2185b4ce94deSChris Mason 		free_extent_buffer(eb);
2186b4ce94deSChris Mason 	}
21878c594ea8SChris Mason 
2188b4ce94deSChris Mason 	if (block1)
2189b4ce94deSChris Mason 		readahead_tree_block(root, block1, blocksize, 0);
2190b4ce94deSChris Mason 	if (block2)
2191b4ce94deSChris Mason 		readahead_tree_block(root, block2, blocksize, 0);
2192b4ce94deSChris Mason }
2193b4ce94deSChris Mason 
2194b4ce94deSChris Mason 
2195b4ce94deSChris Mason /*
2196d397712bSChris Mason  * when we walk down the tree, it is usually safe to unlock the higher layers
2197d397712bSChris Mason  * in the tree.  The exceptions are when our path goes through slot 0, because
2198d397712bSChris Mason  * operations on the tree might require changing key pointers higher up in the
2199d397712bSChris Mason  * tree.
2200d352ac68SChris Mason  *
2201d397712bSChris Mason  * callers might also have set path->keep_locks, which tells this code to keep
2202d397712bSChris Mason  * the lock if the path points to the last slot in the block.  This is part of
2203d397712bSChris Mason  * walking through the tree, and selecting the next slot in the higher block.
2204d352ac68SChris Mason  *
2205d397712bSChris Mason  * lowest_unlock sets the lowest level in the tree we're allowed to unlock.  so
2206d397712bSChris Mason  * if lowest_unlock is 1, level 0 won't be unlocked
2207d352ac68SChris Mason  */
2208e02119d5SChris Mason static noinline void unlock_up(struct btrfs_path *path, int level,
2209f7c79f30SChris Mason 			       int lowest_unlock, int min_write_lock_level,
2210f7c79f30SChris Mason 			       int *write_lock_level)
2211925baeddSChris Mason {
2212925baeddSChris Mason 	int i;
2213925baeddSChris Mason 	int skip_level = level;
2214051e1b9fSChris Mason 	int no_skips = 0;
2215925baeddSChris Mason 	struct extent_buffer *t;
2216925baeddSChris Mason 
2217925baeddSChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2218925baeddSChris Mason 		if (!path->nodes[i])
2219925baeddSChris Mason 			break;
2220925baeddSChris Mason 		if (!path->locks[i])
2221925baeddSChris Mason 			break;
2222051e1b9fSChris Mason 		if (!no_skips && path->slots[i] == 0) {
2223925baeddSChris Mason 			skip_level = i + 1;
2224925baeddSChris Mason 			continue;
2225925baeddSChris Mason 		}
2226051e1b9fSChris Mason 		if (!no_skips && path->keep_locks) {
2227925baeddSChris Mason 			u32 nritems;
2228925baeddSChris Mason 			t = path->nodes[i];
2229925baeddSChris Mason 			nritems = btrfs_header_nritems(t);
2230051e1b9fSChris Mason 			if (nritems < 1 || path->slots[i] >= nritems - 1) {
2231925baeddSChris Mason 				skip_level = i + 1;
2232925baeddSChris Mason 				continue;
2233925baeddSChris Mason 			}
2234925baeddSChris Mason 		}
2235051e1b9fSChris Mason 		if (skip_level < i && i >= lowest_unlock)
2236051e1b9fSChris Mason 			no_skips = 1;
2237051e1b9fSChris Mason 
2238925baeddSChris Mason 		t = path->nodes[i];
2239925baeddSChris Mason 		if (i >= lowest_unlock && i > skip_level && path->locks[i]) {
2240bd681513SChris Mason 			btrfs_tree_unlock_rw(t, path->locks[i]);
2241925baeddSChris Mason 			path->locks[i] = 0;
2242f7c79f30SChris Mason 			if (write_lock_level &&
2243f7c79f30SChris Mason 			    i > min_write_lock_level &&
2244f7c79f30SChris Mason 			    i <= *write_lock_level) {
2245f7c79f30SChris Mason 				*write_lock_level = i - 1;
2246f7c79f30SChris Mason 			}
2247925baeddSChris Mason 		}
2248925baeddSChris Mason 	}
2249925baeddSChris Mason }
2250925baeddSChris Mason 
22513c69faecSChris Mason /*
2252b4ce94deSChris Mason  * This releases any locks held in the path starting at level and
2253b4ce94deSChris Mason  * going all the way up to the root.
2254b4ce94deSChris Mason  *
2255b4ce94deSChris Mason  * btrfs_search_slot will keep the lock held on higher nodes in a few
2256b4ce94deSChris Mason  * corner cases, such as COW of the block at slot zero in the node.  This
2257b4ce94deSChris Mason  * ignores those rules, and it should only be called when there are no
2258b4ce94deSChris Mason  * more updates to be done higher up in the tree.
2259b4ce94deSChris Mason  */
2260b4ce94deSChris Mason noinline void btrfs_unlock_up_safe(struct btrfs_path *path, int level)
2261b4ce94deSChris Mason {
2262b4ce94deSChris Mason 	int i;
2263b4ce94deSChris Mason 
226409a2a8f9SJosef Bacik 	if (path->keep_locks)
2265b4ce94deSChris Mason 		return;
2266b4ce94deSChris Mason 
2267b4ce94deSChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2268b4ce94deSChris Mason 		if (!path->nodes[i])
226912f4daccSChris Mason 			continue;
2270b4ce94deSChris Mason 		if (!path->locks[i])
227112f4daccSChris Mason 			continue;
2272bd681513SChris Mason 		btrfs_tree_unlock_rw(path->nodes[i], path->locks[i]);
2273b4ce94deSChris Mason 		path->locks[i] = 0;
2274b4ce94deSChris Mason 	}
2275b4ce94deSChris Mason }
2276b4ce94deSChris Mason 
2277b4ce94deSChris Mason /*
2278c8c42864SChris Mason  * helper function for btrfs_search_slot.  The goal is to find a block
2279c8c42864SChris Mason  * in cache without setting the path to blocking.  If we find the block
2280c8c42864SChris Mason  * we return zero and the path is unchanged.
2281c8c42864SChris Mason  *
2282c8c42864SChris Mason  * If we can't find the block, we set the path blocking and do some
2283c8c42864SChris Mason  * reada.  -EAGAIN is returned and the search must be repeated.
2284c8c42864SChris Mason  */
2285c8c42864SChris Mason static int
2286c8c42864SChris Mason read_block_for_search(struct btrfs_trans_handle *trans,
2287c8c42864SChris Mason 		       struct btrfs_root *root, struct btrfs_path *p,
2288c8c42864SChris Mason 		       struct extent_buffer **eb_ret, int level, int slot,
22895d9e75c4SJan Schmidt 		       struct btrfs_key *key, u64 time_seq)
2290c8c42864SChris Mason {
2291c8c42864SChris Mason 	u64 blocknr;
2292c8c42864SChris Mason 	u64 gen;
2293c8c42864SChris Mason 	u32 blocksize;
2294c8c42864SChris Mason 	struct extent_buffer *b = *eb_ret;
2295c8c42864SChris Mason 	struct extent_buffer *tmp;
229676a05b35SChris Mason 	int ret;
2297c8c42864SChris Mason 
2298c8c42864SChris Mason 	blocknr = btrfs_node_blockptr(b, slot);
2299c8c42864SChris Mason 	gen = btrfs_node_ptr_generation(b, slot);
2300c8c42864SChris Mason 	blocksize = btrfs_level_size(root, level - 1);
2301c8c42864SChris Mason 
2302c8c42864SChris Mason 	tmp = btrfs_find_tree_block(root, blocknr, blocksize);
2303cb44921aSChris Mason 	if (tmp) {
2304b9fab919SChris Mason 		/* first we do an atomic uptodate check */
2305b9fab919SChris Mason 		if (btrfs_buffer_uptodate(tmp, gen, 1) > 0) {
2306c8c42864SChris Mason 			*eb_ret = tmp;
2307c8c42864SChris Mason 			return 0;
2308c8c42864SChris Mason 		}
2309bdf7c00eSJosef Bacik 
2310cb44921aSChris Mason 		/* the pages were up to date, but we failed
2311cb44921aSChris Mason 		 * the generation number check.  Do a full
2312cb44921aSChris Mason 		 * read for the generation number that is correct.
2313cb44921aSChris Mason 		 * We must do this without dropping locks so
2314cb44921aSChris Mason 		 * we can trust our generation number
2315cb44921aSChris Mason 		 */
2316bd681513SChris Mason 		btrfs_set_path_blocking(p);
2317bd681513SChris Mason 
2318b9fab919SChris Mason 		/* now we're allowed to do a blocking uptodate check */
2319bdf7c00eSJosef Bacik 		ret = btrfs_read_buffer(tmp, gen);
2320bdf7c00eSJosef Bacik 		if (!ret) {
2321cb44921aSChris Mason 			*eb_ret = tmp;
2322cb44921aSChris Mason 			return 0;
2323cb44921aSChris Mason 		}
2324cb44921aSChris Mason 		free_extent_buffer(tmp);
2325b3b4aa74SDavid Sterba 		btrfs_release_path(p);
2326cb44921aSChris Mason 		return -EIO;
2327cb44921aSChris Mason 	}
2328c8c42864SChris Mason 
2329c8c42864SChris Mason 	/*
2330c8c42864SChris Mason 	 * reduce lock contention at high levels
2331c8c42864SChris Mason 	 * of the btree by dropping locks before
233276a05b35SChris Mason 	 * we read.  Don't release the lock on the current
233376a05b35SChris Mason 	 * level because we need to walk this node to figure
233476a05b35SChris Mason 	 * out which blocks to read.
2335c8c42864SChris Mason 	 */
23368c594ea8SChris Mason 	btrfs_unlock_up_safe(p, level + 1);
23378c594ea8SChris Mason 	btrfs_set_path_blocking(p);
23388c594ea8SChris Mason 
2339c8c42864SChris Mason 	free_extent_buffer(tmp);
2340c8c42864SChris Mason 	if (p->reada)
2341c8c42864SChris Mason 		reada_for_search(root, p, level, slot, key->objectid);
2342c8c42864SChris Mason 
2343b3b4aa74SDavid Sterba 	btrfs_release_path(p);
234476a05b35SChris Mason 
234576a05b35SChris Mason 	ret = -EAGAIN;
23465bdd3536SYan, Zheng 	tmp = read_tree_block(root, blocknr, blocksize, 0);
234776a05b35SChris Mason 	if (tmp) {
234876a05b35SChris Mason 		/*
234976a05b35SChris Mason 		 * If the read above didn't mark this buffer up to date,
235076a05b35SChris Mason 		 * it will never end up being up to date.  Set ret to EIO now
235176a05b35SChris Mason 		 * and give up so that our caller doesn't loop forever
235276a05b35SChris Mason 		 * on our EAGAINs.
235376a05b35SChris Mason 		 */
2354b9fab919SChris Mason 		if (!btrfs_buffer_uptodate(tmp, 0, 0))
235576a05b35SChris Mason 			ret = -EIO;
2356c8c42864SChris Mason 		free_extent_buffer(tmp);
235776a05b35SChris Mason 	}
235876a05b35SChris Mason 	return ret;
2359c8c42864SChris Mason }
2360c8c42864SChris Mason 
2361c8c42864SChris Mason /*
2362c8c42864SChris Mason  * helper function for btrfs_search_slot.  This does all of the checks
2363c8c42864SChris Mason  * for node-level blocks and does any balancing required based on
2364c8c42864SChris Mason  * the ins_len.
2365c8c42864SChris Mason  *
2366c8c42864SChris Mason  * If no extra work was required, zero is returned.  If we had to
2367c8c42864SChris Mason  * drop the path, -EAGAIN is returned and btrfs_search_slot must
2368c8c42864SChris Mason  * start over
2369c8c42864SChris Mason  */
2370c8c42864SChris Mason static int
2371c8c42864SChris Mason setup_nodes_for_search(struct btrfs_trans_handle *trans,
2372c8c42864SChris Mason 		       struct btrfs_root *root, struct btrfs_path *p,
2373bd681513SChris Mason 		       struct extent_buffer *b, int level, int ins_len,
2374bd681513SChris Mason 		       int *write_lock_level)
2375c8c42864SChris Mason {
2376c8c42864SChris Mason 	int ret;
2377c8c42864SChris Mason 	if ((p->search_for_split || ins_len > 0) && btrfs_header_nritems(b) >=
2378c8c42864SChris Mason 	    BTRFS_NODEPTRS_PER_BLOCK(root) - 3) {
2379c8c42864SChris Mason 		int sret;
2380c8c42864SChris Mason 
2381bd681513SChris Mason 		if (*write_lock_level < level + 1) {
2382bd681513SChris Mason 			*write_lock_level = level + 1;
2383bd681513SChris Mason 			btrfs_release_path(p);
2384bd681513SChris Mason 			goto again;
2385bd681513SChris Mason 		}
2386bd681513SChris Mason 
2387c8c42864SChris Mason 		btrfs_set_path_blocking(p);
23880b08851fSJosef Bacik 		reada_for_balance(root, p, level);
2389c8c42864SChris Mason 		sret = split_node(trans, root, p, level);
2390bd681513SChris Mason 		btrfs_clear_path_blocking(p, NULL, 0);
2391c8c42864SChris Mason 
2392c8c42864SChris Mason 		BUG_ON(sret > 0);
2393c8c42864SChris Mason 		if (sret) {
2394c8c42864SChris Mason 			ret = sret;
2395c8c42864SChris Mason 			goto done;
2396c8c42864SChris Mason 		}
2397c8c42864SChris Mason 		b = p->nodes[level];
2398c8c42864SChris Mason 	} else if (ins_len < 0 && btrfs_header_nritems(b) <
2399cfbb9308SChris Mason 		   BTRFS_NODEPTRS_PER_BLOCK(root) / 2) {
2400c8c42864SChris Mason 		int sret;
2401c8c42864SChris Mason 
2402bd681513SChris Mason 		if (*write_lock_level < level + 1) {
2403bd681513SChris Mason 			*write_lock_level = level + 1;
2404bd681513SChris Mason 			btrfs_release_path(p);
2405bd681513SChris Mason 			goto again;
2406bd681513SChris Mason 		}
2407bd681513SChris Mason 
2408c8c42864SChris Mason 		btrfs_set_path_blocking(p);
24090b08851fSJosef Bacik 		reada_for_balance(root, p, level);
2410c8c42864SChris Mason 		sret = balance_level(trans, root, p, level);
2411bd681513SChris Mason 		btrfs_clear_path_blocking(p, NULL, 0);
2412c8c42864SChris Mason 
2413c8c42864SChris Mason 		if (sret) {
2414c8c42864SChris Mason 			ret = sret;
2415c8c42864SChris Mason 			goto done;
2416c8c42864SChris Mason 		}
2417c8c42864SChris Mason 		b = p->nodes[level];
2418c8c42864SChris Mason 		if (!b) {
2419b3b4aa74SDavid Sterba 			btrfs_release_path(p);
2420c8c42864SChris Mason 			goto again;
2421c8c42864SChris Mason 		}
2422c8c42864SChris Mason 		BUG_ON(btrfs_header_nritems(b) == 1);
2423c8c42864SChris Mason 	}
2424c8c42864SChris Mason 	return 0;
2425c8c42864SChris Mason 
2426c8c42864SChris Mason again:
2427c8c42864SChris Mason 	ret = -EAGAIN;
2428c8c42864SChris Mason done:
2429c8c42864SChris Mason 	return ret;
2430c8c42864SChris Mason }
2431c8c42864SChris Mason 
2432d7396f07SFilipe David Borba Manana static void key_search_validate(struct extent_buffer *b,
2433d7396f07SFilipe David Borba Manana 				struct btrfs_key *key,
2434d7396f07SFilipe David Borba Manana 				int level)
2435d7396f07SFilipe David Borba Manana {
2436d7396f07SFilipe David Borba Manana #ifdef CONFIG_BTRFS_ASSERT
2437d7396f07SFilipe David Borba Manana 	struct btrfs_disk_key disk_key;
2438d7396f07SFilipe David Borba Manana 
2439d7396f07SFilipe David Borba Manana 	btrfs_cpu_key_to_disk(&disk_key, key);
2440d7396f07SFilipe David Borba Manana 
2441d7396f07SFilipe David Borba Manana 	if (level == 0)
2442d7396f07SFilipe David Borba Manana 		ASSERT(!memcmp_extent_buffer(b, &disk_key,
2443d7396f07SFilipe David Borba Manana 		    offsetof(struct btrfs_leaf, items[0].key),
2444d7396f07SFilipe David Borba Manana 		    sizeof(disk_key)));
2445d7396f07SFilipe David Borba Manana 	else
2446d7396f07SFilipe David Borba Manana 		ASSERT(!memcmp_extent_buffer(b, &disk_key,
2447d7396f07SFilipe David Borba Manana 		    offsetof(struct btrfs_node, ptrs[0].key),
2448d7396f07SFilipe David Borba Manana 		    sizeof(disk_key)));
2449d7396f07SFilipe David Borba Manana #endif
2450d7396f07SFilipe David Borba Manana }
2451d7396f07SFilipe David Borba Manana 
2452d7396f07SFilipe David Borba Manana static int key_search(struct extent_buffer *b, struct btrfs_key *key,
2453d7396f07SFilipe David Borba Manana 		      int level, int *prev_cmp, int *slot)
2454d7396f07SFilipe David Borba Manana {
2455d7396f07SFilipe David Borba Manana 	if (*prev_cmp != 0) {
2456d7396f07SFilipe David Borba Manana 		*prev_cmp = bin_search(b, key, level, slot);
2457d7396f07SFilipe David Borba Manana 		return *prev_cmp;
2458d7396f07SFilipe David Borba Manana 	}
2459d7396f07SFilipe David Borba Manana 
2460d7396f07SFilipe David Borba Manana 	key_search_validate(b, key, level);
2461d7396f07SFilipe David Borba Manana 	*slot = 0;
2462d7396f07SFilipe David Borba Manana 
2463d7396f07SFilipe David Borba Manana 	return 0;
2464d7396f07SFilipe David Borba Manana }
2465d7396f07SFilipe David Borba Manana 
2466c8c42864SChris Mason /*
246774123bd7SChris Mason  * look for key in the tree.  path is filled in with nodes along the way
246874123bd7SChris Mason  * if key is found, we return zero and you can find the item in the leaf
246974123bd7SChris Mason  * level of the path (level 0)
247074123bd7SChris Mason  *
247174123bd7SChris Mason  * If the key isn't found, the path points to the slot where it should
2472aa5d6bedSChris Mason  * be inserted, and 1 is returned.  If there are other errors during the
2473aa5d6bedSChris Mason  * search a negative error number is returned.
247497571fd0SChris Mason  *
247597571fd0SChris Mason  * if ins_len > 0, nodes and leaves will be split as we walk down the
247697571fd0SChris Mason  * tree.  if ins_len < 0, nodes will be merged as we walk down the tree (if
247797571fd0SChris Mason  * possible)
247874123bd7SChris Mason  */
2479e089f05cSChris Mason int btrfs_search_slot(struct btrfs_trans_handle *trans, struct btrfs_root
2480e089f05cSChris Mason 		      *root, struct btrfs_key *key, struct btrfs_path *p, int
2481e089f05cSChris Mason 		      ins_len, int cow)
2482be0e5c09SChris Mason {
24835f39d397SChris Mason 	struct extent_buffer *b;
2484be0e5c09SChris Mason 	int slot;
2485be0e5c09SChris Mason 	int ret;
248633c66f43SYan Zheng 	int err;
2487be0e5c09SChris Mason 	int level;
2488925baeddSChris Mason 	int lowest_unlock = 1;
2489bd681513SChris Mason 	int root_lock;
2490bd681513SChris Mason 	/* everything at write_lock_level or lower must be write locked */
2491bd681513SChris Mason 	int write_lock_level = 0;
24929f3a7427SChris Mason 	u8 lowest_level = 0;
2493f7c79f30SChris Mason 	int min_write_lock_level;
2494d7396f07SFilipe David Borba Manana 	int prev_cmp;
24959f3a7427SChris Mason 
24966702ed49SChris Mason 	lowest_level = p->lowest_level;
2497323ac95bSChris Mason 	WARN_ON(lowest_level && ins_len > 0);
249822b0ebdaSChris Mason 	WARN_ON(p->nodes[0] != NULL);
249925179201SJosef Bacik 
2500bd681513SChris Mason 	if (ins_len < 0) {
2501925baeddSChris Mason 		lowest_unlock = 2;
250265b51a00SChris Mason 
2503bd681513SChris Mason 		/* when we are removing items, we might have to go up to level
2504bd681513SChris Mason 		 * two as we update tree pointers  Make sure we keep write
2505bd681513SChris Mason 		 * for those levels as well
2506bd681513SChris Mason 		 */
2507bd681513SChris Mason 		write_lock_level = 2;
2508bd681513SChris Mason 	} else if (ins_len > 0) {
2509bd681513SChris Mason 		/*
2510bd681513SChris Mason 		 * for inserting items, make sure we have a write lock on
2511bd681513SChris Mason 		 * level 1 so we can update keys
2512bd681513SChris Mason 		 */
2513bd681513SChris Mason 		write_lock_level = 1;
2514bd681513SChris Mason 	}
2515bd681513SChris Mason 
2516bd681513SChris Mason 	if (!cow)
2517bd681513SChris Mason 		write_lock_level = -1;
2518bd681513SChris Mason 
251909a2a8f9SJosef Bacik 	if (cow && (p->keep_locks || p->lowest_level))
2520bd681513SChris Mason 		write_lock_level = BTRFS_MAX_LEVEL;
2521bd681513SChris Mason 
2522f7c79f30SChris Mason 	min_write_lock_level = write_lock_level;
2523f7c79f30SChris Mason 
2524bb803951SChris Mason again:
2525d7396f07SFilipe David Borba Manana 	prev_cmp = -1;
2526bd681513SChris Mason 	/*
2527bd681513SChris Mason 	 * we try very hard to do read locks on the root
2528bd681513SChris Mason 	 */
2529bd681513SChris Mason 	root_lock = BTRFS_READ_LOCK;
2530bd681513SChris Mason 	level = 0;
25315d4f98a2SYan Zheng 	if (p->search_commit_root) {
2532bd681513SChris Mason 		/*
2533bd681513SChris Mason 		 * the commit roots are read only
2534bd681513SChris Mason 		 * so we always do read locks
2535bd681513SChris Mason 		 */
25365d4f98a2SYan Zheng 		b = root->commit_root;
25375d4f98a2SYan Zheng 		extent_buffer_get(b);
2538bd681513SChris Mason 		level = btrfs_header_level(b);
25395d4f98a2SYan Zheng 		if (!p->skip_locking)
2540bd681513SChris Mason 			btrfs_tree_read_lock(b);
25415d4f98a2SYan Zheng 	} else {
2542bd681513SChris Mason 		if (p->skip_locking) {
25435cd57b2cSChris Mason 			b = btrfs_root_node(root);
2544bd681513SChris Mason 			level = btrfs_header_level(b);
2545bd681513SChris Mason 		} else {
2546bd681513SChris Mason 			/* we don't know the level of the root node
2547bd681513SChris Mason 			 * until we actually have it read locked
2548bd681513SChris Mason 			 */
2549bd681513SChris Mason 			b = btrfs_read_lock_root_node(root);
2550bd681513SChris Mason 			level = btrfs_header_level(b);
2551bd681513SChris Mason 			if (level <= write_lock_level) {
2552bd681513SChris Mason 				/* whoops, must trade for write lock */
2553bd681513SChris Mason 				btrfs_tree_read_unlock(b);
2554bd681513SChris Mason 				free_extent_buffer(b);
2555925baeddSChris Mason 				b = btrfs_lock_root_node(root);
2556bd681513SChris Mason 				root_lock = BTRFS_WRITE_LOCK;
2557bd681513SChris Mason 
2558bd681513SChris Mason 				/* the level might have changed, check again */
2559bd681513SChris Mason 				level = btrfs_header_level(b);
25605d4f98a2SYan Zheng 			}
2561bd681513SChris Mason 		}
2562bd681513SChris Mason 	}
2563bd681513SChris Mason 	p->nodes[level] = b;
2564bd681513SChris Mason 	if (!p->skip_locking)
2565bd681513SChris Mason 		p->locks[level] = root_lock;
2566925baeddSChris Mason 
2567eb60ceacSChris Mason 	while (b) {
25685f39d397SChris Mason 		level = btrfs_header_level(b);
256965b51a00SChris Mason 
257065b51a00SChris Mason 		/*
257165b51a00SChris Mason 		 * setup the path here so we can release it under lock
257265b51a00SChris Mason 		 * contention with the cow code
257365b51a00SChris Mason 		 */
257402217ed2SChris Mason 		if (cow) {
2575c8c42864SChris Mason 			/*
2576c8c42864SChris Mason 			 * if we don't really need to cow this block
2577c8c42864SChris Mason 			 * then we don't want to set the path blocking,
2578c8c42864SChris Mason 			 * so we test it here
2579c8c42864SChris Mason 			 */
25805d4f98a2SYan Zheng 			if (!should_cow_block(trans, root, b))
258165b51a00SChris Mason 				goto cow_done;
25825d4f98a2SYan Zheng 
2583b4ce94deSChris Mason 			btrfs_set_path_blocking(p);
2584b4ce94deSChris Mason 
2585bd681513SChris Mason 			/*
2586bd681513SChris Mason 			 * must have write locks on this node and the
2587bd681513SChris Mason 			 * parent
2588bd681513SChris Mason 			 */
25895124e00eSJosef Bacik 			if (level > write_lock_level ||
25905124e00eSJosef Bacik 			    (level + 1 > write_lock_level &&
25915124e00eSJosef Bacik 			    level + 1 < BTRFS_MAX_LEVEL &&
25925124e00eSJosef Bacik 			    p->nodes[level + 1])) {
2593bd681513SChris Mason 				write_lock_level = level + 1;
2594bd681513SChris Mason 				btrfs_release_path(p);
2595bd681513SChris Mason 				goto again;
2596bd681513SChris Mason 			}
2597bd681513SChris Mason 
259833c66f43SYan Zheng 			err = btrfs_cow_block(trans, root, b,
2599e20d96d6SChris Mason 					      p->nodes[level + 1],
26009fa8cfe7SChris Mason 					      p->slots[level + 1], &b);
260133c66f43SYan Zheng 			if (err) {
260233c66f43SYan Zheng 				ret = err;
260365b51a00SChris Mason 				goto done;
260454aa1f4dSChris Mason 			}
260502217ed2SChris Mason 		}
260665b51a00SChris Mason cow_done:
260702217ed2SChris Mason 		BUG_ON(!cow && ins_len);
260865b51a00SChris Mason 
2609eb60ceacSChris Mason 		p->nodes[level] = b;
2610bd681513SChris Mason 		btrfs_clear_path_blocking(p, NULL, 0);
2611b4ce94deSChris Mason 
2612b4ce94deSChris Mason 		/*
2613b4ce94deSChris Mason 		 * we have a lock on b and as long as we aren't changing
2614b4ce94deSChris Mason 		 * the tree, there is no way to for the items in b to change.
2615b4ce94deSChris Mason 		 * It is safe to drop the lock on our parent before we
2616b4ce94deSChris Mason 		 * go through the expensive btree search on b.
2617b4ce94deSChris Mason 		 *
2618b4ce94deSChris Mason 		 * If cow is true, then we might be changing slot zero,
2619b4ce94deSChris Mason 		 * which may require changing the parent.  So, we can't
2620b4ce94deSChris Mason 		 * drop the lock until after we know which slot we're
2621b4ce94deSChris Mason 		 * operating on.
2622b4ce94deSChris Mason 		 */
2623b4ce94deSChris Mason 		if (!cow)
2624b4ce94deSChris Mason 			btrfs_unlock_up_safe(p, level + 1);
2625b4ce94deSChris Mason 
2626d7396f07SFilipe David Borba Manana 		ret = key_search(b, key, level, &prev_cmp, &slot);
2627b4ce94deSChris Mason 
26285f39d397SChris Mason 		if (level != 0) {
262933c66f43SYan Zheng 			int dec = 0;
263033c66f43SYan Zheng 			if (ret && slot > 0) {
263133c66f43SYan Zheng 				dec = 1;
2632be0e5c09SChris Mason 				slot -= 1;
263333c66f43SYan Zheng 			}
2634be0e5c09SChris Mason 			p->slots[level] = slot;
263533c66f43SYan Zheng 			err = setup_nodes_for_search(trans, root, p, b, level,
2636bd681513SChris Mason 					     ins_len, &write_lock_level);
263733c66f43SYan Zheng 			if (err == -EAGAIN)
2638b4ce94deSChris Mason 				goto again;
263933c66f43SYan Zheng 			if (err) {
264033c66f43SYan Zheng 				ret = err;
264165b51a00SChris Mason 				goto done;
264233c66f43SYan Zheng 			}
26435c680ed6SChris Mason 			b = p->nodes[level];
26445c680ed6SChris Mason 			slot = p->slots[level];
2645b4ce94deSChris Mason 
2646bd681513SChris Mason 			/*
2647bd681513SChris Mason 			 * slot 0 is special, if we change the key
2648bd681513SChris Mason 			 * we have to update the parent pointer
2649bd681513SChris Mason 			 * which means we must have a write lock
2650bd681513SChris Mason 			 * on the parent
2651bd681513SChris Mason 			 */
2652bd681513SChris Mason 			if (slot == 0 && cow &&
2653bd681513SChris Mason 			    write_lock_level < level + 1) {
2654bd681513SChris Mason 				write_lock_level = level + 1;
2655bd681513SChris Mason 				btrfs_release_path(p);
2656bd681513SChris Mason 				goto again;
2657bd681513SChris Mason 			}
2658bd681513SChris Mason 
2659f7c79f30SChris Mason 			unlock_up(p, level, lowest_unlock,
2660f7c79f30SChris Mason 				  min_write_lock_level, &write_lock_level);
2661f9efa9c7SChris Mason 
2662925baeddSChris Mason 			if (level == lowest_level) {
266333c66f43SYan Zheng 				if (dec)
266433c66f43SYan Zheng 					p->slots[level]++;
26655b21f2edSZheng Yan 				goto done;
2666925baeddSChris Mason 			}
2667ca7a79adSChris Mason 
266833c66f43SYan Zheng 			err = read_block_for_search(trans, root, p,
26695d9e75c4SJan Schmidt 						    &b, level, slot, key, 0);
267033c66f43SYan Zheng 			if (err == -EAGAIN)
2671051e1b9fSChris Mason 				goto again;
267233c66f43SYan Zheng 			if (err) {
267333c66f43SYan Zheng 				ret = err;
267476a05b35SChris Mason 				goto done;
267533c66f43SYan Zheng 			}
267676a05b35SChris Mason 
2677b4ce94deSChris Mason 			if (!p->skip_locking) {
2678bd681513SChris Mason 				level = btrfs_header_level(b);
2679bd681513SChris Mason 				if (level <= write_lock_level) {
2680bd681513SChris Mason 					err = btrfs_try_tree_write_lock(b);
268133c66f43SYan Zheng 					if (!err) {
2682b4ce94deSChris Mason 						btrfs_set_path_blocking(p);
2683925baeddSChris Mason 						btrfs_tree_lock(b);
2684bd681513SChris Mason 						btrfs_clear_path_blocking(p, b,
2685bd681513SChris Mason 								  BTRFS_WRITE_LOCK);
2686b4ce94deSChris Mason 					}
2687bd681513SChris Mason 					p->locks[level] = BTRFS_WRITE_LOCK;
2688bd681513SChris Mason 				} else {
2689bd681513SChris Mason 					err = btrfs_try_tree_read_lock(b);
2690bd681513SChris Mason 					if (!err) {
2691bd681513SChris Mason 						btrfs_set_path_blocking(p);
2692bd681513SChris Mason 						btrfs_tree_read_lock(b);
2693bd681513SChris Mason 						btrfs_clear_path_blocking(p, b,
2694bd681513SChris Mason 								  BTRFS_READ_LOCK);
2695bd681513SChris Mason 					}
2696bd681513SChris Mason 					p->locks[level] = BTRFS_READ_LOCK;
2697bd681513SChris Mason 				}
2698bd681513SChris Mason 				p->nodes[level] = b;
2699b4ce94deSChris Mason 			}
2700be0e5c09SChris Mason 		} else {
2701be0e5c09SChris Mason 			p->slots[level] = slot;
270287b29b20SYan Zheng 			if (ins_len > 0 &&
270387b29b20SYan Zheng 			    btrfs_leaf_free_space(root, b) < ins_len) {
2704bd681513SChris Mason 				if (write_lock_level < 1) {
2705bd681513SChris Mason 					write_lock_level = 1;
2706bd681513SChris Mason 					btrfs_release_path(p);
2707bd681513SChris Mason 					goto again;
2708bd681513SChris Mason 				}
2709bd681513SChris Mason 
2710b4ce94deSChris Mason 				btrfs_set_path_blocking(p);
271133c66f43SYan Zheng 				err = split_leaf(trans, root, key,
2712cc0c5538SChris Mason 						 p, ins_len, ret == 0);
2713bd681513SChris Mason 				btrfs_clear_path_blocking(p, NULL, 0);
2714b4ce94deSChris Mason 
271533c66f43SYan Zheng 				BUG_ON(err > 0);
271633c66f43SYan Zheng 				if (err) {
271733c66f43SYan Zheng 					ret = err;
271865b51a00SChris Mason 					goto done;
271965b51a00SChris Mason 				}
27205c680ed6SChris Mason 			}
2721459931ecSChris Mason 			if (!p->search_for_split)
2722f7c79f30SChris Mason 				unlock_up(p, level, lowest_unlock,
2723f7c79f30SChris Mason 					  min_write_lock_level, &write_lock_level);
272465b51a00SChris Mason 			goto done;
272565b51a00SChris Mason 		}
272665b51a00SChris Mason 	}
272765b51a00SChris Mason 	ret = 1;
272865b51a00SChris Mason done:
2729b4ce94deSChris Mason 	/*
2730b4ce94deSChris Mason 	 * we don't really know what they plan on doing with the path
2731b4ce94deSChris Mason 	 * from here on, so for now just mark it as blocking
2732b4ce94deSChris Mason 	 */
2733b9473439SChris Mason 	if (!p->leave_spinning)
2734b4ce94deSChris Mason 		btrfs_set_path_blocking(p);
273576a05b35SChris Mason 	if (ret < 0)
2736b3b4aa74SDavid Sterba 		btrfs_release_path(p);
2737be0e5c09SChris Mason 	return ret;
2738be0e5c09SChris Mason }
2739be0e5c09SChris Mason 
274074123bd7SChris Mason /*
27415d9e75c4SJan Schmidt  * Like btrfs_search_slot, this looks for a key in the given tree. It uses the
27425d9e75c4SJan Schmidt  * current state of the tree together with the operations recorded in the tree
27435d9e75c4SJan Schmidt  * modification log to search for the key in a previous version of this tree, as
27445d9e75c4SJan Schmidt  * denoted by the time_seq parameter.
27455d9e75c4SJan Schmidt  *
27465d9e75c4SJan Schmidt  * Naturally, there is no support for insert, delete or cow operations.
27475d9e75c4SJan Schmidt  *
27485d9e75c4SJan Schmidt  * The resulting path and return value will be set up as if we called
27495d9e75c4SJan Schmidt  * btrfs_search_slot at that point in time with ins_len and cow both set to 0.
27505d9e75c4SJan Schmidt  */
27515d9e75c4SJan Schmidt int btrfs_search_old_slot(struct btrfs_root *root, struct btrfs_key *key,
27525d9e75c4SJan Schmidt 			  struct btrfs_path *p, u64 time_seq)
27535d9e75c4SJan Schmidt {
27545d9e75c4SJan Schmidt 	struct extent_buffer *b;
27555d9e75c4SJan Schmidt 	int slot;
27565d9e75c4SJan Schmidt 	int ret;
27575d9e75c4SJan Schmidt 	int err;
27585d9e75c4SJan Schmidt 	int level;
27595d9e75c4SJan Schmidt 	int lowest_unlock = 1;
27605d9e75c4SJan Schmidt 	u8 lowest_level = 0;
2761d7396f07SFilipe David Borba Manana 	int prev_cmp;
27625d9e75c4SJan Schmidt 
27635d9e75c4SJan Schmidt 	lowest_level = p->lowest_level;
27645d9e75c4SJan Schmidt 	WARN_ON(p->nodes[0] != NULL);
27655d9e75c4SJan Schmidt 
27665d9e75c4SJan Schmidt 	if (p->search_commit_root) {
27675d9e75c4SJan Schmidt 		BUG_ON(time_seq);
27685d9e75c4SJan Schmidt 		return btrfs_search_slot(NULL, root, key, p, 0, 0);
27695d9e75c4SJan Schmidt 	}
27705d9e75c4SJan Schmidt 
27715d9e75c4SJan Schmidt again:
2772d7396f07SFilipe David Borba Manana 	prev_cmp = -1;
27735d9e75c4SJan Schmidt 	b = get_old_root(root, time_seq);
27745d9e75c4SJan Schmidt 	level = btrfs_header_level(b);
27755d9e75c4SJan Schmidt 	p->locks[level] = BTRFS_READ_LOCK;
27765d9e75c4SJan Schmidt 
27775d9e75c4SJan Schmidt 	while (b) {
27785d9e75c4SJan Schmidt 		level = btrfs_header_level(b);
27795d9e75c4SJan Schmidt 		p->nodes[level] = b;
27805d9e75c4SJan Schmidt 		btrfs_clear_path_blocking(p, NULL, 0);
27815d9e75c4SJan Schmidt 
27825d9e75c4SJan Schmidt 		/*
27835d9e75c4SJan Schmidt 		 * we have a lock on b and as long as we aren't changing
27845d9e75c4SJan Schmidt 		 * the tree, there is no way to for the items in b to change.
27855d9e75c4SJan Schmidt 		 * It is safe to drop the lock on our parent before we
27865d9e75c4SJan Schmidt 		 * go through the expensive btree search on b.
27875d9e75c4SJan Schmidt 		 */
27885d9e75c4SJan Schmidt 		btrfs_unlock_up_safe(p, level + 1);
27895d9e75c4SJan Schmidt 
2790d7396f07SFilipe David Borba Manana 		ret = key_search(b, key, level, &prev_cmp, &slot);
27915d9e75c4SJan Schmidt 
27925d9e75c4SJan Schmidt 		if (level != 0) {
27935d9e75c4SJan Schmidt 			int dec = 0;
27945d9e75c4SJan Schmidt 			if (ret && slot > 0) {
27955d9e75c4SJan Schmidt 				dec = 1;
27965d9e75c4SJan Schmidt 				slot -= 1;
27975d9e75c4SJan Schmidt 			}
27985d9e75c4SJan Schmidt 			p->slots[level] = slot;
27995d9e75c4SJan Schmidt 			unlock_up(p, level, lowest_unlock, 0, NULL);
28005d9e75c4SJan Schmidt 
28015d9e75c4SJan Schmidt 			if (level == lowest_level) {
28025d9e75c4SJan Schmidt 				if (dec)
28035d9e75c4SJan Schmidt 					p->slots[level]++;
28045d9e75c4SJan Schmidt 				goto done;
28055d9e75c4SJan Schmidt 			}
28065d9e75c4SJan Schmidt 
28075d9e75c4SJan Schmidt 			err = read_block_for_search(NULL, root, p, &b, level,
28085d9e75c4SJan Schmidt 						    slot, key, time_seq);
28095d9e75c4SJan Schmidt 			if (err == -EAGAIN)
28105d9e75c4SJan Schmidt 				goto again;
28115d9e75c4SJan Schmidt 			if (err) {
28125d9e75c4SJan Schmidt 				ret = err;
28135d9e75c4SJan Schmidt 				goto done;
28145d9e75c4SJan Schmidt 			}
28155d9e75c4SJan Schmidt 
28165d9e75c4SJan Schmidt 			level = btrfs_header_level(b);
28175d9e75c4SJan Schmidt 			err = btrfs_try_tree_read_lock(b);
28185d9e75c4SJan Schmidt 			if (!err) {
28195d9e75c4SJan Schmidt 				btrfs_set_path_blocking(p);
28205d9e75c4SJan Schmidt 				btrfs_tree_read_lock(b);
28215d9e75c4SJan Schmidt 				btrfs_clear_path_blocking(p, b,
28225d9e75c4SJan Schmidt 							  BTRFS_READ_LOCK);
28235d9e75c4SJan Schmidt 			}
28249ec72677SJosef Bacik 			b = tree_mod_log_rewind(root->fs_info, p, b, time_seq);
2825db7f3436SJosef Bacik 			if (!b) {
2826db7f3436SJosef Bacik 				ret = -ENOMEM;
2827db7f3436SJosef Bacik 				goto done;
2828db7f3436SJosef Bacik 			}
28295d9e75c4SJan Schmidt 			p->locks[level] = BTRFS_READ_LOCK;
28305d9e75c4SJan Schmidt 			p->nodes[level] = b;
28315d9e75c4SJan Schmidt 		} else {
28325d9e75c4SJan Schmidt 			p->slots[level] = slot;
28335d9e75c4SJan Schmidt 			unlock_up(p, level, lowest_unlock, 0, NULL);
28345d9e75c4SJan Schmidt 			goto done;
28355d9e75c4SJan Schmidt 		}
28365d9e75c4SJan Schmidt 	}
28375d9e75c4SJan Schmidt 	ret = 1;
28385d9e75c4SJan Schmidt done:
28395d9e75c4SJan Schmidt 	if (!p->leave_spinning)
28405d9e75c4SJan Schmidt 		btrfs_set_path_blocking(p);
28415d9e75c4SJan Schmidt 	if (ret < 0)
28425d9e75c4SJan Schmidt 		btrfs_release_path(p);
28435d9e75c4SJan Schmidt 
28445d9e75c4SJan Schmidt 	return ret;
28455d9e75c4SJan Schmidt }
28465d9e75c4SJan Schmidt 
28475d9e75c4SJan Schmidt /*
28482f38b3e1SArne Jansen  * helper to use instead of search slot if no exact match is needed but
28492f38b3e1SArne Jansen  * instead the next or previous item should be returned.
28502f38b3e1SArne Jansen  * When find_higher is true, the next higher item is returned, the next lower
28512f38b3e1SArne Jansen  * otherwise.
28522f38b3e1SArne Jansen  * When return_any and find_higher are both true, and no higher item is found,
28532f38b3e1SArne Jansen  * return the next lower instead.
28542f38b3e1SArne Jansen  * When return_any is true and find_higher is false, and no lower item is found,
28552f38b3e1SArne Jansen  * return the next higher instead.
28562f38b3e1SArne Jansen  * It returns 0 if any item is found, 1 if none is found (tree empty), and
28572f38b3e1SArne Jansen  * < 0 on error
28582f38b3e1SArne Jansen  */
28592f38b3e1SArne Jansen int btrfs_search_slot_for_read(struct btrfs_root *root,
28602f38b3e1SArne Jansen 			       struct btrfs_key *key, struct btrfs_path *p,
28612f38b3e1SArne Jansen 			       int find_higher, int return_any)
28622f38b3e1SArne Jansen {
28632f38b3e1SArne Jansen 	int ret;
28642f38b3e1SArne Jansen 	struct extent_buffer *leaf;
28652f38b3e1SArne Jansen 
28662f38b3e1SArne Jansen again:
28672f38b3e1SArne Jansen 	ret = btrfs_search_slot(NULL, root, key, p, 0, 0);
28682f38b3e1SArne Jansen 	if (ret <= 0)
28692f38b3e1SArne Jansen 		return ret;
28702f38b3e1SArne Jansen 	/*
28712f38b3e1SArne Jansen 	 * a return value of 1 means the path is at the position where the
28722f38b3e1SArne Jansen 	 * item should be inserted. Normally this is the next bigger item,
28732f38b3e1SArne Jansen 	 * but in case the previous item is the last in a leaf, path points
28742f38b3e1SArne Jansen 	 * to the first free slot in the previous leaf, i.e. at an invalid
28752f38b3e1SArne Jansen 	 * item.
28762f38b3e1SArne Jansen 	 */
28772f38b3e1SArne Jansen 	leaf = p->nodes[0];
28782f38b3e1SArne Jansen 
28792f38b3e1SArne Jansen 	if (find_higher) {
28802f38b3e1SArne Jansen 		if (p->slots[0] >= btrfs_header_nritems(leaf)) {
28812f38b3e1SArne Jansen 			ret = btrfs_next_leaf(root, p);
28822f38b3e1SArne Jansen 			if (ret <= 0)
28832f38b3e1SArne Jansen 				return ret;
28842f38b3e1SArne Jansen 			if (!return_any)
28852f38b3e1SArne Jansen 				return 1;
28862f38b3e1SArne Jansen 			/*
28872f38b3e1SArne Jansen 			 * no higher item found, return the next
28882f38b3e1SArne Jansen 			 * lower instead
28892f38b3e1SArne Jansen 			 */
28902f38b3e1SArne Jansen 			return_any = 0;
28912f38b3e1SArne Jansen 			find_higher = 0;
28922f38b3e1SArne Jansen 			btrfs_release_path(p);
28932f38b3e1SArne Jansen 			goto again;
28942f38b3e1SArne Jansen 		}
28952f38b3e1SArne Jansen 	} else {
28962f38b3e1SArne Jansen 		if (p->slots[0] == 0) {
28972f38b3e1SArne Jansen 			ret = btrfs_prev_leaf(root, p);
2898e6793769SArne Jansen 			if (ret < 0)
28992f38b3e1SArne Jansen 				return ret;
2900e6793769SArne Jansen 			if (!ret) {
2901e6793769SArne Jansen 				p->slots[0] = btrfs_header_nritems(leaf) - 1;
2902e6793769SArne Jansen 				return 0;
2903e6793769SArne Jansen 			}
29042f38b3e1SArne Jansen 			if (!return_any)
29052f38b3e1SArne Jansen 				return 1;
29062f38b3e1SArne Jansen 			/*
29072f38b3e1SArne Jansen 			 * no lower item found, return the next
29082f38b3e1SArne Jansen 			 * higher instead
29092f38b3e1SArne Jansen 			 */
29102f38b3e1SArne Jansen 			return_any = 0;
29112f38b3e1SArne Jansen 			find_higher = 1;
29122f38b3e1SArne Jansen 			btrfs_release_path(p);
29132f38b3e1SArne Jansen 			goto again;
2914e6793769SArne Jansen 		} else {
29152f38b3e1SArne Jansen 			--p->slots[0];
29162f38b3e1SArne Jansen 		}
29172f38b3e1SArne Jansen 	}
29182f38b3e1SArne Jansen 	return 0;
29192f38b3e1SArne Jansen }
29202f38b3e1SArne Jansen 
29212f38b3e1SArne Jansen /*
292274123bd7SChris Mason  * adjust the pointers going up the tree, starting at level
292374123bd7SChris Mason  * making sure the right key of each node is points to 'key'.
292474123bd7SChris Mason  * This is used after shifting pointers to the left, so it stops
292574123bd7SChris Mason  * fixing up pointers when a given leaf/node is not in slot 0 of the
292674123bd7SChris Mason  * higher levels
2927aa5d6bedSChris Mason  *
292874123bd7SChris Mason  */
2929d6a0a126STsutomu Itoh static void fixup_low_keys(struct btrfs_root *root, struct btrfs_path *path,
29305f39d397SChris Mason 			   struct btrfs_disk_key *key, int level)
2931be0e5c09SChris Mason {
2932be0e5c09SChris Mason 	int i;
29335f39d397SChris Mason 	struct extent_buffer *t;
29345f39d397SChris Mason 
2935234b63a0SChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2936be0e5c09SChris Mason 		int tslot = path->slots[i];
2937eb60ceacSChris Mason 		if (!path->nodes[i])
2938be0e5c09SChris Mason 			break;
29395f39d397SChris Mason 		t = path->nodes[i];
294032adf090SLiu Bo 		tree_mod_log_set_node_key(root->fs_info, t, tslot, 1);
29415f39d397SChris Mason 		btrfs_set_node_key(t, key, tslot);
2942d6025579SChris Mason 		btrfs_mark_buffer_dirty(path->nodes[i]);
2943be0e5c09SChris Mason 		if (tslot != 0)
2944be0e5c09SChris Mason 			break;
2945be0e5c09SChris Mason 	}
2946be0e5c09SChris Mason }
2947be0e5c09SChris Mason 
294874123bd7SChris Mason /*
294931840ae1SZheng Yan  * update item key.
295031840ae1SZheng Yan  *
295131840ae1SZheng Yan  * This function isn't completely safe. It's the caller's responsibility
295231840ae1SZheng Yan  * that the new key won't break the order
295331840ae1SZheng Yan  */
2954afe5fea7STsutomu Itoh void btrfs_set_item_key_safe(struct btrfs_root *root, struct btrfs_path *path,
295531840ae1SZheng Yan 			     struct btrfs_key *new_key)
295631840ae1SZheng Yan {
295731840ae1SZheng Yan 	struct btrfs_disk_key disk_key;
295831840ae1SZheng Yan 	struct extent_buffer *eb;
295931840ae1SZheng Yan 	int slot;
296031840ae1SZheng Yan 
296131840ae1SZheng Yan 	eb = path->nodes[0];
296231840ae1SZheng Yan 	slot = path->slots[0];
296331840ae1SZheng Yan 	if (slot > 0) {
296431840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot - 1);
2965143bede5SJeff Mahoney 		BUG_ON(comp_keys(&disk_key, new_key) >= 0);
296631840ae1SZheng Yan 	}
296731840ae1SZheng Yan 	if (slot < btrfs_header_nritems(eb) - 1) {
296831840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot + 1);
2969143bede5SJeff Mahoney 		BUG_ON(comp_keys(&disk_key, new_key) <= 0);
297031840ae1SZheng Yan 	}
297131840ae1SZheng Yan 
297231840ae1SZheng Yan 	btrfs_cpu_key_to_disk(&disk_key, new_key);
297331840ae1SZheng Yan 	btrfs_set_item_key(eb, &disk_key, slot);
297431840ae1SZheng Yan 	btrfs_mark_buffer_dirty(eb);
297531840ae1SZheng Yan 	if (slot == 0)
2976d6a0a126STsutomu Itoh 		fixup_low_keys(root, path, &disk_key, 1);
297731840ae1SZheng Yan }
297831840ae1SZheng Yan 
297931840ae1SZheng Yan /*
298074123bd7SChris Mason  * try to push data from one node into the next node left in the
298179f95c82SChris Mason  * tree.
2982aa5d6bedSChris Mason  *
2983aa5d6bedSChris Mason  * returns 0 if some ptrs were pushed left, < 0 if there was some horrible
2984aa5d6bedSChris Mason  * error, and > 0 if there was no room in the left hand block.
298574123bd7SChris Mason  */
298698ed5174SChris Mason static int push_node_left(struct btrfs_trans_handle *trans,
298798ed5174SChris Mason 			  struct btrfs_root *root, struct extent_buffer *dst,
2988971a1f66SChris Mason 			  struct extent_buffer *src, int empty)
2989be0e5c09SChris Mason {
2990be0e5c09SChris Mason 	int push_items = 0;
2991bb803951SChris Mason 	int src_nritems;
2992bb803951SChris Mason 	int dst_nritems;
2993aa5d6bedSChris Mason 	int ret = 0;
2994be0e5c09SChris Mason 
29955f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
29965f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
2997123abc88SChris Mason 	push_items = BTRFS_NODEPTRS_PER_BLOCK(root) - dst_nritems;
29987bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
29997bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
300054aa1f4dSChris Mason 
3001bce4eae9SChris Mason 	if (!empty && src_nritems <= 8)
3002971a1f66SChris Mason 		return 1;
3003971a1f66SChris Mason 
3004d397712bSChris Mason 	if (push_items <= 0)
3005be0e5c09SChris Mason 		return 1;
3006be0e5c09SChris Mason 
3007bce4eae9SChris Mason 	if (empty) {
3008971a1f66SChris Mason 		push_items = min(src_nritems, push_items);
3009bce4eae9SChris Mason 		if (push_items < src_nritems) {
3010bce4eae9SChris Mason 			/* leave at least 8 pointers in the node if
3011bce4eae9SChris Mason 			 * we aren't going to empty it
3012bce4eae9SChris Mason 			 */
3013bce4eae9SChris Mason 			if (src_nritems - push_items < 8) {
3014bce4eae9SChris Mason 				if (push_items <= 8)
3015bce4eae9SChris Mason 					return 1;
3016bce4eae9SChris Mason 				push_items -= 8;
3017bce4eae9SChris Mason 			}
3018bce4eae9SChris Mason 		}
3019bce4eae9SChris Mason 	} else
3020bce4eae9SChris Mason 		push_items = min(src_nritems - 8, push_items);
302179f95c82SChris Mason 
3022f230475eSJan Schmidt 	tree_mod_log_eb_copy(root->fs_info, dst, src, dst_nritems, 0,
302390f8d62eSJan Schmidt 			     push_items);
30245f39d397SChris Mason 	copy_extent_buffer(dst, src,
30255f39d397SChris Mason 			   btrfs_node_key_ptr_offset(dst_nritems),
30265f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
3027123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
30285f39d397SChris Mason 
3029bb803951SChris Mason 	if (push_items < src_nritems) {
303057911b8bSJan Schmidt 		/*
303157911b8bSJan Schmidt 		 * don't call tree_mod_log_eb_move here, key removal was already
303257911b8bSJan Schmidt 		 * fully logged by tree_mod_log_eb_copy above.
303357911b8bSJan Schmidt 		 */
30345f39d397SChris Mason 		memmove_extent_buffer(src, btrfs_node_key_ptr_offset(0),
30355f39d397SChris Mason 				      btrfs_node_key_ptr_offset(push_items),
3036e2fa7227SChris Mason 				      (src_nritems - push_items) *
3037123abc88SChris Mason 				      sizeof(struct btrfs_key_ptr));
3038bb803951SChris Mason 	}
30395f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
30405f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
30415f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
30425f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
304331840ae1SZheng Yan 
3044bb803951SChris Mason 	return ret;
3045be0e5c09SChris Mason }
3046be0e5c09SChris Mason 
304797571fd0SChris Mason /*
304879f95c82SChris Mason  * try to push data from one node into the next node right in the
304979f95c82SChris Mason  * tree.
305079f95c82SChris Mason  *
305179f95c82SChris Mason  * returns 0 if some ptrs were pushed, < 0 if there was some horrible
305279f95c82SChris Mason  * error, and > 0 if there was no room in the right hand block.
305379f95c82SChris Mason  *
305479f95c82SChris Mason  * this will  only push up to 1/2 the contents of the left node over
305579f95c82SChris Mason  */
30565f39d397SChris Mason static int balance_node_right(struct btrfs_trans_handle *trans,
30575f39d397SChris Mason 			      struct btrfs_root *root,
30585f39d397SChris Mason 			      struct extent_buffer *dst,
30595f39d397SChris Mason 			      struct extent_buffer *src)
306079f95c82SChris Mason {
306179f95c82SChris Mason 	int push_items = 0;
306279f95c82SChris Mason 	int max_push;
306379f95c82SChris Mason 	int src_nritems;
306479f95c82SChris Mason 	int dst_nritems;
306579f95c82SChris Mason 	int ret = 0;
306679f95c82SChris Mason 
30677bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
30687bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
30697bb86316SChris Mason 
30705f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
30715f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
3072123abc88SChris Mason 	push_items = BTRFS_NODEPTRS_PER_BLOCK(root) - dst_nritems;
3073d397712bSChris Mason 	if (push_items <= 0)
307479f95c82SChris Mason 		return 1;
3075bce4eae9SChris Mason 
3076d397712bSChris Mason 	if (src_nritems < 4)
3077bce4eae9SChris Mason 		return 1;
307879f95c82SChris Mason 
307979f95c82SChris Mason 	max_push = src_nritems / 2 + 1;
308079f95c82SChris Mason 	/* don't try to empty the node */
3081d397712bSChris Mason 	if (max_push >= src_nritems)
308279f95c82SChris Mason 		return 1;
3083252c38f0SYan 
308479f95c82SChris Mason 	if (max_push < push_items)
308579f95c82SChris Mason 		push_items = max_push;
308679f95c82SChris Mason 
3087f230475eSJan Schmidt 	tree_mod_log_eb_move(root->fs_info, dst, push_items, 0, dst_nritems);
30885f39d397SChris Mason 	memmove_extent_buffer(dst, btrfs_node_key_ptr_offset(push_items),
30895f39d397SChris Mason 				      btrfs_node_key_ptr_offset(0),
30905f39d397SChris Mason 				      (dst_nritems) *
30915f39d397SChris Mason 				      sizeof(struct btrfs_key_ptr));
3092d6025579SChris Mason 
3093f230475eSJan Schmidt 	tree_mod_log_eb_copy(root->fs_info, dst, src, 0,
309490f8d62eSJan Schmidt 			     src_nritems - push_items, push_items);
30955f39d397SChris Mason 	copy_extent_buffer(dst, src,
30965f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
30975f39d397SChris Mason 			   btrfs_node_key_ptr_offset(src_nritems - push_items),
3098123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
309979f95c82SChris Mason 
31005f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
31015f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
310279f95c82SChris Mason 
31035f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
31045f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
310531840ae1SZheng Yan 
310679f95c82SChris Mason 	return ret;
310779f95c82SChris Mason }
310879f95c82SChris Mason 
310979f95c82SChris Mason /*
311097571fd0SChris Mason  * helper function to insert a new root level in the tree.
311197571fd0SChris Mason  * A new node is allocated, and a single item is inserted to
311297571fd0SChris Mason  * point to the existing root
3113aa5d6bedSChris Mason  *
3114aa5d6bedSChris Mason  * returns zero on success or < 0 on failure.
311597571fd0SChris Mason  */
3116d397712bSChris Mason static noinline int insert_new_root(struct btrfs_trans_handle *trans,
31175f39d397SChris Mason 			   struct btrfs_root *root,
3118fdd99c72SLiu Bo 			   struct btrfs_path *path, int level)
311974123bd7SChris Mason {
31207bb86316SChris Mason 	u64 lower_gen;
31215f39d397SChris Mason 	struct extent_buffer *lower;
31225f39d397SChris Mason 	struct extent_buffer *c;
3123925baeddSChris Mason 	struct extent_buffer *old;
31245f39d397SChris Mason 	struct btrfs_disk_key lower_key;
31255c680ed6SChris Mason 
31265c680ed6SChris Mason 	BUG_ON(path->nodes[level]);
31275c680ed6SChris Mason 	BUG_ON(path->nodes[level-1] != root->node);
31285c680ed6SChris Mason 
31297bb86316SChris Mason 	lower = path->nodes[level-1];
31307bb86316SChris Mason 	if (level == 1)
31317bb86316SChris Mason 		btrfs_item_key(lower, &lower_key, 0);
31327bb86316SChris Mason 	else
31337bb86316SChris Mason 		btrfs_node_key(lower, &lower_key, 0);
31347bb86316SChris Mason 
313531840ae1SZheng Yan 	c = btrfs_alloc_free_block(trans, root, root->nodesize, 0,
31365d4f98a2SYan Zheng 				   root->root_key.objectid, &lower_key,
31375581a51aSJan Schmidt 				   level, root->node->start, 0);
31385f39d397SChris Mason 	if (IS_ERR(c))
31395f39d397SChris Mason 		return PTR_ERR(c);
3140925baeddSChris Mason 
3141f0486c68SYan, Zheng 	root_add_used(root, root->nodesize);
3142f0486c68SYan, Zheng 
31435d4f98a2SYan Zheng 	memset_extent_buffer(c, 0, 0, sizeof(struct btrfs_header));
31445f39d397SChris Mason 	btrfs_set_header_nritems(c, 1);
31455f39d397SChris Mason 	btrfs_set_header_level(c, level);
3146db94535dSChris Mason 	btrfs_set_header_bytenr(c, c->start);
31475f39d397SChris Mason 	btrfs_set_header_generation(c, trans->transid);
31485d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(c, BTRFS_MIXED_BACKREF_REV);
31495f39d397SChris Mason 	btrfs_set_header_owner(c, root->root_key.objectid);
3150d5719762SChris Mason 
3151fba6aa75SGeert Uytterhoeven 	write_extent_buffer(c, root->fs_info->fsid, btrfs_header_fsid(c),
31525f39d397SChris Mason 			    BTRFS_FSID_SIZE);
3153e17cade2SChris Mason 
3154e17cade2SChris Mason 	write_extent_buffer(c, root->fs_info->chunk_tree_uuid,
3155b308bc2fSGeert Uytterhoeven 			    btrfs_header_chunk_tree_uuid(c), BTRFS_UUID_SIZE);
3156e17cade2SChris Mason 
31575f39d397SChris Mason 	btrfs_set_node_key(c, &lower_key, 0);
3158db94535dSChris Mason 	btrfs_set_node_blockptr(c, 0, lower->start);
31597bb86316SChris Mason 	lower_gen = btrfs_header_generation(lower);
316031840ae1SZheng Yan 	WARN_ON(lower_gen != trans->transid);
31617bb86316SChris Mason 
31627bb86316SChris Mason 	btrfs_set_node_ptr_generation(c, 0, lower_gen);
31635f39d397SChris Mason 
31645f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
3165d5719762SChris Mason 
3166925baeddSChris Mason 	old = root->node;
3167fdd99c72SLiu Bo 	tree_mod_log_set_root_pointer(root, c, 0);
3168240f62c8SChris Mason 	rcu_assign_pointer(root->node, c);
3169925baeddSChris Mason 
3170925baeddSChris Mason 	/* the super has an extra ref to root->node */
3171925baeddSChris Mason 	free_extent_buffer(old);
3172925baeddSChris Mason 
31730b86a832SChris Mason 	add_root_to_dirty_list(root);
31745f39d397SChris Mason 	extent_buffer_get(c);
31755f39d397SChris Mason 	path->nodes[level] = c;
3176bd681513SChris Mason 	path->locks[level] = BTRFS_WRITE_LOCK;
317774123bd7SChris Mason 	path->slots[level] = 0;
317874123bd7SChris Mason 	return 0;
317974123bd7SChris Mason }
31805c680ed6SChris Mason 
31815c680ed6SChris Mason /*
31825c680ed6SChris Mason  * worker function to insert a single pointer in a node.
31835c680ed6SChris Mason  * the node should have enough room for the pointer already
318497571fd0SChris Mason  *
31855c680ed6SChris Mason  * slot and level indicate where you want the key to go, and
31865c680ed6SChris Mason  * blocknr is the block the key points to.
31875c680ed6SChris Mason  */
3188143bede5SJeff Mahoney static void insert_ptr(struct btrfs_trans_handle *trans,
3189143bede5SJeff Mahoney 		       struct btrfs_root *root, struct btrfs_path *path,
3190143bede5SJeff Mahoney 		       struct btrfs_disk_key *key, u64 bytenr,
3191c3e06965SJan Schmidt 		       int slot, int level)
31925c680ed6SChris Mason {
31935f39d397SChris Mason 	struct extent_buffer *lower;
31945c680ed6SChris Mason 	int nritems;
3195f3ea38daSJan Schmidt 	int ret;
31965c680ed6SChris Mason 
31975c680ed6SChris Mason 	BUG_ON(!path->nodes[level]);
3198f0486c68SYan, Zheng 	btrfs_assert_tree_locked(path->nodes[level]);
31995f39d397SChris Mason 	lower = path->nodes[level];
32005f39d397SChris Mason 	nritems = btrfs_header_nritems(lower);
3201c293498bSStoyan Gaydarov 	BUG_ON(slot > nritems);
3202143bede5SJeff Mahoney 	BUG_ON(nritems == BTRFS_NODEPTRS_PER_BLOCK(root));
320374123bd7SChris Mason 	if (slot != nritems) {
3204c3e06965SJan Schmidt 		if (level)
3205f3ea38daSJan Schmidt 			tree_mod_log_eb_move(root->fs_info, lower, slot + 1,
3206f3ea38daSJan Schmidt 					     slot, nritems - slot);
32075f39d397SChris Mason 		memmove_extent_buffer(lower,
32085f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot + 1),
32095f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot),
3210123abc88SChris Mason 			      (nritems - slot) * sizeof(struct btrfs_key_ptr));
321174123bd7SChris Mason 	}
3212c3e06965SJan Schmidt 	if (level) {
3213f3ea38daSJan Schmidt 		ret = tree_mod_log_insert_key(root->fs_info, lower, slot,
3214c8cc6341SJosef Bacik 					      MOD_LOG_KEY_ADD, GFP_NOFS);
3215f3ea38daSJan Schmidt 		BUG_ON(ret < 0);
3216f3ea38daSJan Schmidt 	}
32175f39d397SChris Mason 	btrfs_set_node_key(lower, key, slot);
3218db94535dSChris Mason 	btrfs_set_node_blockptr(lower, slot, bytenr);
321974493f7aSChris Mason 	WARN_ON(trans->transid == 0);
322074493f7aSChris Mason 	btrfs_set_node_ptr_generation(lower, slot, trans->transid);
32215f39d397SChris Mason 	btrfs_set_header_nritems(lower, nritems + 1);
32225f39d397SChris Mason 	btrfs_mark_buffer_dirty(lower);
322374123bd7SChris Mason }
322474123bd7SChris Mason 
322597571fd0SChris Mason /*
322697571fd0SChris Mason  * split the node at the specified level in path in two.
322797571fd0SChris Mason  * The path is corrected to point to the appropriate node after the split
322897571fd0SChris Mason  *
322997571fd0SChris Mason  * Before splitting this tries to make some room in the node by pushing
323097571fd0SChris Mason  * left and right, if either one works, it returns right away.
3231aa5d6bedSChris Mason  *
3232aa5d6bedSChris Mason  * returns 0 on success and < 0 on failure
323397571fd0SChris Mason  */
3234e02119d5SChris Mason static noinline int split_node(struct btrfs_trans_handle *trans,
3235e02119d5SChris Mason 			       struct btrfs_root *root,
3236e02119d5SChris Mason 			       struct btrfs_path *path, int level)
3237be0e5c09SChris Mason {
32385f39d397SChris Mason 	struct extent_buffer *c;
32395f39d397SChris Mason 	struct extent_buffer *split;
32405f39d397SChris Mason 	struct btrfs_disk_key disk_key;
3241be0e5c09SChris Mason 	int mid;
32425c680ed6SChris Mason 	int ret;
32437518a238SChris Mason 	u32 c_nritems;
3244be0e5c09SChris Mason 
32455f39d397SChris Mason 	c = path->nodes[level];
32467bb86316SChris Mason 	WARN_ON(btrfs_header_generation(c) != trans->transid);
32475f39d397SChris Mason 	if (c == root->node) {
3248d9abbf1cSJan Schmidt 		/*
324990f8d62eSJan Schmidt 		 * trying to split the root, lets make a new one
325090f8d62eSJan Schmidt 		 *
3251fdd99c72SLiu Bo 		 * tree mod log: We don't log_removal old root in
325290f8d62eSJan Schmidt 		 * insert_new_root, because that root buffer will be kept as a
325390f8d62eSJan Schmidt 		 * normal node. We are going to log removal of half of the
325490f8d62eSJan Schmidt 		 * elements below with tree_mod_log_eb_copy. We're holding a
325590f8d62eSJan Schmidt 		 * tree lock on the buffer, which is why we cannot race with
325690f8d62eSJan Schmidt 		 * other tree_mod_log users.
3257d9abbf1cSJan Schmidt 		 */
3258fdd99c72SLiu Bo 		ret = insert_new_root(trans, root, path, level + 1);
32595c680ed6SChris Mason 		if (ret)
32605c680ed6SChris Mason 			return ret;
3261b3612421SChris Mason 	} else {
3262e66f709bSChris Mason 		ret = push_nodes_for_insert(trans, root, path, level);
32635f39d397SChris Mason 		c = path->nodes[level];
32645f39d397SChris Mason 		if (!ret && btrfs_header_nritems(c) <
3265c448acf0SChris Mason 		    BTRFS_NODEPTRS_PER_BLOCK(root) - 3)
3266e66f709bSChris Mason 			return 0;
326754aa1f4dSChris Mason 		if (ret < 0)
326854aa1f4dSChris Mason 			return ret;
32695c680ed6SChris Mason 	}
3270e66f709bSChris Mason 
32715f39d397SChris Mason 	c_nritems = btrfs_header_nritems(c);
32725d4f98a2SYan Zheng 	mid = (c_nritems + 1) / 2;
32735d4f98a2SYan Zheng 	btrfs_node_key(c, &disk_key, mid);
32747bb86316SChris Mason 
32755d4f98a2SYan Zheng 	split = btrfs_alloc_free_block(trans, root, root->nodesize, 0,
32767bb86316SChris Mason 					root->root_key.objectid,
32775581a51aSJan Schmidt 					&disk_key, level, c->start, 0);
32785f39d397SChris Mason 	if (IS_ERR(split))
32795f39d397SChris Mason 		return PTR_ERR(split);
328054aa1f4dSChris Mason 
3281f0486c68SYan, Zheng 	root_add_used(root, root->nodesize);
3282f0486c68SYan, Zheng 
32835d4f98a2SYan Zheng 	memset_extent_buffer(split, 0, 0, sizeof(struct btrfs_header));
32845f39d397SChris Mason 	btrfs_set_header_level(split, btrfs_header_level(c));
3285db94535dSChris Mason 	btrfs_set_header_bytenr(split, split->start);
32865f39d397SChris Mason 	btrfs_set_header_generation(split, trans->transid);
32875d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(split, BTRFS_MIXED_BACKREF_REV);
32885f39d397SChris Mason 	btrfs_set_header_owner(split, root->root_key.objectid);
32895f39d397SChris Mason 	write_extent_buffer(split, root->fs_info->fsid,
3290fba6aa75SGeert Uytterhoeven 			    btrfs_header_fsid(split), BTRFS_FSID_SIZE);
3291e17cade2SChris Mason 	write_extent_buffer(split, root->fs_info->chunk_tree_uuid,
3292b308bc2fSGeert Uytterhoeven 			    btrfs_header_chunk_tree_uuid(split),
3293e17cade2SChris Mason 			    BTRFS_UUID_SIZE);
32945f39d397SChris Mason 
329590f8d62eSJan Schmidt 	tree_mod_log_eb_copy(root->fs_info, split, c, 0, mid, c_nritems - mid);
32965f39d397SChris Mason 	copy_extent_buffer(split, c,
32975f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
32985f39d397SChris Mason 			   btrfs_node_key_ptr_offset(mid),
3299123abc88SChris Mason 			   (c_nritems - mid) * sizeof(struct btrfs_key_ptr));
33005f39d397SChris Mason 	btrfs_set_header_nritems(split, c_nritems - mid);
33015f39d397SChris Mason 	btrfs_set_header_nritems(c, mid);
3302aa5d6bedSChris Mason 	ret = 0;
3303aa5d6bedSChris Mason 
33045f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
33055f39d397SChris Mason 	btrfs_mark_buffer_dirty(split);
33065f39d397SChris Mason 
3307143bede5SJeff Mahoney 	insert_ptr(trans, root, path, &disk_key, split->start,
3308c3e06965SJan Schmidt 		   path->slots[level + 1] + 1, level + 1);
3309aa5d6bedSChris Mason 
33105de08d7dSChris Mason 	if (path->slots[level] >= mid) {
33115c680ed6SChris Mason 		path->slots[level] -= mid;
3312925baeddSChris Mason 		btrfs_tree_unlock(c);
33135f39d397SChris Mason 		free_extent_buffer(c);
33145f39d397SChris Mason 		path->nodes[level] = split;
33155c680ed6SChris Mason 		path->slots[level + 1] += 1;
3316eb60ceacSChris Mason 	} else {
3317925baeddSChris Mason 		btrfs_tree_unlock(split);
33185f39d397SChris Mason 		free_extent_buffer(split);
3319be0e5c09SChris Mason 	}
3320aa5d6bedSChris Mason 	return ret;
3321be0e5c09SChris Mason }
3322be0e5c09SChris Mason 
332374123bd7SChris Mason /*
332474123bd7SChris Mason  * how many bytes are required to store the items in a leaf.  start
332574123bd7SChris Mason  * and nr indicate which items in the leaf to check.  This totals up the
332674123bd7SChris Mason  * space used both by the item structs and the item data
332774123bd7SChris Mason  */
33285f39d397SChris Mason static int leaf_space_used(struct extent_buffer *l, int start, int nr)
3329be0e5c09SChris Mason {
333041be1f3bSJosef Bacik 	struct btrfs_item *start_item;
333141be1f3bSJosef Bacik 	struct btrfs_item *end_item;
333241be1f3bSJosef Bacik 	struct btrfs_map_token token;
3333be0e5c09SChris Mason 	int data_len;
33345f39d397SChris Mason 	int nritems = btrfs_header_nritems(l);
3335d4dbff95SChris Mason 	int end = min(nritems, start + nr) - 1;
3336be0e5c09SChris Mason 
3337be0e5c09SChris Mason 	if (!nr)
3338be0e5c09SChris Mason 		return 0;
333941be1f3bSJosef Bacik 	btrfs_init_map_token(&token);
334041be1f3bSJosef Bacik 	start_item = btrfs_item_nr(l, start);
334141be1f3bSJosef Bacik 	end_item = btrfs_item_nr(l, end);
334241be1f3bSJosef Bacik 	data_len = btrfs_token_item_offset(l, start_item, &token) +
334341be1f3bSJosef Bacik 		btrfs_token_item_size(l, start_item, &token);
334441be1f3bSJosef Bacik 	data_len = data_len - btrfs_token_item_offset(l, end_item, &token);
33450783fcfcSChris Mason 	data_len += sizeof(struct btrfs_item) * nr;
3346d4dbff95SChris Mason 	WARN_ON(data_len < 0);
3347be0e5c09SChris Mason 	return data_len;
3348be0e5c09SChris Mason }
3349be0e5c09SChris Mason 
335074123bd7SChris Mason /*
3351d4dbff95SChris Mason  * The space between the end of the leaf items and
3352d4dbff95SChris Mason  * the start of the leaf data.  IOW, how much room
3353d4dbff95SChris Mason  * the leaf has left for both items and data
3354d4dbff95SChris Mason  */
3355d397712bSChris Mason noinline int btrfs_leaf_free_space(struct btrfs_root *root,
3356e02119d5SChris Mason 				   struct extent_buffer *leaf)
3357d4dbff95SChris Mason {
33585f39d397SChris Mason 	int nritems = btrfs_header_nritems(leaf);
33595f39d397SChris Mason 	int ret;
33605f39d397SChris Mason 	ret = BTRFS_LEAF_DATA_SIZE(root) - leaf_space_used(leaf, 0, nritems);
33615f39d397SChris Mason 	if (ret < 0) {
3362d397712bSChris Mason 		printk(KERN_CRIT "leaf free space ret %d, leaf data size %lu, "
3363d397712bSChris Mason 		       "used %d nritems %d\n",
3364ae2f5411SJens Axboe 		       ret, (unsigned long) BTRFS_LEAF_DATA_SIZE(root),
33655f39d397SChris Mason 		       leaf_space_used(leaf, 0, nritems), nritems);
33665f39d397SChris Mason 	}
33675f39d397SChris Mason 	return ret;
3368d4dbff95SChris Mason }
3369d4dbff95SChris Mason 
337099d8f83cSChris Mason /*
337199d8f83cSChris Mason  * min slot controls the lowest index we're willing to push to the
337299d8f83cSChris Mason  * right.  We'll push up to and including min_slot, but no lower
337399d8f83cSChris Mason  */
337444871b1bSChris Mason static noinline int __push_leaf_right(struct btrfs_trans_handle *trans,
337544871b1bSChris Mason 				      struct btrfs_root *root,
337644871b1bSChris Mason 				      struct btrfs_path *path,
337744871b1bSChris Mason 				      int data_size, int empty,
337844871b1bSChris Mason 				      struct extent_buffer *right,
337999d8f83cSChris Mason 				      int free_space, u32 left_nritems,
338099d8f83cSChris Mason 				      u32 min_slot)
338100ec4c51SChris Mason {
33825f39d397SChris Mason 	struct extent_buffer *left = path->nodes[0];
338344871b1bSChris Mason 	struct extent_buffer *upper = path->nodes[1];
3384cfed81a0SChris Mason 	struct btrfs_map_token token;
33855f39d397SChris Mason 	struct btrfs_disk_key disk_key;
338600ec4c51SChris Mason 	int slot;
338734a38218SChris Mason 	u32 i;
338800ec4c51SChris Mason 	int push_space = 0;
338900ec4c51SChris Mason 	int push_items = 0;
33900783fcfcSChris Mason 	struct btrfs_item *item;
339134a38218SChris Mason 	u32 nr;
33927518a238SChris Mason 	u32 right_nritems;
33935f39d397SChris Mason 	u32 data_end;
3394db94535dSChris Mason 	u32 this_item_size;
339500ec4c51SChris Mason 
3396cfed81a0SChris Mason 	btrfs_init_map_token(&token);
3397cfed81a0SChris Mason 
339834a38218SChris Mason 	if (empty)
339934a38218SChris Mason 		nr = 0;
340034a38218SChris Mason 	else
340199d8f83cSChris Mason 		nr = max_t(u32, 1, min_slot);
340234a38218SChris Mason 
340331840ae1SZheng Yan 	if (path->slots[0] >= left_nritems)
340487b29b20SYan Zheng 		push_space += data_size;
340531840ae1SZheng Yan 
340644871b1bSChris Mason 	slot = path->slots[1];
340734a38218SChris Mason 	i = left_nritems - 1;
340834a38218SChris Mason 	while (i >= nr) {
34095f39d397SChris Mason 		item = btrfs_item_nr(left, i);
3410db94535dSChris Mason 
341131840ae1SZheng Yan 		if (!empty && push_items > 0) {
341231840ae1SZheng Yan 			if (path->slots[0] > i)
341331840ae1SZheng Yan 				break;
341431840ae1SZheng Yan 			if (path->slots[0] == i) {
341531840ae1SZheng Yan 				int space = btrfs_leaf_free_space(root, left);
341631840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
341731840ae1SZheng Yan 					break;
341831840ae1SZheng Yan 			}
341931840ae1SZheng Yan 		}
342031840ae1SZheng Yan 
342100ec4c51SChris Mason 		if (path->slots[0] == i)
342287b29b20SYan Zheng 			push_space += data_size;
3423db94535dSChris Mason 
3424db94535dSChris Mason 		this_item_size = btrfs_item_size(left, item);
3425db94535dSChris Mason 		if (this_item_size + sizeof(*item) + push_space > free_space)
342600ec4c51SChris Mason 			break;
342731840ae1SZheng Yan 
342800ec4c51SChris Mason 		push_items++;
3429db94535dSChris Mason 		push_space += this_item_size + sizeof(*item);
343034a38218SChris Mason 		if (i == 0)
343134a38218SChris Mason 			break;
343234a38218SChris Mason 		i--;
3433db94535dSChris Mason 	}
34345f39d397SChris Mason 
3435925baeddSChris Mason 	if (push_items == 0)
3436925baeddSChris Mason 		goto out_unlock;
34375f39d397SChris Mason 
34386c1500f2SJulia Lawall 	WARN_ON(!empty && push_items == left_nritems);
34395f39d397SChris Mason 
344000ec4c51SChris Mason 	/* push left to right */
34415f39d397SChris Mason 	right_nritems = btrfs_header_nritems(right);
344234a38218SChris Mason 
34435f39d397SChris Mason 	push_space = btrfs_item_end_nr(left, left_nritems - push_items);
3444123abc88SChris Mason 	push_space -= leaf_data_end(root, left);
34455f39d397SChris Mason 
344600ec4c51SChris Mason 	/* make room in the right data area */
34475f39d397SChris Mason 	data_end = leaf_data_end(root, right);
34485f39d397SChris Mason 	memmove_extent_buffer(right,
34495f39d397SChris Mason 			      btrfs_leaf_data(right) + data_end - push_space,
34505f39d397SChris Mason 			      btrfs_leaf_data(right) + data_end,
34515f39d397SChris Mason 			      BTRFS_LEAF_DATA_SIZE(root) - data_end);
34525f39d397SChris Mason 
345300ec4c51SChris Mason 	/* copy from the left data area */
34545f39d397SChris Mason 	copy_extent_buffer(right, left, btrfs_leaf_data(right) +
3455d6025579SChris Mason 		     BTRFS_LEAF_DATA_SIZE(root) - push_space,
3456d6025579SChris Mason 		     btrfs_leaf_data(left) + leaf_data_end(root, left),
3457d6025579SChris Mason 		     push_space);
34585f39d397SChris Mason 
34595f39d397SChris Mason 	memmove_extent_buffer(right, btrfs_item_nr_offset(push_items),
34605f39d397SChris Mason 			      btrfs_item_nr_offset(0),
34610783fcfcSChris Mason 			      right_nritems * sizeof(struct btrfs_item));
34625f39d397SChris Mason 
346300ec4c51SChris Mason 	/* copy the items from left to right */
34645f39d397SChris Mason 	copy_extent_buffer(right, left, btrfs_item_nr_offset(0),
34655f39d397SChris Mason 		   btrfs_item_nr_offset(left_nritems - push_items),
34660783fcfcSChris Mason 		   push_items * sizeof(struct btrfs_item));
346700ec4c51SChris Mason 
346800ec4c51SChris Mason 	/* update the item pointers */
34697518a238SChris Mason 	right_nritems += push_items;
34705f39d397SChris Mason 	btrfs_set_header_nritems(right, right_nritems);
3471123abc88SChris Mason 	push_space = BTRFS_LEAF_DATA_SIZE(root);
34727518a238SChris Mason 	for (i = 0; i < right_nritems; i++) {
34735f39d397SChris Mason 		item = btrfs_item_nr(right, i);
3474cfed81a0SChris Mason 		push_space -= btrfs_token_item_size(right, item, &token);
3475cfed81a0SChris Mason 		btrfs_set_token_item_offset(right, item, push_space, &token);
3476db94535dSChris Mason 	}
3477db94535dSChris Mason 
34787518a238SChris Mason 	left_nritems -= push_items;
34795f39d397SChris Mason 	btrfs_set_header_nritems(left, left_nritems);
348000ec4c51SChris Mason 
348134a38218SChris Mason 	if (left_nritems)
34825f39d397SChris Mason 		btrfs_mark_buffer_dirty(left);
3483f0486c68SYan, Zheng 	else
3484f0486c68SYan, Zheng 		clean_tree_block(trans, root, left);
3485f0486c68SYan, Zheng 
34865f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
3487a429e513SChris Mason 
34885f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
34895f39d397SChris Mason 	btrfs_set_node_key(upper, &disk_key, slot + 1);
3490d6025579SChris Mason 	btrfs_mark_buffer_dirty(upper);
349102217ed2SChris Mason 
349200ec4c51SChris Mason 	/* then fixup the leaf pointer in the path */
34937518a238SChris Mason 	if (path->slots[0] >= left_nritems) {
34947518a238SChris Mason 		path->slots[0] -= left_nritems;
3495925baeddSChris Mason 		if (btrfs_header_nritems(path->nodes[0]) == 0)
3496925baeddSChris Mason 			clean_tree_block(trans, root, path->nodes[0]);
3497925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
34985f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
34995f39d397SChris Mason 		path->nodes[0] = right;
350000ec4c51SChris Mason 		path->slots[1] += 1;
350100ec4c51SChris Mason 	} else {
3502925baeddSChris Mason 		btrfs_tree_unlock(right);
35035f39d397SChris Mason 		free_extent_buffer(right);
350400ec4c51SChris Mason 	}
350500ec4c51SChris Mason 	return 0;
3506925baeddSChris Mason 
3507925baeddSChris Mason out_unlock:
3508925baeddSChris Mason 	btrfs_tree_unlock(right);
3509925baeddSChris Mason 	free_extent_buffer(right);
3510925baeddSChris Mason 	return 1;
351100ec4c51SChris Mason }
3512925baeddSChris Mason 
351300ec4c51SChris Mason /*
351444871b1bSChris Mason  * push some data in the path leaf to the right, trying to free up at
351574123bd7SChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
351644871b1bSChris Mason  *
351744871b1bSChris Mason  * returns 1 if the push failed because the other node didn't have enough
351844871b1bSChris Mason  * room, 0 if everything worked out and < 0 if there were major errors.
351999d8f83cSChris Mason  *
352099d8f83cSChris Mason  * this will push starting from min_slot to the end of the leaf.  It won't
352199d8f83cSChris Mason  * push any slot lower than min_slot
352274123bd7SChris Mason  */
352344871b1bSChris Mason static int push_leaf_right(struct btrfs_trans_handle *trans, struct btrfs_root
352499d8f83cSChris Mason 			   *root, struct btrfs_path *path,
352599d8f83cSChris Mason 			   int min_data_size, int data_size,
352699d8f83cSChris Mason 			   int empty, u32 min_slot)
3527be0e5c09SChris Mason {
352844871b1bSChris Mason 	struct extent_buffer *left = path->nodes[0];
352944871b1bSChris Mason 	struct extent_buffer *right;
353044871b1bSChris Mason 	struct extent_buffer *upper;
353144871b1bSChris Mason 	int slot;
353244871b1bSChris Mason 	int free_space;
353344871b1bSChris Mason 	u32 left_nritems;
353444871b1bSChris Mason 	int ret;
353544871b1bSChris Mason 
353644871b1bSChris Mason 	if (!path->nodes[1])
353744871b1bSChris Mason 		return 1;
353844871b1bSChris Mason 
353944871b1bSChris Mason 	slot = path->slots[1];
354044871b1bSChris Mason 	upper = path->nodes[1];
354144871b1bSChris Mason 	if (slot >= btrfs_header_nritems(upper) - 1)
354244871b1bSChris Mason 		return 1;
354344871b1bSChris Mason 
354444871b1bSChris Mason 	btrfs_assert_tree_locked(path->nodes[1]);
354544871b1bSChris Mason 
354644871b1bSChris Mason 	right = read_node_slot(root, upper, slot + 1);
354791ca338dSTsutomu Itoh 	if (right == NULL)
354891ca338dSTsutomu Itoh 		return 1;
354991ca338dSTsutomu Itoh 
355044871b1bSChris Mason 	btrfs_tree_lock(right);
355144871b1bSChris Mason 	btrfs_set_lock_blocking(right);
355244871b1bSChris Mason 
355344871b1bSChris Mason 	free_space = btrfs_leaf_free_space(root, right);
355444871b1bSChris Mason 	if (free_space < data_size)
355544871b1bSChris Mason 		goto out_unlock;
355644871b1bSChris Mason 
355744871b1bSChris Mason 	/* cow and double check */
355844871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, right, upper,
355944871b1bSChris Mason 			      slot + 1, &right);
356044871b1bSChris Mason 	if (ret)
356144871b1bSChris Mason 		goto out_unlock;
356244871b1bSChris Mason 
356344871b1bSChris Mason 	free_space = btrfs_leaf_free_space(root, right);
356444871b1bSChris Mason 	if (free_space < data_size)
356544871b1bSChris Mason 		goto out_unlock;
356644871b1bSChris Mason 
356744871b1bSChris Mason 	left_nritems = btrfs_header_nritems(left);
356844871b1bSChris Mason 	if (left_nritems == 0)
356944871b1bSChris Mason 		goto out_unlock;
357044871b1bSChris Mason 
357199d8f83cSChris Mason 	return __push_leaf_right(trans, root, path, min_data_size, empty,
357299d8f83cSChris Mason 				right, free_space, left_nritems, min_slot);
357344871b1bSChris Mason out_unlock:
357444871b1bSChris Mason 	btrfs_tree_unlock(right);
357544871b1bSChris Mason 	free_extent_buffer(right);
357644871b1bSChris Mason 	return 1;
357744871b1bSChris Mason }
357844871b1bSChris Mason 
357944871b1bSChris Mason /*
358044871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
358144871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
358299d8f83cSChris Mason  *
358399d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
358499d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us do all the
358599d8f83cSChris Mason  * items
358644871b1bSChris Mason  */
358744871b1bSChris Mason static noinline int __push_leaf_left(struct btrfs_trans_handle *trans,
358844871b1bSChris Mason 				     struct btrfs_root *root,
358944871b1bSChris Mason 				     struct btrfs_path *path, int data_size,
359044871b1bSChris Mason 				     int empty, struct extent_buffer *left,
359199d8f83cSChris Mason 				     int free_space, u32 right_nritems,
359299d8f83cSChris Mason 				     u32 max_slot)
359344871b1bSChris Mason {
35945f39d397SChris Mason 	struct btrfs_disk_key disk_key;
35955f39d397SChris Mason 	struct extent_buffer *right = path->nodes[0];
3596be0e5c09SChris Mason 	int i;
3597be0e5c09SChris Mason 	int push_space = 0;
3598be0e5c09SChris Mason 	int push_items = 0;
35990783fcfcSChris Mason 	struct btrfs_item *item;
36007518a238SChris Mason 	u32 old_left_nritems;
360134a38218SChris Mason 	u32 nr;
3602aa5d6bedSChris Mason 	int ret = 0;
3603db94535dSChris Mason 	u32 this_item_size;
3604db94535dSChris Mason 	u32 old_left_item_size;
3605cfed81a0SChris Mason 	struct btrfs_map_token token;
3606cfed81a0SChris Mason 
3607cfed81a0SChris Mason 	btrfs_init_map_token(&token);
3608be0e5c09SChris Mason 
360934a38218SChris Mason 	if (empty)
361099d8f83cSChris Mason 		nr = min(right_nritems, max_slot);
361134a38218SChris Mason 	else
361299d8f83cSChris Mason 		nr = min(right_nritems - 1, max_slot);
361334a38218SChris Mason 
361434a38218SChris Mason 	for (i = 0; i < nr; i++) {
36155f39d397SChris Mason 		item = btrfs_item_nr(right, i);
3616db94535dSChris Mason 
361731840ae1SZheng Yan 		if (!empty && push_items > 0) {
361831840ae1SZheng Yan 			if (path->slots[0] < i)
361931840ae1SZheng Yan 				break;
362031840ae1SZheng Yan 			if (path->slots[0] == i) {
362131840ae1SZheng Yan 				int space = btrfs_leaf_free_space(root, right);
362231840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
362331840ae1SZheng Yan 					break;
362431840ae1SZheng Yan 			}
362531840ae1SZheng Yan 		}
362631840ae1SZheng Yan 
3627be0e5c09SChris Mason 		if (path->slots[0] == i)
362887b29b20SYan Zheng 			push_space += data_size;
3629db94535dSChris Mason 
3630db94535dSChris Mason 		this_item_size = btrfs_item_size(right, item);
3631db94535dSChris Mason 		if (this_item_size + sizeof(*item) + push_space > free_space)
3632be0e5c09SChris Mason 			break;
3633db94535dSChris Mason 
3634be0e5c09SChris Mason 		push_items++;
3635db94535dSChris Mason 		push_space += this_item_size + sizeof(*item);
3636be0e5c09SChris Mason 	}
3637db94535dSChris Mason 
3638be0e5c09SChris Mason 	if (push_items == 0) {
3639925baeddSChris Mason 		ret = 1;
3640925baeddSChris Mason 		goto out;
3641be0e5c09SChris Mason 	}
364234a38218SChris Mason 	if (!empty && push_items == btrfs_header_nritems(right))
3643a429e513SChris Mason 		WARN_ON(1);
36445f39d397SChris Mason 
3645be0e5c09SChris Mason 	/* push data from right to left */
36465f39d397SChris Mason 	copy_extent_buffer(left, right,
36475f39d397SChris Mason 			   btrfs_item_nr_offset(btrfs_header_nritems(left)),
36485f39d397SChris Mason 			   btrfs_item_nr_offset(0),
36495f39d397SChris Mason 			   push_items * sizeof(struct btrfs_item));
36505f39d397SChris Mason 
3651123abc88SChris Mason 	push_space = BTRFS_LEAF_DATA_SIZE(root) -
36525f39d397SChris Mason 		     btrfs_item_offset_nr(right, push_items - 1);
36535f39d397SChris Mason 
36545f39d397SChris Mason 	copy_extent_buffer(left, right, btrfs_leaf_data(left) +
3655d6025579SChris Mason 		     leaf_data_end(root, left) - push_space,
3656123abc88SChris Mason 		     btrfs_leaf_data(right) +
36575f39d397SChris Mason 		     btrfs_item_offset_nr(right, push_items - 1),
3658be0e5c09SChris Mason 		     push_space);
36595f39d397SChris Mason 	old_left_nritems = btrfs_header_nritems(left);
366087b29b20SYan Zheng 	BUG_ON(old_left_nritems <= 0);
3661eb60ceacSChris Mason 
3662db94535dSChris Mason 	old_left_item_size = btrfs_item_offset_nr(left, old_left_nritems - 1);
3663be0e5c09SChris Mason 	for (i = old_left_nritems; i < old_left_nritems + push_items; i++) {
36645f39d397SChris Mason 		u32 ioff;
3665db94535dSChris Mason 
36665f39d397SChris Mason 		item = btrfs_item_nr(left, i);
3667db94535dSChris Mason 
3668cfed81a0SChris Mason 		ioff = btrfs_token_item_offset(left, item, &token);
3669cfed81a0SChris Mason 		btrfs_set_token_item_offset(left, item,
3670cfed81a0SChris Mason 		      ioff - (BTRFS_LEAF_DATA_SIZE(root) - old_left_item_size),
3671cfed81a0SChris Mason 		      &token);
3672be0e5c09SChris Mason 	}
36735f39d397SChris Mason 	btrfs_set_header_nritems(left, old_left_nritems + push_items);
3674be0e5c09SChris Mason 
3675be0e5c09SChris Mason 	/* fixup right node */
367631b1a2bdSJulia Lawall 	if (push_items > right_nritems)
367731b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "push items %d nr %u\n", push_items,
3678d397712bSChris Mason 		       right_nritems);
367934a38218SChris Mason 
368034a38218SChris Mason 	if (push_items < right_nritems) {
36815f39d397SChris Mason 		push_space = btrfs_item_offset_nr(right, push_items - 1) -
3682123abc88SChris Mason 						  leaf_data_end(root, right);
36835f39d397SChris Mason 		memmove_extent_buffer(right, btrfs_leaf_data(right) +
3684d6025579SChris Mason 				      BTRFS_LEAF_DATA_SIZE(root) - push_space,
3685d6025579SChris Mason 				      btrfs_leaf_data(right) +
3686123abc88SChris Mason 				      leaf_data_end(root, right), push_space);
36875f39d397SChris Mason 
36885f39d397SChris Mason 		memmove_extent_buffer(right, btrfs_item_nr_offset(0),
36895f39d397SChris Mason 			      btrfs_item_nr_offset(push_items),
36905f39d397SChris Mason 			     (btrfs_header_nritems(right) - push_items) *
36910783fcfcSChris Mason 			     sizeof(struct btrfs_item));
369234a38218SChris Mason 	}
3693eef1c494SYan 	right_nritems -= push_items;
3694eef1c494SYan 	btrfs_set_header_nritems(right, right_nritems);
3695123abc88SChris Mason 	push_space = BTRFS_LEAF_DATA_SIZE(root);
36965f39d397SChris Mason 	for (i = 0; i < right_nritems; i++) {
36975f39d397SChris Mason 		item = btrfs_item_nr(right, i);
3698db94535dSChris Mason 
3699cfed81a0SChris Mason 		push_space = push_space - btrfs_token_item_size(right,
3700cfed81a0SChris Mason 								item, &token);
3701cfed81a0SChris Mason 		btrfs_set_token_item_offset(right, item, push_space, &token);
3702db94535dSChris Mason 	}
3703eb60ceacSChris Mason 
37045f39d397SChris Mason 	btrfs_mark_buffer_dirty(left);
370534a38218SChris Mason 	if (right_nritems)
37065f39d397SChris Mason 		btrfs_mark_buffer_dirty(right);
3707f0486c68SYan, Zheng 	else
3708f0486c68SYan, Zheng 		clean_tree_block(trans, root, right);
3709098f59c2SChris Mason 
37105f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
3711d6a0a126STsutomu Itoh 	fixup_low_keys(root, path, &disk_key, 1);
3712be0e5c09SChris Mason 
3713be0e5c09SChris Mason 	/* then fixup the leaf pointer in the path */
3714be0e5c09SChris Mason 	if (path->slots[0] < push_items) {
3715be0e5c09SChris Mason 		path->slots[0] += old_left_nritems;
3716925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
37175f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
37185f39d397SChris Mason 		path->nodes[0] = left;
3719be0e5c09SChris Mason 		path->slots[1] -= 1;
3720be0e5c09SChris Mason 	} else {
3721925baeddSChris Mason 		btrfs_tree_unlock(left);
37225f39d397SChris Mason 		free_extent_buffer(left);
3723be0e5c09SChris Mason 		path->slots[0] -= push_items;
3724be0e5c09SChris Mason 	}
3725eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
3726aa5d6bedSChris Mason 	return ret;
3727925baeddSChris Mason out:
3728925baeddSChris Mason 	btrfs_tree_unlock(left);
3729925baeddSChris Mason 	free_extent_buffer(left);
3730925baeddSChris Mason 	return ret;
3731be0e5c09SChris Mason }
3732be0e5c09SChris Mason 
373374123bd7SChris Mason /*
373444871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
373544871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
373699d8f83cSChris Mason  *
373799d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
373899d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us push all the
373999d8f83cSChris Mason  * items
374044871b1bSChris Mason  */
374144871b1bSChris Mason static int push_leaf_left(struct btrfs_trans_handle *trans, struct btrfs_root
374299d8f83cSChris Mason 			  *root, struct btrfs_path *path, int min_data_size,
374399d8f83cSChris Mason 			  int data_size, int empty, u32 max_slot)
374444871b1bSChris Mason {
374544871b1bSChris Mason 	struct extent_buffer *right = path->nodes[0];
374644871b1bSChris Mason 	struct extent_buffer *left;
374744871b1bSChris Mason 	int slot;
374844871b1bSChris Mason 	int free_space;
374944871b1bSChris Mason 	u32 right_nritems;
375044871b1bSChris Mason 	int ret = 0;
375144871b1bSChris Mason 
375244871b1bSChris Mason 	slot = path->slots[1];
375344871b1bSChris Mason 	if (slot == 0)
375444871b1bSChris Mason 		return 1;
375544871b1bSChris Mason 	if (!path->nodes[1])
375644871b1bSChris Mason 		return 1;
375744871b1bSChris Mason 
375844871b1bSChris Mason 	right_nritems = btrfs_header_nritems(right);
375944871b1bSChris Mason 	if (right_nritems == 0)
376044871b1bSChris Mason 		return 1;
376144871b1bSChris Mason 
376244871b1bSChris Mason 	btrfs_assert_tree_locked(path->nodes[1]);
376344871b1bSChris Mason 
376444871b1bSChris Mason 	left = read_node_slot(root, path->nodes[1], slot - 1);
376591ca338dSTsutomu Itoh 	if (left == NULL)
376691ca338dSTsutomu Itoh 		return 1;
376791ca338dSTsutomu Itoh 
376844871b1bSChris Mason 	btrfs_tree_lock(left);
376944871b1bSChris Mason 	btrfs_set_lock_blocking(left);
377044871b1bSChris Mason 
377144871b1bSChris Mason 	free_space = btrfs_leaf_free_space(root, left);
377244871b1bSChris Mason 	if (free_space < data_size) {
377344871b1bSChris Mason 		ret = 1;
377444871b1bSChris Mason 		goto out;
377544871b1bSChris Mason 	}
377644871b1bSChris Mason 
377744871b1bSChris Mason 	/* cow and double check */
377844871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, left,
377944871b1bSChris Mason 			      path->nodes[1], slot - 1, &left);
378044871b1bSChris Mason 	if (ret) {
378144871b1bSChris Mason 		/* we hit -ENOSPC, but it isn't fatal here */
378279787eaaSJeff Mahoney 		if (ret == -ENOSPC)
378344871b1bSChris Mason 			ret = 1;
378444871b1bSChris Mason 		goto out;
378544871b1bSChris Mason 	}
378644871b1bSChris Mason 
378744871b1bSChris Mason 	free_space = btrfs_leaf_free_space(root, left);
378844871b1bSChris Mason 	if (free_space < data_size) {
378944871b1bSChris Mason 		ret = 1;
379044871b1bSChris Mason 		goto out;
379144871b1bSChris Mason 	}
379244871b1bSChris Mason 
379399d8f83cSChris Mason 	return __push_leaf_left(trans, root, path, min_data_size,
379499d8f83cSChris Mason 			       empty, left, free_space, right_nritems,
379599d8f83cSChris Mason 			       max_slot);
379644871b1bSChris Mason out:
379744871b1bSChris Mason 	btrfs_tree_unlock(left);
379844871b1bSChris Mason 	free_extent_buffer(left);
379944871b1bSChris Mason 	return ret;
380044871b1bSChris Mason }
380144871b1bSChris Mason 
380244871b1bSChris Mason /*
380374123bd7SChris Mason  * split the path's leaf in two, making sure there is at least data_size
380474123bd7SChris Mason  * available for the resulting leaf level of the path.
380574123bd7SChris Mason  */
3806143bede5SJeff Mahoney static noinline void copy_for_split(struct btrfs_trans_handle *trans,
3807e02119d5SChris Mason 				    struct btrfs_root *root,
380844871b1bSChris Mason 				    struct btrfs_path *path,
380944871b1bSChris Mason 				    struct extent_buffer *l,
381044871b1bSChris Mason 				    struct extent_buffer *right,
381144871b1bSChris Mason 				    int slot, int mid, int nritems)
3812be0e5c09SChris Mason {
3813be0e5c09SChris Mason 	int data_copy_size;
3814be0e5c09SChris Mason 	int rt_data_off;
3815be0e5c09SChris Mason 	int i;
3816d4dbff95SChris Mason 	struct btrfs_disk_key disk_key;
3817cfed81a0SChris Mason 	struct btrfs_map_token token;
3818cfed81a0SChris Mason 
3819cfed81a0SChris Mason 	btrfs_init_map_token(&token);
3820be0e5c09SChris Mason 
38215f39d397SChris Mason 	nritems = nritems - mid;
38225f39d397SChris Mason 	btrfs_set_header_nritems(right, nritems);
38235f39d397SChris Mason 	data_copy_size = btrfs_item_end_nr(l, mid) - leaf_data_end(root, l);
38245f39d397SChris Mason 
38255f39d397SChris Mason 	copy_extent_buffer(right, l, btrfs_item_nr_offset(0),
38265f39d397SChris Mason 			   btrfs_item_nr_offset(mid),
38275f39d397SChris Mason 			   nritems * sizeof(struct btrfs_item));
38285f39d397SChris Mason 
38295f39d397SChris Mason 	copy_extent_buffer(right, l,
3830d6025579SChris Mason 		     btrfs_leaf_data(right) + BTRFS_LEAF_DATA_SIZE(root) -
3831123abc88SChris Mason 		     data_copy_size, btrfs_leaf_data(l) +
3832123abc88SChris Mason 		     leaf_data_end(root, l), data_copy_size);
383374123bd7SChris Mason 
38345f39d397SChris Mason 	rt_data_off = BTRFS_LEAF_DATA_SIZE(root) -
38355f39d397SChris Mason 		      btrfs_item_end_nr(l, mid);
38365f39d397SChris Mason 
38375f39d397SChris Mason 	for (i = 0; i < nritems; i++) {
38385f39d397SChris Mason 		struct btrfs_item *item = btrfs_item_nr(right, i);
3839db94535dSChris Mason 		u32 ioff;
3840db94535dSChris Mason 
3841cfed81a0SChris Mason 		ioff = btrfs_token_item_offset(right, item, &token);
3842cfed81a0SChris Mason 		btrfs_set_token_item_offset(right, item,
3843cfed81a0SChris Mason 					    ioff + rt_data_off, &token);
38440783fcfcSChris Mason 	}
384574123bd7SChris Mason 
38465f39d397SChris Mason 	btrfs_set_header_nritems(l, mid);
38475f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
3848143bede5SJeff Mahoney 	insert_ptr(trans, root, path, &disk_key, right->start,
3849c3e06965SJan Schmidt 		   path->slots[1] + 1, 1);
38505f39d397SChris Mason 
38515f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
38525f39d397SChris Mason 	btrfs_mark_buffer_dirty(l);
3853eb60ceacSChris Mason 	BUG_ON(path->slots[0] != slot);
38545f39d397SChris Mason 
3855be0e5c09SChris Mason 	if (mid <= slot) {
3856925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
38575f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
38585f39d397SChris Mason 		path->nodes[0] = right;
3859be0e5c09SChris Mason 		path->slots[0] -= mid;
3860be0e5c09SChris Mason 		path->slots[1] += 1;
3861925baeddSChris Mason 	} else {
3862925baeddSChris Mason 		btrfs_tree_unlock(right);
38635f39d397SChris Mason 		free_extent_buffer(right);
3864925baeddSChris Mason 	}
38655f39d397SChris Mason 
3866eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
386744871b1bSChris Mason }
386844871b1bSChris Mason 
386944871b1bSChris Mason /*
387099d8f83cSChris Mason  * double splits happen when we need to insert a big item in the middle
387199d8f83cSChris Mason  * of a leaf.  A double split can leave us with 3 mostly empty leaves:
387299d8f83cSChris Mason  * leaf: [ slots 0 - N] [ our target ] [ N + 1 - total in leaf ]
387399d8f83cSChris Mason  *          A                 B                 C
387499d8f83cSChris Mason  *
387599d8f83cSChris Mason  * We avoid this by trying to push the items on either side of our target
387699d8f83cSChris Mason  * into the adjacent leaves.  If all goes well we can avoid the double split
387799d8f83cSChris Mason  * completely.
387899d8f83cSChris Mason  */
387999d8f83cSChris Mason static noinline int push_for_double_split(struct btrfs_trans_handle *trans,
388099d8f83cSChris Mason 					  struct btrfs_root *root,
388199d8f83cSChris Mason 					  struct btrfs_path *path,
388299d8f83cSChris Mason 					  int data_size)
388399d8f83cSChris Mason {
388499d8f83cSChris Mason 	int ret;
388599d8f83cSChris Mason 	int progress = 0;
388699d8f83cSChris Mason 	int slot;
388799d8f83cSChris Mason 	u32 nritems;
388899d8f83cSChris Mason 
388999d8f83cSChris Mason 	slot = path->slots[0];
389099d8f83cSChris Mason 
389199d8f83cSChris Mason 	/*
389299d8f83cSChris Mason 	 * try to push all the items after our slot into the
389399d8f83cSChris Mason 	 * right leaf
389499d8f83cSChris Mason 	 */
389599d8f83cSChris Mason 	ret = push_leaf_right(trans, root, path, 1, data_size, 0, slot);
389699d8f83cSChris Mason 	if (ret < 0)
389799d8f83cSChris Mason 		return ret;
389899d8f83cSChris Mason 
389999d8f83cSChris Mason 	if (ret == 0)
390099d8f83cSChris Mason 		progress++;
390199d8f83cSChris Mason 
390299d8f83cSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
390399d8f83cSChris Mason 	/*
390499d8f83cSChris Mason 	 * our goal is to get our slot at the start or end of a leaf.  If
390599d8f83cSChris Mason 	 * we've done so we're done
390699d8f83cSChris Mason 	 */
390799d8f83cSChris Mason 	if (path->slots[0] == 0 || path->slots[0] == nritems)
390899d8f83cSChris Mason 		return 0;
390999d8f83cSChris Mason 
391099d8f83cSChris Mason 	if (btrfs_leaf_free_space(root, path->nodes[0]) >= data_size)
391199d8f83cSChris Mason 		return 0;
391299d8f83cSChris Mason 
391399d8f83cSChris Mason 	/* try to push all the items before our slot into the next leaf */
391499d8f83cSChris Mason 	slot = path->slots[0];
391599d8f83cSChris Mason 	ret = push_leaf_left(trans, root, path, 1, data_size, 0, slot);
391699d8f83cSChris Mason 	if (ret < 0)
391799d8f83cSChris Mason 		return ret;
391899d8f83cSChris Mason 
391999d8f83cSChris Mason 	if (ret == 0)
392099d8f83cSChris Mason 		progress++;
392199d8f83cSChris Mason 
392299d8f83cSChris Mason 	if (progress)
392399d8f83cSChris Mason 		return 0;
392499d8f83cSChris Mason 	return 1;
392599d8f83cSChris Mason }
392699d8f83cSChris Mason 
392799d8f83cSChris Mason /*
392844871b1bSChris Mason  * split the path's leaf in two, making sure there is at least data_size
392944871b1bSChris Mason  * available for the resulting leaf level of the path.
393044871b1bSChris Mason  *
393144871b1bSChris Mason  * returns 0 if all went well and < 0 on failure.
393244871b1bSChris Mason  */
393344871b1bSChris Mason static noinline int split_leaf(struct btrfs_trans_handle *trans,
393444871b1bSChris Mason 			       struct btrfs_root *root,
393544871b1bSChris Mason 			       struct btrfs_key *ins_key,
393644871b1bSChris Mason 			       struct btrfs_path *path, int data_size,
393744871b1bSChris Mason 			       int extend)
393844871b1bSChris Mason {
39395d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
394044871b1bSChris Mason 	struct extent_buffer *l;
394144871b1bSChris Mason 	u32 nritems;
394244871b1bSChris Mason 	int mid;
394344871b1bSChris Mason 	int slot;
394444871b1bSChris Mason 	struct extent_buffer *right;
394544871b1bSChris Mason 	int ret = 0;
394644871b1bSChris Mason 	int wret;
39475d4f98a2SYan Zheng 	int split;
394844871b1bSChris Mason 	int num_doubles = 0;
394999d8f83cSChris Mason 	int tried_avoid_double = 0;
395044871b1bSChris Mason 
3951a5719521SYan, Zheng 	l = path->nodes[0];
3952a5719521SYan, Zheng 	slot = path->slots[0];
3953a5719521SYan, Zheng 	if (extend && data_size + btrfs_item_size_nr(l, slot) +
3954a5719521SYan, Zheng 	    sizeof(struct btrfs_item) > BTRFS_LEAF_DATA_SIZE(root))
3955a5719521SYan, Zheng 		return -EOVERFLOW;
3956a5719521SYan, Zheng 
395744871b1bSChris Mason 	/* first try to make some room by pushing left and right */
395833157e05SLiu Bo 	if (data_size && path->nodes[1]) {
395999d8f83cSChris Mason 		wret = push_leaf_right(trans, root, path, data_size,
396099d8f83cSChris Mason 				       data_size, 0, 0);
396144871b1bSChris Mason 		if (wret < 0)
396244871b1bSChris Mason 			return wret;
396344871b1bSChris Mason 		if (wret) {
396499d8f83cSChris Mason 			wret = push_leaf_left(trans, root, path, data_size,
396599d8f83cSChris Mason 					      data_size, 0, (u32)-1);
396644871b1bSChris Mason 			if (wret < 0)
396744871b1bSChris Mason 				return wret;
396844871b1bSChris Mason 		}
396944871b1bSChris Mason 		l = path->nodes[0];
397044871b1bSChris Mason 
397144871b1bSChris Mason 		/* did the pushes work? */
397244871b1bSChris Mason 		if (btrfs_leaf_free_space(root, l) >= data_size)
397344871b1bSChris Mason 			return 0;
397444871b1bSChris Mason 	}
397544871b1bSChris Mason 
397644871b1bSChris Mason 	if (!path->nodes[1]) {
3977fdd99c72SLiu Bo 		ret = insert_new_root(trans, root, path, 1);
397844871b1bSChris Mason 		if (ret)
397944871b1bSChris Mason 			return ret;
398044871b1bSChris Mason 	}
398144871b1bSChris Mason again:
39825d4f98a2SYan Zheng 	split = 1;
398344871b1bSChris Mason 	l = path->nodes[0];
398444871b1bSChris Mason 	slot = path->slots[0];
398544871b1bSChris Mason 	nritems = btrfs_header_nritems(l);
398644871b1bSChris Mason 	mid = (nritems + 1) / 2;
398744871b1bSChris Mason 
39885d4f98a2SYan Zheng 	if (mid <= slot) {
39895d4f98a2SYan Zheng 		if (nritems == 1 ||
39905d4f98a2SYan Zheng 		    leaf_space_used(l, mid, nritems - mid) + data_size >
39915d4f98a2SYan Zheng 			BTRFS_LEAF_DATA_SIZE(root)) {
39925d4f98a2SYan Zheng 			if (slot >= nritems) {
39935d4f98a2SYan Zheng 				split = 0;
39945d4f98a2SYan Zheng 			} else {
39955d4f98a2SYan Zheng 				mid = slot;
39965d4f98a2SYan Zheng 				if (mid != nritems &&
39975d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
39985d4f98a2SYan Zheng 				    data_size > BTRFS_LEAF_DATA_SIZE(root)) {
399999d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
400099d8f83cSChris Mason 						goto push_for_double;
40015d4f98a2SYan Zheng 					split = 2;
40025d4f98a2SYan Zheng 				}
40035d4f98a2SYan Zheng 			}
40045d4f98a2SYan Zheng 		}
40055d4f98a2SYan Zheng 	} else {
40065d4f98a2SYan Zheng 		if (leaf_space_used(l, 0, mid) + data_size >
40075d4f98a2SYan Zheng 			BTRFS_LEAF_DATA_SIZE(root)) {
40085d4f98a2SYan Zheng 			if (!extend && data_size && slot == 0) {
40095d4f98a2SYan Zheng 				split = 0;
40105d4f98a2SYan Zheng 			} else if ((extend || !data_size) && slot == 0) {
40115d4f98a2SYan Zheng 				mid = 1;
40125d4f98a2SYan Zheng 			} else {
40135d4f98a2SYan Zheng 				mid = slot;
40145d4f98a2SYan Zheng 				if (mid != nritems &&
40155d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
40165d4f98a2SYan Zheng 				    data_size > BTRFS_LEAF_DATA_SIZE(root)) {
401799d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
401899d8f83cSChris Mason 						goto push_for_double;
40195d4f98a2SYan Zheng 					split = 2 ;
40205d4f98a2SYan Zheng 				}
40215d4f98a2SYan Zheng 			}
40225d4f98a2SYan Zheng 		}
40235d4f98a2SYan Zheng 	}
40245d4f98a2SYan Zheng 
40255d4f98a2SYan Zheng 	if (split == 0)
40265d4f98a2SYan Zheng 		btrfs_cpu_key_to_disk(&disk_key, ins_key);
40275d4f98a2SYan Zheng 	else
40285d4f98a2SYan Zheng 		btrfs_item_key(l, &disk_key, mid);
40295d4f98a2SYan Zheng 
40305d4f98a2SYan Zheng 	right = btrfs_alloc_free_block(trans, root, root->leafsize, 0,
403144871b1bSChris Mason 					root->root_key.objectid,
40325581a51aSJan Schmidt 					&disk_key, 0, l->start, 0);
4033f0486c68SYan, Zheng 	if (IS_ERR(right))
403444871b1bSChris Mason 		return PTR_ERR(right);
4035f0486c68SYan, Zheng 
4036f0486c68SYan, Zheng 	root_add_used(root, root->leafsize);
403744871b1bSChris Mason 
403844871b1bSChris Mason 	memset_extent_buffer(right, 0, 0, sizeof(struct btrfs_header));
403944871b1bSChris Mason 	btrfs_set_header_bytenr(right, right->start);
404044871b1bSChris Mason 	btrfs_set_header_generation(right, trans->transid);
40415d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(right, BTRFS_MIXED_BACKREF_REV);
404244871b1bSChris Mason 	btrfs_set_header_owner(right, root->root_key.objectid);
404344871b1bSChris Mason 	btrfs_set_header_level(right, 0);
404444871b1bSChris Mason 	write_extent_buffer(right, root->fs_info->fsid,
4045fba6aa75SGeert Uytterhoeven 			    btrfs_header_fsid(right), BTRFS_FSID_SIZE);
404644871b1bSChris Mason 
404744871b1bSChris Mason 	write_extent_buffer(right, root->fs_info->chunk_tree_uuid,
4048b308bc2fSGeert Uytterhoeven 			    btrfs_header_chunk_tree_uuid(right),
404944871b1bSChris Mason 			    BTRFS_UUID_SIZE);
405044871b1bSChris Mason 
40515d4f98a2SYan Zheng 	if (split == 0) {
405244871b1bSChris Mason 		if (mid <= slot) {
405344871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
4054143bede5SJeff Mahoney 			insert_ptr(trans, root, path, &disk_key, right->start,
4055c3e06965SJan Schmidt 				   path->slots[1] + 1, 1);
405644871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
405744871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
405844871b1bSChris Mason 			path->nodes[0] = right;
405944871b1bSChris Mason 			path->slots[0] = 0;
406044871b1bSChris Mason 			path->slots[1] += 1;
406144871b1bSChris Mason 		} else {
406244871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
4063143bede5SJeff Mahoney 			insert_ptr(trans, root, path, &disk_key, right->start,
4064c3e06965SJan Schmidt 					  path->slots[1], 1);
406544871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
406644871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
406744871b1bSChris Mason 			path->nodes[0] = right;
406844871b1bSChris Mason 			path->slots[0] = 0;
4069143bede5SJeff Mahoney 			if (path->slots[1] == 0)
4070d6a0a126STsutomu Itoh 				fixup_low_keys(root, path, &disk_key, 1);
40715d4f98a2SYan Zheng 		}
407244871b1bSChris Mason 		btrfs_mark_buffer_dirty(right);
407344871b1bSChris Mason 		return ret;
407444871b1bSChris Mason 	}
407544871b1bSChris Mason 
4076143bede5SJeff Mahoney 	copy_for_split(trans, root, path, l, right, slot, mid, nritems);
407744871b1bSChris Mason 
40785d4f98a2SYan Zheng 	if (split == 2) {
4079cc0c5538SChris Mason 		BUG_ON(num_doubles != 0);
4080cc0c5538SChris Mason 		num_doubles++;
4081cc0c5538SChris Mason 		goto again;
40823326d1b0SChris Mason 	}
408344871b1bSChris Mason 
4084143bede5SJeff Mahoney 	return 0;
408599d8f83cSChris Mason 
408699d8f83cSChris Mason push_for_double:
408799d8f83cSChris Mason 	push_for_double_split(trans, root, path, data_size);
408899d8f83cSChris Mason 	tried_avoid_double = 1;
408999d8f83cSChris Mason 	if (btrfs_leaf_free_space(root, path->nodes[0]) >= data_size)
409099d8f83cSChris Mason 		return 0;
409199d8f83cSChris Mason 	goto again;
4092be0e5c09SChris Mason }
4093be0e5c09SChris Mason 
4094ad48fd75SYan, Zheng static noinline int setup_leaf_for_split(struct btrfs_trans_handle *trans,
4095ad48fd75SYan, Zheng 					 struct btrfs_root *root,
4096ad48fd75SYan, Zheng 					 struct btrfs_path *path, int ins_len)
4097ad48fd75SYan, Zheng {
4098ad48fd75SYan, Zheng 	struct btrfs_key key;
4099ad48fd75SYan, Zheng 	struct extent_buffer *leaf;
4100ad48fd75SYan, Zheng 	struct btrfs_file_extent_item *fi;
4101ad48fd75SYan, Zheng 	u64 extent_len = 0;
4102ad48fd75SYan, Zheng 	u32 item_size;
4103ad48fd75SYan, Zheng 	int ret;
4104ad48fd75SYan, Zheng 
4105ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4106ad48fd75SYan, Zheng 	btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4107ad48fd75SYan, Zheng 
4108ad48fd75SYan, Zheng 	BUG_ON(key.type != BTRFS_EXTENT_DATA_KEY &&
4109ad48fd75SYan, Zheng 	       key.type != BTRFS_EXTENT_CSUM_KEY);
4110ad48fd75SYan, Zheng 
4111ad48fd75SYan, Zheng 	if (btrfs_leaf_free_space(root, leaf) >= ins_len)
4112ad48fd75SYan, Zheng 		return 0;
4113ad48fd75SYan, Zheng 
4114ad48fd75SYan, Zheng 	item_size = btrfs_item_size_nr(leaf, path->slots[0]);
4115ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
4116ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
4117ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
4118ad48fd75SYan, Zheng 		extent_len = btrfs_file_extent_num_bytes(leaf, fi);
4119ad48fd75SYan, Zheng 	}
4120b3b4aa74SDavid Sterba 	btrfs_release_path(path);
4121ad48fd75SYan, Zheng 
4122ad48fd75SYan, Zheng 	path->keep_locks = 1;
4123ad48fd75SYan, Zheng 	path->search_for_split = 1;
4124ad48fd75SYan, Zheng 	ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
4125ad48fd75SYan, Zheng 	path->search_for_split = 0;
4126ad48fd75SYan, Zheng 	if (ret < 0)
4127ad48fd75SYan, Zheng 		goto err;
4128ad48fd75SYan, Zheng 
4129ad48fd75SYan, Zheng 	ret = -EAGAIN;
4130ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4131ad48fd75SYan, Zheng 	/* if our item isn't there or got smaller, return now */
4132ad48fd75SYan, Zheng 	if (ret > 0 || item_size != btrfs_item_size_nr(leaf, path->slots[0]))
4133ad48fd75SYan, Zheng 		goto err;
4134ad48fd75SYan, Zheng 
4135109f6aefSChris Mason 	/* the leaf has  changed, it now has room.  return now */
4136109f6aefSChris Mason 	if (btrfs_leaf_free_space(root, path->nodes[0]) >= ins_len)
4137109f6aefSChris Mason 		goto err;
4138109f6aefSChris Mason 
4139ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
4140ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
4141ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
4142ad48fd75SYan, Zheng 		if (extent_len != btrfs_file_extent_num_bytes(leaf, fi))
4143ad48fd75SYan, Zheng 			goto err;
4144ad48fd75SYan, Zheng 	}
4145ad48fd75SYan, Zheng 
4146ad48fd75SYan, Zheng 	btrfs_set_path_blocking(path);
4147ad48fd75SYan, Zheng 	ret = split_leaf(trans, root, &key, path, ins_len, 1);
4148f0486c68SYan, Zheng 	if (ret)
4149f0486c68SYan, Zheng 		goto err;
4150ad48fd75SYan, Zheng 
4151ad48fd75SYan, Zheng 	path->keep_locks = 0;
4152ad48fd75SYan, Zheng 	btrfs_unlock_up_safe(path, 1);
4153ad48fd75SYan, Zheng 	return 0;
4154ad48fd75SYan, Zheng err:
4155ad48fd75SYan, Zheng 	path->keep_locks = 0;
4156ad48fd75SYan, Zheng 	return ret;
4157ad48fd75SYan, Zheng }
4158ad48fd75SYan, Zheng 
4159ad48fd75SYan, Zheng static noinline int split_item(struct btrfs_trans_handle *trans,
4160459931ecSChris Mason 			       struct btrfs_root *root,
4161459931ecSChris Mason 			       struct btrfs_path *path,
4162459931ecSChris Mason 			       struct btrfs_key *new_key,
4163459931ecSChris Mason 			       unsigned long split_offset)
4164459931ecSChris Mason {
4165459931ecSChris Mason 	struct extent_buffer *leaf;
4166459931ecSChris Mason 	struct btrfs_item *item;
4167459931ecSChris Mason 	struct btrfs_item *new_item;
4168459931ecSChris Mason 	int slot;
4169ad48fd75SYan, Zheng 	char *buf;
4170459931ecSChris Mason 	u32 nritems;
4171ad48fd75SYan, Zheng 	u32 item_size;
4172459931ecSChris Mason 	u32 orig_offset;
4173459931ecSChris Mason 	struct btrfs_disk_key disk_key;
4174459931ecSChris Mason 
4175459931ecSChris Mason 	leaf = path->nodes[0];
4176b9473439SChris Mason 	BUG_ON(btrfs_leaf_free_space(root, leaf) < sizeof(struct btrfs_item));
4177b9473439SChris Mason 
4178b4ce94deSChris Mason 	btrfs_set_path_blocking(path);
4179b4ce94deSChris Mason 
4180459931ecSChris Mason 	item = btrfs_item_nr(leaf, path->slots[0]);
4181459931ecSChris Mason 	orig_offset = btrfs_item_offset(leaf, item);
4182459931ecSChris Mason 	item_size = btrfs_item_size(leaf, item);
4183459931ecSChris Mason 
4184459931ecSChris Mason 	buf = kmalloc(item_size, GFP_NOFS);
4185ad48fd75SYan, Zheng 	if (!buf)
4186ad48fd75SYan, Zheng 		return -ENOMEM;
4187ad48fd75SYan, Zheng 
4188459931ecSChris Mason 	read_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf,
4189459931ecSChris Mason 			    path->slots[0]), item_size);
4190ad48fd75SYan, Zheng 
4191459931ecSChris Mason 	slot = path->slots[0] + 1;
4192459931ecSChris Mason 	nritems = btrfs_header_nritems(leaf);
4193459931ecSChris Mason 	if (slot != nritems) {
4194459931ecSChris Mason 		/* shift the items */
4195459931ecSChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + 1),
4196459931ecSChris Mason 				btrfs_item_nr_offset(slot),
4197459931ecSChris Mason 				(nritems - slot) * sizeof(struct btrfs_item));
4198459931ecSChris Mason 	}
4199459931ecSChris Mason 
4200459931ecSChris Mason 	btrfs_cpu_key_to_disk(&disk_key, new_key);
4201459931ecSChris Mason 	btrfs_set_item_key(leaf, &disk_key, slot);
4202459931ecSChris Mason 
4203459931ecSChris Mason 	new_item = btrfs_item_nr(leaf, slot);
4204459931ecSChris Mason 
4205459931ecSChris Mason 	btrfs_set_item_offset(leaf, new_item, orig_offset);
4206459931ecSChris Mason 	btrfs_set_item_size(leaf, new_item, item_size - split_offset);
4207459931ecSChris Mason 
4208459931ecSChris Mason 	btrfs_set_item_offset(leaf, item,
4209459931ecSChris Mason 			      orig_offset + item_size - split_offset);
4210459931ecSChris Mason 	btrfs_set_item_size(leaf, item, split_offset);
4211459931ecSChris Mason 
4212459931ecSChris Mason 	btrfs_set_header_nritems(leaf, nritems + 1);
4213459931ecSChris Mason 
4214459931ecSChris Mason 	/* write the data for the start of the original item */
4215459931ecSChris Mason 	write_extent_buffer(leaf, buf,
4216459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, path->slots[0]),
4217459931ecSChris Mason 			    split_offset);
4218459931ecSChris Mason 
4219459931ecSChris Mason 	/* write the data for the new item */
4220459931ecSChris Mason 	write_extent_buffer(leaf, buf + split_offset,
4221459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, slot),
4222459931ecSChris Mason 			    item_size - split_offset);
4223459931ecSChris Mason 	btrfs_mark_buffer_dirty(leaf);
4224459931ecSChris Mason 
4225ad48fd75SYan, Zheng 	BUG_ON(btrfs_leaf_free_space(root, leaf) < 0);
4226459931ecSChris Mason 	kfree(buf);
4227ad48fd75SYan, Zheng 	return 0;
4228ad48fd75SYan, Zheng }
4229ad48fd75SYan, Zheng 
4230ad48fd75SYan, Zheng /*
4231ad48fd75SYan, Zheng  * This function splits a single item into two items,
4232ad48fd75SYan, Zheng  * giving 'new_key' to the new item and splitting the
4233ad48fd75SYan, Zheng  * old one at split_offset (from the start of the item).
4234ad48fd75SYan, Zheng  *
4235ad48fd75SYan, Zheng  * The path may be released by this operation.  After
4236ad48fd75SYan, Zheng  * the split, the path is pointing to the old item.  The
4237ad48fd75SYan, Zheng  * new item is going to be in the same node as the old one.
4238ad48fd75SYan, Zheng  *
4239ad48fd75SYan, Zheng  * Note, the item being split must be smaller enough to live alone on
4240ad48fd75SYan, Zheng  * a tree block with room for one extra struct btrfs_item
4241ad48fd75SYan, Zheng  *
4242ad48fd75SYan, Zheng  * This allows us to split the item in place, keeping a lock on the
4243ad48fd75SYan, Zheng  * leaf the entire time.
4244ad48fd75SYan, Zheng  */
4245ad48fd75SYan, Zheng int btrfs_split_item(struct btrfs_trans_handle *trans,
4246ad48fd75SYan, Zheng 		     struct btrfs_root *root,
4247ad48fd75SYan, Zheng 		     struct btrfs_path *path,
4248ad48fd75SYan, Zheng 		     struct btrfs_key *new_key,
4249ad48fd75SYan, Zheng 		     unsigned long split_offset)
4250ad48fd75SYan, Zheng {
4251ad48fd75SYan, Zheng 	int ret;
4252ad48fd75SYan, Zheng 	ret = setup_leaf_for_split(trans, root, path,
4253ad48fd75SYan, Zheng 				   sizeof(struct btrfs_item));
4254ad48fd75SYan, Zheng 	if (ret)
4255459931ecSChris Mason 		return ret;
4256ad48fd75SYan, Zheng 
4257ad48fd75SYan, Zheng 	ret = split_item(trans, root, path, new_key, split_offset);
4258ad48fd75SYan, Zheng 	return ret;
4259ad48fd75SYan, Zheng }
4260ad48fd75SYan, Zheng 
4261ad48fd75SYan, Zheng /*
4262ad48fd75SYan, Zheng  * This function duplicate a item, giving 'new_key' to the new item.
4263ad48fd75SYan, Zheng  * It guarantees both items live in the same tree leaf and the new item
4264ad48fd75SYan, Zheng  * is contiguous with the original item.
4265ad48fd75SYan, Zheng  *
4266ad48fd75SYan, Zheng  * This allows us to split file extent in place, keeping a lock on the
4267ad48fd75SYan, Zheng  * leaf the entire time.
4268ad48fd75SYan, Zheng  */
4269ad48fd75SYan, Zheng int btrfs_duplicate_item(struct btrfs_trans_handle *trans,
4270ad48fd75SYan, Zheng 			 struct btrfs_root *root,
4271ad48fd75SYan, Zheng 			 struct btrfs_path *path,
4272ad48fd75SYan, Zheng 			 struct btrfs_key *new_key)
4273ad48fd75SYan, Zheng {
4274ad48fd75SYan, Zheng 	struct extent_buffer *leaf;
4275ad48fd75SYan, Zheng 	int ret;
4276ad48fd75SYan, Zheng 	u32 item_size;
4277ad48fd75SYan, Zheng 
4278ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4279ad48fd75SYan, Zheng 	item_size = btrfs_item_size_nr(leaf, path->slots[0]);
4280ad48fd75SYan, Zheng 	ret = setup_leaf_for_split(trans, root, path,
4281ad48fd75SYan, Zheng 				   item_size + sizeof(struct btrfs_item));
4282ad48fd75SYan, Zheng 	if (ret)
4283ad48fd75SYan, Zheng 		return ret;
4284ad48fd75SYan, Zheng 
4285ad48fd75SYan, Zheng 	path->slots[0]++;
4286afe5fea7STsutomu Itoh 	setup_items_for_insert(root, path, new_key, &item_size,
4287ad48fd75SYan, Zheng 			       item_size, item_size +
4288ad48fd75SYan, Zheng 			       sizeof(struct btrfs_item), 1);
4289ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4290ad48fd75SYan, Zheng 	memcpy_extent_buffer(leaf,
4291ad48fd75SYan, Zheng 			     btrfs_item_ptr_offset(leaf, path->slots[0]),
4292ad48fd75SYan, Zheng 			     btrfs_item_ptr_offset(leaf, path->slots[0] - 1),
4293ad48fd75SYan, Zheng 			     item_size);
4294ad48fd75SYan, Zheng 	return 0;
4295459931ecSChris Mason }
4296459931ecSChris Mason 
4297459931ecSChris Mason /*
4298d352ac68SChris Mason  * make the item pointed to by the path smaller.  new_size indicates
4299d352ac68SChris Mason  * how small to make it, and from_end tells us if we just chop bytes
4300d352ac68SChris Mason  * off the end of the item or if we shift the item to chop bytes off
4301d352ac68SChris Mason  * the front.
4302d352ac68SChris Mason  */
4303afe5fea7STsutomu Itoh void btrfs_truncate_item(struct btrfs_root *root, struct btrfs_path *path,
4304179e29e4SChris Mason 			 u32 new_size, int from_end)
4305b18c6685SChris Mason {
4306b18c6685SChris Mason 	int slot;
43075f39d397SChris Mason 	struct extent_buffer *leaf;
43085f39d397SChris Mason 	struct btrfs_item *item;
4309b18c6685SChris Mason 	u32 nritems;
4310b18c6685SChris Mason 	unsigned int data_end;
4311b18c6685SChris Mason 	unsigned int old_data_start;
4312b18c6685SChris Mason 	unsigned int old_size;
4313b18c6685SChris Mason 	unsigned int size_diff;
4314b18c6685SChris Mason 	int i;
4315cfed81a0SChris Mason 	struct btrfs_map_token token;
4316cfed81a0SChris Mason 
4317cfed81a0SChris Mason 	btrfs_init_map_token(&token);
4318b18c6685SChris Mason 
43195f39d397SChris Mason 	leaf = path->nodes[0];
4320179e29e4SChris Mason 	slot = path->slots[0];
4321179e29e4SChris Mason 
4322179e29e4SChris Mason 	old_size = btrfs_item_size_nr(leaf, slot);
4323179e29e4SChris Mason 	if (old_size == new_size)
4324143bede5SJeff Mahoney 		return;
4325b18c6685SChris Mason 
43265f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
4327b18c6685SChris Mason 	data_end = leaf_data_end(root, leaf);
4328b18c6685SChris Mason 
43295f39d397SChris Mason 	old_data_start = btrfs_item_offset_nr(leaf, slot);
4330179e29e4SChris Mason 
4331b18c6685SChris Mason 	size_diff = old_size - new_size;
4332b18c6685SChris Mason 
4333b18c6685SChris Mason 	BUG_ON(slot < 0);
4334b18c6685SChris Mason 	BUG_ON(slot >= nritems);
4335b18c6685SChris Mason 
4336b18c6685SChris Mason 	/*
4337b18c6685SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4338b18c6685SChris Mason 	 */
4339b18c6685SChris Mason 	/* first correct the data pointers */
4340b18c6685SChris Mason 	for (i = slot; i < nritems; i++) {
43415f39d397SChris Mason 		u32 ioff;
43425f39d397SChris Mason 		item = btrfs_item_nr(leaf, i);
4343db94535dSChris Mason 
4344cfed81a0SChris Mason 		ioff = btrfs_token_item_offset(leaf, item, &token);
4345cfed81a0SChris Mason 		btrfs_set_token_item_offset(leaf, item,
4346cfed81a0SChris Mason 					    ioff + size_diff, &token);
4347b18c6685SChris Mason 	}
4348db94535dSChris Mason 
4349b18c6685SChris Mason 	/* shift the data */
4350179e29e4SChris Mason 	if (from_end) {
43515f39d397SChris Mason 		memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
4352b18c6685SChris Mason 			      data_end + size_diff, btrfs_leaf_data(leaf) +
4353b18c6685SChris Mason 			      data_end, old_data_start + new_size - data_end);
4354179e29e4SChris Mason 	} else {
4355179e29e4SChris Mason 		struct btrfs_disk_key disk_key;
4356179e29e4SChris Mason 		u64 offset;
4357179e29e4SChris Mason 
4358179e29e4SChris Mason 		btrfs_item_key(leaf, &disk_key, slot);
4359179e29e4SChris Mason 
4360179e29e4SChris Mason 		if (btrfs_disk_key_type(&disk_key) == BTRFS_EXTENT_DATA_KEY) {
4361179e29e4SChris Mason 			unsigned long ptr;
4362179e29e4SChris Mason 			struct btrfs_file_extent_item *fi;
4363179e29e4SChris Mason 
4364179e29e4SChris Mason 			fi = btrfs_item_ptr(leaf, slot,
4365179e29e4SChris Mason 					    struct btrfs_file_extent_item);
4366179e29e4SChris Mason 			fi = (struct btrfs_file_extent_item *)(
4367179e29e4SChris Mason 			     (unsigned long)fi - size_diff);
4368179e29e4SChris Mason 
4369179e29e4SChris Mason 			if (btrfs_file_extent_type(leaf, fi) ==
4370179e29e4SChris Mason 			    BTRFS_FILE_EXTENT_INLINE) {
4371179e29e4SChris Mason 				ptr = btrfs_item_ptr_offset(leaf, slot);
4372179e29e4SChris Mason 				memmove_extent_buffer(leaf, ptr,
4373179e29e4SChris Mason 				      (unsigned long)fi,
4374179e29e4SChris Mason 				      offsetof(struct btrfs_file_extent_item,
4375179e29e4SChris Mason 						 disk_bytenr));
4376179e29e4SChris Mason 			}
4377179e29e4SChris Mason 		}
4378179e29e4SChris Mason 
4379179e29e4SChris Mason 		memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
4380179e29e4SChris Mason 			      data_end + size_diff, btrfs_leaf_data(leaf) +
4381179e29e4SChris Mason 			      data_end, old_data_start - data_end);
4382179e29e4SChris Mason 
4383179e29e4SChris Mason 		offset = btrfs_disk_key_offset(&disk_key);
4384179e29e4SChris Mason 		btrfs_set_disk_key_offset(&disk_key, offset + size_diff);
4385179e29e4SChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot);
4386179e29e4SChris Mason 		if (slot == 0)
4387d6a0a126STsutomu Itoh 			fixup_low_keys(root, path, &disk_key, 1);
4388179e29e4SChris Mason 	}
43895f39d397SChris Mason 
43905f39d397SChris Mason 	item = btrfs_item_nr(leaf, slot);
43915f39d397SChris Mason 	btrfs_set_item_size(leaf, item, new_size);
43925f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
4393b18c6685SChris Mason 
43945f39d397SChris Mason 	if (btrfs_leaf_free_space(root, leaf) < 0) {
43955f39d397SChris Mason 		btrfs_print_leaf(root, leaf);
4396b18c6685SChris Mason 		BUG();
43975f39d397SChris Mason 	}
4398b18c6685SChris Mason }
4399b18c6685SChris Mason 
4400d352ac68SChris Mason /*
44018f69dbd2SStefan Behrens  * make the item pointed to by the path bigger, data_size is the added size.
4402d352ac68SChris Mason  */
44034b90c680STsutomu Itoh void btrfs_extend_item(struct btrfs_root *root, struct btrfs_path *path,
44045f39d397SChris Mason 		       u32 data_size)
44056567e837SChris Mason {
44066567e837SChris Mason 	int slot;
44075f39d397SChris Mason 	struct extent_buffer *leaf;
44085f39d397SChris Mason 	struct btrfs_item *item;
44096567e837SChris Mason 	u32 nritems;
44106567e837SChris Mason 	unsigned int data_end;
44116567e837SChris Mason 	unsigned int old_data;
44126567e837SChris Mason 	unsigned int old_size;
44136567e837SChris Mason 	int i;
4414cfed81a0SChris Mason 	struct btrfs_map_token token;
4415cfed81a0SChris Mason 
4416cfed81a0SChris Mason 	btrfs_init_map_token(&token);
44176567e837SChris Mason 
44185f39d397SChris Mason 	leaf = path->nodes[0];
44196567e837SChris Mason 
44205f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
44216567e837SChris Mason 	data_end = leaf_data_end(root, leaf);
44226567e837SChris Mason 
44235f39d397SChris Mason 	if (btrfs_leaf_free_space(root, leaf) < data_size) {
44245f39d397SChris Mason 		btrfs_print_leaf(root, leaf);
44256567e837SChris Mason 		BUG();
44265f39d397SChris Mason 	}
44276567e837SChris Mason 	slot = path->slots[0];
44285f39d397SChris Mason 	old_data = btrfs_item_end_nr(leaf, slot);
44296567e837SChris Mason 
44306567e837SChris Mason 	BUG_ON(slot < 0);
44313326d1b0SChris Mason 	if (slot >= nritems) {
44323326d1b0SChris Mason 		btrfs_print_leaf(root, leaf);
4433d397712bSChris Mason 		printk(KERN_CRIT "slot %d too large, nritems %d\n",
4434d397712bSChris Mason 		       slot, nritems);
44353326d1b0SChris Mason 		BUG_ON(1);
44363326d1b0SChris Mason 	}
44376567e837SChris Mason 
44386567e837SChris Mason 	/*
44396567e837SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
44406567e837SChris Mason 	 */
44416567e837SChris Mason 	/* first correct the data pointers */
44426567e837SChris Mason 	for (i = slot; i < nritems; i++) {
44435f39d397SChris Mason 		u32 ioff;
44445f39d397SChris Mason 		item = btrfs_item_nr(leaf, i);
4445db94535dSChris Mason 
4446cfed81a0SChris Mason 		ioff = btrfs_token_item_offset(leaf, item, &token);
4447cfed81a0SChris Mason 		btrfs_set_token_item_offset(leaf, item,
4448cfed81a0SChris Mason 					    ioff - data_size, &token);
44496567e837SChris Mason 	}
44505f39d397SChris Mason 
44516567e837SChris Mason 	/* shift the data */
44525f39d397SChris Mason 	memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
44536567e837SChris Mason 		      data_end - data_size, btrfs_leaf_data(leaf) +
44546567e837SChris Mason 		      data_end, old_data - data_end);
44555f39d397SChris Mason 
44566567e837SChris Mason 	data_end = old_data;
44575f39d397SChris Mason 	old_size = btrfs_item_size_nr(leaf, slot);
44585f39d397SChris Mason 	item = btrfs_item_nr(leaf, slot);
44595f39d397SChris Mason 	btrfs_set_item_size(leaf, item, old_size + data_size);
44605f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
44616567e837SChris Mason 
44625f39d397SChris Mason 	if (btrfs_leaf_free_space(root, leaf) < 0) {
44635f39d397SChris Mason 		btrfs_print_leaf(root, leaf);
44646567e837SChris Mason 		BUG();
44655f39d397SChris Mason 	}
44666567e837SChris Mason }
44676567e837SChris Mason 
446874123bd7SChris Mason /*
446944871b1bSChris Mason  * this is a helper for btrfs_insert_empty_items, the main goal here is
447044871b1bSChris Mason  * to save stack depth by doing the bulk of the work in a function
447144871b1bSChris Mason  * that doesn't call btrfs_search_slot
447274123bd7SChris Mason  */
4473afe5fea7STsutomu Itoh void setup_items_for_insert(struct btrfs_root *root, struct btrfs_path *path,
44749c58309dSChris Mason 			    struct btrfs_key *cpu_key, u32 *data_size,
447544871b1bSChris Mason 			    u32 total_data, u32 total_size, int nr)
4476be0e5c09SChris Mason {
44775f39d397SChris Mason 	struct btrfs_item *item;
44789c58309dSChris Mason 	int i;
44797518a238SChris Mason 	u32 nritems;
4480be0e5c09SChris Mason 	unsigned int data_end;
4481e2fa7227SChris Mason 	struct btrfs_disk_key disk_key;
448244871b1bSChris Mason 	struct extent_buffer *leaf;
448344871b1bSChris Mason 	int slot;
4484cfed81a0SChris Mason 	struct btrfs_map_token token;
4485cfed81a0SChris Mason 
4486cfed81a0SChris Mason 	btrfs_init_map_token(&token);
4487e2fa7227SChris Mason 
44885f39d397SChris Mason 	leaf = path->nodes[0];
448944871b1bSChris Mason 	slot = path->slots[0];
449074123bd7SChris Mason 
44915f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
4492123abc88SChris Mason 	data_end = leaf_data_end(root, leaf);
4493eb60ceacSChris Mason 
4494f25956ccSChris Mason 	if (btrfs_leaf_free_space(root, leaf) < total_size) {
44953326d1b0SChris Mason 		btrfs_print_leaf(root, leaf);
4496d397712bSChris Mason 		printk(KERN_CRIT "not enough freespace need %u have %d\n",
44979c58309dSChris Mason 		       total_size, btrfs_leaf_free_space(root, leaf));
4498be0e5c09SChris Mason 		BUG();
4499d4dbff95SChris Mason 	}
45005f39d397SChris Mason 
4501be0e5c09SChris Mason 	if (slot != nritems) {
45025f39d397SChris Mason 		unsigned int old_data = btrfs_item_end_nr(leaf, slot);
4503be0e5c09SChris Mason 
45045f39d397SChris Mason 		if (old_data < data_end) {
45055f39d397SChris Mason 			btrfs_print_leaf(root, leaf);
4506d397712bSChris Mason 			printk(KERN_CRIT "slot %d old_data %d data_end %d\n",
45075f39d397SChris Mason 			       slot, old_data, data_end);
45085f39d397SChris Mason 			BUG_ON(1);
45095f39d397SChris Mason 		}
4510be0e5c09SChris Mason 		/*
4511be0e5c09SChris Mason 		 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4512be0e5c09SChris Mason 		 */
4513be0e5c09SChris Mason 		/* first correct the data pointers */
45140783fcfcSChris Mason 		for (i = slot; i < nritems; i++) {
45155f39d397SChris Mason 			u32 ioff;
4516db94535dSChris Mason 
45175f39d397SChris Mason 			item = btrfs_item_nr(leaf, i);
4518cfed81a0SChris Mason 			ioff = btrfs_token_item_offset(leaf, item, &token);
4519cfed81a0SChris Mason 			btrfs_set_token_item_offset(leaf, item,
4520cfed81a0SChris Mason 						    ioff - total_data, &token);
45210783fcfcSChris Mason 		}
4522be0e5c09SChris Mason 		/* shift the items */
45239c58309dSChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + nr),
45245f39d397SChris Mason 			      btrfs_item_nr_offset(slot),
45250783fcfcSChris Mason 			      (nritems - slot) * sizeof(struct btrfs_item));
4526be0e5c09SChris Mason 
4527be0e5c09SChris Mason 		/* shift the data */
45285f39d397SChris Mason 		memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
45299c58309dSChris Mason 			      data_end - total_data, btrfs_leaf_data(leaf) +
4530be0e5c09SChris Mason 			      data_end, old_data - data_end);
4531be0e5c09SChris Mason 		data_end = old_data;
4532be0e5c09SChris Mason 	}
45335f39d397SChris Mason 
453462e2749eSChris Mason 	/* setup the item for the new data */
45359c58309dSChris Mason 	for (i = 0; i < nr; i++) {
45369c58309dSChris Mason 		btrfs_cpu_key_to_disk(&disk_key, cpu_key + i);
45379c58309dSChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot + i);
45389c58309dSChris Mason 		item = btrfs_item_nr(leaf, slot + i);
4539cfed81a0SChris Mason 		btrfs_set_token_item_offset(leaf, item,
4540cfed81a0SChris Mason 					    data_end - data_size[i], &token);
45419c58309dSChris Mason 		data_end -= data_size[i];
4542cfed81a0SChris Mason 		btrfs_set_token_item_size(leaf, item, data_size[i], &token);
45439c58309dSChris Mason 	}
454444871b1bSChris Mason 
45459c58309dSChris Mason 	btrfs_set_header_nritems(leaf, nritems + nr);
4546aa5d6bedSChris Mason 
45475a01a2e3SChris Mason 	if (slot == 0) {
45485a01a2e3SChris Mason 		btrfs_cpu_key_to_disk(&disk_key, cpu_key);
4549d6a0a126STsutomu Itoh 		fixup_low_keys(root, path, &disk_key, 1);
45505a01a2e3SChris Mason 	}
4551b9473439SChris Mason 	btrfs_unlock_up_safe(path, 1);
4552b9473439SChris Mason 	btrfs_mark_buffer_dirty(leaf);
4553aa5d6bedSChris Mason 
45545f39d397SChris Mason 	if (btrfs_leaf_free_space(root, leaf) < 0) {
45555f39d397SChris Mason 		btrfs_print_leaf(root, leaf);
4556be0e5c09SChris Mason 		BUG();
45575f39d397SChris Mason 	}
455844871b1bSChris Mason }
455944871b1bSChris Mason 
456044871b1bSChris Mason /*
456144871b1bSChris Mason  * Given a key and some data, insert items into the tree.
456244871b1bSChris Mason  * This does all the path init required, making room in the tree if needed.
456344871b1bSChris Mason  */
456444871b1bSChris Mason int btrfs_insert_empty_items(struct btrfs_trans_handle *trans,
456544871b1bSChris Mason 			    struct btrfs_root *root,
456644871b1bSChris Mason 			    struct btrfs_path *path,
456744871b1bSChris Mason 			    struct btrfs_key *cpu_key, u32 *data_size,
456844871b1bSChris Mason 			    int nr)
456944871b1bSChris Mason {
457044871b1bSChris Mason 	int ret = 0;
457144871b1bSChris Mason 	int slot;
457244871b1bSChris Mason 	int i;
457344871b1bSChris Mason 	u32 total_size = 0;
457444871b1bSChris Mason 	u32 total_data = 0;
457544871b1bSChris Mason 
457644871b1bSChris Mason 	for (i = 0; i < nr; i++)
457744871b1bSChris Mason 		total_data += data_size[i];
457844871b1bSChris Mason 
457944871b1bSChris Mason 	total_size = total_data + (nr * sizeof(struct btrfs_item));
458044871b1bSChris Mason 	ret = btrfs_search_slot(trans, root, cpu_key, path, total_size, 1);
458144871b1bSChris Mason 	if (ret == 0)
458244871b1bSChris Mason 		return -EEXIST;
458344871b1bSChris Mason 	if (ret < 0)
4584143bede5SJeff Mahoney 		return ret;
458544871b1bSChris Mason 
458644871b1bSChris Mason 	slot = path->slots[0];
458744871b1bSChris Mason 	BUG_ON(slot < 0);
458844871b1bSChris Mason 
4589afe5fea7STsutomu Itoh 	setup_items_for_insert(root, path, cpu_key, data_size,
459044871b1bSChris Mason 			       total_data, total_size, nr);
4591143bede5SJeff Mahoney 	return 0;
459262e2749eSChris Mason }
459362e2749eSChris Mason 
459462e2749eSChris Mason /*
459562e2749eSChris Mason  * Given a key and some data, insert an item into the tree.
459662e2749eSChris Mason  * This does all the path init required, making room in the tree if needed.
459762e2749eSChris Mason  */
4598e089f05cSChris Mason int btrfs_insert_item(struct btrfs_trans_handle *trans, struct btrfs_root
4599e089f05cSChris Mason 		      *root, struct btrfs_key *cpu_key, void *data, u32
4600e089f05cSChris Mason 		      data_size)
460162e2749eSChris Mason {
460262e2749eSChris Mason 	int ret = 0;
46032c90e5d6SChris Mason 	struct btrfs_path *path;
46045f39d397SChris Mason 	struct extent_buffer *leaf;
46055f39d397SChris Mason 	unsigned long ptr;
460662e2749eSChris Mason 
46072c90e5d6SChris Mason 	path = btrfs_alloc_path();
4608db5b493aSTsutomu Itoh 	if (!path)
4609db5b493aSTsutomu Itoh 		return -ENOMEM;
46102c90e5d6SChris Mason 	ret = btrfs_insert_empty_item(trans, root, path, cpu_key, data_size);
461162e2749eSChris Mason 	if (!ret) {
46125f39d397SChris Mason 		leaf = path->nodes[0];
46135f39d397SChris Mason 		ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
46145f39d397SChris Mason 		write_extent_buffer(leaf, data, ptr, data_size);
46155f39d397SChris Mason 		btrfs_mark_buffer_dirty(leaf);
461662e2749eSChris Mason 	}
46172c90e5d6SChris Mason 	btrfs_free_path(path);
4618aa5d6bedSChris Mason 	return ret;
4619be0e5c09SChris Mason }
4620be0e5c09SChris Mason 
462174123bd7SChris Mason /*
46225de08d7dSChris Mason  * delete the pointer from a given node.
462374123bd7SChris Mason  *
4624d352ac68SChris Mason  * the tree should have been previously balanced so the deletion does not
4625d352ac68SChris Mason  * empty a node.
462674123bd7SChris Mason  */
4627afe5fea7STsutomu Itoh static void del_ptr(struct btrfs_root *root, struct btrfs_path *path,
4628afe5fea7STsutomu Itoh 		    int level, int slot)
4629be0e5c09SChris Mason {
46305f39d397SChris Mason 	struct extent_buffer *parent = path->nodes[level];
46317518a238SChris Mason 	u32 nritems;
4632f3ea38daSJan Schmidt 	int ret;
4633be0e5c09SChris Mason 
46345f39d397SChris Mason 	nritems = btrfs_header_nritems(parent);
4635be0e5c09SChris Mason 	if (slot != nritems - 1) {
46360e411eceSLiu Bo 		if (level)
4637f3ea38daSJan Schmidt 			tree_mod_log_eb_move(root->fs_info, parent, slot,
4638f3ea38daSJan Schmidt 					     slot + 1, nritems - slot - 1);
46395f39d397SChris Mason 		memmove_extent_buffer(parent,
46405f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot),
46415f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot + 1),
4642d6025579SChris Mason 			      sizeof(struct btrfs_key_ptr) *
4643d6025579SChris Mason 			      (nritems - slot - 1));
464457ba86c0SChris Mason 	} else if (level) {
464557ba86c0SChris Mason 		ret = tree_mod_log_insert_key(root->fs_info, parent, slot,
4646c8cc6341SJosef Bacik 					      MOD_LOG_KEY_REMOVE, GFP_NOFS);
464757ba86c0SChris Mason 		BUG_ON(ret < 0);
4648be0e5c09SChris Mason 	}
4649f3ea38daSJan Schmidt 
46507518a238SChris Mason 	nritems--;
46515f39d397SChris Mason 	btrfs_set_header_nritems(parent, nritems);
46527518a238SChris Mason 	if (nritems == 0 && parent == root->node) {
46535f39d397SChris Mason 		BUG_ON(btrfs_header_level(root->node) != 1);
4654eb60ceacSChris Mason 		/* just turn the root into a leaf and break */
46555f39d397SChris Mason 		btrfs_set_header_level(root->node, 0);
4656bb803951SChris Mason 	} else if (slot == 0) {
46575f39d397SChris Mason 		struct btrfs_disk_key disk_key;
46585f39d397SChris Mason 
46595f39d397SChris Mason 		btrfs_node_key(parent, &disk_key, 0);
4660d6a0a126STsutomu Itoh 		fixup_low_keys(root, path, &disk_key, level + 1);
4661be0e5c09SChris Mason 	}
4662d6025579SChris Mason 	btrfs_mark_buffer_dirty(parent);
4663be0e5c09SChris Mason }
4664be0e5c09SChris Mason 
466574123bd7SChris Mason /*
4666323ac95bSChris Mason  * a helper function to delete the leaf pointed to by path->slots[1] and
46675d4f98a2SYan Zheng  * path->nodes[1].
4668323ac95bSChris Mason  *
4669323ac95bSChris Mason  * This deletes the pointer in path->nodes[1] and frees the leaf
4670323ac95bSChris Mason  * block extent.  zero is returned if it all worked out, < 0 otherwise.
4671323ac95bSChris Mason  *
4672323ac95bSChris Mason  * The path must have already been setup for deleting the leaf, including
4673323ac95bSChris Mason  * all the proper balancing.  path->nodes[1] must be locked.
4674323ac95bSChris Mason  */
4675143bede5SJeff Mahoney static noinline void btrfs_del_leaf(struct btrfs_trans_handle *trans,
4676323ac95bSChris Mason 				    struct btrfs_root *root,
46775d4f98a2SYan Zheng 				    struct btrfs_path *path,
46785d4f98a2SYan Zheng 				    struct extent_buffer *leaf)
4679323ac95bSChris Mason {
46805d4f98a2SYan Zheng 	WARN_ON(btrfs_header_generation(leaf) != trans->transid);
4681afe5fea7STsutomu Itoh 	del_ptr(root, path, 1, path->slots[1]);
4682323ac95bSChris Mason 
46834d081c41SChris Mason 	/*
46844d081c41SChris Mason 	 * btrfs_free_extent is expensive, we want to make sure we
46854d081c41SChris Mason 	 * aren't holding any locks when we call it
46864d081c41SChris Mason 	 */
46874d081c41SChris Mason 	btrfs_unlock_up_safe(path, 0);
46884d081c41SChris Mason 
4689f0486c68SYan, Zheng 	root_sub_used(root, leaf->len);
4690f0486c68SYan, Zheng 
46913083ee2eSJosef Bacik 	extent_buffer_get(leaf);
46925581a51aSJan Schmidt 	btrfs_free_tree_block(trans, root, leaf, 0, 1);
46933083ee2eSJosef Bacik 	free_extent_buffer_stale(leaf);
4694323ac95bSChris Mason }
4695323ac95bSChris Mason /*
469674123bd7SChris Mason  * delete the item at the leaf level in path.  If that empties
469774123bd7SChris Mason  * the leaf, remove it from the tree
469874123bd7SChris Mason  */
469985e21bacSChris Mason int btrfs_del_items(struct btrfs_trans_handle *trans, struct btrfs_root *root,
470085e21bacSChris Mason 		    struct btrfs_path *path, int slot, int nr)
4701be0e5c09SChris Mason {
47025f39d397SChris Mason 	struct extent_buffer *leaf;
47035f39d397SChris Mason 	struct btrfs_item *item;
470485e21bacSChris Mason 	int last_off;
470585e21bacSChris Mason 	int dsize = 0;
4706aa5d6bedSChris Mason 	int ret = 0;
4707aa5d6bedSChris Mason 	int wret;
470885e21bacSChris Mason 	int i;
47097518a238SChris Mason 	u32 nritems;
4710cfed81a0SChris Mason 	struct btrfs_map_token token;
4711cfed81a0SChris Mason 
4712cfed81a0SChris Mason 	btrfs_init_map_token(&token);
4713be0e5c09SChris Mason 
47145f39d397SChris Mason 	leaf = path->nodes[0];
471585e21bacSChris Mason 	last_off = btrfs_item_offset_nr(leaf, slot + nr - 1);
471685e21bacSChris Mason 
471785e21bacSChris Mason 	for (i = 0; i < nr; i++)
471885e21bacSChris Mason 		dsize += btrfs_item_size_nr(leaf, slot + i);
471985e21bacSChris Mason 
47205f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
4721be0e5c09SChris Mason 
472285e21bacSChris Mason 	if (slot + nr != nritems) {
4723123abc88SChris Mason 		int data_end = leaf_data_end(root, leaf);
47245f39d397SChris Mason 
47255f39d397SChris Mason 		memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
4726d6025579SChris Mason 			      data_end + dsize,
4727123abc88SChris Mason 			      btrfs_leaf_data(leaf) + data_end,
472885e21bacSChris Mason 			      last_off - data_end);
47295f39d397SChris Mason 
473085e21bacSChris Mason 		for (i = slot + nr; i < nritems; i++) {
47315f39d397SChris Mason 			u32 ioff;
4732db94535dSChris Mason 
47335f39d397SChris Mason 			item = btrfs_item_nr(leaf, i);
4734cfed81a0SChris Mason 			ioff = btrfs_token_item_offset(leaf, item, &token);
4735cfed81a0SChris Mason 			btrfs_set_token_item_offset(leaf, item,
4736cfed81a0SChris Mason 						    ioff + dsize, &token);
47370783fcfcSChris Mason 		}
4738db94535dSChris Mason 
47395f39d397SChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot),
474085e21bacSChris Mason 			      btrfs_item_nr_offset(slot + nr),
47410783fcfcSChris Mason 			      sizeof(struct btrfs_item) *
474285e21bacSChris Mason 			      (nritems - slot - nr));
4743be0e5c09SChris Mason 	}
474485e21bacSChris Mason 	btrfs_set_header_nritems(leaf, nritems - nr);
474585e21bacSChris Mason 	nritems -= nr;
47465f39d397SChris Mason 
474774123bd7SChris Mason 	/* delete the leaf if we've emptied it */
47487518a238SChris Mason 	if (nritems == 0) {
47495f39d397SChris Mason 		if (leaf == root->node) {
47505f39d397SChris Mason 			btrfs_set_header_level(leaf, 0);
47519a8dd150SChris Mason 		} else {
4752f0486c68SYan, Zheng 			btrfs_set_path_blocking(path);
4753f0486c68SYan, Zheng 			clean_tree_block(trans, root, leaf);
4754143bede5SJeff Mahoney 			btrfs_del_leaf(trans, root, path, leaf);
47559a8dd150SChris Mason 		}
4756be0e5c09SChris Mason 	} else {
47577518a238SChris Mason 		int used = leaf_space_used(leaf, 0, nritems);
4758aa5d6bedSChris Mason 		if (slot == 0) {
47595f39d397SChris Mason 			struct btrfs_disk_key disk_key;
47605f39d397SChris Mason 
47615f39d397SChris Mason 			btrfs_item_key(leaf, &disk_key, 0);
4762d6a0a126STsutomu Itoh 			fixup_low_keys(root, path, &disk_key, 1);
4763aa5d6bedSChris Mason 		}
4764aa5d6bedSChris Mason 
476574123bd7SChris Mason 		/* delete the leaf if it is mostly empty */
4766d717aa1dSYan Zheng 		if (used < BTRFS_LEAF_DATA_SIZE(root) / 3) {
4767be0e5c09SChris Mason 			/* push_leaf_left fixes the path.
4768be0e5c09SChris Mason 			 * make sure the path still points to our leaf
4769be0e5c09SChris Mason 			 * for possible call to del_ptr below
4770be0e5c09SChris Mason 			 */
47714920c9acSChris Mason 			slot = path->slots[1];
47725f39d397SChris Mason 			extent_buffer_get(leaf);
47735f39d397SChris Mason 
4774b9473439SChris Mason 			btrfs_set_path_blocking(path);
477599d8f83cSChris Mason 			wret = push_leaf_left(trans, root, path, 1, 1,
477699d8f83cSChris Mason 					      1, (u32)-1);
477754aa1f4dSChris Mason 			if (wret < 0 && wret != -ENOSPC)
4778aa5d6bedSChris Mason 				ret = wret;
47795f39d397SChris Mason 
47805f39d397SChris Mason 			if (path->nodes[0] == leaf &&
47815f39d397SChris Mason 			    btrfs_header_nritems(leaf)) {
478299d8f83cSChris Mason 				wret = push_leaf_right(trans, root, path, 1,
478399d8f83cSChris Mason 						       1, 1, 0);
478454aa1f4dSChris Mason 				if (wret < 0 && wret != -ENOSPC)
4785aa5d6bedSChris Mason 					ret = wret;
4786aa5d6bedSChris Mason 			}
47875f39d397SChris Mason 
47885f39d397SChris Mason 			if (btrfs_header_nritems(leaf) == 0) {
4789323ac95bSChris Mason 				path->slots[1] = slot;
4790143bede5SJeff Mahoney 				btrfs_del_leaf(trans, root, path, leaf);
47915f39d397SChris Mason 				free_extent_buffer(leaf);
4792143bede5SJeff Mahoney 				ret = 0;
47935de08d7dSChris Mason 			} else {
4794925baeddSChris Mason 				/* if we're still in the path, make sure
4795925baeddSChris Mason 				 * we're dirty.  Otherwise, one of the
4796925baeddSChris Mason 				 * push_leaf functions must have already
4797925baeddSChris Mason 				 * dirtied this buffer
4798925baeddSChris Mason 				 */
4799925baeddSChris Mason 				if (path->nodes[0] == leaf)
48005f39d397SChris Mason 					btrfs_mark_buffer_dirty(leaf);
48015f39d397SChris Mason 				free_extent_buffer(leaf);
4802be0e5c09SChris Mason 			}
4803d5719762SChris Mason 		} else {
48045f39d397SChris Mason 			btrfs_mark_buffer_dirty(leaf);
4805be0e5c09SChris Mason 		}
48069a8dd150SChris Mason 	}
4807aa5d6bedSChris Mason 	return ret;
48089a8dd150SChris Mason }
48099a8dd150SChris Mason 
481097571fd0SChris Mason /*
4811925baeddSChris Mason  * search the tree again to find a leaf with lesser keys
48127bb86316SChris Mason  * returns 0 if it found something or 1 if there are no lesser leaves.
48137bb86316SChris Mason  * returns < 0 on io errors.
4814d352ac68SChris Mason  *
4815d352ac68SChris Mason  * This may release the path, and so you may lose any locks held at the
4816d352ac68SChris Mason  * time you call it.
48177bb86316SChris Mason  */
481835a3621bSStefan Behrens static int btrfs_prev_leaf(struct btrfs_root *root, struct btrfs_path *path)
48197bb86316SChris Mason {
4820925baeddSChris Mason 	struct btrfs_key key;
4821925baeddSChris Mason 	struct btrfs_disk_key found_key;
4822925baeddSChris Mason 	int ret;
48237bb86316SChris Mason 
4824925baeddSChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, 0);
4825925baeddSChris Mason 
4826925baeddSChris Mason 	if (key.offset > 0)
4827925baeddSChris Mason 		key.offset--;
4828925baeddSChris Mason 	else if (key.type > 0)
4829925baeddSChris Mason 		key.type--;
4830925baeddSChris Mason 	else if (key.objectid > 0)
4831925baeddSChris Mason 		key.objectid--;
4832925baeddSChris Mason 	else
48337bb86316SChris Mason 		return 1;
48347bb86316SChris Mason 
4835b3b4aa74SDavid Sterba 	btrfs_release_path(path);
4836925baeddSChris Mason 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4837925baeddSChris Mason 	if (ret < 0)
4838925baeddSChris Mason 		return ret;
4839925baeddSChris Mason 	btrfs_item_key(path->nodes[0], &found_key, 0);
4840925baeddSChris Mason 	ret = comp_keys(&found_key, &key);
4841925baeddSChris Mason 	if (ret < 0)
48427bb86316SChris Mason 		return 0;
4843925baeddSChris Mason 	return 1;
48447bb86316SChris Mason }
48457bb86316SChris Mason 
48463f157a2fSChris Mason /*
48473f157a2fSChris Mason  * A helper function to walk down the tree starting at min_key, and looking
4848de78b51aSEric Sandeen  * for nodes or leaves that are have a minimum transaction id.
4849de78b51aSEric Sandeen  * This is used by the btree defrag code, and tree logging
48503f157a2fSChris Mason  *
48513f157a2fSChris Mason  * This does not cow, but it does stuff the starting key it finds back
48523f157a2fSChris Mason  * into min_key, so you can call btrfs_search_slot with cow=1 on the
48533f157a2fSChris Mason  * key and get a writable path.
48543f157a2fSChris Mason  *
48553f157a2fSChris Mason  * This does lock as it descends, and path->keep_locks should be set
48563f157a2fSChris Mason  * to 1 by the caller.
48573f157a2fSChris Mason  *
48583f157a2fSChris Mason  * This honors path->lowest_level to prevent descent past a given level
48593f157a2fSChris Mason  * of the tree.
48603f157a2fSChris Mason  *
4861d352ac68SChris Mason  * min_trans indicates the oldest transaction that you are interested
4862d352ac68SChris Mason  * in walking through.  Any nodes or leaves older than min_trans are
4863d352ac68SChris Mason  * skipped over (without reading them).
4864d352ac68SChris Mason  *
48653f157a2fSChris Mason  * returns zero if something useful was found, < 0 on error and 1 if there
48663f157a2fSChris Mason  * was nothing in the tree that matched the search criteria.
48673f157a2fSChris Mason  */
48683f157a2fSChris Mason int btrfs_search_forward(struct btrfs_root *root, struct btrfs_key *min_key,
4869e02119d5SChris Mason 			 struct btrfs_key *max_key,
4870de78b51aSEric Sandeen 			 struct btrfs_path *path,
48713f157a2fSChris Mason 			 u64 min_trans)
48723f157a2fSChris Mason {
48733f157a2fSChris Mason 	struct extent_buffer *cur;
48743f157a2fSChris Mason 	struct btrfs_key found_key;
48753f157a2fSChris Mason 	int slot;
48769652480bSYan 	int sret;
48773f157a2fSChris Mason 	u32 nritems;
48783f157a2fSChris Mason 	int level;
48793f157a2fSChris Mason 	int ret = 1;
48803f157a2fSChris Mason 
4881934d375bSChris Mason 	WARN_ON(!path->keep_locks);
48823f157a2fSChris Mason again:
4883bd681513SChris Mason 	cur = btrfs_read_lock_root_node(root);
48843f157a2fSChris Mason 	level = btrfs_header_level(cur);
4885e02119d5SChris Mason 	WARN_ON(path->nodes[level]);
48863f157a2fSChris Mason 	path->nodes[level] = cur;
4887bd681513SChris Mason 	path->locks[level] = BTRFS_READ_LOCK;
48883f157a2fSChris Mason 
48893f157a2fSChris Mason 	if (btrfs_header_generation(cur) < min_trans) {
48903f157a2fSChris Mason 		ret = 1;
48913f157a2fSChris Mason 		goto out;
48923f157a2fSChris Mason 	}
48933f157a2fSChris Mason 	while (1) {
48943f157a2fSChris Mason 		nritems = btrfs_header_nritems(cur);
48953f157a2fSChris Mason 		level = btrfs_header_level(cur);
48969652480bSYan 		sret = bin_search(cur, min_key, level, &slot);
48973f157a2fSChris Mason 
4898323ac95bSChris Mason 		/* at the lowest level, we're done, setup the path and exit */
4899323ac95bSChris Mason 		if (level == path->lowest_level) {
4900e02119d5SChris Mason 			if (slot >= nritems)
4901e02119d5SChris Mason 				goto find_next_key;
49023f157a2fSChris Mason 			ret = 0;
49033f157a2fSChris Mason 			path->slots[level] = slot;
49043f157a2fSChris Mason 			btrfs_item_key_to_cpu(cur, &found_key, slot);
49053f157a2fSChris Mason 			goto out;
49063f157a2fSChris Mason 		}
49079652480bSYan 		if (sret && slot > 0)
49089652480bSYan 			slot--;
49093f157a2fSChris Mason 		/*
4910de78b51aSEric Sandeen 		 * check this node pointer against the min_trans parameters.
4911de78b51aSEric Sandeen 		 * If it is too old, old, skip to the next one.
49123f157a2fSChris Mason 		 */
49133f157a2fSChris Mason 		while (slot < nritems) {
49143f157a2fSChris Mason 			u64 blockptr;
49153f157a2fSChris Mason 			u64 gen;
4916e02119d5SChris Mason 
49173f157a2fSChris Mason 			blockptr = btrfs_node_blockptr(cur, slot);
49183f157a2fSChris Mason 			gen = btrfs_node_ptr_generation(cur, slot);
49193f157a2fSChris Mason 			if (gen < min_trans) {
49203f157a2fSChris Mason 				slot++;
49213f157a2fSChris Mason 				continue;
49223f157a2fSChris Mason 			}
49233f157a2fSChris Mason 			break;
49243f157a2fSChris Mason 		}
4925e02119d5SChris Mason find_next_key:
49263f157a2fSChris Mason 		/*
49273f157a2fSChris Mason 		 * we didn't find a candidate key in this node, walk forward
49283f157a2fSChris Mason 		 * and find another one
49293f157a2fSChris Mason 		 */
49303f157a2fSChris Mason 		if (slot >= nritems) {
4931e02119d5SChris Mason 			path->slots[level] = slot;
4932b4ce94deSChris Mason 			btrfs_set_path_blocking(path);
4933e02119d5SChris Mason 			sret = btrfs_find_next_key(root, path, min_key, level,
4934de78b51aSEric Sandeen 						  min_trans);
4935e02119d5SChris Mason 			if (sret == 0) {
4936b3b4aa74SDavid Sterba 				btrfs_release_path(path);
49373f157a2fSChris Mason 				goto again;
49383f157a2fSChris Mason 			} else {
49393f157a2fSChris Mason 				goto out;
49403f157a2fSChris Mason 			}
49413f157a2fSChris Mason 		}
49423f157a2fSChris Mason 		/* save our key for returning back */
49433f157a2fSChris Mason 		btrfs_node_key_to_cpu(cur, &found_key, slot);
49443f157a2fSChris Mason 		path->slots[level] = slot;
49453f157a2fSChris Mason 		if (level == path->lowest_level) {
49463f157a2fSChris Mason 			ret = 0;
4947f7c79f30SChris Mason 			unlock_up(path, level, 1, 0, NULL);
49483f157a2fSChris Mason 			goto out;
49493f157a2fSChris Mason 		}
4950b4ce94deSChris Mason 		btrfs_set_path_blocking(path);
49513f157a2fSChris Mason 		cur = read_node_slot(root, cur, slot);
495279787eaaSJeff Mahoney 		BUG_ON(!cur); /* -ENOMEM */
49533f157a2fSChris Mason 
4954bd681513SChris Mason 		btrfs_tree_read_lock(cur);
4955b4ce94deSChris Mason 
4956bd681513SChris Mason 		path->locks[level - 1] = BTRFS_READ_LOCK;
49573f157a2fSChris Mason 		path->nodes[level - 1] = cur;
4958f7c79f30SChris Mason 		unlock_up(path, level, 1, 0, NULL);
4959bd681513SChris Mason 		btrfs_clear_path_blocking(path, NULL, 0);
49603f157a2fSChris Mason 	}
49613f157a2fSChris Mason out:
49623f157a2fSChris Mason 	if (ret == 0)
49633f157a2fSChris Mason 		memcpy(min_key, &found_key, sizeof(found_key));
4964b4ce94deSChris Mason 	btrfs_set_path_blocking(path);
49653f157a2fSChris Mason 	return ret;
49663f157a2fSChris Mason }
49673f157a2fSChris Mason 
49687069830aSAlexander Block static void tree_move_down(struct btrfs_root *root,
49697069830aSAlexander Block 			   struct btrfs_path *path,
49707069830aSAlexander Block 			   int *level, int root_level)
49717069830aSAlexander Block {
497274dd17fbSChris Mason 	BUG_ON(*level == 0);
49737069830aSAlexander Block 	path->nodes[*level - 1] = read_node_slot(root, path->nodes[*level],
49747069830aSAlexander Block 					path->slots[*level]);
49757069830aSAlexander Block 	path->slots[*level - 1] = 0;
49767069830aSAlexander Block 	(*level)--;
49777069830aSAlexander Block }
49787069830aSAlexander Block 
49797069830aSAlexander Block static int tree_move_next_or_upnext(struct btrfs_root *root,
49807069830aSAlexander Block 				    struct btrfs_path *path,
49817069830aSAlexander Block 				    int *level, int root_level)
49827069830aSAlexander Block {
49837069830aSAlexander Block 	int ret = 0;
49847069830aSAlexander Block 	int nritems;
49857069830aSAlexander Block 	nritems = btrfs_header_nritems(path->nodes[*level]);
49867069830aSAlexander Block 
49877069830aSAlexander Block 	path->slots[*level]++;
49887069830aSAlexander Block 
498974dd17fbSChris Mason 	while (path->slots[*level] >= nritems) {
49907069830aSAlexander Block 		if (*level == root_level)
49917069830aSAlexander Block 			return -1;
49927069830aSAlexander Block 
49937069830aSAlexander Block 		/* move upnext */
49947069830aSAlexander Block 		path->slots[*level] = 0;
49957069830aSAlexander Block 		free_extent_buffer(path->nodes[*level]);
49967069830aSAlexander Block 		path->nodes[*level] = NULL;
49977069830aSAlexander Block 		(*level)++;
49987069830aSAlexander Block 		path->slots[*level]++;
49997069830aSAlexander Block 
50007069830aSAlexander Block 		nritems = btrfs_header_nritems(path->nodes[*level]);
50017069830aSAlexander Block 		ret = 1;
50027069830aSAlexander Block 	}
50037069830aSAlexander Block 	return ret;
50047069830aSAlexander Block }
50057069830aSAlexander Block 
50067069830aSAlexander Block /*
50077069830aSAlexander Block  * Returns 1 if it had to move up and next. 0 is returned if it moved only next
50087069830aSAlexander Block  * or down.
50097069830aSAlexander Block  */
50107069830aSAlexander Block static int tree_advance(struct btrfs_root *root,
50117069830aSAlexander Block 			struct btrfs_path *path,
50127069830aSAlexander Block 			int *level, int root_level,
50137069830aSAlexander Block 			int allow_down,
50147069830aSAlexander Block 			struct btrfs_key *key)
50157069830aSAlexander Block {
50167069830aSAlexander Block 	int ret;
50177069830aSAlexander Block 
50187069830aSAlexander Block 	if (*level == 0 || !allow_down) {
50197069830aSAlexander Block 		ret = tree_move_next_or_upnext(root, path, level, root_level);
50207069830aSAlexander Block 	} else {
50217069830aSAlexander Block 		tree_move_down(root, path, level, root_level);
50227069830aSAlexander Block 		ret = 0;
50237069830aSAlexander Block 	}
50247069830aSAlexander Block 	if (ret >= 0) {
50257069830aSAlexander Block 		if (*level == 0)
50267069830aSAlexander Block 			btrfs_item_key_to_cpu(path->nodes[*level], key,
50277069830aSAlexander Block 					path->slots[*level]);
50287069830aSAlexander Block 		else
50297069830aSAlexander Block 			btrfs_node_key_to_cpu(path->nodes[*level], key,
50307069830aSAlexander Block 					path->slots[*level]);
50317069830aSAlexander Block 	}
50327069830aSAlexander Block 	return ret;
50337069830aSAlexander Block }
50347069830aSAlexander Block 
50357069830aSAlexander Block static int tree_compare_item(struct btrfs_root *left_root,
50367069830aSAlexander Block 			     struct btrfs_path *left_path,
50377069830aSAlexander Block 			     struct btrfs_path *right_path,
50387069830aSAlexander Block 			     char *tmp_buf)
50397069830aSAlexander Block {
50407069830aSAlexander Block 	int cmp;
50417069830aSAlexander Block 	int len1, len2;
50427069830aSAlexander Block 	unsigned long off1, off2;
50437069830aSAlexander Block 
50447069830aSAlexander Block 	len1 = btrfs_item_size_nr(left_path->nodes[0], left_path->slots[0]);
50457069830aSAlexander Block 	len2 = btrfs_item_size_nr(right_path->nodes[0], right_path->slots[0]);
50467069830aSAlexander Block 	if (len1 != len2)
50477069830aSAlexander Block 		return 1;
50487069830aSAlexander Block 
50497069830aSAlexander Block 	off1 = btrfs_item_ptr_offset(left_path->nodes[0], left_path->slots[0]);
50507069830aSAlexander Block 	off2 = btrfs_item_ptr_offset(right_path->nodes[0],
50517069830aSAlexander Block 				right_path->slots[0]);
50527069830aSAlexander Block 
50537069830aSAlexander Block 	read_extent_buffer(left_path->nodes[0], tmp_buf, off1, len1);
50547069830aSAlexander Block 
50557069830aSAlexander Block 	cmp = memcmp_extent_buffer(right_path->nodes[0], tmp_buf, off2, len1);
50567069830aSAlexander Block 	if (cmp)
50577069830aSAlexander Block 		return 1;
50587069830aSAlexander Block 	return 0;
50597069830aSAlexander Block }
50607069830aSAlexander Block 
50617069830aSAlexander Block #define ADVANCE 1
50627069830aSAlexander Block #define ADVANCE_ONLY_NEXT -1
50637069830aSAlexander Block 
50647069830aSAlexander Block /*
50657069830aSAlexander Block  * This function compares two trees and calls the provided callback for
50667069830aSAlexander Block  * every changed/new/deleted item it finds.
50677069830aSAlexander Block  * If shared tree blocks are encountered, whole subtrees are skipped, making
50687069830aSAlexander Block  * the compare pretty fast on snapshotted subvolumes.
50697069830aSAlexander Block  *
50707069830aSAlexander Block  * This currently works on commit roots only. As commit roots are read only,
50717069830aSAlexander Block  * we don't do any locking. The commit roots are protected with transactions.
50727069830aSAlexander Block  * Transactions are ended and rejoined when a commit is tried in between.
50737069830aSAlexander Block  *
50747069830aSAlexander Block  * This function checks for modifications done to the trees while comparing.
50757069830aSAlexander Block  * If it detects a change, it aborts immediately.
50767069830aSAlexander Block  */
50777069830aSAlexander Block int btrfs_compare_trees(struct btrfs_root *left_root,
50787069830aSAlexander Block 			struct btrfs_root *right_root,
50797069830aSAlexander Block 			btrfs_changed_cb_t changed_cb, void *ctx)
50807069830aSAlexander Block {
50817069830aSAlexander Block 	int ret;
50827069830aSAlexander Block 	int cmp;
50837069830aSAlexander Block 	struct btrfs_trans_handle *trans = NULL;
50847069830aSAlexander Block 	struct btrfs_path *left_path = NULL;
50857069830aSAlexander Block 	struct btrfs_path *right_path = NULL;
50867069830aSAlexander Block 	struct btrfs_key left_key;
50877069830aSAlexander Block 	struct btrfs_key right_key;
50887069830aSAlexander Block 	char *tmp_buf = NULL;
50897069830aSAlexander Block 	int left_root_level;
50907069830aSAlexander Block 	int right_root_level;
50917069830aSAlexander Block 	int left_level;
50927069830aSAlexander Block 	int right_level;
50937069830aSAlexander Block 	int left_end_reached;
50947069830aSAlexander Block 	int right_end_reached;
50957069830aSAlexander Block 	int advance_left;
50967069830aSAlexander Block 	int advance_right;
50977069830aSAlexander Block 	u64 left_blockptr;
50987069830aSAlexander Block 	u64 right_blockptr;
50997069830aSAlexander Block 	u64 left_start_ctransid;
51007069830aSAlexander Block 	u64 right_start_ctransid;
51017069830aSAlexander Block 	u64 ctransid;
51027069830aSAlexander Block 
51037069830aSAlexander Block 	left_path = btrfs_alloc_path();
51047069830aSAlexander Block 	if (!left_path) {
51057069830aSAlexander Block 		ret = -ENOMEM;
51067069830aSAlexander Block 		goto out;
51077069830aSAlexander Block 	}
51087069830aSAlexander Block 	right_path = btrfs_alloc_path();
51097069830aSAlexander Block 	if (!right_path) {
51107069830aSAlexander Block 		ret = -ENOMEM;
51117069830aSAlexander Block 		goto out;
51127069830aSAlexander Block 	}
51137069830aSAlexander Block 
51147069830aSAlexander Block 	tmp_buf = kmalloc(left_root->leafsize, GFP_NOFS);
51157069830aSAlexander Block 	if (!tmp_buf) {
51167069830aSAlexander Block 		ret = -ENOMEM;
51177069830aSAlexander Block 		goto out;
51187069830aSAlexander Block 	}
51197069830aSAlexander Block 
51207069830aSAlexander Block 	left_path->search_commit_root = 1;
51217069830aSAlexander Block 	left_path->skip_locking = 1;
51227069830aSAlexander Block 	right_path->search_commit_root = 1;
51237069830aSAlexander Block 	right_path->skip_locking = 1;
51247069830aSAlexander Block 
51255f3ab90aSAnand Jain 	spin_lock(&left_root->root_item_lock);
51267069830aSAlexander Block 	left_start_ctransid = btrfs_root_ctransid(&left_root->root_item);
51275f3ab90aSAnand Jain 	spin_unlock(&left_root->root_item_lock);
51287069830aSAlexander Block 
51295f3ab90aSAnand Jain 	spin_lock(&right_root->root_item_lock);
51307069830aSAlexander Block 	right_start_ctransid = btrfs_root_ctransid(&right_root->root_item);
51315f3ab90aSAnand Jain 	spin_unlock(&right_root->root_item_lock);
51327069830aSAlexander Block 
51337069830aSAlexander Block 	trans = btrfs_join_transaction(left_root);
51347069830aSAlexander Block 	if (IS_ERR(trans)) {
51357069830aSAlexander Block 		ret = PTR_ERR(trans);
51367069830aSAlexander Block 		trans = NULL;
51377069830aSAlexander Block 		goto out;
51387069830aSAlexander Block 	}
51397069830aSAlexander Block 
51407069830aSAlexander Block 	/*
51417069830aSAlexander Block 	 * Strategy: Go to the first items of both trees. Then do
51427069830aSAlexander Block 	 *
51437069830aSAlexander Block 	 * If both trees are at level 0
51447069830aSAlexander Block 	 *   Compare keys of current items
51457069830aSAlexander Block 	 *     If left < right treat left item as new, advance left tree
51467069830aSAlexander Block 	 *       and repeat
51477069830aSAlexander Block 	 *     If left > right treat right item as deleted, advance right tree
51487069830aSAlexander Block 	 *       and repeat
51497069830aSAlexander Block 	 *     If left == right do deep compare of items, treat as changed if
51507069830aSAlexander Block 	 *       needed, advance both trees and repeat
51517069830aSAlexander Block 	 * If both trees are at the same level but not at level 0
51527069830aSAlexander Block 	 *   Compare keys of current nodes/leafs
51537069830aSAlexander Block 	 *     If left < right advance left tree and repeat
51547069830aSAlexander Block 	 *     If left > right advance right tree and repeat
51557069830aSAlexander Block 	 *     If left == right compare blockptrs of the next nodes/leafs
51567069830aSAlexander Block 	 *       If they match advance both trees but stay at the same level
51577069830aSAlexander Block 	 *         and repeat
51587069830aSAlexander Block 	 *       If they don't match advance both trees while allowing to go
51597069830aSAlexander Block 	 *         deeper and repeat
51607069830aSAlexander Block 	 * If tree levels are different
51617069830aSAlexander Block 	 *   Advance the tree that needs it and repeat
51627069830aSAlexander Block 	 *
51637069830aSAlexander Block 	 * Advancing a tree means:
51647069830aSAlexander Block 	 *   If we are at level 0, try to go to the next slot. If that's not
51657069830aSAlexander Block 	 *   possible, go one level up and repeat. Stop when we found a level
51667069830aSAlexander Block 	 *   where we could go to the next slot. We may at this point be on a
51677069830aSAlexander Block 	 *   node or a leaf.
51687069830aSAlexander Block 	 *
51697069830aSAlexander Block 	 *   If we are not at level 0 and not on shared tree blocks, go one
51707069830aSAlexander Block 	 *   level deeper.
51717069830aSAlexander Block 	 *
51727069830aSAlexander Block 	 *   If we are not at level 0 and on shared tree blocks, go one slot to
51737069830aSAlexander Block 	 *   the right if possible or go up and right.
51747069830aSAlexander Block 	 */
51757069830aSAlexander Block 
51767069830aSAlexander Block 	left_level = btrfs_header_level(left_root->commit_root);
51777069830aSAlexander Block 	left_root_level = left_level;
51787069830aSAlexander Block 	left_path->nodes[left_level] = left_root->commit_root;
51797069830aSAlexander Block 	extent_buffer_get(left_path->nodes[left_level]);
51807069830aSAlexander Block 
51817069830aSAlexander Block 	right_level = btrfs_header_level(right_root->commit_root);
51827069830aSAlexander Block 	right_root_level = right_level;
51837069830aSAlexander Block 	right_path->nodes[right_level] = right_root->commit_root;
51847069830aSAlexander Block 	extent_buffer_get(right_path->nodes[right_level]);
51857069830aSAlexander Block 
51867069830aSAlexander Block 	if (left_level == 0)
51877069830aSAlexander Block 		btrfs_item_key_to_cpu(left_path->nodes[left_level],
51887069830aSAlexander Block 				&left_key, left_path->slots[left_level]);
51897069830aSAlexander Block 	else
51907069830aSAlexander Block 		btrfs_node_key_to_cpu(left_path->nodes[left_level],
51917069830aSAlexander Block 				&left_key, left_path->slots[left_level]);
51927069830aSAlexander Block 	if (right_level == 0)
51937069830aSAlexander Block 		btrfs_item_key_to_cpu(right_path->nodes[right_level],
51947069830aSAlexander Block 				&right_key, right_path->slots[right_level]);
51957069830aSAlexander Block 	else
51967069830aSAlexander Block 		btrfs_node_key_to_cpu(right_path->nodes[right_level],
51977069830aSAlexander Block 				&right_key, right_path->slots[right_level]);
51987069830aSAlexander Block 
51997069830aSAlexander Block 	left_end_reached = right_end_reached = 0;
52007069830aSAlexander Block 	advance_left = advance_right = 0;
52017069830aSAlexander Block 
52027069830aSAlexander Block 	while (1) {
52037069830aSAlexander Block 		/*
52047069830aSAlexander Block 		 * We need to make sure the transaction does not get committed
52057069830aSAlexander Block 		 * while we do anything on commit roots. This means, we need to
52067069830aSAlexander Block 		 * join and leave transactions for every item that we process.
52077069830aSAlexander Block 		 */
52087069830aSAlexander Block 		if (trans && btrfs_should_end_transaction(trans, left_root)) {
52097069830aSAlexander Block 			btrfs_release_path(left_path);
52107069830aSAlexander Block 			btrfs_release_path(right_path);
52117069830aSAlexander Block 
52127069830aSAlexander Block 			ret = btrfs_end_transaction(trans, left_root);
52137069830aSAlexander Block 			trans = NULL;
52147069830aSAlexander Block 			if (ret < 0)
52157069830aSAlexander Block 				goto out;
52167069830aSAlexander Block 		}
52177069830aSAlexander Block 		/* now rejoin the transaction */
52187069830aSAlexander Block 		if (!trans) {
52197069830aSAlexander Block 			trans = btrfs_join_transaction(left_root);
52207069830aSAlexander Block 			if (IS_ERR(trans)) {
52217069830aSAlexander Block 				ret = PTR_ERR(trans);
52227069830aSAlexander Block 				trans = NULL;
52237069830aSAlexander Block 				goto out;
52247069830aSAlexander Block 			}
52257069830aSAlexander Block 
52265f3ab90aSAnand Jain 			spin_lock(&left_root->root_item_lock);
52277069830aSAlexander Block 			ctransid = btrfs_root_ctransid(&left_root->root_item);
52285f3ab90aSAnand Jain 			spin_unlock(&left_root->root_item_lock);
52297069830aSAlexander Block 			if (ctransid != left_start_ctransid)
52307069830aSAlexander Block 				left_start_ctransid = 0;
52317069830aSAlexander Block 
52325f3ab90aSAnand Jain 			spin_lock(&right_root->root_item_lock);
52337069830aSAlexander Block 			ctransid = btrfs_root_ctransid(&right_root->root_item);
52345f3ab90aSAnand Jain 			spin_unlock(&right_root->root_item_lock);
52357069830aSAlexander Block 			if (ctransid != right_start_ctransid)
52367069830aSAlexander Block 				right_start_ctransid = 0;
52377069830aSAlexander Block 
52387069830aSAlexander Block 			if (!left_start_ctransid || !right_start_ctransid) {
52397069830aSAlexander Block 				WARN(1, KERN_WARNING
52407069830aSAlexander Block 					"btrfs: btrfs_compare_tree detected "
52417069830aSAlexander Block 					"a change in one of the trees while "
52427069830aSAlexander Block 					"iterating. This is probably a "
52437069830aSAlexander Block 					"bug.\n");
52447069830aSAlexander Block 				ret = -EIO;
52457069830aSAlexander Block 				goto out;
52467069830aSAlexander Block 			}
52477069830aSAlexander Block 
52487069830aSAlexander Block 			/*
52497069830aSAlexander Block 			 * the commit root may have changed, so start again
52507069830aSAlexander Block 			 * where we stopped
52517069830aSAlexander Block 			 */
52527069830aSAlexander Block 			left_path->lowest_level = left_level;
52537069830aSAlexander Block 			right_path->lowest_level = right_level;
52547069830aSAlexander Block 			ret = btrfs_search_slot(NULL, left_root,
52557069830aSAlexander Block 					&left_key, left_path, 0, 0);
52567069830aSAlexander Block 			if (ret < 0)
52577069830aSAlexander Block 				goto out;
52587069830aSAlexander Block 			ret = btrfs_search_slot(NULL, right_root,
52597069830aSAlexander Block 					&right_key, right_path, 0, 0);
52607069830aSAlexander Block 			if (ret < 0)
52617069830aSAlexander Block 				goto out;
52627069830aSAlexander Block 		}
52637069830aSAlexander Block 
52647069830aSAlexander Block 		if (advance_left && !left_end_reached) {
52657069830aSAlexander Block 			ret = tree_advance(left_root, left_path, &left_level,
52667069830aSAlexander Block 					left_root_level,
52677069830aSAlexander Block 					advance_left != ADVANCE_ONLY_NEXT,
52687069830aSAlexander Block 					&left_key);
52697069830aSAlexander Block 			if (ret < 0)
52707069830aSAlexander Block 				left_end_reached = ADVANCE;
52717069830aSAlexander Block 			advance_left = 0;
52727069830aSAlexander Block 		}
52737069830aSAlexander Block 		if (advance_right && !right_end_reached) {
52747069830aSAlexander Block 			ret = tree_advance(right_root, right_path, &right_level,
52757069830aSAlexander Block 					right_root_level,
52767069830aSAlexander Block 					advance_right != ADVANCE_ONLY_NEXT,
52777069830aSAlexander Block 					&right_key);
52787069830aSAlexander Block 			if (ret < 0)
52797069830aSAlexander Block 				right_end_reached = ADVANCE;
52807069830aSAlexander Block 			advance_right = 0;
52817069830aSAlexander Block 		}
52827069830aSAlexander Block 
52837069830aSAlexander Block 		if (left_end_reached && right_end_reached) {
52847069830aSAlexander Block 			ret = 0;
52857069830aSAlexander Block 			goto out;
52867069830aSAlexander Block 		} else if (left_end_reached) {
52877069830aSAlexander Block 			if (right_level == 0) {
52887069830aSAlexander Block 				ret = changed_cb(left_root, right_root,
52897069830aSAlexander Block 						left_path, right_path,
52907069830aSAlexander Block 						&right_key,
52917069830aSAlexander Block 						BTRFS_COMPARE_TREE_DELETED,
52927069830aSAlexander Block 						ctx);
52937069830aSAlexander Block 				if (ret < 0)
52947069830aSAlexander Block 					goto out;
52957069830aSAlexander Block 			}
52967069830aSAlexander Block 			advance_right = ADVANCE;
52977069830aSAlexander Block 			continue;
52987069830aSAlexander Block 		} else if (right_end_reached) {
52997069830aSAlexander Block 			if (left_level == 0) {
53007069830aSAlexander Block 				ret = changed_cb(left_root, right_root,
53017069830aSAlexander Block 						left_path, right_path,
53027069830aSAlexander Block 						&left_key,
53037069830aSAlexander Block 						BTRFS_COMPARE_TREE_NEW,
53047069830aSAlexander Block 						ctx);
53057069830aSAlexander Block 				if (ret < 0)
53067069830aSAlexander Block 					goto out;
53077069830aSAlexander Block 			}
53087069830aSAlexander Block 			advance_left = ADVANCE;
53097069830aSAlexander Block 			continue;
53107069830aSAlexander Block 		}
53117069830aSAlexander Block 
53127069830aSAlexander Block 		if (left_level == 0 && right_level == 0) {
53137069830aSAlexander Block 			cmp = btrfs_comp_cpu_keys(&left_key, &right_key);
53147069830aSAlexander Block 			if (cmp < 0) {
53157069830aSAlexander Block 				ret = changed_cb(left_root, right_root,
53167069830aSAlexander Block 						left_path, right_path,
53177069830aSAlexander Block 						&left_key,
53187069830aSAlexander Block 						BTRFS_COMPARE_TREE_NEW,
53197069830aSAlexander Block 						ctx);
53207069830aSAlexander Block 				if (ret < 0)
53217069830aSAlexander Block 					goto out;
53227069830aSAlexander Block 				advance_left = ADVANCE;
53237069830aSAlexander Block 			} else if (cmp > 0) {
53247069830aSAlexander Block 				ret = changed_cb(left_root, right_root,
53257069830aSAlexander Block 						left_path, right_path,
53267069830aSAlexander Block 						&right_key,
53277069830aSAlexander Block 						BTRFS_COMPARE_TREE_DELETED,
53287069830aSAlexander Block 						ctx);
53297069830aSAlexander Block 				if (ret < 0)
53307069830aSAlexander Block 					goto out;
53317069830aSAlexander Block 				advance_right = ADVANCE;
53327069830aSAlexander Block 			} else {
5333ba5e8f2eSJosef Bacik 				enum btrfs_compare_tree_result cmp;
5334ba5e8f2eSJosef Bacik 
533574dd17fbSChris Mason 				WARN_ON(!extent_buffer_uptodate(left_path->nodes[0]));
53367069830aSAlexander Block 				ret = tree_compare_item(left_root, left_path,
53377069830aSAlexander Block 						right_path, tmp_buf);
5338ba5e8f2eSJosef Bacik 				if (ret)
5339ba5e8f2eSJosef Bacik 					cmp = BTRFS_COMPARE_TREE_CHANGED;
5340ba5e8f2eSJosef Bacik 				else
5341ba5e8f2eSJosef Bacik 					cmp = BTRFS_COMPARE_TREE_SAME;
53427069830aSAlexander Block 				ret = changed_cb(left_root, right_root,
53437069830aSAlexander Block 						 left_path, right_path,
5344ba5e8f2eSJosef Bacik 						 &left_key, cmp, ctx);
53457069830aSAlexander Block 				if (ret < 0)
53467069830aSAlexander Block 					goto out;
53477069830aSAlexander Block 				advance_left = ADVANCE;
53487069830aSAlexander Block 				advance_right = ADVANCE;
53497069830aSAlexander Block 			}
53507069830aSAlexander Block 		} else if (left_level == right_level) {
53517069830aSAlexander Block 			cmp = btrfs_comp_cpu_keys(&left_key, &right_key);
53527069830aSAlexander Block 			if (cmp < 0) {
53537069830aSAlexander Block 				advance_left = ADVANCE;
53547069830aSAlexander Block 			} else if (cmp > 0) {
53557069830aSAlexander Block 				advance_right = ADVANCE;
53567069830aSAlexander Block 			} else {
53577069830aSAlexander Block 				left_blockptr = btrfs_node_blockptr(
53587069830aSAlexander Block 						left_path->nodes[left_level],
53597069830aSAlexander Block 						left_path->slots[left_level]);
53607069830aSAlexander Block 				right_blockptr = btrfs_node_blockptr(
53617069830aSAlexander Block 						right_path->nodes[right_level],
53627069830aSAlexander Block 						right_path->slots[right_level]);
53637069830aSAlexander Block 				if (left_blockptr == right_blockptr) {
53647069830aSAlexander Block 					/*
53657069830aSAlexander Block 					 * As we're on a shared block, don't
53667069830aSAlexander Block 					 * allow to go deeper.
53677069830aSAlexander Block 					 */
53687069830aSAlexander Block 					advance_left = ADVANCE_ONLY_NEXT;
53697069830aSAlexander Block 					advance_right = ADVANCE_ONLY_NEXT;
53707069830aSAlexander Block 				} else {
53717069830aSAlexander Block 					advance_left = ADVANCE;
53727069830aSAlexander Block 					advance_right = ADVANCE;
53737069830aSAlexander Block 				}
53747069830aSAlexander Block 			}
53757069830aSAlexander Block 		} else if (left_level < right_level) {
53767069830aSAlexander Block 			advance_right = ADVANCE;
53777069830aSAlexander Block 		} else {
53787069830aSAlexander Block 			advance_left = ADVANCE;
53797069830aSAlexander Block 		}
53807069830aSAlexander Block 	}
53817069830aSAlexander Block 
53827069830aSAlexander Block out:
53837069830aSAlexander Block 	btrfs_free_path(left_path);
53847069830aSAlexander Block 	btrfs_free_path(right_path);
53857069830aSAlexander Block 	kfree(tmp_buf);
53867069830aSAlexander Block 
53877069830aSAlexander Block 	if (trans) {
53887069830aSAlexander Block 		if (!ret)
53897069830aSAlexander Block 			ret = btrfs_end_transaction(trans, left_root);
53907069830aSAlexander Block 		else
53917069830aSAlexander Block 			btrfs_end_transaction(trans, left_root);
53927069830aSAlexander Block 	}
53937069830aSAlexander Block 
53947069830aSAlexander Block 	return ret;
53957069830aSAlexander Block }
53967069830aSAlexander Block 
53973f157a2fSChris Mason /*
53983f157a2fSChris Mason  * this is similar to btrfs_next_leaf, but does not try to preserve
53993f157a2fSChris Mason  * and fixup the path.  It looks for and returns the next key in the
5400de78b51aSEric Sandeen  * tree based on the current path and the min_trans parameters.
54013f157a2fSChris Mason  *
54023f157a2fSChris Mason  * 0 is returned if another key is found, < 0 if there are any errors
54033f157a2fSChris Mason  * and 1 is returned if there are no higher keys in the tree
54043f157a2fSChris Mason  *
54053f157a2fSChris Mason  * path->keep_locks should be set to 1 on the search made before
54063f157a2fSChris Mason  * calling this function.
54073f157a2fSChris Mason  */
5408e7a84565SChris Mason int btrfs_find_next_key(struct btrfs_root *root, struct btrfs_path *path,
5409de78b51aSEric Sandeen 			struct btrfs_key *key, int level, u64 min_trans)
5410e7a84565SChris Mason {
5411e7a84565SChris Mason 	int slot;
5412e7a84565SChris Mason 	struct extent_buffer *c;
5413e7a84565SChris Mason 
5414934d375bSChris Mason 	WARN_ON(!path->keep_locks);
5415e7a84565SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
5416e7a84565SChris Mason 		if (!path->nodes[level])
5417e7a84565SChris Mason 			return 1;
5418e7a84565SChris Mason 
5419e7a84565SChris Mason 		slot = path->slots[level] + 1;
5420e7a84565SChris Mason 		c = path->nodes[level];
54213f157a2fSChris Mason next:
5422e7a84565SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
542333c66f43SYan Zheng 			int ret;
542433c66f43SYan Zheng 			int orig_lowest;
542533c66f43SYan Zheng 			struct btrfs_key cur_key;
542633c66f43SYan Zheng 			if (level + 1 >= BTRFS_MAX_LEVEL ||
542733c66f43SYan Zheng 			    !path->nodes[level + 1])
5428e7a84565SChris Mason 				return 1;
542933c66f43SYan Zheng 
543033c66f43SYan Zheng 			if (path->locks[level + 1]) {
543133c66f43SYan Zheng 				level++;
5432e7a84565SChris Mason 				continue;
5433e7a84565SChris Mason 			}
543433c66f43SYan Zheng 
543533c66f43SYan Zheng 			slot = btrfs_header_nritems(c) - 1;
543633c66f43SYan Zheng 			if (level == 0)
543733c66f43SYan Zheng 				btrfs_item_key_to_cpu(c, &cur_key, slot);
543833c66f43SYan Zheng 			else
543933c66f43SYan Zheng 				btrfs_node_key_to_cpu(c, &cur_key, slot);
544033c66f43SYan Zheng 
544133c66f43SYan Zheng 			orig_lowest = path->lowest_level;
5442b3b4aa74SDavid Sterba 			btrfs_release_path(path);
544333c66f43SYan Zheng 			path->lowest_level = level;
544433c66f43SYan Zheng 			ret = btrfs_search_slot(NULL, root, &cur_key, path,
544533c66f43SYan Zheng 						0, 0);
544633c66f43SYan Zheng 			path->lowest_level = orig_lowest;
544733c66f43SYan Zheng 			if (ret < 0)
544833c66f43SYan Zheng 				return ret;
544933c66f43SYan Zheng 
545033c66f43SYan Zheng 			c = path->nodes[level];
545133c66f43SYan Zheng 			slot = path->slots[level];
545233c66f43SYan Zheng 			if (ret == 0)
545333c66f43SYan Zheng 				slot++;
545433c66f43SYan Zheng 			goto next;
545533c66f43SYan Zheng 		}
545633c66f43SYan Zheng 
5457e7a84565SChris Mason 		if (level == 0)
5458e7a84565SChris Mason 			btrfs_item_key_to_cpu(c, key, slot);
54593f157a2fSChris Mason 		else {
54603f157a2fSChris Mason 			u64 gen = btrfs_node_ptr_generation(c, slot);
54613f157a2fSChris Mason 
54623f157a2fSChris Mason 			if (gen < min_trans) {
54633f157a2fSChris Mason 				slot++;
54643f157a2fSChris Mason 				goto next;
54653f157a2fSChris Mason 			}
5466e7a84565SChris Mason 			btrfs_node_key_to_cpu(c, key, slot);
54673f157a2fSChris Mason 		}
5468e7a84565SChris Mason 		return 0;
5469e7a84565SChris Mason 	}
5470e7a84565SChris Mason 	return 1;
5471e7a84565SChris Mason }
5472e7a84565SChris Mason 
54737bb86316SChris Mason /*
5474925baeddSChris Mason  * search the tree again to find a leaf with greater keys
54750f70abe2SChris Mason  * returns 0 if it found something or 1 if there are no greater leaves.
54760f70abe2SChris Mason  * returns < 0 on io errors.
547797571fd0SChris Mason  */
5478234b63a0SChris Mason int btrfs_next_leaf(struct btrfs_root *root, struct btrfs_path *path)
5479d97e63b6SChris Mason {
54803d7806ecSJan Schmidt 	return btrfs_next_old_leaf(root, path, 0);
54813d7806ecSJan Schmidt }
54823d7806ecSJan Schmidt 
54833d7806ecSJan Schmidt int btrfs_next_old_leaf(struct btrfs_root *root, struct btrfs_path *path,
54843d7806ecSJan Schmidt 			u64 time_seq)
54853d7806ecSJan Schmidt {
5486d97e63b6SChris Mason 	int slot;
54878e73f275SChris Mason 	int level;
54885f39d397SChris Mason 	struct extent_buffer *c;
54898e73f275SChris Mason 	struct extent_buffer *next;
5490925baeddSChris Mason 	struct btrfs_key key;
5491925baeddSChris Mason 	u32 nritems;
5492925baeddSChris Mason 	int ret;
54938e73f275SChris Mason 	int old_spinning = path->leave_spinning;
5494bd681513SChris Mason 	int next_rw_lock = 0;
5495925baeddSChris Mason 
5496925baeddSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
5497d397712bSChris Mason 	if (nritems == 0)
5498925baeddSChris Mason 		return 1;
5499925baeddSChris Mason 
55008e73f275SChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, nritems - 1);
55018e73f275SChris Mason again:
55028e73f275SChris Mason 	level = 1;
55038e73f275SChris Mason 	next = NULL;
5504bd681513SChris Mason 	next_rw_lock = 0;
5505b3b4aa74SDavid Sterba 	btrfs_release_path(path);
55068e73f275SChris Mason 
5507a2135011SChris Mason 	path->keep_locks = 1;
55088e73f275SChris Mason 	path->leave_spinning = 1;
55098e73f275SChris Mason 
55103d7806ecSJan Schmidt 	if (time_seq)
55113d7806ecSJan Schmidt 		ret = btrfs_search_old_slot(root, &key, path, time_seq);
55123d7806ecSJan Schmidt 	else
5513925baeddSChris Mason 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5514925baeddSChris Mason 	path->keep_locks = 0;
5515925baeddSChris Mason 
5516925baeddSChris Mason 	if (ret < 0)
5517925baeddSChris Mason 		return ret;
5518925baeddSChris Mason 
5519a2135011SChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
5520168fd7d2SChris Mason 	/*
5521168fd7d2SChris Mason 	 * by releasing the path above we dropped all our locks.  A balance
5522168fd7d2SChris Mason 	 * could have added more items next to the key that used to be
5523168fd7d2SChris Mason 	 * at the very end of the block.  So, check again here and
5524168fd7d2SChris Mason 	 * advance the path if there are now more items available.
5525168fd7d2SChris Mason 	 */
5526a2135011SChris Mason 	if (nritems > 0 && path->slots[0] < nritems - 1) {
5527e457afecSYan Zheng 		if (ret == 0)
5528168fd7d2SChris Mason 			path->slots[0]++;
55298e73f275SChris Mason 		ret = 0;
5530925baeddSChris Mason 		goto done;
5531925baeddSChris Mason 	}
5532d97e63b6SChris Mason 
5533234b63a0SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
55348e73f275SChris Mason 		if (!path->nodes[level]) {
55358e73f275SChris Mason 			ret = 1;
55368e73f275SChris Mason 			goto done;
55378e73f275SChris Mason 		}
55385f39d397SChris Mason 
5539d97e63b6SChris Mason 		slot = path->slots[level] + 1;
5540d97e63b6SChris Mason 		c = path->nodes[level];
55415f39d397SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
5542d97e63b6SChris Mason 			level++;
55438e73f275SChris Mason 			if (level == BTRFS_MAX_LEVEL) {
55448e73f275SChris Mason 				ret = 1;
55458e73f275SChris Mason 				goto done;
55468e73f275SChris Mason 			}
5547d97e63b6SChris Mason 			continue;
5548d97e63b6SChris Mason 		}
55495f39d397SChris Mason 
5550925baeddSChris Mason 		if (next) {
5551bd681513SChris Mason 			btrfs_tree_unlock_rw(next, next_rw_lock);
55525f39d397SChris Mason 			free_extent_buffer(next);
5553925baeddSChris Mason 		}
55545f39d397SChris Mason 
55558e73f275SChris Mason 		next = c;
5556bd681513SChris Mason 		next_rw_lock = path->locks[level];
55578e73f275SChris Mason 		ret = read_block_for_search(NULL, root, path, &next, level,
55585d9e75c4SJan Schmidt 					    slot, &key, 0);
55598e73f275SChris Mason 		if (ret == -EAGAIN)
55608e73f275SChris Mason 			goto again;
55615f39d397SChris Mason 
556276a05b35SChris Mason 		if (ret < 0) {
5563b3b4aa74SDavid Sterba 			btrfs_release_path(path);
556476a05b35SChris Mason 			goto done;
556576a05b35SChris Mason 		}
556676a05b35SChris Mason 
55675cd57b2cSChris Mason 		if (!path->skip_locking) {
5568bd681513SChris Mason 			ret = btrfs_try_tree_read_lock(next);
5569d42244a0SJan Schmidt 			if (!ret && time_seq) {
5570d42244a0SJan Schmidt 				/*
5571d42244a0SJan Schmidt 				 * If we don't get the lock, we may be racing
5572d42244a0SJan Schmidt 				 * with push_leaf_left, holding that lock while
5573d42244a0SJan Schmidt 				 * itself waiting for the leaf we've currently
5574d42244a0SJan Schmidt 				 * locked. To solve this situation, we give up
5575d42244a0SJan Schmidt 				 * on our lock and cycle.
5576d42244a0SJan Schmidt 				 */
5577cf538830SJan Schmidt 				free_extent_buffer(next);
5578d42244a0SJan Schmidt 				btrfs_release_path(path);
5579d42244a0SJan Schmidt 				cond_resched();
5580d42244a0SJan Schmidt 				goto again;
5581d42244a0SJan Schmidt 			}
55828e73f275SChris Mason 			if (!ret) {
55838e73f275SChris Mason 				btrfs_set_path_blocking(path);
5584bd681513SChris Mason 				btrfs_tree_read_lock(next);
5585bd681513SChris Mason 				btrfs_clear_path_blocking(path, next,
5586bd681513SChris Mason 							  BTRFS_READ_LOCK);
55878e73f275SChris Mason 			}
5588bd681513SChris Mason 			next_rw_lock = BTRFS_READ_LOCK;
5589bd681513SChris Mason 		}
5590d97e63b6SChris Mason 		break;
5591d97e63b6SChris Mason 	}
5592d97e63b6SChris Mason 	path->slots[level] = slot;
5593d97e63b6SChris Mason 	while (1) {
5594d97e63b6SChris Mason 		level--;
5595d97e63b6SChris Mason 		c = path->nodes[level];
5596925baeddSChris Mason 		if (path->locks[level])
5597bd681513SChris Mason 			btrfs_tree_unlock_rw(c, path->locks[level]);
55988e73f275SChris Mason 
55995f39d397SChris Mason 		free_extent_buffer(c);
5600d97e63b6SChris Mason 		path->nodes[level] = next;
5601d97e63b6SChris Mason 		path->slots[level] = 0;
5602a74a4b97SChris Mason 		if (!path->skip_locking)
5603bd681513SChris Mason 			path->locks[level] = next_rw_lock;
5604d97e63b6SChris Mason 		if (!level)
5605d97e63b6SChris Mason 			break;
5606b4ce94deSChris Mason 
56078e73f275SChris Mason 		ret = read_block_for_search(NULL, root, path, &next, level,
56085d9e75c4SJan Schmidt 					    0, &key, 0);
56098e73f275SChris Mason 		if (ret == -EAGAIN)
56108e73f275SChris Mason 			goto again;
56118e73f275SChris Mason 
561276a05b35SChris Mason 		if (ret < 0) {
5613b3b4aa74SDavid Sterba 			btrfs_release_path(path);
561476a05b35SChris Mason 			goto done;
561576a05b35SChris Mason 		}
561676a05b35SChris Mason 
56175cd57b2cSChris Mason 		if (!path->skip_locking) {
5618bd681513SChris Mason 			ret = btrfs_try_tree_read_lock(next);
56198e73f275SChris Mason 			if (!ret) {
56208e73f275SChris Mason 				btrfs_set_path_blocking(path);
5621bd681513SChris Mason 				btrfs_tree_read_lock(next);
5622bd681513SChris Mason 				btrfs_clear_path_blocking(path, next,
5623bd681513SChris Mason 							  BTRFS_READ_LOCK);
56248e73f275SChris Mason 			}
5625bd681513SChris Mason 			next_rw_lock = BTRFS_READ_LOCK;
5626bd681513SChris Mason 		}
5627d97e63b6SChris Mason 	}
56288e73f275SChris Mason 	ret = 0;
5629925baeddSChris Mason done:
5630f7c79f30SChris Mason 	unlock_up(path, 0, 1, 0, NULL);
56318e73f275SChris Mason 	path->leave_spinning = old_spinning;
56328e73f275SChris Mason 	if (!old_spinning)
56338e73f275SChris Mason 		btrfs_set_path_blocking(path);
56348e73f275SChris Mason 
56358e73f275SChris Mason 	return ret;
5636d97e63b6SChris Mason }
56370b86a832SChris Mason 
56383f157a2fSChris Mason /*
56393f157a2fSChris Mason  * this uses btrfs_prev_leaf to walk backwards in the tree, and keeps
56403f157a2fSChris Mason  * searching until it gets past min_objectid or finds an item of 'type'
56413f157a2fSChris Mason  *
56423f157a2fSChris Mason  * returns 0 if something is found, 1 if nothing was found and < 0 on error
56433f157a2fSChris Mason  */
56440b86a832SChris Mason int btrfs_previous_item(struct btrfs_root *root,
56450b86a832SChris Mason 			struct btrfs_path *path, u64 min_objectid,
56460b86a832SChris Mason 			int type)
56470b86a832SChris Mason {
56480b86a832SChris Mason 	struct btrfs_key found_key;
56490b86a832SChris Mason 	struct extent_buffer *leaf;
5650e02119d5SChris Mason 	u32 nritems;
56510b86a832SChris Mason 	int ret;
56520b86a832SChris Mason 
56530b86a832SChris Mason 	while (1) {
56540b86a832SChris Mason 		if (path->slots[0] == 0) {
5655b4ce94deSChris Mason 			btrfs_set_path_blocking(path);
56560b86a832SChris Mason 			ret = btrfs_prev_leaf(root, path);
56570b86a832SChris Mason 			if (ret != 0)
56580b86a832SChris Mason 				return ret;
56590b86a832SChris Mason 		} else {
56600b86a832SChris Mason 			path->slots[0]--;
56610b86a832SChris Mason 		}
56620b86a832SChris Mason 		leaf = path->nodes[0];
5663e02119d5SChris Mason 		nritems = btrfs_header_nritems(leaf);
5664e02119d5SChris Mason 		if (nritems == 0)
5665e02119d5SChris Mason 			return 1;
5666e02119d5SChris Mason 		if (path->slots[0] == nritems)
5667e02119d5SChris Mason 			path->slots[0]--;
5668e02119d5SChris Mason 
56690b86a832SChris Mason 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5670e02119d5SChris Mason 		if (found_key.objectid < min_objectid)
5671e02119d5SChris Mason 			break;
56720a4eefbbSYan Zheng 		if (found_key.type == type)
56730a4eefbbSYan Zheng 			return 0;
5674e02119d5SChris Mason 		if (found_key.objectid == min_objectid &&
5675e02119d5SChris Mason 		    found_key.type < type)
5676e02119d5SChris Mason 			break;
56770b86a832SChris Mason 	}
56780b86a832SChris Mason 	return 1;
56790b86a832SChris Mason }
5680