xref: /openbmc/linux/fs/btrfs/ctree.c (revision a95236d99fa56766f11056903439f55fe5038bcf)
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 
470926dd8a6SJan Schmidt static inline int tree_mod_alloc(struct btrfs_fs_info *fs_info, gfp_t flags,
471bd989ba3SJan Schmidt 				 struct tree_mod_elem **tm_ret)
472bd989ba3SJan Schmidt {
473bd989ba3SJan Schmidt 	struct tree_mod_elem *tm;
474926dd8a6SJan Schmidt 	int seq;
475bd989ba3SJan Schmidt 
476e9b7fd4dSJan Schmidt 	if (tree_mod_dont_log(fs_info, NULL))
477bd989ba3SJan Schmidt 		return 0;
478bd989ba3SJan Schmidt 
479bd989ba3SJan Schmidt 	tm = *tm_ret = kzalloc(sizeof(*tm), flags);
480bd989ba3SJan Schmidt 	if (!tm)
481bd989ba3SJan Schmidt 		return -ENOMEM;
482bd989ba3SJan Schmidt 
483926dd8a6SJan Schmidt 	tm->elem.flags = 0;
484926dd8a6SJan Schmidt 	spin_lock(&fs_info->tree_mod_seq_lock);
485926dd8a6SJan Schmidt 	if (list_empty(&fs_info->tree_mod_seq_list)) {
486926dd8a6SJan Schmidt 		/*
487926dd8a6SJan Schmidt 		 * someone emptied the list while we were waiting for the lock.
488926dd8a6SJan Schmidt 		 * we must not add to the list, because no blocker exists. items
489926dd8a6SJan Schmidt 		 * are removed from the list only when the existing blocker is
490926dd8a6SJan Schmidt 		 * removed from the list.
491926dd8a6SJan Schmidt 		 */
492926dd8a6SJan Schmidt 		kfree(tm);
493926dd8a6SJan Schmidt 		seq = 0;
494926dd8a6SJan Schmidt 	} else {
495bd989ba3SJan Schmidt 		__get_tree_mod_seq(fs_info, &tm->elem);
496bd989ba3SJan Schmidt 		seq = tm->elem.seq;
497926dd8a6SJan Schmidt 	}
498926dd8a6SJan Schmidt 	spin_unlock(&fs_info->tree_mod_seq_lock);
499bd989ba3SJan Schmidt 
500bd989ba3SJan Schmidt 	return seq;
501bd989ba3SJan Schmidt }
502bd989ba3SJan Schmidt 
503bd989ba3SJan Schmidt static noinline int
504bd989ba3SJan Schmidt tree_mod_log_insert_key_mask(struct btrfs_fs_info *fs_info,
505bd989ba3SJan Schmidt 			     struct extent_buffer *eb, int slot,
506bd989ba3SJan Schmidt 			     enum mod_log_op op, gfp_t flags)
507bd989ba3SJan Schmidt {
508bd989ba3SJan Schmidt 	struct tree_mod_elem *tm;
509bd989ba3SJan Schmidt 	int ret;
510bd989ba3SJan Schmidt 
511bd989ba3SJan Schmidt 	ret = tree_mod_alloc(fs_info, flags, &tm);
512bd989ba3SJan Schmidt 	if (ret <= 0)
513bd989ba3SJan Schmidt 		return ret;
514bd989ba3SJan Schmidt 
515bd989ba3SJan Schmidt 	tm->index = eb->start >> PAGE_CACHE_SHIFT;
516bd989ba3SJan Schmidt 	if (op != MOD_LOG_KEY_ADD) {
517bd989ba3SJan Schmidt 		btrfs_node_key(eb, &tm->key, slot);
518bd989ba3SJan Schmidt 		tm->blockptr = btrfs_node_blockptr(eb, slot);
519bd989ba3SJan Schmidt 	}
520bd989ba3SJan Schmidt 	tm->op = op;
521bd989ba3SJan Schmidt 	tm->slot = slot;
522bd989ba3SJan Schmidt 	tm->generation = btrfs_node_ptr_generation(eb, slot);
523bd989ba3SJan Schmidt 
524bd989ba3SJan Schmidt 	return __tree_mod_log_insert(fs_info, tm);
525bd989ba3SJan Schmidt }
526bd989ba3SJan Schmidt 
527bd989ba3SJan Schmidt static noinline int
528bd989ba3SJan Schmidt tree_mod_log_insert_key(struct btrfs_fs_info *fs_info, struct extent_buffer *eb,
529bd989ba3SJan Schmidt 			int slot, enum mod_log_op op)
530bd989ba3SJan Schmidt {
531bd989ba3SJan Schmidt 	return tree_mod_log_insert_key_mask(fs_info, eb, slot, op, GFP_NOFS);
532bd989ba3SJan Schmidt }
533bd989ba3SJan Schmidt 
534bd989ba3SJan Schmidt static noinline int
535bd989ba3SJan Schmidt tree_mod_log_insert_move(struct btrfs_fs_info *fs_info,
536bd989ba3SJan Schmidt 			 struct extent_buffer *eb, int dst_slot, int src_slot,
537bd989ba3SJan Schmidt 			 int nr_items, gfp_t flags)
538bd989ba3SJan Schmidt {
539bd989ba3SJan Schmidt 	struct tree_mod_elem *tm;
540bd989ba3SJan Schmidt 	int ret;
541bd989ba3SJan Schmidt 	int i;
542bd989ba3SJan Schmidt 
543f395694cSJan Schmidt 	if (tree_mod_dont_log(fs_info, eb))
544f395694cSJan Schmidt 		return 0;
545bd989ba3SJan Schmidt 
546bd989ba3SJan Schmidt 	for (i = 0; i + dst_slot < src_slot && i < nr_items; i++) {
547bd989ba3SJan Schmidt 		ret = tree_mod_log_insert_key(fs_info, eb, i + dst_slot,
548bd989ba3SJan Schmidt 					      MOD_LOG_KEY_REMOVE_WHILE_MOVING);
549bd989ba3SJan Schmidt 		BUG_ON(ret < 0);
550bd989ba3SJan Schmidt 	}
551bd989ba3SJan Schmidt 
552f395694cSJan Schmidt 	ret = tree_mod_alloc(fs_info, flags, &tm);
553f395694cSJan Schmidt 	if (ret <= 0)
554f395694cSJan Schmidt 		return ret;
555f395694cSJan Schmidt 
556bd989ba3SJan Schmidt 	tm->index = eb->start >> PAGE_CACHE_SHIFT;
557bd989ba3SJan Schmidt 	tm->slot = src_slot;
558bd989ba3SJan Schmidt 	tm->move.dst_slot = dst_slot;
559bd989ba3SJan Schmidt 	tm->move.nr_items = nr_items;
560bd989ba3SJan Schmidt 	tm->op = MOD_LOG_MOVE_KEYS;
561bd989ba3SJan Schmidt 
562bd989ba3SJan Schmidt 	return __tree_mod_log_insert(fs_info, tm);
563bd989ba3SJan Schmidt }
564bd989ba3SJan Schmidt 
565bd989ba3SJan Schmidt static noinline int
566bd989ba3SJan Schmidt tree_mod_log_insert_root(struct btrfs_fs_info *fs_info,
567bd989ba3SJan Schmidt 			 struct extent_buffer *old_root,
568bd989ba3SJan Schmidt 			 struct extent_buffer *new_root, gfp_t flags)
569bd989ba3SJan Schmidt {
570bd989ba3SJan Schmidt 	struct tree_mod_elem *tm;
571bd989ba3SJan Schmidt 	int ret;
572bd989ba3SJan Schmidt 
573bd989ba3SJan Schmidt 	ret = tree_mod_alloc(fs_info, flags, &tm);
574bd989ba3SJan Schmidt 	if (ret <= 0)
575bd989ba3SJan Schmidt 		return ret;
576bd989ba3SJan Schmidt 
577bd989ba3SJan Schmidt 	tm->index = new_root->start >> PAGE_CACHE_SHIFT;
578bd989ba3SJan Schmidt 	tm->old_root.logical = old_root->start;
579bd989ba3SJan Schmidt 	tm->old_root.level = btrfs_header_level(old_root);
580bd989ba3SJan Schmidt 	tm->generation = btrfs_header_generation(old_root);
581bd989ba3SJan Schmidt 	tm->op = MOD_LOG_ROOT_REPLACE;
582bd989ba3SJan Schmidt 
583bd989ba3SJan Schmidt 	return __tree_mod_log_insert(fs_info, tm);
584bd989ba3SJan Schmidt }
585bd989ba3SJan Schmidt 
586bd989ba3SJan Schmidt static struct tree_mod_elem *
587bd989ba3SJan Schmidt __tree_mod_log_search(struct btrfs_fs_info *fs_info, u64 start, u64 min_seq,
588bd989ba3SJan Schmidt 		      int smallest)
589bd989ba3SJan Schmidt {
590bd989ba3SJan Schmidt 	struct rb_root *tm_root;
591bd989ba3SJan Schmidt 	struct rb_node *node;
592bd989ba3SJan Schmidt 	struct tree_mod_elem *cur = NULL;
593bd989ba3SJan Schmidt 	struct tree_mod_elem *found = NULL;
594bd989ba3SJan Schmidt 	u64 index = start >> PAGE_CACHE_SHIFT;
595bd989ba3SJan Schmidt 
596bd989ba3SJan Schmidt 	read_lock(&fs_info->tree_mod_log_lock);
597bd989ba3SJan Schmidt 	tm_root = &fs_info->tree_mod_log;
598bd989ba3SJan Schmidt 	node = tm_root->rb_node;
599bd989ba3SJan Schmidt 	while (node) {
600bd989ba3SJan Schmidt 		cur = container_of(node, struct tree_mod_elem, node);
601bd989ba3SJan Schmidt 		if (cur->index < index) {
602bd989ba3SJan Schmidt 			node = node->rb_left;
603bd989ba3SJan Schmidt 		} else if (cur->index > index) {
604bd989ba3SJan Schmidt 			node = node->rb_right;
605bd989ba3SJan Schmidt 		} else if (cur->elem.seq < min_seq) {
606bd989ba3SJan Schmidt 			node = node->rb_left;
607bd989ba3SJan Schmidt 		} else if (!smallest) {
608bd989ba3SJan Schmidt 			/* we want the node with the highest seq */
609bd989ba3SJan Schmidt 			if (found)
610bd989ba3SJan Schmidt 				BUG_ON(found->elem.seq > cur->elem.seq);
611bd989ba3SJan Schmidt 			found = cur;
612bd989ba3SJan Schmidt 			node = node->rb_left;
613bd989ba3SJan Schmidt 		} else if (cur->elem.seq > min_seq) {
614bd989ba3SJan Schmidt 			/* we want the node with the smallest seq */
615bd989ba3SJan Schmidt 			if (found)
616bd989ba3SJan Schmidt 				BUG_ON(found->elem.seq < cur->elem.seq);
617bd989ba3SJan Schmidt 			found = cur;
618bd989ba3SJan Schmidt 			node = node->rb_right;
619bd989ba3SJan Schmidt 		} else {
620bd989ba3SJan Schmidt 			found = cur;
621bd989ba3SJan Schmidt 			break;
622bd989ba3SJan Schmidt 		}
623bd989ba3SJan Schmidt 	}
624bd989ba3SJan Schmidt 	read_unlock(&fs_info->tree_mod_log_lock);
625bd989ba3SJan Schmidt 
626bd989ba3SJan Schmidt 	return found;
627bd989ba3SJan Schmidt }
628bd989ba3SJan Schmidt 
629bd989ba3SJan Schmidt /*
630bd989ba3SJan Schmidt  * this returns the element from the log with the smallest time sequence
631bd989ba3SJan Schmidt  * value that's in the log (the oldest log item). any element with a time
632bd989ba3SJan Schmidt  * sequence lower than min_seq will be ignored.
633bd989ba3SJan Schmidt  */
634bd989ba3SJan Schmidt static struct tree_mod_elem *
635bd989ba3SJan Schmidt tree_mod_log_search_oldest(struct btrfs_fs_info *fs_info, u64 start,
636bd989ba3SJan Schmidt 			   u64 min_seq)
637bd989ba3SJan Schmidt {
638bd989ba3SJan Schmidt 	return __tree_mod_log_search(fs_info, start, min_seq, 1);
639bd989ba3SJan Schmidt }
640bd989ba3SJan Schmidt 
641bd989ba3SJan Schmidt /*
642bd989ba3SJan Schmidt  * this returns the element from the log with the largest time sequence
643bd989ba3SJan Schmidt  * value that's in the log (the most recent log item). any element with
644bd989ba3SJan Schmidt  * a time sequence lower than min_seq will be ignored.
645bd989ba3SJan Schmidt  */
646bd989ba3SJan Schmidt static struct tree_mod_elem *
647bd989ba3SJan Schmidt tree_mod_log_search(struct btrfs_fs_info *fs_info, u64 start, u64 min_seq)
648bd989ba3SJan Schmidt {
649bd989ba3SJan Schmidt 	return __tree_mod_log_search(fs_info, start, min_seq, 0);
650bd989ba3SJan Schmidt }
651bd989ba3SJan Schmidt 
652bd989ba3SJan Schmidt static inline void
653bd989ba3SJan Schmidt tree_mod_log_eb_copy(struct btrfs_fs_info *fs_info, struct extent_buffer *dst,
654bd989ba3SJan Schmidt 		     struct extent_buffer *src, unsigned long dst_offset,
655bd989ba3SJan Schmidt 		     unsigned long src_offset, int nr_items)
656bd989ba3SJan Schmidt {
657bd989ba3SJan Schmidt 	int ret;
658bd989ba3SJan Schmidt 	int i;
659bd989ba3SJan Schmidt 
660e9b7fd4dSJan Schmidt 	if (tree_mod_dont_log(fs_info, NULL))
661bd989ba3SJan Schmidt 		return;
662bd989ba3SJan Schmidt 
663bd989ba3SJan Schmidt 	if (btrfs_header_level(dst) == 0 && btrfs_header_level(src) == 0)
664bd989ba3SJan Schmidt 		return;
665bd989ba3SJan Schmidt 
666bd989ba3SJan Schmidt 	/* speed this up by single seq for all operations? */
667bd989ba3SJan Schmidt 	for (i = 0; i < nr_items; i++) {
668bd989ba3SJan Schmidt 		ret = tree_mod_log_insert_key(fs_info, src, i + src_offset,
669bd989ba3SJan Schmidt 					      MOD_LOG_KEY_REMOVE);
670bd989ba3SJan Schmidt 		BUG_ON(ret < 0);
671bd989ba3SJan Schmidt 		ret = tree_mod_log_insert_key(fs_info, dst, i + dst_offset,
672bd989ba3SJan Schmidt 					      MOD_LOG_KEY_ADD);
673bd989ba3SJan Schmidt 		BUG_ON(ret < 0);
674bd989ba3SJan Schmidt 	}
675bd989ba3SJan Schmidt }
676bd989ba3SJan Schmidt 
677bd989ba3SJan Schmidt static inline void
678bd989ba3SJan Schmidt tree_mod_log_eb_move(struct btrfs_fs_info *fs_info, struct extent_buffer *dst,
679bd989ba3SJan Schmidt 		     int dst_offset, int src_offset, int nr_items)
680bd989ba3SJan Schmidt {
681bd989ba3SJan Schmidt 	int ret;
682bd989ba3SJan Schmidt 	ret = tree_mod_log_insert_move(fs_info, dst, dst_offset, src_offset,
683bd989ba3SJan Schmidt 				       nr_items, GFP_NOFS);
684bd989ba3SJan Schmidt 	BUG_ON(ret < 0);
685bd989ba3SJan Schmidt }
686bd989ba3SJan Schmidt 
687bd989ba3SJan Schmidt static inline void
688bd989ba3SJan Schmidt tree_mod_log_set_node_key(struct btrfs_fs_info *fs_info,
689bd989ba3SJan Schmidt 			  struct extent_buffer *eb,
690bd989ba3SJan Schmidt 			  struct btrfs_disk_key *disk_key, int slot, int atomic)
691bd989ba3SJan Schmidt {
692bd989ba3SJan Schmidt 	int ret;
693bd989ba3SJan Schmidt 
694bd989ba3SJan Schmidt 	ret = tree_mod_log_insert_key_mask(fs_info, eb, slot,
695bd989ba3SJan Schmidt 					   MOD_LOG_KEY_REPLACE,
696bd989ba3SJan Schmidt 					   atomic ? GFP_ATOMIC : GFP_NOFS);
697bd989ba3SJan Schmidt 	BUG_ON(ret < 0);
698bd989ba3SJan Schmidt }
699bd989ba3SJan Schmidt 
700bd989ba3SJan Schmidt static void tree_mod_log_free_eb(struct btrfs_fs_info *fs_info,
701bd989ba3SJan Schmidt 				 struct extent_buffer *eb)
702bd989ba3SJan Schmidt {
703bd989ba3SJan Schmidt 	int i;
704bd989ba3SJan Schmidt 	int ret;
705bd989ba3SJan Schmidt 	u32 nritems;
706bd989ba3SJan Schmidt 
707e9b7fd4dSJan Schmidt 	if (tree_mod_dont_log(fs_info, eb))
708bd989ba3SJan Schmidt 		return;
709bd989ba3SJan Schmidt 
710bd989ba3SJan Schmidt 	nritems = btrfs_header_nritems(eb);
711bd989ba3SJan Schmidt 	for (i = nritems - 1; i >= 0; i--) {
712bd989ba3SJan Schmidt 		ret = tree_mod_log_insert_key(fs_info, eb, i,
713bd989ba3SJan Schmidt 					      MOD_LOG_KEY_REMOVE_WHILE_FREEING);
714bd989ba3SJan Schmidt 		BUG_ON(ret < 0);
715bd989ba3SJan Schmidt 	}
716bd989ba3SJan Schmidt }
717bd989ba3SJan Schmidt 
718bd989ba3SJan Schmidt static inline void
719bd989ba3SJan Schmidt tree_mod_log_set_root_pointer(struct btrfs_root *root,
720bd989ba3SJan Schmidt 			      struct extent_buffer *new_root_node)
721bd989ba3SJan Schmidt {
722bd989ba3SJan Schmidt 	int ret;
723bd989ba3SJan Schmidt 	tree_mod_log_free_eb(root->fs_info, root->node);
724bd989ba3SJan Schmidt 	ret = tree_mod_log_insert_root(root->fs_info, root->node,
725bd989ba3SJan Schmidt 				       new_root_node, GFP_NOFS);
726bd989ba3SJan Schmidt 	BUG_ON(ret < 0);
727bd989ba3SJan Schmidt }
728bd989ba3SJan Schmidt 
729d352ac68SChris Mason /*
7305d4f98a2SYan Zheng  * check if the tree block can be shared by multiple trees
7315d4f98a2SYan Zheng  */
7325d4f98a2SYan Zheng int btrfs_block_can_be_shared(struct btrfs_root *root,
7335d4f98a2SYan Zheng 			      struct extent_buffer *buf)
7345d4f98a2SYan Zheng {
7355d4f98a2SYan Zheng 	/*
7365d4f98a2SYan Zheng 	 * Tree blocks not in refernece counted trees and tree roots
7375d4f98a2SYan Zheng 	 * are never shared. If a block was allocated after the last
7385d4f98a2SYan Zheng 	 * snapshot and the block was not allocated by tree relocation,
7395d4f98a2SYan Zheng 	 * we know the block is not shared.
7405d4f98a2SYan Zheng 	 */
7415d4f98a2SYan Zheng 	if (root->ref_cows &&
7425d4f98a2SYan Zheng 	    buf != root->node && buf != root->commit_root &&
7435d4f98a2SYan Zheng 	    (btrfs_header_generation(buf) <=
7445d4f98a2SYan Zheng 	     btrfs_root_last_snapshot(&root->root_item) ||
7455d4f98a2SYan Zheng 	     btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)))
7465d4f98a2SYan Zheng 		return 1;
7475d4f98a2SYan Zheng #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
7485d4f98a2SYan Zheng 	if (root->ref_cows &&
7495d4f98a2SYan Zheng 	    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
7505d4f98a2SYan Zheng 		return 1;
7515d4f98a2SYan Zheng #endif
7525d4f98a2SYan Zheng 	return 0;
7535d4f98a2SYan Zheng }
7545d4f98a2SYan Zheng 
7555d4f98a2SYan Zheng static noinline int update_ref_for_cow(struct btrfs_trans_handle *trans,
7565d4f98a2SYan Zheng 				       struct btrfs_root *root,
7575d4f98a2SYan Zheng 				       struct extent_buffer *buf,
758f0486c68SYan, Zheng 				       struct extent_buffer *cow,
759f0486c68SYan, Zheng 				       int *last_ref)
7605d4f98a2SYan Zheng {
7615d4f98a2SYan Zheng 	u64 refs;
7625d4f98a2SYan Zheng 	u64 owner;
7635d4f98a2SYan Zheng 	u64 flags;
7645d4f98a2SYan Zheng 	u64 new_flags = 0;
7655d4f98a2SYan Zheng 	int ret;
7665d4f98a2SYan Zheng 
7675d4f98a2SYan Zheng 	/*
7685d4f98a2SYan Zheng 	 * Backrefs update rules:
7695d4f98a2SYan Zheng 	 *
7705d4f98a2SYan Zheng 	 * Always use full backrefs for extent pointers in tree block
7715d4f98a2SYan Zheng 	 * allocated by tree relocation.
7725d4f98a2SYan Zheng 	 *
7735d4f98a2SYan Zheng 	 * If a shared tree block is no longer referenced by its owner
7745d4f98a2SYan Zheng 	 * tree (btrfs_header_owner(buf) == root->root_key.objectid),
7755d4f98a2SYan Zheng 	 * use full backrefs for extent pointers in tree block.
7765d4f98a2SYan Zheng 	 *
7775d4f98a2SYan Zheng 	 * If a tree block is been relocating
7785d4f98a2SYan Zheng 	 * (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID),
7795d4f98a2SYan Zheng 	 * use full backrefs for extent pointers in tree block.
7805d4f98a2SYan Zheng 	 * The reason for this is some operations (such as drop tree)
7815d4f98a2SYan Zheng 	 * are only allowed for blocks use full backrefs.
7825d4f98a2SYan Zheng 	 */
7835d4f98a2SYan Zheng 
7845d4f98a2SYan Zheng 	if (btrfs_block_can_be_shared(root, buf)) {
7855d4f98a2SYan Zheng 		ret = btrfs_lookup_extent_info(trans, root, buf->start,
7865d4f98a2SYan Zheng 					       buf->len, &refs, &flags);
787be1a5564SMark Fasheh 		if (ret)
788be1a5564SMark Fasheh 			return ret;
789e5df9573SMark Fasheh 		if (refs == 0) {
790e5df9573SMark Fasheh 			ret = -EROFS;
791e5df9573SMark Fasheh 			btrfs_std_error(root->fs_info, ret);
792e5df9573SMark Fasheh 			return ret;
793e5df9573SMark Fasheh 		}
7945d4f98a2SYan Zheng 	} else {
7955d4f98a2SYan Zheng 		refs = 1;
7965d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
7975d4f98a2SYan Zheng 		    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
7985d4f98a2SYan Zheng 			flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
7995d4f98a2SYan Zheng 		else
8005d4f98a2SYan Zheng 			flags = 0;
8015d4f98a2SYan Zheng 	}
8025d4f98a2SYan Zheng 
8035d4f98a2SYan Zheng 	owner = btrfs_header_owner(buf);
8045d4f98a2SYan Zheng 	BUG_ON(owner == BTRFS_TREE_RELOC_OBJECTID &&
8055d4f98a2SYan Zheng 	       !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
8065d4f98a2SYan Zheng 
8075d4f98a2SYan Zheng 	if (refs > 1) {
8085d4f98a2SYan Zheng 		if ((owner == root->root_key.objectid ||
8095d4f98a2SYan Zheng 		     root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) &&
8105d4f98a2SYan Zheng 		    !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)) {
81166d7e7f0SArne Jansen 			ret = btrfs_inc_ref(trans, root, buf, 1, 1);
81279787eaaSJeff Mahoney 			BUG_ON(ret); /* -ENOMEM */
8135d4f98a2SYan Zheng 
8145d4f98a2SYan Zheng 			if (root->root_key.objectid ==
8155d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID) {
81666d7e7f0SArne Jansen 				ret = btrfs_dec_ref(trans, root, buf, 0, 1);
81779787eaaSJeff Mahoney 				BUG_ON(ret); /* -ENOMEM */
81866d7e7f0SArne Jansen 				ret = btrfs_inc_ref(trans, root, cow, 1, 1);
81979787eaaSJeff Mahoney 				BUG_ON(ret); /* -ENOMEM */
8205d4f98a2SYan Zheng 			}
8215d4f98a2SYan Zheng 			new_flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
8225d4f98a2SYan Zheng 		} else {
8235d4f98a2SYan Zheng 
8245d4f98a2SYan Zheng 			if (root->root_key.objectid ==
8255d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID)
82666d7e7f0SArne Jansen 				ret = btrfs_inc_ref(trans, root, cow, 1, 1);
8275d4f98a2SYan Zheng 			else
82866d7e7f0SArne Jansen 				ret = btrfs_inc_ref(trans, root, cow, 0, 1);
82979787eaaSJeff Mahoney 			BUG_ON(ret); /* -ENOMEM */
8305d4f98a2SYan Zheng 		}
8315d4f98a2SYan Zheng 		if (new_flags != 0) {
8325d4f98a2SYan Zheng 			ret = btrfs_set_disk_extent_flags(trans, root,
8335d4f98a2SYan Zheng 							  buf->start,
8345d4f98a2SYan Zheng 							  buf->len,
8355d4f98a2SYan Zheng 							  new_flags, 0);
836be1a5564SMark Fasheh 			if (ret)
837be1a5564SMark Fasheh 				return ret;
8385d4f98a2SYan Zheng 		}
8395d4f98a2SYan Zheng 	} else {
8405d4f98a2SYan Zheng 		if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
8415d4f98a2SYan Zheng 			if (root->root_key.objectid ==
8425d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID)
84366d7e7f0SArne Jansen 				ret = btrfs_inc_ref(trans, root, cow, 1, 1);
8445d4f98a2SYan Zheng 			else
84566d7e7f0SArne Jansen 				ret = btrfs_inc_ref(trans, root, cow, 0, 1);
84679787eaaSJeff Mahoney 			BUG_ON(ret); /* -ENOMEM */
84766d7e7f0SArne Jansen 			ret = btrfs_dec_ref(trans, root, buf, 1, 1);
84879787eaaSJeff Mahoney 			BUG_ON(ret); /* -ENOMEM */
8495d4f98a2SYan Zheng 		}
850f230475eSJan Schmidt 		/*
851f230475eSJan Schmidt 		 * don't log freeing in case we're freeing the root node, this
852f230475eSJan Schmidt 		 * is done by tree_mod_log_set_root_pointer later
853f230475eSJan Schmidt 		 */
854f230475eSJan Schmidt 		if (buf != root->node && btrfs_header_level(buf) != 0)
855f230475eSJan Schmidt 			tree_mod_log_free_eb(root->fs_info, buf);
8565d4f98a2SYan Zheng 		clean_tree_block(trans, root, buf);
857f0486c68SYan, Zheng 		*last_ref = 1;
8585d4f98a2SYan Zheng 	}
8595d4f98a2SYan Zheng 	return 0;
8605d4f98a2SYan Zheng }
8615d4f98a2SYan Zheng 
8625d4f98a2SYan Zheng /*
863d397712bSChris Mason  * does the dirty work in cow of a single block.  The parent block (if
864d397712bSChris Mason  * supplied) is updated to point to the new cow copy.  The new buffer is marked
865d397712bSChris Mason  * dirty and returned locked.  If you modify the block it needs to be marked
866d397712bSChris Mason  * dirty again.
867d352ac68SChris Mason  *
868d352ac68SChris Mason  * search_start -- an allocation hint for the new block
869d352ac68SChris Mason  *
870d397712bSChris Mason  * empty_size -- a hint that you plan on doing more cow.  This is the size in
871d397712bSChris Mason  * bytes the allocator should try to find free next to the block it returns.
872d397712bSChris Mason  * This is just a hint and may be ignored by the allocator.
873d352ac68SChris Mason  */
874d397712bSChris Mason static noinline int __btrfs_cow_block(struct btrfs_trans_handle *trans,
8755f39d397SChris Mason 			     struct btrfs_root *root,
8765f39d397SChris Mason 			     struct extent_buffer *buf,
8775f39d397SChris Mason 			     struct extent_buffer *parent, int parent_slot,
8785f39d397SChris Mason 			     struct extent_buffer **cow_ret,
8799fa8cfe7SChris Mason 			     u64 search_start, u64 empty_size)
8806702ed49SChris Mason {
8815d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
8825f39d397SChris Mason 	struct extent_buffer *cow;
883be1a5564SMark Fasheh 	int level, ret;
884f0486c68SYan, Zheng 	int last_ref = 0;
885925baeddSChris Mason 	int unlock_orig = 0;
8865d4f98a2SYan Zheng 	u64 parent_start;
8876702ed49SChris Mason 
888925baeddSChris Mason 	if (*cow_ret == buf)
889925baeddSChris Mason 		unlock_orig = 1;
890925baeddSChris Mason 
891b9447ef8SChris Mason 	btrfs_assert_tree_locked(buf);
892925baeddSChris Mason 
8937bb86316SChris Mason 	WARN_ON(root->ref_cows && trans->transid !=
8947bb86316SChris Mason 		root->fs_info->running_transaction->transid);
8956702ed49SChris Mason 	WARN_ON(root->ref_cows && trans->transid != root->last_trans);
8965f39d397SChris Mason 
8977bb86316SChris Mason 	level = btrfs_header_level(buf);
89831840ae1SZheng Yan 
8995d4f98a2SYan Zheng 	if (level == 0)
9005d4f98a2SYan Zheng 		btrfs_item_key(buf, &disk_key, 0);
9015d4f98a2SYan Zheng 	else
9025d4f98a2SYan Zheng 		btrfs_node_key(buf, &disk_key, 0);
9035d4f98a2SYan Zheng 
9045d4f98a2SYan Zheng 	if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) {
9055d4f98a2SYan Zheng 		if (parent)
9065d4f98a2SYan Zheng 			parent_start = parent->start;
9075d4f98a2SYan Zheng 		else
9085d4f98a2SYan Zheng 			parent_start = 0;
9095d4f98a2SYan Zheng 	} else
9105d4f98a2SYan Zheng 		parent_start = 0;
9115d4f98a2SYan Zheng 
9125d4f98a2SYan Zheng 	cow = btrfs_alloc_free_block(trans, root, buf->len, parent_start,
9135d4f98a2SYan Zheng 				     root->root_key.objectid, &disk_key,
9145581a51aSJan Schmidt 				     level, search_start, empty_size);
9156702ed49SChris Mason 	if (IS_ERR(cow))
9166702ed49SChris Mason 		return PTR_ERR(cow);
9176702ed49SChris Mason 
918b4ce94deSChris Mason 	/* cow is set to blocking by btrfs_init_new_buffer */
919b4ce94deSChris Mason 
9205f39d397SChris Mason 	copy_extent_buffer(cow, buf, 0, 0, cow->len);
921db94535dSChris Mason 	btrfs_set_header_bytenr(cow, cow->start);
9225f39d397SChris Mason 	btrfs_set_header_generation(cow, trans->transid);
9235d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
9245d4f98a2SYan Zheng 	btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
9255d4f98a2SYan Zheng 				     BTRFS_HEADER_FLAG_RELOC);
9265d4f98a2SYan Zheng 	if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
9275d4f98a2SYan Zheng 		btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
9285d4f98a2SYan Zheng 	else
9295f39d397SChris Mason 		btrfs_set_header_owner(cow, root->root_key.objectid);
9306702ed49SChris Mason 
9312b82032cSYan Zheng 	write_extent_buffer(cow, root->fs_info->fsid,
9322b82032cSYan Zheng 			    (unsigned long)btrfs_header_fsid(cow),
9332b82032cSYan Zheng 			    BTRFS_FSID_SIZE);
9342b82032cSYan Zheng 
935be1a5564SMark Fasheh 	ret = update_ref_for_cow(trans, root, buf, cow, &last_ref);
936b68dc2a9SMark Fasheh 	if (ret) {
93779787eaaSJeff Mahoney 		btrfs_abort_transaction(trans, root, ret);
938b68dc2a9SMark Fasheh 		return ret;
939b68dc2a9SMark Fasheh 	}
9401a40e23bSZheng Yan 
9413fd0a558SYan, Zheng 	if (root->ref_cows)
9423fd0a558SYan, Zheng 		btrfs_reloc_cow_block(trans, root, buf, cow);
9433fd0a558SYan, Zheng 
9446702ed49SChris Mason 	if (buf == root->node) {
945925baeddSChris Mason 		WARN_ON(parent && parent != buf);
9465d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
9475d4f98a2SYan Zheng 		    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
9485d4f98a2SYan Zheng 			parent_start = buf->start;
9495d4f98a2SYan Zheng 		else
9505d4f98a2SYan Zheng 			parent_start = 0;
951925baeddSChris Mason 
9525f39d397SChris Mason 		extent_buffer_get(cow);
953f230475eSJan Schmidt 		tree_mod_log_set_root_pointer(root, cow);
954240f62c8SChris Mason 		rcu_assign_pointer(root->node, cow);
955925baeddSChris Mason 
956f0486c68SYan, Zheng 		btrfs_free_tree_block(trans, root, buf, parent_start,
9575581a51aSJan Schmidt 				      last_ref);
9585f39d397SChris Mason 		free_extent_buffer(buf);
9590b86a832SChris Mason 		add_root_to_dirty_list(root);
9606702ed49SChris Mason 	} else {
9615d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
9625d4f98a2SYan Zheng 			parent_start = parent->start;
9635d4f98a2SYan Zheng 		else
9645d4f98a2SYan Zheng 			parent_start = 0;
9655d4f98a2SYan Zheng 
9665d4f98a2SYan Zheng 		WARN_ON(trans->transid != btrfs_header_generation(parent));
967f230475eSJan Schmidt 		tree_mod_log_insert_key(root->fs_info, parent, parent_slot,
968f230475eSJan Schmidt 					MOD_LOG_KEY_REPLACE);
9695f39d397SChris Mason 		btrfs_set_node_blockptr(parent, parent_slot,
970db94535dSChris Mason 					cow->start);
97174493f7aSChris Mason 		btrfs_set_node_ptr_generation(parent, parent_slot,
97274493f7aSChris Mason 					      trans->transid);
9736702ed49SChris Mason 		btrfs_mark_buffer_dirty(parent);
974f0486c68SYan, Zheng 		btrfs_free_tree_block(trans, root, buf, parent_start,
9755581a51aSJan Schmidt 				      last_ref);
9766702ed49SChris Mason 	}
977925baeddSChris Mason 	if (unlock_orig)
978925baeddSChris Mason 		btrfs_tree_unlock(buf);
9793083ee2eSJosef Bacik 	free_extent_buffer_stale(buf);
9806702ed49SChris Mason 	btrfs_mark_buffer_dirty(cow);
9816702ed49SChris Mason 	*cow_ret = cow;
9826702ed49SChris Mason 	return 0;
9836702ed49SChris Mason }
9846702ed49SChris Mason 
9855d9e75c4SJan Schmidt /*
9865d9e75c4SJan Schmidt  * returns the logical address of the oldest predecessor of the given root.
9875d9e75c4SJan Schmidt  * entries older than time_seq are ignored.
9885d9e75c4SJan Schmidt  */
9895d9e75c4SJan Schmidt static struct tree_mod_elem *
9905d9e75c4SJan Schmidt __tree_mod_log_oldest_root(struct btrfs_fs_info *fs_info,
9915d9e75c4SJan Schmidt 			   struct btrfs_root *root, u64 time_seq)
9925d9e75c4SJan Schmidt {
9935d9e75c4SJan Schmidt 	struct tree_mod_elem *tm;
9945d9e75c4SJan Schmidt 	struct tree_mod_elem *found = NULL;
9955d9e75c4SJan Schmidt 	u64 root_logical = root->node->start;
9965d9e75c4SJan Schmidt 	int looped = 0;
9975d9e75c4SJan Schmidt 
9985d9e75c4SJan Schmidt 	if (!time_seq)
9995d9e75c4SJan Schmidt 		return 0;
10005d9e75c4SJan Schmidt 
10015d9e75c4SJan Schmidt 	/*
10025d9e75c4SJan Schmidt 	 * the very last operation that's logged for a root is the replacement
10035d9e75c4SJan Schmidt 	 * operation (if it is replaced at all). this has the index of the *new*
10045d9e75c4SJan Schmidt 	 * root, making it the very first operation that's logged for this root.
10055d9e75c4SJan Schmidt 	 */
10065d9e75c4SJan Schmidt 	while (1) {
10075d9e75c4SJan Schmidt 		tm = tree_mod_log_search_oldest(fs_info, root_logical,
10085d9e75c4SJan Schmidt 						time_seq);
10095d9e75c4SJan Schmidt 		if (!looped && !tm)
10105d9e75c4SJan Schmidt 			return 0;
10115d9e75c4SJan Schmidt 		/*
10125d9e75c4SJan Schmidt 		 * we must have key remove operations in the log before the
10135d9e75c4SJan Schmidt 		 * replace operation.
10145d9e75c4SJan Schmidt 		 */
10155d9e75c4SJan Schmidt 		BUG_ON(!tm);
10165d9e75c4SJan Schmidt 
10175d9e75c4SJan Schmidt 		if (tm->op != MOD_LOG_ROOT_REPLACE)
10185d9e75c4SJan Schmidt 			break;
10195d9e75c4SJan Schmidt 
10205d9e75c4SJan Schmidt 		found = tm;
10215d9e75c4SJan Schmidt 		root_logical = tm->old_root.logical;
10225d9e75c4SJan Schmidt 		BUG_ON(root_logical == root->node->start);
10235d9e75c4SJan Schmidt 		looped = 1;
10245d9e75c4SJan Schmidt 	}
10255d9e75c4SJan Schmidt 
1026*a95236d9SJan Schmidt 	/* if there's no old root to return, return what we found instead */
1027*a95236d9SJan Schmidt 	if (!found)
1028*a95236d9SJan Schmidt 		found = tm;
1029*a95236d9SJan Schmidt 
10305d9e75c4SJan Schmidt 	return found;
10315d9e75c4SJan Schmidt }
10325d9e75c4SJan Schmidt 
10335d9e75c4SJan Schmidt /*
10345d9e75c4SJan Schmidt  * tm is a pointer to the first operation to rewind within eb. then, all
10355d9e75c4SJan Schmidt  * previous operations will be rewinded (until we reach something older than
10365d9e75c4SJan Schmidt  * time_seq).
10375d9e75c4SJan Schmidt  */
10385d9e75c4SJan Schmidt static void
10395d9e75c4SJan Schmidt __tree_mod_log_rewind(struct extent_buffer *eb, u64 time_seq,
10405d9e75c4SJan Schmidt 		      struct tree_mod_elem *first_tm)
10415d9e75c4SJan Schmidt {
10425d9e75c4SJan Schmidt 	u32 n;
10435d9e75c4SJan Schmidt 	struct rb_node *next;
10445d9e75c4SJan Schmidt 	struct tree_mod_elem *tm = first_tm;
10455d9e75c4SJan Schmidt 	unsigned long o_dst;
10465d9e75c4SJan Schmidt 	unsigned long o_src;
10475d9e75c4SJan Schmidt 	unsigned long p_size = sizeof(struct btrfs_key_ptr);
10485d9e75c4SJan Schmidt 
10495d9e75c4SJan Schmidt 	n = btrfs_header_nritems(eb);
10505d9e75c4SJan Schmidt 	while (tm && tm->elem.seq >= time_seq) {
10515d9e75c4SJan Schmidt 		/*
10525d9e75c4SJan Schmidt 		 * all the operations are recorded with the operator used for
10535d9e75c4SJan Schmidt 		 * the modification. as we're going backwards, we do the
10545d9e75c4SJan Schmidt 		 * opposite of each operation here.
10555d9e75c4SJan Schmidt 		 */
10565d9e75c4SJan Schmidt 		switch (tm->op) {
10575d9e75c4SJan Schmidt 		case MOD_LOG_KEY_REMOVE_WHILE_FREEING:
10585d9e75c4SJan Schmidt 			BUG_ON(tm->slot < n);
10595d9e75c4SJan Schmidt 		case MOD_LOG_KEY_REMOVE_WHILE_MOVING:
10605d9e75c4SJan Schmidt 		case MOD_LOG_KEY_REMOVE:
10615d9e75c4SJan Schmidt 			btrfs_set_node_key(eb, &tm->key, tm->slot);
10625d9e75c4SJan Schmidt 			btrfs_set_node_blockptr(eb, tm->slot, tm->blockptr);
10635d9e75c4SJan Schmidt 			btrfs_set_node_ptr_generation(eb, tm->slot,
10645d9e75c4SJan Schmidt 						      tm->generation);
10655d9e75c4SJan Schmidt 			n++;
10665d9e75c4SJan Schmidt 			break;
10675d9e75c4SJan Schmidt 		case MOD_LOG_KEY_REPLACE:
10685d9e75c4SJan Schmidt 			BUG_ON(tm->slot >= n);
10695d9e75c4SJan Schmidt 			btrfs_set_node_key(eb, &tm->key, tm->slot);
10705d9e75c4SJan Schmidt 			btrfs_set_node_blockptr(eb, tm->slot, tm->blockptr);
10715d9e75c4SJan Schmidt 			btrfs_set_node_ptr_generation(eb, tm->slot,
10725d9e75c4SJan Schmidt 						      tm->generation);
10735d9e75c4SJan Schmidt 			break;
10745d9e75c4SJan Schmidt 		case MOD_LOG_KEY_ADD:
10755d9e75c4SJan Schmidt 			if (tm->slot != n - 1) {
10765d9e75c4SJan Schmidt 				o_dst = btrfs_node_key_ptr_offset(tm->slot);
10775d9e75c4SJan Schmidt 				o_src = btrfs_node_key_ptr_offset(tm->slot + 1);
10785d9e75c4SJan Schmidt 				memmove_extent_buffer(eb, o_dst, o_src, p_size);
10795d9e75c4SJan Schmidt 			}
10805d9e75c4SJan Schmidt 			n--;
10815d9e75c4SJan Schmidt 			break;
10825d9e75c4SJan Schmidt 		case MOD_LOG_MOVE_KEYS:
1083c3193108SJan Schmidt 			o_dst = btrfs_node_key_ptr_offset(tm->slot);
1084c3193108SJan Schmidt 			o_src = btrfs_node_key_ptr_offset(tm->move.dst_slot);
1085c3193108SJan Schmidt 			memmove_extent_buffer(eb, o_dst, o_src,
10865d9e75c4SJan Schmidt 					      tm->move.nr_items * p_size);
10875d9e75c4SJan Schmidt 			break;
10885d9e75c4SJan Schmidt 		case MOD_LOG_ROOT_REPLACE:
10895d9e75c4SJan Schmidt 			/*
10905d9e75c4SJan Schmidt 			 * this operation is special. for roots, this must be
10915d9e75c4SJan Schmidt 			 * handled explicitly before rewinding.
10925d9e75c4SJan Schmidt 			 * for non-roots, this operation may exist if the node
10935d9e75c4SJan Schmidt 			 * was a root: root A -> child B; then A gets empty and
10945d9e75c4SJan Schmidt 			 * B is promoted to the new root. in the mod log, we'll
10955d9e75c4SJan Schmidt 			 * have a root-replace operation for B, a tree block
10965d9e75c4SJan Schmidt 			 * that is no root. we simply ignore that operation.
10975d9e75c4SJan Schmidt 			 */
10985d9e75c4SJan Schmidt 			break;
10995d9e75c4SJan Schmidt 		}
11005d9e75c4SJan Schmidt 		next = rb_next(&tm->node);
11015d9e75c4SJan Schmidt 		if (!next)
11025d9e75c4SJan Schmidt 			break;
11035d9e75c4SJan Schmidt 		tm = container_of(next, struct tree_mod_elem, node);
11045d9e75c4SJan Schmidt 		if (tm->index != first_tm->index)
11055d9e75c4SJan Schmidt 			break;
11065d9e75c4SJan Schmidt 	}
11075d9e75c4SJan Schmidt 	btrfs_set_header_nritems(eb, n);
11085d9e75c4SJan Schmidt }
11095d9e75c4SJan Schmidt 
11105d9e75c4SJan Schmidt static struct extent_buffer *
11115d9e75c4SJan Schmidt tree_mod_log_rewind(struct btrfs_fs_info *fs_info, struct extent_buffer *eb,
11125d9e75c4SJan Schmidt 		    u64 time_seq)
11135d9e75c4SJan Schmidt {
11145d9e75c4SJan Schmidt 	struct extent_buffer *eb_rewin;
11155d9e75c4SJan Schmidt 	struct tree_mod_elem *tm;
11165d9e75c4SJan Schmidt 
11175d9e75c4SJan Schmidt 	if (!time_seq)
11185d9e75c4SJan Schmidt 		return eb;
11195d9e75c4SJan Schmidt 
11205d9e75c4SJan Schmidt 	if (btrfs_header_level(eb) == 0)
11215d9e75c4SJan Schmidt 		return eb;
11225d9e75c4SJan Schmidt 
11235d9e75c4SJan Schmidt 	tm = tree_mod_log_search(fs_info, eb->start, time_seq);
11245d9e75c4SJan Schmidt 	if (!tm)
11255d9e75c4SJan Schmidt 		return eb;
11265d9e75c4SJan Schmidt 
11275d9e75c4SJan Schmidt 	if (tm->op == MOD_LOG_KEY_REMOVE_WHILE_FREEING) {
11285d9e75c4SJan Schmidt 		BUG_ON(tm->slot != 0);
11295d9e75c4SJan Schmidt 		eb_rewin = alloc_dummy_extent_buffer(eb->start,
11305d9e75c4SJan Schmidt 						fs_info->tree_root->nodesize);
11315d9e75c4SJan Schmidt 		BUG_ON(!eb_rewin);
11325d9e75c4SJan Schmidt 		btrfs_set_header_bytenr(eb_rewin, eb->start);
11335d9e75c4SJan Schmidt 		btrfs_set_header_backref_rev(eb_rewin,
11345d9e75c4SJan Schmidt 					     btrfs_header_backref_rev(eb));
11355d9e75c4SJan Schmidt 		btrfs_set_header_owner(eb_rewin, btrfs_header_owner(eb));
1136c3193108SJan Schmidt 		btrfs_set_header_level(eb_rewin, btrfs_header_level(eb));
11375d9e75c4SJan Schmidt 	} else {
11385d9e75c4SJan Schmidt 		eb_rewin = btrfs_clone_extent_buffer(eb);
11395d9e75c4SJan Schmidt 		BUG_ON(!eb_rewin);
11405d9e75c4SJan Schmidt 	}
11415d9e75c4SJan Schmidt 
11425d9e75c4SJan Schmidt 	extent_buffer_get(eb_rewin);
11435d9e75c4SJan Schmidt 	free_extent_buffer(eb);
11445d9e75c4SJan Schmidt 
11455d9e75c4SJan Schmidt 	__tree_mod_log_rewind(eb_rewin, time_seq, tm);
11465d9e75c4SJan Schmidt 
11475d9e75c4SJan Schmidt 	return eb_rewin;
11485d9e75c4SJan Schmidt }
11495d9e75c4SJan Schmidt 
11508ba97a15SJan Schmidt /*
11518ba97a15SJan Schmidt  * get_old_root() rewinds the state of @root's root node to the given @time_seq
11528ba97a15SJan Schmidt  * value. If there are no changes, the current root->root_node is returned. If
11538ba97a15SJan Schmidt  * anything changed in between, there's a fresh buffer allocated on which the
11548ba97a15SJan Schmidt  * rewind operations are done. In any case, the returned buffer is read locked.
11558ba97a15SJan Schmidt  * Returns NULL on error (with no locks held).
11568ba97a15SJan Schmidt  */
11575d9e75c4SJan Schmidt static inline struct extent_buffer *
11585d9e75c4SJan Schmidt get_old_root(struct btrfs_root *root, u64 time_seq)
11595d9e75c4SJan Schmidt {
11605d9e75c4SJan Schmidt 	struct tree_mod_elem *tm;
11615d9e75c4SJan Schmidt 	struct extent_buffer *eb;
1162*a95236d9SJan Schmidt 	struct tree_mod_root *old_root = NULL;
11635d9e75c4SJan Schmidt 	u64 old_generation;
1164*a95236d9SJan Schmidt 	u64 logical;
11655d9e75c4SJan Schmidt 
11668ba97a15SJan Schmidt 	eb = btrfs_read_lock_root_node(root);
11675d9e75c4SJan Schmidt 	tm = __tree_mod_log_oldest_root(root->fs_info, root, time_seq);
11685d9e75c4SJan Schmidt 	if (!tm)
11695d9e75c4SJan Schmidt 		return root->node;
11705d9e75c4SJan Schmidt 
1171*a95236d9SJan Schmidt 	if (tm->op == MOD_LOG_ROOT_REPLACE) {
11725d9e75c4SJan Schmidt 		old_root = &tm->old_root;
11735d9e75c4SJan Schmidt 		old_generation = tm->generation;
1174*a95236d9SJan Schmidt 		logical = old_root->logical;
1175*a95236d9SJan Schmidt 	} else {
1176*a95236d9SJan Schmidt 		logical = root->node->start;
1177*a95236d9SJan Schmidt 	}
11785d9e75c4SJan Schmidt 
1179*a95236d9SJan Schmidt 	tm = tree_mod_log_search(root->fs_info, logical, time_seq);
11805d9e75c4SJan Schmidt 	/*
11815d9e75c4SJan Schmidt 	 * there was an item in the log when __tree_mod_log_oldest_root
11825d9e75c4SJan Schmidt 	 * returned. this one must not go away, because the time_seq passed to
11835d9e75c4SJan Schmidt 	 * us must be blocking its removal.
11845d9e75c4SJan Schmidt 	 */
11855d9e75c4SJan Schmidt 	BUG_ON(!tm);
11865d9e75c4SJan Schmidt 
1187*a95236d9SJan Schmidt 	if (old_root)
11885d9e75c4SJan Schmidt 		eb = alloc_dummy_extent_buffer(tm->index << PAGE_CACHE_SHIFT,
11895d9e75c4SJan Schmidt 					       root->nodesize);
1190*a95236d9SJan Schmidt 	else
1191*a95236d9SJan Schmidt 		eb = btrfs_clone_extent_buffer(root->node);
11928ba97a15SJan Schmidt 	btrfs_tree_read_unlock(root->node);
11938ba97a15SJan Schmidt 	free_extent_buffer(root->node);
11948ba97a15SJan Schmidt 	if (!eb)
11958ba97a15SJan Schmidt 		return NULL;
11968ba97a15SJan Schmidt 	btrfs_tree_read_lock(eb);
1197*a95236d9SJan Schmidt 	if (old_root) {
11985d9e75c4SJan Schmidt 		btrfs_set_header_bytenr(eb, eb->start);
11995d9e75c4SJan Schmidt 		btrfs_set_header_backref_rev(eb, BTRFS_MIXED_BACKREF_REV);
12005d9e75c4SJan Schmidt 		btrfs_set_header_owner(eb, root->root_key.objectid);
12015d9e75c4SJan Schmidt 		btrfs_set_header_level(eb, old_root->level);
12025d9e75c4SJan Schmidt 		btrfs_set_header_generation(eb, old_generation);
1203*a95236d9SJan Schmidt 	}
12045d9e75c4SJan Schmidt 	__tree_mod_log_rewind(eb, time_seq, tm);
12058ba97a15SJan Schmidt 	extent_buffer_get(eb);
12065d9e75c4SJan Schmidt 
12075d9e75c4SJan Schmidt 	return eb;
12085d9e75c4SJan Schmidt }
12095d9e75c4SJan Schmidt 
12105d4f98a2SYan Zheng static inline int should_cow_block(struct btrfs_trans_handle *trans,
12115d4f98a2SYan Zheng 				   struct btrfs_root *root,
12125d4f98a2SYan Zheng 				   struct extent_buffer *buf)
12135d4f98a2SYan Zheng {
1214f1ebcc74SLiu Bo 	/* ensure we can see the force_cow */
1215f1ebcc74SLiu Bo 	smp_rmb();
1216f1ebcc74SLiu Bo 
1217f1ebcc74SLiu Bo 	/*
1218f1ebcc74SLiu Bo 	 * We do not need to cow a block if
1219f1ebcc74SLiu Bo 	 * 1) this block is not created or changed in this transaction;
1220f1ebcc74SLiu Bo 	 * 2) this block does not belong to TREE_RELOC tree;
1221f1ebcc74SLiu Bo 	 * 3) the root is not forced COW.
1222f1ebcc74SLiu Bo 	 *
1223f1ebcc74SLiu Bo 	 * What is forced COW:
1224f1ebcc74SLiu Bo 	 *    when we create snapshot during commiting the transaction,
1225f1ebcc74SLiu Bo 	 *    after we've finished coping src root, we must COW the shared
1226f1ebcc74SLiu Bo 	 *    block to ensure the metadata consistency.
1227f1ebcc74SLiu Bo 	 */
12285d4f98a2SYan Zheng 	if (btrfs_header_generation(buf) == trans->transid &&
12295d4f98a2SYan Zheng 	    !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN) &&
12305d4f98a2SYan Zheng 	    !(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
1231f1ebcc74SLiu Bo 	      btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)) &&
1232f1ebcc74SLiu Bo 	    !root->force_cow)
12335d4f98a2SYan Zheng 		return 0;
12345d4f98a2SYan Zheng 	return 1;
12355d4f98a2SYan Zheng }
12365d4f98a2SYan Zheng 
1237d352ac68SChris Mason /*
1238d352ac68SChris Mason  * cows a single block, see __btrfs_cow_block for the real work.
1239d352ac68SChris Mason  * This version of it has extra checks so that a block isn't cow'd more than
1240d352ac68SChris Mason  * once per transaction, as long as it hasn't been written yet
1241d352ac68SChris Mason  */
1242d397712bSChris Mason noinline int btrfs_cow_block(struct btrfs_trans_handle *trans,
12435f39d397SChris Mason 		    struct btrfs_root *root, struct extent_buffer *buf,
12445f39d397SChris Mason 		    struct extent_buffer *parent, int parent_slot,
12459fa8cfe7SChris Mason 		    struct extent_buffer **cow_ret)
124602217ed2SChris Mason {
12476702ed49SChris Mason 	u64 search_start;
1248f510cfecSChris Mason 	int ret;
1249dc17ff8fSChris Mason 
1250ccd467d6SChris Mason 	if (trans->transaction != root->fs_info->running_transaction) {
1251d397712bSChris Mason 		printk(KERN_CRIT "trans %llu running %llu\n",
1252d397712bSChris Mason 		       (unsigned long long)trans->transid,
1253d397712bSChris Mason 		       (unsigned long long)
1254ccd467d6SChris Mason 		       root->fs_info->running_transaction->transid);
1255ccd467d6SChris Mason 		WARN_ON(1);
1256ccd467d6SChris Mason 	}
1257ccd467d6SChris Mason 	if (trans->transid != root->fs_info->generation) {
1258d397712bSChris Mason 		printk(KERN_CRIT "trans %llu running %llu\n",
1259d397712bSChris Mason 		       (unsigned long long)trans->transid,
1260d397712bSChris Mason 		       (unsigned long long)root->fs_info->generation);
1261ccd467d6SChris Mason 		WARN_ON(1);
1262ccd467d6SChris Mason 	}
1263dc17ff8fSChris Mason 
12645d4f98a2SYan Zheng 	if (!should_cow_block(trans, root, buf)) {
126502217ed2SChris Mason 		*cow_ret = buf;
126602217ed2SChris Mason 		return 0;
126702217ed2SChris Mason 	}
1268c487685dSChris Mason 
12690b86a832SChris Mason 	search_start = buf->start & ~((u64)(1024 * 1024 * 1024) - 1);
1270b4ce94deSChris Mason 
1271b4ce94deSChris Mason 	if (parent)
1272b4ce94deSChris Mason 		btrfs_set_lock_blocking(parent);
1273b4ce94deSChris Mason 	btrfs_set_lock_blocking(buf);
1274b4ce94deSChris Mason 
1275f510cfecSChris Mason 	ret = __btrfs_cow_block(trans, root, buf, parent,
12769fa8cfe7SChris Mason 				 parent_slot, cow_ret, search_start, 0);
12771abe9b8aSliubo 
12781abe9b8aSliubo 	trace_btrfs_cow_block(root, buf, *cow_ret);
12791abe9b8aSliubo 
1280f510cfecSChris Mason 	return ret;
12812c90e5d6SChris Mason }
12826702ed49SChris Mason 
1283d352ac68SChris Mason /*
1284d352ac68SChris Mason  * helper function for defrag to decide if two blocks pointed to by a
1285d352ac68SChris Mason  * node are actually close by
1286d352ac68SChris Mason  */
12876b80053dSChris Mason static int close_blocks(u64 blocknr, u64 other, u32 blocksize)
12886702ed49SChris Mason {
12896b80053dSChris Mason 	if (blocknr < other && other - (blocknr + blocksize) < 32768)
12906702ed49SChris Mason 		return 1;
12916b80053dSChris Mason 	if (blocknr > other && blocknr - (other + blocksize) < 32768)
12926702ed49SChris Mason 		return 1;
129302217ed2SChris Mason 	return 0;
129402217ed2SChris Mason }
129502217ed2SChris Mason 
1296081e9573SChris Mason /*
1297081e9573SChris Mason  * compare two keys in a memcmp fashion
1298081e9573SChris Mason  */
1299081e9573SChris Mason static int comp_keys(struct btrfs_disk_key *disk, struct btrfs_key *k2)
1300081e9573SChris Mason {
1301081e9573SChris Mason 	struct btrfs_key k1;
1302081e9573SChris Mason 
1303081e9573SChris Mason 	btrfs_disk_key_to_cpu(&k1, disk);
1304081e9573SChris Mason 
130520736abaSDiego Calleja 	return btrfs_comp_cpu_keys(&k1, k2);
1306081e9573SChris Mason }
1307081e9573SChris Mason 
1308f3465ca4SJosef Bacik /*
1309f3465ca4SJosef Bacik  * same as comp_keys only with two btrfs_key's
1310f3465ca4SJosef Bacik  */
13115d4f98a2SYan Zheng int btrfs_comp_cpu_keys(struct btrfs_key *k1, struct btrfs_key *k2)
1312f3465ca4SJosef Bacik {
1313f3465ca4SJosef Bacik 	if (k1->objectid > k2->objectid)
1314f3465ca4SJosef Bacik 		return 1;
1315f3465ca4SJosef Bacik 	if (k1->objectid < k2->objectid)
1316f3465ca4SJosef Bacik 		return -1;
1317f3465ca4SJosef Bacik 	if (k1->type > k2->type)
1318f3465ca4SJosef Bacik 		return 1;
1319f3465ca4SJosef Bacik 	if (k1->type < k2->type)
1320f3465ca4SJosef Bacik 		return -1;
1321f3465ca4SJosef Bacik 	if (k1->offset > k2->offset)
1322f3465ca4SJosef Bacik 		return 1;
1323f3465ca4SJosef Bacik 	if (k1->offset < k2->offset)
1324f3465ca4SJosef Bacik 		return -1;
1325f3465ca4SJosef Bacik 	return 0;
1326f3465ca4SJosef Bacik }
1327081e9573SChris Mason 
1328d352ac68SChris Mason /*
1329d352ac68SChris Mason  * this is used by the defrag code to go through all the
1330d352ac68SChris Mason  * leaves pointed to by a node and reallocate them so that
1331d352ac68SChris Mason  * disk order is close to key order
1332d352ac68SChris Mason  */
13336702ed49SChris Mason int btrfs_realloc_node(struct btrfs_trans_handle *trans,
13345f39d397SChris Mason 		       struct btrfs_root *root, struct extent_buffer *parent,
1335a6b6e75eSChris Mason 		       int start_slot, int cache_only, u64 *last_ret,
1336a6b6e75eSChris Mason 		       struct btrfs_key *progress)
13376702ed49SChris Mason {
13386b80053dSChris Mason 	struct extent_buffer *cur;
13396702ed49SChris Mason 	u64 blocknr;
1340ca7a79adSChris Mason 	u64 gen;
1341e9d0b13bSChris Mason 	u64 search_start = *last_ret;
1342e9d0b13bSChris Mason 	u64 last_block = 0;
13436702ed49SChris Mason 	u64 other;
13446702ed49SChris Mason 	u32 parent_nritems;
13456702ed49SChris Mason 	int end_slot;
13466702ed49SChris Mason 	int i;
13476702ed49SChris Mason 	int err = 0;
1348f2183bdeSChris Mason 	int parent_level;
13496b80053dSChris Mason 	int uptodate;
13506b80053dSChris Mason 	u32 blocksize;
1351081e9573SChris Mason 	int progress_passed = 0;
1352081e9573SChris Mason 	struct btrfs_disk_key disk_key;
13536702ed49SChris Mason 
13545708b959SChris Mason 	parent_level = btrfs_header_level(parent);
13555708b959SChris Mason 	if (cache_only && parent_level != 1)
13565708b959SChris Mason 		return 0;
13575708b959SChris Mason 
1358d397712bSChris Mason 	if (trans->transaction != root->fs_info->running_transaction)
13596702ed49SChris Mason 		WARN_ON(1);
1360d397712bSChris Mason 	if (trans->transid != root->fs_info->generation)
13616702ed49SChris Mason 		WARN_ON(1);
136286479a04SChris Mason 
13636b80053dSChris Mason 	parent_nritems = btrfs_header_nritems(parent);
13646b80053dSChris Mason 	blocksize = btrfs_level_size(root, parent_level - 1);
13656702ed49SChris Mason 	end_slot = parent_nritems;
13666702ed49SChris Mason 
13676702ed49SChris Mason 	if (parent_nritems == 1)
13686702ed49SChris Mason 		return 0;
13696702ed49SChris Mason 
1370b4ce94deSChris Mason 	btrfs_set_lock_blocking(parent);
1371b4ce94deSChris Mason 
13726702ed49SChris Mason 	for (i = start_slot; i < end_slot; i++) {
13736702ed49SChris Mason 		int close = 1;
1374a6b6e75eSChris Mason 
1375081e9573SChris Mason 		btrfs_node_key(parent, &disk_key, i);
1376081e9573SChris Mason 		if (!progress_passed && comp_keys(&disk_key, progress) < 0)
1377081e9573SChris Mason 			continue;
1378081e9573SChris Mason 
1379081e9573SChris Mason 		progress_passed = 1;
13806b80053dSChris Mason 		blocknr = btrfs_node_blockptr(parent, i);
1381ca7a79adSChris Mason 		gen = btrfs_node_ptr_generation(parent, i);
1382e9d0b13bSChris Mason 		if (last_block == 0)
1383e9d0b13bSChris Mason 			last_block = blocknr;
13845708b959SChris Mason 
13856702ed49SChris Mason 		if (i > 0) {
13866b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i - 1);
13876b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
13886702ed49SChris Mason 		}
13890ef3e66bSChris Mason 		if (!close && i < end_slot - 2) {
13906b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i + 1);
13916b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
13926702ed49SChris Mason 		}
1393e9d0b13bSChris Mason 		if (close) {
1394e9d0b13bSChris Mason 			last_block = blocknr;
13956702ed49SChris Mason 			continue;
1396e9d0b13bSChris Mason 		}
13976702ed49SChris Mason 
13986b80053dSChris Mason 		cur = btrfs_find_tree_block(root, blocknr, blocksize);
13996b80053dSChris Mason 		if (cur)
1400b9fab919SChris Mason 			uptodate = btrfs_buffer_uptodate(cur, gen, 0);
14016b80053dSChris Mason 		else
14026b80053dSChris Mason 			uptodate = 0;
14035708b959SChris Mason 		if (!cur || !uptodate) {
14046702ed49SChris Mason 			if (cache_only) {
14056b80053dSChris Mason 				free_extent_buffer(cur);
14066702ed49SChris Mason 				continue;
14076702ed49SChris Mason 			}
14086b80053dSChris Mason 			if (!cur) {
14096b80053dSChris Mason 				cur = read_tree_block(root, blocknr,
1410ca7a79adSChris Mason 							 blocksize, gen);
141197d9a8a4STsutomu Itoh 				if (!cur)
141297d9a8a4STsutomu Itoh 					return -EIO;
14136b80053dSChris Mason 			} else if (!uptodate) {
1414018642a1STsutomu Itoh 				err = btrfs_read_buffer(cur, gen);
1415018642a1STsutomu Itoh 				if (err) {
1416018642a1STsutomu Itoh 					free_extent_buffer(cur);
1417018642a1STsutomu Itoh 					return err;
1418018642a1STsutomu Itoh 				}
14196702ed49SChris Mason 			}
1420f2183bdeSChris Mason 		}
1421e9d0b13bSChris Mason 		if (search_start == 0)
14226b80053dSChris Mason 			search_start = last_block;
1423e9d0b13bSChris Mason 
1424e7a84565SChris Mason 		btrfs_tree_lock(cur);
1425b4ce94deSChris Mason 		btrfs_set_lock_blocking(cur);
14266b80053dSChris Mason 		err = __btrfs_cow_block(trans, root, cur, parent, i,
1427e7a84565SChris Mason 					&cur, search_start,
14286b80053dSChris Mason 					min(16 * blocksize,
14299fa8cfe7SChris Mason 					    (end_slot - i) * blocksize));
1430252c38f0SYan 		if (err) {
1431e7a84565SChris Mason 			btrfs_tree_unlock(cur);
14326b80053dSChris Mason 			free_extent_buffer(cur);
14336702ed49SChris Mason 			break;
1434252c38f0SYan 		}
1435e7a84565SChris Mason 		search_start = cur->start;
1436e7a84565SChris Mason 		last_block = cur->start;
1437f2183bdeSChris Mason 		*last_ret = search_start;
1438e7a84565SChris Mason 		btrfs_tree_unlock(cur);
1439e7a84565SChris Mason 		free_extent_buffer(cur);
14406702ed49SChris Mason 	}
14416702ed49SChris Mason 	return err;
14426702ed49SChris Mason }
14436702ed49SChris Mason 
144474123bd7SChris Mason /*
144574123bd7SChris Mason  * The leaf data grows from end-to-front in the node.
144674123bd7SChris Mason  * this returns the address of the start of the last item,
144774123bd7SChris Mason  * which is the stop of the leaf data stack
144874123bd7SChris Mason  */
1449123abc88SChris Mason static inline unsigned int leaf_data_end(struct btrfs_root *root,
14505f39d397SChris Mason 					 struct extent_buffer *leaf)
1451be0e5c09SChris Mason {
14525f39d397SChris Mason 	u32 nr = btrfs_header_nritems(leaf);
1453be0e5c09SChris Mason 	if (nr == 0)
1454123abc88SChris Mason 		return BTRFS_LEAF_DATA_SIZE(root);
14555f39d397SChris Mason 	return btrfs_item_offset_nr(leaf, nr - 1);
1456be0e5c09SChris Mason }
1457be0e5c09SChris Mason 
1458aa5d6bedSChris Mason 
145974123bd7SChris Mason /*
14605f39d397SChris Mason  * search for key in the extent_buffer.  The items start at offset p,
14615f39d397SChris Mason  * and they are item_size apart.  There are 'max' items in p.
14625f39d397SChris Mason  *
146374123bd7SChris Mason  * the slot in the array is returned via slot, and it points to
146474123bd7SChris Mason  * the place where you would insert key if it is not found in
146574123bd7SChris Mason  * the array.
146674123bd7SChris Mason  *
146774123bd7SChris Mason  * slot may point to max if the key is bigger than all of the keys
146874123bd7SChris Mason  */
1469e02119d5SChris Mason static noinline int generic_bin_search(struct extent_buffer *eb,
1470e02119d5SChris Mason 				       unsigned long p,
14715f39d397SChris Mason 				       int item_size, struct btrfs_key *key,
1472be0e5c09SChris Mason 				       int max, int *slot)
1473be0e5c09SChris Mason {
1474be0e5c09SChris Mason 	int low = 0;
1475be0e5c09SChris Mason 	int high = max;
1476be0e5c09SChris Mason 	int mid;
1477be0e5c09SChris Mason 	int ret;
1478479965d6SChris Mason 	struct btrfs_disk_key *tmp = NULL;
14795f39d397SChris Mason 	struct btrfs_disk_key unaligned;
14805f39d397SChris Mason 	unsigned long offset;
14815f39d397SChris Mason 	char *kaddr = NULL;
14825f39d397SChris Mason 	unsigned long map_start = 0;
14835f39d397SChris Mason 	unsigned long map_len = 0;
1484479965d6SChris Mason 	int err;
1485be0e5c09SChris Mason 
1486be0e5c09SChris Mason 	while (low < high) {
1487be0e5c09SChris Mason 		mid = (low + high) / 2;
14885f39d397SChris Mason 		offset = p + mid * item_size;
14895f39d397SChris Mason 
1490a6591715SChris Mason 		if (!kaddr || offset < map_start ||
14915f39d397SChris Mason 		    (offset + sizeof(struct btrfs_disk_key)) >
14925f39d397SChris Mason 		    map_start + map_len) {
1493934d375bSChris Mason 
1494934d375bSChris Mason 			err = map_private_extent_buffer(eb, offset,
1495479965d6SChris Mason 						sizeof(struct btrfs_disk_key),
1496a6591715SChris Mason 						&kaddr, &map_start, &map_len);
14975f39d397SChris Mason 
1498479965d6SChris Mason 			if (!err) {
1499479965d6SChris Mason 				tmp = (struct btrfs_disk_key *)(kaddr + offset -
1500479965d6SChris Mason 							map_start);
1501479965d6SChris Mason 			} else {
15025f39d397SChris Mason 				read_extent_buffer(eb, &unaligned,
15035f39d397SChris Mason 						   offset, sizeof(unaligned));
15045f39d397SChris Mason 				tmp = &unaligned;
1505479965d6SChris Mason 			}
1506479965d6SChris Mason 
15075f39d397SChris Mason 		} else {
15085f39d397SChris Mason 			tmp = (struct btrfs_disk_key *)(kaddr + offset -
15095f39d397SChris Mason 							map_start);
15105f39d397SChris Mason 		}
1511be0e5c09SChris Mason 		ret = comp_keys(tmp, key);
1512be0e5c09SChris Mason 
1513be0e5c09SChris Mason 		if (ret < 0)
1514be0e5c09SChris Mason 			low = mid + 1;
1515be0e5c09SChris Mason 		else if (ret > 0)
1516be0e5c09SChris Mason 			high = mid;
1517be0e5c09SChris Mason 		else {
1518be0e5c09SChris Mason 			*slot = mid;
1519be0e5c09SChris Mason 			return 0;
1520be0e5c09SChris Mason 		}
1521be0e5c09SChris Mason 	}
1522be0e5c09SChris Mason 	*slot = low;
1523be0e5c09SChris Mason 	return 1;
1524be0e5c09SChris Mason }
1525be0e5c09SChris Mason 
152697571fd0SChris Mason /*
152797571fd0SChris Mason  * simple bin_search frontend that does the right thing for
152897571fd0SChris Mason  * leaves vs nodes
152997571fd0SChris Mason  */
15305f39d397SChris Mason static int bin_search(struct extent_buffer *eb, struct btrfs_key *key,
15315f39d397SChris Mason 		      int level, int *slot)
1532be0e5c09SChris Mason {
1533f775738fSWang Sheng-Hui 	if (level == 0)
15345f39d397SChris Mason 		return generic_bin_search(eb,
15355f39d397SChris Mason 					  offsetof(struct btrfs_leaf, items),
15360783fcfcSChris Mason 					  sizeof(struct btrfs_item),
15375f39d397SChris Mason 					  key, btrfs_header_nritems(eb),
15387518a238SChris Mason 					  slot);
1539f775738fSWang Sheng-Hui 	else
15405f39d397SChris Mason 		return generic_bin_search(eb,
15415f39d397SChris Mason 					  offsetof(struct btrfs_node, ptrs),
1542123abc88SChris Mason 					  sizeof(struct btrfs_key_ptr),
15435f39d397SChris Mason 					  key, btrfs_header_nritems(eb),
15447518a238SChris Mason 					  slot);
1545be0e5c09SChris Mason }
1546be0e5c09SChris Mason 
15475d4f98a2SYan Zheng int btrfs_bin_search(struct extent_buffer *eb, struct btrfs_key *key,
15485d4f98a2SYan Zheng 		     int level, int *slot)
15495d4f98a2SYan Zheng {
15505d4f98a2SYan Zheng 	return bin_search(eb, key, level, slot);
15515d4f98a2SYan Zheng }
15525d4f98a2SYan Zheng 
1553f0486c68SYan, Zheng static void root_add_used(struct btrfs_root *root, u32 size)
1554f0486c68SYan, Zheng {
1555f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
1556f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
1557f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) + size);
1558f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
1559f0486c68SYan, Zheng }
1560f0486c68SYan, Zheng 
1561f0486c68SYan, Zheng static void root_sub_used(struct btrfs_root *root, u32 size)
1562f0486c68SYan, Zheng {
1563f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
1564f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
1565f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) - size);
1566f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
1567f0486c68SYan, Zheng }
1568f0486c68SYan, Zheng 
1569d352ac68SChris Mason /* given a node and slot number, this reads the blocks it points to.  The
1570d352ac68SChris Mason  * extent buffer is returned with a reference taken (but unlocked).
1571d352ac68SChris Mason  * NULL is returned on error.
1572d352ac68SChris Mason  */
1573e02119d5SChris Mason static noinline struct extent_buffer *read_node_slot(struct btrfs_root *root,
15745f39d397SChris Mason 				   struct extent_buffer *parent, int slot)
1575bb803951SChris Mason {
1576ca7a79adSChris Mason 	int level = btrfs_header_level(parent);
1577bb803951SChris Mason 	if (slot < 0)
1578bb803951SChris Mason 		return NULL;
15795f39d397SChris Mason 	if (slot >= btrfs_header_nritems(parent))
1580bb803951SChris Mason 		return NULL;
1581ca7a79adSChris Mason 
1582ca7a79adSChris Mason 	BUG_ON(level == 0);
1583ca7a79adSChris Mason 
1584db94535dSChris Mason 	return read_tree_block(root, btrfs_node_blockptr(parent, slot),
1585ca7a79adSChris Mason 		       btrfs_level_size(root, level - 1),
1586ca7a79adSChris Mason 		       btrfs_node_ptr_generation(parent, slot));
1587bb803951SChris Mason }
1588bb803951SChris Mason 
1589d352ac68SChris Mason /*
1590d352ac68SChris Mason  * node level balancing, used to make sure nodes are in proper order for
1591d352ac68SChris Mason  * item deletion.  We balance from the top down, so we have to make sure
1592d352ac68SChris Mason  * that a deletion won't leave an node completely empty later on.
1593d352ac68SChris Mason  */
1594e02119d5SChris Mason static noinline int balance_level(struct btrfs_trans_handle *trans,
159598ed5174SChris Mason 			 struct btrfs_root *root,
159698ed5174SChris Mason 			 struct btrfs_path *path, int level)
1597bb803951SChris Mason {
15985f39d397SChris Mason 	struct extent_buffer *right = NULL;
15995f39d397SChris Mason 	struct extent_buffer *mid;
16005f39d397SChris Mason 	struct extent_buffer *left = NULL;
16015f39d397SChris Mason 	struct extent_buffer *parent = NULL;
1602bb803951SChris Mason 	int ret = 0;
1603bb803951SChris Mason 	int wret;
1604bb803951SChris Mason 	int pslot;
1605bb803951SChris Mason 	int orig_slot = path->slots[level];
160679f95c82SChris Mason 	u64 orig_ptr;
1607bb803951SChris Mason 
1608bb803951SChris Mason 	if (level == 0)
1609bb803951SChris Mason 		return 0;
1610bb803951SChris Mason 
16115f39d397SChris Mason 	mid = path->nodes[level];
1612b4ce94deSChris Mason 
1613bd681513SChris Mason 	WARN_ON(path->locks[level] != BTRFS_WRITE_LOCK &&
1614bd681513SChris Mason 		path->locks[level] != BTRFS_WRITE_LOCK_BLOCKING);
16157bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
16167bb86316SChris Mason 
16171d4f8a0cSChris Mason 	orig_ptr = btrfs_node_blockptr(mid, orig_slot);
161879f95c82SChris Mason 
1619a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
16205f39d397SChris Mason 		parent = path->nodes[level + 1];
1621bb803951SChris Mason 		pslot = path->slots[level + 1];
1622a05a9bb1SLi Zefan 	}
1623bb803951SChris Mason 
162440689478SChris Mason 	/*
162540689478SChris Mason 	 * deal with the case where there is only one pointer in the root
162640689478SChris Mason 	 * by promoting the node below to a root
162740689478SChris Mason 	 */
16285f39d397SChris Mason 	if (!parent) {
16295f39d397SChris Mason 		struct extent_buffer *child;
1630bb803951SChris Mason 
16315f39d397SChris Mason 		if (btrfs_header_nritems(mid) != 1)
1632bb803951SChris Mason 			return 0;
1633bb803951SChris Mason 
1634bb803951SChris Mason 		/* promote the child to a root */
16355f39d397SChris Mason 		child = read_node_slot(root, mid, 0);
1636305a26afSMark Fasheh 		if (!child) {
1637305a26afSMark Fasheh 			ret = -EROFS;
1638305a26afSMark Fasheh 			btrfs_std_error(root->fs_info, ret);
1639305a26afSMark Fasheh 			goto enospc;
1640305a26afSMark Fasheh 		}
1641305a26afSMark Fasheh 
1642925baeddSChris Mason 		btrfs_tree_lock(child);
1643b4ce94deSChris Mason 		btrfs_set_lock_blocking(child);
16449fa8cfe7SChris Mason 		ret = btrfs_cow_block(trans, root, child, mid, 0, &child);
1645f0486c68SYan, Zheng 		if (ret) {
1646f0486c68SYan, Zheng 			btrfs_tree_unlock(child);
1647f0486c68SYan, Zheng 			free_extent_buffer(child);
1648f0486c68SYan, Zheng 			goto enospc;
1649f0486c68SYan, Zheng 		}
16502f375ab9SYan 
1651f230475eSJan Schmidt 		tree_mod_log_set_root_pointer(root, child);
1652240f62c8SChris Mason 		rcu_assign_pointer(root->node, child);
1653925baeddSChris Mason 
16540b86a832SChris Mason 		add_root_to_dirty_list(root);
1655925baeddSChris Mason 		btrfs_tree_unlock(child);
1656b4ce94deSChris Mason 
1657925baeddSChris Mason 		path->locks[level] = 0;
1658bb803951SChris Mason 		path->nodes[level] = NULL;
16595f39d397SChris Mason 		clean_tree_block(trans, root, mid);
1660925baeddSChris Mason 		btrfs_tree_unlock(mid);
1661bb803951SChris Mason 		/* once for the path */
16625f39d397SChris Mason 		free_extent_buffer(mid);
1663f0486c68SYan, Zheng 
1664f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
16655581a51aSJan Schmidt 		btrfs_free_tree_block(trans, root, mid, 0, 1);
1666bb803951SChris Mason 		/* once for the root ptr */
16673083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
1668f0486c68SYan, Zheng 		return 0;
1669bb803951SChris Mason 	}
16705f39d397SChris Mason 	if (btrfs_header_nritems(mid) >
1671123abc88SChris Mason 	    BTRFS_NODEPTRS_PER_BLOCK(root) / 4)
1672bb803951SChris Mason 		return 0;
1673bb803951SChris Mason 
16745f39d397SChris Mason 	left = read_node_slot(root, parent, pslot - 1);
16755f39d397SChris Mason 	if (left) {
1676925baeddSChris Mason 		btrfs_tree_lock(left);
1677b4ce94deSChris Mason 		btrfs_set_lock_blocking(left);
16785f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, left,
16799fa8cfe7SChris Mason 				       parent, pslot - 1, &left);
168054aa1f4dSChris Mason 		if (wret) {
168154aa1f4dSChris Mason 			ret = wret;
168254aa1f4dSChris Mason 			goto enospc;
168354aa1f4dSChris Mason 		}
16842cc58cf2SChris Mason 	}
16855f39d397SChris Mason 	right = read_node_slot(root, parent, pslot + 1);
16865f39d397SChris Mason 	if (right) {
1687925baeddSChris Mason 		btrfs_tree_lock(right);
1688b4ce94deSChris Mason 		btrfs_set_lock_blocking(right);
16895f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, right,
16909fa8cfe7SChris Mason 				       parent, pslot + 1, &right);
16912cc58cf2SChris Mason 		if (wret) {
16922cc58cf2SChris Mason 			ret = wret;
16932cc58cf2SChris Mason 			goto enospc;
16942cc58cf2SChris Mason 		}
16952cc58cf2SChris Mason 	}
16962cc58cf2SChris Mason 
16972cc58cf2SChris Mason 	/* first, try to make some room in the middle buffer */
16985f39d397SChris Mason 	if (left) {
16995f39d397SChris Mason 		orig_slot += btrfs_header_nritems(left);
1700bce4eae9SChris Mason 		wret = push_node_left(trans, root, left, mid, 1);
170179f95c82SChris Mason 		if (wret < 0)
170279f95c82SChris Mason 			ret = wret;
1703bb803951SChris Mason 	}
170479f95c82SChris Mason 
170579f95c82SChris Mason 	/*
170679f95c82SChris Mason 	 * then try to empty the right most buffer into the middle
170779f95c82SChris Mason 	 */
17085f39d397SChris Mason 	if (right) {
1709971a1f66SChris Mason 		wret = push_node_left(trans, root, mid, right, 1);
171054aa1f4dSChris Mason 		if (wret < 0 && wret != -ENOSPC)
171179f95c82SChris Mason 			ret = wret;
17125f39d397SChris Mason 		if (btrfs_header_nritems(right) == 0) {
17135f39d397SChris Mason 			clean_tree_block(trans, root, right);
1714925baeddSChris Mason 			btrfs_tree_unlock(right);
1715f3ea38daSJan Schmidt 			del_ptr(trans, root, path, level + 1, pslot + 1, 1);
1716f0486c68SYan, Zheng 			root_sub_used(root, right->len);
17175581a51aSJan Schmidt 			btrfs_free_tree_block(trans, root, right, 0, 1);
17183083ee2eSJosef Bacik 			free_extent_buffer_stale(right);
1719f0486c68SYan, Zheng 			right = NULL;
1720bb803951SChris Mason 		} else {
17215f39d397SChris Mason 			struct btrfs_disk_key right_key;
17225f39d397SChris Mason 			btrfs_node_key(right, &right_key, 0);
1723f230475eSJan Schmidt 			tree_mod_log_set_node_key(root->fs_info, parent,
1724f230475eSJan Schmidt 						  &right_key, pslot + 1, 0);
17255f39d397SChris Mason 			btrfs_set_node_key(parent, &right_key, pslot + 1);
17265f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
1727bb803951SChris Mason 		}
1728bb803951SChris Mason 	}
17295f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 1) {
173079f95c82SChris Mason 		/*
173179f95c82SChris Mason 		 * we're not allowed to leave a node with one item in the
173279f95c82SChris Mason 		 * tree during a delete.  A deletion from lower in the tree
173379f95c82SChris Mason 		 * could try to delete the only pointer in this node.
173479f95c82SChris Mason 		 * So, pull some keys from the left.
173579f95c82SChris Mason 		 * There has to be a left pointer at this point because
173679f95c82SChris Mason 		 * otherwise we would have pulled some pointers from the
173779f95c82SChris Mason 		 * right
173879f95c82SChris Mason 		 */
1739305a26afSMark Fasheh 		if (!left) {
1740305a26afSMark Fasheh 			ret = -EROFS;
1741305a26afSMark Fasheh 			btrfs_std_error(root->fs_info, ret);
1742305a26afSMark Fasheh 			goto enospc;
1743305a26afSMark Fasheh 		}
17445f39d397SChris Mason 		wret = balance_node_right(trans, root, mid, left);
174554aa1f4dSChris Mason 		if (wret < 0) {
174679f95c82SChris Mason 			ret = wret;
174754aa1f4dSChris Mason 			goto enospc;
174854aa1f4dSChris Mason 		}
1749bce4eae9SChris Mason 		if (wret == 1) {
1750bce4eae9SChris Mason 			wret = push_node_left(trans, root, left, mid, 1);
1751bce4eae9SChris Mason 			if (wret < 0)
1752bce4eae9SChris Mason 				ret = wret;
1753bce4eae9SChris Mason 		}
175479f95c82SChris Mason 		BUG_ON(wret == 1);
175579f95c82SChris Mason 	}
17565f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 0) {
17575f39d397SChris Mason 		clean_tree_block(trans, root, mid);
1758925baeddSChris Mason 		btrfs_tree_unlock(mid);
1759f3ea38daSJan Schmidt 		del_ptr(trans, root, path, level + 1, pslot, 1);
1760f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
17615581a51aSJan Schmidt 		btrfs_free_tree_block(trans, root, mid, 0, 1);
17623083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
1763f0486c68SYan, Zheng 		mid = NULL;
176479f95c82SChris Mason 	} else {
176579f95c82SChris Mason 		/* update the parent key to reflect our changes */
17665f39d397SChris Mason 		struct btrfs_disk_key mid_key;
17675f39d397SChris Mason 		btrfs_node_key(mid, &mid_key, 0);
1768f230475eSJan Schmidt 		tree_mod_log_set_node_key(root->fs_info, parent, &mid_key,
1769f230475eSJan Schmidt 					  pslot, 0);
17705f39d397SChris Mason 		btrfs_set_node_key(parent, &mid_key, pslot);
17715f39d397SChris Mason 		btrfs_mark_buffer_dirty(parent);
177279f95c82SChris Mason 	}
1773bb803951SChris Mason 
177479f95c82SChris Mason 	/* update the path */
17755f39d397SChris Mason 	if (left) {
17765f39d397SChris Mason 		if (btrfs_header_nritems(left) > orig_slot) {
17775f39d397SChris Mason 			extent_buffer_get(left);
1778925baeddSChris Mason 			/* left was locked after cow */
17795f39d397SChris Mason 			path->nodes[level] = left;
1780bb803951SChris Mason 			path->slots[level + 1] -= 1;
1781bb803951SChris Mason 			path->slots[level] = orig_slot;
1782925baeddSChris Mason 			if (mid) {
1783925baeddSChris Mason 				btrfs_tree_unlock(mid);
17845f39d397SChris Mason 				free_extent_buffer(mid);
1785925baeddSChris Mason 			}
1786bb803951SChris Mason 		} else {
17875f39d397SChris Mason 			orig_slot -= btrfs_header_nritems(left);
1788bb803951SChris Mason 			path->slots[level] = orig_slot;
1789bb803951SChris Mason 		}
1790bb803951SChris Mason 	}
179179f95c82SChris Mason 	/* double check we haven't messed things up */
1792e20d96d6SChris Mason 	if (orig_ptr !=
17935f39d397SChris Mason 	    btrfs_node_blockptr(path->nodes[level], path->slots[level]))
179479f95c82SChris Mason 		BUG();
179554aa1f4dSChris Mason enospc:
1796925baeddSChris Mason 	if (right) {
1797925baeddSChris Mason 		btrfs_tree_unlock(right);
17985f39d397SChris Mason 		free_extent_buffer(right);
1799925baeddSChris Mason 	}
1800925baeddSChris Mason 	if (left) {
1801925baeddSChris Mason 		if (path->nodes[level] != left)
1802925baeddSChris Mason 			btrfs_tree_unlock(left);
18035f39d397SChris Mason 		free_extent_buffer(left);
1804925baeddSChris Mason 	}
1805bb803951SChris Mason 	return ret;
1806bb803951SChris Mason }
1807bb803951SChris Mason 
1808d352ac68SChris Mason /* Node balancing for insertion.  Here we only split or push nodes around
1809d352ac68SChris Mason  * when they are completely full.  This is also done top down, so we
1810d352ac68SChris Mason  * have to be pessimistic.
1811d352ac68SChris Mason  */
1812d397712bSChris Mason static noinline int push_nodes_for_insert(struct btrfs_trans_handle *trans,
1813e66f709bSChris Mason 					  struct btrfs_root *root,
1814e66f709bSChris Mason 					  struct btrfs_path *path, int level)
1815e66f709bSChris Mason {
18165f39d397SChris Mason 	struct extent_buffer *right = NULL;
18175f39d397SChris Mason 	struct extent_buffer *mid;
18185f39d397SChris Mason 	struct extent_buffer *left = NULL;
18195f39d397SChris Mason 	struct extent_buffer *parent = NULL;
1820e66f709bSChris Mason 	int ret = 0;
1821e66f709bSChris Mason 	int wret;
1822e66f709bSChris Mason 	int pslot;
1823e66f709bSChris Mason 	int orig_slot = path->slots[level];
1824e66f709bSChris Mason 
1825e66f709bSChris Mason 	if (level == 0)
1826e66f709bSChris Mason 		return 1;
1827e66f709bSChris Mason 
18285f39d397SChris Mason 	mid = path->nodes[level];
18297bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
1830e66f709bSChris Mason 
1831a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
18325f39d397SChris Mason 		parent = path->nodes[level + 1];
1833e66f709bSChris Mason 		pslot = path->slots[level + 1];
1834a05a9bb1SLi Zefan 	}
1835e66f709bSChris Mason 
18365f39d397SChris Mason 	if (!parent)
1837e66f709bSChris Mason 		return 1;
1838e66f709bSChris Mason 
18395f39d397SChris Mason 	left = read_node_slot(root, parent, pslot - 1);
1840e66f709bSChris Mason 
1841e66f709bSChris Mason 	/* first, try to make some room in the middle buffer */
18425f39d397SChris Mason 	if (left) {
1843e66f709bSChris Mason 		u32 left_nr;
1844925baeddSChris Mason 
1845925baeddSChris Mason 		btrfs_tree_lock(left);
1846b4ce94deSChris Mason 		btrfs_set_lock_blocking(left);
1847b4ce94deSChris Mason 
18485f39d397SChris Mason 		left_nr = btrfs_header_nritems(left);
184933ade1f8SChris Mason 		if (left_nr >= BTRFS_NODEPTRS_PER_BLOCK(root) - 1) {
185033ade1f8SChris Mason 			wret = 1;
185133ade1f8SChris Mason 		} else {
18525f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, left, parent,
18539fa8cfe7SChris Mason 					      pslot - 1, &left);
185454aa1f4dSChris Mason 			if (ret)
185554aa1f4dSChris Mason 				wret = 1;
185654aa1f4dSChris Mason 			else {
185754aa1f4dSChris Mason 				wret = push_node_left(trans, root,
1858971a1f66SChris Mason 						      left, mid, 0);
185954aa1f4dSChris Mason 			}
186033ade1f8SChris Mason 		}
1861e66f709bSChris Mason 		if (wret < 0)
1862e66f709bSChris Mason 			ret = wret;
1863e66f709bSChris Mason 		if (wret == 0) {
18645f39d397SChris Mason 			struct btrfs_disk_key disk_key;
1865e66f709bSChris Mason 			orig_slot += left_nr;
18665f39d397SChris Mason 			btrfs_node_key(mid, &disk_key, 0);
1867f230475eSJan Schmidt 			tree_mod_log_set_node_key(root->fs_info, parent,
1868f230475eSJan Schmidt 						  &disk_key, pslot, 0);
18695f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot);
18705f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
18715f39d397SChris Mason 			if (btrfs_header_nritems(left) > orig_slot) {
18725f39d397SChris Mason 				path->nodes[level] = left;
1873e66f709bSChris Mason 				path->slots[level + 1] -= 1;
1874e66f709bSChris Mason 				path->slots[level] = orig_slot;
1875925baeddSChris Mason 				btrfs_tree_unlock(mid);
18765f39d397SChris Mason 				free_extent_buffer(mid);
1877e66f709bSChris Mason 			} else {
1878e66f709bSChris Mason 				orig_slot -=
18795f39d397SChris Mason 					btrfs_header_nritems(left);
1880e66f709bSChris Mason 				path->slots[level] = orig_slot;
1881925baeddSChris Mason 				btrfs_tree_unlock(left);
18825f39d397SChris Mason 				free_extent_buffer(left);
1883e66f709bSChris Mason 			}
1884e66f709bSChris Mason 			return 0;
1885e66f709bSChris Mason 		}
1886925baeddSChris Mason 		btrfs_tree_unlock(left);
18875f39d397SChris Mason 		free_extent_buffer(left);
1888e66f709bSChris Mason 	}
18895f39d397SChris Mason 	right = read_node_slot(root, parent, pslot + 1);
1890e66f709bSChris Mason 
1891e66f709bSChris Mason 	/*
1892e66f709bSChris Mason 	 * then try to empty the right most buffer into the middle
1893e66f709bSChris Mason 	 */
18945f39d397SChris Mason 	if (right) {
189533ade1f8SChris Mason 		u32 right_nr;
1896b4ce94deSChris Mason 
1897925baeddSChris Mason 		btrfs_tree_lock(right);
1898b4ce94deSChris Mason 		btrfs_set_lock_blocking(right);
1899b4ce94deSChris Mason 
19005f39d397SChris Mason 		right_nr = btrfs_header_nritems(right);
190133ade1f8SChris Mason 		if (right_nr >= BTRFS_NODEPTRS_PER_BLOCK(root) - 1) {
190233ade1f8SChris Mason 			wret = 1;
190333ade1f8SChris Mason 		} else {
19045f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, right,
19055f39d397SChris Mason 					      parent, pslot + 1,
19069fa8cfe7SChris Mason 					      &right);
190754aa1f4dSChris Mason 			if (ret)
190854aa1f4dSChris Mason 				wret = 1;
190954aa1f4dSChris Mason 			else {
191033ade1f8SChris Mason 				wret = balance_node_right(trans, root,
19115f39d397SChris Mason 							  right, mid);
191233ade1f8SChris Mason 			}
191354aa1f4dSChris Mason 		}
1914e66f709bSChris Mason 		if (wret < 0)
1915e66f709bSChris Mason 			ret = wret;
1916e66f709bSChris Mason 		if (wret == 0) {
19175f39d397SChris Mason 			struct btrfs_disk_key disk_key;
19185f39d397SChris Mason 
19195f39d397SChris Mason 			btrfs_node_key(right, &disk_key, 0);
1920f230475eSJan Schmidt 			tree_mod_log_set_node_key(root->fs_info, parent,
1921f230475eSJan Schmidt 						  &disk_key, pslot + 1, 0);
19225f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot + 1);
19235f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
19245f39d397SChris Mason 
19255f39d397SChris Mason 			if (btrfs_header_nritems(mid) <= orig_slot) {
19265f39d397SChris Mason 				path->nodes[level] = right;
1927e66f709bSChris Mason 				path->slots[level + 1] += 1;
1928e66f709bSChris Mason 				path->slots[level] = orig_slot -
19295f39d397SChris Mason 					btrfs_header_nritems(mid);
1930925baeddSChris Mason 				btrfs_tree_unlock(mid);
19315f39d397SChris Mason 				free_extent_buffer(mid);
1932e66f709bSChris Mason 			} else {
1933925baeddSChris Mason 				btrfs_tree_unlock(right);
19345f39d397SChris Mason 				free_extent_buffer(right);
1935e66f709bSChris Mason 			}
1936e66f709bSChris Mason 			return 0;
1937e66f709bSChris Mason 		}
1938925baeddSChris Mason 		btrfs_tree_unlock(right);
19395f39d397SChris Mason 		free_extent_buffer(right);
1940e66f709bSChris Mason 	}
1941e66f709bSChris Mason 	return 1;
1942e66f709bSChris Mason }
1943e66f709bSChris Mason 
194474123bd7SChris Mason /*
1945d352ac68SChris Mason  * readahead one full node of leaves, finding things that are close
1946d352ac68SChris Mason  * to the block in 'slot', and triggering ra on them.
19473c69faecSChris Mason  */
1948c8c42864SChris Mason static void reada_for_search(struct btrfs_root *root,
1949e02119d5SChris Mason 			     struct btrfs_path *path,
195001f46658SChris Mason 			     int level, int slot, u64 objectid)
19513c69faecSChris Mason {
19525f39d397SChris Mason 	struct extent_buffer *node;
195301f46658SChris Mason 	struct btrfs_disk_key disk_key;
19543c69faecSChris Mason 	u32 nritems;
19553c69faecSChris Mason 	u64 search;
1956a7175319SChris Mason 	u64 target;
19576b80053dSChris Mason 	u64 nread = 0;
1958cb25c2eaSJosef Bacik 	u64 gen;
19593c69faecSChris Mason 	int direction = path->reada;
19605f39d397SChris Mason 	struct extent_buffer *eb;
19616b80053dSChris Mason 	u32 nr;
19626b80053dSChris Mason 	u32 blocksize;
19636b80053dSChris Mason 	u32 nscan = 0;
1964db94535dSChris Mason 
1965a6b6e75eSChris Mason 	if (level != 1)
19663c69faecSChris Mason 		return;
19673c69faecSChris Mason 
19686702ed49SChris Mason 	if (!path->nodes[level])
19696702ed49SChris Mason 		return;
19706702ed49SChris Mason 
19715f39d397SChris Mason 	node = path->nodes[level];
1972925baeddSChris Mason 
19733c69faecSChris Mason 	search = btrfs_node_blockptr(node, slot);
19746b80053dSChris Mason 	blocksize = btrfs_level_size(root, level - 1);
19756b80053dSChris Mason 	eb = btrfs_find_tree_block(root, search, blocksize);
19765f39d397SChris Mason 	if (eb) {
19775f39d397SChris Mason 		free_extent_buffer(eb);
19783c69faecSChris Mason 		return;
19793c69faecSChris Mason 	}
19803c69faecSChris Mason 
1981a7175319SChris Mason 	target = search;
19826b80053dSChris Mason 
19835f39d397SChris Mason 	nritems = btrfs_header_nritems(node);
19846b80053dSChris Mason 	nr = slot;
198525b8b936SJosef Bacik 
19863c69faecSChris Mason 	while (1) {
19876b80053dSChris Mason 		if (direction < 0) {
19886b80053dSChris Mason 			if (nr == 0)
19893c69faecSChris Mason 				break;
19906b80053dSChris Mason 			nr--;
19916b80053dSChris Mason 		} else if (direction > 0) {
19926b80053dSChris Mason 			nr++;
19936b80053dSChris Mason 			if (nr >= nritems)
19946b80053dSChris Mason 				break;
19953c69faecSChris Mason 		}
199601f46658SChris Mason 		if (path->reada < 0 && objectid) {
199701f46658SChris Mason 			btrfs_node_key(node, &disk_key, nr);
199801f46658SChris Mason 			if (btrfs_disk_key_objectid(&disk_key) != objectid)
199901f46658SChris Mason 				break;
200001f46658SChris Mason 		}
20016b80053dSChris Mason 		search = btrfs_node_blockptr(node, nr);
2002a7175319SChris Mason 		if ((search <= target && target - search <= 65536) ||
2003a7175319SChris Mason 		    (search > target && search - target <= 65536)) {
2004cb25c2eaSJosef Bacik 			gen = btrfs_node_ptr_generation(node, nr);
2005cb25c2eaSJosef Bacik 			readahead_tree_block(root, search, blocksize, gen);
20066b80053dSChris Mason 			nread += blocksize;
20073c69faecSChris Mason 		}
20086b80053dSChris Mason 		nscan++;
2009a7175319SChris Mason 		if ((nread > 65536 || nscan > 32))
20106b80053dSChris Mason 			break;
20113c69faecSChris Mason 	}
20123c69faecSChris Mason }
2013925baeddSChris Mason 
2014d352ac68SChris Mason /*
2015b4ce94deSChris Mason  * returns -EAGAIN if it had to drop the path, or zero if everything was in
2016b4ce94deSChris Mason  * cache
2017b4ce94deSChris Mason  */
2018b4ce94deSChris Mason static noinline int reada_for_balance(struct btrfs_root *root,
2019b4ce94deSChris Mason 				      struct btrfs_path *path, int level)
2020b4ce94deSChris Mason {
2021b4ce94deSChris Mason 	int slot;
2022b4ce94deSChris Mason 	int nritems;
2023b4ce94deSChris Mason 	struct extent_buffer *parent;
2024b4ce94deSChris Mason 	struct extent_buffer *eb;
2025b4ce94deSChris Mason 	u64 gen;
2026b4ce94deSChris Mason 	u64 block1 = 0;
2027b4ce94deSChris Mason 	u64 block2 = 0;
2028b4ce94deSChris Mason 	int ret = 0;
2029b4ce94deSChris Mason 	int blocksize;
2030b4ce94deSChris Mason 
20318c594ea8SChris Mason 	parent = path->nodes[level + 1];
2032b4ce94deSChris Mason 	if (!parent)
2033b4ce94deSChris Mason 		return 0;
2034b4ce94deSChris Mason 
2035b4ce94deSChris Mason 	nritems = btrfs_header_nritems(parent);
20368c594ea8SChris Mason 	slot = path->slots[level + 1];
2037b4ce94deSChris Mason 	blocksize = btrfs_level_size(root, level);
2038b4ce94deSChris Mason 
2039b4ce94deSChris Mason 	if (slot > 0) {
2040b4ce94deSChris Mason 		block1 = btrfs_node_blockptr(parent, slot - 1);
2041b4ce94deSChris Mason 		gen = btrfs_node_ptr_generation(parent, slot - 1);
2042b4ce94deSChris Mason 		eb = btrfs_find_tree_block(root, block1, blocksize);
2043b9fab919SChris Mason 		/*
2044b9fab919SChris Mason 		 * if we get -eagain from btrfs_buffer_uptodate, we
2045b9fab919SChris Mason 		 * don't want to return eagain here.  That will loop
2046b9fab919SChris Mason 		 * forever
2047b9fab919SChris Mason 		 */
2048b9fab919SChris Mason 		if (eb && btrfs_buffer_uptodate(eb, gen, 1) != 0)
2049b4ce94deSChris Mason 			block1 = 0;
2050b4ce94deSChris Mason 		free_extent_buffer(eb);
2051b4ce94deSChris Mason 	}
20528c594ea8SChris Mason 	if (slot + 1 < nritems) {
2053b4ce94deSChris Mason 		block2 = btrfs_node_blockptr(parent, slot + 1);
2054b4ce94deSChris Mason 		gen = btrfs_node_ptr_generation(parent, slot + 1);
2055b4ce94deSChris Mason 		eb = btrfs_find_tree_block(root, block2, blocksize);
2056b9fab919SChris Mason 		if (eb && btrfs_buffer_uptodate(eb, gen, 1) != 0)
2057b4ce94deSChris Mason 			block2 = 0;
2058b4ce94deSChris Mason 		free_extent_buffer(eb);
2059b4ce94deSChris Mason 	}
2060b4ce94deSChris Mason 	if (block1 || block2) {
2061b4ce94deSChris Mason 		ret = -EAGAIN;
20628c594ea8SChris Mason 
20638c594ea8SChris Mason 		/* release the whole path */
2064b3b4aa74SDavid Sterba 		btrfs_release_path(path);
20658c594ea8SChris Mason 
20668c594ea8SChris Mason 		/* read the blocks */
2067b4ce94deSChris Mason 		if (block1)
2068b4ce94deSChris Mason 			readahead_tree_block(root, block1, blocksize, 0);
2069b4ce94deSChris Mason 		if (block2)
2070b4ce94deSChris Mason 			readahead_tree_block(root, block2, blocksize, 0);
2071b4ce94deSChris Mason 
2072b4ce94deSChris Mason 		if (block1) {
2073b4ce94deSChris Mason 			eb = read_tree_block(root, block1, blocksize, 0);
2074b4ce94deSChris Mason 			free_extent_buffer(eb);
2075b4ce94deSChris Mason 		}
20768c594ea8SChris Mason 		if (block2) {
2077b4ce94deSChris Mason 			eb = read_tree_block(root, block2, blocksize, 0);
2078b4ce94deSChris Mason 			free_extent_buffer(eb);
2079b4ce94deSChris Mason 		}
2080b4ce94deSChris Mason 	}
2081b4ce94deSChris Mason 	return ret;
2082b4ce94deSChris Mason }
2083b4ce94deSChris Mason 
2084b4ce94deSChris Mason 
2085b4ce94deSChris Mason /*
2086d397712bSChris Mason  * when we walk down the tree, it is usually safe to unlock the higher layers
2087d397712bSChris Mason  * in the tree.  The exceptions are when our path goes through slot 0, because
2088d397712bSChris Mason  * operations on the tree might require changing key pointers higher up in the
2089d397712bSChris Mason  * tree.
2090d352ac68SChris Mason  *
2091d397712bSChris Mason  * callers might also have set path->keep_locks, which tells this code to keep
2092d397712bSChris Mason  * the lock if the path points to the last slot in the block.  This is part of
2093d397712bSChris Mason  * walking through the tree, and selecting the next slot in the higher block.
2094d352ac68SChris Mason  *
2095d397712bSChris Mason  * lowest_unlock sets the lowest level in the tree we're allowed to unlock.  so
2096d397712bSChris Mason  * if lowest_unlock is 1, level 0 won't be unlocked
2097d352ac68SChris Mason  */
2098e02119d5SChris Mason static noinline void unlock_up(struct btrfs_path *path, int level,
2099f7c79f30SChris Mason 			       int lowest_unlock, int min_write_lock_level,
2100f7c79f30SChris Mason 			       int *write_lock_level)
2101925baeddSChris Mason {
2102925baeddSChris Mason 	int i;
2103925baeddSChris Mason 	int skip_level = level;
2104051e1b9fSChris Mason 	int no_skips = 0;
2105925baeddSChris Mason 	struct extent_buffer *t;
2106925baeddSChris Mason 
2107925baeddSChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2108925baeddSChris Mason 		if (!path->nodes[i])
2109925baeddSChris Mason 			break;
2110925baeddSChris Mason 		if (!path->locks[i])
2111925baeddSChris Mason 			break;
2112051e1b9fSChris Mason 		if (!no_skips && path->slots[i] == 0) {
2113925baeddSChris Mason 			skip_level = i + 1;
2114925baeddSChris Mason 			continue;
2115925baeddSChris Mason 		}
2116051e1b9fSChris Mason 		if (!no_skips && path->keep_locks) {
2117925baeddSChris Mason 			u32 nritems;
2118925baeddSChris Mason 			t = path->nodes[i];
2119925baeddSChris Mason 			nritems = btrfs_header_nritems(t);
2120051e1b9fSChris Mason 			if (nritems < 1 || path->slots[i] >= nritems - 1) {
2121925baeddSChris Mason 				skip_level = i + 1;
2122925baeddSChris Mason 				continue;
2123925baeddSChris Mason 			}
2124925baeddSChris Mason 		}
2125051e1b9fSChris Mason 		if (skip_level < i && i >= lowest_unlock)
2126051e1b9fSChris Mason 			no_skips = 1;
2127051e1b9fSChris Mason 
2128925baeddSChris Mason 		t = path->nodes[i];
2129925baeddSChris Mason 		if (i >= lowest_unlock && i > skip_level && path->locks[i]) {
2130bd681513SChris Mason 			btrfs_tree_unlock_rw(t, path->locks[i]);
2131925baeddSChris Mason 			path->locks[i] = 0;
2132f7c79f30SChris Mason 			if (write_lock_level &&
2133f7c79f30SChris Mason 			    i > min_write_lock_level &&
2134f7c79f30SChris Mason 			    i <= *write_lock_level) {
2135f7c79f30SChris Mason 				*write_lock_level = i - 1;
2136f7c79f30SChris Mason 			}
2137925baeddSChris Mason 		}
2138925baeddSChris Mason 	}
2139925baeddSChris Mason }
2140925baeddSChris Mason 
21413c69faecSChris Mason /*
2142b4ce94deSChris Mason  * This releases any locks held in the path starting at level and
2143b4ce94deSChris Mason  * going all the way up to the root.
2144b4ce94deSChris Mason  *
2145b4ce94deSChris Mason  * btrfs_search_slot will keep the lock held on higher nodes in a few
2146b4ce94deSChris Mason  * corner cases, such as COW of the block at slot zero in the node.  This
2147b4ce94deSChris Mason  * ignores those rules, and it should only be called when there are no
2148b4ce94deSChris Mason  * more updates to be done higher up in the tree.
2149b4ce94deSChris Mason  */
2150b4ce94deSChris Mason noinline void btrfs_unlock_up_safe(struct btrfs_path *path, int level)
2151b4ce94deSChris Mason {
2152b4ce94deSChris Mason 	int i;
2153b4ce94deSChris Mason 
21545d4f98a2SYan Zheng 	if (path->keep_locks)
2155b4ce94deSChris Mason 		return;
2156b4ce94deSChris Mason 
2157b4ce94deSChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2158b4ce94deSChris Mason 		if (!path->nodes[i])
215912f4daccSChris Mason 			continue;
2160b4ce94deSChris Mason 		if (!path->locks[i])
216112f4daccSChris Mason 			continue;
2162bd681513SChris Mason 		btrfs_tree_unlock_rw(path->nodes[i], path->locks[i]);
2163b4ce94deSChris Mason 		path->locks[i] = 0;
2164b4ce94deSChris Mason 	}
2165b4ce94deSChris Mason }
2166b4ce94deSChris Mason 
2167b4ce94deSChris Mason /*
2168c8c42864SChris Mason  * helper function for btrfs_search_slot.  The goal is to find a block
2169c8c42864SChris Mason  * in cache without setting the path to blocking.  If we find the block
2170c8c42864SChris Mason  * we return zero and the path is unchanged.
2171c8c42864SChris Mason  *
2172c8c42864SChris Mason  * If we can't find the block, we set the path blocking and do some
2173c8c42864SChris Mason  * reada.  -EAGAIN is returned and the search must be repeated.
2174c8c42864SChris Mason  */
2175c8c42864SChris Mason static int
2176c8c42864SChris Mason read_block_for_search(struct btrfs_trans_handle *trans,
2177c8c42864SChris Mason 		       struct btrfs_root *root, struct btrfs_path *p,
2178c8c42864SChris Mason 		       struct extent_buffer **eb_ret, int level, int slot,
21795d9e75c4SJan Schmidt 		       struct btrfs_key *key, u64 time_seq)
2180c8c42864SChris Mason {
2181c8c42864SChris Mason 	u64 blocknr;
2182c8c42864SChris Mason 	u64 gen;
2183c8c42864SChris Mason 	u32 blocksize;
2184c8c42864SChris Mason 	struct extent_buffer *b = *eb_ret;
2185c8c42864SChris Mason 	struct extent_buffer *tmp;
218676a05b35SChris Mason 	int ret;
2187c8c42864SChris Mason 
2188c8c42864SChris Mason 	blocknr = btrfs_node_blockptr(b, slot);
2189c8c42864SChris Mason 	gen = btrfs_node_ptr_generation(b, slot);
2190c8c42864SChris Mason 	blocksize = btrfs_level_size(root, level - 1);
2191c8c42864SChris Mason 
2192c8c42864SChris Mason 	tmp = btrfs_find_tree_block(root, blocknr, blocksize);
2193cb44921aSChris Mason 	if (tmp) {
2194b9fab919SChris Mason 		/* first we do an atomic uptodate check */
2195b9fab919SChris Mason 		if (btrfs_buffer_uptodate(tmp, 0, 1) > 0) {
2196b9fab919SChris Mason 			if (btrfs_buffer_uptodate(tmp, gen, 1) > 0) {
219776a05b35SChris Mason 				/*
2198cb44921aSChris Mason 				 * we found an up to date block without
2199cb44921aSChris Mason 				 * sleeping, return
220076a05b35SChris Mason 				 * right away
220176a05b35SChris Mason 				 */
2202c8c42864SChris Mason 				*eb_ret = tmp;
2203c8c42864SChris Mason 				return 0;
2204c8c42864SChris Mason 			}
2205cb44921aSChris Mason 			/* the pages were up to date, but we failed
2206cb44921aSChris Mason 			 * the generation number check.  Do a full
2207cb44921aSChris Mason 			 * read for the generation number that is correct.
2208cb44921aSChris Mason 			 * We must do this without dropping locks so
2209cb44921aSChris Mason 			 * we can trust our generation number
2210cb44921aSChris Mason 			 */
2211cb44921aSChris Mason 			free_extent_buffer(tmp);
2212bd681513SChris Mason 			btrfs_set_path_blocking(p);
2213bd681513SChris Mason 
2214b9fab919SChris Mason 			/* now we're allowed to do a blocking uptodate check */
2215cb44921aSChris Mason 			tmp = read_tree_block(root, blocknr, blocksize, gen);
2216b9fab919SChris Mason 			if (tmp && btrfs_buffer_uptodate(tmp, gen, 0) > 0) {
2217cb44921aSChris Mason 				*eb_ret = tmp;
2218cb44921aSChris Mason 				return 0;
2219cb44921aSChris Mason 			}
2220cb44921aSChris Mason 			free_extent_buffer(tmp);
2221b3b4aa74SDavid Sterba 			btrfs_release_path(p);
2222cb44921aSChris Mason 			return -EIO;
2223cb44921aSChris Mason 		}
2224cb44921aSChris Mason 	}
2225c8c42864SChris Mason 
2226c8c42864SChris Mason 	/*
2227c8c42864SChris Mason 	 * reduce lock contention at high levels
2228c8c42864SChris Mason 	 * of the btree by dropping locks before
222976a05b35SChris Mason 	 * we read.  Don't release the lock on the current
223076a05b35SChris Mason 	 * level because we need to walk this node to figure
223176a05b35SChris Mason 	 * out which blocks to read.
2232c8c42864SChris Mason 	 */
22338c594ea8SChris Mason 	btrfs_unlock_up_safe(p, level + 1);
22348c594ea8SChris Mason 	btrfs_set_path_blocking(p);
22358c594ea8SChris Mason 
2236c8c42864SChris Mason 	free_extent_buffer(tmp);
2237c8c42864SChris Mason 	if (p->reada)
2238c8c42864SChris Mason 		reada_for_search(root, p, level, slot, key->objectid);
2239c8c42864SChris Mason 
2240b3b4aa74SDavid Sterba 	btrfs_release_path(p);
224176a05b35SChris Mason 
224276a05b35SChris Mason 	ret = -EAGAIN;
22435bdd3536SYan, Zheng 	tmp = read_tree_block(root, blocknr, blocksize, 0);
224476a05b35SChris Mason 	if (tmp) {
224576a05b35SChris Mason 		/*
224676a05b35SChris Mason 		 * If the read above didn't mark this buffer up to date,
224776a05b35SChris Mason 		 * it will never end up being up to date.  Set ret to EIO now
224876a05b35SChris Mason 		 * and give up so that our caller doesn't loop forever
224976a05b35SChris Mason 		 * on our EAGAINs.
225076a05b35SChris Mason 		 */
2251b9fab919SChris Mason 		if (!btrfs_buffer_uptodate(tmp, 0, 0))
225276a05b35SChris Mason 			ret = -EIO;
2253c8c42864SChris Mason 		free_extent_buffer(tmp);
225476a05b35SChris Mason 	}
225576a05b35SChris Mason 	return ret;
2256c8c42864SChris Mason }
2257c8c42864SChris Mason 
2258c8c42864SChris Mason /*
2259c8c42864SChris Mason  * helper function for btrfs_search_slot.  This does all of the checks
2260c8c42864SChris Mason  * for node-level blocks and does any balancing required based on
2261c8c42864SChris Mason  * the ins_len.
2262c8c42864SChris Mason  *
2263c8c42864SChris Mason  * If no extra work was required, zero is returned.  If we had to
2264c8c42864SChris Mason  * drop the path, -EAGAIN is returned and btrfs_search_slot must
2265c8c42864SChris Mason  * start over
2266c8c42864SChris Mason  */
2267c8c42864SChris Mason static int
2268c8c42864SChris Mason setup_nodes_for_search(struct btrfs_trans_handle *trans,
2269c8c42864SChris Mason 		       struct btrfs_root *root, struct btrfs_path *p,
2270bd681513SChris Mason 		       struct extent_buffer *b, int level, int ins_len,
2271bd681513SChris Mason 		       int *write_lock_level)
2272c8c42864SChris Mason {
2273c8c42864SChris Mason 	int ret;
2274c8c42864SChris Mason 	if ((p->search_for_split || ins_len > 0) && btrfs_header_nritems(b) >=
2275c8c42864SChris Mason 	    BTRFS_NODEPTRS_PER_BLOCK(root) - 3) {
2276c8c42864SChris Mason 		int sret;
2277c8c42864SChris Mason 
2278bd681513SChris Mason 		if (*write_lock_level < level + 1) {
2279bd681513SChris Mason 			*write_lock_level = level + 1;
2280bd681513SChris Mason 			btrfs_release_path(p);
2281bd681513SChris Mason 			goto again;
2282bd681513SChris Mason 		}
2283bd681513SChris Mason 
2284c8c42864SChris Mason 		sret = reada_for_balance(root, p, level);
2285c8c42864SChris Mason 		if (sret)
2286c8c42864SChris Mason 			goto again;
2287c8c42864SChris Mason 
2288c8c42864SChris Mason 		btrfs_set_path_blocking(p);
2289c8c42864SChris Mason 		sret = split_node(trans, root, p, level);
2290bd681513SChris Mason 		btrfs_clear_path_blocking(p, NULL, 0);
2291c8c42864SChris Mason 
2292c8c42864SChris Mason 		BUG_ON(sret > 0);
2293c8c42864SChris Mason 		if (sret) {
2294c8c42864SChris Mason 			ret = sret;
2295c8c42864SChris Mason 			goto done;
2296c8c42864SChris Mason 		}
2297c8c42864SChris Mason 		b = p->nodes[level];
2298c8c42864SChris Mason 	} else if (ins_len < 0 && btrfs_header_nritems(b) <
2299cfbb9308SChris Mason 		   BTRFS_NODEPTRS_PER_BLOCK(root) / 2) {
2300c8c42864SChris Mason 		int sret;
2301c8c42864SChris Mason 
2302bd681513SChris Mason 		if (*write_lock_level < level + 1) {
2303bd681513SChris Mason 			*write_lock_level = level + 1;
2304bd681513SChris Mason 			btrfs_release_path(p);
2305bd681513SChris Mason 			goto again;
2306bd681513SChris Mason 		}
2307bd681513SChris Mason 
2308c8c42864SChris Mason 		sret = reada_for_balance(root, p, level);
2309c8c42864SChris Mason 		if (sret)
2310c8c42864SChris Mason 			goto again;
2311c8c42864SChris Mason 
2312c8c42864SChris Mason 		btrfs_set_path_blocking(p);
2313c8c42864SChris Mason 		sret = balance_level(trans, root, p, level);
2314bd681513SChris Mason 		btrfs_clear_path_blocking(p, NULL, 0);
2315c8c42864SChris Mason 
2316c8c42864SChris Mason 		if (sret) {
2317c8c42864SChris Mason 			ret = sret;
2318c8c42864SChris Mason 			goto done;
2319c8c42864SChris Mason 		}
2320c8c42864SChris Mason 		b = p->nodes[level];
2321c8c42864SChris Mason 		if (!b) {
2322b3b4aa74SDavid Sterba 			btrfs_release_path(p);
2323c8c42864SChris Mason 			goto again;
2324c8c42864SChris Mason 		}
2325c8c42864SChris Mason 		BUG_ON(btrfs_header_nritems(b) == 1);
2326c8c42864SChris Mason 	}
2327c8c42864SChris Mason 	return 0;
2328c8c42864SChris Mason 
2329c8c42864SChris Mason again:
2330c8c42864SChris Mason 	ret = -EAGAIN;
2331c8c42864SChris Mason done:
2332c8c42864SChris Mason 	return ret;
2333c8c42864SChris Mason }
2334c8c42864SChris Mason 
2335c8c42864SChris Mason /*
233674123bd7SChris Mason  * look for key in the tree.  path is filled in with nodes along the way
233774123bd7SChris Mason  * if key is found, we return zero and you can find the item in the leaf
233874123bd7SChris Mason  * level of the path (level 0)
233974123bd7SChris Mason  *
234074123bd7SChris Mason  * If the key isn't found, the path points to the slot where it should
2341aa5d6bedSChris Mason  * be inserted, and 1 is returned.  If there are other errors during the
2342aa5d6bedSChris Mason  * search a negative error number is returned.
234397571fd0SChris Mason  *
234497571fd0SChris Mason  * if ins_len > 0, nodes and leaves will be split as we walk down the
234597571fd0SChris Mason  * tree.  if ins_len < 0, nodes will be merged as we walk down the tree (if
234697571fd0SChris Mason  * possible)
234774123bd7SChris Mason  */
2348e089f05cSChris Mason int btrfs_search_slot(struct btrfs_trans_handle *trans, struct btrfs_root
2349e089f05cSChris Mason 		      *root, struct btrfs_key *key, struct btrfs_path *p, int
2350e089f05cSChris Mason 		      ins_len, int cow)
2351be0e5c09SChris Mason {
23525f39d397SChris Mason 	struct extent_buffer *b;
2353be0e5c09SChris Mason 	int slot;
2354be0e5c09SChris Mason 	int ret;
235533c66f43SYan Zheng 	int err;
2356be0e5c09SChris Mason 	int level;
2357925baeddSChris Mason 	int lowest_unlock = 1;
2358bd681513SChris Mason 	int root_lock;
2359bd681513SChris Mason 	/* everything at write_lock_level or lower must be write locked */
2360bd681513SChris Mason 	int write_lock_level = 0;
23619f3a7427SChris Mason 	u8 lowest_level = 0;
2362f7c79f30SChris Mason 	int min_write_lock_level;
23639f3a7427SChris Mason 
23646702ed49SChris Mason 	lowest_level = p->lowest_level;
2365323ac95bSChris Mason 	WARN_ON(lowest_level && ins_len > 0);
236622b0ebdaSChris Mason 	WARN_ON(p->nodes[0] != NULL);
236725179201SJosef Bacik 
2368bd681513SChris Mason 	if (ins_len < 0) {
2369925baeddSChris Mason 		lowest_unlock = 2;
237065b51a00SChris Mason 
2371bd681513SChris Mason 		/* when we are removing items, we might have to go up to level
2372bd681513SChris Mason 		 * two as we update tree pointers  Make sure we keep write
2373bd681513SChris Mason 		 * for those levels as well
2374bd681513SChris Mason 		 */
2375bd681513SChris Mason 		write_lock_level = 2;
2376bd681513SChris Mason 	} else if (ins_len > 0) {
2377bd681513SChris Mason 		/*
2378bd681513SChris Mason 		 * for inserting items, make sure we have a write lock on
2379bd681513SChris Mason 		 * level 1 so we can update keys
2380bd681513SChris Mason 		 */
2381bd681513SChris Mason 		write_lock_level = 1;
2382bd681513SChris Mason 	}
2383bd681513SChris Mason 
2384bd681513SChris Mason 	if (!cow)
2385bd681513SChris Mason 		write_lock_level = -1;
2386bd681513SChris Mason 
2387bd681513SChris Mason 	if (cow && (p->keep_locks || p->lowest_level))
2388bd681513SChris Mason 		write_lock_level = BTRFS_MAX_LEVEL;
2389bd681513SChris Mason 
2390f7c79f30SChris Mason 	min_write_lock_level = write_lock_level;
2391f7c79f30SChris Mason 
2392bb803951SChris Mason again:
2393bd681513SChris Mason 	/*
2394bd681513SChris Mason 	 * we try very hard to do read locks on the root
2395bd681513SChris Mason 	 */
2396bd681513SChris Mason 	root_lock = BTRFS_READ_LOCK;
2397bd681513SChris Mason 	level = 0;
23985d4f98a2SYan Zheng 	if (p->search_commit_root) {
2399bd681513SChris Mason 		/*
2400bd681513SChris Mason 		 * the commit roots are read only
2401bd681513SChris Mason 		 * so we always do read locks
2402bd681513SChris Mason 		 */
24035d4f98a2SYan Zheng 		b = root->commit_root;
24045d4f98a2SYan Zheng 		extent_buffer_get(b);
2405bd681513SChris Mason 		level = btrfs_header_level(b);
24065d4f98a2SYan Zheng 		if (!p->skip_locking)
2407bd681513SChris Mason 			btrfs_tree_read_lock(b);
24085d4f98a2SYan Zheng 	} else {
2409bd681513SChris Mason 		if (p->skip_locking) {
24105cd57b2cSChris Mason 			b = btrfs_root_node(root);
2411bd681513SChris Mason 			level = btrfs_header_level(b);
2412bd681513SChris Mason 		} else {
2413bd681513SChris Mason 			/* we don't know the level of the root node
2414bd681513SChris Mason 			 * until we actually have it read locked
2415bd681513SChris Mason 			 */
2416bd681513SChris Mason 			b = btrfs_read_lock_root_node(root);
2417bd681513SChris Mason 			level = btrfs_header_level(b);
2418bd681513SChris Mason 			if (level <= write_lock_level) {
2419bd681513SChris Mason 				/* whoops, must trade for write lock */
2420bd681513SChris Mason 				btrfs_tree_read_unlock(b);
2421bd681513SChris Mason 				free_extent_buffer(b);
2422925baeddSChris Mason 				b = btrfs_lock_root_node(root);
2423bd681513SChris Mason 				root_lock = BTRFS_WRITE_LOCK;
2424bd681513SChris Mason 
2425bd681513SChris Mason 				/* the level might have changed, check again */
2426bd681513SChris Mason 				level = btrfs_header_level(b);
24275d4f98a2SYan Zheng 			}
2428bd681513SChris Mason 		}
2429bd681513SChris Mason 	}
2430bd681513SChris Mason 	p->nodes[level] = b;
2431bd681513SChris Mason 	if (!p->skip_locking)
2432bd681513SChris Mason 		p->locks[level] = root_lock;
2433925baeddSChris Mason 
2434eb60ceacSChris Mason 	while (b) {
24355f39d397SChris Mason 		level = btrfs_header_level(b);
243665b51a00SChris Mason 
243765b51a00SChris Mason 		/*
243865b51a00SChris Mason 		 * setup the path here so we can release it under lock
243965b51a00SChris Mason 		 * contention with the cow code
244065b51a00SChris Mason 		 */
244102217ed2SChris Mason 		if (cow) {
2442c8c42864SChris Mason 			/*
2443c8c42864SChris Mason 			 * if we don't really need to cow this block
2444c8c42864SChris Mason 			 * then we don't want to set the path blocking,
2445c8c42864SChris Mason 			 * so we test it here
2446c8c42864SChris Mason 			 */
24475d4f98a2SYan Zheng 			if (!should_cow_block(trans, root, b))
244865b51a00SChris Mason 				goto cow_done;
24495d4f98a2SYan Zheng 
2450b4ce94deSChris Mason 			btrfs_set_path_blocking(p);
2451b4ce94deSChris Mason 
2452bd681513SChris Mason 			/*
2453bd681513SChris Mason 			 * must have write locks on this node and the
2454bd681513SChris Mason 			 * parent
2455bd681513SChris Mason 			 */
2456bd681513SChris Mason 			if (level + 1 > write_lock_level) {
2457bd681513SChris Mason 				write_lock_level = level + 1;
2458bd681513SChris Mason 				btrfs_release_path(p);
2459bd681513SChris Mason 				goto again;
2460bd681513SChris Mason 			}
2461bd681513SChris Mason 
246233c66f43SYan Zheng 			err = btrfs_cow_block(trans, root, b,
2463e20d96d6SChris Mason 					      p->nodes[level + 1],
24649fa8cfe7SChris Mason 					      p->slots[level + 1], &b);
246533c66f43SYan Zheng 			if (err) {
246633c66f43SYan Zheng 				ret = err;
246765b51a00SChris Mason 				goto done;
246854aa1f4dSChris Mason 			}
246902217ed2SChris Mason 		}
247065b51a00SChris Mason cow_done:
247102217ed2SChris Mason 		BUG_ON(!cow && ins_len);
247265b51a00SChris Mason 
2473eb60ceacSChris Mason 		p->nodes[level] = b;
2474bd681513SChris Mason 		btrfs_clear_path_blocking(p, NULL, 0);
2475b4ce94deSChris Mason 
2476b4ce94deSChris Mason 		/*
2477b4ce94deSChris Mason 		 * we have a lock on b and as long as we aren't changing
2478b4ce94deSChris Mason 		 * the tree, there is no way to for the items in b to change.
2479b4ce94deSChris Mason 		 * It is safe to drop the lock on our parent before we
2480b4ce94deSChris Mason 		 * go through the expensive btree search on b.
2481b4ce94deSChris Mason 		 *
2482b4ce94deSChris Mason 		 * If cow is true, then we might be changing slot zero,
2483b4ce94deSChris Mason 		 * which may require changing the parent.  So, we can't
2484b4ce94deSChris Mason 		 * drop the lock until after we know which slot we're
2485b4ce94deSChris Mason 		 * operating on.
2486b4ce94deSChris Mason 		 */
2487b4ce94deSChris Mason 		if (!cow)
2488b4ce94deSChris Mason 			btrfs_unlock_up_safe(p, level + 1);
2489b4ce94deSChris Mason 
24905f39d397SChris Mason 		ret = bin_search(b, key, level, &slot);
2491b4ce94deSChris Mason 
24925f39d397SChris Mason 		if (level != 0) {
249333c66f43SYan Zheng 			int dec = 0;
249433c66f43SYan Zheng 			if (ret && slot > 0) {
249533c66f43SYan Zheng 				dec = 1;
2496be0e5c09SChris Mason 				slot -= 1;
249733c66f43SYan Zheng 			}
2498be0e5c09SChris Mason 			p->slots[level] = slot;
249933c66f43SYan Zheng 			err = setup_nodes_for_search(trans, root, p, b, level,
2500bd681513SChris Mason 					     ins_len, &write_lock_level);
250133c66f43SYan Zheng 			if (err == -EAGAIN)
2502b4ce94deSChris Mason 				goto again;
250333c66f43SYan Zheng 			if (err) {
250433c66f43SYan Zheng 				ret = err;
250565b51a00SChris Mason 				goto done;
250633c66f43SYan Zheng 			}
25075c680ed6SChris Mason 			b = p->nodes[level];
25085c680ed6SChris Mason 			slot = p->slots[level];
2509b4ce94deSChris Mason 
2510bd681513SChris Mason 			/*
2511bd681513SChris Mason 			 * slot 0 is special, if we change the key
2512bd681513SChris Mason 			 * we have to update the parent pointer
2513bd681513SChris Mason 			 * which means we must have a write lock
2514bd681513SChris Mason 			 * on the parent
2515bd681513SChris Mason 			 */
2516bd681513SChris Mason 			if (slot == 0 && cow &&
2517bd681513SChris Mason 			    write_lock_level < level + 1) {
2518bd681513SChris Mason 				write_lock_level = level + 1;
2519bd681513SChris Mason 				btrfs_release_path(p);
2520bd681513SChris Mason 				goto again;
2521bd681513SChris Mason 			}
2522bd681513SChris Mason 
2523f7c79f30SChris Mason 			unlock_up(p, level, lowest_unlock,
2524f7c79f30SChris Mason 				  min_write_lock_level, &write_lock_level);
2525f9efa9c7SChris Mason 
2526925baeddSChris Mason 			if (level == lowest_level) {
252733c66f43SYan Zheng 				if (dec)
252833c66f43SYan Zheng 					p->slots[level]++;
25295b21f2edSZheng Yan 				goto done;
2530925baeddSChris Mason 			}
2531ca7a79adSChris Mason 
253233c66f43SYan Zheng 			err = read_block_for_search(trans, root, p,
25335d9e75c4SJan Schmidt 						    &b, level, slot, key, 0);
253433c66f43SYan Zheng 			if (err == -EAGAIN)
2535051e1b9fSChris Mason 				goto again;
253633c66f43SYan Zheng 			if (err) {
253733c66f43SYan Zheng 				ret = err;
253876a05b35SChris Mason 				goto done;
253933c66f43SYan Zheng 			}
254076a05b35SChris Mason 
2541b4ce94deSChris Mason 			if (!p->skip_locking) {
2542bd681513SChris Mason 				level = btrfs_header_level(b);
2543bd681513SChris Mason 				if (level <= write_lock_level) {
2544bd681513SChris Mason 					err = btrfs_try_tree_write_lock(b);
254533c66f43SYan Zheng 					if (!err) {
2546b4ce94deSChris Mason 						btrfs_set_path_blocking(p);
2547925baeddSChris Mason 						btrfs_tree_lock(b);
2548bd681513SChris Mason 						btrfs_clear_path_blocking(p, b,
2549bd681513SChris Mason 								  BTRFS_WRITE_LOCK);
2550b4ce94deSChris Mason 					}
2551bd681513SChris Mason 					p->locks[level] = BTRFS_WRITE_LOCK;
2552bd681513SChris Mason 				} else {
2553bd681513SChris Mason 					err = btrfs_try_tree_read_lock(b);
2554bd681513SChris Mason 					if (!err) {
2555bd681513SChris Mason 						btrfs_set_path_blocking(p);
2556bd681513SChris Mason 						btrfs_tree_read_lock(b);
2557bd681513SChris Mason 						btrfs_clear_path_blocking(p, b,
2558bd681513SChris Mason 								  BTRFS_READ_LOCK);
2559bd681513SChris Mason 					}
2560bd681513SChris Mason 					p->locks[level] = BTRFS_READ_LOCK;
2561bd681513SChris Mason 				}
2562bd681513SChris Mason 				p->nodes[level] = b;
2563b4ce94deSChris Mason 			}
2564be0e5c09SChris Mason 		} else {
2565be0e5c09SChris Mason 			p->slots[level] = slot;
256687b29b20SYan Zheng 			if (ins_len > 0 &&
256787b29b20SYan Zheng 			    btrfs_leaf_free_space(root, b) < ins_len) {
2568bd681513SChris Mason 				if (write_lock_level < 1) {
2569bd681513SChris Mason 					write_lock_level = 1;
2570bd681513SChris Mason 					btrfs_release_path(p);
2571bd681513SChris Mason 					goto again;
2572bd681513SChris Mason 				}
2573bd681513SChris Mason 
2574b4ce94deSChris Mason 				btrfs_set_path_blocking(p);
257533c66f43SYan Zheng 				err = split_leaf(trans, root, key,
2576cc0c5538SChris Mason 						 p, ins_len, ret == 0);
2577bd681513SChris Mason 				btrfs_clear_path_blocking(p, NULL, 0);
2578b4ce94deSChris Mason 
257933c66f43SYan Zheng 				BUG_ON(err > 0);
258033c66f43SYan Zheng 				if (err) {
258133c66f43SYan Zheng 					ret = err;
258265b51a00SChris Mason 					goto done;
258365b51a00SChris Mason 				}
25845c680ed6SChris Mason 			}
2585459931ecSChris Mason 			if (!p->search_for_split)
2586f7c79f30SChris Mason 				unlock_up(p, level, lowest_unlock,
2587f7c79f30SChris Mason 					  min_write_lock_level, &write_lock_level);
258865b51a00SChris Mason 			goto done;
258965b51a00SChris Mason 		}
259065b51a00SChris Mason 	}
259165b51a00SChris Mason 	ret = 1;
259265b51a00SChris Mason done:
2593b4ce94deSChris Mason 	/*
2594b4ce94deSChris Mason 	 * we don't really know what they plan on doing with the path
2595b4ce94deSChris Mason 	 * from here on, so for now just mark it as blocking
2596b4ce94deSChris Mason 	 */
2597b9473439SChris Mason 	if (!p->leave_spinning)
2598b4ce94deSChris Mason 		btrfs_set_path_blocking(p);
259976a05b35SChris Mason 	if (ret < 0)
2600b3b4aa74SDavid Sterba 		btrfs_release_path(p);
2601be0e5c09SChris Mason 	return ret;
2602be0e5c09SChris Mason }
2603be0e5c09SChris Mason 
260474123bd7SChris Mason /*
26055d9e75c4SJan Schmidt  * Like btrfs_search_slot, this looks for a key in the given tree. It uses the
26065d9e75c4SJan Schmidt  * current state of the tree together with the operations recorded in the tree
26075d9e75c4SJan Schmidt  * modification log to search for the key in a previous version of this tree, as
26085d9e75c4SJan Schmidt  * denoted by the time_seq parameter.
26095d9e75c4SJan Schmidt  *
26105d9e75c4SJan Schmidt  * Naturally, there is no support for insert, delete or cow operations.
26115d9e75c4SJan Schmidt  *
26125d9e75c4SJan Schmidt  * The resulting path and return value will be set up as if we called
26135d9e75c4SJan Schmidt  * btrfs_search_slot at that point in time with ins_len and cow both set to 0.
26145d9e75c4SJan Schmidt  */
26155d9e75c4SJan Schmidt int btrfs_search_old_slot(struct btrfs_root *root, struct btrfs_key *key,
26165d9e75c4SJan Schmidt 			  struct btrfs_path *p, u64 time_seq)
26175d9e75c4SJan Schmidt {
26185d9e75c4SJan Schmidt 	struct extent_buffer *b;
26195d9e75c4SJan Schmidt 	int slot;
26205d9e75c4SJan Schmidt 	int ret;
26215d9e75c4SJan Schmidt 	int err;
26225d9e75c4SJan Schmidt 	int level;
26235d9e75c4SJan Schmidt 	int lowest_unlock = 1;
26245d9e75c4SJan Schmidt 	u8 lowest_level = 0;
26255d9e75c4SJan Schmidt 
26265d9e75c4SJan Schmidt 	lowest_level = p->lowest_level;
26275d9e75c4SJan Schmidt 	WARN_ON(p->nodes[0] != NULL);
26285d9e75c4SJan Schmidt 
26295d9e75c4SJan Schmidt 	if (p->search_commit_root) {
26305d9e75c4SJan Schmidt 		BUG_ON(time_seq);
26315d9e75c4SJan Schmidt 		return btrfs_search_slot(NULL, root, key, p, 0, 0);
26325d9e75c4SJan Schmidt 	}
26335d9e75c4SJan Schmidt 
26345d9e75c4SJan Schmidt again:
26355d9e75c4SJan Schmidt 	b = get_old_root(root, time_seq);
26365d9e75c4SJan Schmidt 	level = btrfs_header_level(b);
26375d9e75c4SJan Schmidt 	p->locks[level] = BTRFS_READ_LOCK;
26385d9e75c4SJan Schmidt 
26395d9e75c4SJan Schmidt 	while (b) {
26405d9e75c4SJan Schmidt 		level = btrfs_header_level(b);
26415d9e75c4SJan Schmidt 		p->nodes[level] = b;
26425d9e75c4SJan Schmidt 		btrfs_clear_path_blocking(p, NULL, 0);
26435d9e75c4SJan Schmidt 
26445d9e75c4SJan Schmidt 		/*
26455d9e75c4SJan Schmidt 		 * we have a lock on b and as long as we aren't changing
26465d9e75c4SJan Schmidt 		 * the tree, there is no way to for the items in b to change.
26475d9e75c4SJan Schmidt 		 * It is safe to drop the lock on our parent before we
26485d9e75c4SJan Schmidt 		 * go through the expensive btree search on b.
26495d9e75c4SJan Schmidt 		 */
26505d9e75c4SJan Schmidt 		btrfs_unlock_up_safe(p, level + 1);
26515d9e75c4SJan Schmidt 
26525d9e75c4SJan Schmidt 		ret = bin_search(b, key, level, &slot);
26535d9e75c4SJan Schmidt 
26545d9e75c4SJan Schmidt 		if (level != 0) {
26555d9e75c4SJan Schmidt 			int dec = 0;
26565d9e75c4SJan Schmidt 			if (ret && slot > 0) {
26575d9e75c4SJan Schmidt 				dec = 1;
26585d9e75c4SJan Schmidt 				slot -= 1;
26595d9e75c4SJan Schmidt 			}
26605d9e75c4SJan Schmidt 			p->slots[level] = slot;
26615d9e75c4SJan Schmidt 			unlock_up(p, level, lowest_unlock, 0, NULL);
26625d9e75c4SJan Schmidt 
26635d9e75c4SJan Schmidt 			if (level == lowest_level) {
26645d9e75c4SJan Schmidt 				if (dec)
26655d9e75c4SJan Schmidt 					p->slots[level]++;
26665d9e75c4SJan Schmidt 				goto done;
26675d9e75c4SJan Schmidt 			}
26685d9e75c4SJan Schmidt 
26695d9e75c4SJan Schmidt 			err = read_block_for_search(NULL, root, p, &b, level,
26705d9e75c4SJan Schmidt 						    slot, key, time_seq);
26715d9e75c4SJan Schmidt 			if (err == -EAGAIN)
26725d9e75c4SJan Schmidt 				goto again;
26735d9e75c4SJan Schmidt 			if (err) {
26745d9e75c4SJan Schmidt 				ret = err;
26755d9e75c4SJan Schmidt 				goto done;
26765d9e75c4SJan Schmidt 			}
26775d9e75c4SJan Schmidt 
26785d9e75c4SJan Schmidt 			level = btrfs_header_level(b);
26795d9e75c4SJan Schmidt 			err = btrfs_try_tree_read_lock(b);
26805d9e75c4SJan Schmidt 			if (!err) {
26815d9e75c4SJan Schmidt 				btrfs_set_path_blocking(p);
26825d9e75c4SJan Schmidt 				btrfs_tree_read_lock(b);
26835d9e75c4SJan Schmidt 				btrfs_clear_path_blocking(p, b,
26845d9e75c4SJan Schmidt 							  BTRFS_READ_LOCK);
26855d9e75c4SJan Schmidt 			}
26865d9e75c4SJan Schmidt 			p->locks[level] = BTRFS_READ_LOCK;
26875d9e75c4SJan Schmidt 			p->nodes[level] = b;
26885d9e75c4SJan Schmidt 			b = tree_mod_log_rewind(root->fs_info, b, time_seq);
26895d9e75c4SJan Schmidt 			if (b != p->nodes[level]) {
26905d9e75c4SJan Schmidt 				btrfs_tree_unlock_rw(p->nodes[level],
26915d9e75c4SJan Schmidt 						     p->locks[level]);
26925d9e75c4SJan Schmidt 				p->locks[level] = 0;
26935d9e75c4SJan Schmidt 				p->nodes[level] = b;
26945d9e75c4SJan Schmidt 			}
26955d9e75c4SJan Schmidt 		} else {
26965d9e75c4SJan Schmidt 			p->slots[level] = slot;
26975d9e75c4SJan Schmidt 			unlock_up(p, level, lowest_unlock, 0, NULL);
26985d9e75c4SJan Schmidt 			goto done;
26995d9e75c4SJan Schmidt 		}
27005d9e75c4SJan Schmidt 	}
27015d9e75c4SJan Schmidt 	ret = 1;
27025d9e75c4SJan Schmidt done:
27035d9e75c4SJan Schmidt 	if (!p->leave_spinning)
27045d9e75c4SJan Schmidt 		btrfs_set_path_blocking(p);
27055d9e75c4SJan Schmidt 	if (ret < 0)
27065d9e75c4SJan Schmidt 		btrfs_release_path(p);
27075d9e75c4SJan Schmidt 
27085d9e75c4SJan Schmidt 	return ret;
27095d9e75c4SJan Schmidt }
27105d9e75c4SJan Schmidt 
27115d9e75c4SJan Schmidt /*
271274123bd7SChris Mason  * adjust the pointers going up the tree, starting at level
271374123bd7SChris Mason  * making sure the right key of each node is points to 'key'.
271474123bd7SChris Mason  * This is used after shifting pointers to the left, so it stops
271574123bd7SChris Mason  * fixing up pointers when a given leaf/node is not in slot 0 of the
271674123bd7SChris Mason  * higher levels
2717aa5d6bedSChris Mason  *
271874123bd7SChris Mason  */
2719143bede5SJeff Mahoney static void fixup_low_keys(struct btrfs_trans_handle *trans,
27205f39d397SChris Mason 			   struct btrfs_root *root, struct btrfs_path *path,
27215f39d397SChris Mason 			   struct btrfs_disk_key *key, int level)
2722be0e5c09SChris Mason {
2723be0e5c09SChris Mason 	int i;
27245f39d397SChris Mason 	struct extent_buffer *t;
27255f39d397SChris Mason 
2726234b63a0SChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2727be0e5c09SChris Mason 		int tslot = path->slots[i];
2728eb60ceacSChris Mason 		if (!path->nodes[i])
2729be0e5c09SChris Mason 			break;
27305f39d397SChris Mason 		t = path->nodes[i];
2731f230475eSJan Schmidt 		tree_mod_log_set_node_key(root->fs_info, t, key, tslot, 1);
27325f39d397SChris Mason 		btrfs_set_node_key(t, key, tslot);
2733d6025579SChris Mason 		btrfs_mark_buffer_dirty(path->nodes[i]);
2734be0e5c09SChris Mason 		if (tslot != 0)
2735be0e5c09SChris Mason 			break;
2736be0e5c09SChris Mason 	}
2737be0e5c09SChris Mason }
2738be0e5c09SChris Mason 
273974123bd7SChris Mason /*
274031840ae1SZheng Yan  * update item key.
274131840ae1SZheng Yan  *
274231840ae1SZheng Yan  * This function isn't completely safe. It's the caller's responsibility
274331840ae1SZheng Yan  * that the new key won't break the order
274431840ae1SZheng Yan  */
2745143bede5SJeff Mahoney void btrfs_set_item_key_safe(struct btrfs_trans_handle *trans,
274631840ae1SZheng Yan 			     struct btrfs_root *root, struct btrfs_path *path,
274731840ae1SZheng Yan 			     struct btrfs_key *new_key)
274831840ae1SZheng Yan {
274931840ae1SZheng Yan 	struct btrfs_disk_key disk_key;
275031840ae1SZheng Yan 	struct extent_buffer *eb;
275131840ae1SZheng Yan 	int slot;
275231840ae1SZheng Yan 
275331840ae1SZheng Yan 	eb = path->nodes[0];
275431840ae1SZheng Yan 	slot = path->slots[0];
275531840ae1SZheng Yan 	if (slot > 0) {
275631840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot - 1);
2757143bede5SJeff Mahoney 		BUG_ON(comp_keys(&disk_key, new_key) >= 0);
275831840ae1SZheng Yan 	}
275931840ae1SZheng Yan 	if (slot < btrfs_header_nritems(eb) - 1) {
276031840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot + 1);
2761143bede5SJeff Mahoney 		BUG_ON(comp_keys(&disk_key, new_key) <= 0);
276231840ae1SZheng Yan 	}
276331840ae1SZheng Yan 
276431840ae1SZheng Yan 	btrfs_cpu_key_to_disk(&disk_key, new_key);
276531840ae1SZheng Yan 	btrfs_set_item_key(eb, &disk_key, slot);
276631840ae1SZheng Yan 	btrfs_mark_buffer_dirty(eb);
276731840ae1SZheng Yan 	if (slot == 0)
276831840ae1SZheng Yan 		fixup_low_keys(trans, root, path, &disk_key, 1);
276931840ae1SZheng Yan }
277031840ae1SZheng Yan 
277131840ae1SZheng Yan /*
277274123bd7SChris Mason  * try to push data from one node into the next node left in the
277379f95c82SChris Mason  * tree.
2774aa5d6bedSChris Mason  *
2775aa5d6bedSChris Mason  * returns 0 if some ptrs were pushed left, < 0 if there was some horrible
2776aa5d6bedSChris Mason  * error, and > 0 if there was no room in the left hand block.
277774123bd7SChris Mason  */
277898ed5174SChris Mason static int push_node_left(struct btrfs_trans_handle *trans,
277998ed5174SChris Mason 			  struct btrfs_root *root, struct extent_buffer *dst,
2780971a1f66SChris Mason 			  struct extent_buffer *src, int empty)
2781be0e5c09SChris Mason {
2782be0e5c09SChris Mason 	int push_items = 0;
2783bb803951SChris Mason 	int src_nritems;
2784bb803951SChris Mason 	int dst_nritems;
2785aa5d6bedSChris Mason 	int ret = 0;
2786be0e5c09SChris Mason 
27875f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
27885f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
2789123abc88SChris Mason 	push_items = BTRFS_NODEPTRS_PER_BLOCK(root) - dst_nritems;
27907bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
27917bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
279254aa1f4dSChris Mason 
2793bce4eae9SChris Mason 	if (!empty && src_nritems <= 8)
2794971a1f66SChris Mason 		return 1;
2795971a1f66SChris Mason 
2796d397712bSChris Mason 	if (push_items <= 0)
2797be0e5c09SChris Mason 		return 1;
2798be0e5c09SChris Mason 
2799bce4eae9SChris Mason 	if (empty) {
2800971a1f66SChris Mason 		push_items = min(src_nritems, push_items);
2801bce4eae9SChris Mason 		if (push_items < src_nritems) {
2802bce4eae9SChris Mason 			/* leave at least 8 pointers in the node if
2803bce4eae9SChris Mason 			 * we aren't going to empty it
2804bce4eae9SChris Mason 			 */
2805bce4eae9SChris Mason 			if (src_nritems - push_items < 8) {
2806bce4eae9SChris Mason 				if (push_items <= 8)
2807bce4eae9SChris Mason 					return 1;
2808bce4eae9SChris Mason 				push_items -= 8;
2809bce4eae9SChris Mason 			}
2810bce4eae9SChris Mason 		}
2811bce4eae9SChris Mason 	} else
2812bce4eae9SChris Mason 		push_items = min(src_nritems - 8, push_items);
281379f95c82SChris Mason 
2814f230475eSJan Schmidt 	tree_mod_log_eb_copy(root->fs_info, dst, src, dst_nritems, 0,
2815f230475eSJan Schmidt 			     push_items);
28165f39d397SChris Mason 	copy_extent_buffer(dst, src,
28175f39d397SChris Mason 			   btrfs_node_key_ptr_offset(dst_nritems),
28185f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
2819123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
28205f39d397SChris Mason 
2821bb803951SChris Mason 	if (push_items < src_nritems) {
2822f230475eSJan Schmidt 		tree_mod_log_eb_move(root->fs_info, src, 0, push_items,
2823f230475eSJan Schmidt 				     src_nritems - push_items);
28245f39d397SChris Mason 		memmove_extent_buffer(src, btrfs_node_key_ptr_offset(0),
28255f39d397SChris Mason 				      btrfs_node_key_ptr_offset(push_items),
2826e2fa7227SChris Mason 				      (src_nritems - push_items) *
2827123abc88SChris Mason 				      sizeof(struct btrfs_key_ptr));
2828bb803951SChris Mason 	}
28295f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
28305f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
28315f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
28325f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
283331840ae1SZheng Yan 
2834bb803951SChris Mason 	return ret;
2835be0e5c09SChris Mason }
2836be0e5c09SChris Mason 
283797571fd0SChris Mason /*
283879f95c82SChris Mason  * try to push data from one node into the next node right in the
283979f95c82SChris Mason  * tree.
284079f95c82SChris Mason  *
284179f95c82SChris Mason  * returns 0 if some ptrs were pushed, < 0 if there was some horrible
284279f95c82SChris Mason  * error, and > 0 if there was no room in the right hand block.
284379f95c82SChris Mason  *
284479f95c82SChris Mason  * this will  only push up to 1/2 the contents of the left node over
284579f95c82SChris Mason  */
28465f39d397SChris Mason static int balance_node_right(struct btrfs_trans_handle *trans,
28475f39d397SChris Mason 			      struct btrfs_root *root,
28485f39d397SChris Mason 			      struct extent_buffer *dst,
28495f39d397SChris Mason 			      struct extent_buffer *src)
285079f95c82SChris Mason {
285179f95c82SChris Mason 	int push_items = 0;
285279f95c82SChris Mason 	int max_push;
285379f95c82SChris Mason 	int src_nritems;
285479f95c82SChris Mason 	int dst_nritems;
285579f95c82SChris Mason 	int ret = 0;
285679f95c82SChris Mason 
28577bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
28587bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
28597bb86316SChris Mason 
28605f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
28615f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
2862123abc88SChris Mason 	push_items = BTRFS_NODEPTRS_PER_BLOCK(root) - dst_nritems;
2863d397712bSChris Mason 	if (push_items <= 0)
286479f95c82SChris Mason 		return 1;
2865bce4eae9SChris Mason 
2866d397712bSChris Mason 	if (src_nritems < 4)
2867bce4eae9SChris Mason 		return 1;
286879f95c82SChris Mason 
286979f95c82SChris Mason 	max_push = src_nritems / 2 + 1;
287079f95c82SChris Mason 	/* don't try to empty the node */
2871d397712bSChris Mason 	if (max_push >= src_nritems)
287279f95c82SChris Mason 		return 1;
2873252c38f0SYan 
287479f95c82SChris Mason 	if (max_push < push_items)
287579f95c82SChris Mason 		push_items = max_push;
287679f95c82SChris Mason 
2877f230475eSJan Schmidt 	tree_mod_log_eb_move(root->fs_info, dst, push_items, 0, dst_nritems);
28785f39d397SChris Mason 	memmove_extent_buffer(dst, btrfs_node_key_ptr_offset(push_items),
28795f39d397SChris Mason 				      btrfs_node_key_ptr_offset(0),
28805f39d397SChris Mason 				      (dst_nritems) *
28815f39d397SChris Mason 				      sizeof(struct btrfs_key_ptr));
2882d6025579SChris Mason 
2883f230475eSJan Schmidt 	tree_mod_log_eb_copy(root->fs_info, dst, src, 0,
2884f230475eSJan Schmidt 			     src_nritems - push_items, push_items);
28855f39d397SChris Mason 	copy_extent_buffer(dst, src,
28865f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
28875f39d397SChris Mason 			   btrfs_node_key_ptr_offset(src_nritems - push_items),
2888123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
288979f95c82SChris Mason 
28905f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
28915f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
289279f95c82SChris Mason 
28935f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
28945f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
289531840ae1SZheng Yan 
289679f95c82SChris Mason 	return ret;
289779f95c82SChris Mason }
289879f95c82SChris Mason 
289979f95c82SChris Mason /*
290097571fd0SChris Mason  * helper function to insert a new root level in the tree.
290197571fd0SChris Mason  * A new node is allocated, and a single item is inserted to
290297571fd0SChris Mason  * point to the existing root
2903aa5d6bedSChris Mason  *
2904aa5d6bedSChris Mason  * returns zero on success or < 0 on failure.
290597571fd0SChris Mason  */
2906d397712bSChris Mason static noinline int insert_new_root(struct btrfs_trans_handle *trans,
29075f39d397SChris Mason 			   struct btrfs_root *root,
29085f39d397SChris Mason 			   struct btrfs_path *path, int level)
290974123bd7SChris Mason {
29107bb86316SChris Mason 	u64 lower_gen;
29115f39d397SChris Mason 	struct extent_buffer *lower;
29125f39d397SChris Mason 	struct extent_buffer *c;
2913925baeddSChris Mason 	struct extent_buffer *old;
29145f39d397SChris Mason 	struct btrfs_disk_key lower_key;
29155c680ed6SChris Mason 
29165c680ed6SChris Mason 	BUG_ON(path->nodes[level]);
29175c680ed6SChris Mason 	BUG_ON(path->nodes[level-1] != root->node);
29185c680ed6SChris Mason 
29197bb86316SChris Mason 	lower = path->nodes[level-1];
29207bb86316SChris Mason 	if (level == 1)
29217bb86316SChris Mason 		btrfs_item_key(lower, &lower_key, 0);
29227bb86316SChris Mason 	else
29237bb86316SChris Mason 		btrfs_node_key(lower, &lower_key, 0);
29247bb86316SChris Mason 
292531840ae1SZheng Yan 	c = btrfs_alloc_free_block(trans, root, root->nodesize, 0,
29265d4f98a2SYan Zheng 				   root->root_key.objectid, &lower_key,
29275581a51aSJan Schmidt 				   level, root->node->start, 0);
29285f39d397SChris Mason 	if (IS_ERR(c))
29295f39d397SChris Mason 		return PTR_ERR(c);
2930925baeddSChris Mason 
2931f0486c68SYan, Zheng 	root_add_used(root, root->nodesize);
2932f0486c68SYan, Zheng 
29335d4f98a2SYan Zheng 	memset_extent_buffer(c, 0, 0, sizeof(struct btrfs_header));
29345f39d397SChris Mason 	btrfs_set_header_nritems(c, 1);
29355f39d397SChris Mason 	btrfs_set_header_level(c, level);
2936db94535dSChris Mason 	btrfs_set_header_bytenr(c, c->start);
29375f39d397SChris Mason 	btrfs_set_header_generation(c, trans->transid);
29385d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(c, BTRFS_MIXED_BACKREF_REV);
29395f39d397SChris Mason 	btrfs_set_header_owner(c, root->root_key.objectid);
2940d5719762SChris Mason 
29415f39d397SChris Mason 	write_extent_buffer(c, root->fs_info->fsid,
29425f39d397SChris Mason 			    (unsigned long)btrfs_header_fsid(c),
29435f39d397SChris Mason 			    BTRFS_FSID_SIZE);
2944e17cade2SChris Mason 
2945e17cade2SChris Mason 	write_extent_buffer(c, root->fs_info->chunk_tree_uuid,
2946e17cade2SChris Mason 			    (unsigned long)btrfs_header_chunk_tree_uuid(c),
2947e17cade2SChris Mason 			    BTRFS_UUID_SIZE);
2948e17cade2SChris Mason 
29495f39d397SChris Mason 	btrfs_set_node_key(c, &lower_key, 0);
2950db94535dSChris Mason 	btrfs_set_node_blockptr(c, 0, lower->start);
29517bb86316SChris Mason 	lower_gen = btrfs_header_generation(lower);
295231840ae1SZheng Yan 	WARN_ON(lower_gen != trans->transid);
29537bb86316SChris Mason 
29547bb86316SChris Mason 	btrfs_set_node_ptr_generation(c, 0, lower_gen);
29555f39d397SChris Mason 
29565f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
2957d5719762SChris Mason 
2958925baeddSChris Mason 	old = root->node;
2959f230475eSJan Schmidt 	tree_mod_log_set_root_pointer(root, c);
2960240f62c8SChris Mason 	rcu_assign_pointer(root->node, c);
2961925baeddSChris Mason 
2962925baeddSChris Mason 	/* the super has an extra ref to root->node */
2963925baeddSChris Mason 	free_extent_buffer(old);
2964925baeddSChris Mason 
29650b86a832SChris Mason 	add_root_to_dirty_list(root);
29665f39d397SChris Mason 	extent_buffer_get(c);
29675f39d397SChris Mason 	path->nodes[level] = c;
2968bd681513SChris Mason 	path->locks[level] = BTRFS_WRITE_LOCK;
296974123bd7SChris Mason 	path->slots[level] = 0;
297074123bd7SChris Mason 	return 0;
297174123bd7SChris Mason }
29725c680ed6SChris Mason 
29735c680ed6SChris Mason /*
29745c680ed6SChris Mason  * worker function to insert a single pointer in a node.
29755c680ed6SChris Mason  * the node should have enough room for the pointer already
297697571fd0SChris Mason  *
29775c680ed6SChris Mason  * slot and level indicate where you want the key to go, and
29785c680ed6SChris Mason  * blocknr is the block the key points to.
29795c680ed6SChris Mason  */
2980143bede5SJeff Mahoney static void insert_ptr(struct btrfs_trans_handle *trans,
2981143bede5SJeff Mahoney 		       struct btrfs_root *root, struct btrfs_path *path,
2982143bede5SJeff Mahoney 		       struct btrfs_disk_key *key, u64 bytenr,
2983f3ea38daSJan Schmidt 		       int slot, int level, int tree_mod_log)
29845c680ed6SChris Mason {
29855f39d397SChris Mason 	struct extent_buffer *lower;
29865c680ed6SChris Mason 	int nritems;
2987f3ea38daSJan Schmidt 	int ret;
29885c680ed6SChris Mason 
29895c680ed6SChris Mason 	BUG_ON(!path->nodes[level]);
2990f0486c68SYan, Zheng 	btrfs_assert_tree_locked(path->nodes[level]);
29915f39d397SChris Mason 	lower = path->nodes[level];
29925f39d397SChris Mason 	nritems = btrfs_header_nritems(lower);
2993c293498bSStoyan Gaydarov 	BUG_ON(slot > nritems);
2994143bede5SJeff Mahoney 	BUG_ON(nritems == BTRFS_NODEPTRS_PER_BLOCK(root));
299574123bd7SChris Mason 	if (slot != nritems) {
2996f3ea38daSJan Schmidt 		if (tree_mod_log && level)
2997f3ea38daSJan Schmidt 			tree_mod_log_eb_move(root->fs_info, lower, slot + 1,
2998f3ea38daSJan Schmidt 					     slot, nritems - slot);
29995f39d397SChris Mason 		memmove_extent_buffer(lower,
30005f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot + 1),
30015f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot),
3002123abc88SChris Mason 			      (nritems - slot) * sizeof(struct btrfs_key_ptr));
300374123bd7SChris Mason 	}
3004f3ea38daSJan Schmidt 	if (tree_mod_log && level) {
3005f3ea38daSJan Schmidt 		ret = tree_mod_log_insert_key(root->fs_info, lower, slot,
3006f3ea38daSJan Schmidt 					      MOD_LOG_KEY_ADD);
3007f3ea38daSJan Schmidt 		BUG_ON(ret < 0);
3008f3ea38daSJan Schmidt 	}
30095f39d397SChris Mason 	btrfs_set_node_key(lower, key, slot);
3010db94535dSChris Mason 	btrfs_set_node_blockptr(lower, slot, bytenr);
301174493f7aSChris Mason 	WARN_ON(trans->transid == 0);
301274493f7aSChris Mason 	btrfs_set_node_ptr_generation(lower, slot, trans->transid);
30135f39d397SChris Mason 	btrfs_set_header_nritems(lower, nritems + 1);
30145f39d397SChris Mason 	btrfs_mark_buffer_dirty(lower);
301574123bd7SChris Mason }
301674123bd7SChris Mason 
301797571fd0SChris Mason /*
301897571fd0SChris Mason  * split the node at the specified level in path in two.
301997571fd0SChris Mason  * The path is corrected to point to the appropriate node after the split
302097571fd0SChris Mason  *
302197571fd0SChris Mason  * Before splitting this tries to make some room in the node by pushing
302297571fd0SChris Mason  * left and right, if either one works, it returns right away.
3023aa5d6bedSChris Mason  *
3024aa5d6bedSChris Mason  * returns 0 on success and < 0 on failure
302597571fd0SChris Mason  */
3026e02119d5SChris Mason static noinline int split_node(struct btrfs_trans_handle *trans,
3027e02119d5SChris Mason 			       struct btrfs_root *root,
3028e02119d5SChris Mason 			       struct btrfs_path *path, int level)
3029be0e5c09SChris Mason {
30305f39d397SChris Mason 	struct extent_buffer *c;
30315f39d397SChris Mason 	struct extent_buffer *split;
30325f39d397SChris Mason 	struct btrfs_disk_key disk_key;
3033be0e5c09SChris Mason 	int mid;
30345c680ed6SChris Mason 	int ret;
30357518a238SChris Mason 	u32 c_nritems;
3036be0e5c09SChris Mason 
30375f39d397SChris Mason 	c = path->nodes[level];
30387bb86316SChris Mason 	WARN_ON(btrfs_header_generation(c) != trans->transid);
30395f39d397SChris Mason 	if (c == root->node) {
30405c680ed6SChris Mason 		/* trying to split the root, lets make a new one */
3041e089f05cSChris Mason 		ret = insert_new_root(trans, root, path, level + 1);
30425c680ed6SChris Mason 		if (ret)
30435c680ed6SChris Mason 			return ret;
3044b3612421SChris Mason 	} else {
3045e66f709bSChris Mason 		ret = push_nodes_for_insert(trans, root, path, level);
30465f39d397SChris Mason 		c = path->nodes[level];
30475f39d397SChris Mason 		if (!ret && btrfs_header_nritems(c) <
3048c448acf0SChris Mason 		    BTRFS_NODEPTRS_PER_BLOCK(root) - 3)
3049e66f709bSChris Mason 			return 0;
305054aa1f4dSChris Mason 		if (ret < 0)
305154aa1f4dSChris Mason 			return ret;
30525c680ed6SChris Mason 	}
3053e66f709bSChris Mason 
30545f39d397SChris Mason 	c_nritems = btrfs_header_nritems(c);
30555d4f98a2SYan Zheng 	mid = (c_nritems + 1) / 2;
30565d4f98a2SYan Zheng 	btrfs_node_key(c, &disk_key, mid);
30577bb86316SChris Mason 
30585d4f98a2SYan Zheng 	split = btrfs_alloc_free_block(trans, root, root->nodesize, 0,
30597bb86316SChris Mason 					root->root_key.objectid,
30605581a51aSJan Schmidt 					&disk_key, level, c->start, 0);
30615f39d397SChris Mason 	if (IS_ERR(split))
30625f39d397SChris Mason 		return PTR_ERR(split);
306354aa1f4dSChris Mason 
3064f0486c68SYan, Zheng 	root_add_used(root, root->nodesize);
3065f0486c68SYan, Zheng 
30665d4f98a2SYan Zheng 	memset_extent_buffer(split, 0, 0, sizeof(struct btrfs_header));
30675f39d397SChris Mason 	btrfs_set_header_level(split, btrfs_header_level(c));
3068db94535dSChris Mason 	btrfs_set_header_bytenr(split, split->start);
30695f39d397SChris Mason 	btrfs_set_header_generation(split, trans->transid);
30705d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(split, BTRFS_MIXED_BACKREF_REV);
30715f39d397SChris Mason 	btrfs_set_header_owner(split, root->root_key.objectid);
30725f39d397SChris Mason 	write_extent_buffer(split, root->fs_info->fsid,
30735f39d397SChris Mason 			    (unsigned long)btrfs_header_fsid(split),
30745f39d397SChris Mason 			    BTRFS_FSID_SIZE);
3075e17cade2SChris Mason 	write_extent_buffer(split, root->fs_info->chunk_tree_uuid,
3076e17cade2SChris Mason 			    (unsigned long)btrfs_header_chunk_tree_uuid(split),
3077e17cade2SChris Mason 			    BTRFS_UUID_SIZE);
30785f39d397SChris Mason 
3079f230475eSJan Schmidt 	tree_mod_log_eb_copy(root->fs_info, split, c, 0, mid, c_nritems - mid);
30805f39d397SChris Mason 	copy_extent_buffer(split, c,
30815f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
30825f39d397SChris Mason 			   btrfs_node_key_ptr_offset(mid),
3083123abc88SChris Mason 			   (c_nritems - mid) * sizeof(struct btrfs_key_ptr));
30845f39d397SChris Mason 	btrfs_set_header_nritems(split, c_nritems - mid);
30855f39d397SChris Mason 	btrfs_set_header_nritems(c, mid);
3086aa5d6bedSChris Mason 	ret = 0;
3087aa5d6bedSChris Mason 
30885f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
30895f39d397SChris Mason 	btrfs_mark_buffer_dirty(split);
30905f39d397SChris Mason 
3091143bede5SJeff Mahoney 	insert_ptr(trans, root, path, &disk_key, split->start,
3092f3ea38daSJan Schmidt 		   path->slots[level + 1] + 1, level + 1, 1);
3093aa5d6bedSChris Mason 
30945de08d7dSChris Mason 	if (path->slots[level] >= mid) {
30955c680ed6SChris Mason 		path->slots[level] -= mid;
3096925baeddSChris Mason 		btrfs_tree_unlock(c);
30975f39d397SChris Mason 		free_extent_buffer(c);
30985f39d397SChris Mason 		path->nodes[level] = split;
30995c680ed6SChris Mason 		path->slots[level + 1] += 1;
3100eb60ceacSChris Mason 	} else {
3101925baeddSChris Mason 		btrfs_tree_unlock(split);
31025f39d397SChris Mason 		free_extent_buffer(split);
3103be0e5c09SChris Mason 	}
3104aa5d6bedSChris Mason 	return ret;
3105be0e5c09SChris Mason }
3106be0e5c09SChris Mason 
310774123bd7SChris Mason /*
310874123bd7SChris Mason  * how many bytes are required to store the items in a leaf.  start
310974123bd7SChris Mason  * and nr indicate which items in the leaf to check.  This totals up the
311074123bd7SChris Mason  * space used both by the item structs and the item data
311174123bd7SChris Mason  */
31125f39d397SChris Mason static int leaf_space_used(struct extent_buffer *l, int start, int nr)
3113be0e5c09SChris Mason {
3114be0e5c09SChris Mason 	int data_len;
31155f39d397SChris Mason 	int nritems = btrfs_header_nritems(l);
3116d4dbff95SChris Mason 	int end = min(nritems, start + nr) - 1;
3117be0e5c09SChris Mason 
3118be0e5c09SChris Mason 	if (!nr)
3119be0e5c09SChris Mason 		return 0;
31205f39d397SChris Mason 	data_len = btrfs_item_end_nr(l, start);
31215f39d397SChris Mason 	data_len = data_len - btrfs_item_offset_nr(l, end);
31220783fcfcSChris Mason 	data_len += sizeof(struct btrfs_item) * nr;
3123d4dbff95SChris Mason 	WARN_ON(data_len < 0);
3124be0e5c09SChris Mason 	return data_len;
3125be0e5c09SChris Mason }
3126be0e5c09SChris Mason 
312774123bd7SChris Mason /*
3128d4dbff95SChris Mason  * The space between the end of the leaf items and
3129d4dbff95SChris Mason  * the start of the leaf data.  IOW, how much room
3130d4dbff95SChris Mason  * the leaf has left for both items and data
3131d4dbff95SChris Mason  */
3132d397712bSChris Mason noinline int btrfs_leaf_free_space(struct btrfs_root *root,
3133e02119d5SChris Mason 				   struct extent_buffer *leaf)
3134d4dbff95SChris Mason {
31355f39d397SChris Mason 	int nritems = btrfs_header_nritems(leaf);
31365f39d397SChris Mason 	int ret;
31375f39d397SChris Mason 	ret = BTRFS_LEAF_DATA_SIZE(root) - leaf_space_used(leaf, 0, nritems);
31385f39d397SChris Mason 	if (ret < 0) {
3139d397712bSChris Mason 		printk(KERN_CRIT "leaf free space ret %d, leaf data size %lu, "
3140d397712bSChris Mason 		       "used %d nritems %d\n",
3141ae2f5411SJens Axboe 		       ret, (unsigned long) BTRFS_LEAF_DATA_SIZE(root),
31425f39d397SChris Mason 		       leaf_space_used(leaf, 0, nritems), nritems);
31435f39d397SChris Mason 	}
31445f39d397SChris Mason 	return ret;
3145d4dbff95SChris Mason }
3146d4dbff95SChris Mason 
314799d8f83cSChris Mason /*
314899d8f83cSChris Mason  * min slot controls the lowest index we're willing to push to the
314999d8f83cSChris Mason  * right.  We'll push up to and including min_slot, but no lower
315099d8f83cSChris Mason  */
315144871b1bSChris Mason static noinline int __push_leaf_right(struct btrfs_trans_handle *trans,
315244871b1bSChris Mason 				      struct btrfs_root *root,
315344871b1bSChris Mason 				      struct btrfs_path *path,
315444871b1bSChris Mason 				      int data_size, int empty,
315544871b1bSChris Mason 				      struct extent_buffer *right,
315699d8f83cSChris Mason 				      int free_space, u32 left_nritems,
315799d8f83cSChris Mason 				      u32 min_slot)
315800ec4c51SChris Mason {
31595f39d397SChris Mason 	struct extent_buffer *left = path->nodes[0];
316044871b1bSChris Mason 	struct extent_buffer *upper = path->nodes[1];
3161cfed81a0SChris Mason 	struct btrfs_map_token token;
31625f39d397SChris Mason 	struct btrfs_disk_key disk_key;
316300ec4c51SChris Mason 	int slot;
316434a38218SChris Mason 	u32 i;
316500ec4c51SChris Mason 	int push_space = 0;
316600ec4c51SChris Mason 	int push_items = 0;
31670783fcfcSChris Mason 	struct btrfs_item *item;
316834a38218SChris Mason 	u32 nr;
31697518a238SChris Mason 	u32 right_nritems;
31705f39d397SChris Mason 	u32 data_end;
3171db94535dSChris Mason 	u32 this_item_size;
317200ec4c51SChris Mason 
3173cfed81a0SChris Mason 	btrfs_init_map_token(&token);
3174cfed81a0SChris Mason 
317534a38218SChris Mason 	if (empty)
317634a38218SChris Mason 		nr = 0;
317734a38218SChris Mason 	else
317899d8f83cSChris Mason 		nr = max_t(u32, 1, min_slot);
317934a38218SChris Mason 
318031840ae1SZheng Yan 	if (path->slots[0] >= left_nritems)
318187b29b20SYan Zheng 		push_space += data_size;
318231840ae1SZheng Yan 
318344871b1bSChris Mason 	slot = path->slots[1];
318434a38218SChris Mason 	i = left_nritems - 1;
318534a38218SChris Mason 	while (i >= nr) {
31865f39d397SChris Mason 		item = btrfs_item_nr(left, i);
3187db94535dSChris Mason 
318831840ae1SZheng Yan 		if (!empty && push_items > 0) {
318931840ae1SZheng Yan 			if (path->slots[0] > i)
319031840ae1SZheng Yan 				break;
319131840ae1SZheng Yan 			if (path->slots[0] == i) {
319231840ae1SZheng Yan 				int space = btrfs_leaf_free_space(root, left);
319331840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
319431840ae1SZheng Yan 					break;
319531840ae1SZheng Yan 			}
319631840ae1SZheng Yan 		}
319731840ae1SZheng Yan 
319800ec4c51SChris Mason 		if (path->slots[0] == i)
319987b29b20SYan Zheng 			push_space += data_size;
3200db94535dSChris Mason 
3201db94535dSChris Mason 		this_item_size = btrfs_item_size(left, item);
3202db94535dSChris Mason 		if (this_item_size + sizeof(*item) + push_space > free_space)
320300ec4c51SChris Mason 			break;
320431840ae1SZheng Yan 
320500ec4c51SChris Mason 		push_items++;
3206db94535dSChris Mason 		push_space += this_item_size + sizeof(*item);
320734a38218SChris Mason 		if (i == 0)
320834a38218SChris Mason 			break;
320934a38218SChris Mason 		i--;
3210db94535dSChris Mason 	}
32115f39d397SChris Mason 
3212925baeddSChris Mason 	if (push_items == 0)
3213925baeddSChris Mason 		goto out_unlock;
32145f39d397SChris Mason 
321534a38218SChris Mason 	if (!empty && push_items == left_nritems)
3216a429e513SChris Mason 		WARN_ON(1);
32175f39d397SChris Mason 
321800ec4c51SChris Mason 	/* push left to right */
32195f39d397SChris Mason 	right_nritems = btrfs_header_nritems(right);
322034a38218SChris Mason 
32215f39d397SChris Mason 	push_space = btrfs_item_end_nr(left, left_nritems - push_items);
3222123abc88SChris Mason 	push_space -= leaf_data_end(root, left);
32235f39d397SChris Mason 
322400ec4c51SChris Mason 	/* make room in the right data area */
32255f39d397SChris Mason 	data_end = leaf_data_end(root, right);
32265f39d397SChris Mason 	memmove_extent_buffer(right,
32275f39d397SChris Mason 			      btrfs_leaf_data(right) + data_end - push_space,
32285f39d397SChris Mason 			      btrfs_leaf_data(right) + data_end,
32295f39d397SChris Mason 			      BTRFS_LEAF_DATA_SIZE(root) - data_end);
32305f39d397SChris Mason 
323100ec4c51SChris Mason 	/* copy from the left data area */
32325f39d397SChris Mason 	copy_extent_buffer(right, left, btrfs_leaf_data(right) +
3233d6025579SChris Mason 		     BTRFS_LEAF_DATA_SIZE(root) - push_space,
3234d6025579SChris Mason 		     btrfs_leaf_data(left) + leaf_data_end(root, left),
3235d6025579SChris Mason 		     push_space);
32365f39d397SChris Mason 
32375f39d397SChris Mason 	memmove_extent_buffer(right, btrfs_item_nr_offset(push_items),
32385f39d397SChris Mason 			      btrfs_item_nr_offset(0),
32390783fcfcSChris Mason 			      right_nritems * sizeof(struct btrfs_item));
32405f39d397SChris Mason 
324100ec4c51SChris Mason 	/* copy the items from left to right */
32425f39d397SChris Mason 	copy_extent_buffer(right, left, btrfs_item_nr_offset(0),
32435f39d397SChris Mason 		   btrfs_item_nr_offset(left_nritems - push_items),
32440783fcfcSChris Mason 		   push_items * sizeof(struct btrfs_item));
324500ec4c51SChris Mason 
324600ec4c51SChris Mason 	/* update the item pointers */
32477518a238SChris Mason 	right_nritems += push_items;
32485f39d397SChris Mason 	btrfs_set_header_nritems(right, right_nritems);
3249123abc88SChris Mason 	push_space = BTRFS_LEAF_DATA_SIZE(root);
32507518a238SChris Mason 	for (i = 0; i < right_nritems; i++) {
32515f39d397SChris Mason 		item = btrfs_item_nr(right, i);
3252cfed81a0SChris Mason 		push_space -= btrfs_token_item_size(right, item, &token);
3253cfed81a0SChris Mason 		btrfs_set_token_item_offset(right, item, push_space, &token);
3254db94535dSChris Mason 	}
3255db94535dSChris Mason 
32567518a238SChris Mason 	left_nritems -= push_items;
32575f39d397SChris Mason 	btrfs_set_header_nritems(left, left_nritems);
325800ec4c51SChris Mason 
325934a38218SChris Mason 	if (left_nritems)
32605f39d397SChris Mason 		btrfs_mark_buffer_dirty(left);
3261f0486c68SYan, Zheng 	else
3262f0486c68SYan, Zheng 		clean_tree_block(trans, root, left);
3263f0486c68SYan, Zheng 
32645f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
3265a429e513SChris Mason 
32665f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
32675f39d397SChris Mason 	btrfs_set_node_key(upper, &disk_key, slot + 1);
3268d6025579SChris Mason 	btrfs_mark_buffer_dirty(upper);
326902217ed2SChris Mason 
327000ec4c51SChris Mason 	/* then fixup the leaf pointer in the path */
32717518a238SChris Mason 	if (path->slots[0] >= left_nritems) {
32727518a238SChris Mason 		path->slots[0] -= left_nritems;
3273925baeddSChris Mason 		if (btrfs_header_nritems(path->nodes[0]) == 0)
3274925baeddSChris Mason 			clean_tree_block(trans, root, path->nodes[0]);
3275925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
32765f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
32775f39d397SChris Mason 		path->nodes[0] = right;
327800ec4c51SChris Mason 		path->slots[1] += 1;
327900ec4c51SChris Mason 	} else {
3280925baeddSChris Mason 		btrfs_tree_unlock(right);
32815f39d397SChris Mason 		free_extent_buffer(right);
328200ec4c51SChris Mason 	}
328300ec4c51SChris Mason 	return 0;
3284925baeddSChris Mason 
3285925baeddSChris Mason out_unlock:
3286925baeddSChris Mason 	btrfs_tree_unlock(right);
3287925baeddSChris Mason 	free_extent_buffer(right);
3288925baeddSChris Mason 	return 1;
328900ec4c51SChris Mason }
3290925baeddSChris Mason 
329100ec4c51SChris Mason /*
329244871b1bSChris Mason  * push some data in the path leaf to the right, trying to free up at
329374123bd7SChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
329444871b1bSChris Mason  *
329544871b1bSChris Mason  * returns 1 if the push failed because the other node didn't have enough
329644871b1bSChris Mason  * room, 0 if everything worked out and < 0 if there were major errors.
329799d8f83cSChris Mason  *
329899d8f83cSChris Mason  * this will push starting from min_slot to the end of the leaf.  It won't
329999d8f83cSChris Mason  * push any slot lower than min_slot
330074123bd7SChris Mason  */
330144871b1bSChris Mason static int push_leaf_right(struct btrfs_trans_handle *trans, struct btrfs_root
330299d8f83cSChris Mason 			   *root, struct btrfs_path *path,
330399d8f83cSChris Mason 			   int min_data_size, int data_size,
330499d8f83cSChris Mason 			   int empty, u32 min_slot)
3305be0e5c09SChris Mason {
330644871b1bSChris Mason 	struct extent_buffer *left = path->nodes[0];
330744871b1bSChris Mason 	struct extent_buffer *right;
330844871b1bSChris Mason 	struct extent_buffer *upper;
330944871b1bSChris Mason 	int slot;
331044871b1bSChris Mason 	int free_space;
331144871b1bSChris Mason 	u32 left_nritems;
331244871b1bSChris Mason 	int ret;
331344871b1bSChris Mason 
331444871b1bSChris Mason 	if (!path->nodes[1])
331544871b1bSChris Mason 		return 1;
331644871b1bSChris Mason 
331744871b1bSChris Mason 	slot = path->slots[1];
331844871b1bSChris Mason 	upper = path->nodes[1];
331944871b1bSChris Mason 	if (slot >= btrfs_header_nritems(upper) - 1)
332044871b1bSChris Mason 		return 1;
332144871b1bSChris Mason 
332244871b1bSChris Mason 	btrfs_assert_tree_locked(path->nodes[1]);
332344871b1bSChris Mason 
332444871b1bSChris Mason 	right = read_node_slot(root, upper, slot + 1);
332591ca338dSTsutomu Itoh 	if (right == NULL)
332691ca338dSTsutomu Itoh 		return 1;
332791ca338dSTsutomu Itoh 
332844871b1bSChris Mason 	btrfs_tree_lock(right);
332944871b1bSChris Mason 	btrfs_set_lock_blocking(right);
333044871b1bSChris Mason 
333144871b1bSChris Mason 	free_space = btrfs_leaf_free_space(root, right);
333244871b1bSChris Mason 	if (free_space < data_size)
333344871b1bSChris Mason 		goto out_unlock;
333444871b1bSChris Mason 
333544871b1bSChris Mason 	/* cow and double check */
333644871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, right, upper,
333744871b1bSChris Mason 			      slot + 1, &right);
333844871b1bSChris Mason 	if (ret)
333944871b1bSChris Mason 		goto out_unlock;
334044871b1bSChris Mason 
334144871b1bSChris Mason 	free_space = btrfs_leaf_free_space(root, right);
334244871b1bSChris Mason 	if (free_space < data_size)
334344871b1bSChris Mason 		goto out_unlock;
334444871b1bSChris Mason 
334544871b1bSChris Mason 	left_nritems = btrfs_header_nritems(left);
334644871b1bSChris Mason 	if (left_nritems == 0)
334744871b1bSChris Mason 		goto out_unlock;
334844871b1bSChris Mason 
334999d8f83cSChris Mason 	return __push_leaf_right(trans, root, path, min_data_size, empty,
335099d8f83cSChris Mason 				right, free_space, left_nritems, min_slot);
335144871b1bSChris Mason out_unlock:
335244871b1bSChris Mason 	btrfs_tree_unlock(right);
335344871b1bSChris Mason 	free_extent_buffer(right);
335444871b1bSChris Mason 	return 1;
335544871b1bSChris Mason }
335644871b1bSChris Mason 
335744871b1bSChris Mason /*
335844871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
335944871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
336099d8f83cSChris Mason  *
336199d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
336299d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us do all the
336399d8f83cSChris Mason  * items
336444871b1bSChris Mason  */
336544871b1bSChris Mason static noinline int __push_leaf_left(struct btrfs_trans_handle *trans,
336644871b1bSChris Mason 				     struct btrfs_root *root,
336744871b1bSChris Mason 				     struct btrfs_path *path, int data_size,
336844871b1bSChris Mason 				     int empty, struct extent_buffer *left,
336999d8f83cSChris Mason 				     int free_space, u32 right_nritems,
337099d8f83cSChris Mason 				     u32 max_slot)
337144871b1bSChris Mason {
33725f39d397SChris Mason 	struct btrfs_disk_key disk_key;
33735f39d397SChris Mason 	struct extent_buffer *right = path->nodes[0];
3374be0e5c09SChris Mason 	int i;
3375be0e5c09SChris Mason 	int push_space = 0;
3376be0e5c09SChris Mason 	int push_items = 0;
33770783fcfcSChris Mason 	struct btrfs_item *item;
33787518a238SChris Mason 	u32 old_left_nritems;
337934a38218SChris Mason 	u32 nr;
3380aa5d6bedSChris Mason 	int ret = 0;
3381db94535dSChris Mason 	u32 this_item_size;
3382db94535dSChris Mason 	u32 old_left_item_size;
3383cfed81a0SChris Mason 	struct btrfs_map_token token;
3384cfed81a0SChris Mason 
3385cfed81a0SChris Mason 	btrfs_init_map_token(&token);
3386be0e5c09SChris Mason 
338734a38218SChris Mason 	if (empty)
338899d8f83cSChris Mason 		nr = min(right_nritems, max_slot);
338934a38218SChris Mason 	else
339099d8f83cSChris Mason 		nr = min(right_nritems - 1, max_slot);
339134a38218SChris Mason 
339234a38218SChris Mason 	for (i = 0; i < nr; i++) {
33935f39d397SChris Mason 		item = btrfs_item_nr(right, i);
3394db94535dSChris Mason 
339531840ae1SZheng Yan 		if (!empty && push_items > 0) {
339631840ae1SZheng Yan 			if (path->slots[0] < i)
339731840ae1SZheng Yan 				break;
339831840ae1SZheng Yan 			if (path->slots[0] == i) {
339931840ae1SZheng Yan 				int space = btrfs_leaf_free_space(root, right);
340031840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
340131840ae1SZheng Yan 					break;
340231840ae1SZheng Yan 			}
340331840ae1SZheng Yan 		}
340431840ae1SZheng Yan 
3405be0e5c09SChris Mason 		if (path->slots[0] == i)
340687b29b20SYan Zheng 			push_space += data_size;
3407db94535dSChris Mason 
3408db94535dSChris Mason 		this_item_size = btrfs_item_size(right, item);
3409db94535dSChris Mason 		if (this_item_size + sizeof(*item) + push_space > free_space)
3410be0e5c09SChris Mason 			break;
3411db94535dSChris Mason 
3412be0e5c09SChris Mason 		push_items++;
3413db94535dSChris Mason 		push_space += this_item_size + sizeof(*item);
3414be0e5c09SChris Mason 	}
3415db94535dSChris Mason 
3416be0e5c09SChris Mason 	if (push_items == 0) {
3417925baeddSChris Mason 		ret = 1;
3418925baeddSChris Mason 		goto out;
3419be0e5c09SChris Mason 	}
342034a38218SChris Mason 	if (!empty && push_items == btrfs_header_nritems(right))
3421a429e513SChris Mason 		WARN_ON(1);
34225f39d397SChris Mason 
3423be0e5c09SChris Mason 	/* push data from right to left */
34245f39d397SChris Mason 	copy_extent_buffer(left, right,
34255f39d397SChris Mason 			   btrfs_item_nr_offset(btrfs_header_nritems(left)),
34265f39d397SChris Mason 			   btrfs_item_nr_offset(0),
34275f39d397SChris Mason 			   push_items * sizeof(struct btrfs_item));
34285f39d397SChris Mason 
3429123abc88SChris Mason 	push_space = BTRFS_LEAF_DATA_SIZE(root) -
34305f39d397SChris Mason 		     btrfs_item_offset_nr(right, push_items - 1);
34315f39d397SChris Mason 
34325f39d397SChris Mason 	copy_extent_buffer(left, right, btrfs_leaf_data(left) +
3433d6025579SChris Mason 		     leaf_data_end(root, left) - push_space,
3434123abc88SChris Mason 		     btrfs_leaf_data(right) +
34355f39d397SChris Mason 		     btrfs_item_offset_nr(right, push_items - 1),
3436be0e5c09SChris Mason 		     push_space);
34375f39d397SChris Mason 	old_left_nritems = btrfs_header_nritems(left);
343887b29b20SYan Zheng 	BUG_ON(old_left_nritems <= 0);
3439eb60ceacSChris Mason 
3440db94535dSChris Mason 	old_left_item_size = btrfs_item_offset_nr(left, old_left_nritems - 1);
3441be0e5c09SChris Mason 	for (i = old_left_nritems; i < old_left_nritems + push_items; i++) {
34425f39d397SChris Mason 		u32 ioff;
3443db94535dSChris Mason 
34445f39d397SChris Mason 		item = btrfs_item_nr(left, i);
3445db94535dSChris Mason 
3446cfed81a0SChris Mason 		ioff = btrfs_token_item_offset(left, item, &token);
3447cfed81a0SChris Mason 		btrfs_set_token_item_offset(left, item,
3448cfed81a0SChris Mason 		      ioff - (BTRFS_LEAF_DATA_SIZE(root) - old_left_item_size),
3449cfed81a0SChris Mason 		      &token);
3450be0e5c09SChris Mason 	}
34515f39d397SChris Mason 	btrfs_set_header_nritems(left, old_left_nritems + push_items);
3452be0e5c09SChris Mason 
3453be0e5c09SChris Mason 	/* fixup right node */
345434a38218SChris Mason 	if (push_items > right_nritems) {
3455d397712bSChris Mason 		printk(KERN_CRIT "push items %d nr %u\n", push_items,
3456d397712bSChris Mason 		       right_nritems);
345734a38218SChris Mason 		WARN_ON(1);
345834a38218SChris Mason 	}
345934a38218SChris Mason 
346034a38218SChris Mason 	if (push_items < right_nritems) {
34615f39d397SChris Mason 		push_space = btrfs_item_offset_nr(right, push_items - 1) -
3462123abc88SChris Mason 						  leaf_data_end(root, right);
34635f39d397SChris Mason 		memmove_extent_buffer(right, btrfs_leaf_data(right) +
3464d6025579SChris Mason 				      BTRFS_LEAF_DATA_SIZE(root) - push_space,
3465d6025579SChris Mason 				      btrfs_leaf_data(right) +
3466123abc88SChris Mason 				      leaf_data_end(root, right), push_space);
34675f39d397SChris Mason 
34685f39d397SChris Mason 		memmove_extent_buffer(right, btrfs_item_nr_offset(0),
34695f39d397SChris Mason 			      btrfs_item_nr_offset(push_items),
34705f39d397SChris Mason 			     (btrfs_header_nritems(right) - push_items) *
34710783fcfcSChris Mason 			     sizeof(struct btrfs_item));
347234a38218SChris Mason 	}
3473eef1c494SYan 	right_nritems -= push_items;
3474eef1c494SYan 	btrfs_set_header_nritems(right, right_nritems);
3475123abc88SChris Mason 	push_space = BTRFS_LEAF_DATA_SIZE(root);
34765f39d397SChris Mason 	for (i = 0; i < right_nritems; i++) {
34775f39d397SChris Mason 		item = btrfs_item_nr(right, i);
3478db94535dSChris Mason 
3479cfed81a0SChris Mason 		push_space = push_space - btrfs_token_item_size(right,
3480cfed81a0SChris Mason 								item, &token);
3481cfed81a0SChris Mason 		btrfs_set_token_item_offset(right, item, push_space, &token);
3482db94535dSChris Mason 	}
3483eb60ceacSChris Mason 
34845f39d397SChris Mason 	btrfs_mark_buffer_dirty(left);
348534a38218SChris Mason 	if (right_nritems)
34865f39d397SChris Mason 		btrfs_mark_buffer_dirty(right);
3487f0486c68SYan, Zheng 	else
3488f0486c68SYan, Zheng 		clean_tree_block(trans, root, right);
3489098f59c2SChris Mason 
34905f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
3491143bede5SJeff Mahoney 	fixup_low_keys(trans, root, path, &disk_key, 1);
3492be0e5c09SChris Mason 
3493be0e5c09SChris Mason 	/* then fixup the leaf pointer in the path */
3494be0e5c09SChris Mason 	if (path->slots[0] < push_items) {
3495be0e5c09SChris Mason 		path->slots[0] += old_left_nritems;
3496925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
34975f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
34985f39d397SChris Mason 		path->nodes[0] = left;
3499be0e5c09SChris Mason 		path->slots[1] -= 1;
3500be0e5c09SChris Mason 	} else {
3501925baeddSChris Mason 		btrfs_tree_unlock(left);
35025f39d397SChris Mason 		free_extent_buffer(left);
3503be0e5c09SChris Mason 		path->slots[0] -= push_items;
3504be0e5c09SChris Mason 	}
3505eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
3506aa5d6bedSChris Mason 	return ret;
3507925baeddSChris Mason out:
3508925baeddSChris Mason 	btrfs_tree_unlock(left);
3509925baeddSChris Mason 	free_extent_buffer(left);
3510925baeddSChris Mason 	return ret;
3511be0e5c09SChris Mason }
3512be0e5c09SChris Mason 
351374123bd7SChris Mason /*
351444871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
351544871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
351699d8f83cSChris Mason  *
351799d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
351899d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us push all the
351999d8f83cSChris Mason  * items
352044871b1bSChris Mason  */
352144871b1bSChris Mason static int push_leaf_left(struct btrfs_trans_handle *trans, struct btrfs_root
352299d8f83cSChris Mason 			  *root, struct btrfs_path *path, int min_data_size,
352399d8f83cSChris Mason 			  int data_size, int empty, u32 max_slot)
352444871b1bSChris Mason {
352544871b1bSChris Mason 	struct extent_buffer *right = path->nodes[0];
352644871b1bSChris Mason 	struct extent_buffer *left;
352744871b1bSChris Mason 	int slot;
352844871b1bSChris Mason 	int free_space;
352944871b1bSChris Mason 	u32 right_nritems;
353044871b1bSChris Mason 	int ret = 0;
353144871b1bSChris Mason 
353244871b1bSChris Mason 	slot = path->slots[1];
353344871b1bSChris Mason 	if (slot == 0)
353444871b1bSChris Mason 		return 1;
353544871b1bSChris Mason 	if (!path->nodes[1])
353644871b1bSChris Mason 		return 1;
353744871b1bSChris Mason 
353844871b1bSChris Mason 	right_nritems = btrfs_header_nritems(right);
353944871b1bSChris Mason 	if (right_nritems == 0)
354044871b1bSChris Mason 		return 1;
354144871b1bSChris Mason 
354244871b1bSChris Mason 	btrfs_assert_tree_locked(path->nodes[1]);
354344871b1bSChris Mason 
354444871b1bSChris Mason 	left = read_node_slot(root, path->nodes[1], slot - 1);
354591ca338dSTsutomu Itoh 	if (left == NULL)
354691ca338dSTsutomu Itoh 		return 1;
354791ca338dSTsutomu Itoh 
354844871b1bSChris Mason 	btrfs_tree_lock(left);
354944871b1bSChris Mason 	btrfs_set_lock_blocking(left);
355044871b1bSChris Mason 
355144871b1bSChris Mason 	free_space = btrfs_leaf_free_space(root, left);
355244871b1bSChris Mason 	if (free_space < data_size) {
355344871b1bSChris Mason 		ret = 1;
355444871b1bSChris Mason 		goto out;
355544871b1bSChris Mason 	}
355644871b1bSChris Mason 
355744871b1bSChris Mason 	/* cow and double check */
355844871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, left,
355944871b1bSChris Mason 			      path->nodes[1], slot - 1, &left);
356044871b1bSChris Mason 	if (ret) {
356144871b1bSChris Mason 		/* we hit -ENOSPC, but it isn't fatal here */
356279787eaaSJeff Mahoney 		if (ret == -ENOSPC)
356344871b1bSChris Mason 			ret = 1;
356444871b1bSChris Mason 		goto out;
356544871b1bSChris Mason 	}
356644871b1bSChris Mason 
356744871b1bSChris Mason 	free_space = btrfs_leaf_free_space(root, left);
356844871b1bSChris Mason 	if (free_space < data_size) {
356944871b1bSChris Mason 		ret = 1;
357044871b1bSChris Mason 		goto out;
357144871b1bSChris Mason 	}
357244871b1bSChris Mason 
357399d8f83cSChris Mason 	return __push_leaf_left(trans, root, path, min_data_size,
357499d8f83cSChris Mason 			       empty, left, free_space, right_nritems,
357599d8f83cSChris Mason 			       max_slot);
357644871b1bSChris Mason out:
357744871b1bSChris Mason 	btrfs_tree_unlock(left);
357844871b1bSChris Mason 	free_extent_buffer(left);
357944871b1bSChris Mason 	return ret;
358044871b1bSChris Mason }
358144871b1bSChris Mason 
358244871b1bSChris Mason /*
358374123bd7SChris Mason  * split the path's leaf in two, making sure there is at least data_size
358474123bd7SChris Mason  * available for the resulting leaf level of the path.
358574123bd7SChris Mason  */
3586143bede5SJeff Mahoney static noinline void copy_for_split(struct btrfs_trans_handle *trans,
3587e02119d5SChris Mason 				    struct btrfs_root *root,
358844871b1bSChris Mason 				    struct btrfs_path *path,
358944871b1bSChris Mason 				    struct extent_buffer *l,
359044871b1bSChris Mason 				    struct extent_buffer *right,
359144871b1bSChris Mason 				    int slot, int mid, int nritems)
3592be0e5c09SChris Mason {
3593be0e5c09SChris Mason 	int data_copy_size;
3594be0e5c09SChris Mason 	int rt_data_off;
3595be0e5c09SChris Mason 	int i;
3596d4dbff95SChris Mason 	struct btrfs_disk_key disk_key;
3597cfed81a0SChris Mason 	struct btrfs_map_token token;
3598cfed81a0SChris Mason 
3599cfed81a0SChris Mason 	btrfs_init_map_token(&token);
3600be0e5c09SChris Mason 
36015f39d397SChris Mason 	nritems = nritems - mid;
36025f39d397SChris Mason 	btrfs_set_header_nritems(right, nritems);
36035f39d397SChris Mason 	data_copy_size = btrfs_item_end_nr(l, mid) - leaf_data_end(root, l);
36045f39d397SChris Mason 
36055f39d397SChris Mason 	copy_extent_buffer(right, l, btrfs_item_nr_offset(0),
36065f39d397SChris Mason 			   btrfs_item_nr_offset(mid),
36075f39d397SChris Mason 			   nritems * sizeof(struct btrfs_item));
36085f39d397SChris Mason 
36095f39d397SChris Mason 	copy_extent_buffer(right, l,
3610d6025579SChris Mason 		     btrfs_leaf_data(right) + BTRFS_LEAF_DATA_SIZE(root) -
3611123abc88SChris Mason 		     data_copy_size, btrfs_leaf_data(l) +
3612123abc88SChris Mason 		     leaf_data_end(root, l), data_copy_size);
361374123bd7SChris Mason 
36145f39d397SChris Mason 	rt_data_off = BTRFS_LEAF_DATA_SIZE(root) -
36155f39d397SChris Mason 		      btrfs_item_end_nr(l, mid);
36165f39d397SChris Mason 
36175f39d397SChris Mason 	for (i = 0; i < nritems; i++) {
36185f39d397SChris Mason 		struct btrfs_item *item = btrfs_item_nr(right, i);
3619db94535dSChris Mason 		u32 ioff;
3620db94535dSChris Mason 
3621cfed81a0SChris Mason 		ioff = btrfs_token_item_offset(right, item, &token);
3622cfed81a0SChris Mason 		btrfs_set_token_item_offset(right, item,
3623cfed81a0SChris Mason 					    ioff + rt_data_off, &token);
36240783fcfcSChris Mason 	}
362574123bd7SChris Mason 
36265f39d397SChris Mason 	btrfs_set_header_nritems(l, mid);
36275f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
3628143bede5SJeff Mahoney 	insert_ptr(trans, root, path, &disk_key, right->start,
3629f3ea38daSJan Schmidt 		   path->slots[1] + 1, 1, 0);
36305f39d397SChris Mason 
36315f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
36325f39d397SChris Mason 	btrfs_mark_buffer_dirty(l);
3633eb60ceacSChris Mason 	BUG_ON(path->slots[0] != slot);
36345f39d397SChris Mason 
3635be0e5c09SChris Mason 	if (mid <= slot) {
3636925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
36375f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
36385f39d397SChris Mason 		path->nodes[0] = right;
3639be0e5c09SChris Mason 		path->slots[0] -= mid;
3640be0e5c09SChris Mason 		path->slots[1] += 1;
3641925baeddSChris Mason 	} else {
3642925baeddSChris Mason 		btrfs_tree_unlock(right);
36435f39d397SChris Mason 		free_extent_buffer(right);
3644925baeddSChris Mason 	}
36455f39d397SChris Mason 
3646eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
364744871b1bSChris Mason }
364844871b1bSChris Mason 
364944871b1bSChris Mason /*
365099d8f83cSChris Mason  * double splits happen when we need to insert a big item in the middle
365199d8f83cSChris Mason  * of a leaf.  A double split can leave us with 3 mostly empty leaves:
365299d8f83cSChris Mason  * leaf: [ slots 0 - N] [ our target ] [ N + 1 - total in leaf ]
365399d8f83cSChris Mason  *          A                 B                 C
365499d8f83cSChris Mason  *
365599d8f83cSChris Mason  * We avoid this by trying to push the items on either side of our target
365699d8f83cSChris Mason  * into the adjacent leaves.  If all goes well we can avoid the double split
365799d8f83cSChris Mason  * completely.
365899d8f83cSChris Mason  */
365999d8f83cSChris Mason static noinline int push_for_double_split(struct btrfs_trans_handle *trans,
366099d8f83cSChris Mason 					  struct btrfs_root *root,
366199d8f83cSChris Mason 					  struct btrfs_path *path,
366299d8f83cSChris Mason 					  int data_size)
366399d8f83cSChris Mason {
366499d8f83cSChris Mason 	int ret;
366599d8f83cSChris Mason 	int progress = 0;
366699d8f83cSChris Mason 	int slot;
366799d8f83cSChris Mason 	u32 nritems;
366899d8f83cSChris Mason 
366999d8f83cSChris Mason 	slot = path->slots[0];
367099d8f83cSChris Mason 
367199d8f83cSChris Mason 	/*
367299d8f83cSChris Mason 	 * try to push all the items after our slot into the
367399d8f83cSChris Mason 	 * right leaf
367499d8f83cSChris Mason 	 */
367599d8f83cSChris Mason 	ret = push_leaf_right(trans, root, path, 1, data_size, 0, slot);
367699d8f83cSChris Mason 	if (ret < 0)
367799d8f83cSChris Mason 		return ret;
367899d8f83cSChris Mason 
367999d8f83cSChris Mason 	if (ret == 0)
368099d8f83cSChris Mason 		progress++;
368199d8f83cSChris Mason 
368299d8f83cSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
368399d8f83cSChris Mason 	/*
368499d8f83cSChris Mason 	 * our goal is to get our slot at the start or end of a leaf.  If
368599d8f83cSChris Mason 	 * we've done so we're done
368699d8f83cSChris Mason 	 */
368799d8f83cSChris Mason 	if (path->slots[0] == 0 || path->slots[0] == nritems)
368899d8f83cSChris Mason 		return 0;
368999d8f83cSChris Mason 
369099d8f83cSChris Mason 	if (btrfs_leaf_free_space(root, path->nodes[0]) >= data_size)
369199d8f83cSChris Mason 		return 0;
369299d8f83cSChris Mason 
369399d8f83cSChris Mason 	/* try to push all the items before our slot into the next leaf */
369499d8f83cSChris Mason 	slot = path->slots[0];
369599d8f83cSChris Mason 	ret = push_leaf_left(trans, root, path, 1, data_size, 0, slot);
369699d8f83cSChris Mason 	if (ret < 0)
369799d8f83cSChris Mason 		return ret;
369899d8f83cSChris Mason 
369999d8f83cSChris Mason 	if (ret == 0)
370099d8f83cSChris Mason 		progress++;
370199d8f83cSChris Mason 
370299d8f83cSChris Mason 	if (progress)
370399d8f83cSChris Mason 		return 0;
370499d8f83cSChris Mason 	return 1;
370599d8f83cSChris Mason }
370699d8f83cSChris Mason 
370799d8f83cSChris Mason /*
370844871b1bSChris Mason  * split the path's leaf in two, making sure there is at least data_size
370944871b1bSChris Mason  * available for the resulting leaf level of the path.
371044871b1bSChris Mason  *
371144871b1bSChris Mason  * returns 0 if all went well and < 0 on failure.
371244871b1bSChris Mason  */
371344871b1bSChris Mason static noinline int split_leaf(struct btrfs_trans_handle *trans,
371444871b1bSChris Mason 			       struct btrfs_root *root,
371544871b1bSChris Mason 			       struct btrfs_key *ins_key,
371644871b1bSChris Mason 			       struct btrfs_path *path, int data_size,
371744871b1bSChris Mason 			       int extend)
371844871b1bSChris Mason {
37195d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
372044871b1bSChris Mason 	struct extent_buffer *l;
372144871b1bSChris Mason 	u32 nritems;
372244871b1bSChris Mason 	int mid;
372344871b1bSChris Mason 	int slot;
372444871b1bSChris Mason 	struct extent_buffer *right;
372544871b1bSChris Mason 	int ret = 0;
372644871b1bSChris Mason 	int wret;
37275d4f98a2SYan Zheng 	int split;
372844871b1bSChris Mason 	int num_doubles = 0;
372999d8f83cSChris Mason 	int tried_avoid_double = 0;
373044871b1bSChris Mason 
3731a5719521SYan, Zheng 	l = path->nodes[0];
3732a5719521SYan, Zheng 	slot = path->slots[0];
3733a5719521SYan, Zheng 	if (extend && data_size + btrfs_item_size_nr(l, slot) +
3734a5719521SYan, Zheng 	    sizeof(struct btrfs_item) > BTRFS_LEAF_DATA_SIZE(root))
3735a5719521SYan, Zheng 		return -EOVERFLOW;
3736a5719521SYan, Zheng 
373744871b1bSChris Mason 	/* first try to make some room by pushing left and right */
373899d8f83cSChris Mason 	if (data_size) {
373999d8f83cSChris Mason 		wret = push_leaf_right(trans, root, path, data_size,
374099d8f83cSChris Mason 				       data_size, 0, 0);
374144871b1bSChris Mason 		if (wret < 0)
374244871b1bSChris Mason 			return wret;
374344871b1bSChris Mason 		if (wret) {
374499d8f83cSChris Mason 			wret = push_leaf_left(trans, root, path, data_size,
374599d8f83cSChris Mason 					      data_size, 0, (u32)-1);
374644871b1bSChris Mason 			if (wret < 0)
374744871b1bSChris Mason 				return wret;
374844871b1bSChris Mason 		}
374944871b1bSChris Mason 		l = path->nodes[0];
375044871b1bSChris Mason 
375144871b1bSChris Mason 		/* did the pushes work? */
375244871b1bSChris Mason 		if (btrfs_leaf_free_space(root, l) >= data_size)
375344871b1bSChris Mason 			return 0;
375444871b1bSChris Mason 	}
375544871b1bSChris Mason 
375644871b1bSChris Mason 	if (!path->nodes[1]) {
375744871b1bSChris Mason 		ret = insert_new_root(trans, root, path, 1);
375844871b1bSChris Mason 		if (ret)
375944871b1bSChris Mason 			return ret;
376044871b1bSChris Mason 	}
376144871b1bSChris Mason again:
37625d4f98a2SYan Zheng 	split = 1;
376344871b1bSChris Mason 	l = path->nodes[0];
376444871b1bSChris Mason 	slot = path->slots[0];
376544871b1bSChris Mason 	nritems = btrfs_header_nritems(l);
376644871b1bSChris Mason 	mid = (nritems + 1) / 2;
376744871b1bSChris Mason 
37685d4f98a2SYan Zheng 	if (mid <= slot) {
37695d4f98a2SYan Zheng 		if (nritems == 1 ||
37705d4f98a2SYan Zheng 		    leaf_space_used(l, mid, nritems - mid) + data_size >
37715d4f98a2SYan Zheng 			BTRFS_LEAF_DATA_SIZE(root)) {
37725d4f98a2SYan Zheng 			if (slot >= nritems) {
37735d4f98a2SYan Zheng 				split = 0;
37745d4f98a2SYan Zheng 			} else {
37755d4f98a2SYan Zheng 				mid = slot;
37765d4f98a2SYan Zheng 				if (mid != nritems &&
37775d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
37785d4f98a2SYan Zheng 				    data_size > BTRFS_LEAF_DATA_SIZE(root)) {
377999d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
378099d8f83cSChris Mason 						goto push_for_double;
37815d4f98a2SYan Zheng 					split = 2;
37825d4f98a2SYan Zheng 				}
37835d4f98a2SYan Zheng 			}
37845d4f98a2SYan Zheng 		}
37855d4f98a2SYan Zheng 	} else {
37865d4f98a2SYan Zheng 		if (leaf_space_used(l, 0, mid) + data_size >
37875d4f98a2SYan Zheng 			BTRFS_LEAF_DATA_SIZE(root)) {
37885d4f98a2SYan Zheng 			if (!extend && data_size && slot == 0) {
37895d4f98a2SYan Zheng 				split = 0;
37905d4f98a2SYan Zheng 			} else if ((extend || !data_size) && slot == 0) {
37915d4f98a2SYan Zheng 				mid = 1;
37925d4f98a2SYan Zheng 			} else {
37935d4f98a2SYan Zheng 				mid = slot;
37945d4f98a2SYan Zheng 				if (mid != nritems &&
37955d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
37965d4f98a2SYan Zheng 				    data_size > BTRFS_LEAF_DATA_SIZE(root)) {
379799d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
379899d8f83cSChris Mason 						goto push_for_double;
37995d4f98a2SYan Zheng 					split = 2 ;
38005d4f98a2SYan Zheng 				}
38015d4f98a2SYan Zheng 			}
38025d4f98a2SYan Zheng 		}
38035d4f98a2SYan Zheng 	}
38045d4f98a2SYan Zheng 
38055d4f98a2SYan Zheng 	if (split == 0)
38065d4f98a2SYan Zheng 		btrfs_cpu_key_to_disk(&disk_key, ins_key);
38075d4f98a2SYan Zheng 	else
38085d4f98a2SYan Zheng 		btrfs_item_key(l, &disk_key, mid);
38095d4f98a2SYan Zheng 
38105d4f98a2SYan Zheng 	right = btrfs_alloc_free_block(trans, root, root->leafsize, 0,
381144871b1bSChris Mason 					root->root_key.objectid,
38125581a51aSJan Schmidt 					&disk_key, 0, l->start, 0);
3813f0486c68SYan, Zheng 	if (IS_ERR(right))
381444871b1bSChris Mason 		return PTR_ERR(right);
3815f0486c68SYan, Zheng 
3816f0486c68SYan, Zheng 	root_add_used(root, root->leafsize);
381744871b1bSChris Mason 
381844871b1bSChris Mason 	memset_extent_buffer(right, 0, 0, sizeof(struct btrfs_header));
381944871b1bSChris Mason 	btrfs_set_header_bytenr(right, right->start);
382044871b1bSChris Mason 	btrfs_set_header_generation(right, trans->transid);
38215d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(right, BTRFS_MIXED_BACKREF_REV);
382244871b1bSChris Mason 	btrfs_set_header_owner(right, root->root_key.objectid);
382344871b1bSChris Mason 	btrfs_set_header_level(right, 0);
382444871b1bSChris Mason 	write_extent_buffer(right, root->fs_info->fsid,
382544871b1bSChris Mason 			    (unsigned long)btrfs_header_fsid(right),
382644871b1bSChris Mason 			    BTRFS_FSID_SIZE);
382744871b1bSChris Mason 
382844871b1bSChris Mason 	write_extent_buffer(right, root->fs_info->chunk_tree_uuid,
382944871b1bSChris Mason 			    (unsigned long)btrfs_header_chunk_tree_uuid(right),
383044871b1bSChris Mason 			    BTRFS_UUID_SIZE);
383144871b1bSChris Mason 
38325d4f98a2SYan Zheng 	if (split == 0) {
383344871b1bSChris Mason 		if (mid <= slot) {
383444871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
3835143bede5SJeff Mahoney 			insert_ptr(trans, root, path, &disk_key, right->start,
3836f3ea38daSJan Schmidt 				   path->slots[1] + 1, 1, 0);
383744871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
383844871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
383944871b1bSChris Mason 			path->nodes[0] = right;
384044871b1bSChris Mason 			path->slots[0] = 0;
384144871b1bSChris Mason 			path->slots[1] += 1;
384244871b1bSChris Mason 		} else {
384344871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
3844143bede5SJeff Mahoney 			insert_ptr(trans, root, path, &disk_key, right->start,
3845f3ea38daSJan Schmidt 					  path->slots[1], 1, 0);
384644871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
384744871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
384844871b1bSChris Mason 			path->nodes[0] = right;
384944871b1bSChris Mason 			path->slots[0] = 0;
3850143bede5SJeff Mahoney 			if (path->slots[1] == 0)
3851143bede5SJeff Mahoney 				fixup_low_keys(trans, root, path,
3852143bede5SJeff Mahoney 					       &disk_key, 1);
38535d4f98a2SYan Zheng 		}
385444871b1bSChris Mason 		btrfs_mark_buffer_dirty(right);
385544871b1bSChris Mason 		return ret;
385644871b1bSChris Mason 	}
385744871b1bSChris Mason 
3858143bede5SJeff Mahoney 	copy_for_split(trans, root, path, l, right, slot, mid, nritems);
385944871b1bSChris Mason 
38605d4f98a2SYan Zheng 	if (split == 2) {
3861cc0c5538SChris Mason 		BUG_ON(num_doubles != 0);
3862cc0c5538SChris Mason 		num_doubles++;
3863cc0c5538SChris Mason 		goto again;
38643326d1b0SChris Mason 	}
386544871b1bSChris Mason 
3866143bede5SJeff Mahoney 	return 0;
386799d8f83cSChris Mason 
386899d8f83cSChris Mason push_for_double:
386999d8f83cSChris Mason 	push_for_double_split(trans, root, path, data_size);
387099d8f83cSChris Mason 	tried_avoid_double = 1;
387199d8f83cSChris Mason 	if (btrfs_leaf_free_space(root, path->nodes[0]) >= data_size)
387299d8f83cSChris Mason 		return 0;
387399d8f83cSChris Mason 	goto again;
3874be0e5c09SChris Mason }
3875be0e5c09SChris Mason 
3876ad48fd75SYan, Zheng static noinline int setup_leaf_for_split(struct btrfs_trans_handle *trans,
3877ad48fd75SYan, Zheng 					 struct btrfs_root *root,
3878ad48fd75SYan, Zheng 					 struct btrfs_path *path, int ins_len)
3879ad48fd75SYan, Zheng {
3880ad48fd75SYan, Zheng 	struct btrfs_key key;
3881ad48fd75SYan, Zheng 	struct extent_buffer *leaf;
3882ad48fd75SYan, Zheng 	struct btrfs_file_extent_item *fi;
3883ad48fd75SYan, Zheng 	u64 extent_len = 0;
3884ad48fd75SYan, Zheng 	u32 item_size;
3885ad48fd75SYan, Zheng 	int ret;
3886ad48fd75SYan, Zheng 
3887ad48fd75SYan, Zheng 	leaf = path->nodes[0];
3888ad48fd75SYan, Zheng 	btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3889ad48fd75SYan, Zheng 
3890ad48fd75SYan, Zheng 	BUG_ON(key.type != BTRFS_EXTENT_DATA_KEY &&
3891ad48fd75SYan, Zheng 	       key.type != BTRFS_EXTENT_CSUM_KEY);
3892ad48fd75SYan, Zheng 
3893ad48fd75SYan, Zheng 	if (btrfs_leaf_free_space(root, leaf) >= ins_len)
3894ad48fd75SYan, Zheng 		return 0;
3895ad48fd75SYan, Zheng 
3896ad48fd75SYan, Zheng 	item_size = btrfs_item_size_nr(leaf, path->slots[0]);
3897ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
3898ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
3899ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
3900ad48fd75SYan, Zheng 		extent_len = btrfs_file_extent_num_bytes(leaf, fi);
3901ad48fd75SYan, Zheng 	}
3902b3b4aa74SDavid Sterba 	btrfs_release_path(path);
3903ad48fd75SYan, Zheng 
3904ad48fd75SYan, Zheng 	path->keep_locks = 1;
3905ad48fd75SYan, Zheng 	path->search_for_split = 1;
3906ad48fd75SYan, Zheng 	ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
3907ad48fd75SYan, Zheng 	path->search_for_split = 0;
3908ad48fd75SYan, Zheng 	if (ret < 0)
3909ad48fd75SYan, Zheng 		goto err;
3910ad48fd75SYan, Zheng 
3911ad48fd75SYan, Zheng 	ret = -EAGAIN;
3912ad48fd75SYan, Zheng 	leaf = path->nodes[0];
3913ad48fd75SYan, Zheng 	/* if our item isn't there or got smaller, return now */
3914ad48fd75SYan, Zheng 	if (ret > 0 || item_size != btrfs_item_size_nr(leaf, path->slots[0]))
3915ad48fd75SYan, Zheng 		goto err;
3916ad48fd75SYan, Zheng 
3917109f6aefSChris Mason 	/* the leaf has  changed, it now has room.  return now */
3918109f6aefSChris Mason 	if (btrfs_leaf_free_space(root, path->nodes[0]) >= ins_len)
3919109f6aefSChris Mason 		goto err;
3920109f6aefSChris Mason 
3921ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
3922ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
3923ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
3924ad48fd75SYan, Zheng 		if (extent_len != btrfs_file_extent_num_bytes(leaf, fi))
3925ad48fd75SYan, Zheng 			goto err;
3926ad48fd75SYan, Zheng 	}
3927ad48fd75SYan, Zheng 
3928ad48fd75SYan, Zheng 	btrfs_set_path_blocking(path);
3929ad48fd75SYan, Zheng 	ret = split_leaf(trans, root, &key, path, ins_len, 1);
3930f0486c68SYan, Zheng 	if (ret)
3931f0486c68SYan, Zheng 		goto err;
3932ad48fd75SYan, Zheng 
3933ad48fd75SYan, Zheng 	path->keep_locks = 0;
3934ad48fd75SYan, Zheng 	btrfs_unlock_up_safe(path, 1);
3935ad48fd75SYan, Zheng 	return 0;
3936ad48fd75SYan, Zheng err:
3937ad48fd75SYan, Zheng 	path->keep_locks = 0;
3938ad48fd75SYan, Zheng 	return ret;
3939ad48fd75SYan, Zheng }
3940ad48fd75SYan, Zheng 
3941ad48fd75SYan, Zheng static noinline int split_item(struct btrfs_trans_handle *trans,
3942459931ecSChris Mason 			       struct btrfs_root *root,
3943459931ecSChris Mason 			       struct btrfs_path *path,
3944459931ecSChris Mason 			       struct btrfs_key *new_key,
3945459931ecSChris Mason 			       unsigned long split_offset)
3946459931ecSChris Mason {
3947459931ecSChris Mason 	struct extent_buffer *leaf;
3948459931ecSChris Mason 	struct btrfs_item *item;
3949459931ecSChris Mason 	struct btrfs_item *new_item;
3950459931ecSChris Mason 	int slot;
3951ad48fd75SYan, Zheng 	char *buf;
3952459931ecSChris Mason 	u32 nritems;
3953ad48fd75SYan, Zheng 	u32 item_size;
3954459931ecSChris Mason 	u32 orig_offset;
3955459931ecSChris Mason 	struct btrfs_disk_key disk_key;
3956459931ecSChris Mason 
3957459931ecSChris Mason 	leaf = path->nodes[0];
3958b9473439SChris Mason 	BUG_ON(btrfs_leaf_free_space(root, leaf) < sizeof(struct btrfs_item));
3959b9473439SChris Mason 
3960b4ce94deSChris Mason 	btrfs_set_path_blocking(path);
3961b4ce94deSChris Mason 
3962459931ecSChris Mason 	item = btrfs_item_nr(leaf, path->slots[0]);
3963459931ecSChris Mason 	orig_offset = btrfs_item_offset(leaf, item);
3964459931ecSChris Mason 	item_size = btrfs_item_size(leaf, item);
3965459931ecSChris Mason 
3966459931ecSChris Mason 	buf = kmalloc(item_size, GFP_NOFS);
3967ad48fd75SYan, Zheng 	if (!buf)
3968ad48fd75SYan, Zheng 		return -ENOMEM;
3969ad48fd75SYan, Zheng 
3970459931ecSChris Mason 	read_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf,
3971459931ecSChris Mason 			    path->slots[0]), item_size);
3972ad48fd75SYan, Zheng 
3973459931ecSChris Mason 	slot = path->slots[0] + 1;
3974459931ecSChris Mason 	nritems = btrfs_header_nritems(leaf);
3975459931ecSChris Mason 	if (slot != nritems) {
3976459931ecSChris Mason 		/* shift the items */
3977459931ecSChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + 1),
3978459931ecSChris Mason 				btrfs_item_nr_offset(slot),
3979459931ecSChris Mason 				(nritems - slot) * sizeof(struct btrfs_item));
3980459931ecSChris Mason 	}
3981459931ecSChris Mason 
3982459931ecSChris Mason 	btrfs_cpu_key_to_disk(&disk_key, new_key);
3983459931ecSChris Mason 	btrfs_set_item_key(leaf, &disk_key, slot);
3984459931ecSChris Mason 
3985459931ecSChris Mason 	new_item = btrfs_item_nr(leaf, slot);
3986459931ecSChris Mason 
3987459931ecSChris Mason 	btrfs_set_item_offset(leaf, new_item, orig_offset);
3988459931ecSChris Mason 	btrfs_set_item_size(leaf, new_item, item_size - split_offset);
3989459931ecSChris Mason 
3990459931ecSChris Mason 	btrfs_set_item_offset(leaf, item,
3991459931ecSChris Mason 			      orig_offset + item_size - split_offset);
3992459931ecSChris Mason 	btrfs_set_item_size(leaf, item, split_offset);
3993459931ecSChris Mason 
3994459931ecSChris Mason 	btrfs_set_header_nritems(leaf, nritems + 1);
3995459931ecSChris Mason 
3996459931ecSChris Mason 	/* write the data for the start of the original item */
3997459931ecSChris Mason 	write_extent_buffer(leaf, buf,
3998459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, path->slots[0]),
3999459931ecSChris Mason 			    split_offset);
4000459931ecSChris Mason 
4001459931ecSChris Mason 	/* write the data for the new item */
4002459931ecSChris Mason 	write_extent_buffer(leaf, buf + split_offset,
4003459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, slot),
4004459931ecSChris Mason 			    item_size - split_offset);
4005459931ecSChris Mason 	btrfs_mark_buffer_dirty(leaf);
4006459931ecSChris Mason 
4007ad48fd75SYan, Zheng 	BUG_ON(btrfs_leaf_free_space(root, leaf) < 0);
4008459931ecSChris Mason 	kfree(buf);
4009ad48fd75SYan, Zheng 	return 0;
4010ad48fd75SYan, Zheng }
4011ad48fd75SYan, Zheng 
4012ad48fd75SYan, Zheng /*
4013ad48fd75SYan, Zheng  * This function splits a single item into two items,
4014ad48fd75SYan, Zheng  * giving 'new_key' to the new item and splitting the
4015ad48fd75SYan, Zheng  * old one at split_offset (from the start of the item).
4016ad48fd75SYan, Zheng  *
4017ad48fd75SYan, Zheng  * The path may be released by this operation.  After
4018ad48fd75SYan, Zheng  * the split, the path is pointing to the old item.  The
4019ad48fd75SYan, Zheng  * new item is going to be in the same node as the old one.
4020ad48fd75SYan, Zheng  *
4021ad48fd75SYan, Zheng  * Note, the item being split must be smaller enough to live alone on
4022ad48fd75SYan, Zheng  * a tree block with room for one extra struct btrfs_item
4023ad48fd75SYan, Zheng  *
4024ad48fd75SYan, Zheng  * This allows us to split the item in place, keeping a lock on the
4025ad48fd75SYan, Zheng  * leaf the entire time.
4026ad48fd75SYan, Zheng  */
4027ad48fd75SYan, Zheng int btrfs_split_item(struct btrfs_trans_handle *trans,
4028ad48fd75SYan, Zheng 		     struct btrfs_root *root,
4029ad48fd75SYan, Zheng 		     struct btrfs_path *path,
4030ad48fd75SYan, Zheng 		     struct btrfs_key *new_key,
4031ad48fd75SYan, Zheng 		     unsigned long split_offset)
4032ad48fd75SYan, Zheng {
4033ad48fd75SYan, Zheng 	int ret;
4034ad48fd75SYan, Zheng 	ret = setup_leaf_for_split(trans, root, path,
4035ad48fd75SYan, Zheng 				   sizeof(struct btrfs_item));
4036ad48fd75SYan, Zheng 	if (ret)
4037459931ecSChris Mason 		return ret;
4038ad48fd75SYan, Zheng 
4039ad48fd75SYan, Zheng 	ret = split_item(trans, root, path, new_key, split_offset);
4040ad48fd75SYan, Zheng 	return ret;
4041ad48fd75SYan, Zheng }
4042ad48fd75SYan, Zheng 
4043ad48fd75SYan, Zheng /*
4044ad48fd75SYan, Zheng  * This function duplicate a item, giving 'new_key' to the new item.
4045ad48fd75SYan, Zheng  * It guarantees both items live in the same tree leaf and the new item
4046ad48fd75SYan, Zheng  * is contiguous with the original item.
4047ad48fd75SYan, Zheng  *
4048ad48fd75SYan, Zheng  * This allows us to split file extent in place, keeping a lock on the
4049ad48fd75SYan, Zheng  * leaf the entire time.
4050ad48fd75SYan, Zheng  */
4051ad48fd75SYan, Zheng int btrfs_duplicate_item(struct btrfs_trans_handle *trans,
4052ad48fd75SYan, Zheng 			 struct btrfs_root *root,
4053ad48fd75SYan, Zheng 			 struct btrfs_path *path,
4054ad48fd75SYan, Zheng 			 struct btrfs_key *new_key)
4055ad48fd75SYan, Zheng {
4056ad48fd75SYan, Zheng 	struct extent_buffer *leaf;
4057ad48fd75SYan, Zheng 	int ret;
4058ad48fd75SYan, Zheng 	u32 item_size;
4059ad48fd75SYan, Zheng 
4060ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4061ad48fd75SYan, Zheng 	item_size = btrfs_item_size_nr(leaf, path->slots[0]);
4062ad48fd75SYan, Zheng 	ret = setup_leaf_for_split(trans, root, path,
4063ad48fd75SYan, Zheng 				   item_size + sizeof(struct btrfs_item));
4064ad48fd75SYan, Zheng 	if (ret)
4065ad48fd75SYan, Zheng 		return ret;
4066ad48fd75SYan, Zheng 
4067ad48fd75SYan, Zheng 	path->slots[0]++;
4068143bede5SJeff Mahoney 	setup_items_for_insert(trans, root, path, new_key, &item_size,
4069ad48fd75SYan, Zheng 			       item_size, item_size +
4070ad48fd75SYan, Zheng 			       sizeof(struct btrfs_item), 1);
4071ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4072ad48fd75SYan, Zheng 	memcpy_extent_buffer(leaf,
4073ad48fd75SYan, Zheng 			     btrfs_item_ptr_offset(leaf, path->slots[0]),
4074ad48fd75SYan, Zheng 			     btrfs_item_ptr_offset(leaf, path->slots[0] - 1),
4075ad48fd75SYan, Zheng 			     item_size);
4076ad48fd75SYan, Zheng 	return 0;
4077459931ecSChris Mason }
4078459931ecSChris Mason 
4079459931ecSChris Mason /*
4080d352ac68SChris Mason  * make the item pointed to by the path smaller.  new_size indicates
4081d352ac68SChris Mason  * how small to make it, and from_end tells us if we just chop bytes
4082d352ac68SChris Mason  * off the end of the item or if we shift the item to chop bytes off
4083d352ac68SChris Mason  * the front.
4084d352ac68SChris Mason  */
4085143bede5SJeff Mahoney void btrfs_truncate_item(struct btrfs_trans_handle *trans,
4086b18c6685SChris Mason 			 struct btrfs_root *root,
4087b18c6685SChris Mason 			 struct btrfs_path *path,
4088179e29e4SChris Mason 			 u32 new_size, int from_end)
4089b18c6685SChris Mason {
4090b18c6685SChris Mason 	int slot;
40915f39d397SChris Mason 	struct extent_buffer *leaf;
40925f39d397SChris Mason 	struct btrfs_item *item;
4093b18c6685SChris Mason 	u32 nritems;
4094b18c6685SChris Mason 	unsigned int data_end;
4095b18c6685SChris Mason 	unsigned int old_data_start;
4096b18c6685SChris Mason 	unsigned int old_size;
4097b18c6685SChris Mason 	unsigned int size_diff;
4098b18c6685SChris Mason 	int i;
4099cfed81a0SChris Mason 	struct btrfs_map_token token;
4100cfed81a0SChris Mason 
4101cfed81a0SChris Mason 	btrfs_init_map_token(&token);
4102b18c6685SChris Mason 
41035f39d397SChris Mason 	leaf = path->nodes[0];
4104179e29e4SChris Mason 	slot = path->slots[0];
4105179e29e4SChris Mason 
4106179e29e4SChris Mason 	old_size = btrfs_item_size_nr(leaf, slot);
4107179e29e4SChris Mason 	if (old_size == new_size)
4108143bede5SJeff Mahoney 		return;
4109b18c6685SChris Mason 
41105f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
4111b18c6685SChris Mason 	data_end = leaf_data_end(root, leaf);
4112b18c6685SChris Mason 
41135f39d397SChris Mason 	old_data_start = btrfs_item_offset_nr(leaf, slot);
4114179e29e4SChris Mason 
4115b18c6685SChris Mason 	size_diff = old_size - new_size;
4116b18c6685SChris Mason 
4117b18c6685SChris Mason 	BUG_ON(slot < 0);
4118b18c6685SChris Mason 	BUG_ON(slot >= nritems);
4119b18c6685SChris Mason 
4120b18c6685SChris Mason 	/*
4121b18c6685SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4122b18c6685SChris Mason 	 */
4123b18c6685SChris Mason 	/* first correct the data pointers */
4124b18c6685SChris Mason 	for (i = slot; i < nritems; i++) {
41255f39d397SChris Mason 		u32 ioff;
41265f39d397SChris Mason 		item = btrfs_item_nr(leaf, i);
4127db94535dSChris Mason 
4128cfed81a0SChris Mason 		ioff = btrfs_token_item_offset(leaf, item, &token);
4129cfed81a0SChris Mason 		btrfs_set_token_item_offset(leaf, item,
4130cfed81a0SChris Mason 					    ioff + size_diff, &token);
4131b18c6685SChris Mason 	}
4132db94535dSChris Mason 
4133b18c6685SChris Mason 	/* shift the data */
4134179e29e4SChris Mason 	if (from_end) {
41355f39d397SChris Mason 		memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
4136b18c6685SChris Mason 			      data_end + size_diff, btrfs_leaf_data(leaf) +
4137b18c6685SChris Mason 			      data_end, old_data_start + new_size - data_end);
4138179e29e4SChris Mason 	} else {
4139179e29e4SChris Mason 		struct btrfs_disk_key disk_key;
4140179e29e4SChris Mason 		u64 offset;
4141179e29e4SChris Mason 
4142179e29e4SChris Mason 		btrfs_item_key(leaf, &disk_key, slot);
4143179e29e4SChris Mason 
4144179e29e4SChris Mason 		if (btrfs_disk_key_type(&disk_key) == BTRFS_EXTENT_DATA_KEY) {
4145179e29e4SChris Mason 			unsigned long ptr;
4146179e29e4SChris Mason 			struct btrfs_file_extent_item *fi;
4147179e29e4SChris Mason 
4148179e29e4SChris Mason 			fi = btrfs_item_ptr(leaf, slot,
4149179e29e4SChris Mason 					    struct btrfs_file_extent_item);
4150179e29e4SChris Mason 			fi = (struct btrfs_file_extent_item *)(
4151179e29e4SChris Mason 			     (unsigned long)fi - size_diff);
4152179e29e4SChris Mason 
4153179e29e4SChris Mason 			if (btrfs_file_extent_type(leaf, fi) ==
4154179e29e4SChris Mason 			    BTRFS_FILE_EXTENT_INLINE) {
4155179e29e4SChris Mason 				ptr = btrfs_item_ptr_offset(leaf, slot);
4156179e29e4SChris Mason 				memmove_extent_buffer(leaf, ptr,
4157179e29e4SChris Mason 				      (unsigned long)fi,
4158179e29e4SChris Mason 				      offsetof(struct btrfs_file_extent_item,
4159179e29e4SChris Mason 						 disk_bytenr));
4160179e29e4SChris Mason 			}
4161179e29e4SChris Mason 		}
4162179e29e4SChris Mason 
4163179e29e4SChris Mason 		memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
4164179e29e4SChris Mason 			      data_end + size_diff, btrfs_leaf_data(leaf) +
4165179e29e4SChris Mason 			      data_end, old_data_start - data_end);
4166179e29e4SChris Mason 
4167179e29e4SChris Mason 		offset = btrfs_disk_key_offset(&disk_key);
4168179e29e4SChris Mason 		btrfs_set_disk_key_offset(&disk_key, offset + size_diff);
4169179e29e4SChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot);
4170179e29e4SChris Mason 		if (slot == 0)
4171179e29e4SChris Mason 			fixup_low_keys(trans, root, path, &disk_key, 1);
4172179e29e4SChris Mason 	}
41735f39d397SChris Mason 
41745f39d397SChris Mason 	item = btrfs_item_nr(leaf, slot);
41755f39d397SChris Mason 	btrfs_set_item_size(leaf, item, new_size);
41765f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
4177b18c6685SChris Mason 
41785f39d397SChris Mason 	if (btrfs_leaf_free_space(root, leaf) < 0) {
41795f39d397SChris Mason 		btrfs_print_leaf(root, leaf);
4180b18c6685SChris Mason 		BUG();
41815f39d397SChris Mason 	}
4182b18c6685SChris Mason }
4183b18c6685SChris Mason 
4184d352ac68SChris Mason /*
4185d352ac68SChris Mason  * make the item pointed to by the path bigger, data_size is the new size.
4186d352ac68SChris Mason  */
4187143bede5SJeff Mahoney void btrfs_extend_item(struct btrfs_trans_handle *trans,
41885f39d397SChris Mason 		       struct btrfs_root *root, struct btrfs_path *path,
41895f39d397SChris Mason 		       u32 data_size)
41906567e837SChris Mason {
41916567e837SChris Mason 	int slot;
41925f39d397SChris Mason 	struct extent_buffer *leaf;
41935f39d397SChris Mason 	struct btrfs_item *item;
41946567e837SChris Mason 	u32 nritems;
41956567e837SChris Mason 	unsigned int data_end;
41966567e837SChris Mason 	unsigned int old_data;
41976567e837SChris Mason 	unsigned int old_size;
41986567e837SChris Mason 	int i;
4199cfed81a0SChris Mason 	struct btrfs_map_token token;
4200cfed81a0SChris Mason 
4201cfed81a0SChris Mason 	btrfs_init_map_token(&token);
42026567e837SChris Mason 
42035f39d397SChris Mason 	leaf = path->nodes[0];
42046567e837SChris Mason 
42055f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
42066567e837SChris Mason 	data_end = leaf_data_end(root, leaf);
42076567e837SChris Mason 
42085f39d397SChris Mason 	if (btrfs_leaf_free_space(root, leaf) < data_size) {
42095f39d397SChris Mason 		btrfs_print_leaf(root, leaf);
42106567e837SChris Mason 		BUG();
42115f39d397SChris Mason 	}
42126567e837SChris Mason 	slot = path->slots[0];
42135f39d397SChris Mason 	old_data = btrfs_item_end_nr(leaf, slot);
42146567e837SChris Mason 
42156567e837SChris Mason 	BUG_ON(slot < 0);
42163326d1b0SChris Mason 	if (slot >= nritems) {
42173326d1b0SChris Mason 		btrfs_print_leaf(root, leaf);
4218d397712bSChris Mason 		printk(KERN_CRIT "slot %d too large, nritems %d\n",
4219d397712bSChris Mason 		       slot, nritems);
42203326d1b0SChris Mason 		BUG_ON(1);
42213326d1b0SChris Mason 	}
42226567e837SChris Mason 
42236567e837SChris Mason 	/*
42246567e837SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
42256567e837SChris Mason 	 */
42266567e837SChris Mason 	/* first correct the data pointers */
42276567e837SChris Mason 	for (i = slot; i < nritems; i++) {
42285f39d397SChris Mason 		u32 ioff;
42295f39d397SChris Mason 		item = btrfs_item_nr(leaf, i);
4230db94535dSChris Mason 
4231cfed81a0SChris Mason 		ioff = btrfs_token_item_offset(leaf, item, &token);
4232cfed81a0SChris Mason 		btrfs_set_token_item_offset(leaf, item,
4233cfed81a0SChris Mason 					    ioff - data_size, &token);
42346567e837SChris Mason 	}
42355f39d397SChris Mason 
42366567e837SChris Mason 	/* shift the data */
42375f39d397SChris Mason 	memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
42386567e837SChris Mason 		      data_end - data_size, btrfs_leaf_data(leaf) +
42396567e837SChris Mason 		      data_end, old_data - data_end);
42405f39d397SChris Mason 
42416567e837SChris Mason 	data_end = old_data;
42425f39d397SChris Mason 	old_size = btrfs_item_size_nr(leaf, slot);
42435f39d397SChris Mason 	item = btrfs_item_nr(leaf, slot);
42445f39d397SChris Mason 	btrfs_set_item_size(leaf, item, old_size + data_size);
42455f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
42466567e837SChris Mason 
42475f39d397SChris Mason 	if (btrfs_leaf_free_space(root, leaf) < 0) {
42485f39d397SChris Mason 		btrfs_print_leaf(root, leaf);
42496567e837SChris Mason 		BUG();
42505f39d397SChris Mason 	}
42516567e837SChris Mason }
42526567e837SChris Mason 
425374123bd7SChris Mason /*
4254d352ac68SChris Mason  * Given a key and some data, insert items into the tree.
425574123bd7SChris Mason  * This does all the path init required, making room in the tree if needed.
4256f3465ca4SJosef Bacik  * Returns the number of keys that were inserted.
4257f3465ca4SJosef Bacik  */
4258f3465ca4SJosef Bacik int btrfs_insert_some_items(struct btrfs_trans_handle *trans,
4259f3465ca4SJosef Bacik 			    struct btrfs_root *root,
4260f3465ca4SJosef Bacik 			    struct btrfs_path *path,
4261f3465ca4SJosef Bacik 			    struct btrfs_key *cpu_key, u32 *data_size,
4262f3465ca4SJosef Bacik 			    int nr)
4263f3465ca4SJosef Bacik {
4264f3465ca4SJosef Bacik 	struct extent_buffer *leaf;
4265f3465ca4SJosef Bacik 	struct btrfs_item *item;
4266f3465ca4SJosef Bacik 	int ret = 0;
4267f3465ca4SJosef Bacik 	int slot;
4268f3465ca4SJosef Bacik 	int i;
4269f3465ca4SJosef Bacik 	u32 nritems;
4270f3465ca4SJosef Bacik 	u32 total_data = 0;
4271f3465ca4SJosef Bacik 	u32 total_size = 0;
4272f3465ca4SJosef Bacik 	unsigned int data_end;
4273f3465ca4SJosef Bacik 	struct btrfs_disk_key disk_key;
4274f3465ca4SJosef Bacik 	struct btrfs_key found_key;
4275cfed81a0SChris Mason 	struct btrfs_map_token token;
4276cfed81a0SChris Mason 
4277cfed81a0SChris Mason 	btrfs_init_map_token(&token);
4278f3465ca4SJosef Bacik 
427987b29b20SYan Zheng 	for (i = 0; i < nr; i++) {
428087b29b20SYan Zheng 		if (total_size + data_size[i] + sizeof(struct btrfs_item) >
428187b29b20SYan Zheng 		    BTRFS_LEAF_DATA_SIZE(root)) {
428287b29b20SYan Zheng 			break;
428387b29b20SYan Zheng 			nr = i;
428487b29b20SYan Zheng 		}
4285f3465ca4SJosef Bacik 		total_data += data_size[i];
428687b29b20SYan Zheng 		total_size += data_size[i] + sizeof(struct btrfs_item);
428787b29b20SYan Zheng 	}
428887b29b20SYan Zheng 	BUG_ON(nr == 0);
4289f3465ca4SJosef Bacik 
4290f3465ca4SJosef Bacik 	ret = btrfs_search_slot(trans, root, cpu_key, path, total_size, 1);
4291f3465ca4SJosef Bacik 	if (ret == 0)
4292f3465ca4SJosef Bacik 		return -EEXIST;
4293f3465ca4SJosef Bacik 	if (ret < 0)
4294f3465ca4SJosef Bacik 		goto out;
4295f3465ca4SJosef Bacik 
4296f3465ca4SJosef Bacik 	leaf = path->nodes[0];
4297f3465ca4SJosef Bacik 
4298f3465ca4SJosef Bacik 	nritems = btrfs_header_nritems(leaf);
4299f3465ca4SJosef Bacik 	data_end = leaf_data_end(root, leaf);
4300f3465ca4SJosef Bacik 
4301f3465ca4SJosef Bacik 	if (btrfs_leaf_free_space(root, leaf) < total_size) {
4302f3465ca4SJosef Bacik 		for (i = nr; i >= 0; i--) {
4303f3465ca4SJosef Bacik 			total_data -= data_size[i];
4304f3465ca4SJosef Bacik 			total_size -= data_size[i] + sizeof(struct btrfs_item);
4305f3465ca4SJosef Bacik 			if (total_size < btrfs_leaf_free_space(root, leaf))
4306f3465ca4SJosef Bacik 				break;
4307f3465ca4SJosef Bacik 		}
4308f3465ca4SJosef Bacik 		nr = i;
4309f3465ca4SJosef Bacik 	}
4310f3465ca4SJosef Bacik 
4311f3465ca4SJosef Bacik 	slot = path->slots[0];
4312f3465ca4SJosef Bacik 	BUG_ON(slot < 0);
4313f3465ca4SJosef Bacik 
4314f3465ca4SJosef Bacik 	if (slot != nritems) {
4315f3465ca4SJosef Bacik 		unsigned int old_data = btrfs_item_end_nr(leaf, slot);
4316f3465ca4SJosef Bacik 
4317f3465ca4SJosef Bacik 		item = btrfs_item_nr(leaf, slot);
4318f3465ca4SJosef Bacik 		btrfs_item_key_to_cpu(leaf, &found_key, slot);
4319f3465ca4SJosef Bacik 
4320f3465ca4SJosef Bacik 		/* figure out how many keys we can insert in here */
4321f3465ca4SJosef Bacik 		total_data = data_size[0];
4322f3465ca4SJosef Bacik 		for (i = 1; i < nr; i++) {
43235d4f98a2SYan Zheng 			if (btrfs_comp_cpu_keys(&found_key, cpu_key + i) <= 0)
4324f3465ca4SJosef Bacik 				break;
4325f3465ca4SJosef Bacik 			total_data += data_size[i];
4326f3465ca4SJosef Bacik 		}
4327f3465ca4SJosef Bacik 		nr = i;
4328f3465ca4SJosef Bacik 
4329f3465ca4SJosef Bacik 		if (old_data < data_end) {
4330f3465ca4SJosef Bacik 			btrfs_print_leaf(root, leaf);
4331d397712bSChris Mason 			printk(KERN_CRIT "slot %d old_data %d data_end %d\n",
4332f3465ca4SJosef Bacik 			       slot, old_data, data_end);
4333f3465ca4SJosef Bacik 			BUG_ON(1);
4334f3465ca4SJosef Bacik 		}
4335f3465ca4SJosef Bacik 		/*
4336f3465ca4SJosef Bacik 		 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4337f3465ca4SJosef Bacik 		 */
4338f3465ca4SJosef Bacik 		/* first correct the data pointers */
4339f3465ca4SJosef Bacik 		for (i = slot; i < nritems; i++) {
4340f3465ca4SJosef Bacik 			u32 ioff;
4341f3465ca4SJosef Bacik 
4342f3465ca4SJosef Bacik 			item = btrfs_item_nr(leaf, i);
4343cfed81a0SChris Mason 			ioff = btrfs_token_item_offset(leaf, item, &token);
4344cfed81a0SChris Mason 			btrfs_set_token_item_offset(leaf, item,
4345cfed81a0SChris Mason 						    ioff - total_data, &token);
4346f3465ca4SJosef Bacik 		}
4347f3465ca4SJosef Bacik 		/* shift the items */
4348f3465ca4SJosef Bacik 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + nr),
4349f3465ca4SJosef Bacik 			      btrfs_item_nr_offset(slot),
4350f3465ca4SJosef Bacik 			      (nritems - slot) * sizeof(struct btrfs_item));
4351f3465ca4SJosef Bacik 
4352f3465ca4SJosef Bacik 		/* shift the data */
4353f3465ca4SJosef Bacik 		memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
4354f3465ca4SJosef Bacik 			      data_end - total_data, btrfs_leaf_data(leaf) +
4355f3465ca4SJosef Bacik 			      data_end, old_data - data_end);
4356f3465ca4SJosef Bacik 		data_end = old_data;
4357f3465ca4SJosef Bacik 	} else {
4358f3465ca4SJosef Bacik 		/*
4359f3465ca4SJosef Bacik 		 * this sucks but it has to be done, if we are inserting at
4360f3465ca4SJosef Bacik 		 * the end of the leaf only insert 1 of the items, since we
4361f3465ca4SJosef Bacik 		 * have no way of knowing whats on the next leaf and we'd have
4362f3465ca4SJosef Bacik 		 * to drop our current locks to figure it out
4363f3465ca4SJosef Bacik 		 */
4364f3465ca4SJosef Bacik 		nr = 1;
4365f3465ca4SJosef Bacik 	}
4366f3465ca4SJosef Bacik 
4367f3465ca4SJosef Bacik 	/* setup the item for the new data */
4368f3465ca4SJosef Bacik 	for (i = 0; i < nr; i++) {
4369f3465ca4SJosef Bacik 		btrfs_cpu_key_to_disk(&disk_key, cpu_key + i);
4370f3465ca4SJosef Bacik 		btrfs_set_item_key(leaf, &disk_key, slot + i);
4371f3465ca4SJosef Bacik 		item = btrfs_item_nr(leaf, slot + i);
4372cfed81a0SChris Mason 		btrfs_set_token_item_offset(leaf, item,
4373cfed81a0SChris Mason 					    data_end - data_size[i], &token);
4374f3465ca4SJosef Bacik 		data_end -= data_size[i];
4375cfed81a0SChris Mason 		btrfs_set_token_item_size(leaf, item, data_size[i], &token);
4376f3465ca4SJosef Bacik 	}
4377f3465ca4SJosef Bacik 	btrfs_set_header_nritems(leaf, nritems + nr);
4378f3465ca4SJosef Bacik 	btrfs_mark_buffer_dirty(leaf);
4379f3465ca4SJosef Bacik 
4380f3465ca4SJosef Bacik 	ret = 0;
4381f3465ca4SJosef Bacik 	if (slot == 0) {
4382f3465ca4SJosef Bacik 		btrfs_cpu_key_to_disk(&disk_key, cpu_key);
4383143bede5SJeff Mahoney 		fixup_low_keys(trans, root, path, &disk_key, 1);
4384f3465ca4SJosef Bacik 	}
4385f3465ca4SJosef Bacik 
4386f3465ca4SJosef Bacik 	if (btrfs_leaf_free_space(root, leaf) < 0) {
4387f3465ca4SJosef Bacik 		btrfs_print_leaf(root, leaf);
4388f3465ca4SJosef Bacik 		BUG();
4389f3465ca4SJosef Bacik 	}
4390f3465ca4SJosef Bacik out:
4391f3465ca4SJosef Bacik 	if (!ret)
4392f3465ca4SJosef Bacik 		ret = nr;
4393f3465ca4SJosef Bacik 	return ret;
4394f3465ca4SJosef Bacik }
4395f3465ca4SJosef Bacik 
4396f3465ca4SJosef Bacik /*
439744871b1bSChris Mason  * this is a helper for btrfs_insert_empty_items, the main goal here is
439844871b1bSChris Mason  * to save stack depth by doing the bulk of the work in a function
439944871b1bSChris Mason  * that doesn't call btrfs_search_slot
440074123bd7SChris Mason  */
4401143bede5SJeff Mahoney void setup_items_for_insert(struct btrfs_trans_handle *trans,
440244871b1bSChris Mason 			    struct btrfs_root *root, struct btrfs_path *path,
44039c58309dSChris Mason 			    struct btrfs_key *cpu_key, u32 *data_size,
440444871b1bSChris Mason 			    u32 total_data, u32 total_size, int nr)
4405be0e5c09SChris Mason {
44065f39d397SChris Mason 	struct btrfs_item *item;
44079c58309dSChris Mason 	int i;
44087518a238SChris Mason 	u32 nritems;
4409be0e5c09SChris Mason 	unsigned int data_end;
4410e2fa7227SChris Mason 	struct btrfs_disk_key disk_key;
441144871b1bSChris Mason 	struct extent_buffer *leaf;
441244871b1bSChris Mason 	int slot;
4413cfed81a0SChris Mason 	struct btrfs_map_token token;
4414cfed81a0SChris Mason 
4415cfed81a0SChris Mason 	btrfs_init_map_token(&token);
4416e2fa7227SChris Mason 
44175f39d397SChris Mason 	leaf = path->nodes[0];
441844871b1bSChris Mason 	slot = path->slots[0];
441974123bd7SChris Mason 
44205f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
4421123abc88SChris Mason 	data_end = leaf_data_end(root, leaf);
4422eb60ceacSChris Mason 
4423f25956ccSChris Mason 	if (btrfs_leaf_free_space(root, leaf) < total_size) {
44243326d1b0SChris Mason 		btrfs_print_leaf(root, leaf);
4425d397712bSChris Mason 		printk(KERN_CRIT "not enough freespace need %u have %d\n",
44269c58309dSChris Mason 		       total_size, btrfs_leaf_free_space(root, leaf));
4427be0e5c09SChris Mason 		BUG();
4428d4dbff95SChris Mason 	}
44295f39d397SChris Mason 
4430be0e5c09SChris Mason 	if (slot != nritems) {
44315f39d397SChris Mason 		unsigned int old_data = btrfs_item_end_nr(leaf, slot);
4432be0e5c09SChris Mason 
44335f39d397SChris Mason 		if (old_data < data_end) {
44345f39d397SChris Mason 			btrfs_print_leaf(root, leaf);
4435d397712bSChris Mason 			printk(KERN_CRIT "slot %d old_data %d data_end %d\n",
44365f39d397SChris Mason 			       slot, old_data, data_end);
44375f39d397SChris Mason 			BUG_ON(1);
44385f39d397SChris Mason 		}
4439be0e5c09SChris Mason 		/*
4440be0e5c09SChris Mason 		 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4441be0e5c09SChris Mason 		 */
4442be0e5c09SChris Mason 		/* first correct the data pointers */
44430783fcfcSChris Mason 		for (i = slot; i < nritems; i++) {
44445f39d397SChris Mason 			u32 ioff;
4445db94535dSChris Mason 
44465f39d397SChris Mason 			item = btrfs_item_nr(leaf, i);
4447cfed81a0SChris Mason 			ioff = btrfs_token_item_offset(leaf, item, &token);
4448cfed81a0SChris Mason 			btrfs_set_token_item_offset(leaf, item,
4449cfed81a0SChris Mason 						    ioff - total_data, &token);
44500783fcfcSChris Mason 		}
4451be0e5c09SChris Mason 		/* shift the items */
44529c58309dSChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + nr),
44535f39d397SChris Mason 			      btrfs_item_nr_offset(slot),
44540783fcfcSChris Mason 			      (nritems - slot) * sizeof(struct btrfs_item));
4455be0e5c09SChris Mason 
4456be0e5c09SChris Mason 		/* shift the data */
44575f39d397SChris Mason 		memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
44589c58309dSChris Mason 			      data_end - total_data, btrfs_leaf_data(leaf) +
4459be0e5c09SChris Mason 			      data_end, old_data - data_end);
4460be0e5c09SChris Mason 		data_end = old_data;
4461be0e5c09SChris Mason 	}
44625f39d397SChris Mason 
446362e2749eSChris Mason 	/* setup the item for the new data */
44649c58309dSChris Mason 	for (i = 0; i < nr; i++) {
44659c58309dSChris Mason 		btrfs_cpu_key_to_disk(&disk_key, cpu_key + i);
44669c58309dSChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot + i);
44679c58309dSChris Mason 		item = btrfs_item_nr(leaf, slot + i);
4468cfed81a0SChris Mason 		btrfs_set_token_item_offset(leaf, item,
4469cfed81a0SChris Mason 					    data_end - data_size[i], &token);
44709c58309dSChris Mason 		data_end -= data_size[i];
4471cfed81a0SChris Mason 		btrfs_set_token_item_size(leaf, item, data_size[i], &token);
44729c58309dSChris Mason 	}
447344871b1bSChris Mason 
44749c58309dSChris Mason 	btrfs_set_header_nritems(leaf, nritems + nr);
4475aa5d6bedSChris Mason 
44765a01a2e3SChris Mason 	if (slot == 0) {
44775a01a2e3SChris Mason 		btrfs_cpu_key_to_disk(&disk_key, cpu_key);
4478143bede5SJeff Mahoney 		fixup_low_keys(trans, root, path, &disk_key, 1);
44795a01a2e3SChris Mason 	}
4480b9473439SChris Mason 	btrfs_unlock_up_safe(path, 1);
4481b9473439SChris Mason 	btrfs_mark_buffer_dirty(leaf);
4482aa5d6bedSChris Mason 
44835f39d397SChris Mason 	if (btrfs_leaf_free_space(root, leaf) < 0) {
44845f39d397SChris Mason 		btrfs_print_leaf(root, leaf);
4485be0e5c09SChris Mason 		BUG();
44865f39d397SChris Mason 	}
448744871b1bSChris Mason }
448844871b1bSChris Mason 
448944871b1bSChris Mason /*
449044871b1bSChris Mason  * Given a key and some data, insert items into the tree.
449144871b1bSChris Mason  * This does all the path init required, making room in the tree if needed.
449244871b1bSChris Mason  */
449344871b1bSChris Mason int btrfs_insert_empty_items(struct btrfs_trans_handle *trans,
449444871b1bSChris Mason 			    struct btrfs_root *root,
449544871b1bSChris Mason 			    struct btrfs_path *path,
449644871b1bSChris Mason 			    struct btrfs_key *cpu_key, u32 *data_size,
449744871b1bSChris Mason 			    int nr)
449844871b1bSChris Mason {
449944871b1bSChris Mason 	int ret = 0;
450044871b1bSChris Mason 	int slot;
450144871b1bSChris Mason 	int i;
450244871b1bSChris Mason 	u32 total_size = 0;
450344871b1bSChris Mason 	u32 total_data = 0;
450444871b1bSChris Mason 
450544871b1bSChris Mason 	for (i = 0; i < nr; i++)
450644871b1bSChris Mason 		total_data += data_size[i];
450744871b1bSChris Mason 
450844871b1bSChris Mason 	total_size = total_data + (nr * sizeof(struct btrfs_item));
450944871b1bSChris Mason 	ret = btrfs_search_slot(trans, root, cpu_key, path, total_size, 1);
451044871b1bSChris Mason 	if (ret == 0)
451144871b1bSChris Mason 		return -EEXIST;
451244871b1bSChris Mason 	if (ret < 0)
4513143bede5SJeff Mahoney 		return ret;
451444871b1bSChris Mason 
451544871b1bSChris Mason 	slot = path->slots[0];
451644871b1bSChris Mason 	BUG_ON(slot < 0);
451744871b1bSChris Mason 
4518143bede5SJeff Mahoney 	setup_items_for_insert(trans, root, path, cpu_key, data_size,
451944871b1bSChris Mason 			       total_data, total_size, nr);
4520143bede5SJeff Mahoney 	return 0;
452162e2749eSChris Mason }
452262e2749eSChris Mason 
452362e2749eSChris Mason /*
452462e2749eSChris Mason  * Given a key and some data, insert an item into the tree.
452562e2749eSChris Mason  * This does all the path init required, making room in the tree if needed.
452662e2749eSChris Mason  */
4527e089f05cSChris Mason int btrfs_insert_item(struct btrfs_trans_handle *trans, struct btrfs_root
4528e089f05cSChris Mason 		      *root, struct btrfs_key *cpu_key, void *data, u32
4529e089f05cSChris Mason 		      data_size)
453062e2749eSChris Mason {
453162e2749eSChris Mason 	int ret = 0;
45322c90e5d6SChris Mason 	struct btrfs_path *path;
45335f39d397SChris Mason 	struct extent_buffer *leaf;
45345f39d397SChris Mason 	unsigned long ptr;
453562e2749eSChris Mason 
45362c90e5d6SChris Mason 	path = btrfs_alloc_path();
4537db5b493aSTsutomu Itoh 	if (!path)
4538db5b493aSTsutomu Itoh 		return -ENOMEM;
45392c90e5d6SChris Mason 	ret = btrfs_insert_empty_item(trans, root, path, cpu_key, data_size);
454062e2749eSChris Mason 	if (!ret) {
45415f39d397SChris Mason 		leaf = path->nodes[0];
45425f39d397SChris Mason 		ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
45435f39d397SChris Mason 		write_extent_buffer(leaf, data, ptr, data_size);
45445f39d397SChris Mason 		btrfs_mark_buffer_dirty(leaf);
454562e2749eSChris Mason 	}
45462c90e5d6SChris Mason 	btrfs_free_path(path);
4547aa5d6bedSChris Mason 	return ret;
4548be0e5c09SChris Mason }
4549be0e5c09SChris Mason 
455074123bd7SChris Mason /*
45515de08d7dSChris Mason  * delete the pointer from a given node.
455274123bd7SChris Mason  *
4553d352ac68SChris Mason  * the tree should have been previously balanced so the deletion does not
4554d352ac68SChris Mason  * empty a node.
455574123bd7SChris Mason  */
4556143bede5SJeff Mahoney static void del_ptr(struct btrfs_trans_handle *trans, struct btrfs_root *root,
4557f3ea38daSJan Schmidt 		    struct btrfs_path *path, int level, int slot,
4558f3ea38daSJan Schmidt 		    int tree_mod_log)
4559be0e5c09SChris Mason {
45605f39d397SChris Mason 	struct extent_buffer *parent = path->nodes[level];
45617518a238SChris Mason 	u32 nritems;
4562f3ea38daSJan Schmidt 	int ret;
4563be0e5c09SChris Mason 
45645f39d397SChris Mason 	nritems = btrfs_header_nritems(parent);
4565be0e5c09SChris Mason 	if (slot != nritems - 1) {
4566f3ea38daSJan Schmidt 		if (tree_mod_log && level)
4567f3ea38daSJan Schmidt 			tree_mod_log_eb_move(root->fs_info, parent, slot,
4568f3ea38daSJan Schmidt 					     slot + 1, nritems - slot - 1);
45695f39d397SChris Mason 		memmove_extent_buffer(parent,
45705f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot),
45715f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot + 1),
4572d6025579SChris Mason 			      sizeof(struct btrfs_key_ptr) *
4573d6025579SChris Mason 			      (nritems - slot - 1));
4574f395694cSJan Schmidt 	} else if (tree_mod_log && level) {
4575f3ea38daSJan Schmidt 		ret = tree_mod_log_insert_key(root->fs_info, parent, slot,
4576f3ea38daSJan Schmidt 					      MOD_LOG_KEY_REMOVE);
4577f3ea38daSJan Schmidt 		BUG_ON(ret < 0);
4578be0e5c09SChris Mason 	}
4579f3ea38daSJan Schmidt 
45807518a238SChris Mason 	nritems--;
45815f39d397SChris Mason 	btrfs_set_header_nritems(parent, nritems);
45827518a238SChris Mason 	if (nritems == 0 && parent == root->node) {
45835f39d397SChris Mason 		BUG_ON(btrfs_header_level(root->node) != 1);
4584eb60ceacSChris Mason 		/* just turn the root into a leaf and break */
45855f39d397SChris Mason 		btrfs_set_header_level(root->node, 0);
4586bb803951SChris Mason 	} else if (slot == 0) {
45875f39d397SChris Mason 		struct btrfs_disk_key disk_key;
45885f39d397SChris Mason 
45895f39d397SChris Mason 		btrfs_node_key(parent, &disk_key, 0);
4590143bede5SJeff Mahoney 		fixup_low_keys(trans, root, path, &disk_key, level + 1);
4591be0e5c09SChris Mason 	}
4592d6025579SChris Mason 	btrfs_mark_buffer_dirty(parent);
4593be0e5c09SChris Mason }
4594be0e5c09SChris Mason 
459574123bd7SChris Mason /*
4596323ac95bSChris Mason  * a helper function to delete the leaf pointed to by path->slots[1] and
45975d4f98a2SYan Zheng  * path->nodes[1].
4598323ac95bSChris Mason  *
4599323ac95bSChris Mason  * This deletes the pointer in path->nodes[1] and frees the leaf
4600323ac95bSChris Mason  * block extent.  zero is returned if it all worked out, < 0 otherwise.
4601323ac95bSChris Mason  *
4602323ac95bSChris Mason  * The path must have already been setup for deleting the leaf, including
4603323ac95bSChris Mason  * all the proper balancing.  path->nodes[1] must be locked.
4604323ac95bSChris Mason  */
4605143bede5SJeff Mahoney static noinline void btrfs_del_leaf(struct btrfs_trans_handle *trans,
4606323ac95bSChris Mason 				    struct btrfs_root *root,
46075d4f98a2SYan Zheng 				    struct btrfs_path *path,
46085d4f98a2SYan Zheng 				    struct extent_buffer *leaf)
4609323ac95bSChris Mason {
46105d4f98a2SYan Zheng 	WARN_ON(btrfs_header_generation(leaf) != trans->transid);
4611f3ea38daSJan Schmidt 	del_ptr(trans, root, path, 1, path->slots[1], 1);
4612323ac95bSChris Mason 
46134d081c41SChris Mason 	/*
46144d081c41SChris Mason 	 * btrfs_free_extent is expensive, we want to make sure we
46154d081c41SChris Mason 	 * aren't holding any locks when we call it
46164d081c41SChris Mason 	 */
46174d081c41SChris Mason 	btrfs_unlock_up_safe(path, 0);
46184d081c41SChris Mason 
4619f0486c68SYan, Zheng 	root_sub_used(root, leaf->len);
4620f0486c68SYan, Zheng 
46213083ee2eSJosef Bacik 	extent_buffer_get(leaf);
46225581a51aSJan Schmidt 	btrfs_free_tree_block(trans, root, leaf, 0, 1);
46233083ee2eSJosef Bacik 	free_extent_buffer_stale(leaf);
4624323ac95bSChris Mason }
4625323ac95bSChris Mason /*
462674123bd7SChris Mason  * delete the item at the leaf level in path.  If that empties
462774123bd7SChris Mason  * the leaf, remove it from the tree
462874123bd7SChris Mason  */
462985e21bacSChris Mason int btrfs_del_items(struct btrfs_trans_handle *trans, struct btrfs_root *root,
463085e21bacSChris Mason 		    struct btrfs_path *path, int slot, int nr)
4631be0e5c09SChris Mason {
46325f39d397SChris Mason 	struct extent_buffer *leaf;
46335f39d397SChris Mason 	struct btrfs_item *item;
463485e21bacSChris Mason 	int last_off;
463585e21bacSChris Mason 	int dsize = 0;
4636aa5d6bedSChris Mason 	int ret = 0;
4637aa5d6bedSChris Mason 	int wret;
463885e21bacSChris Mason 	int i;
46397518a238SChris Mason 	u32 nritems;
4640cfed81a0SChris Mason 	struct btrfs_map_token token;
4641cfed81a0SChris Mason 
4642cfed81a0SChris Mason 	btrfs_init_map_token(&token);
4643be0e5c09SChris Mason 
46445f39d397SChris Mason 	leaf = path->nodes[0];
464585e21bacSChris Mason 	last_off = btrfs_item_offset_nr(leaf, slot + nr - 1);
464685e21bacSChris Mason 
464785e21bacSChris Mason 	for (i = 0; i < nr; i++)
464885e21bacSChris Mason 		dsize += btrfs_item_size_nr(leaf, slot + i);
464985e21bacSChris Mason 
46505f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
4651be0e5c09SChris Mason 
465285e21bacSChris Mason 	if (slot + nr != nritems) {
4653123abc88SChris Mason 		int data_end = leaf_data_end(root, leaf);
46545f39d397SChris Mason 
46555f39d397SChris Mason 		memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
4656d6025579SChris Mason 			      data_end + dsize,
4657123abc88SChris Mason 			      btrfs_leaf_data(leaf) + data_end,
465885e21bacSChris Mason 			      last_off - data_end);
46595f39d397SChris Mason 
466085e21bacSChris Mason 		for (i = slot + nr; i < nritems; i++) {
46615f39d397SChris Mason 			u32 ioff;
4662db94535dSChris Mason 
46635f39d397SChris Mason 			item = btrfs_item_nr(leaf, i);
4664cfed81a0SChris Mason 			ioff = btrfs_token_item_offset(leaf, item, &token);
4665cfed81a0SChris Mason 			btrfs_set_token_item_offset(leaf, item,
4666cfed81a0SChris Mason 						    ioff + dsize, &token);
46670783fcfcSChris Mason 		}
4668db94535dSChris Mason 
46695f39d397SChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot),
467085e21bacSChris Mason 			      btrfs_item_nr_offset(slot + nr),
46710783fcfcSChris Mason 			      sizeof(struct btrfs_item) *
467285e21bacSChris Mason 			      (nritems - slot - nr));
4673be0e5c09SChris Mason 	}
467485e21bacSChris Mason 	btrfs_set_header_nritems(leaf, nritems - nr);
467585e21bacSChris Mason 	nritems -= nr;
46765f39d397SChris Mason 
467774123bd7SChris Mason 	/* delete the leaf if we've emptied it */
46787518a238SChris Mason 	if (nritems == 0) {
46795f39d397SChris Mason 		if (leaf == root->node) {
46805f39d397SChris Mason 			btrfs_set_header_level(leaf, 0);
46819a8dd150SChris Mason 		} else {
4682f0486c68SYan, Zheng 			btrfs_set_path_blocking(path);
4683f0486c68SYan, Zheng 			clean_tree_block(trans, root, leaf);
4684143bede5SJeff Mahoney 			btrfs_del_leaf(trans, root, path, leaf);
46859a8dd150SChris Mason 		}
4686be0e5c09SChris Mason 	} else {
46877518a238SChris Mason 		int used = leaf_space_used(leaf, 0, nritems);
4688aa5d6bedSChris Mason 		if (slot == 0) {
46895f39d397SChris Mason 			struct btrfs_disk_key disk_key;
46905f39d397SChris Mason 
46915f39d397SChris Mason 			btrfs_item_key(leaf, &disk_key, 0);
4692143bede5SJeff Mahoney 			fixup_low_keys(trans, root, path, &disk_key, 1);
4693aa5d6bedSChris Mason 		}
4694aa5d6bedSChris Mason 
469574123bd7SChris Mason 		/* delete the leaf if it is mostly empty */
4696d717aa1dSYan Zheng 		if (used < BTRFS_LEAF_DATA_SIZE(root) / 3) {
4697be0e5c09SChris Mason 			/* push_leaf_left fixes the path.
4698be0e5c09SChris Mason 			 * make sure the path still points to our leaf
4699be0e5c09SChris Mason 			 * for possible call to del_ptr below
4700be0e5c09SChris Mason 			 */
47014920c9acSChris Mason 			slot = path->slots[1];
47025f39d397SChris Mason 			extent_buffer_get(leaf);
47035f39d397SChris Mason 
4704b9473439SChris Mason 			btrfs_set_path_blocking(path);
470599d8f83cSChris Mason 			wret = push_leaf_left(trans, root, path, 1, 1,
470699d8f83cSChris Mason 					      1, (u32)-1);
470754aa1f4dSChris Mason 			if (wret < 0 && wret != -ENOSPC)
4708aa5d6bedSChris Mason 				ret = wret;
47095f39d397SChris Mason 
47105f39d397SChris Mason 			if (path->nodes[0] == leaf &&
47115f39d397SChris Mason 			    btrfs_header_nritems(leaf)) {
471299d8f83cSChris Mason 				wret = push_leaf_right(trans, root, path, 1,
471399d8f83cSChris Mason 						       1, 1, 0);
471454aa1f4dSChris Mason 				if (wret < 0 && wret != -ENOSPC)
4715aa5d6bedSChris Mason 					ret = wret;
4716aa5d6bedSChris Mason 			}
47175f39d397SChris Mason 
47185f39d397SChris Mason 			if (btrfs_header_nritems(leaf) == 0) {
4719323ac95bSChris Mason 				path->slots[1] = slot;
4720143bede5SJeff Mahoney 				btrfs_del_leaf(trans, root, path, leaf);
47215f39d397SChris Mason 				free_extent_buffer(leaf);
4722143bede5SJeff Mahoney 				ret = 0;
47235de08d7dSChris Mason 			} else {
4724925baeddSChris Mason 				/* if we're still in the path, make sure
4725925baeddSChris Mason 				 * we're dirty.  Otherwise, one of the
4726925baeddSChris Mason 				 * push_leaf functions must have already
4727925baeddSChris Mason 				 * dirtied this buffer
4728925baeddSChris Mason 				 */
4729925baeddSChris Mason 				if (path->nodes[0] == leaf)
47305f39d397SChris Mason 					btrfs_mark_buffer_dirty(leaf);
47315f39d397SChris Mason 				free_extent_buffer(leaf);
4732be0e5c09SChris Mason 			}
4733d5719762SChris Mason 		} else {
47345f39d397SChris Mason 			btrfs_mark_buffer_dirty(leaf);
4735be0e5c09SChris Mason 		}
47369a8dd150SChris Mason 	}
4737aa5d6bedSChris Mason 	return ret;
47389a8dd150SChris Mason }
47399a8dd150SChris Mason 
474097571fd0SChris Mason /*
4741925baeddSChris Mason  * search the tree again to find a leaf with lesser keys
47427bb86316SChris Mason  * returns 0 if it found something or 1 if there are no lesser leaves.
47437bb86316SChris Mason  * returns < 0 on io errors.
4744d352ac68SChris Mason  *
4745d352ac68SChris Mason  * This may release the path, and so you may lose any locks held at the
4746d352ac68SChris Mason  * time you call it.
47477bb86316SChris Mason  */
47487bb86316SChris Mason int btrfs_prev_leaf(struct btrfs_root *root, struct btrfs_path *path)
47497bb86316SChris Mason {
4750925baeddSChris Mason 	struct btrfs_key key;
4751925baeddSChris Mason 	struct btrfs_disk_key found_key;
4752925baeddSChris Mason 	int ret;
47537bb86316SChris Mason 
4754925baeddSChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, 0);
4755925baeddSChris Mason 
4756925baeddSChris Mason 	if (key.offset > 0)
4757925baeddSChris Mason 		key.offset--;
4758925baeddSChris Mason 	else if (key.type > 0)
4759925baeddSChris Mason 		key.type--;
4760925baeddSChris Mason 	else if (key.objectid > 0)
4761925baeddSChris Mason 		key.objectid--;
4762925baeddSChris Mason 	else
47637bb86316SChris Mason 		return 1;
47647bb86316SChris Mason 
4765b3b4aa74SDavid Sterba 	btrfs_release_path(path);
4766925baeddSChris Mason 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4767925baeddSChris Mason 	if (ret < 0)
4768925baeddSChris Mason 		return ret;
4769925baeddSChris Mason 	btrfs_item_key(path->nodes[0], &found_key, 0);
4770925baeddSChris Mason 	ret = comp_keys(&found_key, &key);
4771925baeddSChris Mason 	if (ret < 0)
47727bb86316SChris Mason 		return 0;
4773925baeddSChris Mason 	return 1;
47747bb86316SChris Mason }
47757bb86316SChris Mason 
47763f157a2fSChris Mason /*
47773f157a2fSChris Mason  * A helper function to walk down the tree starting at min_key, and looking
47783f157a2fSChris Mason  * for nodes or leaves that are either in cache or have a minimum
4779d352ac68SChris Mason  * transaction id.  This is used by the btree defrag code, and tree logging
47803f157a2fSChris Mason  *
47813f157a2fSChris Mason  * This does not cow, but it does stuff the starting key it finds back
47823f157a2fSChris Mason  * into min_key, so you can call btrfs_search_slot with cow=1 on the
47833f157a2fSChris Mason  * key and get a writable path.
47843f157a2fSChris Mason  *
47853f157a2fSChris Mason  * This does lock as it descends, and path->keep_locks should be set
47863f157a2fSChris Mason  * to 1 by the caller.
47873f157a2fSChris Mason  *
47883f157a2fSChris Mason  * This honors path->lowest_level to prevent descent past a given level
47893f157a2fSChris Mason  * of the tree.
47903f157a2fSChris Mason  *
4791d352ac68SChris Mason  * min_trans indicates the oldest transaction that you are interested
4792d352ac68SChris Mason  * in walking through.  Any nodes or leaves older than min_trans are
4793d352ac68SChris Mason  * skipped over (without reading them).
4794d352ac68SChris Mason  *
47953f157a2fSChris Mason  * returns zero if something useful was found, < 0 on error and 1 if there
47963f157a2fSChris Mason  * was nothing in the tree that matched the search criteria.
47973f157a2fSChris Mason  */
47983f157a2fSChris Mason int btrfs_search_forward(struct btrfs_root *root, struct btrfs_key *min_key,
4799e02119d5SChris Mason 			 struct btrfs_key *max_key,
48003f157a2fSChris Mason 			 struct btrfs_path *path, int cache_only,
48013f157a2fSChris Mason 			 u64 min_trans)
48023f157a2fSChris Mason {
48033f157a2fSChris Mason 	struct extent_buffer *cur;
48043f157a2fSChris Mason 	struct btrfs_key found_key;
48053f157a2fSChris Mason 	int slot;
48069652480bSYan 	int sret;
48073f157a2fSChris Mason 	u32 nritems;
48083f157a2fSChris Mason 	int level;
48093f157a2fSChris Mason 	int ret = 1;
48103f157a2fSChris Mason 
4811934d375bSChris Mason 	WARN_ON(!path->keep_locks);
48123f157a2fSChris Mason again:
4813bd681513SChris Mason 	cur = btrfs_read_lock_root_node(root);
48143f157a2fSChris Mason 	level = btrfs_header_level(cur);
4815e02119d5SChris Mason 	WARN_ON(path->nodes[level]);
48163f157a2fSChris Mason 	path->nodes[level] = cur;
4817bd681513SChris Mason 	path->locks[level] = BTRFS_READ_LOCK;
48183f157a2fSChris Mason 
48193f157a2fSChris Mason 	if (btrfs_header_generation(cur) < min_trans) {
48203f157a2fSChris Mason 		ret = 1;
48213f157a2fSChris Mason 		goto out;
48223f157a2fSChris Mason 	}
48233f157a2fSChris Mason 	while (1) {
48243f157a2fSChris Mason 		nritems = btrfs_header_nritems(cur);
48253f157a2fSChris Mason 		level = btrfs_header_level(cur);
48269652480bSYan 		sret = bin_search(cur, min_key, level, &slot);
48273f157a2fSChris Mason 
4828323ac95bSChris Mason 		/* at the lowest level, we're done, setup the path and exit */
4829323ac95bSChris Mason 		if (level == path->lowest_level) {
4830e02119d5SChris Mason 			if (slot >= nritems)
4831e02119d5SChris Mason 				goto find_next_key;
48323f157a2fSChris Mason 			ret = 0;
48333f157a2fSChris Mason 			path->slots[level] = slot;
48343f157a2fSChris Mason 			btrfs_item_key_to_cpu(cur, &found_key, slot);
48353f157a2fSChris Mason 			goto out;
48363f157a2fSChris Mason 		}
48379652480bSYan 		if (sret && slot > 0)
48389652480bSYan 			slot--;
48393f157a2fSChris Mason 		/*
48403f157a2fSChris Mason 		 * check this node pointer against the cache_only and
48413f157a2fSChris Mason 		 * min_trans parameters.  If it isn't in cache or is too
48423f157a2fSChris Mason 		 * old, skip to the next one.
48433f157a2fSChris Mason 		 */
48443f157a2fSChris Mason 		while (slot < nritems) {
48453f157a2fSChris Mason 			u64 blockptr;
48463f157a2fSChris Mason 			u64 gen;
48473f157a2fSChris Mason 			struct extent_buffer *tmp;
4848e02119d5SChris Mason 			struct btrfs_disk_key disk_key;
4849e02119d5SChris Mason 
48503f157a2fSChris Mason 			blockptr = btrfs_node_blockptr(cur, slot);
48513f157a2fSChris Mason 			gen = btrfs_node_ptr_generation(cur, slot);
48523f157a2fSChris Mason 			if (gen < min_trans) {
48533f157a2fSChris Mason 				slot++;
48543f157a2fSChris Mason 				continue;
48553f157a2fSChris Mason 			}
48563f157a2fSChris Mason 			if (!cache_only)
48573f157a2fSChris Mason 				break;
48583f157a2fSChris Mason 
4859e02119d5SChris Mason 			if (max_key) {
4860e02119d5SChris Mason 				btrfs_node_key(cur, &disk_key, slot);
4861e02119d5SChris Mason 				if (comp_keys(&disk_key, max_key) >= 0) {
4862e02119d5SChris Mason 					ret = 1;
4863e02119d5SChris Mason 					goto out;
4864e02119d5SChris Mason 				}
4865e02119d5SChris Mason 			}
4866e02119d5SChris Mason 
48673f157a2fSChris Mason 			tmp = btrfs_find_tree_block(root, blockptr,
48683f157a2fSChris Mason 					    btrfs_level_size(root, level - 1));
48693f157a2fSChris Mason 
4870b9fab919SChris Mason 			if (tmp && btrfs_buffer_uptodate(tmp, gen, 1) > 0) {
48713f157a2fSChris Mason 				free_extent_buffer(tmp);
48723f157a2fSChris Mason 				break;
48733f157a2fSChris Mason 			}
48743f157a2fSChris Mason 			if (tmp)
48753f157a2fSChris Mason 				free_extent_buffer(tmp);
48763f157a2fSChris Mason 			slot++;
48773f157a2fSChris Mason 		}
4878e02119d5SChris Mason find_next_key:
48793f157a2fSChris Mason 		/*
48803f157a2fSChris Mason 		 * we didn't find a candidate key in this node, walk forward
48813f157a2fSChris Mason 		 * and find another one
48823f157a2fSChris Mason 		 */
48833f157a2fSChris Mason 		if (slot >= nritems) {
4884e02119d5SChris Mason 			path->slots[level] = slot;
4885b4ce94deSChris Mason 			btrfs_set_path_blocking(path);
4886e02119d5SChris Mason 			sret = btrfs_find_next_key(root, path, min_key, level,
48873f157a2fSChris Mason 						  cache_only, min_trans);
4888e02119d5SChris Mason 			if (sret == 0) {
4889b3b4aa74SDavid Sterba 				btrfs_release_path(path);
48903f157a2fSChris Mason 				goto again;
48913f157a2fSChris Mason 			} else {
48923f157a2fSChris Mason 				goto out;
48933f157a2fSChris Mason 			}
48943f157a2fSChris Mason 		}
48953f157a2fSChris Mason 		/* save our key for returning back */
48963f157a2fSChris Mason 		btrfs_node_key_to_cpu(cur, &found_key, slot);
48973f157a2fSChris Mason 		path->slots[level] = slot;
48983f157a2fSChris Mason 		if (level == path->lowest_level) {
48993f157a2fSChris Mason 			ret = 0;
4900f7c79f30SChris Mason 			unlock_up(path, level, 1, 0, NULL);
49013f157a2fSChris Mason 			goto out;
49023f157a2fSChris Mason 		}
4903b4ce94deSChris Mason 		btrfs_set_path_blocking(path);
49043f157a2fSChris Mason 		cur = read_node_slot(root, cur, slot);
490579787eaaSJeff Mahoney 		BUG_ON(!cur); /* -ENOMEM */
49063f157a2fSChris Mason 
4907bd681513SChris Mason 		btrfs_tree_read_lock(cur);
4908b4ce94deSChris Mason 
4909bd681513SChris Mason 		path->locks[level - 1] = BTRFS_READ_LOCK;
49103f157a2fSChris Mason 		path->nodes[level - 1] = cur;
4911f7c79f30SChris Mason 		unlock_up(path, level, 1, 0, NULL);
4912bd681513SChris Mason 		btrfs_clear_path_blocking(path, NULL, 0);
49133f157a2fSChris Mason 	}
49143f157a2fSChris Mason out:
49153f157a2fSChris Mason 	if (ret == 0)
49163f157a2fSChris Mason 		memcpy(min_key, &found_key, sizeof(found_key));
4917b4ce94deSChris Mason 	btrfs_set_path_blocking(path);
49183f157a2fSChris Mason 	return ret;
49193f157a2fSChris Mason }
49203f157a2fSChris Mason 
49213f157a2fSChris Mason /*
49223f157a2fSChris Mason  * this is similar to btrfs_next_leaf, but does not try to preserve
49233f157a2fSChris Mason  * and fixup the path.  It looks for and returns the next key in the
49243f157a2fSChris Mason  * tree based on the current path and the cache_only and min_trans
49253f157a2fSChris Mason  * parameters.
49263f157a2fSChris Mason  *
49273f157a2fSChris Mason  * 0 is returned if another key is found, < 0 if there are any errors
49283f157a2fSChris Mason  * and 1 is returned if there are no higher keys in the tree
49293f157a2fSChris Mason  *
49303f157a2fSChris Mason  * path->keep_locks should be set to 1 on the search made before
49313f157a2fSChris Mason  * calling this function.
49323f157a2fSChris Mason  */
4933e7a84565SChris Mason int btrfs_find_next_key(struct btrfs_root *root, struct btrfs_path *path,
493433c66f43SYan Zheng 			struct btrfs_key *key, int level,
49353f157a2fSChris Mason 			int cache_only, u64 min_trans)
4936e7a84565SChris Mason {
4937e7a84565SChris Mason 	int slot;
4938e7a84565SChris Mason 	struct extent_buffer *c;
4939e7a84565SChris Mason 
4940934d375bSChris Mason 	WARN_ON(!path->keep_locks);
4941e7a84565SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
4942e7a84565SChris Mason 		if (!path->nodes[level])
4943e7a84565SChris Mason 			return 1;
4944e7a84565SChris Mason 
4945e7a84565SChris Mason 		slot = path->slots[level] + 1;
4946e7a84565SChris Mason 		c = path->nodes[level];
49473f157a2fSChris Mason next:
4948e7a84565SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
494933c66f43SYan Zheng 			int ret;
495033c66f43SYan Zheng 			int orig_lowest;
495133c66f43SYan Zheng 			struct btrfs_key cur_key;
495233c66f43SYan Zheng 			if (level + 1 >= BTRFS_MAX_LEVEL ||
495333c66f43SYan Zheng 			    !path->nodes[level + 1])
4954e7a84565SChris Mason 				return 1;
495533c66f43SYan Zheng 
495633c66f43SYan Zheng 			if (path->locks[level + 1]) {
495733c66f43SYan Zheng 				level++;
4958e7a84565SChris Mason 				continue;
4959e7a84565SChris Mason 			}
496033c66f43SYan Zheng 
496133c66f43SYan Zheng 			slot = btrfs_header_nritems(c) - 1;
496233c66f43SYan Zheng 			if (level == 0)
496333c66f43SYan Zheng 				btrfs_item_key_to_cpu(c, &cur_key, slot);
496433c66f43SYan Zheng 			else
496533c66f43SYan Zheng 				btrfs_node_key_to_cpu(c, &cur_key, slot);
496633c66f43SYan Zheng 
496733c66f43SYan Zheng 			orig_lowest = path->lowest_level;
4968b3b4aa74SDavid Sterba 			btrfs_release_path(path);
496933c66f43SYan Zheng 			path->lowest_level = level;
497033c66f43SYan Zheng 			ret = btrfs_search_slot(NULL, root, &cur_key, path,
497133c66f43SYan Zheng 						0, 0);
497233c66f43SYan Zheng 			path->lowest_level = orig_lowest;
497333c66f43SYan Zheng 			if (ret < 0)
497433c66f43SYan Zheng 				return ret;
497533c66f43SYan Zheng 
497633c66f43SYan Zheng 			c = path->nodes[level];
497733c66f43SYan Zheng 			slot = path->slots[level];
497833c66f43SYan Zheng 			if (ret == 0)
497933c66f43SYan Zheng 				slot++;
498033c66f43SYan Zheng 			goto next;
498133c66f43SYan Zheng 		}
498233c66f43SYan Zheng 
4983e7a84565SChris Mason 		if (level == 0)
4984e7a84565SChris Mason 			btrfs_item_key_to_cpu(c, key, slot);
49853f157a2fSChris Mason 		else {
49863f157a2fSChris Mason 			u64 blockptr = btrfs_node_blockptr(c, slot);
49873f157a2fSChris Mason 			u64 gen = btrfs_node_ptr_generation(c, slot);
49883f157a2fSChris Mason 
49893f157a2fSChris Mason 			if (cache_only) {
49903f157a2fSChris Mason 				struct extent_buffer *cur;
49913f157a2fSChris Mason 				cur = btrfs_find_tree_block(root, blockptr,
49923f157a2fSChris Mason 					    btrfs_level_size(root, level - 1));
4993b9fab919SChris Mason 				if (!cur ||
4994b9fab919SChris Mason 				    btrfs_buffer_uptodate(cur, gen, 1) <= 0) {
49953f157a2fSChris Mason 					slot++;
49963f157a2fSChris Mason 					if (cur)
49973f157a2fSChris Mason 						free_extent_buffer(cur);
49983f157a2fSChris Mason 					goto next;
49993f157a2fSChris Mason 				}
50003f157a2fSChris Mason 				free_extent_buffer(cur);
50013f157a2fSChris Mason 			}
50023f157a2fSChris Mason 			if (gen < min_trans) {
50033f157a2fSChris Mason 				slot++;
50043f157a2fSChris Mason 				goto next;
50053f157a2fSChris Mason 			}
5006e7a84565SChris Mason 			btrfs_node_key_to_cpu(c, key, slot);
50073f157a2fSChris Mason 		}
5008e7a84565SChris Mason 		return 0;
5009e7a84565SChris Mason 	}
5010e7a84565SChris Mason 	return 1;
5011e7a84565SChris Mason }
5012e7a84565SChris Mason 
50137bb86316SChris Mason /*
5014925baeddSChris Mason  * search the tree again to find a leaf with greater keys
50150f70abe2SChris Mason  * returns 0 if it found something or 1 if there are no greater leaves.
50160f70abe2SChris Mason  * returns < 0 on io errors.
501797571fd0SChris Mason  */
5018234b63a0SChris Mason int btrfs_next_leaf(struct btrfs_root *root, struct btrfs_path *path)
5019d97e63b6SChris Mason {
5020d97e63b6SChris Mason 	int slot;
50218e73f275SChris Mason 	int level;
50225f39d397SChris Mason 	struct extent_buffer *c;
50238e73f275SChris Mason 	struct extent_buffer *next;
5024925baeddSChris Mason 	struct btrfs_key key;
5025925baeddSChris Mason 	u32 nritems;
5026925baeddSChris Mason 	int ret;
50278e73f275SChris Mason 	int old_spinning = path->leave_spinning;
5028bd681513SChris Mason 	int next_rw_lock = 0;
5029925baeddSChris Mason 
5030925baeddSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
5031d397712bSChris Mason 	if (nritems == 0)
5032925baeddSChris Mason 		return 1;
5033925baeddSChris Mason 
50348e73f275SChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, nritems - 1);
50358e73f275SChris Mason again:
50368e73f275SChris Mason 	level = 1;
50378e73f275SChris Mason 	next = NULL;
5038bd681513SChris Mason 	next_rw_lock = 0;
5039b3b4aa74SDavid Sterba 	btrfs_release_path(path);
50408e73f275SChris Mason 
5041a2135011SChris Mason 	path->keep_locks = 1;
50428e73f275SChris Mason 	path->leave_spinning = 1;
50438e73f275SChris Mason 
5044925baeddSChris Mason 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5045925baeddSChris Mason 	path->keep_locks = 0;
5046925baeddSChris Mason 
5047925baeddSChris Mason 	if (ret < 0)
5048925baeddSChris Mason 		return ret;
5049925baeddSChris Mason 
5050a2135011SChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
5051168fd7d2SChris Mason 	/*
5052168fd7d2SChris Mason 	 * by releasing the path above we dropped all our locks.  A balance
5053168fd7d2SChris Mason 	 * could have added more items next to the key that used to be
5054168fd7d2SChris Mason 	 * at the very end of the block.  So, check again here and
5055168fd7d2SChris Mason 	 * advance the path if there are now more items available.
5056168fd7d2SChris Mason 	 */
5057a2135011SChris Mason 	if (nritems > 0 && path->slots[0] < nritems - 1) {
5058e457afecSYan Zheng 		if (ret == 0)
5059168fd7d2SChris Mason 			path->slots[0]++;
50608e73f275SChris Mason 		ret = 0;
5061925baeddSChris Mason 		goto done;
5062925baeddSChris Mason 	}
5063d97e63b6SChris Mason 
5064234b63a0SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
50658e73f275SChris Mason 		if (!path->nodes[level]) {
50668e73f275SChris Mason 			ret = 1;
50678e73f275SChris Mason 			goto done;
50688e73f275SChris Mason 		}
50695f39d397SChris Mason 
5070d97e63b6SChris Mason 		slot = path->slots[level] + 1;
5071d97e63b6SChris Mason 		c = path->nodes[level];
50725f39d397SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
5073d97e63b6SChris Mason 			level++;
50748e73f275SChris Mason 			if (level == BTRFS_MAX_LEVEL) {
50758e73f275SChris Mason 				ret = 1;
50768e73f275SChris Mason 				goto done;
50778e73f275SChris Mason 			}
5078d97e63b6SChris Mason 			continue;
5079d97e63b6SChris Mason 		}
50805f39d397SChris Mason 
5081925baeddSChris Mason 		if (next) {
5082bd681513SChris Mason 			btrfs_tree_unlock_rw(next, next_rw_lock);
50835f39d397SChris Mason 			free_extent_buffer(next);
5084925baeddSChris Mason 		}
50855f39d397SChris Mason 
50868e73f275SChris Mason 		next = c;
5087bd681513SChris Mason 		next_rw_lock = path->locks[level];
50888e73f275SChris Mason 		ret = read_block_for_search(NULL, root, path, &next, level,
50895d9e75c4SJan Schmidt 					    slot, &key, 0);
50908e73f275SChris Mason 		if (ret == -EAGAIN)
50918e73f275SChris Mason 			goto again;
50925f39d397SChris Mason 
509376a05b35SChris Mason 		if (ret < 0) {
5094b3b4aa74SDavid Sterba 			btrfs_release_path(path);
509576a05b35SChris Mason 			goto done;
509676a05b35SChris Mason 		}
509776a05b35SChris Mason 
50985cd57b2cSChris Mason 		if (!path->skip_locking) {
5099bd681513SChris Mason 			ret = btrfs_try_tree_read_lock(next);
51008e73f275SChris Mason 			if (!ret) {
51018e73f275SChris Mason 				btrfs_set_path_blocking(path);
5102bd681513SChris Mason 				btrfs_tree_read_lock(next);
5103bd681513SChris Mason 				btrfs_clear_path_blocking(path, next,
5104bd681513SChris Mason 							  BTRFS_READ_LOCK);
51058e73f275SChris Mason 			}
5106bd681513SChris Mason 			next_rw_lock = BTRFS_READ_LOCK;
5107bd681513SChris Mason 		}
5108d97e63b6SChris Mason 		break;
5109d97e63b6SChris Mason 	}
5110d97e63b6SChris Mason 	path->slots[level] = slot;
5111d97e63b6SChris Mason 	while (1) {
5112d97e63b6SChris Mason 		level--;
5113d97e63b6SChris Mason 		c = path->nodes[level];
5114925baeddSChris Mason 		if (path->locks[level])
5115bd681513SChris Mason 			btrfs_tree_unlock_rw(c, path->locks[level]);
51168e73f275SChris Mason 
51175f39d397SChris Mason 		free_extent_buffer(c);
5118d97e63b6SChris Mason 		path->nodes[level] = next;
5119d97e63b6SChris Mason 		path->slots[level] = 0;
5120a74a4b97SChris Mason 		if (!path->skip_locking)
5121bd681513SChris Mason 			path->locks[level] = next_rw_lock;
5122d97e63b6SChris Mason 		if (!level)
5123d97e63b6SChris Mason 			break;
5124b4ce94deSChris Mason 
51258e73f275SChris Mason 		ret = read_block_for_search(NULL, root, path, &next, level,
51265d9e75c4SJan Schmidt 					    0, &key, 0);
51278e73f275SChris Mason 		if (ret == -EAGAIN)
51288e73f275SChris Mason 			goto again;
51298e73f275SChris Mason 
513076a05b35SChris Mason 		if (ret < 0) {
5131b3b4aa74SDavid Sterba 			btrfs_release_path(path);
513276a05b35SChris Mason 			goto done;
513376a05b35SChris Mason 		}
513476a05b35SChris Mason 
51355cd57b2cSChris Mason 		if (!path->skip_locking) {
5136bd681513SChris Mason 			ret = btrfs_try_tree_read_lock(next);
51378e73f275SChris Mason 			if (!ret) {
51388e73f275SChris Mason 				btrfs_set_path_blocking(path);
5139bd681513SChris Mason 				btrfs_tree_read_lock(next);
5140bd681513SChris Mason 				btrfs_clear_path_blocking(path, next,
5141bd681513SChris Mason 							  BTRFS_READ_LOCK);
51428e73f275SChris Mason 			}
5143bd681513SChris Mason 			next_rw_lock = BTRFS_READ_LOCK;
5144bd681513SChris Mason 		}
5145d97e63b6SChris Mason 	}
51468e73f275SChris Mason 	ret = 0;
5147925baeddSChris Mason done:
5148f7c79f30SChris Mason 	unlock_up(path, 0, 1, 0, NULL);
51498e73f275SChris Mason 	path->leave_spinning = old_spinning;
51508e73f275SChris Mason 	if (!old_spinning)
51518e73f275SChris Mason 		btrfs_set_path_blocking(path);
51528e73f275SChris Mason 
51538e73f275SChris Mason 	return ret;
5154d97e63b6SChris Mason }
51550b86a832SChris Mason 
51563f157a2fSChris Mason /*
51573f157a2fSChris Mason  * this uses btrfs_prev_leaf to walk backwards in the tree, and keeps
51583f157a2fSChris Mason  * searching until it gets past min_objectid or finds an item of 'type'
51593f157a2fSChris Mason  *
51603f157a2fSChris Mason  * returns 0 if something is found, 1 if nothing was found and < 0 on error
51613f157a2fSChris Mason  */
51620b86a832SChris Mason int btrfs_previous_item(struct btrfs_root *root,
51630b86a832SChris Mason 			struct btrfs_path *path, u64 min_objectid,
51640b86a832SChris Mason 			int type)
51650b86a832SChris Mason {
51660b86a832SChris Mason 	struct btrfs_key found_key;
51670b86a832SChris Mason 	struct extent_buffer *leaf;
5168e02119d5SChris Mason 	u32 nritems;
51690b86a832SChris Mason 	int ret;
51700b86a832SChris Mason 
51710b86a832SChris Mason 	while (1) {
51720b86a832SChris Mason 		if (path->slots[0] == 0) {
5173b4ce94deSChris Mason 			btrfs_set_path_blocking(path);
51740b86a832SChris Mason 			ret = btrfs_prev_leaf(root, path);
51750b86a832SChris Mason 			if (ret != 0)
51760b86a832SChris Mason 				return ret;
51770b86a832SChris Mason 		} else {
51780b86a832SChris Mason 			path->slots[0]--;
51790b86a832SChris Mason 		}
51800b86a832SChris Mason 		leaf = path->nodes[0];
5181e02119d5SChris Mason 		nritems = btrfs_header_nritems(leaf);
5182e02119d5SChris Mason 		if (nritems == 0)
5183e02119d5SChris Mason 			return 1;
5184e02119d5SChris Mason 		if (path->slots[0] == nritems)
5185e02119d5SChris Mason 			path->slots[0]--;
5186e02119d5SChris Mason 
51870b86a832SChris Mason 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5188e02119d5SChris Mason 		if (found_key.objectid < min_objectid)
5189e02119d5SChris Mason 			break;
51900a4eefbbSYan Zheng 		if (found_key.type == type)
51910a4eefbbSYan Zheng 			return 0;
5192e02119d5SChris Mason 		if (found_key.objectid == min_objectid &&
5193e02119d5SChris Mason 		    found_key.type < type)
5194e02119d5SChris Mason 			break;
51950b86a832SChris Mason 	}
51960b86a832SChris Mason 	return 1;
51970b86a832SChris Mason }
5198