xref: /openbmc/linux/fs/btrfs/ctree.c (revision 19956c7e94a7a58d6df8c4db5ae62f9109a7c663)
16cbd5570SChris Mason /*
2d352ac68SChris Mason  * Copyright (C) 2007,2008 Oracle.  All rights reserved.
36cbd5570SChris Mason  *
46cbd5570SChris Mason  * This program is free software; you can redistribute it and/or
56cbd5570SChris Mason  * modify it under the terms of the GNU General Public
66cbd5570SChris Mason  * License v2 as published by the Free Software Foundation.
76cbd5570SChris Mason  *
86cbd5570SChris Mason  * This program is distributed in the hope that it will be useful,
96cbd5570SChris Mason  * but WITHOUT ANY WARRANTY; without even the implied warranty of
106cbd5570SChris Mason  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
116cbd5570SChris Mason  * General Public License for more details.
126cbd5570SChris Mason  *
136cbd5570SChris Mason  * You should have received a copy of the GNU General Public
146cbd5570SChris Mason  * License along with this program; if not, write to the
156cbd5570SChris Mason  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
166cbd5570SChris Mason  * Boston, MA 021110-1307, USA.
176cbd5570SChris Mason  */
186cbd5570SChris Mason 
19a6b6e75eSChris Mason #include <linux/sched.h>
205a0e3ad6STejun Heo #include <linux/slab.h>
21bd989ba3SJan Schmidt #include <linux/rbtree.h>
22eb60ceacSChris Mason #include "ctree.h"
23eb60ceacSChris Mason #include "disk-io.h"
247f5c1516SChris Mason #include "transaction.h"
255f39d397SChris Mason #include "print-tree.h"
26925baeddSChris Mason #include "locking.h"
279a8dd150SChris Mason 
28e089f05cSChris Mason static int split_node(struct btrfs_trans_handle *trans, struct btrfs_root
29e089f05cSChris Mason 		      *root, struct btrfs_path *path, int level);
30e089f05cSChris Mason static int split_leaf(struct btrfs_trans_handle *trans, struct btrfs_root
31d4dbff95SChris Mason 		      *root, struct btrfs_key *ins_key,
32cc0c5538SChris Mason 		      struct btrfs_path *path, int data_size, int extend);
335f39d397SChris Mason static int push_node_left(struct btrfs_trans_handle *trans,
345f39d397SChris Mason 			  struct btrfs_root *root, struct extent_buffer *dst,
35971a1f66SChris Mason 			  struct extent_buffer *src, int empty);
365f39d397SChris Mason static int balance_node_right(struct btrfs_trans_handle *trans,
375f39d397SChris Mason 			      struct btrfs_root *root,
385f39d397SChris Mason 			      struct extent_buffer *dst_buf,
395f39d397SChris Mason 			      struct extent_buffer *src_buf);
40143bede5SJeff Mahoney static void del_ptr(struct btrfs_trans_handle *trans, struct btrfs_root *root,
41f3ea38daSJan Schmidt 		    struct btrfs_path *path, int level, int slot,
42f3ea38daSJan Schmidt 		    int tree_mod_log);
43f230475eSJan Schmidt static void tree_mod_log_free_eb(struct btrfs_fs_info *fs_info,
44f230475eSJan Schmidt 				 struct extent_buffer *eb);
45f230475eSJan Schmidt struct extent_buffer *read_old_tree_block(struct btrfs_root *root, u64 bytenr,
46f230475eSJan Schmidt 					  u32 blocksize, u64 parent_transid,
47f230475eSJan Schmidt 					  u64 time_seq);
48f230475eSJan Schmidt struct extent_buffer *btrfs_find_old_tree_block(struct btrfs_root *root,
49f230475eSJan Schmidt 						u64 bytenr, u32 blocksize,
50f230475eSJan Schmidt 						u64 time_seq);
51d97e63b6SChris Mason 
522c90e5d6SChris Mason struct btrfs_path *btrfs_alloc_path(void)
532c90e5d6SChris Mason {
54df24a2b9SChris Mason 	struct btrfs_path *path;
55e00f7308SJeff Mahoney 	path = kmem_cache_zalloc(btrfs_path_cachep, GFP_NOFS);
56df24a2b9SChris Mason 	return path;
572c90e5d6SChris Mason }
582c90e5d6SChris Mason 
59b4ce94deSChris Mason /*
60b4ce94deSChris Mason  * set all locked nodes in the path to blocking locks.  This should
61b4ce94deSChris Mason  * be done before scheduling
62b4ce94deSChris Mason  */
63b4ce94deSChris Mason noinline void btrfs_set_path_blocking(struct btrfs_path *p)
64b4ce94deSChris Mason {
65b4ce94deSChris Mason 	int i;
66b4ce94deSChris Mason 	for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
67bd681513SChris Mason 		if (!p->nodes[i] || !p->locks[i])
68bd681513SChris Mason 			continue;
69bd681513SChris Mason 		btrfs_set_lock_blocking_rw(p->nodes[i], p->locks[i]);
70bd681513SChris Mason 		if (p->locks[i] == BTRFS_READ_LOCK)
71bd681513SChris Mason 			p->locks[i] = BTRFS_READ_LOCK_BLOCKING;
72bd681513SChris Mason 		else if (p->locks[i] == BTRFS_WRITE_LOCK)
73bd681513SChris Mason 			p->locks[i] = BTRFS_WRITE_LOCK_BLOCKING;
74b4ce94deSChris Mason 	}
75b4ce94deSChris Mason }
76b4ce94deSChris Mason 
77b4ce94deSChris Mason /*
78b4ce94deSChris Mason  * reset all the locked nodes in the patch to spinning locks.
794008c04aSChris Mason  *
804008c04aSChris Mason  * held is used to keep lockdep happy, when lockdep is enabled
814008c04aSChris Mason  * we set held to a blocking lock before we go around and
824008c04aSChris Mason  * retake all the spinlocks in the path.  You can safely use NULL
834008c04aSChris Mason  * for held
84b4ce94deSChris Mason  */
854008c04aSChris Mason noinline void btrfs_clear_path_blocking(struct btrfs_path *p,
86bd681513SChris Mason 					struct extent_buffer *held, int held_rw)
87b4ce94deSChris Mason {
88b4ce94deSChris Mason 	int i;
894008c04aSChris Mason 
904008c04aSChris Mason #ifdef CONFIG_DEBUG_LOCK_ALLOC
914008c04aSChris Mason 	/* lockdep really cares that we take all of these spinlocks
924008c04aSChris Mason 	 * in the right order.  If any of the locks in the path are not
934008c04aSChris Mason 	 * currently blocking, it is going to complain.  So, make really
944008c04aSChris Mason 	 * really sure by forcing the path to blocking before we clear
954008c04aSChris Mason 	 * the path blocking.
964008c04aSChris Mason 	 */
97bd681513SChris Mason 	if (held) {
98bd681513SChris Mason 		btrfs_set_lock_blocking_rw(held, held_rw);
99bd681513SChris Mason 		if (held_rw == BTRFS_WRITE_LOCK)
100bd681513SChris Mason 			held_rw = BTRFS_WRITE_LOCK_BLOCKING;
101bd681513SChris Mason 		else if (held_rw == BTRFS_READ_LOCK)
102bd681513SChris Mason 			held_rw = BTRFS_READ_LOCK_BLOCKING;
103bd681513SChris Mason 	}
1044008c04aSChris Mason 	btrfs_set_path_blocking(p);
1054008c04aSChris Mason #endif
1064008c04aSChris Mason 
1074008c04aSChris Mason 	for (i = BTRFS_MAX_LEVEL - 1; i >= 0; i--) {
108bd681513SChris Mason 		if (p->nodes[i] && p->locks[i]) {
109bd681513SChris Mason 			btrfs_clear_lock_blocking_rw(p->nodes[i], p->locks[i]);
110bd681513SChris Mason 			if (p->locks[i] == BTRFS_WRITE_LOCK_BLOCKING)
111bd681513SChris Mason 				p->locks[i] = BTRFS_WRITE_LOCK;
112bd681513SChris Mason 			else if (p->locks[i] == BTRFS_READ_LOCK_BLOCKING)
113bd681513SChris Mason 				p->locks[i] = BTRFS_READ_LOCK;
114bd681513SChris Mason 		}
115b4ce94deSChris Mason 	}
1164008c04aSChris Mason 
1174008c04aSChris Mason #ifdef CONFIG_DEBUG_LOCK_ALLOC
1184008c04aSChris Mason 	if (held)
119bd681513SChris Mason 		btrfs_clear_lock_blocking_rw(held, held_rw);
1204008c04aSChris Mason #endif
121b4ce94deSChris Mason }
122b4ce94deSChris Mason 
123d352ac68SChris Mason /* this also releases the path */
1242c90e5d6SChris Mason void btrfs_free_path(struct btrfs_path *p)
1252c90e5d6SChris Mason {
126ff175d57SJesper Juhl 	if (!p)
127ff175d57SJesper Juhl 		return;
128b3b4aa74SDavid Sterba 	btrfs_release_path(p);
1292c90e5d6SChris Mason 	kmem_cache_free(btrfs_path_cachep, p);
1302c90e5d6SChris Mason }
1312c90e5d6SChris Mason 
132d352ac68SChris Mason /*
133d352ac68SChris Mason  * path release drops references on the extent buffers in the path
134d352ac68SChris Mason  * and it drops any locks held by this path
135d352ac68SChris Mason  *
136d352ac68SChris Mason  * It is safe to call this on paths that no locks or extent buffers held.
137d352ac68SChris Mason  */
138b3b4aa74SDavid Sterba noinline void btrfs_release_path(struct btrfs_path *p)
139eb60ceacSChris Mason {
140eb60ceacSChris Mason 	int i;
141a2135011SChris Mason 
142234b63a0SChris Mason 	for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
1433f157a2fSChris Mason 		p->slots[i] = 0;
144eb60ceacSChris Mason 		if (!p->nodes[i])
145925baeddSChris Mason 			continue;
146925baeddSChris Mason 		if (p->locks[i]) {
147bd681513SChris Mason 			btrfs_tree_unlock_rw(p->nodes[i], p->locks[i]);
148925baeddSChris Mason 			p->locks[i] = 0;
149925baeddSChris Mason 		}
1505f39d397SChris Mason 		free_extent_buffer(p->nodes[i]);
1513f157a2fSChris Mason 		p->nodes[i] = NULL;
152eb60ceacSChris Mason 	}
153eb60ceacSChris Mason }
154eb60ceacSChris Mason 
155d352ac68SChris Mason /*
156d352ac68SChris Mason  * safely gets a reference on the root node of a tree.  A lock
157d352ac68SChris Mason  * is not taken, so a concurrent writer may put a different node
158d352ac68SChris Mason  * at the root of the tree.  See btrfs_lock_root_node for the
159d352ac68SChris Mason  * looping required.
160d352ac68SChris Mason  *
161d352ac68SChris Mason  * The extent buffer returned by this has a reference taken, so
162d352ac68SChris Mason  * it won't disappear.  It may stop being the root of the tree
163d352ac68SChris Mason  * at any time because there are no locks held.
164d352ac68SChris Mason  */
165925baeddSChris Mason struct extent_buffer *btrfs_root_node(struct btrfs_root *root)
166925baeddSChris Mason {
167925baeddSChris Mason 	struct extent_buffer *eb;
168240f62c8SChris Mason 
1693083ee2eSJosef Bacik 	while (1) {
170240f62c8SChris Mason 		rcu_read_lock();
171240f62c8SChris Mason 		eb = rcu_dereference(root->node);
1723083ee2eSJosef Bacik 
1733083ee2eSJosef Bacik 		/*
1743083ee2eSJosef Bacik 		 * RCU really hurts here, we could free up the root node because
1753083ee2eSJosef Bacik 		 * it was cow'ed but we may not get the new root node yet so do
1763083ee2eSJosef Bacik 		 * the inc_not_zero dance and if it doesn't work then
1773083ee2eSJosef Bacik 		 * synchronize_rcu and try again.
1783083ee2eSJosef Bacik 		 */
1793083ee2eSJosef Bacik 		if (atomic_inc_not_zero(&eb->refs)) {
180240f62c8SChris Mason 			rcu_read_unlock();
1813083ee2eSJosef Bacik 			break;
1823083ee2eSJosef Bacik 		}
1833083ee2eSJosef Bacik 		rcu_read_unlock();
1843083ee2eSJosef Bacik 		synchronize_rcu();
1853083ee2eSJosef Bacik 	}
186925baeddSChris Mason 	return eb;
187925baeddSChris Mason }
188925baeddSChris Mason 
189d352ac68SChris Mason /* loop around taking references on and locking the root node of the
190d352ac68SChris Mason  * tree until you end up with a lock on the root.  A locked buffer
191d352ac68SChris Mason  * is returned, with a reference held.
192d352ac68SChris Mason  */
193925baeddSChris Mason struct extent_buffer *btrfs_lock_root_node(struct btrfs_root *root)
194925baeddSChris Mason {
195925baeddSChris Mason 	struct extent_buffer *eb;
196925baeddSChris Mason 
197925baeddSChris Mason 	while (1) {
198925baeddSChris Mason 		eb = btrfs_root_node(root);
199925baeddSChris Mason 		btrfs_tree_lock(eb);
200240f62c8SChris Mason 		if (eb == root->node)
201925baeddSChris Mason 			break;
202925baeddSChris Mason 		btrfs_tree_unlock(eb);
203925baeddSChris Mason 		free_extent_buffer(eb);
204925baeddSChris Mason 	}
205925baeddSChris Mason 	return eb;
206925baeddSChris Mason }
207925baeddSChris Mason 
208bd681513SChris Mason /* loop around taking references on and locking the root node of the
209bd681513SChris Mason  * tree until you end up with a lock on the root.  A locked buffer
210bd681513SChris Mason  * is returned, with a reference held.
211bd681513SChris Mason  */
212bd681513SChris Mason struct extent_buffer *btrfs_read_lock_root_node(struct btrfs_root *root)
213bd681513SChris Mason {
214bd681513SChris Mason 	struct extent_buffer *eb;
215bd681513SChris Mason 
216bd681513SChris Mason 	while (1) {
217bd681513SChris Mason 		eb = btrfs_root_node(root);
218bd681513SChris Mason 		btrfs_tree_read_lock(eb);
219bd681513SChris Mason 		if (eb == root->node)
220bd681513SChris Mason 			break;
221bd681513SChris Mason 		btrfs_tree_read_unlock(eb);
222bd681513SChris Mason 		free_extent_buffer(eb);
223bd681513SChris Mason 	}
224bd681513SChris Mason 	return eb;
225bd681513SChris Mason }
226bd681513SChris Mason 
227d352ac68SChris Mason /* cowonly root (everything not a reference counted cow subvolume), just get
228d352ac68SChris Mason  * put onto a simple dirty list.  transaction.c walks this to make sure they
229d352ac68SChris Mason  * get properly updated on disk.
230d352ac68SChris Mason  */
2310b86a832SChris Mason static void add_root_to_dirty_list(struct btrfs_root *root)
2320b86a832SChris Mason {
233e5846fc6SChris Mason 	spin_lock(&root->fs_info->trans_lock);
2340b86a832SChris Mason 	if (root->track_dirty && list_empty(&root->dirty_list)) {
2350b86a832SChris Mason 		list_add(&root->dirty_list,
2360b86a832SChris Mason 			 &root->fs_info->dirty_cowonly_roots);
2370b86a832SChris Mason 	}
238e5846fc6SChris Mason 	spin_unlock(&root->fs_info->trans_lock);
2390b86a832SChris Mason }
2400b86a832SChris Mason 
241d352ac68SChris Mason /*
242d352ac68SChris Mason  * used by snapshot creation to make a copy of a root for a tree with
243d352ac68SChris Mason  * a given objectid.  The buffer with the new root node is returned in
244d352ac68SChris Mason  * cow_ret, and this func returns zero on success or a negative error code.
245d352ac68SChris Mason  */
246be20aa9dSChris Mason int btrfs_copy_root(struct btrfs_trans_handle *trans,
247be20aa9dSChris Mason 		      struct btrfs_root *root,
248be20aa9dSChris Mason 		      struct extent_buffer *buf,
249be20aa9dSChris Mason 		      struct extent_buffer **cow_ret, u64 new_root_objectid)
250be20aa9dSChris Mason {
251be20aa9dSChris Mason 	struct extent_buffer *cow;
252be20aa9dSChris Mason 	int ret = 0;
253be20aa9dSChris Mason 	int level;
2545d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
255be20aa9dSChris Mason 
256be20aa9dSChris Mason 	WARN_ON(root->ref_cows && trans->transid !=
257be20aa9dSChris Mason 		root->fs_info->running_transaction->transid);
258be20aa9dSChris Mason 	WARN_ON(root->ref_cows && trans->transid != root->last_trans);
259be20aa9dSChris Mason 
260be20aa9dSChris Mason 	level = btrfs_header_level(buf);
2615d4f98a2SYan Zheng 	if (level == 0)
2625d4f98a2SYan Zheng 		btrfs_item_key(buf, &disk_key, 0);
2635d4f98a2SYan Zheng 	else
2645d4f98a2SYan Zheng 		btrfs_node_key(buf, &disk_key, 0);
26531840ae1SZheng Yan 
2665d4f98a2SYan Zheng 	cow = btrfs_alloc_free_block(trans, root, buf->len, 0,
2675d4f98a2SYan Zheng 				     new_root_objectid, &disk_key, level,
2685581a51aSJan Schmidt 				     buf->start, 0);
2695d4f98a2SYan Zheng 	if (IS_ERR(cow))
270be20aa9dSChris Mason 		return PTR_ERR(cow);
271be20aa9dSChris Mason 
272be20aa9dSChris Mason 	copy_extent_buffer(cow, buf, 0, 0, cow->len);
273be20aa9dSChris Mason 	btrfs_set_header_bytenr(cow, cow->start);
274be20aa9dSChris Mason 	btrfs_set_header_generation(cow, trans->transid);
2755d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
2765d4f98a2SYan Zheng 	btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
2775d4f98a2SYan Zheng 				     BTRFS_HEADER_FLAG_RELOC);
2785d4f98a2SYan Zheng 	if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
2795d4f98a2SYan Zheng 		btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
2805d4f98a2SYan Zheng 	else
281be20aa9dSChris Mason 		btrfs_set_header_owner(cow, new_root_objectid);
282be20aa9dSChris Mason 
2832b82032cSYan Zheng 	write_extent_buffer(cow, root->fs_info->fsid,
2842b82032cSYan Zheng 			    (unsigned long)btrfs_header_fsid(cow),
2852b82032cSYan Zheng 			    BTRFS_FSID_SIZE);
2862b82032cSYan Zheng 
287be20aa9dSChris Mason 	WARN_ON(btrfs_header_generation(buf) > trans->transid);
2885d4f98a2SYan Zheng 	if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
28966d7e7f0SArne Jansen 		ret = btrfs_inc_ref(trans, root, cow, 1, 1);
2905d4f98a2SYan Zheng 	else
29166d7e7f0SArne Jansen 		ret = btrfs_inc_ref(trans, root, cow, 0, 1);
2924aec2b52SChris Mason 
293be20aa9dSChris Mason 	if (ret)
294be20aa9dSChris Mason 		return ret;
295be20aa9dSChris Mason 
296be20aa9dSChris Mason 	btrfs_mark_buffer_dirty(cow);
297be20aa9dSChris Mason 	*cow_ret = cow;
298be20aa9dSChris Mason 	return 0;
299be20aa9dSChris Mason }
300be20aa9dSChris Mason 
301bd989ba3SJan Schmidt enum mod_log_op {
302bd989ba3SJan Schmidt 	MOD_LOG_KEY_REPLACE,
303bd989ba3SJan Schmidt 	MOD_LOG_KEY_ADD,
304bd989ba3SJan Schmidt 	MOD_LOG_KEY_REMOVE,
305bd989ba3SJan Schmidt 	MOD_LOG_KEY_REMOVE_WHILE_FREEING,
306bd989ba3SJan Schmidt 	MOD_LOG_KEY_REMOVE_WHILE_MOVING,
307bd989ba3SJan Schmidt 	MOD_LOG_MOVE_KEYS,
308bd989ba3SJan Schmidt 	MOD_LOG_ROOT_REPLACE,
309bd989ba3SJan Schmidt };
310bd989ba3SJan Schmidt 
311bd989ba3SJan Schmidt struct tree_mod_move {
312bd989ba3SJan Schmidt 	int dst_slot;
313bd989ba3SJan Schmidt 	int nr_items;
314bd989ba3SJan Schmidt };
315bd989ba3SJan Schmidt 
316bd989ba3SJan Schmidt struct tree_mod_root {
317bd989ba3SJan Schmidt 	u64 logical;
318bd989ba3SJan Schmidt 	u8 level;
319bd989ba3SJan Schmidt };
320bd989ba3SJan Schmidt 
321bd989ba3SJan Schmidt struct tree_mod_elem {
322bd989ba3SJan Schmidt 	struct rb_node node;
323bd989ba3SJan Schmidt 	u64 index;		/* shifted logical */
324bd989ba3SJan Schmidt 	struct seq_list elem;
325bd989ba3SJan Schmidt 	enum mod_log_op op;
326bd989ba3SJan Schmidt 
327bd989ba3SJan Schmidt 	/* this is used for MOD_LOG_KEY_* and MOD_LOG_MOVE_KEYS operations */
328bd989ba3SJan Schmidt 	int slot;
329bd989ba3SJan Schmidt 
330bd989ba3SJan Schmidt 	/* this is used for MOD_LOG_KEY* and MOD_LOG_ROOT_REPLACE */
331bd989ba3SJan Schmidt 	u64 generation;
332bd989ba3SJan Schmidt 
333bd989ba3SJan Schmidt 	/* those are used for op == MOD_LOG_KEY_{REPLACE,REMOVE} */
334bd989ba3SJan Schmidt 	struct btrfs_disk_key key;
335bd989ba3SJan Schmidt 	u64 blockptr;
336bd989ba3SJan Schmidt 
337bd989ba3SJan Schmidt 	/* this is used for op == MOD_LOG_MOVE_KEYS */
338bd989ba3SJan Schmidt 	struct tree_mod_move move;
339bd989ba3SJan Schmidt 
340bd989ba3SJan Schmidt 	/* this is used for op == MOD_LOG_ROOT_REPLACE */
341bd989ba3SJan Schmidt 	struct tree_mod_root old_root;
342bd989ba3SJan Schmidt };
343bd989ba3SJan Schmidt 
344bd989ba3SJan Schmidt static inline void
345bd989ba3SJan Schmidt __get_tree_mod_seq(struct btrfs_fs_info *fs_info, struct seq_list *elem)
346bd989ba3SJan Schmidt {
347bd989ba3SJan Schmidt 	elem->seq = atomic_inc_return(&fs_info->tree_mod_seq);
348bd989ba3SJan Schmidt 	list_add_tail(&elem->list, &fs_info->tree_mod_seq_list);
349bd989ba3SJan Schmidt }
350bd989ba3SJan Schmidt 
351bd989ba3SJan Schmidt void btrfs_get_tree_mod_seq(struct btrfs_fs_info *fs_info,
352bd989ba3SJan Schmidt 			    struct seq_list *elem)
353bd989ba3SJan Schmidt {
354bd989ba3SJan Schmidt 	elem->flags = 1;
355bd989ba3SJan Schmidt 	spin_lock(&fs_info->tree_mod_seq_lock);
356bd989ba3SJan Schmidt 	__get_tree_mod_seq(fs_info, elem);
357bd989ba3SJan Schmidt 	spin_unlock(&fs_info->tree_mod_seq_lock);
358bd989ba3SJan Schmidt }
359bd989ba3SJan Schmidt 
360bd989ba3SJan Schmidt void btrfs_put_tree_mod_seq(struct btrfs_fs_info *fs_info,
361bd989ba3SJan Schmidt 			    struct seq_list *elem)
362bd989ba3SJan Schmidt {
363bd989ba3SJan Schmidt 	struct rb_root *tm_root;
364bd989ba3SJan Schmidt 	struct rb_node *node;
365bd989ba3SJan Schmidt 	struct rb_node *next;
366bd989ba3SJan Schmidt 	struct seq_list *cur_elem;
367bd989ba3SJan Schmidt 	struct tree_mod_elem *tm;
368bd989ba3SJan Schmidt 	u64 min_seq = (u64)-1;
369bd989ba3SJan Schmidt 	u64 seq_putting = elem->seq;
370bd989ba3SJan Schmidt 
371bd989ba3SJan Schmidt 	if (!seq_putting)
372bd989ba3SJan Schmidt 		return;
373bd989ba3SJan Schmidt 
374bd989ba3SJan Schmidt 	BUG_ON(!(elem->flags & 1));
375bd989ba3SJan Schmidt 	spin_lock(&fs_info->tree_mod_seq_lock);
376bd989ba3SJan Schmidt 	list_del(&elem->list);
377bd989ba3SJan Schmidt 
378bd989ba3SJan Schmidt 	list_for_each_entry(cur_elem, &fs_info->tree_mod_seq_list, list) {
379bd989ba3SJan Schmidt 		if ((cur_elem->flags & 1) && cur_elem->seq < min_seq) {
380bd989ba3SJan Schmidt 			if (seq_putting > cur_elem->seq) {
381bd989ba3SJan Schmidt 				/*
382bd989ba3SJan Schmidt 				 * blocker with lower sequence number exists, we
383bd989ba3SJan Schmidt 				 * cannot remove anything from the log
384bd989ba3SJan Schmidt 				 */
385bd989ba3SJan Schmidt 				goto out;
386bd989ba3SJan Schmidt 			}
387bd989ba3SJan Schmidt 			min_seq = cur_elem->seq;
388bd989ba3SJan Schmidt 		}
389bd989ba3SJan Schmidt 	}
390bd989ba3SJan Schmidt 
391bd989ba3SJan Schmidt 	/*
392bd989ba3SJan Schmidt 	 * anything that's lower than the lowest existing (read: blocked)
393bd989ba3SJan Schmidt 	 * sequence number can be removed from the tree.
394bd989ba3SJan Schmidt 	 */
395bd989ba3SJan Schmidt 	write_lock(&fs_info->tree_mod_log_lock);
396bd989ba3SJan Schmidt 	tm_root = &fs_info->tree_mod_log;
397bd989ba3SJan Schmidt 	for (node = rb_first(tm_root); node; node = next) {
398bd989ba3SJan Schmidt 		next = rb_next(node);
399bd989ba3SJan Schmidt 		tm = container_of(node, struct tree_mod_elem, node);
400bd989ba3SJan Schmidt 		if (tm->elem.seq > min_seq)
401bd989ba3SJan Schmidt 			continue;
402bd989ba3SJan Schmidt 		rb_erase(node, tm_root);
403bd989ba3SJan Schmidt 		list_del(&tm->elem.list);
404bd989ba3SJan Schmidt 		kfree(tm);
405bd989ba3SJan Schmidt 	}
406bd989ba3SJan Schmidt 	write_unlock(&fs_info->tree_mod_log_lock);
407bd989ba3SJan Schmidt out:
408bd989ba3SJan Schmidt 	spin_unlock(&fs_info->tree_mod_seq_lock);
409bd989ba3SJan Schmidt }
410bd989ba3SJan Schmidt 
411bd989ba3SJan Schmidt /*
412bd989ba3SJan Schmidt  * key order of the log:
413bd989ba3SJan Schmidt  *       index -> sequence
414bd989ba3SJan Schmidt  *
415bd989ba3SJan Schmidt  * the index is the shifted logical of the *new* root node for root replace
416bd989ba3SJan Schmidt  * operations, or the shifted logical of the affected block for all other
417bd989ba3SJan Schmidt  * operations.
418bd989ba3SJan Schmidt  */
419bd989ba3SJan Schmidt static noinline int
420bd989ba3SJan Schmidt __tree_mod_log_insert(struct btrfs_fs_info *fs_info, struct tree_mod_elem *tm)
421bd989ba3SJan Schmidt {
422bd989ba3SJan Schmidt 	struct rb_root *tm_root;
423bd989ba3SJan Schmidt 	struct rb_node **new;
424bd989ba3SJan Schmidt 	struct rb_node *parent = NULL;
425bd989ba3SJan Schmidt 	struct tree_mod_elem *cur;
426bd989ba3SJan Schmidt 	int ret = 0;
427bd989ba3SJan Schmidt 
428bd989ba3SJan Schmidt 	BUG_ON(!tm || !tm->elem.seq);
429bd989ba3SJan Schmidt 
430bd989ba3SJan Schmidt 	write_lock(&fs_info->tree_mod_log_lock);
431bd989ba3SJan Schmidt 	tm_root = &fs_info->tree_mod_log;
432bd989ba3SJan Schmidt 	new = &tm_root->rb_node;
433bd989ba3SJan Schmidt 	while (*new) {
434bd989ba3SJan Schmidt 		cur = container_of(*new, struct tree_mod_elem, node);
435bd989ba3SJan Schmidt 		parent = *new;
436bd989ba3SJan Schmidt 		if (cur->index < tm->index)
437bd989ba3SJan Schmidt 			new = &((*new)->rb_left);
438bd989ba3SJan Schmidt 		else if (cur->index > tm->index)
439bd989ba3SJan Schmidt 			new = &((*new)->rb_right);
440bd989ba3SJan Schmidt 		else if (cur->elem.seq < tm->elem.seq)
441bd989ba3SJan Schmidt 			new = &((*new)->rb_left);
442bd989ba3SJan Schmidt 		else if (cur->elem.seq > tm->elem.seq)
443bd989ba3SJan Schmidt 			new = &((*new)->rb_right);
444bd989ba3SJan Schmidt 		else {
445bd989ba3SJan Schmidt 			kfree(tm);
446bd989ba3SJan Schmidt 			ret = -EEXIST;
447bd989ba3SJan Schmidt 			goto unlock;
448bd989ba3SJan Schmidt 		}
449bd989ba3SJan Schmidt 	}
450bd989ba3SJan Schmidt 
451bd989ba3SJan Schmidt 	rb_link_node(&tm->node, parent, new);
452bd989ba3SJan Schmidt 	rb_insert_color(&tm->node, tm_root);
453bd989ba3SJan Schmidt unlock:
454bd989ba3SJan Schmidt 	write_unlock(&fs_info->tree_mod_log_lock);
455bd989ba3SJan Schmidt 	return ret;
456bd989ba3SJan Schmidt }
457bd989ba3SJan Schmidt 
458e9b7fd4dSJan Schmidt static inline int tree_mod_dont_log(struct btrfs_fs_info *fs_info,
459e9b7fd4dSJan Schmidt 				    struct extent_buffer *eb) {
460e9b7fd4dSJan Schmidt 	smp_mb();
461e9b7fd4dSJan Schmidt 	if (list_empty(&(fs_info)->tree_mod_seq_list))
462e9b7fd4dSJan Schmidt 		return 1;
463e9b7fd4dSJan Schmidt 	if (!eb)
464e9b7fd4dSJan Schmidt 		return 0;
465e9b7fd4dSJan Schmidt 	if (btrfs_header_level(eb) == 0)
466e9b7fd4dSJan Schmidt 		return 1;
467e9b7fd4dSJan Schmidt 	return 0;
468e9b7fd4dSJan Schmidt }
469e9b7fd4dSJan Schmidt 
4703310c36eSJan Schmidt /*
4713310c36eSJan Schmidt  * This allocates memory and gets a tree modification sequence number when
4723310c36eSJan Schmidt  * needed.
4733310c36eSJan Schmidt  *
4743310c36eSJan Schmidt  * Returns 0 when no sequence number is needed, < 0 on error.
4753310c36eSJan Schmidt  * Returns 1 when a sequence number was added. In this case,
4763310c36eSJan Schmidt  * fs_info->tree_mod_seq_lock was acquired and must be released by the caller
4773310c36eSJan Schmidt  * after inserting into the rb tree.
4783310c36eSJan Schmidt  */
479926dd8a6SJan Schmidt static inline int tree_mod_alloc(struct btrfs_fs_info *fs_info, gfp_t flags,
480bd989ba3SJan Schmidt 				 struct tree_mod_elem **tm_ret)
481bd989ba3SJan Schmidt {
482bd989ba3SJan Schmidt 	struct tree_mod_elem *tm;
483926dd8a6SJan Schmidt 	int seq;
484bd989ba3SJan Schmidt 
485e9b7fd4dSJan Schmidt 	if (tree_mod_dont_log(fs_info, NULL))
486bd989ba3SJan Schmidt 		return 0;
487bd989ba3SJan Schmidt 
488bd989ba3SJan Schmidt 	tm = *tm_ret = kzalloc(sizeof(*tm), flags);
489bd989ba3SJan Schmidt 	if (!tm)
490bd989ba3SJan Schmidt 		return -ENOMEM;
491bd989ba3SJan Schmidt 
492926dd8a6SJan Schmidt 	tm->elem.flags = 0;
493926dd8a6SJan Schmidt 	spin_lock(&fs_info->tree_mod_seq_lock);
494926dd8a6SJan Schmidt 	if (list_empty(&fs_info->tree_mod_seq_list)) {
495926dd8a6SJan Schmidt 		/*
496926dd8a6SJan Schmidt 		 * someone emptied the list while we were waiting for the lock.
497926dd8a6SJan Schmidt 		 * we must not add to the list, because no blocker exists. items
498926dd8a6SJan Schmidt 		 * are removed from the list only when the existing blocker is
499926dd8a6SJan Schmidt 		 * removed from the list.
500926dd8a6SJan Schmidt 		 */
501926dd8a6SJan Schmidt 		kfree(tm);
502926dd8a6SJan Schmidt 		seq = 0;
5033310c36eSJan Schmidt 		spin_unlock(&fs_info->tree_mod_seq_lock);
504926dd8a6SJan Schmidt 	} else {
505bd989ba3SJan Schmidt 		__get_tree_mod_seq(fs_info, &tm->elem);
506bd989ba3SJan Schmidt 		seq = tm->elem.seq;
507926dd8a6SJan Schmidt 	}
508bd989ba3SJan Schmidt 
509bd989ba3SJan Schmidt 	return seq;
510bd989ba3SJan Schmidt }
511bd989ba3SJan Schmidt 
512bd989ba3SJan Schmidt static noinline int
513bd989ba3SJan Schmidt tree_mod_log_insert_key_mask(struct btrfs_fs_info *fs_info,
514bd989ba3SJan Schmidt 			     struct extent_buffer *eb, int slot,
515bd989ba3SJan Schmidt 			     enum mod_log_op op, gfp_t flags)
516bd989ba3SJan Schmidt {
517bd989ba3SJan Schmidt 	struct tree_mod_elem *tm;
518bd989ba3SJan Schmidt 	int ret;
519bd989ba3SJan Schmidt 
520bd989ba3SJan Schmidt 	ret = tree_mod_alloc(fs_info, flags, &tm);
521bd989ba3SJan Schmidt 	if (ret <= 0)
522bd989ba3SJan Schmidt 		return ret;
523bd989ba3SJan Schmidt 
524bd989ba3SJan Schmidt 	tm->index = eb->start >> PAGE_CACHE_SHIFT;
525bd989ba3SJan Schmidt 	if (op != MOD_LOG_KEY_ADD) {
526bd989ba3SJan Schmidt 		btrfs_node_key(eb, &tm->key, slot);
527bd989ba3SJan Schmidt 		tm->blockptr = btrfs_node_blockptr(eb, slot);
528bd989ba3SJan Schmidt 	}
529bd989ba3SJan Schmidt 	tm->op = op;
530bd989ba3SJan Schmidt 	tm->slot = slot;
531bd989ba3SJan Schmidt 	tm->generation = btrfs_node_ptr_generation(eb, slot);
532bd989ba3SJan Schmidt 
5333310c36eSJan Schmidt 	ret = __tree_mod_log_insert(fs_info, tm);
5343310c36eSJan Schmidt 	spin_unlock(&fs_info->tree_mod_seq_lock);
5353310c36eSJan Schmidt 	return ret;
536bd989ba3SJan Schmidt }
537bd989ba3SJan Schmidt 
538bd989ba3SJan Schmidt static noinline int
539bd989ba3SJan Schmidt tree_mod_log_insert_key(struct btrfs_fs_info *fs_info, struct extent_buffer *eb,
540bd989ba3SJan Schmidt 			int slot, enum mod_log_op op)
541bd989ba3SJan Schmidt {
542bd989ba3SJan Schmidt 	return tree_mod_log_insert_key_mask(fs_info, eb, slot, op, GFP_NOFS);
543bd989ba3SJan Schmidt }
544bd989ba3SJan Schmidt 
545bd989ba3SJan Schmidt static noinline int
546bd989ba3SJan Schmidt tree_mod_log_insert_move(struct btrfs_fs_info *fs_info,
547bd989ba3SJan Schmidt 			 struct extent_buffer *eb, int dst_slot, int src_slot,
548bd989ba3SJan Schmidt 			 int nr_items, gfp_t flags)
549bd989ba3SJan Schmidt {
550bd989ba3SJan Schmidt 	struct tree_mod_elem *tm;
551bd989ba3SJan Schmidt 	int ret;
552bd989ba3SJan Schmidt 	int i;
553bd989ba3SJan Schmidt 
554f395694cSJan Schmidt 	if (tree_mod_dont_log(fs_info, eb))
555f395694cSJan Schmidt 		return 0;
556bd989ba3SJan Schmidt 
557bd989ba3SJan Schmidt 	for (i = 0; i + dst_slot < src_slot && i < nr_items; i++) {
558bd989ba3SJan Schmidt 		ret = tree_mod_log_insert_key(fs_info, eb, i + dst_slot,
559bd989ba3SJan Schmidt 					      MOD_LOG_KEY_REMOVE_WHILE_MOVING);
560bd989ba3SJan Schmidt 		BUG_ON(ret < 0);
561bd989ba3SJan Schmidt 	}
562bd989ba3SJan Schmidt 
563f395694cSJan Schmidt 	ret = tree_mod_alloc(fs_info, flags, &tm);
564f395694cSJan Schmidt 	if (ret <= 0)
565f395694cSJan Schmidt 		return ret;
566f395694cSJan Schmidt 
567bd989ba3SJan Schmidt 	tm->index = eb->start >> PAGE_CACHE_SHIFT;
568bd989ba3SJan Schmidt 	tm->slot = src_slot;
569bd989ba3SJan Schmidt 	tm->move.dst_slot = dst_slot;
570bd989ba3SJan Schmidt 	tm->move.nr_items = nr_items;
571bd989ba3SJan Schmidt 	tm->op = MOD_LOG_MOVE_KEYS;
572bd989ba3SJan Schmidt 
5733310c36eSJan Schmidt 	ret = __tree_mod_log_insert(fs_info, tm);
5743310c36eSJan Schmidt 	spin_unlock(&fs_info->tree_mod_seq_lock);
5753310c36eSJan Schmidt 	return ret;
576bd989ba3SJan Schmidt }
577bd989ba3SJan Schmidt 
578bd989ba3SJan Schmidt static noinline int
579bd989ba3SJan Schmidt tree_mod_log_insert_root(struct btrfs_fs_info *fs_info,
580bd989ba3SJan Schmidt 			 struct extent_buffer *old_root,
581bd989ba3SJan Schmidt 			 struct extent_buffer *new_root, gfp_t flags)
582bd989ba3SJan Schmidt {
583bd989ba3SJan Schmidt 	struct tree_mod_elem *tm;
584bd989ba3SJan Schmidt 	int ret;
585bd989ba3SJan Schmidt 
586bd989ba3SJan Schmidt 	ret = tree_mod_alloc(fs_info, flags, &tm);
587bd989ba3SJan Schmidt 	if (ret <= 0)
588bd989ba3SJan Schmidt 		return ret;
589bd989ba3SJan Schmidt 
590bd989ba3SJan Schmidt 	tm->index = new_root->start >> PAGE_CACHE_SHIFT;
591bd989ba3SJan Schmidt 	tm->old_root.logical = old_root->start;
592bd989ba3SJan Schmidt 	tm->old_root.level = btrfs_header_level(old_root);
593bd989ba3SJan Schmidt 	tm->generation = btrfs_header_generation(old_root);
594bd989ba3SJan Schmidt 	tm->op = MOD_LOG_ROOT_REPLACE;
595bd989ba3SJan Schmidt 
5963310c36eSJan Schmidt 	ret = __tree_mod_log_insert(fs_info, tm);
5973310c36eSJan Schmidt 	spin_unlock(&fs_info->tree_mod_seq_lock);
5983310c36eSJan Schmidt 	return ret;
599bd989ba3SJan Schmidt }
600bd989ba3SJan Schmidt 
601bd989ba3SJan Schmidt static struct tree_mod_elem *
602bd989ba3SJan Schmidt __tree_mod_log_search(struct btrfs_fs_info *fs_info, u64 start, u64 min_seq,
603bd989ba3SJan Schmidt 		      int smallest)
604bd989ba3SJan Schmidt {
605bd989ba3SJan Schmidt 	struct rb_root *tm_root;
606bd989ba3SJan Schmidt 	struct rb_node *node;
607bd989ba3SJan Schmidt 	struct tree_mod_elem *cur = NULL;
608bd989ba3SJan Schmidt 	struct tree_mod_elem *found = NULL;
609bd989ba3SJan Schmidt 	u64 index = start >> PAGE_CACHE_SHIFT;
610bd989ba3SJan Schmidt 
611bd989ba3SJan Schmidt 	read_lock(&fs_info->tree_mod_log_lock);
612bd989ba3SJan Schmidt 	tm_root = &fs_info->tree_mod_log;
613bd989ba3SJan Schmidt 	node = tm_root->rb_node;
614bd989ba3SJan Schmidt 	while (node) {
615bd989ba3SJan Schmidt 		cur = container_of(node, struct tree_mod_elem, node);
616bd989ba3SJan Schmidt 		if (cur->index < index) {
617bd989ba3SJan Schmidt 			node = node->rb_left;
618bd989ba3SJan Schmidt 		} else if (cur->index > index) {
619bd989ba3SJan Schmidt 			node = node->rb_right;
620bd989ba3SJan Schmidt 		} else if (cur->elem.seq < min_seq) {
621bd989ba3SJan Schmidt 			node = node->rb_left;
622bd989ba3SJan Schmidt 		} else if (!smallest) {
623bd989ba3SJan Schmidt 			/* we want the node with the highest seq */
624bd989ba3SJan Schmidt 			if (found)
625bd989ba3SJan Schmidt 				BUG_ON(found->elem.seq > cur->elem.seq);
626bd989ba3SJan Schmidt 			found = cur;
627bd989ba3SJan Schmidt 			node = node->rb_left;
628bd989ba3SJan Schmidt 		} else if (cur->elem.seq > min_seq) {
629bd989ba3SJan Schmidt 			/* we want the node with the smallest seq */
630bd989ba3SJan Schmidt 			if (found)
631bd989ba3SJan Schmidt 				BUG_ON(found->elem.seq < cur->elem.seq);
632bd989ba3SJan Schmidt 			found = cur;
633bd989ba3SJan Schmidt 			node = node->rb_right;
634bd989ba3SJan Schmidt 		} else {
635bd989ba3SJan Schmidt 			found = cur;
636bd989ba3SJan Schmidt 			break;
637bd989ba3SJan Schmidt 		}
638bd989ba3SJan Schmidt 	}
639bd989ba3SJan Schmidt 	read_unlock(&fs_info->tree_mod_log_lock);
640bd989ba3SJan Schmidt 
641bd989ba3SJan Schmidt 	return found;
642bd989ba3SJan Schmidt }
643bd989ba3SJan Schmidt 
644bd989ba3SJan Schmidt /*
645bd989ba3SJan Schmidt  * this returns the element from the log with the smallest time sequence
646bd989ba3SJan Schmidt  * value that's in the log (the oldest log item). any element with a time
647bd989ba3SJan Schmidt  * sequence lower than min_seq will be ignored.
648bd989ba3SJan Schmidt  */
649bd989ba3SJan Schmidt static struct tree_mod_elem *
650bd989ba3SJan Schmidt tree_mod_log_search_oldest(struct btrfs_fs_info *fs_info, u64 start,
651bd989ba3SJan Schmidt 			   u64 min_seq)
652bd989ba3SJan Schmidt {
653bd989ba3SJan Schmidt 	return __tree_mod_log_search(fs_info, start, min_seq, 1);
654bd989ba3SJan Schmidt }
655bd989ba3SJan Schmidt 
656bd989ba3SJan Schmidt /*
657bd989ba3SJan Schmidt  * this returns the element from the log with the largest time sequence
658bd989ba3SJan Schmidt  * value that's in the log (the most recent log item). any element with
659bd989ba3SJan Schmidt  * a time sequence lower than min_seq will be ignored.
660bd989ba3SJan Schmidt  */
661bd989ba3SJan Schmidt static struct tree_mod_elem *
662bd989ba3SJan Schmidt tree_mod_log_search(struct btrfs_fs_info *fs_info, u64 start, u64 min_seq)
663bd989ba3SJan Schmidt {
664bd989ba3SJan Schmidt 	return __tree_mod_log_search(fs_info, start, min_seq, 0);
665bd989ba3SJan Schmidt }
666bd989ba3SJan Schmidt 
667bd989ba3SJan Schmidt static inline void
668bd989ba3SJan Schmidt tree_mod_log_eb_copy(struct btrfs_fs_info *fs_info, struct extent_buffer *dst,
669bd989ba3SJan Schmidt 		     struct extent_buffer *src, unsigned long dst_offset,
670bd989ba3SJan Schmidt 		     unsigned long src_offset, int nr_items)
671bd989ba3SJan Schmidt {
672bd989ba3SJan Schmidt 	int ret;
673bd989ba3SJan Schmidt 	int i;
674bd989ba3SJan Schmidt 
675e9b7fd4dSJan Schmidt 	if (tree_mod_dont_log(fs_info, NULL))
676bd989ba3SJan Schmidt 		return;
677bd989ba3SJan Schmidt 
678bd989ba3SJan Schmidt 	if (btrfs_header_level(dst) == 0 && btrfs_header_level(src) == 0)
679bd989ba3SJan Schmidt 		return;
680bd989ba3SJan Schmidt 
681bd989ba3SJan Schmidt 	/* speed this up by single seq for all operations? */
682bd989ba3SJan Schmidt 	for (i = 0; i < nr_items; i++) {
683bd989ba3SJan Schmidt 		ret = tree_mod_log_insert_key(fs_info, src, i + src_offset,
684bd989ba3SJan Schmidt 					      MOD_LOG_KEY_REMOVE);
685bd989ba3SJan Schmidt 		BUG_ON(ret < 0);
686bd989ba3SJan Schmidt 		ret = tree_mod_log_insert_key(fs_info, dst, i + dst_offset,
687bd989ba3SJan Schmidt 					      MOD_LOG_KEY_ADD);
688bd989ba3SJan Schmidt 		BUG_ON(ret < 0);
689bd989ba3SJan Schmidt 	}
690bd989ba3SJan Schmidt }
691bd989ba3SJan Schmidt 
692bd989ba3SJan Schmidt static inline void
693bd989ba3SJan Schmidt tree_mod_log_eb_move(struct btrfs_fs_info *fs_info, struct extent_buffer *dst,
694bd989ba3SJan Schmidt 		     int dst_offset, int src_offset, int nr_items)
695bd989ba3SJan Schmidt {
696bd989ba3SJan Schmidt 	int ret;
697bd989ba3SJan Schmidt 	ret = tree_mod_log_insert_move(fs_info, dst, dst_offset, src_offset,
698bd989ba3SJan Schmidt 				       nr_items, GFP_NOFS);
699bd989ba3SJan Schmidt 	BUG_ON(ret < 0);
700bd989ba3SJan Schmidt }
701bd989ba3SJan Schmidt 
702bd989ba3SJan Schmidt static inline void
703bd989ba3SJan Schmidt tree_mod_log_set_node_key(struct btrfs_fs_info *fs_info,
704bd989ba3SJan Schmidt 			  struct extent_buffer *eb,
705bd989ba3SJan Schmidt 			  struct btrfs_disk_key *disk_key, int slot, int atomic)
706bd989ba3SJan Schmidt {
707bd989ba3SJan Schmidt 	int ret;
708bd989ba3SJan Schmidt 
709bd989ba3SJan Schmidt 	ret = tree_mod_log_insert_key_mask(fs_info, eb, slot,
710bd989ba3SJan Schmidt 					   MOD_LOG_KEY_REPLACE,
711bd989ba3SJan Schmidt 					   atomic ? GFP_ATOMIC : GFP_NOFS);
712bd989ba3SJan Schmidt 	BUG_ON(ret < 0);
713bd989ba3SJan Schmidt }
714bd989ba3SJan Schmidt 
715bd989ba3SJan Schmidt static void tree_mod_log_free_eb(struct btrfs_fs_info *fs_info,
716bd989ba3SJan Schmidt 				 struct extent_buffer *eb)
717bd989ba3SJan Schmidt {
718bd989ba3SJan Schmidt 	int i;
719bd989ba3SJan Schmidt 	int ret;
720bd989ba3SJan Schmidt 	u32 nritems;
721bd989ba3SJan Schmidt 
722e9b7fd4dSJan Schmidt 	if (tree_mod_dont_log(fs_info, eb))
723bd989ba3SJan Schmidt 		return;
724bd989ba3SJan Schmidt 
725bd989ba3SJan Schmidt 	nritems = btrfs_header_nritems(eb);
726bd989ba3SJan Schmidt 	for (i = nritems - 1; i >= 0; i--) {
727bd989ba3SJan Schmidt 		ret = tree_mod_log_insert_key(fs_info, eb, i,
728bd989ba3SJan Schmidt 					      MOD_LOG_KEY_REMOVE_WHILE_FREEING);
729bd989ba3SJan Schmidt 		BUG_ON(ret < 0);
730bd989ba3SJan Schmidt 	}
731bd989ba3SJan Schmidt }
732bd989ba3SJan Schmidt 
733bd989ba3SJan Schmidt static inline void
734bd989ba3SJan Schmidt tree_mod_log_set_root_pointer(struct btrfs_root *root,
735bd989ba3SJan Schmidt 			      struct extent_buffer *new_root_node)
736bd989ba3SJan Schmidt {
737bd989ba3SJan Schmidt 	int ret;
738bd989ba3SJan Schmidt 	tree_mod_log_free_eb(root->fs_info, root->node);
739bd989ba3SJan Schmidt 	ret = tree_mod_log_insert_root(root->fs_info, root->node,
740bd989ba3SJan Schmidt 				       new_root_node, GFP_NOFS);
741bd989ba3SJan Schmidt 	BUG_ON(ret < 0);
742bd989ba3SJan Schmidt }
743bd989ba3SJan Schmidt 
744d352ac68SChris Mason /*
7455d4f98a2SYan Zheng  * check if the tree block can be shared by multiple trees
7465d4f98a2SYan Zheng  */
7475d4f98a2SYan Zheng int btrfs_block_can_be_shared(struct btrfs_root *root,
7485d4f98a2SYan Zheng 			      struct extent_buffer *buf)
7495d4f98a2SYan Zheng {
7505d4f98a2SYan Zheng 	/*
7515d4f98a2SYan Zheng 	 * Tree blocks not in refernece counted trees and tree roots
7525d4f98a2SYan Zheng 	 * are never shared. If a block was allocated after the last
7535d4f98a2SYan Zheng 	 * snapshot and the block was not allocated by tree relocation,
7545d4f98a2SYan Zheng 	 * we know the block is not shared.
7555d4f98a2SYan Zheng 	 */
7565d4f98a2SYan Zheng 	if (root->ref_cows &&
7575d4f98a2SYan Zheng 	    buf != root->node && buf != root->commit_root &&
7585d4f98a2SYan Zheng 	    (btrfs_header_generation(buf) <=
7595d4f98a2SYan Zheng 	     btrfs_root_last_snapshot(&root->root_item) ||
7605d4f98a2SYan Zheng 	     btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)))
7615d4f98a2SYan Zheng 		return 1;
7625d4f98a2SYan Zheng #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
7635d4f98a2SYan Zheng 	if (root->ref_cows &&
7645d4f98a2SYan Zheng 	    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
7655d4f98a2SYan Zheng 		return 1;
7665d4f98a2SYan Zheng #endif
7675d4f98a2SYan Zheng 	return 0;
7685d4f98a2SYan Zheng }
7695d4f98a2SYan Zheng 
7705d4f98a2SYan Zheng static noinline int update_ref_for_cow(struct btrfs_trans_handle *trans,
7715d4f98a2SYan Zheng 				       struct btrfs_root *root,
7725d4f98a2SYan Zheng 				       struct extent_buffer *buf,
773f0486c68SYan, Zheng 				       struct extent_buffer *cow,
774f0486c68SYan, Zheng 				       int *last_ref)
7755d4f98a2SYan Zheng {
7765d4f98a2SYan Zheng 	u64 refs;
7775d4f98a2SYan Zheng 	u64 owner;
7785d4f98a2SYan Zheng 	u64 flags;
7795d4f98a2SYan Zheng 	u64 new_flags = 0;
7805d4f98a2SYan Zheng 	int ret;
7815d4f98a2SYan Zheng 
7825d4f98a2SYan Zheng 	/*
7835d4f98a2SYan Zheng 	 * Backrefs update rules:
7845d4f98a2SYan Zheng 	 *
7855d4f98a2SYan Zheng 	 * Always use full backrefs for extent pointers in tree block
7865d4f98a2SYan Zheng 	 * allocated by tree relocation.
7875d4f98a2SYan Zheng 	 *
7885d4f98a2SYan Zheng 	 * If a shared tree block is no longer referenced by its owner
7895d4f98a2SYan Zheng 	 * tree (btrfs_header_owner(buf) == root->root_key.objectid),
7905d4f98a2SYan Zheng 	 * use full backrefs for extent pointers in tree block.
7915d4f98a2SYan Zheng 	 *
7925d4f98a2SYan Zheng 	 * If a tree block is been relocating
7935d4f98a2SYan Zheng 	 * (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID),
7945d4f98a2SYan Zheng 	 * use full backrefs for extent pointers in tree block.
7955d4f98a2SYan Zheng 	 * The reason for this is some operations (such as drop tree)
7965d4f98a2SYan Zheng 	 * are only allowed for blocks use full backrefs.
7975d4f98a2SYan Zheng 	 */
7985d4f98a2SYan Zheng 
7995d4f98a2SYan Zheng 	if (btrfs_block_can_be_shared(root, buf)) {
8005d4f98a2SYan Zheng 		ret = btrfs_lookup_extent_info(trans, root, buf->start,
8015d4f98a2SYan Zheng 					       buf->len, &refs, &flags);
802be1a5564SMark Fasheh 		if (ret)
803be1a5564SMark Fasheh 			return ret;
804e5df9573SMark Fasheh 		if (refs == 0) {
805e5df9573SMark Fasheh 			ret = -EROFS;
806e5df9573SMark Fasheh 			btrfs_std_error(root->fs_info, ret);
807e5df9573SMark Fasheh 			return ret;
808e5df9573SMark Fasheh 		}
8095d4f98a2SYan Zheng 	} else {
8105d4f98a2SYan Zheng 		refs = 1;
8115d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
8125d4f98a2SYan Zheng 		    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
8135d4f98a2SYan Zheng 			flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
8145d4f98a2SYan Zheng 		else
8155d4f98a2SYan Zheng 			flags = 0;
8165d4f98a2SYan Zheng 	}
8175d4f98a2SYan Zheng 
8185d4f98a2SYan Zheng 	owner = btrfs_header_owner(buf);
8195d4f98a2SYan Zheng 	BUG_ON(owner == BTRFS_TREE_RELOC_OBJECTID &&
8205d4f98a2SYan Zheng 	       !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
8215d4f98a2SYan Zheng 
8225d4f98a2SYan Zheng 	if (refs > 1) {
8235d4f98a2SYan Zheng 		if ((owner == root->root_key.objectid ||
8245d4f98a2SYan Zheng 		     root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) &&
8255d4f98a2SYan Zheng 		    !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)) {
82666d7e7f0SArne Jansen 			ret = btrfs_inc_ref(trans, root, buf, 1, 1);
82779787eaaSJeff Mahoney 			BUG_ON(ret); /* -ENOMEM */
8285d4f98a2SYan Zheng 
8295d4f98a2SYan Zheng 			if (root->root_key.objectid ==
8305d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID) {
83166d7e7f0SArne Jansen 				ret = btrfs_dec_ref(trans, root, buf, 0, 1);
83279787eaaSJeff Mahoney 				BUG_ON(ret); /* -ENOMEM */
83366d7e7f0SArne Jansen 				ret = btrfs_inc_ref(trans, root, cow, 1, 1);
83479787eaaSJeff Mahoney 				BUG_ON(ret); /* -ENOMEM */
8355d4f98a2SYan Zheng 			}
8365d4f98a2SYan Zheng 			new_flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
8375d4f98a2SYan Zheng 		} else {
8385d4f98a2SYan Zheng 
8395d4f98a2SYan Zheng 			if (root->root_key.objectid ==
8405d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID)
84166d7e7f0SArne Jansen 				ret = btrfs_inc_ref(trans, root, cow, 1, 1);
8425d4f98a2SYan Zheng 			else
84366d7e7f0SArne Jansen 				ret = btrfs_inc_ref(trans, root, cow, 0, 1);
84479787eaaSJeff Mahoney 			BUG_ON(ret); /* -ENOMEM */
8455d4f98a2SYan Zheng 		}
8465d4f98a2SYan Zheng 		if (new_flags != 0) {
8475d4f98a2SYan Zheng 			ret = btrfs_set_disk_extent_flags(trans, root,
8485d4f98a2SYan Zheng 							  buf->start,
8495d4f98a2SYan Zheng 							  buf->len,
8505d4f98a2SYan Zheng 							  new_flags, 0);
851be1a5564SMark Fasheh 			if (ret)
852be1a5564SMark Fasheh 				return ret;
8535d4f98a2SYan Zheng 		}
8545d4f98a2SYan Zheng 	} else {
8555d4f98a2SYan Zheng 		if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
8565d4f98a2SYan Zheng 			if (root->root_key.objectid ==
8575d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID)
85866d7e7f0SArne Jansen 				ret = btrfs_inc_ref(trans, root, cow, 1, 1);
8595d4f98a2SYan Zheng 			else
86066d7e7f0SArne Jansen 				ret = btrfs_inc_ref(trans, root, cow, 0, 1);
86179787eaaSJeff Mahoney 			BUG_ON(ret); /* -ENOMEM */
86266d7e7f0SArne Jansen 			ret = btrfs_dec_ref(trans, root, buf, 1, 1);
86379787eaaSJeff Mahoney 			BUG_ON(ret); /* -ENOMEM */
8645d4f98a2SYan Zheng 		}
865f230475eSJan Schmidt 		/*
866f230475eSJan Schmidt 		 * don't log freeing in case we're freeing the root node, this
867f230475eSJan Schmidt 		 * is done by tree_mod_log_set_root_pointer later
868f230475eSJan Schmidt 		 */
869f230475eSJan Schmidt 		if (buf != root->node && btrfs_header_level(buf) != 0)
870f230475eSJan Schmidt 			tree_mod_log_free_eb(root->fs_info, buf);
8715d4f98a2SYan Zheng 		clean_tree_block(trans, root, buf);
872f0486c68SYan, Zheng 		*last_ref = 1;
8735d4f98a2SYan Zheng 	}
8745d4f98a2SYan Zheng 	return 0;
8755d4f98a2SYan Zheng }
8765d4f98a2SYan Zheng 
8775d4f98a2SYan Zheng /*
878d397712bSChris Mason  * does the dirty work in cow of a single block.  The parent block (if
879d397712bSChris Mason  * supplied) is updated to point to the new cow copy.  The new buffer is marked
880d397712bSChris Mason  * dirty and returned locked.  If you modify the block it needs to be marked
881d397712bSChris Mason  * dirty again.
882d352ac68SChris Mason  *
883d352ac68SChris Mason  * search_start -- an allocation hint for the new block
884d352ac68SChris Mason  *
885d397712bSChris Mason  * empty_size -- a hint that you plan on doing more cow.  This is the size in
886d397712bSChris Mason  * bytes the allocator should try to find free next to the block it returns.
887d397712bSChris Mason  * This is just a hint and may be ignored by the allocator.
888d352ac68SChris Mason  */
889d397712bSChris Mason static noinline int __btrfs_cow_block(struct btrfs_trans_handle *trans,
8905f39d397SChris Mason 			     struct btrfs_root *root,
8915f39d397SChris Mason 			     struct extent_buffer *buf,
8925f39d397SChris Mason 			     struct extent_buffer *parent, int parent_slot,
8935f39d397SChris Mason 			     struct extent_buffer **cow_ret,
8949fa8cfe7SChris Mason 			     u64 search_start, u64 empty_size)
8956702ed49SChris Mason {
8965d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
8975f39d397SChris Mason 	struct extent_buffer *cow;
898be1a5564SMark Fasheh 	int level, ret;
899f0486c68SYan, Zheng 	int last_ref = 0;
900925baeddSChris Mason 	int unlock_orig = 0;
9015d4f98a2SYan Zheng 	u64 parent_start;
9026702ed49SChris Mason 
903925baeddSChris Mason 	if (*cow_ret == buf)
904925baeddSChris Mason 		unlock_orig = 1;
905925baeddSChris Mason 
906b9447ef8SChris Mason 	btrfs_assert_tree_locked(buf);
907925baeddSChris Mason 
9087bb86316SChris Mason 	WARN_ON(root->ref_cows && trans->transid !=
9097bb86316SChris Mason 		root->fs_info->running_transaction->transid);
9106702ed49SChris Mason 	WARN_ON(root->ref_cows && trans->transid != root->last_trans);
9115f39d397SChris Mason 
9127bb86316SChris Mason 	level = btrfs_header_level(buf);
91331840ae1SZheng Yan 
9145d4f98a2SYan Zheng 	if (level == 0)
9155d4f98a2SYan Zheng 		btrfs_item_key(buf, &disk_key, 0);
9165d4f98a2SYan Zheng 	else
9175d4f98a2SYan Zheng 		btrfs_node_key(buf, &disk_key, 0);
9185d4f98a2SYan Zheng 
9195d4f98a2SYan Zheng 	if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) {
9205d4f98a2SYan Zheng 		if (parent)
9215d4f98a2SYan Zheng 			parent_start = parent->start;
9225d4f98a2SYan Zheng 		else
9235d4f98a2SYan Zheng 			parent_start = 0;
9245d4f98a2SYan Zheng 	} else
9255d4f98a2SYan Zheng 		parent_start = 0;
9265d4f98a2SYan Zheng 
9275d4f98a2SYan Zheng 	cow = btrfs_alloc_free_block(trans, root, buf->len, parent_start,
9285d4f98a2SYan Zheng 				     root->root_key.objectid, &disk_key,
9295581a51aSJan Schmidt 				     level, search_start, empty_size);
9306702ed49SChris Mason 	if (IS_ERR(cow))
9316702ed49SChris Mason 		return PTR_ERR(cow);
9326702ed49SChris Mason 
933b4ce94deSChris Mason 	/* cow is set to blocking by btrfs_init_new_buffer */
934b4ce94deSChris Mason 
9355f39d397SChris Mason 	copy_extent_buffer(cow, buf, 0, 0, cow->len);
936db94535dSChris Mason 	btrfs_set_header_bytenr(cow, cow->start);
9375f39d397SChris Mason 	btrfs_set_header_generation(cow, trans->transid);
9385d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
9395d4f98a2SYan Zheng 	btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
9405d4f98a2SYan Zheng 				     BTRFS_HEADER_FLAG_RELOC);
9415d4f98a2SYan Zheng 	if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
9425d4f98a2SYan Zheng 		btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
9435d4f98a2SYan Zheng 	else
9445f39d397SChris Mason 		btrfs_set_header_owner(cow, root->root_key.objectid);
9456702ed49SChris Mason 
9462b82032cSYan Zheng 	write_extent_buffer(cow, root->fs_info->fsid,
9472b82032cSYan Zheng 			    (unsigned long)btrfs_header_fsid(cow),
9482b82032cSYan Zheng 			    BTRFS_FSID_SIZE);
9492b82032cSYan Zheng 
950be1a5564SMark Fasheh 	ret = update_ref_for_cow(trans, root, buf, cow, &last_ref);
951b68dc2a9SMark Fasheh 	if (ret) {
95279787eaaSJeff Mahoney 		btrfs_abort_transaction(trans, root, ret);
953b68dc2a9SMark Fasheh 		return ret;
954b68dc2a9SMark Fasheh 	}
9551a40e23bSZheng Yan 
9563fd0a558SYan, Zheng 	if (root->ref_cows)
9573fd0a558SYan, Zheng 		btrfs_reloc_cow_block(trans, root, buf, cow);
9583fd0a558SYan, Zheng 
9596702ed49SChris Mason 	if (buf == root->node) {
960925baeddSChris Mason 		WARN_ON(parent && parent != buf);
9615d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
9625d4f98a2SYan Zheng 		    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
9635d4f98a2SYan Zheng 			parent_start = buf->start;
9645d4f98a2SYan Zheng 		else
9655d4f98a2SYan Zheng 			parent_start = 0;
966925baeddSChris Mason 
9675f39d397SChris Mason 		extent_buffer_get(cow);
968f230475eSJan Schmidt 		tree_mod_log_set_root_pointer(root, cow);
969240f62c8SChris Mason 		rcu_assign_pointer(root->node, cow);
970925baeddSChris Mason 
971f0486c68SYan, Zheng 		btrfs_free_tree_block(trans, root, buf, parent_start,
9725581a51aSJan Schmidt 				      last_ref);
9735f39d397SChris Mason 		free_extent_buffer(buf);
9740b86a832SChris Mason 		add_root_to_dirty_list(root);
9756702ed49SChris Mason 	} else {
9765d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
9775d4f98a2SYan Zheng 			parent_start = parent->start;
9785d4f98a2SYan Zheng 		else
9795d4f98a2SYan Zheng 			parent_start = 0;
9805d4f98a2SYan Zheng 
9815d4f98a2SYan Zheng 		WARN_ON(trans->transid != btrfs_header_generation(parent));
982f230475eSJan Schmidt 		tree_mod_log_insert_key(root->fs_info, parent, parent_slot,
983f230475eSJan Schmidt 					MOD_LOG_KEY_REPLACE);
9845f39d397SChris Mason 		btrfs_set_node_blockptr(parent, parent_slot,
985db94535dSChris Mason 					cow->start);
98674493f7aSChris Mason 		btrfs_set_node_ptr_generation(parent, parent_slot,
98774493f7aSChris Mason 					      trans->transid);
9886702ed49SChris Mason 		btrfs_mark_buffer_dirty(parent);
989f0486c68SYan, Zheng 		btrfs_free_tree_block(trans, root, buf, parent_start,
9905581a51aSJan Schmidt 				      last_ref);
9916702ed49SChris Mason 	}
992925baeddSChris Mason 	if (unlock_orig)
993925baeddSChris Mason 		btrfs_tree_unlock(buf);
9943083ee2eSJosef Bacik 	free_extent_buffer_stale(buf);
9956702ed49SChris Mason 	btrfs_mark_buffer_dirty(cow);
9966702ed49SChris Mason 	*cow_ret = cow;
9976702ed49SChris Mason 	return 0;
9986702ed49SChris Mason }
9996702ed49SChris Mason 
10005d9e75c4SJan Schmidt /*
10015d9e75c4SJan Schmidt  * returns the logical address of the oldest predecessor of the given root.
10025d9e75c4SJan Schmidt  * entries older than time_seq are ignored.
10035d9e75c4SJan Schmidt  */
10045d9e75c4SJan Schmidt static struct tree_mod_elem *
10055d9e75c4SJan Schmidt __tree_mod_log_oldest_root(struct btrfs_fs_info *fs_info,
10065d9e75c4SJan Schmidt 			   struct btrfs_root *root, u64 time_seq)
10075d9e75c4SJan Schmidt {
10085d9e75c4SJan Schmidt 	struct tree_mod_elem *tm;
10095d9e75c4SJan Schmidt 	struct tree_mod_elem *found = NULL;
10105d9e75c4SJan Schmidt 	u64 root_logical = root->node->start;
10115d9e75c4SJan Schmidt 	int looped = 0;
10125d9e75c4SJan Schmidt 
10135d9e75c4SJan Schmidt 	if (!time_seq)
10145d9e75c4SJan Schmidt 		return 0;
10155d9e75c4SJan Schmidt 
10165d9e75c4SJan Schmidt 	/*
10175d9e75c4SJan Schmidt 	 * the very last operation that's logged for a root is the replacement
10185d9e75c4SJan Schmidt 	 * operation (if it is replaced at all). this has the index of the *new*
10195d9e75c4SJan Schmidt 	 * root, making it the very first operation that's logged for this root.
10205d9e75c4SJan Schmidt 	 */
10215d9e75c4SJan Schmidt 	while (1) {
10225d9e75c4SJan Schmidt 		tm = tree_mod_log_search_oldest(fs_info, root_logical,
10235d9e75c4SJan Schmidt 						time_seq);
10245d9e75c4SJan Schmidt 		if (!looped && !tm)
10255d9e75c4SJan Schmidt 			return 0;
10265d9e75c4SJan Schmidt 		/*
102728da9fb4SJan Schmidt 		 * if there are no tree operation for the oldest root, we simply
102828da9fb4SJan Schmidt 		 * return it. this should only happen if that (old) root is at
102928da9fb4SJan Schmidt 		 * level 0.
10305d9e75c4SJan Schmidt 		 */
103128da9fb4SJan Schmidt 		if (!tm)
103228da9fb4SJan Schmidt 			break;
10335d9e75c4SJan Schmidt 
103428da9fb4SJan Schmidt 		/*
103528da9fb4SJan Schmidt 		 * if there's an operation that's not a root replacement, we
103628da9fb4SJan Schmidt 		 * found the oldest version of our root. normally, we'll find a
103728da9fb4SJan Schmidt 		 * MOD_LOG_KEY_REMOVE_WHILE_FREEING operation here.
103828da9fb4SJan Schmidt 		 */
10395d9e75c4SJan Schmidt 		if (tm->op != MOD_LOG_ROOT_REPLACE)
10405d9e75c4SJan Schmidt 			break;
10415d9e75c4SJan Schmidt 
10425d9e75c4SJan Schmidt 		found = tm;
10435d9e75c4SJan Schmidt 		root_logical = tm->old_root.logical;
10445d9e75c4SJan Schmidt 		BUG_ON(root_logical == root->node->start);
10455d9e75c4SJan Schmidt 		looped = 1;
10465d9e75c4SJan Schmidt 	}
10475d9e75c4SJan Schmidt 
1048a95236d9SJan Schmidt 	/* if there's no old root to return, return what we found instead */
1049a95236d9SJan Schmidt 	if (!found)
1050a95236d9SJan Schmidt 		found = tm;
1051a95236d9SJan Schmidt 
10525d9e75c4SJan Schmidt 	return found;
10535d9e75c4SJan Schmidt }
10545d9e75c4SJan Schmidt 
10555d9e75c4SJan Schmidt /*
10565d9e75c4SJan Schmidt  * tm is a pointer to the first operation to rewind within eb. then, all
10575d9e75c4SJan Schmidt  * previous operations will be rewinded (until we reach something older than
10585d9e75c4SJan Schmidt  * time_seq).
10595d9e75c4SJan Schmidt  */
10605d9e75c4SJan Schmidt static void
10615d9e75c4SJan Schmidt __tree_mod_log_rewind(struct extent_buffer *eb, u64 time_seq,
10625d9e75c4SJan Schmidt 		      struct tree_mod_elem *first_tm)
10635d9e75c4SJan Schmidt {
10645d9e75c4SJan Schmidt 	u32 n;
10655d9e75c4SJan Schmidt 	struct rb_node *next;
10665d9e75c4SJan Schmidt 	struct tree_mod_elem *tm = first_tm;
10675d9e75c4SJan Schmidt 	unsigned long o_dst;
10685d9e75c4SJan Schmidt 	unsigned long o_src;
10695d9e75c4SJan Schmidt 	unsigned long p_size = sizeof(struct btrfs_key_ptr);
10705d9e75c4SJan Schmidt 
10715d9e75c4SJan Schmidt 	n = btrfs_header_nritems(eb);
10725d9e75c4SJan Schmidt 	while (tm && tm->elem.seq >= time_seq) {
10735d9e75c4SJan Schmidt 		/*
10745d9e75c4SJan Schmidt 		 * all the operations are recorded with the operator used for
10755d9e75c4SJan Schmidt 		 * the modification. as we're going backwards, we do the
10765d9e75c4SJan Schmidt 		 * opposite of each operation here.
10775d9e75c4SJan Schmidt 		 */
10785d9e75c4SJan Schmidt 		switch (tm->op) {
10795d9e75c4SJan Schmidt 		case MOD_LOG_KEY_REMOVE_WHILE_FREEING:
10805d9e75c4SJan Schmidt 			BUG_ON(tm->slot < n);
10815d9e75c4SJan Schmidt 		case MOD_LOG_KEY_REMOVE_WHILE_MOVING:
10825d9e75c4SJan Schmidt 		case MOD_LOG_KEY_REMOVE:
10835d9e75c4SJan Schmidt 			btrfs_set_node_key(eb, &tm->key, tm->slot);
10845d9e75c4SJan Schmidt 			btrfs_set_node_blockptr(eb, tm->slot, tm->blockptr);
10855d9e75c4SJan Schmidt 			btrfs_set_node_ptr_generation(eb, tm->slot,
10865d9e75c4SJan Schmidt 						      tm->generation);
10875d9e75c4SJan Schmidt 			n++;
10885d9e75c4SJan Schmidt 			break;
10895d9e75c4SJan Schmidt 		case MOD_LOG_KEY_REPLACE:
10905d9e75c4SJan Schmidt 			BUG_ON(tm->slot >= n);
10915d9e75c4SJan Schmidt 			btrfs_set_node_key(eb, &tm->key, tm->slot);
10925d9e75c4SJan Schmidt 			btrfs_set_node_blockptr(eb, tm->slot, tm->blockptr);
10935d9e75c4SJan Schmidt 			btrfs_set_node_ptr_generation(eb, tm->slot,
10945d9e75c4SJan Schmidt 						      tm->generation);
10955d9e75c4SJan Schmidt 			break;
10965d9e75c4SJan Schmidt 		case MOD_LOG_KEY_ADD:
1097*19956c7eSJan Schmidt 			/* if a move operation is needed it's in the log */
10985d9e75c4SJan Schmidt 			n--;
10995d9e75c4SJan Schmidt 			break;
11005d9e75c4SJan Schmidt 		case MOD_LOG_MOVE_KEYS:
1101c3193108SJan Schmidt 			o_dst = btrfs_node_key_ptr_offset(tm->slot);
1102c3193108SJan Schmidt 			o_src = btrfs_node_key_ptr_offset(tm->move.dst_slot);
1103c3193108SJan Schmidt 			memmove_extent_buffer(eb, o_dst, o_src,
11045d9e75c4SJan Schmidt 					      tm->move.nr_items * p_size);
11055d9e75c4SJan Schmidt 			break;
11065d9e75c4SJan Schmidt 		case MOD_LOG_ROOT_REPLACE:
11075d9e75c4SJan Schmidt 			/*
11085d9e75c4SJan Schmidt 			 * this operation is special. for roots, this must be
11095d9e75c4SJan Schmidt 			 * handled explicitly before rewinding.
11105d9e75c4SJan Schmidt 			 * for non-roots, this operation may exist if the node
11115d9e75c4SJan Schmidt 			 * was a root: root A -> child B; then A gets empty and
11125d9e75c4SJan Schmidt 			 * B is promoted to the new root. in the mod log, we'll
11135d9e75c4SJan Schmidt 			 * have a root-replace operation for B, a tree block
11145d9e75c4SJan Schmidt 			 * that is no root. we simply ignore that operation.
11155d9e75c4SJan Schmidt 			 */
11165d9e75c4SJan Schmidt 			break;
11175d9e75c4SJan Schmidt 		}
11185d9e75c4SJan Schmidt 		next = rb_next(&tm->node);
11195d9e75c4SJan Schmidt 		if (!next)
11205d9e75c4SJan Schmidt 			break;
11215d9e75c4SJan Schmidt 		tm = container_of(next, struct tree_mod_elem, node);
11225d9e75c4SJan Schmidt 		if (tm->index != first_tm->index)
11235d9e75c4SJan Schmidt 			break;
11245d9e75c4SJan Schmidt 	}
11255d9e75c4SJan Schmidt 	btrfs_set_header_nritems(eb, n);
11265d9e75c4SJan Schmidt }
11275d9e75c4SJan Schmidt 
11285d9e75c4SJan Schmidt static struct extent_buffer *
11295d9e75c4SJan Schmidt tree_mod_log_rewind(struct btrfs_fs_info *fs_info, struct extent_buffer *eb,
11305d9e75c4SJan Schmidt 		    u64 time_seq)
11315d9e75c4SJan Schmidt {
11325d9e75c4SJan Schmidt 	struct extent_buffer *eb_rewin;
11335d9e75c4SJan Schmidt 	struct tree_mod_elem *tm;
11345d9e75c4SJan Schmidt 
11355d9e75c4SJan Schmidt 	if (!time_seq)
11365d9e75c4SJan Schmidt 		return eb;
11375d9e75c4SJan Schmidt 
11385d9e75c4SJan Schmidt 	if (btrfs_header_level(eb) == 0)
11395d9e75c4SJan Schmidt 		return eb;
11405d9e75c4SJan Schmidt 
11415d9e75c4SJan Schmidt 	tm = tree_mod_log_search(fs_info, eb->start, time_seq);
11425d9e75c4SJan Schmidt 	if (!tm)
11435d9e75c4SJan Schmidt 		return eb;
11445d9e75c4SJan Schmidt 
11455d9e75c4SJan Schmidt 	if (tm->op == MOD_LOG_KEY_REMOVE_WHILE_FREEING) {
11465d9e75c4SJan Schmidt 		BUG_ON(tm->slot != 0);
11475d9e75c4SJan Schmidt 		eb_rewin = alloc_dummy_extent_buffer(eb->start,
11485d9e75c4SJan Schmidt 						fs_info->tree_root->nodesize);
11495d9e75c4SJan Schmidt 		BUG_ON(!eb_rewin);
11505d9e75c4SJan Schmidt 		btrfs_set_header_bytenr(eb_rewin, eb->start);
11515d9e75c4SJan Schmidt 		btrfs_set_header_backref_rev(eb_rewin,
11525d9e75c4SJan Schmidt 					     btrfs_header_backref_rev(eb));
11535d9e75c4SJan Schmidt 		btrfs_set_header_owner(eb_rewin, btrfs_header_owner(eb));
1154c3193108SJan Schmidt 		btrfs_set_header_level(eb_rewin, btrfs_header_level(eb));
11555d9e75c4SJan Schmidt 	} else {
11565d9e75c4SJan Schmidt 		eb_rewin = btrfs_clone_extent_buffer(eb);
11575d9e75c4SJan Schmidt 		BUG_ON(!eb_rewin);
11585d9e75c4SJan Schmidt 	}
11595d9e75c4SJan Schmidt 
11605d9e75c4SJan Schmidt 	extent_buffer_get(eb_rewin);
11615d9e75c4SJan Schmidt 	free_extent_buffer(eb);
11625d9e75c4SJan Schmidt 
11635d9e75c4SJan Schmidt 	__tree_mod_log_rewind(eb_rewin, time_seq, tm);
11645d9e75c4SJan Schmidt 
11655d9e75c4SJan Schmidt 	return eb_rewin;
11665d9e75c4SJan Schmidt }
11675d9e75c4SJan Schmidt 
11688ba97a15SJan Schmidt /*
11698ba97a15SJan Schmidt  * get_old_root() rewinds the state of @root's root node to the given @time_seq
11708ba97a15SJan Schmidt  * value. If there are no changes, the current root->root_node is returned. If
11718ba97a15SJan Schmidt  * anything changed in between, there's a fresh buffer allocated on which the
11728ba97a15SJan Schmidt  * rewind operations are done. In any case, the returned buffer is read locked.
11738ba97a15SJan Schmidt  * Returns NULL on error (with no locks held).
11748ba97a15SJan Schmidt  */
11755d9e75c4SJan Schmidt static inline struct extent_buffer *
11765d9e75c4SJan Schmidt get_old_root(struct btrfs_root *root, u64 time_seq)
11775d9e75c4SJan Schmidt {
11785d9e75c4SJan Schmidt 	struct tree_mod_elem *tm;
11795d9e75c4SJan Schmidt 	struct extent_buffer *eb;
1180a95236d9SJan Schmidt 	struct tree_mod_root *old_root = NULL;
11814325edd0SChris Mason 	u64 old_generation = 0;
1182a95236d9SJan Schmidt 	u64 logical;
11835d9e75c4SJan Schmidt 
11848ba97a15SJan Schmidt 	eb = btrfs_read_lock_root_node(root);
11855d9e75c4SJan Schmidt 	tm = __tree_mod_log_oldest_root(root->fs_info, root, time_seq);
11865d9e75c4SJan Schmidt 	if (!tm)
11875d9e75c4SJan Schmidt 		return root->node;
11885d9e75c4SJan Schmidt 
1189a95236d9SJan Schmidt 	if (tm->op == MOD_LOG_ROOT_REPLACE) {
11905d9e75c4SJan Schmidt 		old_root = &tm->old_root;
11915d9e75c4SJan Schmidt 		old_generation = tm->generation;
1192a95236d9SJan Schmidt 		logical = old_root->logical;
1193a95236d9SJan Schmidt 	} else {
1194a95236d9SJan Schmidt 		logical = root->node->start;
1195a95236d9SJan Schmidt 	}
11965d9e75c4SJan Schmidt 
1197a95236d9SJan Schmidt 	tm = tree_mod_log_search(root->fs_info, logical, time_seq);
1198a95236d9SJan Schmidt 	if (old_root)
119928da9fb4SJan Schmidt 		eb = alloc_dummy_extent_buffer(logical, root->nodesize);
1200a95236d9SJan Schmidt 	else
1201a95236d9SJan Schmidt 		eb = btrfs_clone_extent_buffer(root->node);
12028ba97a15SJan Schmidt 	btrfs_tree_read_unlock(root->node);
12038ba97a15SJan Schmidt 	free_extent_buffer(root->node);
12048ba97a15SJan Schmidt 	if (!eb)
12058ba97a15SJan Schmidt 		return NULL;
12068ba97a15SJan Schmidt 	btrfs_tree_read_lock(eb);
1207a95236d9SJan Schmidt 	if (old_root) {
12085d9e75c4SJan Schmidt 		btrfs_set_header_bytenr(eb, eb->start);
12095d9e75c4SJan Schmidt 		btrfs_set_header_backref_rev(eb, BTRFS_MIXED_BACKREF_REV);
12105d9e75c4SJan Schmidt 		btrfs_set_header_owner(eb, root->root_key.objectid);
12115d9e75c4SJan Schmidt 		btrfs_set_header_level(eb, old_root->level);
12125d9e75c4SJan Schmidt 		btrfs_set_header_generation(eb, old_generation);
1213a95236d9SJan Schmidt 	}
121428da9fb4SJan Schmidt 	if (tm)
12155d9e75c4SJan Schmidt 		__tree_mod_log_rewind(eb, time_seq, tm);
121628da9fb4SJan Schmidt 	else
121728da9fb4SJan Schmidt 		WARN_ON(btrfs_header_level(eb) != 0);
12188ba97a15SJan Schmidt 	extent_buffer_get(eb);
12195d9e75c4SJan Schmidt 
12205d9e75c4SJan Schmidt 	return eb;
12215d9e75c4SJan Schmidt }
12225d9e75c4SJan Schmidt 
12235d4f98a2SYan Zheng static inline int should_cow_block(struct btrfs_trans_handle *trans,
12245d4f98a2SYan Zheng 				   struct btrfs_root *root,
12255d4f98a2SYan Zheng 				   struct extent_buffer *buf)
12265d4f98a2SYan Zheng {
1227f1ebcc74SLiu Bo 	/* ensure we can see the force_cow */
1228f1ebcc74SLiu Bo 	smp_rmb();
1229f1ebcc74SLiu Bo 
1230f1ebcc74SLiu Bo 	/*
1231f1ebcc74SLiu Bo 	 * We do not need to cow a block if
1232f1ebcc74SLiu Bo 	 * 1) this block is not created or changed in this transaction;
1233f1ebcc74SLiu Bo 	 * 2) this block does not belong to TREE_RELOC tree;
1234f1ebcc74SLiu Bo 	 * 3) the root is not forced COW.
1235f1ebcc74SLiu Bo 	 *
1236f1ebcc74SLiu Bo 	 * What is forced COW:
1237f1ebcc74SLiu Bo 	 *    when we create snapshot during commiting the transaction,
1238f1ebcc74SLiu Bo 	 *    after we've finished coping src root, we must COW the shared
1239f1ebcc74SLiu Bo 	 *    block to ensure the metadata consistency.
1240f1ebcc74SLiu Bo 	 */
12415d4f98a2SYan Zheng 	if (btrfs_header_generation(buf) == trans->transid &&
12425d4f98a2SYan Zheng 	    !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN) &&
12435d4f98a2SYan Zheng 	    !(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
1244f1ebcc74SLiu Bo 	      btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)) &&
1245f1ebcc74SLiu Bo 	    !root->force_cow)
12465d4f98a2SYan Zheng 		return 0;
12475d4f98a2SYan Zheng 	return 1;
12485d4f98a2SYan Zheng }
12495d4f98a2SYan Zheng 
1250d352ac68SChris Mason /*
1251d352ac68SChris Mason  * cows a single block, see __btrfs_cow_block for the real work.
1252d352ac68SChris Mason  * This version of it has extra checks so that a block isn't cow'd more than
1253d352ac68SChris Mason  * once per transaction, as long as it hasn't been written yet
1254d352ac68SChris Mason  */
1255d397712bSChris Mason noinline int btrfs_cow_block(struct btrfs_trans_handle *trans,
12565f39d397SChris Mason 		    struct btrfs_root *root, struct extent_buffer *buf,
12575f39d397SChris Mason 		    struct extent_buffer *parent, int parent_slot,
12589fa8cfe7SChris Mason 		    struct extent_buffer **cow_ret)
125902217ed2SChris Mason {
12606702ed49SChris Mason 	u64 search_start;
1261f510cfecSChris Mason 	int ret;
1262dc17ff8fSChris Mason 
1263ccd467d6SChris Mason 	if (trans->transaction != root->fs_info->running_transaction) {
1264d397712bSChris Mason 		printk(KERN_CRIT "trans %llu running %llu\n",
1265d397712bSChris Mason 		       (unsigned long long)trans->transid,
1266d397712bSChris Mason 		       (unsigned long long)
1267ccd467d6SChris Mason 		       root->fs_info->running_transaction->transid);
1268ccd467d6SChris Mason 		WARN_ON(1);
1269ccd467d6SChris Mason 	}
1270ccd467d6SChris Mason 	if (trans->transid != root->fs_info->generation) {
1271d397712bSChris Mason 		printk(KERN_CRIT "trans %llu running %llu\n",
1272d397712bSChris Mason 		       (unsigned long long)trans->transid,
1273d397712bSChris Mason 		       (unsigned long long)root->fs_info->generation);
1274ccd467d6SChris Mason 		WARN_ON(1);
1275ccd467d6SChris Mason 	}
1276dc17ff8fSChris Mason 
12775d4f98a2SYan Zheng 	if (!should_cow_block(trans, root, buf)) {
127802217ed2SChris Mason 		*cow_ret = buf;
127902217ed2SChris Mason 		return 0;
128002217ed2SChris Mason 	}
1281c487685dSChris Mason 
12820b86a832SChris Mason 	search_start = buf->start & ~((u64)(1024 * 1024 * 1024) - 1);
1283b4ce94deSChris Mason 
1284b4ce94deSChris Mason 	if (parent)
1285b4ce94deSChris Mason 		btrfs_set_lock_blocking(parent);
1286b4ce94deSChris Mason 	btrfs_set_lock_blocking(buf);
1287b4ce94deSChris Mason 
1288f510cfecSChris Mason 	ret = __btrfs_cow_block(trans, root, buf, parent,
12899fa8cfe7SChris Mason 				 parent_slot, cow_ret, search_start, 0);
12901abe9b8aSliubo 
12911abe9b8aSliubo 	trace_btrfs_cow_block(root, buf, *cow_ret);
12921abe9b8aSliubo 
1293f510cfecSChris Mason 	return ret;
12942c90e5d6SChris Mason }
12956702ed49SChris Mason 
1296d352ac68SChris Mason /*
1297d352ac68SChris Mason  * helper function for defrag to decide if two blocks pointed to by a
1298d352ac68SChris Mason  * node are actually close by
1299d352ac68SChris Mason  */
13006b80053dSChris Mason static int close_blocks(u64 blocknr, u64 other, u32 blocksize)
13016702ed49SChris Mason {
13026b80053dSChris Mason 	if (blocknr < other && other - (blocknr + blocksize) < 32768)
13036702ed49SChris Mason 		return 1;
13046b80053dSChris Mason 	if (blocknr > other && blocknr - (other + blocksize) < 32768)
13056702ed49SChris Mason 		return 1;
130602217ed2SChris Mason 	return 0;
130702217ed2SChris Mason }
130802217ed2SChris Mason 
1309081e9573SChris Mason /*
1310081e9573SChris Mason  * compare two keys in a memcmp fashion
1311081e9573SChris Mason  */
1312081e9573SChris Mason static int comp_keys(struct btrfs_disk_key *disk, struct btrfs_key *k2)
1313081e9573SChris Mason {
1314081e9573SChris Mason 	struct btrfs_key k1;
1315081e9573SChris Mason 
1316081e9573SChris Mason 	btrfs_disk_key_to_cpu(&k1, disk);
1317081e9573SChris Mason 
131820736abaSDiego Calleja 	return btrfs_comp_cpu_keys(&k1, k2);
1319081e9573SChris Mason }
1320081e9573SChris Mason 
1321f3465ca4SJosef Bacik /*
1322f3465ca4SJosef Bacik  * same as comp_keys only with two btrfs_key's
1323f3465ca4SJosef Bacik  */
13245d4f98a2SYan Zheng int btrfs_comp_cpu_keys(struct btrfs_key *k1, struct btrfs_key *k2)
1325f3465ca4SJosef Bacik {
1326f3465ca4SJosef Bacik 	if (k1->objectid > k2->objectid)
1327f3465ca4SJosef Bacik 		return 1;
1328f3465ca4SJosef Bacik 	if (k1->objectid < k2->objectid)
1329f3465ca4SJosef Bacik 		return -1;
1330f3465ca4SJosef Bacik 	if (k1->type > k2->type)
1331f3465ca4SJosef Bacik 		return 1;
1332f3465ca4SJosef Bacik 	if (k1->type < k2->type)
1333f3465ca4SJosef Bacik 		return -1;
1334f3465ca4SJosef Bacik 	if (k1->offset > k2->offset)
1335f3465ca4SJosef Bacik 		return 1;
1336f3465ca4SJosef Bacik 	if (k1->offset < k2->offset)
1337f3465ca4SJosef Bacik 		return -1;
1338f3465ca4SJosef Bacik 	return 0;
1339f3465ca4SJosef Bacik }
1340081e9573SChris Mason 
1341d352ac68SChris Mason /*
1342d352ac68SChris Mason  * this is used by the defrag code to go through all the
1343d352ac68SChris Mason  * leaves pointed to by a node and reallocate them so that
1344d352ac68SChris Mason  * disk order is close to key order
1345d352ac68SChris Mason  */
13466702ed49SChris Mason int btrfs_realloc_node(struct btrfs_trans_handle *trans,
13475f39d397SChris Mason 		       struct btrfs_root *root, struct extent_buffer *parent,
1348a6b6e75eSChris Mason 		       int start_slot, int cache_only, u64 *last_ret,
1349a6b6e75eSChris Mason 		       struct btrfs_key *progress)
13506702ed49SChris Mason {
13516b80053dSChris Mason 	struct extent_buffer *cur;
13526702ed49SChris Mason 	u64 blocknr;
1353ca7a79adSChris Mason 	u64 gen;
1354e9d0b13bSChris Mason 	u64 search_start = *last_ret;
1355e9d0b13bSChris Mason 	u64 last_block = 0;
13566702ed49SChris Mason 	u64 other;
13576702ed49SChris Mason 	u32 parent_nritems;
13586702ed49SChris Mason 	int end_slot;
13596702ed49SChris Mason 	int i;
13606702ed49SChris Mason 	int err = 0;
1361f2183bdeSChris Mason 	int parent_level;
13626b80053dSChris Mason 	int uptodate;
13636b80053dSChris Mason 	u32 blocksize;
1364081e9573SChris Mason 	int progress_passed = 0;
1365081e9573SChris Mason 	struct btrfs_disk_key disk_key;
13666702ed49SChris Mason 
13675708b959SChris Mason 	parent_level = btrfs_header_level(parent);
13685708b959SChris Mason 	if (cache_only && parent_level != 1)
13695708b959SChris Mason 		return 0;
13705708b959SChris Mason 
1371d397712bSChris Mason 	if (trans->transaction != root->fs_info->running_transaction)
13726702ed49SChris Mason 		WARN_ON(1);
1373d397712bSChris Mason 	if (trans->transid != root->fs_info->generation)
13746702ed49SChris Mason 		WARN_ON(1);
137586479a04SChris Mason 
13766b80053dSChris Mason 	parent_nritems = btrfs_header_nritems(parent);
13776b80053dSChris Mason 	blocksize = btrfs_level_size(root, parent_level - 1);
13786702ed49SChris Mason 	end_slot = parent_nritems;
13796702ed49SChris Mason 
13806702ed49SChris Mason 	if (parent_nritems == 1)
13816702ed49SChris Mason 		return 0;
13826702ed49SChris Mason 
1383b4ce94deSChris Mason 	btrfs_set_lock_blocking(parent);
1384b4ce94deSChris Mason 
13856702ed49SChris Mason 	for (i = start_slot; i < end_slot; i++) {
13866702ed49SChris Mason 		int close = 1;
1387a6b6e75eSChris Mason 
1388081e9573SChris Mason 		btrfs_node_key(parent, &disk_key, i);
1389081e9573SChris Mason 		if (!progress_passed && comp_keys(&disk_key, progress) < 0)
1390081e9573SChris Mason 			continue;
1391081e9573SChris Mason 
1392081e9573SChris Mason 		progress_passed = 1;
13936b80053dSChris Mason 		blocknr = btrfs_node_blockptr(parent, i);
1394ca7a79adSChris Mason 		gen = btrfs_node_ptr_generation(parent, i);
1395e9d0b13bSChris Mason 		if (last_block == 0)
1396e9d0b13bSChris Mason 			last_block = blocknr;
13975708b959SChris Mason 
13986702ed49SChris Mason 		if (i > 0) {
13996b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i - 1);
14006b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
14016702ed49SChris Mason 		}
14020ef3e66bSChris Mason 		if (!close && i < end_slot - 2) {
14036b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i + 1);
14046b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
14056702ed49SChris Mason 		}
1406e9d0b13bSChris Mason 		if (close) {
1407e9d0b13bSChris Mason 			last_block = blocknr;
14086702ed49SChris Mason 			continue;
1409e9d0b13bSChris Mason 		}
14106702ed49SChris Mason 
14116b80053dSChris Mason 		cur = btrfs_find_tree_block(root, blocknr, blocksize);
14126b80053dSChris Mason 		if (cur)
1413b9fab919SChris Mason 			uptodate = btrfs_buffer_uptodate(cur, gen, 0);
14146b80053dSChris Mason 		else
14156b80053dSChris Mason 			uptodate = 0;
14165708b959SChris Mason 		if (!cur || !uptodate) {
14176702ed49SChris Mason 			if (cache_only) {
14186b80053dSChris Mason 				free_extent_buffer(cur);
14196702ed49SChris Mason 				continue;
14206702ed49SChris Mason 			}
14216b80053dSChris Mason 			if (!cur) {
14226b80053dSChris Mason 				cur = read_tree_block(root, blocknr,
1423ca7a79adSChris Mason 							 blocksize, gen);
142497d9a8a4STsutomu Itoh 				if (!cur)
142597d9a8a4STsutomu Itoh 					return -EIO;
14266b80053dSChris Mason 			} else if (!uptodate) {
1427018642a1STsutomu Itoh 				err = btrfs_read_buffer(cur, gen);
1428018642a1STsutomu Itoh 				if (err) {
1429018642a1STsutomu Itoh 					free_extent_buffer(cur);
1430018642a1STsutomu Itoh 					return err;
1431018642a1STsutomu Itoh 				}
14326702ed49SChris Mason 			}
1433f2183bdeSChris Mason 		}
1434e9d0b13bSChris Mason 		if (search_start == 0)
14356b80053dSChris Mason 			search_start = last_block;
1436e9d0b13bSChris Mason 
1437e7a84565SChris Mason 		btrfs_tree_lock(cur);
1438b4ce94deSChris Mason 		btrfs_set_lock_blocking(cur);
14396b80053dSChris Mason 		err = __btrfs_cow_block(trans, root, cur, parent, i,
1440e7a84565SChris Mason 					&cur, search_start,
14416b80053dSChris Mason 					min(16 * blocksize,
14429fa8cfe7SChris Mason 					    (end_slot - i) * blocksize));
1443252c38f0SYan 		if (err) {
1444e7a84565SChris Mason 			btrfs_tree_unlock(cur);
14456b80053dSChris Mason 			free_extent_buffer(cur);
14466702ed49SChris Mason 			break;
1447252c38f0SYan 		}
1448e7a84565SChris Mason 		search_start = cur->start;
1449e7a84565SChris Mason 		last_block = cur->start;
1450f2183bdeSChris Mason 		*last_ret = search_start;
1451e7a84565SChris Mason 		btrfs_tree_unlock(cur);
1452e7a84565SChris Mason 		free_extent_buffer(cur);
14536702ed49SChris Mason 	}
14546702ed49SChris Mason 	return err;
14556702ed49SChris Mason }
14566702ed49SChris Mason 
145774123bd7SChris Mason /*
145874123bd7SChris Mason  * The leaf data grows from end-to-front in the node.
145974123bd7SChris Mason  * this returns the address of the start of the last item,
146074123bd7SChris Mason  * which is the stop of the leaf data stack
146174123bd7SChris Mason  */
1462123abc88SChris Mason static inline unsigned int leaf_data_end(struct btrfs_root *root,
14635f39d397SChris Mason 					 struct extent_buffer *leaf)
1464be0e5c09SChris Mason {
14655f39d397SChris Mason 	u32 nr = btrfs_header_nritems(leaf);
1466be0e5c09SChris Mason 	if (nr == 0)
1467123abc88SChris Mason 		return BTRFS_LEAF_DATA_SIZE(root);
14685f39d397SChris Mason 	return btrfs_item_offset_nr(leaf, nr - 1);
1469be0e5c09SChris Mason }
1470be0e5c09SChris Mason 
1471aa5d6bedSChris Mason 
147274123bd7SChris Mason /*
14735f39d397SChris Mason  * search for key in the extent_buffer.  The items start at offset p,
14745f39d397SChris Mason  * and they are item_size apart.  There are 'max' items in p.
14755f39d397SChris Mason  *
147674123bd7SChris Mason  * the slot in the array is returned via slot, and it points to
147774123bd7SChris Mason  * the place where you would insert key if it is not found in
147874123bd7SChris Mason  * the array.
147974123bd7SChris Mason  *
148074123bd7SChris Mason  * slot may point to max if the key is bigger than all of the keys
148174123bd7SChris Mason  */
1482e02119d5SChris Mason static noinline int generic_bin_search(struct extent_buffer *eb,
1483e02119d5SChris Mason 				       unsigned long p,
14845f39d397SChris Mason 				       int item_size, struct btrfs_key *key,
1485be0e5c09SChris Mason 				       int max, int *slot)
1486be0e5c09SChris Mason {
1487be0e5c09SChris Mason 	int low = 0;
1488be0e5c09SChris Mason 	int high = max;
1489be0e5c09SChris Mason 	int mid;
1490be0e5c09SChris Mason 	int ret;
1491479965d6SChris Mason 	struct btrfs_disk_key *tmp = NULL;
14925f39d397SChris Mason 	struct btrfs_disk_key unaligned;
14935f39d397SChris Mason 	unsigned long offset;
14945f39d397SChris Mason 	char *kaddr = NULL;
14955f39d397SChris Mason 	unsigned long map_start = 0;
14965f39d397SChris Mason 	unsigned long map_len = 0;
1497479965d6SChris Mason 	int err;
1498be0e5c09SChris Mason 
1499be0e5c09SChris Mason 	while (low < high) {
1500be0e5c09SChris Mason 		mid = (low + high) / 2;
15015f39d397SChris Mason 		offset = p + mid * item_size;
15025f39d397SChris Mason 
1503a6591715SChris Mason 		if (!kaddr || offset < map_start ||
15045f39d397SChris Mason 		    (offset + sizeof(struct btrfs_disk_key)) >
15055f39d397SChris Mason 		    map_start + map_len) {
1506934d375bSChris Mason 
1507934d375bSChris Mason 			err = map_private_extent_buffer(eb, offset,
1508479965d6SChris Mason 						sizeof(struct btrfs_disk_key),
1509a6591715SChris Mason 						&kaddr, &map_start, &map_len);
15105f39d397SChris Mason 
1511479965d6SChris Mason 			if (!err) {
1512479965d6SChris Mason 				tmp = (struct btrfs_disk_key *)(kaddr + offset -
1513479965d6SChris Mason 							map_start);
1514479965d6SChris Mason 			} else {
15155f39d397SChris Mason 				read_extent_buffer(eb, &unaligned,
15165f39d397SChris Mason 						   offset, sizeof(unaligned));
15175f39d397SChris Mason 				tmp = &unaligned;
1518479965d6SChris Mason 			}
1519479965d6SChris Mason 
15205f39d397SChris Mason 		} else {
15215f39d397SChris Mason 			tmp = (struct btrfs_disk_key *)(kaddr + offset -
15225f39d397SChris Mason 							map_start);
15235f39d397SChris Mason 		}
1524be0e5c09SChris Mason 		ret = comp_keys(tmp, key);
1525be0e5c09SChris Mason 
1526be0e5c09SChris Mason 		if (ret < 0)
1527be0e5c09SChris Mason 			low = mid + 1;
1528be0e5c09SChris Mason 		else if (ret > 0)
1529be0e5c09SChris Mason 			high = mid;
1530be0e5c09SChris Mason 		else {
1531be0e5c09SChris Mason 			*slot = mid;
1532be0e5c09SChris Mason 			return 0;
1533be0e5c09SChris Mason 		}
1534be0e5c09SChris Mason 	}
1535be0e5c09SChris Mason 	*slot = low;
1536be0e5c09SChris Mason 	return 1;
1537be0e5c09SChris Mason }
1538be0e5c09SChris Mason 
153997571fd0SChris Mason /*
154097571fd0SChris Mason  * simple bin_search frontend that does the right thing for
154197571fd0SChris Mason  * leaves vs nodes
154297571fd0SChris Mason  */
15435f39d397SChris Mason static int bin_search(struct extent_buffer *eb, struct btrfs_key *key,
15445f39d397SChris Mason 		      int level, int *slot)
1545be0e5c09SChris Mason {
1546f775738fSWang Sheng-Hui 	if (level == 0)
15475f39d397SChris Mason 		return generic_bin_search(eb,
15485f39d397SChris Mason 					  offsetof(struct btrfs_leaf, items),
15490783fcfcSChris Mason 					  sizeof(struct btrfs_item),
15505f39d397SChris Mason 					  key, btrfs_header_nritems(eb),
15517518a238SChris Mason 					  slot);
1552f775738fSWang Sheng-Hui 	else
15535f39d397SChris Mason 		return generic_bin_search(eb,
15545f39d397SChris Mason 					  offsetof(struct btrfs_node, ptrs),
1555123abc88SChris Mason 					  sizeof(struct btrfs_key_ptr),
15565f39d397SChris Mason 					  key, btrfs_header_nritems(eb),
15577518a238SChris Mason 					  slot);
1558be0e5c09SChris Mason }
1559be0e5c09SChris Mason 
15605d4f98a2SYan Zheng int btrfs_bin_search(struct extent_buffer *eb, struct btrfs_key *key,
15615d4f98a2SYan Zheng 		     int level, int *slot)
15625d4f98a2SYan Zheng {
15635d4f98a2SYan Zheng 	return bin_search(eb, key, level, slot);
15645d4f98a2SYan Zheng }
15655d4f98a2SYan Zheng 
1566f0486c68SYan, Zheng static void root_add_used(struct btrfs_root *root, u32 size)
1567f0486c68SYan, Zheng {
1568f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
1569f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
1570f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) + size);
1571f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
1572f0486c68SYan, Zheng }
1573f0486c68SYan, Zheng 
1574f0486c68SYan, Zheng static void root_sub_used(struct btrfs_root *root, u32 size)
1575f0486c68SYan, Zheng {
1576f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
1577f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
1578f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) - size);
1579f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
1580f0486c68SYan, Zheng }
1581f0486c68SYan, Zheng 
1582d352ac68SChris Mason /* given a node and slot number, this reads the blocks it points to.  The
1583d352ac68SChris Mason  * extent buffer is returned with a reference taken (but unlocked).
1584d352ac68SChris Mason  * NULL is returned on error.
1585d352ac68SChris Mason  */
1586e02119d5SChris Mason static noinline struct extent_buffer *read_node_slot(struct btrfs_root *root,
15875f39d397SChris Mason 				   struct extent_buffer *parent, int slot)
1588bb803951SChris Mason {
1589ca7a79adSChris Mason 	int level = btrfs_header_level(parent);
1590bb803951SChris Mason 	if (slot < 0)
1591bb803951SChris Mason 		return NULL;
15925f39d397SChris Mason 	if (slot >= btrfs_header_nritems(parent))
1593bb803951SChris Mason 		return NULL;
1594ca7a79adSChris Mason 
1595ca7a79adSChris Mason 	BUG_ON(level == 0);
1596ca7a79adSChris Mason 
1597db94535dSChris Mason 	return read_tree_block(root, btrfs_node_blockptr(parent, slot),
1598ca7a79adSChris Mason 		       btrfs_level_size(root, level - 1),
1599ca7a79adSChris Mason 		       btrfs_node_ptr_generation(parent, slot));
1600bb803951SChris Mason }
1601bb803951SChris Mason 
1602d352ac68SChris Mason /*
1603d352ac68SChris Mason  * node level balancing, used to make sure nodes are in proper order for
1604d352ac68SChris Mason  * item deletion.  We balance from the top down, so we have to make sure
1605d352ac68SChris Mason  * that a deletion won't leave an node completely empty later on.
1606d352ac68SChris Mason  */
1607e02119d5SChris Mason static noinline int balance_level(struct btrfs_trans_handle *trans,
160898ed5174SChris Mason 			 struct btrfs_root *root,
160998ed5174SChris Mason 			 struct btrfs_path *path, int level)
1610bb803951SChris Mason {
16115f39d397SChris Mason 	struct extent_buffer *right = NULL;
16125f39d397SChris Mason 	struct extent_buffer *mid;
16135f39d397SChris Mason 	struct extent_buffer *left = NULL;
16145f39d397SChris Mason 	struct extent_buffer *parent = NULL;
1615bb803951SChris Mason 	int ret = 0;
1616bb803951SChris Mason 	int wret;
1617bb803951SChris Mason 	int pslot;
1618bb803951SChris Mason 	int orig_slot = path->slots[level];
161979f95c82SChris Mason 	u64 orig_ptr;
1620bb803951SChris Mason 
1621bb803951SChris Mason 	if (level == 0)
1622bb803951SChris Mason 		return 0;
1623bb803951SChris Mason 
16245f39d397SChris Mason 	mid = path->nodes[level];
1625b4ce94deSChris Mason 
1626bd681513SChris Mason 	WARN_ON(path->locks[level] != BTRFS_WRITE_LOCK &&
1627bd681513SChris Mason 		path->locks[level] != BTRFS_WRITE_LOCK_BLOCKING);
16287bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
16297bb86316SChris Mason 
16301d4f8a0cSChris Mason 	orig_ptr = btrfs_node_blockptr(mid, orig_slot);
163179f95c82SChris Mason 
1632a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
16335f39d397SChris Mason 		parent = path->nodes[level + 1];
1634bb803951SChris Mason 		pslot = path->slots[level + 1];
1635a05a9bb1SLi Zefan 	}
1636bb803951SChris Mason 
163740689478SChris Mason 	/*
163840689478SChris Mason 	 * deal with the case where there is only one pointer in the root
163940689478SChris Mason 	 * by promoting the node below to a root
164040689478SChris Mason 	 */
16415f39d397SChris Mason 	if (!parent) {
16425f39d397SChris Mason 		struct extent_buffer *child;
1643bb803951SChris Mason 
16445f39d397SChris Mason 		if (btrfs_header_nritems(mid) != 1)
1645bb803951SChris Mason 			return 0;
1646bb803951SChris Mason 
1647bb803951SChris Mason 		/* promote the child to a root */
16485f39d397SChris Mason 		child = read_node_slot(root, mid, 0);
1649305a26afSMark Fasheh 		if (!child) {
1650305a26afSMark Fasheh 			ret = -EROFS;
1651305a26afSMark Fasheh 			btrfs_std_error(root->fs_info, ret);
1652305a26afSMark Fasheh 			goto enospc;
1653305a26afSMark Fasheh 		}
1654305a26afSMark Fasheh 
1655925baeddSChris Mason 		btrfs_tree_lock(child);
1656b4ce94deSChris Mason 		btrfs_set_lock_blocking(child);
16579fa8cfe7SChris Mason 		ret = btrfs_cow_block(trans, root, child, mid, 0, &child);
1658f0486c68SYan, Zheng 		if (ret) {
1659f0486c68SYan, Zheng 			btrfs_tree_unlock(child);
1660f0486c68SYan, Zheng 			free_extent_buffer(child);
1661f0486c68SYan, Zheng 			goto enospc;
1662f0486c68SYan, Zheng 		}
16632f375ab9SYan 
1664f230475eSJan Schmidt 		tree_mod_log_set_root_pointer(root, child);
1665240f62c8SChris Mason 		rcu_assign_pointer(root->node, child);
1666925baeddSChris Mason 
16670b86a832SChris Mason 		add_root_to_dirty_list(root);
1668925baeddSChris Mason 		btrfs_tree_unlock(child);
1669b4ce94deSChris Mason 
1670925baeddSChris Mason 		path->locks[level] = 0;
1671bb803951SChris Mason 		path->nodes[level] = NULL;
16725f39d397SChris Mason 		clean_tree_block(trans, root, mid);
1673925baeddSChris Mason 		btrfs_tree_unlock(mid);
1674bb803951SChris Mason 		/* once for the path */
16755f39d397SChris Mason 		free_extent_buffer(mid);
1676f0486c68SYan, Zheng 
1677f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
16785581a51aSJan Schmidt 		btrfs_free_tree_block(trans, root, mid, 0, 1);
1679bb803951SChris Mason 		/* once for the root ptr */
16803083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
1681f0486c68SYan, Zheng 		return 0;
1682bb803951SChris Mason 	}
16835f39d397SChris Mason 	if (btrfs_header_nritems(mid) >
1684123abc88SChris Mason 	    BTRFS_NODEPTRS_PER_BLOCK(root) / 4)
1685bb803951SChris Mason 		return 0;
1686bb803951SChris Mason 
16875f39d397SChris Mason 	left = read_node_slot(root, parent, pslot - 1);
16885f39d397SChris Mason 	if (left) {
1689925baeddSChris Mason 		btrfs_tree_lock(left);
1690b4ce94deSChris Mason 		btrfs_set_lock_blocking(left);
16915f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, left,
16929fa8cfe7SChris Mason 				       parent, pslot - 1, &left);
169354aa1f4dSChris Mason 		if (wret) {
169454aa1f4dSChris Mason 			ret = wret;
169554aa1f4dSChris Mason 			goto enospc;
169654aa1f4dSChris Mason 		}
16972cc58cf2SChris Mason 	}
16985f39d397SChris Mason 	right = read_node_slot(root, parent, pslot + 1);
16995f39d397SChris Mason 	if (right) {
1700925baeddSChris Mason 		btrfs_tree_lock(right);
1701b4ce94deSChris Mason 		btrfs_set_lock_blocking(right);
17025f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, right,
17039fa8cfe7SChris Mason 				       parent, pslot + 1, &right);
17042cc58cf2SChris Mason 		if (wret) {
17052cc58cf2SChris Mason 			ret = wret;
17062cc58cf2SChris Mason 			goto enospc;
17072cc58cf2SChris Mason 		}
17082cc58cf2SChris Mason 	}
17092cc58cf2SChris Mason 
17102cc58cf2SChris Mason 	/* first, try to make some room in the middle buffer */
17115f39d397SChris Mason 	if (left) {
17125f39d397SChris Mason 		orig_slot += btrfs_header_nritems(left);
1713bce4eae9SChris Mason 		wret = push_node_left(trans, root, left, mid, 1);
171479f95c82SChris Mason 		if (wret < 0)
171579f95c82SChris Mason 			ret = wret;
1716bb803951SChris Mason 	}
171779f95c82SChris Mason 
171879f95c82SChris Mason 	/*
171979f95c82SChris Mason 	 * then try to empty the right most buffer into the middle
172079f95c82SChris Mason 	 */
17215f39d397SChris Mason 	if (right) {
1722971a1f66SChris Mason 		wret = push_node_left(trans, root, mid, right, 1);
172354aa1f4dSChris Mason 		if (wret < 0 && wret != -ENOSPC)
172479f95c82SChris Mason 			ret = wret;
17255f39d397SChris Mason 		if (btrfs_header_nritems(right) == 0) {
17265f39d397SChris Mason 			clean_tree_block(trans, root, right);
1727925baeddSChris Mason 			btrfs_tree_unlock(right);
1728f3ea38daSJan Schmidt 			del_ptr(trans, root, path, level + 1, pslot + 1, 1);
1729f0486c68SYan, Zheng 			root_sub_used(root, right->len);
17305581a51aSJan Schmidt 			btrfs_free_tree_block(trans, root, right, 0, 1);
17313083ee2eSJosef Bacik 			free_extent_buffer_stale(right);
1732f0486c68SYan, Zheng 			right = NULL;
1733bb803951SChris Mason 		} else {
17345f39d397SChris Mason 			struct btrfs_disk_key right_key;
17355f39d397SChris Mason 			btrfs_node_key(right, &right_key, 0);
1736f230475eSJan Schmidt 			tree_mod_log_set_node_key(root->fs_info, parent,
1737f230475eSJan Schmidt 						  &right_key, pslot + 1, 0);
17385f39d397SChris Mason 			btrfs_set_node_key(parent, &right_key, pslot + 1);
17395f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
1740bb803951SChris Mason 		}
1741bb803951SChris Mason 	}
17425f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 1) {
174379f95c82SChris Mason 		/*
174479f95c82SChris Mason 		 * we're not allowed to leave a node with one item in the
174579f95c82SChris Mason 		 * tree during a delete.  A deletion from lower in the tree
174679f95c82SChris Mason 		 * could try to delete the only pointer in this node.
174779f95c82SChris Mason 		 * So, pull some keys from the left.
174879f95c82SChris Mason 		 * There has to be a left pointer at this point because
174979f95c82SChris Mason 		 * otherwise we would have pulled some pointers from the
175079f95c82SChris Mason 		 * right
175179f95c82SChris Mason 		 */
1752305a26afSMark Fasheh 		if (!left) {
1753305a26afSMark Fasheh 			ret = -EROFS;
1754305a26afSMark Fasheh 			btrfs_std_error(root->fs_info, ret);
1755305a26afSMark Fasheh 			goto enospc;
1756305a26afSMark Fasheh 		}
17575f39d397SChris Mason 		wret = balance_node_right(trans, root, mid, left);
175854aa1f4dSChris Mason 		if (wret < 0) {
175979f95c82SChris Mason 			ret = wret;
176054aa1f4dSChris Mason 			goto enospc;
176154aa1f4dSChris Mason 		}
1762bce4eae9SChris Mason 		if (wret == 1) {
1763bce4eae9SChris Mason 			wret = push_node_left(trans, root, left, mid, 1);
1764bce4eae9SChris Mason 			if (wret < 0)
1765bce4eae9SChris Mason 				ret = wret;
1766bce4eae9SChris Mason 		}
176779f95c82SChris Mason 		BUG_ON(wret == 1);
176879f95c82SChris Mason 	}
17695f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 0) {
17705f39d397SChris Mason 		clean_tree_block(trans, root, mid);
1771925baeddSChris Mason 		btrfs_tree_unlock(mid);
1772f3ea38daSJan Schmidt 		del_ptr(trans, root, path, level + 1, pslot, 1);
1773f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
17745581a51aSJan Schmidt 		btrfs_free_tree_block(trans, root, mid, 0, 1);
17753083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
1776f0486c68SYan, Zheng 		mid = NULL;
177779f95c82SChris Mason 	} else {
177879f95c82SChris Mason 		/* update the parent key to reflect our changes */
17795f39d397SChris Mason 		struct btrfs_disk_key mid_key;
17805f39d397SChris Mason 		btrfs_node_key(mid, &mid_key, 0);
1781f230475eSJan Schmidt 		tree_mod_log_set_node_key(root->fs_info, parent, &mid_key,
1782f230475eSJan Schmidt 					  pslot, 0);
17835f39d397SChris Mason 		btrfs_set_node_key(parent, &mid_key, pslot);
17845f39d397SChris Mason 		btrfs_mark_buffer_dirty(parent);
178579f95c82SChris Mason 	}
1786bb803951SChris Mason 
178779f95c82SChris Mason 	/* update the path */
17885f39d397SChris Mason 	if (left) {
17895f39d397SChris Mason 		if (btrfs_header_nritems(left) > orig_slot) {
17905f39d397SChris Mason 			extent_buffer_get(left);
1791925baeddSChris Mason 			/* left was locked after cow */
17925f39d397SChris Mason 			path->nodes[level] = left;
1793bb803951SChris Mason 			path->slots[level + 1] -= 1;
1794bb803951SChris Mason 			path->slots[level] = orig_slot;
1795925baeddSChris Mason 			if (mid) {
1796925baeddSChris Mason 				btrfs_tree_unlock(mid);
17975f39d397SChris Mason 				free_extent_buffer(mid);
1798925baeddSChris Mason 			}
1799bb803951SChris Mason 		} else {
18005f39d397SChris Mason 			orig_slot -= btrfs_header_nritems(left);
1801bb803951SChris Mason 			path->slots[level] = orig_slot;
1802bb803951SChris Mason 		}
1803bb803951SChris Mason 	}
180479f95c82SChris Mason 	/* double check we haven't messed things up */
1805e20d96d6SChris Mason 	if (orig_ptr !=
18065f39d397SChris Mason 	    btrfs_node_blockptr(path->nodes[level], path->slots[level]))
180779f95c82SChris Mason 		BUG();
180854aa1f4dSChris Mason enospc:
1809925baeddSChris Mason 	if (right) {
1810925baeddSChris Mason 		btrfs_tree_unlock(right);
18115f39d397SChris Mason 		free_extent_buffer(right);
1812925baeddSChris Mason 	}
1813925baeddSChris Mason 	if (left) {
1814925baeddSChris Mason 		if (path->nodes[level] != left)
1815925baeddSChris Mason 			btrfs_tree_unlock(left);
18165f39d397SChris Mason 		free_extent_buffer(left);
1817925baeddSChris Mason 	}
1818bb803951SChris Mason 	return ret;
1819bb803951SChris Mason }
1820bb803951SChris Mason 
1821d352ac68SChris Mason /* Node balancing for insertion.  Here we only split or push nodes around
1822d352ac68SChris Mason  * when they are completely full.  This is also done top down, so we
1823d352ac68SChris Mason  * have to be pessimistic.
1824d352ac68SChris Mason  */
1825d397712bSChris Mason static noinline int push_nodes_for_insert(struct btrfs_trans_handle *trans,
1826e66f709bSChris Mason 					  struct btrfs_root *root,
1827e66f709bSChris Mason 					  struct btrfs_path *path, int level)
1828e66f709bSChris Mason {
18295f39d397SChris Mason 	struct extent_buffer *right = NULL;
18305f39d397SChris Mason 	struct extent_buffer *mid;
18315f39d397SChris Mason 	struct extent_buffer *left = NULL;
18325f39d397SChris Mason 	struct extent_buffer *parent = NULL;
1833e66f709bSChris Mason 	int ret = 0;
1834e66f709bSChris Mason 	int wret;
1835e66f709bSChris Mason 	int pslot;
1836e66f709bSChris Mason 	int orig_slot = path->slots[level];
1837e66f709bSChris Mason 
1838e66f709bSChris Mason 	if (level == 0)
1839e66f709bSChris Mason 		return 1;
1840e66f709bSChris Mason 
18415f39d397SChris Mason 	mid = path->nodes[level];
18427bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
1843e66f709bSChris Mason 
1844a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
18455f39d397SChris Mason 		parent = path->nodes[level + 1];
1846e66f709bSChris Mason 		pslot = path->slots[level + 1];
1847a05a9bb1SLi Zefan 	}
1848e66f709bSChris Mason 
18495f39d397SChris Mason 	if (!parent)
1850e66f709bSChris Mason 		return 1;
1851e66f709bSChris Mason 
18525f39d397SChris Mason 	left = read_node_slot(root, parent, pslot - 1);
1853e66f709bSChris Mason 
1854e66f709bSChris Mason 	/* first, try to make some room in the middle buffer */
18555f39d397SChris Mason 	if (left) {
1856e66f709bSChris Mason 		u32 left_nr;
1857925baeddSChris Mason 
1858925baeddSChris Mason 		btrfs_tree_lock(left);
1859b4ce94deSChris Mason 		btrfs_set_lock_blocking(left);
1860b4ce94deSChris Mason 
18615f39d397SChris Mason 		left_nr = btrfs_header_nritems(left);
186233ade1f8SChris Mason 		if (left_nr >= BTRFS_NODEPTRS_PER_BLOCK(root) - 1) {
186333ade1f8SChris Mason 			wret = 1;
186433ade1f8SChris Mason 		} else {
18655f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, left, parent,
18669fa8cfe7SChris Mason 					      pslot - 1, &left);
186754aa1f4dSChris Mason 			if (ret)
186854aa1f4dSChris Mason 				wret = 1;
186954aa1f4dSChris Mason 			else {
187054aa1f4dSChris Mason 				wret = push_node_left(trans, root,
1871971a1f66SChris Mason 						      left, mid, 0);
187254aa1f4dSChris Mason 			}
187333ade1f8SChris Mason 		}
1874e66f709bSChris Mason 		if (wret < 0)
1875e66f709bSChris Mason 			ret = wret;
1876e66f709bSChris Mason 		if (wret == 0) {
18775f39d397SChris Mason 			struct btrfs_disk_key disk_key;
1878e66f709bSChris Mason 			orig_slot += left_nr;
18795f39d397SChris Mason 			btrfs_node_key(mid, &disk_key, 0);
1880f230475eSJan Schmidt 			tree_mod_log_set_node_key(root->fs_info, parent,
1881f230475eSJan Schmidt 						  &disk_key, pslot, 0);
18825f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot);
18835f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
18845f39d397SChris Mason 			if (btrfs_header_nritems(left) > orig_slot) {
18855f39d397SChris Mason 				path->nodes[level] = left;
1886e66f709bSChris Mason 				path->slots[level + 1] -= 1;
1887e66f709bSChris Mason 				path->slots[level] = orig_slot;
1888925baeddSChris Mason 				btrfs_tree_unlock(mid);
18895f39d397SChris Mason 				free_extent_buffer(mid);
1890e66f709bSChris Mason 			} else {
1891e66f709bSChris Mason 				orig_slot -=
18925f39d397SChris Mason 					btrfs_header_nritems(left);
1893e66f709bSChris Mason 				path->slots[level] = orig_slot;
1894925baeddSChris Mason 				btrfs_tree_unlock(left);
18955f39d397SChris Mason 				free_extent_buffer(left);
1896e66f709bSChris Mason 			}
1897e66f709bSChris Mason 			return 0;
1898e66f709bSChris Mason 		}
1899925baeddSChris Mason 		btrfs_tree_unlock(left);
19005f39d397SChris Mason 		free_extent_buffer(left);
1901e66f709bSChris Mason 	}
19025f39d397SChris Mason 	right = read_node_slot(root, parent, pslot + 1);
1903e66f709bSChris Mason 
1904e66f709bSChris Mason 	/*
1905e66f709bSChris Mason 	 * then try to empty the right most buffer into the middle
1906e66f709bSChris Mason 	 */
19075f39d397SChris Mason 	if (right) {
190833ade1f8SChris Mason 		u32 right_nr;
1909b4ce94deSChris Mason 
1910925baeddSChris Mason 		btrfs_tree_lock(right);
1911b4ce94deSChris Mason 		btrfs_set_lock_blocking(right);
1912b4ce94deSChris Mason 
19135f39d397SChris Mason 		right_nr = btrfs_header_nritems(right);
191433ade1f8SChris Mason 		if (right_nr >= BTRFS_NODEPTRS_PER_BLOCK(root) - 1) {
191533ade1f8SChris Mason 			wret = 1;
191633ade1f8SChris Mason 		} else {
19175f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, right,
19185f39d397SChris Mason 					      parent, pslot + 1,
19199fa8cfe7SChris Mason 					      &right);
192054aa1f4dSChris Mason 			if (ret)
192154aa1f4dSChris Mason 				wret = 1;
192254aa1f4dSChris Mason 			else {
192333ade1f8SChris Mason 				wret = balance_node_right(trans, root,
19245f39d397SChris Mason 							  right, mid);
192533ade1f8SChris Mason 			}
192654aa1f4dSChris Mason 		}
1927e66f709bSChris Mason 		if (wret < 0)
1928e66f709bSChris Mason 			ret = wret;
1929e66f709bSChris Mason 		if (wret == 0) {
19305f39d397SChris Mason 			struct btrfs_disk_key disk_key;
19315f39d397SChris Mason 
19325f39d397SChris Mason 			btrfs_node_key(right, &disk_key, 0);
1933f230475eSJan Schmidt 			tree_mod_log_set_node_key(root->fs_info, parent,
1934f230475eSJan Schmidt 						  &disk_key, pslot + 1, 0);
19355f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot + 1);
19365f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
19375f39d397SChris Mason 
19385f39d397SChris Mason 			if (btrfs_header_nritems(mid) <= orig_slot) {
19395f39d397SChris Mason 				path->nodes[level] = right;
1940e66f709bSChris Mason 				path->slots[level + 1] += 1;
1941e66f709bSChris Mason 				path->slots[level] = orig_slot -
19425f39d397SChris Mason 					btrfs_header_nritems(mid);
1943925baeddSChris Mason 				btrfs_tree_unlock(mid);
19445f39d397SChris Mason 				free_extent_buffer(mid);
1945e66f709bSChris Mason 			} else {
1946925baeddSChris Mason 				btrfs_tree_unlock(right);
19475f39d397SChris Mason 				free_extent_buffer(right);
1948e66f709bSChris Mason 			}
1949e66f709bSChris Mason 			return 0;
1950e66f709bSChris Mason 		}
1951925baeddSChris Mason 		btrfs_tree_unlock(right);
19525f39d397SChris Mason 		free_extent_buffer(right);
1953e66f709bSChris Mason 	}
1954e66f709bSChris Mason 	return 1;
1955e66f709bSChris Mason }
1956e66f709bSChris Mason 
195774123bd7SChris Mason /*
1958d352ac68SChris Mason  * readahead one full node of leaves, finding things that are close
1959d352ac68SChris Mason  * to the block in 'slot', and triggering ra on them.
19603c69faecSChris Mason  */
1961c8c42864SChris Mason static void reada_for_search(struct btrfs_root *root,
1962e02119d5SChris Mason 			     struct btrfs_path *path,
196301f46658SChris Mason 			     int level, int slot, u64 objectid)
19643c69faecSChris Mason {
19655f39d397SChris Mason 	struct extent_buffer *node;
196601f46658SChris Mason 	struct btrfs_disk_key disk_key;
19673c69faecSChris Mason 	u32 nritems;
19683c69faecSChris Mason 	u64 search;
1969a7175319SChris Mason 	u64 target;
19706b80053dSChris Mason 	u64 nread = 0;
1971cb25c2eaSJosef Bacik 	u64 gen;
19723c69faecSChris Mason 	int direction = path->reada;
19735f39d397SChris Mason 	struct extent_buffer *eb;
19746b80053dSChris Mason 	u32 nr;
19756b80053dSChris Mason 	u32 blocksize;
19766b80053dSChris Mason 	u32 nscan = 0;
1977db94535dSChris Mason 
1978a6b6e75eSChris Mason 	if (level != 1)
19793c69faecSChris Mason 		return;
19803c69faecSChris Mason 
19816702ed49SChris Mason 	if (!path->nodes[level])
19826702ed49SChris Mason 		return;
19836702ed49SChris Mason 
19845f39d397SChris Mason 	node = path->nodes[level];
1985925baeddSChris Mason 
19863c69faecSChris Mason 	search = btrfs_node_blockptr(node, slot);
19876b80053dSChris Mason 	blocksize = btrfs_level_size(root, level - 1);
19886b80053dSChris Mason 	eb = btrfs_find_tree_block(root, search, blocksize);
19895f39d397SChris Mason 	if (eb) {
19905f39d397SChris Mason 		free_extent_buffer(eb);
19913c69faecSChris Mason 		return;
19923c69faecSChris Mason 	}
19933c69faecSChris Mason 
1994a7175319SChris Mason 	target = search;
19956b80053dSChris Mason 
19965f39d397SChris Mason 	nritems = btrfs_header_nritems(node);
19976b80053dSChris Mason 	nr = slot;
199825b8b936SJosef Bacik 
19993c69faecSChris Mason 	while (1) {
20006b80053dSChris Mason 		if (direction < 0) {
20016b80053dSChris Mason 			if (nr == 0)
20023c69faecSChris Mason 				break;
20036b80053dSChris Mason 			nr--;
20046b80053dSChris Mason 		} else if (direction > 0) {
20056b80053dSChris Mason 			nr++;
20066b80053dSChris Mason 			if (nr >= nritems)
20076b80053dSChris Mason 				break;
20083c69faecSChris Mason 		}
200901f46658SChris Mason 		if (path->reada < 0 && objectid) {
201001f46658SChris Mason 			btrfs_node_key(node, &disk_key, nr);
201101f46658SChris Mason 			if (btrfs_disk_key_objectid(&disk_key) != objectid)
201201f46658SChris Mason 				break;
201301f46658SChris Mason 		}
20146b80053dSChris Mason 		search = btrfs_node_blockptr(node, nr);
2015a7175319SChris Mason 		if ((search <= target && target - search <= 65536) ||
2016a7175319SChris Mason 		    (search > target && search - target <= 65536)) {
2017cb25c2eaSJosef Bacik 			gen = btrfs_node_ptr_generation(node, nr);
2018cb25c2eaSJosef Bacik 			readahead_tree_block(root, search, blocksize, gen);
20196b80053dSChris Mason 			nread += blocksize;
20203c69faecSChris Mason 		}
20216b80053dSChris Mason 		nscan++;
2022a7175319SChris Mason 		if ((nread > 65536 || nscan > 32))
20236b80053dSChris Mason 			break;
20243c69faecSChris Mason 	}
20253c69faecSChris Mason }
2026925baeddSChris Mason 
2027d352ac68SChris Mason /*
2028b4ce94deSChris Mason  * returns -EAGAIN if it had to drop the path, or zero if everything was in
2029b4ce94deSChris Mason  * cache
2030b4ce94deSChris Mason  */
2031b4ce94deSChris Mason static noinline int reada_for_balance(struct btrfs_root *root,
2032b4ce94deSChris Mason 				      struct btrfs_path *path, int level)
2033b4ce94deSChris Mason {
2034b4ce94deSChris Mason 	int slot;
2035b4ce94deSChris Mason 	int nritems;
2036b4ce94deSChris Mason 	struct extent_buffer *parent;
2037b4ce94deSChris Mason 	struct extent_buffer *eb;
2038b4ce94deSChris Mason 	u64 gen;
2039b4ce94deSChris Mason 	u64 block1 = 0;
2040b4ce94deSChris Mason 	u64 block2 = 0;
2041b4ce94deSChris Mason 	int ret = 0;
2042b4ce94deSChris Mason 	int blocksize;
2043b4ce94deSChris Mason 
20448c594ea8SChris Mason 	parent = path->nodes[level + 1];
2045b4ce94deSChris Mason 	if (!parent)
2046b4ce94deSChris Mason 		return 0;
2047b4ce94deSChris Mason 
2048b4ce94deSChris Mason 	nritems = btrfs_header_nritems(parent);
20498c594ea8SChris Mason 	slot = path->slots[level + 1];
2050b4ce94deSChris Mason 	blocksize = btrfs_level_size(root, level);
2051b4ce94deSChris Mason 
2052b4ce94deSChris Mason 	if (slot > 0) {
2053b4ce94deSChris Mason 		block1 = btrfs_node_blockptr(parent, slot - 1);
2054b4ce94deSChris Mason 		gen = btrfs_node_ptr_generation(parent, slot - 1);
2055b4ce94deSChris Mason 		eb = btrfs_find_tree_block(root, block1, blocksize);
2056b9fab919SChris Mason 		/*
2057b9fab919SChris Mason 		 * if we get -eagain from btrfs_buffer_uptodate, we
2058b9fab919SChris Mason 		 * don't want to return eagain here.  That will loop
2059b9fab919SChris Mason 		 * forever
2060b9fab919SChris Mason 		 */
2061b9fab919SChris Mason 		if (eb && btrfs_buffer_uptodate(eb, gen, 1) != 0)
2062b4ce94deSChris Mason 			block1 = 0;
2063b4ce94deSChris Mason 		free_extent_buffer(eb);
2064b4ce94deSChris Mason 	}
20658c594ea8SChris Mason 	if (slot + 1 < nritems) {
2066b4ce94deSChris Mason 		block2 = btrfs_node_blockptr(parent, slot + 1);
2067b4ce94deSChris Mason 		gen = btrfs_node_ptr_generation(parent, slot + 1);
2068b4ce94deSChris Mason 		eb = btrfs_find_tree_block(root, block2, blocksize);
2069b9fab919SChris Mason 		if (eb && btrfs_buffer_uptodate(eb, gen, 1) != 0)
2070b4ce94deSChris Mason 			block2 = 0;
2071b4ce94deSChris Mason 		free_extent_buffer(eb);
2072b4ce94deSChris Mason 	}
2073b4ce94deSChris Mason 	if (block1 || block2) {
2074b4ce94deSChris Mason 		ret = -EAGAIN;
20758c594ea8SChris Mason 
20768c594ea8SChris Mason 		/* release the whole path */
2077b3b4aa74SDavid Sterba 		btrfs_release_path(path);
20788c594ea8SChris Mason 
20798c594ea8SChris Mason 		/* read the blocks */
2080b4ce94deSChris Mason 		if (block1)
2081b4ce94deSChris Mason 			readahead_tree_block(root, block1, blocksize, 0);
2082b4ce94deSChris Mason 		if (block2)
2083b4ce94deSChris Mason 			readahead_tree_block(root, block2, blocksize, 0);
2084b4ce94deSChris Mason 
2085b4ce94deSChris Mason 		if (block1) {
2086b4ce94deSChris Mason 			eb = read_tree_block(root, block1, blocksize, 0);
2087b4ce94deSChris Mason 			free_extent_buffer(eb);
2088b4ce94deSChris Mason 		}
20898c594ea8SChris Mason 		if (block2) {
2090b4ce94deSChris Mason 			eb = read_tree_block(root, block2, blocksize, 0);
2091b4ce94deSChris Mason 			free_extent_buffer(eb);
2092b4ce94deSChris Mason 		}
2093b4ce94deSChris Mason 	}
2094b4ce94deSChris Mason 	return ret;
2095b4ce94deSChris Mason }
2096b4ce94deSChris Mason 
2097b4ce94deSChris Mason 
2098b4ce94deSChris Mason /*
2099d397712bSChris Mason  * when we walk down the tree, it is usually safe to unlock the higher layers
2100d397712bSChris Mason  * in the tree.  The exceptions are when our path goes through slot 0, because
2101d397712bSChris Mason  * operations on the tree might require changing key pointers higher up in the
2102d397712bSChris Mason  * tree.
2103d352ac68SChris Mason  *
2104d397712bSChris Mason  * callers might also have set path->keep_locks, which tells this code to keep
2105d397712bSChris Mason  * the lock if the path points to the last slot in the block.  This is part of
2106d397712bSChris Mason  * walking through the tree, and selecting the next slot in the higher block.
2107d352ac68SChris Mason  *
2108d397712bSChris Mason  * lowest_unlock sets the lowest level in the tree we're allowed to unlock.  so
2109d397712bSChris Mason  * if lowest_unlock is 1, level 0 won't be unlocked
2110d352ac68SChris Mason  */
2111e02119d5SChris Mason static noinline void unlock_up(struct btrfs_path *path, int level,
2112f7c79f30SChris Mason 			       int lowest_unlock, int min_write_lock_level,
2113f7c79f30SChris Mason 			       int *write_lock_level)
2114925baeddSChris Mason {
2115925baeddSChris Mason 	int i;
2116925baeddSChris Mason 	int skip_level = level;
2117051e1b9fSChris Mason 	int no_skips = 0;
2118925baeddSChris Mason 	struct extent_buffer *t;
2119925baeddSChris Mason 
2120925baeddSChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2121925baeddSChris Mason 		if (!path->nodes[i])
2122925baeddSChris Mason 			break;
2123925baeddSChris Mason 		if (!path->locks[i])
2124925baeddSChris Mason 			break;
2125051e1b9fSChris Mason 		if (!no_skips && path->slots[i] == 0) {
2126925baeddSChris Mason 			skip_level = i + 1;
2127925baeddSChris Mason 			continue;
2128925baeddSChris Mason 		}
2129051e1b9fSChris Mason 		if (!no_skips && path->keep_locks) {
2130925baeddSChris Mason 			u32 nritems;
2131925baeddSChris Mason 			t = path->nodes[i];
2132925baeddSChris Mason 			nritems = btrfs_header_nritems(t);
2133051e1b9fSChris Mason 			if (nritems < 1 || path->slots[i] >= nritems - 1) {
2134925baeddSChris Mason 				skip_level = i + 1;
2135925baeddSChris Mason 				continue;
2136925baeddSChris Mason 			}
2137925baeddSChris Mason 		}
2138051e1b9fSChris Mason 		if (skip_level < i && i >= lowest_unlock)
2139051e1b9fSChris Mason 			no_skips = 1;
2140051e1b9fSChris Mason 
2141925baeddSChris Mason 		t = path->nodes[i];
2142925baeddSChris Mason 		if (i >= lowest_unlock && i > skip_level && path->locks[i]) {
2143bd681513SChris Mason 			btrfs_tree_unlock_rw(t, path->locks[i]);
2144925baeddSChris Mason 			path->locks[i] = 0;
2145f7c79f30SChris Mason 			if (write_lock_level &&
2146f7c79f30SChris Mason 			    i > min_write_lock_level &&
2147f7c79f30SChris Mason 			    i <= *write_lock_level) {
2148f7c79f30SChris Mason 				*write_lock_level = i - 1;
2149f7c79f30SChris Mason 			}
2150925baeddSChris Mason 		}
2151925baeddSChris Mason 	}
2152925baeddSChris Mason }
2153925baeddSChris Mason 
21543c69faecSChris Mason /*
2155b4ce94deSChris Mason  * This releases any locks held in the path starting at level and
2156b4ce94deSChris Mason  * going all the way up to the root.
2157b4ce94deSChris Mason  *
2158b4ce94deSChris Mason  * btrfs_search_slot will keep the lock held on higher nodes in a few
2159b4ce94deSChris Mason  * corner cases, such as COW of the block at slot zero in the node.  This
2160b4ce94deSChris Mason  * ignores those rules, and it should only be called when there are no
2161b4ce94deSChris Mason  * more updates to be done higher up in the tree.
2162b4ce94deSChris Mason  */
2163b4ce94deSChris Mason noinline void btrfs_unlock_up_safe(struct btrfs_path *path, int level)
2164b4ce94deSChris Mason {
2165b4ce94deSChris Mason 	int i;
2166b4ce94deSChris Mason 
21675d4f98a2SYan Zheng 	if (path->keep_locks)
2168b4ce94deSChris Mason 		return;
2169b4ce94deSChris Mason 
2170b4ce94deSChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2171b4ce94deSChris Mason 		if (!path->nodes[i])
217212f4daccSChris Mason 			continue;
2173b4ce94deSChris Mason 		if (!path->locks[i])
217412f4daccSChris Mason 			continue;
2175bd681513SChris Mason 		btrfs_tree_unlock_rw(path->nodes[i], path->locks[i]);
2176b4ce94deSChris Mason 		path->locks[i] = 0;
2177b4ce94deSChris Mason 	}
2178b4ce94deSChris Mason }
2179b4ce94deSChris Mason 
2180b4ce94deSChris Mason /*
2181c8c42864SChris Mason  * helper function for btrfs_search_slot.  The goal is to find a block
2182c8c42864SChris Mason  * in cache without setting the path to blocking.  If we find the block
2183c8c42864SChris Mason  * we return zero and the path is unchanged.
2184c8c42864SChris Mason  *
2185c8c42864SChris Mason  * If we can't find the block, we set the path blocking and do some
2186c8c42864SChris Mason  * reada.  -EAGAIN is returned and the search must be repeated.
2187c8c42864SChris Mason  */
2188c8c42864SChris Mason static int
2189c8c42864SChris Mason read_block_for_search(struct btrfs_trans_handle *trans,
2190c8c42864SChris Mason 		       struct btrfs_root *root, struct btrfs_path *p,
2191c8c42864SChris Mason 		       struct extent_buffer **eb_ret, int level, int slot,
21925d9e75c4SJan Schmidt 		       struct btrfs_key *key, u64 time_seq)
2193c8c42864SChris Mason {
2194c8c42864SChris Mason 	u64 blocknr;
2195c8c42864SChris Mason 	u64 gen;
2196c8c42864SChris Mason 	u32 blocksize;
2197c8c42864SChris Mason 	struct extent_buffer *b = *eb_ret;
2198c8c42864SChris Mason 	struct extent_buffer *tmp;
219976a05b35SChris Mason 	int ret;
2200c8c42864SChris Mason 
2201c8c42864SChris Mason 	blocknr = btrfs_node_blockptr(b, slot);
2202c8c42864SChris Mason 	gen = btrfs_node_ptr_generation(b, slot);
2203c8c42864SChris Mason 	blocksize = btrfs_level_size(root, level - 1);
2204c8c42864SChris Mason 
2205c8c42864SChris Mason 	tmp = btrfs_find_tree_block(root, blocknr, blocksize);
2206cb44921aSChris Mason 	if (tmp) {
2207b9fab919SChris Mason 		/* first we do an atomic uptodate check */
2208b9fab919SChris Mason 		if (btrfs_buffer_uptodate(tmp, 0, 1) > 0) {
2209b9fab919SChris Mason 			if (btrfs_buffer_uptodate(tmp, gen, 1) > 0) {
221076a05b35SChris Mason 				/*
2211cb44921aSChris Mason 				 * we found an up to date block without
2212cb44921aSChris Mason 				 * sleeping, return
221376a05b35SChris Mason 				 * right away
221476a05b35SChris Mason 				 */
2215c8c42864SChris Mason 				*eb_ret = tmp;
2216c8c42864SChris Mason 				return 0;
2217c8c42864SChris Mason 			}
2218cb44921aSChris Mason 			/* the pages were up to date, but we failed
2219cb44921aSChris Mason 			 * the generation number check.  Do a full
2220cb44921aSChris Mason 			 * read for the generation number that is correct.
2221cb44921aSChris Mason 			 * We must do this without dropping locks so
2222cb44921aSChris Mason 			 * we can trust our generation number
2223cb44921aSChris Mason 			 */
2224cb44921aSChris Mason 			free_extent_buffer(tmp);
2225bd681513SChris Mason 			btrfs_set_path_blocking(p);
2226bd681513SChris Mason 
2227b9fab919SChris Mason 			/* now we're allowed to do a blocking uptodate check */
2228cb44921aSChris Mason 			tmp = read_tree_block(root, blocknr, blocksize, gen);
2229b9fab919SChris Mason 			if (tmp && btrfs_buffer_uptodate(tmp, gen, 0) > 0) {
2230cb44921aSChris Mason 				*eb_ret = tmp;
2231cb44921aSChris Mason 				return 0;
2232cb44921aSChris Mason 			}
2233cb44921aSChris Mason 			free_extent_buffer(tmp);
2234b3b4aa74SDavid Sterba 			btrfs_release_path(p);
2235cb44921aSChris Mason 			return -EIO;
2236cb44921aSChris Mason 		}
2237cb44921aSChris Mason 	}
2238c8c42864SChris Mason 
2239c8c42864SChris Mason 	/*
2240c8c42864SChris Mason 	 * reduce lock contention at high levels
2241c8c42864SChris Mason 	 * of the btree by dropping locks before
224276a05b35SChris Mason 	 * we read.  Don't release the lock on the current
224376a05b35SChris Mason 	 * level because we need to walk this node to figure
224476a05b35SChris Mason 	 * out which blocks to read.
2245c8c42864SChris Mason 	 */
22468c594ea8SChris Mason 	btrfs_unlock_up_safe(p, level + 1);
22478c594ea8SChris Mason 	btrfs_set_path_blocking(p);
22488c594ea8SChris Mason 
2249c8c42864SChris Mason 	free_extent_buffer(tmp);
2250c8c42864SChris Mason 	if (p->reada)
2251c8c42864SChris Mason 		reada_for_search(root, p, level, slot, key->objectid);
2252c8c42864SChris Mason 
2253b3b4aa74SDavid Sterba 	btrfs_release_path(p);
225476a05b35SChris Mason 
225576a05b35SChris Mason 	ret = -EAGAIN;
22565bdd3536SYan, Zheng 	tmp = read_tree_block(root, blocknr, blocksize, 0);
225776a05b35SChris Mason 	if (tmp) {
225876a05b35SChris Mason 		/*
225976a05b35SChris Mason 		 * If the read above didn't mark this buffer up to date,
226076a05b35SChris Mason 		 * it will never end up being up to date.  Set ret to EIO now
226176a05b35SChris Mason 		 * and give up so that our caller doesn't loop forever
226276a05b35SChris Mason 		 * on our EAGAINs.
226376a05b35SChris Mason 		 */
2264b9fab919SChris Mason 		if (!btrfs_buffer_uptodate(tmp, 0, 0))
226576a05b35SChris Mason 			ret = -EIO;
2266c8c42864SChris Mason 		free_extent_buffer(tmp);
226776a05b35SChris Mason 	}
226876a05b35SChris Mason 	return ret;
2269c8c42864SChris Mason }
2270c8c42864SChris Mason 
2271c8c42864SChris Mason /*
2272c8c42864SChris Mason  * helper function for btrfs_search_slot.  This does all of the checks
2273c8c42864SChris Mason  * for node-level blocks and does any balancing required based on
2274c8c42864SChris Mason  * the ins_len.
2275c8c42864SChris Mason  *
2276c8c42864SChris Mason  * If no extra work was required, zero is returned.  If we had to
2277c8c42864SChris Mason  * drop the path, -EAGAIN is returned and btrfs_search_slot must
2278c8c42864SChris Mason  * start over
2279c8c42864SChris Mason  */
2280c8c42864SChris Mason static int
2281c8c42864SChris Mason setup_nodes_for_search(struct btrfs_trans_handle *trans,
2282c8c42864SChris Mason 		       struct btrfs_root *root, struct btrfs_path *p,
2283bd681513SChris Mason 		       struct extent_buffer *b, int level, int ins_len,
2284bd681513SChris Mason 		       int *write_lock_level)
2285c8c42864SChris Mason {
2286c8c42864SChris Mason 	int ret;
2287c8c42864SChris Mason 	if ((p->search_for_split || ins_len > 0) && btrfs_header_nritems(b) >=
2288c8c42864SChris Mason 	    BTRFS_NODEPTRS_PER_BLOCK(root) - 3) {
2289c8c42864SChris Mason 		int sret;
2290c8c42864SChris Mason 
2291bd681513SChris Mason 		if (*write_lock_level < level + 1) {
2292bd681513SChris Mason 			*write_lock_level = level + 1;
2293bd681513SChris Mason 			btrfs_release_path(p);
2294bd681513SChris Mason 			goto again;
2295bd681513SChris Mason 		}
2296bd681513SChris Mason 
2297c8c42864SChris Mason 		sret = reada_for_balance(root, p, level);
2298c8c42864SChris Mason 		if (sret)
2299c8c42864SChris Mason 			goto again;
2300c8c42864SChris Mason 
2301c8c42864SChris Mason 		btrfs_set_path_blocking(p);
2302c8c42864SChris Mason 		sret = split_node(trans, root, p, level);
2303bd681513SChris Mason 		btrfs_clear_path_blocking(p, NULL, 0);
2304c8c42864SChris Mason 
2305c8c42864SChris Mason 		BUG_ON(sret > 0);
2306c8c42864SChris Mason 		if (sret) {
2307c8c42864SChris Mason 			ret = sret;
2308c8c42864SChris Mason 			goto done;
2309c8c42864SChris Mason 		}
2310c8c42864SChris Mason 		b = p->nodes[level];
2311c8c42864SChris Mason 	} else if (ins_len < 0 && btrfs_header_nritems(b) <
2312cfbb9308SChris Mason 		   BTRFS_NODEPTRS_PER_BLOCK(root) / 2) {
2313c8c42864SChris Mason 		int sret;
2314c8c42864SChris Mason 
2315bd681513SChris Mason 		if (*write_lock_level < level + 1) {
2316bd681513SChris Mason 			*write_lock_level = level + 1;
2317bd681513SChris Mason 			btrfs_release_path(p);
2318bd681513SChris Mason 			goto again;
2319bd681513SChris Mason 		}
2320bd681513SChris Mason 
2321c8c42864SChris Mason 		sret = reada_for_balance(root, p, level);
2322c8c42864SChris Mason 		if (sret)
2323c8c42864SChris Mason 			goto again;
2324c8c42864SChris Mason 
2325c8c42864SChris Mason 		btrfs_set_path_blocking(p);
2326c8c42864SChris Mason 		sret = balance_level(trans, root, p, level);
2327bd681513SChris Mason 		btrfs_clear_path_blocking(p, NULL, 0);
2328c8c42864SChris Mason 
2329c8c42864SChris Mason 		if (sret) {
2330c8c42864SChris Mason 			ret = sret;
2331c8c42864SChris Mason 			goto done;
2332c8c42864SChris Mason 		}
2333c8c42864SChris Mason 		b = p->nodes[level];
2334c8c42864SChris Mason 		if (!b) {
2335b3b4aa74SDavid Sterba 			btrfs_release_path(p);
2336c8c42864SChris Mason 			goto again;
2337c8c42864SChris Mason 		}
2338c8c42864SChris Mason 		BUG_ON(btrfs_header_nritems(b) == 1);
2339c8c42864SChris Mason 	}
2340c8c42864SChris Mason 	return 0;
2341c8c42864SChris Mason 
2342c8c42864SChris Mason again:
2343c8c42864SChris Mason 	ret = -EAGAIN;
2344c8c42864SChris Mason done:
2345c8c42864SChris Mason 	return ret;
2346c8c42864SChris Mason }
2347c8c42864SChris Mason 
2348c8c42864SChris Mason /*
234974123bd7SChris Mason  * look for key in the tree.  path is filled in with nodes along the way
235074123bd7SChris Mason  * if key is found, we return zero and you can find the item in the leaf
235174123bd7SChris Mason  * level of the path (level 0)
235274123bd7SChris Mason  *
235374123bd7SChris Mason  * If the key isn't found, the path points to the slot where it should
2354aa5d6bedSChris Mason  * be inserted, and 1 is returned.  If there are other errors during the
2355aa5d6bedSChris Mason  * search a negative error number is returned.
235697571fd0SChris Mason  *
235797571fd0SChris Mason  * if ins_len > 0, nodes and leaves will be split as we walk down the
235897571fd0SChris Mason  * tree.  if ins_len < 0, nodes will be merged as we walk down the tree (if
235997571fd0SChris Mason  * possible)
236074123bd7SChris Mason  */
2361e089f05cSChris Mason int btrfs_search_slot(struct btrfs_trans_handle *trans, struct btrfs_root
2362e089f05cSChris Mason 		      *root, struct btrfs_key *key, struct btrfs_path *p, int
2363e089f05cSChris Mason 		      ins_len, int cow)
2364be0e5c09SChris Mason {
23655f39d397SChris Mason 	struct extent_buffer *b;
2366be0e5c09SChris Mason 	int slot;
2367be0e5c09SChris Mason 	int ret;
236833c66f43SYan Zheng 	int err;
2369be0e5c09SChris Mason 	int level;
2370925baeddSChris Mason 	int lowest_unlock = 1;
2371bd681513SChris Mason 	int root_lock;
2372bd681513SChris Mason 	/* everything at write_lock_level or lower must be write locked */
2373bd681513SChris Mason 	int write_lock_level = 0;
23749f3a7427SChris Mason 	u8 lowest_level = 0;
2375f7c79f30SChris Mason 	int min_write_lock_level;
23769f3a7427SChris Mason 
23776702ed49SChris Mason 	lowest_level = p->lowest_level;
2378323ac95bSChris Mason 	WARN_ON(lowest_level && ins_len > 0);
237922b0ebdaSChris Mason 	WARN_ON(p->nodes[0] != NULL);
238025179201SJosef Bacik 
2381bd681513SChris Mason 	if (ins_len < 0) {
2382925baeddSChris Mason 		lowest_unlock = 2;
238365b51a00SChris Mason 
2384bd681513SChris Mason 		/* when we are removing items, we might have to go up to level
2385bd681513SChris Mason 		 * two as we update tree pointers  Make sure we keep write
2386bd681513SChris Mason 		 * for those levels as well
2387bd681513SChris Mason 		 */
2388bd681513SChris Mason 		write_lock_level = 2;
2389bd681513SChris Mason 	} else if (ins_len > 0) {
2390bd681513SChris Mason 		/*
2391bd681513SChris Mason 		 * for inserting items, make sure we have a write lock on
2392bd681513SChris Mason 		 * level 1 so we can update keys
2393bd681513SChris Mason 		 */
2394bd681513SChris Mason 		write_lock_level = 1;
2395bd681513SChris Mason 	}
2396bd681513SChris Mason 
2397bd681513SChris Mason 	if (!cow)
2398bd681513SChris Mason 		write_lock_level = -1;
2399bd681513SChris Mason 
2400bd681513SChris Mason 	if (cow && (p->keep_locks || p->lowest_level))
2401bd681513SChris Mason 		write_lock_level = BTRFS_MAX_LEVEL;
2402bd681513SChris Mason 
2403f7c79f30SChris Mason 	min_write_lock_level = write_lock_level;
2404f7c79f30SChris Mason 
2405bb803951SChris Mason again:
2406bd681513SChris Mason 	/*
2407bd681513SChris Mason 	 * we try very hard to do read locks on the root
2408bd681513SChris Mason 	 */
2409bd681513SChris Mason 	root_lock = BTRFS_READ_LOCK;
2410bd681513SChris Mason 	level = 0;
24115d4f98a2SYan Zheng 	if (p->search_commit_root) {
2412bd681513SChris Mason 		/*
2413bd681513SChris Mason 		 * the commit roots are read only
2414bd681513SChris Mason 		 * so we always do read locks
2415bd681513SChris Mason 		 */
24165d4f98a2SYan Zheng 		b = root->commit_root;
24175d4f98a2SYan Zheng 		extent_buffer_get(b);
2418bd681513SChris Mason 		level = btrfs_header_level(b);
24195d4f98a2SYan Zheng 		if (!p->skip_locking)
2420bd681513SChris Mason 			btrfs_tree_read_lock(b);
24215d4f98a2SYan Zheng 	} else {
2422bd681513SChris Mason 		if (p->skip_locking) {
24235cd57b2cSChris Mason 			b = btrfs_root_node(root);
2424bd681513SChris Mason 			level = btrfs_header_level(b);
2425bd681513SChris Mason 		} else {
2426bd681513SChris Mason 			/* we don't know the level of the root node
2427bd681513SChris Mason 			 * until we actually have it read locked
2428bd681513SChris Mason 			 */
2429bd681513SChris Mason 			b = btrfs_read_lock_root_node(root);
2430bd681513SChris Mason 			level = btrfs_header_level(b);
2431bd681513SChris Mason 			if (level <= write_lock_level) {
2432bd681513SChris Mason 				/* whoops, must trade for write lock */
2433bd681513SChris Mason 				btrfs_tree_read_unlock(b);
2434bd681513SChris Mason 				free_extent_buffer(b);
2435925baeddSChris Mason 				b = btrfs_lock_root_node(root);
2436bd681513SChris Mason 				root_lock = BTRFS_WRITE_LOCK;
2437bd681513SChris Mason 
2438bd681513SChris Mason 				/* the level might have changed, check again */
2439bd681513SChris Mason 				level = btrfs_header_level(b);
24405d4f98a2SYan Zheng 			}
2441bd681513SChris Mason 		}
2442bd681513SChris Mason 	}
2443bd681513SChris Mason 	p->nodes[level] = b;
2444bd681513SChris Mason 	if (!p->skip_locking)
2445bd681513SChris Mason 		p->locks[level] = root_lock;
2446925baeddSChris Mason 
2447eb60ceacSChris Mason 	while (b) {
24485f39d397SChris Mason 		level = btrfs_header_level(b);
244965b51a00SChris Mason 
245065b51a00SChris Mason 		/*
245165b51a00SChris Mason 		 * setup the path here so we can release it under lock
245265b51a00SChris Mason 		 * contention with the cow code
245365b51a00SChris Mason 		 */
245402217ed2SChris Mason 		if (cow) {
2455c8c42864SChris Mason 			/*
2456c8c42864SChris Mason 			 * if we don't really need to cow this block
2457c8c42864SChris Mason 			 * then we don't want to set the path blocking,
2458c8c42864SChris Mason 			 * so we test it here
2459c8c42864SChris Mason 			 */
24605d4f98a2SYan Zheng 			if (!should_cow_block(trans, root, b))
246165b51a00SChris Mason 				goto cow_done;
24625d4f98a2SYan Zheng 
2463b4ce94deSChris Mason 			btrfs_set_path_blocking(p);
2464b4ce94deSChris Mason 
2465bd681513SChris Mason 			/*
2466bd681513SChris Mason 			 * must have write locks on this node and the
2467bd681513SChris Mason 			 * parent
2468bd681513SChris Mason 			 */
2469bd681513SChris Mason 			if (level + 1 > write_lock_level) {
2470bd681513SChris Mason 				write_lock_level = level + 1;
2471bd681513SChris Mason 				btrfs_release_path(p);
2472bd681513SChris Mason 				goto again;
2473bd681513SChris Mason 			}
2474bd681513SChris Mason 
247533c66f43SYan Zheng 			err = btrfs_cow_block(trans, root, b,
2476e20d96d6SChris Mason 					      p->nodes[level + 1],
24779fa8cfe7SChris Mason 					      p->slots[level + 1], &b);
247833c66f43SYan Zheng 			if (err) {
247933c66f43SYan Zheng 				ret = err;
248065b51a00SChris Mason 				goto done;
248154aa1f4dSChris Mason 			}
248202217ed2SChris Mason 		}
248365b51a00SChris Mason cow_done:
248402217ed2SChris Mason 		BUG_ON(!cow && ins_len);
248565b51a00SChris Mason 
2486eb60ceacSChris Mason 		p->nodes[level] = b;
2487bd681513SChris Mason 		btrfs_clear_path_blocking(p, NULL, 0);
2488b4ce94deSChris Mason 
2489b4ce94deSChris Mason 		/*
2490b4ce94deSChris Mason 		 * we have a lock on b and as long as we aren't changing
2491b4ce94deSChris Mason 		 * the tree, there is no way to for the items in b to change.
2492b4ce94deSChris Mason 		 * It is safe to drop the lock on our parent before we
2493b4ce94deSChris Mason 		 * go through the expensive btree search on b.
2494b4ce94deSChris Mason 		 *
2495b4ce94deSChris Mason 		 * If cow is true, then we might be changing slot zero,
2496b4ce94deSChris Mason 		 * which may require changing the parent.  So, we can't
2497b4ce94deSChris Mason 		 * drop the lock until after we know which slot we're
2498b4ce94deSChris Mason 		 * operating on.
2499b4ce94deSChris Mason 		 */
2500b4ce94deSChris Mason 		if (!cow)
2501b4ce94deSChris Mason 			btrfs_unlock_up_safe(p, level + 1);
2502b4ce94deSChris Mason 
25035f39d397SChris Mason 		ret = bin_search(b, key, level, &slot);
2504b4ce94deSChris Mason 
25055f39d397SChris Mason 		if (level != 0) {
250633c66f43SYan Zheng 			int dec = 0;
250733c66f43SYan Zheng 			if (ret && slot > 0) {
250833c66f43SYan Zheng 				dec = 1;
2509be0e5c09SChris Mason 				slot -= 1;
251033c66f43SYan Zheng 			}
2511be0e5c09SChris Mason 			p->slots[level] = slot;
251233c66f43SYan Zheng 			err = setup_nodes_for_search(trans, root, p, b, level,
2513bd681513SChris Mason 					     ins_len, &write_lock_level);
251433c66f43SYan Zheng 			if (err == -EAGAIN)
2515b4ce94deSChris Mason 				goto again;
251633c66f43SYan Zheng 			if (err) {
251733c66f43SYan Zheng 				ret = err;
251865b51a00SChris Mason 				goto done;
251933c66f43SYan Zheng 			}
25205c680ed6SChris Mason 			b = p->nodes[level];
25215c680ed6SChris Mason 			slot = p->slots[level];
2522b4ce94deSChris Mason 
2523bd681513SChris Mason 			/*
2524bd681513SChris Mason 			 * slot 0 is special, if we change the key
2525bd681513SChris Mason 			 * we have to update the parent pointer
2526bd681513SChris Mason 			 * which means we must have a write lock
2527bd681513SChris Mason 			 * on the parent
2528bd681513SChris Mason 			 */
2529bd681513SChris Mason 			if (slot == 0 && cow &&
2530bd681513SChris Mason 			    write_lock_level < level + 1) {
2531bd681513SChris Mason 				write_lock_level = level + 1;
2532bd681513SChris Mason 				btrfs_release_path(p);
2533bd681513SChris Mason 				goto again;
2534bd681513SChris Mason 			}
2535bd681513SChris Mason 
2536f7c79f30SChris Mason 			unlock_up(p, level, lowest_unlock,
2537f7c79f30SChris Mason 				  min_write_lock_level, &write_lock_level);
2538f9efa9c7SChris Mason 
2539925baeddSChris Mason 			if (level == lowest_level) {
254033c66f43SYan Zheng 				if (dec)
254133c66f43SYan Zheng 					p->slots[level]++;
25425b21f2edSZheng Yan 				goto done;
2543925baeddSChris Mason 			}
2544ca7a79adSChris Mason 
254533c66f43SYan Zheng 			err = read_block_for_search(trans, root, p,
25465d9e75c4SJan Schmidt 						    &b, level, slot, key, 0);
254733c66f43SYan Zheng 			if (err == -EAGAIN)
2548051e1b9fSChris Mason 				goto again;
254933c66f43SYan Zheng 			if (err) {
255033c66f43SYan Zheng 				ret = err;
255176a05b35SChris Mason 				goto done;
255233c66f43SYan Zheng 			}
255376a05b35SChris Mason 
2554b4ce94deSChris Mason 			if (!p->skip_locking) {
2555bd681513SChris Mason 				level = btrfs_header_level(b);
2556bd681513SChris Mason 				if (level <= write_lock_level) {
2557bd681513SChris Mason 					err = btrfs_try_tree_write_lock(b);
255833c66f43SYan Zheng 					if (!err) {
2559b4ce94deSChris Mason 						btrfs_set_path_blocking(p);
2560925baeddSChris Mason 						btrfs_tree_lock(b);
2561bd681513SChris Mason 						btrfs_clear_path_blocking(p, b,
2562bd681513SChris Mason 								  BTRFS_WRITE_LOCK);
2563b4ce94deSChris Mason 					}
2564bd681513SChris Mason 					p->locks[level] = BTRFS_WRITE_LOCK;
2565bd681513SChris Mason 				} else {
2566bd681513SChris Mason 					err = btrfs_try_tree_read_lock(b);
2567bd681513SChris Mason 					if (!err) {
2568bd681513SChris Mason 						btrfs_set_path_blocking(p);
2569bd681513SChris Mason 						btrfs_tree_read_lock(b);
2570bd681513SChris Mason 						btrfs_clear_path_blocking(p, b,
2571bd681513SChris Mason 								  BTRFS_READ_LOCK);
2572bd681513SChris Mason 					}
2573bd681513SChris Mason 					p->locks[level] = BTRFS_READ_LOCK;
2574bd681513SChris Mason 				}
2575bd681513SChris Mason 				p->nodes[level] = b;
2576b4ce94deSChris Mason 			}
2577be0e5c09SChris Mason 		} else {
2578be0e5c09SChris Mason 			p->slots[level] = slot;
257987b29b20SYan Zheng 			if (ins_len > 0 &&
258087b29b20SYan Zheng 			    btrfs_leaf_free_space(root, b) < ins_len) {
2581bd681513SChris Mason 				if (write_lock_level < 1) {
2582bd681513SChris Mason 					write_lock_level = 1;
2583bd681513SChris Mason 					btrfs_release_path(p);
2584bd681513SChris Mason 					goto again;
2585bd681513SChris Mason 				}
2586bd681513SChris Mason 
2587b4ce94deSChris Mason 				btrfs_set_path_blocking(p);
258833c66f43SYan Zheng 				err = split_leaf(trans, root, key,
2589cc0c5538SChris Mason 						 p, ins_len, ret == 0);
2590bd681513SChris Mason 				btrfs_clear_path_blocking(p, NULL, 0);
2591b4ce94deSChris Mason 
259233c66f43SYan Zheng 				BUG_ON(err > 0);
259333c66f43SYan Zheng 				if (err) {
259433c66f43SYan Zheng 					ret = err;
259565b51a00SChris Mason 					goto done;
259665b51a00SChris Mason 				}
25975c680ed6SChris Mason 			}
2598459931ecSChris Mason 			if (!p->search_for_split)
2599f7c79f30SChris Mason 				unlock_up(p, level, lowest_unlock,
2600f7c79f30SChris Mason 					  min_write_lock_level, &write_lock_level);
260165b51a00SChris Mason 			goto done;
260265b51a00SChris Mason 		}
260365b51a00SChris Mason 	}
260465b51a00SChris Mason 	ret = 1;
260565b51a00SChris Mason done:
2606b4ce94deSChris Mason 	/*
2607b4ce94deSChris Mason 	 * we don't really know what they plan on doing with the path
2608b4ce94deSChris Mason 	 * from here on, so for now just mark it as blocking
2609b4ce94deSChris Mason 	 */
2610b9473439SChris Mason 	if (!p->leave_spinning)
2611b4ce94deSChris Mason 		btrfs_set_path_blocking(p);
261276a05b35SChris Mason 	if (ret < 0)
2613b3b4aa74SDavid Sterba 		btrfs_release_path(p);
2614be0e5c09SChris Mason 	return ret;
2615be0e5c09SChris Mason }
2616be0e5c09SChris Mason 
261774123bd7SChris Mason /*
26185d9e75c4SJan Schmidt  * Like btrfs_search_slot, this looks for a key in the given tree. It uses the
26195d9e75c4SJan Schmidt  * current state of the tree together with the operations recorded in the tree
26205d9e75c4SJan Schmidt  * modification log to search for the key in a previous version of this tree, as
26215d9e75c4SJan Schmidt  * denoted by the time_seq parameter.
26225d9e75c4SJan Schmidt  *
26235d9e75c4SJan Schmidt  * Naturally, there is no support for insert, delete or cow operations.
26245d9e75c4SJan Schmidt  *
26255d9e75c4SJan Schmidt  * The resulting path and return value will be set up as if we called
26265d9e75c4SJan Schmidt  * btrfs_search_slot at that point in time with ins_len and cow both set to 0.
26275d9e75c4SJan Schmidt  */
26285d9e75c4SJan Schmidt int btrfs_search_old_slot(struct btrfs_root *root, struct btrfs_key *key,
26295d9e75c4SJan Schmidt 			  struct btrfs_path *p, u64 time_seq)
26305d9e75c4SJan Schmidt {
26315d9e75c4SJan Schmidt 	struct extent_buffer *b;
26325d9e75c4SJan Schmidt 	int slot;
26335d9e75c4SJan Schmidt 	int ret;
26345d9e75c4SJan Schmidt 	int err;
26355d9e75c4SJan Schmidt 	int level;
26365d9e75c4SJan Schmidt 	int lowest_unlock = 1;
26375d9e75c4SJan Schmidt 	u8 lowest_level = 0;
26385d9e75c4SJan Schmidt 
26395d9e75c4SJan Schmidt 	lowest_level = p->lowest_level;
26405d9e75c4SJan Schmidt 	WARN_ON(p->nodes[0] != NULL);
26415d9e75c4SJan Schmidt 
26425d9e75c4SJan Schmidt 	if (p->search_commit_root) {
26435d9e75c4SJan Schmidt 		BUG_ON(time_seq);
26445d9e75c4SJan Schmidt 		return btrfs_search_slot(NULL, root, key, p, 0, 0);
26455d9e75c4SJan Schmidt 	}
26465d9e75c4SJan Schmidt 
26475d9e75c4SJan Schmidt again:
26485d9e75c4SJan Schmidt 	b = get_old_root(root, time_seq);
26495d9e75c4SJan Schmidt 	level = btrfs_header_level(b);
26505d9e75c4SJan Schmidt 	p->locks[level] = BTRFS_READ_LOCK;
26515d9e75c4SJan Schmidt 
26525d9e75c4SJan Schmidt 	while (b) {
26535d9e75c4SJan Schmidt 		level = btrfs_header_level(b);
26545d9e75c4SJan Schmidt 		p->nodes[level] = b;
26555d9e75c4SJan Schmidt 		btrfs_clear_path_blocking(p, NULL, 0);
26565d9e75c4SJan Schmidt 
26575d9e75c4SJan Schmidt 		/*
26585d9e75c4SJan Schmidt 		 * we have a lock on b and as long as we aren't changing
26595d9e75c4SJan Schmidt 		 * the tree, there is no way to for the items in b to change.
26605d9e75c4SJan Schmidt 		 * It is safe to drop the lock on our parent before we
26615d9e75c4SJan Schmidt 		 * go through the expensive btree search on b.
26625d9e75c4SJan Schmidt 		 */
26635d9e75c4SJan Schmidt 		btrfs_unlock_up_safe(p, level + 1);
26645d9e75c4SJan Schmidt 
26655d9e75c4SJan Schmidt 		ret = bin_search(b, key, level, &slot);
26665d9e75c4SJan Schmidt 
26675d9e75c4SJan Schmidt 		if (level != 0) {
26685d9e75c4SJan Schmidt 			int dec = 0;
26695d9e75c4SJan Schmidt 			if (ret && slot > 0) {
26705d9e75c4SJan Schmidt 				dec = 1;
26715d9e75c4SJan Schmidt 				slot -= 1;
26725d9e75c4SJan Schmidt 			}
26735d9e75c4SJan Schmidt 			p->slots[level] = slot;
26745d9e75c4SJan Schmidt 			unlock_up(p, level, lowest_unlock, 0, NULL);
26755d9e75c4SJan Schmidt 
26765d9e75c4SJan Schmidt 			if (level == lowest_level) {
26775d9e75c4SJan Schmidt 				if (dec)
26785d9e75c4SJan Schmidt 					p->slots[level]++;
26795d9e75c4SJan Schmidt 				goto done;
26805d9e75c4SJan Schmidt 			}
26815d9e75c4SJan Schmidt 
26825d9e75c4SJan Schmidt 			err = read_block_for_search(NULL, root, p, &b, level,
26835d9e75c4SJan Schmidt 						    slot, key, time_seq);
26845d9e75c4SJan Schmidt 			if (err == -EAGAIN)
26855d9e75c4SJan Schmidt 				goto again;
26865d9e75c4SJan Schmidt 			if (err) {
26875d9e75c4SJan Schmidt 				ret = err;
26885d9e75c4SJan Schmidt 				goto done;
26895d9e75c4SJan Schmidt 			}
26905d9e75c4SJan Schmidt 
26915d9e75c4SJan Schmidt 			level = btrfs_header_level(b);
26925d9e75c4SJan Schmidt 			err = btrfs_try_tree_read_lock(b);
26935d9e75c4SJan Schmidt 			if (!err) {
26945d9e75c4SJan Schmidt 				btrfs_set_path_blocking(p);
26955d9e75c4SJan Schmidt 				btrfs_tree_read_lock(b);
26965d9e75c4SJan Schmidt 				btrfs_clear_path_blocking(p, b,
26975d9e75c4SJan Schmidt 							  BTRFS_READ_LOCK);
26985d9e75c4SJan Schmidt 			}
26995d9e75c4SJan Schmidt 			p->locks[level] = BTRFS_READ_LOCK;
27005d9e75c4SJan Schmidt 			p->nodes[level] = b;
27015d9e75c4SJan Schmidt 			b = tree_mod_log_rewind(root->fs_info, b, time_seq);
27025d9e75c4SJan Schmidt 			if (b != p->nodes[level]) {
27035d9e75c4SJan Schmidt 				btrfs_tree_unlock_rw(p->nodes[level],
27045d9e75c4SJan Schmidt 						     p->locks[level]);
27055d9e75c4SJan Schmidt 				p->locks[level] = 0;
27065d9e75c4SJan Schmidt 				p->nodes[level] = b;
27075d9e75c4SJan Schmidt 			}
27085d9e75c4SJan Schmidt 		} else {
27095d9e75c4SJan Schmidt 			p->slots[level] = slot;
27105d9e75c4SJan Schmidt 			unlock_up(p, level, lowest_unlock, 0, NULL);
27115d9e75c4SJan Schmidt 			goto done;
27125d9e75c4SJan Schmidt 		}
27135d9e75c4SJan Schmidt 	}
27145d9e75c4SJan Schmidt 	ret = 1;
27155d9e75c4SJan Schmidt done:
27165d9e75c4SJan Schmidt 	if (!p->leave_spinning)
27175d9e75c4SJan Schmidt 		btrfs_set_path_blocking(p);
27185d9e75c4SJan Schmidt 	if (ret < 0)
27195d9e75c4SJan Schmidt 		btrfs_release_path(p);
27205d9e75c4SJan Schmidt 
27215d9e75c4SJan Schmidt 	return ret;
27225d9e75c4SJan Schmidt }
27235d9e75c4SJan Schmidt 
27245d9e75c4SJan Schmidt /*
272574123bd7SChris Mason  * adjust the pointers going up the tree, starting at level
272674123bd7SChris Mason  * making sure the right key of each node is points to 'key'.
272774123bd7SChris Mason  * This is used after shifting pointers to the left, so it stops
272874123bd7SChris Mason  * fixing up pointers when a given leaf/node is not in slot 0 of the
272974123bd7SChris Mason  * higher levels
2730aa5d6bedSChris Mason  *
273174123bd7SChris Mason  */
2732143bede5SJeff Mahoney static void fixup_low_keys(struct btrfs_trans_handle *trans,
27335f39d397SChris Mason 			   struct btrfs_root *root, struct btrfs_path *path,
27345f39d397SChris Mason 			   struct btrfs_disk_key *key, int level)
2735be0e5c09SChris Mason {
2736be0e5c09SChris Mason 	int i;
27375f39d397SChris Mason 	struct extent_buffer *t;
27385f39d397SChris Mason 
2739234b63a0SChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2740be0e5c09SChris Mason 		int tslot = path->slots[i];
2741eb60ceacSChris Mason 		if (!path->nodes[i])
2742be0e5c09SChris Mason 			break;
27435f39d397SChris Mason 		t = path->nodes[i];
2744f230475eSJan Schmidt 		tree_mod_log_set_node_key(root->fs_info, t, key, tslot, 1);
27455f39d397SChris Mason 		btrfs_set_node_key(t, key, tslot);
2746d6025579SChris Mason 		btrfs_mark_buffer_dirty(path->nodes[i]);
2747be0e5c09SChris Mason 		if (tslot != 0)
2748be0e5c09SChris Mason 			break;
2749be0e5c09SChris Mason 	}
2750be0e5c09SChris Mason }
2751be0e5c09SChris Mason 
275274123bd7SChris Mason /*
275331840ae1SZheng Yan  * update item key.
275431840ae1SZheng Yan  *
275531840ae1SZheng Yan  * This function isn't completely safe. It's the caller's responsibility
275631840ae1SZheng Yan  * that the new key won't break the order
275731840ae1SZheng Yan  */
2758143bede5SJeff Mahoney void btrfs_set_item_key_safe(struct btrfs_trans_handle *trans,
275931840ae1SZheng Yan 			     struct btrfs_root *root, struct btrfs_path *path,
276031840ae1SZheng Yan 			     struct btrfs_key *new_key)
276131840ae1SZheng Yan {
276231840ae1SZheng Yan 	struct btrfs_disk_key disk_key;
276331840ae1SZheng Yan 	struct extent_buffer *eb;
276431840ae1SZheng Yan 	int slot;
276531840ae1SZheng Yan 
276631840ae1SZheng Yan 	eb = path->nodes[0];
276731840ae1SZheng Yan 	slot = path->slots[0];
276831840ae1SZheng Yan 	if (slot > 0) {
276931840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot - 1);
2770143bede5SJeff Mahoney 		BUG_ON(comp_keys(&disk_key, new_key) >= 0);
277131840ae1SZheng Yan 	}
277231840ae1SZheng Yan 	if (slot < btrfs_header_nritems(eb) - 1) {
277331840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot + 1);
2774143bede5SJeff Mahoney 		BUG_ON(comp_keys(&disk_key, new_key) <= 0);
277531840ae1SZheng Yan 	}
277631840ae1SZheng Yan 
277731840ae1SZheng Yan 	btrfs_cpu_key_to_disk(&disk_key, new_key);
277831840ae1SZheng Yan 	btrfs_set_item_key(eb, &disk_key, slot);
277931840ae1SZheng Yan 	btrfs_mark_buffer_dirty(eb);
278031840ae1SZheng Yan 	if (slot == 0)
278131840ae1SZheng Yan 		fixup_low_keys(trans, root, path, &disk_key, 1);
278231840ae1SZheng Yan }
278331840ae1SZheng Yan 
278431840ae1SZheng Yan /*
278574123bd7SChris Mason  * try to push data from one node into the next node left in the
278679f95c82SChris Mason  * tree.
2787aa5d6bedSChris Mason  *
2788aa5d6bedSChris Mason  * returns 0 if some ptrs were pushed left, < 0 if there was some horrible
2789aa5d6bedSChris Mason  * error, and > 0 if there was no room in the left hand block.
279074123bd7SChris Mason  */
279198ed5174SChris Mason static int push_node_left(struct btrfs_trans_handle *trans,
279298ed5174SChris Mason 			  struct btrfs_root *root, struct extent_buffer *dst,
2793971a1f66SChris Mason 			  struct extent_buffer *src, int empty)
2794be0e5c09SChris Mason {
2795be0e5c09SChris Mason 	int push_items = 0;
2796bb803951SChris Mason 	int src_nritems;
2797bb803951SChris Mason 	int dst_nritems;
2798aa5d6bedSChris Mason 	int ret = 0;
2799be0e5c09SChris Mason 
28005f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
28015f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
2802123abc88SChris Mason 	push_items = BTRFS_NODEPTRS_PER_BLOCK(root) - dst_nritems;
28037bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
28047bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
280554aa1f4dSChris Mason 
2806bce4eae9SChris Mason 	if (!empty && src_nritems <= 8)
2807971a1f66SChris Mason 		return 1;
2808971a1f66SChris Mason 
2809d397712bSChris Mason 	if (push_items <= 0)
2810be0e5c09SChris Mason 		return 1;
2811be0e5c09SChris Mason 
2812bce4eae9SChris Mason 	if (empty) {
2813971a1f66SChris Mason 		push_items = min(src_nritems, push_items);
2814bce4eae9SChris Mason 		if (push_items < src_nritems) {
2815bce4eae9SChris Mason 			/* leave at least 8 pointers in the node if
2816bce4eae9SChris Mason 			 * we aren't going to empty it
2817bce4eae9SChris Mason 			 */
2818bce4eae9SChris Mason 			if (src_nritems - push_items < 8) {
2819bce4eae9SChris Mason 				if (push_items <= 8)
2820bce4eae9SChris Mason 					return 1;
2821bce4eae9SChris Mason 				push_items -= 8;
2822bce4eae9SChris Mason 			}
2823bce4eae9SChris Mason 		}
2824bce4eae9SChris Mason 	} else
2825bce4eae9SChris Mason 		push_items = min(src_nritems - 8, push_items);
282679f95c82SChris Mason 
2827f230475eSJan Schmidt 	tree_mod_log_eb_copy(root->fs_info, dst, src, dst_nritems, 0,
2828f230475eSJan Schmidt 			     push_items);
28295f39d397SChris Mason 	copy_extent_buffer(dst, src,
28305f39d397SChris Mason 			   btrfs_node_key_ptr_offset(dst_nritems),
28315f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
2832123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
28335f39d397SChris Mason 
2834bb803951SChris Mason 	if (push_items < src_nritems) {
2835f230475eSJan Schmidt 		tree_mod_log_eb_move(root->fs_info, src, 0, push_items,
2836f230475eSJan Schmidt 				     src_nritems - push_items);
28375f39d397SChris Mason 		memmove_extent_buffer(src, btrfs_node_key_ptr_offset(0),
28385f39d397SChris Mason 				      btrfs_node_key_ptr_offset(push_items),
2839e2fa7227SChris Mason 				      (src_nritems - push_items) *
2840123abc88SChris Mason 				      sizeof(struct btrfs_key_ptr));
2841bb803951SChris Mason 	}
28425f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
28435f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
28445f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
28455f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
284631840ae1SZheng Yan 
2847bb803951SChris Mason 	return ret;
2848be0e5c09SChris Mason }
2849be0e5c09SChris Mason 
285097571fd0SChris Mason /*
285179f95c82SChris Mason  * try to push data from one node into the next node right in the
285279f95c82SChris Mason  * tree.
285379f95c82SChris Mason  *
285479f95c82SChris Mason  * returns 0 if some ptrs were pushed, < 0 if there was some horrible
285579f95c82SChris Mason  * error, and > 0 if there was no room in the right hand block.
285679f95c82SChris Mason  *
285779f95c82SChris Mason  * this will  only push up to 1/2 the contents of the left node over
285879f95c82SChris Mason  */
28595f39d397SChris Mason static int balance_node_right(struct btrfs_trans_handle *trans,
28605f39d397SChris Mason 			      struct btrfs_root *root,
28615f39d397SChris Mason 			      struct extent_buffer *dst,
28625f39d397SChris Mason 			      struct extent_buffer *src)
286379f95c82SChris Mason {
286479f95c82SChris Mason 	int push_items = 0;
286579f95c82SChris Mason 	int max_push;
286679f95c82SChris Mason 	int src_nritems;
286779f95c82SChris Mason 	int dst_nritems;
286879f95c82SChris Mason 	int ret = 0;
286979f95c82SChris Mason 
28707bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
28717bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
28727bb86316SChris Mason 
28735f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
28745f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
2875123abc88SChris Mason 	push_items = BTRFS_NODEPTRS_PER_BLOCK(root) - dst_nritems;
2876d397712bSChris Mason 	if (push_items <= 0)
287779f95c82SChris Mason 		return 1;
2878bce4eae9SChris Mason 
2879d397712bSChris Mason 	if (src_nritems < 4)
2880bce4eae9SChris Mason 		return 1;
288179f95c82SChris Mason 
288279f95c82SChris Mason 	max_push = src_nritems / 2 + 1;
288379f95c82SChris Mason 	/* don't try to empty the node */
2884d397712bSChris Mason 	if (max_push >= src_nritems)
288579f95c82SChris Mason 		return 1;
2886252c38f0SYan 
288779f95c82SChris Mason 	if (max_push < push_items)
288879f95c82SChris Mason 		push_items = max_push;
288979f95c82SChris Mason 
2890f230475eSJan Schmidt 	tree_mod_log_eb_move(root->fs_info, dst, push_items, 0, dst_nritems);
28915f39d397SChris Mason 	memmove_extent_buffer(dst, btrfs_node_key_ptr_offset(push_items),
28925f39d397SChris Mason 				      btrfs_node_key_ptr_offset(0),
28935f39d397SChris Mason 				      (dst_nritems) *
28945f39d397SChris Mason 				      sizeof(struct btrfs_key_ptr));
2895d6025579SChris Mason 
2896f230475eSJan Schmidt 	tree_mod_log_eb_copy(root->fs_info, dst, src, 0,
2897f230475eSJan Schmidt 			     src_nritems - push_items, push_items);
28985f39d397SChris Mason 	copy_extent_buffer(dst, src,
28995f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
29005f39d397SChris Mason 			   btrfs_node_key_ptr_offset(src_nritems - push_items),
2901123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
290279f95c82SChris Mason 
29035f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
29045f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
290579f95c82SChris Mason 
29065f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
29075f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
290831840ae1SZheng Yan 
290979f95c82SChris Mason 	return ret;
291079f95c82SChris Mason }
291179f95c82SChris Mason 
291279f95c82SChris Mason /*
291397571fd0SChris Mason  * helper function to insert a new root level in the tree.
291497571fd0SChris Mason  * A new node is allocated, and a single item is inserted to
291597571fd0SChris Mason  * point to the existing root
2916aa5d6bedSChris Mason  *
2917aa5d6bedSChris Mason  * returns zero on success or < 0 on failure.
291897571fd0SChris Mason  */
2919d397712bSChris Mason static noinline int insert_new_root(struct btrfs_trans_handle *trans,
29205f39d397SChris Mason 			   struct btrfs_root *root,
29215f39d397SChris Mason 			   struct btrfs_path *path, int level)
292274123bd7SChris Mason {
29237bb86316SChris Mason 	u64 lower_gen;
29245f39d397SChris Mason 	struct extent_buffer *lower;
29255f39d397SChris Mason 	struct extent_buffer *c;
2926925baeddSChris Mason 	struct extent_buffer *old;
29275f39d397SChris Mason 	struct btrfs_disk_key lower_key;
29285c680ed6SChris Mason 
29295c680ed6SChris Mason 	BUG_ON(path->nodes[level]);
29305c680ed6SChris Mason 	BUG_ON(path->nodes[level-1] != root->node);
29315c680ed6SChris Mason 
29327bb86316SChris Mason 	lower = path->nodes[level-1];
29337bb86316SChris Mason 	if (level == 1)
29347bb86316SChris Mason 		btrfs_item_key(lower, &lower_key, 0);
29357bb86316SChris Mason 	else
29367bb86316SChris Mason 		btrfs_node_key(lower, &lower_key, 0);
29377bb86316SChris Mason 
293831840ae1SZheng Yan 	c = btrfs_alloc_free_block(trans, root, root->nodesize, 0,
29395d4f98a2SYan Zheng 				   root->root_key.objectid, &lower_key,
29405581a51aSJan Schmidt 				   level, root->node->start, 0);
29415f39d397SChris Mason 	if (IS_ERR(c))
29425f39d397SChris Mason 		return PTR_ERR(c);
2943925baeddSChris Mason 
2944f0486c68SYan, Zheng 	root_add_used(root, root->nodesize);
2945f0486c68SYan, Zheng 
29465d4f98a2SYan Zheng 	memset_extent_buffer(c, 0, 0, sizeof(struct btrfs_header));
29475f39d397SChris Mason 	btrfs_set_header_nritems(c, 1);
29485f39d397SChris Mason 	btrfs_set_header_level(c, level);
2949db94535dSChris Mason 	btrfs_set_header_bytenr(c, c->start);
29505f39d397SChris Mason 	btrfs_set_header_generation(c, trans->transid);
29515d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(c, BTRFS_MIXED_BACKREF_REV);
29525f39d397SChris Mason 	btrfs_set_header_owner(c, root->root_key.objectid);
2953d5719762SChris Mason 
29545f39d397SChris Mason 	write_extent_buffer(c, root->fs_info->fsid,
29555f39d397SChris Mason 			    (unsigned long)btrfs_header_fsid(c),
29565f39d397SChris Mason 			    BTRFS_FSID_SIZE);
2957e17cade2SChris Mason 
2958e17cade2SChris Mason 	write_extent_buffer(c, root->fs_info->chunk_tree_uuid,
2959e17cade2SChris Mason 			    (unsigned long)btrfs_header_chunk_tree_uuid(c),
2960e17cade2SChris Mason 			    BTRFS_UUID_SIZE);
2961e17cade2SChris Mason 
29625f39d397SChris Mason 	btrfs_set_node_key(c, &lower_key, 0);
2963db94535dSChris Mason 	btrfs_set_node_blockptr(c, 0, lower->start);
29647bb86316SChris Mason 	lower_gen = btrfs_header_generation(lower);
296531840ae1SZheng Yan 	WARN_ON(lower_gen != trans->transid);
29667bb86316SChris Mason 
29677bb86316SChris Mason 	btrfs_set_node_ptr_generation(c, 0, lower_gen);
29685f39d397SChris Mason 
29695f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
2970d5719762SChris Mason 
2971925baeddSChris Mason 	old = root->node;
2972f230475eSJan Schmidt 	tree_mod_log_set_root_pointer(root, c);
2973240f62c8SChris Mason 	rcu_assign_pointer(root->node, c);
2974925baeddSChris Mason 
2975925baeddSChris Mason 	/* the super has an extra ref to root->node */
2976925baeddSChris Mason 	free_extent_buffer(old);
2977925baeddSChris Mason 
29780b86a832SChris Mason 	add_root_to_dirty_list(root);
29795f39d397SChris Mason 	extent_buffer_get(c);
29805f39d397SChris Mason 	path->nodes[level] = c;
2981bd681513SChris Mason 	path->locks[level] = BTRFS_WRITE_LOCK;
298274123bd7SChris Mason 	path->slots[level] = 0;
298374123bd7SChris Mason 	return 0;
298474123bd7SChris Mason }
29855c680ed6SChris Mason 
29865c680ed6SChris Mason /*
29875c680ed6SChris Mason  * worker function to insert a single pointer in a node.
29885c680ed6SChris Mason  * the node should have enough room for the pointer already
298997571fd0SChris Mason  *
29905c680ed6SChris Mason  * slot and level indicate where you want the key to go, and
29915c680ed6SChris Mason  * blocknr is the block the key points to.
29925c680ed6SChris Mason  */
2993143bede5SJeff Mahoney static void insert_ptr(struct btrfs_trans_handle *trans,
2994143bede5SJeff Mahoney 		       struct btrfs_root *root, struct btrfs_path *path,
2995143bede5SJeff Mahoney 		       struct btrfs_disk_key *key, u64 bytenr,
2996c3e06965SJan Schmidt 		       int slot, int level)
29975c680ed6SChris Mason {
29985f39d397SChris Mason 	struct extent_buffer *lower;
29995c680ed6SChris Mason 	int nritems;
3000f3ea38daSJan Schmidt 	int ret;
30015c680ed6SChris Mason 
30025c680ed6SChris Mason 	BUG_ON(!path->nodes[level]);
3003f0486c68SYan, Zheng 	btrfs_assert_tree_locked(path->nodes[level]);
30045f39d397SChris Mason 	lower = path->nodes[level];
30055f39d397SChris Mason 	nritems = btrfs_header_nritems(lower);
3006c293498bSStoyan Gaydarov 	BUG_ON(slot > nritems);
3007143bede5SJeff Mahoney 	BUG_ON(nritems == BTRFS_NODEPTRS_PER_BLOCK(root));
300874123bd7SChris Mason 	if (slot != nritems) {
3009c3e06965SJan Schmidt 		if (level)
3010f3ea38daSJan Schmidt 			tree_mod_log_eb_move(root->fs_info, lower, slot + 1,
3011f3ea38daSJan Schmidt 					     slot, nritems - slot);
30125f39d397SChris Mason 		memmove_extent_buffer(lower,
30135f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot + 1),
30145f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot),
3015123abc88SChris Mason 			      (nritems - slot) * sizeof(struct btrfs_key_ptr));
301674123bd7SChris Mason 	}
3017c3e06965SJan Schmidt 	if (level) {
3018f3ea38daSJan Schmidt 		ret = tree_mod_log_insert_key(root->fs_info, lower, slot,
3019f3ea38daSJan Schmidt 					      MOD_LOG_KEY_ADD);
3020f3ea38daSJan Schmidt 		BUG_ON(ret < 0);
3021f3ea38daSJan Schmidt 	}
30225f39d397SChris Mason 	btrfs_set_node_key(lower, key, slot);
3023db94535dSChris Mason 	btrfs_set_node_blockptr(lower, slot, bytenr);
302474493f7aSChris Mason 	WARN_ON(trans->transid == 0);
302574493f7aSChris Mason 	btrfs_set_node_ptr_generation(lower, slot, trans->transid);
30265f39d397SChris Mason 	btrfs_set_header_nritems(lower, nritems + 1);
30275f39d397SChris Mason 	btrfs_mark_buffer_dirty(lower);
302874123bd7SChris Mason }
302974123bd7SChris Mason 
303097571fd0SChris Mason /*
303197571fd0SChris Mason  * split the node at the specified level in path in two.
303297571fd0SChris Mason  * The path is corrected to point to the appropriate node after the split
303397571fd0SChris Mason  *
303497571fd0SChris Mason  * Before splitting this tries to make some room in the node by pushing
303597571fd0SChris Mason  * left and right, if either one works, it returns right away.
3036aa5d6bedSChris Mason  *
3037aa5d6bedSChris Mason  * returns 0 on success and < 0 on failure
303897571fd0SChris Mason  */
3039e02119d5SChris Mason static noinline int split_node(struct btrfs_trans_handle *trans,
3040e02119d5SChris Mason 			       struct btrfs_root *root,
3041e02119d5SChris Mason 			       struct btrfs_path *path, int level)
3042be0e5c09SChris Mason {
30435f39d397SChris Mason 	struct extent_buffer *c;
30445f39d397SChris Mason 	struct extent_buffer *split;
30455f39d397SChris Mason 	struct btrfs_disk_key disk_key;
3046be0e5c09SChris Mason 	int mid;
30475c680ed6SChris Mason 	int ret;
30487518a238SChris Mason 	u32 c_nritems;
3049be0e5c09SChris Mason 
30505f39d397SChris Mason 	c = path->nodes[level];
30517bb86316SChris Mason 	WARN_ON(btrfs_header_generation(c) != trans->transid);
30525f39d397SChris Mason 	if (c == root->node) {
30535c680ed6SChris Mason 		/* trying to split the root, lets make a new one */
3054e089f05cSChris Mason 		ret = insert_new_root(trans, root, path, level + 1);
30555c680ed6SChris Mason 		if (ret)
30565c680ed6SChris Mason 			return ret;
3057b3612421SChris Mason 	} else {
3058e66f709bSChris Mason 		ret = push_nodes_for_insert(trans, root, path, level);
30595f39d397SChris Mason 		c = path->nodes[level];
30605f39d397SChris Mason 		if (!ret && btrfs_header_nritems(c) <
3061c448acf0SChris Mason 		    BTRFS_NODEPTRS_PER_BLOCK(root) - 3)
3062e66f709bSChris Mason 			return 0;
306354aa1f4dSChris Mason 		if (ret < 0)
306454aa1f4dSChris Mason 			return ret;
30655c680ed6SChris Mason 	}
3066e66f709bSChris Mason 
30675f39d397SChris Mason 	c_nritems = btrfs_header_nritems(c);
30685d4f98a2SYan Zheng 	mid = (c_nritems + 1) / 2;
30695d4f98a2SYan Zheng 	btrfs_node_key(c, &disk_key, mid);
30707bb86316SChris Mason 
30715d4f98a2SYan Zheng 	split = btrfs_alloc_free_block(trans, root, root->nodesize, 0,
30727bb86316SChris Mason 					root->root_key.objectid,
30735581a51aSJan Schmidt 					&disk_key, level, c->start, 0);
30745f39d397SChris Mason 	if (IS_ERR(split))
30755f39d397SChris Mason 		return PTR_ERR(split);
307654aa1f4dSChris Mason 
3077f0486c68SYan, Zheng 	root_add_used(root, root->nodesize);
3078f0486c68SYan, Zheng 
30795d4f98a2SYan Zheng 	memset_extent_buffer(split, 0, 0, sizeof(struct btrfs_header));
30805f39d397SChris Mason 	btrfs_set_header_level(split, btrfs_header_level(c));
3081db94535dSChris Mason 	btrfs_set_header_bytenr(split, split->start);
30825f39d397SChris Mason 	btrfs_set_header_generation(split, trans->transid);
30835d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(split, BTRFS_MIXED_BACKREF_REV);
30845f39d397SChris Mason 	btrfs_set_header_owner(split, root->root_key.objectid);
30855f39d397SChris Mason 	write_extent_buffer(split, root->fs_info->fsid,
30865f39d397SChris Mason 			    (unsigned long)btrfs_header_fsid(split),
30875f39d397SChris Mason 			    BTRFS_FSID_SIZE);
3088e17cade2SChris Mason 	write_extent_buffer(split, root->fs_info->chunk_tree_uuid,
3089e17cade2SChris Mason 			    (unsigned long)btrfs_header_chunk_tree_uuid(split),
3090e17cade2SChris Mason 			    BTRFS_UUID_SIZE);
30915f39d397SChris Mason 
3092f230475eSJan Schmidt 	tree_mod_log_eb_copy(root->fs_info, split, c, 0, mid, c_nritems - mid);
30935f39d397SChris Mason 	copy_extent_buffer(split, c,
30945f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
30955f39d397SChris Mason 			   btrfs_node_key_ptr_offset(mid),
3096123abc88SChris Mason 			   (c_nritems - mid) * sizeof(struct btrfs_key_ptr));
30975f39d397SChris Mason 	btrfs_set_header_nritems(split, c_nritems - mid);
30985f39d397SChris Mason 	btrfs_set_header_nritems(c, mid);
3099aa5d6bedSChris Mason 	ret = 0;
3100aa5d6bedSChris Mason 
31015f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
31025f39d397SChris Mason 	btrfs_mark_buffer_dirty(split);
31035f39d397SChris Mason 
3104143bede5SJeff Mahoney 	insert_ptr(trans, root, path, &disk_key, split->start,
3105c3e06965SJan Schmidt 		   path->slots[level + 1] + 1, level + 1);
3106aa5d6bedSChris Mason 
31075de08d7dSChris Mason 	if (path->slots[level] >= mid) {
31085c680ed6SChris Mason 		path->slots[level] -= mid;
3109925baeddSChris Mason 		btrfs_tree_unlock(c);
31105f39d397SChris Mason 		free_extent_buffer(c);
31115f39d397SChris Mason 		path->nodes[level] = split;
31125c680ed6SChris Mason 		path->slots[level + 1] += 1;
3113eb60ceacSChris Mason 	} else {
3114925baeddSChris Mason 		btrfs_tree_unlock(split);
31155f39d397SChris Mason 		free_extent_buffer(split);
3116be0e5c09SChris Mason 	}
3117aa5d6bedSChris Mason 	return ret;
3118be0e5c09SChris Mason }
3119be0e5c09SChris Mason 
312074123bd7SChris Mason /*
312174123bd7SChris Mason  * how many bytes are required to store the items in a leaf.  start
312274123bd7SChris Mason  * and nr indicate which items in the leaf to check.  This totals up the
312374123bd7SChris Mason  * space used both by the item structs and the item data
312474123bd7SChris Mason  */
31255f39d397SChris Mason static int leaf_space_used(struct extent_buffer *l, int start, int nr)
3126be0e5c09SChris Mason {
3127be0e5c09SChris Mason 	int data_len;
31285f39d397SChris Mason 	int nritems = btrfs_header_nritems(l);
3129d4dbff95SChris Mason 	int end = min(nritems, start + nr) - 1;
3130be0e5c09SChris Mason 
3131be0e5c09SChris Mason 	if (!nr)
3132be0e5c09SChris Mason 		return 0;
31335f39d397SChris Mason 	data_len = btrfs_item_end_nr(l, start);
31345f39d397SChris Mason 	data_len = data_len - btrfs_item_offset_nr(l, end);
31350783fcfcSChris Mason 	data_len += sizeof(struct btrfs_item) * nr;
3136d4dbff95SChris Mason 	WARN_ON(data_len < 0);
3137be0e5c09SChris Mason 	return data_len;
3138be0e5c09SChris Mason }
3139be0e5c09SChris Mason 
314074123bd7SChris Mason /*
3141d4dbff95SChris Mason  * The space between the end of the leaf items and
3142d4dbff95SChris Mason  * the start of the leaf data.  IOW, how much room
3143d4dbff95SChris Mason  * the leaf has left for both items and data
3144d4dbff95SChris Mason  */
3145d397712bSChris Mason noinline int btrfs_leaf_free_space(struct btrfs_root *root,
3146e02119d5SChris Mason 				   struct extent_buffer *leaf)
3147d4dbff95SChris Mason {
31485f39d397SChris Mason 	int nritems = btrfs_header_nritems(leaf);
31495f39d397SChris Mason 	int ret;
31505f39d397SChris Mason 	ret = BTRFS_LEAF_DATA_SIZE(root) - leaf_space_used(leaf, 0, nritems);
31515f39d397SChris Mason 	if (ret < 0) {
3152d397712bSChris Mason 		printk(KERN_CRIT "leaf free space ret %d, leaf data size %lu, "
3153d397712bSChris Mason 		       "used %d nritems %d\n",
3154ae2f5411SJens Axboe 		       ret, (unsigned long) BTRFS_LEAF_DATA_SIZE(root),
31555f39d397SChris Mason 		       leaf_space_used(leaf, 0, nritems), nritems);
31565f39d397SChris Mason 	}
31575f39d397SChris Mason 	return ret;
3158d4dbff95SChris Mason }
3159d4dbff95SChris Mason 
316099d8f83cSChris Mason /*
316199d8f83cSChris Mason  * min slot controls the lowest index we're willing to push to the
316299d8f83cSChris Mason  * right.  We'll push up to and including min_slot, but no lower
316399d8f83cSChris Mason  */
316444871b1bSChris Mason static noinline int __push_leaf_right(struct btrfs_trans_handle *trans,
316544871b1bSChris Mason 				      struct btrfs_root *root,
316644871b1bSChris Mason 				      struct btrfs_path *path,
316744871b1bSChris Mason 				      int data_size, int empty,
316844871b1bSChris Mason 				      struct extent_buffer *right,
316999d8f83cSChris Mason 				      int free_space, u32 left_nritems,
317099d8f83cSChris Mason 				      u32 min_slot)
317100ec4c51SChris Mason {
31725f39d397SChris Mason 	struct extent_buffer *left = path->nodes[0];
317344871b1bSChris Mason 	struct extent_buffer *upper = path->nodes[1];
3174cfed81a0SChris Mason 	struct btrfs_map_token token;
31755f39d397SChris Mason 	struct btrfs_disk_key disk_key;
317600ec4c51SChris Mason 	int slot;
317734a38218SChris Mason 	u32 i;
317800ec4c51SChris Mason 	int push_space = 0;
317900ec4c51SChris Mason 	int push_items = 0;
31800783fcfcSChris Mason 	struct btrfs_item *item;
318134a38218SChris Mason 	u32 nr;
31827518a238SChris Mason 	u32 right_nritems;
31835f39d397SChris Mason 	u32 data_end;
3184db94535dSChris Mason 	u32 this_item_size;
318500ec4c51SChris Mason 
3186cfed81a0SChris Mason 	btrfs_init_map_token(&token);
3187cfed81a0SChris Mason 
318834a38218SChris Mason 	if (empty)
318934a38218SChris Mason 		nr = 0;
319034a38218SChris Mason 	else
319199d8f83cSChris Mason 		nr = max_t(u32, 1, min_slot);
319234a38218SChris Mason 
319331840ae1SZheng Yan 	if (path->slots[0] >= left_nritems)
319487b29b20SYan Zheng 		push_space += data_size;
319531840ae1SZheng Yan 
319644871b1bSChris Mason 	slot = path->slots[1];
319734a38218SChris Mason 	i = left_nritems - 1;
319834a38218SChris Mason 	while (i >= nr) {
31995f39d397SChris Mason 		item = btrfs_item_nr(left, i);
3200db94535dSChris Mason 
320131840ae1SZheng Yan 		if (!empty && push_items > 0) {
320231840ae1SZheng Yan 			if (path->slots[0] > i)
320331840ae1SZheng Yan 				break;
320431840ae1SZheng Yan 			if (path->slots[0] == i) {
320531840ae1SZheng Yan 				int space = btrfs_leaf_free_space(root, left);
320631840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
320731840ae1SZheng Yan 					break;
320831840ae1SZheng Yan 			}
320931840ae1SZheng Yan 		}
321031840ae1SZheng Yan 
321100ec4c51SChris Mason 		if (path->slots[0] == i)
321287b29b20SYan Zheng 			push_space += data_size;
3213db94535dSChris Mason 
3214db94535dSChris Mason 		this_item_size = btrfs_item_size(left, item);
3215db94535dSChris Mason 		if (this_item_size + sizeof(*item) + push_space > free_space)
321600ec4c51SChris Mason 			break;
321731840ae1SZheng Yan 
321800ec4c51SChris Mason 		push_items++;
3219db94535dSChris Mason 		push_space += this_item_size + sizeof(*item);
322034a38218SChris Mason 		if (i == 0)
322134a38218SChris Mason 			break;
322234a38218SChris Mason 		i--;
3223db94535dSChris Mason 	}
32245f39d397SChris Mason 
3225925baeddSChris Mason 	if (push_items == 0)
3226925baeddSChris Mason 		goto out_unlock;
32275f39d397SChris Mason 
322834a38218SChris Mason 	if (!empty && push_items == left_nritems)
3229a429e513SChris Mason 		WARN_ON(1);
32305f39d397SChris Mason 
323100ec4c51SChris Mason 	/* push left to right */
32325f39d397SChris Mason 	right_nritems = btrfs_header_nritems(right);
323334a38218SChris Mason 
32345f39d397SChris Mason 	push_space = btrfs_item_end_nr(left, left_nritems - push_items);
3235123abc88SChris Mason 	push_space -= leaf_data_end(root, left);
32365f39d397SChris Mason 
323700ec4c51SChris Mason 	/* make room in the right data area */
32385f39d397SChris Mason 	data_end = leaf_data_end(root, right);
32395f39d397SChris Mason 	memmove_extent_buffer(right,
32405f39d397SChris Mason 			      btrfs_leaf_data(right) + data_end - push_space,
32415f39d397SChris Mason 			      btrfs_leaf_data(right) + data_end,
32425f39d397SChris Mason 			      BTRFS_LEAF_DATA_SIZE(root) - data_end);
32435f39d397SChris Mason 
324400ec4c51SChris Mason 	/* copy from the left data area */
32455f39d397SChris Mason 	copy_extent_buffer(right, left, btrfs_leaf_data(right) +
3246d6025579SChris Mason 		     BTRFS_LEAF_DATA_SIZE(root) - push_space,
3247d6025579SChris Mason 		     btrfs_leaf_data(left) + leaf_data_end(root, left),
3248d6025579SChris Mason 		     push_space);
32495f39d397SChris Mason 
32505f39d397SChris Mason 	memmove_extent_buffer(right, btrfs_item_nr_offset(push_items),
32515f39d397SChris Mason 			      btrfs_item_nr_offset(0),
32520783fcfcSChris Mason 			      right_nritems * sizeof(struct btrfs_item));
32535f39d397SChris Mason 
325400ec4c51SChris Mason 	/* copy the items from left to right */
32555f39d397SChris Mason 	copy_extent_buffer(right, left, btrfs_item_nr_offset(0),
32565f39d397SChris Mason 		   btrfs_item_nr_offset(left_nritems - push_items),
32570783fcfcSChris Mason 		   push_items * sizeof(struct btrfs_item));
325800ec4c51SChris Mason 
325900ec4c51SChris Mason 	/* update the item pointers */
32607518a238SChris Mason 	right_nritems += push_items;
32615f39d397SChris Mason 	btrfs_set_header_nritems(right, right_nritems);
3262123abc88SChris Mason 	push_space = BTRFS_LEAF_DATA_SIZE(root);
32637518a238SChris Mason 	for (i = 0; i < right_nritems; i++) {
32645f39d397SChris Mason 		item = btrfs_item_nr(right, i);
3265cfed81a0SChris Mason 		push_space -= btrfs_token_item_size(right, item, &token);
3266cfed81a0SChris Mason 		btrfs_set_token_item_offset(right, item, push_space, &token);
3267db94535dSChris Mason 	}
3268db94535dSChris Mason 
32697518a238SChris Mason 	left_nritems -= push_items;
32705f39d397SChris Mason 	btrfs_set_header_nritems(left, left_nritems);
327100ec4c51SChris Mason 
327234a38218SChris Mason 	if (left_nritems)
32735f39d397SChris Mason 		btrfs_mark_buffer_dirty(left);
3274f0486c68SYan, Zheng 	else
3275f0486c68SYan, Zheng 		clean_tree_block(trans, root, left);
3276f0486c68SYan, Zheng 
32775f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
3278a429e513SChris Mason 
32795f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
32805f39d397SChris Mason 	btrfs_set_node_key(upper, &disk_key, slot + 1);
3281d6025579SChris Mason 	btrfs_mark_buffer_dirty(upper);
328202217ed2SChris Mason 
328300ec4c51SChris Mason 	/* then fixup the leaf pointer in the path */
32847518a238SChris Mason 	if (path->slots[0] >= left_nritems) {
32857518a238SChris Mason 		path->slots[0] -= left_nritems;
3286925baeddSChris Mason 		if (btrfs_header_nritems(path->nodes[0]) == 0)
3287925baeddSChris Mason 			clean_tree_block(trans, root, path->nodes[0]);
3288925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
32895f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
32905f39d397SChris Mason 		path->nodes[0] = right;
329100ec4c51SChris Mason 		path->slots[1] += 1;
329200ec4c51SChris Mason 	} else {
3293925baeddSChris Mason 		btrfs_tree_unlock(right);
32945f39d397SChris Mason 		free_extent_buffer(right);
329500ec4c51SChris Mason 	}
329600ec4c51SChris Mason 	return 0;
3297925baeddSChris Mason 
3298925baeddSChris Mason out_unlock:
3299925baeddSChris Mason 	btrfs_tree_unlock(right);
3300925baeddSChris Mason 	free_extent_buffer(right);
3301925baeddSChris Mason 	return 1;
330200ec4c51SChris Mason }
3303925baeddSChris Mason 
330400ec4c51SChris Mason /*
330544871b1bSChris Mason  * push some data in the path leaf to the right, trying to free up at
330674123bd7SChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
330744871b1bSChris Mason  *
330844871b1bSChris Mason  * returns 1 if the push failed because the other node didn't have enough
330944871b1bSChris Mason  * room, 0 if everything worked out and < 0 if there were major errors.
331099d8f83cSChris Mason  *
331199d8f83cSChris Mason  * this will push starting from min_slot to the end of the leaf.  It won't
331299d8f83cSChris Mason  * push any slot lower than min_slot
331374123bd7SChris Mason  */
331444871b1bSChris Mason static int push_leaf_right(struct btrfs_trans_handle *trans, struct btrfs_root
331599d8f83cSChris Mason 			   *root, struct btrfs_path *path,
331699d8f83cSChris Mason 			   int min_data_size, int data_size,
331799d8f83cSChris Mason 			   int empty, u32 min_slot)
3318be0e5c09SChris Mason {
331944871b1bSChris Mason 	struct extent_buffer *left = path->nodes[0];
332044871b1bSChris Mason 	struct extent_buffer *right;
332144871b1bSChris Mason 	struct extent_buffer *upper;
332244871b1bSChris Mason 	int slot;
332344871b1bSChris Mason 	int free_space;
332444871b1bSChris Mason 	u32 left_nritems;
332544871b1bSChris Mason 	int ret;
332644871b1bSChris Mason 
332744871b1bSChris Mason 	if (!path->nodes[1])
332844871b1bSChris Mason 		return 1;
332944871b1bSChris Mason 
333044871b1bSChris Mason 	slot = path->slots[1];
333144871b1bSChris Mason 	upper = path->nodes[1];
333244871b1bSChris Mason 	if (slot >= btrfs_header_nritems(upper) - 1)
333344871b1bSChris Mason 		return 1;
333444871b1bSChris Mason 
333544871b1bSChris Mason 	btrfs_assert_tree_locked(path->nodes[1]);
333644871b1bSChris Mason 
333744871b1bSChris Mason 	right = read_node_slot(root, upper, slot + 1);
333891ca338dSTsutomu Itoh 	if (right == NULL)
333991ca338dSTsutomu Itoh 		return 1;
334091ca338dSTsutomu Itoh 
334144871b1bSChris Mason 	btrfs_tree_lock(right);
334244871b1bSChris Mason 	btrfs_set_lock_blocking(right);
334344871b1bSChris Mason 
334444871b1bSChris Mason 	free_space = btrfs_leaf_free_space(root, right);
334544871b1bSChris Mason 	if (free_space < data_size)
334644871b1bSChris Mason 		goto out_unlock;
334744871b1bSChris Mason 
334844871b1bSChris Mason 	/* cow and double check */
334944871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, right, upper,
335044871b1bSChris Mason 			      slot + 1, &right);
335144871b1bSChris Mason 	if (ret)
335244871b1bSChris Mason 		goto out_unlock;
335344871b1bSChris Mason 
335444871b1bSChris Mason 	free_space = btrfs_leaf_free_space(root, right);
335544871b1bSChris Mason 	if (free_space < data_size)
335644871b1bSChris Mason 		goto out_unlock;
335744871b1bSChris Mason 
335844871b1bSChris Mason 	left_nritems = btrfs_header_nritems(left);
335944871b1bSChris Mason 	if (left_nritems == 0)
336044871b1bSChris Mason 		goto out_unlock;
336144871b1bSChris Mason 
336299d8f83cSChris Mason 	return __push_leaf_right(trans, root, path, min_data_size, empty,
336399d8f83cSChris Mason 				right, free_space, left_nritems, min_slot);
336444871b1bSChris Mason out_unlock:
336544871b1bSChris Mason 	btrfs_tree_unlock(right);
336644871b1bSChris Mason 	free_extent_buffer(right);
336744871b1bSChris Mason 	return 1;
336844871b1bSChris Mason }
336944871b1bSChris Mason 
337044871b1bSChris Mason /*
337144871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
337244871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
337399d8f83cSChris Mason  *
337499d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
337599d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us do all the
337699d8f83cSChris Mason  * items
337744871b1bSChris Mason  */
337844871b1bSChris Mason static noinline int __push_leaf_left(struct btrfs_trans_handle *trans,
337944871b1bSChris Mason 				     struct btrfs_root *root,
338044871b1bSChris Mason 				     struct btrfs_path *path, int data_size,
338144871b1bSChris Mason 				     int empty, struct extent_buffer *left,
338299d8f83cSChris Mason 				     int free_space, u32 right_nritems,
338399d8f83cSChris Mason 				     u32 max_slot)
338444871b1bSChris Mason {
33855f39d397SChris Mason 	struct btrfs_disk_key disk_key;
33865f39d397SChris Mason 	struct extent_buffer *right = path->nodes[0];
3387be0e5c09SChris Mason 	int i;
3388be0e5c09SChris Mason 	int push_space = 0;
3389be0e5c09SChris Mason 	int push_items = 0;
33900783fcfcSChris Mason 	struct btrfs_item *item;
33917518a238SChris Mason 	u32 old_left_nritems;
339234a38218SChris Mason 	u32 nr;
3393aa5d6bedSChris Mason 	int ret = 0;
3394db94535dSChris Mason 	u32 this_item_size;
3395db94535dSChris Mason 	u32 old_left_item_size;
3396cfed81a0SChris Mason 	struct btrfs_map_token token;
3397cfed81a0SChris Mason 
3398cfed81a0SChris Mason 	btrfs_init_map_token(&token);
3399be0e5c09SChris Mason 
340034a38218SChris Mason 	if (empty)
340199d8f83cSChris Mason 		nr = min(right_nritems, max_slot);
340234a38218SChris Mason 	else
340399d8f83cSChris Mason 		nr = min(right_nritems - 1, max_slot);
340434a38218SChris Mason 
340534a38218SChris Mason 	for (i = 0; i < nr; i++) {
34065f39d397SChris Mason 		item = btrfs_item_nr(right, i);
3407db94535dSChris Mason 
340831840ae1SZheng Yan 		if (!empty && push_items > 0) {
340931840ae1SZheng Yan 			if (path->slots[0] < i)
341031840ae1SZheng Yan 				break;
341131840ae1SZheng Yan 			if (path->slots[0] == i) {
341231840ae1SZheng Yan 				int space = btrfs_leaf_free_space(root, right);
341331840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
341431840ae1SZheng Yan 					break;
341531840ae1SZheng Yan 			}
341631840ae1SZheng Yan 		}
341731840ae1SZheng Yan 
3418be0e5c09SChris Mason 		if (path->slots[0] == i)
341987b29b20SYan Zheng 			push_space += data_size;
3420db94535dSChris Mason 
3421db94535dSChris Mason 		this_item_size = btrfs_item_size(right, item);
3422db94535dSChris Mason 		if (this_item_size + sizeof(*item) + push_space > free_space)
3423be0e5c09SChris Mason 			break;
3424db94535dSChris Mason 
3425be0e5c09SChris Mason 		push_items++;
3426db94535dSChris Mason 		push_space += this_item_size + sizeof(*item);
3427be0e5c09SChris Mason 	}
3428db94535dSChris Mason 
3429be0e5c09SChris Mason 	if (push_items == 0) {
3430925baeddSChris Mason 		ret = 1;
3431925baeddSChris Mason 		goto out;
3432be0e5c09SChris Mason 	}
343334a38218SChris Mason 	if (!empty && push_items == btrfs_header_nritems(right))
3434a429e513SChris Mason 		WARN_ON(1);
34355f39d397SChris Mason 
3436be0e5c09SChris Mason 	/* push data from right to left */
34375f39d397SChris Mason 	copy_extent_buffer(left, right,
34385f39d397SChris Mason 			   btrfs_item_nr_offset(btrfs_header_nritems(left)),
34395f39d397SChris Mason 			   btrfs_item_nr_offset(0),
34405f39d397SChris Mason 			   push_items * sizeof(struct btrfs_item));
34415f39d397SChris Mason 
3442123abc88SChris Mason 	push_space = BTRFS_LEAF_DATA_SIZE(root) -
34435f39d397SChris Mason 		     btrfs_item_offset_nr(right, push_items - 1);
34445f39d397SChris Mason 
34455f39d397SChris Mason 	copy_extent_buffer(left, right, btrfs_leaf_data(left) +
3446d6025579SChris Mason 		     leaf_data_end(root, left) - push_space,
3447123abc88SChris Mason 		     btrfs_leaf_data(right) +
34485f39d397SChris Mason 		     btrfs_item_offset_nr(right, push_items - 1),
3449be0e5c09SChris Mason 		     push_space);
34505f39d397SChris Mason 	old_left_nritems = btrfs_header_nritems(left);
345187b29b20SYan Zheng 	BUG_ON(old_left_nritems <= 0);
3452eb60ceacSChris Mason 
3453db94535dSChris Mason 	old_left_item_size = btrfs_item_offset_nr(left, old_left_nritems - 1);
3454be0e5c09SChris Mason 	for (i = old_left_nritems; i < old_left_nritems + push_items; i++) {
34555f39d397SChris Mason 		u32 ioff;
3456db94535dSChris Mason 
34575f39d397SChris Mason 		item = btrfs_item_nr(left, i);
3458db94535dSChris Mason 
3459cfed81a0SChris Mason 		ioff = btrfs_token_item_offset(left, item, &token);
3460cfed81a0SChris Mason 		btrfs_set_token_item_offset(left, item,
3461cfed81a0SChris Mason 		      ioff - (BTRFS_LEAF_DATA_SIZE(root) - old_left_item_size),
3462cfed81a0SChris Mason 		      &token);
3463be0e5c09SChris Mason 	}
34645f39d397SChris Mason 	btrfs_set_header_nritems(left, old_left_nritems + push_items);
3465be0e5c09SChris Mason 
3466be0e5c09SChris Mason 	/* fixup right node */
346734a38218SChris Mason 	if (push_items > right_nritems) {
3468d397712bSChris Mason 		printk(KERN_CRIT "push items %d nr %u\n", push_items,
3469d397712bSChris Mason 		       right_nritems);
347034a38218SChris Mason 		WARN_ON(1);
347134a38218SChris Mason 	}
347234a38218SChris Mason 
347334a38218SChris Mason 	if (push_items < right_nritems) {
34745f39d397SChris Mason 		push_space = btrfs_item_offset_nr(right, push_items - 1) -
3475123abc88SChris Mason 						  leaf_data_end(root, right);
34765f39d397SChris Mason 		memmove_extent_buffer(right, btrfs_leaf_data(right) +
3477d6025579SChris Mason 				      BTRFS_LEAF_DATA_SIZE(root) - push_space,
3478d6025579SChris Mason 				      btrfs_leaf_data(right) +
3479123abc88SChris Mason 				      leaf_data_end(root, right), push_space);
34805f39d397SChris Mason 
34815f39d397SChris Mason 		memmove_extent_buffer(right, btrfs_item_nr_offset(0),
34825f39d397SChris Mason 			      btrfs_item_nr_offset(push_items),
34835f39d397SChris Mason 			     (btrfs_header_nritems(right) - push_items) *
34840783fcfcSChris Mason 			     sizeof(struct btrfs_item));
348534a38218SChris Mason 	}
3486eef1c494SYan 	right_nritems -= push_items;
3487eef1c494SYan 	btrfs_set_header_nritems(right, right_nritems);
3488123abc88SChris Mason 	push_space = BTRFS_LEAF_DATA_SIZE(root);
34895f39d397SChris Mason 	for (i = 0; i < right_nritems; i++) {
34905f39d397SChris Mason 		item = btrfs_item_nr(right, i);
3491db94535dSChris Mason 
3492cfed81a0SChris Mason 		push_space = push_space - btrfs_token_item_size(right,
3493cfed81a0SChris Mason 								item, &token);
3494cfed81a0SChris Mason 		btrfs_set_token_item_offset(right, item, push_space, &token);
3495db94535dSChris Mason 	}
3496eb60ceacSChris Mason 
34975f39d397SChris Mason 	btrfs_mark_buffer_dirty(left);
349834a38218SChris Mason 	if (right_nritems)
34995f39d397SChris Mason 		btrfs_mark_buffer_dirty(right);
3500f0486c68SYan, Zheng 	else
3501f0486c68SYan, Zheng 		clean_tree_block(trans, root, right);
3502098f59c2SChris Mason 
35035f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
3504143bede5SJeff Mahoney 	fixup_low_keys(trans, root, path, &disk_key, 1);
3505be0e5c09SChris Mason 
3506be0e5c09SChris Mason 	/* then fixup the leaf pointer in the path */
3507be0e5c09SChris Mason 	if (path->slots[0] < push_items) {
3508be0e5c09SChris Mason 		path->slots[0] += old_left_nritems;
3509925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
35105f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
35115f39d397SChris Mason 		path->nodes[0] = left;
3512be0e5c09SChris Mason 		path->slots[1] -= 1;
3513be0e5c09SChris Mason 	} else {
3514925baeddSChris Mason 		btrfs_tree_unlock(left);
35155f39d397SChris Mason 		free_extent_buffer(left);
3516be0e5c09SChris Mason 		path->slots[0] -= push_items;
3517be0e5c09SChris Mason 	}
3518eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
3519aa5d6bedSChris Mason 	return ret;
3520925baeddSChris Mason out:
3521925baeddSChris Mason 	btrfs_tree_unlock(left);
3522925baeddSChris Mason 	free_extent_buffer(left);
3523925baeddSChris Mason 	return ret;
3524be0e5c09SChris Mason }
3525be0e5c09SChris Mason 
352674123bd7SChris Mason /*
352744871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
352844871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
352999d8f83cSChris Mason  *
353099d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
353199d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us push all the
353299d8f83cSChris Mason  * items
353344871b1bSChris Mason  */
353444871b1bSChris Mason static int push_leaf_left(struct btrfs_trans_handle *trans, struct btrfs_root
353599d8f83cSChris Mason 			  *root, struct btrfs_path *path, int min_data_size,
353699d8f83cSChris Mason 			  int data_size, int empty, u32 max_slot)
353744871b1bSChris Mason {
353844871b1bSChris Mason 	struct extent_buffer *right = path->nodes[0];
353944871b1bSChris Mason 	struct extent_buffer *left;
354044871b1bSChris Mason 	int slot;
354144871b1bSChris Mason 	int free_space;
354244871b1bSChris Mason 	u32 right_nritems;
354344871b1bSChris Mason 	int ret = 0;
354444871b1bSChris Mason 
354544871b1bSChris Mason 	slot = path->slots[1];
354644871b1bSChris Mason 	if (slot == 0)
354744871b1bSChris Mason 		return 1;
354844871b1bSChris Mason 	if (!path->nodes[1])
354944871b1bSChris Mason 		return 1;
355044871b1bSChris Mason 
355144871b1bSChris Mason 	right_nritems = btrfs_header_nritems(right);
355244871b1bSChris Mason 	if (right_nritems == 0)
355344871b1bSChris Mason 		return 1;
355444871b1bSChris Mason 
355544871b1bSChris Mason 	btrfs_assert_tree_locked(path->nodes[1]);
355644871b1bSChris Mason 
355744871b1bSChris Mason 	left = read_node_slot(root, path->nodes[1], slot - 1);
355891ca338dSTsutomu Itoh 	if (left == NULL)
355991ca338dSTsutomu Itoh 		return 1;
356091ca338dSTsutomu Itoh 
356144871b1bSChris Mason 	btrfs_tree_lock(left);
356244871b1bSChris Mason 	btrfs_set_lock_blocking(left);
356344871b1bSChris Mason 
356444871b1bSChris Mason 	free_space = btrfs_leaf_free_space(root, left);
356544871b1bSChris Mason 	if (free_space < data_size) {
356644871b1bSChris Mason 		ret = 1;
356744871b1bSChris Mason 		goto out;
356844871b1bSChris Mason 	}
356944871b1bSChris Mason 
357044871b1bSChris Mason 	/* cow and double check */
357144871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, left,
357244871b1bSChris Mason 			      path->nodes[1], slot - 1, &left);
357344871b1bSChris Mason 	if (ret) {
357444871b1bSChris Mason 		/* we hit -ENOSPC, but it isn't fatal here */
357579787eaaSJeff Mahoney 		if (ret == -ENOSPC)
357644871b1bSChris Mason 			ret = 1;
357744871b1bSChris Mason 		goto out;
357844871b1bSChris Mason 	}
357944871b1bSChris Mason 
358044871b1bSChris Mason 	free_space = btrfs_leaf_free_space(root, left);
358144871b1bSChris Mason 	if (free_space < data_size) {
358244871b1bSChris Mason 		ret = 1;
358344871b1bSChris Mason 		goto out;
358444871b1bSChris Mason 	}
358544871b1bSChris Mason 
358699d8f83cSChris Mason 	return __push_leaf_left(trans, root, path, min_data_size,
358799d8f83cSChris Mason 			       empty, left, free_space, right_nritems,
358899d8f83cSChris Mason 			       max_slot);
358944871b1bSChris Mason out:
359044871b1bSChris Mason 	btrfs_tree_unlock(left);
359144871b1bSChris Mason 	free_extent_buffer(left);
359244871b1bSChris Mason 	return ret;
359344871b1bSChris Mason }
359444871b1bSChris Mason 
359544871b1bSChris Mason /*
359674123bd7SChris Mason  * split the path's leaf in two, making sure there is at least data_size
359774123bd7SChris Mason  * available for the resulting leaf level of the path.
359874123bd7SChris Mason  */
3599143bede5SJeff Mahoney static noinline void copy_for_split(struct btrfs_trans_handle *trans,
3600e02119d5SChris Mason 				    struct btrfs_root *root,
360144871b1bSChris Mason 				    struct btrfs_path *path,
360244871b1bSChris Mason 				    struct extent_buffer *l,
360344871b1bSChris Mason 				    struct extent_buffer *right,
360444871b1bSChris Mason 				    int slot, int mid, int nritems)
3605be0e5c09SChris Mason {
3606be0e5c09SChris Mason 	int data_copy_size;
3607be0e5c09SChris Mason 	int rt_data_off;
3608be0e5c09SChris Mason 	int i;
3609d4dbff95SChris Mason 	struct btrfs_disk_key disk_key;
3610cfed81a0SChris Mason 	struct btrfs_map_token token;
3611cfed81a0SChris Mason 
3612cfed81a0SChris Mason 	btrfs_init_map_token(&token);
3613be0e5c09SChris Mason 
36145f39d397SChris Mason 	nritems = nritems - mid;
36155f39d397SChris Mason 	btrfs_set_header_nritems(right, nritems);
36165f39d397SChris Mason 	data_copy_size = btrfs_item_end_nr(l, mid) - leaf_data_end(root, l);
36175f39d397SChris Mason 
36185f39d397SChris Mason 	copy_extent_buffer(right, l, btrfs_item_nr_offset(0),
36195f39d397SChris Mason 			   btrfs_item_nr_offset(mid),
36205f39d397SChris Mason 			   nritems * sizeof(struct btrfs_item));
36215f39d397SChris Mason 
36225f39d397SChris Mason 	copy_extent_buffer(right, l,
3623d6025579SChris Mason 		     btrfs_leaf_data(right) + BTRFS_LEAF_DATA_SIZE(root) -
3624123abc88SChris Mason 		     data_copy_size, btrfs_leaf_data(l) +
3625123abc88SChris Mason 		     leaf_data_end(root, l), data_copy_size);
362674123bd7SChris Mason 
36275f39d397SChris Mason 	rt_data_off = BTRFS_LEAF_DATA_SIZE(root) -
36285f39d397SChris Mason 		      btrfs_item_end_nr(l, mid);
36295f39d397SChris Mason 
36305f39d397SChris Mason 	for (i = 0; i < nritems; i++) {
36315f39d397SChris Mason 		struct btrfs_item *item = btrfs_item_nr(right, i);
3632db94535dSChris Mason 		u32 ioff;
3633db94535dSChris Mason 
3634cfed81a0SChris Mason 		ioff = btrfs_token_item_offset(right, item, &token);
3635cfed81a0SChris Mason 		btrfs_set_token_item_offset(right, item,
3636cfed81a0SChris Mason 					    ioff + rt_data_off, &token);
36370783fcfcSChris Mason 	}
363874123bd7SChris Mason 
36395f39d397SChris Mason 	btrfs_set_header_nritems(l, mid);
36405f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
3641143bede5SJeff Mahoney 	insert_ptr(trans, root, path, &disk_key, right->start,
3642c3e06965SJan Schmidt 		   path->slots[1] + 1, 1);
36435f39d397SChris Mason 
36445f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
36455f39d397SChris Mason 	btrfs_mark_buffer_dirty(l);
3646eb60ceacSChris Mason 	BUG_ON(path->slots[0] != slot);
36475f39d397SChris Mason 
3648be0e5c09SChris Mason 	if (mid <= slot) {
3649925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
36505f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
36515f39d397SChris Mason 		path->nodes[0] = right;
3652be0e5c09SChris Mason 		path->slots[0] -= mid;
3653be0e5c09SChris Mason 		path->slots[1] += 1;
3654925baeddSChris Mason 	} else {
3655925baeddSChris Mason 		btrfs_tree_unlock(right);
36565f39d397SChris Mason 		free_extent_buffer(right);
3657925baeddSChris Mason 	}
36585f39d397SChris Mason 
3659eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
366044871b1bSChris Mason }
366144871b1bSChris Mason 
366244871b1bSChris Mason /*
366399d8f83cSChris Mason  * double splits happen when we need to insert a big item in the middle
366499d8f83cSChris Mason  * of a leaf.  A double split can leave us with 3 mostly empty leaves:
366599d8f83cSChris Mason  * leaf: [ slots 0 - N] [ our target ] [ N + 1 - total in leaf ]
366699d8f83cSChris Mason  *          A                 B                 C
366799d8f83cSChris Mason  *
366899d8f83cSChris Mason  * We avoid this by trying to push the items on either side of our target
366999d8f83cSChris Mason  * into the adjacent leaves.  If all goes well we can avoid the double split
367099d8f83cSChris Mason  * completely.
367199d8f83cSChris Mason  */
367299d8f83cSChris Mason static noinline int push_for_double_split(struct btrfs_trans_handle *trans,
367399d8f83cSChris Mason 					  struct btrfs_root *root,
367499d8f83cSChris Mason 					  struct btrfs_path *path,
367599d8f83cSChris Mason 					  int data_size)
367699d8f83cSChris Mason {
367799d8f83cSChris Mason 	int ret;
367899d8f83cSChris Mason 	int progress = 0;
367999d8f83cSChris Mason 	int slot;
368099d8f83cSChris Mason 	u32 nritems;
368199d8f83cSChris Mason 
368299d8f83cSChris Mason 	slot = path->slots[0];
368399d8f83cSChris Mason 
368499d8f83cSChris Mason 	/*
368599d8f83cSChris Mason 	 * try to push all the items after our slot into the
368699d8f83cSChris Mason 	 * right leaf
368799d8f83cSChris Mason 	 */
368899d8f83cSChris Mason 	ret = push_leaf_right(trans, root, path, 1, data_size, 0, slot);
368999d8f83cSChris Mason 	if (ret < 0)
369099d8f83cSChris Mason 		return ret;
369199d8f83cSChris Mason 
369299d8f83cSChris Mason 	if (ret == 0)
369399d8f83cSChris Mason 		progress++;
369499d8f83cSChris Mason 
369599d8f83cSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
369699d8f83cSChris Mason 	/*
369799d8f83cSChris Mason 	 * our goal is to get our slot at the start or end of a leaf.  If
369899d8f83cSChris Mason 	 * we've done so we're done
369999d8f83cSChris Mason 	 */
370099d8f83cSChris Mason 	if (path->slots[0] == 0 || path->slots[0] == nritems)
370199d8f83cSChris Mason 		return 0;
370299d8f83cSChris Mason 
370399d8f83cSChris Mason 	if (btrfs_leaf_free_space(root, path->nodes[0]) >= data_size)
370499d8f83cSChris Mason 		return 0;
370599d8f83cSChris Mason 
370699d8f83cSChris Mason 	/* try to push all the items before our slot into the next leaf */
370799d8f83cSChris Mason 	slot = path->slots[0];
370899d8f83cSChris Mason 	ret = push_leaf_left(trans, root, path, 1, data_size, 0, slot);
370999d8f83cSChris Mason 	if (ret < 0)
371099d8f83cSChris Mason 		return ret;
371199d8f83cSChris Mason 
371299d8f83cSChris Mason 	if (ret == 0)
371399d8f83cSChris Mason 		progress++;
371499d8f83cSChris Mason 
371599d8f83cSChris Mason 	if (progress)
371699d8f83cSChris Mason 		return 0;
371799d8f83cSChris Mason 	return 1;
371899d8f83cSChris Mason }
371999d8f83cSChris Mason 
372099d8f83cSChris Mason /*
372144871b1bSChris Mason  * split the path's leaf in two, making sure there is at least data_size
372244871b1bSChris Mason  * available for the resulting leaf level of the path.
372344871b1bSChris Mason  *
372444871b1bSChris Mason  * returns 0 if all went well and < 0 on failure.
372544871b1bSChris Mason  */
372644871b1bSChris Mason static noinline int split_leaf(struct btrfs_trans_handle *trans,
372744871b1bSChris Mason 			       struct btrfs_root *root,
372844871b1bSChris Mason 			       struct btrfs_key *ins_key,
372944871b1bSChris Mason 			       struct btrfs_path *path, int data_size,
373044871b1bSChris Mason 			       int extend)
373144871b1bSChris Mason {
37325d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
373344871b1bSChris Mason 	struct extent_buffer *l;
373444871b1bSChris Mason 	u32 nritems;
373544871b1bSChris Mason 	int mid;
373644871b1bSChris Mason 	int slot;
373744871b1bSChris Mason 	struct extent_buffer *right;
373844871b1bSChris Mason 	int ret = 0;
373944871b1bSChris Mason 	int wret;
37405d4f98a2SYan Zheng 	int split;
374144871b1bSChris Mason 	int num_doubles = 0;
374299d8f83cSChris Mason 	int tried_avoid_double = 0;
374344871b1bSChris Mason 
3744a5719521SYan, Zheng 	l = path->nodes[0];
3745a5719521SYan, Zheng 	slot = path->slots[0];
3746a5719521SYan, Zheng 	if (extend && data_size + btrfs_item_size_nr(l, slot) +
3747a5719521SYan, Zheng 	    sizeof(struct btrfs_item) > BTRFS_LEAF_DATA_SIZE(root))
3748a5719521SYan, Zheng 		return -EOVERFLOW;
3749a5719521SYan, Zheng 
375044871b1bSChris Mason 	/* first try to make some room by pushing left and right */
375199d8f83cSChris Mason 	if (data_size) {
375299d8f83cSChris Mason 		wret = push_leaf_right(trans, root, path, data_size,
375399d8f83cSChris Mason 				       data_size, 0, 0);
375444871b1bSChris Mason 		if (wret < 0)
375544871b1bSChris Mason 			return wret;
375644871b1bSChris Mason 		if (wret) {
375799d8f83cSChris Mason 			wret = push_leaf_left(trans, root, path, data_size,
375899d8f83cSChris Mason 					      data_size, 0, (u32)-1);
375944871b1bSChris Mason 			if (wret < 0)
376044871b1bSChris Mason 				return wret;
376144871b1bSChris Mason 		}
376244871b1bSChris Mason 		l = path->nodes[0];
376344871b1bSChris Mason 
376444871b1bSChris Mason 		/* did the pushes work? */
376544871b1bSChris Mason 		if (btrfs_leaf_free_space(root, l) >= data_size)
376644871b1bSChris Mason 			return 0;
376744871b1bSChris Mason 	}
376844871b1bSChris Mason 
376944871b1bSChris Mason 	if (!path->nodes[1]) {
377044871b1bSChris Mason 		ret = insert_new_root(trans, root, path, 1);
377144871b1bSChris Mason 		if (ret)
377244871b1bSChris Mason 			return ret;
377344871b1bSChris Mason 	}
377444871b1bSChris Mason again:
37755d4f98a2SYan Zheng 	split = 1;
377644871b1bSChris Mason 	l = path->nodes[0];
377744871b1bSChris Mason 	slot = path->slots[0];
377844871b1bSChris Mason 	nritems = btrfs_header_nritems(l);
377944871b1bSChris Mason 	mid = (nritems + 1) / 2;
378044871b1bSChris Mason 
37815d4f98a2SYan Zheng 	if (mid <= slot) {
37825d4f98a2SYan Zheng 		if (nritems == 1 ||
37835d4f98a2SYan Zheng 		    leaf_space_used(l, mid, nritems - mid) + data_size >
37845d4f98a2SYan Zheng 			BTRFS_LEAF_DATA_SIZE(root)) {
37855d4f98a2SYan Zheng 			if (slot >= nritems) {
37865d4f98a2SYan Zheng 				split = 0;
37875d4f98a2SYan Zheng 			} else {
37885d4f98a2SYan Zheng 				mid = slot;
37895d4f98a2SYan Zheng 				if (mid != nritems &&
37905d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
37915d4f98a2SYan Zheng 				    data_size > BTRFS_LEAF_DATA_SIZE(root)) {
379299d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
379399d8f83cSChris Mason 						goto push_for_double;
37945d4f98a2SYan Zheng 					split = 2;
37955d4f98a2SYan Zheng 				}
37965d4f98a2SYan Zheng 			}
37975d4f98a2SYan Zheng 		}
37985d4f98a2SYan Zheng 	} else {
37995d4f98a2SYan Zheng 		if (leaf_space_used(l, 0, mid) + data_size >
38005d4f98a2SYan Zheng 			BTRFS_LEAF_DATA_SIZE(root)) {
38015d4f98a2SYan Zheng 			if (!extend && data_size && slot == 0) {
38025d4f98a2SYan Zheng 				split = 0;
38035d4f98a2SYan Zheng 			} else if ((extend || !data_size) && slot == 0) {
38045d4f98a2SYan Zheng 				mid = 1;
38055d4f98a2SYan Zheng 			} else {
38065d4f98a2SYan Zheng 				mid = slot;
38075d4f98a2SYan Zheng 				if (mid != nritems &&
38085d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
38095d4f98a2SYan Zheng 				    data_size > BTRFS_LEAF_DATA_SIZE(root)) {
381099d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
381199d8f83cSChris Mason 						goto push_for_double;
38125d4f98a2SYan Zheng 					split = 2 ;
38135d4f98a2SYan Zheng 				}
38145d4f98a2SYan Zheng 			}
38155d4f98a2SYan Zheng 		}
38165d4f98a2SYan Zheng 	}
38175d4f98a2SYan Zheng 
38185d4f98a2SYan Zheng 	if (split == 0)
38195d4f98a2SYan Zheng 		btrfs_cpu_key_to_disk(&disk_key, ins_key);
38205d4f98a2SYan Zheng 	else
38215d4f98a2SYan Zheng 		btrfs_item_key(l, &disk_key, mid);
38225d4f98a2SYan Zheng 
38235d4f98a2SYan Zheng 	right = btrfs_alloc_free_block(trans, root, root->leafsize, 0,
382444871b1bSChris Mason 					root->root_key.objectid,
38255581a51aSJan Schmidt 					&disk_key, 0, l->start, 0);
3826f0486c68SYan, Zheng 	if (IS_ERR(right))
382744871b1bSChris Mason 		return PTR_ERR(right);
3828f0486c68SYan, Zheng 
3829f0486c68SYan, Zheng 	root_add_used(root, root->leafsize);
383044871b1bSChris Mason 
383144871b1bSChris Mason 	memset_extent_buffer(right, 0, 0, sizeof(struct btrfs_header));
383244871b1bSChris Mason 	btrfs_set_header_bytenr(right, right->start);
383344871b1bSChris Mason 	btrfs_set_header_generation(right, trans->transid);
38345d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(right, BTRFS_MIXED_BACKREF_REV);
383544871b1bSChris Mason 	btrfs_set_header_owner(right, root->root_key.objectid);
383644871b1bSChris Mason 	btrfs_set_header_level(right, 0);
383744871b1bSChris Mason 	write_extent_buffer(right, root->fs_info->fsid,
383844871b1bSChris Mason 			    (unsigned long)btrfs_header_fsid(right),
383944871b1bSChris Mason 			    BTRFS_FSID_SIZE);
384044871b1bSChris Mason 
384144871b1bSChris Mason 	write_extent_buffer(right, root->fs_info->chunk_tree_uuid,
384244871b1bSChris Mason 			    (unsigned long)btrfs_header_chunk_tree_uuid(right),
384344871b1bSChris Mason 			    BTRFS_UUID_SIZE);
384444871b1bSChris Mason 
38455d4f98a2SYan Zheng 	if (split == 0) {
384644871b1bSChris Mason 		if (mid <= slot) {
384744871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
3848143bede5SJeff Mahoney 			insert_ptr(trans, root, path, &disk_key, right->start,
3849c3e06965SJan Schmidt 				   path->slots[1] + 1, 1);
385044871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
385144871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
385244871b1bSChris Mason 			path->nodes[0] = right;
385344871b1bSChris Mason 			path->slots[0] = 0;
385444871b1bSChris Mason 			path->slots[1] += 1;
385544871b1bSChris Mason 		} else {
385644871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
3857143bede5SJeff Mahoney 			insert_ptr(trans, root, path, &disk_key, right->start,
3858c3e06965SJan Schmidt 					  path->slots[1], 1);
385944871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
386044871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
386144871b1bSChris Mason 			path->nodes[0] = right;
386244871b1bSChris Mason 			path->slots[0] = 0;
3863143bede5SJeff Mahoney 			if (path->slots[1] == 0)
3864143bede5SJeff Mahoney 				fixup_low_keys(trans, root, path,
3865143bede5SJeff Mahoney 					       &disk_key, 1);
38665d4f98a2SYan Zheng 		}
386744871b1bSChris Mason 		btrfs_mark_buffer_dirty(right);
386844871b1bSChris Mason 		return ret;
386944871b1bSChris Mason 	}
387044871b1bSChris Mason 
3871143bede5SJeff Mahoney 	copy_for_split(trans, root, path, l, right, slot, mid, nritems);
387244871b1bSChris Mason 
38735d4f98a2SYan Zheng 	if (split == 2) {
3874cc0c5538SChris Mason 		BUG_ON(num_doubles != 0);
3875cc0c5538SChris Mason 		num_doubles++;
3876cc0c5538SChris Mason 		goto again;
38773326d1b0SChris Mason 	}
387844871b1bSChris Mason 
3879143bede5SJeff Mahoney 	return 0;
388099d8f83cSChris Mason 
388199d8f83cSChris Mason push_for_double:
388299d8f83cSChris Mason 	push_for_double_split(trans, root, path, data_size);
388399d8f83cSChris Mason 	tried_avoid_double = 1;
388499d8f83cSChris Mason 	if (btrfs_leaf_free_space(root, path->nodes[0]) >= data_size)
388599d8f83cSChris Mason 		return 0;
388699d8f83cSChris Mason 	goto again;
3887be0e5c09SChris Mason }
3888be0e5c09SChris Mason 
3889ad48fd75SYan, Zheng static noinline int setup_leaf_for_split(struct btrfs_trans_handle *trans,
3890ad48fd75SYan, Zheng 					 struct btrfs_root *root,
3891ad48fd75SYan, Zheng 					 struct btrfs_path *path, int ins_len)
3892ad48fd75SYan, Zheng {
3893ad48fd75SYan, Zheng 	struct btrfs_key key;
3894ad48fd75SYan, Zheng 	struct extent_buffer *leaf;
3895ad48fd75SYan, Zheng 	struct btrfs_file_extent_item *fi;
3896ad48fd75SYan, Zheng 	u64 extent_len = 0;
3897ad48fd75SYan, Zheng 	u32 item_size;
3898ad48fd75SYan, Zheng 	int ret;
3899ad48fd75SYan, Zheng 
3900ad48fd75SYan, Zheng 	leaf = path->nodes[0];
3901ad48fd75SYan, Zheng 	btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3902ad48fd75SYan, Zheng 
3903ad48fd75SYan, Zheng 	BUG_ON(key.type != BTRFS_EXTENT_DATA_KEY &&
3904ad48fd75SYan, Zheng 	       key.type != BTRFS_EXTENT_CSUM_KEY);
3905ad48fd75SYan, Zheng 
3906ad48fd75SYan, Zheng 	if (btrfs_leaf_free_space(root, leaf) >= ins_len)
3907ad48fd75SYan, Zheng 		return 0;
3908ad48fd75SYan, Zheng 
3909ad48fd75SYan, Zheng 	item_size = btrfs_item_size_nr(leaf, path->slots[0]);
3910ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
3911ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
3912ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
3913ad48fd75SYan, Zheng 		extent_len = btrfs_file_extent_num_bytes(leaf, fi);
3914ad48fd75SYan, Zheng 	}
3915b3b4aa74SDavid Sterba 	btrfs_release_path(path);
3916ad48fd75SYan, Zheng 
3917ad48fd75SYan, Zheng 	path->keep_locks = 1;
3918ad48fd75SYan, Zheng 	path->search_for_split = 1;
3919ad48fd75SYan, Zheng 	ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
3920ad48fd75SYan, Zheng 	path->search_for_split = 0;
3921ad48fd75SYan, Zheng 	if (ret < 0)
3922ad48fd75SYan, Zheng 		goto err;
3923ad48fd75SYan, Zheng 
3924ad48fd75SYan, Zheng 	ret = -EAGAIN;
3925ad48fd75SYan, Zheng 	leaf = path->nodes[0];
3926ad48fd75SYan, Zheng 	/* if our item isn't there or got smaller, return now */
3927ad48fd75SYan, Zheng 	if (ret > 0 || item_size != btrfs_item_size_nr(leaf, path->slots[0]))
3928ad48fd75SYan, Zheng 		goto err;
3929ad48fd75SYan, Zheng 
3930109f6aefSChris Mason 	/* the leaf has  changed, it now has room.  return now */
3931109f6aefSChris Mason 	if (btrfs_leaf_free_space(root, path->nodes[0]) >= ins_len)
3932109f6aefSChris Mason 		goto err;
3933109f6aefSChris Mason 
3934ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
3935ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
3936ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
3937ad48fd75SYan, Zheng 		if (extent_len != btrfs_file_extent_num_bytes(leaf, fi))
3938ad48fd75SYan, Zheng 			goto err;
3939ad48fd75SYan, Zheng 	}
3940ad48fd75SYan, Zheng 
3941ad48fd75SYan, Zheng 	btrfs_set_path_blocking(path);
3942ad48fd75SYan, Zheng 	ret = split_leaf(trans, root, &key, path, ins_len, 1);
3943f0486c68SYan, Zheng 	if (ret)
3944f0486c68SYan, Zheng 		goto err;
3945ad48fd75SYan, Zheng 
3946ad48fd75SYan, Zheng 	path->keep_locks = 0;
3947ad48fd75SYan, Zheng 	btrfs_unlock_up_safe(path, 1);
3948ad48fd75SYan, Zheng 	return 0;
3949ad48fd75SYan, Zheng err:
3950ad48fd75SYan, Zheng 	path->keep_locks = 0;
3951ad48fd75SYan, Zheng 	return ret;
3952ad48fd75SYan, Zheng }
3953ad48fd75SYan, Zheng 
3954ad48fd75SYan, Zheng static noinline int split_item(struct btrfs_trans_handle *trans,
3955459931ecSChris Mason 			       struct btrfs_root *root,
3956459931ecSChris Mason 			       struct btrfs_path *path,
3957459931ecSChris Mason 			       struct btrfs_key *new_key,
3958459931ecSChris Mason 			       unsigned long split_offset)
3959459931ecSChris Mason {
3960459931ecSChris Mason 	struct extent_buffer *leaf;
3961459931ecSChris Mason 	struct btrfs_item *item;
3962459931ecSChris Mason 	struct btrfs_item *new_item;
3963459931ecSChris Mason 	int slot;
3964ad48fd75SYan, Zheng 	char *buf;
3965459931ecSChris Mason 	u32 nritems;
3966ad48fd75SYan, Zheng 	u32 item_size;
3967459931ecSChris Mason 	u32 orig_offset;
3968459931ecSChris Mason 	struct btrfs_disk_key disk_key;
3969459931ecSChris Mason 
3970459931ecSChris Mason 	leaf = path->nodes[0];
3971b9473439SChris Mason 	BUG_ON(btrfs_leaf_free_space(root, leaf) < sizeof(struct btrfs_item));
3972b9473439SChris Mason 
3973b4ce94deSChris Mason 	btrfs_set_path_blocking(path);
3974b4ce94deSChris Mason 
3975459931ecSChris Mason 	item = btrfs_item_nr(leaf, path->slots[0]);
3976459931ecSChris Mason 	orig_offset = btrfs_item_offset(leaf, item);
3977459931ecSChris Mason 	item_size = btrfs_item_size(leaf, item);
3978459931ecSChris Mason 
3979459931ecSChris Mason 	buf = kmalloc(item_size, GFP_NOFS);
3980ad48fd75SYan, Zheng 	if (!buf)
3981ad48fd75SYan, Zheng 		return -ENOMEM;
3982ad48fd75SYan, Zheng 
3983459931ecSChris Mason 	read_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf,
3984459931ecSChris Mason 			    path->slots[0]), item_size);
3985ad48fd75SYan, Zheng 
3986459931ecSChris Mason 	slot = path->slots[0] + 1;
3987459931ecSChris Mason 	nritems = btrfs_header_nritems(leaf);
3988459931ecSChris Mason 	if (slot != nritems) {
3989459931ecSChris Mason 		/* shift the items */
3990459931ecSChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + 1),
3991459931ecSChris Mason 				btrfs_item_nr_offset(slot),
3992459931ecSChris Mason 				(nritems - slot) * sizeof(struct btrfs_item));
3993459931ecSChris Mason 	}
3994459931ecSChris Mason 
3995459931ecSChris Mason 	btrfs_cpu_key_to_disk(&disk_key, new_key);
3996459931ecSChris Mason 	btrfs_set_item_key(leaf, &disk_key, slot);
3997459931ecSChris Mason 
3998459931ecSChris Mason 	new_item = btrfs_item_nr(leaf, slot);
3999459931ecSChris Mason 
4000459931ecSChris Mason 	btrfs_set_item_offset(leaf, new_item, orig_offset);
4001459931ecSChris Mason 	btrfs_set_item_size(leaf, new_item, item_size - split_offset);
4002459931ecSChris Mason 
4003459931ecSChris Mason 	btrfs_set_item_offset(leaf, item,
4004459931ecSChris Mason 			      orig_offset + item_size - split_offset);
4005459931ecSChris Mason 	btrfs_set_item_size(leaf, item, split_offset);
4006459931ecSChris Mason 
4007459931ecSChris Mason 	btrfs_set_header_nritems(leaf, nritems + 1);
4008459931ecSChris Mason 
4009459931ecSChris Mason 	/* write the data for the start of the original item */
4010459931ecSChris Mason 	write_extent_buffer(leaf, buf,
4011459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, path->slots[0]),
4012459931ecSChris Mason 			    split_offset);
4013459931ecSChris Mason 
4014459931ecSChris Mason 	/* write the data for the new item */
4015459931ecSChris Mason 	write_extent_buffer(leaf, buf + split_offset,
4016459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, slot),
4017459931ecSChris Mason 			    item_size - split_offset);
4018459931ecSChris Mason 	btrfs_mark_buffer_dirty(leaf);
4019459931ecSChris Mason 
4020ad48fd75SYan, Zheng 	BUG_ON(btrfs_leaf_free_space(root, leaf) < 0);
4021459931ecSChris Mason 	kfree(buf);
4022ad48fd75SYan, Zheng 	return 0;
4023ad48fd75SYan, Zheng }
4024ad48fd75SYan, Zheng 
4025ad48fd75SYan, Zheng /*
4026ad48fd75SYan, Zheng  * This function splits a single item into two items,
4027ad48fd75SYan, Zheng  * giving 'new_key' to the new item and splitting the
4028ad48fd75SYan, Zheng  * old one at split_offset (from the start of the item).
4029ad48fd75SYan, Zheng  *
4030ad48fd75SYan, Zheng  * The path may be released by this operation.  After
4031ad48fd75SYan, Zheng  * the split, the path is pointing to the old item.  The
4032ad48fd75SYan, Zheng  * new item is going to be in the same node as the old one.
4033ad48fd75SYan, Zheng  *
4034ad48fd75SYan, Zheng  * Note, the item being split must be smaller enough to live alone on
4035ad48fd75SYan, Zheng  * a tree block with room for one extra struct btrfs_item
4036ad48fd75SYan, Zheng  *
4037ad48fd75SYan, Zheng  * This allows us to split the item in place, keeping a lock on the
4038ad48fd75SYan, Zheng  * leaf the entire time.
4039ad48fd75SYan, Zheng  */
4040ad48fd75SYan, Zheng int btrfs_split_item(struct btrfs_trans_handle *trans,
4041ad48fd75SYan, Zheng 		     struct btrfs_root *root,
4042ad48fd75SYan, Zheng 		     struct btrfs_path *path,
4043ad48fd75SYan, Zheng 		     struct btrfs_key *new_key,
4044ad48fd75SYan, Zheng 		     unsigned long split_offset)
4045ad48fd75SYan, Zheng {
4046ad48fd75SYan, Zheng 	int ret;
4047ad48fd75SYan, Zheng 	ret = setup_leaf_for_split(trans, root, path,
4048ad48fd75SYan, Zheng 				   sizeof(struct btrfs_item));
4049ad48fd75SYan, Zheng 	if (ret)
4050459931ecSChris Mason 		return ret;
4051ad48fd75SYan, Zheng 
4052ad48fd75SYan, Zheng 	ret = split_item(trans, root, path, new_key, split_offset);
4053ad48fd75SYan, Zheng 	return ret;
4054ad48fd75SYan, Zheng }
4055ad48fd75SYan, Zheng 
4056ad48fd75SYan, Zheng /*
4057ad48fd75SYan, Zheng  * This function duplicate a item, giving 'new_key' to the new item.
4058ad48fd75SYan, Zheng  * It guarantees both items live in the same tree leaf and the new item
4059ad48fd75SYan, Zheng  * is contiguous with the original item.
4060ad48fd75SYan, Zheng  *
4061ad48fd75SYan, Zheng  * This allows us to split file extent in place, keeping a lock on the
4062ad48fd75SYan, Zheng  * leaf the entire time.
4063ad48fd75SYan, Zheng  */
4064ad48fd75SYan, Zheng int btrfs_duplicate_item(struct btrfs_trans_handle *trans,
4065ad48fd75SYan, Zheng 			 struct btrfs_root *root,
4066ad48fd75SYan, Zheng 			 struct btrfs_path *path,
4067ad48fd75SYan, Zheng 			 struct btrfs_key *new_key)
4068ad48fd75SYan, Zheng {
4069ad48fd75SYan, Zheng 	struct extent_buffer *leaf;
4070ad48fd75SYan, Zheng 	int ret;
4071ad48fd75SYan, Zheng 	u32 item_size;
4072ad48fd75SYan, Zheng 
4073ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4074ad48fd75SYan, Zheng 	item_size = btrfs_item_size_nr(leaf, path->slots[0]);
4075ad48fd75SYan, Zheng 	ret = setup_leaf_for_split(trans, root, path,
4076ad48fd75SYan, Zheng 				   item_size + sizeof(struct btrfs_item));
4077ad48fd75SYan, Zheng 	if (ret)
4078ad48fd75SYan, Zheng 		return ret;
4079ad48fd75SYan, Zheng 
4080ad48fd75SYan, Zheng 	path->slots[0]++;
4081143bede5SJeff Mahoney 	setup_items_for_insert(trans, root, path, new_key, &item_size,
4082ad48fd75SYan, Zheng 			       item_size, item_size +
4083ad48fd75SYan, Zheng 			       sizeof(struct btrfs_item), 1);
4084ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4085ad48fd75SYan, Zheng 	memcpy_extent_buffer(leaf,
4086ad48fd75SYan, Zheng 			     btrfs_item_ptr_offset(leaf, path->slots[0]),
4087ad48fd75SYan, Zheng 			     btrfs_item_ptr_offset(leaf, path->slots[0] - 1),
4088ad48fd75SYan, Zheng 			     item_size);
4089ad48fd75SYan, Zheng 	return 0;
4090459931ecSChris Mason }
4091459931ecSChris Mason 
4092459931ecSChris Mason /*
4093d352ac68SChris Mason  * make the item pointed to by the path smaller.  new_size indicates
4094d352ac68SChris Mason  * how small to make it, and from_end tells us if we just chop bytes
4095d352ac68SChris Mason  * off the end of the item or if we shift the item to chop bytes off
4096d352ac68SChris Mason  * the front.
4097d352ac68SChris Mason  */
4098143bede5SJeff Mahoney void btrfs_truncate_item(struct btrfs_trans_handle *trans,
4099b18c6685SChris Mason 			 struct btrfs_root *root,
4100b18c6685SChris Mason 			 struct btrfs_path *path,
4101179e29e4SChris Mason 			 u32 new_size, int from_end)
4102b18c6685SChris Mason {
4103b18c6685SChris Mason 	int slot;
41045f39d397SChris Mason 	struct extent_buffer *leaf;
41055f39d397SChris Mason 	struct btrfs_item *item;
4106b18c6685SChris Mason 	u32 nritems;
4107b18c6685SChris Mason 	unsigned int data_end;
4108b18c6685SChris Mason 	unsigned int old_data_start;
4109b18c6685SChris Mason 	unsigned int old_size;
4110b18c6685SChris Mason 	unsigned int size_diff;
4111b18c6685SChris Mason 	int i;
4112cfed81a0SChris Mason 	struct btrfs_map_token token;
4113cfed81a0SChris Mason 
4114cfed81a0SChris Mason 	btrfs_init_map_token(&token);
4115b18c6685SChris Mason 
41165f39d397SChris Mason 	leaf = path->nodes[0];
4117179e29e4SChris Mason 	slot = path->slots[0];
4118179e29e4SChris Mason 
4119179e29e4SChris Mason 	old_size = btrfs_item_size_nr(leaf, slot);
4120179e29e4SChris Mason 	if (old_size == new_size)
4121143bede5SJeff Mahoney 		return;
4122b18c6685SChris Mason 
41235f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
4124b18c6685SChris Mason 	data_end = leaf_data_end(root, leaf);
4125b18c6685SChris Mason 
41265f39d397SChris Mason 	old_data_start = btrfs_item_offset_nr(leaf, slot);
4127179e29e4SChris Mason 
4128b18c6685SChris Mason 	size_diff = old_size - new_size;
4129b18c6685SChris Mason 
4130b18c6685SChris Mason 	BUG_ON(slot < 0);
4131b18c6685SChris Mason 	BUG_ON(slot >= nritems);
4132b18c6685SChris Mason 
4133b18c6685SChris Mason 	/*
4134b18c6685SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4135b18c6685SChris Mason 	 */
4136b18c6685SChris Mason 	/* first correct the data pointers */
4137b18c6685SChris Mason 	for (i = slot; i < nritems; i++) {
41385f39d397SChris Mason 		u32 ioff;
41395f39d397SChris Mason 		item = btrfs_item_nr(leaf, i);
4140db94535dSChris Mason 
4141cfed81a0SChris Mason 		ioff = btrfs_token_item_offset(leaf, item, &token);
4142cfed81a0SChris Mason 		btrfs_set_token_item_offset(leaf, item,
4143cfed81a0SChris Mason 					    ioff + size_diff, &token);
4144b18c6685SChris Mason 	}
4145db94535dSChris Mason 
4146b18c6685SChris Mason 	/* shift the data */
4147179e29e4SChris Mason 	if (from_end) {
41485f39d397SChris Mason 		memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
4149b18c6685SChris Mason 			      data_end + size_diff, btrfs_leaf_data(leaf) +
4150b18c6685SChris Mason 			      data_end, old_data_start + new_size - data_end);
4151179e29e4SChris Mason 	} else {
4152179e29e4SChris Mason 		struct btrfs_disk_key disk_key;
4153179e29e4SChris Mason 		u64 offset;
4154179e29e4SChris Mason 
4155179e29e4SChris Mason 		btrfs_item_key(leaf, &disk_key, slot);
4156179e29e4SChris Mason 
4157179e29e4SChris Mason 		if (btrfs_disk_key_type(&disk_key) == BTRFS_EXTENT_DATA_KEY) {
4158179e29e4SChris Mason 			unsigned long ptr;
4159179e29e4SChris Mason 			struct btrfs_file_extent_item *fi;
4160179e29e4SChris Mason 
4161179e29e4SChris Mason 			fi = btrfs_item_ptr(leaf, slot,
4162179e29e4SChris Mason 					    struct btrfs_file_extent_item);
4163179e29e4SChris Mason 			fi = (struct btrfs_file_extent_item *)(
4164179e29e4SChris Mason 			     (unsigned long)fi - size_diff);
4165179e29e4SChris Mason 
4166179e29e4SChris Mason 			if (btrfs_file_extent_type(leaf, fi) ==
4167179e29e4SChris Mason 			    BTRFS_FILE_EXTENT_INLINE) {
4168179e29e4SChris Mason 				ptr = btrfs_item_ptr_offset(leaf, slot);
4169179e29e4SChris Mason 				memmove_extent_buffer(leaf, ptr,
4170179e29e4SChris Mason 				      (unsigned long)fi,
4171179e29e4SChris Mason 				      offsetof(struct btrfs_file_extent_item,
4172179e29e4SChris Mason 						 disk_bytenr));
4173179e29e4SChris Mason 			}
4174179e29e4SChris Mason 		}
4175179e29e4SChris Mason 
4176179e29e4SChris Mason 		memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
4177179e29e4SChris Mason 			      data_end + size_diff, btrfs_leaf_data(leaf) +
4178179e29e4SChris Mason 			      data_end, old_data_start - data_end);
4179179e29e4SChris Mason 
4180179e29e4SChris Mason 		offset = btrfs_disk_key_offset(&disk_key);
4181179e29e4SChris Mason 		btrfs_set_disk_key_offset(&disk_key, offset + size_diff);
4182179e29e4SChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot);
4183179e29e4SChris Mason 		if (slot == 0)
4184179e29e4SChris Mason 			fixup_low_keys(trans, root, path, &disk_key, 1);
4185179e29e4SChris Mason 	}
41865f39d397SChris Mason 
41875f39d397SChris Mason 	item = btrfs_item_nr(leaf, slot);
41885f39d397SChris Mason 	btrfs_set_item_size(leaf, item, new_size);
41895f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
4190b18c6685SChris Mason 
41915f39d397SChris Mason 	if (btrfs_leaf_free_space(root, leaf) < 0) {
41925f39d397SChris Mason 		btrfs_print_leaf(root, leaf);
4193b18c6685SChris Mason 		BUG();
41945f39d397SChris Mason 	}
4195b18c6685SChris Mason }
4196b18c6685SChris Mason 
4197d352ac68SChris Mason /*
4198d352ac68SChris Mason  * make the item pointed to by the path bigger, data_size is the new size.
4199d352ac68SChris Mason  */
4200143bede5SJeff Mahoney void btrfs_extend_item(struct btrfs_trans_handle *trans,
42015f39d397SChris Mason 		       struct btrfs_root *root, struct btrfs_path *path,
42025f39d397SChris Mason 		       u32 data_size)
42036567e837SChris Mason {
42046567e837SChris Mason 	int slot;
42055f39d397SChris Mason 	struct extent_buffer *leaf;
42065f39d397SChris Mason 	struct btrfs_item *item;
42076567e837SChris Mason 	u32 nritems;
42086567e837SChris Mason 	unsigned int data_end;
42096567e837SChris Mason 	unsigned int old_data;
42106567e837SChris Mason 	unsigned int old_size;
42116567e837SChris Mason 	int i;
4212cfed81a0SChris Mason 	struct btrfs_map_token token;
4213cfed81a0SChris Mason 
4214cfed81a0SChris Mason 	btrfs_init_map_token(&token);
42156567e837SChris Mason 
42165f39d397SChris Mason 	leaf = path->nodes[0];
42176567e837SChris Mason 
42185f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
42196567e837SChris Mason 	data_end = leaf_data_end(root, leaf);
42206567e837SChris Mason 
42215f39d397SChris Mason 	if (btrfs_leaf_free_space(root, leaf) < data_size) {
42225f39d397SChris Mason 		btrfs_print_leaf(root, leaf);
42236567e837SChris Mason 		BUG();
42245f39d397SChris Mason 	}
42256567e837SChris Mason 	slot = path->slots[0];
42265f39d397SChris Mason 	old_data = btrfs_item_end_nr(leaf, slot);
42276567e837SChris Mason 
42286567e837SChris Mason 	BUG_ON(slot < 0);
42293326d1b0SChris Mason 	if (slot >= nritems) {
42303326d1b0SChris Mason 		btrfs_print_leaf(root, leaf);
4231d397712bSChris Mason 		printk(KERN_CRIT "slot %d too large, nritems %d\n",
4232d397712bSChris Mason 		       slot, nritems);
42333326d1b0SChris Mason 		BUG_ON(1);
42343326d1b0SChris Mason 	}
42356567e837SChris Mason 
42366567e837SChris Mason 	/*
42376567e837SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
42386567e837SChris Mason 	 */
42396567e837SChris Mason 	/* first correct the data pointers */
42406567e837SChris Mason 	for (i = slot; i < nritems; i++) {
42415f39d397SChris Mason 		u32 ioff;
42425f39d397SChris Mason 		item = btrfs_item_nr(leaf, i);
4243db94535dSChris Mason 
4244cfed81a0SChris Mason 		ioff = btrfs_token_item_offset(leaf, item, &token);
4245cfed81a0SChris Mason 		btrfs_set_token_item_offset(leaf, item,
4246cfed81a0SChris Mason 					    ioff - data_size, &token);
42476567e837SChris Mason 	}
42485f39d397SChris Mason 
42496567e837SChris Mason 	/* shift the data */
42505f39d397SChris Mason 	memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
42516567e837SChris Mason 		      data_end - data_size, btrfs_leaf_data(leaf) +
42526567e837SChris Mason 		      data_end, old_data - data_end);
42535f39d397SChris Mason 
42546567e837SChris Mason 	data_end = old_data;
42555f39d397SChris Mason 	old_size = btrfs_item_size_nr(leaf, slot);
42565f39d397SChris Mason 	item = btrfs_item_nr(leaf, slot);
42575f39d397SChris Mason 	btrfs_set_item_size(leaf, item, old_size + data_size);
42585f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
42596567e837SChris Mason 
42605f39d397SChris Mason 	if (btrfs_leaf_free_space(root, leaf) < 0) {
42615f39d397SChris Mason 		btrfs_print_leaf(root, leaf);
42626567e837SChris Mason 		BUG();
42635f39d397SChris Mason 	}
42646567e837SChris Mason }
42656567e837SChris Mason 
426674123bd7SChris Mason /*
4267d352ac68SChris Mason  * Given a key and some data, insert items into the tree.
426874123bd7SChris Mason  * This does all the path init required, making room in the tree if needed.
4269f3465ca4SJosef Bacik  * Returns the number of keys that were inserted.
4270f3465ca4SJosef Bacik  */
4271f3465ca4SJosef Bacik int btrfs_insert_some_items(struct btrfs_trans_handle *trans,
4272f3465ca4SJosef Bacik 			    struct btrfs_root *root,
4273f3465ca4SJosef Bacik 			    struct btrfs_path *path,
4274f3465ca4SJosef Bacik 			    struct btrfs_key *cpu_key, u32 *data_size,
4275f3465ca4SJosef Bacik 			    int nr)
4276f3465ca4SJosef Bacik {
4277f3465ca4SJosef Bacik 	struct extent_buffer *leaf;
4278f3465ca4SJosef Bacik 	struct btrfs_item *item;
4279f3465ca4SJosef Bacik 	int ret = 0;
4280f3465ca4SJosef Bacik 	int slot;
4281f3465ca4SJosef Bacik 	int i;
4282f3465ca4SJosef Bacik 	u32 nritems;
4283f3465ca4SJosef Bacik 	u32 total_data = 0;
4284f3465ca4SJosef Bacik 	u32 total_size = 0;
4285f3465ca4SJosef Bacik 	unsigned int data_end;
4286f3465ca4SJosef Bacik 	struct btrfs_disk_key disk_key;
4287f3465ca4SJosef Bacik 	struct btrfs_key found_key;
4288cfed81a0SChris Mason 	struct btrfs_map_token token;
4289cfed81a0SChris Mason 
4290cfed81a0SChris Mason 	btrfs_init_map_token(&token);
4291f3465ca4SJosef Bacik 
429287b29b20SYan Zheng 	for (i = 0; i < nr; i++) {
429387b29b20SYan Zheng 		if (total_size + data_size[i] + sizeof(struct btrfs_item) >
429487b29b20SYan Zheng 		    BTRFS_LEAF_DATA_SIZE(root)) {
429587b29b20SYan Zheng 			break;
429687b29b20SYan Zheng 			nr = i;
429787b29b20SYan Zheng 		}
4298f3465ca4SJosef Bacik 		total_data += data_size[i];
429987b29b20SYan Zheng 		total_size += data_size[i] + sizeof(struct btrfs_item);
430087b29b20SYan Zheng 	}
430187b29b20SYan Zheng 	BUG_ON(nr == 0);
4302f3465ca4SJosef Bacik 
4303f3465ca4SJosef Bacik 	ret = btrfs_search_slot(trans, root, cpu_key, path, total_size, 1);
4304f3465ca4SJosef Bacik 	if (ret == 0)
4305f3465ca4SJosef Bacik 		return -EEXIST;
4306f3465ca4SJosef Bacik 	if (ret < 0)
4307f3465ca4SJosef Bacik 		goto out;
4308f3465ca4SJosef Bacik 
4309f3465ca4SJosef Bacik 	leaf = path->nodes[0];
4310f3465ca4SJosef Bacik 
4311f3465ca4SJosef Bacik 	nritems = btrfs_header_nritems(leaf);
4312f3465ca4SJosef Bacik 	data_end = leaf_data_end(root, leaf);
4313f3465ca4SJosef Bacik 
4314f3465ca4SJosef Bacik 	if (btrfs_leaf_free_space(root, leaf) < total_size) {
4315f3465ca4SJosef Bacik 		for (i = nr; i >= 0; i--) {
4316f3465ca4SJosef Bacik 			total_data -= data_size[i];
4317f3465ca4SJosef Bacik 			total_size -= data_size[i] + sizeof(struct btrfs_item);
4318f3465ca4SJosef Bacik 			if (total_size < btrfs_leaf_free_space(root, leaf))
4319f3465ca4SJosef Bacik 				break;
4320f3465ca4SJosef Bacik 		}
4321f3465ca4SJosef Bacik 		nr = i;
4322f3465ca4SJosef Bacik 	}
4323f3465ca4SJosef Bacik 
4324f3465ca4SJosef Bacik 	slot = path->slots[0];
4325f3465ca4SJosef Bacik 	BUG_ON(slot < 0);
4326f3465ca4SJosef Bacik 
4327f3465ca4SJosef Bacik 	if (slot != nritems) {
4328f3465ca4SJosef Bacik 		unsigned int old_data = btrfs_item_end_nr(leaf, slot);
4329f3465ca4SJosef Bacik 
4330f3465ca4SJosef Bacik 		item = btrfs_item_nr(leaf, slot);
4331f3465ca4SJosef Bacik 		btrfs_item_key_to_cpu(leaf, &found_key, slot);
4332f3465ca4SJosef Bacik 
4333f3465ca4SJosef Bacik 		/* figure out how many keys we can insert in here */
4334f3465ca4SJosef Bacik 		total_data = data_size[0];
4335f3465ca4SJosef Bacik 		for (i = 1; i < nr; i++) {
43365d4f98a2SYan Zheng 			if (btrfs_comp_cpu_keys(&found_key, cpu_key + i) <= 0)
4337f3465ca4SJosef Bacik 				break;
4338f3465ca4SJosef Bacik 			total_data += data_size[i];
4339f3465ca4SJosef Bacik 		}
4340f3465ca4SJosef Bacik 		nr = i;
4341f3465ca4SJosef Bacik 
4342f3465ca4SJosef Bacik 		if (old_data < data_end) {
4343f3465ca4SJosef Bacik 			btrfs_print_leaf(root, leaf);
4344d397712bSChris Mason 			printk(KERN_CRIT "slot %d old_data %d data_end %d\n",
4345f3465ca4SJosef Bacik 			       slot, old_data, data_end);
4346f3465ca4SJosef Bacik 			BUG_ON(1);
4347f3465ca4SJosef Bacik 		}
4348f3465ca4SJosef Bacik 		/*
4349f3465ca4SJosef Bacik 		 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4350f3465ca4SJosef Bacik 		 */
4351f3465ca4SJosef Bacik 		/* first correct the data pointers */
4352f3465ca4SJosef Bacik 		for (i = slot; i < nritems; i++) {
4353f3465ca4SJosef Bacik 			u32 ioff;
4354f3465ca4SJosef Bacik 
4355f3465ca4SJosef Bacik 			item = btrfs_item_nr(leaf, i);
4356cfed81a0SChris Mason 			ioff = btrfs_token_item_offset(leaf, item, &token);
4357cfed81a0SChris Mason 			btrfs_set_token_item_offset(leaf, item,
4358cfed81a0SChris Mason 						    ioff - total_data, &token);
4359f3465ca4SJosef Bacik 		}
4360f3465ca4SJosef Bacik 		/* shift the items */
4361f3465ca4SJosef Bacik 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + nr),
4362f3465ca4SJosef Bacik 			      btrfs_item_nr_offset(slot),
4363f3465ca4SJosef Bacik 			      (nritems - slot) * sizeof(struct btrfs_item));
4364f3465ca4SJosef Bacik 
4365f3465ca4SJosef Bacik 		/* shift the data */
4366f3465ca4SJosef Bacik 		memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
4367f3465ca4SJosef Bacik 			      data_end - total_data, btrfs_leaf_data(leaf) +
4368f3465ca4SJosef Bacik 			      data_end, old_data - data_end);
4369f3465ca4SJosef Bacik 		data_end = old_data;
4370f3465ca4SJosef Bacik 	} else {
4371f3465ca4SJosef Bacik 		/*
4372f3465ca4SJosef Bacik 		 * this sucks but it has to be done, if we are inserting at
4373f3465ca4SJosef Bacik 		 * the end of the leaf only insert 1 of the items, since we
4374f3465ca4SJosef Bacik 		 * have no way of knowing whats on the next leaf and we'd have
4375f3465ca4SJosef Bacik 		 * to drop our current locks to figure it out
4376f3465ca4SJosef Bacik 		 */
4377f3465ca4SJosef Bacik 		nr = 1;
4378f3465ca4SJosef Bacik 	}
4379f3465ca4SJosef Bacik 
4380f3465ca4SJosef Bacik 	/* setup the item for the new data */
4381f3465ca4SJosef Bacik 	for (i = 0; i < nr; i++) {
4382f3465ca4SJosef Bacik 		btrfs_cpu_key_to_disk(&disk_key, cpu_key + i);
4383f3465ca4SJosef Bacik 		btrfs_set_item_key(leaf, &disk_key, slot + i);
4384f3465ca4SJosef Bacik 		item = btrfs_item_nr(leaf, slot + i);
4385cfed81a0SChris Mason 		btrfs_set_token_item_offset(leaf, item,
4386cfed81a0SChris Mason 					    data_end - data_size[i], &token);
4387f3465ca4SJosef Bacik 		data_end -= data_size[i];
4388cfed81a0SChris Mason 		btrfs_set_token_item_size(leaf, item, data_size[i], &token);
4389f3465ca4SJosef Bacik 	}
4390f3465ca4SJosef Bacik 	btrfs_set_header_nritems(leaf, nritems + nr);
4391f3465ca4SJosef Bacik 	btrfs_mark_buffer_dirty(leaf);
4392f3465ca4SJosef Bacik 
4393f3465ca4SJosef Bacik 	ret = 0;
4394f3465ca4SJosef Bacik 	if (slot == 0) {
4395f3465ca4SJosef Bacik 		btrfs_cpu_key_to_disk(&disk_key, cpu_key);
4396143bede5SJeff Mahoney 		fixup_low_keys(trans, root, path, &disk_key, 1);
4397f3465ca4SJosef Bacik 	}
4398f3465ca4SJosef Bacik 
4399f3465ca4SJosef Bacik 	if (btrfs_leaf_free_space(root, leaf) < 0) {
4400f3465ca4SJosef Bacik 		btrfs_print_leaf(root, leaf);
4401f3465ca4SJosef Bacik 		BUG();
4402f3465ca4SJosef Bacik 	}
4403f3465ca4SJosef Bacik out:
4404f3465ca4SJosef Bacik 	if (!ret)
4405f3465ca4SJosef Bacik 		ret = nr;
4406f3465ca4SJosef Bacik 	return ret;
4407f3465ca4SJosef Bacik }
4408f3465ca4SJosef Bacik 
4409f3465ca4SJosef Bacik /*
441044871b1bSChris Mason  * this is a helper for btrfs_insert_empty_items, the main goal here is
441144871b1bSChris Mason  * to save stack depth by doing the bulk of the work in a function
441244871b1bSChris Mason  * that doesn't call btrfs_search_slot
441374123bd7SChris Mason  */
4414143bede5SJeff Mahoney void setup_items_for_insert(struct btrfs_trans_handle *trans,
441544871b1bSChris Mason 			    struct btrfs_root *root, struct btrfs_path *path,
44169c58309dSChris Mason 			    struct btrfs_key *cpu_key, u32 *data_size,
441744871b1bSChris Mason 			    u32 total_data, u32 total_size, int nr)
4418be0e5c09SChris Mason {
44195f39d397SChris Mason 	struct btrfs_item *item;
44209c58309dSChris Mason 	int i;
44217518a238SChris Mason 	u32 nritems;
4422be0e5c09SChris Mason 	unsigned int data_end;
4423e2fa7227SChris Mason 	struct btrfs_disk_key disk_key;
442444871b1bSChris Mason 	struct extent_buffer *leaf;
442544871b1bSChris Mason 	int slot;
4426cfed81a0SChris Mason 	struct btrfs_map_token token;
4427cfed81a0SChris Mason 
4428cfed81a0SChris Mason 	btrfs_init_map_token(&token);
4429e2fa7227SChris Mason 
44305f39d397SChris Mason 	leaf = path->nodes[0];
443144871b1bSChris Mason 	slot = path->slots[0];
443274123bd7SChris Mason 
44335f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
4434123abc88SChris Mason 	data_end = leaf_data_end(root, leaf);
4435eb60ceacSChris Mason 
4436f25956ccSChris Mason 	if (btrfs_leaf_free_space(root, leaf) < total_size) {
44373326d1b0SChris Mason 		btrfs_print_leaf(root, leaf);
4438d397712bSChris Mason 		printk(KERN_CRIT "not enough freespace need %u have %d\n",
44399c58309dSChris Mason 		       total_size, btrfs_leaf_free_space(root, leaf));
4440be0e5c09SChris Mason 		BUG();
4441d4dbff95SChris Mason 	}
44425f39d397SChris Mason 
4443be0e5c09SChris Mason 	if (slot != nritems) {
44445f39d397SChris Mason 		unsigned int old_data = btrfs_item_end_nr(leaf, slot);
4445be0e5c09SChris Mason 
44465f39d397SChris Mason 		if (old_data < data_end) {
44475f39d397SChris Mason 			btrfs_print_leaf(root, leaf);
4448d397712bSChris Mason 			printk(KERN_CRIT "slot %d old_data %d data_end %d\n",
44495f39d397SChris Mason 			       slot, old_data, data_end);
44505f39d397SChris Mason 			BUG_ON(1);
44515f39d397SChris Mason 		}
4452be0e5c09SChris Mason 		/*
4453be0e5c09SChris Mason 		 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4454be0e5c09SChris Mason 		 */
4455be0e5c09SChris Mason 		/* first correct the data pointers */
44560783fcfcSChris Mason 		for (i = slot; i < nritems; i++) {
44575f39d397SChris Mason 			u32 ioff;
4458db94535dSChris Mason 
44595f39d397SChris Mason 			item = btrfs_item_nr(leaf, i);
4460cfed81a0SChris Mason 			ioff = btrfs_token_item_offset(leaf, item, &token);
4461cfed81a0SChris Mason 			btrfs_set_token_item_offset(leaf, item,
4462cfed81a0SChris Mason 						    ioff - total_data, &token);
44630783fcfcSChris Mason 		}
4464be0e5c09SChris Mason 		/* shift the items */
44659c58309dSChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + nr),
44665f39d397SChris Mason 			      btrfs_item_nr_offset(slot),
44670783fcfcSChris Mason 			      (nritems - slot) * sizeof(struct btrfs_item));
4468be0e5c09SChris Mason 
4469be0e5c09SChris Mason 		/* shift the data */
44705f39d397SChris Mason 		memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
44719c58309dSChris Mason 			      data_end - total_data, btrfs_leaf_data(leaf) +
4472be0e5c09SChris Mason 			      data_end, old_data - data_end);
4473be0e5c09SChris Mason 		data_end = old_data;
4474be0e5c09SChris Mason 	}
44755f39d397SChris Mason 
447662e2749eSChris Mason 	/* setup the item for the new data */
44779c58309dSChris Mason 	for (i = 0; i < nr; i++) {
44789c58309dSChris Mason 		btrfs_cpu_key_to_disk(&disk_key, cpu_key + i);
44799c58309dSChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot + i);
44809c58309dSChris Mason 		item = btrfs_item_nr(leaf, slot + i);
4481cfed81a0SChris Mason 		btrfs_set_token_item_offset(leaf, item,
4482cfed81a0SChris Mason 					    data_end - data_size[i], &token);
44839c58309dSChris Mason 		data_end -= data_size[i];
4484cfed81a0SChris Mason 		btrfs_set_token_item_size(leaf, item, data_size[i], &token);
44859c58309dSChris Mason 	}
448644871b1bSChris Mason 
44879c58309dSChris Mason 	btrfs_set_header_nritems(leaf, nritems + nr);
4488aa5d6bedSChris Mason 
44895a01a2e3SChris Mason 	if (slot == 0) {
44905a01a2e3SChris Mason 		btrfs_cpu_key_to_disk(&disk_key, cpu_key);
4491143bede5SJeff Mahoney 		fixup_low_keys(trans, root, path, &disk_key, 1);
44925a01a2e3SChris Mason 	}
4493b9473439SChris Mason 	btrfs_unlock_up_safe(path, 1);
4494b9473439SChris Mason 	btrfs_mark_buffer_dirty(leaf);
4495aa5d6bedSChris Mason 
44965f39d397SChris Mason 	if (btrfs_leaf_free_space(root, leaf) < 0) {
44975f39d397SChris Mason 		btrfs_print_leaf(root, leaf);
4498be0e5c09SChris Mason 		BUG();
44995f39d397SChris Mason 	}
450044871b1bSChris Mason }
450144871b1bSChris Mason 
450244871b1bSChris Mason /*
450344871b1bSChris Mason  * Given a key and some data, insert items into the tree.
450444871b1bSChris Mason  * This does all the path init required, making room in the tree if needed.
450544871b1bSChris Mason  */
450644871b1bSChris Mason int btrfs_insert_empty_items(struct btrfs_trans_handle *trans,
450744871b1bSChris Mason 			    struct btrfs_root *root,
450844871b1bSChris Mason 			    struct btrfs_path *path,
450944871b1bSChris Mason 			    struct btrfs_key *cpu_key, u32 *data_size,
451044871b1bSChris Mason 			    int nr)
451144871b1bSChris Mason {
451244871b1bSChris Mason 	int ret = 0;
451344871b1bSChris Mason 	int slot;
451444871b1bSChris Mason 	int i;
451544871b1bSChris Mason 	u32 total_size = 0;
451644871b1bSChris Mason 	u32 total_data = 0;
451744871b1bSChris Mason 
451844871b1bSChris Mason 	for (i = 0; i < nr; i++)
451944871b1bSChris Mason 		total_data += data_size[i];
452044871b1bSChris Mason 
452144871b1bSChris Mason 	total_size = total_data + (nr * sizeof(struct btrfs_item));
452244871b1bSChris Mason 	ret = btrfs_search_slot(trans, root, cpu_key, path, total_size, 1);
452344871b1bSChris Mason 	if (ret == 0)
452444871b1bSChris Mason 		return -EEXIST;
452544871b1bSChris Mason 	if (ret < 0)
4526143bede5SJeff Mahoney 		return ret;
452744871b1bSChris Mason 
452844871b1bSChris Mason 	slot = path->slots[0];
452944871b1bSChris Mason 	BUG_ON(slot < 0);
453044871b1bSChris Mason 
4531143bede5SJeff Mahoney 	setup_items_for_insert(trans, root, path, cpu_key, data_size,
453244871b1bSChris Mason 			       total_data, total_size, nr);
4533143bede5SJeff Mahoney 	return 0;
453462e2749eSChris Mason }
453562e2749eSChris Mason 
453662e2749eSChris Mason /*
453762e2749eSChris Mason  * Given a key and some data, insert an item into the tree.
453862e2749eSChris Mason  * This does all the path init required, making room in the tree if needed.
453962e2749eSChris Mason  */
4540e089f05cSChris Mason int btrfs_insert_item(struct btrfs_trans_handle *trans, struct btrfs_root
4541e089f05cSChris Mason 		      *root, struct btrfs_key *cpu_key, void *data, u32
4542e089f05cSChris Mason 		      data_size)
454362e2749eSChris Mason {
454462e2749eSChris Mason 	int ret = 0;
45452c90e5d6SChris Mason 	struct btrfs_path *path;
45465f39d397SChris Mason 	struct extent_buffer *leaf;
45475f39d397SChris Mason 	unsigned long ptr;
454862e2749eSChris Mason 
45492c90e5d6SChris Mason 	path = btrfs_alloc_path();
4550db5b493aSTsutomu Itoh 	if (!path)
4551db5b493aSTsutomu Itoh 		return -ENOMEM;
45522c90e5d6SChris Mason 	ret = btrfs_insert_empty_item(trans, root, path, cpu_key, data_size);
455362e2749eSChris Mason 	if (!ret) {
45545f39d397SChris Mason 		leaf = path->nodes[0];
45555f39d397SChris Mason 		ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
45565f39d397SChris Mason 		write_extent_buffer(leaf, data, ptr, data_size);
45575f39d397SChris Mason 		btrfs_mark_buffer_dirty(leaf);
455862e2749eSChris Mason 	}
45592c90e5d6SChris Mason 	btrfs_free_path(path);
4560aa5d6bedSChris Mason 	return ret;
4561be0e5c09SChris Mason }
4562be0e5c09SChris Mason 
456374123bd7SChris Mason /*
45645de08d7dSChris Mason  * delete the pointer from a given node.
456574123bd7SChris Mason  *
4566d352ac68SChris Mason  * the tree should have been previously balanced so the deletion does not
4567d352ac68SChris Mason  * empty a node.
456874123bd7SChris Mason  */
4569143bede5SJeff Mahoney static void del_ptr(struct btrfs_trans_handle *trans, struct btrfs_root *root,
4570f3ea38daSJan Schmidt 		    struct btrfs_path *path, int level, int slot,
4571f3ea38daSJan Schmidt 		    int tree_mod_log)
4572be0e5c09SChris Mason {
45735f39d397SChris Mason 	struct extent_buffer *parent = path->nodes[level];
45747518a238SChris Mason 	u32 nritems;
4575f3ea38daSJan Schmidt 	int ret;
4576be0e5c09SChris Mason 
45775f39d397SChris Mason 	nritems = btrfs_header_nritems(parent);
4578be0e5c09SChris Mason 	if (slot != nritems - 1) {
4579f3ea38daSJan Schmidt 		if (tree_mod_log && level)
4580f3ea38daSJan Schmidt 			tree_mod_log_eb_move(root->fs_info, parent, slot,
4581f3ea38daSJan Schmidt 					     slot + 1, nritems - slot - 1);
45825f39d397SChris Mason 		memmove_extent_buffer(parent,
45835f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot),
45845f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot + 1),
4585d6025579SChris Mason 			      sizeof(struct btrfs_key_ptr) *
4586d6025579SChris Mason 			      (nritems - slot - 1));
4587f395694cSJan Schmidt 	} else if (tree_mod_log && level) {
4588f3ea38daSJan Schmidt 		ret = tree_mod_log_insert_key(root->fs_info, parent, slot,
4589f3ea38daSJan Schmidt 					      MOD_LOG_KEY_REMOVE);
4590f3ea38daSJan Schmidt 		BUG_ON(ret < 0);
4591be0e5c09SChris Mason 	}
4592f3ea38daSJan Schmidt 
45937518a238SChris Mason 	nritems--;
45945f39d397SChris Mason 	btrfs_set_header_nritems(parent, nritems);
45957518a238SChris Mason 	if (nritems == 0 && parent == root->node) {
45965f39d397SChris Mason 		BUG_ON(btrfs_header_level(root->node) != 1);
4597eb60ceacSChris Mason 		/* just turn the root into a leaf and break */
45985f39d397SChris Mason 		btrfs_set_header_level(root->node, 0);
4599bb803951SChris Mason 	} else if (slot == 0) {
46005f39d397SChris Mason 		struct btrfs_disk_key disk_key;
46015f39d397SChris Mason 
46025f39d397SChris Mason 		btrfs_node_key(parent, &disk_key, 0);
4603143bede5SJeff Mahoney 		fixup_low_keys(trans, root, path, &disk_key, level + 1);
4604be0e5c09SChris Mason 	}
4605d6025579SChris Mason 	btrfs_mark_buffer_dirty(parent);
4606be0e5c09SChris Mason }
4607be0e5c09SChris Mason 
460874123bd7SChris Mason /*
4609323ac95bSChris Mason  * a helper function to delete the leaf pointed to by path->slots[1] and
46105d4f98a2SYan Zheng  * path->nodes[1].
4611323ac95bSChris Mason  *
4612323ac95bSChris Mason  * This deletes the pointer in path->nodes[1] and frees the leaf
4613323ac95bSChris Mason  * block extent.  zero is returned if it all worked out, < 0 otherwise.
4614323ac95bSChris Mason  *
4615323ac95bSChris Mason  * The path must have already been setup for deleting the leaf, including
4616323ac95bSChris Mason  * all the proper balancing.  path->nodes[1] must be locked.
4617323ac95bSChris Mason  */
4618143bede5SJeff Mahoney static noinline void btrfs_del_leaf(struct btrfs_trans_handle *trans,
4619323ac95bSChris Mason 				    struct btrfs_root *root,
46205d4f98a2SYan Zheng 				    struct btrfs_path *path,
46215d4f98a2SYan Zheng 				    struct extent_buffer *leaf)
4622323ac95bSChris Mason {
46235d4f98a2SYan Zheng 	WARN_ON(btrfs_header_generation(leaf) != trans->transid);
4624f3ea38daSJan Schmidt 	del_ptr(trans, root, path, 1, path->slots[1], 1);
4625323ac95bSChris Mason 
46264d081c41SChris Mason 	/*
46274d081c41SChris Mason 	 * btrfs_free_extent is expensive, we want to make sure we
46284d081c41SChris Mason 	 * aren't holding any locks when we call it
46294d081c41SChris Mason 	 */
46304d081c41SChris Mason 	btrfs_unlock_up_safe(path, 0);
46314d081c41SChris Mason 
4632f0486c68SYan, Zheng 	root_sub_used(root, leaf->len);
4633f0486c68SYan, Zheng 
46343083ee2eSJosef Bacik 	extent_buffer_get(leaf);
46355581a51aSJan Schmidt 	btrfs_free_tree_block(trans, root, leaf, 0, 1);
46363083ee2eSJosef Bacik 	free_extent_buffer_stale(leaf);
4637323ac95bSChris Mason }
4638323ac95bSChris Mason /*
463974123bd7SChris Mason  * delete the item at the leaf level in path.  If that empties
464074123bd7SChris Mason  * the leaf, remove it from the tree
464174123bd7SChris Mason  */
464285e21bacSChris Mason int btrfs_del_items(struct btrfs_trans_handle *trans, struct btrfs_root *root,
464385e21bacSChris Mason 		    struct btrfs_path *path, int slot, int nr)
4644be0e5c09SChris Mason {
46455f39d397SChris Mason 	struct extent_buffer *leaf;
46465f39d397SChris Mason 	struct btrfs_item *item;
464785e21bacSChris Mason 	int last_off;
464885e21bacSChris Mason 	int dsize = 0;
4649aa5d6bedSChris Mason 	int ret = 0;
4650aa5d6bedSChris Mason 	int wret;
465185e21bacSChris Mason 	int i;
46527518a238SChris Mason 	u32 nritems;
4653cfed81a0SChris Mason 	struct btrfs_map_token token;
4654cfed81a0SChris Mason 
4655cfed81a0SChris Mason 	btrfs_init_map_token(&token);
4656be0e5c09SChris Mason 
46575f39d397SChris Mason 	leaf = path->nodes[0];
465885e21bacSChris Mason 	last_off = btrfs_item_offset_nr(leaf, slot + nr - 1);
465985e21bacSChris Mason 
466085e21bacSChris Mason 	for (i = 0; i < nr; i++)
466185e21bacSChris Mason 		dsize += btrfs_item_size_nr(leaf, slot + i);
466285e21bacSChris Mason 
46635f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
4664be0e5c09SChris Mason 
466585e21bacSChris Mason 	if (slot + nr != nritems) {
4666123abc88SChris Mason 		int data_end = leaf_data_end(root, leaf);
46675f39d397SChris Mason 
46685f39d397SChris Mason 		memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
4669d6025579SChris Mason 			      data_end + dsize,
4670123abc88SChris Mason 			      btrfs_leaf_data(leaf) + data_end,
467185e21bacSChris Mason 			      last_off - data_end);
46725f39d397SChris Mason 
467385e21bacSChris Mason 		for (i = slot + nr; i < nritems; i++) {
46745f39d397SChris Mason 			u32 ioff;
4675db94535dSChris Mason 
46765f39d397SChris Mason 			item = btrfs_item_nr(leaf, i);
4677cfed81a0SChris Mason 			ioff = btrfs_token_item_offset(leaf, item, &token);
4678cfed81a0SChris Mason 			btrfs_set_token_item_offset(leaf, item,
4679cfed81a0SChris Mason 						    ioff + dsize, &token);
46800783fcfcSChris Mason 		}
4681db94535dSChris Mason 
46825f39d397SChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot),
468385e21bacSChris Mason 			      btrfs_item_nr_offset(slot + nr),
46840783fcfcSChris Mason 			      sizeof(struct btrfs_item) *
468585e21bacSChris Mason 			      (nritems - slot - nr));
4686be0e5c09SChris Mason 	}
468785e21bacSChris Mason 	btrfs_set_header_nritems(leaf, nritems - nr);
468885e21bacSChris Mason 	nritems -= nr;
46895f39d397SChris Mason 
469074123bd7SChris Mason 	/* delete the leaf if we've emptied it */
46917518a238SChris Mason 	if (nritems == 0) {
46925f39d397SChris Mason 		if (leaf == root->node) {
46935f39d397SChris Mason 			btrfs_set_header_level(leaf, 0);
46949a8dd150SChris Mason 		} else {
4695f0486c68SYan, Zheng 			btrfs_set_path_blocking(path);
4696f0486c68SYan, Zheng 			clean_tree_block(trans, root, leaf);
4697143bede5SJeff Mahoney 			btrfs_del_leaf(trans, root, path, leaf);
46989a8dd150SChris Mason 		}
4699be0e5c09SChris Mason 	} else {
47007518a238SChris Mason 		int used = leaf_space_used(leaf, 0, nritems);
4701aa5d6bedSChris Mason 		if (slot == 0) {
47025f39d397SChris Mason 			struct btrfs_disk_key disk_key;
47035f39d397SChris Mason 
47045f39d397SChris Mason 			btrfs_item_key(leaf, &disk_key, 0);
4705143bede5SJeff Mahoney 			fixup_low_keys(trans, root, path, &disk_key, 1);
4706aa5d6bedSChris Mason 		}
4707aa5d6bedSChris Mason 
470874123bd7SChris Mason 		/* delete the leaf if it is mostly empty */
4709d717aa1dSYan Zheng 		if (used < BTRFS_LEAF_DATA_SIZE(root) / 3) {
4710be0e5c09SChris Mason 			/* push_leaf_left fixes the path.
4711be0e5c09SChris Mason 			 * make sure the path still points to our leaf
4712be0e5c09SChris Mason 			 * for possible call to del_ptr below
4713be0e5c09SChris Mason 			 */
47144920c9acSChris Mason 			slot = path->slots[1];
47155f39d397SChris Mason 			extent_buffer_get(leaf);
47165f39d397SChris Mason 
4717b9473439SChris Mason 			btrfs_set_path_blocking(path);
471899d8f83cSChris Mason 			wret = push_leaf_left(trans, root, path, 1, 1,
471999d8f83cSChris Mason 					      1, (u32)-1);
472054aa1f4dSChris Mason 			if (wret < 0 && wret != -ENOSPC)
4721aa5d6bedSChris Mason 				ret = wret;
47225f39d397SChris Mason 
47235f39d397SChris Mason 			if (path->nodes[0] == leaf &&
47245f39d397SChris Mason 			    btrfs_header_nritems(leaf)) {
472599d8f83cSChris Mason 				wret = push_leaf_right(trans, root, path, 1,
472699d8f83cSChris Mason 						       1, 1, 0);
472754aa1f4dSChris Mason 				if (wret < 0 && wret != -ENOSPC)
4728aa5d6bedSChris Mason 					ret = wret;
4729aa5d6bedSChris Mason 			}
47305f39d397SChris Mason 
47315f39d397SChris Mason 			if (btrfs_header_nritems(leaf) == 0) {
4732323ac95bSChris Mason 				path->slots[1] = slot;
4733143bede5SJeff Mahoney 				btrfs_del_leaf(trans, root, path, leaf);
47345f39d397SChris Mason 				free_extent_buffer(leaf);
4735143bede5SJeff Mahoney 				ret = 0;
47365de08d7dSChris Mason 			} else {
4737925baeddSChris Mason 				/* if we're still in the path, make sure
4738925baeddSChris Mason 				 * we're dirty.  Otherwise, one of the
4739925baeddSChris Mason 				 * push_leaf functions must have already
4740925baeddSChris Mason 				 * dirtied this buffer
4741925baeddSChris Mason 				 */
4742925baeddSChris Mason 				if (path->nodes[0] == leaf)
47435f39d397SChris Mason 					btrfs_mark_buffer_dirty(leaf);
47445f39d397SChris Mason 				free_extent_buffer(leaf);
4745be0e5c09SChris Mason 			}
4746d5719762SChris Mason 		} else {
47475f39d397SChris Mason 			btrfs_mark_buffer_dirty(leaf);
4748be0e5c09SChris Mason 		}
47499a8dd150SChris Mason 	}
4750aa5d6bedSChris Mason 	return ret;
47519a8dd150SChris Mason }
47529a8dd150SChris Mason 
475397571fd0SChris Mason /*
4754925baeddSChris Mason  * search the tree again to find a leaf with lesser keys
47557bb86316SChris Mason  * returns 0 if it found something or 1 if there are no lesser leaves.
47567bb86316SChris Mason  * returns < 0 on io errors.
4757d352ac68SChris Mason  *
4758d352ac68SChris Mason  * This may release the path, and so you may lose any locks held at the
4759d352ac68SChris Mason  * time you call it.
47607bb86316SChris Mason  */
47617bb86316SChris Mason int btrfs_prev_leaf(struct btrfs_root *root, struct btrfs_path *path)
47627bb86316SChris Mason {
4763925baeddSChris Mason 	struct btrfs_key key;
4764925baeddSChris Mason 	struct btrfs_disk_key found_key;
4765925baeddSChris Mason 	int ret;
47667bb86316SChris Mason 
4767925baeddSChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, 0);
4768925baeddSChris Mason 
4769925baeddSChris Mason 	if (key.offset > 0)
4770925baeddSChris Mason 		key.offset--;
4771925baeddSChris Mason 	else if (key.type > 0)
4772925baeddSChris Mason 		key.type--;
4773925baeddSChris Mason 	else if (key.objectid > 0)
4774925baeddSChris Mason 		key.objectid--;
4775925baeddSChris Mason 	else
47767bb86316SChris Mason 		return 1;
47777bb86316SChris Mason 
4778b3b4aa74SDavid Sterba 	btrfs_release_path(path);
4779925baeddSChris Mason 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4780925baeddSChris Mason 	if (ret < 0)
4781925baeddSChris Mason 		return ret;
4782925baeddSChris Mason 	btrfs_item_key(path->nodes[0], &found_key, 0);
4783925baeddSChris Mason 	ret = comp_keys(&found_key, &key);
4784925baeddSChris Mason 	if (ret < 0)
47857bb86316SChris Mason 		return 0;
4786925baeddSChris Mason 	return 1;
47877bb86316SChris Mason }
47887bb86316SChris Mason 
47893f157a2fSChris Mason /*
47903f157a2fSChris Mason  * A helper function to walk down the tree starting at min_key, and looking
47913f157a2fSChris Mason  * for nodes or leaves that are either in cache or have a minimum
4792d352ac68SChris Mason  * transaction id.  This is used by the btree defrag code, and tree logging
47933f157a2fSChris Mason  *
47943f157a2fSChris Mason  * This does not cow, but it does stuff the starting key it finds back
47953f157a2fSChris Mason  * into min_key, so you can call btrfs_search_slot with cow=1 on the
47963f157a2fSChris Mason  * key and get a writable path.
47973f157a2fSChris Mason  *
47983f157a2fSChris Mason  * This does lock as it descends, and path->keep_locks should be set
47993f157a2fSChris Mason  * to 1 by the caller.
48003f157a2fSChris Mason  *
48013f157a2fSChris Mason  * This honors path->lowest_level to prevent descent past a given level
48023f157a2fSChris Mason  * of the tree.
48033f157a2fSChris Mason  *
4804d352ac68SChris Mason  * min_trans indicates the oldest transaction that you are interested
4805d352ac68SChris Mason  * in walking through.  Any nodes or leaves older than min_trans are
4806d352ac68SChris Mason  * skipped over (without reading them).
4807d352ac68SChris Mason  *
48083f157a2fSChris Mason  * returns zero if something useful was found, < 0 on error and 1 if there
48093f157a2fSChris Mason  * was nothing in the tree that matched the search criteria.
48103f157a2fSChris Mason  */
48113f157a2fSChris Mason int btrfs_search_forward(struct btrfs_root *root, struct btrfs_key *min_key,
4812e02119d5SChris Mason 			 struct btrfs_key *max_key,
48133f157a2fSChris Mason 			 struct btrfs_path *path, int cache_only,
48143f157a2fSChris Mason 			 u64 min_trans)
48153f157a2fSChris Mason {
48163f157a2fSChris Mason 	struct extent_buffer *cur;
48173f157a2fSChris Mason 	struct btrfs_key found_key;
48183f157a2fSChris Mason 	int slot;
48199652480bSYan 	int sret;
48203f157a2fSChris Mason 	u32 nritems;
48213f157a2fSChris Mason 	int level;
48223f157a2fSChris Mason 	int ret = 1;
48233f157a2fSChris Mason 
4824934d375bSChris Mason 	WARN_ON(!path->keep_locks);
48253f157a2fSChris Mason again:
4826bd681513SChris Mason 	cur = btrfs_read_lock_root_node(root);
48273f157a2fSChris Mason 	level = btrfs_header_level(cur);
4828e02119d5SChris Mason 	WARN_ON(path->nodes[level]);
48293f157a2fSChris Mason 	path->nodes[level] = cur;
4830bd681513SChris Mason 	path->locks[level] = BTRFS_READ_LOCK;
48313f157a2fSChris Mason 
48323f157a2fSChris Mason 	if (btrfs_header_generation(cur) < min_trans) {
48333f157a2fSChris Mason 		ret = 1;
48343f157a2fSChris Mason 		goto out;
48353f157a2fSChris Mason 	}
48363f157a2fSChris Mason 	while (1) {
48373f157a2fSChris Mason 		nritems = btrfs_header_nritems(cur);
48383f157a2fSChris Mason 		level = btrfs_header_level(cur);
48399652480bSYan 		sret = bin_search(cur, min_key, level, &slot);
48403f157a2fSChris Mason 
4841323ac95bSChris Mason 		/* at the lowest level, we're done, setup the path and exit */
4842323ac95bSChris Mason 		if (level == path->lowest_level) {
4843e02119d5SChris Mason 			if (slot >= nritems)
4844e02119d5SChris Mason 				goto find_next_key;
48453f157a2fSChris Mason 			ret = 0;
48463f157a2fSChris Mason 			path->slots[level] = slot;
48473f157a2fSChris Mason 			btrfs_item_key_to_cpu(cur, &found_key, slot);
48483f157a2fSChris Mason 			goto out;
48493f157a2fSChris Mason 		}
48509652480bSYan 		if (sret && slot > 0)
48519652480bSYan 			slot--;
48523f157a2fSChris Mason 		/*
48533f157a2fSChris Mason 		 * check this node pointer against the cache_only and
48543f157a2fSChris Mason 		 * min_trans parameters.  If it isn't in cache or is too
48553f157a2fSChris Mason 		 * old, skip to the next one.
48563f157a2fSChris Mason 		 */
48573f157a2fSChris Mason 		while (slot < nritems) {
48583f157a2fSChris Mason 			u64 blockptr;
48593f157a2fSChris Mason 			u64 gen;
48603f157a2fSChris Mason 			struct extent_buffer *tmp;
4861e02119d5SChris Mason 			struct btrfs_disk_key disk_key;
4862e02119d5SChris Mason 
48633f157a2fSChris Mason 			blockptr = btrfs_node_blockptr(cur, slot);
48643f157a2fSChris Mason 			gen = btrfs_node_ptr_generation(cur, slot);
48653f157a2fSChris Mason 			if (gen < min_trans) {
48663f157a2fSChris Mason 				slot++;
48673f157a2fSChris Mason 				continue;
48683f157a2fSChris Mason 			}
48693f157a2fSChris Mason 			if (!cache_only)
48703f157a2fSChris Mason 				break;
48713f157a2fSChris Mason 
4872e02119d5SChris Mason 			if (max_key) {
4873e02119d5SChris Mason 				btrfs_node_key(cur, &disk_key, slot);
4874e02119d5SChris Mason 				if (comp_keys(&disk_key, max_key) >= 0) {
4875e02119d5SChris Mason 					ret = 1;
4876e02119d5SChris Mason 					goto out;
4877e02119d5SChris Mason 				}
4878e02119d5SChris Mason 			}
4879e02119d5SChris Mason 
48803f157a2fSChris Mason 			tmp = btrfs_find_tree_block(root, blockptr,
48813f157a2fSChris Mason 					    btrfs_level_size(root, level - 1));
48823f157a2fSChris Mason 
4883b9fab919SChris Mason 			if (tmp && btrfs_buffer_uptodate(tmp, gen, 1) > 0) {
48843f157a2fSChris Mason 				free_extent_buffer(tmp);
48853f157a2fSChris Mason 				break;
48863f157a2fSChris Mason 			}
48873f157a2fSChris Mason 			if (tmp)
48883f157a2fSChris Mason 				free_extent_buffer(tmp);
48893f157a2fSChris Mason 			slot++;
48903f157a2fSChris Mason 		}
4891e02119d5SChris Mason find_next_key:
48923f157a2fSChris Mason 		/*
48933f157a2fSChris Mason 		 * we didn't find a candidate key in this node, walk forward
48943f157a2fSChris Mason 		 * and find another one
48953f157a2fSChris Mason 		 */
48963f157a2fSChris Mason 		if (slot >= nritems) {
4897e02119d5SChris Mason 			path->slots[level] = slot;
4898b4ce94deSChris Mason 			btrfs_set_path_blocking(path);
4899e02119d5SChris Mason 			sret = btrfs_find_next_key(root, path, min_key, level,
49003f157a2fSChris Mason 						  cache_only, min_trans);
4901e02119d5SChris Mason 			if (sret == 0) {
4902b3b4aa74SDavid Sterba 				btrfs_release_path(path);
49033f157a2fSChris Mason 				goto again;
49043f157a2fSChris Mason 			} else {
49053f157a2fSChris Mason 				goto out;
49063f157a2fSChris Mason 			}
49073f157a2fSChris Mason 		}
49083f157a2fSChris Mason 		/* save our key for returning back */
49093f157a2fSChris Mason 		btrfs_node_key_to_cpu(cur, &found_key, slot);
49103f157a2fSChris Mason 		path->slots[level] = slot;
49113f157a2fSChris Mason 		if (level == path->lowest_level) {
49123f157a2fSChris Mason 			ret = 0;
4913f7c79f30SChris Mason 			unlock_up(path, level, 1, 0, NULL);
49143f157a2fSChris Mason 			goto out;
49153f157a2fSChris Mason 		}
4916b4ce94deSChris Mason 		btrfs_set_path_blocking(path);
49173f157a2fSChris Mason 		cur = read_node_slot(root, cur, slot);
491879787eaaSJeff Mahoney 		BUG_ON(!cur); /* -ENOMEM */
49193f157a2fSChris Mason 
4920bd681513SChris Mason 		btrfs_tree_read_lock(cur);
4921b4ce94deSChris Mason 
4922bd681513SChris Mason 		path->locks[level - 1] = BTRFS_READ_LOCK;
49233f157a2fSChris Mason 		path->nodes[level - 1] = cur;
4924f7c79f30SChris Mason 		unlock_up(path, level, 1, 0, NULL);
4925bd681513SChris Mason 		btrfs_clear_path_blocking(path, NULL, 0);
49263f157a2fSChris Mason 	}
49273f157a2fSChris Mason out:
49283f157a2fSChris Mason 	if (ret == 0)
49293f157a2fSChris Mason 		memcpy(min_key, &found_key, sizeof(found_key));
4930b4ce94deSChris Mason 	btrfs_set_path_blocking(path);
49313f157a2fSChris Mason 	return ret;
49323f157a2fSChris Mason }
49333f157a2fSChris Mason 
49343f157a2fSChris Mason /*
49353f157a2fSChris Mason  * this is similar to btrfs_next_leaf, but does not try to preserve
49363f157a2fSChris Mason  * and fixup the path.  It looks for and returns the next key in the
49373f157a2fSChris Mason  * tree based on the current path and the cache_only and min_trans
49383f157a2fSChris Mason  * parameters.
49393f157a2fSChris Mason  *
49403f157a2fSChris Mason  * 0 is returned if another key is found, < 0 if there are any errors
49413f157a2fSChris Mason  * and 1 is returned if there are no higher keys in the tree
49423f157a2fSChris Mason  *
49433f157a2fSChris Mason  * path->keep_locks should be set to 1 on the search made before
49443f157a2fSChris Mason  * calling this function.
49453f157a2fSChris Mason  */
4946e7a84565SChris Mason int btrfs_find_next_key(struct btrfs_root *root, struct btrfs_path *path,
494733c66f43SYan Zheng 			struct btrfs_key *key, int level,
49483f157a2fSChris Mason 			int cache_only, u64 min_trans)
4949e7a84565SChris Mason {
4950e7a84565SChris Mason 	int slot;
4951e7a84565SChris Mason 	struct extent_buffer *c;
4952e7a84565SChris Mason 
4953934d375bSChris Mason 	WARN_ON(!path->keep_locks);
4954e7a84565SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
4955e7a84565SChris Mason 		if (!path->nodes[level])
4956e7a84565SChris Mason 			return 1;
4957e7a84565SChris Mason 
4958e7a84565SChris Mason 		slot = path->slots[level] + 1;
4959e7a84565SChris Mason 		c = path->nodes[level];
49603f157a2fSChris Mason next:
4961e7a84565SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
496233c66f43SYan Zheng 			int ret;
496333c66f43SYan Zheng 			int orig_lowest;
496433c66f43SYan Zheng 			struct btrfs_key cur_key;
496533c66f43SYan Zheng 			if (level + 1 >= BTRFS_MAX_LEVEL ||
496633c66f43SYan Zheng 			    !path->nodes[level + 1])
4967e7a84565SChris Mason 				return 1;
496833c66f43SYan Zheng 
496933c66f43SYan Zheng 			if (path->locks[level + 1]) {
497033c66f43SYan Zheng 				level++;
4971e7a84565SChris Mason 				continue;
4972e7a84565SChris Mason 			}
497333c66f43SYan Zheng 
497433c66f43SYan Zheng 			slot = btrfs_header_nritems(c) - 1;
497533c66f43SYan Zheng 			if (level == 0)
497633c66f43SYan Zheng 				btrfs_item_key_to_cpu(c, &cur_key, slot);
497733c66f43SYan Zheng 			else
497833c66f43SYan Zheng 				btrfs_node_key_to_cpu(c, &cur_key, slot);
497933c66f43SYan Zheng 
498033c66f43SYan Zheng 			orig_lowest = path->lowest_level;
4981b3b4aa74SDavid Sterba 			btrfs_release_path(path);
498233c66f43SYan Zheng 			path->lowest_level = level;
498333c66f43SYan Zheng 			ret = btrfs_search_slot(NULL, root, &cur_key, path,
498433c66f43SYan Zheng 						0, 0);
498533c66f43SYan Zheng 			path->lowest_level = orig_lowest;
498633c66f43SYan Zheng 			if (ret < 0)
498733c66f43SYan Zheng 				return ret;
498833c66f43SYan Zheng 
498933c66f43SYan Zheng 			c = path->nodes[level];
499033c66f43SYan Zheng 			slot = path->slots[level];
499133c66f43SYan Zheng 			if (ret == 0)
499233c66f43SYan Zheng 				slot++;
499333c66f43SYan Zheng 			goto next;
499433c66f43SYan Zheng 		}
499533c66f43SYan Zheng 
4996e7a84565SChris Mason 		if (level == 0)
4997e7a84565SChris Mason 			btrfs_item_key_to_cpu(c, key, slot);
49983f157a2fSChris Mason 		else {
49993f157a2fSChris Mason 			u64 blockptr = btrfs_node_blockptr(c, slot);
50003f157a2fSChris Mason 			u64 gen = btrfs_node_ptr_generation(c, slot);
50013f157a2fSChris Mason 
50023f157a2fSChris Mason 			if (cache_only) {
50033f157a2fSChris Mason 				struct extent_buffer *cur;
50043f157a2fSChris Mason 				cur = btrfs_find_tree_block(root, blockptr,
50053f157a2fSChris Mason 					    btrfs_level_size(root, level - 1));
5006b9fab919SChris Mason 				if (!cur ||
5007b9fab919SChris Mason 				    btrfs_buffer_uptodate(cur, gen, 1) <= 0) {
50083f157a2fSChris Mason 					slot++;
50093f157a2fSChris Mason 					if (cur)
50103f157a2fSChris Mason 						free_extent_buffer(cur);
50113f157a2fSChris Mason 					goto next;
50123f157a2fSChris Mason 				}
50133f157a2fSChris Mason 				free_extent_buffer(cur);
50143f157a2fSChris Mason 			}
50153f157a2fSChris Mason 			if (gen < min_trans) {
50163f157a2fSChris Mason 				slot++;
50173f157a2fSChris Mason 				goto next;
50183f157a2fSChris Mason 			}
5019e7a84565SChris Mason 			btrfs_node_key_to_cpu(c, key, slot);
50203f157a2fSChris Mason 		}
5021e7a84565SChris Mason 		return 0;
5022e7a84565SChris Mason 	}
5023e7a84565SChris Mason 	return 1;
5024e7a84565SChris Mason }
5025e7a84565SChris Mason 
50267bb86316SChris Mason /*
5027925baeddSChris Mason  * search the tree again to find a leaf with greater keys
50280f70abe2SChris Mason  * returns 0 if it found something or 1 if there are no greater leaves.
50290f70abe2SChris Mason  * returns < 0 on io errors.
503097571fd0SChris Mason  */
5031234b63a0SChris Mason int btrfs_next_leaf(struct btrfs_root *root, struct btrfs_path *path)
5032d97e63b6SChris Mason {
50333d7806ecSJan Schmidt 	return btrfs_next_old_leaf(root, path, 0);
50343d7806ecSJan Schmidt }
50353d7806ecSJan Schmidt 
50363d7806ecSJan Schmidt int btrfs_next_old_leaf(struct btrfs_root *root, struct btrfs_path *path,
50373d7806ecSJan Schmidt 			u64 time_seq)
50383d7806ecSJan Schmidt {
5039d97e63b6SChris Mason 	int slot;
50408e73f275SChris Mason 	int level;
50415f39d397SChris Mason 	struct extent_buffer *c;
50428e73f275SChris Mason 	struct extent_buffer *next;
5043925baeddSChris Mason 	struct btrfs_key key;
5044925baeddSChris Mason 	u32 nritems;
5045925baeddSChris Mason 	int ret;
50468e73f275SChris Mason 	int old_spinning = path->leave_spinning;
5047bd681513SChris Mason 	int next_rw_lock = 0;
5048925baeddSChris Mason 
5049925baeddSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
5050d397712bSChris Mason 	if (nritems == 0)
5051925baeddSChris Mason 		return 1;
5052925baeddSChris Mason 
50538e73f275SChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, nritems - 1);
50548e73f275SChris Mason again:
50558e73f275SChris Mason 	level = 1;
50568e73f275SChris Mason 	next = NULL;
5057bd681513SChris Mason 	next_rw_lock = 0;
5058b3b4aa74SDavid Sterba 	btrfs_release_path(path);
50598e73f275SChris Mason 
5060a2135011SChris Mason 	path->keep_locks = 1;
50618e73f275SChris Mason 	path->leave_spinning = 1;
50628e73f275SChris Mason 
50633d7806ecSJan Schmidt 	if (time_seq)
50643d7806ecSJan Schmidt 		ret = btrfs_search_old_slot(root, &key, path, time_seq);
50653d7806ecSJan Schmidt 	else
5066925baeddSChris Mason 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5067925baeddSChris Mason 	path->keep_locks = 0;
5068925baeddSChris Mason 
5069925baeddSChris Mason 	if (ret < 0)
5070925baeddSChris Mason 		return ret;
5071925baeddSChris Mason 
5072a2135011SChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
5073168fd7d2SChris Mason 	/*
5074168fd7d2SChris Mason 	 * by releasing the path above we dropped all our locks.  A balance
5075168fd7d2SChris Mason 	 * could have added more items next to the key that used to be
5076168fd7d2SChris Mason 	 * at the very end of the block.  So, check again here and
5077168fd7d2SChris Mason 	 * advance the path if there are now more items available.
5078168fd7d2SChris Mason 	 */
5079a2135011SChris Mason 	if (nritems > 0 && path->slots[0] < nritems - 1) {
5080e457afecSYan Zheng 		if (ret == 0)
5081168fd7d2SChris Mason 			path->slots[0]++;
50828e73f275SChris Mason 		ret = 0;
5083925baeddSChris Mason 		goto done;
5084925baeddSChris Mason 	}
5085d97e63b6SChris Mason 
5086234b63a0SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
50878e73f275SChris Mason 		if (!path->nodes[level]) {
50888e73f275SChris Mason 			ret = 1;
50898e73f275SChris Mason 			goto done;
50908e73f275SChris Mason 		}
50915f39d397SChris Mason 
5092d97e63b6SChris Mason 		slot = path->slots[level] + 1;
5093d97e63b6SChris Mason 		c = path->nodes[level];
50945f39d397SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
5095d97e63b6SChris Mason 			level++;
50968e73f275SChris Mason 			if (level == BTRFS_MAX_LEVEL) {
50978e73f275SChris Mason 				ret = 1;
50988e73f275SChris Mason 				goto done;
50998e73f275SChris Mason 			}
5100d97e63b6SChris Mason 			continue;
5101d97e63b6SChris Mason 		}
51025f39d397SChris Mason 
5103925baeddSChris Mason 		if (next) {
5104bd681513SChris Mason 			btrfs_tree_unlock_rw(next, next_rw_lock);
51055f39d397SChris Mason 			free_extent_buffer(next);
5106925baeddSChris Mason 		}
51075f39d397SChris Mason 
51088e73f275SChris Mason 		next = c;
5109bd681513SChris Mason 		next_rw_lock = path->locks[level];
51108e73f275SChris Mason 		ret = read_block_for_search(NULL, root, path, &next, level,
51115d9e75c4SJan Schmidt 					    slot, &key, 0);
51128e73f275SChris Mason 		if (ret == -EAGAIN)
51138e73f275SChris Mason 			goto again;
51145f39d397SChris Mason 
511576a05b35SChris Mason 		if (ret < 0) {
5116b3b4aa74SDavid Sterba 			btrfs_release_path(path);
511776a05b35SChris Mason 			goto done;
511876a05b35SChris Mason 		}
511976a05b35SChris Mason 
51205cd57b2cSChris Mason 		if (!path->skip_locking) {
5121bd681513SChris Mason 			ret = btrfs_try_tree_read_lock(next);
51228e73f275SChris Mason 			if (!ret) {
51238e73f275SChris Mason 				btrfs_set_path_blocking(path);
5124bd681513SChris Mason 				btrfs_tree_read_lock(next);
5125bd681513SChris Mason 				btrfs_clear_path_blocking(path, next,
5126bd681513SChris Mason 							  BTRFS_READ_LOCK);
51278e73f275SChris Mason 			}
5128bd681513SChris Mason 			next_rw_lock = BTRFS_READ_LOCK;
5129bd681513SChris Mason 		}
5130d97e63b6SChris Mason 		break;
5131d97e63b6SChris Mason 	}
5132d97e63b6SChris Mason 	path->slots[level] = slot;
5133d97e63b6SChris Mason 	while (1) {
5134d97e63b6SChris Mason 		level--;
5135d97e63b6SChris Mason 		c = path->nodes[level];
5136925baeddSChris Mason 		if (path->locks[level])
5137bd681513SChris Mason 			btrfs_tree_unlock_rw(c, path->locks[level]);
51388e73f275SChris Mason 
51395f39d397SChris Mason 		free_extent_buffer(c);
5140d97e63b6SChris Mason 		path->nodes[level] = next;
5141d97e63b6SChris Mason 		path->slots[level] = 0;
5142a74a4b97SChris Mason 		if (!path->skip_locking)
5143bd681513SChris Mason 			path->locks[level] = next_rw_lock;
5144d97e63b6SChris Mason 		if (!level)
5145d97e63b6SChris Mason 			break;
5146b4ce94deSChris Mason 
51478e73f275SChris Mason 		ret = read_block_for_search(NULL, root, path, &next, level,
51485d9e75c4SJan Schmidt 					    0, &key, 0);
51498e73f275SChris Mason 		if (ret == -EAGAIN)
51508e73f275SChris Mason 			goto again;
51518e73f275SChris Mason 
515276a05b35SChris Mason 		if (ret < 0) {
5153b3b4aa74SDavid Sterba 			btrfs_release_path(path);
515476a05b35SChris Mason 			goto done;
515576a05b35SChris Mason 		}
515676a05b35SChris Mason 
51575cd57b2cSChris Mason 		if (!path->skip_locking) {
5158bd681513SChris Mason 			ret = btrfs_try_tree_read_lock(next);
51598e73f275SChris Mason 			if (!ret) {
51608e73f275SChris Mason 				btrfs_set_path_blocking(path);
5161bd681513SChris Mason 				btrfs_tree_read_lock(next);
5162bd681513SChris Mason 				btrfs_clear_path_blocking(path, next,
5163bd681513SChris Mason 							  BTRFS_READ_LOCK);
51648e73f275SChris Mason 			}
5165bd681513SChris Mason 			next_rw_lock = BTRFS_READ_LOCK;
5166bd681513SChris Mason 		}
5167d97e63b6SChris Mason 	}
51688e73f275SChris Mason 	ret = 0;
5169925baeddSChris Mason done:
5170f7c79f30SChris Mason 	unlock_up(path, 0, 1, 0, NULL);
51718e73f275SChris Mason 	path->leave_spinning = old_spinning;
51728e73f275SChris Mason 	if (!old_spinning)
51738e73f275SChris Mason 		btrfs_set_path_blocking(path);
51748e73f275SChris Mason 
51758e73f275SChris Mason 	return ret;
5176d97e63b6SChris Mason }
51770b86a832SChris Mason 
51783f157a2fSChris Mason /*
51793f157a2fSChris Mason  * this uses btrfs_prev_leaf to walk backwards in the tree, and keeps
51803f157a2fSChris Mason  * searching until it gets past min_objectid or finds an item of 'type'
51813f157a2fSChris Mason  *
51823f157a2fSChris Mason  * returns 0 if something is found, 1 if nothing was found and < 0 on error
51833f157a2fSChris Mason  */
51840b86a832SChris Mason int btrfs_previous_item(struct btrfs_root *root,
51850b86a832SChris Mason 			struct btrfs_path *path, u64 min_objectid,
51860b86a832SChris Mason 			int type)
51870b86a832SChris Mason {
51880b86a832SChris Mason 	struct btrfs_key found_key;
51890b86a832SChris Mason 	struct extent_buffer *leaf;
5190e02119d5SChris Mason 	u32 nritems;
51910b86a832SChris Mason 	int ret;
51920b86a832SChris Mason 
51930b86a832SChris Mason 	while (1) {
51940b86a832SChris Mason 		if (path->slots[0] == 0) {
5195b4ce94deSChris Mason 			btrfs_set_path_blocking(path);
51960b86a832SChris Mason 			ret = btrfs_prev_leaf(root, path);
51970b86a832SChris Mason 			if (ret != 0)
51980b86a832SChris Mason 				return ret;
51990b86a832SChris Mason 		} else {
52000b86a832SChris Mason 			path->slots[0]--;
52010b86a832SChris Mason 		}
52020b86a832SChris Mason 		leaf = path->nodes[0];
5203e02119d5SChris Mason 		nritems = btrfs_header_nritems(leaf);
5204e02119d5SChris Mason 		if (nritems == 0)
5205e02119d5SChris Mason 			return 1;
5206e02119d5SChris Mason 		if (path->slots[0] == nritems)
5207e02119d5SChris Mason 			path->slots[0]--;
5208e02119d5SChris Mason 
52090b86a832SChris Mason 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5210e02119d5SChris Mason 		if (found_key.objectid < min_objectid)
5211e02119d5SChris Mason 			break;
52120a4eefbbSYan Zheng 		if (found_key.type == type)
52130a4eefbbSYan Zheng 			return 0;
5214e02119d5SChris Mason 		if (found_key.objectid == min_objectid &&
5215e02119d5SChris Mason 		    found_key.type < type)
5216e02119d5SChris Mason 			break;
52170b86a832SChris Mason 	}
52180b86a832SChris Mason 	return 1;
52190b86a832SChris Mason }
5220