xref: /openbmc/linux/fs/btrfs/ctree.c (revision 352ae07b)
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;
35b4e967beSDavid Sterba 	const char	*driver;
36af024ed2SJohannes Thumshirn } btrfs_csums[] = {
37af024ed2SJohannes Thumshirn 	[BTRFS_CSUM_TYPE_CRC32] = { .size = 4, .name = "crc32c" },
383951e7f0SJohannes Thumshirn 	[BTRFS_CSUM_TYPE_XXHASH] = { .size = 8, .name = "xxhash64" },
393831bf00SJohannes Thumshirn 	[BTRFS_CSUM_TYPE_SHA256] = { .size = 32, .name = "sha256" },
40352ae07bSDavid Sterba 	[BTRFS_CSUM_TYPE_BLAKE2] = { .size = 32, .name = "blake2b",
41352ae07bSDavid Sterba 				     .driver = "blake2b-256" },
42af024ed2SJohannes Thumshirn };
43af024ed2SJohannes Thumshirn 
44af024ed2SJohannes Thumshirn int btrfs_super_csum_size(const struct btrfs_super_block *s)
45af024ed2SJohannes Thumshirn {
46af024ed2SJohannes Thumshirn 	u16 t = btrfs_super_csum_type(s);
47af024ed2SJohannes Thumshirn 	/*
48af024ed2SJohannes Thumshirn 	 * csum type is validated at mount time
49af024ed2SJohannes Thumshirn 	 */
50af024ed2SJohannes Thumshirn 	return btrfs_csums[t].size;
51af024ed2SJohannes Thumshirn }
52af024ed2SJohannes Thumshirn 
53af024ed2SJohannes Thumshirn const char *btrfs_super_csum_name(u16 csum_type)
54af024ed2SJohannes Thumshirn {
55af024ed2SJohannes Thumshirn 	/* csum type is validated at mount time */
56af024ed2SJohannes Thumshirn 	return btrfs_csums[csum_type].name;
57af024ed2SJohannes Thumshirn }
58af024ed2SJohannes Thumshirn 
59b4e967beSDavid Sterba /*
60b4e967beSDavid Sterba  * Return driver name if defined, otherwise the name that's also a valid driver
61b4e967beSDavid Sterba  * name
62b4e967beSDavid Sterba  */
63b4e967beSDavid Sterba const char *btrfs_super_csum_driver(u16 csum_type)
64b4e967beSDavid Sterba {
65b4e967beSDavid Sterba 	/* csum type is validated at mount time */
66b4e967beSDavid Sterba 	return btrfs_csums[csum_type].driver ?:
67b4e967beSDavid Sterba 		btrfs_csums[csum_type].name;
68b4e967beSDavid Sterba }
69b4e967beSDavid Sterba 
70f7cea56cSDavid Sterba size_t __const btrfs_get_num_csums(void)
71f7cea56cSDavid Sterba {
72f7cea56cSDavid Sterba 	return ARRAY_SIZE(btrfs_csums);
73f7cea56cSDavid Sterba }
74f7cea56cSDavid Sterba 
752c90e5d6SChris Mason struct btrfs_path *btrfs_alloc_path(void)
762c90e5d6SChris Mason {
77e2c89907SMasahiro Yamada 	return kmem_cache_zalloc(btrfs_path_cachep, GFP_NOFS);
782c90e5d6SChris Mason }
792c90e5d6SChris Mason 
80d352ac68SChris Mason /* this also releases the path */
812c90e5d6SChris Mason void btrfs_free_path(struct btrfs_path *p)
822c90e5d6SChris Mason {
83ff175d57SJesper Juhl 	if (!p)
84ff175d57SJesper Juhl 		return;
85b3b4aa74SDavid Sterba 	btrfs_release_path(p);
862c90e5d6SChris Mason 	kmem_cache_free(btrfs_path_cachep, p);
872c90e5d6SChris Mason }
882c90e5d6SChris Mason 
89d352ac68SChris Mason /*
90d352ac68SChris Mason  * path release drops references on the extent buffers in the path
91d352ac68SChris Mason  * and it drops any locks held by this path
92d352ac68SChris Mason  *
93d352ac68SChris Mason  * It is safe to call this on paths that no locks or extent buffers held.
94d352ac68SChris Mason  */
95b3b4aa74SDavid Sterba noinline void btrfs_release_path(struct btrfs_path *p)
96eb60ceacSChris Mason {
97eb60ceacSChris Mason 	int i;
98a2135011SChris Mason 
99234b63a0SChris Mason 	for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
1003f157a2fSChris Mason 		p->slots[i] = 0;
101eb60ceacSChris Mason 		if (!p->nodes[i])
102925baeddSChris Mason 			continue;
103925baeddSChris Mason 		if (p->locks[i]) {
104bd681513SChris Mason 			btrfs_tree_unlock_rw(p->nodes[i], p->locks[i]);
105925baeddSChris Mason 			p->locks[i] = 0;
106925baeddSChris Mason 		}
1075f39d397SChris Mason 		free_extent_buffer(p->nodes[i]);
1083f157a2fSChris Mason 		p->nodes[i] = NULL;
109eb60ceacSChris Mason 	}
110eb60ceacSChris Mason }
111eb60ceacSChris Mason 
112d352ac68SChris Mason /*
113d352ac68SChris Mason  * safely gets a reference on the root node of a tree.  A lock
114d352ac68SChris Mason  * is not taken, so a concurrent writer may put a different node
115d352ac68SChris Mason  * at the root of the tree.  See btrfs_lock_root_node for the
116d352ac68SChris Mason  * looping required.
117d352ac68SChris Mason  *
118d352ac68SChris Mason  * The extent buffer returned by this has a reference taken, so
119d352ac68SChris Mason  * it won't disappear.  It may stop being the root of the tree
120d352ac68SChris Mason  * at any time because there are no locks held.
121d352ac68SChris Mason  */
122925baeddSChris Mason struct extent_buffer *btrfs_root_node(struct btrfs_root *root)
123925baeddSChris Mason {
124925baeddSChris Mason 	struct extent_buffer *eb;
125240f62c8SChris Mason 
1263083ee2eSJosef Bacik 	while (1) {
127240f62c8SChris Mason 		rcu_read_lock();
128240f62c8SChris Mason 		eb = rcu_dereference(root->node);
1293083ee2eSJosef Bacik 
1303083ee2eSJosef Bacik 		/*
1313083ee2eSJosef Bacik 		 * RCU really hurts here, we could free up the root node because
13201327610SNicholas D Steeves 		 * it was COWed but we may not get the new root node yet so do
1333083ee2eSJosef Bacik 		 * the inc_not_zero dance and if it doesn't work then
1343083ee2eSJosef Bacik 		 * synchronize_rcu and try again.
1353083ee2eSJosef Bacik 		 */
1363083ee2eSJosef Bacik 		if (atomic_inc_not_zero(&eb->refs)) {
137240f62c8SChris Mason 			rcu_read_unlock();
1383083ee2eSJosef Bacik 			break;
1393083ee2eSJosef Bacik 		}
1403083ee2eSJosef Bacik 		rcu_read_unlock();
1413083ee2eSJosef Bacik 		synchronize_rcu();
1423083ee2eSJosef Bacik 	}
143925baeddSChris Mason 	return eb;
144925baeddSChris Mason }
145925baeddSChris Mason 
146d352ac68SChris Mason /* loop around taking references on and locking the root node of the
147d352ac68SChris Mason  * tree until you end up with a lock on the root.  A locked buffer
148d352ac68SChris Mason  * is returned, with a reference held.
149d352ac68SChris Mason  */
150925baeddSChris Mason struct extent_buffer *btrfs_lock_root_node(struct btrfs_root *root)
151925baeddSChris Mason {
152925baeddSChris Mason 	struct extent_buffer *eb;
153925baeddSChris Mason 
154925baeddSChris Mason 	while (1) {
155925baeddSChris Mason 		eb = btrfs_root_node(root);
156925baeddSChris Mason 		btrfs_tree_lock(eb);
157240f62c8SChris Mason 		if (eb == root->node)
158925baeddSChris Mason 			break;
159925baeddSChris Mason 		btrfs_tree_unlock(eb);
160925baeddSChris Mason 		free_extent_buffer(eb);
161925baeddSChris Mason 	}
162925baeddSChris Mason 	return eb;
163925baeddSChris Mason }
164925baeddSChris Mason 
165bd681513SChris Mason /* loop around taking references on and locking the root node of the
166bd681513SChris Mason  * tree until you end up with a lock on the root.  A locked buffer
167bd681513SChris Mason  * is returned, with a reference held.
168bd681513SChris Mason  */
16984f7d8e6SJosef Bacik struct extent_buffer *btrfs_read_lock_root_node(struct btrfs_root *root)
170bd681513SChris Mason {
171bd681513SChris Mason 	struct extent_buffer *eb;
172bd681513SChris Mason 
173bd681513SChris Mason 	while (1) {
174bd681513SChris Mason 		eb = btrfs_root_node(root);
175bd681513SChris Mason 		btrfs_tree_read_lock(eb);
176bd681513SChris Mason 		if (eb == root->node)
177bd681513SChris Mason 			break;
178bd681513SChris Mason 		btrfs_tree_read_unlock(eb);
179bd681513SChris Mason 		free_extent_buffer(eb);
180bd681513SChris Mason 	}
181bd681513SChris Mason 	return eb;
182bd681513SChris Mason }
183bd681513SChris Mason 
184d352ac68SChris Mason /* cowonly root (everything not a reference counted cow subvolume), just get
185d352ac68SChris Mason  * put onto a simple dirty list.  transaction.c walks this to make sure they
186d352ac68SChris Mason  * get properly updated on disk.
187d352ac68SChris Mason  */
1880b86a832SChris Mason static void add_root_to_dirty_list(struct btrfs_root *root)
1890b86a832SChris Mason {
1900b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
1910b246afaSJeff Mahoney 
192e7070be1SJosef Bacik 	if (test_bit(BTRFS_ROOT_DIRTY, &root->state) ||
193e7070be1SJosef Bacik 	    !test_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state))
194e7070be1SJosef Bacik 		return;
195e7070be1SJosef Bacik 
1960b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
197e7070be1SJosef Bacik 	if (!test_and_set_bit(BTRFS_ROOT_DIRTY, &root->state)) {
198e7070be1SJosef Bacik 		/* Want the extent tree to be the last on the list */
1994fd786e6SMisono Tomohiro 		if (root->root_key.objectid == BTRFS_EXTENT_TREE_OBJECTID)
200e7070be1SJosef Bacik 			list_move_tail(&root->dirty_list,
2010b246afaSJeff Mahoney 				       &fs_info->dirty_cowonly_roots);
202e7070be1SJosef Bacik 		else
203e7070be1SJosef Bacik 			list_move(&root->dirty_list,
2040b246afaSJeff Mahoney 				  &fs_info->dirty_cowonly_roots);
2050b86a832SChris Mason 	}
2060b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
2070b86a832SChris Mason }
2080b86a832SChris Mason 
209d352ac68SChris Mason /*
210d352ac68SChris Mason  * used by snapshot creation to make a copy of a root for a tree with
211d352ac68SChris Mason  * a given objectid.  The buffer with the new root node is returned in
212d352ac68SChris Mason  * cow_ret, and this func returns zero on success or a negative error code.
213d352ac68SChris Mason  */
214be20aa9dSChris Mason int btrfs_copy_root(struct btrfs_trans_handle *trans,
215be20aa9dSChris Mason 		      struct btrfs_root *root,
216be20aa9dSChris Mason 		      struct extent_buffer *buf,
217be20aa9dSChris Mason 		      struct extent_buffer **cow_ret, u64 new_root_objectid)
218be20aa9dSChris Mason {
2190b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
220be20aa9dSChris Mason 	struct extent_buffer *cow;
221be20aa9dSChris Mason 	int ret = 0;
222be20aa9dSChris Mason 	int level;
2235d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
224be20aa9dSChris Mason 
22527cdeb70SMiao Xie 	WARN_ON(test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
2260b246afaSJeff Mahoney 		trans->transid != fs_info->running_transaction->transid);
22727cdeb70SMiao Xie 	WARN_ON(test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
22827cdeb70SMiao Xie 		trans->transid != root->last_trans);
229be20aa9dSChris Mason 
230be20aa9dSChris Mason 	level = btrfs_header_level(buf);
2315d4f98a2SYan Zheng 	if (level == 0)
2325d4f98a2SYan Zheng 		btrfs_item_key(buf, &disk_key, 0);
2335d4f98a2SYan Zheng 	else
2345d4f98a2SYan Zheng 		btrfs_node_key(buf, &disk_key, 0);
23531840ae1SZheng Yan 
2364d75f8a9SDavid Sterba 	cow = btrfs_alloc_tree_block(trans, root, 0, new_root_objectid,
2374d75f8a9SDavid Sterba 			&disk_key, level, buf->start, 0);
2385d4f98a2SYan Zheng 	if (IS_ERR(cow))
239be20aa9dSChris Mason 		return PTR_ERR(cow);
240be20aa9dSChris Mason 
24158e8012cSDavid Sterba 	copy_extent_buffer_full(cow, buf);
242be20aa9dSChris Mason 	btrfs_set_header_bytenr(cow, cow->start);
243be20aa9dSChris Mason 	btrfs_set_header_generation(cow, trans->transid);
2445d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
2455d4f98a2SYan Zheng 	btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
2465d4f98a2SYan Zheng 				     BTRFS_HEADER_FLAG_RELOC);
2475d4f98a2SYan Zheng 	if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
2485d4f98a2SYan Zheng 		btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
2495d4f98a2SYan Zheng 	else
250be20aa9dSChris Mason 		btrfs_set_header_owner(cow, new_root_objectid);
251be20aa9dSChris Mason 
252de37aa51SNikolay Borisov 	write_extent_buffer_fsid(cow, fs_info->fs_devices->metadata_uuid);
2532b82032cSYan Zheng 
254be20aa9dSChris Mason 	WARN_ON(btrfs_header_generation(buf) > trans->transid);
2555d4f98a2SYan Zheng 	if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
256e339a6b0SJosef Bacik 		ret = btrfs_inc_ref(trans, root, cow, 1);
2575d4f98a2SYan Zheng 	else
258e339a6b0SJosef Bacik 		ret = btrfs_inc_ref(trans, root, cow, 0);
2594aec2b52SChris Mason 
260be20aa9dSChris Mason 	if (ret)
261be20aa9dSChris Mason 		return ret;
262be20aa9dSChris Mason 
263be20aa9dSChris Mason 	btrfs_mark_buffer_dirty(cow);
264be20aa9dSChris Mason 	*cow_ret = cow;
265be20aa9dSChris Mason 	return 0;
266be20aa9dSChris Mason }
267be20aa9dSChris Mason 
268bd989ba3SJan Schmidt enum mod_log_op {
269bd989ba3SJan Schmidt 	MOD_LOG_KEY_REPLACE,
270bd989ba3SJan Schmidt 	MOD_LOG_KEY_ADD,
271bd989ba3SJan Schmidt 	MOD_LOG_KEY_REMOVE,
272bd989ba3SJan Schmidt 	MOD_LOG_KEY_REMOVE_WHILE_FREEING,
273bd989ba3SJan Schmidt 	MOD_LOG_KEY_REMOVE_WHILE_MOVING,
274bd989ba3SJan Schmidt 	MOD_LOG_MOVE_KEYS,
275bd989ba3SJan Schmidt 	MOD_LOG_ROOT_REPLACE,
276bd989ba3SJan Schmidt };
277bd989ba3SJan Schmidt 
278bd989ba3SJan Schmidt struct tree_mod_root {
279bd989ba3SJan Schmidt 	u64 logical;
280bd989ba3SJan Schmidt 	u8 level;
281bd989ba3SJan Schmidt };
282bd989ba3SJan Schmidt 
283bd989ba3SJan Schmidt struct tree_mod_elem {
284bd989ba3SJan Schmidt 	struct rb_node node;
285298cfd36SChandan Rajendra 	u64 logical;
286097b8a7cSJan Schmidt 	u64 seq;
287bd989ba3SJan Schmidt 	enum mod_log_op op;
288bd989ba3SJan Schmidt 
289bd989ba3SJan Schmidt 	/* this is used for MOD_LOG_KEY_* and MOD_LOG_MOVE_KEYS operations */
290bd989ba3SJan Schmidt 	int slot;
291bd989ba3SJan Schmidt 
292bd989ba3SJan Schmidt 	/* this is used for MOD_LOG_KEY* and MOD_LOG_ROOT_REPLACE */
293bd989ba3SJan Schmidt 	u64 generation;
294bd989ba3SJan Schmidt 
295bd989ba3SJan Schmidt 	/* those are used for op == MOD_LOG_KEY_{REPLACE,REMOVE} */
296bd989ba3SJan Schmidt 	struct btrfs_disk_key key;
297bd989ba3SJan Schmidt 	u64 blockptr;
298bd989ba3SJan Schmidt 
299bd989ba3SJan Schmidt 	/* this is used for op == MOD_LOG_MOVE_KEYS */
300b6dfa35bSDavid Sterba 	struct {
301b6dfa35bSDavid Sterba 		int dst_slot;
302b6dfa35bSDavid Sterba 		int nr_items;
303b6dfa35bSDavid Sterba 	} move;
304bd989ba3SJan Schmidt 
305bd989ba3SJan Schmidt 	/* this is used for op == MOD_LOG_ROOT_REPLACE */
306bd989ba3SJan Schmidt 	struct tree_mod_root old_root;
307bd989ba3SJan Schmidt };
308bd989ba3SJan Schmidt 
309097b8a7cSJan Schmidt /*
310fcebe456SJosef Bacik  * Pull a new tree mod seq number for our operation.
311fc36ed7eSJan Schmidt  */
312fcebe456SJosef Bacik static inline u64 btrfs_inc_tree_mod_seq(struct btrfs_fs_info *fs_info)
313fc36ed7eSJan Schmidt {
314fc36ed7eSJan Schmidt 	return atomic64_inc_return(&fs_info->tree_mod_seq);
315fc36ed7eSJan Schmidt }
316fc36ed7eSJan Schmidt 
317fc36ed7eSJan Schmidt /*
318097b8a7cSJan Schmidt  * This adds a new blocker to the tree mod log's blocker list if the @elem
319097b8a7cSJan Schmidt  * passed does not already have a sequence number set. So when a caller expects
320097b8a7cSJan Schmidt  * to record tree modifications, it should ensure to set elem->seq to zero
321097b8a7cSJan Schmidt  * before calling btrfs_get_tree_mod_seq.
322097b8a7cSJan Schmidt  * Returns a fresh, unused tree log modification sequence number, even if no new
323097b8a7cSJan Schmidt  * blocker was added.
324097b8a7cSJan Schmidt  */
325097b8a7cSJan Schmidt u64 btrfs_get_tree_mod_seq(struct btrfs_fs_info *fs_info,
326bd989ba3SJan Schmidt 			   struct seq_list *elem)
327bd989ba3SJan Schmidt {
328b1a09f1eSDavid Sterba 	write_lock(&fs_info->tree_mod_log_lock);
329bd989ba3SJan Schmidt 	spin_lock(&fs_info->tree_mod_seq_lock);
330097b8a7cSJan Schmidt 	if (!elem->seq) {
331fcebe456SJosef Bacik 		elem->seq = btrfs_inc_tree_mod_seq(fs_info);
332097b8a7cSJan Schmidt 		list_add_tail(&elem->list, &fs_info->tree_mod_seq_list);
333097b8a7cSJan Schmidt 	}
334bd989ba3SJan Schmidt 	spin_unlock(&fs_info->tree_mod_seq_lock);
335b1a09f1eSDavid Sterba 	write_unlock(&fs_info->tree_mod_log_lock);
336097b8a7cSJan Schmidt 
337fcebe456SJosef Bacik 	return elem->seq;
338bd989ba3SJan Schmidt }
339bd989ba3SJan Schmidt 
340bd989ba3SJan Schmidt void btrfs_put_tree_mod_seq(struct btrfs_fs_info *fs_info,
341bd989ba3SJan Schmidt 			    struct seq_list *elem)
342bd989ba3SJan Schmidt {
343bd989ba3SJan Schmidt 	struct rb_root *tm_root;
344bd989ba3SJan Schmidt 	struct rb_node *node;
345bd989ba3SJan Schmidt 	struct rb_node *next;
346bd989ba3SJan Schmidt 	struct seq_list *cur_elem;
347bd989ba3SJan Schmidt 	struct tree_mod_elem *tm;
348bd989ba3SJan Schmidt 	u64 min_seq = (u64)-1;
349bd989ba3SJan Schmidt 	u64 seq_putting = elem->seq;
350bd989ba3SJan Schmidt 
351bd989ba3SJan Schmidt 	if (!seq_putting)
352bd989ba3SJan Schmidt 		return;
353bd989ba3SJan Schmidt 
354bd989ba3SJan Schmidt 	spin_lock(&fs_info->tree_mod_seq_lock);
355bd989ba3SJan Schmidt 	list_del(&elem->list);
356097b8a7cSJan Schmidt 	elem->seq = 0;
357bd989ba3SJan Schmidt 
358bd989ba3SJan Schmidt 	list_for_each_entry(cur_elem, &fs_info->tree_mod_seq_list, list) {
359097b8a7cSJan Schmidt 		if (cur_elem->seq < min_seq) {
360bd989ba3SJan Schmidt 			if (seq_putting > cur_elem->seq) {
361bd989ba3SJan Schmidt 				/*
362bd989ba3SJan Schmidt 				 * blocker with lower sequence number exists, we
363bd989ba3SJan Schmidt 				 * cannot remove anything from the log
364bd989ba3SJan Schmidt 				 */
365097b8a7cSJan Schmidt 				spin_unlock(&fs_info->tree_mod_seq_lock);
366097b8a7cSJan Schmidt 				return;
367bd989ba3SJan Schmidt 			}
368bd989ba3SJan Schmidt 			min_seq = cur_elem->seq;
369bd989ba3SJan Schmidt 		}
370bd989ba3SJan Schmidt 	}
371097b8a7cSJan Schmidt 	spin_unlock(&fs_info->tree_mod_seq_lock);
372097b8a7cSJan Schmidt 
373097b8a7cSJan Schmidt 	/*
374bd989ba3SJan Schmidt 	 * anything that's lower than the lowest existing (read: blocked)
375bd989ba3SJan Schmidt 	 * sequence number can be removed from the tree.
376bd989ba3SJan Schmidt 	 */
377b1a09f1eSDavid Sterba 	write_lock(&fs_info->tree_mod_log_lock);
378bd989ba3SJan Schmidt 	tm_root = &fs_info->tree_mod_log;
379bd989ba3SJan Schmidt 	for (node = rb_first(tm_root); node; node = next) {
380bd989ba3SJan Schmidt 		next = rb_next(node);
3816b4df8b6SGeliang Tang 		tm = rb_entry(node, struct tree_mod_elem, node);
382097b8a7cSJan Schmidt 		if (tm->seq > min_seq)
383bd989ba3SJan Schmidt 			continue;
384bd989ba3SJan Schmidt 		rb_erase(node, tm_root);
385bd989ba3SJan Schmidt 		kfree(tm);
386bd989ba3SJan Schmidt 	}
387b1a09f1eSDavid Sterba 	write_unlock(&fs_info->tree_mod_log_lock);
388bd989ba3SJan Schmidt }
389bd989ba3SJan Schmidt 
390bd989ba3SJan Schmidt /*
391bd989ba3SJan Schmidt  * key order of the log:
392298cfd36SChandan Rajendra  *       node/leaf start address -> sequence
393bd989ba3SJan Schmidt  *
394298cfd36SChandan Rajendra  * The 'start address' is the logical address of the *new* root node
395298cfd36SChandan Rajendra  * for root replace operations, or the logical address of the affected
396298cfd36SChandan Rajendra  * block for all other operations.
397bd989ba3SJan Schmidt  */
398bd989ba3SJan Schmidt static noinline int
399bd989ba3SJan Schmidt __tree_mod_log_insert(struct btrfs_fs_info *fs_info, struct tree_mod_elem *tm)
400bd989ba3SJan Schmidt {
401bd989ba3SJan Schmidt 	struct rb_root *tm_root;
402bd989ba3SJan Schmidt 	struct rb_node **new;
403bd989ba3SJan Schmidt 	struct rb_node *parent = NULL;
404bd989ba3SJan Schmidt 	struct tree_mod_elem *cur;
405bd989ba3SJan Schmidt 
40673e82fe4SDavid Sterba 	lockdep_assert_held_write(&fs_info->tree_mod_log_lock);
40773e82fe4SDavid Sterba 
408fcebe456SJosef Bacik 	tm->seq = btrfs_inc_tree_mod_seq(fs_info);
409bd989ba3SJan Schmidt 
410bd989ba3SJan Schmidt 	tm_root = &fs_info->tree_mod_log;
411bd989ba3SJan Schmidt 	new = &tm_root->rb_node;
412bd989ba3SJan Schmidt 	while (*new) {
4136b4df8b6SGeliang Tang 		cur = rb_entry(*new, struct tree_mod_elem, node);
414bd989ba3SJan Schmidt 		parent = *new;
415298cfd36SChandan Rajendra 		if (cur->logical < tm->logical)
416bd989ba3SJan Schmidt 			new = &((*new)->rb_left);
417298cfd36SChandan Rajendra 		else if (cur->logical > tm->logical)
418bd989ba3SJan Schmidt 			new = &((*new)->rb_right);
419097b8a7cSJan Schmidt 		else if (cur->seq < tm->seq)
420bd989ba3SJan Schmidt 			new = &((*new)->rb_left);
421097b8a7cSJan Schmidt 		else if (cur->seq > tm->seq)
422bd989ba3SJan Schmidt 			new = &((*new)->rb_right);
4235de865eeSFilipe David Borba Manana 		else
4245de865eeSFilipe David Borba Manana 			return -EEXIST;
425bd989ba3SJan Schmidt 	}
426bd989ba3SJan Schmidt 
427bd989ba3SJan Schmidt 	rb_link_node(&tm->node, parent, new);
428bd989ba3SJan Schmidt 	rb_insert_color(&tm->node, tm_root);
4295de865eeSFilipe David Borba Manana 	return 0;
430bd989ba3SJan Schmidt }
431bd989ba3SJan Schmidt 
432097b8a7cSJan Schmidt /*
433097b8a7cSJan Schmidt  * Determines if logging can be omitted. Returns 1 if it can. Otherwise, it
434097b8a7cSJan Schmidt  * returns zero with the tree_mod_log_lock acquired. The caller must hold
435097b8a7cSJan Schmidt  * this until all tree mod log insertions are recorded in the rb tree and then
436b1a09f1eSDavid Sterba  * write unlock fs_info::tree_mod_log_lock.
437097b8a7cSJan Schmidt  */
438e9b7fd4dSJan Schmidt static inline int tree_mod_dont_log(struct btrfs_fs_info *fs_info,
439e9b7fd4dSJan Schmidt 				    struct extent_buffer *eb) {
440e9b7fd4dSJan Schmidt 	smp_mb();
441e9b7fd4dSJan Schmidt 	if (list_empty(&(fs_info)->tree_mod_seq_list))
442e9b7fd4dSJan Schmidt 		return 1;
443097b8a7cSJan Schmidt 	if (eb && btrfs_header_level(eb) == 0)
444e9b7fd4dSJan Schmidt 		return 1;
4455de865eeSFilipe David Borba Manana 
446b1a09f1eSDavid Sterba 	write_lock(&fs_info->tree_mod_log_lock);
4475de865eeSFilipe David Borba Manana 	if (list_empty(&(fs_info)->tree_mod_seq_list)) {
448b1a09f1eSDavid Sterba 		write_unlock(&fs_info->tree_mod_log_lock);
4495de865eeSFilipe David Borba Manana 		return 1;
4505de865eeSFilipe David Borba Manana 	}
4515de865eeSFilipe David Borba Manana 
452e9b7fd4dSJan Schmidt 	return 0;
453e9b7fd4dSJan Schmidt }
454e9b7fd4dSJan Schmidt 
4555de865eeSFilipe David Borba Manana /* Similar to tree_mod_dont_log, but doesn't acquire any locks. */
4565de865eeSFilipe David Borba Manana static inline int tree_mod_need_log(const struct btrfs_fs_info *fs_info,
4575de865eeSFilipe David Borba Manana 				    struct extent_buffer *eb)
4585de865eeSFilipe David Borba Manana {
4595de865eeSFilipe David Borba Manana 	smp_mb();
4605de865eeSFilipe David Borba Manana 	if (list_empty(&(fs_info)->tree_mod_seq_list))
4615de865eeSFilipe David Borba Manana 		return 0;
4625de865eeSFilipe David Borba Manana 	if (eb && btrfs_header_level(eb) == 0)
4635de865eeSFilipe David Borba Manana 		return 0;
4645de865eeSFilipe David Borba Manana 
4655de865eeSFilipe David Borba Manana 	return 1;
4665de865eeSFilipe David Borba Manana }
4675de865eeSFilipe David Borba Manana 
4685de865eeSFilipe David Borba Manana static struct tree_mod_elem *
4695de865eeSFilipe David Borba Manana alloc_tree_mod_elem(struct extent_buffer *eb, int slot,
470bd989ba3SJan Schmidt 		    enum mod_log_op op, gfp_t flags)
471bd989ba3SJan Schmidt {
472097b8a7cSJan Schmidt 	struct tree_mod_elem *tm;
473bd989ba3SJan Schmidt 
474c8cc6341SJosef Bacik 	tm = kzalloc(sizeof(*tm), flags);
475c8cc6341SJosef Bacik 	if (!tm)
4765de865eeSFilipe David Borba Manana 		return NULL;
477bd989ba3SJan Schmidt 
478298cfd36SChandan Rajendra 	tm->logical = eb->start;
479bd989ba3SJan Schmidt 	if (op != MOD_LOG_KEY_ADD) {
480bd989ba3SJan Schmidt 		btrfs_node_key(eb, &tm->key, slot);
481bd989ba3SJan Schmidt 		tm->blockptr = btrfs_node_blockptr(eb, slot);
482bd989ba3SJan Schmidt 	}
483bd989ba3SJan Schmidt 	tm->op = op;
484bd989ba3SJan Schmidt 	tm->slot = slot;
485bd989ba3SJan Schmidt 	tm->generation = btrfs_node_ptr_generation(eb, slot);
4865de865eeSFilipe David Borba Manana 	RB_CLEAR_NODE(&tm->node);
487bd989ba3SJan Schmidt 
4885de865eeSFilipe David Borba Manana 	return tm;
489097b8a7cSJan Schmidt }
490097b8a7cSJan Schmidt 
491e09c2efeSDavid Sterba static noinline int tree_mod_log_insert_key(struct extent_buffer *eb, int slot,
492097b8a7cSJan Schmidt 		enum mod_log_op op, gfp_t flags)
493097b8a7cSJan Schmidt {
4945de865eeSFilipe David Borba Manana 	struct tree_mod_elem *tm;
4955de865eeSFilipe David Borba Manana 	int ret;
4965de865eeSFilipe David Borba Manana 
497e09c2efeSDavid Sterba 	if (!tree_mod_need_log(eb->fs_info, eb))
498097b8a7cSJan Schmidt 		return 0;
499097b8a7cSJan Schmidt 
5005de865eeSFilipe David Borba Manana 	tm = alloc_tree_mod_elem(eb, slot, op, flags);
5015de865eeSFilipe David Borba Manana 	if (!tm)
5025de865eeSFilipe David Borba Manana 		return -ENOMEM;
5035de865eeSFilipe David Borba Manana 
504e09c2efeSDavid Sterba 	if (tree_mod_dont_log(eb->fs_info, eb)) {
5055de865eeSFilipe David Borba Manana 		kfree(tm);
5065de865eeSFilipe David Borba Manana 		return 0;
5075de865eeSFilipe David Borba Manana 	}
5085de865eeSFilipe David Borba Manana 
509e09c2efeSDavid Sterba 	ret = __tree_mod_log_insert(eb->fs_info, tm);
510b1a09f1eSDavid Sterba 	write_unlock(&eb->fs_info->tree_mod_log_lock);
5115de865eeSFilipe David Borba Manana 	if (ret)
5125de865eeSFilipe David Borba Manana 		kfree(tm);
5135de865eeSFilipe David Borba Manana 
5145de865eeSFilipe David Borba Manana 	return ret;
515097b8a7cSJan Schmidt }
516097b8a7cSJan Schmidt 
5176074d45fSDavid Sterba static noinline int tree_mod_log_insert_move(struct extent_buffer *eb,
5186074d45fSDavid Sterba 		int dst_slot, int src_slot, int nr_items)
519bd989ba3SJan Schmidt {
5205de865eeSFilipe David Borba Manana 	struct tree_mod_elem *tm = NULL;
5215de865eeSFilipe David Borba Manana 	struct tree_mod_elem **tm_list = NULL;
5225de865eeSFilipe David Borba Manana 	int ret = 0;
523bd989ba3SJan Schmidt 	int i;
5245de865eeSFilipe David Borba Manana 	int locked = 0;
525bd989ba3SJan Schmidt 
5266074d45fSDavid Sterba 	if (!tree_mod_need_log(eb->fs_info, eb))
527f395694cSJan Schmidt 		return 0;
528bd989ba3SJan Schmidt 
529176ef8f5SDavid Sterba 	tm_list = kcalloc(nr_items, sizeof(struct tree_mod_elem *), GFP_NOFS);
5305de865eeSFilipe David Borba Manana 	if (!tm_list)
5315de865eeSFilipe David Borba Manana 		return -ENOMEM;
532bd989ba3SJan Schmidt 
533176ef8f5SDavid Sterba 	tm = kzalloc(sizeof(*tm), GFP_NOFS);
5345de865eeSFilipe David Borba Manana 	if (!tm) {
5355de865eeSFilipe David Borba Manana 		ret = -ENOMEM;
5365de865eeSFilipe David Borba Manana 		goto free_tms;
5375de865eeSFilipe David Borba Manana 	}
538f395694cSJan Schmidt 
539298cfd36SChandan Rajendra 	tm->logical = eb->start;
540bd989ba3SJan Schmidt 	tm->slot = src_slot;
541bd989ba3SJan Schmidt 	tm->move.dst_slot = dst_slot;
542bd989ba3SJan Schmidt 	tm->move.nr_items = nr_items;
543bd989ba3SJan Schmidt 	tm->op = MOD_LOG_MOVE_KEYS;
544bd989ba3SJan Schmidt 
5455de865eeSFilipe David Borba Manana 	for (i = 0; i + dst_slot < src_slot && i < nr_items; i++) {
5465de865eeSFilipe David Borba Manana 		tm_list[i] = alloc_tree_mod_elem(eb, i + dst_slot,
547176ef8f5SDavid Sterba 		    MOD_LOG_KEY_REMOVE_WHILE_MOVING, GFP_NOFS);
5485de865eeSFilipe David Borba Manana 		if (!tm_list[i]) {
5495de865eeSFilipe David Borba Manana 			ret = -ENOMEM;
5505de865eeSFilipe David Borba Manana 			goto free_tms;
5515de865eeSFilipe David Borba Manana 		}
552bd989ba3SJan Schmidt 	}
553bd989ba3SJan Schmidt 
5546074d45fSDavid Sterba 	if (tree_mod_dont_log(eb->fs_info, eb))
5555de865eeSFilipe David Borba Manana 		goto free_tms;
5565de865eeSFilipe David Borba Manana 	locked = 1;
5575de865eeSFilipe David Borba Manana 
5585de865eeSFilipe David Borba Manana 	/*
5595de865eeSFilipe David Borba Manana 	 * When we override something during the move, we log these removals.
5605de865eeSFilipe David Borba Manana 	 * This can only happen when we move towards the beginning of the
5615de865eeSFilipe David Borba Manana 	 * buffer, i.e. dst_slot < src_slot.
5625de865eeSFilipe David Borba Manana 	 */
5635de865eeSFilipe David Borba Manana 	for (i = 0; i + dst_slot < src_slot && i < nr_items; i++) {
5646074d45fSDavid Sterba 		ret = __tree_mod_log_insert(eb->fs_info, tm_list[i]);
5655de865eeSFilipe David Borba Manana 		if (ret)
5665de865eeSFilipe David Borba Manana 			goto free_tms;
5675de865eeSFilipe David Borba Manana 	}
5685de865eeSFilipe David Borba Manana 
5696074d45fSDavid Sterba 	ret = __tree_mod_log_insert(eb->fs_info, tm);
5705de865eeSFilipe David Borba Manana 	if (ret)
5715de865eeSFilipe David Borba Manana 		goto free_tms;
572b1a09f1eSDavid Sterba 	write_unlock(&eb->fs_info->tree_mod_log_lock);
5735de865eeSFilipe David Borba Manana 	kfree(tm_list);
5745de865eeSFilipe David Borba Manana 
5755de865eeSFilipe David Borba Manana 	return 0;
5765de865eeSFilipe David Borba Manana free_tms:
5775de865eeSFilipe David Borba Manana 	for (i = 0; i < nr_items; i++) {
5785de865eeSFilipe David Borba Manana 		if (tm_list[i] && !RB_EMPTY_NODE(&tm_list[i]->node))
5796074d45fSDavid Sterba 			rb_erase(&tm_list[i]->node, &eb->fs_info->tree_mod_log);
5805de865eeSFilipe David Borba Manana 		kfree(tm_list[i]);
5815de865eeSFilipe David Borba Manana 	}
5825de865eeSFilipe David Borba Manana 	if (locked)
583b1a09f1eSDavid Sterba 		write_unlock(&eb->fs_info->tree_mod_log_lock);
5845de865eeSFilipe David Borba Manana 	kfree(tm_list);
5855de865eeSFilipe David Borba Manana 	kfree(tm);
5865de865eeSFilipe David Borba Manana 
5875de865eeSFilipe David Borba Manana 	return ret;
5885de865eeSFilipe David Borba Manana }
5895de865eeSFilipe David Borba Manana 
5905de865eeSFilipe David Borba Manana static inline int
5915de865eeSFilipe David Borba Manana __tree_mod_log_free_eb(struct btrfs_fs_info *fs_info,
5925de865eeSFilipe David Borba Manana 		       struct tree_mod_elem **tm_list,
5935de865eeSFilipe David Borba Manana 		       int nritems)
594097b8a7cSJan Schmidt {
5955de865eeSFilipe David Borba Manana 	int i, j;
596097b8a7cSJan Schmidt 	int ret;
597097b8a7cSJan Schmidt 
598097b8a7cSJan Schmidt 	for (i = nritems - 1; i >= 0; i--) {
5995de865eeSFilipe David Borba Manana 		ret = __tree_mod_log_insert(fs_info, tm_list[i]);
6005de865eeSFilipe David Borba Manana 		if (ret) {
6015de865eeSFilipe David Borba Manana 			for (j = nritems - 1; j > i; j--)
6025de865eeSFilipe David Borba Manana 				rb_erase(&tm_list[j]->node,
6035de865eeSFilipe David Borba Manana 					 &fs_info->tree_mod_log);
6045de865eeSFilipe David Borba Manana 			return ret;
605097b8a7cSJan Schmidt 		}
606097b8a7cSJan Schmidt 	}
607097b8a7cSJan Schmidt 
6085de865eeSFilipe David Borba Manana 	return 0;
6095de865eeSFilipe David Borba Manana }
6105de865eeSFilipe David Borba Manana 
61195b757c1SDavid Sterba static noinline int tree_mod_log_insert_root(struct extent_buffer *old_root,
61295b757c1SDavid Sterba 			 struct extent_buffer *new_root, int log_removal)
613bd989ba3SJan Schmidt {
61495b757c1SDavid Sterba 	struct btrfs_fs_info *fs_info = old_root->fs_info;
6155de865eeSFilipe David Borba Manana 	struct tree_mod_elem *tm = NULL;
6165de865eeSFilipe David Borba Manana 	struct tree_mod_elem **tm_list = NULL;
6175de865eeSFilipe David Borba Manana 	int nritems = 0;
6185de865eeSFilipe David Borba Manana 	int ret = 0;
6195de865eeSFilipe David Borba Manana 	int i;
620bd989ba3SJan Schmidt 
6215de865eeSFilipe David Borba Manana 	if (!tree_mod_need_log(fs_info, NULL))
622097b8a7cSJan Schmidt 		return 0;
623097b8a7cSJan Schmidt 
6245de865eeSFilipe David Borba Manana 	if (log_removal && btrfs_header_level(old_root) > 0) {
6255de865eeSFilipe David Borba Manana 		nritems = btrfs_header_nritems(old_root);
62631e818feSDavid Sterba 		tm_list = kcalloc(nritems, sizeof(struct tree_mod_elem *),
627bcc8e07fSDavid Sterba 				  GFP_NOFS);
6285de865eeSFilipe David Borba Manana 		if (!tm_list) {
6295de865eeSFilipe David Borba Manana 			ret = -ENOMEM;
6305de865eeSFilipe David Borba Manana 			goto free_tms;
6315de865eeSFilipe David Borba Manana 		}
6325de865eeSFilipe David Borba Manana 		for (i = 0; i < nritems; i++) {
6335de865eeSFilipe David Borba Manana 			tm_list[i] = alloc_tree_mod_elem(old_root, i,
634bcc8e07fSDavid Sterba 			    MOD_LOG_KEY_REMOVE_WHILE_FREEING, GFP_NOFS);
6355de865eeSFilipe David Borba Manana 			if (!tm_list[i]) {
6365de865eeSFilipe David Borba Manana 				ret = -ENOMEM;
6375de865eeSFilipe David Borba Manana 				goto free_tms;
6385de865eeSFilipe David Borba Manana 			}
6395de865eeSFilipe David Borba Manana 		}
6405de865eeSFilipe David Borba Manana 	}
641d9abbf1cSJan Schmidt 
642bcc8e07fSDavid Sterba 	tm = kzalloc(sizeof(*tm), GFP_NOFS);
6435de865eeSFilipe David Borba Manana 	if (!tm) {
6445de865eeSFilipe David Borba Manana 		ret = -ENOMEM;
6455de865eeSFilipe David Borba Manana 		goto free_tms;
6465de865eeSFilipe David Borba Manana 	}
647bd989ba3SJan Schmidt 
648298cfd36SChandan Rajendra 	tm->logical = new_root->start;
649bd989ba3SJan Schmidt 	tm->old_root.logical = old_root->start;
650bd989ba3SJan Schmidt 	tm->old_root.level = btrfs_header_level(old_root);
651bd989ba3SJan Schmidt 	tm->generation = btrfs_header_generation(old_root);
652bd989ba3SJan Schmidt 	tm->op = MOD_LOG_ROOT_REPLACE;
653bd989ba3SJan Schmidt 
6545de865eeSFilipe David Borba Manana 	if (tree_mod_dont_log(fs_info, NULL))
6555de865eeSFilipe David Borba Manana 		goto free_tms;
6565de865eeSFilipe David Borba Manana 
6575de865eeSFilipe David Borba Manana 	if (tm_list)
6585de865eeSFilipe David Borba Manana 		ret = __tree_mod_log_free_eb(fs_info, tm_list, nritems);
6595de865eeSFilipe David Borba Manana 	if (!ret)
6605de865eeSFilipe David Borba Manana 		ret = __tree_mod_log_insert(fs_info, tm);
6615de865eeSFilipe David Borba Manana 
662b1a09f1eSDavid Sterba 	write_unlock(&fs_info->tree_mod_log_lock);
6635de865eeSFilipe David Borba Manana 	if (ret)
6645de865eeSFilipe David Borba Manana 		goto free_tms;
6655de865eeSFilipe David Borba Manana 	kfree(tm_list);
6665de865eeSFilipe David Borba Manana 
6675de865eeSFilipe David Borba Manana 	return ret;
6685de865eeSFilipe David Borba Manana 
6695de865eeSFilipe David Borba Manana free_tms:
6705de865eeSFilipe David Borba Manana 	if (tm_list) {
6715de865eeSFilipe David Borba Manana 		for (i = 0; i < nritems; i++)
6725de865eeSFilipe David Borba Manana 			kfree(tm_list[i]);
6735de865eeSFilipe David Borba Manana 		kfree(tm_list);
6745de865eeSFilipe David Borba Manana 	}
6755de865eeSFilipe David Borba Manana 	kfree(tm);
6765de865eeSFilipe David Borba Manana 
6775de865eeSFilipe David Borba Manana 	return ret;
678bd989ba3SJan Schmidt }
679bd989ba3SJan Schmidt 
680bd989ba3SJan Schmidt static struct tree_mod_elem *
681bd989ba3SJan Schmidt __tree_mod_log_search(struct btrfs_fs_info *fs_info, u64 start, u64 min_seq,
682bd989ba3SJan Schmidt 		      int smallest)
683bd989ba3SJan Schmidt {
684bd989ba3SJan Schmidt 	struct rb_root *tm_root;
685bd989ba3SJan Schmidt 	struct rb_node *node;
686bd989ba3SJan Schmidt 	struct tree_mod_elem *cur = NULL;
687bd989ba3SJan Schmidt 	struct tree_mod_elem *found = NULL;
688bd989ba3SJan Schmidt 
689b1a09f1eSDavid Sterba 	read_lock(&fs_info->tree_mod_log_lock);
690bd989ba3SJan Schmidt 	tm_root = &fs_info->tree_mod_log;
691bd989ba3SJan Schmidt 	node = tm_root->rb_node;
692bd989ba3SJan Schmidt 	while (node) {
6936b4df8b6SGeliang Tang 		cur = rb_entry(node, struct tree_mod_elem, node);
694298cfd36SChandan Rajendra 		if (cur->logical < start) {
695bd989ba3SJan Schmidt 			node = node->rb_left;
696298cfd36SChandan Rajendra 		} else if (cur->logical > start) {
697bd989ba3SJan Schmidt 			node = node->rb_right;
698097b8a7cSJan Schmidt 		} else if (cur->seq < min_seq) {
699bd989ba3SJan Schmidt 			node = node->rb_left;
700bd989ba3SJan Schmidt 		} else if (!smallest) {
701bd989ba3SJan Schmidt 			/* we want the node with the highest seq */
702bd989ba3SJan Schmidt 			if (found)
703097b8a7cSJan Schmidt 				BUG_ON(found->seq > cur->seq);
704bd989ba3SJan Schmidt 			found = cur;
705bd989ba3SJan Schmidt 			node = node->rb_left;
706097b8a7cSJan Schmidt 		} else if (cur->seq > min_seq) {
707bd989ba3SJan Schmidt 			/* we want the node with the smallest seq */
708bd989ba3SJan Schmidt 			if (found)
709097b8a7cSJan Schmidt 				BUG_ON(found->seq < cur->seq);
710bd989ba3SJan Schmidt 			found = cur;
711bd989ba3SJan Schmidt 			node = node->rb_right;
712bd989ba3SJan Schmidt 		} else {
713bd989ba3SJan Schmidt 			found = cur;
714bd989ba3SJan Schmidt 			break;
715bd989ba3SJan Schmidt 		}
716bd989ba3SJan Schmidt 	}
717b1a09f1eSDavid Sterba 	read_unlock(&fs_info->tree_mod_log_lock);
718bd989ba3SJan Schmidt 
719bd989ba3SJan Schmidt 	return found;
720bd989ba3SJan Schmidt }
721bd989ba3SJan Schmidt 
722bd989ba3SJan Schmidt /*
723bd989ba3SJan Schmidt  * this returns the element from the log with the smallest time sequence
724bd989ba3SJan Schmidt  * value that's in the log (the oldest log item). any element with a time
725bd989ba3SJan Schmidt  * sequence lower than min_seq will be ignored.
726bd989ba3SJan Schmidt  */
727bd989ba3SJan Schmidt static struct tree_mod_elem *
728bd989ba3SJan Schmidt tree_mod_log_search_oldest(struct btrfs_fs_info *fs_info, u64 start,
729bd989ba3SJan Schmidt 			   u64 min_seq)
730bd989ba3SJan Schmidt {
731bd989ba3SJan Schmidt 	return __tree_mod_log_search(fs_info, start, min_seq, 1);
732bd989ba3SJan Schmidt }
733bd989ba3SJan Schmidt 
734bd989ba3SJan Schmidt /*
735bd989ba3SJan Schmidt  * this returns the element from the log with the largest time sequence
736bd989ba3SJan Schmidt  * value that's in the log (the most recent log item). any element with
737bd989ba3SJan Schmidt  * a time sequence lower than min_seq will be ignored.
738bd989ba3SJan Schmidt  */
739bd989ba3SJan Schmidt static struct tree_mod_elem *
740bd989ba3SJan Schmidt tree_mod_log_search(struct btrfs_fs_info *fs_info, u64 start, u64 min_seq)
741bd989ba3SJan Schmidt {
742bd989ba3SJan Schmidt 	return __tree_mod_log_search(fs_info, start, min_seq, 0);
743bd989ba3SJan Schmidt }
744bd989ba3SJan Schmidt 
745ed874f0dSDavid Sterba static noinline int tree_mod_log_eb_copy(struct extent_buffer *dst,
746bd989ba3SJan Schmidt 		     struct extent_buffer *src, unsigned long dst_offset,
74790f8d62eSJan Schmidt 		     unsigned long src_offset, int nr_items)
748bd989ba3SJan Schmidt {
749ed874f0dSDavid Sterba 	struct btrfs_fs_info *fs_info = dst->fs_info;
7505de865eeSFilipe David Borba Manana 	int ret = 0;
7515de865eeSFilipe David Borba Manana 	struct tree_mod_elem **tm_list = NULL;
7525de865eeSFilipe David Borba Manana 	struct tree_mod_elem **tm_list_add, **tm_list_rem;
753bd989ba3SJan Schmidt 	int i;
7545de865eeSFilipe David Borba Manana 	int locked = 0;
755bd989ba3SJan Schmidt 
7565de865eeSFilipe David Borba Manana 	if (!tree_mod_need_log(fs_info, NULL))
7575de865eeSFilipe David Borba Manana 		return 0;
758bd989ba3SJan Schmidt 
759c8cc6341SJosef Bacik 	if (btrfs_header_level(dst) == 0 && btrfs_header_level(src) == 0)
7605de865eeSFilipe David Borba Manana 		return 0;
7615de865eeSFilipe David Borba Manana 
76231e818feSDavid Sterba 	tm_list = kcalloc(nr_items * 2, sizeof(struct tree_mod_elem *),
7635de865eeSFilipe David Borba Manana 			  GFP_NOFS);
7645de865eeSFilipe David Borba Manana 	if (!tm_list)
7655de865eeSFilipe David Borba Manana 		return -ENOMEM;
7665de865eeSFilipe David Borba Manana 
7675de865eeSFilipe David Borba Manana 	tm_list_add = tm_list;
7685de865eeSFilipe David Borba Manana 	tm_list_rem = tm_list + nr_items;
7695de865eeSFilipe David Borba Manana 	for (i = 0; i < nr_items; i++) {
7705de865eeSFilipe David Borba Manana 		tm_list_rem[i] = alloc_tree_mod_elem(src, i + src_offset,
7715de865eeSFilipe David Borba Manana 		    MOD_LOG_KEY_REMOVE, GFP_NOFS);
7725de865eeSFilipe David Borba Manana 		if (!tm_list_rem[i]) {
7735de865eeSFilipe David Borba Manana 			ret = -ENOMEM;
7745de865eeSFilipe David Borba Manana 			goto free_tms;
7755de865eeSFilipe David Borba Manana 		}
7765de865eeSFilipe David Borba Manana 
7775de865eeSFilipe David Borba Manana 		tm_list_add[i] = alloc_tree_mod_elem(dst, i + dst_offset,
7785de865eeSFilipe David Borba Manana 		    MOD_LOG_KEY_ADD, GFP_NOFS);
7795de865eeSFilipe David Borba Manana 		if (!tm_list_add[i]) {
7805de865eeSFilipe David Borba Manana 			ret = -ENOMEM;
7815de865eeSFilipe David Borba Manana 			goto free_tms;
7825de865eeSFilipe David Borba Manana 		}
7835de865eeSFilipe David Borba Manana 	}
7845de865eeSFilipe David Borba Manana 
7855de865eeSFilipe David Borba Manana 	if (tree_mod_dont_log(fs_info, NULL))
7865de865eeSFilipe David Borba Manana 		goto free_tms;
7875de865eeSFilipe David Borba Manana 	locked = 1;
788bd989ba3SJan Schmidt 
789bd989ba3SJan Schmidt 	for (i = 0; i < nr_items; i++) {
7905de865eeSFilipe David Borba Manana 		ret = __tree_mod_log_insert(fs_info, tm_list_rem[i]);
7915de865eeSFilipe David Borba Manana 		if (ret)
7925de865eeSFilipe David Borba Manana 			goto free_tms;
7935de865eeSFilipe David Borba Manana 		ret = __tree_mod_log_insert(fs_info, tm_list_add[i]);
7945de865eeSFilipe David Borba Manana 		if (ret)
7955de865eeSFilipe David Borba Manana 			goto free_tms;
796bd989ba3SJan Schmidt 	}
7975de865eeSFilipe David Borba Manana 
798b1a09f1eSDavid Sterba 	write_unlock(&fs_info->tree_mod_log_lock);
7995de865eeSFilipe David Borba Manana 	kfree(tm_list);
8005de865eeSFilipe David Borba Manana 
8015de865eeSFilipe David Borba Manana 	return 0;
8025de865eeSFilipe David Borba Manana 
8035de865eeSFilipe David Borba Manana free_tms:
8045de865eeSFilipe David Borba Manana 	for (i = 0; i < nr_items * 2; i++) {
8055de865eeSFilipe David Borba Manana 		if (tm_list[i] && !RB_EMPTY_NODE(&tm_list[i]->node))
8065de865eeSFilipe David Borba Manana 			rb_erase(&tm_list[i]->node, &fs_info->tree_mod_log);
8075de865eeSFilipe David Borba Manana 		kfree(tm_list[i]);
8085de865eeSFilipe David Borba Manana 	}
8095de865eeSFilipe David Borba Manana 	if (locked)
810b1a09f1eSDavid Sterba 		write_unlock(&fs_info->tree_mod_log_lock);
8115de865eeSFilipe David Borba Manana 	kfree(tm_list);
8125de865eeSFilipe David Borba Manana 
8135de865eeSFilipe David Borba Manana 	return ret;
814bd989ba3SJan Schmidt }
815bd989ba3SJan Schmidt 
816db7279a2SDavid Sterba static noinline int tree_mod_log_free_eb(struct extent_buffer *eb)
817bd989ba3SJan Schmidt {
8185de865eeSFilipe David Borba Manana 	struct tree_mod_elem **tm_list = NULL;
8195de865eeSFilipe David Borba Manana 	int nritems = 0;
8205de865eeSFilipe David Borba Manana 	int i;
8215de865eeSFilipe David Borba Manana 	int ret = 0;
8225de865eeSFilipe David Borba Manana 
8235de865eeSFilipe David Borba Manana 	if (btrfs_header_level(eb) == 0)
8245de865eeSFilipe David Borba Manana 		return 0;
8255de865eeSFilipe David Borba Manana 
826db7279a2SDavid Sterba 	if (!tree_mod_need_log(eb->fs_info, NULL))
8275de865eeSFilipe David Borba Manana 		return 0;
8285de865eeSFilipe David Borba Manana 
8295de865eeSFilipe David Borba Manana 	nritems = btrfs_header_nritems(eb);
83031e818feSDavid Sterba 	tm_list = kcalloc(nritems, sizeof(struct tree_mod_elem *), GFP_NOFS);
8315de865eeSFilipe David Borba Manana 	if (!tm_list)
8325de865eeSFilipe David Borba Manana 		return -ENOMEM;
8335de865eeSFilipe David Borba Manana 
8345de865eeSFilipe David Borba Manana 	for (i = 0; i < nritems; i++) {
8355de865eeSFilipe David Borba Manana 		tm_list[i] = alloc_tree_mod_elem(eb, i,
8365de865eeSFilipe David Borba Manana 		    MOD_LOG_KEY_REMOVE_WHILE_FREEING, GFP_NOFS);
8375de865eeSFilipe David Borba Manana 		if (!tm_list[i]) {
8385de865eeSFilipe David Borba Manana 			ret = -ENOMEM;
8395de865eeSFilipe David Borba Manana 			goto free_tms;
8405de865eeSFilipe David Borba Manana 		}
8415de865eeSFilipe David Borba Manana 	}
8425de865eeSFilipe David Borba Manana 
843db7279a2SDavid Sterba 	if (tree_mod_dont_log(eb->fs_info, eb))
8445de865eeSFilipe David Borba Manana 		goto free_tms;
8455de865eeSFilipe David Borba Manana 
846db7279a2SDavid Sterba 	ret = __tree_mod_log_free_eb(eb->fs_info, tm_list, nritems);
847b1a09f1eSDavid Sterba 	write_unlock(&eb->fs_info->tree_mod_log_lock);
8485de865eeSFilipe David Borba Manana 	if (ret)
8495de865eeSFilipe David Borba Manana 		goto free_tms;
8505de865eeSFilipe David Borba Manana 	kfree(tm_list);
8515de865eeSFilipe David Borba Manana 
8525de865eeSFilipe David Borba Manana 	return 0;
8535de865eeSFilipe David Borba Manana 
8545de865eeSFilipe David Borba Manana free_tms:
8555de865eeSFilipe David Borba Manana 	for (i = 0; i < nritems; i++)
8565de865eeSFilipe David Borba Manana 		kfree(tm_list[i]);
8575de865eeSFilipe David Borba Manana 	kfree(tm_list);
8585de865eeSFilipe David Borba Manana 
8595de865eeSFilipe David Borba Manana 	return ret;
860bd989ba3SJan Schmidt }
861bd989ba3SJan Schmidt 
862d352ac68SChris Mason /*
8635d4f98a2SYan Zheng  * check if the tree block can be shared by multiple trees
8645d4f98a2SYan Zheng  */
8655d4f98a2SYan Zheng int btrfs_block_can_be_shared(struct btrfs_root *root,
8665d4f98a2SYan Zheng 			      struct extent_buffer *buf)
8675d4f98a2SYan Zheng {
8685d4f98a2SYan Zheng 	/*
86901327610SNicholas D Steeves 	 * Tree blocks not in reference counted trees and tree roots
8705d4f98a2SYan Zheng 	 * are never shared. If a block was allocated after the last
8715d4f98a2SYan Zheng 	 * snapshot and the block was not allocated by tree relocation,
8725d4f98a2SYan Zheng 	 * we know the block is not shared.
8735d4f98a2SYan Zheng 	 */
87427cdeb70SMiao Xie 	if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
8755d4f98a2SYan Zheng 	    buf != root->node && buf != root->commit_root &&
8765d4f98a2SYan Zheng 	    (btrfs_header_generation(buf) <=
8775d4f98a2SYan Zheng 	     btrfs_root_last_snapshot(&root->root_item) ||
8785d4f98a2SYan Zheng 	     btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)))
8795d4f98a2SYan Zheng 		return 1;
880a79865c6SNikolay Borisov 
8815d4f98a2SYan Zheng 	return 0;
8825d4f98a2SYan Zheng }
8835d4f98a2SYan Zheng 
8845d4f98a2SYan Zheng static noinline int update_ref_for_cow(struct btrfs_trans_handle *trans,
8855d4f98a2SYan Zheng 				       struct btrfs_root *root,
8865d4f98a2SYan Zheng 				       struct extent_buffer *buf,
887f0486c68SYan, Zheng 				       struct extent_buffer *cow,
888f0486c68SYan, Zheng 				       int *last_ref)
8895d4f98a2SYan Zheng {
8900b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
8915d4f98a2SYan Zheng 	u64 refs;
8925d4f98a2SYan Zheng 	u64 owner;
8935d4f98a2SYan Zheng 	u64 flags;
8945d4f98a2SYan Zheng 	u64 new_flags = 0;
8955d4f98a2SYan Zheng 	int ret;
8965d4f98a2SYan Zheng 
8975d4f98a2SYan Zheng 	/*
8985d4f98a2SYan Zheng 	 * Backrefs update rules:
8995d4f98a2SYan Zheng 	 *
9005d4f98a2SYan Zheng 	 * Always use full backrefs for extent pointers in tree block
9015d4f98a2SYan Zheng 	 * allocated by tree relocation.
9025d4f98a2SYan Zheng 	 *
9035d4f98a2SYan Zheng 	 * If a shared tree block is no longer referenced by its owner
9045d4f98a2SYan Zheng 	 * tree (btrfs_header_owner(buf) == root->root_key.objectid),
9055d4f98a2SYan Zheng 	 * use full backrefs for extent pointers in tree block.
9065d4f98a2SYan Zheng 	 *
9075d4f98a2SYan Zheng 	 * If a tree block is been relocating
9085d4f98a2SYan Zheng 	 * (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID),
9095d4f98a2SYan Zheng 	 * use full backrefs for extent pointers in tree block.
9105d4f98a2SYan Zheng 	 * The reason for this is some operations (such as drop tree)
9115d4f98a2SYan Zheng 	 * are only allowed for blocks use full backrefs.
9125d4f98a2SYan Zheng 	 */
9135d4f98a2SYan Zheng 
9145d4f98a2SYan Zheng 	if (btrfs_block_can_be_shared(root, buf)) {
9152ff7e61eSJeff Mahoney 		ret = btrfs_lookup_extent_info(trans, fs_info, buf->start,
9163173a18fSJosef Bacik 					       btrfs_header_level(buf), 1,
9173173a18fSJosef Bacik 					       &refs, &flags);
918be1a5564SMark Fasheh 		if (ret)
919be1a5564SMark Fasheh 			return ret;
920e5df9573SMark Fasheh 		if (refs == 0) {
921e5df9573SMark Fasheh 			ret = -EROFS;
9220b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
923e5df9573SMark Fasheh 			return ret;
924e5df9573SMark Fasheh 		}
9255d4f98a2SYan Zheng 	} else {
9265d4f98a2SYan Zheng 		refs = 1;
9275d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
9285d4f98a2SYan Zheng 		    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
9295d4f98a2SYan Zheng 			flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
9305d4f98a2SYan Zheng 		else
9315d4f98a2SYan Zheng 			flags = 0;
9325d4f98a2SYan Zheng 	}
9335d4f98a2SYan Zheng 
9345d4f98a2SYan Zheng 	owner = btrfs_header_owner(buf);
9355d4f98a2SYan Zheng 	BUG_ON(owner == BTRFS_TREE_RELOC_OBJECTID &&
9365d4f98a2SYan Zheng 	       !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
9375d4f98a2SYan Zheng 
9385d4f98a2SYan Zheng 	if (refs > 1) {
9395d4f98a2SYan Zheng 		if ((owner == root->root_key.objectid ||
9405d4f98a2SYan Zheng 		     root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) &&
9415d4f98a2SYan Zheng 		    !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)) {
942e339a6b0SJosef Bacik 			ret = btrfs_inc_ref(trans, root, buf, 1);
943692826b2SJeff Mahoney 			if (ret)
944692826b2SJeff Mahoney 				return ret;
9455d4f98a2SYan Zheng 
9465d4f98a2SYan Zheng 			if (root->root_key.objectid ==
9475d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID) {
948e339a6b0SJosef Bacik 				ret = btrfs_dec_ref(trans, root, buf, 0);
949692826b2SJeff Mahoney 				if (ret)
950692826b2SJeff Mahoney 					return ret;
951e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
952692826b2SJeff Mahoney 				if (ret)
953692826b2SJeff Mahoney 					return ret;
9545d4f98a2SYan Zheng 			}
9555d4f98a2SYan Zheng 			new_flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
9565d4f98a2SYan Zheng 		} else {
9575d4f98a2SYan Zheng 
9585d4f98a2SYan Zheng 			if (root->root_key.objectid ==
9595d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID)
960e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
9615d4f98a2SYan Zheng 			else
962e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 0);
963692826b2SJeff Mahoney 			if (ret)
964692826b2SJeff Mahoney 				return ret;
9655d4f98a2SYan Zheng 		}
9665d4f98a2SYan Zheng 		if (new_flags != 0) {
967b1c79e09SJosef Bacik 			int level = btrfs_header_level(buf);
968b1c79e09SJosef Bacik 
969f5c8daa5SDavid Sterba 			ret = btrfs_set_disk_extent_flags(trans,
9705d4f98a2SYan Zheng 							  buf->start,
9715d4f98a2SYan Zheng 							  buf->len,
972b1c79e09SJosef Bacik 							  new_flags, level, 0);
973be1a5564SMark Fasheh 			if (ret)
974be1a5564SMark Fasheh 				return ret;
9755d4f98a2SYan Zheng 		}
9765d4f98a2SYan Zheng 	} else {
9775d4f98a2SYan Zheng 		if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
9785d4f98a2SYan Zheng 			if (root->root_key.objectid ==
9795d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID)
980e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
9815d4f98a2SYan Zheng 			else
982e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 0);
983692826b2SJeff Mahoney 			if (ret)
984692826b2SJeff Mahoney 				return ret;
985e339a6b0SJosef Bacik 			ret = btrfs_dec_ref(trans, root, buf, 1);
986692826b2SJeff Mahoney 			if (ret)
987692826b2SJeff Mahoney 				return ret;
9885d4f98a2SYan Zheng 		}
9896a884d7dSDavid Sterba 		btrfs_clean_tree_block(buf);
990f0486c68SYan, Zheng 		*last_ref = 1;
9915d4f98a2SYan Zheng 	}
9925d4f98a2SYan Zheng 	return 0;
9935d4f98a2SYan Zheng }
9945d4f98a2SYan Zheng 
995a6279470SFilipe Manana static struct extent_buffer *alloc_tree_block_no_bg_flush(
996a6279470SFilipe Manana 					  struct btrfs_trans_handle *trans,
997a6279470SFilipe Manana 					  struct btrfs_root *root,
998a6279470SFilipe Manana 					  u64 parent_start,
999a6279470SFilipe Manana 					  const struct btrfs_disk_key *disk_key,
1000a6279470SFilipe Manana 					  int level,
1001a6279470SFilipe Manana 					  u64 hint,
1002a6279470SFilipe Manana 					  u64 empty_size)
1003a6279470SFilipe Manana {
1004a6279470SFilipe Manana 	struct btrfs_fs_info *fs_info = root->fs_info;
1005a6279470SFilipe Manana 	struct extent_buffer *ret;
1006a6279470SFilipe Manana 
1007a6279470SFilipe Manana 	/*
1008a6279470SFilipe Manana 	 * If we are COWing a node/leaf from the extent, chunk, device or free
1009a6279470SFilipe Manana 	 * space trees, make sure that we do not finish block group creation of
1010a6279470SFilipe Manana 	 * pending block groups. We do this to avoid a deadlock.
1011a6279470SFilipe Manana 	 * COWing can result in allocation of a new chunk, and flushing pending
1012a6279470SFilipe Manana 	 * block groups (btrfs_create_pending_block_groups()) can be triggered
1013a6279470SFilipe Manana 	 * when finishing allocation of a new chunk. Creation of a pending block
1014a6279470SFilipe Manana 	 * group modifies the extent, chunk, device and free space trees,
1015a6279470SFilipe Manana 	 * therefore we could deadlock with ourselves since we are holding a
1016a6279470SFilipe Manana 	 * lock on an extent buffer that btrfs_create_pending_block_groups() may
1017a6279470SFilipe Manana 	 * try to COW later.
1018a6279470SFilipe Manana 	 * For similar reasons, we also need to delay flushing pending block
1019a6279470SFilipe Manana 	 * groups when splitting a leaf or node, from one of those trees, since
1020a6279470SFilipe Manana 	 * we are holding a write lock on it and its parent or when inserting a
1021a6279470SFilipe Manana 	 * new root node for one of those trees.
1022a6279470SFilipe Manana 	 */
1023a6279470SFilipe Manana 	if (root == fs_info->extent_root ||
1024a6279470SFilipe Manana 	    root == fs_info->chunk_root ||
1025a6279470SFilipe Manana 	    root == fs_info->dev_root ||
1026a6279470SFilipe Manana 	    root == fs_info->free_space_root)
1027a6279470SFilipe Manana 		trans->can_flush_pending_bgs = false;
1028a6279470SFilipe Manana 
1029a6279470SFilipe Manana 	ret = btrfs_alloc_tree_block(trans, root, parent_start,
1030a6279470SFilipe Manana 				     root->root_key.objectid, disk_key, level,
1031a6279470SFilipe Manana 				     hint, empty_size);
1032a6279470SFilipe Manana 	trans->can_flush_pending_bgs = true;
1033a6279470SFilipe Manana 
1034a6279470SFilipe Manana 	return ret;
1035a6279470SFilipe Manana }
1036a6279470SFilipe Manana 
10375d4f98a2SYan Zheng /*
1038d397712bSChris Mason  * does the dirty work in cow of a single block.  The parent block (if
1039d397712bSChris Mason  * supplied) is updated to point to the new cow copy.  The new buffer is marked
1040d397712bSChris Mason  * dirty and returned locked.  If you modify the block it needs to be marked
1041d397712bSChris Mason  * dirty again.
1042d352ac68SChris Mason  *
1043d352ac68SChris Mason  * search_start -- an allocation hint for the new block
1044d352ac68SChris Mason  *
1045d397712bSChris Mason  * empty_size -- a hint that you plan on doing more cow.  This is the size in
1046d397712bSChris Mason  * bytes the allocator should try to find free next to the block it returns.
1047d397712bSChris Mason  * This is just a hint and may be ignored by the allocator.
1048d352ac68SChris Mason  */
1049d397712bSChris Mason static noinline int __btrfs_cow_block(struct btrfs_trans_handle *trans,
10505f39d397SChris Mason 			     struct btrfs_root *root,
10515f39d397SChris Mason 			     struct extent_buffer *buf,
10525f39d397SChris Mason 			     struct extent_buffer *parent, int parent_slot,
10535f39d397SChris Mason 			     struct extent_buffer **cow_ret,
10549fa8cfe7SChris Mason 			     u64 search_start, u64 empty_size)
10556702ed49SChris Mason {
10560b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
10575d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
10585f39d397SChris Mason 	struct extent_buffer *cow;
1059be1a5564SMark Fasheh 	int level, ret;
1060f0486c68SYan, Zheng 	int last_ref = 0;
1061925baeddSChris Mason 	int unlock_orig = 0;
10620f5053ebSGoldwyn Rodrigues 	u64 parent_start = 0;
10636702ed49SChris Mason 
1064925baeddSChris Mason 	if (*cow_ret == buf)
1065925baeddSChris Mason 		unlock_orig = 1;
1066925baeddSChris Mason 
1067b9447ef8SChris Mason 	btrfs_assert_tree_locked(buf);
1068925baeddSChris Mason 
106927cdeb70SMiao Xie 	WARN_ON(test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
10700b246afaSJeff Mahoney 		trans->transid != fs_info->running_transaction->transid);
107127cdeb70SMiao Xie 	WARN_ON(test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
107227cdeb70SMiao Xie 		trans->transid != root->last_trans);
10735f39d397SChris Mason 
10747bb86316SChris Mason 	level = btrfs_header_level(buf);
107531840ae1SZheng Yan 
10765d4f98a2SYan Zheng 	if (level == 0)
10775d4f98a2SYan Zheng 		btrfs_item_key(buf, &disk_key, 0);
10785d4f98a2SYan Zheng 	else
10795d4f98a2SYan Zheng 		btrfs_node_key(buf, &disk_key, 0);
10805d4f98a2SYan Zheng 
10810f5053ebSGoldwyn Rodrigues 	if ((root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) && parent)
10825d4f98a2SYan Zheng 		parent_start = parent->start;
10835d4f98a2SYan Zheng 
1084a6279470SFilipe Manana 	cow = alloc_tree_block_no_bg_flush(trans, root, parent_start, &disk_key,
1085a6279470SFilipe Manana 					   level, search_start, empty_size);
10866702ed49SChris Mason 	if (IS_ERR(cow))
10876702ed49SChris Mason 		return PTR_ERR(cow);
10886702ed49SChris Mason 
1089b4ce94deSChris Mason 	/* cow is set to blocking by btrfs_init_new_buffer */
1090b4ce94deSChris Mason 
109158e8012cSDavid Sterba 	copy_extent_buffer_full(cow, buf);
1092db94535dSChris Mason 	btrfs_set_header_bytenr(cow, cow->start);
10935f39d397SChris Mason 	btrfs_set_header_generation(cow, trans->transid);
10945d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
10955d4f98a2SYan Zheng 	btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
10965d4f98a2SYan Zheng 				     BTRFS_HEADER_FLAG_RELOC);
10975d4f98a2SYan Zheng 	if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
10985d4f98a2SYan Zheng 		btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
10995d4f98a2SYan Zheng 	else
11005f39d397SChris Mason 		btrfs_set_header_owner(cow, root->root_key.objectid);
11016702ed49SChris Mason 
1102de37aa51SNikolay Borisov 	write_extent_buffer_fsid(cow, fs_info->fs_devices->metadata_uuid);
11032b82032cSYan Zheng 
1104be1a5564SMark Fasheh 	ret = update_ref_for_cow(trans, root, buf, cow, &last_ref);
1105b68dc2a9SMark Fasheh 	if (ret) {
110666642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
1107b68dc2a9SMark Fasheh 		return ret;
1108b68dc2a9SMark Fasheh 	}
11091a40e23bSZheng Yan 
111027cdeb70SMiao Xie 	if (test_bit(BTRFS_ROOT_REF_COWS, &root->state)) {
111183d4cfd4SJosef Bacik 		ret = btrfs_reloc_cow_block(trans, root, buf, cow);
111293314e3bSZhaolei 		if (ret) {
111366642832SJeff Mahoney 			btrfs_abort_transaction(trans, ret);
111483d4cfd4SJosef Bacik 			return ret;
111583d4cfd4SJosef Bacik 		}
111693314e3bSZhaolei 	}
11173fd0a558SYan, Zheng 
11186702ed49SChris Mason 	if (buf == root->node) {
1119925baeddSChris Mason 		WARN_ON(parent && parent != buf);
11205d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
11215d4f98a2SYan Zheng 		    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
11225d4f98a2SYan Zheng 			parent_start = buf->start;
1123925baeddSChris Mason 
112467439dadSDavid Sterba 		atomic_inc(&cow->refs);
1125d9d19a01SDavid Sterba 		ret = tree_mod_log_insert_root(root->node, cow, 1);
1126d9d19a01SDavid Sterba 		BUG_ON(ret < 0);
1127240f62c8SChris Mason 		rcu_assign_pointer(root->node, cow);
1128925baeddSChris Mason 
1129f0486c68SYan, Zheng 		btrfs_free_tree_block(trans, root, buf, parent_start,
11305581a51aSJan Schmidt 				      last_ref);
11315f39d397SChris Mason 		free_extent_buffer(buf);
11320b86a832SChris Mason 		add_root_to_dirty_list(root);
11336702ed49SChris Mason 	} else {
11345d4f98a2SYan Zheng 		WARN_ON(trans->transid != btrfs_header_generation(parent));
1135e09c2efeSDavid Sterba 		tree_mod_log_insert_key(parent, parent_slot,
1136c8cc6341SJosef Bacik 					MOD_LOG_KEY_REPLACE, GFP_NOFS);
11375f39d397SChris Mason 		btrfs_set_node_blockptr(parent, parent_slot,
1138db94535dSChris Mason 					cow->start);
113974493f7aSChris Mason 		btrfs_set_node_ptr_generation(parent, parent_slot,
114074493f7aSChris Mason 					      trans->transid);
11416702ed49SChris Mason 		btrfs_mark_buffer_dirty(parent);
11425de865eeSFilipe David Borba Manana 		if (last_ref) {
1143db7279a2SDavid Sterba 			ret = tree_mod_log_free_eb(buf);
11445de865eeSFilipe David Borba Manana 			if (ret) {
114566642832SJeff Mahoney 				btrfs_abort_transaction(trans, ret);
11465de865eeSFilipe David Borba Manana 				return ret;
11475de865eeSFilipe David Borba Manana 			}
11485de865eeSFilipe David Borba Manana 		}
1149f0486c68SYan, Zheng 		btrfs_free_tree_block(trans, root, buf, parent_start,
11505581a51aSJan Schmidt 				      last_ref);
11516702ed49SChris Mason 	}
1152925baeddSChris Mason 	if (unlock_orig)
1153925baeddSChris Mason 		btrfs_tree_unlock(buf);
11543083ee2eSJosef Bacik 	free_extent_buffer_stale(buf);
11556702ed49SChris Mason 	btrfs_mark_buffer_dirty(cow);
11566702ed49SChris Mason 	*cow_ret = cow;
11576702ed49SChris Mason 	return 0;
11586702ed49SChris Mason }
11596702ed49SChris Mason 
11605d9e75c4SJan Schmidt /*
11615d9e75c4SJan Schmidt  * returns the logical address of the oldest predecessor of the given root.
11625d9e75c4SJan Schmidt  * entries older than time_seq are ignored.
11635d9e75c4SJan Schmidt  */
1164bcd24dabSDavid Sterba static struct tree_mod_elem *__tree_mod_log_oldest_root(
116530b0463aSJan Schmidt 		struct extent_buffer *eb_root, u64 time_seq)
11665d9e75c4SJan Schmidt {
11675d9e75c4SJan Schmidt 	struct tree_mod_elem *tm;
11685d9e75c4SJan Schmidt 	struct tree_mod_elem *found = NULL;
116930b0463aSJan Schmidt 	u64 root_logical = eb_root->start;
11705d9e75c4SJan Schmidt 	int looped = 0;
11715d9e75c4SJan Schmidt 
11725d9e75c4SJan Schmidt 	if (!time_seq)
117335a3621bSStefan Behrens 		return NULL;
11745d9e75c4SJan Schmidt 
11755d9e75c4SJan Schmidt 	/*
1176298cfd36SChandan Rajendra 	 * the very last operation that's logged for a root is the
1177298cfd36SChandan Rajendra 	 * replacement operation (if it is replaced at all). this has
1178298cfd36SChandan Rajendra 	 * the logical address of the *new* root, making it the very
1179298cfd36SChandan Rajendra 	 * first operation that's logged for this root.
11805d9e75c4SJan Schmidt 	 */
11815d9e75c4SJan Schmidt 	while (1) {
1182bcd24dabSDavid Sterba 		tm = tree_mod_log_search_oldest(eb_root->fs_info, root_logical,
11835d9e75c4SJan Schmidt 						time_seq);
11845d9e75c4SJan Schmidt 		if (!looped && !tm)
118535a3621bSStefan Behrens 			return NULL;
11865d9e75c4SJan Schmidt 		/*
118728da9fb4SJan Schmidt 		 * if there are no tree operation for the oldest root, we simply
118828da9fb4SJan Schmidt 		 * return it. this should only happen if that (old) root is at
118928da9fb4SJan Schmidt 		 * level 0.
11905d9e75c4SJan Schmidt 		 */
119128da9fb4SJan Schmidt 		if (!tm)
119228da9fb4SJan Schmidt 			break;
11935d9e75c4SJan Schmidt 
119428da9fb4SJan Schmidt 		/*
119528da9fb4SJan Schmidt 		 * if there's an operation that's not a root replacement, we
119628da9fb4SJan Schmidt 		 * found the oldest version of our root. normally, we'll find a
119728da9fb4SJan Schmidt 		 * MOD_LOG_KEY_REMOVE_WHILE_FREEING operation here.
119828da9fb4SJan Schmidt 		 */
11995d9e75c4SJan Schmidt 		if (tm->op != MOD_LOG_ROOT_REPLACE)
12005d9e75c4SJan Schmidt 			break;
12015d9e75c4SJan Schmidt 
12025d9e75c4SJan Schmidt 		found = tm;
12035d9e75c4SJan Schmidt 		root_logical = tm->old_root.logical;
12045d9e75c4SJan Schmidt 		looped = 1;
12055d9e75c4SJan Schmidt 	}
12065d9e75c4SJan Schmidt 
1207a95236d9SJan Schmidt 	/* if there's no old root to return, return what we found instead */
1208a95236d9SJan Schmidt 	if (!found)
1209a95236d9SJan Schmidt 		found = tm;
1210a95236d9SJan Schmidt 
12115d9e75c4SJan Schmidt 	return found;
12125d9e75c4SJan Schmidt }
12135d9e75c4SJan Schmidt 
12145d9e75c4SJan Schmidt /*
12155d9e75c4SJan Schmidt  * tm is a pointer to the first operation to rewind within eb. then, all
121601327610SNicholas D Steeves  * previous operations will be rewound (until we reach something older than
12175d9e75c4SJan Schmidt  * time_seq).
12185d9e75c4SJan Schmidt  */
12195d9e75c4SJan Schmidt static void
1220f1ca7e98SJosef Bacik __tree_mod_log_rewind(struct btrfs_fs_info *fs_info, struct extent_buffer *eb,
1221f1ca7e98SJosef Bacik 		      u64 time_seq, struct tree_mod_elem *first_tm)
12225d9e75c4SJan Schmidt {
12235d9e75c4SJan Schmidt 	u32 n;
12245d9e75c4SJan Schmidt 	struct rb_node *next;
12255d9e75c4SJan Schmidt 	struct tree_mod_elem *tm = first_tm;
12265d9e75c4SJan Schmidt 	unsigned long o_dst;
12275d9e75c4SJan Schmidt 	unsigned long o_src;
12285d9e75c4SJan Schmidt 	unsigned long p_size = sizeof(struct btrfs_key_ptr);
12295d9e75c4SJan Schmidt 
12305d9e75c4SJan Schmidt 	n = btrfs_header_nritems(eb);
1231b1a09f1eSDavid Sterba 	read_lock(&fs_info->tree_mod_log_lock);
1232097b8a7cSJan Schmidt 	while (tm && tm->seq >= time_seq) {
12335d9e75c4SJan Schmidt 		/*
12345d9e75c4SJan Schmidt 		 * all the operations are recorded with the operator used for
12355d9e75c4SJan Schmidt 		 * the modification. as we're going backwards, we do the
12365d9e75c4SJan Schmidt 		 * opposite of each operation here.
12375d9e75c4SJan Schmidt 		 */
12385d9e75c4SJan Schmidt 		switch (tm->op) {
12395d9e75c4SJan Schmidt 		case MOD_LOG_KEY_REMOVE_WHILE_FREEING:
12405d9e75c4SJan Schmidt 			BUG_ON(tm->slot < n);
12411c697d4aSEric Sandeen 			/* Fallthrough */
124295c80bb1SLiu Bo 		case MOD_LOG_KEY_REMOVE_WHILE_MOVING:
12434c3e6969SChris Mason 		case MOD_LOG_KEY_REMOVE:
12445d9e75c4SJan Schmidt 			btrfs_set_node_key(eb, &tm->key, tm->slot);
12455d9e75c4SJan Schmidt 			btrfs_set_node_blockptr(eb, tm->slot, tm->blockptr);
12465d9e75c4SJan Schmidt 			btrfs_set_node_ptr_generation(eb, tm->slot,
12475d9e75c4SJan Schmidt 						      tm->generation);
12484c3e6969SChris Mason 			n++;
12495d9e75c4SJan Schmidt 			break;
12505d9e75c4SJan Schmidt 		case MOD_LOG_KEY_REPLACE:
12515d9e75c4SJan Schmidt 			BUG_ON(tm->slot >= n);
12525d9e75c4SJan Schmidt 			btrfs_set_node_key(eb, &tm->key, tm->slot);
12535d9e75c4SJan Schmidt 			btrfs_set_node_blockptr(eb, tm->slot, tm->blockptr);
12545d9e75c4SJan Schmidt 			btrfs_set_node_ptr_generation(eb, tm->slot,
12555d9e75c4SJan Schmidt 						      tm->generation);
12565d9e75c4SJan Schmidt 			break;
12575d9e75c4SJan Schmidt 		case MOD_LOG_KEY_ADD:
125819956c7eSJan Schmidt 			/* if a move operation is needed it's in the log */
12595d9e75c4SJan Schmidt 			n--;
12605d9e75c4SJan Schmidt 			break;
12615d9e75c4SJan Schmidt 		case MOD_LOG_MOVE_KEYS:
1262c3193108SJan Schmidt 			o_dst = btrfs_node_key_ptr_offset(tm->slot);
1263c3193108SJan Schmidt 			o_src = btrfs_node_key_ptr_offset(tm->move.dst_slot);
1264c3193108SJan Schmidt 			memmove_extent_buffer(eb, o_dst, o_src,
12655d9e75c4SJan Schmidt 					      tm->move.nr_items * p_size);
12665d9e75c4SJan Schmidt 			break;
12675d9e75c4SJan Schmidt 		case MOD_LOG_ROOT_REPLACE:
12685d9e75c4SJan Schmidt 			/*
12695d9e75c4SJan Schmidt 			 * this operation is special. for roots, this must be
12705d9e75c4SJan Schmidt 			 * handled explicitly before rewinding.
12715d9e75c4SJan Schmidt 			 * for non-roots, this operation may exist if the node
12725d9e75c4SJan Schmidt 			 * was a root: root A -> child B; then A gets empty and
12735d9e75c4SJan Schmidt 			 * B is promoted to the new root. in the mod log, we'll
12745d9e75c4SJan Schmidt 			 * have a root-replace operation for B, a tree block
12755d9e75c4SJan Schmidt 			 * that is no root. we simply ignore that operation.
12765d9e75c4SJan Schmidt 			 */
12775d9e75c4SJan Schmidt 			break;
12785d9e75c4SJan Schmidt 		}
12795d9e75c4SJan Schmidt 		next = rb_next(&tm->node);
12805d9e75c4SJan Schmidt 		if (!next)
12815d9e75c4SJan Schmidt 			break;
12826b4df8b6SGeliang Tang 		tm = rb_entry(next, struct tree_mod_elem, node);
1283298cfd36SChandan Rajendra 		if (tm->logical != first_tm->logical)
12845d9e75c4SJan Schmidt 			break;
12855d9e75c4SJan Schmidt 	}
1286b1a09f1eSDavid Sterba 	read_unlock(&fs_info->tree_mod_log_lock);
12875d9e75c4SJan Schmidt 	btrfs_set_header_nritems(eb, n);
12885d9e75c4SJan Schmidt }
12895d9e75c4SJan Schmidt 
129047fb091fSJan Schmidt /*
129101327610SNicholas D Steeves  * Called with eb read locked. If the buffer cannot be rewound, the same buffer
129247fb091fSJan Schmidt  * is returned. If rewind operations happen, a fresh buffer is returned. The
129347fb091fSJan Schmidt  * returned buffer is always read-locked. If the returned buffer is not the
129447fb091fSJan Schmidt  * input buffer, the lock on the input buffer is released and the input buffer
129547fb091fSJan Schmidt  * is freed (its refcount is decremented).
129647fb091fSJan Schmidt  */
12975d9e75c4SJan Schmidt static struct extent_buffer *
12989ec72677SJosef Bacik tree_mod_log_rewind(struct btrfs_fs_info *fs_info, struct btrfs_path *path,
12999ec72677SJosef Bacik 		    struct extent_buffer *eb, u64 time_seq)
13005d9e75c4SJan Schmidt {
13015d9e75c4SJan Schmidt 	struct extent_buffer *eb_rewin;
13025d9e75c4SJan Schmidt 	struct tree_mod_elem *tm;
13035d9e75c4SJan Schmidt 
13045d9e75c4SJan Schmidt 	if (!time_seq)
13055d9e75c4SJan Schmidt 		return eb;
13065d9e75c4SJan Schmidt 
13075d9e75c4SJan Schmidt 	if (btrfs_header_level(eb) == 0)
13085d9e75c4SJan Schmidt 		return eb;
13095d9e75c4SJan Schmidt 
13105d9e75c4SJan Schmidt 	tm = tree_mod_log_search(fs_info, eb->start, time_seq);
13115d9e75c4SJan Schmidt 	if (!tm)
13125d9e75c4SJan Schmidt 		return eb;
13135d9e75c4SJan Schmidt 
13149ec72677SJosef Bacik 	btrfs_set_path_blocking(path);
1315300aa896SDavid Sterba 	btrfs_set_lock_blocking_read(eb);
13169ec72677SJosef Bacik 
13175d9e75c4SJan Schmidt 	if (tm->op == MOD_LOG_KEY_REMOVE_WHILE_FREEING) {
13185d9e75c4SJan Schmidt 		BUG_ON(tm->slot != 0);
1319da17066cSJeff Mahoney 		eb_rewin = alloc_dummy_extent_buffer(fs_info, eb->start);
1320db7f3436SJosef Bacik 		if (!eb_rewin) {
13219ec72677SJosef Bacik 			btrfs_tree_read_unlock_blocking(eb);
1322db7f3436SJosef Bacik 			free_extent_buffer(eb);
1323db7f3436SJosef Bacik 			return NULL;
1324db7f3436SJosef Bacik 		}
13255d9e75c4SJan Schmidt 		btrfs_set_header_bytenr(eb_rewin, eb->start);
13265d9e75c4SJan Schmidt 		btrfs_set_header_backref_rev(eb_rewin,
13275d9e75c4SJan Schmidt 					     btrfs_header_backref_rev(eb));
13285d9e75c4SJan Schmidt 		btrfs_set_header_owner(eb_rewin, btrfs_header_owner(eb));
1329c3193108SJan Schmidt 		btrfs_set_header_level(eb_rewin, btrfs_header_level(eb));
13305d9e75c4SJan Schmidt 	} else {
13315d9e75c4SJan Schmidt 		eb_rewin = btrfs_clone_extent_buffer(eb);
1332db7f3436SJosef Bacik 		if (!eb_rewin) {
13339ec72677SJosef Bacik 			btrfs_tree_read_unlock_blocking(eb);
1334db7f3436SJosef Bacik 			free_extent_buffer(eb);
1335db7f3436SJosef Bacik 			return NULL;
1336db7f3436SJosef Bacik 		}
13375d9e75c4SJan Schmidt 	}
13385d9e75c4SJan Schmidt 
13399ec72677SJosef Bacik 	btrfs_tree_read_unlock_blocking(eb);
13405d9e75c4SJan Schmidt 	free_extent_buffer(eb);
13415d9e75c4SJan Schmidt 
134247fb091fSJan Schmidt 	btrfs_tree_read_lock(eb_rewin);
1343f1ca7e98SJosef Bacik 	__tree_mod_log_rewind(fs_info, eb_rewin, time_seq, tm);
134457911b8bSJan Schmidt 	WARN_ON(btrfs_header_nritems(eb_rewin) >
1345da17066cSJeff Mahoney 		BTRFS_NODEPTRS_PER_BLOCK(fs_info));
13465d9e75c4SJan Schmidt 
13475d9e75c4SJan Schmidt 	return eb_rewin;
13485d9e75c4SJan Schmidt }
13495d9e75c4SJan Schmidt 
13508ba97a15SJan Schmidt /*
13518ba97a15SJan Schmidt  * get_old_root() rewinds the state of @root's root node to the given @time_seq
13528ba97a15SJan Schmidt  * value. If there are no changes, the current root->root_node is returned. If
13538ba97a15SJan Schmidt  * anything changed in between, there's a fresh buffer allocated on which the
13548ba97a15SJan Schmidt  * rewind operations are done. In any case, the returned buffer is read locked.
13558ba97a15SJan Schmidt  * Returns NULL on error (with no locks held).
13568ba97a15SJan Schmidt  */
13575d9e75c4SJan Schmidt static inline struct extent_buffer *
13585d9e75c4SJan Schmidt get_old_root(struct btrfs_root *root, u64 time_seq)
13595d9e75c4SJan Schmidt {
13600b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
13615d9e75c4SJan Schmidt 	struct tree_mod_elem *tm;
136230b0463aSJan Schmidt 	struct extent_buffer *eb = NULL;
136330b0463aSJan Schmidt 	struct extent_buffer *eb_root;
1364efad8a85SFilipe Manana 	u64 eb_root_owner = 0;
13657bfdcf7fSLiu Bo 	struct extent_buffer *old;
1366a95236d9SJan Schmidt 	struct tree_mod_root *old_root = NULL;
13674325edd0SChris Mason 	u64 old_generation = 0;
1368a95236d9SJan Schmidt 	u64 logical;
1369581c1760SQu Wenruo 	int level;
13705d9e75c4SJan Schmidt 
137130b0463aSJan Schmidt 	eb_root = btrfs_read_lock_root_node(root);
1372bcd24dabSDavid Sterba 	tm = __tree_mod_log_oldest_root(eb_root, time_seq);
13735d9e75c4SJan Schmidt 	if (!tm)
137430b0463aSJan Schmidt 		return eb_root;
13755d9e75c4SJan Schmidt 
1376a95236d9SJan Schmidt 	if (tm->op == MOD_LOG_ROOT_REPLACE) {
13775d9e75c4SJan Schmidt 		old_root = &tm->old_root;
13785d9e75c4SJan Schmidt 		old_generation = tm->generation;
1379a95236d9SJan Schmidt 		logical = old_root->logical;
1380581c1760SQu Wenruo 		level = old_root->level;
1381a95236d9SJan Schmidt 	} else {
138230b0463aSJan Schmidt 		logical = eb_root->start;
1383581c1760SQu Wenruo 		level = btrfs_header_level(eb_root);
1384a95236d9SJan Schmidt 	}
13855d9e75c4SJan Schmidt 
13860b246afaSJeff Mahoney 	tm = tree_mod_log_search(fs_info, logical, time_seq);
1387834328a8SJan Schmidt 	if (old_root && tm && tm->op != MOD_LOG_KEY_REMOVE_WHILE_FREEING) {
138830b0463aSJan Schmidt 		btrfs_tree_read_unlock(eb_root);
138930b0463aSJan Schmidt 		free_extent_buffer(eb_root);
1390581c1760SQu Wenruo 		old = read_tree_block(fs_info, logical, 0, level, NULL);
139164c043deSLiu Bo 		if (WARN_ON(IS_ERR(old) || !extent_buffer_uptodate(old))) {
139264c043deSLiu Bo 			if (!IS_ERR(old))
1393416bc658SJosef Bacik 				free_extent_buffer(old);
13940b246afaSJeff Mahoney 			btrfs_warn(fs_info,
13950b246afaSJeff Mahoney 				   "failed to read tree block %llu from get_old_root",
13960b246afaSJeff Mahoney 				   logical);
1397834328a8SJan Schmidt 		} else {
13987bfdcf7fSLiu Bo 			eb = btrfs_clone_extent_buffer(old);
13997bfdcf7fSLiu Bo 			free_extent_buffer(old);
1400834328a8SJan Schmidt 		}
1401834328a8SJan Schmidt 	} else if (old_root) {
1402efad8a85SFilipe Manana 		eb_root_owner = btrfs_header_owner(eb_root);
140330b0463aSJan Schmidt 		btrfs_tree_read_unlock(eb_root);
140430b0463aSJan Schmidt 		free_extent_buffer(eb_root);
14050b246afaSJeff Mahoney 		eb = alloc_dummy_extent_buffer(fs_info, logical);
1406834328a8SJan Schmidt 	} else {
1407300aa896SDavid Sterba 		btrfs_set_lock_blocking_read(eb_root);
140830b0463aSJan Schmidt 		eb = btrfs_clone_extent_buffer(eb_root);
14099ec72677SJosef Bacik 		btrfs_tree_read_unlock_blocking(eb_root);
141030b0463aSJan Schmidt 		free_extent_buffer(eb_root);
1411834328a8SJan Schmidt 	}
1412834328a8SJan Schmidt 
14138ba97a15SJan Schmidt 	if (!eb)
14148ba97a15SJan Schmidt 		return NULL;
14158ba97a15SJan Schmidt 	btrfs_tree_read_lock(eb);
1416a95236d9SJan Schmidt 	if (old_root) {
14175d9e75c4SJan Schmidt 		btrfs_set_header_bytenr(eb, eb->start);
14185d9e75c4SJan Schmidt 		btrfs_set_header_backref_rev(eb, BTRFS_MIXED_BACKREF_REV);
1419efad8a85SFilipe Manana 		btrfs_set_header_owner(eb, eb_root_owner);
14205d9e75c4SJan Schmidt 		btrfs_set_header_level(eb, old_root->level);
14215d9e75c4SJan Schmidt 		btrfs_set_header_generation(eb, old_generation);
1422a95236d9SJan Schmidt 	}
142328da9fb4SJan Schmidt 	if (tm)
14240b246afaSJeff Mahoney 		__tree_mod_log_rewind(fs_info, eb, time_seq, tm);
142528da9fb4SJan Schmidt 	else
142628da9fb4SJan Schmidt 		WARN_ON(btrfs_header_level(eb) != 0);
14270b246afaSJeff Mahoney 	WARN_ON(btrfs_header_nritems(eb) > BTRFS_NODEPTRS_PER_BLOCK(fs_info));
14285d9e75c4SJan Schmidt 
14295d9e75c4SJan Schmidt 	return eb;
14305d9e75c4SJan Schmidt }
14315d9e75c4SJan Schmidt 
14325b6602e7SJan Schmidt int btrfs_old_root_level(struct btrfs_root *root, u64 time_seq)
14335b6602e7SJan Schmidt {
14345b6602e7SJan Schmidt 	struct tree_mod_elem *tm;
14355b6602e7SJan Schmidt 	int level;
143630b0463aSJan Schmidt 	struct extent_buffer *eb_root = btrfs_root_node(root);
14375b6602e7SJan Schmidt 
1438bcd24dabSDavid Sterba 	tm = __tree_mod_log_oldest_root(eb_root, time_seq);
14395b6602e7SJan Schmidt 	if (tm && tm->op == MOD_LOG_ROOT_REPLACE) {
14405b6602e7SJan Schmidt 		level = tm->old_root.level;
14415b6602e7SJan Schmidt 	} else {
144230b0463aSJan Schmidt 		level = btrfs_header_level(eb_root);
14435b6602e7SJan Schmidt 	}
144430b0463aSJan Schmidt 	free_extent_buffer(eb_root);
14455b6602e7SJan Schmidt 
14465b6602e7SJan Schmidt 	return level;
14475b6602e7SJan Schmidt }
14485b6602e7SJan Schmidt 
14495d4f98a2SYan Zheng static inline int should_cow_block(struct btrfs_trans_handle *trans,
14505d4f98a2SYan Zheng 				   struct btrfs_root *root,
14515d4f98a2SYan Zheng 				   struct extent_buffer *buf)
14525d4f98a2SYan Zheng {
1453f5ee5c9aSJeff Mahoney 	if (btrfs_is_testing(root->fs_info))
1454faa2dbf0SJosef Bacik 		return 0;
1455fccb84c9SDavid Sterba 
1456d1980131SDavid Sterba 	/* Ensure we can see the FORCE_COW bit */
1457d1980131SDavid Sterba 	smp_mb__before_atomic();
1458f1ebcc74SLiu Bo 
1459f1ebcc74SLiu Bo 	/*
1460f1ebcc74SLiu Bo 	 * We do not need to cow a block if
1461f1ebcc74SLiu Bo 	 * 1) this block is not created or changed in this transaction;
1462f1ebcc74SLiu Bo 	 * 2) this block does not belong to TREE_RELOC tree;
1463f1ebcc74SLiu Bo 	 * 3) the root is not forced COW.
1464f1ebcc74SLiu Bo 	 *
1465f1ebcc74SLiu Bo 	 * What is forced COW:
146601327610SNicholas D Steeves 	 *    when we create snapshot during committing the transaction,
146752042d8eSAndrea Gelmini 	 *    after we've finished copying src root, we must COW the shared
1468f1ebcc74SLiu Bo 	 *    block to ensure the metadata consistency.
1469f1ebcc74SLiu Bo 	 */
14705d4f98a2SYan Zheng 	if (btrfs_header_generation(buf) == trans->transid &&
14715d4f98a2SYan Zheng 	    !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN) &&
14725d4f98a2SYan Zheng 	    !(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
1473f1ebcc74SLiu Bo 	      btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)) &&
147427cdeb70SMiao Xie 	    !test_bit(BTRFS_ROOT_FORCE_COW, &root->state))
14755d4f98a2SYan Zheng 		return 0;
14765d4f98a2SYan Zheng 	return 1;
14775d4f98a2SYan Zheng }
14785d4f98a2SYan Zheng 
1479d352ac68SChris Mason /*
1480d352ac68SChris Mason  * cows a single block, see __btrfs_cow_block for the real work.
148101327610SNicholas D Steeves  * This version of it has extra checks so that a block isn't COWed more than
1482d352ac68SChris Mason  * once per transaction, as long as it hasn't been written yet
1483d352ac68SChris Mason  */
1484d397712bSChris Mason noinline int btrfs_cow_block(struct btrfs_trans_handle *trans,
14855f39d397SChris Mason 		    struct btrfs_root *root, struct extent_buffer *buf,
14865f39d397SChris Mason 		    struct extent_buffer *parent, int parent_slot,
14879fa8cfe7SChris Mason 		    struct extent_buffer **cow_ret)
148802217ed2SChris Mason {
14890b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
14906702ed49SChris Mason 	u64 search_start;
1491f510cfecSChris Mason 	int ret;
1492dc17ff8fSChris Mason 
149383354f07SJosef Bacik 	if (test_bit(BTRFS_ROOT_DELETING, &root->state))
149483354f07SJosef Bacik 		btrfs_err(fs_info,
149583354f07SJosef Bacik 			"COW'ing blocks on a fs root that's being dropped");
149683354f07SJosef Bacik 
14970b246afaSJeff Mahoney 	if (trans->transaction != fs_info->running_transaction)
149831b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "trans %llu running %llu\n",
1499c1c9ff7cSGeert Uytterhoeven 		       trans->transid,
15000b246afaSJeff Mahoney 		       fs_info->running_transaction->transid);
150131b1a2bdSJulia Lawall 
15020b246afaSJeff Mahoney 	if (trans->transid != fs_info->generation)
150331b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "trans %llu running %llu\n",
15040b246afaSJeff Mahoney 		       trans->transid, fs_info->generation);
1505dc17ff8fSChris Mason 
15065d4f98a2SYan Zheng 	if (!should_cow_block(trans, root, buf)) {
150764c12921SJeff Mahoney 		trans->dirty = true;
150802217ed2SChris Mason 		*cow_ret = buf;
150902217ed2SChris Mason 		return 0;
151002217ed2SChris Mason 	}
1511c487685dSChris Mason 
1512ee22184bSByongho Lee 	search_start = buf->start & ~((u64)SZ_1G - 1);
1513b4ce94deSChris Mason 
1514b4ce94deSChris Mason 	if (parent)
15158bead258SDavid Sterba 		btrfs_set_lock_blocking_write(parent);
15168bead258SDavid Sterba 	btrfs_set_lock_blocking_write(buf);
1517b4ce94deSChris Mason 
1518f616f5cdSQu Wenruo 	/*
1519f616f5cdSQu Wenruo 	 * Before CoWing this block for later modification, check if it's
1520f616f5cdSQu Wenruo 	 * the subtree root and do the delayed subtree trace if needed.
1521f616f5cdSQu Wenruo 	 *
1522f616f5cdSQu Wenruo 	 * Also We don't care about the error, as it's handled internally.
1523f616f5cdSQu Wenruo 	 */
1524f616f5cdSQu Wenruo 	btrfs_qgroup_trace_subtree_after_cow(trans, root, buf);
1525f510cfecSChris Mason 	ret = __btrfs_cow_block(trans, root, buf, parent,
15269fa8cfe7SChris Mason 				 parent_slot, cow_ret, search_start, 0);
15271abe9b8aSliubo 
15281abe9b8aSliubo 	trace_btrfs_cow_block(root, buf, *cow_ret);
15291abe9b8aSliubo 
1530f510cfecSChris Mason 	return ret;
15312c90e5d6SChris Mason }
15326702ed49SChris Mason 
1533d352ac68SChris Mason /*
1534d352ac68SChris Mason  * helper function for defrag to decide if two blocks pointed to by a
1535d352ac68SChris Mason  * node are actually close by
1536d352ac68SChris Mason  */
15376b80053dSChris Mason static int close_blocks(u64 blocknr, u64 other, u32 blocksize)
15386702ed49SChris Mason {
15396b80053dSChris Mason 	if (blocknr < other && other - (blocknr + blocksize) < 32768)
15406702ed49SChris Mason 		return 1;
15416b80053dSChris Mason 	if (blocknr > other && blocknr - (other + blocksize) < 32768)
15426702ed49SChris Mason 		return 1;
154302217ed2SChris Mason 	return 0;
154402217ed2SChris Mason }
154502217ed2SChris Mason 
1546081e9573SChris Mason /*
1547081e9573SChris Mason  * compare two keys in a memcmp fashion
1548081e9573SChris Mason  */
1549310712b2SOmar Sandoval static int comp_keys(const struct btrfs_disk_key *disk,
1550310712b2SOmar Sandoval 		     const struct btrfs_key *k2)
1551081e9573SChris Mason {
1552081e9573SChris Mason 	struct btrfs_key k1;
1553081e9573SChris Mason 
1554081e9573SChris Mason 	btrfs_disk_key_to_cpu(&k1, disk);
1555081e9573SChris Mason 
155620736abaSDiego Calleja 	return btrfs_comp_cpu_keys(&k1, k2);
1557081e9573SChris Mason }
1558081e9573SChris Mason 
1559f3465ca4SJosef Bacik /*
1560f3465ca4SJosef Bacik  * same as comp_keys only with two btrfs_key's
1561f3465ca4SJosef Bacik  */
1562e1f60a65SDavid Sterba int __pure btrfs_comp_cpu_keys(const struct btrfs_key *k1, const struct btrfs_key *k2)
1563f3465ca4SJosef Bacik {
1564f3465ca4SJosef Bacik 	if (k1->objectid > k2->objectid)
1565f3465ca4SJosef Bacik 		return 1;
1566f3465ca4SJosef Bacik 	if (k1->objectid < k2->objectid)
1567f3465ca4SJosef Bacik 		return -1;
1568f3465ca4SJosef Bacik 	if (k1->type > k2->type)
1569f3465ca4SJosef Bacik 		return 1;
1570f3465ca4SJosef Bacik 	if (k1->type < k2->type)
1571f3465ca4SJosef Bacik 		return -1;
1572f3465ca4SJosef Bacik 	if (k1->offset > k2->offset)
1573f3465ca4SJosef Bacik 		return 1;
1574f3465ca4SJosef Bacik 	if (k1->offset < k2->offset)
1575f3465ca4SJosef Bacik 		return -1;
1576f3465ca4SJosef Bacik 	return 0;
1577f3465ca4SJosef Bacik }
1578081e9573SChris Mason 
1579d352ac68SChris Mason /*
1580d352ac68SChris Mason  * this is used by the defrag code to go through all the
1581d352ac68SChris Mason  * leaves pointed to by a node and reallocate them so that
1582d352ac68SChris Mason  * disk order is close to key order
1583d352ac68SChris Mason  */
15846702ed49SChris Mason int btrfs_realloc_node(struct btrfs_trans_handle *trans,
15855f39d397SChris Mason 		       struct btrfs_root *root, struct extent_buffer *parent,
1586de78b51aSEric Sandeen 		       int start_slot, u64 *last_ret,
1587a6b6e75eSChris Mason 		       struct btrfs_key *progress)
15886702ed49SChris Mason {
15890b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
15906b80053dSChris Mason 	struct extent_buffer *cur;
15916702ed49SChris Mason 	u64 blocknr;
1592ca7a79adSChris Mason 	u64 gen;
1593e9d0b13bSChris Mason 	u64 search_start = *last_ret;
1594e9d0b13bSChris Mason 	u64 last_block = 0;
15956702ed49SChris Mason 	u64 other;
15966702ed49SChris Mason 	u32 parent_nritems;
15976702ed49SChris Mason 	int end_slot;
15986702ed49SChris Mason 	int i;
15996702ed49SChris Mason 	int err = 0;
1600f2183bdeSChris Mason 	int parent_level;
16016b80053dSChris Mason 	int uptodate;
16026b80053dSChris Mason 	u32 blocksize;
1603081e9573SChris Mason 	int progress_passed = 0;
1604081e9573SChris Mason 	struct btrfs_disk_key disk_key;
16056702ed49SChris Mason 
16065708b959SChris Mason 	parent_level = btrfs_header_level(parent);
16075708b959SChris Mason 
16080b246afaSJeff Mahoney 	WARN_ON(trans->transaction != fs_info->running_transaction);
16090b246afaSJeff Mahoney 	WARN_ON(trans->transid != fs_info->generation);
161086479a04SChris Mason 
16116b80053dSChris Mason 	parent_nritems = btrfs_header_nritems(parent);
16120b246afaSJeff Mahoney 	blocksize = fs_info->nodesize;
16135dfe2be7SFilipe Manana 	end_slot = parent_nritems - 1;
16146702ed49SChris Mason 
16155dfe2be7SFilipe Manana 	if (parent_nritems <= 1)
16166702ed49SChris Mason 		return 0;
16176702ed49SChris Mason 
16188bead258SDavid Sterba 	btrfs_set_lock_blocking_write(parent);
1619b4ce94deSChris Mason 
16205dfe2be7SFilipe Manana 	for (i = start_slot; i <= end_slot; i++) {
1621581c1760SQu Wenruo 		struct btrfs_key first_key;
16226702ed49SChris Mason 		int close = 1;
1623a6b6e75eSChris Mason 
1624081e9573SChris Mason 		btrfs_node_key(parent, &disk_key, i);
1625081e9573SChris Mason 		if (!progress_passed && comp_keys(&disk_key, progress) < 0)
1626081e9573SChris Mason 			continue;
1627081e9573SChris Mason 
1628081e9573SChris Mason 		progress_passed = 1;
16296b80053dSChris Mason 		blocknr = btrfs_node_blockptr(parent, i);
1630ca7a79adSChris Mason 		gen = btrfs_node_ptr_generation(parent, i);
1631581c1760SQu Wenruo 		btrfs_node_key_to_cpu(parent, &first_key, i);
1632e9d0b13bSChris Mason 		if (last_block == 0)
1633e9d0b13bSChris Mason 			last_block = blocknr;
16345708b959SChris Mason 
16356702ed49SChris Mason 		if (i > 0) {
16366b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i - 1);
16376b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
16386702ed49SChris Mason 		}
16395dfe2be7SFilipe Manana 		if (!close && i < end_slot) {
16406b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i + 1);
16416b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
16426702ed49SChris Mason 		}
1643e9d0b13bSChris Mason 		if (close) {
1644e9d0b13bSChris Mason 			last_block = blocknr;
16456702ed49SChris Mason 			continue;
1646e9d0b13bSChris Mason 		}
16476702ed49SChris Mason 
16480b246afaSJeff Mahoney 		cur = find_extent_buffer(fs_info, blocknr);
16496b80053dSChris Mason 		if (cur)
1650b9fab919SChris Mason 			uptodate = btrfs_buffer_uptodate(cur, gen, 0);
16516b80053dSChris Mason 		else
16526b80053dSChris Mason 			uptodate = 0;
16535708b959SChris Mason 		if (!cur || !uptodate) {
16546b80053dSChris Mason 			if (!cur) {
1655581c1760SQu Wenruo 				cur = read_tree_block(fs_info, blocknr, gen,
1656581c1760SQu Wenruo 						      parent_level - 1,
1657581c1760SQu Wenruo 						      &first_key);
165864c043deSLiu Bo 				if (IS_ERR(cur)) {
165964c043deSLiu Bo 					return PTR_ERR(cur);
166064c043deSLiu Bo 				} else if (!extent_buffer_uptodate(cur)) {
1661416bc658SJosef Bacik 					free_extent_buffer(cur);
166297d9a8a4STsutomu Itoh 					return -EIO;
1663416bc658SJosef Bacik 				}
16646b80053dSChris Mason 			} else if (!uptodate) {
1665581c1760SQu Wenruo 				err = btrfs_read_buffer(cur, gen,
1666581c1760SQu Wenruo 						parent_level - 1,&first_key);
1667018642a1STsutomu Itoh 				if (err) {
1668018642a1STsutomu Itoh 					free_extent_buffer(cur);
1669018642a1STsutomu Itoh 					return err;
1670018642a1STsutomu Itoh 				}
16716702ed49SChris Mason 			}
1672f2183bdeSChris Mason 		}
1673e9d0b13bSChris Mason 		if (search_start == 0)
16746b80053dSChris Mason 			search_start = last_block;
1675e9d0b13bSChris Mason 
1676e7a84565SChris Mason 		btrfs_tree_lock(cur);
16778bead258SDavid Sterba 		btrfs_set_lock_blocking_write(cur);
16786b80053dSChris Mason 		err = __btrfs_cow_block(trans, root, cur, parent, i,
1679e7a84565SChris Mason 					&cur, search_start,
16806b80053dSChris Mason 					min(16 * blocksize,
16819fa8cfe7SChris Mason 					    (end_slot - i) * blocksize));
1682252c38f0SYan 		if (err) {
1683e7a84565SChris Mason 			btrfs_tree_unlock(cur);
16846b80053dSChris Mason 			free_extent_buffer(cur);
16856702ed49SChris Mason 			break;
1686252c38f0SYan 		}
1687e7a84565SChris Mason 		search_start = cur->start;
1688e7a84565SChris Mason 		last_block = cur->start;
1689f2183bdeSChris Mason 		*last_ret = search_start;
1690e7a84565SChris Mason 		btrfs_tree_unlock(cur);
1691e7a84565SChris Mason 		free_extent_buffer(cur);
16926702ed49SChris Mason 	}
16936702ed49SChris Mason 	return err;
16946702ed49SChris Mason }
16956702ed49SChris Mason 
169674123bd7SChris Mason /*
16975f39d397SChris Mason  * search for key in the extent_buffer.  The items start at offset p,
16985f39d397SChris Mason  * and they are item_size apart.  There are 'max' items in p.
16995f39d397SChris Mason  *
170074123bd7SChris Mason  * the slot in the array is returned via slot, and it points to
170174123bd7SChris Mason  * the place where you would insert key if it is not found in
170274123bd7SChris Mason  * the array.
170374123bd7SChris Mason  *
170474123bd7SChris Mason  * slot may point to max if the key is bigger than all of the keys
170574123bd7SChris Mason  */
1706e02119d5SChris Mason static noinline int generic_bin_search(struct extent_buffer *eb,
1707310712b2SOmar Sandoval 				       unsigned long p, int item_size,
1708310712b2SOmar Sandoval 				       const struct btrfs_key *key,
1709be0e5c09SChris Mason 				       int max, int *slot)
1710be0e5c09SChris Mason {
1711be0e5c09SChris Mason 	int low = 0;
1712be0e5c09SChris Mason 	int high = max;
1713be0e5c09SChris Mason 	int mid;
1714be0e5c09SChris Mason 	int ret;
1715479965d6SChris Mason 	struct btrfs_disk_key *tmp = NULL;
17165f39d397SChris Mason 	struct btrfs_disk_key unaligned;
17175f39d397SChris Mason 	unsigned long offset;
17185f39d397SChris Mason 	char *kaddr = NULL;
17195f39d397SChris Mason 	unsigned long map_start = 0;
17205f39d397SChris Mason 	unsigned long map_len = 0;
1721479965d6SChris Mason 	int err;
1722be0e5c09SChris Mason 
17235e24e9afSLiu Bo 	if (low > high) {
17245e24e9afSLiu Bo 		btrfs_err(eb->fs_info,
17255e24e9afSLiu Bo 		 "%s: low (%d) > high (%d) eb %llu owner %llu level %d",
17265e24e9afSLiu Bo 			  __func__, low, high, eb->start,
17275e24e9afSLiu Bo 			  btrfs_header_owner(eb), btrfs_header_level(eb));
17285e24e9afSLiu Bo 		return -EINVAL;
17295e24e9afSLiu Bo 	}
17305e24e9afSLiu Bo 
1731be0e5c09SChris Mason 	while (low < high) {
1732be0e5c09SChris Mason 		mid = (low + high) / 2;
17335f39d397SChris Mason 		offset = p + mid * item_size;
17345f39d397SChris Mason 
1735a6591715SChris Mason 		if (!kaddr || offset < map_start ||
17365f39d397SChris Mason 		    (offset + sizeof(struct btrfs_disk_key)) >
17375f39d397SChris Mason 		    map_start + map_len) {
1738934d375bSChris Mason 
1739934d375bSChris Mason 			err = map_private_extent_buffer(eb, offset,
1740479965d6SChris Mason 						sizeof(struct btrfs_disk_key),
1741a6591715SChris Mason 						&kaddr, &map_start, &map_len);
17425f39d397SChris Mason 
1743479965d6SChris Mason 			if (!err) {
1744479965d6SChris Mason 				tmp = (struct btrfs_disk_key *)(kaddr + offset -
1745479965d6SChris Mason 							map_start);
1746415b35a5SLiu Bo 			} else if (err == 1) {
17475f39d397SChris Mason 				read_extent_buffer(eb, &unaligned,
17485f39d397SChris Mason 						   offset, sizeof(unaligned));
17495f39d397SChris Mason 				tmp = &unaligned;
1750415b35a5SLiu Bo 			} else {
1751415b35a5SLiu Bo 				return err;
1752479965d6SChris Mason 			}
1753479965d6SChris Mason 
17545f39d397SChris Mason 		} else {
17555f39d397SChris Mason 			tmp = (struct btrfs_disk_key *)(kaddr + offset -
17565f39d397SChris Mason 							map_start);
17575f39d397SChris Mason 		}
1758be0e5c09SChris Mason 		ret = comp_keys(tmp, key);
1759be0e5c09SChris Mason 
1760be0e5c09SChris Mason 		if (ret < 0)
1761be0e5c09SChris Mason 			low = mid + 1;
1762be0e5c09SChris Mason 		else if (ret > 0)
1763be0e5c09SChris Mason 			high = mid;
1764be0e5c09SChris Mason 		else {
1765be0e5c09SChris Mason 			*slot = mid;
1766be0e5c09SChris Mason 			return 0;
1767be0e5c09SChris Mason 		}
1768be0e5c09SChris Mason 	}
1769be0e5c09SChris Mason 	*slot = low;
1770be0e5c09SChris Mason 	return 1;
1771be0e5c09SChris Mason }
1772be0e5c09SChris Mason 
177397571fd0SChris Mason /*
177497571fd0SChris Mason  * simple bin_search frontend that does the right thing for
177597571fd0SChris Mason  * leaves vs nodes
177697571fd0SChris Mason  */
1777a74b35ecSNikolay Borisov int btrfs_bin_search(struct extent_buffer *eb, const struct btrfs_key *key,
17785f39d397SChris Mason 		     int level, int *slot)
1779be0e5c09SChris Mason {
1780f775738fSWang Sheng-Hui 	if (level == 0)
17815f39d397SChris Mason 		return generic_bin_search(eb,
17825f39d397SChris Mason 					  offsetof(struct btrfs_leaf, items),
17830783fcfcSChris Mason 					  sizeof(struct btrfs_item),
17845f39d397SChris Mason 					  key, btrfs_header_nritems(eb),
17857518a238SChris Mason 					  slot);
1786f775738fSWang Sheng-Hui 	else
17875f39d397SChris Mason 		return generic_bin_search(eb,
17885f39d397SChris Mason 					  offsetof(struct btrfs_node, ptrs),
1789123abc88SChris Mason 					  sizeof(struct btrfs_key_ptr),
17905f39d397SChris Mason 					  key, btrfs_header_nritems(eb),
17917518a238SChris Mason 					  slot);
1792be0e5c09SChris Mason }
1793be0e5c09SChris Mason 
1794f0486c68SYan, Zheng static void root_add_used(struct btrfs_root *root, u32 size)
1795f0486c68SYan, Zheng {
1796f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
1797f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
1798f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) + size);
1799f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
1800f0486c68SYan, Zheng }
1801f0486c68SYan, Zheng 
1802f0486c68SYan, Zheng static void root_sub_used(struct btrfs_root *root, u32 size)
1803f0486c68SYan, Zheng {
1804f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
1805f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
1806f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) - size);
1807f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
1808f0486c68SYan, Zheng }
1809f0486c68SYan, Zheng 
1810d352ac68SChris Mason /* given a node and slot number, this reads the blocks it points to.  The
1811d352ac68SChris Mason  * extent buffer is returned with a reference taken (but unlocked).
1812d352ac68SChris Mason  */
18134b231ae4SDavid Sterba struct extent_buffer *btrfs_read_node_slot(struct extent_buffer *parent,
18144b231ae4SDavid Sterba 					   int slot)
1815bb803951SChris Mason {
1816ca7a79adSChris Mason 	int level = btrfs_header_level(parent);
1817416bc658SJosef Bacik 	struct extent_buffer *eb;
1818581c1760SQu Wenruo 	struct btrfs_key first_key;
1819416bc658SJosef Bacik 
1820fb770ae4SLiu Bo 	if (slot < 0 || slot >= btrfs_header_nritems(parent))
1821fb770ae4SLiu Bo 		return ERR_PTR(-ENOENT);
1822ca7a79adSChris Mason 
1823ca7a79adSChris Mason 	BUG_ON(level == 0);
1824ca7a79adSChris Mason 
1825581c1760SQu Wenruo 	btrfs_node_key_to_cpu(parent, &first_key, slot);
1826d0d20b0fSDavid Sterba 	eb = read_tree_block(parent->fs_info, btrfs_node_blockptr(parent, slot),
1827581c1760SQu Wenruo 			     btrfs_node_ptr_generation(parent, slot),
1828581c1760SQu Wenruo 			     level - 1, &first_key);
1829fb770ae4SLiu Bo 	if (!IS_ERR(eb) && !extent_buffer_uptodate(eb)) {
1830416bc658SJosef Bacik 		free_extent_buffer(eb);
1831fb770ae4SLiu Bo 		eb = ERR_PTR(-EIO);
1832416bc658SJosef Bacik 	}
1833416bc658SJosef Bacik 
1834416bc658SJosef Bacik 	return eb;
1835bb803951SChris Mason }
1836bb803951SChris Mason 
1837d352ac68SChris Mason /*
1838d352ac68SChris Mason  * node level balancing, used to make sure nodes are in proper order for
1839d352ac68SChris Mason  * item deletion.  We balance from the top down, so we have to make sure
1840d352ac68SChris Mason  * that a deletion won't leave an node completely empty later on.
1841d352ac68SChris Mason  */
1842e02119d5SChris Mason static noinline int balance_level(struct btrfs_trans_handle *trans,
184398ed5174SChris Mason 			 struct btrfs_root *root,
184498ed5174SChris Mason 			 struct btrfs_path *path, int level)
1845bb803951SChris Mason {
18460b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
18475f39d397SChris Mason 	struct extent_buffer *right = NULL;
18485f39d397SChris Mason 	struct extent_buffer *mid;
18495f39d397SChris Mason 	struct extent_buffer *left = NULL;
18505f39d397SChris Mason 	struct extent_buffer *parent = NULL;
1851bb803951SChris Mason 	int ret = 0;
1852bb803951SChris Mason 	int wret;
1853bb803951SChris Mason 	int pslot;
1854bb803951SChris Mason 	int orig_slot = path->slots[level];
185579f95c82SChris Mason 	u64 orig_ptr;
1856bb803951SChris Mason 
185798e6b1ebSLiu Bo 	ASSERT(level > 0);
1858bb803951SChris Mason 
18595f39d397SChris Mason 	mid = path->nodes[level];
1860b4ce94deSChris Mason 
1861bd681513SChris Mason 	WARN_ON(path->locks[level] != BTRFS_WRITE_LOCK &&
1862bd681513SChris Mason 		path->locks[level] != BTRFS_WRITE_LOCK_BLOCKING);
18637bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
18647bb86316SChris Mason 
18651d4f8a0cSChris Mason 	orig_ptr = btrfs_node_blockptr(mid, orig_slot);
186679f95c82SChris Mason 
1867a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
18685f39d397SChris Mason 		parent = path->nodes[level + 1];
1869bb803951SChris Mason 		pslot = path->slots[level + 1];
1870a05a9bb1SLi Zefan 	}
1871bb803951SChris Mason 
187240689478SChris Mason 	/*
187340689478SChris Mason 	 * deal with the case where there is only one pointer in the root
187440689478SChris Mason 	 * by promoting the node below to a root
187540689478SChris Mason 	 */
18765f39d397SChris Mason 	if (!parent) {
18775f39d397SChris Mason 		struct extent_buffer *child;
1878bb803951SChris Mason 
18795f39d397SChris Mason 		if (btrfs_header_nritems(mid) != 1)
1880bb803951SChris Mason 			return 0;
1881bb803951SChris Mason 
1882bb803951SChris Mason 		/* promote the child to a root */
18834b231ae4SDavid Sterba 		child = btrfs_read_node_slot(mid, 0);
1884fb770ae4SLiu Bo 		if (IS_ERR(child)) {
1885fb770ae4SLiu Bo 			ret = PTR_ERR(child);
18860b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
1887305a26afSMark Fasheh 			goto enospc;
1888305a26afSMark Fasheh 		}
1889305a26afSMark Fasheh 
1890925baeddSChris Mason 		btrfs_tree_lock(child);
18918bead258SDavid Sterba 		btrfs_set_lock_blocking_write(child);
18929fa8cfe7SChris Mason 		ret = btrfs_cow_block(trans, root, child, mid, 0, &child);
1893f0486c68SYan, Zheng 		if (ret) {
1894f0486c68SYan, Zheng 			btrfs_tree_unlock(child);
1895f0486c68SYan, Zheng 			free_extent_buffer(child);
1896f0486c68SYan, Zheng 			goto enospc;
1897f0486c68SYan, Zheng 		}
18982f375ab9SYan 
1899d9d19a01SDavid Sterba 		ret = tree_mod_log_insert_root(root->node, child, 1);
1900d9d19a01SDavid Sterba 		BUG_ON(ret < 0);
1901240f62c8SChris Mason 		rcu_assign_pointer(root->node, child);
1902925baeddSChris Mason 
19030b86a832SChris Mason 		add_root_to_dirty_list(root);
1904925baeddSChris Mason 		btrfs_tree_unlock(child);
1905b4ce94deSChris Mason 
1906925baeddSChris Mason 		path->locks[level] = 0;
1907bb803951SChris Mason 		path->nodes[level] = NULL;
19086a884d7dSDavid Sterba 		btrfs_clean_tree_block(mid);
1909925baeddSChris Mason 		btrfs_tree_unlock(mid);
1910bb803951SChris Mason 		/* once for the path */
19115f39d397SChris Mason 		free_extent_buffer(mid);
1912f0486c68SYan, Zheng 
1913f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
19145581a51aSJan Schmidt 		btrfs_free_tree_block(trans, root, mid, 0, 1);
1915bb803951SChris Mason 		/* once for the root ptr */
19163083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
1917f0486c68SYan, Zheng 		return 0;
1918bb803951SChris Mason 	}
19195f39d397SChris Mason 	if (btrfs_header_nritems(mid) >
19200b246afaSJeff Mahoney 	    BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 4)
1921bb803951SChris Mason 		return 0;
1922bb803951SChris Mason 
19234b231ae4SDavid Sterba 	left = btrfs_read_node_slot(parent, pslot - 1);
1924fb770ae4SLiu Bo 	if (IS_ERR(left))
1925fb770ae4SLiu Bo 		left = NULL;
1926fb770ae4SLiu Bo 
19275f39d397SChris Mason 	if (left) {
1928925baeddSChris Mason 		btrfs_tree_lock(left);
19298bead258SDavid Sterba 		btrfs_set_lock_blocking_write(left);
19305f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, left,
19319fa8cfe7SChris Mason 				       parent, pslot - 1, &left);
193254aa1f4dSChris Mason 		if (wret) {
193354aa1f4dSChris Mason 			ret = wret;
193454aa1f4dSChris Mason 			goto enospc;
193554aa1f4dSChris Mason 		}
19362cc58cf2SChris Mason 	}
1937fb770ae4SLiu Bo 
19384b231ae4SDavid Sterba 	right = btrfs_read_node_slot(parent, pslot + 1);
1939fb770ae4SLiu Bo 	if (IS_ERR(right))
1940fb770ae4SLiu Bo 		right = NULL;
1941fb770ae4SLiu Bo 
19425f39d397SChris Mason 	if (right) {
1943925baeddSChris Mason 		btrfs_tree_lock(right);
19448bead258SDavid Sterba 		btrfs_set_lock_blocking_write(right);
19455f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, right,
19469fa8cfe7SChris Mason 				       parent, pslot + 1, &right);
19472cc58cf2SChris Mason 		if (wret) {
19482cc58cf2SChris Mason 			ret = wret;
19492cc58cf2SChris Mason 			goto enospc;
19502cc58cf2SChris Mason 		}
19512cc58cf2SChris Mason 	}
19522cc58cf2SChris Mason 
19532cc58cf2SChris Mason 	/* first, try to make some room in the middle buffer */
19545f39d397SChris Mason 	if (left) {
19555f39d397SChris Mason 		orig_slot += btrfs_header_nritems(left);
1956d30a668fSDavid Sterba 		wret = push_node_left(trans, left, mid, 1);
195779f95c82SChris Mason 		if (wret < 0)
195879f95c82SChris Mason 			ret = wret;
1959bb803951SChris Mason 	}
196079f95c82SChris Mason 
196179f95c82SChris Mason 	/*
196279f95c82SChris Mason 	 * then try to empty the right most buffer into the middle
196379f95c82SChris Mason 	 */
19645f39d397SChris Mason 	if (right) {
1965d30a668fSDavid Sterba 		wret = push_node_left(trans, mid, right, 1);
196654aa1f4dSChris Mason 		if (wret < 0 && wret != -ENOSPC)
196779f95c82SChris Mason 			ret = wret;
19685f39d397SChris Mason 		if (btrfs_header_nritems(right) == 0) {
19696a884d7dSDavid Sterba 			btrfs_clean_tree_block(right);
1970925baeddSChris Mason 			btrfs_tree_unlock(right);
1971afe5fea7STsutomu Itoh 			del_ptr(root, path, level + 1, pslot + 1);
1972f0486c68SYan, Zheng 			root_sub_used(root, right->len);
19735581a51aSJan Schmidt 			btrfs_free_tree_block(trans, root, right, 0, 1);
19743083ee2eSJosef Bacik 			free_extent_buffer_stale(right);
1975f0486c68SYan, Zheng 			right = NULL;
1976bb803951SChris Mason 		} else {
19775f39d397SChris Mason 			struct btrfs_disk_key right_key;
19785f39d397SChris Mason 			btrfs_node_key(right, &right_key, 0);
19790e82bcfeSDavid Sterba 			ret = tree_mod_log_insert_key(parent, pslot + 1,
19800e82bcfeSDavid Sterba 					MOD_LOG_KEY_REPLACE, GFP_NOFS);
19810e82bcfeSDavid Sterba 			BUG_ON(ret < 0);
19825f39d397SChris Mason 			btrfs_set_node_key(parent, &right_key, pslot + 1);
19835f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
1984bb803951SChris Mason 		}
1985bb803951SChris Mason 	}
19865f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 1) {
198779f95c82SChris Mason 		/*
198879f95c82SChris Mason 		 * we're not allowed to leave a node with one item in the
198979f95c82SChris Mason 		 * tree during a delete.  A deletion from lower in the tree
199079f95c82SChris Mason 		 * could try to delete the only pointer in this node.
199179f95c82SChris Mason 		 * So, pull some keys from the left.
199279f95c82SChris Mason 		 * There has to be a left pointer at this point because
199379f95c82SChris Mason 		 * otherwise we would have pulled some pointers from the
199479f95c82SChris Mason 		 * right
199579f95c82SChris Mason 		 */
1996305a26afSMark Fasheh 		if (!left) {
1997305a26afSMark Fasheh 			ret = -EROFS;
19980b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
1999305a26afSMark Fasheh 			goto enospc;
2000305a26afSMark Fasheh 		}
200155d32ed8SDavid Sterba 		wret = balance_node_right(trans, mid, left);
200254aa1f4dSChris Mason 		if (wret < 0) {
200379f95c82SChris Mason 			ret = wret;
200454aa1f4dSChris Mason 			goto enospc;
200554aa1f4dSChris Mason 		}
2006bce4eae9SChris Mason 		if (wret == 1) {
2007d30a668fSDavid Sterba 			wret = push_node_left(trans, left, mid, 1);
2008bce4eae9SChris Mason 			if (wret < 0)
2009bce4eae9SChris Mason 				ret = wret;
2010bce4eae9SChris Mason 		}
201179f95c82SChris Mason 		BUG_ON(wret == 1);
201279f95c82SChris Mason 	}
20135f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 0) {
20146a884d7dSDavid Sterba 		btrfs_clean_tree_block(mid);
2015925baeddSChris Mason 		btrfs_tree_unlock(mid);
2016afe5fea7STsutomu Itoh 		del_ptr(root, path, level + 1, pslot);
2017f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
20185581a51aSJan Schmidt 		btrfs_free_tree_block(trans, root, mid, 0, 1);
20193083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
2020f0486c68SYan, Zheng 		mid = NULL;
202179f95c82SChris Mason 	} else {
202279f95c82SChris Mason 		/* update the parent key to reflect our changes */
20235f39d397SChris Mason 		struct btrfs_disk_key mid_key;
20245f39d397SChris Mason 		btrfs_node_key(mid, &mid_key, 0);
20250e82bcfeSDavid Sterba 		ret = tree_mod_log_insert_key(parent, pslot,
20260e82bcfeSDavid Sterba 				MOD_LOG_KEY_REPLACE, GFP_NOFS);
20270e82bcfeSDavid Sterba 		BUG_ON(ret < 0);
20285f39d397SChris Mason 		btrfs_set_node_key(parent, &mid_key, pslot);
20295f39d397SChris Mason 		btrfs_mark_buffer_dirty(parent);
203079f95c82SChris Mason 	}
2031bb803951SChris Mason 
203279f95c82SChris Mason 	/* update the path */
20335f39d397SChris Mason 	if (left) {
20345f39d397SChris Mason 		if (btrfs_header_nritems(left) > orig_slot) {
203567439dadSDavid Sterba 			atomic_inc(&left->refs);
2036925baeddSChris Mason 			/* left was locked after cow */
20375f39d397SChris Mason 			path->nodes[level] = left;
2038bb803951SChris Mason 			path->slots[level + 1] -= 1;
2039bb803951SChris Mason 			path->slots[level] = orig_slot;
2040925baeddSChris Mason 			if (mid) {
2041925baeddSChris Mason 				btrfs_tree_unlock(mid);
20425f39d397SChris Mason 				free_extent_buffer(mid);
2043925baeddSChris Mason 			}
2044bb803951SChris Mason 		} else {
20455f39d397SChris Mason 			orig_slot -= btrfs_header_nritems(left);
2046bb803951SChris Mason 			path->slots[level] = orig_slot;
2047bb803951SChris Mason 		}
2048bb803951SChris Mason 	}
204979f95c82SChris Mason 	/* double check we haven't messed things up */
2050e20d96d6SChris Mason 	if (orig_ptr !=
20515f39d397SChris Mason 	    btrfs_node_blockptr(path->nodes[level], path->slots[level]))
205279f95c82SChris Mason 		BUG();
205354aa1f4dSChris Mason enospc:
2054925baeddSChris Mason 	if (right) {
2055925baeddSChris Mason 		btrfs_tree_unlock(right);
20565f39d397SChris Mason 		free_extent_buffer(right);
2057925baeddSChris Mason 	}
2058925baeddSChris Mason 	if (left) {
2059925baeddSChris Mason 		if (path->nodes[level] != left)
2060925baeddSChris Mason 			btrfs_tree_unlock(left);
20615f39d397SChris Mason 		free_extent_buffer(left);
2062925baeddSChris Mason 	}
2063bb803951SChris Mason 	return ret;
2064bb803951SChris Mason }
2065bb803951SChris Mason 
2066d352ac68SChris Mason /* Node balancing for insertion.  Here we only split or push nodes around
2067d352ac68SChris Mason  * when they are completely full.  This is also done top down, so we
2068d352ac68SChris Mason  * have to be pessimistic.
2069d352ac68SChris Mason  */
2070d397712bSChris Mason static noinline int push_nodes_for_insert(struct btrfs_trans_handle *trans,
2071e66f709bSChris Mason 					  struct btrfs_root *root,
2072e66f709bSChris Mason 					  struct btrfs_path *path, int level)
2073e66f709bSChris Mason {
20740b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
20755f39d397SChris Mason 	struct extent_buffer *right = NULL;
20765f39d397SChris Mason 	struct extent_buffer *mid;
20775f39d397SChris Mason 	struct extent_buffer *left = NULL;
20785f39d397SChris Mason 	struct extent_buffer *parent = NULL;
2079e66f709bSChris Mason 	int ret = 0;
2080e66f709bSChris Mason 	int wret;
2081e66f709bSChris Mason 	int pslot;
2082e66f709bSChris Mason 	int orig_slot = path->slots[level];
2083e66f709bSChris Mason 
2084e66f709bSChris Mason 	if (level == 0)
2085e66f709bSChris Mason 		return 1;
2086e66f709bSChris Mason 
20875f39d397SChris Mason 	mid = path->nodes[level];
20887bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
2089e66f709bSChris Mason 
2090a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
20915f39d397SChris Mason 		parent = path->nodes[level + 1];
2092e66f709bSChris Mason 		pslot = path->slots[level + 1];
2093a05a9bb1SLi Zefan 	}
2094e66f709bSChris Mason 
20955f39d397SChris Mason 	if (!parent)
2096e66f709bSChris Mason 		return 1;
2097e66f709bSChris Mason 
20984b231ae4SDavid Sterba 	left = btrfs_read_node_slot(parent, pslot - 1);
2099fb770ae4SLiu Bo 	if (IS_ERR(left))
2100fb770ae4SLiu Bo 		left = NULL;
2101e66f709bSChris Mason 
2102e66f709bSChris Mason 	/* first, try to make some room in the middle buffer */
21035f39d397SChris Mason 	if (left) {
2104e66f709bSChris Mason 		u32 left_nr;
2105925baeddSChris Mason 
2106925baeddSChris Mason 		btrfs_tree_lock(left);
21078bead258SDavid Sterba 		btrfs_set_lock_blocking_write(left);
2108b4ce94deSChris Mason 
21095f39d397SChris Mason 		left_nr = btrfs_header_nritems(left);
21100b246afaSJeff Mahoney 		if (left_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
211133ade1f8SChris Mason 			wret = 1;
211233ade1f8SChris Mason 		} else {
21135f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, left, parent,
21149fa8cfe7SChris Mason 					      pslot - 1, &left);
211554aa1f4dSChris Mason 			if (ret)
211654aa1f4dSChris Mason 				wret = 1;
211754aa1f4dSChris Mason 			else {
2118d30a668fSDavid Sterba 				wret = push_node_left(trans, left, mid, 0);
211954aa1f4dSChris Mason 			}
212033ade1f8SChris Mason 		}
2121e66f709bSChris Mason 		if (wret < 0)
2122e66f709bSChris Mason 			ret = wret;
2123e66f709bSChris Mason 		if (wret == 0) {
21245f39d397SChris Mason 			struct btrfs_disk_key disk_key;
2125e66f709bSChris Mason 			orig_slot += left_nr;
21265f39d397SChris Mason 			btrfs_node_key(mid, &disk_key, 0);
21270e82bcfeSDavid Sterba 			ret = tree_mod_log_insert_key(parent, pslot,
21280e82bcfeSDavid Sterba 					MOD_LOG_KEY_REPLACE, GFP_NOFS);
21290e82bcfeSDavid Sterba 			BUG_ON(ret < 0);
21305f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot);
21315f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
21325f39d397SChris Mason 			if (btrfs_header_nritems(left) > orig_slot) {
21335f39d397SChris Mason 				path->nodes[level] = left;
2134e66f709bSChris Mason 				path->slots[level + 1] -= 1;
2135e66f709bSChris Mason 				path->slots[level] = orig_slot;
2136925baeddSChris Mason 				btrfs_tree_unlock(mid);
21375f39d397SChris Mason 				free_extent_buffer(mid);
2138e66f709bSChris Mason 			} else {
2139e66f709bSChris Mason 				orig_slot -=
21405f39d397SChris Mason 					btrfs_header_nritems(left);
2141e66f709bSChris Mason 				path->slots[level] = orig_slot;
2142925baeddSChris Mason 				btrfs_tree_unlock(left);
21435f39d397SChris Mason 				free_extent_buffer(left);
2144e66f709bSChris Mason 			}
2145e66f709bSChris Mason 			return 0;
2146e66f709bSChris Mason 		}
2147925baeddSChris Mason 		btrfs_tree_unlock(left);
21485f39d397SChris Mason 		free_extent_buffer(left);
2149e66f709bSChris Mason 	}
21504b231ae4SDavid Sterba 	right = btrfs_read_node_slot(parent, pslot + 1);
2151fb770ae4SLiu Bo 	if (IS_ERR(right))
2152fb770ae4SLiu Bo 		right = NULL;
2153e66f709bSChris Mason 
2154e66f709bSChris Mason 	/*
2155e66f709bSChris Mason 	 * then try to empty the right most buffer into the middle
2156e66f709bSChris Mason 	 */
21575f39d397SChris Mason 	if (right) {
215833ade1f8SChris Mason 		u32 right_nr;
2159b4ce94deSChris Mason 
2160925baeddSChris Mason 		btrfs_tree_lock(right);
21618bead258SDavid Sterba 		btrfs_set_lock_blocking_write(right);
2162b4ce94deSChris Mason 
21635f39d397SChris Mason 		right_nr = btrfs_header_nritems(right);
21640b246afaSJeff Mahoney 		if (right_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
216533ade1f8SChris Mason 			wret = 1;
216633ade1f8SChris Mason 		} else {
21675f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, right,
21685f39d397SChris Mason 					      parent, pslot + 1,
21699fa8cfe7SChris Mason 					      &right);
217054aa1f4dSChris Mason 			if (ret)
217154aa1f4dSChris Mason 				wret = 1;
217254aa1f4dSChris Mason 			else {
217355d32ed8SDavid Sterba 				wret = balance_node_right(trans, right, mid);
217433ade1f8SChris Mason 			}
217554aa1f4dSChris Mason 		}
2176e66f709bSChris Mason 		if (wret < 0)
2177e66f709bSChris Mason 			ret = wret;
2178e66f709bSChris Mason 		if (wret == 0) {
21795f39d397SChris Mason 			struct btrfs_disk_key disk_key;
21805f39d397SChris Mason 
21815f39d397SChris Mason 			btrfs_node_key(right, &disk_key, 0);
21820e82bcfeSDavid Sterba 			ret = tree_mod_log_insert_key(parent, pslot + 1,
21830e82bcfeSDavid Sterba 					MOD_LOG_KEY_REPLACE, GFP_NOFS);
21840e82bcfeSDavid Sterba 			BUG_ON(ret < 0);
21855f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot + 1);
21865f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
21875f39d397SChris Mason 
21885f39d397SChris Mason 			if (btrfs_header_nritems(mid) <= orig_slot) {
21895f39d397SChris Mason 				path->nodes[level] = right;
2190e66f709bSChris Mason 				path->slots[level + 1] += 1;
2191e66f709bSChris Mason 				path->slots[level] = orig_slot -
21925f39d397SChris Mason 					btrfs_header_nritems(mid);
2193925baeddSChris Mason 				btrfs_tree_unlock(mid);
21945f39d397SChris Mason 				free_extent_buffer(mid);
2195e66f709bSChris Mason 			} else {
2196925baeddSChris Mason 				btrfs_tree_unlock(right);
21975f39d397SChris Mason 				free_extent_buffer(right);
2198e66f709bSChris Mason 			}
2199e66f709bSChris Mason 			return 0;
2200e66f709bSChris Mason 		}
2201925baeddSChris Mason 		btrfs_tree_unlock(right);
22025f39d397SChris Mason 		free_extent_buffer(right);
2203e66f709bSChris Mason 	}
2204e66f709bSChris Mason 	return 1;
2205e66f709bSChris Mason }
2206e66f709bSChris Mason 
220774123bd7SChris Mason /*
2208d352ac68SChris Mason  * readahead one full node of leaves, finding things that are close
2209d352ac68SChris Mason  * to the block in 'slot', and triggering ra on them.
22103c69faecSChris Mason  */
22112ff7e61eSJeff Mahoney static void reada_for_search(struct btrfs_fs_info *fs_info,
2212e02119d5SChris Mason 			     struct btrfs_path *path,
221301f46658SChris Mason 			     int level, int slot, u64 objectid)
22143c69faecSChris Mason {
22155f39d397SChris Mason 	struct extent_buffer *node;
221601f46658SChris Mason 	struct btrfs_disk_key disk_key;
22173c69faecSChris Mason 	u32 nritems;
22183c69faecSChris Mason 	u64 search;
2219a7175319SChris Mason 	u64 target;
22206b80053dSChris Mason 	u64 nread = 0;
22215f39d397SChris Mason 	struct extent_buffer *eb;
22226b80053dSChris Mason 	u32 nr;
22236b80053dSChris Mason 	u32 blocksize;
22246b80053dSChris Mason 	u32 nscan = 0;
2225db94535dSChris Mason 
2226a6b6e75eSChris Mason 	if (level != 1)
22273c69faecSChris Mason 		return;
22283c69faecSChris Mason 
22296702ed49SChris Mason 	if (!path->nodes[level])
22306702ed49SChris Mason 		return;
22316702ed49SChris Mason 
22325f39d397SChris Mason 	node = path->nodes[level];
2233925baeddSChris Mason 
22343c69faecSChris Mason 	search = btrfs_node_blockptr(node, slot);
22350b246afaSJeff Mahoney 	blocksize = fs_info->nodesize;
22360b246afaSJeff Mahoney 	eb = find_extent_buffer(fs_info, search);
22375f39d397SChris Mason 	if (eb) {
22385f39d397SChris Mason 		free_extent_buffer(eb);
22393c69faecSChris Mason 		return;
22403c69faecSChris Mason 	}
22413c69faecSChris Mason 
2242a7175319SChris Mason 	target = search;
22436b80053dSChris Mason 
22445f39d397SChris Mason 	nritems = btrfs_header_nritems(node);
22456b80053dSChris Mason 	nr = slot;
224625b8b936SJosef Bacik 
22473c69faecSChris Mason 	while (1) {
2248e4058b54SDavid Sterba 		if (path->reada == READA_BACK) {
22496b80053dSChris Mason 			if (nr == 0)
22503c69faecSChris Mason 				break;
22516b80053dSChris Mason 			nr--;
2252e4058b54SDavid Sterba 		} else if (path->reada == READA_FORWARD) {
22536b80053dSChris Mason 			nr++;
22546b80053dSChris Mason 			if (nr >= nritems)
22556b80053dSChris Mason 				break;
22563c69faecSChris Mason 		}
2257e4058b54SDavid Sterba 		if (path->reada == READA_BACK && objectid) {
225801f46658SChris Mason 			btrfs_node_key(node, &disk_key, nr);
225901f46658SChris Mason 			if (btrfs_disk_key_objectid(&disk_key) != objectid)
226001f46658SChris Mason 				break;
226101f46658SChris Mason 		}
22626b80053dSChris Mason 		search = btrfs_node_blockptr(node, nr);
2263a7175319SChris Mason 		if ((search <= target && target - search <= 65536) ||
2264a7175319SChris Mason 		    (search > target && search - target <= 65536)) {
22652ff7e61eSJeff Mahoney 			readahead_tree_block(fs_info, search);
22666b80053dSChris Mason 			nread += blocksize;
22673c69faecSChris Mason 		}
22686b80053dSChris Mason 		nscan++;
2269a7175319SChris Mason 		if ((nread > 65536 || nscan > 32))
22706b80053dSChris Mason 			break;
22713c69faecSChris Mason 	}
22723c69faecSChris Mason }
2273925baeddSChris Mason 
22742ff7e61eSJeff Mahoney static noinline void reada_for_balance(struct btrfs_fs_info *fs_info,
2275b4ce94deSChris Mason 				       struct btrfs_path *path, int level)
2276b4ce94deSChris Mason {
2277b4ce94deSChris Mason 	int slot;
2278b4ce94deSChris Mason 	int nritems;
2279b4ce94deSChris Mason 	struct extent_buffer *parent;
2280b4ce94deSChris Mason 	struct extent_buffer *eb;
2281b4ce94deSChris Mason 	u64 gen;
2282b4ce94deSChris Mason 	u64 block1 = 0;
2283b4ce94deSChris Mason 	u64 block2 = 0;
2284b4ce94deSChris Mason 
22858c594ea8SChris Mason 	parent = path->nodes[level + 1];
2286b4ce94deSChris Mason 	if (!parent)
22870b08851fSJosef Bacik 		return;
2288b4ce94deSChris Mason 
2289b4ce94deSChris Mason 	nritems = btrfs_header_nritems(parent);
22908c594ea8SChris Mason 	slot = path->slots[level + 1];
2291b4ce94deSChris Mason 
2292b4ce94deSChris Mason 	if (slot > 0) {
2293b4ce94deSChris Mason 		block1 = btrfs_node_blockptr(parent, slot - 1);
2294b4ce94deSChris Mason 		gen = btrfs_node_ptr_generation(parent, slot - 1);
22950b246afaSJeff Mahoney 		eb = find_extent_buffer(fs_info, block1);
2296b9fab919SChris Mason 		/*
2297b9fab919SChris Mason 		 * if we get -eagain from btrfs_buffer_uptodate, we
2298b9fab919SChris Mason 		 * don't want to return eagain here.  That will loop
2299b9fab919SChris Mason 		 * forever
2300b9fab919SChris Mason 		 */
2301b9fab919SChris Mason 		if (eb && btrfs_buffer_uptodate(eb, gen, 1) != 0)
2302b4ce94deSChris Mason 			block1 = 0;
2303b4ce94deSChris Mason 		free_extent_buffer(eb);
2304b4ce94deSChris Mason 	}
23058c594ea8SChris Mason 	if (slot + 1 < nritems) {
2306b4ce94deSChris Mason 		block2 = btrfs_node_blockptr(parent, slot + 1);
2307b4ce94deSChris Mason 		gen = btrfs_node_ptr_generation(parent, slot + 1);
23080b246afaSJeff Mahoney 		eb = find_extent_buffer(fs_info, block2);
2309b9fab919SChris Mason 		if (eb && btrfs_buffer_uptodate(eb, gen, 1) != 0)
2310b4ce94deSChris Mason 			block2 = 0;
2311b4ce94deSChris Mason 		free_extent_buffer(eb);
2312b4ce94deSChris Mason 	}
23138c594ea8SChris Mason 
2314b4ce94deSChris Mason 	if (block1)
23152ff7e61eSJeff Mahoney 		readahead_tree_block(fs_info, block1);
2316b4ce94deSChris Mason 	if (block2)
23172ff7e61eSJeff Mahoney 		readahead_tree_block(fs_info, block2);
2318b4ce94deSChris Mason }
2319b4ce94deSChris Mason 
2320b4ce94deSChris Mason 
2321b4ce94deSChris Mason /*
2322d397712bSChris Mason  * when we walk down the tree, it is usually safe to unlock the higher layers
2323d397712bSChris Mason  * in the tree.  The exceptions are when our path goes through slot 0, because
2324d397712bSChris Mason  * operations on the tree might require changing key pointers higher up in the
2325d397712bSChris Mason  * tree.
2326d352ac68SChris Mason  *
2327d397712bSChris Mason  * callers might also have set path->keep_locks, which tells this code to keep
2328d397712bSChris Mason  * the lock if the path points to the last slot in the block.  This is part of
2329d397712bSChris Mason  * walking through the tree, and selecting the next slot in the higher block.
2330d352ac68SChris Mason  *
2331d397712bSChris Mason  * lowest_unlock sets the lowest level in the tree we're allowed to unlock.  so
2332d397712bSChris Mason  * if lowest_unlock is 1, level 0 won't be unlocked
2333d352ac68SChris Mason  */
2334e02119d5SChris Mason static noinline void unlock_up(struct btrfs_path *path, int level,
2335f7c79f30SChris Mason 			       int lowest_unlock, int min_write_lock_level,
2336f7c79f30SChris Mason 			       int *write_lock_level)
2337925baeddSChris Mason {
2338925baeddSChris Mason 	int i;
2339925baeddSChris Mason 	int skip_level = level;
2340051e1b9fSChris Mason 	int no_skips = 0;
2341925baeddSChris Mason 	struct extent_buffer *t;
2342925baeddSChris Mason 
2343925baeddSChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2344925baeddSChris Mason 		if (!path->nodes[i])
2345925baeddSChris Mason 			break;
2346925baeddSChris Mason 		if (!path->locks[i])
2347925baeddSChris Mason 			break;
2348051e1b9fSChris Mason 		if (!no_skips && path->slots[i] == 0) {
2349925baeddSChris Mason 			skip_level = i + 1;
2350925baeddSChris Mason 			continue;
2351925baeddSChris Mason 		}
2352051e1b9fSChris Mason 		if (!no_skips && path->keep_locks) {
2353925baeddSChris Mason 			u32 nritems;
2354925baeddSChris Mason 			t = path->nodes[i];
2355925baeddSChris Mason 			nritems = btrfs_header_nritems(t);
2356051e1b9fSChris Mason 			if (nritems < 1 || path->slots[i] >= nritems - 1) {
2357925baeddSChris Mason 				skip_level = i + 1;
2358925baeddSChris Mason 				continue;
2359925baeddSChris Mason 			}
2360925baeddSChris Mason 		}
2361051e1b9fSChris Mason 		if (skip_level < i && i >= lowest_unlock)
2362051e1b9fSChris Mason 			no_skips = 1;
2363051e1b9fSChris Mason 
2364925baeddSChris Mason 		t = path->nodes[i];
2365d80bb3f9SLiu Bo 		if (i >= lowest_unlock && i > skip_level) {
2366bd681513SChris Mason 			btrfs_tree_unlock_rw(t, path->locks[i]);
2367925baeddSChris Mason 			path->locks[i] = 0;
2368f7c79f30SChris Mason 			if (write_lock_level &&
2369f7c79f30SChris Mason 			    i > min_write_lock_level &&
2370f7c79f30SChris Mason 			    i <= *write_lock_level) {
2371f7c79f30SChris Mason 				*write_lock_level = i - 1;
2372f7c79f30SChris Mason 			}
2373925baeddSChris Mason 		}
2374925baeddSChris Mason 	}
2375925baeddSChris Mason }
2376925baeddSChris Mason 
23773c69faecSChris Mason /*
2378c8c42864SChris Mason  * helper function for btrfs_search_slot.  The goal is to find a block
2379c8c42864SChris Mason  * in cache without setting the path to blocking.  If we find the block
2380c8c42864SChris Mason  * we return zero and the path is unchanged.
2381c8c42864SChris Mason  *
2382c8c42864SChris Mason  * If we can't find the block, we set the path blocking and do some
2383c8c42864SChris Mason  * reada.  -EAGAIN is returned and the search must be repeated.
2384c8c42864SChris Mason  */
2385c8c42864SChris Mason static int
2386d07b8528SLiu Bo read_block_for_search(struct btrfs_root *root, struct btrfs_path *p,
2387c8c42864SChris Mason 		      struct extent_buffer **eb_ret, int level, int slot,
2388cda79c54SDavid Sterba 		      const struct btrfs_key *key)
2389c8c42864SChris Mason {
23900b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
2391c8c42864SChris Mason 	u64 blocknr;
2392c8c42864SChris Mason 	u64 gen;
2393c8c42864SChris Mason 	struct extent_buffer *b = *eb_ret;
2394c8c42864SChris Mason 	struct extent_buffer *tmp;
2395581c1760SQu Wenruo 	struct btrfs_key first_key;
239676a05b35SChris Mason 	int ret;
2397581c1760SQu Wenruo 	int parent_level;
2398c8c42864SChris Mason 
2399c8c42864SChris Mason 	blocknr = btrfs_node_blockptr(b, slot);
2400c8c42864SChris Mason 	gen = btrfs_node_ptr_generation(b, slot);
2401581c1760SQu Wenruo 	parent_level = btrfs_header_level(b);
2402581c1760SQu Wenruo 	btrfs_node_key_to_cpu(b, &first_key, slot);
2403c8c42864SChris Mason 
24040b246afaSJeff Mahoney 	tmp = find_extent_buffer(fs_info, blocknr);
2405cb44921aSChris Mason 	if (tmp) {
2406b9fab919SChris Mason 		/* first we do an atomic uptodate check */
2407b9fab919SChris Mason 		if (btrfs_buffer_uptodate(tmp, gen, 1) > 0) {
2408448de471SQu Wenruo 			/*
2409448de471SQu Wenruo 			 * Do extra check for first_key, eb can be stale due to
2410448de471SQu Wenruo 			 * being cached, read from scrub, or have multiple
2411448de471SQu Wenruo 			 * parents (shared tree blocks).
2412448de471SQu Wenruo 			 */
2413e064d5e9SDavid Sterba 			if (btrfs_verify_level_key(tmp,
2414448de471SQu Wenruo 					parent_level - 1, &first_key, gen)) {
2415448de471SQu Wenruo 				free_extent_buffer(tmp);
2416448de471SQu Wenruo 				return -EUCLEAN;
2417448de471SQu Wenruo 			}
2418c8c42864SChris Mason 			*eb_ret = tmp;
2419c8c42864SChris Mason 			return 0;
2420c8c42864SChris Mason 		}
2421bdf7c00eSJosef Bacik 
2422cb44921aSChris Mason 		/* the pages were up to date, but we failed
2423cb44921aSChris Mason 		 * the generation number check.  Do a full
2424cb44921aSChris Mason 		 * read for the generation number that is correct.
2425cb44921aSChris Mason 		 * We must do this without dropping locks so
2426cb44921aSChris Mason 		 * we can trust our generation number
2427cb44921aSChris Mason 		 */
2428bd681513SChris Mason 		btrfs_set_path_blocking(p);
2429bd681513SChris Mason 
2430b9fab919SChris Mason 		/* now we're allowed to do a blocking uptodate check */
2431581c1760SQu Wenruo 		ret = btrfs_read_buffer(tmp, gen, parent_level - 1, &first_key);
2432bdf7c00eSJosef Bacik 		if (!ret) {
2433cb44921aSChris Mason 			*eb_ret = tmp;
2434cb44921aSChris Mason 			return 0;
2435cb44921aSChris Mason 		}
2436cb44921aSChris Mason 		free_extent_buffer(tmp);
2437b3b4aa74SDavid Sterba 		btrfs_release_path(p);
2438cb44921aSChris Mason 		return -EIO;
2439cb44921aSChris Mason 	}
2440c8c42864SChris Mason 
2441c8c42864SChris Mason 	/*
2442c8c42864SChris Mason 	 * reduce lock contention at high levels
2443c8c42864SChris Mason 	 * of the btree by dropping locks before
244476a05b35SChris Mason 	 * we read.  Don't release the lock on the current
244576a05b35SChris Mason 	 * level because we need to walk this node to figure
244676a05b35SChris Mason 	 * out which blocks to read.
2447c8c42864SChris Mason 	 */
24488c594ea8SChris Mason 	btrfs_unlock_up_safe(p, level + 1);
24498c594ea8SChris Mason 	btrfs_set_path_blocking(p);
24508c594ea8SChris Mason 
2451e4058b54SDavid Sterba 	if (p->reada != READA_NONE)
24522ff7e61eSJeff Mahoney 		reada_for_search(fs_info, p, level, slot, key->objectid);
2453c8c42864SChris Mason 
245476a05b35SChris Mason 	ret = -EAGAIN;
245502a3307aSLiu Bo 	tmp = read_tree_block(fs_info, blocknr, gen, parent_level - 1,
2456581c1760SQu Wenruo 			      &first_key);
245764c043deSLiu Bo 	if (!IS_ERR(tmp)) {
245876a05b35SChris Mason 		/*
245976a05b35SChris Mason 		 * If the read above didn't mark this buffer up to date,
246076a05b35SChris Mason 		 * it will never end up being up to date.  Set ret to EIO now
246176a05b35SChris Mason 		 * and give up so that our caller doesn't loop forever
246276a05b35SChris Mason 		 * on our EAGAINs.
246376a05b35SChris Mason 		 */
2464e6a1d6fdSLiu Bo 		if (!extent_buffer_uptodate(tmp))
246576a05b35SChris Mason 			ret = -EIO;
2466c8c42864SChris Mason 		free_extent_buffer(tmp);
2467c871b0f2SLiu Bo 	} else {
2468c871b0f2SLiu Bo 		ret = PTR_ERR(tmp);
246976a05b35SChris Mason 	}
247002a3307aSLiu Bo 
247102a3307aSLiu Bo 	btrfs_release_path(p);
247276a05b35SChris Mason 	return ret;
2473c8c42864SChris Mason }
2474c8c42864SChris Mason 
2475c8c42864SChris Mason /*
2476c8c42864SChris Mason  * helper function for btrfs_search_slot.  This does all of the checks
2477c8c42864SChris Mason  * for node-level blocks and does any balancing required based on
2478c8c42864SChris Mason  * the ins_len.
2479c8c42864SChris Mason  *
2480c8c42864SChris Mason  * If no extra work was required, zero is returned.  If we had to
2481c8c42864SChris Mason  * drop the path, -EAGAIN is returned and btrfs_search_slot must
2482c8c42864SChris Mason  * start over
2483c8c42864SChris Mason  */
2484c8c42864SChris Mason static int
2485c8c42864SChris Mason setup_nodes_for_search(struct btrfs_trans_handle *trans,
2486c8c42864SChris Mason 		       struct btrfs_root *root, struct btrfs_path *p,
2487bd681513SChris Mason 		       struct extent_buffer *b, int level, int ins_len,
2488bd681513SChris Mason 		       int *write_lock_level)
2489c8c42864SChris Mason {
24900b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
2491c8c42864SChris Mason 	int ret;
24920b246afaSJeff Mahoney 
2493c8c42864SChris Mason 	if ((p->search_for_split || ins_len > 0) && btrfs_header_nritems(b) >=
24940b246afaSJeff Mahoney 	    BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3) {
2495c8c42864SChris Mason 		int sret;
2496c8c42864SChris Mason 
2497bd681513SChris Mason 		if (*write_lock_level < level + 1) {
2498bd681513SChris Mason 			*write_lock_level = level + 1;
2499bd681513SChris Mason 			btrfs_release_path(p);
2500bd681513SChris Mason 			goto again;
2501bd681513SChris Mason 		}
2502bd681513SChris Mason 
2503c8c42864SChris Mason 		btrfs_set_path_blocking(p);
25042ff7e61eSJeff Mahoney 		reada_for_balance(fs_info, p, level);
2505c8c42864SChris Mason 		sret = split_node(trans, root, p, level);
2506c8c42864SChris Mason 
2507c8c42864SChris Mason 		BUG_ON(sret > 0);
2508c8c42864SChris Mason 		if (sret) {
2509c8c42864SChris Mason 			ret = sret;
2510c8c42864SChris Mason 			goto done;
2511c8c42864SChris Mason 		}
2512c8c42864SChris Mason 		b = p->nodes[level];
2513c8c42864SChris Mason 	} else if (ins_len < 0 && btrfs_header_nritems(b) <
25140b246afaSJeff Mahoney 		   BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 2) {
2515c8c42864SChris Mason 		int sret;
2516c8c42864SChris Mason 
2517bd681513SChris Mason 		if (*write_lock_level < level + 1) {
2518bd681513SChris Mason 			*write_lock_level = level + 1;
2519bd681513SChris Mason 			btrfs_release_path(p);
2520bd681513SChris Mason 			goto again;
2521bd681513SChris Mason 		}
2522bd681513SChris Mason 
2523c8c42864SChris Mason 		btrfs_set_path_blocking(p);
25242ff7e61eSJeff Mahoney 		reada_for_balance(fs_info, p, level);
2525c8c42864SChris Mason 		sret = balance_level(trans, root, p, level);
2526c8c42864SChris Mason 
2527c8c42864SChris Mason 		if (sret) {
2528c8c42864SChris Mason 			ret = sret;
2529c8c42864SChris Mason 			goto done;
2530c8c42864SChris Mason 		}
2531c8c42864SChris Mason 		b = p->nodes[level];
2532c8c42864SChris Mason 		if (!b) {
2533b3b4aa74SDavid Sterba 			btrfs_release_path(p);
2534c8c42864SChris Mason 			goto again;
2535c8c42864SChris Mason 		}
2536c8c42864SChris Mason 		BUG_ON(btrfs_header_nritems(b) == 1);
2537c8c42864SChris Mason 	}
2538c8c42864SChris Mason 	return 0;
2539c8c42864SChris Mason 
2540c8c42864SChris Mason again:
2541c8c42864SChris Mason 	ret = -EAGAIN;
2542c8c42864SChris Mason done:
2543c8c42864SChris Mason 	return ret;
2544c8c42864SChris Mason }
2545c8c42864SChris Mason 
2546310712b2SOmar Sandoval static int key_search(struct extent_buffer *b, const struct btrfs_key *key,
2547d7396f07SFilipe David Borba Manana 		      int level, int *prev_cmp, int *slot)
2548d7396f07SFilipe David Borba Manana {
2549d7396f07SFilipe David Borba Manana 	if (*prev_cmp != 0) {
2550a74b35ecSNikolay Borisov 		*prev_cmp = btrfs_bin_search(b, key, level, slot);
2551d7396f07SFilipe David Borba Manana 		return *prev_cmp;
2552d7396f07SFilipe David Borba Manana 	}
2553d7396f07SFilipe David Borba Manana 
2554d7396f07SFilipe David Borba Manana 	*slot = 0;
2555d7396f07SFilipe David Borba Manana 
2556d7396f07SFilipe David Borba Manana 	return 0;
2557d7396f07SFilipe David Borba Manana }
2558d7396f07SFilipe David Borba Manana 
2559381cf658SDavid Sterba int btrfs_find_item(struct btrfs_root *fs_root, struct btrfs_path *path,
2560e33d5c3dSKelley Nielsen 		u64 iobjectid, u64 ioff, u8 key_type,
2561e33d5c3dSKelley Nielsen 		struct btrfs_key *found_key)
2562e33d5c3dSKelley Nielsen {
2563e33d5c3dSKelley Nielsen 	int ret;
2564e33d5c3dSKelley Nielsen 	struct btrfs_key key;
2565e33d5c3dSKelley Nielsen 	struct extent_buffer *eb;
2566381cf658SDavid Sterba 
2567381cf658SDavid Sterba 	ASSERT(path);
25681d4c08e0SDavid Sterba 	ASSERT(found_key);
2569e33d5c3dSKelley Nielsen 
2570e33d5c3dSKelley Nielsen 	key.type = key_type;
2571e33d5c3dSKelley Nielsen 	key.objectid = iobjectid;
2572e33d5c3dSKelley Nielsen 	key.offset = ioff;
2573e33d5c3dSKelley Nielsen 
2574e33d5c3dSKelley Nielsen 	ret = btrfs_search_slot(NULL, fs_root, &key, path, 0, 0);
25751d4c08e0SDavid Sterba 	if (ret < 0)
2576e33d5c3dSKelley Nielsen 		return ret;
2577e33d5c3dSKelley Nielsen 
2578e33d5c3dSKelley Nielsen 	eb = path->nodes[0];
2579e33d5c3dSKelley Nielsen 	if (ret && path->slots[0] >= btrfs_header_nritems(eb)) {
2580e33d5c3dSKelley Nielsen 		ret = btrfs_next_leaf(fs_root, path);
2581e33d5c3dSKelley Nielsen 		if (ret)
2582e33d5c3dSKelley Nielsen 			return ret;
2583e33d5c3dSKelley Nielsen 		eb = path->nodes[0];
2584e33d5c3dSKelley Nielsen 	}
2585e33d5c3dSKelley Nielsen 
2586e33d5c3dSKelley Nielsen 	btrfs_item_key_to_cpu(eb, found_key, path->slots[0]);
2587e33d5c3dSKelley Nielsen 	if (found_key->type != key.type ||
2588e33d5c3dSKelley Nielsen 			found_key->objectid != key.objectid)
2589e33d5c3dSKelley Nielsen 		return 1;
2590e33d5c3dSKelley Nielsen 
2591e33d5c3dSKelley Nielsen 	return 0;
2592e33d5c3dSKelley Nielsen }
2593e33d5c3dSKelley Nielsen 
25941fc28d8eSLiu Bo static struct extent_buffer *btrfs_search_slot_get_root(struct btrfs_root *root,
25951fc28d8eSLiu Bo 							struct btrfs_path *p,
25961fc28d8eSLiu Bo 							int write_lock_level)
25971fc28d8eSLiu Bo {
25981fc28d8eSLiu Bo 	struct btrfs_fs_info *fs_info = root->fs_info;
25991fc28d8eSLiu Bo 	struct extent_buffer *b;
26001fc28d8eSLiu Bo 	int root_lock;
26011fc28d8eSLiu Bo 	int level = 0;
26021fc28d8eSLiu Bo 
26031fc28d8eSLiu Bo 	/* We try very hard to do read locks on the root */
26041fc28d8eSLiu Bo 	root_lock = BTRFS_READ_LOCK;
26051fc28d8eSLiu Bo 
26061fc28d8eSLiu Bo 	if (p->search_commit_root) {
2607be6821f8SFilipe Manana 		/*
2608be6821f8SFilipe Manana 		 * The commit roots are read only so we always do read locks,
2609be6821f8SFilipe Manana 		 * and we always must hold the commit_root_sem when doing
2610be6821f8SFilipe Manana 		 * searches on them, the only exception is send where we don't
2611be6821f8SFilipe Manana 		 * want to block transaction commits for a long time, so
2612be6821f8SFilipe Manana 		 * we need to clone the commit root in order to avoid races
2613be6821f8SFilipe Manana 		 * with transaction commits that create a snapshot of one of
2614be6821f8SFilipe Manana 		 * the roots used by a send operation.
2615be6821f8SFilipe Manana 		 */
2616be6821f8SFilipe Manana 		if (p->need_commit_sem) {
26171fc28d8eSLiu Bo 			down_read(&fs_info->commit_root_sem);
2618be6821f8SFilipe Manana 			b = btrfs_clone_extent_buffer(root->commit_root);
2619be6821f8SFilipe Manana 			up_read(&fs_info->commit_root_sem);
2620be6821f8SFilipe Manana 			if (!b)
2621be6821f8SFilipe Manana 				return ERR_PTR(-ENOMEM);
2622be6821f8SFilipe Manana 
2623be6821f8SFilipe Manana 		} else {
26241fc28d8eSLiu Bo 			b = root->commit_root;
262567439dadSDavid Sterba 			atomic_inc(&b->refs);
2626be6821f8SFilipe Manana 		}
26271fc28d8eSLiu Bo 		level = btrfs_header_level(b);
2628f9ddfd05SLiu Bo 		/*
2629f9ddfd05SLiu Bo 		 * Ensure that all callers have set skip_locking when
2630f9ddfd05SLiu Bo 		 * p->search_commit_root = 1.
2631f9ddfd05SLiu Bo 		 */
2632f9ddfd05SLiu Bo 		ASSERT(p->skip_locking == 1);
26331fc28d8eSLiu Bo 
26341fc28d8eSLiu Bo 		goto out;
26351fc28d8eSLiu Bo 	}
26361fc28d8eSLiu Bo 
26371fc28d8eSLiu Bo 	if (p->skip_locking) {
26381fc28d8eSLiu Bo 		b = btrfs_root_node(root);
26391fc28d8eSLiu Bo 		level = btrfs_header_level(b);
26401fc28d8eSLiu Bo 		goto out;
26411fc28d8eSLiu Bo 	}
26421fc28d8eSLiu Bo 
26431fc28d8eSLiu Bo 	/*
2644662c653bSLiu Bo 	 * If the level is set to maximum, we can skip trying to get the read
2645662c653bSLiu Bo 	 * lock.
2646662c653bSLiu Bo 	 */
2647662c653bSLiu Bo 	if (write_lock_level < BTRFS_MAX_LEVEL) {
2648662c653bSLiu Bo 		/*
2649662c653bSLiu Bo 		 * We don't know the level of the root node until we actually
2650662c653bSLiu Bo 		 * have it read locked
26511fc28d8eSLiu Bo 		 */
26521fc28d8eSLiu Bo 		b = btrfs_read_lock_root_node(root);
26531fc28d8eSLiu Bo 		level = btrfs_header_level(b);
26541fc28d8eSLiu Bo 		if (level > write_lock_level)
26551fc28d8eSLiu Bo 			goto out;
26561fc28d8eSLiu Bo 
2657662c653bSLiu Bo 		/* Whoops, must trade for write lock */
26581fc28d8eSLiu Bo 		btrfs_tree_read_unlock(b);
26591fc28d8eSLiu Bo 		free_extent_buffer(b);
2660662c653bSLiu Bo 	}
2661662c653bSLiu Bo 
26621fc28d8eSLiu Bo 	b = btrfs_lock_root_node(root);
26631fc28d8eSLiu Bo 	root_lock = BTRFS_WRITE_LOCK;
26641fc28d8eSLiu Bo 
26651fc28d8eSLiu Bo 	/* The level might have changed, check again */
26661fc28d8eSLiu Bo 	level = btrfs_header_level(b);
26671fc28d8eSLiu Bo 
26681fc28d8eSLiu Bo out:
26691fc28d8eSLiu Bo 	p->nodes[level] = b;
26701fc28d8eSLiu Bo 	if (!p->skip_locking)
26711fc28d8eSLiu Bo 		p->locks[level] = root_lock;
26721fc28d8eSLiu Bo 	/*
26731fc28d8eSLiu Bo 	 * Callers are responsible for dropping b's references.
26741fc28d8eSLiu Bo 	 */
26751fc28d8eSLiu Bo 	return b;
26761fc28d8eSLiu Bo }
26771fc28d8eSLiu Bo 
26781fc28d8eSLiu Bo 
2679c8c42864SChris Mason /*
26804271eceaSNikolay Borisov  * btrfs_search_slot - look for a key in a tree and perform necessary
26814271eceaSNikolay Borisov  * modifications to preserve tree invariants.
268274123bd7SChris Mason  *
26834271eceaSNikolay Borisov  * @trans:	Handle of transaction, used when modifying the tree
26844271eceaSNikolay Borisov  * @p:		Holds all btree nodes along the search path
26854271eceaSNikolay Borisov  * @root:	The root node of the tree
26864271eceaSNikolay Borisov  * @key:	The key we are looking for
26874271eceaSNikolay Borisov  * @ins_len:	Indicates purpose of search, for inserts it is 1, for
26884271eceaSNikolay Borisov  *		deletions it's -1. 0 for plain searches
26894271eceaSNikolay Borisov  * @cow:	boolean should CoW operations be performed. Must always be 1
26904271eceaSNikolay Borisov  *		when modifying the tree.
269197571fd0SChris Mason  *
26924271eceaSNikolay Borisov  * If @ins_len > 0, nodes and leaves will be split as we walk down the tree.
26934271eceaSNikolay Borisov  * If @ins_len < 0, nodes will be merged as we walk down the tree (if possible)
26944271eceaSNikolay Borisov  *
26954271eceaSNikolay Borisov  * If @key is found, 0 is returned and you can find the item in the leaf level
26964271eceaSNikolay Borisov  * of the path (level 0)
26974271eceaSNikolay Borisov  *
26984271eceaSNikolay Borisov  * If @key isn't found, 1 is returned and the leaf level of the path (level 0)
26994271eceaSNikolay Borisov  * points to the slot where it should be inserted
27004271eceaSNikolay Borisov  *
27014271eceaSNikolay Borisov  * If an error is encountered while searching the tree a negative error number
27024271eceaSNikolay Borisov  * is returned
270374123bd7SChris Mason  */
2704310712b2SOmar Sandoval int btrfs_search_slot(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2705310712b2SOmar Sandoval 		      const struct btrfs_key *key, struct btrfs_path *p,
2706310712b2SOmar Sandoval 		      int ins_len, int cow)
2707be0e5c09SChris Mason {
27085f39d397SChris Mason 	struct extent_buffer *b;
2709be0e5c09SChris Mason 	int slot;
2710be0e5c09SChris Mason 	int ret;
271133c66f43SYan Zheng 	int err;
2712be0e5c09SChris Mason 	int level;
2713925baeddSChris Mason 	int lowest_unlock = 1;
2714bd681513SChris Mason 	/* everything at write_lock_level or lower must be write locked */
2715bd681513SChris Mason 	int write_lock_level = 0;
27169f3a7427SChris Mason 	u8 lowest_level = 0;
2717f7c79f30SChris Mason 	int min_write_lock_level;
2718d7396f07SFilipe David Borba Manana 	int prev_cmp;
27199f3a7427SChris Mason 
27206702ed49SChris Mason 	lowest_level = p->lowest_level;
2721323ac95bSChris Mason 	WARN_ON(lowest_level && ins_len > 0);
272222b0ebdaSChris Mason 	WARN_ON(p->nodes[0] != NULL);
2723eb653de1SFilipe David Borba Manana 	BUG_ON(!cow && ins_len);
272425179201SJosef Bacik 
2725bd681513SChris Mason 	if (ins_len < 0) {
2726925baeddSChris Mason 		lowest_unlock = 2;
272765b51a00SChris Mason 
2728bd681513SChris Mason 		/* when we are removing items, we might have to go up to level
2729bd681513SChris Mason 		 * two as we update tree pointers  Make sure we keep write
2730bd681513SChris Mason 		 * for those levels as well
2731bd681513SChris Mason 		 */
2732bd681513SChris Mason 		write_lock_level = 2;
2733bd681513SChris Mason 	} else if (ins_len > 0) {
2734bd681513SChris Mason 		/*
2735bd681513SChris Mason 		 * for inserting items, make sure we have a write lock on
2736bd681513SChris Mason 		 * level 1 so we can update keys
2737bd681513SChris Mason 		 */
2738bd681513SChris Mason 		write_lock_level = 1;
2739bd681513SChris Mason 	}
2740bd681513SChris Mason 
2741bd681513SChris Mason 	if (!cow)
2742bd681513SChris Mason 		write_lock_level = -1;
2743bd681513SChris Mason 
274409a2a8f9SJosef Bacik 	if (cow && (p->keep_locks || p->lowest_level))
2745bd681513SChris Mason 		write_lock_level = BTRFS_MAX_LEVEL;
2746bd681513SChris Mason 
2747f7c79f30SChris Mason 	min_write_lock_level = write_lock_level;
2748f7c79f30SChris Mason 
2749bb803951SChris Mason again:
2750d7396f07SFilipe David Borba Manana 	prev_cmp = -1;
27511fc28d8eSLiu Bo 	b = btrfs_search_slot_get_root(root, p, write_lock_level);
2752be6821f8SFilipe Manana 	if (IS_ERR(b)) {
2753be6821f8SFilipe Manana 		ret = PTR_ERR(b);
2754be6821f8SFilipe Manana 		goto done;
2755be6821f8SFilipe Manana 	}
2756925baeddSChris Mason 
2757eb60ceacSChris Mason 	while (b) {
2758f624d976SQu Wenruo 		int dec = 0;
2759f624d976SQu Wenruo 
27605f39d397SChris Mason 		level = btrfs_header_level(b);
276165b51a00SChris Mason 
276202217ed2SChris Mason 		if (cow) {
27639ea2c7c9SNikolay Borisov 			bool last_level = (level == (BTRFS_MAX_LEVEL - 1));
27649ea2c7c9SNikolay Borisov 
2765c8c42864SChris Mason 			/*
2766c8c42864SChris Mason 			 * if we don't really need to cow this block
2767c8c42864SChris Mason 			 * then we don't want to set the path blocking,
2768c8c42864SChris Mason 			 * so we test it here
2769c8c42864SChris Mason 			 */
277064c12921SJeff Mahoney 			if (!should_cow_block(trans, root, b)) {
277164c12921SJeff Mahoney 				trans->dirty = true;
277265b51a00SChris Mason 				goto cow_done;
277364c12921SJeff Mahoney 			}
27745d4f98a2SYan Zheng 
2775bd681513SChris Mason 			/*
2776bd681513SChris Mason 			 * must have write locks on this node and the
2777bd681513SChris Mason 			 * parent
2778bd681513SChris Mason 			 */
27795124e00eSJosef Bacik 			if (level > write_lock_level ||
27805124e00eSJosef Bacik 			    (level + 1 > write_lock_level &&
27815124e00eSJosef Bacik 			    level + 1 < BTRFS_MAX_LEVEL &&
27825124e00eSJosef Bacik 			    p->nodes[level + 1])) {
2783bd681513SChris Mason 				write_lock_level = level + 1;
2784bd681513SChris Mason 				btrfs_release_path(p);
2785bd681513SChris Mason 				goto again;
2786bd681513SChris Mason 			}
2787bd681513SChris Mason 
2788160f4089SFilipe Manana 			btrfs_set_path_blocking(p);
27899ea2c7c9SNikolay Borisov 			if (last_level)
27909ea2c7c9SNikolay Borisov 				err = btrfs_cow_block(trans, root, b, NULL, 0,
27919ea2c7c9SNikolay Borisov 						      &b);
27929ea2c7c9SNikolay Borisov 			else
279333c66f43SYan Zheng 				err = btrfs_cow_block(trans, root, b,
2794e20d96d6SChris Mason 						      p->nodes[level + 1],
27959fa8cfe7SChris Mason 						      p->slots[level + 1], &b);
279633c66f43SYan Zheng 			if (err) {
279733c66f43SYan Zheng 				ret = err;
279865b51a00SChris Mason 				goto done;
279954aa1f4dSChris Mason 			}
280002217ed2SChris Mason 		}
280165b51a00SChris Mason cow_done:
2802eb60ceacSChris Mason 		p->nodes[level] = b;
280352398340SLiu Bo 		/*
280452398340SLiu Bo 		 * Leave path with blocking locks to avoid massive
280552398340SLiu Bo 		 * lock context switch, this is made on purpose.
280652398340SLiu Bo 		 */
2807b4ce94deSChris Mason 
2808b4ce94deSChris Mason 		/*
2809b4ce94deSChris Mason 		 * we have a lock on b and as long as we aren't changing
2810b4ce94deSChris Mason 		 * the tree, there is no way to for the items in b to change.
2811b4ce94deSChris Mason 		 * It is safe to drop the lock on our parent before we
2812b4ce94deSChris Mason 		 * go through the expensive btree search on b.
2813b4ce94deSChris Mason 		 *
2814eb653de1SFilipe David Borba Manana 		 * If we're inserting or deleting (ins_len != 0), then we might
2815eb653de1SFilipe David Borba Manana 		 * be changing slot zero, which may require changing the parent.
2816eb653de1SFilipe David Borba Manana 		 * So, we can't drop the lock until after we know which slot
2817eb653de1SFilipe David Borba Manana 		 * we're operating on.
2818b4ce94deSChris Mason 		 */
2819eb653de1SFilipe David Borba Manana 		if (!ins_len && !p->keep_locks) {
2820eb653de1SFilipe David Borba Manana 			int u = level + 1;
2821eb653de1SFilipe David Borba Manana 
2822eb653de1SFilipe David Borba Manana 			if (u < BTRFS_MAX_LEVEL && p->locks[u]) {
2823eb653de1SFilipe David Borba Manana 				btrfs_tree_unlock_rw(p->nodes[u], p->locks[u]);
2824eb653de1SFilipe David Borba Manana 				p->locks[u] = 0;
2825eb653de1SFilipe David Borba Manana 			}
2826eb653de1SFilipe David Borba Manana 		}
2827b4ce94deSChris Mason 
2828d7396f07SFilipe David Borba Manana 		ret = key_search(b, key, level, &prev_cmp, &slot);
2829415b35a5SLiu Bo 		if (ret < 0)
2830415b35a5SLiu Bo 			goto done;
2831b4ce94deSChris Mason 
2832f624d976SQu Wenruo 		if (level == 0) {
2833be0e5c09SChris Mason 			p->slots[level] = slot;
283487b29b20SYan Zheng 			if (ins_len > 0 &&
2835e902baacSDavid Sterba 			    btrfs_leaf_free_space(b) < ins_len) {
2836bd681513SChris Mason 				if (write_lock_level < 1) {
2837bd681513SChris Mason 					write_lock_level = 1;
2838bd681513SChris Mason 					btrfs_release_path(p);
2839bd681513SChris Mason 					goto again;
2840bd681513SChris Mason 				}
2841bd681513SChris Mason 
2842b4ce94deSChris Mason 				btrfs_set_path_blocking(p);
284333c66f43SYan Zheng 				err = split_leaf(trans, root, key,
2844cc0c5538SChris Mason 						 p, ins_len, ret == 0);
2845b4ce94deSChris Mason 
284633c66f43SYan Zheng 				BUG_ON(err > 0);
284733c66f43SYan Zheng 				if (err) {
284833c66f43SYan Zheng 					ret = err;
284965b51a00SChris Mason 					goto done;
285065b51a00SChris Mason 				}
28515c680ed6SChris Mason 			}
2852459931ecSChris Mason 			if (!p->search_for_split)
2853f7c79f30SChris Mason 				unlock_up(p, level, lowest_unlock,
28544b6f8e96SLiu Bo 					  min_write_lock_level, NULL);
285565b51a00SChris Mason 			goto done;
285665b51a00SChris Mason 		}
2857f624d976SQu Wenruo 		if (ret && slot > 0) {
2858f624d976SQu Wenruo 			dec = 1;
2859f624d976SQu Wenruo 			slot--;
2860f624d976SQu Wenruo 		}
2861f624d976SQu Wenruo 		p->slots[level] = slot;
2862f624d976SQu Wenruo 		err = setup_nodes_for_search(trans, root, p, b, level, ins_len,
2863f624d976SQu Wenruo 					     &write_lock_level);
2864f624d976SQu Wenruo 		if (err == -EAGAIN)
2865f624d976SQu Wenruo 			goto again;
2866f624d976SQu Wenruo 		if (err) {
2867f624d976SQu Wenruo 			ret = err;
2868f624d976SQu Wenruo 			goto done;
2869f624d976SQu Wenruo 		}
2870f624d976SQu Wenruo 		b = p->nodes[level];
2871f624d976SQu Wenruo 		slot = p->slots[level];
2872f624d976SQu Wenruo 
2873f624d976SQu Wenruo 		/*
2874f624d976SQu Wenruo 		 * Slot 0 is special, if we change the key we have to update
2875f624d976SQu Wenruo 		 * the parent pointer which means we must have a write lock on
2876f624d976SQu Wenruo 		 * the parent
2877f624d976SQu Wenruo 		 */
2878f624d976SQu Wenruo 		if (slot == 0 && ins_len && write_lock_level < level + 1) {
2879f624d976SQu Wenruo 			write_lock_level = level + 1;
2880f624d976SQu Wenruo 			btrfs_release_path(p);
2881f624d976SQu Wenruo 			goto again;
2882f624d976SQu Wenruo 		}
2883f624d976SQu Wenruo 
2884f624d976SQu Wenruo 		unlock_up(p, level, lowest_unlock, min_write_lock_level,
2885f624d976SQu Wenruo 			  &write_lock_level);
2886f624d976SQu Wenruo 
2887f624d976SQu Wenruo 		if (level == lowest_level) {
2888f624d976SQu Wenruo 			if (dec)
2889f624d976SQu Wenruo 				p->slots[level]++;
2890f624d976SQu Wenruo 			goto done;
2891f624d976SQu Wenruo 		}
2892f624d976SQu Wenruo 
2893f624d976SQu Wenruo 		err = read_block_for_search(root, p, &b, level, slot, key);
2894f624d976SQu Wenruo 		if (err == -EAGAIN)
2895f624d976SQu Wenruo 			goto again;
2896f624d976SQu Wenruo 		if (err) {
2897f624d976SQu Wenruo 			ret = err;
2898f624d976SQu Wenruo 			goto done;
2899f624d976SQu Wenruo 		}
2900f624d976SQu Wenruo 
2901f624d976SQu Wenruo 		if (!p->skip_locking) {
2902f624d976SQu Wenruo 			level = btrfs_header_level(b);
2903f624d976SQu Wenruo 			if (level <= write_lock_level) {
2904f624d976SQu Wenruo 				if (!btrfs_try_tree_write_lock(b)) {
2905f624d976SQu Wenruo 					btrfs_set_path_blocking(p);
2906f624d976SQu Wenruo 					btrfs_tree_lock(b);
2907f624d976SQu Wenruo 				}
2908f624d976SQu Wenruo 				p->locks[level] = BTRFS_WRITE_LOCK;
2909f624d976SQu Wenruo 			} else {
2910f624d976SQu Wenruo 				if (!btrfs_tree_read_lock_atomic(b)) {
2911f624d976SQu Wenruo 					btrfs_set_path_blocking(p);
2912f624d976SQu Wenruo 					btrfs_tree_read_lock(b);
2913f624d976SQu Wenruo 				}
2914f624d976SQu Wenruo 				p->locks[level] = BTRFS_READ_LOCK;
2915f624d976SQu Wenruo 			}
2916f624d976SQu Wenruo 			p->nodes[level] = b;
2917f624d976SQu Wenruo 		}
291865b51a00SChris Mason 	}
291965b51a00SChris Mason 	ret = 1;
292065b51a00SChris Mason done:
2921b4ce94deSChris Mason 	/*
2922b4ce94deSChris Mason 	 * we don't really know what they plan on doing with the path
2923b4ce94deSChris Mason 	 * from here on, so for now just mark it as blocking
2924b4ce94deSChris Mason 	 */
2925b9473439SChris Mason 	if (!p->leave_spinning)
2926b4ce94deSChris Mason 		btrfs_set_path_blocking(p);
29275f5bc6b1SFilipe Manana 	if (ret < 0 && !p->skip_release_on_error)
2928b3b4aa74SDavid Sterba 		btrfs_release_path(p);
2929be0e5c09SChris Mason 	return ret;
2930be0e5c09SChris Mason }
2931be0e5c09SChris Mason 
293274123bd7SChris Mason /*
29335d9e75c4SJan Schmidt  * Like btrfs_search_slot, this looks for a key in the given tree. It uses the
29345d9e75c4SJan Schmidt  * current state of the tree together with the operations recorded in the tree
29355d9e75c4SJan Schmidt  * modification log to search for the key in a previous version of this tree, as
29365d9e75c4SJan Schmidt  * denoted by the time_seq parameter.
29375d9e75c4SJan Schmidt  *
29385d9e75c4SJan Schmidt  * Naturally, there is no support for insert, delete or cow operations.
29395d9e75c4SJan Schmidt  *
29405d9e75c4SJan Schmidt  * The resulting path and return value will be set up as if we called
29415d9e75c4SJan Schmidt  * btrfs_search_slot at that point in time with ins_len and cow both set to 0.
29425d9e75c4SJan Schmidt  */
2943310712b2SOmar Sandoval int btrfs_search_old_slot(struct btrfs_root *root, const struct btrfs_key *key,
29445d9e75c4SJan Schmidt 			  struct btrfs_path *p, u64 time_seq)
29455d9e75c4SJan Schmidt {
29460b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
29475d9e75c4SJan Schmidt 	struct extent_buffer *b;
29485d9e75c4SJan Schmidt 	int slot;
29495d9e75c4SJan Schmidt 	int ret;
29505d9e75c4SJan Schmidt 	int err;
29515d9e75c4SJan Schmidt 	int level;
29525d9e75c4SJan Schmidt 	int lowest_unlock = 1;
29535d9e75c4SJan Schmidt 	u8 lowest_level = 0;
2954d4b4087cSJosef Bacik 	int prev_cmp = -1;
29555d9e75c4SJan Schmidt 
29565d9e75c4SJan Schmidt 	lowest_level = p->lowest_level;
29575d9e75c4SJan Schmidt 	WARN_ON(p->nodes[0] != NULL);
29585d9e75c4SJan Schmidt 
29595d9e75c4SJan Schmidt 	if (p->search_commit_root) {
29605d9e75c4SJan Schmidt 		BUG_ON(time_seq);
29615d9e75c4SJan Schmidt 		return btrfs_search_slot(NULL, root, key, p, 0, 0);
29625d9e75c4SJan Schmidt 	}
29635d9e75c4SJan Schmidt 
29645d9e75c4SJan Schmidt again:
29655d9e75c4SJan Schmidt 	b = get_old_root(root, time_seq);
2966315bed43SNikolay Borisov 	if (!b) {
2967315bed43SNikolay Borisov 		ret = -EIO;
2968315bed43SNikolay Borisov 		goto done;
2969315bed43SNikolay Borisov 	}
29705d9e75c4SJan Schmidt 	level = btrfs_header_level(b);
29715d9e75c4SJan Schmidt 	p->locks[level] = BTRFS_READ_LOCK;
29725d9e75c4SJan Schmidt 
29735d9e75c4SJan Schmidt 	while (b) {
2974abe9339dSQu Wenruo 		int dec = 0;
2975abe9339dSQu Wenruo 
29765d9e75c4SJan Schmidt 		level = btrfs_header_level(b);
29775d9e75c4SJan Schmidt 		p->nodes[level] = b;
29785d9e75c4SJan Schmidt 
29795d9e75c4SJan Schmidt 		/*
29805d9e75c4SJan Schmidt 		 * we have a lock on b and as long as we aren't changing
29815d9e75c4SJan Schmidt 		 * the tree, there is no way to for the items in b to change.
29825d9e75c4SJan Schmidt 		 * It is safe to drop the lock on our parent before we
29835d9e75c4SJan Schmidt 		 * go through the expensive btree search on b.
29845d9e75c4SJan Schmidt 		 */
29855d9e75c4SJan Schmidt 		btrfs_unlock_up_safe(p, level + 1);
29865d9e75c4SJan Schmidt 
2987d4b4087cSJosef Bacik 		/*
298801327610SNicholas D Steeves 		 * Since we can unwind ebs we want to do a real search every
2989d4b4087cSJosef Bacik 		 * time.
2990d4b4087cSJosef Bacik 		 */
2991d4b4087cSJosef Bacik 		prev_cmp = -1;
2992d7396f07SFilipe David Borba Manana 		ret = key_search(b, key, level, &prev_cmp, &slot);
2993cbca7d59SFilipe Manana 		if (ret < 0)
2994cbca7d59SFilipe Manana 			goto done;
29955d9e75c4SJan Schmidt 
2996abe9339dSQu Wenruo 		if (level == 0) {
2997abe9339dSQu Wenruo 			p->slots[level] = slot;
2998abe9339dSQu Wenruo 			unlock_up(p, level, lowest_unlock, 0, NULL);
2999abe9339dSQu Wenruo 			goto done;
3000abe9339dSQu Wenruo 		}
3001abe9339dSQu Wenruo 
30025d9e75c4SJan Schmidt 		if (ret && slot > 0) {
30035d9e75c4SJan Schmidt 			dec = 1;
3004abe9339dSQu Wenruo 			slot--;
30055d9e75c4SJan Schmidt 		}
30065d9e75c4SJan Schmidt 		p->slots[level] = slot;
30075d9e75c4SJan Schmidt 		unlock_up(p, level, lowest_unlock, 0, NULL);
30085d9e75c4SJan Schmidt 
30095d9e75c4SJan Schmidt 		if (level == lowest_level) {
30105d9e75c4SJan Schmidt 			if (dec)
30115d9e75c4SJan Schmidt 				p->slots[level]++;
30125d9e75c4SJan Schmidt 			goto done;
30135d9e75c4SJan Schmidt 		}
30145d9e75c4SJan Schmidt 
3015abe9339dSQu Wenruo 		err = read_block_for_search(root, p, &b, level, slot, key);
30165d9e75c4SJan Schmidt 		if (err == -EAGAIN)
30175d9e75c4SJan Schmidt 			goto again;
30185d9e75c4SJan Schmidt 		if (err) {
30195d9e75c4SJan Schmidt 			ret = err;
30205d9e75c4SJan Schmidt 			goto done;
30215d9e75c4SJan Schmidt 		}
30225d9e75c4SJan Schmidt 
30235d9e75c4SJan Schmidt 		level = btrfs_header_level(b);
302465e99c43SNikolay Borisov 		if (!btrfs_tree_read_lock_atomic(b)) {
30255d9e75c4SJan Schmidt 			btrfs_set_path_blocking(p);
30265d9e75c4SJan Schmidt 			btrfs_tree_read_lock(b);
30275d9e75c4SJan Schmidt 		}
30280b246afaSJeff Mahoney 		b = tree_mod_log_rewind(fs_info, p, b, time_seq);
3029db7f3436SJosef Bacik 		if (!b) {
3030db7f3436SJosef Bacik 			ret = -ENOMEM;
3031db7f3436SJosef Bacik 			goto done;
3032db7f3436SJosef Bacik 		}
30335d9e75c4SJan Schmidt 		p->locks[level] = BTRFS_READ_LOCK;
30345d9e75c4SJan Schmidt 		p->nodes[level] = b;
30355d9e75c4SJan Schmidt 	}
30365d9e75c4SJan Schmidt 	ret = 1;
30375d9e75c4SJan Schmidt done:
30385d9e75c4SJan Schmidt 	if (!p->leave_spinning)
30395d9e75c4SJan Schmidt 		btrfs_set_path_blocking(p);
30405d9e75c4SJan Schmidt 	if (ret < 0)
30415d9e75c4SJan Schmidt 		btrfs_release_path(p);
30425d9e75c4SJan Schmidt 
30435d9e75c4SJan Schmidt 	return ret;
30445d9e75c4SJan Schmidt }
30455d9e75c4SJan Schmidt 
30465d9e75c4SJan Schmidt /*
30472f38b3e1SArne Jansen  * helper to use instead of search slot if no exact match is needed but
30482f38b3e1SArne Jansen  * instead the next or previous item should be returned.
30492f38b3e1SArne Jansen  * When find_higher is true, the next higher item is returned, the next lower
30502f38b3e1SArne Jansen  * otherwise.
30512f38b3e1SArne Jansen  * When return_any and find_higher are both true, and no higher item is found,
30522f38b3e1SArne Jansen  * return the next lower instead.
30532f38b3e1SArne Jansen  * When return_any is true and find_higher is false, and no lower item is found,
30542f38b3e1SArne Jansen  * return the next higher instead.
30552f38b3e1SArne Jansen  * It returns 0 if any item is found, 1 if none is found (tree empty), and
30562f38b3e1SArne Jansen  * < 0 on error
30572f38b3e1SArne Jansen  */
30582f38b3e1SArne Jansen int btrfs_search_slot_for_read(struct btrfs_root *root,
3059310712b2SOmar Sandoval 			       const struct btrfs_key *key,
3060310712b2SOmar Sandoval 			       struct btrfs_path *p, int find_higher,
3061310712b2SOmar Sandoval 			       int return_any)
30622f38b3e1SArne Jansen {
30632f38b3e1SArne Jansen 	int ret;
30642f38b3e1SArne Jansen 	struct extent_buffer *leaf;
30652f38b3e1SArne Jansen 
30662f38b3e1SArne Jansen again:
30672f38b3e1SArne Jansen 	ret = btrfs_search_slot(NULL, root, key, p, 0, 0);
30682f38b3e1SArne Jansen 	if (ret <= 0)
30692f38b3e1SArne Jansen 		return ret;
30702f38b3e1SArne Jansen 	/*
30712f38b3e1SArne Jansen 	 * a return value of 1 means the path is at the position where the
30722f38b3e1SArne Jansen 	 * item should be inserted. Normally this is the next bigger item,
30732f38b3e1SArne Jansen 	 * but in case the previous item is the last in a leaf, path points
30742f38b3e1SArne Jansen 	 * to the first free slot in the previous leaf, i.e. at an invalid
30752f38b3e1SArne Jansen 	 * item.
30762f38b3e1SArne Jansen 	 */
30772f38b3e1SArne Jansen 	leaf = p->nodes[0];
30782f38b3e1SArne Jansen 
30792f38b3e1SArne Jansen 	if (find_higher) {
30802f38b3e1SArne Jansen 		if (p->slots[0] >= btrfs_header_nritems(leaf)) {
30812f38b3e1SArne Jansen 			ret = btrfs_next_leaf(root, p);
30822f38b3e1SArne Jansen 			if (ret <= 0)
30832f38b3e1SArne Jansen 				return ret;
30842f38b3e1SArne Jansen 			if (!return_any)
30852f38b3e1SArne Jansen 				return 1;
30862f38b3e1SArne Jansen 			/*
30872f38b3e1SArne Jansen 			 * no higher item found, return the next
30882f38b3e1SArne Jansen 			 * lower instead
30892f38b3e1SArne Jansen 			 */
30902f38b3e1SArne Jansen 			return_any = 0;
30912f38b3e1SArne Jansen 			find_higher = 0;
30922f38b3e1SArne Jansen 			btrfs_release_path(p);
30932f38b3e1SArne Jansen 			goto again;
30942f38b3e1SArne Jansen 		}
30952f38b3e1SArne Jansen 	} else {
30962f38b3e1SArne Jansen 		if (p->slots[0] == 0) {
30972f38b3e1SArne Jansen 			ret = btrfs_prev_leaf(root, p);
3098e6793769SArne Jansen 			if (ret < 0)
30992f38b3e1SArne Jansen 				return ret;
3100e6793769SArne Jansen 			if (!ret) {
310123c6bf6aSFilipe David Borba Manana 				leaf = p->nodes[0];
310223c6bf6aSFilipe David Borba Manana 				if (p->slots[0] == btrfs_header_nritems(leaf))
310323c6bf6aSFilipe David Borba Manana 					p->slots[0]--;
3104e6793769SArne Jansen 				return 0;
3105e6793769SArne Jansen 			}
31062f38b3e1SArne Jansen 			if (!return_any)
31072f38b3e1SArne Jansen 				return 1;
31082f38b3e1SArne Jansen 			/*
31092f38b3e1SArne Jansen 			 * no lower item found, return the next
31102f38b3e1SArne Jansen 			 * higher instead
31112f38b3e1SArne Jansen 			 */
31122f38b3e1SArne Jansen 			return_any = 0;
31132f38b3e1SArne Jansen 			find_higher = 1;
31142f38b3e1SArne Jansen 			btrfs_release_path(p);
31152f38b3e1SArne Jansen 			goto again;
3116e6793769SArne Jansen 		} else {
31172f38b3e1SArne Jansen 			--p->slots[0];
31182f38b3e1SArne Jansen 		}
31192f38b3e1SArne Jansen 	}
31202f38b3e1SArne Jansen 	return 0;
31212f38b3e1SArne Jansen }
31222f38b3e1SArne Jansen 
31232f38b3e1SArne Jansen /*
312474123bd7SChris Mason  * adjust the pointers going up the tree, starting at level
312574123bd7SChris Mason  * making sure the right key of each node is points to 'key'.
312674123bd7SChris Mason  * This is used after shifting pointers to the left, so it stops
312774123bd7SChris Mason  * fixing up pointers when a given leaf/node is not in slot 0 of the
312874123bd7SChris Mason  * higher levels
3129aa5d6bedSChris Mason  *
313074123bd7SChris Mason  */
3131b167fa91SNikolay Borisov static void fixup_low_keys(struct btrfs_path *path,
31325f39d397SChris Mason 			   struct btrfs_disk_key *key, int level)
3133be0e5c09SChris Mason {
3134be0e5c09SChris Mason 	int i;
31355f39d397SChris Mason 	struct extent_buffer *t;
31360e82bcfeSDavid Sterba 	int ret;
31375f39d397SChris Mason 
3138234b63a0SChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
3139be0e5c09SChris Mason 		int tslot = path->slots[i];
31400e82bcfeSDavid Sterba 
3141eb60ceacSChris Mason 		if (!path->nodes[i])
3142be0e5c09SChris Mason 			break;
31435f39d397SChris Mason 		t = path->nodes[i];
31440e82bcfeSDavid Sterba 		ret = tree_mod_log_insert_key(t, tslot, MOD_LOG_KEY_REPLACE,
31450e82bcfeSDavid Sterba 				GFP_ATOMIC);
31460e82bcfeSDavid Sterba 		BUG_ON(ret < 0);
31475f39d397SChris Mason 		btrfs_set_node_key(t, key, tslot);
3148d6025579SChris Mason 		btrfs_mark_buffer_dirty(path->nodes[i]);
3149be0e5c09SChris Mason 		if (tslot != 0)
3150be0e5c09SChris Mason 			break;
3151be0e5c09SChris Mason 	}
3152be0e5c09SChris Mason }
3153be0e5c09SChris Mason 
315474123bd7SChris Mason /*
315531840ae1SZheng Yan  * update item key.
315631840ae1SZheng Yan  *
315731840ae1SZheng Yan  * This function isn't completely safe. It's the caller's responsibility
315831840ae1SZheng Yan  * that the new key won't break the order
315931840ae1SZheng Yan  */
3160b7a0365eSDaniel Dressler void btrfs_set_item_key_safe(struct btrfs_fs_info *fs_info,
3161b7a0365eSDaniel Dressler 			     struct btrfs_path *path,
3162310712b2SOmar Sandoval 			     const struct btrfs_key *new_key)
316331840ae1SZheng Yan {
316431840ae1SZheng Yan 	struct btrfs_disk_key disk_key;
316531840ae1SZheng Yan 	struct extent_buffer *eb;
316631840ae1SZheng Yan 	int slot;
316731840ae1SZheng Yan 
316831840ae1SZheng Yan 	eb = path->nodes[0];
316931840ae1SZheng Yan 	slot = path->slots[0];
317031840ae1SZheng Yan 	if (slot > 0) {
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 	if (slot < btrfs_header_nritems(eb) - 1) {
318531840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot + 1);
31867c15d410SQu Wenruo 		if (unlikely(comp_keys(&disk_key, new_key) <= 0)) {
31877c15d410SQu Wenruo 			btrfs_crit(fs_info,
31887c15d410SQu Wenruo 		"slot %u key (%llu %u %llu) new key (%llu %u %llu)",
31897c15d410SQu Wenruo 				   slot, btrfs_disk_key_objectid(&disk_key),
31907c15d410SQu Wenruo 				   btrfs_disk_key_type(&disk_key),
31917c15d410SQu Wenruo 				   btrfs_disk_key_offset(&disk_key),
31927c15d410SQu Wenruo 				   new_key->objectid, new_key->type,
31937c15d410SQu Wenruo 				   new_key->offset);
31947c15d410SQu Wenruo 			btrfs_print_leaf(eb);
31957c15d410SQu Wenruo 			BUG();
31967c15d410SQu Wenruo 		}
319731840ae1SZheng Yan 	}
319831840ae1SZheng Yan 
319931840ae1SZheng Yan 	btrfs_cpu_key_to_disk(&disk_key, new_key);
320031840ae1SZheng Yan 	btrfs_set_item_key(eb, &disk_key, slot);
320131840ae1SZheng Yan 	btrfs_mark_buffer_dirty(eb);
320231840ae1SZheng Yan 	if (slot == 0)
3203b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, 1);
320431840ae1SZheng Yan }
320531840ae1SZheng Yan 
320631840ae1SZheng Yan /*
320774123bd7SChris Mason  * try to push data from one node into the next node left in the
320879f95c82SChris Mason  * tree.
3209aa5d6bedSChris Mason  *
3210aa5d6bedSChris Mason  * returns 0 if some ptrs were pushed left, < 0 if there was some horrible
3211aa5d6bedSChris Mason  * error, and > 0 if there was no room in the left hand block.
321274123bd7SChris Mason  */
321398ed5174SChris Mason static int push_node_left(struct btrfs_trans_handle *trans,
32142ff7e61eSJeff Mahoney 			  struct extent_buffer *dst,
3215971a1f66SChris Mason 			  struct extent_buffer *src, int empty)
3216be0e5c09SChris Mason {
3217d30a668fSDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
3218be0e5c09SChris Mason 	int push_items = 0;
3219bb803951SChris Mason 	int src_nritems;
3220bb803951SChris Mason 	int dst_nritems;
3221aa5d6bedSChris Mason 	int ret = 0;
3222be0e5c09SChris Mason 
32235f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
32245f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
32250b246afaSJeff Mahoney 	push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
32267bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
32277bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
322854aa1f4dSChris Mason 
3229bce4eae9SChris Mason 	if (!empty && src_nritems <= 8)
3230971a1f66SChris Mason 		return 1;
3231971a1f66SChris Mason 
3232d397712bSChris Mason 	if (push_items <= 0)
3233be0e5c09SChris Mason 		return 1;
3234be0e5c09SChris Mason 
3235bce4eae9SChris Mason 	if (empty) {
3236971a1f66SChris Mason 		push_items = min(src_nritems, push_items);
3237bce4eae9SChris Mason 		if (push_items < src_nritems) {
3238bce4eae9SChris Mason 			/* leave at least 8 pointers in the node if
3239bce4eae9SChris Mason 			 * we aren't going to empty it
3240bce4eae9SChris Mason 			 */
3241bce4eae9SChris Mason 			if (src_nritems - push_items < 8) {
3242bce4eae9SChris Mason 				if (push_items <= 8)
3243bce4eae9SChris Mason 					return 1;
3244bce4eae9SChris Mason 				push_items -= 8;
3245bce4eae9SChris Mason 			}
3246bce4eae9SChris Mason 		}
3247bce4eae9SChris Mason 	} else
3248bce4eae9SChris Mason 		push_items = min(src_nritems - 8, push_items);
324979f95c82SChris Mason 
3250ed874f0dSDavid Sterba 	ret = tree_mod_log_eb_copy(dst, src, dst_nritems, 0, push_items);
32515de865eeSFilipe David Borba Manana 	if (ret) {
325266642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
32535de865eeSFilipe David Borba Manana 		return ret;
32545de865eeSFilipe David Borba Manana 	}
32555f39d397SChris Mason 	copy_extent_buffer(dst, src,
32565f39d397SChris Mason 			   btrfs_node_key_ptr_offset(dst_nritems),
32575f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
3258123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
32595f39d397SChris Mason 
3260bb803951SChris Mason 	if (push_items < src_nritems) {
326157911b8bSJan Schmidt 		/*
3262bf1d3425SDavid Sterba 		 * Don't call tree_mod_log_insert_move here, key removal was
3263bf1d3425SDavid Sterba 		 * already fully logged by tree_mod_log_eb_copy above.
326457911b8bSJan Schmidt 		 */
32655f39d397SChris Mason 		memmove_extent_buffer(src, btrfs_node_key_ptr_offset(0),
32665f39d397SChris Mason 				      btrfs_node_key_ptr_offset(push_items),
3267e2fa7227SChris Mason 				      (src_nritems - push_items) *
3268123abc88SChris Mason 				      sizeof(struct btrfs_key_ptr));
3269bb803951SChris Mason 	}
32705f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
32715f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
32725f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
32735f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
327431840ae1SZheng Yan 
3275bb803951SChris Mason 	return ret;
3276be0e5c09SChris Mason }
3277be0e5c09SChris Mason 
327897571fd0SChris Mason /*
327979f95c82SChris Mason  * try to push data from one node into the next node right in the
328079f95c82SChris Mason  * tree.
328179f95c82SChris Mason  *
328279f95c82SChris Mason  * returns 0 if some ptrs were pushed, < 0 if there was some horrible
328379f95c82SChris Mason  * error, and > 0 if there was no room in the right hand block.
328479f95c82SChris Mason  *
328579f95c82SChris Mason  * this will  only push up to 1/2 the contents of the left node over
328679f95c82SChris Mason  */
32875f39d397SChris Mason static int balance_node_right(struct btrfs_trans_handle *trans,
32885f39d397SChris Mason 			      struct extent_buffer *dst,
32895f39d397SChris Mason 			      struct extent_buffer *src)
329079f95c82SChris Mason {
329155d32ed8SDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
329279f95c82SChris Mason 	int push_items = 0;
329379f95c82SChris Mason 	int max_push;
329479f95c82SChris Mason 	int src_nritems;
329579f95c82SChris Mason 	int dst_nritems;
329679f95c82SChris Mason 	int ret = 0;
329779f95c82SChris Mason 
32987bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
32997bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
33007bb86316SChris Mason 
33015f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
33025f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
33030b246afaSJeff Mahoney 	push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
3304d397712bSChris Mason 	if (push_items <= 0)
330579f95c82SChris Mason 		return 1;
3306bce4eae9SChris Mason 
3307d397712bSChris Mason 	if (src_nritems < 4)
3308bce4eae9SChris Mason 		return 1;
330979f95c82SChris Mason 
331079f95c82SChris Mason 	max_push = src_nritems / 2 + 1;
331179f95c82SChris Mason 	/* don't try to empty the node */
3312d397712bSChris Mason 	if (max_push >= src_nritems)
331379f95c82SChris Mason 		return 1;
3314252c38f0SYan 
331579f95c82SChris Mason 	if (max_push < push_items)
331679f95c82SChris Mason 		push_items = max_push;
331779f95c82SChris Mason 
3318bf1d3425SDavid Sterba 	ret = tree_mod_log_insert_move(dst, push_items, 0, dst_nritems);
3319bf1d3425SDavid Sterba 	BUG_ON(ret < 0);
33205f39d397SChris Mason 	memmove_extent_buffer(dst, btrfs_node_key_ptr_offset(push_items),
33215f39d397SChris Mason 				      btrfs_node_key_ptr_offset(0),
33225f39d397SChris Mason 				      (dst_nritems) *
33235f39d397SChris Mason 				      sizeof(struct btrfs_key_ptr));
3324d6025579SChris Mason 
3325ed874f0dSDavid Sterba 	ret = tree_mod_log_eb_copy(dst, src, 0, src_nritems - push_items,
3326ed874f0dSDavid Sterba 				   push_items);
33275de865eeSFilipe David Borba Manana 	if (ret) {
332866642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
33295de865eeSFilipe David Borba Manana 		return ret;
33305de865eeSFilipe David Borba Manana 	}
33315f39d397SChris Mason 	copy_extent_buffer(dst, src,
33325f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
33335f39d397SChris Mason 			   btrfs_node_key_ptr_offset(src_nritems - push_items),
3334123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
333579f95c82SChris Mason 
33365f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
33375f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
333879f95c82SChris Mason 
33395f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
33405f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
334131840ae1SZheng Yan 
334279f95c82SChris Mason 	return ret;
334379f95c82SChris Mason }
334479f95c82SChris Mason 
334579f95c82SChris Mason /*
334697571fd0SChris Mason  * helper function to insert a new root level in the tree.
334797571fd0SChris Mason  * A new node is allocated, and a single item is inserted to
334897571fd0SChris Mason  * point to the existing root
3349aa5d6bedSChris Mason  *
3350aa5d6bedSChris Mason  * returns zero on success or < 0 on failure.
335197571fd0SChris Mason  */
3352d397712bSChris Mason static noinline int insert_new_root(struct btrfs_trans_handle *trans,
33535f39d397SChris Mason 			   struct btrfs_root *root,
3354fdd99c72SLiu Bo 			   struct btrfs_path *path, int level)
335574123bd7SChris Mason {
33560b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
33577bb86316SChris Mason 	u64 lower_gen;
33585f39d397SChris Mason 	struct extent_buffer *lower;
33595f39d397SChris Mason 	struct extent_buffer *c;
3360925baeddSChris Mason 	struct extent_buffer *old;
33615f39d397SChris Mason 	struct btrfs_disk_key lower_key;
3362d9d19a01SDavid Sterba 	int ret;
33635c680ed6SChris Mason 
33645c680ed6SChris Mason 	BUG_ON(path->nodes[level]);
33655c680ed6SChris Mason 	BUG_ON(path->nodes[level-1] != root->node);
33665c680ed6SChris Mason 
33677bb86316SChris Mason 	lower = path->nodes[level-1];
33687bb86316SChris Mason 	if (level == 1)
33697bb86316SChris Mason 		btrfs_item_key(lower, &lower_key, 0);
33707bb86316SChris Mason 	else
33717bb86316SChris Mason 		btrfs_node_key(lower, &lower_key, 0);
33727bb86316SChris Mason 
3373a6279470SFilipe Manana 	c = alloc_tree_block_no_bg_flush(trans, root, 0, &lower_key, level,
3374a6279470SFilipe Manana 					 root->node->start, 0);
33755f39d397SChris Mason 	if (IS_ERR(c))
33765f39d397SChris Mason 		return PTR_ERR(c);
3377925baeddSChris Mason 
33780b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
3379f0486c68SYan, Zheng 
33805f39d397SChris Mason 	btrfs_set_header_nritems(c, 1);
33815f39d397SChris Mason 	btrfs_set_node_key(c, &lower_key, 0);
3382db94535dSChris Mason 	btrfs_set_node_blockptr(c, 0, lower->start);
33837bb86316SChris Mason 	lower_gen = btrfs_header_generation(lower);
338431840ae1SZheng Yan 	WARN_ON(lower_gen != trans->transid);
33857bb86316SChris Mason 
33867bb86316SChris Mason 	btrfs_set_node_ptr_generation(c, 0, lower_gen);
33875f39d397SChris Mason 
33885f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
3389d5719762SChris Mason 
3390925baeddSChris Mason 	old = root->node;
3391d9d19a01SDavid Sterba 	ret = tree_mod_log_insert_root(root->node, c, 0);
3392d9d19a01SDavid Sterba 	BUG_ON(ret < 0);
3393240f62c8SChris Mason 	rcu_assign_pointer(root->node, c);
3394925baeddSChris Mason 
3395925baeddSChris Mason 	/* the super has an extra ref to root->node */
3396925baeddSChris Mason 	free_extent_buffer(old);
3397925baeddSChris Mason 
33980b86a832SChris Mason 	add_root_to_dirty_list(root);
339967439dadSDavid Sterba 	atomic_inc(&c->refs);
34005f39d397SChris Mason 	path->nodes[level] = c;
340195449a16Schandan 	path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
340274123bd7SChris Mason 	path->slots[level] = 0;
340374123bd7SChris Mason 	return 0;
340474123bd7SChris Mason }
34055c680ed6SChris Mason 
34065c680ed6SChris Mason /*
34075c680ed6SChris Mason  * worker function to insert a single pointer in a node.
34085c680ed6SChris Mason  * the node should have enough room for the pointer already
340997571fd0SChris Mason  *
34105c680ed6SChris Mason  * slot and level indicate where you want the key to go, and
34115c680ed6SChris Mason  * blocknr is the block the key points to.
34125c680ed6SChris Mason  */
3413143bede5SJeff Mahoney static void insert_ptr(struct btrfs_trans_handle *trans,
34146ad3cf6dSDavid Sterba 		       struct btrfs_path *path,
3415143bede5SJeff Mahoney 		       struct btrfs_disk_key *key, u64 bytenr,
3416c3e06965SJan Schmidt 		       int slot, int level)
34175c680ed6SChris Mason {
34185f39d397SChris Mason 	struct extent_buffer *lower;
34195c680ed6SChris Mason 	int nritems;
3420f3ea38daSJan Schmidt 	int ret;
34215c680ed6SChris Mason 
34225c680ed6SChris Mason 	BUG_ON(!path->nodes[level]);
3423f0486c68SYan, Zheng 	btrfs_assert_tree_locked(path->nodes[level]);
34245f39d397SChris Mason 	lower = path->nodes[level];
34255f39d397SChris Mason 	nritems = btrfs_header_nritems(lower);
3426c293498bSStoyan Gaydarov 	BUG_ON(slot > nritems);
34276ad3cf6dSDavid Sterba 	BUG_ON(nritems == BTRFS_NODEPTRS_PER_BLOCK(trans->fs_info));
342874123bd7SChris Mason 	if (slot != nritems) {
3429bf1d3425SDavid Sterba 		if (level) {
3430bf1d3425SDavid Sterba 			ret = tree_mod_log_insert_move(lower, slot + 1, slot,
3431a446a979SDavid Sterba 					nritems - slot);
3432bf1d3425SDavid Sterba 			BUG_ON(ret < 0);
3433bf1d3425SDavid Sterba 		}
34345f39d397SChris Mason 		memmove_extent_buffer(lower,
34355f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot + 1),
34365f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot),
3437123abc88SChris Mason 			      (nritems - slot) * sizeof(struct btrfs_key_ptr));
343874123bd7SChris Mason 	}
3439c3e06965SJan Schmidt 	if (level) {
3440e09c2efeSDavid Sterba 		ret = tree_mod_log_insert_key(lower, slot, MOD_LOG_KEY_ADD,
3441e09c2efeSDavid Sterba 				GFP_NOFS);
3442f3ea38daSJan Schmidt 		BUG_ON(ret < 0);
3443f3ea38daSJan Schmidt 	}
34445f39d397SChris Mason 	btrfs_set_node_key(lower, key, slot);
3445db94535dSChris Mason 	btrfs_set_node_blockptr(lower, slot, bytenr);
344674493f7aSChris Mason 	WARN_ON(trans->transid == 0);
344774493f7aSChris Mason 	btrfs_set_node_ptr_generation(lower, slot, trans->transid);
34485f39d397SChris Mason 	btrfs_set_header_nritems(lower, nritems + 1);
34495f39d397SChris Mason 	btrfs_mark_buffer_dirty(lower);
345074123bd7SChris Mason }
345174123bd7SChris Mason 
345297571fd0SChris Mason /*
345397571fd0SChris Mason  * split the node at the specified level in path in two.
345497571fd0SChris Mason  * The path is corrected to point to the appropriate node after the split
345597571fd0SChris Mason  *
345697571fd0SChris Mason  * Before splitting this tries to make some room in the node by pushing
345797571fd0SChris Mason  * left and right, if either one works, it returns right away.
3458aa5d6bedSChris Mason  *
3459aa5d6bedSChris Mason  * returns 0 on success and < 0 on failure
346097571fd0SChris Mason  */
3461e02119d5SChris Mason static noinline int split_node(struct btrfs_trans_handle *trans,
3462e02119d5SChris Mason 			       struct btrfs_root *root,
3463e02119d5SChris Mason 			       struct btrfs_path *path, int level)
3464be0e5c09SChris Mason {
34650b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
34665f39d397SChris Mason 	struct extent_buffer *c;
34675f39d397SChris Mason 	struct extent_buffer *split;
34685f39d397SChris Mason 	struct btrfs_disk_key disk_key;
3469be0e5c09SChris Mason 	int mid;
34705c680ed6SChris Mason 	int ret;
34717518a238SChris Mason 	u32 c_nritems;
3472be0e5c09SChris Mason 
34735f39d397SChris Mason 	c = path->nodes[level];
34747bb86316SChris Mason 	WARN_ON(btrfs_header_generation(c) != trans->transid);
34755f39d397SChris Mason 	if (c == root->node) {
3476d9abbf1cSJan Schmidt 		/*
347790f8d62eSJan Schmidt 		 * trying to split the root, lets make a new one
347890f8d62eSJan Schmidt 		 *
3479fdd99c72SLiu Bo 		 * tree mod log: We don't log_removal old root in
348090f8d62eSJan Schmidt 		 * insert_new_root, because that root buffer will be kept as a
348190f8d62eSJan Schmidt 		 * normal node. We are going to log removal of half of the
348290f8d62eSJan Schmidt 		 * elements below with tree_mod_log_eb_copy. We're holding a
348390f8d62eSJan Schmidt 		 * tree lock on the buffer, which is why we cannot race with
348490f8d62eSJan Schmidt 		 * other tree_mod_log users.
3485d9abbf1cSJan Schmidt 		 */
3486fdd99c72SLiu Bo 		ret = insert_new_root(trans, root, path, level + 1);
34875c680ed6SChris Mason 		if (ret)
34885c680ed6SChris Mason 			return ret;
3489b3612421SChris Mason 	} else {
3490e66f709bSChris Mason 		ret = push_nodes_for_insert(trans, root, path, level);
34915f39d397SChris Mason 		c = path->nodes[level];
34925f39d397SChris Mason 		if (!ret && btrfs_header_nritems(c) <
34930b246afaSJeff Mahoney 		    BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3)
3494e66f709bSChris Mason 			return 0;
349554aa1f4dSChris Mason 		if (ret < 0)
349654aa1f4dSChris Mason 			return ret;
34975c680ed6SChris Mason 	}
3498e66f709bSChris Mason 
34995f39d397SChris Mason 	c_nritems = btrfs_header_nritems(c);
35005d4f98a2SYan Zheng 	mid = (c_nritems + 1) / 2;
35015d4f98a2SYan Zheng 	btrfs_node_key(c, &disk_key, mid);
35027bb86316SChris Mason 
3503a6279470SFilipe Manana 	split = alloc_tree_block_no_bg_flush(trans, root, 0, &disk_key, level,
3504a6279470SFilipe Manana 					     c->start, 0);
35055f39d397SChris Mason 	if (IS_ERR(split))
35065f39d397SChris Mason 		return PTR_ERR(split);
350754aa1f4dSChris Mason 
35080b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
3509bc877d28SNikolay Borisov 	ASSERT(btrfs_header_level(c) == level);
35105f39d397SChris Mason 
3511ed874f0dSDavid Sterba 	ret = tree_mod_log_eb_copy(split, c, 0, mid, c_nritems - mid);
35125de865eeSFilipe David Borba Manana 	if (ret) {
351366642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
35145de865eeSFilipe David Borba Manana 		return ret;
35155de865eeSFilipe David Borba Manana 	}
35165f39d397SChris Mason 	copy_extent_buffer(split, c,
35175f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
35185f39d397SChris Mason 			   btrfs_node_key_ptr_offset(mid),
3519123abc88SChris Mason 			   (c_nritems - mid) * sizeof(struct btrfs_key_ptr));
35205f39d397SChris Mason 	btrfs_set_header_nritems(split, c_nritems - mid);
35215f39d397SChris Mason 	btrfs_set_header_nritems(c, mid);
3522aa5d6bedSChris Mason 	ret = 0;
3523aa5d6bedSChris Mason 
35245f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
35255f39d397SChris Mason 	btrfs_mark_buffer_dirty(split);
35265f39d397SChris Mason 
35276ad3cf6dSDavid Sterba 	insert_ptr(trans, path, &disk_key, split->start,
3528c3e06965SJan Schmidt 		   path->slots[level + 1] + 1, level + 1);
3529aa5d6bedSChris Mason 
35305de08d7dSChris Mason 	if (path->slots[level] >= mid) {
35315c680ed6SChris Mason 		path->slots[level] -= mid;
3532925baeddSChris Mason 		btrfs_tree_unlock(c);
35335f39d397SChris Mason 		free_extent_buffer(c);
35345f39d397SChris Mason 		path->nodes[level] = split;
35355c680ed6SChris Mason 		path->slots[level + 1] += 1;
3536eb60ceacSChris Mason 	} else {
3537925baeddSChris Mason 		btrfs_tree_unlock(split);
35385f39d397SChris Mason 		free_extent_buffer(split);
3539be0e5c09SChris Mason 	}
3540aa5d6bedSChris Mason 	return ret;
3541be0e5c09SChris Mason }
3542be0e5c09SChris Mason 
354374123bd7SChris Mason /*
354474123bd7SChris Mason  * how many bytes are required to store the items in a leaf.  start
354574123bd7SChris Mason  * and nr indicate which items in the leaf to check.  This totals up the
354674123bd7SChris Mason  * space used both by the item structs and the item data
354774123bd7SChris Mason  */
35485f39d397SChris Mason static int leaf_space_used(struct extent_buffer *l, int start, int nr)
3549be0e5c09SChris Mason {
355041be1f3bSJosef Bacik 	struct btrfs_item *start_item;
355141be1f3bSJosef Bacik 	struct btrfs_item *end_item;
355241be1f3bSJosef Bacik 	struct btrfs_map_token token;
3553be0e5c09SChris Mason 	int data_len;
35545f39d397SChris Mason 	int nritems = btrfs_header_nritems(l);
3555d4dbff95SChris Mason 	int end = min(nritems, start + nr) - 1;
3556be0e5c09SChris Mason 
3557be0e5c09SChris Mason 	if (!nr)
3558be0e5c09SChris Mason 		return 0;
3559c82f823cSDavid Sterba 	btrfs_init_map_token(&token, l);
3560dd3cc16bSRoss Kirk 	start_item = btrfs_item_nr(start);
3561dd3cc16bSRoss Kirk 	end_item = btrfs_item_nr(end);
356241be1f3bSJosef Bacik 	data_len = btrfs_token_item_offset(l, start_item, &token) +
356341be1f3bSJosef Bacik 		btrfs_token_item_size(l, start_item, &token);
356441be1f3bSJosef Bacik 	data_len = data_len - btrfs_token_item_offset(l, end_item, &token);
35650783fcfcSChris Mason 	data_len += sizeof(struct btrfs_item) * nr;
3566d4dbff95SChris Mason 	WARN_ON(data_len < 0);
3567be0e5c09SChris Mason 	return data_len;
3568be0e5c09SChris Mason }
3569be0e5c09SChris Mason 
357074123bd7SChris Mason /*
3571d4dbff95SChris Mason  * The space between the end of the leaf items and
3572d4dbff95SChris Mason  * the start of the leaf data.  IOW, how much room
3573d4dbff95SChris Mason  * the leaf has left for both items and data
3574d4dbff95SChris Mason  */
3575e902baacSDavid Sterba noinline int btrfs_leaf_free_space(struct extent_buffer *leaf)
3576d4dbff95SChris Mason {
3577e902baacSDavid Sterba 	struct btrfs_fs_info *fs_info = leaf->fs_info;
35785f39d397SChris Mason 	int nritems = btrfs_header_nritems(leaf);
35795f39d397SChris Mason 	int ret;
35800b246afaSJeff Mahoney 
35810b246afaSJeff Mahoney 	ret = BTRFS_LEAF_DATA_SIZE(fs_info) - leaf_space_used(leaf, 0, nritems);
35825f39d397SChris Mason 	if (ret < 0) {
35830b246afaSJeff Mahoney 		btrfs_crit(fs_info,
3584efe120a0SFrank Holton 			   "leaf free space ret %d, leaf data size %lu, used %d nritems %d",
3585da17066cSJeff Mahoney 			   ret,
35860b246afaSJeff Mahoney 			   (unsigned long) BTRFS_LEAF_DATA_SIZE(fs_info),
35875f39d397SChris Mason 			   leaf_space_used(leaf, 0, nritems), nritems);
35885f39d397SChris Mason 	}
35895f39d397SChris Mason 	return ret;
3590d4dbff95SChris Mason }
3591d4dbff95SChris Mason 
359299d8f83cSChris Mason /*
359399d8f83cSChris Mason  * min slot controls the lowest index we're willing to push to the
359499d8f83cSChris Mason  * right.  We'll push up to and including min_slot, but no lower
359599d8f83cSChris Mason  */
3596f72f0010SDavid Sterba static noinline int __push_leaf_right(struct btrfs_path *path,
359744871b1bSChris Mason 				      int data_size, int empty,
359844871b1bSChris Mason 				      struct extent_buffer *right,
359999d8f83cSChris Mason 				      int free_space, u32 left_nritems,
360099d8f83cSChris Mason 				      u32 min_slot)
360100ec4c51SChris Mason {
3602f72f0010SDavid Sterba 	struct btrfs_fs_info *fs_info = right->fs_info;
36035f39d397SChris Mason 	struct extent_buffer *left = path->nodes[0];
360444871b1bSChris Mason 	struct extent_buffer *upper = path->nodes[1];
3605cfed81a0SChris Mason 	struct btrfs_map_token token;
36065f39d397SChris Mason 	struct btrfs_disk_key disk_key;
360700ec4c51SChris Mason 	int slot;
360834a38218SChris Mason 	u32 i;
360900ec4c51SChris Mason 	int push_space = 0;
361000ec4c51SChris Mason 	int push_items = 0;
36110783fcfcSChris Mason 	struct btrfs_item *item;
361234a38218SChris Mason 	u32 nr;
36137518a238SChris Mason 	u32 right_nritems;
36145f39d397SChris Mason 	u32 data_end;
3615db94535dSChris Mason 	u32 this_item_size;
361600ec4c51SChris Mason 
361734a38218SChris Mason 	if (empty)
361834a38218SChris Mason 		nr = 0;
361934a38218SChris Mason 	else
362099d8f83cSChris Mason 		nr = max_t(u32, 1, min_slot);
362134a38218SChris Mason 
362231840ae1SZheng Yan 	if (path->slots[0] >= left_nritems)
362387b29b20SYan Zheng 		push_space += data_size;
362431840ae1SZheng Yan 
362544871b1bSChris Mason 	slot = path->slots[1];
362634a38218SChris Mason 	i = left_nritems - 1;
362734a38218SChris Mason 	while (i >= nr) {
3628dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
3629db94535dSChris Mason 
363031840ae1SZheng Yan 		if (!empty && push_items > 0) {
363131840ae1SZheng Yan 			if (path->slots[0] > i)
363231840ae1SZheng Yan 				break;
363331840ae1SZheng Yan 			if (path->slots[0] == i) {
3634e902baacSDavid Sterba 				int space = btrfs_leaf_free_space(left);
3635e902baacSDavid Sterba 
363631840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
363731840ae1SZheng Yan 					break;
363831840ae1SZheng Yan 			}
363931840ae1SZheng Yan 		}
364031840ae1SZheng Yan 
364100ec4c51SChris Mason 		if (path->slots[0] == i)
364287b29b20SYan Zheng 			push_space += data_size;
3643db94535dSChris Mason 
3644db94535dSChris Mason 		this_item_size = btrfs_item_size(left, item);
3645db94535dSChris Mason 		if (this_item_size + sizeof(*item) + push_space > free_space)
364600ec4c51SChris Mason 			break;
364731840ae1SZheng Yan 
364800ec4c51SChris Mason 		push_items++;
3649db94535dSChris Mason 		push_space += this_item_size + sizeof(*item);
365034a38218SChris Mason 		if (i == 0)
365134a38218SChris Mason 			break;
365234a38218SChris Mason 		i--;
3653db94535dSChris Mason 	}
36545f39d397SChris Mason 
3655925baeddSChris Mason 	if (push_items == 0)
3656925baeddSChris Mason 		goto out_unlock;
36575f39d397SChris Mason 
36586c1500f2SJulia Lawall 	WARN_ON(!empty && push_items == left_nritems);
36595f39d397SChris Mason 
366000ec4c51SChris Mason 	/* push left to right */
36615f39d397SChris Mason 	right_nritems = btrfs_header_nritems(right);
366234a38218SChris Mason 
36635f39d397SChris Mason 	push_space = btrfs_item_end_nr(left, left_nritems - push_items);
36648f881e8cSDavid Sterba 	push_space -= leaf_data_end(left);
36655f39d397SChris Mason 
366600ec4c51SChris Mason 	/* make room in the right data area */
36678f881e8cSDavid Sterba 	data_end = leaf_data_end(right);
36685f39d397SChris Mason 	memmove_extent_buffer(right,
36693d9ec8c4SNikolay Borisov 			      BTRFS_LEAF_DATA_OFFSET + data_end - push_space,
36703d9ec8c4SNikolay Borisov 			      BTRFS_LEAF_DATA_OFFSET + data_end,
36710b246afaSJeff Mahoney 			      BTRFS_LEAF_DATA_SIZE(fs_info) - data_end);
36725f39d397SChris Mason 
367300ec4c51SChris Mason 	/* copy from the left data area */
36743d9ec8c4SNikolay Borisov 	copy_extent_buffer(right, left, BTRFS_LEAF_DATA_OFFSET +
36750b246afaSJeff Mahoney 		     BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
36768f881e8cSDavid Sterba 		     BTRFS_LEAF_DATA_OFFSET + leaf_data_end(left),
3677d6025579SChris Mason 		     push_space);
36785f39d397SChris Mason 
36795f39d397SChris Mason 	memmove_extent_buffer(right, btrfs_item_nr_offset(push_items),
36805f39d397SChris Mason 			      btrfs_item_nr_offset(0),
36810783fcfcSChris Mason 			      right_nritems * sizeof(struct btrfs_item));
36825f39d397SChris Mason 
368300ec4c51SChris Mason 	/* copy the items from left to right */
36845f39d397SChris Mason 	copy_extent_buffer(right, left, btrfs_item_nr_offset(0),
36855f39d397SChris Mason 		   btrfs_item_nr_offset(left_nritems - push_items),
36860783fcfcSChris Mason 		   push_items * sizeof(struct btrfs_item));
368700ec4c51SChris Mason 
368800ec4c51SChris Mason 	/* update the item pointers */
3689c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
36907518a238SChris Mason 	right_nritems += push_items;
36915f39d397SChris Mason 	btrfs_set_header_nritems(right, right_nritems);
36920b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
36937518a238SChris Mason 	for (i = 0; i < right_nritems; i++) {
3694dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
3695cfed81a0SChris Mason 		push_space -= btrfs_token_item_size(right, item, &token);
3696cfed81a0SChris Mason 		btrfs_set_token_item_offset(right, item, push_space, &token);
3697db94535dSChris Mason 	}
3698db94535dSChris Mason 
36997518a238SChris Mason 	left_nritems -= push_items;
37005f39d397SChris Mason 	btrfs_set_header_nritems(left, left_nritems);
370100ec4c51SChris Mason 
370234a38218SChris Mason 	if (left_nritems)
37035f39d397SChris Mason 		btrfs_mark_buffer_dirty(left);
3704f0486c68SYan, Zheng 	else
37056a884d7dSDavid Sterba 		btrfs_clean_tree_block(left);
3706f0486c68SYan, Zheng 
37075f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
3708a429e513SChris Mason 
37095f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
37105f39d397SChris Mason 	btrfs_set_node_key(upper, &disk_key, slot + 1);
3711d6025579SChris Mason 	btrfs_mark_buffer_dirty(upper);
371202217ed2SChris Mason 
371300ec4c51SChris Mason 	/* then fixup the leaf pointer in the path */
37147518a238SChris Mason 	if (path->slots[0] >= left_nritems) {
37157518a238SChris Mason 		path->slots[0] -= left_nritems;
3716925baeddSChris Mason 		if (btrfs_header_nritems(path->nodes[0]) == 0)
37176a884d7dSDavid Sterba 			btrfs_clean_tree_block(path->nodes[0]);
3718925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
37195f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
37205f39d397SChris Mason 		path->nodes[0] = right;
372100ec4c51SChris Mason 		path->slots[1] += 1;
372200ec4c51SChris Mason 	} else {
3723925baeddSChris Mason 		btrfs_tree_unlock(right);
37245f39d397SChris Mason 		free_extent_buffer(right);
372500ec4c51SChris Mason 	}
372600ec4c51SChris Mason 	return 0;
3727925baeddSChris Mason 
3728925baeddSChris Mason out_unlock:
3729925baeddSChris Mason 	btrfs_tree_unlock(right);
3730925baeddSChris Mason 	free_extent_buffer(right);
3731925baeddSChris Mason 	return 1;
373200ec4c51SChris Mason }
3733925baeddSChris Mason 
373400ec4c51SChris Mason /*
373544871b1bSChris Mason  * push some data in the path leaf to the right, trying to free up at
373674123bd7SChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
373744871b1bSChris Mason  *
373844871b1bSChris Mason  * returns 1 if the push failed because the other node didn't have enough
373944871b1bSChris Mason  * room, 0 if everything worked out and < 0 if there were major errors.
374099d8f83cSChris Mason  *
374199d8f83cSChris Mason  * this will push starting from min_slot to the end of the leaf.  It won't
374299d8f83cSChris Mason  * push any slot lower than min_slot
374374123bd7SChris Mason  */
374444871b1bSChris Mason static int push_leaf_right(struct btrfs_trans_handle *trans, struct btrfs_root
374599d8f83cSChris Mason 			   *root, struct btrfs_path *path,
374699d8f83cSChris Mason 			   int min_data_size, int data_size,
374799d8f83cSChris Mason 			   int empty, u32 min_slot)
3748be0e5c09SChris Mason {
374944871b1bSChris Mason 	struct extent_buffer *left = path->nodes[0];
375044871b1bSChris Mason 	struct extent_buffer *right;
375144871b1bSChris Mason 	struct extent_buffer *upper;
375244871b1bSChris Mason 	int slot;
375344871b1bSChris Mason 	int free_space;
375444871b1bSChris Mason 	u32 left_nritems;
375544871b1bSChris Mason 	int ret;
375644871b1bSChris Mason 
375744871b1bSChris Mason 	if (!path->nodes[1])
375844871b1bSChris Mason 		return 1;
375944871b1bSChris Mason 
376044871b1bSChris Mason 	slot = path->slots[1];
376144871b1bSChris Mason 	upper = path->nodes[1];
376244871b1bSChris Mason 	if (slot >= btrfs_header_nritems(upper) - 1)
376344871b1bSChris Mason 		return 1;
376444871b1bSChris Mason 
376544871b1bSChris Mason 	btrfs_assert_tree_locked(path->nodes[1]);
376644871b1bSChris Mason 
37674b231ae4SDavid Sterba 	right = btrfs_read_node_slot(upper, slot + 1);
3768fb770ae4SLiu Bo 	/*
3769fb770ae4SLiu Bo 	 * slot + 1 is not valid or we fail to read the right node,
3770fb770ae4SLiu Bo 	 * no big deal, just return.
3771fb770ae4SLiu Bo 	 */
3772fb770ae4SLiu Bo 	if (IS_ERR(right))
377391ca338dSTsutomu Itoh 		return 1;
377491ca338dSTsutomu Itoh 
377544871b1bSChris Mason 	btrfs_tree_lock(right);
37768bead258SDavid Sterba 	btrfs_set_lock_blocking_write(right);
377744871b1bSChris Mason 
3778e902baacSDavid Sterba 	free_space = btrfs_leaf_free_space(right);
377944871b1bSChris Mason 	if (free_space < data_size)
378044871b1bSChris Mason 		goto out_unlock;
378144871b1bSChris Mason 
378244871b1bSChris Mason 	/* cow and double check */
378344871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, right, upper,
378444871b1bSChris Mason 			      slot + 1, &right);
378544871b1bSChris Mason 	if (ret)
378644871b1bSChris Mason 		goto out_unlock;
378744871b1bSChris Mason 
3788e902baacSDavid Sterba 	free_space = btrfs_leaf_free_space(right);
378944871b1bSChris Mason 	if (free_space < data_size)
379044871b1bSChris Mason 		goto out_unlock;
379144871b1bSChris Mason 
379244871b1bSChris Mason 	left_nritems = btrfs_header_nritems(left);
379344871b1bSChris Mason 	if (left_nritems == 0)
379444871b1bSChris Mason 		goto out_unlock;
379544871b1bSChris Mason 
37962ef1fed2SFilipe David Borba Manana 	if (path->slots[0] == left_nritems && !empty) {
37972ef1fed2SFilipe David Borba Manana 		/* Key greater than all keys in the leaf, right neighbor has
37982ef1fed2SFilipe David Borba Manana 		 * enough room for it and we're not emptying our leaf to delete
37992ef1fed2SFilipe David Borba Manana 		 * it, therefore use right neighbor to insert the new item and
380052042d8eSAndrea Gelmini 		 * no need to touch/dirty our left leaf. */
38012ef1fed2SFilipe David Borba Manana 		btrfs_tree_unlock(left);
38022ef1fed2SFilipe David Borba Manana 		free_extent_buffer(left);
38032ef1fed2SFilipe David Borba Manana 		path->nodes[0] = right;
38042ef1fed2SFilipe David Borba Manana 		path->slots[0] = 0;
38052ef1fed2SFilipe David Borba Manana 		path->slots[1]++;
38062ef1fed2SFilipe David Borba Manana 		return 0;
38072ef1fed2SFilipe David Borba Manana 	}
38082ef1fed2SFilipe David Borba Manana 
3809f72f0010SDavid Sterba 	return __push_leaf_right(path, min_data_size, empty,
381099d8f83cSChris Mason 				right, free_space, left_nritems, min_slot);
381144871b1bSChris Mason out_unlock:
381244871b1bSChris Mason 	btrfs_tree_unlock(right);
381344871b1bSChris Mason 	free_extent_buffer(right);
381444871b1bSChris Mason 	return 1;
381544871b1bSChris Mason }
381644871b1bSChris Mason 
381744871b1bSChris Mason /*
381844871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
381944871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
382099d8f83cSChris Mason  *
382199d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
382299d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us do all the
382399d8f83cSChris Mason  * items
382444871b1bSChris Mason  */
38258087c193SDavid Sterba static noinline int __push_leaf_left(struct btrfs_path *path, int data_size,
382644871b1bSChris Mason 				     int empty, struct extent_buffer *left,
382799d8f83cSChris Mason 				     int free_space, u32 right_nritems,
382899d8f83cSChris Mason 				     u32 max_slot)
382944871b1bSChris Mason {
38308087c193SDavid Sterba 	struct btrfs_fs_info *fs_info = left->fs_info;
38315f39d397SChris Mason 	struct btrfs_disk_key disk_key;
38325f39d397SChris Mason 	struct extent_buffer *right = path->nodes[0];
3833be0e5c09SChris Mason 	int i;
3834be0e5c09SChris Mason 	int push_space = 0;
3835be0e5c09SChris Mason 	int push_items = 0;
38360783fcfcSChris Mason 	struct btrfs_item *item;
38377518a238SChris Mason 	u32 old_left_nritems;
383834a38218SChris Mason 	u32 nr;
3839aa5d6bedSChris Mason 	int ret = 0;
3840db94535dSChris Mason 	u32 this_item_size;
3841db94535dSChris Mason 	u32 old_left_item_size;
3842cfed81a0SChris Mason 	struct btrfs_map_token token;
3843cfed81a0SChris Mason 
384434a38218SChris Mason 	if (empty)
384599d8f83cSChris Mason 		nr = min(right_nritems, max_slot);
384634a38218SChris Mason 	else
384799d8f83cSChris Mason 		nr = min(right_nritems - 1, max_slot);
384834a38218SChris Mason 
384934a38218SChris Mason 	for (i = 0; i < nr; i++) {
3850dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
3851db94535dSChris Mason 
385231840ae1SZheng Yan 		if (!empty && push_items > 0) {
385331840ae1SZheng Yan 			if (path->slots[0] < i)
385431840ae1SZheng Yan 				break;
385531840ae1SZheng Yan 			if (path->slots[0] == i) {
3856e902baacSDavid Sterba 				int space = btrfs_leaf_free_space(right);
3857e902baacSDavid Sterba 
385831840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
385931840ae1SZheng Yan 					break;
386031840ae1SZheng Yan 			}
386131840ae1SZheng Yan 		}
386231840ae1SZheng Yan 
3863be0e5c09SChris Mason 		if (path->slots[0] == i)
386487b29b20SYan Zheng 			push_space += data_size;
3865db94535dSChris Mason 
3866db94535dSChris Mason 		this_item_size = btrfs_item_size(right, item);
3867db94535dSChris Mason 		if (this_item_size + sizeof(*item) + push_space > free_space)
3868be0e5c09SChris Mason 			break;
3869db94535dSChris Mason 
3870be0e5c09SChris Mason 		push_items++;
3871db94535dSChris Mason 		push_space += this_item_size + sizeof(*item);
3872be0e5c09SChris Mason 	}
3873db94535dSChris Mason 
3874be0e5c09SChris Mason 	if (push_items == 0) {
3875925baeddSChris Mason 		ret = 1;
3876925baeddSChris Mason 		goto out;
3877be0e5c09SChris Mason 	}
3878fae7f21cSDulshani Gunawardhana 	WARN_ON(!empty && push_items == btrfs_header_nritems(right));
38795f39d397SChris Mason 
3880be0e5c09SChris Mason 	/* push data from right to left */
38815f39d397SChris Mason 	copy_extent_buffer(left, right,
38825f39d397SChris Mason 			   btrfs_item_nr_offset(btrfs_header_nritems(left)),
38835f39d397SChris Mason 			   btrfs_item_nr_offset(0),
38845f39d397SChris Mason 			   push_items * sizeof(struct btrfs_item));
38855f39d397SChris Mason 
38860b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info) -
38875f39d397SChris Mason 		     btrfs_item_offset_nr(right, push_items - 1);
38885f39d397SChris Mason 
38893d9ec8c4SNikolay Borisov 	copy_extent_buffer(left, right, BTRFS_LEAF_DATA_OFFSET +
38908f881e8cSDavid Sterba 		     leaf_data_end(left) - push_space,
38913d9ec8c4SNikolay Borisov 		     BTRFS_LEAF_DATA_OFFSET +
38925f39d397SChris Mason 		     btrfs_item_offset_nr(right, push_items - 1),
3893be0e5c09SChris Mason 		     push_space);
38945f39d397SChris Mason 	old_left_nritems = btrfs_header_nritems(left);
389587b29b20SYan Zheng 	BUG_ON(old_left_nritems <= 0);
3896eb60ceacSChris Mason 
3897c82f823cSDavid Sterba 	btrfs_init_map_token(&token, left);
3898db94535dSChris Mason 	old_left_item_size = btrfs_item_offset_nr(left, old_left_nritems - 1);
3899be0e5c09SChris Mason 	for (i = old_left_nritems; i < old_left_nritems + push_items; i++) {
39005f39d397SChris Mason 		u32 ioff;
3901db94535dSChris Mason 
3902dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
3903db94535dSChris Mason 
3904cfed81a0SChris Mason 		ioff = btrfs_token_item_offset(left, item, &token);
3905cfed81a0SChris Mason 		btrfs_set_token_item_offset(left, item,
39060b246afaSJeff Mahoney 		      ioff - (BTRFS_LEAF_DATA_SIZE(fs_info) - old_left_item_size),
3907cfed81a0SChris Mason 		      &token);
3908be0e5c09SChris Mason 	}
39095f39d397SChris Mason 	btrfs_set_header_nritems(left, old_left_nritems + push_items);
3910be0e5c09SChris Mason 
3911be0e5c09SChris Mason 	/* fixup right node */
391231b1a2bdSJulia Lawall 	if (push_items > right_nritems)
391331b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "push items %d nr %u\n", push_items,
3914d397712bSChris Mason 		       right_nritems);
391534a38218SChris Mason 
391634a38218SChris Mason 	if (push_items < right_nritems) {
39175f39d397SChris Mason 		push_space = btrfs_item_offset_nr(right, push_items - 1) -
39188f881e8cSDavid Sterba 						  leaf_data_end(right);
39193d9ec8c4SNikolay Borisov 		memmove_extent_buffer(right, BTRFS_LEAF_DATA_OFFSET +
39200b246afaSJeff Mahoney 				      BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
39213d9ec8c4SNikolay Borisov 				      BTRFS_LEAF_DATA_OFFSET +
39228f881e8cSDavid Sterba 				      leaf_data_end(right), push_space);
39235f39d397SChris Mason 
39245f39d397SChris Mason 		memmove_extent_buffer(right, btrfs_item_nr_offset(0),
39255f39d397SChris Mason 			      btrfs_item_nr_offset(push_items),
39265f39d397SChris Mason 			     (btrfs_header_nritems(right) - push_items) *
39270783fcfcSChris Mason 			     sizeof(struct btrfs_item));
392834a38218SChris Mason 	}
3929c82f823cSDavid Sterba 
3930c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
3931eef1c494SYan 	right_nritems -= push_items;
3932eef1c494SYan 	btrfs_set_header_nritems(right, right_nritems);
39330b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
39345f39d397SChris Mason 	for (i = 0; i < right_nritems; i++) {
3935dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
3936db94535dSChris Mason 
3937cfed81a0SChris Mason 		push_space = push_space - btrfs_token_item_size(right,
3938cfed81a0SChris Mason 								item, &token);
3939cfed81a0SChris Mason 		btrfs_set_token_item_offset(right, item, push_space, &token);
3940db94535dSChris Mason 	}
3941eb60ceacSChris Mason 
39425f39d397SChris Mason 	btrfs_mark_buffer_dirty(left);
394334a38218SChris Mason 	if (right_nritems)
39445f39d397SChris Mason 		btrfs_mark_buffer_dirty(right);
3945f0486c68SYan, Zheng 	else
39466a884d7dSDavid Sterba 		btrfs_clean_tree_block(right);
3947098f59c2SChris Mason 
39485f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
3949b167fa91SNikolay Borisov 	fixup_low_keys(path, &disk_key, 1);
3950be0e5c09SChris Mason 
3951be0e5c09SChris Mason 	/* then fixup the leaf pointer in the path */
3952be0e5c09SChris Mason 	if (path->slots[0] < push_items) {
3953be0e5c09SChris Mason 		path->slots[0] += old_left_nritems;
3954925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
39555f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
39565f39d397SChris Mason 		path->nodes[0] = left;
3957be0e5c09SChris Mason 		path->slots[1] -= 1;
3958be0e5c09SChris Mason 	} else {
3959925baeddSChris Mason 		btrfs_tree_unlock(left);
39605f39d397SChris Mason 		free_extent_buffer(left);
3961be0e5c09SChris Mason 		path->slots[0] -= push_items;
3962be0e5c09SChris Mason 	}
3963eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
3964aa5d6bedSChris Mason 	return ret;
3965925baeddSChris Mason out:
3966925baeddSChris Mason 	btrfs_tree_unlock(left);
3967925baeddSChris Mason 	free_extent_buffer(left);
3968925baeddSChris Mason 	return ret;
3969be0e5c09SChris Mason }
3970be0e5c09SChris Mason 
397174123bd7SChris Mason /*
397244871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
397344871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
397499d8f83cSChris Mason  *
397599d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
397699d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us push all the
397799d8f83cSChris Mason  * items
397844871b1bSChris Mason  */
397944871b1bSChris Mason static int push_leaf_left(struct btrfs_trans_handle *trans, struct btrfs_root
398099d8f83cSChris Mason 			  *root, struct btrfs_path *path, int min_data_size,
398199d8f83cSChris Mason 			  int data_size, int empty, u32 max_slot)
398244871b1bSChris Mason {
398344871b1bSChris Mason 	struct extent_buffer *right = path->nodes[0];
398444871b1bSChris Mason 	struct extent_buffer *left;
398544871b1bSChris Mason 	int slot;
398644871b1bSChris Mason 	int free_space;
398744871b1bSChris Mason 	u32 right_nritems;
398844871b1bSChris Mason 	int ret = 0;
398944871b1bSChris Mason 
399044871b1bSChris Mason 	slot = path->slots[1];
399144871b1bSChris Mason 	if (slot == 0)
399244871b1bSChris Mason 		return 1;
399344871b1bSChris Mason 	if (!path->nodes[1])
399444871b1bSChris Mason 		return 1;
399544871b1bSChris Mason 
399644871b1bSChris Mason 	right_nritems = btrfs_header_nritems(right);
399744871b1bSChris Mason 	if (right_nritems == 0)
399844871b1bSChris Mason 		return 1;
399944871b1bSChris Mason 
400044871b1bSChris Mason 	btrfs_assert_tree_locked(path->nodes[1]);
400144871b1bSChris Mason 
40024b231ae4SDavid Sterba 	left = btrfs_read_node_slot(path->nodes[1], slot - 1);
4003fb770ae4SLiu Bo 	/*
4004fb770ae4SLiu Bo 	 * slot - 1 is not valid or we fail to read the left node,
4005fb770ae4SLiu Bo 	 * no big deal, just return.
4006fb770ae4SLiu Bo 	 */
4007fb770ae4SLiu Bo 	if (IS_ERR(left))
400891ca338dSTsutomu Itoh 		return 1;
400991ca338dSTsutomu Itoh 
401044871b1bSChris Mason 	btrfs_tree_lock(left);
40118bead258SDavid Sterba 	btrfs_set_lock_blocking_write(left);
401244871b1bSChris Mason 
4013e902baacSDavid Sterba 	free_space = btrfs_leaf_free_space(left);
401444871b1bSChris Mason 	if (free_space < data_size) {
401544871b1bSChris Mason 		ret = 1;
401644871b1bSChris Mason 		goto out;
401744871b1bSChris Mason 	}
401844871b1bSChris Mason 
401944871b1bSChris Mason 	/* cow and double check */
402044871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, left,
402144871b1bSChris Mason 			      path->nodes[1], slot - 1, &left);
402244871b1bSChris Mason 	if (ret) {
402344871b1bSChris Mason 		/* we hit -ENOSPC, but it isn't fatal here */
402479787eaaSJeff Mahoney 		if (ret == -ENOSPC)
402544871b1bSChris Mason 			ret = 1;
402644871b1bSChris Mason 		goto out;
402744871b1bSChris Mason 	}
402844871b1bSChris Mason 
4029e902baacSDavid Sterba 	free_space = btrfs_leaf_free_space(left);
403044871b1bSChris Mason 	if (free_space < data_size) {
403144871b1bSChris Mason 		ret = 1;
403244871b1bSChris Mason 		goto out;
403344871b1bSChris Mason 	}
403444871b1bSChris Mason 
40358087c193SDavid Sterba 	return __push_leaf_left(path, min_data_size,
403699d8f83cSChris Mason 			       empty, left, free_space, right_nritems,
403799d8f83cSChris Mason 			       max_slot);
403844871b1bSChris Mason out:
403944871b1bSChris Mason 	btrfs_tree_unlock(left);
404044871b1bSChris Mason 	free_extent_buffer(left);
404144871b1bSChris Mason 	return ret;
404244871b1bSChris Mason }
404344871b1bSChris Mason 
404444871b1bSChris Mason /*
404574123bd7SChris Mason  * split the path's leaf in two, making sure there is at least data_size
404674123bd7SChris Mason  * available for the resulting leaf level of the path.
404774123bd7SChris Mason  */
4048143bede5SJeff Mahoney static noinline void copy_for_split(struct btrfs_trans_handle *trans,
404944871b1bSChris Mason 				    struct btrfs_path *path,
405044871b1bSChris Mason 				    struct extent_buffer *l,
405144871b1bSChris Mason 				    struct extent_buffer *right,
405244871b1bSChris Mason 				    int slot, int mid, int nritems)
4053be0e5c09SChris Mason {
405494f94ad9SDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
4055be0e5c09SChris Mason 	int data_copy_size;
4056be0e5c09SChris Mason 	int rt_data_off;
4057be0e5c09SChris Mason 	int i;
4058d4dbff95SChris Mason 	struct btrfs_disk_key disk_key;
4059cfed81a0SChris Mason 	struct btrfs_map_token token;
4060cfed81a0SChris Mason 
40615f39d397SChris Mason 	nritems = nritems - mid;
40625f39d397SChris Mason 	btrfs_set_header_nritems(right, nritems);
40638f881e8cSDavid Sterba 	data_copy_size = btrfs_item_end_nr(l, mid) - leaf_data_end(l);
40645f39d397SChris Mason 
40655f39d397SChris Mason 	copy_extent_buffer(right, l, btrfs_item_nr_offset(0),
40665f39d397SChris Mason 			   btrfs_item_nr_offset(mid),
40675f39d397SChris Mason 			   nritems * sizeof(struct btrfs_item));
40685f39d397SChris Mason 
40695f39d397SChris Mason 	copy_extent_buffer(right, l,
40703d9ec8c4SNikolay Borisov 		     BTRFS_LEAF_DATA_OFFSET + BTRFS_LEAF_DATA_SIZE(fs_info) -
40713d9ec8c4SNikolay Borisov 		     data_copy_size, BTRFS_LEAF_DATA_OFFSET +
40728f881e8cSDavid Sterba 		     leaf_data_end(l), data_copy_size);
407374123bd7SChris Mason 
40740b246afaSJeff Mahoney 	rt_data_off = BTRFS_LEAF_DATA_SIZE(fs_info) - btrfs_item_end_nr(l, mid);
40755f39d397SChris Mason 
4076c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
40775f39d397SChris Mason 	for (i = 0; i < nritems; i++) {
4078dd3cc16bSRoss Kirk 		struct btrfs_item *item = btrfs_item_nr(i);
4079db94535dSChris Mason 		u32 ioff;
4080db94535dSChris Mason 
4081cfed81a0SChris Mason 		ioff = btrfs_token_item_offset(right, item, &token);
4082cfed81a0SChris Mason 		btrfs_set_token_item_offset(right, item,
4083cfed81a0SChris Mason 					    ioff + rt_data_off, &token);
40840783fcfcSChris Mason 	}
408574123bd7SChris Mason 
40865f39d397SChris Mason 	btrfs_set_header_nritems(l, mid);
40875f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
40886ad3cf6dSDavid Sterba 	insert_ptr(trans, path, &disk_key, right->start, path->slots[1] + 1, 1);
40895f39d397SChris Mason 
40905f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
40915f39d397SChris Mason 	btrfs_mark_buffer_dirty(l);
4092eb60ceacSChris Mason 	BUG_ON(path->slots[0] != slot);
40935f39d397SChris Mason 
4094be0e5c09SChris Mason 	if (mid <= slot) {
4095925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
40965f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
40975f39d397SChris Mason 		path->nodes[0] = right;
4098be0e5c09SChris Mason 		path->slots[0] -= mid;
4099be0e5c09SChris Mason 		path->slots[1] += 1;
4100925baeddSChris Mason 	} else {
4101925baeddSChris Mason 		btrfs_tree_unlock(right);
41025f39d397SChris Mason 		free_extent_buffer(right);
4103925baeddSChris Mason 	}
41045f39d397SChris Mason 
4105eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
410644871b1bSChris Mason }
410744871b1bSChris Mason 
410844871b1bSChris Mason /*
410999d8f83cSChris Mason  * double splits happen when we need to insert a big item in the middle
411099d8f83cSChris Mason  * of a leaf.  A double split can leave us with 3 mostly empty leaves:
411199d8f83cSChris Mason  * leaf: [ slots 0 - N] [ our target ] [ N + 1 - total in leaf ]
411299d8f83cSChris Mason  *          A                 B                 C
411399d8f83cSChris Mason  *
411499d8f83cSChris Mason  * We avoid this by trying to push the items on either side of our target
411599d8f83cSChris Mason  * into the adjacent leaves.  If all goes well we can avoid the double split
411699d8f83cSChris Mason  * completely.
411799d8f83cSChris Mason  */
411899d8f83cSChris Mason static noinline int push_for_double_split(struct btrfs_trans_handle *trans,
411999d8f83cSChris Mason 					  struct btrfs_root *root,
412099d8f83cSChris Mason 					  struct btrfs_path *path,
412199d8f83cSChris Mason 					  int data_size)
412299d8f83cSChris Mason {
412399d8f83cSChris Mason 	int ret;
412499d8f83cSChris Mason 	int progress = 0;
412599d8f83cSChris Mason 	int slot;
412699d8f83cSChris Mason 	u32 nritems;
41275a4267caSFilipe David Borba Manana 	int space_needed = data_size;
412899d8f83cSChris Mason 
412999d8f83cSChris Mason 	slot = path->slots[0];
41305a4267caSFilipe David Borba Manana 	if (slot < btrfs_header_nritems(path->nodes[0]))
4131e902baacSDavid Sterba 		space_needed -= btrfs_leaf_free_space(path->nodes[0]);
413299d8f83cSChris Mason 
413399d8f83cSChris Mason 	/*
413499d8f83cSChris Mason 	 * try to push all the items after our slot into the
413599d8f83cSChris Mason 	 * right leaf
413699d8f83cSChris Mason 	 */
41375a4267caSFilipe David Borba Manana 	ret = push_leaf_right(trans, root, path, 1, space_needed, 0, slot);
413899d8f83cSChris Mason 	if (ret < 0)
413999d8f83cSChris Mason 		return ret;
414099d8f83cSChris Mason 
414199d8f83cSChris Mason 	if (ret == 0)
414299d8f83cSChris Mason 		progress++;
414399d8f83cSChris Mason 
414499d8f83cSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
414599d8f83cSChris Mason 	/*
414699d8f83cSChris Mason 	 * our goal is to get our slot at the start or end of a leaf.  If
414799d8f83cSChris Mason 	 * we've done so we're done
414899d8f83cSChris Mason 	 */
414999d8f83cSChris Mason 	if (path->slots[0] == 0 || path->slots[0] == nritems)
415099d8f83cSChris Mason 		return 0;
415199d8f83cSChris Mason 
4152e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
415399d8f83cSChris Mason 		return 0;
415499d8f83cSChris Mason 
415599d8f83cSChris Mason 	/* try to push all the items before our slot into the next leaf */
415699d8f83cSChris Mason 	slot = path->slots[0];
4157263d3995SFilipe Manana 	space_needed = data_size;
4158263d3995SFilipe Manana 	if (slot > 0)
4159e902baacSDavid Sterba 		space_needed -= btrfs_leaf_free_space(path->nodes[0]);
41605a4267caSFilipe David Borba Manana 	ret = push_leaf_left(trans, root, path, 1, space_needed, 0, slot);
416199d8f83cSChris Mason 	if (ret < 0)
416299d8f83cSChris Mason 		return ret;
416399d8f83cSChris Mason 
416499d8f83cSChris Mason 	if (ret == 0)
416599d8f83cSChris Mason 		progress++;
416699d8f83cSChris Mason 
416799d8f83cSChris Mason 	if (progress)
416899d8f83cSChris Mason 		return 0;
416999d8f83cSChris Mason 	return 1;
417099d8f83cSChris Mason }
417199d8f83cSChris Mason 
417299d8f83cSChris Mason /*
417344871b1bSChris Mason  * split the path's leaf in two, making sure there is at least data_size
417444871b1bSChris Mason  * available for the resulting leaf level of the path.
417544871b1bSChris Mason  *
417644871b1bSChris Mason  * returns 0 if all went well and < 0 on failure.
417744871b1bSChris Mason  */
417844871b1bSChris Mason static noinline int split_leaf(struct btrfs_trans_handle *trans,
417944871b1bSChris Mason 			       struct btrfs_root *root,
4180310712b2SOmar Sandoval 			       const struct btrfs_key *ins_key,
418144871b1bSChris Mason 			       struct btrfs_path *path, int data_size,
418244871b1bSChris Mason 			       int extend)
418344871b1bSChris Mason {
41845d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
418544871b1bSChris Mason 	struct extent_buffer *l;
418644871b1bSChris Mason 	u32 nritems;
418744871b1bSChris Mason 	int mid;
418844871b1bSChris Mason 	int slot;
418944871b1bSChris Mason 	struct extent_buffer *right;
4190b7a0365eSDaniel Dressler 	struct btrfs_fs_info *fs_info = root->fs_info;
419144871b1bSChris Mason 	int ret = 0;
419244871b1bSChris Mason 	int wret;
41935d4f98a2SYan Zheng 	int split;
419444871b1bSChris Mason 	int num_doubles = 0;
419599d8f83cSChris Mason 	int tried_avoid_double = 0;
419644871b1bSChris Mason 
4197a5719521SYan, Zheng 	l = path->nodes[0];
4198a5719521SYan, Zheng 	slot = path->slots[0];
4199a5719521SYan, Zheng 	if (extend && data_size + btrfs_item_size_nr(l, slot) +
42000b246afaSJeff Mahoney 	    sizeof(struct btrfs_item) > BTRFS_LEAF_DATA_SIZE(fs_info))
4201a5719521SYan, Zheng 		return -EOVERFLOW;
4202a5719521SYan, Zheng 
420344871b1bSChris Mason 	/* first try to make some room by pushing left and right */
420433157e05SLiu Bo 	if (data_size && path->nodes[1]) {
42055a4267caSFilipe David Borba Manana 		int space_needed = data_size;
42065a4267caSFilipe David Borba Manana 
42075a4267caSFilipe David Borba Manana 		if (slot < btrfs_header_nritems(l))
4208e902baacSDavid Sterba 			space_needed -= btrfs_leaf_free_space(l);
42095a4267caSFilipe David Borba Manana 
42105a4267caSFilipe David Borba Manana 		wret = push_leaf_right(trans, root, path, space_needed,
42115a4267caSFilipe David Borba Manana 				       space_needed, 0, 0);
421244871b1bSChris Mason 		if (wret < 0)
421344871b1bSChris Mason 			return wret;
421444871b1bSChris Mason 		if (wret) {
4215263d3995SFilipe Manana 			space_needed = data_size;
4216263d3995SFilipe Manana 			if (slot > 0)
4217e902baacSDavid Sterba 				space_needed -= btrfs_leaf_free_space(l);
42185a4267caSFilipe David Borba Manana 			wret = push_leaf_left(trans, root, path, space_needed,
42195a4267caSFilipe David Borba Manana 					      space_needed, 0, (u32)-1);
422044871b1bSChris Mason 			if (wret < 0)
422144871b1bSChris Mason 				return wret;
422244871b1bSChris Mason 		}
422344871b1bSChris Mason 		l = path->nodes[0];
422444871b1bSChris Mason 
422544871b1bSChris Mason 		/* did the pushes work? */
4226e902baacSDavid Sterba 		if (btrfs_leaf_free_space(l) >= data_size)
422744871b1bSChris Mason 			return 0;
422844871b1bSChris Mason 	}
422944871b1bSChris Mason 
423044871b1bSChris Mason 	if (!path->nodes[1]) {
4231fdd99c72SLiu Bo 		ret = insert_new_root(trans, root, path, 1);
423244871b1bSChris Mason 		if (ret)
423344871b1bSChris Mason 			return ret;
423444871b1bSChris Mason 	}
423544871b1bSChris Mason again:
42365d4f98a2SYan Zheng 	split = 1;
423744871b1bSChris Mason 	l = path->nodes[0];
423844871b1bSChris Mason 	slot = path->slots[0];
423944871b1bSChris Mason 	nritems = btrfs_header_nritems(l);
424044871b1bSChris Mason 	mid = (nritems + 1) / 2;
424144871b1bSChris Mason 
42425d4f98a2SYan Zheng 	if (mid <= slot) {
42435d4f98a2SYan Zheng 		if (nritems == 1 ||
42445d4f98a2SYan Zheng 		    leaf_space_used(l, mid, nritems - mid) + data_size >
42450b246afaSJeff Mahoney 			BTRFS_LEAF_DATA_SIZE(fs_info)) {
42465d4f98a2SYan Zheng 			if (slot >= nritems) {
42475d4f98a2SYan Zheng 				split = 0;
42485d4f98a2SYan Zheng 			} else {
42495d4f98a2SYan Zheng 				mid = slot;
42505d4f98a2SYan Zheng 				if (mid != nritems &&
42515d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
42520b246afaSJeff Mahoney 				    data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
425399d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
425499d8f83cSChris Mason 						goto push_for_double;
42555d4f98a2SYan Zheng 					split = 2;
42565d4f98a2SYan Zheng 				}
42575d4f98a2SYan Zheng 			}
42585d4f98a2SYan Zheng 		}
42595d4f98a2SYan Zheng 	} else {
42605d4f98a2SYan Zheng 		if (leaf_space_used(l, 0, mid) + data_size >
42610b246afaSJeff Mahoney 			BTRFS_LEAF_DATA_SIZE(fs_info)) {
42625d4f98a2SYan Zheng 			if (!extend && data_size && slot == 0) {
42635d4f98a2SYan Zheng 				split = 0;
42645d4f98a2SYan Zheng 			} else if ((extend || !data_size) && slot == 0) {
42655d4f98a2SYan Zheng 				mid = 1;
42665d4f98a2SYan Zheng 			} else {
42675d4f98a2SYan Zheng 				mid = slot;
42685d4f98a2SYan Zheng 				if (mid != nritems &&
42695d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
42700b246afaSJeff Mahoney 				    data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
427199d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
427299d8f83cSChris Mason 						goto push_for_double;
42735d4f98a2SYan Zheng 					split = 2;
42745d4f98a2SYan Zheng 				}
42755d4f98a2SYan Zheng 			}
42765d4f98a2SYan Zheng 		}
42775d4f98a2SYan Zheng 	}
42785d4f98a2SYan Zheng 
42795d4f98a2SYan Zheng 	if (split == 0)
42805d4f98a2SYan Zheng 		btrfs_cpu_key_to_disk(&disk_key, ins_key);
42815d4f98a2SYan Zheng 	else
42825d4f98a2SYan Zheng 		btrfs_item_key(l, &disk_key, mid);
42835d4f98a2SYan Zheng 
4284a6279470SFilipe Manana 	right = alloc_tree_block_no_bg_flush(trans, root, 0, &disk_key, 0,
4285a6279470SFilipe Manana 					     l->start, 0);
4286f0486c68SYan, Zheng 	if (IS_ERR(right))
428744871b1bSChris Mason 		return PTR_ERR(right);
4288f0486c68SYan, Zheng 
42890b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
429044871b1bSChris Mason 
42915d4f98a2SYan Zheng 	if (split == 0) {
429244871b1bSChris Mason 		if (mid <= slot) {
429344871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
42946ad3cf6dSDavid Sterba 			insert_ptr(trans, path, &disk_key,
42952ff7e61eSJeff Mahoney 				   right->start, path->slots[1] + 1, 1);
429644871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
429744871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
429844871b1bSChris Mason 			path->nodes[0] = right;
429944871b1bSChris Mason 			path->slots[0] = 0;
430044871b1bSChris Mason 			path->slots[1] += 1;
430144871b1bSChris Mason 		} else {
430244871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
43036ad3cf6dSDavid Sterba 			insert_ptr(trans, path, &disk_key,
43042ff7e61eSJeff Mahoney 				   right->start, path->slots[1], 1);
430544871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
430644871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
430744871b1bSChris Mason 			path->nodes[0] = right;
430844871b1bSChris Mason 			path->slots[0] = 0;
4309143bede5SJeff Mahoney 			if (path->slots[1] == 0)
4310b167fa91SNikolay Borisov 				fixup_low_keys(path, &disk_key, 1);
43115d4f98a2SYan Zheng 		}
4312196e0249SLiu Bo 		/*
4313196e0249SLiu Bo 		 * We create a new leaf 'right' for the required ins_len and
4314196e0249SLiu Bo 		 * we'll do btrfs_mark_buffer_dirty() on this leaf after copying
4315196e0249SLiu Bo 		 * the content of ins_len to 'right'.
4316196e0249SLiu Bo 		 */
431744871b1bSChris Mason 		return ret;
431844871b1bSChris Mason 	}
431944871b1bSChris Mason 
432094f94ad9SDavid Sterba 	copy_for_split(trans, path, l, right, slot, mid, nritems);
432144871b1bSChris Mason 
43225d4f98a2SYan Zheng 	if (split == 2) {
4323cc0c5538SChris Mason 		BUG_ON(num_doubles != 0);
4324cc0c5538SChris Mason 		num_doubles++;
4325cc0c5538SChris Mason 		goto again;
43263326d1b0SChris Mason 	}
432744871b1bSChris Mason 
4328143bede5SJeff Mahoney 	return 0;
432999d8f83cSChris Mason 
433099d8f83cSChris Mason push_for_double:
433199d8f83cSChris Mason 	push_for_double_split(trans, root, path, data_size);
433299d8f83cSChris Mason 	tried_avoid_double = 1;
4333e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
433499d8f83cSChris Mason 		return 0;
433599d8f83cSChris Mason 	goto again;
4336be0e5c09SChris Mason }
4337be0e5c09SChris Mason 
4338ad48fd75SYan, Zheng static noinline int setup_leaf_for_split(struct btrfs_trans_handle *trans,
4339ad48fd75SYan, Zheng 					 struct btrfs_root *root,
4340ad48fd75SYan, Zheng 					 struct btrfs_path *path, int ins_len)
4341ad48fd75SYan, Zheng {
4342ad48fd75SYan, Zheng 	struct btrfs_key key;
4343ad48fd75SYan, Zheng 	struct extent_buffer *leaf;
4344ad48fd75SYan, Zheng 	struct btrfs_file_extent_item *fi;
4345ad48fd75SYan, Zheng 	u64 extent_len = 0;
4346ad48fd75SYan, Zheng 	u32 item_size;
4347ad48fd75SYan, Zheng 	int ret;
4348ad48fd75SYan, Zheng 
4349ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4350ad48fd75SYan, Zheng 	btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4351ad48fd75SYan, Zheng 
4352ad48fd75SYan, Zheng 	BUG_ON(key.type != BTRFS_EXTENT_DATA_KEY &&
4353ad48fd75SYan, Zheng 	       key.type != BTRFS_EXTENT_CSUM_KEY);
4354ad48fd75SYan, Zheng 
4355e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) >= ins_len)
4356ad48fd75SYan, Zheng 		return 0;
4357ad48fd75SYan, Zheng 
4358ad48fd75SYan, Zheng 	item_size = btrfs_item_size_nr(leaf, path->slots[0]);
4359ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
4360ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
4361ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
4362ad48fd75SYan, Zheng 		extent_len = btrfs_file_extent_num_bytes(leaf, fi);
4363ad48fd75SYan, Zheng 	}
4364b3b4aa74SDavid Sterba 	btrfs_release_path(path);
4365ad48fd75SYan, Zheng 
4366ad48fd75SYan, Zheng 	path->keep_locks = 1;
4367ad48fd75SYan, Zheng 	path->search_for_split = 1;
4368ad48fd75SYan, Zheng 	ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
4369ad48fd75SYan, Zheng 	path->search_for_split = 0;
4370a8df6fe6SFilipe Manana 	if (ret > 0)
4371a8df6fe6SFilipe Manana 		ret = -EAGAIN;
4372ad48fd75SYan, Zheng 	if (ret < 0)
4373ad48fd75SYan, Zheng 		goto err;
4374ad48fd75SYan, Zheng 
4375ad48fd75SYan, Zheng 	ret = -EAGAIN;
4376ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4377a8df6fe6SFilipe Manana 	/* if our item isn't there, return now */
4378a8df6fe6SFilipe Manana 	if (item_size != btrfs_item_size_nr(leaf, path->slots[0]))
4379ad48fd75SYan, Zheng 		goto err;
4380ad48fd75SYan, Zheng 
4381109f6aefSChris Mason 	/* the leaf has  changed, it now has room.  return now */
4382e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= ins_len)
4383109f6aefSChris Mason 		goto err;
4384109f6aefSChris Mason 
4385ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
4386ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
4387ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
4388ad48fd75SYan, Zheng 		if (extent_len != btrfs_file_extent_num_bytes(leaf, fi))
4389ad48fd75SYan, Zheng 			goto err;
4390ad48fd75SYan, Zheng 	}
4391ad48fd75SYan, Zheng 
4392ad48fd75SYan, Zheng 	btrfs_set_path_blocking(path);
4393ad48fd75SYan, Zheng 	ret = split_leaf(trans, root, &key, path, ins_len, 1);
4394f0486c68SYan, Zheng 	if (ret)
4395f0486c68SYan, Zheng 		goto err;
4396ad48fd75SYan, Zheng 
4397ad48fd75SYan, Zheng 	path->keep_locks = 0;
4398ad48fd75SYan, Zheng 	btrfs_unlock_up_safe(path, 1);
4399ad48fd75SYan, Zheng 	return 0;
4400ad48fd75SYan, Zheng err:
4401ad48fd75SYan, Zheng 	path->keep_locks = 0;
4402ad48fd75SYan, Zheng 	return ret;
4403ad48fd75SYan, Zheng }
4404ad48fd75SYan, Zheng 
440525263cd7SDavid Sterba static noinline int split_item(struct btrfs_path *path,
4406310712b2SOmar Sandoval 			       const struct btrfs_key *new_key,
4407459931ecSChris Mason 			       unsigned long split_offset)
4408459931ecSChris Mason {
4409459931ecSChris Mason 	struct extent_buffer *leaf;
4410459931ecSChris Mason 	struct btrfs_item *item;
4411459931ecSChris Mason 	struct btrfs_item *new_item;
4412459931ecSChris Mason 	int slot;
4413ad48fd75SYan, Zheng 	char *buf;
4414459931ecSChris Mason 	u32 nritems;
4415ad48fd75SYan, Zheng 	u32 item_size;
4416459931ecSChris Mason 	u32 orig_offset;
4417459931ecSChris Mason 	struct btrfs_disk_key disk_key;
4418459931ecSChris Mason 
4419459931ecSChris Mason 	leaf = path->nodes[0];
4420e902baacSDavid Sterba 	BUG_ON(btrfs_leaf_free_space(leaf) < sizeof(struct btrfs_item));
4421b9473439SChris Mason 
4422b4ce94deSChris Mason 	btrfs_set_path_blocking(path);
4423b4ce94deSChris Mason 
4424dd3cc16bSRoss Kirk 	item = btrfs_item_nr(path->slots[0]);
4425459931ecSChris Mason 	orig_offset = btrfs_item_offset(leaf, item);
4426459931ecSChris Mason 	item_size = btrfs_item_size(leaf, item);
4427459931ecSChris Mason 
4428459931ecSChris Mason 	buf = kmalloc(item_size, GFP_NOFS);
4429ad48fd75SYan, Zheng 	if (!buf)
4430ad48fd75SYan, Zheng 		return -ENOMEM;
4431ad48fd75SYan, Zheng 
4432459931ecSChris Mason 	read_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf,
4433459931ecSChris Mason 			    path->slots[0]), item_size);
4434ad48fd75SYan, Zheng 
4435459931ecSChris Mason 	slot = path->slots[0] + 1;
4436459931ecSChris Mason 	nritems = btrfs_header_nritems(leaf);
4437459931ecSChris Mason 	if (slot != nritems) {
4438459931ecSChris Mason 		/* shift the items */
4439459931ecSChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + 1),
4440459931ecSChris Mason 				btrfs_item_nr_offset(slot),
4441459931ecSChris Mason 				(nritems - slot) * sizeof(struct btrfs_item));
4442459931ecSChris Mason 	}
4443459931ecSChris Mason 
4444459931ecSChris Mason 	btrfs_cpu_key_to_disk(&disk_key, new_key);
4445459931ecSChris Mason 	btrfs_set_item_key(leaf, &disk_key, slot);
4446459931ecSChris Mason 
4447dd3cc16bSRoss Kirk 	new_item = btrfs_item_nr(slot);
4448459931ecSChris Mason 
4449459931ecSChris Mason 	btrfs_set_item_offset(leaf, new_item, orig_offset);
4450459931ecSChris Mason 	btrfs_set_item_size(leaf, new_item, item_size - split_offset);
4451459931ecSChris Mason 
4452459931ecSChris Mason 	btrfs_set_item_offset(leaf, item,
4453459931ecSChris Mason 			      orig_offset + item_size - split_offset);
4454459931ecSChris Mason 	btrfs_set_item_size(leaf, item, split_offset);
4455459931ecSChris Mason 
4456459931ecSChris Mason 	btrfs_set_header_nritems(leaf, nritems + 1);
4457459931ecSChris Mason 
4458459931ecSChris Mason 	/* write the data for the start of the original item */
4459459931ecSChris Mason 	write_extent_buffer(leaf, buf,
4460459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, path->slots[0]),
4461459931ecSChris Mason 			    split_offset);
4462459931ecSChris Mason 
4463459931ecSChris Mason 	/* write the data for the new item */
4464459931ecSChris Mason 	write_extent_buffer(leaf, buf + split_offset,
4465459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, slot),
4466459931ecSChris Mason 			    item_size - split_offset);
4467459931ecSChris Mason 	btrfs_mark_buffer_dirty(leaf);
4468459931ecSChris Mason 
4469e902baacSDavid Sterba 	BUG_ON(btrfs_leaf_free_space(leaf) < 0);
4470459931ecSChris Mason 	kfree(buf);
4471ad48fd75SYan, Zheng 	return 0;
4472ad48fd75SYan, Zheng }
4473ad48fd75SYan, Zheng 
4474ad48fd75SYan, Zheng /*
4475ad48fd75SYan, Zheng  * This function splits a single item into two items,
4476ad48fd75SYan, Zheng  * giving 'new_key' to the new item and splitting the
4477ad48fd75SYan, Zheng  * old one at split_offset (from the start of the item).
4478ad48fd75SYan, Zheng  *
4479ad48fd75SYan, Zheng  * The path may be released by this operation.  After
4480ad48fd75SYan, Zheng  * the split, the path is pointing to the old item.  The
4481ad48fd75SYan, Zheng  * new item is going to be in the same node as the old one.
4482ad48fd75SYan, Zheng  *
4483ad48fd75SYan, Zheng  * Note, the item being split must be smaller enough to live alone on
4484ad48fd75SYan, Zheng  * a tree block with room for one extra struct btrfs_item
4485ad48fd75SYan, Zheng  *
4486ad48fd75SYan, Zheng  * This allows us to split the item in place, keeping a lock on the
4487ad48fd75SYan, Zheng  * leaf the entire time.
4488ad48fd75SYan, Zheng  */
4489ad48fd75SYan, Zheng int btrfs_split_item(struct btrfs_trans_handle *trans,
4490ad48fd75SYan, Zheng 		     struct btrfs_root *root,
4491ad48fd75SYan, Zheng 		     struct btrfs_path *path,
4492310712b2SOmar Sandoval 		     const struct btrfs_key *new_key,
4493ad48fd75SYan, Zheng 		     unsigned long split_offset)
4494ad48fd75SYan, Zheng {
4495ad48fd75SYan, Zheng 	int ret;
4496ad48fd75SYan, Zheng 	ret = setup_leaf_for_split(trans, root, path,
4497ad48fd75SYan, Zheng 				   sizeof(struct btrfs_item));
4498ad48fd75SYan, Zheng 	if (ret)
4499459931ecSChris Mason 		return ret;
4500ad48fd75SYan, Zheng 
450125263cd7SDavid Sterba 	ret = split_item(path, new_key, split_offset);
4502ad48fd75SYan, Zheng 	return ret;
4503ad48fd75SYan, Zheng }
4504ad48fd75SYan, Zheng 
4505ad48fd75SYan, Zheng /*
4506ad48fd75SYan, Zheng  * This function duplicate a item, giving 'new_key' to the new item.
4507ad48fd75SYan, Zheng  * It guarantees both items live in the same tree leaf and the new item
4508ad48fd75SYan, Zheng  * is contiguous with the original item.
4509ad48fd75SYan, Zheng  *
4510ad48fd75SYan, Zheng  * This allows us to split file extent in place, keeping a lock on the
4511ad48fd75SYan, Zheng  * leaf the entire time.
4512ad48fd75SYan, Zheng  */
4513ad48fd75SYan, Zheng int btrfs_duplicate_item(struct btrfs_trans_handle *trans,
4514ad48fd75SYan, Zheng 			 struct btrfs_root *root,
4515ad48fd75SYan, Zheng 			 struct btrfs_path *path,
4516310712b2SOmar Sandoval 			 const struct btrfs_key *new_key)
4517ad48fd75SYan, Zheng {
4518ad48fd75SYan, Zheng 	struct extent_buffer *leaf;
4519ad48fd75SYan, Zheng 	int ret;
4520ad48fd75SYan, Zheng 	u32 item_size;
4521ad48fd75SYan, Zheng 
4522ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4523ad48fd75SYan, Zheng 	item_size = btrfs_item_size_nr(leaf, path->slots[0]);
4524ad48fd75SYan, Zheng 	ret = setup_leaf_for_split(trans, root, path,
4525ad48fd75SYan, Zheng 				   item_size + sizeof(struct btrfs_item));
4526ad48fd75SYan, Zheng 	if (ret)
4527ad48fd75SYan, Zheng 		return ret;
4528ad48fd75SYan, Zheng 
4529ad48fd75SYan, Zheng 	path->slots[0]++;
4530afe5fea7STsutomu Itoh 	setup_items_for_insert(root, path, new_key, &item_size,
4531ad48fd75SYan, Zheng 			       item_size, item_size +
4532ad48fd75SYan, Zheng 			       sizeof(struct btrfs_item), 1);
4533ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4534ad48fd75SYan, Zheng 	memcpy_extent_buffer(leaf,
4535ad48fd75SYan, Zheng 			     btrfs_item_ptr_offset(leaf, path->slots[0]),
4536ad48fd75SYan, Zheng 			     btrfs_item_ptr_offset(leaf, path->slots[0] - 1),
4537ad48fd75SYan, Zheng 			     item_size);
4538ad48fd75SYan, Zheng 	return 0;
4539459931ecSChris Mason }
4540459931ecSChris Mason 
4541459931ecSChris Mason /*
4542d352ac68SChris Mason  * make the item pointed to by the path smaller.  new_size indicates
4543d352ac68SChris Mason  * how small to make it, and from_end tells us if we just chop bytes
4544d352ac68SChris Mason  * off the end of the item or if we shift the item to chop bytes off
4545d352ac68SChris Mason  * the front.
4546d352ac68SChris Mason  */
454778ac4f9eSDavid Sterba void btrfs_truncate_item(struct btrfs_path *path, u32 new_size, int from_end)
4548b18c6685SChris Mason {
4549b18c6685SChris Mason 	int slot;
45505f39d397SChris Mason 	struct extent_buffer *leaf;
45515f39d397SChris Mason 	struct btrfs_item *item;
4552b18c6685SChris Mason 	u32 nritems;
4553b18c6685SChris Mason 	unsigned int data_end;
4554b18c6685SChris Mason 	unsigned int old_data_start;
4555b18c6685SChris Mason 	unsigned int old_size;
4556b18c6685SChris Mason 	unsigned int size_diff;
4557b18c6685SChris Mason 	int i;
4558cfed81a0SChris Mason 	struct btrfs_map_token token;
4559cfed81a0SChris Mason 
45605f39d397SChris Mason 	leaf = path->nodes[0];
4561179e29e4SChris Mason 	slot = path->slots[0];
4562179e29e4SChris Mason 
4563179e29e4SChris Mason 	old_size = btrfs_item_size_nr(leaf, slot);
4564179e29e4SChris Mason 	if (old_size == new_size)
4565143bede5SJeff Mahoney 		return;
4566b18c6685SChris Mason 
45675f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
45688f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
4569b18c6685SChris Mason 
45705f39d397SChris Mason 	old_data_start = btrfs_item_offset_nr(leaf, slot);
4571179e29e4SChris Mason 
4572b18c6685SChris Mason 	size_diff = old_size - new_size;
4573b18c6685SChris Mason 
4574b18c6685SChris Mason 	BUG_ON(slot < 0);
4575b18c6685SChris Mason 	BUG_ON(slot >= nritems);
4576b18c6685SChris Mason 
4577b18c6685SChris Mason 	/*
4578b18c6685SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4579b18c6685SChris Mason 	 */
4580b18c6685SChris Mason 	/* first correct the data pointers */
4581c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
4582b18c6685SChris Mason 	for (i = slot; i < nritems; i++) {
45835f39d397SChris Mason 		u32 ioff;
4584dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
4585db94535dSChris Mason 
4586cfed81a0SChris Mason 		ioff = btrfs_token_item_offset(leaf, item, &token);
4587cfed81a0SChris Mason 		btrfs_set_token_item_offset(leaf, item,
4588cfed81a0SChris Mason 					    ioff + size_diff, &token);
4589b18c6685SChris Mason 	}
4590db94535dSChris Mason 
4591b18c6685SChris Mason 	/* shift the data */
4592179e29e4SChris Mason 	if (from_end) {
45933d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
45943d9ec8c4SNikolay Borisov 			      data_end + size_diff, BTRFS_LEAF_DATA_OFFSET +
4595b18c6685SChris Mason 			      data_end, old_data_start + new_size - data_end);
4596179e29e4SChris Mason 	} else {
4597179e29e4SChris Mason 		struct btrfs_disk_key disk_key;
4598179e29e4SChris Mason 		u64 offset;
4599179e29e4SChris Mason 
4600179e29e4SChris Mason 		btrfs_item_key(leaf, &disk_key, slot);
4601179e29e4SChris Mason 
4602179e29e4SChris Mason 		if (btrfs_disk_key_type(&disk_key) == BTRFS_EXTENT_DATA_KEY) {
4603179e29e4SChris Mason 			unsigned long ptr;
4604179e29e4SChris Mason 			struct btrfs_file_extent_item *fi;
4605179e29e4SChris Mason 
4606179e29e4SChris Mason 			fi = btrfs_item_ptr(leaf, slot,
4607179e29e4SChris Mason 					    struct btrfs_file_extent_item);
4608179e29e4SChris Mason 			fi = (struct btrfs_file_extent_item *)(
4609179e29e4SChris Mason 			     (unsigned long)fi - size_diff);
4610179e29e4SChris Mason 
4611179e29e4SChris Mason 			if (btrfs_file_extent_type(leaf, fi) ==
4612179e29e4SChris Mason 			    BTRFS_FILE_EXTENT_INLINE) {
4613179e29e4SChris Mason 				ptr = btrfs_item_ptr_offset(leaf, slot);
4614179e29e4SChris Mason 				memmove_extent_buffer(leaf, ptr,
4615179e29e4SChris Mason 				      (unsigned long)fi,
46167ec20afbSDavid Sterba 				      BTRFS_FILE_EXTENT_INLINE_DATA_START);
4617179e29e4SChris Mason 			}
4618179e29e4SChris Mason 		}
4619179e29e4SChris Mason 
46203d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
46213d9ec8c4SNikolay Borisov 			      data_end + size_diff, BTRFS_LEAF_DATA_OFFSET +
4622179e29e4SChris Mason 			      data_end, old_data_start - data_end);
4623179e29e4SChris Mason 
4624179e29e4SChris Mason 		offset = btrfs_disk_key_offset(&disk_key);
4625179e29e4SChris Mason 		btrfs_set_disk_key_offset(&disk_key, offset + size_diff);
4626179e29e4SChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot);
4627179e29e4SChris Mason 		if (slot == 0)
4628b167fa91SNikolay Borisov 			fixup_low_keys(path, &disk_key, 1);
4629179e29e4SChris Mason 	}
46305f39d397SChris Mason 
4631dd3cc16bSRoss Kirk 	item = btrfs_item_nr(slot);
46325f39d397SChris Mason 	btrfs_set_item_size(leaf, item, new_size);
46335f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
4634b18c6685SChris Mason 
4635e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
4636a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
4637b18c6685SChris Mason 		BUG();
46385f39d397SChris Mason 	}
4639b18c6685SChris Mason }
4640b18c6685SChris Mason 
4641d352ac68SChris Mason /*
46428f69dbd2SStefan Behrens  * make the item pointed to by the path bigger, data_size is the added size.
4643d352ac68SChris Mason  */
4644c71dd880SDavid Sterba void btrfs_extend_item(struct btrfs_path *path, u32 data_size)
46456567e837SChris Mason {
46466567e837SChris Mason 	int slot;
46475f39d397SChris Mason 	struct extent_buffer *leaf;
46485f39d397SChris Mason 	struct btrfs_item *item;
46496567e837SChris Mason 	u32 nritems;
46506567e837SChris Mason 	unsigned int data_end;
46516567e837SChris Mason 	unsigned int old_data;
46526567e837SChris Mason 	unsigned int old_size;
46536567e837SChris Mason 	int i;
4654cfed81a0SChris Mason 	struct btrfs_map_token token;
4655cfed81a0SChris Mason 
46565f39d397SChris Mason 	leaf = path->nodes[0];
46576567e837SChris Mason 
46585f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
46598f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
46606567e837SChris Mason 
4661e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < data_size) {
4662a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
46636567e837SChris Mason 		BUG();
46645f39d397SChris Mason 	}
46656567e837SChris Mason 	slot = path->slots[0];
46665f39d397SChris Mason 	old_data = btrfs_item_end_nr(leaf, slot);
46676567e837SChris Mason 
46686567e837SChris Mason 	BUG_ON(slot < 0);
46693326d1b0SChris Mason 	if (slot >= nritems) {
4670a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
4671c71dd880SDavid Sterba 		btrfs_crit(leaf->fs_info, "slot %d too large, nritems %d",
4672d397712bSChris Mason 			   slot, nritems);
4673290342f6SArnd Bergmann 		BUG();
46743326d1b0SChris Mason 	}
46756567e837SChris Mason 
46766567e837SChris Mason 	/*
46776567e837SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
46786567e837SChris Mason 	 */
46796567e837SChris Mason 	/* first correct the data pointers */
4680c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
46816567e837SChris Mason 	for (i = slot; i < nritems; i++) {
46825f39d397SChris Mason 		u32 ioff;
4683dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
4684db94535dSChris Mason 
4685cfed81a0SChris Mason 		ioff = btrfs_token_item_offset(leaf, item, &token);
4686cfed81a0SChris Mason 		btrfs_set_token_item_offset(leaf, item,
4687cfed81a0SChris Mason 					    ioff - data_size, &token);
46886567e837SChris Mason 	}
46895f39d397SChris Mason 
46906567e837SChris Mason 	/* shift the data */
46913d9ec8c4SNikolay Borisov 	memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
46923d9ec8c4SNikolay Borisov 		      data_end - data_size, BTRFS_LEAF_DATA_OFFSET +
46936567e837SChris Mason 		      data_end, old_data - data_end);
46945f39d397SChris Mason 
46956567e837SChris Mason 	data_end = old_data;
46965f39d397SChris Mason 	old_size = btrfs_item_size_nr(leaf, slot);
4697dd3cc16bSRoss Kirk 	item = btrfs_item_nr(slot);
46985f39d397SChris Mason 	btrfs_set_item_size(leaf, item, old_size + data_size);
46995f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
47006567e837SChris Mason 
4701e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
4702a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
47036567e837SChris Mason 		BUG();
47045f39d397SChris Mason 	}
47056567e837SChris Mason }
47066567e837SChris Mason 
470774123bd7SChris Mason /*
470844871b1bSChris Mason  * this is a helper for btrfs_insert_empty_items, the main goal here is
470944871b1bSChris Mason  * to save stack depth by doing the bulk of the work in a function
471044871b1bSChris Mason  * that doesn't call btrfs_search_slot
471174123bd7SChris Mason  */
4712afe5fea7STsutomu Itoh void setup_items_for_insert(struct btrfs_root *root, struct btrfs_path *path,
4713310712b2SOmar Sandoval 			    const struct btrfs_key *cpu_key, u32 *data_size,
471444871b1bSChris Mason 			    u32 total_data, u32 total_size, int nr)
4715be0e5c09SChris Mason {
47160b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
47175f39d397SChris Mason 	struct btrfs_item *item;
47189c58309dSChris Mason 	int i;
47197518a238SChris Mason 	u32 nritems;
4720be0e5c09SChris Mason 	unsigned int data_end;
4721e2fa7227SChris Mason 	struct btrfs_disk_key disk_key;
472244871b1bSChris Mason 	struct extent_buffer *leaf;
472344871b1bSChris Mason 	int slot;
4724cfed81a0SChris Mason 	struct btrfs_map_token token;
4725cfed81a0SChris Mason 
472624cdc847SFilipe Manana 	if (path->slots[0] == 0) {
472724cdc847SFilipe Manana 		btrfs_cpu_key_to_disk(&disk_key, cpu_key);
4728b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, 1);
472924cdc847SFilipe Manana 	}
473024cdc847SFilipe Manana 	btrfs_unlock_up_safe(path, 1);
473124cdc847SFilipe Manana 
47325f39d397SChris Mason 	leaf = path->nodes[0];
473344871b1bSChris Mason 	slot = path->slots[0];
473474123bd7SChris Mason 
47355f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
47368f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
4737eb60ceacSChris Mason 
4738e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < total_size) {
4739a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
47400b246afaSJeff Mahoney 		btrfs_crit(fs_info, "not enough freespace need %u have %d",
4741e902baacSDavid Sterba 			   total_size, btrfs_leaf_free_space(leaf));
4742be0e5c09SChris Mason 		BUG();
4743d4dbff95SChris Mason 	}
47445f39d397SChris Mason 
4745c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
4746be0e5c09SChris Mason 	if (slot != nritems) {
47475f39d397SChris Mason 		unsigned int old_data = btrfs_item_end_nr(leaf, slot);
4748be0e5c09SChris Mason 
47495f39d397SChris Mason 		if (old_data < data_end) {
4750a4f78750SDavid Sterba 			btrfs_print_leaf(leaf);
47510b246afaSJeff Mahoney 			btrfs_crit(fs_info, "slot %d old_data %d data_end %d",
47525f39d397SChris Mason 				   slot, old_data, data_end);
4753290342f6SArnd Bergmann 			BUG();
47545f39d397SChris Mason 		}
4755be0e5c09SChris Mason 		/*
4756be0e5c09SChris Mason 		 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4757be0e5c09SChris Mason 		 */
4758be0e5c09SChris Mason 		/* first correct the data pointers */
47590783fcfcSChris Mason 		for (i = slot; i < nritems; i++) {
47605f39d397SChris Mason 			u32 ioff;
4761db94535dSChris Mason 
4762dd3cc16bSRoss Kirk 			item = btrfs_item_nr(i);
4763cfed81a0SChris Mason 			ioff = btrfs_token_item_offset(leaf, item, &token);
4764cfed81a0SChris Mason 			btrfs_set_token_item_offset(leaf, item,
4765cfed81a0SChris Mason 						    ioff - total_data, &token);
47660783fcfcSChris Mason 		}
4767be0e5c09SChris Mason 		/* shift the items */
47689c58309dSChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + nr),
47695f39d397SChris Mason 			      btrfs_item_nr_offset(slot),
47700783fcfcSChris Mason 			      (nritems - slot) * sizeof(struct btrfs_item));
4771be0e5c09SChris Mason 
4772be0e5c09SChris Mason 		/* shift the data */
47733d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
47743d9ec8c4SNikolay Borisov 			      data_end - total_data, BTRFS_LEAF_DATA_OFFSET +
4775be0e5c09SChris Mason 			      data_end, old_data - data_end);
4776be0e5c09SChris Mason 		data_end = old_data;
4777be0e5c09SChris Mason 	}
47785f39d397SChris Mason 
477962e2749eSChris Mason 	/* setup the item for the new data */
47809c58309dSChris Mason 	for (i = 0; i < nr; i++) {
47819c58309dSChris Mason 		btrfs_cpu_key_to_disk(&disk_key, cpu_key + i);
47829c58309dSChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot + i);
4783dd3cc16bSRoss Kirk 		item = btrfs_item_nr(slot + i);
4784cfed81a0SChris Mason 		btrfs_set_token_item_offset(leaf, item,
4785cfed81a0SChris Mason 					    data_end - data_size[i], &token);
47869c58309dSChris Mason 		data_end -= data_size[i];
4787cfed81a0SChris Mason 		btrfs_set_token_item_size(leaf, item, data_size[i], &token);
47889c58309dSChris Mason 	}
478944871b1bSChris Mason 
47909c58309dSChris Mason 	btrfs_set_header_nritems(leaf, nritems + nr);
4791b9473439SChris Mason 	btrfs_mark_buffer_dirty(leaf);
4792aa5d6bedSChris Mason 
4793e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
4794a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
4795be0e5c09SChris Mason 		BUG();
47965f39d397SChris Mason 	}
479744871b1bSChris Mason }
479844871b1bSChris Mason 
479944871b1bSChris Mason /*
480044871b1bSChris Mason  * Given a key and some data, insert items into the tree.
480144871b1bSChris Mason  * This does all the path init required, making room in the tree if needed.
480244871b1bSChris Mason  */
480344871b1bSChris Mason int btrfs_insert_empty_items(struct btrfs_trans_handle *trans,
480444871b1bSChris Mason 			    struct btrfs_root *root,
480544871b1bSChris Mason 			    struct btrfs_path *path,
4806310712b2SOmar Sandoval 			    const struct btrfs_key *cpu_key, u32 *data_size,
480744871b1bSChris Mason 			    int nr)
480844871b1bSChris Mason {
480944871b1bSChris Mason 	int ret = 0;
481044871b1bSChris Mason 	int slot;
481144871b1bSChris Mason 	int i;
481244871b1bSChris Mason 	u32 total_size = 0;
481344871b1bSChris Mason 	u32 total_data = 0;
481444871b1bSChris Mason 
481544871b1bSChris Mason 	for (i = 0; i < nr; i++)
481644871b1bSChris Mason 		total_data += data_size[i];
481744871b1bSChris Mason 
481844871b1bSChris Mason 	total_size = total_data + (nr * sizeof(struct btrfs_item));
481944871b1bSChris Mason 	ret = btrfs_search_slot(trans, root, cpu_key, path, total_size, 1);
482044871b1bSChris Mason 	if (ret == 0)
482144871b1bSChris Mason 		return -EEXIST;
482244871b1bSChris Mason 	if (ret < 0)
4823143bede5SJeff Mahoney 		return ret;
482444871b1bSChris Mason 
482544871b1bSChris Mason 	slot = path->slots[0];
482644871b1bSChris Mason 	BUG_ON(slot < 0);
482744871b1bSChris Mason 
4828afe5fea7STsutomu Itoh 	setup_items_for_insert(root, path, cpu_key, data_size,
482944871b1bSChris Mason 			       total_data, total_size, nr);
4830143bede5SJeff Mahoney 	return 0;
483162e2749eSChris Mason }
483262e2749eSChris Mason 
483362e2749eSChris Mason /*
483462e2749eSChris Mason  * Given a key and some data, insert an item into the tree.
483562e2749eSChris Mason  * This does all the path init required, making room in the tree if needed.
483662e2749eSChris Mason  */
4837310712b2SOmar Sandoval int btrfs_insert_item(struct btrfs_trans_handle *trans, struct btrfs_root *root,
4838310712b2SOmar Sandoval 		      const struct btrfs_key *cpu_key, void *data,
4839310712b2SOmar Sandoval 		      u32 data_size)
484062e2749eSChris Mason {
484162e2749eSChris Mason 	int ret = 0;
48422c90e5d6SChris Mason 	struct btrfs_path *path;
48435f39d397SChris Mason 	struct extent_buffer *leaf;
48445f39d397SChris Mason 	unsigned long ptr;
484562e2749eSChris Mason 
48462c90e5d6SChris Mason 	path = btrfs_alloc_path();
4847db5b493aSTsutomu Itoh 	if (!path)
4848db5b493aSTsutomu Itoh 		return -ENOMEM;
48492c90e5d6SChris Mason 	ret = btrfs_insert_empty_item(trans, root, path, cpu_key, data_size);
485062e2749eSChris Mason 	if (!ret) {
48515f39d397SChris Mason 		leaf = path->nodes[0];
48525f39d397SChris Mason 		ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
48535f39d397SChris Mason 		write_extent_buffer(leaf, data, ptr, data_size);
48545f39d397SChris Mason 		btrfs_mark_buffer_dirty(leaf);
485562e2749eSChris Mason 	}
48562c90e5d6SChris Mason 	btrfs_free_path(path);
4857aa5d6bedSChris Mason 	return ret;
4858be0e5c09SChris Mason }
4859be0e5c09SChris Mason 
486074123bd7SChris Mason /*
48615de08d7dSChris Mason  * delete the pointer from a given node.
486274123bd7SChris Mason  *
4863d352ac68SChris Mason  * the tree should have been previously balanced so the deletion does not
4864d352ac68SChris Mason  * empty a node.
486574123bd7SChris Mason  */
4866afe5fea7STsutomu Itoh static void del_ptr(struct btrfs_root *root, struct btrfs_path *path,
4867afe5fea7STsutomu Itoh 		    int level, int slot)
4868be0e5c09SChris Mason {
48695f39d397SChris Mason 	struct extent_buffer *parent = path->nodes[level];
48707518a238SChris Mason 	u32 nritems;
4871f3ea38daSJan Schmidt 	int ret;
4872be0e5c09SChris Mason 
48735f39d397SChris Mason 	nritems = btrfs_header_nritems(parent);
4874be0e5c09SChris Mason 	if (slot != nritems - 1) {
4875bf1d3425SDavid Sterba 		if (level) {
4876bf1d3425SDavid Sterba 			ret = tree_mod_log_insert_move(parent, slot, slot + 1,
4877a446a979SDavid Sterba 					nritems - slot - 1);
4878bf1d3425SDavid Sterba 			BUG_ON(ret < 0);
4879bf1d3425SDavid Sterba 		}
48805f39d397SChris Mason 		memmove_extent_buffer(parent,
48815f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot),
48825f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot + 1),
4883d6025579SChris Mason 			      sizeof(struct btrfs_key_ptr) *
4884d6025579SChris Mason 			      (nritems - slot - 1));
488557ba86c0SChris Mason 	} else if (level) {
4886e09c2efeSDavid Sterba 		ret = tree_mod_log_insert_key(parent, slot, MOD_LOG_KEY_REMOVE,
4887e09c2efeSDavid Sterba 				GFP_NOFS);
488857ba86c0SChris Mason 		BUG_ON(ret < 0);
4889be0e5c09SChris Mason 	}
4890f3ea38daSJan Schmidt 
48917518a238SChris Mason 	nritems--;
48925f39d397SChris Mason 	btrfs_set_header_nritems(parent, nritems);
48937518a238SChris Mason 	if (nritems == 0 && parent == root->node) {
48945f39d397SChris Mason 		BUG_ON(btrfs_header_level(root->node) != 1);
4895eb60ceacSChris Mason 		/* just turn the root into a leaf and break */
48965f39d397SChris Mason 		btrfs_set_header_level(root->node, 0);
4897bb803951SChris Mason 	} else if (slot == 0) {
48985f39d397SChris Mason 		struct btrfs_disk_key disk_key;
48995f39d397SChris Mason 
49005f39d397SChris Mason 		btrfs_node_key(parent, &disk_key, 0);
4901b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, level + 1);
4902be0e5c09SChris Mason 	}
4903d6025579SChris Mason 	btrfs_mark_buffer_dirty(parent);
4904be0e5c09SChris Mason }
4905be0e5c09SChris Mason 
490674123bd7SChris Mason /*
4907323ac95bSChris Mason  * a helper function to delete the leaf pointed to by path->slots[1] and
49085d4f98a2SYan Zheng  * path->nodes[1].
4909323ac95bSChris Mason  *
4910323ac95bSChris Mason  * This deletes the pointer in path->nodes[1] and frees the leaf
4911323ac95bSChris Mason  * block extent.  zero is returned if it all worked out, < 0 otherwise.
4912323ac95bSChris Mason  *
4913323ac95bSChris Mason  * The path must have already been setup for deleting the leaf, including
4914323ac95bSChris Mason  * all the proper balancing.  path->nodes[1] must be locked.
4915323ac95bSChris Mason  */
4916143bede5SJeff Mahoney static noinline void btrfs_del_leaf(struct btrfs_trans_handle *trans,
4917323ac95bSChris Mason 				    struct btrfs_root *root,
49185d4f98a2SYan Zheng 				    struct btrfs_path *path,
49195d4f98a2SYan Zheng 				    struct extent_buffer *leaf)
4920323ac95bSChris Mason {
49215d4f98a2SYan Zheng 	WARN_ON(btrfs_header_generation(leaf) != trans->transid);
4922afe5fea7STsutomu Itoh 	del_ptr(root, path, 1, path->slots[1]);
4923323ac95bSChris Mason 
49244d081c41SChris Mason 	/*
49254d081c41SChris Mason 	 * btrfs_free_extent is expensive, we want to make sure we
49264d081c41SChris Mason 	 * aren't holding any locks when we call it
49274d081c41SChris Mason 	 */
49284d081c41SChris Mason 	btrfs_unlock_up_safe(path, 0);
49294d081c41SChris Mason 
4930f0486c68SYan, Zheng 	root_sub_used(root, leaf->len);
4931f0486c68SYan, Zheng 
493267439dadSDavid Sterba 	atomic_inc(&leaf->refs);
49335581a51aSJan Schmidt 	btrfs_free_tree_block(trans, root, leaf, 0, 1);
49343083ee2eSJosef Bacik 	free_extent_buffer_stale(leaf);
4935323ac95bSChris Mason }
4936323ac95bSChris Mason /*
493774123bd7SChris Mason  * delete the item at the leaf level in path.  If that empties
493874123bd7SChris Mason  * the leaf, remove it from the tree
493974123bd7SChris Mason  */
494085e21bacSChris Mason int btrfs_del_items(struct btrfs_trans_handle *trans, struct btrfs_root *root,
494185e21bacSChris Mason 		    struct btrfs_path *path, int slot, int nr)
4942be0e5c09SChris Mason {
49430b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
49445f39d397SChris Mason 	struct extent_buffer *leaf;
49455f39d397SChris Mason 	struct btrfs_item *item;
4946ce0eac2aSAlexandru Moise 	u32 last_off;
4947ce0eac2aSAlexandru Moise 	u32 dsize = 0;
4948aa5d6bedSChris Mason 	int ret = 0;
4949aa5d6bedSChris Mason 	int wret;
495085e21bacSChris Mason 	int i;
49517518a238SChris Mason 	u32 nritems;
4952be0e5c09SChris Mason 
49535f39d397SChris Mason 	leaf = path->nodes[0];
495485e21bacSChris Mason 	last_off = btrfs_item_offset_nr(leaf, slot + nr - 1);
495585e21bacSChris Mason 
495685e21bacSChris Mason 	for (i = 0; i < nr; i++)
495785e21bacSChris Mason 		dsize += btrfs_item_size_nr(leaf, slot + i);
495885e21bacSChris Mason 
49595f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
4960be0e5c09SChris Mason 
496185e21bacSChris Mason 	if (slot + nr != nritems) {
49628f881e8cSDavid Sterba 		int data_end = leaf_data_end(leaf);
4963c82f823cSDavid Sterba 		struct btrfs_map_token token;
49645f39d397SChris Mason 
49653d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
4966d6025579SChris Mason 			      data_end + dsize,
49673d9ec8c4SNikolay Borisov 			      BTRFS_LEAF_DATA_OFFSET + data_end,
496885e21bacSChris Mason 			      last_off - data_end);
49695f39d397SChris Mason 
4970c82f823cSDavid Sterba 		btrfs_init_map_token(&token, leaf);
497185e21bacSChris Mason 		for (i = slot + nr; i < nritems; i++) {
49725f39d397SChris Mason 			u32 ioff;
4973db94535dSChris Mason 
4974dd3cc16bSRoss Kirk 			item = btrfs_item_nr(i);
4975cfed81a0SChris Mason 			ioff = btrfs_token_item_offset(leaf, item, &token);
4976cfed81a0SChris Mason 			btrfs_set_token_item_offset(leaf, item,
4977cfed81a0SChris Mason 						    ioff + dsize, &token);
49780783fcfcSChris Mason 		}
4979db94535dSChris Mason 
49805f39d397SChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot),
498185e21bacSChris Mason 			      btrfs_item_nr_offset(slot + nr),
49820783fcfcSChris Mason 			      sizeof(struct btrfs_item) *
498385e21bacSChris Mason 			      (nritems - slot - nr));
4984be0e5c09SChris Mason 	}
498585e21bacSChris Mason 	btrfs_set_header_nritems(leaf, nritems - nr);
498685e21bacSChris Mason 	nritems -= nr;
49875f39d397SChris Mason 
498874123bd7SChris Mason 	/* delete the leaf if we've emptied it */
49897518a238SChris Mason 	if (nritems == 0) {
49905f39d397SChris Mason 		if (leaf == root->node) {
49915f39d397SChris Mason 			btrfs_set_header_level(leaf, 0);
49929a8dd150SChris Mason 		} else {
4993f0486c68SYan, Zheng 			btrfs_set_path_blocking(path);
49946a884d7dSDavid Sterba 			btrfs_clean_tree_block(leaf);
4995143bede5SJeff Mahoney 			btrfs_del_leaf(trans, root, path, leaf);
49969a8dd150SChris Mason 		}
4997be0e5c09SChris Mason 	} else {
49987518a238SChris Mason 		int used = leaf_space_used(leaf, 0, nritems);
4999aa5d6bedSChris Mason 		if (slot == 0) {
50005f39d397SChris Mason 			struct btrfs_disk_key disk_key;
50015f39d397SChris Mason 
50025f39d397SChris Mason 			btrfs_item_key(leaf, &disk_key, 0);
5003b167fa91SNikolay Borisov 			fixup_low_keys(path, &disk_key, 1);
5004aa5d6bedSChris Mason 		}
5005aa5d6bedSChris Mason 
500674123bd7SChris Mason 		/* delete the leaf if it is mostly empty */
50070b246afaSJeff Mahoney 		if (used < BTRFS_LEAF_DATA_SIZE(fs_info) / 3) {
5008be0e5c09SChris Mason 			/* push_leaf_left fixes the path.
5009be0e5c09SChris Mason 			 * make sure the path still points to our leaf
5010be0e5c09SChris Mason 			 * for possible call to del_ptr below
5011be0e5c09SChris Mason 			 */
50124920c9acSChris Mason 			slot = path->slots[1];
501367439dadSDavid Sterba 			atomic_inc(&leaf->refs);
50145f39d397SChris Mason 
5015b9473439SChris Mason 			btrfs_set_path_blocking(path);
501699d8f83cSChris Mason 			wret = push_leaf_left(trans, root, path, 1, 1,
501799d8f83cSChris Mason 					      1, (u32)-1);
501854aa1f4dSChris Mason 			if (wret < 0 && wret != -ENOSPC)
5019aa5d6bedSChris Mason 				ret = wret;
50205f39d397SChris Mason 
50215f39d397SChris Mason 			if (path->nodes[0] == leaf &&
50225f39d397SChris Mason 			    btrfs_header_nritems(leaf)) {
502399d8f83cSChris Mason 				wret = push_leaf_right(trans, root, path, 1,
502499d8f83cSChris Mason 						       1, 1, 0);
502554aa1f4dSChris Mason 				if (wret < 0 && wret != -ENOSPC)
5026aa5d6bedSChris Mason 					ret = wret;
5027aa5d6bedSChris Mason 			}
50285f39d397SChris Mason 
50295f39d397SChris Mason 			if (btrfs_header_nritems(leaf) == 0) {
5030323ac95bSChris Mason 				path->slots[1] = slot;
5031143bede5SJeff Mahoney 				btrfs_del_leaf(trans, root, path, leaf);
50325f39d397SChris Mason 				free_extent_buffer(leaf);
5033143bede5SJeff Mahoney 				ret = 0;
50345de08d7dSChris Mason 			} else {
5035925baeddSChris Mason 				/* if we're still in the path, make sure
5036925baeddSChris Mason 				 * we're dirty.  Otherwise, one of the
5037925baeddSChris Mason 				 * push_leaf functions must have already
5038925baeddSChris Mason 				 * dirtied this buffer
5039925baeddSChris Mason 				 */
5040925baeddSChris Mason 				if (path->nodes[0] == leaf)
50415f39d397SChris Mason 					btrfs_mark_buffer_dirty(leaf);
50425f39d397SChris Mason 				free_extent_buffer(leaf);
5043be0e5c09SChris Mason 			}
5044d5719762SChris Mason 		} else {
50455f39d397SChris Mason 			btrfs_mark_buffer_dirty(leaf);
5046be0e5c09SChris Mason 		}
50479a8dd150SChris Mason 	}
5048aa5d6bedSChris Mason 	return ret;
50499a8dd150SChris Mason }
50509a8dd150SChris Mason 
505197571fd0SChris Mason /*
5052925baeddSChris Mason  * search the tree again to find a leaf with lesser keys
50537bb86316SChris Mason  * returns 0 if it found something or 1 if there are no lesser leaves.
50547bb86316SChris Mason  * returns < 0 on io errors.
5055d352ac68SChris Mason  *
5056d352ac68SChris Mason  * This may release the path, and so you may lose any locks held at the
5057d352ac68SChris Mason  * time you call it.
50587bb86316SChris Mason  */
505916e7549fSJosef Bacik int btrfs_prev_leaf(struct btrfs_root *root, struct btrfs_path *path)
50607bb86316SChris Mason {
5061925baeddSChris Mason 	struct btrfs_key key;
5062925baeddSChris Mason 	struct btrfs_disk_key found_key;
5063925baeddSChris Mason 	int ret;
50647bb86316SChris Mason 
5065925baeddSChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, 0);
5066925baeddSChris Mason 
5067e8b0d724SFilipe David Borba Manana 	if (key.offset > 0) {
5068925baeddSChris Mason 		key.offset--;
5069e8b0d724SFilipe David Borba Manana 	} else if (key.type > 0) {
5070925baeddSChris Mason 		key.type--;
5071e8b0d724SFilipe David Borba Manana 		key.offset = (u64)-1;
5072e8b0d724SFilipe David Borba Manana 	} else if (key.objectid > 0) {
5073925baeddSChris Mason 		key.objectid--;
5074e8b0d724SFilipe David Borba Manana 		key.type = (u8)-1;
5075e8b0d724SFilipe David Borba Manana 		key.offset = (u64)-1;
5076e8b0d724SFilipe David Borba Manana 	} else {
50777bb86316SChris Mason 		return 1;
5078e8b0d724SFilipe David Borba Manana 	}
50797bb86316SChris Mason 
5080b3b4aa74SDavid Sterba 	btrfs_release_path(path);
5081925baeddSChris Mason 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5082925baeddSChris Mason 	if (ret < 0)
5083925baeddSChris Mason 		return ret;
5084925baeddSChris Mason 	btrfs_item_key(path->nodes[0], &found_key, 0);
5085925baeddSChris Mason 	ret = comp_keys(&found_key, &key);
5086337c6f68SFilipe Manana 	/*
5087337c6f68SFilipe Manana 	 * We might have had an item with the previous key in the tree right
5088337c6f68SFilipe Manana 	 * before we released our path. And after we released our path, that
5089337c6f68SFilipe Manana 	 * item might have been pushed to the first slot (0) of the leaf we
5090337c6f68SFilipe Manana 	 * were holding due to a tree balance. Alternatively, an item with the
5091337c6f68SFilipe Manana 	 * previous key can exist as the only element of a leaf (big fat item).
5092337c6f68SFilipe Manana 	 * Therefore account for these 2 cases, so that our callers (like
5093337c6f68SFilipe Manana 	 * btrfs_previous_item) don't miss an existing item with a key matching
5094337c6f68SFilipe Manana 	 * the previous key we computed above.
5095337c6f68SFilipe Manana 	 */
5096337c6f68SFilipe Manana 	if (ret <= 0)
50977bb86316SChris Mason 		return 0;
5098925baeddSChris Mason 	return 1;
50997bb86316SChris Mason }
51007bb86316SChris Mason 
51013f157a2fSChris Mason /*
51023f157a2fSChris Mason  * A helper function to walk down the tree starting at min_key, and looking
5103de78b51aSEric Sandeen  * for nodes or leaves that are have a minimum transaction id.
5104de78b51aSEric Sandeen  * This is used by the btree defrag code, and tree logging
51053f157a2fSChris Mason  *
51063f157a2fSChris Mason  * This does not cow, but it does stuff the starting key it finds back
51073f157a2fSChris Mason  * into min_key, so you can call btrfs_search_slot with cow=1 on the
51083f157a2fSChris Mason  * key and get a writable path.
51093f157a2fSChris Mason  *
51103f157a2fSChris Mason  * This honors path->lowest_level to prevent descent past a given level
51113f157a2fSChris Mason  * of the tree.
51123f157a2fSChris Mason  *
5113d352ac68SChris Mason  * min_trans indicates the oldest transaction that you are interested
5114d352ac68SChris Mason  * in walking through.  Any nodes or leaves older than min_trans are
5115d352ac68SChris Mason  * skipped over (without reading them).
5116d352ac68SChris Mason  *
51173f157a2fSChris Mason  * returns zero if something useful was found, < 0 on error and 1 if there
51183f157a2fSChris Mason  * was nothing in the tree that matched the search criteria.
51193f157a2fSChris Mason  */
51203f157a2fSChris Mason int btrfs_search_forward(struct btrfs_root *root, struct btrfs_key *min_key,
5121de78b51aSEric Sandeen 			 struct btrfs_path *path,
51223f157a2fSChris Mason 			 u64 min_trans)
51233f157a2fSChris Mason {
51243f157a2fSChris Mason 	struct extent_buffer *cur;
51253f157a2fSChris Mason 	struct btrfs_key found_key;
51263f157a2fSChris Mason 	int slot;
51279652480bSYan 	int sret;
51283f157a2fSChris Mason 	u32 nritems;
51293f157a2fSChris Mason 	int level;
51303f157a2fSChris Mason 	int ret = 1;
5131f98de9b9SFilipe Manana 	int keep_locks = path->keep_locks;
51323f157a2fSChris Mason 
5133f98de9b9SFilipe Manana 	path->keep_locks = 1;
51343f157a2fSChris Mason again:
5135bd681513SChris Mason 	cur = btrfs_read_lock_root_node(root);
51363f157a2fSChris Mason 	level = btrfs_header_level(cur);
5137e02119d5SChris Mason 	WARN_ON(path->nodes[level]);
51383f157a2fSChris Mason 	path->nodes[level] = cur;
5139bd681513SChris Mason 	path->locks[level] = BTRFS_READ_LOCK;
51403f157a2fSChris Mason 
51413f157a2fSChris Mason 	if (btrfs_header_generation(cur) < min_trans) {
51423f157a2fSChris Mason 		ret = 1;
51433f157a2fSChris Mason 		goto out;
51443f157a2fSChris Mason 	}
51453f157a2fSChris Mason 	while (1) {
51463f157a2fSChris Mason 		nritems = btrfs_header_nritems(cur);
51473f157a2fSChris Mason 		level = btrfs_header_level(cur);
5148a74b35ecSNikolay Borisov 		sret = btrfs_bin_search(cur, min_key, level, &slot);
5149cbca7d59SFilipe Manana 		if (sret < 0) {
5150cbca7d59SFilipe Manana 			ret = sret;
5151cbca7d59SFilipe Manana 			goto out;
5152cbca7d59SFilipe Manana 		}
51533f157a2fSChris Mason 
5154323ac95bSChris Mason 		/* at the lowest level, we're done, setup the path and exit */
5155323ac95bSChris Mason 		if (level == path->lowest_level) {
5156e02119d5SChris Mason 			if (slot >= nritems)
5157e02119d5SChris Mason 				goto find_next_key;
51583f157a2fSChris Mason 			ret = 0;
51593f157a2fSChris Mason 			path->slots[level] = slot;
51603f157a2fSChris Mason 			btrfs_item_key_to_cpu(cur, &found_key, slot);
51613f157a2fSChris Mason 			goto out;
51623f157a2fSChris Mason 		}
51639652480bSYan 		if (sret && slot > 0)
51649652480bSYan 			slot--;
51653f157a2fSChris Mason 		/*
5166de78b51aSEric Sandeen 		 * check this node pointer against the min_trans parameters.
5167de78b51aSEric Sandeen 		 * If it is too old, old, skip to the next one.
51683f157a2fSChris Mason 		 */
51693f157a2fSChris Mason 		while (slot < nritems) {
51703f157a2fSChris Mason 			u64 gen;
5171e02119d5SChris Mason 
51723f157a2fSChris Mason 			gen = btrfs_node_ptr_generation(cur, slot);
51733f157a2fSChris Mason 			if (gen < min_trans) {
51743f157a2fSChris Mason 				slot++;
51753f157a2fSChris Mason 				continue;
51763f157a2fSChris Mason 			}
51773f157a2fSChris Mason 			break;
51783f157a2fSChris Mason 		}
5179e02119d5SChris Mason find_next_key:
51803f157a2fSChris Mason 		/*
51813f157a2fSChris Mason 		 * we didn't find a candidate key in this node, walk forward
51823f157a2fSChris Mason 		 * and find another one
51833f157a2fSChris Mason 		 */
51843f157a2fSChris Mason 		if (slot >= nritems) {
5185e02119d5SChris Mason 			path->slots[level] = slot;
5186b4ce94deSChris Mason 			btrfs_set_path_blocking(path);
5187e02119d5SChris Mason 			sret = btrfs_find_next_key(root, path, min_key, level,
5188de78b51aSEric Sandeen 						  min_trans);
5189e02119d5SChris Mason 			if (sret == 0) {
5190b3b4aa74SDavid Sterba 				btrfs_release_path(path);
51913f157a2fSChris Mason 				goto again;
51923f157a2fSChris Mason 			} else {
51933f157a2fSChris Mason 				goto out;
51943f157a2fSChris Mason 			}
51953f157a2fSChris Mason 		}
51963f157a2fSChris Mason 		/* save our key for returning back */
51973f157a2fSChris Mason 		btrfs_node_key_to_cpu(cur, &found_key, slot);
51983f157a2fSChris Mason 		path->slots[level] = slot;
51993f157a2fSChris Mason 		if (level == path->lowest_level) {
52003f157a2fSChris Mason 			ret = 0;
52013f157a2fSChris Mason 			goto out;
52023f157a2fSChris Mason 		}
5203b4ce94deSChris Mason 		btrfs_set_path_blocking(path);
52044b231ae4SDavid Sterba 		cur = btrfs_read_node_slot(cur, slot);
5205fb770ae4SLiu Bo 		if (IS_ERR(cur)) {
5206fb770ae4SLiu Bo 			ret = PTR_ERR(cur);
5207fb770ae4SLiu Bo 			goto out;
5208fb770ae4SLiu Bo 		}
52093f157a2fSChris Mason 
5210bd681513SChris Mason 		btrfs_tree_read_lock(cur);
5211b4ce94deSChris Mason 
5212bd681513SChris Mason 		path->locks[level - 1] = BTRFS_READ_LOCK;
52133f157a2fSChris Mason 		path->nodes[level - 1] = cur;
5214f7c79f30SChris Mason 		unlock_up(path, level, 1, 0, NULL);
52153f157a2fSChris Mason 	}
52163f157a2fSChris Mason out:
5217f98de9b9SFilipe Manana 	path->keep_locks = keep_locks;
5218f98de9b9SFilipe Manana 	if (ret == 0) {
5219f98de9b9SFilipe Manana 		btrfs_unlock_up_safe(path, path->lowest_level + 1);
5220b4ce94deSChris Mason 		btrfs_set_path_blocking(path);
5221f98de9b9SFilipe Manana 		memcpy(min_key, &found_key, sizeof(found_key));
5222f98de9b9SFilipe Manana 	}
52233f157a2fSChris Mason 	return ret;
52243f157a2fSChris Mason }
52253f157a2fSChris Mason 
52263f157a2fSChris Mason /*
52273f157a2fSChris Mason  * this is similar to btrfs_next_leaf, but does not try to preserve
52283f157a2fSChris Mason  * and fixup the path.  It looks for and returns the next key in the
5229de78b51aSEric Sandeen  * tree based on the current path and the min_trans parameters.
52303f157a2fSChris Mason  *
52313f157a2fSChris Mason  * 0 is returned if another key is found, < 0 if there are any errors
52323f157a2fSChris Mason  * and 1 is returned if there are no higher keys in the tree
52333f157a2fSChris Mason  *
52343f157a2fSChris Mason  * path->keep_locks should be set to 1 on the search made before
52353f157a2fSChris Mason  * calling this function.
52363f157a2fSChris Mason  */
5237e7a84565SChris Mason int btrfs_find_next_key(struct btrfs_root *root, struct btrfs_path *path,
5238de78b51aSEric Sandeen 			struct btrfs_key *key, int level, u64 min_trans)
5239e7a84565SChris Mason {
5240e7a84565SChris Mason 	int slot;
5241e7a84565SChris Mason 	struct extent_buffer *c;
5242e7a84565SChris Mason 
52436a9fb468SJosef Bacik 	WARN_ON(!path->keep_locks && !path->skip_locking);
5244e7a84565SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
5245e7a84565SChris Mason 		if (!path->nodes[level])
5246e7a84565SChris Mason 			return 1;
5247e7a84565SChris Mason 
5248e7a84565SChris Mason 		slot = path->slots[level] + 1;
5249e7a84565SChris Mason 		c = path->nodes[level];
52503f157a2fSChris Mason next:
5251e7a84565SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
525233c66f43SYan Zheng 			int ret;
525333c66f43SYan Zheng 			int orig_lowest;
525433c66f43SYan Zheng 			struct btrfs_key cur_key;
525533c66f43SYan Zheng 			if (level + 1 >= BTRFS_MAX_LEVEL ||
525633c66f43SYan Zheng 			    !path->nodes[level + 1])
5257e7a84565SChris Mason 				return 1;
525833c66f43SYan Zheng 
52596a9fb468SJosef Bacik 			if (path->locks[level + 1] || path->skip_locking) {
526033c66f43SYan Zheng 				level++;
5261e7a84565SChris Mason 				continue;
5262e7a84565SChris Mason 			}
526333c66f43SYan Zheng 
526433c66f43SYan Zheng 			slot = btrfs_header_nritems(c) - 1;
526533c66f43SYan Zheng 			if (level == 0)
526633c66f43SYan Zheng 				btrfs_item_key_to_cpu(c, &cur_key, slot);
526733c66f43SYan Zheng 			else
526833c66f43SYan Zheng 				btrfs_node_key_to_cpu(c, &cur_key, slot);
526933c66f43SYan Zheng 
527033c66f43SYan Zheng 			orig_lowest = path->lowest_level;
5271b3b4aa74SDavid Sterba 			btrfs_release_path(path);
527233c66f43SYan Zheng 			path->lowest_level = level;
527333c66f43SYan Zheng 			ret = btrfs_search_slot(NULL, root, &cur_key, path,
527433c66f43SYan Zheng 						0, 0);
527533c66f43SYan Zheng 			path->lowest_level = orig_lowest;
527633c66f43SYan Zheng 			if (ret < 0)
527733c66f43SYan Zheng 				return ret;
527833c66f43SYan Zheng 
527933c66f43SYan Zheng 			c = path->nodes[level];
528033c66f43SYan Zheng 			slot = path->slots[level];
528133c66f43SYan Zheng 			if (ret == 0)
528233c66f43SYan Zheng 				slot++;
528333c66f43SYan Zheng 			goto next;
528433c66f43SYan Zheng 		}
528533c66f43SYan Zheng 
5286e7a84565SChris Mason 		if (level == 0)
5287e7a84565SChris Mason 			btrfs_item_key_to_cpu(c, key, slot);
52883f157a2fSChris Mason 		else {
52893f157a2fSChris Mason 			u64 gen = btrfs_node_ptr_generation(c, slot);
52903f157a2fSChris Mason 
52913f157a2fSChris Mason 			if (gen < min_trans) {
52923f157a2fSChris Mason 				slot++;
52933f157a2fSChris Mason 				goto next;
52943f157a2fSChris Mason 			}
5295e7a84565SChris Mason 			btrfs_node_key_to_cpu(c, key, slot);
52963f157a2fSChris Mason 		}
5297e7a84565SChris Mason 		return 0;
5298e7a84565SChris Mason 	}
5299e7a84565SChris Mason 	return 1;
5300e7a84565SChris Mason }
5301e7a84565SChris Mason 
53027bb86316SChris Mason /*
5303925baeddSChris Mason  * search the tree again to find a leaf with greater keys
53040f70abe2SChris Mason  * returns 0 if it found something or 1 if there are no greater leaves.
53050f70abe2SChris Mason  * returns < 0 on io errors.
530697571fd0SChris Mason  */
5307234b63a0SChris Mason int btrfs_next_leaf(struct btrfs_root *root, struct btrfs_path *path)
5308d97e63b6SChris Mason {
53093d7806ecSJan Schmidt 	return btrfs_next_old_leaf(root, path, 0);
53103d7806ecSJan Schmidt }
53113d7806ecSJan Schmidt 
53123d7806ecSJan Schmidt int btrfs_next_old_leaf(struct btrfs_root *root, struct btrfs_path *path,
53133d7806ecSJan Schmidt 			u64 time_seq)
53143d7806ecSJan Schmidt {
5315d97e63b6SChris Mason 	int slot;
53168e73f275SChris Mason 	int level;
53175f39d397SChris Mason 	struct extent_buffer *c;
53188e73f275SChris Mason 	struct extent_buffer *next;
5319925baeddSChris Mason 	struct btrfs_key key;
5320925baeddSChris Mason 	u32 nritems;
5321925baeddSChris Mason 	int ret;
53228e73f275SChris Mason 	int old_spinning = path->leave_spinning;
5323bd681513SChris Mason 	int next_rw_lock = 0;
5324925baeddSChris Mason 
5325925baeddSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
5326d397712bSChris Mason 	if (nritems == 0)
5327925baeddSChris Mason 		return 1;
5328925baeddSChris Mason 
53298e73f275SChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, nritems - 1);
53308e73f275SChris Mason again:
53318e73f275SChris Mason 	level = 1;
53328e73f275SChris Mason 	next = NULL;
5333bd681513SChris Mason 	next_rw_lock = 0;
5334b3b4aa74SDavid Sterba 	btrfs_release_path(path);
53358e73f275SChris Mason 
5336a2135011SChris Mason 	path->keep_locks = 1;
53378e73f275SChris Mason 	path->leave_spinning = 1;
53388e73f275SChris Mason 
53393d7806ecSJan Schmidt 	if (time_seq)
53403d7806ecSJan Schmidt 		ret = btrfs_search_old_slot(root, &key, path, time_seq);
53413d7806ecSJan Schmidt 	else
5342925baeddSChris Mason 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5343925baeddSChris Mason 	path->keep_locks = 0;
5344925baeddSChris Mason 
5345925baeddSChris Mason 	if (ret < 0)
5346925baeddSChris Mason 		return ret;
5347925baeddSChris Mason 
5348a2135011SChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
5349168fd7d2SChris Mason 	/*
5350168fd7d2SChris Mason 	 * by releasing the path above we dropped all our locks.  A balance
5351168fd7d2SChris Mason 	 * could have added more items next to the key that used to be
5352168fd7d2SChris Mason 	 * at the very end of the block.  So, check again here and
5353168fd7d2SChris Mason 	 * advance the path if there are now more items available.
5354168fd7d2SChris Mason 	 */
5355a2135011SChris Mason 	if (nritems > 0 && path->slots[0] < nritems - 1) {
5356e457afecSYan Zheng 		if (ret == 0)
5357168fd7d2SChris Mason 			path->slots[0]++;
53588e73f275SChris Mason 		ret = 0;
5359925baeddSChris Mason 		goto done;
5360925baeddSChris Mason 	}
53610b43e04fSLiu Bo 	/*
53620b43e04fSLiu Bo 	 * So the above check misses one case:
53630b43e04fSLiu Bo 	 * - after releasing the path above, someone has removed the item that
53640b43e04fSLiu Bo 	 *   used to be at the very end of the block, and balance between leafs
53650b43e04fSLiu Bo 	 *   gets another one with bigger key.offset to replace it.
53660b43e04fSLiu Bo 	 *
53670b43e04fSLiu Bo 	 * This one should be returned as well, or we can get leaf corruption
53680b43e04fSLiu Bo 	 * later(esp. in __btrfs_drop_extents()).
53690b43e04fSLiu Bo 	 *
53700b43e04fSLiu Bo 	 * And a bit more explanation about this check,
53710b43e04fSLiu Bo 	 * with ret > 0, the key isn't found, the path points to the slot
53720b43e04fSLiu Bo 	 * where it should be inserted, so the path->slots[0] item must be the
53730b43e04fSLiu Bo 	 * bigger one.
53740b43e04fSLiu Bo 	 */
53750b43e04fSLiu Bo 	if (nritems > 0 && ret > 0 && path->slots[0] == nritems - 1) {
53760b43e04fSLiu Bo 		ret = 0;
53770b43e04fSLiu Bo 		goto done;
53780b43e04fSLiu Bo 	}
5379d97e63b6SChris Mason 
5380234b63a0SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
53818e73f275SChris Mason 		if (!path->nodes[level]) {
53828e73f275SChris Mason 			ret = 1;
53838e73f275SChris Mason 			goto done;
53848e73f275SChris Mason 		}
53855f39d397SChris Mason 
5386d97e63b6SChris Mason 		slot = path->slots[level] + 1;
5387d97e63b6SChris Mason 		c = path->nodes[level];
53885f39d397SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
5389d97e63b6SChris Mason 			level++;
53908e73f275SChris Mason 			if (level == BTRFS_MAX_LEVEL) {
53918e73f275SChris Mason 				ret = 1;
53928e73f275SChris Mason 				goto done;
53938e73f275SChris Mason 			}
5394d97e63b6SChris Mason 			continue;
5395d97e63b6SChris Mason 		}
53965f39d397SChris Mason 
5397925baeddSChris Mason 		if (next) {
5398bd681513SChris Mason 			btrfs_tree_unlock_rw(next, next_rw_lock);
53995f39d397SChris Mason 			free_extent_buffer(next);
5400925baeddSChris Mason 		}
54015f39d397SChris Mason 
54028e73f275SChris Mason 		next = c;
5403bd681513SChris Mason 		next_rw_lock = path->locks[level];
5404d07b8528SLiu Bo 		ret = read_block_for_search(root, path, &next, level,
5405cda79c54SDavid Sterba 					    slot, &key);
54068e73f275SChris Mason 		if (ret == -EAGAIN)
54078e73f275SChris Mason 			goto again;
54085f39d397SChris Mason 
540976a05b35SChris Mason 		if (ret < 0) {
5410b3b4aa74SDavid Sterba 			btrfs_release_path(path);
541176a05b35SChris Mason 			goto done;
541276a05b35SChris Mason 		}
541376a05b35SChris Mason 
54145cd57b2cSChris Mason 		if (!path->skip_locking) {
5415bd681513SChris Mason 			ret = btrfs_try_tree_read_lock(next);
5416d42244a0SJan Schmidt 			if (!ret && time_seq) {
5417d42244a0SJan Schmidt 				/*
5418d42244a0SJan Schmidt 				 * If we don't get the lock, we may be racing
5419d42244a0SJan Schmidt 				 * with push_leaf_left, holding that lock while
5420d42244a0SJan Schmidt 				 * itself waiting for the leaf we've currently
5421d42244a0SJan Schmidt 				 * locked. To solve this situation, we give up
5422d42244a0SJan Schmidt 				 * on our lock and cycle.
5423d42244a0SJan Schmidt 				 */
5424cf538830SJan Schmidt 				free_extent_buffer(next);
5425d42244a0SJan Schmidt 				btrfs_release_path(path);
5426d42244a0SJan Schmidt 				cond_resched();
5427d42244a0SJan Schmidt 				goto again;
5428d42244a0SJan Schmidt 			}
54298e73f275SChris Mason 			if (!ret) {
54308e73f275SChris Mason 				btrfs_set_path_blocking(path);
5431bd681513SChris Mason 				btrfs_tree_read_lock(next);
54328e73f275SChris Mason 			}
5433bd681513SChris Mason 			next_rw_lock = BTRFS_READ_LOCK;
5434bd681513SChris Mason 		}
5435d97e63b6SChris Mason 		break;
5436d97e63b6SChris Mason 	}
5437d97e63b6SChris Mason 	path->slots[level] = slot;
5438d97e63b6SChris Mason 	while (1) {
5439d97e63b6SChris Mason 		level--;
5440d97e63b6SChris Mason 		c = path->nodes[level];
5441925baeddSChris Mason 		if (path->locks[level])
5442bd681513SChris Mason 			btrfs_tree_unlock_rw(c, path->locks[level]);
54438e73f275SChris Mason 
54445f39d397SChris Mason 		free_extent_buffer(c);
5445d97e63b6SChris Mason 		path->nodes[level] = next;
5446d97e63b6SChris Mason 		path->slots[level] = 0;
5447a74a4b97SChris Mason 		if (!path->skip_locking)
5448bd681513SChris Mason 			path->locks[level] = next_rw_lock;
5449d97e63b6SChris Mason 		if (!level)
5450d97e63b6SChris Mason 			break;
5451b4ce94deSChris Mason 
5452d07b8528SLiu Bo 		ret = read_block_for_search(root, path, &next, level,
5453cda79c54SDavid Sterba 					    0, &key);
54548e73f275SChris Mason 		if (ret == -EAGAIN)
54558e73f275SChris Mason 			goto again;
54568e73f275SChris Mason 
545776a05b35SChris Mason 		if (ret < 0) {
5458b3b4aa74SDavid Sterba 			btrfs_release_path(path);
545976a05b35SChris Mason 			goto done;
546076a05b35SChris Mason 		}
546176a05b35SChris Mason 
54625cd57b2cSChris Mason 		if (!path->skip_locking) {
5463bd681513SChris Mason 			ret = btrfs_try_tree_read_lock(next);
54648e73f275SChris Mason 			if (!ret) {
54658e73f275SChris Mason 				btrfs_set_path_blocking(path);
5466bd681513SChris Mason 				btrfs_tree_read_lock(next);
54678e73f275SChris Mason 			}
5468bd681513SChris Mason 			next_rw_lock = BTRFS_READ_LOCK;
5469bd681513SChris Mason 		}
5470d97e63b6SChris Mason 	}
54718e73f275SChris Mason 	ret = 0;
5472925baeddSChris Mason done:
5473f7c79f30SChris Mason 	unlock_up(path, 0, 1, 0, NULL);
54748e73f275SChris Mason 	path->leave_spinning = old_spinning;
54758e73f275SChris Mason 	if (!old_spinning)
54768e73f275SChris Mason 		btrfs_set_path_blocking(path);
54778e73f275SChris Mason 
54788e73f275SChris Mason 	return ret;
5479d97e63b6SChris Mason }
54800b86a832SChris Mason 
54813f157a2fSChris Mason /*
54823f157a2fSChris Mason  * this uses btrfs_prev_leaf to walk backwards in the tree, and keeps
54833f157a2fSChris Mason  * searching until it gets past min_objectid or finds an item of 'type'
54843f157a2fSChris Mason  *
54853f157a2fSChris Mason  * returns 0 if something is found, 1 if nothing was found and < 0 on error
54863f157a2fSChris Mason  */
54870b86a832SChris Mason int btrfs_previous_item(struct btrfs_root *root,
54880b86a832SChris Mason 			struct btrfs_path *path, u64 min_objectid,
54890b86a832SChris Mason 			int type)
54900b86a832SChris Mason {
54910b86a832SChris Mason 	struct btrfs_key found_key;
54920b86a832SChris Mason 	struct extent_buffer *leaf;
5493e02119d5SChris Mason 	u32 nritems;
54940b86a832SChris Mason 	int ret;
54950b86a832SChris Mason 
54960b86a832SChris Mason 	while (1) {
54970b86a832SChris Mason 		if (path->slots[0] == 0) {
5498b4ce94deSChris Mason 			btrfs_set_path_blocking(path);
54990b86a832SChris Mason 			ret = btrfs_prev_leaf(root, path);
55000b86a832SChris Mason 			if (ret != 0)
55010b86a832SChris Mason 				return ret;
55020b86a832SChris Mason 		} else {
55030b86a832SChris Mason 			path->slots[0]--;
55040b86a832SChris Mason 		}
55050b86a832SChris Mason 		leaf = path->nodes[0];
5506e02119d5SChris Mason 		nritems = btrfs_header_nritems(leaf);
5507e02119d5SChris Mason 		if (nritems == 0)
5508e02119d5SChris Mason 			return 1;
5509e02119d5SChris Mason 		if (path->slots[0] == nritems)
5510e02119d5SChris Mason 			path->slots[0]--;
5511e02119d5SChris Mason 
55120b86a832SChris Mason 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5513e02119d5SChris Mason 		if (found_key.objectid < min_objectid)
5514e02119d5SChris Mason 			break;
55150a4eefbbSYan Zheng 		if (found_key.type == type)
55160a4eefbbSYan Zheng 			return 0;
5517e02119d5SChris Mason 		if (found_key.objectid == min_objectid &&
5518e02119d5SChris Mason 		    found_key.type < type)
5519e02119d5SChris Mason 			break;
55200b86a832SChris Mason 	}
55210b86a832SChris Mason 	return 1;
55220b86a832SChris Mason }
5523ade2e0b3SWang Shilong 
5524ade2e0b3SWang Shilong /*
5525ade2e0b3SWang Shilong  * search in extent tree to find a previous Metadata/Data extent item with
5526ade2e0b3SWang Shilong  * min objecitd.
5527ade2e0b3SWang Shilong  *
5528ade2e0b3SWang Shilong  * returns 0 if something is found, 1 if nothing was found and < 0 on error
5529ade2e0b3SWang Shilong  */
5530ade2e0b3SWang Shilong int btrfs_previous_extent_item(struct btrfs_root *root,
5531ade2e0b3SWang Shilong 			struct btrfs_path *path, u64 min_objectid)
5532ade2e0b3SWang Shilong {
5533ade2e0b3SWang Shilong 	struct btrfs_key found_key;
5534ade2e0b3SWang Shilong 	struct extent_buffer *leaf;
5535ade2e0b3SWang Shilong 	u32 nritems;
5536ade2e0b3SWang Shilong 	int ret;
5537ade2e0b3SWang Shilong 
5538ade2e0b3SWang Shilong 	while (1) {
5539ade2e0b3SWang Shilong 		if (path->slots[0] == 0) {
5540ade2e0b3SWang Shilong 			btrfs_set_path_blocking(path);
5541ade2e0b3SWang Shilong 			ret = btrfs_prev_leaf(root, path);
5542ade2e0b3SWang Shilong 			if (ret != 0)
5543ade2e0b3SWang Shilong 				return ret;
5544ade2e0b3SWang Shilong 		} else {
5545ade2e0b3SWang Shilong 			path->slots[0]--;
5546ade2e0b3SWang Shilong 		}
5547ade2e0b3SWang Shilong 		leaf = path->nodes[0];
5548ade2e0b3SWang Shilong 		nritems = btrfs_header_nritems(leaf);
5549ade2e0b3SWang Shilong 		if (nritems == 0)
5550ade2e0b3SWang Shilong 			return 1;
5551ade2e0b3SWang Shilong 		if (path->slots[0] == nritems)
5552ade2e0b3SWang Shilong 			path->slots[0]--;
5553ade2e0b3SWang Shilong 
5554ade2e0b3SWang Shilong 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5555ade2e0b3SWang Shilong 		if (found_key.objectid < min_objectid)
5556ade2e0b3SWang Shilong 			break;
5557ade2e0b3SWang Shilong 		if (found_key.type == BTRFS_EXTENT_ITEM_KEY ||
5558ade2e0b3SWang Shilong 		    found_key.type == BTRFS_METADATA_ITEM_KEY)
5559ade2e0b3SWang Shilong 			return 0;
5560ade2e0b3SWang Shilong 		if (found_key.objectid == min_objectid &&
5561ade2e0b3SWang Shilong 		    found_key.type < BTRFS_EXTENT_ITEM_KEY)
5562ade2e0b3SWang Shilong 			break;
5563ade2e0b3SWang Shilong 	}
5564ade2e0b3SWang Shilong 	return 1;
5565ade2e0b3SWang Shilong }
5566