xref: /openbmc/linux/fs/btrfs/ctree.c (revision 4325edd0786fdd3909f9550e52a963b2fe54f78b)
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 		/*
10275d9e75c4SJan Schmidt 		 * we must have key remove operations in the log before the
10285d9e75c4SJan Schmidt 		 * replace operation.
10295d9e75c4SJan Schmidt 		 */
10305d9e75c4SJan Schmidt 		BUG_ON(!tm);
10315d9e75c4SJan Schmidt 
10325d9e75c4SJan Schmidt 		if (tm->op != MOD_LOG_ROOT_REPLACE)
10335d9e75c4SJan Schmidt 			break;
10345d9e75c4SJan Schmidt 
10355d9e75c4SJan Schmidt 		found = tm;
10365d9e75c4SJan Schmidt 		root_logical = tm->old_root.logical;
10375d9e75c4SJan Schmidt 		BUG_ON(root_logical == root->node->start);
10385d9e75c4SJan Schmidt 		looped = 1;
10395d9e75c4SJan Schmidt 	}
10405d9e75c4SJan Schmidt 
1041a95236d9SJan Schmidt 	/* if there's no old root to return, return what we found instead */
1042a95236d9SJan Schmidt 	if (!found)
1043a95236d9SJan Schmidt 		found = tm;
1044a95236d9SJan Schmidt 
10455d9e75c4SJan Schmidt 	return found;
10465d9e75c4SJan Schmidt }
10475d9e75c4SJan Schmidt 
10485d9e75c4SJan Schmidt /*
10495d9e75c4SJan Schmidt  * tm is a pointer to the first operation to rewind within eb. then, all
10505d9e75c4SJan Schmidt  * previous operations will be rewinded (until we reach something older than
10515d9e75c4SJan Schmidt  * time_seq).
10525d9e75c4SJan Schmidt  */
10535d9e75c4SJan Schmidt static void
10545d9e75c4SJan Schmidt __tree_mod_log_rewind(struct extent_buffer *eb, u64 time_seq,
10555d9e75c4SJan Schmidt 		      struct tree_mod_elem *first_tm)
10565d9e75c4SJan Schmidt {
10575d9e75c4SJan Schmidt 	u32 n;
10585d9e75c4SJan Schmidt 	struct rb_node *next;
10595d9e75c4SJan Schmidt 	struct tree_mod_elem *tm = first_tm;
10605d9e75c4SJan Schmidt 	unsigned long o_dst;
10615d9e75c4SJan Schmidt 	unsigned long o_src;
10625d9e75c4SJan Schmidt 	unsigned long p_size = sizeof(struct btrfs_key_ptr);
10635d9e75c4SJan Schmidt 
10645d9e75c4SJan Schmidt 	n = btrfs_header_nritems(eb);
10655d9e75c4SJan Schmidt 	while (tm && tm->elem.seq >= time_seq) {
10665d9e75c4SJan Schmidt 		/*
10675d9e75c4SJan Schmidt 		 * all the operations are recorded with the operator used for
10685d9e75c4SJan Schmidt 		 * the modification. as we're going backwards, we do the
10695d9e75c4SJan Schmidt 		 * opposite of each operation here.
10705d9e75c4SJan Schmidt 		 */
10715d9e75c4SJan Schmidt 		switch (tm->op) {
10725d9e75c4SJan Schmidt 		case MOD_LOG_KEY_REMOVE_WHILE_FREEING:
10735d9e75c4SJan Schmidt 			BUG_ON(tm->slot < n);
10745d9e75c4SJan Schmidt 		case MOD_LOG_KEY_REMOVE_WHILE_MOVING:
10755d9e75c4SJan Schmidt 		case MOD_LOG_KEY_REMOVE:
10765d9e75c4SJan Schmidt 			btrfs_set_node_key(eb, &tm->key, tm->slot);
10775d9e75c4SJan Schmidt 			btrfs_set_node_blockptr(eb, tm->slot, tm->blockptr);
10785d9e75c4SJan Schmidt 			btrfs_set_node_ptr_generation(eb, tm->slot,
10795d9e75c4SJan Schmidt 						      tm->generation);
10805d9e75c4SJan Schmidt 			n++;
10815d9e75c4SJan Schmidt 			break;
10825d9e75c4SJan Schmidt 		case MOD_LOG_KEY_REPLACE:
10835d9e75c4SJan Schmidt 			BUG_ON(tm->slot >= n);
10845d9e75c4SJan Schmidt 			btrfs_set_node_key(eb, &tm->key, tm->slot);
10855d9e75c4SJan Schmidt 			btrfs_set_node_blockptr(eb, tm->slot, tm->blockptr);
10865d9e75c4SJan Schmidt 			btrfs_set_node_ptr_generation(eb, tm->slot,
10875d9e75c4SJan Schmidt 						      tm->generation);
10885d9e75c4SJan Schmidt 			break;
10895d9e75c4SJan Schmidt 		case MOD_LOG_KEY_ADD:
10905d9e75c4SJan Schmidt 			if (tm->slot != n - 1) {
10915d9e75c4SJan Schmidt 				o_dst = btrfs_node_key_ptr_offset(tm->slot);
10925d9e75c4SJan Schmidt 				o_src = btrfs_node_key_ptr_offset(tm->slot + 1);
10935d9e75c4SJan Schmidt 				memmove_extent_buffer(eb, o_dst, o_src, p_size);
10945d9e75c4SJan Schmidt 			}
10955d9e75c4SJan Schmidt 			n--;
10965d9e75c4SJan Schmidt 			break;
10975d9e75c4SJan Schmidt 		case MOD_LOG_MOVE_KEYS:
1098c3193108SJan Schmidt 			o_dst = btrfs_node_key_ptr_offset(tm->slot);
1099c3193108SJan Schmidt 			o_src = btrfs_node_key_ptr_offset(tm->move.dst_slot);
1100c3193108SJan Schmidt 			memmove_extent_buffer(eb, o_dst, o_src,
11015d9e75c4SJan Schmidt 					      tm->move.nr_items * p_size);
11025d9e75c4SJan Schmidt 			break;
11035d9e75c4SJan Schmidt 		case MOD_LOG_ROOT_REPLACE:
11045d9e75c4SJan Schmidt 			/*
11055d9e75c4SJan Schmidt 			 * this operation is special. for roots, this must be
11065d9e75c4SJan Schmidt 			 * handled explicitly before rewinding.
11075d9e75c4SJan Schmidt 			 * for non-roots, this operation may exist if the node
11085d9e75c4SJan Schmidt 			 * was a root: root A -> child B; then A gets empty and
11095d9e75c4SJan Schmidt 			 * B is promoted to the new root. in the mod log, we'll
11105d9e75c4SJan Schmidt 			 * have a root-replace operation for B, a tree block
11115d9e75c4SJan Schmidt 			 * that is no root. we simply ignore that operation.
11125d9e75c4SJan Schmidt 			 */
11135d9e75c4SJan Schmidt 			break;
11145d9e75c4SJan Schmidt 		}
11155d9e75c4SJan Schmidt 		next = rb_next(&tm->node);
11165d9e75c4SJan Schmidt 		if (!next)
11175d9e75c4SJan Schmidt 			break;
11185d9e75c4SJan Schmidt 		tm = container_of(next, struct tree_mod_elem, node);
11195d9e75c4SJan Schmidt 		if (tm->index != first_tm->index)
11205d9e75c4SJan Schmidt 			break;
11215d9e75c4SJan Schmidt 	}
11225d9e75c4SJan Schmidt 	btrfs_set_header_nritems(eb, n);
11235d9e75c4SJan Schmidt }
11245d9e75c4SJan Schmidt 
11255d9e75c4SJan Schmidt static struct extent_buffer *
11265d9e75c4SJan Schmidt tree_mod_log_rewind(struct btrfs_fs_info *fs_info, struct extent_buffer *eb,
11275d9e75c4SJan Schmidt 		    u64 time_seq)
11285d9e75c4SJan Schmidt {
11295d9e75c4SJan Schmidt 	struct extent_buffer *eb_rewin;
11305d9e75c4SJan Schmidt 	struct tree_mod_elem *tm;
11315d9e75c4SJan Schmidt 
11325d9e75c4SJan Schmidt 	if (!time_seq)
11335d9e75c4SJan Schmidt 		return eb;
11345d9e75c4SJan Schmidt 
11355d9e75c4SJan Schmidt 	if (btrfs_header_level(eb) == 0)
11365d9e75c4SJan Schmidt 		return eb;
11375d9e75c4SJan Schmidt 
11385d9e75c4SJan Schmidt 	tm = tree_mod_log_search(fs_info, eb->start, time_seq);
11395d9e75c4SJan Schmidt 	if (!tm)
11405d9e75c4SJan Schmidt 		return eb;
11415d9e75c4SJan Schmidt 
11425d9e75c4SJan Schmidt 	if (tm->op == MOD_LOG_KEY_REMOVE_WHILE_FREEING) {
11435d9e75c4SJan Schmidt 		BUG_ON(tm->slot != 0);
11445d9e75c4SJan Schmidt 		eb_rewin = alloc_dummy_extent_buffer(eb->start,
11455d9e75c4SJan Schmidt 						fs_info->tree_root->nodesize);
11465d9e75c4SJan Schmidt 		BUG_ON(!eb_rewin);
11475d9e75c4SJan Schmidt 		btrfs_set_header_bytenr(eb_rewin, eb->start);
11485d9e75c4SJan Schmidt 		btrfs_set_header_backref_rev(eb_rewin,
11495d9e75c4SJan Schmidt 					     btrfs_header_backref_rev(eb));
11505d9e75c4SJan Schmidt 		btrfs_set_header_owner(eb_rewin, btrfs_header_owner(eb));
1151c3193108SJan Schmidt 		btrfs_set_header_level(eb_rewin, btrfs_header_level(eb));
11525d9e75c4SJan Schmidt 	} else {
11535d9e75c4SJan Schmidt 		eb_rewin = btrfs_clone_extent_buffer(eb);
11545d9e75c4SJan Schmidt 		BUG_ON(!eb_rewin);
11555d9e75c4SJan Schmidt 	}
11565d9e75c4SJan Schmidt 
11575d9e75c4SJan Schmidt 	extent_buffer_get(eb_rewin);
11585d9e75c4SJan Schmidt 	free_extent_buffer(eb);
11595d9e75c4SJan Schmidt 
11605d9e75c4SJan Schmidt 	__tree_mod_log_rewind(eb_rewin, time_seq, tm);
11615d9e75c4SJan Schmidt 
11625d9e75c4SJan Schmidt 	return eb_rewin;
11635d9e75c4SJan Schmidt }
11645d9e75c4SJan Schmidt 
11658ba97a15SJan Schmidt /*
11668ba97a15SJan Schmidt  * get_old_root() rewinds the state of @root's root node to the given @time_seq
11678ba97a15SJan Schmidt  * value. If there are no changes, the current root->root_node is returned. If
11688ba97a15SJan Schmidt  * anything changed in between, there's a fresh buffer allocated on which the
11698ba97a15SJan Schmidt  * rewind operations are done. In any case, the returned buffer is read locked.
11708ba97a15SJan Schmidt  * Returns NULL on error (with no locks held).
11718ba97a15SJan Schmidt  */
11725d9e75c4SJan Schmidt static inline struct extent_buffer *
11735d9e75c4SJan Schmidt get_old_root(struct btrfs_root *root, u64 time_seq)
11745d9e75c4SJan Schmidt {
11755d9e75c4SJan Schmidt 	struct tree_mod_elem *tm;
11765d9e75c4SJan Schmidt 	struct extent_buffer *eb;
1177a95236d9SJan Schmidt 	struct tree_mod_root *old_root = NULL;
1178*4325edd0SChris Mason 	u64 old_generation = 0;
1179a95236d9SJan Schmidt 	u64 logical;
11805d9e75c4SJan Schmidt 
11818ba97a15SJan Schmidt 	eb = btrfs_read_lock_root_node(root);
11825d9e75c4SJan Schmidt 	tm = __tree_mod_log_oldest_root(root->fs_info, root, time_seq);
11835d9e75c4SJan Schmidt 	if (!tm)
11845d9e75c4SJan Schmidt 		return root->node;
11855d9e75c4SJan Schmidt 
1186a95236d9SJan Schmidt 	if (tm->op == MOD_LOG_ROOT_REPLACE) {
11875d9e75c4SJan Schmidt 		old_root = &tm->old_root;
11885d9e75c4SJan Schmidt 		old_generation = tm->generation;
1189a95236d9SJan Schmidt 		logical = old_root->logical;
1190a95236d9SJan Schmidt 	} else {
1191a95236d9SJan Schmidt 		logical = root->node->start;
1192a95236d9SJan Schmidt 	}
11935d9e75c4SJan Schmidt 
1194a95236d9SJan Schmidt 	tm = tree_mod_log_search(root->fs_info, logical, time_seq);
11955d9e75c4SJan Schmidt 	/*
11965d9e75c4SJan Schmidt 	 * there was an item in the log when __tree_mod_log_oldest_root
11975d9e75c4SJan Schmidt 	 * returned. this one must not go away, because the time_seq passed to
11985d9e75c4SJan Schmidt 	 * us must be blocking its removal.
11995d9e75c4SJan Schmidt 	 */
12005d9e75c4SJan Schmidt 	BUG_ON(!tm);
12015d9e75c4SJan Schmidt 
1202a95236d9SJan Schmidt 	if (old_root)
12035d9e75c4SJan Schmidt 		eb = alloc_dummy_extent_buffer(tm->index << PAGE_CACHE_SHIFT,
12045d9e75c4SJan Schmidt 					       root->nodesize);
1205a95236d9SJan Schmidt 	else
1206a95236d9SJan Schmidt 		eb = btrfs_clone_extent_buffer(root->node);
12078ba97a15SJan Schmidt 	btrfs_tree_read_unlock(root->node);
12088ba97a15SJan Schmidt 	free_extent_buffer(root->node);
12098ba97a15SJan Schmidt 	if (!eb)
12108ba97a15SJan Schmidt 		return NULL;
12118ba97a15SJan Schmidt 	btrfs_tree_read_lock(eb);
1212a95236d9SJan Schmidt 	if (old_root) {
12135d9e75c4SJan Schmidt 		btrfs_set_header_bytenr(eb, eb->start);
12145d9e75c4SJan Schmidt 		btrfs_set_header_backref_rev(eb, BTRFS_MIXED_BACKREF_REV);
12155d9e75c4SJan Schmidt 		btrfs_set_header_owner(eb, root->root_key.objectid);
12165d9e75c4SJan Schmidt 		btrfs_set_header_level(eb, old_root->level);
12175d9e75c4SJan Schmidt 		btrfs_set_header_generation(eb, old_generation);
1218a95236d9SJan Schmidt 	}
12195d9e75c4SJan Schmidt 	__tree_mod_log_rewind(eb, time_seq, tm);
12208ba97a15SJan Schmidt 	extent_buffer_get(eb);
12215d9e75c4SJan Schmidt 
12225d9e75c4SJan Schmidt 	return eb;
12235d9e75c4SJan Schmidt }
12245d9e75c4SJan Schmidt 
12255d4f98a2SYan Zheng static inline int should_cow_block(struct btrfs_trans_handle *trans,
12265d4f98a2SYan Zheng 				   struct btrfs_root *root,
12275d4f98a2SYan Zheng 				   struct extent_buffer *buf)
12285d4f98a2SYan Zheng {
1229f1ebcc74SLiu Bo 	/* ensure we can see the force_cow */
1230f1ebcc74SLiu Bo 	smp_rmb();
1231f1ebcc74SLiu Bo 
1232f1ebcc74SLiu Bo 	/*
1233f1ebcc74SLiu Bo 	 * We do not need to cow a block if
1234f1ebcc74SLiu Bo 	 * 1) this block is not created or changed in this transaction;
1235f1ebcc74SLiu Bo 	 * 2) this block does not belong to TREE_RELOC tree;
1236f1ebcc74SLiu Bo 	 * 3) the root is not forced COW.
1237f1ebcc74SLiu Bo 	 *
1238f1ebcc74SLiu Bo 	 * What is forced COW:
1239f1ebcc74SLiu Bo 	 *    when we create snapshot during commiting the transaction,
1240f1ebcc74SLiu Bo 	 *    after we've finished coping src root, we must COW the shared
1241f1ebcc74SLiu Bo 	 *    block to ensure the metadata consistency.
1242f1ebcc74SLiu Bo 	 */
12435d4f98a2SYan Zheng 	if (btrfs_header_generation(buf) == trans->transid &&
12445d4f98a2SYan Zheng 	    !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN) &&
12455d4f98a2SYan Zheng 	    !(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
1246f1ebcc74SLiu Bo 	      btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)) &&
1247f1ebcc74SLiu Bo 	    !root->force_cow)
12485d4f98a2SYan Zheng 		return 0;
12495d4f98a2SYan Zheng 	return 1;
12505d4f98a2SYan Zheng }
12515d4f98a2SYan Zheng 
1252d352ac68SChris Mason /*
1253d352ac68SChris Mason  * cows a single block, see __btrfs_cow_block for the real work.
1254d352ac68SChris Mason  * This version of it has extra checks so that a block isn't cow'd more than
1255d352ac68SChris Mason  * once per transaction, as long as it hasn't been written yet
1256d352ac68SChris Mason  */
1257d397712bSChris Mason noinline int btrfs_cow_block(struct btrfs_trans_handle *trans,
12585f39d397SChris Mason 		    struct btrfs_root *root, struct extent_buffer *buf,
12595f39d397SChris Mason 		    struct extent_buffer *parent, int parent_slot,
12609fa8cfe7SChris Mason 		    struct extent_buffer **cow_ret)
126102217ed2SChris Mason {
12626702ed49SChris Mason 	u64 search_start;
1263f510cfecSChris Mason 	int ret;
1264dc17ff8fSChris Mason 
1265ccd467d6SChris Mason 	if (trans->transaction != root->fs_info->running_transaction) {
1266d397712bSChris Mason 		printk(KERN_CRIT "trans %llu running %llu\n",
1267d397712bSChris Mason 		       (unsigned long long)trans->transid,
1268d397712bSChris Mason 		       (unsigned long long)
1269ccd467d6SChris Mason 		       root->fs_info->running_transaction->transid);
1270ccd467d6SChris Mason 		WARN_ON(1);
1271ccd467d6SChris Mason 	}
1272ccd467d6SChris Mason 	if (trans->transid != root->fs_info->generation) {
1273d397712bSChris Mason 		printk(KERN_CRIT "trans %llu running %llu\n",
1274d397712bSChris Mason 		       (unsigned long long)trans->transid,
1275d397712bSChris Mason 		       (unsigned long long)root->fs_info->generation);
1276ccd467d6SChris Mason 		WARN_ON(1);
1277ccd467d6SChris Mason 	}
1278dc17ff8fSChris Mason 
12795d4f98a2SYan Zheng 	if (!should_cow_block(trans, root, buf)) {
128002217ed2SChris Mason 		*cow_ret = buf;
128102217ed2SChris Mason 		return 0;
128202217ed2SChris Mason 	}
1283c487685dSChris Mason 
12840b86a832SChris Mason 	search_start = buf->start & ~((u64)(1024 * 1024 * 1024) - 1);
1285b4ce94deSChris Mason 
1286b4ce94deSChris Mason 	if (parent)
1287b4ce94deSChris Mason 		btrfs_set_lock_blocking(parent);
1288b4ce94deSChris Mason 	btrfs_set_lock_blocking(buf);
1289b4ce94deSChris Mason 
1290f510cfecSChris Mason 	ret = __btrfs_cow_block(trans, root, buf, parent,
12919fa8cfe7SChris Mason 				 parent_slot, cow_ret, search_start, 0);
12921abe9b8aSliubo 
12931abe9b8aSliubo 	trace_btrfs_cow_block(root, buf, *cow_ret);
12941abe9b8aSliubo 
1295f510cfecSChris Mason 	return ret;
12962c90e5d6SChris Mason }
12976702ed49SChris Mason 
1298d352ac68SChris Mason /*
1299d352ac68SChris Mason  * helper function for defrag to decide if two blocks pointed to by a
1300d352ac68SChris Mason  * node are actually close by
1301d352ac68SChris Mason  */
13026b80053dSChris Mason static int close_blocks(u64 blocknr, u64 other, u32 blocksize)
13036702ed49SChris Mason {
13046b80053dSChris Mason 	if (blocknr < other && other - (blocknr + blocksize) < 32768)
13056702ed49SChris Mason 		return 1;
13066b80053dSChris Mason 	if (blocknr > other && blocknr - (other + blocksize) < 32768)
13076702ed49SChris Mason 		return 1;
130802217ed2SChris Mason 	return 0;
130902217ed2SChris Mason }
131002217ed2SChris Mason 
1311081e9573SChris Mason /*
1312081e9573SChris Mason  * compare two keys in a memcmp fashion
1313081e9573SChris Mason  */
1314081e9573SChris Mason static int comp_keys(struct btrfs_disk_key *disk, struct btrfs_key *k2)
1315081e9573SChris Mason {
1316081e9573SChris Mason 	struct btrfs_key k1;
1317081e9573SChris Mason 
1318081e9573SChris Mason 	btrfs_disk_key_to_cpu(&k1, disk);
1319081e9573SChris Mason 
132020736abaSDiego Calleja 	return btrfs_comp_cpu_keys(&k1, k2);
1321081e9573SChris Mason }
1322081e9573SChris Mason 
1323f3465ca4SJosef Bacik /*
1324f3465ca4SJosef Bacik  * same as comp_keys only with two btrfs_key's
1325f3465ca4SJosef Bacik  */
13265d4f98a2SYan Zheng int btrfs_comp_cpu_keys(struct btrfs_key *k1, struct btrfs_key *k2)
1327f3465ca4SJosef Bacik {
1328f3465ca4SJosef Bacik 	if (k1->objectid > k2->objectid)
1329f3465ca4SJosef Bacik 		return 1;
1330f3465ca4SJosef Bacik 	if (k1->objectid < k2->objectid)
1331f3465ca4SJosef Bacik 		return -1;
1332f3465ca4SJosef Bacik 	if (k1->type > k2->type)
1333f3465ca4SJosef Bacik 		return 1;
1334f3465ca4SJosef Bacik 	if (k1->type < k2->type)
1335f3465ca4SJosef Bacik 		return -1;
1336f3465ca4SJosef Bacik 	if (k1->offset > k2->offset)
1337f3465ca4SJosef Bacik 		return 1;
1338f3465ca4SJosef Bacik 	if (k1->offset < k2->offset)
1339f3465ca4SJosef Bacik 		return -1;
1340f3465ca4SJosef Bacik 	return 0;
1341f3465ca4SJosef Bacik }
1342081e9573SChris Mason 
1343d352ac68SChris Mason /*
1344d352ac68SChris Mason  * this is used by the defrag code to go through all the
1345d352ac68SChris Mason  * leaves pointed to by a node and reallocate them so that
1346d352ac68SChris Mason  * disk order is close to key order
1347d352ac68SChris Mason  */
13486702ed49SChris Mason int btrfs_realloc_node(struct btrfs_trans_handle *trans,
13495f39d397SChris Mason 		       struct btrfs_root *root, struct extent_buffer *parent,
1350a6b6e75eSChris Mason 		       int start_slot, int cache_only, u64 *last_ret,
1351a6b6e75eSChris Mason 		       struct btrfs_key *progress)
13526702ed49SChris Mason {
13536b80053dSChris Mason 	struct extent_buffer *cur;
13546702ed49SChris Mason 	u64 blocknr;
1355ca7a79adSChris Mason 	u64 gen;
1356e9d0b13bSChris Mason 	u64 search_start = *last_ret;
1357e9d0b13bSChris Mason 	u64 last_block = 0;
13586702ed49SChris Mason 	u64 other;
13596702ed49SChris Mason 	u32 parent_nritems;
13606702ed49SChris Mason 	int end_slot;
13616702ed49SChris Mason 	int i;
13626702ed49SChris Mason 	int err = 0;
1363f2183bdeSChris Mason 	int parent_level;
13646b80053dSChris Mason 	int uptodate;
13656b80053dSChris Mason 	u32 blocksize;
1366081e9573SChris Mason 	int progress_passed = 0;
1367081e9573SChris Mason 	struct btrfs_disk_key disk_key;
13686702ed49SChris Mason 
13695708b959SChris Mason 	parent_level = btrfs_header_level(parent);
13705708b959SChris Mason 	if (cache_only && parent_level != 1)
13715708b959SChris Mason 		return 0;
13725708b959SChris Mason 
1373d397712bSChris Mason 	if (trans->transaction != root->fs_info->running_transaction)
13746702ed49SChris Mason 		WARN_ON(1);
1375d397712bSChris Mason 	if (trans->transid != root->fs_info->generation)
13766702ed49SChris Mason 		WARN_ON(1);
137786479a04SChris Mason 
13786b80053dSChris Mason 	parent_nritems = btrfs_header_nritems(parent);
13796b80053dSChris Mason 	blocksize = btrfs_level_size(root, parent_level - 1);
13806702ed49SChris Mason 	end_slot = parent_nritems;
13816702ed49SChris Mason 
13826702ed49SChris Mason 	if (parent_nritems == 1)
13836702ed49SChris Mason 		return 0;
13846702ed49SChris Mason 
1385b4ce94deSChris Mason 	btrfs_set_lock_blocking(parent);
1386b4ce94deSChris Mason 
13876702ed49SChris Mason 	for (i = start_slot; i < end_slot; i++) {
13886702ed49SChris Mason 		int close = 1;
1389a6b6e75eSChris Mason 
1390081e9573SChris Mason 		btrfs_node_key(parent, &disk_key, i);
1391081e9573SChris Mason 		if (!progress_passed && comp_keys(&disk_key, progress) < 0)
1392081e9573SChris Mason 			continue;
1393081e9573SChris Mason 
1394081e9573SChris Mason 		progress_passed = 1;
13956b80053dSChris Mason 		blocknr = btrfs_node_blockptr(parent, i);
1396ca7a79adSChris Mason 		gen = btrfs_node_ptr_generation(parent, i);
1397e9d0b13bSChris Mason 		if (last_block == 0)
1398e9d0b13bSChris Mason 			last_block = blocknr;
13995708b959SChris Mason 
14006702ed49SChris Mason 		if (i > 0) {
14016b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i - 1);
14026b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
14036702ed49SChris Mason 		}
14040ef3e66bSChris Mason 		if (!close && i < end_slot - 2) {
14056b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i + 1);
14066b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
14076702ed49SChris Mason 		}
1408e9d0b13bSChris Mason 		if (close) {
1409e9d0b13bSChris Mason 			last_block = blocknr;
14106702ed49SChris Mason 			continue;
1411e9d0b13bSChris Mason 		}
14126702ed49SChris Mason 
14136b80053dSChris Mason 		cur = btrfs_find_tree_block(root, blocknr, blocksize);
14146b80053dSChris Mason 		if (cur)
1415b9fab919SChris Mason 			uptodate = btrfs_buffer_uptodate(cur, gen, 0);
14166b80053dSChris Mason 		else
14176b80053dSChris Mason 			uptodate = 0;
14185708b959SChris Mason 		if (!cur || !uptodate) {
14196702ed49SChris Mason 			if (cache_only) {
14206b80053dSChris Mason 				free_extent_buffer(cur);
14216702ed49SChris Mason 				continue;
14226702ed49SChris Mason 			}
14236b80053dSChris Mason 			if (!cur) {
14246b80053dSChris Mason 				cur = read_tree_block(root, blocknr,
1425ca7a79adSChris Mason 							 blocksize, gen);
142697d9a8a4STsutomu Itoh 				if (!cur)
142797d9a8a4STsutomu Itoh 					return -EIO;
14286b80053dSChris Mason 			} else if (!uptodate) {
1429018642a1STsutomu Itoh 				err = btrfs_read_buffer(cur, gen);
1430018642a1STsutomu Itoh 				if (err) {
1431018642a1STsutomu Itoh 					free_extent_buffer(cur);
1432018642a1STsutomu Itoh 					return err;
1433018642a1STsutomu Itoh 				}
14346702ed49SChris Mason 			}
1435f2183bdeSChris Mason 		}
1436e9d0b13bSChris Mason 		if (search_start == 0)
14376b80053dSChris Mason 			search_start = last_block;
1438e9d0b13bSChris Mason 
1439e7a84565SChris Mason 		btrfs_tree_lock(cur);
1440b4ce94deSChris Mason 		btrfs_set_lock_blocking(cur);
14416b80053dSChris Mason 		err = __btrfs_cow_block(trans, root, cur, parent, i,
1442e7a84565SChris Mason 					&cur, search_start,
14436b80053dSChris Mason 					min(16 * blocksize,
14449fa8cfe7SChris Mason 					    (end_slot - i) * blocksize));
1445252c38f0SYan 		if (err) {
1446e7a84565SChris Mason 			btrfs_tree_unlock(cur);
14476b80053dSChris Mason 			free_extent_buffer(cur);
14486702ed49SChris Mason 			break;
1449252c38f0SYan 		}
1450e7a84565SChris Mason 		search_start = cur->start;
1451e7a84565SChris Mason 		last_block = cur->start;
1452f2183bdeSChris Mason 		*last_ret = search_start;
1453e7a84565SChris Mason 		btrfs_tree_unlock(cur);
1454e7a84565SChris Mason 		free_extent_buffer(cur);
14556702ed49SChris Mason 	}
14566702ed49SChris Mason 	return err;
14576702ed49SChris Mason }
14586702ed49SChris Mason 
145974123bd7SChris Mason /*
146074123bd7SChris Mason  * The leaf data grows from end-to-front in the node.
146174123bd7SChris Mason  * this returns the address of the start of the last item,
146274123bd7SChris Mason  * which is the stop of the leaf data stack
146374123bd7SChris Mason  */
1464123abc88SChris Mason static inline unsigned int leaf_data_end(struct btrfs_root *root,
14655f39d397SChris Mason 					 struct extent_buffer *leaf)
1466be0e5c09SChris Mason {
14675f39d397SChris Mason 	u32 nr = btrfs_header_nritems(leaf);
1468be0e5c09SChris Mason 	if (nr == 0)
1469123abc88SChris Mason 		return BTRFS_LEAF_DATA_SIZE(root);
14705f39d397SChris Mason 	return btrfs_item_offset_nr(leaf, nr - 1);
1471be0e5c09SChris Mason }
1472be0e5c09SChris Mason 
1473aa5d6bedSChris Mason 
147474123bd7SChris Mason /*
14755f39d397SChris Mason  * search for key in the extent_buffer.  The items start at offset p,
14765f39d397SChris Mason  * and they are item_size apart.  There are 'max' items in p.
14775f39d397SChris Mason  *
147874123bd7SChris Mason  * the slot in the array is returned via slot, and it points to
147974123bd7SChris Mason  * the place where you would insert key if it is not found in
148074123bd7SChris Mason  * the array.
148174123bd7SChris Mason  *
148274123bd7SChris Mason  * slot may point to max if the key is bigger than all of the keys
148374123bd7SChris Mason  */
1484e02119d5SChris Mason static noinline int generic_bin_search(struct extent_buffer *eb,
1485e02119d5SChris Mason 				       unsigned long p,
14865f39d397SChris Mason 				       int item_size, struct btrfs_key *key,
1487be0e5c09SChris Mason 				       int max, int *slot)
1488be0e5c09SChris Mason {
1489be0e5c09SChris Mason 	int low = 0;
1490be0e5c09SChris Mason 	int high = max;
1491be0e5c09SChris Mason 	int mid;
1492be0e5c09SChris Mason 	int ret;
1493479965d6SChris Mason 	struct btrfs_disk_key *tmp = NULL;
14945f39d397SChris Mason 	struct btrfs_disk_key unaligned;
14955f39d397SChris Mason 	unsigned long offset;
14965f39d397SChris Mason 	char *kaddr = NULL;
14975f39d397SChris Mason 	unsigned long map_start = 0;
14985f39d397SChris Mason 	unsigned long map_len = 0;
1499479965d6SChris Mason 	int err;
1500be0e5c09SChris Mason 
1501be0e5c09SChris Mason 	while (low < high) {
1502be0e5c09SChris Mason 		mid = (low + high) / 2;
15035f39d397SChris Mason 		offset = p + mid * item_size;
15045f39d397SChris Mason 
1505a6591715SChris Mason 		if (!kaddr || offset < map_start ||
15065f39d397SChris Mason 		    (offset + sizeof(struct btrfs_disk_key)) >
15075f39d397SChris Mason 		    map_start + map_len) {
1508934d375bSChris Mason 
1509934d375bSChris Mason 			err = map_private_extent_buffer(eb, offset,
1510479965d6SChris Mason 						sizeof(struct btrfs_disk_key),
1511a6591715SChris Mason 						&kaddr, &map_start, &map_len);
15125f39d397SChris Mason 
1513479965d6SChris Mason 			if (!err) {
1514479965d6SChris Mason 				tmp = (struct btrfs_disk_key *)(kaddr + offset -
1515479965d6SChris Mason 							map_start);
1516479965d6SChris Mason 			} else {
15175f39d397SChris Mason 				read_extent_buffer(eb, &unaligned,
15185f39d397SChris Mason 						   offset, sizeof(unaligned));
15195f39d397SChris Mason 				tmp = &unaligned;
1520479965d6SChris Mason 			}
1521479965d6SChris Mason 
15225f39d397SChris Mason 		} else {
15235f39d397SChris Mason 			tmp = (struct btrfs_disk_key *)(kaddr + offset -
15245f39d397SChris Mason 							map_start);
15255f39d397SChris Mason 		}
1526be0e5c09SChris Mason 		ret = comp_keys(tmp, key);
1527be0e5c09SChris Mason 
1528be0e5c09SChris Mason 		if (ret < 0)
1529be0e5c09SChris Mason 			low = mid + 1;
1530be0e5c09SChris Mason 		else if (ret > 0)
1531be0e5c09SChris Mason 			high = mid;
1532be0e5c09SChris Mason 		else {
1533be0e5c09SChris Mason 			*slot = mid;
1534be0e5c09SChris Mason 			return 0;
1535be0e5c09SChris Mason 		}
1536be0e5c09SChris Mason 	}
1537be0e5c09SChris Mason 	*slot = low;
1538be0e5c09SChris Mason 	return 1;
1539be0e5c09SChris Mason }
1540be0e5c09SChris Mason 
154197571fd0SChris Mason /*
154297571fd0SChris Mason  * simple bin_search frontend that does the right thing for
154397571fd0SChris Mason  * leaves vs nodes
154497571fd0SChris Mason  */
15455f39d397SChris Mason static int bin_search(struct extent_buffer *eb, struct btrfs_key *key,
15465f39d397SChris Mason 		      int level, int *slot)
1547be0e5c09SChris Mason {
1548f775738fSWang Sheng-Hui 	if (level == 0)
15495f39d397SChris Mason 		return generic_bin_search(eb,
15505f39d397SChris Mason 					  offsetof(struct btrfs_leaf, items),
15510783fcfcSChris Mason 					  sizeof(struct btrfs_item),
15525f39d397SChris Mason 					  key, btrfs_header_nritems(eb),
15537518a238SChris Mason 					  slot);
1554f775738fSWang Sheng-Hui 	else
15555f39d397SChris Mason 		return generic_bin_search(eb,
15565f39d397SChris Mason 					  offsetof(struct btrfs_node, ptrs),
1557123abc88SChris Mason 					  sizeof(struct btrfs_key_ptr),
15585f39d397SChris Mason 					  key, btrfs_header_nritems(eb),
15597518a238SChris Mason 					  slot);
1560be0e5c09SChris Mason }
1561be0e5c09SChris Mason 
15625d4f98a2SYan Zheng int btrfs_bin_search(struct extent_buffer *eb, struct btrfs_key *key,
15635d4f98a2SYan Zheng 		     int level, int *slot)
15645d4f98a2SYan Zheng {
15655d4f98a2SYan Zheng 	return bin_search(eb, key, level, slot);
15665d4f98a2SYan Zheng }
15675d4f98a2SYan Zheng 
1568f0486c68SYan, Zheng static void root_add_used(struct btrfs_root *root, u32 size)
1569f0486c68SYan, Zheng {
1570f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
1571f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
1572f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) + size);
1573f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
1574f0486c68SYan, Zheng }
1575f0486c68SYan, Zheng 
1576f0486c68SYan, Zheng static void root_sub_used(struct btrfs_root *root, u32 size)
1577f0486c68SYan, Zheng {
1578f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
1579f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
1580f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) - size);
1581f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
1582f0486c68SYan, Zheng }
1583f0486c68SYan, Zheng 
1584d352ac68SChris Mason /* given a node and slot number, this reads the blocks it points to.  The
1585d352ac68SChris Mason  * extent buffer is returned with a reference taken (but unlocked).
1586d352ac68SChris Mason  * NULL is returned on error.
1587d352ac68SChris Mason  */
1588e02119d5SChris Mason static noinline struct extent_buffer *read_node_slot(struct btrfs_root *root,
15895f39d397SChris Mason 				   struct extent_buffer *parent, int slot)
1590bb803951SChris Mason {
1591ca7a79adSChris Mason 	int level = btrfs_header_level(parent);
1592bb803951SChris Mason 	if (slot < 0)
1593bb803951SChris Mason 		return NULL;
15945f39d397SChris Mason 	if (slot >= btrfs_header_nritems(parent))
1595bb803951SChris Mason 		return NULL;
1596ca7a79adSChris Mason 
1597ca7a79adSChris Mason 	BUG_ON(level == 0);
1598ca7a79adSChris Mason 
1599db94535dSChris Mason 	return read_tree_block(root, btrfs_node_blockptr(parent, slot),
1600ca7a79adSChris Mason 		       btrfs_level_size(root, level - 1),
1601ca7a79adSChris Mason 		       btrfs_node_ptr_generation(parent, slot));
1602bb803951SChris Mason }
1603bb803951SChris Mason 
1604d352ac68SChris Mason /*
1605d352ac68SChris Mason  * node level balancing, used to make sure nodes are in proper order for
1606d352ac68SChris Mason  * item deletion.  We balance from the top down, so we have to make sure
1607d352ac68SChris Mason  * that a deletion won't leave an node completely empty later on.
1608d352ac68SChris Mason  */
1609e02119d5SChris Mason static noinline int balance_level(struct btrfs_trans_handle *trans,
161098ed5174SChris Mason 			 struct btrfs_root *root,
161198ed5174SChris Mason 			 struct btrfs_path *path, int level)
1612bb803951SChris Mason {
16135f39d397SChris Mason 	struct extent_buffer *right = NULL;
16145f39d397SChris Mason 	struct extent_buffer *mid;
16155f39d397SChris Mason 	struct extent_buffer *left = NULL;
16165f39d397SChris Mason 	struct extent_buffer *parent = NULL;
1617bb803951SChris Mason 	int ret = 0;
1618bb803951SChris Mason 	int wret;
1619bb803951SChris Mason 	int pslot;
1620bb803951SChris Mason 	int orig_slot = path->slots[level];
162179f95c82SChris Mason 	u64 orig_ptr;
1622bb803951SChris Mason 
1623bb803951SChris Mason 	if (level == 0)
1624bb803951SChris Mason 		return 0;
1625bb803951SChris Mason 
16265f39d397SChris Mason 	mid = path->nodes[level];
1627b4ce94deSChris Mason 
1628bd681513SChris Mason 	WARN_ON(path->locks[level] != BTRFS_WRITE_LOCK &&
1629bd681513SChris Mason 		path->locks[level] != BTRFS_WRITE_LOCK_BLOCKING);
16307bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
16317bb86316SChris Mason 
16321d4f8a0cSChris Mason 	orig_ptr = btrfs_node_blockptr(mid, orig_slot);
163379f95c82SChris Mason 
1634a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
16355f39d397SChris Mason 		parent = path->nodes[level + 1];
1636bb803951SChris Mason 		pslot = path->slots[level + 1];
1637a05a9bb1SLi Zefan 	}
1638bb803951SChris Mason 
163940689478SChris Mason 	/*
164040689478SChris Mason 	 * deal with the case where there is only one pointer in the root
164140689478SChris Mason 	 * by promoting the node below to a root
164240689478SChris Mason 	 */
16435f39d397SChris Mason 	if (!parent) {
16445f39d397SChris Mason 		struct extent_buffer *child;
1645bb803951SChris Mason 
16465f39d397SChris Mason 		if (btrfs_header_nritems(mid) != 1)
1647bb803951SChris Mason 			return 0;
1648bb803951SChris Mason 
1649bb803951SChris Mason 		/* promote the child to a root */
16505f39d397SChris Mason 		child = read_node_slot(root, mid, 0);
1651305a26afSMark Fasheh 		if (!child) {
1652305a26afSMark Fasheh 			ret = -EROFS;
1653305a26afSMark Fasheh 			btrfs_std_error(root->fs_info, ret);
1654305a26afSMark Fasheh 			goto enospc;
1655305a26afSMark Fasheh 		}
1656305a26afSMark Fasheh 
1657925baeddSChris Mason 		btrfs_tree_lock(child);
1658b4ce94deSChris Mason 		btrfs_set_lock_blocking(child);
16599fa8cfe7SChris Mason 		ret = btrfs_cow_block(trans, root, child, mid, 0, &child);
1660f0486c68SYan, Zheng 		if (ret) {
1661f0486c68SYan, Zheng 			btrfs_tree_unlock(child);
1662f0486c68SYan, Zheng 			free_extent_buffer(child);
1663f0486c68SYan, Zheng 			goto enospc;
1664f0486c68SYan, Zheng 		}
16652f375ab9SYan 
1666f230475eSJan Schmidt 		tree_mod_log_set_root_pointer(root, child);
1667240f62c8SChris Mason 		rcu_assign_pointer(root->node, child);
1668925baeddSChris Mason 
16690b86a832SChris Mason 		add_root_to_dirty_list(root);
1670925baeddSChris Mason 		btrfs_tree_unlock(child);
1671b4ce94deSChris Mason 
1672925baeddSChris Mason 		path->locks[level] = 0;
1673bb803951SChris Mason 		path->nodes[level] = NULL;
16745f39d397SChris Mason 		clean_tree_block(trans, root, mid);
1675925baeddSChris Mason 		btrfs_tree_unlock(mid);
1676bb803951SChris Mason 		/* once for the path */
16775f39d397SChris Mason 		free_extent_buffer(mid);
1678f0486c68SYan, Zheng 
1679f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
16805581a51aSJan Schmidt 		btrfs_free_tree_block(trans, root, mid, 0, 1);
1681bb803951SChris Mason 		/* once for the root ptr */
16823083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
1683f0486c68SYan, Zheng 		return 0;
1684bb803951SChris Mason 	}
16855f39d397SChris Mason 	if (btrfs_header_nritems(mid) >
1686123abc88SChris Mason 	    BTRFS_NODEPTRS_PER_BLOCK(root) / 4)
1687bb803951SChris Mason 		return 0;
1688bb803951SChris Mason 
16895f39d397SChris Mason 	left = read_node_slot(root, parent, pslot - 1);
16905f39d397SChris Mason 	if (left) {
1691925baeddSChris Mason 		btrfs_tree_lock(left);
1692b4ce94deSChris Mason 		btrfs_set_lock_blocking(left);
16935f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, left,
16949fa8cfe7SChris Mason 				       parent, pslot - 1, &left);
169554aa1f4dSChris Mason 		if (wret) {
169654aa1f4dSChris Mason 			ret = wret;
169754aa1f4dSChris Mason 			goto enospc;
169854aa1f4dSChris Mason 		}
16992cc58cf2SChris Mason 	}
17005f39d397SChris Mason 	right = read_node_slot(root, parent, pslot + 1);
17015f39d397SChris Mason 	if (right) {
1702925baeddSChris Mason 		btrfs_tree_lock(right);
1703b4ce94deSChris Mason 		btrfs_set_lock_blocking(right);
17045f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, right,
17059fa8cfe7SChris Mason 				       parent, pslot + 1, &right);
17062cc58cf2SChris Mason 		if (wret) {
17072cc58cf2SChris Mason 			ret = wret;
17082cc58cf2SChris Mason 			goto enospc;
17092cc58cf2SChris Mason 		}
17102cc58cf2SChris Mason 	}
17112cc58cf2SChris Mason 
17122cc58cf2SChris Mason 	/* first, try to make some room in the middle buffer */
17135f39d397SChris Mason 	if (left) {
17145f39d397SChris Mason 		orig_slot += btrfs_header_nritems(left);
1715bce4eae9SChris Mason 		wret = push_node_left(trans, root, left, mid, 1);
171679f95c82SChris Mason 		if (wret < 0)
171779f95c82SChris Mason 			ret = wret;
1718bb803951SChris Mason 	}
171979f95c82SChris Mason 
172079f95c82SChris Mason 	/*
172179f95c82SChris Mason 	 * then try to empty the right most buffer into the middle
172279f95c82SChris Mason 	 */
17235f39d397SChris Mason 	if (right) {
1724971a1f66SChris Mason 		wret = push_node_left(trans, root, mid, right, 1);
172554aa1f4dSChris Mason 		if (wret < 0 && wret != -ENOSPC)
172679f95c82SChris Mason 			ret = wret;
17275f39d397SChris Mason 		if (btrfs_header_nritems(right) == 0) {
17285f39d397SChris Mason 			clean_tree_block(trans, root, right);
1729925baeddSChris Mason 			btrfs_tree_unlock(right);
1730f3ea38daSJan Schmidt 			del_ptr(trans, root, path, level + 1, pslot + 1, 1);
1731f0486c68SYan, Zheng 			root_sub_used(root, right->len);
17325581a51aSJan Schmidt 			btrfs_free_tree_block(trans, root, right, 0, 1);
17333083ee2eSJosef Bacik 			free_extent_buffer_stale(right);
1734f0486c68SYan, Zheng 			right = NULL;
1735bb803951SChris Mason 		} else {
17365f39d397SChris Mason 			struct btrfs_disk_key right_key;
17375f39d397SChris Mason 			btrfs_node_key(right, &right_key, 0);
1738f230475eSJan Schmidt 			tree_mod_log_set_node_key(root->fs_info, parent,
1739f230475eSJan Schmidt 						  &right_key, pslot + 1, 0);
17405f39d397SChris Mason 			btrfs_set_node_key(parent, &right_key, pslot + 1);
17415f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
1742bb803951SChris Mason 		}
1743bb803951SChris Mason 	}
17445f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 1) {
174579f95c82SChris Mason 		/*
174679f95c82SChris Mason 		 * we're not allowed to leave a node with one item in the
174779f95c82SChris Mason 		 * tree during a delete.  A deletion from lower in the tree
174879f95c82SChris Mason 		 * could try to delete the only pointer in this node.
174979f95c82SChris Mason 		 * So, pull some keys from the left.
175079f95c82SChris Mason 		 * There has to be a left pointer at this point because
175179f95c82SChris Mason 		 * otherwise we would have pulled some pointers from the
175279f95c82SChris Mason 		 * right
175379f95c82SChris Mason 		 */
1754305a26afSMark Fasheh 		if (!left) {
1755305a26afSMark Fasheh 			ret = -EROFS;
1756305a26afSMark Fasheh 			btrfs_std_error(root->fs_info, ret);
1757305a26afSMark Fasheh 			goto enospc;
1758305a26afSMark Fasheh 		}
17595f39d397SChris Mason 		wret = balance_node_right(trans, root, mid, left);
176054aa1f4dSChris Mason 		if (wret < 0) {
176179f95c82SChris Mason 			ret = wret;
176254aa1f4dSChris Mason 			goto enospc;
176354aa1f4dSChris Mason 		}
1764bce4eae9SChris Mason 		if (wret == 1) {
1765bce4eae9SChris Mason 			wret = push_node_left(trans, root, left, mid, 1);
1766bce4eae9SChris Mason 			if (wret < 0)
1767bce4eae9SChris Mason 				ret = wret;
1768bce4eae9SChris Mason 		}
176979f95c82SChris Mason 		BUG_ON(wret == 1);
177079f95c82SChris Mason 	}
17715f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 0) {
17725f39d397SChris Mason 		clean_tree_block(trans, root, mid);
1773925baeddSChris Mason 		btrfs_tree_unlock(mid);
1774f3ea38daSJan Schmidt 		del_ptr(trans, root, path, level + 1, pslot, 1);
1775f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
17765581a51aSJan Schmidt 		btrfs_free_tree_block(trans, root, mid, 0, 1);
17773083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
1778f0486c68SYan, Zheng 		mid = NULL;
177979f95c82SChris Mason 	} else {
178079f95c82SChris Mason 		/* update the parent key to reflect our changes */
17815f39d397SChris Mason 		struct btrfs_disk_key mid_key;
17825f39d397SChris Mason 		btrfs_node_key(mid, &mid_key, 0);
1783f230475eSJan Schmidt 		tree_mod_log_set_node_key(root->fs_info, parent, &mid_key,
1784f230475eSJan Schmidt 					  pslot, 0);
17855f39d397SChris Mason 		btrfs_set_node_key(parent, &mid_key, pslot);
17865f39d397SChris Mason 		btrfs_mark_buffer_dirty(parent);
178779f95c82SChris Mason 	}
1788bb803951SChris Mason 
178979f95c82SChris Mason 	/* update the path */
17905f39d397SChris Mason 	if (left) {
17915f39d397SChris Mason 		if (btrfs_header_nritems(left) > orig_slot) {
17925f39d397SChris Mason 			extent_buffer_get(left);
1793925baeddSChris Mason 			/* left was locked after cow */
17945f39d397SChris Mason 			path->nodes[level] = left;
1795bb803951SChris Mason 			path->slots[level + 1] -= 1;
1796bb803951SChris Mason 			path->slots[level] = orig_slot;
1797925baeddSChris Mason 			if (mid) {
1798925baeddSChris Mason 				btrfs_tree_unlock(mid);
17995f39d397SChris Mason 				free_extent_buffer(mid);
1800925baeddSChris Mason 			}
1801bb803951SChris Mason 		} else {
18025f39d397SChris Mason 			orig_slot -= btrfs_header_nritems(left);
1803bb803951SChris Mason 			path->slots[level] = orig_slot;
1804bb803951SChris Mason 		}
1805bb803951SChris Mason 	}
180679f95c82SChris Mason 	/* double check we haven't messed things up */
1807e20d96d6SChris Mason 	if (orig_ptr !=
18085f39d397SChris Mason 	    btrfs_node_blockptr(path->nodes[level], path->slots[level]))
180979f95c82SChris Mason 		BUG();
181054aa1f4dSChris Mason enospc:
1811925baeddSChris Mason 	if (right) {
1812925baeddSChris Mason 		btrfs_tree_unlock(right);
18135f39d397SChris Mason 		free_extent_buffer(right);
1814925baeddSChris Mason 	}
1815925baeddSChris Mason 	if (left) {
1816925baeddSChris Mason 		if (path->nodes[level] != left)
1817925baeddSChris Mason 			btrfs_tree_unlock(left);
18185f39d397SChris Mason 		free_extent_buffer(left);
1819925baeddSChris Mason 	}
1820bb803951SChris Mason 	return ret;
1821bb803951SChris Mason }
1822bb803951SChris Mason 
1823d352ac68SChris Mason /* Node balancing for insertion.  Here we only split or push nodes around
1824d352ac68SChris Mason  * when they are completely full.  This is also done top down, so we
1825d352ac68SChris Mason  * have to be pessimistic.
1826d352ac68SChris Mason  */
1827d397712bSChris Mason static noinline int push_nodes_for_insert(struct btrfs_trans_handle *trans,
1828e66f709bSChris Mason 					  struct btrfs_root *root,
1829e66f709bSChris Mason 					  struct btrfs_path *path, int level)
1830e66f709bSChris Mason {
18315f39d397SChris Mason 	struct extent_buffer *right = NULL;
18325f39d397SChris Mason 	struct extent_buffer *mid;
18335f39d397SChris Mason 	struct extent_buffer *left = NULL;
18345f39d397SChris Mason 	struct extent_buffer *parent = NULL;
1835e66f709bSChris Mason 	int ret = 0;
1836e66f709bSChris Mason 	int wret;
1837e66f709bSChris Mason 	int pslot;
1838e66f709bSChris Mason 	int orig_slot = path->slots[level];
1839e66f709bSChris Mason 
1840e66f709bSChris Mason 	if (level == 0)
1841e66f709bSChris Mason 		return 1;
1842e66f709bSChris Mason 
18435f39d397SChris Mason 	mid = path->nodes[level];
18447bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
1845e66f709bSChris Mason 
1846a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
18475f39d397SChris Mason 		parent = path->nodes[level + 1];
1848e66f709bSChris Mason 		pslot = path->slots[level + 1];
1849a05a9bb1SLi Zefan 	}
1850e66f709bSChris Mason 
18515f39d397SChris Mason 	if (!parent)
1852e66f709bSChris Mason 		return 1;
1853e66f709bSChris Mason 
18545f39d397SChris Mason 	left = read_node_slot(root, parent, pslot - 1);
1855e66f709bSChris Mason 
1856e66f709bSChris Mason 	/* first, try to make some room in the middle buffer */
18575f39d397SChris Mason 	if (left) {
1858e66f709bSChris Mason 		u32 left_nr;
1859925baeddSChris Mason 
1860925baeddSChris Mason 		btrfs_tree_lock(left);
1861b4ce94deSChris Mason 		btrfs_set_lock_blocking(left);
1862b4ce94deSChris Mason 
18635f39d397SChris Mason 		left_nr = btrfs_header_nritems(left);
186433ade1f8SChris Mason 		if (left_nr >= BTRFS_NODEPTRS_PER_BLOCK(root) - 1) {
186533ade1f8SChris Mason 			wret = 1;
186633ade1f8SChris Mason 		} else {
18675f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, left, parent,
18689fa8cfe7SChris Mason 					      pslot - 1, &left);
186954aa1f4dSChris Mason 			if (ret)
187054aa1f4dSChris Mason 				wret = 1;
187154aa1f4dSChris Mason 			else {
187254aa1f4dSChris Mason 				wret = push_node_left(trans, root,
1873971a1f66SChris Mason 						      left, mid, 0);
187454aa1f4dSChris Mason 			}
187533ade1f8SChris Mason 		}
1876e66f709bSChris Mason 		if (wret < 0)
1877e66f709bSChris Mason 			ret = wret;
1878e66f709bSChris Mason 		if (wret == 0) {
18795f39d397SChris Mason 			struct btrfs_disk_key disk_key;
1880e66f709bSChris Mason 			orig_slot += left_nr;
18815f39d397SChris Mason 			btrfs_node_key(mid, &disk_key, 0);
1882f230475eSJan Schmidt 			tree_mod_log_set_node_key(root->fs_info, parent,
1883f230475eSJan Schmidt 						  &disk_key, pslot, 0);
18845f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot);
18855f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
18865f39d397SChris Mason 			if (btrfs_header_nritems(left) > orig_slot) {
18875f39d397SChris Mason 				path->nodes[level] = left;
1888e66f709bSChris Mason 				path->slots[level + 1] -= 1;
1889e66f709bSChris Mason 				path->slots[level] = orig_slot;
1890925baeddSChris Mason 				btrfs_tree_unlock(mid);
18915f39d397SChris Mason 				free_extent_buffer(mid);
1892e66f709bSChris Mason 			} else {
1893e66f709bSChris Mason 				orig_slot -=
18945f39d397SChris Mason 					btrfs_header_nritems(left);
1895e66f709bSChris Mason 				path->slots[level] = orig_slot;
1896925baeddSChris Mason 				btrfs_tree_unlock(left);
18975f39d397SChris Mason 				free_extent_buffer(left);
1898e66f709bSChris Mason 			}
1899e66f709bSChris Mason 			return 0;
1900e66f709bSChris Mason 		}
1901925baeddSChris Mason 		btrfs_tree_unlock(left);
19025f39d397SChris Mason 		free_extent_buffer(left);
1903e66f709bSChris Mason 	}
19045f39d397SChris Mason 	right = read_node_slot(root, parent, pslot + 1);
1905e66f709bSChris Mason 
1906e66f709bSChris Mason 	/*
1907e66f709bSChris Mason 	 * then try to empty the right most buffer into the middle
1908e66f709bSChris Mason 	 */
19095f39d397SChris Mason 	if (right) {
191033ade1f8SChris Mason 		u32 right_nr;
1911b4ce94deSChris Mason 
1912925baeddSChris Mason 		btrfs_tree_lock(right);
1913b4ce94deSChris Mason 		btrfs_set_lock_blocking(right);
1914b4ce94deSChris Mason 
19155f39d397SChris Mason 		right_nr = btrfs_header_nritems(right);
191633ade1f8SChris Mason 		if (right_nr >= BTRFS_NODEPTRS_PER_BLOCK(root) - 1) {
191733ade1f8SChris Mason 			wret = 1;
191833ade1f8SChris Mason 		} else {
19195f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, right,
19205f39d397SChris Mason 					      parent, pslot + 1,
19219fa8cfe7SChris Mason 					      &right);
192254aa1f4dSChris Mason 			if (ret)
192354aa1f4dSChris Mason 				wret = 1;
192454aa1f4dSChris Mason 			else {
192533ade1f8SChris Mason 				wret = balance_node_right(trans, root,
19265f39d397SChris Mason 							  right, mid);
192733ade1f8SChris Mason 			}
192854aa1f4dSChris Mason 		}
1929e66f709bSChris Mason 		if (wret < 0)
1930e66f709bSChris Mason 			ret = wret;
1931e66f709bSChris Mason 		if (wret == 0) {
19325f39d397SChris Mason 			struct btrfs_disk_key disk_key;
19335f39d397SChris Mason 
19345f39d397SChris Mason 			btrfs_node_key(right, &disk_key, 0);
1935f230475eSJan Schmidt 			tree_mod_log_set_node_key(root->fs_info, parent,
1936f230475eSJan Schmidt 						  &disk_key, pslot + 1, 0);
19375f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot + 1);
19385f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
19395f39d397SChris Mason 
19405f39d397SChris Mason 			if (btrfs_header_nritems(mid) <= orig_slot) {
19415f39d397SChris Mason 				path->nodes[level] = right;
1942e66f709bSChris Mason 				path->slots[level + 1] += 1;
1943e66f709bSChris Mason 				path->slots[level] = orig_slot -
19445f39d397SChris Mason 					btrfs_header_nritems(mid);
1945925baeddSChris Mason 				btrfs_tree_unlock(mid);
19465f39d397SChris Mason 				free_extent_buffer(mid);
1947e66f709bSChris Mason 			} else {
1948925baeddSChris Mason 				btrfs_tree_unlock(right);
19495f39d397SChris Mason 				free_extent_buffer(right);
1950e66f709bSChris Mason 			}
1951e66f709bSChris Mason 			return 0;
1952e66f709bSChris Mason 		}
1953925baeddSChris Mason 		btrfs_tree_unlock(right);
19545f39d397SChris Mason 		free_extent_buffer(right);
1955e66f709bSChris Mason 	}
1956e66f709bSChris Mason 	return 1;
1957e66f709bSChris Mason }
1958e66f709bSChris Mason 
195974123bd7SChris Mason /*
1960d352ac68SChris Mason  * readahead one full node of leaves, finding things that are close
1961d352ac68SChris Mason  * to the block in 'slot', and triggering ra on them.
19623c69faecSChris Mason  */
1963c8c42864SChris Mason static void reada_for_search(struct btrfs_root *root,
1964e02119d5SChris Mason 			     struct btrfs_path *path,
196501f46658SChris Mason 			     int level, int slot, u64 objectid)
19663c69faecSChris Mason {
19675f39d397SChris Mason 	struct extent_buffer *node;
196801f46658SChris Mason 	struct btrfs_disk_key disk_key;
19693c69faecSChris Mason 	u32 nritems;
19703c69faecSChris Mason 	u64 search;
1971a7175319SChris Mason 	u64 target;
19726b80053dSChris Mason 	u64 nread = 0;
1973cb25c2eaSJosef Bacik 	u64 gen;
19743c69faecSChris Mason 	int direction = path->reada;
19755f39d397SChris Mason 	struct extent_buffer *eb;
19766b80053dSChris Mason 	u32 nr;
19776b80053dSChris Mason 	u32 blocksize;
19786b80053dSChris Mason 	u32 nscan = 0;
1979db94535dSChris Mason 
1980a6b6e75eSChris Mason 	if (level != 1)
19813c69faecSChris Mason 		return;
19823c69faecSChris Mason 
19836702ed49SChris Mason 	if (!path->nodes[level])
19846702ed49SChris Mason 		return;
19856702ed49SChris Mason 
19865f39d397SChris Mason 	node = path->nodes[level];
1987925baeddSChris Mason 
19883c69faecSChris Mason 	search = btrfs_node_blockptr(node, slot);
19896b80053dSChris Mason 	blocksize = btrfs_level_size(root, level - 1);
19906b80053dSChris Mason 	eb = btrfs_find_tree_block(root, search, blocksize);
19915f39d397SChris Mason 	if (eb) {
19925f39d397SChris Mason 		free_extent_buffer(eb);
19933c69faecSChris Mason 		return;
19943c69faecSChris Mason 	}
19953c69faecSChris Mason 
1996a7175319SChris Mason 	target = search;
19976b80053dSChris Mason 
19985f39d397SChris Mason 	nritems = btrfs_header_nritems(node);
19996b80053dSChris Mason 	nr = slot;
200025b8b936SJosef Bacik 
20013c69faecSChris Mason 	while (1) {
20026b80053dSChris Mason 		if (direction < 0) {
20036b80053dSChris Mason 			if (nr == 0)
20043c69faecSChris Mason 				break;
20056b80053dSChris Mason 			nr--;
20066b80053dSChris Mason 		} else if (direction > 0) {
20076b80053dSChris Mason 			nr++;
20086b80053dSChris Mason 			if (nr >= nritems)
20096b80053dSChris Mason 				break;
20103c69faecSChris Mason 		}
201101f46658SChris Mason 		if (path->reada < 0 && objectid) {
201201f46658SChris Mason 			btrfs_node_key(node, &disk_key, nr);
201301f46658SChris Mason 			if (btrfs_disk_key_objectid(&disk_key) != objectid)
201401f46658SChris Mason 				break;
201501f46658SChris Mason 		}
20166b80053dSChris Mason 		search = btrfs_node_blockptr(node, nr);
2017a7175319SChris Mason 		if ((search <= target && target - search <= 65536) ||
2018a7175319SChris Mason 		    (search > target && search - target <= 65536)) {
2019cb25c2eaSJosef Bacik 			gen = btrfs_node_ptr_generation(node, nr);
2020cb25c2eaSJosef Bacik 			readahead_tree_block(root, search, blocksize, gen);
20216b80053dSChris Mason 			nread += blocksize;
20223c69faecSChris Mason 		}
20236b80053dSChris Mason 		nscan++;
2024a7175319SChris Mason 		if ((nread > 65536 || nscan > 32))
20256b80053dSChris Mason 			break;
20263c69faecSChris Mason 	}
20273c69faecSChris Mason }
2028925baeddSChris Mason 
2029d352ac68SChris Mason /*
2030b4ce94deSChris Mason  * returns -EAGAIN if it had to drop the path, or zero if everything was in
2031b4ce94deSChris Mason  * cache
2032b4ce94deSChris Mason  */
2033b4ce94deSChris Mason static noinline int reada_for_balance(struct btrfs_root *root,
2034b4ce94deSChris Mason 				      struct btrfs_path *path, int level)
2035b4ce94deSChris Mason {
2036b4ce94deSChris Mason 	int slot;
2037b4ce94deSChris Mason 	int nritems;
2038b4ce94deSChris Mason 	struct extent_buffer *parent;
2039b4ce94deSChris Mason 	struct extent_buffer *eb;
2040b4ce94deSChris Mason 	u64 gen;
2041b4ce94deSChris Mason 	u64 block1 = 0;
2042b4ce94deSChris Mason 	u64 block2 = 0;
2043b4ce94deSChris Mason 	int ret = 0;
2044b4ce94deSChris Mason 	int blocksize;
2045b4ce94deSChris Mason 
20468c594ea8SChris Mason 	parent = path->nodes[level + 1];
2047b4ce94deSChris Mason 	if (!parent)
2048b4ce94deSChris Mason 		return 0;
2049b4ce94deSChris Mason 
2050b4ce94deSChris Mason 	nritems = btrfs_header_nritems(parent);
20518c594ea8SChris Mason 	slot = path->slots[level + 1];
2052b4ce94deSChris Mason 	blocksize = btrfs_level_size(root, level);
2053b4ce94deSChris Mason 
2054b4ce94deSChris Mason 	if (slot > 0) {
2055b4ce94deSChris Mason 		block1 = btrfs_node_blockptr(parent, slot - 1);
2056b4ce94deSChris Mason 		gen = btrfs_node_ptr_generation(parent, slot - 1);
2057b4ce94deSChris Mason 		eb = btrfs_find_tree_block(root, block1, blocksize);
2058b9fab919SChris Mason 		/*
2059b9fab919SChris Mason 		 * if we get -eagain from btrfs_buffer_uptodate, we
2060b9fab919SChris Mason 		 * don't want to return eagain here.  That will loop
2061b9fab919SChris Mason 		 * forever
2062b9fab919SChris Mason 		 */
2063b9fab919SChris Mason 		if (eb && btrfs_buffer_uptodate(eb, gen, 1) != 0)
2064b4ce94deSChris Mason 			block1 = 0;
2065b4ce94deSChris Mason 		free_extent_buffer(eb);
2066b4ce94deSChris Mason 	}
20678c594ea8SChris Mason 	if (slot + 1 < nritems) {
2068b4ce94deSChris Mason 		block2 = btrfs_node_blockptr(parent, slot + 1);
2069b4ce94deSChris Mason 		gen = btrfs_node_ptr_generation(parent, slot + 1);
2070b4ce94deSChris Mason 		eb = btrfs_find_tree_block(root, block2, blocksize);
2071b9fab919SChris Mason 		if (eb && btrfs_buffer_uptodate(eb, gen, 1) != 0)
2072b4ce94deSChris Mason 			block2 = 0;
2073b4ce94deSChris Mason 		free_extent_buffer(eb);
2074b4ce94deSChris Mason 	}
2075b4ce94deSChris Mason 	if (block1 || block2) {
2076b4ce94deSChris Mason 		ret = -EAGAIN;
20778c594ea8SChris Mason 
20788c594ea8SChris Mason 		/* release the whole path */
2079b3b4aa74SDavid Sterba 		btrfs_release_path(path);
20808c594ea8SChris Mason 
20818c594ea8SChris Mason 		/* read the blocks */
2082b4ce94deSChris Mason 		if (block1)
2083b4ce94deSChris Mason 			readahead_tree_block(root, block1, blocksize, 0);
2084b4ce94deSChris Mason 		if (block2)
2085b4ce94deSChris Mason 			readahead_tree_block(root, block2, blocksize, 0);
2086b4ce94deSChris Mason 
2087b4ce94deSChris Mason 		if (block1) {
2088b4ce94deSChris Mason 			eb = read_tree_block(root, block1, blocksize, 0);
2089b4ce94deSChris Mason 			free_extent_buffer(eb);
2090b4ce94deSChris Mason 		}
20918c594ea8SChris Mason 		if (block2) {
2092b4ce94deSChris Mason 			eb = read_tree_block(root, block2, blocksize, 0);
2093b4ce94deSChris Mason 			free_extent_buffer(eb);
2094b4ce94deSChris Mason 		}
2095b4ce94deSChris Mason 	}
2096b4ce94deSChris Mason 	return ret;
2097b4ce94deSChris Mason }
2098b4ce94deSChris Mason 
2099b4ce94deSChris Mason 
2100b4ce94deSChris Mason /*
2101d397712bSChris Mason  * when we walk down the tree, it is usually safe to unlock the higher layers
2102d397712bSChris Mason  * in the tree.  The exceptions are when our path goes through slot 0, because
2103d397712bSChris Mason  * operations on the tree might require changing key pointers higher up in the
2104d397712bSChris Mason  * tree.
2105d352ac68SChris Mason  *
2106d397712bSChris Mason  * callers might also have set path->keep_locks, which tells this code to keep
2107d397712bSChris Mason  * the lock if the path points to the last slot in the block.  This is part of
2108d397712bSChris Mason  * walking through the tree, and selecting the next slot in the higher block.
2109d352ac68SChris Mason  *
2110d397712bSChris Mason  * lowest_unlock sets the lowest level in the tree we're allowed to unlock.  so
2111d397712bSChris Mason  * if lowest_unlock is 1, level 0 won't be unlocked
2112d352ac68SChris Mason  */
2113e02119d5SChris Mason static noinline void unlock_up(struct btrfs_path *path, int level,
2114f7c79f30SChris Mason 			       int lowest_unlock, int min_write_lock_level,
2115f7c79f30SChris Mason 			       int *write_lock_level)
2116925baeddSChris Mason {
2117925baeddSChris Mason 	int i;
2118925baeddSChris Mason 	int skip_level = level;
2119051e1b9fSChris Mason 	int no_skips = 0;
2120925baeddSChris Mason 	struct extent_buffer *t;
2121925baeddSChris Mason 
2122925baeddSChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2123925baeddSChris Mason 		if (!path->nodes[i])
2124925baeddSChris Mason 			break;
2125925baeddSChris Mason 		if (!path->locks[i])
2126925baeddSChris Mason 			break;
2127051e1b9fSChris Mason 		if (!no_skips && path->slots[i] == 0) {
2128925baeddSChris Mason 			skip_level = i + 1;
2129925baeddSChris Mason 			continue;
2130925baeddSChris Mason 		}
2131051e1b9fSChris Mason 		if (!no_skips && path->keep_locks) {
2132925baeddSChris Mason 			u32 nritems;
2133925baeddSChris Mason 			t = path->nodes[i];
2134925baeddSChris Mason 			nritems = btrfs_header_nritems(t);
2135051e1b9fSChris Mason 			if (nritems < 1 || path->slots[i] >= nritems - 1) {
2136925baeddSChris Mason 				skip_level = i + 1;
2137925baeddSChris Mason 				continue;
2138925baeddSChris Mason 			}
2139925baeddSChris Mason 		}
2140051e1b9fSChris Mason 		if (skip_level < i && i >= lowest_unlock)
2141051e1b9fSChris Mason 			no_skips = 1;
2142051e1b9fSChris Mason 
2143925baeddSChris Mason 		t = path->nodes[i];
2144925baeddSChris Mason 		if (i >= lowest_unlock && i > skip_level && path->locks[i]) {
2145bd681513SChris Mason 			btrfs_tree_unlock_rw(t, path->locks[i]);
2146925baeddSChris Mason 			path->locks[i] = 0;
2147f7c79f30SChris Mason 			if (write_lock_level &&
2148f7c79f30SChris Mason 			    i > min_write_lock_level &&
2149f7c79f30SChris Mason 			    i <= *write_lock_level) {
2150f7c79f30SChris Mason 				*write_lock_level = i - 1;
2151f7c79f30SChris Mason 			}
2152925baeddSChris Mason 		}
2153925baeddSChris Mason 	}
2154925baeddSChris Mason }
2155925baeddSChris Mason 
21563c69faecSChris Mason /*
2157b4ce94deSChris Mason  * This releases any locks held in the path starting at level and
2158b4ce94deSChris Mason  * going all the way up to the root.
2159b4ce94deSChris Mason  *
2160b4ce94deSChris Mason  * btrfs_search_slot will keep the lock held on higher nodes in a few
2161b4ce94deSChris Mason  * corner cases, such as COW of the block at slot zero in the node.  This
2162b4ce94deSChris Mason  * ignores those rules, and it should only be called when there are no
2163b4ce94deSChris Mason  * more updates to be done higher up in the tree.
2164b4ce94deSChris Mason  */
2165b4ce94deSChris Mason noinline void btrfs_unlock_up_safe(struct btrfs_path *path, int level)
2166b4ce94deSChris Mason {
2167b4ce94deSChris Mason 	int i;
2168b4ce94deSChris Mason 
21695d4f98a2SYan Zheng 	if (path->keep_locks)
2170b4ce94deSChris Mason 		return;
2171b4ce94deSChris Mason 
2172b4ce94deSChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2173b4ce94deSChris Mason 		if (!path->nodes[i])
217412f4daccSChris Mason 			continue;
2175b4ce94deSChris Mason 		if (!path->locks[i])
217612f4daccSChris Mason 			continue;
2177bd681513SChris Mason 		btrfs_tree_unlock_rw(path->nodes[i], path->locks[i]);
2178b4ce94deSChris Mason 		path->locks[i] = 0;
2179b4ce94deSChris Mason 	}
2180b4ce94deSChris Mason }
2181b4ce94deSChris Mason 
2182b4ce94deSChris Mason /*
2183c8c42864SChris Mason  * helper function for btrfs_search_slot.  The goal is to find a block
2184c8c42864SChris Mason  * in cache without setting the path to blocking.  If we find the block
2185c8c42864SChris Mason  * we return zero and the path is unchanged.
2186c8c42864SChris Mason  *
2187c8c42864SChris Mason  * If we can't find the block, we set the path blocking and do some
2188c8c42864SChris Mason  * reada.  -EAGAIN is returned and the search must be repeated.
2189c8c42864SChris Mason  */
2190c8c42864SChris Mason static int
2191c8c42864SChris Mason read_block_for_search(struct btrfs_trans_handle *trans,
2192c8c42864SChris Mason 		       struct btrfs_root *root, struct btrfs_path *p,
2193c8c42864SChris Mason 		       struct extent_buffer **eb_ret, int level, int slot,
21945d9e75c4SJan Schmidt 		       struct btrfs_key *key, u64 time_seq)
2195c8c42864SChris Mason {
2196c8c42864SChris Mason 	u64 blocknr;
2197c8c42864SChris Mason 	u64 gen;
2198c8c42864SChris Mason 	u32 blocksize;
2199c8c42864SChris Mason 	struct extent_buffer *b = *eb_ret;
2200c8c42864SChris Mason 	struct extent_buffer *tmp;
220176a05b35SChris Mason 	int ret;
2202c8c42864SChris Mason 
2203c8c42864SChris Mason 	blocknr = btrfs_node_blockptr(b, slot);
2204c8c42864SChris Mason 	gen = btrfs_node_ptr_generation(b, slot);
2205c8c42864SChris Mason 	blocksize = btrfs_level_size(root, level - 1);
2206c8c42864SChris Mason 
2207c8c42864SChris Mason 	tmp = btrfs_find_tree_block(root, blocknr, blocksize);
2208cb44921aSChris Mason 	if (tmp) {
2209b9fab919SChris Mason 		/* first we do an atomic uptodate check */
2210b9fab919SChris Mason 		if (btrfs_buffer_uptodate(tmp, 0, 1) > 0) {
2211b9fab919SChris Mason 			if (btrfs_buffer_uptodate(tmp, gen, 1) > 0) {
221276a05b35SChris Mason 				/*
2213cb44921aSChris Mason 				 * we found an up to date block without
2214cb44921aSChris Mason 				 * sleeping, return
221576a05b35SChris Mason 				 * right away
221676a05b35SChris Mason 				 */
2217c8c42864SChris Mason 				*eb_ret = tmp;
2218c8c42864SChris Mason 				return 0;
2219c8c42864SChris Mason 			}
2220cb44921aSChris Mason 			/* the pages were up to date, but we failed
2221cb44921aSChris Mason 			 * the generation number check.  Do a full
2222cb44921aSChris Mason 			 * read for the generation number that is correct.
2223cb44921aSChris Mason 			 * We must do this without dropping locks so
2224cb44921aSChris Mason 			 * we can trust our generation number
2225cb44921aSChris Mason 			 */
2226cb44921aSChris Mason 			free_extent_buffer(tmp);
2227bd681513SChris Mason 			btrfs_set_path_blocking(p);
2228bd681513SChris Mason 
2229b9fab919SChris Mason 			/* now we're allowed to do a blocking uptodate check */
2230cb44921aSChris Mason 			tmp = read_tree_block(root, blocknr, blocksize, gen);
2231b9fab919SChris Mason 			if (tmp && btrfs_buffer_uptodate(tmp, gen, 0) > 0) {
2232cb44921aSChris Mason 				*eb_ret = tmp;
2233cb44921aSChris Mason 				return 0;
2234cb44921aSChris Mason 			}
2235cb44921aSChris Mason 			free_extent_buffer(tmp);
2236b3b4aa74SDavid Sterba 			btrfs_release_path(p);
2237cb44921aSChris Mason 			return -EIO;
2238cb44921aSChris Mason 		}
2239cb44921aSChris Mason 	}
2240c8c42864SChris Mason 
2241c8c42864SChris Mason 	/*
2242c8c42864SChris Mason 	 * reduce lock contention at high levels
2243c8c42864SChris Mason 	 * of the btree by dropping locks before
224476a05b35SChris Mason 	 * we read.  Don't release the lock on the current
224576a05b35SChris Mason 	 * level because we need to walk this node to figure
224676a05b35SChris Mason 	 * out which blocks to read.
2247c8c42864SChris Mason 	 */
22488c594ea8SChris Mason 	btrfs_unlock_up_safe(p, level + 1);
22498c594ea8SChris Mason 	btrfs_set_path_blocking(p);
22508c594ea8SChris Mason 
2251c8c42864SChris Mason 	free_extent_buffer(tmp);
2252c8c42864SChris Mason 	if (p->reada)
2253c8c42864SChris Mason 		reada_for_search(root, p, level, slot, key->objectid);
2254c8c42864SChris Mason 
2255b3b4aa74SDavid Sterba 	btrfs_release_path(p);
225676a05b35SChris Mason 
225776a05b35SChris Mason 	ret = -EAGAIN;
22585bdd3536SYan, Zheng 	tmp = read_tree_block(root, blocknr, blocksize, 0);
225976a05b35SChris Mason 	if (tmp) {
226076a05b35SChris Mason 		/*
226176a05b35SChris Mason 		 * If the read above didn't mark this buffer up to date,
226276a05b35SChris Mason 		 * it will never end up being up to date.  Set ret to EIO now
226376a05b35SChris Mason 		 * and give up so that our caller doesn't loop forever
226476a05b35SChris Mason 		 * on our EAGAINs.
226576a05b35SChris Mason 		 */
2266b9fab919SChris Mason 		if (!btrfs_buffer_uptodate(tmp, 0, 0))
226776a05b35SChris Mason 			ret = -EIO;
2268c8c42864SChris Mason 		free_extent_buffer(tmp);
226976a05b35SChris Mason 	}
227076a05b35SChris Mason 	return ret;
2271c8c42864SChris Mason }
2272c8c42864SChris Mason 
2273c8c42864SChris Mason /*
2274c8c42864SChris Mason  * helper function for btrfs_search_slot.  This does all of the checks
2275c8c42864SChris Mason  * for node-level blocks and does any balancing required based on
2276c8c42864SChris Mason  * the ins_len.
2277c8c42864SChris Mason  *
2278c8c42864SChris Mason  * If no extra work was required, zero is returned.  If we had to
2279c8c42864SChris Mason  * drop the path, -EAGAIN is returned and btrfs_search_slot must
2280c8c42864SChris Mason  * start over
2281c8c42864SChris Mason  */
2282c8c42864SChris Mason static int
2283c8c42864SChris Mason setup_nodes_for_search(struct btrfs_trans_handle *trans,
2284c8c42864SChris Mason 		       struct btrfs_root *root, struct btrfs_path *p,
2285bd681513SChris Mason 		       struct extent_buffer *b, int level, int ins_len,
2286bd681513SChris Mason 		       int *write_lock_level)
2287c8c42864SChris Mason {
2288c8c42864SChris Mason 	int ret;
2289c8c42864SChris Mason 	if ((p->search_for_split || ins_len > 0) && btrfs_header_nritems(b) >=
2290c8c42864SChris Mason 	    BTRFS_NODEPTRS_PER_BLOCK(root) - 3) {
2291c8c42864SChris Mason 		int sret;
2292c8c42864SChris Mason 
2293bd681513SChris Mason 		if (*write_lock_level < level + 1) {
2294bd681513SChris Mason 			*write_lock_level = level + 1;
2295bd681513SChris Mason 			btrfs_release_path(p);
2296bd681513SChris Mason 			goto again;
2297bd681513SChris Mason 		}
2298bd681513SChris Mason 
2299c8c42864SChris Mason 		sret = reada_for_balance(root, p, level);
2300c8c42864SChris Mason 		if (sret)
2301c8c42864SChris Mason 			goto again;
2302c8c42864SChris Mason 
2303c8c42864SChris Mason 		btrfs_set_path_blocking(p);
2304c8c42864SChris Mason 		sret = split_node(trans, root, p, level);
2305bd681513SChris Mason 		btrfs_clear_path_blocking(p, NULL, 0);
2306c8c42864SChris Mason 
2307c8c42864SChris Mason 		BUG_ON(sret > 0);
2308c8c42864SChris Mason 		if (sret) {
2309c8c42864SChris Mason 			ret = sret;
2310c8c42864SChris Mason 			goto done;
2311c8c42864SChris Mason 		}
2312c8c42864SChris Mason 		b = p->nodes[level];
2313c8c42864SChris Mason 	} else if (ins_len < 0 && btrfs_header_nritems(b) <
2314cfbb9308SChris Mason 		   BTRFS_NODEPTRS_PER_BLOCK(root) / 2) {
2315c8c42864SChris Mason 		int sret;
2316c8c42864SChris Mason 
2317bd681513SChris Mason 		if (*write_lock_level < level + 1) {
2318bd681513SChris Mason 			*write_lock_level = level + 1;
2319bd681513SChris Mason 			btrfs_release_path(p);
2320bd681513SChris Mason 			goto again;
2321bd681513SChris Mason 		}
2322bd681513SChris Mason 
2323c8c42864SChris Mason 		sret = reada_for_balance(root, p, level);
2324c8c42864SChris Mason 		if (sret)
2325c8c42864SChris Mason 			goto again;
2326c8c42864SChris Mason 
2327c8c42864SChris Mason 		btrfs_set_path_blocking(p);
2328c8c42864SChris Mason 		sret = balance_level(trans, root, p, level);
2329bd681513SChris Mason 		btrfs_clear_path_blocking(p, NULL, 0);
2330c8c42864SChris Mason 
2331c8c42864SChris Mason 		if (sret) {
2332c8c42864SChris Mason 			ret = sret;
2333c8c42864SChris Mason 			goto done;
2334c8c42864SChris Mason 		}
2335c8c42864SChris Mason 		b = p->nodes[level];
2336c8c42864SChris Mason 		if (!b) {
2337b3b4aa74SDavid Sterba 			btrfs_release_path(p);
2338c8c42864SChris Mason 			goto again;
2339c8c42864SChris Mason 		}
2340c8c42864SChris Mason 		BUG_ON(btrfs_header_nritems(b) == 1);
2341c8c42864SChris Mason 	}
2342c8c42864SChris Mason 	return 0;
2343c8c42864SChris Mason 
2344c8c42864SChris Mason again:
2345c8c42864SChris Mason 	ret = -EAGAIN;
2346c8c42864SChris Mason done:
2347c8c42864SChris Mason 	return ret;
2348c8c42864SChris Mason }
2349c8c42864SChris Mason 
2350c8c42864SChris Mason /*
235174123bd7SChris Mason  * look for key in the tree.  path is filled in with nodes along the way
235274123bd7SChris Mason  * if key is found, we return zero and you can find the item in the leaf
235374123bd7SChris Mason  * level of the path (level 0)
235474123bd7SChris Mason  *
235574123bd7SChris Mason  * If the key isn't found, the path points to the slot where it should
2356aa5d6bedSChris Mason  * be inserted, and 1 is returned.  If there are other errors during the
2357aa5d6bedSChris Mason  * search a negative error number is returned.
235897571fd0SChris Mason  *
235997571fd0SChris Mason  * if ins_len > 0, nodes and leaves will be split as we walk down the
236097571fd0SChris Mason  * tree.  if ins_len < 0, nodes will be merged as we walk down the tree (if
236197571fd0SChris Mason  * possible)
236274123bd7SChris Mason  */
2363e089f05cSChris Mason int btrfs_search_slot(struct btrfs_trans_handle *trans, struct btrfs_root
2364e089f05cSChris Mason 		      *root, struct btrfs_key *key, struct btrfs_path *p, int
2365e089f05cSChris Mason 		      ins_len, int cow)
2366be0e5c09SChris Mason {
23675f39d397SChris Mason 	struct extent_buffer *b;
2368be0e5c09SChris Mason 	int slot;
2369be0e5c09SChris Mason 	int ret;
237033c66f43SYan Zheng 	int err;
2371be0e5c09SChris Mason 	int level;
2372925baeddSChris Mason 	int lowest_unlock = 1;
2373bd681513SChris Mason 	int root_lock;
2374bd681513SChris Mason 	/* everything at write_lock_level or lower must be write locked */
2375bd681513SChris Mason 	int write_lock_level = 0;
23769f3a7427SChris Mason 	u8 lowest_level = 0;
2377f7c79f30SChris Mason 	int min_write_lock_level;
23789f3a7427SChris Mason 
23796702ed49SChris Mason 	lowest_level = p->lowest_level;
2380323ac95bSChris Mason 	WARN_ON(lowest_level && ins_len > 0);
238122b0ebdaSChris Mason 	WARN_ON(p->nodes[0] != NULL);
238225179201SJosef Bacik 
2383bd681513SChris Mason 	if (ins_len < 0) {
2384925baeddSChris Mason 		lowest_unlock = 2;
238565b51a00SChris Mason 
2386bd681513SChris Mason 		/* when we are removing items, we might have to go up to level
2387bd681513SChris Mason 		 * two as we update tree pointers  Make sure we keep write
2388bd681513SChris Mason 		 * for those levels as well
2389bd681513SChris Mason 		 */
2390bd681513SChris Mason 		write_lock_level = 2;
2391bd681513SChris Mason 	} else if (ins_len > 0) {
2392bd681513SChris Mason 		/*
2393bd681513SChris Mason 		 * for inserting items, make sure we have a write lock on
2394bd681513SChris Mason 		 * level 1 so we can update keys
2395bd681513SChris Mason 		 */
2396bd681513SChris Mason 		write_lock_level = 1;
2397bd681513SChris Mason 	}
2398bd681513SChris Mason 
2399bd681513SChris Mason 	if (!cow)
2400bd681513SChris Mason 		write_lock_level = -1;
2401bd681513SChris Mason 
2402bd681513SChris Mason 	if (cow && (p->keep_locks || p->lowest_level))
2403bd681513SChris Mason 		write_lock_level = BTRFS_MAX_LEVEL;
2404bd681513SChris Mason 
2405f7c79f30SChris Mason 	min_write_lock_level = write_lock_level;
2406f7c79f30SChris Mason 
2407bb803951SChris Mason again:
2408bd681513SChris Mason 	/*
2409bd681513SChris Mason 	 * we try very hard to do read locks on the root
2410bd681513SChris Mason 	 */
2411bd681513SChris Mason 	root_lock = BTRFS_READ_LOCK;
2412bd681513SChris Mason 	level = 0;
24135d4f98a2SYan Zheng 	if (p->search_commit_root) {
2414bd681513SChris Mason 		/*
2415bd681513SChris Mason 		 * the commit roots are read only
2416bd681513SChris Mason 		 * so we always do read locks
2417bd681513SChris Mason 		 */
24185d4f98a2SYan Zheng 		b = root->commit_root;
24195d4f98a2SYan Zheng 		extent_buffer_get(b);
2420bd681513SChris Mason 		level = btrfs_header_level(b);
24215d4f98a2SYan Zheng 		if (!p->skip_locking)
2422bd681513SChris Mason 			btrfs_tree_read_lock(b);
24235d4f98a2SYan Zheng 	} else {
2424bd681513SChris Mason 		if (p->skip_locking) {
24255cd57b2cSChris Mason 			b = btrfs_root_node(root);
2426bd681513SChris Mason 			level = btrfs_header_level(b);
2427bd681513SChris Mason 		} else {
2428bd681513SChris Mason 			/* we don't know the level of the root node
2429bd681513SChris Mason 			 * until we actually have it read locked
2430bd681513SChris Mason 			 */
2431bd681513SChris Mason 			b = btrfs_read_lock_root_node(root);
2432bd681513SChris Mason 			level = btrfs_header_level(b);
2433bd681513SChris Mason 			if (level <= write_lock_level) {
2434bd681513SChris Mason 				/* whoops, must trade for write lock */
2435bd681513SChris Mason 				btrfs_tree_read_unlock(b);
2436bd681513SChris Mason 				free_extent_buffer(b);
2437925baeddSChris Mason 				b = btrfs_lock_root_node(root);
2438bd681513SChris Mason 				root_lock = BTRFS_WRITE_LOCK;
2439bd681513SChris Mason 
2440bd681513SChris Mason 				/* the level might have changed, check again */
2441bd681513SChris Mason 				level = btrfs_header_level(b);
24425d4f98a2SYan Zheng 			}
2443bd681513SChris Mason 		}
2444bd681513SChris Mason 	}
2445bd681513SChris Mason 	p->nodes[level] = b;
2446bd681513SChris Mason 	if (!p->skip_locking)
2447bd681513SChris Mason 		p->locks[level] = root_lock;
2448925baeddSChris Mason 
2449eb60ceacSChris Mason 	while (b) {
24505f39d397SChris Mason 		level = btrfs_header_level(b);
245165b51a00SChris Mason 
245265b51a00SChris Mason 		/*
245365b51a00SChris Mason 		 * setup the path here so we can release it under lock
245465b51a00SChris Mason 		 * contention with the cow code
245565b51a00SChris Mason 		 */
245602217ed2SChris Mason 		if (cow) {
2457c8c42864SChris Mason 			/*
2458c8c42864SChris Mason 			 * if we don't really need to cow this block
2459c8c42864SChris Mason 			 * then we don't want to set the path blocking,
2460c8c42864SChris Mason 			 * so we test it here
2461c8c42864SChris Mason 			 */
24625d4f98a2SYan Zheng 			if (!should_cow_block(trans, root, b))
246365b51a00SChris Mason 				goto cow_done;
24645d4f98a2SYan Zheng 
2465b4ce94deSChris Mason 			btrfs_set_path_blocking(p);
2466b4ce94deSChris Mason 
2467bd681513SChris Mason 			/*
2468bd681513SChris Mason 			 * must have write locks on this node and the
2469bd681513SChris Mason 			 * parent
2470bd681513SChris Mason 			 */
2471bd681513SChris Mason 			if (level + 1 > write_lock_level) {
2472bd681513SChris Mason 				write_lock_level = level + 1;
2473bd681513SChris Mason 				btrfs_release_path(p);
2474bd681513SChris Mason 				goto again;
2475bd681513SChris Mason 			}
2476bd681513SChris Mason 
247733c66f43SYan Zheng 			err = btrfs_cow_block(trans, root, b,
2478e20d96d6SChris Mason 					      p->nodes[level + 1],
24799fa8cfe7SChris Mason 					      p->slots[level + 1], &b);
248033c66f43SYan Zheng 			if (err) {
248133c66f43SYan Zheng 				ret = err;
248265b51a00SChris Mason 				goto done;
248354aa1f4dSChris Mason 			}
248402217ed2SChris Mason 		}
248565b51a00SChris Mason cow_done:
248602217ed2SChris Mason 		BUG_ON(!cow && ins_len);
248765b51a00SChris Mason 
2488eb60ceacSChris Mason 		p->nodes[level] = b;
2489bd681513SChris Mason 		btrfs_clear_path_blocking(p, NULL, 0);
2490b4ce94deSChris Mason 
2491b4ce94deSChris Mason 		/*
2492b4ce94deSChris Mason 		 * we have a lock on b and as long as we aren't changing
2493b4ce94deSChris Mason 		 * the tree, there is no way to for the items in b to change.
2494b4ce94deSChris Mason 		 * It is safe to drop the lock on our parent before we
2495b4ce94deSChris Mason 		 * go through the expensive btree search on b.
2496b4ce94deSChris Mason 		 *
2497b4ce94deSChris Mason 		 * If cow is true, then we might be changing slot zero,
2498b4ce94deSChris Mason 		 * which may require changing the parent.  So, we can't
2499b4ce94deSChris Mason 		 * drop the lock until after we know which slot we're
2500b4ce94deSChris Mason 		 * operating on.
2501b4ce94deSChris Mason 		 */
2502b4ce94deSChris Mason 		if (!cow)
2503b4ce94deSChris Mason 			btrfs_unlock_up_safe(p, level + 1);
2504b4ce94deSChris Mason 
25055f39d397SChris Mason 		ret = bin_search(b, key, level, &slot);
2506b4ce94deSChris Mason 
25075f39d397SChris Mason 		if (level != 0) {
250833c66f43SYan Zheng 			int dec = 0;
250933c66f43SYan Zheng 			if (ret && slot > 0) {
251033c66f43SYan Zheng 				dec = 1;
2511be0e5c09SChris Mason 				slot -= 1;
251233c66f43SYan Zheng 			}
2513be0e5c09SChris Mason 			p->slots[level] = slot;
251433c66f43SYan Zheng 			err = setup_nodes_for_search(trans, root, p, b, level,
2515bd681513SChris Mason 					     ins_len, &write_lock_level);
251633c66f43SYan Zheng 			if (err == -EAGAIN)
2517b4ce94deSChris Mason 				goto again;
251833c66f43SYan Zheng 			if (err) {
251933c66f43SYan Zheng 				ret = err;
252065b51a00SChris Mason 				goto done;
252133c66f43SYan Zheng 			}
25225c680ed6SChris Mason 			b = p->nodes[level];
25235c680ed6SChris Mason 			slot = p->slots[level];
2524b4ce94deSChris Mason 
2525bd681513SChris Mason 			/*
2526bd681513SChris Mason 			 * slot 0 is special, if we change the key
2527bd681513SChris Mason 			 * we have to update the parent pointer
2528bd681513SChris Mason 			 * which means we must have a write lock
2529bd681513SChris Mason 			 * on the parent
2530bd681513SChris Mason 			 */
2531bd681513SChris Mason 			if (slot == 0 && cow &&
2532bd681513SChris Mason 			    write_lock_level < level + 1) {
2533bd681513SChris Mason 				write_lock_level = level + 1;
2534bd681513SChris Mason 				btrfs_release_path(p);
2535bd681513SChris Mason 				goto again;
2536bd681513SChris Mason 			}
2537bd681513SChris Mason 
2538f7c79f30SChris Mason 			unlock_up(p, level, lowest_unlock,
2539f7c79f30SChris Mason 				  min_write_lock_level, &write_lock_level);
2540f9efa9c7SChris Mason 
2541925baeddSChris Mason 			if (level == lowest_level) {
254233c66f43SYan Zheng 				if (dec)
254333c66f43SYan Zheng 					p->slots[level]++;
25445b21f2edSZheng Yan 				goto done;
2545925baeddSChris Mason 			}
2546ca7a79adSChris Mason 
254733c66f43SYan Zheng 			err = read_block_for_search(trans, root, p,
25485d9e75c4SJan Schmidt 						    &b, level, slot, key, 0);
254933c66f43SYan Zheng 			if (err == -EAGAIN)
2550051e1b9fSChris Mason 				goto again;
255133c66f43SYan Zheng 			if (err) {
255233c66f43SYan Zheng 				ret = err;
255376a05b35SChris Mason 				goto done;
255433c66f43SYan Zheng 			}
255576a05b35SChris Mason 
2556b4ce94deSChris Mason 			if (!p->skip_locking) {
2557bd681513SChris Mason 				level = btrfs_header_level(b);
2558bd681513SChris Mason 				if (level <= write_lock_level) {
2559bd681513SChris Mason 					err = btrfs_try_tree_write_lock(b);
256033c66f43SYan Zheng 					if (!err) {
2561b4ce94deSChris Mason 						btrfs_set_path_blocking(p);
2562925baeddSChris Mason 						btrfs_tree_lock(b);
2563bd681513SChris Mason 						btrfs_clear_path_blocking(p, b,
2564bd681513SChris Mason 								  BTRFS_WRITE_LOCK);
2565b4ce94deSChris Mason 					}
2566bd681513SChris Mason 					p->locks[level] = BTRFS_WRITE_LOCK;
2567bd681513SChris Mason 				} else {
2568bd681513SChris Mason 					err = btrfs_try_tree_read_lock(b);
2569bd681513SChris Mason 					if (!err) {
2570bd681513SChris Mason 						btrfs_set_path_blocking(p);
2571bd681513SChris Mason 						btrfs_tree_read_lock(b);
2572bd681513SChris Mason 						btrfs_clear_path_blocking(p, b,
2573bd681513SChris Mason 								  BTRFS_READ_LOCK);
2574bd681513SChris Mason 					}
2575bd681513SChris Mason 					p->locks[level] = BTRFS_READ_LOCK;
2576bd681513SChris Mason 				}
2577bd681513SChris Mason 				p->nodes[level] = b;
2578b4ce94deSChris Mason 			}
2579be0e5c09SChris Mason 		} else {
2580be0e5c09SChris Mason 			p->slots[level] = slot;
258187b29b20SYan Zheng 			if (ins_len > 0 &&
258287b29b20SYan Zheng 			    btrfs_leaf_free_space(root, b) < ins_len) {
2583bd681513SChris Mason 				if (write_lock_level < 1) {
2584bd681513SChris Mason 					write_lock_level = 1;
2585bd681513SChris Mason 					btrfs_release_path(p);
2586bd681513SChris Mason 					goto again;
2587bd681513SChris Mason 				}
2588bd681513SChris Mason 
2589b4ce94deSChris Mason 				btrfs_set_path_blocking(p);
259033c66f43SYan Zheng 				err = split_leaf(trans, root, key,
2591cc0c5538SChris Mason 						 p, ins_len, ret == 0);
2592bd681513SChris Mason 				btrfs_clear_path_blocking(p, NULL, 0);
2593b4ce94deSChris Mason 
259433c66f43SYan Zheng 				BUG_ON(err > 0);
259533c66f43SYan Zheng 				if (err) {
259633c66f43SYan Zheng 					ret = err;
259765b51a00SChris Mason 					goto done;
259865b51a00SChris Mason 				}
25995c680ed6SChris Mason 			}
2600459931ecSChris Mason 			if (!p->search_for_split)
2601f7c79f30SChris Mason 				unlock_up(p, level, lowest_unlock,
2602f7c79f30SChris Mason 					  min_write_lock_level, &write_lock_level);
260365b51a00SChris Mason 			goto done;
260465b51a00SChris Mason 		}
260565b51a00SChris Mason 	}
260665b51a00SChris Mason 	ret = 1;
260765b51a00SChris Mason done:
2608b4ce94deSChris Mason 	/*
2609b4ce94deSChris Mason 	 * we don't really know what they plan on doing with the path
2610b4ce94deSChris Mason 	 * from here on, so for now just mark it as blocking
2611b4ce94deSChris Mason 	 */
2612b9473439SChris Mason 	if (!p->leave_spinning)
2613b4ce94deSChris Mason 		btrfs_set_path_blocking(p);
261476a05b35SChris Mason 	if (ret < 0)
2615b3b4aa74SDavid Sterba 		btrfs_release_path(p);
2616be0e5c09SChris Mason 	return ret;
2617be0e5c09SChris Mason }
2618be0e5c09SChris Mason 
261974123bd7SChris Mason /*
26205d9e75c4SJan Schmidt  * Like btrfs_search_slot, this looks for a key in the given tree. It uses the
26215d9e75c4SJan Schmidt  * current state of the tree together with the operations recorded in the tree
26225d9e75c4SJan Schmidt  * modification log to search for the key in a previous version of this tree, as
26235d9e75c4SJan Schmidt  * denoted by the time_seq parameter.
26245d9e75c4SJan Schmidt  *
26255d9e75c4SJan Schmidt  * Naturally, there is no support for insert, delete or cow operations.
26265d9e75c4SJan Schmidt  *
26275d9e75c4SJan Schmidt  * The resulting path and return value will be set up as if we called
26285d9e75c4SJan Schmidt  * btrfs_search_slot at that point in time with ins_len and cow both set to 0.
26295d9e75c4SJan Schmidt  */
26305d9e75c4SJan Schmidt int btrfs_search_old_slot(struct btrfs_root *root, struct btrfs_key *key,
26315d9e75c4SJan Schmidt 			  struct btrfs_path *p, u64 time_seq)
26325d9e75c4SJan Schmidt {
26335d9e75c4SJan Schmidt 	struct extent_buffer *b;
26345d9e75c4SJan Schmidt 	int slot;
26355d9e75c4SJan Schmidt 	int ret;
26365d9e75c4SJan Schmidt 	int err;
26375d9e75c4SJan Schmidt 	int level;
26385d9e75c4SJan Schmidt 	int lowest_unlock = 1;
26395d9e75c4SJan Schmidt 	u8 lowest_level = 0;
26405d9e75c4SJan Schmidt 
26415d9e75c4SJan Schmidt 	lowest_level = p->lowest_level;
26425d9e75c4SJan Schmidt 	WARN_ON(p->nodes[0] != NULL);
26435d9e75c4SJan Schmidt 
26445d9e75c4SJan Schmidt 	if (p->search_commit_root) {
26455d9e75c4SJan Schmidt 		BUG_ON(time_seq);
26465d9e75c4SJan Schmidt 		return btrfs_search_slot(NULL, root, key, p, 0, 0);
26475d9e75c4SJan Schmidt 	}
26485d9e75c4SJan Schmidt 
26495d9e75c4SJan Schmidt again:
26505d9e75c4SJan Schmidt 	b = get_old_root(root, time_seq);
26515d9e75c4SJan Schmidt 	level = btrfs_header_level(b);
26525d9e75c4SJan Schmidt 	p->locks[level] = BTRFS_READ_LOCK;
26535d9e75c4SJan Schmidt 
26545d9e75c4SJan Schmidt 	while (b) {
26555d9e75c4SJan Schmidt 		level = btrfs_header_level(b);
26565d9e75c4SJan Schmidt 		p->nodes[level] = b;
26575d9e75c4SJan Schmidt 		btrfs_clear_path_blocking(p, NULL, 0);
26585d9e75c4SJan Schmidt 
26595d9e75c4SJan Schmidt 		/*
26605d9e75c4SJan Schmidt 		 * we have a lock on b and as long as we aren't changing
26615d9e75c4SJan Schmidt 		 * the tree, there is no way to for the items in b to change.
26625d9e75c4SJan Schmidt 		 * It is safe to drop the lock on our parent before we
26635d9e75c4SJan Schmidt 		 * go through the expensive btree search on b.
26645d9e75c4SJan Schmidt 		 */
26655d9e75c4SJan Schmidt 		btrfs_unlock_up_safe(p, level + 1);
26665d9e75c4SJan Schmidt 
26675d9e75c4SJan Schmidt 		ret = bin_search(b, key, level, &slot);
26685d9e75c4SJan Schmidt 
26695d9e75c4SJan Schmidt 		if (level != 0) {
26705d9e75c4SJan Schmidt 			int dec = 0;
26715d9e75c4SJan Schmidt 			if (ret && slot > 0) {
26725d9e75c4SJan Schmidt 				dec = 1;
26735d9e75c4SJan Schmidt 				slot -= 1;
26745d9e75c4SJan Schmidt 			}
26755d9e75c4SJan Schmidt 			p->slots[level] = slot;
26765d9e75c4SJan Schmidt 			unlock_up(p, level, lowest_unlock, 0, NULL);
26775d9e75c4SJan Schmidt 
26785d9e75c4SJan Schmidt 			if (level == lowest_level) {
26795d9e75c4SJan Schmidt 				if (dec)
26805d9e75c4SJan Schmidt 					p->slots[level]++;
26815d9e75c4SJan Schmidt 				goto done;
26825d9e75c4SJan Schmidt 			}
26835d9e75c4SJan Schmidt 
26845d9e75c4SJan Schmidt 			err = read_block_for_search(NULL, root, p, &b, level,
26855d9e75c4SJan Schmidt 						    slot, key, time_seq);
26865d9e75c4SJan Schmidt 			if (err == -EAGAIN)
26875d9e75c4SJan Schmidt 				goto again;
26885d9e75c4SJan Schmidt 			if (err) {
26895d9e75c4SJan Schmidt 				ret = err;
26905d9e75c4SJan Schmidt 				goto done;
26915d9e75c4SJan Schmidt 			}
26925d9e75c4SJan Schmidt 
26935d9e75c4SJan Schmidt 			level = btrfs_header_level(b);
26945d9e75c4SJan Schmidt 			err = btrfs_try_tree_read_lock(b);
26955d9e75c4SJan Schmidt 			if (!err) {
26965d9e75c4SJan Schmidt 				btrfs_set_path_blocking(p);
26975d9e75c4SJan Schmidt 				btrfs_tree_read_lock(b);
26985d9e75c4SJan Schmidt 				btrfs_clear_path_blocking(p, b,
26995d9e75c4SJan Schmidt 							  BTRFS_READ_LOCK);
27005d9e75c4SJan Schmidt 			}
27015d9e75c4SJan Schmidt 			p->locks[level] = BTRFS_READ_LOCK;
27025d9e75c4SJan Schmidt 			p->nodes[level] = b;
27035d9e75c4SJan Schmidt 			b = tree_mod_log_rewind(root->fs_info, b, time_seq);
27045d9e75c4SJan Schmidt 			if (b != p->nodes[level]) {
27055d9e75c4SJan Schmidt 				btrfs_tree_unlock_rw(p->nodes[level],
27065d9e75c4SJan Schmidt 						     p->locks[level]);
27075d9e75c4SJan Schmidt 				p->locks[level] = 0;
27085d9e75c4SJan Schmidt 				p->nodes[level] = b;
27095d9e75c4SJan Schmidt 			}
27105d9e75c4SJan Schmidt 		} else {
27115d9e75c4SJan Schmidt 			p->slots[level] = slot;
27125d9e75c4SJan Schmidt 			unlock_up(p, level, lowest_unlock, 0, NULL);
27135d9e75c4SJan Schmidt 			goto done;
27145d9e75c4SJan Schmidt 		}
27155d9e75c4SJan Schmidt 	}
27165d9e75c4SJan Schmidt 	ret = 1;
27175d9e75c4SJan Schmidt done:
27185d9e75c4SJan Schmidt 	if (!p->leave_spinning)
27195d9e75c4SJan Schmidt 		btrfs_set_path_blocking(p);
27205d9e75c4SJan Schmidt 	if (ret < 0)
27215d9e75c4SJan Schmidt 		btrfs_release_path(p);
27225d9e75c4SJan Schmidt 
27235d9e75c4SJan Schmidt 	return ret;
27245d9e75c4SJan Schmidt }
27255d9e75c4SJan Schmidt 
27265d9e75c4SJan Schmidt /*
272774123bd7SChris Mason  * adjust the pointers going up the tree, starting at level
272874123bd7SChris Mason  * making sure the right key of each node is points to 'key'.
272974123bd7SChris Mason  * This is used after shifting pointers to the left, so it stops
273074123bd7SChris Mason  * fixing up pointers when a given leaf/node is not in slot 0 of the
273174123bd7SChris Mason  * higher levels
2732aa5d6bedSChris Mason  *
273374123bd7SChris Mason  */
2734143bede5SJeff Mahoney static void fixup_low_keys(struct btrfs_trans_handle *trans,
27355f39d397SChris Mason 			   struct btrfs_root *root, struct btrfs_path *path,
27365f39d397SChris Mason 			   struct btrfs_disk_key *key, int level)
2737be0e5c09SChris Mason {
2738be0e5c09SChris Mason 	int i;
27395f39d397SChris Mason 	struct extent_buffer *t;
27405f39d397SChris Mason 
2741234b63a0SChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2742be0e5c09SChris Mason 		int tslot = path->slots[i];
2743eb60ceacSChris Mason 		if (!path->nodes[i])
2744be0e5c09SChris Mason 			break;
27455f39d397SChris Mason 		t = path->nodes[i];
2746f230475eSJan Schmidt 		tree_mod_log_set_node_key(root->fs_info, t, key, tslot, 1);
27475f39d397SChris Mason 		btrfs_set_node_key(t, key, tslot);
2748d6025579SChris Mason 		btrfs_mark_buffer_dirty(path->nodes[i]);
2749be0e5c09SChris Mason 		if (tslot != 0)
2750be0e5c09SChris Mason 			break;
2751be0e5c09SChris Mason 	}
2752be0e5c09SChris Mason }
2753be0e5c09SChris Mason 
275474123bd7SChris Mason /*
275531840ae1SZheng Yan  * update item key.
275631840ae1SZheng Yan  *
275731840ae1SZheng Yan  * This function isn't completely safe. It's the caller's responsibility
275831840ae1SZheng Yan  * that the new key won't break the order
275931840ae1SZheng Yan  */
2760143bede5SJeff Mahoney void btrfs_set_item_key_safe(struct btrfs_trans_handle *trans,
276131840ae1SZheng Yan 			     struct btrfs_root *root, struct btrfs_path *path,
276231840ae1SZheng Yan 			     struct btrfs_key *new_key)
276331840ae1SZheng Yan {
276431840ae1SZheng Yan 	struct btrfs_disk_key disk_key;
276531840ae1SZheng Yan 	struct extent_buffer *eb;
276631840ae1SZheng Yan 	int slot;
276731840ae1SZheng Yan 
276831840ae1SZheng Yan 	eb = path->nodes[0];
276931840ae1SZheng Yan 	slot = path->slots[0];
277031840ae1SZheng Yan 	if (slot > 0) {
277131840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot - 1);
2772143bede5SJeff Mahoney 		BUG_ON(comp_keys(&disk_key, new_key) >= 0);
277331840ae1SZheng Yan 	}
277431840ae1SZheng Yan 	if (slot < btrfs_header_nritems(eb) - 1) {
277531840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot + 1);
2776143bede5SJeff Mahoney 		BUG_ON(comp_keys(&disk_key, new_key) <= 0);
277731840ae1SZheng Yan 	}
277831840ae1SZheng Yan 
277931840ae1SZheng Yan 	btrfs_cpu_key_to_disk(&disk_key, new_key);
278031840ae1SZheng Yan 	btrfs_set_item_key(eb, &disk_key, slot);
278131840ae1SZheng Yan 	btrfs_mark_buffer_dirty(eb);
278231840ae1SZheng Yan 	if (slot == 0)
278331840ae1SZheng Yan 		fixup_low_keys(trans, root, path, &disk_key, 1);
278431840ae1SZheng Yan }
278531840ae1SZheng Yan 
278631840ae1SZheng Yan /*
278774123bd7SChris Mason  * try to push data from one node into the next node left in the
278879f95c82SChris Mason  * tree.
2789aa5d6bedSChris Mason  *
2790aa5d6bedSChris Mason  * returns 0 if some ptrs were pushed left, < 0 if there was some horrible
2791aa5d6bedSChris Mason  * error, and > 0 if there was no room in the left hand block.
279274123bd7SChris Mason  */
279398ed5174SChris Mason static int push_node_left(struct btrfs_trans_handle *trans,
279498ed5174SChris Mason 			  struct btrfs_root *root, struct extent_buffer *dst,
2795971a1f66SChris Mason 			  struct extent_buffer *src, int empty)
2796be0e5c09SChris Mason {
2797be0e5c09SChris Mason 	int push_items = 0;
2798bb803951SChris Mason 	int src_nritems;
2799bb803951SChris Mason 	int dst_nritems;
2800aa5d6bedSChris Mason 	int ret = 0;
2801be0e5c09SChris Mason 
28025f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
28035f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
2804123abc88SChris Mason 	push_items = BTRFS_NODEPTRS_PER_BLOCK(root) - dst_nritems;
28057bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
28067bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
280754aa1f4dSChris Mason 
2808bce4eae9SChris Mason 	if (!empty && src_nritems <= 8)
2809971a1f66SChris Mason 		return 1;
2810971a1f66SChris Mason 
2811d397712bSChris Mason 	if (push_items <= 0)
2812be0e5c09SChris Mason 		return 1;
2813be0e5c09SChris Mason 
2814bce4eae9SChris Mason 	if (empty) {
2815971a1f66SChris Mason 		push_items = min(src_nritems, push_items);
2816bce4eae9SChris Mason 		if (push_items < src_nritems) {
2817bce4eae9SChris Mason 			/* leave at least 8 pointers in the node if
2818bce4eae9SChris Mason 			 * we aren't going to empty it
2819bce4eae9SChris Mason 			 */
2820bce4eae9SChris Mason 			if (src_nritems - push_items < 8) {
2821bce4eae9SChris Mason 				if (push_items <= 8)
2822bce4eae9SChris Mason 					return 1;
2823bce4eae9SChris Mason 				push_items -= 8;
2824bce4eae9SChris Mason 			}
2825bce4eae9SChris Mason 		}
2826bce4eae9SChris Mason 	} else
2827bce4eae9SChris Mason 		push_items = min(src_nritems - 8, push_items);
282879f95c82SChris Mason 
2829f230475eSJan Schmidt 	tree_mod_log_eb_copy(root->fs_info, dst, src, dst_nritems, 0,
2830f230475eSJan Schmidt 			     push_items);
28315f39d397SChris Mason 	copy_extent_buffer(dst, src,
28325f39d397SChris Mason 			   btrfs_node_key_ptr_offset(dst_nritems),
28335f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
2834123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
28355f39d397SChris Mason 
2836bb803951SChris Mason 	if (push_items < src_nritems) {
2837f230475eSJan Schmidt 		tree_mod_log_eb_move(root->fs_info, src, 0, push_items,
2838f230475eSJan Schmidt 				     src_nritems - push_items);
28395f39d397SChris Mason 		memmove_extent_buffer(src, btrfs_node_key_ptr_offset(0),
28405f39d397SChris Mason 				      btrfs_node_key_ptr_offset(push_items),
2841e2fa7227SChris Mason 				      (src_nritems - push_items) *
2842123abc88SChris Mason 				      sizeof(struct btrfs_key_ptr));
2843bb803951SChris Mason 	}
28445f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
28455f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
28465f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
28475f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
284831840ae1SZheng Yan 
2849bb803951SChris Mason 	return ret;
2850be0e5c09SChris Mason }
2851be0e5c09SChris Mason 
285297571fd0SChris Mason /*
285379f95c82SChris Mason  * try to push data from one node into the next node right in the
285479f95c82SChris Mason  * tree.
285579f95c82SChris Mason  *
285679f95c82SChris Mason  * returns 0 if some ptrs were pushed, < 0 if there was some horrible
285779f95c82SChris Mason  * error, and > 0 if there was no room in the right hand block.
285879f95c82SChris Mason  *
285979f95c82SChris Mason  * this will  only push up to 1/2 the contents of the left node over
286079f95c82SChris Mason  */
28615f39d397SChris Mason static int balance_node_right(struct btrfs_trans_handle *trans,
28625f39d397SChris Mason 			      struct btrfs_root *root,
28635f39d397SChris Mason 			      struct extent_buffer *dst,
28645f39d397SChris Mason 			      struct extent_buffer *src)
286579f95c82SChris Mason {
286679f95c82SChris Mason 	int push_items = 0;
286779f95c82SChris Mason 	int max_push;
286879f95c82SChris Mason 	int src_nritems;
286979f95c82SChris Mason 	int dst_nritems;
287079f95c82SChris Mason 	int ret = 0;
287179f95c82SChris Mason 
28727bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
28737bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
28747bb86316SChris Mason 
28755f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
28765f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
2877123abc88SChris Mason 	push_items = BTRFS_NODEPTRS_PER_BLOCK(root) - dst_nritems;
2878d397712bSChris Mason 	if (push_items <= 0)
287979f95c82SChris Mason 		return 1;
2880bce4eae9SChris Mason 
2881d397712bSChris Mason 	if (src_nritems < 4)
2882bce4eae9SChris Mason 		return 1;
288379f95c82SChris Mason 
288479f95c82SChris Mason 	max_push = src_nritems / 2 + 1;
288579f95c82SChris Mason 	/* don't try to empty the node */
2886d397712bSChris Mason 	if (max_push >= src_nritems)
288779f95c82SChris Mason 		return 1;
2888252c38f0SYan 
288979f95c82SChris Mason 	if (max_push < push_items)
289079f95c82SChris Mason 		push_items = max_push;
289179f95c82SChris Mason 
2892f230475eSJan Schmidt 	tree_mod_log_eb_move(root->fs_info, dst, push_items, 0, dst_nritems);
28935f39d397SChris Mason 	memmove_extent_buffer(dst, btrfs_node_key_ptr_offset(push_items),
28945f39d397SChris Mason 				      btrfs_node_key_ptr_offset(0),
28955f39d397SChris Mason 				      (dst_nritems) *
28965f39d397SChris Mason 				      sizeof(struct btrfs_key_ptr));
2897d6025579SChris Mason 
2898f230475eSJan Schmidt 	tree_mod_log_eb_copy(root->fs_info, dst, src, 0,
2899f230475eSJan Schmidt 			     src_nritems - push_items, push_items);
29005f39d397SChris Mason 	copy_extent_buffer(dst, src,
29015f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
29025f39d397SChris Mason 			   btrfs_node_key_ptr_offset(src_nritems - push_items),
2903123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
290479f95c82SChris Mason 
29055f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
29065f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
290779f95c82SChris Mason 
29085f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
29095f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
291031840ae1SZheng Yan 
291179f95c82SChris Mason 	return ret;
291279f95c82SChris Mason }
291379f95c82SChris Mason 
291479f95c82SChris Mason /*
291597571fd0SChris Mason  * helper function to insert a new root level in the tree.
291697571fd0SChris Mason  * A new node is allocated, and a single item is inserted to
291797571fd0SChris Mason  * point to the existing root
2918aa5d6bedSChris Mason  *
2919aa5d6bedSChris Mason  * returns zero on success or < 0 on failure.
292097571fd0SChris Mason  */
2921d397712bSChris Mason static noinline int insert_new_root(struct btrfs_trans_handle *trans,
29225f39d397SChris Mason 			   struct btrfs_root *root,
29235f39d397SChris Mason 			   struct btrfs_path *path, int level)
292474123bd7SChris Mason {
29257bb86316SChris Mason 	u64 lower_gen;
29265f39d397SChris Mason 	struct extent_buffer *lower;
29275f39d397SChris Mason 	struct extent_buffer *c;
2928925baeddSChris Mason 	struct extent_buffer *old;
29295f39d397SChris Mason 	struct btrfs_disk_key lower_key;
29305c680ed6SChris Mason 
29315c680ed6SChris Mason 	BUG_ON(path->nodes[level]);
29325c680ed6SChris Mason 	BUG_ON(path->nodes[level-1] != root->node);
29335c680ed6SChris Mason 
29347bb86316SChris Mason 	lower = path->nodes[level-1];
29357bb86316SChris Mason 	if (level == 1)
29367bb86316SChris Mason 		btrfs_item_key(lower, &lower_key, 0);
29377bb86316SChris Mason 	else
29387bb86316SChris Mason 		btrfs_node_key(lower, &lower_key, 0);
29397bb86316SChris Mason 
294031840ae1SZheng Yan 	c = btrfs_alloc_free_block(trans, root, root->nodesize, 0,
29415d4f98a2SYan Zheng 				   root->root_key.objectid, &lower_key,
29425581a51aSJan Schmidt 				   level, root->node->start, 0);
29435f39d397SChris Mason 	if (IS_ERR(c))
29445f39d397SChris Mason 		return PTR_ERR(c);
2945925baeddSChris Mason 
2946f0486c68SYan, Zheng 	root_add_used(root, root->nodesize);
2947f0486c68SYan, Zheng 
29485d4f98a2SYan Zheng 	memset_extent_buffer(c, 0, 0, sizeof(struct btrfs_header));
29495f39d397SChris Mason 	btrfs_set_header_nritems(c, 1);
29505f39d397SChris Mason 	btrfs_set_header_level(c, level);
2951db94535dSChris Mason 	btrfs_set_header_bytenr(c, c->start);
29525f39d397SChris Mason 	btrfs_set_header_generation(c, trans->transid);
29535d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(c, BTRFS_MIXED_BACKREF_REV);
29545f39d397SChris Mason 	btrfs_set_header_owner(c, root->root_key.objectid);
2955d5719762SChris Mason 
29565f39d397SChris Mason 	write_extent_buffer(c, root->fs_info->fsid,
29575f39d397SChris Mason 			    (unsigned long)btrfs_header_fsid(c),
29585f39d397SChris Mason 			    BTRFS_FSID_SIZE);
2959e17cade2SChris Mason 
2960e17cade2SChris Mason 	write_extent_buffer(c, root->fs_info->chunk_tree_uuid,
2961e17cade2SChris Mason 			    (unsigned long)btrfs_header_chunk_tree_uuid(c),
2962e17cade2SChris Mason 			    BTRFS_UUID_SIZE);
2963e17cade2SChris Mason 
29645f39d397SChris Mason 	btrfs_set_node_key(c, &lower_key, 0);
2965db94535dSChris Mason 	btrfs_set_node_blockptr(c, 0, lower->start);
29667bb86316SChris Mason 	lower_gen = btrfs_header_generation(lower);
296731840ae1SZheng Yan 	WARN_ON(lower_gen != trans->transid);
29687bb86316SChris Mason 
29697bb86316SChris Mason 	btrfs_set_node_ptr_generation(c, 0, lower_gen);
29705f39d397SChris Mason 
29715f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
2972d5719762SChris Mason 
2973925baeddSChris Mason 	old = root->node;
2974f230475eSJan Schmidt 	tree_mod_log_set_root_pointer(root, c);
2975240f62c8SChris Mason 	rcu_assign_pointer(root->node, c);
2976925baeddSChris Mason 
2977925baeddSChris Mason 	/* the super has an extra ref to root->node */
2978925baeddSChris Mason 	free_extent_buffer(old);
2979925baeddSChris Mason 
29800b86a832SChris Mason 	add_root_to_dirty_list(root);
29815f39d397SChris Mason 	extent_buffer_get(c);
29825f39d397SChris Mason 	path->nodes[level] = c;
2983bd681513SChris Mason 	path->locks[level] = BTRFS_WRITE_LOCK;
298474123bd7SChris Mason 	path->slots[level] = 0;
298574123bd7SChris Mason 	return 0;
298674123bd7SChris Mason }
29875c680ed6SChris Mason 
29885c680ed6SChris Mason /*
29895c680ed6SChris Mason  * worker function to insert a single pointer in a node.
29905c680ed6SChris Mason  * the node should have enough room for the pointer already
299197571fd0SChris Mason  *
29925c680ed6SChris Mason  * slot and level indicate where you want the key to go, and
29935c680ed6SChris Mason  * blocknr is the block the key points to.
29945c680ed6SChris Mason  */
2995143bede5SJeff Mahoney static void insert_ptr(struct btrfs_trans_handle *trans,
2996143bede5SJeff Mahoney 		       struct btrfs_root *root, struct btrfs_path *path,
2997143bede5SJeff Mahoney 		       struct btrfs_disk_key *key, u64 bytenr,
2998f3ea38daSJan Schmidt 		       int slot, int level, int tree_mod_log)
29995c680ed6SChris Mason {
30005f39d397SChris Mason 	struct extent_buffer *lower;
30015c680ed6SChris Mason 	int nritems;
3002f3ea38daSJan Schmidt 	int ret;
30035c680ed6SChris Mason 
30045c680ed6SChris Mason 	BUG_ON(!path->nodes[level]);
3005f0486c68SYan, Zheng 	btrfs_assert_tree_locked(path->nodes[level]);
30065f39d397SChris Mason 	lower = path->nodes[level];
30075f39d397SChris Mason 	nritems = btrfs_header_nritems(lower);
3008c293498bSStoyan Gaydarov 	BUG_ON(slot > nritems);
3009143bede5SJeff Mahoney 	BUG_ON(nritems == BTRFS_NODEPTRS_PER_BLOCK(root));
301074123bd7SChris Mason 	if (slot != nritems) {
3011f3ea38daSJan Schmidt 		if (tree_mod_log && level)
3012f3ea38daSJan Schmidt 			tree_mod_log_eb_move(root->fs_info, lower, slot + 1,
3013f3ea38daSJan Schmidt 					     slot, nritems - slot);
30145f39d397SChris Mason 		memmove_extent_buffer(lower,
30155f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot + 1),
30165f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot),
3017123abc88SChris Mason 			      (nritems - slot) * sizeof(struct btrfs_key_ptr));
301874123bd7SChris Mason 	}
3019f3ea38daSJan Schmidt 	if (tree_mod_log && level) {
3020f3ea38daSJan Schmidt 		ret = tree_mod_log_insert_key(root->fs_info, lower, slot,
3021f3ea38daSJan Schmidt 					      MOD_LOG_KEY_ADD);
3022f3ea38daSJan Schmidt 		BUG_ON(ret < 0);
3023f3ea38daSJan Schmidt 	}
30245f39d397SChris Mason 	btrfs_set_node_key(lower, key, slot);
3025db94535dSChris Mason 	btrfs_set_node_blockptr(lower, slot, bytenr);
302674493f7aSChris Mason 	WARN_ON(trans->transid == 0);
302774493f7aSChris Mason 	btrfs_set_node_ptr_generation(lower, slot, trans->transid);
30285f39d397SChris Mason 	btrfs_set_header_nritems(lower, nritems + 1);
30295f39d397SChris Mason 	btrfs_mark_buffer_dirty(lower);
303074123bd7SChris Mason }
303174123bd7SChris Mason 
303297571fd0SChris Mason /*
303397571fd0SChris Mason  * split the node at the specified level in path in two.
303497571fd0SChris Mason  * The path is corrected to point to the appropriate node after the split
303597571fd0SChris Mason  *
303697571fd0SChris Mason  * Before splitting this tries to make some room in the node by pushing
303797571fd0SChris Mason  * left and right, if either one works, it returns right away.
3038aa5d6bedSChris Mason  *
3039aa5d6bedSChris Mason  * returns 0 on success and < 0 on failure
304097571fd0SChris Mason  */
3041e02119d5SChris Mason static noinline int split_node(struct btrfs_trans_handle *trans,
3042e02119d5SChris Mason 			       struct btrfs_root *root,
3043e02119d5SChris Mason 			       struct btrfs_path *path, int level)
3044be0e5c09SChris Mason {
30455f39d397SChris Mason 	struct extent_buffer *c;
30465f39d397SChris Mason 	struct extent_buffer *split;
30475f39d397SChris Mason 	struct btrfs_disk_key disk_key;
3048be0e5c09SChris Mason 	int mid;
30495c680ed6SChris Mason 	int ret;
30507518a238SChris Mason 	u32 c_nritems;
3051be0e5c09SChris Mason 
30525f39d397SChris Mason 	c = path->nodes[level];
30537bb86316SChris Mason 	WARN_ON(btrfs_header_generation(c) != trans->transid);
30545f39d397SChris Mason 	if (c == root->node) {
30555c680ed6SChris Mason 		/* trying to split the root, lets make a new one */
3056e089f05cSChris Mason 		ret = insert_new_root(trans, root, path, level + 1);
30575c680ed6SChris Mason 		if (ret)
30585c680ed6SChris Mason 			return ret;
3059b3612421SChris Mason 	} else {
3060e66f709bSChris Mason 		ret = push_nodes_for_insert(trans, root, path, level);
30615f39d397SChris Mason 		c = path->nodes[level];
30625f39d397SChris Mason 		if (!ret && btrfs_header_nritems(c) <
3063c448acf0SChris Mason 		    BTRFS_NODEPTRS_PER_BLOCK(root) - 3)
3064e66f709bSChris Mason 			return 0;
306554aa1f4dSChris Mason 		if (ret < 0)
306654aa1f4dSChris Mason 			return ret;
30675c680ed6SChris Mason 	}
3068e66f709bSChris Mason 
30695f39d397SChris Mason 	c_nritems = btrfs_header_nritems(c);
30705d4f98a2SYan Zheng 	mid = (c_nritems + 1) / 2;
30715d4f98a2SYan Zheng 	btrfs_node_key(c, &disk_key, mid);
30727bb86316SChris Mason 
30735d4f98a2SYan Zheng 	split = btrfs_alloc_free_block(trans, root, root->nodesize, 0,
30747bb86316SChris Mason 					root->root_key.objectid,
30755581a51aSJan Schmidt 					&disk_key, level, c->start, 0);
30765f39d397SChris Mason 	if (IS_ERR(split))
30775f39d397SChris Mason 		return PTR_ERR(split);
307854aa1f4dSChris Mason 
3079f0486c68SYan, Zheng 	root_add_used(root, root->nodesize);
3080f0486c68SYan, Zheng 
30815d4f98a2SYan Zheng 	memset_extent_buffer(split, 0, 0, sizeof(struct btrfs_header));
30825f39d397SChris Mason 	btrfs_set_header_level(split, btrfs_header_level(c));
3083db94535dSChris Mason 	btrfs_set_header_bytenr(split, split->start);
30845f39d397SChris Mason 	btrfs_set_header_generation(split, trans->transid);
30855d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(split, BTRFS_MIXED_BACKREF_REV);
30865f39d397SChris Mason 	btrfs_set_header_owner(split, root->root_key.objectid);
30875f39d397SChris Mason 	write_extent_buffer(split, root->fs_info->fsid,
30885f39d397SChris Mason 			    (unsigned long)btrfs_header_fsid(split),
30895f39d397SChris Mason 			    BTRFS_FSID_SIZE);
3090e17cade2SChris Mason 	write_extent_buffer(split, root->fs_info->chunk_tree_uuid,
3091e17cade2SChris Mason 			    (unsigned long)btrfs_header_chunk_tree_uuid(split),
3092e17cade2SChris Mason 			    BTRFS_UUID_SIZE);
30935f39d397SChris Mason 
3094f230475eSJan Schmidt 	tree_mod_log_eb_copy(root->fs_info, split, c, 0, mid, c_nritems - mid);
30955f39d397SChris Mason 	copy_extent_buffer(split, c,
30965f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
30975f39d397SChris Mason 			   btrfs_node_key_ptr_offset(mid),
3098123abc88SChris Mason 			   (c_nritems - mid) * sizeof(struct btrfs_key_ptr));
30995f39d397SChris Mason 	btrfs_set_header_nritems(split, c_nritems - mid);
31005f39d397SChris Mason 	btrfs_set_header_nritems(c, mid);
3101aa5d6bedSChris Mason 	ret = 0;
3102aa5d6bedSChris Mason 
31035f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
31045f39d397SChris Mason 	btrfs_mark_buffer_dirty(split);
31055f39d397SChris Mason 
3106143bede5SJeff Mahoney 	insert_ptr(trans, root, path, &disk_key, split->start,
3107f3ea38daSJan Schmidt 		   path->slots[level + 1] + 1, level + 1, 1);
3108aa5d6bedSChris Mason 
31095de08d7dSChris Mason 	if (path->slots[level] >= mid) {
31105c680ed6SChris Mason 		path->slots[level] -= mid;
3111925baeddSChris Mason 		btrfs_tree_unlock(c);
31125f39d397SChris Mason 		free_extent_buffer(c);
31135f39d397SChris Mason 		path->nodes[level] = split;
31145c680ed6SChris Mason 		path->slots[level + 1] += 1;
3115eb60ceacSChris Mason 	} else {
3116925baeddSChris Mason 		btrfs_tree_unlock(split);
31175f39d397SChris Mason 		free_extent_buffer(split);
3118be0e5c09SChris Mason 	}
3119aa5d6bedSChris Mason 	return ret;
3120be0e5c09SChris Mason }
3121be0e5c09SChris Mason 
312274123bd7SChris Mason /*
312374123bd7SChris Mason  * how many bytes are required to store the items in a leaf.  start
312474123bd7SChris Mason  * and nr indicate which items in the leaf to check.  This totals up the
312574123bd7SChris Mason  * space used both by the item structs and the item data
312674123bd7SChris Mason  */
31275f39d397SChris Mason static int leaf_space_used(struct extent_buffer *l, int start, int nr)
3128be0e5c09SChris Mason {
3129be0e5c09SChris Mason 	int data_len;
31305f39d397SChris Mason 	int nritems = btrfs_header_nritems(l);
3131d4dbff95SChris Mason 	int end = min(nritems, start + nr) - 1;
3132be0e5c09SChris Mason 
3133be0e5c09SChris Mason 	if (!nr)
3134be0e5c09SChris Mason 		return 0;
31355f39d397SChris Mason 	data_len = btrfs_item_end_nr(l, start);
31365f39d397SChris Mason 	data_len = data_len - btrfs_item_offset_nr(l, end);
31370783fcfcSChris Mason 	data_len += sizeof(struct btrfs_item) * nr;
3138d4dbff95SChris Mason 	WARN_ON(data_len < 0);
3139be0e5c09SChris Mason 	return data_len;
3140be0e5c09SChris Mason }
3141be0e5c09SChris Mason 
314274123bd7SChris Mason /*
3143d4dbff95SChris Mason  * The space between the end of the leaf items and
3144d4dbff95SChris Mason  * the start of the leaf data.  IOW, how much room
3145d4dbff95SChris Mason  * the leaf has left for both items and data
3146d4dbff95SChris Mason  */
3147d397712bSChris Mason noinline int btrfs_leaf_free_space(struct btrfs_root *root,
3148e02119d5SChris Mason 				   struct extent_buffer *leaf)
3149d4dbff95SChris Mason {
31505f39d397SChris Mason 	int nritems = btrfs_header_nritems(leaf);
31515f39d397SChris Mason 	int ret;
31525f39d397SChris Mason 	ret = BTRFS_LEAF_DATA_SIZE(root) - leaf_space_used(leaf, 0, nritems);
31535f39d397SChris Mason 	if (ret < 0) {
3154d397712bSChris Mason 		printk(KERN_CRIT "leaf free space ret %d, leaf data size %lu, "
3155d397712bSChris Mason 		       "used %d nritems %d\n",
3156ae2f5411SJens Axboe 		       ret, (unsigned long) BTRFS_LEAF_DATA_SIZE(root),
31575f39d397SChris Mason 		       leaf_space_used(leaf, 0, nritems), nritems);
31585f39d397SChris Mason 	}
31595f39d397SChris Mason 	return ret;
3160d4dbff95SChris Mason }
3161d4dbff95SChris Mason 
316299d8f83cSChris Mason /*
316399d8f83cSChris Mason  * min slot controls the lowest index we're willing to push to the
316499d8f83cSChris Mason  * right.  We'll push up to and including min_slot, but no lower
316599d8f83cSChris Mason  */
316644871b1bSChris Mason static noinline int __push_leaf_right(struct btrfs_trans_handle *trans,
316744871b1bSChris Mason 				      struct btrfs_root *root,
316844871b1bSChris Mason 				      struct btrfs_path *path,
316944871b1bSChris Mason 				      int data_size, int empty,
317044871b1bSChris Mason 				      struct extent_buffer *right,
317199d8f83cSChris Mason 				      int free_space, u32 left_nritems,
317299d8f83cSChris Mason 				      u32 min_slot)
317300ec4c51SChris Mason {
31745f39d397SChris Mason 	struct extent_buffer *left = path->nodes[0];
317544871b1bSChris Mason 	struct extent_buffer *upper = path->nodes[1];
3176cfed81a0SChris Mason 	struct btrfs_map_token token;
31775f39d397SChris Mason 	struct btrfs_disk_key disk_key;
317800ec4c51SChris Mason 	int slot;
317934a38218SChris Mason 	u32 i;
318000ec4c51SChris Mason 	int push_space = 0;
318100ec4c51SChris Mason 	int push_items = 0;
31820783fcfcSChris Mason 	struct btrfs_item *item;
318334a38218SChris Mason 	u32 nr;
31847518a238SChris Mason 	u32 right_nritems;
31855f39d397SChris Mason 	u32 data_end;
3186db94535dSChris Mason 	u32 this_item_size;
318700ec4c51SChris Mason 
3188cfed81a0SChris Mason 	btrfs_init_map_token(&token);
3189cfed81a0SChris Mason 
319034a38218SChris Mason 	if (empty)
319134a38218SChris Mason 		nr = 0;
319234a38218SChris Mason 	else
319399d8f83cSChris Mason 		nr = max_t(u32, 1, min_slot);
319434a38218SChris Mason 
319531840ae1SZheng Yan 	if (path->slots[0] >= left_nritems)
319687b29b20SYan Zheng 		push_space += data_size;
319731840ae1SZheng Yan 
319844871b1bSChris Mason 	slot = path->slots[1];
319934a38218SChris Mason 	i = left_nritems - 1;
320034a38218SChris Mason 	while (i >= nr) {
32015f39d397SChris Mason 		item = btrfs_item_nr(left, i);
3202db94535dSChris Mason 
320331840ae1SZheng Yan 		if (!empty && push_items > 0) {
320431840ae1SZheng Yan 			if (path->slots[0] > i)
320531840ae1SZheng Yan 				break;
320631840ae1SZheng Yan 			if (path->slots[0] == i) {
320731840ae1SZheng Yan 				int space = btrfs_leaf_free_space(root, left);
320831840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
320931840ae1SZheng Yan 					break;
321031840ae1SZheng Yan 			}
321131840ae1SZheng Yan 		}
321231840ae1SZheng Yan 
321300ec4c51SChris Mason 		if (path->slots[0] == i)
321487b29b20SYan Zheng 			push_space += data_size;
3215db94535dSChris Mason 
3216db94535dSChris Mason 		this_item_size = btrfs_item_size(left, item);
3217db94535dSChris Mason 		if (this_item_size + sizeof(*item) + push_space > free_space)
321800ec4c51SChris Mason 			break;
321931840ae1SZheng Yan 
322000ec4c51SChris Mason 		push_items++;
3221db94535dSChris Mason 		push_space += this_item_size + sizeof(*item);
322234a38218SChris Mason 		if (i == 0)
322334a38218SChris Mason 			break;
322434a38218SChris Mason 		i--;
3225db94535dSChris Mason 	}
32265f39d397SChris Mason 
3227925baeddSChris Mason 	if (push_items == 0)
3228925baeddSChris Mason 		goto out_unlock;
32295f39d397SChris Mason 
323034a38218SChris Mason 	if (!empty && push_items == left_nritems)
3231a429e513SChris Mason 		WARN_ON(1);
32325f39d397SChris Mason 
323300ec4c51SChris Mason 	/* push left to right */
32345f39d397SChris Mason 	right_nritems = btrfs_header_nritems(right);
323534a38218SChris Mason 
32365f39d397SChris Mason 	push_space = btrfs_item_end_nr(left, left_nritems - push_items);
3237123abc88SChris Mason 	push_space -= leaf_data_end(root, left);
32385f39d397SChris Mason 
323900ec4c51SChris Mason 	/* make room in the right data area */
32405f39d397SChris Mason 	data_end = leaf_data_end(root, right);
32415f39d397SChris Mason 	memmove_extent_buffer(right,
32425f39d397SChris Mason 			      btrfs_leaf_data(right) + data_end - push_space,
32435f39d397SChris Mason 			      btrfs_leaf_data(right) + data_end,
32445f39d397SChris Mason 			      BTRFS_LEAF_DATA_SIZE(root) - data_end);
32455f39d397SChris Mason 
324600ec4c51SChris Mason 	/* copy from the left data area */
32475f39d397SChris Mason 	copy_extent_buffer(right, left, btrfs_leaf_data(right) +
3248d6025579SChris Mason 		     BTRFS_LEAF_DATA_SIZE(root) - push_space,
3249d6025579SChris Mason 		     btrfs_leaf_data(left) + leaf_data_end(root, left),
3250d6025579SChris Mason 		     push_space);
32515f39d397SChris Mason 
32525f39d397SChris Mason 	memmove_extent_buffer(right, btrfs_item_nr_offset(push_items),
32535f39d397SChris Mason 			      btrfs_item_nr_offset(0),
32540783fcfcSChris Mason 			      right_nritems * sizeof(struct btrfs_item));
32555f39d397SChris Mason 
325600ec4c51SChris Mason 	/* copy the items from left to right */
32575f39d397SChris Mason 	copy_extent_buffer(right, left, btrfs_item_nr_offset(0),
32585f39d397SChris Mason 		   btrfs_item_nr_offset(left_nritems - push_items),
32590783fcfcSChris Mason 		   push_items * sizeof(struct btrfs_item));
326000ec4c51SChris Mason 
326100ec4c51SChris Mason 	/* update the item pointers */
32627518a238SChris Mason 	right_nritems += push_items;
32635f39d397SChris Mason 	btrfs_set_header_nritems(right, right_nritems);
3264123abc88SChris Mason 	push_space = BTRFS_LEAF_DATA_SIZE(root);
32657518a238SChris Mason 	for (i = 0; i < right_nritems; i++) {
32665f39d397SChris Mason 		item = btrfs_item_nr(right, i);
3267cfed81a0SChris Mason 		push_space -= btrfs_token_item_size(right, item, &token);
3268cfed81a0SChris Mason 		btrfs_set_token_item_offset(right, item, push_space, &token);
3269db94535dSChris Mason 	}
3270db94535dSChris Mason 
32717518a238SChris Mason 	left_nritems -= push_items;
32725f39d397SChris Mason 	btrfs_set_header_nritems(left, left_nritems);
327300ec4c51SChris Mason 
327434a38218SChris Mason 	if (left_nritems)
32755f39d397SChris Mason 		btrfs_mark_buffer_dirty(left);
3276f0486c68SYan, Zheng 	else
3277f0486c68SYan, Zheng 		clean_tree_block(trans, root, left);
3278f0486c68SYan, Zheng 
32795f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
3280a429e513SChris Mason 
32815f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
32825f39d397SChris Mason 	btrfs_set_node_key(upper, &disk_key, slot + 1);
3283d6025579SChris Mason 	btrfs_mark_buffer_dirty(upper);
328402217ed2SChris Mason 
328500ec4c51SChris Mason 	/* then fixup the leaf pointer in the path */
32867518a238SChris Mason 	if (path->slots[0] >= left_nritems) {
32877518a238SChris Mason 		path->slots[0] -= left_nritems;
3288925baeddSChris Mason 		if (btrfs_header_nritems(path->nodes[0]) == 0)
3289925baeddSChris Mason 			clean_tree_block(trans, root, path->nodes[0]);
3290925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
32915f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
32925f39d397SChris Mason 		path->nodes[0] = right;
329300ec4c51SChris Mason 		path->slots[1] += 1;
329400ec4c51SChris Mason 	} else {
3295925baeddSChris Mason 		btrfs_tree_unlock(right);
32965f39d397SChris Mason 		free_extent_buffer(right);
329700ec4c51SChris Mason 	}
329800ec4c51SChris Mason 	return 0;
3299925baeddSChris Mason 
3300925baeddSChris Mason out_unlock:
3301925baeddSChris Mason 	btrfs_tree_unlock(right);
3302925baeddSChris Mason 	free_extent_buffer(right);
3303925baeddSChris Mason 	return 1;
330400ec4c51SChris Mason }
3305925baeddSChris Mason 
330600ec4c51SChris Mason /*
330744871b1bSChris Mason  * push some data in the path leaf to the right, trying to free up at
330874123bd7SChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
330944871b1bSChris Mason  *
331044871b1bSChris Mason  * returns 1 if the push failed because the other node didn't have enough
331144871b1bSChris Mason  * room, 0 if everything worked out and < 0 if there were major errors.
331299d8f83cSChris Mason  *
331399d8f83cSChris Mason  * this will push starting from min_slot to the end of the leaf.  It won't
331499d8f83cSChris Mason  * push any slot lower than min_slot
331574123bd7SChris Mason  */
331644871b1bSChris Mason static int push_leaf_right(struct btrfs_trans_handle *trans, struct btrfs_root
331799d8f83cSChris Mason 			   *root, struct btrfs_path *path,
331899d8f83cSChris Mason 			   int min_data_size, int data_size,
331999d8f83cSChris Mason 			   int empty, u32 min_slot)
3320be0e5c09SChris Mason {
332144871b1bSChris Mason 	struct extent_buffer *left = path->nodes[0];
332244871b1bSChris Mason 	struct extent_buffer *right;
332344871b1bSChris Mason 	struct extent_buffer *upper;
332444871b1bSChris Mason 	int slot;
332544871b1bSChris Mason 	int free_space;
332644871b1bSChris Mason 	u32 left_nritems;
332744871b1bSChris Mason 	int ret;
332844871b1bSChris Mason 
332944871b1bSChris Mason 	if (!path->nodes[1])
333044871b1bSChris Mason 		return 1;
333144871b1bSChris Mason 
333244871b1bSChris Mason 	slot = path->slots[1];
333344871b1bSChris Mason 	upper = path->nodes[1];
333444871b1bSChris Mason 	if (slot >= btrfs_header_nritems(upper) - 1)
333544871b1bSChris Mason 		return 1;
333644871b1bSChris Mason 
333744871b1bSChris Mason 	btrfs_assert_tree_locked(path->nodes[1]);
333844871b1bSChris Mason 
333944871b1bSChris Mason 	right = read_node_slot(root, upper, slot + 1);
334091ca338dSTsutomu Itoh 	if (right == NULL)
334191ca338dSTsutomu Itoh 		return 1;
334291ca338dSTsutomu Itoh 
334344871b1bSChris Mason 	btrfs_tree_lock(right);
334444871b1bSChris Mason 	btrfs_set_lock_blocking(right);
334544871b1bSChris Mason 
334644871b1bSChris Mason 	free_space = btrfs_leaf_free_space(root, right);
334744871b1bSChris Mason 	if (free_space < data_size)
334844871b1bSChris Mason 		goto out_unlock;
334944871b1bSChris Mason 
335044871b1bSChris Mason 	/* cow and double check */
335144871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, right, upper,
335244871b1bSChris Mason 			      slot + 1, &right);
335344871b1bSChris Mason 	if (ret)
335444871b1bSChris Mason 		goto out_unlock;
335544871b1bSChris Mason 
335644871b1bSChris Mason 	free_space = btrfs_leaf_free_space(root, right);
335744871b1bSChris Mason 	if (free_space < data_size)
335844871b1bSChris Mason 		goto out_unlock;
335944871b1bSChris Mason 
336044871b1bSChris Mason 	left_nritems = btrfs_header_nritems(left);
336144871b1bSChris Mason 	if (left_nritems == 0)
336244871b1bSChris Mason 		goto out_unlock;
336344871b1bSChris Mason 
336499d8f83cSChris Mason 	return __push_leaf_right(trans, root, path, min_data_size, empty,
336599d8f83cSChris Mason 				right, free_space, left_nritems, min_slot);
336644871b1bSChris Mason out_unlock:
336744871b1bSChris Mason 	btrfs_tree_unlock(right);
336844871b1bSChris Mason 	free_extent_buffer(right);
336944871b1bSChris Mason 	return 1;
337044871b1bSChris Mason }
337144871b1bSChris Mason 
337244871b1bSChris Mason /*
337344871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
337444871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
337599d8f83cSChris Mason  *
337699d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
337799d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us do all the
337899d8f83cSChris Mason  * items
337944871b1bSChris Mason  */
338044871b1bSChris Mason static noinline int __push_leaf_left(struct btrfs_trans_handle *trans,
338144871b1bSChris Mason 				     struct btrfs_root *root,
338244871b1bSChris Mason 				     struct btrfs_path *path, int data_size,
338344871b1bSChris Mason 				     int empty, struct extent_buffer *left,
338499d8f83cSChris Mason 				     int free_space, u32 right_nritems,
338599d8f83cSChris Mason 				     u32 max_slot)
338644871b1bSChris Mason {
33875f39d397SChris Mason 	struct btrfs_disk_key disk_key;
33885f39d397SChris Mason 	struct extent_buffer *right = path->nodes[0];
3389be0e5c09SChris Mason 	int i;
3390be0e5c09SChris Mason 	int push_space = 0;
3391be0e5c09SChris Mason 	int push_items = 0;
33920783fcfcSChris Mason 	struct btrfs_item *item;
33937518a238SChris Mason 	u32 old_left_nritems;
339434a38218SChris Mason 	u32 nr;
3395aa5d6bedSChris Mason 	int ret = 0;
3396db94535dSChris Mason 	u32 this_item_size;
3397db94535dSChris Mason 	u32 old_left_item_size;
3398cfed81a0SChris Mason 	struct btrfs_map_token token;
3399cfed81a0SChris Mason 
3400cfed81a0SChris Mason 	btrfs_init_map_token(&token);
3401be0e5c09SChris Mason 
340234a38218SChris Mason 	if (empty)
340399d8f83cSChris Mason 		nr = min(right_nritems, max_slot);
340434a38218SChris Mason 	else
340599d8f83cSChris Mason 		nr = min(right_nritems - 1, max_slot);
340634a38218SChris Mason 
340734a38218SChris Mason 	for (i = 0; i < nr; i++) {
34085f39d397SChris Mason 		item = btrfs_item_nr(right, i);
3409db94535dSChris Mason 
341031840ae1SZheng Yan 		if (!empty && push_items > 0) {
341131840ae1SZheng Yan 			if (path->slots[0] < i)
341231840ae1SZheng Yan 				break;
341331840ae1SZheng Yan 			if (path->slots[0] == i) {
341431840ae1SZheng Yan 				int space = btrfs_leaf_free_space(root, right);
341531840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
341631840ae1SZheng Yan 					break;
341731840ae1SZheng Yan 			}
341831840ae1SZheng Yan 		}
341931840ae1SZheng Yan 
3420be0e5c09SChris Mason 		if (path->slots[0] == i)
342187b29b20SYan Zheng 			push_space += data_size;
3422db94535dSChris Mason 
3423db94535dSChris Mason 		this_item_size = btrfs_item_size(right, item);
3424db94535dSChris Mason 		if (this_item_size + sizeof(*item) + push_space > free_space)
3425be0e5c09SChris Mason 			break;
3426db94535dSChris Mason 
3427be0e5c09SChris Mason 		push_items++;
3428db94535dSChris Mason 		push_space += this_item_size + sizeof(*item);
3429be0e5c09SChris Mason 	}
3430db94535dSChris Mason 
3431be0e5c09SChris Mason 	if (push_items == 0) {
3432925baeddSChris Mason 		ret = 1;
3433925baeddSChris Mason 		goto out;
3434be0e5c09SChris Mason 	}
343534a38218SChris Mason 	if (!empty && push_items == btrfs_header_nritems(right))
3436a429e513SChris Mason 		WARN_ON(1);
34375f39d397SChris Mason 
3438be0e5c09SChris Mason 	/* push data from right to left */
34395f39d397SChris Mason 	copy_extent_buffer(left, right,
34405f39d397SChris Mason 			   btrfs_item_nr_offset(btrfs_header_nritems(left)),
34415f39d397SChris Mason 			   btrfs_item_nr_offset(0),
34425f39d397SChris Mason 			   push_items * sizeof(struct btrfs_item));
34435f39d397SChris Mason 
3444123abc88SChris Mason 	push_space = BTRFS_LEAF_DATA_SIZE(root) -
34455f39d397SChris Mason 		     btrfs_item_offset_nr(right, push_items - 1);
34465f39d397SChris Mason 
34475f39d397SChris Mason 	copy_extent_buffer(left, right, btrfs_leaf_data(left) +
3448d6025579SChris Mason 		     leaf_data_end(root, left) - push_space,
3449123abc88SChris Mason 		     btrfs_leaf_data(right) +
34505f39d397SChris Mason 		     btrfs_item_offset_nr(right, push_items - 1),
3451be0e5c09SChris Mason 		     push_space);
34525f39d397SChris Mason 	old_left_nritems = btrfs_header_nritems(left);
345387b29b20SYan Zheng 	BUG_ON(old_left_nritems <= 0);
3454eb60ceacSChris Mason 
3455db94535dSChris Mason 	old_left_item_size = btrfs_item_offset_nr(left, old_left_nritems - 1);
3456be0e5c09SChris Mason 	for (i = old_left_nritems; i < old_left_nritems + push_items; i++) {
34575f39d397SChris Mason 		u32 ioff;
3458db94535dSChris Mason 
34595f39d397SChris Mason 		item = btrfs_item_nr(left, i);
3460db94535dSChris Mason 
3461cfed81a0SChris Mason 		ioff = btrfs_token_item_offset(left, item, &token);
3462cfed81a0SChris Mason 		btrfs_set_token_item_offset(left, item,
3463cfed81a0SChris Mason 		      ioff - (BTRFS_LEAF_DATA_SIZE(root) - old_left_item_size),
3464cfed81a0SChris Mason 		      &token);
3465be0e5c09SChris Mason 	}
34665f39d397SChris Mason 	btrfs_set_header_nritems(left, old_left_nritems + push_items);
3467be0e5c09SChris Mason 
3468be0e5c09SChris Mason 	/* fixup right node */
346934a38218SChris Mason 	if (push_items > right_nritems) {
3470d397712bSChris Mason 		printk(KERN_CRIT "push items %d nr %u\n", push_items,
3471d397712bSChris Mason 		       right_nritems);
347234a38218SChris Mason 		WARN_ON(1);
347334a38218SChris Mason 	}
347434a38218SChris Mason 
347534a38218SChris Mason 	if (push_items < right_nritems) {
34765f39d397SChris Mason 		push_space = btrfs_item_offset_nr(right, push_items - 1) -
3477123abc88SChris Mason 						  leaf_data_end(root, right);
34785f39d397SChris Mason 		memmove_extent_buffer(right, btrfs_leaf_data(right) +
3479d6025579SChris Mason 				      BTRFS_LEAF_DATA_SIZE(root) - push_space,
3480d6025579SChris Mason 				      btrfs_leaf_data(right) +
3481123abc88SChris Mason 				      leaf_data_end(root, right), push_space);
34825f39d397SChris Mason 
34835f39d397SChris Mason 		memmove_extent_buffer(right, btrfs_item_nr_offset(0),
34845f39d397SChris Mason 			      btrfs_item_nr_offset(push_items),
34855f39d397SChris Mason 			     (btrfs_header_nritems(right) - push_items) *
34860783fcfcSChris Mason 			     sizeof(struct btrfs_item));
348734a38218SChris Mason 	}
3488eef1c494SYan 	right_nritems -= push_items;
3489eef1c494SYan 	btrfs_set_header_nritems(right, right_nritems);
3490123abc88SChris Mason 	push_space = BTRFS_LEAF_DATA_SIZE(root);
34915f39d397SChris Mason 	for (i = 0; i < right_nritems; i++) {
34925f39d397SChris Mason 		item = btrfs_item_nr(right, i);
3493db94535dSChris Mason 
3494cfed81a0SChris Mason 		push_space = push_space - btrfs_token_item_size(right,
3495cfed81a0SChris Mason 								item, &token);
3496cfed81a0SChris Mason 		btrfs_set_token_item_offset(right, item, push_space, &token);
3497db94535dSChris Mason 	}
3498eb60ceacSChris Mason 
34995f39d397SChris Mason 	btrfs_mark_buffer_dirty(left);
350034a38218SChris Mason 	if (right_nritems)
35015f39d397SChris Mason 		btrfs_mark_buffer_dirty(right);
3502f0486c68SYan, Zheng 	else
3503f0486c68SYan, Zheng 		clean_tree_block(trans, root, right);
3504098f59c2SChris Mason 
35055f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
3506143bede5SJeff Mahoney 	fixup_low_keys(trans, root, path, &disk_key, 1);
3507be0e5c09SChris Mason 
3508be0e5c09SChris Mason 	/* then fixup the leaf pointer in the path */
3509be0e5c09SChris Mason 	if (path->slots[0] < push_items) {
3510be0e5c09SChris Mason 		path->slots[0] += old_left_nritems;
3511925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
35125f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
35135f39d397SChris Mason 		path->nodes[0] = left;
3514be0e5c09SChris Mason 		path->slots[1] -= 1;
3515be0e5c09SChris Mason 	} else {
3516925baeddSChris Mason 		btrfs_tree_unlock(left);
35175f39d397SChris Mason 		free_extent_buffer(left);
3518be0e5c09SChris Mason 		path->slots[0] -= push_items;
3519be0e5c09SChris Mason 	}
3520eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
3521aa5d6bedSChris Mason 	return ret;
3522925baeddSChris Mason out:
3523925baeddSChris Mason 	btrfs_tree_unlock(left);
3524925baeddSChris Mason 	free_extent_buffer(left);
3525925baeddSChris Mason 	return ret;
3526be0e5c09SChris Mason }
3527be0e5c09SChris Mason 
352874123bd7SChris Mason /*
352944871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
353044871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
353199d8f83cSChris Mason  *
353299d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
353399d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us push all the
353499d8f83cSChris Mason  * items
353544871b1bSChris Mason  */
353644871b1bSChris Mason static int push_leaf_left(struct btrfs_trans_handle *trans, struct btrfs_root
353799d8f83cSChris Mason 			  *root, struct btrfs_path *path, int min_data_size,
353899d8f83cSChris Mason 			  int data_size, int empty, u32 max_slot)
353944871b1bSChris Mason {
354044871b1bSChris Mason 	struct extent_buffer *right = path->nodes[0];
354144871b1bSChris Mason 	struct extent_buffer *left;
354244871b1bSChris Mason 	int slot;
354344871b1bSChris Mason 	int free_space;
354444871b1bSChris Mason 	u32 right_nritems;
354544871b1bSChris Mason 	int ret = 0;
354644871b1bSChris Mason 
354744871b1bSChris Mason 	slot = path->slots[1];
354844871b1bSChris Mason 	if (slot == 0)
354944871b1bSChris Mason 		return 1;
355044871b1bSChris Mason 	if (!path->nodes[1])
355144871b1bSChris Mason 		return 1;
355244871b1bSChris Mason 
355344871b1bSChris Mason 	right_nritems = btrfs_header_nritems(right);
355444871b1bSChris Mason 	if (right_nritems == 0)
355544871b1bSChris Mason 		return 1;
355644871b1bSChris Mason 
355744871b1bSChris Mason 	btrfs_assert_tree_locked(path->nodes[1]);
355844871b1bSChris Mason 
355944871b1bSChris Mason 	left = read_node_slot(root, path->nodes[1], slot - 1);
356091ca338dSTsutomu Itoh 	if (left == NULL)
356191ca338dSTsutomu Itoh 		return 1;
356291ca338dSTsutomu Itoh 
356344871b1bSChris Mason 	btrfs_tree_lock(left);
356444871b1bSChris Mason 	btrfs_set_lock_blocking(left);
356544871b1bSChris Mason 
356644871b1bSChris Mason 	free_space = btrfs_leaf_free_space(root, left);
356744871b1bSChris Mason 	if (free_space < data_size) {
356844871b1bSChris Mason 		ret = 1;
356944871b1bSChris Mason 		goto out;
357044871b1bSChris Mason 	}
357144871b1bSChris Mason 
357244871b1bSChris Mason 	/* cow and double check */
357344871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, left,
357444871b1bSChris Mason 			      path->nodes[1], slot - 1, &left);
357544871b1bSChris Mason 	if (ret) {
357644871b1bSChris Mason 		/* we hit -ENOSPC, but it isn't fatal here */
357779787eaaSJeff Mahoney 		if (ret == -ENOSPC)
357844871b1bSChris Mason 			ret = 1;
357944871b1bSChris Mason 		goto out;
358044871b1bSChris Mason 	}
358144871b1bSChris Mason 
358244871b1bSChris Mason 	free_space = btrfs_leaf_free_space(root, left);
358344871b1bSChris Mason 	if (free_space < data_size) {
358444871b1bSChris Mason 		ret = 1;
358544871b1bSChris Mason 		goto out;
358644871b1bSChris Mason 	}
358744871b1bSChris Mason 
358899d8f83cSChris Mason 	return __push_leaf_left(trans, root, path, min_data_size,
358999d8f83cSChris Mason 			       empty, left, free_space, right_nritems,
359099d8f83cSChris Mason 			       max_slot);
359144871b1bSChris Mason out:
359244871b1bSChris Mason 	btrfs_tree_unlock(left);
359344871b1bSChris Mason 	free_extent_buffer(left);
359444871b1bSChris Mason 	return ret;
359544871b1bSChris Mason }
359644871b1bSChris Mason 
359744871b1bSChris Mason /*
359874123bd7SChris Mason  * split the path's leaf in two, making sure there is at least data_size
359974123bd7SChris Mason  * available for the resulting leaf level of the path.
360074123bd7SChris Mason  */
3601143bede5SJeff Mahoney static noinline void copy_for_split(struct btrfs_trans_handle *trans,
3602e02119d5SChris Mason 				    struct btrfs_root *root,
360344871b1bSChris Mason 				    struct btrfs_path *path,
360444871b1bSChris Mason 				    struct extent_buffer *l,
360544871b1bSChris Mason 				    struct extent_buffer *right,
360644871b1bSChris Mason 				    int slot, int mid, int nritems)
3607be0e5c09SChris Mason {
3608be0e5c09SChris Mason 	int data_copy_size;
3609be0e5c09SChris Mason 	int rt_data_off;
3610be0e5c09SChris Mason 	int i;
3611d4dbff95SChris Mason 	struct btrfs_disk_key disk_key;
3612cfed81a0SChris Mason 	struct btrfs_map_token token;
3613cfed81a0SChris Mason 
3614cfed81a0SChris Mason 	btrfs_init_map_token(&token);
3615be0e5c09SChris Mason 
36165f39d397SChris Mason 	nritems = nritems - mid;
36175f39d397SChris Mason 	btrfs_set_header_nritems(right, nritems);
36185f39d397SChris Mason 	data_copy_size = btrfs_item_end_nr(l, mid) - leaf_data_end(root, l);
36195f39d397SChris Mason 
36205f39d397SChris Mason 	copy_extent_buffer(right, l, btrfs_item_nr_offset(0),
36215f39d397SChris Mason 			   btrfs_item_nr_offset(mid),
36225f39d397SChris Mason 			   nritems * sizeof(struct btrfs_item));
36235f39d397SChris Mason 
36245f39d397SChris Mason 	copy_extent_buffer(right, l,
3625d6025579SChris Mason 		     btrfs_leaf_data(right) + BTRFS_LEAF_DATA_SIZE(root) -
3626123abc88SChris Mason 		     data_copy_size, btrfs_leaf_data(l) +
3627123abc88SChris Mason 		     leaf_data_end(root, l), data_copy_size);
362874123bd7SChris Mason 
36295f39d397SChris Mason 	rt_data_off = BTRFS_LEAF_DATA_SIZE(root) -
36305f39d397SChris Mason 		      btrfs_item_end_nr(l, mid);
36315f39d397SChris Mason 
36325f39d397SChris Mason 	for (i = 0; i < nritems; i++) {
36335f39d397SChris Mason 		struct btrfs_item *item = btrfs_item_nr(right, i);
3634db94535dSChris Mason 		u32 ioff;
3635db94535dSChris Mason 
3636cfed81a0SChris Mason 		ioff = btrfs_token_item_offset(right, item, &token);
3637cfed81a0SChris Mason 		btrfs_set_token_item_offset(right, item,
3638cfed81a0SChris Mason 					    ioff + rt_data_off, &token);
36390783fcfcSChris Mason 	}
364074123bd7SChris Mason 
36415f39d397SChris Mason 	btrfs_set_header_nritems(l, mid);
36425f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
3643143bede5SJeff Mahoney 	insert_ptr(trans, root, path, &disk_key, right->start,
3644f3ea38daSJan Schmidt 		   path->slots[1] + 1, 1, 0);
36455f39d397SChris Mason 
36465f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
36475f39d397SChris Mason 	btrfs_mark_buffer_dirty(l);
3648eb60ceacSChris Mason 	BUG_ON(path->slots[0] != slot);
36495f39d397SChris Mason 
3650be0e5c09SChris Mason 	if (mid <= slot) {
3651925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
36525f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
36535f39d397SChris Mason 		path->nodes[0] = right;
3654be0e5c09SChris Mason 		path->slots[0] -= mid;
3655be0e5c09SChris Mason 		path->slots[1] += 1;
3656925baeddSChris Mason 	} else {
3657925baeddSChris Mason 		btrfs_tree_unlock(right);
36585f39d397SChris Mason 		free_extent_buffer(right);
3659925baeddSChris Mason 	}
36605f39d397SChris Mason 
3661eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
366244871b1bSChris Mason }
366344871b1bSChris Mason 
366444871b1bSChris Mason /*
366599d8f83cSChris Mason  * double splits happen when we need to insert a big item in the middle
366699d8f83cSChris Mason  * of a leaf.  A double split can leave us with 3 mostly empty leaves:
366799d8f83cSChris Mason  * leaf: [ slots 0 - N] [ our target ] [ N + 1 - total in leaf ]
366899d8f83cSChris Mason  *          A                 B                 C
366999d8f83cSChris Mason  *
367099d8f83cSChris Mason  * We avoid this by trying to push the items on either side of our target
367199d8f83cSChris Mason  * into the adjacent leaves.  If all goes well we can avoid the double split
367299d8f83cSChris Mason  * completely.
367399d8f83cSChris Mason  */
367499d8f83cSChris Mason static noinline int push_for_double_split(struct btrfs_trans_handle *trans,
367599d8f83cSChris Mason 					  struct btrfs_root *root,
367699d8f83cSChris Mason 					  struct btrfs_path *path,
367799d8f83cSChris Mason 					  int data_size)
367899d8f83cSChris Mason {
367999d8f83cSChris Mason 	int ret;
368099d8f83cSChris Mason 	int progress = 0;
368199d8f83cSChris Mason 	int slot;
368299d8f83cSChris Mason 	u32 nritems;
368399d8f83cSChris Mason 
368499d8f83cSChris Mason 	slot = path->slots[0];
368599d8f83cSChris Mason 
368699d8f83cSChris Mason 	/*
368799d8f83cSChris Mason 	 * try to push all the items after our slot into the
368899d8f83cSChris Mason 	 * right leaf
368999d8f83cSChris Mason 	 */
369099d8f83cSChris Mason 	ret = push_leaf_right(trans, root, path, 1, data_size, 0, slot);
369199d8f83cSChris Mason 	if (ret < 0)
369299d8f83cSChris Mason 		return ret;
369399d8f83cSChris Mason 
369499d8f83cSChris Mason 	if (ret == 0)
369599d8f83cSChris Mason 		progress++;
369699d8f83cSChris Mason 
369799d8f83cSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
369899d8f83cSChris Mason 	/*
369999d8f83cSChris Mason 	 * our goal is to get our slot at the start or end of a leaf.  If
370099d8f83cSChris Mason 	 * we've done so we're done
370199d8f83cSChris Mason 	 */
370299d8f83cSChris Mason 	if (path->slots[0] == 0 || path->slots[0] == nritems)
370399d8f83cSChris Mason 		return 0;
370499d8f83cSChris Mason 
370599d8f83cSChris Mason 	if (btrfs_leaf_free_space(root, path->nodes[0]) >= data_size)
370699d8f83cSChris Mason 		return 0;
370799d8f83cSChris Mason 
370899d8f83cSChris Mason 	/* try to push all the items before our slot into the next leaf */
370999d8f83cSChris Mason 	slot = path->slots[0];
371099d8f83cSChris Mason 	ret = push_leaf_left(trans, root, path, 1, data_size, 0, slot);
371199d8f83cSChris Mason 	if (ret < 0)
371299d8f83cSChris Mason 		return ret;
371399d8f83cSChris Mason 
371499d8f83cSChris Mason 	if (ret == 0)
371599d8f83cSChris Mason 		progress++;
371699d8f83cSChris Mason 
371799d8f83cSChris Mason 	if (progress)
371899d8f83cSChris Mason 		return 0;
371999d8f83cSChris Mason 	return 1;
372099d8f83cSChris Mason }
372199d8f83cSChris Mason 
372299d8f83cSChris Mason /*
372344871b1bSChris Mason  * split the path's leaf in two, making sure there is at least data_size
372444871b1bSChris Mason  * available for the resulting leaf level of the path.
372544871b1bSChris Mason  *
372644871b1bSChris Mason  * returns 0 if all went well and < 0 on failure.
372744871b1bSChris Mason  */
372844871b1bSChris Mason static noinline int split_leaf(struct btrfs_trans_handle *trans,
372944871b1bSChris Mason 			       struct btrfs_root *root,
373044871b1bSChris Mason 			       struct btrfs_key *ins_key,
373144871b1bSChris Mason 			       struct btrfs_path *path, int data_size,
373244871b1bSChris Mason 			       int extend)
373344871b1bSChris Mason {
37345d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
373544871b1bSChris Mason 	struct extent_buffer *l;
373644871b1bSChris Mason 	u32 nritems;
373744871b1bSChris Mason 	int mid;
373844871b1bSChris Mason 	int slot;
373944871b1bSChris Mason 	struct extent_buffer *right;
374044871b1bSChris Mason 	int ret = 0;
374144871b1bSChris Mason 	int wret;
37425d4f98a2SYan Zheng 	int split;
374344871b1bSChris Mason 	int num_doubles = 0;
374499d8f83cSChris Mason 	int tried_avoid_double = 0;
374544871b1bSChris Mason 
3746a5719521SYan, Zheng 	l = path->nodes[0];
3747a5719521SYan, Zheng 	slot = path->slots[0];
3748a5719521SYan, Zheng 	if (extend && data_size + btrfs_item_size_nr(l, slot) +
3749a5719521SYan, Zheng 	    sizeof(struct btrfs_item) > BTRFS_LEAF_DATA_SIZE(root))
3750a5719521SYan, Zheng 		return -EOVERFLOW;
3751a5719521SYan, Zheng 
375244871b1bSChris Mason 	/* first try to make some room by pushing left and right */
375399d8f83cSChris Mason 	if (data_size) {
375499d8f83cSChris Mason 		wret = push_leaf_right(trans, root, path, data_size,
375599d8f83cSChris Mason 				       data_size, 0, 0);
375644871b1bSChris Mason 		if (wret < 0)
375744871b1bSChris Mason 			return wret;
375844871b1bSChris Mason 		if (wret) {
375999d8f83cSChris Mason 			wret = push_leaf_left(trans, root, path, data_size,
376099d8f83cSChris Mason 					      data_size, 0, (u32)-1);
376144871b1bSChris Mason 			if (wret < 0)
376244871b1bSChris Mason 				return wret;
376344871b1bSChris Mason 		}
376444871b1bSChris Mason 		l = path->nodes[0];
376544871b1bSChris Mason 
376644871b1bSChris Mason 		/* did the pushes work? */
376744871b1bSChris Mason 		if (btrfs_leaf_free_space(root, l) >= data_size)
376844871b1bSChris Mason 			return 0;
376944871b1bSChris Mason 	}
377044871b1bSChris Mason 
377144871b1bSChris Mason 	if (!path->nodes[1]) {
377244871b1bSChris Mason 		ret = insert_new_root(trans, root, path, 1);
377344871b1bSChris Mason 		if (ret)
377444871b1bSChris Mason 			return ret;
377544871b1bSChris Mason 	}
377644871b1bSChris Mason again:
37775d4f98a2SYan Zheng 	split = 1;
377844871b1bSChris Mason 	l = path->nodes[0];
377944871b1bSChris Mason 	slot = path->slots[0];
378044871b1bSChris Mason 	nritems = btrfs_header_nritems(l);
378144871b1bSChris Mason 	mid = (nritems + 1) / 2;
378244871b1bSChris Mason 
37835d4f98a2SYan Zheng 	if (mid <= slot) {
37845d4f98a2SYan Zheng 		if (nritems == 1 ||
37855d4f98a2SYan Zheng 		    leaf_space_used(l, mid, nritems - mid) + data_size >
37865d4f98a2SYan Zheng 			BTRFS_LEAF_DATA_SIZE(root)) {
37875d4f98a2SYan Zheng 			if (slot >= nritems) {
37885d4f98a2SYan Zheng 				split = 0;
37895d4f98a2SYan Zheng 			} else {
37905d4f98a2SYan Zheng 				mid = slot;
37915d4f98a2SYan Zheng 				if (mid != nritems &&
37925d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
37935d4f98a2SYan Zheng 				    data_size > BTRFS_LEAF_DATA_SIZE(root)) {
379499d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
379599d8f83cSChris Mason 						goto push_for_double;
37965d4f98a2SYan Zheng 					split = 2;
37975d4f98a2SYan Zheng 				}
37985d4f98a2SYan Zheng 			}
37995d4f98a2SYan Zheng 		}
38005d4f98a2SYan Zheng 	} else {
38015d4f98a2SYan Zheng 		if (leaf_space_used(l, 0, mid) + data_size >
38025d4f98a2SYan Zheng 			BTRFS_LEAF_DATA_SIZE(root)) {
38035d4f98a2SYan Zheng 			if (!extend && data_size && slot == 0) {
38045d4f98a2SYan Zheng 				split = 0;
38055d4f98a2SYan Zheng 			} else if ((extend || !data_size) && slot == 0) {
38065d4f98a2SYan Zheng 				mid = 1;
38075d4f98a2SYan Zheng 			} else {
38085d4f98a2SYan Zheng 				mid = slot;
38095d4f98a2SYan Zheng 				if (mid != nritems &&
38105d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
38115d4f98a2SYan Zheng 				    data_size > BTRFS_LEAF_DATA_SIZE(root)) {
381299d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
381399d8f83cSChris Mason 						goto push_for_double;
38145d4f98a2SYan Zheng 					split = 2 ;
38155d4f98a2SYan Zheng 				}
38165d4f98a2SYan Zheng 			}
38175d4f98a2SYan Zheng 		}
38185d4f98a2SYan Zheng 	}
38195d4f98a2SYan Zheng 
38205d4f98a2SYan Zheng 	if (split == 0)
38215d4f98a2SYan Zheng 		btrfs_cpu_key_to_disk(&disk_key, ins_key);
38225d4f98a2SYan Zheng 	else
38235d4f98a2SYan Zheng 		btrfs_item_key(l, &disk_key, mid);
38245d4f98a2SYan Zheng 
38255d4f98a2SYan Zheng 	right = btrfs_alloc_free_block(trans, root, root->leafsize, 0,
382644871b1bSChris Mason 					root->root_key.objectid,
38275581a51aSJan Schmidt 					&disk_key, 0, l->start, 0);
3828f0486c68SYan, Zheng 	if (IS_ERR(right))
382944871b1bSChris Mason 		return PTR_ERR(right);
3830f0486c68SYan, Zheng 
3831f0486c68SYan, Zheng 	root_add_used(root, root->leafsize);
383244871b1bSChris Mason 
383344871b1bSChris Mason 	memset_extent_buffer(right, 0, 0, sizeof(struct btrfs_header));
383444871b1bSChris Mason 	btrfs_set_header_bytenr(right, right->start);
383544871b1bSChris Mason 	btrfs_set_header_generation(right, trans->transid);
38365d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(right, BTRFS_MIXED_BACKREF_REV);
383744871b1bSChris Mason 	btrfs_set_header_owner(right, root->root_key.objectid);
383844871b1bSChris Mason 	btrfs_set_header_level(right, 0);
383944871b1bSChris Mason 	write_extent_buffer(right, root->fs_info->fsid,
384044871b1bSChris Mason 			    (unsigned long)btrfs_header_fsid(right),
384144871b1bSChris Mason 			    BTRFS_FSID_SIZE);
384244871b1bSChris Mason 
384344871b1bSChris Mason 	write_extent_buffer(right, root->fs_info->chunk_tree_uuid,
384444871b1bSChris Mason 			    (unsigned long)btrfs_header_chunk_tree_uuid(right),
384544871b1bSChris Mason 			    BTRFS_UUID_SIZE);
384644871b1bSChris Mason 
38475d4f98a2SYan Zheng 	if (split == 0) {
384844871b1bSChris Mason 		if (mid <= slot) {
384944871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
3850143bede5SJeff Mahoney 			insert_ptr(trans, root, path, &disk_key, right->start,
3851f3ea38daSJan Schmidt 				   path->slots[1] + 1, 1, 0);
385244871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
385344871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
385444871b1bSChris Mason 			path->nodes[0] = right;
385544871b1bSChris Mason 			path->slots[0] = 0;
385644871b1bSChris Mason 			path->slots[1] += 1;
385744871b1bSChris Mason 		} else {
385844871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
3859143bede5SJeff Mahoney 			insert_ptr(trans, root, path, &disk_key, right->start,
3860f3ea38daSJan Schmidt 					  path->slots[1], 1, 0);
386144871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
386244871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
386344871b1bSChris Mason 			path->nodes[0] = right;
386444871b1bSChris Mason 			path->slots[0] = 0;
3865143bede5SJeff Mahoney 			if (path->slots[1] == 0)
3866143bede5SJeff Mahoney 				fixup_low_keys(trans, root, path,
3867143bede5SJeff Mahoney 					       &disk_key, 1);
38685d4f98a2SYan Zheng 		}
386944871b1bSChris Mason 		btrfs_mark_buffer_dirty(right);
387044871b1bSChris Mason 		return ret;
387144871b1bSChris Mason 	}
387244871b1bSChris Mason 
3873143bede5SJeff Mahoney 	copy_for_split(trans, root, path, l, right, slot, mid, nritems);
387444871b1bSChris Mason 
38755d4f98a2SYan Zheng 	if (split == 2) {
3876cc0c5538SChris Mason 		BUG_ON(num_doubles != 0);
3877cc0c5538SChris Mason 		num_doubles++;
3878cc0c5538SChris Mason 		goto again;
38793326d1b0SChris Mason 	}
388044871b1bSChris Mason 
3881143bede5SJeff Mahoney 	return 0;
388299d8f83cSChris Mason 
388399d8f83cSChris Mason push_for_double:
388499d8f83cSChris Mason 	push_for_double_split(trans, root, path, data_size);
388599d8f83cSChris Mason 	tried_avoid_double = 1;
388699d8f83cSChris Mason 	if (btrfs_leaf_free_space(root, path->nodes[0]) >= data_size)
388799d8f83cSChris Mason 		return 0;
388899d8f83cSChris Mason 	goto again;
3889be0e5c09SChris Mason }
3890be0e5c09SChris Mason 
3891ad48fd75SYan, Zheng static noinline int setup_leaf_for_split(struct btrfs_trans_handle *trans,
3892ad48fd75SYan, Zheng 					 struct btrfs_root *root,
3893ad48fd75SYan, Zheng 					 struct btrfs_path *path, int ins_len)
3894ad48fd75SYan, Zheng {
3895ad48fd75SYan, Zheng 	struct btrfs_key key;
3896ad48fd75SYan, Zheng 	struct extent_buffer *leaf;
3897ad48fd75SYan, Zheng 	struct btrfs_file_extent_item *fi;
3898ad48fd75SYan, Zheng 	u64 extent_len = 0;
3899ad48fd75SYan, Zheng 	u32 item_size;
3900ad48fd75SYan, Zheng 	int ret;
3901ad48fd75SYan, Zheng 
3902ad48fd75SYan, Zheng 	leaf = path->nodes[0];
3903ad48fd75SYan, Zheng 	btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3904ad48fd75SYan, Zheng 
3905ad48fd75SYan, Zheng 	BUG_ON(key.type != BTRFS_EXTENT_DATA_KEY &&
3906ad48fd75SYan, Zheng 	       key.type != BTRFS_EXTENT_CSUM_KEY);
3907ad48fd75SYan, Zheng 
3908ad48fd75SYan, Zheng 	if (btrfs_leaf_free_space(root, leaf) >= ins_len)
3909ad48fd75SYan, Zheng 		return 0;
3910ad48fd75SYan, Zheng 
3911ad48fd75SYan, Zheng 	item_size = btrfs_item_size_nr(leaf, path->slots[0]);
3912ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
3913ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
3914ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
3915ad48fd75SYan, Zheng 		extent_len = btrfs_file_extent_num_bytes(leaf, fi);
3916ad48fd75SYan, Zheng 	}
3917b3b4aa74SDavid Sterba 	btrfs_release_path(path);
3918ad48fd75SYan, Zheng 
3919ad48fd75SYan, Zheng 	path->keep_locks = 1;
3920ad48fd75SYan, Zheng 	path->search_for_split = 1;
3921ad48fd75SYan, Zheng 	ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
3922ad48fd75SYan, Zheng 	path->search_for_split = 0;
3923ad48fd75SYan, Zheng 	if (ret < 0)
3924ad48fd75SYan, Zheng 		goto err;
3925ad48fd75SYan, Zheng 
3926ad48fd75SYan, Zheng 	ret = -EAGAIN;
3927ad48fd75SYan, Zheng 	leaf = path->nodes[0];
3928ad48fd75SYan, Zheng 	/* if our item isn't there or got smaller, return now */
3929ad48fd75SYan, Zheng 	if (ret > 0 || item_size != btrfs_item_size_nr(leaf, path->slots[0]))
3930ad48fd75SYan, Zheng 		goto err;
3931ad48fd75SYan, Zheng 
3932109f6aefSChris Mason 	/* the leaf has  changed, it now has room.  return now */
3933109f6aefSChris Mason 	if (btrfs_leaf_free_space(root, path->nodes[0]) >= ins_len)
3934109f6aefSChris Mason 		goto err;
3935109f6aefSChris Mason 
3936ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
3937ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
3938ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
3939ad48fd75SYan, Zheng 		if (extent_len != btrfs_file_extent_num_bytes(leaf, fi))
3940ad48fd75SYan, Zheng 			goto err;
3941ad48fd75SYan, Zheng 	}
3942ad48fd75SYan, Zheng 
3943ad48fd75SYan, Zheng 	btrfs_set_path_blocking(path);
3944ad48fd75SYan, Zheng 	ret = split_leaf(trans, root, &key, path, ins_len, 1);
3945f0486c68SYan, Zheng 	if (ret)
3946f0486c68SYan, Zheng 		goto err;
3947ad48fd75SYan, Zheng 
3948ad48fd75SYan, Zheng 	path->keep_locks = 0;
3949ad48fd75SYan, Zheng 	btrfs_unlock_up_safe(path, 1);
3950ad48fd75SYan, Zheng 	return 0;
3951ad48fd75SYan, Zheng err:
3952ad48fd75SYan, Zheng 	path->keep_locks = 0;
3953ad48fd75SYan, Zheng 	return ret;
3954ad48fd75SYan, Zheng }
3955ad48fd75SYan, Zheng 
3956ad48fd75SYan, Zheng static noinline int split_item(struct btrfs_trans_handle *trans,
3957459931ecSChris Mason 			       struct btrfs_root *root,
3958459931ecSChris Mason 			       struct btrfs_path *path,
3959459931ecSChris Mason 			       struct btrfs_key *new_key,
3960459931ecSChris Mason 			       unsigned long split_offset)
3961459931ecSChris Mason {
3962459931ecSChris Mason 	struct extent_buffer *leaf;
3963459931ecSChris Mason 	struct btrfs_item *item;
3964459931ecSChris Mason 	struct btrfs_item *new_item;
3965459931ecSChris Mason 	int slot;
3966ad48fd75SYan, Zheng 	char *buf;
3967459931ecSChris Mason 	u32 nritems;
3968ad48fd75SYan, Zheng 	u32 item_size;
3969459931ecSChris Mason 	u32 orig_offset;
3970459931ecSChris Mason 	struct btrfs_disk_key disk_key;
3971459931ecSChris Mason 
3972459931ecSChris Mason 	leaf = path->nodes[0];
3973b9473439SChris Mason 	BUG_ON(btrfs_leaf_free_space(root, leaf) < sizeof(struct btrfs_item));
3974b9473439SChris Mason 
3975b4ce94deSChris Mason 	btrfs_set_path_blocking(path);
3976b4ce94deSChris Mason 
3977459931ecSChris Mason 	item = btrfs_item_nr(leaf, path->slots[0]);
3978459931ecSChris Mason 	orig_offset = btrfs_item_offset(leaf, item);
3979459931ecSChris Mason 	item_size = btrfs_item_size(leaf, item);
3980459931ecSChris Mason 
3981459931ecSChris Mason 	buf = kmalloc(item_size, GFP_NOFS);
3982ad48fd75SYan, Zheng 	if (!buf)
3983ad48fd75SYan, Zheng 		return -ENOMEM;
3984ad48fd75SYan, Zheng 
3985459931ecSChris Mason 	read_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf,
3986459931ecSChris Mason 			    path->slots[0]), item_size);
3987ad48fd75SYan, Zheng 
3988459931ecSChris Mason 	slot = path->slots[0] + 1;
3989459931ecSChris Mason 	nritems = btrfs_header_nritems(leaf);
3990459931ecSChris Mason 	if (slot != nritems) {
3991459931ecSChris Mason 		/* shift the items */
3992459931ecSChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + 1),
3993459931ecSChris Mason 				btrfs_item_nr_offset(slot),
3994459931ecSChris Mason 				(nritems - slot) * sizeof(struct btrfs_item));
3995459931ecSChris Mason 	}
3996459931ecSChris Mason 
3997459931ecSChris Mason 	btrfs_cpu_key_to_disk(&disk_key, new_key);
3998459931ecSChris Mason 	btrfs_set_item_key(leaf, &disk_key, slot);
3999459931ecSChris Mason 
4000459931ecSChris Mason 	new_item = btrfs_item_nr(leaf, slot);
4001459931ecSChris Mason 
4002459931ecSChris Mason 	btrfs_set_item_offset(leaf, new_item, orig_offset);
4003459931ecSChris Mason 	btrfs_set_item_size(leaf, new_item, item_size - split_offset);
4004459931ecSChris Mason 
4005459931ecSChris Mason 	btrfs_set_item_offset(leaf, item,
4006459931ecSChris Mason 			      orig_offset + item_size - split_offset);
4007459931ecSChris Mason 	btrfs_set_item_size(leaf, item, split_offset);
4008459931ecSChris Mason 
4009459931ecSChris Mason 	btrfs_set_header_nritems(leaf, nritems + 1);
4010459931ecSChris Mason 
4011459931ecSChris Mason 	/* write the data for the start of the original item */
4012459931ecSChris Mason 	write_extent_buffer(leaf, buf,
4013459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, path->slots[0]),
4014459931ecSChris Mason 			    split_offset);
4015459931ecSChris Mason 
4016459931ecSChris Mason 	/* write the data for the new item */
4017459931ecSChris Mason 	write_extent_buffer(leaf, buf + split_offset,
4018459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, slot),
4019459931ecSChris Mason 			    item_size - split_offset);
4020459931ecSChris Mason 	btrfs_mark_buffer_dirty(leaf);
4021459931ecSChris Mason 
4022ad48fd75SYan, Zheng 	BUG_ON(btrfs_leaf_free_space(root, leaf) < 0);
4023459931ecSChris Mason 	kfree(buf);
4024ad48fd75SYan, Zheng 	return 0;
4025ad48fd75SYan, Zheng }
4026ad48fd75SYan, Zheng 
4027ad48fd75SYan, Zheng /*
4028ad48fd75SYan, Zheng  * This function splits a single item into two items,
4029ad48fd75SYan, Zheng  * giving 'new_key' to the new item and splitting the
4030ad48fd75SYan, Zheng  * old one at split_offset (from the start of the item).
4031ad48fd75SYan, Zheng  *
4032ad48fd75SYan, Zheng  * The path may be released by this operation.  After
4033ad48fd75SYan, Zheng  * the split, the path is pointing to the old item.  The
4034ad48fd75SYan, Zheng  * new item is going to be in the same node as the old one.
4035ad48fd75SYan, Zheng  *
4036ad48fd75SYan, Zheng  * Note, the item being split must be smaller enough to live alone on
4037ad48fd75SYan, Zheng  * a tree block with room for one extra struct btrfs_item
4038ad48fd75SYan, Zheng  *
4039ad48fd75SYan, Zheng  * This allows us to split the item in place, keeping a lock on the
4040ad48fd75SYan, Zheng  * leaf the entire time.
4041ad48fd75SYan, Zheng  */
4042ad48fd75SYan, Zheng int btrfs_split_item(struct btrfs_trans_handle *trans,
4043ad48fd75SYan, Zheng 		     struct btrfs_root *root,
4044ad48fd75SYan, Zheng 		     struct btrfs_path *path,
4045ad48fd75SYan, Zheng 		     struct btrfs_key *new_key,
4046ad48fd75SYan, Zheng 		     unsigned long split_offset)
4047ad48fd75SYan, Zheng {
4048ad48fd75SYan, Zheng 	int ret;
4049ad48fd75SYan, Zheng 	ret = setup_leaf_for_split(trans, root, path,
4050ad48fd75SYan, Zheng 				   sizeof(struct btrfs_item));
4051ad48fd75SYan, Zheng 	if (ret)
4052459931ecSChris Mason 		return ret;
4053ad48fd75SYan, Zheng 
4054ad48fd75SYan, Zheng 	ret = split_item(trans, root, path, new_key, split_offset);
4055ad48fd75SYan, Zheng 	return ret;
4056ad48fd75SYan, Zheng }
4057ad48fd75SYan, Zheng 
4058ad48fd75SYan, Zheng /*
4059ad48fd75SYan, Zheng  * This function duplicate a item, giving 'new_key' to the new item.
4060ad48fd75SYan, Zheng  * It guarantees both items live in the same tree leaf and the new item
4061ad48fd75SYan, Zheng  * is contiguous with the original item.
4062ad48fd75SYan, Zheng  *
4063ad48fd75SYan, Zheng  * This allows us to split file extent in place, keeping a lock on the
4064ad48fd75SYan, Zheng  * leaf the entire time.
4065ad48fd75SYan, Zheng  */
4066ad48fd75SYan, Zheng int btrfs_duplicate_item(struct btrfs_trans_handle *trans,
4067ad48fd75SYan, Zheng 			 struct btrfs_root *root,
4068ad48fd75SYan, Zheng 			 struct btrfs_path *path,
4069ad48fd75SYan, Zheng 			 struct btrfs_key *new_key)
4070ad48fd75SYan, Zheng {
4071ad48fd75SYan, Zheng 	struct extent_buffer *leaf;
4072ad48fd75SYan, Zheng 	int ret;
4073ad48fd75SYan, Zheng 	u32 item_size;
4074ad48fd75SYan, Zheng 
4075ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4076ad48fd75SYan, Zheng 	item_size = btrfs_item_size_nr(leaf, path->slots[0]);
4077ad48fd75SYan, Zheng 	ret = setup_leaf_for_split(trans, root, path,
4078ad48fd75SYan, Zheng 				   item_size + sizeof(struct btrfs_item));
4079ad48fd75SYan, Zheng 	if (ret)
4080ad48fd75SYan, Zheng 		return ret;
4081ad48fd75SYan, Zheng 
4082ad48fd75SYan, Zheng 	path->slots[0]++;
4083143bede5SJeff Mahoney 	setup_items_for_insert(trans, root, path, new_key, &item_size,
4084ad48fd75SYan, Zheng 			       item_size, item_size +
4085ad48fd75SYan, Zheng 			       sizeof(struct btrfs_item), 1);
4086ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4087ad48fd75SYan, Zheng 	memcpy_extent_buffer(leaf,
4088ad48fd75SYan, Zheng 			     btrfs_item_ptr_offset(leaf, path->slots[0]),
4089ad48fd75SYan, Zheng 			     btrfs_item_ptr_offset(leaf, path->slots[0] - 1),
4090ad48fd75SYan, Zheng 			     item_size);
4091ad48fd75SYan, Zheng 	return 0;
4092459931ecSChris Mason }
4093459931ecSChris Mason 
4094459931ecSChris Mason /*
4095d352ac68SChris Mason  * make the item pointed to by the path smaller.  new_size indicates
4096d352ac68SChris Mason  * how small to make it, and from_end tells us if we just chop bytes
4097d352ac68SChris Mason  * off the end of the item or if we shift the item to chop bytes off
4098d352ac68SChris Mason  * the front.
4099d352ac68SChris Mason  */
4100143bede5SJeff Mahoney void btrfs_truncate_item(struct btrfs_trans_handle *trans,
4101b18c6685SChris Mason 			 struct btrfs_root *root,
4102b18c6685SChris Mason 			 struct btrfs_path *path,
4103179e29e4SChris Mason 			 u32 new_size, int from_end)
4104b18c6685SChris Mason {
4105b18c6685SChris Mason 	int slot;
41065f39d397SChris Mason 	struct extent_buffer *leaf;
41075f39d397SChris Mason 	struct btrfs_item *item;
4108b18c6685SChris Mason 	u32 nritems;
4109b18c6685SChris Mason 	unsigned int data_end;
4110b18c6685SChris Mason 	unsigned int old_data_start;
4111b18c6685SChris Mason 	unsigned int old_size;
4112b18c6685SChris Mason 	unsigned int size_diff;
4113b18c6685SChris Mason 	int i;
4114cfed81a0SChris Mason 	struct btrfs_map_token token;
4115cfed81a0SChris Mason 
4116cfed81a0SChris Mason 	btrfs_init_map_token(&token);
4117b18c6685SChris Mason 
41185f39d397SChris Mason 	leaf = path->nodes[0];
4119179e29e4SChris Mason 	slot = path->slots[0];
4120179e29e4SChris Mason 
4121179e29e4SChris Mason 	old_size = btrfs_item_size_nr(leaf, slot);
4122179e29e4SChris Mason 	if (old_size == new_size)
4123143bede5SJeff Mahoney 		return;
4124b18c6685SChris Mason 
41255f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
4126b18c6685SChris Mason 	data_end = leaf_data_end(root, leaf);
4127b18c6685SChris Mason 
41285f39d397SChris Mason 	old_data_start = btrfs_item_offset_nr(leaf, slot);
4129179e29e4SChris Mason 
4130b18c6685SChris Mason 	size_diff = old_size - new_size;
4131b18c6685SChris Mason 
4132b18c6685SChris Mason 	BUG_ON(slot < 0);
4133b18c6685SChris Mason 	BUG_ON(slot >= nritems);
4134b18c6685SChris Mason 
4135b18c6685SChris Mason 	/*
4136b18c6685SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4137b18c6685SChris Mason 	 */
4138b18c6685SChris Mason 	/* first correct the data pointers */
4139b18c6685SChris Mason 	for (i = slot; i < nritems; i++) {
41405f39d397SChris Mason 		u32 ioff;
41415f39d397SChris Mason 		item = btrfs_item_nr(leaf, i);
4142db94535dSChris Mason 
4143cfed81a0SChris Mason 		ioff = btrfs_token_item_offset(leaf, item, &token);
4144cfed81a0SChris Mason 		btrfs_set_token_item_offset(leaf, item,
4145cfed81a0SChris Mason 					    ioff + size_diff, &token);
4146b18c6685SChris Mason 	}
4147db94535dSChris Mason 
4148b18c6685SChris Mason 	/* shift the data */
4149179e29e4SChris Mason 	if (from_end) {
41505f39d397SChris Mason 		memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
4151b18c6685SChris Mason 			      data_end + size_diff, btrfs_leaf_data(leaf) +
4152b18c6685SChris Mason 			      data_end, old_data_start + new_size - data_end);
4153179e29e4SChris Mason 	} else {
4154179e29e4SChris Mason 		struct btrfs_disk_key disk_key;
4155179e29e4SChris Mason 		u64 offset;
4156179e29e4SChris Mason 
4157179e29e4SChris Mason 		btrfs_item_key(leaf, &disk_key, slot);
4158179e29e4SChris Mason 
4159179e29e4SChris Mason 		if (btrfs_disk_key_type(&disk_key) == BTRFS_EXTENT_DATA_KEY) {
4160179e29e4SChris Mason 			unsigned long ptr;
4161179e29e4SChris Mason 			struct btrfs_file_extent_item *fi;
4162179e29e4SChris Mason 
4163179e29e4SChris Mason 			fi = btrfs_item_ptr(leaf, slot,
4164179e29e4SChris Mason 					    struct btrfs_file_extent_item);
4165179e29e4SChris Mason 			fi = (struct btrfs_file_extent_item *)(
4166179e29e4SChris Mason 			     (unsigned long)fi - size_diff);
4167179e29e4SChris Mason 
4168179e29e4SChris Mason 			if (btrfs_file_extent_type(leaf, fi) ==
4169179e29e4SChris Mason 			    BTRFS_FILE_EXTENT_INLINE) {
4170179e29e4SChris Mason 				ptr = btrfs_item_ptr_offset(leaf, slot);
4171179e29e4SChris Mason 				memmove_extent_buffer(leaf, ptr,
4172179e29e4SChris Mason 				      (unsigned long)fi,
4173179e29e4SChris Mason 				      offsetof(struct btrfs_file_extent_item,
4174179e29e4SChris Mason 						 disk_bytenr));
4175179e29e4SChris Mason 			}
4176179e29e4SChris Mason 		}
4177179e29e4SChris Mason 
4178179e29e4SChris Mason 		memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
4179179e29e4SChris Mason 			      data_end + size_diff, btrfs_leaf_data(leaf) +
4180179e29e4SChris Mason 			      data_end, old_data_start - data_end);
4181179e29e4SChris Mason 
4182179e29e4SChris Mason 		offset = btrfs_disk_key_offset(&disk_key);
4183179e29e4SChris Mason 		btrfs_set_disk_key_offset(&disk_key, offset + size_diff);
4184179e29e4SChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot);
4185179e29e4SChris Mason 		if (slot == 0)
4186179e29e4SChris Mason 			fixup_low_keys(trans, root, path, &disk_key, 1);
4187179e29e4SChris Mason 	}
41885f39d397SChris Mason 
41895f39d397SChris Mason 	item = btrfs_item_nr(leaf, slot);
41905f39d397SChris Mason 	btrfs_set_item_size(leaf, item, new_size);
41915f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
4192b18c6685SChris Mason 
41935f39d397SChris Mason 	if (btrfs_leaf_free_space(root, leaf) < 0) {
41945f39d397SChris Mason 		btrfs_print_leaf(root, leaf);
4195b18c6685SChris Mason 		BUG();
41965f39d397SChris Mason 	}
4197b18c6685SChris Mason }
4198b18c6685SChris Mason 
4199d352ac68SChris Mason /*
4200d352ac68SChris Mason  * make the item pointed to by the path bigger, data_size is the new size.
4201d352ac68SChris Mason  */
4202143bede5SJeff Mahoney void btrfs_extend_item(struct btrfs_trans_handle *trans,
42035f39d397SChris Mason 		       struct btrfs_root *root, struct btrfs_path *path,
42045f39d397SChris Mason 		       u32 data_size)
42056567e837SChris Mason {
42066567e837SChris Mason 	int slot;
42075f39d397SChris Mason 	struct extent_buffer *leaf;
42085f39d397SChris Mason 	struct btrfs_item *item;
42096567e837SChris Mason 	u32 nritems;
42106567e837SChris Mason 	unsigned int data_end;
42116567e837SChris Mason 	unsigned int old_data;
42126567e837SChris Mason 	unsigned int old_size;
42136567e837SChris Mason 	int i;
4214cfed81a0SChris Mason 	struct btrfs_map_token token;
4215cfed81a0SChris Mason 
4216cfed81a0SChris Mason 	btrfs_init_map_token(&token);
42176567e837SChris Mason 
42185f39d397SChris Mason 	leaf = path->nodes[0];
42196567e837SChris Mason 
42205f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
42216567e837SChris Mason 	data_end = leaf_data_end(root, leaf);
42226567e837SChris Mason 
42235f39d397SChris Mason 	if (btrfs_leaf_free_space(root, leaf) < data_size) {
42245f39d397SChris Mason 		btrfs_print_leaf(root, leaf);
42256567e837SChris Mason 		BUG();
42265f39d397SChris Mason 	}
42276567e837SChris Mason 	slot = path->slots[0];
42285f39d397SChris Mason 	old_data = btrfs_item_end_nr(leaf, slot);
42296567e837SChris Mason 
42306567e837SChris Mason 	BUG_ON(slot < 0);
42313326d1b0SChris Mason 	if (slot >= nritems) {
42323326d1b0SChris Mason 		btrfs_print_leaf(root, leaf);
4233d397712bSChris Mason 		printk(KERN_CRIT "slot %d too large, nritems %d\n",
4234d397712bSChris Mason 		       slot, nritems);
42353326d1b0SChris Mason 		BUG_ON(1);
42363326d1b0SChris Mason 	}
42376567e837SChris Mason 
42386567e837SChris Mason 	/*
42396567e837SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
42406567e837SChris Mason 	 */
42416567e837SChris Mason 	/* first correct the data pointers */
42426567e837SChris Mason 	for (i = slot; i < nritems; i++) {
42435f39d397SChris Mason 		u32 ioff;
42445f39d397SChris Mason 		item = btrfs_item_nr(leaf, i);
4245db94535dSChris Mason 
4246cfed81a0SChris Mason 		ioff = btrfs_token_item_offset(leaf, item, &token);
4247cfed81a0SChris Mason 		btrfs_set_token_item_offset(leaf, item,
4248cfed81a0SChris Mason 					    ioff - data_size, &token);
42496567e837SChris Mason 	}
42505f39d397SChris Mason 
42516567e837SChris Mason 	/* shift the data */
42525f39d397SChris Mason 	memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
42536567e837SChris Mason 		      data_end - data_size, btrfs_leaf_data(leaf) +
42546567e837SChris Mason 		      data_end, old_data - data_end);
42555f39d397SChris Mason 
42566567e837SChris Mason 	data_end = old_data;
42575f39d397SChris Mason 	old_size = btrfs_item_size_nr(leaf, slot);
42585f39d397SChris Mason 	item = btrfs_item_nr(leaf, slot);
42595f39d397SChris Mason 	btrfs_set_item_size(leaf, item, old_size + data_size);
42605f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
42616567e837SChris Mason 
42625f39d397SChris Mason 	if (btrfs_leaf_free_space(root, leaf) < 0) {
42635f39d397SChris Mason 		btrfs_print_leaf(root, leaf);
42646567e837SChris Mason 		BUG();
42655f39d397SChris Mason 	}
42666567e837SChris Mason }
42676567e837SChris Mason 
426874123bd7SChris Mason /*
4269d352ac68SChris Mason  * Given a key and some data, insert items into the tree.
427074123bd7SChris Mason  * This does all the path init required, making room in the tree if needed.
4271f3465ca4SJosef Bacik  * Returns the number of keys that were inserted.
4272f3465ca4SJosef Bacik  */
4273f3465ca4SJosef Bacik int btrfs_insert_some_items(struct btrfs_trans_handle *trans,
4274f3465ca4SJosef Bacik 			    struct btrfs_root *root,
4275f3465ca4SJosef Bacik 			    struct btrfs_path *path,
4276f3465ca4SJosef Bacik 			    struct btrfs_key *cpu_key, u32 *data_size,
4277f3465ca4SJosef Bacik 			    int nr)
4278f3465ca4SJosef Bacik {
4279f3465ca4SJosef Bacik 	struct extent_buffer *leaf;
4280f3465ca4SJosef Bacik 	struct btrfs_item *item;
4281f3465ca4SJosef Bacik 	int ret = 0;
4282f3465ca4SJosef Bacik 	int slot;
4283f3465ca4SJosef Bacik 	int i;
4284f3465ca4SJosef Bacik 	u32 nritems;
4285f3465ca4SJosef Bacik 	u32 total_data = 0;
4286f3465ca4SJosef Bacik 	u32 total_size = 0;
4287f3465ca4SJosef Bacik 	unsigned int data_end;
4288f3465ca4SJosef Bacik 	struct btrfs_disk_key disk_key;
4289f3465ca4SJosef Bacik 	struct btrfs_key found_key;
4290cfed81a0SChris Mason 	struct btrfs_map_token token;
4291cfed81a0SChris Mason 
4292cfed81a0SChris Mason 	btrfs_init_map_token(&token);
4293f3465ca4SJosef Bacik 
429487b29b20SYan Zheng 	for (i = 0; i < nr; i++) {
429587b29b20SYan Zheng 		if (total_size + data_size[i] + sizeof(struct btrfs_item) >
429687b29b20SYan Zheng 		    BTRFS_LEAF_DATA_SIZE(root)) {
429787b29b20SYan Zheng 			break;
429887b29b20SYan Zheng 			nr = i;
429987b29b20SYan Zheng 		}
4300f3465ca4SJosef Bacik 		total_data += data_size[i];
430187b29b20SYan Zheng 		total_size += data_size[i] + sizeof(struct btrfs_item);
430287b29b20SYan Zheng 	}
430387b29b20SYan Zheng 	BUG_ON(nr == 0);
4304f3465ca4SJosef Bacik 
4305f3465ca4SJosef Bacik 	ret = btrfs_search_slot(trans, root, cpu_key, path, total_size, 1);
4306f3465ca4SJosef Bacik 	if (ret == 0)
4307f3465ca4SJosef Bacik 		return -EEXIST;
4308f3465ca4SJosef Bacik 	if (ret < 0)
4309f3465ca4SJosef Bacik 		goto out;
4310f3465ca4SJosef Bacik 
4311f3465ca4SJosef Bacik 	leaf = path->nodes[0];
4312f3465ca4SJosef Bacik 
4313f3465ca4SJosef Bacik 	nritems = btrfs_header_nritems(leaf);
4314f3465ca4SJosef Bacik 	data_end = leaf_data_end(root, leaf);
4315f3465ca4SJosef Bacik 
4316f3465ca4SJosef Bacik 	if (btrfs_leaf_free_space(root, leaf) < total_size) {
4317f3465ca4SJosef Bacik 		for (i = nr; i >= 0; i--) {
4318f3465ca4SJosef Bacik 			total_data -= data_size[i];
4319f3465ca4SJosef Bacik 			total_size -= data_size[i] + sizeof(struct btrfs_item);
4320f3465ca4SJosef Bacik 			if (total_size < btrfs_leaf_free_space(root, leaf))
4321f3465ca4SJosef Bacik 				break;
4322f3465ca4SJosef Bacik 		}
4323f3465ca4SJosef Bacik 		nr = i;
4324f3465ca4SJosef Bacik 	}
4325f3465ca4SJosef Bacik 
4326f3465ca4SJosef Bacik 	slot = path->slots[0];
4327f3465ca4SJosef Bacik 	BUG_ON(slot < 0);
4328f3465ca4SJosef Bacik 
4329f3465ca4SJosef Bacik 	if (slot != nritems) {
4330f3465ca4SJosef Bacik 		unsigned int old_data = btrfs_item_end_nr(leaf, slot);
4331f3465ca4SJosef Bacik 
4332f3465ca4SJosef Bacik 		item = btrfs_item_nr(leaf, slot);
4333f3465ca4SJosef Bacik 		btrfs_item_key_to_cpu(leaf, &found_key, slot);
4334f3465ca4SJosef Bacik 
4335f3465ca4SJosef Bacik 		/* figure out how many keys we can insert in here */
4336f3465ca4SJosef Bacik 		total_data = data_size[0];
4337f3465ca4SJosef Bacik 		for (i = 1; i < nr; i++) {
43385d4f98a2SYan Zheng 			if (btrfs_comp_cpu_keys(&found_key, cpu_key + i) <= 0)
4339f3465ca4SJosef Bacik 				break;
4340f3465ca4SJosef Bacik 			total_data += data_size[i];
4341f3465ca4SJosef Bacik 		}
4342f3465ca4SJosef Bacik 		nr = i;
4343f3465ca4SJosef Bacik 
4344f3465ca4SJosef Bacik 		if (old_data < data_end) {
4345f3465ca4SJosef Bacik 			btrfs_print_leaf(root, leaf);
4346d397712bSChris Mason 			printk(KERN_CRIT "slot %d old_data %d data_end %d\n",
4347f3465ca4SJosef Bacik 			       slot, old_data, data_end);
4348f3465ca4SJosef Bacik 			BUG_ON(1);
4349f3465ca4SJosef Bacik 		}
4350f3465ca4SJosef Bacik 		/*
4351f3465ca4SJosef Bacik 		 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4352f3465ca4SJosef Bacik 		 */
4353f3465ca4SJosef Bacik 		/* first correct the data pointers */
4354f3465ca4SJosef Bacik 		for (i = slot; i < nritems; i++) {
4355f3465ca4SJosef Bacik 			u32 ioff;
4356f3465ca4SJosef Bacik 
4357f3465ca4SJosef Bacik 			item = btrfs_item_nr(leaf, i);
4358cfed81a0SChris Mason 			ioff = btrfs_token_item_offset(leaf, item, &token);
4359cfed81a0SChris Mason 			btrfs_set_token_item_offset(leaf, item,
4360cfed81a0SChris Mason 						    ioff - total_data, &token);
4361f3465ca4SJosef Bacik 		}
4362f3465ca4SJosef Bacik 		/* shift the items */
4363f3465ca4SJosef Bacik 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + nr),
4364f3465ca4SJosef Bacik 			      btrfs_item_nr_offset(slot),
4365f3465ca4SJosef Bacik 			      (nritems - slot) * sizeof(struct btrfs_item));
4366f3465ca4SJosef Bacik 
4367f3465ca4SJosef Bacik 		/* shift the data */
4368f3465ca4SJosef Bacik 		memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
4369f3465ca4SJosef Bacik 			      data_end - total_data, btrfs_leaf_data(leaf) +
4370f3465ca4SJosef Bacik 			      data_end, old_data - data_end);
4371f3465ca4SJosef Bacik 		data_end = old_data;
4372f3465ca4SJosef Bacik 	} else {
4373f3465ca4SJosef Bacik 		/*
4374f3465ca4SJosef Bacik 		 * this sucks but it has to be done, if we are inserting at
4375f3465ca4SJosef Bacik 		 * the end of the leaf only insert 1 of the items, since we
4376f3465ca4SJosef Bacik 		 * have no way of knowing whats on the next leaf and we'd have
4377f3465ca4SJosef Bacik 		 * to drop our current locks to figure it out
4378f3465ca4SJosef Bacik 		 */
4379f3465ca4SJosef Bacik 		nr = 1;
4380f3465ca4SJosef Bacik 	}
4381f3465ca4SJosef Bacik 
4382f3465ca4SJosef Bacik 	/* setup the item for the new data */
4383f3465ca4SJosef Bacik 	for (i = 0; i < nr; i++) {
4384f3465ca4SJosef Bacik 		btrfs_cpu_key_to_disk(&disk_key, cpu_key + i);
4385f3465ca4SJosef Bacik 		btrfs_set_item_key(leaf, &disk_key, slot + i);
4386f3465ca4SJosef Bacik 		item = btrfs_item_nr(leaf, slot + i);
4387cfed81a0SChris Mason 		btrfs_set_token_item_offset(leaf, item,
4388cfed81a0SChris Mason 					    data_end - data_size[i], &token);
4389f3465ca4SJosef Bacik 		data_end -= data_size[i];
4390cfed81a0SChris Mason 		btrfs_set_token_item_size(leaf, item, data_size[i], &token);
4391f3465ca4SJosef Bacik 	}
4392f3465ca4SJosef Bacik 	btrfs_set_header_nritems(leaf, nritems + nr);
4393f3465ca4SJosef Bacik 	btrfs_mark_buffer_dirty(leaf);
4394f3465ca4SJosef Bacik 
4395f3465ca4SJosef Bacik 	ret = 0;
4396f3465ca4SJosef Bacik 	if (slot == 0) {
4397f3465ca4SJosef Bacik 		btrfs_cpu_key_to_disk(&disk_key, cpu_key);
4398143bede5SJeff Mahoney 		fixup_low_keys(trans, root, path, &disk_key, 1);
4399f3465ca4SJosef Bacik 	}
4400f3465ca4SJosef Bacik 
4401f3465ca4SJosef Bacik 	if (btrfs_leaf_free_space(root, leaf) < 0) {
4402f3465ca4SJosef Bacik 		btrfs_print_leaf(root, leaf);
4403f3465ca4SJosef Bacik 		BUG();
4404f3465ca4SJosef Bacik 	}
4405f3465ca4SJosef Bacik out:
4406f3465ca4SJosef Bacik 	if (!ret)
4407f3465ca4SJosef Bacik 		ret = nr;
4408f3465ca4SJosef Bacik 	return ret;
4409f3465ca4SJosef Bacik }
4410f3465ca4SJosef Bacik 
4411f3465ca4SJosef Bacik /*
441244871b1bSChris Mason  * this is a helper for btrfs_insert_empty_items, the main goal here is
441344871b1bSChris Mason  * to save stack depth by doing the bulk of the work in a function
441444871b1bSChris Mason  * that doesn't call btrfs_search_slot
441574123bd7SChris Mason  */
4416143bede5SJeff Mahoney void setup_items_for_insert(struct btrfs_trans_handle *trans,
441744871b1bSChris Mason 			    struct btrfs_root *root, struct btrfs_path *path,
44189c58309dSChris Mason 			    struct btrfs_key *cpu_key, u32 *data_size,
441944871b1bSChris Mason 			    u32 total_data, u32 total_size, int nr)
4420be0e5c09SChris Mason {
44215f39d397SChris Mason 	struct btrfs_item *item;
44229c58309dSChris Mason 	int i;
44237518a238SChris Mason 	u32 nritems;
4424be0e5c09SChris Mason 	unsigned int data_end;
4425e2fa7227SChris Mason 	struct btrfs_disk_key disk_key;
442644871b1bSChris Mason 	struct extent_buffer *leaf;
442744871b1bSChris Mason 	int slot;
4428cfed81a0SChris Mason 	struct btrfs_map_token token;
4429cfed81a0SChris Mason 
4430cfed81a0SChris Mason 	btrfs_init_map_token(&token);
4431e2fa7227SChris Mason 
44325f39d397SChris Mason 	leaf = path->nodes[0];
443344871b1bSChris Mason 	slot = path->slots[0];
443474123bd7SChris Mason 
44355f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
4436123abc88SChris Mason 	data_end = leaf_data_end(root, leaf);
4437eb60ceacSChris Mason 
4438f25956ccSChris Mason 	if (btrfs_leaf_free_space(root, leaf) < total_size) {
44393326d1b0SChris Mason 		btrfs_print_leaf(root, leaf);
4440d397712bSChris Mason 		printk(KERN_CRIT "not enough freespace need %u have %d\n",
44419c58309dSChris Mason 		       total_size, btrfs_leaf_free_space(root, leaf));
4442be0e5c09SChris Mason 		BUG();
4443d4dbff95SChris Mason 	}
44445f39d397SChris Mason 
4445be0e5c09SChris Mason 	if (slot != nritems) {
44465f39d397SChris Mason 		unsigned int old_data = btrfs_item_end_nr(leaf, slot);
4447be0e5c09SChris Mason 
44485f39d397SChris Mason 		if (old_data < data_end) {
44495f39d397SChris Mason 			btrfs_print_leaf(root, leaf);
4450d397712bSChris Mason 			printk(KERN_CRIT "slot %d old_data %d data_end %d\n",
44515f39d397SChris Mason 			       slot, old_data, data_end);
44525f39d397SChris Mason 			BUG_ON(1);
44535f39d397SChris Mason 		}
4454be0e5c09SChris Mason 		/*
4455be0e5c09SChris Mason 		 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4456be0e5c09SChris Mason 		 */
4457be0e5c09SChris Mason 		/* first correct the data pointers */
44580783fcfcSChris Mason 		for (i = slot; i < nritems; i++) {
44595f39d397SChris Mason 			u32 ioff;
4460db94535dSChris Mason 
44615f39d397SChris Mason 			item = btrfs_item_nr(leaf, i);
4462cfed81a0SChris Mason 			ioff = btrfs_token_item_offset(leaf, item, &token);
4463cfed81a0SChris Mason 			btrfs_set_token_item_offset(leaf, item,
4464cfed81a0SChris Mason 						    ioff - total_data, &token);
44650783fcfcSChris Mason 		}
4466be0e5c09SChris Mason 		/* shift the items */
44679c58309dSChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + nr),
44685f39d397SChris Mason 			      btrfs_item_nr_offset(slot),
44690783fcfcSChris Mason 			      (nritems - slot) * sizeof(struct btrfs_item));
4470be0e5c09SChris Mason 
4471be0e5c09SChris Mason 		/* shift the data */
44725f39d397SChris Mason 		memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
44739c58309dSChris Mason 			      data_end - total_data, btrfs_leaf_data(leaf) +
4474be0e5c09SChris Mason 			      data_end, old_data - data_end);
4475be0e5c09SChris Mason 		data_end = old_data;
4476be0e5c09SChris Mason 	}
44775f39d397SChris Mason 
447862e2749eSChris Mason 	/* setup the item for the new data */
44799c58309dSChris Mason 	for (i = 0; i < nr; i++) {
44809c58309dSChris Mason 		btrfs_cpu_key_to_disk(&disk_key, cpu_key + i);
44819c58309dSChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot + i);
44829c58309dSChris Mason 		item = btrfs_item_nr(leaf, slot + i);
4483cfed81a0SChris Mason 		btrfs_set_token_item_offset(leaf, item,
4484cfed81a0SChris Mason 					    data_end - data_size[i], &token);
44859c58309dSChris Mason 		data_end -= data_size[i];
4486cfed81a0SChris Mason 		btrfs_set_token_item_size(leaf, item, data_size[i], &token);
44879c58309dSChris Mason 	}
448844871b1bSChris Mason 
44899c58309dSChris Mason 	btrfs_set_header_nritems(leaf, nritems + nr);
4490aa5d6bedSChris Mason 
44915a01a2e3SChris Mason 	if (slot == 0) {
44925a01a2e3SChris Mason 		btrfs_cpu_key_to_disk(&disk_key, cpu_key);
4493143bede5SJeff Mahoney 		fixup_low_keys(trans, root, path, &disk_key, 1);
44945a01a2e3SChris Mason 	}
4495b9473439SChris Mason 	btrfs_unlock_up_safe(path, 1);
4496b9473439SChris Mason 	btrfs_mark_buffer_dirty(leaf);
4497aa5d6bedSChris Mason 
44985f39d397SChris Mason 	if (btrfs_leaf_free_space(root, leaf) < 0) {
44995f39d397SChris Mason 		btrfs_print_leaf(root, leaf);
4500be0e5c09SChris Mason 		BUG();
45015f39d397SChris Mason 	}
450244871b1bSChris Mason }
450344871b1bSChris Mason 
450444871b1bSChris Mason /*
450544871b1bSChris Mason  * Given a key and some data, insert items into the tree.
450644871b1bSChris Mason  * This does all the path init required, making room in the tree if needed.
450744871b1bSChris Mason  */
450844871b1bSChris Mason int btrfs_insert_empty_items(struct btrfs_trans_handle *trans,
450944871b1bSChris Mason 			    struct btrfs_root *root,
451044871b1bSChris Mason 			    struct btrfs_path *path,
451144871b1bSChris Mason 			    struct btrfs_key *cpu_key, u32 *data_size,
451244871b1bSChris Mason 			    int nr)
451344871b1bSChris Mason {
451444871b1bSChris Mason 	int ret = 0;
451544871b1bSChris Mason 	int slot;
451644871b1bSChris Mason 	int i;
451744871b1bSChris Mason 	u32 total_size = 0;
451844871b1bSChris Mason 	u32 total_data = 0;
451944871b1bSChris Mason 
452044871b1bSChris Mason 	for (i = 0; i < nr; i++)
452144871b1bSChris Mason 		total_data += data_size[i];
452244871b1bSChris Mason 
452344871b1bSChris Mason 	total_size = total_data + (nr * sizeof(struct btrfs_item));
452444871b1bSChris Mason 	ret = btrfs_search_slot(trans, root, cpu_key, path, total_size, 1);
452544871b1bSChris Mason 	if (ret == 0)
452644871b1bSChris Mason 		return -EEXIST;
452744871b1bSChris Mason 	if (ret < 0)
4528143bede5SJeff Mahoney 		return ret;
452944871b1bSChris Mason 
453044871b1bSChris Mason 	slot = path->slots[0];
453144871b1bSChris Mason 	BUG_ON(slot < 0);
453244871b1bSChris Mason 
4533143bede5SJeff Mahoney 	setup_items_for_insert(trans, root, path, cpu_key, data_size,
453444871b1bSChris Mason 			       total_data, total_size, nr);
4535143bede5SJeff Mahoney 	return 0;
453662e2749eSChris Mason }
453762e2749eSChris Mason 
453862e2749eSChris Mason /*
453962e2749eSChris Mason  * Given a key and some data, insert an item into the tree.
454062e2749eSChris Mason  * This does all the path init required, making room in the tree if needed.
454162e2749eSChris Mason  */
4542e089f05cSChris Mason int btrfs_insert_item(struct btrfs_trans_handle *trans, struct btrfs_root
4543e089f05cSChris Mason 		      *root, struct btrfs_key *cpu_key, void *data, u32
4544e089f05cSChris Mason 		      data_size)
454562e2749eSChris Mason {
454662e2749eSChris Mason 	int ret = 0;
45472c90e5d6SChris Mason 	struct btrfs_path *path;
45485f39d397SChris Mason 	struct extent_buffer *leaf;
45495f39d397SChris Mason 	unsigned long ptr;
455062e2749eSChris Mason 
45512c90e5d6SChris Mason 	path = btrfs_alloc_path();
4552db5b493aSTsutomu Itoh 	if (!path)
4553db5b493aSTsutomu Itoh 		return -ENOMEM;
45542c90e5d6SChris Mason 	ret = btrfs_insert_empty_item(trans, root, path, cpu_key, data_size);
455562e2749eSChris Mason 	if (!ret) {
45565f39d397SChris Mason 		leaf = path->nodes[0];
45575f39d397SChris Mason 		ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
45585f39d397SChris Mason 		write_extent_buffer(leaf, data, ptr, data_size);
45595f39d397SChris Mason 		btrfs_mark_buffer_dirty(leaf);
456062e2749eSChris Mason 	}
45612c90e5d6SChris Mason 	btrfs_free_path(path);
4562aa5d6bedSChris Mason 	return ret;
4563be0e5c09SChris Mason }
4564be0e5c09SChris Mason 
456574123bd7SChris Mason /*
45665de08d7dSChris Mason  * delete the pointer from a given node.
456774123bd7SChris Mason  *
4568d352ac68SChris Mason  * the tree should have been previously balanced so the deletion does not
4569d352ac68SChris Mason  * empty a node.
457074123bd7SChris Mason  */
4571143bede5SJeff Mahoney static void del_ptr(struct btrfs_trans_handle *trans, struct btrfs_root *root,
4572f3ea38daSJan Schmidt 		    struct btrfs_path *path, int level, int slot,
4573f3ea38daSJan Schmidt 		    int tree_mod_log)
4574be0e5c09SChris Mason {
45755f39d397SChris Mason 	struct extent_buffer *parent = path->nodes[level];
45767518a238SChris Mason 	u32 nritems;
4577f3ea38daSJan Schmidt 	int ret;
4578be0e5c09SChris Mason 
45795f39d397SChris Mason 	nritems = btrfs_header_nritems(parent);
4580be0e5c09SChris Mason 	if (slot != nritems - 1) {
4581f3ea38daSJan Schmidt 		if (tree_mod_log && level)
4582f3ea38daSJan Schmidt 			tree_mod_log_eb_move(root->fs_info, parent, slot,
4583f3ea38daSJan Schmidt 					     slot + 1, nritems - slot - 1);
45845f39d397SChris Mason 		memmove_extent_buffer(parent,
45855f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot),
45865f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot + 1),
4587d6025579SChris Mason 			      sizeof(struct btrfs_key_ptr) *
4588d6025579SChris Mason 			      (nritems - slot - 1));
4589f395694cSJan Schmidt 	} else if (tree_mod_log && level) {
4590f3ea38daSJan Schmidt 		ret = tree_mod_log_insert_key(root->fs_info, parent, slot,
4591f3ea38daSJan Schmidt 					      MOD_LOG_KEY_REMOVE);
4592f3ea38daSJan Schmidt 		BUG_ON(ret < 0);
4593be0e5c09SChris Mason 	}
4594f3ea38daSJan Schmidt 
45957518a238SChris Mason 	nritems--;
45965f39d397SChris Mason 	btrfs_set_header_nritems(parent, nritems);
45977518a238SChris Mason 	if (nritems == 0 && parent == root->node) {
45985f39d397SChris Mason 		BUG_ON(btrfs_header_level(root->node) != 1);
4599eb60ceacSChris Mason 		/* just turn the root into a leaf and break */
46005f39d397SChris Mason 		btrfs_set_header_level(root->node, 0);
4601bb803951SChris Mason 	} else if (slot == 0) {
46025f39d397SChris Mason 		struct btrfs_disk_key disk_key;
46035f39d397SChris Mason 
46045f39d397SChris Mason 		btrfs_node_key(parent, &disk_key, 0);
4605143bede5SJeff Mahoney 		fixup_low_keys(trans, root, path, &disk_key, level + 1);
4606be0e5c09SChris Mason 	}
4607d6025579SChris Mason 	btrfs_mark_buffer_dirty(parent);
4608be0e5c09SChris Mason }
4609be0e5c09SChris Mason 
461074123bd7SChris Mason /*
4611323ac95bSChris Mason  * a helper function to delete the leaf pointed to by path->slots[1] and
46125d4f98a2SYan Zheng  * path->nodes[1].
4613323ac95bSChris Mason  *
4614323ac95bSChris Mason  * This deletes the pointer in path->nodes[1] and frees the leaf
4615323ac95bSChris Mason  * block extent.  zero is returned if it all worked out, < 0 otherwise.
4616323ac95bSChris Mason  *
4617323ac95bSChris Mason  * The path must have already been setup for deleting the leaf, including
4618323ac95bSChris Mason  * all the proper balancing.  path->nodes[1] must be locked.
4619323ac95bSChris Mason  */
4620143bede5SJeff Mahoney static noinline void btrfs_del_leaf(struct btrfs_trans_handle *trans,
4621323ac95bSChris Mason 				    struct btrfs_root *root,
46225d4f98a2SYan Zheng 				    struct btrfs_path *path,
46235d4f98a2SYan Zheng 				    struct extent_buffer *leaf)
4624323ac95bSChris Mason {
46255d4f98a2SYan Zheng 	WARN_ON(btrfs_header_generation(leaf) != trans->transid);
4626f3ea38daSJan Schmidt 	del_ptr(trans, root, path, 1, path->slots[1], 1);
4627323ac95bSChris Mason 
46284d081c41SChris Mason 	/*
46294d081c41SChris Mason 	 * btrfs_free_extent is expensive, we want to make sure we
46304d081c41SChris Mason 	 * aren't holding any locks when we call it
46314d081c41SChris Mason 	 */
46324d081c41SChris Mason 	btrfs_unlock_up_safe(path, 0);
46334d081c41SChris Mason 
4634f0486c68SYan, Zheng 	root_sub_used(root, leaf->len);
4635f0486c68SYan, Zheng 
46363083ee2eSJosef Bacik 	extent_buffer_get(leaf);
46375581a51aSJan Schmidt 	btrfs_free_tree_block(trans, root, leaf, 0, 1);
46383083ee2eSJosef Bacik 	free_extent_buffer_stale(leaf);
4639323ac95bSChris Mason }
4640323ac95bSChris Mason /*
464174123bd7SChris Mason  * delete the item at the leaf level in path.  If that empties
464274123bd7SChris Mason  * the leaf, remove it from the tree
464374123bd7SChris Mason  */
464485e21bacSChris Mason int btrfs_del_items(struct btrfs_trans_handle *trans, struct btrfs_root *root,
464585e21bacSChris Mason 		    struct btrfs_path *path, int slot, int nr)
4646be0e5c09SChris Mason {
46475f39d397SChris Mason 	struct extent_buffer *leaf;
46485f39d397SChris Mason 	struct btrfs_item *item;
464985e21bacSChris Mason 	int last_off;
465085e21bacSChris Mason 	int dsize = 0;
4651aa5d6bedSChris Mason 	int ret = 0;
4652aa5d6bedSChris Mason 	int wret;
465385e21bacSChris Mason 	int i;
46547518a238SChris Mason 	u32 nritems;
4655cfed81a0SChris Mason 	struct btrfs_map_token token;
4656cfed81a0SChris Mason 
4657cfed81a0SChris Mason 	btrfs_init_map_token(&token);
4658be0e5c09SChris Mason 
46595f39d397SChris Mason 	leaf = path->nodes[0];
466085e21bacSChris Mason 	last_off = btrfs_item_offset_nr(leaf, slot + nr - 1);
466185e21bacSChris Mason 
466285e21bacSChris Mason 	for (i = 0; i < nr; i++)
466385e21bacSChris Mason 		dsize += btrfs_item_size_nr(leaf, slot + i);
466485e21bacSChris Mason 
46655f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
4666be0e5c09SChris Mason 
466785e21bacSChris Mason 	if (slot + nr != nritems) {
4668123abc88SChris Mason 		int data_end = leaf_data_end(root, leaf);
46695f39d397SChris Mason 
46705f39d397SChris Mason 		memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
4671d6025579SChris Mason 			      data_end + dsize,
4672123abc88SChris Mason 			      btrfs_leaf_data(leaf) + data_end,
467385e21bacSChris Mason 			      last_off - data_end);
46745f39d397SChris Mason 
467585e21bacSChris Mason 		for (i = slot + nr; i < nritems; i++) {
46765f39d397SChris Mason 			u32 ioff;
4677db94535dSChris Mason 
46785f39d397SChris Mason 			item = btrfs_item_nr(leaf, i);
4679cfed81a0SChris Mason 			ioff = btrfs_token_item_offset(leaf, item, &token);
4680cfed81a0SChris Mason 			btrfs_set_token_item_offset(leaf, item,
4681cfed81a0SChris Mason 						    ioff + dsize, &token);
46820783fcfcSChris Mason 		}
4683db94535dSChris Mason 
46845f39d397SChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot),
468585e21bacSChris Mason 			      btrfs_item_nr_offset(slot + nr),
46860783fcfcSChris Mason 			      sizeof(struct btrfs_item) *
468785e21bacSChris Mason 			      (nritems - slot - nr));
4688be0e5c09SChris Mason 	}
468985e21bacSChris Mason 	btrfs_set_header_nritems(leaf, nritems - nr);
469085e21bacSChris Mason 	nritems -= nr;
46915f39d397SChris Mason 
469274123bd7SChris Mason 	/* delete the leaf if we've emptied it */
46937518a238SChris Mason 	if (nritems == 0) {
46945f39d397SChris Mason 		if (leaf == root->node) {
46955f39d397SChris Mason 			btrfs_set_header_level(leaf, 0);
46969a8dd150SChris Mason 		} else {
4697f0486c68SYan, Zheng 			btrfs_set_path_blocking(path);
4698f0486c68SYan, Zheng 			clean_tree_block(trans, root, leaf);
4699143bede5SJeff Mahoney 			btrfs_del_leaf(trans, root, path, leaf);
47009a8dd150SChris Mason 		}
4701be0e5c09SChris Mason 	} else {
47027518a238SChris Mason 		int used = leaf_space_used(leaf, 0, nritems);
4703aa5d6bedSChris Mason 		if (slot == 0) {
47045f39d397SChris Mason 			struct btrfs_disk_key disk_key;
47055f39d397SChris Mason 
47065f39d397SChris Mason 			btrfs_item_key(leaf, &disk_key, 0);
4707143bede5SJeff Mahoney 			fixup_low_keys(trans, root, path, &disk_key, 1);
4708aa5d6bedSChris Mason 		}
4709aa5d6bedSChris Mason 
471074123bd7SChris Mason 		/* delete the leaf if it is mostly empty */
4711d717aa1dSYan Zheng 		if (used < BTRFS_LEAF_DATA_SIZE(root) / 3) {
4712be0e5c09SChris Mason 			/* push_leaf_left fixes the path.
4713be0e5c09SChris Mason 			 * make sure the path still points to our leaf
4714be0e5c09SChris Mason 			 * for possible call to del_ptr below
4715be0e5c09SChris Mason 			 */
47164920c9acSChris Mason 			slot = path->slots[1];
47175f39d397SChris Mason 			extent_buffer_get(leaf);
47185f39d397SChris Mason 
4719b9473439SChris Mason 			btrfs_set_path_blocking(path);
472099d8f83cSChris Mason 			wret = push_leaf_left(trans, root, path, 1, 1,
472199d8f83cSChris Mason 					      1, (u32)-1);
472254aa1f4dSChris Mason 			if (wret < 0 && wret != -ENOSPC)
4723aa5d6bedSChris Mason 				ret = wret;
47245f39d397SChris Mason 
47255f39d397SChris Mason 			if (path->nodes[0] == leaf &&
47265f39d397SChris Mason 			    btrfs_header_nritems(leaf)) {
472799d8f83cSChris Mason 				wret = push_leaf_right(trans, root, path, 1,
472899d8f83cSChris Mason 						       1, 1, 0);
472954aa1f4dSChris Mason 				if (wret < 0 && wret != -ENOSPC)
4730aa5d6bedSChris Mason 					ret = wret;
4731aa5d6bedSChris Mason 			}
47325f39d397SChris Mason 
47335f39d397SChris Mason 			if (btrfs_header_nritems(leaf) == 0) {
4734323ac95bSChris Mason 				path->slots[1] = slot;
4735143bede5SJeff Mahoney 				btrfs_del_leaf(trans, root, path, leaf);
47365f39d397SChris Mason 				free_extent_buffer(leaf);
4737143bede5SJeff Mahoney 				ret = 0;
47385de08d7dSChris Mason 			} else {
4739925baeddSChris Mason 				/* if we're still in the path, make sure
4740925baeddSChris Mason 				 * we're dirty.  Otherwise, one of the
4741925baeddSChris Mason 				 * push_leaf functions must have already
4742925baeddSChris Mason 				 * dirtied this buffer
4743925baeddSChris Mason 				 */
4744925baeddSChris Mason 				if (path->nodes[0] == leaf)
47455f39d397SChris Mason 					btrfs_mark_buffer_dirty(leaf);
47465f39d397SChris Mason 				free_extent_buffer(leaf);
4747be0e5c09SChris Mason 			}
4748d5719762SChris Mason 		} else {
47495f39d397SChris Mason 			btrfs_mark_buffer_dirty(leaf);
4750be0e5c09SChris Mason 		}
47519a8dd150SChris Mason 	}
4752aa5d6bedSChris Mason 	return ret;
47539a8dd150SChris Mason }
47549a8dd150SChris Mason 
475597571fd0SChris Mason /*
4756925baeddSChris Mason  * search the tree again to find a leaf with lesser keys
47577bb86316SChris Mason  * returns 0 if it found something or 1 if there are no lesser leaves.
47587bb86316SChris Mason  * returns < 0 on io errors.
4759d352ac68SChris Mason  *
4760d352ac68SChris Mason  * This may release the path, and so you may lose any locks held at the
4761d352ac68SChris Mason  * time you call it.
47627bb86316SChris Mason  */
47637bb86316SChris Mason int btrfs_prev_leaf(struct btrfs_root *root, struct btrfs_path *path)
47647bb86316SChris Mason {
4765925baeddSChris Mason 	struct btrfs_key key;
4766925baeddSChris Mason 	struct btrfs_disk_key found_key;
4767925baeddSChris Mason 	int ret;
47687bb86316SChris Mason 
4769925baeddSChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, 0);
4770925baeddSChris Mason 
4771925baeddSChris Mason 	if (key.offset > 0)
4772925baeddSChris Mason 		key.offset--;
4773925baeddSChris Mason 	else if (key.type > 0)
4774925baeddSChris Mason 		key.type--;
4775925baeddSChris Mason 	else if (key.objectid > 0)
4776925baeddSChris Mason 		key.objectid--;
4777925baeddSChris Mason 	else
47787bb86316SChris Mason 		return 1;
47797bb86316SChris Mason 
4780b3b4aa74SDavid Sterba 	btrfs_release_path(path);
4781925baeddSChris Mason 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4782925baeddSChris Mason 	if (ret < 0)
4783925baeddSChris Mason 		return ret;
4784925baeddSChris Mason 	btrfs_item_key(path->nodes[0], &found_key, 0);
4785925baeddSChris Mason 	ret = comp_keys(&found_key, &key);
4786925baeddSChris Mason 	if (ret < 0)
47877bb86316SChris Mason 		return 0;
4788925baeddSChris Mason 	return 1;
47897bb86316SChris Mason }
47907bb86316SChris Mason 
47913f157a2fSChris Mason /*
47923f157a2fSChris Mason  * A helper function to walk down the tree starting at min_key, and looking
47933f157a2fSChris Mason  * for nodes or leaves that are either in cache or have a minimum
4794d352ac68SChris Mason  * transaction id.  This is used by the btree defrag code, and tree logging
47953f157a2fSChris Mason  *
47963f157a2fSChris Mason  * This does not cow, but it does stuff the starting key it finds back
47973f157a2fSChris Mason  * into min_key, so you can call btrfs_search_slot with cow=1 on the
47983f157a2fSChris Mason  * key and get a writable path.
47993f157a2fSChris Mason  *
48003f157a2fSChris Mason  * This does lock as it descends, and path->keep_locks should be set
48013f157a2fSChris Mason  * to 1 by the caller.
48023f157a2fSChris Mason  *
48033f157a2fSChris Mason  * This honors path->lowest_level to prevent descent past a given level
48043f157a2fSChris Mason  * of the tree.
48053f157a2fSChris Mason  *
4806d352ac68SChris Mason  * min_trans indicates the oldest transaction that you are interested
4807d352ac68SChris Mason  * in walking through.  Any nodes or leaves older than min_trans are
4808d352ac68SChris Mason  * skipped over (without reading them).
4809d352ac68SChris Mason  *
48103f157a2fSChris Mason  * returns zero if something useful was found, < 0 on error and 1 if there
48113f157a2fSChris Mason  * was nothing in the tree that matched the search criteria.
48123f157a2fSChris Mason  */
48133f157a2fSChris Mason int btrfs_search_forward(struct btrfs_root *root, struct btrfs_key *min_key,
4814e02119d5SChris Mason 			 struct btrfs_key *max_key,
48153f157a2fSChris Mason 			 struct btrfs_path *path, int cache_only,
48163f157a2fSChris Mason 			 u64 min_trans)
48173f157a2fSChris Mason {
48183f157a2fSChris Mason 	struct extent_buffer *cur;
48193f157a2fSChris Mason 	struct btrfs_key found_key;
48203f157a2fSChris Mason 	int slot;
48219652480bSYan 	int sret;
48223f157a2fSChris Mason 	u32 nritems;
48233f157a2fSChris Mason 	int level;
48243f157a2fSChris Mason 	int ret = 1;
48253f157a2fSChris Mason 
4826934d375bSChris Mason 	WARN_ON(!path->keep_locks);
48273f157a2fSChris Mason again:
4828bd681513SChris Mason 	cur = btrfs_read_lock_root_node(root);
48293f157a2fSChris Mason 	level = btrfs_header_level(cur);
4830e02119d5SChris Mason 	WARN_ON(path->nodes[level]);
48313f157a2fSChris Mason 	path->nodes[level] = cur;
4832bd681513SChris Mason 	path->locks[level] = BTRFS_READ_LOCK;
48333f157a2fSChris Mason 
48343f157a2fSChris Mason 	if (btrfs_header_generation(cur) < min_trans) {
48353f157a2fSChris Mason 		ret = 1;
48363f157a2fSChris Mason 		goto out;
48373f157a2fSChris Mason 	}
48383f157a2fSChris Mason 	while (1) {
48393f157a2fSChris Mason 		nritems = btrfs_header_nritems(cur);
48403f157a2fSChris Mason 		level = btrfs_header_level(cur);
48419652480bSYan 		sret = bin_search(cur, min_key, level, &slot);
48423f157a2fSChris Mason 
4843323ac95bSChris Mason 		/* at the lowest level, we're done, setup the path and exit */
4844323ac95bSChris Mason 		if (level == path->lowest_level) {
4845e02119d5SChris Mason 			if (slot >= nritems)
4846e02119d5SChris Mason 				goto find_next_key;
48473f157a2fSChris Mason 			ret = 0;
48483f157a2fSChris Mason 			path->slots[level] = slot;
48493f157a2fSChris Mason 			btrfs_item_key_to_cpu(cur, &found_key, slot);
48503f157a2fSChris Mason 			goto out;
48513f157a2fSChris Mason 		}
48529652480bSYan 		if (sret && slot > 0)
48539652480bSYan 			slot--;
48543f157a2fSChris Mason 		/*
48553f157a2fSChris Mason 		 * check this node pointer against the cache_only and
48563f157a2fSChris Mason 		 * min_trans parameters.  If it isn't in cache or is too
48573f157a2fSChris Mason 		 * old, skip to the next one.
48583f157a2fSChris Mason 		 */
48593f157a2fSChris Mason 		while (slot < nritems) {
48603f157a2fSChris Mason 			u64 blockptr;
48613f157a2fSChris Mason 			u64 gen;
48623f157a2fSChris Mason 			struct extent_buffer *tmp;
4863e02119d5SChris Mason 			struct btrfs_disk_key disk_key;
4864e02119d5SChris Mason 
48653f157a2fSChris Mason 			blockptr = btrfs_node_blockptr(cur, slot);
48663f157a2fSChris Mason 			gen = btrfs_node_ptr_generation(cur, slot);
48673f157a2fSChris Mason 			if (gen < min_trans) {
48683f157a2fSChris Mason 				slot++;
48693f157a2fSChris Mason 				continue;
48703f157a2fSChris Mason 			}
48713f157a2fSChris Mason 			if (!cache_only)
48723f157a2fSChris Mason 				break;
48733f157a2fSChris Mason 
4874e02119d5SChris Mason 			if (max_key) {
4875e02119d5SChris Mason 				btrfs_node_key(cur, &disk_key, slot);
4876e02119d5SChris Mason 				if (comp_keys(&disk_key, max_key) >= 0) {
4877e02119d5SChris Mason 					ret = 1;
4878e02119d5SChris Mason 					goto out;
4879e02119d5SChris Mason 				}
4880e02119d5SChris Mason 			}
4881e02119d5SChris Mason 
48823f157a2fSChris Mason 			tmp = btrfs_find_tree_block(root, blockptr,
48833f157a2fSChris Mason 					    btrfs_level_size(root, level - 1));
48843f157a2fSChris Mason 
4885b9fab919SChris Mason 			if (tmp && btrfs_buffer_uptodate(tmp, gen, 1) > 0) {
48863f157a2fSChris Mason 				free_extent_buffer(tmp);
48873f157a2fSChris Mason 				break;
48883f157a2fSChris Mason 			}
48893f157a2fSChris Mason 			if (tmp)
48903f157a2fSChris Mason 				free_extent_buffer(tmp);
48913f157a2fSChris Mason 			slot++;
48923f157a2fSChris Mason 		}
4893e02119d5SChris Mason find_next_key:
48943f157a2fSChris Mason 		/*
48953f157a2fSChris Mason 		 * we didn't find a candidate key in this node, walk forward
48963f157a2fSChris Mason 		 * and find another one
48973f157a2fSChris Mason 		 */
48983f157a2fSChris Mason 		if (slot >= nritems) {
4899e02119d5SChris Mason 			path->slots[level] = slot;
4900b4ce94deSChris Mason 			btrfs_set_path_blocking(path);
4901e02119d5SChris Mason 			sret = btrfs_find_next_key(root, path, min_key, level,
49023f157a2fSChris Mason 						  cache_only, min_trans);
4903e02119d5SChris Mason 			if (sret == 0) {
4904b3b4aa74SDavid Sterba 				btrfs_release_path(path);
49053f157a2fSChris Mason 				goto again;
49063f157a2fSChris Mason 			} else {
49073f157a2fSChris Mason 				goto out;
49083f157a2fSChris Mason 			}
49093f157a2fSChris Mason 		}
49103f157a2fSChris Mason 		/* save our key for returning back */
49113f157a2fSChris Mason 		btrfs_node_key_to_cpu(cur, &found_key, slot);
49123f157a2fSChris Mason 		path->slots[level] = slot;
49133f157a2fSChris Mason 		if (level == path->lowest_level) {
49143f157a2fSChris Mason 			ret = 0;
4915f7c79f30SChris Mason 			unlock_up(path, level, 1, 0, NULL);
49163f157a2fSChris Mason 			goto out;
49173f157a2fSChris Mason 		}
4918b4ce94deSChris Mason 		btrfs_set_path_blocking(path);
49193f157a2fSChris Mason 		cur = read_node_slot(root, cur, slot);
492079787eaaSJeff Mahoney 		BUG_ON(!cur); /* -ENOMEM */
49213f157a2fSChris Mason 
4922bd681513SChris Mason 		btrfs_tree_read_lock(cur);
4923b4ce94deSChris Mason 
4924bd681513SChris Mason 		path->locks[level - 1] = BTRFS_READ_LOCK;
49253f157a2fSChris Mason 		path->nodes[level - 1] = cur;
4926f7c79f30SChris Mason 		unlock_up(path, level, 1, 0, NULL);
4927bd681513SChris Mason 		btrfs_clear_path_blocking(path, NULL, 0);
49283f157a2fSChris Mason 	}
49293f157a2fSChris Mason out:
49303f157a2fSChris Mason 	if (ret == 0)
49313f157a2fSChris Mason 		memcpy(min_key, &found_key, sizeof(found_key));
4932b4ce94deSChris Mason 	btrfs_set_path_blocking(path);
49333f157a2fSChris Mason 	return ret;
49343f157a2fSChris Mason }
49353f157a2fSChris Mason 
49363f157a2fSChris Mason /*
49373f157a2fSChris Mason  * this is similar to btrfs_next_leaf, but does not try to preserve
49383f157a2fSChris Mason  * and fixup the path.  It looks for and returns the next key in the
49393f157a2fSChris Mason  * tree based on the current path and the cache_only and min_trans
49403f157a2fSChris Mason  * parameters.
49413f157a2fSChris Mason  *
49423f157a2fSChris Mason  * 0 is returned if another key is found, < 0 if there are any errors
49433f157a2fSChris Mason  * and 1 is returned if there are no higher keys in the tree
49443f157a2fSChris Mason  *
49453f157a2fSChris Mason  * path->keep_locks should be set to 1 on the search made before
49463f157a2fSChris Mason  * calling this function.
49473f157a2fSChris Mason  */
4948e7a84565SChris Mason int btrfs_find_next_key(struct btrfs_root *root, struct btrfs_path *path,
494933c66f43SYan Zheng 			struct btrfs_key *key, int level,
49503f157a2fSChris Mason 			int cache_only, u64 min_trans)
4951e7a84565SChris Mason {
4952e7a84565SChris Mason 	int slot;
4953e7a84565SChris Mason 	struct extent_buffer *c;
4954e7a84565SChris Mason 
4955934d375bSChris Mason 	WARN_ON(!path->keep_locks);
4956e7a84565SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
4957e7a84565SChris Mason 		if (!path->nodes[level])
4958e7a84565SChris Mason 			return 1;
4959e7a84565SChris Mason 
4960e7a84565SChris Mason 		slot = path->slots[level] + 1;
4961e7a84565SChris Mason 		c = path->nodes[level];
49623f157a2fSChris Mason next:
4963e7a84565SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
496433c66f43SYan Zheng 			int ret;
496533c66f43SYan Zheng 			int orig_lowest;
496633c66f43SYan Zheng 			struct btrfs_key cur_key;
496733c66f43SYan Zheng 			if (level + 1 >= BTRFS_MAX_LEVEL ||
496833c66f43SYan Zheng 			    !path->nodes[level + 1])
4969e7a84565SChris Mason 				return 1;
497033c66f43SYan Zheng 
497133c66f43SYan Zheng 			if (path->locks[level + 1]) {
497233c66f43SYan Zheng 				level++;
4973e7a84565SChris Mason 				continue;
4974e7a84565SChris Mason 			}
497533c66f43SYan Zheng 
497633c66f43SYan Zheng 			slot = btrfs_header_nritems(c) - 1;
497733c66f43SYan Zheng 			if (level == 0)
497833c66f43SYan Zheng 				btrfs_item_key_to_cpu(c, &cur_key, slot);
497933c66f43SYan Zheng 			else
498033c66f43SYan Zheng 				btrfs_node_key_to_cpu(c, &cur_key, slot);
498133c66f43SYan Zheng 
498233c66f43SYan Zheng 			orig_lowest = path->lowest_level;
4983b3b4aa74SDavid Sterba 			btrfs_release_path(path);
498433c66f43SYan Zheng 			path->lowest_level = level;
498533c66f43SYan Zheng 			ret = btrfs_search_slot(NULL, root, &cur_key, path,
498633c66f43SYan Zheng 						0, 0);
498733c66f43SYan Zheng 			path->lowest_level = orig_lowest;
498833c66f43SYan Zheng 			if (ret < 0)
498933c66f43SYan Zheng 				return ret;
499033c66f43SYan Zheng 
499133c66f43SYan Zheng 			c = path->nodes[level];
499233c66f43SYan Zheng 			slot = path->slots[level];
499333c66f43SYan Zheng 			if (ret == 0)
499433c66f43SYan Zheng 				slot++;
499533c66f43SYan Zheng 			goto next;
499633c66f43SYan Zheng 		}
499733c66f43SYan Zheng 
4998e7a84565SChris Mason 		if (level == 0)
4999e7a84565SChris Mason 			btrfs_item_key_to_cpu(c, key, slot);
50003f157a2fSChris Mason 		else {
50013f157a2fSChris Mason 			u64 blockptr = btrfs_node_blockptr(c, slot);
50023f157a2fSChris Mason 			u64 gen = btrfs_node_ptr_generation(c, slot);
50033f157a2fSChris Mason 
50043f157a2fSChris Mason 			if (cache_only) {
50053f157a2fSChris Mason 				struct extent_buffer *cur;
50063f157a2fSChris Mason 				cur = btrfs_find_tree_block(root, blockptr,
50073f157a2fSChris Mason 					    btrfs_level_size(root, level - 1));
5008b9fab919SChris Mason 				if (!cur ||
5009b9fab919SChris Mason 				    btrfs_buffer_uptodate(cur, gen, 1) <= 0) {
50103f157a2fSChris Mason 					slot++;
50113f157a2fSChris Mason 					if (cur)
50123f157a2fSChris Mason 						free_extent_buffer(cur);
50133f157a2fSChris Mason 					goto next;
50143f157a2fSChris Mason 				}
50153f157a2fSChris Mason 				free_extent_buffer(cur);
50163f157a2fSChris Mason 			}
50173f157a2fSChris Mason 			if (gen < min_trans) {
50183f157a2fSChris Mason 				slot++;
50193f157a2fSChris Mason 				goto next;
50203f157a2fSChris Mason 			}
5021e7a84565SChris Mason 			btrfs_node_key_to_cpu(c, key, slot);
50223f157a2fSChris Mason 		}
5023e7a84565SChris Mason 		return 0;
5024e7a84565SChris Mason 	}
5025e7a84565SChris Mason 	return 1;
5026e7a84565SChris Mason }
5027e7a84565SChris Mason 
50287bb86316SChris Mason /*
5029925baeddSChris Mason  * search the tree again to find a leaf with greater keys
50300f70abe2SChris Mason  * returns 0 if it found something or 1 if there are no greater leaves.
50310f70abe2SChris Mason  * returns < 0 on io errors.
503297571fd0SChris Mason  */
5033234b63a0SChris Mason int btrfs_next_leaf(struct btrfs_root *root, struct btrfs_path *path)
5034d97e63b6SChris Mason {
50353d7806ecSJan Schmidt 	return btrfs_next_old_leaf(root, path, 0);
50363d7806ecSJan Schmidt }
50373d7806ecSJan Schmidt 
50383d7806ecSJan Schmidt int btrfs_next_old_leaf(struct btrfs_root *root, struct btrfs_path *path,
50393d7806ecSJan Schmidt 			u64 time_seq)
50403d7806ecSJan Schmidt {
5041d97e63b6SChris Mason 	int slot;
50428e73f275SChris Mason 	int level;
50435f39d397SChris Mason 	struct extent_buffer *c;
50448e73f275SChris Mason 	struct extent_buffer *next;
5045925baeddSChris Mason 	struct btrfs_key key;
5046925baeddSChris Mason 	u32 nritems;
5047925baeddSChris Mason 	int ret;
50488e73f275SChris Mason 	int old_spinning = path->leave_spinning;
5049bd681513SChris Mason 	int next_rw_lock = 0;
5050925baeddSChris Mason 
5051925baeddSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
5052d397712bSChris Mason 	if (nritems == 0)
5053925baeddSChris Mason 		return 1;
5054925baeddSChris Mason 
50558e73f275SChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, nritems - 1);
50568e73f275SChris Mason again:
50578e73f275SChris Mason 	level = 1;
50588e73f275SChris Mason 	next = NULL;
5059bd681513SChris Mason 	next_rw_lock = 0;
5060b3b4aa74SDavid Sterba 	btrfs_release_path(path);
50618e73f275SChris Mason 
5062a2135011SChris Mason 	path->keep_locks = 1;
50638e73f275SChris Mason 	path->leave_spinning = 1;
50648e73f275SChris Mason 
50653d7806ecSJan Schmidt 	if (time_seq)
50663d7806ecSJan Schmidt 		ret = btrfs_search_old_slot(root, &key, path, time_seq);
50673d7806ecSJan Schmidt 	else
5068925baeddSChris Mason 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5069925baeddSChris Mason 	path->keep_locks = 0;
5070925baeddSChris Mason 
5071925baeddSChris Mason 	if (ret < 0)
5072925baeddSChris Mason 		return ret;
5073925baeddSChris Mason 
5074a2135011SChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
5075168fd7d2SChris Mason 	/*
5076168fd7d2SChris Mason 	 * by releasing the path above we dropped all our locks.  A balance
5077168fd7d2SChris Mason 	 * could have added more items next to the key that used to be
5078168fd7d2SChris Mason 	 * at the very end of the block.  So, check again here and
5079168fd7d2SChris Mason 	 * advance the path if there are now more items available.
5080168fd7d2SChris Mason 	 */
5081a2135011SChris Mason 	if (nritems > 0 && path->slots[0] < nritems - 1) {
5082e457afecSYan Zheng 		if (ret == 0)
5083168fd7d2SChris Mason 			path->slots[0]++;
50848e73f275SChris Mason 		ret = 0;
5085925baeddSChris Mason 		goto done;
5086925baeddSChris Mason 	}
5087d97e63b6SChris Mason 
5088234b63a0SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
50898e73f275SChris Mason 		if (!path->nodes[level]) {
50908e73f275SChris Mason 			ret = 1;
50918e73f275SChris Mason 			goto done;
50928e73f275SChris Mason 		}
50935f39d397SChris Mason 
5094d97e63b6SChris Mason 		slot = path->slots[level] + 1;
5095d97e63b6SChris Mason 		c = path->nodes[level];
50965f39d397SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
5097d97e63b6SChris Mason 			level++;
50988e73f275SChris Mason 			if (level == BTRFS_MAX_LEVEL) {
50998e73f275SChris Mason 				ret = 1;
51008e73f275SChris Mason 				goto done;
51018e73f275SChris Mason 			}
5102d97e63b6SChris Mason 			continue;
5103d97e63b6SChris Mason 		}
51045f39d397SChris Mason 
5105925baeddSChris Mason 		if (next) {
5106bd681513SChris Mason 			btrfs_tree_unlock_rw(next, next_rw_lock);
51075f39d397SChris Mason 			free_extent_buffer(next);
5108925baeddSChris Mason 		}
51095f39d397SChris Mason 
51108e73f275SChris Mason 		next = c;
5111bd681513SChris Mason 		next_rw_lock = path->locks[level];
51128e73f275SChris Mason 		ret = read_block_for_search(NULL, root, path, &next, level,
51135d9e75c4SJan Schmidt 					    slot, &key, 0);
51148e73f275SChris Mason 		if (ret == -EAGAIN)
51158e73f275SChris Mason 			goto again;
51165f39d397SChris Mason 
511776a05b35SChris Mason 		if (ret < 0) {
5118b3b4aa74SDavid Sterba 			btrfs_release_path(path);
511976a05b35SChris Mason 			goto done;
512076a05b35SChris Mason 		}
512176a05b35SChris Mason 
51225cd57b2cSChris Mason 		if (!path->skip_locking) {
5123bd681513SChris Mason 			ret = btrfs_try_tree_read_lock(next);
51248e73f275SChris Mason 			if (!ret) {
51258e73f275SChris Mason 				btrfs_set_path_blocking(path);
5126bd681513SChris Mason 				btrfs_tree_read_lock(next);
5127bd681513SChris Mason 				btrfs_clear_path_blocking(path, next,
5128bd681513SChris Mason 							  BTRFS_READ_LOCK);
51298e73f275SChris Mason 			}
5130bd681513SChris Mason 			next_rw_lock = BTRFS_READ_LOCK;
5131bd681513SChris Mason 		}
5132d97e63b6SChris Mason 		break;
5133d97e63b6SChris Mason 	}
5134d97e63b6SChris Mason 	path->slots[level] = slot;
5135d97e63b6SChris Mason 	while (1) {
5136d97e63b6SChris Mason 		level--;
5137d97e63b6SChris Mason 		c = path->nodes[level];
5138925baeddSChris Mason 		if (path->locks[level])
5139bd681513SChris Mason 			btrfs_tree_unlock_rw(c, path->locks[level]);
51408e73f275SChris Mason 
51415f39d397SChris Mason 		free_extent_buffer(c);
5142d97e63b6SChris Mason 		path->nodes[level] = next;
5143d97e63b6SChris Mason 		path->slots[level] = 0;
5144a74a4b97SChris Mason 		if (!path->skip_locking)
5145bd681513SChris Mason 			path->locks[level] = next_rw_lock;
5146d97e63b6SChris Mason 		if (!level)
5147d97e63b6SChris Mason 			break;
5148b4ce94deSChris Mason 
51498e73f275SChris Mason 		ret = read_block_for_search(NULL, root, path, &next, level,
51505d9e75c4SJan Schmidt 					    0, &key, 0);
51518e73f275SChris Mason 		if (ret == -EAGAIN)
51528e73f275SChris Mason 			goto again;
51538e73f275SChris Mason 
515476a05b35SChris Mason 		if (ret < 0) {
5155b3b4aa74SDavid Sterba 			btrfs_release_path(path);
515676a05b35SChris Mason 			goto done;
515776a05b35SChris Mason 		}
515876a05b35SChris Mason 
51595cd57b2cSChris Mason 		if (!path->skip_locking) {
5160bd681513SChris Mason 			ret = btrfs_try_tree_read_lock(next);
51618e73f275SChris Mason 			if (!ret) {
51628e73f275SChris Mason 				btrfs_set_path_blocking(path);
5163bd681513SChris Mason 				btrfs_tree_read_lock(next);
5164bd681513SChris Mason 				btrfs_clear_path_blocking(path, next,
5165bd681513SChris Mason 							  BTRFS_READ_LOCK);
51668e73f275SChris Mason 			}
5167bd681513SChris Mason 			next_rw_lock = BTRFS_READ_LOCK;
5168bd681513SChris Mason 		}
5169d97e63b6SChris Mason 	}
51708e73f275SChris Mason 	ret = 0;
5171925baeddSChris Mason done:
5172f7c79f30SChris Mason 	unlock_up(path, 0, 1, 0, NULL);
51738e73f275SChris Mason 	path->leave_spinning = old_spinning;
51748e73f275SChris Mason 	if (!old_spinning)
51758e73f275SChris Mason 		btrfs_set_path_blocking(path);
51768e73f275SChris Mason 
51778e73f275SChris Mason 	return ret;
5178d97e63b6SChris Mason }
51790b86a832SChris Mason 
51803f157a2fSChris Mason /*
51813f157a2fSChris Mason  * this uses btrfs_prev_leaf to walk backwards in the tree, and keeps
51823f157a2fSChris Mason  * searching until it gets past min_objectid or finds an item of 'type'
51833f157a2fSChris Mason  *
51843f157a2fSChris Mason  * returns 0 if something is found, 1 if nothing was found and < 0 on error
51853f157a2fSChris Mason  */
51860b86a832SChris Mason int btrfs_previous_item(struct btrfs_root *root,
51870b86a832SChris Mason 			struct btrfs_path *path, u64 min_objectid,
51880b86a832SChris Mason 			int type)
51890b86a832SChris Mason {
51900b86a832SChris Mason 	struct btrfs_key found_key;
51910b86a832SChris Mason 	struct extent_buffer *leaf;
5192e02119d5SChris Mason 	u32 nritems;
51930b86a832SChris Mason 	int ret;
51940b86a832SChris Mason 
51950b86a832SChris Mason 	while (1) {
51960b86a832SChris Mason 		if (path->slots[0] == 0) {
5197b4ce94deSChris Mason 			btrfs_set_path_blocking(path);
51980b86a832SChris Mason 			ret = btrfs_prev_leaf(root, path);
51990b86a832SChris Mason 			if (ret != 0)
52000b86a832SChris Mason 				return ret;
52010b86a832SChris Mason 		} else {
52020b86a832SChris Mason 			path->slots[0]--;
52030b86a832SChris Mason 		}
52040b86a832SChris Mason 		leaf = path->nodes[0];
5205e02119d5SChris Mason 		nritems = btrfs_header_nritems(leaf);
5206e02119d5SChris Mason 		if (nritems == 0)
5207e02119d5SChris Mason 			return 1;
5208e02119d5SChris Mason 		if (path->slots[0] == nritems)
5209e02119d5SChris Mason 			path->slots[0]--;
5210e02119d5SChris Mason 
52110b86a832SChris Mason 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5212e02119d5SChris Mason 		if (found_key.objectid < min_objectid)
5213e02119d5SChris Mason 			break;
52140a4eefbbSYan Zheng 		if (found_key.type == type)
52150a4eefbbSYan Zheng 			return 0;
5216e02119d5SChris Mason 		if (found_key.objectid == min_objectid &&
5217e02119d5SChris Mason 		    found_key.type < type)
5218e02119d5SChris Mason 			break;
52190b86a832SChris Mason 	}
52200b86a832SChris Mason 	return 1;
52210b86a832SChris Mason }
5222