xref: /openbmc/linux/fs/btrfs/ctree.c (revision 28da9fb4467f7a650cd31af6dfad3a4e4a3abf6e)
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 		/*
1027*28da9fb4SJan Schmidt 		 * if there are no tree operation for the oldest root, we simply
1028*28da9fb4SJan Schmidt 		 * return it. this should only happen if that (old) root is at
1029*28da9fb4SJan Schmidt 		 * level 0.
10305d9e75c4SJan Schmidt 		 */
1031*28da9fb4SJan Schmidt 		if (!tm)
1032*28da9fb4SJan Schmidt 			break;
10335d9e75c4SJan Schmidt 
1034*28da9fb4SJan Schmidt 		/*
1035*28da9fb4SJan Schmidt 		 * if there's an operation that's not a root replacement, we
1036*28da9fb4SJan Schmidt 		 * found the oldest version of our root. normally, we'll find a
1037*28da9fb4SJan Schmidt 		 * MOD_LOG_KEY_REMOVE_WHILE_FREEING operation here.
1038*28da9fb4SJan 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:
10975d9e75c4SJan Schmidt 			if (tm->slot != n - 1) {
10985d9e75c4SJan Schmidt 				o_dst = btrfs_node_key_ptr_offset(tm->slot);
10995d9e75c4SJan Schmidt 				o_src = btrfs_node_key_ptr_offset(tm->slot + 1);
11005d9e75c4SJan Schmidt 				memmove_extent_buffer(eb, o_dst, o_src, p_size);
11015d9e75c4SJan Schmidt 			}
11025d9e75c4SJan Schmidt 			n--;
11035d9e75c4SJan Schmidt 			break;
11045d9e75c4SJan Schmidt 		case MOD_LOG_MOVE_KEYS:
1105c3193108SJan Schmidt 			o_dst = btrfs_node_key_ptr_offset(tm->slot);
1106c3193108SJan Schmidt 			o_src = btrfs_node_key_ptr_offset(tm->move.dst_slot);
1107c3193108SJan Schmidt 			memmove_extent_buffer(eb, o_dst, o_src,
11085d9e75c4SJan Schmidt 					      tm->move.nr_items * p_size);
11095d9e75c4SJan Schmidt 			break;
11105d9e75c4SJan Schmidt 		case MOD_LOG_ROOT_REPLACE:
11115d9e75c4SJan Schmidt 			/*
11125d9e75c4SJan Schmidt 			 * this operation is special. for roots, this must be
11135d9e75c4SJan Schmidt 			 * handled explicitly before rewinding.
11145d9e75c4SJan Schmidt 			 * for non-roots, this operation may exist if the node
11155d9e75c4SJan Schmidt 			 * was a root: root A -> child B; then A gets empty and
11165d9e75c4SJan Schmidt 			 * B is promoted to the new root. in the mod log, we'll
11175d9e75c4SJan Schmidt 			 * have a root-replace operation for B, a tree block
11185d9e75c4SJan Schmidt 			 * that is no root. we simply ignore that operation.
11195d9e75c4SJan Schmidt 			 */
11205d9e75c4SJan Schmidt 			break;
11215d9e75c4SJan Schmidt 		}
11225d9e75c4SJan Schmidt 		next = rb_next(&tm->node);
11235d9e75c4SJan Schmidt 		if (!next)
11245d9e75c4SJan Schmidt 			break;
11255d9e75c4SJan Schmidt 		tm = container_of(next, struct tree_mod_elem, node);
11265d9e75c4SJan Schmidt 		if (tm->index != first_tm->index)
11275d9e75c4SJan Schmidt 			break;
11285d9e75c4SJan Schmidt 	}
11295d9e75c4SJan Schmidt 	btrfs_set_header_nritems(eb, n);
11305d9e75c4SJan Schmidt }
11315d9e75c4SJan Schmidt 
11325d9e75c4SJan Schmidt static struct extent_buffer *
11335d9e75c4SJan Schmidt tree_mod_log_rewind(struct btrfs_fs_info *fs_info, struct extent_buffer *eb,
11345d9e75c4SJan Schmidt 		    u64 time_seq)
11355d9e75c4SJan Schmidt {
11365d9e75c4SJan Schmidt 	struct extent_buffer *eb_rewin;
11375d9e75c4SJan Schmidt 	struct tree_mod_elem *tm;
11385d9e75c4SJan Schmidt 
11395d9e75c4SJan Schmidt 	if (!time_seq)
11405d9e75c4SJan Schmidt 		return eb;
11415d9e75c4SJan Schmidt 
11425d9e75c4SJan Schmidt 	if (btrfs_header_level(eb) == 0)
11435d9e75c4SJan Schmidt 		return eb;
11445d9e75c4SJan Schmidt 
11455d9e75c4SJan Schmidt 	tm = tree_mod_log_search(fs_info, eb->start, time_seq);
11465d9e75c4SJan Schmidt 	if (!tm)
11475d9e75c4SJan Schmidt 		return eb;
11485d9e75c4SJan Schmidt 
11495d9e75c4SJan Schmidt 	if (tm->op == MOD_LOG_KEY_REMOVE_WHILE_FREEING) {
11505d9e75c4SJan Schmidt 		BUG_ON(tm->slot != 0);
11515d9e75c4SJan Schmidt 		eb_rewin = alloc_dummy_extent_buffer(eb->start,
11525d9e75c4SJan Schmidt 						fs_info->tree_root->nodesize);
11535d9e75c4SJan Schmidt 		BUG_ON(!eb_rewin);
11545d9e75c4SJan Schmidt 		btrfs_set_header_bytenr(eb_rewin, eb->start);
11555d9e75c4SJan Schmidt 		btrfs_set_header_backref_rev(eb_rewin,
11565d9e75c4SJan Schmidt 					     btrfs_header_backref_rev(eb));
11575d9e75c4SJan Schmidt 		btrfs_set_header_owner(eb_rewin, btrfs_header_owner(eb));
1158c3193108SJan Schmidt 		btrfs_set_header_level(eb_rewin, btrfs_header_level(eb));
11595d9e75c4SJan Schmidt 	} else {
11605d9e75c4SJan Schmidt 		eb_rewin = btrfs_clone_extent_buffer(eb);
11615d9e75c4SJan Schmidt 		BUG_ON(!eb_rewin);
11625d9e75c4SJan Schmidt 	}
11635d9e75c4SJan Schmidt 
11645d9e75c4SJan Schmidt 	extent_buffer_get(eb_rewin);
11655d9e75c4SJan Schmidt 	free_extent_buffer(eb);
11665d9e75c4SJan Schmidt 
11675d9e75c4SJan Schmidt 	__tree_mod_log_rewind(eb_rewin, time_seq, tm);
11685d9e75c4SJan Schmidt 
11695d9e75c4SJan Schmidt 	return eb_rewin;
11705d9e75c4SJan Schmidt }
11715d9e75c4SJan Schmidt 
11728ba97a15SJan Schmidt /*
11738ba97a15SJan Schmidt  * get_old_root() rewinds the state of @root's root node to the given @time_seq
11748ba97a15SJan Schmidt  * value. If there are no changes, the current root->root_node is returned. If
11758ba97a15SJan Schmidt  * anything changed in between, there's a fresh buffer allocated on which the
11768ba97a15SJan Schmidt  * rewind operations are done. In any case, the returned buffer is read locked.
11778ba97a15SJan Schmidt  * Returns NULL on error (with no locks held).
11788ba97a15SJan Schmidt  */
11795d9e75c4SJan Schmidt static inline struct extent_buffer *
11805d9e75c4SJan Schmidt get_old_root(struct btrfs_root *root, u64 time_seq)
11815d9e75c4SJan Schmidt {
11825d9e75c4SJan Schmidt 	struct tree_mod_elem *tm;
11835d9e75c4SJan Schmidt 	struct extent_buffer *eb;
1184a95236d9SJan Schmidt 	struct tree_mod_root *old_root = NULL;
11854325edd0SChris Mason 	u64 old_generation = 0;
1186a95236d9SJan Schmidt 	u64 logical;
11875d9e75c4SJan Schmidt 
11888ba97a15SJan Schmidt 	eb = btrfs_read_lock_root_node(root);
11895d9e75c4SJan Schmidt 	tm = __tree_mod_log_oldest_root(root->fs_info, root, time_seq);
11905d9e75c4SJan Schmidt 	if (!tm)
11915d9e75c4SJan Schmidt 		return root->node;
11925d9e75c4SJan Schmidt 
1193a95236d9SJan Schmidt 	if (tm->op == MOD_LOG_ROOT_REPLACE) {
11945d9e75c4SJan Schmidt 		old_root = &tm->old_root;
11955d9e75c4SJan Schmidt 		old_generation = tm->generation;
1196a95236d9SJan Schmidt 		logical = old_root->logical;
1197a95236d9SJan Schmidt 	} else {
1198a95236d9SJan Schmidt 		logical = root->node->start;
1199a95236d9SJan Schmidt 	}
12005d9e75c4SJan Schmidt 
1201a95236d9SJan Schmidt 	tm = tree_mod_log_search(root->fs_info, logical, time_seq);
1202a95236d9SJan Schmidt 	if (old_root)
1203*28da9fb4SJan Schmidt 		eb = alloc_dummy_extent_buffer(logical, root->nodesize);
1204a95236d9SJan Schmidt 	else
1205a95236d9SJan Schmidt 		eb = btrfs_clone_extent_buffer(root->node);
12068ba97a15SJan Schmidt 	btrfs_tree_read_unlock(root->node);
12078ba97a15SJan Schmidt 	free_extent_buffer(root->node);
12088ba97a15SJan Schmidt 	if (!eb)
12098ba97a15SJan Schmidt 		return NULL;
12108ba97a15SJan Schmidt 	btrfs_tree_read_lock(eb);
1211a95236d9SJan Schmidt 	if (old_root) {
12125d9e75c4SJan Schmidt 		btrfs_set_header_bytenr(eb, eb->start);
12135d9e75c4SJan Schmidt 		btrfs_set_header_backref_rev(eb, BTRFS_MIXED_BACKREF_REV);
12145d9e75c4SJan Schmidt 		btrfs_set_header_owner(eb, root->root_key.objectid);
12155d9e75c4SJan Schmidt 		btrfs_set_header_level(eb, old_root->level);
12165d9e75c4SJan Schmidt 		btrfs_set_header_generation(eb, old_generation);
1217a95236d9SJan Schmidt 	}
1218*28da9fb4SJan Schmidt 	if (tm)
12195d9e75c4SJan Schmidt 		__tree_mod_log_rewind(eb, time_seq, tm);
1220*28da9fb4SJan Schmidt 	else
1221*28da9fb4SJan Schmidt 		WARN_ON(btrfs_header_level(eb) != 0);
12228ba97a15SJan Schmidt 	extent_buffer_get(eb);
12235d9e75c4SJan Schmidt 
12245d9e75c4SJan Schmidt 	return eb;
12255d9e75c4SJan Schmidt }
12265d9e75c4SJan Schmidt 
12275d4f98a2SYan Zheng static inline int should_cow_block(struct btrfs_trans_handle *trans,
12285d4f98a2SYan Zheng 				   struct btrfs_root *root,
12295d4f98a2SYan Zheng 				   struct extent_buffer *buf)
12305d4f98a2SYan Zheng {
1231f1ebcc74SLiu Bo 	/* ensure we can see the force_cow */
1232f1ebcc74SLiu Bo 	smp_rmb();
1233f1ebcc74SLiu Bo 
1234f1ebcc74SLiu Bo 	/*
1235f1ebcc74SLiu Bo 	 * We do not need to cow a block if
1236f1ebcc74SLiu Bo 	 * 1) this block is not created or changed in this transaction;
1237f1ebcc74SLiu Bo 	 * 2) this block does not belong to TREE_RELOC tree;
1238f1ebcc74SLiu Bo 	 * 3) the root is not forced COW.
1239f1ebcc74SLiu Bo 	 *
1240f1ebcc74SLiu Bo 	 * What is forced COW:
1241f1ebcc74SLiu Bo 	 *    when we create snapshot during commiting the transaction,
1242f1ebcc74SLiu Bo 	 *    after we've finished coping src root, we must COW the shared
1243f1ebcc74SLiu Bo 	 *    block to ensure the metadata consistency.
1244f1ebcc74SLiu Bo 	 */
12455d4f98a2SYan Zheng 	if (btrfs_header_generation(buf) == trans->transid &&
12465d4f98a2SYan Zheng 	    !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN) &&
12475d4f98a2SYan Zheng 	    !(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
1248f1ebcc74SLiu Bo 	      btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)) &&
1249f1ebcc74SLiu Bo 	    !root->force_cow)
12505d4f98a2SYan Zheng 		return 0;
12515d4f98a2SYan Zheng 	return 1;
12525d4f98a2SYan Zheng }
12535d4f98a2SYan Zheng 
1254d352ac68SChris Mason /*
1255d352ac68SChris Mason  * cows a single block, see __btrfs_cow_block for the real work.
1256d352ac68SChris Mason  * This version of it has extra checks so that a block isn't cow'd more than
1257d352ac68SChris Mason  * once per transaction, as long as it hasn't been written yet
1258d352ac68SChris Mason  */
1259d397712bSChris Mason noinline int btrfs_cow_block(struct btrfs_trans_handle *trans,
12605f39d397SChris Mason 		    struct btrfs_root *root, struct extent_buffer *buf,
12615f39d397SChris Mason 		    struct extent_buffer *parent, int parent_slot,
12629fa8cfe7SChris Mason 		    struct extent_buffer **cow_ret)
126302217ed2SChris Mason {
12646702ed49SChris Mason 	u64 search_start;
1265f510cfecSChris Mason 	int ret;
1266dc17ff8fSChris Mason 
1267ccd467d6SChris Mason 	if (trans->transaction != root->fs_info->running_transaction) {
1268d397712bSChris Mason 		printk(KERN_CRIT "trans %llu running %llu\n",
1269d397712bSChris Mason 		       (unsigned long long)trans->transid,
1270d397712bSChris Mason 		       (unsigned long long)
1271ccd467d6SChris Mason 		       root->fs_info->running_transaction->transid);
1272ccd467d6SChris Mason 		WARN_ON(1);
1273ccd467d6SChris Mason 	}
1274ccd467d6SChris Mason 	if (trans->transid != root->fs_info->generation) {
1275d397712bSChris Mason 		printk(KERN_CRIT "trans %llu running %llu\n",
1276d397712bSChris Mason 		       (unsigned long long)trans->transid,
1277d397712bSChris Mason 		       (unsigned long long)root->fs_info->generation);
1278ccd467d6SChris Mason 		WARN_ON(1);
1279ccd467d6SChris Mason 	}
1280dc17ff8fSChris Mason 
12815d4f98a2SYan Zheng 	if (!should_cow_block(trans, root, buf)) {
128202217ed2SChris Mason 		*cow_ret = buf;
128302217ed2SChris Mason 		return 0;
128402217ed2SChris Mason 	}
1285c487685dSChris Mason 
12860b86a832SChris Mason 	search_start = buf->start & ~((u64)(1024 * 1024 * 1024) - 1);
1287b4ce94deSChris Mason 
1288b4ce94deSChris Mason 	if (parent)
1289b4ce94deSChris Mason 		btrfs_set_lock_blocking(parent);
1290b4ce94deSChris Mason 	btrfs_set_lock_blocking(buf);
1291b4ce94deSChris Mason 
1292f510cfecSChris Mason 	ret = __btrfs_cow_block(trans, root, buf, parent,
12939fa8cfe7SChris Mason 				 parent_slot, cow_ret, search_start, 0);
12941abe9b8aSliubo 
12951abe9b8aSliubo 	trace_btrfs_cow_block(root, buf, *cow_ret);
12961abe9b8aSliubo 
1297f510cfecSChris Mason 	return ret;
12982c90e5d6SChris Mason }
12996702ed49SChris Mason 
1300d352ac68SChris Mason /*
1301d352ac68SChris Mason  * helper function for defrag to decide if two blocks pointed to by a
1302d352ac68SChris Mason  * node are actually close by
1303d352ac68SChris Mason  */
13046b80053dSChris Mason static int close_blocks(u64 blocknr, u64 other, u32 blocksize)
13056702ed49SChris Mason {
13066b80053dSChris Mason 	if (blocknr < other && other - (blocknr + blocksize) < 32768)
13076702ed49SChris Mason 		return 1;
13086b80053dSChris Mason 	if (blocknr > other && blocknr - (other + blocksize) < 32768)
13096702ed49SChris Mason 		return 1;
131002217ed2SChris Mason 	return 0;
131102217ed2SChris Mason }
131202217ed2SChris Mason 
1313081e9573SChris Mason /*
1314081e9573SChris Mason  * compare two keys in a memcmp fashion
1315081e9573SChris Mason  */
1316081e9573SChris Mason static int comp_keys(struct btrfs_disk_key *disk, struct btrfs_key *k2)
1317081e9573SChris Mason {
1318081e9573SChris Mason 	struct btrfs_key k1;
1319081e9573SChris Mason 
1320081e9573SChris Mason 	btrfs_disk_key_to_cpu(&k1, disk);
1321081e9573SChris Mason 
132220736abaSDiego Calleja 	return btrfs_comp_cpu_keys(&k1, k2);
1323081e9573SChris Mason }
1324081e9573SChris Mason 
1325f3465ca4SJosef Bacik /*
1326f3465ca4SJosef Bacik  * same as comp_keys only with two btrfs_key's
1327f3465ca4SJosef Bacik  */
13285d4f98a2SYan Zheng int btrfs_comp_cpu_keys(struct btrfs_key *k1, struct btrfs_key *k2)
1329f3465ca4SJosef Bacik {
1330f3465ca4SJosef Bacik 	if (k1->objectid > k2->objectid)
1331f3465ca4SJosef Bacik 		return 1;
1332f3465ca4SJosef Bacik 	if (k1->objectid < k2->objectid)
1333f3465ca4SJosef Bacik 		return -1;
1334f3465ca4SJosef Bacik 	if (k1->type > k2->type)
1335f3465ca4SJosef Bacik 		return 1;
1336f3465ca4SJosef Bacik 	if (k1->type < k2->type)
1337f3465ca4SJosef Bacik 		return -1;
1338f3465ca4SJosef Bacik 	if (k1->offset > k2->offset)
1339f3465ca4SJosef Bacik 		return 1;
1340f3465ca4SJosef Bacik 	if (k1->offset < k2->offset)
1341f3465ca4SJosef Bacik 		return -1;
1342f3465ca4SJosef Bacik 	return 0;
1343f3465ca4SJosef Bacik }
1344081e9573SChris Mason 
1345d352ac68SChris Mason /*
1346d352ac68SChris Mason  * this is used by the defrag code to go through all the
1347d352ac68SChris Mason  * leaves pointed to by a node and reallocate them so that
1348d352ac68SChris Mason  * disk order is close to key order
1349d352ac68SChris Mason  */
13506702ed49SChris Mason int btrfs_realloc_node(struct btrfs_trans_handle *trans,
13515f39d397SChris Mason 		       struct btrfs_root *root, struct extent_buffer *parent,
1352a6b6e75eSChris Mason 		       int start_slot, int cache_only, u64 *last_ret,
1353a6b6e75eSChris Mason 		       struct btrfs_key *progress)
13546702ed49SChris Mason {
13556b80053dSChris Mason 	struct extent_buffer *cur;
13566702ed49SChris Mason 	u64 blocknr;
1357ca7a79adSChris Mason 	u64 gen;
1358e9d0b13bSChris Mason 	u64 search_start = *last_ret;
1359e9d0b13bSChris Mason 	u64 last_block = 0;
13606702ed49SChris Mason 	u64 other;
13616702ed49SChris Mason 	u32 parent_nritems;
13626702ed49SChris Mason 	int end_slot;
13636702ed49SChris Mason 	int i;
13646702ed49SChris Mason 	int err = 0;
1365f2183bdeSChris Mason 	int parent_level;
13666b80053dSChris Mason 	int uptodate;
13676b80053dSChris Mason 	u32 blocksize;
1368081e9573SChris Mason 	int progress_passed = 0;
1369081e9573SChris Mason 	struct btrfs_disk_key disk_key;
13706702ed49SChris Mason 
13715708b959SChris Mason 	parent_level = btrfs_header_level(parent);
13725708b959SChris Mason 	if (cache_only && parent_level != 1)
13735708b959SChris Mason 		return 0;
13745708b959SChris Mason 
1375d397712bSChris Mason 	if (trans->transaction != root->fs_info->running_transaction)
13766702ed49SChris Mason 		WARN_ON(1);
1377d397712bSChris Mason 	if (trans->transid != root->fs_info->generation)
13786702ed49SChris Mason 		WARN_ON(1);
137986479a04SChris Mason 
13806b80053dSChris Mason 	parent_nritems = btrfs_header_nritems(parent);
13816b80053dSChris Mason 	blocksize = btrfs_level_size(root, parent_level - 1);
13826702ed49SChris Mason 	end_slot = parent_nritems;
13836702ed49SChris Mason 
13846702ed49SChris Mason 	if (parent_nritems == 1)
13856702ed49SChris Mason 		return 0;
13866702ed49SChris Mason 
1387b4ce94deSChris Mason 	btrfs_set_lock_blocking(parent);
1388b4ce94deSChris Mason 
13896702ed49SChris Mason 	for (i = start_slot; i < end_slot; i++) {
13906702ed49SChris Mason 		int close = 1;
1391a6b6e75eSChris Mason 
1392081e9573SChris Mason 		btrfs_node_key(parent, &disk_key, i);
1393081e9573SChris Mason 		if (!progress_passed && comp_keys(&disk_key, progress) < 0)
1394081e9573SChris Mason 			continue;
1395081e9573SChris Mason 
1396081e9573SChris Mason 		progress_passed = 1;
13976b80053dSChris Mason 		blocknr = btrfs_node_blockptr(parent, i);
1398ca7a79adSChris Mason 		gen = btrfs_node_ptr_generation(parent, i);
1399e9d0b13bSChris Mason 		if (last_block == 0)
1400e9d0b13bSChris Mason 			last_block = blocknr;
14015708b959SChris Mason 
14026702ed49SChris Mason 		if (i > 0) {
14036b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i - 1);
14046b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
14056702ed49SChris Mason 		}
14060ef3e66bSChris Mason 		if (!close && i < end_slot - 2) {
14076b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i + 1);
14086b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
14096702ed49SChris Mason 		}
1410e9d0b13bSChris Mason 		if (close) {
1411e9d0b13bSChris Mason 			last_block = blocknr;
14126702ed49SChris Mason 			continue;
1413e9d0b13bSChris Mason 		}
14146702ed49SChris Mason 
14156b80053dSChris Mason 		cur = btrfs_find_tree_block(root, blocknr, blocksize);
14166b80053dSChris Mason 		if (cur)
1417b9fab919SChris Mason 			uptodate = btrfs_buffer_uptodate(cur, gen, 0);
14186b80053dSChris Mason 		else
14196b80053dSChris Mason 			uptodate = 0;
14205708b959SChris Mason 		if (!cur || !uptodate) {
14216702ed49SChris Mason 			if (cache_only) {
14226b80053dSChris Mason 				free_extent_buffer(cur);
14236702ed49SChris Mason 				continue;
14246702ed49SChris Mason 			}
14256b80053dSChris Mason 			if (!cur) {
14266b80053dSChris Mason 				cur = read_tree_block(root, blocknr,
1427ca7a79adSChris Mason 							 blocksize, gen);
142897d9a8a4STsutomu Itoh 				if (!cur)
142997d9a8a4STsutomu Itoh 					return -EIO;
14306b80053dSChris Mason 			} else if (!uptodate) {
1431018642a1STsutomu Itoh 				err = btrfs_read_buffer(cur, gen);
1432018642a1STsutomu Itoh 				if (err) {
1433018642a1STsutomu Itoh 					free_extent_buffer(cur);
1434018642a1STsutomu Itoh 					return err;
1435018642a1STsutomu Itoh 				}
14366702ed49SChris Mason 			}
1437f2183bdeSChris Mason 		}
1438e9d0b13bSChris Mason 		if (search_start == 0)
14396b80053dSChris Mason 			search_start = last_block;
1440e9d0b13bSChris Mason 
1441e7a84565SChris Mason 		btrfs_tree_lock(cur);
1442b4ce94deSChris Mason 		btrfs_set_lock_blocking(cur);
14436b80053dSChris Mason 		err = __btrfs_cow_block(trans, root, cur, parent, i,
1444e7a84565SChris Mason 					&cur, search_start,
14456b80053dSChris Mason 					min(16 * blocksize,
14469fa8cfe7SChris Mason 					    (end_slot - i) * blocksize));
1447252c38f0SYan 		if (err) {
1448e7a84565SChris Mason 			btrfs_tree_unlock(cur);
14496b80053dSChris Mason 			free_extent_buffer(cur);
14506702ed49SChris Mason 			break;
1451252c38f0SYan 		}
1452e7a84565SChris Mason 		search_start = cur->start;
1453e7a84565SChris Mason 		last_block = cur->start;
1454f2183bdeSChris Mason 		*last_ret = search_start;
1455e7a84565SChris Mason 		btrfs_tree_unlock(cur);
1456e7a84565SChris Mason 		free_extent_buffer(cur);
14576702ed49SChris Mason 	}
14586702ed49SChris Mason 	return err;
14596702ed49SChris Mason }
14606702ed49SChris Mason 
146174123bd7SChris Mason /*
146274123bd7SChris Mason  * The leaf data grows from end-to-front in the node.
146374123bd7SChris Mason  * this returns the address of the start of the last item,
146474123bd7SChris Mason  * which is the stop of the leaf data stack
146574123bd7SChris Mason  */
1466123abc88SChris Mason static inline unsigned int leaf_data_end(struct btrfs_root *root,
14675f39d397SChris Mason 					 struct extent_buffer *leaf)
1468be0e5c09SChris Mason {
14695f39d397SChris Mason 	u32 nr = btrfs_header_nritems(leaf);
1470be0e5c09SChris Mason 	if (nr == 0)
1471123abc88SChris Mason 		return BTRFS_LEAF_DATA_SIZE(root);
14725f39d397SChris Mason 	return btrfs_item_offset_nr(leaf, nr - 1);
1473be0e5c09SChris Mason }
1474be0e5c09SChris Mason 
1475aa5d6bedSChris Mason 
147674123bd7SChris Mason /*
14775f39d397SChris Mason  * search for key in the extent_buffer.  The items start at offset p,
14785f39d397SChris Mason  * and they are item_size apart.  There are 'max' items in p.
14795f39d397SChris Mason  *
148074123bd7SChris Mason  * the slot in the array is returned via slot, and it points to
148174123bd7SChris Mason  * the place where you would insert key if it is not found in
148274123bd7SChris Mason  * the array.
148374123bd7SChris Mason  *
148474123bd7SChris Mason  * slot may point to max if the key is bigger than all of the keys
148574123bd7SChris Mason  */
1486e02119d5SChris Mason static noinline int generic_bin_search(struct extent_buffer *eb,
1487e02119d5SChris Mason 				       unsigned long p,
14885f39d397SChris Mason 				       int item_size, struct btrfs_key *key,
1489be0e5c09SChris Mason 				       int max, int *slot)
1490be0e5c09SChris Mason {
1491be0e5c09SChris Mason 	int low = 0;
1492be0e5c09SChris Mason 	int high = max;
1493be0e5c09SChris Mason 	int mid;
1494be0e5c09SChris Mason 	int ret;
1495479965d6SChris Mason 	struct btrfs_disk_key *tmp = NULL;
14965f39d397SChris Mason 	struct btrfs_disk_key unaligned;
14975f39d397SChris Mason 	unsigned long offset;
14985f39d397SChris Mason 	char *kaddr = NULL;
14995f39d397SChris Mason 	unsigned long map_start = 0;
15005f39d397SChris Mason 	unsigned long map_len = 0;
1501479965d6SChris Mason 	int err;
1502be0e5c09SChris Mason 
1503be0e5c09SChris Mason 	while (low < high) {
1504be0e5c09SChris Mason 		mid = (low + high) / 2;
15055f39d397SChris Mason 		offset = p + mid * item_size;
15065f39d397SChris Mason 
1507a6591715SChris Mason 		if (!kaddr || offset < map_start ||
15085f39d397SChris Mason 		    (offset + sizeof(struct btrfs_disk_key)) >
15095f39d397SChris Mason 		    map_start + map_len) {
1510934d375bSChris Mason 
1511934d375bSChris Mason 			err = map_private_extent_buffer(eb, offset,
1512479965d6SChris Mason 						sizeof(struct btrfs_disk_key),
1513a6591715SChris Mason 						&kaddr, &map_start, &map_len);
15145f39d397SChris Mason 
1515479965d6SChris Mason 			if (!err) {
1516479965d6SChris Mason 				tmp = (struct btrfs_disk_key *)(kaddr + offset -
1517479965d6SChris Mason 							map_start);
1518479965d6SChris Mason 			} else {
15195f39d397SChris Mason 				read_extent_buffer(eb, &unaligned,
15205f39d397SChris Mason 						   offset, sizeof(unaligned));
15215f39d397SChris Mason 				tmp = &unaligned;
1522479965d6SChris Mason 			}
1523479965d6SChris Mason 
15245f39d397SChris Mason 		} else {
15255f39d397SChris Mason 			tmp = (struct btrfs_disk_key *)(kaddr + offset -
15265f39d397SChris Mason 							map_start);
15275f39d397SChris Mason 		}
1528be0e5c09SChris Mason 		ret = comp_keys(tmp, key);
1529be0e5c09SChris Mason 
1530be0e5c09SChris Mason 		if (ret < 0)
1531be0e5c09SChris Mason 			low = mid + 1;
1532be0e5c09SChris Mason 		else if (ret > 0)
1533be0e5c09SChris Mason 			high = mid;
1534be0e5c09SChris Mason 		else {
1535be0e5c09SChris Mason 			*slot = mid;
1536be0e5c09SChris Mason 			return 0;
1537be0e5c09SChris Mason 		}
1538be0e5c09SChris Mason 	}
1539be0e5c09SChris Mason 	*slot = low;
1540be0e5c09SChris Mason 	return 1;
1541be0e5c09SChris Mason }
1542be0e5c09SChris Mason 
154397571fd0SChris Mason /*
154497571fd0SChris Mason  * simple bin_search frontend that does the right thing for
154597571fd0SChris Mason  * leaves vs nodes
154697571fd0SChris Mason  */
15475f39d397SChris Mason static int bin_search(struct extent_buffer *eb, struct btrfs_key *key,
15485f39d397SChris Mason 		      int level, int *slot)
1549be0e5c09SChris Mason {
1550f775738fSWang Sheng-Hui 	if (level == 0)
15515f39d397SChris Mason 		return generic_bin_search(eb,
15525f39d397SChris Mason 					  offsetof(struct btrfs_leaf, items),
15530783fcfcSChris Mason 					  sizeof(struct btrfs_item),
15545f39d397SChris Mason 					  key, btrfs_header_nritems(eb),
15557518a238SChris Mason 					  slot);
1556f775738fSWang Sheng-Hui 	else
15575f39d397SChris Mason 		return generic_bin_search(eb,
15585f39d397SChris Mason 					  offsetof(struct btrfs_node, ptrs),
1559123abc88SChris Mason 					  sizeof(struct btrfs_key_ptr),
15605f39d397SChris Mason 					  key, btrfs_header_nritems(eb),
15617518a238SChris Mason 					  slot);
1562be0e5c09SChris Mason }
1563be0e5c09SChris Mason 
15645d4f98a2SYan Zheng int btrfs_bin_search(struct extent_buffer *eb, struct btrfs_key *key,
15655d4f98a2SYan Zheng 		     int level, int *slot)
15665d4f98a2SYan Zheng {
15675d4f98a2SYan Zheng 	return bin_search(eb, key, level, slot);
15685d4f98a2SYan Zheng }
15695d4f98a2SYan Zheng 
1570f0486c68SYan, Zheng static void root_add_used(struct btrfs_root *root, u32 size)
1571f0486c68SYan, Zheng {
1572f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
1573f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
1574f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) + size);
1575f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
1576f0486c68SYan, Zheng }
1577f0486c68SYan, Zheng 
1578f0486c68SYan, Zheng static void root_sub_used(struct btrfs_root *root, u32 size)
1579f0486c68SYan, Zheng {
1580f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
1581f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
1582f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) - size);
1583f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
1584f0486c68SYan, Zheng }
1585f0486c68SYan, Zheng 
1586d352ac68SChris Mason /* given a node and slot number, this reads the blocks it points to.  The
1587d352ac68SChris Mason  * extent buffer is returned with a reference taken (but unlocked).
1588d352ac68SChris Mason  * NULL is returned on error.
1589d352ac68SChris Mason  */
1590e02119d5SChris Mason static noinline struct extent_buffer *read_node_slot(struct btrfs_root *root,
15915f39d397SChris Mason 				   struct extent_buffer *parent, int slot)
1592bb803951SChris Mason {
1593ca7a79adSChris Mason 	int level = btrfs_header_level(parent);
1594bb803951SChris Mason 	if (slot < 0)
1595bb803951SChris Mason 		return NULL;
15965f39d397SChris Mason 	if (slot >= btrfs_header_nritems(parent))
1597bb803951SChris Mason 		return NULL;
1598ca7a79adSChris Mason 
1599ca7a79adSChris Mason 	BUG_ON(level == 0);
1600ca7a79adSChris Mason 
1601db94535dSChris Mason 	return read_tree_block(root, btrfs_node_blockptr(parent, slot),
1602ca7a79adSChris Mason 		       btrfs_level_size(root, level - 1),
1603ca7a79adSChris Mason 		       btrfs_node_ptr_generation(parent, slot));
1604bb803951SChris Mason }
1605bb803951SChris Mason 
1606d352ac68SChris Mason /*
1607d352ac68SChris Mason  * node level balancing, used to make sure nodes are in proper order for
1608d352ac68SChris Mason  * item deletion.  We balance from the top down, so we have to make sure
1609d352ac68SChris Mason  * that a deletion won't leave an node completely empty later on.
1610d352ac68SChris Mason  */
1611e02119d5SChris Mason static noinline int balance_level(struct btrfs_trans_handle *trans,
161298ed5174SChris Mason 			 struct btrfs_root *root,
161398ed5174SChris Mason 			 struct btrfs_path *path, int level)
1614bb803951SChris Mason {
16155f39d397SChris Mason 	struct extent_buffer *right = NULL;
16165f39d397SChris Mason 	struct extent_buffer *mid;
16175f39d397SChris Mason 	struct extent_buffer *left = NULL;
16185f39d397SChris Mason 	struct extent_buffer *parent = NULL;
1619bb803951SChris Mason 	int ret = 0;
1620bb803951SChris Mason 	int wret;
1621bb803951SChris Mason 	int pslot;
1622bb803951SChris Mason 	int orig_slot = path->slots[level];
162379f95c82SChris Mason 	u64 orig_ptr;
1624bb803951SChris Mason 
1625bb803951SChris Mason 	if (level == 0)
1626bb803951SChris Mason 		return 0;
1627bb803951SChris Mason 
16285f39d397SChris Mason 	mid = path->nodes[level];
1629b4ce94deSChris Mason 
1630bd681513SChris Mason 	WARN_ON(path->locks[level] != BTRFS_WRITE_LOCK &&
1631bd681513SChris Mason 		path->locks[level] != BTRFS_WRITE_LOCK_BLOCKING);
16327bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
16337bb86316SChris Mason 
16341d4f8a0cSChris Mason 	orig_ptr = btrfs_node_blockptr(mid, orig_slot);
163579f95c82SChris Mason 
1636a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
16375f39d397SChris Mason 		parent = path->nodes[level + 1];
1638bb803951SChris Mason 		pslot = path->slots[level + 1];
1639a05a9bb1SLi Zefan 	}
1640bb803951SChris Mason 
164140689478SChris Mason 	/*
164240689478SChris Mason 	 * deal with the case where there is only one pointer in the root
164340689478SChris Mason 	 * by promoting the node below to a root
164440689478SChris Mason 	 */
16455f39d397SChris Mason 	if (!parent) {
16465f39d397SChris Mason 		struct extent_buffer *child;
1647bb803951SChris Mason 
16485f39d397SChris Mason 		if (btrfs_header_nritems(mid) != 1)
1649bb803951SChris Mason 			return 0;
1650bb803951SChris Mason 
1651bb803951SChris Mason 		/* promote the child to a root */
16525f39d397SChris Mason 		child = read_node_slot(root, mid, 0);
1653305a26afSMark Fasheh 		if (!child) {
1654305a26afSMark Fasheh 			ret = -EROFS;
1655305a26afSMark Fasheh 			btrfs_std_error(root->fs_info, ret);
1656305a26afSMark Fasheh 			goto enospc;
1657305a26afSMark Fasheh 		}
1658305a26afSMark Fasheh 
1659925baeddSChris Mason 		btrfs_tree_lock(child);
1660b4ce94deSChris Mason 		btrfs_set_lock_blocking(child);
16619fa8cfe7SChris Mason 		ret = btrfs_cow_block(trans, root, child, mid, 0, &child);
1662f0486c68SYan, Zheng 		if (ret) {
1663f0486c68SYan, Zheng 			btrfs_tree_unlock(child);
1664f0486c68SYan, Zheng 			free_extent_buffer(child);
1665f0486c68SYan, Zheng 			goto enospc;
1666f0486c68SYan, Zheng 		}
16672f375ab9SYan 
1668f230475eSJan Schmidt 		tree_mod_log_set_root_pointer(root, child);
1669240f62c8SChris Mason 		rcu_assign_pointer(root->node, child);
1670925baeddSChris Mason 
16710b86a832SChris Mason 		add_root_to_dirty_list(root);
1672925baeddSChris Mason 		btrfs_tree_unlock(child);
1673b4ce94deSChris Mason 
1674925baeddSChris Mason 		path->locks[level] = 0;
1675bb803951SChris Mason 		path->nodes[level] = NULL;
16765f39d397SChris Mason 		clean_tree_block(trans, root, mid);
1677925baeddSChris Mason 		btrfs_tree_unlock(mid);
1678bb803951SChris Mason 		/* once for the path */
16795f39d397SChris Mason 		free_extent_buffer(mid);
1680f0486c68SYan, Zheng 
1681f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
16825581a51aSJan Schmidt 		btrfs_free_tree_block(trans, root, mid, 0, 1);
1683bb803951SChris Mason 		/* once for the root ptr */
16843083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
1685f0486c68SYan, Zheng 		return 0;
1686bb803951SChris Mason 	}
16875f39d397SChris Mason 	if (btrfs_header_nritems(mid) >
1688123abc88SChris Mason 	    BTRFS_NODEPTRS_PER_BLOCK(root) / 4)
1689bb803951SChris Mason 		return 0;
1690bb803951SChris Mason 
16915f39d397SChris Mason 	left = read_node_slot(root, parent, pslot - 1);
16925f39d397SChris Mason 	if (left) {
1693925baeddSChris Mason 		btrfs_tree_lock(left);
1694b4ce94deSChris Mason 		btrfs_set_lock_blocking(left);
16955f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, left,
16969fa8cfe7SChris Mason 				       parent, pslot - 1, &left);
169754aa1f4dSChris Mason 		if (wret) {
169854aa1f4dSChris Mason 			ret = wret;
169954aa1f4dSChris Mason 			goto enospc;
170054aa1f4dSChris Mason 		}
17012cc58cf2SChris Mason 	}
17025f39d397SChris Mason 	right = read_node_slot(root, parent, pslot + 1);
17035f39d397SChris Mason 	if (right) {
1704925baeddSChris Mason 		btrfs_tree_lock(right);
1705b4ce94deSChris Mason 		btrfs_set_lock_blocking(right);
17065f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, right,
17079fa8cfe7SChris Mason 				       parent, pslot + 1, &right);
17082cc58cf2SChris Mason 		if (wret) {
17092cc58cf2SChris Mason 			ret = wret;
17102cc58cf2SChris Mason 			goto enospc;
17112cc58cf2SChris Mason 		}
17122cc58cf2SChris Mason 	}
17132cc58cf2SChris Mason 
17142cc58cf2SChris Mason 	/* first, try to make some room in the middle buffer */
17155f39d397SChris Mason 	if (left) {
17165f39d397SChris Mason 		orig_slot += btrfs_header_nritems(left);
1717bce4eae9SChris Mason 		wret = push_node_left(trans, root, left, mid, 1);
171879f95c82SChris Mason 		if (wret < 0)
171979f95c82SChris Mason 			ret = wret;
1720bb803951SChris Mason 	}
172179f95c82SChris Mason 
172279f95c82SChris Mason 	/*
172379f95c82SChris Mason 	 * then try to empty the right most buffer into the middle
172479f95c82SChris Mason 	 */
17255f39d397SChris Mason 	if (right) {
1726971a1f66SChris Mason 		wret = push_node_left(trans, root, mid, right, 1);
172754aa1f4dSChris Mason 		if (wret < 0 && wret != -ENOSPC)
172879f95c82SChris Mason 			ret = wret;
17295f39d397SChris Mason 		if (btrfs_header_nritems(right) == 0) {
17305f39d397SChris Mason 			clean_tree_block(trans, root, right);
1731925baeddSChris Mason 			btrfs_tree_unlock(right);
1732f3ea38daSJan Schmidt 			del_ptr(trans, root, path, level + 1, pslot + 1, 1);
1733f0486c68SYan, Zheng 			root_sub_used(root, right->len);
17345581a51aSJan Schmidt 			btrfs_free_tree_block(trans, root, right, 0, 1);
17353083ee2eSJosef Bacik 			free_extent_buffer_stale(right);
1736f0486c68SYan, Zheng 			right = NULL;
1737bb803951SChris Mason 		} else {
17385f39d397SChris Mason 			struct btrfs_disk_key right_key;
17395f39d397SChris Mason 			btrfs_node_key(right, &right_key, 0);
1740f230475eSJan Schmidt 			tree_mod_log_set_node_key(root->fs_info, parent,
1741f230475eSJan Schmidt 						  &right_key, pslot + 1, 0);
17425f39d397SChris Mason 			btrfs_set_node_key(parent, &right_key, pslot + 1);
17435f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
1744bb803951SChris Mason 		}
1745bb803951SChris Mason 	}
17465f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 1) {
174779f95c82SChris Mason 		/*
174879f95c82SChris Mason 		 * we're not allowed to leave a node with one item in the
174979f95c82SChris Mason 		 * tree during a delete.  A deletion from lower in the tree
175079f95c82SChris Mason 		 * could try to delete the only pointer in this node.
175179f95c82SChris Mason 		 * So, pull some keys from the left.
175279f95c82SChris Mason 		 * There has to be a left pointer at this point because
175379f95c82SChris Mason 		 * otherwise we would have pulled some pointers from the
175479f95c82SChris Mason 		 * right
175579f95c82SChris Mason 		 */
1756305a26afSMark Fasheh 		if (!left) {
1757305a26afSMark Fasheh 			ret = -EROFS;
1758305a26afSMark Fasheh 			btrfs_std_error(root->fs_info, ret);
1759305a26afSMark Fasheh 			goto enospc;
1760305a26afSMark Fasheh 		}
17615f39d397SChris Mason 		wret = balance_node_right(trans, root, mid, left);
176254aa1f4dSChris Mason 		if (wret < 0) {
176379f95c82SChris Mason 			ret = wret;
176454aa1f4dSChris Mason 			goto enospc;
176554aa1f4dSChris Mason 		}
1766bce4eae9SChris Mason 		if (wret == 1) {
1767bce4eae9SChris Mason 			wret = push_node_left(trans, root, left, mid, 1);
1768bce4eae9SChris Mason 			if (wret < 0)
1769bce4eae9SChris Mason 				ret = wret;
1770bce4eae9SChris Mason 		}
177179f95c82SChris Mason 		BUG_ON(wret == 1);
177279f95c82SChris Mason 	}
17735f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 0) {
17745f39d397SChris Mason 		clean_tree_block(trans, root, mid);
1775925baeddSChris Mason 		btrfs_tree_unlock(mid);
1776f3ea38daSJan Schmidt 		del_ptr(trans, root, path, level + 1, pslot, 1);
1777f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
17785581a51aSJan Schmidt 		btrfs_free_tree_block(trans, root, mid, 0, 1);
17793083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
1780f0486c68SYan, Zheng 		mid = NULL;
178179f95c82SChris Mason 	} else {
178279f95c82SChris Mason 		/* update the parent key to reflect our changes */
17835f39d397SChris Mason 		struct btrfs_disk_key mid_key;
17845f39d397SChris Mason 		btrfs_node_key(mid, &mid_key, 0);
1785f230475eSJan Schmidt 		tree_mod_log_set_node_key(root->fs_info, parent, &mid_key,
1786f230475eSJan Schmidt 					  pslot, 0);
17875f39d397SChris Mason 		btrfs_set_node_key(parent, &mid_key, pslot);
17885f39d397SChris Mason 		btrfs_mark_buffer_dirty(parent);
178979f95c82SChris Mason 	}
1790bb803951SChris Mason 
179179f95c82SChris Mason 	/* update the path */
17925f39d397SChris Mason 	if (left) {
17935f39d397SChris Mason 		if (btrfs_header_nritems(left) > orig_slot) {
17945f39d397SChris Mason 			extent_buffer_get(left);
1795925baeddSChris Mason 			/* left was locked after cow */
17965f39d397SChris Mason 			path->nodes[level] = left;
1797bb803951SChris Mason 			path->slots[level + 1] -= 1;
1798bb803951SChris Mason 			path->slots[level] = orig_slot;
1799925baeddSChris Mason 			if (mid) {
1800925baeddSChris Mason 				btrfs_tree_unlock(mid);
18015f39d397SChris Mason 				free_extent_buffer(mid);
1802925baeddSChris Mason 			}
1803bb803951SChris Mason 		} else {
18045f39d397SChris Mason 			orig_slot -= btrfs_header_nritems(left);
1805bb803951SChris Mason 			path->slots[level] = orig_slot;
1806bb803951SChris Mason 		}
1807bb803951SChris Mason 	}
180879f95c82SChris Mason 	/* double check we haven't messed things up */
1809e20d96d6SChris Mason 	if (orig_ptr !=
18105f39d397SChris Mason 	    btrfs_node_blockptr(path->nodes[level], path->slots[level]))
181179f95c82SChris Mason 		BUG();
181254aa1f4dSChris Mason enospc:
1813925baeddSChris Mason 	if (right) {
1814925baeddSChris Mason 		btrfs_tree_unlock(right);
18155f39d397SChris Mason 		free_extent_buffer(right);
1816925baeddSChris Mason 	}
1817925baeddSChris Mason 	if (left) {
1818925baeddSChris Mason 		if (path->nodes[level] != left)
1819925baeddSChris Mason 			btrfs_tree_unlock(left);
18205f39d397SChris Mason 		free_extent_buffer(left);
1821925baeddSChris Mason 	}
1822bb803951SChris Mason 	return ret;
1823bb803951SChris Mason }
1824bb803951SChris Mason 
1825d352ac68SChris Mason /* Node balancing for insertion.  Here we only split or push nodes around
1826d352ac68SChris Mason  * when they are completely full.  This is also done top down, so we
1827d352ac68SChris Mason  * have to be pessimistic.
1828d352ac68SChris Mason  */
1829d397712bSChris Mason static noinline int push_nodes_for_insert(struct btrfs_trans_handle *trans,
1830e66f709bSChris Mason 					  struct btrfs_root *root,
1831e66f709bSChris Mason 					  struct btrfs_path *path, int level)
1832e66f709bSChris Mason {
18335f39d397SChris Mason 	struct extent_buffer *right = NULL;
18345f39d397SChris Mason 	struct extent_buffer *mid;
18355f39d397SChris Mason 	struct extent_buffer *left = NULL;
18365f39d397SChris Mason 	struct extent_buffer *parent = NULL;
1837e66f709bSChris Mason 	int ret = 0;
1838e66f709bSChris Mason 	int wret;
1839e66f709bSChris Mason 	int pslot;
1840e66f709bSChris Mason 	int orig_slot = path->slots[level];
1841e66f709bSChris Mason 
1842e66f709bSChris Mason 	if (level == 0)
1843e66f709bSChris Mason 		return 1;
1844e66f709bSChris Mason 
18455f39d397SChris Mason 	mid = path->nodes[level];
18467bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
1847e66f709bSChris Mason 
1848a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
18495f39d397SChris Mason 		parent = path->nodes[level + 1];
1850e66f709bSChris Mason 		pslot = path->slots[level + 1];
1851a05a9bb1SLi Zefan 	}
1852e66f709bSChris Mason 
18535f39d397SChris Mason 	if (!parent)
1854e66f709bSChris Mason 		return 1;
1855e66f709bSChris Mason 
18565f39d397SChris Mason 	left = read_node_slot(root, parent, pslot - 1);
1857e66f709bSChris Mason 
1858e66f709bSChris Mason 	/* first, try to make some room in the middle buffer */
18595f39d397SChris Mason 	if (left) {
1860e66f709bSChris Mason 		u32 left_nr;
1861925baeddSChris Mason 
1862925baeddSChris Mason 		btrfs_tree_lock(left);
1863b4ce94deSChris Mason 		btrfs_set_lock_blocking(left);
1864b4ce94deSChris Mason 
18655f39d397SChris Mason 		left_nr = btrfs_header_nritems(left);
186633ade1f8SChris Mason 		if (left_nr >= BTRFS_NODEPTRS_PER_BLOCK(root) - 1) {
186733ade1f8SChris Mason 			wret = 1;
186833ade1f8SChris Mason 		} else {
18695f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, left, parent,
18709fa8cfe7SChris Mason 					      pslot - 1, &left);
187154aa1f4dSChris Mason 			if (ret)
187254aa1f4dSChris Mason 				wret = 1;
187354aa1f4dSChris Mason 			else {
187454aa1f4dSChris Mason 				wret = push_node_left(trans, root,
1875971a1f66SChris Mason 						      left, mid, 0);
187654aa1f4dSChris Mason 			}
187733ade1f8SChris Mason 		}
1878e66f709bSChris Mason 		if (wret < 0)
1879e66f709bSChris Mason 			ret = wret;
1880e66f709bSChris Mason 		if (wret == 0) {
18815f39d397SChris Mason 			struct btrfs_disk_key disk_key;
1882e66f709bSChris Mason 			orig_slot += left_nr;
18835f39d397SChris Mason 			btrfs_node_key(mid, &disk_key, 0);
1884f230475eSJan Schmidt 			tree_mod_log_set_node_key(root->fs_info, parent,
1885f230475eSJan Schmidt 						  &disk_key, pslot, 0);
18865f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot);
18875f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
18885f39d397SChris Mason 			if (btrfs_header_nritems(left) > orig_slot) {
18895f39d397SChris Mason 				path->nodes[level] = left;
1890e66f709bSChris Mason 				path->slots[level + 1] -= 1;
1891e66f709bSChris Mason 				path->slots[level] = orig_slot;
1892925baeddSChris Mason 				btrfs_tree_unlock(mid);
18935f39d397SChris Mason 				free_extent_buffer(mid);
1894e66f709bSChris Mason 			} else {
1895e66f709bSChris Mason 				orig_slot -=
18965f39d397SChris Mason 					btrfs_header_nritems(left);
1897e66f709bSChris Mason 				path->slots[level] = orig_slot;
1898925baeddSChris Mason 				btrfs_tree_unlock(left);
18995f39d397SChris Mason 				free_extent_buffer(left);
1900e66f709bSChris Mason 			}
1901e66f709bSChris Mason 			return 0;
1902e66f709bSChris Mason 		}
1903925baeddSChris Mason 		btrfs_tree_unlock(left);
19045f39d397SChris Mason 		free_extent_buffer(left);
1905e66f709bSChris Mason 	}
19065f39d397SChris Mason 	right = read_node_slot(root, parent, pslot + 1);
1907e66f709bSChris Mason 
1908e66f709bSChris Mason 	/*
1909e66f709bSChris Mason 	 * then try to empty the right most buffer into the middle
1910e66f709bSChris Mason 	 */
19115f39d397SChris Mason 	if (right) {
191233ade1f8SChris Mason 		u32 right_nr;
1913b4ce94deSChris Mason 
1914925baeddSChris Mason 		btrfs_tree_lock(right);
1915b4ce94deSChris Mason 		btrfs_set_lock_blocking(right);
1916b4ce94deSChris Mason 
19175f39d397SChris Mason 		right_nr = btrfs_header_nritems(right);
191833ade1f8SChris Mason 		if (right_nr >= BTRFS_NODEPTRS_PER_BLOCK(root) - 1) {
191933ade1f8SChris Mason 			wret = 1;
192033ade1f8SChris Mason 		} else {
19215f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, right,
19225f39d397SChris Mason 					      parent, pslot + 1,
19239fa8cfe7SChris Mason 					      &right);
192454aa1f4dSChris Mason 			if (ret)
192554aa1f4dSChris Mason 				wret = 1;
192654aa1f4dSChris Mason 			else {
192733ade1f8SChris Mason 				wret = balance_node_right(trans, root,
19285f39d397SChris Mason 							  right, mid);
192933ade1f8SChris Mason 			}
193054aa1f4dSChris Mason 		}
1931e66f709bSChris Mason 		if (wret < 0)
1932e66f709bSChris Mason 			ret = wret;
1933e66f709bSChris Mason 		if (wret == 0) {
19345f39d397SChris Mason 			struct btrfs_disk_key disk_key;
19355f39d397SChris Mason 
19365f39d397SChris Mason 			btrfs_node_key(right, &disk_key, 0);
1937f230475eSJan Schmidt 			tree_mod_log_set_node_key(root->fs_info, parent,
1938f230475eSJan Schmidt 						  &disk_key, pslot + 1, 0);
19395f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot + 1);
19405f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
19415f39d397SChris Mason 
19425f39d397SChris Mason 			if (btrfs_header_nritems(mid) <= orig_slot) {
19435f39d397SChris Mason 				path->nodes[level] = right;
1944e66f709bSChris Mason 				path->slots[level + 1] += 1;
1945e66f709bSChris Mason 				path->slots[level] = orig_slot -
19465f39d397SChris Mason 					btrfs_header_nritems(mid);
1947925baeddSChris Mason 				btrfs_tree_unlock(mid);
19485f39d397SChris Mason 				free_extent_buffer(mid);
1949e66f709bSChris Mason 			} else {
1950925baeddSChris Mason 				btrfs_tree_unlock(right);
19515f39d397SChris Mason 				free_extent_buffer(right);
1952e66f709bSChris Mason 			}
1953e66f709bSChris Mason 			return 0;
1954e66f709bSChris Mason 		}
1955925baeddSChris Mason 		btrfs_tree_unlock(right);
19565f39d397SChris Mason 		free_extent_buffer(right);
1957e66f709bSChris Mason 	}
1958e66f709bSChris Mason 	return 1;
1959e66f709bSChris Mason }
1960e66f709bSChris Mason 
196174123bd7SChris Mason /*
1962d352ac68SChris Mason  * readahead one full node of leaves, finding things that are close
1963d352ac68SChris Mason  * to the block in 'slot', and triggering ra on them.
19643c69faecSChris Mason  */
1965c8c42864SChris Mason static void reada_for_search(struct btrfs_root *root,
1966e02119d5SChris Mason 			     struct btrfs_path *path,
196701f46658SChris Mason 			     int level, int slot, u64 objectid)
19683c69faecSChris Mason {
19695f39d397SChris Mason 	struct extent_buffer *node;
197001f46658SChris Mason 	struct btrfs_disk_key disk_key;
19713c69faecSChris Mason 	u32 nritems;
19723c69faecSChris Mason 	u64 search;
1973a7175319SChris Mason 	u64 target;
19746b80053dSChris Mason 	u64 nread = 0;
1975cb25c2eaSJosef Bacik 	u64 gen;
19763c69faecSChris Mason 	int direction = path->reada;
19775f39d397SChris Mason 	struct extent_buffer *eb;
19786b80053dSChris Mason 	u32 nr;
19796b80053dSChris Mason 	u32 blocksize;
19806b80053dSChris Mason 	u32 nscan = 0;
1981db94535dSChris Mason 
1982a6b6e75eSChris Mason 	if (level != 1)
19833c69faecSChris Mason 		return;
19843c69faecSChris Mason 
19856702ed49SChris Mason 	if (!path->nodes[level])
19866702ed49SChris Mason 		return;
19876702ed49SChris Mason 
19885f39d397SChris Mason 	node = path->nodes[level];
1989925baeddSChris Mason 
19903c69faecSChris Mason 	search = btrfs_node_blockptr(node, slot);
19916b80053dSChris Mason 	blocksize = btrfs_level_size(root, level - 1);
19926b80053dSChris Mason 	eb = btrfs_find_tree_block(root, search, blocksize);
19935f39d397SChris Mason 	if (eb) {
19945f39d397SChris Mason 		free_extent_buffer(eb);
19953c69faecSChris Mason 		return;
19963c69faecSChris Mason 	}
19973c69faecSChris Mason 
1998a7175319SChris Mason 	target = search;
19996b80053dSChris Mason 
20005f39d397SChris Mason 	nritems = btrfs_header_nritems(node);
20016b80053dSChris Mason 	nr = slot;
200225b8b936SJosef Bacik 
20033c69faecSChris Mason 	while (1) {
20046b80053dSChris Mason 		if (direction < 0) {
20056b80053dSChris Mason 			if (nr == 0)
20063c69faecSChris Mason 				break;
20076b80053dSChris Mason 			nr--;
20086b80053dSChris Mason 		} else if (direction > 0) {
20096b80053dSChris Mason 			nr++;
20106b80053dSChris Mason 			if (nr >= nritems)
20116b80053dSChris Mason 				break;
20123c69faecSChris Mason 		}
201301f46658SChris Mason 		if (path->reada < 0 && objectid) {
201401f46658SChris Mason 			btrfs_node_key(node, &disk_key, nr);
201501f46658SChris Mason 			if (btrfs_disk_key_objectid(&disk_key) != objectid)
201601f46658SChris Mason 				break;
201701f46658SChris Mason 		}
20186b80053dSChris Mason 		search = btrfs_node_blockptr(node, nr);
2019a7175319SChris Mason 		if ((search <= target && target - search <= 65536) ||
2020a7175319SChris Mason 		    (search > target && search - target <= 65536)) {
2021cb25c2eaSJosef Bacik 			gen = btrfs_node_ptr_generation(node, nr);
2022cb25c2eaSJosef Bacik 			readahead_tree_block(root, search, blocksize, gen);
20236b80053dSChris Mason 			nread += blocksize;
20243c69faecSChris Mason 		}
20256b80053dSChris Mason 		nscan++;
2026a7175319SChris Mason 		if ((nread > 65536 || nscan > 32))
20276b80053dSChris Mason 			break;
20283c69faecSChris Mason 	}
20293c69faecSChris Mason }
2030925baeddSChris Mason 
2031d352ac68SChris Mason /*
2032b4ce94deSChris Mason  * returns -EAGAIN if it had to drop the path, or zero if everything was in
2033b4ce94deSChris Mason  * cache
2034b4ce94deSChris Mason  */
2035b4ce94deSChris Mason static noinline int reada_for_balance(struct btrfs_root *root,
2036b4ce94deSChris Mason 				      struct btrfs_path *path, int level)
2037b4ce94deSChris Mason {
2038b4ce94deSChris Mason 	int slot;
2039b4ce94deSChris Mason 	int nritems;
2040b4ce94deSChris Mason 	struct extent_buffer *parent;
2041b4ce94deSChris Mason 	struct extent_buffer *eb;
2042b4ce94deSChris Mason 	u64 gen;
2043b4ce94deSChris Mason 	u64 block1 = 0;
2044b4ce94deSChris Mason 	u64 block2 = 0;
2045b4ce94deSChris Mason 	int ret = 0;
2046b4ce94deSChris Mason 	int blocksize;
2047b4ce94deSChris Mason 
20488c594ea8SChris Mason 	parent = path->nodes[level + 1];
2049b4ce94deSChris Mason 	if (!parent)
2050b4ce94deSChris Mason 		return 0;
2051b4ce94deSChris Mason 
2052b4ce94deSChris Mason 	nritems = btrfs_header_nritems(parent);
20538c594ea8SChris Mason 	slot = path->slots[level + 1];
2054b4ce94deSChris Mason 	blocksize = btrfs_level_size(root, level);
2055b4ce94deSChris Mason 
2056b4ce94deSChris Mason 	if (slot > 0) {
2057b4ce94deSChris Mason 		block1 = btrfs_node_blockptr(parent, slot - 1);
2058b4ce94deSChris Mason 		gen = btrfs_node_ptr_generation(parent, slot - 1);
2059b4ce94deSChris Mason 		eb = btrfs_find_tree_block(root, block1, blocksize);
2060b9fab919SChris Mason 		/*
2061b9fab919SChris Mason 		 * if we get -eagain from btrfs_buffer_uptodate, we
2062b9fab919SChris Mason 		 * don't want to return eagain here.  That will loop
2063b9fab919SChris Mason 		 * forever
2064b9fab919SChris Mason 		 */
2065b9fab919SChris Mason 		if (eb && btrfs_buffer_uptodate(eb, gen, 1) != 0)
2066b4ce94deSChris Mason 			block1 = 0;
2067b4ce94deSChris Mason 		free_extent_buffer(eb);
2068b4ce94deSChris Mason 	}
20698c594ea8SChris Mason 	if (slot + 1 < nritems) {
2070b4ce94deSChris Mason 		block2 = btrfs_node_blockptr(parent, slot + 1);
2071b4ce94deSChris Mason 		gen = btrfs_node_ptr_generation(parent, slot + 1);
2072b4ce94deSChris Mason 		eb = btrfs_find_tree_block(root, block2, blocksize);
2073b9fab919SChris Mason 		if (eb && btrfs_buffer_uptodate(eb, gen, 1) != 0)
2074b4ce94deSChris Mason 			block2 = 0;
2075b4ce94deSChris Mason 		free_extent_buffer(eb);
2076b4ce94deSChris Mason 	}
2077b4ce94deSChris Mason 	if (block1 || block2) {
2078b4ce94deSChris Mason 		ret = -EAGAIN;
20798c594ea8SChris Mason 
20808c594ea8SChris Mason 		/* release the whole path */
2081b3b4aa74SDavid Sterba 		btrfs_release_path(path);
20828c594ea8SChris Mason 
20838c594ea8SChris Mason 		/* read the blocks */
2084b4ce94deSChris Mason 		if (block1)
2085b4ce94deSChris Mason 			readahead_tree_block(root, block1, blocksize, 0);
2086b4ce94deSChris Mason 		if (block2)
2087b4ce94deSChris Mason 			readahead_tree_block(root, block2, blocksize, 0);
2088b4ce94deSChris Mason 
2089b4ce94deSChris Mason 		if (block1) {
2090b4ce94deSChris Mason 			eb = read_tree_block(root, block1, blocksize, 0);
2091b4ce94deSChris Mason 			free_extent_buffer(eb);
2092b4ce94deSChris Mason 		}
20938c594ea8SChris Mason 		if (block2) {
2094b4ce94deSChris Mason 			eb = read_tree_block(root, block2, blocksize, 0);
2095b4ce94deSChris Mason 			free_extent_buffer(eb);
2096b4ce94deSChris Mason 		}
2097b4ce94deSChris Mason 	}
2098b4ce94deSChris Mason 	return ret;
2099b4ce94deSChris Mason }
2100b4ce94deSChris Mason 
2101b4ce94deSChris Mason 
2102b4ce94deSChris Mason /*
2103d397712bSChris Mason  * when we walk down the tree, it is usually safe to unlock the higher layers
2104d397712bSChris Mason  * in the tree.  The exceptions are when our path goes through slot 0, because
2105d397712bSChris Mason  * operations on the tree might require changing key pointers higher up in the
2106d397712bSChris Mason  * tree.
2107d352ac68SChris Mason  *
2108d397712bSChris Mason  * callers might also have set path->keep_locks, which tells this code to keep
2109d397712bSChris Mason  * the lock if the path points to the last slot in the block.  This is part of
2110d397712bSChris Mason  * walking through the tree, and selecting the next slot in the higher block.
2111d352ac68SChris Mason  *
2112d397712bSChris Mason  * lowest_unlock sets the lowest level in the tree we're allowed to unlock.  so
2113d397712bSChris Mason  * if lowest_unlock is 1, level 0 won't be unlocked
2114d352ac68SChris Mason  */
2115e02119d5SChris Mason static noinline void unlock_up(struct btrfs_path *path, int level,
2116f7c79f30SChris Mason 			       int lowest_unlock, int min_write_lock_level,
2117f7c79f30SChris Mason 			       int *write_lock_level)
2118925baeddSChris Mason {
2119925baeddSChris Mason 	int i;
2120925baeddSChris Mason 	int skip_level = level;
2121051e1b9fSChris Mason 	int no_skips = 0;
2122925baeddSChris Mason 	struct extent_buffer *t;
2123925baeddSChris Mason 
2124925baeddSChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2125925baeddSChris Mason 		if (!path->nodes[i])
2126925baeddSChris Mason 			break;
2127925baeddSChris Mason 		if (!path->locks[i])
2128925baeddSChris Mason 			break;
2129051e1b9fSChris Mason 		if (!no_skips && path->slots[i] == 0) {
2130925baeddSChris Mason 			skip_level = i + 1;
2131925baeddSChris Mason 			continue;
2132925baeddSChris Mason 		}
2133051e1b9fSChris Mason 		if (!no_skips && path->keep_locks) {
2134925baeddSChris Mason 			u32 nritems;
2135925baeddSChris Mason 			t = path->nodes[i];
2136925baeddSChris Mason 			nritems = btrfs_header_nritems(t);
2137051e1b9fSChris Mason 			if (nritems < 1 || path->slots[i] >= nritems - 1) {
2138925baeddSChris Mason 				skip_level = i + 1;
2139925baeddSChris Mason 				continue;
2140925baeddSChris Mason 			}
2141925baeddSChris Mason 		}
2142051e1b9fSChris Mason 		if (skip_level < i && i >= lowest_unlock)
2143051e1b9fSChris Mason 			no_skips = 1;
2144051e1b9fSChris Mason 
2145925baeddSChris Mason 		t = path->nodes[i];
2146925baeddSChris Mason 		if (i >= lowest_unlock && i > skip_level && path->locks[i]) {
2147bd681513SChris Mason 			btrfs_tree_unlock_rw(t, path->locks[i]);
2148925baeddSChris Mason 			path->locks[i] = 0;
2149f7c79f30SChris Mason 			if (write_lock_level &&
2150f7c79f30SChris Mason 			    i > min_write_lock_level &&
2151f7c79f30SChris Mason 			    i <= *write_lock_level) {
2152f7c79f30SChris Mason 				*write_lock_level = i - 1;
2153f7c79f30SChris Mason 			}
2154925baeddSChris Mason 		}
2155925baeddSChris Mason 	}
2156925baeddSChris Mason }
2157925baeddSChris Mason 
21583c69faecSChris Mason /*
2159b4ce94deSChris Mason  * This releases any locks held in the path starting at level and
2160b4ce94deSChris Mason  * going all the way up to the root.
2161b4ce94deSChris Mason  *
2162b4ce94deSChris Mason  * btrfs_search_slot will keep the lock held on higher nodes in a few
2163b4ce94deSChris Mason  * corner cases, such as COW of the block at slot zero in the node.  This
2164b4ce94deSChris Mason  * ignores those rules, and it should only be called when there are no
2165b4ce94deSChris Mason  * more updates to be done higher up in the tree.
2166b4ce94deSChris Mason  */
2167b4ce94deSChris Mason noinline void btrfs_unlock_up_safe(struct btrfs_path *path, int level)
2168b4ce94deSChris Mason {
2169b4ce94deSChris Mason 	int i;
2170b4ce94deSChris Mason 
21715d4f98a2SYan Zheng 	if (path->keep_locks)
2172b4ce94deSChris Mason 		return;
2173b4ce94deSChris Mason 
2174b4ce94deSChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2175b4ce94deSChris Mason 		if (!path->nodes[i])
217612f4daccSChris Mason 			continue;
2177b4ce94deSChris Mason 		if (!path->locks[i])
217812f4daccSChris Mason 			continue;
2179bd681513SChris Mason 		btrfs_tree_unlock_rw(path->nodes[i], path->locks[i]);
2180b4ce94deSChris Mason 		path->locks[i] = 0;
2181b4ce94deSChris Mason 	}
2182b4ce94deSChris Mason }
2183b4ce94deSChris Mason 
2184b4ce94deSChris Mason /*
2185c8c42864SChris Mason  * helper function for btrfs_search_slot.  The goal is to find a block
2186c8c42864SChris Mason  * in cache without setting the path to blocking.  If we find the block
2187c8c42864SChris Mason  * we return zero and the path is unchanged.
2188c8c42864SChris Mason  *
2189c8c42864SChris Mason  * If we can't find the block, we set the path blocking and do some
2190c8c42864SChris Mason  * reada.  -EAGAIN is returned and the search must be repeated.
2191c8c42864SChris Mason  */
2192c8c42864SChris Mason static int
2193c8c42864SChris Mason read_block_for_search(struct btrfs_trans_handle *trans,
2194c8c42864SChris Mason 		       struct btrfs_root *root, struct btrfs_path *p,
2195c8c42864SChris Mason 		       struct extent_buffer **eb_ret, int level, int slot,
21965d9e75c4SJan Schmidt 		       struct btrfs_key *key, u64 time_seq)
2197c8c42864SChris Mason {
2198c8c42864SChris Mason 	u64 blocknr;
2199c8c42864SChris Mason 	u64 gen;
2200c8c42864SChris Mason 	u32 blocksize;
2201c8c42864SChris Mason 	struct extent_buffer *b = *eb_ret;
2202c8c42864SChris Mason 	struct extent_buffer *tmp;
220376a05b35SChris Mason 	int ret;
2204c8c42864SChris Mason 
2205c8c42864SChris Mason 	blocknr = btrfs_node_blockptr(b, slot);
2206c8c42864SChris Mason 	gen = btrfs_node_ptr_generation(b, slot);
2207c8c42864SChris Mason 	blocksize = btrfs_level_size(root, level - 1);
2208c8c42864SChris Mason 
2209c8c42864SChris Mason 	tmp = btrfs_find_tree_block(root, blocknr, blocksize);
2210cb44921aSChris Mason 	if (tmp) {
2211b9fab919SChris Mason 		/* first we do an atomic uptodate check */
2212b9fab919SChris Mason 		if (btrfs_buffer_uptodate(tmp, 0, 1) > 0) {
2213b9fab919SChris Mason 			if (btrfs_buffer_uptodate(tmp, gen, 1) > 0) {
221476a05b35SChris Mason 				/*
2215cb44921aSChris Mason 				 * we found an up to date block without
2216cb44921aSChris Mason 				 * sleeping, return
221776a05b35SChris Mason 				 * right away
221876a05b35SChris Mason 				 */
2219c8c42864SChris Mason 				*eb_ret = tmp;
2220c8c42864SChris Mason 				return 0;
2221c8c42864SChris Mason 			}
2222cb44921aSChris Mason 			/* the pages were up to date, but we failed
2223cb44921aSChris Mason 			 * the generation number check.  Do a full
2224cb44921aSChris Mason 			 * read for the generation number that is correct.
2225cb44921aSChris Mason 			 * We must do this without dropping locks so
2226cb44921aSChris Mason 			 * we can trust our generation number
2227cb44921aSChris Mason 			 */
2228cb44921aSChris Mason 			free_extent_buffer(tmp);
2229bd681513SChris Mason 			btrfs_set_path_blocking(p);
2230bd681513SChris Mason 
2231b9fab919SChris Mason 			/* now we're allowed to do a blocking uptodate check */
2232cb44921aSChris Mason 			tmp = read_tree_block(root, blocknr, blocksize, gen);
2233b9fab919SChris Mason 			if (tmp && btrfs_buffer_uptodate(tmp, gen, 0) > 0) {
2234cb44921aSChris Mason 				*eb_ret = tmp;
2235cb44921aSChris Mason 				return 0;
2236cb44921aSChris Mason 			}
2237cb44921aSChris Mason 			free_extent_buffer(tmp);
2238b3b4aa74SDavid Sterba 			btrfs_release_path(p);
2239cb44921aSChris Mason 			return -EIO;
2240cb44921aSChris Mason 		}
2241cb44921aSChris Mason 	}
2242c8c42864SChris Mason 
2243c8c42864SChris Mason 	/*
2244c8c42864SChris Mason 	 * reduce lock contention at high levels
2245c8c42864SChris Mason 	 * of the btree by dropping locks before
224676a05b35SChris Mason 	 * we read.  Don't release the lock on the current
224776a05b35SChris Mason 	 * level because we need to walk this node to figure
224876a05b35SChris Mason 	 * out which blocks to read.
2249c8c42864SChris Mason 	 */
22508c594ea8SChris Mason 	btrfs_unlock_up_safe(p, level + 1);
22518c594ea8SChris Mason 	btrfs_set_path_blocking(p);
22528c594ea8SChris Mason 
2253c8c42864SChris Mason 	free_extent_buffer(tmp);
2254c8c42864SChris Mason 	if (p->reada)
2255c8c42864SChris Mason 		reada_for_search(root, p, level, slot, key->objectid);
2256c8c42864SChris Mason 
2257b3b4aa74SDavid Sterba 	btrfs_release_path(p);
225876a05b35SChris Mason 
225976a05b35SChris Mason 	ret = -EAGAIN;
22605bdd3536SYan, Zheng 	tmp = read_tree_block(root, blocknr, blocksize, 0);
226176a05b35SChris Mason 	if (tmp) {
226276a05b35SChris Mason 		/*
226376a05b35SChris Mason 		 * If the read above didn't mark this buffer up to date,
226476a05b35SChris Mason 		 * it will never end up being up to date.  Set ret to EIO now
226576a05b35SChris Mason 		 * and give up so that our caller doesn't loop forever
226676a05b35SChris Mason 		 * on our EAGAINs.
226776a05b35SChris Mason 		 */
2268b9fab919SChris Mason 		if (!btrfs_buffer_uptodate(tmp, 0, 0))
226976a05b35SChris Mason 			ret = -EIO;
2270c8c42864SChris Mason 		free_extent_buffer(tmp);
227176a05b35SChris Mason 	}
227276a05b35SChris Mason 	return ret;
2273c8c42864SChris Mason }
2274c8c42864SChris Mason 
2275c8c42864SChris Mason /*
2276c8c42864SChris Mason  * helper function for btrfs_search_slot.  This does all of the checks
2277c8c42864SChris Mason  * for node-level blocks and does any balancing required based on
2278c8c42864SChris Mason  * the ins_len.
2279c8c42864SChris Mason  *
2280c8c42864SChris Mason  * If no extra work was required, zero is returned.  If we had to
2281c8c42864SChris Mason  * drop the path, -EAGAIN is returned and btrfs_search_slot must
2282c8c42864SChris Mason  * start over
2283c8c42864SChris Mason  */
2284c8c42864SChris Mason static int
2285c8c42864SChris Mason setup_nodes_for_search(struct btrfs_trans_handle *trans,
2286c8c42864SChris Mason 		       struct btrfs_root *root, struct btrfs_path *p,
2287bd681513SChris Mason 		       struct extent_buffer *b, int level, int ins_len,
2288bd681513SChris Mason 		       int *write_lock_level)
2289c8c42864SChris Mason {
2290c8c42864SChris Mason 	int ret;
2291c8c42864SChris Mason 	if ((p->search_for_split || ins_len > 0) && btrfs_header_nritems(b) >=
2292c8c42864SChris Mason 	    BTRFS_NODEPTRS_PER_BLOCK(root) - 3) {
2293c8c42864SChris Mason 		int sret;
2294c8c42864SChris Mason 
2295bd681513SChris Mason 		if (*write_lock_level < level + 1) {
2296bd681513SChris Mason 			*write_lock_level = level + 1;
2297bd681513SChris Mason 			btrfs_release_path(p);
2298bd681513SChris Mason 			goto again;
2299bd681513SChris Mason 		}
2300bd681513SChris Mason 
2301c8c42864SChris Mason 		sret = reada_for_balance(root, p, level);
2302c8c42864SChris Mason 		if (sret)
2303c8c42864SChris Mason 			goto again;
2304c8c42864SChris Mason 
2305c8c42864SChris Mason 		btrfs_set_path_blocking(p);
2306c8c42864SChris Mason 		sret = split_node(trans, root, p, level);
2307bd681513SChris Mason 		btrfs_clear_path_blocking(p, NULL, 0);
2308c8c42864SChris Mason 
2309c8c42864SChris Mason 		BUG_ON(sret > 0);
2310c8c42864SChris Mason 		if (sret) {
2311c8c42864SChris Mason 			ret = sret;
2312c8c42864SChris Mason 			goto done;
2313c8c42864SChris Mason 		}
2314c8c42864SChris Mason 		b = p->nodes[level];
2315c8c42864SChris Mason 	} else if (ins_len < 0 && btrfs_header_nritems(b) <
2316cfbb9308SChris Mason 		   BTRFS_NODEPTRS_PER_BLOCK(root) / 2) {
2317c8c42864SChris Mason 		int sret;
2318c8c42864SChris Mason 
2319bd681513SChris Mason 		if (*write_lock_level < level + 1) {
2320bd681513SChris Mason 			*write_lock_level = level + 1;
2321bd681513SChris Mason 			btrfs_release_path(p);
2322bd681513SChris Mason 			goto again;
2323bd681513SChris Mason 		}
2324bd681513SChris Mason 
2325c8c42864SChris Mason 		sret = reada_for_balance(root, p, level);
2326c8c42864SChris Mason 		if (sret)
2327c8c42864SChris Mason 			goto again;
2328c8c42864SChris Mason 
2329c8c42864SChris Mason 		btrfs_set_path_blocking(p);
2330c8c42864SChris Mason 		sret = balance_level(trans, root, p, level);
2331bd681513SChris Mason 		btrfs_clear_path_blocking(p, NULL, 0);
2332c8c42864SChris Mason 
2333c8c42864SChris Mason 		if (sret) {
2334c8c42864SChris Mason 			ret = sret;
2335c8c42864SChris Mason 			goto done;
2336c8c42864SChris Mason 		}
2337c8c42864SChris Mason 		b = p->nodes[level];
2338c8c42864SChris Mason 		if (!b) {
2339b3b4aa74SDavid Sterba 			btrfs_release_path(p);
2340c8c42864SChris Mason 			goto again;
2341c8c42864SChris Mason 		}
2342c8c42864SChris Mason 		BUG_ON(btrfs_header_nritems(b) == 1);
2343c8c42864SChris Mason 	}
2344c8c42864SChris Mason 	return 0;
2345c8c42864SChris Mason 
2346c8c42864SChris Mason again:
2347c8c42864SChris Mason 	ret = -EAGAIN;
2348c8c42864SChris Mason done:
2349c8c42864SChris Mason 	return ret;
2350c8c42864SChris Mason }
2351c8c42864SChris Mason 
2352c8c42864SChris Mason /*
235374123bd7SChris Mason  * look for key in the tree.  path is filled in with nodes along the way
235474123bd7SChris Mason  * if key is found, we return zero and you can find the item in the leaf
235574123bd7SChris Mason  * level of the path (level 0)
235674123bd7SChris Mason  *
235774123bd7SChris Mason  * If the key isn't found, the path points to the slot where it should
2358aa5d6bedSChris Mason  * be inserted, and 1 is returned.  If there are other errors during the
2359aa5d6bedSChris Mason  * search a negative error number is returned.
236097571fd0SChris Mason  *
236197571fd0SChris Mason  * if ins_len > 0, nodes and leaves will be split as we walk down the
236297571fd0SChris Mason  * tree.  if ins_len < 0, nodes will be merged as we walk down the tree (if
236397571fd0SChris Mason  * possible)
236474123bd7SChris Mason  */
2365e089f05cSChris Mason int btrfs_search_slot(struct btrfs_trans_handle *trans, struct btrfs_root
2366e089f05cSChris Mason 		      *root, struct btrfs_key *key, struct btrfs_path *p, int
2367e089f05cSChris Mason 		      ins_len, int cow)
2368be0e5c09SChris Mason {
23695f39d397SChris Mason 	struct extent_buffer *b;
2370be0e5c09SChris Mason 	int slot;
2371be0e5c09SChris Mason 	int ret;
237233c66f43SYan Zheng 	int err;
2373be0e5c09SChris Mason 	int level;
2374925baeddSChris Mason 	int lowest_unlock = 1;
2375bd681513SChris Mason 	int root_lock;
2376bd681513SChris Mason 	/* everything at write_lock_level or lower must be write locked */
2377bd681513SChris Mason 	int write_lock_level = 0;
23789f3a7427SChris Mason 	u8 lowest_level = 0;
2379f7c79f30SChris Mason 	int min_write_lock_level;
23809f3a7427SChris Mason 
23816702ed49SChris Mason 	lowest_level = p->lowest_level;
2382323ac95bSChris Mason 	WARN_ON(lowest_level && ins_len > 0);
238322b0ebdaSChris Mason 	WARN_ON(p->nodes[0] != NULL);
238425179201SJosef Bacik 
2385bd681513SChris Mason 	if (ins_len < 0) {
2386925baeddSChris Mason 		lowest_unlock = 2;
238765b51a00SChris Mason 
2388bd681513SChris Mason 		/* when we are removing items, we might have to go up to level
2389bd681513SChris Mason 		 * two as we update tree pointers  Make sure we keep write
2390bd681513SChris Mason 		 * for those levels as well
2391bd681513SChris Mason 		 */
2392bd681513SChris Mason 		write_lock_level = 2;
2393bd681513SChris Mason 	} else if (ins_len > 0) {
2394bd681513SChris Mason 		/*
2395bd681513SChris Mason 		 * for inserting items, make sure we have a write lock on
2396bd681513SChris Mason 		 * level 1 so we can update keys
2397bd681513SChris Mason 		 */
2398bd681513SChris Mason 		write_lock_level = 1;
2399bd681513SChris Mason 	}
2400bd681513SChris Mason 
2401bd681513SChris Mason 	if (!cow)
2402bd681513SChris Mason 		write_lock_level = -1;
2403bd681513SChris Mason 
2404bd681513SChris Mason 	if (cow && (p->keep_locks || p->lowest_level))
2405bd681513SChris Mason 		write_lock_level = BTRFS_MAX_LEVEL;
2406bd681513SChris Mason 
2407f7c79f30SChris Mason 	min_write_lock_level = write_lock_level;
2408f7c79f30SChris Mason 
2409bb803951SChris Mason again:
2410bd681513SChris Mason 	/*
2411bd681513SChris Mason 	 * we try very hard to do read locks on the root
2412bd681513SChris Mason 	 */
2413bd681513SChris Mason 	root_lock = BTRFS_READ_LOCK;
2414bd681513SChris Mason 	level = 0;
24155d4f98a2SYan Zheng 	if (p->search_commit_root) {
2416bd681513SChris Mason 		/*
2417bd681513SChris Mason 		 * the commit roots are read only
2418bd681513SChris Mason 		 * so we always do read locks
2419bd681513SChris Mason 		 */
24205d4f98a2SYan Zheng 		b = root->commit_root;
24215d4f98a2SYan Zheng 		extent_buffer_get(b);
2422bd681513SChris Mason 		level = btrfs_header_level(b);
24235d4f98a2SYan Zheng 		if (!p->skip_locking)
2424bd681513SChris Mason 			btrfs_tree_read_lock(b);
24255d4f98a2SYan Zheng 	} else {
2426bd681513SChris Mason 		if (p->skip_locking) {
24275cd57b2cSChris Mason 			b = btrfs_root_node(root);
2428bd681513SChris Mason 			level = btrfs_header_level(b);
2429bd681513SChris Mason 		} else {
2430bd681513SChris Mason 			/* we don't know the level of the root node
2431bd681513SChris Mason 			 * until we actually have it read locked
2432bd681513SChris Mason 			 */
2433bd681513SChris Mason 			b = btrfs_read_lock_root_node(root);
2434bd681513SChris Mason 			level = btrfs_header_level(b);
2435bd681513SChris Mason 			if (level <= write_lock_level) {
2436bd681513SChris Mason 				/* whoops, must trade for write lock */
2437bd681513SChris Mason 				btrfs_tree_read_unlock(b);
2438bd681513SChris Mason 				free_extent_buffer(b);
2439925baeddSChris Mason 				b = btrfs_lock_root_node(root);
2440bd681513SChris Mason 				root_lock = BTRFS_WRITE_LOCK;
2441bd681513SChris Mason 
2442bd681513SChris Mason 				/* the level might have changed, check again */
2443bd681513SChris Mason 				level = btrfs_header_level(b);
24445d4f98a2SYan Zheng 			}
2445bd681513SChris Mason 		}
2446bd681513SChris Mason 	}
2447bd681513SChris Mason 	p->nodes[level] = b;
2448bd681513SChris Mason 	if (!p->skip_locking)
2449bd681513SChris Mason 		p->locks[level] = root_lock;
2450925baeddSChris Mason 
2451eb60ceacSChris Mason 	while (b) {
24525f39d397SChris Mason 		level = btrfs_header_level(b);
245365b51a00SChris Mason 
245465b51a00SChris Mason 		/*
245565b51a00SChris Mason 		 * setup the path here so we can release it under lock
245665b51a00SChris Mason 		 * contention with the cow code
245765b51a00SChris Mason 		 */
245802217ed2SChris Mason 		if (cow) {
2459c8c42864SChris Mason 			/*
2460c8c42864SChris Mason 			 * if we don't really need to cow this block
2461c8c42864SChris Mason 			 * then we don't want to set the path blocking,
2462c8c42864SChris Mason 			 * so we test it here
2463c8c42864SChris Mason 			 */
24645d4f98a2SYan Zheng 			if (!should_cow_block(trans, root, b))
246565b51a00SChris Mason 				goto cow_done;
24665d4f98a2SYan Zheng 
2467b4ce94deSChris Mason 			btrfs_set_path_blocking(p);
2468b4ce94deSChris Mason 
2469bd681513SChris Mason 			/*
2470bd681513SChris Mason 			 * must have write locks on this node and the
2471bd681513SChris Mason 			 * parent
2472bd681513SChris Mason 			 */
2473bd681513SChris Mason 			if (level + 1 > write_lock_level) {
2474bd681513SChris Mason 				write_lock_level = level + 1;
2475bd681513SChris Mason 				btrfs_release_path(p);
2476bd681513SChris Mason 				goto again;
2477bd681513SChris Mason 			}
2478bd681513SChris Mason 
247933c66f43SYan Zheng 			err = btrfs_cow_block(trans, root, b,
2480e20d96d6SChris Mason 					      p->nodes[level + 1],
24819fa8cfe7SChris Mason 					      p->slots[level + 1], &b);
248233c66f43SYan Zheng 			if (err) {
248333c66f43SYan Zheng 				ret = err;
248465b51a00SChris Mason 				goto done;
248554aa1f4dSChris Mason 			}
248602217ed2SChris Mason 		}
248765b51a00SChris Mason cow_done:
248802217ed2SChris Mason 		BUG_ON(!cow && ins_len);
248965b51a00SChris Mason 
2490eb60ceacSChris Mason 		p->nodes[level] = b;
2491bd681513SChris Mason 		btrfs_clear_path_blocking(p, NULL, 0);
2492b4ce94deSChris Mason 
2493b4ce94deSChris Mason 		/*
2494b4ce94deSChris Mason 		 * we have a lock on b and as long as we aren't changing
2495b4ce94deSChris Mason 		 * the tree, there is no way to for the items in b to change.
2496b4ce94deSChris Mason 		 * It is safe to drop the lock on our parent before we
2497b4ce94deSChris Mason 		 * go through the expensive btree search on b.
2498b4ce94deSChris Mason 		 *
2499b4ce94deSChris Mason 		 * If cow is true, then we might be changing slot zero,
2500b4ce94deSChris Mason 		 * which may require changing the parent.  So, we can't
2501b4ce94deSChris Mason 		 * drop the lock until after we know which slot we're
2502b4ce94deSChris Mason 		 * operating on.
2503b4ce94deSChris Mason 		 */
2504b4ce94deSChris Mason 		if (!cow)
2505b4ce94deSChris Mason 			btrfs_unlock_up_safe(p, level + 1);
2506b4ce94deSChris Mason 
25075f39d397SChris Mason 		ret = bin_search(b, key, level, &slot);
2508b4ce94deSChris Mason 
25095f39d397SChris Mason 		if (level != 0) {
251033c66f43SYan Zheng 			int dec = 0;
251133c66f43SYan Zheng 			if (ret && slot > 0) {
251233c66f43SYan Zheng 				dec = 1;
2513be0e5c09SChris Mason 				slot -= 1;
251433c66f43SYan Zheng 			}
2515be0e5c09SChris Mason 			p->slots[level] = slot;
251633c66f43SYan Zheng 			err = setup_nodes_for_search(trans, root, p, b, level,
2517bd681513SChris Mason 					     ins_len, &write_lock_level);
251833c66f43SYan Zheng 			if (err == -EAGAIN)
2519b4ce94deSChris Mason 				goto again;
252033c66f43SYan Zheng 			if (err) {
252133c66f43SYan Zheng 				ret = err;
252265b51a00SChris Mason 				goto done;
252333c66f43SYan Zheng 			}
25245c680ed6SChris Mason 			b = p->nodes[level];
25255c680ed6SChris Mason 			slot = p->slots[level];
2526b4ce94deSChris Mason 
2527bd681513SChris Mason 			/*
2528bd681513SChris Mason 			 * slot 0 is special, if we change the key
2529bd681513SChris Mason 			 * we have to update the parent pointer
2530bd681513SChris Mason 			 * which means we must have a write lock
2531bd681513SChris Mason 			 * on the parent
2532bd681513SChris Mason 			 */
2533bd681513SChris Mason 			if (slot == 0 && cow &&
2534bd681513SChris Mason 			    write_lock_level < level + 1) {
2535bd681513SChris Mason 				write_lock_level = level + 1;
2536bd681513SChris Mason 				btrfs_release_path(p);
2537bd681513SChris Mason 				goto again;
2538bd681513SChris Mason 			}
2539bd681513SChris Mason 
2540f7c79f30SChris Mason 			unlock_up(p, level, lowest_unlock,
2541f7c79f30SChris Mason 				  min_write_lock_level, &write_lock_level);
2542f9efa9c7SChris Mason 
2543925baeddSChris Mason 			if (level == lowest_level) {
254433c66f43SYan Zheng 				if (dec)
254533c66f43SYan Zheng 					p->slots[level]++;
25465b21f2edSZheng Yan 				goto done;
2547925baeddSChris Mason 			}
2548ca7a79adSChris Mason 
254933c66f43SYan Zheng 			err = read_block_for_search(trans, root, p,
25505d9e75c4SJan Schmidt 						    &b, level, slot, key, 0);
255133c66f43SYan Zheng 			if (err == -EAGAIN)
2552051e1b9fSChris Mason 				goto again;
255333c66f43SYan Zheng 			if (err) {
255433c66f43SYan Zheng 				ret = err;
255576a05b35SChris Mason 				goto done;
255633c66f43SYan Zheng 			}
255776a05b35SChris Mason 
2558b4ce94deSChris Mason 			if (!p->skip_locking) {
2559bd681513SChris Mason 				level = btrfs_header_level(b);
2560bd681513SChris Mason 				if (level <= write_lock_level) {
2561bd681513SChris Mason 					err = btrfs_try_tree_write_lock(b);
256233c66f43SYan Zheng 					if (!err) {
2563b4ce94deSChris Mason 						btrfs_set_path_blocking(p);
2564925baeddSChris Mason 						btrfs_tree_lock(b);
2565bd681513SChris Mason 						btrfs_clear_path_blocking(p, b,
2566bd681513SChris Mason 								  BTRFS_WRITE_LOCK);
2567b4ce94deSChris Mason 					}
2568bd681513SChris Mason 					p->locks[level] = BTRFS_WRITE_LOCK;
2569bd681513SChris Mason 				} else {
2570bd681513SChris Mason 					err = btrfs_try_tree_read_lock(b);
2571bd681513SChris Mason 					if (!err) {
2572bd681513SChris Mason 						btrfs_set_path_blocking(p);
2573bd681513SChris Mason 						btrfs_tree_read_lock(b);
2574bd681513SChris Mason 						btrfs_clear_path_blocking(p, b,
2575bd681513SChris Mason 								  BTRFS_READ_LOCK);
2576bd681513SChris Mason 					}
2577bd681513SChris Mason 					p->locks[level] = BTRFS_READ_LOCK;
2578bd681513SChris Mason 				}
2579bd681513SChris Mason 				p->nodes[level] = b;
2580b4ce94deSChris Mason 			}
2581be0e5c09SChris Mason 		} else {
2582be0e5c09SChris Mason 			p->slots[level] = slot;
258387b29b20SYan Zheng 			if (ins_len > 0 &&
258487b29b20SYan Zheng 			    btrfs_leaf_free_space(root, b) < ins_len) {
2585bd681513SChris Mason 				if (write_lock_level < 1) {
2586bd681513SChris Mason 					write_lock_level = 1;
2587bd681513SChris Mason 					btrfs_release_path(p);
2588bd681513SChris Mason 					goto again;
2589bd681513SChris Mason 				}
2590bd681513SChris Mason 
2591b4ce94deSChris Mason 				btrfs_set_path_blocking(p);
259233c66f43SYan Zheng 				err = split_leaf(trans, root, key,
2593cc0c5538SChris Mason 						 p, ins_len, ret == 0);
2594bd681513SChris Mason 				btrfs_clear_path_blocking(p, NULL, 0);
2595b4ce94deSChris Mason 
259633c66f43SYan Zheng 				BUG_ON(err > 0);
259733c66f43SYan Zheng 				if (err) {
259833c66f43SYan Zheng 					ret = err;
259965b51a00SChris Mason 					goto done;
260065b51a00SChris Mason 				}
26015c680ed6SChris Mason 			}
2602459931ecSChris Mason 			if (!p->search_for_split)
2603f7c79f30SChris Mason 				unlock_up(p, level, lowest_unlock,
2604f7c79f30SChris Mason 					  min_write_lock_level, &write_lock_level);
260565b51a00SChris Mason 			goto done;
260665b51a00SChris Mason 		}
260765b51a00SChris Mason 	}
260865b51a00SChris Mason 	ret = 1;
260965b51a00SChris Mason done:
2610b4ce94deSChris Mason 	/*
2611b4ce94deSChris Mason 	 * we don't really know what they plan on doing with the path
2612b4ce94deSChris Mason 	 * from here on, so for now just mark it as blocking
2613b4ce94deSChris Mason 	 */
2614b9473439SChris Mason 	if (!p->leave_spinning)
2615b4ce94deSChris Mason 		btrfs_set_path_blocking(p);
261676a05b35SChris Mason 	if (ret < 0)
2617b3b4aa74SDavid Sterba 		btrfs_release_path(p);
2618be0e5c09SChris Mason 	return ret;
2619be0e5c09SChris Mason }
2620be0e5c09SChris Mason 
262174123bd7SChris Mason /*
26225d9e75c4SJan Schmidt  * Like btrfs_search_slot, this looks for a key in the given tree. It uses the
26235d9e75c4SJan Schmidt  * current state of the tree together with the operations recorded in the tree
26245d9e75c4SJan Schmidt  * modification log to search for the key in a previous version of this tree, as
26255d9e75c4SJan Schmidt  * denoted by the time_seq parameter.
26265d9e75c4SJan Schmidt  *
26275d9e75c4SJan Schmidt  * Naturally, there is no support for insert, delete or cow operations.
26285d9e75c4SJan Schmidt  *
26295d9e75c4SJan Schmidt  * The resulting path and return value will be set up as if we called
26305d9e75c4SJan Schmidt  * btrfs_search_slot at that point in time with ins_len and cow both set to 0.
26315d9e75c4SJan Schmidt  */
26325d9e75c4SJan Schmidt int btrfs_search_old_slot(struct btrfs_root *root, struct btrfs_key *key,
26335d9e75c4SJan Schmidt 			  struct btrfs_path *p, u64 time_seq)
26345d9e75c4SJan Schmidt {
26355d9e75c4SJan Schmidt 	struct extent_buffer *b;
26365d9e75c4SJan Schmidt 	int slot;
26375d9e75c4SJan Schmidt 	int ret;
26385d9e75c4SJan Schmidt 	int err;
26395d9e75c4SJan Schmidt 	int level;
26405d9e75c4SJan Schmidt 	int lowest_unlock = 1;
26415d9e75c4SJan Schmidt 	u8 lowest_level = 0;
26425d9e75c4SJan Schmidt 
26435d9e75c4SJan Schmidt 	lowest_level = p->lowest_level;
26445d9e75c4SJan Schmidt 	WARN_ON(p->nodes[0] != NULL);
26455d9e75c4SJan Schmidt 
26465d9e75c4SJan Schmidt 	if (p->search_commit_root) {
26475d9e75c4SJan Schmidt 		BUG_ON(time_seq);
26485d9e75c4SJan Schmidt 		return btrfs_search_slot(NULL, root, key, p, 0, 0);
26495d9e75c4SJan Schmidt 	}
26505d9e75c4SJan Schmidt 
26515d9e75c4SJan Schmidt again:
26525d9e75c4SJan Schmidt 	b = get_old_root(root, time_seq);
26535d9e75c4SJan Schmidt 	level = btrfs_header_level(b);
26545d9e75c4SJan Schmidt 	p->locks[level] = BTRFS_READ_LOCK;
26555d9e75c4SJan Schmidt 
26565d9e75c4SJan Schmidt 	while (b) {
26575d9e75c4SJan Schmidt 		level = btrfs_header_level(b);
26585d9e75c4SJan Schmidt 		p->nodes[level] = b;
26595d9e75c4SJan Schmidt 		btrfs_clear_path_blocking(p, NULL, 0);
26605d9e75c4SJan Schmidt 
26615d9e75c4SJan Schmidt 		/*
26625d9e75c4SJan Schmidt 		 * we have a lock on b and as long as we aren't changing
26635d9e75c4SJan Schmidt 		 * the tree, there is no way to for the items in b to change.
26645d9e75c4SJan Schmidt 		 * It is safe to drop the lock on our parent before we
26655d9e75c4SJan Schmidt 		 * go through the expensive btree search on b.
26665d9e75c4SJan Schmidt 		 */
26675d9e75c4SJan Schmidt 		btrfs_unlock_up_safe(p, level + 1);
26685d9e75c4SJan Schmidt 
26695d9e75c4SJan Schmidt 		ret = bin_search(b, key, level, &slot);
26705d9e75c4SJan Schmidt 
26715d9e75c4SJan Schmidt 		if (level != 0) {
26725d9e75c4SJan Schmidt 			int dec = 0;
26735d9e75c4SJan Schmidt 			if (ret && slot > 0) {
26745d9e75c4SJan Schmidt 				dec = 1;
26755d9e75c4SJan Schmidt 				slot -= 1;
26765d9e75c4SJan Schmidt 			}
26775d9e75c4SJan Schmidt 			p->slots[level] = slot;
26785d9e75c4SJan Schmidt 			unlock_up(p, level, lowest_unlock, 0, NULL);
26795d9e75c4SJan Schmidt 
26805d9e75c4SJan Schmidt 			if (level == lowest_level) {
26815d9e75c4SJan Schmidt 				if (dec)
26825d9e75c4SJan Schmidt 					p->slots[level]++;
26835d9e75c4SJan Schmidt 				goto done;
26845d9e75c4SJan Schmidt 			}
26855d9e75c4SJan Schmidt 
26865d9e75c4SJan Schmidt 			err = read_block_for_search(NULL, root, p, &b, level,
26875d9e75c4SJan Schmidt 						    slot, key, time_seq);
26885d9e75c4SJan Schmidt 			if (err == -EAGAIN)
26895d9e75c4SJan Schmidt 				goto again;
26905d9e75c4SJan Schmidt 			if (err) {
26915d9e75c4SJan Schmidt 				ret = err;
26925d9e75c4SJan Schmidt 				goto done;
26935d9e75c4SJan Schmidt 			}
26945d9e75c4SJan Schmidt 
26955d9e75c4SJan Schmidt 			level = btrfs_header_level(b);
26965d9e75c4SJan Schmidt 			err = btrfs_try_tree_read_lock(b);
26975d9e75c4SJan Schmidt 			if (!err) {
26985d9e75c4SJan Schmidt 				btrfs_set_path_blocking(p);
26995d9e75c4SJan Schmidt 				btrfs_tree_read_lock(b);
27005d9e75c4SJan Schmidt 				btrfs_clear_path_blocking(p, b,
27015d9e75c4SJan Schmidt 							  BTRFS_READ_LOCK);
27025d9e75c4SJan Schmidt 			}
27035d9e75c4SJan Schmidt 			p->locks[level] = BTRFS_READ_LOCK;
27045d9e75c4SJan Schmidt 			p->nodes[level] = b;
27055d9e75c4SJan Schmidt 			b = tree_mod_log_rewind(root->fs_info, b, time_seq);
27065d9e75c4SJan Schmidt 			if (b != p->nodes[level]) {
27075d9e75c4SJan Schmidt 				btrfs_tree_unlock_rw(p->nodes[level],
27085d9e75c4SJan Schmidt 						     p->locks[level]);
27095d9e75c4SJan Schmidt 				p->locks[level] = 0;
27105d9e75c4SJan Schmidt 				p->nodes[level] = b;
27115d9e75c4SJan Schmidt 			}
27125d9e75c4SJan Schmidt 		} else {
27135d9e75c4SJan Schmidt 			p->slots[level] = slot;
27145d9e75c4SJan Schmidt 			unlock_up(p, level, lowest_unlock, 0, NULL);
27155d9e75c4SJan Schmidt 			goto done;
27165d9e75c4SJan Schmidt 		}
27175d9e75c4SJan Schmidt 	}
27185d9e75c4SJan Schmidt 	ret = 1;
27195d9e75c4SJan Schmidt done:
27205d9e75c4SJan Schmidt 	if (!p->leave_spinning)
27215d9e75c4SJan Schmidt 		btrfs_set_path_blocking(p);
27225d9e75c4SJan Schmidt 	if (ret < 0)
27235d9e75c4SJan Schmidt 		btrfs_release_path(p);
27245d9e75c4SJan Schmidt 
27255d9e75c4SJan Schmidt 	return ret;
27265d9e75c4SJan Schmidt }
27275d9e75c4SJan Schmidt 
27285d9e75c4SJan Schmidt /*
272974123bd7SChris Mason  * adjust the pointers going up the tree, starting at level
273074123bd7SChris Mason  * making sure the right key of each node is points to 'key'.
273174123bd7SChris Mason  * This is used after shifting pointers to the left, so it stops
273274123bd7SChris Mason  * fixing up pointers when a given leaf/node is not in slot 0 of the
273374123bd7SChris Mason  * higher levels
2734aa5d6bedSChris Mason  *
273574123bd7SChris Mason  */
2736143bede5SJeff Mahoney static void fixup_low_keys(struct btrfs_trans_handle *trans,
27375f39d397SChris Mason 			   struct btrfs_root *root, struct btrfs_path *path,
27385f39d397SChris Mason 			   struct btrfs_disk_key *key, int level)
2739be0e5c09SChris Mason {
2740be0e5c09SChris Mason 	int i;
27415f39d397SChris Mason 	struct extent_buffer *t;
27425f39d397SChris Mason 
2743234b63a0SChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2744be0e5c09SChris Mason 		int tslot = path->slots[i];
2745eb60ceacSChris Mason 		if (!path->nodes[i])
2746be0e5c09SChris Mason 			break;
27475f39d397SChris Mason 		t = path->nodes[i];
2748f230475eSJan Schmidt 		tree_mod_log_set_node_key(root->fs_info, t, key, tslot, 1);
27495f39d397SChris Mason 		btrfs_set_node_key(t, key, tslot);
2750d6025579SChris Mason 		btrfs_mark_buffer_dirty(path->nodes[i]);
2751be0e5c09SChris Mason 		if (tslot != 0)
2752be0e5c09SChris Mason 			break;
2753be0e5c09SChris Mason 	}
2754be0e5c09SChris Mason }
2755be0e5c09SChris Mason 
275674123bd7SChris Mason /*
275731840ae1SZheng Yan  * update item key.
275831840ae1SZheng Yan  *
275931840ae1SZheng Yan  * This function isn't completely safe. It's the caller's responsibility
276031840ae1SZheng Yan  * that the new key won't break the order
276131840ae1SZheng Yan  */
2762143bede5SJeff Mahoney void btrfs_set_item_key_safe(struct btrfs_trans_handle *trans,
276331840ae1SZheng Yan 			     struct btrfs_root *root, struct btrfs_path *path,
276431840ae1SZheng Yan 			     struct btrfs_key *new_key)
276531840ae1SZheng Yan {
276631840ae1SZheng Yan 	struct btrfs_disk_key disk_key;
276731840ae1SZheng Yan 	struct extent_buffer *eb;
276831840ae1SZheng Yan 	int slot;
276931840ae1SZheng Yan 
277031840ae1SZheng Yan 	eb = path->nodes[0];
277131840ae1SZheng Yan 	slot = path->slots[0];
277231840ae1SZheng Yan 	if (slot > 0) {
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 	if (slot < btrfs_header_nritems(eb) - 1) {
277731840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot + 1);
2778143bede5SJeff Mahoney 		BUG_ON(comp_keys(&disk_key, new_key) <= 0);
277931840ae1SZheng Yan 	}
278031840ae1SZheng Yan 
278131840ae1SZheng Yan 	btrfs_cpu_key_to_disk(&disk_key, new_key);
278231840ae1SZheng Yan 	btrfs_set_item_key(eb, &disk_key, slot);
278331840ae1SZheng Yan 	btrfs_mark_buffer_dirty(eb);
278431840ae1SZheng Yan 	if (slot == 0)
278531840ae1SZheng Yan 		fixup_low_keys(trans, root, path, &disk_key, 1);
278631840ae1SZheng Yan }
278731840ae1SZheng Yan 
278831840ae1SZheng Yan /*
278974123bd7SChris Mason  * try to push data from one node into the next node left in the
279079f95c82SChris Mason  * tree.
2791aa5d6bedSChris Mason  *
2792aa5d6bedSChris Mason  * returns 0 if some ptrs were pushed left, < 0 if there was some horrible
2793aa5d6bedSChris Mason  * error, and > 0 if there was no room in the left hand block.
279474123bd7SChris Mason  */
279598ed5174SChris Mason static int push_node_left(struct btrfs_trans_handle *trans,
279698ed5174SChris Mason 			  struct btrfs_root *root, struct extent_buffer *dst,
2797971a1f66SChris Mason 			  struct extent_buffer *src, int empty)
2798be0e5c09SChris Mason {
2799be0e5c09SChris Mason 	int push_items = 0;
2800bb803951SChris Mason 	int src_nritems;
2801bb803951SChris Mason 	int dst_nritems;
2802aa5d6bedSChris Mason 	int ret = 0;
2803be0e5c09SChris Mason 
28045f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
28055f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
2806123abc88SChris Mason 	push_items = BTRFS_NODEPTRS_PER_BLOCK(root) - dst_nritems;
28077bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
28087bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
280954aa1f4dSChris Mason 
2810bce4eae9SChris Mason 	if (!empty && src_nritems <= 8)
2811971a1f66SChris Mason 		return 1;
2812971a1f66SChris Mason 
2813d397712bSChris Mason 	if (push_items <= 0)
2814be0e5c09SChris Mason 		return 1;
2815be0e5c09SChris Mason 
2816bce4eae9SChris Mason 	if (empty) {
2817971a1f66SChris Mason 		push_items = min(src_nritems, push_items);
2818bce4eae9SChris Mason 		if (push_items < src_nritems) {
2819bce4eae9SChris Mason 			/* leave at least 8 pointers in the node if
2820bce4eae9SChris Mason 			 * we aren't going to empty it
2821bce4eae9SChris Mason 			 */
2822bce4eae9SChris Mason 			if (src_nritems - push_items < 8) {
2823bce4eae9SChris Mason 				if (push_items <= 8)
2824bce4eae9SChris Mason 					return 1;
2825bce4eae9SChris Mason 				push_items -= 8;
2826bce4eae9SChris Mason 			}
2827bce4eae9SChris Mason 		}
2828bce4eae9SChris Mason 	} else
2829bce4eae9SChris Mason 		push_items = min(src_nritems - 8, push_items);
283079f95c82SChris Mason 
2831f230475eSJan Schmidt 	tree_mod_log_eb_copy(root->fs_info, dst, src, dst_nritems, 0,
2832f230475eSJan Schmidt 			     push_items);
28335f39d397SChris Mason 	copy_extent_buffer(dst, src,
28345f39d397SChris Mason 			   btrfs_node_key_ptr_offset(dst_nritems),
28355f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
2836123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
28375f39d397SChris Mason 
2838bb803951SChris Mason 	if (push_items < src_nritems) {
2839f230475eSJan Schmidt 		tree_mod_log_eb_move(root->fs_info, src, 0, push_items,
2840f230475eSJan Schmidt 				     src_nritems - push_items);
28415f39d397SChris Mason 		memmove_extent_buffer(src, btrfs_node_key_ptr_offset(0),
28425f39d397SChris Mason 				      btrfs_node_key_ptr_offset(push_items),
2843e2fa7227SChris Mason 				      (src_nritems - push_items) *
2844123abc88SChris Mason 				      sizeof(struct btrfs_key_ptr));
2845bb803951SChris Mason 	}
28465f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
28475f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
28485f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
28495f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
285031840ae1SZheng Yan 
2851bb803951SChris Mason 	return ret;
2852be0e5c09SChris Mason }
2853be0e5c09SChris Mason 
285497571fd0SChris Mason /*
285579f95c82SChris Mason  * try to push data from one node into the next node right in the
285679f95c82SChris Mason  * tree.
285779f95c82SChris Mason  *
285879f95c82SChris Mason  * returns 0 if some ptrs were pushed, < 0 if there was some horrible
285979f95c82SChris Mason  * error, and > 0 if there was no room in the right hand block.
286079f95c82SChris Mason  *
286179f95c82SChris Mason  * this will  only push up to 1/2 the contents of the left node over
286279f95c82SChris Mason  */
28635f39d397SChris Mason static int balance_node_right(struct btrfs_trans_handle *trans,
28645f39d397SChris Mason 			      struct btrfs_root *root,
28655f39d397SChris Mason 			      struct extent_buffer *dst,
28665f39d397SChris Mason 			      struct extent_buffer *src)
286779f95c82SChris Mason {
286879f95c82SChris Mason 	int push_items = 0;
286979f95c82SChris Mason 	int max_push;
287079f95c82SChris Mason 	int src_nritems;
287179f95c82SChris Mason 	int dst_nritems;
287279f95c82SChris Mason 	int ret = 0;
287379f95c82SChris Mason 
28747bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
28757bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
28767bb86316SChris Mason 
28775f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
28785f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
2879123abc88SChris Mason 	push_items = BTRFS_NODEPTRS_PER_BLOCK(root) - dst_nritems;
2880d397712bSChris Mason 	if (push_items <= 0)
288179f95c82SChris Mason 		return 1;
2882bce4eae9SChris Mason 
2883d397712bSChris Mason 	if (src_nritems < 4)
2884bce4eae9SChris Mason 		return 1;
288579f95c82SChris Mason 
288679f95c82SChris Mason 	max_push = src_nritems / 2 + 1;
288779f95c82SChris Mason 	/* don't try to empty the node */
2888d397712bSChris Mason 	if (max_push >= src_nritems)
288979f95c82SChris Mason 		return 1;
2890252c38f0SYan 
289179f95c82SChris Mason 	if (max_push < push_items)
289279f95c82SChris Mason 		push_items = max_push;
289379f95c82SChris Mason 
2894f230475eSJan Schmidt 	tree_mod_log_eb_move(root->fs_info, dst, push_items, 0, dst_nritems);
28955f39d397SChris Mason 	memmove_extent_buffer(dst, btrfs_node_key_ptr_offset(push_items),
28965f39d397SChris Mason 				      btrfs_node_key_ptr_offset(0),
28975f39d397SChris Mason 				      (dst_nritems) *
28985f39d397SChris Mason 				      sizeof(struct btrfs_key_ptr));
2899d6025579SChris Mason 
2900f230475eSJan Schmidt 	tree_mod_log_eb_copy(root->fs_info, dst, src, 0,
2901f230475eSJan Schmidt 			     src_nritems - push_items, push_items);
29025f39d397SChris Mason 	copy_extent_buffer(dst, src,
29035f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
29045f39d397SChris Mason 			   btrfs_node_key_ptr_offset(src_nritems - push_items),
2905123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
290679f95c82SChris Mason 
29075f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
29085f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
290979f95c82SChris Mason 
29105f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
29115f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
291231840ae1SZheng Yan 
291379f95c82SChris Mason 	return ret;
291479f95c82SChris Mason }
291579f95c82SChris Mason 
291679f95c82SChris Mason /*
291797571fd0SChris Mason  * helper function to insert a new root level in the tree.
291897571fd0SChris Mason  * A new node is allocated, and a single item is inserted to
291997571fd0SChris Mason  * point to the existing root
2920aa5d6bedSChris Mason  *
2921aa5d6bedSChris Mason  * returns zero on success or < 0 on failure.
292297571fd0SChris Mason  */
2923d397712bSChris Mason static noinline int insert_new_root(struct btrfs_trans_handle *trans,
29245f39d397SChris Mason 			   struct btrfs_root *root,
29255f39d397SChris Mason 			   struct btrfs_path *path, int level)
292674123bd7SChris Mason {
29277bb86316SChris Mason 	u64 lower_gen;
29285f39d397SChris Mason 	struct extent_buffer *lower;
29295f39d397SChris Mason 	struct extent_buffer *c;
2930925baeddSChris Mason 	struct extent_buffer *old;
29315f39d397SChris Mason 	struct btrfs_disk_key lower_key;
29325c680ed6SChris Mason 
29335c680ed6SChris Mason 	BUG_ON(path->nodes[level]);
29345c680ed6SChris Mason 	BUG_ON(path->nodes[level-1] != root->node);
29355c680ed6SChris Mason 
29367bb86316SChris Mason 	lower = path->nodes[level-1];
29377bb86316SChris Mason 	if (level == 1)
29387bb86316SChris Mason 		btrfs_item_key(lower, &lower_key, 0);
29397bb86316SChris Mason 	else
29407bb86316SChris Mason 		btrfs_node_key(lower, &lower_key, 0);
29417bb86316SChris Mason 
294231840ae1SZheng Yan 	c = btrfs_alloc_free_block(trans, root, root->nodesize, 0,
29435d4f98a2SYan Zheng 				   root->root_key.objectid, &lower_key,
29445581a51aSJan Schmidt 				   level, root->node->start, 0);
29455f39d397SChris Mason 	if (IS_ERR(c))
29465f39d397SChris Mason 		return PTR_ERR(c);
2947925baeddSChris Mason 
2948f0486c68SYan, Zheng 	root_add_used(root, root->nodesize);
2949f0486c68SYan, Zheng 
29505d4f98a2SYan Zheng 	memset_extent_buffer(c, 0, 0, sizeof(struct btrfs_header));
29515f39d397SChris Mason 	btrfs_set_header_nritems(c, 1);
29525f39d397SChris Mason 	btrfs_set_header_level(c, level);
2953db94535dSChris Mason 	btrfs_set_header_bytenr(c, c->start);
29545f39d397SChris Mason 	btrfs_set_header_generation(c, trans->transid);
29555d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(c, BTRFS_MIXED_BACKREF_REV);
29565f39d397SChris Mason 	btrfs_set_header_owner(c, root->root_key.objectid);
2957d5719762SChris Mason 
29585f39d397SChris Mason 	write_extent_buffer(c, root->fs_info->fsid,
29595f39d397SChris Mason 			    (unsigned long)btrfs_header_fsid(c),
29605f39d397SChris Mason 			    BTRFS_FSID_SIZE);
2961e17cade2SChris Mason 
2962e17cade2SChris Mason 	write_extent_buffer(c, root->fs_info->chunk_tree_uuid,
2963e17cade2SChris Mason 			    (unsigned long)btrfs_header_chunk_tree_uuid(c),
2964e17cade2SChris Mason 			    BTRFS_UUID_SIZE);
2965e17cade2SChris Mason 
29665f39d397SChris Mason 	btrfs_set_node_key(c, &lower_key, 0);
2967db94535dSChris Mason 	btrfs_set_node_blockptr(c, 0, lower->start);
29687bb86316SChris Mason 	lower_gen = btrfs_header_generation(lower);
296931840ae1SZheng Yan 	WARN_ON(lower_gen != trans->transid);
29707bb86316SChris Mason 
29717bb86316SChris Mason 	btrfs_set_node_ptr_generation(c, 0, lower_gen);
29725f39d397SChris Mason 
29735f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
2974d5719762SChris Mason 
2975925baeddSChris Mason 	old = root->node;
2976f230475eSJan Schmidt 	tree_mod_log_set_root_pointer(root, c);
2977240f62c8SChris Mason 	rcu_assign_pointer(root->node, c);
2978925baeddSChris Mason 
2979925baeddSChris Mason 	/* the super has an extra ref to root->node */
2980925baeddSChris Mason 	free_extent_buffer(old);
2981925baeddSChris Mason 
29820b86a832SChris Mason 	add_root_to_dirty_list(root);
29835f39d397SChris Mason 	extent_buffer_get(c);
29845f39d397SChris Mason 	path->nodes[level] = c;
2985bd681513SChris Mason 	path->locks[level] = BTRFS_WRITE_LOCK;
298674123bd7SChris Mason 	path->slots[level] = 0;
298774123bd7SChris Mason 	return 0;
298874123bd7SChris Mason }
29895c680ed6SChris Mason 
29905c680ed6SChris Mason /*
29915c680ed6SChris Mason  * worker function to insert a single pointer in a node.
29925c680ed6SChris Mason  * the node should have enough room for the pointer already
299397571fd0SChris Mason  *
29945c680ed6SChris Mason  * slot and level indicate where you want the key to go, and
29955c680ed6SChris Mason  * blocknr is the block the key points to.
29965c680ed6SChris Mason  */
2997143bede5SJeff Mahoney static void insert_ptr(struct btrfs_trans_handle *trans,
2998143bede5SJeff Mahoney 		       struct btrfs_root *root, struct btrfs_path *path,
2999143bede5SJeff Mahoney 		       struct btrfs_disk_key *key, u64 bytenr,
3000f3ea38daSJan Schmidt 		       int slot, int level, int tree_mod_log)
30015c680ed6SChris Mason {
30025f39d397SChris Mason 	struct extent_buffer *lower;
30035c680ed6SChris Mason 	int nritems;
3004f3ea38daSJan Schmidt 	int ret;
30055c680ed6SChris Mason 
30065c680ed6SChris Mason 	BUG_ON(!path->nodes[level]);
3007f0486c68SYan, Zheng 	btrfs_assert_tree_locked(path->nodes[level]);
30085f39d397SChris Mason 	lower = path->nodes[level];
30095f39d397SChris Mason 	nritems = btrfs_header_nritems(lower);
3010c293498bSStoyan Gaydarov 	BUG_ON(slot > nritems);
3011143bede5SJeff Mahoney 	BUG_ON(nritems == BTRFS_NODEPTRS_PER_BLOCK(root));
301274123bd7SChris Mason 	if (slot != nritems) {
3013f3ea38daSJan Schmidt 		if (tree_mod_log && level)
3014f3ea38daSJan Schmidt 			tree_mod_log_eb_move(root->fs_info, lower, slot + 1,
3015f3ea38daSJan Schmidt 					     slot, nritems - slot);
30165f39d397SChris Mason 		memmove_extent_buffer(lower,
30175f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot + 1),
30185f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot),
3019123abc88SChris Mason 			      (nritems - slot) * sizeof(struct btrfs_key_ptr));
302074123bd7SChris Mason 	}
3021f3ea38daSJan Schmidt 	if (tree_mod_log && level) {
3022f3ea38daSJan Schmidt 		ret = tree_mod_log_insert_key(root->fs_info, lower, slot,
3023f3ea38daSJan Schmidt 					      MOD_LOG_KEY_ADD);
3024f3ea38daSJan Schmidt 		BUG_ON(ret < 0);
3025f3ea38daSJan Schmidt 	}
30265f39d397SChris Mason 	btrfs_set_node_key(lower, key, slot);
3027db94535dSChris Mason 	btrfs_set_node_blockptr(lower, slot, bytenr);
302874493f7aSChris Mason 	WARN_ON(trans->transid == 0);
302974493f7aSChris Mason 	btrfs_set_node_ptr_generation(lower, slot, trans->transid);
30305f39d397SChris Mason 	btrfs_set_header_nritems(lower, nritems + 1);
30315f39d397SChris Mason 	btrfs_mark_buffer_dirty(lower);
303274123bd7SChris Mason }
303374123bd7SChris Mason 
303497571fd0SChris Mason /*
303597571fd0SChris Mason  * split the node at the specified level in path in two.
303697571fd0SChris Mason  * The path is corrected to point to the appropriate node after the split
303797571fd0SChris Mason  *
303897571fd0SChris Mason  * Before splitting this tries to make some room in the node by pushing
303997571fd0SChris Mason  * left and right, if either one works, it returns right away.
3040aa5d6bedSChris Mason  *
3041aa5d6bedSChris Mason  * returns 0 on success and < 0 on failure
304297571fd0SChris Mason  */
3043e02119d5SChris Mason static noinline int split_node(struct btrfs_trans_handle *trans,
3044e02119d5SChris Mason 			       struct btrfs_root *root,
3045e02119d5SChris Mason 			       struct btrfs_path *path, int level)
3046be0e5c09SChris Mason {
30475f39d397SChris Mason 	struct extent_buffer *c;
30485f39d397SChris Mason 	struct extent_buffer *split;
30495f39d397SChris Mason 	struct btrfs_disk_key disk_key;
3050be0e5c09SChris Mason 	int mid;
30515c680ed6SChris Mason 	int ret;
30527518a238SChris Mason 	u32 c_nritems;
3053be0e5c09SChris Mason 
30545f39d397SChris Mason 	c = path->nodes[level];
30557bb86316SChris Mason 	WARN_ON(btrfs_header_generation(c) != trans->transid);
30565f39d397SChris Mason 	if (c == root->node) {
30575c680ed6SChris Mason 		/* trying to split the root, lets make a new one */
3058e089f05cSChris Mason 		ret = insert_new_root(trans, root, path, level + 1);
30595c680ed6SChris Mason 		if (ret)
30605c680ed6SChris Mason 			return ret;
3061b3612421SChris Mason 	} else {
3062e66f709bSChris Mason 		ret = push_nodes_for_insert(trans, root, path, level);
30635f39d397SChris Mason 		c = path->nodes[level];
30645f39d397SChris Mason 		if (!ret && btrfs_header_nritems(c) <
3065c448acf0SChris Mason 		    BTRFS_NODEPTRS_PER_BLOCK(root) - 3)
3066e66f709bSChris Mason 			return 0;
306754aa1f4dSChris Mason 		if (ret < 0)
306854aa1f4dSChris Mason 			return ret;
30695c680ed6SChris Mason 	}
3070e66f709bSChris Mason 
30715f39d397SChris Mason 	c_nritems = btrfs_header_nritems(c);
30725d4f98a2SYan Zheng 	mid = (c_nritems + 1) / 2;
30735d4f98a2SYan Zheng 	btrfs_node_key(c, &disk_key, mid);
30747bb86316SChris Mason 
30755d4f98a2SYan Zheng 	split = btrfs_alloc_free_block(trans, root, root->nodesize, 0,
30767bb86316SChris Mason 					root->root_key.objectid,
30775581a51aSJan Schmidt 					&disk_key, level, c->start, 0);
30785f39d397SChris Mason 	if (IS_ERR(split))
30795f39d397SChris Mason 		return PTR_ERR(split);
308054aa1f4dSChris Mason 
3081f0486c68SYan, Zheng 	root_add_used(root, root->nodesize);
3082f0486c68SYan, Zheng 
30835d4f98a2SYan Zheng 	memset_extent_buffer(split, 0, 0, sizeof(struct btrfs_header));
30845f39d397SChris Mason 	btrfs_set_header_level(split, btrfs_header_level(c));
3085db94535dSChris Mason 	btrfs_set_header_bytenr(split, split->start);
30865f39d397SChris Mason 	btrfs_set_header_generation(split, trans->transid);
30875d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(split, BTRFS_MIXED_BACKREF_REV);
30885f39d397SChris Mason 	btrfs_set_header_owner(split, root->root_key.objectid);
30895f39d397SChris Mason 	write_extent_buffer(split, root->fs_info->fsid,
30905f39d397SChris Mason 			    (unsigned long)btrfs_header_fsid(split),
30915f39d397SChris Mason 			    BTRFS_FSID_SIZE);
3092e17cade2SChris Mason 	write_extent_buffer(split, root->fs_info->chunk_tree_uuid,
3093e17cade2SChris Mason 			    (unsigned long)btrfs_header_chunk_tree_uuid(split),
3094e17cade2SChris Mason 			    BTRFS_UUID_SIZE);
30955f39d397SChris Mason 
3096f230475eSJan Schmidt 	tree_mod_log_eb_copy(root->fs_info, split, c, 0, mid, c_nritems - mid);
30975f39d397SChris Mason 	copy_extent_buffer(split, c,
30985f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
30995f39d397SChris Mason 			   btrfs_node_key_ptr_offset(mid),
3100123abc88SChris Mason 			   (c_nritems - mid) * sizeof(struct btrfs_key_ptr));
31015f39d397SChris Mason 	btrfs_set_header_nritems(split, c_nritems - mid);
31025f39d397SChris Mason 	btrfs_set_header_nritems(c, mid);
3103aa5d6bedSChris Mason 	ret = 0;
3104aa5d6bedSChris Mason 
31055f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
31065f39d397SChris Mason 	btrfs_mark_buffer_dirty(split);
31075f39d397SChris Mason 
3108143bede5SJeff Mahoney 	insert_ptr(trans, root, path, &disk_key, split->start,
3109f3ea38daSJan Schmidt 		   path->slots[level + 1] + 1, level + 1, 1);
3110aa5d6bedSChris Mason 
31115de08d7dSChris Mason 	if (path->slots[level] >= mid) {
31125c680ed6SChris Mason 		path->slots[level] -= mid;
3113925baeddSChris Mason 		btrfs_tree_unlock(c);
31145f39d397SChris Mason 		free_extent_buffer(c);
31155f39d397SChris Mason 		path->nodes[level] = split;
31165c680ed6SChris Mason 		path->slots[level + 1] += 1;
3117eb60ceacSChris Mason 	} else {
3118925baeddSChris Mason 		btrfs_tree_unlock(split);
31195f39d397SChris Mason 		free_extent_buffer(split);
3120be0e5c09SChris Mason 	}
3121aa5d6bedSChris Mason 	return ret;
3122be0e5c09SChris Mason }
3123be0e5c09SChris Mason 
312474123bd7SChris Mason /*
312574123bd7SChris Mason  * how many bytes are required to store the items in a leaf.  start
312674123bd7SChris Mason  * and nr indicate which items in the leaf to check.  This totals up the
312774123bd7SChris Mason  * space used both by the item structs and the item data
312874123bd7SChris Mason  */
31295f39d397SChris Mason static int leaf_space_used(struct extent_buffer *l, int start, int nr)
3130be0e5c09SChris Mason {
3131be0e5c09SChris Mason 	int data_len;
31325f39d397SChris Mason 	int nritems = btrfs_header_nritems(l);
3133d4dbff95SChris Mason 	int end = min(nritems, start + nr) - 1;
3134be0e5c09SChris Mason 
3135be0e5c09SChris Mason 	if (!nr)
3136be0e5c09SChris Mason 		return 0;
31375f39d397SChris Mason 	data_len = btrfs_item_end_nr(l, start);
31385f39d397SChris Mason 	data_len = data_len - btrfs_item_offset_nr(l, end);
31390783fcfcSChris Mason 	data_len += sizeof(struct btrfs_item) * nr;
3140d4dbff95SChris Mason 	WARN_ON(data_len < 0);
3141be0e5c09SChris Mason 	return data_len;
3142be0e5c09SChris Mason }
3143be0e5c09SChris Mason 
314474123bd7SChris Mason /*
3145d4dbff95SChris Mason  * The space between the end of the leaf items and
3146d4dbff95SChris Mason  * the start of the leaf data.  IOW, how much room
3147d4dbff95SChris Mason  * the leaf has left for both items and data
3148d4dbff95SChris Mason  */
3149d397712bSChris Mason noinline int btrfs_leaf_free_space(struct btrfs_root *root,
3150e02119d5SChris Mason 				   struct extent_buffer *leaf)
3151d4dbff95SChris Mason {
31525f39d397SChris Mason 	int nritems = btrfs_header_nritems(leaf);
31535f39d397SChris Mason 	int ret;
31545f39d397SChris Mason 	ret = BTRFS_LEAF_DATA_SIZE(root) - leaf_space_used(leaf, 0, nritems);
31555f39d397SChris Mason 	if (ret < 0) {
3156d397712bSChris Mason 		printk(KERN_CRIT "leaf free space ret %d, leaf data size %lu, "
3157d397712bSChris Mason 		       "used %d nritems %d\n",
3158ae2f5411SJens Axboe 		       ret, (unsigned long) BTRFS_LEAF_DATA_SIZE(root),
31595f39d397SChris Mason 		       leaf_space_used(leaf, 0, nritems), nritems);
31605f39d397SChris Mason 	}
31615f39d397SChris Mason 	return ret;
3162d4dbff95SChris Mason }
3163d4dbff95SChris Mason 
316499d8f83cSChris Mason /*
316599d8f83cSChris Mason  * min slot controls the lowest index we're willing to push to the
316699d8f83cSChris Mason  * right.  We'll push up to and including min_slot, but no lower
316799d8f83cSChris Mason  */
316844871b1bSChris Mason static noinline int __push_leaf_right(struct btrfs_trans_handle *trans,
316944871b1bSChris Mason 				      struct btrfs_root *root,
317044871b1bSChris Mason 				      struct btrfs_path *path,
317144871b1bSChris Mason 				      int data_size, int empty,
317244871b1bSChris Mason 				      struct extent_buffer *right,
317399d8f83cSChris Mason 				      int free_space, u32 left_nritems,
317499d8f83cSChris Mason 				      u32 min_slot)
317500ec4c51SChris Mason {
31765f39d397SChris Mason 	struct extent_buffer *left = path->nodes[0];
317744871b1bSChris Mason 	struct extent_buffer *upper = path->nodes[1];
3178cfed81a0SChris Mason 	struct btrfs_map_token token;
31795f39d397SChris Mason 	struct btrfs_disk_key disk_key;
318000ec4c51SChris Mason 	int slot;
318134a38218SChris Mason 	u32 i;
318200ec4c51SChris Mason 	int push_space = 0;
318300ec4c51SChris Mason 	int push_items = 0;
31840783fcfcSChris Mason 	struct btrfs_item *item;
318534a38218SChris Mason 	u32 nr;
31867518a238SChris Mason 	u32 right_nritems;
31875f39d397SChris Mason 	u32 data_end;
3188db94535dSChris Mason 	u32 this_item_size;
318900ec4c51SChris Mason 
3190cfed81a0SChris Mason 	btrfs_init_map_token(&token);
3191cfed81a0SChris Mason 
319234a38218SChris Mason 	if (empty)
319334a38218SChris Mason 		nr = 0;
319434a38218SChris Mason 	else
319599d8f83cSChris Mason 		nr = max_t(u32, 1, min_slot);
319634a38218SChris Mason 
319731840ae1SZheng Yan 	if (path->slots[0] >= left_nritems)
319887b29b20SYan Zheng 		push_space += data_size;
319931840ae1SZheng Yan 
320044871b1bSChris Mason 	slot = path->slots[1];
320134a38218SChris Mason 	i = left_nritems - 1;
320234a38218SChris Mason 	while (i >= nr) {
32035f39d397SChris Mason 		item = btrfs_item_nr(left, i);
3204db94535dSChris Mason 
320531840ae1SZheng Yan 		if (!empty && push_items > 0) {
320631840ae1SZheng Yan 			if (path->slots[0] > i)
320731840ae1SZheng Yan 				break;
320831840ae1SZheng Yan 			if (path->slots[0] == i) {
320931840ae1SZheng Yan 				int space = btrfs_leaf_free_space(root, left);
321031840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
321131840ae1SZheng Yan 					break;
321231840ae1SZheng Yan 			}
321331840ae1SZheng Yan 		}
321431840ae1SZheng Yan 
321500ec4c51SChris Mason 		if (path->slots[0] == i)
321687b29b20SYan Zheng 			push_space += data_size;
3217db94535dSChris Mason 
3218db94535dSChris Mason 		this_item_size = btrfs_item_size(left, item);
3219db94535dSChris Mason 		if (this_item_size + sizeof(*item) + push_space > free_space)
322000ec4c51SChris Mason 			break;
322131840ae1SZheng Yan 
322200ec4c51SChris Mason 		push_items++;
3223db94535dSChris Mason 		push_space += this_item_size + sizeof(*item);
322434a38218SChris Mason 		if (i == 0)
322534a38218SChris Mason 			break;
322634a38218SChris Mason 		i--;
3227db94535dSChris Mason 	}
32285f39d397SChris Mason 
3229925baeddSChris Mason 	if (push_items == 0)
3230925baeddSChris Mason 		goto out_unlock;
32315f39d397SChris Mason 
323234a38218SChris Mason 	if (!empty && push_items == left_nritems)
3233a429e513SChris Mason 		WARN_ON(1);
32345f39d397SChris Mason 
323500ec4c51SChris Mason 	/* push left to right */
32365f39d397SChris Mason 	right_nritems = btrfs_header_nritems(right);
323734a38218SChris Mason 
32385f39d397SChris Mason 	push_space = btrfs_item_end_nr(left, left_nritems - push_items);
3239123abc88SChris Mason 	push_space -= leaf_data_end(root, left);
32405f39d397SChris Mason 
324100ec4c51SChris Mason 	/* make room in the right data area */
32425f39d397SChris Mason 	data_end = leaf_data_end(root, right);
32435f39d397SChris Mason 	memmove_extent_buffer(right,
32445f39d397SChris Mason 			      btrfs_leaf_data(right) + data_end - push_space,
32455f39d397SChris Mason 			      btrfs_leaf_data(right) + data_end,
32465f39d397SChris Mason 			      BTRFS_LEAF_DATA_SIZE(root) - data_end);
32475f39d397SChris Mason 
324800ec4c51SChris Mason 	/* copy from the left data area */
32495f39d397SChris Mason 	copy_extent_buffer(right, left, btrfs_leaf_data(right) +
3250d6025579SChris Mason 		     BTRFS_LEAF_DATA_SIZE(root) - push_space,
3251d6025579SChris Mason 		     btrfs_leaf_data(left) + leaf_data_end(root, left),
3252d6025579SChris Mason 		     push_space);
32535f39d397SChris Mason 
32545f39d397SChris Mason 	memmove_extent_buffer(right, btrfs_item_nr_offset(push_items),
32555f39d397SChris Mason 			      btrfs_item_nr_offset(0),
32560783fcfcSChris Mason 			      right_nritems * sizeof(struct btrfs_item));
32575f39d397SChris Mason 
325800ec4c51SChris Mason 	/* copy the items from left to right */
32595f39d397SChris Mason 	copy_extent_buffer(right, left, btrfs_item_nr_offset(0),
32605f39d397SChris Mason 		   btrfs_item_nr_offset(left_nritems - push_items),
32610783fcfcSChris Mason 		   push_items * sizeof(struct btrfs_item));
326200ec4c51SChris Mason 
326300ec4c51SChris Mason 	/* update the item pointers */
32647518a238SChris Mason 	right_nritems += push_items;
32655f39d397SChris Mason 	btrfs_set_header_nritems(right, right_nritems);
3266123abc88SChris Mason 	push_space = BTRFS_LEAF_DATA_SIZE(root);
32677518a238SChris Mason 	for (i = 0; i < right_nritems; i++) {
32685f39d397SChris Mason 		item = btrfs_item_nr(right, i);
3269cfed81a0SChris Mason 		push_space -= btrfs_token_item_size(right, item, &token);
3270cfed81a0SChris Mason 		btrfs_set_token_item_offset(right, item, push_space, &token);
3271db94535dSChris Mason 	}
3272db94535dSChris Mason 
32737518a238SChris Mason 	left_nritems -= push_items;
32745f39d397SChris Mason 	btrfs_set_header_nritems(left, left_nritems);
327500ec4c51SChris Mason 
327634a38218SChris Mason 	if (left_nritems)
32775f39d397SChris Mason 		btrfs_mark_buffer_dirty(left);
3278f0486c68SYan, Zheng 	else
3279f0486c68SYan, Zheng 		clean_tree_block(trans, root, left);
3280f0486c68SYan, Zheng 
32815f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
3282a429e513SChris Mason 
32835f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
32845f39d397SChris Mason 	btrfs_set_node_key(upper, &disk_key, slot + 1);
3285d6025579SChris Mason 	btrfs_mark_buffer_dirty(upper);
328602217ed2SChris Mason 
328700ec4c51SChris Mason 	/* then fixup the leaf pointer in the path */
32887518a238SChris Mason 	if (path->slots[0] >= left_nritems) {
32897518a238SChris Mason 		path->slots[0] -= left_nritems;
3290925baeddSChris Mason 		if (btrfs_header_nritems(path->nodes[0]) == 0)
3291925baeddSChris Mason 			clean_tree_block(trans, root, path->nodes[0]);
3292925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
32935f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
32945f39d397SChris Mason 		path->nodes[0] = right;
329500ec4c51SChris Mason 		path->slots[1] += 1;
329600ec4c51SChris Mason 	} else {
3297925baeddSChris Mason 		btrfs_tree_unlock(right);
32985f39d397SChris Mason 		free_extent_buffer(right);
329900ec4c51SChris Mason 	}
330000ec4c51SChris Mason 	return 0;
3301925baeddSChris Mason 
3302925baeddSChris Mason out_unlock:
3303925baeddSChris Mason 	btrfs_tree_unlock(right);
3304925baeddSChris Mason 	free_extent_buffer(right);
3305925baeddSChris Mason 	return 1;
330600ec4c51SChris Mason }
3307925baeddSChris Mason 
330800ec4c51SChris Mason /*
330944871b1bSChris Mason  * push some data in the path leaf to the right, trying to free up at
331074123bd7SChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
331144871b1bSChris Mason  *
331244871b1bSChris Mason  * returns 1 if the push failed because the other node didn't have enough
331344871b1bSChris Mason  * room, 0 if everything worked out and < 0 if there were major errors.
331499d8f83cSChris Mason  *
331599d8f83cSChris Mason  * this will push starting from min_slot to the end of the leaf.  It won't
331699d8f83cSChris Mason  * push any slot lower than min_slot
331774123bd7SChris Mason  */
331844871b1bSChris Mason static int push_leaf_right(struct btrfs_trans_handle *trans, struct btrfs_root
331999d8f83cSChris Mason 			   *root, struct btrfs_path *path,
332099d8f83cSChris Mason 			   int min_data_size, int data_size,
332199d8f83cSChris Mason 			   int empty, u32 min_slot)
3322be0e5c09SChris Mason {
332344871b1bSChris Mason 	struct extent_buffer *left = path->nodes[0];
332444871b1bSChris Mason 	struct extent_buffer *right;
332544871b1bSChris Mason 	struct extent_buffer *upper;
332644871b1bSChris Mason 	int slot;
332744871b1bSChris Mason 	int free_space;
332844871b1bSChris Mason 	u32 left_nritems;
332944871b1bSChris Mason 	int ret;
333044871b1bSChris Mason 
333144871b1bSChris Mason 	if (!path->nodes[1])
333244871b1bSChris Mason 		return 1;
333344871b1bSChris Mason 
333444871b1bSChris Mason 	slot = path->slots[1];
333544871b1bSChris Mason 	upper = path->nodes[1];
333644871b1bSChris Mason 	if (slot >= btrfs_header_nritems(upper) - 1)
333744871b1bSChris Mason 		return 1;
333844871b1bSChris Mason 
333944871b1bSChris Mason 	btrfs_assert_tree_locked(path->nodes[1]);
334044871b1bSChris Mason 
334144871b1bSChris Mason 	right = read_node_slot(root, upper, slot + 1);
334291ca338dSTsutomu Itoh 	if (right == NULL)
334391ca338dSTsutomu Itoh 		return 1;
334491ca338dSTsutomu Itoh 
334544871b1bSChris Mason 	btrfs_tree_lock(right);
334644871b1bSChris Mason 	btrfs_set_lock_blocking(right);
334744871b1bSChris Mason 
334844871b1bSChris Mason 	free_space = btrfs_leaf_free_space(root, right);
334944871b1bSChris Mason 	if (free_space < data_size)
335044871b1bSChris Mason 		goto out_unlock;
335144871b1bSChris Mason 
335244871b1bSChris Mason 	/* cow and double check */
335344871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, right, upper,
335444871b1bSChris Mason 			      slot + 1, &right);
335544871b1bSChris Mason 	if (ret)
335644871b1bSChris Mason 		goto out_unlock;
335744871b1bSChris Mason 
335844871b1bSChris Mason 	free_space = btrfs_leaf_free_space(root, right);
335944871b1bSChris Mason 	if (free_space < data_size)
336044871b1bSChris Mason 		goto out_unlock;
336144871b1bSChris Mason 
336244871b1bSChris Mason 	left_nritems = btrfs_header_nritems(left);
336344871b1bSChris Mason 	if (left_nritems == 0)
336444871b1bSChris Mason 		goto out_unlock;
336544871b1bSChris Mason 
336699d8f83cSChris Mason 	return __push_leaf_right(trans, root, path, min_data_size, empty,
336799d8f83cSChris Mason 				right, free_space, left_nritems, min_slot);
336844871b1bSChris Mason out_unlock:
336944871b1bSChris Mason 	btrfs_tree_unlock(right);
337044871b1bSChris Mason 	free_extent_buffer(right);
337144871b1bSChris Mason 	return 1;
337244871b1bSChris Mason }
337344871b1bSChris Mason 
337444871b1bSChris Mason /*
337544871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
337644871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
337799d8f83cSChris Mason  *
337899d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
337999d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us do all the
338099d8f83cSChris Mason  * items
338144871b1bSChris Mason  */
338244871b1bSChris Mason static noinline int __push_leaf_left(struct btrfs_trans_handle *trans,
338344871b1bSChris Mason 				     struct btrfs_root *root,
338444871b1bSChris Mason 				     struct btrfs_path *path, int data_size,
338544871b1bSChris Mason 				     int empty, struct extent_buffer *left,
338699d8f83cSChris Mason 				     int free_space, u32 right_nritems,
338799d8f83cSChris Mason 				     u32 max_slot)
338844871b1bSChris Mason {
33895f39d397SChris Mason 	struct btrfs_disk_key disk_key;
33905f39d397SChris Mason 	struct extent_buffer *right = path->nodes[0];
3391be0e5c09SChris Mason 	int i;
3392be0e5c09SChris Mason 	int push_space = 0;
3393be0e5c09SChris Mason 	int push_items = 0;
33940783fcfcSChris Mason 	struct btrfs_item *item;
33957518a238SChris Mason 	u32 old_left_nritems;
339634a38218SChris Mason 	u32 nr;
3397aa5d6bedSChris Mason 	int ret = 0;
3398db94535dSChris Mason 	u32 this_item_size;
3399db94535dSChris Mason 	u32 old_left_item_size;
3400cfed81a0SChris Mason 	struct btrfs_map_token token;
3401cfed81a0SChris Mason 
3402cfed81a0SChris Mason 	btrfs_init_map_token(&token);
3403be0e5c09SChris Mason 
340434a38218SChris Mason 	if (empty)
340599d8f83cSChris Mason 		nr = min(right_nritems, max_slot);
340634a38218SChris Mason 	else
340799d8f83cSChris Mason 		nr = min(right_nritems - 1, max_slot);
340834a38218SChris Mason 
340934a38218SChris Mason 	for (i = 0; i < nr; i++) {
34105f39d397SChris Mason 		item = btrfs_item_nr(right, i);
3411db94535dSChris Mason 
341231840ae1SZheng Yan 		if (!empty && push_items > 0) {
341331840ae1SZheng Yan 			if (path->slots[0] < i)
341431840ae1SZheng Yan 				break;
341531840ae1SZheng Yan 			if (path->slots[0] == i) {
341631840ae1SZheng Yan 				int space = btrfs_leaf_free_space(root, right);
341731840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
341831840ae1SZheng Yan 					break;
341931840ae1SZheng Yan 			}
342031840ae1SZheng Yan 		}
342131840ae1SZheng Yan 
3422be0e5c09SChris Mason 		if (path->slots[0] == i)
342387b29b20SYan Zheng 			push_space += data_size;
3424db94535dSChris Mason 
3425db94535dSChris Mason 		this_item_size = btrfs_item_size(right, item);
3426db94535dSChris Mason 		if (this_item_size + sizeof(*item) + push_space > free_space)
3427be0e5c09SChris Mason 			break;
3428db94535dSChris Mason 
3429be0e5c09SChris Mason 		push_items++;
3430db94535dSChris Mason 		push_space += this_item_size + sizeof(*item);
3431be0e5c09SChris Mason 	}
3432db94535dSChris Mason 
3433be0e5c09SChris Mason 	if (push_items == 0) {
3434925baeddSChris Mason 		ret = 1;
3435925baeddSChris Mason 		goto out;
3436be0e5c09SChris Mason 	}
343734a38218SChris Mason 	if (!empty && push_items == btrfs_header_nritems(right))
3438a429e513SChris Mason 		WARN_ON(1);
34395f39d397SChris Mason 
3440be0e5c09SChris Mason 	/* push data from right to left */
34415f39d397SChris Mason 	copy_extent_buffer(left, right,
34425f39d397SChris Mason 			   btrfs_item_nr_offset(btrfs_header_nritems(left)),
34435f39d397SChris Mason 			   btrfs_item_nr_offset(0),
34445f39d397SChris Mason 			   push_items * sizeof(struct btrfs_item));
34455f39d397SChris Mason 
3446123abc88SChris Mason 	push_space = BTRFS_LEAF_DATA_SIZE(root) -
34475f39d397SChris Mason 		     btrfs_item_offset_nr(right, push_items - 1);
34485f39d397SChris Mason 
34495f39d397SChris Mason 	copy_extent_buffer(left, right, btrfs_leaf_data(left) +
3450d6025579SChris Mason 		     leaf_data_end(root, left) - push_space,
3451123abc88SChris Mason 		     btrfs_leaf_data(right) +
34525f39d397SChris Mason 		     btrfs_item_offset_nr(right, push_items - 1),
3453be0e5c09SChris Mason 		     push_space);
34545f39d397SChris Mason 	old_left_nritems = btrfs_header_nritems(left);
345587b29b20SYan Zheng 	BUG_ON(old_left_nritems <= 0);
3456eb60ceacSChris Mason 
3457db94535dSChris Mason 	old_left_item_size = btrfs_item_offset_nr(left, old_left_nritems - 1);
3458be0e5c09SChris Mason 	for (i = old_left_nritems; i < old_left_nritems + push_items; i++) {
34595f39d397SChris Mason 		u32 ioff;
3460db94535dSChris Mason 
34615f39d397SChris Mason 		item = btrfs_item_nr(left, i);
3462db94535dSChris Mason 
3463cfed81a0SChris Mason 		ioff = btrfs_token_item_offset(left, item, &token);
3464cfed81a0SChris Mason 		btrfs_set_token_item_offset(left, item,
3465cfed81a0SChris Mason 		      ioff - (BTRFS_LEAF_DATA_SIZE(root) - old_left_item_size),
3466cfed81a0SChris Mason 		      &token);
3467be0e5c09SChris Mason 	}
34685f39d397SChris Mason 	btrfs_set_header_nritems(left, old_left_nritems + push_items);
3469be0e5c09SChris Mason 
3470be0e5c09SChris Mason 	/* fixup right node */
347134a38218SChris Mason 	if (push_items > right_nritems) {
3472d397712bSChris Mason 		printk(KERN_CRIT "push items %d nr %u\n", push_items,
3473d397712bSChris Mason 		       right_nritems);
347434a38218SChris Mason 		WARN_ON(1);
347534a38218SChris Mason 	}
347634a38218SChris Mason 
347734a38218SChris Mason 	if (push_items < right_nritems) {
34785f39d397SChris Mason 		push_space = btrfs_item_offset_nr(right, push_items - 1) -
3479123abc88SChris Mason 						  leaf_data_end(root, right);
34805f39d397SChris Mason 		memmove_extent_buffer(right, btrfs_leaf_data(right) +
3481d6025579SChris Mason 				      BTRFS_LEAF_DATA_SIZE(root) - push_space,
3482d6025579SChris Mason 				      btrfs_leaf_data(right) +
3483123abc88SChris Mason 				      leaf_data_end(root, right), push_space);
34845f39d397SChris Mason 
34855f39d397SChris Mason 		memmove_extent_buffer(right, btrfs_item_nr_offset(0),
34865f39d397SChris Mason 			      btrfs_item_nr_offset(push_items),
34875f39d397SChris Mason 			     (btrfs_header_nritems(right) - push_items) *
34880783fcfcSChris Mason 			     sizeof(struct btrfs_item));
348934a38218SChris Mason 	}
3490eef1c494SYan 	right_nritems -= push_items;
3491eef1c494SYan 	btrfs_set_header_nritems(right, right_nritems);
3492123abc88SChris Mason 	push_space = BTRFS_LEAF_DATA_SIZE(root);
34935f39d397SChris Mason 	for (i = 0; i < right_nritems; i++) {
34945f39d397SChris Mason 		item = btrfs_item_nr(right, i);
3495db94535dSChris Mason 
3496cfed81a0SChris Mason 		push_space = push_space - btrfs_token_item_size(right,
3497cfed81a0SChris Mason 								item, &token);
3498cfed81a0SChris Mason 		btrfs_set_token_item_offset(right, item, push_space, &token);
3499db94535dSChris Mason 	}
3500eb60ceacSChris Mason 
35015f39d397SChris Mason 	btrfs_mark_buffer_dirty(left);
350234a38218SChris Mason 	if (right_nritems)
35035f39d397SChris Mason 		btrfs_mark_buffer_dirty(right);
3504f0486c68SYan, Zheng 	else
3505f0486c68SYan, Zheng 		clean_tree_block(trans, root, right);
3506098f59c2SChris Mason 
35075f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
3508143bede5SJeff Mahoney 	fixup_low_keys(trans, root, path, &disk_key, 1);
3509be0e5c09SChris Mason 
3510be0e5c09SChris Mason 	/* then fixup the leaf pointer in the path */
3511be0e5c09SChris Mason 	if (path->slots[0] < push_items) {
3512be0e5c09SChris Mason 		path->slots[0] += old_left_nritems;
3513925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
35145f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
35155f39d397SChris Mason 		path->nodes[0] = left;
3516be0e5c09SChris Mason 		path->slots[1] -= 1;
3517be0e5c09SChris Mason 	} else {
3518925baeddSChris Mason 		btrfs_tree_unlock(left);
35195f39d397SChris Mason 		free_extent_buffer(left);
3520be0e5c09SChris Mason 		path->slots[0] -= push_items;
3521be0e5c09SChris Mason 	}
3522eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
3523aa5d6bedSChris Mason 	return ret;
3524925baeddSChris Mason out:
3525925baeddSChris Mason 	btrfs_tree_unlock(left);
3526925baeddSChris Mason 	free_extent_buffer(left);
3527925baeddSChris Mason 	return ret;
3528be0e5c09SChris Mason }
3529be0e5c09SChris Mason 
353074123bd7SChris Mason /*
353144871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
353244871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
353399d8f83cSChris Mason  *
353499d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
353599d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us push all the
353699d8f83cSChris Mason  * items
353744871b1bSChris Mason  */
353844871b1bSChris Mason static int push_leaf_left(struct btrfs_trans_handle *trans, struct btrfs_root
353999d8f83cSChris Mason 			  *root, struct btrfs_path *path, int min_data_size,
354099d8f83cSChris Mason 			  int data_size, int empty, u32 max_slot)
354144871b1bSChris Mason {
354244871b1bSChris Mason 	struct extent_buffer *right = path->nodes[0];
354344871b1bSChris Mason 	struct extent_buffer *left;
354444871b1bSChris Mason 	int slot;
354544871b1bSChris Mason 	int free_space;
354644871b1bSChris Mason 	u32 right_nritems;
354744871b1bSChris Mason 	int ret = 0;
354844871b1bSChris Mason 
354944871b1bSChris Mason 	slot = path->slots[1];
355044871b1bSChris Mason 	if (slot == 0)
355144871b1bSChris Mason 		return 1;
355244871b1bSChris Mason 	if (!path->nodes[1])
355344871b1bSChris Mason 		return 1;
355444871b1bSChris Mason 
355544871b1bSChris Mason 	right_nritems = btrfs_header_nritems(right);
355644871b1bSChris Mason 	if (right_nritems == 0)
355744871b1bSChris Mason 		return 1;
355844871b1bSChris Mason 
355944871b1bSChris Mason 	btrfs_assert_tree_locked(path->nodes[1]);
356044871b1bSChris Mason 
356144871b1bSChris Mason 	left = read_node_slot(root, path->nodes[1], slot - 1);
356291ca338dSTsutomu Itoh 	if (left == NULL)
356391ca338dSTsutomu Itoh 		return 1;
356491ca338dSTsutomu Itoh 
356544871b1bSChris Mason 	btrfs_tree_lock(left);
356644871b1bSChris Mason 	btrfs_set_lock_blocking(left);
356744871b1bSChris Mason 
356844871b1bSChris Mason 	free_space = btrfs_leaf_free_space(root, left);
356944871b1bSChris Mason 	if (free_space < data_size) {
357044871b1bSChris Mason 		ret = 1;
357144871b1bSChris Mason 		goto out;
357244871b1bSChris Mason 	}
357344871b1bSChris Mason 
357444871b1bSChris Mason 	/* cow and double check */
357544871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, left,
357644871b1bSChris Mason 			      path->nodes[1], slot - 1, &left);
357744871b1bSChris Mason 	if (ret) {
357844871b1bSChris Mason 		/* we hit -ENOSPC, but it isn't fatal here */
357979787eaaSJeff Mahoney 		if (ret == -ENOSPC)
358044871b1bSChris Mason 			ret = 1;
358144871b1bSChris Mason 		goto out;
358244871b1bSChris Mason 	}
358344871b1bSChris Mason 
358444871b1bSChris Mason 	free_space = btrfs_leaf_free_space(root, left);
358544871b1bSChris Mason 	if (free_space < data_size) {
358644871b1bSChris Mason 		ret = 1;
358744871b1bSChris Mason 		goto out;
358844871b1bSChris Mason 	}
358944871b1bSChris Mason 
359099d8f83cSChris Mason 	return __push_leaf_left(trans, root, path, min_data_size,
359199d8f83cSChris Mason 			       empty, left, free_space, right_nritems,
359299d8f83cSChris Mason 			       max_slot);
359344871b1bSChris Mason out:
359444871b1bSChris Mason 	btrfs_tree_unlock(left);
359544871b1bSChris Mason 	free_extent_buffer(left);
359644871b1bSChris Mason 	return ret;
359744871b1bSChris Mason }
359844871b1bSChris Mason 
359944871b1bSChris Mason /*
360074123bd7SChris Mason  * split the path's leaf in two, making sure there is at least data_size
360174123bd7SChris Mason  * available for the resulting leaf level of the path.
360274123bd7SChris Mason  */
3603143bede5SJeff Mahoney static noinline void copy_for_split(struct btrfs_trans_handle *trans,
3604e02119d5SChris Mason 				    struct btrfs_root *root,
360544871b1bSChris Mason 				    struct btrfs_path *path,
360644871b1bSChris Mason 				    struct extent_buffer *l,
360744871b1bSChris Mason 				    struct extent_buffer *right,
360844871b1bSChris Mason 				    int slot, int mid, int nritems)
3609be0e5c09SChris Mason {
3610be0e5c09SChris Mason 	int data_copy_size;
3611be0e5c09SChris Mason 	int rt_data_off;
3612be0e5c09SChris Mason 	int i;
3613d4dbff95SChris Mason 	struct btrfs_disk_key disk_key;
3614cfed81a0SChris Mason 	struct btrfs_map_token token;
3615cfed81a0SChris Mason 
3616cfed81a0SChris Mason 	btrfs_init_map_token(&token);
3617be0e5c09SChris Mason 
36185f39d397SChris Mason 	nritems = nritems - mid;
36195f39d397SChris Mason 	btrfs_set_header_nritems(right, nritems);
36205f39d397SChris Mason 	data_copy_size = btrfs_item_end_nr(l, mid) - leaf_data_end(root, l);
36215f39d397SChris Mason 
36225f39d397SChris Mason 	copy_extent_buffer(right, l, btrfs_item_nr_offset(0),
36235f39d397SChris Mason 			   btrfs_item_nr_offset(mid),
36245f39d397SChris Mason 			   nritems * sizeof(struct btrfs_item));
36255f39d397SChris Mason 
36265f39d397SChris Mason 	copy_extent_buffer(right, l,
3627d6025579SChris Mason 		     btrfs_leaf_data(right) + BTRFS_LEAF_DATA_SIZE(root) -
3628123abc88SChris Mason 		     data_copy_size, btrfs_leaf_data(l) +
3629123abc88SChris Mason 		     leaf_data_end(root, l), data_copy_size);
363074123bd7SChris Mason 
36315f39d397SChris Mason 	rt_data_off = BTRFS_LEAF_DATA_SIZE(root) -
36325f39d397SChris Mason 		      btrfs_item_end_nr(l, mid);
36335f39d397SChris Mason 
36345f39d397SChris Mason 	for (i = 0; i < nritems; i++) {
36355f39d397SChris Mason 		struct btrfs_item *item = btrfs_item_nr(right, i);
3636db94535dSChris Mason 		u32 ioff;
3637db94535dSChris Mason 
3638cfed81a0SChris Mason 		ioff = btrfs_token_item_offset(right, item, &token);
3639cfed81a0SChris Mason 		btrfs_set_token_item_offset(right, item,
3640cfed81a0SChris Mason 					    ioff + rt_data_off, &token);
36410783fcfcSChris Mason 	}
364274123bd7SChris Mason 
36435f39d397SChris Mason 	btrfs_set_header_nritems(l, mid);
36445f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
3645143bede5SJeff Mahoney 	insert_ptr(trans, root, path, &disk_key, right->start,
3646f3ea38daSJan Schmidt 		   path->slots[1] + 1, 1, 0);
36475f39d397SChris Mason 
36485f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
36495f39d397SChris Mason 	btrfs_mark_buffer_dirty(l);
3650eb60ceacSChris Mason 	BUG_ON(path->slots[0] != slot);
36515f39d397SChris Mason 
3652be0e5c09SChris Mason 	if (mid <= slot) {
3653925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
36545f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
36555f39d397SChris Mason 		path->nodes[0] = right;
3656be0e5c09SChris Mason 		path->slots[0] -= mid;
3657be0e5c09SChris Mason 		path->slots[1] += 1;
3658925baeddSChris Mason 	} else {
3659925baeddSChris Mason 		btrfs_tree_unlock(right);
36605f39d397SChris Mason 		free_extent_buffer(right);
3661925baeddSChris Mason 	}
36625f39d397SChris Mason 
3663eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
366444871b1bSChris Mason }
366544871b1bSChris Mason 
366644871b1bSChris Mason /*
366799d8f83cSChris Mason  * double splits happen when we need to insert a big item in the middle
366899d8f83cSChris Mason  * of a leaf.  A double split can leave us with 3 mostly empty leaves:
366999d8f83cSChris Mason  * leaf: [ slots 0 - N] [ our target ] [ N + 1 - total in leaf ]
367099d8f83cSChris Mason  *          A                 B                 C
367199d8f83cSChris Mason  *
367299d8f83cSChris Mason  * We avoid this by trying to push the items on either side of our target
367399d8f83cSChris Mason  * into the adjacent leaves.  If all goes well we can avoid the double split
367499d8f83cSChris Mason  * completely.
367599d8f83cSChris Mason  */
367699d8f83cSChris Mason static noinline int push_for_double_split(struct btrfs_trans_handle *trans,
367799d8f83cSChris Mason 					  struct btrfs_root *root,
367899d8f83cSChris Mason 					  struct btrfs_path *path,
367999d8f83cSChris Mason 					  int data_size)
368099d8f83cSChris Mason {
368199d8f83cSChris Mason 	int ret;
368299d8f83cSChris Mason 	int progress = 0;
368399d8f83cSChris Mason 	int slot;
368499d8f83cSChris Mason 	u32 nritems;
368599d8f83cSChris Mason 
368699d8f83cSChris Mason 	slot = path->slots[0];
368799d8f83cSChris Mason 
368899d8f83cSChris Mason 	/*
368999d8f83cSChris Mason 	 * try to push all the items after our slot into the
369099d8f83cSChris Mason 	 * right leaf
369199d8f83cSChris Mason 	 */
369299d8f83cSChris Mason 	ret = push_leaf_right(trans, root, path, 1, data_size, 0, slot);
369399d8f83cSChris Mason 	if (ret < 0)
369499d8f83cSChris Mason 		return ret;
369599d8f83cSChris Mason 
369699d8f83cSChris Mason 	if (ret == 0)
369799d8f83cSChris Mason 		progress++;
369899d8f83cSChris Mason 
369999d8f83cSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
370099d8f83cSChris Mason 	/*
370199d8f83cSChris Mason 	 * our goal is to get our slot at the start or end of a leaf.  If
370299d8f83cSChris Mason 	 * we've done so we're done
370399d8f83cSChris Mason 	 */
370499d8f83cSChris Mason 	if (path->slots[0] == 0 || path->slots[0] == nritems)
370599d8f83cSChris Mason 		return 0;
370699d8f83cSChris Mason 
370799d8f83cSChris Mason 	if (btrfs_leaf_free_space(root, path->nodes[0]) >= data_size)
370899d8f83cSChris Mason 		return 0;
370999d8f83cSChris Mason 
371099d8f83cSChris Mason 	/* try to push all the items before our slot into the next leaf */
371199d8f83cSChris Mason 	slot = path->slots[0];
371299d8f83cSChris Mason 	ret = push_leaf_left(trans, root, path, 1, data_size, 0, slot);
371399d8f83cSChris Mason 	if (ret < 0)
371499d8f83cSChris Mason 		return ret;
371599d8f83cSChris Mason 
371699d8f83cSChris Mason 	if (ret == 0)
371799d8f83cSChris Mason 		progress++;
371899d8f83cSChris Mason 
371999d8f83cSChris Mason 	if (progress)
372099d8f83cSChris Mason 		return 0;
372199d8f83cSChris Mason 	return 1;
372299d8f83cSChris Mason }
372399d8f83cSChris Mason 
372499d8f83cSChris Mason /*
372544871b1bSChris Mason  * split the path's leaf in two, making sure there is at least data_size
372644871b1bSChris Mason  * available for the resulting leaf level of the path.
372744871b1bSChris Mason  *
372844871b1bSChris Mason  * returns 0 if all went well and < 0 on failure.
372944871b1bSChris Mason  */
373044871b1bSChris Mason static noinline int split_leaf(struct btrfs_trans_handle *trans,
373144871b1bSChris Mason 			       struct btrfs_root *root,
373244871b1bSChris Mason 			       struct btrfs_key *ins_key,
373344871b1bSChris Mason 			       struct btrfs_path *path, int data_size,
373444871b1bSChris Mason 			       int extend)
373544871b1bSChris Mason {
37365d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
373744871b1bSChris Mason 	struct extent_buffer *l;
373844871b1bSChris Mason 	u32 nritems;
373944871b1bSChris Mason 	int mid;
374044871b1bSChris Mason 	int slot;
374144871b1bSChris Mason 	struct extent_buffer *right;
374244871b1bSChris Mason 	int ret = 0;
374344871b1bSChris Mason 	int wret;
37445d4f98a2SYan Zheng 	int split;
374544871b1bSChris Mason 	int num_doubles = 0;
374699d8f83cSChris Mason 	int tried_avoid_double = 0;
374744871b1bSChris Mason 
3748a5719521SYan, Zheng 	l = path->nodes[0];
3749a5719521SYan, Zheng 	slot = path->slots[0];
3750a5719521SYan, Zheng 	if (extend && data_size + btrfs_item_size_nr(l, slot) +
3751a5719521SYan, Zheng 	    sizeof(struct btrfs_item) > BTRFS_LEAF_DATA_SIZE(root))
3752a5719521SYan, Zheng 		return -EOVERFLOW;
3753a5719521SYan, Zheng 
375444871b1bSChris Mason 	/* first try to make some room by pushing left and right */
375599d8f83cSChris Mason 	if (data_size) {
375699d8f83cSChris Mason 		wret = push_leaf_right(trans, root, path, data_size,
375799d8f83cSChris Mason 				       data_size, 0, 0);
375844871b1bSChris Mason 		if (wret < 0)
375944871b1bSChris Mason 			return wret;
376044871b1bSChris Mason 		if (wret) {
376199d8f83cSChris Mason 			wret = push_leaf_left(trans, root, path, data_size,
376299d8f83cSChris Mason 					      data_size, 0, (u32)-1);
376344871b1bSChris Mason 			if (wret < 0)
376444871b1bSChris Mason 				return wret;
376544871b1bSChris Mason 		}
376644871b1bSChris Mason 		l = path->nodes[0];
376744871b1bSChris Mason 
376844871b1bSChris Mason 		/* did the pushes work? */
376944871b1bSChris Mason 		if (btrfs_leaf_free_space(root, l) >= data_size)
377044871b1bSChris Mason 			return 0;
377144871b1bSChris Mason 	}
377244871b1bSChris Mason 
377344871b1bSChris Mason 	if (!path->nodes[1]) {
377444871b1bSChris Mason 		ret = insert_new_root(trans, root, path, 1);
377544871b1bSChris Mason 		if (ret)
377644871b1bSChris Mason 			return ret;
377744871b1bSChris Mason 	}
377844871b1bSChris Mason again:
37795d4f98a2SYan Zheng 	split = 1;
378044871b1bSChris Mason 	l = path->nodes[0];
378144871b1bSChris Mason 	slot = path->slots[0];
378244871b1bSChris Mason 	nritems = btrfs_header_nritems(l);
378344871b1bSChris Mason 	mid = (nritems + 1) / 2;
378444871b1bSChris Mason 
37855d4f98a2SYan Zheng 	if (mid <= slot) {
37865d4f98a2SYan Zheng 		if (nritems == 1 ||
37875d4f98a2SYan Zheng 		    leaf_space_used(l, mid, nritems - mid) + data_size >
37885d4f98a2SYan Zheng 			BTRFS_LEAF_DATA_SIZE(root)) {
37895d4f98a2SYan Zheng 			if (slot >= nritems) {
37905d4f98a2SYan Zheng 				split = 0;
37915d4f98a2SYan Zheng 			} else {
37925d4f98a2SYan Zheng 				mid = slot;
37935d4f98a2SYan Zheng 				if (mid != nritems &&
37945d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
37955d4f98a2SYan Zheng 				    data_size > BTRFS_LEAF_DATA_SIZE(root)) {
379699d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
379799d8f83cSChris Mason 						goto push_for_double;
37985d4f98a2SYan Zheng 					split = 2;
37995d4f98a2SYan Zheng 				}
38005d4f98a2SYan Zheng 			}
38015d4f98a2SYan Zheng 		}
38025d4f98a2SYan Zheng 	} else {
38035d4f98a2SYan Zheng 		if (leaf_space_used(l, 0, mid) + data_size >
38045d4f98a2SYan Zheng 			BTRFS_LEAF_DATA_SIZE(root)) {
38055d4f98a2SYan Zheng 			if (!extend && data_size && slot == 0) {
38065d4f98a2SYan Zheng 				split = 0;
38075d4f98a2SYan Zheng 			} else if ((extend || !data_size) && slot == 0) {
38085d4f98a2SYan Zheng 				mid = 1;
38095d4f98a2SYan Zheng 			} else {
38105d4f98a2SYan Zheng 				mid = slot;
38115d4f98a2SYan Zheng 				if (mid != nritems &&
38125d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
38135d4f98a2SYan Zheng 				    data_size > BTRFS_LEAF_DATA_SIZE(root)) {
381499d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
381599d8f83cSChris Mason 						goto push_for_double;
38165d4f98a2SYan Zheng 					split = 2 ;
38175d4f98a2SYan Zheng 				}
38185d4f98a2SYan Zheng 			}
38195d4f98a2SYan Zheng 		}
38205d4f98a2SYan Zheng 	}
38215d4f98a2SYan Zheng 
38225d4f98a2SYan Zheng 	if (split == 0)
38235d4f98a2SYan Zheng 		btrfs_cpu_key_to_disk(&disk_key, ins_key);
38245d4f98a2SYan Zheng 	else
38255d4f98a2SYan Zheng 		btrfs_item_key(l, &disk_key, mid);
38265d4f98a2SYan Zheng 
38275d4f98a2SYan Zheng 	right = btrfs_alloc_free_block(trans, root, root->leafsize, 0,
382844871b1bSChris Mason 					root->root_key.objectid,
38295581a51aSJan Schmidt 					&disk_key, 0, l->start, 0);
3830f0486c68SYan, Zheng 	if (IS_ERR(right))
383144871b1bSChris Mason 		return PTR_ERR(right);
3832f0486c68SYan, Zheng 
3833f0486c68SYan, Zheng 	root_add_used(root, root->leafsize);
383444871b1bSChris Mason 
383544871b1bSChris Mason 	memset_extent_buffer(right, 0, 0, sizeof(struct btrfs_header));
383644871b1bSChris Mason 	btrfs_set_header_bytenr(right, right->start);
383744871b1bSChris Mason 	btrfs_set_header_generation(right, trans->transid);
38385d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(right, BTRFS_MIXED_BACKREF_REV);
383944871b1bSChris Mason 	btrfs_set_header_owner(right, root->root_key.objectid);
384044871b1bSChris Mason 	btrfs_set_header_level(right, 0);
384144871b1bSChris Mason 	write_extent_buffer(right, root->fs_info->fsid,
384244871b1bSChris Mason 			    (unsigned long)btrfs_header_fsid(right),
384344871b1bSChris Mason 			    BTRFS_FSID_SIZE);
384444871b1bSChris Mason 
384544871b1bSChris Mason 	write_extent_buffer(right, root->fs_info->chunk_tree_uuid,
384644871b1bSChris Mason 			    (unsigned long)btrfs_header_chunk_tree_uuid(right),
384744871b1bSChris Mason 			    BTRFS_UUID_SIZE);
384844871b1bSChris Mason 
38495d4f98a2SYan Zheng 	if (split == 0) {
385044871b1bSChris Mason 		if (mid <= slot) {
385144871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
3852143bede5SJeff Mahoney 			insert_ptr(trans, root, path, &disk_key, right->start,
3853f3ea38daSJan Schmidt 				   path->slots[1] + 1, 1, 0);
385444871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
385544871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
385644871b1bSChris Mason 			path->nodes[0] = right;
385744871b1bSChris Mason 			path->slots[0] = 0;
385844871b1bSChris Mason 			path->slots[1] += 1;
385944871b1bSChris Mason 		} else {
386044871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
3861143bede5SJeff Mahoney 			insert_ptr(trans, root, path, &disk_key, right->start,
3862f3ea38daSJan Schmidt 					  path->slots[1], 1, 0);
386344871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
386444871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
386544871b1bSChris Mason 			path->nodes[0] = right;
386644871b1bSChris Mason 			path->slots[0] = 0;
3867143bede5SJeff Mahoney 			if (path->slots[1] == 0)
3868143bede5SJeff Mahoney 				fixup_low_keys(trans, root, path,
3869143bede5SJeff Mahoney 					       &disk_key, 1);
38705d4f98a2SYan Zheng 		}
387144871b1bSChris Mason 		btrfs_mark_buffer_dirty(right);
387244871b1bSChris Mason 		return ret;
387344871b1bSChris Mason 	}
387444871b1bSChris Mason 
3875143bede5SJeff Mahoney 	copy_for_split(trans, root, path, l, right, slot, mid, nritems);
387644871b1bSChris Mason 
38775d4f98a2SYan Zheng 	if (split == 2) {
3878cc0c5538SChris Mason 		BUG_ON(num_doubles != 0);
3879cc0c5538SChris Mason 		num_doubles++;
3880cc0c5538SChris Mason 		goto again;
38813326d1b0SChris Mason 	}
388244871b1bSChris Mason 
3883143bede5SJeff Mahoney 	return 0;
388499d8f83cSChris Mason 
388599d8f83cSChris Mason push_for_double:
388699d8f83cSChris Mason 	push_for_double_split(trans, root, path, data_size);
388799d8f83cSChris Mason 	tried_avoid_double = 1;
388899d8f83cSChris Mason 	if (btrfs_leaf_free_space(root, path->nodes[0]) >= data_size)
388999d8f83cSChris Mason 		return 0;
389099d8f83cSChris Mason 	goto again;
3891be0e5c09SChris Mason }
3892be0e5c09SChris Mason 
3893ad48fd75SYan, Zheng static noinline int setup_leaf_for_split(struct btrfs_trans_handle *trans,
3894ad48fd75SYan, Zheng 					 struct btrfs_root *root,
3895ad48fd75SYan, Zheng 					 struct btrfs_path *path, int ins_len)
3896ad48fd75SYan, Zheng {
3897ad48fd75SYan, Zheng 	struct btrfs_key key;
3898ad48fd75SYan, Zheng 	struct extent_buffer *leaf;
3899ad48fd75SYan, Zheng 	struct btrfs_file_extent_item *fi;
3900ad48fd75SYan, Zheng 	u64 extent_len = 0;
3901ad48fd75SYan, Zheng 	u32 item_size;
3902ad48fd75SYan, Zheng 	int ret;
3903ad48fd75SYan, Zheng 
3904ad48fd75SYan, Zheng 	leaf = path->nodes[0];
3905ad48fd75SYan, Zheng 	btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3906ad48fd75SYan, Zheng 
3907ad48fd75SYan, Zheng 	BUG_ON(key.type != BTRFS_EXTENT_DATA_KEY &&
3908ad48fd75SYan, Zheng 	       key.type != BTRFS_EXTENT_CSUM_KEY);
3909ad48fd75SYan, Zheng 
3910ad48fd75SYan, Zheng 	if (btrfs_leaf_free_space(root, leaf) >= ins_len)
3911ad48fd75SYan, Zheng 		return 0;
3912ad48fd75SYan, Zheng 
3913ad48fd75SYan, Zheng 	item_size = btrfs_item_size_nr(leaf, path->slots[0]);
3914ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
3915ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
3916ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
3917ad48fd75SYan, Zheng 		extent_len = btrfs_file_extent_num_bytes(leaf, fi);
3918ad48fd75SYan, Zheng 	}
3919b3b4aa74SDavid Sterba 	btrfs_release_path(path);
3920ad48fd75SYan, Zheng 
3921ad48fd75SYan, Zheng 	path->keep_locks = 1;
3922ad48fd75SYan, Zheng 	path->search_for_split = 1;
3923ad48fd75SYan, Zheng 	ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
3924ad48fd75SYan, Zheng 	path->search_for_split = 0;
3925ad48fd75SYan, Zheng 	if (ret < 0)
3926ad48fd75SYan, Zheng 		goto err;
3927ad48fd75SYan, Zheng 
3928ad48fd75SYan, Zheng 	ret = -EAGAIN;
3929ad48fd75SYan, Zheng 	leaf = path->nodes[0];
3930ad48fd75SYan, Zheng 	/* if our item isn't there or got smaller, return now */
3931ad48fd75SYan, Zheng 	if (ret > 0 || item_size != btrfs_item_size_nr(leaf, path->slots[0]))
3932ad48fd75SYan, Zheng 		goto err;
3933ad48fd75SYan, Zheng 
3934109f6aefSChris Mason 	/* the leaf has  changed, it now has room.  return now */
3935109f6aefSChris Mason 	if (btrfs_leaf_free_space(root, path->nodes[0]) >= ins_len)
3936109f6aefSChris Mason 		goto err;
3937109f6aefSChris Mason 
3938ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
3939ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
3940ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
3941ad48fd75SYan, Zheng 		if (extent_len != btrfs_file_extent_num_bytes(leaf, fi))
3942ad48fd75SYan, Zheng 			goto err;
3943ad48fd75SYan, Zheng 	}
3944ad48fd75SYan, Zheng 
3945ad48fd75SYan, Zheng 	btrfs_set_path_blocking(path);
3946ad48fd75SYan, Zheng 	ret = split_leaf(trans, root, &key, path, ins_len, 1);
3947f0486c68SYan, Zheng 	if (ret)
3948f0486c68SYan, Zheng 		goto err;
3949ad48fd75SYan, Zheng 
3950ad48fd75SYan, Zheng 	path->keep_locks = 0;
3951ad48fd75SYan, Zheng 	btrfs_unlock_up_safe(path, 1);
3952ad48fd75SYan, Zheng 	return 0;
3953ad48fd75SYan, Zheng err:
3954ad48fd75SYan, Zheng 	path->keep_locks = 0;
3955ad48fd75SYan, Zheng 	return ret;
3956ad48fd75SYan, Zheng }
3957ad48fd75SYan, Zheng 
3958ad48fd75SYan, Zheng static noinline int split_item(struct btrfs_trans_handle *trans,
3959459931ecSChris Mason 			       struct btrfs_root *root,
3960459931ecSChris Mason 			       struct btrfs_path *path,
3961459931ecSChris Mason 			       struct btrfs_key *new_key,
3962459931ecSChris Mason 			       unsigned long split_offset)
3963459931ecSChris Mason {
3964459931ecSChris Mason 	struct extent_buffer *leaf;
3965459931ecSChris Mason 	struct btrfs_item *item;
3966459931ecSChris Mason 	struct btrfs_item *new_item;
3967459931ecSChris Mason 	int slot;
3968ad48fd75SYan, Zheng 	char *buf;
3969459931ecSChris Mason 	u32 nritems;
3970ad48fd75SYan, Zheng 	u32 item_size;
3971459931ecSChris Mason 	u32 orig_offset;
3972459931ecSChris Mason 	struct btrfs_disk_key disk_key;
3973459931ecSChris Mason 
3974459931ecSChris Mason 	leaf = path->nodes[0];
3975b9473439SChris Mason 	BUG_ON(btrfs_leaf_free_space(root, leaf) < sizeof(struct btrfs_item));
3976b9473439SChris Mason 
3977b4ce94deSChris Mason 	btrfs_set_path_blocking(path);
3978b4ce94deSChris Mason 
3979459931ecSChris Mason 	item = btrfs_item_nr(leaf, path->slots[0]);
3980459931ecSChris Mason 	orig_offset = btrfs_item_offset(leaf, item);
3981459931ecSChris Mason 	item_size = btrfs_item_size(leaf, item);
3982459931ecSChris Mason 
3983459931ecSChris Mason 	buf = kmalloc(item_size, GFP_NOFS);
3984ad48fd75SYan, Zheng 	if (!buf)
3985ad48fd75SYan, Zheng 		return -ENOMEM;
3986ad48fd75SYan, Zheng 
3987459931ecSChris Mason 	read_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf,
3988459931ecSChris Mason 			    path->slots[0]), item_size);
3989ad48fd75SYan, Zheng 
3990459931ecSChris Mason 	slot = path->slots[0] + 1;
3991459931ecSChris Mason 	nritems = btrfs_header_nritems(leaf);
3992459931ecSChris Mason 	if (slot != nritems) {
3993459931ecSChris Mason 		/* shift the items */
3994459931ecSChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + 1),
3995459931ecSChris Mason 				btrfs_item_nr_offset(slot),
3996459931ecSChris Mason 				(nritems - slot) * sizeof(struct btrfs_item));
3997459931ecSChris Mason 	}
3998459931ecSChris Mason 
3999459931ecSChris Mason 	btrfs_cpu_key_to_disk(&disk_key, new_key);
4000459931ecSChris Mason 	btrfs_set_item_key(leaf, &disk_key, slot);
4001459931ecSChris Mason 
4002459931ecSChris Mason 	new_item = btrfs_item_nr(leaf, slot);
4003459931ecSChris Mason 
4004459931ecSChris Mason 	btrfs_set_item_offset(leaf, new_item, orig_offset);
4005459931ecSChris Mason 	btrfs_set_item_size(leaf, new_item, item_size - split_offset);
4006459931ecSChris Mason 
4007459931ecSChris Mason 	btrfs_set_item_offset(leaf, item,
4008459931ecSChris Mason 			      orig_offset + item_size - split_offset);
4009459931ecSChris Mason 	btrfs_set_item_size(leaf, item, split_offset);
4010459931ecSChris Mason 
4011459931ecSChris Mason 	btrfs_set_header_nritems(leaf, nritems + 1);
4012459931ecSChris Mason 
4013459931ecSChris Mason 	/* write the data for the start of the original item */
4014459931ecSChris Mason 	write_extent_buffer(leaf, buf,
4015459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, path->slots[0]),
4016459931ecSChris Mason 			    split_offset);
4017459931ecSChris Mason 
4018459931ecSChris Mason 	/* write the data for the new item */
4019459931ecSChris Mason 	write_extent_buffer(leaf, buf + split_offset,
4020459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, slot),
4021459931ecSChris Mason 			    item_size - split_offset);
4022459931ecSChris Mason 	btrfs_mark_buffer_dirty(leaf);
4023459931ecSChris Mason 
4024ad48fd75SYan, Zheng 	BUG_ON(btrfs_leaf_free_space(root, leaf) < 0);
4025459931ecSChris Mason 	kfree(buf);
4026ad48fd75SYan, Zheng 	return 0;
4027ad48fd75SYan, Zheng }
4028ad48fd75SYan, Zheng 
4029ad48fd75SYan, Zheng /*
4030ad48fd75SYan, Zheng  * This function splits a single item into two items,
4031ad48fd75SYan, Zheng  * giving 'new_key' to the new item and splitting the
4032ad48fd75SYan, Zheng  * old one at split_offset (from the start of the item).
4033ad48fd75SYan, Zheng  *
4034ad48fd75SYan, Zheng  * The path may be released by this operation.  After
4035ad48fd75SYan, Zheng  * the split, the path is pointing to the old item.  The
4036ad48fd75SYan, Zheng  * new item is going to be in the same node as the old one.
4037ad48fd75SYan, Zheng  *
4038ad48fd75SYan, Zheng  * Note, the item being split must be smaller enough to live alone on
4039ad48fd75SYan, Zheng  * a tree block with room for one extra struct btrfs_item
4040ad48fd75SYan, Zheng  *
4041ad48fd75SYan, Zheng  * This allows us to split the item in place, keeping a lock on the
4042ad48fd75SYan, Zheng  * leaf the entire time.
4043ad48fd75SYan, Zheng  */
4044ad48fd75SYan, Zheng int btrfs_split_item(struct btrfs_trans_handle *trans,
4045ad48fd75SYan, Zheng 		     struct btrfs_root *root,
4046ad48fd75SYan, Zheng 		     struct btrfs_path *path,
4047ad48fd75SYan, Zheng 		     struct btrfs_key *new_key,
4048ad48fd75SYan, Zheng 		     unsigned long split_offset)
4049ad48fd75SYan, Zheng {
4050ad48fd75SYan, Zheng 	int ret;
4051ad48fd75SYan, Zheng 	ret = setup_leaf_for_split(trans, root, path,
4052ad48fd75SYan, Zheng 				   sizeof(struct btrfs_item));
4053ad48fd75SYan, Zheng 	if (ret)
4054459931ecSChris Mason 		return ret;
4055ad48fd75SYan, Zheng 
4056ad48fd75SYan, Zheng 	ret = split_item(trans, root, path, new_key, split_offset);
4057ad48fd75SYan, Zheng 	return ret;
4058ad48fd75SYan, Zheng }
4059ad48fd75SYan, Zheng 
4060ad48fd75SYan, Zheng /*
4061ad48fd75SYan, Zheng  * This function duplicate a item, giving 'new_key' to the new item.
4062ad48fd75SYan, Zheng  * It guarantees both items live in the same tree leaf and the new item
4063ad48fd75SYan, Zheng  * is contiguous with the original item.
4064ad48fd75SYan, Zheng  *
4065ad48fd75SYan, Zheng  * This allows us to split file extent in place, keeping a lock on the
4066ad48fd75SYan, Zheng  * leaf the entire time.
4067ad48fd75SYan, Zheng  */
4068ad48fd75SYan, Zheng int btrfs_duplicate_item(struct btrfs_trans_handle *trans,
4069ad48fd75SYan, Zheng 			 struct btrfs_root *root,
4070ad48fd75SYan, Zheng 			 struct btrfs_path *path,
4071ad48fd75SYan, Zheng 			 struct btrfs_key *new_key)
4072ad48fd75SYan, Zheng {
4073ad48fd75SYan, Zheng 	struct extent_buffer *leaf;
4074ad48fd75SYan, Zheng 	int ret;
4075ad48fd75SYan, Zheng 	u32 item_size;
4076ad48fd75SYan, Zheng 
4077ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4078ad48fd75SYan, Zheng 	item_size = btrfs_item_size_nr(leaf, path->slots[0]);
4079ad48fd75SYan, Zheng 	ret = setup_leaf_for_split(trans, root, path,
4080ad48fd75SYan, Zheng 				   item_size + sizeof(struct btrfs_item));
4081ad48fd75SYan, Zheng 	if (ret)
4082ad48fd75SYan, Zheng 		return ret;
4083ad48fd75SYan, Zheng 
4084ad48fd75SYan, Zheng 	path->slots[0]++;
4085143bede5SJeff Mahoney 	setup_items_for_insert(trans, root, path, new_key, &item_size,
4086ad48fd75SYan, Zheng 			       item_size, item_size +
4087ad48fd75SYan, Zheng 			       sizeof(struct btrfs_item), 1);
4088ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4089ad48fd75SYan, Zheng 	memcpy_extent_buffer(leaf,
4090ad48fd75SYan, Zheng 			     btrfs_item_ptr_offset(leaf, path->slots[0]),
4091ad48fd75SYan, Zheng 			     btrfs_item_ptr_offset(leaf, path->slots[0] - 1),
4092ad48fd75SYan, Zheng 			     item_size);
4093ad48fd75SYan, Zheng 	return 0;
4094459931ecSChris Mason }
4095459931ecSChris Mason 
4096459931ecSChris Mason /*
4097d352ac68SChris Mason  * make the item pointed to by the path smaller.  new_size indicates
4098d352ac68SChris Mason  * how small to make it, and from_end tells us if we just chop bytes
4099d352ac68SChris Mason  * off the end of the item or if we shift the item to chop bytes off
4100d352ac68SChris Mason  * the front.
4101d352ac68SChris Mason  */
4102143bede5SJeff Mahoney void btrfs_truncate_item(struct btrfs_trans_handle *trans,
4103b18c6685SChris Mason 			 struct btrfs_root *root,
4104b18c6685SChris Mason 			 struct btrfs_path *path,
4105179e29e4SChris Mason 			 u32 new_size, int from_end)
4106b18c6685SChris Mason {
4107b18c6685SChris Mason 	int slot;
41085f39d397SChris Mason 	struct extent_buffer *leaf;
41095f39d397SChris Mason 	struct btrfs_item *item;
4110b18c6685SChris Mason 	u32 nritems;
4111b18c6685SChris Mason 	unsigned int data_end;
4112b18c6685SChris Mason 	unsigned int old_data_start;
4113b18c6685SChris Mason 	unsigned int old_size;
4114b18c6685SChris Mason 	unsigned int size_diff;
4115b18c6685SChris Mason 	int i;
4116cfed81a0SChris Mason 	struct btrfs_map_token token;
4117cfed81a0SChris Mason 
4118cfed81a0SChris Mason 	btrfs_init_map_token(&token);
4119b18c6685SChris Mason 
41205f39d397SChris Mason 	leaf = path->nodes[0];
4121179e29e4SChris Mason 	slot = path->slots[0];
4122179e29e4SChris Mason 
4123179e29e4SChris Mason 	old_size = btrfs_item_size_nr(leaf, slot);
4124179e29e4SChris Mason 	if (old_size == new_size)
4125143bede5SJeff Mahoney 		return;
4126b18c6685SChris Mason 
41275f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
4128b18c6685SChris Mason 	data_end = leaf_data_end(root, leaf);
4129b18c6685SChris Mason 
41305f39d397SChris Mason 	old_data_start = btrfs_item_offset_nr(leaf, slot);
4131179e29e4SChris Mason 
4132b18c6685SChris Mason 	size_diff = old_size - new_size;
4133b18c6685SChris Mason 
4134b18c6685SChris Mason 	BUG_ON(slot < 0);
4135b18c6685SChris Mason 	BUG_ON(slot >= nritems);
4136b18c6685SChris Mason 
4137b18c6685SChris Mason 	/*
4138b18c6685SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4139b18c6685SChris Mason 	 */
4140b18c6685SChris Mason 	/* first correct the data pointers */
4141b18c6685SChris Mason 	for (i = slot; i < nritems; i++) {
41425f39d397SChris Mason 		u32 ioff;
41435f39d397SChris Mason 		item = btrfs_item_nr(leaf, i);
4144db94535dSChris Mason 
4145cfed81a0SChris Mason 		ioff = btrfs_token_item_offset(leaf, item, &token);
4146cfed81a0SChris Mason 		btrfs_set_token_item_offset(leaf, item,
4147cfed81a0SChris Mason 					    ioff + size_diff, &token);
4148b18c6685SChris Mason 	}
4149db94535dSChris Mason 
4150b18c6685SChris Mason 	/* shift the data */
4151179e29e4SChris Mason 	if (from_end) {
41525f39d397SChris Mason 		memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
4153b18c6685SChris Mason 			      data_end + size_diff, btrfs_leaf_data(leaf) +
4154b18c6685SChris Mason 			      data_end, old_data_start + new_size - data_end);
4155179e29e4SChris Mason 	} else {
4156179e29e4SChris Mason 		struct btrfs_disk_key disk_key;
4157179e29e4SChris Mason 		u64 offset;
4158179e29e4SChris Mason 
4159179e29e4SChris Mason 		btrfs_item_key(leaf, &disk_key, slot);
4160179e29e4SChris Mason 
4161179e29e4SChris Mason 		if (btrfs_disk_key_type(&disk_key) == BTRFS_EXTENT_DATA_KEY) {
4162179e29e4SChris Mason 			unsigned long ptr;
4163179e29e4SChris Mason 			struct btrfs_file_extent_item *fi;
4164179e29e4SChris Mason 
4165179e29e4SChris Mason 			fi = btrfs_item_ptr(leaf, slot,
4166179e29e4SChris Mason 					    struct btrfs_file_extent_item);
4167179e29e4SChris Mason 			fi = (struct btrfs_file_extent_item *)(
4168179e29e4SChris Mason 			     (unsigned long)fi - size_diff);
4169179e29e4SChris Mason 
4170179e29e4SChris Mason 			if (btrfs_file_extent_type(leaf, fi) ==
4171179e29e4SChris Mason 			    BTRFS_FILE_EXTENT_INLINE) {
4172179e29e4SChris Mason 				ptr = btrfs_item_ptr_offset(leaf, slot);
4173179e29e4SChris Mason 				memmove_extent_buffer(leaf, ptr,
4174179e29e4SChris Mason 				      (unsigned long)fi,
4175179e29e4SChris Mason 				      offsetof(struct btrfs_file_extent_item,
4176179e29e4SChris Mason 						 disk_bytenr));
4177179e29e4SChris Mason 			}
4178179e29e4SChris Mason 		}
4179179e29e4SChris Mason 
4180179e29e4SChris Mason 		memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
4181179e29e4SChris Mason 			      data_end + size_diff, btrfs_leaf_data(leaf) +
4182179e29e4SChris Mason 			      data_end, old_data_start - data_end);
4183179e29e4SChris Mason 
4184179e29e4SChris Mason 		offset = btrfs_disk_key_offset(&disk_key);
4185179e29e4SChris Mason 		btrfs_set_disk_key_offset(&disk_key, offset + size_diff);
4186179e29e4SChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot);
4187179e29e4SChris Mason 		if (slot == 0)
4188179e29e4SChris Mason 			fixup_low_keys(trans, root, path, &disk_key, 1);
4189179e29e4SChris Mason 	}
41905f39d397SChris Mason 
41915f39d397SChris Mason 	item = btrfs_item_nr(leaf, slot);
41925f39d397SChris Mason 	btrfs_set_item_size(leaf, item, new_size);
41935f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
4194b18c6685SChris Mason 
41955f39d397SChris Mason 	if (btrfs_leaf_free_space(root, leaf) < 0) {
41965f39d397SChris Mason 		btrfs_print_leaf(root, leaf);
4197b18c6685SChris Mason 		BUG();
41985f39d397SChris Mason 	}
4199b18c6685SChris Mason }
4200b18c6685SChris Mason 
4201d352ac68SChris Mason /*
4202d352ac68SChris Mason  * make the item pointed to by the path bigger, data_size is the new size.
4203d352ac68SChris Mason  */
4204143bede5SJeff Mahoney void btrfs_extend_item(struct btrfs_trans_handle *trans,
42055f39d397SChris Mason 		       struct btrfs_root *root, struct btrfs_path *path,
42065f39d397SChris Mason 		       u32 data_size)
42076567e837SChris Mason {
42086567e837SChris Mason 	int slot;
42095f39d397SChris Mason 	struct extent_buffer *leaf;
42105f39d397SChris Mason 	struct btrfs_item *item;
42116567e837SChris Mason 	u32 nritems;
42126567e837SChris Mason 	unsigned int data_end;
42136567e837SChris Mason 	unsigned int old_data;
42146567e837SChris Mason 	unsigned int old_size;
42156567e837SChris Mason 	int i;
4216cfed81a0SChris Mason 	struct btrfs_map_token token;
4217cfed81a0SChris Mason 
4218cfed81a0SChris Mason 	btrfs_init_map_token(&token);
42196567e837SChris Mason 
42205f39d397SChris Mason 	leaf = path->nodes[0];
42216567e837SChris Mason 
42225f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
42236567e837SChris Mason 	data_end = leaf_data_end(root, leaf);
42246567e837SChris Mason 
42255f39d397SChris Mason 	if (btrfs_leaf_free_space(root, leaf) < data_size) {
42265f39d397SChris Mason 		btrfs_print_leaf(root, leaf);
42276567e837SChris Mason 		BUG();
42285f39d397SChris Mason 	}
42296567e837SChris Mason 	slot = path->slots[0];
42305f39d397SChris Mason 	old_data = btrfs_item_end_nr(leaf, slot);
42316567e837SChris Mason 
42326567e837SChris Mason 	BUG_ON(slot < 0);
42333326d1b0SChris Mason 	if (slot >= nritems) {
42343326d1b0SChris Mason 		btrfs_print_leaf(root, leaf);
4235d397712bSChris Mason 		printk(KERN_CRIT "slot %d too large, nritems %d\n",
4236d397712bSChris Mason 		       slot, nritems);
42373326d1b0SChris Mason 		BUG_ON(1);
42383326d1b0SChris Mason 	}
42396567e837SChris Mason 
42406567e837SChris Mason 	/*
42416567e837SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
42426567e837SChris Mason 	 */
42436567e837SChris Mason 	/* first correct the data pointers */
42446567e837SChris Mason 	for (i = slot; i < nritems; i++) {
42455f39d397SChris Mason 		u32 ioff;
42465f39d397SChris Mason 		item = btrfs_item_nr(leaf, i);
4247db94535dSChris Mason 
4248cfed81a0SChris Mason 		ioff = btrfs_token_item_offset(leaf, item, &token);
4249cfed81a0SChris Mason 		btrfs_set_token_item_offset(leaf, item,
4250cfed81a0SChris Mason 					    ioff - data_size, &token);
42516567e837SChris Mason 	}
42525f39d397SChris Mason 
42536567e837SChris Mason 	/* shift the data */
42545f39d397SChris Mason 	memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
42556567e837SChris Mason 		      data_end - data_size, btrfs_leaf_data(leaf) +
42566567e837SChris Mason 		      data_end, old_data - data_end);
42575f39d397SChris Mason 
42586567e837SChris Mason 	data_end = old_data;
42595f39d397SChris Mason 	old_size = btrfs_item_size_nr(leaf, slot);
42605f39d397SChris Mason 	item = btrfs_item_nr(leaf, slot);
42615f39d397SChris Mason 	btrfs_set_item_size(leaf, item, old_size + data_size);
42625f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
42636567e837SChris Mason 
42645f39d397SChris Mason 	if (btrfs_leaf_free_space(root, leaf) < 0) {
42655f39d397SChris Mason 		btrfs_print_leaf(root, leaf);
42666567e837SChris Mason 		BUG();
42675f39d397SChris Mason 	}
42686567e837SChris Mason }
42696567e837SChris Mason 
427074123bd7SChris Mason /*
4271d352ac68SChris Mason  * Given a key and some data, insert items into the tree.
427274123bd7SChris Mason  * This does all the path init required, making room in the tree if needed.
4273f3465ca4SJosef Bacik  * Returns the number of keys that were inserted.
4274f3465ca4SJosef Bacik  */
4275f3465ca4SJosef Bacik int btrfs_insert_some_items(struct btrfs_trans_handle *trans,
4276f3465ca4SJosef Bacik 			    struct btrfs_root *root,
4277f3465ca4SJosef Bacik 			    struct btrfs_path *path,
4278f3465ca4SJosef Bacik 			    struct btrfs_key *cpu_key, u32 *data_size,
4279f3465ca4SJosef Bacik 			    int nr)
4280f3465ca4SJosef Bacik {
4281f3465ca4SJosef Bacik 	struct extent_buffer *leaf;
4282f3465ca4SJosef Bacik 	struct btrfs_item *item;
4283f3465ca4SJosef Bacik 	int ret = 0;
4284f3465ca4SJosef Bacik 	int slot;
4285f3465ca4SJosef Bacik 	int i;
4286f3465ca4SJosef Bacik 	u32 nritems;
4287f3465ca4SJosef Bacik 	u32 total_data = 0;
4288f3465ca4SJosef Bacik 	u32 total_size = 0;
4289f3465ca4SJosef Bacik 	unsigned int data_end;
4290f3465ca4SJosef Bacik 	struct btrfs_disk_key disk_key;
4291f3465ca4SJosef Bacik 	struct btrfs_key found_key;
4292cfed81a0SChris Mason 	struct btrfs_map_token token;
4293cfed81a0SChris Mason 
4294cfed81a0SChris Mason 	btrfs_init_map_token(&token);
4295f3465ca4SJosef Bacik 
429687b29b20SYan Zheng 	for (i = 0; i < nr; i++) {
429787b29b20SYan Zheng 		if (total_size + data_size[i] + sizeof(struct btrfs_item) >
429887b29b20SYan Zheng 		    BTRFS_LEAF_DATA_SIZE(root)) {
429987b29b20SYan Zheng 			break;
430087b29b20SYan Zheng 			nr = i;
430187b29b20SYan Zheng 		}
4302f3465ca4SJosef Bacik 		total_data += data_size[i];
430387b29b20SYan Zheng 		total_size += data_size[i] + sizeof(struct btrfs_item);
430487b29b20SYan Zheng 	}
430587b29b20SYan Zheng 	BUG_ON(nr == 0);
4306f3465ca4SJosef Bacik 
4307f3465ca4SJosef Bacik 	ret = btrfs_search_slot(trans, root, cpu_key, path, total_size, 1);
4308f3465ca4SJosef Bacik 	if (ret == 0)
4309f3465ca4SJosef Bacik 		return -EEXIST;
4310f3465ca4SJosef Bacik 	if (ret < 0)
4311f3465ca4SJosef Bacik 		goto out;
4312f3465ca4SJosef Bacik 
4313f3465ca4SJosef Bacik 	leaf = path->nodes[0];
4314f3465ca4SJosef Bacik 
4315f3465ca4SJosef Bacik 	nritems = btrfs_header_nritems(leaf);
4316f3465ca4SJosef Bacik 	data_end = leaf_data_end(root, leaf);
4317f3465ca4SJosef Bacik 
4318f3465ca4SJosef Bacik 	if (btrfs_leaf_free_space(root, leaf) < total_size) {
4319f3465ca4SJosef Bacik 		for (i = nr; i >= 0; i--) {
4320f3465ca4SJosef Bacik 			total_data -= data_size[i];
4321f3465ca4SJosef Bacik 			total_size -= data_size[i] + sizeof(struct btrfs_item);
4322f3465ca4SJosef Bacik 			if (total_size < btrfs_leaf_free_space(root, leaf))
4323f3465ca4SJosef Bacik 				break;
4324f3465ca4SJosef Bacik 		}
4325f3465ca4SJosef Bacik 		nr = i;
4326f3465ca4SJosef Bacik 	}
4327f3465ca4SJosef Bacik 
4328f3465ca4SJosef Bacik 	slot = path->slots[0];
4329f3465ca4SJosef Bacik 	BUG_ON(slot < 0);
4330f3465ca4SJosef Bacik 
4331f3465ca4SJosef Bacik 	if (slot != nritems) {
4332f3465ca4SJosef Bacik 		unsigned int old_data = btrfs_item_end_nr(leaf, slot);
4333f3465ca4SJosef Bacik 
4334f3465ca4SJosef Bacik 		item = btrfs_item_nr(leaf, slot);
4335f3465ca4SJosef Bacik 		btrfs_item_key_to_cpu(leaf, &found_key, slot);
4336f3465ca4SJosef Bacik 
4337f3465ca4SJosef Bacik 		/* figure out how many keys we can insert in here */
4338f3465ca4SJosef Bacik 		total_data = data_size[0];
4339f3465ca4SJosef Bacik 		for (i = 1; i < nr; i++) {
43405d4f98a2SYan Zheng 			if (btrfs_comp_cpu_keys(&found_key, cpu_key + i) <= 0)
4341f3465ca4SJosef Bacik 				break;
4342f3465ca4SJosef Bacik 			total_data += data_size[i];
4343f3465ca4SJosef Bacik 		}
4344f3465ca4SJosef Bacik 		nr = i;
4345f3465ca4SJosef Bacik 
4346f3465ca4SJosef Bacik 		if (old_data < data_end) {
4347f3465ca4SJosef Bacik 			btrfs_print_leaf(root, leaf);
4348d397712bSChris Mason 			printk(KERN_CRIT "slot %d old_data %d data_end %d\n",
4349f3465ca4SJosef Bacik 			       slot, old_data, data_end);
4350f3465ca4SJosef Bacik 			BUG_ON(1);
4351f3465ca4SJosef Bacik 		}
4352f3465ca4SJosef Bacik 		/*
4353f3465ca4SJosef Bacik 		 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4354f3465ca4SJosef Bacik 		 */
4355f3465ca4SJosef Bacik 		/* first correct the data pointers */
4356f3465ca4SJosef Bacik 		for (i = slot; i < nritems; i++) {
4357f3465ca4SJosef Bacik 			u32 ioff;
4358f3465ca4SJosef Bacik 
4359f3465ca4SJosef Bacik 			item = btrfs_item_nr(leaf, i);
4360cfed81a0SChris Mason 			ioff = btrfs_token_item_offset(leaf, item, &token);
4361cfed81a0SChris Mason 			btrfs_set_token_item_offset(leaf, item,
4362cfed81a0SChris Mason 						    ioff - total_data, &token);
4363f3465ca4SJosef Bacik 		}
4364f3465ca4SJosef Bacik 		/* shift the items */
4365f3465ca4SJosef Bacik 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + nr),
4366f3465ca4SJosef Bacik 			      btrfs_item_nr_offset(slot),
4367f3465ca4SJosef Bacik 			      (nritems - slot) * sizeof(struct btrfs_item));
4368f3465ca4SJosef Bacik 
4369f3465ca4SJosef Bacik 		/* shift the data */
4370f3465ca4SJosef Bacik 		memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
4371f3465ca4SJosef Bacik 			      data_end - total_data, btrfs_leaf_data(leaf) +
4372f3465ca4SJosef Bacik 			      data_end, old_data - data_end);
4373f3465ca4SJosef Bacik 		data_end = old_data;
4374f3465ca4SJosef Bacik 	} else {
4375f3465ca4SJosef Bacik 		/*
4376f3465ca4SJosef Bacik 		 * this sucks but it has to be done, if we are inserting at
4377f3465ca4SJosef Bacik 		 * the end of the leaf only insert 1 of the items, since we
4378f3465ca4SJosef Bacik 		 * have no way of knowing whats on the next leaf and we'd have
4379f3465ca4SJosef Bacik 		 * to drop our current locks to figure it out
4380f3465ca4SJosef Bacik 		 */
4381f3465ca4SJosef Bacik 		nr = 1;
4382f3465ca4SJosef Bacik 	}
4383f3465ca4SJosef Bacik 
4384f3465ca4SJosef Bacik 	/* setup the item for the new data */
4385f3465ca4SJosef Bacik 	for (i = 0; i < nr; i++) {
4386f3465ca4SJosef Bacik 		btrfs_cpu_key_to_disk(&disk_key, cpu_key + i);
4387f3465ca4SJosef Bacik 		btrfs_set_item_key(leaf, &disk_key, slot + i);
4388f3465ca4SJosef Bacik 		item = btrfs_item_nr(leaf, slot + i);
4389cfed81a0SChris Mason 		btrfs_set_token_item_offset(leaf, item,
4390cfed81a0SChris Mason 					    data_end - data_size[i], &token);
4391f3465ca4SJosef Bacik 		data_end -= data_size[i];
4392cfed81a0SChris Mason 		btrfs_set_token_item_size(leaf, item, data_size[i], &token);
4393f3465ca4SJosef Bacik 	}
4394f3465ca4SJosef Bacik 	btrfs_set_header_nritems(leaf, nritems + nr);
4395f3465ca4SJosef Bacik 	btrfs_mark_buffer_dirty(leaf);
4396f3465ca4SJosef Bacik 
4397f3465ca4SJosef Bacik 	ret = 0;
4398f3465ca4SJosef Bacik 	if (slot == 0) {
4399f3465ca4SJosef Bacik 		btrfs_cpu_key_to_disk(&disk_key, cpu_key);
4400143bede5SJeff Mahoney 		fixup_low_keys(trans, root, path, &disk_key, 1);
4401f3465ca4SJosef Bacik 	}
4402f3465ca4SJosef Bacik 
4403f3465ca4SJosef Bacik 	if (btrfs_leaf_free_space(root, leaf) < 0) {
4404f3465ca4SJosef Bacik 		btrfs_print_leaf(root, leaf);
4405f3465ca4SJosef Bacik 		BUG();
4406f3465ca4SJosef Bacik 	}
4407f3465ca4SJosef Bacik out:
4408f3465ca4SJosef Bacik 	if (!ret)
4409f3465ca4SJosef Bacik 		ret = nr;
4410f3465ca4SJosef Bacik 	return ret;
4411f3465ca4SJosef Bacik }
4412f3465ca4SJosef Bacik 
4413f3465ca4SJosef Bacik /*
441444871b1bSChris Mason  * this is a helper for btrfs_insert_empty_items, the main goal here is
441544871b1bSChris Mason  * to save stack depth by doing the bulk of the work in a function
441644871b1bSChris Mason  * that doesn't call btrfs_search_slot
441774123bd7SChris Mason  */
4418143bede5SJeff Mahoney void setup_items_for_insert(struct btrfs_trans_handle *trans,
441944871b1bSChris Mason 			    struct btrfs_root *root, struct btrfs_path *path,
44209c58309dSChris Mason 			    struct btrfs_key *cpu_key, u32 *data_size,
442144871b1bSChris Mason 			    u32 total_data, u32 total_size, int nr)
4422be0e5c09SChris Mason {
44235f39d397SChris Mason 	struct btrfs_item *item;
44249c58309dSChris Mason 	int i;
44257518a238SChris Mason 	u32 nritems;
4426be0e5c09SChris Mason 	unsigned int data_end;
4427e2fa7227SChris Mason 	struct btrfs_disk_key disk_key;
442844871b1bSChris Mason 	struct extent_buffer *leaf;
442944871b1bSChris Mason 	int slot;
4430cfed81a0SChris Mason 	struct btrfs_map_token token;
4431cfed81a0SChris Mason 
4432cfed81a0SChris Mason 	btrfs_init_map_token(&token);
4433e2fa7227SChris Mason 
44345f39d397SChris Mason 	leaf = path->nodes[0];
443544871b1bSChris Mason 	slot = path->slots[0];
443674123bd7SChris Mason 
44375f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
4438123abc88SChris Mason 	data_end = leaf_data_end(root, leaf);
4439eb60ceacSChris Mason 
4440f25956ccSChris Mason 	if (btrfs_leaf_free_space(root, leaf) < total_size) {
44413326d1b0SChris Mason 		btrfs_print_leaf(root, leaf);
4442d397712bSChris Mason 		printk(KERN_CRIT "not enough freespace need %u have %d\n",
44439c58309dSChris Mason 		       total_size, btrfs_leaf_free_space(root, leaf));
4444be0e5c09SChris Mason 		BUG();
4445d4dbff95SChris Mason 	}
44465f39d397SChris Mason 
4447be0e5c09SChris Mason 	if (slot != nritems) {
44485f39d397SChris Mason 		unsigned int old_data = btrfs_item_end_nr(leaf, slot);
4449be0e5c09SChris Mason 
44505f39d397SChris Mason 		if (old_data < data_end) {
44515f39d397SChris Mason 			btrfs_print_leaf(root, leaf);
4452d397712bSChris Mason 			printk(KERN_CRIT "slot %d old_data %d data_end %d\n",
44535f39d397SChris Mason 			       slot, old_data, data_end);
44545f39d397SChris Mason 			BUG_ON(1);
44555f39d397SChris Mason 		}
4456be0e5c09SChris Mason 		/*
4457be0e5c09SChris Mason 		 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4458be0e5c09SChris Mason 		 */
4459be0e5c09SChris Mason 		/* first correct the data pointers */
44600783fcfcSChris Mason 		for (i = slot; i < nritems; i++) {
44615f39d397SChris Mason 			u32 ioff;
4462db94535dSChris Mason 
44635f39d397SChris Mason 			item = btrfs_item_nr(leaf, i);
4464cfed81a0SChris Mason 			ioff = btrfs_token_item_offset(leaf, item, &token);
4465cfed81a0SChris Mason 			btrfs_set_token_item_offset(leaf, item,
4466cfed81a0SChris Mason 						    ioff - total_data, &token);
44670783fcfcSChris Mason 		}
4468be0e5c09SChris Mason 		/* shift the items */
44699c58309dSChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + nr),
44705f39d397SChris Mason 			      btrfs_item_nr_offset(slot),
44710783fcfcSChris Mason 			      (nritems - slot) * sizeof(struct btrfs_item));
4472be0e5c09SChris Mason 
4473be0e5c09SChris Mason 		/* shift the data */
44745f39d397SChris Mason 		memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
44759c58309dSChris Mason 			      data_end - total_data, btrfs_leaf_data(leaf) +
4476be0e5c09SChris Mason 			      data_end, old_data - data_end);
4477be0e5c09SChris Mason 		data_end = old_data;
4478be0e5c09SChris Mason 	}
44795f39d397SChris Mason 
448062e2749eSChris Mason 	/* setup the item for the new data */
44819c58309dSChris Mason 	for (i = 0; i < nr; i++) {
44829c58309dSChris Mason 		btrfs_cpu_key_to_disk(&disk_key, cpu_key + i);
44839c58309dSChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot + i);
44849c58309dSChris Mason 		item = btrfs_item_nr(leaf, slot + i);
4485cfed81a0SChris Mason 		btrfs_set_token_item_offset(leaf, item,
4486cfed81a0SChris Mason 					    data_end - data_size[i], &token);
44879c58309dSChris Mason 		data_end -= data_size[i];
4488cfed81a0SChris Mason 		btrfs_set_token_item_size(leaf, item, data_size[i], &token);
44899c58309dSChris Mason 	}
449044871b1bSChris Mason 
44919c58309dSChris Mason 	btrfs_set_header_nritems(leaf, nritems + nr);
4492aa5d6bedSChris Mason 
44935a01a2e3SChris Mason 	if (slot == 0) {
44945a01a2e3SChris Mason 		btrfs_cpu_key_to_disk(&disk_key, cpu_key);
4495143bede5SJeff Mahoney 		fixup_low_keys(trans, root, path, &disk_key, 1);
44965a01a2e3SChris Mason 	}
4497b9473439SChris Mason 	btrfs_unlock_up_safe(path, 1);
4498b9473439SChris Mason 	btrfs_mark_buffer_dirty(leaf);
4499aa5d6bedSChris Mason 
45005f39d397SChris Mason 	if (btrfs_leaf_free_space(root, leaf) < 0) {
45015f39d397SChris Mason 		btrfs_print_leaf(root, leaf);
4502be0e5c09SChris Mason 		BUG();
45035f39d397SChris Mason 	}
450444871b1bSChris Mason }
450544871b1bSChris Mason 
450644871b1bSChris Mason /*
450744871b1bSChris Mason  * Given a key and some data, insert items into the tree.
450844871b1bSChris Mason  * This does all the path init required, making room in the tree if needed.
450944871b1bSChris Mason  */
451044871b1bSChris Mason int btrfs_insert_empty_items(struct btrfs_trans_handle *trans,
451144871b1bSChris Mason 			    struct btrfs_root *root,
451244871b1bSChris Mason 			    struct btrfs_path *path,
451344871b1bSChris Mason 			    struct btrfs_key *cpu_key, u32 *data_size,
451444871b1bSChris Mason 			    int nr)
451544871b1bSChris Mason {
451644871b1bSChris Mason 	int ret = 0;
451744871b1bSChris Mason 	int slot;
451844871b1bSChris Mason 	int i;
451944871b1bSChris Mason 	u32 total_size = 0;
452044871b1bSChris Mason 	u32 total_data = 0;
452144871b1bSChris Mason 
452244871b1bSChris Mason 	for (i = 0; i < nr; i++)
452344871b1bSChris Mason 		total_data += data_size[i];
452444871b1bSChris Mason 
452544871b1bSChris Mason 	total_size = total_data + (nr * sizeof(struct btrfs_item));
452644871b1bSChris Mason 	ret = btrfs_search_slot(trans, root, cpu_key, path, total_size, 1);
452744871b1bSChris Mason 	if (ret == 0)
452844871b1bSChris Mason 		return -EEXIST;
452944871b1bSChris Mason 	if (ret < 0)
4530143bede5SJeff Mahoney 		return ret;
453144871b1bSChris Mason 
453244871b1bSChris Mason 	slot = path->slots[0];
453344871b1bSChris Mason 	BUG_ON(slot < 0);
453444871b1bSChris Mason 
4535143bede5SJeff Mahoney 	setup_items_for_insert(trans, root, path, cpu_key, data_size,
453644871b1bSChris Mason 			       total_data, total_size, nr);
4537143bede5SJeff Mahoney 	return 0;
453862e2749eSChris Mason }
453962e2749eSChris Mason 
454062e2749eSChris Mason /*
454162e2749eSChris Mason  * Given a key and some data, insert an item into the tree.
454262e2749eSChris Mason  * This does all the path init required, making room in the tree if needed.
454362e2749eSChris Mason  */
4544e089f05cSChris Mason int btrfs_insert_item(struct btrfs_trans_handle *trans, struct btrfs_root
4545e089f05cSChris Mason 		      *root, struct btrfs_key *cpu_key, void *data, u32
4546e089f05cSChris Mason 		      data_size)
454762e2749eSChris Mason {
454862e2749eSChris Mason 	int ret = 0;
45492c90e5d6SChris Mason 	struct btrfs_path *path;
45505f39d397SChris Mason 	struct extent_buffer *leaf;
45515f39d397SChris Mason 	unsigned long ptr;
455262e2749eSChris Mason 
45532c90e5d6SChris Mason 	path = btrfs_alloc_path();
4554db5b493aSTsutomu Itoh 	if (!path)
4555db5b493aSTsutomu Itoh 		return -ENOMEM;
45562c90e5d6SChris Mason 	ret = btrfs_insert_empty_item(trans, root, path, cpu_key, data_size);
455762e2749eSChris Mason 	if (!ret) {
45585f39d397SChris Mason 		leaf = path->nodes[0];
45595f39d397SChris Mason 		ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
45605f39d397SChris Mason 		write_extent_buffer(leaf, data, ptr, data_size);
45615f39d397SChris Mason 		btrfs_mark_buffer_dirty(leaf);
456262e2749eSChris Mason 	}
45632c90e5d6SChris Mason 	btrfs_free_path(path);
4564aa5d6bedSChris Mason 	return ret;
4565be0e5c09SChris Mason }
4566be0e5c09SChris Mason 
456774123bd7SChris Mason /*
45685de08d7dSChris Mason  * delete the pointer from a given node.
456974123bd7SChris Mason  *
4570d352ac68SChris Mason  * the tree should have been previously balanced so the deletion does not
4571d352ac68SChris Mason  * empty a node.
457274123bd7SChris Mason  */
4573143bede5SJeff Mahoney static void del_ptr(struct btrfs_trans_handle *trans, struct btrfs_root *root,
4574f3ea38daSJan Schmidt 		    struct btrfs_path *path, int level, int slot,
4575f3ea38daSJan Schmidt 		    int tree_mod_log)
4576be0e5c09SChris Mason {
45775f39d397SChris Mason 	struct extent_buffer *parent = path->nodes[level];
45787518a238SChris Mason 	u32 nritems;
4579f3ea38daSJan Schmidt 	int ret;
4580be0e5c09SChris Mason 
45815f39d397SChris Mason 	nritems = btrfs_header_nritems(parent);
4582be0e5c09SChris Mason 	if (slot != nritems - 1) {
4583f3ea38daSJan Schmidt 		if (tree_mod_log && level)
4584f3ea38daSJan Schmidt 			tree_mod_log_eb_move(root->fs_info, parent, slot,
4585f3ea38daSJan Schmidt 					     slot + 1, nritems - slot - 1);
45865f39d397SChris Mason 		memmove_extent_buffer(parent,
45875f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot),
45885f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot + 1),
4589d6025579SChris Mason 			      sizeof(struct btrfs_key_ptr) *
4590d6025579SChris Mason 			      (nritems - slot - 1));
4591f395694cSJan Schmidt 	} else if (tree_mod_log && level) {
4592f3ea38daSJan Schmidt 		ret = tree_mod_log_insert_key(root->fs_info, parent, slot,
4593f3ea38daSJan Schmidt 					      MOD_LOG_KEY_REMOVE);
4594f3ea38daSJan Schmidt 		BUG_ON(ret < 0);
4595be0e5c09SChris Mason 	}
4596f3ea38daSJan Schmidt 
45977518a238SChris Mason 	nritems--;
45985f39d397SChris Mason 	btrfs_set_header_nritems(parent, nritems);
45997518a238SChris Mason 	if (nritems == 0 && parent == root->node) {
46005f39d397SChris Mason 		BUG_ON(btrfs_header_level(root->node) != 1);
4601eb60ceacSChris Mason 		/* just turn the root into a leaf and break */
46025f39d397SChris Mason 		btrfs_set_header_level(root->node, 0);
4603bb803951SChris Mason 	} else if (slot == 0) {
46045f39d397SChris Mason 		struct btrfs_disk_key disk_key;
46055f39d397SChris Mason 
46065f39d397SChris Mason 		btrfs_node_key(parent, &disk_key, 0);
4607143bede5SJeff Mahoney 		fixup_low_keys(trans, root, path, &disk_key, level + 1);
4608be0e5c09SChris Mason 	}
4609d6025579SChris Mason 	btrfs_mark_buffer_dirty(parent);
4610be0e5c09SChris Mason }
4611be0e5c09SChris Mason 
461274123bd7SChris Mason /*
4613323ac95bSChris Mason  * a helper function to delete the leaf pointed to by path->slots[1] and
46145d4f98a2SYan Zheng  * path->nodes[1].
4615323ac95bSChris Mason  *
4616323ac95bSChris Mason  * This deletes the pointer in path->nodes[1] and frees the leaf
4617323ac95bSChris Mason  * block extent.  zero is returned if it all worked out, < 0 otherwise.
4618323ac95bSChris Mason  *
4619323ac95bSChris Mason  * The path must have already been setup for deleting the leaf, including
4620323ac95bSChris Mason  * all the proper balancing.  path->nodes[1] must be locked.
4621323ac95bSChris Mason  */
4622143bede5SJeff Mahoney static noinline void btrfs_del_leaf(struct btrfs_trans_handle *trans,
4623323ac95bSChris Mason 				    struct btrfs_root *root,
46245d4f98a2SYan Zheng 				    struct btrfs_path *path,
46255d4f98a2SYan Zheng 				    struct extent_buffer *leaf)
4626323ac95bSChris Mason {
46275d4f98a2SYan Zheng 	WARN_ON(btrfs_header_generation(leaf) != trans->transid);
4628f3ea38daSJan Schmidt 	del_ptr(trans, root, path, 1, path->slots[1], 1);
4629323ac95bSChris Mason 
46304d081c41SChris Mason 	/*
46314d081c41SChris Mason 	 * btrfs_free_extent is expensive, we want to make sure we
46324d081c41SChris Mason 	 * aren't holding any locks when we call it
46334d081c41SChris Mason 	 */
46344d081c41SChris Mason 	btrfs_unlock_up_safe(path, 0);
46354d081c41SChris Mason 
4636f0486c68SYan, Zheng 	root_sub_used(root, leaf->len);
4637f0486c68SYan, Zheng 
46383083ee2eSJosef Bacik 	extent_buffer_get(leaf);
46395581a51aSJan Schmidt 	btrfs_free_tree_block(trans, root, leaf, 0, 1);
46403083ee2eSJosef Bacik 	free_extent_buffer_stale(leaf);
4641323ac95bSChris Mason }
4642323ac95bSChris Mason /*
464374123bd7SChris Mason  * delete the item at the leaf level in path.  If that empties
464474123bd7SChris Mason  * the leaf, remove it from the tree
464574123bd7SChris Mason  */
464685e21bacSChris Mason int btrfs_del_items(struct btrfs_trans_handle *trans, struct btrfs_root *root,
464785e21bacSChris Mason 		    struct btrfs_path *path, int slot, int nr)
4648be0e5c09SChris Mason {
46495f39d397SChris Mason 	struct extent_buffer *leaf;
46505f39d397SChris Mason 	struct btrfs_item *item;
465185e21bacSChris Mason 	int last_off;
465285e21bacSChris Mason 	int dsize = 0;
4653aa5d6bedSChris Mason 	int ret = 0;
4654aa5d6bedSChris Mason 	int wret;
465585e21bacSChris Mason 	int i;
46567518a238SChris Mason 	u32 nritems;
4657cfed81a0SChris Mason 	struct btrfs_map_token token;
4658cfed81a0SChris Mason 
4659cfed81a0SChris Mason 	btrfs_init_map_token(&token);
4660be0e5c09SChris Mason 
46615f39d397SChris Mason 	leaf = path->nodes[0];
466285e21bacSChris Mason 	last_off = btrfs_item_offset_nr(leaf, slot + nr - 1);
466385e21bacSChris Mason 
466485e21bacSChris Mason 	for (i = 0; i < nr; i++)
466585e21bacSChris Mason 		dsize += btrfs_item_size_nr(leaf, slot + i);
466685e21bacSChris Mason 
46675f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
4668be0e5c09SChris Mason 
466985e21bacSChris Mason 	if (slot + nr != nritems) {
4670123abc88SChris Mason 		int data_end = leaf_data_end(root, leaf);
46715f39d397SChris Mason 
46725f39d397SChris Mason 		memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
4673d6025579SChris Mason 			      data_end + dsize,
4674123abc88SChris Mason 			      btrfs_leaf_data(leaf) + data_end,
467585e21bacSChris Mason 			      last_off - data_end);
46765f39d397SChris Mason 
467785e21bacSChris Mason 		for (i = slot + nr; i < nritems; i++) {
46785f39d397SChris Mason 			u32 ioff;
4679db94535dSChris Mason 
46805f39d397SChris Mason 			item = btrfs_item_nr(leaf, i);
4681cfed81a0SChris Mason 			ioff = btrfs_token_item_offset(leaf, item, &token);
4682cfed81a0SChris Mason 			btrfs_set_token_item_offset(leaf, item,
4683cfed81a0SChris Mason 						    ioff + dsize, &token);
46840783fcfcSChris Mason 		}
4685db94535dSChris Mason 
46865f39d397SChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot),
468785e21bacSChris Mason 			      btrfs_item_nr_offset(slot + nr),
46880783fcfcSChris Mason 			      sizeof(struct btrfs_item) *
468985e21bacSChris Mason 			      (nritems - slot - nr));
4690be0e5c09SChris Mason 	}
469185e21bacSChris Mason 	btrfs_set_header_nritems(leaf, nritems - nr);
469285e21bacSChris Mason 	nritems -= nr;
46935f39d397SChris Mason 
469474123bd7SChris Mason 	/* delete the leaf if we've emptied it */
46957518a238SChris Mason 	if (nritems == 0) {
46965f39d397SChris Mason 		if (leaf == root->node) {
46975f39d397SChris Mason 			btrfs_set_header_level(leaf, 0);
46989a8dd150SChris Mason 		} else {
4699f0486c68SYan, Zheng 			btrfs_set_path_blocking(path);
4700f0486c68SYan, Zheng 			clean_tree_block(trans, root, leaf);
4701143bede5SJeff Mahoney 			btrfs_del_leaf(trans, root, path, leaf);
47029a8dd150SChris Mason 		}
4703be0e5c09SChris Mason 	} else {
47047518a238SChris Mason 		int used = leaf_space_used(leaf, 0, nritems);
4705aa5d6bedSChris Mason 		if (slot == 0) {
47065f39d397SChris Mason 			struct btrfs_disk_key disk_key;
47075f39d397SChris Mason 
47085f39d397SChris Mason 			btrfs_item_key(leaf, &disk_key, 0);
4709143bede5SJeff Mahoney 			fixup_low_keys(trans, root, path, &disk_key, 1);
4710aa5d6bedSChris Mason 		}
4711aa5d6bedSChris Mason 
471274123bd7SChris Mason 		/* delete the leaf if it is mostly empty */
4713d717aa1dSYan Zheng 		if (used < BTRFS_LEAF_DATA_SIZE(root) / 3) {
4714be0e5c09SChris Mason 			/* push_leaf_left fixes the path.
4715be0e5c09SChris Mason 			 * make sure the path still points to our leaf
4716be0e5c09SChris Mason 			 * for possible call to del_ptr below
4717be0e5c09SChris Mason 			 */
47184920c9acSChris Mason 			slot = path->slots[1];
47195f39d397SChris Mason 			extent_buffer_get(leaf);
47205f39d397SChris Mason 
4721b9473439SChris Mason 			btrfs_set_path_blocking(path);
472299d8f83cSChris Mason 			wret = push_leaf_left(trans, root, path, 1, 1,
472399d8f83cSChris Mason 					      1, (u32)-1);
472454aa1f4dSChris Mason 			if (wret < 0 && wret != -ENOSPC)
4725aa5d6bedSChris Mason 				ret = wret;
47265f39d397SChris Mason 
47275f39d397SChris Mason 			if (path->nodes[0] == leaf &&
47285f39d397SChris Mason 			    btrfs_header_nritems(leaf)) {
472999d8f83cSChris Mason 				wret = push_leaf_right(trans, root, path, 1,
473099d8f83cSChris Mason 						       1, 1, 0);
473154aa1f4dSChris Mason 				if (wret < 0 && wret != -ENOSPC)
4732aa5d6bedSChris Mason 					ret = wret;
4733aa5d6bedSChris Mason 			}
47345f39d397SChris Mason 
47355f39d397SChris Mason 			if (btrfs_header_nritems(leaf) == 0) {
4736323ac95bSChris Mason 				path->slots[1] = slot;
4737143bede5SJeff Mahoney 				btrfs_del_leaf(trans, root, path, leaf);
47385f39d397SChris Mason 				free_extent_buffer(leaf);
4739143bede5SJeff Mahoney 				ret = 0;
47405de08d7dSChris Mason 			} else {
4741925baeddSChris Mason 				/* if we're still in the path, make sure
4742925baeddSChris Mason 				 * we're dirty.  Otherwise, one of the
4743925baeddSChris Mason 				 * push_leaf functions must have already
4744925baeddSChris Mason 				 * dirtied this buffer
4745925baeddSChris Mason 				 */
4746925baeddSChris Mason 				if (path->nodes[0] == leaf)
47475f39d397SChris Mason 					btrfs_mark_buffer_dirty(leaf);
47485f39d397SChris Mason 				free_extent_buffer(leaf);
4749be0e5c09SChris Mason 			}
4750d5719762SChris Mason 		} else {
47515f39d397SChris Mason 			btrfs_mark_buffer_dirty(leaf);
4752be0e5c09SChris Mason 		}
47539a8dd150SChris Mason 	}
4754aa5d6bedSChris Mason 	return ret;
47559a8dd150SChris Mason }
47569a8dd150SChris Mason 
475797571fd0SChris Mason /*
4758925baeddSChris Mason  * search the tree again to find a leaf with lesser keys
47597bb86316SChris Mason  * returns 0 if it found something or 1 if there are no lesser leaves.
47607bb86316SChris Mason  * returns < 0 on io errors.
4761d352ac68SChris Mason  *
4762d352ac68SChris Mason  * This may release the path, and so you may lose any locks held at the
4763d352ac68SChris Mason  * time you call it.
47647bb86316SChris Mason  */
47657bb86316SChris Mason int btrfs_prev_leaf(struct btrfs_root *root, struct btrfs_path *path)
47667bb86316SChris Mason {
4767925baeddSChris Mason 	struct btrfs_key key;
4768925baeddSChris Mason 	struct btrfs_disk_key found_key;
4769925baeddSChris Mason 	int ret;
47707bb86316SChris Mason 
4771925baeddSChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, 0);
4772925baeddSChris Mason 
4773925baeddSChris Mason 	if (key.offset > 0)
4774925baeddSChris Mason 		key.offset--;
4775925baeddSChris Mason 	else if (key.type > 0)
4776925baeddSChris Mason 		key.type--;
4777925baeddSChris Mason 	else if (key.objectid > 0)
4778925baeddSChris Mason 		key.objectid--;
4779925baeddSChris Mason 	else
47807bb86316SChris Mason 		return 1;
47817bb86316SChris Mason 
4782b3b4aa74SDavid Sterba 	btrfs_release_path(path);
4783925baeddSChris Mason 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4784925baeddSChris Mason 	if (ret < 0)
4785925baeddSChris Mason 		return ret;
4786925baeddSChris Mason 	btrfs_item_key(path->nodes[0], &found_key, 0);
4787925baeddSChris Mason 	ret = comp_keys(&found_key, &key);
4788925baeddSChris Mason 	if (ret < 0)
47897bb86316SChris Mason 		return 0;
4790925baeddSChris Mason 	return 1;
47917bb86316SChris Mason }
47927bb86316SChris Mason 
47933f157a2fSChris Mason /*
47943f157a2fSChris Mason  * A helper function to walk down the tree starting at min_key, and looking
47953f157a2fSChris Mason  * for nodes or leaves that are either in cache or have a minimum
4796d352ac68SChris Mason  * transaction id.  This is used by the btree defrag code, and tree logging
47973f157a2fSChris Mason  *
47983f157a2fSChris Mason  * This does not cow, but it does stuff the starting key it finds back
47993f157a2fSChris Mason  * into min_key, so you can call btrfs_search_slot with cow=1 on the
48003f157a2fSChris Mason  * key and get a writable path.
48013f157a2fSChris Mason  *
48023f157a2fSChris Mason  * This does lock as it descends, and path->keep_locks should be set
48033f157a2fSChris Mason  * to 1 by the caller.
48043f157a2fSChris Mason  *
48053f157a2fSChris Mason  * This honors path->lowest_level to prevent descent past a given level
48063f157a2fSChris Mason  * of the tree.
48073f157a2fSChris Mason  *
4808d352ac68SChris Mason  * min_trans indicates the oldest transaction that you are interested
4809d352ac68SChris Mason  * in walking through.  Any nodes or leaves older than min_trans are
4810d352ac68SChris Mason  * skipped over (without reading them).
4811d352ac68SChris Mason  *
48123f157a2fSChris Mason  * returns zero if something useful was found, < 0 on error and 1 if there
48133f157a2fSChris Mason  * was nothing in the tree that matched the search criteria.
48143f157a2fSChris Mason  */
48153f157a2fSChris Mason int btrfs_search_forward(struct btrfs_root *root, struct btrfs_key *min_key,
4816e02119d5SChris Mason 			 struct btrfs_key *max_key,
48173f157a2fSChris Mason 			 struct btrfs_path *path, int cache_only,
48183f157a2fSChris Mason 			 u64 min_trans)
48193f157a2fSChris Mason {
48203f157a2fSChris Mason 	struct extent_buffer *cur;
48213f157a2fSChris Mason 	struct btrfs_key found_key;
48223f157a2fSChris Mason 	int slot;
48239652480bSYan 	int sret;
48243f157a2fSChris Mason 	u32 nritems;
48253f157a2fSChris Mason 	int level;
48263f157a2fSChris Mason 	int ret = 1;
48273f157a2fSChris Mason 
4828934d375bSChris Mason 	WARN_ON(!path->keep_locks);
48293f157a2fSChris Mason again:
4830bd681513SChris Mason 	cur = btrfs_read_lock_root_node(root);
48313f157a2fSChris Mason 	level = btrfs_header_level(cur);
4832e02119d5SChris Mason 	WARN_ON(path->nodes[level]);
48333f157a2fSChris Mason 	path->nodes[level] = cur;
4834bd681513SChris Mason 	path->locks[level] = BTRFS_READ_LOCK;
48353f157a2fSChris Mason 
48363f157a2fSChris Mason 	if (btrfs_header_generation(cur) < min_trans) {
48373f157a2fSChris Mason 		ret = 1;
48383f157a2fSChris Mason 		goto out;
48393f157a2fSChris Mason 	}
48403f157a2fSChris Mason 	while (1) {
48413f157a2fSChris Mason 		nritems = btrfs_header_nritems(cur);
48423f157a2fSChris Mason 		level = btrfs_header_level(cur);
48439652480bSYan 		sret = bin_search(cur, min_key, level, &slot);
48443f157a2fSChris Mason 
4845323ac95bSChris Mason 		/* at the lowest level, we're done, setup the path and exit */
4846323ac95bSChris Mason 		if (level == path->lowest_level) {
4847e02119d5SChris Mason 			if (slot >= nritems)
4848e02119d5SChris Mason 				goto find_next_key;
48493f157a2fSChris Mason 			ret = 0;
48503f157a2fSChris Mason 			path->slots[level] = slot;
48513f157a2fSChris Mason 			btrfs_item_key_to_cpu(cur, &found_key, slot);
48523f157a2fSChris Mason 			goto out;
48533f157a2fSChris Mason 		}
48549652480bSYan 		if (sret && slot > 0)
48559652480bSYan 			slot--;
48563f157a2fSChris Mason 		/*
48573f157a2fSChris Mason 		 * check this node pointer against the cache_only and
48583f157a2fSChris Mason 		 * min_trans parameters.  If it isn't in cache or is too
48593f157a2fSChris Mason 		 * old, skip to the next one.
48603f157a2fSChris Mason 		 */
48613f157a2fSChris Mason 		while (slot < nritems) {
48623f157a2fSChris Mason 			u64 blockptr;
48633f157a2fSChris Mason 			u64 gen;
48643f157a2fSChris Mason 			struct extent_buffer *tmp;
4865e02119d5SChris Mason 			struct btrfs_disk_key disk_key;
4866e02119d5SChris Mason 
48673f157a2fSChris Mason 			blockptr = btrfs_node_blockptr(cur, slot);
48683f157a2fSChris Mason 			gen = btrfs_node_ptr_generation(cur, slot);
48693f157a2fSChris Mason 			if (gen < min_trans) {
48703f157a2fSChris Mason 				slot++;
48713f157a2fSChris Mason 				continue;
48723f157a2fSChris Mason 			}
48733f157a2fSChris Mason 			if (!cache_only)
48743f157a2fSChris Mason 				break;
48753f157a2fSChris Mason 
4876e02119d5SChris Mason 			if (max_key) {
4877e02119d5SChris Mason 				btrfs_node_key(cur, &disk_key, slot);
4878e02119d5SChris Mason 				if (comp_keys(&disk_key, max_key) >= 0) {
4879e02119d5SChris Mason 					ret = 1;
4880e02119d5SChris Mason 					goto out;
4881e02119d5SChris Mason 				}
4882e02119d5SChris Mason 			}
4883e02119d5SChris Mason 
48843f157a2fSChris Mason 			tmp = btrfs_find_tree_block(root, blockptr,
48853f157a2fSChris Mason 					    btrfs_level_size(root, level - 1));
48863f157a2fSChris Mason 
4887b9fab919SChris Mason 			if (tmp && btrfs_buffer_uptodate(tmp, gen, 1) > 0) {
48883f157a2fSChris Mason 				free_extent_buffer(tmp);
48893f157a2fSChris Mason 				break;
48903f157a2fSChris Mason 			}
48913f157a2fSChris Mason 			if (tmp)
48923f157a2fSChris Mason 				free_extent_buffer(tmp);
48933f157a2fSChris Mason 			slot++;
48943f157a2fSChris Mason 		}
4895e02119d5SChris Mason find_next_key:
48963f157a2fSChris Mason 		/*
48973f157a2fSChris Mason 		 * we didn't find a candidate key in this node, walk forward
48983f157a2fSChris Mason 		 * and find another one
48993f157a2fSChris Mason 		 */
49003f157a2fSChris Mason 		if (slot >= nritems) {
4901e02119d5SChris Mason 			path->slots[level] = slot;
4902b4ce94deSChris Mason 			btrfs_set_path_blocking(path);
4903e02119d5SChris Mason 			sret = btrfs_find_next_key(root, path, min_key, level,
49043f157a2fSChris Mason 						  cache_only, min_trans);
4905e02119d5SChris Mason 			if (sret == 0) {
4906b3b4aa74SDavid Sterba 				btrfs_release_path(path);
49073f157a2fSChris Mason 				goto again;
49083f157a2fSChris Mason 			} else {
49093f157a2fSChris Mason 				goto out;
49103f157a2fSChris Mason 			}
49113f157a2fSChris Mason 		}
49123f157a2fSChris Mason 		/* save our key for returning back */
49133f157a2fSChris Mason 		btrfs_node_key_to_cpu(cur, &found_key, slot);
49143f157a2fSChris Mason 		path->slots[level] = slot;
49153f157a2fSChris Mason 		if (level == path->lowest_level) {
49163f157a2fSChris Mason 			ret = 0;
4917f7c79f30SChris Mason 			unlock_up(path, level, 1, 0, NULL);
49183f157a2fSChris Mason 			goto out;
49193f157a2fSChris Mason 		}
4920b4ce94deSChris Mason 		btrfs_set_path_blocking(path);
49213f157a2fSChris Mason 		cur = read_node_slot(root, cur, slot);
492279787eaaSJeff Mahoney 		BUG_ON(!cur); /* -ENOMEM */
49233f157a2fSChris Mason 
4924bd681513SChris Mason 		btrfs_tree_read_lock(cur);
4925b4ce94deSChris Mason 
4926bd681513SChris Mason 		path->locks[level - 1] = BTRFS_READ_LOCK;
49273f157a2fSChris Mason 		path->nodes[level - 1] = cur;
4928f7c79f30SChris Mason 		unlock_up(path, level, 1, 0, NULL);
4929bd681513SChris Mason 		btrfs_clear_path_blocking(path, NULL, 0);
49303f157a2fSChris Mason 	}
49313f157a2fSChris Mason out:
49323f157a2fSChris Mason 	if (ret == 0)
49333f157a2fSChris Mason 		memcpy(min_key, &found_key, sizeof(found_key));
4934b4ce94deSChris Mason 	btrfs_set_path_blocking(path);
49353f157a2fSChris Mason 	return ret;
49363f157a2fSChris Mason }
49373f157a2fSChris Mason 
49383f157a2fSChris Mason /*
49393f157a2fSChris Mason  * this is similar to btrfs_next_leaf, but does not try to preserve
49403f157a2fSChris Mason  * and fixup the path.  It looks for and returns the next key in the
49413f157a2fSChris Mason  * tree based on the current path and the cache_only and min_trans
49423f157a2fSChris Mason  * parameters.
49433f157a2fSChris Mason  *
49443f157a2fSChris Mason  * 0 is returned if another key is found, < 0 if there are any errors
49453f157a2fSChris Mason  * and 1 is returned if there are no higher keys in the tree
49463f157a2fSChris Mason  *
49473f157a2fSChris Mason  * path->keep_locks should be set to 1 on the search made before
49483f157a2fSChris Mason  * calling this function.
49493f157a2fSChris Mason  */
4950e7a84565SChris Mason int btrfs_find_next_key(struct btrfs_root *root, struct btrfs_path *path,
495133c66f43SYan Zheng 			struct btrfs_key *key, int level,
49523f157a2fSChris Mason 			int cache_only, u64 min_trans)
4953e7a84565SChris Mason {
4954e7a84565SChris Mason 	int slot;
4955e7a84565SChris Mason 	struct extent_buffer *c;
4956e7a84565SChris Mason 
4957934d375bSChris Mason 	WARN_ON(!path->keep_locks);
4958e7a84565SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
4959e7a84565SChris Mason 		if (!path->nodes[level])
4960e7a84565SChris Mason 			return 1;
4961e7a84565SChris Mason 
4962e7a84565SChris Mason 		slot = path->slots[level] + 1;
4963e7a84565SChris Mason 		c = path->nodes[level];
49643f157a2fSChris Mason next:
4965e7a84565SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
496633c66f43SYan Zheng 			int ret;
496733c66f43SYan Zheng 			int orig_lowest;
496833c66f43SYan Zheng 			struct btrfs_key cur_key;
496933c66f43SYan Zheng 			if (level + 1 >= BTRFS_MAX_LEVEL ||
497033c66f43SYan Zheng 			    !path->nodes[level + 1])
4971e7a84565SChris Mason 				return 1;
497233c66f43SYan Zheng 
497333c66f43SYan Zheng 			if (path->locks[level + 1]) {
497433c66f43SYan Zheng 				level++;
4975e7a84565SChris Mason 				continue;
4976e7a84565SChris Mason 			}
497733c66f43SYan Zheng 
497833c66f43SYan Zheng 			slot = btrfs_header_nritems(c) - 1;
497933c66f43SYan Zheng 			if (level == 0)
498033c66f43SYan Zheng 				btrfs_item_key_to_cpu(c, &cur_key, slot);
498133c66f43SYan Zheng 			else
498233c66f43SYan Zheng 				btrfs_node_key_to_cpu(c, &cur_key, slot);
498333c66f43SYan Zheng 
498433c66f43SYan Zheng 			orig_lowest = path->lowest_level;
4985b3b4aa74SDavid Sterba 			btrfs_release_path(path);
498633c66f43SYan Zheng 			path->lowest_level = level;
498733c66f43SYan Zheng 			ret = btrfs_search_slot(NULL, root, &cur_key, path,
498833c66f43SYan Zheng 						0, 0);
498933c66f43SYan Zheng 			path->lowest_level = orig_lowest;
499033c66f43SYan Zheng 			if (ret < 0)
499133c66f43SYan Zheng 				return ret;
499233c66f43SYan Zheng 
499333c66f43SYan Zheng 			c = path->nodes[level];
499433c66f43SYan Zheng 			slot = path->slots[level];
499533c66f43SYan Zheng 			if (ret == 0)
499633c66f43SYan Zheng 				slot++;
499733c66f43SYan Zheng 			goto next;
499833c66f43SYan Zheng 		}
499933c66f43SYan Zheng 
5000e7a84565SChris Mason 		if (level == 0)
5001e7a84565SChris Mason 			btrfs_item_key_to_cpu(c, key, slot);
50023f157a2fSChris Mason 		else {
50033f157a2fSChris Mason 			u64 blockptr = btrfs_node_blockptr(c, slot);
50043f157a2fSChris Mason 			u64 gen = btrfs_node_ptr_generation(c, slot);
50053f157a2fSChris Mason 
50063f157a2fSChris Mason 			if (cache_only) {
50073f157a2fSChris Mason 				struct extent_buffer *cur;
50083f157a2fSChris Mason 				cur = btrfs_find_tree_block(root, blockptr,
50093f157a2fSChris Mason 					    btrfs_level_size(root, level - 1));
5010b9fab919SChris Mason 				if (!cur ||
5011b9fab919SChris Mason 				    btrfs_buffer_uptodate(cur, gen, 1) <= 0) {
50123f157a2fSChris Mason 					slot++;
50133f157a2fSChris Mason 					if (cur)
50143f157a2fSChris Mason 						free_extent_buffer(cur);
50153f157a2fSChris Mason 					goto next;
50163f157a2fSChris Mason 				}
50173f157a2fSChris Mason 				free_extent_buffer(cur);
50183f157a2fSChris Mason 			}
50193f157a2fSChris Mason 			if (gen < min_trans) {
50203f157a2fSChris Mason 				slot++;
50213f157a2fSChris Mason 				goto next;
50223f157a2fSChris Mason 			}
5023e7a84565SChris Mason 			btrfs_node_key_to_cpu(c, key, slot);
50243f157a2fSChris Mason 		}
5025e7a84565SChris Mason 		return 0;
5026e7a84565SChris Mason 	}
5027e7a84565SChris Mason 	return 1;
5028e7a84565SChris Mason }
5029e7a84565SChris Mason 
50307bb86316SChris Mason /*
5031925baeddSChris Mason  * search the tree again to find a leaf with greater keys
50320f70abe2SChris Mason  * returns 0 if it found something or 1 if there are no greater leaves.
50330f70abe2SChris Mason  * returns < 0 on io errors.
503497571fd0SChris Mason  */
5035234b63a0SChris Mason int btrfs_next_leaf(struct btrfs_root *root, struct btrfs_path *path)
5036d97e63b6SChris Mason {
50373d7806ecSJan Schmidt 	return btrfs_next_old_leaf(root, path, 0);
50383d7806ecSJan Schmidt }
50393d7806ecSJan Schmidt 
50403d7806ecSJan Schmidt int btrfs_next_old_leaf(struct btrfs_root *root, struct btrfs_path *path,
50413d7806ecSJan Schmidt 			u64 time_seq)
50423d7806ecSJan Schmidt {
5043d97e63b6SChris Mason 	int slot;
50448e73f275SChris Mason 	int level;
50455f39d397SChris Mason 	struct extent_buffer *c;
50468e73f275SChris Mason 	struct extent_buffer *next;
5047925baeddSChris Mason 	struct btrfs_key key;
5048925baeddSChris Mason 	u32 nritems;
5049925baeddSChris Mason 	int ret;
50508e73f275SChris Mason 	int old_spinning = path->leave_spinning;
5051bd681513SChris Mason 	int next_rw_lock = 0;
5052925baeddSChris Mason 
5053925baeddSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
5054d397712bSChris Mason 	if (nritems == 0)
5055925baeddSChris Mason 		return 1;
5056925baeddSChris Mason 
50578e73f275SChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, nritems - 1);
50588e73f275SChris Mason again:
50598e73f275SChris Mason 	level = 1;
50608e73f275SChris Mason 	next = NULL;
5061bd681513SChris Mason 	next_rw_lock = 0;
5062b3b4aa74SDavid Sterba 	btrfs_release_path(path);
50638e73f275SChris Mason 
5064a2135011SChris Mason 	path->keep_locks = 1;
50658e73f275SChris Mason 	path->leave_spinning = 1;
50668e73f275SChris Mason 
50673d7806ecSJan Schmidt 	if (time_seq)
50683d7806ecSJan Schmidt 		ret = btrfs_search_old_slot(root, &key, path, time_seq);
50693d7806ecSJan Schmidt 	else
5070925baeddSChris Mason 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5071925baeddSChris Mason 	path->keep_locks = 0;
5072925baeddSChris Mason 
5073925baeddSChris Mason 	if (ret < 0)
5074925baeddSChris Mason 		return ret;
5075925baeddSChris Mason 
5076a2135011SChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
5077168fd7d2SChris Mason 	/*
5078168fd7d2SChris Mason 	 * by releasing the path above we dropped all our locks.  A balance
5079168fd7d2SChris Mason 	 * could have added more items next to the key that used to be
5080168fd7d2SChris Mason 	 * at the very end of the block.  So, check again here and
5081168fd7d2SChris Mason 	 * advance the path if there are now more items available.
5082168fd7d2SChris Mason 	 */
5083a2135011SChris Mason 	if (nritems > 0 && path->slots[0] < nritems - 1) {
5084e457afecSYan Zheng 		if (ret == 0)
5085168fd7d2SChris Mason 			path->slots[0]++;
50868e73f275SChris Mason 		ret = 0;
5087925baeddSChris Mason 		goto done;
5088925baeddSChris Mason 	}
5089d97e63b6SChris Mason 
5090234b63a0SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
50918e73f275SChris Mason 		if (!path->nodes[level]) {
50928e73f275SChris Mason 			ret = 1;
50938e73f275SChris Mason 			goto done;
50948e73f275SChris Mason 		}
50955f39d397SChris Mason 
5096d97e63b6SChris Mason 		slot = path->slots[level] + 1;
5097d97e63b6SChris Mason 		c = path->nodes[level];
50985f39d397SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
5099d97e63b6SChris Mason 			level++;
51008e73f275SChris Mason 			if (level == BTRFS_MAX_LEVEL) {
51018e73f275SChris Mason 				ret = 1;
51028e73f275SChris Mason 				goto done;
51038e73f275SChris Mason 			}
5104d97e63b6SChris Mason 			continue;
5105d97e63b6SChris Mason 		}
51065f39d397SChris Mason 
5107925baeddSChris Mason 		if (next) {
5108bd681513SChris Mason 			btrfs_tree_unlock_rw(next, next_rw_lock);
51095f39d397SChris Mason 			free_extent_buffer(next);
5110925baeddSChris Mason 		}
51115f39d397SChris Mason 
51128e73f275SChris Mason 		next = c;
5113bd681513SChris Mason 		next_rw_lock = path->locks[level];
51148e73f275SChris Mason 		ret = read_block_for_search(NULL, root, path, &next, level,
51155d9e75c4SJan Schmidt 					    slot, &key, 0);
51168e73f275SChris Mason 		if (ret == -EAGAIN)
51178e73f275SChris Mason 			goto again;
51185f39d397SChris Mason 
511976a05b35SChris Mason 		if (ret < 0) {
5120b3b4aa74SDavid Sterba 			btrfs_release_path(path);
512176a05b35SChris Mason 			goto done;
512276a05b35SChris Mason 		}
512376a05b35SChris Mason 
51245cd57b2cSChris Mason 		if (!path->skip_locking) {
5125bd681513SChris Mason 			ret = btrfs_try_tree_read_lock(next);
51268e73f275SChris Mason 			if (!ret) {
51278e73f275SChris Mason 				btrfs_set_path_blocking(path);
5128bd681513SChris Mason 				btrfs_tree_read_lock(next);
5129bd681513SChris Mason 				btrfs_clear_path_blocking(path, next,
5130bd681513SChris Mason 							  BTRFS_READ_LOCK);
51318e73f275SChris Mason 			}
5132bd681513SChris Mason 			next_rw_lock = BTRFS_READ_LOCK;
5133bd681513SChris Mason 		}
5134d97e63b6SChris Mason 		break;
5135d97e63b6SChris Mason 	}
5136d97e63b6SChris Mason 	path->slots[level] = slot;
5137d97e63b6SChris Mason 	while (1) {
5138d97e63b6SChris Mason 		level--;
5139d97e63b6SChris Mason 		c = path->nodes[level];
5140925baeddSChris Mason 		if (path->locks[level])
5141bd681513SChris Mason 			btrfs_tree_unlock_rw(c, path->locks[level]);
51428e73f275SChris Mason 
51435f39d397SChris Mason 		free_extent_buffer(c);
5144d97e63b6SChris Mason 		path->nodes[level] = next;
5145d97e63b6SChris Mason 		path->slots[level] = 0;
5146a74a4b97SChris Mason 		if (!path->skip_locking)
5147bd681513SChris Mason 			path->locks[level] = next_rw_lock;
5148d97e63b6SChris Mason 		if (!level)
5149d97e63b6SChris Mason 			break;
5150b4ce94deSChris Mason 
51518e73f275SChris Mason 		ret = read_block_for_search(NULL, root, path, &next, level,
51525d9e75c4SJan Schmidt 					    0, &key, 0);
51538e73f275SChris Mason 		if (ret == -EAGAIN)
51548e73f275SChris Mason 			goto again;
51558e73f275SChris Mason 
515676a05b35SChris Mason 		if (ret < 0) {
5157b3b4aa74SDavid Sterba 			btrfs_release_path(path);
515876a05b35SChris Mason 			goto done;
515976a05b35SChris Mason 		}
516076a05b35SChris Mason 
51615cd57b2cSChris Mason 		if (!path->skip_locking) {
5162bd681513SChris Mason 			ret = btrfs_try_tree_read_lock(next);
51638e73f275SChris Mason 			if (!ret) {
51648e73f275SChris Mason 				btrfs_set_path_blocking(path);
5165bd681513SChris Mason 				btrfs_tree_read_lock(next);
5166bd681513SChris Mason 				btrfs_clear_path_blocking(path, next,
5167bd681513SChris Mason 							  BTRFS_READ_LOCK);
51688e73f275SChris Mason 			}
5169bd681513SChris Mason 			next_rw_lock = BTRFS_READ_LOCK;
5170bd681513SChris Mason 		}
5171d97e63b6SChris Mason 	}
51728e73f275SChris Mason 	ret = 0;
5173925baeddSChris Mason done:
5174f7c79f30SChris Mason 	unlock_up(path, 0, 1, 0, NULL);
51758e73f275SChris Mason 	path->leave_spinning = old_spinning;
51768e73f275SChris Mason 	if (!old_spinning)
51778e73f275SChris Mason 		btrfs_set_path_blocking(path);
51788e73f275SChris Mason 
51798e73f275SChris Mason 	return ret;
5180d97e63b6SChris Mason }
51810b86a832SChris Mason 
51823f157a2fSChris Mason /*
51833f157a2fSChris Mason  * this uses btrfs_prev_leaf to walk backwards in the tree, and keeps
51843f157a2fSChris Mason  * searching until it gets past min_objectid or finds an item of 'type'
51853f157a2fSChris Mason  *
51863f157a2fSChris Mason  * returns 0 if something is found, 1 if nothing was found and < 0 on error
51873f157a2fSChris Mason  */
51880b86a832SChris Mason int btrfs_previous_item(struct btrfs_root *root,
51890b86a832SChris Mason 			struct btrfs_path *path, u64 min_objectid,
51900b86a832SChris Mason 			int type)
51910b86a832SChris Mason {
51920b86a832SChris Mason 	struct btrfs_key found_key;
51930b86a832SChris Mason 	struct extent_buffer *leaf;
5194e02119d5SChris Mason 	u32 nritems;
51950b86a832SChris Mason 	int ret;
51960b86a832SChris Mason 
51970b86a832SChris Mason 	while (1) {
51980b86a832SChris Mason 		if (path->slots[0] == 0) {
5199b4ce94deSChris Mason 			btrfs_set_path_blocking(path);
52000b86a832SChris Mason 			ret = btrfs_prev_leaf(root, path);
52010b86a832SChris Mason 			if (ret != 0)
52020b86a832SChris Mason 				return ret;
52030b86a832SChris Mason 		} else {
52040b86a832SChris Mason 			path->slots[0]--;
52050b86a832SChris Mason 		}
52060b86a832SChris Mason 		leaf = path->nodes[0];
5207e02119d5SChris Mason 		nritems = btrfs_header_nritems(leaf);
5208e02119d5SChris Mason 		if (nritems == 0)
5209e02119d5SChris Mason 			return 1;
5210e02119d5SChris Mason 		if (path->slots[0] == nritems)
5211e02119d5SChris Mason 			path->slots[0]--;
5212e02119d5SChris Mason 
52130b86a832SChris Mason 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5214e02119d5SChris Mason 		if (found_key.objectid < min_objectid)
5215e02119d5SChris Mason 			break;
52160a4eefbbSYan Zheng 		if (found_key.type == type)
52170a4eefbbSYan Zheng 			return 0;
5218e02119d5SChris Mason 		if (found_key.objectid == min_objectid &&
5219e02119d5SChris Mason 		    found_key.type < type)
5220e02119d5SChris Mason 			break;
52210b86a832SChris Mason 	}
52220b86a832SChris Mason 	return 1;
52230b86a832SChris Mason }
5224