xref: /openbmc/linux/fs/btrfs/ctree.c (revision c8cc6341653721b54760480b0d0d9b5f09b46741)
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);
40afe5fea7STsutomu Itoh static void del_ptr(struct btrfs_root *root, struct btrfs_path *path,
41afe5fea7STsutomu Itoh 		    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);
4448a3b636SEric Sandeen static int btrfs_prev_leaf(struct btrfs_root *root, struct btrfs_path *path);
45d97e63b6SChris Mason 
462c90e5d6SChris Mason struct btrfs_path *btrfs_alloc_path(void)
472c90e5d6SChris Mason {
48df24a2b9SChris Mason 	struct btrfs_path *path;
49e00f7308SJeff Mahoney 	path = kmem_cache_zalloc(btrfs_path_cachep, GFP_NOFS);
50df24a2b9SChris Mason 	return path;
512c90e5d6SChris Mason }
522c90e5d6SChris Mason 
53b4ce94deSChris Mason /*
54b4ce94deSChris Mason  * set all locked nodes in the path to blocking locks.  This should
55b4ce94deSChris Mason  * be done before scheduling
56b4ce94deSChris Mason  */
57b4ce94deSChris Mason noinline void btrfs_set_path_blocking(struct btrfs_path *p)
58b4ce94deSChris Mason {
59b4ce94deSChris Mason 	int i;
60b4ce94deSChris Mason 	for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
61bd681513SChris Mason 		if (!p->nodes[i] || !p->locks[i])
62bd681513SChris Mason 			continue;
63bd681513SChris Mason 		btrfs_set_lock_blocking_rw(p->nodes[i], p->locks[i]);
64bd681513SChris Mason 		if (p->locks[i] == BTRFS_READ_LOCK)
65bd681513SChris Mason 			p->locks[i] = BTRFS_READ_LOCK_BLOCKING;
66bd681513SChris Mason 		else if (p->locks[i] == BTRFS_WRITE_LOCK)
67bd681513SChris Mason 			p->locks[i] = BTRFS_WRITE_LOCK_BLOCKING;
68b4ce94deSChris Mason 	}
69b4ce94deSChris Mason }
70b4ce94deSChris Mason 
71b4ce94deSChris Mason /*
72b4ce94deSChris Mason  * reset all the locked nodes in the patch to spinning locks.
734008c04aSChris Mason  *
744008c04aSChris Mason  * held is used to keep lockdep happy, when lockdep is enabled
754008c04aSChris Mason  * we set held to a blocking lock before we go around and
764008c04aSChris Mason  * retake all the spinlocks in the path.  You can safely use NULL
774008c04aSChris Mason  * for held
78b4ce94deSChris Mason  */
794008c04aSChris Mason noinline void btrfs_clear_path_blocking(struct btrfs_path *p,
80bd681513SChris Mason 					struct extent_buffer *held, int held_rw)
81b4ce94deSChris Mason {
82b4ce94deSChris Mason 	int i;
834008c04aSChris Mason 
844008c04aSChris Mason #ifdef CONFIG_DEBUG_LOCK_ALLOC
854008c04aSChris Mason 	/* lockdep really cares that we take all of these spinlocks
864008c04aSChris Mason 	 * in the right order.  If any of the locks in the path are not
874008c04aSChris Mason 	 * currently blocking, it is going to complain.  So, make really
884008c04aSChris Mason 	 * really sure by forcing the path to blocking before we clear
894008c04aSChris Mason 	 * the path blocking.
904008c04aSChris Mason 	 */
91bd681513SChris Mason 	if (held) {
92bd681513SChris Mason 		btrfs_set_lock_blocking_rw(held, held_rw);
93bd681513SChris Mason 		if (held_rw == BTRFS_WRITE_LOCK)
94bd681513SChris Mason 			held_rw = BTRFS_WRITE_LOCK_BLOCKING;
95bd681513SChris Mason 		else if (held_rw == BTRFS_READ_LOCK)
96bd681513SChris Mason 			held_rw = BTRFS_READ_LOCK_BLOCKING;
97bd681513SChris Mason 	}
984008c04aSChris Mason 	btrfs_set_path_blocking(p);
994008c04aSChris Mason #endif
1004008c04aSChris Mason 
1014008c04aSChris Mason 	for (i = BTRFS_MAX_LEVEL - 1; i >= 0; i--) {
102bd681513SChris Mason 		if (p->nodes[i] && p->locks[i]) {
103bd681513SChris Mason 			btrfs_clear_lock_blocking_rw(p->nodes[i], p->locks[i]);
104bd681513SChris Mason 			if (p->locks[i] == BTRFS_WRITE_LOCK_BLOCKING)
105bd681513SChris Mason 				p->locks[i] = BTRFS_WRITE_LOCK;
106bd681513SChris Mason 			else if (p->locks[i] == BTRFS_READ_LOCK_BLOCKING)
107bd681513SChris Mason 				p->locks[i] = BTRFS_READ_LOCK;
108bd681513SChris Mason 		}
109b4ce94deSChris Mason 	}
1104008c04aSChris Mason 
1114008c04aSChris Mason #ifdef CONFIG_DEBUG_LOCK_ALLOC
1124008c04aSChris Mason 	if (held)
113bd681513SChris Mason 		btrfs_clear_lock_blocking_rw(held, held_rw);
1144008c04aSChris Mason #endif
115b4ce94deSChris Mason }
116b4ce94deSChris Mason 
117d352ac68SChris Mason /* this also releases the path */
1182c90e5d6SChris Mason void btrfs_free_path(struct btrfs_path *p)
1192c90e5d6SChris Mason {
120ff175d57SJesper Juhl 	if (!p)
121ff175d57SJesper Juhl 		return;
122b3b4aa74SDavid Sterba 	btrfs_release_path(p);
1232c90e5d6SChris Mason 	kmem_cache_free(btrfs_path_cachep, p);
1242c90e5d6SChris Mason }
1252c90e5d6SChris Mason 
126d352ac68SChris Mason /*
127d352ac68SChris Mason  * path release drops references on the extent buffers in the path
128d352ac68SChris Mason  * and it drops any locks held by this path
129d352ac68SChris Mason  *
130d352ac68SChris Mason  * It is safe to call this on paths that no locks or extent buffers held.
131d352ac68SChris Mason  */
132b3b4aa74SDavid Sterba noinline void btrfs_release_path(struct btrfs_path *p)
133eb60ceacSChris Mason {
134eb60ceacSChris Mason 	int i;
135a2135011SChris Mason 
136234b63a0SChris Mason 	for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
1373f157a2fSChris Mason 		p->slots[i] = 0;
138eb60ceacSChris Mason 		if (!p->nodes[i])
139925baeddSChris Mason 			continue;
140925baeddSChris Mason 		if (p->locks[i]) {
141bd681513SChris Mason 			btrfs_tree_unlock_rw(p->nodes[i], p->locks[i]);
142925baeddSChris Mason 			p->locks[i] = 0;
143925baeddSChris Mason 		}
1445f39d397SChris Mason 		free_extent_buffer(p->nodes[i]);
1453f157a2fSChris Mason 		p->nodes[i] = NULL;
146eb60ceacSChris Mason 	}
147eb60ceacSChris Mason }
148eb60ceacSChris Mason 
149d352ac68SChris Mason /*
150d352ac68SChris Mason  * safely gets a reference on the root node of a tree.  A lock
151d352ac68SChris Mason  * is not taken, so a concurrent writer may put a different node
152d352ac68SChris Mason  * at the root of the tree.  See btrfs_lock_root_node for the
153d352ac68SChris Mason  * looping required.
154d352ac68SChris Mason  *
155d352ac68SChris Mason  * The extent buffer returned by this has a reference taken, so
156d352ac68SChris Mason  * it won't disappear.  It may stop being the root of the tree
157d352ac68SChris Mason  * at any time because there are no locks held.
158d352ac68SChris Mason  */
159925baeddSChris Mason struct extent_buffer *btrfs_root_node(struct btrfs_root *root)
160925baeddSChris Mason {
161925baeddSChris Mason 	struct extent_buffer *eb;
162240f62c8SChris Mason 
1633083ee2eSJosef Bacik 	while (1) {
164240f62c8SChris Mason 		rcu_read_lock();
165240f62c8SChris Mason 		eb = rcu_dereference(root->node);
1663083ee2eSJosef Bacik 
1673083ee2eSJosef Bacik 		/*
1683083ee2eSJosef Bacik 		 * RCU really hurts here, we could free up the root node because
1693083ee2eSJosef Bacik 		 * it was cow'ed but we may not get the new root node yet so do
1703083ee2eSJosef Bacik 		 * the inc_not_zero dance and if it doesn't work then
1713083ee2eSJosef Bacik 		 * synchronize_rcu and try again.
1723083ee2eSJosef Bacik 		 */
1733083ee2eSJosef Bacik 		if (atomic_inc_not_zero(&eb->refs)) {
174240f62c8SChris Mason 			rcu_read_unlock();
1753083ee2eSJosef Bacik 			break;
1763083ee2eSJosef Bacik 		}
1773083ee2eSJosef Bacik 		rcu_read_unlock();
1783083ee2eSJosef Bacik 		synchronize_rcu();
1793083ee2eSJosef Bacik 	}
180925baeddSChris Mason 	return eb;
181925baeddSChris Mason }
182925baeddSChris Mason 
183d352ac68SChris Mason /* loop around taking references on and locking the root node of the
184d352ac68SChris Mason  * tree until you end up with a lock on the root.  A locked buffer
185d352ac68SChris Mason  * is returned, with a reference held.
186d352ac68SChris Mason  */
187925baeddSChris Mason struct extent_buffer *btrfs_lock_root_node(struct btrfs_root *root)
188925baeddSChris Mason {
189925baeddSChris Mason 	struct extent_buffer *eb;
190925baeddSChris Mason 
191925baeddSChris Mason 	while (1) {
192925baeddSChris Mason 		eb = btrfs_root_node(root);
193925baeddSChris Mason 		btrfs_tree_lock(eb);
194240f62c8SChris Mason 		if (eb == root->node)
195925baeddSChris Mason 			break;
196925baeddSChris Mason 		btrfs_tree_unlock(eb);
197925baeddSChris Mason 		free_extent_buffer(eb);
198925baeddSChris Mason 	}
199925baeddSChris Mason 	return eb;
200925baeddSChris Mason }
201925baeddSChris Mason 
202bd681513SChris Mason /* loop around taking references on and locking the root node of the
203bd681513SChris Mason  * tree until you end up with a lock on the root.  A locked buffer
204bd681513SChris Mason  * is returned, with a reference held.
205bd681513SChris Mason  */
20648a3b636SEric Sandeen static struct extent_buffer *btrfs_read_lock_root_node(struct btrfs_root *root)
207bd681513SChris Mason {
208bd681513SChris Mason 	struct extent_buffer *eb;
209bd681513SChris Mason 
210bd681513SChris Mason 	while (1) {
211bd681513SChris Mason 		eb = btrfs_root_node(root);
212bd681513SChris Mason 		btrfs_tree_read_lock(eb);
213bd681513SChris Mason 		if (eb == root->node)
214bd681513SChris Mason 			break;
215bd681513SChris Mason 		btrfs_tree_read_unlock(eb);
216bd681513SChris Mason 		free_extent_buffer(eb);
217bd681513SChris Mason 	}
218bd681513SChris Mason 	return eb;
219bd681513SChris Mason }
220bd681513SChris Mason 
221d352ac68SChris Mason /* cowonly root (everything not a reference counted cow subvolume), just get
222d352ac68SChris Mason  * put onto a simple dirty list.  transaction.c walks this to make sure they
223d352ac68SChris Mason  * get properly updated on disk.
224d352ac68SChris Mason  */
2250b86a832SChris Mason static void add_root_to_dirty_list(struct btrfs_root *root)
2260b86a832SChris Mason {
227e5846fc6SChris Mason 	spin_lock(&root->fs_info->trans_lock);
2280b86a832SChris Mason 	if (root->track_dirty && list_empty(&root->dirty_list)) {
2290b86a832SChris Mason 		list_add(&root->dirty_list,
2300b86a832SChris Mason 			 &root->fs_info->dirty_cowonly_roots);
2310b86a832SChris Mason 	}
232e5846fc6SChris Mason 	spin_unlock(&root->fs_info->trans_lock);
2330b86a832SChris Mason }
2340b86a832SChris Mason 
235d352ac68SChris Mason /*
236d352ac68SChris Mason  * used by snapshot creation to make a copy of a root for a tree with
237d352ac68SChris Mason  * a given objectid.  The buffer with the new root node is returned in
238d352ac68SChris Mason  * cow_ret, and this func returns zero on success or a negative error code.
239d352ac68SChris Mason  */
240be20aa9dSChris Mason int btrfs_copy_root(struct btrfs_trans_handle *trans,
241be20aa9dSChris Mason 		      struct btrfs_root *root,
242be20aa9dSChris Mason 		      struct extent_buffer *buf,
243be20aa9dSChris Mason 		      struct extent_buffer **cow_ret, u64 new_root_objectid)
244be20aa9dSChris Mason {
245be20aa9dSChris Mason 	struct extent_buffer *cow;
246be20aa9dSChris Mason 	int ret = 0;
247be20aa9dSChris Mason 	int level;
2485d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
249be20aa9dSChris Mason 
250be20aa9dSChris Mason 	WARN_ON(root->ref_cows && trans->transid !=
251be20aa9dSChris Mason 		root->fs_info->running_transaction->transid);
252be20aa9dSChris Mason 	WARN_ON(root->ref_cows && trans->transid != root->last_trans);
253be20aa9dSChris Mason 
254be20aa9dSChris Mason 	level = btrfs_header_level(buf);
2555d4f98a2SYan Zheng 	if (level == 0)
2565d4f98a2SYan Zheng 		btrfs_item_key(buf, &disk_key, 0);
2575d4f98a2SYan Zheng 	else
2585d4f98a2SYan Zheng 		btrfs_node_key(buf, &disk_key, 0);
25931840ae1SZheng Yan 
2605d4f98a2SYan Zheng 	cow = btrfs_alloc_free_block(trans, root, buf->len, 0,
2615d4f98a2SYan Zheng 				     new_root_objectid, &disk_key, level,
2625581a51aSJan Schmidt 				     buf->start, 0);
2635d4f98a2SYan Zheng 	if (IS_ERR(cow))
264be20aa9dSChris Mason 		return PTR_ERR(cow);
265be20aa9dSChris Mason 
266be20aa9dSChris Mason 	copy_extent_buffer(cow, buf, 0, 0, cow->len);
267be20aa9dSChris Mason 	btrfs_set_header_bytenr(cow, cow->start);
268be20aa9dSChris Mason 	btrfs_set_header_generation(cow, trans->transid);
2695d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
2705d4f98a2SYan Zheng 	btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
2715d4f98a2SYan Zheng 				     BTRFS_HEADER_FLAG_RELOC);
2725d4f98a2SYan Zheng 	if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
2735d4f98a2SYan Zheng 		btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
2745d4f98a2SYan Zheng 	else
275be20aa9dSChris Mason 		btrfs_set_header_owner(cow, new_root_objectid);
276be20aa9dSChris Mason 
2772b82032cSYan Zheng 	write_extent_buffer(cow, root->fs_info->fsid,
2782b82032cSYan Zheng 			    (unsigned long)btrfs_header_fsid(cow),
2792b82032cSYan Zheng 			    BTRFS_FSID_SIZE);
2802b82032cSYan Zheng 
281be20aa9dSChris Mason 	WARN_ON(btrfs_header_generation(buf) > trans->transid);
2825d4f98a2SYan Zheng 	if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
28366d7e7f0SArne Jansen 		ret = btrfs_inc_ref(trans, root, cow, 1, 1);
2845d4f98a2SYan Zheng 	else
28566d7e7f0SArne Jansen 		ret = btrfs_inc_ref(trans, root, cow, 0, 1);
2864aec2b52SChris Mason 
287be20aa9dSChris Mason 	if (ret)
288be20aa9dSChris Mason 		return ret;
289be20aa9dSChris Mason 
290be20aa9dSChris Mason 	btrfs_mark_buffer_dirty(cow);
291be20aa9dSChris Mason 	*cow_ret = cow;
292be20aa9dSChris Mason 	return 0;
293be20aa9dSChris Mason }
294be20aa9dSChris Mason 
295bd989ba3SJan Schmidt enum mod_log_op {
296bd989ba3SJan Schmidt 	MOD_LOG_KEY_REPLACE,
297bd989ba3SJan Schmidt 	MOD_LOG_KEY_ADD,
298bd989ba3SJan Schmidt 	MOD_LOG_KEY_REMOVE,
299bd989ba3SJan Schmidt 	MOD_LOG_KEY_REMOVE_WHILE_FREEING,
300bd989ba3SJan Schmidt 	MOD_LOG_KEY_REMOVE_WHILE_MOVING,
301bd989ba3SJan Schmidt 	MOD_LOG_MOVE_KEYS,
302bd989ba3SJan Schmidt 	MOD_LOG_ROOT_REPLACE,
303bd989ba3SJan Schmidt };
304bd989ba3SJan Schmidt 
305bd989ba3SJan Schmidt struct tree_mod_move {
306bd989ba3SJan Schmidt 	int dst_slot;
307bd989ba3SJan Schmidt 	int nr_items;
308bd989ba3SJan Schmidt };
309bd989ba3SJan Schmidt 
310bd989ba3SJan Schmidt struct tree_mod_root {
311bd989ba3SJan Schmidt 	u64 logical;
312bd989ba3SJan Schmidt 	u8 level;
313bd989ba3SJan Schmidt };
314bd989ba3SJan Schmidt 
315bd989ba3SJan Schmidt struct tree_mod_elem {
316bd989ba3SJan Schmidt 	struct rb_node node;
317bd989ba3SJan Schmidt 	u64 index;		/* shifted logical */
318097b8a7cSJan Schmidt 	u64 seq;
319bd989ba3SJan Schmidt 	enum mod_log_op op;
320bd989ba3SJan Schmidt 
321bd989ba3SJan Schmidt 	/* this is used for MOD_LOG_KEY_* and MOD_LOG_MOVE_KEYS operations */
322bd989ba3SJan Schmidt 	int slot;
323bd989ba3SJan Schmidt 
324bd989ba3SJan Schmidt 	/* this is used for MOD_LOG_KEY* and MOD_LOG_ROOT_REPLACE */
325bd989ba3SJan Schmidt 	u64 generation;
326bd989ba3SJan Schmidt 
327bd989ba3SJan Schmidt 	/* those are used for op == MOD_LOG_KEY_{REPLACE,REMOVE} */
328bd989ba3SJan Schmidt 	struct btrfs_disk_key key;
329bd989ba3SJan Schmidt 	u64 blockptr;
330bd989ba3SJan Schmidt 
331bd989ba3SJan Schmidt 	/* this is used for op == MOD_LOG_MOVE_KEYS */
332bd989ba3SJan Schmidt 	struct tree_mod_move move;
333bd989ba3SJan Schmidt 
334bd989ba3SJan Schmidt 	/* this is used for op == MOD_LOG_ROOT_REPLACE */
335bd989ba3SJan Schmidt 	struct tree_mod_root old_root;
336bd989ba3SJan Schmidt };
337bd989ba3SJan Schmidt 
338097b8a7cSJan Schmidt static inline void tree_mod_log_read_lock(struct btrfs_fs_info *fs_info)
339bd989ba3SJan Schmidt {
340097b8a7cSJan Schmidt 	read_lock(&fs_info->tree_mod_log_lock);
341bd989ba3SJan Schmidt }
342bd989ba3SJan Schmidt 
343097b8a7cSJan Schmidt static inline void tree_mod_log_read_unlock(struct btrfs_fs_info *fs_info)
344097b8a7cSJan Schmidt {
345097b8a7cSJan Schmidt 	read_unlock(&fs_info->tree_mod_log_lock);
346097b8a7cSJan Schmidt }
347097b8a7cSJan Schmidt 
348097b8a7cSJan Schmidt static inline void tree_mod_log_write_lock(struct btrfs_fs_info *fs_info)
349097b8a7cSJan Schmidt {
350097b8a7cSJan Schmidt 	write_lock(&fs_info->tree_mod_log_lock);
351097b8a7cSJan Schmidt }
352097b8a7cSJan Schmidt 
353097b8a7cSJan Schmidt static inline void tree_mod_log_write_unlock(struct btrfs_fs_info *fs_info)
354097b8a7cSJan Schmidt {
355097b8a7cSJan Schmidt 	write_unlock(&fs_info->tree_mod_log_lock);
356097b8a7cSJan Schmidt }
357097b8a7cSJan Schmidt 
358097b8a7cSJan Schmidt /*
359fc36ed7eSJan Schmidt  * Increment the upper half of tree_mod_seq, set lower half zero.
360fc36ed7eSJan Schmidt  *
361fc36ed7eSJan Schmidt  * Must be called with fs_info->tree_mod_seq_lock held.
362fc36ed7eSJan Schmidt  */
363fc36ed7eSJan Schmidt static inline u64 btrfs_inc_tree_mod_seq_major(struct btrfs_fs_info *fs_info)
364fc36ed7eSJan Schmidt {
365fc36ed7eSJan Schmidt 	u64 seq = atomic64_read(&fs_info->tree_mod_seq);
366fc36ed7eSJan Schmidt 	seq &= 0xffffffff00000000ull;
367fc36ed7eSJan Schmidt 	seq += 1ull << 32;
368fc36ed7eSJan Schmidt 	atomic64_set(&fs_info->tree_mod_seq, seq);
369fc36ed7eSJan Schmidt 	return seq;
370fc36ed7eSJan Schmidt }
371fc36ed7eSJan Schmidt 
372fc36ed7eSJan Schmidt /*
373fc36ed7eSJan Schmidt  * Increment the lower half of tree_mod_seq.
374fc36ed7eSJan Schmidt  *
375fc36ed7eSJan Schmidt  * Must be called with fs_info->tree_mod_seq_lock held. The way major numbers
376fc36ed7eSJan Schmidt  * are generated should not technically require a spin lock here. (Rationale:
377fc36ed7eSJan Schmidt  * incrementing the minor while incrementing the major seq number is between its
378fc36ed7eSJan Schmidt  * atomic64_read and atomic64_set calls doesn't duplicate sequence numbers, it
379fc36ed7eSJan Schmidt  * just returns a unique sequence number as usual.) We have decided to leave
380fc36ed7eSJan Schmidt  * that requirement in here and rethink it once we notice it really imposes a
381fc36ed7eSJan Schmidt  * problem on some workload.
382fc36ed7eSJan Schmidt  */
383fc36ed7eSJan Schmidt static inline u64 btrfs_inc_tree_mod_seq_minor(struct btrfs_fs_info *fs_info)
384fc36ed7eSJan Schmidt {
385fc36ed7eSJan Schmidt 	return atomic64_inc_return(&fs_info->tree_mod_seq);
386fc36ed7eSJan Schmidt }
387fc36ed7eSJan Schmidt 
388fc36ed7eSJan Schmidt /*
389fc36ed7eSJan Schmidt  * return the last minor in the previous major tree_mod_seq number
390fc36ed7eSJan Schmidt  */
391fc36ed7eSJan Schmidt u64 btrfs_tree_mod_seq_prev(u64 seq)
392fc36ed7eSJan Schmidt {
393fc36ed7eSJan Schmidt 	return (seq & 0xffffffff00000000ull) - 1ull;
394fc36ed7eSJan Schmidt }
395fc36ed7eSJan Schmidt 
396fc36ed7eSJan Schmidt /*
397097b8a7cSJan Schmidt  * This adds a new blocker to the tree mod log's blocker list if the @elem
398097b8a7cSJan Schmidt  * passed does not already have a sequence number set. So when a caller expects
399097b8a7cSJan Schmidt  * to record tree modifications, it should ensure to set elem->seq to zero
400097b8a7cSJan Schmidt  * before calling btrfs_get_tree_mod_seq.
401097b8a7cSJan Schmidt  * Returns a fresh, unused tree log modification sequence number, even if no new
402097b8a7cSJan Schmidt  * blocker was added.
403097b8a7cSJan Schmidt  */
404097b8a7cSJan Schmidt u64 btrfs_get_tree_mod_seq(struct btrfs_fs_info *fs_info,
405bd989ba3SJan Schmidt 			   struct seq_list *elem)
406bd989ba3SJan Schmidt {
407097b8a7cSJan Schmidt 	u64 seq;
408097b8a7cSJan Schmidt 
409097b8a7cSJan Schmidt 	tree_mod_log_write_lock(fs_info);
410bd989ba3SJan Schmidt 	spin_lock(&fs_info->tree_mod_seq_lock);
411097b8a7cSJan Schmidt 	if (!elem->seq) {
412fc36ed7eSJan Schmidt 		elem->seq = btrfs_inc_tree_mod_seq_major(fs_info);
413097b8a7cSJan Schmidt 		list_add_tail(&elem->list, &fs_info->tree_mod_seq_list);
414097b8a7cSJan Schmidt 	}
415fc36ed7eSJan Schmidt 	seq = btrfs_inc_tree_mod_seq_minor(fs_info);
416bd989ba3SJan Schmidt 	spin_unlock(&fs_info->tree_mod_seq_lock);
417097b8a7cSJan Schmidt 	tree_mod_log_write_unlock(fs_info);
418097b8a7cSJan Schmidt 
419097b8a7cSJan Schmidt 	return seq;
420bd989ba3SJan Schmidt }
421bd989ba3SJan Schmidt 
422bd989ba3SJan Schmidt void btrfs_put_tree_mod_seq(struct btrfs_fs_info *fs_info,
423bd989ba3SJan Schmidt 			    struct seq_list *elem)
424bd989ba3SJan Schmidt {
425bd989ba3SJan Schmidt 	struct rb_root *tm_root;
426bd989ba3SJan Schmidt 	struct rb_node *node;
427bd989ba3SJan Schmidt 	struct rb_node *next;
428bd989ba3SJan Schmidt 	struct seq_list *cur_elem;
429bd989ba3SJan Schmidt 	struct tree_mod_elem *tm;
430bd989ba3SJan Schmidt 	u64 min_seq = (u64)-1;
431bd989ba3SJan Schmidt 	u64 seq_putting = elem->seq;
432bd989ba3SJan Schmidt 
433bd989ba3SJan Schmidt 	if (!seq_putting)
434bd989ba3SJan Schmidt 		return;
435bd989ba3SJan Schmidt 
436bd989ba3SJan Schmidt 	spin_lock(&fs_info->tree_mod_seq_lock);
437bd989ba3SJan Schmidt 	list_del(&elem->list);
438097b8a7cSJan Schmidt 	elem->seq = 0;
439bd989ba3SJan Schmidt 
440bd989ba3SJan Schmidt 	list_for_each_entry(cur_elem, &fs_info->tree_mod_seq_list, list) {
441097b8a7cSJan Schmidt 		if (cur_elem->seq < min_seq) {
442bd989ba3SJan Schmidt 			if (seq_putting > cur_elem->seq) {
443bd989ba3SJan Schmidt 				/*
444bd989ba3SJan Schmidt 				 * blocker with lower sequence number exists, we
445bd989ba3SJan Schmidt 				 * cannot remove anything from the log
446bd989ba3SJan Schmidt 				 */
447097b8a7cSJan Schmidt 				spin_unlock(&fs_info->tree_mod_seq_lock);
448097b8a7cSJan Schmidt 				return;
449bd989ba3SJan Schmidt 			}
450bd989ba3SJan Schmidt 			min_seq = cur_elem->seq;
451bd989ba3SJan Schmidt 		}
452bd989ba3SJan Schmidt 	}
453097b8a7cSJan Schmidt 	spin_unlock(&fs_info->tree_mod_seq_lock);
454097b8a7cSJan Schmidt 
455097b8a7cSJan Schmidt 	/*
456bd989ba3SJan Schmidt 	 * anything that's lower than the lowest existing (read: blocked)
457bd989ba3SJan Schmidt 	 * sequence number can be removed from the tree.
458bd989ba3SJan Schmidt 	 */
459097b8a7cSJan Schmidt 	tree_mod_log_write_lock(fs_info);
460bd989ba3SJan Schmidt 	tm_root = &fs_info->tree_mod_log;
461bd989ba3SJan Schmidt 	for (node = rb_first(tm_root); node; node = next) {
462bd989ba3SJan Schmidt 		next = rb_next(node);
463bd989ba3SJan Schmidt 		tm = container_of(node, struct tree_mod_elem, node);
464097b8a7cSJan Schmidt 		if (tm->seq > min_seq)
465bd989ba3SJan Schmidt 			continue;
466bd989ba3SJan Schmidt 		rb_erase(node, tm_root);
467bd989ba3SJan Schmidt 		kfree(tm);
468bd989ba3SJan Schmidt 	}
469097b8a7cSJan Schmidt 	tree_mod_log_write_unlock(fs_info);
470bd989ba3SJan Schmidt }
471bd989ba3SJan Schmidt 
472bd989ba3SJan Schmidt /*
473bd989ba3SJan Schmidt  * key order of the log:
474bd989ba3SJan Schmidt  *       index -> sequence
475bd989ba3SJan Schmidt  *
476bd989ba3SJan Schmidt  * the index is the shifted logical of the *new* root node for root replace
477bd989ba3SJan Schmidt  * operations, or the shifted logical of the affected block for all other
478bd989ba3SJan Schmidt  * operations.
479bd989ba3SJan Schmidt  */
480bd989ba3SJan Schmidt static noinline int
481bd989ba3SJan Schmidt __tree_mod_log_insert(struct btrfs_fs_info *fs_info, struct tree_mod_elem *tm)
482bd989ba3SJan Schmidt {
483bd989ba3SJan Schmidt 	struct rb_root *tm_root;
484bd989ba3SJan Schmidt 	struct rb_node **new;
485bd989ba3SJan Schmidt 	struct rb_node *parent = NULL;
486bd989ba3SJan Schmidt 	struct tree_mod_elem *cur;
487*c8cc6341SJosef Bacik 	int ret = 0;
488bd989ba3SJan Schmidt 
489*c8cc6341SJosef Bacik 	BUG_ON(!tm);
490*c8cc6341SJosef Bacik 
491*c8cc6341SJosef Bacik 	tree_mod_log_write_lock(fs_info);
492*c8cc6341SJosef Bacik 	if (list_empty(&fs_info->tree_mod_seq_list)) {
493*c8cc6341SJosef Bacik 		tree_mod_log_write_unlock(fs_info);
494*c8cc6341SJosef Bacik 		/*
495*c8cc6341SJosef Bacik 		 * Ok we no longer care about logging modifications, free up tm
496*c8cc6341SJosef Bacik 		 * and return 0.  Any callers shouldn't be using tm after
497*c8cc6341SJosef Bacik 		 * calling tree_mod_log_insert, but if they do we can just
498*c8cc6341SJosef Bacik 		 * change this to return a special error code to let the callers
499*c8cc6341SJosef Bacik 		 * do their own thing.
500*c8cc6341SJosef Bacik 		 */
501*c8cc6341SJosef Bacik 		kfree(tm);
502*c8cc6341SJosef Bacik 		return 0;
503*c8cc6341SJosef Bacik 	}
504*c8cc6341SJosef Bacik 
505*c8cc6341SJosef Bacik 	spin_lock(&fs_info->tree_mod_seq_lock);
506*c8cc6341SJosef Bacik 	tm->seq = btrfs_inc_tree_mod_seq_minor(fs_info);
507*c8cc6341SJosef Bacik 	spin_unlock(&fs_info->tree_mod_seq_lock);
508bd989ba3SJan Schmidt 
509bd989ba3SJan Schmidt 	tm_root = &fs_info->tree_mod_log;
510bd989ba3SJan Schmidt 	new = &tm_root->rb_node;
511bd989ba3SJan Schmidt 	while (*new) {
512bd989ba3SJan Schmidt 		cur = container_of(*new, struct tree_mod_elem, node);
513bd989ba3SJan Schmidt 		parent = *new;
514bd989ba3SJan Schmidt 		if (cur->index < tm->index)
515bd989ba3SJan Schmidt 			new = &((*new)->rb_left);
516bd989ba3SJan Schmidt 		else if (cur->index > tm->index)
517bd989ba3SJan Schmidt 			new = &((*new)->rb_right);
518097b8a7cSJan Schmidt 		else if (cur->seq < tm->seq)
519bd989ba3SJan Schmidt 			new = &((*new)->rb_left);
520097b8a7cSJan Schmidt 		else if (cur->seq > tm->seq)
521bd989ba3SJan Schmidt 			new = &((*new)->rb_right);
522bd989ba3SJan Schmidt 		else {
523*c8cc6341SJosef Bacik 			ret = -EEXIST;
524bd989ba3SJan Schmidt 			kfree(tm);
525*c8cc6341SJosef Bacik 			goto out;
526bd989ba3SJan Schmidt 		}
527bd989ba3SJan Schmidt 	}
528bd989ba3SJan Schmidt 
529bd989ba3SJan Schmidt 	rb_link_node(&tm->node, parent, new);
530bd989ba3SJan Schmidt 	rb_insert_color(&tm->node, tm_root);
531*c8cc6341SJosef Bacik out:
532*c8cc6341SJosef Bacik 	tree_mod_log_write_unlock(fs_info);
533*c8cc6341SJosef Bacik 	return ret;
534bd989ba3SJan Schmidt }
535bd989ba3SJan Schmidt 
536097b8a7cSJan Schmidt /*
537097b8a7cSJan Schmidt  * Determines if logging can be omitted. Returns 1 if it can. Otherwise, it
538097b8a7cSJan Schmidt  * returns zero with the tree_mod_log_lock acquired. The caller must hold
539097b8a7cSJan Schmidt  * this until all tree mod log insertions are recorded in the rb tree and then
540097b8a7cSJan Schmidt  * call tree_mod_log_write_unlock() to release.
541097b8a7cSJan Schmidt  */
542e9b7fd4dSJan Schmidt static inline int tree_mod_dont_log(struct btrfs_fs_info *fs_info,
543e9b7fd4dSJan Schmidt 				    struct extent_buffer *eb) {
544e9b7fd4dSJan Schmidt 	smp_mb();
545e9b7fd4dSJan Schmidt 	if (list_empty(&(fs_info)->tree_mod_seq_list))
546e9b7fd4dSJan Schmidt 		return 1;
547097b8a7cSJan Schmidt 	if (eb && btrfs_header_level(eb) == 0)
548e9b7fd4dSJan Schmidt 		return 1;
549e9b7fd4dSJan Schmidt 	return 0;
550e9b7fd4dSJan Schmidt }
551e9b7fd4dSJan Schmidt 
552097b8a7cSJan Schmidt static inline int
553097b8a7cSJan Schmidt __tree_mod_log_insert_key(struct btrfs_fs_info *fs_info,
554bd989ba3SJan Schmidt 			  struct extent_buffer *eb, int slot,
555bd989ba3SJan Schmidt 			  enum mod_log_op op, gfp_t flags)
556bd989ba3SJan Schmidt {
557097b8a7cSJan Schmidt 	struct tree_mod_elem *tm;
558bd989ba3SJan Schmidt 
559*c8cc6341SJosef Bacik 	tm = kzalloc(sizeof(*tm), flags);
560*c8cc6341SJosef Bacik 	if (!tm)
561*c8cc6341SJosef Bacik 		return -ENOMEM;
562bd989ba3SJan Schmidt 
563bd989ba3SJan Schmidt 	tm->index = eb->start >> PAGE_CACHE_SHIFT;
564bd989ba3SJan Schmidt 	if (op != MOD_LOG_KEY_ADD) {
565bd989ba3SJan Schmidt 		btrfs_node_key(eb, &tm->key, slot);
566bd989ba3SJan Schmidt 		tm->blockptr = btrfs_node_blockptr(eb, slot);
567bd989ba3SJan Schmidt 	}
568bd989ba3SJan Schmidt 	tm->op = op;
569bd989ba3SJan Schmidt 	tm->slot = slot;
570bd989ba3SJan Schmidt 	tm->generation = btrfs_node_ptr_generation(eb, slot);
571bd989ba3SJan Schmidt 
572097b8a7cSJan Schmidt 	return __tree_mod_log_insert(fs_info, tm);
573097b8a7cSJan Schmidt }
574097b8a7cSJan Schmidt 
575097b8a7cSJan Schmidt static noinline int
576*c8cc6341SJosef Bacik tree_mod_log_insert_key(struct btrfs_fs_info *fs_info,
577097b8a7cSJan Schmidt 			struct extent_buffer *eb, int slot,
578097b8a7cSJan Schmidt 			enum mod_log_op op, gfp_t flags)
579097b8a7cSJan Schmidt {
580097b8a7cSJan Schmidt 	if (tree_mod_dont_log(fs_info, eb))
581097b8a7cSJan Schmidt 		return 0;
582097b8a7cSJan Schmidt 
583*c8cc6341SJosef Bacik 	return __tree_mod_log_insert_key(fs_info, eb, slot, op, flags);
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++) {
604*c8cc6341SJosef Bacik 		ret = __tree_mod_log_insert_key(fs_info, eb, i + dst_slot,
605*c8cc6341SJosef Bacik 				MOD_LOG_KEY_REMOVE_WHILE_MOVING, GFP_NOFS);
606bd989ba3SJan Schmidt 		BUG_ON(ret < 0);
607bd989ba3SJan Schmidt 	}
608bd989ba3SJan Schmidt 
609*c8cc6341SJosef Bacik 	tm = kzalloc(sizeof(*tm), flags);
610*c8cc6341SJosef Bacik 	if (!tm)
611*c8cc6341SJosef Bacik 		return -ENOMEM;
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 
619*c8cc6341SJosef Bacik 	return __tree_mod_log_insert(fs_info, tm);
620bd989ba3SJan Schmidt }
621bd989ba3SJan Schmidt 
622097b8a7cSJan Schmidt static inline void
623097b8a7cSJan Schmidt __tree_mod_log_free_eb(struct btrfs_fs_info *fs_info, struct extent_buffer *eb)
624097b8a7cSJan Schmidt {
625097b8a7cSJan Schmidt 	int i;
626097b8a7cSJan Schmidt 	u32 nritems;
627097b8a7cSJan Schmidt 	int ret;
628097b8a7cSJan Schmidt 
629b12a3b1eSChris Mason 	if (btrfs_header_level(eb) == 0)
630b12a3b1eSChris Mason 		return;
631b12a3b1eSChris Mason 
632097b8a7cSJan Schmidt 	nritems = btrfs_header_nritems(eb);
633097b8a7cSJan Schmidt 	for (i = nritems - 1; i >= 0; i--) {
634*c8cc6341SJosef Bacik 		ret = __tree_mod_log_insert_key(fs_info, eb, i,
635*c8cc6341SJosef Bacik 				MOD_LOG_KEY_REMOVE_WHILE_FREEING, GFP_NOFS);
636097b8a7cSJan Schmidt 		BUG_ON(ret < 0);
637097b8a7cSJan Schmidt 	}
638097b8a7cSJan Schmidt }
639097b8a7cSJan Schmidt 
640bd989ba3SJan Schmidt static noinline int
641bd989ba3SJan Schmidt tree_mod_log_insert_root(struct btrfs_fs_info *fs_info,
642bd989ba3SJan Schmidt 			 struct extent_buffer *old_root,
64390f8d62eSJan Schmidt 			 struct extent_buffer *new_root, gfp_t flags,
64490f8d62eSJan Schmidt 			 int log_removal)
645bd989ba3SJan Schmidt {
646bd989ba3SJan Schmidt 	struct tree_mod_elem *tm;
647bd989ba3SJan Schmidt 
648097b8a7cSJan Schmidt 	if (tree_mod_dont_log(fs_info, NULL))
649097b8a7cSJan Schmidt 		return 0;
650097b8a7cSJan Schmidt 
65190f8d62eSJan Schmidt 	if (log_removal)
652d9abbf1cSJan Schmidt 		__tree_mod_log_free_eb(fs_info, old_root);
653d9abbf1cSJan Schmidt 
654*c8cc6341SJosef Bacik 	tm = kzalloc(sizeof(*tm), flags);
655*c8cc6341SJosef Bacik 	if (!tm)
656*c8cc6341SJosef Bacik 		return -ENOMEM;
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 
664*c8cc6341SJosef Bacik 	return __tree_mod_log_insert(fs_info, tm);
665bd989ba3SJan Schmidt }
666bd989ba3SJan Schmidt 
667bd989ba3SJan Schmidt static struct tree_mod_elem *
668bd989ba3SJan Schmidt __tree_mod_log_search(struct btrfs_fs_info *fs_info, u64 start, u64 min_seq,
669bd989ba3SJan Schmidt 		      int smallest)
670bd989ba3SJan Schmidt {
671bd989ba3SJan Schmidt 	struct rb_root *tm_root;
672bd989ba3SJan Schmidt 	struct rb_node *node;
673bd989ba3SJan Schmidt 	struct tree_mod_elem *cur = NULL;
674bd989ba3SJan Schmidt 	struct tree_mod_elem *found = NULL;
675bd989ba3SJan Schmidt 	u64 index = start >> PAGE_CACHE_SHIFT;
676bd989ba3SJan Schmidt 
677097b8a7cSJan Schmidt 	tree_mod_log_read_lock(fs_info);
678bd989ba3SJan Schmidt 	tm_root = &fs_info->tree_mod_log;
679bd989ba3SJan Schmidt 	node = tm_root->rb_node;
680bd989ba3SJan Schmidt 	while (node) {
681bd989ba3SJan Schmidt 		cur = container_of(node, struct tree_mod_elem, node);
682bd989ba3SJan Schmidt 		if (cur->index < index) {
683bd989ba3SJan Schmidt 			node = node->rb_left;
684bd989ba3SJan Schmidt 		} else if (cur->index > index) {
685bd989ba3SJan Schmidt 			node = node->rb_right;
686097b8a7cSJan Schmidt 		} else if (cur->seq < min_seq) {
687bd989ba3SJan Schmidt 			node = node->rb_left;
688bd989ba3SJan Schmidt 		} else if (!smallest) {
689bd989ba3SJan Schmidt 			/* we want the node with the highest seq */
690bd989ba3SJan Schmidt 			if (found)
691097b8a7cSJan Schmidt 				BUG_ON(found->seq > cur->seq);
692bd989ba3SJan Schmidt 			found = cur;
693bd989ba3SJan Schmidt 			node = node->rb_left;
694097b8a7cSJan Schmidt 		} else if (cur->seq > min_seq) {
695bd989ba3SJan Schmidt 			/* we want the node with the smallest seq */
696bd989ba3SJan Schmidt 			if (found)
697097b8a7cSJan Schmidt 				BUG_ON(found->seq < cur->seq);
698bd989ba3SJan Schmidt 			found = cur;
699bd989ba3SJan Schmidt 			node = node->rb_right;
700bd989ba3SJan Schmidt 		} else {
701bd989ba3SJan Schmidt 			found = cur;
702bd989ba3SJan Schmidt 			break;
703bd989ba3SJan Schmidt 		}
704bd989ba3SJan Schmidt 	}
705097b8a7cSJan Schmidt 	tree_mod_log_read_unlock(fs_info);
706bd989ba3SJan Schmidt 
707bd989ba3SJan Schmidt 	return found;
708bd989ba3SJan Schmidt }
709bd989ba3SJan Schmidt 
710bd989ba3SJan Schmidt /*
711bd989ba3SJan Schmidt  * this returns the element from the log with the smallest time sequence
712bd989ba3SJan Schmidt  * value that's in the log (the oldest log item). any element with a time
713bd989ba3SJan Schmidt  * sequence lower than min_seq will be ignored.
714bd989ba3SJan Schmidt  */
715bd989ba3SJan Schmidt static struct tree_mod_elem *
716bd989ba3SJan Schmidt tree_mod_log_search_oldest(struct btrfs_fs_info *fs_info, u64 start,
717bd989ba3SJan Schmidt 			   u64 min_seq)
718bd989ba3SJan Schmidt {
719bd989ba3SJan Schmidt 	return __tree_mod_log_search(fs_info, start, min_seq, 1);
720bd989ba3SJan Schmidt }
721bd989ba3SJan Schmidt 
722bd989ba3SJan Schmidt /*
723bd989ba3SJan Schmidt  * this returns the element from the log with the largest time sequence
724bd989ba3SJan Schmidt  * value that's in the log (the most recent log item). any element with
725bd989ba3SJan Schmidt  * a time sequence lower than min_seq will be ignored.
726bd989ba3SJan Schmidt  */
727bd989ba3SJan Schmidt static struct tree_mod_elem *
728bd989ba3SJan Schmidt tree_mod_log_search(struct btrfs_fs_info *fs_info, u64 start, u64 min_seq)
729bd989ba3SJan Schmidt {
730bd989ba3SJan Schmidt 	return __tree_mod_log_search(fs_info, start, min_seq, 0);
731bd989ba3SJan Schmidt }
732bd989ba3SJan Schmidt 
733097b8a7cSJan Schmidt static noinline void
734bd989ba3SJan Schmidt tree_mod_log_eb_copy(struct btrfs_fs_info *fs_info, struct extent_buffer *dst,
735bd989ba3SJan Schmidt 		     struct extent_buffer *src, unsigned long dst_offset,
73690f8d62eSJan Schmidt 		     unsigned long src_offset, int nr_items)
737bd989ba3SJan Schmidt {
738bd989ba3SJan Schmidt 	int ret;
739bd989ba3SJan Schmidt 	int i;
740bd989ba3SJan Schmidt 
741e9b7fd4dSJan Schmidt 	if (tree_mod_dont_log(fs_info, NULL))
742bd989ba3SJan Schmidt 		return;
743bd989ba3SJan Schmidt 
744*c8cc6341SJosef Bacik 	if (btrfs_header_level(dst) == 0 && btrfs_header_level(src) == 0)
745bd989ba3SJan Schmidt 		return;
746bd989ba3SJan Schmidt 
747bd989ba3SJan Schmidt 	for (i = 0; i < nr_items; i++) {
748*c8cc6341SJosef Bacik 		ret = __tree_mod_log_insert_key(fs_info, src,
749097b8a7cSJan Schmidt 						i + src_offset,
750*c8cc6341SJosef Bacik 						MOD_LOG_KEY_REMOVE, GFP_NOFS);
751bd989ba3SJan Schmidt 		BUG_ON(ret < 0);
752*c8cc6341SJosef Bacik 		ret = __tree_mod_log_insert_key(fs_info, dst,
753097b8a7cSJan Schmidt 						     i + dst_offset,
754*c8cc6341SJosef Bacik 						     MOD_LOG_KEY_ADD,
755*c8cc6341SJosef Bacik 						     GFP_NOFS);
756bd989ba3SJan Schmidt 		BUG_ON(ret < 0);
757bd989ba3SJan Schmidt 	}
758bd989ba3SJan Schmidt }
759bd989ba3SJan Schmidt 
760bd989ba3SJan Schmidt static inline void
761bd989ba3SJan Schmidt tree_mod_log_eb_move(struct btrfs_fs_info *fs_info, struct extent_buffer *dst,
762bd989ba3SJan Schmidt 		     int dst_offset, int src_offset, int nr_items)
763bd989ba3SJan Schmidt {
764bd989ba3SJan Schmidt 	int ret;
765bd989ba3SJan Schmidt 	ret = tree_mod_log_insert_move(fs_info, dst, dst_offset, src_offset,
766bd989ba3SJan Schmidt 				       nr_items, GFP_NOFS);
767bd989ba3SJan Schmidt 	BUG_ON(ret < 0);
768bd989ba3SJan Schmidt }
769bd989ba3SJan Schmidt 
770097b8a7cSJan Schmidt static noinline void
771bd989ba3SJan Schmidt tree_mod_log_set_node_key(struct btrfs_fs_info *fs_info,
77232adf090SLiu Bo 			  struct extent_buffer *eb, int slot, int atomic)
773bd989ba3SJan Schmidt {
774bd989ba3SJan Schmidt 	int ret;
775bd989ba3SJan Schmidt 
776*c8cc6341SJosef Bacik 	ret = __tree_mod_log_insert_key(fs_info, eb, slot,
777bd989ba3SJan Schmidt 					MOD_LOG_KEY_REPLACE,
778bd989ba3SJan Schmidt 					atomic ? GFP_ATOMIC : GFP_NOFS);
779bd989ba3SJan Schmidt 	BUG_ON(ret < 0);
780bd989ba3SJan Schmidt }
781bd989ba3SJan Schmidt 
782097b8a7cSJan Schmidt static noinline void
783097b8a7cSJan Schmidt tree_mod_log_free_eb(struct btrfs_fs_info *fs_info, struct extent_buffer *eb)
784bd989ba3SJan Schmidt {
785e9b7fd4dSJan Schmidt 	if (tree_mod_dont_log(fs_info, eb))
786bd989ba3SJan Schmidt 		return;
787097b8a7cSJan Schmidt 	__tree_mod_log_free_eb(fs_info, eb);
788bd989ba3SJan Schmidt }
789bd989ba3SJan Schmidt 
790097b8a7cSJan Schmidt static noinline void
791bd989ba3SJan Schmidt tree_mod_log_set_root_pointer(struct btrfs_root *root,
79290f8d62eSJan Schmidt 			      struct extent_buffer *new_root_node,
79390f8d62eSJan Schmidt 			      int log_removal)
794bd989ba3SJan Schmidt {
795bd989ba3SJan Schmidt 	int ret;
796bd989ba3SJan Schmidt 	ret = tree_mod_log_insert_root(root->fs_info, root->node,
79790f8d62eSJan Schmidt 				       new_root_node, GFP_NOFS, log_removal);
798bd989ba3SJan Schmidt 	BUG_ON(ret < 0);
799bd989ba3SJan Schmidt }
800bd989ba3SJan Schmidt 
801d352ac68SChris Mason /*
8025d4f98a2SYan Zheng  * check if the tree block can be shared by multiple trees
8035d4f98a2SYan Zheng  */
8045d4f98a2SYan Zheng int btrfs_block_can_be_shared(struct btrfs_root *root,
8055d4f98a2SYan Zheng 			      struct extent_buffer *buf)
8065d4f98a2SYan Zheng {
8075d4f98a2SYan Zheng 	/*
8085d4f98a2SYan Zheng 	 * Tree blocks not in refernece counted trees and tree roots
8095d4f98a2SYan Zheng 	 * are never shared. If a block was allocated after the last
8105d4f98a2SYan Zheng 	 * snapshot and the block was not allocated by tree relocation,
8115d4f98a2SYan Zheng 	 * we know the block is not shared.
8125d4f98a2SYan Zheng 	 */
8135d4f98a2SYan Zheng 	if (root->ref_cows &&
8145d4f98a2SYan Zheng 	    buf != root->node && buf != root->commit_root &&
8155d4f98a2SYan Zheng 	    (btrfs_header_generation(buf) <=
8165d4f98a2SYan Zheng 	     btrfs_root_last_snapshot(&root->root_item) ||
8175d4f98a2SYan Zheng 	     btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)))
8185d4f98a2SYan Zheng 		return 1;
8195d4f98a2SYan Zheng #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
8205d4f98a2SYan Zheng 	if (root->ref_cows &&
8215d4f98a2SYan Zheng 	    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
8225d4f98a2SYan Zheng 		return 1;
8235d4f98a2SYan Zheng #endif
8245d4f98a2SYan Zheng 	return 0;
8255d4f98a2SYan Zheng }
8265d4f98a2SYan Zheng 
8275d4f98a2SYan Zheng static noinline int update_ref_for_cow(struct btrfs_trans_handle *trans,
8285d4f98a2SYan Zheng 				       struct btrfs_root *root,
8295d4f98a2SYan Zheng 				       struct extent_buffer *buf,
830f0486c68SYan, Zheng 				       struct extent_buffer *cow,
831f0486c68SYan, Zheng 				       int *last_ref)
8325d4f98a2SYan Zheng {
8335d4f98a2SYan Zheng 	u64 refs;
8345d4f98a2SYan Zheng 	u64 owner;
8355d4f98a2SYan Zheng 	u64 flags;
8365d4f98a2SYan Zheng 	u64 new_flags = 0;
8375d4f98a2SYan Zheng 	int ret;
8385d4f98a2SYan Zheng 
8395d4f98a2SYan Zheng 	/*
8405d4f98a2SYan Zheng 	 * Backrefs update rules:
8415d4f98a2SYan Zheng 	 *
8425d4f98a2SYan Zheng 	 * Always use full backrefs for extent pointers in tree block
8435d4f98a2SYan Zheng 	 * allocated by tree relocation.
8445d4f98a2SYan Zheng 	 *
8455d4f98a2SYan Zheng 	 * If a shared tree block is no longer referenced by its owner
8465d4f98a2SYan Zheng 	 * tree (btrfs_header_owner(buf) == root->root_key.objectid),
8475d4f98a2SYan Zheng 	 * use full backrefs for extent pointers in tree block.
8485d4f98a2SYan Zheng 	 *
8495d4f98a2SYan Zheng 	 * If a tree block is been relocating
8505d4f98a2SYan Zheng 	 * (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID),
8515d4f98a2SYan Zheng 	 * use full backrefs for extent pointers in tree block.
8525d4f98a2SYan Zheng 	 * The reason for this is some operations (such as drop tree)
8535d4f98a2SYan Zheng 	 * are only allowed for blocks use full backrefs.
8545d4f98a2SYan Zheng 	 */
8555d4f98a2SYan Zheng 
8565d4f98a2SYan Zheng 	if (btrfs_block_can_be_shared(root, buf)) {
8575d4f98a2SYan Zheng 		ret = btrfs_lookup_extent_info(trans, root, buf->start,
8583173a18fSJosef Bacik 					       btrfs_header_level(buf), 1,
8593173a18fSJosef Bacik 					       &refs, &flags);
860be1a5564SMark Fasheh 		if (ret)
861be1a5564SMark Fasheh 			return ret;
862e5df9573SMark Fasheh 		if (refs == 0) {
863e5df9573SMark Fasheh 			ret = -EROFS;
864e5df9573SMark Fasheh 			btrfs_std_error(root->fs_info, ret);
865e5df9573SMark Fasheh 			return ret;
866e5df9573SMark Fasheh 		}
8675d4f98a2SYan Zheng 	} else {
8685d4f98a2SYan Zheng 		refs = 1;
8695d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
8705d4f98a2SYan Zheng 		    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
8715d4f98a2SYan Zheng 			flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
8725d4f98a2SYan Zheng 		else
8735d4f98a2SYan Zheng 			flags = 0;
8745d4f98a2SYan Zheng 	}
8755d4f98a2SYan Zheng 
8765d4f98a2SYan Zheng 	owner = btrfs_header_owner(buf);
8775d4f98a2SYan Zheng 	BUG_ON(owner == BTRFS_TREE_RELOC_OBJECTID &&
8785d4f98a2SYan Zheng 	       !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
8795d4f98a2SYan Zheng 
8805d4f98a2SYan Zheng 	if (refs > 1) {
8815d4f98a2SYan Zheng 		if ((owner == root->root_key.objectid ||
8825d4f98a2SYan Zheng 		     root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) &&
8835d4f98a2SYan Zheng 		    !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)) {
88466d7e7f0SArne Jansen 			ret = btrfs_inc_ref(trans, root, buf, 1, 1);
88579787eaaSJeff Mahoney 			BUG_ON(ret); /* -ENOMEM */
8865d4f98a2SYan Zheng 
8875d4f98a2SYan Zheng 			if (root->root_key.objectid ==
8885d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID) {
88966d7e7f0SArne Jansen 				ret = btrfs_dec_ref(trans, root, buf, 0, 1);
89079787eaaSJeff Mahoney 				BUG_ON(ret); /* -ENOMEM */
89166d7e7f0SArne Jansen 				ret = btrfs_inc_ref(trans, root, cow, 1, 1);
89279787eaaSJeff Mahoney 				BUG_ON(ret); /* -ENOMEM */
8935d4f98a2SYan Zheng 			}
8945d4f98a2SYan Zheng 			new_flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
8955d4f98a2SYan Zheng 		} else {
8965d4f98a2SYan Zheng 
8975d4f98a2SYan Zheng 			if (root->root_key.objectid ==
8985d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID)
89966d7e7f0SArne Jansen 				ret = btrfs_inc_ref(trans, root, cow, 1, 1);
9005d4f98a2SYan Zheng 			else
90166d7e7f0SArne Jansen 				ret = btrfs_inc_ref(trans, root, cow, 0, 1);
90279787eaaSJeff Mahoney 			BUG_ON(ret); /* -ENOMEM */
9035d4f98a2SYan Zheng 		}
9045d4f98a2SYan Zheng 		if (new_flags != 0) {
905b1c79e09SJosef Bacik 			int level = btrfs_header_level(buf);
906b1c79e09SJosef Bacik 
9075d4f98a2SYan Zheng 			ret = btrfs_set_disk_extent_flags(trans, root,
9085d4f98a2SYan Zheng 							  buf->start,
9095d4f98a2SYan Zheng 							  buf->len,
910b1c79e09SJosef Bacik 							  new_flags, level, 0);
911be1a5564SMark Fasheh 			if (ret)
912be1a5564SMark Fasheh 				return ret;
9135d4f98a2SYan Zheng 		}
9145d4f98a2SYan Zheng 	} else {
9155d4f98a2SYan Zheng 		if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
9165d4f98a2SYan Zheng 			if (root->root_key.objectid ==
9175d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID)
91866d7e7f0SArne Jansen 				ret = btrfs_inc_ref(trans, root, cow, 1, 1);
9195d4f98a2SYan Zheng 			else
92066d7e7f0SArne Jansen 				ret = btrfs_inc_ref(trans, root, cow, 0, 1);
92179787eaaSJeff Mahoney 			BUG_ON(ret); /* -ENOMEM */
92266d7e7f0SArne Jansen 			ret = btrfs_dec_ref(trans, root, buf, 1, 1);
92379787eaaSJeff Mahoney 			BUG_ON(ret); /* -ENOMEM */
9245d4f98a2SYan Zheng 		}
9255d4f98a2SYan Zheng 		clean_tree_block(trans, root, buf);
926f0486c68SYan, Zheng 		*last_ref = 1;
9275d4f98a2SYan Zheng 	}
9285d4f98a2SYan Zheng 	return 0;
9295d4f98a2SYan Zheng }
9305d4f98a2SYan Zheng 
9315d4f98a2SYan Zheng /*
932d397712bSChris Mason  * does the dirty work in cow of a single block.  The parent block (if
933d397712bSChris Mason  * supplied) is updated to point to the new cow copy.  The new buffer is marked
934d397712bSChris Mason  * dirty and returned locked.  If you modify the block it needs to be marked
935d397712bSChris Mason  * dirty again.
936d352ac68SChris Mason  *
937d352ac68SChris Mason  * search_start -- an allocation hint for the new block
938d352ac68SChris Mason  *
939d397712bSChris Mason  * empty_size -- a hint that you plan on doing more cow.  This is the size in
940d397712bSChris Mason  * bytes the allocator should try to find free next to the block it returns.
941d397712bSChris Mason  * This is just a hint and may be ignored by the allocator.
942d352ac68SChris Mason  */
943d397712bSChris Mason static noinline int __btrfs_cow_block(struct btrfs_trans_handle *trans,
9445f39d397SChris Mason 			     struct btrfs_root *root,
9455f39d397SChris Mason 			     struct extent_buffer *buf,
9465f39d397SChris Mason 			     struct extent_buffer *parent, int parent_slot,
9475f39d397SChris Mason 			     struct extent_buffer **cow_ret,
9489fa8cfe7SChris Mason 			     u64 search_start, u64 empty_size)
9496702ed49SChris Mason {
9505d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
9515f39d397SChris Mason 	struct extent_buffer *cow;
952be1a5564SMark Fasheh 	int level, ret;
953f0486c68SYan, Zheng 	int last_ref = 0;
954925baeddSChris Mason 	int unlock_orig = 0;
9555d4f98a2SYan Zheng 	u64 parent_start;
9566702ed49SChris Mason 
957925baeddSChris Mason 	if (*cow_ret == buf)
958925baeddSChris Mason 		unlock_orig = 1;
959925baeddSChris Mason 
960b9447ef8SChris Mason 	btrfs_assert_tree_locked(buf);
961925baeddSChris Mason 
9627bb86316SChris Mason 	WARN_ON(root->ref_cows && trans->transid !=
9637bb86316SChris Mason 		root->fs_info->running_transaction->transid);
9646702ed49SChris Mason 	WARN_ON(root->ref_cows && trans->transid != root->last_trans);
9655f39d397SChris Mason 
9667bb86316SChris Mason 	level = btrfs_header_level(buf);
96731840ae1SZheng Yan 
9685d4f98a2SYan Zheng 	if (level == 0)
9695d4f98a2SYan Zheng 		btrfs_item_key(buf, &disk_key, 0);
9705d4f98a2SYan Zheng 	else
9715d4f98a2SYan Zheng 		btrfs_node_key(buf, &disk_key, 0);
9725d4f98a2SYan Zheng 
9735d4f98a2SYan Zheng 	if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) {
9745d4f98a2SYan Zheng 		if (parent)
9755d4f98a2SYan Zheng 			parent_start = parent->start;
9765d4f98a2SYan Zheng 		else
9775d4f98a2SYan Zheng 			parent_start = 0;
9785d4f98a2SYan Zheng 	} else
9795d4f98a2SYan Zheng 		parent_start = 0;
9805d4f98a2SYan Zheng 
9815d4f98a2SYan Zheng 	cow = btrfs_alloc_free_block(trans, root, buf->len, parent_start,
9825d4f98a2SYan Zheng 				     root->root_key.objectid, &disk_key,
9835581a51aSJan Schmidt 				     level, search_start, empty_size);
9846702ed49SChris Mason 	if (IS_ERR(cow))
9856702ed49SChris Mason 		return PTR_ERR(cow);
9866702ed49SChris Mason 
987b4ce94deSChris Mason 	/* cow is set to blocking by btrfs_init_new_buffer */
988b4ce94deSChris Mason 
9895f39d397SChris Mason 	copy_extent_buffer(cow, buf, 0, 0, cow->len);
990db94535dSChris Mason 	btrfs_set_header_bytenr(cow, cow->start);
9915f39d397SChris Mason 	btrfs_set_header_generation(cow, trans->transid);
9925d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
9935d4f98a2SYan Zheng 	btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
9945d4f98a2SYan Zheng 				     BTRFS_HEADER_FLAG_RELOC);
9955d4f98a2SYan Zheng 	if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
9965d4f98a2SYan Zheng 		btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
9975d4f98a2SYan Zheng 	else
9985f39d397SChris Mason 		btrfs_set_header_owner(cow, root->root_key.objectid);
9996702ed49SChris Mason 
10002b82032cSYan Zheng 	write_extent_buffer(cow, root->fs_info->fsid,
10012b82032cSYan Zheng 			    (unsigned long)btrfs_header_fsid(cow),
10022b82032cSYan Zheng 			    BTRFS_FSID_SIZE);
10032b82032cSYan Zheng 
1004be1a5564SMark Fasheh 	ret = update_ref_for_cow(trans, root, buf, cow, &last_ref);
1005b68dc2a9SMark Fasheh 	if (ret) {
100679787eaaSJeff Mahoney 		btrfs_abort_transaction(trans, root, ret);
1007b68dc2a9SMark Fasheh 		return ret;
1008b68dc2a9SMark Fasheh 	}
10091a40e23bSZheng Yan 
10103fd0a558SYan, Zheng 	if (root->ref_cows)
10113fd0a558SYan, Zheng 		btrfs_reloc_cow_block(trans, root, buf, cow);
10123fd0a558SYan, Zheng 
10136702ed49SChris Mason 	if (buf == root->node) {
1014925baeddSChris Mason 		WARN_ON(parent && parent != buf);
10155d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
10165d4f98a2SYan Zheng 		    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
10175d4f98a2SYan Zheng 			parent_start = buf->start;
10185d4f98a2SYan Zheng 		else
10195d4f98a2SYan Zheng 			parent_start = 0;
1020925baeddSChris Mason 
10215f39d397SChris Mason 		extent_buffer_get(cow);
102290f8d62eSJan Schmidt 		tree_mod_log_set_root_pointer(root, cow, 1);
1023240f62c8SChris Mason 		rcu_assign_pointer(root->node, cow);
1024925baeddSChris Mason 
1025f0486c68SYan, Zheng 		btrfs_free_tree_block(trans, root, buf, parent_start,
10265581a51aSJan Schmidt 				      last_ref);
10275f39d397SChris Mason 		free_extent_buffer(buf);
10280b86a832SChris Mason 		add_root_to_dirty_list(root);
10296702ed49SChris Mason 	} else {
10305d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
10315d4f98a2SYan Zheng 			parent_start = parent->start;
10325d4f98a2SYan Zheng 		else
10335d4f98a2SYan Zheng 			parent_start = 0;
10345d4f98a2SYan Zheng 
10355d4f98a2SYan Zheng 		WARN_ON(trans->transid != btrfs_header_generation(parent));
1036f230475eSJan Schmidt 		tree_mod_log_insert_key(root->fs_info, parent, parent_slot,
1037*c8cc6341SJosef Bacik 					MOD_LOG_KEY_REPLACE, GFP_NOFS);
10385f39d397SChris Mason 		btrfs_set_node_blockptr(parent, parent_slot,
1039db94535dSChris Mason 					cow->start);
104074493f7aSChris Mason 		btrfs_set_node_ptr_generation(parent, parent_slot,
104174493f7aSChris Mason 					      trans->transid);
10426702ed49SChris Mason 		btrfs_mark_buffer_dirty(parent);
10437fb7d76fSJosef Bacik 		if (last_ref)
1044d9abbf1cSJan Schmidt 			tree_mod_log_free_eb(root->fs_info, buf);
1045f0486c68SYan, Zheng 		btrfs_free_tree_block(trans, root, buf, parent_start,
10465581a51aSJan Schmidt 				      last_ref);
10476702ed49SChris Mason 	}
1048925baeddSChris Mason 	if (unlock_orig)
1049925baeddSChris Mason 		btrfs_tree_unlock(buf);
10503083ee2eSJosef Bacik 	free_extent_buffer_stale(buf);
10516702ed49SChris Mason 	btrfs_mark_buffer_dirty(cow);
10526702ed49SChris Mason 	*cow_ret = cow;
10536702ed49SChris Mason 	return 0;
10546702ed49SChris Mason }
10556702ed49SChris Mason 
10565d9e75c4SJan Schmidt /*
10575d9e75c4SJan Schmidt  * returns the logical address of the oldest predecessor of the given root.
10585d9e75c4SJan Schmidt  * entries older than time_seq are ignored.
10595d9e75c4SJan Schmidt  */
10605d9e75c4SJan Schmidt static struct tree_mod_elem *
10615d9e75c4SJan Schmidt __tree_mod_log_oldest_root(struct btrfs_fs_info *fs_info,
106230b0463aSJan Schmidt 			   struct extent_buffer *eb_root, u64 time_seq)
10635d9e75c4SJan Schmidt {
10645d9e75c4SJan Schmidt 	struct tree_mod_elem *tm;
10655d9e75c4SJan Schmidt 	struct tree_mod_elem *found = NULL;
106630b0463aSJan Schmidt 	u64 root_logical = eb_root->start;
10675d9e75c4SJan Schmidt 	int looped = 0;
10685d9e75c4SJan Schmidt 
10695d9e75c4SJan Schmidt 	if (!time_seq)
10705d9e75c4SJan Schmidt 		return 0;
10715d9e75c4SJan Schmidt 
10725d9e75c4SJan Schmidt 	/*
10735d9e75c4SJan Schmidt 	 * the very last operation that's logged for a root is the replacement
10745d9e75c4SJan Schmidt 	 * operation (if it is replaced at all). this has the index of the *new*
10755d9e75c4SJan Schmidt 	 * root, making it the very first operation that's logged for this root.
10765d9e75c4SJan Schmidt 	 */
10775d9e75c4SJan Schmidt 	while (1) {
10785d9e75c4SJan Schmidt 		tm = tree_mod_log_search_oldest(fs_info, root_logical,
10795d9e75c4SJan Schmidt 						time_seq);
10805d9e75c4SJan Schmidt 		if (!looped && !tm)
10815d9e75c4SJan Schmidt 			return 0;
10825d9e75c4SJan Schmidt 		/*
108328da9fb4SJan Schmidt 		 * if there are no tree operation for the oldest root, we simply
108428da9fb4SJan Schmidt 		 * return it. this should only happen if that (old) root is at
108528da9fb4SJan Schmidt 		 * level 0.
10865d9e75c4SJan Schmidt 		 */
108728da9fb4SJan Schmidt 		if (!tm)
108828da9fb4SJan Schmidt 			break;
10895d9e75c4SJan Schmidt 
109028da9fb4SJan Schmidt 		/*
109128da9fb4SJan Schmidt 		 * if there's an operation that's not a root replacement, we
109228da9fb4SJan Schmidt 		 * found the oldest version of our root. normally, we'll find a
109328da9fb4SJan Schmidt 		 * MOD_LOG_KEY_REMOVE_WHILE_FREEING operation here.
109428da9fb4SJan Schmidt 		 */
10955d9e75c4SJan Schmidt 		if (tm->op != MOD_LOG_ROOT_REPLACE)
10965d9e75c4SJan Schmidt 			break;
10975d9e75c4SJan Schmidt 
10985d9e75c4SJan Schmidt 		found = tm;
10995d9e75c4SJan Schmidt 		root_logical = tm->old_root.logical;
11005d9e75c4SJan Schmidt 		looped = 1;
11015d9e75c4SJan Schmidt 	}
11025d9e75c4SJan Schmidt 
1103a95236d9SJan Schmidt 	/* if there's no old root to return, return what we found instead */
1104a95236d9SJan Schmidt 	if (!found)
1105a95236d9SJan Schmidt 		found = tm;
1106a95236d9SJan Schmidt 
11075d9e75c4SJan Schmidt 	return found;
11085d9e75c4SJan Schmidt }
11095d9e75c4SJan Schmidt 
11105d9e75c4SJan Schmidt /*
11115d9e75c4SJan Schmidt  * tm is a pointer to the first operation to rewind within eb. then, all
11125d9e75c4SJan Schmidt  * previous operations will be rewinded (until we reach something older than
11135d9e75c4SJan Schmidt  * time_seq).
11145d9e75c4SJan Schmidt  */
11155d9e75c4SJan Schmidt static void
1116f1ca7e98SJosef Bacik __tree_mod_log_rewind(struct btrfs_fs_info *fs_info, struct extent_buffer *eb,
1117f1ca7e98SJosef Bacik 		      u64 time_seq, struct tree_mod_elem *first_tm)
11185d9e75c4SJan Schmidt {
11195d9e75c4SJan Schmidt 	u32 n;
11205d9e75c4SJan Schmidt 	struct rb_node *next;
11215d9e75c4SJan Schmidt 	struct tree_mod_elem *tm = first_tm;
11225d9e75c4SJan Schmidt 	unsigned long o_dst;
11235d9e75c4SJan Schmidt 	unsigned long o_src;
11245d9e75c4SJan Schmidt 	unsigned long p_size = sizeof(struct btrfs_key_ptr);
11255d9e75c4SJan Schmidt 
11265d9e75c4SJan Schmidt 	n = btrfs_header_nritems(eb);
1127f1ca7e98SJosef Bacik 	tree_mod_log_read_lock(fs_info);
1128097b8a7cSJan Schmidt 	while (tm && tm->seq >= time_seq) {
11295d9e75c4SJan Schmidt 		/*
11305d9e75c4SJan Schmidt 		 * all the operations are recorded with the operator used for
11315d9e75c4SJan Schmidt 		 * the modification. as we're going backwards, we do the
11325d9e75c4SJan Schmidt 		 * opposite of each operation here.
11335d9e75c4SJan Schmidt 		 */
11345d9e75c4SJan Schmidt 		switch (tm->op) {
11355d9e75c4SJan Schmidt 		case MOD_LOG_KEY_REMOVE_WHILE_FREEING:
11365d9e75c4SJan Schmidt 			BUG_ON(tm->slot < n);
11371c697d4aSEric Sandeen 			/* Fallthrough */
113895c80bb1SLiu Bo 		case MOD_LOG_KEY_REMOVE_WHILE_MOVING:
11394c3e6969SChris Mason 		case MOD_LOG_KEY_REMOVE:
11405d9e75c4SJan Schmidt 			btrfs_set_node_key(eb, &tm->key, tm->slot);
11415d9e75c4SJan Schmidt 			btrfs_set_node_blockptr(eb, tm->slot, tm->blockptr);
11425d9e75c4SJan Schmidt 			btrfs_set_node_ptr_generation(eb, tm->slot,
11435d9e75c4SJan Schmidt 						      tm->generation);
11444c3e6969SChris Mason 			n++;
11455d9e75c4SJan Schmidt 			break;
11465d9e75c4SJan Schmidt 		case MOD_LOG_KEY_REPLACE:
11475d9e75c4SJan Schmidt 			BUG_ON(tm->slot >= n);
11485d9e75c4SJan Schmidt 			btrfs_set_node_key(eb, &tm->key, tm->slot);
11495d9e75c4SJan Schmidt 			btrfs_set_node_blockptr(eb, tm->slot, tm->blockptr);
11505d9e75c4SJan Schmidt 			btrfs_set_node_ptr_generation(eb, tm->slot,
11515d9e75c4SJan Schmidt 						      tm->generation);
11525d9e75c4SJan Schmidt 			break;
11535d9e75c4SJan Schmidt 		case MOD_LOG_KEY_ADD:
115419956c7eSJan Schmidt 			/* if a move operation is needed it's in the log */
11555d9e75c4SJan Schmidt 			n--;
11565d9e75c4SJan Schmidt 			break;
11575d9e75c4SJan Schmidt 		case MOD_LOG_MOVE_KEYS:
1158c3193108SJan Schmidt 			o_dst = btrfs_node_key_ptr_offset(tm->slot);
1159c3193108SJan Schmidt 			o_src = btrfs_node_key_ptr_offset(tm->move.dst_slot);
1160c3193108SJan Schmidt 			memmove_extent_buffer(eb, o_dst, o_src,
11615d9e75c4SJan Schmidt 					      tm->move.nr_items * p_size);
11625d9e75c4SJan Schmidt 			break;
11635d9e75c4SJan Schmidt 		case MOD_LOG_ROOT_REPLACE:
11645d9e75c4SJan Schmidt 			/*
11655d9e75c4SJan Schmidt 			 * this operation is special. for roots, this must be
11665d9e75c4SJan Schmidt 			 * handled explicitly before rewinding.
11675d9e75c4SJan Schmidt 			 * for non-roots, this operation may exist if the node
11685d9e75c4SJan Schmidt 			 * was a root: root A -> child B; then A gets empty and
11695d9e75c4SJan Schmidt 			 * B is promoted to the new root. in the mod log, we'll
11705d9e75c4SJan Schmidt 			 * have a root-replace operation for B, a tree block
11715d9e75c4SJan Schmidt 			 * that is no root. we simply ignore that operation.
11725d9e75c4SJan Schmidt 			 */
11735d9e75c4SJan Schmidt 			break;
11745d9e75c4SJan Schmidt 		}
11755d9e75c4SJan Schmidt 		next = rb_next(&tm->node);
11765d9e75c4SJan Schmidt 		if (!next)
11775d9e75c4SJan Schmidt 			break;
11785d9e75c4SJan Schmidt 		tm = container_of(next, struct tree_mod_elem, node);
11795d9e75c4SJan Schmidt 		if (tm->index != first_tm->index)
11805d9e75c4SJan Schmidt 			break;
11815d9e75c4SJan Schmidt 	}
1182f1ca7e98SJosef Bacik 	tree_mod_log_read_unlock(fs_info);
11835d9e75c4SJan Schmidt 	btrfs_set_header_nritems(eb, n);
11845d9e75c4SJan Schmidt }
11855d9e75c4SJan Schmidt 
118647fb091fSJan Schmidt /*
118747fb091fSJan Schmidt  * Called with eb read locked. If the buffer cannot be rewinded, the same buffer
118847fb091fSJan Schmidt  * is returned. If rewind operations happen, a fresh buffer is returned. The
118947fb091fSJan Schmidt  * returned buffer is always read-locked. If the returned buffer is not the
119047fb091fSJan Schmidt  * input buffer, the lock on the input buffer is released and the input buffer
119147fb091fSJan Schmidt  * is freed (its refcount is decremented).
119247fb091fSJan Schmidt  */
11935d9e75c4SJan Schmidt static struct extent_buffer *
11945d9e75c4SJan Schmidt tree_mod_log_rewind(struct btrfs_fs_info *fs_info, struct extent_buffer *eb,
11955d9e75c4SJan Schmidt 		    u64 time_seq)
11965d9e75c4SJan Schmidt {
11975d9e75c4SJan Schmidt 	struct extent_buffer *eb_rewin;
11985d9e75c4SJan Schmidt 	struct tree_mod_elem *tm;
11995d9e75c4SJan Schmidt 
12005d9e75c4SJan Schmidt 	if (!time_seq)
12015d9e75c4SJan Schmidt 		return eb;
12025d9e75c4SJan Schmidt 
12035d9e75c4SJan Schmidt 	if (btrfs_header_level(eb) == 0)
12045d9e75c4SJan Schmidt 		return eb;
12055d9e75c4SJan Schmidt 
12065d9e75c4SJan Schmidt 	tm = tree_mod_log_search(fs_info, eb->start, time_seq);
12075d9e75c4SJan Schmidt 	if (!tm)
12085d9e75c4SJan Schmidt 		return eb;
12095d9e75c4SJan Schmidt 
12105d9e75c4SJan Schmidt 	if (tm->op == MOD_LOG_KEY_REMOVE_WHILE_FREEING) {
12115d9e75c4SJan Schmidt 		BUG_ON(tm->slot != 0);
12125d9e75c4SJan Schmidt 		eb_rewin = alloc_dummy_extent_buffer(eb->start,
12135d9e75c4SJan Schmidt 						fs_info->tree_root->nodesize);
12145d9e75c4SJan Schmidt 		BUG_ON(!eb_rewin);
12155d9e75c4SJan Schmidt 		btrfs_set_header_bytenr(eb_rewin, eb->start);
12165d9e75c4SJan Schmidt 		btrfs_set_header_backref_rev(eb_rewin,
12175d9e75c4SJan Schmidt 					     btrfs_header_backref_rev(eb));
12185d9e75c4SJan Schmidt 		btrfs_set_header_owner(eb_rewin, btrfs_header_owner(eb));
1219c3193108SJan Schmidt 		btrfs_set_header_level(eb_rewin, btrfs_header_level(eb));
12205d9e75c4SJan Schmidt 	} else {
12215d9e75c4SJan Schmidt 		eb_rewin = btrfs_clone_extent_buffer(eb);
12225d9e75c4SJan Schmidt 		BUG_ON(!eb_rewin);
12235d9e75c4SJan Schmidt 	}
12245d9e75c4SJan Schmidt 
122547fb091fSJan Schmidt 	btrfs_tree_read_unlock(eb);
12265d9e75c4SJan Schmidt 	free_extent_buffer(eb);
12275d9e75c4SJan Schmidt 
122847fb091fSJan Schmidt 	extent_buffer_get(eb_rewin);
122947fb091fSJan Schmidt 	btrfs_tree_read_lock(eb_rewin);
1230f1ca7e98SJosef Bacik 	__tree_mod_log_rewind(fs_info, eb_rewin, time_seq, tm);
123157911b8bSJan Schmidt 	WARN_ON(btrfs_header_nritems(eb_rewin) >
12322a745b14SArne Jansen 		BTRFS_NODEPTRS_PER_BLOCK(fs_info->tree_root));
12335d9e75c4SJan Schmidt 
12345d9e75c4SJan Schmidt 	return eb_rewin;
12355d9e75c4SJan Schmidt }
12365d9e75c4SJan Schmidt 
12378ba97a15SJan Schmidt /*
12388ba97a15SJan Schmidt  * get_old_root() rewinds the state of @root's root node to the given @time_seq
12398ba97a15SJan Schmidt  * value. If there are no changes, the current root->root_node is returned. If
12408ba97a15SJan Schmidt  * anything changed in between, there's a fresh buffer allocated on which the
12418ba97a15SJan Schmidt  * rewind operations are done. In any case, the returned buffer is read locked.
12428ba97a15SJan Schmidt  * Returns NULL on error (with no locks held).
12438ba97a15SJan Schmidt  */
12445d9e75c4SJan Schmidt static inline struct extent_buffer *
12455d9e75c4SJan Schmidt get_old_root(struct btrfs_root *root, u64 time_seq)
12465d9e75c4SJan Schmidt {
12475d9e75c4SJan Schmidt 	struct tree_mod_elem *tm;
124830b0463aSJan Schmidt 	struct extent_buffer *eb = NULL;
124930b0463aSJan Schmidt 	struct extent_buffer *eb_root;
12507bfdcf7fSLiu Bo 	struct extent_buffer *old;
1251a95236d9SJan Schmidt 	struct tree_mod_root *old_root = NULL;
12524325edd0SChris Mason 	u64 old_generation = 0;
1253a95236d9SJan Schmidt 	u64 logical;
1254834328a8SJan Schmidt 	u32 blocksize;
12555d9e75c4SJan Schmidt 
125630b0463aSJan Schmidt 	eb_root = btrfs_read_lock_root_node(root);
125730b0463aSJan Schmidt 	tm = __tree_mod_log_oldest_root(root->fs_info, eb_root, time_seq);
12585d9e75c4SJan Schmidt 	if (!tm)
125930b0463aSJan Schmidt 		return eb_root;
12605d9e75c4SJan Schmidt 
1261a95236d9SJan Schmidt 	if (tm->op == MOD_LOG_ROOT_REPLACE) {
12625d9e75c4SJan Schmidt 		old_root = &tm->old_root;
12635d9e75c4SJan Schmidt 		old_generation = tm->generation;
1264a95236d9SJan Schmidt 		logical = old_root->logical;
1265a95236d9SJan Schmidt 	} else {
126630b0463aSJan Schmidt 		logical = eb_root->start;
1267a95236d9SJan Schmidt 	}
12685d9e75c4SJan Schmidt 
1269a95236d9SJan Schmidt 	tm = tree_mod_log_search(root->fs_info, logical, time_seq);
1270834328a8SJan Schmidt 	if (old_root && tm && tm->op != MOD_LOG_KEY_REMOVE_WHILE_FREEING) {
127130b0463aSJan Schmidt 		btrfs_tree_read_unlock(eb_root);
127230b0463aSJan Schmidt 		free_extent_buffer(eb_root);
1273834328a8SJan Schmidt 		blocksize = btrfs_level_size(root, old_root->level);
12747bfdcf7fSLiu Bo 		old = read_tree_block(root, logical, blocksize, 0);
1275416bc658SJosef Bacik 		if (!old || !extent_buffer_uptodate(old)) {
1276416bc658SJosef Bacik 			free_extent_buffer(old);
1277834328a8SJan Schmidt 			pr_warn("btrfs: failed to read tree block %llu from get_old_root\n",
1278834328a8SJan Schmidt 				logical);
1279834328a8SJan Schmidt 			WARN_ON(1);
1280834328a8SJan Schmidt 		} else {
12817bfdcf7fSLiu Bo 			eb = btrfs_clone_extent_buffer(old);
12827bfdcf7fSLiu Bo 			free_extent_buffer(old);
1283834328a8SJan Schmidt 		}
1284834328a8SJan Schmidt 	} else if (old_root) {
128530b0463aSJan Schmidt 		btrfs_tree_read_unlock(eb_root);
128630b0463aSJan Schmidt 		free_extent_buffer(eb_root);
128728da9fb4SJan Schmidt 		eb = alloc_dummy_extent_buffer(logical, root->nodesize);
1288834328a8SJan Schmidt 	} else {
128930b0463aSJan Schmidt 		eb = btrfs_clone_extent_buffer(eb_root);
129030b0463aSJan Schmidt 		btrfs_tree_read_unlock(eb_root);
129130b0463aSJan Schmidt 		free_extent_buffer(eb_root);
1292834328a8SJan Schmidt 	}
1293834328a8SJan Schmidt 
12948ba97a15SJan Schmidt 	if (!eb)
12958ba97a15SJan Schmidt 		return NULL;
1296d6381084SJan Schmidt 	extent_buffer_get(eb);
12978ba97a15SJan Schmidt 	btrfs_tree_read_lock(eb);
1298a95236d9SJan Schmidt 	if (old_root) {
12995d9e75c4SJan Schmidt 		btrfs_set_header_bytenr(eb, eb->start);
13005d9e75c4SJan Schmidt 		btrfs_set_header_backref_rev(eb, BTRFS_MIXED_BACKREF_REV);
130130b0463aSJan Schmidt 		btrfs_set_header_owner(eb, btrfs_header_owner(eb_root));
13025d9e75c4SJan Schmidt 		btrfs_set_header_level(eb, old_root->level);
13035d9e75c4SJan Schmidt 		btrfs_set_header_generation(eb, old_generation);
1304a95236d9SJan Schmidt 	}
130528da9fb4SJan Schmidt 	if (tm)
1306f1ca7e98SJosef Bacik 		__tree_mod_log_rewind(root->fs_info, eb, time_seq, tm);
130728da9fb4SJan Schmidt 	else
130828da9fb4SJan Schmidt 		WARN_ON(btrfs_header_level(eb) != 0);
130957911b8bSJan Schmidt 	WARN_ON(btrfs_header_nritems(eb) > BTRFS_NODEPTRS_PER_BLOCK(root));
13105d9e75c4SJan Schmidt 
13115d9e75c4SJan Schmidt 	return eb;
13125d9e75c4SJan Schmidt }
13135d9e75c4SJan Schmidt 
13145b6602e7SJan Schmidt int btrfs_old_root_level(struct btrfs_root *root, u64 time_seq)
13155b6602e7SJan Schmidt {
13165b6602e7SJan Schmidt 	struct tree_mod_elem *tm;
13175b6602e7SJan Schmidt 	int level;
131830b0463aSJan Schmidt 	struct extent_buffer *eb_root = btrfs_root_node(root);
13195b6602e7SJan Schmidt 
132030b0463aSJan Schmidt 	tm = __tree_mod_log_oldest_root(root->fs_info, eb_root, time_seq);
13215b6602e7SJan Schmidt 	if (tm && tm->op == MOD_LOG_ROOT_REPLACE) {
13225b6602e7SJan Schmidt 		level = tm->old_root.level;
13235b6602e7SJan Schmidt 	} else {
132430b0463aSJan Schmidt 		level = btrfs_header_level(eb_root);
13255b6602e7SJan Schmidt 	}
132630b0463aSJan Schmidt 	free_extent_buffer(eb_root);
13275b6602e7SJan Schmidt 
13285b6602e7SJan Schmidt 	return level;
13295b6602e7SJan Schmidt }
13305b6602e7SJan Schmidt 
13315d4f98a2SYan Zheng static inline int should_cow_block(struct btrfs_trans_handle *trans,
13325d4f98a2SYan Zheng 				   struct btrfs_root *root,
13335d4f98a2SYan Zheng 				   struct extent_buffer *buf)
13345d4f98a2SYan Zheng {
1335f1ebcc74SLiu Bo 	/* ensure we can see the force_cow */
1336f1ebcc74SLiu Bo 	smp_rmb();
1337f1ebcc74SLiu Bo 
1338f1ebcc74SLiu Bo 	/*
1339f1ebcc74SLiu Bo 	 * We do not need to cow a block if
1340f1ebcc74SLiu Bo 	 * 1) this block is not created or changed in this transaction;
1341f1ebcc74SLiu Bo 	 * 2) this block does not belong to TREE_RELOC tree;
1342f1ebcc74SLiu Bo 	 * 3) the root is not forced COW.
1343f1ebcc74SLiu Bo 	 *
1344f1ebcc74SLiu Bo 	 * What is forced COW:
1345f1ebcc74SLiu Bo 	 *    when we create snapshot during commiting the transaction,
1346f1ebcc74SLiu Bo 	 *    after we've finished coping src root, we must COW the shared
1347f1ebcc74SLiu Bo 	 *    block to ensure the metadata consistency.
1348f1ebcc74SLiu Bo 	 */
13495d4f98a2SYan Zheng 	if (btrfs_header_generation(buf) == trans->transid &&
13505d4f98a2SYan Zheng 	    !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN) &&
13515d4f98a2SYan Zheng 	    !(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
1352f1ebcc74SLiu Bo 	      btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)) &&
1353f1ebcc74SLiu Bo 	    !root->force_cow)
13545d4f98a2SYan Zheng 		return 0;
13555d4f98a2SYan Zheng 	return 1;
13565d4f98a2SYan Zheng }
13575d4f98a2SYan Zheng 
1358d352ac68SChris Mason /*
1359d352ac68SChris Mason  * cows a single block, see __btrfs_cow_block for the real work.
1360d352ac68SChris Mason  * This version of it has extra checks so that a block isn't cow'd more than
1361d352ac68SChris Mason  * once per transaction, as long as it hasn't been written yet
1362d352ac68SChris Mason  */
1363d397712bSChris Mason noinline int btrfs_cow_block(struct btrfs_trans_handle *trans,
13645f39d397SChris Mason 		    struct btrfs_root *root, struct extent_buffer *buf,
13655f39d397SChris Mason 		    struct extent_buffer *parent, int parent_slot,
13669fa8cfe7SChris Mason 		    struct extent_buffer **cow_ret)
136702217ed2SChris Mason {
13686702ed49SChris Mason 	u64 search_start;
1369f510cfecSChris Mason 	int ret;
1370dc17ff8fSChris Mason 
137131b1a2bdSJulia Lawall 	if (trans->transaction != root->fs_info->running_transaction)
137231b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "trans %llu running %llu\n",
1373d397712bSChris Mason 		       (unsigned long long)trans->transid,
1374d397712bSChris Mason 		       (unsigned long long)
1375ccd467d6SChris Mason 		       root->fs_info->running_transaction->transid);
137631b1a2bdSJulia Lawall 
137731b1a2bdSJulia Lawall 	if (trans->transid != root->fs_info->generation)
137831b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "trans %llu running %llu\n",
1379d397712bSChris Mason 		       (unsigned long long)trans->transid,
1380d397712bSChris Mason 		       (unsigned long long)root->fs_info->generation);
1381dc17ff8fSChris Mason 
13825d4f98a2SYan Zheng 	if (!should_cow_block(trans, root, buf)) {
138302217ed2SChris Mason 		*cow_ret = buf;
138402217ed2SChris Mason 		return 0;
138502217ed2SChris Mason 	}
1386c487685dSChris Mason 
13870b86a832SChris Mason 	search_start = buf->start & ~((u64)(1024 * 1024 * 1024) - 1);
1388b4ce94deSChris Mason 
1389b4ce94deSChris Mason 	if (parent)
1390b4ce94deSChris Mason 		btrfs_set_lock_blocking(parent);
1391b4ce94deSChris Mason 	btrfs_set_lock_blocking(buf);
1392b4ce94deSChris Mason 
1393f510cfecSChris Mason 	ret = __btrfs_cow_block(trans, root, buf, parent,
13949fa8cfe7SChris Mason 				 parent_slot, cow_ret, search_start, 0);
13951abe9b8aSliubo 
13961abe9b8aSliubo 	trace_btrfs_cow_block(root, buf, *cow_ret);
13971abe9b8aSliubo 
1398f510cfecSChris Mason 	return ret;
13992c90e5d6SChris Mason }
14006702ed49SChris Mason 
1401d352ac68SChris Mason /*
1402d352ac68SChris Mason  * helper function for defrag to decide if two blocks pointed to by a
1403d352ac68SChris Mason  * node are actually close by
1404d352ac68SChris Mason  */
14056b80053dSChris Mason static int close_blocks(u64 blocknr, u64 other, u32 blocksize)
14066702ed49SChris Mason {
14076b80053dSChris Mason 	if (blocknr < other && other - (blocknr + blocksize) < 32768)
14086702ed49SChris Mason 		return 1;
14096b80053dSChris Mason 	if (blocknr > other && blocknr - (other + blocksize) < 32768)
14106702ed49SChris Mason 		return 1;
141102217ed2SChris Mason 	return 0;
141202217ed2SChris Mason }
141302217ed2SChris Mason 
1414081e9573SChris Mason /*
1415081e9573SChris Mason  * compare two keys in a memcmp fashion
1416081e9573SChris Mason  */
1417081e9573SChris Mason static int comp_keys(struct btrfs_disk_key *disk, struct btrfs_key *k2)
1418081e9573SChris Mason {
1419081e9573SChris Mason 	struct btrfs_key k1;
1420081e9573SChris Mason 
1421081e9573SChris Mason 	btrfs_disk_key_to_cpu(&k1, disk);
1422081e9573SChris Mason 
142320736abaSDiego Calleja 	return btrfs_comp_cpu_keys(&k1, k2);
1424081e9573SChris Mason }
1425081e9573SChris Mason 
1426f3465ca4SJosef Bacik /*
1427f3465ca4SJosef Bacik  * same as comp_keys only with two btrfs_key's
1428f3465ca4SJosef Bacik  */
14295d4f98a2SYan Zheng int btrfs_comp_cpu_keys(struct btrfs_key *k1, struct btrfs_key *k2)
1430f3465ca4SJosef Bacik {
1431f3465ca4SJosef Bacik 	if (k1->objectid > k2->objectid)
1432f3465ca4SJosef Bacik 		return 1;
1433f3465ca4SJosef Bacik 	if (k1->objectid < k2->objectid)
1434f3465ca4SJosef Bacik 		return -1;
1435f3465ca4SJosef Bacik 	if (k1->type > k2->type)
1436f3465ca4SJosef Bacik 		return 1;
1437f3465ca4SJosef Bacik 	if (k1->type < k2->type)
1438f3465ca4SJosef Bacik 		return -1;
1439f3465ca4SJosef Bacik 	if (k1->offset > k2->offset)
1440f3465ca4SJosef Bacik 		return 1;
1441f3465ca4SJosef Bacik 	if (k1->offset < k2->offset)
1442f3465ca4SJosef Bacik 		return -1;
1443f3465ca4SJosef Bacik 	return 0;
1444f3465ca4SJosef Bacik }
1445081e9573SChris Mason 
1446d352ac68SChris Mason /*
1447d352ac68SChris Mason  * this is used by the defrag code to go through all the
1448d352ac68SChris Mason  * leaves pointed to by a node and reallocate them so that
1449d352ac68SChris Mason  * disk order is close to key order
1450d352ac68SChris Mason  */
14516702ed49SChris Mason int btrfs_realloc_node(struct btrfs_trans_handle *trans,
14525f39d397SChris Mason 		       struct btrfs_root *root, struct extent_buffer *parent,
1453de78b51aSEric Sandeen 		       int start_slot, u64 *last_ret,
1454a6b6e75eSChris Mason 		       struct btrfs_key *progress)
14556702ed49SChris Mason {
14566b80053dSChris Mason 	struct extent_buffer *cur;
14576702ed49SChris Mason 	u64 blocknr;
1458ca7a79adSChris Mason 	u64 gen;
1459e9d0b13bSChris Mason 	u64 search_start = *last_ret;
1460e9d0b13bSChris Mason 	u64 last_block = 0;
14616702ed49SChris Mason 	u64 other;
14626702ed49SChris Mason 	u32 parent_nritems;
14636702ed49SChris Mason 	int end_slot;
14646702ed49SChris Mason 	int i;
14656702ed49SChris Mason 	int err = 0;
1466f2183bdeSChris Mason 	int parent_level;
14676b80053dSChris Mason 	int uptodate;
14686b80053dSChris Mason 	u32 blocksize;
1469081e9573SChris Mason 	int progress_passed = 0;
1470081e9573SChris Mason 	struct btrfs_disk_key disk_key;
14716702ed49SChris Mason 
14725708b959SChris Mason 	parent_level = btrfs_header_level(parent);
14735708b959SChris Mason 
14746c1500f2SJulia Lawall 	WARN_ON(trans->transaction != root->fs_info->running_transaction);
14756c1500f2SJulia Lawall 	WARN_ON(trans->transid != root->fs_info->generation);
147686479a04SChris Mason 
14776b80053dSChris Mason 	parent_nritems = btrfs_header_nritems(parent);
14786b80053dSChris Mason 	blocksize = btrfs_level_size(root, parent_level - 1);
14796702ed49SChris Mason 	end_slot = parent_nritems;
14806702ed49SChris Mason 
14816702ed49SChris Mason 	if (parent_nritems == 1)
14826702ed49SChris Mason 		return 0;
14836702ed49SChris Mason 
1484b4ce94deSChris Mason 	btrfs_set_lock_blocking(parent);
1485b4ce94deSChris Mason 
14866702ed49SChris Mason 	for (i = start_slot; i < end_slot; i++) {
14876702ed49SChris Mason 		int close = 1;
1488a6b6e75eSChris Mason 
1489081e9573SChris Mason 		btrfs_node_key(parent, &disk_key, i);
1490081e9573SChris Mason 		if (!progress_passed && comp_keys(&disk_key, progress) < 0)
1491081e9573SChris Mason 			continue;
1492081e9573SChris Mason 
1493081e9573SChris Mason 		progress_passed = 1;
14946b80053dSChris Mason 		blocknr = btrfs_node_blockptr(parent, i);
1495ca7a79adSChris Mason 		gen = btrfs_node_ptr_generation(parent, i);
1496e9d0b13bSChris Mason 		if (last_block == 0)
1497e9d0b13bSChris Mason 			last_block = blocknr;
14985708b959SChris Mason 
14996702ed49SChris Mason 		if (i > 0) {
15006b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i - 1);
15016b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
15026702ed49SChris Mason 		}
15030ef3e66bSChris Mason 		if (!close && i < end_slot - 2) {
15046b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i + 1);
15056b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
15066702ed49SChris Mason 		}
1507e9d0b13bSChris Mason 		if (close) {
1508e9d0b13bSChris Mason 			last_block = blocknr;
15096702ed49SChris Mason 			continue;
1510e9d0b13bSChris Mason 		}
15116702ed49SChris Mason 
15126b80053dSChris Mason 		cur = btrfs_find_tree_block(root, blocknr, blocksize);
15136b80053dSChris Mason 		if (cur)
1514b9fab919SChris Mason 			uptodate = btrfs_buffer_uptodate(cur, gen, 0);
15156b80053dSChris Mason 		else
15166b80053dSChris Mason 			uptodate = 0;
15175708b959SChris Mason 		if (!cur || !uptodate) {
15186b80053dSChris Mason 			if (!cur) {
15196b80053dSChris Mason 				cur = read_tree_block(root, blocknr,
1520ca7a79adSChris Mason 							 blocksize, gen);
1521416bc658SJosef Bacik 				if (!cur || !extent_buffer_uptodate(cur)) {
1522416bc658SJosef Bacik 					free_extent_buffer(cur);
152397d9a8a4STsutomu Itoh 					return -EIO;
1524416bc658SJosef Bacik 				}
15256b80053dSChris Mason 			} else if (!uptodate) {
1526018642a1STsutomu Itoh 				err = btrfs_read_buffer(cur, gen);
1527018642a1STsutomu Itoh 				if (err) {
1528018642a1STsutomu Itoh 					free_extent_buffer(cur);
1529018642a1STsutomu Itoh 					return err;
1530018642a1STsutomu Itoh 				}
15316702ed49SChris Mason 			}
1532f2183bdeSChris Mason 		}
1533e9d0b13bSChris Mason 		if (search_start == 0)
15346b80053dSChris Mason 			search_start = last_block;
1535e9d0b13bSChris Mason 
1536e7a84565SChris Mason 		btrfs_tree_lock(cur);
1537b4ce94deSChris Mason 		btrfs_set_lock_blocking(cur);
15386b80053dSChris Mason 		err = __btrfs_cow_block(trans, root, cur, parent, i,
1539e7a84565SChris Mason 					&cur, search_start,
15406b80053dSChris Mason 					min(16 * blocksize,
15419fa8cfe7SChris Mason 					    (end_slot - i) * blocksize));
1542252c38f0SYan 		if (err) {
1543e7a84565SChris Mason 			btrfs_tree_unlock(cur);
15446b80053dSChris Mason 			free_extent_buffer(cur);
15456702ed49SChris Mason 			break;
1546252c38f0SYan 		}
1547e7a84565SChris Mason 		search_start = cur->start;
1548e7a84565SChris Mason 		last_block = cur->start;
1549f2183bdeSChris Mason 		*last_ret = search_start;
1550e7a84565SChris Mason 		btrfs_tree_unlock(cur);
1551e7a84565SChris Mason 		free_extent_buffer(cur);
15526702ed49SChris Mason 	}
15536702ed49SChris Mason 	return err;
15546702ed49SChris Mason }
15556702ed49SChris Mason 
155674123bd7SChris Mason /*
155774123bd7SChris Mason  * The leaf data grows from end-to-front in the node.
155874123bd7SChris Mason  * this returns the address of the start of the last item,
155974123bd7SChris Mason  * which is the stop of the leaf data stack
156074123bd7SChris Mason  */
1561123abc88SChris Mason static inline unsigned int leaf_data_end(struct btrfs_root *root,
15625f39d397SChris Mason 					 struct extent_buffer *leaf)
1563be0e5c09SChris Mason {
15645f39d397SChris Mason 	u32 nr = btrfs_header_nritems(leaf);
1565be0e5c09SChris Mason 	if (nr == 0)
1566123abc88SChris Mason 		return BTRFS_LEAF_DATA_SIZE(root);
15675f39d397SChris Mason 	return btrfs_item_offset_nr(leaf, nr - 1);
1568be0e5c09SChris Mason }
1569be0e5c09SChris Mason 
1570aa5d6bedSChris Mason 
157174123bd7SChris Mason /*
15725f39d397SChris Mason  * search for key in the extent_buffer.  The items start at offset p,
15735f39d397SChris Mason  * and they are item_size apart.  There are 'max' items in p.
15745f39d397SChris Mason  *
157574123bd7SChris Mason  * the slot in the array is returned via slot, and it points to
157674123bd7SChris Mason  * the place where you would insert key if it is not found in
157774123bd7SChris Mason  * the array.
157874123bd7SChris Mason  *
157974123bd7SChris Mason  * slot may point to max if the key is bigger than all of the keys
158074123bd7SChris Mason  */
1581e02119d5SChris Mason static noinline int generic_bin_search(struct extent_buffer *eb,
1582e02119d5SChris Mason 				       unsigned long p,
15835f39d397SChris Mason 				       int item_size, struct btrfs_key *key,
1584be0e5c09SChris Mason 				       int max, int *slot)
1585be0e5c09SChris Mason {
1586be0e5c09SChris Mason 	int low = 0;
1587be0e5c09SChris Mason 	int high = max;
1588be0e5c09SChris Mason 	int mid;
1589be0e5c09SChris Mason 	int ret;
1590479965d6SChris Mason 	struct btrfs_disk_key *tmp = NULL;
15915f39d397SChris Mason 	struct btrfs_disk_key unaligned;
15925f39d397SChris Mason 	unsigned long offset;
15935f39d397SChris Mason 	char *kaddr = NULL;
15945f39d397SChris Mason 	unsigned long map_start = 0;
15955f39d397SChris Mason 	unsigned long map_len = 0;
1596479965d6SChris Mason 	int err;
1597be0e5c09SChris Mason 
1598be0e5c09SChris Mason 	while (low < high) {
1599be0e5c09SChris Mason 		mid = (low + high) / 2;
16005f39d397SChris Mason 		offset = p + mid * item_size;
16015f39d397SChris Mason 
1602a6591715SChris Mason 		if (!kaddr || offset < map_start ||
16035f39d397SChris Mason 		    (offset + sizeof(struct btrfs_disk_key)) >
16045f39d397SChris Mason 		    map_start + map_len) {
1605934d375bSChris Mason 
1606934d375bSChris Mason 			err = map_private_extent_buffer(eb, offset,
1607479965d6SChris Mason 						sizeof(struct btrfs_disk_key),
1608a6591715SChris Mason 						&kaddr, &map_start, &map_len);
16095f39d397SChris Mason 
1610479965d6SChris Mason 			if (!err) {
1611479965d6SChris Mason 				tmp = (struct btrfs_disk_key *)(kaddr + offset -
1612479965d6SChris Mason 							map_start);
1613479965d6SChris Mason 			} else {
16145f39d397SChris Mason 				read_extent_buffer(eb, &unaligned,
16155f39d397SChris Mason 						   offset, sizeof(unaligned));
16165f39d397SChris Mason 				tmp = &unaligned;
1617479965d6SChris Mason 			}
1618479965d6SChris Mason 
16195f39d397SChris Mason 		} else {
16205f39d397SChris Mason 			tmp = (struct btrfs_disk_key *)(kaddr + offset -
16215f39d397SChris Mason 							map_start);
16225f39d397SChris Mason 		}
1623be0e5c09SChris Mason 		ret = comp_keys(tmp, key);
1624be0e5c09SChris Mason 
1625be0e5c09SChris Mason 		if (ret < 0)
1626be0e5c09SChris Mason 			low = mid + 1;
1627be0e5c09SChris Mason 		else if (ret > 0)
1628be0e5c09SChris Mason 			high = mid;
1629be0e5c09SChris Mason 		else {
1630be0e5c09SChris Mason 			*slot = mid;
1631be0e5c09SChris Mason 			return 0;
1632be0e5c09SChris Mason 		}
1633be0e5c09SChris Mason 	}
1634be0e5c09SChris Mason 	*slot = low;
1635be0e5c09SChris Mason 	return 1;
1636be0e5c09SChris Mason }
1637be0e5c09SChris Mason 
163897571fd0SChris Mason /*
163997571fd0SChris Mason  * simple bin_search frontend that does the right thing for
164097571fd0SChris Mason  * leaves vs nodes
164197571fd0SChris Mason  */
16425f39d397SChris Mason static int bin_search(struct extent_buffer *eb, struct btrfs_key *key,
16435f39d397SChris Mason 		      int level, int *slot)
1644be0e5c09SChris Mason {
1645f775738fSWang Sheng-Hui 	if (level == 0)
16465f39d397SChris Mason 		return generic_bin_search(eb,
16475f39d397SChris Mason 					  offsetof(struct btrfs_leaf, items),
16480783fcfcSChris Mason 					  sizeof(struct btrfs_item),
16495f39d397SChris Mason 					  key, btrfs_header_nritems(eb),
16507518a238SChris Mason 					  slot);
1651f775738fSWang Sheng-Hui 	else
16525f39d397SChris Mason 		return generic_bin_search(eb,
16535f39d397SChris Mason 					  offsetof(struct btrfs_node, ptrs),
1654123abc88SChris Mason 					  sizeof(struct btrfs_key_ptr),
16555f39d397SChris Mason 					  key, btrfs_header_nritems(eb),
16567518a238SChris Mason 					  slot);
1657be0e5c09SChris Mason }
1658be0e5c09SChris Mason 
16595d4f98a2SYan Zheng int btrfs_bin_search(struct extent_buffer *eb, struct btrfs_key *key,
16605d4f98a2SYan Zheng 		     int level, int *slot)
16615d4f98a2SYan Zheng {
16625d4f98a2SYan Zheng 	return bin_search(eb, key, level, slot);
16635d4f98a2SYan Zheng }
16645d4f98a2SYan Zheng 
1665f0486c68SYan, Zheng static void root_add_used(struct btrfs_root *root, u32 size)
1666f0486c68SYan, Zheng {
1667f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
1668f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
1669f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) + size);
1670f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
1671f0486c68SYan, Zheng }
1672f0486c68SYan, Zheng 
1673f0486c68SYan, Zheng static void root_sub_used(struct btrfs_root *root, u32 size)
1674f0486c68SYan, Zheng {
1675f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
1676f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
1677f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) - size);
1678f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
1679f0486c68SYan, Zheng }
1680f0486c68SYan, Zheng 
1681d352ac68SChris Mason /* given a node and slot number, this reads the blocks it points to.  The
1682d352ac68SChris Mason  * extent buffer is returned with a reference taken (but unlocked).
1683d352ac68SChris Mason  * NULL is returned on error.
1684d352ac68SChris Mason  */
1685e02119d5SChris Mason static noinline struct extent_buffer *read_node_slot(struct btrfs_root *root,
16865f39d397SChris Mason 				   struct extent_buffer *parent, int slot)
1687bb803951SChris Mason {
1688ca7a79adSChris Mason 	int level = btrfs_header_level(parent);
1689416bc658SJosef Bacik 	struct extent_buffer *eb;
1690416bc658SJosef Bacik 
1691bb803951SChris Mason 	if (slot < 0)
1692bb803951SChris Mason 		return NULL;
16935f39d397SChris Mason 	if (slot >= btrfs_header_nritems(parent))
1694bb803951SChris Mason 		return NULL;
1695ca7a79adSChris Mason 
1696ca7a79adSChris Mason 	BUG_ON(level == 0);
1697ca7a79adSChris Mason 
1698416bc658SJosef Bacik 	eb = read_tree_block(root, btrfs_node_blockptr(parent, slot),
1699ca7a79adSChris Mason 			     btrfs_level_size(root, level - 1),
1700ca7a79adSChris Mason 			     btrfs_node_ptr_generation(parent, slot));
1701416bc658SJosef Bacik 	if (eb && !extent_buffer_uptodate(eb)) {
1702416bc658SJosef Bacik 		free_extent_buffer(eb);
1703416bc658SJosef Bacik 		eb = NULL;
1704416bc658SJosef Bacik 	}
1705416bc658SJosef Bacik 
1706416bc658SJosef Bacik 	return eb;
1707bb803951SChris Mason }
1708bb803951SChris Mason 
1709d352ac68SChris Mason /*
1710d352ac68SChris Mason  * node level balancing, used to make sure nodes are in proper order for
1711d352ac68SChris Mason  * item deletion.  We balance from the top down, so we have to make sure
1712d352ac68SChris Mason  * that a deletion won't leave an node completely empty later on.
1713d352ac68SChris Mason  */
1714e02119d5SChris Mason static noinline int balance_level(struct btrfs_trans_handle *trans,
171598ed5174SChris Mason 			 struct btrfs_root *root,
171698ed5174SChris Mason 			 struct btrfs_path *path, int level)
1717bb803951SChris Mason {
17185f39d397SChris Mason 	struct extent_buffer *right = NULL;
17195f39d397SChris Mason 	struct extent_buffer *mid;
17205f39d397SChris Mason 	struct extent_buffer *left = NULL;
17215f39d397SChris Mason 	struct extent_buffer *parent = NULL;
1722bb803951SChris Mason 	int ret = 0;
1723bb803951SChris Mason 	int wret;
1724bb803951SChris Mason 	int pslot;
1725bb803951SChris Mason 	int orig_slot = path->slots[level];
172679f95c82SChris Mason 	u64 orig_ptr;
1727bb803951SChris Mason 
1728bb803951SChris Mason 	if (level == 0)
1729bb803951SChris Mason 		return 0;
1730bb803951SChris Mason 
17315f39d397SChris Mason 	mid = path->nodes[level];
1732b4ce94deSChris Mason 
1733bd681513SChris Mason 	WARN_ON(path->locks[level] != BTRFS_WRITE_LOCK &&
1734bd681513SChris Mason 		path->locks[level] != BTRFS_WRITE_LOCK_BLOCKING);
17357bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
17367bb86316SChris Mason 
17371d4f8a0cSChris Mason 	orig_ptr = btrfs_node_blockptr(mid, orig_slot);
173879f95c82SChris Mason 
1739a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
17405f39d397SChris Mason 		parent = path->nodes[level + 1];
1741bb803951SChris Mason 		pslot = path->slots[level + 1];
1742a05a9bb1SLi Zefan 	}
1743bb803951SChris Mason 
174440689478SChris Mason 	/*
174540689478SChris Mason 	 * deal with the case where there is only one pointer in the root
174640689478SChris Mason 	 * by promoting the node below to a root
174740689478SChris Mason 	 */
17485f39d397SChris Mason 	if (!parent) {
17495f39d397SChris Mason 		struct extent_buffer *child;
1750bb803951SChris Mason 
17515f39d397SChris Mason 		if (btrfs_header_nritems(mid) != 1)
1752bb803951SChris Mason 			return 0;
1753bb803951SChris Mason 
1754bb803951SChris Mason 		/* promote the child to a root */
17555f39d397SChris Mason 		child = read_node_slot(root, mid, 0);
1756305a26afSMark Fasheh 		if (!child) {
1757305a26afSMark Fasheh 			ret = -EROFS;
1758305a26afSMark Fasheh 			btrfs_std_error(root->fs_info, ret);
1759305a26afSMark Fasheh 			goto enospc;
1760305a26afSMark Fasheh 		}
1761305a26afSMark Fasheh 
1762925baeddSChris Mason 		btrfs_tree_lock(child);
1763b4ce94deSChris Mason 		btrfs_set_lock_blocking(child);
17649fa8cfe7SChris Mason 		ret = btrfs_cow_block(trans, root, child, mid, 0, &child);
1765f0486c68SYan, Zheng 		if (ret) {
1766f0486c68SYan, Zheng 			btrfs_tree_unlock(child);
1767f0486c68SYan, Zheng 			free_extent_buffer(child);
1768f0486c68SYan, Zheng 			goto enospc;
1769f0486c68SYan, Zheng 		}
17702f375ab9SYan 
177190f8d62eSJan Schmidt 		tree_mod_log_set_root_pointer(root, child, 1);
1772240f62c8SChris Mason 		rcu_assign_pointer(root->node, child);
1773925baeddSChris Mason 
17740b86a832SChris Mason 		add_root_to_dirty_list(root);
1775925baeddSChris Mason 		btrfs_tree_unlock(child);
1776b4ce94deSChris Mason 
1777925baeddSChris Mason 		path->locks[level] = 0;
1778bb803951SChris Mason 		path->nodes[level] = NULL;
17795f39d397SChris Mason 		clean_tree_block(trans, root, mid);
1780925baeddSChris Mason 		btrfs_tree_unlock(mid);
1781bb803951SChris Mason 		/* once for the path */
17825f39d397SChris Mason 		free_extent_buffer(mid);
1783f0486c68SYan, Zheng 
1784f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
17855581a51aSJan Schmidt 		btrfs_free_tree_block(trans, root, mid, 0, 1);
1786bb803951SChris Mason 		/* once for the root ptr */
17873083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
1788f0486c68SYan, Zheng 		return 0;
1789bb803951SChris Mason 	}
17905f39d397SChris Mason 	if (btrfs_header_nritems(mid) >
1791123abc88SChris Mason 	    BTRFS_NODEPTRS_PER_BLOCK(root) / 4)
1792bb803951SChris Mason 		return 0;
1793bb803951SChris Mason 
17945f39d397SChris Mason 	left = read_node_slot(root, parent, pslot - 1);
17955f39d397SChris Mason 	if (left) {
1796925baeddSChris Mason 		btrfs_tree_lock(left);
1797b4ce94deSChris Mason 		btrfs_set_lock_blocking(left);
17985f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, left,
17999fa8cfe7SChris Mason 				       parent, pslot - 1, &left);
180054aa1f4dSChris Mason 		if (wret) {
180154aa1f4dSChris Mason 			ret = wret;
180254aa1f4dSChris Mason 			goto enospc;
180354aa1f4dSChris Mason 		}
18042cc58cf2SChris Mason 	}
18055f39d397SChris Mason 	right = read_node_slot(root, parent, pslot + 1);
18065f39d397SChris Mason 	if (right) {
1807925baeddSChris Mason 		btrfs_tree_lock(right);
1808b4ce94deSChris Mason 		btrfs_set_lock_blocking(right);
18095f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, right,
18109fa8cfe7SChris Mason 				       parent, pslot + 1, &right);
18112cc58cf2SChris Mason 		if (wret) {
18122cc58cf2SChris Mason 			ret = wret;
18132cc58cf2SChris Mason 			goto enospc;
18142cc58cf2SChris Mason 		}
18152cc58cf2SChris Mason 	}
18162cc58cf2SChris Mason 
18172cc58cf2SChris Mason 	/* first, try to make some room in the middle buffer */
18185f39d397SChris Mason 	if (left) {
18195f39d397SChris Mason 		orig_slot += btrfs_header_nritems(left);
1820bce4eae9SChris Mason 		wret = push_node_left(trans, root, left, mid, 1);
182179f95c82SChris Mason 		if (wret < 0)
182279f95c82SChris Mason 			ret = wret;
1823bb803951SChris Mason 	}
182479f95c82SChris Mason 
182579f95c82SChris Mason 	/*
182679f95c82SChris Mason 	 * then try to empty the right most buffer into the middle
182779f95c82SChris Mason 	 */
18285f39d397SChris Mason 	if (right) {
1829971a1f66SChris Mason 		wret = push_node_left(trans, root, mid, right, 1);
183054aa1f4dSChris Mason 		if (wret < 0 && wret != -ENOSPC)
183179f95c82SChris Mason 			ret = wret;
18325f39d397SChris Mason 		if (btrfs_header_nritems(right) == 0) {
18335f39d397SChris Mason 			clean_tree_block(trans, root, right);
1834925baeddSChris Mason 			btrfs_tree_unlock(right);
1835afe5fea7STsutomu Itoh 			del_ptr(root, path, level + 1, pslot + 1);
1836f0486c68SYan, Zheng 			root_sub_used(root, right->len);
18375581a51aSJan Schmidt 			btrfs_free_tree_block(trans, root, right, 0, 1);
18383083ee2eSJosef Bacik 			free_extent_buffer_stale(right);
1839f0486c68SYan, Zheng 			right = NULL;
1840bb803951SChris Mason 		} else {
18415f39d397SChris Mason 			struct btrfs_disk_key right_key;
18425f39d397SChris Mason 			btrfs_node_key(right, &right_key, 0);
1843f230475eSJan Schmidt 			tree_mod_log_set_node_key(root->fs_info, parent,
184432adf090SLiu Bo 						  pslot + 1, 0);
18455f39d397SChris Mason 			btrfs_set_node_key(parent, &right_key, pslot + 1);
18465f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
1847bb803951SChris Mason 		}
1848bb803951SChris Mason 	}
18495f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 1) {
185079f95c82SChris Mason 		/*
185179f95c82SChris Mason 		 * we're not allowed to leave a node with one item in the
185279f95c82SChris Mason 		 * tree during a delete.  A deletion from lower in the tree
185379f95c82SChris Mason 		 * could try to delete the only pointer in this node.
185479f95c82SChris Mason 		 * So, pull some keys from the left.
185579f95c82SChris Mason 		 * There has to be a left pointer at this point because
185679f95c82SChris Mason 		 * otherwise we would have pulled some pointers from the
185779f95c82SChris Mason 		 * right
185879f95c82SChris Mason 		 */
1859305a26afSMark Fasheh 		if (!left) {
1860305a26afSMark Fasheh 			ret = -EROFS;
1861305a26afSMark Fasheh 			btrfs_std_error(root->fs_info, ret);
1862305a26afSMark Fasheh 			goto enospc;
1863305a26afSMark Fasheh 		}
18645f39d397SChris Mason 		wret = balance_node_right(trans, root, mid, left);
186554aa1f4dSChris Mason 		if (wret < 0) {
186679f95c82SChris Mason 			ret = wret;
186754aa1f4dSChris Mason 			goto enospc;
186854aa1f4dSChris Mason 		}
1869bce4eae9SChris Mason 		if (wret == 1) {
1870bce4eae9SChris Mason 			wret = push_node_left(trans, root, left, mid, 1);
1871bce4eae9SChris Mason 			if (wret < 0)
1872bce4eae9SChris Mason 				ret = wret;
1873bce4eae9SChris Mason 		}
187479f95c82SChris Mason 		BUG_ON(wret == 1);
187579f95c82SChris Mason 	}
18765f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 0) {
18775f39d397SChris Mason 		clean_tree_block(trans, root, mid);
1878925baeddSChris Mason 		btrfs_tree_unlock(mid);
1879afe5fea7STsutomu Itoh 		del_ptr(root, path, level + 1, pslot);
1880f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
18815581a51aSJan Schmidt 		btrfs_free_tree_block(trans, root, mid, 0, 1);
18823083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
1883f0486c68SYan, Zheng 		mid = NULL;
188479f95c82SChris Mason 	} else {
188579f95c82SChris Mason 		/* update the parent key to reflect our changes */
18865f39d397SChris Mason 		struct btrfs_disk_key mid_key;
18875f39d397SChris Mason 		btrfs_node_key(mid, &mid_key, 0);
188832adf090SLiu Bo 		tree_mod_log_set_node_key(root->fs_info, parent,
1889f230475eSJan Schmidt 					  pslot, 0);
18905f39d397SChris Mason 		btrfs_set_node_key(parent, &mid_key, pslot);
18915f39d397SChris Mason 		btrfs_mark_buffer_dirty(parent);
189279f95c82SChris Mason 	}
1893bb803951SChris Mason 
189479f95c82SChris Mason 	/* update the path */
18955f39d397SChris Mason 	if (left) {
18965f39d397SChris Mason 		if (btrfs_header_nritems(left) > orig_slot) {
18975f39d397SChris Mason 			extent_buffer_get(left);
1898925baeddSChris Mason 			/* left was locked after cow */
18995f39d397SChris Mason 			path->nodes[level] = left;
1900bb803951SChris Mason 			path->slots[level + 1] -= 1;
1901bb803951SChris Mason 			path->slots[level] = orig_slot;
1902925baeddSChris Mason 			if (mid) {
1903925baeddSChris Mason 				btrfs_tree_unlock(mid);
19045f39d397SChris Mason 				free_extent_buffer(mid);
1905925baeddSChris Mason 			}
1906bb803951SChris Mason 		} else {
19075f39d397SChris Mason 			orig_slot -= btrfs_header_nritems(left);
1908bb803951SChris Mason 			path->slots[level] = orig_slot;
1909bb803951SChris Mason 		}
1910bb803951SChris Mason 	}
191179f95c82SChris Mason 	/* double check we haven't messed things up */
1912e20d96d6SChris Mason 	if (orig_ptr !=
19135f39d397SChris Mason 	    btrfs_node_blockptr(path->nodes[level], path->slots[level]))
191479f95c82SChris Mason 		BUG();
191554aa1f4dSChris Mason enospc:
1916925baeddSChris Mason 	if (right) {
1917925baeddSChris Mason 		btrfs_tree_unlock(right);
19185f39d397SChris Mason 		free_extent_buffer(right);
1919925baeddSChris Mason 	}
1920925baeddSChris Mason 	if (left) {
1921925baeddSChris Mason 		if (path->nodes[level] != left)
1922925baeddSChris Mason 			btrfs_tree_unlock(left);
19235f39d397SChris Mason 		free_extent_buffer(left);
1924925baeddSChris Mason 	}
1925bb803951SChris Mason 	return ret;
1926bb803951SChris Mason }
1927bb803951SChris Mason 
1928d352ac68SChris Mason /* Node balancing for insertion.  Here we only split or push nodes around
1929d352ac68SChris Mason  * when they are completely full.  This is also done top down, so we
1930d352ac68SChris Mason  * have to be pessimistic.
1931d352ac68SChris Mason  */
1932d397712bSChris Mason static noinline int push_nodes_for_insert(struct btrfs_trans_handle *trans,
1933e66f709bSChris Mason 					  struct btrfs_root *root,
1934e66f709bSChris Mason 					  struct btrfs_path *path, int level)
1935e66f709bSChris Mason {
19365f39d397SChris Mason 	struct extent_buffer *right = NULL;
19375f39d397SChris Mason 	struct extent_buffer *mid;
19385f39d397SChris Mason 	struct extent_buffer *left = NULL;
19395f39d397SChris Mason 	struct extent_buffer *parent = NULL;
1940e66f709bSChris Mason 	int ret = 0;
1941e66f709bSChris Mason 	int wret;
1942e66f709bSChris Mason 	int pslot;
1943e66f709bSChris Mason 	int orig_slot = path->slots[level];
1944e66f709bSChris Mason 
1945e66f709bSChris Mason 	if (level == 0)
1946e66f709bSChris Mason 		return 1;
1947e66f709bSChris Mason 
19485f39d397SChris Mason 	mid = path->nodes[level];
19497bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
1950e66f709bSChris Mason 
1951a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
19525f39d397SChris Mason 		parent = path->nodes[level + 1];
1953e66f709bSChris Mason 		pslot = path->slots[level + 1];
1954a05a9bb1SLi Zefan 	}
1955e66f709bSChris Mason 
19565f39d397SChris Mason 	if (!parent)
1957e66f709bSChris Mason 		return 1;
1958e66f709bSChris Mason 
19595f39d397SChris Mason 	left = read_node_slot(root, parent, pslot - 1);
1960e66f709bSChris Mason 
1961e66f709bSChris Mason 	/* first, try to make some room in the middle buffer */
19625f39d397SChris Mason 	if (left) {
1963e66f709bSChris Mason 		u32 left_nr;
1964925baeddSChris Mason 
1965925baeddSChris Mason 		btrfs_tree_lock(left);
1966b4ce94deSChris Mason 		btrfs_set_lock_blocking(left);
1967b4ce94deSChris Mason 
19685f39d397SChris Mason 		left_nr = btrfs_header_nritems(left);
196933ade1f8SChris Mason 		if (left_nr >= BTRFS_NODEPTRS_PER_BLOCK(root) - 1) {
197033ade1f8SChris Mason 			wret = 1;
197133ade1f8SChris Mason 		} else {
19725f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, left, parent,
19739fa8cfe7SChris Mason 					      pslot - 1, &left);
197454aa1f4dSChris Mason 			if (ret)
197554aa1f4dSChris Mason 				wret = 1;
197654aa1f4dSChris Mason 			else {
197754aa1f4dSChris Mason 				wret = push_node_left(trans, root,
1978971a1f66SChris Mason 						      left, mid, 0);
197954aa1f4dSChris Mason 			}
198033ade1f8SChris Mason 		}
1981e66f709bSChris Mason 		if (wret < 0)
1982e66f709bSChris Mason 			ret = wret;
1983e66f709bSChris Mason 		if (wret == 0) {
19845f39d397SChris Mason 			struct btrfs_disk_key disk_key;
1985e66f709bSChris Mason 			orig_slot += left_nr;
19865f39d397SChris Mason 			btrfs_node_key(mid, &disk_key, 0);
1987f230475eSJan Schmidt 			tree_mod_log_set_node_key(root->fs_info, parent,
198832adf090SLiu Bo 						  pslot, 0);
19895f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot);
19905f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
19915f39d397SChris Mason 			if (btrfs_header_nritems(left) > orig_slot) {
19925f39d397SChris Mason 				path->nodes[level] = left;
1993e66f709bSChris Mason 				path->slots[level + 1] -= 1;
1994e66f709bSChris Mason 				path->slots[level] = orig_slot;
1995925baeddSChris Mason 				btrfs_tree_unlock(mid);
19965f39d397SChris Mason 				free_extent_buffer(mid);
1997e66f709bSChris Mason 			} else {
1998e66f709bSChris Mason 				orig_slot -=
19995f39d397SChris Mason 					btrfs_header_nritems(left);
2000e66f709bSChris Mason 				path->slots[level] = orig_slot;
2001925baeddSChris Mason 				btrfs_tree_unlock(left);
20025f39d397SChris Mason 				free_extent_buffer(left);
2003e66f709bSChris Mason 			}
2004e66f709bSChris Mason 			return 0;
2005e66f709bSChris Mason 		}
2006925baeddSChris Mason 		btrfs_tree_unlock(left);
20075f39d397SChris Mason 		free_extent_buffer(left);
2008e66f709bSChris Mason 	}
20095f39d397SChris Mason 	right = read_node_slot(root, parent, pslot + 1);
2010e66f709bSChris Mason 
2011e66f709bSChris Mason 	/*
2012e66f709bSChris Mason 	 * then try to empty the right most buffer into the middle
2013e66f709bSChris Mason 	 */
20145f39d397SChris Mason 	if (right) {
201533ade1f8SChris Mason 		u32 right_nr;
2016b4ce94deSChris Mason 
2017925baeddSChris Mason 		btrfs_tree_lock(right);
2018b4ce94deSChris Mason 		btrfs_set_lock_blocking(right);
2019b4ce94deSChris Mason 
20205f39d397SChris Mason 		right_nr = btrfs_header_nritems(right);
202133ade1f8SChris Mason 		if (right_nr >= BTRFS_NODEPTRS_PER_BLOCK(root) - 1) {
202233ade1f8SChris Mason 			wret = 1;
202333ade1f8SChris Mason 		} else {
20245f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, right,
20255f39d397SChris Mason 					      parent, pslot + 1,
20269fa8cfe7SChris Mason 					      &right);
202754aa1f4dSChris Mason 			if (ret)
202854aa1f4dSChris Mason 				wret = 1;
202954aa1f4dSChris Mason 			else {
203033ade1f8SChris Mason 				wret = balance_node_right(trans, root,
20315f39d397SChris Mason 							  right, mid);
203233ade1f8SChris Mason 			}
203354aa1f4dSChris Mason 		}
2034e66f709bSChris Mason 		if (wret < 0)
2035e66f709bSChris Mason 			ret = wret;
2036e66f709bSChris Mason 		if (wret == 0) {
20375f39d397SChris Mason 			struct btrfs_disk_key disk_key;
20385f39d397SChris Mason 
20395f39d397SChris Mason 			btrfs_node_key(right, &disk_key, 0);
2040f230475eSJan Schmidt 			tree_mod_log_set_node_key(root->fs_info, parent,
204132adf090SLiu Bo 						  pslot + 1, 0);
20425f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot + 1);
20435f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
20445f39d397SChris Mason 
20455f39d397SChris Mason 			if (btrfs_header_nritems(mid) <= orig_slot) {
20465f39d397SChris Mason 				path->nodes[level] = right;
2047e66f709bSChris Mason 				path->slots[level + 1] += 1;
2048e66f709bSChris Mason 				path->slots[level] = orig_slot -
20495f39d397SChris Mason 					btrfs_header_nritems(mid);
2050925baeddSChris Mason 				btrfs_tree_unlock(mid);
20515f39d397SChris Mason 				free_extent_buffer(mid);
2052e66f709bSChris Mason 			} else {
2053925baeddSChris Mason 				btrfs_tree_unlock(right);
20545f39d397SChris Mason 				free_extent_buffer(right);
2055e66f709bSChris Mason 			}
2056e66f709bSChris Mason 			return 0;
2057e66f709bSChris Mason 		}
2058925baeddSChris Mason 		btrfs_tree_unlock(right);
20595f39d397SChris Mason 		free_extent_buffer(right);
2060e66f709bSChris Mason 	}
2061e66f709bSChris Mason 	return 1;
2062e66f709bSChris Mason }
2063e66f709bSChris Mason 
206474123bd7SChris Mason /*
2065d352ac68SChris Mason  * readahead one full node of leaves, finding things that are close
2066d352ac68SChris Mason  * to the block in 'slot', and triggering ra on them.
20673c69faecSChris Mason  */
2068c8c42864SChris Mason static void reada_for_search(struct btrfs_root *root,
2069e02119d5SChris Mason 			     struct btrfs_path *path,
207001f46658SChris Mason 			     int level, int slot, u64 objectid)
20713c69faecSChris Mason {
20725f39d397SChris Mason 	struct extent_buffer *node;
207301f46658SChris Mason 	struct btrfs_disk_key disk_key;
20743c69faecSChris Mason 	u32 nritems;
20753c69faecSChris Mason 	u64 search;
2076a7175319SChris Mason 	u64 target;
20776b80053dSChris Mason 	u64 nread = 0;
2078cb25c2eaSJosef Bacik 	u64 gen;
20793c69faecSChris Mason 	int direction = path->reada;
20805f39d397SChris Mason 	struct extent_buffer *eb;
20816b80053dSChris Mason 	u32 nr;
20826b80053dSChris Mason 	u32 blocksize;
20836b80053dSChris Mason 	u32 nscan = 0;
2084db94535dSChris Mason 
2085a6b6e75eSChris Mason 	if (level != 1)
20863c69faecSChris Mason 		return;
20873c69faecSChris Mason 
20886702ed49SChris Mason 	if (!path->nodes[level])
20896702ed49SChris Mason 		return;
20906702ed49SChris Mason 
20915f39d397SChris Mason 	node = path->nodes[level];
2092925baeddSChris Mason 
20933c69faecSChris Mason 	search = btrfs_node_blockptr(node, slot);
20946b80053dSChris Mason 	blocksize = btrfs_level_size(root, level - 1);
20956b80053dSChris Mason 	eb = btrfs_find_tree_block(root, search, blocksize);
20965f39d397SChris Mason 	if (eb) {
20975f39d397SChris Mason 		free_extent_buffer(eb);
20983c69faecSChris Mason 		return;
20993c69faecSChris Mason 	}
21003c69faecSChris Mason 
2101a7175319SChris Mason 	target = search;
21026b80053dSChris Mason 
21035f39d397SChris Mason 	nritems = btrfs_header_nritems(node);
21046b80053dSChris Mason 	nr = slot;
210525b8b936SJosef Bacik 
21063c69faecSChris Mason 	while (1) {
21076b80053dSChris Mason 		if (direction < 0) {
21086b80053dSChris Mason 			if (nr == 0)
21093c69faecSChris Mason 				break;
21106b80053dSChris Mason 			nr--;
21116b80053dSChris Mason 		} else if (direction > 0) {
21126b80053dSChris Mason 			nr++;
21136b80053dSChris Mason 			if (nr >= nritems)
21146b80053dSChris Mason 				break;
21153c69faecSChris Mason 		}
211601f46658SChris Mason 		if (path->reada < 0 && objectid) {
211701f46658SChris Mason 			btrfs_node_key(node, &disk_key, nr);
211801f46658SChris Mason 			if (btrfs_disk_key_objectid(&disk_key) != objectid)
211901f46658SChris Mason 				break;
212001f46658SChris Mason 		}
21216b80053dSChris Mason 		search = btrfs_node_blockptr(node, nr);
2122a7175319SChris Mason 		if ((search <= target && target - search <= 65536) ||
2123a7175319SChris Mason 		    (search > target && search - target <= 65536)) {
2124cb25c2eaSJosef Bacik 			gen = btrfs_node_ptr_generation(node, nr);
2125cb25c2eaSJosef Bacik 			readahead_tree_block(root, search, blocksize, gen);
21266b80053dSChris Mason 			nread += blocksize;
21273c69faecSChris Mason 		}
21286b80053dSChris Mason 		nscan++;
2129a7175319SChris Mason 		if ((nread > 65536 || nscan > 32))
21306b80053dSChris Mason 			break;
21313c69faecSChris Mason 	}
21323c69faecSChris Mason }
2133925baeddSChris Mason 
21340b08851fSJosef Bacik static noinline void reada_for_balance(struct btrfs_root *root,
2135b4ce94deSChris Mason 				       struct btrfs_path *path, int level)
2136b4ce94deSChris Mason {
2137b4ce94deSChris Mason 	int slot;
2138b4ce94deSChris Mason 	int nritems;
2139b4ce94deSChris Mason 	struct extent_buffer *parent;
2140b4ce94deSChris Mason 	struct extent_buffer *eb;
2141b4ce94deSChris Mason 	u64 gen;
2142b4ce94deSChris Mason 	u64 block1 = 0;
2143b4ce94deSChris Mason 	u64 block2 = 0;
2144b4ce94deSChris Mason 	int blocksize;
2145b4ce94deSChris Mason 
21468c594ea8SChris Mason 	parent = path->nodes[level + 1];
2147b4ce94deSChris Mason 	if (!parent)
21480b08851fSJosef Bacik 		return;
2149b4ce94deSChris Mason 
2150b4ce94deSChris Mason 	nritems = btrfs_header_nritems(parent);
21518c594ea8SChris Mason 	slot = path->slots[level + 1];
2152b4ce94deSChris Mason 	blocksize = btrfs_level_size(root, level);
2153b4ce94deSChris Mason 
2154b4ce94deSChris Mason 	if (slot > 0) {
2155b4ce94deSChris Mason 		block1 = btrfs_node_blockptr(parent, slot - 1);
2156b4ce94deSChris Mason 		gen = btrfs_node_ptr_generation(parent, slot - 1);
2157b4ce94deSChris Mason 		eb = btrfs_find_tree_block(root, block1, blocksize);
2158b9fab919SChris Mason 		/*
2159b9fab919SChris Mason 		 * if we get -eagain from btrfs_buffer_uptodate, we
2160b9fab919SChris Mason 		 * don't want to return eagain here.  That will loop
2161b9fab919SChris Mason 		 * forever
2162b9fab919SChris Mason 		 */
2163b9fab919SChris Mason 		if (eb && btrfs_buffer_uptodate(eb, gen, 1) != 0)
2164b4ce94deSChris Mason 			block1 = 0;
2165b4ce94deSChris Mason 		free_extent_buffer(eb);
2166b4ce94deSChris Mason 	}
21678c594ea8SChris Mason 	if (slot + 1 < nritems) {
2168b4ce94deSChris Mason 		block2 = btrfs_node_blockptr(parent, slot + 1);
2169b4ce94deSChris Mason 		gen = btrfs_node_ptr_generation(parent, slot + 1);
2170b4ce94deSChris Mason 		eb = btrfs_find_tree_block(root, block2, blocksize);
2171b9fab919SChris Mason 		if (eb && btrfs_buffer_uptodate(eb, gen, 1) != 0)
2172b4ce94deSChris Mason 			block2 = 0;
2173b4ce94deSChris Mason 		free_extent_buffer(eb);
2174b4ce94deSChris Mason 	}
21758c594ea8SChris Mason 
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 
2182b4ce94deSChris Mason 
2183b4ce94deSChris Mason /*
2184d397712bSChris Mason  * when we walk down the tree, it is usually safe to unlock the higher layers
2185d397712bSChris Mason  * in the tree.  The exceptions are when our path goes through slot 0, because
2186d397712bSChris Mason  * operations on the tree might require changing key pointers higher up in the
2187d397712bSChris Mason  * tree.
2188d352ac68SChris Mason  *
2189d397712bSChris Mason  * callers might also have set path->keep_locks, which tells this code to keep
2190d397712bSChris Mason  * the lock if the path points to the last slot in the block.  This is part of
2191d397712bSChris Mason  * walking through the tree, and selecting the next slot in the higher block.
2192d352ac68SChris Mason  *
2193d397712bSChris Mason  * lowest_unlock sets the lowest level in the tree we're allowed to unlock.  so
2194d397712bSChris Mason  * if lowest_unlock is 1, level 0 won't be unlocked
2195d352ac68SChris Mason  */
2196e02119d5SChris Mason static noinline void unlock_up(struct btrfs_path *path, int level,
2197f7c79f30SChris Mason 			       int lowest_unlock, int min_write_lock_level,
2198f7c79f30SChris Mason 			       int *write_lock_level)
2199925baeddSChris Mason {
2200925baeddSChris Mason 	int i;
2201925baeddSChris Mason 	int skip_level = level;
2202051e1b9fSChris Mason 	int no_skips = 0;
2203925baeddSChris Mason 	struct extent_buffer *t;
2204925baeddSChris Mason 
2205925baeddSChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2206925baeddSChris Mason 		if (!path->nodes[i])
2207925baeddSChris Mason 			break;
2208925baeddSChris Mason 		if (!path->locks[i])
2209925baeddSChris Mason 			break;
2210051e1b9fSChris Mason 		if (!no_skips && path->slots[i] == 0) {
2211925baeddSChris Mason 			skip_level = i + 1;
2212925baeddSChris Mason 			continue;
2213925baeddSChris Mason 		}
2214051e1b9fSChris Mason 		if (!no_skips && path->keep_locks) {
2215925baeddSChris Mason 			u32 nritems;
2216925baeddSChris Mason 			t = path->nodes[i];
2217925baeddSChris Mason 			nritems = btrfs_header_nritems(t);
2218051e1b9fSChris Mason 			if (nritems < 1 || path->slots[i] >= nritems - 1) {
2219925baeddSChris Mason 				skip_level = i + 1;
2220925baeddSChris Mason 				continue;
2221925baeddSChris Mason 			}
2222925baeddSChris Mason 		}
2223051e1b9fSChris Mason 		if (skip_level < i && i >= lowest_unlock)
2224051e1b9fSChris Mason 			no_skips = 1;
2225051e1b9fSChris Mason 
2226925baeddSChris Mason 		t = path->nodes[i];
2227925baeddSChris Mason 		if (i >= lowest_unlock && i > skip_level && path->locks[i]) {
2228bd681513SChris Mason 			btrfs_tree_unlock_rw(t, path->locks[i]);
2229925baeddSChris Mason 			path->locks[i] = 0;
2230f7c79f30SChris Mason 			if (write_lock_level &&
2231f7c79f30SChris Mason 			    i > min_write_lock_level &&
2232f7c79f30SChris Mason 			    i <= *write_lock_level) {
2233f7c79f30SChris Mason 				*write_lock_level = i - 1;
2234f7c79f30SChris Mason 			}
2235925baeddSChris Mason 		}
2236925baeddSChris Mason 	}
2237925baeddSChris Mason }
2238925baeddSChris Mason 
22393c69faecSChris Mason /*
2240b4ce94deSChris Mason  * This releases any locks held in the path starting at level and
2241b4ce94deSChris Mason  * going all the way up to the root.
2242b4ce94deSChris Mason  *
2243b4ce94deSChris Mason  * btrfs_search_slot will keep the lock held on higher nodes in a few
2244b4ce94deSChris Mason  * corner cases, such as COW of the block at slot zero in the node.  This
2245b4ce94deSChris Mason  * ignores those rules, and it should only be called when there are no
2246b4ce94deSChris Mason  * more updates to be done higher up in the tree.
2247b4ce94deSChris Mason  */
2248b4ce94deSChris Mason noinline void btrfs_unlock_up_safe(struct btrfs_path *path, int level)
2249b4ce94deSChris Mason {
2250b4ce94deSChris Mason 	int i;
2251b4ce94deSChris Mason 
225209a2a8f9SJosef Bacik 	if (path->keep_locks)
2253b4ce94deSChris Mason 		return;
2254b4ce94deSChris Mason 
2255b4ce94deSChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2256b4ce94deSChris Mason 		if (!path->nodes[i])
225712f4daccSChris Mason 			continue;
2258b4ce94deSChris Mason 		if (!path->locks[i])
225912f4daccSChris Mason 			continue;
2260bd681513SChris Mason 		btrfs_tree_unlock_rw(path->nodes[i], path->locks[i]);
2261b4ce94deSChris Mason 		path->locks[i] = 0;
2262b4ce94deSChris Mason 	}
2263b4ce94deSChris Mason }
2264b4ce94deSChris Mason 
2265b4ce94deSChris Mason /*
2266c8c42864SChris Mason  * helper function for btrfs_search_slot.  The goal is to find a block
2267c8c42864SChris Mason  * in cache without setting the path to blocking.  If we find the block
2268c8c42864SChris Mason  * we return zero and the path is unchanged.
2269c8c42864SChris Mason  *
2270c8c42864SChris Mason  * If we can't find the block, we set the path blocking and do some
2271c8c42864SChris Mason  * reada.  -EAGAIN is returned and the search must be repeated.
2272c8c42864SChris Mason  */
2273c8c42864SChris Mason static int
2274c8c42864SChris Mason read_block_for_search(struct btrfs_trans_handle *trans,
2275c8c42864SChris Mason 		       struct btrfs_root *root, struct btrfs_path *p,
2276c8c42864SChris Mason 		       struct extent_buffer **eb_ret, int level, int slot,
22775d9e75c4SJan Schmidt 		       struct btrfs_key *key, u64 time_seq)
2278c8c42864SChris Mason {
2279c8c42864SChris Mason 	u64 blocknr;
2280c8c42864SChris Mason 	u64 gen;
2281c8c42864SChris Mason 	u32 blocksize;
2282c8c42864SChris Mason 	struct extent_buffer *b = *eb_ret;
2283c8c42864SChris Mason 	struct extent_buffer *tmp;
228476a05b35SChris Mason 	int ret;
2285c8c42864SChris Mason 
2286c8c42864SChris Mason 	blocknr = btrfs_node_blockptr(b, slot);
2287c8c42864SChris Mason 	gen = btrfs_node_ptr_generation(b, slot);
2288c8c42864SChris Mason 	blocksize = btrfs_level_size(root, level - 1);
2289c8c42864SChris Mason 
2290c8c42864SChris Mason 	tmp = btrfs_find_tree_block(root, blocknr, blocksize);
2291cb44921aSChris Mason 	if (tmp) {
2292b9fab919SChris Mason 		/* first we do an atomic uptodate check */
2293b9fab919SChris Mason 		if (btrfs_buffer_uptodate(tmp, gen, 1) > 0) {
2294c8c42864SChris Mason 			*eb_ret = tmp;
2295c8c42864SChris Mason 			return 0;
2296c8c42864SChris Mason 		}
2297bdf7c00eSJosef Bacik 
2298cb44921aSChris Mason 		/* the pages were up to date, but we failed
2299cb44921aSChris Mason 		 * the generation number check.  Do a full
2300cb44921aSChris Mason 		 * read for the generation number that is correct.
2301cb44921aSChris Mason 		 * We must do this without dropping locks so
2302cb44921aSChris Mason 		 * we can trust our generation number
2303cb44921aSChris Mason 		 */
2304bd681513SChris Mason 		btrfs_set_path_blocking(p);
2305bd681513SChris Mason 
2306b9fab919SChris Mason 		/* now we're allowed to do a blocking uptodate check */
2307bdf7c00eSJosef Bacik 		ret = btrfs_read_buffer(tmp, gen);
2308bdf7c00eSJosef Bacik 		if (!ret) {
2309cb44921aSChris Mason 			*eb_ret = tmp;
2310cb44921aSChris Mason 			return 0;
2311cb44921aSChris Mason 		}
2312cb44921aSChris Mason 		free_extent_buffer(tmp);
2313b3b4aa74SDavid Sterba 		btrfs_release_path(p);
2314cb44921aSChris Mason 		return -EIO;
2315cb44921aSChris Mason 	}
2316c8c42864SChris Mason 
2317c8c42864SChris Mason 	/*
2318c8c42864SChris Mason 	 * reduce lock contention at high levels
2319c8c42864SChris Mason 	 * of the btree by dropping locks before
232076a05b35SChris Mason 	 * we read.  Don't release the lock on the current
232176a05b35SChris Mason 	 * level because we need to walk this node to figure
232276a05b35SChris Mason 	 * out which blocks to read.
2323c8c42864SChris Mason 	 */
23248c594ea8SChris Mason 	btrfs_unlock_up_safe(p, level + 1);
23258c594ea8SChris Mason 	btrfs_set_path_blocking(p);
23268c594ea8SChris Mason 
2327c8c42864SChris Mason 	free_extent_buffer(tmp);
2328c8c42864SChris Mason 	if (p->reada)
2329c8c42864SChris Mason 		reada_for_search(root, p, level, slot, key->objectid);
2330c8c42864SChris Mason 
2331b3b4aa74SDavid Sterba 	btrfs_release_path(p);
233276a05b35SChris Mason 
233376a05b35SChris Mason 	ret = -EAGAIN;
23345bdd3536SYan, Zheng 	tmp = read_tree_block(root, blocknr, blocksize, 0);
233576a05b35SChris Mason 	if (tmp) {
233676a05b35SChris Mason 		/*
233776a05b35SChris Mason 		 * If the read above didn't mark this buffer up to date,
233876a05b35SChris Mason 		 * it will never end up being up to date.  Set ret to EIO now
233976a05b35SChris Mason 		 * and give up so that our caller doesn't loop forever
234076a05b35SChris Mason 		 * on our EAGAINs.
234176a05b35SChris Mason 		 */
2342b9fab919SChris Mason 		if (!btrfs_buffer_uptodate(tmp, 0, 0))
234376a05b35SChris Mason 			ret = -EIO;
2344c8c42864SChris Mason 		free_extent_buffer(tmp);
234576a05b35SChris Mason 	}
234676a05b35SChris Mason 	return ret;
2347c8c42864SChris Mason }
2348c8c42864SChris Mason 
2349c8c42864SChris Mason /*
2350c8c42864SChris Mason  * helper function for btrfs_search_slot.  This does all of the checks
2351c8c42864SChris Mason  * for node-level blocks and does any balancing required based on
2352c8c42864SChris Mason  * the ins_len.
2353c8c42864SChris Mason  *
2354c8c42864SChris Mason  * If no extra work was required, zero is returned.  If we had to
2355c8c42864SChris Mason  * drop the path, -EAGAIN is returned and btrfs_search_slot must
2356c8c42864SChris Mason  * start over
2357c8c42864SChris Mason  */
2358c8c42864SChris Mason static int
2359c8c42864SChris Mason setup_nodes_for_search(struct btrfs_trans_handle *trans,
2360c8c42864SChris Mason 		       struct btrfs_root *root, struct btrfs_path *p,
2361bd681513SChris Mason 		       struct extent_buffer *b, int level, int ins_len,
2362bd681513SChris Mason 		       int *write_lock_level)
2363c8c42864SChris Mason {
2364c8c42864SChris Mason 	int ret;
2365c8c42864SChris Mason 	if ((p->search_for_split || ins_len > 0) && btrfs_header_nritems(b) >=
2366c8c42864SChris Mason 	    BTRFS_NODEPTRS_PER_BLOCK(root) - 3) {
2367c8c42864SChris Mason 		int sret;
2368c8c42864SChris Mason 
2369bd681513SChris Mason 		if (*write_lock_level < level + 1) {
2370bd681513SChris Mason 			*write_lock_level = level + 1;
2371bd681513SChris Mason 			btrfs_release_path(p);
2372bd681513SChris Mason 			goto again;
2373bd681513SChris Mason 		}
2374bd681513SChris Mason 
2375c8c42864SChris Mason 		btrfs_set_path_blocking(p);
23760b08851fSJosef Bacik 		reada_for_balance(root, p, level);
2377c8c42864SChris Mason 		sret = split_node(trans, root, p, level);
2378bd681513SChris Mason 		btrfs_clear_path_blocking(p, NULL, 0);
2379c8c42864SChris Mason 
2380c8c42864SChris Mason 		BUG_ON(sret > 0);
2381c8c42864SChris Mason 		if (sret) {
2382c8c42864SChris Mason 			ret = sret;
2383c8c42864SChris Mason 			goto done;
2384c8c42864SChris Mason 		}
2385c8c42864SChris Mason 		b = p->nodes[level];
2386c8c42864SChris Mason 	} else if (ins_len < 0 && btrfs_header_nritems(b) <
2387cfbb9308SChris Mason 		   BTRFS_NODEPTRS_PER_BLOCK(root) / 2) {
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 		btrfs_set_path_blocking(p);
23970b08851fSJosef Bacik 		reada_for_balance(root, p, level);
2398c8c42864SChris Mason 		sret = balance_level(trans, root, p, level);
2399bd681513SChris Mason 		btrfs_clear_path_blocking(p, NULL, 0);
2400c8c42864SChris Mason 
2401c8c42864SChris Mason 		if (sret) {
2402c8c42864SChris Mason 			ret = sret;
2403c8c42864SChris Mason 			goto done;
2404c8c42864SChris Mason 		}
2405c8c42864SChris Mason 		b = p->nodes[level];
2406c8c42864SChris Mason 		if (!b) {
2407b3b4aa74SDavid Sterba 			btrfs_release_path(p);
2408c8c42864SChris Mason 			goto again;
2409c8c42864SChris Mason 		}
2410c8c42864SChris Mason 		BUG_ON(btrfs_header_nritems(b) == 1);
2411c8c42864SChris Mason 	}
2412c8c42864SChris Mason 	return 0;
2413c8c42864SChris Mason 
2414c8c42864SChris Mason again:
2415c8c42864SChris Mason 	ret = -EAGAIN;
2416c8c42864SChris Mason done:
2417c8c42864SChris Mason 	return ret;
2418c8c42864SChris Mason }
2419c8c42864SChris Mason 
2420c8c42864SChris Mason /*
242174123bd7SChris Mason  * look for key in the tree.  path is filled in with nodes along the way
242274123bd7SChris Mason  * if key is found, we return zero and you can find the item in the leaf
242374123bd7SChris Mason  * level of the path (level 0)
242474123bd7SChris Mason  *
242574123bd7SChris Mason  * If the key isn't found, the path points to the slot where it should
2426aa5d6bedSChris Mason  * be inserted, and 1 is returned.  If there are other errors during the
2427aa5d6bedSChris Mason  * search a negative error number is returned.
242897571fd0SChris Mason  *
242997571fd0SChris Mason  * if ins_len > 0, nodes and leaves will be split as we walk down the
243097571fd0SChris Mason  * tree.  if ins_len < 0, nodes will be merged as we walk down the tree (if
243197571fd0SChris Mason  * possible)
243274123bd7SChris Mason  */
2433e089f05cSChris Mason int btrfs_search_slot(struct btrfs_trans_handle *trans, struct btrfs_root
2434e089f05cSChris Mason 		      *root, struct btrfs_key *key, struct btrfs_path *p, int
2435e089f05cSChris Mason 		      ins_len, int cow)
2436be0e5c09SChris Mason {
24375f39d397SChris Mason 	struct extent_buffer *b;
2438be0e5c09SChris Mason 	int slot;
2439be0e5c09SChris Mason 	int ret;
244033c66f43SYan Zheng 	int err;
2441be0e5c09SChris Mason 	int level;
2442925baeddSChris Mason 	int lowest_unlock = 1;
2443bd681513SChris Mason 	int root_lock;
2444bd681513SChris Mason 	/* everything at write_lock_level or lower must be write locked */
2445bd681513SChris Mason 	int write_lock_level = 0;
24469f3a7427SChris Mason 	u8 lowest_level = 0;
2447f7c79f30SChris Mason 	int min_write_lock_level;
24489f3a7427SChris Mason 
24496702ed49SChris Mason 	lowest_level = p->lowest_level;
2450323ac95bSChris Mason 	WARN_ON(lowest_level && ins_len > 0);
245122b0ebdaSChris Mason 	WARN_ON(p->nodes[0] != NULL);
245225179201SJosef Bacik 
2453bd681513SChris Mason 	if (ins_len < 0) {
2454925baeddSChris Mason 		lowest_unlock = 2;
245565b51a00SChris Mason 
2456bd681513SChris Mason 		/* when we are removing items, we might have to go up to level
2457bd681513SChris Mason 		 * two as we update tree pointers  Make sure we keep write
2458bd681513SChris Mason 		 * for those levels as well
2459bd681513SChris Mason 		 */
2460bd681513SChris Mason 		write_lock_level = 2;
2461bd681513SChris Mason 	} else if (ins_len > 0) {
2462bd681513SChris Mason 		/*
2463bd681513SChris Mason 		 * for inserting items, make sure we have a write lock on
2464bd681513SChris Mason 		 * level 1 so we can update keys
2465bd681513SChris Mason 		 */
2466bd681513SChris Mason 		write_lock_level = 1;
2467bd681513SChris Mason 	}
2468bd681513SChris Mason 
2469bd681513SChris Mason 	if (!cow)
2470bd681513SChris Mason 		write_lock_level = -1;
2471bd681513SChris Mason 
247209a2a8f9SJosef Bacik 	if (cow && (p->keep_locks || p->lowest_level))
2473bd681513SChris Mason 		write_lock_level = BTRFS_MAX_LEVEL;
2474bd681513SChris Mason 
2475f7c79f30SChris Mason 	min_write_lock_level = write_lock_level;
2476f7c79f30SChris Mason 
2477bb803951SChris Mason again:
2478bd681513SChris Mason 	/*
2479bd681513SChris Mason 	 * we try very hard to do read locks on the root
2480bd681513SChris Mason 	 */
2481bd681513SChris Mason 	root_lock = BTRFS_READ_LOCK;
2482bd681513SChris Mason 	level = 0;
24835d4f98a2SYan Zheng 	if (p->search_commit_root) {
2484bd681513SChris Mason 		/*
2485bd681513SChris Mason 		 * the commit roots are read only
2486bd681513SChris Mason 		 * so we always do read locks
2487bd681513SChris Mason 		 */
24885d4f98a2SYan Zheng 		b = root->commit_root;
24895d4f98a2SYan Zheng 		extent_buffer_get(b);
2490bd681513SChris Mason 		level = btrfs_header_level(b);
24915d4f98a2SYan Zheng 		if (!p->skip_locking)
2492bd681513SChris Mason 			btrfs_tree_read_lock(b);
24935d4f98a2SYan Zheng 	} else {
2494bd681513SChris Mason 		if (p->skip_locking) {
24955cd57b2cSChris Mason 			b = btrfs_root_node(root);
2496bd681513SChris Mason 			level = btrfs_header_level(b);
2497bd681513SChris Mason 		} else {
2498bd681513SChris Mason 			/* we don't know the level of the root node
2499bd681513SChris Mason 			 * until we actually have it read locked
2500bd681513SChris Mason 			 */
2501bd681513SChris Mason 			b = btrfs_read_lock_root_node(root);
2502bd681513SChris Mason 			level = btrfs_header_level(b);
2503bd681513SChris Mason 			if (level <= write_lock_level) {
2504bd681513SChris Mason 				/* whoops, must trade for write lock */
2505bd681513SChris Mason 				btrfs_tree_read_unlock(b);
2506bd681513SChris Mason 				free_extent_buffer(b);
2507925baeddSChris Mason 				b = btrfs_lock_root_node(root);
2508bd681513SChris Mason 				root_lock = BTRFS_WRITE_LOCK;
2509bd681513SChris Mason 
2510bd681513SChris Mason 				/* the level might have changed, check again */
2511bd681513SChris Mason 				level = btrfs_header_level(b);
25125d4f98a2SYan Zheng 			}
2513bd681513SChris Mason 		}
2514bd681513SChris Mason 	}
2515bd681513SChris Mason 	p->nodes[level] = b;
2516bd681513SChris Mason 	if (!p->skip_locking)
2517bd681513SChris Mason 		p->locks[level] = root_lock;
2518925baeddSChris Mason 
2519eb60ceacSChris Mason 	while (b) {
25205f39d397SChris Mason 		level = btrfs_header_level(b);
252165b51a00SChris Mason 
252265b51a00SChris Mason 		/*
252365b51a00SChris Mason 		 * setup the path here so we can release it under lock
252465b51a00SChris Mason 		 * contention with the cow code
252565b51a00SChris Mason 		 */
252602217ed2SChris Mason 		if (cow) {
2527c8c42864SChris Mason 			/*
2528c8c42864SChris Mason 			 * if we don't really need to cow this block
2529c8c42864SChris Mason 			 * then we don't want to set the path blocking,
2530c8c42864SChris Mason 			 * so we test it here
2531c8c42864SChris Mason 			 */
25325d4f98a2SYan Zheng 			if (!should_cow_block(trans, root, b))
253365b51a00SChris Mason 				goto cow_done;
25345d4f98a2SYan Zheng 
2535b4ce94deSChris Mason 			btrfs_set_path_blocking(p);
2536b4ce94deSChris Mason 
2537bd681513SChris Mason 			/*
2538bd681513SChris Mason 			 * must have write locks on this node and the
2539bd681513SChris Mason 			 * parent
2540bd681513SChris Mason 			 */
25415124e00eSJosef Bacik 			if (level > write_lock_level ||
25425124e00eSJosef Bacik 			    (level + 1 > write_lock_level &&
25435124e00eSJosef Bacik 			    level + 1 < BTRFS_MAX_LEVEL &&
25445124e00eSJosef Bacik 			    p->nodes[level + 1])) {
2545bd681513SChris Mason 				write_lock_level = level + 1;
2546bd681513SChris Mason 				btrfs_release_path(p);
2547bd681513SChris Mason 				goto again;
2548bd681513SChris Mason 			}
2549bd681513SChris Mason 
255033c66f43SYan Zheng 			err = btrfs_cow_block(trans, root, b,
2551e20d96d6SChris Mason 					      p->nodes[level + 1],
25529fa8cfe7SChris Mason 					      p->slots[level + 1], &b);
255333c66f43SYan Zheng 			if (err) {
255433c66f43SYan Zheng 				ret = err;
255565b51a00SChris Mason 				goto done;
255654aa1f4dSChris Mason 			}
255702217ed2SChris Mason 		}
255865b51a00SChris Mason cow_done:
255902217ed2SChris Mason 		BUG_ON(!cow && ins_len);
256065b51a00SChris Mason 
2561eb60ceacSChris Mason 		p->nodes[level] = b;
2562bd681513SChris Mason 		btrfs_clear_path_blocking(p, NULL, 0);
2563b4ce94deSChris Mason 
2564b4ce94deSChris Mason 		/*
2565b4ce94deSChris Mason 		 * we have a lock on b and as long as we aren't changing
2566b4ce94deSChris Mason 		 * the tree, there is no way to for the items in b to change.
2567b4ce94deSChris Mason 		 * It is safe to drop the lock on our parent before we
2568b4ce94deSChris Mason 		 * go through the expensive btree search on b.
2569b4ce94deSChris Mason 		 *
2570b4ce94deSChris Mason 		 * If cow is true, then we might be changing slot zero,
2571b4ce94deSChris Mason 		 * which may require changing the parent.  So, we can't
2572b4ce94deSChris Mason 		 * drop the lock until after we know which slot we're
2573b4ce94deSChris Mason 		 * operating on.
2574b4ce94deSChris Mason 		 */
2575b4ce94deSChris Mason 		if (!cow)
2576b4ce94deSChris Mason 			btrfs_unlock_up_safe(p, level + 1);
2577b4ce94deSChris Mason 
25785f39d397SChris Mason 		ret = bin_search(b, key, level, &slot);
2579b4ce94deSChris Mason 
25805f39d397SChris Mason 		if (level != 0) {
258133c66f43SYan Zheng 			int dec = 0;
258233c66f43SYan Zheng 			if (ret && slot > 0) {
258333c66f43SYan Zheng 				dec = 1;
2584be0e5c09SChris Mason 				slot -= 1;
258533c66f43SYan Zheng 			}
2586be0e5c09SChris Mason 			p->slots[level] = slot;
258733c66f43SYan Zheng 			err = setup_nodes_for_search(trans, root, p, b, level,
2588bd681513SChris Mason 					     ins_len, &write_lock_level);
258933c66f43SYan Zheng 			if (err == -EAGAIN)
2590b4ce94deSChris Mason 				goto again;
259133c66f43SYan Zheng 			if (err) {
259233c66f43SYan Zheng 				ret = err;
259365b51a00SChris Mason 				goto done;
259433c66f43SYan Zheng 			}
25955c680ed6SChris Mason 			b = p->nodes[level];
25965c680ed6SChris Mason 			slot = p->slots[level];
2597b4ce94deSChris Mason 
2598bd681513SChris Mason 			/*
2599bd681513SChris Mason 			 * slot 0 is special, if we change the key
2600bd681513SChris Mason 			 * we have to update the parent pointer
2601bd681513SChris Mason 			 * which means we must have a write lock
2602bd681513SChris Mason 			 * on the parent
2603bd681513SChris Mason 			 */
2604bd681513SChris Mason 			if (slot == 0 && cow &&
2605bd681513SChris Mason 			    write_lock_level < level + 1) {
2606bd681513SChris Mason 				write_lock_level = level + 1;
2607bd681513SChris Mason 				btrfs_release_path(p);
2608bd681513SChris Mason 				goto again;
2609bd681513SChris Mason 			}
2610bd681513SChris Mason 
2611f7c79f30SChris Mason 			unlock_up(p, level, lowest_unlock,
2612f7c79f30SChris Mason 				  min_write_lock_level, &write_lock_level);
2613f9efa9c7SChris Mason 
2614925baeddSChris Mason 			if (level == lowest_level) {
261533c66f43SYan Zheng 				if (dec)
261633c66f43SYan Zheng 					p->slots[level]++;
26175b21f2edSZheng Yan 				goto done;
2618925baeddSChris Mason 			}
2619ca7a79adSChris Mason 
262033c66f43SYan Zheng 			err = read_block_for_search(trans, root, p,
26215d9e75c4SJan Schmidt 						    &b, level, slot, key, 0);
262233c66f43SYan Zheng 			if (err == -EAGAIN)
2623051e1b9fSChris Mason 				goto again;
262433c66f43SYan Zheng 			if (err) {
262533c66f43SYan Zheng 				ret = err;
262676a05b35SChris Mason 				goto done;
262733c66f43SYan Zheng 			}
262876a05b35SChris Mason 
2629b4ce94deSChris Mason 			if (!p->skip_locking) {
2630bd681513SChris Mason 				level = btrfs_header_level(b);
2631bd681513SChris Mason 				if (level <= write_lock_level) {
2632bd681513SChris Mason 					err = btrfs_try_tree_write_lock(b);
263333c66f43SYan Zheng 					if (!err) {
2634b4ce94deSChris Mason 						btrfs_set_path_blocking(p);
2635925baeddSChris Mason 						btrfs_tree_lock(b);
2636bd681513SChris Mason 						btrfs_clear_path_blocking(p, b,
2637bd681513SChris Mason 								  BTRFS_WRITE_LOCK);
2638b4ce94deSChris Mason 					}
2639bd681513SChris Mason 					p->locks[level] = BTRFS_WRITE_LOCK;
2640bd681513SChris Mason 				} else {
2641bd681513SChris Mason 					err = btrfs_try_tree_read_lock(b);
2642bd681513SChris Mason 					if (!err) {
2643bd681513SChris Mason 						btrfs_set_path_blocking(p);
2644bd681513SChris Mason 						btrfs_tree_read_lock(b);
2645bd681513SChris Mason 						btrfs_clear_path_blocking(p, b,
2646bd681513SChris Mason 								  BTRFS_READ_LOCK);
2647bd681513SChris Mason 					}
2648bd681513SChris Mason 					p->locks[level] = BTRFS_READ_LOCK;
2649bd681513SChris Mason 				}
2650bd681513SChris Mason 				p->nodes[level] = b;
2651b4ce94deSChris Mason 			}
2652be0e5c09SChris Mason 		} else {
2653be0e5c09SChris Mason 			p->slots[level] = slot;
265487b29b20SYan Zheng 			if (ins_len > 0 &&
265587b29b20SYan Zheng 			    btrfs_leaf_free_space(root, b) < ins_len) {
2656bd681513SChris Mason 				if (write_lock_level < 1) {
2657bd681513SChris Mason 					write_lock_level = 1;
2658bd681513SChris Mason 					btrfs_release_path(p);
2659bd681513SChris Mason 					goto again;
2660bd681513SChris Mason 				}
2661bd681513SChris Mason 
2662b4ce94deSChris Mason 				btrfs_set_path_blocking(p);
266333c66f43SYan Zheng 				err = split_leaf(trans, root, key,
2664cc0c5538SChris Mason 						 p, ins_len, ret == 0);
2665bd681513SChris Mason 				btrfs_clear_path_blocking(p, NULL, 0);
2666b4ce94deSChris Mason 
266733c66f43SYan Zheng 				BUG_ON(err > 0);
266833c66f43SYan Zheng 				if (err) {
266933c66f43SYan Zheng 					ret = err;
267065b51a00SChris Mason 					goto done;
267165b51a00SChris Mason 				}
26725c680ed6SChris Mason 			}
2673459931ecSChris Mason 			if (!p->search_for_split)
2674f7c79f30SChris Mason 				unlock_up(p, level, lowest_unlock,
2675f7c79f30SChris Mason 					  min_write_lock_level, &write_lock_level);
267665b51a00SChris Mason 			goto done;
267765b51a00SChris Mason 		}
267865b51a00SChris Mason 	}
267965b51a00SChris Mason 	ret = 1;
268065b51a00SChris Mason done:
2681b4ce94deSChris Mason 	/*
2682b4ce94deSChris Mason 	 * we don't really know what they plan on doing with the path
2683b4ce94deSChris Mason 	 * from here on, so for now just mark it as blocking
2684b4ce94deSChris Mason 	 */
2685b9473439SChris Mason 	if (!p->leave_spinning)
2686b4ce94deSChris Mason 		btrfs_set_path_blocking(p);
268776a05b35SChris Mason 	if (ret < 0)
2688b3b4aa74SDavid Sterba 		btrfs_release_path(p);
2689be0e5c09SChris Mason 	return ret;
2690be0e5c09SChris Mason }
2691be0e5c09SChris Mason 
269274123bd7SChris Mason /*
26935d9e75c4SJan Schmidt  * Like btrfs_search_slot, this looks for a key in the given tree. It uses the
26945d9e75c4SJan Schmidt  * current state of the tree together with the operations recorded in the tree
26955d9e75c4SJan Schmidt  * modification log to search for the key in a previous version of this tree, as
26965d9e75c4SJan Schmidt  * denoted by the time_seq parameter.
26975d9e75c4SJan Schmidt  *
26985d9e75c4SJan Schmidt  * Naturally, there is no support for insert, delete or cow operations.
26995d9e75c4SJan Schmidt  *
27005d9e75c4SJan Schmidt  * The resulting path and return value will be set up as if we called
27015d9e75c4SJan Schmidt  * btrfs_search_slot at that point in time with ins_len and cow both set to 0.
27025d9e75c4SJan Schmidt  */
27035d9e75c4SJan Schmidt int btrfs_search_old_slot(struct btrfs_root *root, struct btrfs_key *key,
27045d9e75c4SJan Schmidt 			  struct btrfs_path *p, u64 time_seq)
27055d9e75c4SJan Schmidt {
27065d9e75c4SJan Schmidt 	struct extent_buffer *b;
27075d9e75c4SJan Schmidt 	int slot;
27085d9e75c4SJan Schmidt 	int ret;
27095d9e75c4SJan Schmidt 	int err;
27105d9e75c4SJan Schmidt 	int level;
27115d9e75c4SJan Schmidt 	int lowest_unlock = 1;
27125d9e75c4SJan Schmidt 	u8 lowest_level = 0;
27135d9e75c4SJan Schmidt 
27145d9e75c4SJan Schmidt 	lowest_level = p->lowest_level;
27155d9e75c4SJan Schmidt 	WARN_ON(p->nodes[0] != NULL);
27165d9e75c4SJan Schmidt 
27175d9e75c4SJan Schmidt 	if (p->search_commit_root) {
27185d9e75c4SJan Schmidt 		BUG_ON(time_seq);
27195d9e75c4SJan Schmidt 		return btrfs_search_slot(NULL, root, key, p, 0, 0);
27205d9e75c4SJan Schmidt 	}
27215d9e75c4SJan Schmidt 
27225d9e75c4SJan Schmidt again:
27235d9e75c4SJan Schmidt 	b = get_old_root(root, time_seq);
27245d9e75c4SJan Schmidt 	level = btrfs_header_level(b);
27255d9e75c4SJan Schmidt 	p->locks[level] = BTRFS_READ_LOCK;
27265d9e75c4SJan Schmidt 
27275d9e75c4SJan Schmidt 	while (b) {
27285d9e75c4SJan Schmidt 		level = btrfs_header_level(b);
27295d9e75c4SJan Schmidt 		p->nodes[level] = b;
27305d9e75c4SJan Schmidt 		btrfs_clear_path_blocking(p, NULL, 0);
27315d9e75c4SJan Schmidt 
27325d9e75c4SJan Schmidt 		/*
27335d9e75c4SJan Schmidt 		 * we have a lock on b and as long as we aren't changing
27345d9e75c4SJan Schmidt 		 * the tree, there is no way to for the items in b to change.
27355d9e75c4SJan Schmidt 		 * It is safe to drop the lock on our parent before we
27365d9e75c4SJan Schmidt 		 * go through the expensive btree search on b.
27375d9e75c4SJan Schmidt 		 */
27385d9e75c4SJan Schmidt 		btrfs_unlock_up_safe(p, level + 1);
27395d9e75c4SJan Schmidt 
27405d9e75c4SJan Schmidt 		ret = bin_search(b, key, level, &slot);
27415d9e75c4SJan Schmidt 
27425d9e75c4SJan Schmidt 		if (level != 0) {
27435d9e75c4SJan Schmidt 			int dec = 0;
27445d9e75c4SJan Schmidt 			if (ret && slot > 0) {
27455d9e75c4SJan Schmidt 				dec = 1;
27465d9e75c4SJan Schmidt 				slot -= 1;
27475d9e75c4SJan Schmidt 			}
27485d9e75c4SJan Schmidt 			p->slots[level] = slot;
27495d9e75c4SJan Schmidt 			unlock_up(p, level, lowest_unlock, 0, NULL);
27505d9e75c4SJan Schmidt 
27515d9e75c4SJan Schmidt 			if (level == lowest_level) {
27525d9e75c4SJan Schmidt 				if (dec)
27535d9e75c4SJan Schmidt 					p->slots[level]++;
27545d9e75c4SJan Schmidt 				goto done;
27555d9e75c4SJan Schmidt 			}
27565d9e75c4SJan Schmidt 
27575d9e75c4SJan Schmidt 			err = read_block_for_search(NULL, root, p, &b, level,
27585d9e75c4SJan Schmidt 						    slot, key, time_seq);
27595d9e75c4SJan Schmidt 			if (err == -EAGAIN)
27605d9e75c4SJan Schmidt 				goto again;
27615d9e75c4SJan Schmidt 			if (err) {
27625d9e75c4SJan Schmidt 				ret = err;
27635d9e75c4SJan Schmidt 				goto done;
27645d9e75c4SJan Schmidt 			}
27655d9e75c4SJan Schmidt 
27665d9e75c4SJan Schmidt 			level = btrfs_header_level(b);
27675d9e75c4SJan Schmidt 			err = btrfs_try_tree_read_lock(b);
27685d9e75c4SJan Schmidt 			if (!err) {
27695d9e75c4SJan Schmidt 				btrfs_set_path_blocking(p);
27705d9e75c4SJan Schmidt 				btrfs_tree_read_lock(b);
27715d9e75c4SJan Schmidt 				btrfs_clear_path_blocking(p, b,
27725d9e75c4SJan Schmidt 							  BTRFS_READ_LOCK);
27735d9e75c4SJan Schmidt 			}
277447fb091fSJan Schmidt 			b = tree_mod_log_rewind(root->fs_info, b, time_seq);
27755d9e75c4SJan Schmidt 			p->locks[level] = BTRFS_READ_LOCK;
27765d9e75c4SJan Schmidt 			p->nodes[level] = b;
27775d9e75c4SJan Schmidt 		} else {
27785d9e75c4SJan Schmidt 			p->slots[level] = slot;
27795d9e75c4SJan Schmidt 			unlock_up(p, level, lowest_unlock, 0, NULL);
27805d9e75c4SJan Schmidt 			goto done;
27815d9e75c4SJan Schmidt 		}
27825d9e75c4SJan Schmidt 	}
27835d9e75c4SJan Schmidt 	ret = 1;
27845d9e75c4SJan Schmidt done:
27855d9e75c4SJan Schmidt 	if (!p->leave_spinning)
27865d9e75c4SJan Schmidt 		btrfs_set_path_blocking(p);
27875d9e75c4SJan Schmidt 	if (ret < 0)
27885d9e75c4SJan Schmidt 		btrfs_release_path(p);
27895d9e75c4SJan Schmidt 
27905d9e75c4SJan Schmidt 	return ret;
27915d9e75c4SJan Schmidt }
27925d9e75c4SJan Schmidt 
27935d9e75c4SJan Schmidt /*
27942f38b3e1SArne Jansen  * helper to use instead of search slot if no exact match is needed but
27952f38b3e1SArne Jansen  * instead the next or previous item should be returned.
27962f38b3e1SArne Jansen  * When find_higher is true, the next higher item is returned, the next lower
27972f38b3e1SArne Jansen  * otherwise.
27982f38b3e1SArne Jansen  * When return_any and find_higher are both true, and no higher item is found,
27992f38b3e1SArne Jansen  * return the next lower instead.
28002f38b3e1SArne Jansen  * When return_any is true and find_higher is false, and no lower item is found,
28012f38b3e1SArne Jansen  * return the next higher instead.
28022f38b3e1SArne Jansen  * It returns 0 if any item is found, 1 if none is found (tree empty), and
28032f38b3e1SArne Jansen  * < 0 on error
28042f38b3e1SArne Jansen  */
28052f38b3e1SArne Jansen int btrfs_search_slot_for_read(struct btrfs_root *root,
28062f38b3e1SArne Jansen 			       struct btrfs_key *key, struct btrfs_path *p,
28072f38b3e1SArne Jansen 			       int find_higher, int return_any)
28082f38b3e1SArne Jansen {
28092f38b3e1SArne Jansen 	int ret;
28102f38b3e1SArne Jansen 	struct extent_buffer *leaf;
28112f38b3e1SArne Jansen 
28122f38b3e1SArne Jansen again:
28132f38b3e1SArne Jansen 	ret = btrfs_search_slot(NULL, root, key, p, 0, 0);
28142f38b3e1SArne Jansen 	if (ret <= 0)
28152f38b3e1SArne Jansen 		return ret;
28162f38b3e1SArne Jansen 	/*
28172f38b3e1SArne Jansen 	 * a return value of 1 means the path is at the position where the
28182f38b3e1SArne Jansen 	 * item should be inserted. Normally this is the next bigger item,
28192f38b3e1SArne Jansen 	 * but in case the previous item is the last in a leaf, path points
28202f38b3e1SArne Jansen 	 * to the first free slot in the previous leaf, i.e. at an invalid
28212f38b3e1SArne Jansen 	 * item.
28222f38b3e1SArne Jansen 	 */
28232f38b3e1SArne Jansen 	leaf = p->nodes[0];
28242f38b3e1SArne Jansen 
28252f38b3e1SArne Jansen 	if (find_higher) {
28262f38b3e1SArne Jansen 		if (p->slots[0] >= btrfs_header_nritems(leaf)) {
28272f38b3e1SArne Jansen 			ret = btrfs_next_leaf(root, p);
28282f38b3e1SArne Jansen 			if (ret <= 0)
28292f38b3e1SArne Jansen 				return ret;
28302f38b3e1SArne Jansen 			if (!return_any)
28312f38b3e1SArne Jansen 				return 1;
28322f38b3e1SArne Jansen 			/*
28332f38b3e1SArne Jansen 			 * no higher item found, return the next
28342f38b3e1SArne Jansen 			 * lower instead
28352f38b3e1SArne Jansen 			 */
28362f38b3e1SArne Jansen 			return_any = 0;
28372f38b3e1SArne Jansen 			find_higher = 0;
28382f38b3e1SArne Jansen 			btrfs_release_path(p);
28392f38b3e1SArne Jansen 			goto again;
28402f38b3e1SArne Jansen 		}
28412f38b3e1SArne Jansen 	} else {
28422f38b3e1SArne Jansen 		if (p->slots[0] == 0) {
28432f38b3e1SArne Jansen 			ret = btrfs_prev_leaf(root, p);
2844e6793769SArne Jansen 			if (ret < 0)
28452f38b3e1SArne Jansen 				return ret;
2846e6793769SArne Jansen 			if (!ret) {
2847e6793769SArne Jansen 				p->slots[0] = btrfs_header_nritems(leaf) - 1;
2848e6793769SArne Jansen 				return 0;
2849e6793769SArne Jansen 			}
28502f38b3e1SArne Jansen 			if (!return_any)
28512f38b3e1SArne Jansen 				return 1;
28522f38b3e1SArne Jansen 			/*
28532f38b3e1SArne Jansen 			 * no lower item found, return the next
28542f38b3e1SArne Jansen 			 * higher instead
28552f38b3e1SArne Jansen 			 */
28562f38b3e1SArne Jansen 			return_any = 0;
28572f38b3e1SArne Jansen 			find_higher = 1;
28582f38b3e1SArne Jansen 			btrfs_release_path(p);
28592f38b3e1SArne Jansen 			goto again;
2860e6793769SArne Jansen 		} else {
28612f38b3e1SArne Jansen 			--p->slots[0];
28622f38b3e1SArne Jansen 		}
28632f38b3e1SArne Jansen 	}
28642f38b3e1SArne Jansen 	return 0;
28652f38b3e1SArne Jansen }
28662f38b3e1SArne Jansen 
28672f38b3e1SArne Jansen /*
286874123bd7SChris Mason  * adjust the pointers going up the tree, starting at level
286974123bd7SChris Mason  * making sure the right key of each node is points to 'key'.
287074123bd7SChris Mason  * This is used after shifting pointers to the left, so it stops
287174123bd7SChris Mason  * fixing up pointers when a given leaf/node is not in slot 0 of the
287274123bd7SChris Mason  * higher levels
2873aa5d6bedSChris Mason  *
287474123bd7SChris Mason  */
2875d6a0a126STsutomu Itoh static void fixup_low_keys(struct btrfs_root *root, struct btrfs_path *path,
28765f39d397SChris Mason 			   struct btrfs_disk_key *key, int level)
2877be0e5c09SChris Mason {
2878be0e5c09SChris Mason 	int i;
28795f39d397SChris Mason 	struct extent_buffer *t;
28805f39d397SChris Mason 
2881234b63a0SChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2882be0e5c09SChris Mason 		int tslot = path->slots[i];
2883eb60ceacSChris Mason 		if (!path->nodes[i])
2884be0e5c09SChris Mason 			break;
28855f39d397SChris Mason 		t = path->nodes[i];
288632adf090SLiu Bo 		tree_mod_log_set_node_key(root->fs_info, t, tslot, 1);
28875f39d397SChris Mason 		btrfs_set_node_key(t, key, tslot);
2888d6025579SChris Mason 		btrfs_mark_buffer_dirty(path->nodes[i]);
2889be0e5c09SChris Mason 		if (tslot != 0)
2890be0e5c09SChris Mason 			break;
2891be0e5c09SChris Mason 	}
2892be0e5c09SChris Mason }
2893be0e5c09SChris Mason 
289474123bd7SChris Mason /*
289531840ae1SZheng Yan  * update item key.
289631840ae1SZheng Yan  *
289731840ae1SZheng Yan  * This function isn't completely safe. It's the caller's responsibility
289831840ae1SZheng Yan  * that the new key won't break the order
289931840ae1SZheng Yan  */
2900afe5fea7STsutomu Itoh void btrfs_set_item_key_safe(struct btrfs_root *root, struct btrfs_path *path,
290131840ae1SZheng Yan 			     struct btrfs_key *new_key)
290231840ae1SZheng Yan {
290331840ae1SZheng Yan 	struct btrfs_disk_key disk_key;
290431840ae1SZheng Yan 	struct extent_buffer *eb;
290531840ae1SZheng Yan 	int slot;
290631840ae1SZheng Yan 
290731840ae1SZheng Yan 	eb = path->nodes[0];
290831840ae1SZheng Yan 	slot = path->slots[0];
290931840ae1SZheng Yan 	if (slot > 0) {
291031840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot - 1);
2911143bede5SJeff Mahoney 		BUG_ON(comp_keys(&disk_key, new_key) >= 0);
291231840ae1SZheng Yan 	}
291331840ae1SZheng Yan 	if (slot < btrfs_header_nritems(eb) - 1) {
291431840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot + 1);
2915143bede5SJeff Mahoney 		BUG_ON(comp_keys(&disk_key, new_key) <= 0);
291631840ae1SZheng Yan 	}
291731840ae1SZheng Yan 
291831840ae1SZheng Yan 	btrfs_cpu_key_to_disk(&disk_key, new_key);
291931840ae1SZheng Yan 	btrfs_set_item_key(eb, &disk_key, slot);
292031840ae1SZheng Yan 	btrfs_mark_buffer_dirty(eb);
292131840ae1SZheng Yan 	if (slot == 0)
2922d6a0a126STsutomu Itoh 		fixup_low_keys(root, path, &disk_key, 1);
292331840ae1SZheng Yan }
292431840ae1SZheng Yan 
292531840ae1SZheng Yan /*
292674123bd7SChris Mason  * try to push data from one node into the next node left in the
292779f95c82SChris Mason  * tree.
2928aa5d6bedSChris Mason  *
2929aa5d6bedSChris Mason  * returns 0 if some ptrs were pushed left, < 0 if there was some horrible
2930aa5d6bedSChris Mason  * error, and > 0 if there was no room in the left hand block.
293174123bd7SChris Mason  */
293298ed5174SChris Mason static int push_node_left(struct btrfs_trans_handle *trans,
293398ed5174SChris Mason 			  struct btrfs_root *root, struct extent_buffer *dst,
2934971a1f66SChris Mason 			  struct extent_buffer *src, int empty)
2935be0e5c09SChris Mason {
2936be0e5c09SChris Mason 	int push_items = 0;
2937bb803951SChris Mason 	int src_nritems;
2938bb803951SChris Mason 	int dst_nritems;
2939aa5d6bedSChris Mason 	int ret = 0;
2940be0e5c09SChris Mason 
29415f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
29425f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
2943123abc88SChris Mason 	push_items = BTRFS_NODEPTRS_PER_BLOCK(root) - dst_nritems;
29447bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
29457bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
294654aa1f4dSChris Mason 
2947bce4eae9SChris Mason 	if (!empty && src_nritems <= 8)
2948971a1f66SChris Mason 		return 1;
2949971a1f66SChris Mason 
2950d397712bSChris Mason 	if (push_items <= 0)
2951be0e5c09SChris Mason 		return 1;
2952be0e5c09SChris Mason 
2953bce4eae9SChris Mason 	if (empty) {
2954971a1f66SChris Mason 		push_items = min(src_nritems, push_items);
2955bce4eae9SChris Mason 		if (push_items < src_nritems) {
2956bce4eae9SChris Mason 			/* leave at least 8 pointers in the node if
2957bce4eae9SChris Mason 			 * we aren't going to empty it
2958bce4eae9SChris Mason 			 */
2959bce4eae9SChris Mason 			if (src_nritems - push_items < 8) {
2960bce4eae9SChris Mason 				if (push_items <= 8)
2961bce4eae9SChris Mason 					return 1;
2962bce4eae9SChris Mason 				push_items -= 8;
2963bce4eae9SChris Mason 			}
2964bce4eae9SChris Mason 		}
2965bce4eae9SChris Mason 	} else
2966bce4eae9SChris Mason 		push_items = min(src_nritems - 8, push_items);
296779f95c82SChris Mason 
2968f230475eSJan Schmidt 	tree_mod_log_eb_copy(root->fs_info, dst, src, dst_nritems, 0,
296990f8d62eSJan Schmidt 			     push_items);
29705f39d397SChris Mason 	copy_extent_buffer(dst, src,
29715f39d397SChris Mason 			   btrfs_node_key_ptr_offset(dst_nritems),
29725f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
2973123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
29745f39d397SChris Mason 
2975bb803951SChris Mason 	if (push_items < src_nritems) {
297657911b8bSJan Schmidt 		/*
297757911b8bSJan Schmidt 		 * don't call tree_mod_log_eb_move here, key removal was already
297857911b8bSJan Schmidt 		 * fully logged by tree_mod_log_eb_copy above.
297957911b8bSJan Schmidt 		 */
29805f39d397SChris Mason 		memmove_extent_buffer(src, btrfs_node_key_ptr_offset(0),
29815f39d397SChris Mason 				      btrfs_node_key_ptr_offset(push_items),
2982e2fa7227SChris Mason 				      (src_nritems - push_items) *
2983123abc88SChris Mason 				      sizeof(struct btrfs_key_ptr));
2984bb803951SChris Mason 	}
29855f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
29865f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
29875f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
29885f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
298931840ae1SZheng Yan 
2990bb803951SChris Mason 	return ret;
2991be0e5c09SChris Mason }
2992be0e5c09SChris Mason 
299397571fd0SChris Mason /*
299479f95c82SChris Mason  * try to push data from one node into the next node right in the
299579f95c82SChris Mason  * tree.
299679f95c82SChris Mason  *
299779f95c82SChris Mason  * returns 0 if some ptrs were pushed, < 0 if there was some horrible
299879f95c82SChris Mason  * error, and > 0 if there was no room in the right hand block.
299979f95c82SChris Mason  *
300079f95c82SChris Mason  * this will  only push up to 1/2 the contents of the left node over
300179f95c82SChris Mason  */
30025f39d397SChris Mason static int balance_node_right(struct btrfs_trans_handle *trans,
30035f39d397SChris Mason 			      struct btrfs_root *root,
30045f39d397SChris Mason 			      struct extent_buffer *dst,
30055f39d397SChris Mason 			      struct extent_buffer *src)
300679f95c82SChris Mason {
300779f95c82SChris Mason 	int push_items = 0;
300879f95c82SChris Mason 	int max_push;
300979f95c82SChris Mason 	int src_nritems;
301079f95c82SChris Mason 	int dst_nritems;
301179f95c82SChris Mason 	int ret = 0;
301279f95c82SChris Mason 
30137bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
30147bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
30157bb86316SChris Mason 
30165f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
30175f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
3018123abc88SChris Mason 	push_items = BTRFS_NODEPTRS_PER_BLOCK(root) - dst_nritems;
3019d397712bSChris Mason 	if (push_items <= 0)
302079f95c82SChris Mason 		return 1;
3021bce4eae9SChris Mason 
3022d397712bSChris Mason 	if (src_nritems < 4)
3023bce4eae9SChris Mason 		return 1;
302479f95c82SChris Mason 
302579f95c82SChris Mason 	max_push = src_nritems / 2 + 1;
302679f95c82SChris Mason 	/* don't try to empty the node */
3027d397712bSChris Mason 	if (max_push >= src_nritems)
302879f95c82SChris Mason 		return 1;
3029252c38f0SYan 
303079f95c82SChris Mason 	if (max_push < push_items)
303179f95c82SChris Mason 		push_items = max_push;
303279f95c82SChris Mason 
3033f230475eSJan Schmidt 	tree_mod_log_eb_move(root->fs_info, dst, push_items, 0, dst_nritems);
30345f39d397SChris Mason 	memmove_extent_buffer(dst, btrfs_node_key_ptr_offset(push_items),
30355f39d397SChris Mason 				      btrfs_node_key_ptr_offset(0),
30365f39d397SChris Mason 				      (dst_nritems) *
30375f39d397SChris Mason 				      sizeof(struct btrfs_key_ptr));
3038d6025579SChris Mason 
3039f230475eSJan Schmidt 	tree_mod_log_eb_copy(root->fs_info, dst, src, 0,
304090f8d62eSJan Schmidt 			     src_nritems - push_items, push_items);
30415f39d397SChris Mason 	copy_extent_buffer(dst, src,
30425f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
30435f39d397SChris Mason 			   btrfs_node_key_ptr_offset(src_nritems - push_items),
3044123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
304579f95c82SChris Mason 
30465f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
30475f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
304879f95c82SChris Mason 
30495f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
30505f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
305131840ae1SZheng Yan 
305279f95c82SChris Mason 	return ret;
305379f95c82SChris Mason }
305479f95c82SChris Mason 
305579f95c82SChris Mason /*
305697571fd0SChris Mason  * helper function to insert a new root level in the tree.
305797571fd0SChris Mason  * A new node is allocated, and a single item is inserted to
305897571fd0SChris Mason  * point to the existing root
3059aa5d6bedSChris Mason  *
3060aa5d6bedSChris Mason  * returns zero on success or < 0 on failure.
306197571fd0SChris Mason  */
3062d397712bSChris Mason static noinline int insert_new_root(struct btrfs_trans_handle *trans,
30635f39d397SChris Mason 			   struct btrfs_root *root,
3064fdd99c72SLiu Bo 			   struct btrfs_path *path, int level)
306574123bd7SChris Mason {
30667bb86316SChris Mason 	u64 lower_gen;
30675f39d397SChris Mason 	struct extent_buffer *lower;
30685f39d397SChris Mason 	struct extent_buffer *c;
3069925baeddSChris Mason 	struct extent_buffer *old;
30705f39d397SChris Mason 	struct btrfs_disk_key lower_key;
30715c680ed6SChris Mason 
30725c680ed6SChris Mason 	BUG_ON(path->nodes[level]);
30735c680ed6SChris Mason 	BUG_ON(path->nodes[level-1] != root->node);
30745c680ed6SChris Mason 
30757bb86316SChris Mason 	lower = path->nodes[level-1];
30767bb86316SChris Mason 	if (level == 1)
30777bb86316SChris Mason 		btrfs_item_key(lower, &lower_key, 0);
30787bb86316SChris Mason 	else
30797bb86316SChris Mason 		btrfs_node_key(lower, &lower_key, 0);
30807bb86316SChris Mason 
308131840ae1SZheng Yan 	c = btrfs_alloc_free_block(trans, root, root->nodesize, 0,
30825d4f98a2SYan Zheng 				   root->root_key.objectid, &lower_key,
30835581a51aSJan Schmidt 				   level, root->node->start, 0);
30845f39d397SChris Mason 	if (IS_ERR(c))
30855f39d397SChris Mason 		return PTR_ERR(c);
3086925baeddSChris Mason 
3087f0486c68SYan, Zheng 	root_add_used(root, root->nodesize);
3088f0486c68SYan, Zheng 
30895d4f98a2SYan Zheng 	memset_extent_buffer(c, 0, 0, sizeof(struct btrfs_header));
30905f39d397SChris Mason 	btrfs_set_header_nritems(c, 1);
30915f39d397SChris Mason 	btrfs_set_header_level(c, level);
3092db94535dSChris Mason 	btrfs_set_header_bytenr(c, c->start);
30935f39d397SChris Mason 	btrfs_set_header_generation(c, trans->transid);
30945d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(c, BTRFS_MIXED_BACKREF_REV);
30955f39d397SChris Mason 	btrfs_set_header_owner(c, root->root_key.objectid);
3096d5719762SChris Mason 
30975f39d397SChris Mason 	write_extent_buffer(c, root->fs_info->fsid,
30985f39d397SChris Mason 			    (unsigned long)btrfs_header_fsid(c),
30995f39d397SChris Mason 			    BTRFS_FSID_SIZE);
3100e17cade2SChris Mason 
3101e17cade2SChris Mason 	write_extent_buffer(c, root->fs_info->chunk_tree_uuid,
3102e17cade2SChris Mason 			    (unsigned long)btrfs_header_chunk_tree_uuid(c),
3103e17cade2SChris Mason 			    BTRFS_UUID_SIZE);
3104e17cade2SChris Mason 
31055f39d397SChris Mason 	btrfs_set_node_key(c, &lower_key, 0);
3106db94535dSChris Mason 	btrfs_set_node_blockptr(c, 0, lower->start);
31077bb86316SChris Mason 	lower_gen = btrfs_header_generation(lower);
310831840ae1SZheng Yan 	WARN_ON(lower_gen != trans->transid);
31097bb86316SChris Mason 
31107bb86316SChris Mason 	btrfs_set_node_ptr_generation(c, 0, lower_gen);
31115f39d397SChris Mason 
31125f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
3113d5719762SChris Mason 
3114925baeddSChris Mason 	old = root->node;
3115fdd99c72SLiu Bo 	tree_mod_log_set_root_pointer(root, c, 0);
3116240f62c8SChris Mason 	rcu_assign_pointer(root->node, c);
3117925baeddSChris Mason 
3118925baeddSChris Mason 	/* the super has an extra ref to root->node */
3119925baeddSChris Mason 	free_extent_buffer(old);
3120925baeddSChris Mason 
31210b86a832SChris Mason 	add_root_to_dirty_list(root);
31225f39d397SChris Mason 	extent_buffer_get(c);
31235f39d397SChris Mason 	path->nodes[level] = c;
3124bd681513SChris Mason 	path->locks[level] = BTRFS_WRITE_LOCK;
312574123bd7SChris Mason 	path->slots[level] = 0;
312674123bd7SChris Mason 	return 0;
312774123bd7SChris Mason }
31285c680ed6SChris Mason 
31295c680ed6SChris Mason /*
31305c680ed6SChris Mason  * worker function to insert a single pointer in a node.
31315c680ed6SChris Mason  * the node should have enough room for the pointer already
313297571fd0SChris Mason  *
31335c680ed6SChris Mason  * slot and level indicate where you want the key to go, and
31345c680ed6SChris Mason  * blocknr is the block the key points to.
31355c680ed6SChris Mason  */
3136143bede5SJeff Mahoney static void insert_ptr(struct btrfs_trans_handle *trans,
3137143bede5SJeff Mahoney 		       struct btrfs_root *root, struct btrfs_path *path,
3138143bede5SJeff Mahoney 		       struct btrfs_disk_key *key, u64 bytenr,
3139c3e06965SJan Schmidt 		       int slot, int level)
31405c680ed6SChris Mason {
31415f39d397SChris Mason 	struct extent_buffer *lower;
31425c680ed6SChris Mason 	int nritems;
3143f3ea38daSJan Schmidt 	int ret;
31445c680ed6SChris Mason 
31455c680ed6SChris Mason 	BUG_ON(!path->nodes[level]);
3146f0486c68SYan, Zheng 	btrfs_assert_tree_locked(path->nodes[level]);
31475f39d397SChris Mason 	lower = path->nodes[level];
31485f39d397SChris Mason 	nritems = btrfs_header_nritems(lower);
3149c293498bSStoyan Gaydarov 	BUG_ON(slot > nritems);
3150143bede5SJeff Mahoney 	BUG_ON(nritems == BTRFS_NODEPTRS_PER_BLOCK(root));
315174123bd7SChris Mason 	if (slot != nritems) {
3152c3e06965SJan Schmidt 		if (level)
3153f3ea38daSJan Schmidt 			tree_mod_log_eb_move(root->fs_info, lower, slot + 1,
3154f3ea38daSJan Schmidt 					     slot, nritems - slot);
31555f39d397SChris Mason 		memmove_extent_buffer(lower,
31565f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot + 1),
31575f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot),
3158123abc88SChris Mason 			      (nritems - slot) * sizeof(struct btrfs_key_ptr));
315974123bd7SChris Mason 	}
3160c3e06965SJan Schmidt 	if (level) {
3161f3ea38daSJan Schmidt 		ret = tree_mod_log_insert_key(root->fs_info, lower, slot,
3162*c8cc6341SJosef Bacik 					      MOD_LOG_KEY_ADD, GFP_NOFS);
3163f3ea38daSJan Schmidt 		BUG_ON(ret < 0);
3164f3ea38daSJan Schmidt 	}
31655f39d397SChris Mason 	btrfs_set_node_key(lower, key, slot);
3166db94535dSChris Mason 	btrfs_set_node_blockptr(lower, slot, bytenr);
316774493f7aSChris Mason 	WARN_ON(trans->transid == 0);
316874493f7aSChris Mason 	btrfs_set_node_ptr_generation(lower, slot, trans->transid);
31695f39d397SChris Mason 	btrfs_set_header_nritems(lower, nritems + 1);
31705f39d397SChris Mason 	btrfs_mark_buffer_dirty(lower);
317174123bd7SChris Mason }
317274123bd7SChris Mason 
317397571fd0SChris Mason /*
317497571fd0SChris Mason  * split the node at the specified level in path in two.
317597571fd0SChris Mason  * The path is corrected to point to the appropriate node after the split
317697571fd0SChris Mason  *
317797571fd0SChris Mason  * Before splitting this tries to make some room in the node by pushing
317897571fd0SChris Mason  * left and right, if either one works, it returns right away.
3179aa5d6bedSChris Mason  *
3180aa5d6bedSChris Mason  * returns 0 on success and < 0 on failure
318197571fd0SChris Mason  */
3182e02119d5SChris Mason static noinline int split_node(struct btrfs_trans_handle *trans,
3183e02119d5SChris Mason 			       struct btrfs_root *root,
3184e02119d5SChris Mason 			       struct btrfs_path *path, int level)
3185be0e5c09SChris Mason {
31865f39d397SChris Mason 	struct extent_buffer *c;
31875f39d397SChris Mason 	struct extent_buffer *split;
31885f39d397SChris Mason 	struct btrfs_disk_key disk_key;
3189be0e5c09SChris Mason 	int mid;
31905c680ed6SChris Mason 	int ret;
31917518a238SChris Mason 	u32 c_nritems;
3192be0e5c09SChris Mason 
31935f39d397SChris Mason 	c = path->nodes[level];
31947bb86316SChris Mason 	WARN_ON(btrfs_header_generation(c) != trans->transid);
31955f39d397SChris Mason 	if (c == root->node) {
3196d9abbf1cSJan Schmidt 		/*
319790f8d62eSJan Schmidt 		 * trying to split the root, lets make a new one
319890f8d62eSJan Schmidt 		 *
3199fdd99c72SLiu Bo 		 * tree mod log: We don't log_removal old root in
320090f8d62eSJan Schmidt 		 * insert_new_root, because that root buffer will be kept as a
320190f8d62eSJan Schmidt 		 * normal node. We are going to log removal of half of the
320290f8d62eSJan Schmidt 		 * elements below with tree_mod_log_eb_copy. We're holding a
320390f8d62eSJan Schmidt 		 * tree lock on the buffer, which is why we cannot race with
320490f8d62eSJan Schmidt 		 * other tree_mod_log users.
3205d9abbf1cSJan Schmidt 		 */
3206fdd99c72SLiu Bo 		ret = insert_new_root(trans, root, path, level + 1);
32075c680ed6SChris Mason 		if (ret)
32085c680ed6SChris Mason 			return ret;
3209b3612421SChris Mason 	} else {
3210e66f709bSChris Mason 		ret = push_nodes_for_insert(trans, root, path, level);
32115f39d397SChris Mason 		c = path->nodes[level];
32125f39d397SChris Mason 		if (!ret && btrfs_header_nritems(c) <
3213c448acf0SChris Mason 		    BTRFS_NODEPTRS_PER_BLOCK(root) - 3)
3214e66f709bSChris Mason 			return 0;
321554aa1f4dSChris Mason 		if (ret < 0)
321654aa1f4dSChris Mason 			return ret;
32175c680ed6SChris Mason 	}
3218e66f709bSChris Mason 
32195f39d397SChris Mason 	c_nritems = btrfs_header_nritems(c);
32205d4f98a2SYan Zheng 	mid = (c_nritems + 1) / 2;
32215d4f98a2SYan Zheng 	btrfs_node_key(c, &disk_key, mid);
32227bb86316SChris Mason 
32235d4f98a2SYan Zheng 	split = btrfs_alloc_free_block(trans, root, root->nodesize, 0,
32247bb86316SChris Mason 					root->root_key.objectid,
32255581a51aSJan Schmidt 					&disk_key, level, c->start, 0);
32265f39d397SChris Mason 	if (IS_ERR(split))
32275f39d397SChris Mason 		return PTR_ERR(split);
322854aa1f4dSChris Mason 
3229f0486c68SYan, Zheng 	root_add_used(root, root->nodesize);
3230f0486c68SYan, Zheng 
32315d4f98a2SYan Zheng 	memset_extent_buffer(split, 0, 0, sizeof(struct btrfs_header));
32325f39d397SChris Mason 	btrfs_set_header_level(split, btrfs_header_level(c));
3233db94535dSChris Mason 	btrfs_set_header_bytenr(split, split->start);
32345f39d397SChris Mason 	btrfs_set_header_generation(split, trans->transid);
32355d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(split, BTRFS_MIXED_BACKREF_REV);
32365f39d397SChris Mason 	btrfs_set_header_owner(split, root->root_key.objectid);
32375f39d397SChris Mason 	write_extent_buffer(split, root->fs_info->fsid,
32385f39d397SChris Mason 			    (unsigned long)btrfs_header_fsid(split),
32395f39d397SChris Mason 			    BTRFS_FSID_SIZE);
3240e17cade2SChris Mason 	write_extent_buffer(split, root->fs_info->chunk_tree_uuid,
3241e17cade2SChris Mason 			    (unsigned long)btrfs_header_chunk_tree_uuid(split),
3242e17cade2SChris Mason 			    BTRFS_UUID_SIZE);
32435f39d397SChris Mason 
324490f8d62eSJan Schmidt 	tree_mod_log_eb_copy(root->fs_info, split, c, 0, mid, c_nritems - mid);
32455f39d397SChris Mason 	copy_extent_buffer(split, c,
32465f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
32475f39d397SChris Mason 			   btrfs_node_key_ptr_offset(mid),
3248123abc88SChris Mason 			   (c_nritems - mid) * sizeof(struct btrfs_key_ptr));
32495f39d397SChris Mason 	btrfs_set_header_nritems(split, c_nritems - mid);
32505f39d397SChris Mason 	btrfs_set_header_nritems(c, mid);
3251aa5d6bedSChris Mason 	ret = 0;
3252aa5d6bedSChris Mason 
32535f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
32545f39d397SChris Mason 	btrfs_mark_buffer_dirty(split);
32555f39d397SChris Mason 
3256143bede5SJeff Mahoney 	insert_ptr(trans, root, path, &disk_key, split->start,
3257c3e06965SJan Schmidt 		   path->slots[level + 1] + 1, level + 1);
3258aa5d6bedSChris Mason 
32595de08d7dSChris Mason 	if (path->slots[level] >= mid) {
32605c680ed6SChris Mason 		path->slots[level] -= mid;
3261925baeddSChris Mason 		btrfs_tree_unlock(c);
32625f39d397SChris Mason 		free_extent_buffer(c);
32635f39d397SChris Mason 		path->nodes[level] = split;
32645c680ed6SChris Mason 		path->slots[level + 1] += 1;
3265eb60ceacSChris Mason 	} else {
3266925baeddSChris Mason 		btrfs_tree_unlock(split);
32675f39d397SChris Mason 		free_extent_buffer(split);
3268be0e5c09SChris Mason 	}
3269aa5d6bedSChris Mason 	return ret;
3270be0e5c09SChris Mason }
3271be0e5c09SChris Mason 
327274123bd7SChris Mason /*
327374123bd7SChris Mason  * how many bytes are required to store the items in a leaf.  start
327474123bd7SChris Mason  * and nr indicate which items in the leaf to check.  This totals up the
327574123bd7SChris Mason  * space used both by the item structs and the item data
327674123bd7SChris Mason  */
32775f39d397SChris Mason static int leaf_space_used(struct extent_buffer *l, int start, int nr)
3278be0e5c09SChris Mason {
327941be1f3bSJosef Bacik 	struct btrfs_item *start_item;
328041be1f3bSJosef Bacik 	struct btrfs_item *end_item;
328141be1f3bSJosef Bacik 	struct btrfs_map_token token;
3282be0e5c09SChris Mason 	int data_len;
32835f39d397SChris Mason 	int nritems = btrfs_header_nritems(l);
3284d4dbff95SChris Mason 	int end = min(nritems, start + nr) - 1;
3285be0e5c09SChris Mason 
3286be0e5c09SChris Mason 	if (!nr)
3287be0e5c09SChris Mason 		return 0;
328841be1f3bSJosef Bacik 	btrfs_init_map_token(&token);
328941be1f3bSJosef Bacik 	start_item = btrfs_item_nr(l, start);
329041be1f3bSJosef Bacik 	end_item = btrfs_item_nr(l, end);
329141be1f3bSJosef Bacik 	data_len = btrfs_token_item_offset(l, start_item, &token) +
329241be1f3bSJosef Bacik 		btrfs_token_item_size(l, start_item, &token);
329341be1f3bSJosef Bacik 	data_len = data_len - btrfs_token_item_offset(l, end_item, &token);
32940783fcfcSChris Mason 	data_len += sizeof(struct btrfs_item) * nr;
3295d4dbff95SChris Mason 	WARN_ON(data_len < 0);
3296be0e5c09SChris Mason 	return data_len;
3297be0e5c09SChris Mason }
3298be0e5c09SChris Mason 
329974123bd7SChris Mason /*
3300d4dbff95SChris Mason  * The space between the end of the leaf items and
3301d4dbff95SChris Mason  * the start of the leaf data.  IOW, how much room
3302d4dbff95SChris Mason  * the leaf has left for both items and data
3303d4dbff95SChris Mason  */
3304d397712bSChris Mason noinline int btrfs_leaf_free_space(struct btrfs_root *root,
3305e02119d5SChris Mason 				   struct extent_buffer *leaf)
3306d4dbff95SChris Mason {
33075f39d397SChris Mason 	int nritems = btrfs_header_nritems(leaf);
33085f39d397SChris Mason 	int ret;
33095f39d397SChris Mason 	ret = BTRFS_LEAF_DATA_SIZE(root) - leaf_space_used(leaf, 0, nritems);
33105f39d397SChris Mason 	if (ret < 0) {
3311d397712bSChris Mason 		printk(KERN_CRIT "leaf free space ret %d, leaf data size %lu, "
3312d397712bSChris Mason 		       "used %d nritems %d\n",
3313ae2f5411SJens Axboe 		       ret, (unsigned long) BTRFS_LEAF_DATA_SIZE(root),
33145f39d397SChris Mason 		       leaf_space_used(leaf, 0, nritems), nritems);
33155f39d397SChris Mason 	}
33165f39d397SChris Mason 	return ret;
3317d4dbff95SChris Mason }
3318d4dbff95SChris Mason 
331999d8f83cSChris Mason /*
332099d8f83cSChris Mason  * min slot controls the lowest index we're willing to push to the
332199d8f83cSChris Mason  * right.  We'll push up to and including min_slot, but no lower
332299d8f83cSChris Mason  */
332344871b1bSChris Mason static noinline int __push_leaf_right(struct btrfs_trans_handle *trans,
332444871b1bSChris Mason 				      struct btrfs_root *root,
332544871b1bSChris Mason 				      struct btrfs_path *path,
332644871b1bSChris Mason 				      int data_size, int empty,
332744871b1bSChris Mason 				      struct extent_buffer *right,
332899d8f83cSChris Mason 				      int free_space, u32 left_nritems,
332999d8f83cSChris Mason 				      u32 min_slot)
333000ec4c51SChris Mason {
33315f39d397SChris Mason 	struct extent_buffer *left = path->nodes[0];
333244871b1bSChris Mason 	struct extent_buffer *upper = path->nodes[1];
3333cfed81a0SChris Mason 	struct btrfs_map_token token;
33345f39d397SChris Mason 	struct btrfs_disk_key disk_key;
333500ec4c51SChris Mason 	int slot;
333634a38218SChris Mason 	u32 i;
333700ec4c51SChris Mason 	int push_space = 0;
333800ec4c51SChris Mason 	int push_items = 0;
33390783fcfcSChris Mason 	struct btrfs_item *item;
334034a38218SChris Mason 	u32 nr;
33417518a238SChris Mason 	u32 right_nritems;
33425f39d397SChris Mason 	u32 data_end;
3343db94535dSChris Mason 	u32 this_item_size;
334400ec4c51SChris Mason 
3345cfed81a0SChris Mason 	btrfs_init_map_token(&token);
3346cfed81a0SChris Mason 
334734a38218SChris Mason 	if (empty)
334834a38218SChris Mason 		nr = 0;
334934a38218SChris Mason 	else
335099d8f83cSChris Mason 		nr = max_t(u32, 1, min_slot);
335134a38218SChris Mason 
335231840ae1SZheng Yan 	if (path->slots[0] >= left_nritems)
335387b29b20SYan Zheng 		push_space += data_size;
335431840ae1SZheng Yan 
335544871b1bSChris Mason 	slot = path->slots[1];
335634a38218SChris Mason 	i = left_nritems - 1;
335734a38218SChris Mason 	while (i >= nr) {
33585f39d397SChris Mason 		item = btrfs_item_nr(left, i);
3359db94535dSChris Mason 
336031840ae1SZheng Yan 		if (!empty && push_items > 0) {
336131840ae1SZheng Yan 			if (path->slots[0] > i)
336231840ae1SZheng Yan 				break;
336331840ae1SZheng Yan 			if (path->slots[0] == i) {
336431840ae1SZheng Yan 				int space = btrfs_leaf_free_space(root, left);
336531840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
336631840ae1SZheng Yan 					break;
336731840ae1SZheng Yan 			}
336831840ae1SZheng Yan 		}
336931840ae1SZheng Yan 
337000ec4c51SChris Mason 		if (path->slots[0] == i)
337187b29b20SYan Zheng 			push_space += data_size;
3372db94535dSChris Mason 
3373db94535dSChris Mason 		this_item_size = btrfs_item_size(left, item);
3374db94535dSChris Mason 		if (this_item_size + sizeof(*item) + push_space > free_space)
337500ec4c51SChris Mason 			break;
337631840ae1SZheng Yan 
337700ec4c51SChris Mason 		push_items++;
3378db94535dSChris Mason 		push_space += this_item_size + sizeof(*item);
337934a38218SChris Mason 		if (i == 0)
338034a38218SChris Mason 			break;
338134a38218SChris Mason 		i--;
3382db94535dSChris Mason 	}
33835f39d397SChris Mason 
3384925baeddSChris Mason 	if (push_items == 0)
3385925baeddSChris Mason 		goto out_unlock;
33865f39d397SChris Mason 
33876c1500f2SJulia Lawall 	WARN_ON(!empty && push_items == left_nritems);
33885f39d397SChris Mason 
338900ec4c51SChris Mason 	/* push left to right */
33905f39d397SChris Mason 	right_nritems = btrfs_header_nritems(right);
339134a38218SChris Mason 
33925f39d397SChris Mason 	push_space = btrfs_item_end_nr(left, left_nritems - push_items);
3393123abc88SChris Mason 	push_space -= leaf_data_end(root, left);
33945f39d397SChris Mason 
339500ec4c51SChris Mason 	/* make room in the right data area */
33965f39d397SChris Mason 	data_end = leaf_data_end(root, right);
33975f39d397SChris Mason 	memmove_extent_buffer(right,
33985f39d397SChris Mason 			      btrfs_leaf_data(right) + data_end - push_space,
33995f39d397SChris Mason 			      btrfs_leaf_data(right) + data_end,
34005f39d397SChris Mason 			      BTRFS_LEAF_DATA_SIZE(root) - data_end);
34015f39d397SChris Mason 
340200ec4c51SChris Mason 	/* copy from the left data area */
34035f39d397SChris Mason 	copy_extent_buffer(right, left, btrfs_leaf_data(right) +
3404d6025579SChris Mason 		     BTRFS_LEAF_DATA_SIZE(root) - push_space,
3405d6025579SChris Mason 		     btrfs_leaf_data(left) + leaf_data_end(root, left),
3406d6025579SChris Mason 		     push_space);
34075f39d397SChris Mason 
34085f39d397SChris Mason 	memmove_extent_buffer(right, btrfs_item_nr_offset(push_items),
34095f39d397SChris Mason 			      btrfs_item_nr_offset(0),
34100783fcfcSChris Mason 			      right_nritems * sizeof(struct btrfs_item));
34115f39d397SChris Mason 
341200ec4c51SChris Mason 	/* copy the items from left to right */
34135f39d397SChris Mason 	copy_extent_buffer(right, left, btrfs_item_nr_offset(0),
34145f39d397SChris Mason 		   btrfs_item_nr_offset(left_nritems - push_items),
34150783fcfcSChris Mason 		   push_items * sizeof(struct btrfs_item));
341600ec4c51SChris Mason 
341700ec4c51SChris Mason 	/* update the item pointers */
34187518a238SChris Mason 	right_nritems += push_items;
34195f39d397SChris Mason 	btrfs_set_header_nritems(right, right_nritems);
3420123abc88SChris Mason 	push_space = BTRFS_LEAF_DATA_SIZE(root);
34217518a238SChris Mason 	for (i = 0; i < right_nritems; i++) {
34225f39d397SChris Mason 		item = btrfs_item_nr(right, i);
3423cfed81a0SChris Mason 		push_space -= btrfs_token_item_size(right, item, &token);
3424cfed81a0SChris Mason 		btrfs_set_token_item_offset(right, item, push_space, &token);
3425db94535dSChris Mason 	}
3426db94535dSChris Mason 
34277518a238SChris Mason 	left_nritems -= push_items;
34285f39d397SChris Mason 	btrfs_set_header_nritems(left, left_nritems);
342900ec4c51SChris Mason 
343034a38218SChris Mason 	if (left_nritems)
34315f39d397SChris Mason 		btrfs_mark_buffer_dirty(left);
3432f0486c68SYan, Zheng 	else
3433f0486c68SYan, Zheng 		clean_tree_block(trans, root, left);
3434f0486c68SYan, Zheng 
34355f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
3436a429e513SChris Mason 
34375f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
34385f39d397SChris Mason 	btrfs_set_node_key(upper, &disk_key, slot + 1);
3439d6025579SChris Mason 	btrfs_mark_buffer_dirty(upper);
344002217ed2SChris Mason 
344100ec4c51SChris Mason 	/* then fixup the leaf pointer in the path */
34427518a238SChris Mason 	if (path->slots[0] >= left_nritems) {
34437518a238SChris Mason 		path->slots[0] -= left_nritems;
3444925baeddSChris Mason 		if (btrfs_header_nritems(path->nodes[0]) == 0)
3445925baeddSChris Mason 			clean_tree_block(trans, root, path->nodes[0]);
3446925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
34475f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
34485f39d397SChris Mason 		path->nodes[0] = right;
344900ec4c51SChris Mason 		path->slots[1] += 1;
345000ec4c51SChris Mason 	} else {
3451925baeddSChris Mason 		btrfs_tree_unlock(right);
34525f39d397SChris Mason 		free_extent_buffer(right);
345300ec4c51SChris Mason 	}
345400ec4c51SChris Mason 	return 0;
3455925baeddSChris Mason 
3456925baeddSChris Mason out_unlock:
3457925baeddSChris Mason 	btrfs_tree_unlock(right);
3458925baeddSChris Mason 	free_extent_buffer(right);
3459925baeddSChris Mason 	return 1;
346000ec4c51SChris Mason }
3461925baeddSChris Mason 
346200ec4c51SChris Mason /*
346344871b1bSChris Mason  * push some data in the path leaf to the right, trying to free up at
346474123bd7SChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
346544871b1bSChris Mason  *
346644871b1bSChris Mason  * returns 1 if the push failed because the other node didn't have enough
346744871b1bSChris Mason  * room, 0 if everything worked out and < 0 if there were major errors.
346899d8f83cSChris Mason  *
346999d8f83cSChris Mason  * this will push starting from min_slot to the end of the leaf.  It won't
347099d8f83cSChris Mason  * push any slot lower than min_slot
347174123bd7SChris Mason  */
347244871b1bSChris Mason static int push_leaf_right(struct btrfs_trans_handle *trans, struct btrfs_root
347399d8f83cSChris Mason 			   *root, struct btrfs_path *path,
347499d8f83cSChris Mason 			   int min_data_size, int data_size,
347599d8f83cSChris Mason 			   int empty, u32 min_slot)
3476be0e5c09SChris Mason {
347744871b1bSChris Mason 	struct extent_buffer *left = path->nodes[0];
347844871b1bSChris Mason 	struct extent_buffer *right;
347944871b1bSChris Mason 	struct extent_buffer *upper;
348044871b1bSChris Mason 	int slot;
348144871b1bSChris Mason 	int free_space;
348244871b1bSChris Mason 	u32 left_nritems;
348344871b1bSChris Mason 	int ret;
348444871b1bSChris Mason 
348544871b1bSChris Mason 	if (!path->nodes[1])
348644871b1bSChris Mason 		return 1;
348744871b1bSChris Mason 
348844871b1bSChris Mason 	slot = path->slots[1];
348944871b1bSChris Mason 	upper = path->nodes[1];
349044871b1bSChris Mason 	if (slot >= btrfs_header_nritems(upper) - 1)
349144871b1bSChris Mason 		return 1;
349244871b1bSChris Mason 
349344871b1bSChris Mason 	btrfs_assert_tree_locked(path->nodes[1]);
349444871b1bSChris Mason 
349544871b1bSChris Mason 	right = read_node_slot(root, upper, slot + 1);
349691ca338dSTsutomu Itoh 	if (right == NULL)
349791ca338dSTsutomu Itoh 		return 1;
349891ca338dSTsutomu Itoh 
349944871b1bSChris Mason 	btrfs_tree_lock(right);
350044871b1bSChris Mason 	btrfs_set_lock_blocking(right);
350144871b1bSChris Mason 
350244871b1bSChris Mason 	free_space = btrfs_leaf_free_space(root, right);
350344871b1bSChris Mason 	if (free_space < data_size)
350444871b1bSChris Mason 		goto out_unlock;
350544871b1bSChris Mason 
350644871b1bSChris Mason 	/* cow and double check */
350744871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, right, upper,
350844871b1bSChris Mason 			      slot + 1, &right);
350944871b1bSChris Mason 	if (ret)
351044871b1bSChris Mason 		goto out_unlock;
351144871b1bSChris Mason 
351244871b1bSChris Mason 	free_space = btrfs_leaf_free_space(root, right);
351344871b1bSChris Mason 	if (free_space < data_size)
351444871b1bSChris Mason 		goto out_unlock;
351544871b1bSChris Mason 
351644871b1bSChris Mason 	left_nritems = btrfs_header_nritems(left);
351744871b1bSChris Mason 	if (left_nritems == 0)
351844871b1bSChris Mason 		goto out_unlock;
351944871b1bSChris Mason 
352099d8f83cSChris Mason 	return __push_leaf_right(trans, root, path, min_data_size, empty,
352199d8f83cSChris Mason 				right, free_space, left_nritems, min_slot);
352244871b1bSChris Mason out_unlock:
352344871b1bSChris Mason 	btrfs_tree_unlock(right);
352444871b1bSChris Mason 	free_extent_buffer(right);
352544871b1bSChris Mason 	return 1;
352644871b1bSChris Mason }
352744871b1bSChris Mason 
352844871b1bSChris Mason /*
352944871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
353044871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
353199d8f83cSChris Mason  *
353299d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
353399d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us do all the
353499d8f83cSChris Mason  * items
353544871b1bSChris Mason  */
353644871b1bSChris Mason static noinline int __push_leaf_left(struct btrfs_trans_handle *trans,
353744871b1bSChris Mason 				     struct btrfs_root *root,
353844871b1bSChris Mason 				     struct btrfs_path *path, int data_size,
353944871b1bSChris Mason 				     int empty, struct extent_buffer *left,
354099d8f83cSChris Mason 				     int free_space, u32 right_nritems,
354199d8f83cSChris Mason 				     u32 max_slot)
354244871b1bSChris Mason {
35435f39d397SChris Mason 	struct btrfs_disk_key disk_key;
35445f39d397SChris Mason 	struct extent_buffer *right = path->nodes[0];
3545be0e5c09SChris Mason 	int i;
3546be0e5c09SChris Mason 	int push_space = 0;
3547be0e5c09SChris Mason 	int push_items = 0;
35480783fcfcSChris Mason 	struct btrfs_item *item;
35497518a238SChris Mason 	u32 old_left_nritems;
355034a38218SChris Mason 	u32 nr;
3551aa5d6bedSChris Mason 	int ret = 0;
3552db94535dSChris Mason 	u32 this_item_size;
3553db94535dSChris Mason 	u32 old_left_item_size;
3554cfed81a0SChris Mason 	struct btrfs_map_token token;
3555cfed81a0SChris Mason 
3556cfed81a0SChris Mason 	btrfs_init_map_token(&token);
3557be0e5c09SChris Mason 
355834a38218SChris Mason 	if (empty)
355999d8f83cSChris Mason 		nr = min(right_nritems, max_slot);
356034a38218SChris Mason 	else
356199d8f83cSChris Mason 		nr = min(right_nritems - 1, max_slot);
356234a38218SChris Mason 
356334a38218SChris Mason 	for (i = 0; i < nr; i++) {
35645f39d397SChris Mason 		item = btrfs_item_nr(right, i);
3565db94535dSChris Mason 
356631840ae1SZheng Yan 		if (!empty && push_items > 0) {
356731840ae1SZheng Yan 			if (path->slots[0] < i)
356831840ae1SZheng Yan 				break;
356931840ae1SZheng Yan 			if (path->slots[0] == i) {
357031840ae1SZheng Yan 				int space = btrfs_leaf_free_space(root, right);
357131840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
357231840ae1SZheng Yan 					break;
357331840ae1SZheng Yan 			}
357431840ae1SZheng Yan 		}
357531840ae1SZheng Yan 
3576be0e5c09SChris Mason 		if (path->slots[0] == i)
357787b29b20SYan Zheng 			push_space += data_size;
3578db94535dSChris Mason 
3579db94535dSChris Mason 		this_item_size = btrfs_item_size(right, item);
3580db94535dSChris Mason 		if (this_item_size + sizeof(*item) + push_space > free_space)
3581be0e5c09SChris Mason 			break;
3582db94535dSChris Mason 
3583be0e5c09SChris Mason 		push_items++;
3584db94535dSChris Mason 		push_space += this_item_size + sizeof(*item);
3585be0e5c09SChris Mason 	}
3586db94535dSChris Mason 
3587be0e5c09SChris Mason 	if (push_items == 0) {
3588925baeddSChris Mason 		ret = 1;
3589925baeddSChris Mason 		goto out;
3590be0e5c09SChris Mason 	}
359134a38218SChris Mason 	if (!empty && push_items == btrfs_header_nritems(right))
3592a429e513SChris Mason 		WARN_ON(1);
35935f39d397SChris Mason 
3594be0e5c09SChris Mason 	/* push data from right to left */
35955f39d397SChris Mason 	copy_extent_buffer(left, right,
35965f39d397SChris Mason 			   btrfs_item_nr_offset(btrfs_header_nritems(left)),
35975f39d397SChris Mason 			   btrfs_item_nr_offset(0),
35985f39d397SChris Mason 			   push_items * sizeof(struct btrfs_item));
35995f39d397SChris Mason 
3600123abc88SChris Mason 	push_space = BTRFS_LEAF_DATA_SIZE(root) -
36015f39d397SChris Mason 		     btrfs_item_offset_nr(right, push_items - 1);
36025f39d397SChris Mason 
36035f39d397SChris Mason 	copy_extent_buffer(left, right, btrfs_leaf_data(left) +
3604d6025579SChris Mason 		     leaf_data_end(root, left) - push_space,
3605123abc88SChris Mason 		     btrfs_leaf_data(right) +
36065f39d397SChris Mason 		     btrfs_item_offset_nr(right, push_items - 1),
3607be0e5c09SChris Mason 		     push_space);
36085f39d397SChris Mason 	old_left_nritems = btrfs_header_nritems(left);
360987b29b20SYan Zheng 	BUG_ON(old_left_nritems <= 0);
3610eb60ceacSChris Mason 
3611db94535dSChris Mason 	old_left_item_size = btrfs_item_offset_nr(left, old_left_nritems - 1);
3612be0e5c09SChris Mason 	for (i = old_left_nritems; i < old_left_nritems + push_items; i++) {
36135f39d397SChris Mason 		u32 ioff;
3614db94535dSChris Mason 
36155f39d397SChris Mason 		item = btrfs_item_nr(left, i);
3616db94535dSChris Mason 
3617cfed81a0SChris Mason 		ioff = btrfs_token_item_offset(left, item, &token);
3618cfed81a0SChris Mason 		btrfs_set_token_item_offset(left, item,
3619cfed81a0SChris Mason 		      ioff - (BTRFS_LEAF_DATA_SIZE(root) - old_left_item_size),
3620cfed81a0SChris Mason 		      &token);
3621be0e5c09SChris Mason 	}
36225f39d397SChris Mason 	btrfs_set_header_nritems(left, old_left_nritems + push_items);
3623be0e5c09SChris Mason 
3624be0e5c09SChris Mason 	/* fixup right node */
362531b1a2bdSJulia Lawall 	if (push_items > right_nritems)
362631b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "push items %d nr %u\n", push_items,
3627d397712bSChris Mason 		       right_nritems);
362834a38218SChris Mason 
362934a38218SChris Mason 	if (push_items < right_nritems) {
36305f39d397SChris Mason 		push_space = btrfs_item_offset_nr(right, push_items - 1) -
3631123abc88SChris Mason 						  leaf_data_end(root, right);
36325f39d397SChris Mason 		memmove_extent_buffer(right, btrfs_leaf_data(right) +
3633d6025579SChris Mason 				      BTRFS_LEAF_DATA_SIZE(root) - push_space,
3634d6025579SChris Mason 				      btrfs_leaf_data(right) +
3635123abc88SChris Mason 				      leaf_data_end(root, right), push_space);
36365f39d397SChris Mason 
36375f39d397SChris Mason 		memmove_extent_buffer(right, btrfs_item_nr_offset(0),
36385f39d397SChris Mason 			      btrfs_item_nr_offset(push_items),
36395f39d397SChris Mason 			     (btrfs_header_nritems(right) - push_items) *
36400783fcfcSChris Mason 			     sizeof(struct btrfs_item));
364134a38218SChris Mason 	}
3642eef1c494SYan 	right_nritems -= push_items;
3643eef1c494SYan 	btrfs_set_header_nritems(right, right_nritems);
3644123abc88SChris Mason 	push_space = BTRFS_LEAF_DATA_SIZE(root);
36455f39d397SChris Mason 	for (i = 0; i < right_nritems; i++) {
36465f39d397SChris Mason 		item = btrfs_item_nr(right, i);
3647db94535dSChris Mason 
3648cfed81a0SChris Mason 		push_space = push_space - btrfs_token_item_size(right,
3649cfed81a0SChris Mason 								item, &token);
3650cfed81a0SChris Mason 		btrfs_set_token_item_offset(right, item, push_space, &token);
3651db94535dSChris Mason 	}
3652eb60ceacSChris Mason 
36535f39d397SChris Mason 	btrfs_mark_buffer_dirty(left);
365434a38218SChris Mason 	if (right_nritems)
36555f39d397SChris Mason 		btrfs_mark_buffer_dirty(right);
3656f0486c68SYan, Zheng 	else
3657f0486c68SYan, Zheng 		clean_tree_block(trans, root, right);
3658098f59c2SChris Mason 
36595f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
3660d6a0a126STsutomu Itoh 	fixup_low_keys(root, path, &disk_key, 1);
3661be0e5c09SChris Mason 
3662be0e5c09SChris Mason 	/* then fixup the leaf pointer in the path */
3663be0e5c09SChris Mason 	if (path->slots[0] < push_items) {
3664be0e5c09SChris Mason 		path->slots[0] += old_left_nritems;
3665925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
36665f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
36675f39d397SChris Mason 		path->nodes[0] = left;
3668be0e5c09SChris Mason 		path->slots[1] -= 1;
3669be0e5c09SChris Mason 	} else {
3670925baeddSChris Mason 		btrfs_tree_unlock(left);
36715f39d397SChris Mason 		free_extent_buffer(left);
3672be0e5c09SChris Mason 		path->slots[0] -= push_items;
3673be0e5c09SChris Mason 	}
3674eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
3675aa5d6bedSChris Mason 	return ret;
3676925baeddSChris Mason out:
3677925baeddSChris Mason 	btrfs_tree_unlock(left);
3678925baeddSChris Mason 	free_extent_buffer(left);
3679925baeddSChris Mason 	return ret;
3680be0e5c09SChris Mason }
3681be0e5c09SChris Mason 
368274123bd7SChris Mason /*
368344871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
368444871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
368599d8f83cSChris Mason  *
368699d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
368799d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us push all the
368899d8f83cSChris Mason  * items
368944871b1bSChris Mason  */
369044871b1bSChris Mason static int push_leaf_left(struct btrfs_trans_handle *trans, struct btrfs_root
369199d8f83cSChris Mason 			  *root, struct btrfs_path *path, int min_data_size,
369299d8f83cSChris Mason 			  int data_size, int empty, u32 max_slot)
369344871b1bSChris Mason {
369444871b1bSChris Mason 	struct extent_buffer *right = path->nodes[0];
369544871b1bSChris Mason 	struct extent_buffer *left;
369644871b1bSChris Mason 	int slot;
369744871b1bSChris Mason 	int free_space;
369844871b1bSChris Mason 	u32 right_nritems;
369944871b1bSChris Mason 	int ret = 0;
370044871b1bSChris Mason 
370144871b1bSChris Mason 	slot = path->slots[1];
370244871b1bSChris Mason 	if (slot == 0)
370344871b1bSChris Mason 		return 1;
370444871b1bSChris Mason 	if (!path->nodes[1])
370544871b1bSChris Mason 		return 1;
370644871b1bSChris Mason 
370744871b1bSChris Mason 	right_nritems = btrfs_header_nritems(right);
370844871b1bSChris Mason 	if (right_nritems == 0)
370944871b1bSChris Mason 		return 1;
371044871b1bSChris Mason 
371144871b1bSChris Mason 	btrfs_assert_tree_locked(path->nodes[1]);
371244871b1bSChris Mason 
371344871b1bSChris Mason 	left = read_node_slot(root, path->nodes[1], slot - 1);
371491ca338dSTsutomu Itoh 	if (left == NULL)
371591ca338dSTsutomu Itoh 		return 1;
371691ca338dSTsutomu Itoh 
371744871b1bSChris Mason 	btrfs_tree_lock(left);
371844871b1bSChris Mason 	btrfs_set_lock_blocking(left);
371944871b1bSChris Mason 
372044871b1bSChris Mason 	free_space = btrfs_leaf_free_space(root, left);
372144871b1bSChris Mason 	if (free_space < data_size) {
372244871b1bSChris Mason 		ret = 1;
372344871b1bSChris Mason 		goto out;
372444871b1bSChris Mason 	}
372544871b1bSChris Mason 
372644871b1bSChris Mason 	/* cow and double check */
372744871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, left,
372844871b1bSChris Mason 			      path->nodes[1], slot - 1, &left);
372944871b1bSChris Mason 	if (ret) {
373044871b1bSChris Mason 		/* we hit -ENOSPC, but it isn't fatal here */
373179787eaaSJeff Mahoney 		if (ret == -ENOSPC)
373244871b1bSChris Mason 			ret = 1;
373344871b1bSChris Mason 		goto out;
373444871b1bSChris Mason 	}
373544871b1bSChris Mason 
373644871b1bSChris Mason 	free_space = btrfs_leaf_free_space(root, left);
373744871b1bSChris Mason 	if (free_space < data_size) {
373844871b1bSChris Mason 		ret = 1;
373944871b1bSChris Mason 		goto out;
374044871b1bSChris Mason 	}
374144871b1bSChris Mason 
374299d8f83cSChris Mason 	return __push_leaf_left(trans, root, path, min_data_size,
374399d8f83cSChris Mason 			       empty, left, free_space, right_nritems,
374499d8f83cSChris Mason 			       max_slot);
374544871b1bSChris Mason out:
374644871b1bSChris Mason 	btrfs_tree_unlock(left);
374744871b1bSChris Mason 	free_extent_buffer(left);
374844871b1bSChris Mason 	return ret;
374944871b1bSChris Mason }
375044871b1bSChris Mason 
375144871b1bSChris Mason /*
375274123bd7SChris Mason  * split the path's leaf in two, making sure there is at least data_size
375374123bd7SChris Mason  * available for the resulting leaf level of the path.
375474123bd7SChris Mason  */
3755143bede5SJeff Mahoney static noinline void copy_for_split(struct btrfs_trans_handle *trans,
3756e02119d5SChris Mason 				    struct btrfs_root *root,
375744871b1bSChris Mason 				    struct btrfs_path *path,
375844871b1bSChris Mason 				    struct extent_buffer *l,
375944871b1bSChris Mason 				    struct extent_buffer *right,
376044871b1bSChris Mason 				    int slot, int mid, int nritems)
3761be0e5c09SChris Mason {
3762be0e5c09SChris Mason 	int data_copy_size;
3763be0e5c09SChris Mason 	int rt_data_off;
3764be0e5c09SChris Mason 	int i;
3765d4dbff95SChris Mason 	struct btrfs_disk_key disk_key;
3766cfed81a0SChris Mason 	struct btrfs_map_token token;
3767cfed81a0SChris Mason 
3768cfed81a0SChris Mason 	btrfs_init_map_token(&token);
3769be0e5c09SChris Mason 
37705f39d397SChris Mason 	nritems = nritems - mid;
37715f39d397SChris Mason 	btrfs_set_header_nritems(right, nritems);
37725f39d397SChris Mason 	data_copy_size = btrfs_item_end_nr(l, mid) - leaf_data_end(root, l);
37735f39d397SChris Mason 
37745f39d397SChris Mason 	copy_extent_buffer(right, l, btrfs_item_nr_offset(0),
37755f39d397SChris Mason 			   btrfs_item_nr_offset(mid),
37765f39d397SChris Mason 			   nritems * sizeof(struct btrfs_item));
37775f39d397SChris Mason 
37785f39d397SChris Mason 	copy_extent_buffer(right, l,
3779d6025579SChris Mason 		     btrfs_leaf_data(right) + BTRFS_LEAF_DATA_SIZE(root) -
3780123abc88SChris Mason 		     data_copy_size, btrfs_leaf_data(l) +
3781123abc88SChris Mason 		     leaf_data_end(root, l), data_copy_size);
378274123bd7SChris Mason 
37835f39d397SChris Mason 	rt_data_off = BTRFS_LEAF_DATA_SIZE(root) -
37845f39d397SChris Mason 		      btrfs_item_end_nr(l, mid);
37855f39d397SChris Mason 
37865f39d397SChris Mason 	for (i = 0; i < nritems; i++) {
37875f39d397SChris Mason 		struct btrfs_item *item = btrfs_item_nr(right, i);
3788db94535dSChris Mason 		u32 ioff;
3789db94535dSChris Mason 
3790cfed81a0SChris Mason 		ioff = btrfs_token_item_offset(right, item, &token);
3791cfed81a0SChris Mason 		btrfs_set_token_item_offset(right, item,
3792cfed81a0SChris Mason 					    ioff + rt_data_off, &token);
37930783fcfcSChris Mason 	}
379474123bd7SChris Mason 
37955f39d397SChris Mason 	btrfs_set_header_nritems(l, mid);
37965f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
3797143bede5SJeff Mahoney 	insert_ptr(trans, root, path, &disk_key, right->start,
3798c3e06965SJan Schmidt 		   path->slots[1] + 1, 1);
37995f39d397SChris Mason 
38005f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
38015f39d397SChris Mason 	btrfs_mark_buffer_dirty(l);
3802eb60ceacSChris Mason 	BUG_ON(path->slots[0] != slot);
38035f39d397SChris Mason 
3804be0e5c09SChris Mason 	if (mid <= slot) {
3805925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
38065f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
38075f39d397SChris Mason 		path->nodes[0] = right;
3808be0e5c09SChris Mason 		path->slots[0] -= mid;
3809be0e5c09SChris Mason 		path->slots[1] += 1;
3810925baeddSChris Mason 	} else {
3811925baeddSChris Mason 		btrfs_tree_unlock(right);
38125f39d397SChris Mason 		free_extent_buffer(right);
3813925baeddSChris Mason 	}
38145f39d397SChris Mason 
3815eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
381644871b1bSChris Mason }
381744871b1bSChris Mason 
381844871b1bSChris Mason /*
381999d8f83cSChris Mason  * double splits happen when we need to insert a big item in the middle
382099d8f83cSChris Mason  * of a leaf.  A double split can leave us with 3 mostly empty leaves:
382199d8f83cSChris Mason  * leaf: [ slots 0 - N] [ our target ] [ N + 1 - total in leaf ]
382299d8f83cSChris Mason  *          A                 B                 C
382399d8f83cSChris Mason  *
382499d8f83cSChris Mason  * We avoid this by trying to push the items on either side of our target
382599d8f83cSChris Mason  * into the adjacent leaves.  If all goes well we can avoid the double split
382699d8f83cSChris Mason  * completely.
382799d8f83cSChris Mason  */
382899d8f83cSChris Mason static noinline int push_for_double_split(struct btrfs_trans_handle *trans,
382999d8f83cSChris Mason 					  struct btrfs_root *root,
383099d8f83cSChris Mason 					  struct btrfs_path *path,
383199d8f83cSChris Mason 					  int data_size)
383299d8f83cSChris Mason {
383399d8f83cSChris Mason 	int ret;
383499d8f83cSChris Mason 	int progress = 0;
383599d8f83cSChris Mason 	int slot;
383699d8f83cSChris Mason 	u32 nritems;
383799d8f83cSChris Mason 
383899d8f83cSChris Mason 	slot = path->slots[0];
383999d8f83cSChris Mason 
384099d8f83cSChris Mason 	/*
384199d8f83cSChris Mason 	 * try to push all the items after our slot into the
384299d8f83cSChris Mason 	 * right leaf
384399d8f83cSChris Mason 	 */
384499d8f83cSChris Mason 	ret = push_leaf_right(trans, root, path, 1, data_size, 0, slot);
384599d8f83cSChris Mason 	if (ret < 0)
384699d8f83cSChris Mason 		return ret;
384799d8f83cSChris Mason 
384899d8f83cSChris Mason 	if (ret == 0)
384999d8f83cSChris Mason 		progress++;
385099d8f83cSChris Mason 
385199d8f83cSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
385299d8f83cSChris Mason 	/*
385399d8f83cSChris Mason 	 * our goal is to get our slot at the start or end of a leaf.  If
385499d8f83cSChris Mason 	 * we've done so we're done
385599d8f83cSChris Mason 	 */
385699d8f83cSChris Mason 	if (path->slots[0] == 0 || path->slots[0] == nritems)
385799d8f83cSChris Mason 		return 0;
385899d8f83cSChris Mason 
385999d8f83cSChris Mason 	if (btrfs_leaf_free_space(root, path->nodes[0]) >= data_size)
386099d8f83cSChris Mason 		return 0;
386199d8f83cSChris Mason 
386299d8f83cSChris Mason 	/* try to push all the items before our slot into the next leaf */
386399d8f83cSChris Mason 	slot = path->slots[0];
386499d8f83cSChris Mason 	ret = push_leaf_left(trans, root, path, 1, data_size, 0, slot);
386599d8f83cSChris Mason 	if (ret < 0)
386699d8f83cSChris Mason 		return ret;
386799d8f83cSChris Mason 
386899d8f83cSChris Mason 	if (ret == 0)
386999d8f83cSChris Mason 		progress++;
387099d8f83cSChris Mason 
387199d8f83cSChris Mason 	if (progress)
387299d8f83cSChris Mason 		return 0;
387399d8f83cSChris Mason 	return 1;
387499d8f83cSChris Mason }
387599d8f83cSChris Mason 
387699d8f83cSChris Mason /*
387744871b1bSChris Mason  * split the path's leaf in two, making sure there is at least data_size
387844871b1bSChris Mason  * available for the resulting leaf level of the path.
387944871b1bSChris Mason  *
388044871b1bSChris Mason  * returns 0 if all went well and < 0 on failure.
388144871b1bSChris Mason  */
388244871b1bSChris Mason static noinline int split_leaf(struct btrfs_trans_handle *trans,
388344871b1bSChris Mason 			       struct btrfs_root *root,
388444871b1bSChris Mason 			       struct btrfs_key *ins_key,
388544871b1bSChris Mason 			       struct btrfs_path *path, int data_size,
388644871b1bSChris Mason 			       int extend)
388744871b1bSChris Mason {
38885d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
388944871b1bSChris Mason 	struct extent_buffer *l;
389044871b1bSChris Mason 	u32 nritems;
389144871b1bSChris Mason 	int mid;
389244871b1bSChris Mason 	int slot;
389344871b1bSChris Mason 	struct extent_buffer *right;
389444871b1bSChris Mason 	int ret = 0;
389544871b1bSChris Mason 	int wret;
38965d4f98a2SYan Zheng 	int split;
389744871b1bSChris Mason 	int num_doubles = 0;
389899d8f83cSChris Mason 	int tried_avoid_double = 0;
389944871b1bSChris Mason 
3900a5719521SYan, Zheng 	l = path->nodes[0];
3901a5719521SYan, Zheng 	slot = path->slots[0];
3902a5719521SYan, Zheng 	if (extend && data_size + btrfs_item_size_nr(l, slot) +
3903a5719521SYan, Zheng 	    sizeof(struct btrfs_item) > BTRFS_LEAF_DATA_SIZE(root))
3904a5719521SYan, Zheng 		return -EOVERFLOW;
3905a5719521SYan, Zheng 
390644871b1bSChris Mason 	/* first try to make some room by pushing left and right */
390733157e05SLiu Bo 	if (data_size && path->nodes[1]) {
390899d8f83cSChris Mason 		wret = push_leaf_right(trans, root, path, data_size,
390999d8f83cSChris Mason 				       data_size, 0, 0);
391044871b1bSChris Mason 		if (wret < 0)
391144871b1bSChris Mason 			return wret;
391244871b1bSChris Mason 		if (wret) {
391399d8f83cSChris Mason 			wret = push_leaf_left(trans, root, path, data_size,
391499d8f83cSChris Mason 					      data_size, 0, (u32)-1);
391544871b1bSChris Mason 			if (wret < 0)
391644871b1bSChris Mason 				return wret;
391744871b1bSChris Mason 		}
391844871b1bSChris Mason 		l = path->nodes[0];
391944871b1bSChris Mason 
392044871b1bSChris Mason 		/* did the pushes work? */
392144871b1bSChris Mason 		if (btrfs_leaf_free_space(root, l) >= data_size)
392244871b1bSChris Mason 			return 0;
392344871b1bSChris Mason 	}
392444871b1bSChris Mason 
392544871b1bSChris Mason 	if (!path->nodes[1]) {
3926fdd99c72SLiu Bo 		ret = insert_new_root(trans, root, path, 1);
392744871b1bSChris Mason 		if (ret)
392844871b1bSChris Mason 			return ret;
392944871b1bSChris Mason 	}
393044871b1bSChris Mason again:
39315d4f98a2SYan Zheng 	split = 1;
393244871b1bSChris Mason 	l = path->nodes[0];
393344871b1bSChris Mason 	slot = path->slots[0];
393444871b1bSChris Mason 	nritems = btrfs_header_nritems(l);
393544871b1bSChris Mason 	mid = (nritems + 1) / 2;
393644871b1bSChris Mason 
39375d4f98a2SYan Zheng 	if (mid <= slot) {
39385d4f98a2SYan Zheng 		if (nritems == 1 ||
39395d4f98a2SYan Zheng 		    leaf_space_used(l, mid, nritems - mid) + data_size >
39405d4f98a2SYan Zheng 			BTRFS_LEAF_DATA_SIZE(root)) {
39415d4f98a2SYan Zheng 			if (slot >= nritems) {
39425d4f98a2SYan Zheng 				split = 0;
39435d4f98a2SYan Zheng 			} else {
39445d4f98a2SYan Zheng 				mid = slot;
39455d4f98a2SYan Zheng 				if (mid != nritems &&
39465d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
39475d4f98a2SYan Zheng 				    data_size > BTRFS_LEAF_DATA_SIZE(root)) {
394899d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
394999d8f83cSChris Mason 						goto push_for_double;
39505d4f98a2SYan Zheng 					split = 2;
39515d4f98a2SYan Zheng 				}
39525d4f98a2SYan Zheng 			}
39535d4f98a2SYan Zheng 		}
39545d4f98a2SYan Zheng 	} else {
39555d4f98a2SYan Zheng 		if (leaf_space_used(l, 0, mid) + data_size >
39565d4f98a2SYan Zheng 			BTRFS_LEAF_DATA_SIZE(root)) {
39575d4f98a2SYan Zheng 			if (!extend && data_size && slot == 0) {
39585d4f98a2SYan Zheng 				split = 0;
39595d4f98a2SYan Zheng 			} else if ((extend || !data_size) && slot == 0) {
39605d4f98a2SYan Zheng 				mid = 1;
39615d4f98a2SYan Zheng 			} else {
39625d4f98a2SYan Zheng 				mid = slot;
39635d4f98a2SYan Zheng 				if (mid != nritems &&
39645d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
39655d4f98a2SYan Zheng 				    data_size > BTRFS_LEAF_DATA_SIZE(root)) {
396699d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
396799d8f83cSChris Mason 						goto push_for_double;
39685d4f98a2SYan Zheng 					split = 2 ;
39695d4f98a2SYan Zheng 				}
39705d4f98a2SYan Zheng 			}
39715d4f98a2SYan Zheng 		}
39725d4f98a2SYan Zheng 	}
39735d4f98a2SYan Zheng 
39745d4f98a2SYan Zheng 	if (split == 0)
39755d4f98a2SYan Zheng 		btrfs_cpu_key_to_disk(&disk_key, ins_key);
39765d4f98a2SYan Zheng 	else
39775d4f98a2SYan Zheng 		btrfs_item_key(l, &disk_key, mid);
39785d4f98a2SYan Zheng 
39795d4f98a2SYan Zheng 	right = btrfs_alloc_free_block(trans, root, root->leafsize, 0,
398044871b1bSChris Mason 					root->root_key.objectid,
39815581a51aSJan Schmidt 					&disk_key, 0, l->start, 0);
3982f0486c68SYan, Zheng 	if (IS_ERR(right))
398344871b1bSChris Mason 		return PTR_ERR(right);
3984f0486c68SYan, Zheng 
3985f0486c68SYan, Zheng 	root_add_used(root, root->leafsize);
398644871b1bSChris Mason 
398744871b1bSChris Mason 	memset_extent_buffer(right, 0, 0, sizeof(struct btrfs_header));
398844871b1bSChris Mason 	btrfs_set_header_bytenr(right, right->start);
398944871b1bSChris Mason 	btrfs_set_header_generation(right, trans->transid);
39905d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(right, BTRFS_MIXED_BACKREF_REV);
399144871b1bSChris Mason 	btrfs_set_header_owner(right, root->root_key.objectid);
399244871b1bSChris Mason 	btrfs_set_header_level(right, 0);
399344871b1bSChris Mason 	write_extent_buffer(right, root->fs_info->fsid,
399444871b1bSChris Mason 			    (unsigned long)btrfs_header_fsid(right),
399544871b1bSChris Mason 			    BTRFS_FSID_SIZE);
399644871b1bSChris Mason 
399744871b1bSChris Mason 	write_extent_buffer(right, root->fs_info->chunk_tree_uuid,
399844871b1bSChris Mason 			    (unsigned long)btrfs_header_chunk_tree_uuid(right),
399944871b1bSChris Mason 			    BTRFS_UUID_SIZE);
400044871b1bSChris Mason 
40015d4f98a2SYan Zheng 	if (split == 0) {
400244871b1bSChris Mason 		if (mid <= slot) {
400344871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
4004143bede5SJeff Mahoney 			insert_ptr(trans, root, path, &disk_key, right->start,
4005c3e06965SJan Schmidt 				   path->slots[1] + 1, 1);
400644871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
400744871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
400844871b1bSChris Mason 			path->nodes[0] = right;
400944871b1bSChris Mason 			path->slots[0] = 0;
401044871b1bSChris Mason 			path->slots[1] += 1;
401144871b1bSChris Mason 		} else {
401244871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
4013143bede5SJeff Mahoney 			insert_ptr(trans, root, path, &disk_key, right->start,
4014c3e06965SJan Schmidt 					  path->slots[1], 1);
401544871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
401644871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
401744871b1bSChris Mason 			path->nodes[0] = right;
401844871b1bSChris Mason 			path->slots[0] = 0;
4019143bede5SJeff Mahoney 			if (path->slots[1] == 0)
4020d6a0a126STsutomu Itoh 				fixup_low_keys(root, path, &disk_key, 1);
40215d4f98a2SYan Zheng 		}
402244871b1bSChris Mason 		btrfs_mark_buffer_dirty(right);
402344871b1bSChris Mason 		return ret;
402444871b1bSChris Mason 	}
402544871b1bSChris Mason 
4026143bede5SJeff Mahoney 	copy_for_split(trans, root, path, l, right, slot, mid, nritems);
402744871b1bSChris Mason 
40285d4f98a2SYan Zheng 	if (split == 2) {
4029cc0c5538SChris Mason 		BUG_ON(num_doubles != 0);
4030cc0c5538SChris Mason 		num_doubles++;
4031cc0c5538SChris Mason 		goto again;
40323326d1b0SChris Mason 	}
403344871b1bSChris Mason 
4034143bede5SJeff Mahoney 	return 0;
403599d8f83cSChris Mason 
403699d8f83cSChris Mason push_for_double:
403799d8f83cSChris Mason 	push_for_double_split(trans, root, path, data_size);
403899d8f83cSChris Mason 	tried_avoid_double = 1;
403999d8f83cSChris Mason 	if (btrfs_leaf_free_space(root, path->nodes[0]) >= data_size)
404099d8f83cSChris Mason 		return 0;
404199d8f83cSChris Mason 	goto again;
4042be0e5c09SChris Mason }
4043be0e5c09SChris Mason 
4044ad48fd75SYan, Zheng static noinline int setup_leaf_for_split(struct btrfs_trans_handle *trans,
4045ad48fd75SYan, Zheng 					 struct btrfs_root *root,
4046ad48fd75SYan, Zheng 					 struct btrfs_path *path, int ins_len)
4047ad48fd75SYan, Zheng {
4048ad48fd75SYan, Zheng 	struct btrfs_key key;
4049ad48fd75SYan, Zheng 	struct extent_buffer *leaf;
4050ad48fd75SYan, Zheng 	struct btrfs_file_extent_item *fi;
4051ad48fd75SYan, Zheng 	u64 extent_len = 0;
4052ad48fd75SYan, Zheng 	u32 item_size;
4053ad48fd75SYan, Zheng 	int ret;
4054ad48fd75SYan, Zheng 
4055ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4056ad48fd75SYan, Zheng 	btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4057ad48fd75SYan, Zheng 
4058ad48fd75SYan, Zheng 	BUG_ON(key.type != BTRFS_EXTENT_DATA_KEY &&
4059ad48fd75SYan, Zheng 	       key.type != BTRFS_EXTENT_CSUM_KEY);
4060ad48fd75SYan, Zheng 
4061ad48fd75SYan, Zheng 	if (btrfs_leaf_free_space(root, leaf) >= ins_len)
4062ad48fd75SYan, Zheng 		return 0;
4063ad48fd75SYan, Zheng 
4064ad48fd75SYan, Zheng 	item_size = btrfs_item_size_nr(leaf, path->slots[0]);
4065ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
4066ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
4067ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
4068ad48fd75SYan, Zheng 		extent_len = btrfs_file_extent_num_bytes(leaf, fi);
4069ad48fd75SYan, Zheng 	}
4070b3b4aa74SDavid Sterba 	btrfs_release_path(path);
4071ad48fd75SYan, Zheng 
4072ad48fd75SYan, Zheng 	path->keep_locks = 1;
4073ad48fd75SYan, Zheng 	path->search_for_split = 1;
4074ad48fd75SYan, Zheng 	ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
4075ad48fd75SYan, Zheng 	path->search_for_split = 0;
4076ad48fd75SYan, Zheng 	if (ret < 0)
4077ad48fd75SYan, Zheng 		goto err;
4078ad48fd75SYan, Zheng 
4079ad48fd75SYan, Zheng 	ret = -EAGAIN;
4080ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4081ad48fd75SYan, Zheng 	/* if our item isn't there or got smaller, return now */
4082ad48fd75SYan, Zheng 	if (ret > 0 || item_size != btrfs_item_size_nr(leaf, path->slots[0]))
4083ad48fd75SYan, Zheng 		goto err;
4084ad48fd75SYan, Zheng 
4085109f6aefSChris Mason 	/* the leaf has  changed, it now has room.  return now */
4086109f6aefSChris Mason 	if (btrfs_leaf_free_space(root, path->nodes[0]) >= ins_len)
4087109f6aefSChris Mason 		goto err;
4088109f6aefSChris Mason 
4089ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
4090ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
4091ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
4092ad48fd75SYan, Zheng 		if (extent_len != btrfs_file_extent_num_bytes(leaf, fi))
4093ad48fd75SYan, Zheng 			goto err;
4094ad48fd75SYan, Zheng 	}
4095ad48fd75SYan, Zheng 
4096ad48fd75SYan, Zheng 	btrfs_set_path_blocking(path);
4097ad48fd75SYan, Zheng 	ret = split_leaf(trans, root, &key, path, ins_len, 1);
4098f0486c68SYan, Zheng 	if (ret)
4099f0486c68SYan, Zheng 		goto err;
4100ad48fd75SYan, Zheng 
4101ad48fd75SYan, Zheng 	path->keep_locks = 0;
4102ad48fd75SYan, Zheng 	btrfs_unlock_up_safe(path, 1);
4103ad48fd75SYan, Zheng 	return 0;
4104ad48fd75SYan, Zheng err:
4105ad48fd75SYan, Zheng 	path->keep_locks = 0;
4106ad48fd75SYan, Zheng 	return ret;
4107ad48fd75SYan, Zheng }
4108ad48fd75SYan, Zheng 
4109ad48fd75SYan, Zheng static noinline int split_item(struct btrfs_trans_handle *trans,
4110459931ecSChris Mason 			       struct btrfs_root *root,
4111459931ecSChris Mason 			       struct btrfs_path *path,
4112459931ecSChris Mason 			       struct btrfs_key *new_key,
4113459931ecSChris Mason 			       unsigned long split_offset)
4114459931ecSChris Mason {
4115459931ecSChris Mason 	struct extent_buffer *leaf;
4116459931ecSChris Mason 	struct btrfs_item *item;
4117459931ecSChris Mason 	struct btrfs_item *new_item;
4118459931ecSChris Mason 	int slot;
4119ad48fd75SYan, Zheng 	char *buf;
4120459931ecSChris Mason 	u32 nritems;
4121ad48fd75SYan, Zheng 	u32 item_size;
4122459931ecSChris Mason 	u32 orig_offset;
4123459931ecSChris Mason 	struct btrfs_disk_key disk_key;
4124459931ecSChris Mason 
4125459931ecSChris Mason 	leaf = path->nodes[0];
4126b9473439SChris Mason 	BUG_ON(btrfs_leaf_free_space(root, leaf) < sizeof(struct btrfs_item));
4127b9473439SChris Mason 
4128b4ce94deSChris Mason 	btrfs_set_path_blocking(path);
4129b4ce94deSChris Mason 
4130459931ecSChris Mason 	item = btrfs_item_nr(leaf, path->slots[0]);
4131459931ecSChris Mason 	orig_offset = btrfs_item_offset(leaf, item);
4132459931ecSChris Mason 	item_size = btrfs_item_size(leaf, item);
4133459931ecSChris Mason 
4134459931ecSChris Mason 	buf = kmalloc(item_size, GFP_NOFS);
4135ad48fd75SYan, Zheng 	if (!buf)
4136ad48fd75SYan, Zheng 		return -ENOMEM;
4137ad48fd75SYan, Zheng 
4138459931ecSChris Mason 	read_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf,
4139459931ecSChris Mason 			    path->slots[0]), item_size);
4140ad48fd75SYan, Zheng 
4141459931ecSChris Mason 	slot = path->slots[0] + 1;
4142459931ecSChris Mason 	nritems = btrfs_header_nritems(leaf);
4143459931ecSChris Mason 	if (slot != nritems) {
4144459931ecSChris Mason 		/* shift the items */
4145459931ecSChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + 1),
4146459931ecSChris Mason 				btrfs_item_nr_offset(slot),
4147459931ecSChris Mason 				(nritems - slot) * sizeof(struct btrfs_item));
4148459931ecSChris Mason 	}
4149459931ecSChris Mason 
4150459931ecSChris Mason 	btrfs_cpu_key_to_disk(&disk_key, new_key);
4151459931ecSChris Mason 	btrfs_set_item_key(leaf, &disk_key, slot);
4152459931ecSChris Mason 
4153459931ecSChris Mason 	new_item = btrfs_item_nr(leaf, slot);
4154459931ecSChris Mason 
4155459931ecSChris Mason 	btrfs_set_item_offset(leaf, new_item, orig_offset);
4156459931ecSChris Mason 	btrfs_set_item_size(leaf, new_item, item_size - split_offset);
4157459931ecSChris Mason 
4158459931ecSChris Mason 	btrfs_set_item_offset(leaf, item,
4159459931ecSChris Mason 			      orig_offset + item_size - split_offset);
4160459931ecSChris Mason 	btrfs_set_item_size(leaf, item, split_offset);
4161459931ecSChris Mason 
4162459931ecSChris Mason 	btrfs_set_header_nritems(leaf, nritems + 1);
4163459931ecSChris Mason 
4164459931ecSChris Mason 	/* write the data for the start of the original item */
4165459931ecSChris Mason 	write_extent_buffer(leaf, buf,
4166459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, path->slots[0]),
4167459931ecSChris Mason 			    split_offset);
4168459931ecSChris Mason 
4169459931ecSChris Mason 	/* write the data for the new item */
4170459931ecSChris Mason 	write_extent_buffer(leaf, buf + split_offset,
4171459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, slot),
4172459931ecSChris Mason 			    item_size - split_offset);
4173459931ecSChris Mason 	btrfs_mark_buffer_dirty(leaf);
4174459931ecSChris Mason 
4175ad48fd75SYan, Zheng 	BUG_ON(btrfs_leaf_free_space(root, leaf) < 0);
4176459931ecSChris Mason 	kfree(buf);
4177ad48fd75SYan, Zheng 	return 0;
4178ad48fd75SYan, Zheng }
4179ad48fd75SYan, Zheng 
4180ad48fd75SYan, Zheng /*
4181ad48fd75SYan, Zheng  * This function splits a single item into two items,
4182ad48fd75SYan, Zheng  * giving 'new_key' to the new item and splitting the
4183ad48fd75SYan, Zheng  * old one at split_offset (from the start of the item).
4184ad48fd75SYan, Zheng  *
4185ad48fd75SYan, Zheng  * The path may be released by this operation.  After
4186ad48fd75SYan, Zheng  * the split, the path is pointing to the old item.  The
4187ad48fd75SYan, Zheng  * new item is going to be in the same node as the old one.
4188ad48fd75SYan, Zheng  *
4189ad48fd75SYan, Zheng  * Note, the item being split must be smaller enough to live alone on
4190ad48fd75SYan, Zheng  * a tree block with room for one extra struct btrfs_item
4191ad48fd75SYan, Zheng  *
4192ad48fd75SYan, Zheng  * This allows us to split the item in place, keeping a lock on the
4193ad48fd75SYan, Zheng  * leaf the entire time.
4194ad48fd75SYan, Zheng  */
4195ad48fd75SYan, Zheng int btrfs_split_item(struct btrfs_trans_handle *trans,
4196ad48fd75SYan, Zheng 		     struct btrfs_root *root,
4197ad48fd75SYan, Zheng 		     struct btrfs_path *path,
4198ad48fd75SYan, Zheng 		     struct btrfs_key *new_key,
4199ad48fd75SYan, Zheng 		     unsigned long split_offset)
4200ad48fd75SYan, Zheng {
4201ad48fd75SYan, Zheng 	int ret;
4202ad48fd75SYan, Zheng 	ret = setup_leaf_for_split(trans, root, path,
4203ad48fd75SYan, Zheng 				   sizeof(struct btrfs_item));
4204ad48fd75SYan, Zheng 	if (ret)
4205459931ecSChris Mason 		return ret;
4206ad48fd75SYan, Zheng 
4207ad48fd75SYan, Zheng 	ret = split_item(trans, root, path, new_key, split_offset);
4208ad48fd75SYan, Zheng 	return ret;
4209ad48fd75SYan, Zheng }
4210ad48fd75SYan, Zheng 
4211ad48fd75SYan, Zheng /*
4212ad48fd75SYan, Zheng  * This function duplicate a item, giving 'new_key' to the new item.
4213ad48fd75SYan, Zheng  * It guarantees both items live in the same tree leaf and the new item
4214ad48fd75SYan, Zheng  * is contiguous with the original item.
4215ad48fd75SYan, Zheng  *
4216ad48fd75SYan, Zheng  * This allows us to split file extent in place, keeping a lock on the
4217ad48fd75SYan, Zheng  * leaf the entire time.
4218ad48fd75SYan, Zheng  */
4219ad48fd75SYan, Zheng int btrfs_duplicate_item(struct btrfs_trans_handle *trans,
4220ad48fd75SYan, Zheng 			 struct btrfs_root *root,
4221ad48fd75SYan, Zheng 			 struct btrfs_path *path,
4222ad48fd75SYan, Zheng 			 struct btrfs_key *new_key)
4223ad48fd75SYan, Zheng {
4224ad48fd75SYan, Zheng 	struct extent_buffer *leaf;
4225ad48fd75SYan, Zheng 	int ret;
4226ad48fd75SYan, Zheng 	u32 item_size;
4227ad48fd75SYan, Zheng 
4228ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4229ad48fd75SYan, Zheng 	item_size = btrfs_item_size_nr(leaf, path->slots[0]);
4230ad48fd75SYan, Zheng 	ret = setup_leaf_for_split(trans, root, path,
4231ad48fd75SYan, Zheng 				   item_size + sizeof(struct btrfs_item));
4232ad48fd75SYan, Zheng 	if (ret)
4233ad48fd75SYan, Zheng 		return ret;
4234ad48fd75SYan, Zheng 
4235ad48fd75SYan, Zheng 	path->slots[0]++;
4236afe5fea7STsutomu Itoh 	setup_items_for_insert(root, path, new_key, &item_size,
4237ad48fd75SYan, Zheng 			       item_size, item_size +
4238ad48fd75SYan, Zheng 			       sizeof(struct btrfs_item), 1);
4239ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4240ad48fd75SYan, Zheng 	memcpy_extent_buffer(leaf,
4241ad48fd75SYan, Zheng 			     btrfs_item_ptr_offset(leaf, path->slots[0]),
4242ad48fd75SYan, Zheng 			     btrfs_item_ptr_offset(leaf, path->slots[0] - 1),
4243ad48fd75SYan, Zheng 			     item_size);
4244ad48fd75SYan, Zheng 	return 0;
4245459931ecSChris Mason }
4246459931ecSChris Mason 
4247459931ecSChris Mason /*
4248d352ac68SChris Mason  * make the item pointed to by the path smaller.  new_size indicates
4249d352ac68SChris Mason  * how small to make it, and from_end tells us if we just chop bytes
4250d352ac68SChris Mason  * off the end of the item or if we shift the item to chop bytes off
4251d352ac68SChris Mason  * the front.
4252d352ac68SChris Mason  */
4253afe5fea7STsutomu Itoh void btrfs_truncate_item(struct btrfs_root *root, struct btrfs_path *path,
4254179e29e4SChris Mason 			 u32 new_size, int from_end)
4255b18c6685SChris Mason {
4256b18c6685SChris Mason 	int slot;
42575f39d397SChris Mason 	struct extent_buffer *leaf;
42585f39d397SChris Mason 	struct btrfs_item *item;
4259b18c6685SChris Mason 	u32 nritems;
4260b18c6685SChris Mason 	unsigned int data_end;
4261b18c6685SChris Mason 	unsigned int old_data_start;
4262b18c6685SChris Mason 	unsigned int old_size;
4263b18c6685SChris Mason 	unsigned int size_diff;
4264b18c6685SChris Mason 	int i;
4265cfed81a0SChris Mason 	struct btrfs_map_token token;
4266cfed81a0SChris Mason 
4267cfed81a0SChris Mason 	btrfs_init_map_token(&token);
4268b18c6685SChris Mason 
42695f39d397SChris Mason 	leaf = path->nodes[0];
4270179e29e4SChris Mason 	slot = path->slots[0];
4271179e29e4SChris Mason 
4272179e29e4SChris Mason 	old_size = btrfs_item_size_nr(leaf, slot);
4273179e29e4SChris Mason 	if (old_size == new_size)
4274143bede5SJeff Mahoney 		return;
4275b18c6685SChris Mason 
42765f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
4277b18c6685SChris Mason 	data_end = leaf_data_end(root, leaf);
4278b18c6685SChris Mason 
42795f39d397SChris Mason 	old_data_start = btrfs_item_offset_nr(leaf, slot);
4280179e29e4SChris Mason 
4281b18c6685SChris Mason 	size_diff = old_size - new_size;
4282b18c6685SChris Mason 
4283b18c6685SChris Mason 	BUG_ON(slot < 0);
4284b18c6685SChris Mason 	BUG_ON(slot >= nritems);
4285b18c6685SChris Mason 
4286b18c6685SChris Mason 	/*
4287b18c6685SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4288b18c6685SChris Mason 	 */
4289b18c6685SChris Mason 	/* first correct the data pointers */
4290b18c6685SChris Mason 	for (i = slot; i < nritems; i++) {
42915f39d397SChris Mason 		u32 ioff;
42925f39d397SChris Mason 		item = btrfs_item_nr(leaf, i);
4293db94535dSChris Mason 
4294cfed81a0SChris Mason 		ioff = btrfs_token_item_offset(leaf, item, &token);
4295cfed81a0SChris Mason 		btrfs_set_token_item_offset(leaf, item,
4296cfed81a0SChris Mason 					    ioff + size_diff, &token);
4297b18c6685SChris Mason 	}
4298db94535dSChris Mason 
4299b18c6685SChris Mason 	/* shift the data */
4300179e29e4SChris Mason 	if (from_end) {
43015f39d397SChris Mason 		memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
4302b18c6685SChris Mason 			      data_end + size_diff, btrfs_leaf_data(leaf) +
4303b18c6685SChris Mason 			      data_end, old_data_start + new_size - data_end);
4304179e29e4SChris Mason 	} else {
4305179e29e4SChris Mason 		struct btrfs_disk_key disk_key;
4306179e29e4SChris Mason 		u64 offset;
4307179e29e4SChris Mason 
4308179e29e4SChris Mason 		btrfs_item_key(leaf, &disk_key, slot);
4309179e29e4SChris Mason 
4310179e29e4SChris Mason 		if (btrfs_disk_key_type(&disk_key) == BTRFS_EXTENT_DATA_KEY) {
4311179e29e4SChris Mason 			unsigned long ptr;
4312179e29e4SChris Mason 			struct btrfs_file_extent_item *fi;
4313179e29e4SChris Mason 
4314179e29e4SChris Mason 			fi = btrfs_item_ptr(leaf, slot,
4315179e29e4SChris Mason 					    struct btrfs_file_extent_item);
4316179e29e4SChris Mason 			fi = (struct btrfs_file_extent_item *)(
4317179e29e4SChris Mason 			     (unsigned long)fi - size_diff);
4318179e29e4SChris Mason 
4319179e29e4SChris Mason 			if (btrfs_file_extent_type(leaf, fi) ==
4320179e29e4SChris Mason 			    BTRFS_FILE_EXTENT_INLINE) {
4321179e29e4SChris Mason 				ptr = btrfs_item_ptr_offset(leaf, slot);
4322179e29e4SChris Mason 				memmove_extent_buffer(leaf, ptr,
4323179e29e4SChris Mason 				      (unsigned long)fi,
4324179e29e4SChris Mason 				      offsetof(struct btrfs_file_extent_item,
4325179e29e4SChris Mason 						 disk_bytenr));
4326179e29e4SChris Mason 			}
4327179e29e4SChris Mason 		}
4328179e29e4SChris Mason 
4329179e29e4SChris Mason 		memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
4330179e29e4SChris Mason 			      data_end + size_diff, btrfs_leaf_data(leaf) +
4331179e29e4SChris Mason 			      data_end, old_data_start - data_end);
4332179e29e4SChris Mason 
4333179e29e4SChris Mason 		offset = btrfs_disk_key_offset(&disk_key);
4334179e29e4SChris Mason 		btrfs_set_disk_key_offset(&disk_key, offset + size_diff);
4335179e29e4SChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot);
4336179e29e4SChris Mason 		if (slot == 0)
4337d6a0a126STsutomu Itoh 			fixup_low_keys(root, path, &disk_key, 1);
4338179e29e4SChris Mason 	}
43395f39d397SChris Mason 
43405f39d397SChris Mason 	item = btrfs_item_nr(leaf, slot);
43415f39d397SChris Mason 	btrfs_set_item_size(leaf, item, new_size);
43425f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
4343b18c6685SChris Mason 
43445f39d397SChris Mason 	if (btrfs_leaf_free_space(root, leaf) < 0) {
43455f39d397SChris Mason 		btrfs_print_leaf(root, leaf);
4346b18c6685SChris Mason 		BUG();
43475f39d397SChris Mason 	}
4348b18c6685SChris Mason }
4349b18c6685SChris Mason 
4350d352ac68SChris Mason /*
43518f69dbd2SStefan Behrens  * make the item pointed to by the path bigger, data_size is the added size.
4352d352ac68SChris Mason  */
43534b90c680STsutomu Itoh void btrfs_extend_item(struct btrfs_root *root, struct btrfs_path *path,
43545f39d397SChris Mason 		       u32 data_size)
43556567e837SChris Mason {
43566567e837SChris Mason 	int slot;
43575f39d397SChris Mason 	struct extent_buffer *leaf;
43585f39d397SChris Mason 	struct btrfs_item *item;
43596567e837SChris Mason 	u32 nritems;
43606567e837SChris Mason 	unsigned int data_end;
43616567e837SChris Mason 	unsigned int old_data;
43626567e837SChris Mason 	unsigned int old_size;
43636567e837SChris Mason 	int i;
4364cfed81a0SChris Mason 	struct btrfs_map_token token;
4365cfed81a0SChris Mason 
4366cfed81a0SChris Mason 	btrfs_init_map_token(&token);
43676567e837SChris Mason 
43685f39d397SChris Mason 	leaf = path->nodes[0];
43696567e837SChris Mason 
43705f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
43716567e837SChris Mason 	data_end = leaf_data_end(root, leaf);
43726567e837SChris Mason 
43735f39d397SChris Mason 	if (btrfs_leaf_free_space(root, leaf) < data_size) {
43745f39d397SChris Mason 		btrfs_print_leaf(root, leaf);
43756567e837SChris Mason 		BUG();
43765f39d397SChris Mason 	}
43776567e837SChris Mason 	slot = path->slots[0];
43785f39d397SChris Mason 	old_data = btrfs_item_end_nr(leaf, slot);
43796567e837SChris Mason 
43806567e837SChris Mason 	BUG_ON(slot < 0);
43813326d1b0SChris Mason 	if (slot >= nritems) {
43823326d1b0SChris Mason 		btrfs_print_leaf(root, leaf);
4383d397712bSChris Mason 		printk(KERN_CRIT "slot %d too large, nritems %d\n",
4384d397712bSChris Mason 		       slot, nritems);
43853326d1b0SChris Mason 		BUG_ON(1);
43863326d1b0SChris Mason 	}
43876567e837SChris Mason 
43886567e837SChris Mason 	/*
43896567e837SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
43906567e837SChris Mason 	 */
43916567e837SChris Mason 	/* first correct the data pointers */
43926567e837SChris Mason 	for (i = slot; i < nritems; i++) {
43935f39d397SChris Mason 		u32 ioff;
43945f39d397SChris Mason 		item = btrfs_item_nr(leaf, i);
4395db94535dSChris Mason 
4396cfed81a0SChris Mason 		ioff = btrfs_token_item_offset(leaf, item, &token);
4397cfed81a0SChris Mason 		btrfs_set_token_item_offset(leaf, item,
4398cfed81a0SChris Mason 					    ioff - data_size, &token);
43996567e837SChris Mason 	}
44005f39d397SChris Mason 
44016567e837SChris Mason 	/* shift the data */
44025f39d397SChris Mason 	memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
44036567e837SChris Mason 		      data_end - data_size, btrfs_leaf_data(leaf) +
44046567e837SChris Mason 		      data_end, old_data - data_end);
44055f39d397SChris Mason 
44066567e837SChris Mason 	data_end = old_data;
44075f39d397SChris Mason 	old_size = btrfs_item_size_nr(leaf, slot);
44085f39d397SChris Mason 	item = btrfs_item_nr(leaf, slot);
44095f39d397SChris Mason 	btrfs_set_item_size(leaf, item, old_size + data_size);
44105f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
44116567e837SChris Mason 
44125f39d397SChris Mason 	if (btrfs_leaf_free_space(root, leaf) < 0) {
44135f39d397SChris Mason 		btrfs_print_leaf(root, leaf);
44146567e837SChris Mason 		BUG();
44155f39d397SChris Mason 	}
44166567e837SChris Mason }
44176567e837SChris Mason 
441874123bd7SChris Mason /*
441944871b1bSChris Mason  * this is a helper for btrfs_insert_empty_items, the main goal here is
442044871b1bSChris Mason  * to save stack depth by doing the bulk of the work in a function
442144871b1bSChris Mason  * that doesn't call btrfs_search_slot
442274123bd7SChris Mason  */
4423afe5fea7STsutomu Itoh void setup_items_for_insert(struct btrfs_root *root, struct btrfs_path *path,
44249c58309dSChris Mason 			    struct btrfs_key *cpu_key, u32 *data_size,
442544871b1bSChris Mason 			    u32 total_data, u32 total_size, int nr)
4426be0e5c09SChris Mason {
44275f39d397SChris Mason 	struct btrfs_item *item;
44289c58309dSChris Mason 	int i;
44297518a238SChris Mason 	u32 nritems;
4430be0e5c09SChris Mason 	unsigned int data_end;
4431e2fa7227SChris Mason 	struct btrfs_disk_key disk_key;
443244871b1bSChris Mason 	struct extent_buffer *leaf;
443344871b1bSChris Mason 	int slot;
4434cfed81a0SChris Mason 	struct btrfs_map_token token;
4435cfed81a0SChris Mason 
4436cfed81a0SChris Mason 	btrfs_init_map_token(&token);
4437e2fa7227SChris Mason 
44385f39d397SChris Mason 	leaf = path->nodes[0];
443944871b1bSChris Mason 	slot = path->slots[0];
444074123bd7SChris Mason 
44415f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
4442123abc88SChris Mason 	data_end = leaf_data_end(root, leaf);
4443eb60ceacSChris Mason 
4444f25956ccSChris Mason 	if (btrfs_leaf_free_space(root, leaf) < total_size) {
44453326d1b0SChris Mason 		btrfs_print_leaf(root, leaf);
4446d397712bSChris Mason 		printk(KERN_CRIT "not enough freespace need %u have %d\n",
44479c58309dSChris Mason 		       total_size, btrfs_leaf_free_space(root, leaf));
4448be0e5c09SChris Mason 		BUG();
4449d4dbff95SChris Mason 	}
44505f39d397SChris Mason 
4451be0e5c09SChris Mason 	if (slot != nritems) {
44525f39d397SChris Mason 		unsigned int old_data = btrfs_item_end_nr(leaf, slot);
4453be0e5c09SChris Mason 
44545f39d397SChris Mason 		if (old_data < data_end) {
44555f39d397SChris Mason 			btrfs_print_leaf(root, leaf);
4456d397712bSChris Mason 			printk(KERN_CRIT "slot %d old_data %d data_end %d\n",
44575f39d397SChris Mason 			       slot, old_data, data_end);
44585f39d397SChris Mason 			BUG_ON(1);
44595f39d397SChris Mason 		}
4460be0e5c09SChris Mason 		/*
4461be0e5c09SChris Mason 		 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4462be0e5c09SChris Mason 		 */
4463be0e5c09SChris Mason 		/* first correct the data pointers */
44640783fcfcSChris Mason 		for (i = slot; i < nritems; i++) {
44655f39d397SChris Mason 			u32 ioff;
4466db94535dSChris Mason 
44675f39d397SChris Mason 			item = btrfs_item_nr(leaf, i);
4468cfed81a0SChris Mason 			ioff = btrfs_token_item_offset(leaf, item, &token);
4469cfed81a0SChris Mason 			btrfs_set_token_item_offset(leaf, item,
4470cfed81a0SChris Mason 						    ioff - total_data, &token);
44710783fcfcSChris Mason 		}
4472be0e5c09SChris Mason 		/* shift the items */
44739c58309dSChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + nr),
44745f39d397SChris Mason 			      btrfs_item_nr_offset(slot),
44750783fcfcSChris Mason 			      (nritems - slot) * sizeof(struct btrfs_item));
4476be0e5c09SChris Mason 
4477be0e5c09SChris Mason 		/* shift the data */
44785f39d397SChris Mason 		memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
44799c58309dSChris Mason 			      data_end - total_data, btrfs_leaf_data(leaf) +
4480be0e5c09SChris Mason 			      data_end, old_data - data_end);
4481be0e5c09SChris Mason 		data_end = old_data;
4482be0e5c09SChris Mason 	}
44835f39d397SChris Mason 
448462e2749eSChris Mason 	/* setup the item for the new data */
44859c58309dSChris Mason 	for (i = 0; i < nr; i++) {
44869c58309dSChris Mason 		btrfs_cpu_key_to_disk(&disk_key, cpu_key + i);
44879c58309dSChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot + i);
44889c58309dSChris Mason 		item = btrfs_item_nr(leaf, slot + i);
4489cfed81a0SChris Mason 		btrfs_set_token_item_offset(leaf, item,
4490cfed81a0SChris Mason 					    data_end - data_size[i], &token);
44919c58309dSChris Mason 		data_end -= data_size[i];
4492cfed81a0SChris Mason 		btrfs_set_token_item_size(leaf, item, data_size[i], &token);
44939c58309dSChris Mason 	}
449444871b1bSChris Mason 
44959c58309dSChris Mason 	btrfs_set_header_nritems(leaf, nritems + nr);
4496aa5d6bedSChris Mason 
44975a01a2e3SChris Mason 	if (slot == 0) {
44985a01a2e3SChris Mason 		btrfs_cpu_key_to_disk(&disk_key, cpu_key);
4499d6a0a126STsutomu Itoh 		fixup_low_keys(root, path, &disk_key, 1);
45005a01a2e3SChris Mason 	}
4501b9473439SChris Mason 	btrfs_unlock_up_safe(path, 1);
4502b9473439SChris Mason 	btrfs_mark_buffer_dirty(leaf);
4503aa5d6bedSChris Mason 
45045f39d397SChris Mason 	if (btrfs_leaf_free_space(root, leaf) < 0) {
45055f39d397SChris Mason 		btrfs_print_leaf(root, leaf);
4506be0e5c09SChris Mason 		BUG();
45075f39d397SChris Mason 	}
450844871b1bSChris Mason }
450944871b1bSChris Mason 
451044871b1bSChris Mason /*
451144871b1bSChris Mason  * Given a key and some data, insert items into the tree.
451244871b1bSChris Mason  * This does all the path init required, making room in the tree if needed.
451344871b1bSChris Mason  */
451444871b1bSChris Mason int btrfs_insert_empty_items(struct btrfs_trans_handle *trans,
451544871b1bSChris Mason 			    struct btrfs_root *root,
451644871b1bSChris Mason 			    struct btrfs_path *path,
451744871b1bSChris Mason 			    struct btrfs_key *cpu_key, u32 *data_size,
451844871b1bSChris Mason 			    int nr)
451944871b1bSChris Mason {
452044871b1bSChris Mason 	int ret = 0;
452144871b1bSChris Mason 	int slot;
452244871b1bSChris Mason 	int i;
452344871b1bSChris Mason 	u32 total_size = 0;
452444871b1bSChris Mason 	u32 total_data = 0;
452544871b1bSChris Mason 
452644871b1bSChris Mason 	for (i = 0; i < nr; i++)
452744871b1bSChris Mason 		total_data += data_size[i];
452844871b1bSChris Mason 
452944871b1bSChris Mason 	total_size = total_data + (nr * sizeof(struct btrfs_item));
453044871b1bSChris Mason 	ret = btrfs_search_slot(trans, root, cpu_key, path, total_size, 1);
453144871b1bSChris Mason 	if (ret == 0)
453244871b1bSChris Mason 		return -EEXIST;
453344871b1bSChris Mason 	if (ret < 0)
4534143bede5SJeff Mahoney 		return ret;
453544871b1bSChris Mason 
453644871b1bSChris Mason 	slot = path->slots[0];
453744871b1bSChris Mason 	BUG_ON(slot < 0);
453844871b1bSChris Mason 
4539afe5fea7STsutomu Itoh 	setup_items_for_insert(root, path, cpu_key, data_size,
454044871b1bSChris Mason 			       total_data, total_size, nr);
4541143bede5SJeff Mahoney 	return 0;
454262e2749eSChris Mason }
454362e2749eSChris Mason 
454462e2749eSChris Mason /*
454562e2749eSChris Mason  * Given a key and some data, insert an item into the tree.
454662e2749eSChris Mason  * This does all the path init required, making room in the tree if needed.
454762e2749eSChris Mason  */
4548e089f05cSChris Mason int btrfs_insert_item(struct btrfs_trans_handle *trans, struct btrfs_root
4549e089f05cSChris Mason 		      *root, struct btrfs_key *cpu_key, void *data, u32
4550e089f05cSChris Mason 		      data_size)
455162e2749eSChris Mason {
455262e2749eSChris Mason 	int ret = 0;
45532c90e5d6SChris Mason 	struct btrfs_path *path;
45545f39d397SChris Mason 	struct extent_buffer *leaf;
45555f39d397SChris Mason 	unsigned long ptr;
455662e2749eSChris Mason 
45572c90e5d6SChris Mason 	path = btrfs_alloc_path();
4558db5b493aSTsutomu Itoh 	if (!path)
4559db5b493aSTsutomu Itoh 		return -ENOMEM;
45602c90e5d6SChris Mason 	ret = btrfs_insert_empty_item(trans, root, path, cpu_key, data_size);
456162e2749eSChris Mason 	if (!ret) {
45625f39d397SChris Mason 		leaf = path->nodes[0];
45635f39d397SChris Mason 		ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
45645f39d397SChris Mason 		write_extent_buffer(leaf, data, ptr, data_size);
45655f39d397SChris Mason 		btrfs_mark_buffer_dirty(leaf);
456662e2749eSChris Mason 	}
45672c90e5d6SChris Mason 	btrfs_free_path(path);
4568aa5d6bedSChris Mason 	return ret;
4569be0e5c09SChris Mason }
4570be0e5c09SChris Mason 
457174123bd7SChris Mason /*
45725de08d7dSChris Mason  * delete the pointer from a given node.
457374123bd7SChris Mason  *
4574d352ac68SChris Mason  * the tree should have been previously balanced so the deletion does not
4575d352ac68SChris Mason  * empty a node.
457674123bd7SChris Mason  */
4577afe5fea7STsutomu Itoh static void del_ptr(struct btrfs_root *root, struct btrfs_path *path,
4578afe5fea7STsutomu Itoh 		    int level, int slot)
4579be0e5c09SChris Mason {
45805f39d397SChris Mason 	struct extent_buffer *parent = path->nodes[level];
45817518a238SChris Mason 	u32 nritems;
4582f3ea38daSJan Schmidt 	int ret;
4583be0e5c09SChris Mason 
45845f39d397SChris Mason 	nritems = btrfs_header_nritems(parent);
4585be0e5c09SChris Mason 	if (slot != nritems - 1) {
45860e411eceSLiu Bo 		if (level)
4587f3ea38daSJan Schmidt 			tree_mod_log_eb_move(root->fs_info, parent, slot,
4588f3ea38daSJan Schmidt 					     slot + 1, nritems - slot - 1);
45895f39d397SChris Mason 		memmove_extent_buffer(parent,
45905f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot),
45915f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot + 1),
4592d6025579SChris Mason 			      sizeof(struct btrfs_key_ptr) *
4593d6025579SChris Mason 			      (nritems - slot - 1));
459457ba86c0SChris Mason 	} else if (level) {
459557ba86c0SChris Mason 		ret = tree_mod_log_insert_key(root->fs_info, parent, slot,
4596*c8cc6341SJosef Bacik 					      MOD_LOG_KEY_REMOVE, GFP_NOFS);
459757ba86c0SChris Mason 		BUG_ON(ret < 0);
4598be0e5c09SChris Mason 	}
4599f3ea38daSJan Schmidt 
46007518a238SChris Mason 	nritems--;
46015f39d397SChris Mason 	btrfs_set_header_nritems(parent, nritems);
46027518a238SChris Mason 	if (nritems == 0 && parent == root->node) {
46035f39d397SChris Mason 		BUG_ON(btrfs_header_level(root->node) != 1);
4604eb60ceacSChris Mason 		/* just turn the root into a leaf and break */
46055f39d397SChris Mason 		btrfs_set_header_level(root->node, 0);
4606bb803951SChris Mason 	} else if (slot == 0) {
46075f39d397SChris Mason 		struct btrfs_disk_key disk_key;
46085f39d397SChris Mason 
46095f39d397SChris Mason 		btrfs_node_key(parent, &disk_key, 0);
4610d6a0a126STsutomu Itoh 		fixup_low_keys(root, path, &disk_key, level + 1);
4611be0e5c09SChris Mason 	}
4612d6025579SChris Mason 	btrfs_mark_buffer_dirty(parent);
4613be0e5c09SChris Mason }
4614be0e5c09SChris Mason 
461574123bd7SChris Mason /*
4616323ac95bSChris Mason  * a helper function to delete the leaf pointed to by path->slots[1] and
46175d4f98a2SYan Zheng  * path->nodes[1].
4618323ac95bSChris Mason  *
4619323ac95bSChris Mason  * This deletes the pointer in path->nodes[1] and frees the leaf
4620323ac95bSChris Mason  * block extent.  zero is returned if it all worked out, < 0 otherwise.
4621323ac95bSChris Mason  *
4622323ac95bSChris Mason  * The path must have already been setup for deleting the leaf, including
4623323ac95bSChris Mason  * all the proper balancing.  path->nodes[1] must be locked.
4624323ac95bSChris Mason  */
4625143bede5SJeff Mahoney static noinline void btrfs_del_leaf(struct btrfs_trans_handle *trans,
4626323ac95bSChris Mason 				    struct btrfs_root *root,
46275d4f98a2SYan Zheng 				    struct btrfs_path *path,
46285d4f98a2SYan Zheng 				    struct extent_buffer *leaf)
4629323ac95bSChris Mason {
46305d4f98a2SYan Zheng 	WARN_ON(btrfs_header_generation(leaf) != trans->transid);
4631afe5fea7STsutomu Itoh 	del_ptr(root, path, 1, path->slots[1]);
4632323ac95bSChris Mason 
46334d081c41SChris Mason 	/*
46344d081c41SChris Mason 	 * btrfs_free_extent is expensive, we want to make sure we
46354d081c41SChris Mason 	 * aren't holding any locks when we call it
46364d081c41SChris Mason 	 */
46374d081c41SChris Mason 	btrfs_unlock_up_safe(path, 0);
46384d081c41SChris Mason 
4639f0486c68SYan, Zheng 	root_sub_used(root, leaf->len);
4640f0486c68SYan, Zheng 
46413083ee2eSJosef Bacik 	extent_buffer_get(leaf);
46425581a51aSJan Schmidt 	btrfs_free_tree_block(trans, root, leaf, 0, 1);
46433083ee2eSJosef Bacik 	free_extent_buffer_stale(leaf);
4644323ac95bSChris Mason }
4645323ac95bSChris Mason /*
464674123bd7SChris Mason  * delete the item at the leaf level in path.  If that empties
464774123bd7SChris Mason  * the leaf, remove it from the tree
464874123bd7SChris Mason  */
464985e21bacSChris Mason int btrfs_del_items(struct btrfs_trans_handle *trans, struct btrfs_root *root,
465085e21bacSChris Mason 		    struct btrfs_path *path, int slot, int nr)
4651be0e5c09SChris Mason {
46525f39d397SChris Mason 	struct extent_buffer *leaf;
46535f39d397SChris Mason 	struct btrfs_item *item;
465485e21bacSChris Mason 	int last_off;
465585e21bacSChris Mason 	int dsize = 0;
4656aa5d6bedSChris Mason 	int ret = 0;
4657aa5d6bedSChris Mason 	int wret;
465885e21bacSChris Mason 	int i;
46597518a238SChris Mason 	u32 nritems;
4660cfed81a0SChris Mason 	struct btrfs_map_token token;
4661cfed81a0SChris Mason 
4662cfed81a0SChris Mason 	btrfs_init_map_token(&token);
4663be0e5c09SChris Mason 
46645f39d397SChris Mason 	leaf = path->nodes[0];
466585e21bacSChris Mason 	last_off = btrfs_item_offset_nr(leaf, slot + nr - 1);
466685e21bacSChris Mason 
466785e21bacSChris Mason 	for (i = 0; i < nr; i++)
466885e21bacSChris Mason 		dsize += btrfs_item_size_nr(leaf, slot + i);
466985e21bacSChris Mason 
46705f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
4671be0e5c09SChris Mason 
467285e21bacSChris Mason 	if (slot + nr != nritems) {
4673123abc88SChris Mason 		int data_end = leaf_data_end(root, leaf);
46745f39d397SChris Mason 
46755f39d397SChris Mason 		memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
4676d6025579SChris Mason 			      data_end + dsize,
4677123abc88SChris Mason 			      btrfs_leaf_data(leaf) + data_end,
467885e21bacSChris Mason 			      last_off - data_end);
46795f39d397SChris Mason 
468085e21bacSChris Mason 		for (i = slot + nr; i < nritems; i++) {
46815f39d397SChris Mason 			u32 ioff;
4682db94535dSChris Mason 
46835f39d397SChris Mason 			item = btrfs_item_nr(leaf, i);
4684cfed81a0SChris Mason 			ioff = btrfs_token_item_offset(leaf, item, &token);
4685cfed81a0SChris Mason 			btrfs_set_token_item_offset(leaf, item,
4686cfed81a0SChris Mason 						    ioff + dsize, &token);
46870783fcfcSChris Mason 		}
4688db94535dSChris Mason 
46895f39d397SChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot),
469085e21bacSChris Mason 			      btrfs_item_nr_offset(slot + nr),
46910783fcfcSChris Mason 			      sizeof(struct btrfs_item) *
469285e21bacSChris Mason 			      (nritems - slot - nr));
4693be0e5c09SChris Mason 	}
469485e21bacSChris Mason 	btrfs_set_header_nritems(leaf, nritems - nr);
469585e21bacSChris Mason 	nritems -= nr;
46965f39d397SChris Mason 
469774123bd7SChris Mason 	/* delete the leaf if we've emptied it */
46987518a238SChris Mason 	if (nritems == 0) {
46995f39d397SChris Mason 		if (leaf == root->node) {
47005f39d397SChris Mason 			btrfs_set_header_level(leaf, 0);
47019a8dd150SChris Mason 		} else {
4702f0486c68SYan, Zheng 			btrfs_set_path_blocking(path);
4703f0486c68SYan, Zheng 			clean_tree_block(trans, root, leaf);
4704143bede5SJeff Mahoney 			btrfs_del_leaf(trans, root, path, leaf);
47059a8dd150SChris Mason 		}
4706be0e5c09SChris Mason 	} else {
47077518a238SChris Mason 		int used = leaf_space_used(leaf, 0, nritems);
4708aa5d6bedSChris Mason 		if (slot == 0) {
47095f39d397SChris Mason 			struct btrfs_disk_key disk_key;
47105f39d397SChris Mason 
47115f39d397SChris Mason 			btrfs_item_key(leaf, &disk_key, 0);
4712d6a0a126STsutomu Itoh 			fixup_low_keys(root, path, &disk_key, 1);
4713aa5d6bedSChris Mason 		}
4714aa5d6bedSChris Mason 
471574123bd7SChris Mason 		/* delete the leaf if it is mostly empty */
4716d717aa1dSYan Zheng 		if (used < BTRFS_LEAF_DATA_SIZE(root) / 3) {
4717be0e5c09SChris Mason 			/* push_leaf_left fixes the path.
4718be0e5c09SChris Mason 			 * make sure the path still points to our leaf
4719be0e5c09SChris Mason 			 * for possible call to del_ptr below
4720be0e5c09SChris Mason 			 */
47214920c9acSChris Mason 			slot = path->slots[1];
47225f39d397SChris Mason 			extent_buffer_get(leaf);
47235f39d397SChris Mason 
4724b9473439SChris Mason 			btrfs_set_path_blocking(path);
472599d8f83cSChris Mason 			wret = push_leaf_left(trans, root, path, 1, 1,
472699d8f83cSChris Mason 					      1, (u32)-1);
472754aa1f4dSChris Mason 			if (wret < 0 && wret != -ENOSPC)
4728aa5d6bedSChris Mason 				ret = wret;
47295f39d397SChris Mason 
47305f39d397SChris Mason 			if (path->nodes[0] == leaf &&
47315f39d397SChris Mason 			    btrfs_header_nritems(leaf)) {
473299d8f83cSChris Mason 				wret = push_leaf_right(trans, root, path, 1,
473399d8f83cSChris Mason 						       1, 1, 0);
473454aa1f4dSChris Mason 				if (wret < 0 && wret != -ENOSPC)
4735aa5d6bedSChris Mason 					ret = wret;
4736aa5d6bedSChris Mason 			}
47375f39d397SChris Mason 
47385f39d397SChris Mason 			if (btrfs_header_nritems(leaf) == 0) {
4739323ac95bSChris Mason 				path->slots[1] = slot;
4740143bede5SJeff Mahoney 				btrfs_del_leaf(trans, root, path, leaf);
47415f39d397SChris Mason 				free_extent_buffer(leaf);
4742143bede5SJeff Mahoney 				ret = 0;
47435de08d7dSChris Mason 			} else {
4744925baeddSChris Mason 				/* if we're still in the path, make sure
4745925baeddSChris Mason 				 * we're dirty.  Otherwise, one of the
4746925baeddSChris Mason 				 * push_leaf functions must have already
4747925baeddSChris Mason 				 * dirtied this buffer
4748925baeddSChris Mason 				 */
4749925baeddSChris Mason 				if (path->nodes[0] == leaf)
47505f39d397SChris Mason 					btrfs_mark_buffer_dirty(leaf);
47515f39d397SChris Mason 				free_extent_buffer(leaf);
4752be0e5c09SChris Mason 			}
4753d5719762SChris Mason 		} else {
47545f39d397SChris Mason 			btrfs_mark_buffer_dirty(leaf);
4755be0e5c09SChris Mason 		}
47569a8dd150SChris Mason 	}
4757aa5d6bedSChris Mason 	return ret;
47589a8dd150SChris Mason }
47599a8dd150SChris Mason 
476097571fd0SChris Mason /*
4761925baeddSChris Mason  * search the tree again to find a leaf with lesser keys
47627bb86316SChris Mason  * returns 0 if it found something or 1 if there are no lesser leaves.
47637bb86316SChris Mason  * returns < 0 on io errors.
4764d352ac68SChris Mason  *
4765d352ac68SChris Mason  * This may release the path, and so you may lose any locks held at the
4766d352ac68SChris Mason  * time you call it.
47677bb86316SChris Mason  */
47687bb86316SChris Mason int btrfs_prev_leaf(struct btrfs_root *root, struct btrfs_path *path)
47697bb86316SChris Mason {
4770925baeddSChris Mason 	struct btrfs_key key;
4771925baeddSChris Mason 	struct btrfs_disk_key found_key;
4772925baeddSChris Mason 	int ret;
47737bb86316SChris Mason 
4774925baeddSChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, 0);
4775925baeddSChris Mason 
4776925baeddSChris Mason 	if (key.offset > 0)
4777925baeddSChris Mason 		key.offset--;
4778925baeddSChris Mason 	else if (key.type > 0)
4779925baeddSChris Mason 		key.type--;
4780925baeddSChris Mason 	else if (key.objectid > 0)
4781925baeddSChris Mason 		key.objectid--;
4782925baeddSChris Mason 	else
47837bb86316SChris Mason 		return 1;
47847bb86316SChris Mason 
4785b3b4aa74SDavid Sterba 	btrfs_release_path(path);
4786925baeddSChris Mason 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4787925baeddSChris Mason 	if (ret < 0)
4788925baeddSChris Mason 		return ret;
4789925baeddSChris Mason 	btrfs_item_key(path->nodes[0], &found_key, 0);
4790925baeddSChris Mason 	ret = comp_keys(&found_key, &key);
4791925baeddSChris Mason 	if (ret < 0)
47927bb86316SChris Mason 		return 0;
4793925baeddSChris Mason 	return 1;
47947bb86316SChris Mason }
47957bb86316SChris Mason 
47963f157a2fSChris Mason /*
47973f157a2fSChris Mason  * A helper function to walk down the tree starting at min_key, and looking
4798de78b51aSEric Sandeen  * for nodes or leaves that are have a minimum transaction id.
4799de78b51aSEric Sandeen  * This is used by the btree defrag code, and tree logging
48003f157a2fSChris Mason  *
48013f157a2fSChris Mason  * This does not cow, but it does stuff the starting key it finds back
48023f157a2fSChris Mason  * into min_key, so you can call btrfs_search_slot with cow=1 on the
48033f157a2fSChris Mason  * key and get a writable path.
48043f157a2fSChris Mason  *
48053f157a2fSChris Mason  * This does lock as it descends, and path->keep_locks should be set
48063f157a2fSChris Mason  * to 1 by the caller.
48073f157a2fSChris Mason  *
48083f157a2fSChris Mason  * This honors path->lowest_level to prevent descent past a given level
48093f157a2fSChris Mason  * of the tree.
48103f157a2fSChris Mason  *
4811d352ac68SChris Mason  * min_trans indicates the oldest transaction that you are interested
4812d352ac68SChris Mason  * in walking through.  Any nodes or leaves older than min_trans are
4813d352ac68SChris Mason  * skipped over (without reading them).
4814d352ac68SChris Mason  *
48153f157a2fSChris Mason  * returns zero if something useful was found, < 0 on error and 1 if there
48163f157a2fSChris Mason  * was nothing in the tree that matched the search criteria.
48173f157a2fSChris Mason  */
48183f157a2fSChris Mason int btrfs_search_forward(struct btrfs_root *root, struct btrfs_key *min_key,
4819e02119d5SChris Mason 			 struct btrfs_key *max_key,
4820de78b51aSEric Sandeen 			 struct btrfs_path *path,
48213f157a2fSChris Mason 			 u64 min_trans)
48223f157a2fSChris Mason {
48233f157a2fSChris Mason 	struct extent_buffer *cur;
48243f157a2fSChris Mason 	struct btrfs_key found_key;
48253f157a2fSChris Mason 	int slot;
48269652480bSYan 	int sret;
48273f157a2fSChris Mason 	u32 nritems;
48283f157a2fSChris Mason 	int level;
48293f157a2fSChris Mason 	int ret = 1;
48303f157a2fSChris Mason 
4831934d375bSChris Mason 	WARN_ON(!path->keep_locks);
48323f157a2fSChris Mason again:
4833bd681513SChris Mason 	cur = btrfs_read_lock_root_node(root);
48343f157a2fSChris Mason 	level = btrfs_header_level(cur);
4835e02119d5SChris Mason 	WARN_ON(path->nodes[level]);
48363f157a2fSChris Mason 	path->nodes[level] = cur;
4837bd681513SChris Mason 	path->locks[level] = BTRFS_READ_LOCK;
48383f157a2fSChris Mason 
48393f157a2fSChris Mason 	if (btrfs_header_generation(cur) < min_trans) {
48403f157a2fSChris Mason 		ret = 1;
48413f157a2fSChris Mason 		goto out;
48423f157a2fSChris Mason 	}
48433f157a2fSChris Mason 	while (1) {
48443f157a2fSChris Mason 		nritems = btrfs_header_nritems(cur);
48453f157a2fSChris Mason 		level = btrfs_header_level(cur);
48469652480bSYan 		sret = bin_search(cur, min_key, level, &slot);
48473f157a2fSChris Mason 
4848323ac95bSChris Mason 		/* at the lowest level, we're done, setup the path and exit */
4849323ac95bSChris Mason 		if (level == path->lowest_level) {
4850e02119d5SChris Mason 			if (slot >= nritems)
4851e02119d5SChris Mason 				goto find_next_key;
48523f157a2fSChris Mason 			ret = 0;
48533f157a2fSChris Mason 			path->slots[level] = slot;
48543f157a2fSChris Mason 			btrfs_item_key_to_cpu(cur, &found_key, slot);
48553f157a2fSChris Mason 			goto out;
48563f157a2fSChris Mason 		}
48579652480bSYan 		if (sret && slot > 0)
48589652480bSYan 			slot--;
48593f157a2fSChris Mason 		/*
4860de78b51aSEric Sandeen 		 * check this node pointer against the min_trans parameters.
4861de78b51aSEric Sandeen 		 * If it is too old, old, skip to the next one.
48623f157a2fSChris Mason 		 */
48633f157a2fSChris Mason 		while (slot < nritems) {
48643f157a2fSChris Mason 			u64 blockptr;
48653f157a2fSChris Mason 			u64 gen;
4866e02119d5SChris Mason 
48673f157a2fSChris Mason 			blockptr = btrfs_node_blockptr(cur, slot);
48683f157a2fSChris Mason 			gen = btrfs_node_ptr_generation(cur, slot);
48693f157a2fSChris Mason 			if (gen < min_trans) {
48703f157a2fSChris Mason 				slot++;
48713f157a2fSChris Mason 				continue;
48723f157a2fSChris Mason 			}
48733f157a2fSChris Mason 			break;
48743f157a2fSChris Mason 		}
4875e02119d5SChris Mason find_next_key:
48763f157a2fSChris Mason 		/*
48773f157a2fSChris Mason 		 * we didn't find a candidate key in this node, walk forward
48783f157a2fSChris Mason 		 * and find another one
48793f157a2fSChris Mason 		 */
48803f157a2fSChris Mason 		if (slot >= nritems) {
4881e02119d5SChris Mason 			path->slots[level] = slot;
4882b4ce94deSChris Mason 			btrfs_set_path_blocking(path);
4883e02119d5SChris Mason 			sret = btrfs_find_next_key(root, path, min_key, level,
4884de78b51aSEric Sandeen 						  min_trans);
4885e02119d5SChris Mason 			if (sret == 0) {
4886b3b4aa74SDavid Sterba 				btrfs_release_path(path);
48873f157a2fSChris Mason 				goto again;
48883f157a2fSChris Mason 			} else {
48893f157a2fSChris Mason 				goto out;
48903f157a2fSChris Mason 			}
48913f157a2fSChris Mason 		}
48923f157a2fSChris Mason 		/* save our key for returning back */
48933f157a2fSChris Mason 		btrfs_node_key_to_cpu(cur, &found_key, slot);
48943f157a2fSChris Mason 		path->slots[level] = slot;
48953f157a2fSChris Mason 		if (level == path->lowest_level) {
48963f157a2fSChris Mason 			ret = 0;
4897f7c79f30SChris Mason 			unlock_up(path, level, 1, 0, NULL);
48983f157a2fSChris Mason 			goto out;
48993f157a2fSChris Mason 		}
4900b4ce94deSChris Mason 		btrfs_set_path_blocking(path);
49013f157a2fSChris Mason 		cur = read_node_slot(root, cur, slot);
490279787eaaSJeff Mahoney 		BUG_ON(!cur); /* -ENOMEM */
49033f157a2fSChris Mason 
4904bd681513SChris Mason 		btrfs_tree_read_lock(cur);
4905b4ce94deSChris Mason 
4906bd681513SChris Mason 		path->locks[level - 1] = BTRFS_READ_LOCK;
49073f157a2fSChris Mason 		path->nodes[level - 1] = cur;
4908f7c79f30SChris Mason 		unlock_up(path, level, 1, 0, NULL);
4909bd681513SChris Mason 		btrfs_clear_path_blocking(path, NULL, 0);
49103f157a2fSChris Mason 	}
49113f157a2fSChris Mason out:
49123f157a2fSChris Mason 	if (ret == 0)
49133f157a2fSChris Mason 		memcpy(min_key, &found_key, sizeof(found_key));
4914b4ce94deSChris Mason 	btrfs_set_path_blocking(path);
49153f157a2fSChris Mason 	return ret;
49163f157a2fSChris Mason }
49173f157a2fSChris Mason 
49187069830aSAlexander Block static void tree_move_down(struct btrfs_root *root,
49197069830aSAlexander Block 			   struct btrfs_path *path,
49207069830aSAlexander Block 			   int *level, int root_level)
49217069830aSAlexander Block {
492274dd17fbSChris Mason 	BUG_ON(*level == 0);
49237069830aSAlexander Block 	path->nodes[*level - 1] = read_node_slot(root, path->nodes[*level],
49247069830aSAlexander Block 					path->slots[*level]);
49257069830aSAlexander Block 	path->slots[*level - 1] = 0;
49267069830aSAlexander Block 	(*level)--;
49277069830aSAlexander Block }
49287069830aSAlexander Block 
49297069830aSAlexander Block static int tree_move_next_or_upnext(struct btrfs_root *root,
49307069830aSAlexander Block 				    struct btrfs_path *path,
49317069830aSAlexander Block 				    int *level, int root_level)
49327069830aSAlexander Block {
49337069830aSAlexander Block 	int ret = 0;
49347069830aSAlexander Block 	int nritems;
49357069830aSAlexander Block 	nritems = btrfs_header_nritems(path->nodes[*level]);
49367069830aSAlexander Block 
49377069830aSAlexander Block 	path->slots[*level]++;
49387069830aSAlexander Block 
493974dd17fbSChris Mason 	while (path->slots[*level] >= nritems) {
49407069830aSAlexander Block 		if (*level == root_level)
49417069830aSAlexander Block 			return -1;
49427069830aSAlexander Block 
49437069830aSAlexander Block 		/* move upnext */
49447069830aSAlexander Block 		path->slots[*level] = 0;
49457069830aSAlexander Block 		free_extent_buffer(path->nodes[*level]);
49467069830aSAlexander Block 		path->nodes[*level] = NULL;
49477069830aSAlexander Block 		(*level)++;
49487069830aSAlexander Block 		path->slots[*level]++;
49497069830aSAlexander Block 
49507069830aSAlexander Block 		nritems = btrfs_header_nritems(path->nodes[*level]);
49517069830aSAlexander Block 		ret = 1;
49527069830aSAlexander Block 	}
49537069830aSAlexander Block 	return ret;
49547069830aSAlexander Block }
49557069830aSAlexander Block 
49567069830aSAlexander Block /*
49577069830aSAlexander Block  * Returns 1 if it had to move up and next. 0 is returned if it moved only next
49587069830aSAlexander Block  * or down.
49597069830aSAlexander Block  */
49607069830aSAlexander Block static int tree_advance(struct btrfs_root *root,
49617069830aSAlexander Block 			struct btrfs_path *path,
49627069830aSAlexander Block 			int *level, int root_level,
49637069830aSAlexander Block 			int allow_down,
49647069830aSAlexander Block 			struct btrfs_key *key)
49657069830aSAlexander Block {
49667069830aSAlexander Block 	int ret;
49677069830aSAlexander Block 
49687069830aSAlexander Block 	if (*level == 0 || !allow_down) {
49697069830aSAlexander Block 		ret = tree_move_next_or_upnext(root, path, level, root_level);
49707069830aSAlexander Block 	} else {
49717069830aSAlexander Block 		tree_move_down(root, path, level, root_level);
49727069830aSAlexander Block 		ret = 0;
49737069830aSAlexander Block 	}
49747069830aSAlexander Block 	if (ret >= 0) {
49757069830aSAlexander Block 		if (*level == 0)
49767069830aSAlexander Block 			btrfs_item_key_to_cpu(path->nodes[*level], key,
49777069830aSAlexander Block 					path->slots[*level]);
49787069830aSAlexander Block 		else
49797069830aSAlexander Block 			btrfs_node_key_to_cpu(path->nodes[*level], key,
49807069830aSAlexander Block 					path->slots[*level]);
49817069830aSAlexander Block 	}
49827069830aSAlexander Block 	return ret;
49837069830aSAlexander Block }
49847069830aSAlexander Block 
49857069830aSAlexander Block static int tree_compare_item(struct btrfs_root *left_root,
49867069830aSAlexander Block 			     struct btrfs_path *left_path,
49877069830aSAlexander Block 			     struct btrfs_path *right_path,
49887069830aSAlexander Block 			     char *tmp_buf)
49897069830aSAlexander Block {
49907069830aSAlexander Block 	int cmp;
49917069830aSAlexander Block 	int len1, len2;
49927069830aSAlexander Block 	unsigned long off1, off2;
49937069830aSAlexander Block 
49947069830aSAlexander Block 	len1 = btrfs_item_size_nr(left_path->nodes[0], left_path->slots[0]);
49957069830aSAlexander Block 	len2 = btrfs_item_size_nr(right_path->nodes[0], right_path->slots[0]);
49967069830aSAlexander Block 	if (len1 != len2)
49977069830aSAlexander Block 		return 1;
49987069830aSAlexander Block 
49997069830aSAlexander Block 	off1 = btrfs_item_ptr_offset(left_path->nodes[0], left_path->slots[0]);
50007069830aSAlexander Block 	off2 = btrfs_item_ptr_offset(right_path->nodes[0],
50017069830aSAlexander Block 				right_path->slots[0]);
50027069830aSAlexander Block 
50037069830aSAlexander Block 	read_extent_buffer(left_path->nodes[0], tmp_buf, off1, len1);
50047069830aSAlexander Block 
50057069830aSAlexander Block 	cmp = memcmp_extent_buffer(right_path->nodes[0], tmp_buf, off2, len1);
50067069830aSAlexander Block 	if (cmp)
50077069830aSAlexander Block 		return 1;
50087069830aSAlexander Block 	return 0;
50097069830aSAlexander Block }
50107069830aSAlexander Block 
50117069830aSAlexander Block #define ADVANCE 1
50127069830aSAlexander Block #define ADVANCE_ONLY_NEXT -1
50137069830aSAlexander Block 
50147069830aSAlexander Block /*
50157069830aSAlexander Block  * This function compares two trees and calls the provided callback for
50167069830aSAlexander Block  * every changed/new/deleted item it finds.
50177069830aSAlexander Block  * If shared tree blocks are encountered, whole subtrees are skipped, making
50187069830aSAlexander Block  * the compare pretty fast on snapshotted subvolumes.
50197069830aSAlexander Block  *
50207069830aSAlexander Block  * This currently works on commit roots only. As commit roots are read only,
50217069830aSAlexander Block  * we don't do any locking. The commit roots are protected with transactions.
50227069830aSAlexander Block  * Transactions are ended and rejoined when a commit is tried in between.
50237069830aSAlexander Block  *
50247069830aSAlexander Block  * This function checks for modifications done to the trees while comparing.
50257069830aSAlexander Block  * If it detects a change, it aborts immediately.
50267069830aSAlexander Block  */
50277069830aSAlexander Block int btrfs_compare_trees(struct btrfs_root *left_root,
50287069830aSAlexander Block 			struct btrfs_root *right_root,
50297069830aSAlexander Block 			btrfs_changed_cb_t changed_cb, void *ctx)
50307069830aSAlexander Block {
50317069830aSAlexander Block 	int ret;
50327069830aSAlexander Block 	int cmp;
50337069830aSAlexander Block 	struct btrfs_trans_handle *trans = NULL;
50347069830aSAlexander Block 	struct btrfs_path *left_path = NULL;
50357069830aSAlexander Block 	struct btrfs_path *right_path = NULL;
50367069830aSAlexander Block 	struct btrfs_key left_key;
50377069830aSAlexander Block 	struct btrfs_key right_key;
50387069830aSAlexander Block 	char *tmp_buf = NULL;
50397069830aSAlexander Block 	int left_root_level;
50407069830aSAlexander Block 	int right_root_level;
50417069830aSAlexander Block 	int left_level;
50427069830aSAlexander Block 	int right_level;
50437069830aSAlexander Block 	int left_end_reached;
50447069830aSAlexander Block 	int right_end_reached;
50457069830aSAlexander Block 	int advance_left;
50467069830aSAlexander Block 	int advance_right;
50477069830aSAlexander Block 	u64 left_blockptr;
50487069830aSAlexander Block 	u64 right_blockptr;
50497069830aSAlexander Block 	u64 left_start_ctransid;
50507069830aSAlexander Block 	u64 right_start_ctransid;
50517069830aSAlexander Block 	u64 ctransid;
50527069830aSAlexander Block 
50537069830aSAlexander Block 	left_path = btrfs_alloc_path();
50547069830aSAlexander Block 	if (!left_path) {
50557069830aSAlexander Block 		ret = -ENOMEM;
50567069830aSAlexander Block 		goto out;
50577069830aSAlexander Block 	}
50587069830aSAlexander Block 	right_path = btrfs_alloc_path();
50597069830aSAlexander Block 	if (!right_path) {
50607069830aSAlexander Block 		ret = -ENOMEM;
50617069830aSAlexander Block 		goto out;
50627069830aSAlexander Block 	}
50637069830aSAlexander Block 
50647069830aSAlexander Block 	tmp_buf = kmalloc(left_root->leafsize, GFP_NOFS);
50657069830aSAlexander Block 	if (!tmp_buf) {
50667069830aSAlexander Block 		ret = -ENOMEM;
50677069830aSAlexander Block 		goto out;
50687069830aSAlexander Block 	}
50697069830aSAlexander Block 
50707069830aSAlexander Block 	left_path->search_commit_root = 1;
50717069830aSAlexander Block 	left_path->skip_locking = 1;
50727069830aSAlexander Block 	right_path->search_commit_root = 1;
50737069830aSAlexander Block 	right_path->skip_locking = 1;
50747069830aSAlexander Block 
50755f3ab90aSAnand Jain 	spin_lock(&left_root->root_item_lock);
50767069830aSAlexander Block 	left_start_ctransid = btrfs_root_ctransid(&left_root->root_item);
50775f3ab90aSAnand Jain 	spin_unlock(&left_root->root_item_lock);
50787069830aSAlexander Block 
50795f3ab90aSAnand Jain 	spin_lock(&right_root->root_item_lock);
50807069830aSAlexander Block 	right_start_ctransid = btrfs_root_ctransid(&right_root->root_item);
50815f3ab90aSAnand Jain 	spin_unlock(&right_root->root_item_lock);
50827069830aSAlexander Block 
50837069830aSAlexander Block 	trans = btrfs_join_transaction(left_root);
50847069830aSAlexander Block 	if (IS_ERR(trans)) {
50857069830aSAlexander Block 		ret = PTR_ERR(trans);
50867069830aSAlexander Block 		trans = NULL;
50877069830aSAlexander Block 		goto out;
50887069830aSAlexander Block 	}
50897069830aSAlexander Block 
50907069830aSAlexander Block 	/*
50917069830aSAlexander Block 	 * Strategy: Go to the first items of both trees. Then do
50927069830aSAlexander Block 	 *
50937069830aSAlexander Block 	 * If both trees are at level 0
50947069830aSAlexander Block 	 *   Compare keys of current items
50957069830aSAlexander Block 	 *     If left < right treat left item as new, advance left tree
50967069830aSAlexander Block 	 *       and repeat
50977069830aSAlexander Block 	 *     If left > right treat right item as deleted, advance right tree
50987069830aSAlexander Block 	 *       and repeat
50997069830aSAlexander Block 	 *     If left == right do deep compare of items, treat as changed if
51007069830aSAlexander Block 	 *       needed, advance both trees and repeat
51017069830aSAlexander Block 	 * If both trees are at the same level but not at level 0
51027069830aSAlexander Block 	 *   Compare keys of current nodes/leafs
51037069830aSAlexander Block 	 *     If left < right advance left tree and repeat
51047069830aSAlexander Block 	 *     If left > right advance right tree and repeat
51057069830aSAlexander Block 	 *     If left == right compare blockptrs of the next nodes/leafs
51067069830aSAlexander Block 	 *       If they match advance both trees but stay at the same level
51077069830aSAlexander Block 	 *         and repeat
51087069830aSAlexander Block 	 *       If they don't match advance both trees while allowing to go
51097069830aSAlexander Block 	 *         deeper and repeat
51107069830aSAlexander Block 	 * If tree levels are different
51117069830aSAlexander Block 	 *   Advance the tree that needs it and repeat
51127069830aSAlexander Block 	 *
51137069830aSAlexander Block 	 * Advancing a tree means:
51147069830aSAlexander Block 	 *   If we are at level 0, try to go to the next slot. If that's not
51157069830aSAlexander Block 	 *   possible, go one level up and repeat. Stop when we found a level
51167069830aSAlexander Block 	 *   where we could go to the next slot. We may at this point be on a
51177069830aSAlexander Block 	 *   node or a leaf.
51187069830aSAlexander Block 	 *
51197069830aSAlexander Block 	 *   If we are not at level 0 and not on shared tree blocks, go one
51207069830aSAlexander Block 	 *   level deeper.
51217069830aSAlexander Block 	 *
51227069830aSAlexander Block 	 *   If we are not at level 0 and on shared tree blocks, go one slot to
51237069830aSAlexander Block 	 *   the right if possible or go up and right.
51247069830aSAlexander Block 	 */
51257069830aSAlexander Block 
51267069830aSAlexander Block 	left_level = btrfs_header_level(left_root->commit_root);
51277069830aSAlexander Block 	left_root_level = left_level;
51287069830aSAlexander Block 	left_path->nodes[left_level] = left_root->commit_root;
51297069830aSAlexander Block 	extent_buffer_get(left_path->nodes[left_level]);
51307069830aSAlexander Block 
51317069830aSAlexander Block 	right_level = btrfs_header_level(right_root->commit_root);
51327069830aSAlexander Block 	right_root_level = right_level;
51337069830aSAlexander Block 	right_path->nodes[right_level] = right_root->commit_root;
51347069830aSAlexander Block 	extent_buffer_get(right_path->nodes[right_level]);
51357069830aSAlexander Block 
51367069830aSAlexander Block 	if (left_level == 0)
51377069830aSAlexander Block 		btrfs_item_key_to_cpu(left_path->nodes[left_level],
51387069830aSAlexander Block 				&left_key, left_path->slots[left_level]);
51397069830aSAlexander Block 	else
51407069830aSAlexander Block 		btrfs_node_key_to_cpu(left_path->nodes[left_level],
51417069830aSAlexander Block 				&left_key, left_path->slots[left_level]);
51427069830aSAlexander Block 	if (right_level == 0)
51437069830aSAlexander Block 		btrfs_item_key_to_cpu(right_path->nodes[right_level],
51447069830aSAlexander Block 				&right_key, right_path->slots[right_level]);
51457069830aSAlexander Block 	else
51467069830aSAlexander Block 		btrfs_node_key_to_cpu(right_path->nodes[right_level],
51477069830aSAlexander Block 				&right_key, right_path->slots[right_level]);
51487069830aSAlexander Block 
51497069830aSAlexander Block 	left_end_reached = right_end_reached = 0;
51507069830aSAlexander Block 	advance_left = advance_right = 0;
51517069830aSAlexander Block 
51527069830aSAlexander Block 	while (1) {
51537069830aSAlexander Block 		/*
51547069830aSAlexander Block 		 * We need to make sure the transaction does not get committed
51557069830aSAlexander Block 		 * while we do anything on commit roots. This means, we need to
51567069830aSAlexander Block 		 * join and leave transactions for every item that we process.
51577069830aSAlexander Block 		 */
51587069830aSAlexander Block 		if (trans && btrfs_should_end_transaction(trans, left_root)) {
51597069830aSAlexander Block 			btrfs_release_path(left_path);
51607069830aSAlexander Block 			btrfs_release_path(right_path);
51617069830aSAlexander Block 
51627069830aSAlexander Block 			ret = btrfs_end_transaction(trans, left_root);
51637069830aSAlexander Block 			trans = NULL;
51647069830aSAlexander Block 			if (ret < 0)
51657069830aSAlexander Block 				goto out;
51667069830aSAlexander Block 		}
51677069830aSAlexander Block 		/* now rejoin the transaction */
51687069830aSAlexander Block 		if (!trans) {
51697069830aSAlexander Block 			trans = btrfs_join_transaction(left_root);
51707069830aSAlexander Block 			if (IS_ERR(trans)) {
51717069830aSAlexander Block 				ret = PTR_ERR(trans);
51727069830aSAlexander Block 				trans = NULL;
51737069830aSAlexander Block 				goto out;
51747069830aSAlexander Block 			}
51757069830aSAlexander Block 
51765f3ab90aSAnand Jain 			spin_lock(&left_root->root_item_lock);
51777069830aSAlexander Block 			ctransid = btrfs_root_ctransid(&left_root->root_item);
51785f3ab90aSAnand Jain 			spin_unlock(&left_root->root_item_lock);
51797069830aSAlexander Block 			if (ctransid != left_start_ctransid)
51807069830aSAlexander Block 				left_start_ctransid = 0;
51817069830aSAlexander Block 
51825f3ab90aSAnand Jain 			spin_lock(&right_root->root_item_lock);
51837069830aSAlexander Block 			ctransid = btrfs_root_ctransid(&right_root->root_item);
51845f3ab90aSAnand Jain 			spin_unlock(&right_root->root_item_lock);
51857069830aSAlexander Block 			if (ctransid != right_start_ctransid)
51867069830aSAlexander Block 				right_start_ctransid = 0;
51877069830aSAlexander Block 
51887069830aSAlexander Block 			if (!left_start_ctransid || !right_start_ctransid) {
51897069830aSAlexander Block 				WARN(1, KERN_WARNING
51907069830aSAlexander Block 					"btrfs: btrfs_compare_tree detected "
51917069830aSAlexander Block 					"a change in one of the trees while "
51927069830aSAlexander Block 					"iterating. This is probably a "
51937069830aSAlexander Block 					"bug.\n");
51947069830aSAlexander Block 				ret = -EIO;
51957069830aSAlexander Block 				goto out;
51967069830aSAlexander Block 			}
51977069830aSAlexander Block 
51987069830aSAlexander Block 			/*
51997069830aSAlexander Block 			 * the commit root may have changed, so start again
52007069830aSAlexander Block 			 * where we stopped
52017069830aSAlexander Block 			 */
52027069830aSAlexander Block 			left_path->lowest_level = left_level;
52037069830aSAlexander Block 			right_path->lowest_level = right_level;
52047069830aSAlexander Block 			ret = btrfs_search_slot(NULL, left_root,
52057069830aSAlexander Block 					&left_key, left_path, 0, 0);
52067069830aSAlexander Block 			if (ret < 0)
52077069830aSAlexander Block 				goto out;
52087069830aSAlexander Block 			ret = btrfs_search_slot(NULL, right_root,
52097069830aSAlexander Block 					&right_key, right_path, 0, 0);
52107069830aSAlexander Block 			if (ret < 0)
52117069830aSAlexander Block 				goto out;
52127069830aSAlexander Block 		}
52137069830aSAlexander Block 
52147069830aSAlexander Block 		if (advance_left && !left_end_reached) {
52157069830aSAlexander Block 			ret = tree_advance(left_root, left_path, &left_level,
52167069830aSAlexander Block 					left_root_level,
52177069830aSAlexander Block 					advance_left != ADVANCE_ONLY_NEXT,
52187069830aSAlexander Block 					&left_key);
52197069830aSAlexander Block 			if (ret < 0)
52207069830aSAlexander Block 				left_end_reached = ADVANCE;
52217069830aSAlexander Block 			advance_left = 0;
52227069830aSAlexander Block 		}
52237069830aSAlexander Block 		if (advance_right && !right_end_reached) {
52247069830aSAlexander Block 			ret = tree_advance(right_root, right_path, &right_level,
52257069830aSAlexander Block 					right_root_level,
52267069830aSAlexander Block 					advance_right != ADVANCE_ONLY_NEXT,
52277069830aSAlexander Block 					&right_key);
52287069830aSAlexander Block 			if (ret < 0)
52297069830aSAlexander Block 				right_end_reached = ADVANCE;
52307069830aSAlexander Block 			advance_right = 0;
52317069830aSAlexander Block 		}
52327069830aSAlexander Block 
52337069830aSAlexander Block 		if (left_end_reached && right_end_reached) {
52347069830aSAlexander Block 			ret = 0;
52357069830aSAlexander Block 			goto out;
52367069830aSAlexander Block 		} else if (left_end_reached) {
52377069830aSAlexander Block 			if (right_level == 0) {
52387069830aSAlexander Block 				ret = changed_cb(left_root, right_root,
52397069830aSAlexander Block 						left_path, right_path,
52407069830aSAlexander Block 						&right_key,
52417069830aSAlexander Block 						BTRFS_COMPARE_TREE_DELETED,
52427069830aSAlexander Block 						ctx);
52437069830aSAlexander Block 				if (ret < 0)
52447069830aSAlexander Block 					goto out;
52457069830aSAlexander Block 			}
52467069830aSAlexander Block 			advance_right = ADVANCE;
52477069830aSAlexander Block 			continue;
52487069830aSAlexander Block 		} else if (right_end_reached) {
52497069830aSAlexander Block 			if (left_level == 0) {
52507069830aSAlexander Block 				ret = changed_cb(left_root, right_root,
52517069830aSAlexander Block 						left_path, right_path,
52527069830aSAlexander Block 						&left_key,
52537069830aSAlexander Block 						BTRFS_COMPARE_TREE_NEW,
52547069830aSAlexander Block 						ctx);
52557069830aSAlexander Block 				if (ret < 0)
52567069830aSAlexander Block 					goto out;
52577069830aSAlexander Block 			}
52587069830aSAlexander Block 			advance_left = ADVANCE;
52597069830aSAlexander Block 			continue;
52607069830aSAlexander Block 		}
52617069830aSAlexander Block 
52627069830aSAlexander Block 		if (left_level == 0 && right_level == 0) {
52637069830aSAlexander Block 			cmp = btrfs_comp_cpu_keys(&left_key, &right_key);
52647069830aSAlexander Block 			if (cmp < 0) {
52657069830aSAlexander Block 				ret = changed_cb(left_root, right_root,
52667069830aSAlexander Block 						left_path, right_path,
52677069830aSAlexander Block 						&left_key,
52687069830aSAlexander Block 						BTRFS_COMPARE_TREE_NEW,
52697069830aSAlexander Block 						ctx);
52707069830aSAlexander Block 				if (ret < 0)
52717069830aSAlexander Block 					goto out;
52727069830aSAlexander Block 				advance_left = ADVANCE;
52737069830aSAlexander Block 			} else if (cmp > 0) {
52747069830aSAlexander Block 				ret = changed_cb(left_root, right_root,
52757069830aSAlexander Block 						left_path, right_path,
52767069830aSAlexander Block 						&right_key,
52777069830aSAlexander Block 						BTRFS_COMPARE_TREE_DELETED,
52787069830aSAlexander Block 						ctx);
52797069830aSAlexander Block 				if (ret < 0)
52807069830aSAlexander Block 					goto out;
52817069830aSAlexander Block 				advance_right = ADVANCE;
52827069830aSAlexander Block 			} else {
528374dd17fbSChris Mason 				WARN_ON(!extent_buffer_uptodate(left_path->nodes[0]));
52847069830aSAlexander Block 				ret = tree_compare_item(left_root, left_path,
52857069830aSAlexander Block 						right_path, tmp_buf);
52867069830aSAlexander Block 				if (ret) {
528774dd17fbSChris Mason 					WARN_ON(!extent_buffer_uptodate(left_path->nodes[0]));
52887069830aSAlexander Block 					ret = changed_cb(left_root, right_root,
52897069830aSAlexander Block 						left_path, right_path,
52907069830aSAlexander Block 						&left_key,
52917069830aSAlexander Block 						BTRFS_COMPARE_TREE_CHANGED,
52927069830aSAlexander Block 						ctx);
52937069830aSAlexander Block 					if (ret < 0)
52947069830aSAlexander Block 						goto out;
52957069830aSAlexander Block 				}
52967069830aSAlexander Block 				advance_left = ADVANCE;
52977069830aSAlexander Block 				advance_right = ADVANCE;
52987069830aSAlexander Block 			}
52997069830aSAlexander Block 		} else if (left_level == right_level) {
53007069830aSAlexander Block 			cmp = btrfs_comp_cpu_keys(&left_key, &right_key);
53017069830aSAlexander Block 			if (cmp < 0) {
53027069830aSAlexander Block 				advance_left = ADVANCE;
53037069830aSAlexander Block 			} else if (cmp > 0) {
53047069830aSAlexander Block 				advance_right = ADVANCE;
53057069830aSAlexander Block 			} else {
53067069830aSAlexander Block 				left_blockptr = btrfs_node_blockptr(
53077069830aSAlexander Block 						left_path->nodes[left_level],
53087069830aSAlexander Block 						left_path->slots[left_level]);
53097069830aSAlexander Block 				right_blockptr = btrfs_node_blockptr(
53107069830aSAlexander Block 						right_path->nodes[right_level],
53117069830aSAlexander Block 						right_path->slots[right_level]);
53127069830aSAlexander Block 				if (left_blockptr == right_blockptr) {
53137069830aSAlexander Block 					/*
53147069830aSAlexander Block 					 * As we're on a shared block, don't
53157069830aSAlexander Block 					 * allow to go deeper.
53167069830aSAlexander Block 					 */
53177069830aSAlexander Block 					advance_left = ADVANCE_ONLY_NEXT;
53187069830aSAlexander Block 					advance_right = ADVANCE_ONLY_NEXT;
53197069830aSAlexander Block 				} else {
53207069830aSAlexander Block 					advance_left = ADVANCE;
53217069830aSAlexander Block 					advance_right = ADVANCE;
53227069830aSAlexander Block 				}
53237069830aSAlexander Block 			}
53247069830aSAlexander Block 		} else if (left_level < right_level) {
53257069830aSAlexander Block 			advance_right = ADVANCE;
53267069830aSAlexander Block 		} else {
53277069830aSAlexander Block 			advance_left = ADVANCE;
53287069830aSAlexander Block 		}
53297069830aSAlexander Block 	}
53307069830aSAlexander Block 
53317069830aSAlexander Block out:
53327069830aSAlexander Block 	btrfs_free_path(left_path);
53337069830aSAlexander Block 	btrfs_free_path(right_path);
53347069830aSAlexander Block 	kfree(tmp_buf);
53357069830aSAlexander Block 
53367069830aSAlexander Block 	if (trans) {
53377069830aSAlexander Block 		if (!ret)
53387069830aSAlexander Block 			ret = btrfs_end_transaction(trans, left_root);
53397069830aSAlexander Block 		else
53407069830aSAlexander Block 			btrfs_end_transaction(trans, left_root);
53417069830aSAlexander Block 	}
53427069830aSAlexander Block 
53437069830aSAlexander Block 	return ret;
53447069830aSAlexander Block }
53457069830aSAlexander Block 
53463f157a2fSChris Mason /*
53473f157a2fSChris Mason  * this is similar to btrfs_next_leaf, but does not try to preserve
53483f157a2fSChris Mason  * and fixup the path.  It looks for and returns the next key in the
5349de78b51aSEric Sandeen  * tree based on the current path and the min_trans parameters.
53503f157a2fSChris Mason  *
53513f157a2fSChris Mason  * 0 is returned if another key is found, < 0 if there are any errors
53523f157a2fSChris Mason  * and 1 is returned if there are no higher keys in the tree
53533f157a2fSChris Mason  *
53543f157a2fSChris Mason  * path->keep_locks should be set to 1 on the search made before
53553f157a2fSChris Mason  * calling this function.
53563f157a2fSChris Mason  */
5357e7a84565SChris Mason int btrfs_find_next_key(struct btrfs_root *root, struct btrfs_path *path,
5358de78b51aSEric Sandeen 			struct btrfs_key *key, int level, u64 min_trans)
5359e7a84565SChris Mason {
5360e7a84565SChris Mason 	int slot;
5361e7a84565SChris Mason 	struct extent_buffer *c;
5362e7a84565SChris Mason 
5363934d375bSChris Mason 	WARN_ON(!path->keep_locks);
5364e7a84565SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
5365e7a84565SChris Mason 		if (!path->nodes[level])
5366e7a84565SChris Mason 			return 1;
5367e7a84565SChris Mason 
5368e7a84565SChris Mason 		slot = path->slots[level] + 1;
5369e7a84565SChris Mason 		c = path->nodes[level];
53703f157a2fSChris Mason next:
5371e7a84565SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
537233c66f43SYan Zheng 			int ret;
537333c66f43SYan Zheng 			int orig_lowest;
537433c66f43SYan Zheng 			struct btrfs_key cur_key;
537533c66f43SYan Zheng 			if (level + 1 >= BTRFS_MAX_LEVEL ||
537633c66f43SYan Zheng 			    !path->nodes[level + 1])
5377e7a84565SChris Mason 				return 1;
537833c66f43SYan Zheng 
537933c66f43SYan Zheng 			if (path->locks[level + 1]) {
538033c66f43SYan Zheng 				level++;
5381e7a84565SChris Mason 				continue;
5382e7a84565SChris Mason 			}
538333c66f43SYan Zheng 
538433c66f43SYan Zheng 			slot = btrfs_header_nritems(c) - 1;
538533c66f43SYan Zheng 			if (level == 0)
538633c66f43SYan Zheng 				btrfs_item_key_to_cpu(c, &cur_key, slot);
538733c66f43SYan Zheng 			else
538833c66f43SYan Zheng 				btrfs_node_key_to_cpu(c, &cur_key, slot);
538933c66f43SYan Zheng 
539033c66f43SYan Zheng 			orig_lowest = path->lowest_level;
5391b3b4aa74SDavid Sterba 			btrfs_release_path(path);
539233c66f43SYan Zheng 			path->lowest_level = level;
539333c66f43SYan Zheng 			ret = btrfs_search_slot(NULL, root, &cur_key, path,
539433c66f43SYan Zheng 						0, 0);
539533c66f43SYan Zheng 			path->lowest_level = orig_lowest;
539633c66f43SYan Zheng 			if (ret < 0)
539733c66f43SYan Zheng 				return ret;
539833c66f43SYan Zheng 
539933c66f43SYan Zheng 			c = path->nodes[level];
540033c66f43SYan Zheng 			slot = path->slots[level];
540133c66f43SYan Zheng 			if (ret == 0)
540233c66f43SYan Zheng 				slot++;
540333c66f43SYan Zheng 			goto next;
540433c66f43SYan Zheng 		}
540533c66f43SYan Zheng 
5406e7a84565SChris Mason 		if (level == 0)
5407e7a84565SChris Mason 			btrfs_item_key_to_cpu(c, key, slot);
54083f157a2fSChris Mason 		else {
54093f157a2fSChris Mason 			u64 gen = btrfs_node_ptr_generation(c, slot);
54103f157a2fSChris Mason 
54113f157a2fSChris Mason 			if (gen < min_trans) {
54123f157a2fSChris Mason 				slot++;
54133f157a2fSChris Mason 				goto next;
54143f157a2fSChris Mason 			}
5415e7a84565SChris Mason 			btrfs_node_key_to_cpu(c, key, slot);
54163f157a2fSChris Mason 		}
5417e7a84565SChris Mason 		return 0;
5418e7a84565SChris Mason 	}
5419e7a84565SChris Mason 	return 1;
5420e7a84565SChris Mason }
5421e7a84565SChris Mason 
54227bb86316SChris Mason /*
5423925baeddSChris Mason  * search the tree again to find a leaf with greater keys
54240f70abe2SChris Mason  * returns 0 if it found something or 1 if there are no greater leaves.
54250f70abe2SChris Mason  * returns < 0 on io errors.
542697571fd0SChris Mason  */
5427234b63a0SChris Mason int btrfs_next_leaf(struct btrfs_root *root, struct btrfs_path *path)
5428d97e63b6SChris Mason {
54293d7806ecSJan Schmidt 	return btrfs_next_old_leaf(root, path, 0);
54303d7806ecSJan Schmidt }
54313d7806ecSJan Schmidt 
54323d7806ecSJan Schmidt int btrfs_next_old_leaf(struct btrfs_root *root, struct btrfs_path *path,
54333d7806ecSJan Schmidt 			u64 time_seq)
54343d7806ecSJan Schmidt {
5435d97e63b6SChris Mason 	int slot;
54368e73f275SChris Mason 	int level;
54375f39d397SChris Mason 	struct extent_buffer *c;
54388e73f275SChris Mason 	struct extent_buffer *next;
5439925baeddSChris Mason 	struct btrfs_key key;
5440925baeddSChris Mason 	u32 nritems;
5441925baeddSChris Mason 	int ret;
54428e73f275SChris Mason 	int old_spinning = path->leave_spinning;
5443bd681513SChris Mason 	int next_rw_lock = 0;
5444925baeddSChris Mason 
5445925baeddSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
5446d397712bSChris Mason 	if (nritems == 0)
5447925baeddSChris Mason 		return 1;
5448925baeddSChris Mason 
54498e73f275SChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, nritems - 1);
54508e73f275SChris Mason again:
54518e73f275SChris Mason 	level = 1;
54528e73f275SChris Mason 	next = NULL;
5453bd681513SChris Mason 	next_rw_lock = 0;
5454b3b4aa74SDavid Sterba 	btrfs_release_path(path);
54558e73f275SChris Mason 
5456a2135011SChris Mason 	path->keep_locks = 1;
54578e73f275SChris Mason 	path->leave_spinning = 1;
54588e73f275SChris Mason 
54593d7806ecSJan Schmidt 	if (time_seq)
54603d7806ecSJan Schmidt 		ret = btrfs_search_old_slot(root, &key, path, time_seq);
54613d7806ecSJan Schmidt 	else
5462925baeddSChris Mason 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5463925baeddSChris Mason 	path->keep_locks = 0;
5464925baeddSChris Mason 
5465925baeddSChris Mason 	if (ret < 0)
5466925baeddSChris Mason 		return ret;
5467925baeddSChris Mason 
5468a2135011SChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
5469168fd7d2SChris Mason 	/*
5470168fd7d2SChris Mason 	 * by releasing the path above we dropped all our locks.  A balance
5471168fd7d2SChris Mason 	 * could have added more items next to the key that used to be
5472168fd7d2SChris Mason 	 * at the very end of the block.  So, check again here and
5473168fd7d2SChris Mason 	 * advance the path if there are now more items available.
5474168fd7d2SChris Mason 	 */
5475a2135011SChris Mason 	if (nritems > 0 && path->slots[0] < nritems - 1) {
5476e457afecSYan Zheng 		if (ret == 0)
5477168fd7d2SChris Mason 			path->slots[0]++;
54788e73f275SChris Mason 		ret = 0;
5479925baeddSChris Mason 		goto done;
5480925baeddSChris Mason 	}
5481d97e63b6SChris Mason 
5482234b63a0SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
54838e73f275SChris Mason 		if (!path->nodes[level]) {
54848e73f275SChris Mason 			ret = 1;
54858e73f275SChris Mason 			goto done;
54868e73f275SChris Mason 		}
54875f39d397SChris Mason 
5488d97e63b6SChris Mason 		slot = path->slots[level] + 1;
5489d97e63b6SChris Mason 		c = path->nodes[level];
54905f39d397SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
5491d97e63b6SChris Mason 			level++;
54928e73f275SChris Mason 			if (level == BTRFS_MAX_LEVEL) {
54938e73f275SChris Mason 				ret = 1;
54948e73f275SChris Mason 				goto done;
54958e73f275SChris Mason 			}
5496d97e63b6SChris Mason 			continue;
5497d97e63b6SChris Mason 		}
54985f39d397SChris Mason 
5499925baeddSChris Mason 		if (next) {
5500bd681513SChris Mason 			btrfs_tree_unlock_rw(next, next_rw_lock);
55015f39d397SChris Mason 			free_extent_buffer(next);
5502925baeddSChris Mason 		}
55035f39d397SChris Mason 
55048e73f275SChris Mason 		next = c;
5505bd681513SChris Mason 		next_rw_lock = path->locks[level];
55068e73f275SChris Mason 		ret = read_block_for_search(NULL, root, path, &next, level,
55075d9e75c4SJan Schmidt 					    slot, &key, 0);
55088e73f275SChris Mason 		if (ret == -EAGAIN)
55098e73f275SChris Mason 			goto again;
55105f39d397SChris Mason 
551176a05b35SChris Mason 		if (ret < 0) {
5512b3b4aa74SDavid Sterba 			btrfs_release_path(path);
551376a05b35SChris Mason 			goto done;
551476a05b35SChris Mason 		}
551576a05b35SChris Mason 
55165cd57b2cSChris Mason 		if (!path->skip_locking) {
5517bd681513SChris Mason 			ret = btrfs_try_tree_read_lock(next);
5518d42244a0SJan Schmidt 			if (!ret && time_seq) {
5519d42244a0SJan Schmidt 				/*
5520d42244a0SJan Schmidt 				 * If we don't get the lock, we may be racing
5521d42244a0SJan Schmidt 				 * with push_leaf_left, holding that lock while
5522d42244a0SJan Schmidt 				 * itself waiting for the leaf we've currently
5523d42244a0SJan Schmidt 				 * locked. To solve this situation, we give up
5524d42244a0SJan Schmidt 				 * on our lock and cycle.
5525d42244a0SJan Schmidt 				 */
5526cf538830SJan Schmidt 				free_extent_buffer(next);
5527d42244a0SJan Schmidt 				btrfs_release_path(path);
5528d42244a0SJan Schmidt 				cond_resched();
5529d42244a0SJan Schmidt 				goto again;
5530d42244a0SJan Schmidt 			}
55318e73f275SChris Mason 			if (!ret) {
55328e73f275SChris Mason 				btrfs_set_path_blocking(path);
5533bd681513SChris Mason 				btrfs_tree_read_lock(next);
5534bd681513SChris Mason 				btrfs_clear_path_blocking(path, next,
5535bd681513SChris Mason 							  BTRFS_READ_LOCK);
55368e73f275SChris Mason 			}
5537bd681513SChris Mason 			next_rw_lock = BTRFS_READ_LOCK;
5538bd681513SChris Mason 		}
5539d97e63b6SChris Mason 		break;
5540d97e63b6SChris Mason 	}
5541d97e63b6SChris Mason 	path->slots[level] = slot;
5542d97e63b6SChris Mason 	while (1) {
5543d97e63b6SChris Mason 		level--;
5544d97e63b6SChris Mason 		c = path->nodes[level];
5545925baeddSChris Mason 		if (path->locks[level])
5546bd681513SChris Mason 			btrfs_tree_unlock_rw(c, path->locks[level]);
55478e73f275SChris Mason 
55485f39d397SChris Mason 		free_extent_buffer(c);
5549d97e63b6SChris Mason 		path->nodes[level] = next;
5550d97e63b6SChris Mason 		path->slots[level] = 0;
5551a74a4b97SChris Mason 		if (!path->skip_locking)
5552bd681513SChris Mason 			path->locks[level] = next_rw_lock;
5553d97e63b6SChris Mason 		if (!level)
5554d97e63b6SChris Mason 			break;
5555b4ce94deSChris Mason 
55568e73f275SChris Mason 		ret = read_block_for_search(NULL, root, path, &next, level,
55575d9e75c4SJan Schmidt 					    0, &key, 0);
55588e73f275SChris Mason 		if (ret == -EAGAIN)
55598e73f275SChris Mason 			goto again;
55608e73f275SChris Mason 
556176a05b35SChris Mason 		if (ret < 0) {
5562b3b4aa74SDavid Sterba 			btrfs_release_path(path);
556376a05b35SChris Mason 			goto done;
556476a05b35SChris Mason 		}
556576a05b35SChris Mason 
55665cd57b2cSChris Mason 		if (!path->skip_locking) {
5567bd681513SChris Mason 			ret = btrfs_try_tree_read_lock(next);
55688e73f275SChris Mason 			if (!ret) {
55698e73f275SChris Mason 				btrfs_set_path_blocking(path);
5570bd681513SChris Mason 				btrfs_tree_read_lock(next);
5571bd681513SChris Mason 				btrfs_clear_path_blocking(path, next,
5572bd681513SChris Mason 							  BTRFS_READ_LOCK);
55738e73f275SChris Mason 			}
5574bd681513SChris Mason 			next_rw_lock = BTRFS_READ_LOCK;
5575bd681513SChris Mason 		}
5576d97e63b6SChris Mason 	}
55778e73f275SChris Mason 	ret = 0;
5578925baeddSChris Mason done:
5579f7c79f30SChris Mason 	unlock_up(path, 0, 1, 0, NULL);
55808e73f275SChris Mason 	path->leave_spinning = old_spinning;
55818e73f275SChris Mason 	if (!old_spinning)
55828e73f275SChris Mason 		btrfs_set_path_blocking(path);
55838e73f275SChris Mason 
55848e73f275SChris Mason 	return ret;
5585d97e63b6SChris Mason }
55860b86a832SChris Mason 
55873f157a2fSChris Mason /*
55883f157a2fSChris Mason  * this uses btrfs_prev_leaf to walk backwards in the tree, and keeps
55893f157a2fSChris Mason  * searching until it gets past min_objectid or finds an item of 'type'
55903f157a2fSChris Mason  *
55913f157a2fSChris Mason  * returns 0 if something is found, 1 if nothing was found and < 0 on error
55923f157a2fSChris Mason  */
55930b86a832SChris Mason int btrfs_previous_item(struct btrfs_root *root,
55940b86a832SChris Mason 			struct btrfs_path *path, u64 min_objectid,
55950b86a832SChris Mason 			int type)
55960b86a832SChris Mason {
55970b86a832SChris Mason 	struct btrfs_key found_key;
55980b86a832SChris Mason 	struct extent_buffer *leaf;
5599e02119d5SChris Mason 	u32 nritems;
56000b86a832SChris Mason 	int ret;
56010b86a832SChris Mason 
56020b86a832SChris Mason 	while (1) {
56030b86a832SChris Mason 		if (path->slots[0] == 0) {
5604b4ce94deSChris Mason 			btrfs_set_path_blocking(path);
56050b86a832SChris Mason 			ret = btrfs_prev_leaf(root, path);
56060b86a832SChris Mason 			if (ret != 0)
56070b86a832SChris Mason 				return ret;
56080b86a832SChris Mason 		} else {
56090b86a832SChris Mason 			path->slots[0]--;
56100b86a832SChris Mason 		}
56110b86a832SChris Mason 		leaf = path->nodes[0];
5612e02119d5SChris Mason 		nritems = btrfs_header_nritems(leaf);
5613e02119d5SChris Mason 		if (nritems == 0)
5614e02119d5SChris Mason 			return 1;
5615e02119d5SChris Mason 		if (path->slots[0] == nritems)
5616e02119d5SChris Mason 			path->slots[0]--;
5617e02119d5SChris Mason 
56180b86a832SChris Mason 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5619e02119d5SChris Mason 		if (found_key.objectid < min_objectid)
5620e02119d5SChris Mason 			break;
56210a4eefbbSYan Zheng 		if (found_key.type == type)
56220a4eefbbSYan Zheng 			return 0;
5623e02119d5SChris Mason 		if (found_key.objectid == min_objectid &&
5624e02119d5SChris Mason 		    found_key.type < type)
5625e02119d5SChris Mason 			break;
56260b86a832SChris Mason 	}
56270b86a832SChris Mason 	return 1;
56280b86a832SChris Mason }
5629