xref: /openbmc/linux/fs/btrfs/ctree.c (revision f7cea56c0fff95bd5a6cd21b9fa299f66193b604)
1c1d7c514SDavid Sterba // SPDX-License-Identifier: GPL-2.0
26cbd5570SChris Mason /*
3d352ac68SChris Mason  * Copyright (C) 2007,2008 Oracle.  All rights reserved.
46cbd5570SChris Mason  */
56cbd5570SChris Mason 
6a6b6e75eSChris Mason #include <linux/sched.h>
75a0e3ad6STejun Heo #include <linux/slab.h>
8bd989ba3SJan Schmidt #include <linux/rbtree.h>
9adf02123SDavid Sterba #include <linux/mm.h>
10eb60ceacSChris Mason #include "ctree.h"
11eb60ceacSChris Mason #include "disk-io.h"
127f5c1516SChris Mason #include "transaction.h"
135f39d397SChris Mason #include "print-tree.h"
14925baeddSChris Mason #include "locking.h"
15de37aa51SNikolay Borisov #include "volumes.h"
16f616f5cdSQu Wenruo #include "qgroup.h"
179a8dd150SChris Mason 
18e089f05cSChris Mason static int split_node(struct btrfs_trans_handle *trans, struct btrfs_root
19e089f05cSChris Mason 		      *root, struct btrfs_path *path, int level);
20310712b2SOmar Sandoval static int split_leaf(struct btrfs_trans_handle *trans, struct btrfs_root *root,
21310712b2SOmar Sandoval 		      const struct btrfs_key *ins_key, struct btrfs_path *path,
22310712b2SOmar Sandoval 		      int data_size, int extend);
235f39d397SChris Mason static int push_node_left(struct btrfs_trans_handle *trans,
242ff7e61eSJeff Mahoney 			  struct extent_buffer *dst,
25971a1f66SChris Mason 			  struct extent_buffer *src, int empty);
265f39d397SChris Mason static int balance_node_right(struct btrfs_trans_handle *trans,
275f39d397SChris Mason 			      struct extent_buffer *dst_buf,
285f39d397SChris Mason 			      struct extent_buffer *src_buf);
29afe5fea7STsutomu Itoh static void del_ptr(struct btrfs_root *root, struct btrfs_path *path,
30afe5fea7STsutomu Itoh 		    int level, int slot);
31d97e63b6SChris Mason 
32af024ed2SJohannes Thumshirn static const struct btrfs_csums {
33af024ed2SJohannes Thumshirn 	u16		size;
34af024ed2SJohannes Thumshirn 	const char	*name;
35af024ed2SJohannes Thumshirn } btrfs_csums[] = {
36af024ed2SJohannes Thumshirn 	[BTRFS_CSUM_TYPE_CRC32] = { .size = 4, .name = "crc32c" },
373951e7f0SJohannes Thumshirn 	[BTRFS_CSUM_TYPE_XXHASH] = { .size = 8, .name = "xxhash64" },
383831bf00SJohannes Thumshirn 	[BTRFS_CSUM_TYPE_SHA256] = { .size = 32, .name = "sha256" },
39af024ed2SJohannes Thumshirn };
40af024ed2SJohannes Thumshirn 
41af024ed2SJohannes Thumshirn int btrfs_super_csum_size(const struct btrfs_super_block *s)
42af024ed2SJohannes Thumshirn {
43af024ed2SJohannes Thumshirn 	u16 t = btrfs_super_csum_type(s);
44af024ed2SJohannes Thumshirn 	/*
45af024ed2SJohannes Thumshirn 	 * csum type is validated at mount time
46af024ed2SJohannes Thumshirn 	 */
47af024ed2SJohannes Thumshirn 	return btrfs_csums[t].size;
48af024ed2SJohannes Thumshirn }
49af024ed2SJohannes Thumshirn 
50af024ed2SJohannes Thumshirn const char *btrfs_super_csum_name(u16 csum_type)
51af024ed2SJohannes Thumshirn {
52af024ed2SJohannes Thumshirn 	/* csum type is validated at mount time */
53af024ed2SJohannes Thumshirn 	return btrfs_csums[csum_type].name;
54af024ed2SJohannes Thumshirn }
55af024ed2SJohannes Thumshirn 
56*f7cea56cSDavid Sterba size_t __const btrfs_get_num_csums(void)
57*f7cea56cSDavid Sterba {
58*f7cea56cSDavid Sterba 	return ARRAY_SIZE(btrfs_csums);
59*f7cea56cSDavid Sterba }
60*f7cea56cSDavid Sterba 
612c90e5d6SChris Mason struct btrfs_path *btrfs_alloc_path(void)
622c90e5d6SChris Mason {
63e2c89907SMasahiro Yamada 	return kmem_cache_zalloc(btrfs_path_cachep, GFP_NOFS);
642c90e5d6SChris Mason }
652c90e5d6SChris Mason 
66d352ac68SChris Mason /* this also releases the path */
672c90e5d6SChris Mason void btrfs_free_path(struct btrfs_path *p)
682c90e5d6SChris Mason {
69ff175d57SJesper Juhl 	if (!p)
70ff175d57SJesper Juhl 		return;
71b3b4aa74SDavid Sterba 	btrfs_release_path(p);
722c90e5d6SChris Mason 	kmem_cache_free(btrfs_path_cachep, p);
732c90e5d6SChris Mason }
742c90e5d6SChris Mason 
75d352ac68SChris Mason /*
76d352ac68SChris Mason  * path release drops references on the extent buffers in the path
77d352ac68SChris Mason  * and it drops any locks held by this path
78d352ac68SChris Mason  *
79d352ac68SChris Mason  * It is safe to call this on paths that no locks or extent buffers held.
80d352ac68SChris Mason  */
81b3b4aa74SDavid Sterba noinline void btrfs_release_path(struct btrfs_path *p)
82eb60ceacSChris Mason {
83eb60ceacSChris Mason 	int i;
84a2135011SChris Mason 
85234b63a0SChris Mason 	for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
863f157a2fSChris Mason 		p->slots[i] = 0;
87eb60ceacSChris Mason 		if (!p->nodes[i])
88925baeddSChris Mason 			continue;
89925baeddSChris Mason 		if (p->locks[i]) {
90bd681513SChris Mason 			btrfs_tree_unlock_rw(p->nodes[i], p->locks[i]);
91925baeddSChris Mason 			p->locks[i] = 0;
92925baeddSChris Mason 		}
935f39d397SChris Mason 		free_extent_buffer(p->nodes[i]);
943f157a2fSChris Mason 		p->nodes[i] = NULL;
95eb60ceacSChris Mason 	}
96eb60ceacSChris Mason }
97eb60ceacSChris Mason 
98d352ac68SChris Mason /*
99d352ac68SChris Mason  * safely gets a reference on the root node of a tree.  A lock
100d352ac68SChris Mason  * is not taken, so a concurrent writer may put a different node
101d352ac68SChris Mason  * at the root of the tree.  See btrfs_lock_root_node for the
102d352ac68SChris Mason  * looping required.
103d352ac68SChris Mason  *
104d352ac68SChris Mason  * The extent buffer returned by this has a reference taken, so
105d352ac68SChris Mason  * it won't disappear.  It may stop being the root of the tree
106d352ac68SChris Mason  * at any time because there are no locks held.
107d352ac68SChris Mason  */
108925baeddSChris Mason struct extent_buffer *btrfs_root_node(struct btrfs_root *root)
109925baeddSChris Mason {
110925baeddSChris Mason 	struct extent_buffer *eb;
111240f62c8SChris Mason 
1123083ee2eSJosef Bacik 	while (1) {
113240f62c8SChris Mason 		rcu_read_lock();
114240f62c8SChris Mason 		eb = rcu_dereference(root->node);
1153083ee2eSJosef Bacik 
1163083ee2eSJosef Bacik 		/*
1173083ee2eSJosef Bacik 		 * RCU really hurts here, we could free up the root node because
11801327610SNicholas D Steeves 		 * it was COWed but we may not get the new root node yet so do
1193083ee2eSJosef Bacik 		 * the inc_not_zero dance and if it doesn't work then
1203083ee2eSJosef Bacik 		 * synchronize_rcu and try again.
1213083ee2eSJosef Bacik 		 */
1223083ee2eSJosef Bacik 		if (atomic_inc_not_zero(&eb->refs)) {
123240f62c8SChris Mason 			rcu_read_unlock();
1243083ee2eSJosef Bacik 			break;
1253083ee2eSJosef Bacik 		}
1263083ee2eSJosef Bacik 		rcu_read_unlock();
1273083ee2eSJosef Bacik 		synchronize_rcu();
1283083ee2eSJosef Bacik 	}
129925baeddSChris Mason 	return eb;
130925baeddSChris Mason }
131925baeddSChris Mason 
132d352ac68SChris Mason /* loop around taking references on and locking the root node of the
133d352ac68SChris Mason  * tree until you end up with a lock on the root.  A locked buffer
134d352ac68SChris Mason  * is returned, with a reference held.
135d352ac68SChris Mason  */
136925baeddSChris Mason struct extent_buffer *btrfs_lock_root_node(struct btrfs_root *root)
137925baeddSChris Mason {
138925baeddSChris Mason 	struct extent_buffer *eb;
139925baeddSChris Mason 
140925baeddSChris Mason 	while (1) {
141925baeddSChris Mason 		eb = btrfs_root_node(root);
142925baeddSChris Mason 		btrfs_tree_lock(eb);
143240f62c8SChris Mason 		if (eb == root->node)
144925baeddSChris Mason 			break;
145925baeddSChris Mason 		btrfs_tree_unlock(eb);
146925baeddSChris Mason 		free_extent_buffer(eb);
147925baeddSChris Mason 	}
148925baeddSChris Mason 	return eb;
149925baeddSChris Mason }
150925baeddSChris Mason 
151bd681513SChris Mason /* loop around taking references on and locking the root node of the
152bd681513SChris Mason  * tree until you end up with a lock on the root.  A locked buffer
153bd681513SChris Mason  * is returned, with a reference held.
154bd681513SChris Mason  */
15584f7d8e6SJosef Bacik struct extent_buffer *btrfs_read_lock_root_node(struct btrfs_root *root)
156bd681513SChris Mason {
157bd681513SChris Mason 	struct extent_buffer *eb;
158bd681513SChris Mason 
159bd681513SChris Mason 	while (1) {
160bd681513SChris Mason 		eb = btrfs_root_node(root);
161bd681513SChris Mason 		btrfs_tree_read_lock(eb);
162bd681513SChris Mason 		if (eb == root->node)
163bd681513SChris Mason 			break;
164bd681513SChris Mason 		btrfs_tree_read_unlock(eb);
165bd681513SChris Mason 		free_extent_buffer(eb);
166bd681513SChris Mason 	}
167bd681513SChris Mason 	return eb;
168bd681513SChris Mason }
169bd681513SChris Mason 
170d352ac68SChris Mason /* cowonly root (everything not a reference counted cow subvolume), just get
171d352ac68SChris Mason  * put onto a simple dirty list.  transaction.c walks this to make sure they
172d352ac68SChris Mason  * get properly updated on disk.
173d352ac68SChris Mason  */
1740b86a832SChris Mason static void add_root_to_dirty_list(struct btrfs_root *root)
1750b86a832SChris Mason {
1760b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
1770b246afaSJeff Mahoney 
178e7070be1SJosef Bacik 	if (test_bit(BTRFS_ROOT_DIRTY, &root->state) ||
179e7070be1SJosef Bacik 	    !test_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state))
180e7070be1SJosef Bacik 		return;
181e7070be1SJosef Bacik 
1820b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
183e7070be1SJosef Bacik 	if (!test_and_set_bit(BTRFS_ROOT_DIRTY, &root->state)) {
184e7070be1SJosef Bacik 		/* Want the extent tree to be the last on the list */
1854fd786e6SMisono Tomohiro 		if (root->root_key.objectid == BTRFS_EXTENT_TREE_OBJECTID)
186e7070be1SJosef Bacik 			list_move_tail(&root->dirty_list,
1870b246afaSJeff Mahoney 				       &fs_info->dirty_cowonly_roots);
188e7070be1SJosef Bacik 		else
189e7070be1SJosef Bacik 			list_move(&root->dirty_list,
1900b246afaSJeff Mahoney 				  &fs_info->dirty_cowonly_roots);
1910b86a832SChris Mason 	}
1920b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
1930b86a832SChris Mason }
1940b86a832SChris Mason 
195d352ac68SChris Mason /*
196d352ac68SChris Mason  * used by snapshot creation to make a copy of a root for a tree with
197d352ac68SChris Mason  * a given objectid.  The buffer with the new root node is returned in
198d352ac68SChris Mason  * cow_ret, and this func returns zero on success or a negative error code.
199d352ac68SChris Mason  */
200be20aa9dSChris Mason int btrfs_copy_root(struct btrfs_trans_handle *trans,
201be20aa9dSChris Mason 		      struct btrfs_root *root,
202be20aa9dSChris Mason 		      struct extent_buffer *buf,
203be20aa9dSChris Mason 		      struct extent_buffer **cow_ret, u64 new_root_objectid)
204be20aa9dSChris Mason {
2050b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
206be20aa9dSChris Mason 	struct extent_buffer *cow;
207be20aa9dSChris Mason 	int ret = 0;
208be20aa9dSChris Mason 	int level;
2095d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
210be20aa9dSChris Mason 
21127cdeb70SMiao Xie 	WARN_ON(test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
2120b246afaSJeff Mahoney 		trans->transid != fs_info->running_transaction->transid);
21327cdeb70SMiao Xie 	WARN_ON(test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
21427cdeb70SMiao Xie 		trans->transid != root->last_trans);
215be20aa9dSChris Mason 
216be20aa9dSChris Mason 	level = btrfs_header_level(buf);
2175d4f98a2SYan Zheng 	if (level == 0)
2185d4f98a2SYan Zheng 		btrfs_item_key(buf, &disk_key, 0);
2195d4f98a2SYan Zheng 	else
2205d4f98a2SYan Zheng 		btrfs_node_key(buf, &disk_key, 0);
22131840ae1SZheng Yan 
2224d75f8a9SDavid Sterba 	cow = btrfs_alloc_tree_block(trans, root, 0, new_root_objectid,
2234d75f8a9SDavid Sterba 			&disk_key, level, buf->start, 0);
2245d4f98a2SYan Zheng 	if (IS_ERR(cow))
225be20aa9dSChris Mason 		return PTR_ERR(cow);
226be20aa9dSChris Mason 
22758e8012cSDavid Sterba 	copy_extent_buffer_full(cow, buf);
228be20aa9dSChris Mason 	btrfs_set_header_bytenr(cow, cow->start);
229be20aa9dSChris Mason 	btrfs_set_header_generation(cow, trans->transid);
2305d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
2315d4f98a2SYan Zheng 	btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
2325d4f98a2SYan Zheng 				     BTRFS_HEADER_FLAG_RELOC);
2335d4f98a2SYan Zheng 	if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
2345d4f98a2SYan Zheng 		btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
2355d4f98a2SYan Zheng 	else
236be20aa9dSChris Mason 		btrfs_set_header_owner(cow, new_root_objectid);
237be20aa9dSChris Mason 
238de37aa51SNikolay Borisov 	write_extent_buffer_fsid(cow, fs_info->fs_devices->metadata_uuid);
2392b82032cSYan Zheng 
240be20aa9dSChris Mason 	WARN_ON(btrfs_header_generation(buf) > trans->transid);
2415d4f98a2SYan Zheng 	if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
242e339a6b0SJosef Bacik 		ret = btrfs_inc_ref(trans, root, cow, 1);
2435d4f98a2SYan Zheng 	else
244e339a6b0SJosef Bacik 		ret = btrfs_inc_ref(trans, root, cow, 0);
2454aec2b52SChris Mason 
246be20aa9dSChris Mason 	if (ret)
247be20aa9dSChris Mason 		return ret;
248be20aa9dSChris Mason 
249be20aa9dSChris Mason 	btrfs_mark_buffer_dirty(cow);
250be20aa9dSChris Mason 	*cow_ret = cow;
251be20aa9dSChris Mason 	return 0;
252be20aa9dSChris Mason }
253be20aa9dSChris Mason 
254bd989ba3SJan Schmidt enum mod_log_op {
255bd989ba3SJan Schmidt 	MOD_LOG_KEY_REPLACE,
256bd989ba3SJan Schmidt 	MOD_LOG_KEY_ADD,
257bd989ba3SJan Schmidt 	MOD_LOG_KEY_REMOVE,
258bd989ba3SJan Schmidt 	MOD_LOG_KEY_REMOVE_WHILE_FREEING,
259bd989ba3SJan Schmidt 	MOD_LOG_KEY_REMOVE_WHILE_MOVING,
260bd989ba3SJan Schmidt 	MOD_LOG_MOVE_KEYS,
261bd989ba3SJan Schmidt 	MOD_LOG_ROOT_REPLACE,
262bd989ba3SJan Schmidt };
263bd989ba3SJan Schmidt 
264bd989ba3SJan Schmidt struct tree_mod_root {
265bd989ba3SJan Schmidt 	u64 logical;
266bd989ba3SJan Schmidt 	u8 level;
267bd989ba3SJan Schmidt };
268bd989ba3SJan Schmidt 
269bd989ba3SJan Schmidt struct tree_mod_elem {
270bd989ba3SJan Schmidt 	struct rb_node node;
271298cfd36SChandan Rajendra 	u64 logical;
272097b8a7cSJan Schmidt 	u64 seq;
273bd989ba3SJan Schmidt 	enum mod_log_op op;
274bd989ba3SJan Schmidt 
275bd989ba3SJan Schmidt 	/* this is used for MOD_LOG_KEY_* and MOD_LOG_MOVE_KEYS operations */
276bd989ba3SJan Schmidt 	int slot;
277bd989ba3SJan Schmidt 
278bd989ba3SJan Schmidt 	/* this is used for MOD_LOG_KEY* and MOD_LOG_ROOT_REPLACE */
279bd989ba3SJan Schmidt 	u64 generation;
280bd989ba3SJan Schmidt 
281bd989ba3SJan Schmidt 	/* those are used for op == MOD_LOG_KEY_{REPLACE,REMOVE} */
282bd989ba3SJan Schmidt 	struct btrfs_disk_key key;
283bd989ba3SJan Schmidt 	u64 blockptr;
284bd989ba3SJan Schmidt 
285bd989ba3SJan Schmidt 	/* this is used for op == MOD_LOG_MOVE_KEYS */
286b6dfa35bSDavid Sterba 	struct {
287b6dfa35bSDavid Sterba 		int dst_slot;
288b6dfa35bSDavid Sterba 		int nr_items;
289b6dfa35bSDavid Sterba 	} move;
290bd989ba3SJan Schmidt 
291bd989ba3SJan Schmidt 	/* this is used for op == MOD_LOG_ROOT_REPLACE */
292bd989ba3SJan Schmidt 	struct tree_mod_root old_root;
293bd989ba3SJan Schmidt };
294bd989ba3SJan Schmidt 
295097b8a7cSJan Schmidt /*
296fcebe456SJosef Bacik  * Pull a new tree mod seq number for our operation.
297fc36ed7eSJan Schmidt  */
298fcebe456SJosef Bacik static inline u64 btrfs_inc_tree_mod_seq(struct btrfs_fs_info *fs_info)
299fc36ed7eSJan Schmidt {
300fc36ed7eSJan Schmidt 	return atomic64_inc_return(&fs_info->tree_mod_seq);
301fc36ed7eSJan Schmidt }
302fc36ed7eSJan Schmidt 
303fc36ed7eSJan Schmidt /*
304097b8a7cSJan Schmidt  * This adds a new blocker to the tree mod log's blocker list if the @elem
305097b8a7cSJan Schmidt  * passed does not already have a sequence number set. So when a caller expects
306097b8a7cSJan Schmidt  * to record tree modifications, it should ensure to set elem->seq to zero
307097b8a7cSJan Schmidt  * before calling btrfs_get_tree_mod_seq.
308097b8a7cSJan Schmidt  * Returns a fresh, unused tree log modification sequence number, even if no new
309097b8a7cSJan Schmidt  * blocker was added.
310097b8a7cSJan Schmidt  */
311097b8a7cSJan Schmidt u64 btrfs_get_tree_mod_seq(struct btrfs_fs_info *fs_info,
312bd989ba3SJan Schmidt 			   struct seq_list *elem)
313bd989ba3SJan Schmidt {
314b1a09f1eSDavid Sterba 	write_lock(&fs_info->tree_mod_log_lock);
315bd989ba3SJan Schmidt 	spin_lock(&fs_info->tree_mod_seq_lock);
316097b8a7cSJan Schmidt 	if (!elem->seq) {
317fcebe456SJosef Bacik 		elem->seq = btrfs_inc_tree_mod_seq(fs_info);
318097b8a7cSJan Schmidt 		list_add_tail(&elem->list, &fs_info->tree_mod_seq_list);
319097b8a7cSJan Schmidt 	}
320bd989ba3SJan Schmidt 	spin_unlock(&fs_info->tree_mod_seq_lock);
321b1a09f1eSDavid Sterba 	write_unlock(&fs_info->tree_mod_log_lock);
322097b8a7cSJan Schmidt 
323fcebe456SJosef Bacik 	return elem->seq;
324bd989ba3SJan Schmidt }
325bd989ba3SJan Schmidt 
326bd989ba3SJan Schmidt void btrfs_put_tree_mod_seq(struct btrfs_fs_info *fs_info,
327bd989ba3SJan Schmidt 			    struct seq_list *elem)
328bd989ba3SJan Schmidt {
329bd989ba3SJan Schmidt 	struct rb_root *tm_root;
330bd989ba3SJan Schmidt 	struct rb_node *node;
331bd989ba3SJan Schmidt 	struct rb_node *next;
332bd989ba3SJan Schmidt 	struct seq_list *cur_elem;
333bd989ba3SJan Schmidt 	struct tree_mod_elem *tm;
334bd989ba3SJan Schmidt 	u64 min_seq = (u64)-1;
335bd989ba3SJan Schmidt 	u64 seq_putting = elem->seq;
336bd989ba3SJan Schmidt 
337bd989ba3SJan Schmidt 	if (!seq_putting)
338bd989ba3SJan Schmidt 		return;
339bd989ba3SJan Schmidt 
340bd989ba3SJan Schmidt 	spin_lock(&fs_info->tree_mod_seq_lock);
341bd989ba3SJan Schmidt 	list_del(&elem->list);
342097b8a7cSJan Schmidt 	elem->seq = 0;
343bd989ba3SJan Schmidt 
344bd989ba3SJan Schmidt 	list_for_each_entry(cur_elem, &fs_info->tree_mod_seq_list, list) {
345097b8a7cSJan Schmidt 		if (cur_elem->seq < min_seq) {
346bd989ba3SJan Schmidt 			if (seq_putting > cur_elem->seq) {
347bd989ba3SJan Schmidt 				/*
348bd989ba3SJan Schmidt 				 * blocker with lower sequence number exists, we
349bd989ba3SJan Schmidt 				 * cannot remove anything from the log
350bd989ba3SJan Schmidt 				 */
351097b8a7cSJan Schmidt 				spin_unlock(&fs_info->tree_mod_seq_lock);
352097b8a7cSJan Schmidt 				return;
353bd989ba3SJan Schmidt 			}
354bd989ba3SJan Schmidt 			min_seq = cur_elem->seq;
355bd989ba3SJan Schmidt 		}
356bd989ba3SJan Schmidt 	}
357097b8a7cSJan Schmidt 	spin_unlock(&fs_info->tree_mod_seq_lock);
358097b8a7cSJan Schmidt 
359097b8a7cSJan Schmidt 	/*
360bd989ba3SJan Schmidt 	 * anything that's lower than the lowest existing (read: blocked)
361bd989ba3SJan Schmidt 	 * sequence number can be removed from the tree.
362bd989ba3SJan Schmidt 	 */
363b1a09f1eSDavid Sterba 	write_lock(&fs_info->tree_mod_log_lock);
364bd989ba3SJan Schmidt 	tm_root = &fs_info->tree_mod_log;
365bd989ba3SJan Schmidt 	for (node = rb_first(tm_root); node; node = next) {
366bd989ba3SJan Schmidt 		next = rb_next(node);
3676b4df8b6SGeliang Tang 		tm = rb_entry(node, struct tree_mod_elem, node);
368097b8a7cSJan Schmidt 		if (tm->seq > min_seq)
369bd989ba3SJan Schmidt 			continue;
370bd989ba3SJan Schmidt 		rb_erase(node, tm_root);
371bd989ba3SJan Schmidt 		kfree(tm);
372bd989ba3SJan Schmidt 	}
373b1a09f1eSDavid Sterba 	write_unlock(&fs_info->tree_mod_log_lock);
374bd989ba3SJan Schmidt }
375bd989ba3SJan Schmidt 
376bd989ba3SJan Schmidt /*
377bd989ba3SJan Schmidt  * key order of the log:
378298cfd36SChandan Rajendra  *       node/leaf start address -> sequence
379bd989ba3SJan Schmidt  *
380298cfd36SChandan Rajendra  * The 'start address' is the logical address of the *new* root node
381298cfd36SChandan Rajendra  * for root replace operations, or the logical address of the affected
382298cfd36SChandan Rajendra  * block for all other operations.
383bd989ba3SJan Schmidt  */
384bd989ba3SJan Schmidt static noinline int
385bd989ba3SJan Schmidt __tree_mod_log_insert(struct btrfs_fs_info *fs_info, struct tree_mod_elem *tm)
386bd989ba3SJan Schmidt {
387bd989ba3SJan Schmidt 	struct rb_root *tm_root;
388bd989ba3SJan Schmidt 	struct rb_node **new;
389bd989ba3SJan Schmidt 	struct rb_node *parent = NULL;
390bd989ba3SJan Schmidt 	struct tree_mod_elem *cur;
391bd989ba3SJan Schmidt 
39273e82fe4SDavid Sterba 	lockdep_assert_held_write(&fs_info->tree_mod_log_lock);
39373e82fe4SDavid Sterba 
394fcebe456SJosef Bacik 	tm->seq = btrfs_inc_tree_mod_seq(fs_info);
395bd989ba3SJan Schmidt 
396bd989ba3SJan Schmidt 	tm_root = &fs_info->tree_mod_log;
397bd989ba3SJan Schmidt 	new = &tm_root->rb_node;
398bd989ba3SJan Schmidt 	while (*new) {
3996b4df8b6SGeliang Tang 		cur = rb_entry(*new, struct tree_mod_elem, node);
400bd989ba3SJan Schmidt 		parent = *new;
401298cfd36SChandan Rajendra 		if (cur->logical < tm->logical)
402bd989ba3SJan Schmidt 			new = &((*new)->rb_left);
403298cfd36SChandan Rajendra 		else if (cur->logical > tm->logical)
404bd989ba3SJan Schmidt 			new = &((*new)->rb_right);
405097b8a7cSJan Schmidt 		else if (cur->seq < tm->seq)
406bd989ba3SJan Schmidt 			new = &((*new)->rb_left);
407097b8a7cSJan Schmidt 		else if (cur->seq > tm->seq)
408bd989ba3SJan Schmidt 			new = &((*new)->rb_right);
4095de865eeSFilipe David Borba Manana 		else
4105de865eeSFilipe David Borba Manana 			return -EEXIST;
411bd989ba3SJan Schmidt 	}
412bd989ba3SJan Schmidt 
413bd989ba3SJan Schmidt 	rb_link_node(&tm->node, parent, new);
414bd989ba3SJan Schmidt 	rb_insert_color(&tm->node, tm_root);
4155de865eeSFilipe David Borba Manana 	return 0;
416bd989ba3SJan Schmidt }
417bd989ba3SJan Schmidt 
418097b8a7cSJan Schmidt /*
419097b8a7cSJan Schmidt  * Determines if logging can be omitted. Returns 1 if it can. Otherwise, it
420097b8a7cSJan Schmidt  * returns zero with the tree_mod_log_lock acquired. The caller must hold
421097b8a7cSJan Schmidt  * this until all tree mod log insertions are recorded in the rb tree and then
422b1a09f1eSDavid Sterba  * write unlock fs_info::tree_mod_log_lock.
423097b8a7cSJan Schmidt  */
424e9b7fd4dSJan Schmidt static inline int tree_mod_dont_log(struct btrfs_fs_info *fs_info,
425e9b7fd4dSJan Schmidt 				    struct extent_buffer *eb) {
426e9b7fd4dSJan Schmidt 	smp_mb();
427e9b7fd4dSJan Schmidt 	if (list_empty(&(fs_info)->tree_mod_seq_list))
428e9b7fd4dSJan Schmidt 		return 1;
429097b8a7cSJan Schmidt 	if (eb && btrfs_header_level(eb) == 0)
430e9b7fd4dSJan Schmidt 		return 1;
4315de865eeSFilipe David Borba Manana 
432b1a09f1eSDavid Sterba 	write_lock(&fs_info->tree_mod_log_lock);
4335de865eeSFilipe David Borba Manana 	if (list_empty(&(fs_info)->tree_mod_seq_list)) {
434b1a09f1eSDavid Sterba 		write_unlock(&fs_info->tree_mod_log_lock);
4355de865eeSFilipe David Borba Manana 		return 1;
4365de865eeSFilipe David Borba Manana 	}
4375de865eeSFilipe David Borba Manana 
438e9b7fd4dSJan Schmidt 	return 0;
439e9b7fd4dSJan Schmidt }
440e9b7fd4dSJan Schmidt 
4415de865eeSFilipe David Borba Manana /* Similar to tree_mod_dont_log, but doesn't acquire any locks. */
4425de865eeSFilipe David Borba Manana static inline int tree_mod_need_log(const struct btrfs_fs_info *fs_info,
4435de865eeSFilipe David Borba Manana 				    struct extent_buffer *eb)
4445de865eeSFilipe David Borba Manana {
4455de865eeSFilipe David Borba Manana 	smp_mb();
4465de865eeSFilipe David Borba Manana 	if (list_empty(&(fs_info)->tree_mod_seq_list))
4475de865eeSFilipe David Borba Manana 		return 0;
4485de865eeSFilipe David Borba Manana 	if (eb && btrfs_header_level(eb) == 0)
4495de865eeSFilipe David Borba Manana 		return 0;
4505de865eeSFilipe David Borba Manana 
4515de865eeSFilipe David Borba Manana 	return 1;
4525de865eeSFilipe David Borba Manana }
4535de865eeSFilipe David Borba Manana 
4545de865eeSFilipe David Borba Manana static struct tree_mod_elem *
4555de865eeSFilipe David Borba Manana alloc_tree_mod_elem(struct extent_buffer *eb, int slot,
456bd989ba3SJan Schmidt 		    enum mod_log_op op, gfp_t flags)
457bd989ba3SJan Schmidt {
458097b8a7cSJan Schmidt 	struct tree_mod_elem *tm;
459bd989ba3SJan Schmidt 
460c8cc6341SJosef Bacik 	tm = kzalloc(sizeof(*tm), flags);
461c8cc6341SJosef Bacik 	if (!tm)
4625de865eeSFilipe David Borba Manana 		return NULL;
463bd989ba3SJan Schmidt 
464298cfd36SChandan Rajendra 	tm->logical = eb->start;
465bd989ba3SJan Schmidt 	if (op != MOD_LOG_KEY_ADD) {
466bd989ba3SJan Schmidt 		btrfs_node_key(eb, &tm->key, slot);
467bd989ba3SJan Schmidt 		tm->blockptr = btrfs_node_blockptr(eb, slot);
468bd989ba3SJan Schmidt 	}
469bd989ba3SJan Schmidt 	tm->op = op;
470bd989ba3SJan Schmidt 	tm->slot = slot;
471bd989ba3SJan Schmidt 	tm->generation = btrfs_node_ptr_generation(eb, slot);
4725de865eeSFilipe David Borba Manana 	RB_CLEAR_NODE(&tm->node);
473bd989ba3SJan Schmidt 
4745de865eeSFilipe David Borba Manana 	return tm;
475097b8a7cSJan Schmidt }
476097b8a7cSJan Schmidt 
477e09c2efeSDavid Sterba static noinline int tree_mod_log_insert_key(struct extent_buffer *eb, int slot,
478097b8a7cSJan Schmidt 		enum mod_log_op op, gfp_t flags)
479097b8a7cSJan Schmidt {
4805de865eeSFilipe David Borba Manana 	struct tree_mod_elem *tm;
4815de865eeSFilipe David Borba Manana 	int ret;
4825de865eeSFilipe David Borba Manana 
483e09c2efeSDavid Sterba 	if (!tree_mod_need_log(eb->fs_info, eb))
484097b8a7cSJan Schmidt 		return 0;
485097b8a7cSJan Schmidt 
4865de865eeSFilipe David Borba Manana 	tm = alloc_tree_mod_elem(eb, slot, op, flags);
4875de865eeSFilipe David Borba Manana 	if (!tm)
4885de865eeSFilipe David Borba Manana 		return -ENOMEM;
4895de865eeSFilipe David Borba Manana 
490e09c2efeSDavid Sterba 	if (tree_mod_dont_log(eb->fs_info, eb)) {
4915de865eeSFilipe David Borba Manana 		kfree(tm);
4925de865eeSFilipe David Borba Manana 		return 0;
4935de865eeSFilipe David Borba Manana 	}
4945de865eeSFilipe David Borba Manana 
495e09c2efeSDavid Sterba 	ret = __tree_mod_log_insert(eb->fs_info, tm);
496b1a09f1eSDavid Sterba 	write_unlock(&eb->fs_info->tree_mod_log_lock);
4975de865eeSFilipe David Borba Manana 	if (ret)
4985de865eeSFilipe David Borba Manana 		kfree(tm);
4995de865eeSFilipe David Borba Manana 
5005de865eeSFilipe David Borba Manana 	return ret;
501097b8a7cSJan Schmidt }
502097b8a7cSJan Schmidt 
5036074d45fSDavid Sterba static noinline int tree_mod_log_insert_move(struct extent_buffer *eb,
5046074d45fSDavid Sterba 		int dst_slot, int src_slot, int nr_items)
505bd989ba3SJan Schmidt {
5065de865eeSFilipe David Borba Manana 	struct tree_mod_elem *tm = NULL;
5075de865eeSFilipe David Borba Manana 	struct tree_mod_elem **tm_list = NULL;
5085de865eeSFilipe David Borba Manana 	int ret = 0;
509bd989ba3SJan Schmidt 	int i;
5105de865eeSFilipe David Borba Manana 	int locked = 0;
511bd989ba3SJan Schmidt 
5126074d45fSDavid Sterba 	if (!tree_mod_need_log(eb->fs_info, eb))
513f395694cSJan Schmidt 		return 0;
514bd989ba3SJan Schmidt 
515176ef8f5SDavid Sterba 	tm_list = kcalloc(nr_items, sizeof(struct tree_mod_elem *), GFP_NOFS);
5165de865eeSFilipe David Borba Manana 	if (!tm_list)
5175de865eeSFilipe David Borba Manana 		return -ENOMEM;
518bd989ba3SJan Schmidt 
519176ef8f5SDavid Sterba 	tm = kzalloc(sizeof(*tm), GFP_NOFS);
5205de865eeSFilipe David Borba Manana 	if (!tm) {
5215de865eeSFilipe David Borba Manana 		ret = -ENOMEM;
5225de865eeSFilipe David Borba Manana 		goto free_tms;
5235de865eeSFilipe David Borba Manana 	}
524f395694cSJan Schmidt 
525298cfd36SChandan Rajendra 	tm->logical = eb->start;
526bd989ba3SJan Schmidt 	tm->slot = src_slot;
527bd989ba3SJan Schmidt 	tm->move.dst_slot = dst_slot;
528bd989ba3SJan Schmidt 	tm->move.nr_items = nr_items;
529bd989ba3SJan Schmidt 	tm->op = MOD_LOG_MOVE_KEYS;
530bd989ba3SJan Schmidt 
5315de865eeSFilipe David Borba Manana 	for (i = 0; i + dst_slot < src_slot && i < nr_items; i++) {
5325de865eeSFilipe David Borba Manana 		tm_list[i] = alloc_tree_mod_elem(eb, i + dst_slot,
533176ef8f5SDavid Sterba 		    MOD_LOG_KEY_REMOVE_WHILE_MOVING, GFP_NOFS);
5345de865eeSFilipe David Borba Manana 		if (!tm_list[i]) {
5355de865eeSFilipe David Borba Manana 			ret = -ENOMEM;
5365de865eeSFilipe David Borba Manana 			goto free_tms;
5375de865eeSFilipe David Borba Manana 		}
538bd989ba3SJan Schmidt 	}
539bd989ba3SJan Schmidt 
5406074d45fSDavid Sterba 	if (tree_mod_dont_log(eb->fs_info, eb))
5415de865eeSFilipe David Borba Manana 		goto free_tms;
5425de865eeSFilipe David Borba Manana 	locked = 1;
5435de865eeSFilipe David Borba Manana 
5445de865eeSFilipe David Borba Manana 	/*
5455de865eeSFilipe David Borba Manana 	 * When we override something during the move, we log these removals.
5465de865eeSFilipe David Borba Manana 	 * This can only happen when we move towards the beginning of the
5475de865eeSFilipe David Borba Manana 	 * buffer, i.e. dst_slot < src_slot.
5485de865eeSFilipe David Borba Manana 	 */
5495de865eeSFilipe David Borba Manana 	for (i = 0; i + dst_slot < src_slot && i < nr_items; i++) {
5506074d45fSDavid Sterba 		ret = __tree_mod_log_insert(eb->fs_info, tm_list[i]);
5515de865eeSFilipe David Borba Manana 		if (ret)
5525de865eeSFilipe David Borba Manana 			goto free_tms;
5535de865eeSFilipe David Borba Manana 	}
5545de865eeSFilipe David Borba Manana 
5556074d45fSDavid Sterba 	ret = __tree_mod_log_insert(eb->fs_info, tm);
5565de865eeSFilipe David Borba Manana 	if (ret)
5575de865eeSFilipe David Borba Manana 		goto free_tms;
558b1a09f1eSDavid Sterba 	write_unlock(&eb->fs_info->tree_mod_log_lock);
5595de865eeSFilipe David Borba Manana 	kfree(tm_list);
5605de865eeSFilipe David Borba Manana 
5615de865eeSFilipe David Borba Manana 	return 0;
5625de865eeSFilipe David Borba Manana free_tms:
5635de865eeSFilipe David Borba Manana 	for (i = 0; i < nr_items; i++) {
5645de865eeSFilipe David Borba Manana 		if (tm_list[i] && !RB_EMPTY_NODE(&tm_list[i]->node))
5656074d45fSDavid Sterba 			rb_erase(&tm_list[i]->node, &eb->fs_info->tree_mod_log);
5665de865eeSFilipe David Borba Manana 		kfree(tm_list[i]);
5675de865eeSFilipe David Borba Manana 	}
5685de865eeSFilipe David Borba Manana 	if (locked)
569b1a09f1eSDavid Sterba 		write_unlock(&eb->fs_info->tree_mod_log_lock);
5705de865eeSFilipe David Borba Manana 	kfree(tm_list);
5715de865eeSFilipe David Borba Manana 	kfree(tm);
5725de865eeSFilipe David Borba Manana 
5735de865eeSFilipe David Borba Manana 	return ret;
5745de865eeSFilipe David Borba Manana }
5755de865eeSFilipe David Borba Manana 
5765de865eeSFilipe David Borba Manana static inline int
5775de865eeSFilipe David Borba Manana __tree_mod_log_free_eb(struct btrfs_fs_info *fs_info,
5785de865eeSFilipe David Borba Manana 		       struct tree_mod_elem **tm_list,
5795de865eeSFilipe David Borba Manana 		       int nritems)
580097b8a7cSJan Schmidt {
5815de865eeSFilipe David Borba Manana 	int i, j;
582097b8a7cSJan Schmidt 	int ret;
583097b8a7cSJan Schmidt 
584097b8a7cSJan Schmidt 	for (i = nritems - 1; i >= 0; i--) {
5855de865eeSFilipe David Borba Manana 		ret = __tree_mod_log_insert(fs_info, tm_list[i]);
5865de865eeSFilipe David Borba Manana 		if (ret) {
5875de865eeSFilipe David Borba Manana 			for (j = nritems - 1; j > i; j--)
5885de865eeSFilipe David Borba Manana 				rb_erase(&tm_list[j]->node,
5895de865eeSFilipe David Borba Manana 					 &fs_info->tree_mod_log);
5905de865eeSFilipe David Borba Manana 			return ret;
591097b8a7cSJan Schmidt 		}
592097b8a7cSJan Schmidt 	}
593097b8a7cSJan Schmidt 
5945de865eeSFilipe David Borba Manana 	return 0;
5955de865eeSFilipe David Borba Manana }
5965de865eeSFilipe David Borba Manana 
59795b757c1SDavid Sterba static noinline int tree_mod_log_insert_root(struct extent_buffer *old_root,
59895b757c1SDavid Sterba 			 struct extent_buffer *new_root, int log_removal)
599bd989ba3SJan Schmidt {
60095b757c1SDavid Sterba 	struct btrfs_fs_info *fs_info = old_root->fs_info;
6015de865eeSFilipe David Borba Manana 	struct tree_mod_elem *tm = NULL;
6025de865eeSFilipe David Borba Manana 	struct tree_mod_elem **tm_list = NULL;
6035de865eeSFilipe David Borba Manana 	int nritems = 0;
6045de865eeSFilipe David Borba Manana 	int ret = 0;
6055de865eeSFilipe David Borba Manana 	int i;
606bd989ba3SJan Schmidt 
6075de865eeSFilipe David Borba Manana 	if (!tree_mod_need_log(fs_info, NULL))
608097b8a7cSJan Schmidt 		return 0;
609097b8a7cSJan Schmidt 
6105de865eeSFilipe David Borba Manana 	if (log_removal && btrfs_header_level(old_root) > 0) {
6115de865eeSFilipe David Borba Manana 		nritems = btrfs_header_nritems(old_root);
61231e818feSDavid Sterba 		tm_list = kcalloc(nritems, sizeof(struct tree_mod_elem *),
613bcc8e07fSDavid Sterba 				  GFP_NOFS);
6145de865eeSFilipe David Borba Manana 		if (!tm_list) {
6155de865eeSFilipe David Borba Manana 			ret = -ENOMEM;
6165de865eeSFilipe David Borba Manana 			goto free_tms;
6175de865eeSFilipe David Borba Manana 		}
6185de865eeSFilipe David Borba Manana 		for (i = 0; i < nritems; i++) {
6195de865eeSFilipe David Borba Manana 			tm_list[i] = alloc_tree_mod_elem(old_root, i,
620bcc8e07fSDavid Sterba 			    MOD_LOG_KEY_REMOVE_WHILE_FREEING, GFP_NOFS);
6215de865eeSFilipe David Borba Manana 			if (!tm_list[i]) {
6225de865eeSFilipe David Borba Manana 				ret = -ENOMEM;
6235de865eeSFilipe David Borba Manana 				goto free_tms;
6245de865eeSFilipe David Borba Manana 			}
6255de865eeSFilipe David Borba Manana 		}
6265de865eeSFilipe David Borba Manana 	}
627d9abbf1cSJan Schmidt 
628bcc8e07fSDavid Sterba 	tm = kzalloc(sizeof(*tm), GFP_NOFS);
6295de865eeSFilipe David Borba Manana 	if (!tm) {
6305de865eeSFilipe David Borba Manana 		ret = -ENOMEM;
6315de865eeSFilipe David Borba Manana 		goto free_tms;
6325de865eeSFilipe David Borba Manana 	}
633bd989ba3SJan Schmidt 
634298cfd36SChandan Rajendra 	tm->logical = new_root->start;
635bd989ba3SJan Schmidt 	tm->old_root.logical = old_root->start;
636bd989ba3SJan Schmidt 	tm->old_root.level = btrfs_header_level(old_root);
637bd989ba3SJan Schmidt 	tm->generation = btrfs_header_generation(old_root);
638bd989ba3SJan Schmidt 	tm->op = MOD_LOG_ROOT_REPLACE;
639bd989ba3SJan Schmidt 
6405de865eeSFilipe David Borba Manana 	if (tree_mod_dont_log(fs_info, NULL))
6415de865eeSFilipe David Borba Manana 		goto free_tms;
6425de865eeSFilipe David Borba Manana 
6435de865eeSFilipe David Borba Manana 	if (tm_list)
6445de865eeSFilipe David Borba Manana 		ret = __tree_mod_log_free_eb(fs_info, tm_list, nritems);
6455de865eeSFilipe David Borba Manana 	if (!ret)
6465de865eeSFilipe David Borba Manana 		ret = __tree_mod_log_insert(fs_info, tm);
6475de865eeSFilipe David Borba Manana 
648b1a09f1eSDavid Sterba 	write_unlock(&fs_info->tree_mod_log_lock);
6495de865eeSFilipe David Borba Manana 	if (ret)
6505de865eeSFilipe David Borba Manana 		goto free_tms;
6515de865eeSFilipe David Borba Manana 	kfree(tm_list);
6525de865eeSFilipe David Borba Manana 
6535de865eeSFilipe David Borba Manana 	return ret;
6545de865eeSFilipe David Borba Manana 
6555de865eeSFilipe David Borba Manana free_tms:
6565de865eeSFilipe David Borba Manana 	if (tm_list) {
6575de865eeSFilipe David Borba Manana 		for (i = 0; i < nritems; i++)
6585de865eeSFilipe David Borba Manana 			kfree(tm_list[i]);
6595de865eeSFilipe David Borba Manana 		kfree(tm_list);
6605de865eeSFilipe David Borba Manana 	}
6615de865eeSFilipe David Borba Manana 	kfree(tm);
6625de865eeSFilipe David Borba Manana 
6635de865eeSFilipe David Borba Manana 	return ret;
664bd989ba3SJan Schmidt }
665bd989ba3SJan Schmidt 
666bd989ba3SJan Schmidt static struct tree_mod_elem *
667bd989ba3SJan Schmidt __tree_mod_log_search(struct btrfs_fs_info *fs_info, u64 start, u64 min_seq,
668bd989ba3SJan Schmidt 		      int smallest)
669bd989ba3SJan Schmidt {
670bd989ba3SJan Schmidt 	struct rb_root *tm_root;
671bd989ba3SJan Schmidt 	struct rb_node *node;
672bd989ba3SJan Schmidt 	struct tree_mod_elem *cur = NULL;
673bd989ba3SJan Schmidt 	struct tree_mod_elem *found = NULL;
674bd989ba3SJan Schmidt 
675b1a09f1eSDavid Sterba 	read_lock(&fs_info->tree_mod_log_lock);
676bd989ba3SJan Schmidt 	tm_root = &fs_info->tree_mod_log;
677bd989ba3SJan Schmidt 	node = tm_root->rb_node;
678bd989ba3SJan Schmidt 	while (node) {
6796b4df8b6SGeliang Tang 		cur = rb_entry(node, struct tree_mod_elem, node);
680298cfd36SChandan Rajendra 		if (cur->logical < start) {
681bd989ba3SJan Schmidt 			node = node->rb_left;
682298cfd36SChandan Rajendra 		} else if (cur->logical > start) {
683bd989ba3SJan Schmidt 			node = node->rb_right;
684097b8a7cSJan Schmidt 		} else if (cur->seq < min_seq) {
685bd989ba3SJan Schmidt 			node = node->rb_left;
686bd989ba3SJan Schmidt 		} else if (!smallest) {
687bd989ba3SJan Schmidt 			/* we want the node with the highest seq */
688bd989ba3SJan Schmidt 			if (found)
689097b8a7cSJan Schmidt 				BUG_ON(found->seq > cur->seq);
690bd989ba3SJan Schmidt 			found = cur;
691bd989ba3SJan Schmidt 			node = node->rb_left;
692097b8a7cSJan Schmidt 		} else if (cur->seq > min_seq) {
693bd989ba3SJan Schmidt 			/* we want the node with the smallest seq */
694bd989ba3SJan Schmidt 			if (found)
695097b8a7cSJan Schmidt 				BUG_ON(found->seq < cur->seq);
696bd989ba3SJan Schmidt 			found = cur;
697bd989ba3SJan Schmidt 			node = node->rb_right;
698bd989ba3SJan Schmidt 		} else {
699bd989ba3SJan Schmidt 			found = cur;
700bd989ba3SJan Schmidt 			break;
701bd989ba3SJan Schmidt 		}
702bd989ba3SJan Schmidt 	}
703b1a09f1eSDavid Sterba 	read_unlock(&fs_info->tree_mod_log_lock);
704bd989ba3SJan Schmidt 
705bd989ba3SJan Schmidt 	return found;
706bd989ba3SJan Schmidt }
707bd989ba3SJan Schmidt 
708bd989ba3SJan Schmidt /*
709bd989ba3SJan Schmidt  * this returns the element from the log with the smallest time sequence
710bd989ba3SJan Schmidt  * value that's in the log (the oldest log item). any element with a time
711bd989ba3SJan Schmidt  * sequence lower than min_seq will be ignored.
712bd989ba3SJan Schmidt  */
713bd989ba3SJan Schmidt static struct tree_mod_elem *
714bd989ba3SJan Schmidt tree_mod_log_search_oldest(struct btrfs_fs_info *fs_info, u64 start,
715bd989ba3SJan Schmidt 			   u64 min_seq)
716bd989ba3SJan Schmidt {
717bd989ba3SJan Schmidt 	return __tree_mod_log_search(fs_info, start, min_seq, 1);
718bd989ba3SJan Schmidt }
719bd989ba3SJan Schmidt 
720bd989ba3SJan Schmidt /*
721bd989ba3SJan Schmidt  * this returns the element from the log with the largest time sequence
722bd989ba3SJan Schmidt  * value that's in the log (the most recent log item). any element with
723bd989ba3SJan Schmidt  * a time sequence lower than min_seq will be ignored.
724bd989ba3SJan Schmidt  */
725bd989ba3SJan Schmidt static struct tree_mod_elem *
726bd989ba3SJan Schmidt tree_mod_log_search(struct btrfs_fs_info *fs_info, u64 start, u64 min_seq)
727bd989ba3SJan Schmidt {
728bd989ba3SJan Schmidt 	return __tree_mod_log_search(fs_info, start, min_seq, 0);
729bd989ba3SJan Schmidt }
730bd989ba3SJan Schmidt 
731ed874f0dSDavid Sterba static noinline int tree_mod_log_eb_copy(struct extent_buffer *dst,
732bd989ba3SJan Schmidt 		     struct extent_buffer *src, unsigned long dst_offset,
73390f8d62eSJan Schmidt 		     unsigned long src_offset, int nr_items)
734bd989ba3SJan Schmidt {
735ed874f0dSDavid Sterba 	struct btrfs_fs_info *fs_info = dst->fs_info;
7365de865eeSFilipe David Borba Manana 	int ret = 0;
7375de865eeSFilipe David Borba Manana 	struct tree_mod_elem **tm_list = NULL;
7385de865eeSFilipe David Borba Manana 	struct tree_mod_elem **tm_list_add, **tm_list_rem;
739bd989ba3SJan Schmidt 	int i;
7405de865eeSFilipe David Borba Manana 	int locked = 0;
741bd989ba3SJan Schmidt 
7425de865eeSFilipe David Borba Manana 	if (!tree_mod_need_log(fs_info, NULL))
7435de865eeSFilipe David Borba Manana 		return 0;
744bd989ba3SJan Schmidt 
745c8cc6341SJosef Bacik 	if (btrfs_header_level(dst) == 0 && btrfs_header_level(src) == 0)
7465de865eeSFilipe David Borba Manana 		return 0;
7475de865eeSFilipe David Borba Manana 
74831e818feSDavid Sterba 	tm_list = kcalloc(nr_items * 2, sizeof(struct tree_mod_elem *),
7495de865eeSFilipe David Borba Manana 			  GFP_NOFS);
7505de865eeSFilipe David Borba Manana 	if (!tm_list)
7515de865eeSFilipe David Borba Manana 		return -ENOMEM;
7525de865eeSFilipe David Borba Manana 
7535de865eeSFilipe David Borba Manana 	tm_list_add = tm_list;
7545de865eeSFilipe David Borba Manana 	tm_list_rem = tm_list + nr_items;
7555de865eeSFilipe David Borba Manana 	for (i = 0; i < nr_items; i++) {
7565de865eeSFilipe David Borba Manana 		tm_list_rem[i] = alloc_tree_mod_elem(src, i + src_offset,
7575de865eeSFilipe David Borba Manana 		    MOD_LOG_KEY_REMOVE, GFP_NOFS);
7585de865eeSFilipe David Borba Manana 		if (!tm_list_rem[i]) {
7595de865eeSFilipe David Borba Manana 			ret = -ENOMEM;
7605de865eeSFilipe David Borba Manana 			goto free_tms;
7615de865eeSFilipe David Borba Manana 		}
7625de865eeSFilipe David Borba Manana 
7635de865eeSFilipe David Borba Manana 		tm_list_add[i] = alloc_tree_mod_elem(dst, i + dst_offset,
7645de865eeSFilipe David Borba Manana 		    MOD_LOG_KEY_ADD, GFP_NOFS);
7655de865eeSFilipe David Borba Manana 		if (!tm_list_add[i]) {
7665de865eeSFilipe David Borba Manana 			ret = -ENOMEM;
7675de865eeSFilipe David Borba Manana 			goto free_tms;
7685de865eeSFilipe David Borba Manana 		}
7695de865eeSFilipe David Borba Manana 	}
7705de865eeSFilipe David Borba Manana 
7715de865eeSFilipe David Borba Manana 	if (tree_mod_dont_log(fs_info, NULL))
7725de865eeSFilipe David Borba Manana 		goto free_tms;
7735de865eeSFilipe David Borba Manana 	locked = 1;
774bd989ba3SJan Schmidt 
775bd989ba3SJan Schmidt 	for (i = 0; i < nr_items; i++) {
7765de865eeSFilipe David Borba Manana 		ret = __tree_mod_log_insert(fs_info, tm_list_rem[i]);
7775de865eeSFilipe David Borba Manana 		if (ret)
7785de865eeSFilipe David Borba Manana 			goto free_tms;
7795de865eeSFilipe David Borba Manana 		ret = __tree_mod_log_insert(fs_info, tm_list_add[i]);
7805de865eeSFilipe David Borba Manana 		if (ret)
7815de865eeSFilipe David Borba Manana 			goto free_tms;
782bd989ba3SJan Schmidt 	}
7835de865eeSFilipe David Borba Manana 
784b1a09f1eSDavid Sterba 	write_unlock(&fs_info->tree_mod_log_lock);
7855de865eeSFilipe David Borba Manana 	kfree(tm_list);
7865de865eeSFilipe David Borba Manana 
7875de865eeSFilipe David Borba Manana 	return 0;
7885de865eeSFilipe David Borba Manana 
7895de865eeSFilipe David Borba Manana free_tms:
7905de865eeSFilipe David Borba Manana 	for (i = 0; i < nr_items * 2; i++) {
7915de865eeSFilipe David Borba Manana 		if (tm_list[i] && !RB_EMPTY_NODE(&tm_list[i]->node))
7925de865eeSFilipe David Borba Manana 			rb_erase(&tm_list[i]->node, &fs_info->tree_mod_log);
7935de865eeSFilipe David Borba Manana 		kfree(tm_list[i]);
7945de865eeSFilipe David Borba Manana 	}
7955de865eeSFilipe David Borba Manana 	if (locked)
796b1a09f1eSDavid Sterba 		write_unlock(&fs_info->tree_mod_log_lock);
7975de865eeSFilipe David Borba Manana 	kfree(tm_list);
7985de865eeSFilipe David Borba Manana 
7995de865eeSFilipe David Borba Manana 	return ret;
800bd989ba3SJan Schmidt }
801bd989ba3SJan Schmidt 
802db7279a2SDavid Sterba static noinline int tree_mod_log_free_eb(struct extent_buffer *eb)
803bd989ba3SJan Schmidt {
8045de865eeSFilipe David Borba Manana 	struct tree_mod_elem **tm_list = NULL;
8055de865eeSFilipe David Borba Manana 	int nritems = 0;
8065de865eeSFilipe David Borba Manana 	int i;
8075de865eeSFilipe David Borba Manana 	int ret = 0;
8085de865eeSFilipe David Borba Manana 
8095de865eeSFilipe David Borba Manana 	if (btrfs_header_level(eb) == 0)
8105de865eeSFilipe David Borba Manana 		return 0;
8115de865eeSFilipe David Borba Manana 
812db7279a2SDavid Sterba 	if (!tree_mod_need_log(eb->fs_info, NULL))
8135de865eeSFilipe David Borba Manana 		return 0;
8145de865eeSFilipe David Borba Manana 
8155de865eeSFilipe David Borba Manana 	nritems = btrfs_header_nritems(eb);
81631e818feSDavid Sterba 	tm_list = kcalloc(nritems, sizeof(struct tree_mod_elem *), GFP_NOFS);
8175de865eeSFilipe David Borba Manana 	if (!tm_list)
8185de865eeSFilipe David Borba Manana 		return -ENOMEM;
8195de865eeSFilipe David Borba Manana 
8205de865eeSFilipe David Borba Manana 	for (i = 0; i < nritems; i++) {
8215de865eeSFilipe David Borba Manana 		tm_list[i] = alloc_tree_mod_elem(eb, i,
8225de865eeSFilipe David Borba Manana 		    MOD_LOG_KEY_REMOVE_WHILE_FREEING, GFP_NOFS);
8235de865eeSFilipe David Borba Manana 		if (!tm_list[i]) {
8245de865eeSFilipe David Borba Manana 			ret = -ENOMEM;
8255de865eeSFilipe David Borba Manana 			goto free_tms;
8265de865eeSFilipe David Borba Manana 		}
8275de865eeSFilipe David Borba Manana 	}
8285de865eeSFilipe David Borba Manana 
829db7279a2SDavid Sterba 	if (tree_mod_dont_log(eb->fs_info, eb))
8305de865eeSFilipe David Borba Manana 		goto free_tms;
8315de865eeSFilipe David Borba Manana 
832db7279a2SDavid Sterba 	ret = __tree_mod_log_free_eb(eb->fs_info, tm_list, nritems);
833b1a09f1eSDavid Sterba 	write_unlock(&eb->fs_info->tree_mod_log_lock);
8345de865eeSFilipe David Borba Manana 	if (ret)
8355de865eeSFilipe David Borba Manana 		goto free_tms;
8365de865eeSFilipe David Borba Manana 	kfree(tm_list);
8375de865eeSFilipe David Borba Manana 
8385de865eeSFilipe David Borba Manana 	return 0;
8395de865eeSFilipe David Borba Manana 
8405de865eeSFilipe David Borba Manana free_tms:
8415de865eeSFilipe David Borba Manana 	for (i = 0; i < nritems; i++)
8425de865eeSFilipe David Borba Manana 		kfree(tm_list[i]);
8435de865eeSFilipe David Borba Manana 	kfree(tm_list);
8445de865eeSFilipe David Borba Manana 
8455de865eeSFilipe David Borba Manana 	return ret;
846bd989ba3SJan Schmidt }
847bd989ba3SJan Schmidt 
848d352ac68SChris Mason /*
8495d4f98a2SYan Zheng  * check if the tree block can be shared by multiple trees
8505d4f98a2SYan Zheng  */
8515d4f98a2SYan Zheng int btrfs_block_can_be_shared(struct btrfs_root *root,
8525d4f98a2SYan Zheng 			      struct extent_buffer *buf)
8535d4f98a2SYan Zheng {
8545d4f98a2SYan Zheng 	/*
85501327610SNicholas D Steeves 	 * Tree blocks not in reference counted trees and tree roots
8565d4f98a2SYan Zheng 	 * are never shared. If a block was allocated after the last
8575d4f98a2SYan Zheng 	 * snapshot and the block was not allocated by tree relocation,
8585d4f98a2SYan Zheng 	 * we know the block is not shared.
8595d4f98a2SYan Zheng 	 */
86027cdeb70SMiao Xie 	if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
8615d4f98a2SYan Zheng 	    buf != root->node && buf != root->commit_root &&
8625d4f98a2SYan Zheng 	    (btrfs_header_generation(buf) <=
8635d4f98a2SYan Zheng 	     btrfs_root_last_snapshot(&root->root_item) ||
8645d4f98a2SYan Zheng 	     btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)))
8655d4f98a2SYan Zheng 		return 1;
866a79865c6SNikolay Borisov 
8675d4f98a2SYan Zheng 	return 0;
8685d4f98a2SYan Zheng }
8695d4f98a2SYan Zheng 
8705d4f98a2SYan Zheng static noinline int update_ref_for_cow(struct btrfs_trans_handle *trans,
8715d4f98a2SYan Zheng 				       struct btrfs_root *root,
8725d4f98a2SYan Zheng 				       struct extent_buffer *buf,
873f0486c68SYan, Zheng 				       struct extent_buffer *cow,
874f0486c68SYan, Zheng 				       int *last_ref)
8755d4f98a2SYan Zheng {
8760b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
8775d4f98a2SYan Zheng 	u64 refs;
8785d4f98a2SYan Zheng 	u64 owner;
8795d4f98a2SYan Zheng 	u64 flags;
8805d4f98a2SYan Zheng 	u64 new_flags = 0;
8815d4f98a2SYan Zheng 	int ret;
8825d4f98a2SYan Zheng 
8835d4f98a2SYan Zheng 	/*
8845d4f98a2SYan Zheng 	 * Backrefs update rules:
8855d4f98a2SYan Zheng 	 *
8865d4f98a2SYan Zheng 	 * Always use full backrefs for extent pointers in tree block
8875d4f98a2SYan Zheng 	 * allocated by tree relocation.
8885d4f98a2SYan Zheng 	 *
8895d4f98a2SYan Zheng 	 * If a shared tree block is no longer referenced by its owner
8905d4f98a2SYan Zheng 	 * tree (btrfs_header_owner(buf) == root->root_key.objectid),
8915d4f98a2SYan Zheng 	 * use full backrefs for extent pointers in tree block.
8925d4f98a2SYan Zheng 	 *
8935d4f98a2SYan Zheng 	 * If a tree block is been relocating
8945d4f98a2SYan Zheng 	 * (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID),
8955d4f98a2SYan Zheng 	 * use full backrefs for extent pointers in tree block.
8965d4f98a2SYan Zheng 	 * The reason for this is some operations (such as drop tree)
8975d4f98a2SYan Zheng 	 * are only allowed for blocks use full backrefs.
8985d4f98a2SYan Zheng 	 */
8995d4f98a2SYan Zheng 
9005d4f98a2SYan Zheng 	if (btrfs_block_can_be_shared(root, buf)) {
9012ff7e61eSJeff Mahoney 		ret = btrfs_lookup_extent_info(trans, fs_info, buf->start,
9023173a18fSJosef Bacik 					       btrfs_header_level(buf), 1,
9033173a18fSJosef Bacik 					       &refs, &flags);
904be1a5564SMark Fasheh 		if (ret)
905be1a5564SMark Fasheh 			return ret;
906e5df9573SMark Fasheh 		if (refs == 0) {
907e5df9573SMark Fasheh 			ret = -EROFS;
9080b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
909e5df9573SMark Fasheh 			return ret;
910e5df9573SMark Fasheh 		}
9115d4f98a2SYan Zheng 	} else {
9125d4f98a2SYan Zheng 		refs = 1;
9135d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
9145d4f98a2SYan Zheng 		    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
9155d4f98a2SYan Zheng 			flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
9165d4f98a2SYan Zheng 		else
9175d4f98a2SYan Zheng 			flags = 0;
9185d4f98a2SYan Zheng 	}
9195d4f98a2SYan Zheng 
9205d4f98a2SYan Zheng 	owner = btrfs_header_owner(buf);
9215d4f98a2SYan Zheng 	BUG_ON(owner == BTRFS_TREE_RELOC_OBJECTID &&
9225d4f98a2SYan Zheng 	       !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
9235d4f98a2SYan Zheng 
9245d4f98a2SYan Zheng 	if (refs > 1) {
9255d4f98a2SYan Zheng 		if ((owner == root->root_key.objectid ||
9265d4f98a2SYan Zheng 		     root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) &&
9275d4f98a2SYan Zheng 		    !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)) {
928e339a6b0SJosef Bacik 			ret = btrfs_inc_ref(trans, root, buf, 1);
929692826b2SJeff Mahoney 			if (ret)
930692826b2SJeff Mahoney 				return ret;
9315d4f98a2SYan Zheng 
9325d4f98a2SYan Zheng 			if (root->root_key.objectid ==
9335d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID) {
934e339a6b0SJosef Bacik 				ret = btrfs_dec_ref(trans, root, buf, 0);
935692826b2SJeff Mahoney 				if (ret)
936692826b2SJeff Mahoney 					return ret;
937e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
938692826b2SJeff Mahoney 				if (ret)
939692826b2SJeff Mahoney 					return ret;
9405d4f98a2SYan Zheng 			}
9415d4f98a2SYan Zheng 			new_flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
9425d4f98a2SYan Zheng 		} else {
9435d4f98a2SYan Zheng 
9445d4f98a2SYan Zheng 			if (root->root_key.objectid ==
9455d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID)
946e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
9475d4f98a2SYan Zheng 			else
948e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 0);
949692826b2SJeff Mahoney 			if (ret)
950692826b2SJeff Mahoney 				return ret;
9515d4f98a2SYan Zheng 		}
9525d4f98a2SYan Zheng 		if (new_flags != 0) {
953b1c79e09SJosef Bacik 			int level = btrfs_header_level(buf);
954b1c79e09SJosef Bacik 
955f5c8daa5SDavid Sterba 			ret = btrfs_set_disk_extent_flags(trans,
9565d4f98a2SYan Zheng 							  buf->start,
9575d4f98a2SYan Zheng 							  buf->len,
958b1c79e09SJosef Bacik 							  new_flags, level, 0);
959be1a5564SMark Fasheh 			if (ret)
960be1a5564SMark Fasheh 				return ret;
9615d4f98a2SYan Zheng 		}
9625d4f98a2SYan Zheng 	} else {
9635d4f98a2SYan Zheng 		if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
9645d4f98a2SYan Zheng 			if (root->root_key.objectid ==
9655d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID)
966e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
9675d4f98a2SYan Zheng 			else
968e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 0);
969692826b2SJeff Mahoney 			if (ret)
970692826b2SJeff Mahoney 				return ret;
971e339a6b0SJosef Bacik 			ret = btrfs_dec_ref(trans, root, buf, 1);
972692826b2SJeff Mahoney 			if (ret)
973692826b2SJeff Mahoney 				return ret;
9745d4f98a2SYan Zheng 		}
9756a884d7dSDavid Sterba 		btrfs_clean_tree_block(buf);
976f0486c68SYan, Zheng 		*last_ref = 1;
9775d4f98a2SYan Zheng 	}
9785d4f98a2SYan Zheng 	return 0;
9795d4f98a2SYan Zheng }
9805d4f98a2SYan Zheng 
981a6279470SFilipe Manana static struct extent_buffer *alloc_tree_block_no_bg_flush(
982a6279470SFilipe Manana 					  struct btrfs_trans_handle *trans,
983a6279470SFilipe Manana 					  struct btrfs_root *root,
984a6279470SFilipe Manana 					  u64 parent_start,
985a6279470SFilipe Manana 					  const struct btrfs_disk_key *disk_key,
986a6279470SFilipe Manana 					  int level,
987a6279470SFilipe Manana 					  u64 hint,
988a6279470SFilipe Manana 					  u64 empty_size)
989a6279470SFilipe Manana {
990a6279470SFilipe Manana 	struct btrfs_fs_info *fs_info = root->fs_info;
991a6279470SFilipe Manana 	struct extent_buffer *ret;
992a6279470SFilipe Manana 
993a6279470SFilipe Manana 	/*
994a6279470SFilipe Manana 	 * If we are COWing a node/leaf from the extent, chunk, device or free
995a6279470SFilipe Manana 	 * space trees, make sure that we do not finish block group creation of
996a6279470SFilipe Manana 	 * pending block groups. We do this to avoid a deadlock.
997a6279470SFilipe Manana 	 * COWing can result in allocation of a new chunk, and flushing pending
998a6279470SFilipe Manana 	 * block groups (btrfs_create_pending_block_groups()) can be triggered
999a6279470SFilipe Manana 	 * when finishing allocation of a new chunk. Creation of a pending block
1000a6279470SFilipe Manana 	 * group modifies the extent, chunk, device and free space trees,
1001a6279470SFilipe Manana 	 * therefore we could deadlock with ourselves since we are holding a
1002a6279470SFilipe Manana 	 * lock on an extent buffer that btrfs_create_pending_block_groups() may
1003a6279470SFilipe Manana 	 * try to COW later.
1004a6279470SFilipe Manana 	 * For similar reasons, we also need to delay flushing pending block
1005a6279470SFilipe Manana 	 * groups when splitting a leaf or node, from one of those trees, since
1006a6279470SFilipe Manana 	 * we are holding a write lock on it and its parent or when inserting a
1007a6279470SFilipe Manana 	 * new root node for one of those trees.
1008a6279470SFilipe Manana 	 */
1009a6279470SFilipe Manana 	if (root == fs_info->extent_root ||
1010a6279470SFilipe Manana 	    root == fs_info->chunk_root ||
1011a6279470SFilipe Manana 	    root == fs_info->dev_root ||
1012a6279470SFilipe Manana 	    root == fs_info->free_space_root)
1013a6279470SFilipe Manana 		trans->can_flush_pending_bgs = false;
1014a6279470SFilipe Manana 
1015a6279470SFilipe Manana 	ret = btrfs_alloc_tree_block(trans, root, parent_start,
1016a6279470SFilipe Manana 				     root->root_key.objectid, disk_key, level,
1017a6279470SFilipe Manana 				     hint, empty_size);
1018a6279470SFilipe Manana 	trans->can_flush_pending_bgs = true;
1019a6279470SFilipe Manana 
1020a6279470SFilipe Manana 	return ret;
1021a6279470SFilipe Manana }
1022a6279470SFilipe Manana 
10235d4f98a2SYan Zheng /*
1024d397712bSChris Mason  * does the dirty work in cow of a single block.  The parent block (if
1025d397712bSChris Mason  * supplied) is updated to point to the new cow copy.  The new buffer is marked
1026d397712bSChris Mason  * dirty and returned locked.  If you modify the block it needs to be marked
1027d397712bSChris Mason  * dirty again.
1028d352ac68SChris Mason  *
1029d352ac68SChris Mason  * search_start -- an allocation hint for the new block
1030d352ac68SChris Mason  *
1031d397712bSChris Mason  * empty_size -- a hint that you plan on doing more cow.  This is the size in
1032d397712bSChris Mason  * bytes the allocator should try to find free next to the block it returns.
1033d397712bSChris Mason  * This is just a hint and may be ignored by the allocator.
1034d352ac68SChris Mason  */
1035d397712bSChris Mason static noinline int __btrfs_cow_block(struct btrfs_trans_handle *trans,
10365f39d397SChris Mason 			     struct btrfs_root *root,
10375f39d397SChris Mason 			     struct extent_buffer *buf,
10385f39d397SChris Mason 			     struct extent_buffer *parent, int parent_slot,
10395f39d397SChris Mason 			     struct extent_buffer **cow_ret,
10409fa8cfe7SChris Mason 			     u64 search_start, u64 empty_size)
10416702ed49SChris Mason {
10420b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
10435d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
10445f39d397SChris Mason 	struct extent_buffer *cow;
1045be1a5564SMark Fasheh 	int level, ret;
1046f0486c68SYan, Zheng 	int last_ref = 0;
1047925baeddSChris Mason 	int unlock_orig = 0;
10480f5053ebSGoldwyn Rodrigues 	u64 parent_start = 0;
10496702ed49SChris Mason 
1050925baeddSChris Mason 	if (*cow_ret == buf)
1051925baeddSChris Mason 		unlock_orig = 1;
1052925baeddSChris Mason 
1053b9447ef8SChris Mason 	btrfs_assert_tree_locked(buf);
1054925baeddSChris Mason 
105527cdeb70SMiao Xie 	WARN_ON(test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
10560b246afaSJeff Mahoney 		trans->transid != fs_info->running_transaction->transid);
105727cdeb70SMiao Xie 	WARN_ON(test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
105827cdeb70SMiao Xie 		trans->transid != root->last_trans);
10595f39d397SChris Mason 
10607bb86316SChris Mason 	level = btrfs_header_level(buf);
106131840ae1SZheng Yan 
10625d4f98a2SYan Zheng 	if (level == 0)
10635d4f98a2SYan Zheng 		btrfs_item_key(buf, &disk_key, 0);
10645d4f98a2SYan Zheng 	else
10655d4f98a2SYan Zheng 		btrfs_node_key(buf, &disk_key, 0);
10665d4f98a2SYan Zheng 
10670f5053ebSGoldwyn Rodrigues 	if ((root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) && parent)
10685d4f98a2SYan Zheng 		parent_start = parent->start;
10695d4f98a2SYan Zheng 
1070a6279470SFilipe Manana 	cow = alloc_tree_block_no_bg_flush(trans, root, parent_start, &disk_key,
1071a6279470SFilipe Manana 					   level, search_start, empty_size);
10726702ed49SChris Mason 	if (IS_ERR(cow))
10736702ed49SChris Mason 		return PTR_ERR(cow);
10746702ed49SChris Mason 
1075b4ce94deSChris Mason 	/* cow is set to blocking by btrfs_init_new_buffer */
1076b4ce94deSChris Mason 
107758e8012cSDavid Sterba 	copy_extent_buffer_full(cow, buf);
1078db94535dSChris Mason 	btrfs_set_header_bytenr(cow, cow->start);
10795f39d397SChris Mason 	btrfs_set_header_generation(cow, trans->transid);
10805d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
10815d4f98a2SYan Zheng 	btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
10825d4f98a2SYan Zheng 				     BTRFS_HEADER_FLAG_RELOC);
10835d4f98a2SYan Zheng 	if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
10845d4f98a2SYan Zheng 		btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
10855d4f98a2SYan Zheng 	else
10865f39d397SChris Mason 		btrfs_set_header_owner(cow, root->root_key.objectid);
10876702ed49SChris Mason 
1088de37aa51SNikolay Borisov 	write_extent_buffer_fsid(cow, fs_info->fs_devices->metadata_uuid);
10892b82032cSYan Zheng 
1090be1a5564SMark Fasheh 	ret = update_ref_for_cow(trans, root, buf, cow, &last_ref);
1091b68dc2a9SMark Fasheh 	if (ret) {
109266642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
1093b68dc2a9SMark Fasheh 		return ret;
1094b68dc2a9SMark Fasheh 	}
10951a40e23bSZheng Yan 
109627cdeb70SMiao Xie 	if (test_bit(BTRFS_ROOT_REF_COWS, &root->state)) {
109783d4cfd4SJosef Bacik 		ret = btrfs_reloc_cow_block(trans, root, buf, cow);
109893314e3bSZhaolei 		if (ret) {
109966642832SJeff Mahoney 			btrfs_abort_transaction(trans, ret);
110083d4cfd4SJosef Bacik 			return ret;
110183d4cfd4SJosef Bacik 		}
110293314e3bSZhaolei 	}
11033fd0a558SYan, Zheng 
11046702ed49SChris Mason 	if (buf == root->node) {
1105925baeddSChris Mason 		WARN_ON(parent && parent != buf);
11065d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
11075d4f98a2SYan Zheng 		    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
11085d4f98a2SYan Zheng 			parent_start = buf->start;
1109925baeddSChris Mason 
111067439dadSDavid Sterba 		atomic_inc(&cow->refs);
1111d9d19a01SDavid Sterba 		ret = tree_mod_log_insert_root(root->node, cow, 1);
1112d9d19a01SDavid Sterba 		BUG_ON(ret < 0);
1113240f62c8SChris Mason 		rcu_assign_pointer(root->node, cow);
1114925baeddSChris Mason 
1115f0486c68SYan, Zheng 		btrfs_free_tree_block(trans, root, buf, parent_start,
11165581a51aSJan Schmidt 				      last_ref);
11175f39d397SChris Mason 		free_extent_buffer(buf);
11180b86a832SChris Mason 		add_root_to_dirty_list(root);
11196702ed49SChris Mason 	} else {
11205d4f98a2SYan Zheng 		WARN_ON(trans->transid != btrfs_header_generation(parent));
1121e09c2efeSDavid Sterba 		tree_mod_log_insert_key(parent, parent_slot,
1122c8cc6341SJosef Bacik 					MOD_LOG_KEY_REPLACE, GFP_NOFS);
11235f39d397SChris Mason 		btrfs_set_node_blockptr(parent, parent_slot,
1124db94535dSChris Mason 					cow->start);
112574493f7aSChris Mason 		btrfs_set_node_ptr_generation(parent, parent_slot,
112674493f7aSChris Mason 					      trans->transid);
11276702ed49SChris Mason 		btrfs_mark_buffer_dirty(parent);
11285de865eeSFilipe David Borba Manana 		if (last_ref) {
1129db7279a2SDavid Sterba 			ret = tree_mod_log_free_eb(buf);
11305de865eeSFilipe David Borba Manana 			if (ret) {
113166642832SJeff Mahoney 				btrfs_abort_transaction(trans, ret);
11325de865eeSFilipe David Borba Manana 				return ret;
11335de865eeSFilipe David Borba Manana 			}
11345de865eeSFilipe David Borba Manana 		}
1135f0486c68SYan, Zheng 		btrfs_free_tree_block(trans, root, buf, parent_start,
11365581a51aSJan Schmidt 				      last_ref);
11376702ed49SChris Mason 	}
1138925baeddSChris Mason 	if (unlock_orig)
1139925baeddSChris Mason 		btrfs_tree_unlock(buf);
11403083ee2eSJosef Bacik 	free_extent_buffer_stale(buf);
11416702ed49SChris Mason 	btrfs_mark_buffer_dirty(cow);
11426702ed49SChris Mason 	*cow_ret = cow;
11436702ed49SChris Mason 	return 0;
11446702ed49SChris Mason }
11456702ed49SChris Mason 
11465d9e75c4SJan Schmidt /*
11475d9e75c4SJan Schmidt  * returns the logical address of the oldest predecessor of the given root.
11485d9e75c4SJan Schmidt  * entries older than time_seq are ignored.
11495d9e75c4SJan Schmidt  */
1150bcd24dabSDavid Sterba static struct tree_mod_elem *__tree_mod_log_oldest_root(
115130b0463aSJan Schmidt 		struct extent_buffer *eb_root, u64 time_seq)
11525d9e75c4SJan Schmidt {
11535d9e75c4SJan Schmidt 	struct tree_mod_elem *tm;
11545d9e75c4SJan Schmidt 	struct tree_mod_elem *found = NULL;
115530b0463aSJan Schmidt 	u64 root_logical = eb_root->start;
11565d9e75c4SJan Schmidt 	int looped = 0;
11575d9e75c4SJan Schmidt 
11585d9e75c4SJan Schmidt 	if (!time_seq)
115935a3621bSStefan Behrens 		return NULL;
11605d9e75c4SJan Schmidt 
11615d9e75c4SJan Schmidt 	/*
1162298cfd36SChandan Rajendra 	 * the very last operation that's logged for a root is the
1163298cfd36SChandan Rajendra 	 * replacement operation (if it is replaced at all). this has
1164298cfd36SChandan Rajendra 	 * the logical address of the *new* root, making it the very
1165298cfd36SChandan Rajendra 	 * first operation that's logged for this root.
11665d9e75c4SJan Schmidt 	 */
11675d9e75c4SJan Schmidt 	while (1) {
1168bcd24dabSDavid Sterba 		tm = tree_mod_log_search_oldest(eb_root->fs_info, root_logical,
11695d9e75c4SJan Schmidt 						time_seq);
11705d9e75c4SJan Schmidt 		if (!looped && !tm)
117135a3621bSStefan Behrens 			return NULL;
11725d9e75c4SJan Schmidt 		/*
117328da9fb4SJan Schmidt 		 * if there are no tree operation for the oldest root, we simply
117428da9fb4SJan Schmidt 		 * return it. this should only happen if that (old) root is at
117528da9fb4SJan Schmidt 		 * level 0.
11765d9e75c4SJan Schmidt 		 */
117728da9fb4SJan Schmidt 		if (!tm)
117828da9fb4SJan Schmidt 			break;
11795d9e75c4SJan Schmidt 
118028da9fb4SJan Schmidt 		/*
118128da9fb4SJan Schmidt 		 * if there's an operation that's not a root replacement, we
118228da9fb4SJan Schmidt 		 * found the oldest version of our root. normally, we'll find a
118328da9fb4SJan Schmidt 		 * MOD_LOG_KEY_REMOVE_WHILE_FREEING operation here.
118428da9fb4SJan Schmidt 		 */
11855d9e75c4SJan Schmidt 		if (tm->op != MOD_LOG_ROOT_REPLACE)
11865d9e75c4SJan Schmidt 			break;
11875d9e75c4SJan Schmidt 
11885d9e75c4SJan Schmidt 		found = tm;
11895d9e75c4SJan Schmidt 		root_logical = tm->old_root.logical;
11905d9e75c4SJan Schmidt 		looped = 1;
11915d9e75c4SJan Schmidt 	}
11925d9e75c4SJan Schmidt 
1193a95236d9SJan Schmidt 	/* if there's no old root to return, return what we found instead */
1194a95236d9SJan Schmidt 	if (!found)
1195a95236d9SJan Schmidt 		found = tm;
1196a95236d9SJan Schmidt 
11975d9e75c4SJan Schmidt 	return found;
11985d9e75c4SJan Schmidt }
11995d9e75c4SJan Schmidt 
12005d9e75c4SJan Schmidt /*
12015d9e75c4SJan Schmidt  * tm is a pointer to the first operation to rewind within eb. then, all
120201327610SNicholas D Steeves  * previous operations will be rewound (until we reach something older than
12035d9e75c4SJan Schmidt  * time_seq).
12045d9e75c4SJan Schmidt  */
12055d9e75c4SJan Schmidt static void
1206f1ca7e98SJosef Bacik __tree_mod_log_rewind(struct btrfs_fs_info *fs_info, struct extent_buffer *eb,
1207f1ca7e98SJosef Bacik 		      u64 time_seq, struct tree_mod_elem *first_tm)
12085d9e75c4SJan Schmidt {
12095d9e75c4SJan Schmidt 	u32 n;
12105d9e75c4SJan Schmidt 	struct rb_node *next;
12115d9e75c4SJan Schmidt 	struct tree_mod_elem *tm = first_tm;
12125d9e75c4SJan Schmidt 	unsigned long o_dst;
12135d9e75c4SJan Schmidt 	unsigned long o_src;
12145d9e75c4SJan Schmidt 	unsigned long p_size = sizeof(struct btrfs_key_ptr);
12155d9e75c4SJan Schmidt 
12165d9e75c4SJan Schmidt 	n = btrfs_header_nritems(eb);
1217b1a09f1eSDavid Sterba 	read_lock(&fs_info->tree_mod_log_lock);
1218097b8a7cSJan Schmidt 	while (tm && tm->seq >= time_seq) {
12195d9e75c4SJan Schmidt 		/*
12205d9e75c4SJan Schmidt 		 * all the operations are recorded with the operator used for
12215d9e75c4SJan Schmidt 		 * the modification. as we're going backwards, we do the
12225d9e75c4SJan Schmidt 		 * opposite of each operation here.
12235d9e75c4SJan Schmidt 		 */
12245d9e75c4SJan Schmidt 		switch (tm->op) {
12255d9e75c4SJan Schmidt 		case MOD_LOG_KEY_REMOVE_WHILE_FREEING:
12265d9e75c4SJan Schmidt 			BUG_ON(tm->slot < n);
12271c697d4aSEric Sandeen 			/* Fallthrough */
122895c80bb1SLiu Bo 		case MOD_LOG_KEY_REMOVE_WHILE_MOVING:
12294c3e6969SChris Mason 		case MOD_LOG_KEY_REMOVE:
12305d9e75c4SJan Schmidt 			btrfs_set_node_key(eb, &tm->key, tm->slot);
12315d9e75c4SJan Schmidt 			btrfs_set_node_blockptr(eb, tm->slot, tm->blockptr);
12325d9e75c4SJan Schmidt 			btrfs_set_node_ptr_generation(eb, tm->slot,
12335d9e75c4SJan Schmidt 						      tm->generation);
12344c3e6969SChris Mason 			n++;
12355d9e75c4SJan Schmidt 			break;
12365d9e75c4SJan Schmidt 		case MOD_LOG_KEY_REPLACE:
12375d9e75c4SJan Schmidt 			BUG_ON(tm->slot >= n);
12385d9e75c4SJan Schmidt 			btrfs_set_node_key(eb, &tm->key, tm->slot);
12395d9e75c4SJan Schmidt 			btrfs_set_node_blockptr(eb, tm->slot, tm->blockptr);
12405d9e75c4SJan Schmidt 			btrfs_set_node_ptr_generation(eb, tm->slot,
12415d9e75c4SJan Schmidt 						      tm->generation);
12425d9e75c4SJan Schmidt 			break;
12435d9e75c4SJan Schmidt 		case MOD_LOG_KEY_ADD:
124419956c7eSJan Schmidt 			/* if a move operation is needed it's in the log */
12455d9e75c4SJan Schmidt 			n--;
12465d9e75c4SJan Schmidt 			break;
12475d9e75c4SJan Schmidt 		case MOD_LOG_MOVE_KEYS:
1248c3193108SJan Schmidt 			o_dst = btrfs_node_key_ptr_offset(tm->slot);
1249c3193108SJan Schmidt 			o_src = btrfs_node_key_ptr_offset(tm->move.dst_slot);
1250c3193108SJan Schmidt 			memmove_extent_buffer(eb, o_dst, o_src,
12515d9e75c4SJan Schmidt 					      tm->move.nr_items * p_size);
12525d9e75c4SJan Schmidt 			break;
12535d9e75c4SJan Schmidt 		case MOD_LOG_ROOT_REPLACE:
12545d9e75c4SJan Schmidt 			/*
12555d9e75c4SJan Schmidt 			 * this operation is special. for roots, this must be
12565d9e75c4SJan Schmidt 			 * handled explicitly before rewinding.
12575d9e75c4SJan Schmidt 			 * for non-roots, this operation may exist if the node
12585d9e75c4SJan Schmidt 			 * was a root: root A -> child B; then A gets empty and
12595d9e75c4SJan Schmidt 			 * B is promoted to the new root. in the mod log, we'll
12605d9e75c4SJan Schmidt 			 * have a root-replace operation for B, a tree block
12615d9e75c4SJan Schmidt 			 * that is no root. we simply ignore that operation.
12625d9e75c4SJan Schmidt 			 */
12635d9e75c4SJan Schmidt 			break;
12645d9e75c4SJan Schmidt 		}
12655d9e75c4SJan Schmidt 		next = rb_next(&tm->node);
12665d9e75c4SJan Schmidt 		if (!next)
12675d9e75c4SJan Schmidt 			break;
12686b4df8b6SGeliang Tang 		tm = rb_entry(next, struct tree_mod_elem, node);
1269298cfd36SChandan Rajendra 		if (tm->logical != first_tm->logical)
12705d9e75c4SJan Schmidt 			break;
12715d9e75c4SJan Schmidt 	}
1272b1a09f1eSDavid Sterba 	read_unlock(&fs_info->tree_mod_log_lock);
12735d9e75c4SJan Schmidt 	btrfs_set_header_nritems(eb, n);
12745d9e75c4SJan Schmidt }
12755d9e75c4SJan Schmidt 
127647fb091fSJan Schmidt /*
127701327610SNicholas D Steeves  * Called with eb read locked. If the buffer cannot be rewound, the same buffer
127847fb091fSJan Schmidt  * is returned. If rewind operations happen, a fresh buffer is returned. The
127947fb091fSJan Schmidt  * returned buffer is always read-locked. If the returned buffer is not the
128047fb091fSJan Schmidt  * input buffer, the lock on the input buffer is released and the input buffer
128147fb091fSJan Schmidt  * is freed (its refcount is decremented).
128247fb091fSJan Schmidt  */
12835d9e75c4SJan Schmidt static struct extent_buffer *
12849ec72677SJosef Bacik tree_mod_log_rewind(struct btrfs_fs_info *fs_info, struct btrfs_path *path,
12859ec72677SJosef Bacik 		    struct extent_buffer *eb, u64 time_seq)
12865d9e75c4SJan Schmidt {
12875d9e75c4SJan Schmidt 	struct extent_buffer *eb_rewin;
12885d9e75c4SJan Schmidt 	struct tree_mod_elem *tm;
12895d9e75c4SJan Schmidt 
12905d9e75c4SJan Schmidt 	if (!time_seq)
12915d9e75c4SJan Schmidt 		return eb;
12925d9e75c4SJan Schmidt 
12935d9e75c4SJan Schmidt 	if (btrfs_header_level(eb) == 0)
12945d9e75c4SJan Schmidt 		return eb;
12955d9e75c4SJan Schmidt 
12965d9e75c4SJan Schmidt 	tm = tree_mod_log_search(fs_info, eb->start, time_seq);
12975d9e75c4SJan Schmidt 	if (!tm)
12985d9e75c4SJan Schmidt 		return eb;
12995d9e75c4SJan Schmidt 
13009ec72677SJosef Bacik 	btrfs_set_path_blocking(path);
1301300aa896SDavid Sterba 	btrfs_set_lock_blocking_read(eb);
13029ec72677SJosef Bacik 
13035d9e75c4SJan Schmidt 	if (tm->op == MOD_LOG_KEY_REMOVE_WHILE_FREEING) {
13045d9e75c4SJan Schmidt 		BUG_ON(tm->slot != 0);
1305da17066cSJeff Mahoney 		eb_rewin = alloc_dummy_extent_buffer(fs_info, eb->start);
1306db7f3436SJosef Bacik 		if (!eb_rewin) {
13079ec72677SJosef Bacik 			btrfs_tree_read_unlock_blocking(eb);
1308db7f3436SJosef Bacik 			free_extent_buffer(eb);
1309db7f3436SJosef Bacik 			return NULL;
1310db7f3436SJosef Bacik 		}
13115d9e75c4SJan Schmidt 		btrfs_set_header_bytenr(eb_rewin, eb->start);
13125d9e75c4SJan Schmidt 		btrfs_set_header_backref_rev(eb_rewin,
13135d9e75c4SJan Schmidt 					     btrfs_header_backref_rev(eb));
13145d9e75c4SJan Schmidt 		btrfs_set_header_owner(eb_rewin, btrfs_header_owner(eb));
1315c3193108SJan Schmidt 		btrfs_set_header_level(eb_rewin, btrfs_header_level(eb));
13165d9e75c4SJan Schmidt 	} else {
13175d9e75c4SJan Schmidt 		eb_rewin = btrfs_clone_extent_buffer(eb);
1318db7f3436SJosef Bacik 		if (!eb_rewin) {
13199ec72677SJosef Bacik 			btrfs_tree_read_unlock_blocking(eb);
1320db7f3436SJosef Bacik 			free_extent_buffer(eb);
1321db7f3436SJosef Bacik 			return NULL;
1322db7f3436SJosef Bacik 		}
13235d9e75c4SJan Schmidt 	}
13245d9e75c4SJan Schmidt 
13259ec72677SJosef Bacik 	btrfs_tree_read_unlock_blocking(eb);
13265d9e75c4SJan Schmidt 	free_extent_buffer(eb);
13275d9e75c4SJan Schmidt 
132847fb091fSJan Schmidt 	btrfs_tree_read_lock(eb_rewin);
1329f1ca7e98SJosef Bacik 	__tree_mod_log_rewind(fs_info, eb_rewin, time_seq, tm);
133057911b8bSJan Schmidt 	WARN_ON(btrfs_header_nritems(eb_rewin) >
1331da17066cSJeff Mahoney 		BTRFS_NODEPTRS_PER_BLOCK(fs_info));
13325d9e75c4SJan Schmidt 
13335d9e75c4SJan Schmidt 	return eb_rewin;
13345d9e75c4SJan Schmidt }
13355d9e75c4SJan Schmidt 
13368ba97a15SJan Schmidt /*
13378ba97a15SJan Schmidt  * get_old_root() rewinds the state of @root's root node to the given @time_seq
13388ba97a15SJan Schmidt  * value. If there are no changes, the current root->root_node is returned. If
13398ba97a15SJan Schmidt  * anything changed in between, there's a fresh buffer allocated on which the
13408ba97a15SJan Schmidt  * rewind operations are done. In any case, the returned buffer is read locked.
13418ba97a15SJan Schmidt  * Returns NULL on error (with no locks held).
13428ba97a15SJan Schmidt  */
13435d9e75c4SJan Schmidt static inline struct extent_buffer *
13445d9e75c4SJan Schmidt get_old_root(struct btrfs_root *root, u64 time_seq)
13455d9e75c4SJan Schmidt {
13460b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
13475d9e75c4SJan Schmidt 	struct tree_mod_elem *tm;
134830b0463aSJan Schmidt 	struct extent_buffer *eb = NULL;
134930b0463aSJan Schmidt 	struct extent_buffer *eb_root;
1350efad8a85SFilipe Manana 	u64 eb_root_owner = 0;
13517bfdcf7fSLiu Bo 	struct extent_buffer *old;
1352a95236d9SJan Schmidt 	struct tree_mod_root *old_root = NULL;
13534325edd0SChris Mason 	u64 old_generation = 0;
1354a95236d9SJan Schmidt 	u64 logical;
1355581c1760SQu Wenruo 	int level;
13565d9e75c4SJan Schmidt 
135730b0463aSJan Schmidt 	eb_root = btrfs_read_lock_root_node(root);
1358bcd24dabSDavid Sterba 	tm = __tree_mod_log_oldest_root(eb_root, time_seq);
13595d9e75c4SJan Schmidt 	if (!tm)
136030b0463aSJan Schmidt 		return eb_root;
13615d9e75c4SJan Schmidt 
1362a95236d9SJan Schmidt 	if (tm->op == MOD_LOG_ROOT_REPLACE) {
13635d9e75c4SJan Schmidt 		old_root = &tm->old_root;
13645d9e75c4SJan Schmidt 		old_generation = tm->generation;
1365a95236d9SJan Schmidt 		logical = old_root->logical;
1366581c1760SQu Wenruo 		level = old_root->level;
1367a95236d9SJan Schmidt 	} else {
136830b0463aSJan Schmidt 		logical = eb_root->start;
1369581c1760SQu Wenruo 		level = btrfs_header_level(eb_root);
1370a95236d9SJan Schmidt 	}
13715d9e75c4SJan Schmidt 
13720b246afaSJeff Mahoney 	tm = tree_mod_log_search(fs_info, logical, time_seq);
1373834328a8SJan Schmidt 	if (old_root && tm && tm->op != MOD_LOG_KEY_REMOVE_WHILE_FREEING) {
137430b0463aSJan Schmidt 		btrfs_tree_read_unlock(eb_root);
137530b0463aSJan Schmidt 		free_extent_buffer(eb_root);
1376581c1760SQu Wenruo 		old = read_tree_block(fs_info, logical, 0, level, NULL);
137764c043deSLiu Bo 		if (WARN_ON(IS_ERR(old) || !extent_buffer_uptodate(old))) {
137864c043deSLiu Bo 			if (!IS_ERR(old))
1379416bc658SJosef Bacik 				free_extent_buffer(old);
13800b246afaSJeff Mahoney 			btrfs_warn(fs_info,
13810b246afaSJeff Mahoney 				   "failed to read tree block %llu from get_old_root",
13820b246afaSJeff Mahoney 				   logical);
1383834328a8SJan Schmidt 		} else {
13847bfdcf7fSLiu Bo 			eb = btrfs_clone_extent_buffer(old);
13857bfdcf7fSLiu Bo 			free_extent_buffer(old);
1386834328a8SJan Schmidt 		}
1387834328a8SJan Schmidt 	} else if (old_root) {
1388efad8a85SFilipe Manana 		eb_root_owner = btrfs_header_owner(eb_root);
138930b0463aSJan Schmidt 		btrfs_tree_read_unlock(eb_root);
139030b0463aSJan Schmidt 		free_extent_buffer(eb_root);
13910b246afaSJeff Mahoney 		eb = alloc_dummy_extent_buffer(fs_info, logical);
1392834328a8SJan Schmidt 	} else {
1393300aa896SDavid Sterba 		btrfs_set_lock_blocking_read(eb_root);
139430b0463aSJan Schmidt 		eb = btrfs_clone_extent_buffer(eb_root);
13959ec72677SJosef Bacik 		btrfs_tree_read_unlock_blocking(eb_root);
139630b0463aSJan Schmidt 		free_extent_buffer(eb_root);
1397834328a8SJan Schmidt 	}
1398834328a8SJan Schmidt 
13998ba97a15SJan Schmidt 	if (!eb)
14008ba97a15SJan Schmidt 		return NULL;
14018ba97a15SJan Schmidt 	btrfs_tree_read_lock(eb);
1402a95236d9SJan Schmidt 	if (old_root) {
14035d9e75c4SJan Schmidt 		btrfs_set_header_bytenr(eb, eb->start);
14045d9e75c4SJan Schmidt 		btrfs_set_header_backref_rev(eb, BTRFS_MIXED_BACKREF_REV);
1405efad8a85SFilipe Manana 		btrfs_set_header_owner(eb, eb_root_owner);
14065d9e75c4SJan Schmidt 		btrfs_set_header_level(eb, old_root->level);
14075d9e75c4SJan Schmidt 		btrfs_set_header_generation(eb, old_generation);
1408a95236d9SJan Schmidt 	}
140928da9fb4SJan Schmidt 	if (tm)
14100b246afaSJeff Mahoney 		__tree_mod_log_rewind(fs_info, eb, time_seq, tm);
141128da9fb4SJan Schmidt 	else
141228da9fb4SJan Schmidt 		WARN_ON(btrfs_header_level(eb) != 0);
14130b246afaSJeff Mahoney 	WARN_ON(btrfs_header_nritems(eb) > BTRFS_NODEPTRS_PER_BLOCK(fs_info));
14145d9e75c4SJan Schmidt 
14155d9e75c4SJan Schmidt 	return eb;
14165d9e75c4SJan Schmidt }
14175d9e75c4SJan Schmidt 
14185b6602e7SJan Schmidt int btrfs_old_root_level(struct btrfs_root *root, u64 time_seq)
14195b6602e7SJan Schmidt {
14205b6602e7SJan Schmidt 	struct tree_mod_elem *tm;
14215b6602e7SJan Schmidt 	int level;
142230b0463aSJan Schmidt 	struct extent_buffer *eb_root = btrfs_root_node(root);
14235b6602e7SJan Schmidt 
1424bcd24dabSDavid Sterba 	tm = __tree_mod_log_oldest_root(eb_root, time_seq);
14255b6602e7SJan Schmidt 	if (tm && tm->op == MOD_LOG_ROOT_REPLACE) {
14265b6602e7SJan Schmidt 		level = tm->old_root.level;
14275b6602e7SJan Schmidt 	} else {
142830b0463aSJan Schmidt 		level = btrfs_header_level(eb_root);
14295b6602e7SJan Schmidt 	}
143030b0463aSJan Schmidt 	free_extent_buffer(eb_root);
14315b6602e7SJan Schmidt 
14325b6602e7SJan Schmidt 	return level;
14335b6602e7SJan Schmidt }
14345b6602e7SJan Schmidt 
14355d4f98a2SYan Zheng static inline int should_cow_block(struct btrfs_trans_handle *trans,
14365d4f98a2SYan Zheng 				   struct btrfs_root *root,
14375d4f98a2SYan Zheng 				   struct extent_buffer *buf)
14385d4f98a2SYan Zheng {
1439f5ee5c9aSJeff Mahoney 	if (btrfs_is_testing(root->fs_info))
1440faa2dbf0SJosef Bacik 		return 0;
1441fccb84c9SDavid Sterba 
1442d1980131SDavid Sterba 	/* Ensure we can see the FORCE_COW bit */
1443d1980131SDavid Sterba 	smp_mb__before_atomic();
1444f1ebcc74SLiu Bo 
1445f1ebcc74SLiu Bo 	/*
1446f1ebcc74SLiu Bo 	 * We do not need to cow a block if
1447f1ebcc74SLiu Bo 	 * 1) this block is not created or changed in this transaction;
1448f1ebcc74SLiu Bo 	 * 2) this block does not belong to TREE_RELOC tree;
1449f1ebcc74SLiu Bo 	 * 3) the root is not forced COW.
1450f1ebcc74SLiu Bo 	 *
1451f1ebcc74SLiu Bo 	 * What is forced COW:
145201327610SNicholas D Steeves 	 *    when we create snapshot during committing the transaction,
145352042d8eSAndrea Gelmini 	 *    after we've finished copying src root, we must COW the shared
1454f1ebcc74SLiu Bo 	 *    block to ensure the metadata consistency.
1455f1ebcc74SLiu Bo 	 */
14565d4f98a2SYan Zheng 	if (btrfs_header_generation(buf) == trans->transid &&
14575d4f98a2SYan Zheng 	    !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN) &&
14585d4f98a2SYan Zheng 	    !(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
1459f1ebcc74SLiu Bo 	      btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)) &&
146027cdeb70SMiao Xie 	    !test_bit(BTRFS_ROOT_FORCE_COW, &root->state))
14615d4f98a2SYan Zheng 		return 0;
14625d4f98a2SYan Zheng 	return 1;
14635d4f98a2SYan Zheng }
14645d4f98a2SYan Zheng 
1465d352ac68SChris Mason /*
1466d352ac68SChris Mason  * cows a single block, see __btrfs_cow_block for the real work.
146701327610SNicholas D Steeves  * This version of it has extra checks so that a block isn't COWed more than
1468d352ac68SChris Mason  * once per transaction, as long as it hasn't been written yet
1469d352ac68SChris Mason  */
1470d397712bSChris Mason noinline int btrfs_cow_block(struct btrfs_trans_handle *trans,
14715f39d397SChris Mason 		    struct btrfs_root *root, struct extent_buffer *buf,
14725f39d397SChris Mason 		    struct extent_buffer *parent, int parent_slot,
14739fa8cfe7SChris Mason 		    struct extent_buffer **cow_ret)
147402217ed2SChris Mason {
14750b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
14766702ed49SChris Mason 	u64 search_start;
1477f510cfecSChris Mason 	int ret;
1478dc17ff8fSChris Mason 
147983354f07SJosef Bacik 	if (test_bit(BTRFS_ROOT_DELETING, &root->state))
148083354f07SJosef Bacik 		btrfs_err(fs_info,
148183354f07SJosef Bacik 			"COW'ing blocks on a fs root that's being dropped");
148283354f07SJosef Bacik 
14830b246afaSJeff Mahoney 	if (trans->transaction != fs_info->running_transaction)
148431b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "trans %llu running %llu\n",
1485c1c9ff7cSGeert Uytterhoeven 		       trans->transid,
14860b246afaSJeff Mahoney 		       fs_info->running_transaction->transid);
148731b1a2bdSJulia Lawall 
14880b246afaSJeff Mahoney 	if (trans->transid != fs_info->generation)
148931b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "trans %llu running %llu\n",
14900b246afaSJeff Mahoney 		       trans->transid, fs_info->generation);
1491dc17ff8fSChris Mason 
14925d4f98a2SYan Zheng 	if (!should_cow_block(trans, root, buf)) {
149364c12921SJeff Mahoney 		trans->dirty = true;
149402217ed2SChris Mason 		*cow_ret = buf;
149502217ed2SChris Mason 		return 0;
149602217ed2SChris Mason 	}
1497c487685dSChris Mason 
1498ee22184bSByongho Lee 	search_start = buf->start & ~((u64)SZ_1G - 1);
1499b4ce94deSChris Mason 
1500b4ce94deSChris Mason 	if (parent)
15018bead258SDavid Sterba 		btrfs_set_lock_blocking_write(parent);
15028bead258SDavid Sterba 	btrfs_set_lock_blocking_write(buf);
1503b4ce94deSChris Mason 
1504f616f5cdSQu Wenruo 	/*
1505f616f5cdSQu Wenruo 	 * Before CoWing this block for later modification, check if it's
1506f616f5cdSQu Wenruo 	 * the subtree root and do the delayed subtree trace if needed.
1507f616f5cdSQu Wenruo 	 *
1508f616f5cdSQu Wenruo 	 * Also We don't care about the error, as it's handled internally.
1509f616f5cdSQu Wenruo 	 */
1510f616f5cdSQu Wenruo 	btrfs_qgroup_trace_subtree_after_cow(trans, root, buf);
1511f510cfecSChris Mason 	ret = __btrfs_cow_block(trans, root, buf, parent,
15129fa8cfe7SChris Mason 				 parent_slot, cow_ret, search_start, 0);
15131abe9b8aSliubo 
15141abe9b8aSliubo 	trace_btrfs_cow_block(root, buf, *cow_ret);
15151abe9b8aSliubo 
1516f510cfecSChris Mason 	return ret;
15172c90e5d6SChris Mason }
15186702ed49SChris Mason 
1519d352ac68SChris Mason /*
1520d352ac68SChris Mason  * helper function for defrag to decide if two blocks pointed to by a
1521d352ac68SChris Mason  * node are actually close by
1522d352ac68SChris Mason  */
15236b80053dSChris Mason static int close_blocks(u64 blocknr, u64 other, u32 blocksize)
15246702ed49SChris Mason {
15256b80053dSChris Mason 	if (blocknr < other && other - (blocknr + blocksize) < 32768)
15266702ed49SChris Mason 		return 1;
15276b80053dSChris Mason 	if (blocknr > other && blocknr - (other + blocksize) < 32768)
15286702ed49SChris Mason 		return 1;
152902217ed2SChris Mason 	return 0;
153002217ed2SChris Mason }
153102217ed2SChris Mason 
1532081e9573SChris Mason /*
1533081e9573SChris Mason  * compare two keys in a memcmp fashion
1534081e9573SChris Mason  */
1535310712b2SOmar Sandoval static int comp_keys(const struct btrfs_disk_key *disk,
1536310712b2SOmar Sandoval 		     const struct btrfs_key *k2)
1537081e9573SChris Mason {
1538081e9573SChris Mason 	struct btrfs_key k1;
1539081e9573SChris Mason 
1540081e9573SChris Mason 	btrfs_disk_key_to_cpu(&k1, disk);
1541081e9573SChris Mason 
154220736abaSDiego Calleja 	return btrfs_comp_cpu_keys(&k1, k2);
1543081e9573SChris Mason }
1544081e9573SChris Mason 
1545f3465ca4SJosef Bacik /*
1546f3465ca4SJosef Bacik  * same as comp_keys only with two btrfs_key's
1547f3465ca4SJosef Bacik  */
1548e1f60a65SDavid Sterba int __pure btrfs_comp_cpu_keys(const struct btrfs_key *k1, const struct btrfs_key *k2)
1549f3465ca4SJosef Bacik {
1550f3465ca4SJosef Bacik 	if (k1->objectid > k2->objectid)
1551f3465ca4SJosef Bacik 		return 1;
1552f3465ca4SJosef Bacik 	if (k1->objectid < k2->objectid)
1553f3465ca4SJosef Bacik 		return -1;
1554f3465ca4SJosef Bacik 	if (k1->type > k2->type)
1555f3465ca4SJosef Bacik 		return 1;
1556f3465ca4SJosef Bacik 	if (k1->type < k2->type)
1557f3465ca4SJosef Bacik 		return -1;
1558f3465ca4SJosef Bacik 	if (k1->offset > k2->offset)
1559f3465ca4SJosef Bacik 		return 1;
1560f3465ca4SJosef Bacik 	if (k1->offset < k2->offset)
1561f3465ca4SJosef Bacik 		return -1;
1562f3465ca4SJosef Bacik 	return 0;
1563f3465ca4SJosef Bacik }
1564081e9573SChris Mason 
1565d352ac68SChris Mason /*
1566d352ac68SChris Mason  * this is used by the defrag code to go through all the
1567d352ac68SChris Mason  * leaves pointed to by a node and reallocate them so that
1568d352ac68SChris Mason  * disk order is close to key order
1569d352ac68SChris Mason  */
15706702ed49SChris Mason int btrfs_realloc_node(struct btrfs_trans_handle *trans,
15715f39d397SChris Mason 		       struct btrfs_root *root, struct extent_buffer *parent,
1572de78b51aSEric Sandeen 		       int start_slot, u64 *last_ret,
1573a6b6e75eSChris Mason 		       struct btrfs_key *progress)
15746702ed49SChris Mason {
15750b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
15766b80053dSChris Mason 	struct extent_buffer *cur;
15776702ed49SChris Mason 	u64 blocknr;
1578ca7a79adSChris Mason 	u64 gen;
1579e9d0b13bSChris Mason 	u64 search_start = *last_ret;
1580e9d0b13bSChris Mason 	u64 last_block = 0;
15816702ed49SChris Mason 	u64 other;
15826702ed49SChris Mason 	u32 parent_nritems;
15836702ed49SChris Mason 	int end_slot;
15846702ed49SChris Mason 	int i;
15856702ed49SChris Mason 	int err = 0;
1586f2183bdeSChris Mason 	int parent_level;
15876b80053dSChris Mason 	int uptodate;
15886b80053dSChris Mason 	u32 blocksize;
1589081e9573SChris Mason 	int progress_passed = 0;
1590081e9573SChris Mason 	struct btrfs_disk_key disk_key;
15916702ed49SChris Mason 
15925708b959SChris Mason 	parent_level = btrfs_header_level(parent);
15935708b959SChris Mason 
15940b246afaSJeff Mahoney 	WARN_ON(trans->transaction != fs_info->running_transaction);
15950b246afaSJeff Mahoney 	WARN_ON(trans->transid != fs_info->generation);
159686479a04SChris Mason 
15976b80053dSChris Mason 	parent_nritems = btrfs_header_nritems(parent);
15980b246afaSJeff Mahoney 	blocksize = fs_info->nodesize;
15995dfe2be7SFilipe Manana 	end_slot = parent_nritems - 1;
16006702ed49SChris Mason 
16015dfe2be7SFilipe Manana 	if (parent_nritems <= 1)
16026702ed49SChris Mason 		return 0;
16036702ed49SChris Mason 
16048bead258SDavid Sterba 	btrfs_set_lock_blocking_write(parent);
1605b4ce94deSChris Mason 
16065dfe2be7SFilipe Manana 	for (i = start_slot; i <= end_slot; i++) {
1607581c1760SQu Wenruo 		struct btrfs_key first_key;
16086702ed49SChris Mason 		int close = 1;
1609a6b6e75eSChris Mason 
1610081e9573SChris Mason 		btrfs_node_key(parent, &disk_key, i);
1611081e9573SChris Mason 		if (!progress_passed && comp_keys(&disk_key, progress) < 0)
1612081e9573SChris Mason 			continue;
1613081e9573SChris Mason 
1614081e9573SChris Mason 		progress_passed = 1;
16156b80053dSChris Mason 		blocknr = btrfs_node_blockptr(parent, i);
1616ca7a79adSChris Mason 		gen = btrfs_node_ptr_generation(parent, i);
1617581c1760SQu Wenruo 		btrfs_node_key_to_cpu(parent, &first_key, i);
1618e9d0b13bSChris Mason 		if (last_block == 0)
1619e9d0b13bSChris Mason 			last_block = blocknr;
16205708b959SChris Mason 
16216702ed49SChris Mason 		if (i > 0) {
16226b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i - 1);
16236b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
16246702ed49SChris Mason 		}
16255dfe2be7SFilipe Manana 		if (!close && i < end_slot) {
16266b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i + 1);
16276b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
16286702ed49SChris Mason 		}
1629e9d0b13bSChris Mason 		if (close) {
1630e9d0b13bSChris Mason 			last_block = blocknr;
16316702ed49SChris Mason 			continue;
1632e9d0b13bSChris Mason 		}
16336702ed49SChris Mason 
16340b246afaSJeff Mahoney 		cur = find_extent_buffer(fs_info, blocknr);
16356b80053dSChris Mason 		if (cur)
1636b9fab919SChris Mason 			uptodate = btrfs_buffer_uptodate(cur, gen, 0);
16376b80053dSChris Mason 		else
16386b80053dSChris Mason 			uptodate = 0;
16395708b959SChris Mason 		if (!cur || !uptodate) {
16406b80053dSChris Mason 			if (!cur) {
1641581c1760SQu Wenruo 				cur = read_tree_block(fs_info, blocknr, gen,
1642581c1760SQu Wenruo 						      parent_level - 1,
1643581c1760SQu Wenruo 						      &first_key);
164464c043deSLiu Bo 				if (IS_ERR(cur)) {
164564c043deSLiu Bo 					return PTR_ERR(cur);
164664c043deSLiu Bo 				} else if (!extent_buffer_uptodate(cur)) {
1647416bc658SJosef Bacik 					free_extent_buffer(cur);
164897d9a8a4STsutomu Itoh 					return -EIO;
1649416bc658SJosef Bacik 				}
16506b80053dSChris Mason 			} else if (!uptodate) {
1651581c1760SQu Wenruo 				err = btrfs_read_buffer(cur, gen,
1652581c1760SQu Wenruo 						parent_level - 1,&first_key);
1653018642a1STsutomu Itoh 				if (err) {
1654018642a1STsutomu Itoh 					free_extent_buffer(cur);
1655018642a1STsutomu Itoh 					return err;
1656018642a1STsutomu Itoh 				}
16576702ed49SChris Mason 			}
1658f2183bdeSChris Mason 		}
1659e9d0b13bSChris Mason 		if (search_start == 0)
16606b80053dSChris Mason 			search_start = last_block;
1661e9d0b13bSChris Mason 
1662e7a84565SChris Mason 		btrfs_tree_lock(cur);
16638bead258SDavid Sterba 		btrfs_set_lock_blocking_write(cur);
16646b80053dSChris Mason 		err = __btrfs_cow_block(trans, root, cur, parent, i,
1665e7a84565SChris Mason 					&cur, search_start,
16666b80053dSChris Mason 					min(16 * blocksize,
16679fa8cfe7SChris Mason 					    (end_slot - i) * blocksize));
1668252c38f0SYan 		if (err) {
1669e7a84565SChris Mason 			btrfs_tree_unlock(cur);
16706b80053dSChris Mason 			free_extent_buffer(cur);
16716702ed49SChris Mason 			break;
1672252c38f0SYan 		}
1673e7a84565SChris Mason 		search_start = cur->start;
1674e7a84565SChris Mason 		last_block = cur->start;
1675f2183bdeSChris Mason 		*last_ret = search_start;
1676e7a84565SChris Mason 		btrfs_tree_unlock(cur);
1677e7a84565SChris Mason 		free_extent_buffer(cur);
16786702ed49SChris Mason 	}
16796702ed49SChris Mason 	return err;
16806702ed49SChris Mason }
16816702ed49SChris Mason 
168274123bd7SChris Mason /*
16835f39d397SChris Mason  * search for key in the extent_buffer.  The items start at offset p,
16845f39d397SChris Mason  * and they are item_size apart.  There are 'max' items in p.
16855f39d397SChris Mason  *
168674123bd7SChris Mason  * the slot in the array is returned via slot, and it points to
168774123bd7SChris Mason  * the place where you would insert key if it is not found in
168874123bd7SChris Mason  * the array.
168974123bd7SChris Mason  *
169074123bd7SChris Mason  * slot may point to max if the key is bigger than all of the keys
169174123bd7SChris Mason  */
1692e02119d5SChris Mason static noinline int generic_bin_search(struct extent_buffer *eb,
1693310712b2SOmar Sandoval 				       unsigned long p, int item_size,
1694310712b2SOmar Sandoval 				       const struct btrfs_key *key,
1695be0e5c09SChris Mason 				       int max, int *slot)
1696be0e5c09SChris Mason {
1697be0e5c09SChris Mason 	int low = 0;
1698be0e5c09SChris Mason 	int high = max;
1699be0e5c09SChris Mason 	int mid;
1700be0e5c09SChris Mason 	int ret;
1701479965d6SChris Mason 	struct btrfs_disk_key *tmp = NULL;
17025f39d397SChris Mason 	struct btrfs_disk_key unaligned;
17035f39d397SChris Mason 	unsigned long offset;
17045f39d397SChris Mason 	char *kaddr = NULL;
17055f39d397SChris Mason 	unsigned long map_start = 0;
17065f39d397SChris Mason 	unsigned long map_len = 0;
1707479965d6SChris Mason 	int err;
1708be0e5c09SChris Mason 
17095e24e9afSLiu Bo 	if (low > high) {
17105e24e9afSLiu Bo 		btrfs_err(eb->fs_info,
17115e24e9afSLiu Bo 		 "%s: low (%d) > high (%d) eb %llu owner %llu level %d",
17125e24e9afSLiu Bo 			  __func__, low, high, eb->start,
17135e24e9afSLiu Bo 			  btrfs_header_owner(eb), btrfs_header_level(eb));
17145e24e9afSLiu Bo 		return -EINVAL;
17155e24e9afSLiu Bo 	}
17165e24e9afSLiu Bo 
1717be0e5c09SChris Mason 	while (low < high) {
1718be0e5c09SChris Mason 		mid = (low + high) / 2;
17195f39d397SChris Mason 		offset = p + mid * item_size;
17205f39d397SChris Mason 
1721a6591715SChris Mason 		if (!kaddr || offset < map_start ||
17225f39d397SChris Mason 		    (offset + sizeof(struct btrfs_disk_key)) >
17235f39d397SChris Mason 		    map_start + map_len) {
1724934d375bSChris Mason 
1725934d375bSChris Mason 			err = map_private_extent_buffer(eb, offset,
1726479965d6SChris Mason 						sizeof(struct btrfs_disk_key),
1727a6591715SChris Mason 						&kaddr, &map_start, &map_len);
17285f39d397SChris Mason 
1729479965d6SChris Mason 			if (!err) {
1730479965d6SChris Mason 				tmp = (struct btrfs_disk_key *)(kaddr + offset -
1731479965d6SChris Mason 							map_start);
1732415b35a5SLiu Bo 			} else if (err == 1) {
17335f39d397SChris Mason 				read_extent_buffer(eb, &unaligned,
17345f39d397SChris Mason 						   offset, sizeof(unaligned));
17355f39d397SChris Mason 				tmp = &unaligned;
1736415b35a5SLiu Bo 			} else {
1737415b35a5SLiu Bo 				return err;
1738479965d6SChris Mason 			}
1739479965d6SChris Mason 
17405f39d397SChris Mason 		} else {
17415f39d397SChris Mason 			tmp = (struct btrfs_disk_key *)(kaddr + offset -
17425f39d397SChris Mason 							map_start);
17435f39d397SChris Mason 		}
1744be0e5c09SChris Mason 		ret = comp_keys(tmp, key);
1745be0e5c09SChris Mason 
1746be0e5c09SChris Mason 		if (ret < 0)
1747be0e5c09SChris Mason 			low = mid + 1;
1748be0e5c09SChris Mason 		else if (ret > 0)
1749be0e5c09SChris Mason 			high = mid;
1750be0e5c09SChris Mason 		else {
1751be0e5c09SChris Mason 			*slot = mid;
1752be0e5c09SChris Mason 			return 0;
1753be0e5c09SChris Mason 		}
1754be0e5c09SChris Mason 	}
1755be0e5c09SChris Mason 	*slot = low;
1756be0e5c09SChris Mason 	return 1;
1757be0e5c09SChris Mason }
1758be0e5c09SChris Mason 
175997571fd0SChris Mason /*
176097571fd0SChris Mason  * simple bin_search frontend that does the right thing for
176197571fd0SChris Mason  * leaves vs nodes
176297571fd0SChris Mason  */
1763a74b35ecSNikolay Borisov int btrfs_bin_search(struct extent_buffer *eb, const struct btrfs_key *key,
17645f39d397SChris Mason 		     int level, int *slot)
1765be0e5c09SChris Mason {
1766f775738fSWang Sheng-Hui 	if (level == 0)
17675f39d397SChris Mason 		return generic_bin_search(eb,
17685f39d397SChris Mason 					  offsetof(struct btrfs_leaf, items),
17690783fcfcSChris Mason 					  sizeof(struct btrfs_item),
17705f39d397SChris Mason 					  key, btrfs_header_nritems(eb),
17717518a238SChris Mason 					  slot);
1772f775738fSWang Sheng-Hui 	else
17735f39d397SChris Mason 		return generic_bin_search(eb,
17745f39d397SChris Mason 					  offsetof(struct btrfs_node, ptrs),
1775123abc88SChris Mason 					  sizeof(struct btrfs_key_ptr),
17765f39d397SChris Mason 					  key, btrfs_header_nritems(eb),
17777518a238SChris Mason 					  slot);
1778be0e5c09SChris Mason }
1779be0e5c09SChris Mason 
1780f0486c68SYan, Zheng static void root_add_used(struct btrfs_root *root, u32 size)
1781f0486c68SYan, Zheng {
1782f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
1783f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
1784f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) + size);
1785f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
1786f0486c68SYan, Zheng }
1787f0486c68SYan, Zheng 
1788f0486c68SYan, Zheng static void root_sub_used(struct btrfs_root *root, u32 size)
1789f0486c68SYan, Zheng {
1790f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
1791f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
1792f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) - size);
1793f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
1794f0486c68SYan, Zheng }
1795f0486c68SYan, Zheng 
1796d352ac68SChris Mason /* given a node and slot number, this reads the blocks it points to.  The
1797d352ac68SChris Mason  * extent buffer is returned with a reference taken (but unlocked).
1798d352ac68SChris Mason  */
17994b231ae4SDavid Sterba struct extent_buffer *btrfs_read_node_slot(struct extent_buffer *parent,
18004b231ae4SDavid Sterba 					   int slot)
1801bb803951SChris Mason {
1802ca7a79adSChris Mason 	int level = btrfs_header_level(parent);
1803416bc658SJosef Bacik 	struct extent_buffer *eb;
1804581c1760SQu Wenruo 	struct btrfs_key first_key;
1805416bc658SJosef Bacik 
1806fb770ae4SLiu Bo 	if (slot < 0 || slot >= btrfs_header_nritems(parent))
1807fb770ae4SLiu Bo 		return ERR_PTR(-ENOENT);
1808ca7a79adSChris Mason 
1809ca7a79adSChris Mason 	BUG_ON(level == 0);
1810ca7a79adSChris Mason 
1811581c1760SQu Wenruo 	btrfs_node_key_to_cpu(parent, &first_key, slot);
1812d0d20b0fSDavid Sterba 	eb = read_tree_block(parent->fs_info, btrfs_node_blockptr(parent, slot),
1813581c1760SQu Wenruo 			     btrfs_node_ptr_generation(parent, slot),
1814581c1760SQu Wenruo 			     level - 1, &first_key);
1815fb770ae4SLiu Bo 	if (!IS_ERR(eb) && !extent_buffer_uptodate(eb)) {
1816416bc658SJosef Bacik 		free_extent_buffer(eb);
1817fb770ae4SLiu Bo 		eb = ERR_PTR(-EIO);
1818416bc658SJosef Bacik 	}
1819416bc658SJosef Bacik 
1820416bc658SJosef Bacik 	return eb;
1821bb803951SChris Mason }
1822bb803951SChris Mason 
1823d352ac68SChris Mason /*
1824d352ac68SChris Mason  * node level balancing, used to make sure nodes are in proper order for
1825d352ac68SChris Mason  * item deletion.  We balance from the top down, so we have to make sure
1826d352ac68SChris Mason  * that a deletion won't leave an node completely empty later on.
1827d352ac68SChris Mason  */
1828e02119d5SChris Mason static noinline int balance_level(struct btrfs_trans_handle *trans,
182998ed5174SChris Mason 			 struct btrfs_root *root,
183098ed5174SChris Mason 			 struct btrfs_path *path, int level)
1831bb803951SChris Mason {
18320b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
18335f39d397SChris Mason 	struct extent_buffer *right = NULL;
18345f39d397SChris Mason 	struct extent_buffer *mid;
18355f39d397SChris Mason 	struct extent_buffer *left = NULL;
18365f39d397SChris Mason 	struct extent_buffer *parent = NULL;
1837bb803951SChris Mason 	int ret = 0;
1838bb803951SChris Mason 	int wret;
1839bb803951SChris Mason 	int pslot;
1840bb803951SChris Mason 	int orig_slot = path->slots[level];
184179f95c82SChris Mason 	u64 orig_ptr;
1842bb803951SChris Mason 
184398e6b1ebSLiu Bo 	ASSERT(level > 0);
1844bb803951SChris Mason 
18455f39d397SChris Mason 	mid = path->nodes[level];
1846b4ce94deSChris Mason 
1847bd681513SChris Mason 	WARN_ON(path->locks[level] != BTRFS_WRITE_LOCK &&
1848bd681513SChris Mason 		path->locks[level] != BTRFS_WRITE_LOCK_BLOCKING);
18497bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
18507bb86316SChris Mason 
18511d4f8a0cSChris Mason 	orig_ptr = btrfs_node_blockptr(mid, orig_slot);
185279f95c82SChris Mason 
1853a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
18545f39d397SChris Mason 		parent = path->nodes[level + 1];
1855bb803951SChris Mason 		pslot = path->slots[level + 1];
1856a05a9bb1SLi Zefan 	}
1857bb803951SChris Mason 
185840689478SChris Mason 	/*
185940689478SChris Mason 	 * deal with the case where there is only one pointer in the root
186040689478SChris Mason 	 * by promoting the node below to a root
186140689478SChris Mason 	 */
18625f39d397SChris Mason 	if (!parent) {
18635f39d397SChris Mason 		struct extent_buffer *child;
1864bb803951SChris Mason 
18655f39d397SChris Mason 		if (btrfs_header_nritems(mid) != 1)
1866bb803951SChris Mason 			return 0;
1867bb803951SChris Mason 
1868bb803951SChris Mason 		/* promote the child to a root */
18694b231ae4SDavid Sterba 		child = btrfs_read_node_slot(mid, 0);
1870fb770ae4SLiu Bo 		if (IS_ERR(child)) {
1871fb770ae4SLiu Bo 			ret = PTR_ERR(child);
18720b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
1873305a26afSMark Fasheh 			goto enospc;
1874305a26afSMark Fasheh 		}
1875305a26afSMark Fasheh 
1876925baeddSChris Mason 		btrfs_tree_lock(child);
18778bead258SDavid Sterba 		btrfs_set_lock_blocking_write(child);
18789fa8cfe7SChris Mason 		ret = btrfs_cow_block(trans, root, child, mid, 0, &child);
1879f0486c68SYan, Zheng 		if (ret) {
1880f0486c68SYan, Zheng 			btrfs_tree_unlock(child);
1881f0486c68SYan, Zheng 			free_extent_buffer(child);
1882f0486c68SYan, Zheng 			goto enospc;
1883f0486c68SYan, Zheng 		}
18842f375ab9SYan 
1885d9d19a01SDavid Sterba 		ret = tree_mod_log_insert_root(root->node, child, 1);
1886d9d19a01SDavid Sterba 		BUG_ON(ret < 0);
1887240f62c8SChris Mason 		rcu_assign_pointer(root->node, child);
1888925baeddSChris Mason 
18890b86a832SChris Mason 		add_root_to_dirty_list(root);
1890925baeddSChris Mason 		btrfs_tree_unlock(child);
1891b4ce94deSChris Mason 
1892925baeddSChris Mason 		path->locks[level] = 0;
1893bb803951SChris Mason 		path->nodes[level] = NULL;
18946a884d7dSDavid Sterba 		btrfs_clean_tree_block(mid);
1895925baeddSChris Mason 		btrfs_tree_unlock(mid);
1896bb803951SChris Mason 		/* once for the path */
18975f39d397SChris Mason 		free_extent_buffer(mid);
1898f0486c68SYan, Zheng 
1899f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
19005581a51aSJan Schmidt 		btrfs_free_tree_block(trans, root, mid, 0, 1);
1901bb803951SChris Mason 		/* once for the root ptr */
19023083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
1903f0486c68SYan, Zheng 		return 0;
1904bb803951SChris Mason 	}
19055f39d397SChris Mason 	if (btrfs_header_nritems(mid) >
19060b246afaSJeff Mahoney 	    BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 4)
1907bb803951SChris Mason 		return 0;
1908bb803951SChris Mason 
19094b231ae4SDavid Sterba 	left = btrfs_read_node_slot(parent, pslot - 1);
1910fb770ae4SLiu Bo 	if (IS_ERR(left))
1911fb770ae4SLiu Bo 		left = NULL;
1912fb770ae4SLiu Bo 
19135f39d397SChris Mason 	if (left) {
1914925baeddSChris Mason 		btrfs_tree_lock(left);
19158bead258SDavid Sterba 		btrfs_set_lock_blocking_write(left);
19165f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, left,
19179fa8cfe7SChris Mason 				       parent, pslot - 1, &left);
191854aa1f4dSChris Mason 		if (wret) {
191954aa1f4dSChris Mason 			ret = wret;
192054aa1f4dSChris Mason 			goto enospc;
192154aa1f4dSChris Mason 		}
19222cc58cf2SChris Mason 	}
1923fb770ae4SLiu Bo 
19244b231ae4SDavid Sterba 	right = btrfs_read_node_slot(parent, pslot + 1);
1925fb770ae4SLiu Bo 	if (IS_ERR(right))
1926fb770ae4SLiu Bo 		right = NULL;
1927fb770ae4SLiu Bo 
19285f39d397SChris Mason 	if (right) {
1929925baeddSChris Mason 		btrfs_tree_lock(right);
19308bead258SDavid Sterba 		btrfs_set_lock_blocking_write(right);
19315f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, right,
19329fa8cfe7SChris Mason 				       parent, pslot + 1, &right);
19332cc58cf2SChris Mason 		if (wret) {
19342cc58cf2SChris Mason 			ret = wret;
19352cc58cf2SChris Mason 			goto enospc;
19362cc58cf2SChris Mason 		}
19372cc58cf2SChris Mason 	}
19382cc58cf2SChris Mason 
19392cc58cf2SChris Mason 	/* first, try to make some room in the middle buffer */
19405f39d397SChris Mason 	if (left) {
19415f39d397SChris Mason 		orig_slot += btrfs_header_nritems(left);
1942d30a668fSDavid Sterba 		wret = push_node_left(trans, left, mid, 1);
194379f95c82SChris Mason 		if (wret < 0)
194479f95c82SChris Mason 			ret = wret;
1945bb803951SChris Mason 	}
194679f95c82SChris Mason 
194779f95c82SChris Mason 	/*
194879f95c82SChris Mason 	 * then try to empty the right most buffer into the middle
194979f95c82SChris Mason 	 */
19505f39d397SChris Mason 	if (right) {
1951d30a668fSDavid Sterba 		wret = push_node_left(trans, mid, right, 1);
195254aa1f4dSChris Mason 		if (wret < 0 && wret != -ENOSPC)
195379f95c82SChris Mason 			ret = wret;
19545f39d397SChris Mason 		if (btrfs_header_nritems(right) == 0) {
19556a884d7dSDavid Sterba 			btrfs_clean_tree_block(right);
1956925baeddSChris Mason 			btrfs_tree_unlock(right);
1957afe5fea7STsutomu Itoh 			del_ptr(root, path, level + 1, pslot + 1);
1958f0486c68SYan, Zheng 			root_sub_used(root, right->len);
19595581a51aSJan Schmidt 			btrfs_free_tree_block(trans, root, right, 0, 1);
19603083ee2eSJosef Bacik 			free_extent_buffer_stale(right);
1961f0486c68SYan, Zheng 			right = NULL;
1962bb803951SChris Mason 		} else {
19635f39d397SChris Mason 			struct btrfs_disk_key right_key;
19645f39d397SChris Mason 			btrfs_node_key(right, &right_key, 0);
19650e82bcfeSDavid Sterba 			ret = tree_mod_log_insert_key(parent, pslot + 1,
19660e82bcfeSDavid Sterba 					MOD_LOG_KEY_REPLACE, GFP_NOFS);
19670e82bcfeSDavid Sterba 			BUG_ON(ret < 0);
19685f39d397SChris Mason 			btrfs_set_node_key(parent, &right_key, pslot + 1);
19695f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
1970bb803951SChris Mason 		}
1971bb803951SChris Mason 	}
19725f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 1) {
197379f95c82SChris Mason 		/*
197479f95c82SChris Mason 		 * we're not allowed to leave a node with one item in the
197579f95c82SChris Mason 		 * tree during a delete.  A deletion from lower in the tree
197679f95c82SChris Mason 		 * could try to delete the only pointer in this node.
197779f95c82SChris Mason 		 * So, pull some keys from the left.
197879f95c82SChris Mason 		 * There has to be a left pointer at this point because
197979f95c82SChris Mason 		 * otherwise we would have pulled some pointers from the
198079f95c82SChris Mason 		 * right
198179f95c82SChris Mason 		 */
1982305a26afSMark Fasheh 		if (!left) {
1983305a26afSMark Fasheh 			ret = -EROFS;
19840b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
1985305a26afSMark Fasheh 			goto enospc;
1986305a26afSMark Fasheh 		}
198755d32ed8SDavid Sterba 		wret = balance_node_right(trans, mid, left);
198854aa1f4dSChris Mason 		if (wret < 0) {
198979f95c82SChris Mason 			ret = wret;
199054aa1f4dSChris Mason 			goto enospc;
199154aa1f4dSChris Mason 		}
1992bce4eae9SChris Mason 		if (wret == 1) {
1993d30a668fSDavid Sterba 			wret = push_node_left(trans, left, mid, 1);
1994bce4eae9SChris Mason 			if (wret < 0)
1995bce4eae9SChris Mason 				ret = wret;
1996bce4eae9SChris Mason 		}
199779f95c82SChris Mason 		BUG_ON(wret == 1);
199879f95c82SChris Mason 	}
19995f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 0) {
20006a884d7dSDavid Sterba 		btrfs_clean_tree_block(mid);
2001925baeddSChris Mason 		btrfs_tree_unlock(mid);
2002afe5fea7STsutomu Itoh 		del_ptr(root, path, level + 1, pslot);
2003f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
20045581a51aSJan Schmidt 		btrfs_free_tree_block(trans, root, mid, 0, 1);
20053083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
2006f0486c68SYan, Zheng 		mid = NULL;
200779f95c82SChris Mason 	} else {
200879f95c82SChris Mason 		/* update the parent key to reflect our changes */
20095f39d397SChris Mason 		struct btrfs_disk_key mid_key;
20105f39d397SChris Mason 		btrfs_node_key(mid, &mid_key, 0);
20110e82bcfeSDavid Sterba 		ret = tree_mod_log_insert_key(parent, pslot,
20120e82bcfeSDavid Sterba 				MOD_LOG_KEY_REPLACE, GFP_NOFS);
20130e82bcfeSDavid Sterba 		BUG_ON(ret < 0);
20145f39d397SChris Mason 		btrfs_set_node_key(parent, &mid_key, pslot);
20155f39d397SChris Mason 		btrfs_mark_buffer_dirty(parent);
201679f95c82SChris Mason 	}
2017bb803951SChris Mason 
201879f95c82SChris Mason 	/* update the path */
20195f39d397SChris Mason 	if (left) {
20205f39d397SChris Mason 		if (btrfs_header_nritems(left) > orig_slot) {
202167439dadSDavid Sterba 			atomic_inc(&left->refs);
2022925baeddSChris Mason 			/* left was locked after cow */
20235f39d397SChris Mason 			path->nodes[level] = left;
2024bb803951SChris Mason 			path->slots[level + 1] -= 1;
2025bb803951SChris Mason 			path->slots[level] = orig_slot;
2026925baeddSChris Mason 			if (mid) {
2027925baeddSChris Mason 				btrfs_tree_unlock(mid);
20285f39d397SChris Mason 				free_extent_buffer(mid);
2029925baeddSChris Mason 			}
2030bb803951SChris Mason 		} else {
20315f39d397SChris Mason 			orig_slot -= btrfs_header_nritems(left);
2032bb803951SChris Mason 			path->slots[level] = orig_slot;
2033bb803951SChris Mason 		}
2034bb803951SChris Mason 	}
203579f95c82SChris Mason 	/* double check we haven't messed things up */
2036e20d96d6SChris Mason 	if (orig_ptr !=
20375f39d397SChris Mason 	    btrfs_node_blockptr(path->nodes[level], path->slots[level]))
203879f95c82SChris Mason 		BUG();
203954aa1f4dSChris Mason enospc:
2040925baeddSChris Mason 	if (right) {
2041925baeddSChris Mason 		btrfs_tree_unlock(right);
20425f39d397SChris Mason 		free_extent_buffer(right);
2043925baeddSChris Mason 	}
2044925baeddSChris Mason 	if (left) {
2045925baeddSChris Mason 		if (path->nodes[level] != left)
2046925baeddSChris Mason 			btrfs_tree_unlock(left);
20475f39d397SChris Mason 		free_extent_buffer(left);
2048925baeddSChris Mason 	}
2049bb803951SChris Mason 	return ret;
2050bb803951SChris Mason }
2051bb803951SChris Mason 
2052d352ac68SChris Mason /* Node balancing for insertion.  Here we only split or push nodes around
2053d352ac68SChris Mason  * when they are completely full.  This is also done top down, so we
2054d352ac68SChris Mason  * have to be pessimistic.
2055d352ac68SChris Mason  */
2056d397712bSChris Mason static noinline int push_nodes_for_insert(struct btrfs_trans_handle *trans,
2057e66f709bSChris Mason 					  struct btrfs_root *root,
2058e66f709bSChris Mason 					  struct btrfs_path *path, int level)
2059e66f709bSChris Mason {
20600b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
20615f39d397SChris Mason 	struct extent_buffer *right = NULL;
20625f39d397SChris Mason 	struct extent_buffer *mid;
20635f39d397SChris Mason 	struct extent_buffer *left = NULL;
20645f39d397SChris Mason 	struct extent_buffer *parent = NULL;
2065e66f709bSChris Mason 	int ret = 0;
2066e66f709bSChris Mason 	int wret;
2067e66f709bSChris Mason 	int pslot;
2068e66f709bSChris Mason 	int orig_slot = path->slots[level];
2069e66f709bSChris Mason 
2070e66f709bSChris Mason 	if (level == 0)
2071e66f709bSChris Mason 		return 1;
2072e66f709bSChris Mason 
20735f39d397SChris Mason 	mid = path->nodes[level];
20747bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
2075e66f709bSChris Mason 
2076a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
20775f39d397SChris Mason 		parent = path->nodes[level + 1];
2078e66f709bSChris Mason 		pslot = path->slots[level + 1];
2079a05a9bb1SLi Zefan 	}
2080e66f709bSChris Mason 
20815f39d397SChris Mason 	if (!parent)
2082e66f709bSChris Mason 		return 1;
2083e66f709bSChris Mason 
20844b231ae4SDavid Sterba 	left = btrfs_read_node_slot(parent, pslot - 1);
2085fb770ae4SLiu Bo 	if (IS_ERR(left))
2086fb770ae4SLiu Bo 		left = NULL;
2087e66f709bSChris Mason 
2088e66f709bSChris Mason 	/* first, try to make some room in the middle buffer */
20895f39d397SChris Mason 	if (left) {
2090e66f709bSChris Mason 		u32 left_nr;
2091925baeddSChris Mason 
2092925baeddSChris Mason 		btrfs_tree_lock(left);
20938bead258SDavid Sterba 		btrfs_set_lock_blocking_write(left);
2094b4ce94deSChris Mason 
20955f39d397SChris Mason 		left_nr = btrfs_header_nritems(left);
20960b246afaSJeff Mahoney 		if (left_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
209733ade1f8SChris Mason 			wret = 1;
209833ade1f8SChris Mason 		} else {
20995f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, left, parent,
21009fa8cfe7SChris Mason 					      pslot - 1, &left);
210154aa1f4dSChris Mason 			if (ret)
210254aa1f4dSChris Mason 				wret = 1;
210354aa1f4dSChris Mason 			else {
2104d30a668fSDavid Sterba 				wret = push_node_left(trans, left, mid, 0);
210554aa1f4dSChris Mason 			}
210633ade1f8SChris Mason 		}
2107e66f709bSChris Mason 		if (wret < 0)
2108e66f709bSChris Mason 			ret = wret;
2109e66f709bSChris Mason 		if (wret == 0) {
21105f39d397SChris Mason 			struct btrfs_disk_key disk_key;
2111e66f709bSChris Mason 			orig_slot += left_nr;
21125f39d397SChris Mason 			btrfs_node_key(mid, &disk_key, 0);
21130e82bcfeSDavid Sterba 			ret = tree_mod_log_insert_key(parent, pslot,
21140e82bcfeSDavid Sterba 					MOD_LOG_KEY_REPLACE, GFP_NOFS);
21150e82bcfeSDavid Sterba 			BUG_ON(ret < 0);
21165f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot);
21175f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
21185f39d397SChris Mason 			if (btrfs_header_nritems(left) > orig_slot) {
21195f39d397SChris Mason 				path->nodes[level] = left;
2120e66f709bSChris Mason 				path->slots[level + 1] -= 1;
2121e66f709bSChris Mason 				path->slots[level] = orig_slot;
2122925baeddSChris Mason 				btrfs_tree_unlock(mid);
21235f39d397SChris Mason 				free_extent_buffer(mid);
2124e66f709bSChris Mason 			} else {
2125e66f709bSChris Mason 				orig_slot -=
21265f39d397SChris Mason 					btrfs_header_nritems(left);
2127e66f709bSChris Mason 				path->slots[level] = orig_slot;
2128925baeddSChris Mason 				btrfs_tree_unlock(left);
21295f39d397SChris Mason 				free_extent_buffer(left);
2130e66f709bSChris Mason 			}
2131e66f709bSChris Mason 			return 0;
2132e66f709bSChris Mason 		}
2133925baeddSChris Mason 		btrfs_tree_unlock(left);
21345f39d397SChris Mason 		free_extent_buffer(left);
2135e66f709bSChris Mason 	}
21364b231ae4SDavid Sterba 	right = btrfs_read_node_slot(parent, pslot + 1);
2137fb770ae4SLiu Bo 	if (IS_ERR(right))
2138fb770ae4SLiu Bo 		right = NULL;
2139e66f709bSChris Mason 
2140e66f709bSChris Mason 	/*
2141e66f709bSChris Mason 	 * then try to empty the right most buffer into the middle
2142e66f709bSChris Mason 	 */
21435f39d397SChris Mason 	if (right) {
214433ade1f8SChris Mason 		u32 right_nr;
2145b4ce94deSChris Mason 
2146925baeddSChris Mason 		btrfs_tree_lock(right);
21478bead258SDavid Sterba 		btrfs_set_lock_blocking_write(right);
2148b4ce94deSChris Mason 
21495f39d397SChris Mason 		right_nr = btrfs_header_nritems(right);
21500b246afaSJeff Mahoney 		if (right_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
215133ade1f8SChris Mason 			wret = 1;
215233ade1f8SChris Mason 		} else {
21535f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, right,
21545f39d397SChris Mason 					      parent, pslot + 1,
21559fa8cfe7SChris Mason 					      &right);
215654aa1f4dSChris Mason 			if (ret)
215754aa1f4dSChris Mason 				wret = 1;
215854aa1f4dSChris Mason 			else {
215955d32ed8SDavid Sterba 				wret = balance_node_right(trans, right, mid);
216033ade1f8SChris Mason 			}
216154aa1f4dSChris Mason 		}
2162e66f709bSChris Mason 		if (wret < 0)
2163e66f709bSChris Mason 			ret = wret;
2164e66f709bSChris Mason 		if (wret == 0) {
21655f39d397SChris Mason 			struct btrfs_disk_key disk_key;
21665f39d397SChris Mason 
21675f39d397SChris Mason 			btrfs_node_key(right, &disk_key, 0);
21680e82bcfeSDavid Sterba 			ret = tree_mod_log_insert_key(parent, pslot + 1,
21690e82bcfeSDavid Sterba 					MOD_LOG_KEY_REPLACE, GFP_NOFS);
21700e82bcfeSDavid Sterba 			BUG_ON(ret < 0);
21715f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot + 1);
21725f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
21735f39d397SChris Mason 
21745f39d397SChris Mason 			if (btrfs_header_nritems(mid) <= orig_slot) {
21755f39d397SChris Mason 				path->nodes[level] = right;
2176e66f709bSChris Mason 				path->slots[level + 1] += 1;
2177e66f709bSChris Mason 				path->slots[level] = orig_slot -
21785f39d397SChris Mason 					btrfs_header_nritems(mid);
2179925baeddSChris Mason 				btrfs_tree_unlock(mid);
21805f39d397SChris Mason 				free_extent_buffer(mid);
2181e66f709bSChris Mason 			} else {
2182925baeddSChris Mason 				btrfs_tree_unlock(right);
21835f39d397SChris Mason 				free_extent_buffer(right);
2184e66f709bSChris Mason 			}
2185e66f709bSChris Mason 			return 0;
2186e66f709bSChris Mason 		}
2187925baeddSChris Mason 		btrfs_tree_unlock(right);
21885f39d397SChris Mason 		free_extent_buffer(right);
2189e66f709bSChris Mason 	}
2190e66f709bSChris Mason 	return 1;
2191e66f709bSChris Mason }
2192e66f709bSChris Mason 
219374123bd7SChris Mason /*
2194d352ac68SChris Mason  * readahead one full node of leaves, finding things that are close
2195d352ac68SChris Mason  * to the block in 'slot', and triggering ra on them.
21963c69faecSChris Mason  */
21972ff7e61eSJeff Mahoney static void reada_for_search(struct btrfs_fs_info *fs_info,
2198e02119d5SChris Mason 			     struct btrfs_path *path,
219901f46658SChris Mason 			     int level, int slot, u64 objectid)
22003c69faecSChris Mason {
22015f39d397SChris Mason 	struct extent_buffer *node;
220201f46658SChris Mason 	struct btrfs_disk_key disk_key;
22033c69faecSChris Mason 	u32 nritems;
22043c69faecSChris Mason 	u64 search;
2205a7175319SChris Mason 	u64 target;
22066b80053dSChris Mason 	u64 nread = 0;
22075f39d397SChris Mason 	struct extent_buffer *eb;
22086b80053dSChris Mason 	u32 nr;
22096b80053dSChris Mason 	u32 blocksize;
22106b80053dSChris Mason 	u32 nscan = 0;
2211db94535dSChris Mason 
2212a6b6e75eSChris Mason 	if (level != 1)
22133c69faecSChris Mason 		return;
22143c69faecSChris Mason 
22156702ed49SChris Mason 	if (!path->nodes[level])
22166702ed49SChris Mason 		return;
22176702ed49SChris Mason 
22185f39d397SChris Mason 	node = path->nodes[level];
2219925baeddSChris Mason 
22203c69faecSChris Mason 	search = btrfs_node_blockptr(node, slot);
22210b246afaSJeff Mahoney 	blocksize = fs_info->nodesize;
22220b246afaSJeff Mahoney 	eb = find_extent_buffer(fs_info, search);
22235f39d397SChris Mason 	if (eb) {
22245f39d397SChris Mason 		free_extent_buffer(eb);
22253c69faecSChris Mason 		return;
22263c69faecSChris Mason 	}
22273c69faecSChris Mason 
2228a7175319SChris Mason 	target = search;
22296b80053dSChris Mason 
22305f39d397SChris Mason 	nritems = btrfs_header_nritems(node);
22316b80053dSChris Mason 	nr = slot;
223225b8b936SJosef Bacik 
22333c69faecSChris Mason 	while (1) {
2234e4058b54SDavid Sterba 		if (path->reada == READA_BACK) {
22356b80053dSChris Mason 			if (nr == 0)
22363c69faecSChris Mason 				break;
22376b80053dSChris Mason 			nr--;
2238e4058b54SDavid Sterba 		} else if (path->reada == READA_FORWARD) {
22396b80053dSChris Mason 			nr++;
22406b80053dSChris Mason 			if (nr >= nritems)
22416b80053dSChris Mason 				break;
22423c69faecSChris Mason 		}
2243e4058b54SDavid Sterba 		if (path->reada == READA_BACK && objectid) {
224401f46658SChris Mason 			btrfs_node_key(node, &disk_key, nr);
224501f46658SChris Mason 			if (btrfs_disk_key_objectid(&disk_key) != objectid)
224601f46658SChris Mason 				break;
224701f46658SChris Mason 		}
22486b80053dSChris Mason 		search = btrfs_node_blockptr(node, nr);
2249a7175319SChris Mason 		if ((search <= target && target - search <= 65536) ||
2250a7175319SChris Mason 		    (search > target && search - target <= 65536)) {
22512ff7e61eSJeff Mahoney 			readahead_tree_block(fs_info, search);
22526b80053dSChris Mason 			nread += blocksize;
22533c69faecSChris Mason 		}
22546b80053dSChris Mason 		nscan++;
2255a7175319SChris Mason 		if ((nread > 65536 || nscan > 32))
22566b80053dSChris Mason 			break;
22573c69faecSChris Mason 	}
22583c69faecSChris Mason }
2259925baeddSChris Mason 
22602ff7e61eSJeff Mahoney static noinline void reada_for_balance(struct btrfs_fs_info *fs_info,
2261b4ce94deSChris Mason 				       struct btrfs_path *path, int level)
2262b4ce94deSChris Mason {
2263b4ce94deSChris Mason 	int slot;
2264b4ce94deSChris Mason 	int nritems;
2265b4ce94deSChris Mason 	struct extent_buffer *parent;
2266b4ce94deSChris Mason 	struct extent_buffer *eb;
2267b4ce94deSChris Mason 	u64 gen;
2268b4ce94deSChris Mason 	u64 block1 = 0;
2269b4ce94deSChris Mason 	u64 block2 = 0;
2270b4ce94deSChris Mason 
22718c594ea8SChris Mason 	parent = path->nodes[level + 1];
2272b4ce94deSChris Mason 	if (!parent)
22730b08851fSJosef Bacik 		return;
2274b4ce94deSChris Mason 
2275b4ce94deSChris Mason 	nritems = btrfs_header_nritems(parent);
22768c594ea8SChris Mason 	slot = path->slots[level + 1];
2277b4ce94deSChris Mason 
2278b4ce94deSChris Mason 	if (slot > 0) {
2279b4ce94deSChris Mason 		block1 = btrfs_node_blockptr(parent, slot - 1);
2280b4ce94deSChris Mason 		gen = btrfs_node_ptr_generation(parent, slot - 1);
22810b246afaSJeff Mahoney 		eb = find_extent_buffer(fs_info, block1);
2282b9fab919SChris Mason 		/*
2283b9fab919SChris Mason 		 * if we get -eagain from btrfs_buffer_uptodate, we
2284b9fab919SChris Mason 		 * don't want to return eagain here.  That will loop
2285b9fab919SChris Mason 		 * forever
2286b9fab919SChris Mason 		 */
2287b9fab919SChris Mason 		if (eb && btrfs_buffer_uptodate(eb, gen, 1) != 0)
2288b4ce94deSChris Mason 			block1 = 0;
2289b4ce94deSChris Mason 		free_extent_buffer(eb);
2290b4ce94deSChris Mason 	}
22918c594ea8SChris Mason 	if (slot + 1 < nritems) {
2292b4ce94deSChris Mason 		block2 = btrfs_node_blockptr(parent, slot + 1);
2293b4ce94deSChris Mason 		gen = btrfs_node_ptr_generation(parent, slot + 1);
22940b246afaSJeff Mahoney 		eb = find_extent_buffer(fs_info, block2);
2295b9fab919SChris Mason 		if (eb && btrfs_buffer_uptodate(eb, gen, 1) != 0)
2296b4ce94deSChris Mason 			block2 = 0;
2297b4ce94deSChris Mason 		free_extent_buffer(eb);
2298b4ce94deSChris Mason 	}
22998c594ea8SChris Mason 
2300b4ce94deSChris Mason 	if (block1)
23012ff7e61eSJeff Mahoney 		readahead_tree_block(fs_info, block1);
2302b4ce94deSChris Mason 	if (block2)
23032ff7e61eSJeff Mahoney 		readahead_tree_block(fs_info, block2);
2304b4ce94deSChris Mason }
2305b4ce94deSChris Mason 
2306b4ce94deSChris Mason 
2307b4ce94deSChris Mason /*
2308d397712bSChris Mason  * when we walk down the tree, it is usually safe to unlock the higher layers
2309d397712bSChris Mason  * in the tree.  The exceptions are when our path goes through slot 0, because
2310d397712bSChris Mason  * operations on the tree might require changing key pointers higher up in the
2311d397712bSChris Mason  * tree.
2312d352ac68SChris Mason  *
2313d397712bSChris Mason  * callers might also have set path->keep_locks, which tells this code to keep
2314d397712bSChris Mason  * the lock if the path points to the last slot in the block.  This is part of
2315d397712bSChris Mason  * walking through the tree, and selecting the next slot in the higher block.
2316d352ac68SChris Mason  *
2317d397712bSChris Mason  * lowest_unlock sets the lowest level in the tree we're allowed to unlock.  so
2318d397712bSChris Mason  * if lowest_unlock is 1, level 0 won't be unlocked
2319d352ac68SChris Mason  */
2320e02119d5SChris Mason static noinline void unlock_up(struct btrfs_path *path, int level,
2321f7c79f30SChris Mason 			       int lowest_unlock, int min_write_lock_level,
2322f7c79f30SChris Mason 			       int *write_lock_level)
2323925baeddSChris Mason {
2324925baeddSChris Mason 	int i;
2325925baeddSChris Mason 	int skip_level = level;
2326051e1b9fSChris Mason 	int no_skips = 0;
2327925baeddSChris Mason 	struct extent_buffer *t;
2328925baeddSChris Mason 
2329925baeddSChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2330925baeddSChris Mason 		if (!path->nodes[i])
2331925baeddSChris Mason 			break;
2332925baeddSChris Mason 		if (!path->locks[i])
2333925baeddSChris Mason 			break;
2334051e1b9fSChris Mason 		if (!no_skips && path->slots[i] == 0) {
2335925baeddSChris Mason 			skip_level = i + 1;
2336925baeddSChris Mason 			continue;
2337925baeddSChris Mason 		}
2338051e1b9fSChris Mason 		if (!no_skips && path->keep_locks) {
2339925baeddSChris Mason 			u32 nritems;
2340925baeddSChris Mason 			t = path->nodes[i];
2341925baeddSChris Mason 			nritems = btrfs_header_nritems(t);
2342051e1b9fSChris Mason 			if (nritems < 1 || path->slots[i] >= nritems - 1) {
2343925baeddSChris Mason 				skip_level = i + 1;
2344925baeddSChris Mason 				continue;
2345925baeddSChris Mason 			}
2346925baeddSChris Mason 		}
2347051e1b9fSChris Mason 		if (skip_level < i && i >= lowest_unlock)
2348051e1b9fSChris Mason 			no_skips = 1;
2349051e1b9fSChris Mason 
2350925baeddSChris Mason 		t = path->nodes[i];
2351d80bb3f9SLiu Bo 		if (i >= lowest_unlock && i > skip_level) {
2352bd681513SChris Mason 			btrfs_tree_unlock_rw(t, path->locks[i]);
2353925baeddSChris Mason 			path->locks[i] = 0;
2354f7c79f30SChris Mason 			if (write_lock_level &&
2355f7c79f30SChris Mason 			    i > min_write_lock_level &&
2356f7c79f30SChris Mason 			    i <= *write_lock_level) {
2357f7c79f30SChris Mason 				*write_lock_level = i - 1;
2358f7c79f30SChris Mason 			}
2359925baeddSChris Mason 		}
2360925baeddSChris Mason 	}
2361925baeddSChris Mason }
2362925baeddSChris Mason 
23633c69faecSChris Mason /*
2364c8c42864SChris Mason  * helper function for btrfs_search_slot.  The goal is to find a block
2365c8c42864SChris Mason  * in cache without setting the path to blocking.  If we find the block
2366c8c42864SChris Mason  * we return zero and the path is unchanged.
2367c8c42864SChris Mason  *
2368c8c42864SChris Mason  * If we can't find the block, we set the path blocking and do some
2369c8c42864SChris Mason  * reada.  -EAGAIN is returned and the search must be repeated.
2370c8c42864SChris Mason  */
2371c8c42864SChris Mason static int
2372d07b8528SLiu Bo read_block_for_search(struct btrfs_root *root, struct btrfs_path *p,
2373c8c42864SChris Mason 		      struct extent_buffer **eb_ret, int level, int slot,
2374cda79c54SDavid Sterba 		      const struct btrfs_key *key)
2375c8c42864SChris Mason {
23760b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
2377c8c42864SChris Mason 	u64 blocknr;
2378c8c42864SChris Mason 	u64 gen;
2379c8c42864SChris Mason 	struct extent_buffer *b = *eb_ret;
2380c8c42864SChris Mason 	struct extent_buffer *tmp;
2381581c1760SQu Wenruo 	struct btrfs_key first_key;
238276a05b35SChris Mason 	int ret;
2383581c1760SQu Wenruo 	int parent_level;
2384c8c42864SChris Mason 
2385c8c42864SChris Mason 	blocknr = btrfs_node_blockptr(b, slot);
2386c8c42864SChris Mason 	gen = btrfs_node_ptr_generation(b, slot);
2387581c1760SQu Wenruo 	parent_level = btrfs_header_level(b);
2388581c1760SQu Wenruo 	btrfs_node_key_to_cpu(b, &first_key, slot);
2389c8c42864SChris Mason 
23900b246afaSJeff Mahoney 	tmp = find_extent_buffer(fs_info, blocknr);
2391cb44921aSChris Mason 	if (tmp) {
2392b9fab919SChris Mason 		/* first we do an atomic uptodate check */
2393b9fab919SChris Mason 		if (btrfs_buffer_uptodate(tmp, gen, 1) > 0) {
2394448de471SQu Wenruo 			/*
2395448de471SQu Wenruo 			 * Do extra check for first_key, eb can be stale due to
2396448de471SQu Wenruo 			 * being cached, read from scrub, or have multiple
2397448de471SQu Wenruo 			 * parents (shared tree blocks).
2398448de471SQu Wenruo 			 */
2399e064d5e9SDavid Sterba 			if (btrfs_verify_level_key(tmp,
2400448de471SQu Wenruo 					parent_level - 1, &first_key, gen)) {
2401448de471SQu Wenruo 				free_extent_buffer(tmp);
2402448de471SQu Wenruo 				return -EUCLEAN;
2403448de471SQu Wenruo 			}
2404c8c42864SChris Mason 			*eb_ret = tmp;
2405c8c42864SChris Mason 			return 0;
2406c8c42864SChris Mason 		}
2407bdf7c00eSJosef Bacik 
2408cb44921aSChris Mason 		/* the pages were up to date, but we failed
2409cb44921aSChris Mason 		 * the generation number check.  Do a full
2410cb44921aSChris Mason 		 * read for the generation number that is correct.
2411cb44921aSChris Mason 		 * We must do this without dropping locks so
2412cb44921aSChris Mason 		 * we can trust our generation number
2413cb44921aSChris Mason 		 */
2414bd681513SChris Mason 		btrfs_set_path_blocking(p);
2415bd681513SChris Mason 
2416b9fab919SChris Mason 		/* now we're allowed to do a blocking uptodate check */
2417581c1760SQu Wenruo 		ret = btrfs_read_buffer(tmp, gen, parent_level - 1, &first_key);
2418bdf7c00eSJosef Bacik 		if (!ret) {
2419cb44921aSChris Mason 			*eb_ret = tmp;
2420cb44921aSChris Mason 			return 0;
2421cb44921aSChris Mason 		}
2422cb44921aSChris Mason 		free_extent_buffer(tmp);
2423b3b4aa74SDavid Sterba 		btrfs_release_path(p);
2424cb44921aSChris Mason 		return -EIO;
2425cb44921aSChris Mason 	}
2426c8c42864SChris Mason 
2427c8c42864SChris Mason 	/*
2428c8c42864SChris Mason 	 * reduce lock contention at high levels
2429c8c42864SChris Mason 	 * of the btree by dropping locks before
243076a05b35SChris Mason 	 * we read.  Don't release the lock on the current
243176a05b35SChris Mason 	 * level because we need to walk this node to figure
243276a05b35SChris Mason 	 * out which blocks to read.
2433c8c42864SChris Mason 	 */
24348c594ea8SChris Mason 	btrfs_unlock_up_safe(p, level + 1);
24358c594ea8SChris Mason 	btrfs_set_path_blocking(p);
24368c594ea8SChris Mason 
2437e4058b54SDavid Sterba 	if (p->reada != READA_NONE)
24382ff7e61eSJeff Mahoney 		reada_for_search(fs_info, p, level, slot, key->objectid);
2439c8c42864SChris Mason 
244076a05b35SChris Mason 	ret = -EAGAIN;
244102a3307aSLiu Bo 	tmp = read_tree_block(fs_info, blocknr, gen, parent_level - 1,
2442581c1760SQu Wenruo 			      &first_key);
244364c043deSLiu Bo 	if (!IS_ERR(tmp)) {
244476a05b35SChris Mason 		/*
244576a05b35SChris Mason 		 * If the read above didn't mark this buffer up to date,
244676a05b35SChris Mason 		 * it will never end up being up to date.  Set ret to EIO now
244776a05b35SChris Mason 		 * and give up so that our caller doesn't loop forever
244876a05b35SChris Mason 		 * on our EAGAINs.
244976a05b35SChris Mason 		 */
2450e6a1d6fdSLiu Bo 		if (!extent_buffer_uptodate(tmp))
245176a05b35SChris Mason 			ret = -EIO;
2452c8c42864SChris Mason 		free_extent_buffer(tmp);
2453c871b0f2SLiu Bo 	} else {
2454c871b0f2SLiu Bo 		ret = PTR_ERR(tmp);
245576a05b35SChris Mason 	}
245602a3307aSLiu Bo 
245702a3307aSLiu Bo 	btrfs_release_path(p);
245876a05b35SChris Mason 	return ret;
2459c8c42864SChris Mason }
2460c8c42864SChris Mason 
2461c8c42864SChris Mason /*
2462c8c42864SChris Mason  * helper function for btrfs_search_slot.  This does all of the checks
2463c8c42864SChris Mason  * for node-level blocks and does any balancing required based on
2464c8c42864SChris Mason  * the ins_len.
2465c8c42864SChris Mason  *
2466c8c42864SChris Mason  * If no extra work was required, zero is returned.  If we had to
2467c8c42864SChris Mason  * drop the path, -EAGAIN is returned and btrfs_search_slot must
2468c8c42864SChris Mason  * start over
2469c8c42864SChris Mason  */
2470c8c42864SChris Mason static int
2471c8c42864SChris Mason setup_nodes_for_search(struct btrfs_trans_handle *trans,
2472c8c42864SChris Mason 		       struct btrfs_root *root, struct btrfs_path *p,
2473bd681513SChris Mason 		       struct extent_buffer *b, int level, int ins_len,
2474bd681513SChris Mason 		       int *write_lock_level)
2475c8c42864SChris Mason {
24760b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
2477c8c42864SChris Mason 	int ret;
24780b246afaSJeff Mahoney 
2479c8c42864SChris Mason 	if ((p->search_for_split || ins_len > 0) && btrfs_header_nritems(b) >=
24800b246afaSJeff Mahoney 	    BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3) {
2481c8c42864SChris Mason 		int sret;
2482c8c42864SChris Mason 
2483bd681513SChris Mason 		if (*write_lock_level < level + 1) {
2484bd681513SChris Mason 			*write_lock_level = level + 1;
2485bd681513SChris Mason 			btrfs_release_path(p);
2486bd681513SChris Mason 			goto again;
2487bd681513SChris Mason 		}
2488bd681513SChris Mason 
2489c8c42864SChris Mason 		btrfs_set_path_blocking(p);
24902ff7e61eSJeff Mahoney 		reada_for_balance(fs_info, p, level);
2491c8c42864SChris Mason 		sret = split_node(trans, root, p, level);
2492c8c42864SChris Mason 
2493c8c42864SChris Mason 		BUG_ON(sret > 0);
2494c8c42864SChris Mason 		if (sret) {
2495c8c42864SChris Mason 			ret = sret;
2496c8c42864SChris Mason 			goto done;
2497c8c42864SChris Mason 		}
2498c8c42864SChris Mason 		b = p->nodes[level];
2499c8c42864SChris Mason 	} else if (ins_len < 0 && btrfs_header_nritems(b) <
25000b246afaSJeff Mahoney 		   BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 2) {
2501c8c42864SChris Mason 		int sret;
2502c8c42864SChris Mason 
2503bd681513SChris Mason 		if (*write_lock_level < level + 1) {
2504bd681513SChris Mason 			*write_lock_level = level + 1;
2505bd681513SChris Mason 			btrfs_release_path(p);
2506bd681513SChris Mason 			goto again;
2507bd681513SChris Mason 		}
2508bd681513SChris Mason 
2509c8c42864SChris Mason 		btrfs_set_path_blocking(p);
25102ff7e61eSJeff Mahoney 		reada_for_balance(fs_info, p, level);
2511c8c42864SChris Mason 		sret = balance_level(trans, root, p, level);
2512c8c42864SChris Mason 
2513c8c42864SChris Mason 		if (sret) {
2514c8c42864SChris Mason 			ret = sret;
2515c8c42864SChris Mason 			goto done;
2516c8c42864SChris Mason 		}
2517c8c42864SChris Mason 		b = p->nodes[level];
2518c8c42864SChris Mason 		if (!b) {
2519b3b4aa74SDavid Sterba 			btrfs_release_path(p);
2520c8c42864SChris Mason 			goto again;
2521c8c42864SChris Mason 		}
2522c8c42864SChris Mason 		BUG_ON(btrfs_header_nritems(b) == 1);
2523c8c42864SChris Mason 	}
2524c8c42864SChris Mason 	return 0;
2525c8c42864SChris Mason 
2526c8c42864SChris Mason again:
2527c8c42864SChris Mason 	ret = -EAGAIN;
2528c8c42864SChris Mason done:
2529c8c42864SChris Mason 	return ret;
2530c8c42864SChris Mason }
2531c8c42864SChris Mason 
2532310712b2SOmar Sandoval static int key_search(struct extent_buffer *b, const struct btrfs_key *key,
2533d7396f07SFilipe David Borba Manana 		      int level, int *prev_cmp, int *slot)
2534d7396f07SFilipe David Borba Manana {
2535d7396f07SFilipe David Borba Manana 	if (*prev_cmp != 0) {
2536a74b35ecSNikolay Borisov 		*prev_cmp = btrfs_bin_search(b, key, level, slot);
2537d7396f07SFilipe David Borba Manana 		return *prev_cmp;
2538d7396f07SFilipe David Borba Manana 	}
2539d7396f07SFilipe David Borba Manana 
2540d7396f07SFilipe David Borba Manana 	*slot = 0;
2541d7396f07SFilipe David Borba Manana 
2542d7396f07SFilipe David Borba Manana 	return 0;
2543d7396f07SFilipe David Borba Manana }
2544d7396f07SFilipe David Borba Manana 
2545381cf658SDavid Sterba int btrfs_find_item(struct btrfs_root *fs_root, struct btrfs_path *path,
2546e33d5c3dSKelley Nielsen 		u64 iobjectid, u64 ioff, u8 key_type,
2547e33d5c3dSKelley Nielsen 		struct btrfs_key *found_key)
2548e33d5c3dSKelley Nielsen {
2549e33d5c3dSKelley Nielsen 	int ret;
2550e33d5c3dSKelley Nielsen 	struct btrfs_key key;
2551e33d5c3dSKelley Nielsen 	struct extent_buffer *eb;
2552381cf658SDavid Sterba 
2553381cf658SDavid Sterba 	ASSERT(path);
25541d4c08e0SDavid Sterba 	ASSERT(found_key);
2555e33d5c3dSKelley Nielsen 
2556e33d5c3dSKelley Nielsen 	key.type = key_type;
2557e33d5c3dSKelley Nielsen 	key.objectid = iobjectid;
2558e33d5c3dSKelley Nielsen 	key.offset = ioff;
2559e33d5c3dSKelley Nielsen 
2560e33d5c3dSKelley Nielsen 	ret = btrfs_search_slot(NULL, fs_root, &key, path, 0, 0);
25611d4c08e0SDavid Sterba 	if (ret < 0)
2562e33d5c3dSKelley Nielsen 		return ret;
2563e33d5c3dSKelley Nielsen 
2564e33d5c3dSKelley Nielsen 	eb = path->nodes[0];
2565e33d5c3dSKelley Nielsen 	if (ret && path->slots[0] >= btrfs_header_nritems(eb)) {
2566e33d5c3dSKelley Nielsen 		ret = btrfs_next_leaf(fs_root, path);
2567e33d5c3dSKelley Nielsen 		if (ret)
2568e33d5c3dSKelley Nielsen 			return ret;
2569e33d5c3dSKelley Nielsen 		eb = path->nodes[0];
2570e33d5c3dSKelley Nielsen 	}
2571e33d5c3dSKelley Nielsen 
2572e33d5c3dSKelley Nielsen 	btrfs_item_key_to_cpu(eb, found_key, path->slots[0]);
2573e33d5c3dSKelley Nielsen 	if (found_key->type != key.type ||
2574e33d5c3dSKelley Nielsen 			found_key->objectid != key.objectid)
2575e33d5c3dSKelley Nielsen 		return 1;
2576e33d5c3dSKelley Nielsen 
2577e33d5c3dSKelley Nielsen 	return 0;
2578e33d5c3dSKelley Nielsen }
2579e33d5c3dSKelley Nielsen 
25801fc28d8eSLiu Bo static struct extent_buffer *btrfs_search_slot_get_root(struct btrfs_root *root,
25811fc28d8eSLiu Bo 							struct btrfs_path *p,
25821fc28d8eSLiu Bo 							int write_lock_level)
25831fc28d8eSLiu Bo {
25841fc28d8eSLiu Bo 	struct btrfs_fs_info *fs_info = root->fs_info;
25851fc28d8eSLiu Bo 	struct extent_buffer *b;
25861fc28d8eSLiu Bo 	int root_lock;
25871fc28d8eSLiu Bo 	int level = 0;
25881fc28d8eSLiu Bo 
25891fc28d8eSLiu Bo 	/* We try very hard to do read locks on the root */
25901fc28d8eSLiu Bo 	root_lock = BTRFS_READ_LOCK;
25911fc28d8eSLiu Bo 
25921fc28d8eSLiu Bo 	if (p->search_commit_root) {
2593be6821f8SFilipe Manana 		/*
2594be6821f8SFilipe Manana 		 * The commit roots are read only so we always do read locks,
2595be6821f8SFilipe Manana 		 * and we always must hold the commit_root_sem when doing
2596be6821f8SFilipe Manana 		 * searches on them, the only exception is send where we don't
2597be6821f8SFilipe Manana 		 * want to block transaction commits for a long time, so
2598be6821f8SFilipe Manana 		 * we need to clone the commit root in order to avoid races
2599be6821f8SFilipe Manana 		 * with transaction commits that create a snapshot of one of
2600be6821f8SFilipe Manana 		 * the roots used by a send operation.
2601be6821f8SFilipe Manana 		 */
2602be6821f8SFilipe Manana 		if (p->need_commit_sem) {
26031fc28d8eSLiu Bo 			down_read(&fs_info->commit_root_sem);
2604be6821f8SFilipe Manana 			b = btrfs_clone_extent_buffer(root->commit_root);
2605be6821f8SFilipe Manana 			up_read(&fs_info->commit_root_sem);
2606be6821f8SFilipe Manana 			if (!b)
2607be6821f8SFilipe Manana 				return ERR_PTR(-ENOMEM);
2608be6821f8SFilipe Manana 
2609be6821f8SFilipe Manana 		} else {
26101fc28d8eSLiu Bo 			b = root->commit_root;
261167439dadSDavid Sterba 			atomic_inc(&b->refs);
2612be6821f8SFilipe Manana 		}
26131fc28d8eSLiu Bo 		level = btrfs_header_level(b);
2614f9ddfd05SLiu Bo 		/*
2615f9ddfd05SLiu Bo 		 * Ensure that all callers have set skip_locking when
2616f9ddfd05SLiu Bo 		 * p->search_commit_root = 1.
2617f9ddfd05SLiu Bo 		 */
2618f9ddfd05SLiu Bo 		ASSERT(p->skip_locking == 1);
26191fc28d8eSLiu Bo 
26201fc28d8eSLiu Bo 		goto out;
26211fc28d8eSLiu Bo 	}
26221fc28d8eSLiu Bo 
26231fc28d8eSLiu Bo 	if (p->skip_locking) {
26241fc28d8eSLiu Bo 		b = btrfs_root_node(root);
26251fc28d8eSLiu Bo 		level = btrfs_header_level(b);
26261fc28d8eSLiu Bo 		goto out;
26271fc28d8eSLiu Bo 	}
26281fc28d8eSLiu Bo 
26291fc28d8eSLiu Bo 	/*
2630662c653bSLiu Bo 	 * If the level is set to maximum, we can skip trying to get the read
2631662c653bSLiu Bo 	 * lock.
2632662c653bSLiu Bo 	 */
2633662c653bSLiu Bo 	if (write_lock_level < BTRFS_MAX_LEVEL) {
2634662c653bSLiu Bo 		/*
2635662c653bSLiu Bo 		 * We don't know the level of the root node until we actually
2636662c653bSLiu Bo 		 * have it read locked
26371fc28d8eSLiu Bo 		 */
26381fc28d8eSLiu Bo 		b = btrfs_read_lock_root_node(root);
26391fc28d8eSLiu Bo 		level = btrfs_header_level(b);
26401fc28d8eSLiu Bo 		if (level > write_lock_level)
26411fc28d8eSLiu Bo 			goto out;
26421fc28d8eSLiu Bo 
2643662c653bSLiu Bo 		/* Whoops, must trade for write lock */
26441fc28d8eSLiu Bo 		btrfs_tree_read_unlock(b);
26451fc28d8eSLiu Bo 		free_extent_buffer(b);
2646662c653bSLiu Bo 	}
2647662c653bSLiu Bo 
26481fc28d8eSLiu Bo 	b = btrfs_lock_root_node(root);
26491fc28d8eSLiu Bo 	root_lock = BTRFS_WRITE_LOCK;
26501fc28d8eSLiu Bo 
26511fc28d8eSLiu Bo 	/* The level might have changed, check again */
26521fc28d8eSLiu Bo 	level = btrfs_header_level(b);
26531fc28d8eSLiu Bo 
26541fc28d8eSLiu Bo out:
26551fc28d8eSLiu Bo 	p->nodes[level] = b;
26561fc28d8eSLiu Bo 	if (!p->skip_locking)
26571fc28d8eSLiu Bo 		p->locks[level] = root_lock;
26581fc28d8eSLiu Bo 	/*
26591fc28d8eSLiu Bo 	 * Callers are responsible for dropping b's references.
26601fc28d8eSLiu Bo 	 */
26611fc28d8eSLiu Bo 	return b;
26621fc28d8eSLiu Bo }
26631fc28d8eSLiu Bo 
26641fc28d8eSLiu Bo 
2665c8c42864SChris Mason /*
26664271eceaSNikolay Borisov  * btrfs_search_slot - look for a key in a tree and perform necessary
26674271eceaSNikolay Borisov  * modifications to preserve tree invariants.
266874123bd7SChris Mason  *
26694271eceaSNikolay Borisov  * @trans:	Handle of transaction, used when modifying the tree
26704271eceaSNikolay Borisov  * @p:		Holds all btree nodes along the search path
26714271eceaSNikolay Borisov  * @root:	The root node of the tree
26724271eceaSNikolay Borisov  * @key:	The key we are looking for
26734271eceaSNikolay Borisov  * @ins_len:	Indicates purpose of search, for inserts it is 1, for
26744271eceaSNikolay Borisov  *		deletions it's -1. 0 for plain searches
26754271eceaSNikolay Borisov  * @cow:	boolean should CoW operations be performed. Must always be 1
26764271eceaSNikolay Borisov  *		when modifying the tree.
267797571fd0SChris Mason  *
26784271eceaSNikolay Borisov  * If @ins_len > 0, nodes and leaves will be split as we walk down the tree.
26794271eceaSNikolay Borisov  * If @ins_len < 0, nodes will be merged as we walk down the tree (if possible)
26804271eceaSNikolay Borisov  *
26814271eceaSNikolay Borisov  * If @key is found, 0 is returned and you can find the item in the leaf level
26824271eceaSNikolay Borisov  * of the path (level 0)
26834271eceaSNikolay Borisov  *
26844271eceaSNikolay Borisov  * If @key isn't found, 1 is returned and the leaf level of the path (level 0)
26854271eceaSNikolay Borisov  * points to the slot where it should be inserted
26864271eceaSNikolay Borisov  *
26874271eceaSNikolay Borisov  * If an error is encountered while searching the tree a negative error number
26884271eceaSNikolay Borisov  * is returned
268974123bd7SChris Mason  */
2690310712b2SOmar Sandoval int btrfs_search_slot(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2691310712b2SOmar Sandoval 		      const struct btrfs_key *key, struct btrfs_path *p,
2692310712b2SOmar Sandoval 		      int ins_len, int cow)
2693be0e5c09SChris Mason {
26945f39d397SChris Mason 	struct extent_buffer *b;
2695be0e5c09SChris Mason 	int slot;
2696be0e5c09SChris Mason 	int ret;
269733c66f43SYan Zheng 	int err;
2698be0e5c09SChris Mason 	int level;
2699925baeddSChris Mason 	int lowest_unlock = 1;
2700bd681513SChris Mason 	/* everything at write_lock_level or lower must be write locked */
2701bd681513SChris Mason 	int write_lock_level = 0;
27029f3a7427SChris Mason 	u8 lowest_level = 0;
2703f7c79f30SChris Mason 	int min_write_lock_level;
2704d7396f07SFilipe David Borba Manana 	int prev_cmp;
27059f3a7427SChris Mason 
27066702ed49SChris Mason 	lowest_level = p->lowest_level;
2707323ac95bSChris Mason 	WARN_ON(lowest_level && ins_len > 0);
270822b0ebdaSChris Mason 	WARN_ON(p->nodes[0] != NULL);
2709eb653de1SFilipe David Borba Manana 	BUG_ON(!cow && ins_len);
271025179201SJosef Bacik 
2711bd681513SChris Mason 	if (ins_len < 0) {
2712925baeddSChris Mason 		lowest_unlock = 2;
271365b51a00SChris Mason 
2714bd681513SChris Mason 		/* when we are removing items, we might have to go up to level
2715bd681513SChris Mason 		 * two as we update tree pointers  Make sure we keep write
2716bd681513SChris Mason 		 * for those levels as well
2717bd681513SChris Mason 		 */
2718bd681513SChris Mason 		write_lock_level = 2;
2719bd681513SChris Mason 	} else if (ins_len > 0) {
2720bd681513SChris Mason 		/*
2721bd681513SChris Mason 		 * for inserting items, make sure we have a write lock on
2722bd681513SChris Mason 		 * level 1 so we can update keys
2723bd681513SChris Mason 		 */
2724bd681513SChris Mason 		write_lock_level = 1;
2725bd681513SChris Mason 	}
2726bd681513SChris Mason 
2727bd681513SChris Mason 	if (!cow)
2728bd681513SChris Mason 		write_lock_level = -1;
2729bd681513SChris Mason 
273009a2a8f9SJosef Bacik 	if (cow && (p->keep_locks || p->lowest_level))
2731bd681513SChris Mason 		write_lock_level = BTRFS_MAX_LEVEL;
2732bd681513SChris Mason 
2733f7c79f30SChris Mason 	min_write_lock_level = write_lock_level;
2734f7c79f30SChris Mason 
2735bb803951SChris Mason again:
2736d7396f07SFilipe David Borba Manana 	prev_cmp = -1;
27371fc28d8eSLiu Bo 	b = btrfs_search_slot_get_root(root, p, write_lock_level);
2738be6821f8SFilipe Manana 	if (IS_ERR(b)) {
2739be6821f8SFilipe Manana 		ret = PTR_ERR(b);
2740be6821f8SFilipe Manana 		goto done;
2741be6821f8SFilipe Manana 	}
2742925baeddSChris Mason 
2743eb60ceacSChris Mason 	while (b) {
2744f624d976SQu Wenruo 		int dec = 0;
2745f624d976SQu Wenruo 
27465f39d397SChris Mason 		level = btrfs_header_level(b);
274765b51a00SChris Mason 
274802217ed2SChris Mason 		if (cow) {
27499ea2c7c9SNikolay Borisov 			bool last_level = (level == (BTRFS_MAX_LEVEL - 1));
27509ea2c7c9SNikolay Borisov 
2751c8c42864SChris Mason 			/*
2752c8c42864SChris Mason 			 * if we don't really need to cow this block
2753c8c42864SChris Mason 			 * then we don't want to set the path blocking,
2754c8c42864SChris Mason 			 * so we test it here
2755c8c42864SChris Mason 			 */
275664c12921SJeff Mahoney 			if (!should_cow_block(trans, root, b)) {
275764c12921SJeff Mahoney 				trans->dirty = true;
275865b51a00SChris Mason 				goto cow_done;
275964c12921SJeff Mahoney 			}
27605d4f98a2SYan Zheng 
2761bd681513SChris Mason 			/*
2762bd681513SChris Mason 			 * must have write locks on this node and the
2763bd681513SChris Mason 			 * parent
2764bd681513SChris Mason 			 */
27655124e00eSJosef Bacik 			if (level > write_lock_level ||
27665124e00eSJosef Bacik 			    (level + 1 > write_lock_level &&
27675124e00eSJosef Bacik 			    level + 1 < BTRFS_MAX_LEVEL &&
27685124e00eSJosef Bacik 			    p->nodes[level + 1])) {
2769bd681513SChris Mason 				write_lock_level = level + 1;
2770bd681513SChris Mason 				btrfs_release_path(p);
2771bd681513SChris Mason 				goto again;
2772bd681513SChris Mason 			}
2773bd681513SChris Mason 
2774160f4089SFilipe Manana 			btrfs_set_path_blocking(p);
27759ea2c7c9SNikolay Borisov 			if (last_level)
27769ea2c7c9SNikolay Borisov 				err = btrfs_cow_block(trans, root, b, NULL, 0,
27779ea2c7c9SNikolay Borisov 						      &b);
27789ea2c7c9SNikolay Borisov 			else
277933c66f43SYan Zheng 				err = btrfs_cow_block(trans, root, b,
2780e20d96d6SChris Mason 						      p->nodes[level + 1],
27819fa8cfe7SChris Mason 						      p->slots[level + 1], &b);
278233c66f43SYan Zheng 			if (err) {
278333c66f43SYan Zheng 				ret = err;
278465b51a00SChris Mason 				goto done;
278554aa1f4dSChris Mason 			}
278602217ed2SChris Mason 		}
278765b51a00SChris Mason cow_done:
2788eb60ceacSChris Mason 		p->nodes[level] = b;
278952398340SLiu Bo 		/*
279052398340SLiu Bo 		 * Leave path with blocking locks to avoid massive
279152398340SLiu Bo 		 * lock context switch, this is made on purpose.
279252398340SLiu Bo 		 */
2793b4ce94deSChris Mason 
2794b4ce94deSChris Mason 		/*
2795b4ce94deSChris Mason 		 * we have a lock on b and as long as we aren't changing
2796b4ce94deSChris Mason 		 * the tree, there is no way to for the items in b to change.
2797b4ce94deSChris Mason 		 * It is safe to drop the lock on our parent before we
2798b4ce94deSChris Mason 		 * go through the expensive btree search on b.
2799b4ce94deSChris Mason 		 *
2800eb653de1SFilipe David Borba Manana 		 * If we're inserting or deleting (ins_len != 0), then we might
2801eb653de1SFilipe David Borba Manana 		 * be changing slot zero, which may require changing the parent.
2802eb653de1SFilipe David Borba Manana 		 * So, we can't drop the lock until after we know which slot
2803eb653de1SFilipe David Borba Manana 		 * we're operating on.
2804b4ce94deSChris Mason 		 */
2805eb653de1SFilipe David Borba Manana 		if (!ins_len && !p->keep_locks) {
2806eb653de1SFilipe David Borba Manana 			int u = level + 1;
2807eb653de1SFilipe David Borba Manana 
2808eb653de1SFilipe David Borba Manana 			if (u < BTRFS_MAX_LEVEL && p->locks[u]) {
2809eb653de1SFilipe David Borba Manana 				btrfs_tree_unlock_rw(p->nodes[u], p->locks[u]);
2810eb653de1SFilipe David Borba Manana 				p->locks[u] = 0;
2811eb653de1SFilipe David Borba Manana 			}
2812eb653de1SFilipe David Borba Manana 		}
2813b4ce94deSChris Mason 
2814d7396f07SFilipe David Borba Manana 		ret = key_search(b, key, level, &prev_cmp, &slot);
2815415b35a5SLiu Bo 		if (ret < 0)
2816415b35a5SLiu Bo 			goto done;
2817b4ce94deSChris Mason 
2818f624d976SQu Wenruo 		if (level == 0) {
2819be0e5c09SChris Mason 			p->slots[level] = slot;
282087b29b20SYan Zheng 			if (ins_len > 0 &&
2821e902baacSDavid Sterba 			    btrfs_leaf_free_space(b) < ins_len) {
2822bd681513SChris Mason 				if (write_lock_level < 1) {
2823bd681513SChris Mason 					write_lock_level = 1;
2824bd681513SChris Mason 					btrfs_release_path(p);
2825bd681513SChris Mason 					goto again;
2826bd681513SChris Mason 				}
2827bd681513SChris Mason 
2828b4ce94deSChris Mason 				btrfs_set_path_blocking(p);
282933c66f43SYan Zheng 				err = split_leaf(trans, root, key,
2830cc0c5538SChris Mason 						 p, ins_len, ret == 0);
2831b4ce94deSChris Mason 
283233c66f43SYan Zheng 				BUG_ON(err > 0);
283333c66f43SYan Zheng 				if (err) {
283433c66f43SYan Zheng 					ret = err;
283565b51a00SChris Mason 					goto done;
283665b51a00SChris Mason 				}
28375c680ed6SChris Mason 			}
2838459931ecSChris Mason 			if (!p->search_for_split)
2839f7c79f30SChris Mason 				unlock_up(p, level, lowest_unlock,
28404b6f8e96SLiu Bo 					  min_write_lock_level, NULL);
284165b51a00SChris Mason 			goto done;
284265b51a00SChris Mason 		}
2843f624d976SQu Wenruo 		if (ret && slot > 0) {
2844f624d976SQu Wenruo 			dec = 1;
2845f624d976SQu Wenruo 			slot--;
2846f624d976SQu Wenruo 		}
2847f624d976SQu Wenruo 		p->slots[level] = slot;
2848f624d976SQu Wenruo 		err = setup_nodes_for_search(trans, root, p, b, level, ins_len,
2849f624d976SQu Wenruo 					     &write_lock_level);
2850f624d976SQu Wenruo 		if (err == -EAGAIN)
2851f624d976SQu Wenruo 			goto again;
2852f624d976SQu Wenruo 		if (err) {
2853f624d976SQu Wenruo 			ret = err;
2854f624d976SQu Wenruo 			goto done;
2855f624d976SQu Wenruo 		}
2856f624d976SQu Wenruo 		b = p->nodes[level];
2857f624d976SQu Wenruo 		slot = p->slots[level];
2858f624d976SQu Wenruo 
2859f624d976SQu Wenruo 		/*
2860f624d976SQu Wenruo 		 * Slot 0 is special, if we change the key we have to update
2861f624d976SQu Wenruo 		 * the parent pointer which means we must have a write lock on
2862f624d976SQu Wenruo 		 * the parent
2863f624d976SQu Wenruo 		 */
2864f624d976SQu Wenruo 		if (slot == 0 && ins_len && write_lock_level < level + 1) {
2865f624d976SQu Wenruo 			write_lock_level = level + 1;
2866f624d976SQu Wenruo 			btrfs_release_path(p);
2867f624d976SQu Wenruo 			goto again;
2868f624d976SQu Wenruo 		}
2869f624d976SQu Wenruo 
2870f624d976SQu Wenruo 		unlock_up(p, level, lowest_unlock, min_write_lock_level,
2871f624d976SQu Wenruo 			  &write_lock_level);
2872f624d976SQu Wenruo 
2873f624d976SQu Wenruo 		if (level == lowest_level) {
2874f624d976SQu Wenruo 			if (dec)
2875f624d976SQu Wenruo 				p->slots[level]++;
2876f624d976SQu Wenruo 			goto done;
2877f624d976SQu Wenruo 		}
2878f624d976SQu Wenruo 
2879f624d976SQu Wenruo 		err = read_block_for_search(root, p, &b, level, slot, key);
2880f624d976SQu Wenruo 		if (err == -EAGAIN)
2881f624d976SQu Wenruo 			goto again;
2882f624d976SQu Wenruo 		if (err) {
2883f624d976SQu Wenruo 			ret = err;
2884f624d976SQu Wenruo 			goto done;
2885f624d976SQu Wenruo 		}
2886f624d976SQu Wenruo 
2887f624d976SQu Wenruo 		if (!p->skip_locking) {
2888f624d976SQu Wenruo 			level = btrfs_header_level(b);
2889f624d976SQu Wenruo 			if (level <= write_lock_level) {
2890f624d976SQu Wenruo 				if (!btrfs_try_tree_write_lock(b)) {
2891f624d976SQu Wenruo 					btrfs_set_path_blocking(p);
2892f624d976SQu Wenruo 					btrfs_tree_lock(b);
2893f624d976SQu Wenruo 				}
2894f624d976SQu Wenruo 				p->locks[level] = BTRFS_WRITE_LOCK;
2895f624d976SQu Wenruo 			} else {
2896f624d976SQu Wenruo 				if (!btrfs_tree_read_lock_atomic(b)) {
2897f624d976SQu Wenruo 					btrfs_set_path_blocking(p);
2898f624d976SQu Wenruo 					btrfs_tree_read_lock(b);
2899f624d976SQu Wenruo 				}
2900f624d976SQu Wenruo 				p->locks[level] = BTRFS_READ_LOCK;
2901f624d976SQu Wenruo 			}
2902f624d976SQu Wenruo 			p->nodes[level] = b;
2903f624d976SQu Wenruo 		}
290465b51a00SChris Mason 	}
290565b51a00SChris Mason 	ret = 1;
290665b51a00SChris Mason done:
2907b4ce94deSChris Mason 	/*
2908b4ce94deSChris Mason 	 * we don't really know what they plan on doing with the path
2909b4ce94deSChris Mason 	 * from here on, so for now just mark it as blocking
2910b4ce94deSChris Mason 	 */
2911b9473439SChris Mason 	if (!p->leave_spinning)
2912b4ce94deSChris Mason 		btrfs_set_path_blocking(p);
29135f5bc6b1SFilipe Manana 	if (ret < 0 && !p->skip_release_on_error)
2914b3b4aa74SDavid Sterba 		btrfs_release_path(p);
2915be0e5c09SChris Mason 	return ret;
2916be0e5c09SChris Mason }
2917be0e5c09SChris Mason 
291874123bd7SChris Mason /*
29195d9e75c4SJan Schmidt  * Like btrfs_search_slot, this looks for a key in the given tree. It uses the
29205d9e75c4SJan Schmidt  * current state of the tree together with the operations recorded in the tree
29215d9e75c4SJan Schmidt  * modification log to search for the key in a previous version of this tree, as
29225d9e75c4SJan Schmidt  * denoted by the time_seq parameter.
29235d9e75c4SJan Schmidt  *
29245d9e75c4SJan Schmidt  * Naturally, there is no support for insert, delete or cow operations.
29255d9e75c4SJan Schmidt  *
29265d9e75c4SJan Schmidt  * The resulting path and return value will be set up as if we called
29275d9e75c4SJan Schmidt  * btrfs_search_slot at that point in time with ins_len and cow both set to 0.
29285d9e75c4SJan Schmidt  */
2929310712b2SOmar Sandoval int btrfs_search_old_slot(struct btrfs_root *root, const struct btrfs_key *key,
29305d9e75c4SJan Schmidt 			  struct btrfs_path *p, u64 time_seq)
29315d9e75c4SJan Schmidt {
29320b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
29335d9e75c4SJan Schmidt 	struct extent_buffer *b;
29345d9e75c4SJan Schmidt 	int slot;
29355d9e75c4SJan Schmidt 	int ret;
29365d9e75c4SJan Schmidt 	int err;
29375d9e75c4SJan Schmidt 	int level;
29385d9e75c4SJan Schmidt 	int lowest_unlock = 1;
29395d9e75c4SJan Schmidt 	u8 lowest_level = 0;
2940d4b4087cSJosef Bacik 	int prev_cmp = -1;
29415d9e75c4SJan Schmidt 
29425d9e75c4SJan Schmidt 	lowest_level = p->lowest_level;
29435d9e75c4SJan Schmidt 	WARN_ON(p->nodes[0] != NULL);
29445d9e75c4SJan Schmidt 
29455d9e75c4SJan Schmidt 	if (p->search_commit_root) {
29465d9e75c4SJan Schmidt 		BUG_ON(time_seq);
29475d9e75c4SJan Schmidt 		return btrfs_search_slot(NULL, root, key, p, 0, 0);
29485d9e75c4SJan Schmidt 	}
29495d9e75c4SJan Schmidt 
29505d9e75c4SJan Schmidt again:
29515d9e75c4SJan Schmidt 	b = get_old_root(root, time_seq);
2952315bed43SNikolay Borisov 	if (!b) {
2953315bed43SNikolay Borisov 		ret = -EIO;
2954315bed43SNikolay Borisov 		goto done;
2955315bed43SNikolay Borisov 	}
29565d9e75c4SJan Schmidt 	level = btrfs_header_level(b);
29575d9e75c4SJan Schmidt 	p->locks[level] = BTRFS_READ_LOCK;
29585d9e75c4SJan Schmidt 
29595d9e75c4SJan Schmidt 	while (b) {
2960abe9339dSQu Wenruo 		int dec = 0;
2961abe9339dSQu Wenruo 
29625d9e75c4SJan Schmidt 		level = btrfs_header_level(b);
29635d9e75c4SJan Schmidt 		p->nodes[level] = b;
29645d9e75c4SJan Schmidt 
29655d9e75c4SJan Schmidt 		/*
29665d9e75c4SJan Schmidt 		 * we have a lock on b and as long as we aren't changing
29675d9e75c4SJan Schmidt 		 * the tree, there is no way to for the items in b to change.
29685d9e75c4SJan Schmidt 		 * It is safe to drop the lock on our parent before we
29695d9e75c4SJan Schmidt 		 * go through the expensive btree search on b.
29705d9e75c4SJan Schmidt 		 */
29715d9e75c4SJan Schmidt 		btrfs_unlock_up_safe(p, level + 1);
29725d9e75c4SJan Schmidt 
2973d4b4087cSJosef Bacik 		/*
297401327610SNicholas D Steeves 		 * Since we can unwind ebs we want to do a real search every
2975d4b4087cSJosef Bacik 		 * time.
2976d4b4087cSJosef Bacik 		 */
2977d4b4087cSJosef Bacik 		prev_cmp = -1;
2978d7396f07SFilipe David Borba Manana 		ret = key_search(b, key, level, &prev_cmp, &slot);
2979cbca7d59SFilipe Manana 		if (ret < 0)
2980cbca7d59SFilipe Manana 			goto done;
29815d9e75c4SJan Schmidt 
2982abe9339dSQu Wenruo 		if (level == 0) {
2983abe9339dSQu Wenruo 			p->slots[level] = slot;
2984abe9339dSQu Wenruo 			unlock_up(p, level, lowest_unlock, 0, NULL);
2985abe9339dSQu Wenruo 			goto done;
2986abe9339dSQu Wenruo 		}
2987abe9339dSQu Wenruo 
29885d9e75c4SJan Schmidt 		if (ret && slot > 0) {
29895d9e75c4SJan Schmidt 			dec = 1;
2990abe9339dSQu Wenruo 			slot--;
29915d9e75c4SJan Schmidt 		}
29925d9e75c4SJan Schmidt 		p->slots[level] = slot;
29935d9e75c4SJan Schmidt 		unlock_up(p, level, lowest_unlock, 0, NULL);
29945d9e75c4SJan Schmidt 
29955d9e75c4SJan Schmidt 		if (level == lowest_level) {
29965d9e75c4SJan Schmidt 			if (dec)
29975d9e75c4SJan Schmidt 				p->slots[level]++;
29985d9e75c4SJan Schmidt 			goto done;
29995d9e75c4SJan Schmidt 		}
30005d9e75c4SJan Schmidt 
3001abe9339dSQu Wenruo 		err = read_block_for_search(root, p, &b, level, slot, key);
30025d9e75c4SJan Schmidt 		if (err == -EAGAIN)
30035d9e75c4SJan Schmidt 			goto again;
30045d9e75c4SJan Schmidt 		if (err) {
30055d9e75c4SJan Schmidt 			ret = err;
30065d9e75c4SJan Schmidt 			goto done;
30075d9e75c4SJan Schmidt 		}
30085d9e75c4SJan Schmidt 
30095d9e75c4SJan Schmidt 		level = btrfs_header_level(b);
301065e99c43SNikolay Borisov 		if (!btrfs_tree_read_lock_atomic(b)) {
30115d9e75c4SJan Schmidt 			btrfs_set_path_blocking(p);
30125d9e75c4SJan Schmidt 			btrfs_tree_read_lock(b);
30135d9e75c4SJan Schmidt 		}
30140b246afaSJeff Mahoney 		b = tree_mod_log_rewind(fs_info, p, b, time_seq);
3015db7f3436SJosef Bacik 		if (!b) {
3016db7f3436SJosef Bacik 			ret = -ENOMEM;
3017db7f3436SJosef Bacik 			goto done;
3018db7f3436SJosef Bacik 		}
30195d9e75c4SJan Schmidt 		p->locks[level] = BTRFS_READ_LOCK;
30205d9e75c4SJan Schmidt 		p->nodes[level] = b;
30215d9e75c4SJan Schmidt 	}
30225d9e75c4SJan Schmidt 	ret = 1;
30235d9e75c4SJan Schmidt done:
30245d9e75c4SJan Schmidt 	if (!p->leave_spinning)
30255d9e75c4SJan Schmidt 		btrfs_set_path_blocking(p);
30265d9e75c4SJan Schmidt 	if (ret < 0)
30275d9e75c4SJan Schmidt 		btrfs_release_path(p);
30285d9e75c4SJan Schmidt 
30295d9e75c4SJan Schmidt 	return ret;
30305d9e75c4SJan Schmidt }
30315d9e75c4SJan Schmidt 
30325d9e75c4SJan Schmidt /*
30332f38b3e1SArne Jansen  * helper to use instead of search slot if no exact match is needed but
30342f38b3e1SArne Jansen  * instead the next or previous item should be returned.
30352f38b3e1SArne Jansen  * When find_higher is true, the next higher item is returned, the next lower
30362f38b3e1SArne Jansen  * otherwise.
30372f38b3e1SArne Jansen  * When return_any and find_higher are both true, and no higher item is found,
30382f38b3e1SArne Jansen  * return the next lower instead.
30392f38b3e1SArne Jansen  * When return_any is true and find_higher is false, and no lower item is found,
30402f38b3e1SArne Jansen  * return the next higher instead.
30412f38b3e1SArne Jansen  * It returns 0 if any item is found, 1 if none is found (tree empty), and
30422f38b3e1SArne Jansen  * < 0 on error
30432f38b3e1SArne Jansen  */
30442f38b3e1SArne Jansen int btrfs_search_slot_for_read(struct btrfs_root *root,
3045310712b2SOmar Sandoval 			       const struct btrfs_key *key,
3046310712b2SOmar Sandoval 			       struct btrfs_path *p, int find_higher,
3047310712b2SOmar Sandoval 			       int return_any)
30482f38b3e1SArne Jansen {
30492f38b3e1SArne Jansen 	int ret;
30502f38b3e1SArne Jansen 	struct extent_buffer *leaf;
30512f38b3e1SArne Jansen 
30522f38b3e1SArne Jansen again:
30532f38b3e1SArne Jansen 	ret = btrfs_search_slot(NULL, root, key, p, 0, 0);
30542f38b3e1SArne Jansen 	if (ret <= 0)
30552f38b3e1SArne Jansen 		return ret;
30562f38b3e1SArne Jansen 	/*
30572f38b3e1SArne Jansen 	 * a return value of 1 means the path is at the position where the
30582f38b3e1SArne Jansen 	 * item should be inserted. Normally this is the next bigger item,
30592f38b3e1SArne Jansen 	 * but in case the previous item is the last in a leaf, path points
30602f38b3e1SArne Jansen 	 * to the first free slot in the previous leaf, i.e. at an invalid
30612f38b3e1SArne Jansen 	 * item.
30622f38b3e1SArne Jansen 	 */
30632f38b3e1SArne Jansen 	leaf = p->nodes[0];
30642f38b3e1SArne Jansen 
30652f38b3e1SArne Jansen 	if (find_higher) {
30662f38b3e1SArne Jansen 		if (p->slots[0] >= btrfs_header_nritems(leaf)) {
30672f38b3e1SArne Jansen 			ret = btrfs_next_leaf(root, p);
30682f38b3e1SArne Jansen 			if (ret <= 0)
30692f38b3e1SArne Jansen 				return ret;
30702f38b3e1SArne Jansen 			if (!return_any)
30712f38b3e1SArne Jansen 				return 1;
30722f38b3e1SArne Jansen 			/*
30732f38b3e1SArne Jansen 			 * no higher item found, return the next
30742f38b3e1SArne Jansen 			 * lower instead
30752f38b3e1SArne Jansen 			 */
30762f38b3e1SArne Jansen 			return_any = 0;
30772f38b3e1SArne Jansen 			find_higher = 0;
30782f38b3e1SArne Jansen 			btrfs_release_path(p);
30792f38b3e1SArne Jansen 			goto again;
30802f38b3e1SArne Jansen 		}
30812f38b3e1SArne Jansen 	} else {
30822f38b3e1SArne Jansen 		if (p->slots[0] == 0) {
30832f38b3e1SArne Jansen 			ret = btrfs_prev_leaf(root, p);
3084e6793769SArne Jansen 			if (ret < 0)
30852f38b3e1SArne Jansen 				return ret;
3086e6793769SArne Jansen 			if (!ret) {
308723c6bf6aSFilipe David Borba Manana 				leaf = p->nodes[0];
308823c6bf6aSFilipe David Borba Manana 				if (p->slots[0] == btrfs_header_nritems(leaf))
308923c6bf6aSFilipe David Borba Manana 					p->slots[0]--;
3090e6793769SArne Jansen 				return 0;
3091e6793769SArne Jansen 			}
30922f38b3e1SArne Jansen 			if (!return_any)
30932f38b3e1SArne Jansen 				return 1;
30942f38b3e1SArne Jansen 			/*
30952f38b3e1SArne Jansen 			 * no lower item found, return the next
30962f38b3e1SArne Jansen 			 * higher instead
30972f38b3e1SArne Jansen 			 */
30982f38b3e1SArne Jansen 			return_any = 0;
30992f38b3e1SArne Jansen 			find_higher = 1;
31002f38b3e1SArne Jansen 			btrfs_release_path(p);
31012f38b3e1SArne Jansen 			goto again;
3102e6793769SArne Jansen 		} else {
31032f38b3e1SArne Jansen 			--p->slots[0];
31042f38b3e1SArne Jansen 		}
31052f38b3e1SArne Jansen 	}
31062f38b3e1SArne Jansen 	return 0;
31072f38b3e1SArne Jansen }
31082f38b3e1SArne Jansen 
31092f38b3e1SArne Jansen /*
311074123bd7SChris Mason  * adjust the pointers going up the tree, starting at level
311174123bd7SChris Mason  * making sure the right key of each node is points to 'key'.
311274123bd7SChris Mason  * This is used after shifting pointers to the left, so it stops
311374123bd7SChris Mason  * fixing up pointers when a given leaf/node is not in slot 0 of the
311474123bd7SChris Mason  * higher levels
3115aa5d6bedSChris Mason  *
311674123bd7SChris Mason  */
3117b167fa91SNikolay Borisov static void fixup_low_keys(struct btrfs_path *path,
31185f39d397SChris Mason 			   struct btrfs_disk_key *key, int level)
3119be0e5c09SChris Mason {
3120be0e5c09SChris Mason 	int i;
31215f39d397SChris Mason 	struct extent_buffer *t;
31220e82bcfeSDavid Sterba 	int ret;
31235f39d397SChris Mason 
3124234b63a0SChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
3125be0e5c09SChris Mason 		int tslot = path->slots[i];
31260e82bcfeSDavid Sterba 
3127eb60ceacSChris Mason 		if (!path->nodes[i])
3128be0e5c09SChris Mason 			break;
31295f39d397SChris Mason 		t = path->nodes[i];
31300e82bcfeSDavid Sterba 		ret = tree_mod_log_insert_key(t, tslot, MOD_LOG_KEY_REPLACE,
31310e82bcfeSDavid Sterba 				GFP_ATOMIC);
31320e82bcfeSDavid Sterba 		BUG_ON(ret < 0);
31335f39d397SChris Mason 		btrfs_set_node_key(t, key, tslot);
3134d6025579SChris Mason 		btrfs_mark_buffer_dirty(path->nodes[i]);
3135be0e5c09SChris Mason 		if (tslot != 0)
3136be0e5c09SChris Mason 			break;
3137be0e5c09SChris Mason 	}
3138be0e5c09SChris Mason }
3139be0e5c09SChris Mason 
314074123bd7SChris Mason /*
314131840ae1SZheng Yan  * update item key.
314231840ae1SZheng Yan  *
314331840ae1SZheng Yan  * This function isn't completely safe. It's the caller's responsibility
314431840ae1SZheng Yan  * that the new key won't break the order
314531840ae1SZheng Yan  */
3146b7a0365eSDaniel Dressler void btrfs_set_item_key_safe(struct btrfs_fs_info *fs_info,
3147b7a0365eSDaniel Dressler 			     struct btrfs_path *path,
3148310712b2SOmar Sandoval 			     const struct btrfs_key *new_key)
314931840ae1SZheng Yan {
315031840ae1SZheng Yan 	struct btrfs_disk_key disk_key;
315131840ae1SZheng Yan 	struct extent_buffer *eb;
315231840ae1SZheng Yan 	int slot;
315331840ae1SZheng Yan 
315431840ae1SZheng Yan 	eb = path->nodes[0];
315531840ae1SZheng Yan 	slot = path->slots[0];
315631840ae1SZheng Yan 	if (slot > 0) {
315731840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot - 1);
31587c15d410SQu Wenruo 		if (unlikely(comp_keys(&disk_key, new_key) >= 0)) {
31597c15d410SQu Wenruo 			btrfs_crit(fs_info,
31607c15d410SQu Wenruo 		"slot %u key (%llu %u %llu) new key (%llu %u %llu)",
31617c15d410SQu Wenruo 				   slot, btrfs_disk_key_objectid(&disk_key),
31627c15d410SQu Wenruo 				   btrfs_disk_key_type(&disk_key),
31637c15d410SQu Wenruo 				   btrfs_disk_key_offset(&disk_key),
31647c15d410SQu Wenruo 				   new_key->objectid, new_key->type,
31657c15d410SQu Wenruo 				   new_key->offset);
31667c15d410SQu Wenruo 			btrfs_print_leaf(eb);
31677c15d410SQu Wenruo 			BUG();
31687c15d410SQu Wenruo 		}
316931840ae1SZheng Yan 	}
317031840ae1SZheng Yan 	if (slot < btrfs_header_nritems(eb) - 1) {
317131840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot + 1);
31727c15d410SQu Wenruo 		if (unlikely(comp_keys(&disk_key, new_key) <= 0)) {
31737c15d410SQu Wenruo 			btrfs_crit(fs_info,
31747c15d410SQu Wenruo 		"slot %u key (%llu %u %llu) new key (%llu %u %llu)",
31757c15d410SQu Wenruo 				   slot, btrfs_disk_key_objectid(&disk_key),
31767c15d410SQu Wenruo 				   btrfs_disk_key_type(&disk_key),
31777c15d410SQu Wenruo 				   btrfs_disk_key_offset(&disk_key),
31787c15d410SQu Wenruo 				   new_key->objectid, new_key->type,
31797c15d410SQu Wenruo 				   new_key->offset);
31807c15d410SQu Wenruo 			btrfs_print_leaf(eb);
31817c15d410SQu Wenruo 			BUG();
31827c15d410SQu Wenruo 		}
318331840ae1SZheng Yan 	}
318431840ae1SZheng Yan 
318531840ae1SZheng Yan 	btrfs_cpu_key_to_disk(&disk_key, new_key);
318631840ae1SZheng Yan 	btrfs_set_item_key(eb, &disk_key, slot);
318731840ae1SZheng Yan 	btrfs_mark_buffer_dirty(eb);
318831840ae1SZheng Yan 	if (slot == 0)
3189b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, 1);
319031840ae1SZheng Yan }
319131840ae1SZheng Yan 
319231840ae1SZheng Yan /*
319374123bd7SChris Mason  * try to push data from one node into the next node left in the
319479f95c82SChris Mason  * tree.
3195aa5d6bedSChris Mason  *
3196aa5d6bedSChris Mason  * returns 0 if some ptrs were pushed left, < 0 if there was some horrible
3197aa5d6bedSChris Mason  * error, and > 0 if there was no room in the left hand block.
319874123bd7SChris Mason  */
319998ed5174SChris Mason static int push_node_left(struct btrfs_trans_handle *trans,
32002ff7e61eSJeff Mahoney 			  struct extent_buffer *dst,
3201971a1f66SChris Mason 			  struct extent_buffer *src, int empty)
3202be0e5c09SChris Mason {
3203d30a668fSDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
3204be0e5c09SChris Mason 	int push_items = 0;
3205bb803951SChris Mason 	int src_nritems;
3206bb803951SChris Mason 	int dst_nritems;
3207aa5d6bedSChris Mason 	int ret = 0;
3208be0e5c09SChris Mason 
32095f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
32105f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
32110b246afaSJeff Mahoney 	push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
32127bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
32137bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
321454aa1f4dSChris Mason 
3215bce4eae9SChris Mason 	if (!empty && src_nritems <= 8)
3216971a1f66SChris Mason 		return 1;
3217971a1f66SChris Mason 
3218d397712bSChris Mason 	if (push_items <= 0)
3219be0e5c09SChris Mason 		return 1;
3220be0e5c09SChris Mason 
3221bce4eae9SChris Mason 	if (empty) {
3222971a1f66SChris Mason 		push_items = min(src_nritems, push_items);
3223bce4eae9SChris Mason 		if (push_items < src_nritems) {
3224bce4eae9SChris Mason 			/* leave at least 8 pointers in the node if
3225bce4eae9SChris Mason 			 * we aren't going to empty it
3226bce4eae9SChris Mason 			 */
3227bce4eae9SChris Mason 			if (src_nritems - push_items < 8) {
3228bce4eae9SChris Mason 				if (push_items <= 8)
3229bce4eae9SChris Mason 					return 1;
3230bce4eae9SChris Mason 				push_items -= 8;
3231bce4eae9SChris Mason 			}
3232bce4eae9SChris Mason 		}
3233bce4eae9SChris Mason 	} else
3234bce4eae9SChris Mason 		push_items = min(src_nritems - 8, push_items);
323579f95c82SChris Mason 
3236ed874f0dSDavid Sterba 	ret = tree_mod_log_eb_copy(dst, src, dst_nritems, 0, push_items);
32375de865eeSFilipe David Borba Manana 	if (ret) {
323866642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
32395de865eeSFilipe David Borba Manana 		return ret;
32405de865eeSFilipe David Borba Manana 	}
32415f39d397SChris Mason 	copy_extent_buffer(dst, src,
32425f39d397SChris Mason 			   btrfs_node_key_ptr_offset(dst_nritems),
32435f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
3244123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
32455f39d397SChris Mason 
3246bb803951SChris Mason 	if (push_items < src_nritems) {
324757911b8bSJan Schmidt 		/*
3248bf1d3425SDavid Sterba 		 * Don't call tree_mod_log_insert_move here, key removal was
3249bf1d3425SDavid Sterba 		 * already fully logged by tree_mod_log_eb_copy above.
325057911b8bSJan Schmidt 		 */
32515f39d397SChris Mason 		memmove_extent_buffer(src, btrfs_node_key_ptr_offset(0),
32525f39d397SChris Mason 				      btrfs_node_key_ptr_offset(push_items),
3253e2fa7227SChris Mason 				      (src_nritems - push_items) *
3254123abc88SChris Mason 				      sizeof(struct btrfs_key_ptr));
3255bb803951SChris Mason 	}
32565f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
32575f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
32585f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
32595f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
326031840ae1SZheng Yan 
3261bb803951SChris Mason 	return ret;
3262be0e5c09SChris Mason }
3263be0e5c09SChris Mason 
326497571fd0SChris Mason /*
326579f95c82SChris Mason  * try to push data from one node into the next node right in the
326679f95c82SChris Mason  * tree.
326779f95c82SChris Mason  *
326879f95c82SChris Mason  * returns 0 if some ptrs were pushed, < 0 if there was some horrible
326979f95c82SChris Mason  * error, and > 0 if there was no room in the right hand block.
327079f95c82SChris Mason  *
327179f95c82SChris Mason  * this will  only push up to 1/2 the contents of the left node over
327279f95c82SChris Mason  */
32735f39d397SChris Mason static int balance_node_right(struct btrfs_trans_handle *trans,
32745f39d397SChris Mason 			      struct extent_buffer *dst,
32755f39d397SChris Mason 			      struct extent_buffer *src)
327679f95c82SChris Mason {
327755d32ed8SDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
327879f95c82SChris Mason 	int push_items = 0;
327979f95c82SChris Mason 	int max_push;
328079f95c82SChris Mason 	int src_nritems;
328179f95c82SChris Mason 	int dst_nritems;
328279f95c82SChris Mason 	int ret = 0;
328379f95c82SChris Mason 
32847bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
32857bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
32867bb86316SChris Mason 
32875f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
32885f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
32890b246afaSJeff Mahoney 	push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
3290d397712bSChris Mason 	if (push_items <= 0)
329179f95c82SChris Mason 		return 1;
3292bce4eae9SChris Mason 
3293d397712bSChris Mason 	if (src_nritems < 4)
3294bce4eae9SChris Mason 		return 1;
329579f95c82SChris Mason 
329679f95c82SChris Mason 	max_push = src_nritems / 2 + 1;
329779f95c82SChris Mason 	/* don't try to empty the node */
3298d397712bSChris Mason 	if (max_push >= src_nritems)
329979f95c82SChris Mason 		return 1;
3300252c38f0SYan 
330179f95c82SChris Mason 	if (max_push < push_items)
330279f95c82SChris Mason 		push_items = max_push;
330379f95c82SChris Mason 
3304bf1d3425SDavid Sterba 	ret = tree_mod_log_insert_move(dst, push_items, 0, dst_nritems);
3305bf1d3425SDavid Sterba 	BUG_ON(ret < 0);
33065f39d397SChris Mason 	memmove_extent_buffer(dst, btrfs_node_key_ptr_offset(push_items),
33075f39d397SChris Mason 				      btrfs_node_key_ptr_offset(0),
33085f39d397SChris Mason 				      (dst_nritems) *
33095f39d397SChris Mason 				      sizeof(struct btrfs_key_ptr));
3310d6025579SChris Mason 
3311ed874f0dSDavid Sterba 	ret = tree_mod_log_eb_copy(dst, src, 0, src_nritems - push_items,
3312ed874f0dSDavid Sterba 				   push_items);
33135de865eeSFilipe David Borba Manana 	if (ret) {
331466642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
33155de865eeSFilipe David Borba Manana 		return ret;
33165de865eeSFilipe David Borba Manana 	}
33175f39d397SChris Mason 	copy_extent_buffer(dst, src,
33185f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
33195f39d397SChris Mason 			   btrfs_node_key_ptr_offset(src_nritems - push_items),
3320123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
332179f95c82SChris Mason 
33225f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
33235f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
332479f95c82SChris Mason 
33255f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
33265f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
332731840ae1SZheng Yan 
332879f95c82SChris Mason 	return ret;
332979f95c82SChris Mason }
333079f95c82SChris Mason 
333179f95c82SChris Mason /*
333297571fd0SChris Mason  * helper function to insert a new root level in the tree.
333397571fd0SChris Mason  * A new node is allocated, and a single item is inserted to
333497571fd0SChris Mason  * point to the existing root
3335aa5d6bedSChris Mason  *
3336aa5d6bedSChris Mason  * returns zero on success or < 0 on failure.
333797571fd0SChris Mason  */
3338d397712bSChris Mason static noinline int insert_new_root(struct btrfs_trans_handle *trans,
33395f39d397SChris Mason 			   struct btrfs_root *root,
3340fdd99c72SLiu Bo 			   struct btrfs_path *path, int level)
334174123bd7SChris Mason {
33420b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
33437bb86316SChris Mason 	u64 lower_gen;
33445f39d397SChris Mason 	struct extent_buffer *lower;
33455f39d397SChris Mason 	struct extent_buffer *c;
3346925baeddSChris Mason 	struct extent_buffer *old;
33475f39d397SChris Mason 	struct btrfs_disk_key lower_key;
3348d9d19a01SDavid Sterba 	int ret;
33495c680ed6SChris Mason 
33505c680ed6SChris Mason 	BUG_ON(path->nodes[level]);
33515c680ed6SChris Mason 	BUG_ON(path->nodes[level-1] != root->node);
33525c680ed6SChris Mason 
33537bb86316SChris Mason 	lower = path->nodes[level-1];
33547bb86316SChris Mason 	if (level == 1)
33557bb86316SChris Mason 		btrfs_item_key(lower, &lower_key, 0);
33567bb86316SChris Mason 	else
33577bb86316SChris Mason 		btrfs_node_key(lower, &lower_key, 0);
33587bb86316SChris Mason 
3359a6279470SFilipe Manana 	c = alloc_tree_block_no_bg_flush(trans, root, 0, &lower_key, level,
3360a6279470SFilipe Manana 					 root->node->start, 0);
33615f39d397SChris Mason 	if (IS_ERR(c))
33625f39d397SChris Mason 		return PTR_ERR(c);
3363925baeddSChris Mason 
33640b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
3365f0486c68SYan, Zheng 
33665f39d397SChris Mason 	btrfs_set_header_nritems(c, 1);
33675f39d397SChris Mason 	btrfs_set_node_key(c, &lower_key, 0);
3368db94535dSChris Mason 	btrfs_set_node_blockptr(c, 0, lower->start);
33697bb86316SChris Mason 	lower_gen = btrfs_header_generation(lower);
337031840ae1SZheng Yan 	WARN_ON(lower_gen != trans->transid);
33717bb86316SChris Mason 
33727bb86316SChris Mason 	btrfs_set_node_ptr_generation(c, 0, lower_gen);
33735f39d397SChris Mason 
33745f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
3375d5719762SChris Mason 
3376925baeddSChris Mason 	old = root->node;
3377d9d19a01SDavid Sterba 	ret = tree_mod_log_insert_root(root->node, c, 0);
3378d9d19a01SDavid Sterba 	BUG_ON(ret < 0);
3379240f62c8SChris Mason 	rcu_assign_pointer(root->node, c);
3380925baeddSChris Mason 
3381925baeddSChris Mason 	/* the super has an extra ref to root->node */
3382925baeddSChris Mason 	free_extent_buffer(old);
3383925baeddSChris Mason 
33840b86a832SChris Mason 	add_root_to_dirty_list(root);
338567439dadSDavid Sterba 	atomic_inc(&c->refs);
33865f39d397SChris Mason 	path->nodes[level] = c;
338795449a16Schandan 	path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
338874123bd7SChris Mason 	path->slots[level] = 0;
338974123bd7SChris Mason 	return 0;
339074123bd7SChris Mason }
33915c680ed6SChris Mason 
33925c680ed6SChris Mason /*
33935c680ed6SChris Mason  * worker function to insert a single pointer in a node.
33945c680ed6SChris Mason  * the node should have enough room for the pointer already
339597571fd0SChris Mason  *
33965c680ed6SChris Mason  * slot and level indicate where you want the key to go, and
33975c680ed6SChris Mason  * blocknr is the block the key points to.
33985c680ed6SChris Mason  */
3399143bede5SJeff Mahoney static void insert_ptr(struct btrfs_trans_handle *trans,
34006ad3cf6dSDavid Sterba 		       struct btrfs_path *path,
3401143bede5SJeff Mahoney 		       struct btrfs_disk_key *key, u64 bytenr,
3402c3e06965SJan Schmidt 		       int slot, int level)
34035c680ed6SChris Mason {
34045f39d397SChris Mason 	struct extent_buffer *lower;
34055c680ed6SChris Mason 	int nritems;
3406f3ea38daSJan Schmidt 	int ret;
34075c680ed6SChris Mason 
34085c680ed6SChris Mason 	BUG_ON(!path->nodes[level]);
3409f0486c68SYan, Zheng 	btrfs_assert_tree_locked(path->nodes[level]);
34105f39d397SChris Mason 	lower = path->nodes[level];
34115f39d397SChris Mason 	nritems = btrfs_header_nritems(lower);
3412c293498bSStoyan Gaydarov 	BUG_ON(slot > nritems);
34136ad3cf6dSDavid Sterba 	BUG_ON(nritems == BTRFS_NODEPTRS_PER_BLOCK(trans->fs_info));
341474123bd7SChris Mason 	if (slot != nritems) {
3415bf1d3425SDavid Sterba 		if (level) {
3416bf1d3425SDavid Sterba 			ret = tree_mod_log_insert_move(lower, slot + 1, slot,
3417a446a979SDavid Sterba 					nritems - slot);
3418bf1d3425SDavid Sterba 			BUG_ON(ret < 0);
3419bf1d3425SDavid Sterba 		}
34205f39d397SChris Mason 		memmove_extent_buffer(lower,
34215f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot + 1),
34225f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot),
3423123abc88SChris Mason 			      (nritems - slot) * sizeof(struct btrfs_key_ptr));
342474123bd7SChris Mason 	}
3425c3e06965SJan Schmidt 	if (level) {
3426e09c2efeSDavid Sterba 		ret = tree_mod_log_insert_key(lower, slot, MOD_LOG_KEY_ADD,
3427e09c2efeSDavid Sterba 				GFP_NOFS);
3428f3ea38daSJan Schmidt 		BUG_ON(ret < 0);
3429f3ea38daSJan Schmidt 	}
34305f39d397SChris Mason 	btrfs_set_node_key(lower, key, slot);
3431db94535dSChris Mason 	btrfs_set_node_blockptr(lower, slot, bytenr);
343274493f7aSChris Mason 	WARN_ON(trans->transid == 0);
343374493f7aSChris Mason 	btrfs_set_node_ptr_generation(lower, slot, trans->transid);
34345f39d397SChris Mason 	btrfs_set_header_nritems(lower, nritems + 1);
34355f39d397SChris Mason 	btrfs_mark_buffer_dirty(lower);
343674123bd7SChris Mason }
343774123bd7SChris Mason 
343897571fd0SChris Mason /*
343997571fd0SChris Mason  * split the node at the specified level in path in two.
344097571fd0SChris Mason  * The path is corrected to point to the appropriate node after the split
344197571fd0SChris Mason  *
344297571fd0SChris Mason  * Before splitting this tries to make some room in the node by pushing
344397571fd0SChris Mason  * left and right, if either one works, it returns right away.
3444aa5d6bedSChris Mason  *
3445aa5d6bedSChris Mason  * returns 0 on success and < 0 on failure
344697571fd0SChris Mason  */
3447e02119d5SChris Mason static noinline int split_node(struct btrfs_trans_handle *trans,
3448e02119d5SChris Mason 			       struct btrfs_root *root,
3449e02119d5SChris Mason 			       struct btrfs_path *path, int level)
3450be0e5c09SChris Mason {
34510b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
34525f39d397SChris Mason 	struct extent_buffer *c;
34535f39d397SChris Mason 	struct extent_buffer *split;
34545f39d397SChris Mason 	struct btrfs_disk_key disk_key;
3455be0e5c09SChris Mason 	int mid;
34565c680ed6SChris Mason 	int ret;
34577518a238SChris Mason 	u32 c_nritems;
3458be0e5c09SChris Mason 
34595f39d397SChris Mason 	c = path->nodes[level];
34607bb86316SChris Mason 	WARN_ON(btrfs_header_generation(c) != trans->transid);
34615f39d397SChris Mason 	if (c == root->node) {
3462d9abbf1cSJan Schmidt 		/*
346390f8d62eSJan Schmidt 		 * trying to split the root, lets make a new one
346490f8d62eSJan Schmidt 		 *
3465fdd99c72SLiu Bo 		 * tree mod log: We don't log_removal old root in
346690f8d62eSJan Schmidt 		 * insert_new_root, because that root buffer will be kept as a
346790f8d62eSJan Schmidt 		 * normal node. We are going to log removal of half of the
346890f8d62eSJan Schmidt 		 * elements below with tree_mod_log_eb_copy. We're holding a
346990f8d62eSJan Schmidt 		 * tree lock on the buffer, which is why we cannot race with
347090f8d62eSJan Schmidt 		 * other tree_mod_log users.
3471d9abbf1cSJan Schmidt 		 */
3472fdd99c72SLiu Bo 		ret = insert_new_root(trans, root, path, level + 1);
34735c680ed6SChris Mason 		if (ret)
34745c680ed6SChris Mason 			return ret;
3475b3612421SChris Mason 	} else {
3476e66f709bSChris Mason 		ret = push_nodes_for_insert(trans, root, path, level);
34775f39d397SChris Mason 		c = path->nodes[level];
34785f39d397SChris Mason 		if (!ret && btrfs_header_nritems(c) <
34790b246afaSJeff Mahoney 		    BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3)
3480e66f709bSChris Mason 			return 0;
348154aa1f4dSChris Mason 		if (ret < 0)
348254aa1f4dSChris Mason 			return ret;
34835c680ed6SChris Mason 	}
3484e66f709bSChris Mason 
34855f39d397SChris Mason 	c_nritems = btrfs_header_nritems(c);
34865d4f98a2SYan Zheng 	mid = (c_nritems + 1) / 2;
34875d4f98a2SYan Zheng 	btrfs_node_key(c, &disk_key, mid);
34887bb86316SChris Mason 
3489a6279470SFilipe Manana 	split = alloc_tree_block_no_bg_flush(trans, root, 0, &disk_key, level,
3490a6279470SFilipe Manana 					     c->start, 0);
34915f39d397SChris Mason 	if (IS_ERR(split))
34925f39d397SChris Mason 		return PTR_ERR(split);
349354aa1f4dSChris Mason 
34940b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
3495bc877d28SNikolay Borisov 	ASSERT(btrfs_header_level(c) == level);
34965f39d397SChris Mason 
3497ed874f0dSDavid Sterba 	ret = tree_mod_log_eb_copy(split, c, 0, mid, c_nritems - mid);
34985de865eeSFilipe David Borba Manana 	if (ret) {
349966642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
35005de865eeSFilipe David Borba Manana 		return ret;
35015de865eeSFilipe David Borba Manana 	}
35025f39d397SChris Mason 	copy_extent_buffer(split, c,
35035f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
35045f39d397SChris Mason 			   btrfs_node_key_ptr_offset(mid),
3505123abc88SChris Mason 			   (c_nritems - mid) * sizeof(struct btrfs_key_ptr));
35065f39d397SChris Mason 	btrfs_set_header_nritems(split, c_nritems - mid);
35075f39d397SChris Mason 	btrfs_set_header_nritems(c, mid);
3508aa5d6bedSChris Mason 	ret = 0;
3509aa5d6bedSChris Mason 
35105f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
35115f39d397SChris Mason 	btrfs_mark_buffer_dirty(split);
35125f39d397SChris Mason 
35136ad3cf6dSDavid Sterba 	insert_ptr(trans, path, &disk_key, split->start,
3514c3e06965SJan Schmidt 		   path->slots[level + 1] + 1, level + 1);
3515aa5d6bedSChris Mason 
35165de08d7dSChris Mason 	if (path->slots[level] >= mid) {
35175c680ed6SChris Mason 		path->slots[level] -= mid;
3518925baeddSChris Mason 		btrfs_tree_unlock(c);
35195f39d397SChris Mason 		free_extent_buffer(c);
35205f39d397SChris Mason 		path->nodes[level] = split;
35215c680ed6SChris Mason 		path->slots[level + 1] += 1;
3522eb60ceacSChris Mason 	} else {
3523925baeddSChris Mason 		btrfs_tree_unlock(split);
35245f39d397SChris Mason 		free_extent_buffer(split);
3525be0e5c09SChris Mason 	}
3526aa5d6bedSChris Mason 	return ret;
3527be0e5c09SChris Mason }
3528be0e5c09SChris Mason 
352974123bd7SChris Mason /*
353074123bd7SChris Mason  * how many bytes are required to store the items in a leaf.  start
353174123bd7SChris Mason  * and nr indicate which items in the leaf to check.  This totals up the
353274123bd7SChris Mason  * space used both by the item structs and the item data
353374123bd7SChris Mason  */
35345f39d397SChris Mason static int leaf_space_used(struct extent_buffer *l, int start, int nr)
3535be0e5c09SChris Mason {
353641be1f3bSJosef Bacik 	struct btrfs_item *start_item;
353741be1f3bSJosef Bacik 	struct btrfs_item *end_item;
353841be1f3bSJosef Bacik 	struct btrfs_map_token token;
3539be0e5c09SChris Mason 	int data_len;
35405f39d397SChris Mason 	int nritems = btrfs_header_nritems(l);
3541d4dbff95SChris Mason 	int end = min(nritems, start + nr) - 1;
3542be0e5c09SChris Mason 
3543be0e5c09SChris Mason 	if (!nr)
3544be0e5c09SChris Mason 		return 0;
3545c82f823cSDavid Sterba 	btrfs_init_map_token(&token, l);
3546dd3cc16bSRoss Kirk 	start_item = btrfs_item_nr(start);
3547dd3cc16bSRoss Kirk 	end_item = btrfs_item_nr(end);
354841be1f3bSJosef Bacik 	data_len = btrfs_token_item_offset(l, start_item, &token) +
354941be1f3bSJosef Bacik 		btrfs_token_item_size(l, start_item, &token);
355041be1f3bSJosef Bacik 	data_len = data_len - btrfs_token_item_offset(l, end_item, &token);
35510783fcfcSChris Mason 	data_len += sizeof(struct btrfs_item) * nr;
3552d4dbff95SChris Mason 	WARN_ON(data_len < 0);
3553be0e5c09SChris Mason 	return data_len;
3554be0e5c09SChris Mason }
3555be0e5c09SChris Mason 
355674123bd7SChris Mason /*
3557d4dbff95SChris Mason  * The space between the end of the leaf items and
3558d4dbff95SChris Mason  * the start of the leaf data.  IOW, how much room
3559d4dbff95SChris Mason  * the leaf has left for both items and data
3560d4dbff95SChris Mason  */
3561e902baacSDavid Sterba noinline int btrfs_leaf_free_space(struct extent_buffer *leaf)
3562d4dbff95SChris Mason {
3563e902baacSDavid Sterba 	struct btrfs_fs_info *fs_info = leaf->fs_info;
35645f39d397SChris Mason 	int nritems = btrfs_header_nritems(leaf);
35655f39d397SChris Mason 	int ret;
35660b246afaSJeff Mahoney 
35670b246afaSJeff Mahoney 	ret = BTRFS_LEAF_DATA_SIZE(fs_info) - leaf_space_used(leaf, 0, nritems);
35685f39d397SChris Mason 	if (ret < 0) {
35690b246afaSJeff Mahoney 		btrfs_crit(fs_info,
3570efe120a0SFrank Holton 			   "leaf free space ret %d, leaf data size %lu, used %d nritems %d",
3571da17066cSJeff Mahoney 			   ret,
35720b246afaSJeff Mahoney 			   (unsigned long) BTRFS_LEAF_DATA_SIZE(fs_info),
35735f39d397SChris Mason 			   leaf_space_used(leaf, 0, nritems), nritems);
35745f39d397SChris Mason 	}
35755f39d397SChris Mason 	return ret;
3576d4dbff95SChris Mason }
3577d4dbff95SChris Mason 
357899d8f83cSChris Mason /*
357999d8f83cSChris Mason  * min slot controls the lowest index we're willing to push to the
358099d8f83cSChris Mason  * right.  We'll push up to and including min_slot, but no lower
358199d8f83cSChris Mason  */
3582f72f0010SDavid Sterba static noinline int __push_leaf_right(struct btrfs_path *path,
358344871b1bSChris Mason 				      int data_size, int empty,
358444871b1bSChris Mason 				      struct extent_buffer *right,
358599d8f83cSChris Mason 				      int free_space, u32 left_nritems,
358699d8f83cSChris Mason 				      u32 min_slot)
358700ec4c51SChris Mason {
3588f72f0010SDavid Sterba 	struct btrfs_fs_info *fs_info = right->fs_info;
35895f39d397SChris Mason 	struct extent_buffer *left = path->nodes[0];
359044871b1bSChris Mason 	struct extent_buffer *upper = path->nodes[1];
3591cfed81a0SChris Mason 	struct btrfs_map_token token;
35925f39d397SChris Mason 	struct btrfs_disk_key disk_key;
359300ec4c51SChris Mason 	int slot;
359434a38218SChris Mason 	u32 i;
359500ec4c51SChris Mason 	int push_space = 0;
359600ec4c51SChris Mason 	int push_items = 0;
35970783fcfcSChris Mason 	struct btrfs_item *item;
359834a38218SChris Mason 	u32 nr;
35997518a238SChris Mason 	u32 right_nritems;
36005f39d397SChris Mason 	u32 data_end;
3601db94535dSChris Mason 	u32 this_item_size;
360200ec4c51SChris Mason 
360334a38218SChris Mason 	if (empty)
360434a38218SChris Mason 		nr = 0;
360534a38218SChris Mason 	else
360699d8f83cSChris Mason 		nr = max_t(u32, 1, min_slot);
360734a38218SChris Mason 
360831840ae1SZheng Yan 	if (path->slots[0] >= left_nritems)
360987b29b20SYan Zheng 		push_space += data_size;
361031840ae1SZheng Yan 
361144871b1bSChris Mason 	slot = path->slots[1];
361234a38218SChris Mason 	i = left_nritems - 1;
361334a38218SChris Mason 	while (i >= nr) {
3614dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
3615db94535dSChris Mason 
361631840ae1SZheng Yan 		if (!empty && push_items > 0) {
361731840ae1SZheng Yan 			if (path->slots[0] > i)
361831840ae1SZheng Yan 				break;
361931840ae1SZheng Yan 			if (path->slots[0] == i) {
3620e902baacSDavid Sterba 				int space = btrfs_leaf_free_space(left);
3621e902baacSDavid Sterba 
362231840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
362331840ae1SZheng Yan 					break;
362431840ae1SZheng Yan 			}
362531840ae1SZheng Yan 		}
362631840ae1SZheng Yan 
362700ec4c51SChris Mason 		if (path->slots[0] == i)
362887b29b20SYan Zheng 			push_space += data_size;
3629db94535dSChris Mason 
3630db94535dSChris Mason 		this_item_size = btrfs_item_size(left, item);
3631db94535dSChris Mason 		if (this_item_size + sizeof(*item) + push_space > free_space)
363200ec4c51SChris Mason 			break;
363331840ae1SZheng Yan 
363400ec4c51SChris Mason 		push_items++;
3635db94535dSChris Mason 		push_space += this_item_size + sizeof(*item);
363634a38218SChris Mason 		if (i == 0)
363734a38218SChris Mason 			break;
363834a38218SChris Mason 		i--;
3639db94535dSChris Mason 	}
36405f39d397SChris Mason 
3641925baeddSChris Mason 	if (push_items == 0)
3642925baeddSChris Mason 		goto out_unlock;
36435f39d397SChris Mason 
36446c1500f2SJulia Lawall 	WARN_ON(!empty && push_items == left_nritems);
36455f39d397SChris Mason 
364600ec4c51SChris Mason 	/* push left to right */
36475f39d397SChris Mason 	right_nritems = btrfs_header_nritems(right);
364834a38218SChris Mason 
36495f39d397SChris Mason 	push_space = btrfs_item_end_nr(left, left_nritems - push_items);
36508f881e8cSDavid Sterba 	push_space -= leaf_data_end(left);
36515f39d397SChris Mason 
365200ec4c51SChris Mason 	/* make room in the right data area */
36538f881e8cSDavid Sterba 	data_end = leaf_data_end(right);
36545f39d397SChris Mason 	memmove_extent_buffer(right,
36553d9ec8c4SNikolay Borisov 			      BTRFS_LEAF_DATA_OFFSET + data_end - push_space,
36563d9ec8c4SNikolay Borisov 			      BTRFS_LEAF_DATA_OFFSET + data_end,
36570b246afaSJeff Mahoney 			      BTRFS_LEAF_DATA_SIZE(fs_info) - data_end);
36585f39d397SChris Mason 
365900ec4c51SChris Mason 	/* copy from the left data area */
36603d9ec8c4SNikolay Borisov 	copy_extent_buffer(right, left, BTRFS_LEAF_DATA_OFFSET +
36610b246afaSJeff Mahoney 		     BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
36628f881e8cSDavid Sterba 		     BTRFS_LEAF_DATA_OFFSET + leaf_data_end(left),
3663d6025579SChris Mason 		     push_space);
36645f39d397SChris Mason 
36655f39d397SChris Mason 	memmove_extent_buffer(right, btrfs_item_nr_offset(push_items),
36665f39d397SChris Mason 			      btrfs_item_nr_offset(0),
36670783fcfcSChris Mason 			      right_nritems * sizeof(struct btrfs_item));
36685f39d397SChris Mason 
366900ec4c51SChris Mason 	/* copy the items from left to right */
36705f39d397SChris Mason 	copy_extent_buffer(right, left, btrfs_item_nr_offset(0),
36715f39d397SChris Mason 		   btrfs_item_nr_offset(left_nritems - push_items),
36720783fcfcSChris Mason 		   push_items * sizeof(struct btrfs_item));
367300ec4c51SChris Mason 
367400ec4c51SChris Mason 	/* update the item pointers */
3675c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
36767518a238SChris Mason 	right_nritems += push_items;
36775f39d397SChris Mason 	btrfs_set_header_nritems(right, right_nritems);
36780b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
36797518a238SChris Mason 	for (i = 0; i < right_nritems; i++) {
3680dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
3681cfed81a0SChris Mason 		push_space -= btrfs_token_item_size(right, item, &token);
3682cfed81a0SChris Mason 		btrfs_set_token_item_offset(right, item, push_space, &token);
3683db94535dSChris Mason 	}
3684db94535dSChris Mason 
36857518a238SChris Mason 	left_nritems -= push_items;
36865f39d397SChris Mason 	btrfs_set_header_nritems(left, left_nritems);
368700ec4c51SChris Mason 
368834a38218SChris Mason 	if (left_nritems)
36895f39d397SChris Mason 		btrfs_mark_buffer_dirty(left);
3690f0486c68SYan, Zheng 	else
36916a884d7dSDavid Sterba 		btrfs_clean_tree_block(left);
3692f0486c68SYan, Zheng 
36935f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
3694a429e513SChris Mason 
36955f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
36965f39d397SChris Mason 	btrfs_set_node_key(upper, &disk_key, slot + 1);
3697d6025579SChris Mason 	btrfs_mark_buffer_dirty(upper);
369802217ed2SChris Mason 
369900ec4c51SChris Mason 	/* then fixup the leaf pointer in the path */
37007518a238SChris Mason 	if (path->slots[0] >= left_nritems) {
37017518a238SChris Mason 		path->slots[0] -= left_nritems;
3702925baeddSChris Mason 		if (btrfs_header_nritems(path->nodes[0]) == 0)
37036a884d7dSDavid Sterba 			btrfs_clean_tree_block(path->nodes[0]);
3704925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
37055f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
37065f39d397SChris Mason 		path->nodes[0] = right;
370700ec4c51SChris Mason 		path->slots[1] += 1;
370800ec4c51SChris Mason 	} else {
3709925baeddSChris Mason 		btrfs_tree_unlock(right);
37105f39d397SChris Mason 		free_extent_buffer(right);
371100ec4c51SChris Mason 	}
371200ec4c51SChris Mason 	return 0;
3713925baeddSChris Mason 
3714925baeddSChris Mason out_unlock:
3715925baeddSChris Mason 	btrfs_tree_unlock(right);
3716925baeddSChris Mason 	free_extent_buffer(right);
3717925baeddSChris Mason 	return 1;
371800ec4c51SChris Mason }
3719925baeddSChris Mason 
372000ec4c51SChris Mason /*
372144871b1bSChris Mason  * push some data in the path leaf to the right, trying to free up at
372274123bd7SChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
372344871b1bSChris Mason  *
372444871b1bSChris Mason  * returns 1 if the push failed because the other node didn't have enough
372544871b1bSChris Mason  * room, 0 if everything worked out and < 0 if there were major errors.
372699d8f83cSChris Mason  *
372799d8f83cSChris Mason  * this will push starting from min_slot to the end of the leaf.  It won't
372899d8f83cSChris Mason  * push any slot lower than min_slot
372974123bd7SChris Mason  */
373044871b1bSChris Mason static int push_leaf_right(struct btrfs_trans_handle *trans, struct btrfs_root
373199d8f83cSChris Mason 			   *root, struct btrfs_path *path,
373299d8f83cSChris Mason 			   int min_data_size, int data_size,
373399d8f83cSChris Mason 			   int empty, u32 min_slot)
3734be0e5c09SChris Mason {
373544871b1bSChris Mason 	struct extent_buffer *left = path->nodes[0];
373644871b1bSChris Mason 	struct extent_buffer *right;
373744871b1bSChris Mason 	struct extent_buffer *upper;
373844871b1bSChris Mason 	int slot;
373944871b1bSChris Mason 	int free_space;
374044871b1bSChris Mason 	u32 left_nritems;
374144871b1bSChris Mason 	int ret;
374244871b1bSChris Mason 
374344871b1bSChris Mason 	if (!path->nodes[1])
374444871b1bSChris Mason 		return 1;
374544871b1bSChris Mason 
374644871b1bSChris Mason 	slot = path->slots[1];
374744871b1bSChris Mason 	upper = path->nodes[1];
374844871b1bSChris Mason 	if (slot >= btrfs_header_nritems(upper) - 1)
374944871b1bSChris Mason 		return 1;
375044871b1bSChris Mason 
375144871b1bSChris Mason 	btrfs_assert_tree_locked(path->nodes[1]);
375244871b1bSChris Mason 
37534b231ae4SDavid Sterba 	right = btrfs_read_node_slot(upper, slot + 1);
3754fb770ae4SLiu Bo 	/*
3755fb770ae4SLiu Bo 	 * slot + 1 is not valid or we fail to read the right node,
3756fb770ae4SLiu Bo 	 * no big deal, just return.
3757fb770ae4SLiu Bo 	 */
3758fb770ae4SLiu Bo 	if (IS_ERR(right))
375991ca338dSTsutomu Itoh 		return 1;
376091ca338dSTsutomu Itoh 
376144871b1bSChris Mason 	btrfs_tree_lock(right);
37628bead258SDavid Sterba 	btrfs_set_lock_blocking_write(right);
376344871b1bSChris Mason 
3764e902baacSDavid Sterba 	free_space = btrfs_leaf_free_space(right);
376544871b1bSChris Mason 	if (free_space < data_size)
376644871b1bSChris Mason 		goto out_unlock;
376744871b1bSChris Mason 
376844871b1bSChris Mason 	/* cow and double check */
376944871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, right, upper,
377044871b1bSChris Mason 			      slot + 1, &right);
377144871b1bSChris Mason 	if (ret)
377244871b1bSChris Mason 		goto out_unlock;
377344871b1bSChris Mason 
3774e902baacSDavid Sterba 	free_space = btrfs_leaf_free_space(right);
377544871b1bSChris Mason 	if (free_space < data_size)
377644871b1bSChris Mason 		goto out_unlock;
377744871b1bSChris Mason 
377844871b1bSChris Mason 	left_nritems = btrfs_header_nritems(left);
377944871b1bSChris Mason 	if (left_nritems == 0)
378044871b1bSChris Mason 		goto out_unlock;
378144871b1bSChris Mason 
37822ef1fed2SFilipe David Borba Manana 	if (path->slots[0] == left_nritems && !empty) {
37832ef1fed2SFilipe David Borba Manana 		/* Key greater than all keys in the leaf, right neighbor has
37842ef1fed2SFilipe David Borba Manana 		 * enough room for it and we're not emptying our leaf to delete
37852ef1fed2SFilipe David Borba Manana 		 * it, therefore use right neighbor to insert the new item and
378652042d8eSAndrea Gelmini 		 * no need to touch/dirty our left leaf. */
37872ef1fed2SFilipe David Borba Manana 		btrfs_tree_unlock(left);
37882ef1fed2SFilipe David Borba Manana 		free_extent_buffer(left);
37892ef1fed2SFilipe David Borba Manana 		path->nodes[0] = right;
37902ef1fed2SFilipe David Borba Manana 		path->slots[0] = 0;
37912ef1fed2SFilipe David Borba Manana 		path->slots[1]++;
37922ef1fed2SFilipe David Borba Manana 		return 0;
37932ef1fed2SFilipe David Borba Manana 	}
37942ef1fed2SFilipe David Borba Manana 
3795f72f0010SDavid Sterba 	return __push_leaf_right(path, min_data_size, empty,
379699d8f83cSChris Mason 				right, free_space, left_nritems, min_slot);
379744871b1bSChris Mason out_unlock:
379844871b1bSChris Mason 	btrfs_tree_unlock(right);
379944871b1bSChris Mason 	free_extent_buffer(right);
380044871b1bSChris Mason 	return 1;
380144871b1bSChris Mason }
380244871b1bSChris Mason 
380344871b1bSChris Mason /*
380444871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
380544871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
380699d8f83cSChris Mason  *
380799d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
380899d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us do all the
380999d8f83cSChris Mason  * items
381044871b1bSChris Mason  */
38118087c193SDavid Sterba static noinline int __push_leaf_left(struct btrfs_path *path, int data_size,
381244871b1bSChris Mason 				     int empty, struct extent_buffer *left,
381399d8f83cSChris Mason 				     int free_space, u32 right_nritems,
381499d8f83cSChris Mason 				     u32 max_slot)
381544871b1bSChris Mason {
38168087c193SDavid Sterba 	struct btrfs_fs_info *fs_info = left->fs_info;
38175f39d397SChris Mason 	struct btrfs_disk_key disk_key;
38185f39d397SChris Mason 	struct extent_buffer *right = path->nodes[0];
3819be0e5c09SChris Mason 	int i;
3820be0e5c09SChris Mason 	int push_space = 0;
3821be0e5c09SChris Mason 	int push_items = 0;
38220783fcfcSChris Mason 	struct btrfs_item *item;
38237518a238SChris Mason 	u32 old_left_nritems;
382434a38218SChris Mason 	u32 nr;
3825aa5d6bedSChris Mason 	int ret = 0;
3826db94535dSChris Mason 	u32 this_item_size;
3827db94535dSChris Mason 	u32 old_left_item_size;
3828cfed81a0SChris Mason 	struct btrfs_map_token token;
3829cfed81a0SChris Mason 
383034a38218SChris Mason 	if (empty)
383199d8f83cSChris Mason 		nr = min(right_nritems, max_slot);
383234a38218SChris Mason 	else
383399d8f83cSChris Mason 		nr = min(right_nritems - 1, max_slot);
383434a38218SChris Mason 
383534a38218SChris Mason 	for (i = 0; i < nr; i++) {
3836dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
3837db94535dSChris Mason 
383831840ae1SZheng Yan 		if (!empty && push_items > 0) {
383931840ae1SZheng Yan 			if (path->slots[0] < i)
384031840ae1SZheng Yan 				break;
384131840ae1SZheng Yan 			if (path->slots[0] == i) {
3842e902baacSDavid Sterba 				int space = btrfs_leaf_free_space(right);
3843e902baacSDavid Sterba 
384431840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
384531840ae1SZheng Yan 					break;
384631840ae1SZheng Yan 			}
384731840ae1SZheng Yan 		}
384831840ae1SZheng Yan 
3849be0e5c09SChris Mason 		if (path->slots[0] == i)
385087b29b20SYan Zheng 			push_space += data_size;
3851db94535dSChris Mason 
3852db94535dSChris Mason 		this_item_size = btrfs_item_size(right, item);
3853db94535dSChris Mason 		if (this_item_size + sizeof(*item) + push_space > free_space)
3854be0e5c09SChris Mason 			break;
3855db94535dSChris Mason 
3856be0e5c09SChris Mason 		push_items++;
3857db94535dSChris Mason 		push_space += this_item_size + sizeof(*item);
3858be0e5c09SChris Mason 	}
3859db94535dSChris Mason 
3860be0e5c09SChris Mason 	if (push_items == 0) {
3861925baeddSChris Mason 		ret = 1;
3862925baeddSChris Mason 		goto out;
3863be0e5c09SChris Mason 	}
3864fae7f21cSDulshani Gunawardhana 	WARN_ON(!empty && push_items == btrfs_header_nritems(right));
38655f39d397SChris Mason 
3866be0e5c09SChris Mason 	/* push data from right to left */
38675f39d397SChris Mason 	copy_extent_buffer(left, right,
38685f39d397SChris Mason 			   btrfs_item_nr_offset(btrfs_header_nritems(left)),
38695f39d397SChris Mason 			   btrfs_item_nr_offset(0),
38705f39d397SChris Mason 			   push_items * sizeof(struct btrfs_item));
38715f39d397SChris Mason 
38720b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info) -
38735f39d397SChris Mason 		     btrfs_item_offset_nr(right, push_items - 1);
38745f39d397SChris Mason 
38753d9ec8c4SNikolay Borisov 	copy_extent_buffer(left, right, BTRFS_LEAF_DATA_OFFSET +
38768f881e8cSDavid Sterba 		     leaf_data_end(left) - push_space,
38773d9ec8c4SNikolay Borisov 		     BTRFS_LEAF_DATA_OFFSET +
38785f39d397SChris Mason 		     btrfs_item_offset_nr(right, push_items - 1),
3879be0e5c09SChris Mason 		     push_space);
38805f39d397SChris Mason 	old_left_nritems = btrfs_header_nritems(left);
388187b29b20SYan Zheng 	BUG_ON(old_left_nritems <= 0);
3882eb60ceacSChris Mason 
3883c82f823cSDavid Sterba 	btrfs_init_map_token(&token, left);
3884db94535dSChris Mason 	old_left_item_size = btrfs_item_offset_nr(left, old_left_nritems - 1);
3885be0e5c09SChris Mason 	for (i = old_left_nritems; i < old_left_nritems + push_items; i++) {
38865f39d397SChris Mason 		u32 ioff;
3887db94535dSChris Mason 
3888dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
3889db94535dSChris Mason 
3890cfed81a0SChris Mason 		ioff = btrfs_token_item_offset(left, item, &token);
3891cfed81a0SChris Mason 		btrfs_set_token_item_offset(left, item,
38920b246afaSJeff Mahoney 		      ioff - (BTRFS_LEAF_DATA_SIZE(fs_info) - old_left_item_size),
3893cfed81a0SChris Mason 		      &token);
3894be0e5c09SChris Mason 	}
38955f39d397SChris Mason 	btrfs_set_header_nritems(left, old_left_nritems + push_items);
3896be0e5c09SChris Mason 
3897be0e5c09SChris Mason 	/* fixup right node */
389831b1a2bdSJulia Lawall 	if (push_items > right_nritems)
389931b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "push items %d nr %u\n", push_items,
3900d397712bSChris Mason 		       right_nritems);
390134a38218SChris Mason 
390234a38218SChris Mason 	if (push_items < right_nritems) {
39035f39d397SChris Mason 		push_space = btrfs_item_offset_nr(right, push_items - 1) -
39048f881e8cSDavid Sterba 						  leaf_data_end(right);
39053d9ec8c4SNikolay Borisov 		memmove_extent_buffer(right, BTRFS_LEAF_DATA_OFFSET +
39060b246afaSJeff Mahoney 				      BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
39073d9ec8c4SNikolay Borisov 				      BTRFS_LEAF_DATA_OFFSET +
39088f881e8cSDavid Sterba 				      leaf_data_end(right), push_space);
39095f39d397SChris Mason 
39105f39d397SChris Mason 		memmove_extent_buffer(right, btrfs_item_nr_offset(0),
39115f39d397SChris Mason 			      btrfs_item_nr_offset(push_items),
39125f39d397SChris Mason 			     (btrfs_header_nritems(right) - push_items) *
39130783fcfcSChris Mason 			     sizeof(struct btrfs_item));
391434a38218SChris Mason 	}
3915c82f823cSDavid Sterba 
3916c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
3917eef1c494SYan 	right_nritems -= push_items;
3918eef1c494SYan 	btrfs_set_header_nritems(right, right_nritems);
39190b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
39205f39d397SChris Mason 	for (i = 0; i < right_nritems; i++) {
3921dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
3922db94535dSChris Mason 
3923cfed81a0SChris Mason 		push_space = push_space - btrfs_token_item_size(right,
3924cfed81a0SChris Mason 								item, &token);
3925cfed81a0SChris Mason 		btrfs_set_token_item_offset(right, item, push_space, &token);
3926db94535dSChris Mason 	}
3927eb60ceacSChris Mason 
39285f39d397SChris Mason 	btrfs_mark_buffer_dirty(left);
392934a38218SChris Mason 	if (right_nritems)
39305f39d397SChris Mason 		btrfs_mark_buffer_dirty(right);
3931f0486c68SYan, Zheng 	else
39326a884d7dSDavid Sterba 		btrfs_clean_tree_block(right);
3933098f59c2SChris Mason 
39345f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
3935b167fa91SNikolay Borisov 	fixup_low_keys(path, &disk_key, 1);
3936be0e5c09SChris Mason 
3937be0e5c09SChris Mason 	/* then fixup the leaf pointer in the path */
3938be0e5c09SChris Mason 	if (path->slots[0] < push_items) {
3939be0e5c09SChris Mason 		path->slots[0] += old_left_nritems;
3940925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
39415f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
39425f39d397SChris Mason 		path->nodes[0] = left;
3943be0e5c09SChris Mason 		path->slots[1] -= 1;
3944be0e5c09SChris Mason 	} else {
3945925baeddSChris Mason 		btrfs_tree_unlock(left);
39465f39d397SChris Mason 		free_extent_buffer(left);
3947be0e5c09SChris Mason 		path->slots[0] -= push_items;
3948be0e5c09SChris Mason 	}
3949eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
3950aa5d6bedSChris Mason 	return ret;
3951925baeddSChris Mason out:
3952925baeddSChris Mason 	btrfs_tree_unlock(left);
3953925baeddSChris Mason 	free_extent_buffer(left);
3954925baeddSChris Mason 	return ret;
3955be0e5c09SChris Mason }
3956be0e5c09SChris Mason 
395774123bd7SChris Mason /*
395844871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
395944871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
396099d8f83cSChris Mason  *
396199d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
396299d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us push all the
396399d8f83cSChris Mason  * items
396444871b1bSChris Mason  */
396544871b1bSChris Mason static int push_leaf_left(struct btrfs_trans_handle *trans, struct btrfs_root
396699d8f83cSChris Mason 			  *root, struct btrfs_path *path, int min_data_size,
396799d8f83cSChris Mason 			  int data_size, int empty, u32 max_slot)
396844871b1bSChris Mason {
396944871b1bSChris Mason 	struct extent_buffer *right = path->nodes[0];
397044871b1bSChris Mason 	struct extent_buffer *left;
397144871b1bSChris Mason 	int slot;
397244871b1bSChris Mason 	int free_space;
397344871b1bSChris Mason 	u32 right_nritems;
397444871b1bSChris Mason 	int ret = 0;
397544871b1bSChris Mason 
397644871b1bSChris Mason 	slot = path->slots[1];
397744871b1bSChris Mason 	if (slot == 0)
397844871b1bSChris Mason 		return 1;
397944871b1bSChris Mason 	if (!path->nodes[1])
398044871b1bSChris Mason 		return 1;
398144871b1bSChris Mason 
398244871b1bSChris Mason 	right_nritems = btrfs_header_nritems(right);
398344871b1bSChris Mason 	if (right_nritems == 0)
398444871b1bSChris Mason 		return 1;
398544871b1bSChris Mason 
398644871b1bSChris Mason 	btrfs_assert_tree_locked(path->nodes[1]);
398744871b1bSChris Mason 
39884b231ae4SDavid Sterba 	left = btrfs_read_node_slot(path->nodes[1], slot - 1);
3989fb770ae4SLiu Bo 	/*
3990fb770ae4SLiu Bo 	 * slot - 1 is not valid or we fail to read the left node,
3991fb770ae4SLiu Bo 	 * no big deal, just return.
3992fb770ae4SLiu Bo 	 */
3993fb770ae4SLiu Bo 	if (IS_ERR(left))
399491ca338dSTsutomu Itoh 		return 1;
399591ca338dSTsutomu Itoh 
399644871b1bSChris Mason 	btrfs_tree_lock(left);
39978bead258SDavid Sterba 	btrfs_set_lock_blocking_write(left);
399844871b1bSChris Mason 
3999e902baacSDavid Sterba 	free_space = btrfs_leaf_free_space(left);
400044871b1bSChris Mason 	if (free_space < data_size) {
400144871b1bSChris Mason 		ret = 1;
400244871b1bSChris Mason 		goto out;
400344871b1bSChris Mason 	}
400444871b1bSChris Mason 
400544871b1bSChris Mason 	/* cow and double check */
400644871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, left,
400744871b1bSChris Mason 			      path->nodes[1], slot - 1, &left);
400844871b1bSChris Mason 	if (ret) {
400944871b1bSChris Mason 		/* we hit -ENOSPC, but it isn't fatal here */
401079787eaaSJeff Mahoney 		if (ret == -ENOSPC)
401144871b1bSChris Mason 			ret = 1;
401244871b1bSChris Mason 		goto out;
401344871b1bSChris Mason 	}
401444871b1bSChris Mason 
4015e902baacSDavid Sterba 	free_space = btrfs_leaf_free_space(left);
401644871b1bSChris Mason 	if (free_space < data_size) {
401744871b1bSChris Mason 		ret = 1;
401844871b1bSChris Mason 		goto out;
401944871b1bSChris Mason 	}
402044871b1bSChris Mason 
40218087c193SDavid Sterba 	return __push_leaf_left(path, min_data_size,
402299d8f83cSChris Mason 			       empty, left, free_space, right_nritems,
402399d8f83cSChris Mason 			       max_slot);
402444871b1bSChris Mason out:
402544871b1bSChris Mason 	btrfs_tree_unlock(left);
402644871b1bSChris Mason 	free_extent_buffer(left);
402744871b1bSChris Mason 	return ret;
402844871b1bSChris Mason }
402944871b1bSChris Mason 
403044871b1bSChris Mason /*
403174123bd7SChris Mason  * split the path's leaf in two, making sure there is at least data_size
403274123bd7SChris Mason  * available for the resulting leaf level of the path.
403374123bd7SChris Mason  */
4034143bede5SJeff Mahoney static noinline void copy_for_split(struct btrfs_trans_handle *trans,
403544871b1bSChris Mason 				    struct btrfs_path *path,
403644871b1bSChris Mason 				    struct extent_buffer *l,
403744871b1bSChris Mason 				    struct extent_buffer *right,
403844871b1bSChris Mason 				    int slot, int mid, int nritems)
4039be0e5c09SChris Mason {
404094f94ad9SDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
4041be0e5c09SChris Mason 	int data_copy_size;
4042be0e5c09SChris Mason 	int rt_data_off;
4043be0e5c09SChris Mason 	int i;
4044d4dbff95SChris Mason 	struct btrfs_disk_key disk_key;
4045cfed81a0SChris Mason 	struct btrfs_map_token token;
4046cfed81a0SChris Mason 
40475f39d397SChris Mason 	nritems = nritems - mid;
40485f39d397SChris Mason 	btrfs_set_header_nritems(right, nritems);
40498f881e8cSDavid Sterba 	data_copy_size = btrfs_item_end_nr(l, mid) - leaf_data_end(l);
40505f39d397SChris Mason 
40515f39d397SChris Mason 	copy_extent_buffer(right, l, btrfs_item_nr_offset(0),
40525f39d397SChris Mason 			   btrfs_item_nr_offset(mid),
40535f39d397SChris Mason 			   nritems * sizeof(struct btrfs_item));
40545f39d397SChris Mason 
40555f39d397SChris Mason 	copy_extent_buffer(right, l,
40563d9ec8c4SNikolay Borisov 		     BTRFS_LEAF_DATA_OFFSET + BTRFS_LEAF_DATA_SIZE(fs_info) -
40573d9ec8c4SNikolay Borisov 		     data_copy_size, BTRFS_LEAF_DATA_OFFSET +
40588f881e8cSDavid Sterba 		     leaf_data_end(l), data_copy_size);
405974123bd7SChris Mason 
40600b246afaSJeff Mahoney 	rt_data_off = BTRFS_LEAF_DATA_SIZE(fs_info) - btrfs_item_end_nr(l, mid);
40615f39d397SChris Mason 
4062c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
40635f39d397SChris Mason 	for (i = 0; i < nritems; i++) {
4064dd3cc16bSRoss Kirk 		struct btrfs_item *item = btrfs_item_nr(i);
4065db94535dSChris Mason 		u32 ioff;
4066db94535dSChris Mason 
4067cfed81a0SChris Mason 		ioff = btrfs_token_item_offset(right, item, &token);
4068cfed81a0SChris Mason 		btrfs_set_token_item_offset(right, item,
4069cfed81a0SChris Mason 					    ioff + rt_data_off, &token);
40700783fcfcSChris Mason 	}
407174123bd7SChris Mason 
40725f39d397SChris Mason 	btrfs_set_header_nritems(l, mid);
40735f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
40746ad3cf6dSDavid Sterba 	insert_ptr(trans, path, &disk_key, right->start, path->slots[1] + 1, 1);
40755f39d397SChris Mason 
40765f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
40775f39d397SChris Mason 	btrfs_mark_buffer_dirty(l);
4078eb60ceacSChris Mason 	BUG_ON(path->slots[0] != slot);
40795f39d397SChris Mason 
4080be0e5c09SChris Mason 	if (mid <= slot) {
4081925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
40825f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
40835f39d397SChris Mason 		path->nodes[0] = right;
4084be0e5c09SChris Mason 		path->slots[0] -= mid;
4085be0e5c09SChris Mason 		path->slots[1] += 1;
4086925baeddSChris Mason 	} else {
4087925baeddSChris Mason 		btrfs_tree_unlock(right);
40885f39d397SChris Mason 		free_extent_buffer(right);
4089925baeddSChris Mason 	}
40905f39d397SChris Mason 
4091eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
409244871b1bSChris Mason }
409344871b1bSChris Mason 
409444871b1bSChris Mason /*
409599d8f83cSChris Mason  * double splits happen when we need to insert a big item in the middle
409699d8f83cSChris Mason  * of a leaf.  A double split can leave us with 3 mostly empty leaves:
409799d8f83cSChris Mason  * leaf: [ slots 0 - N] [ our target ] [ N + 1 - total in leaf ]
409899d8f83cSChris Mason  *          A                 B                 C
409999d8f83cSChris Mason  *
410099d8f83cSChris Mason  * We avoid this by trying to push the items on either side of our target
410199d8f83cSChris Mason  * into the adjacent leaves.  If all goes well we can avoid the double split
410299d8f83cSChris Mason  * completely.
410399d8f83cSChris Mason  */
410499d8f83cSChris Mason static noinline int push_for_double_split(struct btrfs_trans_handle *trans,
410599d8f83cSChris Mason 					  struct btrfs_root *root,
410699d8f83cSChris Mason 					  struct btrfs_path *path,
410799d8f83cSChris Mason 					  int data_size)
410899d8f83cSChris Mason {
410999d8f83cSChris Mason 	int ret;
411099d8f83cSChris Mason 	int progress = 0;
411199d8f83cSChris Mason 	int slot;
411299d8f83cSChris Mason 	u32 nritems;
41135a4267caSFilipe David Borba Manana 	int space_needed = data_size;
411499d8f83cSChris Mason 
411599d8f83cSChris Mason 	slot = path->slots[0];
41165a4267caSFilipe David Borba Manana 	if (slot < btrfs_header_nritems(path->nodes[0]))
4117e902baacSDavid Sterba 		space_needed -= btrfs_leaf_free_space(path->nodes[0]);
411899d8f83cSChris Mason 
411999d8f83cSChris Mason 	/*
412099d8f83cSChris Mason 	 * try to push all the items after our slot into the
412199d8f83cSChris Mason 	 * right leaf
412299d8f83cSChris Mason 	 */
41235a4267caSFilipe David Borba Manana 	ret = push_leaf_right(trans, root, path, 1, space_needed, 0, slot);
412499d8f83cSChris Mason 	if (ret < 0)
412599d8f83cSChris Mason 		return ret;
412699d8f83cSChris Mason 
412799d8f83cSChris Mason 	if (ret == 0)
412899d8f83cSChris Mason 		progress++;
412999d8f83cSChris Mason 
413099d8f83cSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
413199d8f83cSChris Mason 	/*
413299d8f83cSChris Mason 	 * our goal is to get our slot at the start or end of a leaf.  If
413399d8f83cSChris Mason 	 * we've done so we're done
413499d8f83cSChris Mason 	 */
413599d8f83cSChris Mason 	if (path->slots[0] == 0 || path->slots[0] == nritems)
413699d8f83cSChris Mason 		return 0;
413799d8f83cSChris Mason 
4138e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
413999d8f83cSChris Mason 		return 0;
414099d8f83cSChris Mason 
414199d8f83cSChris Mason 	/* try to push all the items before our slot into the next leaf */
414299d8f83cSChris Mason 	slot = path->slots[0];
4143263d3995SFilipe Manana 	space_needed = data_size;
4144263d3995SFilipe Manana 	if (slot > 0)
4145e902baacSDavid Sterba 		space_needed -= btrfs_leaf_free_space(path->nodes[0]);
41465a4267caSFilipe David Borba Manana 	ret = push_leaf_left(trans, root, path, 1, space_needed, 0, slot);
414799d8f83cSChris Mason 	if (ret < 0)
414899d8f83cSChris Mason 		return ret;
414999d8f83cSChris Mason 
415099d8f83cSChris Mason 	if (ret == 0)
415199d8f83cSChris Mason 		progress++;
415299d8f83cSChris Mason 
415399d8f83cSChris Mason 	if (progress)
415499d8f83cSChris Mason 		return 0;
415599d8f83cSChris Mason 	return 1;
415699d8f83cSChris Mason }
415799d8f83cSChris Mason 
415899d8f83cSChris Mason /*
415944871b1bSChris Mason  * split the path's leaf in two, making sure there is at least data_size
416044871b1bSChris Mason  * available for the resulting leaf level of the path.
416144871b1bSChris Mason  *
416244871b1bSChris Mason  * returns 0 if all went well and < 0 on failure.
416344871b1bSChris Mason  */
416444871b1bSChris Mason static noinline int split_leaf(struct btrfs_trans_handle *trans,
416544871b1bSChris Mason 			       struct btrfs_root *root,
4166310712b2SOmar Sandoval 			       const struct btrfs_key *ins_key,
416744871b1bSChris Mason 			       struct btrfs_path *path, int data_size,
416844871b1bSChris Mason 			       int extend)
416944871b1bSChris Mason {
41705d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
417144871b1bSChris Mason 	struct extent_buffer *l;
417244871b1bSChris Mason 	u32 nritems;
417344871b1bSChris Mason 	int mid;
417444871b1bSChris Mason 	int slot;
417544871b1bSChris Mason 	struct extent_buffer *right;
4176b7a0365eSDaniel Dressler 	struct btrfs_fs_info *fs_info = root->fs_info;
417744871b1bSChris Mason 	int ret = 0;
417844871b1bSChris Mason 	int wret;
41795d4f98a2SYan Zheng 	int split;
418044871b1bSChris Mason 	int num_doubles = 0;
418199d8f83cSChris Mason 	int tried_avoid_double = 0;
418244871b1bSChris Mason 
4183a5719521SYan, Zheng 	l = path->nodes[0];
4184a5719521SYan, Zheng 	slot = path->slots[0];
4185a5719521SYan, Zheng 	if (extend && data_size + btrfs_item_size_nr(l, slot) +
41860b246afaSJeff Mahoney 	    sizeof(struct btrfs_item) > BTRFS_LEAF_DATA_SIZE(fs_info))
4187a5719521SYan, Zheng 		return -EOVERFLOW;
4188a5719521SYan, Zheng 
418944871b1bSChris Mason 	/* first try to make some room by pushing left and right */
419033157e05SLiu Bo 	if (data_size && path->nodes[1]) {
41915a4267caSFilipe David Borba Manana 		int space_needed = data_size;
41925a4267caSFilipe David Borba Manana 
41935a4267caSFilipe David Borba Manana 		if (slot < btrfs_header_nritems(l))
4194e902baacSDavid Sterba 			space_needed -= btrfs_leaf_free_space(l);
41955a4267caSFilipe David Borba Manana 
41965a4267caSFilipe David Borba Manana 		wret = push_leaf_right(trans, root, path, space_needed,
41975a4267caSFilipe David Borba Manana 				       space_needed, 0, 0);
419844871b1bSChris Mason 		if (wret < 0)
419944871b1bSChris Mason 			return wret;
420044871b1bSChris Mason 		if (wret) {
4201263d3995SFilipe Manana 			space_needed = data_size;
4202263d3995SFilipe Manana 			if (slot > 0)
4203e902baacSDavid Sterba 				space_needed -= btrfs_leaf_free_space(l);
42045a4267caSFilipe David Borba Manana 			wret = push_leaf_left(trans, root, path, space_needed,
42055a4267caSFilipe David Borba Manana 					      space_needed, 0, (u32)-1);
420644871b1bSChris Mason 			if (wret < 0)
420744871b1bSChris Mason 				return wret;
420844871b1bSChris Mason 		}
420944871b1bSChris Mason 		l = path->nodes[0];
421044871b1bSChris Mason 
421144871b1bSChris Mason 		/* did the pushes work? */
4212e902baacSDavid Sterba 		if (btrfs_leaf_free_space(l) >= data_size)
421344871b1bSChris Mason 			return 0;
421444871b1bSChris Mason 	}
421544871b1bSChris Mason 
421644871b1bSChris Mason 	if (!path->nodes[1]) {
4217fdd99c72SLiu Bo 		ret = insert_new_root(trans, root, path, 1);
421844871b1bSChris Mason 		if (ret)
421944871b1bSChris Mason 			return ret;
422044871b1bSChris Mason 	}
422144871b1bSChris Mason again:
42225d4f98a2SYan Zheng 	split = 1;
422344871b1bSChris Mason 	l = path->nodes[0];
422444871b1bSChris Mason 	slot = path->slots[0];
422544871b1bSChris Mason 	nritems = btrfs_header_nritems(l);
422644871b1bSChris Mason 	mid = (nritems + 1) / 2;
422744871b1bSChris Mason 
42285d4f98a2SYan Zheng 	if (mid <= slot) {
42295d4f98a2SYan Zheng 		if (nritems == 1 ||
42305d4f98a2SYan Zheng 		    leaf_space_used(l, mid, nritems - mid) + data_size >
42310b246afaSJeff Mahoney 			BTRFS_LEAF_DATA_SIZE(fs_info)) {
42325d4f98a2SYan Zheng 			if (slot >= nritems) {
42335d4f98a2SYan Zheng 				split = 0;
42345d4f98a2SYan Zheng 			} else {
42355d4f98a2SYan Zheng 				mid = slot;
42365d4f98a2SYan Zheng 				if (mid != nritems &&
42375d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
42380b246afaSJeff Mahoney 				    data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
423999d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
424099d8f83cSChris Mason 						goto push_for_double;
42415d4f98a2SYan Zheng 					split = 2;
42425d4f98a2SYan Zheng 				}
42435d4f98a2SYan Zheng 			}
42445d4f98a2SYan Zheng 		}
42455d4f98a2SYan Zheng 	} else {
42465d4f98a2SYan Zheng 		if (leaf_space_used(l, 0, mid) + data_size >
42470b246afaSJeff Mahoney 			BTRFS_LEAF_DATA_SIZE(fs_info)) {
42485d4f98a2SYan Zheng 			if (!extend && data_size && slot == 0) {
42495d4f98a2SYan Zheng 				split = 0;
42505d4f98a2SYan Zheng 			} else if ((extend || !data_size) && slot == 0) {
42515d4f98a2SYan Zheng 				mid = 1;
42525d4f98a2SYan Zheng 			} else {
42535d4f98a2SYan Zheng 				mid = slot;
42545d4f98a2SYan Zheng 				if (mid != nritems &&
42555d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
42560b246afaSJeff Mahoney 				    data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
425799d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
425899d8f83cSChris Mason 						goto push_for_double;
42595d4f98a2SYan Zheng 					split = 2;
42605d4f98a2SYan Zheng 				}
42615d4f98a2SYan Zheng 			}
42625d4f98a2SYan Zheng 		}
42635d4f98a2SYan Zheng 	}
42645d4f98a2SYan Zheng 
42655d4f98a2SYan Zheng 	if (split == 0)
42665d4f98a2SYan Zheng 		btrfs_cpu_key_to_disk(&disk_key, ins_key);
42675d4f98a2SYan Zheng 	else
42685d4f98a2SYan Zheng 		btrfs_item_key(l, &disk_key, mid);
42695d4f98a2SYan Zheng 
4270a6279470SFilipe Manana 	right = alloc_tree_block_no_bg_flush(trans, root, 0, &disk_key, 0,
4271a6279470SFilipe Manana 					     l->start, 0);
4272f0486c68SYan, Zheng 	if (IS_ERR(right))
427344871b1bSChris Mason 		return PTR_ERR(right);
4274f0486c68SYan, Zheng 
42750b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
427644871b1bSChris Mason 
42775d4f98a2SYan Zheng 	if (split == 0) {
427844871b1bSChris Mason 		if (mid <= slot) {
427944871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
42806ad3cf6dSDavid Sterba 			insert_ptr(trans, path, &disk_key,
42812ff7e61eSJeff Mahoney 				   right->start, path->slots[1] + 1, 1);
428244871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
428344871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
428444871b1bSChris Mason 			path->nodes[0] = right;
428544871b1bSChris Mason 			path->slots[0] = 0;
428644871b1bSChris Mason 			path->slots[1] += 1;
428744871b1bSChris Mason 		} else {
428844871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
42896ad3cf6dSDavid Sterba 			insert_ptr(trans, path, &disk_key,
42902ff7e61eSJeff Mahoney 				   right->start, path->slots[1], 1);
429144871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
429244871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
429344871b1bSChris Mason 			path->nodes[0] = right;
429444871b1bSChris Mason 			path->slots[0] = 0;
4295143bede5SJeff Mahoney 			if (path->slots[1] == 0)
4296b167fa91SNikolay Borisov 				fixup_low_keys(path, &disk_key, 1);
42975d4f98a2SYan Zheng 		}
4298196e0249SLiu Bo 		/*
4299196e0249SLiu Bo 		 * We create a new leaf 'right' for the required ins_len and
4300196e0249SLiu Bo 		 * we'll do btrfs_mark_buffer_dirty() on this leaf after copying
4301196e0249SLiu Bo 		 * the content of ins_len to 'right'.
4302196e0249SLiu Bo 		 */
430344871b1bSChris Mason 		return ret;
430444871b1bSChris Mason 	}
430544871b1bSChris Mason 
430694f94ad9SDavid Sterba 	copy_for_split(trans, path, l, right, slot, mid, nritems);
430744871b1bSChris Mason 
43085d4f98a2SYan Zheng 	if (split == 2) {
4309cc0c5538SChris Mason 		BUG_ON(num_doubles != 0);
4310cc0c5538SChris Mason 		num_doubles++;
4311cc0c5538SChris Mason 		goto again;
43123326d1b0SChris Mason 	}
431344871b1bSChris Mason 
4314143bede5SJeff Mahoney 	return 0;
431599d8f83cSChris Mason 
431699d8f83cSChris Mason push_for_double:
431799d8f83cSChris Mason 	push_for_double_split(trans, root, path, data_size);
431899d8f83cSChris Mason 	tried_avoid_double = 1;
4319e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
432099d8f83cSChris Mason 		return 0;
432199d8f83cSChris Mason 	goto again;
4322be0e5c09SChris Mason }
4323be0e5c09SChris Mason 
4324ad48fd75SYan, Zheng static noinline int setup_leaf_for_split(struct btrfs_trans_handle *trans,
4325ad48fd75SYan, Zheng 					 struct btrfs_root *root,
4326ad48fd75SYan, Zheng 					 struct btrfs_path *path, int ins_len)
4327ad48fd75SYan, Zheng {
4328ad48fd75SYan, Zheng 	struct btrfs_key key;
4329ad48fd75SYan, Zheng 	struct extent_buffer *leaf;
4330ad48fd75SYan, Zheng 	struct btrfs_file_extent_item *fi;
4331ad48fd75SYan, Zheng 	u64 extent_len = 0;
4332ad48fd75SYan, Zheng 	u32 item_size;
4333ad48fd75SYan, Zheng 	int ret;
4334ad48fd75SYan, Zheng 
4335ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4336ad48fd75SYan, Zheng 	btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4337ad48fd75SYan, Zheng 
4338ad48fd75SYan, Zheng 	BUG_ON(key.type != BTRFS_EXTENT_DATA_KEY &&
4339ad48fd75SYan, Zheng 	       key.type != BTRFS_EXTENT_CSUM_KEY);
4340ad48fd75SYan, Zheng 
4341e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) >= ins_len)
4342ad48fd75SYan, Zheng 		return 0;
4343ad48fd75SYan, Zheng 
4344ad48fd75SYan, Zheng 	item_size = btrfs_item_size_nr(leaf, path->slots[0]);
4345ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
4346ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
4347ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
4348ad48fd75SYan, Zheng 		extent_len = btrfs_file_extent_num_bytes(leaf, fi);
4349ad48fd75SYan, Zheng 	}
4350b3b4aa74SDavid Sterba 	btrfs_release_path(path);
4351ad48fd75SYan, Zheng 
4352ad48fd75SYan, Zheng 	path->keep_locks = 1;
4353ad48fd75SYan, Zheng 	path->search_for_split = 1;
4354ad48fd75SYan, Zheng 	ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
4355ad48fd75SYan, Zheng 	path->search_for_split = 0;
4356a8df6fe6SFilipe Manana 	if (ret > 0)
4357a8df6fe6SFilipe Manana 		ret = -EAGAIN;
4358ad48fd75SYan, Zheng 	if (ret < 0)
4359ad48fd75SYan, Zheng 		goto err;
4360ad48fd75SYan, Zheng 
4361ad48fd75SYan, Zheng 	ret = -EAGAIN;
4362ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4363a8df6fe6SFilipe Manana 	/* if our item isn't there, return now */
4364a8df6fe6SFilipe Manana 	if (item_size != btrfs_item_size_nr(leaf, path->slots[0]))
4365ad48fd75SYan, Zheng 		goto err;
4366ad48fd75SYan, Zheng 
4367109f6aefSChris Mason 	/* the leaf has  changed, it now has room.  return now */
4368e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= ins_len)
4369109f6aefSChris Mason 		goto err;
4370109f6aefSChris Mason 
4371ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
4372ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
4373ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
4374ad48fd75SYan, Zheng 		if (extent_len != btrfs_file_extent_num_bytes(leaf, fi))
4375ad48fd75SYan, Zheng 			goto err;
4376ad48fd75SYan, Zheng 	}
4377ad48fd75SYan, Zheng 
4378ad48fd75SYan, Zheng 	btrfs_set_path_blocking(path);
4379ad48fd75SYan, Zheng 	ret = split_leaf(trans, root, &key, path, ins_len, 1);
4380f0486c68SYan, Zheng 	if (ret)
4381f0486c68SYan, Zheng 		goto err;
4382ad48fd75SYan, Zheng 
4383ad48fd75SYan, Zheng 	path->keep_locks = 0;
4384ad48fd75SYan, Zheng 	btrfs_unlock_up_safe(path, 1);
4385ad48fd75SYan, Zheng 	return 0;
4386ad48fd75SYan, Zheng err:
4387ad48fd75SYan, Zheng 	path->keep_locks = 0;
4388ad48fd75SYan, Zheng 	return ret;
4389ad48fd75SYan, Zheng }
4390ad48fd75SYan, Zheng 
439125263cd7SDavid Sterba static noinline int split_item(struct btrfs_path *path,
4392310712b2SOmar Sandoval 			       const struct btrfs_key *new_key,
4393459931ecSChris Mason 			       unsigned long split_offset)
4394459931ecSChris Mason {
4395459931ecSChris Mason 	struct extent_buffer *leaf;
4396459931ecSChris Mason 	struct btrfs_item *item;
4397459931ecSChris Mason 	struct btrfs_item *new_item;
4398459931ecSChris Mason 	int slot;
4399ad48fd75SYan, Zheng 	char *buf;
4400459931ecSChris Mason 	u32 nritems;
4401ad48fd75SYan, Zheng 	u32 item_size;
4402459931ecSChris Mason 	u32 orig_offset;
4403459931ecSChris Mason 	struct btrfs_disk_key disk_key;
4404459931ecSChris Mason 
4405459931ecSChris Mason 	leaf = path->nodes[0];
4406e902baacSDavid Sterba 	BUG_ON(btrfs_leaf_free_space(leaf) < sizeof(struct btrfs_item));
4407b9473439SChris Mason 
4408b4ce94deSChris Mason 	btrfs_set_path_blocking(path);
4409b4ce94deSChris Mason 
4410dd3cc16bSRoss Kirk 	item = btrfs_item_nr(path->slots[0]);
4411459931ecSChris Mason 	orig_offset = btrfs_item_offset(leaf, item);
4412459931ecSChris Mason 	item_size = btrfs_item_size(leaf, item);
4413459931ecSChris Mason 
4414459931ecSChris Mason 	buf = kmalloc(item_size, GFP_NOFS);
4415ad48fd75SYan, Zheng 	if (!buf)
4416ad48fd75SYan, Zheng 		return -ENOMEM;
4417ad48fd75SYan, Zheng 
4418459931ecSChris Mason 	read_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf,
4419459931ecSChris Mason 			    path->slots[0]), item_size);
4420ad48fd75SYan, Zheng 
4421459931ecSChris Mason 	slot = path->slots[0] + 1;
4422459931ecSChris Mason 	nritems = btrfs_header_nritems(leaf);
4423459931ecSChris Mason 	if (slot != nritems) {
4424459931ecSChris Mason 		/* shift the items */
4425459931ecSChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + 1),
4426459931ecSChris Mason 				btrfs_item_nr_offset(slot),
4427459931ecSChris Mason 				(nritems - slot) * sizeof(struct btrfs_item));
4428459931ecSChris Mason 	}
4429459931ecSChris Mason 
4430459931ecSChris Mason 	btrfs_cpu_key_to_disk(&disk_key, new_key);
4431459931ecSChris Mason 	btrfs_set_item_key(leaf, &disk_key, slot);
4432459931ecSChris Mason 
4433dd3cc16bSRoss Kirk 	new_item = btrfs_item_nr(slot);
4434459931ecSChris Mason 
4435459931ecSChris Mason 	btrfs_set_item_offset(leaf, new_item, orig_offset);
4436459931ecSChris Mason 	btrfs_set_item_size(leaf, new_item, item_size - split_offset);
4437459931ecSChris Mason 
4438459931ecSChris Mason 	btrfs_set_item_offset(leaf, item,
4439459931ecSChris Mason 			      orig_offset + item_size - split_offset);
4440459931ecSChris Mason 	btrfs_set_item_size(leaf, item, split_offset);
4441459931ecSChris Mason 
4442459931ecSChris Mason 	btrfs_set_header_nritems(leaf, nritems + 1);
4443459931ecSChris Mason 
4444459931ecSChris Mason 	/* write the data for the start of the original item */
4445459931ecSChris Mason 	write_extent_buffer(leaf, buf,
4446459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, path->slots[0]),
4447459931ecSChris Mason 			    split_offset);
4448459931ecSChris Mason 
4449459931ecSChris Mason 	/* write the data for the new item */
4450459931ecSChris Mason 	write_extent_buffer(leaf, buf + split_offset,
4451459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, slot),
4452459931ecSChris Mason 			    item_size - split_offset);
4453459931ecSChris Mason 	btrfs_mark_buffer_dirty(leaf);
4454459931ecSChris Mason 
4455e902baacSDavid Sterba 	BUG_ON(btrfs_leaf_free_space(leaf) < 0);
4456459931ecSChris Mason 	kfree(buf);
4457ad48fd75SYan, Zheng 	return 0;
4458ad48fd75SYan, Zheng }
4459ad48fd75SYan, Zheng 
4460ad48fd75SYan, Zheng /*
4461ad48fd75SYan, Zheng  * This function splits a single item into two items,
4462ad48fd75SYan, Zheng  * giving 'new_key' to the new item and splitting the
4463ad48fd75SYan, Zheng  * old one at split_offset (from the start of the item).
4464ad48fd75SYan, Zheng  *
4465ad48fd75SYan, Zheng  * The path may be released by this operation.  After
4466ad48fd75SYan, Zheng  * the split, the path is pointing to the old item.  The
4467ad48fd75SYan, Zheng  * new item is going to be in the same node as the old one.
4468ad48fd75SYan, Zheng  *
4469ad48fd75SYan, Zheng  * Note, the item being split must be smaller enough to live alone on
4470ad48fd75SYan, Zheng  * a tree block with room for one extra struct btrfs_item
4471ad48fd75SYan, Zheng  *
4472ad48fd75SYan, Zheng  * This allows us to split the item in place, keeping a lock on the
4473ad48fd75SYan, Zheng  * leaf the entire time.
4474ad48fd75SYan, Zheng  */
4475ad48fd75SYan, Zheng int btrfs_split_item(struct btrfs_trans_handle *trans,
4476ad48fd75SYan, Zheng 		     struct btrfs_root *root,
4477ad48fd75SYan, Zheng 		     struct btrfs_path *path,
4478310712b2SOmar Sandoval 		     const struct btrfs_key *new_key,
4479ad48fd75SYan, Zheng 		     unsigned long split_offset)
4480ad48fd75SYan, Zheng {
4481ad48fd75SYan, Zheng 	int ret;
4482ad48fd75SYan, Zheng 	ret = setup_leaf_for_split(trans, root, path,
4483ad48fd75SYan, Zheng 				   sizeof(struct btrfs_item));
4484ad48fd75SYan, Zheng 	if (ret)
4485459931ecSChris Mason 		return ret;
4486ad48fd75SYan, Zheng 
448725263cd7SDavid Sterba 	ret = split_item(path, new_key, split_offset);
4488ad48fd75SYan, Zheng 	return ret;
4489ad48fd75SYan, Zheng }
4490ad48fd75SYan, Zheng 
4491ad48fd75SYan, Zheng /*
4492ad48fd75SYan, Zheng  * This function duplicate a item, giving 'new_key' to the new item.
4493ad48fd75SYan, Zheng  * It guarantees both items live in the same tree leaf and the new item
4494ad48fd75SYan, Zheng  * is contiguous with the original item.
4495ad48fd75SYan, Zheng  *
4496ad48fd75SYan, Zheng  * This allows us to split file extent in place, keeping a lock on the
4497ad48fd75SYan, Zheng  * leaf the entire time.
4498ad48fd75SYan, Zheng  */
4499ad48fd75SYan, Zheng int btrfs_duplicate_item(struct btrfs_trans_handle *trans,
4500ad48fd75SYan, Zheng 			 struct btrfs_root *root,
4501ad48fd75SYan, Zheng 			 struct btrfs_path *path,
4502310712b2SOmar Sandoval 			 const struct btrfs_key *new_key)
4503ad48fd75SYan, Zheng {
4504ad48fd75SYan, Zheng 	struct extent_buffer *leaf;
4505ad48fd75SYan, Zheng 	int ret;
4506ad48fd75SYan, Zheng 	u32 item_size;
4507ad48fd75SYan, Zheng 
4508ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4509ad48fd75SYan, Zheng 	item_size = btrfs_item_size_nr(leaf, path->slots[0]);
4510ad48fd75SYan, Zheng 	ret = setup_leaf_for_split(trans, root, path,
4511ad48fd75SYan, Zheng 				   item_size + sizeof(struct btrfs_item));
4512ad48fd75SYan, Zheng 	if (ret)
4513ad48fd75SYan, Zheng 		return ret;
4514ad48fd75SYan, Zheng 
4515ad48fd75SYan, Zheng 	path->slots[0]++;
4516afe5fea7STsutomu Itoh 	setup_items_for_insert(root, path, new_key, &item_size,
4517ad48fd75SYan, Zheng 			       item_size, item_size +
4518ad48fd75SYan, Zheng 			       sizeof(struct btrfs_item), 1);
4519ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4520ad48fd75SYan, Zheng 	memcpy_extent_buffer(leaf,
4521ad48fd75SYan, Zheng 			     btrfs_item_ptr_offset(leaf, path->slots[0]),
4522ad48fd75SYan, Zheng 			     btrfs_item_ptr_offset(leaf, path->slots[0] - 1),
4523ad48fd75SYan, Zheng 			     item_size);
4524ad48fd75SYan, Zheng 	return 0;
4525459931ecSChris Mason }
4526459931ecSChris Mason 
4527459931ecSChris Mason /*
4528d352ac68SChris Mason  * make the item pointed to by the path smaller.  new_size indicates
4529d352ac68SChris Mason  * how small to make it, and from_end tells us if we just chop bytes
4530d352ac68SChris Mason  * off the end of the item or if we shift the item to chop bytes off
4531d352ac68SChris Mason  * the front.
4532d352ac68SChris Mason  */
453378ac4f9eSDavid Sterba void btrfs_truncate_item(struct btrfs_path *path, u32 new_size, int from_end)
4534b18c6685SChris Mason {
4535b18c6685SChris Mason 	int slot;
45365f39d397SChris Mason 	struct extent_buffer *leaf;
45375f39d397SChris Mason 	struct btrfs_item *item;
4538b18c6685SChris Mason 	u32 nritems;
4539b18c6685SChris Mason 	unsigned int data_end;
4540b18c6685SChris Mason 	unsigned int old_data_start;
4541b18c6685SChris Mason 	unsigned int old_size;
4542b18c6685SChris Mason 	unsigned int size_diff;
4543b18c6685SChris Mason 	int i;
4544cfed81a0SChris Mason 	struct btrfs_map_token token;
4545cfed81a0SChris Mason 
45465f39d397SChris Mason 	leaf = path->nodes[0];
4547179e29e4SChris Mason 	slot = path->slots[0];
4548179e29e4SChris Mason 
4549179e29e4SChris Mason 	old_size = btrfs_item_size_nr(leaf, slot);
4550179e29e4SChris Mason 	if (old_size == new_size)
4551143bede5SJeff Mahoney 		return;
4552b18c6685SChris Mason 
45535f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
45548f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
4555b18c6685SChris Mason 
45565f39d397SChris Mason 	old_data_start = btrfs_item_offset_nr(leaf, slot);
4557179e29e4SChris Mason 
4558b18c6685SChris Mason 	size_diff = old_size - new_size;
4559b18c6685SChris Mason 
4560b18c6685SChris Mason 	BUG_ON(slot < 0);
4561b18c6685SChris Mason 	BUG_ON(slot >= nritems);
4562b18c6685SChris Mason 
4563b18c6685SChris Mason 	/*
4564b18c6685SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4565b18c6685SChris Mason 	 */
4566b18c6685SChris Mason 	/* first correct the data pointers */
4567c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
4568b18c6685SChris Mason 	for (i = slot; i < nritems; i++) {
45695f39d397SChris Mason 		u32 ioff;
4570dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
4571db94535dSChris Mason 
4572cfed81a0SChris Mason 		ioff = btrfs_token_item_offset(leaf, item, &token);
4573cfed81a0SChris Mason 		btrfs_set_token_item_offset(leaf, item,
4574cfed81a0SChris Mason 					    ioff + size_diff, &token);
4575b18c6685SChris Mason 	}
4576db94535dSChris Mason 
4577b18c6685SChris Mason 	/* shift the data */
4578179e29e4SChris Mason 	if (from_end) {
45793d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
45803d9ec8c4SNikolay Borisov 			      data_end + size_diff, BTRFS_LEAF_DATA_OFFSET +
4581b18c6685SChris Mason 			      data_end, old_data_start + new_size - data_end);
4582179e29e4SChris Mason 	} else {
4583179e29e4SChris Mason 		struct btrfs_disk_key disk_key;
4584179e29e4SChris Mason 		u64 offset;
4585179e29e4SChris Mason 
4586179e29e4SChris Mason 		btrfs_item_key(leaf, &disk_key, slot);
4587179e29e4SChris Mason 
4588179e29e4SChris Mason 		if (btrfs_disk_key_type(&disk_key) == BTRFS_EXTENT_DATA_KEY) {
4589179e29e4SChris Mason 			unsigned long ptr;
4590179e29e4SChris Mason 			struct btrfs_file_extent_item *fi;
4591179e29e4SChris Mason 
4592179e29e4SChris Mason 			fi = btrfs_item_ptr(leaf, slot,
4593179e29e4SChris Mason 					    struct btrfs_file_extent_item);
4594179e29e4SChris Mason 			fi = (struct btrfs_file_extent_item *)(
4595179e29e4SChris Mason 			     (unsigned long)fi - size_diff);
4596179e29e4SChris Mason 
4597179e29e4SChris Mason 			if (btrfs_file_extent_type(leaf, fi) ==
4598179e29e4SChris Mason 			    BTRFS_FILE_EXTENT_INLINE) {
4599179e29e4SChris Mason 				ptr = btrfs_item_ptr_offset(leaf, slot);
4600179e29e4SChris Mason 				memmove_extent_buffer(leaf, ptr,
4601179e29e4SChris Mason 				      (unsigned long)fi,
46027ec20afbSDavid Sterba 				      BTRFS_FILE_EXTENT_INLINE_DATA_START);
4603179e29e4SChris Mason 			}
4604179e29e4SChris Mason 		}
4605179e29e4SChris Mason 
46063d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
46073d9ec8c4SNikolay Borisov 			      data_end + size_diff, BTRFS_LEAF_DATA_OFFSET +
4608179e29e4SChris Mason 			      data_end, old_data_start - data_end);
4609179e29e4SChris Mason 
4610179e29e4SChris Mason 		offset = btrfs_disk_key_offset(&disk_key);
4611179e29e4SChris Mason 		btrfs_set_disk_key_offset(&disk_key, offset + size_diff);
4612179e29e4SChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot);
4613179e29e4SChris Mason 		if (slot == 0)
4614b167fa91SNikolay Borisov 			fixup_low_keys(path, &disk_key, 1);
4615179e29e4SChris Mason 	}
46165f39d397SChris Mason 
4617dd3cc16bSRoss Kirk 	item = btrfs_item_nr(slot);
46185f39d397SChris Mason 	btrfs_set_item_size(leaf, item, new_size);
46195f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
4620b18c6685SChris Mason 
4621e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
4622a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
4623b18c6685SChris Mason 		BUG();
46245f39d397SChris Mason 	}
4625b18c6685SChris Mason }
4626b18c6685SChris Mason 
4627d352ac68SChris Mason /*
46288f69dbd2SStefan Behrens  * make the item pointed to by the path bigger, data_size is the added size.
4629d352ac68SChris Mason  */
4630c71dd880SDavid Sterba void btrfs_extend_item(struct btrfs_path *path, u32 data_size)
46316567e837SChris Mason {
46326567e837SChris Mason 	int slot;
46335f39d397SChris Mason 	struct extent_buffer *leaf;
46345f39d397SChris Mason 	struct btrfs_item *item;
46356567e837SChris Mason 	u32 nritems;
46366567e837SChris Mason 	unsigned int data_end;
46376567e837SChris Mason 	unsigned int old_data;
46386567e837SChris Mason 	unsigned int old_size;
46396567e837SChris Mason 	int i;
4640cfed81a0SChris Mason 	struct btrfs_map_token token;
4641cfed81a0SChris Mason 
46425f39d397SChris Mason 	leaf = path->nodes[0];
46436567e837SChris Mason 
46445f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
46458f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
46466567e837SChris Mason 
4647e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < data_size) {
4648a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
46496567e837SChris Mason 		BUG();
46505f39d397SChris Mason 	}
46516567e837SChris Mason 	slot = path->slots[0];
46525f39d397SChris Mason 	old_data = btrfs_item_end_nr(leaf, slot);
46536567e837SChris Mason 
46546567e837SChris Mason 	BUG_ON(slot < 0);
46553326d1b0SChris Mason 	if (slot >= nritems) {
4656a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
4657c71dd880SDavid Sterba 		btrfs_crit(leaf->fs_info, "slot %d too large, nritems %d",
4658d397712bSChris Mason 			   slot, nritems);
4659290342f6SArnd Bergmann 		BUG();
46603326d1b0SChris Mason 	}
46616567e837SChris Mason 
46626567e837SChris Mason 	/*
46636567e837SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
46646567e837SChris Mason 	 */
46656567e837SChris Mason 	/* first correct the data pointers */
4666c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
46676567e837SChris Mason 	for (i = slot; i < nritems; i++) {
46685f39d397SChris Mason 		u32 ioff;
4669dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
4670db94535dSChris Mason 
4671cfed81a0SChris Mason 		ioff = btrfs_token_item_offset(leaf, item, &token);
4672cfed81a0SChris Mason 		btrfs_set_token_item_offset(leaf, item,
4673cfed81a0SChris Mason 					    ioff - data_size, &token);
46746567e837SChris Mason 	}
46755f39d397SChris Mason 
46766567e837SChris Mason 	/* shift the data */
46773d9ec8c4SNikolay Borisov 	memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
46783d9ec8c4SNikolay Borisov 		      data_end - data_size, BTRFS_LEAF_DATA_OFFSET +
46796567e837SChris Mason 		      data_end, old_data - data_end);
46805f39d397SChris Mason 
46816567e837SChris Mason 	data_end = old_data;
46825f39d397SChris Mason 	old_size = btrfs_item_size_nr(leaf, slot);
4683dd3cc16bSRoss Kirk 	item = btrfs_item_nr(slot);
46845f39d397SChris Mason 	btrfs_set_item_size(leaf, item, old_size + data_size);
46855f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
46866567e837SChris Mason 
4687e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
4688a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
46896567e837SChris Mason 		BUG();
46905f39d397SChris Mason 	}
46916567e837SChris Mason }
46926567e837SChris Mason 
469374123bd7SChris Mason /*
469444871b1bSChris Mason  * this is a helper for btrfs_insert_empty_items, the main goal here is
469544871b1bSChris Mason  * to save stack depth by doing the bulk of the work in a function
469644871b1bSChris Mason  * that doesn't call btrfs_search_slot
469774123bd7SChris Mason  */
4698afe5fea7STsutomu Itoh void setup_items_for_insert(struct btrfs_root *root, struct btrfs_path *path,
4699310712b2SOmar Sandoval 			    const struct btrfs_key *cpu_key, u32 *data_size,
470044871b1bSChris Mason 			    u32 total_data, u32 total_size, int nr)
4701be0e5c09SChris Mason {
47020b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
47035f39d397SChris Mason 	struct btrfs_item *item;
47049c58309dSChris Mason 	int i;
47057518a238SChris Mason 	u32 nritems;
4706be0e5c09SChris Mason 	unsigned int data_end;
4707e2fa7227SChris Mason 	struct btrfs_disk_key disk_key;
470844871b1bSChris Mason 	struct extent_buffer *leaf;
470944871b1bSChris Mason 	int slot;
4710cfed81a0SChris Mason 	struct btrfs_map_token token;
4711cfed81a0SChris Mason 
471224cdc847SFilipe Manana 	if (path->slots[0] == 0) {
471324cdc847SFilipe Manana 		btrfs_cpu_key_to_disk(&disk_key, cpu_key);
4714b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, 1);
471524cdc847SFilipe Manana 	}
471624cdc847SFilipe Manana 	btrfs_unlock_up_safe(path, 1);
471724cdc847SFilipe Manana 
47185f39d397SChris Mason 	leaf = path->nodes[0];
471944871b1bSChris Mason 	slot = path->slots[0];
472074123bd7SChris Mason 
47215f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
47228f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
4723eb60ceacSChris Mason 
4724e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < total_size) {
4725a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
47260b246afaSJeff Mahoney 		btrfs_crit(fs_info, "not enough freespace need %u have %d",
4727e902baacSDavid Sterba 			   total_size, btrfs_leaf_free_space(leaf));
4728be0e5c09SChris Mason 		BUG();
4729d4dbff95SChris Mason 	}
47305f39d397SChris Mason 
4731c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
4732be0e5c09SChris Mason 	if (slot != nritems) {
47335f39d397SChris Mason 		unsigned int old_data = btrfs_item_end_nr(leaf, slot);
4734be0e5c09SChris Mason 
47355f39d397SChris Mason 		if (old_data < data_end) {
4736a4f78750SDavid Sterba 			btrfs_print_leaf(leaf);
47370b246afaSJeff Mahoney 			btrfs_crit(fs_info, "slot %d old_data %d data_end %d",
47385f39d397SChris Mason 				   slot, old_data, data_end);
4739290342f6SArnd Bergmann 			BUG();
47405f39d397SChris Mason 		}
4741be0e5c09SChris Mason 		/*
4742be0e5c09SChris Mason 		 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4743be0e5c09SChris Mason 		 */
4744be0e5c09SChris Mason 		/* first correct the data pointers */
47450783fcfcSChris Mason 		for (i = slot; i < nritems; i++) {
47465f39d397SChris Mason 			u32 ioff;
4747db94535dSChris Mason 
4748dd3cc16bSRoss Kirk 			item = btrfs_item_nr(i);
4749cfed81a0SChris Mason 			ioff = btrfs_token_item_offset(leaf, item, &token);
4750cfed81a0SChris Mason 			btrfs_set_token_item_offset(leaf, item,
4751cfed81a0SChris Mason 						    ioff - total_data, &token);
47520783fcfcSChris Mason 		}
4753be0e5c09SChris Mason 		/* shift the items */
47549c58309dSChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + nr),
47555f39d397SChris Mason 			      btrfs_item_nr_offset(slot),
47560783fcfcSChris Mason 			      (nritems - slot) * sizeof(struct btrfs_item));
4757be0e5c09SChris Mason 
4758be0e5c09SChris Mason 		/* shift the data */
47593d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
47603d9ec8c4SNikolay Borisov 			      data_end - total_data, BTRFS_LEAF_DATA_OFFSET +
4761be0e5c09SChris Mason 			      data_end, old_data - data_end);
4762be0e5c09SChris Mason 		data_end = old_data;
4763be0e5c09SChris Mason 	}
47645f39d397SChris Mason 
476562e2749eSChris Mason 	/* setup the item for the new data */
47669c58309dSChris Mason 	for (i = 0; i < nr; i++) {
47679c58309dSChris Mason 		btrfs_cpu_key_to_disk(&disk_key, cpu_key + i);
47689c58309dSChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot + i);
4769dd3cc16bSRoss Kirk 		item = btrfs_item_nr(slot + i);
4770cfed81a0SChris Mason 		btrfs_set_token_item_offset(leaf, item,
4771cfed81a0SChris Mason 					    data_end - data_size[i], &token);
47729c58309dSChris Mason 		data_end -= data_size[i];
4773cfed81a0SChris Mason 		btrfs_set_token_item_size(leaf, item, data_size[i], &token);
47749c58309dSChris Mason 	}
477544871b1bSChris Mason 
47769c58309dSChris Mason 	btrfs_set_header_nritems(leaf, nritems + nr);
4777b9473439SChris Mason 	btrfs_mark_buffer_dirty(leaf);
4778aa5d6bedSChris Mason 
4779e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
4780a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
4781be0e5c09SChris Mason 		BUG();
47825f39d397SChris Mason 	}
478344871b1bSChris Mason }
478444871b1bSChris Mason 
478544871b1bSChris Mason /*
478644871b1bSChris Mason  * Given a key and some data, insert items into the tree.
478744871b1bSChris Mason  * This does all the path init required, making room in the tree if needed.
478844871b1bSChris Mason  */
478944871b1bSChris Mason int btrfs_insert_empty_items(struct btrfs_trans_handle *trans,
479044871b1bSChris Mason 			    struct btrfs_root *root,
479144871b1bSChris Mason 			    struct btrfs_path *path,
4792310712b2SOmar Sandoval 			    const struct btrfs_key *cpu_key, u32 *data_size,
479344871b1bSChris Mason 			    int nr)
479444871b1bSChris Mason {
479544871b1bSChris Mason 	int ret = 0;
479644871b1bSChris Mason 	int slot;
479744871b1bSChris Mason 	int i;
479844871b1bSChris Mason 	u32 total_size = 0;
479944871b1bSChris Mason 	u32 total_data = 0;
480044871b1bSChris Mason 
480144871b1bSChris Mason 	for (i = 0; i < nr; i++)
480244871b1bSChris Mason 		total_data += data_size[i];
480344871b1bSChris Mason 
480444871b1bSChris Mason 	total_size = total_data + (nr * sizeof(struct btrfs_item));
480544871b1bSChris Mason 	ret = btrfs_search_slot(trans, root, cpu_key, path, total_size, 1);
480644871b1bSChris Mason 	if (ret == 0)
480744871b1bSChris Mason 		return -EEXIST;
480844871b1bSChris Mason 	if (ret < 0)
4809143bede5SJeff Mahoney 		return ret;
481044871b1bSChris Mason 
481144871b1bSChris Mason 	slot = path->slots[0];
481244871b1bSChris Mason 	BUG_ON(slot < 0);
481344871b1bSChris Mason 
4814afe5fea7STsutomu Itoh 	setup_items_for_insert(root, path, cpu_key, data_size,
481544871b1bSChris Mason 			       total_data, total_size, nr);
4816143bede5SJeff Mahoney 	return 0;
481762e2749eSChris Mason }
481862e2749eSChris Mason 
481962e2749eSChris Mason /*
482062e2749eSChris Mason  * Given a key and some data, insert an item into the tree.
482162e2749eSChris Mason  * This does all the path init required, making room in the tree if needed.
482262e2749eSChris Mason  */
4823310712b2SOmar Sandoval int btrfs_insert_item(struct btrfs_trans_handle *trans, struct btrfs_root *root,
4824310712b2SOmar Sandoval 		      const struct btrfs_key *cpu_key, void *data,
4825310712b2SOmar Sandoval 		      u32 data_size)
482662e2749eSChris Mason {
482762e2749eSChris Mason 	int ret = 0;
48282c90e5d6SChris Mason 	struct btrfs_path *path;
48295f39d397SChris Mason 	struct extent_buffer *leaf;
48305f39d397SChris Mason 	unsigned long ptr;
483162e2749eSChris Mason 
48322c90e5d6SChris Mason 	path = btrfs_alloc_path();
4833db5b493aSTsutomu Itoh 	if (!path)
4834db5b493aSTsutomu Itoh 		return -ENOMEM;
48352c90e5d6SChris Mason 	ret = btrfs_insert_empty_item(trans, root, path, cpu_key, data_size);
483662e2749eSChris Mason 	if (!ret) {
48375f39d397SChris Mason 		leaf = path->nodes[0];
48385f39d397SChris Mason 		ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
48395f39d397SChris Mason 		write_extent_buffer(leaf, data, ptr, data_size);
48405f39d397SChris Mason 		btrfs_mark_buffer_dirty(leaf);
484162e2749eSChris Mason 	}
48422c90e5d6SChris Mason 	btrfs_free_path(path);
4843aa5d6bedSChris Mason 	return ret;
4844be0e5c09SChris Mason }
4845be0e5c09SChris Mason 
484674123bd7SChris Mason /*
48475de08d7dSChris Mason  * delete the pointer from a given node.
484874123bd7SChris Mason  *
4849d352ac68SChris Mason  * the tree should have been previously balanced so the deletion does not
4850d352ac68SChris Mason  * empty a node.
485174123bd7SChris Mason  */
4852afe5fea7STsutomu Itoh static void del_ptr(struct btrfs_root *root, struct btrfs_path *path,
4853afe5fea7STsutomu Itoh 		    int level, int slot)
4854be0e5c09SChris Mason {
48555f39d397SChris Mason 	struct extent_buffer *parent = path->nodes[level];
48567518a238SChris Mason 	u32 nritems;
4857f3ea38daSJan Schmidt 	int ret;
4858be0e5c09SChris Mason 
48595f39d397SChris Mason 	nritems = btrfs_header_nritems(parent);
4860be0e5c09SChris Mason 	if (slot != nritems - 1) {
4861bf1d3425SDavid Sterba 		if (level) {
4862bf1d3425SDavid Sterba 			ret = tree_mod_log_insert_move(parent, slot, slot + 1,
4863a446a979SDavid Sterba 					nritems - slot - 1);
4864bf1d3425SDavid Sterba 			BUG_ON(ret < 0);
4865bf1d3425SDavid Sterba 		}
48665f39d397SChris Mason 		memmove_extent_buffer(parent,
48675f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot),
48685f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot + 1),
4869d6025579SChris Mason 			      sizeof(struct btrfs_key_ptr) *
4870d6025579SChris Mason 			      (nritems - slot - 1));
487157ba86c0SChris Mason 	} else if (level) {
4872e09c2efeSDavid Sterba 		ret = tree_mod_log_insert_key(parent, slot, MOD_LOG_KEY_REMOVE,
4873e09c2efeSDavid Sterba 				GFP_NOFS);
487457ba86c0SChris Mason 		BUG_ON(ret < 0);
4875be0e5c09SChris Mason 	}
4876f3ea38daSJan Schmidt 
48777518a238SChris Mason 	nritems--;
48785f39d397SChris Mason 	btrfs_set_header_nritems(parent, nritems);
48797518a238SChris Mason 	if (nritems == 0 && parent == root->node) {
48805f39d397SChris Mason 		BUG_ON(btrfs_header_level(root->node) != 1);
4881eb60ceacSChris Mason 		/* just turn the root into a leaf and break */
48825f39d397SChris Mason 		btrfs_set_header_level(root->node, 0);
4883bb803951SChris Mason 	} else if (slot == 0) {
48845f39d397SChris Mason 		struct btrfs_disk_key disk_key;
48855f39d397SChris Mason 
48865f39d397SChris Mason 		btrfs_node_key(parent, &disk_key, 0);
4887b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, level + 1);
4888be0e5c09SChris Mason 	}
4889d6025579SChris Mason 	btrfs_mark_buffer_dirty(parent);
4890be0e5c09SChris Mason }
4891be0e5c09SChris Mason 
489274123bd7SChris Mason /*
4893323ac95bSChris Mason  * a helper function to delete the leaf pointed to by path->slots[1] and
48945d4f98a2SYan Zheng  * path->nodes[1].
4895323ac95bSChris Mason  *
4896323ac95bSChris Mason  * This deletes the pointer in path->nodes[1] and frees the leaf
4897323ac95bSChris Mason  * block extent.  zero is returned if it all worked out, < 0 otherwise.
4898323ac95bSChris Mason  *
4899323ac95bSChris Mason  * The path must have already been setup for deleting the leaf, including
4900323ac95bSChris Mason  * all the proper balancing.  path->nodes[1] must be locked.
4901323ac95bSChris Mason  */
4902143bede5SJeff Mahoney static noinline void btrfs_del_leaf(struct btrfs_trans_handle *trans,
4903323ac95bSChris Mason 				    struct btrfs_root *root,
49045d4f98a2SYan Zheng 				    struct btrfs_path *path,
49055d4f98a2SYan Zheng 				    struct extent_buffer *leaf)
4906323ac95bSChris Mason {
49075d4f98a2SYan Zheng 	WARN_ON(btrfs_header_generation(leaf) != trans->transid);
4908afe5fea7STsutomu Itoh 	del_ptr(root, path, 1, path->slots[1]);
4909323ac95bSChris Mason 
49104d081c41SChris Mason 	/*
49114d081c41SChris Mason 	 * btrfs_free_extent is expensive, we want to make sure we
49124d081c41SChris Mason 	 * aren't holding any locks when we call it
49134d081c41SChris Mason 	 */
49144d081c41SChris Mason 	btrfs_unlock_up_safe(path, 0);
49154d081c41SChris Mason 
4916f0486c68SYan, Zheng 	root_sub_used(root, leaf->len);
4917f0486c68SYan, Zheng 
491867439dadSDavid Sterba 	atomic_inc(&leaf->refs);
49195581a51aSJan Schmidt 	btrfs_free_tree_block(trans, root, leaf, 0, 1);
49203083ee2eSJosef Bacik 	free_extent_buffer_stale(leaf);
4921323ac95bSChris Mason }
4922323ac95bSChris Mason /*
492374123bd7SChris Mason  * delete the item at the leaf level in path.  If that empties
492474123bd7SChris Mason  * the leaf, remove it from the tree
492574123bd7SChris Mason  */
492685e21bacSChris Mason int btrfs_del_items(struct btrfs_trans_handle *trans, struct btrfs_root *root,
492785e21bacSChris Mason 		    struct btrfs_path *path, int slot, int nr)
4928be0e5c09SChris Mason {
49290b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
49305f39d397SChris Mason 	struct extent_buffer *leaf;
49315f39d397SChris Mason 	struct btrfs_item *item;
4932ce0eac2aSAlexandru Moise 	u32 last_off;
4933ce0eac2aSAlexandru Moise 	u32 dsize = 0;
4934aa5d6bedSChris Mason 	int ret = 0;
4935aa5d6bedSChris Mason 	int wret;
493685e21bacSChris Mason 	int i;
49377518a238SChris Mason 	u32 nritems;
4938be0e5c09SChris Mason 
49395f39d397SChris Mason 	leaf = path->nodes[0];
494085e21bacSChris Mason 	last_off = btrfs_item_offset_nr(leaf, slot + nr - 1);
494185e21bacSChris Mason 
494285e21bacSChris Mason 	for (i = 0; i < nr; i++)
494385e21bacSChris Mason 		dsize += btrfs_item_size_nr(leaf, slot + i);
494485e21bacSChris Mason 
49455f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
4946be0e5c09SChris Mason 
494785e21bacSChris Mason 	if (slot + nr != nritems) {
49488f881e8cSDavid Sterba 		int data_end = leaf_data_end(leaf);
4949c82f823cSDavid Sterba 		struct btrfs_map_token token;
49505f39d397SChris Mason 
49513d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
4952d6025579SChris Mason 			      data_end + dsize,
49533d9ec8c4SNikolay Borisov 			      BTRFS_LEAF_DATA_OFFSET + data_end,
495485e21bacSChris Mason 			      last_off - data_end);
49555f39d397SChris Mason 
4956c82f823cSDavid Sterba 		btrfs_init_map_token(&token, leaf);
495785e21bacSChris Mason 		for (i = slot + nr; i < nritems; i++) {
49585f39d397SChris Mason 			u32 ioff;
4959db94535dSChris Mason 
4960dd3cc16bSRoss Kirk 			item = btrfs_item_nr(i);
4961cfed81a0SChris Mason 			ioff = btrfs_token_item_offset(leaf, item, &token);
4962cfed81a0SChris Mason 			btrfs_set_token_item_offset(leaf, item,
4963cfed81a0SChris Mason 						    ioff + dsize, &token);
49640783fcfcSChris Mason 		}
4965db94535dSChris Mason 
49665f39d397SChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot),
496785e21bacSChris Mason 			      btrfs_item_nr_offset(slot + nr),
49680783fcfcSChris Mason 			      sizeof(struct btrfs_item) *
496985e21bacSChris Mason 			      (nritems - slot - nr));
4970be0e5c09SChris Mason 	}
497185e21bacSChris Mason 	btrfs_set_header_nritems(leaf, nritems - nr);
497285e21bacSChris Mason 	nritems -= nr;
49735f39d397SChris Mason 
497474123bd7SChris Mason 	/* delete the leaf if we've emptied it */
49757518a238SChris Mason 	if (nritems == 0) {
49765f39d397SChris Mason 		if (leaf == root->node) {
49775f39d397SChris Mason 			btrfs_set_header_level(leaf, 0);
49789a8dd150SChris Mason 		} else {
4979f0486c68SYan, Zheng 			btrfs_set_path_blocking(path);
49806a884d7dSDavid Sterba 			btrfs_clean_tree_block(leaf);
4981143bede5SJeff Mahoney 			btrfs_del_leaf(trans, root, path, leaf);
49829a8dd150SChris Mason 		}
4983be0e5c09SChris Mason 	} else {
49847518a238SChris Mason 		int used = leaf_space_used(leaf, 0, nritems);
4985aa5d6bedSChris Mason 		if (slot == 0) {
49865f39d397SChris Mason 			struct btrfs_disk_key disk_key;
49875f39d397SChris Mason 
49885f39d397SChris Mason 			btrfs_item_key(leaf, &disk_key, 0);
4989b167fa91SNikolay Borisov 			fixup_low_keys(path, &disk_key, 1);
4990aa5d6bedSChris Mason 		}
4991aa5d6bedSChris Mason 
499274123bd7SChris Mason 		/* delete the leaf if it is mostly empty */
49930b246afaSJeff Mahoney 		if (used < BTRFS_LEAF_DATA_SIZE(fs_info) / 3) {
4994be0e5c09SChris Mason 			/* push_leaf_left fixes the path.
4995be0e5c09SChris Mason 			 * make sure the path still points to our leaf
4996be0e5c09SChris Mason 			 * for possible call to del_ptr below
4997be0e5c09SChris Mason 			 */
49984920c9acSChris Mason 			slot = path->slots[1];
499967439dadSDavid Sterba 			atomic_inc(&leaf->refs);
50005f39d397SChris Mason 
5001b9473439SChris Mason 			btrfs_set_path_blocking(path);
500299d8f83cSChris Mason 			wret = push_leaf_left(trans, root, path, 1, 1,
500399d8f83cSChris Mason 					      1, (u32)-1);
500454aa1f4dSChris Mason 			if (wret < 0 && wret != -ENOSPC)
5005aa5d6bedSChris Mason 				ret = wret;
50065f39d397SChris Mason 
50075f39d397SChris Mason 			if (path->nodes[0] == leaf &&
50085f39d397SChris Mason 			    btrfs_header_nritems(leaf)) {
500999d8f83cSChris Mason 				wret = push_leaf_right(trans, root, path, 1,
501099d8f83cSChris Mason 						       1, 1, 0);
501154aa1f4dSChris Mason 				if (wret < 0 && wret != -ENOSPC)
5012aa5d6bedSChris Mason 					ret = wret;
5013aa5d6bedSChris Mason 			}
50145f39d397SChris Mason 
50155f39d397SChris Mason 			if (btrfs_header_nritems(leaf) == 0) {
5016323ac95bSChris Mason 				path->slots[1] = slot;
5017143bede5SJeff Mahoney 				btrfs_del_leaf(trans, root, path, leaf);
50185f39d397SChris Mason 				free_extent_buffer(leaf);
5019143bede5SJeff Mahoney 				ret = 0;
50205de08d7dSChris Mason 			} else {
5021925baeddSChris Mason 				/* if we're still in the path, make sure
5022925baeddSChris Mason 				 * we're dirty.  Otherwise, one of the
5023925baeddSChris Mason 				 * push_leaf functions must have already
5024925baeddSChris Mason 				 * dirtied this buffer
5025925baeddSChris Mason 				 */
5026925baeddSChris Mason 				if (path->nodes[0] == leaf)
50275f39d397SChris Mason 					btrfs_mark_buffer_dirty(leaf);
50285f39d397SChris Mason 				free_extent_buffer(leaf);
5029be0e5c09SChris Mason 			}
5030d5719762SChris Mason 		} else {
50315f39d397SChris Mason 			btrfs_mark_buffer_dirty(leaf);
5032be0e5c09SChris Mason 		}
50339a8dd150SChris Mason 	}
5034aa5d6bedSChris Mason 	return ret;
50359a8dd150SChris Mason }
50369a8dd150SChris Mason 
503797571fd0SChris Mason /*
5038925baeddSChris Mason  * search the tree again to find a leaf with lesser keys
50397bb86316SChris Mason  * returns 0 if it found something or 1 if there are no lesser leaves.
50407bb86316SChris Mason  * returns < 0 on io errors.
5041d352ac68SChris Mason  *
5042d352ac68SChris Mason  * This may release the path, and so you may lose any locks held at the
5043d352ac68SChris Mason  * time you call it.
50447bb86316SChris Mason  */
504516e7549fSJosef Bacik int btrfs_prev_leaf(struct btrfs_root *root, struct btrfs_path *path)
50467bb86316SChris Mason {
5047925baeddSChris Mason 	struct btrfs_key key;
5048925baeddSChris Mason 	struct btrfs_disk_key found_key;
5049925baeddSChris Mason 	int ret;
50507bb86316SChris Mason 
5051925baeddSChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, 0);
5052925baeddSChris Mason 
5053e8b0d724SFilipe David Borba Manana 	if (key.offset > 0) {
5054925baeddSChris Mason 		key.offset--;
5055e8b0d724SFilipe David Borba Manana 	} else if (key.type > 0) {
5056925baeddSChris Mason 		key.type--;
5057e8b0d724SFilipe David Borba Manana 		key.offset = (u64)-1;
5058e8b0d724SFilipe David Borba Manana 	} else if (key.objectid > 0) {
5059925baeddSChris Mason 		key.objectid--;
5060e8b0d724SFilipe David Borba Manana 		key.type = (u8)-1;
5061e8b0d724SFilipe David Borba Manana 		key.offset = (u64)-1;
5062e8b0d724SFilipe David Borba Manana 	} else {
50637bb86316SChris Mason 		return 1;
5064e8b0d724SFilipe David Borba Manana 	}
50657bb86316SChris Mason 
5066b3b4aa74SDavid Sterba 	btrfs_release_path(path);
5067925baeddSChris Mason 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5068925baeddSChris Mason 	if (ret < 0)
5069925baeddSChris Mason 		return ret;
5070925baeddSChris Mason 	btrfs_item_key(path->nodes[0], &found_key, 0);
5071925baeddSChris Mason 	ret = comp_keys(&found_key, &key);
5072337c6f68SFilipe Manana 	/*
5073337c6f68SFilipe Manana 	 * We might have had an item with the previous key in the tree right
5074337c6f68SFilipe Manana 	 * before we released our path. And after we released our path, that
5075337c6f68SFilipe Manana 	 * item might have been pushed to the first slot (0) of the leaf we
5076337c6f68SFilipe Manana 	 * were holding due to a tree balance. Alternatively, an item with the
5077337c6f68SFilipe Manana 	 * previous key can exist as the only element of a leaf (big fat item).
5078337c6f68SFilipe Manana 	 * Therefore account for these 2 cases, so that our callers (like
5079337c6f68SFilipe Manana 	 * btrfs_previous_item) don't miss an existing item with a key matching
5080337c6f68SFilipe Manana 	 * the previous key we computed above.
5081337c6f68SFilipe Manana 	 */
5082337c6f68SFilipe Manana 	if (ret <= 0)
50837bb86316SChris Mason 		return 0;
5084925baeddSChris Mason 	return 1;
50857bb86316SChris Mason }
50867bb86316SChris Mason 
50873f157a2fSChris Mason /*
50883f157a2fSChris Mason  * A helper function to walk down the tree starting at min_key, and looking
5089de78b51aSEric Sandeen  * for nodes or leaves that are have a minimum transaction id.
5090de78b51aSEric Sandeen  * This is used by the btree defrag code, and tree logging
50913f157a2fSChris Mason  *
50923f157a2fSChris Mason  * This does not cow, but it does stuff the starting key it finds back
50933f157a2fSChris Mason  * into min_key, so you can call btrfs_search_slot with cow=1 on the
50943f157a2fSChris Mason  * key and get a writable path.
50953f157a2fSChris Mason  *
50963f157a2fSChris Mason  * This honors path->lowest_level to prevent descent past a given level
50973f157a2fSChris Mason  * of the tree.
50983f157a2fSChris Mason  *
5099d352ac68SChris Mason  * min_trans indicates the oldest transaction that you are interested
5100d352ac68SChris Mason  * in walking through.  Any nodes or leaves older than min_trans are
5101d352ac68SChris Mason  * skipped over (without reading them).
5102d352ac68SChris Mason  *
51033f157a2fSChris Mason  * returns zero if something useful was found, < 0 on error and 1 if there
51043f157a2fSChris Mason  * was nothing in the tree that matched the search criteria.
51053f157a2fSChris Mason  */
51063f157a2fSChris Mason int btrfs_search_forward(struct btrfs_root *root, struct btrfs_key *min_key,
5107de78b51aSEric Sandeen 			 struct btrfs_path *path,
51083f157a2fSChris Mason 			 u64 min_trans)
51093f157a2fSChris Mason {
51103f157a2fSChris Mason 	struct extent_buffer *cur;
51113f157a2fSChris Mason 	struct btrfs_key found_key;
51123f157a2fSChris Mason 	int slot;
51139652480bSYan 	int sret;
51143f157a2fSChris Mason 	u32 nritems;
51153f157a2fSChris Mason 	int level;
51163f157a2fSChris Mason 	int ret = 1;
5117f98de9b9SFilipe Manana 	int keep_locks = path->keep_locks;
51183f157a2fSChris Mason 
5119f98de9b9SFilipe Manana 	path->keep_locks = 1;
51203f157a2fSChris Mason again:
5121bd681513SChris Mason 	cur = btrfs_read_lock_root_node(root);
51223f157a2fSChris Mason 	level = btrfs_header_level(cur);
5123e02119d5SChris Mason 	WARN_ON(path->nodes[level]);
51243f157a2fSChris Mason 	path->nodes[level] = cur;
5125bd681513SChris Mason 	path->locks[level] = BTRFS_READ_LOCK;
51263f157a2fSChris Mason 
51273f157a2fSChris Mason 	if (btrfs_header_generation(cur) < min_trans) {
51283f157a2fSChris Mason 		ret = 1;
51293f157a2fSChris Mason 		goto out;
51303f157a2fSChris Mason 	}
51313f157a2fSChris Mason 	while (1) {
51323f157a2fSChris Mason 		nritems = btrfs_header_nritems(cur);
51333f157a2fSChris Mason 		level = btrfs_header_level(cur);
5134a74b35ecSNikolay Borisov 		sret = btrfs_bin_search(cur, min_key, level, &slot);
5135cbca7d59SFilipe Manana 		if (sret < 0) {
5136cbca7d59SFilipe Manana 			ret = sret;
5137cbca7d59SFilipe Manana 			goto out;
5138cbca7d59SFilipe Manana 		}
51393f157a2fSChris Mason 
5140323ac95bSChris Mason 		/* at the lowest level, we're done, setup the path and exit */
5141323ac95bSChris Mason 		if (level == path->lowest_level) {
5142e02119d5SChris Mason 			if (slot >= nritems)
5143e02119d5SChris Mason 				goto find_next_key;
51443f157a2fSChris Mason 			ret = 0;
51453f157a2fSChris Mason 			path->slots[level] = slot;
51463f157a2fSChris Mason 			btrfs_item_key_to_cpu(cur, &found_key, slot);
51473f157a2fSChris Mason 			goto out;
51483f157a2fSChris Mason 		}
51499652480bSYan 		if (sret && slot > 0)
51509652480bSYan 			slot--;
51513f157a2fSChris Mason 		/*
5152de78b51aSEric Sandeen 		 * check this node pointer against the min_trans parameters.
5153de78b51aSEric Sandeen 		 * If it is too old, old, skip to the next one.
51543f157a2fSChris Mason 		 */
51553f157a2fSChris Mason 		while (slot < nritems) {
51563f157a2fSChris Mason 			u64 gen;
5157e02119d5SChris Mason 
51583f157a2fSChris Mason 			gen = btrfs_node_ptr_generation(cur, slot);
51593f157a2fSChris Mason 			if (gen < min_trans) {
51603f157a2fSChris Mason 				slot++;
51613f157a2fSChris Mason 				continue;
51623f157a2fSChris Mason 			}
51633f157a2fSChris Mason 			break;
51643f157a2fSChris Mason 		}
5165e02119d5SChris Mason find_next_key:
51663f157a2fSChris Mason 		/*
51673f157a2fSChris Mason 		 * we didn't find a candidate key in this node, walk forward
51683f157a2fSChris Mason 		 * and find another one
51693f157a2fSChris Mason 		 */
51703f157a2fSChris Mason 		if (slot >= nritems) {
5171e02119d5SChris Mason 			path->slots[level] = slot;
5172b4ce94deSChris Mason 			btrfs_set_path_blocking(path);
5173e02119d5SChris Mason 			sret = btrfs_find_next_key(root, path, min_key, level,
5174de78b51aSEric Sandeen 						  min_trans);
5175e02119d5SChris Mason 			if (sret == 0) {
5176b3b4aa74SDavid Sterba 				btrfs_release_path(path);
51773f157a2fSChris Mason 				goto again;
51783f157a2fSChris Mason 			} else {
51793f157a2fSChris Mason 				goto out;
51803f157a2fSChris Mason 			}
51813f157a2fSChris Mason 		}
51823f157a2fSChris Mason 		/* save our key for returning back */
51833f157a2fSChris Mason 		btrfs_node_key_to_cpu(cur, &found_key, slot);
51843f157a2fSChris Mason 		path->slots[level] = slot;
51853f157a2fSChris Mason 		if (level == path->lowest_level) {
51863f157a2fSChris Mason 			ret = 0;
51873f157a2fSChris Mason 			goto out;
51883f157a2fSChris Mason 		}
5189b4ce94deSChris Mason 		btrfs_set_path_blocking(path);
51904b231ae4SDavid Sterba 		cur = btrfs_read_node_slot(cur, slot);
5191fb770ae4SLiu Bo 		if (IS_ERR(cur)) {
5192fb770ae4SLiu Bo 			ret = PTR_ERR(cur);
5193fb770ae4SLiu Bo 			goto out;
5194fb770ae4SLiu Bo 		}
51953f157a2fSChris Mason 
5196bd681513SChris Mason 		btrfs_tree_read_lock(cur);
5197b4ce94deSChris Mason 
5198bd681513SChris Mason 		path->locks[level - 1] = BTRFS_READ_LOCK;
51993f157a2fSChris Mason 		path->nodes[level - 1] = cur;
5200f7c79f30SChris Mason 		unlock_up(path, level, 1, 0, NULL);
52013f157a2fSChris Mason 	}
52023f157a2fSChris Mason out:
5203f98de9b9SFilipe Manana 	path->keep_locks = keep_locks;
5204f98de9b9SFilipe Manana 	if (ret == 0) {
5205f98de9b9SFilipe Manana 		btrfs_unlock_up_safe(path, path->lowest_level + 1);
5206b4ce94deSChris Mason 		btrfs_set_path_blocking(path);
5207f98de9b9SFilipe Manana 		memcpy(min_key, &found_key, sizeof(found_key));
5208f98de9b9SFilipe Manana 	}
52093f157a2fSChris Mason 	return ret;
52103f157a2fSChris Mason }
52113f157a2fSChris Mason 
52123f157a2fSChris Mason /*
52133f157a2fSChris Mason  * this is similar to btrfs_next_leaf, but does not try to preserve
52143f157a2fSChris Mason  * and fixup the path.  It looks for and returns the next key in the
5215de78b51aSEric Sandeen  * tree based on the current path and the min_trans parameters.
52163f157a2fSChris Mason  *
52173f157a2fSChris Mason  * 0 is returned if another key is found, < 0 if there are any errors
52183f157a2fSChris Mason  * and 1 is returned if there are no higher keys in the tree
52193f157a2fSChris Mason  *
52203f157a2fSChris Mason  * path->keep_locks should be set to 1 on the search made before
52213f157a2fSChris Mason  * calling this function.
52223f157a2fSChris Mason  */
5223e7a84565SChris Mason int btrfs_find_next_key(struct btrfs_root *root, struct btrfs_path *path,
5224de78b51aSEric Sandeen 			struct btrfs_key *key, int level, u64 min_trans)
5225e7a84565SChris Mason {
5226e7a84565SChris Mason 	int slot;
5227e7a84565SChris Mason 	struct extent_buffer *c;
5228e7a84565SChris Mason 
52296a9fb468SJosef Bacik 	WARN_ON(!path->keep_locks && !path->skip_locking);
5230e7a84565SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
5231e7a84565SChris Mason 		if (!path->nodes[level])
5232e7a84565SChris Mason 			return 1;
5233e7a84565SChris Mason 
5234e7a84565SChris Mason 		slot = path->slots[level] + 1;
5235e7a84565SChris Mason 		c = path->nodes[level];
52363f157a2fSChris Mason next:
5237e7a84565SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
523833c66f43SYan Zheng 			int ret;
523933c66f43SYan Zheng 			int orig_lowest;
524033c66f43SYan Zheng 			struct btrfs_key cur_key;
524133c66f43SYan Zheng 			if (level + 1 >= BTRFS_MAX_LEVEL ||
524233c66f43SYan Zheng 			    !path->nodes[level + 1])
5243e7a84565SChris Mason 				return 1;
524433c66f43SYan Zheng 
52456a9fb468SJosef Bacik 			if (path->locks[level + 1] || path->skip_locking) {
524633c66f43SYan Zheng 				level++;
5247e7a84565SChris Mason 				continue;
5248e7a84565SChris Mason 			}
524933c66f43SYan Zheng 
525033c66f43SYan Zheng 			slot = btrfs_header_nritems(c) - 1;
525133c66f43SYan Zheng 			if (level == 0)
525233c66f43SYan Zheng 				btrfs_item_key_to_cpu(c, &cur_key, slot);
525333c66f43SYan Zheng 			else
525433c66f43SYan Zheng 				btrfs_node_key_to_cpu(c, &cur_key, slot);
525533c66f43SYan Zheng 
525633c66f43SYan Zheng 			orig_lowest = path->lowest_level;
5257b3b4aa74SDavid Sterba 			btrfs_release_path(path);
525833c66f43SYan Zheng 			path->lowest_level = level;
525933c66f43SYan Zheng 			ret = btrfs_search_slot(NULL, root, &cur_key, path,
526033c66f43SYan Zheng 						0, 0);
526133c66f43SYan Zheng 			path->lowest_level = orig_lowest;
526233c66f43SYan Zheng 			if (ret < 0)
526333c66f43SYan Zheng 				return ret;
526433c66f43SYan Zheng 
526533c66f43SYan Zheng 			c = path->nodes[level];
526633c66f43SYan Zheng 			slot = path->slots[level];
526733c66f43SYan Zheng 			if (ret == 0)
526833c66f43SYan Zheng 				slot++;
526933c66f43SYan Zheng 			goto next;
527033c66f43SYan Zheng 		}
527133c66f43SYan Zheng 
5272e7a84565SChris Mason 		if (level == 0)
5273e7a84565SChris Mason 			btrfs_item_key_to_cpu(c, key, slot);
52743f157a2fSChris Mason 		else {
52753f157a2fSChris Mason 			u64 gen = btrfs_node_ptr_generation(c, slot);
52763f157a2fSChris Mason 
52773f157a2fSChris Mason 			if (gen < min_trans) {
52783f157a2fSChris Mason 				slot++;
52793f157a2fSChris Mason 				goto next;
52803f157a2fSChris Mason 			}
5281e7a84565SChris Mason 			btrfs_node_key_to_cpu(c, key, slot);
52823f157a2fSChris Mason 		}
5283e7a84565SChris Mason 		return 0;
5284e7a84565SChris Mason 	}
5285e7a84565SChris Mason 	return 1;
5286e7a84565SChris Mason }
5287e7a84565SChris Mason 
52887bb86316SChris Mason /*
5289925baeddSChris Mason  * search the tree again to find a leaf with greater keys
52900f70abe2SChris Mason  * returns 0 if it found something or 1 if there are no greater leaves.
52910f70abe2SChris Mason  * returns < 0 on io errors.
529297571fd0SChris Mason  */
5293234b63a0SChris Mason int btrfs_next_leaf(struct btrfs_root *root, struct btrfs_path *path)
5294d97e63b6SChris Mason {
52953d7806ecSJan Schmidt 	return btrfs_next_old_leaf(root, path, 0);
52963d7806ecSJan Schmidt }
52973d7806ecSJan Schmidt 
52983d7806ecSJan Schmidt int btrfs_next_old_leaf(struct btrfs_root *root, struct btrfs_path *path,
52993d7806ecSJan Schmidt 			u64 time_seq)
53003d7806ecSJan Schmidt {
5301d97e63b6SChris Mason 	int slot;
53028e73f275SChris Mason 	int level;
53035f39d397SChris Mason 	struct extent_buffer *c;
53048e73f275SChris Mason 	struct extent_buffer *next;
5305925baeddSChris Mason 	struct btrfs_key key;
5306925baeddSChris Mason 	u32 nritems;
5307925baeddSChris Mason 	int ret;
53088e73f275SChris Mason 	int old_spinning = path->leave_spinning;
5309bd681513SChris Mason 	int next_rw_lock = 0;
5310925baeddSChris Mason 
5311925baeddSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
5312d397712bSChris Mason 	if (nritems == 0)
5313925baeddSChris Mason 		return 1;
5314925baeddSChris Mason 
53158e73f275SChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, nritems - 1);
53168e73f275SChris Mason again:
53178e73f275SChris Mason 	level = 1;
53188e73f275SChris Mason 	next = NULL;
5319bd681513SChris Mason 	next_rw_lock = 0;
5320b3b4aa74SDavid Sterba 	btrfs_release_path(path);
53218e73f275SChris Mason 
5322a2135011SChris Mason 	path->keep_locks = 1;
53238e73f275SChris Mason 	path->leave_spinning = 1;
53248e73f275SChris Mason 
53253d7806ecSJan Schmidt 	if (time_seq)
53263d7806ecSJan Schmidt 		ret = btrfs_search_old_slot(root, &key, path, time_seq);
53273d7806ecSJan Schmidt 	else
5328925baeddSChris Mason 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5329925baeddSChris Mason 	path->keep_locks = 0;
5330925baeddSChris Mason 
5331925baeddSChris Mason 	if (ret < 0)
5332925baeddSChris Mason 		return ret;
5333925baeddSChris Mason 
5334a2135011SChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
5335168fd7d2SChris Mason 	/*
5336168fd7d2SChris Mason 	 * by releasing the path above we dropped all our locks.  A balance
5337168fd7d2SChris Mason 	 * could have added more items next to the key that used to be
5338168fd7d2SChris Mason 	 * at the very end of the block.  So, check again here and
5339168fd7d2SChris Mason 	 * advance the path if there are now more items available.
5340168fd7d2SChris Mason 	 */
5341a2135011SChris Mason 	if (nritems > 0 && path->slots[0] < nritems - 1) {
5342e457afecSYan Zheng 		if (ret == 0)
5343168fd7d2SChris Mason 			path->slots[0]++;
53448e73f275SChris Mason 		ret = 0;
5345925baeddSChris Mason 		goto done;
5346925baeddSChris Mason 	}
53470b43e04fSLiu Bo 	/*
53480b43e04fSLiu Bo 	 * So the above check misses one case:
53490b43e04fSLiu Bo 	 * - after releasing the path above, someone has removed the item that
53500b43e04fSLiu Bo 	 *   used to be at the very end of the block, and balance between leafs
53510b43e04fSLiu Bo 	 *   gets another one with bigger key.offset to replace it.
53520b43e04fSLiu Bo 	 *
53530b43e04fSLiu Bo 	 * This one should be returned as well, or we can get leaf corruption
53540b43e04fSLiu Bo 	 * later(esp. in __btrfs_drop_extents()).
53550b43e04fSLiu Bo 	 *
53560b43e04fSLiu Bo 	 * And a bit more explanation about this check,
53570b43e04fSLiu Bo 	 * with ret > 0, the key isn't found, the path points to the slot
53580b43e04fSLiu Bo 	 * where it should be inserted, so the path->slots[0] item must be the
53590b43e04fSLiu Bo 	 * bigger one.
53600b43e04fSLiu Bo 	 */
53610b43e04fSLiu Bo 	if (nritems > 0 && ret > 0 && path->slots[0] == nritems - 1) {
53620b43e04fSLiu Bo 		ret = 0;
53630b43e04fSLiu Bo 		goto done;
53640b43e04fSLiu Bo 	}
5365d97e63b6SChris Mason 
5366234b63a0SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
53678e73f275SChris Mason 		if (!path->nodes[level]) {
53688e73f275SChris Mason 			ret = 1;
53698e73f275SChris Mason 			goto done;
53708e73f275SChris Mason 		}
53715f39d397SChris Mason 
5372d97e63b6SChris Mason 		slot = path->slots[level] + 1;
5373d97e63b6SChris Mason 		c = path->nodes[level];
53745f39d397SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
5375d97e63b6SChris Mason 			level++;
53768e73f275SChris Mason 			if (level == BTRFS_MAX_LEVEL) {
53778e73f275SChris Mason 				ret = 1;
53788e73f275SChris Mason 				goto done;
53798e73f275SChris Mason 			}
5380d97e63b6SChris Mason 			continue;
5381d97e63b6SChris Mason 		}
53825f39d397SChris Mason 
5383925baeddSChris Mason 		if (next) {
5384bd681513SChris Mason 			btrfs_tree_unlock_rw(next, next_rw_lock);
53855f39d397SChris Mason 			free_extent_buffer(next);
5386925baeddSChris Mason 		}
53875f39d397SChris Mason 
53888e73f275SChris Mason 		next = c;
5389bd681513SChris Mason 		next_rw_lock = path->locks[level];
5390d07b8528SLiu Bo 		ret = read_block_for_search(root, path, &next, level,
5391cda79c54SDavid Sterba 					    slot, &key);
53928e73f275SChris Mason 		if (ret == -EAGAIN)
53938e73f275SChris Mason 			goto again;
53945f39d397SChris Mason 
539576a05b35SChris Mason 		if (ret < 0) {
5396b3b4aa74SDavid Sterba 			btrfs_release_path(path);
539776a05b35SChris Mason 			goto done;
539876a05b35SChris Mason 		}
539976a05b35SChris Mason 
54005cd57b2cSChris Mason 		if (!path->skip_locking) {
5401bd681513SChris Mason 			ret = btrfs_try_tree_read_lock(next);
5402d42244a0SJan Schmidt 			if (!ret && time_seq) {
5403d42244a0SJan Schmidt 				/*
5404d42244a0SJan Schmidt 				 * If we don't get the lock, we may be racing
5405d42244a0SJan Schmidt 				 * with push_leaf_left, holding that lock while
5406d42244a0SJan Schmidt 				 * itself waiting for the leaf we've currently
5407d42244a0SJan Schmidt 				 * locked. To solve this situation, we give up
5408d42244a0SJan Schmidt 				 * on our lock and cycle.
5409d42244a0SJan Schmidt 				 */
5410cf538830SJan Schmidt 				free_extent_buffer(next);
5411d42244a0SJan Schmidt 				btrfs_release_path(path);
5412d42244a0SJan Schmidt 				cond_resched();
5413d42244a0SJan Schmidt 				goto again;
5414d42244a0SJan Schmidt 			}
54158e73f275SChris Mason 			if (!ret) {
54168e73f275SChris Mason 				btrfs_set_path_blocking(path);
5417bd681513SChris Mason 				btrfs_tree_read_lock(next);
54188e73f275SChris Mason 			}
5419bd681513SChris Mason 			next_rw_lock = BTRFS_READ_LOCK;
5420bd681513SChris Mason 		}
5421d97e63b6SChris Mason 		break;
5422d97e63b6SChris Mason 	}
5423d97e63b6SChris Mason 	path->slots[level] = slot;
5424d97e63b6SChris Mason 	while (1) {
5425d97e63b6SChris Mason 		level--;
5426d97e63b6SChris Mason 		c = path->nodes[level];
5427925baeddSChris Mason 		if (path->locks[level])
5428bd681513SChris Mason 			btrfs_tree_unlock_rw(c, path->locks[level]);
54298e73f275SChris Mason 
54305f39d397SChris Mason 		free_extent_buffer(c);
5431d97e63b6SChris Mason 		path->nodes[level] = next;
5432d97e63b6SChris Mason 		path->slots[level] = 0;
5433a74a4b97SChris Mason 		if (!path->skip_locking)
5434bd681513SChris Mason 			path->locks[level] = next_rw_lock;
5435d97e63b6SChris Mason 		if (!level)
5436d97e63b6SChris Mason 			break;
5437b4ce94deSChris Mason 
5438d07b8528SLiu Bo 		ret = read_block_for_search(root, path, &next, level,
5439cda79c54SDavid Sterba 					    0, &key);
54408e73f275SChris Mason 		if (ret == -EAGAIN)
54418e73f275SChris Mason 			goto again;
54428e73f275SChris Mason 
544376a05b35SChris Mason 		if (ret < 0) {
5444b3b4aa74SDavid Sterba 			btrfs_release_path(path);
544576a05b35SChris Mason 			goto done;
544676a05b35SChris Mason 		}
544776a05b35SChris Mason 
54485cd57b2cSChris Mason 		if (!path->skip_locking) {
5449bd681513SChris Mason 			ret = btrfs_try_tree_read_lock(next);
54508e73f275SChris Mason 			if (!ret) {
54518e73f275SChris Mason 				btrfs_set_path_blocking(path);
5452bd681513SChris Mason 				btrfs_tree_read_lock(next);
54538e73f275SChris Mason 			}
5454bd681513SChris Mason 			next_rw_lock = BTRFS_READ_LOCK;
5455bd681513SChris Mason 		}
5456d97e63b6SChris Mason 	}
54578e73f275SChris Mason 	ret = 0;
5458925baeddSChris Mason done:
5459f7c79f30SChris Mason 	unlock_up(path, 0, 1, 0, NULL);
54608e73f275SChris Mason 	path->leave_spinning = old_spinning;
54618e73f275SChris Mason 	if (!old_spinning)
54628e73f275SChris Mason 		btrfs_set_path_blocking(path);
54638e73f275SChris Mason 
54648e73f275SChris Mason 	return ret;
5465d97e63b6SChris Mason }
54660b86a832SChris Mason 
54673f157a2fSChris Mason /*
54683f157a2fSChris Mason  * this uses btrfs_prev_leaf to walk backwards in the tree, and keeps
54693f157a2fSChris Mason  * searching until it gets past min_objectid or finds an item of 'type'
54703f157a2fSChris Mason  *
54713f157a2fSChris Mason  * returns 0 if something is found, 1 if nothing was found and < 0 on error
54723f157a2fSChris Mason  */
54730b86a832SChris Mason int btrfs_previous_item(struct btrfs_root *root,
54740b86a832SChris Mason 			struct btrfs_path *path, u64 min_objectid,
54750b86a832SChris Mason 			int type)
54760b86a832SChris Mason {
54770b86a832SChris Mason 	struct btrfs_key found_key;
54780b86a832SChris Mason 	struct extent_buffer *leaf;
5479e02119d5SChris Mason 	u32 nritems;
54800b86a832SChris Mason 	int ret;
54810b86a832SChris Mason 
54820b86a832SChris Mason 	while (1) {
54830b86a832SChris Mason 		if (path->slots[0] == 0) {
5484b4ce94deSChris Mason 			btrfs_set_path_blocking(path);
54850b86a832SChris Mason 			ret = btrfs_prev_leaf(root, path);
54860b86a832SChris Mason 			if (ret != 0)
54870b86a832SChris Mason 				return ret;
54880b86a832SChris Mason 		} else {
54890b86a832SChris Mason 			path->slots[0]--;
54900b86a832SChris Mason 		}
54910b86a832SChris Mason 		leaf = path->nodes[0];
5492e02119d5SChris Mason 		nritems = btrfs_header_nritems(leaf);
5493e02119d5SChris Mason 		if (nritems == 0)
5494e02119d5SChris Mason 			return 1;
5495e02119d5SChris Mason 		if (path->slots[0] == nritems)
5496e02119d5SChris Mason 			path->slots[0]--;
5497e02119d5SChris Mason 
54980b86a832SChris Mason 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5499e02119d5SChris Mason 		if (found_key.objectid < min_objectid)
5500e02119d5SChris Mason 			break;
55010a4eefbbSYan Zheng 		if (found_key.type == type)
55020a4eefbbSYan Zheng 			return 0;
5503e02119d5SChris Mason 		if (found_key.objectid == min_objectid &&
5504e02119d5SChris Mason 		    found_key.type < type)
5505e02119d5SChris Mason 			break;
55060b86a832SChris Mason 	}
55070b86a832SChris Mason 	return 1;
55080b86a832SChris Mason }
5509ade2e0b3SWang Shilong 
5510ade2e0b3SWang Shilong /*
5511ade2e0b3SWang Shilong  * search in extent tree to find a previous Metadata/Data extent item with
5512ade2e0b3SWang Shilong  * min objecitd.
5513ade2e0b3SWang Shilong  *
5514ade2e0b3SWang Shilong  * returns 0 if something is found, 1 if nothing was found and < 0 on error
5515ade2e0b3SWang Shilong  */
5516ade2e0b3SWang Shilong int btrfs_previous_extent_item(struct btrfs_root *root,
5517ade2e0b3SWang Shilong 			struct btrfs_path *path, u64 min_objectid)
5518ade2e0b3SWang Shilong {
5519ade2e0b3SWang Shilong 	struct btrfs_key found_key;
5520ade2e0b3SWang Shilong 	struct extent_buffer *leaf;
5521ade2e0b3SWang Shilong 	u32 nritems;
5522ade2e0b3SWang Shilong 	int ret;
5523ade2e0b3SWang Shilong 
5524ade2e0b3SWang Shilong 	while (1) {
5525ade2e0b3SWang Shilong 		if (path->slots[0] == 0) {
5526ade2e0b3SWang Shilong 			btrfs_set_path_blocking(path);
5527ade2e0b3SWang Shilong 			ret = btrfs_prev_leaf(root, path);
5528ade2e0b3SWang Shilong 			if (ret != 0)
5529ade2e0b3SWang Shilong 				return ret;
5530ade2e0b3SWang Shilong 		} else {
5531ade2e0b3SWang Shilong 			path->slots[0]--;
5532ade2e0b3SWang Shilong 		}
5533ade2e0b3SWang Shilong 		leaf = path->nodes[0];
5534ade2e0b3SWang Shilong 		nritems = btrfs_header_nritems(leaf);
5535ade2e0b3SWang Shilong 		if (nritems == 0)
5536ade2e0b3SWang Shilong 			return 1;
5537ade2e0b3SWang Shilong 		if (path->slots[0] == nritems)
5538ade2e0b3SWang Shilong 			path->slots[0]--;
5539ade2e0b3SWang Shilong 
5540ade2e0b3SWang Shilong 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5541ade2e0b3SWang Shilong 		if (found_key.objectid < min_objectid)
5542ade2e0b3SWang Shilong 			break;
5543ade2e0b3SWang Shilong 		if (found_key.type == BTRFS_EXTENT_ITEM_KEY ||
5544ade2e0b3SWang Shilong 		    found_key.type == BTRFS_METADATA_ITEM_KEY)
5545ade2e0b3SWang Shilong 			return 0;
5546ade2e0b3SWang Shilong 		if (found_key.objectid == min_objectid &&
5547ade2e0b3SWang Shilong 		    found_key.type < BTRFS_EXTENT_ITEM_KEY)
5548ade2e0b3SWang Shilong 			break;
5549ade2e0b3SWang Shilong 	}
5550ade2e0b3SWang Shilong 	return 1;
5551ade2e0b3SWang Shilong }
5552