xref: /openbmc/linux/fs/btrfs/ctree.c (revision 097b8a7c9e48e2cb50fd0eb9315791921beaf484)
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 */
324*097b8a7cSJan Schmidt 	u64 seq;
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 
344*097b8a7cSJan Schmidt static inline void tree_mod_log_read_lock(struct btrfs_fs_info *fs_info)
345bd989ba3SJan Schmidt {
346*097b8a7cSJan Schmidt 	read_lock(&fs_info->tree_mod_log_lock);
347bd989ba3SJan Schmidt }
348bd989ba3SJan Schmidt 
349*097b8a7cSJan Schmidt static inline void tree_mod_log_read_unlock(struct btrfs_fs_info *fs_info)
350*097b8a7cSJan Schmidt {
351*097b8a7cSJan Schmidt 	read_unlock(&fs_info->tree_mod_log_lock);
352*097b8a7cSJan Schmidt }
353*097b8a7cSJan Schmidt 
354*097b8a7cSJan Schmidt static inline void tree_mod_log_write_lock(struct btrfs_fs_info *fs_info)
355*097b8a7cSJan Schmidt {
356*097b8a7cSJan Schmidt 	write_lock(&fs_info->tree_mod_log_lock);
357*097b8a7cSJan Schmidt }
358*097b8a7cSJan Schmidt 
359*097b8a7cSJan Schmidt static inline void tree_mod_log_write_unlock(struct btrfs_fs_info *fs_info)
360*097b8a7cSJan Schmidt {
361*097b8a7cSJan Schmidt 	write_unlock(&fs_info->tree_mod_log_lock);
362*097b8a7cSJan Schmidt }
363*097b8a7cSJan Schmidt 
364*097b8a7cSJan Schmidt /*
365*097b8a7cSJan Schmidt  * This adds a new blocker to the tree mod log's blocker list if the @elem
366*097b8a7cSJan Schmidt  * passed does not already have a sequence number set. So when a caller expects
367*097b8a7cSJan Schmidt  * to record tree modifications, it should ensure to set elem->seq to zero
368*097b8a7cSJan Schmidt  * before calling btrfs_get_tree_mod_seq.
369*097b8a7cSJan Schmidt  * Returns a fresh, unused tree log modification sequence number, even if no new
370*097b8a7cSJan Schmidt  * blocker was added.
371*097b8a7cSJan Schmidt  */
372*097b8a7cSJan Schmidt u64 btrfs_get_tree_mod_seq(struct btrfs_fs_info *fs_info,
373bd989ba3SJan Schmidt 			   struct seq_list *elem)
374bd989ba3SJan Schmidt {
375*097b8a7cSJan Schmidt 	u64 seq;
376*097b8a7cSJan Schmidt 
377*097b8a7cSJan Schmidt 	tree_mod_log_write_lock(fs_info);
378bd989ba3SJan Schmidt 	spin_lock(&fs_info->tree_mod_seq_lock);
379*097b8a7cSJan Schmidt 	if (!elem->seq) {
380*097b8a7cSJan Schmidt 		elem->seq = btrfs_inc_tree_mod_seq(fs_info);
381*097b8a7cSJan Schmidt 		list_add_tail(&elem->list, &fs_info->tree_mod_seq_list);
382*097b8a7cSJan Schmidt 	}
383*097b8a7cSJan Schmidt 	seq = btrfs_inc_tree_mod_seq(fs_info);
384bd989ba3SJan Schmidt 	spin_unlock(&fs_info->tree_mod_seq_lock);
385*097b8a7cSJan Schmidt 	tree_mod_log_write_unlock(fs_info);
386*097b8a7cSJan Schmidt 
387*097b8a7cSJan Schmidt 	return seq;
388bd989ba3SJan Schmidt }
389bd989ba3SJan Schmidt 
390bd989ba3SJan Schmidt void btrfs_put_tree_mod_seq(struct btrfs_fs_info *fs_info,
391bd989ba3SJan Schmidt 			    struct seq_list *elem)
392bd989ba3SJan Schmidt {
393bd989ba3SJan Schmidt 	struct rb_root *tm_root;
394bd989ba3SJan Schmidt 	struct rb_node *node;
395bd989ba3SJan Schmidt 	struct rb_node *next;
396bd989ba3SJan Schmidt 	struct seq_list *cur_elem;
397bd989ba3SJan Schmidt 	struct tree_mod_elem *tm;
398bd989ba3SJan Schmidt 	u64 min_seq = (u64)-1;
399bd989ba3SJan Schmidt 	u64 seq_putting = elem->seq;
400bd989ba3SJan Schmidt 
401bd989ba3SJan Schmidt 	if (!seq_putting)
402bd989ba3SJan Schmidt 		return;
403bd989ba3SJan Schmidt 
404bd989ba3SJan Schmidt 	spin_lock(&fs_info->tree_mod_seq_lock);
405bd989ba3SJan Schmidt 	list_del(&elem->list);
406*097b8a7cSJan Schmidt 	elem->seq = 0;
407bd989ba3SJan Schmidt 
408bd989ba3SJan Schmidt 	list_for_each_entry(cur_elem, &fs_info->tree_mod_seq_list, list) {
409*097b8a7cSJan Schmidt 		if (cur_elem->seq < min_seq) {
410bd989ba3SJan Schmidt 			if (seq_putting > cur_elem->seq) {
411bd989ba3SJan Schmidt 				/*
412bd989ba3SJan Schmidt 				 * blocker with lower sequence number exists, we
413bd989ba3SJan Schmidt 				 * cannot remove anything from the log
414bd989ba3SJan Schmidt 				 */
415*097b8a7cSJan Schmidt 				spin_unlock(&fs_info->tree_mod_seq_lock);
416*097b8a7cSJan Schmidt 				return;
417bd989ba3SJan Schmidt 			}
418bd989ba3SJan Schmidt 			min_seq = cur_elem->seq;
419bd989ba3SJan Schmidt 		}
420bd989ba3SJan Schmidt 	}
421*097b8a7cSJan Schmidt 	spin_unlock(&fs_info->tree_mod_seq_lock);
422*097b8a7cSJan Schmidt 
423*097b8a7cSJan Schmidt 	/*
424*097b8a7cSJan Schmidt 	 * we removed the lowest blocker from the blocker list, so there may be
425*097b8a7cSJan Schmidt 	 * more processible delayed refs.
426*097b8a7cSJan Schmidt 	 */
427*097b8a7cSJan Schmidt 	wake_up(&fs_info->tree_mod_seq_wait);
428bd989ba3SJan Schmidt 
429bd989ba3SJan Schmidt 	/*
430bd989ba3SJan Schmidt 	 * anything that's lower than the lowest existing (read: blocked)
431bd989ba3SJan Schmidt 	 * sequence number can be removed from the tree.
432bd989ba3SJan Schmidt 	 */
433*097b8a7cSJan Schmidt 	tree_mod_log_write_lock(fs_info);
434bd989ba3SJan Schmidt 	tm_root = &fs_info->tree_mod_log;
435bd989ba3SJan Schmidt 	for (node = rb_first(tm_root); node; node = next) {
436bd989ba3SJan Schmidt 		next = rb_next(node);
437bd989ba3SJan Schmidt 		tm = container_of(node, struct tree_mod_elem, node);
438*097b8a7cSJan Schmidt 		if (tm->seq > min_seq)
439bd989ba3SJan Schmidt 			continue;
440bd989ba3SJan Schmidt 		rb_erase(node, tm_root);
441bd989ba3SJan Schmidt 		kfree(tm);
442bd989ba3SJan Schmidt 	}
443*097b8a7cSJan Schmidt 	tree_mod_log_write_unlock(fs_info);
444bd989ba3SJan Schmidt }
445bd989ba3SJan Schmidt 
446bd989ba3SJan Schmidt /*
447bd989ba3SJan Schmidt  * key order of the log:
448bd989ba3SJan Schmidt  *       index -> sequence
449bd989ba3SJan Schmidt  *
450bd989ba3SJan Schmidt  * the index is the shifted logical of the *new* root node for root replace
451bd989ba3SJan Schmidt  * operations, or the shifted logical of the affected block for all other
452bd989ba3SJan Schmidt  * operations.
453bd989ba3SJan Schmidt  */
454bd989ba3SJan Schmidt static noinline int
455bd989ba3SJan Schmidt __tree_mod_log_insert(struct btrfs_fs_info *fs_info, struct tree_mod_elem *tm)
456bd989ba3SJan Schmidt {
457bd989ba3SJan Schmidt 	struct rb_root *tm_root;
458bd989ba3SJan Schmidt 	struct rb_node **new;
459bd989ba3SJan Schmidt 	struct rb_node *parent = NULL;
460bd989ba3SJan Schmidt 	struct tree_mod_elem *cur;
461bd989ba3SJan Schmidt 
462*097b8a7cSJan Schmidt 	BUG_ON(!tm || !tm->seq);
463bd989ba3SJan Schmidt 
464bd989ba3SJan Schmidt 	tm_root = &fs_info->tree_mod_log;
465bd989ba3SJan Schmidt 	new = &tm_root->rb_node;
466bd989ba3SJan Schmidt 	while (*new) {
467bd989ba3SJan Schmidt 		cur = container_of(*new, struct tree_mod_elem, node);
468bd989ba3SJan Schmidt 		parent = *new;
469bd989ba3SJan Schmidt 		if (cur->index < tm->index)
470bd989ba3SJan Schmidt 			new = &((*new)->rb_left);
471bd989ba3SJan Schmidt 		else if (cur->index > tm->index)
472bd989ba3SJan Schmidt 			new = &((*new)->rb_right);
473*097b8a7cSJan Schmidt 		else if (cur->seq < tm->seq)
474bd989ba3SJan Schmidt 			new = &((*new)->rb_left);
475*097b8a7cSJan Schmidt 		else if (cur->seq > tm->seq)
476bd989ba3SJan Schmidt 			new = &((*new)->rb_right);
477bd989ba3SJan Schmidt 		else {
478bd989ba3SJan Schmidt 			kfree(tm);
479*097b8a7cSJan Schmidt 			return -EEXIST;
480bd989ba3SJan Schmidt 		}
481bd989ba3SJan Schmidt 	}
482bd989ba3SJan Schmidt 
483bd989ba3SJan Schmidt 	rb_link_node(&tm->node, parent, new);
484bd989ba3SJan Schmidt 	rb_insert_color(&tm->node, tm_root);
485*097b8a7cSJan Schmidt 	return 0;
486bd989ba3SJan Schmidt }
487bd989ba3SJan Schmidt 
488*097b8a7cSJan Schmidt /*
489*097b8a7cSJan Schmidt  * Determines if logging can be omitted. Returns 1 if it can. Otherwise, it
490*097b8a7cSJan Schmidt  * returns zero with the tree_mod_log_lock acquired. The caller must hold
491*097b8a7cSJan Schmidt  * this until all tree mod log insertions are recorded in the rb tree and then
492*097b8a7cSJan Schmidt  * call tree_mod_log_write_unlock() to release.
493*097b8a7cSJan Schmidt  */
494e9b7fd4dSJan Schmidt static inline int tree_mod_dont_log(struct btrfs_fs_info *fs_info,
495e9b7fd4dSJan Schmidt 				    struct extent_buffer *eb) {
496e9b7fd4dSJan Schmidt 	smp_mb();
497e9b7fd4dSJan Schmidt 	if (list_empty(&(fs_info)->tree_mod_seq_list))
498e9b7fd4dSJan Schmidt 		return 1;
499*097b8a7cSJan Schmidt 	if (eb && btrfs_header_level(eb) == 0)
500e9b7fd4dSJan Schmidt 		return 1;
501*097b8a7cSJan Schmidt 
502*097b8a7cSJan Schmidt 	tree_mod_log_write_lock(fs_info);
503*097b8a7cSJan Schmidt 	if (list_empty(&fs_info->tree_mod_seq_list)) {
504*097b8a7cSJan Schmidt 		/*
505*097b8a7cSJan Schmidt 		 * someone emptied the list while we were waiting for the lock.
506*097b8a7cSJan Schmidt 		 * we must not add to the list when no blocker exists.
507*097b8a7cSJan Schmidt 		 */
508*097b8a7cSJan Schmidt 		tree_mod_log_write_unlock(fs_info);
509*097b8a7cSJan Schmidt 		return 1;
510*097b8a7cSJan Schmidt 	}
511*097b8a7cSJan Schmidt 
512e9b7fd4dSJan Schmidt 	return 0;
513e9b7fd4dSJan Schmidt }
514e9b7fd4dSJan Schmidt 
5153310c36eSJan Schmidt /*
516*097b8a7cSJan Schmidt  * This allocates memory and gets a tree modification sequence number.
5173310c36eSJan Schmidt  *
518*097b8a7cSJan Schmidt  * Returns <0 on error.
519*097b8a7cSJan Schmidt  * Returns >0 (the added sequence number) on success.
5203310c36eSJan Schmidt  */
521926dd8a6SJan Schmidt static inline int tree_mod_alloc(struct btrfs_fs_info *fs_info, gfp_t flags,
522bd989ba3SJan Schmidt 				 struct tree_mod_elem **tm_ret)
523bd989ba3SJan Schmidt {
524bd989ba3SJan Schmidt 	struct tree_mod_elem *tm;
525bd989ba3SJan Schmidt 
526*097b8a7cSJan Schmidt 	/*
527*097b8a7cSJan Schmidt 	 * once we switch from spin locks to something different, we should
528*097b8a7cSJan Schmidt 	 * honor the flags parameter here.
529*097b8a7cSJan Schmidt 	 */
530*097b8a7cSJan Schmidt 	tm = *tm_ret = kzalloc(sizeof(*tm), GFP_ATOMIC);
531bd989ba3SJan Schmidt 	if (!tm)
532bd989ba3SJan Schmidt 		return -ENOMEM;
533bd989ba3SJan Schmidt 
534*097b8a7cSJan Schmidt 	tm->seq = btrfs_inc_tree_mod_seq(fs_info);
535*097b8a7cSJan Schmidt 	return tm->seq;
536926dd8a6SJan Schmidt }
537bd989ba3SJan Schmidt 
538*097b8a7cSJan Schmidt static inline int
539*097b8a7cSJan Schmidt __tree_mod_log_insert_key(struct btrfs_fs_info *fs_info,
540bd989ba3SJan Schmidt 			  struct extent_buffer *eb, int slot,
541bd989ba3SJan Schmidt 			  enum mod_log_op op, gfp_t flags)
542bd989ba3SJan Schmidt {
543bd989ba3SJan Schmidt 	int ret;
544*097b8a7cSJan Schmidt 	struct tree_mod_elem *tm;
545bd989ba3SJan Schmidt 
546bd989ba3SJan Schmidt 	ret = tree_mod_alloc(fs_info, flags, &tm);
547*097b8a7cSJan Schmidt 	if (ret < 0)
548bd989ba3SJan Schmidt 		return ret;
549bd989ba3SJan Schmidt 
550bd989ba3SJan Schmidt 	tm->index = eb->start >> PAGE_CACHE_SHIFT;
551bd989ba3SJan Schmidt 	if (op != MOD_LOG_KEY_ADD) {
552bd989ba3SJan Schmidt 		btrfs_node_key(eb, &tm->key, slot);
553bd989ba3SJan Schmidt 		tm->blockptr = btrfs_node_blockptr(eb, slot);
554bd989ba3SJan Schmidt 	}
555bd989ba3SJan Schmidt 	tm->op = op;
556bd989ba3SJan Schmidt 	tm->slot = slot;
557bd989ba3SJan Schmidt 	tm->generation = btrfs_node_ptr_generation(eb, slot);
558bd989ba3SJan Schmidt 
559*097b8a7cSJan Schmidt 	return __tree_mod_log_insert(fs_info, tm);
560*097b8a7cSJan Schmidt }
561*097b8a7cSJan Schmidt 
562*097b8a7cSJan Schmidt static noinline int
563*097b8a7cSJan Schmidt tree_mod_log_insert_key_mask(struct btrfs_fs_info *fs_info,
564*097b8a7cSJan Schmidt 			     struct extent_buffer *eb, int slot,
565*097b8a7cSJan Schmidt 			     enum mod_log_op op, gfp_t flags)
566*097b8a7cSJan Schmidt {
567*097b8a7cSJan Schmidt 	int ret;
568*097b8a7cSJan Schmidt 
569*097b8a7cSJan Schmidt 	if (tree_mod_dont_log(fs_info, eb))
570*097b8a7cSJan Schmidt 		return 0;
571*097b8a7cSJan Schmidt 
572*097b8a7cSJan Schmidt 	ret = __tree_mod_log_insert_key(fs_info, eb, slot, op, flags);
573*097b8a7cSJan Schmidt 
574*097b8a7cSJan Schmidt 	tree_mod_log_write_unlock(fs_info);
5753310c36eSJan Schmidt 	return ret;
576bd989ba3SJan Schmidt }
577bd989ba3SJan Schmidt 
578bd989ba3SJan Schmidt static noinline int
579bd989ba3SJan Schmidt tree_mod_log_insert_key(struct btrfs_fs_info *fs_info, struct extent_buffer *eb,
580bd989ba3SJan Schmidt 			int slot, enum mod_log_op op)
581bd989ba3SJan Schmidt {
582bd989ba3SJan Schmidt 	return tree_mod_log_insert_key_mask(fs_info, eb, slot, op, GFP_NOFS);
583bd989ba3SJan Schmidt }
584bd989ba3SJan Schmidt 
585bd989ba3SJan Schmidt static noinline int
586*097b8a7cSJan Schmidt tree_mod_log_insert_key_locked(struct btrfs_fs_info *fs_info,
587*097b8a7cSJan Schmidt 			     struct extent_buffer *eb, int slot,
588*097b8a7cSJan Schmidt 			     enum mod_log_op op)
589*097b8a7cSJan Schmidt {
590*097b8a7cSJan Schmidt 	return __tree_mod_log_insert_key(fs_info, eb, slot, op, GFP_NOFS);
591*097b8a7cSJan Schmidt }
592*097b8a7cSJan Schmidt 
593*097b8a7cSJan Schmidt static noinline int
594bd989ba3SJan Schmidt tree_mod_log_insert_move(struct btrfs_fs_info *fs_info,
595bd989ba3SJan Schmidt 			 struct extent_buffer *eb, int dst_slot, int src_slot,
596bd989ba3SJan Schmidt 			 int nr_items, gfp_t flags)
597bd989ba3SJan Schmidt {
598bd989ba3SJan Schmidt 	struct tree_mod_elem *tm;
599bd989ba3SJan Schmidt 	int ret;
600bd989ba3SJan Schmidt 	int i;
601bd989ba3SJan Schmidt 
602f395694cSJan Schmidt 	if (tree_mod_dont_log(fs_info, eb))
603f395694cSJan Schmidt 		return 0;
604bd989ba3SJan Schmidt 
605bd989ba3SJan Schmidt 	for (i = 0; i + dst_slot < src_slot && i < nr_items; i++) {
606*097b8a7cSJan Schmidt 		ret = tree_mod_log_insert_key_locked(fs_info, eb, i + dst_slot,
607bd989ba3SJan Schmidt 					      MOD_LOG_KEY_REMOVE_WHILE_MOVING);
608bd989ba3SJan Schmidt 		BUG_ON(ret < 0);
609bd989ba3SJan Schmidt 	}
610bd989ba3SJan Schmidt 
611f395694cSJan Schmidt 	ret = tree_mod_alloc(fs_info, flags, &tm);
612*097b8a7cSJan Schmidt 	if (ret < 0)
613*097b8a7cSJan Schmidt 		goto out;
614f395694cSJan Schmidt 
615bd989ba3SJan Schmidt 	tm->index = eb->start >> PAGE_CACHE_SHIFT;
616bd989ba3SJan Schmidt 	tm->slot = src_slot;
617bd989ba3SJan Schmidt 	tm->move.dst_slot = dst_slot;
618bd989ba3SJan Schmidt 	tm->move.nr_items = nr_items;
619bd989ba3SJan Schmidt 	tm->op = MOD_LOG_MOVE_KEYS;
620bd989ba3SJan Schmidt 
6213310c36eSJan Schmidt 	ret = __tree_mod_log_insert(fs_info, tm);
622*097b8a7cSJan Schmidt out:
623*097b8a7cSJan Schmidt 	tree_mod_log_write_unlock(fs_info);
6243310c36eSJan Schmidt 	return ret;
625bd989ba3SJan Schmidt }
626bd989ba3SJan Schmidt 
627*097b8a7cSJan Schmidt static inline void
628*097b8a7cSJan Schmidt __tree_mod_log_free_eb(struct btrfs_fs_info *fs_info, struct extent_buffer *eb)
629*097b8a7cSJan Schmidt {
630*097b8a7cSJan Schmidt 	int i;
631*097b8a7cSJan Schmidt 	u32 nritems;
632*097b8a7cSJan Schmidt 	int ret;
633*097b8a7cSJan Schmidt 
634*097b8a7cSJan Schmidt 	nritems = btrfs_header_nritems(eb);
635*097b8a7cSJan Schmidt 	for (i = nritems - 1; i >= 0; i--) {
636*097b8a7cSJan Schmidt 		ret = tree_mod_log_insert_key_locked(fs_info, eb, i,
637*097b8a7cSJan Schmidt 					      MOD_LOG_KEY_REMOVE_WHILE_FREEING);
638*097b8a7cSJan Schmidt 		BUG_ON(ret < 0);
639*097b8a7cSJan Schmidt 	}
640*097b8a7cSJan Schmidt }
641*097b8a7cSJan Schmidt 
642bd989ba3SJan Schmidt static noinline int
643bd989ba3SJan Schmidt tree_mod_log_insert_root(struct btrfs_fs_info *fs_info,
644bd989ba3SJan Schmidt 			 struct extent_buffer *old_root,
645bd989ba3SJan Schmidt 			 struct extent_buffer *new_root, gfp_t flags)
646bd989ba3SJan Schmidt {
647bd989ba3SJan Schmidt 	struct tree_mod_elem *tm;
648bd989ba3SJan Schmidt 	int ret;
649bd989ba3SJan Schmidt 
650*097b8a7cSJan Schmidt 	if (tree_mod_dont_log(fs_info, NULL))
651*097b8a7cSJan Schmidt 		return 0;
652*097b8a7cSJan Schmidt 
653*097b8a7cSJan Schmidt 	__tree_mod_log_free_eb(fs_info, old_root);
654*097b8a7cSJan Schmidt 
655bd989ba3SJan Schmidt 	ret = tree_mod_alloc(fs_info, flags, &tm);
656*097b8a7cSJan Schmidt 	if (ret < 0)
657*097b8a7cSJan Schmidt 		goto out;
658bd989ba3SJan Schmidt 
659bd989ba3SJan Schmidt 	tm->index = new_root->start >> PAGE_CACHE_SHIFT;
660bd989ba3SJan Schmidt 	tm->old_root.logical = old_root->start;
661bd989ba3SJan Schmidt 	tm->old_root.level = btrfs_header_level(old_root);
662bd989ba3SJan Schmidt 	tm->generation = btrfs_header_generation(old_root);
663bd989ba3SJan Schmidt 	tm->op = MOD_LOG_ROOT_REPLACE;
664bd989ba3SJan Schmidt 
6653310c36eSJan Schmidt 	ret = __tree_mod_log_insert(fs_info, tm);
666*097b8a7cSJan Schmidt out:
667*097b8a7cSJan Schmidt 	tree_mod_log_write_unlock(fs_info);
6683310c36eSJan Schmidt 	return ret;
669bd989ba3SJan Schmidt }
670bd989ba3SJan Schmidt 
671bd989ba3SJan Schmidt static struct tree_mod_elem *
672bd989ba3SJan Schmidt __tree_mod_log_search(struct btrfs_fs_info *fs_info, u64 start, u64 min_seq,
673bd989ba3SJan Schmidt 		      int smallest)
674bd989ba3SJan Schmidt {
675bd989ba3SJan Schmidt 	struct rb_root *tm_root;
676bd989ba3SJan Schmidt 	struct rb_node *node;
677bd989ba3SJan Schmidt 	struct tree_mod_elem *cur = NULL;
678bd989ba3SJan Schmidt 	struct tree_mod_elem *found = NULL;
679bd989ba3SJan Schmidt 	u64 index = start >> PAGE_CACHE_SHIFT;
680bd989ba3SJan Schmidt 
681*097b8a7cSJan Schmidt 	tree_mod_log_read_lock(fs_info);
682bd989ba3SJan Schmidt 	tm_root = &fs_info->tree_mod_log;
683bd989ba3SJan Schmidt 	node = tm_root->rb_node;
684bd989ba3SJan Schmidt 	while (node) {
685bd989ba3SJan Schmidt 		cur = container_of(node, struct tree_mod_elem, node);
686bd989ba3SJan Schmidt 		if (cur->index < index) {
687bd989ba3SJan Schmidt 			node = node->rb_left;
688bd989ba3SJan Schmidt 		} else if (cur->index > index) {
689bd989ba3SJan Schmidt 			node = node->rb_right;
690*097b8a7cSJan Schmidt 		} else if (cur->seq < min_seq) {
691bd989ba3SJan Schmidt 			node = node->rb_left;
692bd989ba3SJan Schmidt 		} else if (!smallest) {
693bd989ba3SJan Schmidt 			/* we want the node with the highest seq */
694bd989ba3SJan Schmidt 			if (found)
695*097b8a7cSJan Schmidt 				BUG_ON(found->seq > cur->seq);
696bd989ba3SJan Schmidt 			found = cur;
697bd989ba3SJan Schmidt 			node = node->rb_left;
698*097b8a7cSJan Schmidt 		} else if (cur->seq > min_seq) {
699bd989ba3SJan Schmidt 			/* we want the node with the smallest seq */
700bd989ba3SJan Schmidt 			if (found)
701*097b8a7cSJan Schmidt 				BUG_ON(found->seq < cur->seq);
702bd989ba3SJan Schmidt 			found = cur;
703bd989ba3SJan Schmidt 			node = node->rb_right;
704bd989ba3SJan Schmidt 		} else {
705bd989ba3SJan Schmidt 			found = cur;
706bd989ba3SJan Schmidt 			break;
707bd989ba3SJan Schmidt 		}
708bd989ba3SJan Schmidt 	}
709*097b8a7cSJan Schmidt 	tree_mod_log_read_unlock(fs_info);
710bd989ba3SJan Schmidt 
711bd989ba3SJan Schmidt 	return found;
712bd989ba3SJan Schmidt }
713bd989ba3SJan Schmidt 
714bd989ba3SJan Schmidt /*
715bd989ba3SJan Schmidt  * this returns the element from the log with the smallest time sequence
716bd989ba3SJan Schmidt  * value that's in the log (the oldest log item). any element with a time
717bd989ba3SJan Schmidt  * sequence lower than min_seq will be ignored.
718bd989ba3SJan Schmidt  */
719bd989ba3SJan Schmidt static struct tree_mod_elem *
720bd989ba3SJan Schmidt tree_mod_log_search_oldest(struct btrfs_fs_info *fs_info, u64 start,
721bd989ba3SJan Schmidt 			   u64 min_seq)
722bd989ba3SJan Schmidt {
723bd989ba3SJan Schmidt 	return __tree_mod_log_search(fs_info, start, min_seq, 1);
724bd989ba3SJan Schmidt }
725bd989ba3SJan Schmidt 
726bd989ba3SJan Schmidt /*
727bd989ba3SJan Schmidt  * this returns the element from the log with the largest time sequence
728bd989ba3SJan Schmidt  * value that's in the log (the most recent log item). any element with
729bd989ba3SJan Schmidt  * a time sequence lower than min_seq will be ignored.
730bd989ba3SJan Schmidt  */
731bd989ba3SJan Schmidt static struct tree_mod_elem *
732bd989ba3SJan Schmidt tree_mod_log_search(struct btrfs_fs_info *fs_info, u64 start, u64 min_seq)
733bd989ba3SJan Schmidt {
734bd989ba3SJan Schmidt 	return __tree_mod_log_search(fs_info, start, min_seq, 0);
735bd989ba3SJan Schmidt }
736bd989ba3SJan Schmidt 
737*097b8a7cSJan Schmidt static noinline void
738bd989ba3SJan Schmidt tree_mod_log_eb_copy(struct btrfs_fs_info *fs_info, struct extent_buffer *dst,
739bd989ba3SJan Schmidt 		     struct extent_buffer *src, unsigned long dst_offset,
740bd989ba3SJan Schmidt 		     unsigned long src_offset, int nr_items)
741bd989ba3SJan Schmidt {
742bd989ba3SJan Schmidt 	int ret;
743bd989ba3SJan Schmidt 	int i;
744bd989ba3SJan Schmidt 
745e9b7fd4dSJan Schmidt 	if (tree_mod_dont_log(fs_info, NULL))
746bd989ba3SJan Schmidt 		return;
747bd989ba3SJan Schmidt 
748*097b8a7cSJan Schmidt 	if (btrfs_header_level(dst) == 0 && btrfs_header_level(src) == 0) {
749*097b8a7cSJan Schmidt 		tree_mod_log_write_unlock(fs_info);
750bd989ba3SJan Schmidt 		return;
751*097b8a7cSJan Schmidt 	}
752bd989ba3SJan Schmidt 
753bd989ba3SJan Schmidt 	for (i = 0; i < nr_items; i++) {
754*097b8a7cSJan Schmidt 		ret = tree_mod_log_insert_key_locked(fs_info, src,
755*097b8a7cSJan Schmidt 						     i + src_offset,
756bd989ba3SJan Schmidt 						     MOD_LOG_KEY_REMOVE);
757bd989ba3SJan Schmidt 		BUG_ON(ret < 0);
758*097b8a7cSJan Schmidt 		ret = tree_mod_log_insert_key_locked(fs_info, dst,
759*097b8a7cSJan Schmidt 						     i + dst_offset,
760bd989ba3SJan Schmidt 						     MOD_LOG_KEY_ADD);
761bd989ba3SJan Schmidt 		BUG_ON(ret < 0);
762bd989ba3SJan Schmidt 	}
763*097b8a7cSJan Schmidt 
764*097b8a7cSJan Schmidt 	tree_mod_log_write_unlock(fs_info);
765bd989ba3SJan Schmidt }
766bd989ba3SJan Schmidt 
767bd989ba3SJan Schmidt static inline void
768bd989ba3SJan Schmidt tree_mod_log_eb_move(struct btrfs_fs_info *fs_info, struct extent_buffer *dst,
769bd989ba3SJan Schmidt 		     int dst_offset, int src_offset, int nr_items)
770bd989ba3SJan Schmidt {
771bd989ba3SJan Schmidt 	int ret;
772bd989ba3SJan Schmidt 	ret = tree_mod_log_insert_move(fs_info, dst, dst_offset, src_offset,
773bd989ba3SJan Schmidt 				       nr_items, GFP_NOFS);
774bd989ba3SJan Schmidt 	BUG_ON(ret < 0);
775bd989ba3SJan Schmidt }
776bd989ba3SJan Schmidt 
777*097b8a7cSJan Schmidt static noinline void
778bd989ba3SJan Schmidt tree_mod_log_set_node_key(struct btrfs_fs_info *fs_info,
779bd989ba3SJan Schmidt 			  struct extent_buffer *eb,
780bd989ba3SJan Schmidt 			  struct btrfs_disk_key *disk_key, int slot, int atomic)
781bd989ba3SJan Schmidt {
782bd989ba3SJan Schmidt 	int ret;
783bd989ba3SJan Schmidt 
784bd989ba3SJan Schmidt 	ret = tree_mod_log_insert_key_mask(fs_info, eb, slot,
785bd989ba3SJan Schmidt 					   MOD_LOG_KEY_REPLACE,
786bd989ba3SJan Schmidt 					   atomic ? GFP_ATOMIC : GFP_NOFS);
787bd989ba3SJan Schmidt 	BUG_ON(ret < 0);
788bd989ba3SJan Schmidt }
789bd989ba3SJan Schmidt 
790*097b8a7cSJan Schmidt static noinline void
791*097b8a7cSJan Schmidt tree_mod_log_free_eb(struct btrfs_fs_info *fs_info, struct extent_buffer *eb)
792bd989ba3SJan Schmidt {
793e9b7fd4dSJan Schmidt 	if (tree_mod_dont_log(fs_info, eb))
794bd989ba3SJan Schmidt 		return;
795bd989ba3SJan Schmidt 
796*097b8a7cSJan Schmidt 	__tree_mod_log_free_eb(fs_info, eb);
797*097b8a7cSJan Schmidt 
798*097b8a7cSJan Schmidt 	tree_mod_log_write_unlock(fs_info);
799bd989ba3SJan Schmidt }
800bd989ba3SJan Schmidt 
801*097b8a7cSJan Schmidt static noinline void
802bd989ba3SJan Schmidt tree_mod_log_set_root_pointer(struct btrfs_root *root,
803bd989ba3SJan Schmidt 			      struct extent_buffer *new_root_node)
804bd989ba3SJan Schmidt {
805bd989ba3SJan Schmidt 	int ret;
806bd989ba3SJan Schmidt 	ret = tree_mod_log_insert_root(root->fs_info, root->node,
807bd989ba3SJan Schmidt 				       new_root_node, GFP_NOFS);
808bd989ba3SJan Schmidt 	BUG_ON(ret < 0);
809bd989ba3SJan Schmidt }
810bd989ba3SJan Schmidt 
811d352ac68SChris Mason /*
8125d4f98a2SYan Zheng  * check if the tree block can be shared by multiple trees
8135d4f98a2SYan Zheng  */
8145d4f98a2SYan Zheng int btrfs_block_can_be_shared(struct btrfs_root *root,
8155d4f98a2SYan Zheng 			      struct extent_buffer *buf)
8165d4f98a2SYan Zheng {
8175d4f98a2SYan Zheng 	/*
8185d4f98a2SYan Zheng 	 * Tree blocks not in refernece counted trees and tree roots
8195d4f98a2SYan Zheng 	 * are never shared. If a block was allocated after the last
8205d4f98a2SYan Zheng 	 * snapshot and the block was not allocated by tree relocation,
8215d4f98a2SYan Zheng 	 * we know the block is not shared.
8225d4f98a2SYan Zheng 	 */
8235d4f98a2SYan Zheng 	if (root->ref_cows &&
8245d4f98a2SYan Zheng 	    buf != root->node && buf != root->commit_root &&
8255d4f98a2SYan Zheng 	    (btrfs_header_generation(buf) <=
8265d4f98a2SYan Zheng 	     btrfs_root_last_snapshot(&root->root_item) ||
8275d4f98a2SYan Zheng 	     btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)))
8285d4f98a2SYan Zheng 		return 1;
8295d4f98a2SYan Zheng #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
8305d4f98a2SYan Zheng 	if (root->ref_cows &&
8315d4f98a2SYan Zheng 	    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
8325d4f98a2SYan Zheng 		return 1;
8335d4f98a2SYan Zheng #endif
8345d4f98a2SYan Zheng 	return 0;
8355d4f98a2SYan Zheng }
8365d4f98a2SYan Zheng 
8375d4f98a2SYan Zheng static noinline int update_ref_for_cow(struct btrfs_trans_handle *trans,
8385d4f98a2SYan Zheng 				       struct btrfs_root *root,
8395d4f98a2SYan Zheng 				       struct extent_buffer *buf,
840f0486c68SYan, Zheng 				       struct extent_buffer *cow,
841f0486c68SYan, Zheng 				       int *last_ref)
8425d4f98a2SYan Zheng {
8435d4f98a2SYan Zheng 	u64 refs;
8445d4f98a2SYan Zheng 	u64 owner;
8455d4f98a2SYan Zheng 	u64 flags;
8465d4f98a2SYan Zheng 	u64 new_flags = 0;
8475d4f98a2SYan Zheng 	int ret;
8485d4f98a2SYan Zheng 
8495d4f98a2SYan Zheng 	/*
8505d4f98a2SYan Zheng 	 * Backrefs update rules:
8515d4f98a2SYan Zheng 	 *
8525d4f98a2SYan Zheng 	 * Always use full backrefs for extent pointers in tree block
8535d4f98a2SYan Zheng 	 * allocated by tree relocation.
8545d4f98a2SYan Zheng 	 *
8555d4f98a2SYan Zheng 	 * If a shared tree block is no longer referenced by its owner
8565d4f98a2SYan Zheng 	 * tree (btrfs_header_owner(buf) == root->root_key.objectid),
8575d4f98a2SYan Zheng 	 * use full backrefs for extent pointers in tree block.
8585d4f98a2SYan Zheng 	 *
8595d4f98a2SYan Zheng 	 * If a tree block is been relocating
8605d4f98a2SYan Zheng 	 * (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID),
8615d4f98a2SYan Zheng 	 * use full backrefs for extent pointers in tree block.
8625d4f98a2SYan Zheng 	 * The reason for this is some operations (such as drop tree)
8635d4f98a2SYan Zheng 	 * are only allowed for blocks use full backrefs.
8645d4f98a2SYan Zheng 	 */
8655d4f98a2SYan Zheng 
8665d4f98a2SYan Zheng 	if (btrfs_block_can_be_shared(root, buf)) {
8675d4f98a2SYan Zheng 		ret = btrfs_lookup_extent_info(trans, root, buf->start,
8685d4f98a2SYan Zheng 					       buf->len, &refs, &flags);
869be1a5564SMark Fasheh 		if (ret)
870be1a5564SMark Fasheh 			return ret;
871e5df9573SMark Fasheh 		if (refs == 0) {
872e5df9573SMark Fasheh 			ret = -EROFS;
873e5df9573SMark Fasheh 			btrfs_std_error(root->fs_info, ret);
874e5df9573SMark Fasheh 			return ret;
875e5df9573SMark Fasheh 		}
8765d4f98a2SYan Zheng 	} else {
8775d4f98a2SYan Zheng 		refs = 1;
8785d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
8795d4f98a2SYan Zheng 		    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
8805d4f98a2SYan Zheng 			flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
8815d4f98a2SYan Zheng 		else
8825d4f98a2SYan Zheng 			flags = 0;
8835d4f98a2SYan Zheng 	}
8845d4f98a2SYan Zheng 
8855d4f98a2SYan Zheng 	owner = btrfs_header_owner(buf);
8865d4f98a2SYan Zheng 	BUG_ON(owner == BTRFS_TREE_RELOC_OBJECTID &&
8875d4f98a2SYan Zheng 	       !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
8885d4f98a2SYan Zheng 
8895d4f98a2SYan Zheng 	if (refs > 1) {
8905d4f98a2SYan Zheng 		if ((owner == root->root_key.objectid ||
8915d4f98a2SYan Zheng 		     root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) &&
8925d4f98a2SYan Zheng 		    !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)) {
89366d7e7f0SArne Jansen 			ret = btrfs_inc_ref(trans, root, buf, 1, 1);
89479787eaaSJeff Mahoney 			BUG_ON(ret); /* -ENOMEM */
8955d4f98a2SYan Zheng 
8965d4f98a2SYan Zheng 			if (root->root_key.objectid ==
8975d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID) {
89866d7e7f0SArne Jansen 				ret = btrfs_dec_ref(trans, root, buf, 0, 1);
89979787eaaSJeff Mahoney 				BUG_ON(ret); /* -ENOMEM */
90066d7e7f0SArne Jansen 				ret = btrfs_inc_ref(trans, root, cow, 1, 1);
90179787eaaSJeff Mahoney 				BUG_ON(ret); /* -ENOMEM */
9025d4f98a2SYan Zheng 			}
9035d4f98a2SYan Zheng 			new_flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
9045d4f98a2SYan Zheng 		} else {
9055d4f98a2SYan Zheng 
9065d4f98a2SYan Zheng 			if (root->root_key.objectid ==
9075d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID)
90866d7e7f0SArne Jansen 				ret = btrfs_inc_ref(trans, root, cow, 1, 1);
9095d4f98a2SYan Zheng 			else
91066d7e7f0SArne Jansen 				ret = btrfs_inc_ref(trans, root, cow, 0, 1);
91179787eaaSJeff Mahoney 			BUG_ON(ret); /* -ENOMEM */
9125d4f98a2SYan Zheng 		}
9135d4f98a2SYan Zheng 		if (new_flags != 0) {
9145d4f98a2SYan Zheng 			ret = btrfs_set_disk_extent_flags(trans, root,
9155d4f98a2SYan Zheng 							  buf->start,
9165d4f98a2SYan Zheng 							  buf->len,
9175d4f98a2SYan Zheng 							  new_flags, 0);
918be1a5564SMark Fasheh 			if (ret)
919be1a5564SMark Fasheh 				return ret;
9205d4f98a2SYan Zheng 		}
9215d4f98a2SYan Zheng 	} else {
9225d4f98a2SYan Zheng 		if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
9235d4f98a2SYan Zheng 			if (root->root_key.objectid ==
9245d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID)
92566d7e7f0SArne Jansen 				ret = btrfs_inc_ref(trans, root, cow, 1, 1);
9265d4f98a2SYan Zheng 			else
92766d7e7f0SArne Jansen 				ret = btrfs_inc_ref(trans, root, cow, 0, 1);
92879787eaaSJeff Mahoney 			BUG_ON(ret); /* -ENOMEM */
92966d7e7f0SArne Jansen 			ret = btrfs_dec_ref(trans, root, buf, 1, 1);
93079787eaaSJeff Mahoney 			BUG_ON(ret); /* -ENOMEM */
9315d4f98a2SYan Zheng 		}
932f230475eSJan Schmidt 		/*
933f230475eSJan Schmidt 		 * don't log freeing in case we're freeing the root node, this
934f230475eSJan Schmidt 		 * is done by tree_mod_log_set_root_pointer later
935f230475eSJan Schmidt 		 */
936f230475eSJan Schmidt 		if (buf != root->node && btrfs_header_level(buf) != 0)
937f230475eSJan Schmidt 			tree_mod_log_free_eb(root->fs_info, buf);
9385d4f98a2SYan Zheng 		clean_tree_block(trans, root, buf);
939f0486c68SYan, Zheng 		*last_ref = 1;
9405d4f98a2SYan Zheng 	}
9415d4f98a2SYan Zheng 	return 0;
9425d4f98a2SYan Zheng }
9435d4f98a2SYan Zheng 
9445d4f98a2SYan Zheng /*
945d397712bSChris Mason  * does the dirty work in cow of a single block.  The parent block (if
946d397712bSChris Mason  * supplied) is updated to point to the new cow copy.  The new buffer is marked
947d397712bSChris Mason  * dirty and returned locked.  If you modify the block it needs to be marked
948d397712bSChris Mason  * dirty again.
949d352ac68SChris Mason  *
950d352ac68SChris Mason  * search_start -- an allocation hint for the new block
951d352ac68SChris Mason  *
952d397712bSChris Mason  * empty_size -- a hint that you plan on doing more cow.  This is the size in
953d397712bSChris Mason  * bytes the allocator should try to find free next to the block it returns.
954d397712bSChris Mason  * This is just a hint and may be ignored by the allocator.
955d352ac68SChris Mason  */
956d397712bSChris Mason static noinline int __btrfs_cow_block(struct btrfs_trans_handle *trans,
9575f39d397SChris Mason 			     struct btrfs_root *root,
9585f39d397SChris Mason 			     struct extent_buffer *buf,
9595f39d397SChris Mason 			     struct extent_buffer *parent, int parent_slot,
9605f39d397SChris Mason 			     struct extent_buffer **cow_ret,
9619fa8cfe7SChris Mason 			     u64 search_start, u64 empty_size)
9626702ed49SChris Mason {
9635d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
9645f39d397SChris Mason 	struct extent_buffer *cow;
965be1a5564SMark Fasheh 	int level, ret;
966f0486c68SYan, Zheng 	int last_ref = 0;
967925baeddSChris Mason 	int unlock_orig = 0;
9685d4f98a2SYan Zheng 	u64 parent_start;
9696702ed49SChris Mason 
970925baeddSChris Mason 	if (*cow_ret == buf)
971925baeddSChris Mason 		unlock_orig = 1;
972925baeddSChris Mason 
973b9447ef8SChris Mason 	btrfs_assert_tree_locked(buf);
974925baeddSChris Mason 
9757bb86316SChris Mason 	WARN_ON(root->ref_cows && trans->transid !=
9767bb86316SChris Mason 		root->fs_info->running_transaction->transid);
9776702ed49SChris Mason 	WARN_ON(root->ref_cows && trans->transid != root->last_trans);
9785f39d397SChris Mason 
9797bb86316SChris Mason 	level = btrfs_header_level(buf);
98031840ae1SZheng Yan 
9815d4f98a2SYan Zheng 	if (level == 0)
9825d4f98a2SYan Zheng 		btrfs_item_key(buf, &disk_key, 0);
9835d4f98a2SYan Zheng 	else
9845d4f98a2SYan Zheng 		btrfs_node_key(buf, &disk_key, 0);
9855d4f98a2SYan Zheng 
9865d4f98a2SYan Zheng 	if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) {
9875d4f98a2SYan Zheng 		if (parent)
9885d4f98a2SYan Zheng 			parent_start = parent->start;
9895d4f98a2SYan Zheng 		else
9905d4f98a2SYan Zheng 			parent_start = 0;
9915d4f98a2SYan Zheng 	} else
9925d4f98a2SYan Zheng 		parent_start = 0;
9935d4f98a2SYan Zheng 
9945d4f98a2SYan Zheng 	cow = btrfs_alloc_free_block(trans, root, buf->len, parent_start,
9955d4f98a2SYan Zheng 				     root->root_key.objectid, &disk_key,
9965581a51aSJan Schmidt 				     level, search_start, empty_size);
9976702ed49SChris Mason 	if (IS_ERR(cow))
9986702ed49SChris Mason 		return PTR_ERR(cow);
9996702ed49SChris Mason 
1000b4ce94deSChris Mason 	/* cow is set to blocking by btrfs_init_new_buffer */
1001b4ce94deSChris Mason 
10025f39d397SChris Mason 	copy_extent_buffer(cow, buf, 0, 0, cow->len);
1003db94535dSChris Mason 	btrfs_set_header_bytenr(cow, cow->start);
10045f39d397SChris Mason 	btrfs_set_header_generation(cow, trans->transid);
10055d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
10065d4f98a2SYan Zheng 	btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
10075d4f98a2SYan Zheng 				     BTRFS_HEADER_FLAG_RELOC);
10085d4f98a2SYan Zheng 	if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
10095d4f98a2SYan Zheng 		btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
10105d4f98a2SYan Zheng 	else
10115f39d397SChris Mason 		btrfs_set_header_owner(cow, root->root_key.objectid);
10126702ed49SChris Mason 
10132b82032cSYan Zheng 	write_extent_buffer(cow, root->fs_info->fsid,
10142b82032cSYan Zheng 			    (unsigned long)btrfs_header_fsid(cow),
10152b82032cSYan Zheng 			    BTRFS_FSID_SIZE);
10162b82032cSYan Zheng 
1017be1a5564SMark Fasheh 	ret = update_ref_for_cow(trans, root, buf, cow, &last_ref);
1018b68dc2a9SMark Fasheh 	if (ret) {
101979787eaaSJeff Mahoney 		btrfs_abort_transaction(trans, root, ret);
1020b68dc2a9SMark Fasheh 		return ret;
1021b68dc2a9SMark Fasheh 	}
10221a40e23bSZheng Yan 
10233fd0a558SYan, Zheng 	if (root->ref_cows)
10243fd0a558SYan, Zheng 		btrfs_reloc_cow_block(trans, root, buf, cow);
10253fd0a558SYan, Zheng 
10266702ed49SChris Mason 	if (buf == root->node) {
1027925baeddSChris Mason 		WARN_ON(parent && parent != buf);
10285d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
10295d4f98a2SYan Zheng 		    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
10305d4f98a2SYan Zheng 			parent_start = buf->start;
10315d4f98a2SYan Zheng 		else
10325d4f98a2SYan Zheng 			parent_start = 0;
1033925baeddSChris Mason 
10345f39d397SChris Mason 		extent_buffer_get(cow);
1035f230475eSJan Schmidt 		tree_mod_log_set_root_pointer(root, cow);
1036240f62c8SChris Mason 		rcu_assign_pointer(root->node, cow);
1037925baeddSChris Mason 
1038f0486c68SYan, Zheng 		btrfs_free_tree_block(trans, root, buf, parent_start,
10395581a51aSJan Schmidt 				      last_ref);
10405f39d397SChris Mason 		free_extent_buffer(buf);
10410b86a832SChris Mason 		add_root_to_dirty_list(root);
10426702ed49SChris Mason 	} else {
10435d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
10445d4f98a2SYan Zheng 			parent_start = parent->start;
10455d4f98a2SYan Zheng 		else
10465d4f98a2SYan Zheng 			parent_start = 0;
10475d4f98a2SYan Zheng 
10485d4f98a2SYan Zheng 		WARN_ON(trans->transid != btrfs_header_generation(parent));
1049f230475eSJan Schmidt 		tree_mod_log_insert_key(root->fs_info, parent, parent_slot,
1050f230475eSJan Schmidt 					MOD_LOG_KEY_REPLACE);
10515f39d397SChris Mason 		btrfs_set_node_blockptr(parent, parent_slot,
1052db94535dSChris Mason 					cow->start);
105374493f7aSChris Mason 		btrfs_set_node_ptr_generation(parent, parent_slot,
105474493f7aSChris Mason 					      trans->transid);
10556702ed49SChris Mason 		btrfs_mark_buffer_dirty(parent);
1056f0486c68SYan, Zheng 		btrfs_free_tree_block(trans, root, buf, parent_start,
10575581a51aSJan Schmidt 				      last_ref);
10586702ed49SChris Mason 	}
1059925baeddSChris Mason 	if (unlock_orig)
1060925baeddSChris Mason 		btrfs_tree_unlock(buf);
10613083ee2eSJosef Bacik 	free_extent_buffer_stale(buf);
10626702ed49SChris Mason 	btrfs_mark_buffer_dirty(cow);
10636702ed49SChris Mason 	*cow_ret = cow;
10646702ed49SChris Mason 	return 0;
10656702ed49SChris Mason }
10666702ed49SChris Mason 
10675d9e75c4SJan Schmidt /*
10685d9e75c4SJan Schmidt  * returns the logical address of the oldest predecessor of the given root.
10695d9e75c4SJan Schmidt  * entries older than time_seq are ignored.
10705d9e75c4SJan Schmidt  */
10715d9e75c4SJan Schmidt static struct tree_mod_elem *
10725d9e75c4SJan Schmidt __tree_mod_log_oldest_root(struct btrfs_fs_info *fs_info,
10735d9e75c4SJan Schmidt 			   struct btrfs_root *root, u64 time_seq)
10745d9e75c4SJan Schmidt {
10755d9e75c4SJan Schmidt 	struct tree_mod_elem *tm;
10765d9e75c4SJan Schmidt 	struct tree_mod_elem *found = NULL;
10775d9e75c4SJan Schmidt 	u64 root_logical = root->node->start;
10785d9e75c4SJan Schmidt 	int looped = 0;
10795d9e75c4SJan Schmidt 
10805d9e75c4SJan Schmidt 	if (!time_seq)
10815d9e75c4SJan Schmidt 		return 0;
10825d9e75c4SJan Schmidt 
10835d9e75c4SJan Schmidt 	/*
10845d9e75c4SJan Schmidt 	 * the very last operation that's logged for a root is the replacement
10855d9e75c4SJan Schmidt 	 * operation (if it is replaced at all). this has the index of the *new*
10865d9e75c4SJan Schmidt 	 * root, making it the very first operation that's logged for this root.
10875d9e75c4SJan Schmidt 	 */
10885d9e75c4SJan Schmidt 	while (1) {
10895d9e75c4SJan Schmidt 		tm = tree_mod_log_search_oldest(fs_info, root_logical,
10905d9e75c4SJan Schmidt 						time_seq);
10915d9e75c4SJan Schmidt 		if (!looped && !tm)
10925d9e75c4SJan Schmidt 			return 0;
10935d9e75c4SJan Schmidt 		/*
109428da9fb4SJan Schmidt 		 * if there are no tree operation for the oldest root, we simply
109528da9fb4SJan Schmidt 		 * return it. this should only happen if that (old) root is at
109628da9fb4SJan Schmidt 		 * level 0.
10975d9e75c4SJan Schmidt 		 */
109828da9fb4SJan Schmidt 		if (!tm)
109928da9fb4SJan Schmidt 			break;
11005d9e75c4SJan Schmidt 
110128da9fb4SJan Schmidt 		/*
110228da9fb4SJan Schmidt 		 * if there's an operation that's not a root replacement, we
110328da9fb4SJan Schmidt 		 * found the oldest version of our root. normally, we'll find a
110428da9fb4SJan Schmidt 		 * MOD_LOG_KEY_REMOVE_WHILE_FREEING operation here.
110528da9fb4SJan Schmidt 		 */
11065d9e75c4SJan Schmidt 		if (tm->op != MOD_LOG_ROOT_REPLACE)
11075d9e75c4SJan Schmidt 			break;
11085d9e75c4SJan Schmidt 
11095d9e75c4SJan Schmidt 		found = tm;
11105d9e75c4SJan Schmidt 		root_logical = tm->old_root.logical;
11115d9e75c4SJan Schmidt 		BUG_ON(root_logical == root->node->start);
11125d9e75c4SJan Schmidt 		looped = 1;
11135d9e75c4SJan Schmidt 	}
11145d9e75c4SJan Schmidt 
1115a95236d9SJan Schmidt 	/* if there's no old root to return, return what we found instead */
1116a95236d9SJan Schmidt 	if (!found)
1117a95236d9SJan Schmidt 		found = tm;
1118a95236d9SJan Schmidt 
11195d9e75c4SJan Schmidt 	return found;
11205d9e75c4SJan Schmidt }
11215d9e75c4SJan Schmidt 
11225d9e75c4SJan Schmidt /*
11235d9e75c4SJan Schmidt  * tm is a pointer to the first operation to rewind within eb. then, all
11245d9e75c4SJan Schmidt  * previous operations will be rewinded (until we reach something older than
11255d9e75c4SJan Schmidt  * time_seq).
11265d9e75c4SJan Schmidt  */
11275d9e75c4SJan Schmidt static void
11285d9e75c4SJan Schmidt __tree_mod_log_rewind(struct extent_buffer *eb, u64 time_seq,
11295d9e75c4SJan Schmidt 		      struct tree_mod_elem *first_tm)
11305d9e75c4SJan Schmidt {
11315d9e75c4SJan Schmidt 	u32 n;
11325d9e75c4SJan Schmidt 	struct rb_node *next;
11335d9e75c4SJan Schmidt 	struct tree_mod_elem *tm = first_tm;
11345d9e75c4SJan Schmidt 	unsigned long o_dst;
11355d9e75c4SJan Schmidt 	unsigned long o_src;
11365d9e75c4SJan Schmidt 	unsigned long p_size = sizeof(struct btrfs_key_ptr);
11375d9e75c4SJan Schmidt 
11385d9e75c4SJan Schmidt 	n = btrfs_header_nritems(eb);
1139*097b8a7cSJan Schmidt 	while (tm && tm->seq >= time_seq) {
11405d9e75c4SJan Schmidt 		/*
11415d9e75c4SJan Schmidt 		 * all the operations are recorded with the operator used for
11425d9e75c4SJan Schmidt 		 * the modification. as we're going backwards, we do the
11435d9e75c4SJan Schmidt 		 * opposite of each operation here.
11445d9e75c4SJan Schmidt 		 */
11455d9e75c4SJan Schmidt 		switch (tm->op) {
11465d9e75c4SJan Schmidt 		case MOD_LOG_KEY_REMOVE_WHILE_FREEING:
11475d9e75c4SJan Schmidt 			BUG_ON(tm->slot < n);
11485d9e75c4SJan Schmidt 		case MOD_LOG_KEY_REMOVE_WHILE_MOVING:
11495d9e75c4SJan Schmidt 		case MOD_LOG_KEY_REMOVE:
11505d9e75c4SJan Schmidt 			btrfs_set_node_key(eb, &tm->key, tm->slot);
11515d9e75c4SJan Schmidt 			btrfs_set_node_blockptr(eb, tm->slot, tm->blockptr);
11525d9e75c4SJan Schmidt 			btrfs_set_node_ptr_generation(eb, tm->slot,
11535d9e75c4SJan Schmidt 						      tm->generation);
11545d9e75c4SJan Schmidt 			n++;
11555d9e75c4SJan Schmidt 			break;
11565d9e75c4SJan Schmidt 		case MOD_LOG_KEY_REPLACE:
11575d9e75c4SJan Schmidt 			BUG_ON(tm->slot >= n);
11585d9e75c4SJan Schmidt 			btrfs_set_node_key(eb, &tm->key, tm->slot);
11595d9e75c4SJan Schmidt 			btrfs_set_node_blockptr(eb, tm->slot, tm->blockptr);
11605d9e75c4SJan Schmidt 			btrfs_set_node_ptr_generation(eb, tm->slot,
11615d9e75c4SJan Schmidt 						      tm->generation);
11625d9e75c4SJan Schmidt 			break;
11635d9e75c4SJan Schmidt 		case MOD_LOG_KEY_ADD:
116419956c7eSJan Schmidt 			/* if a move operation is needed it's in the log */
11655d9e75c4SJan Schmidt 			n--;
11665d9e75c4SJan Schmidt 			break;
11675d9e75c4SJan Schmidt 		case MOD_LOG_MOVE_KEYS:
1168c3193108SJan Schmidt 			o_dst = btrfs_node_key_ptr_offset(tm->slot);
1169c3193108SJan Schmidt 			o_src = btrfs_node_key_ptr_offset(tm->move.dst_slot);
1170c3193108SJan Schmidt 			memmove_extent_buffer(eb, o_dst, o_src,
11715d9e75c4SJan Schmidt 					      tm->move.nr_items * p_size);
11725d9e75c4SJan Schmidt 			break;
11735d9e75c4SJan Schmidt 		case MOD_LOG_ROOT_REPLACE:
11745d9e75c4SJan Schmidt 			/*
11755d9e75c4SJan Schmidt 			 * this operation is special. for roots, this must be
11765d9e75c4SJan Schmidt 			 * handled explicitly before rewinding.
11775d9e75c4SJan Schmidt 			 * for non-roots, this operation may exist if the node
11785d9e75c4SJan Schmidt 			 * was a root: root A -> child B; then A gets empty and
11795d9e75c4SJan Schmidt 			 * B is promoted to the new root. in the mod log, we'll
11805d9e75c4SJan Schmidt 			 * have a root-replace operation for B, a tree block
11815d9e75c4SJan Schmidt 			 * that is no root. we simply ignore that operation.
11825d9e75c4SJan Schmidt 			 */
11835d9e75c4SJan Schmidt 			break;
11845d9e75c4SJan Schmidt 		}
11855d9e75c4SJan Schmidt 		next = rb_next(&tm->node);
11865d9e75c4SJan Schmidt 		if (!next)
11875d9e75c4SJan Schmidt 			break;
11885d9e75c4SJan Schmidt 		tm = container_of(next, struct tree_mod_elem, node);
11895d9e75c4SJan Schmidt 		if (tm->index != first_tm->index)
11905d9e75c4SJan Schmidt 			break;
11915d9e75c4SJan Schmidt 	}
11925d9e75c4SJan Schmidt 	btrfs_set_header_nritems(eb, n);
11935d9e75c4SJan Schmidt }
11945d9e75c4SJan Schmidt 
11955d9e75c4SJan Schmidt static struct extent_buffer *
11965d9e75c4SJan Schmidt tree_mod_log_rewind(struct btrfs_fs_info *fs_info, struct extent_buffer *eb,
11975d9e75c4SJan Schmidt 		    u64 time_seq)
11985d9e75c4SJan Schmidt {
11995d9e75c4SJan Schmidt 	struct extent_buffer *eb_rewin;
12005d9e75c4SJan Schmidt 	struct tree_mod_elem *tm;
12015d9e75c4SJan Schmidt 
12025d9e75c4SJan Schmidt 	if (!time_seq)
12035d9e75c4SJan Schmidt 		return eb;
12045d9e75c4SJan Schmidt 
12055d9e75c4SJan Schmidt 	if (btrfs_header_level(eb) == 0)
12065d9e75c4SJan Schmidt 		return eb;
12075d9e75c4SJan Schmidt 
12085d9e75c4SJan Schmidt 	tm = tree_mod_log_search(fs_info, eb->start, time_seq);
12095d9e75c4SJan Schmidt 	if (!tm)
12105d9e75c4SJan Schmidt 		return eb;
12115d9e75c4SJan Schmidt 
12125d9e75c4SJan Schmidt 	if (tm->op == MOD_LOG_KEY_REMOVE_WHILE_FREEING) {
12135d9e75c4SJan Schmidt 		BUG_ON(tm->slot != 0);
12145d9e75c4SJan Schmidt 		eb_rewin = alloc_dummy_extent_buffer(eb->start,
12155d9e75c4SJan Schmidt 						fs_info->tree_root->nodesize);
12165d9e75c4SJan Schmidt 		BUG_ON(!eb_rewin);
12175d9e75c4SJan Schmidt 		btrfs_set_header_bytenr(eb_rewin, eb->start);
12185d9e75c4SJan Schmidt 		btrfs_set_header_backref_rev(eb_rewin,
12195d9e75c4SJan Schmidt 					     btrfs_header_backref_rev(eb));
12205d9e75c4SJan Schmidt 		btrfs_set_header_owner(eb_rewin, btrfs_header_owner(eb));
1221c3193108SJan Schmidt 		btrfs_set_header_level(eb_rewin, btrfs_header_level(eb));
12225d9e75c4SJan Schmidt 	} else {
12235d9e75c4SJan Schmidt 		eb_rewin = btrfs_clone_extent_buffer(eb);
12245d9e75c4SJan Schmidt 		BUG_ON(!eb_rewin);
12255d9e75c4SJan Schmidt 	}
12265d9e75c4SJan Schmidt 
12275d9e75c4SJan Schmidt 	extent_buffer_get(eb_rewin);
12285d9e75c4SJan Schmidt 	free_extent_buffer(eb);
12295d9e75c4SJan Schmidt 
12305d9e75c4SJan Schmidt 	__tree_mod_log_rewind(eb_rewin, time_seq, tm);
12315d9e75c4SJan Schmidt 
12325d9e75c4SJan Schmidt 	return eb_rewin;
12335d9e75c4SJan Schmidt }
12345d9e75c4SJan Schmidt 
12358ba97a15SJan Schmidt /*
12368ba97a15SJan Schmidt  * get_old_root() rewinds the state of @root's root node to the given @time_seq
12378ba97a15SJan Schmidt  * value. If there are no changes, the current root->root_node is returned. If
12388ba97a15SJan Schmidt  * anything changed in between, there's a fresh buffer allocated on which the
12398ba97a15SJan Schmidt  * rewind operations are done. In any case, the returned buffer is read locked.
12408ba97a15SJan Schmidt  * Returns NULL on error (with no locks held).
12418ba97a15SJan Schmidt  */
12425d9e75c4SJan Schmidt static inline struct extent_buffer *
12435d9e75c4SJan Schmidt get_old_root(struct btrfs_root *root, u64 time_seq)
12445d9e75c4SJan Schmidt {
12455d9e75c4SJan Schmidt 	struct tree_mod_elem *tm;
12465d9e75c4SJan Schmidt 	struct extent_buffer *eb;
1247a95236d9SJan Schmidt 	struct tree_mod_root *old_root = NULL;
12484325edd0SChris Mason 	u64 old_generation = 0;
1249a95236d9SJan Schmidt 	u64 logical;
12505d9e75c4SJan Schmidt 
12518ba97a15SJan Schmidt 	eb = btrfs_read_lock_root_node(root);
12525d9e75c4SJan Schmidt 	tm = __tree_mod_log_oldest_root(root->fs_info, root, time_seq);
12535d9e75c4SJan Schmidt 	if (!tm)
12545d9e75c4SJan Schmidt 		return root->node;
12555d9e75c4SJan Schmidt 
1256a95236d9SJan Schmidt 	if (tm->op == MOD_LOG_ROOT_REPLACE) {
12575d9e75c4SJan Schmidt 		old_root = &tm->old_root;
12585d9e75c4SJan Schmidt 		old_generation = tm->generation;
1259a95236d9SJan Schmidt 		logical = old_root->logical;
1260a95236d9SJan Schmidt 	} else {
1261a95236d9SJan Schmidt 		logical = root->node->start;
1262a95236d9SJan Schmidt 	}
12635d9e75c4SJan Schmidt 
1264a95236d9SJan Schmidt 	tm = tree_mod_log_search(root->fs_info, logical, time_seq);
1265a95236d9SJan Schmidt 	if (old_root)
126628da9fb4SJan Schmidt 		eb = alloc_dummy_extent_buffer(logical, root->nodesize);
1267a95236d9SJan Schmidt 	else
1268a95236d9SJan Schmidt 		eb = btrfs_clone_extent_buffer(root->node);
12698ba97a15SJan Schmidt 	btrfs_tree_read_unlock(root->node);
12708ba97a15SJan Schmidt 	free_extent_buffer(root->node);
12718ba97a15SJan Schmidt 	if (!eb)
12728ba97a15SJan Schmidt 		return NULL;
12738ba97a15SJan Schmidt 	btrfs_tree_read_lock(eb);
1274a95236d9SJan Schmidt 	if (old_root) {
12755d9e75c4SJan Schmidt 		btrfs_set_header_bytenr(eb, eb->start);
12765d9e75c4SJan Schmidt 		btrfs_set_header_backref_rev(eb, BTRFS_MIXED_BACKREF_REV);
12775d9e75c4SJan Schmidt 		btrfs_set_header_owner(eb, root->root_key.objectid);
12785d9e75c4SJan Schmidt 		btrfs_set_header_level(eb, old_root->level);
12795d9e75c4SJan Schmidt 		btrfs_set_header_generation(eb, old_generation);
1280a95236d9SJan Schmidt 	}
128128da9fb4SJan Schmidt 	if (tm)
12825d9e75c4SJan Schmidt 		__tree_mod_log_rewind(eb, time_seq, tm);
128328da9fb4SJan Schmidt 	else
128428da9fb4SJan Schmidt 		WARN_ON(btrfs_header_level(eb) != 0);
12858ba97a15SJan Schmidt 	extent_buffer_get(eb);
12865d9e75c4SJan Schmidt 
12875d9e75c4SJan Schmidt 	return eb;
12885d9e75c4SJan Schmidt }
12895d9e75c4SJan Schmidt 
12905d4f98a2SYan Zheng static inline int should_cow_block(struct btrfs_trans_handle *trans,
12915d4f98a2SYan Zheng 				   struct btrfs_root *root,
12925d4f98a2SYan Zheng 				   struct extent_buffer *buf)
12935d4f98a2SYan Zheng {
1294f1ebcc74SLiu Bo 	/* ensure we can see the force_cow */
1295f1ebcc74SLiu Bo 	smp_rmb();
1296f1ebcc74SLiu Bo 
1297f1ebcc74SLiu Bo 	/*
1298f1ebcc74SLiu Bo 	 * We do not need to cow a block if
1299f1ebcc74SLiu Bo 	 * 1) this block is not created or changed in this transaction;
1300f1ebcc74SLiu Bo 	 * 2) this block does not belong to TREE_RELOC tree;
1301f1ebcc74SLiu Bo 	 * 3) the root is not forced COW.
1302f1ebcc74SLiu Bo 	 *
1303f1ebcc74SLiu Bo 	 * What is forced COW:
1304f1ebcc74SLiu Bo 	 *    when we create snapshot during commiting the transaction,
1305f1ebcc74SLiu Bo 	 *    after we've finished coping src root, we must COW the shared
1306f1ebcc74SLiu Bo 	 *    block to ensure the metadata consistency.
1307f1ebcc74SLiu Bo 	 */
13085d4f98a2SYan Zheng 	if (btrfs_header_generation(buf) == trans->transid &&
13095d4f98a2SYan Zheng 	    !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN) &&
13105d4f98a2SYan Zheng 	    !(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
1311f1ebcc74SLiu Bo 	      btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)) &&
1312f1ebcc74SLiu Bo 	    !root->force_cow)
13135d4f98a2SYan Zheng 		return 0;
13145d4f98a2SYan Zheng 	return 1;
13155d4f98a2SYan Zheng }
13165d4f98a2SYan Zheng 
1317d352ac68SChris Mason /*
1318d352ac68SChris Mason  * cows a single block, see __btrfs_cow_block for the real work.
1319d352ac68SChris Mason  * This version of it has extra checks so that a block isn't cow'd more than
1320d352ac68SChris Mason  * once per transaction, as long as it hasn't been written yet
1321d352ac68SChris Mason  */
1322d397712bSChris Mason noinline int btrfs_cow_block(struct btrfs_trans_handle *trans,
13235f39d397SChris Mason 		    struct btrfs_root *root, struct extent_buffer *buf,
13245f39d397SChris Mason 		    struct extent_buffer *parent, int parent_slot,
13259fa8cfe7SChris Mason 		    struct extent_buffer **cow_ret)
132602217ed2SChris Mason {
13276702ed49SChris Mason 	u64 search_start;
1328f510cfecSChris Mason 	int ret;
1329dc17ff8fSChris Mason 
1330ccd467d6SChris Mason 	if (trans->transaction != root->fs_info->running_transaction) {
1331d397712bSChris Mason 		printk(KERN_CRIT "trans %llu running %llu\n",
1332d397712bSChris Mason 		       (unsigned long long)trans->transid,
1333d397712bSChris Mason 		       (unsigned long long)
1334ccd467d6SChris Mason 		       root->fs_info->running_transaction->transid);
1335ccd467d6SChris Mason 		WARN_ON(1);
1336ccd467d6SChris Mason 	}
1337ccd467d6SChris Mason 	if (trans->transid != root->fs_info->generation) {
1338d397712bSChris Mason 		printk(KERN_CRIT "trans %llu running %llu\n",
1339d397712bSChris Mason 		       (unsigned long long)trans->transid,
1340d397712bSChris Mason 		       (unsigned long long)root->fs_info->generation);
1341ccd467d6SChris Mason 		WARN_ON(1);
1342ccd467d6SChris Mason 	}
1343dc17ff8fSChris Mason 
13445d4f98a2SYan Zheng 	if (!should_cow_block(trans, root, buf)) {
134502217ed2SChris Mason 		*cow_ret = buf;
134602217ed2SChris Mason 		return 0;
134702217ed2SChris Mason 	}
1348c487685dSChris Mason 
13490b86a832SChris Mason 	search_start = buf->start & ~((u64)(1024 * 1024 * 1024) - 1);
1350b4ce94deSChris Mason 
1351b4ce94deSChris Mason 	if (parent)
1352b4ce94deSChris Mason 		btrfs_set_lock_blocking(parent);
1353b4ce94deSChris Mason 	btrfs_set_lock_blocking(buf);
1354b4ce94deSChris Mason 
1355f510cfecSChris Mason 	ret = __btrfs_cow_block(trans, root, buf, parent,
13569fa8cfe7SChris Mason 				 parent_slot, cow_ret, search_start, 0);
13571abe9b8aSliubo 
13581abe9b8aSliubo 	trace_btrfs_cow_block(root, buf, *cow_ret);
13591abe9b8aSliubo 
1360f510cfecSChris Mason 	return ret;
13612c90e5d6SChris Mason }
13626702ed49SChris Mason 
1363d352ac68SChris Mason /*
1364d352ac68SChris Mason  * helper function for defrag to decide if two blocks pointed to by a
1365d352ac68SChris Mason  * node are actually close by
1366d352ac68SChris Mason  */
13676b80053dSChris Mason static int close_blocks(u64 blocknr, u64 other, u32 blocksize)
13686702ed49SChris Mason {
13696b80053dSChris Mason 	if (blocknr < other && other - (blocknr + blocksize) < 32768)
13706702ed49SChris Mason 		return 1;
13716b80053dSChris Mason 	if (blocknr > other && blocknr - (other + blocksize) < 32768)
13726702ed49SChris Mason 		return 1;
137302217ed2SChris Mason 	return 0;
137402217ed2SChris Mason }
137502217ed2SChris Mason 
1376081e9573SChris Mason /*
1377081e9573SChris Mason  * compare two keys in a memcmp fashion
1378081e9573SChris Mason  */
1379081e9573SChris Mason static int comp_keys(struct btrfs_disk_key *disk, struct btrfs_key *k2)
1380081e9573SChris Mason {
1381081e9573SChris Mason 	struct btrfs_key k1;
1382081e9573SChris Mason 
1383081e9573SChris Mason 	btrfs_disk_key_to_cpu(&k1, disk);
1384081e9573SChris Mason 
138520736abaSDiego Calleja 	return btrfs_comp_cpu_keys(&k1, k2);
1386081e9573SChris Mason }
1387081e9573SChris Mason 
1388f3465ca4SJosef Bacik /*
1389f3465ca4SJosef Bacik  * same as comp_keys only with two btrfs_key's
1390f3465ca4SJosef Bacik  */
13915d4f98a2SYan Zheng int btrfs_comp_cpu_keys(struct btrfs_key *k1, struct btrfs_key *k2)
1392f3465ca4SJosef Bacik {
1393f3465ca4SJosef Bacik 	if (k1->objectid > k2->objectid)
1394f3465ca4SJosef Bacik 		return 1;
1395f3465ca4SJosef Bacik 	if (k1->objectid < k2->objectid)
1396f3465ca4SJosef Bacik 		return -1;
1397f3465ca4SJosef Bacik 	if (k1->type > k2->type)
1398f3465ca4SJosef Bacik 		return 1;
1399f3465ca4SJosef Bacik 	if (k1->type < k2->type)
1400f3465ca4SJosef Bacik 		return -1;
1401f3465ca4SJosef Bacik 	if (k1->offset > k2->offset)
1402f3465ca4SJosef Bacik 		return 1;
1403f3465ca4SJosef Bacik 	if (k1->offset < k2->offset)
1404f3465ca4SJosef Bacik 		return -1;
1405f3465ca4SJosef Bacik 	return 0;
1406f3465ca4SJosef Bacik }
1407081e9573SChris Mason 
1408d352ac68SChris Mason /*
1409d352ac68SChris Mason  * this is used by the defrag code to go through all the
1410d352ac68SChris Mason  * leaves pointed to by a node and reallocate them so that
1411d352ac68SChris Mason  * disk order is close to key order
1412d352ac68SChris Mason  */
14136702ed49SChris Mason int btrfs_realloc_node(struct btrfs_trans_handle *trans,
14145f39d397SChris Mason 		       struct btrfs_root *root, struct extent_buffer *parent,
1415a6b6e75eSChris Mason 		       int start_slot, int cache_only, u64 *last_ret,
1416a6b6e75eSChris Mason 		       struct btrfs_key *progress)
14176702ed49SChris Mason {
14186b80053dSChris Mason 	struct extent_buffer *cur;
14196702ed49SChris Mason 	u64 blocknr;
1420ca7a79adSChris Mason 	u64 gen;
1421e9d0b13bSChris Mason 	u64 search_start = *last_ret;
1422e9d0b13bSChris Mason 	u64 last_block = 0;
14236702ed49SChris Mason 	u64 other;
14246702ed49SChris Mason 	u32 parent_nritems;
14256702ed49SChris Mason 	int end_slot;
14266702ed49SChris Mason 	int i;
14276702ed49SChris Mason 	int err = 0;
1428f2183bdeSChris Mason 	int parent_level;
14296b80053dSChris Mason 	int uptodate;
14306b80053dSChris Mason 	u32 blocksize;
1431081e9573SChris Mason 	int progress_passed = 0;
1432081e9573SChris Mason 	struct btrfs_disk_key disk_key;
14336702ed49SChris Mason 
14345708b959SChris Mason 	parent_level = btrfs_header_level(parent);
14355708b959SChris Mason 	if (cache_only && parent_level != 1)
14365708b959SChris Mason 		return 0;
14375708b959SChris Mason 
1438d397712bSChris Mason 	if (trans->transaction != root->fs_info->running_transaction)
14396702ed49SChris Mason 		WARN_ON(1);
1440d397712bSChris Mason 	if (trans->transid != root->fs_info->generation)
14416702ed49SChris Mason 		WARN_ON(1);
144286479a04SChris Mason 
14436b80053dSChris Mason 	parent_nritems = btrfs_header_nritems(parent);
14446b80053dSChris Mason 	blocksize = btrfs_level_size(root, parent_level - 1);
14456702ed49SChris Mason 	end_slot = parent_nritems;
14466702ed49SChris Mason 
14476702ed49SChris Mason 	if (parent_nritems == 1)
14486702ed49SChris Mason 		return 0;
14496702ed49SChris Mason 
1450b4ce94deSChris Mason 	btrfs_set_lock_blocking(parent);
1451b4ce94deSChris Mason 
14526702ed49SChris Mason 	for (i = start_slot; i < end_slot; i++) {
14536702ed49SChris Mason 		int close = 1;
1454a6b6e75eSChris Mason 
1455081e9573SChris Mason 		btrfs_node_key(parent, &disk_key, i);
1456081e9573SChris Mason 		if (!progress_passed && comp_keys(&disk_key, progress) < 0)
1457081e9573SChris Mason 			continue;
1458081e9573SChris Mason 
1459081e9573SChris Mason 		progress_passed = 1;
14606b80053dSChris Mason 		blocknr = btrfs_node_blockptr(parent, i);
1461ca7a79adSChris Mason 		gen = btrfs_node_ptr_generation(parent, i);
1462e9d0b13bSChris Mason 		if (last_block == 0)
1463e9d0b13bSChris Mason 			last_block = blocknr;
14645708b959SChris Mason 
14656702ed49SChris Mason 		if (i > 0) {
14666b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i - 1);
14676b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
14686702ed49SChris Mason 		}
14690ef3e66bSChris Mason 		if (!close && i < end_slot - 2) {
14706b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i + 1);
14716b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
14726702ed49SChris Mason 		}
1473e9d0b13bSChris Mason 		if (close) {
1474e9d0b13bSChris Mason 			last_block = blocknr;
14756702ed49SChris Mason 			continue;
1476e9d0b13bSChris Mason 		}
14776702ed49SChris Mason 
14786b80053dSChris Mason 		cur = btrfs_find_tree_block(root, blocknr, blocksize);
14796b80053dSChris Mason 		if (cur)
1480b9fab919SChris Mason 			uptodate = btrfs_buffer_uptodate(cur, gen, 0);
14816b80053dSChris Mason 		else
14826b80053dSChris Mason 			uptodate = 0;
14835708b959SChris Mason 		if (!cur || !uptodate) {
14846702ed49SChris Mason 			if (cache_only) {
14856b80053dSChris Mason 				free_extent_buffer(cur);
14866702ed49SChris Mason 				continue;
14876702ed49SChris Mason 			}
14886b80053dSChris Mason 			if (!cur) {
14896b80053dSChris Mason 				cur = read_tree_block(root, blocknr,
1490ca7a79adSChris Mason 							 blocksize, gen);
149197d9a8a4STsutomu Itoh 				if (!cur)
149297d9a8a4STsutomu Itoh 					return -EIO;
14936b80053dSChris Mason 			} else if (!uptodate) {
1494018642a1STsutomu Itoh 				err = btrfs_read_buffer(cur, gen);
1495018642a1STsutomu Itoh 				if (err) {
1496018642a1STsutomu Itoh 					free_extent_buffer(cur);
1497018642a1STsutomu Itoh 					return err;
1498018642a1STsutomu Itoh 				}
14996702ed49SChris Mason 			}
1500f2183bdeSChris Mason 		}
1501e9d0b13bSChris Mason 		if (search_start == 0)
15026b80053dSChris Mason 			search_start = last_block;
1503e9d0b13bSChris Mason 
1504e7a84565SChris Mason 		btrfs_tree_lock(cur);
1505b4ce94deSChris Mason 		btrfs_set_lock_blocking(cur);
15066b80053dSChris Mason 		err = __btrfs_cow_block(trans, root, cur, parent, i,
1507e7a84565SChris Mason 					&cur, search_start,
15086b80053dSChris Mason 					min(16 * blocksize,
15099fa8cfe7SChris Mason 					    (end_slot - i) * blocksize));
1510252c38f0SYan 		if (err) {
1511e7a84565SChris Mason 			btrfs_tree_unlock(cur);
15126b80053dSChris Mason 			free_extent_buffer(cur);
15136702ed49SChris Mason 			break;
1514252c38f0SYan 		}
1515e7a84565SChris Mason 		search_start = cur->start;
1516e7a84565SChris Mason 		last_block = cur->start;
1517f2183bdeSChris Mason 		*last_ret = search_start;
1518e7a84565SChris Mason 		btrfs_tree_unlock(cur);
1519e7a84565SChris Mason 		free_extent_buffer(cur);
15206702ed49SChris Mason 	}
15216702ed49SChris Mason 	return err;
15226702ed49SChris Mason }
15236702ed49SChris Mason 
152474123bd7SChris Mason /*
152574123bd7SChris Mason  * The leaf data grows from end-to-front in the node.
152674123bd7SChris Mason  * this returns the address of the start of the last item,
152774123bd7SChris Mason  * which is the stop of the leaf data stack
152874123bd7SChris Mason  */
1529123abc88SChris Mason static inline unsigned int leaf_data_end(struct btrfs_root *root,
15305f39d397SChris Mason 					 struct extent_buffer *leaf)
1531be0e5c09SChris Mason {
15325f39d397SChris Mason 	u32 nr = btrfs_header_nritems(leaf);
1533be0e5c09SChris Mason 	if (nr == 0)
1534123abc88SChris Mason 		return BTRFS_LEAF_DATA_SIZE(root);
15355f39d397SChris Mason 	return btrfs_item_offset_nr(leaf, nr - 1);
1536be0e5c09SChris Mason }
1537be0e5c09SChris Mason 
1538aa5d6bedSChris Mason 
153974123bd7SChris Mason /*
15405f39d397SChris Mason  * search for key in the extent_buffer.  The items start at offset p,
15415f39d397SChris Mason  * and they are item_size apart.  There are 'max' items in p.
15425f39d397SChris Mason  *
154374123bd7SChris Mason  * the slot in the array is returned via slot, and it points to
154474123bd7SChris Mason  * the place where you would insert key if it is not found in
154574123bd7SChris Mason  * the array.
154674123bd7SChris Mason  *
154774123bd7SChris Mason  * slot may point to max if the key is bigger than all of the keys
154874123bd7SChris Mason  */
1549e02119d5SChris Mason static noinline int generic_bin_search(struct extent_buffer *eb,
1550e02119d5SChris Mason 				       unsigned long p,
15515f39d397SChris Mason 				       int item_size, struct btrfs_key *key,
1552be0e5c09SChris Mason 				       int max, int *slot)
1553be0e5c09SChris Mason {
1554be0e5c09SChris Mason 	int low = 0;
1555be0e5c09SChris Mason 	int high = max;
1556be0e5c09SChris Mason 	int mid;
1557be0e5c09SChris Mason 	int ret;
1558479965d6SChris Mason 	struct btrfs_disk_key *tmp = NULL;
15595f39d397SChris Mason 	struct btrfs_disk_key unaligned;
15605f39d397SChris Mason 	unsigned long offset;
15615f39d397SChris Mason 	char *kaddr = NULL;
15625f39d397SChris Mason 	unsigned long map_start = 0;
15635f39d397SChris Mason 	unsigned long map_len = 0;
1564479965d6SChris Mason 	int err;
1565be0e5c09SChris Mason 
1566be0e5c09SChris Mason 	while (low < high) {
1567be0e5c09SChris Mason 		mid = (low + high) / 2;
15685f39d397SChris Mason 		offset = p + mid * item_size;
15695f39d397SChris Mason 
1570a6591715SChris Mason 		if (!kaddr || offset < map_start ||
15715f39d397SChris Mason 		    (offset + sizeof(struct btrfs_disk_key)) >
15725f39d397SChris Mason 		    map_start + map_len) {
1573934d375bSChris Mason 
1574934d375bSChris Mason 			err = map_private_extent_buffer(eb, offset,
1575479965d6SChris Mason 						sizeof(struct btrfs_disk_key),
1576a6591715SChris Mason 						&kaddr, &map_start, &map_len);
15775f39d397SChris Mason 
1578479965d6SChris Mason 			if (!err) {
1579479965d6SChris Mason 				tmp = (struct btrfs_disk_key *)(kaddr + offset -
1580479965d6SChris Mason 							map_start);
1581479965d6SChris Mason 			} else {
15825f39d397SChris Mason 				read_extent_buffer(eb, &unaligned,
15835f39d397SChris Mason 						   offset, sizeof(unaligned));
15845f39d397SChris Mason 				tmp = &unaligned;
1585479965d6SChris Mason 			}
1586479965d6SChris Mason 
15875f39d397SChris Mason 		} else {
15885f39d397SChris Mason 			tmp = (struct btrfs_disk_key *)(kaddr + offset -
15895f39d397SChris Mason 							map_start);
15905f39d397SChris Mason 		}
1591be0e5c09SChris Mason 		ret = comp_keys(tmp, key);
1592be0e5c09SChris Mason 
1593be0e5c09SChris Mason 		if (ret < 0)
1594be0e5c09SChris Mason 			low = mid + 1;
1595be0e5c09SChris Mason 		else if (ret > 0)
1596be0e5c09SChris Mason 			high = mid;
1597be0e5c09SChris Mason 		else {
1598be0e5c09SChris Mason 			*slot = mid;
1599be0e5c09SChris Mason 			return 0;
1600be0e5c09SChris Mason 		}
1601be0e5c09SChris Mason 	}
1602be0e5c09SChris Mason 	*slot = low;
1603be0e5c09SChris Mason 	return 1;
1604be0e5c09SChris Mason }
1605be0e5c09SChris Mason 
160697571fd0SChris Mason /*
160797571fd0SChris Mason  * simple bin_search frontend that does the right thing for
160897571fd0SChris Mason  * leaves vs nodes
160997571fd0SChris Mason  */
16105f39d397SChris Mason static int bin_search(struct extent_buffer *eb, struct btrfs_key *key,
16115f39d397SChris Mason 		      int level, int *slot)
1612be0e5c09SChris Mason {
1613f775738fSWang Sheng-Hui 	if (level == 0)
16145f39d397SChris Mason 		return generic_bin_search(eb,
16155f39d397SChris Mason 					  offsetof(struct btrfs_leaf, items),
16160783fcfcSChris Mason 					  sizeof(struct btrfs_item),
16175f39d397SChris Mason 					  key, btrfs_header_nritems(eb),
16187518a238SChris Mason 					  slot);
1619f775738fSWang Sheng-Hui 	else
16205f39d397SChris Mason 		return generic_bin_search(eb,
16215f39d397SChris Mason 					  offsetof(struct btrfs_node, ptrs),
1622123abc88SChris Mason 					  sizeof(struct btrfs_key_ptr),
16235f39d397SChris Mason 					  key, btrfs_header_nritems(eb),
16247518a238SChris Mason 					  slot);
1625be0e5c09SChris Mason }
1626be0e5c09SChris Mason 
16275d4f98a2SYan Zheng int btrfs_bin_search(struct extent_buffer *eb, struct btrfs_key *key,
16285d4f98a2SYan Zheng 		     int level, int *slot)
16295d4f98a2SYan Zheng {
16305d4f98a2SYan Zheng 	return bin_search(eb, key, level, slot);
16315d4f98a2SYan Zheng }
16325d4f98a2SYan Zheng 
1633f0486c68SYan, Zheng static void root_add_used(struct btrfs_root *root, u32 size)
1634f0486c68SYan, Zheng {
1635f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
1636f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
1637f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) + size);
1638f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
1639f0486c68SYan, Zheng }
1640f0486c68SYan, Zheng 
1641f0486c68SYan, Zheng static void root_sub_used(struct btrfs_root *root, u32 size)
1642f0486c68SYan, Zheng {
1643f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
1644f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
1645f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) - size);
1646f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
1647f0486c68SYan, Zheng }
1648f0486c68SYan, Zheng 
1649d352ac68SChris Mason /* given a node and slot number, this reads the blocks it points to.  The
1650d352ac68SChris Mason  * extent buffer is returned with a reference taken (but unlocked).
1651d352ac68SChris Mason  * NULL is returned on error.
1652d352ac68SChris Mason  */
1653e02119d5SChris Mason static noinline struct extent_buffer *read_node_slot(struct btrfs_root *root,
16545f39d397SChris Mason 				   struct extent_buffer *parent, int slot)
1655bb803951SChris Mason {
1656ca7a79adSChris Mason 	int level = btrfs_header_level(parent);
1657bb803951SChris Mason 	if (slot < 0)
1658bb803951SChris Mason 		return NULL;
16595f39d397SChris Mason 	if (slot >= btrfs_header_nritems(parent))
1660bb803951SChris Mason 		return NULL;
1661ca7a79adSChris Mason 
1662ca7a79adSChris Mason 	BUG_ON(level == 0);
1663ca7a79adSChris Mason 
1664db94535dSChris Mason 	return read_tree_block(root, btrfs_node_blockptr(parent, slot),
1665ca7a79adSChris Mason 		       btrfs_level_size(root, level - 1),
1666ca7a79adSChris Mason 		       btrfs_node_ptr_generation(parent, slot));
1667bb803951SChris Mason }
1668bb803951SChris Mason 
1669d352ac68SChris Mason /*
1670d352ac68SChris Mason  * node level balancing, used to make sure nodes are in proper order for
1671d352ac68SChris Mason  * item deletion.  We balance from the top down, so we have to make sure
1672d352ac68SChris Mason  * that a deletion won't leave an node completely empty later on.
1673d352ac68SChris Mason  */
1674e02119d5SChris Mason static noinline int balance_level(struct btrfs_trans_handle *trans,
167598ed5174SChris Mason 			 struct btrfs_root *root,
167698ed5174SChris Mason 			 struct btrfs_path *path, int level)
1677bb803951SChris Mason {
16785f39d397SChris Mason 	struct extent_buffer *right = NULL;
16795f39d397SChris Mason 	struct extent_buffer *mid;
16805f39d397SChris Mason 	struct extent_buffer *left = NULL;
16815f39d397SChris Mason 	struct extent_buffer *parent = NULL;
1682bb803951SChris Mason 	int ret = 0;
1683bb803951SChris Mason 	int wret;
1684bb803951SChris Mason 	int pslot;
1685bb803951SChris Mason 	int orig_slot = path->slots[level];
168679f95c82SChris Mason 	u64 orig_ptr;
1687bb803951SChris Mason 
1688bb803951SChris Mason 	if (level == 0)
1689bb803951SChris Mason 		return 0;
1690bb803951SChris Mason 
16915f39d397SChris Mason 	mid = path->nodes[level];
1692b4ce94deSChris Mason 
1693bd681513SChris Mason 	WARN_ON(path->locks[level] != BTRFS_WRITE_LOCK &&
1694bd681513SChris Mason 		path->locks[level] != BTRFS_WRITE_LOCK_BLOCKING);
16957bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
16967bb86316SChris Mason 
16971d4f8a0cSChris Mason 	orig_ptr = btrfs_node_blockptr(mid, orig_slot);
169879f95c82SChris Mason 
1699a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
17005f39d397SChris Mason 		parent = path->nodes[level + 1];
1701bb803951SChris Mason 		pslot = path->slots[level + 1];
1702a05a9bb1SLi Zefan 	}
1703bb803951SChris Mason 
170440689478SChris Mason 	/*
170540689478SChris Mason 	 * deal with the case where there is only one pointer in the root
170640689478SChris Mason 	 * by promoting the node below to a root
170740689478SChris Mason 	 */
17085f39d397SChris Mason 	if (!parent) {
17095f39d397SChris Mason 		struct extent_buffer *child;
1710bb803951SChris Mason 
17115f39d397SChris Mason 		if (btrfs_header_nritems(mid) != 1)
1712bb803951SChris Mason 			return 0;
1713bb803951SChris Mason 
1714bb803951SChris Mason 		/* promote the child to a root */
17155f39d397SChris Mason 		child = read_node_slot(root, mid, 0);
1716305a26afSMark Fasheh 		if (!child) {
1717305a26afSMark Fasheh 			ret = -EROFS;
1718305a26afSMark Fasheh 			btrfs_std_error(root->fs_info, ret);
1719305a26afSMark Fasheh 			goto enospc;
1720305a26afSMark Fasheh 		}
1721305a26afSMark Fasheh 
1722925baeddSChris Mason 		btrfs_tree_lock(child);
1723b4ce94deSChris Mason 		btrfs_set_lock_blocking(child);
17249fa8cfe7SChris Mason 		ret = btrfs_cow_block(trans, root, child, mid, 0, &child);
1725f0486c68SYan, Zheng 		if (ret) {
1726f0486c68SYan, Zheng 			btrfs_tree_unlock(child);
1727f0486c68SYan, Zheng 			free_extent_buffer(child);
1728f0486c68SYan, Zheng 			goto enospc;
1729f0486c68SYan, Zheng 		}
17302f375ab9SYan 
1731f230475eSJan Schmidt 		tree_mod_log_set_root_pointer(root, child);
1732240f62c8SChris Mason 		rcu_assign_pointer(root->node, child);
1733925baeddSChris Mason 
17340b86a832SChris Mason 		add_root_to_dirty_list(root);
1735925baeddSChris Mason 		btrfs_tree_unlock(child);
1736b4ce94deSChris Mason 
1737925baeddSChris Mason 		path->locks[level] = 0;
1738bb803951SChris Mason 		path->nodes[level] = NULL;
17395f39d397SChris Mason 		clean_tree_block(trans, root, mid);
1740925baeddSChris Mason 		btrfs_tree_unlock(mid);
1741bb803951SChris Mason 		/* once for the path */
17425f39d397SChris Mason 		free_extent_buffer(mid);
1743f0486c68SYan, Zheng 
1744f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
17455581a51aSJan Schmidt 		btrfs_free_tree_block(trans, root, mid, 0, 1);
1746bb803951SChris Mason 		/* once for the root ptr */
17473083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
1748f0486c68SYan, Zheng 		return 0;
1749bb803951SChris Mason 	}
17505f39d397SChris Mason 	if (btrfs_header_nritems(mid) >
1751123abc88SChris Mason 	    BTRFS_NODEPTRS_PER_BLOCK(root) / 4)
1752bb803951SChris Mason 		return 0;
1753bb803951SChris Mason 
17545f39d397SChris Mason 	left = read_node_slot(root, parent, pslot - 1);
17555f39d397SChris Mason 	if (left) {
1756925baeddSChris Mason 		btrfs_tree_lock(left);
1757b4ce94deSChris Mason 		btrfs_set_lock_blocking(left);
17585f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, left,
17599fa8cfe7SChris Mason 				       parent, pslot - 1, &left);
176054aa1f4dSChris Mason 		if (wret) {
176154aa1f4dSChris Mason 			ret = wret;
176254aa1f4dSChris Mason 			goto enospc;
176354aa1f4dSChris Mason 		}
17642cc58cf2SChris Mason 	}
17655f39d397SChris Mason 	right = read_node_slot(root, parent, pslot + 1);
17665f39d397SChris Mason 	if (right) {
1767925baeddSChris Mason 		btrfs_tree_lock(right);
1768b4ce94deSChris Mason 		btrfs_set_lock_blocking(right);
17695f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, right,
17709fa8cfe7SChris Mason 				       parent, pslot + 1, &right);
17712cc58cf2SChris Mason 		if (wret) {
17722cc58cf2SChris Mason 			ret = wret;
17732cc58cf2SChris Mason 			goto enospc;
17742cc58cf2SChris Mason 		}
17752cc58cf2SChris Mason 	}
17762cc58cf2SChris Mason 
17772cc58cf2SChris Mason 	/* first, try to make some room in the middle buffer */
17785f39d397SChris Mason 	if (left) {
17795f39d397SChris Mason 		orig_slot += btrfs_header_nritems(left);
1780bce4eae9SChris Mason 		wret = push_node_left(trans, root, left, mid, 1);
178179f95c82SChris Mason 		if (wret < 0)
178279f95c82SChris Mason 			ret = wret;
1783bb803951SChris Mason 	}
178479f95c82SChris Mason 
178579f95c82SChris Mason 	/*
178679f95c82SChris Mason 	 * then try to empty the right most buffer into the middle
178779f95c82SChris Mason 	 */
17885f39d397SChris Mason 	if (right) {
1789971a1f66SChris Mason 		wret = push_node_left(trans, root, mid, right, 1);
179054aa1f4dSChris Mason 		if (wret < 0 && wret != -ENOSPC)
179179f95c82SChris Mason 			ret = wret;
17925f39d397SChris Mason 		if (btrfs_header_nritems(right) == 0) {
17935f39d397SChris Mason 			clean_tree_block(trans, root, right);
1794925baeddSChris Mason 			btrfs_tree_unlock(right);
1795f3ea38daSJan Schmidt 			del_ptr(trans, root, path, level + 1, pslot + 1, 1);
1796f0486c68SYan, Zheng 			root_sub_used(root, right->len);
17975581a51aSJan Schmidt 			btrfs_free_tree_block(trans, root, right, 0, 1);
17983083ee2eSJosef Bacik 			free_extent_buffer_stale(right);
1799f0486c68SYan, Zheng 			right = NULL;
1800bb803951SChris Mason 		} else {
18015f39d397SChris Mason 			struct btrfs_disk_key right_key;
18025f39d397SChris Mason 			btrfs_node_key(right, &right_key, 0);
1803f230475eSJan Schmidt 			tree_mod_log_set_node_key(root->fs_info, parent,
1804f230475eSJan Schmidt 						  &right_key, pslot + 1, 0);
18055f39d397SChris Mason 			btrfs_set_node_key(parent, &right_key, pslot + 1);
18065f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
1807bb803951SChris Mason 		}
1808bb803951SChris Mason 	}
18095f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 1) {
181079f95c82SChris Mason 		/*
181179f95c82SChris Mason 		 * we're not allowed to leave a node with one item in the
181279f95c82SChris Mason 		 * tree during a delete.  A deletion from lower in the tree
181379f95c82SChris Mason 		 * could try to delete the only pointer in this node.
181479f95c82SChris Mason 		 * So, pull some keys from the left.
181579f95c82SChris Mason 		 * There has to be a left pointer at this point because
181679f95c82SChris Mason 		 * otherwise we would have pulled some pointers from the
181779f95c82SChris Mason 		 * right
181879f95c82SChris Mason 		 */
1819305a26afSMark Fasheh 		if (!left) {
1820305a26afSMark Fasheh 			ret = -EROFS;
1821305a26afSMark Fasheh 			btrfs_std_error(root->fs_info, ret);
1822305a26afSMark Fasheh 			goto enospc;
1823305a26afSMark Fasheh 		}
18245f39d397SChris Mason 		wret = balance_node_right(trans, root, mid, left);
182554aa1f4dSChris Mason 		if (wret < 0) {
182679f95c82SChris Mason 			ret = wret;
182754aa1f4dSChris Mason 			goto enospc;
182854aa1f4dSChris Mason 		}
1829bce4eae9SChris Mason 		if (wret == 1) {
1830bce4eae9SChris Mason 			wret = push_node_left(trans, root, left, mid, 1);
1831bce4eae9SChris Mason 			if (wret < 0)
1832bce4eae9SChris Mason 				ret = wret;
1833bce4eae9SChris Mason 		}
183479f95c82SChris Mason 		BUG_ON(wret == 1);
183579f95c82SChris Mason 	}
18365f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 0) {
18375f39d397SChris Mason 		clean_tree_block(trans, root, mid);
1838925baeddSChris Mason 		btrfs_tree_unlock(mid);
1839f3ea38daSJan Schmidt 		del_ptr(trans, root, path, level + 1, pslot, 1);
1840f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
18415581a51aSJan Schmidt 		btrfs_free_tree_block(trans, root, mid, 0, 1);
18423083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
1843f0486c68SYan, Zheng 		mid = NULL;
184479f95c82SChris Mason 	} else {
184579f95c82SChris Mason 		/* update the parent key to reflect our changes */
18465f39d397SChris Mason 		struct btrfs_disk_key mid_key;
18475f39d397SChris Mason 		btrfs_node_key(mid, &mid_key, 0);
1848f230475eSJan Schmidt 		tree_mod_log_set_node_key(root->fs_info, parent, &mid_key,
1849f230475eSJan Schmidt 					  pslot, 0);
18505f39d397SChris Mason 		btrfs_set_node_key(parent, &mid_key, pslot);
18515f39d397SChris Mason 		btrfs_mark_buffer_dirty(parent);
185279f95c82SChris Mason 	}
1853bb803951SChris Mason 
185479f95c82SChris Mason 	/* update the path */
18555f39d397SChris Mason 	if (left) {
18565f39d397SChris Mason 		if (btrfs_header_nritems(left) > orig_slot) {
18575f39d397SChris Mason 			extent_buffer_get(left);
1858925baeddSChris Mason 			/* left was locked after cow */
18595f39d397SChris Mason 			path->nodes[level] = left;
1860bb803951SChris Mason 			path->slots[level + 1] -= 1;
1861bb803951SChris Mason 			path->slots[level] = orig_slot;
1862925baeddSChris Mason 			if (mid) {
1863925baeddSChris Mason 				btrfs_tree_unlock(mid);
18645f39d397SChris Mason 				free_extent_buffer(mid);
1865925baeddSChris Mason 			}
1866bb803951SChris Mason 		} else {
18675f39d397SChris Mason 			orig_slot -= btrfs_header_nritems(left);
1868bb803951SChris Mason 			path->slots[level] = orig_slot;
1869bb803951SChris Mason 		}
1870bb803951SChris Mason 	}
187179f95c82SChris Mason 	/* double check we haven't messed things up */
1872e20d96d6SChris Mason 	if (orig_ptr !=
18735f39d397SChris Mason 	    btrfs_node_blockptr(path->nodes[level], path->slots[level]))
187479f95c82SChris Mason 		BUG();
187554aa1f4dSChris Mason enospc:
1876925baeddSChris Mason 	if (right) {
1877925baeddSChris Mason 		btrfs_tree_unlock(right);
18785f39d397SChris Mason 		free_extent_buffer(right);
1879925baeddSChris Mason 	}
1880925baeddSChris Mason 	if (left) {
1881925baeddSChris Mason 		if (path->nodes[level] != left)
1882925baeddSChris Mason 			btrfs_tree_unlock(left);
18835f39d397SChris Mason 		free_extent_buffer(left);
1884925baeddSChris Mason 	}
1885bb803951SChris Mason 	return ret;
1886bb803951SChris Mason }
1887bb803951SChris Mason 
1888d352ac68SChris Mason /* Node balancing for insertion.  Here we only split or push nodes around
1889d352ac68SChris Mason  * when they are completely full.  This is also done top down, so we
1890d352ac68SChris Mason  * have to be pessimistic.
1891d352ac68SChris Mason  */
1892d397712bSChris Mason static noinline int push_nodes_for_insert(struct btrfs_trans_handle *trans,
1893e66f709bSChris Mason 					  struct btrfs_root *root,
1894e66f709bSChris Mason 					  struct btrfs_path *path, int level)
1895e66f709bSChris Mason {
18965f39d397SChris Mason 	struct extent_buffer *right = NULL;
18975f39d397SChris Mason 	struct extent_buffer *mid;
18985f39d397SChris Mason 	struct extent_buffer *left = NULL;
18995f39d397SChris Mason 	struct extent_buffer *parent = NULL;
1900e66f709bSChris Mason 	int ret = 0;
1901e66f709bSChris Mason 	int wret;
1902e66f709bSChris Mason 	int pslot;
1903e66f709bSChris Mason 	int orig_slot = path->slots[level];
1904e66f709bSChris Mason 
1905e66f709bSChris Mason 	if (level == 0)
1906e66f709bSChris Mason 		return 1;
1907e66f709bSChris Mason 
19085f39d397SChris Mason 	mid = path->nodes[level];
19097bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
1910e66f709bSChris Mason 
1911a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
19125f39d397SChris Mason 		parent = path->nodes[level + 1];
1913e66f709bSChris Mason 		pslot = path->slots[level + 1];
1914a05a9bb1SLi Zefan 	}
1915e66f709bSChris Mason 
19165f39d397SChris Mason 	if (!parent)
1917e66f709bSChris Mason 		return 1;
1918e66f709bSChris Mason 
19195f39d397SChris Mason 	left = read_node_slot(root, parent, pslot - 1);
1920e66f709bSChris Mason 
1921e66f709bSChris Mason 	/* first, try to make some room in the middle buffer */
19225f39d397SChris Mason 	if (left) {
1923e66f709bSChris Mason 		u32 left_nr;
1924925baeddSChris Mason 
1925925baeddSChris Mason 		btrfs_tree_lock(left);
1926b4ce94deSChris Mason 		btrfs_set_lock_blocking(left);
1927b4ce94deSChris Mason 
19285f39d397SChris Mason 		left_nr = btrfs_header_nritems(left);
192933ade1f8SChris Mason 		if (left_nr >= BTRFS_NODEPTRS_PER_BLOCK(root) - 1) {
193033ade1f8SChris Mason 			wret = 1;
193133ade1f8SChris Mason 		} else {
19325f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, left, parent,
19339fa8cfe7SChris Mason 					      pslot - 1, &left);
193454aa1f4dSChris Mason 			if (ret)
193554aa1f4dSChris Mason 				wret = 1;
193654aa1f4dSChris Mason 			else {
193754aa1f4dSChris Mason 				wret = push_node_left(trans, root,
1938971a1f66SChris Mason 						      left, mid, 0);
193954aa1f4dSChris Mason 			}
194033ade1f8SChris Mason 		}
1941e66f709bSChris Mason 		if (wret < 0)
1942e66f709bSChris Mason 			ret = wret;
1943e66f709bSChris Mason 		if (wret == 0) {
19445f39d397SChris Mason 			struct btrfs_disk_key disk_key;
1945e66f709bSChris Mason 			orig_slot += left_nr;
19465f39d397SChris Mason 			btrfs_node_key(mid, &disk_key, 0);
1947f230475eSJan Schmidt 			tree_mod_log_set_node_key(root->fs_info, parent,
1948f230475eSJan Schmidt 						  &disk_key, pslot, 0);
19495f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot);
19505f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
19515f39d397SChris Mason 			if (btrfs_header_nritems(left) > orig_slot) {
19525f39d397SChris Mason 				path->nodes[level] = left;
1953e66f709bSChris Mason 				path->slots[level + 1] -= 1;
1954e66f709bSChris Mason 				path->slots[level] = orig_slot;
1955925baeddSChris Mason 				btrfs_tree_unlock(mid);
19565f39d397SChris Mason 				free_extent_buffer(mid);
1957e66f709bSChris Mason 			} else {
1958e66f709bSChris Mason 				orig_slot -=
19595f39d397SChris Mason 					btrfs_header_nritems(left);
1960e66f709bSChris Mason 				path->slots[level] = orig_slot;
1961925baeddSChris Mason 				btrfs_tree_unlock(left);
19625f39d397SChris Mason 				free_extent_buffer(left);
1963e66f709bSChris Mason 			}
1964e66f709bSChris Mason 			return 0;
1965e66f709bSChris Mason 		}
1966925baeddSChris Mason 		btrfs_tree_unlock(left);
19675f39d397SChris Mason 		free_extent_buffer(left);
1968e66f709bSChris Mason 	}
19695f39d397SChris Mason 	right = read_node_slot(root, parent, pslot + 1);
1970e66f709bSChris Mason 
1971e66f709bSChris Mason 	/*
1972e66f709bSChris Mason 	 * then try to empty the right most buffer into the middle
1973e66f709bSChris Mason 	 */
19745f39d397SChris Mason 	if (right) {
197533ade1f8SChris Mason 		u32 right_nr;
1976b4ce94deSChris Mason 
1977925baeddSChris Mason 		btrfs_tree_lock(right);
1978b4ce94deSChris Mason 		btrfs_set_lock_blocking(right);
1979b4ce94deSChris Mason 
19805f39d397SChris Mason 		right_nr = btrfs_header_nritems(right);
198133ade1f8SChris Mason 		if (right_nr >= BTRFS_NODEPTRS_PER_BLOCK(root) - 1) {
198233ade1f8SChris Mason 			wret = 1;
198333ade1f8SChris Mason 		} else {
19845f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, right,
19855f39d397SChris Mason 					      parent, pslot + 1,
19869fa8cfe7SChris Mason 					      &right);
198754aa1f4dSChris Mason 			if (ret)
198854aa1f4dSChris Mason 				wret = 1;
198954aa1f4dSChris Mason 			else {
199033ade1f8SChris Mason 				wret = balance_node_right(trans, root,
19915f39d397SChris Mason 							  right, mid);
199233ade1f8SChris Mason 			}
199354aa1f4dSChris Mason 		}
1994e66f709bSChris Mason 		if (wret < 0)
1995e66f709bSChris Mason 			ret = wret;
1996e66f709bSChris Mason 		if (wret == 0) {
19975f39d397SChris Mason 			struct btrfs_disk_key disk_key;
19985f39d397SChris Mason 
19995f39d397SChris Mason 			btrfs_node_key(right, &disk_key, 0);
2000f230475eSJan Schmidt 			tree_mod_log_set_node_key(root->fs_info, parent,
2001f230475eSJan Schmidt 						  &disk_key, pslot + 1, 0);
20025f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot + 1);
20035f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
20045f39d397SChris Mason 
20055f39d397SChris Mason 			if (btrfs_header_nritems(mid) <= orig_slot) {
20065f39d397SChris Mason 				path->nodes[level] = right;
2007e66f709bSChris Mason 				path->slots[level + 1] += 1;
2008e66f709bSChris Mason 				path->slots[level] = orig_slot -
20095f39d397SChris Mason 					btrfs_header_nritems(mid);
2010925baeddSChris Mason 				btrfs_tree_unlock(mid);
20115f39d397SChris Mason 				free_extent_buffer(mid);
2012e66f709bSChris Mason 			} else {
2013925baeddSChris Mason 				btrfs_tree_unlock(right);
20145f39d397SChris Mason 				free_extent_buffer(right);
2015e66f709bSChris Mason 			}
2016e66f709bSChris Mason 			return 0;
2017e66f709bSChris Mason 		}
2018925baeddSChris Mason 		btrfs_tree_unlock(right);
20195f39d397SChris Mason 		free_extent_buffer(right);
2020e66f709bSChris Mason 	}
2021e66f709bSChris Mason 	return 1;
2022e66f709bSChris Mason }
2023e66f709bSChris Mason 
202474123bd7SChris Mason /*
2025d352ac68SChris Mason  * readahead one full node of leaves, finding things that are close
2026d352ac68SChris Mason  * to the block in 'slot', and triggering ra on them.
20273c69faecSChris Mason  */
2028c8c42864SChris Mason static void reada_for_search(struct btrfs_root *root,
2029e02119d5SChris Mason 			     struct btrfs_path *path,
203001f46658SChris Mason 			     int level, int slot, u64 objectid)
20313c69faecSChris Mason {
20325f39d397SChris Mason 	struct extent_buffer *node;
203301f46658SChris Mason 	struct btrfs_disk_key disk_key;
20343c69faecSChris Mason 	u32 nritems;
20353c69faecSChris Mason 	u64 search;
2036a7175319SChris Mason 	u64 target;
20376b80053dSChris Mason 	u64 nread = 0;
2038cb25c2eaSJosef Bacik 	u64 gen;
20393c69faecSChris Mason 	int direction = path->reada;
20405f39d397SChris Mason 	struct extent_buffer *eb;
20416b80053dSChris Mason 	u32 nr;
20426b80053dSChris Mason 	u32 blocksize;
20436b80053dSChris Mason 	u32 nscan = 0;
2044db94535dSChris Mason 
2045a6b6e75eSChris Mason 	if (level != 1)
20463c69faecSChris Mason 		return;
20473c69faecSChris Mason 
20486702ed49SChris Mason 	if (!path->nodes[level])
20496702ed49SChris Mason 		return;
20506702ed49SChris Mason 
20515f39d397SChris Mason 	node = path->nodes[level];
2052925baeddSChris Mason 
20533c69faecSChris Mason 	search = btrfs_node_blockptr(node, slot);
20546b80053dSChris Mason 	blocksize = btrfs_level_size(root, level - 1);
20556b80053dSChris Mason 	eb = btrfs_find_tree_block(root, search, blocksize);
20565f39d397SChris Mason 	if (eb) {
20575f39d397SChris Mason 		free_extent_buffer(eb);
20583c69faecSChris Mason 		return;
20593c69faecSChris Mason 	}
20603c69faecSChris Mason 
2061a7175319SChris Mason 	target = search;
20626b80053dSChris Mason 
20635f39d397SChris Mason 	nritems = btrfs_header_nritems(node);
20646b80053dSChris Mason 	nr = slot;
206525b8b936SJosef Bacik 
20663c69faecSChris Mason 	while (1) {
20676b80053dSChris Mason 		if (direction < 0) {
20686b80053dSChris Mason 			if (nr == 0)
20693c69faecSChris Mason 				break;
20706b80053dSChris Mason 			nr--;
20716b80053dSChris Mason 		} else if (direction > 0) {
20726b80053dSChris Mason 			nr++;
20736b80053dSChris Mason 			if (nr >= nritems)
20746b80053dSChris Mason 				break;
20753c69faecSChris Mason 		}
207601f46658SChris Mason 		if (path->reada < 0 && objectid) {
207701f46658SChris Mason 			btrfs_node_key(node, &disk_key, nr);
207801f46658SChris Mason 			if (btrfs_disk_key_objectid(&disk_key) != objectid)
207901f46658SChris Mason 				break;
208001f46658SChris Mason 		}
20816b80053dSChris Mason 		search = btrfs_node_blockptr(node, nr);
2082a7175319SChris Mason 		if ((search <= target && target - search <= 65536) ||
2083a7175319SChris Mason 		    (search > target && search - target <= 65536)) {
2084cb25c2eaSJosef Bacik 			gen = btrfs_node_ptr_generation(node, nr);
2085cb25c2eaSJosef Bacik 			readahead_tree_block(root, search, blocksize, gen);
20866b80053dSChris Mason 			nread += blocksize;
20873c69faecSChris Mason 		}
20886b80053dSChris Mason 		nscan++;
2089a7175319SChris Mason 		if ((nread > 65536 || nscan > 32))
20906b80053dSChris Mason 			break;
20913c69faecSChris Mason 	}
20923c69faecSChris Mason }
2093925baeddSChris Mason 
2094d352ac68SChris Mason /*
2095b4ce94deSChris Mason  * returns -EAGAIN if it had to drop the path, or zero if everything was in
2096b4ce94deSChris Mason  * cache
2097b4ce94deSChris Mason  */
2098b4ce94deSChris Mason static noinline int reada_for_balance(struct btrfs_root *root,
2099b4ce94deSChris Mason 				      struct btrfs_path *path, int level)
2100b4ce94deSChris Mason {
2101b4ce94deSChris Mason 	int slot;
2102b4ce94deSChris Mason 	int nritems;
2103b4ce94deSChris Mason 	struct extent_buffer *parent;
2104b4ce94deSChris Mason 	struct extent_buffer *eb;
2105b4ce94deSChris Mason 	u64 gen;
2106b4ce94deSChris Mason 	u64 block1 = 0;
2107b4ce94deSChris Mason 	u64 block2 = 0;
2108b4ce94deSChris Mason 	int ret = 0;
2109b4ce94deSChris Mason 	int blocksize;
2110b4ce94deSChris Mason 
21118c594ea8SChris Mason 	parent = path->nodes[level + 1];
2112b4ce94deSChris Mason 	if (!parent)
2113b4ce94deSChris Mason 		return 0;
2114b4ce94deSChris Mason 
2115b4ce94deSChris Mason 	nritems = btrfs_header_nritems(parent);
21168c594ea8SChris Mason 	slot = path->slots[level + 1];
2117b4ce94deSChris Mason 	blocksize = btrfs_level_size(root, level);
2118b4ce94deSChris Mason 
2119b4ce94deSChris Mason 	if (slot > 0) {
2120b4ce94deSChris Mason 		block1 = btrfs_node_blockptr(parent, slot - 1);
2121b4ce94deSChris Mason 		gen = btrfs_node_ptr_generation(parent, slot - 1);
2122b4ce94deSChris Mason 		eb = btrfs_find_tree_block(root, block1, blocksize);
2123b9fab919SChris Mason 		/*
2124b9fab919SChris Mason 		 * if we get -eagain from btrfs_buffer_uptodate, we
2125b9fab919SChris Mason 		 * don't want to return eagain here.  That will loop
2126b9fab919SChris Mason 		 * forever
2127b9fab919SChris Mason 		 */
2128b9fab919SChris Mason 		if (eb && btrfs_buffer_uptodate(eb, gen, 1) != 0)
2129b4ce94deSChris Mason 			block1 = 0;
2130b4ce94deSChris Mason 		free_extent_buffer(eb);
2131b4ce94deSChris Mason 	}
21328c594ea8SChris Mason 	if (slot + 1 < nritems) {
2133b4ce94deSChris Mason 		block2 = btrfs_node_blockptr(parent, slot + 1);
2134b4ce94deSChris Mason 		gen = btrfs_node_ptr_generation(parent, slot + 1);
2135b4ce94deSChris Mason 		eb = btrfs_find_tree_block(root, block2, blocksize);
2136b9fab919SChris Mason 		if (eb && btrfs_buffer_uptodate(eb, gen, 1) != 0)
2137b4ce94deSChris Mason 			block2 = 0;
2138b4ce94deSChris Mason 		free_extent_buffer(eb);
2139b4ce94deSChris Mason 	}
2140b4ce94deSChris Mason 	if (block1 || block2) {
2141b4ce94deSChris Mason 		ret = -EAGAIN;
21428c594ea8SChris Mason 
21438c594ea8SChris Mason 		/* release the whole path */
2144b3b4aa74SDavid Sterba 		btrfs_release_path(path);
21458c594ea8SChris Mason 
21468c594ea8SChris Mason 		/* read the blocks */
2147b4ce94deSChris Mason 		if (block1)
2148b4ce94deSChris Mason 			readahead_tree_block(root, block1, blocksize, 0);
2149b4ce94deSChris Mason 		if (block2)
2150b4ce94deSChris Mason 			readahead_tree_block(root, block2, blocksize, 0);
2151b4ce94deSChris Mason 
2152b4ce94deSChris Mason 		if (block1) {
2153b4ce94deSChris Mason 			eb = read_tree_block(root, block1, blocksize, 0);
2154b4ce94deSChris Mason 			free_extent_buffer(eb);
2155b4ce94deSChris Mason 		}
21568c594ea8SChris Mason 		if (block2) {
2157b4ce94deSChris Mason 			eb = read_tree_block(root, block2, blocksize, 0);
2158b4ce94deSChris Mason 			free_extent_buffer(eb);
2159b4ce94deSChris Mason 		}
2160b4ce94deSChris Mason 	}
2161b4ce94deSChris Mason 	return ret;
2162b4ce94deSChris Mason }
2163b4ce94deSChris Mason 
2164b4ce94deSChris Mason 
2165b4ce94deSChris Mason /*
2166d397712bSChris Mason  * when we walk down the tree, it is usually safe to unlock the higher layers
2167d397712bSChris Mason  * in the tree.  The exceptions are when our path goes through slot 0, because
2168d397712bSChris Mason  * operations on the tree might require changing key pointers higher up in the
2169d397712bSChris Mason  * tree.
2170d352ac68SChris Mason  *
2171d397712bSChris Mason  * callers might also have set path->keep_locks, which tells this code to keep
2172d397712bSChris Mason  * the lock if the path points to the last slot in the block.  This is part of
2173d397712bSChris Mason  * walking through the tree, and selecting the next slot in the higher block.
2174d352ac68SChris Mason  *
2175d397712bSChris Mason  * lowest_unlock sets the lowest level in the tree we're allowed to unlock.  so
2176d397712bSChris Mason  * if lowest_unlock is 1, level 0 won't be unlocked
2177d352ac68SChris Mason  */
2178e02119d5SChris Mason static noinline void unlock_up(struct btrfs_path *path, int level,
2179f7c79f30SChris Mason 			       int lowest_unlock, int min_write_lock_level,
2180f7c79f30SChris Mason 			       int *write_lock_level)
2181925baeddSChris Mason {
2182925baeddSChris Mason 	int i;
2183925baeddSChris Mason 	int skip_level = level;
2184051e1b9fSChris Mason 	int no_skips = 0;
2185925baeddSChris Mason 	struct extent_buffer *t;
2186925baeddSChris Mason 
2187925baeddSChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2188925baeddSChris Mason 		if (!path->nodes[i])
2189925baeddSChris Mason 			break;
2190925baeddSChris Mason 		if (!path->locks[i])
2191925baeddSChris Mason 			break;
2192051e1b9fSChris Mason 		if (!no_skips && path->slots[i] == 0) {
2193925baeddSChris Mason 			skip_level = i + 1;
2194925baeddSChris Mason 			continue;
2195925baeddSChris Mason 		}
2196051e1b9fSChris Mason 		if (!no_skips && path->keep_locks) {
2197925baeddSChris Mason 			u32 nritems;
2198925baeddSChris Mason 			t = path->nodes[i];
2199925baeddSChris Mason 			nritems = btrfs_header_nritems(t);
2200051e1b9fSChris Mason 			if (nritems < 1 || path->slots[i] >= nritems - 1) {
2201925baeddSChris Mason 				skip_level = i + 1;
2202925baeddSChris Mason 				continue;
2203925baeddSChris Mason 			}
2204925baeddSChris Mason 		}
2205051e1b9fSChris Mason 		if (skip_level < i && i >= lowest_unlock)
2206051e1b9fSChris Mason 			no_skips = 1;
2207051e1b9fSChris Mason 
2208925baeddSChris Mason 		t = path->nodes[i];
2209925baeddSChris Mason 		if (i >= lowest_unlock && i > skip_level && path->locks[i]) {
2210bd681513SChris Mason 			btrfs_tree_unlock_rw(t, path->locks[i]);
2211925baeddSChris Mason 			path->locks[i] = 0;
2212f7c79f30SChris Mason 			if (write_lock_level &&
2213f7c79f30SChris Mason 			    i > min_write_lock_level &&
2214f7c79f30SChris Mason 			    i <= *write_lock_level) {
2215f7c79f30SChris Mason 				*write_lock_level = i - 1;
2216f7c79f30SChris Mason 			}
2217925baeddSChris Mason 		}
2218925baeddSChris Mason 	}
2219925baeddSChris Mason }
2220925baeddSChris Mason 
22213c69faecSChris Mason /*
2222b4ce94deSChris Mason  * This releases any locks held in the path starting at level and
2223b4ce94deSChris Mason  * going all the way up to the root.
2224b4ce94deSChris Mason  *
2225b4ce94deSChris Mason  * btrfs_search_slot will keep the lock held on higher nodes in a few
2226b4ce94deSChris Mason  * corner cases, such as COW of the block at slot zero in the node.  This
2227b4ce94deSChris Mason  * ignores those rules, and it should only be called when there are no
2228b4ce94deSChris Mason  * more updates to be done higher up in the tree.
2229b4ce94deSChris Mason  */
2230b4ce94deSChris Mason noinline void btrfs_unlock_up_safe(struct btrfs_path *path, int level)
2231b4ce94deSChris Mason {
2232b4ce94deSChris Mason 	int i;
2233b4ce94deSChris Mason 
22345d4f98a2SYan Zheng 	if (path->keep_locks)
2235b4ce94deSChris Mason 		return;
2236b4ce94deSChris Mason 
2237b4ce94deSChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2238b4ce94deSChris Mason 		if (!path->nodes[i])
223912f4daccSChris Mason 			continue;
2240b4ce94deSChris Mason 		if (!path->locks[i])
224112f4daccSChris Mason 			continue;
2242bd681513SChris Mason 		btrfs_tree_unlock_rw(path->nodes[i], path->locks[i]);
2243b4ce94deSChris Mason 		path->locks[i] = 0;
2244b4ce94deSChris Mason 	}
2245b4ce94deSChris Mason }
2246b4ce94deSChris Mason 
2247b4ce94deSChris Mason /*
2248c8c42864SChris Mason  * helper function for btrfs_search_slot.  The goal is to find a block
2249c8c42864SChris Mason  * in cache without setting the path to blocking.  If we find the block
2250c8c42864SChris Mason  * we return zero and the path is unchanged.
2251c8c42864SChris Mason  *
2252c8c42864SChris Mason  * If we can't find the block, we set the path blocking and do some
2253c8c42864SChris Mason  * reada.  -EAGAIN is returned and the search must be repeated.
2254c8c42864SChris Mason  */
2255c8c42864SChris Mason static int
2256c8c42864SChris Mason read_block_for_search(struct btrfs_trans_handle *trans,
2257c8c42864SChris Mason 		       struct btrfs_root *root, struct btrfs_path *p,
2258c8c42864SChris Mason 		       struct extent_buffer **eb_ret, int level, int slot,
22595d9e75c4SJan Schmidt 		       struct btrfs_key *key, u64 time_seq)
2260c8c42864SChris Mason {
2261c8c42864SChris Mason 	u64 blocknr;
2262c8c42864SChris Mason 	u64 gen;
2263c8c42864SChris Mason 	u32 blocksize;
2264c8c42864SChris Mason 	struct extent_buffer *b = *eb_ret;
2265c8c42864SChris Mason 	struct extent_buffer *tmp;
226676a05b35SChris Mason 	int ret;
2267c8c42864SChris Mason 
2268c8c42864SChris Mason 	blocknr = btrfs_node_blockptr(b, slot);
2269c8c42864SChris Mason 	gen = btrfs_node_ptr_generation(b, slot);
2270c8c42864SChris Mason 	blocksize = btrfs_level_size(root, level - 1);
2271c8c42864SChris Mason 
2272c8c42864SChris Mason 	tmp = btrfs_find_tree_block(root, blocknr, blocksize);
2273cb44921aSChris Mason 	if (tmp) {
2274b9fab919SChris Mason 		/* first we do an atomic uptodate check */
2275b9fab919SChris Mason 		if (btrfs_buffer_uptodate(tmp, 0, 1) > 0) {
2276b9fab919SChris Mason 			if (btrfs_buffer_uptodate(tmp, gen, 1) > 0) {
227776a05b35SChris Mason 				/*
2278cb44921aSChris Mason 				 * we found an up to date block without
2279cb44921aSChris Mason 				 * sleeping, return
228076a05b35SChris Mason 				 * right away
228176a05b35SChris Mason 				 */
2282c8c42864SChris Mason 				*eb_ret = tmp;
2283c8c42864SChris Mason 				return 0;
2284c8c42864SChris Mason 			}
2285cb44921aSChris Mason 			/* the pages were up to date, but we failed
2286cb44921aSChris Mason 			 * the generation number check.  Do a full
2287cb44921aSChris Mason 			 * read for the generation number that is correct.
2288cb44921aSChris Mason 			 * We must do this without dropping locks so
2289cb44921aSChris Mason 			 * we can trust our generation number
2290cb44921aSChris Mason 			 */
2291cb44921aSChris Mason 			free_extent_buffer(tmp);
2292bd681513SChris Mason 			btrfs_set_path_blocking(p);
2293bd681513SChris Mason 
2294b9fab919SChris Mason 			/* now we're allowed to do a blocking uptodate check */
2295cb44921aSChris Mason 			tmp = read_tree_block(root, blocknr, blocksize, gen);
2296b9fab919SChris Mason 			if (tmp && btrfs_buffer_uptodate(tmp, gen, 0) > 0) {
2297cb44921aSChris Mason 				*eb_ret = tmp;
2298cb44921aSChris Mason 				return 0;
2299cb44921aSChris Mason 			}
2300cb44921aSChris Mason 			free_extent_buffer(tmp);
2301b3b4aa74SDavid Sterba 			btrfs_release_path(p);
2302cb44921aSChris Mason 			return -EIO;
2303cb44921aSChris Mason 		}
2304cb44921aSChris Mason 	}
2305c8c42864SChris Mason 
2306c8c42864SChris Mason 	/*
2307c8c42864SChris Mason 	 * reduce lock contention at high levels
2308c8c42864SChris Mason 	 * of the btree by dropping locks before
230976a05b35SChris Mason 	 * we read.  Don't release the lock on the current
231076a05b35SChris Mason 	 * level because we need to walk this node to figure
231176a05b35SChris Mason 	 * out which blocks to read.
2312c8c42864SChris Mason 	 */
23138c594ea8SChris Mason 	btrfs_unlock_up_safe(p, level + 1);
23148c594ea8SChris Mason 	btrfs_set_path_blocking(p);
23158c594ea8SChris Mason 
2316c8c42864SChris Mason 	free_extent_buffer(tmp);
2317c8c42864SChris Mason 	if (p->reada)
2318c8c42864SChris Mason 		reada_for_search(root, p, level, slot, key->objectid);
2319c8c42864SChris Mason 
2320b3b4aa74SDavid Sterba 	btrfs_release_path(p);
232176a05b35SChris Mason 
232276a05b35SChris Mason 	ret = -EAGAIN;
23235bdd3536SYan, Zheng 	tmp = read_tree_block(root, blocknr, blocksize, 0);
232476a05b35SChris Mason 	if (tmp) {
232576a05b35SChris Mason 		/*
232676a05b35SChris Mason 		 * If the read above didn't mark this buffer up to date,
232776a05b35SChris Mason 		 * it will never end up being up to date.  Set ret to EIO now
232876a05b35SChris Mason 		 * and give up so that our caller doesn't loop forever
232976a05b35SChris Mason 		 * on our EAGAINs.
233076a05b35SChris Mason 		 */
2331b9fab919SChris Mason 		if (!btrfs_buffer_uptodate(tmp, 0, 0))
233276a05b35SChris Mason 			ret = -EIO;
2333c8c42864SChris Mason 		free_extent_buffer(tmp);
233476a05b35SChris Mason 	}
233576a05b35SChris Mason 	return ret;
2336c8c42864SChris Mason }
2337c8c42864SChris Mason 
2338c8c42864SChris Mason /*
2339c8c42864SChris Mason  * helper function for btrfs_search_slot.  This does all of the checks
2340c8c42864SChris Mason  * for node-level blocks and does any balancing required based on
2341c8c42864SChris Mason  * the ins_len.
2342c8c42864SChris Mason  *
2343c8c42864SChris Mason  * If no extra work was required, zero is returned.  If we had to
2344c8c42864SChris Mason  * drop the path, -EAGAIN is returned and btrfs_search_slot must
2345c8c42864SChris Mason  * start over
2346c8c42864SChris Mason  */
2347c8c42864SChris Mason static int
2348c8c42864SChris Mason setup_nodes_for_search(struct btrfs_trans_handle *trans,
2349c8c42864SChris Mason 		       struct btrfs_root *root, struct btrfs_path *p,
2350bd681513SChris Mason 		       struct extent_buffer *b, int level, int ins_len,
2351bd681513SChris Mason 		       int *write_lock_level)
2352c8c42864SChris Mason {
2353c8c42864SChris Mason 	int ret;
2354c8c42864SChris Mason 	if ((p->search_for_split || ins_len > 0) && btrfs_header_nritems(b) >=
2355c8c42864SChris Mason 	    BTRFS_NODEPTRS_PER_BLOCK(root) - 3) {
2356c8c42864SChris Mason 		int sret;
2357c8c42864SChris Mason 
2358bd681513SChris Mason 		if (*write_lock_level < level + 1) {
2359bd681513SChris Mason 			*write_lock_level = level + 1;
2360bd681513SChris Mason 			btrfs_release_path(p);
2361bd681513SChris Mason 			goto again;
2362bd681513SChris Mason 		}
2363bd681513SChris Mason 
2364c8c42864SChris Mason 		sret = reada_for_balance(root, p, level);
2365c8c42864SChris Mason 		if (sret)
2366c8c42864SChris Mason 			goto again;
2367c8c42864SChris Mason 
2368c8c42864SChris Mason 		btrfs_set_path_blocking(p);
2369c8c42864SChris Mason 		sret = split_node(trans, root, p, level);
2370bd681513SChris Mason 		btrfs_clear_path_blocking(p, NULL, 0);
2371c8c42864SChris Mason 
2372c8c42864SChris Mason 		BUG_ON(sret > 0);
2373c8c42864SChris Mason 		if (sret) {
2374c8c42864SChris Mason 			ret = sret;
2375c8c42864SChris Mason 			goto done;
2376c8c42864SChris Mason 		}
2377c8c42864SChris Mason 		b = p->nodes[level];
2378c8c42864SChris Mason 	} else if (ins_len < 0 && btrfs_header_nritems(b) <
2379cfbb9308SChris Mason 		   BTRFS_NODEPTRS_PER_BLOCK(root) / 2) {
2380c8c42864SChris Mason 		int sret;
2381c8c42864SChris Mason 
2382bd681513SChris Mason 		if (*write_lock_level < level + 1) {
2383bd681513SChris Mason 			*write_lock_level = level + 1;
2384bd681513SChris Mason 			btrfs_release_path(p);
2385bd681513SChris Mason 			goto again;
2386bd681513SChris Mason 		}
2387bd681513SChris Mason 
2388c8c42864SChris Mason 		sret = reada_for_balance(root, p, level);
2389c8c42864SChris Mason 		if (sret)
2390c8c42864SChris Mason 			goto again;
2391c8c42864SChris Mason 
2392c8c42864SChris Mason 		btrfs_set_path_blocking(p);
2393c8c42864SChris Mason 		sret = balance_level(trans, root, p, level);
2394bd681513SChris Mason 		btrfs_clear_path_blocking(p, NULL, 0);
2395c8c42864SChris Mason 
2396c8c42864SChris Mason 		if (sret) {
2397c8c42864SChris Mason 			ret = sret;
2398c8c42864SChris Mason 			goto done;
2399c8c42864SChris Mason 		}
2400c8c42864SChris Mason 		b = p->nodes[level];
2401c8c42864SChris Mason 		if (!b) {
2402b3b4aa74SDavid Sterba 			btrfs_release_path(p);
2403c8c42864SChris Mason 			goto again;
2404c8c42864SChris Mason 		}
2405c8c42864SChris Mason 		BUG_ON(btrfs_header_nritems(b) == 1);
2406c8c42864SChris Mason 	}
2407c8c42864SChris Mason 	return 0;
2408c8c42864SChris Mason 
2409c8c42864SChris Mason again:
2410c8c42864SChris Mason 	ret = -EAGAIN;
2411c8c42864SChris Mason done:
2412c8c42864SChris Mason 	return ret;
2413c8c42864SChris Mason }
2414c8c42864SChris Mason 
2415c8c42864SChris Mason /*
241674123bd7SChris Mason  * look for key in the tree.  path is filled in with nodes along the way
241774123bd7SChris Mason  * if key is found, we return zero and you can find the item in the leaf
241874123bd7SChris Mason  * level of the path (level 0)
241974123bd7SChris Mason  *
242074123bd7SChris Mason  * If the key isn't found, the path points to the slot where it should
2421aa5d6bedSChris Mason  * be inserted, and 1 is returned.  If there are other errors during the
2422aa5d6bedSChris Mason  * search a negative error number is returned.
242397571fd0SChris Mason  *
242497571fd0SChris Mason  * if ins_len > 0, nodes and leaves will be split as we walk down the
242597571fd0SChris Mason  * tree.  if ins_len < 0, nodes will be merged as we walk down the tree (if
242697571fd0SChris Mason  * possible)
242774123bd7SChris Mason  */
2428e089f05cSChris Mason int btrfs_search_slot(struct btrfs_trans_handle *trans, struct btrfs_root
2429e089f05cSChris Mason 		      *root, struct btrfs_key *key, struct btrfs_path *p, int
2430e089f05cSChris Mason 		      ins_len, int cow)
2431be0e5c09SChris Mason {
24325f39d397SChris Mason 	struct extent_buffer *b;
2433be0e5c09SChris Mason 	int slot;
2434be0e5c09SChris Mason 	int ret;
243533c66f43SYan Zheng 	int err;
2436be0e5c09SChris Mason 	int level;
2437925baeddSChris Mason 	int lowest_unlock = 1;
2438bd681513SChris Mason 	int root_lock;
2439bd681513SChris Mason 	/* everything at write_lock_level or lower must be write locked */
2440bd681513SChris Mason 	int write_lock_level = 0;
24419f3a7427SChris Mason 	u8 lowest_level = 0;
2442f7c79f30SChris Mason 	int min_write_lock_level;
24439f3a7427SChris Mason 
24446702ed49SChris Mason 	lowest_level = p->lowest_level;
2445323ac95bSChris Mason 	WARN_ON(lowest_level && ins_len > 0);
244622b0ebdaSChris Mason 	WARN_ON(p->nodes[0] != NULL);
244725179201SJosef Bacik 
2448bd681513SChris Mason 	if (ins_len < 0) {
2449925baeddSChris Mason 		lowest_unlock = 2;
245065b51a00SChris Mason 
2451bd681513SChris Mason 		/* when we are removing items, we might have to go up to level
2452bd681513SChris Mason 		 * two as we update tree pointers  Make sure we keep write
2453bd681513SChris Mason 		 * for those levels as well
2454bd681513SChris Mason 		 */
2455bd681513SChris Mason 		write_lock_level = 2;
2456bd681513SChris Mason 	} else if (ins_len > 0) {
2457bd681513SChris Mason 		/*
2458bd681513SChris Mason 		 * for inserting items, make sure we have a write lock on
2459bd681513SChris Mason 		 * level 1 so we can update keys
2460bd681513SChris Mason 		 */
2461bd681513SChris Mason 		write_lock_level = 1;
2462bd681513SChris Mason 	}
2463bd681513SChris Mason 
2464bd681513SChris Mason 	if (!cow)
2465bd681513SChris Mason 		write_lock_level = -1;
2466bd681513SChris Mason 
2467bd681513SChris Mason 	if (cow && (p->keep_locks || p->lowest_level))
2468bd681513SChris Mason 		write_lock_level = BTRFS_MAX_LEVEL;
2469bd681513SChris Mason 
2470f7c79f30SChris Mason 	min_write_lock_level = write_lock_level;
2471f7c79f30SChris Mason 
2472bb803951SChris Mason again:
2473bd681513SChris Mason 	/*
2474bd681513SChris Mason 	 * we try very hard to do read locks on the root
2475bd681513SChris Mason 	 */
2476bd681513SChris Mason 	root_lock = BTRFS_READ_LOCK;
2477bd681513SChris Mason 	level = 0;
24785d4f98a2SYan Zheng 	if (p->search_commit_root) {
2479bd681513SChris Mason 		/*
2480bd681513SChris Mason 		 * the commit roots are read only
2481bd681513SChris Mason 		 * so we always do read locks
2482bd681513SChris Mason 		 */
24835d4f98a2SYan Zheng 		b = root->commit_root;
24845d4f98a2SYan Zheng 		extent_buffer_get(b);
2485bd681513SChris Mason 		level = btrfs_header_level(b);
24865d4f98a2SYan Zheng 		if (!p->skip_locking)
2487bd681513SChris Mason 			btrfs_tree_read_lock(b);
24885d4f98a2SYan Zheng 	} else {
2489bd681513SChris Mason 		if (p->skip_locking) {
24905cd57b2cSChris Mason 			b = btrfs_root_node(root);
2491bd681513SChris Mason 			level = btrfs_header_level(b);
2492bd681513SChris Mason 		} else {
2493bd681513SChris Mason 			/* we don't know the level of the root node
2494bd681513SChris Mason 			 * until we actually have it read locked
2495bd681513SChris Mason 			 */
2496bd681513SChris Mason 			b = btrfs_read_lock_root_node(root);
2497bd681513SChris Mason 			level = btrfs_header_level(b);
2498bd681513SChris Mason 			if (level <= write_lock_level) {
2499bd681513SChris Mason 				/* whoops, must trade for write lock */
2500bd681513SChris Mason 				btrfs_tree_read_unlock(b);
2501bd681513SChris Mason 				free_extent_buffer(b);
2502925baeddSChris Mason 				b = btrfs_lock_root_node(root);
2503bd681513SChris Mason 				root_lock = BTRFS_WRITE_LOCK;
2504bd681513SChris Mason 
2505bd681513SChris Mason 				/* the level might have changed, check again */
2506bd681513SChris Mason 				level = btrfs_header_level(b);
25075d4f98a2SYan Zheng 			}
2508bd681513SChris Mason 		}
2509bd681513SChris Mason 	}
2510bd681513SChris Mason 	p->nodes[level] = b;
2511bd681513SChris Mason 	if (!p->skip_locking)
2512bd681513SChris Mason 		p->locks[level] = root_lock;
2513925baeddSChris Mason 
2514eb60ceacSChris Mason 	while (b) {
25155f39d397SChris Mason 		level = btrfs_header_level(b);
251665b51a00SChris Mason 
251765b51a00SChris Mason 		/*
251865b51a00SChris Mason 		 * setup the path here so we can release it under lock
251965b51a00SChris Mason 		 * contention with the cow code
252065b51a00SChris Mason 		 */
252102217ed2SChris Mason 		if (cow) {
2522c8c42864SChris Mason 			/*
2523c8c42864SChris Mason 			 * if we don't really need to cow this block
2524c8c42864SChris Mason 			 * then we don't want to set the path blocking,
2525c8c42864SChris Mason 			 * so we test it here
2526c8c42864SChris Mason 			 */
25275d4f98a2SYan Zheng 			if (!should_cow_block(trans, root, b))
252865b51a00SChris Mason 				goto cow_done;
25295d4f98a2SYan Zheng 
2530b4ce94deSChris Mason 			btrfs_set_path_blocking(p);
2531b4ce94deSChris Mason 
2532bd681513SChris Mason 			/*
2533bd681513SChris Mason 			 * must have write locks on this node and the
2534bd681513SChris Mason 			 * parent
2535bd681513SChris Mason 			 */
2536bd681513SChris Mason 			if (level + 1 > write_lock_level) {
2537bd681513SChris Mason 				write_lock_level = level + 1;
2538bd681513SChris Mason 				btrfs_release_path(p);
2539bd681513SChris Mason 				goto again;
2540bd681513SChris Mason 			}
2541bd681513SChris Mason 
254233c66f43SYan Zheng 			err = btrfs_cow_block(trans, root, b,
2543e20d96d6SChris Mason 					      p->nodes[level + 1],
25449fa8cfe7SChris Mason 					      p->slots[level + 1], &b);
254533c66f43SYan Zheng 			if (err) {
254633c66f43SYan Zheng 				ret = err;
254765b51a00SChris Mason 				goto done;
254854aa1f4dSChris Mason 			}
254902217ed2SChris Mason 		}
255065b51a00SChris Mason cow_done:
255102217ed2SChris Mason 		BUG_ON(!cow && ins_len);
255265b51a00SChris Mason 
2553eb60ceacSChris Mason 		p->nodes[level] = b;
2554bd681513SChris Mason 		btrfs_clear_path_blocking(p, NULL, 0);
2555b4ce94deSChris Mason 
2556b4ce94deSChris Mason 		/*
2557b4ce94deSChris Mason 		 * we have a lock on b and as long as we aren't changing
2558b4ce94deSChris Mason 		 * the tree, there is no way to for the items in b to change.
2559b4ce94deSChris Mason 		 * It is safe to drop the lock on our parent before we
2560b4ce94deSChris Mason 		 * go through the expensive btree search on b.
2561b4ce94deSChris Mason 		 *
2562b4ce94deSChris Mason 		 * If cow is true, then we might be changing slot zero,
2563b4ce94deSChris Mason 		 * which may require changing the parent.  So, we can't
2564b4ce94deSChris Mason 		 * drop the lock until after we know which slot we're
2565b4ce94deSChris Mason 		 * operating on.
2566b4ce94deSChris Mason 		 */
2567b4ce94deSChris Mason 		if (!cow)
2568b4ce94deSChris Mason 			btrfs_unlock_up_safe(p, level + 1);
2569b4ce94deSChris Mason 
25705f39d397SChris Mason 		ret = bin_search(b, key, level, &slot);
2571b4ce94deSChris Mason 
25725f39d397SChris Mason 		if (level != 0) {
257333c66f43SYan Zheng 			int dec = 0;
257433c66f43SYan Zheng 			if (ret && slot > 0) {
257533c66f43SYan Zheng 				dec = 1;
2576be0e5c09SChris Mason 				slot -= 1;
257733c66f43SYan Zheng 			}
2578be0e5c09SChris Mason 			p->slots[level] = slot;
257933c66f43SYan Zheng 			err = setup_nodes_for_search(trans, root, p, b, level,
2580bd681513SChris Mason 					     ins_len, &write_lock_level);
258133c66f43SYan Zheng 			if (err == -EAGAIN)
2582b4ce94deSChris Mason 				goto again;
258333c66f43SYan Zheng 			if (err) {
258433c66f43SYan Zheng 				ret = err;
258565b51a00SChris Mason 				goto done;
258633c66f43SYan Zheng 			}
25875c680ed6SChris Mason 			b = p->nodes[level];
25885c680ed6SChris Mason 			slot = p->slots[level];
2589b4ce94deSChris Mason 
2590bd681513SChris Mason 			/*
2591bd681513SChris Mason 			 * slot 0 is special, if we change the key
2592bd681513SChris Mason 			 * we have to update the parent pointer
2593bd681513SChris Mason 			 * which means we must have a write lock
2594bd681513SChris Mason 			 * on the parent
2595bd681513SChris Mason 			 */
2596bd681513SChris Mason 			if (slot == 0 && cow &&
2597bd681513SChris Mason 			    write_lock_level < level + 1) {
2598bd681513SChris Mason 				write_lock_level = level + 1;
2599bd681513SChris Mason 				btrfs_release_path(p);
2600bd681513SChris Mason 				goto again;
2601bd681513SChris Mason 			}
2602bd681513SChris Mason 
2603f7c79f30SChris Mason 			unlock_up(p, level, lowest_unlock,
2604f7c79f30SChris Mason 				  min_write_lock_level, &write_lock_level);
2605f9efa9c7SChris Mason 
2606925baeddSChris Mason 			if (level == lowest_level) {
260733c66f43SYan Zheng 				if (dec)
260833c66f43SYan Zheng 					p->slots[level]++;
26095b21f2edSZheng Yan 				goto done;
2610925baeddSChris Mason 			}
2611ca7a79adSChris Mason 
261233c66f43SYan Zheng 			err = read_block_for_search(trans, root, p,
26135d9e75c4SJan Schmidt 						    &b, level, slot, key, 0);
261433c66f43SYan Zheng 			if (err == -EAGAIN)
2615051e1b9fSChris Mason 				goto again;
261633c66f43SYan Zheng 			if (err) {
261733c66f43SYan Zheng 				ret = err;
261876a05b35SChris Mason 				goto done;
261933c66f43SYan Zheng 			}
262076a05b35SChris Mason 
2621b4ce94deSChris Mason 			if (!p->skip_locking) {
2622bd681513SChris Mason 				level = btrfs_header_level(b);
2623bd681513SChris Mason 				if (level <= write_lock_level) {
2624bd681513SChris Mason 					err = btrfs_try_tree_write_lock(b);
262533c66f43SYan Zheng 					if (!err) {
2626b4ce94deSChris Mason 						btrfs_set_path_blocking(p);
2627925baeddSChris Mason 						btrfs_tree_lock(b);
2628bd681513SChris Mason 						btrfs_clear_path_blocking(p, b,
2629bd681513SChris Mason 								  BTRFS_WRITE_LOCK);
2630b4ce94deSChris Mason 					}
2631bd681513SChris Mason 					p->locks[level] = BTRFS_WRITE_LOCK;
2632bd681513SChris Mason 				} else {
2633bd681513SChris Mason 					err = btrfs_try_tree_read_lock(b);
2634bd681513SChris Mason 					if (!err) {
2635bd681513SChris Mason 						btrfs_set_path_blocking(p);
2636bd681513SChris Mason 						btrfs_tree_read_lock(b);
2637bd681513SChris Mason 						btrfs_clear_path_blocking(p, b,
2638bd681513SChris Mason 								  BTRFS_READ_LOCK);
2639bd681513SChris Mason 					}
2640bd681513SChris Mason 					p->locks[level] = BTRFS_READ_LOCK;
2641bd681513SChris Mason 				}
2642bd681513SChris Mason 				p->nodes[level] = b;
2643b4ce94deSChris Mason 			}
2644be0e5c09SChris Mason 		} else {
2645be0e5c09SChris Mason 			p->slots[level] = slot;
264687b29b20SYan Zheng 			if (ins_len > 0 &&
264787b29b20SYan Zheng 			    btrfs_leaf_free_space(root, b) < ins_len) {
2648bd681513SChris Mason 				if (write_lock_level < 1) {
2649bd681513SChris Mason 					write_lock_level = 1;
2650bd681513SChris Mason 					btrfs_release_path(p);
2651bd681513SChris Mason 					goto again;
2652bd681513SChris Mason 				}
2653bd681513SChris Mason 
2654b4ce94deSChris Mason 				btrfs_set_path_blocking(p);
265533c66f43SYan Zheng 				err = split_leaf(trans, root, key,
2656cc0c5538SChris Mason 						 p, ins_len, ret == 0);
2657bd681513SChris Mason 				btrfs_clear_path_blocking(p, NULL, 0);
2658b4ce94deSChris Mason 
265933c66f43SYan Zheng 				BUG_ON(err > 0);
266033c66f43SYan Zheng 				if (err) {
266133c66f43SYan Zheng 					ret = err;
266265b51a00SChris Mason 					goto done;
266365b51a00SChris Mason 				}
26645c680ed6SChris Mason 			}
2665459931ecSChris Mason 			if (!p->search_for_split)
2666f7c79f30SChris Mason 				unlock_up(p, level, lowest_unlock,
2667f7c79f30SChris Mason 					  min_write_lock_level, &write_lock_level);
266865b51a00SChris Mason 			goto done;
266965b51a00SChris Mason 		}
267065b51a00SChris Mason 	}
267165b51a00SChris Mason 	ret = 1;
267265b51a00SChris Mason done:
2673b4ce94deSChris Mason 	/*
2674b4ce94deSChris Mason 	 * we don't really know what they plan on doing with the path
2675b4ce94deSChris Mason 	 * from here on, so for now just mark it as blocking
2676b4ce94deSChris Mason 	 */
2677b9473439SChris Mason 	if (!p->leave_spinning)
2678b4ce94deSChris Mason 		btrfs_set_path_blocking(p);
267976a05b35SChris Mason 	if (ret < 0)
2680b3b4aa74SDavid Sterba 		btrfs_release_path(p);
2681be0e5c09SChris Mason 	return ret;
2682be0e5c09SChris Mason }
2683be0e5c09SChris Mason 
268474123bd7SChris Mason /*
26855d9e75c4SJan Schmidt  * Like btrfs_search_slot, this looks for a key in the given tree. It uses the
26865d9e75c4SJan Schmidt  * current state of the tree together with the operations recorded in the tree
26875d9e75c4SJan Schmidt  * modification log to search for the key in a previous version of this tree, as
26885d9e75c4SJan Schmidt  * denoted by the time_seq parameter.
26895d9e75c4SJan Schmidt  *
26905d9e75c4SJan Schmidt  * Naturally, there is no support for insert, delete or cow operations.
26915d9e75c4SJan Schmidt  *
26925d9e75c4SJan Schmidt  * The resulting path and return value will be set up as if we called
26935d9e75c4SJan Schmidt  * btrfs_search_slot at that point in time with ins_len and cow both set to 0.
26945d9e75c4SJan Schmidt  */
26955d9e75c4SJan Schmidt int btrfs_search_old_slot(struct btrfs_root *root, struct btrfs_key *key,
26965d9e75c4SJan Schmidt 			  struct btrfs_path *p, u64 time_seq)
26975d9e75c4SJan Schmidt {
26985d9e75c4SJan Schmidt 	struct extent_buffer *b;
26995d9e75c4SJan Schmidt 	int slot;
27005d9e75c4SJan Schmidt 	int ret;
27015d9e75c4SJan Schmidt 	int err;
27025d9e75c4SJan Schmidt 	int level;
27035d9e75c4SJan Schmidt 	int lowest_unlock = 1;
27045d9e75c4SJan Schmidt 	u8 lowest_level = 0;
27055d9e75c4SJan Schmidt 
27065d9e75c4SJan Schmidt 	lowest_level = p->lowest_level;
27075d9e75c4SJan Schmidt 	WARN_ON(p->nodes[0] != NULL);
27085d9e75c4SJan Schmidt 
27095d9e75c4SJan Schmidt 	if (p->search_commit_root) {
27105d9e75c4SJan Schmidt 		BUG_ON(time_seq);
27115d9e75c4SJan Schmidt 		return btrfs_search_slot(NULL, root, key, p, 0, 0);
27125d9e75c4SJan Schmidt 	}
27135d9e75c4SJan Schmidt 
27145d9e75c4SJan Schmidt again:
27155d9e75c4SJan Schmidt 	b = get_old_root(root, time_seq);
27165d9e75c4SJan Schmidt 	level = btrfs_header_level(b);
27175d9e75c4SJan Schmidt 	p->locks[level] = BTRFS_READ_LOCK;
27185d9e75c4SJan Schmidt 
27195d9e75c4SJan Schmidt 	while (b) {
27205d9e75c4SJan Schmidt 		level = btrfs_header_level(b);
27215d9e75c4SJan Schmidt 		p->nodes[level] = b;
27225d9e75c4SJan Schmidt 		btrfs_clear_path_blocking(p, NULL, 0);
27235d9e75c4SJan Schmidt 
27245d9e75c4SJan Schmidt 		/*
27255d9e75c4SJan Schmidt 		 * we have a lock on b and as long as we aren't changing
27265d9e75c4SJan Schmidt 		 * the tree, there is no way to for the items in b to change.
27275d9e75c4SJan Schmidt 		 * It is safe to drop the lock on our parent before we
27285d9e75c4SJan Schmidt 		 * go through the expensive btree search on b.
27295d9e75c4SJan Schmidt 		 */
27305d9e75c4SJan Schmidt 		btrfs_unlock_up_safe(p, level + 1);
27315d9e75c4SJan Schmidt 
27325d9e75c4SJan Schmidt 		ret = bin_search(b, key, level, &slot);
27335d9e75c4SJan Schmidt 
27345d9e75c4SJan Schmidt 		if (level != 0) {
27355d9e75c4SJan Schmidt 			int dec = 0;
27365d9e75c4SJan Schmidt 			if (ret && slot > 0) {
27375d9e75c4SJan Schmidt 				dec = 1;
27385d9e75c4SJan Schmidt 				slot -= 1;
27395d9e75c4SJan Schmidt 			}
27405d9e75c4SJan Schmidt 			p->slots[level] = slot;
27415d9e75c4SJan Schmidt 			unlock_up(p, level, lowest_unlock, 0, NULL);
27425d9e75c4SJan Schmidt 
27435d9e75c4SJan Schmidt 			if (level == lowest_level) {
27445d9e75c4SJan Schmidt 				if (dec)
27455d9e75c4SJan Schmidt 					p->slots[level]++;
27465d9e75c4SJan Schmidt 				goto done;
27475d9e75c4SJan Schmidt 			}
27485d9e75c4SJan Schmidt 
27495d9e75c4SJan Schmidt 			err = read_block_for_search(NULL, root, p, &b, level,
27505d9e75c4SJan Schmidt 						    slot, key, time_seq);
27515d9e75c4SJan Schmidt 			if (err == -EAGAIN)
27525d9e75c4SJan Schmidt 				goto again;
27535d9e75c4SJan Schmidt 			if (err) {
27545d9e75c4SJan Schmidt 				ret = err;
27555d9e75c4SJan Schmidt 				goto done;
27565d9e75c4SJan Schmidt 			}
27575d9e75c4SJan Schmidt 
27585d9e75c4SJan Schmidt 			level = btrfs_header_level(b);
27595d9e75c4SJan Schmidt 			err = btrfs_try_tree_read_lock(b);
27605d9e75c4SJan Schmidt 			if (!err) {
27615d9e75c4SJan Schmidt 				btrfs_set_path_blocking(p);
27625d9e75c4SJan Schmidt 				btrfs_tree_read_lock(b);
27635d9e75c4SJan Schmidt 				btrfs_clear_path_blocking(p, b,
27645d9e75c4SJan Schmidt 							  BTRFS_READ_LOCK);
27655d9e75c4SJan Schmidt 			}
27665d9e75c4SJan Schmidt 			p->locks[level] = BTRFS_READ_LOCK;
27675d9e75c4SJan Schmidt 			p->nodes[level] = b;
27685d9e75c4SJan Schmidt 			b = tree_mod_log_rewind(root->fs_info, b, time_seq);
27695d9e75c4SJan Schmidt 			if (b != p->nodes[level]) {
27705d9e75c4SJan Schmidt 				btrfs_tree_unlock_rw(p->nodes[level],
27715d9e75c4SJan Schmidt 						     p->locks[level]);
27725d9e75c4SJan Schmidt 				p->locks[level] = 0;
27735d9e75c4SJan Schmidt 				p->nodes[level] = b;
27745d9e75c4SJan Schmidt 			}
27755d9e75c4SJan Schmidt 		} else {
27765d9e75c4SJan Schmidt 			p->slots[level] = slot;
27775d9e75c4SJan Schmidt 			unlock_up(p, level, lowest_unlock, 0, NULL);
27785d9e75c4SJan Schmidt 			goto done;
27795d9e75c4SJan Schmidt 		}
27805d9e75c4SJan Schmidt 	}
27815d9e75c4SJan Schmidt 	ret = 1;
27825d9e75c4SJan Schmidt done:
27835d9e75c4SJan Schmidt 	if (!p->leave_spinning)
27845d9e75c4SJan Schmidt 		btrfs_set_path_blocking(p);
27855d9e75c4SJan Schmidt 	if (ret < 0)
27865d9e75c4SJan Schmidt 		btrfs_release_path(p);
27875d9e75c4SJan Schmidt 
27885d9e75c4SJan Schmidt 	return ret;
27895d9e75c4SJan Schmidt }
27905d9e75c4SJan Schmidt 
27915d9e75c4SJan Schmidt /*
279274123bd7SChris Mason  * adjust the pointers going up the tree, starting at level
279374123bd7SChris Mason  * making sure the right key of each node is points to 'key'.
279474123bd7SChris Mason  * This is used after shifting pointers to the left, so it stops
279574123bd7SChris Mason  * fixing up pointers when a given leaf/node is not in slot 0 of the
279674123bd7SChris Mason  * higher levels
2797aa5d6bedSChris Mason  *
279874123bd7SChris Mason  */
2799143bede5SJeff Mahoney static void fixup_low_keys(struct btrfs_trans_handle *trans,
28005f39d397SChris Mason 			   struct btrfs_root *root, struct btrfs_path *path,
28015f39d397SChris Mason 			   struct btrfs_disk_key *key, int level)
2802be0e5c09SChris Mason {
2803be0e5c09SChris Mason 	int i;
28045f39d397SChris Mason 	struct extent_buffer *t;
28055f39d397SChris Mason 
2806234b63a0SChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2807be0e5c09SChris Mason 		int tslot = path->slots[i];
2808eb60ceacSChris Mason 		if (!path->nodes[i])
2809be0e5c09SChris Mason 			break;
28105f39d397SChris Mason 		t = path->nodes[i];
2811f230475eSJan Schmidt 		tree_mod_log_set_node_key(root->fs_info, t, key, tslot, 1);
28125f39d397SChris Mason 		btrfs_set_node_key(t, key, tslot);
2813d6025579SChris Mason 		btrfs_mark_buffer_dirty(path->nodes[i]);
2814be0e5c09SChris Mason 		if (tslot != 0)
2815be0e5c09SChris Mason 			break;
2816be0e5c09SChris Mason 	}
2817be0e5c09SChris Mason }
2818be0e5c09SChris Mason 
281974123bd7SChris Mason /*
282031840ae1SZheng Yan  * update item key.
282131840ae1SZheng Yan  *
282231840ae1SZheng Yan  * This function isn't completely safe. It's the caller's responsibility
282331840ae1SZheng Yan  * that the new key won't break the order
282431840ae1SZheng Yan  */
2825143bede5SJeff Mahoney void btrfs_set_item_key_safe(struct btrfs_trans_handle *trans,
282631840ae1SZheng Yan 			     struct btrfs_root *root, struct btrfs_path *path,
282731840ae1SZheng Yan 			     struct btrfs_key *new_key)
282831840ae1SZheng Yan {
282931840ae1SZheng Yan 	struct btrfs_disk_key disk_key;
283031840ae1SZheng Yan 	struct extent_buffer *eb;
283131840ae1SZheng Yan 	int slot;
283231840ae1SZheng Yan 
283331840ae1SZheng Yan 	eb = path->nodes[0];
283431840ae1SZheng Yan 	slot = path->slots[0];
283531840ae1SZheng Yan 	if (slot > 0) {
283631840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot - 1);
2837143bede5SJeff Mahoney 		BUG_ON(comp_keys(&disk_key, new_key) >= 0);
283831840ae1SZheng Yan 	}
283931840ae1SZheng Yan 	if (slot < btrfs_header_nritems(eb) - 1) {
284031840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot + 1);
2841143bede5SJeff Mahoney 		BUG_ON(comp_keys(&disk_key, new_key) <= 0);
284231840ae1SZheng Yan 	}
284331840ae1SZheng Yan 
284431840ae1SZheng Yan 	btrfs_cpu_key_to_disk(&disk_key, new_key);
284531840ae1SZheng Yan 	btrfs_set_item_key(eb, &disk_key, slot);
284631840ae1SZheng Yan 	btrfs_mark_buffer_dirty(eb);
284731840ae1SZheng Yan 	if (slot == 0)
284831840ae1SZheng Yan 		fixup_low_keys(trans, root, path, &disk_key, 1);
284931840ae1SZheng Yan }
285031840ae1SZheng Yan 
285131840ae1SZheng Yan /*
285274123bd7SChris Mason  * try to push data from one node into the next node left in the
285379f95c82SChris Mason  * tree.
2854aa5d6bedSChris Mason  *
2855aa5d6bedSChris Mason  * returns 0 if some ptrs were pushed left, < 0 if there was some horrible
2856aa5d6bedSChris Mason  * error, and > 0 if there was no room in the left hand block.
285774123bd7SChris Mason  */
285898ed5174SChris Mason static int push_node_left(struct btrfs_trans_handle *trans,
285998ed5174SChris Mason 			  struct btrfs_root *root, struct extent_buffer *dst,
2860971a1f66SChris Mason 			  struct extent_buffer *src, int empty)
2861be0e5c09SChris Mason {
2862be0e5c09SChris Mason 	int push_items = 0;
2863bb803951SChris Mason 	int src_nritems;
2864bb803951SChris Mason 	int dst_nritems;
2865aa5d6bedSChris Mason 	int ret = 0;
2866be0e5c09SChris Mason 
28675f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
28685f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
2869123abc88SChris Mason 	push_items = BTRFS_NODEPTRS_PER_BLOCK(root) - dst_nritems;
28707bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
28717bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
287254aa1f4dSChris Mason 
2873bce4eae9SChris Mason 	if (!empty && src_nritems <= 8)
2874971a1f66SChris Mason 		return 1;
2875971a1f66SChris Mason 
2876d397712bSChris Mason 	if (push_items <= 0)
2877be0e5c09SChris Mason 		return 1;
2878be0e5c09SChris Mason 
2879bce4eae9SChris Mason 	if (empty) {
2880971a1f66SChris Mason 		push_items = min(src_nritems, push_items);
2881bce4eae9SChris Mason 		if (push_items < src_nritems) {
2882bce4eae9SChris Mason 			/* leave at least 8 pointers in the node if
2883bce4eae9SChris Mason 			 * we aren't going to empty it
2884bce4eae9SChris Mason 			 */
2885bce4eae9SChris Mason 			if (src_nritems - push_items < 8) {
2886bce4eae9SChris Mason 				if (push_items <= 8)
2887bce4eae9SChris Mason 					return 1;
2888bce4eae9SChris Mason 				push_items -= 8;
2889bce4eae9SChris Mason 			}
2890bce4eae9SChris Mason 		}
2891bce4eae9SChris Mason 	} else
2892bce4eae9SChris Mason 		push_items = min(src_nritems - 8, push_items);
289379f95c82SChris Mason 
2894f230475eSJan Schmidt 	tree_mod_log_eb_copy(root->fs_info, dst, src, dst_nritems, 0,
2895f230475eSJan Schmidt 			     push_items);
28965f39d397SChris Mason 	copy_extent_buffer(dst, src,
28975f39d397SChris Mason 			   btrfs_node_key_ptr_offset(dst_nritems),
28985f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
2899123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
29005f39d397SChris Mason 
2901bb803951SChris Mason 	if (push_items < src_nritems) {
2902f230475eSJan Schmidt 		tree_mod_log_eb_move(root->fs_info, src, 0, push_items,
2903f230475eSJan Schmidt 				     src_nritems - push_items);
29045f39d397SChris Mason 		memmove_extent_buffer(src, btrfs_node_key_ptr_offset(0),
29055f39d397SChris Mason 				      btrfs_node_key_ptr_offset(push_items),
2906e2fa7227SChris Mason 				      (src_nritems - push_items) *
2907123abc88SChris Mason 				      sizeof(struct btrfs_key_ptr));
2908bb803951SChris Mason 	}
29095f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
29105f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
29115f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
29125f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
291331840ae1SZheng Yan 
2914bb803951SChris Mason 	return ret;
2915be0e5c09SChris Mason }
2916be0e5c09SChris Mason 
291797571fd0SChris Mason /*
291879f95c82SChris Mason  * try to push data from one node into the next node right in the
291979f95c82SChris Mason  * tree.
292079f95c82SChris Mason  *
292179f95c82SChris Mason  * returns 0 if some ptrs were pushed, < 0 if there was some horrible
292279f95c82SChris Mason  * error, and > 0 if there was no room in the right hand block.
292379f95c82SChris Mason  *
292479f95c82SChris Mason  * this will  only push up to 1/2 the contents of the left node over
292579f95c82SChris Mason  */
29265f39d397SChris Mason static int balance_node_right(struct btrfs_trans_handle *trans,
29275f39d397SChris Mason 			      struct btrfs_root *root,
29285f39d397SChris Mason 			      struct extent_buffer *dst,
29295f39d397SChris Mason 			      struct extent_buffer *src)
293079f95c82SChris Mason {
293179f95c82SChris Mason 	int push_items = 0;
293279f95c82SChris Mason 	int max_push;
293379f95c82SChris Mason 	int src_nritems;
293479f95c82SChris Mason 	int dst_nritems;
293579f95c82SChris Mason 	int ret = 0;
293679f95c82SChris Mason 
29377bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
29387bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
29397bb86316SChris Mason 
29405f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
29415f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
2942123abc88SChris Mason 	push_items = BTRFS_NODEPTRS_PER_BLOCK(root) - dst_nritems;
2943d397712bSChris Mason 	if (push_items <= 0)
294479f95c82SChris Mason 		return 1;
2945bce4eae9SChris Mason 
2946d397712bSChris Mason 	if (src_nritems < 4)
2947bce4eae9SChris Mason 		return 1;
294879f95c82SChris Mason 
294979f95c82SChris Mason 	max_push = src_nritems / 2 + 1;
295079f95c82SChris Mason 	/* don't try to empty the node */
2951d397712bSChris Mason 	if (max_push >= src_nritems)
295279f95c82SChris Mason 		return 1;
2953252c38f0SYan 
295479f95c82SChris Mason 	if (max_push < push_items)
295579f95c82SChris Mason 		push_items = max_push;
295679f95c82SChris Mason 
2957f230475eSJan Schmidt 	tree_mod_log_eb_move(root->fs_info, dst, push_items, 0, dst_nritems);
29585f39d397SChris Mason 	memmove_extent_buffer(dst, btrfs_node_key_ptr_offset(push_items),
29595f39d397SChris Mason 				      btrfs_node_key_ptr_offset(0),
29605f39d397SChris Mason 				      (dst_nritems) *
29615f39d397SChris Mason 				      sizeof(struct btrfs_key_ptr));
2962d6025579SChris Mason 
2963f230475eSJan Schmidt 	tree_mod_log_eb_copy(root->fs_info, dst, src, 0,
2964f230475eSJan Schmidt 			     src_nritems - push_items, push_items);
29655f39d397SChris Mason 	copy_extent_buffer(dst, src,
29665f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
29675f39d397SChris Mason 			   btrfs_node_key_ptr_offset(src_nritems - push_items),
2968123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
296979f95c82SChris Mason 
29705f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
29715f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
297279f95c82SChris Mason 
29735f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
29745f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
297531840ae1SZheng Yan 
297679f95c82SChris Mason 	return ret;
297779f95c82SChris Mason }
297879f95c82SChris Mason 
297979f95c82SChris Mason /*
298097571fd0SChris Mason  * helper function to insert a new root level in the tree.
298197571fd0SChris Mason  * A new node is allocated, and a single item is inserted to
298297571fd0SChris Mason  * point to the existing root
2983aa5d6bedSChris Mason  *
2984aa5d6bedSChris Mason  * returns zero on success or < 0 on failure.
298597571fd0SChris Mason  */
2986d397712bSChris Mason static noinline int insert_new_root(struct btrfs_trans_handle *trans,
29875f39d397SChris Mason 			   struct btrfs_root *root,
29885f39d397SChris Mason 			   struct btrfs_path *path, int level)
298974123bd7SChris Mason {
29907bb86316SChris Mason 	u64 lower_gen;
29915f39d397SChris Mason 	struct extent_buffer *lower;
29925f39d397SChris Mason 	struct extent_buffer *c;
2993925baeddSChris Mason 	struct extent_buffer *old;
29945f39d397SChris Mason 	struct btrfs_disk_key lower_key;
29955c680ed6SChris Mason 
29965c680ed6SChris Mason 	BUG_ON(path->nodes[level]);
29975c680ed6SChris Mason 	BUG_ON(path->nodes[level-1] != root->node);
29985c680ed6SChris Mason 
29997bb86316SChris Mason 	lower = path->nodes[level-1];
30007bb86316SChris Mason 	if (level == 1)
30017bb86316SChris Mason 		btrfs_item_key(lower, &lower_key, 0);
30027bb86316SChris Mason 	else
30037bb86316SChris Mason 		btrfs_node_key(lower, &lower_key, 0);
30047bb86316SChris Mason 
300531840ae1SZheng Yan 	c = btrfs_alloc_free_block(trans, root, root->nodesize, 0,
30065d4f98a2SYan Zheng 				   root->root_key.objectid, &lower_key,
30075581a51aSJan Schmidt 				   level, root->node->start, 0);
30085f39d397SChris Mason 	if (IS_ERR(c))
30095f39d397SChris Mason 		return PTR_ERR(c);
3010925baeddSChris Mason 
3011f0486c68SYan, Zheng 	root_add_used(root, root->nodesize);
3012f0486c68SYan, Zheng 
30135d4f98a2SYan Zheng 	memset_extent_buffer(c, 0, 0, sizeof(struct btrfs_header));
30145f39d397SChris Mason 	btrfs_set_header_nritems(c, 1);
30155f39d397SChris Mason 	btrfs_set_header_level(c, level);
3016db94535dSChris Mason 	btrfs_set_header_bytenr(c, c->start);
30175f39d397SChris Mason 	btrfs_set_header_generation(c, trans->transid);
30185d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(c, BTRFS_MIXED_BACKREF_REV);
30195f39d397SChris Mason 	btrfs_set_header_owner(c, root->root_key.objectid);
3020d5719762SChris Mason 
30215f39d397SChris Mason 	write_extent_buffer(c, root->fs_info->fsid,
30225f39d397SChris Mason 			    (unsigned long)btrfs_header_fsid(c),
30235f39d397SChris Mason 			    BTRFS_FSID_SIZE);
3024e17cade2SChris Mason 
3025e17cade2SChris Mason 	write_extent_buffer(c, root->fs_info->chunk_tree_uuid,
3026e17cade2SChris Mason 			    (unsigned long)btrfs_header_chunk_tree_uuid(c),
3027e17cade2SChris Mason 			    BTRFS_UUID_SIZE);
3028e17cade2SChris Mason 
30295f39d397SChris Mason 	btrfs_set_node_key(c, &lower_key, 0);
3030db94535dSChris Mason 	btrfs_set_node_blockptr(c, 0, lower->start);
30317bb86316SChris Mason 	lower_gen = btrfs_header_generation(lower);
303231840ae1SZheng Yan 	WARN_ON(lower_gen != trans->transid);
30337bb86316SChris Mason 
30347bb86316SChris Mason 	btrfs_set_node_ptr_generation(c, 0, lower_gen);
30355f39d397SChris Mason 
30365f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
3037d5719762SChris Mason 
3038925baeddSChris Mason 	old = root->node;
3039f230475eSJan Schmidt 	tree_mod_log_set_root_pointer(root, c);
3040240f62c8SChris Mason 	rcu_assign_pointer(root->node, c);
3041925baeddSChris Mason 
3042925baeddSChris Mason 	/* the super has an extra ref to root->node */
3043925baeddSChris Mason 	free_extent_buffer(old);
3044925baeddSChris Mason 
30450b86a832SChris Mason 	add_root_to_dirty_list(root);
30465f39d397SChris Mason 	extent_buffer_get(c);
30475f39d397SChris Mason 	path->nodes[level] = c;
3048bd681513SChris Mason 	path->locks[level] = BTRFS_WRITE_LOCK;
304974123bd7SChris Mason 	path->slots[level] = 0;
305074123bd7SChris Mason 	return 0;
305174123bd7SChris Mason }
30525c680ed6SChris Mason 
30535c680ed6SChris Mason /*
30545c680ed6SChris Mason  * worker function to insert a single pointer in a node.
30555c680ed6SChris Mason  * the node should have enough room for the pointer already
305697571fd0SChris Mason  *
30575c680ed6SChris Mason  * slot and level indicate where you want the key to go, and
30585c680ed6SChris Mason  * blocknr is the block the key points to.
30595c680ed6SChris Mason  */
3060143bede5SJeff Mahoney static void insert_ptr(struct btrfs_trans_handle *trans,
3061143bede5SJeff Mahoney 		       struct btrfs_root *root, struct btrfs_path *path,
3062143bede5SJeff Mahoney 		       struct btrfs_disk_key *key, u64 bytenr,
3063c3e06965SJan Schmidt 		       int slot, int level)
30645c680ed6SChris Mason {
30655f39d397SChris Mason 	struct extent_buffer *lower;
30665c680ed6SChris Mason 	int nritems;
3067f3ea38daSJan Schmidt 	int ret;
30685c680ed6SChris Mason 
30695c680ed6SChris Mason 	BUG_ON(!path->nodes[level]);
3070f0486c68SYan, Zheng 	btrfs_assert_tree_locked(path->nodes[level]);
30715f39d397SChris Mason 	lower = path->nodes[level];
30725f39d397SChris Mason 	nritems = btrfs_header_nritems(lower);
3073c293498bSStoyan Gaydarov 	BUG_ON(slot > nritems);
3074143bede5SJeff Mahoney 	BUG_ON(nritems == BTRFS_NODEPTRS_PER_BLOCK(root));
307574123bd7SChris Mason 	if (slot != nritems) {
3076c3e06965SJan Schmidt 		if (level)
3077f3ea38daSJan Schmidt 			tree_mod_log_eb_move(root->fs_info, lower, slot + 1,
3078f3ea38daSJan Schmidt 					     slot, nritems - slot);
30795f39d397SChris Mason 		memmove_extent_buffer(lower,
30805f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot + 1),
30815f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot),
3082123abc88SChris Mason 			      (nritems - slot) * sizeof(struct btrfs_key_ptr));
308374123bd7SChris Mason 	}
3084c3e06965SJan Schmidt 	if (level) {
3085f3ea38daSJan Schmidt 		ret = tree_mod_log_insert_key(root->fs_info, lower, slot,
3086f3ea38daSJan Schmidt 					      MOD_LOG_KEY_ADD);
3087f3ea38daSJan Schmidt 		BUG_ON(ret < 0);
3088f3ea38daSJan Schmidt 	}
30895f39d397SChris Mason 	btrfs_set_node_key(lower, key, slot);
3090db94535dSChris Mason 	btrfs_set_node_blockptr(lower, slot, bytenr);
309174493f7aSChris Mason 	WARN_ON(trans->transid == 0);
309274493f7aSChris Mason 	btrfs_set_node_ptr_generation(lower, slot, trans->transid);
30935f39d397SChris Mason 	btrfs_set_header_nritems(lower, nritems + 1);
30945f39d397SChris Mason 	btrfs_mark_buffer_dirty(lower);
309574123bd7SChris Mason }
309674123bd7SChris Mason 
309797571fd0SChris Mason /*
309897571fd0SChris Mason  * split the node at the specified level in path in two.
309997571fd0SChris Mason  * The path is corrected to point to the appropriate node after the split
310097571fd0SChris Mason  *
310197571fd0SChris Mason  * Before splitting this tries to make some room in the node by pushing
310297571fd0SChris Mason  * left and right, if either one works, it returns right away.
3103aa5d6bedSChris Mason  *
3104aa5d6bedSChris Mason  * returns 0 on success and < 0 on failure
310597571fd0SChris Mason  */
3106e02119d5SChris Mason static noinline int split_node(struct btrfs_trans_handle *trans,
3107e02119d5SChris Mason 			       struct btrfs_root *root,
3108e02119d5SChris Mason 			       struct btrfs_path *path, int level)
3109be0e5c09SChris Mason {
31105f39d397SChris Mason 	struct extent_buffer *c;
31115f39d397SChris Mason 	struct extent_buffer *split;
31125f39d397SChris Mason 	struct btrfs_disk_key disk_key;
3113be0e5c09SChris Mason 	int mid;
31145c680ed6SChris Mason 	int ret;
31157518a238SChris Mason 	u32 c_nritems;
3116be0e5c09SChris Mason 
31175f39d397SChris Mason 	c = path->nodes[level];
31187bb86316SChris Mason 	WARN_ON(btrfs_header_generation(c) != trans->transid);
31195f39d397SChris Mason 	if (c == root->node) {
31205c680ed6SChris Mason 		/* trying to split the root, lets make a new one */
3121e089f05cSChris Mason 		ret = insert_new_root(trans, root, path, level + 1);
31225c680ed6SChris Mason 		if (ret)
31235c680ed6SChris Mason 			return ret;
3124b3612421SChris Mason 	} else {
3125e66f709bSChris Mason 		ret = push_nodes_for_insert(trans, root, path, level);
31265f39d397SChris Mason 		c = path->nodes[level];
31275f39d397SChris Mason 		if (!ret && btrfs_header_nritems(c) <
3128c448acf0SChris Mason 		    BTRFS_NODEPTRS_PER_BLOCK(root) - 3)
3129e66f709bSChris Mason 			return 0;
313054aa1f4dSChris Mason 		if (ret < 0)
313154aa1f4dSChris Mason 			return ret;
31325c680ed6SChris Mason 	}
3133e66f709bSChris Mason 
31345f39d397SChris Mason 	c_nritems = btrfs_header_nritems(c);
31355d4f98a2SYan Zheng 	mid = (c_nritems + 1) / 2;
31365d4f98a2SYan Zheng 	btrfs_node_key(c, &disk_key, mid);
31377bb86316SChris Mason 
31385d4f98a2SYan Zheng 	split = btrfs_alloc_free_block(trans, root, root->nodesize, 0,
31397bb86316SChris Mason 					root->root_key.objectid,
31405581a51aSJan Schmidt 					&disk_key, level, c->start, 0);
31415f39d397SChris Mason 	if (IS_ERR(split))
31425f39d397SChris Mason 		return PTR_ERR(split);
314354aa1f4dSChris Mason 
3144f0486c68SYan, Zheng 	root_add_used(root, root->nodesize);
3145f0486c68SYan, Zheng 
31465d4f98a2SYan Zheng 	memset_extent_buffer(split, 0, 0, sizeof(struct btrfs_header));
31475f39d397SChris Mason 	btrfs_set_header_level(split, btrfs_header_level(c));
3148db94535dSChris Mason 	btrfs_set_header_bytenr(split, split->start);
31495f39d397SChris Mason 	btrfs_set_header_generation(split, trans->transid);
31505d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(split, BTRFS_MIXED_BACKREF_REV);
31515f39d397SChris Mason 	btrfs_set_header_owner(split, root->root_key.objectid);
31525f39d397SChris Mason 	write_extent_buffer(split, root->fs_info->fsid,
31535f39d397SChris Mason 			    (unsigned long)btrfs_header_fsid(split),
31545f39d397SChris Mason 			    BTRFS_FSID_SIZE);
3155e17cade2SChris Mason 	write_extent_buffer(split, root->fs_info->chunk_tree_uuid,
3156e17cade2SChris Mason 			    (unsigned long)btrfs_header_chunk_tree_uuid(split),
3157e17cade2SChris Mason 			    BTRFS_UUID_SIZE);
31585f39d397SChris Mason 
3159f230475eSJan Schmidt 	tree_mod_log_eb_copy(root->fs_info, split, c, 0, mid, c_nritems - mid);
31605f39d397SChris Mason 	copy_extent_buffer(split, c,
31615f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
31625f39d397SChris Mason 			   btrfs_node_key_ptr_offset(mid),
3163123abc88SChris Mason 			   (c_nritems - mid) * sizeof(struct btrfs_key_ptr));
31645f39d397SChris Mason 	btrfs_set_header_nritems(split, c_nritems - mid);
31655f39d397SChris Mason 	btrfs_set_header_nritems(c, mid);
3166aa5d6bedSChris Mason 	ret = 0;
3167aa5d6bedSChris Mason 
31685f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
31695f39d397SChris Mason 	btrfs_mark_buffer_dirty(split);
31705f39d397SChris Mason 
3171143bede5SJeff Mahoney 	insert_ptr(trans, root, path, &disk_key, split->start,
3172c3e06965SJan Schmidt 		   path->slots[level + 1] + 1, level + 1);
3173aa5d6bedSChris Mason 
31745de08d7dSChris Mason 	if (path->slots[level] >= mid) {
31755c680ed6SChris Mason 		path->slots[level] -= mid;
3176925baeddSChris Mason 		btrfs_tree_unlock(c);
31775f39d397SChris Mason 		free_extent_buffer(c);
31785f39d397SChris Mason 		path->nodes[level] = split;
31795c680ed6SChris Mason 		path->slots[level + 1] += 1;
3180eb60ceacSChris Mason 	} else {
3181925baeddSChris Mason 		btrfs_tree_unlock(split);
31825f39d397SChris Mason 		free_extent_buffer(split);
3183be0e5c09SChris Mason 	}
3184aa5d6bedSChris Mason 	return ret;
3185be0e5c09SChris Mason }
3186be0e5c09SChris Mason 
318774123bd7SChris Mason /*
318874123bd7SChris Mason  * how many bytes are required to store the items in a leaf.  start
318974123bd7SChris Mason  * and nr indicate which items in the leaf to check.  This totals up the
319074123bd7SChris Mason  * space used both by the item structs and the item data
319174123bd7SChris Mason  */
31925f39d397SChris Mason static int leaf_space_used(struct extent_buffer *l, int start, int nr)
3193be0e5c09SChris Mason {
3194be0e5c09SChris Mason 	int data_len;
31955f39d397SChris Mason 	int nritems = btrfs_header_nritems(l);
3196d4dbff95SChris Mason 	int end = min(nritems, start + nr) - 1;
3197be0e5c09SChris Mason 
3198be0e5c09SChris Mason 	if (!nr)
3199be0e5c09SChris Mason 		return 0;
32005f39d397SChris Mason 	data_len = btrfs_item_end_nr(l, start);
32015f39d397SChris Mason 	data_len = data_len - btrfs_item_offset_nr(l, end);
32020783fcfcSChris Mason 	data_len += sizeof(struct btrfs_item) * nr;
3203d4dbff95SChris Mason 	WARN_ON(data_len < 0);
3204be0e5c09SChris Mason 	return data_len;
3205be0e5c09SChris Mason }
3206be0e5c09SChris Mason 
320774123bd7SChris Mason /*
3208d4dbff95SChris Mason  * The space between the end of the leaf items and
3209d4dbff95SChris Mason  * the start of the leaf data.  IOW, how much room
3210d4dbff95SChris Mason  * the leaf has left for both items and data
3211d4dbff95SChris Mason  */
3212d397712bSChris Mason noinline int btrfs_leaf_free_space(struct btrfs_root *root,
3213e02119d5SChris Mason 				   struct extent_buffer *leaf)
3214d4dbff95SChris Mason {
32155f39d397SChris Mason 	int nritems = btrfs_header_nritems(leaf);
32165f39d397SChris Mason 	int ret;
32175f39d397SChris Mason 	ret = BTRFS_LEAF_DATA_SIZE(root) - leaf_space_used(leaf, 0, nritems);
32185f39d397SChris Mason 	if (ret < 0) {
3219d397712bSChris Mason 		printk(KERN_CRIT "leaf free space ret %d, leaf data size %lu, "
3220d397712bSChris Mason 		       "used %d nritems %d\n",
3221ae2f5411SJens Axboe 		       ret, (unsigned long) BTRFS_LEAF_DATA_SIZE(root),
32225f39d397SChris Mason 		       leaf_space_used(leaf, 0, nritems), nritems);
32235f39d397SChris Mason 	}
32245f39d397SChris Mason 	return ret;
3225d4dbff95SChris Mason }
3226d4dbff95SChris Mason 
322799d8f83cSChris Mason /*
322899d8f83cSChris Mason  * min slot controls the lowest index we're willing to push to the
322999d8f83cSChris Mason  * right.  We'll push up to and including min_slot, but no lower
323099d8f83cSChris Mason  */
323144871b1bSChris Mason static noinline int __push_leaf_right(struct btrfs_trans_handle *trans,
323244871b1bSChris Mason 				      struct btrfs_root *root,
323344871b1bSChris Mason 				      struct btrfs_path *path,
323444871b1bSChris Mason 				      int data_size, int empty,
323544871b1bSChris Mason 				      struct extent_buffer *right,
323699d8f83cSChris Mason 				      int free_space, u32 left_nritems,
323799d8f83cSChris Mason 				      u32 min_slot)
323800ec4c51SChris Mason {
32395f39d397SChris Mason 	struct extent_buffer *left = path->nodes[0];
324044871b1bSChris Mason 	struct extent_buffer *upper = path->nodes[1];
3241cfed81a0SChris Mason 	struct btrfs_map_token token;
32425f39d397SChris Mason 	struct btrfs_disk_key disk_key;
324300ec4c51SChris Mason 	int slot;
324434a38218SChris Mason 	u32 i;
324500ec4c51SChris Mason 	int push_space = 0;
324600ec4c51SChris Mason 	int push_items = 0;
32470783fcfcSChris Mason 	struct btrfs_item *item;
324834a38218SChris Mason 	u32 nr;
32497518a238SChris Mason 	u32 right_nritems;
32505f39d397SChris Mason 	u32 data_end;
3251db94535dSChris Mason 	u32 this_item_size;
325200ec4c51SChris Mason 
3253cfed81a0SChris Mason 	btrfs_init_map_token(&token);
3254cfed81a0SChris Mason 
325534a38218SChris Mason 	if (empty)
325634a38218SChris Mason 		nr = 0;
325734a38218SChris Mason 	else
325899d8f83cSChris Mason 		nr = max_t(u32, 1, min_slot);
325934a38218SChris Mason 
326031840ae1SZheng Yan 	if (path->slots[0] >= left_nritems)
326187b29b20SYan Zheng 		push_space += data_size;
326231840ae1SZheng Yan 
326344871b1bSChris Mason 	slot = path->slots[1];
326434a38218SChris Mason 	i = left_nritems - 1;
326534a38218SChris Mason 	while (i >= nr) {
32665f39d397SChris Mason 		item = btrfs_item_nr(left, i);
3267db94535dSChris Mason 
326831840ae1SZheng Yan 		if (!empty && push_items > 0) {
326931840ae1SZheng Yan 			if (path->slots[0] > i)
327031840ae1SZheng Yan 				break;
327131840ae1SZheng Yan 			if (path->slots[0] == i) {
327231840ae1SZheng Yan 				int space = btrfs_leaf_free_space(root, left);
327331840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
327431840ae1SZheng Yan 					break;
327531840ae1SZheng Yan 			}
327631840ae1SZheng Yan 		}
327731840ae1SZheng Yan 
327800ec4c51SChris Mason 		if (path->slots[0] == i)
327987b29b20SYan Zheng 			push_space += data_size;
3280db94535dSChris Mason 
3281db94535dSChris Mason 		this_item_size = btrfs_item_size(left, item);
3282db94535dSChris Mason 		if (this_item_size + sizeof(*item) + push_space > free_space)
328300ec4c51SChris Mason 			break;
328431840ae1SZheng Yan 
328500ec4c51SChris Mason 		push_items++;
3286db94535dSChris Mason 		push_space += this_item_size + sizeof(*item);
328734a38218SChris Mason 		if (i == 0)
328834a38218SChris Mason 			break;
328934a38218SChris Mason 		i--;
3290db94535dSChris Mason 	}
32915f39d397SChris Mason 
3292925baeddSChris Mason 	if (push_items == 0)
3293925baeddSChris Mason 		goto out_unlock;
32945f39d397SChris Mason 
329534a38218SChris Mason 	if (!empty && push_items == left_nritems)
3296a429e513SChris Mason 		WARN_ON(1);
32975f39d397SChris Mason 
329800ec4c51SChris Mason 	/* push left to right */
32995f39d397SChris Mason 	right_nritems = btrfs_header_nritems(right);
330034a38218SChris Mason 
33015f39d397SChris Mason 	push_space = btrfs_item_end_nr(left, left_nritems - push_items);
3302123abc88SChris Mason 	push_space -= leaf_data_end(root, left);
33035f39d397SChris Mason 
330400ec4c51SChris Mason 	/* make room in the right data area */
33055f39d397SChris Mason 	data_end = leaf_data_end(root, right);
33065f39d397SChris Mason 	memmove_extent_buffer(right,
33075f39d397SChris Mason 			      btrfs_leaf_data(right) + data_end - push_space,
33085f39d397SChris Mason 			      btrfs_leaf_data(right) + data_end,
33095f39d397SChris Mason 			      BTRFS_LEAF_DATA_SIZE(root) - data_end);
33105f39d397SChris Mason 
331100ec4c51SChris Mason 	/* copy from the left data area */
33125f39d397SChris Mason 	copy_extent_buffer(right, left, btrfs_leaf_data(right) +
3313d6025579SChris Mason 		     BTRFS_LEAF_DATA_SIZE(root) - push_space,
3314d6025579SChris Mason 		     btrfs_leaf_data(left) + leaf_data_end(root, left),
3315d6025579SChris Mason 		     push_space);
33165f39d397SChris Mason 
33175f39d397SChris Mason 	memmove_extent_buffer(right, btrfs_item_nr_offset(push_items),
33185f39d397SChris Mason 			      btrfs_item_nr_offset(0),
33190783fcfcSChris Mason 			      right_nritems * sizeof(struct btrfs_item));
33205f39d397SChris Mason 
332100ec4c51SChris Mason 	/* copy the items from left to right */
33225f39d397SChris Mason 	copy_extent_buffer(right, left, btrfs_item_nr_offset(0),
33235f39d397SChris Mason 		   btrfs_item_nr_offset(left_nritems - push_items),
33240783fcfcSChris Mason 		   push_items * sizeof(struct btrfs_item));
332500ec4c51SChris Mason 
332600ec4c51SChris Mason 	/* update the item pointers */
33277518a238SChris Mason 	right_nritems += push_items;
33285f39d397SChris Mason 	btrfs_set_header_nritems(right, right_nritems);
3329123abc88SChris Mason 	push_space = BTRFS_LEAF_DATA_SIZE(root);
33307518a238SChris Mason 	for (i = 0; i < right_nritems; i++) {
33315f39d397SChris Mason 		item = btrfs_item_nr(right, i);
3332cfed81a0SChris Mason 		push_space -= btrfs_token_item_size(right, item, &token);
3333cfed81a0SChris Mason 		btrfs_set_token_item_offset(right, item, push_space, &token);
3334db94535dSChris Mason 	}
3335db94535dSChris Mason 
33367518a238SChris Mason 	left_nritems -= push_items;
33375f39d397SChris Mason 	btrfs_set_header_nritems(left, left_nritems);
333800ec4c51SChris Mason 
333934a38218SChris Mason 	if (left_nritems)
33405f39d397SChris Mason 		btrfs_mark_buffer_dirty(left);
3341f0486c68SYan, Zheng 	else
3342f0486c68SYan, Zheng 		clean_tree_block(trans, root, left);
3343f0486c68SYan, Zheng 
33445f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
3345a429e513SChris Mason 
33465f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
33475f39d397SChris Mason 	btrfs_set_node_key(upper, &disk_key, slot + 1);
3348d6025579SChris Mason 	btrfs_mark_buffer_dirty(upper);
334902217ed2SChris Mason 
335000ec4c51SChris Mason 	/* then fixup the leaf pointer in the path */
33517518a238SChris Mason 	if (path->slots[0] >= left_nritems) {
33527518a238SChris Mason 		path->slots[0] -= left_nritems;
3353925baeddSChris Mason 		if (btrfs_header_nritems(path->nodes[0]) == 0)
3354925baeddSChris Mason 			clean_tree_block(trans, root, path->nodes[0]);
3355925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
33565f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
33575f39d397SChris Mason 		path->nodes[0] = right;
335800ec4c51SChris Mason 		path->slots[1] += 1;
335900ec4c51SChris Mason 	} else {
3360925baeddSChris Mason 		btrfs_tree_unlock(right);
33615f39d397SChris Mason 		free_extent_buffer(right);
336200ec4c51SChris Mason 	}
336300ec4c51SChris Mason 	return 0;
3364925baeddSChris Mason 
3365925baeddSChris Mason out_unlock:
3366925baeddSChris Mason 	btrfs_tree_unlock(right);
3367925baeddSChris Mason 	free_extent_buffer(right);
3368925baeddSChris Mason 	return 1;
336900ec4c51SChris Mason }
3370925baeddSChris Mason 
337100ec4c51SChris Mason /*
337244871b1bSChris Mason  * push some data in the path leaf to the right, trying to free up at
337374123bd7SChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
337444871b1bSChris Mason  *
337544871b1bSChris Mason  * returns 1 if the push failed because the other node didn't have enough
337644871b1bSChris Mason  * room, 0 if everything worked out and < 0 if there were major errors.
337799d8f83cSChris Mason  *
337899d8f83cSChris Mason  * this will push starting from min_slot to the end of the leaf.  It won't
337999d8f83cSChris Mason  * push any slot lower than min_slot
338074123bd7SChris Mason  */
338144871b1bSChris Mason static int push_leaf_right(struct btrfs_trans_handle *trans, struct btrfs_root
338299d8f83cSChris Mason 			   *root, struct btrfs_path *path,
338399d8f83cSChris Mason 			   int min_data_size, int data_size,
338499d8f83cSChris Mason 			   int empty, u32 min_slot)
3385be0e5c09SChris Mason {
338644871b1bSChris Mason 	struct extent_buffer *left = path->nodes[0];
338744871b1bSChris Mason 	struct extent_buffer *right;
338844871b1bSChris Mason 	struct extent_buffer *upper;
338944871b1bSChris Mason 	int slot;
339044871b1bSChris Mason 	int free_space;
339144871b1bSChris Mason 	u32 left_nritems;
339244871b1bSChris Mason 	int ret;
339344871b1bSChris Mason 
339444871b1bSChris Mason 	if (!path->nodes[1])
339544871b1bSChris Mason 		return 1;
339644871b1bSChris Mason 
339744871b1bSChris Mason 	slot = path->slots[1];
339844871b1bSChris Mason 	upper = path->nodes[1];
339944871b1bSChris Mason 	if (slot >= btrfs_header_nritems(upper) - 1)
340044871b1bSChris Mason 		return 1;
340144871b1bSChris Mason 
340244871b1bSChris Mason 	btrfs_assert_tree_locked(path->nodes[1]);
340344871b1bSChris Mason 
340444871b1bSChris Mason 	right = read_node_slot(root, upper, slot + 1);
340591ca338dSTsutomu Itoh 	if (right == NULL)
340691ca338dSTsutomu Itoh 		return 1;
340791ca338dSTsutomu Itoh 
340844871b1bSChris Mason 	btrfs_tree_lock(right);
340944871b1bSChris Mason 	btrfs_set_lock_blocking(right);
341044871b1bSChris Mason 
341144871b1bSChris Mason 	free_space = btrfs_leaf_free_space(root, right);
341244871b1bSChris Mason 	if (free_space < data_size)
341344871b1bSChris Mason 		goto out_unlock;
341444871b1bSChris Mason 
341544871b1bSChris Mason 	/* cow and double check */
341644871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, right, upper,
341744871b1bSChris Mason 			      slot + 1, &right);
341844871b1bSChris Mason 	if (ret)
341944871b1bSChris Mason 		goto out_unlock;
342044871b1bSChris Mason 
342144871b1bSChris Mason 	free_space = btrfs_leaf_free_space(root, right);
342244871b1bSChris Mason 	if (free_space < data_size)
342344871b1bSChris Mason 		goto out_unlock;
342444871b1bSChris Mason 
342544871b1bSChris Mason 	left_nritems = btrfs_header_nritems(left);
342644871b1bSChris Mason 	if (left_nritems == 0)
342744871b1bSChris Mason 		goto out_unlock;
342844871b1bSChris Mason 
342999d8f83cSChris Mason 	return __push_leaf_right(trans, root, path, min_data_size, empty,
343099d8f83cSChris Mason 				right, free_space, left_nritems, min_slot);
343144871b1bSChris Mason out_unlock:
343244871b1bSChris Mason 	btrfs_tree_unlock(right);
343344871b1bSChris Mason 	free_extent_buffer(right);
343444871b1bSChris Mason 	return 1;
343544871b1bSChris Mason }
343644871b1bSChris Mason 
343744871b1bSChris Mason /*
343844871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
343944871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
344099d8f83cSChris Mason  *
344199d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
344299d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us do all the
344399d8f83cSChris Mason  * items
344444871b1bSChris Mason  */
344544871b1bSChris Mason static noinline int __push_leaf_left(struct btrfs_trans_handle *trans,
344644871b1bSChris Mason 				     struct btrfs_root *root,
344744871b1bSChris Mason 				     struct btrfs_path *path, int data_size,
344844871b1bSChris Mason 				     int empty, struct extent_buffer *left,
344999d8f83cSChris Mason 				     int free_space, u32 right_nritems,
345099d8f83cSChris Mason 				     u32 max_slot)
345144871b1bSChris Mason {
34525f39d397SChris Mason 	struct btrfs_disk_key disk_key;
34535f39d397SChris Mason 	struct extent_buffer *right = path->nodes[0];
3454be0e5c09SChris Mason 	int i;
3455be0e5c09SChris Mason 	int push_space = 0;
3456be0e5c09SChris Mason 	int push_items = 0;
34570783fcfcSChris Mason 	struct btrfs_item *item;
34587518a238SChris Mason 	u32 old_left_nritems;
345934a38218SChris Mason 	u32 nr;
3460aa5d6bedSChris Mason 	int ret = 0;
3461db94535dSChris Mason 	u32 this_item_size;
3462db94535dSChris Mason 	u32 old_left_item_size;
3463cfed81a0SChris Mason 	struct btrfs_map_token token;
3464cfed81a0SChris Mason 
3465cfed81a0SChris Mason 	btrfs_init_map_token(&token);
3466be0e5c09SChris Mason 
346734a38218SChris Mason 	if (empty)
346899d8f83cSChris Mason 		nr = min(right_nritems, max_slot);
346934a38218SChris Mason 	else
347099d8f83cSChris Mason 		nr = min(right_nritems - 1, max_slot);
347134a38218SChris Mason 
347234a38218SChris Mason 	for (i = 0; i < nr; i++) {
34735f39d397SChris Mason 		item = btrfs_item_nr(right, i);
3474db94535dSChris Mason 
347531840ae1SZheng Yan 		if (!empty && push_items > 0) {
347631840ae1SZheng Yan 			if (path->slots[0] < i)
347731840ae1SZheng Yan 				break;
347831840ae1SZheng Yan 			if (path->slots[0] == i) {
347931840ae1SZheng Yan 				int space = btrfs_leaf_free_space(root, right);
348031840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
348131840ae1SZheng Yan 					break;
348231840ae1SZheng Yan 			}
348331840ae1SZheng Yan 		}
348431840ae1SZheng Yan 
3485be0e5c09SChris Mason 		if (path->slots[0] == i)
348687b29b20SYan Zheng 			push_space += data_size;
3487db94535dSChris Mason 
3488db94535dSChris Mason 		this_item_size = btrfs_item_size(right, item);
3489db94535dSChris Mason 		if (this_item_size + sizeof(*item) + push_space > free_space)
3490be0e5c09SChris Mason 			break;
3491db94535dSChris Mason 
3492be0e5c09SChris Mason 		push_items++;
3493db94535dSChris Mason 		push_space += this_item_size + sizeof(*item);
3494be0e5c09SChris Mason 	}
3495db94535dSChris Mason 
3496be0e5c09SChris Mason 	if (push_items == 0) {
3497925baeddSChris Mason 		ret = 1;
3498925baeddSChris Mason 		goto out;
3499be0e5c09SChris Mason 	}
350034a38218SChris Mason 	if (!empty && push_items == btrfs_header_nritems(right))
3501a429e513SChris Mason 		WARN_ON(1);
35025f39d397SChris Mason 
3503be0e5c09SChris Mason 	/* push data from right to left */
35045f39d397SChris Mason 	copy_extent_buffer(left, right,
35055f39d397SChris Mason 			   btrfs_item_nr_offset(btrfs_header_nritems(left)),
35065f39d397SChris Mason 			   btrfs_item_nr_offset(0),
35075f39d397SChris Mason 			   push_items * sizeof(struct btrfs_item));
35085f39d397SChris Mason 
3509123abc88SChris Mason 	push_space = BTRFS_LEAF_DATA_SIZE(root) -
35105f39d397SChris Mason 		     btrfs_item_offset_nr(right, push_items - 1);
35115f39d397SChris Mason 
35125f39d397SChris Mason 	copy_extent_buffer(left, right, btrfs_leaf_data(left) +
3513d6025579SChris Mason 		     leaf_data_end(root, left) - push_space,
3514123abc88SChris Mason 		     btrfs_leaf_data(right) +
35155f39d397SChris Mason 		     btrfs_item_offset_nr(right, push_items - 1),
3516be0e5c09SChris Mason 		     push_space);
35175f39d397SChris Mason 	old_left_nritems = btrfs_header_nritems(left);
351887b29b20SYan Zheng 	BUG_ON(old_left_nritems <= 0);
3519eb60ceacSChris Mason 
3520db94535dSChris Mason 	old_left_item_size = btrfs_item_offset_nr(left, old_left_nritems - 1);
3521be0e5c09SChris Mason 	for (i = old_left_nritems; i < old_left_nritems + push_items; i++) {
35225f39d397SChris Mason 		u32 ioff;
3523db94535dSChris Mason 
35245f39d397SChris Mason 		item = btrfs_item_nr(left, i);
3525db94535dSChris Mason 
3526cfed81a0SChris Mason 		ioff = btrfs_token_item_offset(left, item, &token);
3527cfed81a0SChris Mason 		btrfs_set_token_item_offset(left, item,
3528cfed81a0SChris Mason 		      ioff - (BTRFS_LEAF_DATA_SIZE(root) - old_left_item_size),
3529cfed81a0SChris Mason 		      &token);
3530be0e5c09SChris Mason 	}
35315f39d397SChris Mason 	btrfs_set_header_nritems(left, old_left_nritems + push_items);
3532be0e5c09SChris Mason 
3533be0e5c09SChris Mason 	/* fixup right node */
353434a38218SChris Mason 	if (push_items > right_nritems) {
3535d397712bSChris Mason 		printk(KERN_CRIT "push items %d nr %u\n", push_items,
3536d397712bSChris Mason 		       right_nritems);
353734a38218SChris Mason 		WARN_ON(1);
353834a38218SChris Mason 	}
353934a38218SChris Mason 
354034a38218SChris Mason 	if (push_items < right_nritems) {
35415f39d397SChris Mason 		push_space = btrfs_item_offset_nr(right, push_items - 1) -
3542123abc88SChris Mason 						  leaf_data_end(root, right);
35435f39d397SChris Mason 		memmove_extent_buffer(right, btrfs_leaf_data(right) +
3544d6025579SChris Mason 				      BTRFS_LEAF_DATA_SIZE(root) - push_space,
3545d6025579SChris Mason 				      btrfs_leaf_data(right) +
3546123abc88SChris Mason 				      leaf_data_end(root, right), push_space);
35475f39d397SChris Mason 
35485f39d397SChris Mason 		memmove_extent_buffer(right, btrfs_item_nr_offset(0),
35495f39d397SChris Mason 			      btrfs_item_nr_offset(push_items),
35505f39d397SChris Mason 			     (btrfs_header_nritems(right) - push_items) *
35510783fcfcSChris Mason 			     sizeof(struct btrfs_item));
355234a38218SChris Mason 	}
3553eef1c494SYan 	right_nritems -= push_items;
3554eef1c494SYan 	btrfs_set_header_nritems(right, right_nritems);
3555123abc88SChris Mason 	push_space = BTRFS_LEAF_DATA_SIZE(root);
35565f39d397SChris Mason 	for (i = 0; i < right_nritems; i++) {
35575f39d397SChris Mason 		item = btrfs_item_nr(right, i);
3558db94535dSChris Mason 
3559cfed81a0SChris Mason 		push_space = push_space - btrfs_token_item_size(right,
3560cfed81a0SChris Mason 								item, &token);
3561cfed81a0SChris Mason 		btrfs_set_token_item_offset(right, item, push_space, &token);
3562db94535dSChris Mason 	}
3563eb60ceacSChris Mason 
35645f39d397SChris Mason 	btrfs_mark_buffer_dirty(left);
356534a38218SChris Mason 	if (right_nritems)
35665f39d397SChris Mason 		btrfs_mark_buffer_dirty(right);
3567f0486c68SYan, Zheng 	else
3568f0486c68SYan, Zheng 		clean_tree_block(trans, root, right);
3569098f59c2SChris Mason 
35705f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
3571143bede5SJeff Mahoney 	fixup_low_keys(trans, root, path, &disk_key, 1);
3572be0e5c09SChris Mason 
3573be0e5c09SChris Mason 	/* then fixup the leaf pointer in the path */
3574be0e5c09SChris Mason 	if (path->slots[0] < push_items) {
3575be0e5c09SChris Mason 		path->slots[0] += old_left_nritems;
3576925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
35775f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
35785f39d397SChris Mason 		path->nodes[0] = left;
3579be0e5c09SChris Mason 		path->slots[1] -= 1;
3580be0e5c09SChris Mason 	} else {
3581925baeddSChris Mason 		btrfs_tree_unlock(left);
35825f39d397SChris Mason 		free_extent_buffer(left);
3583be0e5c09SChris Mason 		path->slots[0] -= push_items;
3584be0e5c09SChris Mason 	}
3585eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
3586aa5d6bedSChris Mason 	return ret;
3587925baeddSChris Mason out:
3588925baeddSChris Mason 	btrfs_tree_unlock(left);
3589925baeddSChris Mason 	free_extent_buffer(left);
3590925baeddSChris Mason 	return ret;
3591be0e5c09SChris Mason }
3592be0e5c09SChris Mason 
359374123bd7SChris Mason /*
359444871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
359544871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
359699d8f83cSChris Mason  *
359799d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
359899d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us push all the
359999d8f83cSChris Mason  * items
360044871b1bSChris Mason  */
360144871b1bSChris Mason static int push_leaf_left(struct btrfs_trans_handle *trans, struct btrfs_root
360299d8f83cSChris Mason 			  *root, struct btrfs_path *path, int min_data_size,
360399d8f83cSChris Mason 			  int data_size, int empty, u32 max_slot)
360444871b1bSChris Mason {
360544871b1bSChris Mason 	struct extent_buffer *right = path->nodes[0];
360644871b1bSChris Mason 	struct extent_buffer *left;
360744871b1bSChris Mason 	int slot;
360844871b1bSChris Mason 	int free_space;
360944871b1bSChris Mason 	u32 right_nritems;
361044871b1bSChris Mason 	int ret = 0;
361144871b1bSChris Mason 
361244871b1bSChris Mason 	slot = path->slots[1];
361344871b1bSChris Mason 	if (slot == 0)
361444871b1bSChris Mason 		return 1;
361544871b1bSChris Mason 	if (!path->nodes[1])
361644871b1bSChris Mason 		return 1;
361744871b1bSChris Mason 
361844871b1bSChris Mason 	right_nritems = btrfs_header_nritems(right);
361944871b1bSChris Mason 	if (right_nritems == 0)
362044871b1bSChris Mason 		return 1;
362144871b1bSChris Mason 
362244871b1bSChris Mason 	btrfs_assert_tree_locked(path->nodes[1]);
362344871b1bSChris Mason 
362444871b1bSChris Mason 	left = read_node_slot(root, path->nodes[1], slot - 1);
362591ca338dSTsutomu Itoh 	if (left == NULL)
362691ca338dSTsutomu Itoh 		return 1;
362791ca338dSTsutomu Itoh 
362844871b1bSChris Mason 	btrfs_tree_lock(left);
362944871b1bSChris Mason 	btrfs_set_lock_blocking(left);
363044871b1bSChris Mason 
363144871b1bSChris Mason 	free_space = btrfs_leaf_free_space(root, left);
363244871b1bSChris Mason 	if (free_space < data_size) {
363344871b1bSChris Mason 		ret = 1;
363444871b1bSChris Mason 		goto out;
363544871b1bSChris Mason 	}
363644871b1bSChris Mason 
363744871b1bSChris Mason 	/* cow and double check */
363844871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, left,
363944871b1bSChris Mason 			      path->nodes[1], slot - 1, &left);
364044871b1bSChris Mason 	if (ret) {
364144871b1bSChris Mason 		/* we hit -ENOSPC, but it isn't fatal here */
364279787eaaSJeff Mahoney 		if (ret == -ENOSPC)
364344871b1bSChris Mason 			ret = 1;
364444871b1bSChris Mason 		goto out;
364544871b1bSChris Mason 	}
364644871b1bSChris Mason 
364744871b1bSChris Mason 	free_space = btrfs_leaf_free_space(root, left);
364844871b1bSChris Mason 	if (free_space < data_size) {
364944871b1bSChris Mason 		ret = 1;
365044871b1bSChris Mason 		goto out;
365144871b1bSChris Mason 	}
365244871b1bSChris Mason 
365399d8f83cSChris Mason 	return __push_leaf_left(trans, root, path, min_data_size,
365499d8f83cSChris Mason 			       empty, left, free_space, right_nritems,
365599d8f83cSChris Mason 			       max_slot);
365644871b1bSChris Mason out:
365744871b1bSChris Mason 	btrfs_tree_unlock(left);
365844871b1bSChris Mason 	free_extent_buffer(left);
365944871b1bSChris Mason 	return ret;
366044871b1bSChris Mason }
366144871b1bSChris Mason 
366244871b1bSChris Mason /*
366374123bd7SChris Mason  * split the path's leaf in two, making sure there is at least data_size
366474123bd7SChris Mason  * available for the resulting leaf level of the path.
366574123bd7SChris Mason  */
3666143bede5SJeff Mahoney static noinline void copy_for_split(struct btrfs_trans_handle *trans,
3667e02119d5SChris Mason 				    struct btrfs_root *root,
366844871b1bSChris Mason 				    struct btrfs_path *path,
366944871b1bSChris Mason 				    struct extent_buffer *l,
367044871b1bSChris Mason 				    struct extent_buffer *right,
367144871b1bSChris Mason 				    int slot, int mid, int nritems)
3672be0e5c09SChris Mason {
3673be0e5c09SChris Mason 	int data_copy_size;
3674be0e5c09SChris Mason 	int rt_data_off;
3675be0e5c09SChris Mason 	int i;
3676d4dbff95SChris Mason 	struct btrfs_disk_key disk_key;
3677cfed81a0SChris Mason 	struct btrfs_map_token token;
3678cfed81a0SChris Mason 
3679cfed81a0SChris Mason 	btrfs_init_map_token(&token);
3680be0e5c09SChris Mason 
36815f39d397SChris Mason 	nritems = nritems - mid;
36825f39d397SChris Mason 	btrfs_set_header_nritems(right, nritems);
36835f39d397SChris Mason 	data_copy_size = btrfs_item_end_nr(l, mid) - leaf_data_end(root, l);
36845f39d397SChris Mason 
36855f39d397SChris Mason 	copy_extent_buffer(right, l, btrfs_item_nr_offset(0),
36865f39d397SChris Mason 			   btrfs_item_nr_offset(mid),
36875f39d397SChris Mason 			   nritems * sizeof(struct btrfs_item));
36885f39d397SChris Mason 
36895f39d397SChris Mason 	copy_extent_buffer(right, l,
3690d6025579SChris Mason 		     btrfs_leaf_data(right) + BTRFS_LEAF_DATA_SIZE(root) -
3691123abc88SChris Mason 		     data_copy_size, btrfs_leaf_data(l) +
3692123abc88SChris Mason 		     leaf_data_end(root, l), data_copy_size);
369374123bd7SChris Mason 
36945f39d397SChris Mason 	rt_data_off = BTRFS_LEAF_DATA_SIZE(root) -
36955f39d397SChris Mason 		      btrfs_item_end_nr(l, mid);
36965f39d397SChris Mason 
36975f39d397SChris Mason 	for (i = 0; i < nritems; i++) {
36985f39d397SChris Mason 		struct btrfs_item *item = btrfs_item_nr(right, i);
3699db94535dSChris Mason 		u32 ioff;
3700db94535dSChris Mason 
3701cfed81a0SChris Mason 		ioff = btrfs_token_item_offset(right, item, &token);
3702cfed81a0SChris Mason 		btrfs_set_token_item_offset(right, item,
3703cfed81a0SChris Mason 					    ioff + rt_data_off, &token);
37040783fcfcSChris Mason 	}
370574123bd7SChris Mason 
37065f39d397SChris Mason 	btrfs_set_header_nritems(l, mid);
37075f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
3708143bede5SJeff Mahoney 	insert_ptr(trans, root, path, &disk_key, right->start,
3709c3e06965SJan Schmidt 		   path->slots[1] + 1, 1);
37105f39d397SChris Mason 
37115f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
37125f39d397SChris Mason 	btrfs_mark_buffer_dirty(l);
3713eb60ceacSChris Mason 	BUG_ON(path->slots[0] != slot);
37145f39d397SChris Mason 
3715be0e5c09SChris Mason 	if (mid <= slot) {
3716925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
37175f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
37185f39d397SChris Mason 		path->nodes[0] = right;
3719be0e5c09SChris Mason 		path->slots[0] -= mid;
3720be0e5c09SChris Mason 		path->slots[1] += 1;
3721925baeddSChris Mason 	} else {
3722925baeddSChris Mason 		btrfs_tree_unlock(right);
37235f39d397SChris Mason 		free_extent_buffer(right);
3724925baeddSChris Mason 	}
37255f39d397SChris Mason 
3726eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
372744871b1bSChris Mason }
372844871b1bSChris Mason 
372944871b1bSChris Mason /*
373099d8f83cSChris Mason  * double splits happen when we need to insert a big item in the middle
373199d8f83cSChris Mason  * of a leaf.  A double split can leave us with 3 mostly empty leaves:
373299d8f83cSChris Mason  * leaf: [ slots 0 - N] [ our target ] [ N + 1 - total in leaf ]
373399d8f83cSChris Mason  *          A                 B                 C
373499d8f83cSChris Mason  *
373599d8f83cSChris Mason  * We avoid this by trying to push the items on either side of our target
373699d8f83cSChris Mason  * into the adjacent leaves.  If all goes well we can avoid the double split
373799d8f83cSChris Mason  * completely.
373899d8f83cSChris Mason  */
373999d8f83cSChris Mason static noinline int push_for_double_split(struct btrfs_trans_handle *trans,
374099d8f83cSChris Mason 					  struct btrfs_root *root,
374199d8f83cSChris Mason 					  struct btrfs_path *path,
374299d8f83cSChris Mason 					  int data_size)
374399d8f83cSChris Mason {
374499d8f83cSChris Mason 	int ret;
374599d8f83cSChris Mason 	int progress = 0;
374699d8f83cSChris Mason 	int slot;
374799d8f83cSChris Mason 	u32 nritems;
374899d8f83cSChris Mason 
374999d8f83cSChris Mason 	slot = path->slots[0];
375099d8f83cSChris Mason 
375199d8f83cSChris Mason 	/*
375299d8f83cSChris Mason 	 * try to push all the items after our slot into the
375399d8f83cSChris Mason 	 * right leaf
375499d8f83cSChris Mason 	 */
375599d8f83cSChris Mason 	ret = push_leaf_right(trans, root, path, 1, data_size, 0, slot);
375699d8f83cSChris Mason 	if (ret < 0)
375799d8f83cSChris Mason 		return ret;
375899d8f83cSChris Mason 
375999d8f83cSChris Mason 	if (ret == 0)
376099d8f83cSChris Mason 		progress++;
376199d8f83cSChris Mason 
376299d8f83cSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
376399d8f83cSChris Mason 	/*
376499d8f83cSChris Mason 	 * our goal is to get our slot at the start or end of a leaf.  If
376599d8f83cSChris Mason 	 * we've done so we're done
376699d8f83cSChris Mason 	 */
376799d8f83cSChris Mason 	if (path->slots[0] == 0 || path->slots[0] == nritems)
376899d8f83cSChris Mason 		return 0;
376999d8f83cSChris Mason 
377099d8f83cSChris Mason 	if (btrfs_leaf_free_space(root, path->nodes[0]) >= data_size)
377199d8f83cSChris Mason 		return 0;
377299d8f83cSChris Mason 
377399d8f83cSChris Mason 	/* try to push all the items before our slot into the next leaf */
377499d8f83cSChris Mason 	slot = path->slots[0];
377599d8f83cSChris Mason 	ret = push_leaf_left(trans, root, path, 1, data_size, 0, slot);
377699d8f83cSChris Mason 	if (ret < 0)
377799d8f83cSChris Mason 		return ret;
377899d8f83cSChris Mason 
377999d8f83cSChris Mason 	if (ret == 0)
378099d8f83cSChris Mason 		progress++;
378199d8f83cSChris Mason 
378299d8f83cSChris Mason 	if (progress)
378399d8f83cSChris Mason 		return 0;
378499d8f83cSChris Mason 	return 1;
378599d8f83cSChris Mason }
378699d8f83cSChris Mason 
378799d8f83cSChris Mason /*
378844871b1bSChris Mason  * split the path's leaf in two, making sure there is at least data_size
378944871b1bSChris Mason  * available for the resulting leaf level of the path.
379044871b1bSChris Mason  *
379144871b1bSChris Mason  * returns 0 if all went well and < 0 on failure.
379244871b1bSChris Mason  */
379344871b1bSChris Mason static noinline int split_leaf(struct btrfs_trans_handle *trans,
379444871b1bSChris Mason 			       struct btrfs_root *root,
379544871b1bSChris Mason 			       struct btrfs_key *ins_key,
379644871b1bSChris Mason 			       struct btrfs_path *path, int data_size,
379744871b1bSChris Mason 			       int extend)
379844871b1bSChris Mason {
37995d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
380044871b1bSChris Mason 	struct extent_buffer *l;
380144871b1bSChris Mason 	u32 nritems;
380244871b1bSChris Mason 	int mid;
380344871b1bSChris Mason 	int slot;
380444871b1bSChris Mason 	struct extent_buffer *right;
380544871b1bSChris Mason 	int ret = 0;
380644871b1bSChris Mason 	int wret;
38075d4f98a2SYan Zheng 	int split;
380844871b1bSChris Mason 	int num_doubles = 0;
380999d8f83cSChris Mason 	int tried_avoid_double = 0;
381044871b1bSChris Mason 
3811a5719521SYan, Zheng 	l = path->nodes[0];
3812a5719521SYan, Zheng 	slot = path->slots[0];
3813a5719521SYan, Zheng 	if (extend && data_size + btrfs_item_size_nr(l, slot) +
3814a5719521SYan, Zheng 	    sizeof(struct btrfs_item) > BTRFS_LEAF_DATA_SIZE(root))
3815a5719521SYan, Zheng 		return -EOVERFLOW;
3816a5719521SYan, Zheng 
381744871b1bSChris Mason 	/* first try to make some room by pushing left and right */
381899d8f83cSChris Mason 	if (data_size) {
381999d8f83cSChris Mason 		wret = push_leaf_right(trans, root, path, data_size,
382099d8f83cSChris Mason 				       data_size, 0, 0);
382144871b1bSChris Mason 		if (wret < 0)
382244871b1bSChris Mason 			return wret;
382344871b1bSChris Mason 		if (wret) {
382499d8f83cSChris Mason 			wret = push_leaf_left(trans, root, path, data_size,
382599d8f83cSChris Mason 					      data_size, 0, (u32)-1);
382644871b1bSChris Mason 			if (wret < 0)
382744871b1bSChris Mason 				return wret;
382844871b1bSChris Mason 		}
382944871b1bSChris Mason 		l = path->nodes[0];
383044871b1bSChris Mason 
383144871b1bSChris Mason 		/* did the pushes work? */
383244871b1bSChris Mason 		if (btrfs_leaf_free_space(root, l) >= data_size)
383344871b1bSChris Mason 			return 0;
383444871b1bSChris Mason 	}
383544871b1bSChris Mason 
383644871b1bSChris Mason 	if (!path->nodes[1]) {
383744871b1bSChris Mason 		ret = insert_new_root(trans, root, path, 1);
383844871b1bSChris Mason 		if (ret)
383944871b1bSChris Mason 			return ret;
384044871b1bSChris Mason 	}
384144871b1bSChris Mason again:
38425d4f98a2SYan Zheng 	split = 1;
384344871b1bSChris Mason 	l = path->nodes[0];
384444871b1bSChris Mason 	slot = path->slots[0];
384544871b1bSChris Mason 	nritems = btrfs_header_nritems(l);
384644871b1bSChris Mason 	mid = (nritems + 1) / 2;
384744871b1bSChris Mason 
38485d4f98a2SYan Zheng 	if (mid <= slot) {
38495d4f98a2SYan Zheng 		if (nritems == 1 ||
38505d4f98a2SYan Zheng 		    leaf_space_used(l, mid, nritems - mid) + data_size >
38515d4f98a2SYan Zheng 			BTRFS_LEAF_DATA_SIZE(root)) {
38525d4f98a2SYan Zheng 			if (slot >= nritems) {
38535d4f98a2SYan Zheng 				split = 0;
38545d4f98a2SYan Zheng 			} else {
38555d4f98a2SYan Zheng 				mid = slot;
38565d4f98a2SYan Zheng 				if (mid != nritems &&
38575d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
38585d4f98a2SYan Zheng 				    data_size > BTRFS_LEAF_DATA_SIZE(root)) {
385999d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
386099d8f83cSChris Mason 						goto push_for_double;
38615d4f98a2SYan Zheng 					split = 2;
38625d4f98a2SYan Zheng 				}
38635d4f98a2SYan Zheng 			}
38645d4f98a2SYan Zheng 		}
38655d4f98a2SYan Zheng 	} else {
38665d4f98a2SYan Zheng 		if (leaf_space_used(l, 0, mid) + data_size >
38675d4f98a2SYan Zheng 			BTRFS_LEAF_DATA_SIZE(root)) {
38685d4f98a2SYan Zheng 			if (!extend && data_size && slot == 0) {
38695d4f98a2SYan Zheng 				split = 0;
38705d4f98a2SYan Zheng 			} else if ((extend || !data_size) && slot == 0) {
38715d4f98a2SYan Zheng 				mid = 1;
38725d4f98a2SYan Zheng 			} else {
38735d4f98a2SYan Zheng 				mid = slot;
38745d4f98a2SYan Zheng 				if (mid != nritems &&
38755d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
38765d4f98a2SYan Zheng 				    data_size > BTRFS_LEAF_DATA_SIZE(root)) {
387799d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
387899d8f83cSChris Mason 						goto push_for_double;
38795d4f98a2SYan Zheng 					split = 2 ;
38805d4f98a2SYan Zheng 				}
38815d4f98a2SYan Zheng 			}
38825d4f98a2SYan Zheng 		}
38835d4f98a2SYan Zheng 	}
38845d4f98a2SYan Zheng 
38855d4f98a2SYan Zheng 	if (split == 0)
38865d4f98a2SYan Zheng 		btrfs_cpu_key_to_disk(&disk_key, ins_key);
38875d4f98a2SYan Zheng 	else
38885d4f98a2SYan Zheng 		btrfs_item_key(l, &disk_key, mid);
38895d4f98a2SYan Zheng 
38905d4f98a2SYan Zheng 	right = btrfs_alloc_free_block(trans, root, root->leafsize, 0,
389144871b1bSChris Mason 					root->root_key.objectid,
38925581a51aSJan Schmidt 					&disk_key, 0, l->start, 0);
3893f0486c68SYan, Zheng 	if (IS_ERR(right))
389444871b1bSChris Mason 		return PTR_ERR(right);
3895f0486c68SYan, Zheng 
3896f0486c68SYan, Zheng 	root_add_used(root, root->leafsize);
389744871b1bSChris Mason 
389844871b1bSChris Mason 	memset_extent_buffer(right, 0, 0, sizeof(struct btrfs_header));
389944871b1bSChris Mason 	btrfs_set_header_bytenr(right, right->start);
390044871b1bSChris Mason 	btrfs_set_header_generation(right, trans->transid);
39015d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(right, BTRFS_MIXED_BACKREF_REV);
390244871b1bSChris Mason 	btrfs_set_header_owner(right, root->root_key.objectid);
390344871b1bSChris Mason 	btrfs_set_header_level(right, 0);
390444871b1bSChris Mason 	write_extent_buffer(right, root->fs_info->fsid,
390544871b1bSChris Mason 			    (unsigned long)btrfs_header_fsid(right),
390644871b1bSChris Mason 			    BTRFS_FSID_SIZE);
390744871b1bSChris Mason 
390844871b1bSChris Mason 	write_extent_buffer(right, root->fs_info->chunk_tree_uuid,
390944871b1bSChris Mason 			    (unsigned long)btrfs_header_chunk_tree_uuid(right),
391044871b1bSChris Mason 			    BTRFS_UUID_SIZE);
391144871b1bSChris Mason 
39125d4f98a2SYan Zheng 	if (split == 0) {
391344871b1bSChris Mason 		if (mid <= slot) {
391444871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
3915143bede5SJeff Mahoney 			insert_ptr(trans, root, path, &disk_key, right->start,
3916c3e06965SJan Schmidt 				   path->slots[1] + 1, 1);
391744871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
391844871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
391944871b1bSChris Mason 			path->nodes[0] = right;
392044871b1bSChris Mason 			path->slots[0] = 0;
392144871b1bSChris Mason 			path->slots[1] += 1;
392244871b1bSChris Mason 		} else {
392344871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
3924143bede5SJeff Mahoney 			insert_ptr(trans, root, path, &disk_key, right->start,
3925c3e06965SJan Schmidt 					  path->slots[1], 1);
392644871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
392744871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
392844871b1bSChris Mason 			path->nodes[0] = right;
392944871b1bSChris Mason 			path->slots[0] = 0;
3930143bede5SJeff Mahoney 			if (path->slots[1] == 0)
3931143bede5SJeff Mahoney 				fixup_low_keys(trans, root, path,
3932143bede5SJeff Mahoney 					       &disk_key, 1);
39335d4f98a2SYan Zheng 		}
393444871b1bSChris Mason 		btrfs_mark_buffer_dirty(right);
393544871b1bSChris Mason 		return ret;
393644871b1bSChris Mason 	}
393744871b1bSChris Mason 
3938143bede5SJeff Mahoney 	copy_for_split(trans, root, path, l, right, slot, mid, nritems);
393944871b1bSChris Mason 
39405d4f98a2SYan Zheng 	if (split == 2) {
3941cc0c5538SChris Mason 		BUG_ON(num_doubles != 0);
3942cc0c5538SChris Mason 		num_doubles++;
3943cc0c5538SChris Mason 		goto again;
39443326d1b0SChris Mason 	}
394544871b1bSChris Mason 
3946143bede5SJeff Mahoney 	return 0;
394799d8f83cSChris Mason 
394899d8f83cSChris Mason push_for_double:
394999d8f83cSChris Mason 	push_for_double_split(trans, root, path, data_size);
395099d8f83cSChris Mason 	tried_avoid_double = 1;
395199d8f83cSChris Mason 	if (btrfs_leaf_free_space(root, path->nodes[0]) >= data_size)
395299d8f83cSChris Mason 		return 0;
395399d8f83cSChris Mason 	goto again;
3954be0e5c09SChris Mason }
3955be0e5c09SChris Mason 
3956ad48fd75SYan, Zheng static noinline int setup_leaf_for_split(struct btrfs_trans_handle *trans,
3957ad48fd75SYan, Zheng 					 struct btrfs_root *root,
3958ad48fd75SYan, Zheng 					 struct btrfs_path *path, int ins_len)
3959ad48fd75SYan, Zheng {
3960ad48fd75SYan, Zheng 	struct btrfs_key key;
3961ad48fd75SYan, Zheng 	struct extent_buffer *leaf;
3962ad48fd75SYan, Zheng 	struct btrfs_file_extent_item *fi;
3963ad48fd75SYan, Zheng 	u64 extent_len = 0;
3964ad48fd75SYan, Zheng 	u32 item_size;
3965ad48fd75SYan, Zheng 	int ret;
3966ad48fd75SYan, Zheng 
3967ad48fd75SYan, Zheng 	leaf = path->nodes[0];
3968ad48fd75SYan, Zheng 	btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3969ad48fd75SYan, Zheng 
3970ad48fd75SYan, Zheng 	BUG_ON(key.type != BTRFS_EXTENT_DATA_KEY &&
3971ad48fd75SYan, Zheng 	       key.type != BTRFS_EXTENT_CSUM_KEY);
3972ad48fd75SYan, Zheng 
3973ad48fd75SYan, Zheng 	if (btrfs_leaf_free_space(root, leaf) >= ins_len)
3974ad48fd75SYan, Zheng 		return 0;
3975ad48fd75SYan, Zheng 
3976ad48fd75SYan, Zheng 	item_size = btrfs_item_size_nr(leaf, path->slots[0]);
3977ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
3978ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
3979ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
3980ad48fd75SYan, Zheng 		extent_len = btrfs_file_extent_num_bytes(leaf, fi);
3981ad48fd75SYan, Zheng 	}
3982b3b4aa74SDavid Sterba 	btrfs_release_path(path);
3983ad48fd75SYan, Zheng 
3984ad48fd75SYan, Zheng 	path->keep_locks = 1;
3985ad48fd75SYan, Zheng 	path->search_for_split = 1;
3986ad48fd75SYan, Zheng 	ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
3987ad48fd75SYan, Zheng 	path->search_for_split = 0;
3988ad48fd75SYan, Zheng 	if (ret < 0)
3989ad48fd75SYan, Zheng 		goto err;
3990ad48fd75SYan, Zheng 
3991ad48fd75SYan, Zheng 	ret = -EAGAIN;
3992ad48fd75SYan, Zheng 	leaf = path->nodes[0];
3993ad48fd75SYan, Zheng 	/* if our item isn't there or got smaller, return now */
3994ad48fd75SYan, Zheng 	if (ret > 0 || item_size != btrfs_item_size_nr(leaf, path->slots[0]))
3995ad48fd75SYan, Zheng 		goto err;
3996ad48fd75SYan, Zheng 
3997109f6aefSChris Mason 	/* the leaf has  changed, it now has room.  return now */
3998109f6aefSChris Mason 	if (btrfs_leaf_free_space(root, path->nodes[0]) >= ins_len)
3999109f6aefSChris Mason 		goto err;
4000109f6aefSChris Mason 
4001ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
4002ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
4003ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
4004ad48fd75SYan, Zheng 		if (extent_len != btrfs_file_extent_num_bytes(leaf, fi))
4005ad48fd75SYan, Zheng 			goto err;
4006ad48fd75SYan, Zheng 	}
4007ad48fd75SYan, Zheng 
4008ad48fd75SYan, Zheng 	btrfs_set_path_blocking(path);
4009ad48fd75SYan, Zheng 	ret = split_leaf(trans, root, &key, path, ins_len, 1);
4010f0486c68SYan, Zheng 	if (ret)
4011f0486c68SYan, Zheng 		goto err;
4012ad48fd75SYan, Zheng 
4013ad48fd75SYan, Zheng 	path->keep_locks = 0;
4014ad48fd75SYan, Zheng 	btrfs_unlock_up_safe(path, 1);
4015ad48fd75SYan, Zheng 	return 0;
4016ad48fd75SYan, Zheng err:
4017ad48fd75SYan, Zheng 	path->keep_locks = 0;
4018ad48fd75SYan, Zheng 	return ret;
4019ad48fd75SYan, Zheng }
4020ad48fd75SYan, Zheng 
4021ad48fd75SYan, Zheng static noinline int split_item(struct btrfs_trans_handle *trans,
4022459931ecSChris Mason 			       struct btrfs_root *root,
4023459931ecSChris Mason 			       struct btrfs_path *path,
4024459931ecSChris Mason 			       struct btrfs_key *new_key,
4025459931ecSChris Mason 			       unsigned long split_offset)
4026459931ecSChris Mason {
4027459931ecSChris Mason 	struct extent_buffer *leaf;
4028459931ecSChris Mason 	struct btrfs_item *item;
4029459931ecSChris Mason 	struct btrfs_item *new_item;
4030459931ecSChris Mason 	int slot;
4031ad48fd75SYan, Zheng 	char *buf;
4032459931ecSChris Mason 	u32 nritems;
4033ad48fd75SYan, Zheng 	u32 item_size;
4034459931ecSChris Mason 	u32 orig_offset;
4035459931ecSChris Mason 	struct btrfs_disk_key disk_key;
4036459931ecSChris Mason 
4037459931ecSChris Mason 	leaf = path->nodes[0];
4038b9473439SChris Mason 	BUG_ON(btrfs_leaf_free_space(root, leaf) < sizeof(struct btrfs_item));
4039b9473439SChris Mason 
4040b4ce94deSChris Mason 	btrfs_set_path_blocking(path);
4041b4ce94deSChris Mason 
4042459931ecSChris Mason 	item = btrfs_item_nr(leaf, path->slots[0]);
4043459931ecSChris Mason 	orig_offset = btrfs_item_offset(leaf, item);
4044459931ecSChris Mason 	item_size = btrfs_item_size(leaf, item);
4045459931ecSChris Mason 
4046459931ecSChris Mason 	buf = kmalloc(item_size, GFP_NOFS);
4047ad48fd75SYan, Zheng 	if (!buf)
4048ad48fd75SYan, Zheng 		return -ENOMEM;
4049ad48fd75SYan, Zheng 
4050459931ecSChris Mason 	read_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf,
4051459931ecSChris Mason 			    path->slots[0]), item_size);
4052ad48fd75SYan, Zheng 
4053459931ecSChris Mason 	slot = path->slots[0] + 1;
4054459931ecSChris Mason 	nritems = btrfs_header_nritems(leaf);
4055459931ecSChris Mason 	if (slot != nritems) {
4056459931ecSChris Mason 		/* shift the items */
4057459931ecSChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + 1),
4058459931ecSChris Mason 				btrfs_item_nr_offset(slot),
4059459931ecSChris Mason 				(nritems - slot) * sizeof(struct btrfs_item));
4060459931ecSChris Mason 	}
4061459931ecSChris Mason 
4062459931ecSChris Mason 	btrfs_cpu_key_to_disk(&disk_key, new_key);
4063459931ecSChris Mason 	btrfs_set_item_key(leaf, &disk_key, slot);
4064459931ecSChris Mason 
4065459931ecSChris Mason 	new_item = btrfs_item_nr(leaf, slot);
4066459931ecSChris Mason 
4067459931ecSChris Mason 	btrfs_set_item_offset(leaf, new_item, orig_offset);
4068459931ecSChris Mason 	btrfs_set_item_size(leaf, new_item, item_size - split_offset);
4069459931ecSChris Mason 
4070459931ecSChris Mason 	btrfs_set_item_offset(leaf, item,
4071459931ecSChris Mason 			      orig_offset + item_size - split_offset);
4072459931ecSChris Mason 	btrfs_set_item_size(leaf, item, split_offset);
4073459931ecSChris Mason 
4074459931ecSChris Mason 	btrfs_set_header_nritems(leaf, nritems + 1);
4075459931ecSChris Mason 
4076459931ecSChris Mason 	/* write the data for the start of the original item */
4077459931ecSChris Mason 	write_extent_buffer(leaf, buf,
4078459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, path->slots[0]),
4079459931ecSChris Mason 			    split_offset);
4080459931ecSChris Mason 
4081459931ecSChris Mason 	/* write the data for the new item */
4082459931ecSChris Mason 	write_extent_buffer(leaf, buf + split_offset,
4083459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, slot),
4084459931ecSChris Mason 			    item_size - split_offset);
4085459931ecSChris Mason 	btrfs_mark_buffer_dirty(leaf);
4086459931ecSChris Mason 
4087ad48fd75SYan, Zheng 	BUG_ON(btrfs_leaf_free_space(root, leaf) < 0);
4088459931ecSChris Mason 	kfree(buf);
4089ad48fd75SYan, Zheng 	return 0;
4090ad48fd75SYan, Zheng }
4091ad48fd75SYan, Zheng 
4092ad48fd75SYan, Zheng /*
4093ad48fd75SYan, Zheng  * This function splits a single item into two items,
4094ad48fd75SYan, Zheng  * giving 'new_key' to the new item and splitting the
4095ad48fd75SYan, Zheng  * old one at split_offset (from the start of the item).
4096ad48fd75SYan, Zheng  *
4097ad48fd75SYan, Zheng  * The path may be released by this operation.  After
4098ad48fd75SYan, Zheng  * the split, the path is pointing to the old item.  The
4099ad48fd75SYan, Zheng  * new item is going to be in the same node as the old one.
4100ad48fd75SYan, Zheng  *
4101ad48fd75SYan, Zheng  * Note, the item being split must be smaller enough to live alone on
4102ad48fd75SYan, Zheng  * a tree block with room for one extra struct btrfs_item
4103ad48fd75SYan, Zheng  *
4104ad48fd75SYan, Zheng  * This allows us to split the item in place, keeping a lock on the
4105ad48fd75SYan, Zheng  * leaf the entire time.
4106ad48fd75SYan, Zheng  */
4107ad48fd75SYan, Zheng int btrfs_split_item(struct btrfs_trans_handle *trans,
4108ad48fd75SYan, Zheng 		     struct btrfs_root *root,
4109ad48fd75SYan, Zheng 		     struct btrfs_path *path,
4110ad48fd75SYan, Zheng 		     struct btrfs_key *new_key,
4111ad48fd75SYan, Zheng 		     unsigned long split_offset)
4112ad48fd75SYan, Zheng {
4113ad48fd75SYan, Zheng 	int ret;
4114ad48fd75SYan, Zheng 	ret = setup_leaf_for_split(trans, root, path,
4115ad48fd75SYan, Zheng 				   sizeof(struct btrfs_item));
4116ad48fd75SYan, Zheng 	if (ret)
4117459931ecSChris Mason 		return ret;
4118ad48fd75SYan, Zheng 
4119ad48fd75SYan, Zheng 	ret = split_item(trans, root, path, new_key, split_offset);
4120ad48fd75SYan, Zheng 	return ret;
4121ad48fd75SYan, Zheng }
4122ad48fd75SYan, Zheng 
4123ad48fd75SYan, Zheng /*
4124ad48fd75SYan, Zheng  * This function duplicate a item, giving 'new_key' to the new item.
4125ad48fd75SYan, Zheng  * It guarantees both items live in the same tree leaf and the new item
4126ad48fd75SYan, Zheng  * is contiguous with the original item.
4127ad48fd75SYan, Zheng  *
4128ad48fd75SYan, Zheng  * This allows us to split file extent in place, keeping a lock on the
4129ad48fd75SYan, Zheng  * leaf the entire time.
4130ad48fd75SYan, Zheng  */
4131ad48fd75SYan, Zheng int btrfs_duplicate_item(struct btrfs_trans_handle *trans,
4132ad48fd75SYan, Zheng 			 struct btrfs_root *root,
4133ad48fd75SYan, Zheng 			 struct btrfs_path *path,
4134ad48fd75SYan, Zheng 			 struct btrfs_key *new_key)
4135ad48fd75SYan, Zheng {
4136ad48fd75SYan, Zheng 	struct extent_buffer *leaf;
4137ad48fd75SYan, Zheng 	int ret;
4138ad48fd75SYan, Zheng 	u32 item_size;
4139ad48fd75SYan, Zheng 
4140ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4141ad48fd75SYan, Zheng 	item_size = btrfs_item_size_nr(leaf, path->slots[0]);
4142ad48fd75SYan, Zheng 	ret = setup_leaf_for_split(trans, root, path,
4143ad48fd75SYan, Zheng 				   item_size + sizeof(struct btrfs_item));
4144ad48fd75SYan, Zheng 	if (ret)
4145ad48fd75SYan, Zheng 		return ret;
4146ad48fd75SYan, Zheng 
4147ad48fd75SYan, Zheng 	path->slots[0]++;
4148143bede5SJeff Mahoney 	setup_items_for_insert(trans, root, path, new_key, &item_size,
4149ad48fd75SYan, Zheng 			       item_size, item_size +
4150ad48fd75SYan, Zheng 			       sizeof(struct btrfs_item), 1);
4151ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4152ad48fd75SYan, Zheng 	memcpy_extent_buffer(leaf,
4153ad48fd75SYan, Zheng 			     btrfs_item_ptr_offset(leaf, path->slots[0]),
4154ad48fd75SYan, Zheng 			     btrfs_item_ptr_offset(leaf, path->slots[0] - 1),
4155ad48fd75SYan, Zheng 			     item_size);
4156ad48fd75SYan, Zheng 	return 0;
4157459931ecSChris Mason }
4158459931ecSChris Mason 
4159459931ecSChris Mason /*
4160d352ac68SChris Mason  * make the item pointed to by the path smaller.  new_size indicates
4161d352ac68SChris Mason  * how small to make it, and from_end tells us if we just chop bytes
4162d352ac68SChris Mason  * off the end of the item or if we shift the item to chop bytes off
4163d352ac68SChris Mason  * the front.
4164d352ac68SChris Mason  */
4165143bede5SJeff Mahoney void btrfs_truncate_item(struct btrfs_trans_handle *trans,
4166b18c6685SChris Mason 			 struct btrfs_root *root,
4167b18c6685SChris Mason 			 struct btrfs_path *path,
4168179e29e4SChris Mason 			 u32 new_size, int from_end)
4169b18c6685SChris Mason {
4170b18c6685SChris Mason 	int slot;
41715f39d397SChris Mason 	struct extent_buffer *leaf;
41725f39d397SChris Mason 	struct btrfs_item *item;
4173b18c6685SChris Mason 	u32 nritems;
4174b18c6685SChris Mason 	unsigned int data_end;
4175b18c6685SChris Mason 	unsigned int old_data_start;
4176b18c6685SChris Mason 	unsigned int old_size;
4177b18c6685SChris Mason 	unsigned int size_diff;
4178b18c6685SChris Mason 	int i;
4179cfed81a0SChris Mason 	struct btrfs_map_token token;
4180cfed81a0SChris Mason 
4181cfed81a0SChris Mason 	btrfs_init_map_token(&token);
4182b18c6685SChris Mason 
41835f39d397SChris Mason 	leaf = path->nodes[0];
4184179e29e4SChris Mason 	slot = path->slots[0];
4185179e29e4SChris Mason 
4186179e29e4SChris Mason 	old_size = btrfs_item_size_nr(leaf, slot);
4187179e29e4SChris Mason 	if (old_size == new_size)
4188143bede5SJeff Mahoney 		return;
4189b18c6685SChris Mason 
41905f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
4191b18c6685SChris Mason 	data_end = leaf_data_end(root, leaf);
4192b18c6685SChris Mason 
41935f39d397SChris Mason 	old_data_start = btrfs_item_offset_nr(leaf, slot);
4194179e29e4SChris Mason 
4195b18c6685SChris Mason 	size_diff = old_size - new_size;
4196b18c6685SChris Mason 
4197b18c6685SChris Mason 	BUG_ON(slot < 0);
4198b18c6685SChris Mason 	BUG_ON(slot >= nritems);
4199b18c6685SChris Mason 
4200b18c6685SChris Mason 	/*
4201b18c6685SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4202b18c6685SChris Mason 	 */
4203b18c6685SChris Mason 	/* first correct the data pointers */
4204b18c6685SChris Mason 	for (i = slot; i < nritems; i++) {
42055f39d397SChris Mason 		u32 ioff;
42065f39d397SChris Mason 		item = btrfs_item_nr(leaf, i);
4207db94535dSChris Mason 
4208cfed81a0SChris Mason 		ioff = btrfs_token_item_offset(leaf, item, &token);
4209cfed81a0SChris Mason 		btrfs_set_token_item_offset(leaf, item,
4210cfed81a0SChris Mason 					    ioff + size_diff, &token);
4211b18c6685SChris Mason 	}
4212db94535dSChris Mason 
4213b18c6685SChris Mason 	/* shift the data */
4214179e29e4SChris Mason 	if (from_end) {
42155f39d397SChris Mason 		memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
4216b18c6685SChris Mason 			      data_end + size_diff, btrfs_leaf_data(leaf) +
4217b18c6685SChris Mason 			      data_end, old_data_start + new_size - data_end);
4218179e29e4SChris Mason 	} else {
4219179e29e4SChris Mason 		struct btrfs_disk_key disk_key;
4220179e29e4SChris Mason 		u64 offset;
4221179e29e4SChris Mason 
4222179e29e4SChris Mason 		btrfs_item_key(leaf, &disk_key, slot);
4223179e29e4SChris Mason 
4224179e29e4SChris Mason 		if (btrfs_disk_key_type(&disk_key) == BTRFS_EXTENT_DATA_KEY) {
4225179e29e4SChris Mason 			unsigned long ptr;
4226179e29e4SChris Mason 			struct btrfs_file_extent_item *fi;
4227179e29e4SChris Mason 
4228179e29e4SChris Mason 			fi = btrfs_item_ptr(leaf, slot,
4229179e29e4SChris Mason 					    struct btrfs_file_extent_item);
4230179e29e4SChris Mason 			fi = (struct btrfs_file_extent_item *)(
4231179e29e4SChris Mason 			     (unsigned long)fi - size_diff);
4232179e29e4SChris Mason 
4233179e29e4SChris Mason 			if (btrfs_file_extent_type(leaf, fi) ==
4234179e29e4SChris Mason 			    BTRFS_FILE_EXTENT_INLINE) {
4235179e29e4SChris Mason 				ptr = btrfs_item_ptr_offset(leaf, slot);
4236179e29e4SChris Mason 				memmove_extent_buffer(leaf, ptr,
4237179e29e4SChris Mason 				      (unsigned long)fi,
4238179e29e4SChris Mason 				      offsetof(struct btrfs_file_extent_item,
4239179e29e4SChris Mason 						 disk_bytenr));
4240179e29e4SChris Mason 			}
4241179e29e4SChris Mason 		}
4242179e29e4SChris Mason 
4243179e29e4SChris Mason 		memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
4244179e29e4SChris Mason 			      data_end + size_diff, btrfs_leaf_data(leaf) +
4245179e29e4SChris Mason 			      data_end, old_data_start - data_end);
4246179e29e4SChris Mason 
4247179e29e4SChris Mason 		offset = btrfs_disk_key_offset(&disk_key);
4248179e29e4SChris Mason 		btrfs_set_disk_key_offset(&disk_key, offset + size_diff);
4249179e29e4SChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot);
4250179e29e4SChris Mason 		if (slot == 0)
4251179e29e4SChris Mason 			fixup_low_keys(trans, root, path, &disk_key, 1);
4252179e29e4SChris Mason 	}
42535f39d397SChris Mason 
42545f39d397SChris Mason 	item = btrfs_item_nr(leaf, slot);
42555f39d397SChris Mason 	btrfs_set_item_size(leaf, item, new_size);
42565f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
4257b18c6685SChris Mason 
42585f39d397SChris Mason 	if (btrfs_leaf_free_space(root, leaf) < 0) {
42595f39d397SChris Mason 		btrfs_print_leaf(root, leaf);
4260b18c6685SChris Mason 		BUG();
42615f39d397SChris Mason 	}
4262b18c6685SChris Mason }
4263b18c6685SChris Mason 
4264d352ac68SChris Mason /*
4265d352ac68SChris Mason  * make the item pointed to by the path bigger, data_size is the new size.
4266d352ac68SChris Mason  */
4267143bede5SJeff Mahoney void btrfs_extend_item(struct btrfs_trans_handle *trans,
42685f39d397SChris Mason 		       struct btrfs_root *root, struct btrfs_path *path,
42695f39d397SChris Mason 		       u32 data_size)
42706567e837SChris Mason {
42716567e837SChris Mason 	int slot;
42725f39d397SChris Mason 	struct extent_buffer *leaf;
42735f39d397SChris Mason 	struct btrfs_item *item;
42746567e837SChris Mason 	u32 nritems;
42756567e837SChris Mason 	unsigned int data_end;
42766567e837SChris Mason 	unsigned int old_data;
42776567e837SChris Mason 	unsigned int old_size;
42786567e837SChris Mason 	int i;
4279cfed81a0SChris Mason 	struct btrfs_map_token token;
4280cfed81a0SChris Mason 
4281cfed81a0SChris Mason 	btrfs_init_map_token(&token);
42826567e837SChris Mason 
42835f39d397SChris Mason 	leaf = path->nodes[0];
42846567e837SChris Mason 
42855f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
42866567e837SChris Mason 	data_end = leaf_data_end(root, leaf);
42876567e837SChris Mason 
42885f39d397SChris Mason 	if (btrfs_leaf_free_space(root, leaf) < data_size) {
42895f39d397SChris Mason 		btrfs_print_leaf(root, leaf);
42906567e837SChris Mason 		BUG();
42915f39d397SChris Mason 	}
42926567e837SChris Mason 	slot = path->slots[0];
42935f39d397SChris Mason 	old_data = btrfs_item_end_nr(leaf, slot);
42946567e837SChris Mason 
42956567e837SChris Mason 	BUG_ON(slot < 0);
42963326d1b0SChris Mason 	if (slot >= nritems) {
42973326d1b0SChris Mason 		btrfs_print_leaf(root, leaf);
4298d397712bSChris Mason 		printk(KERN_CRIT "slot %d too large, nritems %d\n",
4299d397712bSChris Mason 		       slot, nritems);
43003326d1b0SChris Mason 		BUG_ON(1);
43013326d1b0SChris Mason 	}
43026567e837SChris Mason 
43036567e837SChris Mason 	/*
43046567e837SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
43056567e837SChris Mason 	 */
43066567e837SChris Mason 	/* first correct the data pointers */
43076567e837SChris Mason 	for (i = slot; i < nritems; i++) {
43085f39d397SChris Mason 		u32 ioff;
43095f39d397SChris Mason 		item = btrfs_item_nr(leaf, i);
4310db94535dSChris Mason 
4311cfed81a0SChris Mason 		ioff = btrfs_token_item_offset(leaf, item, &token);
4312cfed81a0SChris Mason 		btrfs_set_token_item_offset(leaf, item,
4313cfed81a0SChris Mason 					    ioff - data_size, &token);
43146567e837SChris Mason 	}
43155f39d397SChris Mason 
43166567e837SChris Mason 	/* shift the data */
43175f39d397SChris Mason 	memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
43186567e837SChris Mason 		      data_end - data_size, btrfs_leaf_data(leaf) +
43196567e837SChris Mason 		      data_end, old_data - data_end);
43205f39d397SChris Mason 
43216567e837SChris Mason 	data_end = old_data;
43225f39d397SChris Mason 	old_size = btrfs_item_size_nr(leaf, slot);
43235f39d397SChris Mason 	item = btrfs_item_nr(leaf, slot);
43245f39d397SChris Mason 	btrfs_set_item_size(leaf, item, old_size + data_size);
43255f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
43266567e837SChris Mason 
43275f39d397SChris Mason 	if (btrfs_leaf_free_space(root, leaf) < 0) {
43285f39d397SChris Mason 		btrfs_print_leaf(root, leaf);
43296567e837SChris Mason 		BUG();
43305f39d397SChris Mason 	}
43316567e837SChris Mason }
43326567e837SChris Mason 
433374123bd7SChris Mason /*
4334d352ac68SChris Mason  * Given a key and some data, insert items into the tree.
433574123bd7SChris Mason  * This does all the path init required, making room in the tree if needed.
4336f3465ca4SJosef Bacik  * Returns the number of keys that were inserted.
4337f3465ca4SJosef Bacik  */
4338f3465ca4SJosef Bacik int btrfs_insert_some_items(struct btrfs_trans_handle *trans,
4339f3465ca4SJosef Bacik 			    struct btrfs_root *root,
4340f3465ca4SJosef Bacik 			    struct btrfs_path *path,
4341f3465ca4SJosef Bacik 			    struct btrfs_key *cpu_key, u32 *data_size,
4342f3465ca4SJosef Bacik 			    int nr)
4343f3465ca4SJosef Bacik {
4344f3465ca4SJosef Bacik 	struct extent_buffer *leaf;
4345f3465ca4SJosef Bacik 	struct btrfs_item *item;
4346f3465ca4SJosef Bacik 	int ret = 0;
4347f3465ca4SJosef Bacik 	int slot;
4348f3465ca4SJosef Bacik 	int i;
4349f3465ca4SJosef Bacik 	u32 nritems;
4350f3465ca4SJosef Bacik 	u32 total_data = 0;
4351f3465ca4SJosef Bacik 	u32 total_size = 0;
4352f3465ca4SJosef Bacik 	unsigned int data_end;
4353f3465ca4SJosef Bacik 	struct btrfs_disk_key disk_key;
4354f3465ca4SJosef Bacik 	struct btrfs_key found_key;
4355cfed81a0SChris Mason 	struct btrfs_map_token token;
4356cfed81a0SChris Mason 
4357cfed81a0SChris Mason 	btrfs_init_map_token(&token);
4358f3465ca4SJosef Bacik 
435987b29b20SYan Zheng 	for (i = 0; i < nr; i++) {
436087b29b20SYan Zheng 		if (total_size + data_size[i] + sizeof(struct btrfs_item) >
436187b29b20SYan Zheng 		    BTRFS_LEAF_DATA_SIZE(root)) {
436287b29b20SYan Zheng 			break;
436387b29b20SYan Zheng 			nr = i;
436487b29b20SYan Zheng 		}
4365f3465ca4SJosef Bacik 		total_data += data_size[i];
436687b29b20SYan Zheng 		total_size += data_size[i] + sizeof(struct btrfs_item);
436787b29b20SYan Zheng 	}
436887b29b20SYan Zheng 	BUG_ON(nr == 0);
4369f3465ca4SJosef Bacik 
4370f3465ca4SJosef Bacik 	ret = btrfs_search_slot(trans, root, cpu_key, path, total_size, 1);
4371f3465ca4SJosef Bacik 	if (ret == 0)
4372f3465ca4SJosef Bacik 		return -EEXIST;
4373f3465ca4SJosef Bacik 	if (ret < 0)
4374f3465ca4SJosef Bacik 		goto out;
4375f3465ca4SJosef Bacik 
4376f3465ca4SJosef Bacik 	leaf = path->nodes[0];
4377f3465ca4SJosef Bacik 
4378f3465ca4SJosef Bacik 	nritems = btrfs_header_nritems(leaf);
4379f3465ca4SJosef Bacik 	data_end = leaf_data_end(root, leaf);
4380f3465ca4SJosef Bacik 
4381f3465ca4SJosef Bacik 	if (btrfs_leaf_free_space(root, leaf) < total_size) {
4382f3465ca4SJosef Bacik 		for (i = nr; i >= 0; i--) {
4383f3465ca4SJosef Bacik 			total_data -= data_size[i];
4384f3465ca4SJosef Bacik 			total_size -= data_size[i] + sizeof(struct btrfs_item);
4385f3465ca4SJosef Bacik 			if (total_size < btrfs_leaf_free_space(root, leaf))
4386f3465ca4SJosef Bacik 				break;
4387f3465ca4SJosef Bacik 		}
4388f3465ca4SJosef Bacik 		nr = i;
4389f3465ca4SJosef Bacik 	}
4390f3465ca4SJosef Bacik 
4391f3465ca4SJosef Bacik 	slot = path->slots[0];
4392f3465ca4SJosef Bacik 	BUG_ON(slot < 0);
4393f3465ca4SJosef Bacik 
4394f3465ca4SJosef Bacik 	if (slot != nritems) {
4395f3465ca4SJosef Bacik 		unsigned int old_data = btrfs_item_end_nr(leaf, slot);
4396f3465ca4SJosef Bacik 
4397f3465ca4SJosef Bacik 		item = btrfs_item_nr(leaf, slot);
4398f3465ca4SJosef Bacik 		btrfs_item_key_to_cpu(leaf, &found_key, slot);
4399f3465ca4SJosef Bacik 
4400f3465ca4SJosef Bacik 		/* figure out how many keys we can insert in here */
4401f3465ca4SJosef Bacik 		total_data = data_size[0];
4402f3465ca4SJosef Bacik 		for (i = 1; i < nr; i++) {
44035d4f98a2SYan Zheng 			if (btrfs_comp_cpu_keys(&found_key, cpu_key + i) <= 0)
4404f3465ca4SJosef Bacik 				break;
4405f3465ca4SJosef Bacik 			total_data += data_size[i];
4406f3465ca4SJosef Bacik 		}
4407f3465ca4SJosef Bacik 		nr = i;
4408f3465ca4SJosef Bacik 
4409f3465ca4SJosef Bacik 		if (old_data < data_end) {
4410f3465ca4SJosef Bacik 			btrfs_print_leaf(root, leaf);
4411d397712bSChris Mason 			printk(KERN_CRIT "slot %d old_data %d data_end %d\n",
4412f3465ca4SJosef Bacik 			       slot, old_data, data_end);
4413f3465ca4SJosef Bacik 			BUG_ON(1);
4414f3465ca4SJosef Bacik 		}
4415f3465ca4SJosef Bacik 		/*
4416f3465ca4SJosef Bacik 		 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4417f3465ca4SJosef Bacik 		 */
4418f3465ca4SJosef Bacik 		/* first correct the data pointers */
4419f3465ca4SJosef Bacik 		for (i = slot; i < nritems; i++) {
4420f3465ca4SJosef Bacik 			u32 ioff;
4421f3465ca4SJosef Bacik 
4422f3465ca4SJosef Bacik 			item = btrfs_item_nr(leaf, i);
4423cfed81a0SChris Mason 			ioff = btrfs_token_item_offset(leaf, item, &token);
4424cfed81a0SChris Mason 			btrfs_set_token_item_offset(leaf, item,
4425cfed81a0SChris Mason 						    ioff - total_data, &token);
4426f3465ca4SJosef Bacik 		}
4427f3465ca4SJosef Bacik 		/* shift the items */
4428f3465ca4SJosef Bacik 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + nr),
4429f3465ca4SJosef Bacik 			      btrfs_item_nr_offset(slot),
4430f3465ca4SJosef Bacik 			      (nritems - slot) * sizeof(struct btrfs_item));
4431f3465ca4SJosef Bacik 
4432f3465ca4SJosef Bacik 		/* shift the data */
4433f3465ca4SJosef Bacik 		memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
4434f3465ca4SJosef Bacik 			      data_end - total_data, btrfs_leaf_data(leaf) +
4435f3465ca4SJosef Bacik 			      data_end, old_data - data_end);
4436f3465ca4SJosef Bacik 		data_end = old_data;
4437f3465ca4SJosef Bacik 	} else {
4438f3465ca4SJosef Bacik 		/*
4439f3465ca4SJosef Bacik 		 * this sucks but it has to be done, if we are inserting at
4440f3465ca4SJosef Bacik 		 * the end of the leaf only insert 1 of the items, since we
4441f3465ca4SJosef Bacik 		 * have no way of knowing whats on the next leaf and we'd have
4442f3465ca4SJosef Bacik 		 * to drop our current locks to figure it out
4443f3465ca4SJosef Bacik 		 */
4444f3465ca4SJosef Bacik 		nr = 1;
4445f3465ca4SJosef Bacik 	}
4446f3465ca4SJosef Bacik 
4447f3465ca4SJosef Bacik 	/* setup the item for the new data */
4448f3465ca4SJosef Bacik 	for (i = 0; i < nr; i++) {
4449f3465ca4SJosef Bacik 		btrfs_cpu_key_to_disk(&disk_key, cpu_key + i);
4450f3465ca4SJosef Bacik 		btrfs_set_item_key(leaf, &disk_key, slot + i);
4451f3465ca4SJosef Bacik 		item = btrfs_item_nr(leaf, slot + i);
4452cfed81a0SChris Mason 		btrfs_set_token_item_offset(leaf, item,
4453cfed81a0SChris Mason 					    data_end - data_size[i], &token);
4454f3465ca4SJosef Bacik 		data_end -= data_size[i];
4455cfed81a0SChris Mason 		btrfs_set_token_item_size(leaf, item, data_size[i], &token);
4456f3465ca4SJosef Bacik 	}
4457f3465ca4SJosef Bacik 	btrfs_set_header_nritems(leaf, nritems + nr);
4458f3465ca4SJosef Bacik 	btrfs_mark_buffer_dirty(leaf);
4459f3465ca4SJosef Bacik 
4460f3465ca4SJosef Bacik 	ret = 0;
4461f3465ca4SJosef Bacik 	if (slot == 0) {
4462f3465ca4SJosef Bacik 		btrfs_cpu_key_to_disk(&disk_key, cpu_key);
4463143bede5SJeff Mahoney 		fixup_low_keys(trans, root, path, &disk_key, 1);
4464f3465ca4SJosef Bacik 	}
4465f3465ca4SJosef Bacik 
4466f3465ca4SJosef Bacik 	if (btrfs_leaf_free_space(root, leaf) < 0) {
4467f3465ca4SJosef Bacik 		btrfs_print_leaf(root, leaf);
4468f3465ca4SJosef Bacik 		BUG();
4469f3465ca4SJosef Bacik 	}
4470f3465ca4SJosef Bacik out:
4471f3465ca4SJosef Bacik 	if (!ret)
4472f3465ca4SJosef Bacik 		ret = nr;
4473f3465ca4SJosef Bacik 	return ret;
4474f3465ca4SJosef Bacik }
4475f3465ca4SJosef Bacik 
4476f3465ca4SJosef Bacik /*
447744871b1bSChris Mason  * this is a helper for btrfs_insert_empty_items, the main goal here is
447844871b1bSChris Mason  * to save stack depth by doing the bulk of the work in a function
447944871b1bSChris Mason  * that doesn't call btrfs_search_slot
448074123bd7SChris Mason  */
4481143bede5SJeff Mahoney void setup_items_for_insert(struct btrfs_trans_handle *trans,
448244871b1bSChris Mason 			    struct btrfs_root *root, struct btrfs_path *path,
44839c58309dSChris Mason 			    struct btrfs_key *cpu_key, u32 *data_size,
448444871b1bSChris Mason 			    u32 total_data, u32 total_size, int nr)
4485be0e5c09SChris Mason {
44865f39d397SChris Mason 	struct btrfs_item *item;
44879c58309dSChris Mason 	int i;
44887518a238SChris Mason 	u32 nritems;
4489be0e5c09SChris Mason 	unsigned int data_end;
4490e2fa7227SChris Mason 	struct btrfs_disk_key disk_key;
449144871b1bSChris Mason 	struct extent_buffer *leaf;
449244871b1bSChris Mason 	int slot;
4493cfed81a0SChris Mason 	struct btrfs_map_token token;
4494cfed81a0SChris Mason 
4495cfed81a0SChris Mason 	btrfs_init_map_token(&token);
4496e2fa7227SChris Mason 
44975f39d397SChris Mason 	leaf = path->nodes[0];
449844871b1bSChris Mason 	slot = path->slots[0];
449974123bd7SChris Mason 
45005f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
4501123abc88SChris Mason 	data_end = leaf_data_end(root, leaf);
4502eb60ceacSChris Mason 
4503f25956ccSChris Mason 	if (btrfs_leaf_free_space(root, leaf) < total_size) {
45043326d1b0SChris Mason 		btrfs_print_leaf(root, leaf);
4505d397712bSChris Mason 		printk(KERN_CRIT "not enough freespace need %u have %d\n",
45069c58309dSChris Mason 		       total_size, btrfs_leaf_free_space(root, leaf));
4507be0e5c09SChris Mason 		BUG();
4508d4dbff95SChris Mason 	}
45095f39d397SChris Mason 
4510be0e5c09SChris Mason 	if (slot != nritems) {
45115f39d397SChris Mason 		unsigned int old_data = btrfs_item_end_nr(leaf, slot);
4512be0e5c09SChris Mason 
45135f39d397SChris Mason 		if (old_data < data_end) {
45145f39d397SChris Mason 			btrfs_print_leaf(root, leaf);
4515d397712bSChris Mason 			printk(KERN_CRIT "slot %d old_data %d data_end %d\n",
45165f39d397SChris Mason 			       slot, old_data, data_end);
45175f39d397SChris Mason 			BUG_ON(1);
45185f39d397SChris Mason 		}
4519be0e5c09SChris Mason 		/*
4520be0e5c09SChris Mason 		 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4521be0e5c09SChris Mason 		 */
4522be0e5c09SChris Mason 		/* first correct the data pointers */
45230783fcfcSChris Mason 		for (i = slot; i < nritems; i++) {
45245f39d397SChris Mason 			u32 ioff;
4525db94535dSChris Mason 
45265f39d397SChris Mason 			item = btrfs_item_nr(leaf, i);
4527cfed81a0SChris Mason 			ioff = btrfs_token_item_offset(leaf, item, &token);
4528cfed81a0SChris Mason 			btrfs_set_token_item_offset(leaf, item,
4529cfed81a0SChris Mason 						    ioff - total_data, &token);
45300783fcfcSChris Mason 		}
4531be0e5c09SChris Mason 		/* shift the items */
45329c58309dSChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + nr),
45335f39d397SChris Mason 			      btrfs_item_nr_offset(slot),
45340783fcfcSChris Mason 			      (nritems - slot) * sizeof(struct btrfs_item));
4535be0e5c09SChris Mason 
4536be0e5c09SChris Mason 		/* shift the data */
45375f39d397SChris Mason 		memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
45389c58309dSChris Mason 			      data_end - total_data, btrfs_leaf_data(leaf) +
4539be0e5c09SChris Mason 			      data_end, old_data - data_end);
4540be0e5c09SChris Mason 		data_end = old_data;
4541be0e5c09SChris Mason 	}
45425f39d397SChris Mason 
454362e2749eSChris Mason 	/* setup the item for the new data */
45449c58309dSChris Mason 	for (i = 0; i < nr; i++) {
45459c58309dSChris Mason 		btrfs_cpu_key_to_disk(&disk_key, cpu_key + i);
45469c58309dSChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot + i);
45479c58309dSChris Mason 		item = btrfs_item_nr(leaf, slot + i);
4548cfed81a0SChris Mason 		btrfs_set_token_item_offset(leaf, item,
4549cfed81a0SChris Mason 					    data_end - data_size[i], &token);
45509c58309dSChris Mason 		data_end -= data_size[i];
4551cfed81a0SChris Mason 		btrfs_set_token_item_size(leaf, item, data_size[i], &token);
45529c58309dSChris Mason 	}
455344871b1bSChris Mason 
45549c58309dSChris Mason 	btrfs_set_header_nritems(leaf, nritems + nr);
4555aa5d6bedSChris Mason 
45565a01a2e3SChris Mason 	if (slot == 0) {
45575a01a2e3SChris Mason 		btrfs_cpu_key_to_disk(&disk_key, cpu_key);
4558143bede5SJeff Mahoney 		fixup_low_keys(trans, root, path, &disk_key, 1);
45595a01a2e3SChris Mason 	}
4560b9473439SChris Mason 	btrfs_unlock_up_safe(path, 1);
4561b9473439SChris Mason 	btrfs_mark_buffer_dirty(leaf);
4562aa5d6bedSChris Mason 
45635f39d397SChris Mason 	if (btrfs_leaf_free_space(root, leaf) < 0) {
45645f39d397SChris Mason 		btrfs_print_leaf(root, leaf);
4565be0e5c09SChris Mason 		BUG();
45665f39d397SChris Mason 	}
456744871b1bSChris Mason }
456844871b1bSChris Mason 
456944871b1bSChris Mason /*
457044871b1bSChris Mason  * Given a key and some data, insert items into the tree.
457144871b1bSChris Mason  * This does all the path init required, making room in the tree if needed.
457244871b1bSChris Mason  */
457344871b1bSChris Mason int btrfs_insert_empty_items(struct btrfs_trans_handle *trans,
457444871b1bSChris Mason 			    struct btrfs_root *root,
457544871b1bSChris Mason 			    struct btrfs_path *path,
457644871b1bSChris Mason 			    struct btrfs_key *cpu_key, u32 *data_size,
457744871b1bSChris Mason 			    int nr)
457844871b1bSChris Mason {
457944871b1bSChris Mason 	int ret = 0;
458044871b1bSChris Mason 	int slot;
458144871b1bSChris Mason 	int i;
458244871b1bSChris Mason 	u32 total_size = 0;
458344871b1bSChris Mason 	u32 total_data = 0;
458444871b1bSChris Mason 
458544871b1bSChris Mason 	for (i = 0; i < nr; i++)
458644871b1bSChris Mason 		total_data += data_size[i];
458744871b1bSChris Mason 
458844871b1bSChris Mason 	total_size = total_data + (nr * sizeof(struct btrfs_item));
458944871b1bSChris Mason 	ret = btrfs_search_slot(trans, root, cpu_key, path, total_size, 1);
459044871b1bSChris Mason 	if (ret == 0)
459144871b1bSChris Mason 		return -EEXIST;
459244871b1bSChris Mason 	if (ret < 0)
4593143bede5SJeff Mahoney 		return ret;
459444871b1bSChris Mason 
459544871b1bSChris Mason 	slot = path->slots[0];
459644871b1bSChris Mason 	BUG_ON(slot < 0);
459744871b1bSChris Mason 
4598143bede5SJeff Mahoney 	setup_items_for_insert(trans, root, path, cpu_key, data_size,
459944871b1bSChris Mason 			       total_data, total_size, nr);
4600143bede5SJeff Mahoney 	return 0;
460162e2749eSChris Mason }
460262e2749eSChris Mason 
460362e2749eSChris Mason /*
460462e2749eSChris Mason  * Given a key and some data, insert an item into the tree.
460562e2749eSChris Mason  * This does all the path init required, making room in the tree if needed.
460662e2749eSChris Mason  */
4607e089f05cSChris Mason int btrfs_insert_item(struct btrfs_trans_handle *trans, struct btrfs_root
4608e089f05cSChris Mason 		      *root, struct btrfs_key *cpu_key, void *data, u32
4609e089f05cSChris Mason 		      data_size)
461062e2749eSChris Mason {
461162e2749eSChris Mason 	int ret = 0;
46122c90e5d6SChris Mason 	struct btrfs_path *path;
46135f39d397SChris Mason 	struct extent_buffer *leaf;
46145f39d397SChris Mason 	unsigned long ptr;
461562e2749eSChris Mason 
46162c90e5d6SChris Mason 	path = btrfs_alloc_path();
4617db5b493aSTsutomu Itoh 	if (!path)
4618db5b493aSTsutomu Itoh 		return -ENOMEM;
46192c90e5d6SChris Mason 	ret = btrfs_insert_empty_item(trans, root, path, cpu_key, data_size);
462062e2749eSChris Mason 	if (!ret) {
46215f39d397SChris Mason 		leaf = path->nodes[0];
46225f39d397SChris Mason 		ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
46235f39d397SChris Mason 		write_extent_buffer(leaf, data, ptr, data_size);
46245f39d397SChris Mason 		btrfs_mark_buffer_dirty(leaf);
462562e2749eSChris Mason 	}
46262c90e5d6SChris Mason 	btrfs_free_path(path);
4627aa5d6bedSChris Mason 	return ret;
4628be0e5c09SChris Mason }
4629be0e5c09SChris Mason 
463074123bd7SChris Mason /*
46315de08d7dSChris Mason  * delete the pointer from a given node.
463274123bd7SChris Mason  *
4633d352ac68SChris Mason  * the tree should have been previously balanced so the deletion does not
4634d352ac68SChris Mason  * empty a node.
463574123bd7SChris Mason  */
4636143bede5SJeff Mahoney static void del_ptr(struct btrfs_trans_handle *trans, struct btrfs_root *root,
4637f3ea38daSJan Schmidt 		    struct btrfs_path *path, int level, int slot,
4638f3ea38daSJan Schmidt 		    int tree_mod_log)
4639be0e5c09SChris Mason {
46405f39d397SChris Mason 	struct extent_buffer *parent = path->nodes[level];
46417518a238SChris Mason 	u32 nritems;
4642f3ea38daSJan Schmidt 	int ret;
4643be0e5c09SChris Mason 
46445f39d397SChris Mason 	nritems = btrfs_header_nritems(parent);
4645be0e5c09SChris Mason 	if (slot != nritems - 1) {
4646f3ea38daSJan Schmidt 		if (tree_mod_log && level)
4647f3ea38daSJan Schmidt 			tree_mod_log_eb_move(root->fs_info, parent, slot,
4648f3ea38daSJan Schmidt 					     slot + 1, nritems - slot - 1);
46495f39d397SChris Mason 		memmove_extent_buffer(parent,
46505f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot),
46515f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot + 1),
4652d6025579SChris Mason 			      sizeof(struct btrfs_key_ptr) *
4653d6025579SChris Mason 			      (nritems - slot - 1));
4654f395694cSJan Schmidt 	} else if (tree_mod_log && level) {
4655f3ea38daSJan Schmidt 		ret = tree_mod_log_insert_key(root->fs_info, parent, slot,
4656f3ea38daSJan Schmidt 					      MOD_LOG_KEY_REMOVE);
4657f3ea38daSJan Schmidt 		BUG_ON(ret < 0);
4658be0e5c09SChris Mason 	}
4659f3ea38daSJan Schmidt 
46607518a238SChris Mason 	nritems--;
46615f39d397SChris Mason 	btrfs_set_header_nritems(parent, nritems);
46627518a238SChris Mason 	if (nritems == 0 && parent == root->node) {
46635f39d397SChris Mason 		BUG_ON(btrfs_header_level(root->node) != 1);
4664eb60ceacSChris Mason 		/* just turn the root into a leaf and break */
46655f39d397SChris Mason 		btrfs_set_header_level(root->node, 0);
4666bb803951SChris Mason 	} else if (slot == 0) {
46675f39d397SChris Mason 		struct btrfs_disk_key disk_key;
46685f39d397SChris Mason 
46695f39d397SChris Mason 		btrfs_node_key(parent, &disk_key, 0);
4670143bede5SJeff Mahoney 		fixup_low_keys(trans, root, path, &disk_key, level + 1);
4671be0e5c09SChris Mason 	}
4672d6025579SChris Mason 	btrfs_mark_buffer_dirty(parent);
4673be0e5c09SChris Mason }
4674be0e5c09SChris Mason 
467574123bd7SChris Mason /*
4676323ac95bSChris Mason  * a helper function to delete the leaf pointed to by path->slots[1] and
46775d4f98a2SYan Zheng  * path->nodes[1].
4678323ac95bSChris Mason  *
4679323ac95bSChris Mason  * This deletes the pointer in path->nodes[1] and frees the leaf
4680323ac95bSChris Mason  * block extent.  zero is returned if it all worked out, < 0 otherwise.
4681323ac95bSChris Mason  *
4682323ac95bSChris Mason  * The path must have already been setup for deleting the leaf, including
4683323ac95bSChris Mason  * all the proper balancing.  path->nodes[1] must be locked.
4684323ac95bSChris Mason  */
4685143bede5SJeff Mahoney static noinline void btrfs_del_leaf(struct btrfs_trans_handle *trans,
4686323ac95bSChris Mason 				    struct btrfs_root *root,
46875d4f98a2SYan Zheng 				    struct btrfs_path *path,
46885d4f98a2SYan Zheng 				    struct extent_buffer *leaf)
4689323ac95bSChris Mason {
46905d4f98a2SYan Zheng 	WARN_ON(btrfs_header_generation(leaf) != trans->transid);
4691f3ea38daSJan Schmidt 	del_ptr(trans, root, path, 1, path->slots[1], 1);
4692323ac95bSChris Mason 
46934d081c41SChris Mason 	/*
46944d081c41SChris Mason 	 * btrfs_free_extent is expensive, we want to make sure we
46954d081c41SChris Mason 	 * aren't holding any locks when we call it
46964d081c41SChris Mason 	 */
46974d081c41SChris Mason 	btrfs_unlock_up_safe(path, 0);
46984d081c41SChris Mason 
4699f0486c68SYan, Zheng 	root_sub_used(root, leaf->len);
4700f0486c68SYan, Zheng 
47013083ee2eSJosef Bacik 	extent_buffer_get(leaf);
47025581a51aSJan Schmidt 	btrfs_free_tree_block(trans, root, leaf, 0, 1);
47033083ee2eSJosef Bacik 	free_extent_buffer_stale(leaf);
4704323ac95bSChris Mason }
4705323ac95bSChris Mason /*
470674123bd7SChris Mason  * delete the item at the leaf level in path.  If that empties
470774123bd7SChris Mason  * the leaf, remove it from the tree
470874123bd7SChris Mason  */
470985e21bacSChris Mason int btrfs_del_items(struct btrfs_trans_handle *trans, struct btrfs_root *root,
471085e21bacSChris Mason 		    struct btrfs_path *path, int slot, int nr)
4711be0e5c09SChris Mason {
47125f39d397SChris Mason 	struct extent_buffer *leaf;
47135f39d397SChris Mason 	struct btrfs_item *item;
471485e21bacSChris Mason 	int last_off;
471585e21bacSChris Mason 	int dsize = 0;
4716aa5d6bedSChris Mason 	int ret = 0;
4717aa5d6bedSChris Mason 	int wret;
471885e21bacSChris Mason 	int i;
47197518a238SChris Mason 	u32 nritems;
4720cfed81a0SChris Mason 	struct btrfs_map_token token;
4721cfed81a0SChris Mason 
4722cfed81a0SChris Mason 	btrfs_init_map_token(&token);
4723be0e5c09SChris Mason 
47245f39d397SChris Mason 	leaf = path->nodes[0];
472585e21bacSChris Mason 	last_off = btrfs_item_offset_nr(leaf, slot + nr - 1);
472685e21bacSChris Mason 
472785e21bacSChris Mason 	for (i = 0; i < nr; i++)
472885e21bacSChris Mason 		dsize += btrfs_item_size_nr(leaf, slot + i);
472985e21bacSChris Mason 
47305f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
4731be0e5c09SChris Mason 
473285e21bacSChris Mason 	if (slot + nr != nritems) {
4733123abc88SChris Mason 		int data_end = leaf_data_end(root, leaf);
47345f39d397SChris Mason 
47355f39d397SChris Mason 		memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
4736d6025579SChris Mason 			      data_end + dsize,
4737123abc88SChris Mason 			      btrfs_leaf_data(leaf) + data_end,
473885e21bacSChris Mason 			      last_off - data_end);
47395f39d397SChris Mason 
474085e21bacSChris Mason 		for (i = slot + nr; i < nritems; i++) {
47415f39d397SChris Mason 			u32 ioff;
4742db94535dSChris Mason 
47435f39d397SChris Mason 			item = btrfs_item_nr(leaf, i);
4744cfed81a0SChris Mason 			ioff = btrfs_token_item_offset(leaf, item, &token);
4745cfed81a0SChris Mason 			btrfs_set_token_item_offset(leaf, item,
4746cfed81a0SChris Mason 						    ioff + dsize, &token);
47470783fcfcSChris Mason 		}
4748db94535dSChris Mason 
47495f39d397SChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot),
475085e21bacSChris Mason 			      btrfs_item_nr_offset(slot + nr),
47510783fcfcSChris Mason 			      sizeof(struct btrfs_item) *
475285e21bacSChris Mason 			      (nritems - slot - nr));
4753be0e5c09SChris Mason 	}
475485e21bacSChris Mason 	btrfs_set_header_nritems(leaf, nritems - nr);
475585e21bacSChris Mason 	nritems -= nr;
47565f39d397SChris Mason 
475774123bd7SChris Mason 	/* delete the leaf if we've emptied it */
47587518a238SChris Mason 	if (nritems == 0) {
47595f39d397SChris Mason 		if (leaf == root->node) {
47605f39d397SChris Mason 			btrfs_set_header_level(leaf, 0);
47619a8dd150SChris Mason 		} else {
4762f0486c68SYan, Zheng 			btrfs_set_path_blocking(path);
4763f0486c68SYan, Zheng 			clean_tree_block(trans, root, leaf);
4764143bede5SJeff Mahoney 			btrfs_del_leaf(trans, root, path, leaf);
47659a8dd150SChris Mason 		}
4766be0e5c09SChris Mason 	} else {
47677518a238SChris Mason 		int used = leaf_space_used(leaf, 0, nritems);
4768aa5d6bedSChris Mason 		if (slot == 0) {
47695f39d397SChris Mason 			struct btrfs_disk_key disk_key;
47705f39d397SChris Mason 
47715f39d397SChris Mason 			btrfs_item_key(leaf, &disk_key, 0);
4772143bede5SJeff Mahoney 			fixup_low_keys(trans, root, path, &disk_key, 1);
4773aa5d6bedSChris Mason 		}
4774aa5d6bedSChris Mason 
477574123bd7SChris Mason 		/* delete the leaf if it is mostly empty */
4776d717aa1dSYan Zheng 		if (used < BTRFS_LEAF_DATA_SIZE(root) / 3) {
4777be0e5c09SChris Mason 			/* push_leaf_left fixes the path.
4778be0e5c09SChris Mason 			 * make sure the path still points to our leaf
4779be0e5c09SChris Mason 			 * for possible call to del_ptr below
4780be0e5c09SChris Mason 			 */
47814920c9acSChris Mason 			slot = path->slots[1];
47825f39d397SChris Mason 			extent_buffer_get(leaf);
47835f39d397SChris Mason 
4784b9473439SChris Mason 			btrfs_set_path_blocking(path);
478599d8f83cSChris Mason 			wret = push_leaf_left(trans, root, path, 1, 1,
478699d8f83cSChris Mason 					      1, (u32)-1);
478754aa1f4dSChris Mason 			if (wret < 0 && wret != -ENOSPC)
4788aa5d6bedSChris Mason 				ret = wret;
47895f39d397SChris Mason 
47905f39d397SChris Mason 			if (path->nodes[0] == leaf &&
47915f39d397SChris Mason 			    btrfs_header_nritems(leaf)) {
479299d8f83cSChris Mason 				wret = push_leaf_right(trans, root, path, 1,
479399d8f83cSChris Mason 						       1, 1, 0);
479454aa1f4dSChris Mason 				if (wret < 0 && wret != -ENOSPC)
4795aa5d6bedSChris Mason 					ret = wret;
4796aa5d6bedSChris Mason 			}
47975f39d397SChris Mason 
47985f39d397SChris Mason 			if (btrfs_header_nritems(leaf) == 0) {
4799323ac95bSChris Mason 				path->slots[1] = slot;
4800143bede5SJeff Mahoney 				btrfs_del_leaf(trans, root, path, leaf);
48015f39d397SChris Mason 				free_extent_buffer(leaf);
4802143bede5SJeff Mahoney 				ret = 0;
48035de08d7dSChris Mason 			} else {
4804925baeddSChris Mason 				/* if we're still in the path, make sure
4805925baeddSChris Mason 				 * we're dirty.  Otherwise, one of the
4806925baeddSChris Mason 				 * push_leaf functions must have already
4807925baeddSChris Mason 				 * dirtied this buffer
4808925baeddSChris Mason 				 */
4809925baeddSChris Mason 				if (path->nodes[0] == leaf)
48105f39d397SChris Mason 					btrfs_mark_buffer_dirty(leaf);
48115f39d397SChris Mason 				free_extent_buffer(leaf);
4812be0e5c09SChris Mason 			}
4813d5719762SChris Mason 		} else {
48145f39d397SChris Mason 			btrfs_mark_buffer_dirty(leaf);
4815be0e5c09SChris Mason 		}
48169a8dd150SChris Mason 	}
4817aa5d6bedSChris Mason 	return ret;
48189a8dd150SChris Mason }
48199a8dd150SChris Mason 
482097571fd0SChris Mason /*
4821925baeddSChris Mason  * search the tree again to find a leaf with lesser keys
48227bb86316SChris Mason  * returns 0 if it found something or 1 if there are no lesser leaves.
48237bb86316SChris Mason  * returns < 0 on io errors.
4824d352ac68SChris Mason  *
4825d352ac68SChris Mason  * This may release the path, and so you may lose any locks held at the
4826d352ac68SChris Mason  * time you call it.
48277bb86316SChris Mason  */
48287bb86316SChris Mason int btrfs_prev_leaf(struct btrfs_root *root, struct btrfs_path *path)
48297bb86316SChris Mason {
4830925baeddSChris Mason 	struct btrfs_key key;
4831925baeddSChris Mason 	struct btrfs_disk_key found_key;
4832925baeddSChris Mason 	int ret;
48337bb86316SChris Mason 
4834925baeddSChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, 0);
4835925baeddSChris Mason 
4836925baeddSChris Mason 	if (key.offset > 0)
4837925baeddSChris Mason 		key.offset--;
4838925baeddSChris Mason 	else if (key.type > 0)
4839925baeddSChris Mason 		key.type--;
4840925baeddSChris Mason 	else if (key.objectid > 0)
4841925baeddSChris Mason 		key.objectid--;
4842925baeddSChris Mason 	else
48437bb86316SChris Mason 		return 1;
48447bb86316SChris Mason 
4845b3b4aa74SDavid Sterba 	btrfs_release_path(path);
4846925baeddSChris Mason 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4847925baeddSChris Mason 	if (ret < 0)
4848925baeddSChris Mason 		return ret;
4849925baeddSChris Mason 	btrfs_item_key(path->nodes[0], &found_key, 0);
4850925baeddSChris Mason 	ret = comp_keys(&found_key, &key);
4851925baeddSChris Mason 	if (ret < 0)
48527bb86316SChris Mason 		return 0;
4853925baeddSChris Mason 	return 1;
48547bb86316SChris Mason }
48557bb86316SChris Mason 
48563f157a2fSChris Mason /*
48573f157a2fSChris Mason  * A helper function to walk down the tree starting at min_key, and looking
48583f157a2fSChris Mason  * for nodes or leaves that are either in cache or have a minimum
4859d352ac68SChris Mason  * transaction id.  This is used by the btree defrag code, and tree logging
48603f157a2fSChris Mason  *
48613f157a2fSChris Mason  * This does not cow, but it does stuff the starting key it finds back
48623f157a2fSChris Mason  * into min_key, so you can call btrfs_search_slot with cow=1 on the
48633f157a2fSChris Mason  * key and get a writable path.
48643f157a2fSChris Mason  *
48653f157a2fSChris Mason  * This does lock as it descends, and path->keep_locks should be set
48663f157a2fSChris Mason  * to 1 by the caller.
48673f157a2fSChris Mason  *
48683f157a2fSChris Mason  * This honors path->lowest_level to prevent descent past a given level
48693f157a2fSChris Mason  * of the tree.
48703f157a2fSChris Mason  *
4871d352ac68SChris Mason  * min_trans indicates the oldest transaction that you are interested
4872d352ac68SChris Mason  * in walking through.  Any nodes or leaves older than min_trans are
4873d352ac68SChris Mason  * skipped over (without reading them).
4874d352ac68SChris Mason  *
48753f157a2fSChris Mason  * returns zero if something useful was found, < 0 on error and 1 if there
48763f157a2fSChris Mason  * was nothing in the tree that matched the search criteria.
48773f157a2fSChris Mason  */
48783f157a2fSChris Mason int btrfs_search_forward(struct btrfs_root *root, struct btrfs_key *min_key,
4879e02119d5SChris Mason 			 struct btrfs_key *max_key,
48803f157a2fSChris Mason 			 struct btrfs_path *path, int cache_only,
48813f157a2fSChris Mason 			 u64 min_trans)
48823f157a2fSChris Mason {
48833f157a2fSChris Mason 	struct extent_buffer *cur;
48843f157a2fSChris Mason 	struct btrfs_key found_key;
48853f157a2fSChris Mason 	int slot;
48869652480bSYan 	int sret;
48873f157a2fSChris Mason 	u32 nritems;
48883f157a2fSChris Mason 	int level;
48893f157a2fSChris Mason 	int ret = 1;
48903f157a2fSChris Mason 
4891934d375bSChris Mason 	WARN_ON(!path->keep_locks);
48923f157a2fSChris Mason again:
4893bd681513SChris Mason 	cur = btrfs_read_lock_root_node(root);
48943f157a2fSChris Mason 	level = btrfs_header_level(cur);
4895e02119d5SChris Mason 	WARN_ON(path->nodes[level]);
48963f157a2fSChris Mason 	path->nodes[level] = cur;
4897bd681513SChris Mason 	path->locks[level] = BTRFS_READ_LOCK;
48983f157a2fSChris Mason 
48993f157a2fSChris Mason 	if (btrfs_header_generation(cur) < min_trans) {
49003f157a2fSChris Mason 		ret = 1;
49013f157a2fSChris Mason 		goto out;
49023f157a2fSChris Mason 	}
49033f157a2fSChris Mason 	while (1) {
49043f157a2fSChris Mason 		nritems = btrfs_header_nritems(cur);
49053f157a2fSChris Mason 		level = btrfs_header_level(cur);
49069652480bSYan 		sret = bin_search(cur, min_key, level, &slot);
49073f157a2fSChris Mason 
4908323ac95bSChris Mason 		/* at the lowest level, we're done, setup the path and exit */
4909323ac95bSChris Mason 		if (level == path->lowest_level) {
4910e02119d5SChris Mason 			if (slot >= nritems)
4911e02119d5SChris Mason 				goto find_next_key;
49123f157a2fSChris Mason 			ret = 0;
49133f157a2fSChris Mason 			path->slots[level] = slot;
49143f157a2fSChris Mason 			btrfs_item_key_to_cpu(cur, &found_key, slot);
49153f157a2fSChris Mason 			goto out;
49163f157a2fSChris Mason 		}
49179652480bSYan 		if (sret && slot > 0)
49189652480bSYan 			slot--;
49193f157a2fSChris Mason 		/*
49203f157a2fSChris Mason 		 * check this node pointer against the cache_only and
49213f157a2fSChris Mason 		 * min_trans parameters.  If it isn't in cache or is too
49223f157a2fSChris Mason 		 * old, skip to the next one.
49233f157a2fSChris Mason 		 */
49243f157a2fSChris Mason 		while (slot < nritems) {
49253f157a2fSChris Mason 			u64 blockptr;
49263f157a2fSChris Mason 			u64 gen;
49273f157a2fSChris Mason 			struct extent_buffer *tmp;
4928e02119d5SChris Mason 			struct btrfs_disk_key disk_key;
4929e02119d5SChris Mason 
49303f157a2fSChris Mason 			blockptr = btrfs_node_blockptr(cur, slot);
49313f157a2fSChris Mason 			gen = btrfs_node_ptr_generation(cur, slot);
49323f157a2fSChris Mason 			if (gen < min_trans) {
49333f157a2fSChris Mason 				slot++;
49343f157a2fSChris Mason 				continue;
49353f157a2fSChris Mason 			}
49363f157a2fSChris Mason 			if (!cache_only)
49373f157a2fSChris Mason 				break;
49383f157a2fSChris Mason 
4939e02119d5SChris Mason 			if (max_key) {
4940e02119d5SChris Mason 				btrfs_node_key(cur, &disk_key, slot);
4941e02119d5SChris Mason 				if (comp_keys(&disk_key, max_key) >= 0) {
4942e02119d5SChris Mason 					ret = 1;
4943e02119d5SChris Mason 					goto out;
4944e02119d5SChris Mason 				}
4945e02119d5SChris Mason 			}
4946e02119d5SChris Mason 
49473f157a2fSChris Mason 			tmp = btrfs_find_tree_block(root, blockptr,
49483f157a2fSChris Mason 					    btrfs_level_size(root, level - 1));
49493f157a2fSChris Mason 
4950b9fab919SChris Mason 			if (tmp && btrfs_buffer_uptodate(tmp, gen, 1) > 0) {
49513f157a2fSChris Mason 				free_extent_buffer(tmp);
49523f157a2fSChris Mason 				break;
49533f157a2fSChris Mason 			}
49543f157a2fSChris Mason 			if (tmp)
49553f157a2fSChris Mason 				free_extent_buffer(tmp);
49563f157a2fSChris Mason 			slot++;
49573f157a2fSChris Mason 		}
4958e02119d5SChris Mason find_next_key:
49593f157a2fSChris Mason 		/*
49603f157a2fSChris Mason 		 * we didn't find a candidate key in this node, walk forward
49613f157a2fSChris Mason 		 * and find another one
49623f157a2fSChris Mason 		 */
49633f157a2fSChris Mason 		if (slot >= nritems) {
4964e02119d5SChris Mason 			path->slots[level] = slot;
4965b4ce94deSChris Mason 			btrfs_set_path_blocking(path);
4966e02119d5SChris Mason 			sret = btrfs_find_next_key(root, path, min_key, level,
49673f157a2fSChris Mason 						  cache_only, min_trans);
4968e02119d5SChris Mason 			if (sret == 0) {
4969b3b4aa74SDavid Sterba 				btrfs_release_path(path);
49703f157a2fSChris Mason 				goto again;
49713f157a2fSChris Mason 			} else {
49723f157a2fSChris Mason 				goto out;
49733f157a2fSChris Mason 			}
49743f157a2fSChris Mason 		}
49753f157a2fSChris Mason 		/* save our key for returning back */
49763f157a2fSChris Mason 		btrfs_node_key_to_cpu(cur, &found_key, slot);
49773f157a2fSChris Mason 		path->slots[level] = slot;
49783f157a2fSChris Mason 		if (level == path->lowest_level) {
49793f157a2fSChris Mason 			ret = 0;
4980f7c79f30SChris Mason 			unlock_up(path, level, 1, 0, NULL);
49813f157a2fSChris Mason 			goto out;
49823f157a2fSChris Mason 		}
4983b4ce94deSChris Mason 		btrfs_set_path_blocking(path);
49843f157a2fSChris Mason 		cur = read_node_slot(root, cur, slot);
498579787eaaSJeff Mahoney 		BUG_ON(!cur); /* -ENOMEM */
49863f157a2fSChris Mason 
4987bd681513SChris Mason 		btrfs_tree_read_lock(cur);
4988b4ce94deSChris Mason 
4989bd681513SChris Mason 		path->locks[level - 1] = BTRFS_READ_LOCK;
49903f157a2fSChris Mason 		path->nodes[level - 1] = cur;
4991f7c79f30SChris Mason 		unlock_up(path, level, 1, 0, NULL);
4992bd681513SChris Mason 		btrfs_clear_path_blocking(path, NULL, 0);
49933f157a2fSChris Mason 	}
49943f157a2fSChris Mason out:
49953f157a2fSChris Mason 	if (ret == 0)
49963f157a2fSChris Mason 		memcpy(min_key, &found_key, sizeof(found_key));
4997b4ce94deSChris Mason 	btrfs_set_path_blocking(path);
49983f157a2fSChris Mason 	return ret;
49993f157a2fSChris Mason }
50003f157a2fSChris Mason 
50013f157a2fSChris Mason /*
50023f157a2fSChris Mason  * this is similar to btrfs_next_leaf, but does not try to preserve
50033f157a2fSChris Mason  * and fixup the path.  It looks for and returns the next key in the
50043f157a2fSChris Mason  * tree based on the current path and the cache_only and min_trans
50053f157a2fSChris Mason  * parameters.
50063f157a2fSChris Mason  *
50073f157a2fSChris Mason  * 0 is returned if another key is found, < 0 if there are any errors
50083f157a2fSChris Mason  * and 1 is returned if there are no higher keys in the tree
50093f157a2fSChris Mason  *
50103f157a2fSChris Mason  * path->keep_locks should be set to 1 on the search made before
50113f157a2fSChris Mason  * calling this function.
50123f157a2fSChris Mason  */
5013e7a84565SChris Mason int btrfs_find_next_key(struct btrfs_root *root, struct btrfs_path *path,
501433c66f43SYan Zheng 			struct btrfs_key *key, int level,
50153f157a2fSChris Mason 			int cache_only, u64 min_trans)
5016e7a84565SChris Mason {
5017e7a84565SChris Mason 	int slot;
5018e7a84565SChris Mason 	struct extent_buffer *c;
5019e7a84565SChris Mason 
5020934d375bSChris Mason 	WARN_ON(!path->keep_locks);
5021e7a84565SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
5022e7a84565SChris Mason 		if (!path->nodes[level])
5023e7a84565SChris Mason 			return 1;
5024e7a84565SChris Mason 
5025e7a84565SChris Mason 		slot = path->slots[level] + 1;
5026e7a84565SChris Mason 		c = path->nodes[level];
50273f157a2fSChris Mason next:
5028e7a84565SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
502933c66f43SYan Zheng 			int ret;
503033c66f43SYan Zheng 			int orig_lowest;
503133c66f43SYan Zheng 			struct btrfs_key cur_key;
503233c66f43SYan Zheng 			if (level + 1 >= BTRFS_MAX_LEVEL ||
503333c66f43SYan Zheng 			    !path->nodes[level + 1])
5034e7a84565SChris Mason 				return 1;
503533c66f43SYan Zheng 
503633c66f43SYan Zheng 			if (path->locks[level + 1]) {
503733c66f43SYan Zheng 				level++;
5038e7a84565SChris Mason 				continue;
5039e7a84565SChris Mason 			}
504033c66f43SYan Zheng 
504133c66f43SYan Zheng 			slot = btrfs_header_nritems(c) - 1;
504233c66f43SYan Zheng 			if (level == 0)
504333c66f43SYan Zheng 				btrfs_item_key_to_cpu(c, &cur_key, slot);
504433c66f43SYan Zheng 			else
504533c66f43SYan Zheng 				btrfs_node_key_to_cpu(c, &cur_key, slot);
504633c66f43SYan Zheng 
504733c66f43SYan Zheng 			orig_lowest = path->lowest_level;
5048b3b4aa74SDavid Sterba 			btrfs_release_path(path);
504933c66f43SYan Zheng 			path->lowest_level = level;
505033c66f43SYan Zheng 			ret = btrfs_search_slot(NULL, root, &cur_key, path,
505133c66f43SYan Zheng 						0, 0);
505233c66f43SYan Zheng 			path->lowest_level = orig_lowest;
505333c66f43SYan Zheng 			if (ret < 0)
505433c66f43SYan Zheng 				return ret;
505533c66f43SYan Zheng 
505633c66f43SYan Zheng 			c = path->nodes[level];
505733c66f43SYan Zheng 			slot = path->slots[level];
505833c66f43SYan Zheng 			if (ret == 0)
505933c66f43SYan Zheng 				slot++;
506033c66f43SYan Zheng 			goto next;
506133c66f43SYan Zheng 		}
506233c66f43SYan Zheng 
5063e7a84565SChris Mason 		if (level == 0)
5064e7a84565SChris Mason 			btrfs_item_key_to_cpu(c, key, slot);
50653f157a2fSChris Mason 		else {
50663f157a2fSChris Mason 			u64 blockptr = btrfs_node_blockptr(c, slot);
50673f157a2fSChris Mason 			u64 gen = btrfs_node_ptr_generation(c, slot);
50683f157a2fSChris Mason 
50693f157a2fSChris Mason 			if (cache_only) {
50703f157a2fSChris Mason 				struct extent_buffer *cur;
50713f157a2fSChris Mason 				cur = btrfs_find_tree_block(root, blockptr,
50723f157a2fSChris Mason 					    btrfs_level_size(root, level - 1));
5073b9fab919SChris Mason 				if (!cur ||
5074b9fab919SChris Mason 				    btrfs_buffer_uptodate(cur, gen, 1) <= 0) {
50753f157a2fSChris Mason 					slot++;
50763f157a2fSChris Mason 					if (cur)
50773f157a2fSChris Mason 						free_extent_buffer(cur);
50783f157a2fSChris Mason 					goto next;
50793f157a2fSChris Mason 				}
50803f157a2fSChris Mason 				free_extent_buffer(cur);
50813f157a2fSChris Mason 			}
50823f157a2fSChris Mason 			if (gen < min_trans) {
50833f157a2fSChris Mason 				slot++;
50843f157a2fSChris Mason 				goto next;
50853f157a2fSChris Mason 			}
5086e7a84565SChris Mason 			btrfs_node_key_to_cpu(c, key, slot);
50873f157a2fSChris Mason 		}
5088e7a84565SChris Mason 		return 0;
5089e7a84565SChris Mason 	}
5090e7a84565SChris Mason 	return 1;
5091e7a84565SChris Mason }
5092e7a84565SChris Mason 
50937bb86316SChris Mason /*
5094925baeddSChris Mason  * search the tree again to find a leaf with greater keys
50950f70abe2SChris Mason  * returns 0 if it found something or 1 if there are no greater leaves.
50960f70abe2SChris Mason  * returns < 0 on io errors.
509797571fd0SChris Mason  */
5098234b63a0SChris Mason int btrfs_next_leaf(struct btrfs_root *root, struct btrfs_path *path)
5099d97e63b6SChris Mason {
51003d7806ecSJan Schmidt 	return btrfs_next_old_leaf(root, path, 0);
51013d7806ecSJan Schmidt }
51023d7806ecSJan Schmidt 
51033d7806ecSJan Schmidt int btrfs_next_old_leaf(struct btrfs_root *root, struct btrfs_path *path,
51043d7806ecSJan Schmidt 			u64 time_seq)
51053d7806ecSJan Schmidt {
5106d97e63b6SChris Mason 	int slot;
51078e73f275SChris Mason 	int level;
51085f39d397SChris Mason 	struct extent_buffer *c;
51098e73f275SChris Mason 	struct extent_buffer *next;
5110925baeddSChris Mason 	struct btrfs_key key;
5111925baeddSChris Mason 	u32 nritems;
5112925baeddSChris Mason 	int ret;
51138e73f275SChris Mason 	int old_spinning = path->leave_spinning;
5114bd681513SChris Mason 	int next_rw_lock = 0;
5115925baeddSChris Mason 
5116925baeddSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
5117d397712bSChris Mason 	if (nritems == 0)
5118925baeddSChris Mason 		return 1;
5119925baeddSChris Mason 
51208e73f275SChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, nritems - 1);
51218e73f275SChris Mason again:
51228e73f275SChris Mason 	level = 1;
51238e73f275SChris Mason 	next = NULL;
5124bd681513SChris Mason 	next_rw_lock = 0;
5125b3b4aa74SDavid Sterba 	btrfs_release_path(path);
51268e73f275SChris Mason 
5127a2135011SChris Mason 	path->keep_locks = 1;
51288e73f275SChris Mason 	path->leave_spinning = 1;
51298e73f275SChris Mason 
51303d7806ecSJan Schmidt 	if (time_seq)
51313d7806ecSJan Schmidt 		ret = btrfs_search_old_slot(root, &key, path, time_seq);
51323d7806ecSJan Schmidt 	else
5133925baeddSChris Mason 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5134925baeddSChris Mason 	path->keep_locks = 0;
5135925baeddSChris Mason 
5136925baeddSChris Mason 	if (ret < 0)
5137925baeddSChris Mason 		return ret;
5138925baeddSChris Mason 
5139a2135011SChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
5140168fd7d2SChris Mason 	/*
5141168fd7d2SChris Mason 	 * by releasing the path above we dropped all our locks.  A balance
5142168fd7d2SChris Mason 	 * could have added more items next to the key that used to be
5143168fd7d2SChris Mason 	 * at the very end of the block.  So, check again here and
5144168fd7d2SChris Mason 	 * advance the path if there are now more items available.
5145168fd7d2SChris Mason 	 */
5146a2135011SChris Mason 	if (nritems > 0 && path->slots[0] < nritems - 1) {
5147e457afecSYan Zheng 		if (ret == 0)
5148168fd7d2SChris Mason 			path->slots[0]++;
51498e73f275SChris Mason 		ret = 0;
5150925baeddSChris Mason 		goto done;
5151925baeddSChris Mason 	}
5152d97e63b6SChris Mason 
5153234b63a0SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
51548e73f275SChris Mason 		if (!path->nodes[level]) {
51558e73f275SChris Mason 			ret = 1;
51568e73f275SChris Mason 			goto done;
51578e73f275SChris Mason 		}
51585f39d397SChris Mason 
5159d97e63b6SChris Mason 		slot = path->slots[level] + 1;
5160d97e63b6SChris Mason 		c = path->nodes[level];
51615f39d397SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
5162d97e63b6SChris Mason 			level++;
51638e73f275SChris Mason 			if (level == BTRFS_MAX_LEVEL) {
51648e73f275SChris Mason 				ret = 1;
51658e73f275SChris Mason 				goto done;
51668e73f275SChris Mason 			}
5167d97e63b6SChris Mason 			continue;
5168d97e63b6SChris Mason 		}
51695f39d397SChris Mason 
5170925baeddSChris Mason 		if (next) {
5171bd681513SChris Mason 			btrfs_tree_unlock_rw(next, next_rw_lock);
51725f39d397SChris Mason 			free_extent_buffer(next);
5173925baeddSChris Mason 		}
51745f39d397SChris Mason 
51758e73f275SChris Mason 		next = c;
5176bd681513SChris Mason 		next_rw_lock = path->locks[level];
51778e73f275SChris Mason 		ret = read_block_for_search(NULL, root, path, &next, level,
51785d9e75c4SJan Schmidt 					    slot, &key, 0);
51798e73f275SChris Mason 		if (ret == -EAGAIN)
51808e73f275SChris Mason 			goto again;
51815f39d397SChris Mason 
518276a05b35SChris Mason 		if (ret < 0) {
5183b3b4aa74SDavid Sterba 			btrfs_release_path(path);
518476a05b35SChris Mason 			goto done;
518576a05b35SChris Mason 		}
518676a05b35SChris Mason 
51875cd57b2cSChris Mason 		if (!path->skip_locking) {
5188bd681513SChris Mason 			ret = btrfs_try_tree_read_lock(next);
5189d42244a0SJan Schmidt 			if (!ret && time_seq) {
5190d42244a0SJan Schmidt 				/*
5191d42244a0SJan Schmidt 				 * If we don't get the lock, we may be racing
5192d42244a0SJan Schmidt 				 * with push_leaf_left, holding that lock while
5193d42244a0SJan Schmidt 				 * itself waiting for the leaf we've currently
5194d42244a0SJan Schmidt 				 * locked. To solve this situation, we give up
5195d42244a0SJan Schmidt 				 * on our lock and cycle.
5196d42244a0SJan Schmidt 				 */
5197cf538830SJan Schmidt 				free_extent_buffer(next);
5198d42244a0SJan Schmidt 				btrfs_release_path(path);
5199d42244a0SJan Schmidt 				cond_resched();
5200d42244a0SJan Schmidt 				goto again;
5201d42244a0SJan Schmidt 			}
52028e73f275SChris Mason 			if (!ret) {
52038e73f275SChris Mason 				btrfs_set_path_blocking(path);
5204bd681513SChris Mason 				btrfs_tree_read_lock(next);
5205bd681513SChris Mason 				btrfs_clear_path_blocking(path, next,
5206bd681513SChris Mason 							  BTRFS_READ_LOCK);
52078e73f275SChris Mason 			}
5208bd681513SChris Mason 			next_rw_lock = BTRFS_READ_LOCK;
5209bd681513SChris Mason 		}
5210d97e63b6SChris Mason 		break;
5211d97e63b6SChris Mason 	}
5212d97e63b6SChris Mason 	path->slots[level] = slot;
5213d97e63b6SChris Mason 	while (1) {
5214d97e63b6SChris Mason 		level--;
5215d97e63b6SChris Mason 		c = path->nodes[level];
5216925baeddSChris Mason 		if (path->locks[level])
5217bd681513SChris Mason 			btrfs_tree_unlock_rw(c, path->locks[level]);
52188e73f275SChris Mason 
52195f39d397SChris Mason 		free_extent_buffer(c);
5220d97e63b6SChris Mason 		path->nodes[level] = next;
5221d97e63b6SChris Mason 		path->slots[level] = 0;
5222a74a4b97SChris Mason 		if (!path->skip_locking)
5223bd681513SChris Mason 			path->locks[level] = next_rw_lock;
5224d97e63b6SChris Mason 		if (!level)
5225d97e63b6SChris Mason 			break;
5226b4ce94deSChris Mason 
52278e73f275SChris Mason 		ret = read_block_for_search(NULL, root, path, &next, level,
52285d9e75c4SJan Schmidt 					    0, &key, 0);
52298e73f275SChris Mason 		if (ret == -EAGAIN)
52308e73f275SChris Mason 			goto again;
52318e73f275SChris Mason 
523276a05b35SChris Mason 		if (ret < 0) {
5233b3b4aa74SDavid Sterba 			btrfs_release_path(path);
523476a05b35SChris Mason 			goto done;
523576a05b35SChris Mason 		}
523676a05b35SChris Mason 
52375cd57b2cSChris Mason 		if (!path->skip_locking) {
5238bd681513SChris Mason 			ret = btrfs_try_tree_read_lock(next);
52398e73f275SChris Mason 			if (!ret) {
52408e73f275SChris Mason 				btrfs_set_path_blocking(path);
5241bd681513SChris Mason 				btrfs_tree_read_lock(next);
5242bd681513SChris Mason 				btrfs_clear_path_blocking(path, next,
5243bd681513SChris Mason 							  BTRFS_READ_LOCK);
52448e73f275SChris Mason 			}
5245bd681513SChris Mason 			next_rw_lock = BTRFS_READ_LOCK;
5246bd681513SChris Mason 		}
5247d97e63b6SChris Mason 	}
52488e73f275SChris Mason 	ret = 0;
5249925baeddSChris Mason done:
5250f7c79f30SChris Mason 	unlock_up(path, 0, 1, 0, NULL);
52518e73f275SChris Mason 	path->leave_spinning = old_spinning;
52528e73f275SChris Mason 	if (!old_spinning)
52538e73f275SChris Mason 		btrfs_set_path_blocking(path);
52548e73f275SChris Mason 
52558e73f275SChris Mason 	return ret;
5256d97e63b6SChris Mason }
52570b86a832SChris Mason 
52583f157a2fSChris Mason /*
52593f157a2fSChris Mason  * this uses btrfs_prev_leaf to walk backwards in the tree, and keeps
52603f157a2fSChris Mason  * searching until it gets past min_objectid or finds an item of 'type'
52613f157a2fSChris Mason  *
52623f157a2fSChris Mason  * returns 0 if something is found, 1 if nothing was found and < 0 on error
52633f157a2fSChris Mason  */
52640b86a832SChris Mason int btrfs_previous_item(struct btrfs_root *root,
52650b86a832SChris Mason 			struct btrfs_path *path, u64 min_objectid,
52660b86a832SChris Mason 			int type)
52670b86a832SChris Mason {
52680b86a832SChris Mason 	struct btrfs_key found_key;
52690b86a832SChris Mason 	struct extent_buffer *leaf;
5270e02119d5SChris Mason 	u32 nritems;
52710b86a832SChris Mason 	int ret;
52720b86a832SChris Mason 
52730b86a832SChris Mason 	while (1) {
52740b86a832SChris Mason 		if (path->slots[0] == 0) {
5275b4ce94deSChris Mason 			btrfs_set_path_blocking(path);
52760b86a832SChris Mason 			ret = btrfs_prev_leaf(root, path);
52770b86a832SChris Mason 			if (ret != 0)
52780b86a832SChris Mason 				return ret;
52790b86a832SChris Mason 		} else {
52800b86a832SChris Mason 			path->slots[0]--;
52810b86a832SChris Mason 		}
52820b86a832SChris Mason 		leaf = path->nodes[0];
5283e02119d5SChris Mason 		nritems = btrfs_header_nritems(leaf);
5284e02119d5SChris Mason 		if (nritems == 0)
5285e02119d5SChris Mason 			return 1;
5286e02119d5SChris Mason 		if (path->slots[0] == nritems)
5287e02119d5SChris Mason 			path->slots[0]--;
5288e02119d5SChris Mason 
52890b86a832SChris Mason 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5290e02119d5SChris Mason 		if (found_key.objectid < min_objectid)
5291e02119d5SChris Mason 			break;
52920a4eefbbSYan Zheng 		if (found_key.type == type)
52930a4eefbbSYan Zheng 			return 0;
5294e02119d5SChris Mason 		if (found_key.objectid == min_objectid &&
5295e02119d5SChris Mason 		    found_key.type < type)
5296e02119d5SChris Mason 			break;
52970b86a832SChris Mason 	}
52980b86a832SChris Mason 	return 1;
52990b86a832SChris Mason }
5300