xref: /openbmc/linux/fs/btrfs/ctree.c (revision 1c697d4acc2e10b2a65b22abba2687a2897ecd74)
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,
410e411eceSLiu Bo 		    struct btrfs_path *path, int level, int slot);
42f230475eSJan Schmidt static void tree_mod_log_free_eb(struct btrfs_fs_info *fs_info,
43f230475eSJan Schmidt 				 struct extent_buffer *eb);
44f230475eSJan Schmidt struct extent_buffer *read_old_tree_block(struct btrfs_root *root, u64 bytenr,
45f230475eSJan Schmidt 					  u32 blocksize, u64 parent_transid,
46f230475eSJan Schmidt 					  u64 time_seq);
47f230475eSJan Schmidt struct extent_buffer *btrfs_find_old_tree_block(struct btrfs_root *root,
48f230475eSJan Schmidt 						u64 bytenr, u32 blocksize,
49f230475eSJan Schmidt 						u64 time_seq);
50d97e63b6SChris Mason 
512c90e5d6SChris Mason struct btrfs_path *btrfs_alloc_path(void)
522c90e5d6SChris Mason {
53df24a2b9SChris Mason 	struct btrfs_path *path;
54e00f7308SJeff Mahoney 	path = kmem_cache_zalloc(btrfs_path_cachep, GFP_NOFS);
55df24a2b9SChris Mason 	return path;
562c90e5d6SChris Mason }
572c90e5d6SChris Mason 
58b4ce94deSChris Mason /*
59b4ce94deSChris Mason  * set all locked nodes in the path to blocking locks.  This should
60b4ce94deSChris Mason  * be done before scheduling
61b4ce94deSChris Mason  */
62b4ce94deSChris Mason noinline void btrfs_set_path_blocking(struct btrfs_path *p)
63b4ce94deSChris Mason {
64b4ce94deSChris Mason 	int i;
65b4ce94deSChris Mason 	for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
66bd681513SChris Mason 		if (!p->nodes[i] || !p->locks[i])
67bd681513SChris Mason 			continue;
68bd681513SChris Mason 		btrfs_set_lock_blocking_rw(p->nodes[i], p->locks[i]);
69bd681513SChris Mason 		if (p->locks[i] == BTRFS_READ_LOCK)
70bd681513SChris Mason 			p->locks[i] = BTRFS_READ_LOCK_BLOCKING;
71bd681513SChris Mason 		else if (p->locks[i] == BTRFS_WRITE_LOCK)
72bd681513SChris Mason 			p->locks[i] = BTRFS_WRITE_LOCK_BLOCKING;
73b4ce94deSChris Mason 	}
74b4ce94deSChris Mason }
75b4ce94deSChris Mason 
76b4ce94deSChris Mason /*
77b4ce94deSChris Mason  * reset all the locked nodes in the patch to spinning locks.
784008c04aSChris Mason  *
794008c04aSChris Mason  * held is used to keep lockdep happy, when lockdep is enabled
804008c04aSChris Mason  * we set held to a blocking lock before we go around and
814008c04aSChris Mason  * retake all the spinlocks in the path.  You can safely use NULL
824008c04aSChris Mason  * for held
83b4ce94deSChris Mason  */
844008c04aSChris Mason noinline void btrfs_clear_path_blocking(struct btrfs_path *p,
85bd681513SChris Mason 					struct extent_buffer *held, int held_rw)
86b4ce94deSChris Mason {
87b4ce94deSChris Mason 	int i;
884008c04aSChris Mason 
894008c04aSChris Mason #ifdef CONFIG_DEBUG_LOCK_ALLOC
904008c04aSChris Mason 	/* lockdep really cares that we take all of these spinlocks
914008c04aSChris Mason 	 * in the right order.  If any of the locks in the path are not
924008c04aSChris Mason 	 * currently blocking, it is going to complain.  So, make really
934008c04aSChris Mason 	 * really sure by forcing the path to blocking before we clear
944008c04aSChris Mason 	 * the path blocking.
954008c04aSChris Mason 	 */
96bd681513SChris Mason 	if (held) {
97bd681513SChris Mason 		btrfs_set_lock_blocking_rw(held, held_rw);
98bd681513SChris Mason 		if (held_rw == BTRFS_WRITE_LOCK)
99bd681513SChris Mason 			held_rw = BTRFS_WRITE_LOCK_BLOCKING;
100bd681513SChris Mason 		else if (held_rw == BTRFS_READ_LOCK)
101bd681513SChris Mason 			held_rw = BTRFS_READ_LOCK_BLOCKING;
102bd681513SChris Mason 	}
1034008c04aSChris Mason 	btrfs_set_path_blocking(p);
1044008c04aSChris Mason #endif
1054008c04aSChris Mason 
1064008c04aSChris Mason 	for (i = BTRFS_MAX_LEVEL - 1; i >= 0; i--) {
107bd681513SChris Mason 		if (p->nodes[i] && p->locks[i]) {
108bd681513SChris Mason 			btrfs_clear_lock_blocking_rw(p->nodes[i], p->locks[i]);
109bd681513SChris Mason 			if (p->locks[i] == BTRFS_WRITE_LOCK_BLOCKING)
110bd681513SChris Mason 				p->locks[i] = BTRFS_WRITE_LOCK;
111bd681513SChris Mason 			else if (p->locks[i] == BTRFS_READ_LOCK_BLOCKING)
112bd681513SChris Mason 				p->locks[i] = BTRFS_READ_LOCK;
113bd681513SChris Mason 		}
114b4ce94deSChris Mason 	}
1154008c04aSChris Mason 
1164008c04aSChris Mason #ifdef CONFIG_DEBUG_LOCK_ALLOC
1174008c04aSChris Mason 	if (held)
118bd681513SChris Mason 		btrfs_clear_lock_blocking_rw(held, held_rw);
1194008c04aSChris Mason #endif
120b4ce94deSChris Mason }
121b4ce94deSChris Mason 
122d352ac68SChris Mason /* this also releases the path */
1232c90e5d6SChris Mason void btrfs_free_path(struct btrfs_path *p)
1242c90e5d6SChris Mason {
125ff175d57SJesper Juhl 	if (!p)
126ff175d57SJesper Juhl 		return;
127b3b4aa74SDavid Sterba 	btrfs_release_path(p);
1282c90e5d6SChris Mason 	kmem_cache_free(btrfs_path_cachep, p);
1292c90e5d6SChris Mason }
1302c90e5d6SChris Mason 
131d352ac68SChris Mason /*
132d352ac68SChris Mason  * path release drops references on the extent buffers in the path
133d352ac68SChris Mason  * and it drops any locks held by this path
134d352ac68SChris Mason  *
135d352ac68SChris Mason  * It is safe to call this on paths that no locks or extent buffers held.
136d352ac68SChris Mason  */
137b3b4aa74SDavid Sterba noinline void btrfs_release_path(struct btrfs_path *p)
138eb60ceacSChris Mason {
139eb60ceacSChris Mason 	int i;
140a2135011SChris Mason 
141234b63a0SChris Mason 	for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
1423f157a2fSChris Mason 		p->slots[i] = 0;
143eb60ceacSChris Mason 		if (!p->nodes[i])
144925baeddSChris Mason 			continue;
145925baeddSChris Mason 		if (p->locks[i]) {
146bd681513SChris Mason 			btrfs_tree_unlock_rw(p->nodes[i], p->locks[i]);
147925baeddSChris Mason 			p->locks[i] = 0;
148925baeddSChris Mason 		}
1495f39d397SChris Mason 		free_extent_buffer(p->nodes[i]);
1503f157a2fSChris Mason 		p->nodes[i] = NULL;
151eb60ceacSChris Mason 	}
152eb60ceacSChris Mason }
153eb60ceacSChris Mason 
154d352ac68SChris Mason /*
155d352ac68SChris Mason  * safely gets a reference on the root node of a tree.  A lock
156d352ac68SChris Mason  * is not taken, so a concurrent writer may put a different node
157d352ac68SChris Mason  * at the root of the tree.  See btrfs_lock_root_node for the
158d352ac68SChris Mason  * looping required.
159d352ac68SChris Mason  *
160d352ac68SChris Mason  * The extent buffer returned by this has a reference taken, so
161d352ac68SChris Mason  * it won't disappear.  It may stop being the root of the tree
162d352ac68SChris Mason  * at any time because there are no locks held.
163d352ac68SChris Mason  */
164925baeddSChris Mason struct extent_buffer *btrfs_root_node(struct btrfs_root *root)
165925baeddSChris Mason {
166925baeddSChris Mason 	struct extent_buffer *eb;
167240f62c8SChris Mason 
1683083ee2eSJosef Bacik 	while (1) {
169240f62c8SChris Mason 		rcu_read_lock();
170240f62c8SChris Mason 		eb = rcu_dereference(root->node);
1713083ee2eSJosef Bacik 
1723083ee2eSJosef Bacik 		/*
1733083ee2eSJosef Bacik 		 * RCU really hurts here, we could free up the root node because
1743083ee2eSJosef Bacik 		 * it was cow'ed but we may not get the new root node yet so do
1753083ee2eSJosef Bacik 		 * the inc_not_zero dance and if it doesn't work then
1763083ee2eSJosef Bacik 		 * synchronize_rcu and try again.
1773083ee2eSJosef Bacik 		 */
1783083ee2eSJosef Bacik 		if (atomic_inc_not_zero(&eb->refs)) {
179240f62c8SChris Mason 			rcu_read_unlock();
1803083ee2eSJosef Bacik 			break;
1813083ee2eSJosef Bacik 		}
1823083ee2eSJosef Bacik 		rcu_read_unlock();
1833083ee2eSJosef Bacik 		synchronize_rcu();
1843083ee2eSJosef Bacik 	}
185925baeddSChris Mason 	return eb;
186925baeddSChris Mason }
187925baeddSChris Mason 
188d352ac68SChris Mason /* loop around taking references on and locking the root node of the
189d352ac68SChris Mason  * tree until you end up with a lock on the root.  A locked buffer
190d352ac68SChris Mason  * is returned, with a reference held.
191d352ac68SChris Mason  */
192925baeddSChris Mason struct extent_buffer *btrfs_lock_root_node(struct btrfs_root *root)
193925baeddSChris Mason {
194925baeddSChris Mason 	struct extent_buffer *eb;
195925baeddSChris Mason 
196925baeddSChris Mason 	while (1) {
197925baeddSChris Mason 		eb = btrfs_root_node(root);
198925baeddSChris Mason 		btrfs_tree_lock(eb);
199240f62c8SChris Mason 		if (eb == root->node)
200925baeddSChris Mason 			break;
201925baeddSChris Mason 		btrfs_tree_unlock(eb);
202925baeddSChris Mason 		free_extent_buffer(eb);
203925baeddSChris Mason 	}
204925baeddSChris Mason 	return eb;
205925baeddSChris Mason }
206925baeddSChris Mason 
207bd681513SChris Mason /* loop around taking references on and locking the root node of the
208bd681513SChris Mason  * tree until you end up with a lock on the root.  A locked buffer
209bd681513SChris Mason  * is returned, with a reference held.
210bd681513SChris Mason  */
211bd681513SChris Mason struct extent_buffer *btrfs_read_lock_root_node(struct btrfs_root *root)
212bd681513SChris Mason {
213bd681513SChris Mason 	struct extent_buffer *eb;
214bd681513SChris Mason 
215bd681513SChris Mason 	while (1) {
216bd681513SChris Mason 		eb = btrfs_root_node(root);
217bd681513SChris Mason 		btrfs_tree_read_lock(eb);
218bd681513SChris Mason 		if (eb == root->node)
219bd681513SChris Mason 			break;
220bd681513SChris Mason 		btrfs_tree_read_unlock(eb);
221bd681513SChris Mason 		free_extent_buffer(eb);
222bd681513SChris Mason 	}
223bd681513SChris Mason 	return eb;
224bd681513SChris Mason }
225bd681513SChris Mason 
226d352ac68SChris Mason /* cowonly root (everything not a reference counted cow subvolume), just get
227d352ac68SChris Mason  * put onto a simple dirty list.  transaction.c walks this to make sure they
228d352ac68SChris Mason  * get properly updated on disk.
229d352ac68SChris Mason  */
2300b86a832SChris Mason static void add_root_to_dirty_list(struct btrfs_root *root)
2310b86a832SChris Mason {
232e5846fc6SChris Mason 	spin_lock(&root->fs_info->trans_lock);
2330b86a832SChris Mason 	if (root->track_dirty && list_empty(&root->dirty_list)) {
2340b86a832SChris Mason 		list_add(&root->dirty_list,
2350b86a832SChris Mason 			 &root->fs_info->dirty_cowonly_roots);
2360b86a832SChris Mason 	}
237e5846fc6SChris Mason 	spin_unlock(&root->fs_info->trans_lock);
2380b86a832SChris Mason }
2390b86a832SChris Mason 
240d352ac68SChris Mason /*
241d352ac68SChris Mason  * used by snapshot creation to make a copy of a root for a tree with
242d352ac68SChris Mason  * a given objectid.  The buffer with the new root node is returned in
243d352ac68SChris Mason  * cow_ret, and this func returns zero on success or a negative error code.
244d352ac68SChris Mason  */
245be20aa9dSChris Mason int btrfs_copy_root(struct btrfs_trans_handle *trans,
246be20aa9dSChris Mason 		      struct btrfs_root *root,
247be20aa9dSChris Mason 		      struct extent_buffer *buf,
248be20aa9dSChris Mason 		      struct extent_buffer **cow_ret, u64 new_root_objectid)
249be20aa9dSChris Mason {
250be20aa9dSChris Mason 	struct extent_buffer *cow;
251be20aa9dSChris Mason 	int ret = 0;
252be20aa9dSChris Mason 	int level;
2535d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
254be20aa9dSChris Mason 
255be20aa9dSChris Mason 	WARN_ON(root->ref_cows && trans->transid !=
256be20aa9dSChris Mason 		root->fs_info->running_transaction->transid);
257be20aa9dSChris Mason 	WARN_ON(root->ref_cows && trans->transid != root->last_trans);
258be20aa9dSChris Mason 
259be20aa9dSChris Mason 	level = btrfs_header_level(buf);
2605d4f98a2SYan Zheng 	if (level == 0)
2615d4f98a2SYan Zheng 		btrfs_item_key(buf, &disk_key, 0);
2625d4f98a2SYan Zheng 	else
2635d4f98a2SYan Zheng 		btrfs_node_key(buf, &disk_key, 0);
26431840ae1SZheng Yan 
2655d4f98a2SYan Zheng 	cow = btrfs_alloc_free_block(trans, root, buf->len, 0,
2665d4f98a2SYan Zheng 				     new_root_objectid, &disk_key, level,
2675581a51aSJan Schmidt 				     buf->start, 0);
2685d4f98a2SYan Zheng 	if (IS_ERR(cow))
269be20aa9dSChris Mason 		return PTR_ERR(cow);
270be20aa9dSChris Mason 
271be20aa9dSChris Mason 	copy_extent_buffer(cow, buf, 0, 0, cow->len);
272be20aa9dSChris Mason 	btrfs_set_header_bytenr(cow, cow->start);
273be20aa9dSChris Mason 	btrfs_set_header_generation(cow, trans->transid);
2745d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
2755d4f98a2SYan Zheng 	btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
2765d4f98a2SYan Zheng 				     BTRFS_HEADER_FLAG_RELOC);
2775d4f98a2SYan Zheng 	if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
2785d4f98a2SYan Zheng 		btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
2795d4f98a2SYan Zheng 	else
280be20aa9dSChris Mason 		btrfs_set_header_owner(cow, new_root_objectid);
281be20aa9dSChris Mason 
2822b82032cSYan Zheng 	write_extent_buffer(cow, root->fs_info->fsid,
2832b82032cSYan Zheng 			    (unsigned long)btrfs_header_fsid(cow),
2842b82032cSYan Zheng 			    BTRFS_FSID_SIZE);
2852b82032cSYan Zheng 
286be20aa9dSChris Mason 	WARN_ON(btrfs_header_generation(buf) > trans->transid);
2875d4f98a2SYan Zheng 	if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
28866d7e7f0SArne Jansen 		ret = btrfs_inc_ref(trans, root, cow, 1, 1);
2895d4f98a2SYan Zheng 	else
29066d7e7f0SArne Jansen 		ret = btrfs_inc_ref(trans, root, cow, 0, 1);
2914aec2b52SChris Mason 
292be20aa9dSChris Mason 	if (ret)
293be20aa9dSChris Mason 		return ret;
294be20aa9dSChris Mason 
295be20aa9dSChris Mason 	btrfs_mark_buffer_dirty(cow);
296be20aa9dSChris Mason 	*cow_ret = cow;
297be20aa9dSChris Mason 	return 0;
298be20aa9dSChris Mason }
299be20aa9dSChris Mason 
300bd989ba3SJan Schmidt enum mod_log_op {
301bd989ba3SJan Schmidt 	MOD_LOG_KEY_REPLACE,
302bd989ba3SJan Schmidt 	MOD_LOG_KEY_ADD,
303bd989ba3SJan Schmidt 	MOD_LOG_KEY_REMOVE,
304bd989ba3SJan Schmidt 	MOD_LOG_KEY_REMOVE_WHILE_FREEING,
305bd989ba3SJan Schmidt 	MOD_LOG_KEY_REMOVE_WHILE_MOVING,
306bd989ba3SJan Schmidt 	MOD_LOG_MOVE_KEYS,
307bd989ba3SJan Schmidt 	MOD_LOG_ROOT_REPLACE,
308bd989ba3SJan Schmidt };
309bd989ba3SJan Schmidt 
310bd989ba3SJan Schmidt struct tree_mod_move {
311bd989ba3SJan Schmidt 	int dst_slot;
312bd989ba3SJan Schmidt 	int nr_items;
313bd989ba3SJan Schmidt };
314bd989ba3SJan Schmidt 
315bd989ba3SJan Schmidt struct tree_mod_root {
316bd989ba3SJan Schmidt 	u64 logical;
317bd989ba3SJan Schmidt 	u8 level;
318bd989ba3SJan Schmidt };
319bd989ba3SJan Schmidt 
320bd989ba3SJan Schmidt struct tree_mod_elem {
321bd989ba3SJan Schmidt 	struct rb_node node;
322bd989ba3SJan Schmidt 	u64 index;		/* shifted logical */
323097b8a7cSJan Schmidt 	u64 seq;
324bd989ba3SJan Schmidt 	enum mod_log_op op;
325bd989ba3SJan Schmidt 
326bd989ba3SJan Schmidt 	/* this is used for MOD_LOG_KEY_* and MOD_LOG_MOVE_KEYS operations */
327bd989ba3SJan Schmidt 	int slot;
328bd989ba3SJan Schmidt 
329bd989ba3SJan Schmidt 	/* this is used for MOD_LOG_KEY* and MOD_LOG_ROOT_REPLACE */
330bd989ba3SJan Schmidt 	u64 generation;
331bd989ba3SJan Schmidt 
332bd989ba3SJan Schmidt 	/* those are used for op == MOD_LOG_KEY_{REPLACE,REMOVE} */
333bd989ba3SJan Schmidt 	struct btrfs_disk_key key;
334bd989ba3SJan Schmidt 	u64 blockptr;
335bd989ba3SJan Schmidt 
336bd989ba3SJan Schmidt 	/* this is used for op == MOD_LOG_MOVE_KEYS */
337bd989ba3SJan Schmidt 	struct tree_mod_move move;
338bd989ba3SJan Schmidt 
339bd989ba3SJan Schmidt 	/* this is used for op == MOD_LOG_ROOT_REPLACE */
340bd989ba3SJan Schmidt 	struct tree_mod_root old_root;
341bd989ba3SJan Schmidt };
342bd989ba3SJan Schmidt 
343097b8a7cSJan Schmidt static inline void tree_mod_log_read_lock(struct btrfs_fs_info *fs_info)
344bd989ba3SJan Schmidt {
345097b8a7cSJan Schmidt 	read_lock(&fs_info->tree_mod_log_lock);
346bd989ba3SJan Schmidt }
347bd989ba3SJan Schmidt 
348097b8a7cSJan Schmidt static inline void tree_mod_log_read_unlock(struct btrfs_fs_info *fs_info)
349097b8a7cSJan Schmidt {
350097b8a7cSJan Schmidt 	read_unlock(&fs_info->tree_mod_log_lock);
351097b8a7cSJan Schmidt }
352097b8a7cSJan Schmidt 
353097b8a7cSJan Schmidt static inline void tree_mod_log_write_lock(struct btrfs_fs_info *fs_info)
354097b8a7cSJan Schmidt {
355097b8a7cSJan Schmidt 	write_lock(&fs_info->tree_mod_log_lock);
356097b8a7cSJan Schmidt }
357097b8a7cSJan Schmidt 
358097b8a7cSJan Schmidt static inline void tree_mod_log_write_unlock(struct btrfs_fs_info *fs_info)
359097b8a7cSJan Schmidt {
360097b8a7cSJan Schmidt 	write_unlock(&fs_info->tree_mod_log_lock);
361097b8a7cSJan Schmidt }
362097b8a7cSJan Schmidt 
363097b8a7cSJan Schmidt /*
364097b8a7cSJan Schmidt  * This adds a new blocker to the tree mod log's blocker list if the @elem
365097b8a7cSJan Schmidt  * passed does not already have a sequence number set. So when a caller expects
366097b8a7cSJan Schmidt  * to record tree modifications, it should ensure to set elem->seq to zero
367097b8a7cSJan Schmidt  * before calling btrfs_get_tree_mod_seq.
368097b8a7cSJan Schmidt  * Returns a fresh, unused tree log modification sequence number, even if no new
369097b8a7cSJan Schmidt  * blocker was added.
370097b8a7cSJan Schmidt  */
371097b8a7cSJan Schmidt u64 btrfs_get_tree_mod_seq(struct btrfs_fs_info *fs_info,
372bd989ba3SJan Schmidt 			   struct seq_list *elem)
373bd989ba3SJan Schmidt {
374097b8a7cSJan Schmidt 	u64 seq;
375097b8a7cSJan Schmidt 
376097b8a7cSJan Schmidt 	tree_mod_log_write_lock(fs_info);
377bd989ba3SJan Schmidt 	spin_lock(&fs_info->tree_mod_seq_lock);
378097b8a7cSJan Schmidt 	if (!elem->seq) {
379097b8a7cSJan Schmidt 		elem->seq = btrfs_inc_tree_mod_seq(fs_info);
380097b8a7cSJan Schmidt 		list_add_tail(&elem->list, &fs_info->tree_mod_seq_list);
381097b8a7cSJan Schmidt 	}
382097b8a7cSJan Schmidt 	seq = btrfs_inc_tree_mod_seq(fs_info);
383bd989ba3SJan Schmidt 	spin_unlock(&fs_info->tree_mod_seq_lock);
384097b8a7cSJan Schmidt 	tree_mod_log_write_unlock(fs_info);
385097b8a7cSJan Schmidt 
386097b8a7cSJan Schmidt 	return seq;
387bd989ba3SJan Schmidt }
388bd989ba3SJan Schmidt 
389bd989ba3SJan Schmidt void btrfs_put_tree_mod_seq(struct btrfs_fs_info *fs_info,
390bd989ba3SJan Schmidt 			    struct seq_list *elem)
391bd989ba3SJan Schmidt {
392bd989ba3SJan Schmidt 	struct rb_root *tm_root;
393bd989ba3SJan Schmidt 	struct rb_node *node;
394bd989ba3SJan Schmidt 	struct rb_node *next;
395bd989ba3SJan Schmidt 	struct seq_list *cur_elem;
396bd989ba3SJan Schmidt 	struct tree_mod_elem *tm;
397bd989ba3SJan Schmidt 	u64 min_seq = (u64)-1;
398bd989ba3SJan Schmidt 	u64 seq_putting = elem->seq;
399bd989ba3SJan Schmidt 
400bd989ba3SJan Schmidt 	if (!seq_putting)
401bd989ba3SJan Schmidt 		return;
402bd989ba3SJan Schmidt 
403bd989ba3SJan Schmidt 	spin_lock(&fs_info->tree_mod_seq_lock);
404bd989ba3SJan Schmidt 	list_del(&elem->list);
405097b8a7cSJan Schmidt 	elem->seq = 0;
406bd989ba3SJan Schmidt 
407bd989ba3SJan Schmidt 	list_for_each_entry(cur_elem, &fs_info->tree_mod_seq_list, list) {
408097b8a7cSJan Schmidt 		if (cur_elem->seq < min_seq) {
409bd989ba3SJan Schmidt 			if (seq_putting > cur_elem->seq) {
410bd989ba3SJan Schmidt 				/*
411bd989ba3SJan Schmidt 				 * blocker with lower sequence number exists, we
412bd989ba3SJan Schmidt 				 * cannot remove anything from the log
413bd989ba3SJan Schmidt 				 */
414097b8a7cSJan Schmidt 				spin_unlock(&fs_info->tree_mod_seq_lock);
415097b8a7cSJan Schmidt 				return;
416bd989ba3SJan Schmidt 			}
417bd989ba3SJan Schmidt 			min_seq = cur_elem->seq;
418bd989ba3SJan Schmidt 		}
419bd989ba3SJan Schmidt 	}
420097b8a7cSJan Schmidt 	spin_unlock(&fs_info->tree_mod_seq_lock);
421097b8a7cSJan Schmidt 
422097b8a7cSJan Schmidt 	/*
423bd989ba3SJan Schmidt 	 * anything that's lower than the lowest existing (read: blocked)
424bd989ba3SJan Schmidt 	 * sequence number can be removed from the tree.
425bd989ba3SJan Schmidt 	 */
426097b8a7cSJan Schmidt 	tree_mod_log_write_lock(fs_info);
427bd989ba3SJan Schmidt 	tm_root = &fs_info->tree_mod_log;
428bd989ba3SJan Schmidt 	for (node = rb_first(tm_root); node; node = next) {
429bd989ba3SJan Schmidt 		next = rb_next(node);
430bd989ba3SJan Schmidt 		tm = container_of(node, struct tree_mod_elem, node);
431097b8a7cSJan Schmidt 		if (tm->seq > min_seq)
432bd989ba3SJan Schmidt 			continue;
433bd989ba3SJan Schmidt 		rb_erase(node, tm_root);
434bd989ba3SJan Schmidt 		kfree(tm);
435bd989ba3SJan Schmidt 	}
436097b8a7cSJan Schmidt 	tree_mod_log_write_unlock(fs_info);
437bd989ba3SJan Schmidt }
438bd989ba3SJan Schmidt 
439bd989ba3SJan Schmidt /*
440bd989ba3SJan Schmidt  * key order of the log:
441bd989ba3SJan Schmidt  *       index -> sequence
442bd989ba3SJan Schmidt  *
443bd989ba3SJan Schmidt  * the index is the shifted logical of the *new* root node for root replace
444bd989ba3SJan Schmidt  * operations, or the shifted logical of the affected block for all other
445bd989ba3SJan Schmidt  * operations.
446bd989ba3SJan Schmidt  */
447bd989ba3SJan Schmidt static noinline int
448bd989ba3SJan Schmidt __tree_mod_log_insert(struct btrfs_fs_info *fs_info, struct tree_mod_elem *tm)
449bd989ba3SJan Schmidt {
450bd989ba3SJan Schmidt 	struct rb_root *tm_root;
451bd989ba3SJan Schmidt 	struct rb_node **new;
452bd989ba3SJan Schmidt 	struct rb_node *parent = NULL;
453bd989ba3SJan Schmidt 	struct tree_mod_elem *cur;
454bd989ba3SJan Schmidt 
455097b8a7cSJan Schmidt 	BUG_ON(!tm || !tm->seq);
456bd989ba3SJan Schmidt 
457bd989ba3SJan Schmidt 	tm_root = &fs_info->tree_mod_log;
458bd989ba3SJan Schmidt 	new = &tm_root->rb_node;
459bd989ba3SJan Schmidt 	while (*new) {
460bd989ba3SJan Schmidt 		cur = container_of(*new, struct tree_mod_elem, node);
461bd989ba3SJan Schmidt 		parent = *new;
462bd989ba3SJan Schmidt 		if (cur->index < tm->index)
463bd989ba3SJan Schmidt 			new = &((*new)->rb_left);
464bd989ba3SJan Schmidt 		else if (cur->index > tm->index)
465bd989ba3SJan Schmidt 			new = &((*new)->rb_right);
466097b8a7cSJan Schmidt 		else if (cur->seq < tm->seq)
467bd989ba3SJan Schmidt 			new = &((*new)->rb_left);
468097b8a7cSJan Schmidt 		else if (cur->seq > tm->seq)
469bd989ba3SJan Schmidt 			new = &((*new)->rb_right);
470bd989ba3SJan Schmidt 		else {
471bd989ba3SJan Schmidt 			kfree(tm);
472097b8a7cSJan Schmidt 			return -EEXIST;
473bd989ba3SJan Schmidt 		}
474bd989ba3SJan Schmidt 	}
475bd989ba3SJan Schmidt 
476bd989ba3SJan Schmidt 	rb_link_node(&tm->node, parent, new);
477bd989ba3SJan Schmidt 	rb_insert_color(&tm->node, tm_root);
478097b8a7cSJan Schmidt 	return 0;
479bd989ba3SJan Schmidt }
480bd989ba3SJan Schmidt 
481097b8a7cSJan Schmidt /*
482097b8a7cSJan Schmidt  * Determines if logging can be omitted. Returns 1 if it can. Otherwise, it
483097b8a7cSJan Schmidt  * returns zero with the tree_mod_log_lock acquired. The caller must hold
484097b8a7cSJan Schmidt  * this until all tree mod log insertions are recorded in the rb tree and then
485097b8a7cSJan Schmidt  * call tree_mod_log_write_unlock() to release.
486097b8a7cSJan Schmidt  */
487e9b7fd4dSJan Schmidt static inline int tree_mod_dont_log(struct btrfs_fs_info *fs_info,
488e9b7fd4dSJan Schmidt 				    struct extent_buffer *eb) {
489e9b7fd4dSJan Schmidt 	smp_mb();
490e9b7fd4dSJan Schmidt 	if (list_empty(&(fs_info)->tree_mod_seq_list))
491e9b7fd4dSJan Schmidt 		return 1;
492097b8a7cSJan Schmidt 	if (eb && btrfs_header_level(eb) == 0)
493e9b7fd4dSJan Schmidt 		return 1;
494097b8a7cSJan Schmidt 
495097b8a7cSJan Schmidt 	tree_mod_log_write_lock(fs_info);
496097b8a7cSJan Schmidt 	if (list_empty(&fs_info->tree_mod_seq_list)) {
497097b8a7cSJan Schmidt 		/*
498097b8a7cSJan Schmidt 		 * someone emptied the list while we were waiting for the lock.
499097b8a7cSJan Schmidt 		 * we must not add to the list when no blocker exists.
500097b8a7cSJan Schmidt 		 */
501097b8a7cSJan Schmidt 		tree_mod_log_write_unlock(fs_info);
502097b8a7cSJan Schmidt 		return 1;
503097b8a7cSJan Schmidt 	}
504097b8a7cSJan Schmidt 
505e9b7fd4dSJan Schmidt 	return 0;
506e9b7fd4dSJan Schmidt }
507e9b7fd4dSJan Schmidt 
5083310c36eSJan Schmidt /*
509097b8a7cSJan Schmidt  * This allocates memory and gets a tree modification sequence number.
5103310c36eSJan Schmidt  *
511097b8a7cSJan Schmidt  * Returns <0 on error.
512097b8a7cSJan Schmidt  * Returns >0 (the added sequence number) on success.
5133310c36eSJan Schmidt  */
514926dd8a6SJan Schmidt static inline int tree_mod_alloc(struct btrfs_fs_info *fs_info, gfp_t flags,
515bd989ba3SJan Schmidt 				 struct tree_mod_elem **tm_ret)
516bd989ba3SJan Schmidt {
517bd989ba3SJan Schmidt 	struct tree_mod_elem *tm;
518bd989ba3SJan Schmidt 
519097b8a7cSJan Schmidt 	/*
520097b8a7cSJan Schmidt 	 * once we switch from spin locks to something different, we should
521097b8a7cSJan Schmidt 	 * honor the flags parameter here.
522097b8a7cSJan Schmidt 	 */
523097b8a7cSJan Schmidt 	tm = *tm_ret = kzalloc(sizeof(*tm), GFP_ATOMIC);
524bd989ba3SJan Schmidt 	if (!tm)
525bd989ba3SJan Schmidt 		return -ENOMEM;
526bd989ba3SJan Schmidt 
527097b8a7cSJan Schmidt 	tm->seq = btrfs_inc_tree_mod_seq(fs_info);
528097b8a7cSJan Schmidt 	return tm->seq;
529926dd8a6SJan Schmidt }
530bd989ba3SJan Schmidt 
531097b8a7cSJan Schmidt static inline int
532097b8a7cSJan Schmidt __tree_mod_log_insert_key(struct btrfs_fs_info *fs_info,
533bd989ba3SJan Schmidt 			  struct extent_buffer *eb, int slot,
534bd989ba3SJan Schmidt 			  enum mod_log_op op, gfp_t flags)
535bd989ba3SJan Schmidt {
536bd989ba3SJan Schmidt 	int ret;
537097b8a7cSJan Schmidt 	struct tree_mod_elem *tm;
538bd989ba3SJan Schmidt 
539bd989ba3SJan Schmidt 	ret = tree_mod_alloc(fs_info, flags, &tm);
540097b8a7cSJan Schmidt 	if (ret < 0)
541bd989ba3SJan Schmidt 		return ret;
542bd989ba3SJan Schmidt 
543bd989ba3SJan Schmidt 	tm->index = eb->start >> PAGE_CACHE_SHIFT;
544bd989ba3SJan Schmidt 	if (op != MOD_LOG_KEY_ADD) {
545bd989ba3SJan Schmidt 		btrfs_node_key(eb, &tm->key, slot);
546bd989ba3SJan Schmidt 		tm->blockptr = btrfs_node_blockptr(eb, slot);
547bd989ba3SJan Schmidt 	}
548bd989ba3SJan Schmidt 	tm->op = op;
549bd989ba3SJan Schmidt 	tm->slot = slot;
550bd989ba3SJan Schmidt 	tm->generation = btrfs_node_ptr_generation(eb, slot);
551bd989ba3SJan Schmidt 
552097b8a7cSJan Schmidt 	return __tree_mod_log_insert(fs_info, tm);
553097b8a7cSJan Schmidt }
554097b8a7cSJan Schmidt 
555097b8a7cSJan Schmidt static noinline int
556097b8a7cSJan Schmidt tree_mod_log_insert_key_mask(struct btrfs_fs_info *fs_info,
557097b8a7cSJan Schmidt 			     struct extent_buffer *eb, int slot,
558097b8a7cSJan Schmidt 			     enum mod_log_op op, gfp_t flags)
559097b8a7cSJan Schmidt {
560097b8a7cSJan Schmidt 	int ret;
561097b8a7cSJan Schmidt 
562097b8a7cSJan Schmidt 	if (tree_mod_dont_log(fs_info, eb))
563097b8a7cSJan Schmidt 		return 0;
564097b8a7cSJan Schmidt 
565097b8a7cSJan Schmidt 	ret = __tree_mod_log_insert_key(fs_info, eb, slot, op, flags);
566097b8a7cSJan Schmidt 
567097b8a7cSJan Schmidt 	tree_mod_log_write_unlock(fs_info);
5683310c36eSJan Schmidt 	return ret;
569bd989ba3SJan Schmidt }
570bd989ba3SJan Schmidt 
571bd989ba3SJan Schmidt static noinline int
572bd989ba3SJan Schmidt tree_mod_log_insert_key(struct btrfs_fs_info *fs_info, struct extent_buffer *eb,
573bd989ba3SJan Schmidt 			int slot, enum mod_log_op op)
574bd989ba3SJan Schmidt {
575bd989ba3SJan Schmidt 	return tree_mod_log_insert_key_mask(fs_info, eb, slot, op, GFP_NOFS);
576bd989ba3SJan Schmidt }
577bd989ba3SJan Schmidt 
578bd989ba3SJan Schmidt static noinline int
579097b8a7cSJan Schmidt tree_mod_log_insert_key_locked(struct btrfs_fs_info *fs_info,
580097b8a7cSJan Schmidt 			     struct extent_buffer *eb, int slot,
581097b8a7cSJan Schmidt 			     enum mod_log_op op)
582097b8a7cSJan Schmidt {
583097b8a7cSJan Schmidt 	return __tree_mod_log_insert_key(fs_info, eb, slot, op, GFP_NOFS);
584097b8a7cSJan Schmidt }
585097b8a7cSJan Schmidt 
586097b8a7cSJan Schmidt static noinline int
587bd989ba3SJan Schmidt tree_mod_log_insert_move(struct btrfs_fs_info *fs_info,
588bd989ba3SJan Schmidt 			 struct extent_buffer *eb, int dst_slot, int src_slot,
589bd989ba3SJan Schmidt 			 int nr_items, gfp_t flags)
590bd989ba3SJan Schmidt {
591bd989ba3SJan Schmidt 	struct tree_mod_elem *tm;
592bd989ba3SJan Schmidt 	int ret;
593bd989ba3SJan Schmidt 	int i;
594bd989ba3SJan Schmidt 
595f395694cSJan Schmidt 	if (tree_mod_dont_log(fs_info, eb))
596f395694cSJan Schmidt 		return 0;
597bd989ba3SJan Schmidt 
59801763a2eSJan Schmidt 	/*
59901763a2eSJan Schmidt 	 * When we override something during the move, we log these removals.
60001763a2eSJan Schmidt 	 * This can only happen when we move towards the beginning of the
60101763a2eSJan Schmidt 	 * buffer, i.e. dst_slot < src_slot.
60201763a2eSJan Schmidt 	 */
603bd989ba3SJan Schmidt 	for (i = 0; i + dst_slot < src_slot && i < nr_items; i++) {
604097b8a7cSJan Schmidt 		ret = tree_mod_log_insert_key_locked(fs_info, eb, i + dst_slot,
605bd989ba3SJan Schmidt 					      MOD_LOG_KEY_REMOVE_WHILE_MOVING);
606bd989ba3SJan Schmidt 		BUG_ON(ret < 0);
607bd989ba3SJan Schmidt 	}
608bd989ba3SJan Schmidt 
609f395694cSJan Schmidt 	ret = tree_mod_alloc(fs_info, flags, &tm);
610097b8a7cSJan Schmidt 	if (ret < 0)
611097b8a7cSJan Schmidt 		goto out;
612f395694cSJan Schmidt 
613bd989ba3SJan Schmidt 	tm->index = eb->start >> PAGE_CACHE_SHIFT;
614bd989ba3SJan Schmidt 	tm->slot = src_slot;
615bd989ba3SJan Schmidt 	tm->move.dst_slot = dst_slot;
616bd989ba3SJan Schmidt 	tm->move.nr_items = nr_items;
617bd989ba3SJan Schmidt 	tm->op = MOD_LOG_MOVE_KEYS;
618bd989ba3SJan Schmidt 
6193310c36eSJan Schmidt 	ret = __tree_mod_log_insert(fs_info, tm);
620097b8a7cSJan Schmidt out:
621097b8a7cSJan Schmidt 	tree_mod_log_write_unlock(fs_info);
6223310c36eSJan Schmidt 	return ret;
623bd989ba3SJan Schmidt }
624bd989ba3SJan Schmidt 
625097b8a7cSJan Schmidt static inline void
626097b8a7cSJan Schmidt __tree_mod_log_free_eb(struct btrfs_fs_info *fs_info, struct extent_buffer *eb)
627097b8a7cSJan Schmidt {
628097b8a7cSJan Schmidt 	int i;
629097b8a7cSJan Schmidt 	u32 nritems;
630097b8a7cSJan Schmidt 	int ret;
631097b8a7cSJan Schmidt 
632b12a3b1eSChris Mason 	if (btrfs_header_level(eb) == 0)
633b12a3b1eSChris Mason 		return;
634b12a3b1eSChris Mason 
635097b8a7cSJan Schmidt 	nritems = btrfs_header_nritems(eb);
636097b8a7cSJan Schmidt 	for (i = nritems - 1; i >= 0; i--) {
637097b8a7cSJan Schmidt 		ret = tree_mod_log_insert_key_locked(fs_info, eb, i,
638097b8a7cSJan Schmidt 					      MOD_LOG_KEY_REMOVE_WHILE_FREEING);
639097b8a7cSJan Schmidt 		BUG_ON(ret < 0);
640097b8a7cSJan Schmidt 	}
641097b8a7cSJan Schmidt }
642097b8a7cSJan Schmidt 
643bd989ba3SJan Schmidt static noinline int
644bd989ba3SJan Schmidt tree_mod_log_insert_root(struct btrfs_fs_info *fs_info,
645bd989ba3SJan Schmidt 			 struct extent_buffer *old_root,
646bd989ba3SJan Schmidt 			 struct extent_buffer *new_root, gfp_t flags)
647bd989ba3SJan Schmidt {
648bd989ba3SJan Schmidt 	struct tree_mod_elem *tm;
649bd989ba3SJan Schmidt 	int ret;
650bd989ba3SJan Schmidt 
651097b8a7cSJan Schmidt 	if (tree_mod_dont_log(fs_info, NULL))
652097b8a7cSJan Schmidt 		return 0;
653097b8a7cSJan Schmidt 
654bd989ba3SJan Schmidt 	ret = tree_mod_alloc(fs_info, flags, &tm);
655097b8a7cSJan Schmidt 	if (ret < 0)
656097b8a7cSJan Schmidt 		goto out;
657bd989ba3SJan Schmidt 
658bd989ba3SJan Schmidt 	tm->index = new_root->start >> PAGE_CACHE_SHIFT;
659bd989ba3SJan Schmidt 	tm->old_root.logical = old_root->start;
660bd989ba3SJan Schmidt 	tm->old_root.level = btrfs_header_level(old_root);
661bd989ba3SJan Schmidt 	tm->generation = btrfs_header_generation(old_root);
662bd989ba3SJan Schmidt 	tm->op = MOD_LOG_ROOT_REPLACE;
663bd989ba3SJan Schmidt 
6643310c36eSJan Schmidt 	ret = __tree_mod_log_insert(fs_info, tm);
665097b8a7cSJan Schmidt out:
666097b8a7cSJan Schmidt 	tree_mod_log_write_unlock(fs_info);
6673310c36eSJan Schmidt 	return ret;
668bd989ba3SJan Schmidt }
669bd989ba3SJan Schmidt 
670bd989ba3SJan Schmidt static struct tree_mod_elem *
671bd989ba3SJan Schmidt __tree_mod_log_search(struct btrfs_fs_info *fs_info, u64 start, u64 min_seq,
672bd989ba3SJan Schmidt 		      int smallest)
673bd989ba3SJan Schmidt {
674bd989ba3SJan Schmidt 	struct rb_root *tm_root;
675bd989ba3SJan Schmidt 	struct rb_node *node;
676bd989ba3SJan Schmidt 	struct tree_mod_elem *cur = NULL;
677bd989ba3SJan Schmidt 	struct tree_mod_elem *found = NULL;
678bd989ba3SJan Schmidt 	u64 index = start >> PAGE_CACHE_SHIFT;
679bd989ba3SJan Schmidt 
680097b8a7cSJan Schmidt 	tree_mod_log_read_lock(fs_info);
681bd989ba3SJan Schmidt 	tm_root = &fs_info->tree_mod_log;
682bd989ba3SJan Schmidt 	node = tm_root->rb_node;
683bd989ba3SJan Schmidt 	while (node) {
684bd989ba3SJan Schmidt 		cur = container_of(node, struct tree_mod_elem, node);
685bd989ba3SJan Schmidt 		if (cur->index < index) {
686bd989ba3SJan Schmidt 			node = node->rb_left;
687bd989ba3SJan Schmidt 		} else if (cur->index > index) {
688bd989ba3SJan Schmidt 			node = node->rb_right;
689097b8a7cSJan Schmidt 		} else if (cur->seq < min_seq) {
690bd989ba3SJan Schmidt 			node = node->rb_left;
691bd989ba3SJan Schmidt 		} else if (!smallest) {
692bd989ba3SJan Schmidt 			/* we want the node with the highest seq */
693bd989ba3SJan Schmidt 			if (found)
694097b8a7cSJan Schmidt 				BUG_ON(found->seq > cur->seq);
695bd989ba3SJan Schmidt 			found = cur;
696bd989ba3SJan Schmidt 			node = node->rb_left;
697097b8a7cSJan Schmidt 		} else if (cur->seq > min_seq) {
698bd989ba3SJan Schmidt 			/* we want the node with the smallest seq */
699bd989ba3SJan Schmidt 			if (found)
700097b8a7cSJan Schmidt 				BUG_ON(found->seq < cur->seq);
701bd989ba3SJan Schmidt 			found = cur;
702bd989ba3SJan Schmidt 			node = node->rb_right;
703bd989ba3SJan Schmidt 		} else {
704bd989ba3SJan Schmidt 			found = cur;
705bd989ba3SJan Schmidt 			break;
706bd989ba3SJan Schmidt 		}
707bd989ba3SJan Schmidt 	}
708097b8a7cSJan Schmidt 	tree_mod_log_read_unlock(fs_info);
709bd989ba3SJan Schmidt 
710bd989ba3SJan Schmidt 	return found;
711bd989ba3SJan Schmidt }
712bd989ba3SJan Schmidt 
713bd989ba3SJan Schmidt /*
714bd989ba3SJan Schmidt  * this returns the element from the log with the smallest time sequence
715bd989ba3SJan Schmidt  * value that's in the log (the oldest log item). any element with a time
716bd989ba3SJan Schmidt  * sequence lower than min_seq will be ignored.
717bd989ba3SJan Schmidt  */
718bd989ba3SJan Schmidt static struct tree_mod_elem *
719bd989ba3SJan Schmidt tree_mod_log_search_oldest(struct btrfs_fs_info *fs_info, u64 start,
720bd989ba3SJan Schmidt 			   u64 min_seq)
721bd989ba3SJan Schmidt {
722bd989ba3SJan Schmidt 	return __tree_mod_log_search(fs_info, start, min_seq, 1);
723bd989ba3SJan Schmidt }
724bd989ba3SJan Schmidt 
725bd989ba3SJan Schmidt /*
726bd989ba3SJan Schmidt  * this returns the element from the log with the largest time sequence
727bd989ba3SJan Schmidt  * value that's in the log (the most recent log item). any element with
728bd989ba3SJan Schmidt  * a time sequence lower than min_seq will be ignored.
729bd989ba3SJan Schmidt  */
730bd989ba3SJan Schmidt static struct tree_mod_elem *
731bd989ba3SJan Schmidt tree_mod_log_search(struct btrfs_fs_info *fs_info, u64 start, u64 min_seq)
732bd989ba3SJan Schmidt {
733bd989ba3SJan Schmidt 	return __tree_mod_log_search(fs_info, start, min_seq, 0);
734bd989ba3SJan Schmidt }
735bd989ba3SJan Schmidt 
736097b8a7cSJan Schmidt static noinline void
737bd989ba3SJan Schmidt tree_mod_log_eb_copy(struct btrfs_fs_info *fs_info, struct extent_buffer *dst,
738bd989ba3SJan Schmidt 		     struct extent_buffer *src, unsigned long dst_offset,
739bd989ba3SJan Schmidt 		     unsigned long src_offset, int nr_items)
740bd989ba3SJan Schmidt {
741bd989ba3SJan Schmidt 	int ret;
742bd989ba3SJan Schmidt 	int i;
743bd989ba3SJan Schmidt 
744e9b7fd4dSJan Schmidt 	if (tree_mod_dont_log(fs_info, NULL))
745bd989ba3SJan Schmidt 		return;
746bd989ba3SJan Schmidt 
747097b8a7cSJan Schmidt 	if (btrfs_header_level(dst) == 0 && btrfs_header_level(src) == 0) {
748097b8a7cSJan Schmidt 		tree_mod_log_write_unlock(fs_info);
749bd989ba3SJan Schmidt 		return;
750097b8a7cSJan Schmidt 	}
751bd989ba3SJan Schmidt 
752bd989ba3SJan Schmidt 	for (i = 0; i < nr_items; i++) {
753097b8a7cSJan Schmidt 		ret = tree_mod_log_insert_key_locked(fs_info, src,
754097b8a7cSJan Schmidt 						     i + src_offset,
755bd989ba3SJan Schmidt 						     MOD_LOG_KEY_REMOVE);
756bd989ba3SJan Schmidt 		BUG_ON(ret < 0);
757097b8a7cSJan Schmidt 		ret = tree_mod_log_insert_key_locked(fs_info, dst,
758097b8a7cSJan Schmidt 						     i + dst_offset,
759bd989ba3SJan Schmidt 						     MOD_LOG_KEY_ADD);
760bd989ba3SJan Schmidt 		BUG_ON(ret < 0);
761bd989ba3SJan Schmidt 	}
762097b8a7cSJan Schmidt 
763097b8a7cSJan Schmidt 	tree_mod_log_write_unlock(fs_info);
764bd989ba3SJan Schmidt }
765bd989ba3SJan Schmidt 
766bd989ba3SJan Schmidt static inline void
767bd989ba3SJan Schmidt tree_mod_log_eb_move(struct btrfs_fs_info *fs_info, struct extent_buffer *dst,
768bd989ba3SJan Schmidt 		     int dst_offset, int src_offset, int nr_items)
769bd989ba3SJan Schmidt {
770bd989ba3SJan Schmidt 	int ret;
771bd989ba3SJan Schmidt 	ret = tree_mod_log_insert_move(fs_info, dst, dst_offset, src_offset,
772bd989ba3SJan Schmidt 				       nr_items, GFP_NOFS);
773bd989ba3SJan Schmidt 	BUG_ON(ret < 0);
774bd989ba3SJan Schmidt }
775bd989ba3SJan Schmidt 
776097b8a7cSJan Schmidt static noinline void
777bd989ba3SJan Schmidt tree_mod_log_set_node_key(struct btrfs_fs_info *fs_info,
77832adf090SLiu Bo 			  struct extent_buffer *eb, int slot, int atomic)
779bd989ba3SJan Schmidt {
780bd989ba3SJan Schmidt 	int ret;
781bd989ba3SJan Schmidt 
782bd989ba3SJan Schmidt 	ret = tree_mod_log_insert_key_mask(fs_info, eb, slot,
783bd989ba3SJan Schmidt 					   MOD_LOG_KEY_REPLACE,
784bd989ba3SJan Schmidt 					   atomic ? GFP_ATOMIC : GFP_NOFS);
785bd989ba3SJan Schmidt 	BUG_ON(ret < 0);
786bd989ba3SJan Schmidt }
787bd989ba3SJan Schmidt 
788097b8a7cSJan Schmidt static noinline void
789097b8a7cSJan Schmidt tree_mod_log_free_eb(struct btrfs_fs_info *fs_info, struct extent_buffer *eb)
790bd989ba3SJan Schmidt {
791e9b7fd4dSJan Schmidt 	if (tree_mod_dont_log(fs_info, eb))
792bd989ba3SJan Schmidt 		return;
793bd989ba3SJan Schmidt 
794097b8a7cSJan Schmidt 	__tree_mod_log_free_eb(fs_info, eb);
795097b8a7cSJan Schmidt 
796097b8a7cSJan Schmidt 	tree_mod_log_write_unlock(fs_info);
797bd989ba3SJan Schmidt }
798bd989ba3SJan Schmidt 
799097b8a7cSJan Schmidt static noinline void
800bd989ba3SJan Schmidt tree_mod_log_set_root_pointer(struct btrfs_root *root,
801bd989ba3SJan Schmidt 			      struct extent_buffer *new_root_node)
802bd989ba3SJan Schmidt {
803bd989ba3SJan Schmidt 	int ret;
804bd989ba3SJan Schmidt 	ret = tree_mod_log_insert_root(root->fs_info, root->node,
805bd989ba3SJan Schmidt 				       new_root_node, GFP_NOFS);
806bd989ba3SJan Schmidt 	BUG_ON(ret < 0);
807bd989ba3SJan Schmidt }
808bd989ba3SJan Schmidt 
809d352ac68SChris Mason /*
8105d4f98a2SYan Zheng  * check if the tree block can be shared by multiple trees
8115d4f98a2SYan Zheng  */
8125d4f98a2SYan Zheng int btrfs_block_can_be_shared(struct btrfs_root *root,
8135d4f98a2SYan Zheng 			      struct extent_buffer *buf)
8145d4f98a2SYan Zheng {
8155d4f98a2SYan Zheng 	/*
8165d4f98a2SYan Zheng 	 * Tree blocks not in refernece counted trees and tree roots
8175d4f98a2SYan Zheng 	 * are never shared. If a block was allocated after the last
8185d4f98a2SYan Zheng 	 * snapshot and the block was not allocated by tree relocation,
8195d4f98a2SYan Zheng 	 * we know the block is not shared.
8205d4f98a2SYan Zheng 	 */
8215d4f98a2SYan Zheng 	if (root->ref_cows &&
8225d4f98a2SYan Zheng 	    buf != root->node && buf != root->commit_root &&
8235d4f98a2SYan Zheng 	    (btrfs_header_generation(buf) <=
8245d4f98a2SYan Zheng 	     btrfs_root_last_snapshot(&root->root_item) ||
8255d4f98a2SYan Zheng 	     btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)))
8265d4f98a2SYan Zheng 		return 1;
8275d4f98a2SYan Zheng #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
8285d4f98a2SYan Zheng 	if (root->ref_cows &&
8295d4f98a2SYan Zheng 	    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
8305d4f98a2SYan Zheng 		return 1;
8315d4f98a2SYan Zheng #endif
8325d4f98a2SYan Zheng 	return 0;
8335d4f98a2SYan Zheng }
8345d4f98a2SYan Zheng 
8355d4f98a2SYan Zheng static noinline int update_ref_for_cow(struct btrfs_trans_handle *trans,
8365d4f98a2SYan Zheng 				       struct btrfs_root *root,
8375d4f98a2SYan Zheng 				       struct extent_buffer *buf,
838f0486c68SYan, Zheng 				       struct extent_buffer *cow,
839f0486c68SYan, Zheng 				       int *last_ref)
8405d4f98a2SYan Zheng {
8415d4f98a2SYan Zheng 	u64 refs;
8425d4f98a2SYan Zheng 	u64 owner;
8435d4f98a2SYan Zheng 	u64 flags;
8445d4f98a2SYan Zheng 	u64 new_flags = 0;
8455d4f98a2SYan Zheng 	int ret;
8465d4f98a2SYan Zheng 
8475d4f98a2SYan Zheng 	/*
8485d4f98a2SYan Zheng 	 * Backrefs update rules:
8495d4f98a2SYan Zheng 	 *
8505d4f98a2SYan Zheng 	 * Always use full backrefs for extent pointers in tree block
8515d4f98a2SYan Zheng 	 * allocated by tree relocation.
8525d4f98a2SYan Zheng 	 *
8535d4f98a2SYan Zheng 	 * If a shared tree block is no longer referenced by its owner
8545d4f98a2SYan Zheng 	 * tree (btrfs_header_owner(buf) == root->root_key.objectid),
8555d4f98a2SYan Zheng 	 * use full backrefs for extent pointers in tree block.
8565d4f98a2SYan Zheng 	 *
8575d4f98a2SYan Zheng 	 * If a tree block is been relocating
8585d4f98a2SYan Zheng 	 * (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID),
8595d4f98a2SYan Zheng 	 * use full backrefs for extent pointers in tree block.
8605d4f98a2SYan Zheng 	 * The reason for this is some operations (such as drop tree)
8615d4f98a2SYan Zheng 	 * are only allowed for blocks use full backrefs.
8625d4f98a2SYan Zheng 	 */
8635d4f98a2SYan Zheng 
8645d4f98a2SYan Zheng 	if (btrfs_block_can_be_shared(root, buf)) {
8655d4f98a2SYan Zheng 		ret = btrfs_lookup_extent_info(trans, root, buf->start,
8665d4f98a2SYan Zheng 					       buf->len, &refs, &flags);
867be1a5564SMark Fasheh 		if (ret)
868be1a5564SMark Fasheh 			return ret;
869e5df9573SMark Fasheh 		if (refs == 0) {
870e5df9573SMark Fasheh 			ret = -EROFS;
871e5df9573SMark Fasheh 			btrfs_std_error(root->fs_info, ret);
872e5df9573SMark Fasheh 			return ret;
873e5df9573SMark Fasheh 		}
8745d4f98a2SYan Zheng 	} else {
8755d4f98a2SYan Zheng 		refs = 1;
8765d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
8775d4f98a2SYan Zheng 		    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
8785d4f98a2SYan Zheng 			flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
8795d4f98a2SYan Zheng 		else
8805d4f98a2SYan Zheng 			flags = 0;
8815d4f98a2SYan Zheng 	}
8825d4f98a2SYan Zheng 
8835d4f98a2SYan Zheng 	owner = btrfs_header_owner(buf);
8845d4f98a2SYan Zheng 	BUG_ON(owner == BTRFS_TREE_RELOC_OBJECTID &&
8855d4f98a2SYan Zheng 	       !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
8865d4f98a2SYan Zheng 
8875d4f98a2SYan Zheng 	if (refs > 1) {
8885d4f98a2SYan Zheng 		if ((owner == root->root_key.objectid ||
8895d4f98a2SYan Zheng 		     root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) &&
8905d4f98a2SYan Zheng 		    !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)) {
89166d7e7f0SArne Jansen 			ret = btrfs_inc_ref(trans, root, buf, 1, 1);
89279787eaaSJeff Mahoney 			BUG_ON(ret); /* -ENOMEM */
8935d4f98a2SYan Zheng 
8945d4f98a2SYan Zheng 			if (root->root_key.objectid ==
8955d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID) {
89666d7e7f0SArne Jansen 				ret = btrfs_dec_ref(trans, root, buf, 0, 1);
89779787eaaSJeff Mahoney 				BUG_ON(ret); /* -ENOMEM */
89866d7e7f0SArne Jansen 				ret = btrfs_inc_ref(trans, root, cow, 1, 1);
89979787eaaSJeff Mahoney 				BUG_ON(ret); /* -ENOMEM */
9005d4f98a2SYan Zheng 			}
9015d4f98a2SYan Zheng 			new_flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
9025d4f98a2SYan Zheng 		} else {
9035d4f98a2SYan Zheng 
9045d4f98a2SYan Zheng 			if (root->root_key.objectid ==
9055d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID)
90666d7e7f0SArne Jansen 				ret = btrfs_inc_ref(trans, root, cow, 1, 1);
9075d4f98a2SYan Zheng 			else
90866d7e7f0SArne Jansen 				ret = btrfs_inc_ref(trans, root, cow, 0, 1);
90979787eaaSJeff Mahoney 			BUG_ON(ret); /* -ENOMEM */
9105d4f98a2SYan Zheng 		}
9115d4f98a2SYan Zheng 		if (new_flags != 0) {
9125d4f98a2SYan Zheng 			ret = btrfs_set_disk_extent_flags(trans, root,
9135d4f98a2SYan Zheng 							  buf->start,
9145d4f98a2SYan Zheng 							  buf->len,
9155d4f98a2SYan Zheng 							  new_flags, 0);
916be1a5564SMark Fasheh 			if (ret)
917be1a5564SMark Fasheh 				return ret;
9185d4f98a2SYan Zheng 		}
9195d4f98a2SYan Zheng 	} else {
9205d4f98a2SYan Zheng 		if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
9215d4f98a2SYan Zheng 			if (root->root_key.objectid ==
9225d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID)
92366d7e7f0SArne Jansen 				ret = btrfs_inc_ref(trans, root, cow, 1, 1);
9245d4f98a2SYan Zheng 			else
92566d7e7f0SArne Jansen 				ret = btrfs_inc_ref(trans, root, cow, 0, 1);
92679787eaaSJeff Mahoney 			BUG_ON(ret); /* -ENOMEM */
92766d7e7f0SArne Jansen 			ret = btrfs_dec_ref(trans, root, buf, 1, 1);
92879787eaaSJeff Mahoney 			BUG_ON(ret); /* -ENOMEM */
9295d4f98a2SYan Zheng 		}
930f230475eSJan Schmidt 		tree_mod_log_free_eb(root->fs_info, buf);
9315d4f98a2SYan Zheng 		clean_tree_block(trans, root, buf);
932f0486c68SYan, Zheng 		*last_ref = 1;
9335d4f98a2SYan Zheng 	}
9345d4f98a2SYan Zheng 	return 0;
9355d4f98a2SYan Zheng }
9365d4f98a2SYan Zheng 
9375d4f98a2SYan Zheng /*
938d397712bSChris Mason  * does the dirty work in cow of a single block.  The parent block (if
939d397712bSChris Mason  * supplied) is updated to point to the new cow copy.  The new buffer is marked
940d397712bSChris Mason  * dirty and returned locked.  If you modify the block it needs to be marked
941d397712bSChris Mason  * dirty again.
942d352ac68SChris Mason  *
943d352ac68SChris Mason  * search_start -- an allocation hint for the new block
944d352ac68SChris Mason  *
945d397712bSChris Mason  * empty_size -- a hint that you plan on doing more cow.  This is the size in
946d397712bSChris Mason  * bytes the allocator should try to find free next to the block it returns.
947d397712bSChris Mason  * This is just a hint and may be ignored by the allocator.
948d352ac68SChris Mason  */
949d397712bSChris Mason static noinline int __btrfs_cow_block(struct btrfs_trans_handle *trans,
9505f39d397SChris Mason 			     struct btrfs_root *root,
9515f39d397SChris Mason 			     struct extent_buffer *buf,
9525f39d397SChris Mason 			     struct extent_buffer *parent, int parent_slot,
9535f39d397SChris Mason 			     struct extent_buffer **cow_ret,
9549fa8cfe7SChris Mason 			     u64 search_start, u64 empty_size)
9556702ed49SChris Mason {
9565d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
9575f39d397SChris Mason 	struct extent_buffer *cow;
958be1a5564SMark Fasheh 	int level, ret;
959f0486c68SYan, Zheng 	int last_ref = 0;
960925baeddSChris Mason 	int unlock_orig = 0;
9615d4f98a2SYan Zheng 	u64 parent_start;
9626702ed49SChris Mason 
963925baeddSChris Mason 	if (*cow_ret == buf)
964925baeddSChris Mason 		unlock_orig = 1;
965925baeddSChris Mason 
966b9447ef8SChris Mason 	btrfs_assert_tree_locked(buf);
967925baeddSChris Mason 
9687bb86316SChris Mason 	WARN_ON(root->ref_cows && trans->transid !=
9697bb86316SChris Mason 		root->fs_info->running_transaction->transid);
9706702ed49SChris Mason 	WARN_ON(root->ref_cows && trans->transid != root->last_trans);
9715f39d397SChris Mason 
9727bb86316SChris Mason 	level = btrfs_header_level(buf);
97331840ae1SZheng Yan 
9745d4f98a2SYan Zheng 	if (level == 0)
9755d4f98a2SYan Zheng 		btrfs_item_key(buf, &disk_key, 0);
9765d4f98a2SYan Zheng 	else
9775d4f98a2SYan Zheng 		btrfs_node_key(buf, &disk_key, 0);
9785d4f98a2SYan Zheng 
9795d4f98a2SYan Zheng 	if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) {
9805d4f98a2SYan Zheng 		if (parent)
9815d4f98a2SYan Zheng 			parent_start = parent->start;
9825d4f98a2SYan Zheng 		else
9835d4f98a2SYan Zheng 			parent_start = 0;
9845d4f98a2SYan Zheng 	} else
9855d4f98a2SYan Zheng 		parent_start = 0;
9865d4f98a2SYan Zheng 
9875d4f98a2SYan Zheng 	cow = btrfs_alloc_free_block(trans, root, buf->len, parent_start,
9885d4f98a2SYan Zheng 				     root->root_key.objectid, &disk_key,
9895581a51aSJan Schmidt 				     level, search_start, empty_size);
9906702ed49SChris Mason 	if (IS_ERR(cow))
9916702ed49SChris Mason 		return PTR_ERR(cow);
9926702ed49SChris Mason 
993b4ce94deSChris Mason 	/* cow is set to blocking by btrfs_init_new_buffer */
994b4ce94deSChris Mason 
9955f39d397SChris Mason 	copy_extent_buffer(cow, buf, 0, 0, cow->len);
996db94535dSChris Mason 	btrfs_set_header_bytenr(cow, cow->start);
9975f39d397SChris Mason 	btrfs_set_header_generation(cow, trans->transid);
9985d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
9995d4f98a2SYan Zheng 	btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
10005d4f98a2SYan Zheng 				     BTRFS_HEADER_FLAG_RELOC);
10015d4f98a2SYan Zheng 	if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
10025d4f98a2SYan Zheng 		btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
10035d4f98a2SYan Zheng 	else
10045f39d397SChris Mason 		btrfs_set_header_owner(cow, root->root_key.objectid);
10056702ed49SChris Mason 
10062b82032cSYan Zheng 	write_extent_buffer(cow, root->fs_info->fsid,
10072b82032cSYan Zheng 			    (unsigned long)btrfs_header_fsid(cow),
10082b82032cSYan Zheng 			    BTRFS_FSID_SIZE);
10092b82032cSYan Zheng 
1010be1a5564SMark Fasheh 	ret = update_ref_for_cow(trans, root, buf, cow, &last_ref);
1011b68dc2a9SMark Fasheh 	if (ret) {
101279787eaaSJeff Mahoney 		btrfs_abort_transaction(trans, root, ret);
1013b68dc2a9SMark Fasheh 		return ret;
1014b68dc2a9SMark Fasheh 	}
10151a40e23bSZheng Yan 
10163fd0a558SYan, Zheng 	if (root->ref_cows)
10173fd0a558SYan, Zheng 		btrfs_reloc_cow_block(trans, root, buf, cow);
10183fd0a558SYan, Zheng 
10196702ed49SChris Mason 	if (buf == root->node) {
1020925baeddSChris Mason 		WARN_ON(parent && parent != buf);
10215d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
10225d4f98a2SYan Zheng 		    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
10235d4f98a2SYan Zheng 			parent_start = buf->start;
10245d4f98a2SYan Zheng 		else
10255d4f98a2SYan Zheng 			parent_start = 0;
1026925baeddSChris Mason 
10275f39d397SChris Mason 		extent_buffer_get(cow);
1028f230475eSJan Schmidt 		tree_mod_log_set_root_pointer(root, cow);
1029240f62c8SChris Mason 		rcu_assign_pointer(root->node, cow);
1030925baeddSChris Mason 
1031f0486c68SYan, Zheng 		btrfs_free_tree_block(trans, root, buf, parent_start,
10325581a51aSJan Schmidt 				      last_ref);
10335f39d397SChris Mason 		free_extent_buffer(buf);
10340b86a832SChris Mason 		add_root_to_dirty_list(root);
10356702ed49SChris Mason 	} else {
10365d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
10375d4f98a2SYan Zheng 			parent_start = parent->start;
10385d4f98a2SYan Zheng 		else
10395d4f98a2SYan Zheng 			parent_start = 0;
10405d4f98a2SYan Zheng 
10415d4f98a2SYan Zheng 		WARN_ON(trans->transid != btrfs_header_generation(parent));
1042f230475eSJan Schmidt 		tree_mod_log_insert_key(root->fs_info, parent, parent_slot,
1043f230475eSJan Schmidt 					MOD_LOG_KEY_REPLACE);
10445f39d397SChris Mason 		btrfs_set_node_blockptr(parent, parent_slot,
1045db94535dSChris Mason 					cow->start);
104674493f7aSChris Mason 		btrfs_set_node_ptr_generation(parent, parent_slot,
104774493f7aSChris Mason 					      trans->transid);
10486702ed49SChris Mason 		btrfs_mark_buffer_dirty(parent);
1049f0486c68SYan, Zheng 		btrfs_free_tree_block(trans, root, buf, parent_start,
10505581a51aSJan Schmidt 				      last_ref);
10516702ed49SChris Mason 	}
1052925baeddSChris Mason 	if (unlock_orig)
1053925baeddSChris Mason 		btrfs_tree_unlock(buf);
10543083ee2eSJosef Bacik 	free_extent_buffer_stale(buf);
10556702ed49SChris Mason 	btrfs_mark_buffer_dirty(cow);
10566702ed49SChris Mason 	*cow_ret = cow;
10576702ed49SChris Mason 	return 0;
10586702ed49SChris Mason }
10596702ed49SChris Mason 
10605d9e75c4SJan Schmidt /*
10615d9e75c4SJan Schmidt  * returns the logical address of the oldest predecessor of the given root.
10625d9e75c4SJan Schmidt  * entries older than time_seq are ignored.
10635d9e75c4SJan Schmidt  */
10645d9e75c4SJan Schmidt static struct tree_mod_elem *
10655d9e75c4SJan Schmidt __tree_mod_log_oldest_root(struct btrfs_fs_info *fs_info,
10665d9e75c4SJan Schmidt 			   struct btrfs_root *root, u64 time_seq)
10675d9e75c4SJan Schmidt {
10685d9e75c4SJan Schmidt 	struct tree_mod_elem *tm;
10695d9e75c4SJan Schmidt 	struct tree_mod_elem *found = NULL;
10705d9e75c4SJan Schmidt 	u64 root_logical = root->node->start;
10715d9e75c4SJan Schmidt 	int looped = 0;
10725d9e75c4SJan Schmidt 
10735d9e75c4SJan Schmidt 	if (!time_seq)
10745d9e75c4SJan Schmidt 		return 0;
10755d9e75c4SJan Schmidt 
10765d9e75c4SJan Schmidt 	/*
10775d9e75c4SJan Schmidt 	 * the very last operation that's logged for a root is the replacement
10785d9e75c4SJan Schmidt 	 * operation (if it is replaced at all). this has the index of the *new*
10795d9e75c4SJan Schmidt 	 * root, making it the very first operation that's logged for this root.
10805d9e75c4SJan Schmidt 	 */
10815d9e75c4SJan Schmidt 	while (1) {
10825d9e75c4SJan Schmidt 		tm = tree_mod_log_search_oldest(fs_info, root_logical,
10835d9e75c4SJan Schmidt 						time_seq);
10845d9e75c4SJan Schmidt 		if (!looped && !tm)
10855d9e75c4SJan Schmidt 			return 0;
10865d9e75c4SJan Schmidt 		/*
108728da9fb4SJan Schmidt 		 * if there are no tree operation for the oldest root, we simply
108828da9fb4SJan Schmidt 		 * return it. this should only happen if that (old) root is at
108928da9fb4SJan Schmidt 		 * level 0.
10905d9e75c4SJan Schmidt 		 */
109128da9fb4SJan Schmidt 		if (!tm)
109228da9fb4SJan Schmidt 			break;
10935d9e75c4SJan Schmidt 
109428da9fb4SJan Schmidt 		/*
109528da9fb4SJan Schmidt 		 * if there's an operation that's not a root replacement, we
109628da9fb4SJan Schmidt 		 * found the oldest version of our root. normally, we'll find a
109728da9fb4SJan Schmidt 		 * MOD_LOG_KEY_REMOVE_WHILE_FREEING operation here.
109828da9fb4SJan Schmidt 		 */
10995d9e75c4SJan Schmidt 		if (tm->op != MOD_LOG_ROOT_REPLACE)
11005d9e75c4SJan Schmidt 			break;
11015d9e75c4SJan Schmidt 
11025d9e75c4SJan Schmidt 		found = tm;
11035d9e75c4SJan Schmidt 		root_logical = tm->old_root.logical;
11045d9e75c4SJan Schmidt 		BUG_ON(root_logical == root->node->start);
11055d9e75c4SJan Schmidt 		looped = 1;
11065d9e75c4SJan Schmidt 	}
11075d9e75c4SJan Schmidt 
1108a95236d9SJan Schmidt 	/* if there's no old root to return, return what we found instead */
1109a95236d9SJan Schmidt 	if (!found)
1110a95236d9SJan Schmidt 		found = tm;
1111a95236d9SJan Schmidt 
11125d9e75c4SJan Schmidt 	return found;
11135d9e75c4SJan Schmidt }
11145d9e75c4SJan Schmidt 
11155d9e75c4SJan Schmidt /*
11165d9e75c4SJan Schmidt  * tm is a pointer to the first operation to rewind within eb. then, all
11175d9e75c4SJan Schmidt  * previous operations will be rewinded (until we reach something older than
11185d9e75c4SJan Schmidt  * time_seq).
11195d9e75c4SJan Schmidt  */
11205d9e75c4SJan Schmidt static void
11215d9e75c4SJan Schmidt __tree_mod_log_rewind(struct extent_buffer *eb, u64 time_seq,
11225d9e75c4SJan Schmidt 		      struct tree_mod_elem *first_tm)
11235d9e75c4SJan Schmidt {
11245d9e75c4SJan Schmidt 	u32 n;
11255d9e75c4SJan Schmidt 	struct rb_node *next;
11265d9e75c4SJan Schmidt 	struct tree_mod_elem *tm = first_tm;
11275d9e75c4SJan Schmidt 	unsigned long o_dst;
11285d9e75c4SJan Schmidt 	unsigned long o_src;
11295d9e75c4SJan Schmidt 	unsigned long p_size = sizeof(struct btrfs_key_ptr);
11305d9e75c4SJan Schmidt 
11315d9e75c4SJan Schmidt 	n = btrfs_header_nritems(eb);
1132097b8a7cSJan Schmidt 	while (tm && tm->seq >= time_seq) {
11335d9e75c4SJan Schmidt 		/*
11345d9e75c4SJan Schmidt 		 * all the operations are recorded with the operator used for
11355d9e75c4SJan Schmidt 		 * the modification. as we're going backwards, we do the
11365d9e75c4SJan Schmidt 		 * opposite of each operation here.
11375d9e75c4SJan Schmidt 		 */
11385d9e75c4SJan Schmidt 		switch (tm->op) {
11395d9e75c4SJan Schmidt 		case MOD_LOG_KEY_REMOVE_WHILE_FREEING:
11405d9e75c4SJan Schmidt 			BUG_ON(tm->slot < n);
1141*1c697d4aSEric Sandeen 			/* Fallthrough */
114295c80bb1SLiu Bo 		case MOD_LOG_KEY_REMOVE_WHILE_MOVING:
11434c3e6969SChris Mason 		case MOD_LOG_KEY_REMOVE:
11445d9e75c4SJan Schmidt 			btrfs_set_node_key(eb, &tm->key, tm->slot);
11455d9e75c4SJan Schmidt 			btrfs_set_node_blockptr(eb, tm->slot, tm->blockptr);
11465d9e75c4SJan Schmidt 			btrfs_set_node_ptr_generation(eb, tm->slot,
11475d9e75c4SJan Schmidt 						      tm->generation);
11484c3e6969SChris Mason 			n++;
11495d9e75c4SJan Schmidt 			break;
11505d9e75c4SJan Schmidt 		case MOD_LOG_KEY_REPLACE:
11515d9e75c4SJan Schmidt 			BUG_ON(tm->slot >= n);
11525d9e75c4SJan Schmidt 			btrfs_set_node_key(eb, &tm->key, tm->slot);
11535d9e75c4SJan Schmidt 			btrfs_set_node_blockptr(eb, tm->slot, tm->blockptr);
11545d9e75c4SJan Schmidt 			btrfs_set_node_ptr_generation(eb, tm->slot,
11555d9e75c4SJan Schmidt 						      tm->generation);
11565d9e75c4SJan Schmidt 			break;
11575d9e75c4SJan Schmidt 		case MOD_LOG_KEY_ADD:
115819956c7eSJan Schmidt 			/* if a move operation is needed it's in the log */
11595d9e75c4SJan Schmidt 			n--;
11605d9e75c4SJan Schmidt 			break;
11615d9e75c4SJan Schmidt 		case MOD_LOG_MOVE_KEYS:
1162c3193108SJan Schmidt 			o_dst = btrfs_node_key_ptr_offset(tm->slot);
1163c3193108SJan Schmidt 			o_src = btrfs_node_key_ptr_offset(tm->move.dst_slot);
1164c3193108SJan Schmidt 			memmove_extent_buffer(eb, o_dst, o_src,
11655d9e75c4SJan Schmidt 					      tm->move.nr_items * p_size);
11665d9e75c4SJan Schmidt 			break;
11675d9e75c4SJan Schmidt 		case MOD_LOG_ROOT_REPLACE:
11685d9e75c4SJan Schmidt 			/*
11695d9e75c4SJan Schmidt 			 * this operation is special. for roots, this must be
11705d9e75c4SJan Schmidt 			 * handled explicitly before rewinding.
11715d9e75c4SJan Schmidt 			 * for non-roots, this operation may exist if the node
11725d9e75c4SJan Schmidt 			 * was a root: root A -> child B; then A gets empty and
11735d9e75c4SJan Schmidt 			 * B is promoted to the new root. in the mod log, we'll
11745d9e75c4SJan Schmidt 			 * have a root-replace operation for B, a tree block
11755d9e75c4SJan Schmidt 			 * that is no root. we simply ignore that operation.
11765d9e75c4SJan Schmidt 			 */
11775d9e75c4SJan Schmidt 			break;
11785d9e75c4SJan Schmidt 		}
11795d9e75c4SJan Schmidt 		next = rb_next(&tm->node);
11805d9e75c4SJan Schmidt 		if (!next)
11815d9e75c4SJan Schmidt 			break;
11825d9e75c4SJan Schmidt 		tm = container_of(next, struct tree_mod_elem, node);
11835d9e75c4SJan Schmidt 		if (tm->index != first_tm->index)
11845d9e75c4SJan Schmidt 			break;
11855d9e75c4SJan Schmidt 	}
11865d9e75c4SJan Schmidt 	btrfs_set_header_nritems(eb, n);
11875d9e75c4SJan Schmidt }
11885d9e75c4SJan Schmidt 
11895d9e75c4SJan Schmidt static struct extent_buffer *
11905d9e75c4SJan Schmidt tree_mod_log_rewind(struct btrfs_fs_info *fs_info, struct extent_buffer *eb,
11915d9e75c4SJan Schmidt 		    u64 time_seq)
11925d9e75c4SJan Schmidt {
11935d9e75c4SJan Schmidt 	struct extent_buffer *eb_rewin;
11945d9e75c4SJan Schmidt 	struct tree_mod_elem *tm;
11955d9e75c4SJan Schmidt 
11965d9e75c4SJan Schmidt 	if (!time_seq)
11975d9e75c4SJan Schmidt 		return eb;
11985d9e75c4SJan Schmidt 
11995d9e75c4SJan Schmidt 	if (btrfs_header_level(eb) == 0)
12005d9e75c4SJan Schmidt 		return eb;
12015d9e75c4SJan Schmidt 
12025d9e75c4SJan Schmidt 	tm = tree_mod_log_search(fs_info, eb->start, time_seq);
12035d9e75c4SJan Schmidt 	if (!tm)
12045d9e75c4SJan Schmidt 		return eb;
12055d9e75c4SJan Schmidt 
12065d9e75c4SJan Schmidt 	if (tm->op == MOD_LOG_KEY_REMOVE_WHILE_FREEING) {
12075d9e75c4SJan Schmidt 		BUG_ON(tm->slot != 0);
12085d9e75c4SJan Schmidt 		eb_rewin = alloc_dummy_extent_buffer(eb->start,
12095d9e75c4SJan Schmidt 						fs_info->tree_root->nodesize);
12105d9e75c4SJan Schmidt 		BUG_ON(!eb_rewin);
12115d9e75c4SJan Schmidt 		btrfs_set_header_bytenr(eb_rewin, eb->start);
12125d9e75c4SJan Schmidt 		btrfs_set_header_backref_rev(eb_rewin,
12135d9e75c4SJan Schmidt 					     btrfs_header_backref_rev(eb));
12145d9e75c4SJan Schmidt 		btrfs_set_header_owner(eb_rewin, btrfs_header_owner(eb));
1215c3193108SJan Schmidt 		btrfs_set_header_level(eb_rewin, btrfs_header_level(eb));
12165d9e75c4SJan Schmidt 	} else {
12175d9e75c4SJan Schmidt 		eb_rewin = btrfs_clone_extent_buffer(eb);
12185d9e75c4SJan Schmidt 		BUG_ON(!eb_rewin);
12195d9e75c4SJan Schmidt 	}
12205d9e75c4SJan Schmidt 
12215d9e75c4SJan Schmidt 	extent_buffer_get(eb_rewin);
12225d9e75c4SJan Schmidt 	free_extent_buffer(eb);
12235d9e75c4SJan Schmidt 
12245d9e75c4SJan Schmidt 	__tree_mod_log_rewind(eb_rewin, time_seq, tm);
122557911b8bSJan Schmidt 	WARN_ON(btrfs_header_nritems(eb_rewin) >
12262a745b14SArne Jansen 		BTRFS_NODEPTRS_PER_BLOCK(fs_info->tree_root));
12275d9e75c4SJan Schmidt 
12285d9e75c4SJan Schmidt 	return eb_rewin;
12295d9e75c4SJan Schmidt }
12305d9e75c4SJan Schmidt 
12318ba97a15SJan Schmidt /*
12328ba97a15SJan Schmidt  * get_old_root() rewinds the state of @root's root node to the given @time_seq
12338ba97a15SJan Schmidt  * value. If there are no changes, the current root->root_node is returned. If
12348ba97a15SJan Schmidt  * anything changed in between, there's a fresh buffer allocated on which the
12358ba97a15SJan Schmidt  * rewind operations are done. In any case, the returned buffer is read locked.
12368ba97a15SJan Schmidt  * Returns NULL on error (with no locks held).
12378ba97a15SJan Schmidt  */
12385d9e75c4SJan Schmidt static inline struct extent_buffer *
12395d9e75c4SJan Schmidt get_old_root(struct btrfs_root *root, u64 time_seq)
12405d9e75c4SJan Schmidt {
12415d9e75c4SJan Schmidt 	struct tree_mod_elem *tm;
12425d9e75c4SJan Schmidt 	struct extent_buffer *eb;
12437bfdcf7fSLiu Bo 	struct extent_buffer *old;
1244a95236d9SJan Schmidt 	struct tree_mod_root *old_root = NULL;
12454325edd0SChris Mason 	u64 old_generation = 0;
1246a95236d9SJan Schmidt 	u64 logical;
1247834328a8SJan Schmidt 	u32 blocksize;
12485d9e75c4SJan Schmidt 
12498ba97a15SJan Schmidt 	eb = btrfs_read_lock_root_node(root);
12505d9e75c4SJan Schmidt 	tm = __tree_mod_log_oldest_root(root->fs_info, root, time_seq);
12515d9e75c4SJan Schmidt 	if (!tm)
12525d9e75c4SJan Schmidt 		return root->node;
12535d9e75c4SJan Schmidt 
1254a95236d9SJan Schmidt 	if (tm->op == MOD_LOG_ROOT_REPLACE) {
12555d9e75c4SJan Schmidt 		old_root = &tm->old_root;
12565d9e75c4SJan Schmidt 		old_generation = tm->generation;
1257a95236d9SJan Schmidt 		logical = old_root->logical;
1258a95236d9SJan Schmidt 	} else {
1259a95236d9SJan Schmidt 		logical = root->node->start;
1260a95236d9SJan Schmidt 	}
12615d9e75c4SJan Schmidt 
1262a95236d9SJan Schmidt 	tm = tree_mod_log_search(root->fs_info, logical, time_seq);
1263834328a8SJan Schmidt 	if (old_root && tm && tm->op != MOD_LOG_KEY_REMOVE_WHILE_FREEING) {
1264834328a8SJan Schmidt 		btrfs_tree_read_unlock(root->node);
1265834328a8SJan Schmidt 		free_extent_buffer(root->node);
1266834328a8SJan Schmidt 		blocksize = btrfs_level_size(root, old_root->level);
12677bfdcf7fSLiu Bo 		old = read_tree_block(root, logical, blocksize, 0);
12687bfdcf7fSLiu Bo 		if (!old) {
1269834328a8SJan Schmidt 			pr_warn("btrfs: failed to read tree block %llu from get_old_root\n",
1270834328a8SJan Schmidt 				logical);
1271834328a8SJan Schmidt 			WARN_ON(1);
1272834328a8SJan Schmidt 		} else {
12737bfdcf7fSLiu Bo 			eb = btrfs_clone_extent_buffer(old);
12747bfdcf7fSLiu Bo 			free_extent_buffer(old);
1275834328a8SJan Schmidt 		}
1276834328a8SJan Schmidt 	} else if (old_root) {
1277834328a8SJan Schmidt 		btrfs_tree_read_unlock(root->node);
1278834328a8SJan Schmidt 		free_extent_buffer(root->node);
127928da9fb4SJan Schmidt 		eb = alloc_dummy_extent_buffer(logical, root->nodesize);
1280834328a8SJan Schmidt 	} else {
1281a95236d9SJan Schmidt 		eb = btrfs_clone_extent_buffer(root->node);
12828ba97a15SJan Schmidt 		btrfs_tree_read_unlock(root->node);
12838ba97a15SJan Schmidt 		free_extent_buffer(root->node);
1284834328a8SJan Schmidt 	}
1285834328a8SJan Schmidt 
12868ba97a15SJan Schmidt 	if (!eb)
12878ba97a15SJan Schmidt 		return NULL;
1288d6381084SJan Schmidt 	extent_buffer_get(eb);
12898ba97a15SJan Schmidt 	btrfs_tree_read_lock(eb);
1290a95236d9SJan Schmidt 	if (old_root) {
12915d9e75c4SJan Schmidt 		btrfs_set_header_bytenr(eb, eb->start);
12925d9e75c4SJan Schmidt 		btrfs_set_header_backref_rev(eb, BTRFS_MIXED_BACKREF_REV);
12935d9e75c4SJan Schmidt 		btrfs_set_header_owner(eb, root->root_key.objectid);
12945d9e75c4SJan Schmidt 		btrfs_set_header_level(eb, old_root->level);
12955d9e75c4SJan Schmidt 		btrfs_set_header_generation(eb, old_generation);
1296a95236d9SJan Schmidt 	}
129728da9fb4SJan Schmidt 	if (tm)
12985d9e75c4SJan Schmidt 		__tree_mod_log_rewind(eb, time_seq, tm);
129928da9fb4SJan Schmidt 	else
130028da9fb4SJan Schmidt 		WARN_ON(btrfs_header_level(eb) != 0);
130157911b8bSJan Schmidt 	WARN_ON(btrfs_header_nritems(eb) > BTRFS_NODEPTRS_PER_BLOCK(root));
13025d9e75c4SJan Schmidt 
13035d9e75c4SJan Schmidt 	return eb;
13045d9e75c4SJan Schmidt }
13055d9e75c4SJan Schmidt 
13065b6602e7SJan Schmidt int btrfs_old_root_level(struct btrfs_root *root, u64 time_seq)
13075b6602e7SJan Schmidt {
13085b6602e7SJan Schmidt 	struct tree_mod_elem *tm;
13095b6602e7SJan Schmidt 	int level;
13105b6602e7SJan Schmidt 
13115b6602e7SJan Schmidt 	tm = __tree_mod_log_oldest_root(root->fs_info, root, time_seq);
13125b6602e7SJan Schmidt 	if (tm && tm->op == MOD_LOG_ROOT_REPLACE) {
13135b6602e7SJan Schmidt 		level = tm->old_root.level;
13145b6602e7SJan Schmidt 	} else {
13155b6602e7SJan Schmidt 		rcu_read_lock();
13165b6602e7SJan Schmidt 		level = btrfs_header_level(root->node);
13175b6602e7SJan Schmidt 		rcu_read_unlock();
13185b6602e7SJan Schmidt 	}
13195b6602e7SJan Schmidt 
13205b6602e7SJan Schmidt 	return level;
13215b6602e7SJan Schmidt }
13225b6602e7SJan Schmidt 
13235d4f98a2SYan Zheng static inline int should_cow_block(struct btrfs_trans_handle *trans,
13245d4f98a2SYan Zheng 				   struct btrfs_root *root,
13255d4f98a2SYan Zheng 				   struct extent_buffer *buf)
13265d4f98a2SYan Zheng {
1327f1ebcc74SLiu Bo 	/* ensure we can see the force_cow */
1328f1ebcc74SLiu Bo 	smp_rmb();
1329f1ebcc74SLiu Bo 
1330f1ebcc74SLiu Bo 	/*
1331f1ebcc74SLiu Bo 	 * We do not need to cow a block if
1332f1ebcc74SLiu Bo 	 * 1) this block is not created or changed in this transaction;
1333f1ebcc74SLiu Bo 	 * 2) this block does not belong to TREE_RELOC tree;
1334f1ebcc74SLiu Bo 	 * 3) the root is not forced COW.
1335f1ebcc74SLiu Bo 	 *
1336f1ebcc74SLiu Bo 	 * What is forced COW:
1337f1ebcc74SLiu Bo 	 *    when we create snapshot during commiting the transaction,
1338f1ebcc74SLiu Bo 	 *    after we've finished coping src root, we must COW the shared
1339f1ebcc74SLiu Bo 	 *    block to ensure the metadata consistency.
1340f1ebcc74SLiu Bo 	 */
13415d4f98a2SYan Zheng 	if (btrfs_header_generation(buf) == trans->transid &&
13425d4f98a2SYan Zheng 	    !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN) &&
13435d4f98a2SYan Zheng 	    !(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
1344f1ebcc74SLiu Bo 	      btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)) &&
1345f1ebcc74SLiu Bo 	    !root->force_cow)
13465d4f98a2SYan Zheng 		return 0;
13475d4f98a2SYan Zheng 	return 1;
13485d4f98a2SYan Zheng }
13495d4f98a2SYan Zheng 
1350d352ac68SChris Mason /*
1351d352ac68SChris Mason  * cows a single block, see __btrfs_cow_block for the real work.
1352d352ac68SChris Mason  * This version of it has extra checks so that a block isn't cow'd more than
1353d352ac68SChris Mason  * once per transaction, as long as it hasn't been written yet
1354d352ac68SChris Mason  */
1355d397712bSChris Mason noinline int btrfs_cow_block(struct btrfs_trans_handle *trans,
13565f39d397SChris Mason 		    struct btrfs_root *root, struct extent_buffer *buf,
13575f39d397SChris Mason 		    struct extent_buffer *parent, int parent_slot,
13589fa8cfe7SChris Mason 		    struct extent_buffer **cow_ret)
135902217ed2SChris Mason {
13606702ed49SChris Mason 	u64 search_start;
1361f510cfecSChris Mason 	int ret;
1362dc17ff8fSChris Mason 
136331b1a2bdSJulia Lawall 	if (trans->transaction != root->fs_info->running_transaction)
136431b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "trans %llu running %llu\n",
1365d397712bSChris Mason 		       (unsigned long long)trans->transid,
1366d397712bSChris Mason 		       (unsigned long long)
1367ccd467d6SChris Mason 		       root->fs_info->running_transaction->transid);
136831b1a2bdSJulia Lawall 
136931b1a2bdSJulia Lawall 	if (trans->transid != root->fs_info->generation)
137031b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "trans %llu running %llu\n",
1371d397712bSChris Mason 		       (unsigned long long)trans->transid,
1372d397712bSChris Mason 		       (unsigned long long)root->fs_info->generation);
1373dc17ff8fSChris Mason 
13745d4f98a2SYan Zheng 	if (!should_cow_block(trans, root, buf)) {
137502217ed2SChris Mason 		*cow_ret = buf;
137602217ed2SChris Mason 		return 0;
137702217ed2SChris Mason 	}
1378c487685dSChris Mason 
13790b86a832SChris Mason 	search_start = buf->start & ~((u64)(1024 * 1024 * 1024) - 1);
1380b4ce94deSChris Mason 
1381b4ce94deSChris Mason 	if (parent)
1382b4ce94deSChris Mason 		btrfs_set_lock_blocking(parent);
1383b4ce94deSChris Mason 	btrfs_set_lock_blocking(buf);
1384b4ce94deSChris Mason 
1385f510cfecSChris Mason 	ret = __btrfs_cow_block(trans, root, buf, parent,
13869fa8cfe7SChris Mason 				 parent_slot, cow_ret, search_start, 0);
13871abe9b8aSliubo 
13881abe9b8aSliubo 	trace_btrfs_cow_block(root, buf, *cow_ret);
13891abe9b8aSliubo 
1390f510cfecSChris Mason 	return ret;
13912c90e5d6SChris Mason }
13926702ed49SChris Mason 
1393d352ac68SChris Mason /*
1394d352ac68SChris Mason  * helper function for defrag to decide if two blocks pointed to by a
1395d352ac68SChris Mason  * node are actually close by
1396d352ac68SChris Mason  */
13976b80053dSChris Mason static int close_blocks(u64 blocknr, u64 other, u32 blocksize)
13986702ed49SChris Mason {
13996b80053dSChris Mason 	if (blocknr < other && other - (blocknr + blocksize) < 32768)
14006702ed49SChris Mason 		return 1;
14016b80053dSChris Mason 	if (blocknr > other && blocknr - (other + blocksize) < 32768)
14026702ed49SChris Mason 		return 1;
140302217ed2SChris Mason 	return 0;
140402217ed2SChris Mason }
140502217ed2SChris Mason 
1406081e9573SChris Mason /*
1407081e9573SChris Mason  * compare two keys in a memcmp fashion
1408081e9573SChris Mason  */
1409081e9573SChris Mason static int comp_keys(struct btrfs_disk_key *disk, struct btrfs_key *k2)
1410081e9573SChris Mason {
1411081e9573SChris Mason 	struct btrfs_key k1;
1412081e9573SChris Mason 
1413081e9573SChris Mason 	btrfs_disk_key_to_cpu(&k1, disk);
1414081e9573SChris Mason 
141520736abaSDiego Calleja 	return btrfs_comp_cpu_keys(&k1, k2);
1416081e9573SChris Mason }
1417081e9573SChris Mason 
1418f3465ca4SJosef Bacik /*
1419f3465ca4SJosef Bacik  * same as comp_keys only with two btrfs_key's
1420f3465ca4SJosef Bacik  */
14215d4f98a2SYan Zheng int btrfs_comp_cpu_keys(struct btrfs_key *k1, struct btrfs_key *k2)
1422f3465ca4SJosef Bacik {
1423f3465ca4SJosef Bacik 	if (k1->objectid > k2->objectid)
1424f3465ca4SJosef Bacik 		return 1;
1425f3465ca4SJosef Bacik 	if (k1->objectid < k2->objectid)
1426f3465ca4SJosef Bacik 		return -1;
1427f3465ca4SJosef Bacik 	if (k1->type > k2->type)
1428f3465ca4SJosef Bacik 		return 1;
1429f3465ca4SJosef Bacik 	if (k1->type < k2->type)
1430f3465ca4SJosef Bacik 		return -1;
1431f3465ca4SJosef Bacik 	if (k1->offset > k2->offset)
1432f3465ca4SJosef Bacik 		return 1;
1433f3465ca4SJosef Bacik 	if (k1->offset < k2->offset)
1434f3465ca4SJosef Bacik 		return -1;
1435f3465ca4SJosef Bacik 	return 0;
1436f3465ca4SJosef Bacik }
1437081e9573SChris Mason 
1438d352ac68SChris Mason /*
1439d352ac68SChris Mason  * this is used by the defrag code to go through all the
1440d352ac68SChris Mason  * leaves pointed to by a node and reallocate them so that
1441d352ac68SChris Mason  * disk order is close to key order
1442d352ac68SChris Mason  */
14436702ed49SChris Mason int btrfs_realloc_node(struct btrfs_trans_handle *trans,
14445f39d397SChris Mason 		       struct btrfs_root *root, struct extent_buffer *parent,
1445a6b6e75eSChris Mason 		       int start_slot, int cache_only, u64 *last_ret,
1446a6b6e75eSChris Mason 		       struct btrfs_key *progress)
14476702ed49SChris Mason {
14486b80053dSChris Mason 	struct extent_buffer *cur;
14496702ed49SChris Mason 	u64 blocknr;
1450ca7a79adSChris Mason 	u64 gen;
1451e9d0b13bSChris Mason 	u64 search_start = *last_ret;
1452e9d0b13bSChris Mason 	u64 last_block = 0;
14536702ed49SChris Mason 	u64 other;
14546702ed49SChris Mason 	u32 parent_nritems;
14556702ed49SChris Mason 	int end_slot;
14566702ed49SChris Mason 	int i;
14576702ed49SChris Mason 	int err = 0;
1458f2183bdeSChris Mason 	int parent_level;
14596b80053dSChris Mason 	int uptodate;
14606b80053dSChris Mason 	u32 blocksize;
1461081e9573SChris Mason 	int progress_passed = 0;
1462081e9573SChris Mason 	struct btrfs_disk_key disk_key;
14636702ed49SChris Mason 
14645708b959SChris Mason 	parent_level = btrfs_header_level(parent);
14655708b959SChris Mason 	if (cache_only && parent_level != 1)
14665708b959SChris Mason 		return 0;
14675708b959SChris Mason 
14686c1500f2SJulia Lawall 	WARN_ON(trans->transaction != root->fs_info->running_transaction);
14696c1500f2SJulia Lawall 	WARN_ON(trans->transid != root->fs_info->generation);
147086479a04SChris Mason 
14716b80053dSChris Mason 	parent_nritems = btrfs_header_nritems(parent);
14726b80053dSChris Mason 	blocksize = btrfs_level_size(root, parent_level - 1);
14736702ed49SChris Mason 	end_slot = parent_nritems;
14746702ed49SChris Mason 
14756702ed49SChris Mason 	if (parent_nritems == 1)
14766702ed49SChris Mason 		return 0;
14776702ed49SChris Mason 
1478b4ce94deSChris Mason 	btrfs_set_lock_blocking(parent);
1479b4ce94deSChris Mason 
14806702ed49SChris Mason 	for (i = start_slot; i < end_slot; i++) {
14816702ed49SChris Mason 		int close = 1;
1482a6b6e75eSChris Mason 
1483081e9573SChris Mason 		btrfs_node_key(parent, &disk_key, i);
1484081e9573SChris Mason 		if (!progress_passed && comp_keys(&disk_key, progress) < 0)
1485081e9573SChris Mason 			continue;
1486081e9573SChris Mason 
1487081e9573SChris Mason 		progress_passed = 1;
14886b80053dSChris Mason 		blocknr = btrfs_node_blockptr(parent, i);
1489ca7a79adSChris Mason 		gen = btrfs_node_ptr_generation(parent, i);
1490e9d0b13bSChris Mason 		if (last_block == 0)
1491e9d0b13bSChris Mason 			last_block = blocknr;
14925708b959SChris Mason 
14936702ed49SChris Mason 		if (i > 0) {
14946b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i - 1);
14956b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
14966702ed49SChris Mason 		}
14970ef3e66bSChris Mason 		if (!close && i < end_slot - 2) {
14986b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i + 1);
14996b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
15006702ed49SChris Mason 		}
1501e9d0b13bSChris Mason 		if (close) {
1502e9d0b13bSChris Mason 			last_block = blocknr;
15036702ed49SChris Mason 			continue;
1504e9d0b13bSChris Mason 		}
15056702ed49SChris Mason 
15066b80053dSChris Mason 		cur = btrfs_find_tree_block(root, blocknr, blocksize);
15076b80053dSChris Mason 		if (cur)
1508b9fab919SChris Mason 			uptodate = btrfs_buffer_uptodate(cur, gen, 0);
15096b80053dSChris Mason 		else
15106b80053dSChris Mason 			uptodate = 0;
15115708b959SChris Mason 		if (!cur || !uptodate) {
15126702ed49SChris Mason 			if (cache_only) {
15136b80053dSChris Mason 				free_extent_buffer(cur);
15146702ed49SChris Mason 				continue;
15156702ed49SChris Mason 			}
15166b80053dSChris Mason 			if (!cur) {
15176b80053dSChris Mason 				cur = read_tree_block(root, blocknr,
1518ca7a79adSChris Mason 							 blocksize, gen);
151997d9a8a4STsutomu Itoh 				if (!cur)
152097d9a8a4STsutomu Itoh 					return -EIO;
15216b80053dSChris Mason 			} else if (!uptodate) {
1522018642a1STsutomu Itoh 				err = btrfs_read_buffer(cur, gen);
1523018642a1STsutomu Itoh 				if (err) {
1524018642a1STsutomu Itoh 					free_extent_buffer(cur);
1525018642a1STsutomu Itoh 					return err;
1526018642a1STsutomu Itoh 				}
15276702ed49SChris Mason 			}
1528f2183bdeSChris Mason 		}
1529e9d0b13bSChris Mason 		if (search_start == 0)
15306b80053dSChris Mason 			search_start = last_block;
1531e9d0b13bSChris Mason 
1532e7a84565SChris Mason 		btrfs_tree_lock(cur);
1533b4ce94deSChris Mason 		btrfs_set_lock_blocking(cur);
15346b80053dSChris Mason 		err = __btrfs_cow_block(trans, root, cur, parent, i,
1535e7a84565SChris Mason 					&cur, search_start,
15366b80053dSChris Mason 					min(16 * blocksize,
15379fa8cfe7SChris Mason 					    (end_slot - i) * blocksize));
1538252c38f0SYan 		if (err) {
1539e7a84565SChris Mason 			btrfs_tree_unlock(cur);
15406b80053dSChris Mason 			free_extent_buffer(cur);
15416702ed49SChris Mason 			break;
1542252c38f0SYan 		}
1543e7a84565SChris Mason 		search_start = cur->start;
1544e7a84565SChris Mason 		last_block = cur->start;
1545f2183bdeSChris Mason 		*last_ret = search_start;
1546e7a84565SChris Mason 		btrfs_tree_unlock(cur);
1547e7a84565SChris Mason 		free_extent_buffer(cur);
15486702ed49SChris Mason 	}
15496702ed49SChris Mason 	return err;
15506702ed49SChris Mason }
15516702ed49SChris Mason 
155274123bd7SChris Mason /*
155374123bd7SChris Mason  * The leaf data grows from end-to-front in the node.
155474123bd7SChris Mason  * this returns the address of the start of the last item,
155574123bd7SChris Mason  * which is the stop of the leaf data stack
155674123bd7SChris Mason  */
1557123abc88SChris Mason static inline unsigned int leaf_data_end(struct btrfs_root *root,
15585f39d397SChris Mason 					 struct extent_buffer *leaf)
1559be0e5c09SChris Mason {
15605f39d397SChris Mason 	u32 nr = btrfs_header_nritems(leaf);
1561be0e5c09SChris Mason 	if (nr == 0)
1562123abc88SChris Mason 		return BTRFS_LEAF_DATA_SIZE(root);
15635f39d397SChris Mason 	return btrfs_item_offset_nr(leaf, nr - 1);
1564be0e5c09SChris Mason }
1565be0e5c09SChris Mason 
1566aa5d6bedSChris Mason 
156774123bd7SChris Mason /*
15685f39d397SChris Mason  * search for key in the extent_buffer.  The items start at offset p,
15695f39d397SChris Mason  * and they are item_size apart.  There are 'max' items in p.
15705f39d397SChris Mason  *
157174123bd7SChris Mason  * the slot in the array is returned via slot, and it points to
157274123bd7SChris Mason  * the place where you would insert key if it is not found in
157374123bd7SChris Mason  * the array.
157474123bd7SChris Mason  *
157574123bd7SChris Mason  * slot may point to max if the key is bigger than all of the keys
157674123bd7SChris Mason  */
1577e02119d5SChris Mason static noinline int generic_bin_search(struct extent_buffer *eb,
1578e02119d5SChris Mason 				       unsigned long p,
15795f39d397SChris Mason 				       int item_size, struct btrfs_key *key,
1580be0e5c09SChris Mason 				       int max, int *slot)
1581be0e5c09SChris Mason {
1582be0e5c09SChris Mason 	int low = 0;
1583be0e5c09SChris Mason 	int high = max;
1584be0e5c09SChris Mason 	int mid;
1585be0e5c09SChris Mason 	int ret;
1586479965d6SChris Mason 	struct btrfs_disk_key *tmp = NULL;
15875f39d397SChris Mason 	struct btrfs_disk_key unaligned;
15885f39d397SChris Mason 	unsigned long offset;
15895f39d397SChris Mason 	char *kaddr = NULL;
15905f39d397SChris Mason 	unsigned long map_start = 0;
15915f39d397SChris Mason 	unsigned long map_len = 0;
1592479965d6SChris Mason 	int err;
1593be0e5c09SChris Mason 
1594be0e5c09SChris Mason 	while (low < high) {
1595be0e5c09SChris Mason 		mid = (low + high) / 2;
15965f39d397SChris Mason 		offset = p + mid * item_size;
15975f39d397SChris Mason 
1598a6591715SChris Mason 		if (!kaddr || offset < map_start ||
15995f39d397SChris Mason 		    (offset + sizeof(struct btrfs_disk_key)) >
16005f39d397SChris Mason 		    map_start + map_len) {
1601934d375bSChris Mason 
1602934d375bSChris Mason 			err = map_private_extent_buffer(eb, offset,
1603479965d6SChris Mason 						sizeof(struct btrfs_disk_key),
1604a6591715SChris Mason 						&kaddr, &map_start, &map_len);
16055f39d397SChris Mason 
1606479965d6SChris Mason 			if (!err) {
1607479965d6SChris Mason 				tmp = (struct btrfs_disk_key *)(kaddr + offset -
1608479965d6SChris Mason 							map_start);
1609479965d6SChris Mason 			} else {
16105f39d397SChris Mason 				read_extent_buffer(eb, &unaligned,
16115f39d397SChris Mason 						   offset, sizeof(unaligned));
16125f39d397SChris Mason 				tmp = &unaligned;
1613479965d6SChris Mason 			}
1614479965d6SChris Mason 
16155f39d397SChris Mason 		} else {
16165f39d397SChris Mason 			tmp = (struct btrfs_disk_key *)(kaddr + offset -
16175f39d397SChris Mason 							map_start);
16185f39d397SChris Mason 		}
1619be0e5c09SChris Mason 		ret = comp_keys(tmp, key);
1620be0e5c09SChris Mason 
1621be0e5c09SChris Mason 		if (ret < 0)
1622be0e5c09SChris Mason 			low = mid + 1;
1623be0e5c09SChris Mason 		else if (ret > 0)
1624be0e5c09SChris Mason 			high = mid;
1625be0e5c09SChris Mason 		else {
1626be0e5c09SChris Mason 			*slot = mid;
1627be0e5c09SChris Mason 			return 0;
1628be0e5c09SChris Mason 		}
1629be0e5c09SChris Mason 	}
1630be0e5c09SChris Mason 	*slot = low;
1631be0e5c09SChris Mason 	return 1;
1632be0e5c09SChris Mason }
1633be0e5c09SChris Mason 
163497571fd0SChris Mason /*
163597571fd0SChris Mason  * simple bin_search frontend that does the right thing for
163697571fd0SChris Mason  * leaves vs nodes
163797571fd0SChris Mason  */
16385f39d397SChris Mason static int bin_search(struct extent_buffer *eb, struct btrfs_key *key,
16395f39d397SChris Mason 		      int level, int *slot)
1640be0e5c09SChris Mason {
1641f775738fSWang Sheng-Hui 	if (level == 0)
16425f39d397SChris Mason 		return generic_bin_search(eb,
16435f39d397SChris Mason 					  offsetof(struct btrfs_leaf, items),
16440783fcfcSChris Mason 					  sizeof(struct btrfs_item),
16455f39d397SChris Mason 					  key, btrfs_header_nritems(eb),
16467518a238SChris Mason 					  slot);
1647f775738fSWang Sheng-Hui 	else
16485f39d397SChris Mason 		return generic_bin_search(eb,
16495f39d397SChris Mason 					  offsetof(struct btrfs_node, ptrs),
1650123abc88SChris Mason 					  sizeof(struct btrfs_key_ptr),
16515f39d397SChris Mason 					  key, btrfs_header_nritems(eb),
16527518a238SChris Mason 					  slot);
1653be0e5c09SChris Mason }
1654be0e5c09SChris Mason 
16555d4f98a2SYan Zheng int btrfs_bin_search(struct extent_buffer *eb, struct btrfs_key *key,
16565d4f98a2SYan Zheng 		     int level, int *slot)
16575d4f98a2SYan Zheng {
16585d4f98a2SYan Zheng 	return bin_search(eb, key, level, slot);
16595d4f98a2SYan Zheng }
16605d4f98a2SYan Zheng 
1661f0486c68SYan, Zheng static void root_add_used(struct btrfs_root *root, u32 size)
1662f0486c68SYan, Zheng {
1663f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
1664f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
1665f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) + size);
1666f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
1667f0486c68SYan, Zheng }
1668f0486c68SYan, Zheng 
1669f0486c68SYan, Zheng static void root_sub_used(struct btrfs_root *root, u32 size)
1670f0486c68SYan, Zheng {
1671f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
1672f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
1673f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) - size);
1674f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
1675f0486c68SYan, Zheng }
1676f0486c68SYan, Zheng 
1677d352ac68SChris Mason /* given a node and slot number, this reads the blocks it points to.  The
1678d352ac68SChris Mason  * extent buffer is returned with a reference taken (but unlocked).
1679d352ac68SChris Mason  * NULL is returned on error.
1680d352ac68SChris Mason  */
1681e02119d5SChris Mason static noinline struct extent_buffer *read_node_slot(struct btrfs_root *root,
16825f39d397SChris Mason 				   struct extent_buffer *parent, int slot)
1683bb803951SChris Mason {
1684ca7a79adSChris Mason 	int level = btrfs_header_level(parent);
1685bb803951SChris Mason 	if (slot < 0)
1686bb803951SChris Mason 		return NULL;
16875f39d397SChris Mason 	if (slot >= btrfs_header_nritems(parent))
1688bb803951SChris Mason 		return NULL;
1689ca7a79adSChris Mason 
1690ca7a79adSChris Mason 	BUG_ON(level == 0);
1691ca7a79adSChris Mason 
1692db94535dSChris Mason 	return read_tree_block(root, btrfs_node_blockptr(parent, slot),
1693ca7a79adSChris Mason 		       btrfs_level_size(root, level - 1),
1694ca7a79adSChris Mason 		       btrfs_node_ptr_generation(parent, slot));
1695bb803951SChris Mason }
1696bb803951SChris Mason 
1697d352ac68SChris Mason /*
1698d352ac68SChris Mason  * node level balancing, used to make sure nodes are in proper order for
1699d352ac68SChris Mason  * item deletion.  We balance from the top down, so we have to make sure
1700d352ac68SChris Mason  * that a deletion won't leave an node completely empty later on.
1701d352ac68SChris Mason  */
1702e02119d5SChris Mason static noinline int balance_level(struct btrfs_trans_handle *trans,
170398ed5174SChris Mason 			 struct btrfs_root *root,
170498ed5174SChris Mason 			 struct btrfs_path *path, int level)
1705bb803951SChris Mason {
17065f39d397SChris Mason 	struct extent_buffer *right = NULL;
17075f39d397SChris Mason 	struct extent_buffer *mid;
17085f39d397SChris Mason 	struct extent_buffer *left = NULL;
17095f39d397SChris Mason 	struct extent_buffer *parent = NULL;
1710bb803951SChris Mason 	int ret = 0;
1711bb803951SChris Mason 	int wret;
1712bb803951SChris Mason 	int pslot;
1713bb803951SChris Mason 	int orig_slot = path->slots[level];
171479f95c82SChris Mason 	u64 orig_ptr;
1715bb803951SChris Mason 
1716bb803951SChris Mason 	if (level == 0)
1717bb803951SChris Mason 		return 0;
1718bb803951SChris Mason 
17195f39d397SChris Mason 	mid = path->nodes[level];
1720b4ce94deSChris Mason 
1721bd681513SChris Mason 	WARN_ON(path->locks[level] != BTRFS_WRITE_LOCK &&
1722bd681513SChris Mason 		path->locks[level] != BTRFS_WRITE_LOCK_BLOCKING);
17237bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
17247bb86316SChris Mason 
17251d4f8a0cSChris Mason 	orig_ptr = btrfs_node_blockptr(mid, orig_slot);
172679f95c82SChris Mason 
1727a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
17285f39d397SChris Mason 		parent = path->nodes[level + 1];
1729bb803951SChris Mason 		pslot = path->slots[level + 1];
1730a05a9bb1SLi Zefan 	}
1731bb803951SChris Mason 
173240689478SChris Mason 	/*
173340689478SChris Mason 	 * deal with the case where there is only one pointer in the root
173440689478SChris Mason 	 * by promoting the node below to a root
173540689478SChris Mason 	 */
17365f39d397SChris Mason 	if (!parent) {
17375f39d397SChris Mason 		struct extent_buffer *child;
1738bb803951SChris Mason 
17395f39d397SChris Mason 		if (btrfs_header_nritems(mid) != 1)
1740bb803951SChris Mason 			return 0;
1741bb803951SChris Mason 
1742bb803951SChris Mason 		/* promote the child to a root */
17435f39d397SChris Mason 		child = read_node_slot(root, mid, 0);
1744305a26afSMark Fasheh 		if (!child) {
1745305a26afSMark Fasheh 			ret = -EROFS;
1746305a26afSMark Fasheh 			btrfs_std_error(root->fs_info, ret);
1747305a26afSMark Fasheh 			goto enospc;
1748305a26afSMark Fasheh 		}
1749305a26afSMark Fasheh 
1750925baeddSChris Mason 		btrfs_tree_lock(child);
1751b4ce94deSChris Mason 		btrfs_set_lock_blocking(child);
17529fa8cfe7SChris Mason 		ret = btrfs_cow_block(trans, root, child, mid, 0, &child);
1753f0486c68SYan, Zheng 		if (ret) {
1754f0486c68SYan, Zheng 			btrfs_tree_unlock(child);
1755f0486c68SYan, Zheng 			free_extent_buffer(child);
1756f0486c68SYan, Zheng 			goto enospc;
1757f0486c68SYan, Zheng 		}
17582f375ab9SYan 
1759ba1bfbd5SJan Schmidt 		tree_mod_log_free_eb(root->fs_info, root->node);
1760f230475eSJan Schmidt 		tree_mod_log_set_root_pointer(root, child);
1761240f62c8SChris Mason 		rcu_assign_pointer(root->node, child);
1762925baeddSChris Mason 
17630b86a832SChris Mason 		add_root_to_dirty_list(root);
1764925baeddSChris Mason 		btrfs_tree_unlock(child);
1765b4ce94deSChris Mason 
1766925baeddSChris Mason 		path->locks[level] = 0;
1767bb803951SChris Mason 		path->nodes[level] = NULL;
17685f39d397SChris Mason 		clean_tree_block(trans, root, mid);
1769925baeddSChris Mason 		btrfs_tree_unlock(mid);
1770bb803951SChris Mason 		/* once for the path */
17715f39d397SChris Mason 		free_extent_buffer(mid);
1772f0486c68SYan, Zheng 
1773f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
17745581a51aSJan Schmidt 		btrfs_free_tree_block(trans, root, mid, 0, 1);
1775bb803951SChris Mason 		/* once for the root ptr */
17763083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
1777f0486c68SYan, Zheng 		return 0;
1778bb803951SChris Mason 	}
17795f39d397SChris Mason 	if (btrfs_header_nritems(mid) >
1780123abc88SChris Mason 	    BTRFS_NODEPTRS_PER_BLOCK(root) / 4)
1781bb803951SChris Mason 		return 0;
1782bb803951SChris Mason 
17835f39d397SChris Mason 	left = read_node_slot(root, parent, pslot - 1);
17845f39d397SChris Mason 	if (left) {
1785925baeddSChris Mason 		btrfs_tree_lock(left);
1786b4ce94deSChris Mason 		btrfs_set_lock_blocking(left);
17875f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, left,
17889fa8cfe7SChris Mason 				       parent, pslot - 1, &left);
178954aa1f4dSChris Mason 		if (wret) {
179054aa1f4dSChris Mason 			ret = wret;
179154aa1f4dSChris Mason 			goto enospc;
179254aa1f4dSChris Mason 		}
17932cc58cf2SChris Mason 	}
17945f39d397SChris Mason 	right = read_node_slot(root, parent, pslot + 1);
17955f39d397SChris Mason 	if (right) {
1796925baeddSChris Mason 		btrfs_tree_lock(right);
1797b4ce94deSChris Mason 		btrfs_set_lock_blocking(right);
17985f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, right,
17999fa8cfe7SChris Mason 				       parent, pslot + 1, &right);
18002cc58cf2SChris Mason 		if (wret) {
18012cc58cf2SChris Mason 			ret = wret;
18022cc58cf2SChris Mason 			goto enospc;
18032cc58cf2SChris Mason 		}
18042cc58cf2SChris Mason 	}
18052cc58cf2SChris Mason 
18062cc58cf2SChris Mason 	/* first, try to make some room in the middle buffer */
18075f39d397SChris Mason 	if (left) {
18085f39d397SChris Mason 		orig_slot += btrfs_header_nritems(left);
1809bce4eae9SChris Mason 		wret = push_node_left(trans, root, left, mid, 1);
181079f95c82SChris Mason 		if (wret < 0)
181179f95c82SChris Mason 			ret = wret;
1812bb803951SChris Mason 	}
181379f95c82SChris Mason 
181479f95c82SChris Mason 	/*
181579f95c82SChris Mason 	 * then try to empty the right most buffer into the middle
181679f95c82SChris Mason 	 */
18175f39d397SChris Mason 	if (right) {
1818971a1f66SChris Mason 		wret = push_node_left(trans, root, mid, right, 1);
181954aa1f4dSChris Mason 		if (wret < 0 && wret != -ENOSPC)
182079f95c82SChris Mason 			ret = wret;
18215f39d397SChris Mason 		if (btrfs_header_nritems(right) == 0) {
18225f39d397SChris Mason 			clean_tree_block(trans, root, right);
1823925baeddSChris Mason 			btrfs_tree_unlock(right);
18240e411eceSLiu Bo 			del_ptr(trans, root, path, level + 1, pslot + 1);
1825f0486c68SYan, Zheng 			root_sub_used(root, right->len);
18265581a51aSJan Schmidt 			btrfs_free_tree_block(trans, root, right, 0, 1);
18273083ee2eSJosef Bacik 			free_extent_buffer_stale(right);
1828f0486c68SYan, Zheng 			right = NULL;
1829bb803951SChris Mason 		} else {
18305f39d397SChris Mason 			struct btrfs_disk_key right_key;
18315f39d397SChris Mason 			btrfs_node_key(right, &right_key, 0);
1832f230475eSJan Schmidt 			tree_mod_log_set_node_key(root->fs_info, parent,
183332adf090SLiu Bo 						  pslot + 1, 0);
18345f39d397SChris Mason 			btrfs_set_node_key(parent, &right_key, pslot + 1);
18355f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
1836bb803951SChris Mason 		}
1837bb803951SChris Mason 	}
18385f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 1) {
183979f95c82SChris Mason 		/*
184079f95c82SChris Mason 		 * we're not allowed to leave a node with one item in the
184179f95c82SChris Mason 		 * tree during a delete.  A deletion from lower in the tree
184279f95c82SChris Mason 		 * could try to delete the only pointer in this node.
184379f95c82SChris Mason 		 * So, pull some keys from the left.
184479f95c82SChris Mason 		 * There has to be a left pointer at this point because
184579f95c82SChris Mason 		 * otherwise we would have pulled some pointers from the
184679f95c82SChris Mason 		 * right
184779f95c82SChris Mason 		 */
1848305a26afSMark Fasheh 		if (!left) {
1849305a26afSMark Fasheh 			ret = -EROFS;
1850305a26afSMark Fasheh 			btrfs_std_error(root->fs_info, ret);
1851305a26afSMark Fasheh 			goto enospc;
1852305a26afSMark Fasheh 		}
18535f39d397SChris Mason 		wret = balance_node_right(trans, root, mid, left);
185454aa1f4dSChris Mason 		if (wret < 0) {
185579f95c82SChris Mason 			ret = wret;
185654aa1f4dSChris Mason 			goto enospc;
185754aa1f4dSChris Mason 		}
1858bce4eae9SChris Mason 		if (wret == 1) {
1859bce4eae9SChris Mason 			wret = push_node_left(trans, root, left, mid, 1);
1860bce4eae9SChris Mason 			if (wret < 0)
1861bce4eae9SChris Mason 				ret = wret;
1862bce4eae9SChris Mason 		}
186379f95c82SChris Mason 		BUG_ON(wret == 1);
186479f95c82SChris Mason 	}
18655f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 0) {
18665f39d397SChris Mason 		clean_tree_block(trans, root, mid);
1867925baeddSChris Mason 		btrfs_tree_unlock(mid);
18680e411eceSLiu Bo 		del_ptr(trans, root, path, level + 1, pslot);
1869f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
18705581a51aSJan Schmidt 		btrfs_free_tree_block(trans, root, mid, 0, 1);
18713083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
1872f0486c68SYan, Zheng 		mid = NULL;
187379f95c82SChris Mason 	} else {
187479f95c82SChris Mason 		/* update the parent key to reflect our changes */
18755f39d397SChris Mason 		struct btrfs_disk_key mid_key;
18765f39d397SChris Mason 		btrfs_node_key(mid, &mid_key, 0);
187732adf090SLiu Bo 		tree_mod_log_set_node_key(root->fs_info, parent,
1878f230475eSJan Schmidt 					  pslot, 0);
18795f39d397SChris Mason 		btrfs_set_node_key(parent, &mid_key, pslot);
18805f39d397SChris Mason 		btrfs_mark_buffer_dirty(parent);
188179f95c82SChris Mason 	}
1882bb803951SChris Mason 
188379f95c82SChris Mason 	/* update the path */
18845f39d397SChris Mason 	if (left) {
18855f39d397SChris Mason 		if (btrfs_header_nritems(left) > orig_slot) {
18865f39d397SChris Mason 			extent_buffer_get(left);
1887925baeddSChris Mason 			/* left was locked after cow */
18885f39d397SChris Mason 			path->nodes[level] = left;
1889bb803951SChris Mason 			path->slots[level + 1] -= 1;
1890bb803951SChris Mason 			path->slots[level] = orig_slot;
1891925baeddSChris Mason 			if (mid) {
1892925baeddSChris Mason 				btrfs_tree_unlock(mid);
18935f39d397SChris Mason 				free_extent_buffer(mid);
1894925baeddSChris Mason 			}
1895bb803951SChris Mason 		} else {
18965f39d397SChris Mason 			orig_slot -= btrfs_header_nritems(left);
1897bb803951SChris Mason 			path->slots[level] = orig_slot;
1898bb803951SChris Mason 		}
1899bb803951SChris Mason 	}
190079f95c82SChris Mason 	/* double check we haven't messed things up */
1901e20d96d6SChris Mason 	if (orig_ptr !=
19025f39d397SChris Mason 	    btrfs_node_blockptr(path->nodes[level], path->slots[level]))
190379f95c82SChris Mason 		BUG();
190454aa1f4dSChris Mason enospc:
1905925baeddSChris Mason 	if (right) {
1906925baeddSChris Mason 		btrfs_tree_unlock(right);
19075f39d397SChris Mason 		free_extent_buffer(right);
1908925baeddSChris Mason 	}
1909925baeddSChris Mason 	if (left) {
1910925baeddSChris Mason 		if (path->nodes[level] != left)
1911925baeddSChris Mason 			btrfs_tree_unlock(left);
19125f39d397SChris Mason 		free_extent_buffer(left);
1913925baeddSChris Mason 	}
1914bb803951SChris Mason 	return ret;
1915bb803951SChris Mason }
1916bb803951SChris Mason 
1917d352ac68SChris Mason /* Node balancing for insertion.  Here we only split or push nodes around
1918d352ac68SChris Mason  * when they are completely full.  This is also done top down, so we
1919d352ac68SChris Mason  * have to be pessimistic.
1920d352ac68SChris Mason  */
1921d397712bSChris Mason static noinline int push_nodes_for_insert(struct btrfs_trans_handle *trans,
1922e66f709bSChris Mason 					  struct btrfs_root *root,
1923e66f709bSChris Mason 					  struct btrfs_path *path, int level)
1924e66f709bSChris Mason {
19255f39d397SChris Mason 	struct extent_buffer *right = NULL;
19265f39d397SChris Mason 	struct extent_buffer *mid;
19275f39d397SChris Mason 	struct extent_buffer *left = NULL;
19285f39d397SChris Mason 	struct extent_buffer *parent = NULL;
1929e66f709bSChris Mason 	int ret = 0;
1930e66f709bSChris Mason 	int wret;
1931e66f709bSChris Mason 	int pslot;
1932e66f709bSChris Mason 	int orig_slot = path->slots[level];
1933e66f709bSChris Mason 
1934e66f709bSChris Mason 	if (level == 0)
1935e66f709bSChris Mason 		return 1;
1936e66f709bSChris Mason 
19375f39d397SChris Mason 	mid = path->nodes[level];
19387bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
1939e66f709bSChris Mason 
1940a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
19415f39d397SChris Mason 		parent = path->nodes[level + 1];
1942e66f709bSChris Mason 		pslot = path->slots[level + 1];
1943a05a9bb1SLi Zefan 	}
1944e66f709bSChris Mason 
19455f39d397SChris Mason 	if (!parent)
1946e66f709bSChris Mason 		return 1;
1947e66f709bSChris Mason 
19485f39d397SChris Mason 	left = read_node_slot(root, parent, pslot - 1);
1949e66f709bSChris Mason 
1950e66f709bSChris Mason 	/* first, try to make some room in the middle buffer */
19515f39d397SChris Mason 	if (left) {
1952e66f709bSChris Mason 		u32 left_nr;
1953925baeddSChris Mason 
1954925baeddSChris Mason 		btrfs_tree_lock(left);
1955b4ce94deSChris Mason 		btrfs_set_lock_blocking(left);
1956b4ce94deSChris Mason 
19575f39d397SChris Mason 		left_nr = btrfs_header_nritems(left);
195833ade1f8SChris Mason 		if (left_nr >= BTRFS_NODEPTRS_PER_BLOCK(root) - 1) {
195933ade1f8SChris Mason 			wret = 1;
196033ade1f8SChris Mason 		} else {
19615f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, left, parent,
19629fa8cfe7SChris Mason 					      pslot - 1, &left);
196354aa1f4dSChris Mason 			if (ret)
196454aa1f4dSChris Mason 				wret = 1;
196554aa1f4dSChris Mason 			else {
196654aa1f4dSChris Mason 				wret = push_node_left(trans, root,
1967971a1f66SChris Mason 						      left, mid, 0);
196854aa1f4dSChris Mason 			}
196933ade1f8SChris Mason 		}
1970e66f709bSChris Mason 		if (wret < 0)
1971e66f709bSChris Mason 			ret = wret;
1972e66f709bSChris Mason 		if (wret == 0) {
19735f39d397SChris Mason 			struct btrfs_disk_key disk_key;
1974e66f709bSChris Mason 			orig_slot += left_nr;
19755f39d397SChris Mason 			btrfs_node_key(mid, &disk_key, 0);
1976f230475eSJan Schmidt 			tree_mod_log_set_node_key(root->fs_info, parent,
197732adf090SLiu Bo 						  pslot, 0);
19785f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot);
19795f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
19805f39d397SChris Mason 			if (btrfs_header_nritems(left) > orig_slot) {
19815f39d397SChris Mason 				path->nodes[level] = left;
1982e66f709bSChris Mason 				path->slots[level + 1] -= 1;
1983e66f709bSChris Mason 				path->slots[level] = orig_slot;
1984925baeddSChris Mason 				btrfs_tree_unlock(mid);
19855f39d397SChris Mason 				free_extent_buffer(mid);
1986e66f709bSChris Mason 			} else {
1987e66f709bSChris Mason 				orig_slot -=
19885f39d397SChris Mason 					btrfs_header_nritems(left);
1989e66f709bSChris Mason 				path->slots[level] = orig_slot;
1990925baeddSChris Mason 				btrfs_tree_unlock(left);
19915f39d397SChris Mason 				free_extent_buffer(left);
1992e66f709bSChris Mason 			}
1993e66f709bSChris Mason 			return 0;
1994e66f709bSChris Mason 		}
1995925baeddSChris Mason 		btrfs_tree_unlock(left);
19965f39d397SChris Mason 		free_extent_buffer(left);
1997e66f709bSChris Mason 	}
19985f39d397SChris Mason 	right = read_node_slot(root, parent, pslot + 1);
1999e66f709bSChris Mason 
2000e66f709bSChris Mason 	/*
2001e66f709bSChris Mason 	 * then try to empty the right most buffer into the middle
2002e66f709bSChris Mason 	 */
20035f39d397SChris Mason 	if (right) {
200433ade1f8SChris Mason 		u32 right_nr;
2005b4ce94deSChris Mason 
2006925baeddSChris Mason 		btrfs_tree_lock(right);
2007b4ce94deSChris Mason 		btrfs_set_lock_blocking(right);
2008b4ce94deSChris Mason 
20095f39d397SChris Mason 		right_nr = btrfs_header_nritems(right);
201033ade1f8SChris Mason 		if (right_nr >= BTRFS_NODEPTRS_PER_BLOCK(root) - 1) {
201133ade1f8SChris Mason 			wret = 1;
201233ade1f8SChris Mason 		} else {
20135f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, right,
20145f39d397SChris Mason 					      parent, pslot + 1,
20159fa8cfe7SChris Mason 					      &right);
201654aa1f4dSChris Mason 			if (ret)
201754aa1f4dSChris Mason 				wret = 1;
201854aa1f4dSChris Mason 			else {
201933ade1f8SChris Mason 				wret = balance_node_right(trans, root,
20205f39d397SChris Mason 							  right, mid);
202133ade1f8SChris Mason 			}
202254aa1f4dSChris Mason 		}
2023e66f709bSChris Mason 		if (wret < 0)
2024e66f709bSChris Mason 			ret = wret;
2025e66f709bSChris Mason 		if (wret == 0) {
20265f39d397SChris Mason 			struct btrfs_disk_key disk_key;
20275f39d397SChris Mason 
20285f39d397SChris Mason 			btrfs_node_key(right, &disk_key, 0);
2029f230475eSJan Schmidt 			tree_mod_log_set_node_key(root->fs_info, parent,
203032adf090SLiu Bo 						  pslot + 1, 0);
20315f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot + 1);
20325f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
20335f39d397SChris Mason 
20345f39d397SChris Mason 			if (btrfs_header_nritems(mid) <= orig_slot) {
20355f39d397SChris Mason 				path->nodes[level] = right;
2036e66f709bSChris Mason 				path->slots[level + 1] += 1;
2037e66f709bSChris Mason 				path->slots[level] = orig_slot -
20385f39d397SChris Mason 					btrfs_header_nritems(mid);
2039925baeddSChris Mason 				btrfs_tree_unlock(mid);
20405f39d397SChris Mason 				free_extent_buffer(mid);
2041e66f709bSChris Mason 			} else {
2042925baeddSChris Mason 				btrfs_tree_unlock(right);
20435f39d397SChris Mason 				free_extent_buffer(right);
2044e66f709bSChris Mason 			}
2045e66f709bSChris Mason 			return 0;
2046e66f709bSChris Mason 		}
2047925baeddSChris Mason 		btrfs_tree_unlock(right);
20485f39d397SChris Mason 		free_extent_buffer(right);
2049e66f709bSChris Mason 	}
2050e66f709bSChris Mason 	return 1;
2051e66f709bSChris Mason }
2052e66f709bSChris Mason 
205374123bd7SChris Mason /*
2054d352ac68SChris Mason  * readahead one full node of leaves, finding things that are close
2055d352ac68SChris Mason  * to the block in 'slot', and triggering ra on them.
20563c69faecSChris Mason  */
2057c8c42864SChris Mason static void reada_for_search(struct btrfs_root *root,
2058e02119d5SChris Mason 			     struct btrfs_path *path,
205901f46658SChris Mason 			     int level, int slot, u64 objectid)
20603c69faecSChris Mason {
20615f39d397SChris Mason 	struct extent_buffer *node;
206201f46658SChris Mason 	struct btrfs_disk_key disk_key;
20633c69faecSChris Mason 	u32 nritems;
20643c69faecSChris Mason 	u64 search;
2065a7175319SChris Mason 	u64 target;
20666b80053dSChris Mason 	u64 nread = 0;
2067cb25c2eaSJosef Bacik 	u64 gen;
20683c69faecSChris Mason 	int direction = path->reada;
20695f39d397SChris Mason 	struct extent_buffer *eb;
20706b80053dSChris Mason 	u32 nr;
20716b80053dSChris Mason 	u32 blocksize;
20726b80053dSChris Mason 	u32 nscan = 0;
2073db94535dSChris Mason 
2074a6b6e75eSChris Mason 	if (level != 1)
20753c69faecSChris Mason 		return;
20763c69faecSChris Mason 
20776702ed49SChris Mason 	if (!path->nodes[level])
20786702ed49SChris Mason 		return;
20796702ed49SChris Mason 
20805f39d397SChris Mason 	node = path->nodes[level];
2081925baeddSChris Mason 
20823c69faecSChris Mason 	search = btrfs_node_blockptr(node, slot);
20836b80053dSChris Mason 	blocksize = btrfs_level_size(root, level - 1);
20846b80053dSChris Mason 	eb = btrfs_find_tree_block(root, search, blocksize);
20855f39d397SChris Mason 	if (eb) {
20865f39d397SChris Mason 		free_extent_buffer(eb);
20873c69faecSChris Mason 		return;
20883c69faecSChris Mason 	}
20893c69faecSChris Mason 
2090a7175319SChris Mason 	target = search;
20916b80053dSChris Mason 
20925f39d397SChris Mason 	nritems = btrfs_header_nritems(node);
20936b80053dSChris Mason 	nr = slot;
209425b8b936SJosef Bacik 
20953c69faecSChris Mason 	while (1) {
20966b80053dSChris Mason 		if (direction < 0) {
20976b80053dSChris Mason 			if (nr == 0)
20983c69faecSChris Mason 				break;
20996b80053dSChris Mason 			nr--;
21006b80053dSChris Mason 		} else if (direction > 0) {
21016b80053dSChris Mason 			nr++;
21026b80053dSChris Mason 			if (nr >= nritems)
21036b80053dSChris Mason 				break;
21043c69faecSChris Mason 		}
210501f46658SChris Mason 		if (path->reada < 0 && objectid) {
210601f46658SChris Mason 			btrfs_node_key(node, &disk_key, nr);
210701f46658SChris Mason 			if (btrfs_disk_key_objectid(&disk_key) != objectid)
210801f46658SChris Mason 				break;
210901f46658SChris Mason 		}
21106b80053dSChris Mason 		search = btrfs_node_blockptr(node, nr);
2111a7175319SChris Mason 		if ((search <= target && target - search <= 65536) ||
2112a7175319SChris Mason 		    (search > target && search - target <= 65536)) {
2113cb25c2eaSJosef Bacik 			gen = btrfs_node_ptr_generation(node, nr);
2114cb25c2eaSJosef Bacik 			readahead_tree_block(root, search, blocksize, gen);
21156b80053dSChris Mason 			nread += blocksize;
21163c69faecSChris Mason 		}
21176b80053dSChris Mason 		nscan++;
2118a7175319SChris Mason 		if ((nread > 65536 || nscan > 32))
21196b80053dSChris Mason 			break;
21203c69faecSChris Mason 	}
21213c69faecSChris Mason }
2122925baeddSChris Mason 
2123d352ac68SChris Mason /*
2124b4ce94deSChris Mason  * returns -EAGAIN if it had to drop the path, or zero if everything was in
2125b4ce94deSChris Mason  * cache
2126b4ce94deSChris Mason  */
2127b4ce94deSChris Mason static noinline int reada_for_balance(struct btrfs_root *root,
2128b4ce94deSChris Mason 				      struct btrfs_path *path, int level)
2129b4ce94deSChris Mason {
2130b4ce94deSChris Mason 	int slot;
2131b4ce94deSChris Mason 	int nritems;
2132b4ce94deSChris Mason 	struct extent_buffer *parent;
2133b4ce94deSChris Mason 	struct extent_buffer *eb;
2134b4ce94deSChris Mason 	u64 gen;
2135b4ce94deSChris Mason 	u64 block1 = 0;
2136b4ce94deSChris Mason 	u64 block2 = 0;
2137b4ce94deSChris Mason 	int ret = 0;
2138b4ce94deSChris Mason 	int blocksize;
2139b4ce94deSChris Mason 
21408c594ea8SChris Mason 	parent = path->nodes[level + 1];
2141b4ce94deSChris Mason 	if (!parent)
2142b4ce94deSChris Mason 		return 0;
2143b4ce94deSChris Mason 
2144b4ce94deSChris Mason 	nritems = btrfs_header_nritems(parent);
21458c594ea8SChris Mason 	slot = path->slots[level + 1];
2146b4ce94deSChris Mason 	blocksize = btrfs_level_size(root, level);
2147b4ce94deSChris Mason 
2148b4ce94deSChris Mason 	if (slot > 0) {
2149b4ce94deSChris Mason 		block1 = btrfs_node_blockptr(parent, slot - 1);
2150b4ce94deSChris Mason 		gen = btrfs_node_ptr_generation(parent, slot - 1);
2151b4ce94deSChris Mason 		eb = btrfs_find_tree_block(root, block1, blocksize);
2152b9fab919SChris Mason 		/*
2153b9fab919SChris Mason 		 * if we get -eagain from btrfs_buffer_uptodate, we
2154b9fab919SChris Mason 		 * don't want to return eagain here.  That will loop
2155b9fab919SChris Mason 		 * forever
2156b9fab919SChris Mason 		 */
2157b9fab919SChris Mason 		if (eb && btrfs_buffer_uptodate(eb, gen, 1) != 0)
2158b4ce94deSChris Mason 			block1 = 0;
2159b4ce94deSChris Mason 		free_extent_buffer(eb);
2160b4ce94deSChris Mason 	}
21618c594ea8SChris Mason 	if (slot + 1 < nritems) {
2162b4ce94deSChris Mason 		block2 = btrfs_node_blockptr(parent, slot + 1);
2163b4ce94deSChris Mason 		gen = btrfs_node_ptr_generation(parent, slot + 1);
2164b4ce94deSChris Mason 		eb = btrfs_find_tree_block(root, block2, blocksize);
2165b9fab919SChris Mason 		if (eb && btrfs_buffer_uptodate(eb, gen, 1) != 0)
2166b4ce94deSChris Mason 			block2 = 0;
2167b4ce94deSChris Mason 		free_extent_buffer(eb);
2168b4ce94deSChris Mason 	}
2169b4ce94deSChris Mason 	if (block1 || block2) {
2170b4ce94deSChris Mason 		ret = -EAGAIN;
21718c594ea8SChris Mason 
21728c594ea8SChris Mason 		/* release the whole path */
2173b3b4aa74SDavid Sterba 		btrfs_release_path(path);
21748c594ea8SChris Mason 
21758c594ea8SChris Mason 		/* read the blocks */
2176b4ce94deSChris Mason 		if (block1)
2177b4ce94deSChris Mason 			readahead_tree_block(root, block1, blocksize, 0);
2178b4ce94deSChris Mason 		if (block2)
2179b4ce94deSChris Mason 			readahead_tree_block(root, block2, blocksize, 0);
2180b4ce94deSChris Mason 
2181b4ce94deSChris Mason 		if (block1) {
2182b4ce94deSChris Mason 			eb = read_tree_block(root, block1, blocksize, 0);
2183b4ce94deSChris Mason 			free_extent_buffer(eb);
2184b4ce94deSChris Mason 		}
21858c594ea8SChris Mason 		if (block2) {
2186b4ce94deSChris Mason 			eb = read_tree_block(root, block2, blocksize, 0);
2187b4ce94deSChris Mason 			free_extent_buffer(eb);
2188b4ce94deSChris Mason 		}
2189b4ce94deSChris Mason 	}
2190b4ce94deSChris Mason 	return ret;
2191b4ce94deSChris Mason }
2192b4ce94deSChris Mason 
2193b4ce94deSChris Mason 
2194b4ce94deSChris Mason /*
2195d397712bSChris Mason  * when we walk down the tree, it is usually safe to unlock the higher layers
2196d397712bSChris Mason  * in the tree.  The exceptions are when our path goes through slot 0, because
2197d397712bSChris Mason  * operations on the tree might require changing key pointers higher up in the
2198d397712bSChris Mason  * tree.
2199d352ac68SChris Mason  *
2200d397712bSChris Mason  * callers might also have set path->keep_locks, which tells this code to keep
2201d397712bSChris Mason  * the lock if the path points to the last slot in the block.  This is part of
2202d397712bSChris Mason  * walking through the tree, and selecting the next slot in the higher block.
2203d352ac68SChris Mason  *
2204d397712bSChris Mason  * lowest_unlock sets the lowest level in the tree we're allowed to unlock.  so
2205d397712bSChris Mason  * if lowest_unlock is 1, level 0 won't be unlocked
2206d352ac68SChris Mason  */
2207e02119d5SChris Mason static noinline void unlock_up(struct btrfs_path *path, int level,
2208f7c79f30SChris Mason 			       int lowest_unlock, int min_write_lock_level,
2209f7c79f30SChris Mason 			       int *write_lock_level)
2210925baeddSChris Mason {
2211925baeddSChris Mason 	int i;
2212925baeddSChris Mason 	int skip_level = level;
2213051e1b9fSChris Mason 	int no_skips = 0;
2214925baeddSChris Mason 	struct extent_buffer *t;
2215925baeddSChris Mason 
2216d6393786SJosef Bacik 	if (path->really_keep_locks)
2217d6393786SJosef Bacik 		return;
2218d6393786SJosef Bacik 
2219925baeddSChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2220925baeddSChris Mason 		if (!path->nodes[i])
2221925baeddSChris Mason 			break;
2222925baeddSChris Mason 		if (!path->locks[i])
2223925baeddSChris Mason 			break;
2224051e1b9fSChris Mason 		if (!no_skips && path->slots[i] == 0) {
2225925baeddSChris Mason 			skip_level = i + 1;
2226925baeddSChris Mason 			continue;
2227925baeddSChris Mason 		}
2228051e1b9fSChris Mason 		if (!no_skips && path->keep_locks) {
2229925baeddSChris Mason 			u32 nritems;
2230925baeddSChris Mason 			t = path->nodes[i];
2231925baeddSChris Mason 			nritems = btrfs_header_nritems(t);
2232051e1b9fSChris Mason 			if (nritems < 1 || path->slots[i] >= nritems - 1) {
2233925baeddSChris Mason 				skip_level = i + 1;
2234925baeddSChris Mason 				continue;
2235925baeddSChris Mason 			}
2236925baeddSChris Mason 		}
2237051e1b9fSChris Mason 		if (skip_level < i && i >= lowest_unlock)
2238051e1b9fSChris Mason 			no_skips = 1;
2239051e1b9fSChris Mason 
2240925baeddSChris Mason 		t = path->nodes[i];
2241925baeddSChris Mason 		if (i >= lowest_unlock && i > skip_level && path->locks[i]) {
2242bd681513SChris Mason 			btrfs_tree_unlock_rw(t, path->locks[i]);
2243925baeddSChris Mason 			path->locks[i] = 0;
2244f7c79f30SChris Mason 			if (write_lock_level &&
2245f7c79f30SChris Mason 			    i > min_write_lock_level &&
2246f7c79f30SChris Mason 			    i <= *write_lock_level) {
2247f7c79f30SChris Mason 				*write_lock_level = i - 1;
2248f7c79f30SChris Mason 			}
2249925baeddSChris Mason 		}
2250925baeddSChris Mason 	}
2251925baeddSChris Mason }
2252925baeddSChris Mason 
22533c69faecSChris Mason /*
2254b4ce94deSChris Mason  * This releases any locks held in the path starting at level and
2255b4ce94deSChris Mason  * going all the way up to the root.
2256b4ce94deSChris Mason  *
2257b4ce94deSChris Mason  * btrfs_search_slot will keep the lock held on higher nodes in a few
2258b4ce94deSChris Mason  * corner cases, such as COW of the block at slot zero in the node.  This
2259b4ce94deSChris Mason  * ignores those rules, and it should only be called when there are no
2260b4ce94deSChris Mason  * more updates to be done higher up in the tree.
2261b4ce94deSChris Mason  */
2262b4ce94deSChris Mason noinline void btrfs_unlock_up_safe(struct btrfs_path *path, int level)
2263b4ce94deSChris Mason {
2264b4ce94deSChris Mason 	int i;
2265b4ce94deSChris Mason 
2266d6393786SJosef Bacik 	if (path->keep_locks || path->really_keep_locks)
2267b4ce94deSChris Mason 		return;
2268b4ce94deSChris Mason 
2269b4ce94deSChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2270b4ce94deSChris Mason 		if (!path->nodes[i])
227112f4daccSChris Mason 			continue;
2272b4ce94deSChris Mason 		if (!path->locks[i])
227312f4daccSChris Mason 			continue;
2274bd681513SChris Mason 		btrfs_tree_unlock_rw(path->nodes[i], path->locks[i]);
2275b4ce94deSChris Mason 		path->locks[i] = 0;
2276b4ce94deSChris Mason 	}
2277b4ce94deSChris Mason }
2278b4ce94deSChris Mason 
2279b4ce94deSChris Mason /*
2280c8c42864SChris Mason  * helper function for btrfs_search_slot.  The goal is to find a block
2281c8c42864SChris Mason  * in cache without setting the path to blocking.  If we find the block
2282c8c42864SChris Mason  * we return zero and the path is unchanged.
2283c8c42864SChris Mason  *
2284c8c42864SChris Mason  * If we can't find the block, we set the path blocking and do some
2285c8c42864SChris Mason  * reada.  -EAGAIN is returned and the search must be repeated.
2286c8c42864SChris Mason  */
2287c8c42864SChris Mason static int
2288c8c42864SChris Mason read_block_for_search(struct btrfs_trans_handle *trans,
2289c8c42864SChris Mason 		       struct btrfs_root *root, struct btrfs_path *p,
2290c8c42864SChris Mason 		       struct extent_buffer **eb_ret, int level, int slot,
22915d9e75c4SJan Schmidt 		       struct btrfs_key *key, u64 time_seq)
2292c8c42864SChris Mason {
2293c8c42864SChris Mason 	u64 blocknr;
2294c8c42864SChris Mason 	u64 gen;
2295c8c42864SChris Mason 	u32 blocksize;
2296c8c42864SChris Mason 	struct extent_buffer *b = *eb_ret;
2297c8c42864SChris Mason 	struct extent_buffer *tmp;
229876a05b35SChris Mason 	int ret;
2299c8c42864SChris Mason 
2300c8c42864SChris Mason 	blocknr = btrfs_node_blockptr(b, slot);
2301c8c42864SChris Mason 	gen = btrfs_node_ptr_generation(b, slot);
2302c8c42864SChris Mason 	blocksize = btrfs_level_size(root, level - 1);
2303c8c42864SChris Mason 
2304c8c42864SChris Mason 	tmp = btrfs_find_tree_block(root, blocknr, blocksize);
2305cb44921aSChris Mason 	if (tmp) {
2306b9fab919SChris Mason 		/* first we do an atomic uptodate check */
2307b9fab919SChris Mason 		if (btrfs_buffer_uptodate(tmp, 0, 1) > 0) {
2308b9fab919SChris Mason 			if (btrfs_buffer_uptodate(tmp, gen, 1) > 0) {
230976a05b35SChris Mason 				/*
2310cb44921aSChris Mason 				 * we found an up to date block without
2311cb44921aSChris Mason 				 * sleeping, return
231276a05b35SChris Mason 				 * right away
231376a05b35SChris Mason 				 */
2314c8c42864SChris Mason 				*eb_ret = tmp;
2315c8c42864SChris Mason 				return 0;
2316c8c42864SChris Mason 			}
2317cb44921aSChris Mason 			/* the pages were up to date, but we failed
2318cb44921aSChris Mason 			 * the generation number check.  Do a full
2319cb44921aSChris Mason 			 * read for the generation number that is correct.
2320cb44921aSChris Mason 			 * We must do this without dropping locks so
2321cb44921aSChris Mason 			 * we can trust our generation number
2322cb44921aSChris Mason 			 */
2323cb44921aSChris Mason 			free_extent_buffer(tmp);
2324bd681513SChris Mason 			btrfs_set_path_blocking(p);
2325bd681513SChris Mason 
2326b9fab919SChris Mason 			/* now we're allowed to do a blocking uptodate check */
2327cb44921aSChris Mason 			tmp = read_tree_block(root, blocknr, blocksize, gen);
2328b9fab919SChris Mason 			if (tmp && btrfs_buffer_uptodate(tmp, gen, 0) > 0) {
2329cb44921aSChris Mason 				*eb_ret = tmp;
2330cb44921aSChris Mason 				return 0;
2331cb44921aSChris Mason 			}
2332cb44921aSChris Mason 			free_extent_buffer(tmp);
2333b3b4aa74SDavid Sterba 			btrfs_release_path(p);
2334cb44921aSChris Mason 			return -EIO;
2335cb44921aSChris Mason 		}
2336cb44921aSChris Mason 	}
2337c8c42864SChris Mason 
2338c8c42864SChris Mason 	/*
2339c8c42864SChris Mason 	 * reduce lock contention at high levels
2340c8c42864SChris Mason 	 * of the btree by dropping locks before
234176a05b35SChris Mason 	 * we read.  Don't release the lock on the current
234276a05b35SChris Mason 	 * level because we need to walk this node to figure
234376a05b35SChris Mason 	 * out which blocks to read.
2344c8c42864SChris Mason 	 */
23458c594ea8SChris Mason 	btrfs_unlock_up_safe(p, level + 1);
23468c594ea8SChris Mason 	btrfs_set_path_blocking(p);
23478c594ea8SChris Mason 
2348c8c42864SChris Mason 	free_extent_buffer(tmp);
2349c8c42864SChris Mason 	if (p->reada)
2350c8c42864SChris Mason 		reada_for_search(root, p, level, slot, key->objectid);
2351c8c42864SChris Mason 
2352b3b4aa74SDavid Sterba 	btrfs_release_path(p);
235376a05b35SChris Mason 
235476a05b35SChris Mason 	ret = -EAGAIN;
23555bdd3536SYan, Zheng 	tmp = read_tree_block(root, blocknr, blocksize, 0);
235676a05b35SChris Mason 	if (tmp) {
235776a05b35SChris Mason 		/*
235876a05b35SChris Mason 		 * If the read above didn't mark this buffer up to date,
235976a05b35SChris Mason 		 * it will never end up being up to date.  Set ret to EIO now
236076a05b35SChris Mason 		 * and give up so that our caller doesn't loop forever
236176a05b35SChris Mason 		 * on our EAGAINs.
236276a05b35SChris Mason 		 */
2363b9fab919SChris Mason 		if (!btrfs_buffer_uptodate(tmp, 0, 0))
236476a05b35SChris Mason 			ret = -EIO;
2365c8c42864SChris Mason 		free_extent_buffer(tmp);
236676a05b35SChris Mason 	}
236776a05b35SChris Mason 	return ret;
2368c8c42864SChris Mason }
2369c8c42864SChris Mason 
2370c8c42864SChris Mason /*
2371c8c42864SChris Mason  * helper function for btrfs_search_slot.  This does all of the checks
2372c8c42864SChris Mason  * for node-level blocks and does any balancing required based on
2373c8c42864SChris Mason  * the ins_len.
2374c8c42864SChris Mason  *
2375c8c42864SChris Mason  * If no extra work was required, zero is returned.  If we had to
2376c8c42864SChris Mason  * drop the path, -EAGAIN is returned and btrfs_search_slot must
2377c8c42864SChris Mason  * start over
2378c8c42864SChris Mason  */
2379c8c42864SChris Mason static int
2380c8c42864SChris Mason setup_nodes_for_search(struct btrfs_trans_handle *trans,
2381c8c42864SChris Mason 		       struct btrfs_root *root, struct btrfs_path *p,
2382bd681513SChris Mason 		       struct extent_buffer *b, int level, int ins_len,
2383bd681513SChris Mason 		       int *write_lock_level)
2384c8c42864SChris Mason {
2385c8c42864SChris Mason 	int ret;
2386c8c42864SChris Mason 	if ((p->search_for_split || ins_len > 0) && btrfs_header_nritems(b) >=
2387c8c42864SChris Mason 	    BTRFS_NODEPTRS_PER_BLOCK(root) - 3) {
2388c8c42864SChris Mason 		int sret;
2389c8c42864SChris Mason 
2390bd681513SChris Mason 		if (*write_lock_level < level + 1) {
2391bd681513SChris Mason 			*write_lock_level = level + 1;
2392bd681513SChris Mason 			btrfs_release_path(p);
2393bd681513SChris Mason 			goto again;
2394bd681513SChris Mason 		}
2395bd681513SChris Mason 
2396c8c42864SChris Mason 		sret = reada_for_balance(root, p, level);
2397c8c42864SChris Mason 		if (sret)
2398c8c42864SChris Mason 			goto again;
2399c8c42864SChris Mason 
2400c8c42864SChris Mason 		btrfs_set_path_blocking(p);
2401c8c42864SChris Mason 		sret = split_node(trans, root, p, level);
2402bd681513SChris Mason 		btrfs_clear_path_blocking(p, NULL, 0);
2403c8c42864SChris Mason 
2404c8c42864SChris Mason 		BUG_ON(sret > 0);
2405c8c42864SChris Mason 		if (sret) {
2406c8c42864SChris Mason 			ret = sret;
2407c8c42864SChris Mason 			goto done;
2408c8c42864SChris Mason 		}
2409c8c42864SChris Mason 		b = p->nodes[level];
2410c8c42864SChris Mason 	} else if (ins_len < 0 && btrfs_header_nritems(b) <
2411cfbb9308SChris Mason 		   BTRFS_NODEPTRS_PER_BLOCK(root) / 2) {
2412c8c42864SChris Mason 		int sret;
2413c8c42864SChris Mason 
2414bd681513SChris Mason 		if (*write_lock_level < level + 1) {
2415bd681513SChris Mason 			*write_lock_level = level + 1;
2416bd681513SChris Mason 			btrfs_release_path(p);
2417bd681513SChris Mason 			goto again;
2418bd681513SChris Mason 		}
2419bd681513SChris Mason 
2420c8c42864SChris Mason 		sret = reada_for_balance(root, p, level);
2421c8c42864SChris Mason 		if (sret)
2422c8c42864SChris Mason 			goto again;
2423c8c42864SChris Mason 
2424c8c42864SChris Mason 		btrfs_set_path_blocking(p);
2425c8c42864SChris Mason 		sret = balance_level(trans, root, p, level);
2426bd681513SChris Mason 		btrfs_clear_path_blocking(p, NULL, 0);
2427c8c42864SChris Mason 
2428c8c42864SChris Mason 		if (sret) {
2429c8c42864SChris Mason 			ret = sret;
2430c8c42864SChris Mason 			goto done;
2431c8c42864SChris Mason 		}
2432c8c42864SChris Mason 		b = p->nodes[level];
2433c8c42864SChris Mason 		if (!b) {
2434b3b4aa74SDavid Sterba 			btrfs_release_path(p);
2435c8c42864SChris Mason 			goto again;
2436c8c42864SChris Mason 		}
2437c8c42864SChris Mason 		BUG_ON(btrfs_header_nritems(b) == 1);
2438c8c42864SChris Mason 	}
2439c8c42864SChris Mason 	return 0;
2440c8c42864SChris Mason 
2441c8c42864SChris Mason again:
2442c8c42864SChris Mason 	ret = -EAGAIN;
2443c8c42864SChris Mason done:
2444c8c42864SChris Mason 	return ret;
2445c8c42864SChris Mason }
2446c8c42864SChris Mason 
2447c8c42864SChris Mason /*
244874123bd7SChris Mason  * look for key in the tree.  path is filled in with nodes along the way
244974123bd7SChris Mason  * if key is found, we return zero and you can find the item in the leaf
245074123bd7SChris Mason  * level of the path (level 0)
245174123bd7SChris Mason  *
245274123bd7SChris Mason  * If the key isn't found, the path points to the slot where it should
2453aa5d6bedSChris Mason  * be inserted, and 1 is returned.  If there are other errors during the
2454aa5d6bedSChris Mason  * search a negative error number is returned.
245597571fd0SChris Mason  *
245697571fd0SChris Mason  * if ins_len > 0, nodes and leaves will be split as we walk down the
245797571fd0SChris Mason  * tree.  if ins_len < 0, nodes will be merged as we walk down the tree (if
245897571fd0SChris Mason  * possible)
245974123bd7SChris Mason  */
2460e089f05cSChris Mason int btrfs_search_slot(struct btrfs_trans_handle *trans, struct btrfs_root
2461e089f05cSChris Mason 		      *root, struct btrfs_key *key, struct btrfs_path *p, int
2462e089f05cSChris Mason 		      ins_len, int cow)
2463be0e5c09SChris Mason {
24645f39d397SChris Mason 	struct extent_buffer *b;
2465be0e5c09SChris Mason 	int slot;
2466be0e5c09SChris Mason 	int ret;
246733c66f43SYan Zheng 	int err;
2468be0e5c09SChris Mason 	int level;
2469925baeddSChris Mason 	int lowest_unlock = 1;
2470bd681513SChris Mason 	int root_lock;
2471bd681513SChris Mason 	/* everything at write_lock_level or lower must be write locked */
2472bd681513SChris Mason 	int write_lock_level = 0;
24739f3a7427SChris Mason 	u8 lowest_level = 0;
2474f7c79f30SChris Mason 	int min_write_lock_level;
24759f3a7427SChris Mason 
24766702ed49SChris Mason 	lowest_level = p->lowest_level;
2477323ac95bSChris Mason 	WARN_ON(lowest_level && ins_len > 0);
247822b0ebdaSChris Mason 	WARN_ON(p->nodes[0] != NULL);
247925179201SJosef Bacik 
2480bd681513SChris Mason 	if (ins_len < 0) {
2481925baeddSChris Mason 		lowest_unlock = 2;
248265b51a00SChris Mason 
2483bd681513SChris Mason 		/* when we are removing items, we might have to go up to level
2484bd681513SChris Mason 		 * two as we update tree pointers  Make sure we keep write
2485bd681513SChris Mason 		 * for those levels as well
2486bd681513SChris Mason 		 */
2487bd681513SChris Mason 		write_lock_level = 2;
2488bd681513SChris Mason 	} else if (ins_len > 0) {
2489bd681513SChris Mason 		/*
2490bd681513SChris Mason 		 * for inserting items, make sure we have a write lock on
2491bd681513SChris Mason 		 * level 1 so we can update keys
2492bd681513SChris Mason 		 */
2493bd681513SChris Mason 		write_lock_level = 1;
2494bd681513SChris Mason 	}
2495bd681513SChris Mason 
2496bd681513SChris Mason 	if (!cow)
2497bd681513SChris Mason 		write_lock_level = -1;
2498bd681513SChris Mason 
2499d6393786SJosef Bacik 	if (cow && (p->really_keep_locks || p->keep_locks || p->lowest_level))
2500bd681513SChris Mason 		write_lock_level = BTRFS_MAX_LEVEL;
2501bd681513SChris Mason 
2502f7c79f30SChris Mason 	min_write_lock_level = write_lock_level;
2503f7c79f30SChris Mason 
2504bb803951SChris Mason again:
2505bd681513SChris Mason 	/*
2506bd681513SChris Mason 	 * we try very hard to do read locks on the root
2507bd681513SChris Mason 	 */
2508bd681513SChris Mason 	root_lock = BTRFS_READ_LOCK;
2509bd681513SChris Mason 	level = 0;
25105d4f98a2SYan Zheng 	if (p->search_commit_root) {
2511bd681513SChris Mason 		/*
2512bd681513SChris Mason 		 * the commit roots are read only
2513bd681513SChris Mason 		 * so we always do read locks
2514bd681513SChris Mason 		 */
25155d4f98a2SYan Zheng 		b = root->commit_root;
25165d4f98a2SYan Zheng 		extent_buffer_get(b);
2517bd681513SChris Mason 		level = btrfs_header_level(b);
25185d4f98a2SYan Zheng 		if (!p->skip_locking)
2519bd681513SChris Mason 			btrfs_tree_read_lock(b);
25205d4f98a2SYan Zheng 	} else {
2521bd681513SChris Mason 		if (p->skip_locking) {
25225cd57b2cSChris Mason 			b = btrfs_root_node(root);
2523bd681513SChris Mason 			level = btrfs_header_level(b);
2524bd681513SChris Mason 		} else {
2525bd681513SChris Mason 			/* we don't know the level of the root node
2526bd681513SChris Mason 			 * until we actually have it read locked
2527bd681513SChris Mason 			 */
2528bd681513SChris Mason 			b = btrfs_read_lock_root_node(root);
2529bd681513SChris Mason 			level = btrfs_header_level(b);
2530bd681513SChris Mason 			if (level <= write_lock_level) {
2531bd681513SChris Mason 				/* whoops, must trade for write lock */
2532bd681513SChris Mason 				btrfs_tree_read_unlock(b);
2533bd681513SChris Mason 				free_extent_buffer(b);
2534925baeddSChris Mason 				b = btrfs_lock_root_node(root);
2535bd681513SChris Mason 				root_lock = BTRFS_WRITE_LOCK;
2536bd681513SChris Mason 
2537bd681513SChris Mason 				/* the level might have changed, check again */
2538bd681513SChris Mason 				level = btrfs_header_level(b);
25395d4f98a2SYan Zheng 			}
2540bd681513SChris Mason 		}
2541bd681513SChris Mason 	}
2542bd681513SChris Mason 	p->nodes[level] = b;
2543bd681513SChris Mason 	if (!p->skip_locking)
2544bd681513SChris Mason 		p->locks[level] = root_lock;
2545925baeddSChris Mason 
2546eb60ceacSChris Mason 	while (b) {
25475f39d397SChris Mason 		level = btrfs_header_level(b);
254865b51a00SChris Mason 
254965b51a00SChris Mason 		/*
255065b51a00SChris Mason 		 * setup the path here so we can release it under lock
255165b51a00SChris Mason 		 * contention with the cow code
255265b51a00SChris Mason 		 */
255302217ed2SChris Mason 		if (cow) {
2554c8c42864SChris Mason 			/*
2555c8c42864SChris Mason 			 * if we don't really need to cow this block
2556c8c42864SChris Mason 			 * then we don't want to set the path blocking,
2557c8c42864SChris Mason 			 * so we test it here
2558c8c42864SChris Mason 			 */
25595d4f98a2SYan Zheng 			if (!should_cow_block(trans, root, b))
256065b51a00SChris Mason 				goto cow_done;
25615d4f98a2SYan Zheng 
2562b4ce94deSChris Mason 			btrfs_set_path_blocking(p);
2563b4ce94deSChris Mason 
2564bd681513SChris Mason 			/*
2565bd681513SChris Mason 			 * must have write locks on this node and the
2566bd681513SChris Mason 			 * parent
2567bd681513SChris Mason 			 */
25685124e00eSJosef Bacik 			if (level > write_lock_level ||
25695124e00eSJosef Bacik 			    (level + 1 > write_lock_level &&
25705124e00eSJosef Bacik 			    level + 1 < BTRFS_MAX_LEVEL &&
25715124e00eSJosef Bacik 			    p->nodes[level + 1])) {
2572bd681513SChris Mason 				write_lock_level = level + 1;
2573bd681513SChris Mason 				btrfs_release_path(p);
2574bd681513SChris Mason 				goto again;
2575bd681513SChris Mason 			}
2576bd681513SChris Mason 
257733c66f43SYan Zheng 			err = btrfs_cow_block(trans, root, b,
2578e20d96d6SChris Mason 					      p->nodes[level + 1],
25799fa8cfe7SChris Mason 					      p->slots[level + 1], &b);
258033c66f43SYan Zheng 			if (err) {
258133c66f43SYan Zheng 				ret = err;
258265b51a00SChris Mason 				goto done;
258354aa1f4dSChris Mason 			}
258402217ed2SChris Mason 		}
258565b51a00SChris Mason cow_done:
258602217ed2SChris Mason 		BUG_ON(!cow && ins_len);
258765b51a00SChris Mason 
2588eb60ceacSChris Mason 		p->nodes[level] = b;
2589bd681513SChris Mason 		btrfs_clear_path_blocking(p, NULL, 0);
2590b4ce94deSChris Mason 
2591b4ce94deSChris Mason 		/*
2592b4ce94deSChris Mason 		 * we have a lock on b and as long as we aren't changing
2593b4ce94deSChris Mason 		 * the tree, there is no way to for the items in b to change.
2594b4ce94deSChris Mason 		 * It is safe to drop the lock on our parent before we
2595b4ce94deSChris Mason 		 * go through the expensive btree search on b.
2596b4ce94deSChris Mason 		 *
2597b4ce94deSChris Mason 		 * If cow is true, then we might be changing slot zero,
2598b4ce94deSChris Mason 		 * which may require changing the parent.  So, we can't
2599b4ce94deSChris Mason 		 * drop the lock until after we know which slot we're
2600b4ce94deSChris Mason 		 * operating on.
2601b4ce94deSChris Mason 		 */
2602b4ce94deSChris Mason 		if (!cow)
2603b4ce94deSChris Mason 			btrfs_unlock_up_safe(p, level + 1);
2604b4ce94deSChris Mason 
26055f39d397SChris Mason 		ret = bin_search(b, key, level, &slot);
2606b4ce94deSChris Mason 
26075f39d397SChris Mason 		if (level != 0) {
260833c66f43SYan Zheng 			int dec = 0;
260933c66f43SYan Zheng 			if (ret && slot > 0) {
261033c66f43SYan Zheng 				dec = 1;
2611be0e5c09SChris Mason 				slot -= 1;
261233c66f43SYan Zheng 			}
2613be0e5c09SChris Mason 			p->slots[level] = slot;
261433c66f43SYan Zheng 			err = setup_nodes_for_search(trans, root, p, b, level,
2615bd681513SChris Mason 					     ins_len, &write_lock_level);
261633c66f43SYan Zheng 			if (err == -EAGAIN)
2617b4ce94deSChris Mason 				goto again;
261833c66f43SYan Zheng 			if (err) {
261933c66f43SYan Zheng 				ret = err;
262065b51a00SChris Mason 				goto done;
262133c66f43SYan Zheng 			}
26225c680ed6SChris Mason 			b = p->nodes[level];
26235c680ed6SChris Mason 			slot = p->slots[level];
2624b4ce94deSChris Mason 
2625bd681513SChris Mason 			/*
2626bd681513SChris Mason 			 * slot 0 is special, if we change the key
2627bd681513SChris Mason 			 * we have to update the parent pointer
2628bd681513SChris Mason 			 * which means we must have a write lock
2629bd681513SChris Mason 			 * on the parent
2630bd681513SChris Mason 			 */
2631bd681513SChris Mason 			if (slot == 0 && cow &&
2632bd681513SChris Mason 			    write_lock_level < level + 1) {
2633bd681513SChris Mason 				write_lock_level = level + 1;
2634bd681513SChris Mason 				btrfs_release_path(p);
2635bd681513SChris Mason 				goto again;
2636bd681513SChris Mason 			}
2637bd681513SChris Mason 
2638f7c79f30SChris Mason 			unlock_up(p, level, lowest_unlock,
2639f7c79f30SChris Mason 				  min_write_lock_level, &write_lock_level);
2640f9efa9c7SChris Mason 
2641925baeddSChris Mason 			if (level == lowest_level) {
264233c66f43SYan Zheng 				if (dec)
264333c66f43SYan Zheng 					p->slots[level]++;
26445b21f2edSZheng Yan 				goto done;
2645925baeddSChris Mason 			}
2646ca7a79adSChris Mason 
264733c66f43SYan Zheng 			err = read_block_for_search(trans, root, p,
26485d9e75c4SJan Schmidt 						    &b, level, slot, key, 0);
264933c66f43SYan Zheng 			if (err == -EAGAIN)
2650051e1b9fSChris Mason 				goto again;
265133c66f43SYan Zheng 			if (err) {
265233c66f43SYan Zheng 				ret = err;
265376a05b35SChris Mason 				goto done;
265433c66f43SYan Zheng 			}
265576a05b35SChris Mason 
2656b4ce94deSChris Mason 			if (!p->skip_locking) {
2657bd681513SChris Mason 				level = btrfs_header_level(b);
2658bd681513SChris Mason 				if (level <= write_lock_level) {
2659bd681513SChris Mason 					err = btrfs_try_tree_write_lock(b);
266033c66f43SYan Zheng 					if (!err) {
2661b4ce94deSChris Mason 						btrfs_set_path_blocking(p);
2662925baeddSChris Mason 						btrfs_tree_lock(b);
2663bd681513SChris Mason 						btrfs_clear_path_blocking(p, b,
2664bd681513SChris Mason 								  BTRFS_WRITE_LOCK);
2665b4ce94deSChris Mason 					}
2666bd681513SChris Mason 					p->locks[level] = BTRFS_WRITE_LOCK;
2667bd681513SChris Mason 				} else {
2668bd681513SChris Mason 					err = btrfs_try_tree_read_lock(b);
2669bd681513SChris Mason 					if (!err) {
2670bd681513SChris Mason 						btrfs_set_path_blocking(p);
2671bd681513SChris Mason 						btrfs_tree_read_lock(b);
2672bd681513SChris Mason 						btrfs_clear_path_blocking(p, b,
2673bd681513SChris Mason 								  BTRFS_READ_LOCK);
2674bd681513SChris Mason 					}
2675bd681513SChris Mason 					p->locks[level] = BTRFS_READ_LOCK;
2676bd681513SChris Mason 				}
2677bd681513SChris Mason 				p->nodes[level] = b;
2678b4ce94deSChris Mason 			}
2679be0e5c09SChris Mason 		} else {
2680be0e5c09SChris Mason 			p->slots[level] = slot;
268187b29b20SYan Zheng 			if (ins_len > 0 &&
268287b29b20SYan Zheng 			    btrfs_leaf_free_space(root, b) < ins_len) {
2683bd681513SChris Mason 				if (write_lock_level < 1) {
2684bd681513SChris Mason 					write_lock_level = 1;
2685bd681513SChris Mason 					btrfs_release_path(p);
2686bd681513SChris Mason 					goto again;
2687bd681513SChris Mason 				}
2688bd681513SChris Mason 
2689b4ce94deSChris Mason 				btrfs_set_path_blocking(p);
269033c66f43SYan Zheng 				err = split_leaf(trans, root, key,
2691cc0c5538SChris Mason 						 p, ins_len, ret == 0);
2692bd681513SChris Mason 				btrfs_clear_path_blocking(p, NULL, 0);
2693b4ce94deSChris Mason 
269433c66f43SYan Zheng 				BUG_ON(err > 0);
269533c66f43SYan Zheng 				if (err) {
269633c66f43SYan Zheng 					ret = err;
269765b51a00SChris Mason 					goto done;
269865b51a00SChris Mason 				}
26995c680ed6SChris Mason 			}
2700459931ecSChris Mason 			if (!p->search_for_split)
2701f7c79f30SChris Mason 				unlock_up(p, level, lowest_unlock,
2702f7c79f30SChris Mason 					  min_write_lock_level, &write_lock_level);
270365b51a00SChris Mason 			goto done;
270465b51a00SChris Mason 		}
270565b51a00SChris Mason 	}
270665b51a00SChris Mason 	ret = 1;
270765b51a00SChris Mason done:
2708b4ce94deSChris Mason 	/*
2709b4ce94deSChris Mason 	 * we don't really know what they plan on doing with the path
2710b4ce94deSChris Mason 	 * from here on, so for now just mark it as blocking
2711b4ce94deSChris Mason 	 */
2712b9473439SChris Mason 	if (!p->leave_spinning)
2713b4ce94deSChris Mason 		btrfs_set_path_blocking(p);
271476a05b35SChris Mason 	if (ret < 0)
2715b3b4aa74SDavid Sterba 		btrfs_release_path(p);
2716be0e5c09SChris Mason 	return ret;
2717be0e5c09SChris Mason }
2718be0e5c09SChris Mason 
271974123bd7SChris Mason /*
27205d9e75c4SJan Schmidt  * Like btrfs_search_slot, this looks for a key in the given tree. It uses the
27215d9e75c4SJan Schmidt  * current state of the tree together with the operations recorded in the tree
27225d9e75c4SJan Schmidt  * modification log to search for the key in a previous version of this tree, as
27235d9e75c4SJan Schmidt  * denoted by the time_seq parameter.
27245d9e75c4SJan Schmidt  *
27255d9e75c4SJan Schmidt  * Naturally, there is no support for insert, delete or cow operations.
27265d9e75c4SJan Schmidt  *
27275d9e75c4SJan Schmidt  * The resulting path and return value will be set up as if we called
27285d9e75c4SJan Schmidt  * btrfs_search_slot at that point in time with ins_len and cow both set to 0.
27295d9e75c4SJan Schmidt  */
27305d9e75c4SJan Schmidt int btrfs_search_old_slot(struct btrfs_root *root, struct btrfs_key *key,
27315d9e75c4SJan Schmidt 			  struct btrfs_path *p, u64 time_seq)
27325d9e75c4SJan Schmidt {
27335d9e75c4SJan Schmidt 	struct extent_buffer *b;
27345d9e75c4SJan Schmidt 	int slot;
27355d9e75c4SJan Schmidt 	int ret;
27365d9e75c4SJan Schmidt 	int err;
27375d9e75c4SJan Schmidt 	int level;
27385d9e75c4SJan Schmidt 	int lowest_unlock = 1;
27395d9e75c4SJan Schmidt 	u8 lowest_level = 0;
27405d9e75c4SJan Schmidt 
27415d9e75c4SJan Schmidt 	lowest_level = p->lowest_level;
27425d9e75c4SJan Schmidt 	WARN_ON(p->nodes[0] != NULL);
27435d9e75c4SJan Schmidt 
27445d9e75c4SJan Schmidt 	if (p->search_commit_root) {
27455d9e75c4SJan Schmidt 		BUG_ON(time_seq);
27465d9e75c4SJan Schmidt 		return btrfs_search_slot(NULL, root, key, p, 0, 0);
27475d9e75c4SJan Schmidt 	}
27485d9e75c4SJan Schmidt 
27495d9e75c4SJan Schmidt again:
27505d9e75c4SJan Schmidt 	b = get_old_root(root, time_seq);
27515d9e75c4SJan Schmidt 	level = btrfs_header_level(b);
27525d9e75c4SJan Schmidt 	p->locks[level] = BTRFS_READ_LOCK;
27535d9e75c4SJan Schmidt 
27545d9e75c4SJan Schmidt 	while (b) {
27555d9e75c4SJan Schmidt 		level = btrfs_header_level(b);
27565d9e75c4SJan Schmidt 		p->nodes[level] = b;
27575d9e75c4SJan Schmidt 		btrfs_clear_path_blocking(p, NULL, 0);
27585d9e75c4SJan Schmidt 
27595d9e75c4SJan Schmidt 		/*
27605d9e75c4SJan Schmidt 		 * we have a lock on b and as long as we aren't changing
27615d9e75c4SJan Schmidt 		 * the tree, there is no way to for the items in b to change.
27625d9e75c4SJan Schmidt 		 * It is safe to drop the lock on our parent before we
27635d9e75c4SJan Schmidt 		 * go through the expensive btree search on b.
27645d9e75c4SJan Schmidt 		 */
27655d9e75c4SJan Schmidt 		btrfs_unlock_up_safe(p, level + 1);
27665d9e75c4SJan Schmidt 
27675d9e75c4SJan Schmidt 		ret = bin_search(b, key, level, &slot);
27685d9e75c4SJan Schmidt 
27695d9e75c4SJan Schmidt 		if (level != 0) {
27705d9e75c4SJan Schmidt 			int dec = 0;
27715d9e75c4SJan Schmidt 			if (ret && slot > 0) {
27725d9e75c4SJan Schmidt 				dec = 1;
27735d9e75c4SJan Schmidt 				slot -= 1;
27745d9e75c4SJan Schmidt 			}
27755d9e75c4SJan Schmidt 			p->slots[level] = slot;
27765d9e75c4SJan Schmidt 			unlock_up(p, level, lowest_unlock, 0, NULL);
27775d9e75c4SJan Schmidt 
27785d9e75c4SJan Schmidt 			if (level == lowest_level) {
27795d9e75c4SJan Schmidt 				if (dec)
27805d9e75c4SJan Schmidt 					p->slots[level]++;
27815d9e75c4SJan Schmidt 				goto done;
27825d9e75c4SJan Schmidt 			}
27835d9e75c4SJan Schmidt 
27845d9e75c4SJan Schmidt 			err = read_block_for_search(NULL, root, p, &b, level,
27855d9e75c4SJan Schmidt 						    slot, key, time_seq);
27865d9e75c4SJan Schmidt 			if (err == -EAGAIN)
27875d9e75c4SJan Schmidt 				goto again;
27885d9e75c4SJan Schmidt 			if (err) {
27895d9e75c4SJan Schmidt 				ret = err;
27905d9e75c4SJan Schmidt 				goto done;
27915d9e75c4SJan Schmidt 			}
27925d9e75c4SJan Schmidt 
27935d9e75c4SJan Schmidt 			level = btrfs_header_level(b);
27945d9e75c4SJan Schmidt 			err = btrfs_try_tree_read_lock(b);
27955d9e75c4SJan Schmidt 			if (!err) {
27965d9e75c4SJan Schmidt 				btrfs_set_path_blocking(p);
27975d9e75c4SJan Schmidt 				btrfs_tree_read_lock(b);
27985d9e75c4SJan Schmidt 				btrfs_clear_path_blocking(p, b,
27995d9e75c4SJan Schmidt 							  BTRFS_READ_LOCK);
28005d9e75c4SJan Schmidt 			}
28015d9e75c4SJan Schmidt 			p->locks[level] = BTRFS_READ_LOCK;
28025d9e75c4SJan Schmidt 			p->nodes[level] = b;
28035d9e75c4SJan Schmidt 			b = tree_mod_log_rewind(root->fs_info, b, time_seq);
28045d9e75c4SJan Schmidt 			if (b != p->nodes[level]) {
28055d9e75c4SJan Schmidt 				btrfs_tree_unlock_rw(p->nodes[level],
28065d9e75c4SJan Schmidt 						     p->locks[level]);
28075d9e75c4SJan Schmidt 				p->locks[level] = 0;
28085d9e75c4SJan Schmidt 				p->nodes[level] = b;
28095d9e75c4SJan Schmidt 			}
28105d9e75c4SJan Schmidt 		} else {
28115d9e75c4SJan Schmidt 			p->slots[level] = slot;
28125d9e75c4SJan Schmidt 			unlock_up(p, level, lowest_unlock, 0, NULL);
28135d9e75c4SJan Schmidt 			goto done;
28145d9e75c4SJan Schmidt 		}
28155d9e75c4SJan Schmidt 	}
28165d9e75c4SJan Schmidt 	ret = 1;
28175d9e75c4SJan Schmidt done:
28185d9e75c4SJan Schmidt 	if (!p->leave_spinning)
28195d9e75c4SJan Schmidt 		btrfs_set_path_blocking(p);
28205d9e75c4SJan Schmidt 	if (ret < 0)
28215d9e75c4SJan Schmidt 		btrfs_release_path(p);
28225d9e75c4SJan Schmidt 
28235d9e75c4SJan Schmidt 	return ret;
28245d9e75c4SJan Schmidt }
28255d9e75c4SJan Schmidt 
28265d9e75c4SJan Schmidt /*
28272f38b3e1SArne Jansen  * helper to use instead of search slot if no exact match is needed but
28282f38b3e1SArne Jansen  * instead the next or previous item should be returned.
28292f38b3e1SArne Jansen  * When find_higher is true, the next higher item is returned, the next lower
28302f38b3e1SArne Jansen  * otherwise.
28312f38b3e1SArne Jansen  * When return_any and find_higher are both true, and no higher item is found,
28322f38b3e1SArne Jansen  * return the next lower instead.
28332f38b3e1SArne Jansen  * When return_any is true and find_higher is false, and no lower item is found,
28342f38b3e1SArne Jansen  * return the next higher instead.
28352f38b3e1SArne Jansen  * It returns 0 if any item is found, 1 if none is found (tree empty), and
28362f38b3e1SArne Jansen  * < 0 on error
28372f38b3e1SArne Jansen  */
28382f38b3e1SArne Jansen int btrfs_search_slot_for_read(struct btrfs_root *root,
28392f38b3e1SArne Jansen 			       struct btrfs_key *key, struct btrfs_path *p,
28402f38b3e1SArne Jansen 			       int find_higher, int return_any)
28412f38b3e1SArne Jansen {
28422f38b3e1SArne Jansen 	int ret;
28432f38b3e1SArne Jansen 	struct extent_buffer *leaf;
28442f38b3e1SArne Jansen 
28452f38b3e1SArne Jansen again:
28462f38b3e1SArne Jansen 	ret = btrfs_search_slot(NULL, root, key, p, 0, 0);
28472f38b3e1SArne Jansen 	if (ret <= 0)
28482f38b3e1SArne Jansen 		return ret;
28492f38b3e1SArne Jansen 	/*
28502f38b3e1SArne Jansen 	 * a return value of 1 means the path is at the position where the
28512f38b3e1SArne Jansen 	 * item should be inserted. Normally this is the next bigger item,
28522f38b3e1SArne Jansen 	 * but in case the previous item is the last in a leaf, path points
28532f38b3e1SArne Jansen 	 * to the first free slot in the previous leaf, i.e. at an invalid
28542f38b3e1SArne Jansen 	 * item.
28552f38b3e1SArne Jansen 	 */
28562f38b3e1SArne Jansen 	leaf = p->nodes[0];
28572f38b3e1SArne Jansen 
28582f38b3e1SArne Jansen 	if (find_higher) {
28592f38b3e1SArne Jansen 		if (p->slots[0] >= btrfs_header_nritems(leaf)) {
28602f38b3e1SArne Jansen 			ret = btrfs_next_leaf(root, p);
28612f38b3e1SArne Jansen 			if (ret <= 0)
28622f38b3e1SArne Jansen 				return ret;
28632f38b3e1SArne Jansen 			if (!return_any)
28642f38b3e1SArne Jansen 				return 1;
28652f38b3e1SArne Jansen 			/*
28662f38b3e1SArne Jansen 			 * no higher item found, return the next
28672f38b3e1SArne Jansen 			 * lower instead
28682f38b3e1SArne Jansen 			 */
28692f38b3e1SArne Jansen 			return_any = 0;
28702f38b3e1SArne Jansen 			find_higher = 0;
28712f38b3e1SArne Jansen 			btrfs_release_path(p);
28722f38b3e1SArne Jansen 			goto again;
28732f38b3e1SArne Jansen 		}
28742f38b3e1SArne Jansen 	} else {
28752f38b3e1SArne Jansen 		if (p->slots[0] == 0) {
28762f38b3e1SArne Jansen 			ret = btrfs_prev_leaf(root, p);
2877e6793769SArne Jansen 			if (ret < 0)
28782f38b3e1SArne Jansen 				return ret;
2879e6793769SArne Jansen 			if (!ret) {
2880e6793769SArne Jansen 				p->slots[0] = btrfs_header_nritems(leaf) - 1;
2881e6793769SArne Jansen 				return 0;
2882e6793769SArne Jansen 			}
28832f38b3e1SArne Jansen 			if (!return_any)
28842f38b3e1SArne Jansen 				return 1;
28852f38b3e1SArne Jansen 			/*
28862f38b3e1SArne Jansen 			 * no lower item found, return the next
28872f38b3e1SArne Jansen 			 * higher instead
28882f38b3e1SArne Jansen 			 */
28892f38b3e1SArne Jansen 			return_any = 0;
28902f38b3e1SArne Jansen 			find_higher = 1;
28912f38b3e1SArne Jansen 			btrfs_release_path(p);
28922f38b3e1SArne Jansen 			goto again;
2893e6793769SArne Jansen 		} else {
28942f38b3e1SArne Jansen 			--p->slots[0];
28952f38b3e1SArne Jansen 		}
28962f38b3e1SArne Jansen 	}
28972f38b3e1SArne Jansen 	return 0;
28982f38b3e1SArne Jansen }
28992f38b3e1SArne Jansen 
29002f38b3e1SArne Jansen /*
290174123bd7SChris Mason  * adjust the pointers going up the tree, starting at level
290274123bd7SChris Mason  * making sure the right key of each node is points to 'key'.
290374123bd7SChris Mason  * This is used after shifting pointers to the left, so it stops
290474123bd7SChris Mason  * fixing up pointers when a given leaf/node is not in slot 0 of the
290574123bd7SChris Mason  * higher levels
2906aa5d6bedSChris Mason  *
290774123bd7SChris Mason  */
2908143bede5SJeff Mahoney static void fixup_low_keys(struct btrfs_trans_handle *trans,
29095f39d397SChris Mason 			   struct btrfs_root *root, struct btrfs_path *path,
29105f39d397SChris Mason 			   struct btrfs_disk_key *key, int level)
2911be0e5c09SChris Mason {
2912be0e5c09SChris Mason 	int i;
29135f39d397SChris Mason 	struct extent_buffer *t;
29145f39d397SChris Mason 
2915234b63a0SChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2916be0e5c09SChris Mason 		int tslot = path->slots[i];
2917eb60ceacSChris Mason 		if (!path->nodes[i])
2918be0e5c09SChris Mason 			break;
29195f39d397SChris Mason 		t = path->nodes[i];
292032adf090SLiu Bo 		tree_mod_log_set_node_key(root->fs_info, t, tslot, 1);
29215f39d397SChris Mason 		btrfs_set_node_key(t, key, tslot);
2922d6025579SChris Mason 		btrfs_mark_buffer_dirty(path->nodes[i]);
2923be0e5c09SChris Mason 		if (tslot != 0)
2924be0e5c09SChris Mason 			break;
2925be0e5c09SChris Mason 	}
2926be0e5c09SChris Mason }
2927be0e5c09SChris Mason 
292874123bd7SChris Mason /*
292931840ae1SZheng Yan  * update item key.
293031840ae1SZheng Yan  *
293131840ae1SZheng Yan  * This function isn't completely safe. It's the caller's responsibility
293231840ae1SZheng Yan  * that the new key won't break the order
293331840ae1SZheng Yan  */
2934143bede5SJeff Mahoney void btrfs_set_item_key_safe(struct btrfs_trans_handle *trans,
293531840ae1SZheng Yan 			     struct btrfs_root *root, struct btrfs_path *path,
293631840ae1SZheng Yan 			     struct btrfs_key *new_key)
293731840ae1SZheng Yan {
293831840ae1SZheng Yan 	struct btrfs_disk_key disk_key;
293931840ae1SZheng Yan 	struct extent_buffer *eb;
294031840ae1SZheng Yan 	int slot;
294131840ae1SZheng Yan 
294231840ae1SZheng Yan 	eb = path->nodes[0];
294331840ae1SZheng Yan 	slot = path->slots[0];
294431840ae1SZheng Yan 	if (slot > 0) {
294531840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot - 1);
2946143bede5SJeff Mahoney 		BUG_ON(comp_keys(&disk_key, new_key) >= 0);
294731840ae1SZheng Yan 	}
294831840ae1SZheng Yan 	if (slot < btrfs_header_nritems(eb) - 1) {
294931840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot + 1);
2950143bede5SJeff Mahoney 		BUG_ON(comp_keys(&disk_key, new_key) <= 0);
295131840ae1SZheng Yan 	}
295231840ae1SZheng Yan 
295331840ae1SZheng Yan 	btrfs_cpu_key_to_disk(&disk_key, new_key);
295431840ae1SZheng Yan 	btrfs_set_item_key(eb, &disk_key, slot);
295531840ae1SZheng Yan 	btrfs_mark_buffer_dirty(eb);
295631840ae1SZheng Yan 	if (slot == 0)
295731840ae1SZheng Yan 		fixup_low_keys(trans, root, path, &disk_key, 1);
295831840ae1SZheng Yan }
295931840ae1SZheng Yan 
296031840ae1SZheng Yan /*
296174123bd7SChris Mason  * try to push data from one node into the next node left in the
296279f95c82SChris Mason  * tree.
2963aa5d6bedSChris Mason  *
2964aa5d6bedSChris Mason  * returns 0 if some ptrs were pushed left, < 0 if there was some horrible
2965aa5d6bedSChris Mason  * error, and > 0 if there was no room in the left hand block.
296674123bd7SChris Mason  */
296798ed5174SChris Mason static int push_node_left(struct btrfs_trans_handle *trans,
296898ed5174SChris Mason 			  struct btrfs_root *root, struct extent_buffer *dst,
2969971a1f66SChris Mason 			  struct extent_buffer *src, int empty)
2970be0e5c09SChris Mason {
2971be0e5c09SChris Mason 	int push_items = 0;
2972bb803951SChris Mason 	int src_nritems;
2973bb803951SChris Mason 	int dst_nritems;
2974aa5d6bedSChris Mason 	int ret = 0;
2975be0e5c09SChris Mason 
29765f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
29775f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
2978123abc88SChris Mason 	push_items = BTRFS_NODEPTRS_PER_BLOCK(root) - dst_nritems;
29797bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
29807bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
298154aa1f4dSChris Mason 
2982bce4eae9SChris Mason 	if (!empty && src_nritems <= 8)
2983971a1f66SChris Mason 		return 1;
2984971a1f66SChris Mason 
2985d397712bSChris Mason 	if (push_items <= 0)
2986be0e5c09SChris Mason 		return 1;
2987be0e5c09SChris Mason 
2988bce4eae9SChris Mason 	if (empty) {
2989971a1f66SChris Mason 		push_items = min(src_nritems, push_items);
2990bce4eae9SChris Mason 		if (push_items < src_nritems) {
2991bce4eae9SChris Mason 			/* leave at least 8 pointers in the node if
2992bce4eae9SChris Mason 			 * we aren't going to empty it
2993bce4eae9SChris Mason 			 */
2994bce4eae9SChris Mason 			if (src_nritems - push_items < 8) {
2995bce4eae9SChris Mason 				if (push_items <= 8)
2996bce4eae9SChris Mason 					return 1;
2997bce4eae9SChris Mason 				push_items -= 8;
2998bce4eae9SChris Mason 			}
2999bce4eae9SChris Mason 		}
3000bce4eae9SChris Mason 	} else
3001bce4eae9SChris Mason 		push_items = min(src_nritems - 8, push_items);
300279f95c82SChris Mason 
3003f230475eSJan Schmidt 	tree_mod_log_eb_copy(root->fs_info, dst, src, dst_nritems, 0,
3004f230475eSJan Schmidt 			     push_items);
30055f39d397SChris Mason 	copy_extent_buffer(dst, src,
30065f39d397SChris Mason 			   btrfs_node_key_ptr_offset(dst_nritems),
30075f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
3008123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
30095f39d397SChris Mason 
3010bb803951SChris Mason 	if (push_items < src_nritems) {
301157911b8bSJan Schmidt 		/*
301257911b8bSJan Schmidt 		 * don't call tree_mod_log_eb_move here, key removal was already
301357911b8bSJan Schmidt 		 * fully logged by tree_mod_log_eb_copy above.
301457911b8bSJan Schmidt 		 */
30155f39d397SChris Mason 		memmove_extent_buffer(src, btrfs_node_key_ptr_offset(0),
30165f39d397SChris Mason 				      btrfs_node_key_ptr_offset(push_items),
3017e2fa7227SChris Mason 				      (src_nritems - push_items) *
3018123abc88SChris Mason 				      sizeof(struct btrfs_key_ptr));
3019bb803951SChris Mason 	}
30205f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
30215f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
30225f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
30235f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
302431840ae1SZheng Yan 
3025bb803951SChris Mason 	return ret;
3026be0e5c09SChris Mason }
3027be0e5c09SChris Mason 
302897571fd0SChris Mason /*
302979f95c82SChris Mason  * try to push data from one node into the next node right in the
303079f95c82SChris Mason  * tree.
303179f95c82SChris Mason  *
303279f95c82SChris Mason  * returns 0 if some ptrs were pushed, < 0 if there was some horrible
303379f95c82SChris Mason  * error, and > 0 if there was no room in the right hand block.
303479f95c82SChris Mason  *
303579f95c82SChris Mason  * this will  only push up to 1/2 the contents of the left node over
303679f95c82SChris Mason  */
30375f39d397SChris Mason static int balance_node_right(struct btrfs_trans_handle *trans,
30385f39d397SChris Mason 			      struct btrfs_root *root,
30395f39d397SChris Mason 			      struct extent_buffer *dst,
30405f39d397SChris Mason 			      struct extent_buffer *src)
304179f95c82SChris Mason {
304279f95c82SChris Mason 	int push_items = 0;
304379f95c82SChris Mason 	int max_push;
304479f95c82SChris Mason 	int src_nritems;
304579f95c82SChris Mason 	int dst_nritems;
304679f95c82SChris Mason 	int ret = 0;
304779f95c82SChris Mason 
30487bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
30497bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
30507bb86316SChris Mason 
30515f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
30525f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
3053123abc88SChris Mason 	push_items = BTRFS_NODEPTRS_PER_BLOCK(root) - dst_nritems;
3054d397712bSChris Mason 	if (push_items <= 0)
305579f95c82SChris Mason 		return 1;
3056bce4eae9SChris Mason 
3057d397712bSChris Mason 	if (src_nritems < 4)
3058bce4eae9SChris Mason 		return 1;
305979f95c82SChris Mason 
306079f95c82SChris Mason 	max_push = src_nritems / 2 + 1;
306179f95c82SChris Mason 	/* don't try to empty the node */
3062d397712bSChris Mason 	if (max_push >= src_nritems)
306379f95c82SChris Mason 		return 1;
3064252c38f0SYan 
306579f95c82SChris Mason 	if (max_push < push_items)
306679f95c82SChris Mason 		push_items = max_push;
306779f95c82SChris Mason 
3068f230475eSJan Schmidt 	tree_mod_log_eb_move(root->fs_info, dst, push_items, 0, dst_nritems);
30695f39d397SChris Mason 	memmove_extent_buffer(dst, btrfs_node_key_ptr_offset(push_items),
30705f39d397SChris Mason 				      btrfs_node_key_ptr_offset(0),
30715f39d397SChris Mason 				      (dst_nritems) *
30725f39d397SChris Mason 				      sizeof(struct btrfs_key_ptr));
3073d6025579SChris Mason 
3074f230475eSJan Schmidt 	tree_mod_log_eb_copy(root->fs_info, dst, src, 0,
3075f230475eSJan Schmidt 			     src_nritems - push_items, push_items);
30765f39d397SChris Mason 	copy_extent_buffer(dst, src,
30775f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
30785f39d397SChris Mason 			   btrfs_node_key_ptr_offset(src_nritems - push_items),
3079123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
308079f95c82SChris Mason 
30815f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
30825f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
308379f95c82SChris Mason 
30845f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
30855f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
308631840ae1SZheng Yan 
308779f95c82SChris Mason 	return ret;
308879f95c82SChris Mason }
308979f95c82SChris Mason 
309079f95c82SChris Mason /*
309197571fd0SChris Mason  * helper function to insert a new root level in the tree.
309297571fd0SChris Mason  * A new node is allocated, and a single item is inserted to
309397571fd0SChris Mason  * point to the existing root
3094aa5d6bedSChris Mason  *
3095aa5d6bedSChris Mason  * returns zero on success or < 0 on failure.
309697571fd0SChris Mason  */
3097d397712bSChris Mason static noinline int insert_new_root(struct btrfs_trans_handle *trans,
30985f39d397SChris Mason 			   struct btrfs_root *root,
30995f39d397SChris Mason 			   struct btrfs_path *path, int level)
310074123bd7SChris Mason {
31017bb86316SChris Mason 	u64 lower_gen;
31025f39d397SChris Mason 	struct extent_buffer *lower;
31035f39d397SChris Mason 	struct extent_buffer *c;
3104925baeddSChris Mason 	struct extent_buffer *old;
31055f39d397SChris Mason 	struct btrfs_disk_key lower_key;
31065c680ed6SChris Mason 
31075c680ed6SChris Mason 	BUG_ON(path->nodes[level]);
31085c680ed6SChris Mason 	BUG_ON(path->nodes[level-1] != root->node);
31095c680ed6SChris Mason 
31107bb86316SChris Mason 	lower = path->nodes[level-1];
31117bb86316SChris Mason 	if (level == 1)
31127bb86316SChris Mason 		btrfs_item_key(lower, &lower_key, 0);
31137bb86316SChris Mason 	else
31147bb86316SChris Mason 		btrfs_node_key(lower, &lower_key, 0);
31157bb86316SChris Mason 
311631840ae1SZheng Yan 	c = btrfs_alloc_free_block(trans, root, root->nodesize, 0,
31175d4f98a2SYan Zheng 				   root->root_key.objectid, &lower_key,
31185581a51aSJan Schmidt 				   level, root->node->start, 0);
31195f39d397SChris Mason 	if (IS_ERR(c))
31205f39d397SChris Mason 		return PTR_ERR(c);
3121925baeddSChris Mason 
3122f0486c68SYan, Zheng 	root_add_used(root, root->nodesize);
3123f0486c68SYan, Zheng 
31245d4f98a2SYan Zheng 	memset_extent_buffer(c, 0, 0, sizeof(struct btrfs_header));
31255f39d397SChris Mason 	btrfs_set_header_nritems(c, 1);
31265f39d397SChris Mason 	btrfs_set_header_level(c, level);
3127db94535dSChris Mason 	btrfs_set_header_bytenr(c, c->start);
31285f39d397SChris Mason 	btrfs_set_header_generation(c, trans->transid);
31295d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(c, BTRFS_MIXED_BACKREF_REV);
31305f39d397SChris Mason 	btrfs_set_header_owner(c, root->root_key.objectid);
3131d5719762SChris Mason 
31325f39d397SChris Mason 	write_extent_buffer(c, root->fs_info->fsid,
31335f39d397SChris Mason 			    (unsigned long)btrfs_header_fsid(c),
31345f39d397SChris Mason 			    BTRFS_FSID_SIZE);
3135e17cade2SChris Mason 
3136e17cade2SChris Mason 	write_extent_buffer(c, root->fs_info->chunk_tree_uuid,
3137e17cade2SChris Mason 			    (unsigned long)btrfs_header_chunk_tree_uuid(c),
3138e17cade2SChris Mason 			    BTRFS_UUID_SIZE);
3139e17cade2SChris Mason 
31405f39d397SChris Mason 	btrfs_set_node_key(c, &lower_key, 0);
3141db94535dSChris Mason 	btrfs_set_node_blockptr(c, 0, lower->start);
31427bb86316SChris Mason 	lower_gen = btrfs_header_generation(lower);
314331840ae1SZheng Yan 	WARN_ON(lower_gen != trans->transid);
31447bb86316SChris Mason 
31457bb86316SChris Mason 	btrfs_set_node_ptr_generation(c, 0, lower_gen);
31465f39d397SChris Mason 
31475f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
3148d5719762SChris Mason 
3149925baeddSChris Mason 	old = root->node;
3150f230475eSJan Schmidt 	tree_mod_log_set_root_pointer(root, c);
3151240f62c8SChris Mason 	rcu_assign_pointer(root->node, c);
3152925baeddSChris Mason 
3153925baeddSChris Mason 	/* the super has an extra ref to root->node */
3154925baeddSChris Mason 	free_extent_buffer(old);
3155925baeddSChris Mason 
31560b86a832SChris Mason 	add_root_to_dirty_list(root);
31575f39d397SChris Mason 	extent_buffer_get(c);
31585f39d397SChris Mason 	path->nodes[level] = c;
3159bd681513SChris Mason 	path->locks[level] = BTRFS_WRITE_LOCK;
316074123bd7SChris Mason 	path->slots[level] = 0;
316174123bd7SChris Mason 	return 0;
316274123bd7SChris Mason }
31635c680ed6SChris Mason 
31645c680ed6SChris Mason /*
31655c680ed6SChris Mason  * worker function to insert a single pointer in a node.
31665c680ed6SChris Mason  * the node should have enough room for the pointer already
316797571fd0SChris Mason  *
31685c680ed6SChris Mason  * slot and level indicate where you want the key to go, and
31695c680ed6SChris Mason  * blocknr is the block the key points to.
31705c680ed6SChris Mason  */
3171143bede5SJeff Mahoney static void insert_ptr(struct btrfs_trans_handle *trans,
3172143bede5SJeff Mahoney 		       struct btrfs_root *root, struct btrfs_path *path,
3173143bede5SJeff Mahoney 		       struct btrfs_disk_key *key, u64 bytenr,
3174c3e06965SJan Schmidt 		       int slot, int level)
31755c680ed6SChris Mason {
31765f39d397SChris Mason 	struct extent_buffer *lower;
31775c680ed6SChris Mason 	int nritems;
3178f3ea38daSJan Schmidt 	int ret;
31795c680ed6SChris Mason 
31805c680ed6SChris Mason 	BUG_ON(!path->nodes[level]);
3181f0486c68SYan, Zheng 	btrfs_assert_tree_locked(path->nodes[level]);
31825f39d397SChris Mason 	lower = path->nodes[level];
31835f39d397SChris Mason 	nritems = btrfs_header_nritems(lower);
3184c293498bSStoyan Gaydarov 	BUG_ON(slot > nritems);
3185143bede5SJeff Mahoney 	BUG_ON(nritems == BTRFS_NODEPTRS_PER_BLOCK(root));
318674123bd7SChris Mason 	if (slot != nritems) {
3187c3e06965SJan Schmidt 		if (level)
3188f3ea38daSJan Schmidt 			tree_mod_log_eb_move(root->fs_info, lower, slot + 1,
3189f3ea38daSJan Schmidt 					     slot, nritems - slot);
31905f39d397SChris Mason 		memmove_extent_buffer(lower,
31915f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot + 1),
31925f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot),
3193123abc88SChris Mason 			      (nritems - slot) * sizeof(struct btrfs_key_ptr));
319474123bd7SChris Mason 	}
3195c3e06965SJan Schmidt 	if (level) {
3196f3ea38daSJan Schmidt 		ret = tree_mod_log_insert_key(root->fs_info, lower, slot,
3197f3ea38daSJan Schmidt 					      MOD_LOG_KEY_ADD);
3198f3ea38daSJan Schmidt 		BUG_ON(ret < 0);
3199f3ea38daSJan Schmidt 	}
32005f39d397SChris Mason 	btrfs_set_node_key(lower, key, slot);
3201db94535dSChris Mason 	btrfs_set_node_blockptr(lower, slot, bytenr);
320274493f7aSChris Mason 	WARN_ON(trans->transid == 0);
320374493f7aSChris Mason 	btrfs_set_node_ptr_generation(lower, slot, trans->transid);
32045f39d397SChris Mason 	btrfs_set_header_nritems(lower, nritems + 1);
32055f39d397SChris Mason 	btrfs_mark_buffer_dirty(lower);
320674123bd7SChris Mason }
320774123bd7SChris Mason 
320897571fd0SChris Mason /*
320997571fd0SChris Mason  * split the node at the specified level in path in two.
321097571fd0SChris Mason  * The path is corrected to point to the appropriate node after the split
321197571fd0SChris Mason  *
321297571fd0SChris Mason  * Before splitting this tries to make some room in the node by pushing
321397571fd0SChris Mason  * left and right, if either one works, it returns right away.
3214aa5d6bedSChris Mason  *
3215aa5d6bedSChris Mason  * returns 0 on success and < 0 on failure
321697571fd0SChris Mason  */
3217e02119d5SChris Mason static noinline int split_node(struct btrfs_trans_handle *trans,
3218e02119d5SChris Mason 			       struct btrfs_root *root,
3219e02119d5SChris Mason 			       struct btrfs_path *path, int level)
3220be0e5c09SChris Mason {
32215f39d397SChris Mason 	struct extent_buffer *c;
32225f39d397SChris Mason 	struct extent_buffer *split;
32235f39d397SChris Mason 	struct btrfs_disk_key disk_key;
3224be0e5c09SChris Mason 	int mid;
32255c680ed6SChris Mason 	int ret;
32267518a238SChris Mason 	u32 c_nritems;
3227be0e5c09SChris Mason 
32285f39d397SChris Mason 	c = path->nodes[level];
32297bb86316SChris Mason 	WARN_ON(btrfs_header_generation(c) != trans->transid);
32305f39d397SChris Mason 	if (c == root->node) {
32315c680ed6SChris Mason 		/* trying to split the root, lets make a new one */
3232e089f05cSChris Mason 		ret = insert_new_root(trans, root, path, level + 1);
32335c680ed6SChris Mason 		if (ret)
32345c680ed6SChris Mason 			return ret;
3235b3612421SChris Mason 	} else {
3236e66f709bSChris Mason 		ret = push_nodes_for_insert(trans, root, path, level);
32375f39d397SChris Mason 		c = path->nodes[level];
32385f39d397SChris Mason 		if (!ret && btrfs_header_nritems(c) <
3239c448acf0SChris Mason 		    BTRFS_NODEPTRS_PER_BLOCK(root) - 3)
3240e66f709bSChris Mason 			return 0;
324154aa1f4dSChris Mason 		if (ret < 0)
324254aa1f4dSChris Mason 			return ret;
32435c680ed6SChris Mason 	}
3244e66f709bSChris Mason 
32455f39d397SChris Mason 	c_nritems = btrfs_header_nritems(c);
32465d4f98a2SYan Zheng 	mid = (c_nritems + 1) / 2;
32475d4f98a2SYan Zheng 	btrfs_node_key(c, &disk_key, mid);
32487bb86316SChris Mason 
32495d4f98a2SYan Zheng 	split = btrfs_alloc_free_block(trans, root, root->nodesize, 0,
32507bb86316SChris Mason 					root->root_key.objectid,
32515581a51aSJan Schmidt 					&disk_key, level, c->start, 0);
32525f39d397SChris Mason 	if (IS_ERR(split))
32535f39d397SChris Mason 		return PTR_ERR(split);
325454aa1f4dSChris Mason 
3255f0486c68SYan, Zheng 	root_add_used(root, root->nodesize);
3256f0486c68SYan, Zheng 
32575d4f98a2SYan Zheng 	memset_extent_buffer(split, 0, 0, sizeof(struct btrfs_header));
32585f39d397SChris Mason 	btrfs_set_header_level(split, btrfs_header_level(c));
3259db94535dSChris Mason 	btrfs_set_header_bytenr(split, split->start);
32605f39d397SChris Mason 	btrfs_set_header_generation(split, trans->transid);
32615d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(split, BTRFS_MIXED_BACKREF_REV);
32625f39d397SChris Mason 	btrfs_set_header_owner(split, root->root_key.objectid);
32635f39d397SChris Mason 	write_extent_buffer(split, root->fs_info->fsid,
32645f39d397SChris Mason 			    (unsigned long)btrfs_header_fsid(split),
32655f39d397SChris Mason 			    BTRFS_FSID_SIZE);
3266e17cade2SChris Mason 	write_extent_buffer(split, root->fs_info->chunk_tree_uuid,
3267e17cade2SChris Mason 			    (unsigned long)btrfs_header_chunk_tree_uuid(split),
3268e17cade2SChris Mason 			    BTRFS_UUID_SIZE);
32695f39d397SChris Mason 
3270f230475eSJan Schmidt 	tree_mod_log_eb_copy(root->fs_info, split, c, 0, mid, c_nritems - mid);
32715f39d397SChris Mason 	copy_extent_buffer(split, c,
32725f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
32735f39d397SChris Mason 			   btrfs_node_key_ptr_offset(mid),
3274123abc88SChris Mason 			   (c_nritems - mid) * sizeof(struct btrfs_key_ptr));
32755f39d397SChris Mason 	btrfs_set_header_nritems(split, c_nritems - mid);
32765f39d397SChris Mason 	btrfs_set_header_nritems(c, mid);
3277aa5d6bedSChris Mason 	ret = 0;
3278aa5d6bedSChris Mason 
32795f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
32805f39d397SChris Mason 	btrfs_mark_buffer_dirty(split);
32815f39d397SChris Mason 
3282143bede5SJeff Mahoney 	insert_ptr(trans, root, path, &disk_key, split->start,
3283c3e06965SJan Schmidt 		   path->slots[level + 1] + 1, level + 1);
3284aa5d6bedSChris Mason 
32855de08d7dSChris Mason 	if (path->slots[level] >= mid) {
32865c680ed6SChris Mason 		path->slots[level] -= mid;
3287925baeddSChris Mason 		btrfs_tree_unlock(c);
32885f39d397SChris Mason 		free_extent_buffer(c);
32895f39d397SChris Mason 		path->nodes[level] = split;
32905c680ed6SChris Mason 		path->slots[level + 1] += 1;
3291eb60ceacSChris Mason 	} else {
3292925baeddSChris Mason 		btrfs_tree_unlock(split);
32935f39d397SChris Mason 		free_extent_buffer(split);
3294be0e5c09SChris Mason 	}
3295aa5d6bedSChris Mason 	return ret;
3296be0e5c09SChris Mason }
3297be0e5c09SChris Mason 
329874123bd7SChris Mason /*
329974123bd7SChris Mason  * how many bytes are required to store the items in a leaf.  start
330074123bd7SChris Mason  * and nr indicate which items in the leaf to check.  This totals up the
330174123bd7SChris Mason  * space used both by the item structs and the item data
330274123bd7SChris Mason  */
33035f39d397SChris Mason static int leaf_space_used(struct extent_buffer *l, int start, int nr)
3304be0e5c09SChris Mason {
330541be1f3bSJosef Bacik 	struct btrfs_item *start_item;
330641be1f3bSJosef Bacik 	struct btrfs_item *end_item;
330741be1f3bSJosef Bacik 	struct btrfs_map_token token;
3308be0e5c09SChris Mason 	int data_len;
33095f39d397SChris Mason 	int nritems = btrfs_header_nritems(l);
3310d4dbff95SChris Mason 	int end = min(nritems, start + nr) - 1;
3311be0e5c09SChris Mason 
3312be0e5c09SChris Mason 	if (!nr)
3313be0e5c09SChris Mason 		return 0;
331441be1f3bSJosef Bacik 	btrfs_init_map_token(&token);
331541be1f3bSJosef Bacik 	start_item = btrfs_item_nr(l, start);
331641be1f3bSJosef Bacik 	end_item = btrfs_item_nr(l, end);
331741be1f3bSJosef Bacik 	data_len = btrfs_token_item_offset(l, start_item, &token) +
331841be1f3bSJosef Bacik 		btrfs_token_item_size(l, start_item, &token);
331941be1f3bSJosef Bacik 	data_len = data_len - btrfs_token_item_offset(l, end_item, &token);
33200783fcfcSChris Mason 	data_len += sizeof(struct btrfs_item) * nr;
3321d4dbff95SChris Mason 	WARN_ON(data_len < 0);
3322be0e5c09SChris Mason 	return data_len;
3323be0e5c09SChris Mason }
3324be0e5c09SChris Mason 
332574123bd7SChris Mason /*
3326d4dbff95SChris Mason  * The space between the end of the leaf items and
3327d4dbff95SChris Mason  * the start of the leaf data.  IOW, how much room
3328d4dbff95SChris Mason  * the leaf has left for both items and data
3329d4dbff95SChris Mason  */
3330d397712bSChris Mason noinline int btrfs_leaf_free_space(struct btrfs_root *root,
3331e02119d5SChris Mason 				   struct extent_buffer *leaf)
3332d4dbff95SChris Mason {
33335f39d397SChris Mason 	int nritems = btrfs_header_nritems(leaf);
33345f39d397SChris Mason 	int ret;
33355f39d397SChris Mason 	ret = BTRFS_LEAF_DATA_SIZE(root) - leaf_space_used(leaf, 0, nritems);
33365f39d397SChris Mason 	if (ret < 0) {
3337d397712bSChris Mason 		printk(KERN_CRIT "leaf free space ret %d, leaf data size %lu, "
3338d397712bSChris Mason 		       "used %d nritems %d\n",
3339ae2f5411SJens Axboe 		       ret, (unsigned long) BTRFS_LEAF_DATA_SIZE(root),
33405f39d397SChris Mason 		       leaf_space_used(leaf, 0, nritems), nritems);
33415f39d397SChris Mason 	}
33425f39d397SChris Mason 	return ret;
3343d4dbff95SChris Mason }
3344d4dbff95SChris Mason 
334599d8f83cSChris Mason /*
334699d8f83cSChris Mason  * min slot controls the lowest index we're willing to push to the
334799d8f83cSChris Mason  * right.  We'll push up to and including min_slot, but no lower
334899d8f83cSChris Mason  */
334944871b1bSChris Mason static noinline int __push_leaf_right(struct btrfs_trans_handle *trans,
335044871b1bSChris Mason 				      struct btrfs_root *root,
335144871b1bSChris Mason 				      struct btrfs_path *path,
335244871b1bSChris Mason 				      int data_size, int empty,
335344871b1bSChris Mason 				      struct extent_buffer *right,
335499d8f83cSChris Mason 				      int free_space, u32 left_nritems,
335599d8f83cSChris Mason 				      u32 min_slot)
335600ec4c51SChris Mason {
33575f39d397SChris Mason 	struct extent_buffer *left = path->nodes[0];
335844871b1bSChris Mason 	struct extent_buffer *upper = path->nodes[1];
3359cfed81a0SChris Mason 	struct btrfs_map_token token;
33605f39d397SChris Mason 	struct btrfs_disk_key disk_key;
336100ec4c51SChris Mason 	int slot;
336234a38218SChris Mason 	u32 i;
336300ec4c51SChris Mason 	int push_space = 0;
336400ec4c51SChris Mason 	int push_items = 0;
33650783fcfcSChris Mason 	struct btrfs_item *item;
336634a38218SChris Mason 	u32 nr;
33677518a238SChris Mason 	u32 right_nritems;
33685f39d397SChris Mason 	u32 data_end;
3369db94535dSChris Mason 	u32 this_item_size;
337000ec4c51SChris Mason 
3371cfed81a0SChris Mason 	btrfs_init_map_token(&token);
3372cfed81a0SChris Mason 
337334a38218SChris Mason 	if (empty)
337434a38218SChris Mason 		nr = 0;
337534a38218SChris Mason 	else
337699d8f83cSChris Mason 		nr = max_t(u32, 1, min_slot);
337734a38218SChris Mason 
337831840ae1SZheng Yan 	if (path->slots[0] >= left_nritems)
337987b29b20SYan Zheng 		push_space += data_size;
338031840ae1SZheng Yan 
338144871b1bSChris Mason 	slot = path->slots[1];
338234a38218SChris Mason 	i = left_nritems - 1;
338334a38218SChris Mason 	while (i >= nr) {
33845f39d397SChris Mason 		item = btrfs_item_nr(left, i);
3385db94535dSChris Mason 
338631840ae1SZheng Yan 		if (!empty && push_items > 0) {
338731840ae1SZheng Yan 			if (path->slots[0] > i)
338831840ae1SZheng Yan 				break;
338931840ae1SZheng Yan 			if (path->slots[0] == i) {
339031840ae1SZheng Yan 				int space = btrfs_leaf_free_space(root, left);
339131840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
339231840ae1SZheng Yan 					break;
339331840ae1SZheng Yan 			}
339431840ae1SZheng Yan 		}
339531840ae1SZheng Yan 
339600ec4c51SChris Mason 		if (path->slots[0] == i)
339787b29b20SYan Zheng 			push_space += data_size;
3398db94535dSChris Mason 
3399db94535dSChris Mason 		this_item_size = btrfs_item_size(left, item);
3400db94535dSChris Mason 		if (this_item_size + sizeof(*item) + push_space > free_space)
340100ec4c51SChris Mason 			break;
340231840ae1SZheng Yan 
340300ec4c51SChris Mason 		push_items++;
3404db94535dSChris Mason 		push_space += this_item_size + sizeof(*item);
340534a38218SChris Mason 		if (i == 0)
340634a38218SChris Mason 			break;
340734a38218SChris Mason 		i--;
3408db94535dSChris Mason 	}
34095f39d397SChris Mason 
3410925baeddSChris Mason 	if (push_items == 0)
3411925baeddSChris Mason 		goto out_unlock;
34125f39d397SChris Mason 
34136c1500f2SJulia Lawall 	WARN_ON(!empty && push_items == left_nritems);
34145f39d397SChris Mason 
341500ec4c51SChris Mason 	/* push left to right */
34165f39d397SChris Mason 	right_nritems = btrfs_header_nritems(right);
341734a38218SChris Mason 
34185f39d397SChris Mason 	push_space = btrfs_item_end_nr(left, left_nritems - push_items);
3419123abc88SChris Mason 	push_space -= leaf_data_end(root, left);
34205f39d397SChris Mason 
342100ec4c51SChris Mason 	/* make room in the right data area */
34225f39d397SChris Mason 	data_end = leaf_data_end(root, right);
34235f39d397SChris Mason 	memmove_extent_buffer(right,
34245f39d397SChris Mason 			      btrfs_leaf_data(right) + data_end - push_space,
34255f39d397SChris Mason 			      btrfs_leaf_data(right) + data_end,
34265f39d397SChris Mason 			      BTRFS_LEAF_DATA_SIZE(root) - data_end);
34275f39d397SChris Mason 
342800ec4c51SChris Mason 	/* copy from the left data area */
34295f39d397SChris Mason 	copy_extent_buffer(right, left, btrfs_leaf_data(right) +
3430d6025579SChris Mason 		     BTRFS_LEAF_DATA_SIZE(root) - push_space,
3431d6025579SChris Mason 		     btrfs_leaf_data(left) + leaf_data_end(root, left),
3432d6025579SChris Mason 		     push_space);
34335f39d397SChris Mason 
34345f39d397SChris Mason 	memmove_extent_buffer(right, btrfs_item_nr_offset(push_items),
34355f39d397SChris Mason 			      btrfs_item_nr_offset(0),
34360783fcfcSChris Mason 			      right_nritems * sizeof(struct btrfs_item));
34375f39d397SChris Mason 
343800ec4c51SChris Mason 	/* copy the items from left to right */
34395f39d397SChris Mason 	copy_extent_buffer(right, left, btrfs_item_nr_offset(0),
34405f39d397SChris Mason 		   btrfs_item_nr_offset(left_nritems - push_items),
34410783fcfcSChris Mason 		   push_items * sizeof(struct btrfs_item));
344200ec4c51SChris Mason 
344300ec4c51SChris Mason 	/* update the item pointers */
34447518a238SChris Mason 	right_nritems += push_items;
34455f39d397SChris Mason 	btrfs_set_header_nritems(right, right_nritems);
3446123abc88SChris Mason 	push_space = BTRFS_LEAF_DATA_SIZE(root);
34477518a238SChris Mason 	for (i = 0; i < right_nritems; i++) {
34485f39d397SChris Mason 		item = btrfs_item_nr(right, i);
3449cfed81a0SChris Mason 		push_space -= btrfs_token_item_size(right, item, &token);
3450cfed81a0SChris Mason 		btrfs_set_token_item_offset(right, item, push_space, &token);
3451db94535dSChris Mason 	}
3452db94535dSChris Mason 
34537518a238SChris Mason 	left_nritems -= push_items;
34545f39d397SChris Mason 	btrfs_set_header_nritems(left, left_nritems);
345500ec4c51SChris Mason 
345634a38218SChris Mason 	if (left_nritems)
34575f39d397SChris Mason 		btrfs_mark_buffer_dirty(left);
3458f0486c68SYan, Zheng 	else
3459f0486c68SYan, Zheng 		clean_tree_block(trans, root, left);
3460f0486c68SYan, Zheng 
34615f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
3462a429e513SChris Mason 
34635f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
34645f39d397SChris Mason 	btrfs_set_node_key(upper, &disk_key, slot + 1);
3465d6025579SChris Mason 	btrfs_mark_buffer_dirty(upper);
346602217ed2SChris Mason 
346700ec4c51SChris Mason 	/* then fixup the leaf pointer in the path */
34687518a238SChris Mason 	if (path->slots[0] >= left_nritems) {
34697518a238SChris Mason 		path->slots[0] -= left_nritems;
3470925baeddSChris Mason 		if (btrfs_header_nritems(path->nodes[0]) == 0)
3471925baeddSChris Mason 			clean_tree_block(trans, root, path->nodes[0]);
3472925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
34735f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
34745f39d397SChris Mason 		path->nodes[0] = right;
347500ec4c51SChris Mason 		path->slots[1] += 1;
347600ec4c51SChris Mason 	} else {
3477925baeddSChris Mason 		btrfs_tree_unlock(right);
34785f39d397SChris Mason 		free_extent_buffer(right);
347900ec4c51SChris Mason 	}
348000ec4c51SChris Mason 	return 0;
3481925baeddSChris Mason 
3482925baeddSChris Mason out_unlock:
3483925baeddSChris Mason 	btrfs_tree_unlock(right);
3484925baeddSChris Mason 	free_extent_buffer(right);
3485925baeddSChris Mason 	return 1;
348600ec4c51SChris Mason }
3487925baeddSChris Mason 
348800ec4c51SChris Mason /*
348944871b1bSChris Mason  * push some data in the path leaf to the right, trying to free up at
349074123bd7SChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
349144871b1bSChris Mason  *
349244871b1bSChris Mason  * returns 1 if the push failed because the other node didn't have enough
349344871b1bSChris Mason  * room, 0 if everything worked out and < 0 if there were major errors.
349499d8f83cSChris Mason  *
349599d8f83cSChris Mason  * this will push starting from min_slot to the end of the leaf.  It won't
349699d8f83cSChris Mason  * push any slot lower than min_slot
349774123bd7SChris Mason  */
349844871b1bSChris Mason static int push_leaf_right(struct btrfs_trans_handle *trans, struct btrfs_root
349999d8f83cSChris Mason 			   *root, struct btrfs_path *path,
350099d8f83cSChris Mason 			   int min_data_size, int data_size,
350199d8f83cSChris Mason 			   int empty, u32 min_slot)
3502be0e5c09SChris Mason {
350344871b1bSChris Mason 	struct extent_buffer *left = path->nodes[0];
350444871b1bSChris Mason 	struct extent_buffer *right;
350544871b1bSChris Mason 	struct extent_buffer *upper;
350644871b1bSChris Mason 	int slot;
350744871b1bSChris Mason 	int free_space;
350844871b1bSChris Mason 	u32 left_nritems;
350944871b1bSChris Mason 	int ret;
351044871b1bSChris Mason 
351144871b1bSChris Mason 	if (!path->nodes[1])
351244871b1bSChris Mason 		return 1;
351344871b1bSChris Mason 
351444871b1bSChris Mason 	slot = path->slots[1];
351544871b1bSChris Mason 	upper = path->nodes[1];
351644871b1bSChris Mason 	if (slot >= btrfs_header_nritems(upper) - 1)
351744871b1bSChris Mason 		return 1;
351844871b1bSChris Mason 
351944871b1bSChris Mason 	btrfs_assert_tree_locked(path->nodes[1]);
352044871b1bSChris Mason 
352144871b1bSChris Mason 	right = read_node_slot(root, upper, slot + 1);
352291ca338dSTsutomu Itoh 	if (right == NULL)
352391ca338dSTsutomu Itoh 		return 1;
352491ca338dSTsutomu Itoh 
352544871b1bSChris Mason 	btrfs_tree_lock(right);
352644871b1bSChris Mason 	btrfs_set_lock_blocking(right);
352744871b1bSChris Mason 
352844871b1bSChris Mason 	free_space = btrfs_leaf_free_space(root, right);
352944871b1bSChris Mason 	if (free_space < data_size)
353044871b1bSChris Mason 		goto out_unlock;
353144871b1bSChris Mason 
353244871b1bSChris Mason 	/* cow and double check */
353344871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, right, upper,
353444871b1bSChris Mason 			      slot + 1, &right);
353544871b1bSChris Mason 	if (ret)
353644871b1bSChris Mason 		goto out_unlock;
353744871b1bSChris Mason 
353844871b1bSChris Mason 	free_space = btrfs_leaf_free_space(root, right);
353944871b1bSChris Mason 	if (free_space < data_size)
354044871b1bSChris Mason 		goto out_unlock;
354144871b1bSChris Mason 
354244871b1bSChris Mason 	left_nritems = btrfs_header_nritems(left);
354344871b1bSChris Mason 	if (left_nritems == 0)
354444871b1bSChris Mason 		goto out_unlock;
354544871b1bSChris Mason 
354699d8f83cSChris Mason 	return __push_leaf_right(trans, root, path, min_data_size, empty,
354799d8f83cSChris Mason 				right, free_space, left_nritems, min_slot);
354844871b1bSChris Mason out_unlock:
354944871b1bSChris Mason 	btrfs_tree_unlock(right);
355044871b1bSChris Mason 	free_extent_buffer(right);
355144871b1bSChris Mason 	return 1;
355244871b1bSChris Mason }
355344871b1bSChris Mason 
355444871b1bSChris Mason /*
355544871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
355644871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
355799d8f83cSChris Mason  *
355899d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
355999d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us do all the
356099d8f83cSChris Mason  * items
356144871b1bSChris Mason  */
356244871b1bSChris Mason static noinline int __push_leaf_left(struct btrfs_trans_handle *trans,
356344871b1bSChris Mason 				     struct btrfs_root *root,
356444871b1bSChris Mason 				     struct btrfs_path *path, int data_size,
356544871b1bSChris Mason 				     int empty, struct extent_buffer *left,
356699d8f83cSChris Mason 				     int free_space, u32 right_nritems,
356799d8f83cSChris Mason 				     u32 max_slot)
356844871b1bSChris Mason {
35695f39d397SChris Mason 	struct btrfs_disk_key disk_key;
35705f39d397SChris Mason 	struct extent_buffer *right = path->nodes[0];
3571be0e5c09SChris Mason 	int i;
3572be0e5c09SChris Mason 	int push_space = 0;
3573be0e5c09SChris Mason 	int push_items = 0;
35740783fcfcSChris Mason 	struct btrfs_item *item;
35757518a238SChris Mason 	u32 old_left_nritems;
357634a38218SChris Mason 	u32 nr;
3577aa5d6bedSChris Mason 	int ret = 0;
3578db94535dSChris Mason 	u32 this_item_size;
3579db94535dSChris Mason 	u32 old_left_item_size;
3580cfed81a0SChris Mason 	struct btrfs_map_token token;
3581cfed81a0SChris Mason 
3582cfed81a0SChris Mason 	btrfs_init_map_token(&token);
3583be0e5c09SChris Mason 
358434a38218SChris Mason 	if (empty)
358599d8f83cSChris Mason 		nr = min(right_nritems, max_slot);
358634a38218SChris Mason 	else
358799d8f83cSChris Mason 		nr = min(right_nritems - 1, max_slot);
358834a38218SChris Mason 
358934a38218SChris Mason 	for (i = 0; i < nr; i++) {
35905f39d397SChris Mason 		item = btrfs_item_nr(right, i);
3591db94535dSChris Mason 
359231840ae1SZheng Yan 		if (!empty && push_items > 0) {
359331840ae1SZheng Yan 			if (path->slots[0] < i)
359431840ae1SZheng Yan 				break;
359531840ae1SZheng Yan 			if (path->slots[0] == i) {
359631840ae1SZheng Yan 				int space = btrfs_leaf_free_space(root, right);
359731840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
359831840ae1SZheng Yan 					break;
359931840ae1SZheng Yan 			}
360031840ae1SZheng Yan 		}
360131840ae1SZheng Yan 
3602be0e5c09SChris Mason 		if (path->slots[0] == i)
360387b29b20SYan Zheng 			push_space += data_size;
3604db94535dSChris Mason 
3605db94535dSChris Mason 		this_item_size = btrfs_item_size(right, item);
3606db94535dSChris Mason 		if (this_item_size + sizeof(*item) + push_space > free_space)
3607be0e5c09SChris Mason 			break;
3608db94535dSChris Mason 
3609be0e5c09SChris Mason 		push_items++;
3610db94535dSChris Mason 		push_space += this_item_size + sizeof(*item);
3611be0e5c09SChris Mason 	}
3612db94535dSChris Mason 
3613be0e5c09SChris Mason 	if (push_items == 0) {
3614925baeddSChris Mason 		ret = 1;
3615925baeddSChris Mason 		goto out;
3616be0e5c09SChris Mason 	}
361734a38218SChris Mason 	if (!empty && push_items == btrfs_header_nritems(right))
3618a429e513SChris Mason 		WARN_ON(1);
36195f39d397SChris Mason 
3620be0e5c09SChris Mason 	/* push data from right to left */
36215f39d397SChris Mason 	copy_extent_buffer(left, right,
36225f39d397SChris Mason 			   btrfs_item_nr_offset(btrfs_header_nritems(left)),
36235f39d397SChris Mason 			   btrfs_item_nr_offset(0),
36245f39d397SChris Mason 			   push_items * sizeof(struct btrfs_item));
36255f39d397SChris Mason 
3626123abc88SChris Mason 	push_space = BTRFS_LEAF_DATA_SIZE(root) -
36275f39d397SChris Mason 		     btrfs_item_offset_nr(right, push_items - 1);
36285f39d397SChris Mason 
36295f39d397SChris Mason 	copy_extent_buffer(left, right, btrfs_leaf_data(left) +
3630d6025579SChris Mason 		     leaf_data_end(root, left) - push_space,
3631123abc88SChris Mason 		     btrfs_leaf_data(right) +
36325f39d397SChris Mason 		     btrfs_item_offset_nr(right, push_items - 1),
3633be0e5c09SChris Mason 		     push_space);
36345f39d397SChris Mason 	old_left_nritems = btrfs_header_nritems(left);
363587b29b20SYan Zheng 	BUG_ON(old_left_nritems <= 0);
3636eb60ceacSChris Mason 
3637db94535dSChris Mason 	old_left_item_size = btrfs_item_offset_nr(left, old_left_nritems - 1);
3638be0e5c09SChris Mason 	for (i = old_left_nritems; i < old_left_nritems + push_items; i++) {
36395f39d397SChris Mason 		u32 ioff;
3640db94535dSChris Mason 
36415f39d397SChris Mason 		item = btrfs_item_nr(left, i);
3642db94535dSChris Mason 
3643cfed81a0SChris Mason 		ioff = btrfs_token_item_offset(left, item, &token);
3644cfed81a0SChris Mason 		btrfs_set_token_item_offset(left, item,
3645cfed81a0SChris Mason 		      ioff - (BTRFS_LEAF_DATA_SIZE(root) - old_left_item_size),
3646cfed81a0SChris Mason 		      &token);
3647be0e5c09SChris Mason 	}
36485f39d397SChris Mason 	btrfs_set_header_nritems(left, old_left_nritems + push_items);
3649be0e5c09SChris Mason 
3650be0e5c09SChris Mason 	/* fixup right node */
365131b1a2bdSJulia Lawall 	if (push_items > right_nritems)
365231b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "push items %d nr %u\n", push_items,
3653d397712bSChris Mason 		       right_nritems);
365434a38218SChris Mason 
365534a38218SChris Mason 	if (push_items < right_nritems) {
36565f39d397SChris Mason 		push_space = btrfs_item_offset_nr(right, push_items - 1) -
3657123abc88SChris Mason 						  leaf_data_end(root, right);
36585f39d397SChris Mason 		memmove_extent_buffer(right, btrfs_leaf_data(right) +
3659d6025579SChris Mason 				      BTRFS_LEAF_DATA_SIZE(root) - push_space,
3660d6025579SChris Mason 				      btrfs_leaf_data(right) +
3661123abc88SChris Mason 				      leaf_data_end(root, right), push_space);
36625f39d397SChris Mason 
36635f39d397SChris Mason 		memmove_extent_buffer(right, btrfs_item_nr_offset(0),
36645f39d397SChris Mason 			      btrfs_item_nr_offset(push_items),
36655f39d397SChris Mason 			     (btrfs_header_nritems(right) - push_items) *
36660783fcfcSChris Mason 			     sizeof(struct btrfs_item));
366734a38218SChris Mason 	}
3668eef1c494SYan 	right_nritems -= push_items;
3669eef1c494SYan 	btrfs_set_header_nritems(right, right_nritems);
3670123abc88SChris Mason 	push_space = BTRFS_LEAF_DATA_SIZE(root);
36715f39d397SChris Mason 	for (i = 0; i < right_nritems; i++) {
36725f39d397SChris Mason 		item = btrfs_item_nr(right, i);
3673db94535dSChris Mason 
3674cfed81a0SChris Mason 		push_space = push_space - btrfs_token_item_size(right,
3675cfed81a0SChris Mason 								item, &token);
3676cfed81a0SChris Mason 		btrfs_set_token_item_offset(right, item, push_space, &token);
3677db94535dSChris Mason 	}
3678eb60ceacSChris Mason 
36795f39d397SChris Mason 	btrfs_mark_buffer_dirty(left);
368034a38218SChris Mason 	if (right_nritems)
36815f39d397SChris Mason 		btrfs_mark_buffer_dirty(right);
3682f0486c68SYan, Zheng 	else
3683f0486c68SYan, Zheng 		clean_tree_block(trans, root, right);
3684098f59c2SChris Mason 
36855f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
3686143bede5SJeff Mahoney 	fixup_low_keys(trans, root, path, &disk_key, 1);
3687be0e5c09SChris Mason 
3688be0e5c09SChris Mason 	/* then fixup the leaf pointer in the path */
3689be0e5c09SChris Mason 	if (path->slots[0] < push_items) {
3690be0e5c09SChris Mason 		path->slots[0] += old_left_nritems;
3691925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
36925f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
36935f39d397SChris Mason 		path->nodes[0] = left;
3694be0e5c09SChris Mason 		path->slots[1] -= 1;
3695be0e5c09SChris Mason 	} else {
3696925baeddSChris Mason 		btrfs_tree_unlock(left);
36975f39d397SChris Mason 		free_extent_buffer(left);
3698be0e5c09SChris Mason 		path->slots[0] -= push_items;
3699be0e5c09SChris Mason 	}
3700eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
3701aa5d6bedSChris Mason 	return ret;
3702925baeddSChris Mason out:
3703925baeddSChris Mason 	btrfs_tree_unlock(left);
3704925baeddSChris Mason 	free_extent_buffer(left);
3705925baeddSChris Mason 	return ret;
3706be0e5c09SChris Mason }
3707be0e5c09SChris Mason 
370874123bd7SChris Mason /*
370944871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
371044871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
371199d8f83cSChris Mason  *
371299d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
371399d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us push all the
371499d8f83cSChris Mason  * items
371544871b1bSChris Mason  */
371644871b1bSChris Mason static int push_leaf_left(struct btrfs_trans_handle *trans, struct btrfs_root
371799d8f83cSChris Mason 			  *root, struct btrfs_path *path, int min_data_size,
371899d8f83cSChris Mason 			  int data_size, int empty, u32 max_slot)
371944871b1bSChris Mason {
372044871b1bSChris Mason 	struct extent_buffer *right = path->nodes[0];
372144871b1bSChris Mason 	struct extent_buffer *left;
372244871b1bSChris Mason 	int slot;
372344871b1bSChris Mason 	int free_space;
372444871b1bSChris Mason 	u32 right_nritems;
372544871b1bSChris Mason 	int ret = 0;
372644871b1bSChris Mason 
372744871b1bSChris Mason 	slot = path->slots[1];
372844871b1bSChris Mason 	if (slot == 0)
372944871b1bSChris Mason 		return 1;
373044871b1bSChris Mason 	if (!path->nodes[1])
373144871b1bSChris Mason 		return 1;
373244871b1bSChris Mason 
373344871b1bSChris Mason 	right_nritems = btrfs_header_nritems(right);
373444871b1bSChris Mason 	if (right_nritems == 0)
373544871b1bSChris Mason 		return 1;
373644871b1bSChris Mason 
373744871b1bSChris Mason 	btrfs_assert_tree_locked(path->nodes[1]);
373844871b1bSChris Mason 
373944871b1bSChris Mason 	left = read_node_slot(root, path->nodes[1], slot - 1);
374091ca338dSTsutomu Itoh 	if (left == NULL)
374191ca338dSTsutomu Itoh 		return 1;
374291ca338dSTsutomu Itoh 
374344871b1bSChris Mason 	btrfs_tree_lock(left);
374444871b1bSChris Mason 	btrfs_set_lock_blocking(left);
374544871b1bSChris Mason 
374644871b1bSChris Mason 	free_space = btrfs_leaf_free_space(root, left);
374744871b1bSChris Mason 	if (free_space < data_size) {
374844871b1bSChris Mason 		ret = 1;
374944871b1bSChris Mason 		goto out;
375044871b1bSChris Mason 	}
375144871b1bSChris Mason 
375244871b1bSChris Mason 	/* cow and double check */
375344871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, left,
375444871b1bSChris Mason 			      path->nodes[1], slot - 1, &left);
375544871b1bSChris Mason 	if (ret) {
375644871b1bSChris Mason 		/* we hit -ENOSPC, but it isn't fatal here */
375779787eaaSJeff Mahoney 		if (ret == -ENOSPC)
375844871b1bSChris Mason 			ret = 1;
375944871b1bSChris Mason 		goto out;
376044871b1bSChris Mason 	}
376144871b1bSChris Mason 
376244871b1bSChris Mason 	free_space = btrfs_leaf_free_space(root, left);
376344871b1bSChris Mason 	if (free_space < data_size) {
376444871b1bSChris Mason 		ret = 1;
376544871b1bSChris Mason 		goto out;
376644871b1bSChris Mason 	}
376744871b1bSChris Mason 
376899d8f83cSChris Mason 	return __push_leaf_left(trans, root, path, min_data_size,
376999d8f83cSChris Mason 			       empty, left, free_space, right_nritems,
377099d8f83cSChris Mason 			       max_slot);
377144871b1bSChris Mason out:
377244871b1bSChris Mason 	btrfs_tree_unlock(left);
377344871b1bSChris Mason 	free_extent_buffer(left);
377444871b1bSChris Mason 	return ret;
377544871b1bSChris Mason }
377644871b1bSChris Mason 
377744871b1bSChris Mason /*
377874123bd7SChris Mason  * split the path's leaf in two, making sure there is at least data_size
377974123bd7SChris Mason  * available for the resulting leaf level of the path.
378074123bd7SChris Mason  */
3781143bede5SJeff Mahoney static noinline void copy_for_split(struct btrfs_trans_handle *trans,
3782e02119d5SChris Mason 				    struct btrfs_root *root,
378344871b1bSChris Mason 				    struct btrfs_path *path,
378444871b1bSChris Mason 				    struct extent_buffer *l,
378544871b1bSChris Mason 				    struct extent_buffer *right,
378644871b1bSChris Mason 				    int slot, int mid, int nritems)
3787be0e5c09SChris Mason {
3788be0e5c09SChris Mason 	int data_copy_size;
3789be0e5c09SChris Mason 	int rt_data_off;
3790be0e5c09SChris Mason 	int i;
3791d4dbff95SChris Mason 	struct btrfs_disk_key disk_key;
3792cfed81a0SChris Mason 	struct btrfs_map_token token;
3793cfed81a0SChris Mason 
3794cfed81a0SChris Mason 	btrfs_init_map_token(&token);
3795be0e5c09SChris Mason 
37965f39d397SChris Mason 	nritems = nritems - mid;
37975f39d397SChris Mason 	btrfs_set_header_nritems(right, nritems);
37985f39d397SChris Mason 	data_copy_size = btrfs_item_end_nr(l, mid) - leaf_data_end(root, l);
37995f39d397SChris Mason 
38005f39d397SChris Mason 	copy_extent_buffer(right, l, btrfs_item_nr_offset(0),
38015f39d397SChris Mason 			   btrfs_item_nr_offset(mid),
38025f39d397SChris Mason 			   nritems * sizeof(struct btrfs_item));
38035f39d397SChris Mason 
38045f39d397SChris Mason 	copy_extent_buffer(right, l,
3805d6025579SChris Mason 		     btrfs_leaf_data(right) + BTRFS_LEAF_DATA_SIZE(root) -
3806123abc88SChris Mason 		     data_copy_size, btrfs_leaf_data(l) +
3807123abc88SChris Mason 		     leaf_data_end(root, l), data_copy_size);
380874123bd7SChris Mason 
38095f39d397SChris Mason 	rt_data_off = BTRFS_LEAF_DATA_SIZE(root) -
38105f39d397SChris Mason 		      btrfs_item_end_nr(l, mid);
38115f39d397SChris Mason 
38125f39d397SChris Mason 	for (i = 0; i < nritems; i++) {
38135f39d397SChris Mason 		struct btrfs_item *item = btrfs_item_nr(right, i);
3814db94535dSChris Mason 		u32 ioff;
3815db94535dSChris Mason 
3816cfed81a0SChris Mason 		ioff = btrfs_token_item_offset(right, item, &token);
3817cfed81a0SChris Mason 		btrfs_set_token_item_offset(right, item,
3818cfed81a0SChris Mason 					    ioff + rt_data_off, &token);
38190783fcfcSChris Mason 	}
382074123bd7SChris Mason 
38215f39d397SChris Mason 	btrfs_set_header_nritems(l, mid);
38225f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
3823143bede5SJeff Mahoney 	insert_ptr(trans, root, path, &disk_key, right->start,
3824c3e06965SJan Schmidt 		   path->slots[1] + 1, 1);
38255f39d397SChris Mason 
38265f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
38275f39d397SChris Mason 	btrfs_mark_buffer_dirty(l);
3828eb60ceacSChris Mason 	BUG_ON(path->slots[0] != slot);
38295f39d397SChris Mason 
3830be0e5c09SChris Mason 	if (mid <= slot) {
3831925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
38325f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
38335f39d397SChris Mason 		path->nodes[0] = right;
3834be0e5c09SChris Mason 		path->slots[0] -= mid;
3835be0e5c09SChris Mason 		path->slots[1] += 1;
3836925baeddSChris Mason 	} else {
3837925baeddSChris Mason 		btrfs_tree_unlock(right);
38385f39d397SChris Mason 		free_extent_buffer(right);
3839925baeddSChris Mason 	}
38405f39d397SChris Mason 
3841eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
384244871b1bSChris Mason }
384344871b1bSChris Mason 
384444871b1bSChris Mason /*
384599d8f83cSChris Mason  * double splits happen when we need to insert a big item in the middle
384699d8f83cSChris Mason  * of a leaf.  A double split can leave us with 3 mostly empty leaves:
384799d8f83cSChris Mason  * leaf: [ slots 0 - N] [ our target ] [ N + 1 - total in leaf ]
384899d8f83cSChris Mason  *          A                 B                 C
384999d8f83cSChris Mason  *
385099d8f83cSChris Mason  * We avoid this by trying to push the items on either side of our target
385199d8f83cSChris Mason  * into the adjacent leaves.  If all goes well we can avoid the double split
385299d8f83cSChris Mason  * completely.
385399d8f83cSChris Mason  */
385499d8f83cSChris Mason static noinline int push_for_double_split(struct btrfs_trans_handle *trans,
385599d8f83cSChris Mason 					  struct btrfs_root *root,
385699d8f83cSChris Mason 					  struct btrfs_path *path,
385799d8f83cSChris Mason 					  int data_size)
385899d8f83cSChris Mason {
385999d8f83cSChris Mason 	int ret;
386099d8f83cSChris Mason 	int progress = 0;
386199d8f83cSChris Mason 	int slot;
386299d8f83cSChris Mason 	u32 nritems;
386399d8f83cSChris Mason 
386499d8f83cSChris Mason 	slot = path->slots[0];
386599d8f83cSChris Mason 
386699d8f83cSChris Mason 	/*
386799d8f83cSChris Mason 	 * try to push all the items after our slot into the
386899d8f83cSChris Mason 	 * right leaf
386999d8f83cSChris Mason 	 */
387099d8f83cSChris Mason 	ret = push_leaf_right(trans, root, path, 1, data_size, 0, slot);
387199d8f83cSChris Mason 	if (ret < 0)
387299d8f83cSChris Mason 		return ret;
387399d8f83cSChris Mason 
387499d8f83cSChris Mason 	if (ret == 0)
387599d8f83cSChris Mason 		progress++;
387699d8f83cSChris Mason 
387799d8f83cSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
387899d8f83cSChris Mason 	/*
387999d8f83cSChris Mason 	 * our goal is to get our slot at the start or end of a leaf.  If
388099d8f83cSChris Mason 	 * we've done so we're done
388199d8f83cSChris Mason 	 */
388299d8f83cSChris Mason 	if (path->slots[0] == 0 || path->slots[0] == nritems)
388399d8f83cSChris Mason 		return 0;
388499d8f83cSChris Mason 
388599d8f83cSChris Mason 	if (btrfs_leaf_free_space(root, path->nodes[0]) >= data_size)
388699d8f83cSChris Mason 		return 0;
388799d8f83cSChris Mason 
388899d8f83cSChris Mason 	/* try to push all the items before our slot into the next leaf */
388999d8f83cSChris Mason 	slot = path->slots[0];
389099d8f83cSChris Mason 	ret = push_leaf_left(trans, root, path, 1, data_size, 0, slot);
389199d8f83cSChris Mason 	if (ret < 0)
389299d8f83cSChris Mason 		return ret;
389399d8f83cSChris Mason 
389499d8f83cSChris Mason 	if (ret == 0)
389599d8f83cSChris Mason 		progress++;
389699d8f83cSChris Mason 
389799d8f83cSChris Mason 	if (progress)
389899d8f83cSChris Mason 		return 0;
389999d8f83cSChris Mason 	return 1;
390099d8f83cSChris Mason }
390199d8f83cSChris Mason 
390299d8f83cSChris Mason /*
390344871b1bSChris Mason  * split the path's leaf in two, making sure there is at least data_size
390444871b1bSChris Mason  * available for the resulting leaf level of the path.
390544871b1bSChris Mason  *
390644871b1bSChris Mason  * returns 0 if all went well and < 0 on failure.
390744871b1bSChris Mason  */
390844871b1bSChris Mason static noinline int split_leaf(struct btrfs_trans_handle *trans,
390944871b1bSChris Mason 			       struct btrfs_root *root,
391044871b1bSChris Mason 			       struct btrfs_key *ins_key,
391144871b1bSChris Mason 			       struct btrfs_path *path, int data_size,
391244871b1bSChris Mason 			       int extend)
391344871b1bSChris Mason {
39145d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
391544871b1bSChris Mason 	struct extent_buffer *l;
391644871b1bSChris Mason 	u32 nritems;
391744871b1bSChris Mason 	int mid;
391844871b1bSChris Mason 	int slot;
391944871b1bSChris Mason 	struct extent_buffer *right;
392044871b1bSChris Mason 	int ret = 0;
392144871b1bSChris Mason 	int wret;
39225d4f98a2SYan Zheng 	int split;
392344871b1bSChris Mason 	int num_doubles = 0;
392499d8f83cSChris Mason 	int tried_avoid_double = 0;
392544871b1bSChris Mason 
3926a5719521SYan, Zheng 	l = path->nodes[0];
3927a5719521SYan, Zheng 	slot = path->slots[0];
3928a5719521SYan, Zheng 	if (extend && data_size + btrfs_item_size_nr(l, slot) +
3929a5719521SYan, Zheng 	    sizeof(struct btrfs_item) > BTRFS_LEAF_DATA_SIZE(root))
3930a5719521SYan, Zheng 		return -EOVERFLOW;
3931a5719521SYan, Zheng 
393244871b1bSChris Mason 	/* first try to make some room by pushing left and right */
393399d8f83cSChris Mason 	if (data_size) {
393499d8f83cSChris Mason 		wret = push_leaf_right(trans, root, path, data_size,
393599d8f83cSChris Mason 				       data_size, 0, 0);
393644871b1bSChris Mason 		if (wret < 0)
393744871b1bSChris Mason 			return wret;
393844871b1bSChris Mason 		if (wret) {
393999d8f83cSChris Mason 			wret = push_leaf_left(trans, root, path, data_size,
394099d8f83cSChris Mason 					      data_size, 0, (u32)-1);
394144871b1bSChris Mason 			if (wret < 0)
394244871b1bSChris Mason 				return wret;
394344871b1bSChris Mason 		}
394444871b1bSChris Mason 		l = path->nodes[0];
394544871b1bSChris Mason 
394644871b1bSChris Mason 		/* did the pushes work? */
394744871b1bSChris Mason 		if (btrfs_leaf_free_space(root, l) >= data_size)
394844871b1bSChris Mason 			return 0;
394944871b1bSChris Mason 	}
395044871b1bSChris Mason 
395144871b1bSChris Mason 	if (!path->nodes[1]) {
395244871b1bSChris Mason 		ret = insert_new_root(trans, root, path, 1);
395344871b1bSChris Mason 		if (ret)
395444871b1bSChris Mason 			return ret;
395544871b1bSChris Mason 	}
395644871b1bSChris Mason again:
39575d4f98a2SYan Zheng 	split = 1;
395844871b1bSChris Mason 	l = path->nodes[0];
395944871b1bSChris Mason 	slot = path->slots[0];
396044871b1bSChris Mason 	nritems = btrfs_header_nritems(l);
396144871b1bSChris Mason 	mid = (nritems + 1) / 2;
396244871b1bSChris Mason 
39635d4f98a2SYan Zheng 	if (mid <= slot) {
39645d4f98a2SYan Zheng 		if (nritems == 1 ||
39655d4f98a2SYan Zheng 		    leaf_space_used(l, mid, nritems - mid) + data_size >
39665d4f98a2SYan Zheng 			BTRFS_LEAF_DATA_SIZE(root)) {
39675d4f98a2SYan Zheng 			if (slot >= nritems) {
39685d4f98a2SYan Zheng 				split = 0;
39695d4f98a2SYan Zheng 			} else {
39705d4f98a2SYan Zheng 				mid = slot;
39715d4f98a2SYan Zheng 				if (mid != nritems &&
39725d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
39735d4f98a2SYan Zheng 				    data_size > BTRFS_LEAF_DATA_SIZE(root)) {
397499d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
397599d8f83cSChris Mason 						goto push_for_double;
39765d4f98a2SYan Zheng 					split = 2;
39775d4f98a2SYan Zheng 				}
39785d4f98a2SYan Zheng 			}
39795d4f98a2SYan Zheng 		}
39805d4f98a2SYan Zheng 	} else {
39815d4f98a2SYan Zheng 		if (leaf_space_used(l, 0, mid) + data_size >
39825d4f98a2SYan Zheng 			BTRFS_LEAF_DATA_SIZE(root)) {
39835d4f98a2SYan Zheng 			if (!extend && data_size && slot == 0) {
39845d4f98a2SYan Zheng 				split = 0;
39855d4f98a2SYan Zheng 			} else if ((extend || !data_size) && slot == 0) {
39865d4f98a2SYan Zheng 				mid = 1;
39875d4f98a2SYan Zheng 			} else {
39885d4f98a2SYan Zheng 				mid = slot;
39895d4f98a2SYan Zheng 				if (mid != nritems &&
39905d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
39915d4f98a2SYan Zheng 				    data_size > BTRFS_LEAF_DATA_SIZE(root)) {
399299d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
399399d8f83cSChris Mason 						goto push_for_double;
39945d4f98a2SYan Zheng 					split = 2 ;
39955d4f98a2SYan Zheng 				}
39965d4f98a2SYan Zheng 			}
39975d4f98a2SYan Zheng 		}
39985d4f98a2SYan Zheng 	}
39995d4f98a2SYan Zheng 
40005d4f98a2SYan Zheng 	if (split == 0)
40015d4f98a2SYan Zheng 		btrfs_cpu_key_to_disk(&disk_key, ins_key);
40025d4f98a2SYan Zheng 	else
40035d4f98a2SYan Zheng 		btrfs_item_key(l, &disk_key, mid);
40045d4f98a2SYan Zheng 
40055d4f98a2SYan Zheng 	right = btrfs_alloc_free_block(trans, root, root->leafsize, 0,
400644871b1bSChris Mason 					root->root_key.objectid,
40075581a51aSJan Schmidt 					&disk_key, 0, l->start, 0);
4008f0486c68SYan, Zheng 	if (IS_ERR(right))
400944871b1bSChris Mason 		return PTR_ERR(right);
4010f0486c68SYan, Zheng 
4011f0486c68SYan, Zheng 	root_add_used(root, root->leafsize);
401244871b1bSChris Mason 
401344871b1bSChris Mason 	memset_extent_buffer(right, 0, 0, sizeof(struct btrfs_header));
401444871b1bSChris Mason 	btrfs_set_header_bytenr(right, right->start);
401544871b1bSChris Mason 	btrfs_set_header_generation(right, trans->transid);
40165d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(right, BTRFS_MIXED_BACKREF_REV);
401744871b1bSChris Mason 	btrfs_set_header_owner(right, root->root_key.objectid);
401844871b1bSChris Mason 	btrfs_set_header_level(right, 0);
401944871b1bSChris Mason 	write_extent_buffer(right, root->fs_info->fsid,
402044871b1bSChris Mason 			    (unsigned long)btrfs_header_fsid(right),
402144871b1bSChris Mason 			    BTRFS_FSID_SIZE);
402244871b1bSChris Mason 
402344871b1bSChris Mason 	write_extent_buffer(right, root->fs_info->chunk_tree_uuid,
402444871b1bSChris Mason 			    (unsigned long)btrfs_header_chunk_tree_uuid(right),
402544871b1bSChris Mason 			    BTRFS_UUID_SIZE);
402644871b1bSChris Mason 
40275d4f98a2SYan Zheng 	if (split == 0) {
402844871b1bSChris Mason 		if (mid <= slot) {
402944871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
4030143bede5SJeff Mahoney 			insert_ptr(trans, root, path, &disk_key, right->start,
4031c3e06965SJan Schmidt 				   path->slots[1] + 1, 1);
403244871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
403344871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
403444871b1bSChris Mason 			path->nodes[0] = right;
403544871b1bSChris Mason 			path->slots[0] = 0;
403644871b1bSChris Mason 			path->slots[1] += 1;
403744871b1bSChris Mason 		} else {
403844871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
4039143bede5SJeff Mahoney 			insert_ptr(trans, root, path, &disk_key, right->start,
4040c3e06965SJan Schmidt 					  path->slots[1], 1);
404144871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
404244871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
404344871b1bSChris Mason 			path->nodes[0] = right;
404444871b1bSChris Mason 			path->slots[0] = 0;
4045143bede5SJeff Mahoney 			if (path->slots[1] == 0)
4046143bede5SJeff Mahoney 				fixup_low_keys(trans, root, path,
4047143bede5SJeff Mahoney 					       &disk_key, 1);
40485d4f98a2SYan Zheng 		}
404944871b1bSChris Mason 		btrfs_mark_buffer_dirty(right);
405044871b1bSChris Mason 		return ret;
405144871b1bSChris Mason 	}
405244871b1bSChris Mason 
4053143bede5SJeff Mahoney 	copy_for_split(trans, root, path, l, right, slot, mid, nritems);
405444871b1bSChris Mason 
40555d4f98a2SYan Zheng 	if (split == 2) {
4056cc0c5538SChris Mason 		BUG_ON(num_doubles != 0);
4057cc0c5538SChris Mason 		num_doubles++;
4058cc0c5538SChris Mason 		goto again;
40593326d1b0SChris Mason 	}
406044871b1bSChris Mason 
4061143bede5SJeff Mahoney 	return 0;
406299d8f83cSChris Mason 
406399d8f83cSChris Mason push_for_double:
406499d8f83cSChris Mason 	push_for_double_split(trans, root, path, data_size);
406599d8f83cSChris Mason 	tried_avoid_double = 1;
406699d8f83cSChris Mason 	if (btrfs_leaf_free_space(root, path->nodes[0]) >= data_size)
406799d8f83cSChris Mason 		return 0;
406899d8f83cSChris Mason 	goto again;
4069be0e5c09SChris Mason }
4070be0e5c09SChris Mason 
4071ad48fd75SYan, Zheng static noinline int setup_leaf_for_split(struct btrfs_trans_handle *trans,
4072ad48fd75SYan, Zheng 					 struct btrfs_root *root,
4073ad48fd75SYan, Zheng 					 struct btrfs_path *path, int ins_len)
4074ad48fd75SYan, Zheng {
4075ad48fd75SYan, Zheng 	struct btrfs_key key;
4076ad48fd75SYan, Zheng 	struct extent_buffer *leaf;
4077ad48fd75SYan, Zheng 	struct btrfs_file_extent_item *fi;
4078ad48fd75SYan, Zheng 	u64 extent_len = 0;
4079ad48fd75SYan, Zheng 	u32 item_size;
4080ad48fd75SYan, Zheng 	int ret;
4081ad48fd75SYan, Zheng 
4082ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4083ad48fd75SYan, Zheng 	btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4084ad48fd75SYan, Zheng 
4085ad48fd75SYan, Zheng 	BUG_ON(key.type != BTRFS_EXTENT_DATA_KEY &&
4086ad48fd75SYan, Zheng 	       key.type != BTRFS_EXTENT_CSUM_KEY);
4087ad48fd75SYan, Zheng 
4088ad48fd75SYan, Zheng 	if (btrfs_leaf_free_space(root, leaf) >= ins_len)
4089ad48fd75SYan, Zheng 		return 0;
4090ad48fd75SYan, Zheng 
4091ad48fd75SYan, Zheng 	item_size = btrfs_item_size_nr(leaf, path->slots[0]);
4092ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
4093ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
4094ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
4095ad48fd75SYan, Zheng 		extent_len = btrfs_file_extent_num_bytes(leaf, fi);
4096ad48fd75SYan, Zheng 	}
4097b3b4aa74SDavid Sterba 	btrfs_release_path(path);
4098ad48fd75SYan, Zheng 
4099ad48fd75SYan, Zheng 	path->keep_locks = 1;
4100ad48fd75SYan, Zheng 	path->search_for_split = 1;
4101ad48fd75SYan, Zheng 	ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
4102ad48fd75SYan, Zheng 	path->search_for_split = 0;
4103ad48fd75SYan, Zheng 	if (ret < 0)
4104ad48fd75SYan, Zheng 		goto err;
4105ad48fd75SYan, Zheng 
4106ad48fd75SYan, Zheng 	ret = -EAGAIN;
4107ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4108ad48fd75SYan, Zheng 	/* if our item isn't there or got smaller, return now */
4109ad48fd75SYan, Zheng 	if (ret > 0 || item_size != btrfs_item_size_nr(leaf, path->slots[0]))
4110ad48fd75SYan, Zheng 		goto err;
4111ad48fd75SYan, Zheng 
4112109f6aefSChris Mason 	/* the leaf has  changed, it now has room.  return now */
4113109f6aefSChris Mason 	if (btrfs_leaf_free_space(root, path->nodes[0]) >= ins_len)
4114109f6aefSChris Mason 		goto err;
4115109f6aefSChris Mason 
4116ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
4117ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
4118ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
4119ad48fd75SYan, Zheng 		if (extent_len != btrfs_file_extent_num_bytes(leaf, fi))
4120ad48fd75SYan, Zheng 			goto err;
4121ad48fd75SYan, Zheng 	}
4122ad48fd75SYan, Zheng 
4123ad48fd75SYan, Zheng 	btrfs_set_path_blocking(path);
4124ad48fd75SYan, Zheng 	ret = split_leaf(trans, root, &key, path, ins_len, 1);
4125f0486c68SYan, Zheng 	if (ret)
4126f0486c68SYan, Zheng 		goto err;
4127ad48fd75SYan, Zheng 
4128ad48fd75SYan, Zheng 	path->keep_locks = 0;
4129ad48fd75SYan, Zheng 	btrfs_unlock_up_safe(path, 1);
4130ad48fd75SYan, Zheng 	return 0;
4131ad48fd75SYan, Zheng err:
4132ad48fd75SYan, Zheng 	path->keep_locks = 0;
4133ad48fd75SYan, Zheng 	return ret;
4134ad48fd75SYan, Zheng }
4135ad48fd75SYan, Zheng 
4136ad48fd75SYan, Zheng static noinline int split_item(struct btrfs_trans_handle *trans,
4137459931ecSChris Mason 			       struct btrfs_root *root,
4138459931ecSChris Mason 			       struct btrfs_path *path,
4139459931ecSChris Mason 			       struct btrfs_key *new_key,
4140459931ecSChris Mason 			       unsigned long split_offset)
4141459931ecSChris Mason {
4142459931ecSChris Mason 	struct extent_buffer *leaf;
4143459931ecSChris Mason 	struct btrfs_item *item;
4144459931ecSChris Mason 	struct btrfs_item *new_item;
4145459931ecSChris Mason 	int slot;
4146ad48fd75SYan, Zheng 	char *buf;
4147459931ecSChris Mason 	u32 nritems;
4148ad48fd75SYan, Zheng 	u32 item_size;
4149459931ecSChris Mason 	u32 orig_offset;
4150459931ecSChris Mason 	struct btrfs_disk_key disk_key;
4151459931ecSChris Mason 
4152459931ecSChris Mason 	leaf = path->nodes[0];
4153b9473439SChris Mason 	BUG_ON(btrfs_leaf_free_space(root, leaf) < sizeof(struct btrfs_item));
4154b9473439SChris Mason 
4155b4ce94deSChris Mason 	btrfs_set_path_blocking(path);
4156b4ce94deSChris Mason 
4157459931ecSChris Mason 	item = btrfs_item_nr(leaf, path->slots[0]);
4158459931ecSChris Mason 	orig_offset = btrfs_item_offset(leaf, item);
4159459931ecSChris Mason 	item_size = btrfs_item_size(leaf, item);
4160459931ecSChris Mason 
4161459931ecSChris Mason 	buf = kmalloc(item_size, GFP_NOFS);
4162ad48fd75SYan, Zheng 	if (!buf)
4163ad48fd75SYan, Zheng 		return -ENOMEM;
4164ad48fd75SYan, Zheng 
4165459931ecSChris Mason 	read_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf,
4166459931ecSChris Mason 			    path->slots[0]), item_size);
4167ad48fd75SYan, Zheng 
4168459931ecSChris Mason 	slot = path->slots[0] + 1;
4169459931ecSChris Mason 	nritems = btrfs_header_nritems(leaf);
4170459931ecSChris Mason 	if (slot != nritems) {
4171459931ecSChris Mason 		/* shift the items */
4172459931ecSChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + 1),
4173459931ecSChris Mason 				btrfs_item_nr_offset(slot),
4174459931ecSChris Mason 				(nritems - slot) * sizeof(struct btrfs_item));
4175459931ecSChris Mason 	}
4176459931ecSChris Mason 
4177459931ecSChris Mason 	btrfs_cpu_key_to_disk(&disk_key, new_key);
4178459931ecSChris Mason 	btrfs_set_item_key(leaf, &disk_key, slot);
4179459931ecSChris Mason 
4180459931ecSChris Mason 	new_item = btrfs_item_nr(leaf, slot);
4181459931ecSChris Mason 
4182459931ecSChris Mason 	btrfs_set_item_offset(leaf, new_item, orig_offset);
4183459931ecSChris Mason 	btrfs_set_item_size(leaf, new_item, item_size - split_offset);
4184459931ecSChris Mason 
4185459931ecSChris Mason 	btrfs_set_item_offset(leaf, item,
4186459931ecSChris Mason 			      orig_offset + item_size - split_offset);
4187459931ecSChris Mason 	btrfs_set_item_size(leaf, item, split_offset);
4188459931ecSChris Mason 
4189459931ecSChris Mason 	btrfs_set_header_nritems(leaf, nritems + 1);
4190459931ecSChris Mason 
4191459931ecSChris Mason 	/* write the data for the start of the original item */
4192459931ecSChris Mason 	write_extent_buffer(leaf, buf,
4193459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, path->slots[0]),
4194459931ecSChris Mason 			    split_offset);
4195459931ecSChris Mason 
4196459931ecSChris Mason 	/* write the data for the new item */
4197459931ecSChris Mason 	write_extent_buffer(leaf, buf + split_offset,
4198459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, slot),
4199459931ecSChris Mason 			    item_size - split_offset);
4200459931ecSChris Mason 	btrfs_mark_buffer_dirty(leaf);
4201459931ecSChris Mason 
4202ad48fd75SYan, Zheng 	BUG_ON(btrfs_leaf_free_space(root, leaf) < 0);
4203459931ecSChris Mason 	kfree(buf);
4204ad48fd75SYan, Zheng 	return 0;
4205ad48fd75SYan, Zheng }
4206ad48fd75SYan, Zheng 
4207ad48fd75SYan, Zheng /*
4208ad48fd75SYan, Zheng  * This function splits a single item into two items,
4209ad48fd75SYan, Zheng  * giving 'new_key' to the new item and splitting the
4210ad48fd75SYan, Zheng  * old one at split_offset (from the start of the item).
4211ad48fd75SYan, Zheng  *
4212ad48fd75SYan, Zheng  * The path may be released by this operation.  After
4213ad48fd75SYan, Zheng  * the split, the path is pointing to the old item.  The
4214ad48fd75SYan, Zheng  * new item is going to be in the same node as the old one.
4215ad48fd75SYan, Zheng  *
4216ad48fd75SYan, Zheng  * Note, the item being split must be smaller enough to live alone on
4217ad48fd75SYan, Zheng  * a tree block with room for one extra struct btrfs_item
4218ad48fd75SYan, Zheng  *
4219ad48fd75SYan, Zheng  * This allows us to split the item in place, keeping a lock on the
4220ad48fd75SYan, Zheng  * leaf the entire time.
4221ad48fd75SYan, Zheng  */
4222ad48fd75SYan, Zheng int btrfs_split_item(struct btrfs_trans_handle *trans,
4223ad48fd75SYan, Zheng 		     struct btrfs_root *root,
4224ad48fd75SYan, Zheng 		     struct btrfs_path *path,
4225ad48fd75SYan, Zheng 		     struct btrfs_key *new_key,
4226ad48fd75SYan, Zheng 		     unsigned long split_offset)
4227ad48fd75SYan, Zheng {
4228ad48fd75SYan, Zheng 	int ret;
4229ad48fd75SYan, Zheng 	ret = setup_leaf_for_split(trans, root, path,
4230ad48fd75SYan, Zheng 				   sizeof(struct btrfs_item));
4231ad48fd75SYan, Zheng 	if (ret)
4232459931ecSChris Mason 		return ret;
4233ad48fd75SYan, Zheng 
4234ad48fd75SYan, Zheng 	ret = split_item(trans, root, path, new_key, split_offset);
4235ad48fd75SYan, Zheng 	return ret;
4236ad48fd75SYan, Zheng }
4237ad48fd75SYan, Zheng 
4238ad48fd75SYan, Zheng /*
4239ad48fd75SYan, Zheng  * This function duplicate a item, giving 'new_key' to the new item.
4240ad48fd75SYan, Zheng  * It guarantees both items live in the same tree leaf and the new item
4241ad48fd75SYan, Zheng  * is contiguous with the original item.
4242ad48fd75SYan, Zheng  *
4243ad48fd75SYan, Zheng  * This allows us to split file extent in place, keeping a lock on the
4244ad48fd75SYan, Zheng  * leaf the entire time.
4245ad48fd75SYan, Zheng  */
4246ad48fd75SYan, Zheng int btrfs_duplicate_item(struct btrfs_trans_handle *trans,
4247ad48fd75SYan, Zheng 			 struct btrfs_root *root,
4248ad48fd75SYan, Zheng 			 struct btrfs_path *path,
4249ad48fd75SYan, Zheng 			 struct btrfs_key *new_key)
4250ad48fd75SYan, Zheng {
4251ad48fd75SYan, Zheng 	struct extent_buffer *leaf;
4252ad48fd75SYan, Zheng 	int ret;
4253ad48fd75SYan, Zheng 	u32 item_size;
4254ad48fd75SYan, Zheng 
4255ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4256ad48fd75SYan, Zheng 	item_size = btrfs_item_size_nr(leaf, path->slots[0]);
4257ad48fd75SYan, Zheng 	ret = setup_leaf_for_split(trans, root, path,
4258ad48fd75SYan, Zheng 				   item_size + sizeof(struct btrfs_item));
4259ad48fd75SYan, Zheng 	if (ret)
4260ad48fd75SYan, Zheng 		return ret;
4261ad48fd75SYan, Zheng 
4262ad48fd75SYan, Zheng 	path->slots[0]++;
4263143bede5SJeff Mahoney 	setup_items_for_insert(trans, root, path, new_key, &item_size,
4264ad48fd75SYan, Zheng 			       item_size, item_size +
4265ad48fd75SYan, Zheng 			       sizeof(struct btrfs_item), 1);
4266ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4267ad48fd75SYan, Zheng 	memcpy_extent_buffer(leaf,
4268ad48fd75SYan, Zheng 			     btrfs_item_ptr_offset(leaf, path->slots[0]),
4269ad48fd75SYan, Zheng 			     btrfs_item_ptr_offset(leaf, path->slots[0] - 1),
4270ad48fd75SYan, Zheng 			     item_size);
4271ad48fd75SYan, Zheng 	return 0;
4272459931ecSChris Mason }
4273459931ecSChris Mason 
4274459931ecSChris Mason /*
4275d352ac68SChris Mason  * make the item pointed to by the path smaller.  new_size indicates
4276d352ac68SChris Mason  * how small to make it, and from_end tells us if we just chop bytes
4277d352ac68SChris Mason  * off the end of the item or if we shift the item to chop bytes off
4278d352ac68SChris Mason  * the front.
4279d352ac68SChris Mason  */
4280143bede5SJeff Mahoney void btrfs_truncate_item(struct btrfs_trans_handle *trans,
4281b18c6685SChris Mason 			 struct btrfs_root *root,
4282b18c6685SChris Mason 			 struct btrfs_path *path,
4283179e29e4SChris Mason 			 u32 new_size, int from_end)
4284b18c6685SChris Mason {
4285b18c6685SChris Mason 	int slot;
42865f39d397SChris Mason 	struct extent_buffer *leaf;
42875f39d397SChris Mason 	struct btrfs_item *item;
4288b18c6685SChris Mason 	u32 nritems;
4289b18c6685SChris Mason 	unsigned int data_end;
4290b18c6685SChris Mason 	unsigned int old_data_start;
4291b18c6685SChris Mason 	unsigned int old_size;
4292b18c6685SChris Mason 	unsigned int size_diff;
4293b18c6685SChris Mason 	int i;
4294cfed81a0SChris Mason 	struct btrfs_map_token token;
4295cfed81a0SChris Mason 
4296cfed81a0SChris Mason 	btrfs_init_map_token(&token);
4297b18c6685SChris Mason 
42985f39d397SChris Mason 	leaf = path->nodes[0];
4299179e29e4SChris Mason 	slot = path->slots[0];
4300179e29e4SChris Mason 
4301179e29e4SChris Mason 	old_size = btrfs_item_size_nr(leaf, slot);
4302179e29e4SChris Mason 	if (old_size == new_size)
4303143bede5SJeff Mahoney 		return;
4304b18c6685SChris Mason 
43055f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
4306b18c6685SChris Mason 	data_end = leaf_data_end(root, leaf);
4307b18c6685SChris Mason 
43085f39d397SChris Mason 	old_data_start = btrfs_item_offset_nr(leaf, slot);
4309179e29e4SChris Mason 
4310b18c6685SChris Mason 	size_diff = old_size - new_size;
4311b18c6685SChris Mason 
4312b18c6685SChris Mason 	BUG_ON(slot < 0);
4313b18c6685SChris Mason 	BUG_ON(slot >= nritems);
4314b18c6685SChris Mason 
4315b18c6685SChris Mason 	/*
4316b18c6685SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4317b18c6685SChris Mason 	 */
4318b18c6685SChris Mason 	/* first correct the data pointers */
4319b18c6685SChris Mason 	for (i = slot; i < nritems; i++) {
43205f39d397SChris Mason 		u32 ioff;
43215f39d397SChris Mason 		item = btrfs_item_nr(leaf, i);
4322db94535dSChris Mason 
4323cfed81a0SChris Mason 		ioff = btrfs_token_item_offset(leaf, item, &token);
4324cfed81a0SChris Mason 		btrfs_set_token_item_offset(leaf, item,
4325cfed81a0SChris Mason 					    ioff + size_diff, &token);
4326b18c6685SChris Mason 	}
4327db94535dSChris Mason 
4328b18c6685SChris Mason 	/* shift the data */
4329179e29e4SChris Mason 	if (from_end) {
43305f39d397SChris Mason 		memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
4331b18c6685SChris Mason 			      data_end + size_diff, btrfs_leaf_data(leaf) +
4332b18c6685SChris Mason 			      data_end, old_data_start + new_size - data_end);
4333179e29e4SChris Mason 	} else {
4334179e29e4SChris Mason 		struct btrfs_disk_key disk_key;
4335179e29e4SChris Mason 		u64 offset;
4336179e29e4SChris Mason 
4337179e29e4SChris Mason 		btrfs_item_key(leaf, &disk_key, slot);
4338179e29e4SChris Mason 
4339179e29e4SChris Mason 		if (btrfs_disk_key_type(&disk_key) == BTRFS_EXTENT_DATA_KEY) {
4340179e29e4SChris Mason 			unsigned long ptr;
4341179e29e4SChris Mason 			struct btrfs_file_extent_item *fi;
4342179e29e4SChris Mason 
4343179e29e4SChris Mason 			fi = btrfs_item_ptr(leaf, slot,
4344179e29e4SChris Mason 					    struct btrfs_file_extent_item);
4345179e29e4SChris Mason 			fi = (struct btrfs_file_extent_item *)(
4346179e29e4SChris Mason 			     (unsigned long)fi - size_diff);
4347179e29e4SChris Mason 
4348179e29e4SChris Mason 			if (btrfs_file_extent_type(leaf, fi) ==
4349179e29e4SChris Mason 			    BTRFS_FILE_EXTENT_INLINE) {
4350179e29e4SChris Mason 				ptr = btrfs_item_ptr_offset(leaf, slot);
4351179e29e4SChris Mason 				memmove_extent_buffer(leaf, ptr,
4352179e29e4SChris Mason 				      (unsigned long)fi,
4353179e29e4SChris Mason 				      offsetof(struct btrfs_file_extent_item,
4354179e29e4SChris Mason 						 disk_bytenr));
4355179e29e4SChris Mason 			}
4356179e29e4SChris Mason 		}
4357179e29e4SChris Mason 
4358179e29e4SChris Mason 		memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
4359179e29e4SChris Mason 			      data_end + size_diff, btrfs_leaf_data(leaf) +
4360179e29e4SChris Mason 			      data_end, old_data_start - data_end);
4361179e29e4SChris Mason 
4362179e29e4SChris Mason 		offset = btrfs_disk_key_offset(&disk_key);
4363179e29e4SChris Mason 		btrfs_set_disk_key_offset(&disk_key, offset + size_diff);
4364179e29e4SChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot);
4365179e29e4SChris Mason 		if (slot == 0)
4366179e29e4SChris Mason 			fixup_low_keys(trans, root, path, &disk_key, 1);
4367179e29e4SChris Mason 	}
43685f39d397SChris Mason 
43695f39d397SChris Mason 	item = btrfs_item_nr(leaf, slot);
43705f39d397SChris Mason 	btrfs_set_item_size(leaf, item, new_size);
43715f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
4372b18c6685SChris Mason 
43735f39d397SChris Mason 	if (btrfs_leaf_free_space(root, leaf) < 0) {
43745f39d397SChris Mason 		btrfs_print_leaf(root, leaf);
4375b18c6685SChris Mason 		BUG();
43765f39d397SChris Mason 	}
4377b18c6685SChris Mason }
4378b18c6685SChris Mason 
4379d352ac68SChris Mason /*
4380d352ac68SChris Mason  * make the item pointed to by the path bigger, data_size is the new size.
4381d352ac68SChris Mason  */
4382143bede5SJeff Mahoney void btrfs_extend_item(struct btrfs_trans_handle *trans,
43835f39d397SChris Mason 		       struct btrfs_root *root, struct btrfs_path *path,
43845f39d397SChris Mason 		       u32 data_size)
43856567e837SChris Mason {
43866567e837SChris Mason 	int slot;
43875f39d397SChris Mason 	struct extent_buffer *leaf;
43885f39d397SChris Mason 	struct btrfs_item *item;
43896567e837SChris Mason 	u32 nritems;
43906567e837SChris Mason 	unsigned int data_end;
43916567e837SChris Mason 	unsigned int old_data;
43926567e837SChris Mason 	unsigned int old_size;
43936567e837SChris Mason 	int i;
4394cfed81a0SChris Mason 	struct btrfs_map_token token;
4395cfed81a0SChris Mason 
4396cfed81a0SChris Mason 	btrfs_init_map_token(&token);
43976567e837SChris Mason 
43985f39d397SChris Mason 	leaf = path->nodes[0];
43996567e837SChris Mason 
44005f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
44016567e837SChris Mason 	data_end = leaf_data_end(root, leaf);
44026567e837SChris Mason 
44035f39d397SChris Mason 	if (btrfs_leaf_free_space(root, leaf) < data_size) {
44045f39d397SChris Mason 		btrfs_print_leaf(root, leaf);
44056567e837SChris Mason 		BUG();
44065f39d397SChris Mason 	}
44076567e837SChris Mason 	slot = path->slots[0];
44085f39d397SChris Mason 	old_data = btrfs_item_end_nr(leaf, slot);
44096567e837SChris Mason 
44106567e837SChris Mason 	BUG_ON(slot < 0);
44113326d1b0SChris Mason 	if (slot >= nritems) {
44123326d1b0SChris Mason 		btrfs_print_leaf(root, leaf);
4413d397712bSChris Mason 		printk(KERN_CRIT "slot %d too large, nritems %d\n",
4414d397712bSChris Mason 		       slot, nritems);
44153326d1b0SChris Mason 		BUG_ON(1);
44163326d1b0SChris Mason 	}
44176567e837SChris Mason 
44186567e837SChris Mason 	/*
44196567e837SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
44206567e837SChris Mason 	 */
44216567e837SChris Mason 	/* first correct the data pointers */
44226567e837SChris Mason 	for (i = slot; i < nritems; i++) {
44235f39d397SChris Mason 		u32 ioff;
44245f39d397SChris Mason 		item = btrfs_item_nr(leaf, i);
4425db94535dSChris Mason 
4426cfed81a0SChris Mason 		ioff = btrfs_token_item_offset(leaf, item, &token);
4427cfed81a0SChris Mason 		btrfs_set_token_item_offset(leaf, item,
4428cfed81a0SChris Mason 					    ioff - data_size, &token);
44296567e837SChris Mason 	}
44305f39d397SChris Mason 
44316567e837SChris Mason 	/* shift the data */
44325f39d397SChris Mason 	memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
44336567e837SChris Mason 		      data_end - data_size, btrfs_leaf_data(leaf) +
44346567e837SChris Mason 		      data_end, old_data - data_end);
44355f39d397SChris Mason 
44366567e837SChris Mason 	data_end = old_data;
44375f39d397SChris Mason 	old_size = btrfs_item_size_nr(leaf, slot);
44385f39d397SChris Mason 	item = btrfs_item_nr(leaf, slot);
44395f39d397SChris Mason 	btrfs_set_item_size(leaf, item, old_size + data_size);
44405f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
44416567e837SChris Mason 
44425f39d397SChris Mason 	if (btrfs_leaf_free_space(root, leaf) < 0) {
44435f39d397SChris Mason 		btrfs_print_leaf(root, leaf);
44446567e837SChris Mason 		BUG();
44455f39d397SChris Mason 	}
44466567e837SChris Mason }
44476567e837SChris Mason 
444874123bd7SChris Mason /*
444944871b1bSChris Mason  * this is a helper for btrfs_insert_empty_items, the main goal here is
445044871b1bSChris Mason  * to save stack depth by doing the bulk of the work in a function
445144871b1bSChris Mason  * that doesn't call btrfs_search_slot
445274123bd7SChris Mason  */
4453143bede5SJeff Mahoney void setup_items_for_insert(struct btrfs_trans_handle *trans,
445444871b1bSChris Mason 			    struct btrfs_root *root, struct btrfs_path *path,
44559c58309dSChris Mason 			    struct btrfs_key *cpu_key, u32 *data_size,
445644871b1bSChris Mason 			    u32 total_data, u32 total_size, int nr)
4457be0e5c09SChris Mason {
44585f39d397SChris Mason 	struct btrfs_item *item;
44599c58309dSChris Mason 	int i;
44607518a238SChris Mason 	u32 nritems;
4461be0e5c09SChris Mason 	unsigned int data_end;
4462e2fa7227SChris Mason 	struct btrfs_disk_key disk_key;
446344871b1bSChris Mason 	struct extent_buffer *leaf;
446444871b1bSChris Mason 	int slot;
4465cfed81a0SChris Mason 	struct btrfs_map_token token;
4466cfed81a0SChris Mason 
4467cfed81a0SChris Mason 	btrfs_init_map_token(&token);
4468e2fa7227SChris Mason 
44695f39d397SChris Mason 	leaf = path->nodes[0];
447044871b1bSChris Mason 	slot = path->slots[0];
447174123bd7SChris Mason 
44725f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
4473123abc88SChris Mason 	data_end = leaf_data_end(root, leaf);
4474eb60ceacSChris Mason 
4475f25956ccSChris Mason 	if (btrfs_leaf_free_space(root, leaf) < total_size) {
44763326d1b0SChris Mason 		btrfs_print_leaf(root, leaf);
4477d397712bSChris Mason 		printk(KERN_CRIT "not enough freespace need %u have %d\n",
44789c58309dSChris Mason 		       total_size, btrfs_leaf_free_space(root, leaf));
4479be0e5c09SChris Mason 		BUG();
4480d4dbff95SChris Mason 	}
44815f39d397SChris Mason 
4482be0e5c09SChris Mason 	if (slot != nritems) {
44835f39d397SChris Mason 		unsigned int old_data = btrfs_item_end_nr(leaf, slot);
4484be0e5c09SChris Mason 
44855f39d397SChris Mason 		if (old_data < data_end) {
44865f39d397SChris Mason 			btrfs_print_leaf(root, leaf);
4487d397712bSChris Mason 			printk(KERN_CRIT "slot %d old_data %d data_end %d\n",
44885f39d397SChris Mason 			       slot, old_data, data_end);
44895f39d397SChris Mason 			BUG_ON(1);
44905f39d397SChris Mason 		}
4491be0e5c09SChris Mason 		/*
4492be0e5c09SChris Mason 		 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4493be0e5c09SChris Mason 		 */
4494be0e5c09SChris Mason 		/* first correct the data pointers */
44950783fcfcSChris Mason 		for (i = slot; i < nritems; i++) {
44965f39d397SChris Mason 			u32 ioff;
4497db94535dSChris Mason 
44985f39d397SChris Mason 			item = btrfs_item_nr(leaf, i);
4499cfed81a0SChris Mason 			ioff = btrfs_token_item_offset(leaf, item, &token);
4500cfed81a0SChris Mason 			btrfs_set_token_item_offset(leaf, item,
4501cfed81a0SChris Mason 						    ioff - total_data, &token);
45020783fcfcSChris Mason 		}
4503be0e5c09SChris Mason 		/* shift the items */
45049c58309dSChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + nr),
45055f39d397SChris Mason 			      btrfs_item_nr_offset(slot),
45060783fcfcSChris Mason 			      (nritems - slot) * sizeof(struct btrfs_item));
4507be0e5c09SChris Mason 
4508be0e5c09SChris Mason 		/* shift the data */
45095f39d397SChris Mason 		memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
45109c58309dSChris Mason 			      data_end - total_data, btrfs_leaf_data(leaf) +
4511be0e5c09SChris Mason 			      data_end, old_data - data_end);
4512be0e5c09SChris Mason 		data_end = old_data;
4513be0e5c09SChris Mason 	}
45145f39d397SChris Mason 
451562e2749eSChris Mason 	/* setup the item for the new data */
45169c58309dSChris Mason 	for (i = 0; i < nr; i++) {
45179c58309dSChris Mason 		btrfs_cpu_key_to_disk(&disk_key, cpu_key + i);
45189c58309dSChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot + i);
45199c58309dSChris Mason 		item = btrfs_item_nr(leaf, slot + i);
4520cfed81a0SChris Mason 		btrfs_set_token_item_offset(leaf, item,
4521cfed81a0SChris Mason 					    data_end - data_size[i], &token);
45229c58309dSChris Mason 		data_end -= data_size[i];
4523cfed81a0SChris Mason 		btrfs_set_token_item_size(leaf, item, data_size[i], &token);
45249c58309dSChris Mason 	}
452544871b1bSChris Mason 
45269c58309dSChris Mason 	btrfs_set_header_nritems(leaf, nritems + nr);
4527aa5d6bedSChris Mason 
45285a01a2e3SChris Mason 	if (slot == 0) {
45295a01a2e3SChris Mason 		btrfs_cpu_key_to_disk(&disk_key, cpu_key);
4530143bede5SJeff Mahoney 		fixup_low_keys(trans, root, path, &disk_key, 1);
45315a01a2e3SChris Mason 	}
4532b9473439SChris Mason 	btrfs_unlock_up_safe(path, 1);
4533b9473439SChris Mason 	btrfs_mark_buffer_dirty(leaf);
4534aa5d6bedSChris Mason 
45355f39d397SChris Mason 	if (btrfs_leaf_free_space(root, leaf) < 0) {
45365f39d397SChris Mason 		btrfs_print_leaf(root, leaf);
4537be0e5c09SChris Mason 		BUG();
45385f39d397SChris Mason 	}
453944871b1bSChris Mason }
454044871b1bSChris Mason 
454144871b1bSChris Mason /*
454244871b1bSChris Mason  * Given a key and some data, insert items into the tree.
454344871b1bSChris Mason  * This does all the path init required, making room in the tree if needed.
454444871b1bSChris Mason  */
454544871b1bSChris Mason int btrfs_insert_empty_items(struct btrfs_trans_handle *trans,
454644871b1bSChris Mason 			    struct btrfs_root *root,
454744871b1bSChris Mason 			    struct btrfs_path *path,
454844871b1bSChris Mason 			    struct btrfs_key *cpu_key, u32 *data_size,
454944871b1bSChris Mason 			    int nr)
455044871b1bSChris Mason {
455144871b1bSChris Mason 	int ret = 0;
455244871b1bSChris Mason 	int slot;
455344871b1bSChris Mason 	int i;
455444871b1bSChris Mason 	u32 total_size = 0;
455544871b1bSChris Mason 	u32 total_data = 0;
455644871b1bSChris Mason 
455744871b1bSChris Mason 	for (i = 0; i < nr; i++)
455844871b1bSChris Mason 		total_data += data_size[i];
455944871b1bSChris Mason 
456044871b1bSChris Mason 	total_size = total_data + (nr * sizeof(struct btrfs_item));
456144871b1bSChris Mason 	ret = btrfs_search_slot(trans, root, cpu_key, path, total_size, 1);
456244871b1bSChris Mason 	if (ret == 0)
456344871b1bSChris Mason 		return -EEXIST;
456444871b1bSChris Mason 	if (ret < 0)
4565143bede5SJeff Mahoney 		return ret;
456644871b1bSChris Mason 
456744871b1bSChris Mason 	slot = path->slots[0];
456844871b1bSChris Mason 	BUG_ON(slot < 0);
456944871b1bSChris Mason 
4570143bede5SJeff Mahoney 	setup_items_for_insert(trans, root, path, cpu_key, data_size,
457144871b1bSChris Mason 			       total_data, total_size, nr);
4572143bede5SJeff Mahoney 	return 0;
457362e2749eSChris Mason }
457462e2749eSChris Mason 
457562e2749eSChris Mason /*
457662e2749eSChris Mason  * Given a key and some data, insert an item into the tree.
457762e2749eSChris Mason  * This does all the path init required, making room in the tree if needed.
457862e2749eSChris Mason  */
4579e089f05cSChris Mason int btrfs_insert_item(struct btrfs_trans_handle *trans, struct btrfs_root
4580e089f05cSChris Mason 		      *root, struct btrfs_key *cpu_key, void *data, u32
4581e089f05cSChris Mason 		      data_size)
458262e2749eSChris Mason {
458362e2749eSChris Mason 	int ret = 0;
45842c90e5d6SChris Mason 	struct btrfs_path *path;
45855f39d397SChris Mason 	struct extent_buffer *leaf;
45865f39d397SChris Mason 	unsigned long ptr;
458762e2749eSChris Mason 
45882c90e5d6SChris Mason 	path = btrfs_alloc_path();
4589db5b493aSTsutomu Itoh 	if (!path)
4590db5b493aSTsutomu Itoh 		return -ENOMEM;
45912c90e5d6SChris Mason 	ret = btrfs_insert_empty_item(trans, root, path, cpu_key, data_size);
459262e2749eSChris Mason 	if (!ret) {
45935f39d397SChris Mason 		leaf = path->nodes[0];
45945f39d397SChris Mason 		ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
45955f39d397SChris Mason 		write_extent_buffer(leaf, data, ptr, data_size);
45965f39d397SChris Mason 		btrfs_mark_buffer_dirty(leaf);
459762e2749eSChris Mason 	}
45982c90e5d6SChris Mason 	btrfs_free_path(path);
4599aa5d6bedSChris Mason 	return ret;
4600be0e5c09SChris Mason }
4601be0e5c09SChris Mason 
460274123bd7SChris Mason /*
46035de08d7dSChris Mason  * delete the pointer from a given node.
460474123bd7SChris Mason  *
4605d352ac68SChris Mason  * the tree should have been previously balanced so the deletion does not
4606d352ac68SChris Mason  * empty a node.
460774123bd7SChris Mason  */
4608143bede5SJeff Mahoney static void del_ptr(struct btrfs_trans_handle *trans, struct btrfs_root *root,
46090e411eceSLiu Bo 		    struct btrfs_path *path, int level, int slot)
4610be0e5c09SChris Mason {
46115f39d397SChris Mason 	struct extent_buffer *parent = path->nodes[level];
46127518a238SChris Mason 	u32 nritems;
4613f3ea38daSJan Schmidt 	int ret;
4614be0e5c09SChris Mason 
46155f39d397SChris Mason 	nritems = btrfs_header_nritems(parent);
4616be0e5c09SChris Mason 	if (slot != nritems - 1) {
46170e411eceSLiu Bo 		if (level)
4618f3ea38daSJan Schmidt 			tree_mod_log_eb_move(root->fs_info, parent, slot,
4619f3ea38daSJan Schmidt 					     slot + 1, nritems - slot - 1);
46205f39d397SChris Mason 		memmove_extent_buffer(parent,
46215f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot),
46225f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot + 1),
4623d6025579SChris Mason 			      sizeof(struct btrfs_key_ptr) *
4624d6025579SChris Mason 			      (nritems - slot - 1));
462557ba86c0SChris Mason 	} else if (level) {
462657ba86c0SChris Mason 		ret = tree_mod_log_insert_key(root->fs_info, parent, slot,
462757ba86c0SChris Mason 					      MOD_LOG_KEY_REMOVE);
462857ba86c0SChris Mason 		BUG_ON(ret < 0);
4629be0e5c09SChris Mason 	}
4630f3ea38daSJan Schmidt 
46317518a238SChris Mason 	nritems--;
46325f39d397SChris Mason 	btrfs_set_header_nritems(parent, nritems);
46337518a238SChris Mason 	if (nritems == 0 && parent == root->node) {
46345f39d397SChris Mason 		BUG_ON(btrfs_header_level(root->node) != 1);
4635eb60ceacSChris Mason 		/* just turn the root into a leaf and break */
46365f39d397SChris Mason 		btrfs_set_header_level(root->node, 0);
4637bb803951SChris Mason 	} else if (slot == 0) {
46385f39d397SChris Mason 		struct btrfs_disk_key disk_key;
46395f39d397SChris Mason 
46405f39d397SChris Mason 		btrfs_node_key(parent, &disk_key, 0);
4641143bede5SJeff Mahoney 		fixup_low_keys(trans, root, path, &disk_key, level + 1);
4642be0e5c09SChris Mason 	}
4643d6025579SChris Mason 	btrfs_mark_buffer_dirty(parent);
4644be0e5c09SChris Mason }
4645be0e5c09SChris Mason 
464674123bd7SChris Mason /*
4647323ac95bSChris Mason  * a helper function to delete the leaf pointed to by path->slots[1] and
46485d4f98a2SYan Zheng  * path->nodes[1].
4649323ac95bSChris Mason  *
4650323ac95bSChris Mason  * This deletes the pointer in path->nodes[1] and frees the leaf
4651323ac95bSChris Mason  * block extent.  zero is returned if it all worked out, < 0 otherwise.
4652323ac95bSChris Mason  *
4653323ac95bSChris Mason  * The path must have already been setup for deleting the leaf, including
4654323ac95bSChris Mason  * all the proper balancing.  path->nodes[1] must be locked.
4655323ac95bSChris Mason  */
4656143bede5SJeff Mahoney static noinline void btrfs_del_leaf(struct btrfs_trans_handle *trans,
4657323ac95bSChris Mason 				    struct btrfs_root *root,
46585d4f98a2SYan Zheng 				    struct btrfs_path *path,
46595d4f98a2SYan Zheng 				    struct extent_buffer *leaf)
4660323ac95bSChris Mason {
46615d4f98a2SYan Zheng 	WARN_ON(btrfs_header_generation(leaf) != trans->transid);
46620e411eceSLiu Bo 	del_ptr(trans, root, path, 1, path->slots[1]);
4663323ac95bSChris Mason 
46644d081c41SChris Mason 	/*
46654d081c41SChris Mason 	 * btrfs_free_extent is expensive, we want to make sure we
46664d081c41SChris Mason 	 * aren't holding any locks when we call it
46674d081c41SChris Mason 	 */
46684d081c41SChris Mason 	btrfs_unlock_up_safe(path, 0);
46694d081c41SChris Mason 
4670f0486c68SYan, Zheng 	root_sub_used(root, leaf->len);
4671f0486c68SYan, Zheng 
46723083ee2eSJosef Bacik 	extent_buffer_get(leaf);
46735581a51aSJan Schmidt 	btrfs_free_tree_block(trans, root, leaf, 0, 1);
46743083ee2eSJosef Bacik 	free_extent_buffer_stale(leaf);
4675323ac95bSChris Mason }
4676323ac95bSChris Mason /*
467774123bd7SChris Mason  * delete the item at the leaf level in path.  If that empties
467874123bd7SChris Mason  * the leaf, remove it from the tree
467974123bd7SChris Mason  */
468085e21bacSChris Mason int btrfs_del_items(struct btrfs_trans_handle *trans, struct btrfs_root *root,
468185e21bacSChris Mason 		    struct btrfs_path *path, int slot, int nr)
4682be0e5c09SChris Mason {
46835f39d397SChris Mason 	struct extent_buffer *leaf;
46845f39d397SChris Mason 	struct btrfs_item *item;
468585e21bacSChris Mason 	int last_off;
468685e21bacSChris Mason 	int dsize = 0;
4687aa5d6bedSChris Mason 	int ret = 0;
4688aa5d6bedSChris Mason 	int wret;
468985e21bacSChris Mason 	int i;
46907518a238SChris Mason 	u32 nritems;
4691cfed81a0SChris Mason 	struct btrfs_map_token token;
4692cfed81a0SChris Mason 
4693cfed81a0SChris Mason 	btrfs_init_map_token(&token);
4694be0e5c09SChris Mason 
46955f39d397SChris Mason 	leaf = path->nodes[0];
469685e21bacSChris Mason 	last_off = btrfs_item_offset_nr(leaf, slot + nr - 1);
469785e21bacSChris Mason 
469885e21bacSChris Mason 	for (i = 0; i < nr; i++)
469985e21bacSChris Mason 		dsize += btrfs_item_size_nr(leaf, slot + i);
470085e21bacSChris Mason 
47015f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
4702be0e5c09SChris Mason 
470385e21bacSChris Mason 	if (slot + nr != nritems) {
4704123abc88SChris Mason 		int data_end = leaf_data_end(root, leaf);
47055f39d397SChris Mason 
47065f39d397SChris Mason 		memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
4707d6025579SChris Mason 			      data_end + dsize,
4708123abc88SChris Mason 			      btrfs_leaf_data(leaf) + data_end,
470985e21bacSChris Mason 			      last_off - data_end);
47105f39d397SChris Mason 
471185e21bacSChris Mason 		for (i = slot + nr; i < nritems; i++) {
47125f39d397SChris Mason 			u32 ioff;
4713db94535dSChris Mason 
47145f39d397SChris Mason 			item = btrfs_item_nr(leaf, i);
4715cfed81a0SChris Mason 			ioff = btrfs_token_item_offset(leaf, item, &token);
4716cfed81a0SChris Mason 			btrfs_set_token_item_offset(leaf, item,
4717cfed81a0SChris Mason 						    ioff + dsize, &token);
47180783fcfcSChris Mason 		}
4719db94535dSChris Mason 
47205f39d397SChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot),
472185e21bacSChris Mason 			      btrfs_item_nr_offset(slot + nr),
47220783fcfcSChris Mason 			      sizeof(struct btrfs_item) *
472385e21bacSChris Mason 			      (nritems - slot - nr));
4724be0e5c09SChris Mason 	}
472585e21bacSChris Mason 	btrfs_set_header_nritems(leaf, nritems - nr);
472685e21bacSChris Mason 	nritems -= nr;
47275f39d397SChris Mason 
472874123bd7SChris Mason 	/* delete the leaf if we've emptied it */
47297518a238SChris Mason 	if (nritems == 0) {
47305f39d397SChris Mason 		if (leaf == root->node) {
47315f39d397SChris Mason 			btrfs_set_header_level(leaf, 0);
47329a8dd150SChris Mason 		} else {
4733f0486c68SYan, Zheng 			btrfs_set_path_blocking(path);
4734f0486c68SYan, Zheng 			clean_tree_block(trans, root, leaf);
4735143bede5SJeff Mahoney 			btrfs_del_leaf(trans, root, path, leaf);
47369a8dd150SChris Mason 		}
4737be0e5c09SChris Mason 	} else {
47387518a238SChris Mason 		int used = leaf_space_used(leaf, 0, nritems);
4739aa5d6bedSChris Mason 		if (slot == 0) {
47405f39d397SChris Mason 			struct btrfs_disk_key disk_key;
47415f39d397SChris Mason 
47425f39d397SChris Mason 			btrfs_item_key(leaf, &disk_key, 0);
4743143bede5SJeff Mahoney 			fixup_low_keys(trans, root, path, &disk_key, 1);
4744aa5d6bedSChris Mason 		}
4745aa5d6bedSChris Mason 
474674123bd7SChris Mason 		/* delete the leaf if it is mostly empty */
4747d717aa1dSYan Zheng 		if (used < BTRFS_LEAF_DATA_SIZE(root) / 3) {
4748be0e5c09SChris Mason 			/* push_leaf_left fixes the path.
4749be0e5c09SChris Mason 			 * make sure the path still points to our leaf
4750be0e5c09SChris Mason 			 * for possible call to del_ptr below
4751be0e5c09SChris Mason 			 */
47524920c9acSChris Mason 			slot = path->slots[1];
47535f39d397SChris Mason 			extent_buffer_get(leaf);
47545f39d397SChris Mason 
4755b9473439SChris Mason 			btrfs_set_path_blocking(path);
475699d8f83cSChris Mason 			wret = push_leaf_left(trans, root, path, 1, 1,
475799d8f83cSChris Mason 					      1, (u32)-1);
475854aa1f4dSChris Mason 			if (wret < 0 && wret != -ENOSPC)
4759aa5d6bedSChris Mason 				ret = wret;
47605f39d397SChris Mason 
47615f39d397SChris Mason 			if (path->nodes[0] == leaf &&
47625f39d397SChris Mason 			    btrfs_header_nritems(leaf)) {
476399d8f83cSChris Mason 				wret = push_leaf_right(trans, root, path, 1,
476499d8f83cSChris Mason 						       1, 1, 0);
476554aa1f4dSChris Mason 				if (wret < 0 && wret != -ENOSPC)
4766aa5d6bedSChris Mason 					ret = wret;
4767aa5d6bedSChris Mason 			}
47685f39d397SChris Mason 
47695f39d397SChris Mason 			if (btrfs_header_nritems(leaf) == 0) {
4770323ac95bSChris Mason 				path->slots[1] = slot;
4771143bede5SJeff Mahoney 				btrfs_del_leaf(trans, root, path, leaf);
47725f39d397SChris Mason 				free_extent_buffer(leaf);
4773143bede5SJeff Mahoney 				ret = 0;
47745de08d7dSChris Mason 			} else {
4775925baeddSChris Mason 				/* if we're still in the path, make sure
4776925baeddSChris Mason 				 * we're dirty.  Otherwise, one of the
4777925baeddSChris Mason 				 * push_leaf functions must have already
4778925baeddSChris Mason 				 * dirtied this buffer
4779925baeddSChris Mason 				 */
4780925baeddSChris Mason 				if (path->nodes[0] == leaf)
47815f39d397SChris Mason 					btrfs_mark_buffer_dirty(leaf);
47825f39d397SChris Mason 				free_extent_buffer(leaf);
4783be0e5c09SChris Mason 			}
4784d5719762SChris Mason 		} else {
47855f39d397SChris Mason 			btrfs_mark_buffer_dirty(leaf);
4786be0e5c09SChris Mason 		}
47879a8dd150SChris Mason 	}
4788aa5d6bedSChris Mason 	return ret;
47899a8dd150SChris Mason }
47909a8dd150SChris Mason 
479197571fd0SChris Mason /*
4792925baeddSChris Mason  * search the tree again to find a leaf with lesser keys
47937bb86316SChris Mason  * returns 0 if it found something or 1 if there are no lesser leaves.
47947bb86316SChris Mason  * returns < 0 on io errors.
4795d352ac68SChris Mason  *
4796d352ac68SChris Mason  * This may release the path, and so you may lose any locks held at the
4797d352ac68SChris Mason  * time you call it.
47987bb86316SChris Mason  */
47997bb86316SChris Mason int btrfs_prev_leaf(struct btrfs_root *root, struct btrfs_path *path)
48007bb86316SChris Mason {
4801925baeddSChris Mason 	struct btrfs_key key;
4802925baeddSChris Mason 	struct btrfs_disk_key found_key;
4803925baeddSChris Mason 	int ret;
48047bb86316SChris Mason 
4805925baeddSChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, 0);
4806925baeddSChris Mason 
4807925baeddSChris Mason 	if (key.offset > 0)
4808925baeddSChris Mason 		key.offset--;
4809925baeddSChris Mason 	else if (key.type > 0)
4810925baeddSChris Mason 		key.type--;
4811925baeddSChris Mason 	else if (key.objectid > 0)
4812925baeddSChris Mason 		key.objectid--;
4813925baeddSChris Mason 	else
48147bb86316SChris Mason 		return 1;
48157bb86316SChris Mason 
4816b3b4aa74SDavid Sterba 	btrfs_release_path(path);
4817925baeddSChris Mason 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4818925baeddSChris Mason 	if (ret < 0)
4819925baeddSChris Mason 		return ret;
4820925baeddSChris Mason 	btrfs_item_key(path->nodes[0], &found_key, 0);
4821925baeddSChris Mason 	ret = comp_keys(&found_key, &key);
4822925baeddSChris Mason 	if (ret < 0)
48237bb86316SChris Mason 		return 0;
4824925baeddSChris Mason 	return 1;
48257bb86316SChris Mason }
48267bb86316SChris Mason 
48273f157a2fSChris Mason /*
48283f157a2fSChris Mason  * A helper function to walk down the tree starting at min_key, and looking
48293f157a2fSChris Mason  * for nodes or leaves that are either in cache or have a minimum
4830d352ac68SChris Mason  * transaction id.  This is used by the btree defrag code, and tree logging
48313f157a2fSChris Mason  *
48323f157a2fSChris Mason  * This does not cow, but it does stuff the starting key it finds back
48333f157a2fSChris Mason  * into min_key, so you can call btrfs_search_slot with cow=1 on the
48343f157a2fSChris Mason  * key and get a writable path.
48353f157a2fSChris Mason  *
48363f157a2fSChris Mason  * This does lock as it descends, and path->keep_locks should be set
48373f157a2fSChris Mason  * to 1 by the caller.
48383f157a2fSChris Mason  *
48393f157a2fSChris Mason  * This honors path->lowest_level to prevent descent past a given level
48403f157a2fSChris Mason  * of the tree.
48413f157a2fSChris Mason  *
4842d352ac68SChris Mason  * min_trans indicates the oldest transaction that you are interested
4843d352ac68SChris Mason  * in walking through.  Any nodes or leaves older than min_trans are
4844d352ac68SChris Mason  * skipped over (without reading them).
4845d352ac68SChris Mason  *
48463f157a2fSChris Mason  * returns zero if something useful was found, < 0 on error and 1 if there
48473f157a2fSChris Mason  * was nothing in the tree that matched the search criteria.
48483f157a2fSChris Mason  */
48493f157a2fSChris Mason int btrfs_search_forward(struct btrfs_root *root, struct btrfs_key *min_key,
4850e02119d5SChris Mason 			 struct btrfs_key *max_key,
48513f157a2fSChris Mason 			 struct btrfs_path *path, int cache_only,
48523f157a2fSChris Mason 			 u64 min_trans)
48533f157a2fSChris Mason {
48543f157a2fSChris Mason 	struct extent_buffer *cur;
48553f157a2fSChris Mason 	struct btrfs_key found_key;
48563f157a2fSChris Mason 	int slot;
48579652480bSYan 	int sret;
48583f157a2fSChris Mason 	u32 nritems;
48593f157a2fSChris Mason 	int level;
48603f157a2fSChris Mason 	int ret = 1;
48613f157a2fSChris Mason 
4862934d375bSChris Mason 	WARN_ON(!path->keep_locks);
48633f157a2fSChris Mason again:
4864bd681513SChris Mason 	cur = btrfs_read_lock_root_node(root);
48653f157a2fSChris Mason 	level = btrfs_header_level(cur);
4866e02119d5SChris Mason 	WARN_ON(path->nodes[level]);
48673f157a2fSChris Mason 	path->nodes[level] = cur;
4868bd681513SChris Mason 	path->locks[level] = BTRFS_READ_LOCK;
48693f157a2fSChris Mason 
48703f157a2fSChris Mason 	if (btrfs_header_generation(cur) < min_trans) {
48713f157a2fSChris Mason 		ret = 1;
48723f157a2fSChris Mason 		goto out;
48733f157a2fSChris Mason 	}
48743f157a2fSChris Mason 	while (1) {
48753f157a2fSChris Mason 		nritems = btrfs_header_nritems(cur);
48763f157a2fSChris Mason 		level = btrfs_header_level(cur);
48779652480bSYan 		sret = bin_search(cur, min_key, level, &slot);
48783f157a2fSChris Mason 
4879323ac95bSChris Mason 		/* at the lowest level, we're done, setup the path and exit */
4880323ac95bSChris Mason 		if (level == path->lowest_level) {
4881e02119d5SChris Mason 			if (slot >= nritems)
4882e02119d5SChris Mason 				goto find_next_key;
48833f157a2fSChris Mason 			ret = 0;
48843f157a2fSChris Mason 			path->slots[level] = slot;
48853f157a2fSChris Mason 			btrfs_item_key_to_cpu(cur, &found_key, slot);
48863f157a2fSChris Mason 			goto out;
48873f157a2fSChris Mason 		}
48889652480bSYan 		if (sret && slot > 0)
48899652480bSYan 			slot--;
48903f157a2fSChris Mason 		/*
48913f157a2fSChris Mason 		 * check this node pointer against the cache_only and
48923f157a2fSChris Mason 		 * min_trans parameters.  If it isn't in cache or is too
48933f157a2fSChris Mason 		 * old, skip to the next one.
48943f157a2fSChris Mason 		 */
48953f157a2fSChris Mason 		while (slot < nritems) {
48963f157a2fSChris Mason 			u64 blockptr;
48973f157a2fSChris Mason 			u64 gen;
48983f157a2fSChris Mason 			struct extent_buffer *tmp;
4899e02119d5SChris Mason 			struct btrfs_disk_key disk_key;
4900e02119d5SChris Mason 
49013f157a2fSChris Mason 			blockptr = btrfs_node_blockptr(cur, slot);
49023f157a2fSChris Mason 			gen = btrfs_node_ptr_generation(cur, slot);
49033f157a2fSChris Mason 			if (gen < min_trans) {
49043f157a2fSChris Mason 				slot++;
49053f157a2fSChris Mason 				continue;
49063f157a2fSChris Mason 			}
49073f157a2fSChris Mason 			if (!cache_only)
49083f157a2fSChris Mason 				break;
49093f157a2fSChris Mason 
4910e02119d5SChris Mason 			if (max_key) {
4911e02119d5SChris Mason 				btrfs_node_key(cur, &disk_key, slot);
4912e02119d5SChris Mason 				if (comp_keys(&disk_key, max_key) >= 0) {
4913e02119d5SChris Mason 					ret = 1;
4914e02119d5SChris Mason 					goto out;
4915e02119d5SChris Mason 				}
4916e02119d5SChris Mason 			}
4917e02119d5SChris Mason 
49183f157a2fSChris Mason 			tmp = btrfs_find_tree_block(root, blockptr,
49193f157a2fSChris Mason 					    btrfs_level_size(root, level - 1));
49203f157a2fSChris Mason 
4921b9fab919SChris Mason 			if (tmp && btrfs_buffer_uptodate(tmp, gen, 1) > 0) {
49223f157a2fSChris Mason 				free_extent_buffer(tmp);
49233f157a2fSChris Mason 				break;
49243f157a2fSChris Mason 			}
49253f157a2fSChris Mason 			if (tmp)
49263f157a2fSChris Mason 				free_extent_buffer(tmp);
49273f157a2fSChris Mason 			slot++;
49283f157a2fSChris Mason 		}
4929e02119d5SChris Mason find_next_key:
49303f157a2fSChris Mason 		/*
49313f157a2fSChris Mason 		 * we didn't find a candidate key in this node, walk forward
49323f157a2fSChris Mason 		 * and find another one
49333f157a2fSChris Mason 		 */
49343f157a2fSChris Mason 		if (slot >= nritems) {
4935e02119d5SChris Mason 			path->slots[level] = slot;
4936b4ce94deSChris Mason 			btrfs_set_path_blocking(path);
4937e02119d5SChris Mason 			sret = btrfs_find_next_key(root, path, min_key, level,
49383f157a2fSChris Mason 						  cache_only, min_trans);
4939e02119d5SChris Mason 			if (sret == 0) {
4940b3b4aa74SDavid Sterba 				btrfs_release_path(path);
49413f157a2fSChris Mason 				goto again;
49423f157a2fSChris Mason 			} else {
49433f157a2fSChris Mason 				goto out;
49443f157a2fSChris Mason 			}
49453f157a2fSChris Mason 		}
49463f157a2fSChris Mason 		/* save our key for returning back */
49473f157a2fSChris Mason 		btrfs_node_key_to_cpu(cur, &found_key, slot);
49483f157a2fSChris Mason 		path->slots[level] = slot;
49493f157a2fSChris Mason 		if (level == path->lowest_level) {
49503f157a2fSChris Mason 			ret = 0;
4951f7c79f30SChris Mason 			unlock_up(path, level, 1, 0, NULL);
49523f157a2fSChris Mason 			goto out;
49533f157a2fSChris Mason 		}
4954b4ce94deSChris Mason 		btrfs_set_path_blocking(path);
49553f157a2fSChris Mason 		cur = read_node_slot(root, cur, slot);
495679787eaaSJeff Mahoney 		BUG_ON(!cur); /* -ENOMEM */
49573f157a2fSChris Mason 
4958bd681513SChris Mason 		btrfs_tree_read_lock(cur);
4959b4ce94deSChris Mason 
4960bd681513SChris Mason 		path->locks[level - 1] = BTRFS_READ_LOCK;
49613f157a2fSChris Mason 		path->nodes[level - 1] = cur;
4962f7c79f30SChris Mason 		unlock_up(path, level, 1, 0, NULL);
4963bd681513SChris Mason 		btrfs_clear_path_blocking(path, NULL, 0);
49643f157a2fSChris Mason 	}
49653f157a2fSChris Mason out:
49663f157a2fSChris Mason 	if (ret == 0)
49673f157a2fSChris Mason 		memcpy(min_key, &found_key, sizeof(found_key));
4968b4ce94deSChris Mason 	btrfs_set_path_blocking(path);
49693f157a2fSChris Mason 	return ret;
49703f157a2fSChris Mason }
49713f157a2fSChris Mason 
49727069830aSAlexander Block static void tree_move_down(struct btrfs_root *root,
49737069830aSAlexander Block 			   struct btrfs_path *path,
49747069830aSAlexander Block 			   int *level, int root_level)
49757069830aSAlexander Block {
497674dd17fbSChris Mason 	BUG_ON(*level == 0);
49777069830aSAlexander Block 	path->nodes[*level - 1] = read_node_slot(root, path->nodes[*level],
49787069830aSAlexander Block 					path->slots[*level]);
49797069830aSAlexander Block 	path->slots[*level - 1] = 0;
49807069830aSAlexander Block 	(*level)--;
49817069830aSAlexander Block }
49827069830aSAlexander Block 
49837069830aSAlexander Block static int tree_move_next_or_upnext(struct btrfs_root *root,
49847069830aSAlexander Block 				    struct btrfs_path *path,
49857069830aSAlexander Block 				    int *level, int root_level)
49867069830aSAlexander Block {
49877069830aSAlexander Block 	int ret = 0;
49887069830aSAlexander Block 	int nritems;
49897069830aSAlexander Block 	nritems = btrfs_header_nritems(path->nodes[*level]);
49907069830aSAlexander Block 
49917069830aSAlexander Block 	path->slots[*level]++;
49927069830aSAlexander Block 
499374dd17fbSChris Mason 	while (path->slots[*level] >= nritems) {
49947069830aSAlexander Block 		if (*level == root_level)
49957069830aSAlexander Block 			return -1;
49967069830aSAlexander Block 
49977069830aSAlexander Block 		/* move upnext */
49987069830aSAlexander Block 		path->slots[*level] = 0;
49997069830aSAlexander Block 		free_extent_buffer(path->nodes[*level]);
50007069830aSAlexander Block 		path->nodes[*level] = NULL;
50017069830aSAlexander Block 		(*level)++;
50027069830aSAlexander Block 		path->slots[*level]++;
50037069830aSAlexander Block 
50047069830aSAlexander Block 		nritems = btrfs_header_nritems(path->nodes[*level]);
50057069830aSAlexander Block 		ret = 1;
50067069830aSAlexander Block 	}
50077069830aSAlexander Block 	return ret;
50087069830aSAlexander Block }
50097069830aSAlexander Block 
50107069830aSAlexander Block /*
50117069830aSAlexander Block  * Returns 1 if it had to move up and next. 0 is returned if it moved only next
50127069830aSAlexander Block  * or down.
50137069830aSAlexander Block  */
50147069830aSAlexander Block static int tree_advance(struct btrfs_root *root,
50157069830aSAlexander Block 			struct btrfs_path *path,
50167069830aSAlexander Block 			int *level, int root_level,
50177069830aSAlexander Block 			int allow_down,
50187069830aSAlexander Block 			struct btrfs_key *key)
50197069830aSAlexander Block {
50207069830aSAlexander Block 	int ret;
50217069830aSAlexander Block 
50227069830aSAlexander Block 	if (*level == 0 || !allow_down) {
50237069830aSAlexander Block 		ret = tree_move_next_or_upnext(root, path, level, root_level);
50247069830aSAlexander Block 	} else {
50257069830aSAlexander Block 		tree_move_down(root, path, level, root_level);
50267069830aSAlexander Block 		ret = 0;
50277069830aSAlexander Block 	}
50287069830aSAlexander Block 	if (ret >= 0) {
50297069830aSAlexander Block 		if (*level == 0)
50307069830aSAlexander Block 			btrfs_item_key_to_cpu(path->nodes[*level], key,
50317069830aSAlexander Block 					path->slots[*level]);
50327069830aSAlexander Block 		else
50337069830aSAlexander Block 			btrfs_node_key_to_cpu(path->nodes[*level], key,
50347069830aSAlexander Block 					path->slots[*level]);
50357069830aSAlexander Block 	}
50367069830aSAlexander Block 	return ret;
50377069830aSAlexander Block }
50387069830aSAlexander Block 
50397069830aSAlexander Block static int tree_compare_item(struct btrfs_root *left_root,
50407069830aSAlexander Block 			     struct btrfs_path *left_path,
50417069830aSAlexander Block 			     struct btrfs_path *right_path,
50427069830aSAlexander Block 			     char *tmp_buf)
50437069830aSAlexander Block {
50447069830aSAlexander Block 	int cmp;
50457069830aSAlexander Block 	int len1, len2;
50467069830aSAlexander Block 	unsigned long off1, off2;
50477069830aSAlexander Block 
50487069830aSAlexander Block 	len1 = btrfs_item_size_nr(left_path->nodes[0], left_path->slots[0]);
50497069830aSAlexander Block 	len2 = btrfs_item_size_nr(right_path->nodes[0], right_path->slots[0]);
50507069830aSAlexander Block 	if (len1 != len2)
50517069830aSAlexander Block 		return 1;
50527069830aSAlexander Block 
50537069830aSAlexander Block 	off1 = btrfs_item_ptr_offset(left_path->nodes[0], left_path->slots[0]);
50547069830aSAlexander Block 	off2 = btrfs_item_ptr_offset(right_path->nodes[0],
50557069830aSAlexander Block 				right_path->slots[0]);
50567069830aSAlexander Block 
50577069830aSAlexander Block 	read_extent_buffer(left_path->nodes[0], tmp_buf, off1, len1);
50587069830aSAlexander Block 
50597069830aSAlexander Block 	cmp = memcmp_extent_buffer(right_path->nodes[0], tmp_buf, off2, len1);
50607069830aSAlexander Block 	if (cmp)
50617069830aSAlexander Block 		return 1;
50627069830aSAlexander Block 	return 0;
50637069830aSAlexander Block }
50647069830aSAlexander Block 
50657069830aSAlexander Block #define ADVANCE 1
50667069830aSAlexander Block #define ADVANCE_ONLY_NEXT -1
50677069830aSAlexander Block 
50687069830aSAlexander Block /*
50697069830aSAlexander Block  * This function compares two trees and calls the provided callback for
50707069830aSAlexander Block  * every changed/new/deleted item it finds.
50717069830aSAlexander Block  * If shared tree blocks are encountered, whole subtrees are skipped, making
50727069830aSAlexander Block  * the compare pretty fast on snapshotted subvolumes.
50737069830aSAlexander Block  *
50747069830aSAlexander Block  * This currently works on commit roots only. As commit roots are read only,
50757069830aSAlexander Block  * we don't do any locking. The commit roots are protected with transactions.
50767069830aSAlexander Block  * Transactions are ended and rejoined when a commit is tried in between.
50777069830aSAlexander Block  *
50787069830aSAlexander Block  * This function checks for modifications done to the trees while comparing.
50797069830aSAlexander Block  * If it detects a change, it aborts immediately.
50807069830aSAlexander Block  */
50817069830aSAlexander Block int btrfs_compare_trees(struct btrfs_root *left_root,
50827069830aSAlexander Block 			struct btrfs_root *right_root,
50837069830aSAlexander Block 			btrfs_changed_cb_t changed_cb, void *ctx)
50847069830aSAlexander Block {
50857069830aSAlexander Block 	int ret;
50867069830aSAlexander Block 	int cmp;
50877069830aSAlexander Block 	struct btrfs_trans_handle *trans = NULL;
50887069830aSAlexander Block 	struct btrfs_path *left_path = NULL;
50897069830aSAlexander Block 	struct btrfs_path *right_path = NULL;
50907069830aSAlexander Block 	struct btrfs_key left_key;
50917069830aSAlexander Block 	struct btrfs_key right_key;
50927069830aSAlexander Block 	char *tmp_buf = NULL;
50937069830aSAlexander Block 	int left_root_level;
50947069830aSAlexander Block 	int right_root_level;
50957069830aSAlexander Block 	int left_level;
50967069830aSAlexander Block 	int right_level;
50977069830aSAlexander Block 	int left_end_reached;
50987069830aSAlexander Block 	int right_end_reached;
50997069830aSAlexander Block 	int advance_left;
51007069830aSAlexander Block 	int advance_right;
51017069830aSAlexander Block 	u64 left_blockptr;
51027069830aSAlexander Block 	u64 right_blockptr;
51037069830aSAlexander Block 	u64 left_start_ctransid;
51047069830aSAlexander Block 	u64 right_start_ctransid;
51057069830aSAlexander Block 	u64 ctransid;
51067069830aSAlexander Block 
51077069830aSAlexander Block 	left_path = btrfs_alloc_path();
51087069830aSAlexander Block 	if (!left_path) {
51097069830aSAlexander Block 		ret = -ENOMEM;
51107069830aSAlexander Block 		goto out;
51117069830aSAlexander Block 	}
51127069830aSAlexander Block 	right_path = btrfs_alloc_path();
51137069830aSAlexander Block 	if (!right_path) {
51147069830aSAlexander Block 		ret = -ENOMEM;
51157069830aSAlexander Block 		goto out;
51167069830aSAlexander Block 	}
51177069830aSAlexander Block 
51187069830aSAlexander Block 	tmp_buf = kmalloc(left_root->leafsize, GFP_NOFS);
51197069830aSAlexander Block 	if (!tmp_buf) {
51207069830aSAlexander Block 		ret = -ENOMEM;
51217069830aSAlexander Block 		goto out;
51227069830aSAlexander Block 	}
51237069830aSAlexander Block 
51247069830aSAlexander Block 	left_path->search_commit_root = 1;
51257069830aSAlexander Block 	left_path->skip_locking = 1;
51267069830aSAlexander Block 	right_path->search_commit_root = 1;
51277069830aSAlexander Block 	right_path->skip_locking = 1;
51287069830aSAlexander Block 
51295f3ab90aSAnand Jain 	spin_lock(&left_root->root_item_lock);
51307069830aSAlexander Block 	left_start_ctransid = btrfs_root_ctransid(&left_root->root_item);
51315f3ab90aSAnand Jain 	spin_unlock(&left_root->root_item_lock);
51327069830aSAlexander Block 
51335f3ab90aSAnand Jain 	spin_lock(&right_root->root_item_lock);
51347069830aSAlexander Block 	right_start_ctransid = btrfs_root_ctransid(&right_root->root_item);
51355f3ab90aSAnand Jain 	spin_unlock(&right_root->root_item_lock);
51367069830aSAlexander Block 
51377069830aSAlexander Block 	trans = btrfs_join_transaction(left_root);
51387069830aSAlexander Block 	if (IS_ERR(trans)) {
51397069830aSAlexander Block 		ret = PTR_ERR(trans);
51407069830aSAlexander Block 		trans = NULL;
51417069830aSAlexander Block 		goto out;
51427069830aSAlexander Block 	}
51437069830aSAlexander Block 
51447069830aSAlexander Block 	/*
51457069830aSAlexander Block 	 * Strategy: Go to the first items of both trees. Then do
51467069830aSAlexander Block 	 *
51477069830aSAlexander Block 	 * If both trees are at level 0
51487069830aSAlexander Block 	 *   Compare keys of current items
51497069830aSAlexander Block 	 *     If left < right treat left item as new, advance left tree
51507069830aSAlexander Block 	 *       and repeat
51517069830aSAlexander Block 	 *     If left > right treat right item as deleted, advance right tree
51527069830aSAlexander Block 	 *       and repeat
51537069830aSAlexander Block 	 *     If left == right do deep compare of items, treat as changed if
51547069830aSAlexander Block 	 *       needed, advance both trees and repeat
51557069830aSAlexander Block 	 * If both trees are at the same level but not at level 0
51567069830aSAlexander Block 	 *   Compare keys of current nodes/leafs
51577069830aSAlexander Block 	 *     If left < right advance left tree and repeat
51587069830aSAlexander Block 	 *     If left > right advance right tree and repeat
51597069830aSAlexander Block 	 *     If left == right compare blockptrs of the next nodes/leafs
51607069830aSAlexander Block 	 *       If they match advance both trees but stay at the same level
51617069830aSAlexander Block 	 *         and repeat
51627069830aSAlexander Block 	 *       If they don't match advance both trees while allowing to go
51637069830aSAlexander Block 	 *         deeper and repeat
51647069830aSAlexander Block 	 * If tree levels are different
51657069830aSAlexander Block 	 *   Advance the tree that needs it and repeat
51667069830aSAlexander Block 	 *
51677069830aSAlexander Block 	 * Advancing a tree means:
51687069830aSAlexander Block 	 *   If we are at level 0, try to go to the next slot. If that's not
51697069830aSAlexander Block 	 *   possible, go one level up and repeat. Stop when we found a level
51707069830aSAlexander Block 	 *   where we could go to the next slot. We may at this point be on a
51717069830aSAlexander Block 	 *   node or a leaf.
51727069830aSAlexander Block 	 *
51737069830aSAlexander Block 	 *   If we are not at level 0 and not on shared tree blocks, go one
51747069830aSAlexander Block 	 *   level deeper.
51757069830aSAlexander Block 	 *
51767069830aSAlexander Block 	 *   If we are not at level 0 and on shared tree blocks, go one slot to
51777069830aSAlexander Block 	 *   the right if possible or go up and right.
51787069830aSAlexander Block 	 */
51797069830aSAlexander Block 
51807069830aSAlexander Block 	left_level = btrfs_header_level(left_root->commit_root);
51817069830aSAlexander Block 	left_root_level = left_level;
51827069830aSAlexander Block 	left_path->nodes[left_level] = left_root->commit_root;
51837069830aSAlexander Block 	extent_buffer_get(left_path->nodes[left_level]);
51847069830aSAlexander Block 
51857069830aSAlexander Block 	right_level = btrfs_header_level(right_root->commit_root);
51867069830aSAlexander Block 	right_root_level = right_level;
51877069830aSAlexander Block 	right_path->nodes[right_level] = right_root->commit_root;
51887069830aSAlexander Block 	extent_buffer_get(right_path->nodes[right_level]);
51897069830aSAlexander Block 
51907069830aSAlexander Block 	if (left_level == 0)
51917069830aSAlexander Block 		btrfs_item_key_to_cpu(left_path->nodes[left_level],
51927069830aSAlexander Block 				&left_key, left_path->slots[left_level]);
51937069830aSAlexander Block 	else
51947069830aSAlexander Block 		btrfs_node_key_to_cpu(left_path->nodes[left_level],
51957069830aSAlexander Block 				&left_key, left_path->slots[left_level]);
51967069830aSAlexander Block 	if (right_level == 0)
51977069830aSAlexander Block 		btrfs_item_key_to_cpu(right_path->nodes[right_level],
51987069830aSAlexander Block 				&right_key, right_path->slots[right_level]);
51997069830aSAlexander Block 	else
52007069830aSAlexander Block 		btrfs_node_key_to_cpu(right_path->nodes[right_level],
52017069830aSAlexander Block 				&right_key, right_path->slots[right_level]);
52027069830aSAlexander Block 
52037069830aSAlexander Block 	left_end_reached = right_end_reached = 0;
52047069830aSAlexander Block 	advance_left = advance_right = 0;
52057069830aSAlexander Block 
52067069830aSAlexander Block 	while (1) {
52077069830aSAlexander Block 		/*
52087069830aSAlexander Block 		 * We need to make sure the transaction does not get committed
52097069830aSAlexander Block 		 * while we do anything on commit roots. This means, we need to
52107069830aSAlexander Block 		 * join and leave transactions for every item that we process.
52117069830aSAlexander Block 		 */
52127069830aSAlexander Block 		if (trans && btrfs_should_end_transaction(trans, left_root)) {
52137069830aSAlexander Block 			btrfs_release_path(left_path);
52147069830aSAlexander Block 			btrfs_release_path(right_path);
52157069830aSAlexander Block 
52167069830aSAlexander Block 			ret = btrfs_end_transaction(trans, left_root);
52177069830aSAlexander Block 			trans = NULL;
52187069830aSAlexander Block 			if (ret < 0)
52197069830aSAlexander Block 				goto out;
52207069830aSAlexander Block 		}
52217069830aSAlexander Block 		/* now rejoin the transaction */
52227069830aSAlexander Block 		if (!trans) {
52237069830aSAlexander Block 			trans = btrfs_join_transaction(left_root);
52247069830aSAlexander Block 			if (IS_ERR(trans)) {
52257069830aSAlexander Block 				ret = PTR_ERR(trans);
52267069830aSAlexander Block 				trans = NULL;
52277069830aSAlexander Block 				goto out;
52287069830aSAlexander Block 			}
52297069830aSAlexander Block 
52305f3ab90aSAnand Jain 			spin_lock(&left_root->root_item_lock);
52317069830aSAlexander Block 			ctransid = btrfs_root_ctransid(&left_root->root_item);
52325f3ab90aSAnand Jain 			spin_unlock(&left_root->root_item_lock);
52337069830aSAlexander Block 			if (ctransid != left_start_ctransid)
52347069830aSAlexander Block 				left_start_ctransid = 0;
52357069830aSAlexander Block 
52365f3ab90aSAnand Jain 			spin_lock(&right_root->root_item_lock);
52377069830aSAlexander Block 			ctransid = btrfs_root_ctransid(&right_root->root_item);
52385f3ab90aSAnand Jain 			spin_unlock(&right_root->root_item_lock);
52397069830aSAlexander Block 			if (ctransid != right_start_ctransid)
52407069830aSAlexander Block 				right_start_ctransid = 0;
52417069830aSAlexander Block 
52427069830aSAlexander Block 			if (!left_start_ctransid || !right_start_ctransid) {
52437069830aSAlexander Block 				WARN(1, KERN_WARNING
52447069830aSAlexander Block 					"btrfs: btrfs_compare_tree detected "
52457069830aSAlexander Block 					"a change in one of the trees while "
52467069830aSAlexander Block 					"iterating. This is probably a "
52477069830aSAlexander Block 					"bug.\n");
52487069830aSAlexander Block 				ret = -EIO;
52497069830aSAlexander Block 				goto out;
52507069830aSAlexander Block 			}
52517069830aSAlexander Block 
52527069830aSAlexander Block 			/*
52537069830aSAlexander Block 			 * the commit root may have changed, so start again
52547069830aSAlexander Block 			 * where we stopped
52557069830aSAlexander Block 			 */
52567069830aSAlexander Block 			left_path->lowest_level = left_level;
52577069830aSAlexander Block 			right_path->lowest_level = right_level;
52587069830aSAlexander Block 			ret = btrfs_search_slot(NULL, left_root,
52597069830aSAlexander Block 					&left_key, left_path, 0, 0);
52607069830aSAlexander Block 			if (ret < 0)
52617069830aSAlexander Block 				goto out;
52627069830aSAlexander Block 			ret = btrfs_search_slot(NULL, right_root,
52637069830aSAlexander Block 					&right_key, right_path, 0, 0);
52647069830aSAlexander Block 			if (ret < 0)
52657069830aSAlexander Block 				goto out;
52667069830aSAlexander Block 		}
52677069830aSAlexander Block 
52687069830aSAlexander Block 		if (advance_left && !left_end_reached) {
52697069830aSAlexander Block 			ret = tree_advance(left_root, left_path, &left_level,
52707069830aSAlexander Block 					left_root_level,
52717069830aSAlexander Block 					advance_left != ADVANCE_ONLY_NEXT,
52727069830aSAlexander Block 					&left_key);
52737069830aSAlexander Block 			if (ret < 0)
52747069830aSAlexander Block 				left_end_reached = ADVANCE;
52757069830aSAlexander Block 			advance_left = 0;
52767069830aSAlexander Block 		}
52777069830aSAlexander Block 		if (advance_right && !right_end_reached) {
52787069830aSAlexander Block 			ret = tree_advance(right_root, right_path, &right_level,
52797069830aSAlexander Block 					right_root_level,
52807069830aSAlexander Block 					advance_right != ADVANCE_ONLY_NEXT,
52817069830aSAlexander Block 					&right_key);
52827069830aSAlexander Block 			if (ret < 0)
52837069830aSAlexander Block 				right_end_reached = ADVANCE;
52847069830aSAlexander Block 			advance_right = 0;
52857069830aSAlexander Block 		}
52867069830aSAlexander Block 
52877069830aSAlexander Block 		if (left_end_reached && right_end_reached) {
52887069830aSAlexander Block 			ret = 0;
52897069830aSAlexander Block 			goto out;
52907069830aSAlexander Block 		} else if (left_end_reached) {
52917069830aSAlexander Block 			if (right_level == 0) {
52927069830aSAlexander Block 				ret = changed_cb(left_root, right_root,
52937069830aSAlexander Block 						left_path, right_path,
52947069830aSAlexander Block 						&right_key,
52957069830aSAlexander Block 						BTRFS_COMPARE_TREE_DELETED,
52967069830aSAlexander Block 						ctx);
52977069830aSAlexander Block 				if (ret < 0)
52987069830aSAlexander Block 					goto out;
52997069830aSAlexander Block 			}
53007069830aSAlexander Block 			advance_right = ADVANCE;
53017069830aSAlexander Block 			continue;
53027069830aSAlexander Block 		} else if (right_end_reached) {
53037069830aSAlexander Block 			if (left_level == 0) {
53047069830aSAlexander Block 				ret = changed_cb(left_root, right_root,
53057069830aSAlexander Block 						left_path, right_path,
53067069830aSAlexander Block 						&left_key,
53077069830aSAlexander Block 						BTRFS_COMPARE_TREE_NEW,
53087069830aSAlexander Block 						ctx);
53097069830aSAlexander Block 				if (ret < 0)
53107069830aSAlexander Block 					goto out;
53117069830aSAlexander Block 			}
53127069830aSAlexander Block 			advance_left = ADVANCE;
53137069830aSAlexander Block 			continue;
53147069830aSAlexander Block 		}
53157069830aSAlexander Block 
53167069830aSAlexander Block 		if (left_level == 0 && right_level == 0) {
53177069830aSAlexander Block 			cmp = btrfs_comp_cpu_keys(&left_key, &right_key);
53187069830aSAlexander Block 			if (cmp < 0) {
53197069830aSAlexander Block 				ret = changed_cb(left_root, right_root,
53207069830aSAlexander Block 						left_path, right_path,
53217069830aSAlexander Block 						&left_key,
53227069830aSAlexander Block 						BTRFS_COMPARE_TREE_NEW,
53237069830aSAlexander Block 						ctx);
53247069830aSAlexander Block 				if (ret < 0)
53257069830aSAlexander Block 					goto out;
53267069830aSAlexander Block 				advance_left = ADVANCE;
53277069830aSAlexander Block 			} else if (cmp > 0) {
53287069830aSAlexander Block 				ret = changed_cb(left_root, right_root,
53297069830aSAlexander Block 						left_path, right_path,
53307069830aSAlexander Block 						&right_key,
53317069830aSAlexander Block 						BTRFS_COMPARE_TREE_DELETED,
53327069830aSAlexander Block 						ctx);
53337069830aSAlexander Block 				if (ret < 0)
53347069830aSAlexander Block 					goto out;
53357069830aSAlexander Block 				advance_right = ADVANCE;
53367069830aSAlexander Block 			} else {
533774dd17fbSChris Mason 				WARN_ON(!extent_buffer_uptodate(left_path->nodes[0]));
53387069830aSAlexander Block 				ret = tree_compare_item(left_root, left_path,
53397069830aSAlexander Block 						right_path, tmp_buf);
53407069830aSAlexander Block 				if (ret) {
534174dd17fbSChris Mason 					WARN_ON(!extent_buffer_uptodate(left_path->nodes[0]));
53427069830aSAlexander Block 					ret = changed_cb(left_root, right_root,
53437069830aSAlexander Block 						left_path, right_path,
53447069830aSAlexander Block 						&left_key,
53457069830aSAlexander Block 						BTRFS_COMPARE_TREE_CHANGED,
53467069830aSAlexander Block 						ctx);
53477069830aSAlexander Block 					if (ret < 0)
53487069830aSAlexander Block 						goto out;
53497069830aSAlexander Block 				}
53507069830aSAlexander Block 				advance_left = ADVANCE;
53517069830aSAlexander Block 				advance_right = ADVANCE;
53527069830aSAlexander Block 			}
53537069830aSAlexander Block 		} else if (left_level == right_level) {
53547069830aSAlexander Block 			cmp = btrfs_comp_cpu_keys(&left_key, &right_key);
53557069830aSAlexander Block 			if (cmp < 0) {
53567069830aSAlexander Block 				advance_left = ADVANCE;
53577069830aSAlexander Block 			} else if (cmp > 0) {
53587069830aSAlexander Block 				advance_right = ADVANCE;
53597069830aSAlexander Block 			} else {
53607069830aSAlexander Block 				left_blockptr = btrfs_node_blockptr(
53617069830aSAlexander Block 						left_path->nodes[left_level],
53627069830aSAlexander Block 						left_path->slots[left_level]);
53637069830aSAlexander Block 				right_blockptr = btrfs_node_blockptr(
53647069830aSAlexander Block 						right_path->nodes[right_level],
53657069830aSAlexander Block 						right_path->slots[right_level]);
53667069830aSAlexander Block 				if (left_blockptr == right_blockptr) {
53677069830aSAlexander Block 					/*
53687069830aSAlexander Block 					 * As we're on a shared block, don't
53697069830aSAlexander Block 					 * allow to go deeper.
53707069830aSAlexander Block 					 */
53717069830aSAlexander Block 					advance_left = ADVANCE_ONLY_NEXT;
53727069830aSAlexander Block 					advance_right = ADVANCE_ONLY_NEXT;
53737069830aSAlexander Block 				} else {
53747069830aSAlexander Block 					advance_left = ADVANCE;
53757069830aSAlexander Block 					advance_right = ADVANCE;
53767069830aSAlexander Block 				}
53777069830aSAlexander Block 			}
53787069830aSAlexander Block 		} else if (left_level < right_level) {
53797069830aSAlexander Block 			advance_right = ADVANCE;
53807069830aSAlexander Block 		} else {
53817069830aSAlexander Block 			advance_left = ADVANCE;
53827069830aSAlexander Block 		}
53837069830aSAlexander Block 	}
53847069830aSAlexander Block 
53857069830aSAlexander Block out:
53867069830aSAlexander Block 	btrfs_free_path(left_path);
53877069830aSAlexander Block 	btrfs_free_path(right_path);
53887069830aSAlexander Block 	kfree(tmp_buf);
53897069830aSAlexander Block 
53907069830aSAlexander Block 	if (trans) {
53917069830aSAlexander Block 		if (!ret)
53927069830aSAlexander Block 			ret = btrfs_end_transaction(trans, left_root);
53937069830aSAlexander Block 		else
53947069830aSAlexander Block 			btrfs_end_transaction(trans, left_root);
53957069830aSAlexander Block 	}
53967069830aSAlexander Block 
53977069830aSAlexander Block 	return ret;
53987069830aSAlexander Block }
53997069830aSAlexander Block 
54003f157a2fSChris Mason /*
54013f157a2fSChris Mason  * this is similar to btrfs_next_leaf, but does not try to preserve
54023f157a2fSChris Mason  * and fixup the path.  It looks for and returns the next key in the
54033f157a2fSChris Mason  * tree based on the current path and the cache_only and min_trans
54043f157a2fSChris Mason  * parameters.
54053f157a2fSChris Mason  *
54063f157a2fSChris Mason  * 0 is returned if another key is found, < 0 if there are any errors
54073f157a2fSChris Mason  * and 1 is returned if there are no higher keys in the tree
54083f157a2fSChris Mason  *
54093f157a2fSChris Mason  * path->keep_locks should be set to 1 on the search made before
54103f157a2fSChris Mason  * calling this function.
54113f157a2fSChris Mason  */
5412e7a84565SChris Mason int btrfs_find_next_key(struct btrfs_root *root, struct btrfs_path *path,
541333c66f43SYan Zheng 			struct btrfs_key *key, int level,
54143f157a2fSChris Mason 			int cache_only, u64 min_trans)
5415e7a84565SChris Mason {
5416e7a84565SChris Mason 	int slot;
5417e7a84565SChris Mason 	struct extent_buffer *c;
5418e7a84565SChris Mason 
5419934d375bSChris Mason 	WARN_ON(!path->keep_locks);
5420e7a84565SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
5421e7a84565SChris Mason 		if (!path->nodes[level])
5422e7a84565SChris Mason 			return 1;
5423e7a84565SChris Mason 
5424e7a84565SChris Mason 		slot = path->slots[level] + 1;
5425e7a84565SChris Mason 		c = path->nodes[level];
54263f157a2fSChris Mason next:
5427e7a84565SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
542833c66f43SYan Zheng 			int ret;
542933c66f43SYan Zheng 			int orig_lowest;
543033c66f43SYan Zheng 			struct btrfs_key cur_key;
543133c66f43SYan Zheng 			if (level + 1 >= BTRFS_MAX_LEVEL ||
543233c66f43SYan Zheng 			    !path->nodes[level + 1])
5433e7a84565SChris Mason 				return 1;
543433c66f43SYan Zheng 
543533c66f43SYan Zheng 			if (path->locks[level + 1]) {
543633c66f43SYan Zheng 				level++;
5437e7a84565SChris Mason 				continue;
5438e7a84565SChris Mason 			}
543933c66f43SYan Zheng 
544033c66f43SYan Zheng 			slot = btrfs_header_nritems(c) - 1;
544133c66f43SYan Zheng 			if (level == 0)
544233c66f43SYan Zheng 				btrfs_item_key_to_cpu(c, &cur_key, slot);
544333c66f43SYan Zheng 			else
544433c66f43SYan Zheng 				btrfs_node_key_to_cpu(c, &cur_key, slot);
544533c66f43SYan Zheng 
544633c66f43SYan Zheng 			orig_lowest = path->lowest_level;
5447b3b4aa74SDavid Sterba 			btrfs_release_path(path);
544833c66f43SYan Zheng 			path->lowest_level = level;
544933c66f43SYan Zheng 			ret = btrfs_search_slot(NULL, root, &cur_key, path,
545033c66f43SYan Zheng 						0, 0);
545133c66f43SYan Zheng 			path->lowest_level = orig_lowest;
545233c66f43SYan Zheng 			if (ret < 0)
545333c66f43SYan Zheng 				return ret;
545433c66f43SYan Zheng 
545533c66f43SYan Zheng 			c = path->nodes[level];
545633c66f43SYan Zheng 			slot = path->slots[level];
545733c66f43SYan Zheng 			if (ret == 0)
545833c66f43SYan Zheng 				slot++;
545933c66f43SYan Zheng 			goto next;
546033c66f43SYan Zheng 		}
546133c66f43SYan Zheng 
5462e7a84565SChris Mason 		if (level == 0)
5463e7a84565SChris Mason 			btrfs_item_key_to_cpu(c, key, slot);
54643f157a2fSChris Mason 		else {
54653f157a2fSChris Mason 			u64 blockptr = btrfs_node_blockptr(c, slot);
54663f157a2fSChris Mason 			u64 gen = btrfs_node_ptr_generation(c, slot);
54673f157a2fSChris Mason 
54683f157a2fSChris Mason 			if (cache_only) {
54693f157a2fSChris Mason 				struct extent_buffer *cur;
54703f157a2fSChris Mason 				cur = btrfs_find_tree_block(root, blockptr,
54713f157a2fSChris Mason 					    btrfs_level_size(root, level - 1));
5472b9fab919SChris Mason 				if (!cur ||
5473b9fab919SChris Mason 				    btrfs_buffer_uptodate(cur, gen, 1) <= 0) {
54743f157a2fSChris Mason 					slot++;
54753f157a2fSChris Mason 					if (cur)
54763f157a2fSChris Mason 						free_extent_buffer(cur);
54773f157a2fSChris Mason 					goto next;
54783f157a2fSChris Mason 				}
54793f157a2fSChris Mason 				free_extent_buffer(cur);
54803f157a2fSChris Mason 			}
54813f157a2fSChris Mason 			if (gen < min_trans) {
54823f157a2fSChris Mason 				slot++;
54833f157a2fSChris Mason 				goto next;
54843f157a2fSChris Mason 			}
5485e7a84565SChris Mason 			btrfs_node_key_to_cpu(c, key, slot);
54863f157a2fSChris Mason 		}
5487e7a84565SChris Mason 		return 0;
5488e7a84565SChris Mason 	}
5489e7a84565SChris Mason 	return 1;
5490e7a84565SChris Mason }
5491e7a84565SChris Mason 
54927bb86316SChris Mason /*
5493925baeddSChris Mason  * search the tree again to find a leaf with greater keys
54940f70abe2SChris Mason  * returns 0 if it found something or 1 if there are no greater leaves.
54950f70abe2SChris Mason  * returns < 0 on io errors.
549697571fd0SChris Mason  */
5497234b63a0SChris Mason int btrfs_next_leaf(struct btrfs_root *root, struct btrfs_path *path)
5498d97e63b6SChris Mason {
54993d7806ecSJan Schmidt 	return btrfs_next_old_leaf(root, path, 0);
55003d7806ecSJan Schmidt }
55013d7806ecSJan Schmidt 
550270c8a91cSJosef Bacik /* Release the path up to but not including the given level */
550370c8a91cSJosef Bacik static void btrfs_release_level(struct btrfs_path *path, int level)
550470c8a91cSJosef Bacik {
550570c8a91cSJosef Bacik 	int i;
550670c8a91cSJosef Bacik 
550770c8a91cSJosef Bacik 	for (i = 0; i < level; i++) {
550870c8a91cSJosef Bacik 		path->slots[i] = 0;
550970c8a91cSJosef Bacik 		if (!path->nodes[i])
551070c8a91cSJosef Bacik 			continue;
551170c8a91cSJosef Bacik 		if (path->locks[i]) {
551270c8a91cSJosef Bacik 			btrfs_tree_unlock_rw(path->nodes[i], path->locks[i]);
551370c8a91cSJosef Bacik 			path->locks[i] = 0;
551470c8a91cSJosef Bacik 		}
551570c8a91cSJosef Bacik 		free_extent_buffer(path->nodes[i]);
551670c8a91cSJosef Bacik 		path->nodes[i] = NULL;
551770c8a91cSJosef Bacik 	}
551870c8a91cSJosef Bacik }
551970c8a91cSJosef Bacik 
552070c8a91cSJosef Bacik /*
552170c8a91cSJosef Bacik  * This function assumes 2 things
552270c8a91cSJosef Bacik  *
552370c8a91cSJosef Bacik  * 1) You are using path->keep_locks
552470c8a91cSJosef Bacik  * 2) You are not inserting items.
552570c8a91cSJosef Bacik  *
552670c8a91cSJosef Bacik  * If either of these are not true do not use this function. If you need a next
552770c8a91cSJosef Bacik  * leaf with either of these not being true then this function can be easily
552870c8a91cSJosef Bacik  * adapted to do that, but at the moment these are the limitations.
552970c8a91cSJosef Bacik  */
553070c8a91cSJosef Bacik int btrfs_next_leaf_write(struct btrfs_trans_handle *trans,
553170c8a91cSJosef Bacik 			  struct btrfs_root *root, struct btrfs_path *path,
553270c8a91cSJosef Bacik 			  int del)
553370c8a91cSJosef Bacik {
553470c8a91cSJosef Bacik 	struct extent_buffer *b;
553570c8a91cSJosef Bacik 	struct btrfs_key key;
553670c8a91cSJosef Bacik 	u32 nritems;
553770c8a91cSJosef Bacik 	int level = 1;
553870c8a91cSJosef Bacik 	int slot;
553970c8a91cSJosef Bacik 	int ret = 1;
554070c8a91cSJosef Bacik 	int write_lock_level = BTRFS_MAX_LEVEL;
554170c8a91cSJosef Bacik 	int ins_len = del ? -1 : 0;
554270c8a91cSJosef Bacik 
554370c8a91cSJosef Bacik 	WARN_ON(!(path->keep_locks || path->really_keep_locks));
554470c8a91cSJosef Bacik 
554570c8a91cSJosef Bacik 	nritems = btrfs_header_nritems(path->nodes[0]);
554670c8a91cSJosef Bacik 	btrfs_item_key_to_cpu(path->nodes[0], &key, nritems - 1);
554770c8a91cSJosef Bacik 
554870c8a91cSJosef Bacik 	while (path->nodes[level]) {
554970c8a91cSJosef Bacik 		nritems = btrfs_header_nritems(path->nodes[level]);
555070c8a91cSJosef Bacik 		if (!(path->locks[level] & BTRFS_WRITE_LOCK)) {
555170c8a91cSJosef Bacik search:
555270c8a91cSJosef Bacik 			btrfs_release_path(path);
555370c8a91cSJosef Bacik 			ret = btrfs_search_slot(trans, root, &key, path,
555470c8a91cSJosef Bacik 						ins_len, 1);
555570c8a91cSJosef Bacik 			if (ret < 0)
555670c8a91cSJosef Bacik 				goto out;
555770c8a91cSJosef Bacik 			level = 1;
555870c8a91cSJosef Bacik 			continue;
555970c8a91cSJosef Bacik 		}
556070c8a91cSJosef Bacik 
556170c8a91cSJosef Bacik 		if (path->slots[level] >= nritems - 1) {
556270c8a91cSJosef Bacik 			level++;
556370c8a91cSJosef Bacik 			continue;
556470c8a91cSJosef Bacik 		}
556570c8a91cSJosef Bacik 
556670c8a91cSJosef Bacik 		btrfs_release_level(path, level);
556770c8a91cSJosef Bacik 		break;
556870c8a91cSJosef Bacik 	}
556970c8a91cSJosef Bacik 
557070c8a91cSJosef Bacik 	if (!path->nodes[level]) {
557170c8a91cSJosef Bacik 		ret = 1;
557270c8a91cSJosef Bacik 		goto out;
557370c8a91cSJosef Bacik 	}
557470c8a91cSJosef Bacik 
557570c8a91cSJosef Bacik 	path->slots[level]++;
557670c8a91cSJosef Bacik 	b = path->nodes[level];
557770c8a91cSJosef Bacik 
557870c8a91cSJosef Bacik 	while (b) {
557970c8a91cSJosef Bacik 		level = btrfs_header_level(b);
558070c8a91cSJosef Bacik 
558170c8a91cSJosef Bacik 		if (!should_cow_block(trans, root, b))
558270c8a91cSJosef Bacik 			goto cow_done;
558370c8a91cSJosef Bacik 
558470c8a91cSJosef Bacik 		btrfs_set_path_blocking(path);
558570c8a91cSJosef Bacik 		ret = btrfs_cow_block(trans, root, b,
558670c8a91cSJosef Bacik 				      path->nodes[level + 1],
558770c8a91cSJosef Bacik 				      path->slots[level + 1], &b);
558870c8a91cSJosef Bacik 		if (ret)
558970c8a91cSJosef Bacik 			goto out;
559070c8a91cSJosef Bacik cow_done:
559170c8a91cSJosef Bacik 		path->nodes[level] = b;
559270c8a91cSJosef Bacik 		btrfs_clear_path_blocking(path, NULL, 0);
559370c8a91cSJosef Bacik 		if (level != 0) {
559470c8a91cSJosef Bacik 			ret = setup_nodes_for_search(trans, root, path, b,
559570c8a91cSJosef Bacik 						     level, ins_len,
559670c8a91cSJosef Bacik 						     &write_lock_level);
559770c8a91cSJosef Bacik 			if (ret == -EAGAIN)
559870c8a91cSJosef Bacik 				goto search;
559970c8a91cSJosef Bacik 			if (ret)
560070c8a91cSJosef Bacik 				goto out;
560170c8a91cSJosef Bacik 
560270c8a91cSJosef Bacik 			b = path->nodes[level];
560370c8a91cSJosef Bacik 			slot = path->slots[level];
560470c8a91cSJosef Bacik 
560570c8a91cSJosef Bacik 			ret = read_block_for_search(trans, root, path,
560670c8a91cSJosef Bacik 						    &b, level, slot, &key, 0);
560770c8a91cSJosef Bacik 			if (ret == -EAGAIN)
560870c8a91cSJosef Bacik 				goto search;
560970c8a91cSJosef Bacik 			if (ret)
561070c8a91cSJosef Bacik 				goto out;
561170c8a91cSJosef Bacik 			level = btrfs_header_level(b);
561270c8a91cSJosef Bacik 			if (!btrfs_try_tree_write_lock(b)) {
561370c8a91cSJosef Bacik 				btrfs_set_path_blocking(path);
561470c8a91cSJosef Bacik 				btrfs_tree_lock(b);
561570c8a91cSJosef Bacik 				btrfs_clear_path_blocking(path, b,
561670c8a91cSJosef Bacik 							  BTRFS_WRITE_LOCK);
561770c8a91cSJosef Bacik 			}
561870c8a91cSJosef Bacik 			path->locks[level] = BTRFS_WRITE_LOCK;
561970c8a91cSJosef Bacik 			path->nodes[level] = b;
562070c8a91cSJosef Bacik 			path->slots[level] = 0;
562170c8a91cSJosef Bacik 		} else {
562270c8a91cSJosef Bacik 			path->slots[level] = 0;
562370c8a91cSJosef Bacik 			ret = 0;
562470c8a91cSJosef Bacik 			break;
562570c8a91cSJosef Bacik 		}
562670c8a91cSJosef Bacik 	}
562770c8a91cSJosef Bacik 
562870c8a91cSJosef Bacik out:
562970c8a91cSJosef Bacik 	if (ret)
563070c8a91cSJosef Bacik 		btrfs_release_path(path);
563170c8a91cSJosef Bacik 
563270c8a91cSJosef Bacik 	return ret;
563370c8a91cSJosef Bacik }
563470c8a91cSJosef Bacik 
56353d7806ecSJan Schmidt int btrfs_next_old_leaf(struct btrfs_root *root, struct btrfs_path *path,
56363d7806ecSJan Schmidt 			u64 time_seq)
56373d7806ecSJan Schmidt {
5638d97e63b6SChris Mason 	int slot;
56398e73f275SChris Mason 	int level;
56405f39d397SChris Mason 	struct extent_buffer *c;
56418e73f275SChris Mason 	struct extent_buffer *next;
5642925baeddSChris Mason 	struct btrfs_key key;
5643925baeddSChris Mason 	u32 nritems;
5644925baeddSChris Mason 	int ret;
56458e73f275SChris Mason 	int old_spinning = path->leave_spinning;
5646bd681513SChris Mason 	int next_rw_lock = 0;
5647925baeddSChris Mason 
5648925baeddSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
5649d397712bSChris Mason 	if (nritems == 0)
5650925baeddSChris Mason 		return 1;
5651925baeddSChris Mason 
56528e73f275SChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, nritems - 1);
56538e73f275SChris Mason again:
56548e73f275SChris Mason 	level = 1;
56558e73f275SChris Mason 	next = NULL;
5656bd681513SChris Mason 	next_rw_lock = 0;
5657b3b4aa74SDavid Sterba 	btrfs_release_path(path);
56588e73f275SChris Mason 
5659a2135011SChris Mason 	path->keep_locks = 1;
56608e73f275SChris Mason 	path->leave_spinning = 1;
56618e73f275SChris Mason 
56623d7806ecSJan Schmidt 	if (time_seq)
56633d7806ecSJan Schmidt 		ret = btrfs_search_old_slot(root, &key, path, time_seq);
56643d7806ecSJan Schmidt 	else
5665925baeddSChris Mason 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5666925baeddSChris Mason 	path->keep_locks = 0;
5667925baeddSChris Mason 
5668925baeddSChris Mason 	if (ret < 0)
5669925baeddSChris Mason 		return ret;
5670925baeddSChris Mason 
5671a2135011SChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
5672168fd7d2SChris Mason 	/*
5673168fd7d2SChris Mason 	 * by releasing the path above we dropped all our locks.  A balance
5674168fd7d2SChris Mason 	 * could have added more items next to the key that used to be
5675168fd7d2SChris Mason 	 * at the very end of the block.  So, check again here and
5676168fd7d2SChris Mason 	 * advance the path if there are now more items available.
5677168fd7d2SChris Mason 	 */
5678a2135011SChris Mason 	if (nritems > 0 && path->slots[0] < nritems - 1) {
5679e457afecSYan Zheng 		if (ret == 0)
5680168fd7d2SChris Mason 			path->slots[0]++;
56818e73f275SChris Mason 		ret = 0;
5682925baeddSChris Mason 		goto done;
5683925baeddSChris Mason 	}
5684d97e63b6SChris Mason 
5685234b63a0SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
56868e73f275SChris Mason 		if (!path->nodes[level]) {
56878e73f275SChris Mason 			ret = 1;
56888e73f275SChris Mason 			goto done;
56898e73f275SChris Mason 		}
56905f39d397SChris Mason 
5691d97e63b6SChris Mason 		slot = path->slots[level] + 1;
5692d97e63b6SChris Mason 		c = path->nodes[level];
56935f39d397SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
5694d97e63b6SChris Mason 			level++;
56958e73f275SChris Mason 			if (level == BTRFS_MAX_LEVEL) {
56968e73f275SChris Mason 				ret = 1;
56978e73f275SChris Mason 				goto done;
56988e73f275SChris Mason 			}
5699d97e63b6SChris Mason 			continue;
5700d97e63b6SChris Mason 		}
57015f39d397SChris Mason 
5702925baeddSChris Mason 		if (next) {
5703bd681513SChris Mason 			btrfs_tree_unlock_rw(next, next_rw_lock);
57045f39d397SChris Mason 			free_extent_buffer(next);
5705925baeddSChris Mason 		}
57065f39d397SChris Mason 
57078e73f275SChris Mason 		next = c;
5708bd681513SChris Mason 		next_rw_lock = path->locks[level];
57098e73f275SChris Mason 		ret = read_block_for_search(NULL, root, path, &next, level,
57105d9e75c4SJan Schmidt 					    slot, &key, 0);
57118e73f275SChris Mason 		if (ret == -EAGAIN)
57128e73f275SChris Mason 			goto again;
57135f39d397SChris Mason 
571476a05b35SChris Mason 		if (ret < 0) {
5715b3b4aa74SDavid Sterba 			btrfs_release_path(path);
571676a05b35SChris Mason 			goto done;
571776a05b35SChris Mason 		}
571876a05b35SChris Mason 
57195cd57b2cSChris Mason 		if (!path->skip_locking) {
5720bd681513SChris Mason 			ret = btrfs_try_tree_read_lock(next);
5721d42244a0SJan Schmidt 			if (!ret && time_seq) {
5722d42244a0SJan Schmidt 				/*
5723d42244a0SJan Schmidt 				 * If we don't get the lock, we may be racing
5724d42244a0SJan Schmidt 				 * with push_leaf_left, holding that lock while
5725d42244a0SJan Schmidt 				 * itself waiting for the leaf we've currently
5726d42244a0SJan Schmidt 				 * locked. To solve this situation, we give up
5727d42244a0SJan Schmidt 				 * on our lock and cycle.
5728d42244a0SJan Schmidt 				 */
5729cf538830SJan Schmidt 				free_extent_buffer(next);
5730d42244a0SJan Schmidt 				btrfs_release_path(path);
5731d42244a0SJan Schmidt 				cond_resched();
5732d42244a0SJan Schmidt 				goto again;
5733d42244a0SJan Schmidt 			}
57348e73f275SChris Mason 			if (!ret) {
57358e73f275SChris Mason 				btrfs_set_path_blocking(path);
5736bd681513SChris Mason 				btrfs_tree_read_lock(next);
5737bd681513SChris Mason 				btrfs_clear_path_blocking(path, next,
5738bd681513SChris Mason 							  BTRFS_READ_LOCK);
57398e73f275SChris Mason 			}
5740bd681513SChris Mason 			next_rw_lock = BTRFS_READ_LOCK;
5741bd681513SChris Mason 		}
5742d97e63b6SChris Mason 		break;
5743d97e63b6SChris Mason 	}
5744d97e63b6SChris Mason 	path->slots[level] = slot;
5745d97e63b6SChris Mason 	while (1) {
5746d97e63b6SChris Mason 		level--;
5747d97e63b6SChris Mason 		c = path->nodes[level];
5748925baeddSChris Mason 		if (path->locks[level])
5749bd681513SChris Mason 			btrfs_tree_unlock_rw(c, path->locks[level]);
57508e73f275SChris Mason 
57515f39d397SChris Mason 		free_extent_buffer(c);
5752d97e63b6SChris Mason 		path->nodes[level] = next;
5753d97e63b6SChris Mason 		path->slots[level] = 0;
5754a74a4b97SChris Mason 		if (!path->skip_locking)
5755bd681513SChris Mason 			path->locks[level] = next_rw_lock;
5756d97e63b6SChris Mason 		if (!level)
5757d97e63b6SChris Mason 			break;
5758b4ce94deSChris Mason 
57598e73f275SChris Mason 		ret = read_block_for_search(NULL, root, path, &next, level,
57605d9e75c4SJan Schmidt 					    0, &key, 0);
57618e73f275SChris Mason 		if (ret == -EAGAIN)
57628e73f275SChris Mason 			goto again;
57638e73f275SChris Mason 
576476a05b35SChris Mason 		if (ret < 0) {
5765b3b4aa74SDavid Sterba 			btrfs_release_path(path);
576676a05b35SChris Mason 			goto done;
576776a05b35SChris Mason 		}
576876a05b35SChris Mason 
57695cd57b2cSChris Mason 		if (!path->skip_locking) {
5770bd681513SChris Mason 			ret = btrfs_try_tree_read_lock(next);
57718e73f275SChris Mason 			if (!ret) {
57728e73f275SChris Mason 				btrfs_set_path_blocking(path);
5773bd681513SChris Mason 				btrfs_tree_read_lock(next);
5774bd681513SChris Mason 				btrfs_clear_path_blocking(path, next,
5775bd681513SChris Mason 							  BTRFS_READ_LOCK);
57768e73f275SChris Mason 			}
5777bd681513SChris Mason 			next_rw_lock = BTRFS_READ_LOCK;
5778bd681513SChris Mason 		}
5779d97e63b6SChris Mason 	}
57808e73f275SChris Mason 	ret = 0;
5781925baeddSChris Mason done:
5782f7c79f30SChris Mason 	unlock_up(path, 0, 1, 0, NULL);
57838e73f275SChris Mason 	path->leave_spinning = old_spinning;
57848e73f275SChris Mason 	if (!old_spinning)
57858e73f275SChris Mason 		btrfs_set_path_blocking(path);
57868e73f275SChris Mason 
57878e73f275SChris Mason 	return ret;
5788d97e63b6SChris Mason }
57890b86a832SChris Mason 
57903f157a2fSChris Mason /*
57913f157a2fSChris Mason  * this uses btrfs_prev_leaf to walk backwards in the tree, and keeps
57923f157a2fSChris Mason  * searching until it gets past min_objectid or finds an item of 'type'
57933f157a2fSChris Mason  *
57943f157a2fSChris Mason  * returns 0 if something is found, 1 if nothing was found and < 0 on error
57953f157a2fSChris Mason  */
57960b86a832SChris Mason int btrfs_previous_item(struct btrfs_root *root,
57970b86a832SChris Mason 			struct btrfs_path *path, u64 min_objectid,
57980b86a832SChris Mason 			int type)
57990b86a832SChris Mason {
58000b86a832SChris Mason 	struct btrfs_key found_key;
58010b86a832SChris Mason 	struct extent_buffer *leaf;
5802e02119d5SChris Mason 	u32 nritems;
58030b86a832SChris Mason 	int ret;
58040b86a832SChris Mason 
58050b86a832SChris Mason 	while (1) {
58060b86a832SChris Mason 		if (path->slots[0] == 0) {
5807b4ce94deSChris Mason 			btrfs_set_path_blocking(path);
58080b86a832SChris Mason 			ret = btrfs_prev_leaf(root, path);
58090b86a832SChris Mason 			if (ret != 0)
58100b86a832SChris Mason 				return ret;
58110b86a832SChris Mason 		} else {
58120b86a832SChris Mason 			path->slots[0]--;
58130b86a832SChris Mason 		}
58140b86a832SChris Mason 		leaf = path->nodes[0];
5815e02119d5SChris Mason 		nritems = btrfs_header_nritems(leaf);
5816e02119d5SChris Mason 		if (nritems == 0)
5817e02119d5SChris Mason 			return 1;
5818e02119d5SChris Mason 		if (path->slots[0] == nritems)
5819e02119d5SChris Mason 			path->slots[0]--;
5820e02119d5SChris Mason 
58210b86a832SChris Mason 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5822e02119d5SChris Mason 		if (found_key.objectid < min_objectid)
5823e02119d5SChris Mason 			break;
58240a4eefbbSYan Zheng 		if (found_key.type == type)
58250a4eefbbSYan Zheng 			return 0;
5826e02119d5SChris Mason 		if (found_key.objectid == min_objectid &&
5827e02119d5SChris Mason 		    found_key.type < type)
5828e02119d5SChris Mason 			break;
58290b86a832SChris Mason 	}
58300b86a832SChris Mason 	return 1;
58310b86a832SChris Mason }
5832