xref: /openbmc/linux/fs/btrfs/ctree.c (revision bcd24dabe080a627333fb058fdfe760dc579edf1)
16cbd5570SChris Mason /*
2d352ac68SChris Mason  * Copyright (C) 2007,2008 Oracle.  All rights reserved.
36cbd5570SChris Mason  *
46cbd5570SChris Mason  * This program is free software; you can redistribute it and/or
56cbd5570SChris Mason  * modify it under the terms of the GNU General Public
66cbd5570SChris Mason  * License v2 as published by the Free Software Foundation.
76cbd5570SChris Mason  *
86cbd5570SChris Mason  * This program is distributed in the hope that it will be useful,
96cbd5570SChris Mason  * but WITHOUT ANY WARRANTY; without even the implied warranty of
106cbd5570SChris Mason  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
116cbd5570SChris Mason  * General Public License for more details.
126cbd5570SChris Mason  *
136cbd5570SChris Mason  * You should have received a copy of the GNU General Public
146cbd5570SChris Mason  * License along with this program; if not, write to the
156cbd5570SChris Mason  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
166cbd5570SChris Mason  * Boston, MA 021110-1307, USA.
176cbd5570SChris Mason  */
186cbd5570SChris Mason 
19a6b6e75eSChris Mason #include <linux/sched.h>
205a0e3ad6STejun Heo #include <linux/slab.h>
21bd989ba3SJan Schmidt #include <linux/rbtree.h>
22adf02123SDavid Sterba #include <linux/mm.h>
23eb60ceacSChris Mason #include "ctree.h"
24eb60ceacSChris Mason #include "disk-io.h"
257f5c1516SChris Mason #include "transaction.h"
265f39d397SChris Mason #include "print-tree.h"
27925baeddSChris Mason #include "locking.h"
289a8dd150SChris Mason 
29e089f05cSChris Mason static int split_node(struct btrfs_trans_handle *trans, struct btrfs_root
30e089f05cSChris Mason 		      *root, struct btrfs_path *path, int level);
31310712b2SOmar Sandoval static int split_leaf(struct btrfs_trans_handle *trans, struct btrfs_root *root,
32310712b2SOmar Sandoval 		      const struct btrfs_key *ins_key, struct btrfs_path *path,
33310712b2SOmar Sandoval 		      int data_size, int extend);
345f39d397SChris Mason static int push_node_left(struct btrfs_trans_handle *trans,
352ff7e61eSJeff Mahoney 			  struct btrfs_fs_info *fs_info,
362ff7e61eSJeff Mahoney 			  struct extent_buffer *dst,
37971a1f66SChris Mason 			  struct extent_buffer *src, int empty);
385f39d397SChris Mason static int balance_node_right(struct btrfs_trans_handle *trans,
392ff7e61eSJeff Mahoney 			      struct btrfs_fs_info *fs_info,
405f39d397SChris Mason 			      struct extent_buffer *dst_buf,
415f39d397SChris Mason 			      struct extent_buffer *src_buf);
42afe5fea7STsutomu Itoh static void del_ptr(struct btrfs_root *root, struct btrfs_path *path,
43afe5fea7STsutomu Itoh 		    int level, int slot);
44d97e63b6SChris Mason 
452c90e5d6SChris Mason struct btrfs_path *btrfs_alloc_path(void)
462c90e5d6SChris Mason {
47e2c89907SMasahiro Yamada 	return kmem_cache_zalloc(btrfs_path_cachep, GFP_NOFS);
482c90e5d6SChris Mason }
492c90e5d6SChris Mason 
50b4ce94deSChris Mason /*
51b4ce94deSChris Mason  * set all locked nodes in the path to blocking locks.  This should
52b4ce94deSChris Mason  * be done before scheduling
53b4ce94deSChris Mason  */
54b4ce94deSChris Mason noinline void btrfs_set_path_blocking(struct btrfs_path *p)
55b4ce94deSChris Mason {
56b4ce94deSChris Mason 	int i;
57b4ce94deSChris Mason 	for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
58bd681513SChris Mason 		if (!p->nodes[i] || !p->locks[i])
59bd681513SChris Mason 			continue;
60bd681513SChris Mason 		btrfs_set_lock_blocking_rw(p->nodes[i], p->locks[i]);
61bd681513SChris Mason 		if (p->locks[i] == BTRFS_READ_LOCK)
62bd681513SChris Mason 			p->locks[i] = BTRFS_READ_LOCK_BLOCKING;
63bd681513SChris Mason 		else if (p->locks[i] == BTRFS_WRITE_LOCK)
64bd681513SChris Mason 			p->locks[i] = BTRFS_WRITE_LOCK_BLOCKING;
65b4ce94deSChris Mason 	}
66b4ce94deSChris Mason }
67b4ce94deSChris Mason 
68b4ce94deSChris Mason /*
69b4ce94deSChris Mason  * reset all the locked nodes in the patch to spinning locks.
704008c04aSChris Mason  *
714008c04aSChris Mason  * held is used to keep lockdep happy, when lockdep is enabled
724008c04aSChris Mason  * we set held to a blocking lock before we go around and
734008c04aSChris Mason  * retake all the spinlocks in the path.  You can safely use NULL
744008c04aSChris Mason  * for held
75b4ce94deSChris Mason  */
764008c04aSChris Mason noinline void btrfs_clear_path_blocking(struct btrfs_path *p,
77bd681513SChris Mason 					struct extent_buffer *held, int held_rw)
78b4ce94deSChris Mason {
79b4ce94deSChris Mason 	int i;
804008c04aSChris Mason 
81bd681513SChris Mason 	if (held) {
82bd681513SChris Mason 		btrfs_set_lock_blocking_rw(held, held_rw);
83bd681513SChris Mason 		if (held_rw == BTRFS_WRITE_LOCK)
84bd681513SChris Mason 			held_rw = BTRFS_WRITE_LOCK_BLOCKING;
85bd681513SChris Mason 		else if (held_rw == BTRFS_READ_LOCK)
86bd681513SChris Mason 			held_rw = BTRFS_READ_LOCK_BLOCKING;
87bd681513SChris Mason 	}
884008c04aSChris Mason 	btrfs_set_path_blocking(p);
894008c04aSChris Mason 
904008c04aSChris Mason 	for (i = BTRFS_MAX_LEVEL - 1; i >= 0; i--) {
91bd681513SChris Mason 		if (p->nodes[i] && p->locks[i]) {
92bd681513SChris Mason 			btrfs_clear_lock_blocking_rw(p->nodes[i], p->locks[i]);
93bd681513SChris Mason 			if (p->locks[i] == BTRFS_WRITE_LOCK_BLOCKING)
94bd681513SChris Mason 				p->locks[i] = BTRFS_WRITE_LOCK;
95bd681513SChris Mason 			else if (p->locks[i] == BTRFS_READ_LOCK_BLOCKING)
96bd681513SChris Mason 				p->locks[i] = BTRFS_READ_LOCK;
97bd681513SChris Mason 		}
98b4ce94deSChris Mason 	}
994008c04aSChris Mason 
1004008c04aSChris Mason 	if (held)
101bd681513SChris Mason 		btrfs_clear_lock_blocking_rw(held, held_rw);
102b4ce94deSChris Mason }
103b4ce94deSChris Mason 
104d352ac68SChris Mason /* this also releases the path */
1052c90e5d6SChris Mason void btrfs_free_path(struct btrfs_path *p)
1062c90e5d6SChris Mason {
107ff175d57SJesper Juhl 	if (!p)
108ff175d57SJesper Juhl 		return;
109b3b4aa74SDavid Sterba 	btrfs_release_path(p);
1102c90e5d6SChris Mason 	kmem_cache_free(btrfs_path_cachep, p);
1112c90e5d6SChris Mason }
1122c90e5d6SChris Mason 
113d352ac68SChris Mason /*
114d352ac68SChris Mason  * path release drops references on the extent buffers in the path
115d352ac68SChris Mason  * and it drops any locks held by this path
116d352ac68SChris Mason  *
117d352ac68SChris Mason  * It is safe to call this on paths that no locks or extent buffers held.
118d352ac68SChris Mason  */
119b3b4aa74SDavid Sterba noinline void btrfs_release_path(struct btrfs_path *p)
120eb60ceacSChris Mason {
121eb60ceacSChris Mason 	int i;
122a2135011SChris Mason 
123234b63a0SChris Mason 	for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
1243f157a2fSChris Mason 		p->slots[i] = 0;
125eb60ceacSChris Mason 		if (!p->nodes[i])
126925baeddSChris Mason 			continue;
127925baeddSChris Mason 		if (p->locks[i]) {
128bd681513SChris Mason 			btrfs_tree_unlock_rw(p->nodes[i], p->locks[i]);
129925baeddSChris Mason 			p->locks[i] = 0;
130925baeddSChris Mason 		}
1315f39d397SChris Mason 		free_extent_buffer(p->nodes[i]);
1323f157a2fSChris Mason 		p->nodes[i] = NULL;
133eb60ceacSChris Mason 	}
134eb60ceacSChris Mason }
135eb60ceacSChris Mason 
136d352ac68SChris Mason /*
137d352ac68SChris Mason  * safely gets a reference on the root node of a tree.  A lock
138d352ac68SChris Mason  * is not taken, so a concurrent writer may put a different node
139d352ac68SChris Mason  * at the root of the tree.  See btrfs_lock_root_node for the
140d352ac68SChris Mason  * looping required.
141d352ac68SChris Mason  *
142d352ac68SChris Mason  * The extent buffer returned by this has a reference taken, so
143d352ac68SChris Mason  * it won't disappear.  It may stop being the root of the tree
144d352ac68SChris Mason  * at any time because there are no locks held.
145d352ac68SChris Mason  */
146925baeddSChris Mason struct extent_buffer *btrfs_root_node(struct btrfs_root *root)
147925baeddSChris Mason {
148925baeddSChris Mason 	struct extent_buffer *eb;
149240f62c8SChris Mason 
1503083ee2eSJosef Bacik 	while (1) {
151240f62c8SChris Mason 		rcu_read_lock();
152240f62c8SChris Mason 		eb = rcu_dereference(root->node);
1533083ee2eSJosef Bacik 
1543083ee2eSJosef Bacik 		/*
1553083ee2eSJosef Bacik 		 * RCU really hurts here, we could free up the root node because
15601327610SNicholas D Steeves 		 * it was COWed but we may not get the new root node yet so do
1573083ee2eSJosef Bacik 		 * the inc_not_zero dance and if it doesn't work then
1583083ee2eSJosef Bacik 		 * synchronize_rcu and try again.
1593083ee2eSJosef Bacik 		 */
1603083ee2eSJosef Bacik 		if (atomic_inc_not_zero(&eb->refs)) {
161240f62c8SChris Mason 			rcu_read_unlock();
1623083ee2eSJosef Bacik 			break;
1633083ee2eSJosef Bacik 		}
1643083ee2eSJosef Bacik 		rcu_read_unlock();
1653083ee2eSJosef Bacik 		synchronize_rcu();
1663083ee2eSJosef Bacik 	}
167925baeddSChris Mason 	return eb;
168925baeddSChris Mason }
169925baeddSChris Mason 
170d352ac68SChris Mason /* loop around taking references on and locking the root node of the
171d352ac68SChris Mason  * tree until you end up with a lock on the root.  A locked buffer
172d352ac68SChris Mason  * is returned, with a reference held.
173d352ac68SChris Mason  */
174925baeddSChris Mason struct extent_buffer *btrfs_lock_root_node(struct btrfs_root *root)
175925baeddSChris Mason {
176925baeddSChris Mason 	struct extent_buffer *eb;
177925baeddSChris Mason 
178925baeddSChris Mason 	while (1) {
179925baeddSChris Mason 		eb = btrfs_root_node(root);
180925baeddSChris Mason 		btrfs_tree_lock(eb);
181240f62c8SChris Mason 		if (eb == root->node)
182925baeddSChris Mason 			break;
183925baeddSChris Mason 		btrfs_tree_unlock(eb);
184925baeddSChris Mason 		free_extent_buffer(eb);
185925baeddSChris Mason 	}
186925baeddSChris Mason 	return eb;
187925baeddSChris Mason }
188925baeddSChris Mason 
189bd681513SChris Mason /* loop around taking references on and locking the root node of the
190bd681513SChris Mason  * tree until you end up with a lock on the root.  A locked buffer
191bd681513SChris Mason  * is returned, with a reference held.
192bd681513SChris Mason  */
19384f7d8e6SJosef Bacik struct extent_buffer *btrfs_read_lock_root_node(struct btrfs_root *root)
194bd681513SChris Mason {
195bd681513SChris Mason 	struct extent_buffer *eb;
196bd681513SChris Mason 
197bd681513SChris Mason 	while (1) {
198bd681513SChris Mason 		eb = btrfs_root_node(root);
199bd681513SChris Mason 		btrfs_tree_read_lock(eb);
200bd681513SChris Mason 		if (eb == root->node)
201bd681513SChris Mason 			break;
202bd681513SChris Mason 		btrfs_tree_read_unlock(eb);
203bd681513SChris Mason 		free_extent_buffer(eb);
204bd681513SChris Mason 	}
205bd681513SChris Mason 	return eb;
206bd681513SChris Mason }
207bd681513SChris Mason 
208d352ac68SChris Mason /* cowonly root (everything not a reference counted cow subvolume), just get
209d352ac68SChris Mason  * put onto a simple dirty list.  transaction.c walks this to make sure they
210d352ac68SChris Mason  * get properly updated on disk.
211d352ac68SChris Mason  */
2120b86a832SChris Mason static void add_root_to_dirty_list(struct btrfs_root *root)
2130b86a832SChris Mason {
2140b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
2150b246afaSJeff Mahoney 
216e7070be1SJosef Bacik 	if (test_bit(BTRFS_ROOT_DIRTY, &root->state) ||
217e7070be1SJosef Bacik 	    !test_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state))
218e7070be1SJosef Bacik 		return;
219e7070be1SJosef Bacik 
2200b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
221e7070be1SJosef Bacik 	if (!test_and_set_bit(BTRFS_ROOT_DIRTY, &root->state)) {
222e7070be1SJosef Bacik 		/* Want the extent tree to be the last on the list */
223e7070be1SJosef Bacik 		if (root->objectid == BTRFS_EXTENT_TREE_OBJECTID)
224e7070be1SJosef Bacik 			list_move_tail(&root->dirty_list,
2250b246afaSJeff Mahoney 				       &fs_info->dirty_cowonly_roots);
226e7070be1SJosef Bacik 		else
227e7070be1SJosef Bacik 			list_move(&root->dirty_list,
2280b246afaSJeff Mahoney 				  &fs_info->dirty_cowonly_roots);
2290b86a832SChris Mason 	}
2300b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
2310b86a832SChris Mason }
2320b86a832SChris Mason 
233d352ac68SChris Mason /*
234d352ac68SChris Mason  * used by snapshot creation to make a copy of a root for a tree with
235d352ac68SChris Mason  * a given objectid.  The buffer with the new root node is returned in
236d352ac68SChris Mason  * cow_ret, and this func returns zero on success or a negative error code.
237d352ac68SChris Mason  */
238be20aa9dSChris Mason int btrfs_copy_root(struct btrfs_trans_handle *trans,
239be20aa9dSChris Mason 		      struct btrfs_root *root,
240be20aa9dSChris Mason 		      struct extent_buffer *buf,
241be20aa9dSChris Mason 		      struct extent_buffer **cow_ret, u64 new_root_objectid)
242be20aa9dSChris Mason {
2430b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
244be20aa9dSChris Mason 	struct extent_buffer *cow;
245be20aa9dSChris Mason 	int ret = 0;
246be20aa9dSChris Mason 	int level;
2475d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
248be20aa9dSChris Mason 
24927cdeb70SMiao Xie 	WARN_ON(test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
2500b246afaSJeff Mahoney 		trans->transid != fs_info->running_transaction->transid);
25127cdeb70SMiao Xie 	WARN_ON(test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
25227cdeb70SMiao Xie 		trans->transid != root->last_trans);
253be20aa9dSChris Mason 
254be20aa9dSChris Mason 	level = btrfs_header_level(buf);
2555d4f98a2SYan Zheng 	if (level == 0)
2565d4f98a2SYan Zheng 		btrfs_item_key(buf, &disk_key, 0);
2575d4f98a2SYan Zheng 	else
2585d4f98a2SYan Zheng 		btrfs_node_key(buf, &disk_key, 0);
25931840ae1SZheng Yan 
2604d75f8a9SDavid Sterba 	cow = btrfs_alloc_tree_block(trans, root, 0, new_root_objectid,
2614d75f8a9SDavid Sterba 			&disk_key, level, buf->start, 0);
2625d4f98a2SYan Zheng 	if (IS_ERR(cow))
263be20aa9dSChris Mason 		return PTR_ERR(cow);
264be20aa9dSChris Mason 
26558e8012cSDavid Sterba 	copy_extent_buffer_full(cow, buf);
266be20aa9dSChris Mason 	btrfs_set_header_bytenr(cow, cow->start);
267be20aa9dSChris Mason 	btrfs_set_header_generation(cow, trans->transid);
2685d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
2695d4f98a2SYan Zheng 	btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
2705d4f98a2SYan Zheng 				     BTRFS_HEADER_FLAG_RELOC);
2715d4f98a2SYan Zheng 	if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
2725d4f98a2SYan Zheng 		btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
2735d4f98a2SYan Zheng 	else
274be20aa9dSChris Mason 		btrfs_set_header_owner(cow, new_root_objectid);
275be20aa9dSChris Mason 
2760b246afaSJeff Mahoney 	write_extent_buffer_fsid(cow, fs_info->fsid);
2772b82032cSYan Zheng 
278be20aa9dSChris Mason 	WARN_ON(btrfs_header_generation(buf) > trans->transid);
2795d4f98a2SYan Zheng 	if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
280e339a6b0SJosef Bacik 		ret = btrfs_inc_ref(trans, root, cow, 1);
2815d4f98a2SYan Zheng 	else
282e339a6b0SJosef Bacik 		ret = btrfs_inc_ref(trans, root, cow, 0);
2834aec2b52SChris Mason 
284be20aa9dSChris Mason 	if (ret)
285be20aa9dSChris Mason 		return ret;
286be20aa9dSChris Mason 
287be20aa9dSChris Mason 	btrfs_mark_buffer_dirty(cow);
288be20aa9dSChris Mason 	*cow_ret = cow;
289be20aa9dSChris Mason 	return 0;
290be20aa9dSChris Mason }
291be20aa9dSChris Mason 
292bd989ba3SJan Schmidt enum mod_log_op {
293bd989ba3SJan Schmidt 	MOD_LOG_KEY_REPLACE,
294bd989ba3SJan Schmidt 	MOD_LOG_KEY_ADD,
295bd989ba3SJan Schmidt 	MOD_LOG_KEY_REMOVE,
296bd989ba3SJan Schmidt 	MOD_LOG_KEY_REMOVE_WHILE_FREEING,
297bd989ba3SJan Schmidt 	MOD_LOG_KEY_REMOVE_WHILE_MOVING,
298bd989ba3SJan Schmidt 	MOD_LOG_MOVE_KEYS,
299bd989ba3SJan Schmidt 	MOD_LOG_ROOT_REPLACE,
300bd989ba3SJan Schmidt };
301bd989ba3SJan Schmidt 
302bd989ba3SJan Schmidt struct tree_mod_root {
303bd989ba3SJan Schmidt 	u64 logical;
304bd989ba3SJan Schmidt 	u8 level;
305bd989ba3SJan Schmidt };
306bd989ba3SJan Schmidt 
307bd989ba3SJan Schmidt struct tree_mod_elem {
308bd989ba3SJan Schmidt 	struct rb_node node;
309298cfd36SChandan Rajendra 	u64 logical;
310097b8a7cSJan Schmidt 	u64 seq;
311bd989ba3SJan Schmidt 	enum mod_log_op op;
312bd989ba3SJan Schmidt 
313bd989ba3SJan Schmidt 	/* this is used for MOD_LOG_KEY_* and MOD_LOG_MOVE_KEYS operations */
314bd989ba3SJan Schmidt 	int slot;
315bd989ba3SJan Schmidt 
316bd989ba3SJan Schmidt 	/* this is used for MOD_LOG_KEY* and MOD_LOG_ROOT_REPLACE */
317bd989ba3SJan Schmidt 	u64 generation;
318bd989ba3SJan Schmidt 
319bd989ba3SJan Schmidt 	/* those are used for op == MOD_LOG_KEY_{REPLACE,REMOVE} */
320bd989ba3SJan Schmidt 	struct btrfs_disk_key key;
321bd989ba3SJan Schmidt 	u64 blockptr;
322bd989ba3SJan Schmidt 
323bd989ba3SJan Schmidt 	/* this is used for op == MOD_LOG_MOVE_KEYS */
324b6dfa35bSDavid Sterba 	struct {
325b6dfa35bSDavid Sterba 		int dst_slot;
326b6dfa35bSDavid Sterba 		int nr_items;
327b6dfa35bSDavid Sterba 	} move;
328bd989ba3SJan Schmidt 
329bd989ba3SJan Schmidt 	/* this is used for op == MOD_LOG_ROOT_REPLACE */
330bd989ba3SJan Schmidt 	struct tree_mod_root old_root;
331bd989ba3SJan Schmidt };
332bd989ba3SJan Schmidt 
333097b8a7cSJan Schmidt static inline void tree_mod_log_read_lock(struct btrfs_fs_info *fs_info)
334bd989ba3SJan Schmidt {
335097b8a7cSJan Schmidt 	read_lock(&fs_info->tree_mod_log_lock);
336bd989ba3SJan Schmidt }
337bd989ba3SJan Schmidt 
338097b8a7cSJan Schmidt static inline void tree_mod_log_read_unlock(struct btrfs_fs_info *fs_info)
339097b8a7cSJan Schmidt {
340097b8a7cSJan Schmidt 	read_unlock(&fs_info->tree_mod_log_lock);
341097b8a7cSJan Schmidt }
342097b8a7cSJan Schmidt 
343097b8a7cSJan Schmidt static inline void tree_mod_log_write_lock(struct btrfs_fs_info *fs_info)
344097b8a7cSJan Schmidt {
345097b8a7cSJan Schmidt 	write_lock(&fs_info->tree_mod_log_lock);
346097b8a7cSJan Schmidt }
347097b8a7cSJan Schmidt 
348097b8a7cSJan Schmidt static inline void tree_mod_log_write_unlock(struct btrfs_fs_info *fs_info)
349097b8a7cSJan Schmidt {
350097b8a7cSJan Schmidt 	write_unlock(&fs_info->tree_mod_log_lock);
351097b8a7cSJan Schmidt }
352097b8a7cSJan Schmidt 
353097b8a7cSJan Schmidt /*
354fcebe456SJosef Bacik  * Pull a new tree mod seq number for our operation.
355fc36ed7eSJan Schmidt  */
356fcebe456SJosef Bacik static inline u64 btrfs_inc_tree_mod_seq(struct btrfs_fs_info *fs_info)
357fc36ed7eSJan Schmidt {
358fc36ed7eSJan Schmidt 	return atomic64_inc_return(&fs_info->tree_mod_seq);
359fc36ed7eSJan Schmidt }
360fc36ed7eSJan Schmidt 
361fc36ed7eSJan Schmidt /*
362097b8a7cSJan Schmidt  * This adds a new blocker to the tree mod log's blocker list if the @elem
363097b8a7cSJan Schmidt  * passed does not already have a sequence number set. So when a caller expects
364097b8a7cSJan Schmidt  * to record tree modifications, it should ensure to set elem->seq to zero
365097b8a7cSJan Schmidt  * before calling btrfs_get_tree_mod_seq.
366097b8a7cSJan Schmidt  * Returns a fresh, unused tree log modification sequence number, even if no new
367097b8a7cSJan Schmidt  * blocker was added.
368097b8a7cSJan Schmidt  */
369097b8a7cSJan Schmidt u64 btrfs_get_tree_mod_seq(struct btrfs_fs_info *fs_info,
370bd989ba3SJan Schmidt 			   struct seq_list *elem)
371bd989ba3SJan Schmidt {
372097b8a7cSJan Schmidt 	tree_mod_log_write_lock(fs_info);
373bd989ba3SJan Schmidt 	spin_lock(&fs_info->tree_mod_seq_lock);
374097b8a7cSJan Schmidt 	if (!elem->seq) {
375fcebe456SJosef Bacik 		elem->seq = btrfs_inc_tree_mod_seq(fs_info);
376097b8a7cSJan Schmidt 		list_add_tail(&elem->list, &fs_info->tree_mod_seq_list);
377097b8a7cSJan Schmidt 	}
378bd989ba3SJan Schmidt 	spin_unlock(&fs_info->tree_mod_seq_lock);
379097b8a7cSJan Schmidt 	tree_mod_log_write_unlock(fs_info);
380097b8a7cSJan Schmidt 
381fcebe456SJosef Bacik 	return elem->seq;
382bd989ba3SJan Schmidt }
383bd989ba3SJan Schmidt 
384bd989ba3SJan Schmidt void btrfs_put_tree_mod_seq(struct btrfs_fs_info *fs_info,
385bd989ba3SJan Schmidt 			    struct seq_list *elem)
386bd989ba3SJan Schmidt {
387bd989ba3SJan Schmidt 	struct rb_root *tm_root;
388bd989ba3SJan Schmidt 	struct rb_node *node;
389bd989ba3SJan Schmidt 	struct rb_node *next;
390bd989ba3SJan Schmidt 	struct seq_list *cur_elem;
391bd989ba3SJan Schmidt 	struct tree_mod_elem *tm;
392bd989ba3SJan Schmidt 	u64 min_seq = (u64)-1;
393bd989ba3SJan Schmidt 	u64 seq_putting = elem->seq;
394bd989ba3SJan Schmidt 
395bd989ba3SJan Schmidt 	if (!seq_putting)
396bd989ba3SJan Schmidt 		return;
397bd989ba3SJan Schmidt 
398bd989ba3SJan Schmidt 	spin_lock(&fs_info->tree_mod_seq_lock);
399bd989ba3SJan Schmidt 	list_del(&elem->list);
400097b8a7cSJan Schmidt 	elem->seq = 0;
401bd989ba3SJan Schmidt 
402bd989ba3SJan Schmidt 	list_for_each_entry(cur_elem, &fs_info->tree_mod_seq_list, list) {
403097b8a7cSJan Schmidt 		if (cur_elem->seq < min_seq) {
404bd989ba3SJan Schmidt 			if (seq_putting > cur_elem->seq) {
405bd989ba3SJan Schmidt 				/*
406bd989ba3SJan Schmidt 				 * blocker with lower sequence number exists, we
407bd989ba3SJan Schmidt 				 * cannot remove anything from the log
408bd989ba3SJan Schmidt 				 */
409097b8a7cSJan Schmidt 				spin_unlock(&fs_info->tree_mod_seq_lock);
410097b8a7cSJan Schmidt 				return;
411bd989ba3SJan Schmidt 			}
412bd989ba3SJan Schmidt 			min_seq = cur_elem->seq;
413bd989ba3SJan Schmidt 		}
414bd989ba3SJan Schmidt 	}
415097b8a7cSJan Schmidt 	spin_unlock(&fs_info->tree_mod_seq_lock);
416097b8a7cSJan Schmidt 
417097b8a7cSJan Schmidt 	/*
418bd989ba3SJan Schmidt 	 * anything that's lower than the lowest existing (read: blocked)
419bd989ba3SJan Schmidt 	 * sequence number can be removed from the tree.
420bd989ba3SJan Schmidt 	 */
421097b8a7cSJan Schmidt 	tree_mod_log_write_lock(fs_info);
422bd989ba3SJan Schmidt 	tm_root = &fs_info->tree_mod_log;
423bd989ba3SJan Schmidt 	for (node = rb_first(tm_root); node; node = next) {
424bd989ba3SJan Schmidt 		next = rb_next(node);
4256b4df8b6SGeliang Tang 		tm = rb_entry(node, struct tree_mod_elem, node);
426097b8a7cSJan Schmidt 		if (tm->seq > min_seq)
427bd989ba3SJan Schmidt 			continue;
428bd989ba3SJan Schmidt 		rb_erase(node, tm_root);
429bd989ba3SJan Schmidt 		kfree(tm);
430bd989ba3SJan Schmidt 	}
431097b8a7cSJan Schmidt 	tree_mod_log_write_unlock(fs_info);
432bd989ba3SJan Schmidt }
433bd989ba3SJan Schmidt 
434bd989ba3SJan Schmidt /*
435bd989ba3SJan Schmidt  * key order of the log:
436298cfd36SChandan Rajendra  *       node/leaf start address -> sequence
437bd989ba3SJan Schmidt  *
438298cfd36SChandan Rajendra  * The 'start address' is the logical address of the *new* root node
439298cfd36SChandan Rajendra  * for root replace operations, or the logical address of the affected
440298cfd36SChandan Rajendra  * block for all other operations.
4415de865eeSFilipe David Borba Manana  *
4425de865eeSFilipe David Borba Manana  * Note: must be called with write lock (tree_mod_log_write_lock).
443bd989ba3SJan Schmidt  */
444bd989ba3SJan Schmidt static noinline int
445bd989ba3SJan Schmidt __tree_mod_log_insert(struct btrfs_fs_info *fs_info, struct tree_mod_elem *tm)
446bd989ba3SJan Schmidt {
447bd989ba3SJan Schmidt 	struct rb_root *tm_root;
448bd989ba3SJan Schmidt 	struct rb_node **new;
449bd989ba3SJan Schmidt 	struct rb_node *parent = NULL;
450bd989ba3SJan Schmidt 	struct tree_mod_elem *cur;
451bd989ba3SJan Schmidt 
452fcebe456SJosef Bacik 	tm->seq = btrfs_inc_tree_mod_seq(fs_info);
453bd989ba3SJan Schmidt 
454bd989ba3SJan Schmidt 	tm_root = &fs_info->tree_mod_log;
455bd989ba3SJan Schmidt 	new = &tm_root->rb_node;
456bd989ba3SJan Schmidt 	while (*new) {
4576b4df8b6SGeliang Tang 		cur = rb_entry(*new, struct tree_mod_elem, node);
458bd989ba3SJan Schmidt 		parent = *new;
459298cfd36SChandan Rajendra 		if (cur->logical < tm->logical)
460bd989ba3SJan Schmidt 			new = &((*new)->rb_left);
461298cfd36SChandan Rajendra 		else if (cur->logical > tm->logical)
462bd989ba3SJan Schmidt 			new = &((*new)->rb_right);
463097b8a7cSJan Schmidt 		else if (cur->seq < tm->seq)
464bd989ba3SJan Schmidt 			new = &((*new)->rb_left);
465097b8a7cSJan Schmidt 		else if (cur->seq > tm->seq)
466bd989ba3SJan Schmidt 			new = &((*new)->rb_right);
4675de865eeSFilipe David Borba Manana 		else
4685de865eeSFilipe David Borba Manana 			return -EEXIST;
469bd989ba3SJan Schmidt 	}
470bd989ba3SJan Schmidt 
471bd989ba3SJan Schmidt 	rb_link_node(&tm->node, parent, new);
472bd989ba3SJan Schmidt 	rb_insert_color(&tm->node, tm_root);
4735de865eeSFilipe David Borba Manana 	return 0;
474bd989ba3SJan Schmidt }
475bd989ba3SJan Schmidt 
476097b8a7cSJan Schmidt /*
477097b8a7cSJan Schmidt  * Determines if logging can be omitted. Returns 1 if it can. Otherwise, it
478097b8a7cSJan Schmidt  * returns zero with the tree_mod_log_lock acquired. The caller must hold
479097b8a7cSJan Schmidt  * this until all tree mod log insertions are recorded in the rb tree and then
480097b8a7cSJan Schmidt  * call tree_mod_log_write_unlock() to release.
481097b8a7cSJan Schmidt  */
482e9b7fd4dSJan Schmidt static inline int tree_mod_dont_log(struct btrfs_fs_info *fs_info,
483e9b7fd4dSJan Schmidt 				    struct extent_buffer *eb) {
484e9b7fd4dSJan Schmidt 	smp_mb();
485e9b7fd4dSJan Schmidt 	if (list_empty(&(fs_info)->tree_mod_seq_list))
486e9b7fd4dSJan Schmidt 		return 1;
487097b8a7cSJan Schmidt 	if (eb && btrfs_header_level(eb) == 0)
488e9b7fd4dSJan Schmidt 		return 1;
4895de865eeSFilipe David Borba Manana 
4905de865eeSFilipe David Borba Manana 	tree_mod_log_write_lock(fs_info);
4915de865eeSFilipe David Borba Manana 	if (list_empty(&(fs_info)->tree_mod_seq_list)) {
4925de865eeSFilipe David Borba Manana 		tree_mod_log_write_unlock(fs_info);
4935de865eeSFilipe David Borba Manana 		return 1;
4945de865eeSFilipe David Borba Manana 	}
4955de865eeSFilipe David Borba Manana 
496e9b7fd4dSJan Schmidt 	return 0;
497e9b7fd4dSJan Schmidt }
498e9b7fd4dSJan Schmidt 
4995de865eeSFilipe David Borba Manana /* Similar to tree_mod_dont_log, but doesn't acquire any locks. */
5005de865eeSFilipe David Borba Manana static inline int tree_mod_need_log(const struct btrfs_fs_info *fs_info,
5015de865eeSFilipe David Borba Manana 				    struct extent_buffer *eb)
5025de865eeSFilipe David Borba Manana {
5035de865eeSFilipe David Borba Manana 	smp_mb();
5045de865eeSFilipe David Borba Manana 	if (list_empty(&(fs_info)->tree_mod_seq_list))
5055de865eeSFilipe David Borba Manana 		return 0;
5065de865eeSFilipe David Borba Manana 	if (eb && btrfs_header_level(eb) == 0)
5075de865eeSFilipe David Borba Manana 		return 0;
5085de865eeSFilipe David Borba Manana 
5095de865eeSFilipe David Borba Manana 	return 1;
5105de865eeSFilipe David Borba Manana }
5115de865eeSFilipe David Borba Manana 
5125de865eeSFilipe David Borba Manana static struct tree_mod_elem *
5135de865eeSFilipe David Borba Manana alloc_tree_mod_elem(struct extent_buffer *eb, int slot,
514bd989ba3SJan Schmidt 		    enum mod_log_op op, gfp_t flags)
515bd989ba3SJan Schmidt {
516097b8a7cSJan Schmidt 	struct tree_mod_elem *tm;
517bd989ba3SJan Schmidt 
518c8cc6341SJosef Bacik 	tm = kzalloc(sizeof(*tm), flags);
519c8cc6341SJosef Bacik 	if (!tm)
5205de865eeSFilipe David Borba Manana 		return NULL;
521bd989ba3SJan Schmidt 
522298cfd36SChandan Rajendra 	tm->logical = eb->start;
523bd989ba3SJan Schmidt 	if (op != MOD_LOG_KEY_ADD) {
524bd989ba3SJan Schmidt 		btrfs_node_key(eb, &tm->key, slot);
525bd989ba3SJan Schmidt 		tm->blockptr = btrfs_node_blockptr(eb, slot);
526bd989ba3SJan Schmidt 	}
527bd989ba3SJan Schmidt 	tm->op = op;
528bd989ba3SJan Schmidt 	tm->slot = slot;
529bd989ba3SJan Schmidt 	tm->generation = btrfs_node_ptr_generation(eb, slot);
5305de865eeSFilipe David Borba Manana 	RB_CLEAR_NODE(&tm->node);
531bd989ba3SJan Schmidt 
5325de865eeSFilipe David Borba Manana 	return tm;
533097b8a7cSJan Schmidt }
534097b8a7cSJan Schmidt 
535e09c2efeSDavid Sterba static noinline int tree_mod_log_insert_key(struct extent_buffer *eb, int slot,
536097b8a7cSJan Schmidt 		enum mod_log_op op, gfp_t flags)
537097b8a7cSJan Schmidt {
5385de865eeSFilipe David Borba Manana 	struct tree_mod_elem *tm;
5395de865eeSFilipe David Borba Manana 	int ret;
5405de865eeSFilipe David Borba Manana 
541e09c2efeSDavid Sterba 	if (!tree_mod_need_log(eb->fs_info, eb))
542097b8a7cSJan Schmidt 		return 0;
543097b8a7cSJan Schmidt 
5445de865eeSFilipe David Borba Manana 	tm = alloc_tree_mod_elem(eb, slot, op, flags);
5455de865eeSFilipe David Borba Manana 	if (!tm)
5465de865eeSFilipe David Borba Manana 		return -ENOMEM;
5475de865eeSFilipe David Borba Manana 
548e09c2efeSDavid Sterba 	if (tree_mod_dont_log(eb->fs_info, eb)) {
5495de865eeSFilipe David Borba Manana 		kfree(tm);
5505de865eeSFilipe David Borba Manana 		return 0;
5515de865eeSFilipe David Borba Manana 	}
5525de865eeSFilipe David Borba Manana 
553e09c2efeSDavid Sterba 	ret = __tree_mod_log_insert(eb->fs_info, tm);
554e09c2efeSDavid Sterba 	tree_mod_log_write_unlock(eb->fs_info);
5555de865eeSFilipe David Borba Manana 	if (ret)
5565de865eeSFilipe David Borba Manana 		kfree(tm);
5575de865eeSFilipe David Borba Manana 
5585de865eeSFilipe David Borba Manana 	return ret;
559097b8a7cSJan Schmidt }
560097b8a7cSJan Schmidt 
5616074d45fSDavid Sterba static noinline int tree_mod_log_insert_move(struct extent_buffer *eb,
5626074d45fSDavid Sterba 		int dst_slot, int src_slot, int nr_items)
563bd989ba3SJan Schmidt {
5645de865eeSFilipe David Borba Manana 	struct tree_mod_elem *tm = NULL;
5655de865eeSFilipe David Borba Manana 	struct tree_mod_elem **tm_list = NULL;
5665de865eeSFilipe David Borba Manana 	int ret = 0;
567bd989ba3SJan Schmidt 	int i;
5685de865eeSFilipe David Borba Manana 	int locked = 0;
569bd989ba3SJan Schmidt 
5706074d45fSDavid Sterba 	if (!tree_mod_need_log(eb->fs_info, eb))
571f395694cSJan Schmidt 		return 0;
572bd989ba3SJan Schmidt 
573176ef8f5SDavid Sterba 	tm_list = kcalloc(nr_items, sizeof(struct tree_mod_elem *), GFP_NOFS);
5745de865eeSFilipe David Borba Manana 	if (!tm_list)
5755de865eeSFilipe David Borba Manana 		return -ENOMEM;
576bd989ba3SJan Schmidt 
577176ef8f5SDavid Sterba 	tm = kzalloc(sizeof(*tm), GFP_NOFS);
5785de865eeSFilipe David Borba Manana 	if (!tm) {
5795de865eeSFilipe David Borba Manana 		ret = -ENOMEM;
5805de865eeSFilipe David Borba Manana 		goto free_tms;
5815de865eeSFilipe David Borba Manana 	}
582f395694cSJan Schmidt 
583298cfd36SChandan Rajendra 	tm->logical = eb->start;
584bd989ba3SJan Schmidt 	tm->slot = src_slot;
585bd989ba3SJan Schmidt 	tm->move.dst_slot = dst_slot;
586bd989ba3SJan Schmidt 	tm->move.nr_items = nr_items;
587bd989ba3SJan Schmidt 	tm->op = MOD_LOG_MOVE_KEYS;
588bd989ba3SJan Schmidt 
5895de865eeSFilipe David Borba Manana 	for (i = 0; i + dst_slot < src_slot && i < nr_items; i++) {
5905de865eeSFilipe David Borba Manana 		tm_list[i] = alloc_tree_mod_elem(eb, i + dst_slot,
591176ef8f5SDavid Sterba 		    MOD_LOG_KEY_REMOVE_WHILE_MOVING, GFP_NOFS);
5925de865eeSFilipe David Borba Manana 		if (!tm_list[i]) {
5935de865eeSFilipe David Borba Manana 			ret = -ENOMEM;
5945de865eeSFilipe David Borba Manana 			goto free_tms;
5955de865eeSFilipe David Borba Manana 		}
596bd989ba3SJan Schmidt 	}
597bd989ba3SJan Schmidt 
5986074d45fSDavid Sterba 	if (tree_mod_dont_log(eb->fs_info, eb))
5995de865eeSFilipe David Borba Manana 		goto free_tms;
6005de865eeSFilipe David Borba Manana 	locked = 1;
6015de865eeSFilipe David Borba Manana 
6025de865eeSFilipe David Borba Manana 	/*
6035de865eeSFilipe David Borba Manana 	 * When we override something during the move, we log these removals.
6045de865eeSFilipe David Borba Manana 	 * This can only happen when we move towards the beginning of the
6055de865eeSFilipe David Borba Manana 	 * buffer, i.e. dst_slot < src_slot.
6065de865eeSFilipe David Borba Manana 	 */
6075de865eeSFilipe David Borba Manana 	for (i = 0; i + dst_slot < src_slot && i < nr_items; i++) {
6086074d45fSDavid Sterba 		ret = __tree_mod_log_insert(eb->fs_info, tm_list[i]);
6095de865eeSFilipe David Borba Manana 		if (ret)
6105de865eeSFilipe David Borba Manana 			goto free_tms;
6115de865eeSFilipe David Borba Manana 	}
6125de865eeSFilipe David Borba Manana 
6136074d45fSDavid Sterba 	ret = __tree_mod_log_insert(eb->fs_info, tm);
6145de865eeSFilipe David Borba Manana 	if (ret)
6155de865eeSFilipe David Borba Manana 		goto free_tms;
6166074d45fSDavid Sterba 	tree_mod_log_write_unlock(eb->fs_info);
6175de865eeSFilipe David Borba Manana 	kfree(tm_list);
6185de865eeSFilipe David Borba Manana 
6195de865eeSFilipe David Borba Manana 	return 0;
6205de865eeSFilipe David Borba Manana free_tms:
6215de865eeSFilipe David Borba Manana 	for (i = 0; i < nr_items; i++) {
6225de865eeSFilipe David Borba Manana 		if (tm_list[i] && !RB_EMPTY_NODE(&tm_list[i]->node))
6236074d45fSDavid Sterba 			rb_erase(&tm_list[i]->node, &eb->fs_info->tree_mod_log);
6245de865eeSFilipe David Borba Manana 		kfree(tm_list[i]);
6255de865eeSFilipe David Borba Manana 	}
6265de865eeSFilipe David Borba Manana 	if (locked)
6276074d45fSDavid Sterba 		tree_mod_log_write_unlock(eb->fs_info);
6285de865eeSFilipe David Borba Manana 	kfree(tm_list);
6295de865eeSFilipe David Borba Manana 	kfree(tm);
6305de865eeSFilipe David Borba Manana 
6315de865eeSFilipe David Borba Manana 	return ret;
6325de865eeSFilipe David Borba Manana }
6335de865eeSFilipe David Borba Manana 
6345de865eeSFilipe David Borba Manana static inline int
6355de865eeSFilipe David Borba Manana __tree_mod_log_free_eb(struct btrfs_fs_info *fs_info,
6365de865eeSFilipe David Borba Manana 		       struct tree_mod_elem **tm_list,
6375de865eeSFilipe David Borba Manana 		       int nritems)
638097b8a7cSJan Schmidt {
6395de865eeSFilipe David Borba Manana 	int i, j;
640097b8a7cSJan Schmidt 	int ret;
641097b8a7cSJan Schmidt 
642097b8a7cSJan Schmidt 	for (i = nritems - 1; i >= 0; i--) {
6435de865eeSFilipe David Borba Manana 		ret = __tree_mod_log_insert(fs_info, tm_list[i]);
6445de865eeSFilipe David Borba Manana 		if (ret) {
6455de865eeSFilipe David Borba Manana 			for (j = nritems - 1; j > i; j--)
6465de865eeSFilipe David Borba Manana 				rb_erase(&tm_list[j]->node,
6475de865eeSFilipe David Borba Manana 					 &fs_info->tree_mod_log);
6485de865eeSFilipe David Borba Manana 			return ret;
649097b8a7cSJan Schmidt 		}
650097b8a7cSJan Schmidt 	}
651097b8a7cSJan Schmidt 
6525de865eeSFilipe David Borba Manana 	return 0;
6535de865eeSFilipe David Borba Manana }
6545de865eeSFilipe David Borba Manana 
65595b757c1SDavid Sterba static noinline int tree_mod_log_insert_root(struct extent_buffer *old_root,
65695b757c1SDavid Sterba 			 struct extent_buffer *new_root, int log_removal)
657bd989ba3SJan Schmidt {
65895b757c1SDavid Sterba 	struct btrfs_fs_info *fs_info = old_root->fs_info;
6595de865eeSFilipe David Borba Manana 	struct tree_mod_elem *tm = NULL;
6605de865eeSFilipe David Borba Manana 	struct tree_mod_elem **tm_list = NULL;
6615de865eeSFilipe David Borba Manana 	int nritems = 0;
6625de865eeSFilipe David Borba Manana 	int ret = 0;
6635de865eeSFilipe David Borba Manana 	int i;
664bd989ba3SJan Schmidt 
6655de865eeSFilipe David Borba Manana 	if (!tree_mod_need_log(fs_info, NULL))
666097b8a7cSJan Schmidt 		return 0;
667097b8a7cSJan Schmidt 
6685de865eeSFilipe David Borba Manana 	if (log_removal && btrfs_header_level(old_root) > 0) {
6695de865eeSFilipe David Borba Manana 		nritems = btrfs_header_nritems(old_root);
67031e818feSDavid Sterba 		tm_list = kcalloc(nritems, sizeof(struct tree_mod_elem *),
671bcc8e07fSDavid Sterba 				  GFP_NOFS);
6725de865eeSFilipe David Borba Manana 		if (!tm_list) {
6735de865eeSFilipe David Borba Manana 			ret = -ENOMEM;
6745de865eeSFilipe David Borba Manana 			goto free_tms;
6755de865eeSFilipe David Borba Manana 		}
6765de865eeSFilipe David Borba Manana 		for (i = 0; i < nritems; i++) {
6775de865eeSFilipe David Borba Manana 			tm_list[i] = alloc_tree_mod_elem(old_root, i,
678bcc8e07fSDavid Sterba 			    MOD_LOG_KEY_REMOVE_WHILE_FREEING, GFP_NOFS);
6795de865eeSFilipe David Borba Manana 			if (!tm_list[i]) {
6805de865eeSFilipe David Borba Manana 				ret = -ENOMEM;
6815de865eeSFilipe David Borba Manana 				goto free_tms;
6825de865eeSFilipe David Borba Manana 			}
6835de865eeSFilipe David Borba Manana 		}
6845de865eeSFilipe David Borba Manana 	}
685d9abbf1cSJan Schmidt 
686bcc8e07fSDavid Sterba 	tm = kzalloc(sizeof(*tm), GFP_NOFS);
6875de865eeSFilipe David Borba Manana 	if (!tm) {
6885de865eeSFilipe David Borba Manana 		ret = -ENOMEM;
6895de865eeSFilipe David Borba Manana 		goto free_tms;
6905de865eeSFilipe David Borba Manana 	}
691bd989ba3SJan Schmidt 
692298cfd36SChandan Rajendra 	tm->logical = new_root->start;
693bd989ba3SJan Schmidt 	tm->old_root.logical = old_root->start;
694bd989ba3SJan Schmidt 	tm->old_root.level = btrfs_header_level(old_root);
695bd989ba3SJan Schmidt 	tm->generation = btrfs_header_generation(old_root);
696bd989ba3SJan Schmidt 	tm->op = MOD_LOG_ROOT_REPLACE;
697bd989ba3SJan Schmidt 
6985de865eeSFilipe David Borba Manana 	if (tree_mod_dont_log(fs_info, NULL))
6995de865eeSFilipe David Borba Manana 		goto free_tms;
7005de865eeSFilipe David Borba Manana 
7015de865eeSFilipe David Borba Manana 	if (tm_list)
7025de865eeSFilipe David Borba Manana 		ret = __tree_mod_log_free_eb(fs_info, tm_list, nritems);
7035de865eeSFilipe David Borba Manana 	if (!ret)
7045de865eeSFilipe David Borba Manana 		ret = __tree_mod_log_insert(fs_info, tm);
7055de865eeSFilipe David Borba Manana 
7065de865eeSFilipe David Borba Manana 	tree_mod_log_write_unlock(fs_info);
7075de865eeSFilipe David Borba Manana 	if (ret)
7085de865eeSFilipe David Borba Manana 		goto free_tms;
7095de865eeSFilipe David Borba Manana 	kfree(tm_list);
7105de865eeSFilipe David Borba Manana 
7115de865eeSFilipe David Borba Manana 	return ret;
7125de865eeSFilipe David Borba Manana 
7135de865eeSFilipe David Borba Manana free_tms:
7145de865eeSFilipe David Borba Manana 	if (tm_list) {
7155de865eeSFilipe David Borba Manana 		for (i = 0; i < nritems; i++)
7165de865eeSFilipe David Borba Manana 			kfree(tm_list[i]);
7175de865eeSFilipe David Borba Manana 		kfree(tm_list);
7185de865eeSFilipe David Borba Manana 	}
7195de865eeSFilipe David Borba Manana 	kfree(tm);
7205de865eeSFilipe David Borba Manana 
7215de865eeSFilipe David Borba Manana 	return ret;
722bd989ba3SJan Schmidt }
723bd989ba3SJan Schmidt 
724bd989ba3SJan Schmidt static struct tree_mod_elem *
725bd989ba3SJan Schmidt __tree_mod_log_search(struct btrfs_fs_info *fs_info, u64 start, u64 min_seq,
726bd989ba3SJan Schmidt 		      int smallest)
727bd989ba3SJan Schmidt {
728bd989ba3SJan Schmidt 	struct rb_root *tm_root;
729bd989ba3SJan Schmidt 	struct rb_node *node;
730bd989ba3SJan Schmidt 	struct tree_mod_elem *cur = NULL;
731bd989ba3SJan Schmidt 	struct tree_mod_elem *found = NULL;
732bd989ba3SJan Schmidt 
733097b8a7cSJan Schmidt 	tree_mod_log_read_lock(fs_info);
734bd989ba3SJan Schmidt 	tm_root = &fs_info->tree_mod_log;
735bd989ba3SJan Schmidt 	node = tm_root->rb_node;
736bd989ba3SJan Schmidt 	while (node) {
7376b4df8b6SGeliang Tang 		cur = rb_entry(node, struct tree_mod_elem, node);
738298cfd36SChandan Rajendra 		if (cur->logical < start) {
739bd989ba3SJan Schmidt 			node = node->rb_left;
740298cfd36SChandan Rajendra 		} else if (cur->logical > start) {
741bd989ba3SJan Schmidt 			node = node->rb_right;
742097b8a7cSJan Schmidt 		} else if (cur->seq < min_seq) {
743bd989ba3SJan Schmidt 			node = node->rb_left;
744bd989ba3SJan Schmidt 		} else if (!smallest) {
745bd989ba3SJan Schmidt 			/* we want the node with the highest seq */
746bd989ba3SJan Schmidt 			if (found)
747097b8a7cSJan Schmidt 				BUG_ON(found->seq > cur->seq);
748bd989ba3SJan Schmidt 			found = cur;
749bd989ba3SJan Schmidt 			node = node->rb_left;
750097b8a7cSJan Schmidt 		} else if (cur->seq > min_seq) {
751bd989ba3SJan Schmidt 			/* we want the node with the smallest seq */
752bd989ba3SJan Schmidt 			if (found)
753097b8a7cSJan Schmidt 				BUG_ON(found->seq < cur->seq);
754bd989ba3SJan Schmidt 			found = cur;
755bd989ba3SJan Schmidt 			node = node->rb_right;
756bd989ba3SJan Schmidt 		} else {
757bd989ba3SJan Schmidt 			found = cur;
758bd989ba3SJan Schmidt 			break;
759bd989ba3SJan Schmidt 		}
760bd989ba3SJan Schmidt 	}
761097b8a7cSJan Schmidt 	tree_mod_log_read_unlock(fs_info);
762bd989ba3SJan Schmidt 
763bd989ba3SJan Schmidt 	return found;
764bd989ba3SJan Schmidt }
765bd989ba3SJan Schmidt 
766bd989ba3SJan Schmidt /*
767bd989ba3SJan Schmidt  * this returns the element from the log with the smallest time sequence
768bd989ba3SJan Schmidt  * value that's in the log (the oldest log item). any element with a time
769bd989ba3SJan Schmidt  * sequence lower than min_seq will be ignored.
770bd989ba3SJan Schmidt  */
771bd989ba3SJan Schmidt static struct tree_mod_elem *
772bd989ba3SJan Schmidt tree_mod_log_search_oldest(struct btrfs_fs_info *fs_info, u64 start,
773bd989ba3SJan Schmidt 			   u64 min_seq)
774bd989ba3SJan Schmidt {
775bd989ba3SJan Schmidt 	return __tree_mod_log_search(fs_info, start, min_seq, 1);
776bd989ba3SJan Schmidt }
777bd989ba3SJan Schmidt 
778bd989ba3SJan Schmidt /*
779bd989ba3SJan Schmidt  * this returns the element from the log with the largest time sequence
780bd989ba3SJan Schmidt  * value that's in the log (the most recent log item). any element with
781bd989ba3SJan Schmidt  * a time sequence lower than min_seq will be ignored.
782bd989ba3SJan Schmidt  */
783bd989ba3SJan Schmidt static struct tree_mod_elem *
784bd989ba3SJan Schmidt tree_mod_log_search(struct btrfs_fs_info *fs_info, u64 start, u64 min_seq)
785bd989ba3SJan Schmidt {
786bd989ba3SJan Schmidt 	return __tree_mod_log_search(fs_info, start, min_seq, 0);
787bd989ba3SJan Schmidt }
788bd989ba3SJan Schmidt 
7895de865eeSFilipe David Borba Manana static noinline int
790bd989ba3SJan Schmidt tree_mod_log_eb_copy(struct btrfs_fs_info *fs_info, struct extent_buffer *dst,
791bd989ba3SJan Schmidt 		     struct extent_buffer *src, unsigned long dst_offset,
79290f8d62eSJan Schmidt 		     unsigned long src_offset, int nr_items)
793bd989ba3SJan Schmidt {
7945de865eeSFilipe David Borba Manana 	int ret = 0;
7955de865eeSFilipe David Borba Manana 	struct tree_mod_elem **tm_list = NULL;
7965de865eeSFilipe David Borba Manana 	struct tree_mod_elem **tm_list_add, **tm_list_rem;
797bd989ba3SJan Schmidt 	int i;
7985de865eeSFilipe David Borba Manana 	int locked = 0;
799bd989ba3SJan Schmidt 
8005de865eeSFilipe David Borba Manana 	if (!tree_mod_need_log(fs_info, NULL))
8015de865eeSFilipe David Borba Manana 		return 0;
802bd989ba3SJan Schmidt 
803c8cc6341SJosef Bacik 	if (btrfs_header_level(dst) == 0 && btrfs_header_level(src) == 0)
8045de865eeSFilipe David Borba Manana 		return 0;
8055de865eeSFilipe David Borba Manana 
80631e818feSDavid Sterba 	tm_list = kcalloc(nr_items * 2, sizeof(struct tree_mod_elem *),
8075de865eeSFilipe David Borba Manana 			  GFP_NOFS);
8085de865eeSFilipe David Borba Manana 	if (!tm_list)
8095de865eeSFilipe David Borba Manana 		return -ENOMEM;
8105de865eeSFilipe David Borba Manana 
8115de865eeSFilipe David Borba Manana 	tm_list_add = tm_list;
8125de865eeSFilipe David Borba Manana 	tm_list_rem = tm_list + nr_items;
8135de865eeSFilipe David Borba Manana 	for (i = 0; i < nr_items; i++) {
8145de865eeSFilipe David Borba Manana 		tm_list_rem[i] = alloc_tree_mod_elem(src, i + src_offset,
8155de865eeSFilipe David Borba Manana 		    MOD_LOG_KEY_REMOVE, GFP_NOFS);
8165de865eeSFilipe David Borba Manana 		if (!tm_list_rem[i]) {
8175de865eeSFilipe David Borba Manana 			ret = -ENOMEM;
8185de865eeSFilipe David Borba Manana 			goto free_tms;
8195de865eeSFilipe David Borba Manana 		}
8205de865eeSFilipe David Borba Manana 
8215de865eeSFilipe David Borba Manana 		tm_list_add[i] = alloc_tree_mod_elem(dst, i + dst_offset,
8225de865eeSFilipe David Borba Manana 		    MOD_LOG_KEY_ADD, GFP_NOFS);
8235de865eeSFilipe David Borba Manana 		if (!tm_list_add[i]) {
8245de865eeSFilipe David Borba Manana 			ret = -ENOMEM;
8255de865eeSFilipe David Borba Manana 			goto free_tms;
8265de865eeSFilipe David Borba Manana 		}
8275de865eeSFilipe David Borba Manana 	}
8285de865eeSFilipe David Borba Manana 
8295de865eeSFilipe David Borba Manana 	if (tree_mod_dont_log(fs_info, NULL))
8305de865eeSFilipe David Borba Manana 		goto free_tms;
8315de865eeSFilipe David Borba Manana 	locked = 1;
832bd989ba3SJan Schmidt 
833bd989ba3SJan Schmidt 	for (i = 0; i < nr_items; i++) {
8345de865eeSFilipe David Borba Manana 		ret = __tree_mod_log_insert(fs_info, tm_list_rem[i]);
8355de865eeSFilipe David Borba Manana 		if (ret)
8365de865eeSFilipe David Borba Manana 			goto free_tms;
8375de865eeSFilipe David Borba Manana 		ret = __tree_mod_log_insert(fs_info, tm_list_add[i]);
8385de865eeSFilipe David Borba Manana 		if (ret)
8395de865eeSFilipe David Borba Manana 			goto free_tms;
840bd989ba3SJan Schmidt 	}
8415de865eeSFilipe David Borba Manana 
8425de865eeSFilipe David Borba Manana 	tree_mod_log_write_unlock(fs_info);
8435de865eeSFilipe David Borba Manana 	kfree(tm_list);
8445de865eeSFilipe David Borba Manana 
8455de865eeSFilipe David Borba Manana 	return 0;
8465de865eeSFilipe David Borba Manana 
8475de865eeSFilipe David Borba Manana free_tms:
8485de865eeSFilipe David Borba Manana 	for (i = 0; i < nr_items * 2; i++) {
8495de865eeSFilipe David Borba Manana 		if (tm_list[i] && !RB_EMPTY_NODE(&tm_list[i]->node))
8505de865eeSFilipe David Borba Manana 			rb_erase(&tm_list[i]->node, &fs_info->tree_mod_log);
8515de865eeSFilipe David Borba Manana 		kfree(tm_list[i]);
8525de865eeSFilipe David Borba Manana 	}
8535de865eeSFilipe David Borba Manana 	if (locked)
8545de865eeSFilipe David Borba Manana 		tree_mod_log_write_unlock(fs_info);
8555de865eeSFilipe David Borba Manana 	kfree(tm_list);
8565de865eeSFilipe David Borba Manana 
8575de865eeSFilipe David Borba Manana 	return ret;
858bd989ba3SJan Schmidt }
859bd989ba3SJan Schmidt 
860a446a979SDavid Sterba static inline void tree_mod_log_eb_move(struct extent_buffer *dst,
861bd989ba3SJan Schmidt 		     int dst_offset, int src_offset, int nr_items)
862bd989ba3SJan Schmidt {
863bd989ba3SJan Schmidt 	int ret;
8646074d45fSDavid Sterba 	ret = tree_mod_log_insert_move(dst, dst_offset, src_offset, nr_items);
865bd989ba3SJan Schmidt 	BUG_ON(ret < 0);
866bd989ba3SJan Schmidt }
867bd989ba3SJan Schmidt 
8683ac6de1aSDavid Sterba static noinline void tree_mod_log_set_node_key(struct extent_buffer *eb,
8693ac6de1aSDavid Sterba 		int slot, int atomic)
870bd989ba3SJan Schmidt {
871bd989ba3SJan Schmidt 	int ret;
872bd989ba3SJan Schmidt 
873e09c2efeSDavid Sterba 	ret = tree_mod_log_insert_key(eb, slot, MOD_LOG_KEY_REPLACE,
874bd989ba3SJan Schmidt 					atomic ? GFP_ATOMIC : GFP_NOFS);
875bd989ba3SJan Schmidt 	BUG_ON(ret < 0);
876bd989ba3SJan Schmidt }
877bd989ba3SJan Schmidt 
878db7279a2SDavid Sterba static noinline int tree_mod_log_free_eb(struct extent_buffer *eb)
879bd989ba3SJan Schmidt {
8805de865eeSFilipe David Borba Manana 	struct tree_mod_elem **tm_list = NULL;
8815de865eeSFilipe David Borba Manana 	int nritems = 0;
8825de865eeSFilipe David Borba Manana 	int i;
8835de865eeSFilipe David Borba Manana 	int ret = 0;
8845de865eeSFilipe David Borba Manana 
8855de865eeSFilipe David Borba Manana 	if (btrfs_header_level(eb) == 0)
8865de865eeSFilipe David Borba Manana 		return 0;
8875de865eeSFilipe David Borba Manana 
888db7279a2SDavid Sterba 	if (!tree_mod_need_log(eb->fs_info, NULL))
8895de865eeSFilipe David Borba Manana 		return 0;
8905de865eeSFilipe David Borba Manana 
8915de865eeSFilipe David Borba Manana 	nritems = btrfs_header_nritems(eb);
89231e818feSDavid Sterba 	tm_list = kcalloc(nritems, sizeof(struct tree_mod_elem *), GFP_NOFS);
8935de865eeSFilipe David Borba Manana 	if (!tm_list)
8945de865eeSFilipe David Borba Manana 		return -ENOMEM;
8955de865eeSFilipe David Borba Manana 
8965de865eeSFilipe David Borba Manana 	for (i = 0; i < nritems; i++) {
8975de865eeSFilipe David Borba Manana 		tm_list[i] = alloc_tree_mod_elem(eb, i,
8985de865eeSFilipe David Borba Manana 		    MOD_LOG_KEY_REMOVE_WHILE_FREEING, GFP_NOFS);
8995de865eeSFilipe David Borba Manana 		if (!tm_list[i]) {
9005de865eeSFilipe David Borba Manana 			ret = -ENOMEM;
9015de865eeSFilipe David Borba Manana 			goto free_tms;
9025de865eeSFilipe David Borba Manana 		}
9035de865eeSFilipe David Borba Manana 	}
9045de865eeSFilipe David Borba Manana 
905db7279a2SDavid Sterba 	if (tree_mod_dont_log(eb->fs_info, eb))
9065de865eeSFilipe David Borba Manana 		goto free_tms;
9075de865eeSFilipe David Borba Manana 
908db7279a2SDavid Sterba 	ret = __tree_mod_log_free_eb(eb->fs_info, tm_list, nritems);
909db7279a2SDavid Sterba 	tree_mod_log_write_unlock(eb->fs_info);
9105de865eeSFilipe David Borba Manana 	if (ret)
9115de865eeSFilipe David Borba Manana 		goto free_tms;
9125de865eeSFilipe David Borba Manana 	kfree(tm_list);
9135de865eeSFilipe David Borba Manana 
9145de865eeSFilipe David Borba Manana 	return 0;
9155de865eeSFilipe David Borba Manana 
9165de865eeSFilipe David Borba Manana free_tms:
9175de865eeSFilipe David Borba Manana 	for (i = 0; i < nritems; i++)
9185de865eeSFilipe David Borba Manana 		kfree(tm_list[i]);
9195de865eeSFilipe David Borba Manana 	kfree(tm_list);
9205de865eeSFilipe David Borba Manana 
9215de865eeSFilipe David Borba Manana 	return ret;
922bd989ba3SJan Schmidt }
923bd989ba3SJan Schmidt 
924097b8a7cSJan Schmidt static noinline void
925bd989ba3SJan Schmidt tree_mod_log_set_root_pointer(struct btrfs_root *root,
92690f8d62eSJan Schmidt 			      struct extent_buffer *new_root_node,
92790f8d62eSJan Schmidt 			      int log_removal)
928bd989ba3SJan Schmidt {
929bd989ba3SJan Schmidt 	int ret;
93095b757c1SDavid Sterba 	ret = tree_mod_log_insert_root(root->node, new_root_node, log_removal);
931bd989ba3SJan Schmidt 	BUG_ON(ret < 0);
932bd989ba3SJan Schmidt }
933bd989ba3SJan Schmidt 
934d352ac68SChris Mason /*
9355d4f98a2SYan Zheng  * check if the tree block can be shared by multiple trees
9365d4f98a2SYan Zheng  */
9375d4f98a2SYan Zheng int btrfs_block_can_be_shared(struct btrfs_root *root,
9385d4f98a2SYan Zheng 			      struct extent_buffer *buf)
9395d4f98a2SYan Zheng {
9405d4f98a2SYan Zheng 	/*
94101327610SNicholas D Steeves 	 * Tree blocks not in reference counted trees and tree roots
9425d4f98a2SYan Zheng 	 * are never shared. If a block was allocated after the last
9435d4f98a2SYan Zheng 	 * snapshot and the block was not allocated by tree relocation,
9445d4f98a2SYan Zheng 	 * we know the block is not shared.
9455d4f98a2SYan Zheng 	 */
94627cdeb70SMiao Xie 	if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
9475d4f98a2SYan Zheng 	    buf != root->node && buf != root->commit_root &&
9485d4f98a2SYan Zheng 	    (btrfs_header_generation(buf) <=
9495d4f98a2SYan Zheng 	     btrfs_root_last_snapshot(&root->root_item) ||
9505d4f98a2SYan Zheng 	     btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)))
9515d4f98a2SYan Zheng 		return 1;
9525d4f98a2SYan Zheng #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
95327cdeb70SMiao Xie 	if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
9545d4f98a2SYan Zheng 	    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
9555d4f98a2SYan Zheng 		return 1;
9565d4f98a2SYan Zheng #endif
9575d4f98a2SYan Zheng 	return 0;
9585d4f98a2SYan Zheng }
9595d4f98a2SYan Zheng 
9605d4f98a2SYan Zheng static noinline int update_ref_for_cow(struct btrfs_trans_handle *trans,
9615d4f98a2SYan Zheng 				       struct btrfs_root *root,
9625d4f98a2SYan Zheng 				       struct extent_buffer *buf,
963f0486c68SYan, Zheng 				       struct extent_buffer *cow,
964f0486c68SYan, Zheng 				       int *last_ref)
9655d4f98a2SYan Zheng {
9660b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
9675d4f98a2SYan Zheng 	u64 refs;
9685d4f98a2SYan Zheng 	u64 owner;
9695d4f98a2SYan Zheng 	u64 flags;
9705d4f98a2SYan Zheng 	u64 new_flags = 0;
9715d4f98a2SYan Zheng 	int ret;
9725d4f98a2SYan Zheng 
9735d4f98a2SYan Zheng 	/*
9745d4f98a2SYan Zheng 	 * Backrefs update rules:
9755d4f98a2SYan Zheng 	 *
9765d4f98a2SYan Zheng 	 * Always use full backrefs for extent pointers in tree block
9775d4f98a2SYan Zheng 	 * allocated by tree relocation.
9785d4f98a2SYan Zheng 	 *
9795d4f98a2SYan Zheng 	 * If a shared tree block is no longer referenced by its owner
9805d4f98a2SYan Zheng 	 * tree (btrfs_header_owner(buf) == root->root_key.objectid),
9815d4f98a2SYan Zheng 	 * use full backrefs for extent pointers in tree block.
9825d4f98a2SYan Zheng 	 *
9835d4f98a2SYan Zheng 	 * If a tree block is been relocating
9845d4f98a2SYan Zheng 	 * (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID),
9855d4f98a2SYan Zheng 	 * use full backrefs for extent pointers in tree block.
9865d4f98a2SYan Zheng 	 * The reason for this is some operations (such as drop tree)
9875d4f98a2SYan Zheng 	 * are only allowed for blocks use full backrefs.
9885d4f98a2SYan Zheng 	 */
9895d4f98a2SYan Zheng 
9905d4f98a2SYan Zheng 	if (btrfs_block_can_be_shared(root, buf)) {
9912ff7e61eSJeff Mahoney 		ret = btrfs_lookup_extent_info(trans, fs_info, buf->start,
9923173a18fSJosef Bacik 					       btrfs_header_level(buf), 1,
9933173a18fSJosef Bacik 					       &refs, &flags);
994be1a5564SMark Fasheh 		if (ret)
995be1a5564SMark Fasheh 			return ret;
996e5df9573SMark Fasheh 		if (refs == 0) {
997e5df9573SMark Fasheh 			ret = -EROFS;
9980b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
999e5df9573SMark Fasheh 			return ret;
1000e5df9573SMark Fasheh 		}
10015d4f98a2SYan Zheng 	} else {
10025d4f98a2SYan Zheng 		refs = 1;
10035d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
10045d4f98a2SYan Zheng 		    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
10055d4f98a2SYan Zheng 			flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
10065d4f98a2SYan Zheng 		else
10075d4f98a2SYan Zheng 			flags = 0;
10085d4f98a2SYan Zheng 	}
10095d4f98a2SYan Zheng 
10105d4f98a2SYan Zheng 	owner = btrfs_header_owner(buf);
10115d4f98a2SYan Zheng 	BUG_ON(owner == BTRFS_TREE_RELOC_OBJECTID &&
10125d4f98a2SYan Zheng 	       !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
10135d4f98a2SYan Zheng 
10145d4f98a2SYan Zheng 	if (refs > 1) {
10155d4f98a2SYan Zheng 		if ((owner == root->root_key.objectid ||
10165d4f98a2SYan Zheng 		     root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) &&
10175d4f98a2SYan Zheng 		    !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)) {
1018e339a6b0SJosef Bacik 			ret = btrfs_inc_ref(trans, root, buf, 1);
1019692826b2SJeff Mahoney 			if (ret)
1020692826b2SJeff Mahoney 				return ret;
10215d4f98a2SYan Zheng 
10225d4f98a2SYan Zheng 			if (root->root_key.objectid ==
10235d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID) {
1024e339a6b0SJosef Bacik 				ret = btrfs_dec_ref(trans, root, buf, 0);
1025692826b2SJeff Mahoney 				if (ret)
1026692826b2SJeff Mahoney 					return ret;
1027e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
1028692826b2SJeff Mahoney 				if (ret)
1029692826b2SJeff Mahoney 					return ret;
10305d4f98a2SYan Zheng 			}
10315d4f98a2SYan Zheng 			new_flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
10325d4f98a2SYan Zheng 		} else {
10335d4f98a2SYan Zheng 
10345d4f98a2SYan Zheng 			if (root->root_key.objectid ==
10355d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID)
1036e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
10375d4f98a2SYan Zheng 			else
1038e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 0);
1039692826b2SJeff Mahoney 			if (ret)
1040692826b2SJeff Mahoney 				return ret;
10415d4f98a2SYan Zheng 		}
10425d4f98a2SYan Zheng 		if (new_flags != 0) {
1043b1c79e09SJosef Bacik 			int level = btrfs_header_level(buf);
1044b1c79e09SJosef Bacik 
10452ff7e61eSJeff Mahoney 			ret = btrfs_set_disk_extent_flags(trans, fs_info,
10465d4f98a2SYan Zheng 							  buf->start,
10475d4f98a2SYan Zheng 							  buf->len,
1048b1c79e09SJosef Bacik 							  new_flags, level, 0);
1049be1a5564SMark Fasheh 			if (ret)
1050be1a5564SMark Fasheh 				return ret;
10515d4f98a2SYan Zheng 		}
10525d4f98a2SYan Zheng 	} else {
10535d4f98a2SYan Zheng 		if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
10545d4f98a2SYan Zheng 			if (root->root_key.objectid ==
10555d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID)
1056e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
10575d4f98a2SYan Zheng 			else
1058e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 0);
1059692826b2SJeff Mahoney 			if (ret)
1060692826b2SJeff Mahoney 				return ret;
1061e339a6b0SJosef Bacik 			ret = btrfs_dec_ref(trans, root, buf, 1);
1062692826b2SJeff Mahoney 			if (ret)
1063692826b2SJeff Mahoney 				return ret;
10645d4f98a2SYan Zheng 		}
10657c302b49SDavid Sterba 		clean_tree_block(fs_info, buf);
1066f0486c68SYan, Zheng 		*last_ref = 1;
10675d4f98a2SYan Zheng 	}
10685d4f98a2SYan Zheng 	return 0;
10695d4f98a2SYan Zheng }
10705d4f98a2SYan Zheng 
10715d4f98a2SYan Zheng /*
1072d397712bSChris Mason  * does the dirty work in cow of a single block.  The parent block (if
1073d397712bSChris Mason  * supplied) is updated to point to the new cow copy.  The new buffer is marked
1074d397712bSChris Mason  * dirty and returned locked.  If you modify the block it needs to be marked
1075d397712bSChris Mason  * dirty again.
1076d352ac68SChris Mason  *
1077d352ac68SChris Mason  * search_start -- an allocation hint for the new block
1078d352ac68SChris Mason  *
1079d397712bSChris Mason  * empty_size -- a hint that you plan on doing more cow.  This is the size in
1080d397712bSChris Mason  * bytes the allocator should try to find free next to the block it returns.
1081d397712bSChris Mason  * This is just a hint and may be ignored by the allocator.
1082d352ac68SChris Mason  */
1083d397712bSChris Mason static noinline int __btrfs_cow_block(struct btrfs_trans_handle *trans,
10845f39d397SChris Mason 			     struct btrfs_root *root,
10855f39d397SChris Mason 			     struct extent_buffer *buf,
10865f39d397SChris Mason 			     struct extent_buffer *parent, int parent_slot,
10875f39d397SChris Mason 			     struct extent_buffer **cow_ret,
10889fa8cfe7SChris Mason 			     u64 search_start, u64 empty_size)
10896702ed49SChris Mason {
10900b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
10915d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
10925f39d397SChris Mason 	struct extent_buffer *cow;
1093be1a5564SMark Fasheh 	int level, ret;
1094f0486c68SYan, Zheng 	int last_ref = 0;
1095925baeddSChris Mason 	int unlock_orig = 0;
10960f5053ebSGoldwyn Rodrigues 	u64 parent_start = 0;
10976702ed49SChris Mason 
1098925baeddSChris Mason 	if (*cow_ret == buf)
1099925baeddSChris Mason 		unlock_orig = 1;
1100925baeddSChris Mason 
1101b9447ef8SChris Mason 	btrfs_assert_tree_locked(buf);
1102925baeddSChris Mason 
110327cdeb70SMiao Xie 	WARN_ON(test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
11040b246afaSJeff Mahoney 		trans->transid != fs_info->running_transaction->transid);
110527cdeb70SMiao Xie 	WARN_ON(test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
110627cdeb70SMiao Xie 		trans->transid != root->last_trans);
11075f39d397SChris Mason 
11087bb86316SChris Mason 	level = btrfs_header_level(buf);
110931840ae1SZheng Yan 
11105d4f98a2SYan Zheng 	if (level == 0)
11115d4f98a2SYan Zheng 		btrfs_item_key(buf, &disk_key, 0);
11125d4f98a2SYan Zheng 	else
11135d4f98a2SYan Zheng 		btrfs_node_key(buf, &disk_key, 0);
11145d4f98a2SYan Zheng 
11150f5053ebSGoldwyn Rodrigues 	if ((root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) && parent)
11165d4f98a2SYan Zheng 		parent_start = parent->start;
11175d4f98a2SYan Zheng 
11184d75f8a9SDavid Sterba 	cow = btrfs_alloc_tree_block(trans, root, parent_start,
11194d75f8a9SDavid Sterba 			root->root_key.objectid, &disk_key, level,
11204d75f8a9SDavid Sterba 			search_start, empty_size);
11216702ed49SChris Mason 	if (IS_ERR(cow))
11226702ed49SChris Mason 		return PTR_ERR(cow);
11236702ed49SChris Mason 
1124b4ce94deSChris Mason 	/* cow is set to blocking by btrfs_init_new_buffer */
1125b4ce94deSChris Mason 
112658e8012cSDavid Sterba 	copy_extent_buffer_full(cow, buf);
1127db94535dSChris Mason 	btrfs_set_header_bytenr(cow, cow->start);
11285f39d397SChris Mason 	btrfs_set_header_generation(cow, trans->transid);
11295d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
11305d4f98a2SYan Zheng 	btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
11315d4f98a2SYan Zheng 				     BTRFS_HEADER_FLAG_RELOC);
11325d4f98a2SYan Zheng 	if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
11335d4f98a2SYan Zheng 		btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
11345d4f98a2SYan Zheng 	else
11355f39d397SChris Mason 		btrfs_set_header_owner(cow, root->root_key.objectid);
11366702ed49SChris Mason 
11370b246afaSJeff Mahoney 	write_extent_buffer_fsid(cow, fs_info->fsid);
11382b82032cSYan Zheng 
1139be1a5564SMark Fasheh 	ret = update_ref_for_cow(trans, root, buf, cow, &last_ref);
1140b68dc2a9SMark Fasheh 	if (ret) {
114166642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
1142b68dc2a9SMark Fasheh 		return ret;
1143b68dc2a9SMark Fasheh 	}
11441a40e23bSZheng Yan 
114527cdeb70SMiao Xie 	if (test_bit(BTRFS_ROOT_REF_COWS, &root->state)) {
114683d4cfd4SJosef Bacik 		ret = btrfs_reloc_cow_block(trans, root, buf, cow);
114793314e3bSZhaolei 		if (ret) {
114866642832SJeff Mahoney 			btrfs_abort_transaction(trans, ret);
114983d4cfd4SJosef Bacik 			return ret;
115083d4cfd4SJosef Bacik 		}
115193314e3bSZhaolei 	}
11523fd0a558SYan, Zheng 
11536702ed49SChris Mason 	if (buf == root->node) {
1154925baeddSChris Mason 		WARN_ON(parent && parent != buf);
11555d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
11565d4f98a2SYan Zheng 		    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
11575d4f98a2SYan Zheng 			parent_start = buf->start;
1158925baeddSChris Mason 
11595f39d397SChris Mason 		extent_buffer_get(cow);
116090f8d62eSJan Schmidt 		tree_mod_log_set_root_pointer(root, cow, 1);
1161240f62c8SChris Mason 		rcu_assign_pointer(root->node, cow);
1162925baeddSChris Mason 
1163f0486c68SYan, Zheng 		btrfs_free_tree_block(trans, root, buf, parent_start,
11645581a51aSJan Schmidt 				      last_ref);
11655f39d397SChris Mason 		free_extent_buffer(buf);
11660b86a832SChris Mason 		add_root_to_dirty_list(root);
11676702ed49SChris Mason 	} else {
11685d4f98a2SYan Zheng 		WARN_ON(trans->transid != btrfs_header_generation(parent));
1169e09c2efeSDavid Sterba 		tree_mod_log_insert_key(parent, parent_slot,
1170c8cc6341SJosef Bacik 					MOD_LOG_KEY_REPLACE, GFP_NOFS);
11715f39d397SChris Mason 		btrfs_set_node_blockptr(parent, parent_slot,
1172db94535dSChris Mason 					cow->start);
117374493f7aSChris Mason 		btrfs_set_node_ptr_generation(parent, parent_slot,
117474493f7aSChris Mason 					      trans->transid);
11756702ed49SChris Mason 		btrfs_mark_buffer_dirty(parent);
11765de865eeSFilipe David Borba Manana 		if (last_ref) {
1177db7279a2SDavid Sterba 			ret = tree_mod_log_free_eb(buf);
11785de865eeSFilipe David Borba Manana 			if (ret) {
117966642832SJeff Mahoney 				btrfs_abort_transaction(trans, ret);
11805de865eeSFilipe David Borba Manana 				return ret;
11815de865eeSFilipe David Borba Manana 			}
11825de865eeSFilipe David Borba Manana 		}
1183f0486c68SYan, Zheng 		btrfs_free_tree_block(trans, root, buf, parent_start,
11845581a51aSJan Schmidt 				      last_ref);
11856702ed49SChris Mason 	}
1186925baeddSChris Mason 	if (unlock_orig)
1187925baeddSChris Mason 		btrfs_tree_unlock(buf);
11883083ee2eSJosef Bacik 	free_extent_buffer_stale(buf);
11896702ed49SChris Mason 	btrfs_mark_buffer_dirty(cow);
11906702ed49SChris Mason 	*cow_ret = cow;
11916702ed49SChris Mason 	return 0;
11926702ed49SChris Mason }
11936702ed49SChris Mason 
11945d9e75c4SJan Schmidt /*
11955d9e75c4SJan Schmidt  * returns the logical address of the oldest predecessor of the given root.
11965d9e75c4SJan Schmidt  * entries older than time_seq are ignored.
11975d9e75c4SJan Schmidt  */
1198*bcd24dabSDavid Sterba static struct tree_mod_elem *__tree_mod_log_oldest_root(
119930b0463aSJan Schmidt 		struct extent_buffer *eb_root, u64 time_seq)
12005d9e75c4SJan Schmidt {
12015d9e75c4SJan Schmidt 	struct tree_mod_elem *tm;
12025d9e75c4SJan Schmidt 	struct tree_mod_elem *found = NULL;
120330b0463aSJan Schmidt 	u64 root_logical = eb_root->start;
12045d9e75c4SJan Schmidt 	int looped = 0;
12055d9e75c4SJan Schmidt 
12065d9e75c4SJan Schmidt 	if (!time_seq)
120735a3621bSStefan Behrens 		return NULL;
12085d9e75c4SJan Schmidt 
12095d9e75c4SJan Schmidt 	/*
1210298cfd36SChandan Rajendra 	 * the very last operation that's logged for a root is the
1211298cfd36SChandan Rajendra 	 * replacement operation (if it is replaced at all). this has
1212298cfd36SChandan Rajendra 	 * the logical address of the *new* root, making it the very
1213298cfd36SChandan Rajendra 	 * first operation that's logged for this root.
12145d9e75c4SJan Schmidt 	 */
12155d9e75c4SJan Schmidt 	while (1) {
1216*bcd24dabSDavid Sterba 		tm = tree_mod_log_search_oldest(eb_root->fs_info, root_logical,
12175d9e75c4SJan Schmidt 						time_seq);
12185d9e75c4SJan Schmidt 		if (!looped && !tm)
121935a3621bSStefan Behrens 			return NULL;
12205d9e75c4SJan Schmidt 		/*
122128da9fb4SJan Schmidt 		 * if there are no tree operation for the oldest root, we simply
122228da9fb4SJan Schmidt 		 * return it. this should only happen if that (old) root is at
122328da9fb4SJan Schmidt 		 * level 0.
12245d9e75c4SJan Schmidt 		 */
122528da9fb4SJan Schmidt 		if (!tm)
122628da9fb4SJan Schmidt 			break;
12275d9e75c4SJan Schmidt 
122828da9fb4SJan Schmidt 		/*
122928da9fb4SJan Schmidt 		 * if there's an operation that's not a root replacement, we
123028da9fb4SJan Schmidt 		 * found the oldest version of our root. normally, we'll find a
123128da9fb4SJan Schmidt 		 * MOD_LOG_KEY_REMOVE_WHILE_FREEING operation here.
123228da9fb4SJan Schmidt 		 */
12335d9e75c4SJan Schmidt 		if (tm->op != MOD_LOG_ROOT_REPLACE)
12345d9e75c4SJan Schmidt 			break;
12355d9e75c4SJan Schmidt 
12365d9e75c4SJan Schmidt 		found = tm;
12375d9e75c4SJan Schmidt 		root_logical = tm->old_root.logical;
12385d9e75c4SJan Schmidt 		looped = 1;
12395d9e75c4SJan Schmidt 	}
12405d9e75c4SJan Schmidt 
1241a95236d9SJan Schmidt 	/* if there's no old root to return, return what we found instead */
1242a95236d9SJan Schmidt 	if (!found)
1243a95236d9SJan Schmidt 		found = tm;
1244a95236d9SJan Schmidt 
12455d9e75c4SJan Schmidt 	return found;
12465d9e75c4SJan Schmidt }
12475d9e75c4SJan Schmidt 
12485d9e75c4SJan Schmidt /*
12495d9e75c4SJan Schmidt  * tm is a pointer to the first operation to rewind within eb. then, all
125001327610SNicholas D Steeves  * previous operations will be rewound (until we reach something older than
12515d9e75c4SJan Schmidt  * time_seq).
12525d9e75c4SJan Schmidt  */
12535d9e75c4SJan Schmidt static void
1254f1ca7e98SJosef Bacik __tree_mod_log_rewind(struct btrfs_fs_info *fs_info, struct extent_buffer *eb,
1255f1ca7e98SJosef Bacik 		      u64 time_seq, struct tree_mod_elem *first_tm)
12565d9e75c4SJan Schmidt {
12575d9e75c4SJan Schmidt 	u32 n;
12585d9e75c4SJan Schmidt 	struct rb_node *next;
12595d9e75c4SJan Schmidt 	struct tree_mod_elem *tm = first_tm;
12605d9e75c4SJan Schmidt 	unsigned long o_dst;
12615d9e75c4SJan Schmidt 	unsigned long o_src;
12625d9e75c4SJan Schmidt 	unsigned long p_size = sizeof(struct btrfs_key_ptr);
12635d9e75c4SJan Schmidt 
12645d9e75c4SJan Schmidt 	n = btrfs_header_nritems(eb);
1265f1ca7e98SJosef Bacik 	tree_mod_log_read_lock(fs_info);
1266097b8a7cSJan Schmidt 	while (tm && tm->seq >= time_seq) {
12675d9e75c4SJan Schmidt 		/*
12685d9e75c4SJan Schmidt 		 * all the operations are recorded with the operator used for
12695d9e75c4SJan Schmidt 		 * the modification. as we're going backwards, we do the
12705d9e75c4SJan Schmidt 		 * opposite of each operation here.
12715d9e75c4SJan Schmidt 		 */
12725d9e75c4SJan Schmidt 		switch (tm->op) {
12735d9e75c4SJan Schmidt 		case MOD_LOG_KEY_REMOVE_WHILE_FREEING:
12745d9e75c4SJan Schmidt 			BUG_ON(tm->slot < n);
12751c697d4aSEric Sandeen 			/* Fallthrough */
127695c80bb1SLiu Bo 		case MOD_LOG_KEY_REMOVE_WHILE_MOVING:
12774c3e6969SChris Mason 		case MOD_LOG_KEY_REMOVE:
12785d9e75c4SJan Schmidt 			btrfs_set_node_key(eb, &tm->key, tm->slot);
12795d9e75c4SJan Schmidt 			btrfs_set_node_blockptr(eb, tm->slot, tm->blockptr);
12805d9e75c4SJan Schmidt 			btrfs_set_node_ptr_generation(eb, tm->slot,
12815d9e75c4SJan Schmidt 						      tm->generation);
12824c3e6969SChris Mason 			n++;
12835d9e75c4SJan Schmidt 			break;
12845d9e75c4SJan Schmidt 		case MOD_LOG_KEY_REPLACE:
12855d9e75c4SJan Schmidt 			BUG_ON(tm->slot >= n);
12865d9e75c4SJan Schmidt 			btrfs_set_node_key(eb, &tm->key, tm->slot);
12875d9e75c4SJan Schmidt 			btrfs_set_node_blockptr(eb, tm->slot, tm->blockptr);
12885d9e75c4SJan Schmidt 			btrfs_set_node_ptr_generation(eb, tm->slot,
12895d9e75c4SJan Schmidt 						      tm->generation);
12905d9e75c4SJan Schmidt 			break;
12915d9e75c4SJan Schmidt 		case MOD_LOG_KEY_ADD:
129219956c7eSJan Schmidt 			/* if a move operation is needed it's in the log */
12935d9e75c4SJan Schmidt 			n--;
12945d9e75c4SJan Schmidt 			break;
12955d9e75c4SJan Schmidt 		case MOD_LOG_MOVE_KEYS:
1296c3193108SJan Schmidt 			o_dst = btrfs_node_key_ptr_offset(tm->slot);
1297c3193108SJan Schmidt 			o_src = btrfs_node_key_ptr_offset(tm->move.dst_slot);
1298c3193108SJan Schmidt 			memmove_extent_buffer(eb, o_dst, o_src,
12995d9e75c4SJan Schmidt 					      tm->move.nr_items * p_size);
13005d9e75c4SJan Schmidt 			break;
13015d9e75c4SJan Schmidt 		case MOD_LOG_ROOT_REPLACE:
13025d9e75c4SJan Schmidt 			/*
13035d9e75c4SJan Schmidt 			 * this operation is special. for roots, this must be
13045d9e75c4SJan Schmidt 			 * handled explicitly before rewinding.
13055d9e75c4SJan Schmidt 			 * for non-roots, this operation may exist if the node
13065d9e75c4SJan Schmidt 			 * was a root: root A -> child B; then A gets empty and
13075d9e75c4SJan Schmidt 			 * B is promoted to the new root. in the mod log, we'll
13085d9e75c4SJan Schmidt 			 * have a root-replace operation for B, a tree block
13095d9e75c4SJan Schmidt 			 * that is no root. we simply ignore that operation.
13105d9e75c4SJan Schmidt 			 */
13115d9e75c4SJan Schmidt 			break;
13125d9e75c4SJan Schmidt 		}
13135d9e75c4SJan Schmidt 		next = rb_next(&tm->node);
13145d9e75c4SJan Schmidt 		if (!next)
13155d9e75c4SJan Schmidt 			break;
13166b4df8b6SGeliang Tang 		tm = rb_entry(next, struct tree_mod_elem, node);
1317298cfd36SChandan Rajendra 		if (tm->logical != first_tm->logical)
13185d9e75c4SJan Schmidt 			break;
13195d9e75c4SJan Schmidt 	}
1320f1ca7e98SJosef Bacik 	tree_mod_log_read_unlock(fs_info);
13215d9e75c4SJan Schmidt 	btrfs_set_header_nritems(eb, n);
13225d9e75c4SJan Schmidt }
13235d9e75c4SJan Schmidt 
132447fb091fSJan Schmidt /*
132501327610SNicholas D Steeves  * Called with eb read locked. If the buffer cannot be rewound, the same buffer
132647fb091fSJan Schmidt  * is returned. If rewind operations happen, a fresh buffer is returned. The
132747fb091fSJan Schmidt  * returned buffer is always read-locked. If the returned buffer is not the
132847fb091fSJan Schmidt  * input buffer, the lock on the input buffer is released and the input buffer
132947fb091fSJan Schmidt  * is freed (its refcount is decremented).
133047fb091fSJan Schmidt  */
13315d9e75c4SJan Schmidt static struct extent_buffer *
13329ec72677SJosef Bacik tree_mod_log_rewind(struct btrfs_fs_info *fs_info, struct btrfs_path *path,
13339ec72677SJosef Bacik 		    struct extent_buffer *eb, u64 time_seq)
13345d9e75c4SJan Schmidt {
13355d9e75c4SJan Schmidt 	struct extent_buffer *eb_rewin;
13365d9e75c4SJan Schmidt 	struct tree_mod_elem *tm;
13375d9e75c4SJan Schmidt 
13385d9e75c4SJan Schmidt 	if (!time_seq)
13395d9e75c4SJan Schmidt 		return eb;
13405d9e75c4SJan Schmidt 
13415d9e75c4SJan Schmidt 	if (btrfs_header_level(eb) == 0)
13425d9e75c4SJan Schmidt 		return eb;
13435d9e75c4SJan Schmidt 
13445d9e75c4SJan Schmidt 	tm = tree_mod_log_search(fs_info, eb->start, time_seq);
13455d9e75c4SJan Schmidt 	if (!tm)
13465d9e75c4SJan Schmidt 		return eb;
13475d9e75c4SJan Schmidt 
13489ec72677SJosef Bacik 	btrfs_set_path_blocking(path);
13499ec72677SJosef Bacik 	btrfs_set_lock_blocking_rw(eb, BTRFS_READ_LOCK);
13509ec72677SJosef Bacik 
13515d9e75c4SJan Schmidt 	if (tm->op == MOD_LOG_KEY_REMOVE_WHILE_FREEING) {
13525d9e75c4SJan Schmidt 		BUG_ON(tm->slot != 0);
1353da17066cSJeff Mahoney 		eb_rewin = alloc_dummy_extent_buffer(fs_info, eb->start);
1354db7f3436SJosef Bacik 		if (!eb_rewin) {
13559ec72677SJosef Bacik 			btrfs_tree_read_unlock_blocking(eb);
1356db7f3436SJosef Bacik 			free_extent_buffer(eb);
1357db7f3436SJosef Bacik 			return NULL;
1358db7f3436SJosef Bacik 		}
13595d9e75c4SJan Schmidt 		btrfs_set_header_bytenr(eb_rewin, eb->start);
13605d9e75c4SJan Schmidt 		btrfs_set_header_backref_rev(eb_rewin,
13615d9e75c4SJan Schmidt 					     btrfs_header_backref_rev(eb));
13625d9e75c4SJan Schmidt 		btrfs_set_header_owner(eb_rewin, btrfs_header_owner(eb));
1363c3193108SJan Schmidt 		btrfs_set_header_level(eb_rewin, btrfs_header_level(eb));
13645d9e75c4SJan Schmidt 	} else {
13655d9e75c4SJan Schmidt 		eb_rewin = btrfs_clone_extent_buffer(eb);
1366db7f3436SJosef Bacik 		if (!eb_rewin) {
13679ec72677SJosef Bacik 			btrfs_tree_read_unlock_blocking(eb);
1368db7f3436SJosef Bacik 			free_extent_buffer(eb);
1369db7f3436SJosef Bacik 			return NULL;
1370db7f3436SJosef Bacik 		}
13715d9e75c4SJan Schmidt 	}
13725d9e75c4SJan Schmidt 
13739ec72677SJosef Bacik 	btrfs_clear_path_blocking(path, NULL, BTRFS_READ_LOCK);
13749ec72677SJosef Bacik 	btrfs_tree_read_unlock_blocking(eb);
13755d9e75c4SJan Schmidt 	free_extent_buffer(eb);
13765d9e75c4SJan Schmidt 
137747fb091fSJan Schmidt 	extent_buffer_get(eb_rewin);
137847fb091fSJan Schmidt 	btrfs_tree_read_lock(eb_rewin);
1379f1ca7e98SJosef Bacik 	__tree_mod_log_rewind(fs_info, eb_rewin, time_seq, tm);
138057911b8bSJan Schmidt 	WARN_ON(btrfs_header_nritems(eb_rewin) >
1381da17066cSJeff Mahoney 		BTRFS_NODEPTRS_PER_BLOCK(fs_info));
13825d9e75c4SJan Schmidt 
13835d9e75c4SJan Schmidt 	return eb_rewin;
13845d9e75c4SJan Schmidt }
13855d9e75c4SJan Schmidt 
13868ba97a15SJan Schmidt /*
13878ba97a15SJan Schmidt  * get_old_root() rewinds the state of @root's root node to the given @time_seq
13888ba97a15SJan Schmidt  * value. If there are no changes, the current root->root_node is returned. If
13898ba97a15SJan Schmidt  * anything changed in between, there's a fresh buffer allocated on which the
13908ba97a15SJan Schmidt  * rewind operations are done. In any case, the returned buffer is read locked.
13918ba97a15SJan Schmidt  * Returns NULL on error (with no locks held).
13928ba97a15SJan Schmidt  */
13935d9e75c4SJan Schmidt static inline struct extent_buffer *
13945d9e75c4SJan Schmidt get_old_root(struct btrfs_root *root, u64 time_seq)
13955d9e75c4SJan Schmidt {
13960b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
13975d9e75c4SJan Schmidt 	struct tree_mod_elem *tm;
139830b0463aSJan Schmidt 	struct extent_buffer *eb = NULL;
139930b0463aSJan Schmidt 	struct extent_buffer *eb_root;
14007bfdcf7fSLiu Bo 	struct extent_buffer *old;
1401a95236d9SJan Schmidt 	struct tree_mod_root *old_root = NULL;
14024325edd0SChris Mason 	u64 old_generation = 0;
1403a95236d9SJan Schmidt 	u64 logical;
14045d9e75c4SJan Schmidt 
140530b0463aSJan Schmidt 	eb_root = btrfs_read_lock_root_node(root);
1406*bcd24dabSDavid Sterba 	tm = __tree_mod_log_oldest_root(eb_root, time_seq);
14075d9e75c4SJan Schmidt 	if (!tm)
140830b0463aSJan Schmidt 		return eb_root;
14095d9e75c4SJan Schmidt 
1410a95236d9SJan Schmidt 	if (tm->op == MOD_LOG_ROOT_REPLACE) {
14115d9e75c4SJan Schmidt 		old_root = &tm->old_root;
14125d9e75c4SJan Schmidt 		old_generation = tm->generation;
1413a95236d9SJan Schmidt 		logical = old_root->logical;
1414a95236d9SJan Schmidt 	} else {
141530b0463aSJan Schmidt 		logical = eb_root->start;
1416a95236d9SJan Schmidt 	}
14175d9e75c4SJan Schmidt 
14180b246afaSJeff Mahoney 	tm = tree_mod_log_search(fs_info, logical, time_seq);
1419834328a8SJan Schmidt 	if (old_root && tm && tm->op != MOD_LOG_KEY_REMOVE_WHILE_FREEING) {
142030b0463aSJan Schmidt 		btrfs_tree_read_unlock(eb_root);
142130b0463aSJan Schmidt 		free_extent_buffer(eb_root);
14222ff7e61eSJeff Mahoney 		old = read_tree_block(fs_info, logical, 0);
142364c043deSLiu Bo 		if (WARN_ON(IS_ERR(old) || !extent_buffer_uptodate(old))) {
142464c043deSLiu Bo 			if (!IS_ERR(old))
1425416bc658SJosef Bacik 				free_extent_buffer(old);
14260b246afaSJeff Mahoney 			btrfs_warn(fs_info,
14270b246afaSJeff Mahoney 				   "failed to read tree block %llu from get_old_root",
14280b246afaSJeff Mahoney 				   logical);
1429834328a8SJan Schmidt 		} else {
14307bfdcf7fSLiu Bo 			eb = btrfs_clone_extent_buffer(old);
14317bfdcf7fSLiu Bo 			free_extent_buffer(old);
1432834328a8SJan Schmidt 		}
1433834328a8SJan Schmidt 	} else if (old_root) {
143430b0463aSJan Schmidt 		btrfs_tree_read_unlock(eb_root);
143530b0463aSJan Schmidt 		free_extent_buffer(eb_root);
14360b246afaSJeff Mahoney 		eb = alloc_dummy_extent_buffer(fs_info, logical);
1437834328a8SJan Schmidt 	} else {
14389ec72677SJosef Bacik 		btrfs_set_lock_blocking_rw(eb_root, BTRFS_READ_LOCK);
143930b0463aSJan Schmidt 		eb = btrfs_clone_extent_buffer(eb_root);
14409ec72677SJosef Bacik 		btrfs_tree_read_unlock_blocking(eb_root);
144130b0463aSJan Schmidt 		free_extent_buffer(eb_root);
1442834328a8SJan Schmidt 	}
1443834328a8SJan Schmidt 
14448ba97a15SJan Schmidt 	if (!eb)
14458ba97a15SJan Schmidt 		return NULL;
1446d6381084SJan Schmidt 	extent_buffer_get(eb);
14478ba97a15SJan Schmidt 	btrfs_tree_read_lock(eb);
1448a95236d9SJan Schmidt 	if (old_root) {
14495d9e75c4SJan Schmidt 		btrfs_set_header_bytenr(eb, eb->start);
14505d9e75c4SJan Schmidt 		btrfs_set_header_backref_rev(eb, BTRFS_MIXED_BACKREF_REV);
145130b0463aSJan Schmidt 		btrfs_set_header_owner(eb, btrfs_header_owner(eb_root));
14525d9e75c4SJan Schmidt 		btrfs_set_header_level(eb, old_root->level);
14535d9e75c4SJan Schmidt 		btrfs_set_header_generation(eb, old_generation);
1454a95236d9SJan Schmidt 	}
145528da9fb4SJan Schmidt 	if (tm)
14560b246afaSJeff Mahoney 		__tree_mod_log_rewind(fs_info, eb, time_seq, tm);
145728da9fb4SJan Schmidt 	else
145828da9fb4SJan Schmidt 		WARN_ON(btrfs_header_level(eb) != 0);
14590b246afaSJeff Mahoney 	WARN_ON(btrfs_header_nritems(eb) > BTRFS_NODEPTRS_PER_BLOCK(fs_info));
14605d9e75c4SJan Schmidt 
14615d9e75c4SJan Schmidt 	return eb;
14625d9e75c4SJan Schmidt }
14635d9e75c4SJan Schmidt 
14645b6602e7SJan Schmidt int btrfs_old_root_level(struct btrfs_root *root, u64 time_seq)
14655b6602e7SJan Schmidt {
14665b6602e7SJan Schmidt 	struct tree_mod_elem *tm;
14675b6602e7SJan Schmidt 	int level;
146830b0463aSJan Schmidt 	struct extent_buffer *eb_root = btrfs_root_node(root);
14695b6602e7SJan Schmidt 
1470*bcd24dabSDavid Sterba 	tm = __tree_mod_log_oldest_root(eb_root, time_seq);
14715b6602e7SJan Schmidt 	if (tm && tm->op == MOD_LOG_ROOT_REPLACE) {
14725b6602e7SJan Schmidt 		level = tm->old_root.level;
14735b6602e7SJan Schmidt 	} else {
147430b0463aSJan Schmidt 		level = btrfs_header_level(eb_root);
14755b6602e7SJan Schmidt 	}
147630b0463aSJan Schmidt 	free_extent_buffer(eb_root);
14775b6602e7SJan Schmidt 
14785b6602e7SJan Schmidt 	return level;
14795b6602e7SJan Schmidt }
14805b6602e7SJan Schmidt 
14815d4f98a2SYan Zheng static inline int should_cow_block(struct btrfs_trans_handle *trans,
14825d4f98a2SYan Zheng 				   struct btrfs_root *root,
14835d4f98a2SYan Zheng 				   struct extent_buffer *buf)
14845d4f98a2SYan Zheng {
1485f5ee5c9aSJeff Mahoney 	if (btrfs_is_testing(root->fs_info))
1486faa2dbf0SJosef Bacik 		return 0;
1487fccb84c9SDavid Sterba 
1488f1ebcc74SLiu Bo 	/* ensure we can see the force_cow */
1489f1ebcc74SLiu Bo 	smp_rmb();
1490f1ebcc74SLiu Bo 
1491f1ebcc74SLiu Bo 	/*
1492f1ebcc74SLiu Bo 	 * We do not need to cow a block if
1493f1ebcc74SLiu Bo 	 * 1) this block is not created or changed in this transaction;
1494f1ebcc74SLiu Bo 	 * 2) this block does not belong to TREE_RELOC tree;
1495f1ebcc74SLiu Bo 	 * 3) the root is not forced COW.
1496f1ebcc74SLiu Bo 	 *
1497f1ebcc74SLiu Bo 	 * What is forced COW:
149801327610SNicholas D Steeves 	 *    when we create snapshot during committing the transaction,
1499f1ebcc74SLiu Bo 	 *    after we've finished coping src root, we must COW the shared
1500f1ebcc74SLiu Bo 	 *    block to ensure the metadata consistency.
1501f1ebcc74SLiu Bo 	 */
15025d4f98a2SYan Zheng 	if (btrfs_header_generation(buf) == trans->transid &&
15035d4f98a2SYan Zheng 	    !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN) &&
15045d4f98a2SYan Zheng 	    !(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
1505f1ebcc74SLiu Bo 	      btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)) &&
150627cdeb70SMiao Xie 	    !test_bit(BTRFS_ROOT_FORCE_COW, &root->state))
15075d4f98a2SYan Zheng 		return 0;
15085d4f98a2SYan Zheng 	return 1;
15095d4f98a2SYan Zheng }
15105d4f98a2SYan Zheng 
1511d352ac68SChris Mason /*
1512d352ac68SChris Mason  * cows a single block, see __btrfs_cow_block for the real work.
151301327610SNicholas D Steeves  * This version of it has extra checks so that a block isn't COWed more than
1514d352ac68SChris Mason  * once per transaction, as long as it hasn't been written yet
1515d352ac68SChris Mason  */
1516d397712bSChris Mason noinline int btrfs_cow_block(struct btrfs_trans_handle *trans,
15175f39d397SChris Mason 		    struct btrfs_root *root, struct extent_buffer *buf,
15185f39d397SChris Mason 		    struct extent_buffer *parent, int parent_slot,
15199fa8cfe7SChris Mason 		    struct extent_buffer **cow_ret)
152002217ed2SChris Mason {
15210b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
15226702ed49SChris Mason 	u64 search_start;
1523f510cfecSChris Mason 	int ret;
1524dc17ff8fSChris Mason 
15250b246afaSJeff Mahoney 	if (trans->transaction != fs_info->running_transaction)
152631b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "trans %llu running %llu\n",
1527c1c9ff7cSGeert Uytterhoeven 		       trans->transid,
15280b246afaSJeff Mahoney 		       fs_info->running_transaction->transid);
152931b1a2bdSJulia Lawall 
15300b246afaSJeff Mahoney 	if (trans->transid != fs_info->generation)
153131b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "trans %llu running %llu\n",
15320b246afaSJeff Mahoney 		       trans->transid, fs_info->generation);
1533dc17ff8fSChris Mason 
15345d4f98a2SYan Zheng 	if (!should_cow_block(trans, root, buf)) {
153564c12921SJeff Mahoney 		trans->dirty = true;
153602217ed2SChris Mason 		*cow_ret = buf;
153702217ed2SChris Mason 		return 0;
153802217ed2SChris Mason 	}
1539c487685dSChris Mason 
1540ee22184bSByongho Lee 	search_start = buf->start & ~((u64)SZ_1G - 1);
1541b4ce94deSChris Mason 
1542b4ce94deSChris Mason 	if (parent)
1543b4ce94deSChris Mason 		btrfs_set_lock_blocking(parent);
1544b4ce94deSChris Mason 	btrfs_set_lock_blocking(buf);
1545b4ce94deSChris Mason 
1546f510cfecSChris Mason 	ret = __btrfs_cow_block(trans, root, buf, parent,
15479fa8cfe7SChris Mason 				 parent_slot, cow_ret, search_start, 0);
15481abe9b8aSliubo 
15491abe9b8aSliubo 	trace_btrfs_cow_block(root, buf, *cow_ret);
15501abe9b8aSliubo 
1551f510cfecSChris Mason 	return ret;
15522c90e5d6SChris Mason }
15536702ed49SChris Mason 
1554d352ac68SChris Mason /*
1555d352ac68SChris Mason  * helper function for defrag to decide if two blocks pointed to by a
1556d352ac68SChris Mason  * node are actually close by
1557d352ac68SChris Mason  */
15586b80053dSChris Mason static int close_blocks(u64 blocknr, u64 other, u32 blocksize)
15596702ed49SChris Mason {
15606b80053dSChris Mason 	if (blocknr < other && other - (blocknr + blocksize) < 32768)
15616702ed49SChris Mason 		return 1;
15626b80053dSChris Mason 	if (blocknr > other && blocknr - (other + blocksize) < 32768)
15636702ed49SChris Mason 		return 1;
156402217ed2SChris Mason 	return 0;
156502217ed2SChris Mason }
156602217ed2SChris Mason 
1567081e9573SChris Mason /*
1568081e9573SChris Mason  * compare two keys in a memcmp fashion
1569081e9573SChris Mason  */
1570310712b2SOmar Sandoval static int comp_keys(const struct btrfs_disk_key *disk,
1571310712b2SOmar Sandoval 		     const struct btrfs_key *k2)
1572081e9573SChris Mason {
1573081e9573SChris Mason 	struct btrfs_key k1;
1574081e9573SChris Mason 
1575081e9573SChris Mason 	btrfs_disk_key_to_cpu(&k1, disk);
1576081e9573SChris Mason 
157720736abaSDiego Calleja 	return btrfs_comp_cpu_keys(&k1, k2);
1578081e9573SChris Mason }
1579081e9573SChris Mason 
1580f3465ca4SJosef Bacik /*
1581f3465ca4SJosef Bacik  * same as comp_keys only with two btrfs_key's
1582f3465ca4SJosef Bacik  */
1583310712b2SOmar Sandoval int btrfs_comp_cpu_keys(const struct btrfs_key *k1, const struct btrfs_key *k2)
1584f3465ca4SJosef Bacik {
1585f3465ca4SJosef Bacik 	if (k1->objectid > k2->objectid)
1586f3465ca4SJosef Bacik 		return 1;
1587f3465ca4SJosef Bacik 	if (k1->objectid < k2->objectid)
1588f3465ca4SJosef Bacik 		return -1;
1589f3465ca4SJosef Bacik 	if (k1->type > k2->type)
1590f3465ca4SJosef Bacik 		return 1;
1591f3465ca4SJosef Bacik 	if (k1->type < k2->type)
1592f3465ca4SJosef Bacik 		return -1;
1593f3465ca4SJosef Bacik 	if (k1->offset > k2->offset)
1594f3465ca4SJosef Bacik 		return 1;
1595f3465ca4SJosef Bacik 	if (k1->offset < k2->offset)
1596f3465ca4SJosef Bacik 		return -1;
1597f3465ca4SJosef Bacik 	return 0;
1598f3465ca4SJosef Bacik }
1599081e9573SChris Mason 
1600d352ac68SChris Mason /*
1601d352ac68SChris Mason  * this is used by the defrag code to go through all the
1602d352ac68SChris Mason  * leaves pointed to by a node and reallocate them so that
1603d352ac68SChris Mason  * disk order is close to key order
1604d352ac68SChris Mason  */
16056702ed49SChris Mason int btrfs_realloc_node(struct btrfs_trans_handle *trans,
16065f39d397SChris Mason 		       struct btrfs_root *root, struct extent_buffer *parent,
1607de78b51aSEric Sandeen 		       int start_slot, u64 *last_ret,
1608a6b6e75eSChris Mason 		       struct btrfs_key *progress)
16096702ed49SChris Mason {
16100b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
16116b80053dSChris Mason 	struct extent_buffer *cur;
16126702ed49SChris Mason 	u64 blocknr;
1613ca7a79adSChris Mason 	u64 gen;
1614e9d0b13bSChris Mason 	u64 search_start = *last_ret;
1615e9d0b13bSChris Mason 	u64 last_block = 0;
16166702ed49SChris Mason 	u64 other;
16176702ed49SChris Mason 	u32 parent_nritems;
16186702ed49SChris Mason 	int end_slot;
16196702ed49SChris Mason 	int i;
16206702ed49SChris Mason 	int err = 0;
1621f2183bdeSChris Mason 	int parent_level;
16226b80053dSChris Mason 	int uptodate;
16236b80053dSChris Mason 	u32 blocksize;
1624081e9573SChris Mason 	int progress_passed = 0;
1625081e9573SChris Mason 	struct btrfs_disk_key disk_key;
16266702ed49SChris Mason 
16275708b959SChris Mason 	parent_level = btrfs_header_level(parent);
16285708b959SChris Mason 
16290b246afaSJeff Mahoney 	WARN_ON(trans->transaction != fs_info->running_transaction);
16300b246afaSJeff Mahoney 	WARN_ON(trans->transid != fs_info->generation);
163186479a04SChris Mason 
16326b80053dSChris Mason 	parent_nritems = btrfs_header_nritems(parent);
16330b246afaSJeff Mahoney 	blocksize = fs_info->nodesize;
16345dfe2be7SFilipe Manana 	end_slot = parent_nritems - 1;
16356702ed49SChris Mason 
16365dfe2be7SFilipe Manana 	if (parent_nritems <= 1)
16376702ed49SChris Mason 		return 0;
16386702ed49SChris Mason 
1639b4ce94deSChris Mason 	btrfs_set_lock_blocking(parent);
1640b4ce94deSChris Mason 
16415dfe2be7SFilipe Manana 	for (i = start_slot; i <= end_slot; i++) {
16426702ed49SChris Mason 		int close = 1;
1643a6b6e75eSChris Mason 
1644081e9573SChris Mason 		btrfs_node_key(parent, &disk_key, i);
1645081e9573SChris Mason 		if (!progress_passed && comp_keys(&disk_key, progress) < 0)
1646081e9573SChris Mason 			continue;
1647081e9573SChris Mason 
1648081e9573SChris Mason 		progress_passed = 1;
16496b80053dSChris Mason 		blocknr = btrfs_node_blockptr(parent, i);
1650ca7a79adSChris Mason 		gen = btrfs_node_ptr_generation(parent, i);
1651e9d0b13bSChris Mason 		if (last_block == 0)
1652e9d0b13bSChris Mason 			last_block = blocknr;
16535708b959SChris Mason 
16546702ed49SChris Mason 		if (i > 0) {
16556b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i - 1);
16566b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
16576702ed49SChris Mason 		}
16585dfe2be7SFilipe Manana 		if (!close && i < end_slot) {
16596b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i + 1);
16606b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
16616702ed49SChris Mason 		}
1662e9d0b13bSChris Mason 		if (close) {
1663e9d0b13bSChris Mason 			last_block = blocknr;
16646702ed49SChris Mason 			continue;
1665e9d0b13bSChris Mason 		}
16666702ed49SChris Mason 
16670b246afaSJeff Mahoney 		cur = find_extent_buffer(fs_info, blocknr);
16686b80053dSChris Mason 		if (cur)
1669b9fab919SChris Mason 			uptodate = btrfs_buffer_uptodate(cur, gen, 0);
16706b80053dSChris Mason 		else
16716b80053dSChris Mason 			uptodate = 0;
16725708b959SChris Mason 		if (!cur || !uptodate) {
16736b80053dSChris Mason 			if (!cur) {
16742ff7e61eSJeff Mahoney 				cur = read_tree_block(fs_info, blocknr, gen);
167564c043deSLiu Bo 				if (IS_ERR(cur)) {
167664c043deSLiu Bo 					return PTR_ERR(cur);
167764c043deSLiu Bo 				} else if (!extent_buffer_uptodate(cur)) {
1678416bc658SJosef Bacik 					free_extent_buffer(cur);
167997d9a8a4STsutomu Itoh 					return -EIO;
1680416bc658SJosef Bacik 				}
16816b80053dSChris Mason 			} else if (!uptodate) {
1682018642a1STsutomu Itoh 				err = btrfs_read_buffer(cur, gen);
1683018642a1STsutomu Itoh 				if (err) {
1684018642a1STsutomu Itoh 					free_extent_buffer(cur);
1685018642a1STsutomu Itoh 					return err;
1686018642a1STsutomu Itoh 				}
16876702ed49SChris Mason 			}
1688f2183bdeSChris Mason 		}
1689e9d0b13bSChris Mason 		if (search_start == 0)
16906b80053dSChris Mason 			search_start = last_block;
1691e9d0b13bSChris Mason 
1692e7a84565SChris Mason 		btrfs_tree_lock(cur);
1693b4ce94deSChris Mason 		btrfs_set_lock_blocking(cur);
16946b80053dSChris Mason 		err = __btrfs_cow_block(trans, root, cur, parent, i,
1695e7a84565SChris Mason 					&cur, search_start,
16966b80053dSChris Mason 					min(16 * blocksize,
16979fa8cfe7SChris Mason 					    (end_slot - i) * blocksize));
1698252c38f0SYan 		if (err) {
1699e7a84565SChris Mason 			btrfs_tree_unlock(cur);
17006b80053dSChris Mason 			free_extent_buffer(cur);
17016702ed49SChris Mason 			break;
1702252c38f0SYan 		}
1703e7a84565SChris Mason 		search_start = cur->start;
1704e7a84565SChris Mason 		last_block = cur->start;
1705f2183bdeSChris Mason 		*last_ret = search_start;
1706e7a84565SChris Mason 		btrfs_tree_unlock(cur);
1707e7a84565SChris Mason 		free_extent_buffer(cur);
17086702ed49SChris Mason 	}
17096702ed49SChris Mason 	return err;
17106702ed49SChris Mason }
17116702ed49SChris Mason 
171274123bd7SChris Mason /*
17135f39d397SChris Mason  * search for key in the extent_buffer.  The items start at offset p,
17145f39d397SChris Mason  * and they are item_size apart.  There are 'max' items in p.
17155f39d397SChris Mason  *
171674123bd7SChris Mason  * the slot in the array is returned via slot, and it points to
171774123bd7SChris Mason  * the place where you would insert key if it is not found in
171874123bd7SChris Mason  * the array.
171974123bd7SChris Mason  *
172074123bd7SChris Mason  * slot may point to max if the key is bigger than all of the keys
172174123bd7SChris Mason  */
1722e02119d5SChris Mason static noinline int generic_bin_search(struct extent_buffer *eb,
1723310712b2SOmar Sandoval 				       unsigned long p, int item_size,
1724310712b2SOmar Sandoval 				       const struct btrfs_key *key,
1725be0e5c09SChris Mason 				       int max, int *slot)
1726be0e5c09SChris Mason {
1727be0e5c09SChris Mason 	int low = 0;
1728be0e5c09SChris Mason 	int high = max;
1729be0e5c09SChris Mason 	int mid;
1730be0e5c09SChris Mason 	int ret;
1731479965d6SChris Mason 	struct btrfs_disk_key *tmp = NULL;
17325f39d397SChris Mason 	struct btrfs_disk_key unaligned;
17335f39d397SChris Mason 	unsigned long offset;
17345f39d397SChris Mason 	char *kaddr = NULL;
17355f39d397SChris Mason 	unsigned long map_start = 0;
17365f39d397SChris Mason 	unsigned long map_len = 0;
1737479965d6SChris Mason 	int err;
1738be0e5c09SChris Mason 
17395e24e9afSLiu Bo 	if (low > high) {
17405e24e9afSLiu Bo 		btrfs_err(eb->fs_info,
17415e24e9afSLiu Bo 		 "%s: low (%d) > high (%d) eb %llu owner %llu level %d",
17425e24e9afSLiu Bo 			  __func__, low, high, eb->start,
17435e24e9afSLiu Bo 			  btrfs_header_owner(eb), btrfs_header_level(eb));
17445e24e9afSLiu Bo 		return -EINVAL;
17455e24e9afSLiu Bo 	}
17465e24e9afSLiu Bo 
1747be0e5c09SChris Mason 	while (low < high) {
1748be0e5c09SChris Mason 		mid = (low + high) / 2;
17495f39d397SChris Mason 		offset = p + mid * item_size;
17505f39d397SChris Mason 
1751a6591715SChris Mason 		if (!kaddr || offset < map_start ||
17525f39d397SChris Mason 		    (offset + sizeof(struct btrfs_disk_key)) >
17535f39d397SChris Mason 		    map_start + map_len) {
1754934d375bSChris Mason 
1755934d375bSChris Mason 			err = map_private_extent_buffer(eb, offset,
1756479965d6SChris Mason 						sizeof(struct btrfs_disk_key),
1757a6591715SChris Mason 						&kaddr, &map_start, &map_len);
17585f39d397SChris Mason 
1759479965d6SChris Mason 			if (!err) {
1760479965d6SChris Mason 				tmp = (struct btrfs_disk_key *)(kaddr + offset -
1761479965d6SChris Mason 							map_start);
1762415b35a5SLiu Bo 			} else if (err == 1) {
17635f39d397SChris Mason 				read_extent_buffer(eb, &unaligned,
17645f39d397SChris Mason 						   offset, sizeof(unaligned));
17655f39d397SChris Mason 				tmp = &unaligned;
1766415b35a5SLiu Bo 			} else {
1767415b35a5SLiu Bo 				return err;
1768479965d6SChris Mason 			}
1769479965d6SChris Mason 
17705f39d397SChris Mason 		} else {
17715f39d397SChris Mason 			tmp = (struct btrfs_disk_key *)(kaddr + offset -
17725f39d397SChris Mason 							map_start);
17735f39d397SChris Mason 		}
1774be0e5c09SChris Mason 		ret = comp_keys(tmp, key);
1775be0e5c09SChris Mason 
1776be0e5c09SChris Mason 		if (ret < 0)
1777be0e5c09SChris Mason 			low = mid + 1;
1778be0e5c09SChris Mason 		else if (ret > 0)
1779be0e5c09SChris Mason 			high = mid;
1780be0e5c09SChris Mason 		else {
1781be0e5c09SChris Mason 			*slot = mid;
1782be0e5c09SChris Mason 			return 0;
1783be0e5c09SChris Mason 		}
1784be0e5c09SChris Mason 	}
1785be0e5c09SChris Mason 	*slot = low;
1786be0e5c09SChris Mason 	return 1;
1787be0e5c09SChris Mason }
1788be0e5c09SChris Mason 
178997571fd0SChris Mason /*
179097571fd0SChris Mason  * simple bin_search frontend that does the right thing for
179197571fd0SChris Mason  * leaves vs nodes
179297571fd0SChris Mason  */
1793a74b35ecSNikolay Borisov int btrfs_bin_search(struct extent_buffer *eb, const struct btrfs_key *key,
17945f39d397SChris Mason 		     int level, int *slot)
1795be0e5c09SChris Mason {
1796f775738fSWang Sheng-Hui 	if (level == 0)
17975f39d397SChris Mason 		return generic_bin_search(eb,
17985f39d397SChris Mason 					  offsetof(struct btrfs_leaf, items),
17990783fcfcSChris Mason 					  sizeof(struct btrfs_item),
18005f39d397SChris Mason 					  key, btrfs_header_nritems(eb),
18017518a238SChris Mason 					  slot);
1802f775738fSWang Sheng-Hui 	else
18035f39d397SChris Mason 		return generic_bin_search(eb,
18045f39d397SChris Mason 					  offsetof(struct btrfs_node, ptrs),
1805123abc88SChris Mason 					  sizeof(struct btrfs_key_ptr),
18065f39d397SChris Mason 					  key, btrfs_header_nritems(eb),
18077518a238SChris Mason 					  slot);
1808be0e5c09SChris Mason }
1809be0e5c09SChris Mason 
1810f0486c68SYan, Zheng static void root_add_used(struct btrfs_root *root, u32 size)
1811f0486c68SYan, Zheng {
1812f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
1813f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
1814f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) + size);
1815f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
1816f0486c68SYan, Zheng }
1817f0486c68SYan, Zheng 
1818f0486c68SYan, Zheng static void root_sub_used(struct btrfs_root *root, u32 size)
1819f0486c68SYan, Zheng {
1820f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
1821f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
1822f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) - size);
1823f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
1824f0486c68SYan, Zheng }
1825f0486c68SYan, Zheng 
1826d352ac68SChris Mason /* given a node and slot number, this reads the blocks it points to.  The
1827d352ac68SChris Mason  * extent buffer is returned with a reference taken (but unlocked).
1828d352ac68SChris Mason  */
18292ff7e61eSJeff Mahoney static noinline struct extent_buffer *
18302ff7e61eSJeff Mahoney read_node_slot(struct btrfs_fs_info *fs_info, struct extent_buffer *parent,
18312ff7e61eSJeff Mahoney 	       int slot)
1832bb803951SChris Mason {
1833ca7a79adSChris Mason 	int level = btrfs_header_level(parent);
1834416bc658SJosef Bacik 	struct extent_buffer *eb;
1835416bc658SJosef Bacik 
1836fb770ae4SLiu Bo 	if (slot < 0 || slot >= btrfs_header_nritems(parent))
1837fb770ae4SLiu Bo 		return ERR_PTR(-ENOENT);
1838ca7a79adSChris Mason 
1839ca7a79adSChris Mason 	BUG_ON(level == 0);
1840ca7a79adSChris Mason 
18412ff7e61eSJeff Mahoney 	eb = read_tree_block(fs_info, btrfs_node_blockptr(parent, slot),
1842ca7a79adSChris Mason 			     btrfs_node_ptr_generation(parent, slot));
1843fb770ae4SLiu Bo 	if (!IS_ERR(eb) && !extent_buffer_uptodate(eb)) {
1844416bc658SJosef Bacik 		free_extent_buffer(eb);
1845fb770ae4SLiu Bo 		eb = ERR_PTR(-EIO);
1846416bc658SJosef Bacik 	}
1847416bc658SJosef Bacik 
1848416bc658SJosef Bacik 	return eb;
1849bb803951SChris Mason }
1850bb803951SChris Mason 
1851d352ac68SChris Mason /*
1852d352ac68SChris Mason  * node level balancing, used to make sure nodes are in proper order for
1853d352ac68SChris Mason  * item deletion.  We balance from the top down, so we have to make sure
1854d352ac68SChris Mason  * that a deletion won't leave an node completely empty later on.
1855d352ac68SChris Mason  */
1856e02119d5SChris Mason static noinline int balance_level(struct btrfs_trans_handle *trans,
185798ed5174SChris Mason 			 struct btrfs_root *root,
185898ed5174SChris Mason 			 struct btrfs_path *path, int level)
1859bb803951SChris Mason {
18600b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
18615f39d397SChris Mason 	struct extent_buffer *right = NULL;
18625f39d397SChris Mason 	struct extent_buffer *mid;
18635f39d397SChris Mason 	struct extent_buffer *left = NULL;
18645f39d397SChris Mason 	struct extent_buffer *parent = NULL;
1865bb803951SChris Mason 	int ret = 0;
1866bb803951SChris Mason 	int wret;
1867bb803951SChris Mason 	int pslot;
1868bb803951SChris Mason 	int orig_slot = path->slots[level];
186979f95c82SChris Mason 	u64 orig_ptr;
1870bb803951SChris Mason 
1871bb803951SChris Mason 	if (level == 0)
1872bb803951SChris Mason 		return 0;
1873bb803951SChris Mason 
18745f39d397SChris Mason 	mid = path->nodes[level];
1875b4ce94deSChris Mason 
1876bd681513SChris Mason 	WARN_ON(path->locks[level] != BTRFS_WRITE_LOCK &&
1877bd681513SChris Mason 		path->locks[level] != BTRFS_WRITE_LOCK_BLOCKING);
18787bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
18797bb86316SChris Mason 
18801d4f8a0cSChris Mason 	orig_ptr = btrfs_node_blockptr(mid, orig_slot);
188179f95c82SChris Mason 
1882a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
18835f39d397SChris Mason 		parent = path->nodes[level + 1];
1884bb803951SChris Mason 		pslot = path->slots[level + 1];
1885a05a9bb1SLi Zefan 	}
1886bb803951SChris Mason 
188740689478SChris Mason 	/*
188840689478SChris Mason 	 * deal with the case where there is only one pointer in the root
188940689478SChris Mason 	 * by promoting the node below to a root
189040689478SChris Mason 	 */
18915f39d397SChris Mason 	if (!parent) {
18925f39d397SChris Mason 		struct extent_buffer *child;
1893bb803951SChris Mason 
18945f39d397SChris Mason 		if (btrfs_header_nritems(mid) != 1)
1895bb803951SChris Mason 			return 0;
1896bb803951SChris Mason 
1897bb803951SChris Mason 		/* promote the child to a root */
18982ff7e61eSJeff Mahoney 		child = read_node_slot(fs_info, mid, 0);
1899fb770ae4SLiu Bo 		if (IS_ERR(child)) {
1900fb770ae4SLiu Bo 			ret = PTR_ERR(child);
19010b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
1902305a26afSMark Fasheh 			goto enospc;
1903305a26afSMark Fasheh 		}
1904305a26afSMark Fasheh 
1905925baeddSChris Mason 		btrfs_tree_lock(child);
1906b4ce94deSChris Mason 		btrfs_set_lock_blocking(child);
19079fa8cfe7SChris Mason 		ret = btrfs_cow_block(trans, root, child, mid, 0, &child);
1908f0486c68SYan, Zheng 		if (ret) {
1909f0486c68SYan, Zheng 			btrfs_tree_unlock(child);
1910f0486c68SYan, Zheng 			free_extent_buffer(child);
1911f0486c68SYan, Zheng 			goto enospc;
1912f0486c68SYan, Zheng 		}
19132f375ab9SYan 
191490f8d62eSJan Schmidt 		tree_mod_log_set_root_pointer(root, child, 1);
1915240f62c8SChris Mason 		rcu_assign_pointer(root->node, child);
1916925baeddSChris Mason 
19170b86a832SChris Mason 		add_root_to_dirty_list(root);
1918925baeddSChris Mason 		btrfs_tree_unlock(child);
1919b4ce94deSChris Mason 
1920925baeddSChris Mason 		path->locks[level] = 0;
1921bb803951SChris Mason 		path->nodes[level] = NULL;
19227c302b49SDavid Sterba 		clean_tree_block(fs_info, mid);
1923925baeddSChris Mason 		btrfs_tree_unlock(mid);
1924bb803951SChris Mason 		/* once for the path */
19255f39d397SChris Mason 		free_extent_buffer(mid);
1926f0486c68SYan, Zheng 
1927f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
19285581a51aSJan Schmidt 		btrfs_free_tree_block(trans, root, mid, 0, 1);
1929bb803951SChris Mason 		/* once for the root ptr */
19303083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
1931f0486c68SYan, Zheng 		return 0;
1932bb803951SChris Mason 	}
19335f39d397SChris Mason 	if (btrfs_header_nritems(mid) >
19340b246afaSJeff Mahoney 	    BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 4)
1935bb803951SChris Mason 		return 0;
1936bb803951SChris Mason 
19372ff7e61eSJeff Mahoney 	left = read_node_slot(fs_info, parent, pslot - 1);
1938fb770ae4SLiu Bo 	if (IS_ERR(left))
1939fb770ae4SLiu Bo 		left = NULL;
1940fb770ae4SLiu Bo 
19415f39d397SChris Mason 	if (left) {
1942925baeddSChris Mason 		btrfs_tree_lock(left);
1943b4ce94deSChris Mason 		btrfs_set_lock_blocking(left);
19445f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, left,
19459fa8cfe7SChris Mason 				       parent, pslot - 1, &left);
194654aa1f4dSChris Mason 		if (wret) {
194754aa1f4dSChris Mason 			ret = wret;
194854aa1f4dSChris Mason 			goto enospc;
194954aa1f4dSChris Mason 		}
19502cc58cf2SChris Mason 	}
1951fb770ae4SLiu Bo 
19522ff7e61eSJeff Mahoney 	right = read_node_slot(fs_info, parent, pslot + 1);
1953fb770ae4SLiu Bo 	if (IS_ERR(right))
1954fb770ae4SLiu Bo 		right = NULL;
1955fb770ae4SLiu Bo 
19565f39d397SChris Mason 	if (right) {
1957925baeddSChris Mason 		btrfs_tree_lock(right);
1958b4ce94deSChris Mason 		btrfs_set_lock_blocking(right);
19595f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, right,
19609fa8cfe7SChris Mason 				       parent, pslot + 1, &right);
19612cc58cf2SChris Mason 		if (wret) {
19622cc58cf2SChris Mason 			ret = wret;
19632cc58cf2SChris Mason 			goto enospc;
19642cc58cf2SChris Mason 		}
19652cc58cf2SChris Mason 	}
19662cc58cf2SChris Mason 
19672cc58cf2SChris Mason 	/* first, try to make some room in the middle buffer */
19685f39d397SChris Mason 	if (left) {
19695f39d397SChris Mason 		orig_slot += btrfs_header_nritems(left);
19702ff7e61eSJeff Mahoney 		wret = push_node_left(trans, fs_info, left, mid, 1);
197179f95c82SChris Mason 		if (wret < 0)
197279f95c82SChris Mason 			ret = wret;
1973bb803951SChris Mason 	}
197479f95c82SChris Mason 
197579f95c82SChris Mason 	/*
197679f95c82SChris Mason 	 * then try to empty the right most buffer into the middle
197779f95c82SChris Mason 	 */
19785f39d397SChris Mason 	if (right) {
19792ff7e61eSJeff Mahoney 		wret = push_node_left(trans, fs_info, mid, right, 1);
198054aa1f4dSChris Mason 		if (wret < 0 && wret != -ENOSPC)
198179f95c82SChris Mason 			ret = wret;
19825f39d397SChris Mason 		if (btrfs_header_nritems(right) == 0) {
19837c302b49SDavid Sterba 			clean_tree_block(fs_info, right);
1984925baeddSChris Mason 			btrfs_tree_unlock(right);
1985afe5fea7STsutomu Itoh 			del_ptr(root, path, level + 1, pslot + 1);
1986f0486c68SYan, Zheng 			root_sub_used(root, right->len);
19875581a51aSJan Schmidt 			btrfs_free_tree_block(trans, root, right, 0, 1);
19883083ee2eSJosef Bacik 			free_extent_buffer_stale(right);
1989f0486c68SYan, Zheng 			right = NULL;
1990bb803951SChris Mason 		} else {
19915f39d397SChris Mason 			struct btrfs_disk_key right_key;
19925f39d397SChris Mason 			btrfs_node_key(right, &right_key, 0);
19933ac6de1aSDavid Sterba 			tree_mod_log_set_node_key(parent, pslot + 1, 0);
19945f39d397SChris Mason 			btrfs_set_node_key(parent, &right_key, pslot + 1);
19955f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
1996bb803951SChris Mason 		}
1997bb803951SChris Mason 	}
19985f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 1) {
199979f95c82SChris Mason 		/*
200079f95c82SChris Mason 		 * we're not allowed to leave a node with one item in the
200179f95c82SChris Mason 		 * tree during a delete.  A deletion from lower in the tree
200279f95c82SChris Mason 		 * could try to delete the only pointer in this node.
200379f95c82SChris Mason 		 * So, pull some keys from the left.
200479f95c82SChris Mason 		 * There has to be a left pointer at this point because
200579f95c82SChris Mason 		 * otherwise we would have pulled some pointers from the
200679f95c82SChris Mason 		 * right
200779f95c82SChris Mason 		 */
2008305a26afSMark Fasheh 		if (!left) {
2009305a26afSMark Fasheh 			ret = -EROFS;
20100b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
2011305a26afSMark Fasheh 			goto enospc;
2012305a26afSMark Fasheh 		}
20132ff7e61eSJeff Mahoney 		wret = balance_node_right(trans, fs_info, mid, left);
201454aa1f4dSChris Mason 		if (wret < 0) {
201579f95c82SChris Mason 			ret = wret;
201654aa1f4dSChris Mason 			goto enospc;
201754aa1f4dSChris Mason 		}
2018bce4eae9SChris Mason 		if (wret == 1) {
20192ff7e61eSJeff Mahoney 			wret = push_node_left(trans, fs_info, left, mid, 1);
2020bce4eae9SChris Mason 			if (wret < 0)
2021bce4eae9SChris Mason 				ret = wret;
2022bce4eae9SChris Mason 		}
202379f95c82SChris Mason 		BUG_ON(wret == 1);
202479f95c82SChris Mason 	}
20255f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 0) {
20267c302b49SDavid Sterba 		clean_tree_block(fs_info, mid);
2027925baeddSChris Mason 		btrfs_tree_unlock(mid);
2028afe5fea7STsutomu Itoh 		del_ptr(root, path, level + 1, pslot);
2029f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
20305581a51aSJan Schmidt 		btrfs_free_tree_block(trans, root, mid, 0, 1);
20313083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
2032f0486c68SYan, Zheng 		mid = NULL;
203379f95c82SChris Mason 	} else {
203479f95c82SChris Mason 		/* update the parent key to reflect our changes */
20355f39d397SChris Mason 		struct btrfs_disk_key mid_key;
20365f39d397SChris Mason 		btrfs_node_key(mid, &mid_key, 0);
20373ac6de1aSDavid Sterba 		tree_mod_log_set_node_key(parent, pslot, 0);
20385f39d397SChris Mason 		btrfs_set_node_key(parent, &mid_key, pslot);
20395f39d397SChris Mason 		btrfs_mark_buffer_dirty(parent);
204079f95c82SChris Mason 	}
2041bb803951SChris Mason 
204279f95c82SChris Mason 	/* update the path */
20435f39d397SChris Mason 	if (left) {
20445f39d397SChris Mason 		if (btrfs_header_nritems(left) > orig_slot) {
20455f39d397SChris Mason 			extent_buffer_get(left);
2046925baeddSChris Mason 			/* left was locked after cow */
20475f39d397SChris Mason 			path->nodes[level] = left;
2048bb803951SChris Mason 			path->slots[level + 1] -= 1;
2049bb803951SChris Mason 			path->slots[level] = orig_slot;
2050925baeddSChris Mason 			if (mid) {
2051925baeddSChris Mason 				btrfs_tree_unlock(mid);
20525f39d397SChris Mason 				free_extent_buffer(mid);
2053925baeddSChris Mason 			}
2054bb803951SChris Mason 		} else {
20555f39d397SChris Mason 			orig_slot -= btrfs_header_nritems(left);
2056bb803951SChris Mason 			path->slots[level] = orig_slot;
2057bb803951SChris Mason 		}
2058bb803951SChris Mason 	}
205979f95c82SChris Mason 	/* double check we haven't messed things up */
2060e20d96d6SChris Mason 	if (orig_ptr !=
20615f39d397SChris Mason 	    btrfs_node_blockptr(path->nodes[level], path->slots[level]))
206279f95c82SChris Mason 		BUG();
206354aa1f4dSChris Mason enospc:
2064925baeddSChris Mason 	if (right) {
2065925baeddSChris Mason 		btrfs_tree_unlock(right);
20665f39d397SChris Mason 		free_extent_buffer(right);
2067925baeddSChris Mason 	}
2068925baeddSChris Mason 	if (left) {
2069925baeddSChris Mason 		if (path->nodes[level] != left)
2070925baeddSChris Mason 			btrfs_tree_unlock(left);
20715f39d397SChris Mason 		free_extent_buffer(left);
2072925baeddSChris Mason 	}
2073bb803951SChris Mason 	return ret;
2074bb803951SChris Mason }
2075bb803951SChris Mason 
2076d352ac68SChris Mason /* Node balancing for insertion.  Here we only split or push nodes around
2077d352ac68SChris Mason  * when they are completely full.  This is also done top down, so we
2078d352ac68SChris Mason  * have to be pessimistic.
2079d352ac68SChris Mason  */
2080d397712bSChris Mason static noinline int push_nodes_for_insert(struct btrfs_trans_handle *trans,
2081e66f709bSChris Mason 					  struct btrfs_root *root,
2082e66f709bSChris Mason 					  struct btrfs_path *path, int level)
2083e66f709bSChris Mason {
20840b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
20855f39d397SChris Mason 	struct extent_buffer *right = NULL;
20865f39d397SChris Mason 	struct extent_buffer *mid;
20875f39d397SChris Mason 	struct extent_buffer *left = NULL;
20885f39d397SChris Mason 	struct extent_buffer *parent = NULL;
2089e66f709bSChris Mason 	int ret = 0;
2090e66f709bSChris Mason 	int wret;
2091e66f709bSChris Mason 	int pslot;
2092e66f709bSChris Mason 	int orig_slot = path->slots[level];
2093e66f709bSChris Mason 
2094e66f709bSChris Mason 	if (level == 0)
2095e66f709bSChris Mason 		return 1;
2096e66f709bSChris Mason 
20975f39d397SChris Mason 	mid = path->nodes[level];
20987bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
2099e66f709bSChris Mason 
2100a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
21015f39d397SChris Mason 		parent = path->nodes[level + 1];
2102e66f709bSChris Mason 		pslot = path->slots[level + 1];
2103a05a9bb1SLi Zefan 	}
2104e66f709bSChris Mason 
21055f39d397SChris Mason 	if (!parent)
2106e66f709bSChris Mason 		return 1;
2107e66f709bSChris Mason 
21082ff7e61eSJeff Mahoney 	left = read_node_slot(fs_info, parent, pslot - 1);
2109fb770ae4SLiu Bo 	if (IS_ERR(left))
2110fb770ae4SLiu Bo 		left = NULL;
2111e66f709bSChris Mason 
2112e66f709bSChris Mason 	/* first, try to make some room in the middle buffer */
21135f39d397SChris Mason 	if (left) {
2114e66f709bSChris Mason 		u32 left_nr;
2115925baeddSChris Mason 
2116925baeddSChris Mason 		btrfs_tree_lock(left);
2117b4ce94deSChris Mason 		btrfs_set_lock_blocking(left);
2118b4ce94deSChris Mason 
21195f39d397SChris Mason 		left_nr = btrfs_header_nritems(left);
21200b246afaSJeff Mahoney 		if (left_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
212133ade1f8SChris Mason 			wret = 1;
212233ade1f8SChris Mason 		} else {
21235f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, left, parent,
21249fa8cfe7SChris Mason 					      pslot - 1, &left);
212554aa1f4dSChris Mason 			if (ret)
212654aa1f4dSChris Mason 				wret = 1;
212754aa1f4dSChris Mason 			else {
21282ff7e61eSJeff Mahoney 				wret = push_node_left(trans, fs_info,
2129971a1f66SChris Mason 						      left, mid, 0);
213054aa1f4dSChris Mason 			}
213133ade1f8SChris Mason 		}
2132e66f709bSChris Mason 		if (wret < 0)
2133e66f709bSChris Mason 			ret = wret;
2134e66f709bSChris Mason 		if (wret == 0) {
21355f39d397SChris Mason 			struct btrfs_disk_key disk_key;
2136e66f709bSChris Mason 			orig_slot += left_nr;
21375f39d397SChris Mason 			btrfs_node_key(mid, &disk_key, 0);
21383ac6de1aSDavid Sterba 			tree_mod_log_set_node_key(parent, pslot, 0);
21395f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot);
21405f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
21415f39d397SChris Mason 			if (btrfs_header_nritems(left) > orig_slot) {
21425f39d397SChris Mason 				path->nodes[level] = left;
2143e66f709bSChris Mason 				path->slots[level + 1] -= 1;
2144e66f709bSChris Mason 				path->slots[level] = orig_slot;
2145925baeddSChris Mason 				btrfs_tree_unlock(mid);
21465f39d397SChris Mason 				free_extent_buffer(mid);
2147e66f709bSChris Mason 			} else {
2148e66f709bSChris Mason 				orig_slot -=
21495f39d397SChris Mason 					btrfs_header_nritems(left);
2150e66f709bSChris Mason 				path->slots[level] = orig_slot;
2151925baeddSChris Mason 				btrfs_tree_unlock(left);
21525f39d397SChris Mason 				free_extent_buffer(left);
2153e66f709bSChris Mason 			}
2154e66f709bSChris Mason 			return 0;
2155e66f709bSChris Mason 		}
2156925baeddSChris Mason 		btrfs_tree_unlock(left);
21575f39d397SChris Mason 		free_extent_buffer(left);
2158e66f709bSChris Mason 	}
21592ff7e61eSJeff Mahoney 	right = read_node_slot(fs_info, parent, pslot + 1);
2160fb770ae4SLiu Bo 	if (IS_ERR(right))
2161fb770ae4SLiu Bo 		right = NULL;
2162e66f709bSChris Mason 
2163e66f709bSChris Mason 	/*
2164e66f709bSChris Mason 	 * then try to empty the right most buffer into the middle
2165e66f709bSChris Mason 	 */
21665f39d397SChris Mason 	if (right) {
216733ade1f8SChris Mason 		u32 right_nr;
2168b4ce94deSChris Mason 
2169925baeddSChris Mason 		btrfs_tree_lock(right);
2170b4ce94deSChris Mason 		btrfs_set_lock_blocking(right);
2171b4ce94deSChris Mason 
21725f39d397SChris Mason 		right_nr = btrfs_header_nritems(right);
21730b246afaSJeff Mahoney 		if (right_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
217433ade1f8SChris Mason 			wret = 1;
217533ade1f8SChris Mason 		} else {
21765f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, right,
21775f39d397SChris Mason 					      parent, pslot + 1,
21789fa8cfe7SChris Mason 					      &right);
217954aa1f4dSChris Mason 			if (ret)
218054aa1f4dSChris Mason 				wret = 1;
218154aa1f4dSChris Mason 			else {
21822ff7e61eSJeff Mahoney 				wret = balance_node_right(trans, fs_info,
21835f39d397SChris Mason 							  right, mid);
218433ade1f8SChris Mason 			}
218554aa1f4dSChris Mason 		}
2186e66f709bSChris Mason 		if (wret < 0)
2187e66f709bSChris Mason 			ret = wret;
2188e66f709bSChris Mason 		if (wret == 0) {
21895f39d397SChris Mason 			struct btrfs_disk_key disk_key;
21905f39d397SChris Mason 
21915f39d397SChris Mason 			btrfs_node_key(right, &disk_key, 0);
21923ac6de1aSDavid Sterba 			tree_mod_log_set_node_key(parent, pslot + 1, 0);
21935f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot + 1);
21945f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
21955f39d397SChris Mason 
21965f39d397SChris Mason 			if (btrfs_header_nritems(mid) <= orig_slot) {
21975f39d397SChris Mason 				path->nodes[level] = right;
2198e66f709bSChris Mason 				path->slots[level + 1] += 1;
2199e66f709bSChris Mason 				path->slots[level] = orig_slot -
22005f39d397SChris Mason 					btrfs_header_nritems(mid);
2201925baeddSChris Mason 				btrfs_tree_unlock(mid);
22025f39d397SChris Mason 				free_extent_buffer(mid);
2203e66f709bSChris Mason 			} else {
2204925baeddSChris Mason 				btrfs_tree_unlock(right);
22055f39d397SChris Mason 				free_extent_buffer(right);
2206e66f709bSChris Mason 			}
2207e66f709bSChris Mason 			return 0;
2208e66f709bSChris Mason 		}
2209925baeddSChris Mason 		btrfs_tree_unlock(right);
22105f39d397SChris Mason 		free_extent_buffer(right);
2211e66f709bSChris Mason 	}
2212e66f709bSChris Mason 	return 1;
2213e66f709bSChris Mason }
2214e66f709bSChris Mason 
221574123bd7SChris Mason /*
2216d352ac68SChris Mason  * readahead one full node of leaves, finding things that are close
2217d352ac68SChris Mason  * to the block in 'slot', and triggering ra on them.
22183c69faecSChris Mason  */
22192ff7e61eSJeff Mahoney static void reada_for_search(struct btrfs_fs_info *fs_info,
2220e02119d5SChris Mason 			     struct btrfs_path *path,
222101f46658SChris Mason 			     int level, int slot, u64 objectid)
22223c69faecSChris Mason {
22235f39d397SChris Mason 	struct extent_buffer *node;
222401f46658SChris Mason 	struct btrfs_disk_key disk_key;
22253c69faecSChris Mason 	u32 nritems;
22263c69faecSChris Mason 	u64 search;
2227a7175319SChris Mason 	u64 target;
22286b80053dSChris Mason 	u64 nread = 0;
22295f39d397SChris Mason 	struct extent_buffer *eb;
22306b80053dSChris Mason 	u32 nr;
22316b80053dSChris Mason 	u32 blocksize;
22326b80053dSChris Mason 	u32 nscan = 0;
2233db94535dSChris Mason 
2234a6b6e75eSChris Mason 	if (level != 1)
22353c69faecSChris Mason 		return;
22363c69faecSChris Mason 
22376702ed49SChris Mason 	if (!path->nodes[level])
22386702ed49SChris Mason 		return;
22396702ed49SChris Mason 
22405f39d397SChris Mason 	node = path->nodes[level];
2241925baeddSChris Mason 
22423c69faecSChris Mason 	search = btrfs_node_blockptr(node, slot);
22430b246afaSJeff Mahoney 	blocksize = fs_info->nodesize;
22440b246afaSJeff Mahoney 	eb = find_extent_buffer(fs_info, search);
22455f39d397SChris Mason 	if (eb) {
22465f39d397SChris Mason 		free_extent_buffer(eb);
22473c69faecSChris Mason 		return;
22483c69faecSChris Mason 	}
22493c69faecSChris Mason 
2250a7175319SChris Mason 	target = search;
22516b80053dSChris Mason 
22525f39d397SChris Mason 	nritems = btrfs_header_nritems(node);
22536b80053dSChris Mason 	nr = slot;
225425b8b936SJosef Bacik 
22553c69faecSChris Mason 	while (1) {
2256e4058b54SDavid Sterba 		if (path->reada == READA_BACK) {
22576b80053dSChris Mason 			if (nr == 0)
22583c69faecSChris Mason 				break;
22596b80053dSChris Mason 			nr--;
2260e4058b54SDavid Sterba 		} else if (path->reada == READA_FORWARD) {
22616b80053dSChris Mason 			nr++;
22626b80053dSChris Mason 			if (nr >= nritems)
22636b80053dSChris Mason 				break;
22643c69faecSChris Mason 		}
2265e4058b54SDavid Sterba 		if (path->reada == READA_BACK && objectid) {
226601f46658SChris Mason 			btrfs_node_key(node, &disk_key, nr);
226701f46658SChris Mason 			if (btrfs_disk_key_objectid(&disk_key) != objectid)
226801f46658SChris Mason 				break;
226901f46658SChris Mason 		}
22706b80053dSChris Mason 		search = btrfs_node_blockptr(node, nr);
2271a7175319SChris Mason 		if ((search <= target && target - search <= 65536) ||
2272a7175319SChris Mason 		    (search > target && search - target <= 65536)) {
22732ff7e61eSJeff Mahoney 			readahead_tree_block(fs_info, search);
22746b80053dSChris Mason 			nread += blocksize;
22753c69faecSChris Mason 		}
22766b80053dSChris Mason 		nscan++;
2277a7175319SChris Mason 		if ((nread > 65536 || nscan > 32))
22786b80053dSChris Mason 			break;
22793c69faecSChris Mason 	}
22803c69faecSChris Mason }
2281925baeddSChris Mason 
22822ff7e61eSJeff Mahoney static noinline void reada_for_balance(struct btrfs_fs_info *fs_info,
2283b4ce94deSChris Mason 				       struct btrfs_path *path, int level)
2284b4ce94deSChris Mason {
2285b4ce94deSChris Mason 	int slot;
2286b4ce94deSChris Mason 	int nritems;
2287b4ce94deSChris Mason 	struct extent_buffer *parent;
2288b4ce94deSChris Mason 	struct extent_buffer *eb;
2289b4ce94deSChris Mason 	u64 gen;
2290b4ce94deSChris Mason 	u64 block1 = 0;
2291b4ce94deSChris Mason 	u64 block2 = 0;
2292b4ce94deSChris Mason 
22938c594ea8SChris Mason 	parent = path->nodes[level + 1];
2294b4ce94deSChris Mason 	if (!parent)
22950b08851fSJosef Bacik 		return;
2296b4ce94deSChris Mason 
2297b4ce94deSChris Mason 	nritems = btrfs_header_nritems(parent);
22988c594ea8SChris Mason 	slot = path->slots[level + 1];
2299b4ce94deSChris Mason 
2300b4ce94deSChris Mason 	if (slot > 0) {
2301b4ce94deSChris Mason 		block1 = btrfs_node_blockptr(parent, slot - 1);
2302b4ce94deSChris Mason 		gen = btrfs_node_ptr_generation(parent, slot - 1);
23030b246afaSJeff Mahoney 		eb = find_extent_buffer(fs_info, block1);
2304b9fab919SChris Mason 		/*
2305b9fab919SChris Mason 		 * if we get -eagain from btrfs_buffer_uptodate, we
2306b9fab919SChris Mason 		 * don't want to return eagain here.  That will loop
2307b9fab919SChris Mason 		 * forever
2308b9fab919SChris Mason 		 */
2309b9fab919SChris Mason 		if (eb && btrfs_buffer_uptodate(eb, gen, 1) != 0)
2310b4ce94deSChris Mason 			block1 = 0;
2311b4ce94deSChris Mason 		free_extent_buffer(eb);
2312b4ce94deSChris Mason 	}
23138c594ea8SChris Mason 	if (slot + 1 < nritems) {
2314b4ce94deSChris Mason 		block2 = btrfs_node_blockptr(parent, slot + 1);
2315b4ce94deSChris Mason 		gen = btrfs_node_ptr_generation(parent, slot + 1);
23160b246afaSJeff Mahoney 		eb = find_extent_buffer(fs_info, block2);
2317b9fab919SChris Mason 		if (eb && btrfs_buffer_uptodate(eb, gen, 1) != 0)
2318b4ce94deSChris Mason 			block2 = 0;
2319b4ce94deSChris Mason 		free_extent_buffer(eb);
2320b4ce94deSChris Mason 	}
23218c594ea8SChris Mason 
2322b4ce94deSChris Mason 	if (block1)
23232ff7e61eSJeff Mahoney 		readahead_tree_block(fs_info, block1);
2324b4ce94deSChris Mason 	if (block2)
23252ff7e61eSJeff Mahoney 		readahead_tree_block(fs_info, block2);
2326b4ce94deSChris Mason }
2327b4ce94deSChris Mason 
2328b4ce94deSChris Mason 
2329b4ce94deSChris Mason /*
2330d397712bSChris Mason  * when we walk down the tree, it is usually safe to unlock the higher layers
2331d397712bSChris Mason  * in the tree.  The exceptions are when our path goes through slot 0, because
2332d397712bSChris Mason  * operations on the tree might require changing key pointers higher up in the
2333d397712bSChris Mason  * tree.
2334d352ac68SChris Mason  *
2335d397712bSChris Mason  * callers might also have set path->keep_locks, which tells this code to keep
2336d397712bSChris Mason  * the lock if the path points to the last slot in the block.  This is part of
2337d397712bSChris Mason  * walking through the tree, and selecting the next slot in the higher block.
2338d352ac68SChris Mason  *
2339d397712bSChris Mason  * lowest_unlock sets the lowest level in the tree we're allowed to unlock.  so
2340d397712bSChris Mason  * if lowest_unlock is 1, level 0 won't be unlocked
2341d352ac68SChris Mason  */
2342e02119d5SChris Mason static noinline void unlock_up(struct btrfs_path *path, int level,
2343f7c79f30SChris Mason 			       int lowest_unlock, int min_write_lock_level,
2344f7c79f30SChris Mason 			       int *write_lock_level)
2345925baeddSChris Mason {
2346925baeddSChris Mason 	int i;
2347925baeddSChris Mason 	int skip_level = level;
2348051e1b9fSChris Mason 	int no_skips = 0;
2349925baeddSChris Mason 	struct extent_buffer *t;
2350925baeddSChris Mason 
2351925baeddSChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2352925baeddSChris Mason 		if (!path->nodes[i])
2353925baeddSChris Mason 			break;
2354925baeddSChris Mason 		if (!path->locks[i])
2355925baeddSChris Mason 			break;
2356051e1b9fSChris Mason 		if (!no_skips && path->slots[i] == 0) {
2357925baeddSChris Mason 			skip_level = i + 1;
2358925baeddSChris Mason 			continue;
2359925baeddSChris Mason 		}
2360051e1b9fSChris Mason 		if (!no_skips && path->keep_locks) {
2361925baeddSChris Mason 			u32 nritems;
2362925baeddSChris Mason 			t = path->nodes[i];
2363925baeddSChris Mason 			nritems = btrfs_header_nritems(t);
2364051e1b9fSChris Mason 			if (nritems < 1 || path->slots[i] >= nritems - 1) {
2365925baeddSChris Mason 				skip_level = i + 1;
2366925baeddSChris Mason 				continue;
2367925baeddSChris Mason 			}
2368925baeddSChris Mason 		}
2369051e1b9fSChris Mason 		if (skip_level < i && i >= lowest_unlock)
2370051e1b9fSChris Mason 			no_skips = 1;
2371051e1b9fSChris Mason 
2372925baeddSChris Mason 		t = path->nodes[i];
2373925baeddSChris Mason 		if (i >= lowest_unlock && i > skip_level && path->locks[i]) {
2374bd681513SChris Mason 			btrfs_tree_unlock_rw(t, path->locks[i]);
2375925baeddSChris Mason 			path->locks[i] = 0;
2376f7c79f30SChris Mason 			if (write_lock_level &&
2377f7c79f30SChris Mason 			    i > min_write_lock_level &&
2378f7c79f30SChris Mason 			    i <= *write_lock_level) {
2379f7c79f30SChris Mason 				*write_lock_level = i - 1;
2380f7c79f30SChris Mason 			}
2381925baeddSChris Mason 		}
2382925baeddSChris Mason 	}
2383925baeddSChris Mason }
2384925baeddSChris Mason 
23853c69faecSChris Mason /*
2386b4ce94deSChris Mason  * This releases any locks held in the path starting at level and
2387b4ce94deSChris Mason  * going all the way up to the root.
2388b4ce94deSChris Mason  *
2389b4ce94deSChris Mason  * btrfs_search_slot will keep the lock held on higher nodes in a few
2390b4ce94deSChris Mason  * corner cases, such as COW of the block at slot zero in the node.  This
2391b4ce94deSChris Mason  * ignores those rules, and it should only be called when there are no
2392b4ce94deSChris Mason  * more updates to be done higher up in the tree.
2393b4ce94deSChris Mason  */
2394b4ce94deSChris Mason noinline void btrfs_unlock_up_safe(struct btrfs_path *path, int level)
2395b4ce94deSChris Mason {
2396b4ce94deSChris Mason 	int i;
2397b4ce94deSChris Mason 
239809a2a8f9SJosef Bacik 	if (path->keep_locks)
2399b4ce94deSChris Mason 		return;
2400b4ce94deSChris Mason 
2401b4ce94deSChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2402b4ce94deSChris Mason 		if (!path->nodes[i])
240312f4daccSChris Mason 			continue;
2404b4ce94deSChris Mason 		if (!path->locks[i])
240512f4daccSChris Mason 			continue;
2406bd681513SChris Mason 		btrfs_tree_unlock_rw(path->nodes[i], path->locks[i]);
2407b4ce94deSChris Mason 		path->locks[i] = 0;
2408b4ce94deSChris Mason 	}
2409b4ce94deSChris Mason }
2410b4ce94deSChris Mason 
2411b4ce94deSChris Mason /*
2412c8c42864SChris Mason  * helper function for btrfs_search_slot.  The goal is to find a block
2413c8c42864SChris Mason  * in cache without setting the path to blocking.  If we find the block
2414c8c42864SChris Mason  * we return zero and the path is unchanged.
2415c8c42864SChris Mason  *
2416c8c42864SChris Mason  * If we can't find the block, we set the path blocking and do some
2417c8c42864SChris Mason  * reada.  -EAGAIN is returned and the search must be repeated.
2418c8c42864SChris Mason  */
2419c8c42864SChris Mason static int
2420d07b8528SLiu Bo read_block_for_search(struct btrfs_root *root, struct btrfs_path *p,
2421c8c42864SChris Mason 		      struct extent_buffer **eb_ret, int level, int slot,
2422cda79c54SDavid Sterba 		      const struct btrfs_key *key)
2423c8c42864SChris Mason {
24240b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
2425c8c42864SChris Mason 	u64 blocknr;
2426c8c42864SChris Mason 	u64 gen;
2427c8c42864SChris Mason 	struct extent_buffer *b = *eb_ret;
2428c8c42864SChris Mason 	struct extent_buffer *tmp;
242976a05b35SChris Mason 	int ret;
2430c8c42864SChris Mason 
2431c8c42864SChris Mason 	blocknr = btrfs_node_blockptr(b, slot);
2432c8c42864SChris Mason 	gen = btrfs_node_ptr_generation(b, slot);
2433c8c42864SChris Mason 
24340b246afaSJeff Mahoney 	tmp = find_extent_buffer(fs_info, blocknr);
2435cb44921aSChris Mason 	if (tmp) {
2436b9fab919SChris Mason 		/* first we do an atomic uptodate check */
2437b9fab919SChris Mason 		if (btrfs_buffer_uptodate(tmp, gen, 1) > 0) {
2438c8c42864SChris Mason 			*eb_ret = tmp;
2439c8c42864SChris Mason 			return 0;
2440c8c42864SChris Mason 		}
2441bdf7c00eSJosef Bacik 
2442cb44921aSChris Mason 		/* the pages were up to date, but we failed
2443cb44921aSChris Mason 		 * the generation number check.  Do a full
2444cb44921aSChris Mason 		 * read for the generation number that is correct.
2445cb44921aSChris Mason 		 * We must do this without dropping locks so
2446cb44921aSChris Mason 		 * we can trust our generation number
2447cb44921aSChris Mason 		 */
2448bd681513SChris Mason 		btrfs_set_path_blocking(p);
2449bd681513SChris Mason 
2450b9fab919SChris Mason 		/* now we're allowed to do a blocking uptodate check */
2451bdf7c00eSJosef Bacik 		ret = btrfs_read_buffer(tmp, gen);
2452bdf7c00eSJosef Bacik 		if (!ret) {
2453cb44921aSChris Mason 			*eb_ret = tmp;
2454cb44921aSChris Mason 			return 0;
2455cb44921aSChris Mason 		}
2456cb44921aSChris Mason 		free_extent_buffer(tmp);
2457b3b4aa74SDavid Sterba 		btrfs_release_path(p);
2458cb44921aSChris Mason 		return -EIO;
2459cb44921aSChris Mason 	}
2460c8c42864SChris Mason 
2461c8c42864SChris Mason 	/*
2462c8c42864SChris Mason 	 * reduce lock contention at high levels
2463c8c42864SChris Mason 	 * of the btree by dropping locks before
246476a05b35SChris Mason 	 * we read.  Don't release the lock on the current
246576a05b35SChris Mason 	 * level because we need to walk this node to figure
246676a05b35SChris Mason 	 * out which blocks to read.
2467c8c42864SChris Mason 	 */
24688c594ea8SChris Mason 	btrfs_unlock_up_safe(p, level + 1);
24698c594ea8SChris Mason 	btrfs_set_path_blocking(p);
24708c594ea8SChris Mason 
2471c8c42864SChris Mason 	free_extent_buffer(tmp);
2472e4058b54SDavid Sterba 	if (p->reada != READA_NONE)
24732ff7e61eSJeff Mahoney 		reada_for_search(fs_info, p, level, slot, key->objectid);
2474c8c42864SChris Mason 
2475b3b4aa74SDavid Sterba 	btrfs_release_path(p);
247676a05b35SChris Mason 
247776a05b35SChris Mason 	ret = -EAGAIN;
24782ff7e61eSJeff Mahoney 	tmp = read_tree_block(fs_info, blocknr, 0);
247964c043deSLiu Bo 	if (!IS_ERR(tmp)) {
248076a05b35SChris Mason 		/*
248176a05b35SChris Mason 		 * If the read above didn't mark this buffer up to date,
248276a05b35SChris Mason 		 * it will never end up being up to date.  Set ret to EIO now
248376a05b35SChris Mason 		 * and give up so that our caller doesn't loop forever
248476a05b35SChris Mason 		 * on our EAGAINs.
248576a05b35SChris Mason 		 */
2486b9fab919SChris Mason 		if (!btrfs_buffer_uptodate(tmp, 0, 0))
248776a05b35SChris Mason 			ret = -EIO;
2488c8c42864SChris Mason 		free_extent_buffer(tmp);
2489c871b0f2SLiu Bo 	} else {
2490c871b0f2SLiu Bo 		ret = PTR_ERR(tmp);
249176a05b35SChris Mason 	}
249276a05b35SChris Mason 	return ret;
2493c8c42864SChris Mason }
2494c8c42864SChris Mason 
2495c8c42864SChris Mason /*
2496c8c42864SChris Mason  * helper function for btrfs_search_slot.  This does all of the checks
2497c8c42864SChris Mason  * for node-level blocks and does any balancing required based on
2498c8c42864SChris Mason  * the ins_len.
2499c8c42864SChris Mason  *
2500c8c42864SChris Mason  * If no extra work was required, zero is returned.  If we had to
2501c8c42864SChris Mason  * drop the path, -EAGAIN is returned and btrfs_search_slot must
2502c8c42864SChris Mason  * start over
2503c8c42864SChris Mason  */
2504c8c42864SChris Mason static int
2505c8c42864SChris Mason setup_nodes_for_search(struct btrfs_trans_handle *trans,
2506c8c42864SChris Mason 		       struct btrfs_root *root, struct btrfs_path *p,
2507bd681513SChris Mason 		       struct extent_buffer *b, int level, int ins_len,
2508bd681513SChris Mason 		       int *write_lock_level)
2509c8c42864SChris Mason {
25100b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
2511c8c42864SChris Mason 	int ret;
25120b246afaSJeff Mahoney 
2513c8c42864SChris Mason 	if ((p->search_for_split || ins_len > 0) && btrfs_header_nritems(b) >=
25140b246afaSJeff Mahoney 	    BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3) {
2515c8c42864SChris Mason 		int sret;
2516c8c42864SChris Mason 
2517bd681513SChris Mason 		if (*write_lock_level < level + 1) {
2518bd681513SChris Mason 			*write_lock_level = level + 1;
2519bd681513SChris Mason 			btrfs_release_path(p);
2520bd681513SChris Mason 			goto again;
2521bd681513SChris Mason 		}
2522bd681513SChris Mason 
2523c8c42864SChris Mason 		btrfs_set_path_blocking(p);
25242ff7e61eSJeff Mahoney 		reada_for_balance(fs_info, p, level);
2525c8c42864SChris Mason 		sret = split_node(trans, root, p, level);
2526bd681513SChris Mason 		btrfs_clear_path_blocking(p, NULL, 0);
2527c8c42864SChris Mason 
2528c8c42864SChris Mason 		BUG_ON(sret > 0);
2529c8c42864SChris Mason 		if (sret) {
2530c8c42864SChris Mason 			ret = sret;
2531c8c42864SChris Mason 			goto done;
2532c8c42864SChris Mason 		}
2533c8c42864SChris Mason 		b = p->nodes[level];
2534c8c42864SChris Mason 	} else if (ins_len < 0 && btrfs_header_nritems(b) <
25350b246afaSJeff Mahoney 		   BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 2) {
2536c8c42864SChris Mason 		int sret;
2537c8c42864SChris Mason 
2538bd681513SChris Mason 		if (*write_lock_level < level + 1) {
2539bd681513SChris Mason 			*write_lock_level = level + 1;
2540bd681513SChris Mason 			btrfs_release_path(p);
2541bd681513SChris Mason 			goto again;
2542bd681513SChris Mason 		}
2543bd681513SChris Mason 
2544c8c42864SChris Mason 		btrfs_set_path_blocking(p);
25452ff7e61eSJeff Mahoney 		reada_for_balance(fs_info, p, level);
2546c8c42864SChris Mason 		sret = balance_level(trans, root, p, level);
2547bd681513SChris Mason 		btrfs_clear_path_blocking(p, NULL, 0);
2548c8c42864SChris Mason 
2549c8c42864SChris Mason 		if (sret) {
2550c8c42864SChris Mason 			ret = sret;
2551c8c42864SChris Mason 			goto done;
2552c8c42864SChris Mason 		}
2553c8c42864SChris Mason 		b = p->nodes[level];
2554c8c42864SChris Mason 		if (!b) {
2555b3b4aa74SDavid Sterba 			btrfs_release_path(p);
2556c8c42864SChris Mason 			goto again;
2557c8c42864SChris Mason 		}
2558c8c42864SChris Mason 		BUG_ON(btrfs_header_nritems(b) == 1);
2559c8c42864SChris Mason 	}
2560c8c42864SChris Mason 	return 0;
2561c8c42864SChris Mason 
2562c8c42864SChris Mason again:
2563c8c42864SChris Mason 	ret = -EAGAIN;
2564c8c42864SChris Mason done:
2565c8c42864SChris Mason 	return ret;
2566c8c42864SChris Mason }
2567c8c42864SChris Mason 
2568d7396f07SFilipe David Borba Manana static void key_search_validate(struct extent_buffer *b,
2569310712b2SOmar Sandoval 				const struct btrfs_key *key,
2570d7396f07SFilipe David Borba Manana 				int level)
2571d7396f07SFilipe David Borba Manana {
2572d7396f07SFilipe David Borba Manana #ifdef CONFIG_BTRFS_ASSERT
2573d7396f07SFilipe David Borba Manana 	struct btrfs_disk_key disk_key;
2574d7396f07SFilipe David Borba Manana 
2575d7396f07SFilipe David Borba Manana 	btrfs_cpu_key_to_disk(&disk_key, key);
2576d7396f07SFilipe David Borba Manana 
2577d7396f07SFilipe David Borba Manana 	if (level == 0)
2578d7396f07SFilipe David Borba Manana 		ASSERT(!memcmp_extent_buffer(b, &disk_key,
2579d7396f07SFilipe David Borba Manana 		    offsetof(struct btrfs_leaf, items[0].key),
2580d7396f07SFilipe David Borba Manana 		    sizeof(disk_key)));
2581d7396f07SFilipe David Borba Manana 	else
2582d7396f07SFilipe David Borba Manana 		ASSERT(!memcmp_extent_buffer(b, &disk_key,
2583d7396f07SFilipe David Borba Manana 		    offsetof(struct btrfs_node, ptrs[0].key),
2584d7396f07SFilipe David Borba Manana 		    sizeof(disk_key)));
2585d7396f07SFilipe David Borba Manana #endif
2586d7396f07SFilipe David Borba Manana }
2587d7396f07SFilipe David Borba Manana 
2588310712b2SOmar Sandoval static int key_search(struct extent_buffer *b, const struct btrfs_key *key,
2589d7396f07SFilipe David Borba Manana 		      int level, int *prev_cmp, int *slot)
2590d7396f07SFilipe David Borba Manana {
2591d7396f07SFilipe David Borba Manana 	if (*prev_cmp != 0) {
2592a74b35ecSNikolay Borisov 		*prev_cmp = btrfs_bin_search(b, key, level, slot);
2593d7396f07SFilipe David Borba Manana 		return *prev_cmp;
2594d7396f07SFilipe David Borba Manana 	}
2595d7396f07SFilipe David Borba Manana 
2596d7396f07SFilipe David Borba Manana 	key_search_validate(b, key, level);
2597d7396f07SFilipe David Borba Manana 	*slot = 0;
2598d7396f07SFilipe David Borba Manana 
2599d7396f07SFilipe David Borba Manana 	return 0;
2600d7396f07SFilipe David Borba Manana }
2601d7396f07SFilipe David Borba Manana 
2602381cf658SDavid Sterba int btrfs_find_item(struct btrfs_root *fs_root, struct btrfs_path *path,
2603e33d5c3dSKelley Nielsen 		u64 iobjectid, u64 ioff, u8 key_type,
2604e33d5c3dSKelley Nielsen 		struct btrfs_key *found_key)
2605e33d5c3dSKelley Nielsen {
2606e33d5c3dSKelley Nielsen 	int ret;
2607e33d5c3dSKelley Nielsen 	struct btrfs_key key;
2608e33d5c3dSKelley Nielsen 	struct extent_buffer *eb;
2609381cf658SDavid Sterba 
2610381cf658SDavid Sterba 	ASSERT(path);
26111d4c08e0SDavid Sterba 	ASSERT(found_key);
2612e33d5c3dSKelley Nielsen 
2613e33d5c3dSKelley Nielsen 	key.type = key_type;
2614e33d5c3dSKelley Nielsen 	key.objectid = iobjectid;
2615e33d5c3dSKelley Nielsen 	key.offset = ioff;
2616e33d5c3dSKelley Nielsen 
2617e33d5c3dSKelley Nielsen 	ret = btrfs_search_slot(NULL, fs_root, &key, path, 0, 0);
26181d4c08e0SDavid Sterba 	if (ret < 0)
2619e33d5c3dSKelley Nielsen 		return ret;
2620e33d5c3dSKelley Nielsen 
2621e33d5c3dSKelley Nielsen 	eb = path->nodes[0];
2622e33d5c3dSKelley Nielsen 	if (ret && path->slots[0] >= btrfs_header_nritems(eb)) {
2623e33d5c3dSKelley Nielsen 		ret = btrfs_next_leaf(fs_root, path);
2624e33d5c3dSKelley Nielsen 		if (ret)
2625e33d5c3dSKelley Nielsen 			return ret;
2626e33d5c3dSKelley Nielsen 		eb = path->nodes[0];
2627e33d5c3dSKelley Nielsen 	}
2628e33d5c3dSKelley Nielsen 
2629e33d5c3dSKelley Nielsen 	btrfs_item_key_to_cpu(eb, found_key, path->slots[0]);
2630e33d5c3dSKelley Nielsen 	if (found_key->type != key.type ||
2631e33d5c3dSKelley Nielsen 			found_key->objectid != key.objectid)
2632e33d5c3dSKelley Nielsen 		return 1;
2633e33d5c3dSKelley Nielsen 
2634e33d5c3dSKelley Nielsen 	return 0;
2635e33d5c3dSKelley Nielsen }
2636e33d5c3dSKelley Nielsen 
2637c8c42864SChris Mason /*
26384271eceaSNikolay Borisov  * btrfs_search_slot - look for a key in a tree and perform necessary
26394271eceaSNikolay Borisov  * modifications to preserve tree invariants.
264074123bd7SChris Mason  *
26414271eceaSNikolay Borisov  * @trans:	Handle of transaction, used when modifying the tree
26424271eceaSNikolay Borisov  * @p:		Holds all btree nodes along the search path
26434271eceaSNikolay Borisov  * @root:	The root node of the tree
26444271eceaSNikolay Borisov  * @key:	The key we are looking for
26454271eceaSNikolay Borisov  * @ins_len:	Indicates purpose of search, for inserts it is 1, for
26464271eceaSNikolay Borisov  *		deletions it's -1. 0 for plain searches
26474271eceaSNikolay Borisov  * @cow:	boolean should CoW operations be performed. Must always be 1
26484271eceaSNikolay Borisov  *		when modifying the tree.
264997571fd0SChris Mason  *
26504271eceaSNikolay Borisov  * If @ins_len > 0, nodes and leaves will be split as we walk down the tree.
26514271eceaSNikolay Borisov  * If @ins_len < 0, nodes will be merged as we walk down the tree (if possible)
26524271eceaSNikolay Borisov  *
26534271eceaSNikolay Borisov  * If @key is found, 0 is returned and you can find the item in the leaf level
26544271eceaSNikolay Borisov  * of the path (level 0)
26554271eceaSNikolay Borisov  *
26564271eceaSNikolay Borisov  * If @key isn't found, 1 is returned and the leaf level of the path (level 0)
26574271eceaSNikolay Borisov  * points to the slot where it should be inserted
26584271eceaSNikolay Borisov  *
26594271eceaSNikolay Borisov  * If an error is encountered while searching the tree a negative error number
26604271eceaSNikolay Borisov  * is returned
266174123bd7SChris Mason  */
2662310712b2SOmar Sandoval int btrfs_search_slot(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2663310712b2SOmar Sandoval 		      const struct btrfs_key *key, struct btrfs_path *p,
2664310712b2SOmar Sandoval 		      int ins_len, int cow)
2665be0e5c09SChris Mason {
26660b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
26675f39d397SChris Mason 	struct extent_buffer *b;
2668be0e5c09SChris Mason 	int slot;
2669be0e5c09SChris Mason 	int ret;
267033c66f43SYan Zheng 	int err;
2671be0e5c09SChris Mason 	int level;
2672925baeddSChris Mason 	int lowest_unlock = 1;
2673bd681513SChris Mason 	int root_lock;
2674bd681513SChris Mason 	/* everything at write_lock_level or lower must be write locked */
2675bd681513SChris Mason 	int write_lock_level = 0;
26769f3a7427SChris Mason 	u8 lowest_level = 0;
2677f7c79f30SChris Mason 	int min_write_lock_level;
2678d7396f07SFilipe David Borba Manana 	int prev_cmp;
26799f3a7427SChris Mason 
26806702ed49SChris Mason 	lowest_level = p->lowest_level;
2681323ac95bSChris Mason 	WARN_ON(lowest_level && ins_len > 0);
268222b0ebdaSChris Mason 	WARN_ON(p->nodes[0] != NULL);
2683eb653de1SFilipe David Borba Manana 	BUG_ON(!cow && ins_len);
268425179201SJosef Bacik 
2685bd681513SChris Mason 	if (ins_len < 0) {
2686925baeddSChris Mason 		lowest_unlock = 2;
268765b51a00SChris Mason 
2688bd681513SChris Mason 		/* when we are removing items, we might have to go up to level
2689bd681513SChris Mason 		 * two as we update tree pointers  Make sure we keep write
2690bd681513SChris Mason 		 * for those levels as well
2691bd681513SChris Mason 		 */
2692bd681513SChris Mason 		write_lock_level = 2;
2693bd681513SChris Mason 	} else if (ins_len > 0) {
2694bd681513SChris Mason 		/*
2695bd681513SChris Mason 		 * for inserting items, make sure we have a write lock on
2696bd681513SChris Mason 		 * level 1 so we can update keys
2697bd681513SChris Mason 		 */
2698bd681513SChris Mason 		write_lock_level = 1;
2699bd681513SChris Mason 	}
2700bd681513SChris Mason 
2701bd681513SChris Mason 	if (!cow)
2702bd681513SChris Mason 		write_lock_level = -1;
2703bd681513SChris Mason 
270409a2a8f9SJosef Bacik 	if (cow && (p->keep_locks || p->lowest_level))
2705bd681513SChris Mason 		write_lock_level = BTRFS_MAX_LEVEL;
2706bd681513SChris Mason 
2707f7c79f30SChris Mason 	min_write_lock_level = write_lock_level;
2708f7c79f30SChris Mason 
2709bb803951SChris Mason again:
2710d7396f07SFilipe David Borba Manana 	prev_cmp = -1;
2711bd681513SChris Mason 	/*
2712bd681513SChris Mason 	 * we try very hard to do read locks on the root
2713bd681513SChris Mason 	 */
2714bd681513SChris Mason 	root_lock = BTRFS_READ_LOCK;
2715bd681513SChris Mason 	level = 0;
27165d4f98a2SYan Zheng 	if (p->search_commit_root) {
2717bd681513SChris Mason 		/*
2718bd681513SChris Mason 		 * the commit roots are read only
2719bd681513SChris Mason 		 * so we always do read locks
2720bd681513SChris Mason 		 */
27213f8a18ccSJosef Bacik 		if (p->need_commit_sem)
27220b246afaSJeff Mahoney 			down_read(&fs_info->commit_root_sem);
27235d4f98a2SYan Zheng 		b = root->commit_root;
27245d4f98a2SYan Zheng 		extent_buffer_get(b);
2725bd681513SChris Mason 		level = btrfs_header_level(b);
27263f8a18ccSJosef Bacik 		if (p->need_commit_sem)
27270b246afaSJeff Mahoney 			up_read(&fs_info->commit_root_sem);
27285d4f98a2SYan Zheng 		if (!p->skip_locking)
2729bd681513SChris Mason 			btrfs_tree_read_lock(b);
27305d4f98a2SYan Zheng 	} else {
2731bd681513SChris Mason 		if (p->skip_locking) {
27325cd57b2cSChris Mason 			b = btrfs_root_node(root);
2733bd681513SChris Mason 			level = btrfs_header_level(b);
2734bd681513SChris Mason 		} else {
2735bd681513SChris Mason 			/* we don't know the level of the root node
2736bd681513SChris Mason 			 * until we actually have it read locked
2737bd681513SChris Mason 			 */
2738bd681513SChris Mason 			b = btrfs_read_lock_root_node(root);
2739bd681513SChris Mason 			level = btrfs_header_level(b);
2740bd681513SChris Mason 			if (level <= write_lock_level) {
2741bd681513SChris Mason 				/* whoops, must trade for write lock */
2742bd681513SChris Mason 				btrfs_tree_read_unlock(b);
2743bd681513SChris Mason 				free_extent_buffer(b);
2744925baeddSChris Mason 				b = btrfs_lock_root_node(root);
2745bd681513SChris Mason 				root_lock = BTRFS_WRITE_LOCK;
2746bd681513SChris Mason 
2747bd681513SChris Mason 				/* the level might have changed, check again */
2748bd681513SChris Mason 				level = btrfs_header_level(b);
27495d4f98a2SYan Zheng 			}
2750bd681513SChris Mason 		}
2751bd681513SChris Mason 	}
2752bd681513SChris Mason 	p->nodes[level] = b;
2753bd681513SChris Mason 	if (!p->skip_locking)
2754bd681513SChris Mason 		p->locks[level] = root_lock;
2755925baeddSChris Mason 
2756eb60ceacSChris Mason 	while (b) {
27575f39d397SChris Mason 		level = btrfs_header_level(b);
275865b51a00SChris Mason 
275965b51a00SChris Mason 		/*
276065b51a00SChris Mason 		 * setup the path here so we can release it under lock
276165b51a00SChris Mason 		 * contention with the cow code
276265b51a00SChris Mason 		 */
276302217ed2SChris Mason 		if (cow) {
27649ea2c7c9SNikolay Borisov 			bool last_level = (level == (BTRFS_MAX_LEVEL - 1));
27659ea2c7c9SNikolay Borisov 
2766c8c42864SChris Mason 			/*
2767c8c42864SChris Mason 			 * if we don't really need to cow this block
2768c8c42864SChris Mason 			 * then we don't want to set the path blocking,
2769c8c42864SChris Mason 			 * so we test it here
2770c8c42864SChris Mason 			 */
277164c12921SJeff Mahoney 			if (!should_cow_block(trans, root, b)) {
277264c12921SJeff Mahoney 				trans->dirty = true;
277365b51a00SChris Mason 				goto cow_done;
277464c12921SJeff Mahoney 			}
27755d4f98a2SYan Zheng 
2776bd681513SChris Mason 			/*
2777bd681513SChris Mason 			 * must have write locks on this node and the
2778bd681513SChris Mason 			 * parent
2779bd681513SChris Mason 			 */
27805124e00eSJosef Bacik 			if (level > write_lock_level ||
27815124e00eSJosef Bacik 			    (level + 1 > write_lock_level &&
27825124e00eSJosef Bacik 			    level + 1 < BTRFS_MAX_LEVEL &&
27835124e00eSJosef Bacik 			    p->nodes[level + 1])) {
2784bd681513SChris Mason 				write_lock_level = level + 1;
2785bd681513SChris Mason 				btrfs_release_path(p);
2786bd681513SChris Mason 				goto again;
2787bd681513SChris Mason 			}
2788bd681513SChris Mason 
2789160f4089SFilipe Manana 			btrfs_set_path_blocking(p);
27909ea2c7c9SNikolay Borisov 			if (last_level)
27919ea2c7c9SNikolay Borisov 				err = btrfs_cow_block(trans, root, b, NULL, 0,
27929ea2c7c9SNikolay Borisov 						      &b);
27939ea2c7c9SNikolay Borisov 			else
279433c66f43SYan Zheng 				err = btrfs_cow_block(trans, root, b,
2795e20d96d6SChris Mason 						      p->nodes[level + 1],
27969fa8cfe7SChris Mason 						      p->slots[level + 1], &b);
279733c66f43SYan Zheng 			if (err) {
279833c66f43SYan Zheng 				ret = err;
279965b51a00SChris Mason 				goto done;
280054aa1f4dSChris Mason 			}
280102217ed2SChris Mason 		}
280265b51a00SChris Mason cow_done:
2803eb60ceacSChris Mason 		p->nodes[level] = b;
2804bd681513SChris Mason 		btrfs_clear_path_blocking(p, NULL, 0);
2805b4ce94deSChris Mason 
2806b4ce94deSChris Mason 		/*
2807b4ce94deSChris Mason 		 * we have a lock on b and as long as we aren't changing
2808b4ce94deSChris Mason 		 * the tree, there is no way to for the items in b to change.
2809b4ce94deSChris Mason 		 * It is safe to drop the lock on our parent before we
2810b4ce94deSChris Mason 		 * go through the expensive btree search on b.
2811b4ce94deSChris Mason 		 *
2812eb653de1SFilipe David Borba Manana 		 * If we're inserting or deleting (ins_len != 0), then we might
2813eb653de1SFilipe David Borba Manana 		 * be changing slot zero, which may require changing the parent.
2814eb653de1SFilipe David Borba Manana 		 * So, we can't drop the lock until after we know which slot
2815eb653de1SFilipe David Borba Manana 		 * we're operating on.
2816b4ce94deSChris Mason 		 */
2817eb653de1SFilipe David Borba Manana 		if (!ins_len && !p->keep_locks) {
2818eb653de1SFilipe David Borba Manana 			int u = level + 1;
2819eb653de1SFilipe David Borba Manana 
2820eb653de1SFilipe David Borba Manana 			if (u < BTRFS_MAX_LEVEL && p->locks[u]) {
2821eb653de1SFilipe David Borba Manana 				btrfs_tree_unlock_rw(p->nodes[u], p->locks[u]);
2822eb653de1SFilipe David Borba Manana 				p->locks[u] = 0;
2823eb653de1SFilipe David Borba Manana 			}
2824eb653de1SFilipe David Borba Manana 		}
2825b4ce94deSChris Mason 
2826d7396f07SFilipe David Borba Manana 		ret = key_search(b, key, level, &prev_cmp, &slot);
2827415b35a5SLiu Bo 		if (ret < 0)
2828415b35a5SLiu Bo 			goto done;
2829b4ce94deSChris Mason 
28305f39d397SChris Mason 		if (level != 0) {
283133c66f43SYan Zheng 			int dec = 0;
283233c66f43SYan Zheng 			if (ret && slot > 0) {
283333c66f43SYan Zheng 				dec = 1;
2834be0e5c09SChris Mason 				slot -= 1;
283533c66f43SYan Zheng 			}
2836be0e5c09SChris Mason 			p->slots[level] = slot;
283733c66f43SYan Zheng 			err = setup_nodes_for_search(trans, root, p, b, level,
2838bd681513SChris Mason 					     ins_len, &write_lock_level);
283933c66f43SYan Zheng 			if (err == -EAGAIN)
2840b4ce94deSChris Mason 				goto again;
284133c66f43SYan Zheng 			if (err) {
284233c66f43SYan Zheng 				ret = err;
284365b51a00SChris Mason 				goto done;
284433c66f43SYan Zheng 			}
28455c680ed6SChris Mason 			b = p->nodes[level];
28465c680ed6SChris Mason 			slot = p->slots[level];
2847b4ce94deSChris Mason 
2848bd681513SChris Mason 			/*
2849bd681513SChris Mason 			 * slot 0 is special, if we change the key
2850bd681513SChris Mason 			 * we have to update the parent pointer
2851bd681513SChris Mason 			 * which means we must have a write lock
2852bd681513SChris Mason 			 * on the parent
2853bd681513SChris Mason 			 */
2854eb653de1SFilipe David Borba Manana 			if (slot == 0 && ins_len &&
2855bd681513SChris Mason 			    write_lock_level < level + 1) {
2856bd681513SChris Mason 				write_lock_level = level + 1;
2857bd681513SChris Mason 				btrfs_release_path(p);
2858bd681513SChris Mason 				goto again;
2859bd681513SChris Mason 			}
2860bd681513SChris Mason 
2861f7c79f30SChris Mason 			unlock_up(p, level, lowest_unlock,
2862f7c79f30SChris Mason 				  min_write_lock_level, &write_lock_level);
2863f9efa9c7SChris Mason 
2864925baeddSChris Mason 			if (level == lowest_level) {
286533c66f43SYan Zheng 				if (dec)
286633c66f43SYan Zheng 					p->slots[level]++;
28675b21f2edSZheng Yan 				goto done;
2868925baeddSChris Mason 			}
2869ca7a79adSChris Mason 
2870d07b8528SLiu Bo 			err = read_block_for_search(root, p, &b, level,
2871cda79c54SDavid Sterba 						    slot, key);
287233c66f43SYan Zheng 			if (err == -EAGAIN)
2873051e1b9fSChris Mason 				goto again;
287433c66f43SYan Zheng 			if (err) {
287533c66f43SYan Zheng 				ret = err;
287676a05b35SChris Mason 				goto done;
287733c66f43SYan Zheng 			}
287876a05b35SChris Mason 
2879b4ce94deSChris Mason 			if (!p->skip_locking) {
2880bd681513SChris Mason 				level = btrfs_header_level(b);
2881bd681513SChris Mason 				if (level <= write_lock_level) {
2882bd681513SChris Mason 					err = btrfs_try_tree_write_lock(b);
288333c66f43SYan Zheng 					if (!err) {
2884b4ce94deSChris Mason 						btrfs_set_path_blocking(p);
2885925baeddSChris Mason 						btrfs_tree_lock(b);
2886bd681513SChris Mason 						btrfs_clear_path_blocking(p, b,
2887bd681513SChris Mason 								  BTRFS_WRITE_LOCK);
2888b4ce94deSChris Mason 					}
2889bd681513SChris Mason 					p->locks[level] = BTRFS_WRITE_LOCK;
2890bd681513SChris Mason 				} else {
2891f82c458aSChris Mason 					err = btrfs_tree_read_lock_atomic(b);
2892bd681513SChris Mason 					if (!err) {
2893bd681513SChris Mason 						btrfs_set_path_blocking(p);
2894bd681513SChris Mason 						btrfs_tree_read_lock(b);
2895bd681513SChris Mason 						btrfs_clear_path_blocking(p, b,
2896bd681513SChris Mason 								  BTRFS_READ_LOCK);
2897bd681513SChris Mason 					}
2898bd681513SChris Mason 					p->locks[level] = BTRFS_READ_LOCK;
2899bd681513SChris Mason 				}
2900bd681513SChris Mason 				p->nodes[level] = b;
2901b4ce94deSChris Mason 			}
2902be0e5c09SChris Mason 		} else {
2903be0e5c09SChris Mason 			p->slots[level] = slot;
290487b29b20SYan Zheng 			if (ins_len > 0 &&
29052ff7e61eSJeff Mahoney 			    btrfs_leaf_free_space(fs_info, b) < ins_len) {
2906bd681513SChris Mason 				if (write_lock_level < 1) {
2907bd681513SChris Mason 					write_lock_level = 1;
2908bd681513SChris Mason 					btrfs_release_path(p);
2909bd681513SChris Mason 					goto again;
2910bd681513SChris Mason 				}
2911bd681513SChris Mason 
2912b4ce94deSChris Mason 				btrfs_set_path_blocking(p);
291333c66f43SYan Zheng 				err = split_leaf(trans, root, key,
2914cc0c5538SChris Mason 						 p, ins_len, ret == 0);
2915bd681513SChris Mason 				btrfs_clear_path_blocking(p, NULL, 0);
2916b4ce94deSChris Mason 
291733c66f43SYan Zheng 				BUG_ON(err > 0);
291833c66f43SYan Zheng 				if (err) {
291933c66f43SYan Zheng 					ret = err;
292065b51a00SChris Mason 					goto done;
292165b51a00SChris Mason 				}
29225c680ed6SChris Mason 			}
2923459931ecSChris Mason 			if (!p->search_for_split)
2924f7c79f30SChris Mason 				unlock_up(p, level, lowest_unlock,
2925f7c79f30SChris Mason 					  min_write_lock_level, &write_lock_level);
292665b51a00SChris Mason 			goto done;
292765b51a00SChris Mason 		}
292865b51a00SChris Mason 	}
292965b51a00SChris Mason 	ret = 1;
293065b51a00SChris Mason done:
2931b4ce94deSChris Mason 	/*
2932b4ce94deSChris Mason 	 * we don't really know what they plan on doing with the path
2933b4ce94deSChris Mason 	 * from here on, so for now just mark it as blocking
2934b4ce94deSChris Mason 	 */
2935b9473439SChris Mason 	if (!p->leave_spinning)
2936b4ce94deSChris Mason 		btrfs_set_path_blocking(p);
29375f5bc6b1SFilipe Manana 	if (ret < 0 && !p->skip_release_on_error)
2938b3b4aa74SDavid Sterba 		btrfs_release_path(p);
2939be0e5c09SChris Mason 	return ret;
2940be0e5c09SChris Mason }
2941be0e5c09SChris Mason 
294274123bd7SChris Mason /*
29435d9e75c4SJan Schmidt  * Like btrfs_search_slot, this looks for a key in the given tree. It uses the
29445d9e75c4SJan Schmidt  * current state of the tree together with the operations recorded in the tree
29455d9e75c4SJan Schmidt  * modification log to search for the key in a previous version of this tree, as
29465d9e75c4SJan Schmidt  * denoted by the time_seq parameter.
29475d9e75c4SJan Schmidt  *
29485d9e75c4SJan Schmidt  * Naturally, there is no support for insert, delete or cow operations.
29495d9e75c4SJan Schmidt  *
29505d9e75c4SJan Schmidt  * The resulting path and return value will be set up as if we called
29515d9e75c4SJan Schmidt  * btrfs_search_slot at that point in time with ins_len and cow both set to 0.
29525d9e75c4SJan Schmidt  */
2953310712b2SOmar Sandoval int btrfs_search_old_slot(struct btrfs_root *root, const struct btrfs_key *key,
29545d9e75c4SJan Schmidt 			  struct btrfs_path *p, u64 time_seq)
29555d9e75c4SJan Schmidt {
29560b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
29575d9e75c4SJan Schmidt 	struct extent_buffer *b;
29585d9e75c4SJan Schmidt 	int slot;
29595d9e75c4SJan Schmidt 	int ret;
29605d9e75c4SJan Schmidt 	int err;
29615d9e75c4SJan Schmidt 	int level;
29625d9e75c4SJan Schmidt 	int lowest_unlock = 1;
29635d9e75c4SJan Schmidt 	u8 lowest_level = 0;
2964d4b4087cSJosef Bacik 	int prev_cmp = -1;
29655d9e75c4SJan Schmidt 
29665d9e75c4SJan Schmidt 	lowest_level = p->lowest_level;
29675d9e75c4SJan Schmidt 	WARN_ON(p->nodes[0] != NULL);
29685d9e75c4SJan Schmidt 
29695d9e75c4SJan Schmidt 	if (p->search_commit_root) {
29705d9e75c4SJan Schmidt 		BUG_ON(time_seq);
29715d9e75c4SJan Schmidt 		return btrfs_search_slot(NULL, root, key, p, 0, 0);
29725d9e75c4SJan Schmidt 	}
29735d9e75c4SJan Schmidt 
29745d9e75c4SJan Schmidt again:
29755d9e75c4SJan Schmidt 	b = get_old_root(root, time_seq);
29765d9e75c4SJan Schmidt 	level = btrfs_header_level(b);
29775d9e75c4SJan Schmidt 	p->locks[level] = BTRFS_READ_LOCK;
29785d9e75c4SJan Schmidt 
29795d9e75c4SJan Schmidt 	while (b) {
29805d9e75c4SJan Schmidt 		level = btrfs_header_level(b);
29815d9e75c4SJan Schmidt 		p->nodes[level] = b;
29825d9e75c4SJan Schmidt 		btrfs_clear_path_blocking(p, NULL, 0);
29835d9e75c4SJan Schmidt 
29845d9e75c4SJan Schmidt 		/*
29855d9e75c4SJan Schmidt 		 * we have a lock on b and as long as we aren't changing
29865d9e75c4SJan Schmidt 		 * the tree, there is no way to for the items in b to change.
29875d9e75c4SJan Schmidt 		 * It is safe to drop the lock on our parent before we
29885d9e75c4SJan Schmidt 		 * go through the expensive btree search on b.
29895d9e75c4SJan Schmidt 		 */
29905d9e75c4SJan Schmidt 		btrfs_unlock_up_safe(p, level + 1);
29915d9e75c4SJan Schmidt 
2992d4b4087cSJosef Bacik 		/*
299301327610SNicholas D Steeves 		 * Since we can unwind ebs we want to do a real search every
2994d4b4087cSJosef Bacik 		 * time.
2995d4b4087cSJosef Bacik 		 */
2996d4b4087cSJosef Bacik 		prev_cmp = -1;
2997d7396f07SFilipe David Borba Manana 		ret = key_search(b, key, level, &prev_cmp, &slot);
29985d9e75c4SJan Schmidt 
29995d9e75c4SJan Schmidt 		if (level != 0) {
30005d9e75c4SJan Schmidt 			int dec = 0;
30015d9e75c4SJan Schmidt 			if (ret && slot > 0) {
30025d9e75c4SJan Schmidt 				dec = 1;
30035d9e75c4SJan Schmidt 				slot -= 1;
30045d9e75c4SJan Schmidt 			}
30055d9e75c4SJan Schmidt 			p->slots[level] = slot;
30065d9e75c4SJan Schmidt 			unlock_up(p, level, lowest_unlock, 0, NULL);
30075d9e75c4SJan Schmidt 
30085d9e75c4SJan Schmidt 			if (level == lowest_level) {
30095d9e75c4SJan Schmidt 				if (dec)
30105d9e75c4SJan Schmidt 					p->slots[level]++;
30115d9e75c4SJan Schmidt 				goto done;
30125d9e75c4SJan Schmidt 			}
30135d9e75c4SJan Schmidt 
3014d07b8528SLiu Bo 			err = read_block_for_search(root, p, &b, level,
3015cda79c54SDavid Sterba 						    slot, key);
30165d9e75c4SJan Schmidt 			if (err == -EAGAIN)
30175d9e75c4SJan Schmidt 				goto again;
30185d9e75c4SJan Schmidt 			if (err) {
30195d9e75c4SJan Schmidt 				ret = err;
30205d9e75c4SJan Schmidt 				goto done;
30215d9e75c4SJan Schmidt 			}
30225d9e75c4SJan Schmidt 
30235d9e75c4SJan Schmidt 			level = btrfs_header_level(b);
3024f82c458aSChris Mason 			err = btrfs_tree_read_lock_atomic(b);
30255d9e75c4SJan Schmidt 			if (!err) {
30265d9e75c4SJan Schmidt 				btrfs_set_path_blocking(p);
30275d9e75c4SJan Schmidt 				btrfs_tree_read_lock(b);
30285d9e75c4SJan Schmidt 				btrfs_clear_path_blocking(p, b,
30295d9e75c4SJan Schmidt 							  BTRFS_READ_LOCK);
30305d9e75c4SJan Schmidt 			}
30310b246afaSJeff Mahoney 			b = tree_mod_log_rewind(fs_info, p, b, time_seq);
3032db7f3436SJosef Bacik 			if (!b) {
3033db7f3436SJosef Bacik 				ret = -ENOMEM;
3034db7f3436SJosef Bacik 				goto done;
3035db7f3436SJosef Bacik 			}
30365d9e75c4SJan Schmidt 			p->locks[level] = BTRFS_READ_LOCK;
30375d9e75c4SJan Schmidt 			p->nodes[level] = b;
30385d9e75c4SJan Schmidt 		} else {
30395d9e75c4SJan Schmidt 			p->slots[level] = slot;
30405d9e75c4SJan Schmidt 			unlock_up(p, level, lowest_unlock, 0, NULL);
30415d9e75c4SJan Schmidt 			goto done;
30425d9e75c4SJan Schmidt 		}
30435d9e75c4SJan Schmidt 	}
30445d9e75c4SJan Schmidt 	ret = 1;
30455d9e75c4SJan Schmidt done:
30465d9e75c4SJan Schmidt 	if (!p->leave_spinning)
30475d9e75c4SJan Schmidt 		btrfs_set_path_blocking(p);
30485d9e75c4SJan Schmidt 	if (ret < 0)
30495d9e75c4SJan Schmidt 		btrfs_release_path(p);
30505d9e75c4SJan Schmidt 
30515d9e75c4SJan Schmidt 	return ret;
30525d9e75c4SJan Schmidt }
30535d9e75c4SJan Schmidt 
30545d9e75c4SJan Schmidt /*
30552f38b3e1SArne Jansen  * helper to use instead of search slot if no exact match is needed but
30562f38b3e1SArne Jansen  * instead the next or previous item should be returned.
30572f38b3e1SArne Jansen  * When find_higher is true, the next higher item is returned, the next lower
30582f38b3e1SArne Jansen  * otherwise.
30592f38b3e1SArne Jansen  * When return_any and find_higher are both true, and no higher item is found,
30602f38b3e1SArne Jansen  * return the next lower instead.
30612f38b3e1SArne Jansen  * When return_any is true and find_higher is false, and no lower item is found,
30622f38b3e1SArne Jansen  * return the next higher instead.
30632f38b3e1SArne Jansen  * It returns 0 if any item is found, 1 if none is found (tree empty), and
30642f38b3e1SArne Jansen  * < 0 on error
30652f38b3e1SArne Jansen  */
30662f38b3e1SArne Jansen int btrfs_search_slot_for_read(struct btrfs_root *root,
3067310712b2SOmar Sandoval 			       const struct btrfs_key *key,
3068310712b2SOmar Sandoval 			       struct btrfs_path *p, int find_higher,
3069310712b2SOmar Sandoval 			       int return_any)
30702f38b3e1SArne Jansen {
30712f38b3e1SArne Jansen 	int ret;
30722f38b3e1SArne Jansen 	struct extent_buffer *leaf;
30732f38b3e1SArne Jansen 
30742f38b3e1SArne Jansen again:
30752f38b3e1SArne Jansen 	ret = btrfs_search_slot(NULL, root, key, p, 0, 0);
30762f38b3e1SArne Jansen 	if (ret <= 0)
30772f38b3e1SArne Jansen 		return ret;
30782f38b3e1SArne Jansen 	/*
30792f38b3e1SArne Jansen 	 * a return value of 1 means the path is at the position where the
30802f38b3e1SArne Jansen 	 * item should be inserted. Normally this is the next bigger item,
30812f38b3e1SArne Jansen 	 * but in case the previous item is the last in a leaf, path points
30822f38b3e1SArne Jansen 	 * to the first free slot in the previous leaf, i.e. at an invalid
30832f38b3e1SArne Jansen 	 * item.
30842f38b3e1SArne Jansen 	 */
30852f38b3e1SArne Jansen 	leaf = p->nodes[0];
30862f38b3e1SArne Jansen 
30872f38b3e1SArne Jansen 	if (find_higher) {
30882f38b3e1SArne Jansen 		if (p->slots[0] >= btrfs_header_nritems(leaf)) {
30892f38b3e1SArne Jansen 			ret = btrfs_next_leaf(root, p);
30902f38b3e1SArne Jansen 			if (ret <= 0)
30912f38b3e1SArne Jansen 				return ret;
30922f38b3e1SArne Jansen 			if (!return_any)
30932f38b3e1SArne Jansen 				return 1;
30942f38b3e1SArne Jansen 			/*
30952f38b3e1SArne Jansen 			 * no higher item found, return the next
30962f38b3e1SArne Jansen 			 * lower instead
30972f38b3e1SArne Jansen 			 */
30982f38b3e1SArne Jansen 			return_any = 0;
30992f38b3e1SArne Jansen 			find_higher = 0;
31002f38b3e1SArne Jansen 			btrfs_release_path(p);
31012f38b3e1SArne Jansen 			goto again;
31022f38b3e1SArne Jansen 		}
31032f38b3e1SArne Jansen 	} else {
31042f38b3e1SArne Jansen 		if (p->slots[0] == 0) {
31052f38b3e1SArne Jansen 			ret = btrfs_prev_leaf(root, p);
3106e6793769SArne Jansen 			if (ret < 0)
31072f38b3e1SArne Jansen 				return ret;
3108e6793769SArne Jansen 			if (!ret) {
310923c6bf6aSFilipe David Borba Manana 				leaf = p->nodes[0];
311023c6bf6aSFilipe David Borba Manana 				if (p->slots[0] == btrfs_header_nritems(leaf))
311123c6bf6aSFilipe David Borba Manana 					p->slots[0]--;
3112e6793769SArne Jansen 				return 0;
3113e6793769SArne Jansen 			}
31142f38b3e1SArne Jansen 			if (!return_any)
31152f38b3e1SArne Jansen 				return 1;
31162f38b3e1SArne Jansen 			/*
31172f38b3e1SArne Jansen 			 * no lower item found, return the next
31182f38b3e1SArne Jansen 			 * higher instead
31192f38b3e1SArne Jansen 			 */
31202f38b3e1SArne Jansen 			return_any = 0;
31212f38b3e1SArne Jansen 			find_higher = 1;
31222f38b3e1SArne Jansen 			btrfs_release_path(p);
31232f38b3e1SArne Jansen 			goto again;
3124e6793769SArne Jansen 		} else {
31252f38b3e1SArne Jansen 			--p->slots[0];
31262f38b3e1SArne Jansen 		}
31272f38b3e1SArne Jansen 	}
31282f38b3e1SArne Jansen 	return 0;
31292f38b3e1SArne Jansen }
31302f38b3e1SArne Jansen 
31312f38b3e1SArne Jansen /*
313274123bd7SChris Mason  * adjust the pointers going up the tree, starting at level
313374123bd7SChris Mason  * making sure the right key of each node is points to 'key'.
313474123bd7SChris Mason  * This is used after shifting pointers to the left, so it stops
313574123bd7SChris Mason  * fixing up pointers when a given leaf/node is not in slot 0 of the
313674123bd7SChris Mason  * higher levels
3137aa5d6bedSChris Mason  *
313874123bd7SChris Mason  */
3139b7a0365eSDaniel Dressler static void fixup_low_keys(struct btrfs_fs_info *fs_info,
3140b7a0365eSDaniel Dressler 			   struct btrfs_path *path,
31415f39d397SChris Mason 			   struct btrfs_disk_key *key, int level)
3142be0e5c09SChris Mason {
3143be0e5c09SChris Mason 	int i;
31445f39d397SChris Mason 	struct extent_buffer *t;
31455f39d397SChris Mason 
3146234b63a0SChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
3147be0e5c09SChris Mason 		int tslot = path->slots[i];
3148eb60ceacSChris Mason 		if (!path->nodes[i])
3149be0e5c09SChris Mason 			break;
31505f39d397SChris Mason 		t = path->nodes[i];
31513ac6de1aSDavid Sterba 		tree_mod_log_set_node_key(t, tslot, 1);
31525f39d397SChris Mason 		btrfs_set_node_key(t, key, tslot);
3153d6025579SChris Mason 		btrfs_mark_buffer_dirty(path->nodes[i]);
3154be0e5c09SChris Mason 		if (tslot != 0)
3155be0e5c09SChris Mason 			break;
3156be0e5c09SChris Mason 	}
3157be0e5c09SChris Mason }
3158be0e5c09SChris Mason 
315974123bd7SChris Mason /*
316031840ae1SZheng Yan  * update item key.
316131840ae1SZheng Yan  *
316231840ae1SZheng Yan  * This function isn't completely safe. It's the caller's responsibility
316331840ae1SZheng Yan  * that the new key won't break the order
316431840ae1SZheng Yan  */
3165b7a0365eSDaniel Dressler void btrfs_set_item_key_safe(struct btrfs_fs_info *fs_info,
3166b7a0365eSDaniel Dressler 			     struct btrfs_path *path,
3167310712b2SOmar Sandoval 			     const struct btrfs_key *new_key)
316831840ae1SZheng Yan {
316931840ae1SZheng Yan 	struct btrfs_disk_key disk_key;
317031840ae1SZheng Yan 	struct extent_buffer *eb;
317131840ae1SZheng Yan 	int slot;
317231840ae1SZheng Yan 
317331840ae1SZheng Yan 	eb = path->nodes[0];
317431840ae1SZheng Yan 	slot = path->slots[0];
317531840ae1SZheng Yan 	if (slot > 0) {
317631840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot - 1);
3177143bede5SJeff Mahoney 		BUG_ON(comp_keys(&disk_key, new_key) >= 0);
317831840ae1SZheng Yan 	}
317931840ae1SZheng Yan 	if (slot < btrfs_header_nritems(eb) - 1) {
318031840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot + 1);
3181143bede5SJeff Mahoney 		BUG_ON(comp_keys(&disk_key, new_key) <= 0);
318231840ae1SZheng Yan 	}
318331840ae1SZheng Yan 
318431840ae1SZheng Yan 	btrfs_cpu_key_to_disk(&disk_key, new_key);
318531840ae1SZheng Yan 	btrfs_set_item_key(eb, &disk_key, slot);
318631840ae1SZheng Yan 	btrfs_mark_buffer_dirty(eb);
318731840ae1SZheng Yan 	if (slot == 0)
3188b7a0365eSDaniel Dressler 		fixup_low_keys(fs_info, path, &disk_key, 1);
318931840ae1SZheng Yan }
319031840ae1SZheng Yan 
319131840ae1SZheng Yan /*
319274123bd7SChris Mason  * try to push data from one node into the next node left in the
319379f95c82SChris Mason  * tree.
3194aa5d6bedSChris Mason  *
3195aa5d6bedSChris Mason  * returns 0 if some ptrs were pushed left, < 0 if there was some horrible
3196aa5d6bedSChris Mason  * error, and > 0 if there was no room in the left hand block.
319774123bd7SChris Mason  */
319898ed5174SChris Mason static int push_node_left(struct btrfs_trans_handle *trans,
31992ff7e61eSJeff Mahoney 			  struct btrfs_fs_info *fs_info,
32002ff7e61eSJeff Mahoney 			  struct extent_buffer *dst,
3201971a1f66SChris Mason 			  struct extent_buffer *src, int empty)
3202be0e5c09SChris Mason {
3203be0e5c09SChris Mason 	int push_items = 0;
3204bb803951SChris Mason 	int src_nritems;
3205bb803951SChris Mason 	int dst_nritems;
3206aa5d6bedSChris Mason 	int ret = 0;
3207be0e5c09SChris Mason 
32085f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
32095f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
32100b246afaSJeff Mahoney 	push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
32117bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
32127bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
321354aa1f4dSChris Mason 
3214bce4eae9SChris Mason 	if (!empty && src_nritems <= 8)
3215971a1f66SChris Mason 		return 1;
3216971a1f66SChris Mason 
3217d397712bSChris Mason 	if (push_items <= 0)
3218be0e5c09SChris Mason 		return 1;
3219be0e5c09SChris Mason 
3220bce4eae9SChris Mason 	if (empty) {
3221971a1f66SChris Mason 		push_items = min(src_nritems, push_items);
3222bce4eae9SChris Mason 		if (push_items < src_nritems) {
3223bce4eae9SChris Mason 			/* leave at least 8 pointers in the node if
3224bce4eae9SChris Mason 			 * we aren't going to empty it
3225bce4eae9SChris Mason 			 */
3226bce4eae9SChris Mason 			if (src_nritems - push_items < 8) {
3227bce4eae9SChris Mason 				if (push_items <= 8)
3228bce4eae9SChris Mason 					return 1;
3229bce4eae9SChris Mason 				push_items -= 8;
3230bce4eae9SChris Mason 			}
3231bce4eae9SChris Mason 		}
3232bce4eae9SChris Mason 	} else
3233bce4eae9SChris Mason 		push_items = min(src_nritems - 8, push_items);
323479f95c82SChris Mason 
32350b246afaSJeff Mahoney 	ret = tree_mod_log_eb_copy(fs_info, dst, src, dst_nritems, 0,
323690f8d62eSJan Schmidt 				   push_items);
32375de865eeSFilipe David Borba Manana 	if (ret) {
323866642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
32395de865eeSFilipe David Borba Manana 		return ret;
32405de865eeSFilipe David Borba Manana 	}
32415f39d397SChris Mason 	copy_extent_buffer(dst, src,
32425f39d397SChris Mason 			   btrfs_node_key_ptr_offset(dst_nritems),
32435f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
3244123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
32455f39d397SChris Mason 
3246bb803951SChris Mason 	if (push_items < src_nritems) {
324757911b8bSJan Schmidt 		/*
324857911b8bSJan Schmidt 		 * don't call tree_mod_log_eb_move here, key removal was already
324957911b8bSJan Schmidt 		 * fully logged by tree_mod_log_eb_copy above.
325057911b8bSJan Schmidt 		 */
32515f39d397SChris Mason 		memmove_extent_buffer(src, btrfs_node_key_ptr_offset(0),
32525f39d397SChris Mason 				      btrfs_node_key_ptr_offset(push_items),
3253e2fa7227SChris Mason 				      (src_nritems - push_items) *
3254123abc88SChris Mason 				      sizeof(struct btrfs_key_ptr));
3255bb803951SChris Mason 	}
32565f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
32575f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
32585f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
32595f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
326031840ae1SZheng Yan 
3261bb803951SChris Mason 	return ret;
3262be0e5c09SChris Mason }
3263be0e5c09SChris Mason 
326497571fd0SChris Mason /*
326579f95c82SChris Mason  * try to push data from one node into the next node right in the
326679f95c82SChris Mason  * tree.
326779f95c82SChris Mason  *
326879f95c82SChris Mason  * returns 0 if some ptrs were pushed, < 0 if there was some horrible
326979f95c82SChris Mason  * error, and > 0 if there was no room in the right hand block.
327079f95c82SChris Mason  *
327179f95c82SChris Mason  * this will  only push up to 1/2 the contents of the left node over
327279f95c82SChris Mason  */
32735f39d397SChris Mason static int balance_node_right(struct btrfs_trans_handle *trans,
32742ff7e61eSJeff Mahoney 			      struct btrfs_fs_info *fs_info,
32755f39d397SChris Mason 			      struct extent_buffer *dst,
32765f39d397SChris Mason 			      struct extent_buffer *src)
327779f95c82SChris Mason {
327879f95c82SChris Mason 	int push_items = 0;
327979f95c82SChris Mason 	int max_push;
328079f95c82SChris Mason 	int src_nritems;
328179f95c82SChris Mason 	int dst_nritems;
328279f95c82SChris Mason 	int ret = 0;
328379f95c82SChris Mason 
32847bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
32857bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
32867bb86316SChris Mason 
32875f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
32885f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
32890b246afaSJeff Mahoney 	push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
3290d397712bSChris Mason 	if (push_items <= 0)
329179f95c82SChris Mason 		return 1;
3292bce4eae9SChris Mason 
3293d397712bSChris Mason 	if (src_nritems < 4)
3294bce4eae9SChris Mason 		return 1;
329579f95c82SChris Mason 
329679f95c82SChris Mason 	max_push = src_nritems / 2 + 1;
329779f95c82SChris Mason 	/* don't try to empty the node */
3298d397712bSChris Mason 	if (max_push >= src_nritems)
329979f95c82SChris Mason 		return 1;
3300252c38f0SYan 
330179f95c82SChris Mason 	if (max_push < push_items)
330279f95c82SChris Mason 		push_items = max_push;
330379f95c82SChris Mason 
3304a446a979SDavid Sterba 	tree_mod_log_eb_move(dst, push_items, 0, dst_nritems);
33055f39d397SChris Mason 	memmove_extent_buffer(dst, btrfs_node_key_ptr_offset(push_items),
33065f39d397SChris Mason 				      btrfs_node_key_ptr_offset(0),
33075f39d397SChris Mason 				      (dst_nritems) *
33085f39d397SChris Mason 				      sizeof(struct btrfs_key_ptr));
3309d6025579SChris Mason 
33100b246afaSJeff Mahoney 	ret = tree_mod_log_eb_copy(fs_info, dst, src, 0,
331190f8d62eSJan Schmidt 				   src_nritems - push_items, push_items);
33125de865eeSFilipe David Borba Manana 	if (ret) {
331366642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
33145de865eeSFilipe David Borba Manana 		return ret;
33155de865eeSFilipe David Borba Manana 	}
33165f39d397SChris Mason 	copy_extent_buffer(dst, src,
33175f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
33185f39d397SChris Mason 			   btrfs_node_key_ptr_offset(src_nritems - push_items),
3319123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
332079f95c82SChris Mason 
33215f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
33225f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
332379f95c82SChris Mason 
33245f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
33255f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
332631840ae1SZheng Yan 
332779f95c82SChris Mason 	return ret;
332879f95c82SChris Mason }
332979f95c82SChris Mason 
333079f95c82SChris Mason /*
333197571fd0SChris Mason  * helper function to insert a new root level in the tree.
333297571fd0SChris Mason  * A new node is allocated, and a single item is inserted to
333397571fd0SChris Mason  * point to the existing root
3334aa5d6bedSChris Mason  *
3335aa5d6bedSChris Mason  * returns zero on success or < 0 on failure.
333697571fd0SChris Mason  */
3337d397712bSChris Mason static noinline int insert_new_root(struct btrfs_trans_handle *trans,
33385f39d397SChris Mason 			   struct btrfs_root *root,
3339fdd99c72SLiu Bo 			   struct btrfs_path *path, int level)
334074123bd7SChris Mason {
33410b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
33427bb86316SChris Mason 	u64 lower_gen;
33435f39d397SChris Mason 	struct extent_buffer *lower;
33445f39d397SChris Mason 	struct extent_buffer *c;
3345925baeddSChris Mason 	struct extent_buffer *old;
33465f39d397SChris Mason 	struct btrfs_disk_key lower_key;
33475c680ed6SChris Mason 
33485c680ed6SChris Mason 	BUG_ON(path->nodes[level]);
33495c680ed6SChris Mason 	BUG_ON(path->nodes[level-1] != root->node);
33505c680ed6SChris Mason 
33517bb86316SChris Mason 	lower = path->nodes[level-1];
33527bb86316SChris Mason 	if (level == 1)
33537bb86316SChris Mason 		btrfs_item_key(lower, &lower_key, 0);
33547bb86316SChris Mason 	else
33557bb86316SChris Mason 		btrfs_node_key(lower, &lower_key, 0);
33567bb86316SChris Mason 
33574d75f8a9SDavid Sterba 	c = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
33584d75f8a9SDavid Sterba 				   &lower_key, level, root->node->start, 0);
33595f39d397SChris Mason 	if (IS_ERR(c))
33605f39d397SChris Mason 		return PTR_ERR(c);
3361925baeddSChris Mason 
33620b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
3363f0486c68SYan, Zheng 
3364b159fa28SDavid Sterba 	memzero_extent_buffer(c, 0, sizeof(struct btrfs_header));
33655f39d397SChris Mason 	btrfs_set_header_nritems(c, 1);
33665f39d397SChris Mason 	btrfs_set_header_level(c, level);
3367db94535dSChris Mason 	btrfs_set_header_bytenr(c, c->start);
33685f39d397SChris Mason 	btrfs_set_header_generation(c, trans->transid);
33695d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(c, BTRFS_MIXED_BACKREF_REV);
33705f39d397SChris Mason 	btrfs_set_header_owner(c, root->root_key.objectid);
3371d5719762SChris Mason 
33720b246afaSJeff Mahoney 	write_extent_buffer_fsid(c, fs_info->fsid);
33730b246afaSJeff Mahoney 	write_extent_buffer_chunk_tree_uuid(c, fs_info->chunk_tree_uuid);
3374e17cade2SChris Mason 
33755f39d397SChris Mason 	btrfs_set_node_key(c, &lower_key, 0);
3376db94535dSChris Mason 	btrfs_set_node_blockptr(c, 0, lower->start);
33777bb86316SChris Mason 	lower_gen = btrfs_header_generation(lower);
337831840ae1SZheng Yan 	WARN_ON(lower_gen != trans->transid);
33797bb86316SChris Mason 
33807bb86316SChris Mason 	btrfs_set_node_ptr_generation(c, 0, lower_gen);
33815f39d397SChris Mason 
33825f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
3383d5719762SChris Mason 
3384925baeddSChris Mason 	old = root->node;
3385fdd99c72SLiu Bo 	tree_mod_log_set_root_pointer(root, c, 0);
3386240f62c8SChris Mason 	rcu_assign_pointer(root->node, c);
3387925baeddSChris Mason 
3388925baeddSChris Mason 	/* the super has an extra ref to root->node */
3389925baeddSChris Mason 	free_extent_buffer(old);
3390925baeddSChris Mason 
33910b86a832SChris Mason 	add_root_to_dirty_list(root);
33925f39d397SChris Mason 	extent_buffer_get(c);
33935f39d397SChris Mason 	path->nodes[level] = c;
339495449a16Schandan 	path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
339574123bd7SChris Mason 	path->slots[level] = 0;
339674123bd7SChris Mason 	return 0;
339774123bd7SChris Mason }
33985c680ed6SChris Mason 
33995c680ed6SChris Mason /*
34005c680ed6SChris Mason  * worker function to insert a single pointer in a node.
34015c680ed6SChris Mason  * the node should have enough room for the pointer already
340297571fd0SChris Mason  *
34035c680ed6SChris Mason  * slot and level indicate where you want the key to go, and
34045c680ed6SChris Mason  * blocknr is the block the key points to.
34055c680ed6SChris Mason  */
3406143bede5SJeff Mahoney static void insert_ptr(struct btrfs_trans_handle *trans,
34072ff7e61eSJeff Mahoney 		       struct btrfs_fs_info *fs_info, struct btrfs_path *path,
3408143bede5SJeff Mahoney 		       struct btrfs_disk_key *key, u64 bytenr,
3409c3e06965SJan Schmidt 		       int slot, int level)
34105c680ed6SChris Mason {
34115f39d397SChris Mason 	struct extent_buffer *lower;
34125c680ed6SChris Mason 	int nritems;
3413f3ea38daSJan Schmidt 	int ret;
34145c680ed6SChris Mason 
34155c680ed6SChris Mason 	BUG_ON(!path->nodes[level]);
3416f0486c68SYan, Zheng 	btrfs_assert_tree_locked(path->nodes[level]);
34175f39d397SChris Mason 	lower = path->nodes[level];
34185f39d397SChris Mason 	nritems = btrfs_header_nritems(lower);
3419c293498bSStoyan Gaydarov 	BUG_ON(slot > nritems);
34200b246afaSJeff Mahoney 	BUG_ON(nritems == BTRFS_NODEPTRS_PER_BLOCK(fs_info));
342174123bd7SChris Mason 	if (slot != nritems) {
3422c3e06965SJan Schmidt 		if (level)
3423a446a979SDavid Sterba 			tree_mod_log_eb_move(lower, slot + 1, slot,
3424a446a979SDavid Sterba 					nritems - slot);
34255f39d397SChris Mason 		memmove_extent_buffer(lower,
34265f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot + 1),
34275f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot),
3428123abc88SChris Mason 			      (nritems - slot) * sizeof(struct btrfs_key_ptr));
342974123bd7SChris Mason 	}
3430c3e06965SJan Schmidt 	if (level) {
3431e09c2efeSDavid Sterba 		ret = tree_mod_log_insert_key(lower, slot, MOD_LOG_KEY_ADD,
3432e09c2efeSDavid Sterba 				GFP_NOFS);
3433f3ea38daSJan Schmidt 		BUG_ON(ret < 0);
3434f3ea38daSJan Schmidt 	}
34355f39d397SChris Mason 	btrfs_set_node_key(lower, key, slot);
3436db94535dSChris Mason 	btrfs_set_node_blockptr(lower, slot, bytenr);
343774493f7aSChris Mason 	WARN_ON(trans->transid == 0);
343874493f7aSChris Mason 	btrfs_set_node_ptr_generation(lower, slot, trans->transid);
34395f39d397SChris Mason 	btrfs_set_header_nritems(lower, nritems + 1);
34405f39d397SChris Mason 	btrfs_mark_buffer_dirty(lower);
344174123bd7SChris Mason }
344274123bd7SChris Mason 
344397571fd0SChris Mason /*
344497571fd0SChris Mason  * split the node at the specified level in path in two.
344597571fd0SChris Mason  * The path is corrected to point to the appropriate node after the split
344697571fd0SChris Mason  *
344797571fd0SChris Mason  * Before splitting this tries to make some room in the node by pushing
344897571fd0SChris Mason  * left and right, if either one works, it returns right away.
3449aa5d6bedSChris Mason  *
3450aa5d6bedSChris Mason  * returns 0 on success and < 0 on failure
345197571fd0SChris Mason  */
3452e02119d5SChris Mason static noinline int split_node(struct btrfs_trans_handle *trans,
3453e02119d5SChris Mason 			       struct btrfs_root *root,
3454e02119d5SChris Mason 			       struct btrfs_path *path, int level)
3455be0e5c09SChris Mason {
34560b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
34575f39d397SChris Mason 	struct extent_buffer *c;
34585f39d397SChris Mason 	struct extent_buffer *split;
34595f39d397SChris Mason 	struct btrfs_disk_key disk_key;
3460be0e5c09SChris Mason 	int mid;
34615c680ed6SChris Mason 	int ret;
34627518a238SChris Mason 	u32 c_nritems;
3463be0e5c09SChris Mason 
34645f39d397SChris Mason 	c = path->nodes[level];
34657bb86316SChris Mason 	WARN_ON(btrfs_header_generation(c) != trans->transid);
34665f39d397SChris Mason 	if (c == root->node) {
3467d9abbf1cSJan Schmidt 		/*
346890f8d62eSJan Schmidt 		 * trying to split the root, lets make a new one
346990f8d62eSJan Schmidt 		 *
3470fdd99c72SLiu Bo 		 * tree mod log: We don't log_removal old root in
347190f8d62eSJan Schmidt 		 * insert_new_root, because that root buffer will be kept as a
347290f8d62eSJan Schmidt 		 * normal node. We are going to log removal of half of the
347390f8d62eSJan Schmidt 		 * elements below with tree_mod_log_eb_copy. We're holding a
347490f8d62eSJan Schmidt 		 * tree lock on the buffer, which is why we cannot race with
347590f8d62eSJan Schmidt 		 * other tree_mod_log users.
3476d9abbf1cSJan Schmidt 		 */
3477fdd99c72SLiu Bo 		ret = insert_new_root(trans, root, path, level + 1);
34785c680ed6SChris Mason 		if (ret)
34795c680ed6SChris Mason 			return ret;
3480b3612421SChris Mason 	} else {
3481e66f709bSChris Mason 		ret = push_nodes_for_insert(trans, root, path, level);
34825f39d397SChris Mason 		c = path->nodes[level];
34835f39d397SChris Mason 		if (!ret && btrfs_header_nritems(c) <
34840b246afaSJeff Mahoney 		    BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3)
3485e66f709bSChris Mason 			return 0;
348654aa1f4dSChris Mason 		if (ret < 0)
348754aa1f4dSChris Mason 			return ret;
34885c680ed6SChris Mason 	}
3489e66f709bSChris Mason 
34905f39d397SChris Mason 	c_nritems = btrfs_header_nritems(c);
34915d4f98a2SYan Zheng 	mid = (c_nritems + 1) / 2;
34925d4f98a2SYan Zheng 	btrfs_node_key(c, &disk_key, mid);
34937bb86316SChris Mason 
34944d75f8a9SDavid Sterba 	split = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
34955581a51aSJan Schmidt 			&disk_key, level, c->start, 0);
34965f39d397SChris Mason 	if (IS_ERR(split))
34975f39d397SChris Mason 		return PTR_ERR(split);
349854aa1f4dSChris Mason 
34990b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
3500f0486c68SYan, Zheng 
3501b159fa28SDavid Sterba 	memzero_extent_buffer(split, 0, sizeof(struct btrfs_header));
35025f39d397SChris Mason 	btrfs_set_header_level(split, btrfs_header_level(c));
3503db94535dSChris Mason 	btrfs_set_header_bytenr(split, split->start);
35045f39d397SChris Mason 	btrfs_set_header_generation(split, trans->transid);
35055d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(split, BTRFS_MIXED_BACKREF_REV);
35065f39d397SChris Mason 	btrfs_set_header_owner(split, root->root_key.objectid);
35070b246afaSJeff Mahoney 	write_extent_buffer_fsid(split, fs_info->fsid);
35080b246afaSJeff Mahoney 	write_extent_buffer_chunk_tree_uuid(split, fs_info->chunk_tree_uuid);
35095f39d397SChris Mason 
35100b246afaSJeff Mahoney 	ret = tree_mod_log_eb_copy(fs_info, split, c, 0, mid, c_nritems - mid);
35115de865eeSFilipe David Borba Manana 	if (ret) {
351266642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
35135de865eeSFilipe David Borba Manana 		return ret;
35145de865eeSFilipe David Borba Manana 	}
35155f39d397SChris Mason 	copy_extent_buffer(split, c,
35165f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
35175f39d397SChris Mason 			   btrfs_node_key_ptr_offset(mid),
3518123abc88SChris Mason 			   (c_nritems - mid) * sizeof(struct btrfs_key_ptr));
35195f39d397SChris Mason 	btrfs_set_header_nritems(split, c_nritems - mid);
35205f39d397SChris Mason 	btrfs_set_header_nritems(c, mid);
3521aa5d6bedSChris Mason 	ret = 0;
3522aa5d6bedSChris Mason 
35235f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
35245f39d397SChris Mason 	btrfs_mark_buffer_dirty(split);
35255f39d397SChris Mason 
35262ff7e61eSJeff Mahoney 	insert_ptr(trans, fs_info, path, &disk_key, split->start,
3527c3e06965SJan Schmidt 		   path->slots[level + 1] + 1, level + 1);
3528aa5d6bedSChris Mason 
35295de08d7dSChris Mason 	if (path->slots[level] >= mid) {
35305c680ed6SChris Mason 		path->slots[level] -= mid;
3531925baeddSChris Mason 		btrfs_tree_unlock(c);
35325f39d397SChris Mason 		free_extent_buffer(c);
35335f39d397SChris Mason 		path->nodes[level] = split;
35345c680ed6SChris Mason 		path->slots[level + 1] += 1;
3535eb60ceacSChris Mason 	} else {
3536925baeddSChris Mason 		btrfs_tree_unlock(split);
35375f39d397SChris Mason 		free_extent_buffer(split);
3538be0e5c09SChris Mason 	}
3539aa5d6bedSChris Mason 	return ret;
3540be0e5c09SChris Mason }
3541be0e5c09SChris Mason 
354274123bd7SChris Mason /*
354374123bd7SChris Mason  * how many bytes are required to store the items in a leaf.  start
354474123bd7SChris Mason  * and nr indicate which items in the leaf to check.  This totals up the
354574123bd7SChris Mason  * space used both by the item structs and the item data
354674123bd7SChris Mason  */
35475f39d397SChris Mason static int leaf_space_used(struct extent_buffer *l, int start, int nr)
3548be0e5c09SChris Mason {
354941be1f3bSJosef Bacik 	struct btrfs_item *start_item;
355041be1f3bSJosef Bacik 	struct btrfs_item *end_item;
355141be1f3bSJosef Bacik 	struct btrfs_map_token token;
3552be0e5c09SChris Mason 	int data_len;
35535f39d397SChris Mason 	int nritems = btrfs_header_nritems(l);
3554d4dbff95SChris Mason 	int end = min(nritems, start + nr) - 1;
3555be0e5c09SChris Mason 
3556be0e5c09SChris Mason 	if (!nr)
3557be0e5c09SChris Mason 		return 0;
355841be1f3bSJosef Bacik 	btrfs_init_map_token(&token);
3559dd3cc16bSRoss Kirk 	start_item = btrfs_item_nr(start);
3560dd3cc16bSRoss Kirk 	end_item = btrfs_item_nr(end);
356141be1f3bSJosef Bacik 	data_len = btrfs_token_item_offset(l, start_item, &token) +
356241be1f3bSJosef Bacik 		btrfs_token_item_size(l, start_item, &token);
356341be1f3bSJosef Bacik 	data_len = data_len - btrfs_token_item_offset(l, end_item, &token);
35640783fcfcSChris Mason 	data_len += sizeof(struct btrfs_item) * nr;
3565d4dbff95SChris Mason 	WARN_ON(data_len < 0);
3566be0e5c09SChris Mason 	return data_len;
3567be0e5c09SChris Mason }
3568be0e5c09SChris Mason 
356974123bd7SChris Mason /*
3570d4dbff95SChris Mason  * The space between the end of the leaf items and
3571d4dbff95SChris Mason  * the start of the leaf data.  IOW, how much room
3572d4dbff95SChris Mason  * the leaf has left for both items and data
3573d4dbff95SChris Mason  */
35742ff7e61eSJeff Mahoney noinline int btrfs_leaf_free_space(struct btrfs_fs_info *fs_info,
3575e02119d5SChris Mason 				   struct extent_buffer *leaf)
3576d4dbff95SChris Mason {
35775f39d397SChris Mason 	int nritems = btrfs_header_nritems(leaf);
35785f39d397SChris Mason 	int ret;
35790b246afaSJeff Mahoney 
35800b246afaSJeff Mahoney 	ret = BTRFS_LEAF_DATA_SIZE(fs_info) - leaf_space_used(leaf, 0, nritems);
35815f39d397SChris Mason 	if (ret < 0) {
35820b246afaSJeff Mahoney 		btrfs_crit(fs_info,
3583efe120a0SFrank Holton 			   "leaf free space ret %d, leaf data size %lu, used %d nritems %d",
3584da17066cSJeff Mahoney 			   ret,
35850b246afaSJeff Mahoney 			   (unsigned long) BTRFS_LEAF_DATA_SIZE(fs_info),
35865f39d397SChris Mason 			   leaf_space_used(leaf, 0, nritems), nritems);
35875f39d397SChris Mason 	}
35885f39d397SChris Mason 	return ret;
3589d4dbff95SChris Mason }
3590d4dbff95SChris Mason 
359199d8f83cSChris Mason /*
359299d8f83cSChris Mason  * min slot controls the lowest index we're willing to push to the
359399d8f83cSChris Mason  * right.  We'll push up to and including min_slot, but no lower
359499d8f83cSChris Mason  */
35951e47eef2SDavid Sterba static noinline int __push_leaf_right(struct btrfs_fs_info *fs_info,
359644871b1bSChris Mason 				      struct btrfs_path *path,
359744871b1bSChris Mason 				      int data_size, int empty,
359844871b1bSChris Mason 				      struct extent_buffer *right,
359999d8f83cSChris Mason 				      int free_space, u32 left_nritems,
360099d8f83cSChris Mason 				      u32 min_slot)
360100ec4c51SChris Mason {
36025f39d397SChris Mason 	struct extent_buffer *left = path->nodes[0];
360344871b1bSChris Mason 	struct extent_buffer *upper = path->nodes[1];
3604cfed81a0SChris Mason 	struct btrfs_map_token token;
36055f39d397SChris Mason 	struct btrfs_disk_key disk_key;
360600ec4c51SChris Mason 	int slot;
360734a38218SChris Mason 	u32 i;
360800ec4c51SChris Mason 	int push_space = 0;
360900ec4c51SChris Mason 	int push_items = 0;
36100783fcfcSChris Mason 	struct btrfs_item *item;
361134a38218SChris Mason 	u32 nr;
36127518a238SChris Mason 	u32 right_nritems;
36135f39d397SChris Mason 	u32 data_end;
3614db94535dSChris Mason 	u32 this_item_size;
361500ec4c51SChris Mason 
3616cfed81a0SChris Mason 	btrfs_init_map_token(&token);
3617cfed81a0SChris Mason 
361834a38218SChris Mason 	if (empty)
361934a38218SChris Mason 		nr = 0;
362034a38218SChris Mason 	else
362199d8f83cSChris Mason 		nr = max_t(u32, 1, min_slot);
362234a38218SChris Mason 
362331840ae1SZheng Yan 	if (path->slots[0] >= left_nritems)
362487b29b20SYan Zheng 		push_space += data_size;
362531840ae1SZheng Yan 
362644871b1bSChris Mason 	slot = path->slots[1];
362734a38218SChris Mason 	i = left_nritems - 1;
362834a38218SChris Mason 	while (i >= nr) {
3629dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
3630db94535dSChris Mason 
363131840ae1SZheng Yan 		if (!empty && push_items > 0) {
363231840ae1SZheng Yan 			if (path->slots[0] > i)
363331840ae1SZheng Yan 				break;
363431840ae1SZheng Yan 			if (path->slots[0] == i) {
36352ff7e61eSJeff Mahoney 				int space = btrfs_leaf_free_space(fs_info, left);
363631840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
363731840ae1SZheng Yan 					break;
363831840ae1SZheng Yan 			}
363931840ae1SZheng Yan 		}
364031840ae1SZheng Yan 
364100ec4c51SChris Mason 		if (path->slots[0] == i)
364287b29b20SYan Zheng 			push_space += data_size;
3643db94535dSChris Mason 
3644db94535dSChris Mason 		this_item_size = btrfs_item_size(left, item);
3645db94535dSChris Mason 		if (this_item_size + sizeof(*item) + push_space > free_space)
364600ec4c51SChris Mason 			break;
364731840ae1SZheng Yan 
364800ec4c51SChris Mason 		push_items++;
3649db94535dSChris Mason 		push_space += this_item_size + sizeof(*item);
365034a38218SChris Mason 		if (i == 0)
365134a38218SChris Mason 			break;
365234a38218SChris Mason 		i--;
3653db94535dSChris Mason 	}
36545f39d397SChris Mason 
3655925baeddSChris Mason 	if (push_items == 0)
3656925baeddSChris Mason 		goto out_unlock;
36575f39d397SChris Mason 
36586c1500f2SJulia Lawall 	WARN_ON(!empty && push_items == left_nritems);
36595f39d397SChris Mason 
366000ec4c51SChris Mason 	/* push left to right */
36615f39d397SChris Mason 	right_nritems = btrfs_header_nritems(right);
366234a38218SChris Mason 
36635f39d397SChris Mason 	push_space = btrfs_item_end_nr(left, left_nritems - push_items);
36642ff7e61eSJeff Mahoney 	push_space -= leaf_data_end(fs_info, left);
36655f39d397SChris Mason 
366600ec4c51SChris Mason 	/* make room in the right data area */
36672ff7e61eSJeff Mahoney 	data_end = leaf_data_end(fs_info, right);
36685f39d397SChris Mason 	memmove_extent_buffer(right,
36693d9ec8c4SNikolay Borisov 			      BTRFS_LEAF_DATA_OFFSET + data_end - push_space,
36703d9ec8c4SNikolay Borisov 			      BTRFS_LEAF_DATA_OFFSET + data_end,
36710b246afaSJeff Mahoney 			      BTRFS_LEAF_DATA_SIZE(fs_info) - data_end);
36725f39d397SChris Mason 
367300ec4c51SChris Mason 	/* copy from the left data area */
36743d9ec8c4SNikolay Borisov 	copy_extent_buffer(right, left, BTRFS_LEAF_DATA_OFFSET +
36750b246afaSJeff Mahoney 		     BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
36763d9ec8c4SNikolay Borisov 		     BTRFS_LEAF_DATA_OFFSET + leaf_data_end(fs_info, left),
3677d6025579SChris Mason 		     push_space);
36785f39d397SChris Mason 
36795f39d397SChris Mason 	memmove_extent_buffer(right, btrfs_item_nr_offset(push_items),
36805f39d397SChris Mason 			      btrfs_item_nr_offset(0),
36810783fcfcSChris Mason 			      right_nritems * sizeof(struct btrfs_item));
36825f39d397SChris Mason 
368300ec4c51SChris Mason 	/* copy the items from left to right */
36845f39d397SChris Mason 	copy_extent_buffer(right, left, btrfs_item_nr_offset(0),
36855f39d397SChris Mason 		   btrfs_item_nr_offset(left_nritems - push_items),
36860783fcfcSChris Mason 		   push_items * sizeof(struct btrfs_item));
368700ec4c51SChris Mason 
368800ec4c51SChris Mason 	/* update the item pointers */
36897518a238SChris Mason 	right_nritems += push_items;
36905f39d397SChris Mason 	btrfs_set_header_nritems(right, right_nritems);
36910b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
36927518a238SChris Mason 	for (i = 0; i < right_nritems; i++) {
3693dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
3694cfed81a0SChris Mason 		push_space -= btrfs_token_item_size(right, item, &token);
3695cfed81a0SChris Mason 		btrfs_set_token_item_offset(right, item, push_space, &token);
3696db94535dSChris Mason 	}
3697db94535dSChris Mason 
36987518a238SChris Mason 	left_nritems -= push_items;
36995f39d397SChris Mason 	btrfs_set_header_nritems(left, left_nritems);
370000ec4c51SChris Mason 
370134a38218SChris Mason 	if (left_nritems)
37025f39d397SChris Mason 		btrfs_mark_buffer_dirty(left);
3703f0486c68SYan, Zheng 	else
37047c302b49SDavid Sterba 		clean_tree_block(fs_info, left);
3705f0486c68SYan, Zheng 
37065f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
3707a429e513SChris Mason 
37085f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
37095f39d397SChris Mason 	btrfs_set_node_key(upper, &disk_key, slot + 1);
3710d6025579SChris Mason 	btrfs_mark_buffer_dirty(upper);
371102217ed2SChris Mason 
371200ec4c51SChris Mason 	/* then fixup the leaf pointer in the path */
37137518a238SChris Mason 	if (path->slots[0] >= left_nritems) {
37147518a238SChris Mason 		path->slots[0] -= left_nritems;
3715925baeddSChris Mason 		if (btrfs_header_nritems(path->nodes[0]) == 0)
37167c302b49SDavid Sterba 			clean_tree_block(fs_info, path->nodes[0]);
3717925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
37185f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
37195f39d397SChris Mason 		path->nodes[0] = right;
372000ec4c51SChris Mason 		path->slots[1] += 1;
372100ec4c51SChris Mason 	} else {
3722925baeddSChris Mason 		btrfs_tree_unlock(right);
37235f39d397SChris Mason 		free_extent_buffer(right);
372400ec4c51SChris Mason 	}
372500ec4c51SChris Mason 	return 0;
3726925baeddSChris Mason 
3727925baeddSChris Mason out_unlock:
3728925baeddSChris Mason 	btrfs_tree_unlock(right);
3729925baeddSChris Mason 	free_extent_buffer(right);
3730925baeddSChris Mason 	return 1;
373100ec4c51SChris Mason }
3732925baeddSChris Mason 
373300ec4c51SChris Mason /*
373444871b1bSChris Mason  * push some data in the path leaf to the right, trying to free up at
373574123bd7SChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
373644871b1bSChris Mason  *
373744871b1bSChris Mason  * returns 1 if the push failed because the other node didn't have enough
373844871b1bSChris Mason  * room, 0 if everything worked out and < 0 if there were major errors.
373999d8f83cSChris Mason  *
374099d8f83cSChris Mason  * this will push starting from min_slot to the end of the leaf.  It won't
374199d8f83cSChris Mason  * push any slot lower than min_slot
374274123bd7SChris Mason  */
374344871b1bSChris Mason static int push_leaf_right(struct btrfs_trans_handle *trans, struct btrfs_root
374499d8f83cSChris Mason 			   *root, struct btrfs_path *path,
374599d8f83cSChris Mason 			   int min_data_size, int data_size,
374699d8f83cSChris Mason 			   int empty, u32 min_slot)
3747be0e5c09SChris Mason {
37482ff7e61eSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
374944871b1bSChris Mason 	struct extent_buffer *left = path->nodes[0];
375044871b1bSChris Mason 	struct extent_buffer *right;
375144871b1bSChris Mason 	struct extent_buffer *upper;
375244871b1bSChris Mason 	int slot;
375344871b1bSChris Mason 	int free_space;
375444871b1bSChris Mason 	u32 left_nritems;
375544871b1bSChris Mason 	int ret;
375644871b1bSChris Mason 
375744871b1bSChris Mason 	if (!path->nodes[1])
375844871b1bSChris Mason 		return 1;
375944871b1bSChris Mason 
376044871b1bSChris Mason 	slot = path->slots[1];
376144871b1bSChris Mason 	upper = path->nodes[1];
376244871b1bSChris Mason 	if (slot >= btrfs_header_nritems(upper) - 1)
376344871b1bSChris Mason 		return 1;
376444871b1bSChris Mason 
376544871b1bSChris Mason 	btrfs_assert_tree_locked(path->nodes[1]);
376644871b1bSChris Mason 
37672ff7e61eSJeff Mahoney 	right = read_node_slot(fs_info, upper, slot + 1);
3768fb770ae4SLiu Bo 	/*
3769fb770ae4SLiu Bo 	 * slot + 1 is not valid or we fail to read the right node,
3770fb770ae4SLiu Bo 	 * no big deal, just return.
3771fb770ae4SLiu Bo 	 */
3772fb770ae4SLiu Bo 	if (IS_ERR(right))
377391ca338dSTsutomu Itoh 		return 1;
377491ca338dSTsutomu Itoh 
377544871b1bSChris Mason 	btrfs_tree_lock(right);
377644871b1bSChris Mason 	btrfs_set_lock_blocking(right);
377744871b1bSChris Mason 
37782ff7e61eSJeff Mahoney 	free_space = btrfs_leaf_free_space(fs_info, right);
377944871b1bSChris Mason 	if (free_space < data_size)
378044871b1bSChris Mason 		goto out_unlock;
378144871b1bSChris Mason 
378244871b1bSChris Mason 	/* cow and double check */
378344871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, right, upper,
378444871b1bSChris Mason 			      slot + 1, &right);
378544871b1bSChris Mason 	if (ret)
378644871b1bSChris Mason 		goto out_unlock;
378744871b1bSChris Mason 
37882ff7e61eSJeff Mahoney 	free_space = btrfs_leaf_free_space(fs_info, right);
378944871b1bSChris Mason 	if (free_space < data_size)
379044871b1bSChris Mason 		goto out_unlock;
379144871b1bSChris Mason 
379244871b1bSChris Mason 	left_nritems = btrfs_header_nritems(left);
379344871b1bSChris Mason 	if (left_nritems == 0)
379444871b1bSChris Mason 		goto out_unlock;
379544871b1bSChris Mason 
37962ef1fed2SFilipe David Borba Manana 	if (path->slots[0] == left_nritems && !empty) {
37972ef1fed2SFilipe David Borba Manana 		/* Key greater than all keys in the leaf, right neighbor has
37982ef1fed2SFilipe David Borba Manana 		 * enough room for it and we're not emptying our leaf to delete
37992ef1fed2SFilipe David Borba Manana 		 * it, therefore use right neighbor to insert the new item and
38002ef1fed2SFilipe David Borba Manana 		 * no need to touch/dirty our left leaft. */
38012ef1fed2SFilipe David Borba Manana 		btrfs_tree_unlock(left);
38022ef1fed2SFilipe David Borba Manana 		free_extent_buffer(left);
38032ef1fed2SFilipe David Borba Manana 		path->nodes[0] = right;
38042ef1fed2SFilipe David Borba Manana 		path->slots[0] = 0;
38052ef1fed2SFilipe David Borba Manana 		path->slots[1]++;
38062ef1fed2SFilipe David Borba Manana 		return 0;
38072ef1fed2SFilipe David Borba Manana 	}
38082ef1fed2SFilipe David Borba Manana 
38091e47eef2SDavid Sterba 	return __push_leaf_right(fs_info, path, min_data_size, empty,
381099d8f83cSChris Mason 				right, free_space, left_nritems, min_slot);
381144871b1bSChris Mason out_unlock:
381244871b1bSChris Mason 	btrfs_tree_unlock(right);
381344871b1bSChris Mason 	free_extent_buffer(right);
381444871b1bSChris Mason 	return 1;
381544871b1bSChris Mason }
381644871b1bSChris Mason 
381744871b1bSChris Mason /*
381844871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
381944871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
382099d8f83cSChris Mason  *
382199d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
382299d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us do all the
382399d8f83cSChris Mason  * items
382444871b1bSChris Mason  */
382566cb7ddbSDavid Sterba static noinline int __push_leaf_left(struct btrfs_fs_info *fs_info,
382644871b1bSChris Mason 				     struct btrfs_path *path, int data_size,
382744871b1bSChris Mason 				     int empty, struct extent_buffer *left,
382899d8f83cSChris Mason 				     int free_space, u32 right_nritems,
382999d8f83cSChris Mason 				     u32 max_slot)
383044871b1bSChris Mason {
38315f39d397SChris Mason 	struct btrfs_disk_key disk_key;
38325f39d397SChris Mason 	struct extent_buffer *right = path->nodes[0];
3833be0e5c09SChris Mason 	int i;
3834be0e5c09SChris Mason 	int push_space = 0;
3835be0e5c09SChris Mason 	int push_items = 0;
38360783fcfcSChris Mason 	struct btrfs_item *item;
38377518a238SChris Mason 	u32 old_left_nritems;
383834a38218SChris Mason 	u32 nr;
3839aa5d6bedSChris Mason 	int ret = 0;
3840db94535dSChris Mason 	u32 this_item_size;
3841db94535dSChris Mason 	u32 old_left_item_size;
3842cfed81a0SChris Mason 	struct btrfs_map_token token;
3843cfed81a0SChris Mason 
3844cfed81a0SChris Mason 	btrfs_init_map_token(&token);
3845be0e5c09SChris Mason 
384634a38218SChris Mason 	if (empty)
384799d8f83cSChris Mason 		nr = min(right_nritems, max_slot);
384834a38218SChris Mason 	else
384999d8f83cSChris Mason 		nr = min(right_nritems - 1, max_slot);
385034a38218SChris Mason 
385134a38218SChris Mason 	for (i = 0; i < nr; i++) {
3852dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
3853db94535dSChris Mason 
385431840ae1SZheng Yan 		if (!empty && push_items > 0) {
385531840ae1SZheng Yan 			if (path->slots[0] < i)
385631840ae1SZheng Yan 				break;
385731840ae1SZheng Yan 			if (path->slots[0] == i) {
38582ff7e61eSJeff Mahoney 				int space = btrfs_leaf_free_space(fs_info, right);
385931840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
386031840ae1SZheng Yan 					break;
386131840ae1SZheng Yan 			}
386231840ae1SZheng Yan 		}
386331840ae1SZheng Yan 
3864be0e5c09SChris Mason 		if (path->slots[0] == i)
386587b29b20SYan Zheng 			push_space += data_size;
3866db94535dSChris Mason 
3867db94535dSChris Mason 		this_item_size = btrfs_item_size(right, item);
3868db94535dSChris Mason 		if (this_item_size + sizeof(*item) + push_space > free_space)
3869be0e5c09SChris Mason 			break;
3870db94535dSChris Mason 
3871be0e5c09SChris Mason 		push_items++;
3872db94535dSChris Mason 		push_space += this_item_size + sizeof(*item);
3873be0e5c09SChris Mason 	}
3874db94535dSChris Mason 
3875be0e5c09SChris Mason 	if (push_items == 0) {
3876925baeddSChris Mason 		ret = 1;
3877925baeddSChris Mason 		goto out;
3878be0e5c09SChris Mason 	}
3879fae7f21cSDulshani Gunawardhana 	WARN_ON(!empty && push_items == btrfs_header_nritems(right));
38805f39d397SChris Mason 
3881be0e5c09SChris Mason 	/* push data from right to left */
38825f39d397SChris Mason 	copy_extent_buffer(left, right,
38835f39d397SChris Mason 			   btrfs_item_nr_offset(btrfs_header_nritems(left)),
38845f39d397SChris Mason 			   btrfs_item_nr_offset(0),
38855f39d397SChris Mason 			   push_items * sizeof(struct btrfs_item));
38865f39d397SChris Mason 
38870b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info) -
38885f39d397SChris Mason 		     btrfs_item_offset_nr(right, push_items - 1);
38895f39d397SChris Mason 
38903d9ec8c4SNikolay Borisov 	copy_extent_buffer(left, right, BTRFS_LEAF_DATA_OFFSET +
38912ff7e61eSJeff Mahoney 		     leaf_data_end(fs_info, left) - push_space,
38923d9ec8c4SNikolay Borisov 		     BTRFS_LEAF_DATA_OFFSET +
38935f39d397SChris Mason 		     btrfs_item_offset_nr(right, push_items - 1),
3894be0e5c09SChris Mason 		     push_space);
38955f39d397SChris Mason 	old_left_nritems = btrfs_header_nritems(left);
389687b29b20SYan Zheng 	BUG_ON(old_left_nritems <= 0);
3897eb60ceacSChris Mason 
3898db94535dSChris Mason 	old_left_item_size = btrfs_item_offset_nr(left, old_left_nritems - 1);
3899be0e5c09SChris Mason 	for (i = old_left_nritems; i < old_left_nritems + push_items; i++) {
39005f39d397SChris Mason 		u32 ioff;
3901db94535dSChris Mason 
3902dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
3903db94535dSChris Mason 
3904cfed81a0SChris Mason 		ioff = btrfs_token_item_offset(left, item, &token);
3905cfed81a0SChris Mason 		btrfs_set_token_item_offset(left, item,
39060b246afaSJeff Mahoney 		      ioff - (BTRFS_LEAF_DATA_SIZE(fs_info) - old_left_item_size),
3907cfed81a0SChris Mason 		      &token);
3908be0e5c09SChris Mason 	}
39095f39d397SChris Mason 	btrfs_set_header_nritems(left, old_left_nritems + push_items);
3910be0e5c09SChris Mason 
3911be0e5c09SChris Mason 	/* fixup right node */
391231b1a2bdSJulia Lawall 	if (push_items > right_nritems)
391331b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "push items %d nr %u\n", push_items,
3914d397712bSChris Mason 		       right_nritems);
391534a38218SChris Mason 
391634a38218SChris Mason 	if (push_items < right_nritems) {
39175f39d397SChris Mason 		push_space = btrfs_item_offset_nr(right, push_items - 1) -
39182ff7e61eSJeff Mahoney 						  leaf_data_end(fs_info, right);
39193d9ec8c4SNikolay Borisov 		memmove_extent_buffer(right, BTRFS_LEAF_DATA_OFFSET +
39200b246afaSJeff Mahoney 				      BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
39213d9ec8c4SNikolay Borisov 				      BTRFS_LEAF_DATA_OFFSET +
39222ff7e61eSJeff Mahoney 				      leaf_data_end(fs_info, right), push_space);
39235f39d397SChris Mason 
39245f39d397SChris Mason 		memmove_extent_buffer(right, btrfs_item_nr_offset(0),
39255f39d397SChris Mason 			      btrfs_item_nr_offset(push_items),
39265f39d397SChris Mason 			     (btrfs_header_nritems(right) - push_items) *
39270783fcfcSChris Mason 			     sizeof(struct btrfs_item));
392834a38218SChris Mason 	}
3929eef1c494SYan 	right_nritems -= push_items;
3930eef1c494SYan 	btrfs_set_header_nritems(right, right_nritems);
39310b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
39325f39d397SChris Mason 	for (i = 0; i < right_nritems; i++) {
3933dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
3934db94535dSChris Mason 
3935cfed81a0SChris Mason 		push_space = push_space - btrfs_token_item_size(right,
3936cfed81a0SChris Mason 								item, &token);
3937cfed81a0SChris Mason 		btrfs_set_token_item_offset(right, item, push_space, &token);
3938db94535dSChris Mason 	}
3939eb60ceacSChris Mason 
39405f39d397SChris Mason 	btrfs_mark_buffer_dirty(left);
394134a38218SChris Mason 	if (right_nritems)
39425f39d397SChris Mason 		btrfs_mark_buffer_dirty(right);
3943f0486c68SYan, Zheng 	else
39447c302b49SDavid Sterba 		clean_tree_block(fs_info, right);
3945098f59c2SChris Mason 
39465f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
39470b246afaSJeff Mahoney 	fixup_low_keys(fs_info, path, &disk_key, 1);
3948be0e5c09SChris Mason 
3949be0e5c09SChris Mason 	/* then fixup the leaf pointer in the path */
3950be0e5c09SChris Mason 	if (path->slots[0] < push_items) {
3951be0e5c09SChris Mason 		path->slots[0] += old_left_nritems;
3952925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
39535f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
39545f39d397SChris Mason 		path->nodes[0] = left;
3955be0e5c09SChris Mason 		path->slots[1] -= 1;
3956be0e5c09SChris Mason 	} else {
3957925baeddSChris Mason 		btrfs_tree_unlock(left);
39585f39d397SChris Mason 		free_extent_buffer(left);
3959be0e5c09SChris Mason 		path->slots[0] -= push_items;
3960be0e5c09SChris Mason 	}
3961eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
3962aa5d6bedSChris Mason 	return ret;
3963925baeddSChris Mason out:
3964925baeddSChris Mason 	btrfs_tree_unlock(left);
3965925baeddSChris Mason 	free_extent_buffer(left);
3966925baeddSChris Mason 	return ret;
3967be0e5c09SChris Mason }
3968be0e5c09SChris Mason 
396974123bd7SChris Mason /*
397044871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
397144871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
397299d8f83cSChris Mason  *
397399d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
397499d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us push all the
397599d8f83cSChris Mason  * items
397644871b1bSChris Mason  */
397744871b1bSChris Mason static int push_leaf_left(struct btrfs_trans_handle *trans, struct btrfs_root
397899d8f83cSChris Mason 			  *root, struct btrfs_path *path, int min_data_size,
397999d8f83cSChris Mason 			  int data_size, int empty, u32 max_slot)
398044871b1bSChris Mason {
39812ff7e61eSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
398244871b1bSChris Mason 	struct extent_buffer *right = path->nodes[0];
398344871b1bSChris Mason 	struct extent_buffer *left;
398444871b1bSChris Mason 	int slot;
398544871b1bSChris Mason 	int free_space;
398644871b1bSChris Mason 	u32 right_nritems;
398744871b1bSChris Mason 	int ret = 0;
398844871b1bSChris Mason 
398944871b1bSChris Mason 	slot = path->slots[1];
399044871b1bSChris Mason 	if (slot == 0)
399144871b1bSChris Mason 		return 1;
399244871b1bSChris Mason 	if (!path->nodes[1])
399344871b1bSChris Mason 		return 1;
399444871b1bSChris Mason 
399544871b1bSChris Mason 	right_nritems = btrfs_header_nritems(right);
399644871b1bSChris Mason 	if (right_nritems == 0)
399744871b1bSChris Mason 		return 1;
399844871b1bSChris Mason 
399944871b1bSChris Mason 	btrfs_assert_tree_locked(path->nodes[1]);
400044871b1bSChris Mason 
40012ff7e61eSJeff Mahoney 	left = read_node_slot(fs_info, path->nodes[1], slot - 1);
4002fb770ae4SLiu Bo 	/*
4003fb770ae4SLiu Bo 	 * slot - 1 is not valid or we fail to read the left node,
4004fb770ae4SLiu Bo 	 * no big deal, just return.
4005fb770ae4SLiu Bo 	 */
4006fb770ae4SLiu Bo 	if (IS_ERR(left))
400791ca338dSTsutomu Itoh 		return 1;
400891ca338dSTsutomu Itoh 
400944871b1bSChris Mason 	btrfs_tree_lock(left);
401044871b1bSChris Mason 	btrfs_set_lock_blocking(left);
401144871b1bSChris Mason 
40122ff7e61eSJeff Mahoney 	free_space = btrfs_leaf_free_space(fs_info, left);
401344871b1bSChris Mason 	if (free_space < data_size) {
401444871b1bSChris Mason 		ret = 1;
401544871b1bSChris Mason 		goto out;
401644871b1bSChris Mason 	}
401744871b1bSChris Mason 
401844871b1bSChris Mason 	/* cow and double check */
401944871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, left,
402044871b1bSChris Mason 			      path->nodes[1], slot - 1, &left);
402144871b1bSChris Mason 	if (ret) {
402244871b1bSChris Mason 		/* we hit -ENOSPC, but it isn't fatal here */
402379787eaaSJeff Mahoney 		if (ret == -ENOSPC)
402444871b1bSChris Mason 			ret = 1;
402544871b1bSChris Mason 		goto out;
402644871b1bSChris Mason 	}
402744871b1bSChris Mason 
40282ff7e61eSJeff Mahoney 	free_space = btrfs_leaf_free_space(fs_info, left);
402944871b1bSChris Mason 	if (free_space < data_size) {
403044871b1bSChris Mason 		ret = 1;
403144871b1bSChris Mason 		goto out;
403244871b1bSChris Mason 	}
403344871b1bSChris Mason 
403466cb7ddbSDavid Sterba 	return __push_leaf_left(fs_info, path, min_data_size,
403599d8f83cSChris Mason 			       empty, left, free_space, right_nritems,
403699d8f83cSChris Mason 			       max_slot);
403744871b1bSChris Mason out:
403844871b1bSChris Mason 	btrfs_tree_unlock(left);
403944871b1bSChris Mason 	free_extent_buffer(left);
404044871b1bSChris Mason 	return ret;
404144871b1bSChris Mason }
404244871b1bSChris Mason 
404344871b1bSChris Mason /*
404474123bd7SChris Mason  * split the path's leaf in two, making sure there is at least data_size
404574123bd7SChris Mason  * available for the resulting leaf level of the path.
404674123bd7SChris Mason  */
4047143bede5SJeff Mahoney static noinline void copy_for_split(struct btrfs_trans_handle *trans,
40482ff7e61eSJeff Mahoney 				    struct btrfs_fs_info *fs_info,
404944871b1bSChris Mason 				    struct btrfs_path *path,
405044871b1bSChris Mason 				    struct extent_buffer *l,
405144871b1bSChris Mason 				    struct extent_buffer *right,
405244871b1bSChris Mason 				    int slot, int mid, int nritems)
4053be0e5c09SChris Mason {
4054be0e5c09SChris Mason 	int data_copy_size;
4055be0e5c09SChris Mason 	int rt_data_off;
4056be0e5c09SChris Mason 	int i;
4057d4dbff95SChris Mason 	struct btrfs_disk_key disk_key;
4058cfed81a0SChris Mason 	struct btrfs_map_token token;
4059cfed81a0SChris Mason 
4060cfed81a0SChris Mason 	btrfs_init_map_token(&token);
4061be0e5c09SChris Mason 
40625f39d397SChris Mason 	nritems = nritems - mid;
40635f39d397SChris Mason 	btrfs_set_header_nritems(right, nritems);
40642ff7e61eSJeff Mahoney 	data_copy_size = btrfs_item_end_nr(l, mid) - leaf_data_end(fs_info, l);
40655f39d397SChris Mason 
40665f39d397SChris Mason 	copy_extent_buffer(right, l, btrfs_item_nr_offset(0),
40675f39d397SChris Mason 			   btrfs_item_nr_offset(mid),
40685f39d397SChris Mason 			   nritems * sizeof(struct btrfs_item));
40695f39d397SChris Mason 
40705f39d397SChris Mason 	copy_extent_buffer(right, l,
40713d9ec8c4SNikolay Borisov 		     BTRFS_LEAF_DATA_OFFSET + BTRFS_LEAF_DATA_SIZE(fs_info) -
40723d9ec8c4SNikolay Borisov 		     data_copy_size, BTRFS_LEAF_DATA_OFFSET +
40732ff7e61eSJeff Mahoney 		     leaf_data_end(fs_info, l), data_copy_size);
407474123bd7SChris Mason 
40750b246afaSJeff Mahoney 	rt_data_off = BTRFS_LEAF_DATA_SIZE(fs_info) - btrfs_item_end_nr(l, mid);
40765f39d397SChris Mason 
40775f39d397SChris Mason 	for (i = 0; i < nritems; i++) {
4078dd3cc16bSRoss Kirk 		struct btrfs_item *item = btrfs_item_nr(i);
4079db94535dSChris Mason 		u32 ioff;
4080db94535dSChris Mason 
4081cfed81a0SChris Mason 		ioff = btrfs_token_item_offset(right, item, &token);
4082cfed81a0SChris Mason 		btrfs_set_token_item_offset(right, item,
4083cfed81a0SChris Mason 					    ioff + rt_data_off, &token);
40840783fcfcSChris Mason 	}
408574123bd7SChris Mason 
40865f39d397SChris Mason 	btrfs_set_header_nritems(l, mid);
40875f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
40882ff7e61eSJeff Mahoney 	insert_ptr(trans, fs_info, path, &disk_key, right->start,
4089c3e06965SJan Schmidt 		   path->slots[1] + 1, 1);
40905f39d397SChris Mason 
40915f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
40925f39d397SChris Mason 	btrfs_mark_buffer_dirty(l);
4093eb60ceacSChris Mason 	BUG_ON(path->slots[0] != slot);
40945f39d397SChris Mason 
4095be0e5c09SChris Mason 	if (mid <= slot) {
4096925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
40975f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
40985f39d397SChris Mason 		path->nodes[0] = right;
4099be0e5c09SChris Mason 		path->slots[0] -= mid;
4100be0e5c09SChris Mason 		path->slots[1] += 1;
4101925baeddSChris Mason 	} else {
4102925baeddSChris Mason 		btrfs_tree_unlock(right);
41035f39d397SChris Mason 		free_extent_buffer(right);
4104925baeddSChris Mason 	}
41055f39d397SChris Mason 
4106eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
410744871b1bSChris Mason }
410844871b1bSChris Mason 
410944871b1bSChris Mason /*
411099d8f83cSChris Mason  * double splits happen when we need to insert a big item in the middle
411199d8f83cSChris Mason  * of a leaf.  A double split can leave us with 3 mostly empty leaves:
411299d8f83cSChris Mason  * leaf: [ slots 0 - N] [ our target ] [ N + 1 - total in leaf ]
411399d8f83cSChris Mason  *          A                 B                 C
411499d8f83cSChris Mason  *
411599d8f83cSChris Mason  * We avoid this by trying to push the items on either side of our target
411699d8f83cSChris Mason  * into the adjacent leaves.  If all goes well we can avoid the double split
411799d8f83cSChris Mason  * completely.
411899d8f83cSChris Mason  */
411999d8f83cSChris Mason static noinline int push_for_double_split(struct btrfs_trans_handle *trans,
412099d8f83cSChris Mason 					  struct btrfs_root *root,
412199d8f83cSChris Mason 					  struct btrfs_path *path,
412299d8f83cSChris Mason 					  int data_size)
412399d8f83cSChris Mason {
41242ff7e61eSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
412599d8f83cSChris Mason 	int ret;
412699d8f83cSChris Mason 	int progress = 0;
412799d8f83cSChris Mason 	int slot;
412899d8f83cSChris Mason 	u32 nritems;
41295a4267caSFilipe David Borba Manana 	int space_needed = data_size;
413099d8f83cSChris Mason 
413199d8f83cSChris Mason 	slot = path->slots[0];
41325a4267caSFilipe David Borba Manana 	if (slot < btrfs_header_nritems(path->nodes[0]))
41332ff7e61eSJeff Mahoney 		space_needed -= btrfs_leaf_free_space(fs_info, path->nodes[0]);
413499d8f83cSChris Mason 
413599d8f83cSChris Mason 	/*
413699d8f83cSChris Mason 	 * try to push all the items after our slot into the
413799d8f83cSChris Mason 	 * right leaf
413899d8f83cSChris Mason 	 */
41395a4267caSFilipe David Borba Manana 	ret = push_leaf_right(trans, root, path, 1, space_needed, 0, slot);
414099d8f83cSChris Mason 	if (ret < 0)
414199d8f83cSChris Mason 		return ret;
414299d8f83cSChris Mason 
414399d8f83cSChris Mason 	if (ret == 0)
414499d8f83cSChris Mason 		progress++;
414599d8f83cSChris Mason 
414699d8f83cSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
414799d8f83cSChris Mason 	/*
414899d8f83cSChris Mason 	 * our goal is to get our slot at the start or end of a leaf.  If
414999d8f83cSChris Mason 	 * we've done so we're done
415099d8f83cSChris Mason 	 */
415199d8f83cSChris Mason 	if (path->slots[0] == 0 || path->slots[0] == nritems)
415299d8f83cSChris Mason 		return 0;
415399d8f83cSChris Mason 
41542ff7e61eSJeff Mahoney 	if (btrfs_leaf_free_space(fs_info, path->nodes[0]) >= data_size)
415599d8f83cSChris Mason 		return 0;
415699d8f83cSChris Mason 
415799d8f83cSChris Mason 	/* try to push all the items before our slot into the next leaf */
415899d8f83cSChris Mason 	slot = path->slots[0];
4159263d3995SFilipe Manana 	space_needed = data_size;
4160263d3995SFilipe Manana 	if (slot > 0)
4161263d3995SFilipe Manana 		space_needed -= btrfs_leaf_free_space(fs_info, path->nodes[0]);
41625a4267caSFilipe David Borba Manana 	ret = push_leaf_left(trans, root, path, 1, space_needed, 0, slot);
416399d8f83cSChris Mason 	if (ret < 0)
416499d8f83cSChris Mason 		return ret;
416599d8f83cSChris Mason 
416699d8f83cSChris Mason 	if (ret == 0)
416799d8f83cSChris Mason 		progress++;
416899d8f83cSChris Mason 
416999d8f83cSChris Mason 	if (progress)
417099d8f83cSChris Mason 		return 0;
417199d8f83cSChris Mason 	return 1;
417299d8f83cSChris Mason }
417399d8f83cSChris Mason 
417499d8f83cSChris Mason /*
417544871b1bSChris Mason  * split the path's leaf in two, making sure there is at least data_size
417644871b1bSChris Mason  * available for the resulting leaf level of the path.
417744871b1bSChris Mason  *
417844871b1bSChris Mason  * returns 0 if all went well and < 0 on failure.
417944871b1bSChris Mason  */
418044871b1bSChris Mason static noinline int split_leaf(struct btrfs_trans_handle *trans,
418144871b1bSChris Mason 			       struct btrfs_root *root,
4182310712b2SOmar Sandoval 			       const struct btrfs_key *ins_key,
418344871b1bSChris Mason 			       struct btrfs_path *path, int data_size,
418444871b1bSChris Mason 			       int extend)
418544871b1bSChris Mason {
41865d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
418744871b1bSChris Mason 	struct extent_buffer *l;
418844871b1bSChris Mason 	u32 nritems;
418944871b1bSChris Mason 	int mid;
419044871b1bSChris Mason 	int slot;
419144871b1bSChris Mason 	struct extent_buffer *right;
4192b7a0365eSDaniel Dressler 	struct btrfs_fs_info *fs_info = root->fs_info;
419344871b1bSChris Mason 	int ret = 0;
419444871b1bSChris Mason 	int wret;
41955d4f98a2SYan Zheng 	int split;
419644871b1bSChris Mason 	int num_doubles = 0;
419799d8f83cSChris Mason 	int tried_avoid_double = 0;
419844871b1bSChris Mason 
4199a5719521SYan, Zheng 	l = path->nodes[0];
4200a5719521SYan, Zheng 	slot = path->slots[0];
4201a5719521SYan, Zheng 	if (extend && data_size + btrfs_item_size_nr(l, slot) +
42020b246afaSJeff Mahoney 	    sizeof(struct btrfs_item) > BTRFS_LEAF_DATA_SIZE(fs_info))
4203a5719521SYan, Zheng 		return -EOVERFLOW;
4204a5719521SYan, Zheng 
420544871b1bSChris Mason 	/* first try to make some room by pushing left and right */
420633157e05SLiu Bo 	if (data_size && path->nodes[1]) {
42075a4267caSFilipe David Borba Manana 		int space_needed = data_size;
42085a4267caSFilipe David Borba Manana 
42095a4267caSFilipe David Borba Manana 		if (slot < btrfs_header_nritems(l))
42102ff7e61eSJeff Mahoney 			space_needed -= btrfs_leaf_free_space(fs_info, l);
42115a4267caSFilipe David Borba Manana 
42125a4267caSFilipe David Borba Manana 		wret = push_leaf_right(trans, root, path, space_needed,
42135a4267caSFilipe David Borba Manana 				       space_needed, 0, 0);
421444871b1bSChris Mason 		if (wret < 0)
421544871b1bSChris Mason 			return wret;
421644871b1bSChris Mason 		if (wret) {
4217263d3995SFilipe Manana 			space_needed = data_size;
4218263d3995SFilipe Manana 			if (slot > 0)
4219263d3995SFilipe Manana 				space_needed -= btrfs_leaf_free_space(fs_info,
4220263d3995SFilipe Manana 								      l);
42215a4267caSFilipe David Borba Manana 			wret = push_leaf_left(trans, root, path, space_needed,
42225a4267caSFilipe David Borba Manana 					      space_needed, 0, (u32)-1);
422344871b1bSChris Mason 			if (wret < 0)
422444871b1bSChris Mason 				return wret;
422544871b1bSChris Mason 		}
422644871b1bSChris Mason 		l = path->nodes[0];
422744871b1bSChris Mason 
422844871b1bSChris Mason 		/* did the pushes work? */
42292ff7e61eSJeff Mahoney 		if (btrfs_leaf_free_space(fs_info, l) >= data_size)
423044871b1bSChris Mason 			return 0;
423144871b1bSChris Mason 	}
423244871b1bSChris Mason 
423344871b1bSChris Mason 	if (!path->nodes[1]) {
4234fdd99c72SLiu Bo 		ret = insert_new_root(trans, root, path, 1);
423544871b1bSChris Mason 		if (ret)
423644871b1bSChris Mason 			return ret;
423744871b1bSChris Mason 	}
423844871b1bSChris Mason again:
42395d4f98a2SYan Zheng 	split = 1;
424044871b1bSChris Mason 	l = path->nodes[0];
424144871b1bSChris Mason 	slot = path->slots[0];
424244871b1bSChris Mason 	nritems = btrfs_header_nritems(l);
424344871b1bSChris Mason 	mid = (nritems + 1) / 2;
424444871b1bSChris Mason 
42455d4f98a2SYan Zheng 	if (mid <= slot) {
42465d4f98a2SYan Zheng 		if (nritems == 1 ||
42475d4f98a2SYan Zheng 		    leaf_space_used(l, mid, nritems - mid) + data_size >
42480b246afaSJeff Mahoney 			BTRFS_LEAF_DATA_SIZE(fs_info)) {
42495d4f98a2SYan Zheng 			if (slot >= nritems) {
42505d4f98a2SYan Zheng 				split = 0;
42515d4f98a2SYan Zheng 			} else {
42525d4f98a2SYan Zheng 				mid = slot;
42535d4f98a2SYan Zheng 				if (mid != nritems &&
42545d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
42550b246afaSJeff Mahoney 				    data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
425699d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
425799d8f83cSChris Mason 						goto push_for_double;
42585d4f98a2SYan Zheng 					split = 2;
42595d4f98a2SYan Zheng 				}
42605d4f98a2SYan Zheng 			}
42615d4f98a2SYan Zheng 		}
42625d4f98a2SYan Zheng 	} else {
42635d4f98a2SYan Zheng 		if (leaf_space_used(l, 0, mid) + data_size >
42640b246afaSJeff Mahoney 			BTRFS_LEAF_DATA_SIZE(fs_info)) {
42655d4f98a2SYan Zheng 			if (!extend && data_size && slot == 0) {
42665d4f98a2SYan Zheng 				split = 0;
42675d4f98a2SYan Zheng 			} else if ((extend || !data_size) && slot == 0) {
42685d4f98a2SYan Zheng 				mid = 1;
42695d4f98a2SYan Zheng 			} else {
42705d4f98a2SYan Zheng 				mid = slot;
42715d4f98a2SYan Zheng 				if (mid != nritems &&
42725d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
42730b246afaSJeff Mahoney 				    data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
427499d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
427599d8f83cSChris Mason 						goto push_for_double;
42765d4f98a2SYan Zheng 					split = 2;
42775d4f98a2SYan Zheng 				}
42785d4f98a2SYan Zheng 			}
42795d4f98a2SYan Zheng 		}
42805d4f98a2SYan Zheng 	}
42815d4f98a2SYan Zheng 
42825d4f98a2SYan Zheng 	if (split == 0)
42835d4f98a2SYan Zheng 		btrfs_cpu_key_to_disk(&disk_key, ins_key);
42845d4f98a2SYan Zheng 	else
42855d4f98a2SYan Zheng 		btrfs_item_key(l, &disk_key, mid);
42865d4f98a2SYan Zheng 
42874d75f8a9SDavid Sterba 	right = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
42885581a51aSJan Schmidt 			&disk_key, 0, l->start, 0);
4289f0486c68SYan, Zheng 	if (IS_ERR(right))
429044871b1bSChris Mason 		return PTR_ERR(right);
4291f0486c68SYan, Zheng 
42920b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
429344871b1bSChris Mason 
4294b159fa28SDavid Sterba 	memzero_extent_buffer(right, 0, sizeof(struct btrfs_header));
429544871b1bSChris Mason 	btrfs_set_header_bytenr(right, right->start);
429644871b1bSChris Mason 	btrfs_set_header_generation(right, trans->transid);
42975d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(right, BTRFS_MIXED_BACKREF_REV);
429844871b1bSChris Mason 	btrfs_set_header_owner(right, root->root_key.objectid);
429944871b1bSChris Mason 	btrfs_set_header_level(right, 0);
4300d24ee97bSDavid Sterba 	write_extent_buffer_fsid(right, fs_info->fsid);
4301d24ee97bSDavid Sterba 	write_extent_buffer_chunk_tree_uuid(right, fs_info->chunk_tree_uuid);
430244871b1bSChris Mason 
43035d4f98a2SYan Zheng 	if (split == 0) {
430444871b1bSChris Mason 		if (mid <= slot) {
430544871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
43062ff7e61eSJeff Mahoney 			insert_ptr(trans, fs_info, path, &disk_key,
43072ff7e61eSJeff Mahoney 				   right->start, path->slots[1] + 1, 1);
430844871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
430944871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
431044871b1bSChris Mason 			path->nodes[0] = right;
431144871b1bSChris Mason 			path->slots[0] = 0;
431244871b1bSChris Mason 			path->slots[1] += 1;
431344871b1bSChris Mason 		} else {
431444871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
43152ff7e61eSJeff Mahoney 			insert_ptr(trans, fs_info, path, &disk_key,
43162ff7e61eSJeff Mahoney 				   right->start, path->slots[1], 1);
431744871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
431844871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
431944871b1bSChris Mason 			path->nodes[0] = right;
432044871b1bSChris Mason 			path->slots[0] = 0;
4321143bede5SJeff Mahoney 			if (path->slots[1] == 0)
4322b7a0365eSDaniel Dressler 				fixup_low_keys(fs_info, path, &disk_key, 1);
43235d4f98a2SYan Zheng 		}
4324196e0249SLiu Bo 		/*
4325196e0249SLiu Bo 		 * We create a new leaf 'right' for the required ins_len and
4326196e0249SLiu Bo 		 * we'll do btrfs_mark_buffer_dirty() on this leaf after copying
4327196e0249SLiu Bo 		 * the content of ins_len to 'right'.
4328196e0249SLiu Bo 		 */
432944871b1bSChris Mason 		return ret;
433044871b1bSChris Mason 	}
433144871b1bSChris Mason 
43322ff7e61eSJeff Mahoney 	copy_for_split(trans, fs_info, path, l, right, slot, mid, nritems);
433344871b1bSChris Mason 
43345d4f98a2SYan Zheng 	if (split == 2) {
4335cc0c5538SChris Mason 		BUG_ON(num_doubles != 0);
4336cc0c5538SChris Mason 		num_doubles++;
4337cc0c5538SChris Mason 		goto again;
43383326d1b0SChris Mason 	}
433944871b1bSChris Mason 
4340143bede5SJeff Mahoney 	return 0;
434199d8f83cSChris Mason 
434299d8f83cSChris Mason push_for_double:
434399d8f83cSChris Mason 	push_for_double_split(trans, root, path, data_size);
434499d8f83cSChris Mason 	tried_avoid_double = 1;
43452ff7e61eSJeff Mahoney 	if (btrfs_leaf_free_space(fs_info, path->nodes[0]) >= data_size)
434699d8f83cSChris Mason 		return 0;
434799d8f83cSChris Mason 	goto again;
4348be0e5c09SChris Mason }
4349be0e5c09SChris Mason 
4350ad48fd75SYan, Zheng static noinline int setup_leaf_for_split(struct btrfs_trans_handle *trans,
4351ad48fd75SYan, Zheng 					 struct btrfs_root *root,
4352ad48fd75SYan, Zheng 					 struct btrfs_path *path, int ins_len)
4353ad48fd75SYan, Zheng {
43542ff7e61eSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
4355ad48fd75SYan, Zheng 	struct btrfs_key key;
4356ad48fd75SYan, Zheng 	struct extent_buffer *leaf;
4357ad48fd75SYan, Zheng 	struct btrfs_file_extent_item *fi;
4358ad48fd75SYan, Zheng 	u64 extent_len = 0;
4359ad48fd75SYan, Zheng 	u32 item_size;
4360ad48fd75SYan, Zheng 	int ret;
4361ad48fd75SYan, Zheng 
4362ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4363ad48fd75SYan, Zheng 	btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4364ad48fd75SYan, Zheng 
4365ad48fd75SYan, Zheng 	BUG_ON(key.type != BTRFS_EXTENT_DATA_KEY &&
4366ad48fd75SYan, Zheng 	       key.type != BTRFS_EXTENT_CSUM_KEY);
4367ad48fd75SYan, Zheng 
43682ff7e61eSJeff Mahoney 	if (btrfs_leaf_free_space(fs_info, leaf) >= ins_len)
4369ad48fd75SYan, Zheng 		return 0;
4370ad48fd75SYan, Zheng 
4371ad48fd75SYan, Zheng 	item_size = btrfs_item_size_nr(leaf, path->slots[0]);
4372ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
4373ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
4374ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
4375ad48fd75SYan, Zheng 		extent_len = btrfs_file_extent_num_bytes(leaf, fi);
4376ad48fd75SYan, Zheng 	}
4377b3b4aa74SDavid Sterba 	btrfs_release_path(path);
4378ad48fd75SYan, Zheng 
4379ad48fd75SYan, Zheng 	path->keep_locks = 1;
4380ad48fd75SYan, Zheng 	path->search_for_split = 1;
4381ad48fd75SYan, Zheng 	ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
4382ad48fd75SYan, Zheng 	path->search_for_split = 0;
4383a8df6fe6SFilipe Manana 	if (ret > 0)
4384a8df6fe6SFilipe Manana 		ret = -EAGAIN;
4385ad48fd75SYan, Zheng 	if (ret < 0)
4386ad48fd75SYan, Zheng 		goto err;
4387ad48fd75SYan, Zheng 
4388ad48fd75SYan, Zheng 	ret = -EAGAIN;
4389ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4390a8df6fe6SFilipe Manana 	/* if our item isn't there, return now */
4391a8df6fe6SFilipe Manana 	if (item_size != btrfs_item_size_nr(leaf, path->slots[0]))
4392ad48fd75SYan, Zheng 		goto err;
4393ad48fd75SYan, Zheng 
4394109f6aefSChris Mason 	/* the leaf has  changed, it now has room.  return now */
43952ff7e61eSJeff Mahoney 	if (btrfs_leaf_free_space(fs_info, path->nodes[0]) >= ins_len)
4396109f6aefSChris Mason 		goto err;
4397109f6aefSChris Mason 
4398ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
4399ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
4400ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
4401ad48fd75SYan, Zheng 		if (extent_len != btrfs_file_extent_num_bytes(leaf, fi))
4402ad48fd75SYan, Zheng 			goto err;
4403ad48fd75SYan, Zheng 	}
4404ad48fd75SYan, Zheng 
4405ad48fd75SYan, Zheng 	btrfs_set_path_blocking(path);
4406ad48fd75SYan, Zheng 	ret = split_leaf(trans, root, &key, path, ins_len, 1);
4407f0486c68SYan, Zheng 	if (ret)
4408f0486c68SYan, Zheng 		goto err;
4409ad48fd75SYan, Zheng 
4410ad48fd75SYan, Zheng 	path->keep_locks = 0;
4411ad48fd75SYan, Zheng 	btrfs_unlock_up_safe(path, 1);
4412ad48fd75SYan, Zheng 	return 0;
4413ad48fd75SYan, Zheng err:
4414ad48fd75SYan, Zheng 	path->keep_locks = 0;
4415ad48fd75SYan, Zheng 	return ret;
4416ad48fd75SYan, Zheng }
4417ad48fd75SYan, Zheng 
44184961e293SDavid Sterba static noinline int split_item(struct btrfs_fs_info *fs_info,
4419459931ecSChris Mason 			       struct btrfs_path *path,
4420310712b2SOmar Sandoval 			       const struct btrfs_key *new_key,
4421459931ecSChris Mason 			       unsigned long split_offset)
4422459931ecSChris Mason {
4423459931ecSChris Mason 	struct extent_buffer *leaf;
4424459931ecSChris Mason 	struct btrfs_item *item;
4425459931ecSChris Mason 	struct btrfs_item *new_item;
4426459931ecSChris Mason 	int slot;
4427ad48fd75SYan, Zheng 	char *buf;
4428459931ecSChris Mason 	u32 nritems;
4429ad48fd75SYan, Zheng 	u32 item_size;
4430459931ecSChris Mason 	u32 orig_offset;
4431459931ecSChris Mason 	struct btrfs_disk_key disk_key;
4432459931ecSChris Mason 
4433459931ecSChris Mason 	leaf = path->nodes[0];
44342ff7e61eSJeff Mahoney 	BUG_ON(btrfs_leaf_free_space(fs_info, leaf) < sizeof(struct btrfs_item));
4435b9473439SChris Mason 
4436b4ce94deSChris Mason 	btrfs_set_path_blocking(path);
4437b4ce94deSChris Mason 
4438dd3cc16bSRoss Kirk 	item = btrfs_item_nr(path->slots[0]);
4439459931ecSChris Mason 	orig_offset = btrfs_item_offset(leaf, item);
4440459931ecSChris Mason 	item_size = btrfs_item_size(leaf, item);
4441459931ecSChris Mason 
4442459931ecSChris Mason 	buf = kmalloc(item_size, GFP_NOFS);
4443ad48fd75SYan, Zheng 	if (!buf)
4444ad48fd75SYan, Zheng 		return -ENOMEM;
4445ad48fd75SYan, Zheng 
4446459931ecSChris Mason 	read_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf,
4447459931ecSChris Mason 			    path->slots[0]), item_size);
4448ad48fd75SYan, Zheng 
4449459931ecSChris Mason 	slot = path->slots[0] + 1;
4450459931ecSChris Mason 	nritems = btrfs_header_nritems(leaf);
4451459931ecSChris Mason 	if (slot != nritems) {
4452459931ecSChris Mason 		/* shift the items */
4453459931ecSChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + 1),
4454459931ecSChris Mason 				btrfs_item_nr_offset(slot),
4455459931ecSChris Mason 				(nritems - slot) * sizeof(struct btrfs_item));
4456459931ecSChris Mason 	}
4457459931ecSChris Mason 
4458459931ecSChris Mason 	btrfs_cpu_key_to_disk(&disk_key, new_key);
4459459931ecSChris Mason 	btrfs_set_item_key(leaf, &disk_key, slot);
4460459931ecSChris Mason 
4461dd3cc16bSRoss Kirk 	new_item = btrfs_item_nr(slot);
4462459931ecSChris Mason 
4463459931ecSChris Mason 	btrfs_set_item_offset(leaf, new_item, orig_offset);
4464459931ecSChris Mason 	btrfs_set_item_size(leaf, new_item, item_size - split_offset);
4465459931ecSChris Mason 
4466459931ecSChris Mason 	btrfs_set_item_offset(leaf, item,
4467459931ecSChris Mason 			      orig_offset + item_size - split_offset);
4468459931ecSChris Mason 	btrfs_set_item_size(leaf, item, split_offset);
4469459931ecSChris Mason 
4470459931ecSChris Mason 	btrfs_set_header_nritems(leaf, nritems + 1);
4471459931ecSChris Mason 
4472459931ecSChris Mason 	/* write the data for the start of the original item */
4473459931ecSChris Mason 	write_extent_buffer(leaf, buf,
4474459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, path->slots[0]),
4475459931ecSChris Mason 			    split_offset);
4476459931ecSChris Mason 
4477459931ecSChris Mason 	/* write the data for the new item */
4478459931ecSChris Mason 	write_extent_buffer(leaf, buf + split_offset,
4479459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, slot),
4480459931ecSChris Mason 			    item_size - split_offset);
4481459931ecSChris Mason 	btrfs_mark_buffer_dirty(leaf);
4482459931ecSChris Mason 
44832ff7e61eSJeff Mahoney 	BUG_ON(btrfs_leaf_free_space(fs_info, leaf) < 0);
4484459931ecSChris Mason 	kfree(buf);
4485ad48fd75SYan, Zheng 	return 0;
4486ad48fd75SYan, Zheng }
4487ad48fd75SYan, Zheng 
4488ad48fd75SYan, Zheng /*
4489ad48fd75SYan, Zheng  * This function splits a single item into two items,
4490ad48fd75SYan, Zheng  * giving 'new_key' to the new item and splitting the
4491ad48fd75SYan, Zheng  * old one at split_offset (from the start of the item).
4492ad48fd75SYan, Zheng  *
4493ad48fd75SYan, Zheng  * The path may be released by this operation.  After
4494ad48fd75SYan, Zheng  * the split, the path is pointing to the old item.  The
4495ad48fd75SYan, Zheng  * new item is going to be in the same node as the old one.
4496ad48fd75SYan, Zheng  *
4497ad48fd75SYan, Zheng  * Note, the item being split must be smaller enough to live alone on
4498ad48fd75SYan, Zheng  * a tree block with room for one extra struct btrfs_item
4499ad48fd75SYan, Zheng  *
4500ad48fd75SYan, Zheng  * This allows us to split the item in place, keeping a lock on the
4501ad48fd75SYan, Zheng  * leaf the entire time.
4502ad48fd75SYan, Zheng  */
4503ad48fd75SYan, Zheng int btrfs_split_item(struct btrfs_trans_handle *trans,
4504ad48fd75SYan, Zheng 		     struct btrfs_root *root,
4505ad48fd75SYan, Zheng 		     struct btrfs_path *path,
4506310712b2SOmar Sandoval 		     const struct btrfs_key *new_key,
4507ad48fd75SYan, Zheng 		     unsigned long split_offset)
4508ad48fd75SYan, Zheng {
4509ad48fd75SYan, Zheng 	int ret;
4510ad48fd75SYan, Zheng 	ret = setup_leaf_for_split(trans, root, path,
4511ad48fd75SYan, Zheng 				   sizeof(struct btrfs_item));
4512ad48fd75SYan, Zheng 	if (ret)
4513459931ecSChris Mason 		return ret;
4514ad48fd75SYan, Zheng 
45154961e293SDavid Sterba 	ret = split_item(root->fs_info, path, new_key, split_offset);
4516ad48fd75SYan, Zheng 	return ret;
4517ad48fd75SYan, Zheng }
4518ad48fd75SYan, Zheng 
4519ad48fd75SYan, Zheng /*
4520ad48fd75SYan, Zheng  * This function duplicate a item, giving 'new_key' to the new item.
4521ad48fd75SYan, Zheng  * It guarantees both items live in the same tree leaf and the new item
4522ad48fd75SYan, Zheng  * is contiguous with the original item.
4523ad48fd75SYan, Zheng  *
4524ad48fd75SYan, Zheng  * This allows us to split file extent in place, keeping a lock on the
4525ad48fd75SYan, Zheng  * leaf the entire time.
4526ad48fd75SYan, Zheng  */
4527ad48fd75SYan, Zheng int btrfs_duplicate_item(struct btrfs_trans_handle *trans,
4528ad48fd75SYan, Zheng 			 struct btrfs_root *root,
4529ad48fd75SYan, Zheng 			 struct btrfs_path *path,
4530310712b2SOmar Sandoval 			 const struct btrfs_key *new_key)
4531ad48fd75SYan, Zheng {
4532ad48fd75SYan, Zheng 	struct extent_buffer *leaf;
4533ad48fd75SYan, Zheng 	int ret;
4534ad48fd75SYan, Zheng 	u32 item_size;
4535ad48fd75SYan, Zheng 
4536ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4537ad48fd75SYan, Zheng 	item_size = btrfs_item_size_nr(leaf, path->slots[0]);
4538ad48fd75SYan, Zheng 	ret = setup_leaf_for_split(trans, root, path,
4539ad48fd75SYan, Zheng 				   item_size + sizeof(struct btrfs_item));
4540ad48fd75SYan, Zheng 	if (ret)
4541ad48fd75SYan, Zheng 		return ret;
4542ad48fd75SYan, Zheng 
4543ad48fd75SYan, Zheng 	path->slots[0]++;
4544afe5fea7STsutomu Itoh 	setup_items_for_insert(root, path, new_key, &item_size,
4545ad48fd75SYan, Zheng 			       item_size, item_size +
4546ad48fd75SYan, Zheng 			       sizeof(struct btrfs_item), 1);
4547ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4548ad48fd75SYan, Zheng 	memcpy_extent_buffer(leaf,
4549ad48fd75SYan, Zheng 			     btrfs_item_ptr_offset(leaf, path->slots[0]),
4550ad48fd75SYan, Zheng 			     btrfs_item_ptr_offset(leaf, path->slots[0] - 1),
4551ad48fd75SYan, Zheng 			     item_size);
4552ad48fd75SYan, Zheng 	return 0;
4553459931ecSChris Mason }
4554459931ecSChris Mason 
4555459931ecSChris Mason /*
4556d352ac68SChris Mason  * make the item pointed to by the path smaller.  new_size indicates
4557d352ac68SChris Mason  * how small to make it, and from_end tells us if we just chop bytes
4558d352ac68SChris Mason  * off the end of the item or if we shift the item to chop bytes off
4559d352ac68SChris Mason  * the front.
4560d352ac68SChris Mason  */
45612ff7e61eSJeff Mahoney void btrfs_truncate_item(struct btrfs_fs_info *fs_info,
45622ff7e61eSJeff Mahoney 			 struct btrfs_path *path, u32 new_size, int from_end)
4563b18c6685SChris Mason {
4564b18c6685SChris Mason 	int slot;
45655f39d397SChris Mason 	struct extent_buffer *leaf;
45665f39d397SChris Mason 	struct btrfs_item *item;
4567b18c6685SChris Mason 	u32 nritems;
4568b18c6685SChris Mason 	unsigned int data_end;
4569b18c6685SChris Mason 	unsigned int old_data_start;
4570b18c6685SChris Mason 	unsigned int old_size;
4571b18c6685SChris Mason 	unsigned int size_diff;
4572b18c6685SChris Mason 	int i;
4573cfed81a0SChris Mason 	struct btrfs_map_token token;
4574cfed81a0SChris Mason 
4575cfed81a0SChris Mason 	btrfs_init_map_token(&token);
4576b18c6685SChris Mason 
45775f39d397SChris Mason 	leaf = path->nodes[0];
4578179e29e4SChris Mason 	slot = path->slots[0];
4579179e29e4SChris Mason 
4580179e29e4SChris Mason 	old_size = btrfs_item_size_nr(leaf, slot);
4581179e29e4SChris Mason 	if (old_size == new_size)
4582143bede5SJeff Mahoney 		return;
4583b18c6685SChris Mason 
45845f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
45852ff7e61eSJeff Mahoney 	data_end = leaf_data_end(fs_info, leaf);
4586b18c6685SChris Mason 
45875f39d397SChris Mason 	old_data_start = btrfs_item_offset_nr(leaf, slot);
4588179e29e4SChris Mason 
4589b18c6685SChris Mason 	size_diff = old_size - new_size;
4590b18c6685SChris Mason 
4591b18c6685SChris Mason 	BUG_ON(slot < 0);
4592b18c6685SChris Mason 	BUG_ON(slot >= nritems);
4593b18c6685SChris Mason 
4594b18c6685SChris Mason 	/*
4595b18c6685SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4596b18c6685SChris Mason 	 */
4597b18c6685SChris Mason 	/* first correct the data pointers */
4598b18c6685SChris Mason 	for (i = slot; i < nritems; i++) {
45995f39d397SChris Mason 		u32 ioff;
4600dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
4601db94535dSChris Mason 
4602cfed81a0SChris Mason 		ioff = btrfs_token_item_offset(leaf, item, &token);
4603cfed81a0SChris Mason 		btrfs_set_token_item_offset(leaf, item,
4604cfed81a0SChris Mason 					    ioff + size_diff, &token);
4605b18c6685SChris Mason 	}
4606db94535dSChris Mason 
4607b18c6685SChris Mason 	/* shift the data */
4608179e29e4SChris Mason 	if (from_end) {
46093d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
46103d9ec8c4SNikolay Borisov 			      data_end + size_diff, BTRFS_LEAF_DATA_OFFSET +
4611b18c6685SChris Mason 			      data_end, old_data_start + new_size - data_end);
4612179e29e4SChris Mason 	} else {
4613179e29e4SChris Mason 		struct btrfs_disk_key disk_key;
4614179e29e4SChris Mason 		u64 offset;
4615179e29e4SChris Mason 
4616179e29e4SChris Mason 		btrfs_item_key(leaf, &disk_key, slot);
4617179e29e4SChris Mason 
4618179e29e4SChris Mason 		if (btrfs_disk_key_type(&disk_key) == BTRFS_EXTENT_DATA_KEY) {
4619179e29e4SChris Mason 			unsigned long ptr;
4620179e29e4SChris Mason 			struct btrfs_file_extent_item *fi;
4621179e29e4SChris Mason 
4622179e29e4SChris Mason 			fi = btrfs_item_ptr(leaf, slot,
4623179e29e4SChris Mason 					    struct btrfs_file_extent_item);
4624179e29e4SChris Mason 			fi = (struct btrfs_file_extent_item *)(
4625179e29e4SChris Mason 			     (unsigned long)fi - size_diff);
4626179e29e4SChris Mason 
4627179e29e4SChris Mason 			if (btrfs_file_extent_type(leaf, fi) ==
4628179e29e4SChris Mason 			    BTRFS_FILE_EXTENT_INLINE) {
4629179e29e4SChris Mason 				ptr = btrfs_item_ptr_offset(leaf, slot);
4630179e29e4SChris Mason 				memmove_extent_buffer(leaf, ptr,
4631179e29e4SChris Mason 				      (unsigned long)fi,
46327ec20afbSDavid Sterba 				      BTRFS_FILE_EXTENT_INLINE_DATA_START);
4633179e29e4SChris Mason 			}
4634179e29e4SChris Mason 		}
4635179e29e4SChris Mason 
46363d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
46373d9ec8c4SNikolay Borisov 			      data_end + size_diff, BTRFS_LEAF_DATA_OFFSET +
4638179e29e4SChris Mason 			      data_end, old_data_start - data_end);
4639179e29e4SChris Mason 
4640179e29e4SChris Mason 		offset = btrfs_disk_key_offset(&disk_key);
4641179e29e4SChris Mason 		btrfs_set_disk_key_offset(&disk_key, offset + size_diff);
4642179e29e4SChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot);
4643179e29e4SChris Mason 		if (slot == 0)
46440b246afaSJeff Mahoney 			fixup_low_keys(fs_info, path, &disk_key, 1);
4645179e29e4SChris Mason 	}
46465f39d397SChris Mason 
4647dd3cc16bSRoss Kirk 	item = btrfs_item_nr(slot);
46485f39d397SChris Mason 	btrfs_set_item_size(leaf, item, new_size);
46495f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
4650b18c6685SChris Mason 
46512ff7e61eSJeff Mahoney 	if (btrfs_leaf_free_space(fs_info, leaf) < 0) {
4652a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
4653b18c6685SChris Mason 		BUG();
46545f39d397SChris Mason 	}
4655b18c6685SChris Mason }
4656b18c6685SChris Mason 
4657d352ac68SChris Mason /*
46588f69dbd2SStefan Behrens  * make the item pointed to by the path bigger, data_size is the added size.
4659d352ac68SChris Mason  */
46602ff7e61eSJeff Mahoney void btrfs_extend_item(struct btrfs_fs_info *fs_info, struct btrfs_path *path,
46615f39d397SChris Mason 		       u32 data_size)
46626567e837SChris Mason {
46636567e837SChris Mason 	int slot;
46645f39d397SChris Mason 	struct extent_buffer *leaf;
46655f39d397SChris Mason 	struct btrfs_item *item;
46666567e837SChris Mason 	u32 nritems;
46676567e837SChris Mason 	unsigned int data_end;
46686567e837SChris Mason 	unsigned int old_data;
46696567e837SChris Mason 	unsigned int old_size;
46706567e837SChris Mason 	int i;
4671cfed81a0SChris Mason 	struct btrfs_map_token token;
4672cfed81a0SChris Mason 
4673cfed81a0SChris Mason 	btrfs_init_map_token(&token);
46746567e837SChris Mason 
46755f39d397SChris Mason 	leaf = path->nodes[0];
46766567e837SChris Mason 
46775f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
46782ff7e61eSJeff Mahoney 	data_end = leaf_data_end(fs_info, leaf);
46796567e837SChris Mason 
46802ff7e61eSJeff Mahoney 	if (btrfs_leaf_free_space(fs_info, leaf) < data_size) {
4681a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
46826567e837SChris Mason 		BUG();
46835f39d397SChris Mason 	}
46846567e837SChris Mason 	slot = path->slots[0];
46855f39d397SChris Mason 	old_data = btrfs_item_end_nr(leaf, slot);
46866567e837SChris Mason 
46876567e837SChris Mason 	BUG_ON(slot < 0);
46883326d1b0SChris Mason 	if (slot >= nritems) {
4689a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
46900b246afaSJeff Mahoney 		btrfs_crit(fs_info, "slot %d too large, nritems %d",
4691d397712bSChris Mason 			   slot, nritems);
46923326d1b0SChris Mason 		BUG_ON(1);
46933326d1b0SChris Mason 	}
46946567e837SChris Mason 
46956567e837SChris Mason 	/*
46966567e837SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
46976567e837SChris Mason 	 */
46986567e837SChris Mason 	/* first correct the data pointers */
46996567e837SChris Mason 	for (i = slot; i < nritems; i++) {
47005f39d397SChris Mason 		u32 ioff;
4701dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
4702db94535dSChris Mason 
4703cfed81a0SChris Mason 		ioff = btrfs_token_item_offset(leaf, item, &token);
4704cfed81a0SChris Mason 		btrfs_set_token_item_offset(leaf, item,
4705cfed81a0SChris Mason 					    ioff - data_size, &token);
47066567e837SChris Mason 	}
47075f39d397SChris Mason 
47086567e837SChris Mason 	/* shift the data */
47093d9ec8c4SNikolay Borisov 	memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
47103d9ec8c4SNikolay Borisov 		      data_end - data_size, BTRFS_LEAF_DATA_OFFSET +
47116567e837SChris Mason 		      data_end, old_data - data_end);
47125f39d397SChris Mason 
47136567e837SChris Mason 	data_end = old_data;
47145f39d397SChris Mason 	old_size = btrfs_item_size_nr(leaf, slot);
4715dd3cc16bSRoss Kirk 	item = btrfs_item_nr(slot);
47165f39d397SChris Mason 	btrfs_set_item_size(leaf, item, old_size + data_size);
47175f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
47186567e837SChris Mason 
47192ff7e61eSJeff Mahoney 	if (btrfs_leaf_free_space(fs_info, leaf) < 0) {
4720a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
47216567e837SChris Mason 		BUG();
47225f39d397SChris Mason 	}
47236567e837SChris Mason }
47246567e837SChris Mason 
472574123bd7SChris Mason /*
472644871b1bSChris Mason  * this is a helper for btrfs_insert_empty_items, the main goal here is
472744871b1bSChris Mason  * to save stack depth by doing the bulk of the work in a function
472844871b1bSChris Mason  * that doesn't call btrfs_search_slot
472974123bd7SChris Mason  */
4730afe5fea7STsutomu Itoh void setup_items_for_insert(struct btrfs_root *root, struct btrfs_path *path,
4731310712b2SOmar Sandoval 			    const struct btrfs_key *cpu_key, u32 *data_size,
473244871b1bSChris Mason 			    u32 total_data, u32 total_size, int nr)
4733be0e5c09SChris Mason {
47340b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
47355f39d397SChris Mason 	struct btrfs_item *item;
47369c58309dSChris Mason 	int i;
47377518a238SChris Mason 	u32 nritems;
4738be0e5c09SChris Mason 	unsigned int data_end;
4739e2fa7227SChris Mason 	struct btrfs_disk_key disk_key;
474044871b1bSChris Mason 	struct extent_buffer *leaf;
474144871b1bSChris Mason 	int slot;
4742cfed81a0SChris Mason 	struct btrfs_map_token token;
4743cfed81a0SChris Mason 
474424cdc847SFilipe Manana 	if (path->slots[0] == 0) {
474524cdc847SFilipe Manana 		btrfs_cpu_key_to_disk(&disk_key, cpu_key);
47460b246afaSJeff Mahoney 		fixup_low_keys(fs_info, path, &disk_key, 1);
474724cdc847SFilipe Manana 	}
474824cdc847SFilipe Manana 	btrfs_unlock_up_safe(path, 1);
474924cdc847SFilipe Manana 
4750cfed81a0SChris Mason 	btrfs_init_map_token(&token);
4751e2fa7227SChris Mason 
47525f39d397SChris Mason 	leaf = path->nodes[0];
475344871b1bSChris Mason 	slot = path->slots[0];
475474123bd7SChris Mason 
47555f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
47562ff7e61eSJeff Mahoney 	data_end = leaf_data_end(fs_info, leaf);
4757eb60ceacSChris Mason 
47582ff7e61eSJeff Mahoney 	if (btrfs_leaf_free_space(fs_info, leaf) < total_size) {
4759a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
47600b246afaSJeff Mahoney 		btrfs_crit(fs_info, "not enough freespace need %u have %d",
47612ff7e61eSJeff Mahoney 			   total_size, btrfs_leaf_free_space(fs_info, leaf));
4762be0e5c09SChris Mason 		BUG();
4763d4dbff95SChris Mason 	}
47645f39d397SChris Mason 
4765be0e5c09SChris Mason 	if (slot != nritems) {
47665f39d397SChris Mason 		unsigned int old_data = btrfs_item_end_nr(leaf, slot);
4767be0e5c09SChris Mason 
47685f39d397SChris Mason 		if (old_data < data_end) {
4769a4f78750SDavid Sterba 			btrfs_print_leaf(leaf);
47700b246afaSJeff Mahoney 			btrfs_crit(fs_info, "slot %d old_data %d data_end %d",
47715f39d397SChris Mason 				   slot, old_data, data_end);
47725f39d397SChris Mason 			BUG_ON(1);
47735f39d397SChris Mason 		}
4774be0e5c09SChris Mason 		/*
4775be0e5c09SChris Mason 		 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4776be0e5c09SChris Mason 		 */
4777be0e5c09SChris Mason 		/* first correct the data pointers */
47780783fcfcSChris Mason 		for (i = slot; i < nritems; i++) {
47795f39d397SChris Mason 			u32 ioff;
4780db94535dSChris Mason 
4781dd3cc16bSRoss Kirk 			item = btrfs_item_nr(i);
4782cfed81a0SChris Mason 			ioff = btrfs_token_item_offset(leaf, item, &token);
4783cfed81a0SChris Mason 			btrfs_set_token_item_offset(leaf, item,
4784cfed81a0SChris Mason 						    ioff - total_data, &token);
47850783fcfcSChris Mason 		}
4786be0e5c09SChris Mason 		/* shift the items */
47879c58309dSChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + nr),
47885f39d397SChris Mason 			      btrfs_item_nr_offset(slot),
47890783fcfcSChris Mason 			      (nritems - slot) * sizeof(struct btrfs_item));
4790be0e5c09SChris Mason 
4791be0e5c09SChris Mason 		/* shift the data */
47923d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
47933d9ec8c4SNikolay Borisov 			      data_end - total_data, BTRFS_LEAF_DATA_OFFSET +
4794be0e5c09SChris Mason 			      data_end, old_data - data_end);
4795be0e5c09SChris Mason 		data_end = old_data;
4796be0e5c09SChris Mason 	}
47975f39d397SChris Mason 
479862e2749eSChris Mason 	/* setup the item for the new data */
47999c58309dSChris Mason 	for (i = 0; i < nr; i++) {
48009c58309dSChris Mason 		btrfs_cpu_key_to_disk(&disk_key, cpu_key + i);
48019c58309dSChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot + i);
4802dd3cc16bSRoss Kirk 		item = btrfs_item_nr(slot + i);
4803cfed81a0SChris Mason 		btrfs_set_token_item_offset(leaf, item,
4804cfed81a0SChris Mason 					    data_end - data_size[i], &token);
48059c58309dSChris Mason 		data_end -= data_size[i];
4806cfed81a0SChris Mason 		btrfs_set_token_item_size(leaf, item, data_size[i], &token);
48079c58309dSChris Mason 	}
480844871b1bSChris Mason 
48099c58309dSChris Mason 	btrfs_set_header_nritems(leaf, nritems + nr);
4810b9473439SChris Mason 	btrfs_mark_buffer_dirty(leaf);
4811aa5d6bedSChris Mason 
48122ff7e61eSJeff Mahoney 	if (btrfs_leaf_free_space(fs_info, leaf) < 0) {
4813a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
4814be0e5c09SChris Mason 		BUG();
48155f39d397SChris Mason 	}
481644871b1bSChris Mason }
481744871b1bSChris Mason 
481844871b1bSChris Mason /*
481944871b1bSChris Mason  * Given a key and some data, insert items into the tree.
482044871b1bSChris Mason  * This does all the path init required, making room in the tree if needed.
482144871b1bSChris Mason  */
482244871b1bSChris Mason int btrfs_insert_empty_items(struct btrfs_trans_handle *trans,
482344871b1bSChris Mason 			    struct btrfs_root *root,
482444871b1bSChris Mason 			    struct btrfs_path *path,
4825310712b2SOmar Sandoval 			    const struct btrfs_key *cpu_key, u32 *data_size,
482644871b1bSChris Mason 			    int nr)
482744871b1bSChris Mason {
482844871b1bSChris Mason 	int ret = 0;
482944871b1bSChris Mason 	int slot;
483044871b1bSChris Mason 	int i;
483144871b1bSChris Mason 	u32 total_size = 0;
483244871b1bSChris Mason 	u32 total_data = 0;
483344871b1bSChris Mason 
483444871b1bSChris Mason 	for (i = 0; i < nr; i++)
483544871b1bSChris Mason 		total_data += data_size[i];
483644871b1bSChris Mason 
483744871b1bSChris Mason 	total_size = total_data + (nr * sizeof(struct btrfs_item));
483844871b1bSChris Mason 	ret = btrfs_search_slot(trans, root, cpu_key, path, total_size, 1);
483944871b1bSChris Mason 	if (ret == 0)
484044871b1bSChris Mason 		return -EEXIST;
484144871b1bSChris Mason 	if (ret < 0)
4842143bede5SJeff Mahoney 		return ret;
484344871b1bSChris Mason 
484444871b1bSChris Mason 	slot = path->slots[0];
484544871b1bSChris Mason 	BUG_ON(slot < 0);
484644871b1bSChris Mason 
4847afe5fea7STsutomu Itoh 	setup_items_for_insert(root, path, cpu_key, data_size,
484844871b1bSChris Mason 			       total_data, total_size, nr);
4849143bede5SJeff Mahoney 	return 0;
485062e2749eSChris Mason }
485162e2749eSChris Mason 
485262e2749eSChris Mason /*
485362e2749eSChris Mason  * Given a key and some data, insert an item into the tree.
485462e2749eSChris Mason  * This does all the path init required, making room in the tree if needed.
485562e2749eSChris Mason  */
4856310712b2SOmar Sandoval int btrfs_insert_item(struct btrfs_trans_handle *trans, struct btrfs_root *root,
4857310712b2SOmar Sandoval 		      const struct btrfs_key *cpu_key, void *data,
4858310712b2SOmar Sandoval 		      u32 data_size)
485962e2749eSChris Mason {
486062e2749eSChris Mason 	int ret = 0;
48612c90e5d6SChris Mason 	struct btrfs_path *path;
48625f39d397SChris Mason 	struct extent_buffer *leaf;
48635f39d397SChris Mason 	unsigned long ptr;
486462e2749eSChris Mason 
48652c90e5d6SChris Mason 	path = btrfs_alloc_path();
4866db5b493aSTsutomu Itoh 	if (!path)
4867db5b493aSTsutomu Itoh 		return -ENOMEM;
48682c90e5d6SChris Mason 	ret = btrfs_insert_empty_item(trans, root, path, cpu_key, data_size);
486962e2749eSChris Mason 	if (!ret) {
48705f39d397SChris Mason 		leaf = path->nodes[0];
48715f39d397SChris Mason 		ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
48725f39d397SChris Mason 		write_extent_buffer(leaf, data, ptr, data_size);
48735f39d397SChris Mason 		btrfs_mark_buffer_dirty(leaf);
487462e2749eSChris Mason 	}
48752c90e5d6SChris Mason 	btrfs_free_path(path);
4876aa5d6bedSChris Mason 	return ret;
4877be0e5c09SChris Mason }
4878be0e5c09SChris Mason 
487974123bd7SChris Mason /*
48805de08d7dSChris Mason  * delete the pointer from a given node.
488174123bd7SChris Mason  *
4882d352ac68SChris Mason  * the tree should have been previously balanced so the deletion does not
4883d352ac68SChris Mason  * empty a node.
488474123bd7SChris Mason  */
4885afe5fea7STsutomu Itoh static void del_ptr(struct btrfs_root *root, struct btrfs_path *path,
4886afe5fea7STsutomu Itoh 		    int level, int slot)
4887be0e5c09SChris Mason {
48880b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
48895f39d397SChris Mason 	struct extent_buffer *parent = path->nodes[level];
48907518a238SChris Mason 	u32 nritems;
4891f3ea38daSJan Schmidt 	int ret;
4892be0e5c09SChris Mason 
48935f39d397SChris Mason 	nritems = btrfs_header_nritems(parent);
4894be0e5c09SChris Mason 	if (slot != nritems - 1) {
48950e411eceSLiu Bo 		if (level)
4896a446a979SDavid Sterba 			tree_mod_log_eb_move(parent, slot, slot + 1,
4897a446a979SDavid Sterba 					nritems - slot - 1);
48985f39d397SChris Mason 		memmove_extent_buffer(parent,
48995f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot),
49005f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot + 1),
4901d6025579SChris Mason 			      sizeof(struct btrfs_key_ptr) *
4902d6025579SChris Mason 			      (nritems - slot - 1));
490357ba86c0SChris Mason 	} else if (level) {
4904e09c2efeSDavid Sterba 		ret = tree_mod_log_insert_key(parent, slot, MOD_LOG_KEY_REMOVE,
4905e09c2efeSDavid Sterba 				GFP_NOFS);
490657ba86c0SChris Mason 		BUG_ON(ret < 0);
4907be0e5c09SChris Mason 	}
4908f3ea38daSJan Schmidt 
49097518a238SChris Mason 	nritems--;
49105f39d397SChris Mason 	btrfs_set_header_nritems(parent, nritems);
49117518a238SChris Mason 	if (nritems == 0 && parent == root->node) {
49125f39d397SChris Mason 		BUG_ON(btrfs_header_level(root->node) != 1);
4913eb60ceacSChris Mason 		/* just turn the root into a leaf and break */
49145f39d397SChris Mason 		btrfs_set_header_level(root->node, 0);
4915bb803951SChris Mason 	} else if (slot == 0) {
49165f39d397SChris Mason 		struct btrfs_disk_key disk_key;
49175f39d397SChris Mason 
49185f39d397SChris Mason 		btrfs_node_key(parent, &disk_key, 0);
49190b246afaSJeff Mahoney 		fixup_low_keys(fs_info, path, &disk_key, level + 1);
4920be0e5c09SChris Mason 	}
4921d6025579SChris Mason 	btrfs_mark_buffer_dirty(parent);
4922be0e5c09SChris Mason }
4923be0e5c09SChris Mason 
492474123bd7SChris Mason /*
4925323ac95bSChris Mason  * a helper function to delete the leaf pointed to by path->slots[1] and
49265d4f98a2SYan Zheng  * path->nodes[1].
4927323ac95bSChris Mason  *
4928323ac95bSChris Mason  * This deletes the pointer in path->nodes[1] and frees the leaf
4929323ac95bSChris Mason  * block extent.  zero is returned if it all worked out, < 0 otherwise.
4930323ac95bSChris Mason  *
4931323ac95bSChris Mason  * The path must have already been setup for deleting the leaf, including
4932323ac95bSChris Mason  * all the proper balancing.  path->nodes[1] must be locked.
4933323ac95bSChris Mason  */
4934143bede5SJeff Mahoney static noinline void btrfs_del_leaf(struct btrfs_trans_handle *trans,
4935323ac95bSChris Mason 				    struct btrfs_root *root,
49365d4f98a2SYan Zheng 				    struct btrfs_path *path,
49375d4f98a2SYan Zheng 				    struct extent_buffer *leaf)
4938323ac95bSChris Mason {
49395d4f98a2SYan Zheng 	WARN_ON(btrfs_header_generation(leaf) != trans->transid);
4940afe5fea7STsutomu Itoh 	del_ptr(root, path, 1, path->slots[1]);
4941323ac95bSChris Mason 
49424d081c41SChris Mason 	/*
49434d081c41SChris Mason 	 * btrfs_free_extent is expensive, we want to make sure we
49444d081c41SChris Mason 	 * aren't holding any locks when we call it
49454d081c41SChris Mason 	 */
49464d081c41SChris Mason 	btrfs_unlock_up_safe(path, 0);
49474d081c41SChris Mason 
4948f0486c68SYan, Zheng 	root_sub_used(root, leaf->len);
4949f0486c68SYan, Zheng 
49503083ee2eSJosef Bacik 	extent_buffer_get(leaf);
49515581a51aSJan Schmidt 	btrfs_free_tree_block(trans, root, leaf, 0, 1);
49523083ee2eSJosef Bacik 	free_extent_buffer_stale(leaf);
4953323ac95bSChris Mason }
4954323ac95bSChris Mason /*
495574123bd7SChris Mason  * delete the item at the leaf level in path.  If that empties
495674123bd7SChris Mason  * the leaf, remove it from the tree
495774123bd7SChris Mason  */
495885e21bacSChris Mason int btrfs_del_items(struct btrfs_trans_handle *trans, struct btrfs_root *root,
495985e21bacSChris Mason 		    struct btrfs_path *path, int slot, int nr)
4960be0e5c09SChris Mason {
49610b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
49625f39d397SChris Mason 	struct extent_buffer *leaf;
49635f39d397SChris Mason 	struct btrfs_item *item;
4964ce0eac2aSAlexandru Moise 	u32 last_off;
4965ce0eac2aSAlexandru Moise 	u32 dsize = 0;
4966aa5d6bedSChris Mason 	int ret = 0;
4967aa5d6bedSChris Mason 	int wret;
496885e21bacSChris Mason 	int i;
49697518a238SChris Mason 	u32 nritems;
4970cfed81a0SChris Mason 	struct btrfs_map_token token;
4971cfed81a0SChris Mason 
4972cfed81a0SChris Mason 	btrfs_init_map_token(&token);
4973be0e5c09SChris Mason 
49745f39d397SChris Mason 	leaf = path->nodes[0];
497585e21bacSChris Mason 	last_off = btrfs_item_offset_nr(leaf, slot + nr - 1);
497685e21bacSChris Mason 
497785e21bacSChris Mason 	for (i = 0; i < nr; i++)
497885e21bacSChris Mason 		dsize += btrfs_item_size_nr(leaf, slot + i);
497985e21bacSChris Mason 
49805f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
4981be0e5c09SChris Mason 
498285e21bacSChris Mason 	if (slot + nr != nritems) {
49832ff7e61eSJeff Mahoney 		int data_end = leaf_data_end(fs_info, leaf);
49845f39d397SChris Mason 
49853d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
4986d6025579SChris Mason 			      data_end + dsize,
49873d9ec8c4SNikolay Borisov 			      BTRFS_LEAF_DATA_OFFSET + data_end,
498885e21bacSChris Mason 			      last_off - data_end);
49895f39d397SChris Mason 
499085e21bacSChris Mason 		for (i = slot + nr; i < nritems; i++) {
49915f39d397SChris Mason 			u32 ioff;
4992db94535dSChris Mason 
4993dd3cc16bSRoss Kirk 			item = btrfs_item_nr(i);
4994cfed81a0SChris Mason 			ioff = btrfs_token_item_offset(leaf, item, &token);
4995cfed81a0SChris Mason 			btrfs_set_token_item_offset(leaf, item,
4996cfed81a0SChris Mason 						    ioff + dsize, &token);
49970783fcfcSChris Mason 		}
4998db94535dSChris Mason 
49995f39d397SChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot),
500085e21bacSChris Mason 			      btrfs_item_nr_offset(slot + nr),
50010783fcfcSChris Mason 			      sizeof(struct btrfs_item) *
500285e21bacSChris Mason 			      (nritems - slot - nr));
5003be0e5c09SChris Mason 	}
500485e21bacSChris Mason 	btrfs_set_header_nritems(leaf, nritems - nr);
500585e21bacSChris Mason 	nritems -= nr;
50065f39d397SChris Mason 
500774123bd7SChris Mason 	/* delete the leaf if we've emptied it */
50087518a238SChris Mason 	if (nritems == 0) {
50095f39d397SChris Mason 		if (leaf == root->node) {
50105f39d397SChris Mason 			btrfs_set_header_level(leaf, 0);
50119a8dd150SChris Mason 		} else {
5012f0486c68SYan, Zheng 			btrfs_set_path_blocking(path);
50137c302b49SDavid Sterba 			clean_tree_block(fs_info, leaf);
5014143bede5SJeff Mahoney 			btrfs_del_leaf(trans, root, path, leaf);
50159a8dd150SChris Mason 		}
5016be0e5c09SChris Mason 	} else {
50177518a238SChris Mason 		int used = leaf_space_used(leaf, 0, nritems);
5018aa5d6bedSChris Mason 		if (slot == 0) {
50195f39d397SChris Mason 			struct btrfs_disk_key disk_key;
50205f39d397SChris Mason 
50215f39d397SChris Mason 			btrfs_item_key(leaf, &disk_key, 0);
50220b246afaSJeff Mahoney 			fixup_low_keys(fs_info, path, &disk_key, 1);
5023aa5d6bedSChris Mason 		}
5024aa5d6bedSChris Mason 
502574123bd7SChris Mason 		/* delete the leaf if it is mostly empty */
50260b246afaSJeff Mahoney 		if (used < BTRFS_LEAF_DATA_SIZE(fs_info) / 3) {
5027be0e5c09SChris Mason 			/* push_leaf_left fixes the path.
5028be0e5c09SChris Mason 			 * make sure the path still points to our leaf
5029be0e5c09SChris Mason 			 * for possible call to del_ptr below
5030be0e5c09SChris Mason 			 */
50314920c9acSChris Mason 			slot = path->slots[1];
50325f39d397SChris Mason 			extent_buffer_get(leaf);
50335f39d397SChris Mason 
5034b9473439SChris Mason 			btrfs_set_path_blocking(path);
503599d8f83cSChris Mason 			wret = push_leaf_left(trans, root, path, 1, 1,
503699d8f83cSChris Mason 					      1, (u32)-1);
503754aa1f4dSChris Mason 			if (wret < 0 && wret != -ENOSPC)
5038aa5d6bedSChris Mason 				ret = wret;
50395f39d397SChris Mason 
50405f39d397SChris Mason 			if (path->nodes[0] == leaf &&
50415f39d397SChris Mason 			    btrfs_header_nritems(leaf)) {
504299d8f83cSChris Mason 				wret = push_leaf_right(trans, root, path, 1,
504399d8f83cSChris Mason 						       1, 1, 0);
504454aa1f4dSChris Mason 				if (wret < 0 && wret != -ENOSPC)
5045aa5d6bedSChris Mason 					ret = wret;
5046aa5d6bedSChris Mason 			}
50475f39d397SChris Mason 
50485f39d397SChris Mason 			if (btrfs_header_nritems(leaf) == 0) {
5049323ac95bSChris Mason 				path->slots[1] = slot;
5050143bede5SJeff Mahoney 				btrfs_del_leaf(trans, root, path, leaf);
50515f39d397SChris Mason 				free_extent_buffer(leaf);
5052143bede5SJeff Mahoney 				ret = 0;
50535de08d7dSChris Mason 			} else {
5054925baeddSChris Mason 				/* if we're still in the path, make sure
5055925baeddSChris Mason 				 * we're dirty.  Otherwise, one of the
5056925baeddSChris Mason 				 * push_leaf functions must have already
5057925baeddSChris Mason 				 * dirtied this buffer
5058925baeddSChris Mason 				 */
5059925baeddSChris Mason 				if (path->nodes[0] == leaf)
50605f39d397SChris Mason 					btrfs_mark_buffer_dirty(leaf);
50615f39d397SChris Mason 				free_extent_buffer(leaf);
5062be0e5c09SChris Mason 			}
5063d5719762SChris Mason 		} else {
50645f39d397SChris Mason 			btrfs_mark_buffer_dirty(leaf);
5065be0e5c09SChris Mason 		}
50669a8dd150SChris Mason 	}
5067aa5d6bedSChris Mason 	return ret;
50689a8dd150SChris Mason }
50699a8dd150SChris Mason 
507097571fd0SChris Mason /*
5071925baeddSChris Mason  * search the tree again to find a leaf with lesser keys
50727bb86316SChris Mason  * returns 0 if it found something or 1 if there are no lesser leaves.
50737bb86316SChris Mason  * returns < 0 on io errors.
5074d352ac68SChris Mason  *
5075d352ac68SChris Mason  * This may release the path, and so you may lose any locks held at the
5076d352ac68SChris Mason  * time you call it.
50777bb86316SChris Mason  */
507816e7549fSJosef Bacik int btrfs_prev_leaf(struct btrfs_root *root, struct btrfs_path *path)
50797bb86316SChris Mason {
5080925baeddSChris Mason 	struct btrfs_key key;
5081925baeddSChris Mason 	struct btrfs_disk_key found_key;
5082925baeddSChris Mason 	int ret;
50837bb86316SChris Mason 
5084925baeddSChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, 0);
5085925baeddSChris Mason 
5086e8b0d724SFilipe David Borba Manana 	if (key.offset > 0) {
5087925baeddSChris Mason 		key.offset--;
5088e8b0d724SFilipe David Borba Manana 	} else if (key.type > 0) {
5089925baeddSChris Mason 		key.type--;
5090e8b0d724SFilipe David Borba Manana 		key.offset = (u64)-1;
5091e8b0d724SFilipe David Borba Manana 	} else if (key.objectid > 0) {
5092925baeddSChris Mason 		key.objectid--;
5093e8b0d724SFilipe David Borba Manana 		key.type = (u8)-1;
5094e8b0d724SFilipe David Borba Manana 		key.offset = (u64)-1;
5095e8b0d724SFilipe David Borba Manana 	} else {
50967bb86316SChris Mason 		return 1;
5097e8b0d724SFilipe David Borba Manana 	}
50987bb86316SChris Mason 
5099b3b4aa74SDavid Sterba 	btrfs_release_path(path);
5100925baeddSChris Mason 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5101925baeddSChris Mason 	if (ret < 0)
5102925baeddSChris Mason 		return ret;
5103925baeddSChris Mason 	btrfs_item_key(path->nodes[0], &found_key, 0);
5104925baeddSChris Mason 	ret = comp_keys(&found_key, &key);
5105337c6f68SFilipe Manana 	/*
5106337c6f68SFilipe Manana 	 * We might have had an item with the previous key in the tree right
5107337c6f68SFilipe Manana 	 * before we released our path. And after we released our path, that
5108337c6f68SFilipe Manana 	 * item might have been pushed to the first slot (0) of the leaf we
5109337c6f68SFilipe Manana 	 * were holding due to a tree balance. Alternatively, an item with the
5110337c6f68SFilipe Manana 	 * previous key can exist as the only element of a leaf (big fat item).
5111337c6f68SFilipe Manana 	 * Therefore account for these 2 cases, so that our callers (like
5112337c6f68SFilipe Manana 	 * btrfs_previous_item) don't miss an existing item with a key matching
5113337c6f68SFilipe Manana 	 * the previous key we computed above.
5114337c6f68SFilipe Manana 	 */
5115337c6f68SFilipe Manana 	if (ret <= 0)
51167bb86316SChris Mason 		return 0;
5117925baeddSChris Mason 	return 1;
51187bb86316SChris Mason }
51197bb86316SChris Mason 
51203f157a2fSChris Mason /*
51213f157a2fSChris Mason  * A helper function to walk down the tree starting at min_key, and looking
5122de78b51aSEric Sandeen  * for nodes or leaves that are have a minimum transaction id.
5123de78b51aSEric Sandeen  * This is used by the btree defrag code, and tree logging
51243f157a2fSChris Mason  *
51253f157a2fSChris Mason  * This does not cow, but it does stuff the starting key it finds back
51263f157a2fSChris Mason  * into min_key, so you can call btrfs_search_slot with cow=1 on the
51273f157a2fSChris Mason  * key and get a writable path.
51283f157a2fSChris Mason  *
51293f157a2fSChris Mason  * This honors path->lowest_level to prevent descent past a given level
51303f157a2fSChris Mason  * of the tree.
51313f157a2fSChris Mason  *
5132d352ac68SChris Mason  * min_trans indicates the oldest transaction that you are interested
5133d352ac68SChris Mason  * in walking through.  Any nodes or leaves older than min_trans are
5134d352ac68SChris Mason  * skipped over (without reading them).
5135d352ac68SChris Mason  *
51363f157a2fSChris Mason  * returns zero if something useful was found, < 0 on error and 1 if there
51373f157a2fSChris Mason  * was nothing in the tree that matched the search criteria.
51383f157a2fSChris Mason  */
51393f157a2fSChris Mason int btrfs_search_forward(struct btrfs_root *root, struct btrfs_key *min_key,
5140de78b51aSEric Sandeen 			 struct btrfs_path *path,
51413f157a2fSChris Mason 			 u64 min_trans)
51423f157a2fSChris Mason {
51432ff7e61eSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
51443f157a2fSChris Mason 	struct extent_buffer *cur;
51453f157a2fSChris Mason 	struct btrfs_key found_key;
51463f157a2fSChris Mason 	int slot;
51479652480bSYan 	int sret;
51483f157a2fSChris Mason 	u32 nritems;
51493f157a2fSChris Mason 	int level;
51503f157a2fSChris Mason 	int ret = 1;
5151f98de9b9SFilipe Manana 	int keep_locks = path->keep_locks;
51523f157a2fSChris Mason 
5153f98de9b9SFilipe Manana 	path->keep_locks = 1;
51543f157a2fSChris Mason again:
5155bd681513SChris Mason 	cur = btrfs_read_lock_root_node(root);
51563f157a2fSChris Mason 	level = btrfs_header_level(cur);
5157e02119d5SChris Mason 	WARN_ON(path->nodes[level]);
51583f157a2fSChris Mason 	path->nodes[level] = cur;
5159bd681513SChris Mason 	path->locks[level] = BTRFS_READ_LOCK;
51603f157a2fSChris Mason 
51613f157a2fSChris Mason 	if (btrfs_header_generation(cur) < min_trans) {
51623f157a2fSChris Mason 		ret = 1;
51633f157a2fSChris Mason 		goto out;
51643f157a2fSChris Mason 	}
51653f157a2fSChris Mason 	while (1) {
51663f157a2fSChris Mason 		nritems = btrfs_header_nritems(cur);
51673f157a2fSChris Mason 		level = btrfs_header_level(cur);
5168a74b35ecSNikolay Borisov 		sret = btrfs_bin_search(cur, min_key, level, &slot);
51693f157a2fSChris Mason 
5170323ac95bSChris Mason 		/* at the lowest level, we're done, setup the path and exit */
5171323ac95bSChris Mason 		if (level == path->lowest_level) {
5172e02119d5SChris Mason 			if (slot >= nritems)
5173e02119d5SChris Mason 				goto find_next_key;
51743f157a2fSChris Mason 			ret = 0;
51753f157a2fSChris Mason 			path->slots[level] = slot;
51763f157a2fSChris Mason 			btrfs_item_key_to_cpu(cur, &found_key, slot);
51773f157a2fSChris Mason 			goto out;
51783f157a2fSChris Mason 		}
51799652480bSYan 		if (sret && slot > 0)
51809652480bSYan 			slot--;
51813f157a2fSChris Mason 		/*
5182de78b51aSEric Sandeen 		 * check this node pointer against the min_trans parameters.
5183de78b51aSEric Sandeen 		 * If it is too old, old, skip to the next one.
51843f157a2fSChris Mason 		 */
51853f157a2fSChris Mason 		while (slot < nritems) {
51863f157a2fSChris Mason 			u64 gen;
5187e02119d5SChris Mason 
51883f157a2fSChris Mason 			gen = btrfs_node_ptr_generation(cur, slot);
51893f157a2fSChris Mason 			if (gen < min_trans) {
51903f157a2fSChris Mason 				slot++;
51913f157a2fSChris Mason 				continue;
51923f157a2fSChris Mason 			}
51933f157a2fSChris Mason 			break;
51943f157a2fSChris Mason 		}
5195e02119d5SChris Mason find_next_key:
51963f157a2fSChris Mason 		/*
51973f157a2fSChris Mason 		 * we didn't find a candidate key in this node, walk forward
51983f157a2fSChris Mason 		 * and find another one
51993f157a2fSChris Mason 		 */
52003f157a2fSChris Mason 		if (slot >= nritems) {
5201e02119d5SChris Mason 			path->slots[level] = slot;
5202b4ce94deSChris Mason 			btrfs_set_path_blocking(path);
5203e02119d5SChris Mason 			sret = btrfs_find_next_key(root, path, min_key, level,
5204de78b51aSEric Sandeen 						  min_trans);
5205e02119d5SChris Mason 			if (sret == 0) {
5206b3b4aa74SDavid Sterba 				btrfs_release_path(path);
52073f157a2fSChris Mason 				goto again;
52083f157a2fSChris Mason 			} else {
52093f157a2fSChris Mason 				goto out;
52103f157a2fSChris Mason 			}
52113f157a2fSChris Mason 		}
52123f157a2fSChris Mason 		/* save our key for returning back */
52133f157a2fSChris Mason 		btrfs_node_key_to_cpu(cur, &found_key, slot);
52143f157a2fSChris Mason 		path->slots[level] = slot;
52153f157a2fSChris Mason 		if (level == path->lowest_level) {
52163f157a2fSChris Mason 			ret = 0;
52173f157a2fSChris Mason 			goto out;
52183f157a2fSChris Mason 		}
5219b4ce94deSChris Mason 		btrfs_set_path_blocking(path);
52202ff7e61eSJeff Mahoney 		cur = read_node_slot(fs_info, cur, slot);
5221fb770ae4SLiu Bo 		if (IS_ERR(cur)) {
5222fb770ae4SLiu Bo 			ret = PTR_ERR(cur);
5223fb770ae4SLiu Bo 			goto out;
5224fb770ae4SLiu Bo 		}
52253f157a2fSChris Mason 
5226bd681513SChris Mason 		btrfs_tree_read_lock(cur);
5227b4ce94deSChris Mason 
5228bd681513SChris Mason 		path->locks[level - 1] = BTRFS_READ_LOCK;
52293f157a2fSChris Mason 		path->nodes[level - 1] = cur;
5230f7c79f30SChris Mason 		unlock_up(path, level, 1, 0, NULL);
5231bd681513SChris Mason 		btrfs_clear_path_blocking(path, NULL, 0);
52323f157a2fSChris Mason 	}
52333f157a2fSChris Mason out:
5234f98de9b9SFilipe Manana 	path->keep_locks = keep_locks;
5235f98de9b9SFilipe Manana 	if (ret == 0) {
5236f98de9b9SFilipe Manana 		btrfs_unlock_up_safe(path, path->lowest_level + 1);
5237b4ce94deSChris Mason 		btrfs_set_path_blocking(path);
5238f98de9b9SFilipe Manana 		memcpy(min_key, &found_key, sizeof(found_key));
5239f98de9b9SFilipe Manana 	}
52403f157a2fSChris Mason 	return ret;
52413f157a2fSChris Mason }
52423f157a2fSChris Mason 
52432ff7e61eSJeff Mahoney static int tree_move_down(struct btrfs_fs_info *fs_info,
52447069830aSAlexander Block 			   struct btrfs_path *path,
5245ab6a43e1SDavid Sterba 			   int *level)
52467069830aSAlexander Block {
5247fb770ae4SLiu Bo 	struct extent_buffer *eb;
5248fb770ae4SLiu Bo 
524974dd17fbSChris Mason 	BUG_ON(*level == 0);
52502ff7e61eSJeff Mahoney 	eb = read_node_slot(fs_info, path->nodes[*level], path->slots[*level]);
5251fb770ae4SLiu Bo 	if (IS_ERR(eb))
5252fb770ae4SLiu Bo 		return PTR_ERR(eb);
5253fb770ae4SLiu Bo 
5254fb770ae4SLiu Bo 	path->nodes[*level - 1] = eb;
52557069830aSAlexander Block 	path->slots[*level - 1] = 0;
52567069830aSAlexander Block 	(*level)--;
5257fb770ae4SLiu Bo 	return 0;
52587069830aSAlexander Block }
52597069830aSAlexander Block 
5260f1e30261SDavid Sterba static int tree_move_next_or_upnext(struct btrfs_path *path,
52617069830aSAlexander Block 				    int *level, int root_level)
52627069830aSAlexander Block {
52637069830aSAlexander Block 	int ret = 0;
52647069830aSAlexander Block 	int nritems;
52657069830aSAlexander Block 	nritems = btrfs_header_nritems(path->nodes[*level]);
52667069830aSAlexander Block 
52677069830aSAlexander Block 	path->slots[*level]++;
52687069830aSAlexander Block 
526974dd17fbSChris Mason 	while (path->slots[*level] >= nritems) {
52707069830aSAlexander Block 		if (*level == root_level)
52717069830aSAlexander Block 			return -1;
52727069830aSAlexander Block 
52737069830aSAlexander Block 		/* move upnext */
52747069830aSAlexander Block 		path->slots[*level] = 0;
52757069830aSAlexander Block 		free_extent_buffer(path->nodes[*level]);
52767069830aSAlexander Block 		path->nodes[*level] = NULL;
52777069830aSAlexander Block 		(*level)++;
52787069830aSAlexander Block 		path->slots[*level]++;
52797069830aSAlexander Block 
52807069830aSAlexander Block 		nritems = btrfs_header_nritems(path->nodes[*level]);
52817069830aSAlexander Block 		ret = 1;
52827069830aSAlexander Block 	}
52837069830aSAlexander Block 	return ret;
52847069830aSAlexander Block }
52857069830aSAlexander Block 
52867069830aSAlexander Block /*
52877069830aSAlexander Block  * Returns 1 if it had to move up and next. 0 is returned if it moved only next
52887069830aSAlexander Block  * or down.
52897069830aSAlexander Block  */
52902ff7e61eSJeff Mahoney static int tree_advance(struct btrfs_fs_info *fs_info,
52917069830aSAlexander Block 			struct btrfs_path *path,
52927069830aSAlexander Block 			int *level, int root_level,
52937069830aSAlexander Block 			int allow_down,
52947069830aSAlexander Block 			struct btrfs_key *key)
52957069830aSAlexander Block {
52967069830aSAlexander Block 	int ret;
52977069830aSAlexander Block 
52987069830aSAlexander Block 	if (*level == 0 || !allow_down) {
5299f1e30261SDavid Sterba 		ret = tree_move_next_or_upnext(path, level, root_level);
53007069830aSAlexander Block 	} else {
5301ab6a43e1SDavid Sterba 		ret = tree_move_down(fs_info, path, level);
53027069830aSAlexander Block 	}
53037069830aSAlexander Block 	if (ret >= 0) {
53047069830aSAlexander Block 		if (*level == 0)
53057069830aSAlexander Block 			btrfs_item_key_to_cpu(path->nodes[*level], key,
53067069830aSAlexander Block 					path->slots[*level]);
53077069830aSAlexander Block 		else
53087069830aSAlexander Block 			btrfs_node_key_to_cpu(path->nodes[*level], key,
53097069830aSAlexander Block 					path->slots[*level]);
53107069830aSAlexander Block 	}
53117069830aSAlexander Block 	return ret;
53127069830aSAlexander Block }
53137069830aSAlexander Block 
53142ff7e61eSJeff Mahoney static int tree_compare_item(struct btrfs_path *left_path,
53157069830aSAlexander Block 			     struct btrfs_path *right_path,
53167069830aSAlexander Block 			     char *tmp_buf)
53177069830aSAlexander Block {
53187069830aSAlexander Block 	int cmp;
53197069830aSAlexander Block 	int len1, len2;
53207069830aSAlexander Block 	unsigned long off1, off2;
53217069830aSAlexander Block 
53227069830aSAlexander Block 	len1 = btrfs_item_size_nr(left_path->nodes[0], left_path->slots[0]);
53237069830aSAlexander Block 	len2 = btrfs_item_size_nr(right_path->nodes[0], right_path->slots[0]);
53247069830aSAlexander Block 	if (len1 != len2)
53257069830aSAlexander Block 		return 1;
53267069830aSAlexander Block 
53277069830aSAlexander Block 	off1 = btrfs_item_ptr_offset(left_path->nodes[0], left_path->slots[0]);
53287069830aSAlexander Block 	off2 = btrfs_item_ptr_offset(right_path->nodes[0],
53297069830aSAlexander Block 				right_path->slots[0]);
53307069830aSAlexander Block 
53317069830aSAlexander Block 	read_extent_buffer(left_path->nodes[0], tmp_buf, off1, len1);
53327069830aSAlexander Block 
53337069830aSAlexander Block 	cmp = memcmp_extent_buffer(right_path->nodes[0], tmp_buf, off2, len1);
53347069830aSAlexander Block 	if (cmp)
53357069830aSAlexander Block 		return 1;
53367069830aSAlexander Block 	return 0;
53377069830aSAlexander Block }
53387069830aSAlexander Block 
53397069830aSAlexander Block #define ADVANCE 1
53407069830aSAlexander Block #define ADVANCE_ONLY_NEXT -1
53417069830aSAlexander Block 
53427069830aSAlexander Block /*
53437069830aSAlexander Block  * This function compares two trees and calls the provided callback for
53447069830aSAlexander Block  * every changed/new/deleted item it finds.
53457069830aSAlexander Block  * If shared tree blocks are encountered, whole subtrees are skipped, making
53467069830aSAlexander Block  * the compare pretty fast on snapshotted subvolumes.
53477069830aSAlexander Block  *
53487069830aSAlexander Block  * This currently works on commit roots only. As commit roots are read only,
53497069830aSAlexander Block  * we don't do any locking. The commit roots are protected with transactions.
53507069830aSAlexander Block  * Transactions are ended and rejoined when a commit is tried in between.
53517069830aSAlexander Block  *
53527069830aSAlexander Block  * This function checks for modifications done to the trees while comparing.
53537069830aSAlexander Block  * If it detects a change, it aborts immediately.
53547069830aSAlexander Block  */
53557069830aSAlexander Block int btrfs_compare_trees(struct btrfs_root *left_root,
53567069830aSAlexander Block 			struct btrfs_root *right_root,
53577069830aSAlexander Block 			btrfs_changed_cb_t changed_cb, void *ctx)
53587069830aSAlexander Block {
53590b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = left_root->fs_info;
53607069830aSAlexander Block 	int ret;
53617069830aSAlexander Block 	int cmp;
53627069830aSAlexander Block 	struct btrfs_path *left_path = NULL;
53637069830aSAlexander Block 	struct btrfs_path *right_path = NULL;
53647069830aSAlexander Block 	struct btrfs_key left_key;
53657069830aSAlexander Block 	struct btrfs_key right_key;
53667069830aSAlexander Block 	char *tmp_buf = NULL;
53677069830aSAlexander Block 	int left_root_level;
53687069830aSAlexander Block 	int right_root_level;
53697069830aSAlexander Block 	int left_level;
53707069830aSAlexander Block 	int right_level;
53717069830aSAlexander Block 	int left_end_reached;
53727069830aSAlexander Block 	int right_end_reached;
53737069830aSAlexander Block 	int advance_left;
53747069830aSAlexander Block 	int advance_right;
53757069830aSAlexander Block 	u64 left_blockptr;
53767069830aSAlexander Block 	u64 right_blockptr;
53776baa4293SFilipe Manana 	u64 left_gen;
53786baa4293SFilipe Manana 	u64 right_gen;
53797069830aSAlexander Block 
53807069830aSAlexander Block 	left_path = btrfs_alloc_path();
53817069830aSAlexander Block 	if (!left_path) {
53827069830aSAlexander Block 		ret = -ENOMEM;
53837069830aSAlexander Block 		goto out;
53847069830aSAlexander Block 	}
53857069830aSAlexander Block 	right_path = btrfs_alloc_path();
53867069830aSAlexander Block 	if (!right_path) {
53877069830aSAlexander Block 		ret = -ENOMEM;
53887069830aSAlexander Block 		goto out;
53897069830aSAlexander Block 	}
53907069830aSAlexander Block 
5391752ade68SMichal Hocko 	tmp_buf = kvmalloc(fs_info->nodesize, GFP_KERNEL);
53927069830aSAlexander Block 	if (!tmp_buf) {
53937069830aSAlexander Block 		ret = -ENOMEM;
53947069830aSAlexander Block 		goto out;
53957069830aSAlexander Block 	}
53967069830aSAlexander Block 
53977069830aSAlexander Block 	left_path->search_commit_root = 1;
53987069830aSAlexander Block 	left_path->skip_locking = 1;
53997069830aSAlexander Block 	right_path->search_commit_root = 1;
54007069830aSAlexander Block 	right_path->skip_locking = 1;
54017069830aSAlexander Block 
54027069830aSAlexander Block 	/*
54037069830aSAlexander Block 	 * Strategy: Go to the first items of both trees. Then do
54047069830aSAlexander Block 	 *
54057069830aSAlexander Block 	 * If both trees are at level 0
54067069830aSAlexander Block 	 *   Compare keys of current items
54077069830aSAlexander Block 	 *     If left < right treat left item as new, advance left tree
54087069830aSAlexander Block 	 *       and repeat
54097069830aSAlexander Block 	 *     If left > right treat right item as deleted, advance right tree
54107069830aSAlexander Block 	 *       and repeat
54117069830aSAlexander Block 	 *     If left == right do deep compare of items, treat as changed if
54127069830aSAlexander Block 	 *       needed, advance both trees and repeat
54137069830aSAlexander Block 	 * If both trees are at the same level but not at level 0
54147069830aSAlexander Block 	 *   Compare keys of current nodes/leafs
54157069830aSAlexander Block 	 *     If left < right advance left tree and repeat
54167069830aSAlexander Block 	 *     If left > right advance right tree and repeat
54177069830aSAlexander Block 	 *     If left == right compare blockptrs of the next nodes/leafs
54187069830aSAlexander Block 	 *       If they match advance both trees but stay at the same level
54197069830aSAlexander Block 	 *         and repeat
54207069830aSAlexander Block 	 *       If they don't match advance both trees while allowing to go
54217069830aSAlexander Block 	 *         deeper and repeat
54227069830aSAlexander Block 	 * If tree levels are different
54237069830aSAlexander Block 	 *   Advance the tree that needs it and repeat
54247069830aSAlexander Block 	 *
54257069830aSAlexander Block 	 * Advancing a tree means:
54267069830aSAlexander Block 	 *   If we are at level 0, try to go to the next slot. If that's not
54277069830aSAlexander Block 	 *   possible, go one level up and repeat. Stop when we found a level
54287069830aSAlexander Block 	 *   where we could go to the next slot. We may at this point be on a
54297069830aSAlexander Block 	 *   node or a leaf.
54307069830aSAlexander Block 	 *
54317069830aSAlexander Block 	 *   If we are not at level 0 and not on shared tree blocks, go one
54327069830aSAlexander Block 	 *   level deeper.
54337069830aSAlexander Block 	 *
54347069830aSAlexander Block 	 *   If we are not at level 0 and on shared tree blocks, go one slot to
54357069830aSAlexander Block 	 *   the right if possible or go up and right.
54367069830aSAlexander Block 	 */
54377069830aSAlexander Block 
54380b246afaSJeff Mahoney 	down_read(&fs_info->commit_root_sem);
54397069830aSAlexander Block 	left_level = btrfs_header_level(left_root->commit_root);
54407069830aSAlexander Block 	left_root_level = left_level;
54417069830aSAlexander Block 	left_path->nodes[left_level] = left_root->commit_root;
54427069830aSAlexander Block 	extent_buffer_get(left_path->nodes[left_level]);
54437069830aSAlexander Block 
54447069830aSAlexander Block 	right_level = btrfs_header_level(right_root->commit_root);
54457069830aSAlexander Block 	right_root_level = right_level;
54467069830aSAlexander Block 	right_path->nodes[right_level] = right_root->commit_root;
54477069830aSAlexander Block 	extent_buffer_get(right_path->nodes[right_level]);
54480b246afaSJeff Mahoney 	up_read(&fs_info->commit_root_sem);
54497069830aSAlexander Block 
54507069830aSAlexander Block 	if (left_level == 0)
54517069830aSAlexander Block 		btrfs_item_key_to_cpu(left_path->nodes[left_level],
54527069830aSAlexander Block 				&left_key, left_path->slots[left_level]);
54537069830aSAlexander Block 	else
54547069830aSAlexander Block 		btrfs_node_key_to_cpu(left_path->nodes[left_level],
54557069830aSAlexander Block 				&left_key, left_path->slots[left_level]);
54567069830aSAlexander Block 	if (right_level == 0)
54577069830aSAlexander Block 		btrfs_item_key_to_cpu(right_path->nodes[right_level],
54587069830aSAlexander Block 				&right_key, right_path->slots[right_level]);
54597069830aSAlexander Block 	else
54607069830aSAlexander Block 		btrfs_node_key_to_cpu(right_path->nodes[right_level],
54617069830aSAlexander Block 				&right_key, right_path->slots[right_level]);
54627069830aSAlexander Block 
54637069830aSAlexander Block 	left_end_reached = right_end_reached = 0;
54647069830aSAlexander Block 	advance_left = advance_right = 0;
54657069830aSAlexander Block 
54667069830aSAlexander Block 	while (1) {
54677069830aSAlexander Block 		if (advance_left && !left_end_reached) {
54682ff7e61eSJeff Mahoney 			ret = tree_advance(fs_info, left_path, &left_level,
54697069830aSAlexander Block 					left_root_level,
54707069830aSAlexander Block 					advance_left != ADVANCE_ONLY_NEXT,
54717069830aSAlexander Block 					&left_key);
5472fb770ae4SLiu Bo 			if (ret == -1)
54737069830aSAlexander Block 				left_end_reached = ADVANCE;
5474fb770ae4SLiu Bo 			else if (ret < 0)
5475fb770ae4SLiu Bo 				goto out;
54767069830aSAlexander Block 			advance_left = 0;
54777069830aSAlexander Block 		}
54787069830aSAlexander Block 		if (advance_right && !right_end_reached) {
54792ff7e61eSJeff Mahoney 			ret = tree_advance(fs_info, right_path, &right_level,
54807069830aSAlexander Block 					right_root_level,
54817069830aSAlexander Block 					advance_right != ADVANCE_ONLY_NEXT,
54827069830aSAlexander Block 					&right_key);
5483fb770ae4SLiu Bo 			if (ret == -1)
54847069830aSAlexander Block 				right_end_reached = ADVANCE;
5485fb770ae4SLiu Bo 			else if (ret < 0)
5486fb770ae4SLiu Bo 				goto out;
54877069830aSAlexander Block 			advance_right = 0;
54887069830aSAlexander Block 		}
54897069830aSAlexander Block 
54907069830aSAlexander Block 		if (left_end_reached && right_end_reached) {
54917069830aSAlexander Block 			ret = 0;
54927069830aSAlexander Block 			goto out;
54937069830aSAlexander Block 		} else if (left_end_reached) {
54947069830aSAlexander Block 			if (right_level == 0) {
5495ee8c494fSNikolay Borisov 				ret = changed_cb(left_path, right_path,
54967069830aSAlexander Block 						&right_key,
54977069830aSAlexander Block 						BTRFS_COMPARE_TREE_DELETED,
54987069830aSAlexander Block 						ctx);
54997069830aSAlexander Block 				if (ret < 0)
55007069830aSAlexander Block 					goto out;
55017069830aSAlexander Block 			}
55027069830aSAlexander Block 			advance_right = ADVANCE;
55037069830aSAlexander Block 			continue;
55047069830aSAlexander Block 		} else if (right_end_reached) {
55057069830aSAlexander Block 			if (left_level == 0) {
5506ee8c494fSNikolay Borisov 				ret = changed_cb(left_path, right_path,
55077069830aSAlexander Block 						&left_key,
55087069830aSAlexander Block 						BTRFS_COMPARE_TREE_NEW,
55097069830aSAlexander Block 						ctx);
55107069830aSAlexander Block 				if (ret < 0)
55117069830aSAlexander Block 					goto out;
55127069830aSAlexander Block 			}
55137069830aSAlexander Block 			advance_left = ADVANCE;
55147069830aSAlexander Block 			continue;
55157069830aSAlexander Block 		}
55167069830aSAlexander Block 
55177069830aSAlexander Block 		if (left_level == 0 && right_level == 0) {
55187069830aSAlexander Block 			cmp = btrfs_comp_cpu_keys(&left_key, &right_key);
55197069830aSAlexander Block 			if (cmp < 0) {
5520ee8c494fSNikolay Borisov 				ret = changed_cb(left_path, right_path,
55217069830aSAlexander Block 						&left_key,
55227069830aSAlexander Block 						BTRFS_COMPARE_TREE_NEW,
55237069830aSAlexander Block 						ctx);
55247069830aSAlexander Block 				if (ret < 0)
55257069830aSAlexander Block 					goto out;
55267069830aSAlexander Block 				advance_left = ADVANCE;
55277069830aSAlexander Block 			} else if (cmp > 0) {
5528ee8c494fSNikolay Borisov 				ret = changed_cb(left_path, right_path,
55297069830aSAlexander Block 						&right_key,
55307069830aSAlexander Block 						BTRFS_COMPARE_TREE_DELETED,
55317069830aSAlexander Block 						ctx);
55327069830aSAlexander Block 				if (ret < 0)
55337069830aSAlexander Block 					goto out;
55347069830aSAlexander Block 				advance_right = ADVANCE;
55357069830aSAlexander Block 			} else {
5536b99d9a6aSFabian Frederick 				enum btrfs_compare_tree_result result;
5537ba5e8f2eSJosef Bacik 
553874dd17fbSChris Mason 				WARN_ON(!extent_buffer_uptodate(left_path->nodes[0]));
55392ff7e61eSJeff Mahoney 				ret = tree_compare_item(left_path, right_path,
55402ff7e61eSJeff Mahoney 							tmp_buf);
5541ba5e8f2eSJosef Bacik 				if (ret)
5542b99d9a6aSFabian Frederick 					result = BTRFS_COMPARE_TREE_CHANGED;
5543ba5e8f2eSJosef Bacik 				else
5544b99d9a6aSFabian Frederick 					result = BTRFS_COMPARE_TREE_SAME;
5545ee8c494fSNikolay Borisov 				ret = changed_cb(left_path, right_path,
5546b99d9a6aSFabian Frederick 						 &left_key, result, ctx);
55477069830aSAlexander Block 				if (ret < 0)
55487069830aSAlexander Block 					goto out;
55497069830aSAlexander Block 				advance_left = ADVANCE;
55507069830aSAlexander Block 				advance_right = ADVANCE;
55517069830aSAlexander Block 			}
55527069830aSAlexander Block 		} else if (left_level == right_level) {
55537069830aSAlexander Block 			cmp = btrfs_comp_cpu_keys(&left_key, &right_key);
55547069830aSAlexander Block 			if (cmp < 0) {
55557069830aSAlexander Block 				advance_left = ADVANCE;
55567069830aSAlexander Block 			} else if (cmp > 0) {
55577069830aSAlexander Block 				advance_right = ADVANCE;
55587069830aSAlexander Block 			} else {
55597069830aSAlexander Block 				left_blockptr = btrfs_node_blockptr(
55607069830aSAlexander Block 						left_path->nodes[left_level],
55617069830aSAlexander Block 						left_path->slots[left_level]);
55627069830aSAlexander Block 				right_blockptr = btrfs_node_blockptr(
55637069830aSAlexander Block 						right_path->nodes[right_level],
55647069830aSAlexander Block 						right_path->slots[right_level]);
55656baa4293SFilipe Manana 				left_gen = btrfs_node_ptr_generation(
55666baa4293SFilipe Manana 						left_path->nodes[left_level],
55676baa4293SFilipe Manana 						left_path->slots[left_level]);
55686baa4293SFilipe Manana 				right_gen = btrfs_node_ptr_generation(
55696baa4293SFilipe Manana 						right_path->nodes[right_level],
55706baa4293SFilipe Manana 						right_path->slots[right_level]);
55716baa4293SFilipe Manana 				if (left_blockptr == right_blockptr &&
55726baa4293SFilipe Manana 				    left_gen == right_gen) {
55737069830aSAlexander Block 					/*
55747069830aSAlexander Block 					 * As we're on a shared block, don't
55757069830aSAlexander Block 					 * allow to go deeper.
55767069830aSAlexander Block 					 */
55777069830aSAlexander Block 					advance_left = ADVANCE_ONLY_NEXT;
55787069830aSAlexander Block 					advance_right = ADVANCE_ONLY_NEXT;
55797069830aSAlexander Block 				} else {
55807069830aSAlexander Block 					advance_left = ADVANCE;
55817069830aSAlexander Block 					advance_right = ADVANCE;
55827069830aSAlexander Block 				}
55837069830aSAlexander Block 			}
55847069830aSAlexander Block 		} else if (left_level < right_level) {
55857069830aSAlexander Block 			advance_right = ADVANCE;
55867069830aSAlexander Block 		} else {
55877069830aSAlexander Block 			advance_left = ADVANCE;
55887069830aSAlexander Block 		}
55897069830aSAlexander Block 	}
55907069830aSAlexander Block 
55917069830aSAlexander Block out:
55927069830aSAlexander Block 	btrfs_free_path(left_path);
55937069830aSAlexander Block 	btrfs_free_path(right_path);
55948f282f71SDavid Sterba 	kvfree(tmp_buf);
55957069830aSAlexander Block 	return ret;
55967069830aSAlexander Block }
55977069830aSAlexander Block 
55983f157a2fSChris Mason /*
55993f157a2fSChris Mason  * this is similar to btrfs_next_leaf, but does not try to preserve
56003f157a2fSChris Mason  * and fixup the path.  It looks for and returns the next key in the
5601de78b51aSEric Sandeen  * tree based on the current path and the min_trans parameters.
56023f157a2fSChris Mason  *
56033f157a2fSChris Mason  * 0 is returned if another key is found, < 0 if there are any errors
56043f157a2fSChris Mason  * and 1 is returned if there are no higher keys in the tree
56053f157a2fSChris Mason  *
56063f157a2fSChris Mason  * path->keep_locks should be set to 1 on the search made before
56073f157a2fSChris Mason  * calling this function.
56083f157a2fSChris Mason  */
5609e7a84565SChris Mason int btrfs_find_next_key(struct btrfs_root *root, struct btrfs_path *path,
5610de78b51aSEric Sandeen 			struct btrfs_key *key, int level, u64 min_trans)
5611e7a84565SChris Mason {
5612e7a84565SChris Mason 	int slot;
5613e7a84565SChris Mason 	struct extent_buffer *c;
5614e7a84565SChris Mason 
5615934d375bSChris Mason 	WARN_ON(!path->keep_locks);
5616e7a84565SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
5617e7a84565SChris Mason 		if (!path->nodes[level])
5618e7a84565SChris Mason 			return 1;
5619e7a84565SChris Mason 
5620e7a84565SChris Mason 		slot = path->slots[level] + 1;
5621e7a84565SChris Mason 		c = path->nodes[level];
56223f157a2fSChris Mason next:
5623e7a84565SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
562433c66f43SYan Zheng 			int ret;
562533c66f43SYan Zheng 			int orig_lowest;
562633c66f43SYan Zheng 			struct btrfs_key cur_key;
562733c66f43SYan Zheng 			if (level + 1 >= BTRFS_MAX_LEVEL ||
562833c66f43SYan Zheng 			    !path->nodes[level + 1])
5629e7a84565SChris Mason 				return 1;
563033c66f43SYan Zheng 
563133c66f43SYan Zheng 			if (path->locks[level + 1]) {
563233c66f43SYan Zheng 				level++;
5633e7a84565SChris Mason 				continue;
5634e7a84565SChris Mason 			}
563533c66f43SYan Zheng 
563633c66f43SYan Zheng 			slot = btrfs_header_nritems(c) - 1;
563733c66f43SYan Zheng 			if (level == 0)
563833c66f43SYan Zheng 				btrfs_item_key_to_cpu(c, &cur_key, slot);
563933c66f43SYan Zheng 			else
564033c66f43SYan Zheng 				btrfs_node_key_to_cpu(c, &cur_key, slot);
564133c66f43SYan Zheng 
564233c66f43SYan Zheng 			orig_lowest = path->lowest_level;
5643b3b4aa74SDavid Sterba 			btrfs_release_path(path);
564433c66f43SYan Zheng 			path->lowest_level = level;
564533c66f43SYan Zheng 			ret = btrfs_search_slot(NULL, root, &cur_key, path,
564633c66f43SYan Zheng 						0, 0);
564733c66f43SYan Zheng 			path->lowest_level = orig_lowest;
564833c66f43SYan Zheng 			if (ret < 0)
564933c66f43SYan Zheng 				return ret;
565033c66f43SYan Zheng 
565133c66f43SYan Zheng 			c = path->nodes[level];
565233c66f43SYan Zheng 			slot = path->slots[level];
565333c66f43SYan Zheng 			if (ret == 0)
565433c66f43SYan Zheng 				slot++;
565533c66f43SYan Zheng 			goto next;
565633c66f43SYan Zheng 		}
565733c66f43SYan Zheng 
5658e7a84565SChris Mason 		if (level == 0)
5659e7a84565SChris Mason 			btrfs_item_key_to_cpu(c, key, slot);
56603f157a2fSChris Mason 		else {
56613f157a2fSChris Mason 			u64 gen = btrfs_node_ptr_generation(c, slot);
56623f157a2fSChris Mason 
56633f157a2fSChris Mason 			if (gen < min_trans) {
56643f157a2fSChris Mason 				slot++;
56653f157a2fSChris Mason 				goto next;
56663f157a2fSChris Mason 			}
5667e7a84565SChris Mason 			btrfs_node_key_to_cpu(c, key, slot);
56683f157a2fSChris Mason 		}
5669e7a84565SChris Mason 		return 0;
5670e7a84565SChris Mason 	}
5671e7a84565SChris Mason 	return 1;
5672e7a84565SChris Mason }
5673e7a84565SChris Mason 
56747bb86316SChris Mason /*
5675925baeddSChris Mason  * search the tree again to find a leaf with greater keys
56760f70abe2SChris Mason  * returns 0 if it found something or 1 if there are no greater leaves.
56770f70abe2SChris Mason  * returns < 0 on io errors.
567897571fd0SChris Mason  */
5679234b63a0SChris Mason int btrfs_next_leaf(struct btrfs_root *root, struct btrfs_path *path)
5680d97e63b6SChris Mason {
56813d7806ecSJan Schmidt 	return btrfs_next_old_leaf(root, path, 0);
56823d7806ecSJan Schmidt }
56833d7806ecSJan Schmidt 
56843d7806ecSJan Schmidt int btrfs_next_old_leaf(struct btrfs_root *root, struct btrfs_path *path,
56853d7806ecSJan Schmidt 			u64 time_seq)
56863d7806ecSJan Schmidt {
5687d97e63b6SChris Mason 	int slot;
56888e73f275SChris Mason 	int level;
56895f39d397SChris Mason 	struct extent_buffer *c;
56908e73f275SChris Mason 	struct extent_buffer *next;
5691925baeddSChris Mason 	struct btrfs_key key;
5692925baeddSChris Mason 	u32 nritems;
5693925baeddSChris Mason 	int ret;
56948e73f275SChris Mason 	int old_spinning = path->leave_spinning;
5695bd681513SChris Mason 	int next_rw_lock = 0;
5696925baeddSChris Mason 
5697925baeddSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
5698d397712bSChris Mason 	if (nritems == 0)
5699925baeddSChris Mason 		return 1;
5700925baeddSChris Mason 
57018e73f275SChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, nritems - 1);
57028e73f275SChris Mason again:
57038e73f275SChris Mason 	level = 1;
57048e73f275SChris Mason 	next = NULL;
5705bd681513SChris Mason 	next_rw_lock = 0;
5706b3b4aa74SDavid Sterba 	btrfs_release_path(path);
57078e73f275SChris Mason 
5708a2135011SChris Mason 	path->keep_locks = 1;
57098e73f275SChris Mason 	path->leave_spinning = 1;
57108e73f275SChris Mason 
57113d7806ecSJan Schmidt 	if (time_seq)
57123d7806ecSJan Schmidt 		ret = btrfs_search_old_slot(root, &key, path, time_seq);
57133d7806ecSJan Schmidt 	else
5714925baeddSChris Mason 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5715925baeddSChris Mason 	path->keep_locks = 0;
5716925baeddSChris Mason 
5717925baeddSChris Mason 	if (ret < 0)
5718925baeddSChris Mason 		return ret;
5719925baeddSChris Mason 
5720a2135011SChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
5721168fd7d2SChris Mason 	/*
5722168fd7d2SChris Mason 	 * by releasing the path above we dropped all our locks.  A balance
5723168fd7d2SChris Mason 	 * could have added more items next to the key that used to be
5724168fd7d2SChris Mason 	 * at the very end of the block.  So, check again here and
5725168fd7d2SChris Mason 	 * advance the path if there are now more items available.
5726168fd7d2SChris Mason 	 */
5727a2135011SChris Mason 	if (nritems > 0 && path->slots[0] < nritems - 1) {
5728e457afecSYan Zheng 		if (ret == 0)
5729168fd7d2SChris Mason 			path->slots[0]++;
57308e73f275SChris Mason 		ret = 0;
5731925baeddSChris Mason 		goto done;
5732925baeddSChris Mason 	}
57330b43e04fSLiu Bo 	/*
57340b43e04fSLiu Bo 	 * So the above check misses one case:
57350b43e04fSLiu Bo 	 * - after releasing the path above, someone has removed the item that
57360b43e04fSLiu Bo 	 *   used to be at the very end of the block, and balance between leafs
57370b43e04fSLiu Bo 	 *   gets another one with bigger key.offset to replace it.
57380b43e04fSLiu Bo 	 *
57390b43e04fSLiu Bo 	 * This one should be returned as well, or we can get leaf corruption
57400b43e04fSLiu Bo 	 * later(esp. in __btrfs_drop_extents()).
57410b43e04fSLiu Bo 	 *
57420b43e04fSLiu Bo 	 * And a bit more explanation about this check,
57430b43e04fSLiu Bo 	 * with ret > 0, the key isn't found, the path points to the slot
57440b43e04fSLiu Bo 	 * where it should be inserted, so the path->slots[0] item must be the
57450b43e04fSLiu Bo 	 * bigger one.
57460b43e04fSLiu Bo 	 */
57470b43e04fSLiu Bo 	if (nritems > 0 && ret > 0 && path->slots[0] == nritems - 1) {
57480b43e04fSLiu Bo 		ret = 0;
57490b43e04fSLiu Bo 		goto done;
57500b43e04fSLiu Bo 	}
5751d97e63b6SChris Mason 
5752234b63a0SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
57538e73f275SChris Mason 		if (!path->nodes[level]) {
57548e73f275SChris Mason 			ret = 1;
57558e73f275SChris Mason 			goto done;
57568e73f275SChris Mason 		}
57575f39d397SChris Mason 
5758d97e63b6SChris Mason 		slot = path->slots[level] + 1;
5759d97e63b6SChris Mason 		c = path->nodes[level];
57605f39d397SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
5761d97e63b6SChris Mason 			level++;
57628e73f275SChris Mason 			if (level == BTRFS_MAX_LEVEL) {
57638e73f275SChris Mason 				ret = 1;
57648e73f275SChris Mason 				goto done;
57658e73f275SChris Mason 			}
5766d97e63b6SChris Mason 			continue;
5767d97e63b6SChris Mason 		}
57685f39d397SChris Mason 
5769925baeddSChris Mason 		if (next) {
5770bd681513SChris Mason 			btrfs_tree_unlock_rw(next, next_rw_lock);
57715f39d397SChris Mason 			free_extent_buffer(next);
5772925baeddSChris Mason 		}
57735f39d397SChris Mason 
57748e73f275SChris Mason 		next = c;
5775bd681513SChris Mason 		next_rw_lock = path->locks[level];
5776d07b8528SLiu Bo 		ret = read_block_for_search(root, path, &next, level,
5777cda79c54SDavid Sterba 					    slot, &key);
57788e73f275SChris Mason 		if (ret == -EAGAIN)
57798e73f275SChris Mason 			goto again;
57805f39d397SChris Mason 
578176a05b35SChris Mason 		if (ret < 0) {
5782b3b4aa74SDavid Sterba 			btrfs_release_path(path);
578376a05b35SChris Mason 			goto done;
578476a05b35SChris Mason 		}
578576a05b35SChris Mason 
57865cd57b2cSChris Mason 		if (!path->skip_locking) {
5787bd681513SChris Mason 			ret = btrfs_try_tree_read_lock(next);
5788d42244a0SJan Schmidt 			if (!ret && time_seq) {
5789d42244a0SJan Schmidt 				/*
5790d42244a0SJan Schmidt 				 * If we don't get the lock, we may be racing
5791d42244a0SJan Schmidt 				 * with push_leaf_left, holding that lock while
5792d42244a0SJan Schmidt 				 * itself waiting for the leaf we've currently
5793d42244a0SJan Schmidt 				 * locked. To solve this situation, we give up
5794d42244a0SJan Schmidt 				 * on our lock and cycle.
5795d42244a0SJan Schmidt 				 */
5796cf538830SJan Schmidt 				free_extent_buffer(next);
5797d42244a0SJan Schmidt 				btrfs_release_path(path);
5798d42244a0SJan Schmidt 				cond_resched();
5799d42244a0SJan Schmidt 				goto again;
5800d42244a0SJan Schmidt 			}
58018e73f275SChris Mason 			if (!ret) {
58028e73f275SChris Mason 				btrfs_set_path_blocking(path);
5803bd681513SChris Mason 				btrfs_tree_read_lock(next);
5804bd681513SChris Mason 				btrfs_clear_path_blocking(path, next,
5805bd681513SChris Mason 							  BTRFS_READ_LOCK);
58068e73f275SChris Mason 			}
5807bd681513SChris Mason 			next_rw_lock = BTRFS_READ_LOCK;
5808bd681513SChris Mason 		}
5809d97e63b6SChris Mason 		break;
5810d97e63b6SChris Mason 	}
5811d97e63b6SChris Mason 	path->slots[level] = slot;
5812d97e63b6SChris Mason 	while (1) {
5813d97e63b6SChris Mason 		level--;
5814d97e63b6SChris Mason 		c = path->nodes[level];
5815925baeddSChris Mason 		if (path->locks[level])
5816bd681513SChris Mason 			btrfs_tree_unlock_rw(c, path->locks[level]);
58178e73f275SChris Mason 
58185f39d397SChris Mason 		free_extent_buffer(c);
5819d97e63b6SChris Mason 		path->nodes[level] = next;
5820d97e63b6SChris Mason 		path->slots[level] = 0;
5821a74a4b97SChris Mason 		if (!path->skip_locking)
5822bd681513SChris Mason 			path->locks[level] = next_rw_lock;
5823d97e63b6SChris Mason 		if (!level)
5824d97e63b6SChris Mason 			break;
5825b4ce94deSChris Mason 
5826d07b8528SLiu Bo 		ret = read_block_for_search(root, path, &next, level,
5827cda79c54SDavid Sterba 					    0, &key);
58288e73f275SChris Mason 		if (ret == -EAGAIN)
58298e73f275SChris Mason 			goto again;
58308e73f275SChris Mason 
583176a05b35SChris Mason 		if (ret < 0) {
5832b3b4aa74SDavid Sterba 			btrfs_release_path(path);
583376a05b35SChris Mason 			goto done;
583476a05b35SChris Mason 		}
583576a05b35SChris Mason 
58365cd57b2cSChris Mason 		if (!path->skip_locking) {
5837bd681513SChris Mason 			ret = btrfs_try_tree_read_lock(next);
58388e73f275SChris Mason 			if (!ret) {
58398e73f275SChris Mason 				btrfs_set_path_blocking(path);
5840bd681513SChris Mason 				btrfs_tree_read_lock(next);
5841bd681513SChris Mason 				btrfs_clear_path_blocking(path, next,
5842bd681513SChris Mason 							  BTRFS_READ_LOCK);
58438e73f275SChris Mason 			}
5844bd681513SChris Mason 			next_rw_lock = BTRFS_READ_LOCK;
5845bd681513SChris Mason 		}
5846d97e63b6SChris Mason 	}
58478e73f275SChris Mason 	ret = 0;
5848925baeddSChris Mason done:
5849f7c79f30SChris Mason 	unlock_up(path, 0, 1, 0, NULL);
58508e73f275SChris Mason 	path->leave_spinning = old_spinning;
58518e73f275SChris Mason 	if (!old_spinning)
58528e73f275SChris Mason 		btrfs_set_path_blocking(path);
58538e73f275SChris Mason 
58548e73f275SChris Mason 	return ret;
5855d97e63b6SChris Mason }
58560b86a832SChris Mason 
58573f157a2fSChris Mason /*
58583f157a2fSChris Mason  * this uses btrfs_prev_leaf to walk backwards in the tree, and keeps
58593f157a2fSChris Mason  * searching until it gets past min_objectid or finds an item of 'type'
58603f157a2fSChris Mason  *
58613f157a2fSChris Mason  * returns 0 if something is found, 1 if nothing was found and < 0 on error
58623f157a2fSChris Mason  */
58630b86a832SChris Mason int btrfs_previous_item(struct btrfs_root *root,
58640b86a832SChris Mason 			struct btrfs_path *path, u64 min_objectid,
58650b86a832SChris Mason 			int type)
58660b86a832SChris Mason {
58670b86a832SChris Mason 	struct btrfs_key found_key;
58680b86a832SChris Mason 	struct extent_buffer *leaf;
5869e02119d5SChris Mason 	u32 nritems;
58700b86a832SChris Mason 	int ret;
58710b86a832SChris Mason 
58720b86a832SChris Mason 	while (1) {
58730b86a832SChris Mason 		if (path->slots[0] == 0) {
5874b4ce94deSChris Mason 			btrfs_set_path_blocking(path);
58750b86a832SChris Mason 			ret = btrfs_prev_leaf(root, path);
58760b86a832SChris Mason 			if (ret != 0)
58770b86a832SChris Mason 				return ret;
58780b86a832SChris Mason 		} else {
58790b86a832SChris Mason 			path->slots[0]--;
58800b86a832SChris Mason 		}
58810b86a832SChris Mason 		leaf = path->nodes[0];
5882e02119d5SChris Mason 		nritems = btrfs_header_nritems(leaf);
5883e02119d5SChris Mason 		if (nritems == 0)
5884e02119d5SChris Mason 			return 1;
5885e02119d5SChris Mason 		if (path->slots[0] == nritems)
5886e02119d5SChris Mason 			path->slots[0]--;
5887e02119d5SChris Mason 
58880b86a832SChris Mason 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5889e02119d5SChris Mason 		if (found_key.objectid < min_objectid)
5890e02119d5SChris Mason 			break;
58910a4eefbbSYan Zheng 		if (found_key.type == type)
58920a4eefbbSYan Zheng 			return 0;
5893e02119d5SChris Mason 		if (found_key.objectid == min_objectid &&
5894e02119d5SChris Mason 		    found_key.type < type)
5895e02119d5SChris Mason 			break;
58960b86a832SChris Mason 	}
58970b86a832SChris Mason 	return 1;
58980b86a832SChris Mason }
5899ade2e0b3SWang Shilong 
5900ade2e0b3SWang Shilong /*
5901ade2e0b3SWang Shilong  * search in extent tree to find a previous Metadata/Data extent item with
5902ade2e0b3SWang Shilong  * min objecitd.
5903ade2e0b3SWang Shilong  *
5904ade2e0b3SWang Shilong  * returns 0 if something is found, 1 if nothing was found and < 0 on error
5905ade2e0b3SWang Shilong  */
5906ade2e0b3SWang Shilong int btrfs_previous_extent_item(struct btrfs_root *root,
5907ade2e0b3SWang Shilong 			struct btrfs_path *path, u64 min_objectid)
5908ade2e0b3SWang Shilong {
5909ade2e0b3SWang Shilong 	struct btrfs_key found_key;
5910ade2e0b3SWang Shilong 	struct extent_buffer *leaf;
5911ade2e0b3SWang Shilong 	u32 nritems;
5912ade2e0b3SWang Shilong 	int ret;
5913ade2e0b3SWang Shilong 
5914ade2e0b3SWang Shilong 	while (1) {
5915ade2e0b3SWang Shilong 		if (path->slots[0] == 0) {
5916ade2e0b3SWang Shilong 			btrfs_set_path_blocking(path);
5917ade2e0b3SWang Shilong 			ret = btrfs_prev_leaf(root, path);
5918ade2e0b3SWang Shilong 			if (ret != 0)
5919ade2e0b3SWang Shilong 				return ret;
5920ade2e0b3SWang Shilong 		} else {
5921ade2e0b3SWang Shilong 			path->slots[0]--;
5922ade2e0b3SWang Shilong 		}
5923ade2e0b3SWang Shilong 		leaf = path->nodes[0];
5924ade2e0b3SWang Shilong 		nritems = btrfs_header_nritems(leaf);
5925ade2e0b3SWang Shilong 		if (nritems == 0)
5926ade2e0b3SWang Shilong 			return 1;
5927ade2e0b3SWang Shilong 		if (path->slots[0] == nritems)
5928ade2e0b3SWang Shilong 			path->slots[0]--;
5929ade2e0b3SWang Shilong 
5930ade2e0b3SWang Shilong 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5931ade2e0b3SWang Shilong 		if (found_key.objectid < min_objectid)
5932ade2e0b3SWang Shilong 			break;
5933ade2e0b3SWang Shilong 		if (found_key.type == BTRFS_EXTENT_ITEM_KEY ||
5934ade2e0b3SWang Shilong 		    found_key.type == BTRFS_METADATA_ITEM_KEY)
5935ade2e0b3SWang Shilong 			return 0;
5936ade2e0b3SWang Shilong 		if (found_key.objectid == min_objectid &&
5937ade2e0b3SWang Shilong 		    found_key.type < BTRFS_EXTENT_ITEM_KEY)
5938ade2e0b3SWang Shilong 			break;
5939ade2e0b3SWang Shilong 	}
5940ade2e0b3SWang Shilong 	return 1;
5941ade2e0b3SWang Shilong }
5942