xref: /openbmc/linux/fs/btrfs/ctree.c (revision 206983b7)
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;
3459a0fcdbSDavid Sterba 	const char	name[10];
3559a0fcdbSDavid Sterba 	const char	driver[12];
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 */
6659a0fcdbSDavid Sterba 	return btrfs_csums[csum_type].driver[0] ?
6759a0fcdbSDavid Sterba 		btrfs_csums[csum_type].driver :
68b4e967beSDavid Sterba 		btrfs_csums[csum_type].name;
69b4e967beSDavid Sterba }
70b4e967beSDavid Sterba 
71604997b4SDavid Sterba size_t __attribute_const__ btrfs_get_num_csums(void)
72f7cea56cSDavid Sterba {
73f7cea56cSDavid Sterba 	return ARRAY_SIZE(btrfs_csums);
74f7cea56cSDavid Sterba }
75f7cea56cSDavid Sterba 
762c90e5d6SChris Mason struct btrfs_path *btrfs_alloc_path(void)
772c90e5d6SChris Mason {
78e2c89907SMasahiro Yamada 	return kmem_cache_zalloc(btrfs_path_cachep, GFP_NOFS);
792c90e5d6SChris Mason }
802c90e5d6SChris Mason 
81d352ac68SChris Mason /* this also releases the path */
822c90e5d6SChris Mason void btrfs_free_path(struct btrfs_path *p)
832c90e5d6SChris Mason {
84ff175d57SJesper Juhl 	if (!p)
85ff175d57SJesper Juhl 		return;
86b3b4aa74SDavid Sterba 	btrfs_release_path(p);
872c90e5d6SChris Mason 	kmem_cache_free(btrfs_path_cachep, p);
882c90e5d6SChris Mason }
892c90e5d6SChris Mason 
90d352ac68SChris Mason /*
91d352ac68SChris Mason  * path release drops references on the extent buffers in the path
92d352ac68SChris Mason  * and it drops any locks held by this path
93d352ac68SChris Mason  *
94d352ac68SChris Mason  * It is safe to call this on paths that no locks or extent buffers held.
95d352ac68SChris Mason  */
96b3b4aa74SDavid Sterba noinline void btrfs_release_path(struct btrfs_path *p)
97eb60ceacSChris Mason {
98eb60ceacSChris Mason 	int i;
99a2135011SChris Mason 
100234b63a0SChris Mason 	for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
1013f157a2fSChris Mason 		p->slots[i] = 0;
102eb60ceacSChris Mason 		if (!p->nodes[i])
103925baeddSChris Mason 			continue;
104925baeddSChris Mason 		if (p->locks[i]) {
105bd681513SChris Mason 			btrfs_tree_unlock_rw(p->nodes[i], p->locks[i]);
106925baeddSChris Mason 			p->locks[i] = 0;
107925baeddSChris Mason 		}
1085f39d397SChris Mason 		free_extent_buffer(p->nodes[i]);
1093f157a2fSChris Mason 		p->nodes[i] = NULL;
110eb60ceacSChris Mason 	}
111eb60ceacSChris Mason }
112eb60ceacSChris Mason 
113d352ac68SChris Mason /*
114d352ac68SChris Mason  * safely gets a reference on the root node of a tree.  A lock
115d352ac68SChris Mason  * is not taken, so a concurrent writer may put a different node
116d352ac68SChris Mason  * at the root of the tree.  See btrfs_lock_root_node for the
117d352ac68SChris Mason  * looping required.
118d352ac68SChris Mason  *
119d352ac68SChris Mason  * The extent buffer returned by this has a reference taken, so
120d352ac68SChris Mason  * it won't disappear.  It may stop being the root of the tree
121d352ac68SChris Mason  * at any time because there are no locks held.
122d352ac68SChris Mason  */
123925baeddSChris Mason struct extent_buffer *btrfs_root_node(struct btrfs_root *root)
124925baeddSChris Mason {
125925baeddSChris Mason 	struct extent_buffer *eb;
126240f62c8SChris Mason 
1273083ee2eSJosef Bacik 	while (1) {
128240f62c8SChris Mason 		rcu_read_lock();
129240f62c8SChris Mason 		eb = rcu_dereference(root->node);
1303083ee2eSJosef Bacik 
1313083ee2eSJosef Bacik 		/*
1323083ee2eSJosef Bacik 		 * RCU really hurts here, we could free up the root node because
13301327610SNicholas D Steeves 		 * it was COWed but we may not get the new root node yet so do
1343083ee2eSJosef Bacik 		 * the inc_not_zero dance and if it doesn't work then
1353083ee2eSJosef Bacik 		 * synchronize_rcu and try again.
1363083ee2eSJosef Bacik 		 */
1373083ee2eSJosef Bacik 		if (atomic_inc_not_zero(&eb->refs)) {
138240f62c8SChris Mason 			rcu_read_unlock();
1393083ee2eSJosef Bacik 			break;
1403083ee2eSJosef Bacik 		}
1413083ee2eSJosef Bacik 		rcu_read_unlock();
1423083ee2eSJosef Bacik 		synchronize_rcu();
1433083ee2eSJosef Bacik 	}
144925baeddSChris Mason 	return eb;
145925baeddSChris Mason }
146925baeddSChris Mason 
14792a7cc42SQu Wenruo /*
14892a7cc42SQu Wenruo  * Cowonly root (not-shareable trees, everything not subvolume or reloc roots),
14992a7cc42SQu Wenruo  * just get put onto a simple dirty list.  Transaction walks this list to make
15092a7cc42SQu Wenruo  * sure they get properly updated on disk.
151d352ac68SChris Mason  */
1520b86a832SChris Mason static void add_root_to_dirty_list(struct btrfs_root *root)
1530b86a832SChris Mason {
1540b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
1550b246afaSJeff Mahoney 
156e7070be1SJosef Bacik 	if (test_bit(BTRFS_ROOT_DIRTY, &root->state) ||
157e7070be1SJosef Bacik 	    !test_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state))
158e7070be1SJosef Bacik 		return;
159e7070be1SJosef Bacik 
1600b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
161e7070be1SJosef Bacik 	if (!test_and_set_bit(BTRFS_ROOT_DIRTY, &root->state)) {
162e7070be1SJosef Bacik 		/* Want the extent tree to be the last on the list */
1634fd786e6SMisono Tomohiro 		if (root->root_key.objectid == BTRFS_EXTENT_TREE_OBJECTID)
164e7070be1SJosef Bacik 			list_move_tail(&root->dirty_list,
1650b246afaSJeff Mahoney 				       &fs_info->dirty_cowonly_roots);
166e7070be1SJosef Bacik 		else
167e7070be1SJosef Bacik 			list_move(&root->dirty_list,
1680b246afaSJeff Mahoney 				  &fs_info->dirty_cowonly_roots);
1690b86a832SChris Mason 	}
1700b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
1710b86a832SChris Mason }
1720b86a832SChris Mason 
173d352ac68SChris Mason /*
174d352ac68SChris Mason  * used by snapshot creation to make a copy of a root for a tree with
175d352ac68SChris Mason  * a given objectid.  The buffer with the new root node is returned in
176d352ac68SChris Mason  * cow_ret, and this func returns zero on success or a negative error code.
177d352ac68SChris Mason  */
178be20aa9dSChris Mason int btrfs_copy_root(struct btrfs_trans_handle *trans,
179be20aa9dSChris Mason 		      struct btrfs_root *root,
180be20aa9dSChris Mason 		      struct extent_buffer *buf,
181be20aa9dSChris Mason 		      struct extent_buffer **cow_ret, u64 new_root_objectid)
182be20aa9dSChris Mason {
1830b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
184be20aa9dSChris Mason 	struct extent_buffer *cow;
185be20aa9dSChris Mason 	int ret = 0;
186be20aa9dSChris Mason 	int level;
1875d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
188be20aa9dSChris Mason 
18992a7cc42SQu Wenruo 	WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
1900b246afaSJeff Mahoney 		trans->transid != fs_info->running_transaction->transid);
19192a7cc42SQu Wenruo 	WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
19227cdeb70SMiao Xie 		trans->transid != root->last_trans);
193be20aa9dSChris Mason 
194be20aa9dSChris Mason 	level = btrfs_header_level(buf);
1955d4f98a2SYan Zheng 	if (level == 0)
1965d4f98a2SYan Zheng 		btrfs_item_key(buf, &disk_key, 0);
1975d4f98a2SYan Zheng 	else
1985d4f98a2SYan Zheng 		btrfs_node_key(buf, &disk_key, 0);
19931840ae1SZheng Yan 
2004d75f8a9SDavid Sterba 	cow = btrfs_alloc_tree_block(trans, root, 0, new_root_objectid,
201cf6f34aaSJosef Bacik 				     &disk_key, level, buf->start, 0,
202cf6f34aaSJosef Bacik 				     BTRFS_NESTING_NEW_ROOT);
2035d4f98a2SYan Zheng 	if (IS_ERR(cow))
204be20aa9dSChris Mason 		return PTR_ERR(cow);
205be20aa9dSChris Mason 
20658e8012cSDavid Sterba 	copy_extent_buffer_full(cow, buf);
207be20aa9dSChris Mason 	btrfs_set_header_bytenr(cow, cow->start);
208be20aa9dSChris Mason 	btrfs_set_header_generation(cow, trans->transid);
2095d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
2105d4f98a2SYan Zheng 	btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
2115d4f98a2SYan Zheng 				     BTRFS_HEADER_FLAG_RELOC);
2125d4f98a2SYan Zheng 	if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
2135d4f98a2SYan Zheng 		btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
2145d4f98a2SYan Zheng 	else
215be20aa9dSChris Mason 		btrfs_set_header_owner(cow, new_root_objectid);
216be20aa9dSChris Mason 
217de37aa51SNikolay Borisov 	write_extent_buffer_fsid(cow, fs_info->fs_devices->metadata_uuid);
2182b82032cSYan Zheng 
219be20aa9dSChris Mason 	WARN_ON(btrfs_header_generation(buf) > trans->transid);
2205d4f98a2SYan Zheng 	if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
221e339a6b0SJosef Bacik 		ret = btrfs_inc_ref(trans, root, cow, 1);
2225d4f98a2SYan Zheng 	else
223e339a6b0SJosef Bacik 		ret = btrfs_inc_ref(trans, root, cow, 0);
2244aec2b52SChris Mason 
225be20aa9dSChris Mason 	if (ret)
226be20aa9dSChris Mason 		return ret;
227be20aa9dSChris Mason 
228be20aa9dSChris Mason 	btrfs_mark_buffer_dirty(cow);
229be20aa9dSChris Mason 	*cow_ret = cow;
230be20aa9dSChris Mason 	return 0;
231be20aa9dSChris Mason }
232be20aa9dSChris Mason 
233bd989ba3SJan Schmidt enum mod_log_op {
234bd989ba3SJan Schmidt 	MOD_LOG_KEY_REPLACE,
235bd989ba3SJan Schmidt 	MOD_LOG_KEY_ADD,
236bd989ba3SJan Schmidt 	MOD_LOG_KEY_REMOVE,
237bd989ba3SJan Schmidt 	MOD_LOG_KEY_REMOVE_WHILE_FREEING,
238bd989ba3SJan Schmidt 	MOD_LOG_KEY_REMOVE_WHILE_MOVING,
239bd989ba3SJan Schmidt 	MOD_LOG_MOVE_KEYS,
240bd989ba3SJan Schmidt 	MOD_LOG_ROOT_REPLACE,
241bd989ba3SJan Schmidt };
242bd989ba3SJan Schmidt 
243bd989ba3SJan Schmidt struct tree_mod_root {
244bd989ba3SJan Schmidt 	u64 logical;
245bd989ba3SJan Schmidt 	u8 level;
246bd989ba3SJan Schmidt };
247bd989ba3SJan Schmidt 
248bd989ba3SJan Schmidt struct tree_mod_elem {
249bd989ba3SJan Schmidt 	struct rb_node node;
250298cfd36SChandan Rajendra 	u64 logical;
251097b8a7cSJan Schmidt 	u64 seq;
252bd989ba3SJan Schmidt 	enum mod_log_op op;
253bd989ba3SJan Schmidt 
254bd989ba3SJan Schmidt 	/* this is used for MOD_LOG_KEY_* and MOD_LOG_MOVE_KEYS operations */
255bd989ba3SJan Schmidt 	int slot;
256bd989ba3SJan Schmidt 
257bd989ba3SJan Schmidt 	/* this is used for MOD_LOG_KEY* and MOD_LOG_ROOT_REPLACE */
258bd989ba3SJan Schmidt 	u64 generation;
259bd989ba3SJan Schmidt 
260bd989ba3SJan Schmidt 	/* those are used for op == MOD_LOG_KEY_{REPLACE,REMOVE} */
261bd989ba3SJan Schmidt 	struct btrfs_disk_key key;
262bd989ba3SJan Schmidt 	u64 blockptr;
263bd989ba3SJan Schmidt 
264bd989ba3SJan Schmidt 	/* this is used for op == MOD_LOG_MOVE_KEYS */
265b6dfa35bSDavid Sterba 	struct {
266b6dfa35bSDavid Sterba 		int dst_slot;
267b6dfa35bSDavid Sterba 		int nr_items;
268b6dfa35bSDavid Sterba 	} move;
269bd989ba3SJan Schmidt 
270bd989ba3SJan Schmidt 	/* this is used for op == MOD_LOG_ROOT_REPLACE */
271bd989ba3SJan Schmidt 	struct tree_mod_root old_root;
272bd989ba3SJan Schmidt };
273bd989ba3SJan Schmidt 
274097b8a7cSJan Schmidt /*
275fcebe456SJosef Bacik  * Pull a new tree mod seq number for our operation.
276fc36ed7eSJan Schmidt  */
277fcebe456SJosef Bacik static inline u64 btrfs_inc_tree_mod_seq(struct btrfs_fs_info *fs_info)
278fc36ed7eSJan Schmidt {
279fc36ed7eSJan Schmidt 	return atomic64_inc_return(&fs_info->tree_mod_seq);
280fc36ed7eSJan Schmidt }
281fc36ed7eSJan Schmidt 
282fc36ed7eSJan Schmidt /*
283097b8a7cSJan Schmidt  * This adds a new blocker to the tree mod log's blocker list if the @elem
284097b8a7cSJan Schmidt  * passed does not already have a sequence number set. So when a caller expects
285097b8a7cSJan Schmidt  * to record tree modifications, it should ensure to set elem->seq to zero
286097b8a7cSJan Schmidt  * before calling btrfs_get_tree_mod_seq.
287097b8a7cSJan Schmidt  * Returns a fresh, unused tree log modification sequence number, even if no new
288097b8a7cSJan Schmidt  * blocker was added.
289097b8a7cSJan Schmidt  */
290097b8a7cSJan Schmidt u64 btrfs_get_tree_mod_seq(struct btrfs_fs_info *fs_info,
291bd989ba3SJan Schmidt 			   struct seq_list *elem)
292bd989ba3SJan Schmidt {
293b1a09f1eSDavid Sterba 	write_lock(&fs_info->tree_mod_log_lock);
294097b8a7cSJan Schmidt 	if (!elem->seq) {
295fcebe456SJosef Bacik 		elem->seq = btrfs_inc_tree_mod_seq(fs_info);
296097b8a7cSJan Schmidt 		list_add_tail(&elem->list, &fs_info->tree_mod_seq_list);
297097b8a7cSJan Schmidt 	}
298b1a09f1eSDavid Sterba 	write_unlock(&fs_info->tree_mod_log_lock);
299097b8a7cSJan Schmidt 
300fcebe456SJosef Bacik 	return elem->seq;
301bd989ba3SJan Schmidt }
302bd989ba3SJan Schmidt 
303bd989ba3SJan Schmidt void btrfs_put_tree_mod_seq(struct btrfs_fs_info *fs_info,
304bd989ba3SJan Schmidt 			    struct seq_list *elem)
305bd989ba3SJan Schmidt {
306bd989ba3SJan Schmidt 	struct rb_root *tm_root;
307bd989ba3SJan Schmidt 	struct rb_node *node;
308bd989ba3SJan Schmidt 	struct rb_node *next;
309bd989ba3SJan Schmidt 	struct tree_mod_elem *tm;
310bd989ba3SJan Schmidt 	u64 min_seq = (u64)-1;
311bd989ba3SJan Schmidt 	u64 seq_putting = elem->seq;
312bd989ba3SJan Schmidt 
313bd989ba3SJan Schmidt 	if (!seq_putting)
314bd989ba3SJan Schmidt 		return;
315bd989ba3SJan Schmidt 
3167227ff4dSFilipe Manana 	write_lock(&fs_info->tree_mod_log_lock);
317bd989ba3SJan Schmidt 	list_del(&elem->list);
318097b8a7cSJan Schmidt 	elem->seq = 0;
319bd989ba3SJan Schmidt 
32042836cf4SFilipe Manana 	if (!list_empty(&fs_info->tree_mod_seq_list)) {
32142836cf4SFilipe Manana 		struct seq_list *first;
32242836cf4SFilipe Manana 
32342836cf4SFilipe Manana 		first = list_first_entry(&fs_info->tree_mod_seq_list,
32442836cf4SFilipe Manana 					 struct seq_list, list);
32542836cf4SFilipe Manana 		if (seq_putting > first->seq) {
326bd989ba3SJan Schmidt 			/*
32742836cf4SFilipe Manana 			 * Blocker with lower sequence number exists, we
32842836cf4SFilipe Manana 			 * cannot remove anything from the log.
329bd989ba3SJan Schmidt 			 */
3307227ff4dSFilipe Manana 			write_unlock(&fs_info->tree_mod_log_lock);
331097b8a7cSJan Schmidt 			return;
332bd989ba3SJan Schmidt 		}
33342836cf4SFilipe Manana 		min_seq = first->seq;
334bd989ba3SJan Schmidt 	}
335097b8a7cSJan Schmidt 
336097b8a7cSJan Schmidt 	/*
337bd989ba3SJan Schmidt 	 * anything that's lower than the lowest existing (read: blocked)
338bd989ba3SJan Schmidt 	 * sequence number can be removed from the tree.
339bd989ba3SJan Schmidt 	 */
340bd989ba3SJan Schmidt 	tm_root = &fs_info->tree_mod_log;
341bd989ba3SJan Schmidt 	for (node = rb_first(tm_root); node; node = next) {
342bd989ba3SJan Schmidt 		next = rb_next(node);
3436b4df8b6SGeliang Tang 		tm = rb_entry(node, struct tree_mod_elem, node);
3446609fee8SFilipe Manana 		if (tm->seq >= min_seq)
345bd989ba3SJan Schmidt 			continue;
346bd989ba3SJan Schmidt 		rb_erase(node, tm_root);
347bd989ba3SJan Schmidt 		kfree(tm);
348bd989ba3SJan Schmidt 	}
349b1a09f1eSDavid Sterba 	write_unlock(&fs_info->tree_mod_log_lock);
350bd989ba3SJan Schmidt }
351bd989ba3SJan Schmidt 
352bd989ba3SJan Schmidt /*
353bd989ba3SJan Schmidt  * key order of the log:
354298cfd36SChandan Rajendra  *       node/leaf start address -> sequence
355bd989ba3SJan Schmidt  *
356298cfd36SChandan Rajendra  * The 'start address' is the logical address of the *new* root node
357298cfd36SChandan Rajendra  * for root replace operations, or the logical address of the affected
358298cfd36SChandan Rajendra  * block for all other operations.
359bd989ba3SJan Schmidt  */
360bd989ba3SJan Schmidt static noinline int
361bd989ba3SJan Schmidt __tree_mod_log_insert(struct btrfs_fs_info *fs_info, struct tree_mod_elem *tm)
362bd989ba3SJan Schmidt {
363bd989ba3SJan Schmidt 	struct rb_root *tm_root;
364bd989ba3SJan Schmidt 	struct rb_node **new;
365bd989ba3SJan Schmidt 	struct rb_node *parent = NULL;
366bd989ba3SJan Schmidt 	struct tree_mod_elem *cur;
367bd989ba3SJan Schmidt 
36873e82fe4SDavid Sterba 	lockdep_assert_held_write(&fs_info->tree_mod_log_lock);
36973e82fe4SDavid Sterba 
370fcebe456SJosef Bacik 	tm->seq = btrfs_inc_tree_mod_seq(fs_info);
371bd989ba3SJan Schmidt 
372bd989ba3SJan Schmidt 	tm_root = &fs_info->tree_mod_log;
373bd989ba3SJan Schmidt 	new = &tm_root->rb_node;
374bd989ba3SJan Schmidt 	while (*new) {
3756b4df8b6SGeliang Tang 		cur = rb_entry(*new, struct tree_mod_elem, node);
376bd989ba3SJan Schmidt 		parent = *new;
377298cfd36SChandan Rajendra 		if (cur->logical < tm->logical)
378bd989ba3SJan Schmidt 			new = &((*new)->rb_left);
379298cfd36SChandan Rajendra 		else if (cur->logical > tm->logical)
380bd989ba3SJan Schmidt 			new = &((*new)->rb_right);
381097b8a7cSJan Schmidt 		else if (cur->seq < tm->seq)
382bd989ba3SJan Schmidt 			new = &((*new)->rb_left);
383097b8a7cSJan Schmidt 		else if (cur->seq > tm->seq)
384bd989ba3SJan Schmidt 			new = &((*new)->rb_right);
3855de865eeSFilipe David Borba Manana 		else
3865de865eeSFilipe David Borba Manana 			return -EEXIST;
387bd989ba3SJan Schmidt 	}
388bd989ba3SJan Schmidt 
389bd989ba3SJan Schmidt 	rb_link_node(&tm->node, parent, new);
390bd989ba3SJan Schmidt 	rb_insert_color(&tm->node, tm_root);
3915de865eeSFilipe David Borba Manana 	return 0;
392bd989ba3SJan Schmidt }
393bd989ba3SJan Schmidt 
394097b8a7cSJan Schmidt /*
395097b8a7cSJan Schmidt  * Determines if logging can be omitted. Returns 1 if it can. Otherwise, it
396097b8a7cSJan Schmidt  * returns zero with the tree_mod_log_lock acquired. The caller must hold
397097b8a7cSJan Schmidt  * this until all tree mod log insertions are recorded in the rb tree and then
398b1a09f1eSDavid Sterba  * write unlock fs_info::tree_mod_log_lock.
399097b8a7cSJan Schmidt  */
400e9b7fd4dSJan Schmidt static inline int tree_mod_dont_log(struct btrfs_fs_info *fs_info,
401e9b7fd4dSJan Schmidt 				    struct extent_buffer *eb) {
402e9b7fd4dSJan Schmidt 	smp_mb();
403e9b7fd4dSJan Schmidt 	if (list_empty(&(fs_info)->tree_mod_seq_list))
404e9b7fd4dSJan Schmidt 		return 1;
405097b8a7cSJan Schmidt 	if (eb && btrfs_header_level(eb) == 0)
406e9b7fd4dSJan Schmidt 		return 1;
4075de865eeSFilipe David Borba Manana 
408b1a09f1eSDavid Sterba 	write_lock(&fs_info->tree_mod_log_lock);
4095de865eeSFilipe David Borba Manana 	if (list_empty(&(fs_info)->tree_mod_seq_list)) {
410b1a09f1eSDavid Sterba 		write_unlock(&fs_info->tree_mod_log_lock);
4115de865eeSFilipe David Borba Manana 		return 1;
4125de865eeSFilipe David Borba Manana 	}
4135de865eeSFilipe David Borba Manana 
414e9b7fd4dSJan Schmidt 	return 0;
415e9b7fd4dSJan Schmidt }
416e9b7fd4dSJan Schmidt 
4175de865eeSFilipe David Borba Manana /* Similar to tree_mod_dont_log, but doesn't acquire any locks. */
4185de865eeSFilipe David Borba Manana static inline int tree_mod_need_log(const struct btrfs_fs_info *fs_info,
4195de865eeSFilipe David Borba Manana 				    struct extent_buffer *eb)
4205de865eeSFilipe David Borba Manana {
4215de865eeSFilipe David Borba Manana 	smp_mb();
4225de865eeSFilipe David Borba Manana 	if (list_empty(&(fs_info)->tree_mod_seq_list))
4235de865eeSFilipe David Borba Manana 		return 0;
4245de865eeSFilipe David Borba Manana 	if (eb && btrfs_header_level(eb) == 0)
4255de865eeSFilipe David Borba Manana 		return 0;
4265de865eeSFilipe David Borba Manana 
4275de865eeSFilipe David Borba Manana 	return 1;
4285de865eeSFilipe David Borba Manana }
4295de865eeSFilipe David Borba Manana 
4305de865eeSFilipe David Borba Manana static struct tree_mod_elem *
4315de865eeSFilipe David Borba Manana alloc_tree_mod_elem(struct extent_buffer *eb, int slot,
432bd989ba3SJan Schmidt 		    enum mod_log_op op, gfp_t flags)
433bd989ba3SJan Schmidt {
434097b8a7cSJan Schmidt 	struct tree_mod_elem *tm;
435bd989ba3SJan Schmidt 
436c8cc6341SJosef Bacik 	tm = kzalloc(sizeof(*tm), flags);
437c8cc6341SJosef Bacik 	if (!tm)
4385de865eeSFilipe David Borba Manana 		return NULL;
439bd989ba3SJan Schmidt 
440298cfd36SChandan Rajendra 	tm->logical = eb->start;
441bd989ba3SJan Schmidt 	if (op != MOD_LOG_KEY_ADD) {
442bd989ba3SJan Schmidt 		btrfs_node_key(eb, &tm->key, slot);
443bd989ba3SJan Schmidt 		tm->blockptr = btrfs_node_blockptr(eb, slot);
444bd989ba3SJan Schmidt 	}
445bd989ba3SJan Schmidt 	tm->op = op;
446bd989ba3SJan Schmidt 	tm->slot = slot;
447bd989ba3SJan Schmidt 	tm->generation = btrfs_node_ptr_generation(eb, slot);
4485de865eeSFilipe David Borba Manana 	RB_CLEAR_NODE(&tm->node);
449bd989ba3SJan Schmidt 
4505de865eeSFilipe David Borba Manana 	return tm;
451097b8a7cSJan Schmidt }
452097b8a7cSJan Schmidt 
453e09c2efeSDavid Sterba static noinline int tree_mod_log_insert_key(struct extent_buffer *eb, int slot,
454097b8a7cSJan Schmidt 		enum mod_log_op op, gfp_t flags)
455097b8a7cSJan Schmidt {
4565de865eeSFilipe David Borba Manana 	struct tree_mod_elem *tm;
4575de865eeSFilipe David Borba Manana 	int ret;
4585de865eeSFilipe David Borba Manana 
459e09c2efeSDavid Sterba 	if (!tree_mod_need_log(eb->fs_info, eb))
460097b8a7cSJan Schmidt 		return 0;
461097b8a7cSJan Schmidt 
4625de865eeSFilipe David Borba Manana 	tm = alloc_tree_mod_elem(eb, slot, op, flags);
4635de865eeSFilipe David Borba Manana 	if (!tm)
4645de865eeSFilipe David Borba Manana 		return -ENOMEM;
4655de865eeSFilipe David Borba Manana 
466e09c2efeSDavid Sterba 	if (tree_mod_dont_log(eb->fs_info, eb)) {
4675de865eeSFilipe David Borba Manana 		kfree(tm);
4685de865eeSFilipe David Borba Manana 		return 0;
4695de865eeSFilipe David Borba Manana 	}
4705de865eeSFilipe David Borba Manana 
471e09c2efeSDavid Sterba 	ret = __tree_mod_log_insert(eb->fs_info, tm);
472b1a09f1eSDavid Sterba 	write_unlock(&eb->fs_info->tree_mod_log_lock);
4735de865eeSFilipe David Borba Manana 	if (ret)
4745de865eeSFilipe David Borba Manana 		kfree(tm);
4755de865eeSFilipe David Borba Manana 
4765de865eeSFilipe David Borba Manana 	return ret;
477097b8a7cSJan Schmidt }
478097b8a7cSJan Schmidt 
4796074d45fSDavid Sterba static noinline int tree_mod_log_insert_move(struct extent_buffer *eb,
4806074d45fSDavid Sterba 		int dst_slot, int src_slot, int nr_items)
481bd989ba3SJan Schmidt {
4825de865eeSFilipe David Borba Manana 	struct tree_mod_elem *tm = NULL;
4835de865eeSFilipe David Borba Manana 	struct tree_mod_elem **tm_list = NULL;
4845de865eeSFilipe David Borba Manana 	int ret = 0;
485bd989ba3SJan Schmidt 	int i;
4865de865eeSFilipe David Borba Manana 	int locked = 0;
487bd989ba3SJan Schmidt 
4886074d45fSDavid Sterba 	if (!tree_mod_need_log(eb->fs_info, eb))
489f395694cSJan Schmidt 		return 0;
490bd989ba3SJan Schmidt 
491176ef8f5SDavid Sterba 	tm_list = kcalloc(nr_items, sizeof(struct tree_mod_elem *), GFP_NOFS);
4925de865eeSFilipe David Borba Manana 	if (!tm_list)
4935de865eeSFilipe David Borba Manana 		return -ENOMEM;
494bd989ba3SJan Schmidt 
495176ef8f5SDavid Sterba 	tm = kzalloc(sizeof(*tm), GFP_NOFS);
4965de865eeSFilipe David Borba Manana 	if (!tm) {
4975de865eeSFilipe David Borba Manana 		ret = -ENOMEM;
4985de865eeSFilipe David Borba Manana 		goto free_tms;
4995de865eeSFilipe David Borba Manana 	}
500f395694cSJan Schmidt 
501298cfd36SChandan Rajendra 	tm->logical = eb->start;
502bd989ba3SJan Schmidt 	tm->slot = src_slot;
503bd989ba3SJan Schmidt 	tm->move.dst_slot = dst_slot;
504bd989ba3SJan Schmidt 	tm->move.nr_items = nr_items;
505bd989ba3SJan Schmidt 	tm->op = MOD_LOG_MOVE_KEYS;
506bd989ba3SJan Schmidt 
5075de865eeSFilipe David Borba Manana 	for (i = 0; i + dst_slot < src_slot && i < nr_items; i++) {
5085de865eeSFilipe David Borba Manana 		tm_list[i] = alloc_tree_mod_elem(eb, i + dst_slot,
509176ef8f5SDavid Sterba 		    MOD_LOG_KEY_REMOVE_WHILE_MOVING, GFP_NOFS);
5105de865eeSFilipe David Borba Manana 		if (!tm_list[i]) {
5115de865eeSFilipe David Borba Manana 			ret = -ENOMEM;
5125de865eeSFilipe David Borba Manana 			goto free_tms;
5135de865eeSFilipe David Borba Manana 		}
514bd989ba3SJan Schmidt 	}
515bd989ba3SJan Schmidt 
5166074d45fSDavid Sterba 	if (tree_mod_dont_log(eb->fs_info, eb))
5175de865eeSFilipe David Borba Manana 		goto free_tms;
5185de865eeSFilipe David Borba Manana 	locked = 1;
5195de865eeSFilipe David Borba Manana 
5205de865eeSFilipe David Borba Manana 	/*
5215de865eeSFilipe David Borba Manana 	 * When we override something during the move, we log these removals.
5225de865eeSFilipe David Borba Manana 	 * This can only happen when we move towards the beginning of the
5235de865eeSFilipe David Borba Manana 	 * buffer, i.e. dst_slot < src_slot.
5245de865eeSFilipe David Borba Manana 	 */
5255de865eeSFilipe David Borba Manana 	for (i = 0; i + dst_slot < src_slot && i < nr_items; i++) {
5266074d45fSDavid Sterba 		ret = __tree_mod_log_insert(eb->fs_info, tm_list[i]);
5275de865eeSFilipe David Borba Manana 		if (ret)
5285de865eeSFilipe David Borba Manana 			goto free_tms;
5295de865eeSFilipe David Borba Manana 	}
5305de865eeSFilipe David Borba Manana 
5316074d45fSDavid Sterba 	ret = __tree_mod_log_insert(eb->fs_info, tm);
5325de865eeSFilipe David Borba Manana 	if (ret)
5335de865eeSFilipe David Borba Manana 		goto free_tms;
534b1a09f1eSDavid Sterba 	write_unlock(&eb->fs_info->tree_mod_log_lock);
5355de865eeSFilipe David Borba Manana 	kfree(tm_list);
5365de865eeSFilipe David Borba Manana 
5375de865eeSFilipe David Borba Manana 	return 0;
5385de865eeSFilipe David Borba Manana free_tms:
5395de865eeSFilipe David Borba Manana 	for (i = 0; i < nr_items; i++) {
5405de865eeSFilipe David Borba Manana 		if (tm_list[i] && !RB_EMPTY_NODE(&tm_list[i]->node))
5416074d45fSDavid Sterba 			rb_erase(&tm_list[i]->node, &eb->fs_info->tree_mod_log);
5425de865eeSFilipe David Borba Manana 		kfree(tm_list[i]);
5435de865eeSFilipe David Borba Manana 	}
5445de865eeSFilipe David Borba Manana 	if (locked)
545b1a09f1eSDavid Sterba 		write_unlock(&eb->fs_info->tree_mod_log_lock);
5465de865eeSFilipe David Borba Manana 	kfree(tm_list);
5475de865eeSFilipe David Borba Manana 	kfree(tm);
5485de865eeSFilipe David Borba Manana 
5495de865eeSFilipe David Borba Manana 	return ret;
5505de865eeSFilipe David Borba Manana }
5515de865eeSFilipe David Borba Manana 
5525de865eeSFilipe David Borba Manana static inline int
5535de865eeSFilipe David Borba Manana __tree_mod_log_free_eb(struct btrfs_fs_info *fs_info,
5545de865eeSFilipe David Borba Manana 		       struct tree_mod_elem **tm_list,
5555de865eeSFilipe David Borba Manana 		       int nritems)
556097b8a7cSJan Schmidt {
5575de865eeSFilipe David Borba Manana 	int i, j;
558097b8a7cSJan Schmidt 	int ret;
559097b8a7cSJan Schmidt 
560097b8a7cSJan Schmidt 	for (i = nritems - 1; i >= 0; i--) {
5615de865eeSFilipe David Borba Manana 		ret = __tree_mod_log_insert(fs_info, tm_list[i]);
5625de865eeSFilipe David Borba Manana 		if (ret) {
5635de865eeSFilipe David Borba Manana 			for (j = nritems - 1; j > i; j--)
5645de865eeSFilipe David Borba Manana 				rb_erase(&tm_list[j]->node,
5655de865eeSFilipe David Borba Manana 					 &fs_info->tree_mod_log);
5665de865eeSFilipe David Borba Manana 			return ret;
567097b8a7cSJan Schmidt 		}
568097b8a7cSJan Schmidt 	}
569097b8a7cSJan Schmidt 
5705de865eeSFilipe David Borba Manana 	return 0;
5715de865eeSFilipe David Borba Manana }
5725de865eeSFilipe David Borba Manana 
57395b757c1SDavid Sterba static noinline int tree_mod_log_insert_root(struct extent_buffer *old_root,
57495b757c1SDavid Sterba 			 struct extent_buffer *new_root, int log_removal)
575bd989ba3SJan Schmidt {
57695b757c1SDavid Sterba 	struct btrfs_fs_info *fs_info = old_root->fs_info;
5775de865eeSFilipe David Borba Manana 	struct tree_mod_elem *tm = NULL;
5785de865eeSFilipe David Borba Manana 	struct tree_mod_elem **tm_list = NULL;
5795de865eeSFilipe David Borba Manana 	int nritems = 0;
5805de865eeSFilipe David Borba Manana 	int ret = 0;
5815de865eeSFilipe David Borba Manana 	int i;
582bd989ba3SJan Schmidt 
5835de865eeSFilipe David Borba Manana 	if (!tree_mod_need_log(fs_info, NULL))
584097b8a7cSJan Schmidt 		return 0;
585097b8a7cSJan Schmidt 
5865de865eeSFilipe David Borba Manana 	if (log_removal && btrfs_header_level(old_root) > 0) {
5875de865eeSFilipe David Borba Manana 		nritems = btrfs_header_nritems(old_root);
58831e818feSDavid Sterba 		tm_list = kcalloc(nritems, sizeof(struct tree_mod_elem *),
589bcc8e07fSDavid Sterba 				  GFP_NOFS);
5905de865eeSFilipe David Borba Manana 		if (!tm_list) {
5915de865eeSFilipe David Borba Manana 			ret = -ENOMEM;
5925de865eeSFilipe David Borba Manana 			goto free_tms;
5935de865eeSFilipe David Borba Manana 		}
5945de865eeSFilipe David Borba Manana 		for (i = 0; i < nritems; i++) {
5955de865eeSFilipe David Borba Manana 			tm_list[i] = alloc_tree_mod_elem(old_root, i,
596bcc8e07fSDavid Sterba 			    MOD_LOG_KEY_REMOVE_WHILE_FREEING, GFP_NOFS);
5975de865eeSFilipe David Borba Manana 			if (!tm_list[i]) {
5985de865eeSFilipe David Borba Manana 				ret = -ENOMEM;
5995de865eeSFilipe David Borba Manana 				goto free_tms;
6005de865eeSFilipe David Borba Manana 			}
6015de865eeSFilipe David Borba Manana 		}
6025de865eeSFilipe David Borba Manana 	}
603d9abbf1cSJan Schmidt 
604bcc8e07fSDavid Sterba 	tm = kzalloc(sizeof(*tm), GFP_NOFS);
6055de865eeSFilipe David Borba Manana 	if (!tm) {
6065de865eeSFilipe David Borba Manana 		ret = -ENOMEM;
6075de865eeSFilipe David Borba Manana 		goto free_tms;
6085de865eeSFilipe David Borba Manana 	}
609bd989ba3SJan Schmidt 
610298cfd36SChandan Rajendra 	tm->logical = new_root->start;
611bd989ba3SJan Schmidt 	tm->old_root.logical = old_root->start;
612bd989ba3SJan Schmidt 	tm->old_root.level = btrfs_header_level(old_root);
613bd989ba3SJan Schmidt 	tm->generation = btrfs_header_generation(old_root);
614bd989ba3SJan Schmidt 	tm->op = MOD_LOG_ROOT_REPLACE;
615bd989ba3SJan Schmidt 
6165de865eeSFilipe David Borba Manana 	if (tree_mod_dont_log(fs_info, NULL))
6175de865eeSFilipe David Borba Manana 		goto free_tms;
6185de865eeSFilipe David Borba Manana 
6195de865eeSFilipe David Borba Manana 	if (tm_list)
6205de865eeSFilipe David Borba Manana 		ret = __tree_mod_log_free_eb(fs_info, tm_list, nritems);
6215de865eeSFilipe David Borba Manana 	if (!ret)
6225de865eeSFilipe David Borba Manana 		ret = __tree_mod_log_insert(fs_info, tm);
6235de865eeSFilipe David Borba Manana 
624b1a09f1eSDavid Sterba 	write_unlock(&fs_info->tree_mod_log_lock);
6255de865eeSFilipe David Borba Manana 	if (ret)
6265de865eeSFilipe David Borba Manana 		goto free_tms;
6275de865eeSFilipe David Borba Manana 	kfree(tm_list);
6285de865eeSFilipe David Borba Manana 
6295de865eeSFilipe David Borba Manana 	return ret;
6305de865eeSFilipe David Borba Manana 
6315de865eeSFilipe David Borba Manana free_tms:
6325de865eeSFilipe David Borba Manana 	if (tm_list) {
6335de865eeSFilipe David Borba Manana 		for (i = 0; i < nritems; i++)
6345de865eeSFilipe David Borba Manana 			kfree(tm_list[i]);
6355de865eeSFilipe David Borba Manana 		kfree(tm_list);
6365de865eeSFilipe David Borba Manana 	}
6375de865eeSFilipe David Borba Manana 	kfree(tm);
6385de865eeSFilipe David Borba Manana 
6395de865eeSFilipe David Borba Manana 	return ret;
640bd989ba3SJan Schmidt }
641bd989ba3SJan Schmidt 
642bd989ba3SJan Schmidt static struct tree_mod_elem *
643bd989ba3SJan Schmidt __tree_mod_log_search(struct btrfs_fs_info *fs_info, u64 start, u64 min_seq,
644bd989ba3SJan Schmidt 		      int smallest)
645bd989ba3SJan Schmidt {
646bd989ba3SJan Schmidt 	struct rb_root *tm_root;
647bd989ba3SJan Schmidt 	struct rb_node *node;
648bd989ba3SJan Schmidt 	struct tree_mod_elem *cur = NULL;
649bd989ba3SJan Schmidt 	struct tree_mod_elem *found = NULL;
650bd989ba3SJan Schmidt 
651b1a09f1eSDavid Sterba 	read_lock(&fs_info->tree_mod_log_lock);
652bd989ba3SJan Schmidt 	tm_root = &fs_info->tree_mod_log;
653bd989ba3SJan Schmidt 	node = tm_root->rb_node;
654bd989ba3SJan Schmidt 	while (node) {
6556b4df8b6SGeliang Tang 		cur = rb_entry(node, struct tree_mod_elem, node);
656298cfd36SChandan Rajendra 		if (cur->logical < start) {
657bd989ba3SJan Schmidt 			node = node->rb_left;
658298cfd36SChandan Rajendra 		} else if (cur->logical > start) {
659bd989ba3SJan Schmidt 			node = node->rb_right;
660097b8a7cSJan Schmidt 		} else if (cur->seq < min_seq) {
661bd989ba3SJan Schmidt 			node = node->rb_left;
662bd989ba3SJan Schmidt 		} else if (!smallest) {
663bd989ba3SJan Schmidt 			/* we want the node with the highest seq */
664bd989ba3SJan Schmidt 			if (found)
665097b8a7cSJan Schmidt 				BUG_ON(found->seq > cur->seq);
666bd989ba3SJan Schmidt 			found = cur;
667bd989ba3SJan Schmidt 			node = node->rb_left;
668097b8a7cSJan Schmidt 		} else if (cur->seq > min_seq) {
669bd989ba3SJan Schmidt 			/* we want the node with the smallest seq */
670bd989ba3SJan Schmidt 			if (found)
671097b8a7cSJan Schmidt 				BUG_ON(found->seq < cur->seq);
672bd989ba3SJan Schmidt 			found = cur;
673bd989ba3SJan Schmidt 			node = node->rb_right;
674bd989ba3SJan Schmidt 		} else {
675bd989ba3SJan Schmidt 			found = cur;
676bd989ba3SJan Schmidt 			break;
677bd989ba3SJan Schmidt 		}
678bd989ba3SJan Schmidt 	}
679b1a09f1eSDavid Sterba 	read_unlock(&fs_info->tree_mod_log_lock);
680bd989ba3SJan Schmidt 
681bd989ba3SJan Schmidt 	return found;
682bd989ba3SJan Schmidt }
683bd989ba3SJan Schmidt 
684bd989ba3SJan Schmidt /*
685bd989ba3SJan Schmidt  * this returns the element from the log with the smallest time sequence
686bd989ba3SJan Schmidt  * value that's in the log (the oldest log item). any element with a time
687bd989ba3SJan Schmidt  * sequence lower than min_seq will be ignored.
688bd989ba3SJan Schmidt  */
689bd989ba3SJan Schmidt static struct tree_mod_elem *
690bd989ba3SJan Schmidt tree_mod_log_search_oldest(struct btrfs_fs_info *fs_info, u64 start,
691bd989ba3SJan Schmidt 			   u64 min_seq)
692bd989ba3SJan Schmidt {
693bd989ba3SJan Schmidt 	return __tree_mod_log_search(fs_info, start, min_seq, 1);
694bd989ba3SJan Schmidt }
695bd989ba3SJan Schmidt 
696bd989ba3SJan Schmidt /*
697bd989ba3SJan Schmidt  * this returns the element from the log with the largest time sequence
698bd989ba3SJan Schmidt  * value that's in the log (the most recent log item). any element with
699bd989ba3SJan Schmidt  * a time sequence lower than min_seq will be ignored.
700bd989ba3SJan Schmidt  */
701bd989ba3SJan Schmidt static struct tree_mod_elem *
702bd989ba3SJan Schmidt tree_mod_log_search(struct btrfs_fs_info *fs_info, u64 start, u64 min_seq)
703bd989ba3SJan Schmidt {
704bd989ba3SJan Schmidt 	return __tree_mod_log_search(fs_info, start, min_seq, 0);
705bd989ba3SJan Schmidt }
706bd989ba3SJan Schmidt 
707ed874f0dSDavid Sterba static noinline int tree_mod_log_eb_copy(struct extent_buffer *dst,
708bd989ba3SJan Schmidt 		     struct extent_buffer *src, unsigned long dst_offset,
70990f8d62eSJan Schmidt 		     unsigned long src_offset, int nr_items)
710bd989ba3SJan Schmidt {
711ed874f0dSDavid Sterba 	struct btrfs_fs_info *fs_info = dst->fs_info;
7125de865eeSFilipe David Borba Manana 	int ret = 0;
7135de865eeSFilipe David Borba Manana 	struct tree_mod_elem **tm_list = NULL;
7145de865eeSFilipe David Borba Manana 	struct tree_mod_elem **tm_list_add, **tm_list_rem;
715bd989ba3SJan Schmidt 	int i;
7165de865eeSFilipe David Borba Manana 	int locked = 0;
717bd989ba3SJan Schmidt 
7185de865eeSFilipe David Borba Manana 	if (!tree_mod_need_log(fs_info, NULL))
7195de865eeSFilipe David Borba Manana 		return 0;
720bd989ba3SJan Schmidt 
721c8cc6341SJosef Bacik 	if (btrfs_header_level(dst) == 0 && btrfs_header_level(src) == 0)
7225de865eeSFilipe David Borba Manana 		return 0;
7235de865eeSFilipe David Borba Manana 
72431e818feSDavid Sterba 	tm_list = kcalloc(nr_items * 2, sizeof(struct tree_mod_elem *),
7255de865eeSFilipe David Borba Manana 			  GFP_NOFS);
7265de865eeSFilipe David Borba Manana 	if (!tm_list)
7275de865eeSFilipe David Borba Manana 		return -ENOMEM;
7285de865eeSFilipe David Borba Manana 
7295de865eeSFilipe David Borba Manana 	tm_list_add = tm_list;
7305de865eeSFilipe David Borba Manana 	tm_list_rem = tm_list + nr_items;
7315de865eeSFilipe David Borba Manana 	for (i = 0; i < nr_items; i++) {
7325de865eeSFilipe David Borba Manana 		tm_list_rem[i] = alloc_tree_mod_elem(src, i + src_offset,
7335de865eeSFilipe David Borba Manana 		    MOD_LOG_KEY_REMOVE, GFP_NOFS);
7345de865eeSFilipe David Borba Manana 		if (!tm_list_rem[i]) {
7355de865eeSFilipe David Borba Manana 			ret = -ENOMEM;
7365de865eeSFilipe David Borba Manana 			goto free_tms;
7375de865eeSFilipe David Borba Manana 		}
7385de865eeSFilipe David Borba Manana 
7395de865eeSFilipe David Borba Manana 		tm_list_add[i] = alloc_tree_mod_elem(dst, i + dst_offset,
7405de865eeSFilipe David Borba Manana 		    MOD_LOG_KEY_ADD, GFP_NOFS);
7415de865eeSFilipe David Borba Manana 		if (!tm_list_add[i]) {
7425de865eeSFilipe David Borba Manana 			ret = -ENOMEM;
7435de865eeSFilipe David Borba Manana 			goto free_tms;
7445de865eeSFilipe David Borba Manana 		}
7455de865eeSFilipe David Borba Manana 	}
7465de865eeSFilipe David Borba Manana 
7475de865eeSFilipe David Borba Manana 	if (tree_mod_dont_log(fs_info, NULL))
7485de865eeSFilipe David Borba Manana 		goto free_tms;
7495de865eeSFilipe David Borba Manana 	locked = 1;
750bd989ba3SJan Schmidt 
751bd989ba3SJan Schmidt 	for (i = 0; i < nr_items; i++) {
7525de865eeSFilipe David Borba Manana 		ret = __tree_mod_log_insert(fs_info, tm_list_rem[i]);
7535de865eeSFilipe David Borba Manana 		if (ret)
7545de865eeSFilipe David Borba Manana 			goto free_tms;
7555de865eeSFilipe David Borba Manana 		ret = __tree_mod_log_insert(fs_info, tm_list_add[i]);
7565de865eeSFilipe David Borba Manana 		if (ret)
7575de865eeSFilipe David Borba Manana 			goto free_tms;
758bd989ba3SJan Schmidt 	}
7595de865eeSFilipe David Borba Manana 
760b1a09f1eSDavid Sterba 	write_unlock(&fs_info->tree_mod_log_lock);
7615de865eeSFilipe David Borba Manana 	kfree(tm_list);
7625de865eeSFilipe David Borba Manana 
7635de865eeSFilipe David Borba Manana 	return 0;
7645de865eeSFilipe David Borba Manana 
7655de865eeSFilipe David Borba Manana free_tms:
7665de865eeSFilipe David Borba Manana 	for (i = 0; i < nr_items * 2; i++) {
7675de865eeSFilipe David Borba Manana 		if (tm_list[i] && !RB_EMPTY_NODE(&tm_list[i]->node))
7685de865eeSFilipe David Borba Manana 			rb_erase(&tm_list[i]->node, &fs_info->tree_mod_log);
7695de865eeSFilipe David Borba Manana 		kfree(tm_list[i]);
7705de865eeSFilipe David Borba Manana 	}
7715de865eeSFilipe David Borba Manana 	if (locked)
772b1a09f1eSDavid Sterba 		write_unlock(&fs_info->tree_mod_log_lock);
7735de865eeSFilipe David Borba Manana 	kfree(tm_list);
7745de865eeSFilipe David Borba Manana 
7755de865eeSFilipe David Borba Manana 	return ret;
776bd989ba3SJan Schmidt }
777bd989ba3SJan Schmidt 
778db7279a2SDavid Sterba static noinline int tree_mod_log_free_eb(struct extent_buffer *eb)
779bd989ba3SJan Schmidt {
7805de865eeSFilipe David Borba Manana 	struct tree_mod_elem **tm_list = NULL;
7815de865eeSFilipe David Borba Manana 	int nritems = 0;
7825de865eeSFilipe David Borba Manana 	int i;
7835de865eeSFilipe David Borba Manana 	int ret = 0;
7845de865eeSFilipe David Borba Manana 
7855de865eeSFilipe David Borba Manana 	if (btrfs_header_level(eb) == 0)
7865de865eeSFilipe David Borba Manana 		return 0;
7875de865eeSFilipe David Borba Manana 
788db7279a2SDavid Sterba 	if (!tree_mod_need_log(eb->fs_info, NULL))
7895de865eeSFilipe David Borba Manana 		return 0;
7905de865eeSFilipe David Borba Manana 
7915de865eeSFilipe David Borba Manana 	nritems = btrfs_header_nritems(eb);
79231e818feSDavid Sterba 	tm_list = kcalloc(nritems, sizeof(struct tree_mod_elem *), GFP_NOFS);
7935de865eeSFilipe David Borba Manana 	if (!tm_list)
7945de865eeSFilipe David Borba Manana 		return -ENOMEM;
7955de865eeSFilipe David Borba Manana 
7965de865eeSFilipe David Borba Manana 	for (i = 0; i < nritems; i++) {
7975de865eeSFilipe David Borba Manana 		tm_list[i] = alloc_tree_mod_elem(eb, i,
7985de865eeSFilipe David Borba Manana 		    MOD_LOG_KEY_REMOVE_WHILE_FREEING, GFP_NOFS);
7995de865eeSFilipe David Borba Manana 		if (!tm_list[i]) {
8005de865eeSFilipe David Borba Manana 			ret = -ENOMEM;
8015de865eeSFilipe David Borba Manana 			goto free_tms;
8025de865eeSFilipe David Borba Manana 		}
8035de865eeSFilipe David Borba Manana 	}
8045de865eeSFilipe David Borba Manana 
805db7279a2SDavid Sterba 	if (tree_mod_dont_log(eb->fs_info, eb))
8065de865eeSFilipe David Borba Manana 		goto free_tms;
8075de865eeSFilipe David Borba Manana 
808db7279a2SDavid Sterba 	ret = __tree_mod_log_free_eb(eb->fs_info, tm_list, nritems);
809b1a09f1eSDavid Sterba 	write_unlock(&eb->fs_info->tree_mod_log_lock);
8105de865eeSFilipe David Borba Manana 	if (ret)
8115de865eeSFilipe David Borba Manana 		goto free_tms;
8125de865eeSFilipe David Borba Manana 	kfree(tm_list);
8135de865eeSFilipe David Borba Manana 
8145de865eeSFilipe David Borba Manana 	return 0;
8155de865eeSFilipe David Borba Manana 
8165de865eeSFilipe David Borba Manana free_tms:
8175de865eeSFilipe David Borba Manana 	for (i = 0; i < nritems; i++)
8185de865eeSFilipe David Borba Manana 		kfree(tm_list[i]);
8195de865eeSFilipe David Borba Manana 	kfree(tm_list);
8205de865eeSFilipe David Borba Manana 
8215de865eeSFilipe David Borba Manana 	return ret;
822bd989ba3SJan Schmidt }
823bd989ba3SJan Schmidt 
824d352ac68SChris Mason /*
8255d4f98a2SYan Zheng  * check if the tree block can be shared by multiple trees
8265d4f98a2SYan Zheng  */
8275d4f98a2SYan Zheng int btrfs_block_can_be_shared(struct btrfs_root *root,
8285d4f98a2SYan Zheng 			      struct extent_buffer *buf)
8295d4f98a2SYan Zheng {
8305d4f98a2SYan Zheng 	/*
83192a7cc42SQu Wenruo 	 * Tree blocks not in shareable trees and tree roots are never shared.
83292a7cc42SQu Wenruo 	 * If a block was allocated after the last snapshot and the block was
83392a7cc42SQu Wenruo 	 * not allocated by tree relocation, we know the block is not shared.
8345d4f98a2SYan Zheng 	 */
83592a7cc42SQu Wenruo 	if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
8365d4f98a2SYan Zheng 	    buf != root->node && buf != root->commit_root &&
8375d4f98a2SYan Zheng 	    (btrfs_header_generation(buf) <=
8385d4f98a2SYan Zheng 	     btrfs_root_last_snapshot(&root->root_item) ||
8395d4f98a2SYan Zheng 	     btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)))
8405d4f98a2SYan Zheng 		return 1;
841a79865c6SNikolay Borisov 
8425d4f98a2SYan Zheng 	return 0;
8435d4f98a2SYan Zheng }
8445d4f98a2SYan Zheng 
8455d4f98a2SYan Zheng static noinline int update_ref_for_cow(struct btrfs_trans_handle *trans,
8465d4f98a2SYan Zheng 				       struct btrfs_root *root,
8475d4f98a2SYan Zheng 				       struct extent_buffer *buf,
848f0486c68SYan, Zheng 				       struct extent_buffer *cow,
849f0486c68SYan, Zheng 				       int *last_ref)
8505d4f98a2SYan Zheng {
8510b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
8525d4f98a2SYan Zheng 	u64 refs;
8535d4f98a2SYan Zheng 	u64 owner;
8545d4f98a2SYan Zheng 	u64 flags;
8555d4f98a2SYan Zheng 	u64 new_flags = 0;
8565d4f98a2SYan Zheng 	int ret;
8575d4f98a2SYan Zheng 
8585d4f98a2SYan Zheng 	/*
8595d4f98a2SYan Zheng 	 * Backrefs update rules:
8605d4f98a2SYan Zheng 	 *
8615d4f98a2SYan Zheng 	 * Always use full backrefs for extent pointers in tree block
8625d4f98a2SYan Zheng 	 * allocated by tree relocation.
8635d4f98a2SYan Zheng 	 *
8645d4f98a2SYan Zheng 	 * If a shared tree block is no longer referenced by its owner
8655d4f98a2SYan Zheng 	 * tree (btrfs_header_owner(buf) == root->root_key.objectid),
8665d4f98a2SYan Zheng 	 * use full backrefs for extent pointers in tree block.
8675d4f98a2SYan Zheng 	 *
8685d4f98a2SYan Zheng 	 * If a tree block is been relocating
8695d4f98a2SYan Zheng 	 * (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID),
8705d4f98a2SYan Zheng 	 * use full backrefs for extent pointers in tree block.
8715d4f98a2SYan Zheng 	 * The reason for this is some operations (such as drop tree)
8725d4f98a2SYan Zheng 	 * are only allowed for blocks use full backrefs.
8735d4f98a2SYan Zheng 	 */
8745d4f98a2SYan Zheng 
8755d4f98a2SYan Zheng 	if (btrfs_block_can_be_shared(root, buf)) {
8762ff7e61eSJeff Mahoney 		ret = btrfs_lookup_extent_info(trans, fs_info, buf->start,
8773173a18fSJosef Bacik 					       btrfs_header_level(buf), 1,
8783173a18fSJosef Bacik 					       &refs, &flags);
879be1a5564SMark Fasheh 		if (ret)
880be1a5564SMark Fasheh 			return ret;
881e5df9573SMark Fasheh 		if (refs == 0) {
882e5df9573SMark Fasheh 			ret = -EROFS;
8830b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
884e5df9573SMark Fasheh 			return ret;
885e5df9573SMark Fasheh 		}
8865d4f98a2SYan Zheng 	} else {
8875d4f98a2SYan Zheng 		refs = 1;
8885d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
8895d4f98a2SYan Zheng 		    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
8905d4f98a2SYan Zheng 			flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
8915d4f98a2SYan Zheng 		else
8925d4f98a2SYan Zheng 			flags = 0;
8935d4f98a2SYan Zheng 	}
8945d4f98a2SYan Zheng 
8955d4f98a2SYan Zheng 	owner = btrfs_header_owner(buf);
8965d4f98a2SYan Zheng 	BUG_ON(owner == BTRFS_TREE_RELOC_OBJECTID &&
8975d4f98a2SYan Zheng 	       !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
8985d4f98a2SYan Zheng 
8995d4f98a2SYan Zheng 	if (refs > 1) {
9005d4f98a2SYan Zheng 		if ((owner == root->root_key.objectid ||
9015d4f98a2SYan Zheng 		     root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) &&
9025d4f98a2SYan Zheng 		    !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)) {
903e339a6b0SJosef Bacik 			ret = btrfs_inc_ref(trans, root, buf, 1);
904692826b2SJeff Mahoney 			if (ret)
905692826b2SJeff Mahoney 				return ret;
9065d4f98a2SYan Zheng 
9075d4f98a2SYan Zheng 			if (root->root_key.objectid ==
9085d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID) {
909e339a6b0SJosef Bacik 				ret = btrfs_dec_ref(trans, root, buf, 0);
910692826b2SJeff Mahoney 				if (ret)
911692826b2SJeff Mahoney 					return ret;
912e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
913692826b2SJeff Mahoney 				if (ret)
914692826b2SJeff Mahoney 					return ret;
9155d4f98a2SYan Zheng 			}
9165d4f98a2SYan Zheng 			new_flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
9175d4f98a2SYan Zheng 		} else {
9185d4f98a2SYan Zheng 
9195d4f98a2SYan Zheng 			if (root->root_key.objectid ==
9205d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID)
921e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
9225d4f98a2SYan Zheng 			else
923e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 0);
924692826b2SJeff Mahoney 			if (ret)
925692826b2SJeff Mahoney 				return ret;
9265d4f98a2SYan Zheng 		}
9275d4f98a2SYan Zheng 		if (new_flags != 0) {
928b1c79e09SJosef Bacik 			int level = btrfs_header_level(buf);
929b1c79e09SJosef Bacik 
93042c9d0b5SDavid Sterba 			ret = btrfs_set_disk_extent_flags(trans, buf,
931b1c79e09SJosef Bacik 							  new_flags, level, 0);
932be1a5564SMark Fasheh 			if (ret)
933be1a5564SMark Fasheh 				return ret;
9345d4f98a2SYan Zheng 		}
9355d4f98a2SYan Zheng 	} else {
9365d4f98a2SYan Zheng 		if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
9375d4f98a2SYan Zheng 			if (root->root_key.objectid ==
9385d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID)
939e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
9405d4f98a2SYan Zheng 			else
941e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 0);
942692826b2SJeff Mahoney 			if (ret)
943692826b2SJeff Mahoney 				return ret;
944e339a6b0SJosef Bacik 			ret = btrfs_dec_ref(trans, root, buf, 1);
945692826b2SJeff Mahoney 			if (ret)
946692826b2SJeff Mahoney 				return ret;
9475d4f98a2SYan Zheng 		}
9486a884d7dSDavid Sterba 		btrfs_clean_tree_block(buf);
949f0486c68SYan, Zheng 		*last_ref = 1;
9505d4f98a2SYan Zheng 	}
9515d4f98a2SYan Zheng 	return 0;
9525d4f98a2SYan Zheng }
9535d4f98a2SYan Zheng 
954a6279470SFilipe Manana static struct extent_buffer *alloc_tree_block_no_bg_flush(
955a6279470SFilipe Manana 					  struct btrfs_trans_handle *trans,
956a6279470SFilipe Manana 					  struct btrfs_root *root,
957a6279470SFilipe Manana 					  u64 parent_start,
958a6279470SFilipe Manana 					  const struct btrfs_disk_key *disk_key,
959a6279470SFilipe Manana 					  int level,
960a6279470SFilipe Manana 					  u64 hint,
9619631e4ccSJosef Bacik 					  u64 empty_size,
9629631e4ccSJosef Bacik 					  enum btrfs_lock_nesting nest)
963a6279470SFilipe Manana {
964a6279470SFilipe Manana 	struct btrfs_fs_info *fs_info = root->fs_info;
965a6279470SFilipe Manana 	struct extent_buffer *ret;
966a6279470SFilipe Manana 
967a6279470SFilipe Manana 	/*
968a6279470SFilipe Manana 	 * If we are COWing a node/leaf from the extent, chunk, device or free
969a6279470SFilipe Manana 	 * space trees, make sure that we do not finish block group creation of
970a6279470SFilipe Manana 	 * pending block groups. We do this to avoid a deadlock.
971a6279470SFilipe Manana 	 * COWing can result in allocation of a new chunk, and flushing pending
972a6279470SFilipe Manana 	 * block groups (btrfs_create_pending_block_groups()) can be triggered
973a6279470SFilipe Manana 	 * when finishing allocation of a new chunk. Creation of a pending block
974a6279470SFilipe Manana 	 * group modifies the extent, chunk, device and free space trees,
975a6279470SFilipe Manana 	 * therefore we could deadlock with ourselves since we are holding a
976a6279470SFilipe Manana 	 * lock on an extent buffer that btrfs_create_pending_block_groups() may
977a6279470SFilipe Manana 	 * try to COW later.
978a6279470SFilipe Manana 	 * For similar reasons, we also need to delay flushing pending block
979a6279470SFilipe Manana 	 * groups when splitting a leaf or node, from one of those trees, since
980a6279470SFilipe Manana 	 * we are holding a write lock on it and its parent or when inserting a
981a6279470SFilipe Manana 	 * new root node for one of those trees.
982a6279470SFilipe Manana 	 */
983a6279470SFilipe Manana 	if (root == fs_info->extent_root ||
984a6279470SFilipe Manana 	    root == fs_info->chunk_root ||
985a6279470SFilipe Manana 	    root == fs_info->dev_root ||
986a6279470SFilipe Manana 	    root == fs_info->free_space_root)
987a6279470SFilipe Manana 		trans->can_flush_pending_bgs = false;
988a6279470SFilipe Manana 
989a6279470SFilipe Manana 	ret = btrfs_alloc_tree_block(trans, root, parent_start,
990a6279470SFilipe Manana 				     root->root_key.objectid, disk_key, level,
9919631e4ccSJosef Bacik 				     hint, empty_size, nest);
992a6279470SFilipe Manana 	trans->can_flush_pending_bgs = true;
993a6279470SFilipe Manana 
994a6279470SFilipe Manana 	return ret;
995a6279470SFilipe Manana }
996a6279470SFilipe Manana 
9975d4f98a2SYan Zheng /*
998d397712bSChris Mason  * does the dirty work in cow of a single block.  The parent block (if
999d397712bSChris Mason  * supplied) is updated to point to the new cow copy.  The new buffer is marked
1000d397712bSChris Mason  * dirty and returned locked.  If you modify the block it needs to be marked
1001d397712bSChris Mason  * dirty again.
1002d352ac68SChris Mason  *
1003d352ac68SChris Mason  * search_start -- an allocation hint for the new block
1004d352ac68SChris Mason  *
1005d397712bSChris Mason  * empty_size -- a hint that you plan on doing more cow.  This is the size in
1006d397712bSChris Mason  * bytes the allocator should try to find free next to the block it returns.
1007d397712bSChris Mason  * This is just a hint and may be ignored by the allocator.
1008d352ac68SChris Mason  */
1009d397712bSChris Mason static noinline int __btrfs_cow_block(struct btrfs_trans_handle *trans,
10105f39d397SChris Mason 			     struct btrfs_root *root,
10115f39d397SChris Mason 			     struct extent_buffer *buf,
10125f39d397SChris Mason 			     struct extent_buffer *parent, int parent_slot,
10135f39d397SChris Mason 			     struct extent_buffer **cow_ret,
10149631e4ccSJosef Bacik 			     u64 search_start, u64 empty_size,
10159631e4ccSJosef Bacik 			     enum btrfs_lock_nesting nest)
10166702ed49SChris Mason {
10170b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
10185d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
10195f39d397SChris Mason 	struct extent_buffer *cow;
1020be1a5564SMark Fasheh 	int level, ret;
1021f0486c68SYan, Zheng 	int last_ref = 0;
1022925baeddSChris Mason 	int unlock_orig = 0;
10230f5053ebSGoldwyn Rodrigues 	u64 parent_start = 0;
10246702ed49SChris Mason 
1025925baeddSChris Mason 	if (*cow_ret == buf)
1026925baeddSChris Mason 		unlock_orig = 1;
1027925baeddSChris Mason 
1028b9447ef8SChris Mason 	btrfs_assert_tree_locked(buf);
1029925baeddSChris Mason 
103092a7cc42SQu Wenruo 	WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
10310b246afaSJeff Mahoney 		trans->transid != fs_info->running_transaction->transid);
103292a7cc42SQu Wenruo 	WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
103327cdeb70SMiao Xie 		trans->transid != root->last_trans);
10345f39d397SChris Mason 
10357bb86316SChris Mason 	level = btrfs_header_level(buf);
103631840ae1SZheng Yan 
10375d4f98a2SYan Zheng 	if (level == 0)
10385d4f98a2SYan Zheng 		btrfs_item_key(buf, &disk_key, 0);
10395d4f98a2SYan Zheng 	else
10405d4f98a2SYan Zheng 		btrfs_node_key(buf, &disk_key, 0);
10415d4f98a2SYan Zheng 
10420f5053ebSGoldwyn Rodrigues 	if ((root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) && parent)
10435d4f98a2SYan Zheng 		parent_start = parent->start;
10445d4f98a2SYan Zheng 
1045a6279470SFilipe Manana 	cow = alloc_tree_block_no_bg_flush(trans, root, parent_start, &disk_key,
10469631e4ccSJosef Bacik 					   level, search_start, empty_size, nest);
10476702ed49SChris Mason 	if (IS_ERR(cow))
10486702ed49SChris Mason 		return PTR_ERR(cow);
10496702ed49SChris Mason 
1050b4ce94deSChris Mason 	/* cow is set to blocking by btrfs_init_new_buffer */
1051b4ce94deSChris Mason 
105258e8012cSDavid Sterba 	copy_extent_buffer_full(cow, buf);
1053db94535dSChris Mason 	btrfs_set_header_bytenr(cow, cow->start);
10545f39d397SChris Mason 	btrfs_set_header_generation(cow, trans->transid);
10555d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
10565d4f98a2SYan Zheng 	btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
10575d4f98a2SYan Zheng 				     BTRFS_HEADER_FLAG_RELOC);
10585d4f98a2SYan Zheng 	if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
10595d4f98a2SYan Zheng 		btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
10605d4f98a2SYan Zheng 	else
10615f39d397SChris Mason 		btrfs_set_header_owner(cow, root->root_key.objectid);
10626702ed49SChris Mason 
1063de37aa51SNikolay Borisov 	write_extent_buffer_fsid(cow, fs_info->fs_devices->metadata_uuid);
10642b82032cSYan Zheng 
1065be1a5564SMark Fasheh 	ret = update_ref_for_cow(trans, root, buf, cow, &last_ref);
1066b68dc2a9SMark Fasheh 	if (ret) {
1067572c83acSJosef Bacik 		btrfs_tree_unlock(cow);
1068572c83acSJosef Bacik 		free_extent_buffer(cow);
106966642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
1070b68dc2a9SMark Fasheh 		return ret;
1071b68dc2a9SMark Fasheh 	}
10721a40e23bSZheng Yan 
107392a7cc42SQu Wenruo 	if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state)) {
107483d4cfd4SJosef Bacik 		ret = btrfs_reloc_cow_block(trans, root, buf, cow);
107593314e3bSZhaolei 		if (ret) {
1076572c83acSJosef Bacik 			btrfs_tree_unlock(cow);
1077572c83acSJosef Bacik 			free_extent_buffer(cow);
107866642832SJeff Mahoney 			btrfs_abort_transaction(trans, ret);
107983d4cfd4SJosef Bacik 			return ret;
108083d4cfd4SJosef Bacik 		}
108193314e3bSZhaolei 	}
10823fd0a558SYan, Zheng 
10836702ed49SChris Mason 	if (buf == root->node) {
1084925baeddSChris Mason 		WARN_ON(parent && parent != buf);
10855d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
10865d4f98a2SYan Zheng 		    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
10875d4f98a2SYan Zheng 			parent_start = buf->start;
1088925baeddSChris Mason 
108967439dadSDavid Sterba 		atomic_inc(&cow->refs);
1090d9d19a01SDavid Sterba 		ret = tree_mod_log_insert_root(root->node, cow, 1);
1091d9d19a01SDavid Sterba 		BUG_ON(ret < 0);
1092240f62c8SChris Mason 		rcu_assign_pointer(root->node, cow);
1093925baeddSChris Mason 
1094f0486c68SYan, Zheng 		btrfs_free_tree_block(trans, root, buf, parent_start,
10955581a51aSJan Schmidt 				      last_ref);
10965f39d397SChris Mason 		free_extent_buffer(buf);
10970b86a832SChris Mason 		add_root_to_dirty_list(root);
10986702ed49SChris Mason 	} else {
10995d4f98a2SYan Zheng 		WARN_ON(trans->transid != btrfs_header_generation(parent));
1100e09c2efeSDavid Sterba 		tree_mod_log_insert_key(parent, parent_slot,
1101c8cc6341SJosef Bacik 					MOD_LOG_KEY_REPLACE, GFP_NOFS);
11025f39d397SChris Mason 		btrfs_set_node_blockptr(parent, parent_slot,
1103db94535dSChris Mason 					cow->start);
110474493f7aSChris Mason 		btrfs_set_node_ptr_generation(parent, parent_slot,
110574493f7aSChris Mason 					      trans->transid);
11066702ed49SChris Mason 		btrfs_mark_buffer_dirty(parent);
11075de865eeSFilipe David Borba Manana 		if (last_ref) {
1108db7279a2SDavid Sterba 			ret = tree_mod_log_free_eb(buf);
11095de865eeSFilipe David Borba Manana 			if (ret) {
1110572c83acSJosef Bacik 				btrfs_tree_unlock(cow);
1111572c83acSJosef Bacik 				free_extent_buffer(cow);
111266642832SJeff Mahoney 				btrfs_abort_transaction(trans, ret);
11135de865eeSFilipe David Borba Manana 				return ret;
11145de865eeSFilipe David Borba Manana 			}
11155de865eeSFilipe David Borba Manana 		}
1116f0486c68SYan, Zheng 		btrfs_free_tree_block(trans, root, buf, parent_start,
11175581a51aSJan Schmidt 				      last_ref);
11186702ed49SChris Mason 	}
1119925baeddSChris Mason 	if (unlock_orig)
1120925baeddSChris Mason 		btrfs_tree_unlock(buf);
11213083ee2eSJosef Bacik 	free_extent_buffer_stale(buf);
11226702ed49SChris Mason 	btrfs_mark_buffer_dirty(cow);
11236702ed49SChris Mason 	*cow_ret = cow;
11246702ed49SChris Mason 	return 0;
11256702ed49SChris Mason }
11266702ed49SChris Mason 
11275d9e75c4SJan Schmidt /*
11285d9e75c4SJan Schmidt  * returns the logical address of the oldest predecessor of the given root.
11295d9e75c4SJan Schmidt  * entries older than time_seq are ignored.
11305d9e75c4SJan Schmidt  */
1131bcd24dabSDavid Sterba static struct tree_mod_elem *__tree_mod_log_oldest_root(
113230b0463aSJan Schmidt 		struct extent_buffer *eb_root, u64 time_seq)
11335d9e75c4SJan Schmidt {
11345d9e75c4SJan Schmidt 	struct tree_mod_elem *tm;
11355d9e75c4SJan Schmidt 	struct tree_mod_elem *found = NULL;
113630b0463aSJan Schmidt 	u64 root_logical = eb_root->start;
11375d9e75c4SJan Schmidt 	int looped = 0;
11385d9e75c4SJan Schmidt 
11395d9e75c4SJan Schmidt 	if (!time_seq)
114035a3621bSStefan Behrens 		return NULL;
11415d9e75c4SJan Schmidt 
11425d9e75c4SJan Schmidt 	/*
1143298cfd36SChandan Rajendra 	 * the very last operation that's logged for a root is the
1144298cfd36SChandan Rajendra 	 * replacement operation (if it is replaced at all). this has
1145298cfd36SChandan Rajendra 	 * the logical address of the *new* root, making it the very
1146298cfd36SChandan Rajendra 	 * first operation that's logged for this root.
11475d9e75c4SJan Schmidt 	 */
11485d9e75c4SJan Schmidt 	while (1) {
1149bcd24dabSDavid Sterba 		tm = tree_mod_log_search_oldest(eb_root->fs_info, root_logical,
11505d9e75c4SJan Schmidt 						time_seq);
11515d9e75c4SJan Schmidt 		if (!looped && !tm)
115235a3621bSStefan Behrens 			return NULL;
11535d9e75c4SJan Schmidt 		/*
115428da9fb4SJan Schmidt 		 * if there are no tree operation for the oldest root, we simply
115528da9fb4SJan Schmidt 		 * return it. this should only happen if that (old) root is at
115628da9fb4SJan Schmidt 		 * level 0.
11575d9e75c4SJan Schmidt 		 */
115828da9fb4SJan Schmidt 		if (!tm)
115928da9fb4SJan Schmidt 			break;
11605d9e75c4SJan Schmidt 
116128da9fb4SJan Schmidt 		/*
116228da9fb4SJan Schmidt 		 * if there's an operation that's not a root replacement, we
116328da9fb4SJan Schmidt 		 * found the oldest version of our root. normally, we'll find a
116428da9fb4SJan Schmidt 		 * MOD_LOG_KEY_REMOVE_WHILE_FREEING operation here.
116528da9fb4SJan Schmidt 		 */
11665d9e75c4SJan Schmidt 		if (tm->op != MOD_LOG_ROOT_REPLACE)
11675d9e75c4SJan Schmidt 			break;
11685d9e75c4SJan Schmidt 
11695d9e75c4SJan Schmidt 		found = tm;
11705d9e75c4SJan Schmidt 		root_logical = tm->old_root.logical;
11715d9e75c4SJan Schmidt 		looped = 1;
11725d9e75c4SJan Schmidt 	}
11735d9e75c4SJan Schmidt 
1174a95236d9SJan Schmidt 	/* if there's no old root to return, return what we found instead */
1175a95236d9SJan Schmidt 	if (!found)
1176a95236d9SJan Schmidt 		found = tm;
1177a95236d9SJan Schmidt 
11785d9e75c4SJan Schmidt 	return found;
11795d9e75c4SJan Schmidt }
11805d9e75c4SJan Schmidt 
11815d9e75c4SJan Schmidt /*
11825d9e75c4SJan Schmidt  * tm is a pointer to the first operation to rewind within eb. then, all
118301327610SNicholas D Steeves  * previous operations will be rewound (until we reach something older than
11845d9e75c4SJan Schmidt  * time_seq).
11855d9e75c4SJan Schmidt  */
11865d9e75c4SJan Schmidt static void
1187f1ca7e98SJosef Bacik __tree_mod_log_rewind(struct btrfs_fs_info *fs_info, struct extent_buffer *eb,
1188f1ca7e98SJosef Bacik 		      u64 time_seq, struct tree_mod_elem *first_tm)
11895d9e75c4SJan Schmidt {
11905d9e75c4SJan Schmidt 	u32 n;
11915d9e75c4SJan Schmidt 	struct rb_node *next;
11925d9e75c4SJan Schmidt 	struct tree_mod_elem *tm = first_tm;
11935d9e75c4SJan Schmidt 	unsigned long o_dst;
11945d9e75c4SJan Schmidt 	unsigned long o_src;
11955d9e75c4SJan Schmidt 	unsigned long p_size = sizeof(struct btrfs_key_ptr);
11965d9e75c4SJan Schmidt 
11975d9e75c4SJan Schmidt 	n = btrfs_header_nritems(eb);
1198b1a09f1eSDavid Sterba 	read_lock(&fs_info->tree_mod_log_lock);
1199097b8a7cSJan Schmidt 	while (tm && tm->seq >= time_seq) {
12005d9e75c4SJan Schmidt 		/*
12015d9e75c4SJan Schmidt 		 * all the operations are recorded with the operator used for
12025d9e75c4SJan Schmidt 		 * the modification. as we're going backwards, we do the
12035d9e75c4SJan Schmidt 		 * opposite of each operation here.
12045d9e75c4SJan Schmidt 		 */
12055d9e75c4SJan Schmidt 		switch (tm->op) {
12065d9e75c4SJan Schmidt 		case MOD_LOG_KEY_REMOVE_WHILE_FREEING:
12075d9e75c4SJan Schmidt 			BUG_ON(tm->slot < n);
1208c730ae0cSMarcos Paulo de Souza 			fallthrough;
120995c80bb1SLiu Bo 		case MOD_LOG_KEY_REMOVE_WHILE_MOVING:
12104c3e6969SChris Mason 		case MOD_LOG_KEY_REMOVE:
12115d9e75c4SJan Schmidt 			btrfs_set_node_key(eb, &tm->key, tm->slot);
12125d9e75c4SJan Schmidt 			btrfs_set_node_blockptr(eb, tm->slot, tm->blockptr);
12135d9e75c4SJan Schmidt 			btrfs_set_node_ptr_generation(eb, tm->slot,
12145d9e75c4SJan Schmidt 						      tm->generation);
12154c3e6969SChris Mason 			n++;
12165d9e75c4SJan Schmidt 			break;
12175d9e75c4SJan Schmidt 		case MOD_LOG_KEY_REPLACE:
12185d9e75c4SJan Schmidt 			BUG_ON(tm->slot >= n);
12195d9e75c4SJan Schmidt 			btrfs_set_node_key(eb, &tm->key, tm->slot);
12205d9e75c4SJan Schmidt 			btrfs_set_node_blockptr(eb, tm->slot, tm->blockptr);
12215d9e75c4SJan Schmidt 			btrfs_set_node_ptr_generation(eb, tm->slot,
12225d9e75c4SJan Schmidt 						      tm->generation);
12235d9e75c4SJan Schmidt 			break;
12245d9e75c4SJan Schmidt 		case MOD_LOG_KEY_ADD:
122519956c7eSJan Schmidt 			/* if a move operation is needed it's in the log */
12265d9e75c4SJan Schmidt 			n--;
12275d9e75c4SJan Schmidt 			break;
12285d9e75c4SJan Schmidt 		case MOD_LOG_MOVE_KEYS:
1229c3193108SJan Schmidt 			o_dst = btrfs_node_key_ptr_offset(tm->slot);
1230c3193108SJan Schmidt 			o_src = btrfs_node_key_ptr_offset(tm->move.dst_slot);
1231c3193108SJan Schmidt 			memmove_extent_buffer(eb, o_dst, o_src,
12325d9e75c4SJan Schmidt 					      tm->move.nr_items * p_size);
12335d9e75c4SJan Schmidt 			break;
12345d9e75c4SJan Schmidt 		case MOD_LOG_ROOT_REPLACE:
12355d9e75c4SJan Schmidt 			/*
12365d9e75c4SJan Schmidt 			 * this operation is special. for roots, this must be
12375d9e75c4SJan Schmidt 			 * handled explicitly before rewinding.
12385d9e75c4SJan Schmidt 			 * for non-roots, this operation may exist if the node
12395d9e75c4SJan Schmidt 			 * was a root: root A -> child B; then A gets empty and
12405d9e75c4SJan Schmidt 			 * B is promoted to the new root. in the mod log, we'll
12415d9e75c4SJan Schmidt 			 * have a root-replace operation for B, a tree block
12425d9e75c4SJan Schmidt 			 * that is no root. we simply ignore that operation.
12435d9e75c4SJan Schmidt 			 */
12445d9e75c4SJan Schmidt 			break;
12455d9e75c4SJan Schmidt 		}
12465d9e75c4SJan Schmidt 		next = rb_next(&tm->node);
12475d9e75c4SJan Schmidt 		if (!next)
12485d9e75c4SJan Schmidt 			break;
12496b4df8b6SGeliang Tang 		tm = rb_entry(next, struct tree_mod_elem, node);
1250298cfd36SChandan Rajendra 		if (tm->logical != first_tm->logical)
12515d9e75c4SJan Schmidt 			break;
12525d9e75c4SJan Schmidt 	}
1253b1a09f1eSDavid Sterba 	read_unlock(&fs_info->tree_mod_log_lock);
12545d9e75c4SJan Schmidt 	btrfs_set_header_nritems(eb, n);
12555d9e75c4SJan Schmidt }
12565d9e75c4SJan Schmidt 
125747fb091fSJan Schmidt /*
125801327610SNicholas D Steeves  * Called with eb read locked. If the buffer cannot be rewound, the same buffer
125947fb091fSJan Schmidt  * is returned. If rewind operations happen, a fresh buffer is returned. The
126047fb091fSJan Schmidt  * returned buffer is always read-locked. If the returned buffer is not the
126147fb091fSJan Schmidt  * input buffer, the lock on the input buffer is released and the input buffer
126247fb091fSJan Schmidt  * is freed (its refcount is decremented).
126347fb091fSJan Schmidt  */
12645d9e75c4SJan Schmidt static struct extent_buffer *
12659ec72677SJosef Bacik tree_mod_log_rewind(struct btrfs_fs_info *fs_info, struct btrfs_path *path,
12669ec72677SJosef Bacik 		    struct extent_buffer *eb, u64 time_seq)
12675d9e75c4SJan Schmidt {
12685d9e75c4SJan Schmidt 	struct extent_buffer *eb_rewin;
12695d9e75c4SJan Schmidt 	struct tree_mod_elem *tm;
12705d9e75c4SJan Schmidt 
12715d9e75c4SJan Schmidt 	if (!time_seq)
12725d9e75c4SJan Schmidt 		return eb;
12735d9e75c4SJan Schmidt 
12745d9e75c4SJan Schmidt 	if (btrfs_header_level(eb) == 0)
12755d9e75c4SJan Schmidt 		return eb;
12765d9e75c4SJan Schmidt 
12775d9e75c4SJan Schmidt 	tm = tree_mod_log_search(fs_info, eb->start, time_seq);
12785d9e75c4SJan Schmidt 	if (!tm)
12795d9e75c4SJan Schmidt 		return eb;
12805d9e75c4SJan Schmidt 
12815d9e75c4SJan Schmidt 	if (tm->op == MOD_LOG_KEY_REMOVE_WHILE_FREEING) {
12825d9e75c4SJan Schmidt 		BUG_ON(tm->slot != 0);
1283da17066cSJeff Mahoney 		eb_rewin = alloc_dummy_extent_buffer(fs_info, eb->start);
1284db7f3436SJosef Bacik 		if (!eb_rewin) {
1285ac5887c8SJosef Bacik 			btrfs_tree_read_unlock(eb);
1286db7f3436SJosef Bacik 			free_extent_buffer(eb);
1287db7f3436SJosef Bacik 			return NULL;
1288db7f3436SJosef Bacik 		}
12895d9e75c4SJan Schmidt 		btrfs_set_header_bytenr(eb_rewin, eb->start);
12905d9e75c4SJan Schmidt 		btrfs_set_header_backref_rev(eb_rewin,
12915d9e75c4SJan Schmidt 					     btrfs_header_backref_rev(eb));
12925d9e75c4SJan Schmidt 		btrfs_set_header_owner(eb_rewin, btrfs_header_owner(eb));
1293c3193108SJan Schmidt 		btrfs_set_header_level(eb_rewin, btrfs_header_level(eb));
12945d9e75c4SJan Schmidt 	} else {
12955d9e75c4SJan Schmidt 		eb_rewin = btrfs_clone_extent_buffer(eb);
1296db7f3436SJosef Bacik 		if (!eb_rewin) {
1297ac5887c8SJosef Bacik 			btrfs_tree_read_unlock(eb);
1298db7f3436SJosef Bacik 			free_extent_buffer(eb);
1299db7f3436SJosef Bacik 			return NULL;
1300db7f3436SJosef Bacik 		}
13015d9e75c4SJan Schmidt 	}
13025d9e75c4SJan Schmidt 
1303ac5887c8SJosef Bacik 	btrfs_tree_read_unlock(eb);
13045d9e75c4SJan Schmidt 	free_extent_buffer(eb);
13055d9e75c4SJan Schmidt 
1306d3beaa25SJosef Bacik 	btrfs_set_buffer_lockdep_class(btrfs_header_owner(eb_rewin),
1307d3beaa25SJosef Bacik 				       eb_rewin, btrfs_header_level(eb_rewin));
130847fb091fSJan Schmidt 	btrfs_tree_read_lock(eb_rewin);
1309f1ca7e98SJosef Bacik 	__tree_mod_log_rewind(fs_info, eb_rewin, time_seq, tm);
131057911b8bSJan Schmidt 	WARN_ON(btrfs_header_nritems(eb_rewin) >
1311da17066cSJeff Mahoney 		BTRFS_NODEPTRS_PER_BLOCK(fs_info));
13125d9e75c4SJan Schmidt 
13135d9e75c4SJan Schmidt 	return eb_rewin;
13145d9e75c4SJan Schmidt }
13155d9e75c4SJan Schmidt 
13168ba97a15SJan Schmidt /*
13178ba97a15SJan Schmidt  * get_old_root() rewinds the state of @root's root node to the given @time_seq
13188ba97a15SJan Schmidt  * value. If there are no changes, the current root->root_node is returned. If
13198ba97a15SJan Schmidt  * anything changed in between, there's a fresh buffer allocated on which the
13208ba97a15SJan Schmidt  * rewind operations are done. In any case, the returned buffer is read locked.
13218ba97a15SJan Schmidt  * Returns NULL on error (with no locks held).
13228ba97a15SJan Schmidt  */
13235d9e75c4SJan Schmidt static inline struct extent_buffer *
13245d9e75c4SJan Schmidt get_old_root(struct btrfs_root *root, u64 time_seq)
13255d9e75c4SJan Schmidt {
13260b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
13275d9e75c4SJan Schmidt 	struct tree_mod_elem *tm;
132830b0463aSJan Schmidt 	struct extent_buffer *eb = NULL;
132930b0463aSJan Schmidt 	struct extent_buffer *eb_root;
1330efad8a85SFilipe Manana 	u64 eb_root_owner = 0;
13317bfdcf7fSLiu Bo 	struct extent_buffer *old;
1332a95236d9SJan Schmidt 	struct tree_mod_root *old_root = NULL;
13334325edd0SChris Mason 	u64 old_generation = 0;
1334a95236d9SJan Schmidt 	u64 logical;
1335581c1760SQu Wenruo 	int level;
13365d9e75c4SJan Schmidt 
133730b0463aSJan Schmidt 	eb_root = btrfs_read_lock_root_node(root);
1338bcd24dabSDavid Sterba 	tm = __tree_mod_log_oldest_root(eb_root, time_seq);
13395d9e75c4SJan Schmidt 	if (!tm)
134030b0463aSJan Schmidt 		return eb_root;
13415d9e75c4SJan Schmidt 
1342a95236d9SJan Schmidt 	if (tm->op == MOD_LOG_ROOT_REPLACE) {
13435d9e75c4SJan Schmidt 		old_root = &tm->old_root;
13445d9e75c4SJan Schmidt 		old_generation = tm->generation;
1345a95236d9SJan Schmidt 		logical = old_root->logical;
1346581c1760SQu Wenruo 		level = old_root->level;
1347a95236d9SJan Schmidt 	} else {
134830b0463aSJan Schmidt 		logical = eb_root->start;
1349581c1760SQu Wenruo 		level = btrfs_header_level(eb_root);
1350a95236d9SJan Schmidt 	}
13515d9e75c4SJan Schmidt 
13520b246afaSJeff Mahoney 	tm = tree_mod_log_search(fs_info, logical, time_seq);
1353834328a8SJan Schmidt 	if (old_root && tm && tm->op != MOD_LOG_KEY_REMOVE_WHILE_FREEING) {
135430b0463aSJan Schmidt 		btrfs_tree_read_unlock(eb_root);
135530b0463aSJan Schmidt 		free_extent_buffer(eb_root);
1356581c1760SQu Wenruo 		old = read_tree_block(fs_info, logical, 0, level, NULL);
135764c043deSLiu Bo 		if (WARN_ON(IS_ERR(old) || !extent_buffer_uptodate(old))) {
135864c043deSLiu Bo 			if (!IS_ERR(old))
1359416bc658SJosef Bacik 				free_extent_buffer(old);
13600b246afaSJeff Mahoney 			btrfs_warn(fs_info,
13610b246afaSJeff Mahoney 				   "failed to read tree block %llu from get_old_root",
13620b246afaSJeff Mahoney 				   logical);
1363834328a8SJan Schmidt 		} else {
13647bfdcf7fSLiu Bo 			eb = btrfs_clone_extent_buffer(old);
13657bfdcf7fSLiu Bo 			free_extent_buffer(old);
1366834328a8SJan Schmidt 		}
1367834328a8SJan Schmidt 	} else if (old_root) {
1368efad8a85SFilipe Manana 		eb_root_owner = btrfs_header_owner(eb_root);
136930b0463aSJan Schmidt 		btrfs_tree_read_unlock(eb_root);
137030b0463aSJan Schmidt 		free_extent_buffer(eb_root);
13710b246afaSJeff Mahoney 		eb = alloc_dummy_extent_buffer(fs_info, logical);
1372834328a8SJan Schmidt 	} else {
137330b0463aSJan Schmidt 		eb = btrfs_clone_extent_buffer(eb_root);
1374ac5887c8SJosef Bacik 		btrfs_tree_read_unlock(eb_root);
137530b0463aSJan Schmidt 		free_extent_buffer(eb_root);
1376834328a8SJan Schmidt 	}
1377834328a8SJan Schmidt 
13788ba97a15SJan Schmidt 	if (!eb)
13798ba97a15SJan Schmidt 		return NULL;
1380a95236d9SJan Schmidt 	if (old_root) {
13815d9e75c4SJan Schmidt 		btrfs_set_header_bytenr(eb, eb->start);
13825d9e75c4SJan Schmidt 		btrfs_set_header_backref_rev(eb, BTRFS_MIXED_BACKREF_REV);
1383efad8a85SFilipe Manana 		btrfs_set_header_owner(eb, eb_root_owner);
13845d9e75c4SJan Schmidt 		btrfs_set_header_level(eb, old_root->level);
13855d9e75c4SJan Schmidt 		btrfs_set_header_generation(eb, old_generation);
1386a95236d9SJan Schmidt 	}
1387d3beaa25SJosef Bacik 	btrfs_set_buffer_lockdep_class(btrfs_header_owner(eb), eb,
1388d3beaa25SJosef Bacik 				       btrfs_header_level(eb));
1389d3beaa25SJosef Bacik 	btrfs_tree_read_lock(eb);
139028da9fb4SJan Schmidt 	if (tm)
13910b246afaSJeff Mahoney 		__tree_mod_log_rewind(fs_info, eb, time_seq, tm);
139228da9fb4SJan Schmidt 	else
139328da9fb4SJan Schmidt 		WARN_ON(btrfs_header_level(eb) != 0);
13940b246afaSJeff Mahoney 	WARN_ON(btrfs_header_nritems(eb) > BTRFS_NODEPTRS_PER_BLOCK(fs_info));
13955d9e75c4SJan Schmidt 
13965d9e75c4SJan Schmidt 	return eb;
13975d9e75c4SJan Schmidt }
13985d9e75c4SJan Schmidt 
13995b6602e7SJan Schmidt int btrfs_old_root_level(struct btrfs_root *root, u64 time_seq)
14005b6602e7SJan Schmidt {
14015b6602e7SJan Schmidt 	struct tree_mod_elem *tm;
14025b6602e7SJan Schmidt 	int level;
140330b0463aSJan Schmidt 	struct extent_buffer *eb_root = btrfs_root_node(root);
14045b6602e7SJan Schmidt 
1405bcd24dabSDavid Sterba 	tm = __tree_mod_log_oldest_root(eb_root, time_seq);
14065b6602e7SJan Schmidt 	if (tm && tm->op == MOD_LOG_ROOT_REPLACE) {
14075b6602e7SJan Schmidt 		level = tm->old_root.level;
14085b6602e7SJan Schmidt 	} else {
140930b0463aSJan Schmidt 		level = btrfs_header_level(eb_root);
14105b6602e7SJan Schmidt 	}
141130b0463aSJan Schmidt 	free_extent_buffer(eb_root);
14125b6602e7SJan Schmidt 
14135b6602e7SJan Schmidt 	return level;
14145b6602e7SJan Schmidt }
14155b6602e7SJan Schmidt 
14165d4f98a2SYan Zheng static inline int should_cow_block(struct btrfs_trans_handle *trans,
14175d4f98a2SYan Zheng 				   struct btrfs_root *root,
14185d4f98a2SYan Zheng 				   struct extent_buffer *buf)
14195d4f98a2SYan Zheng {
1420f5ee5c9aSJeff Mahoney 	if (btrfs_is_testing(root->fs_info))
1421faa2dbf0SJosef Bacik 		return 0;
1422fccb84c9SDavid Sterba 
1423d1980131SDavid Sterba 	/* Ensure we can see the FORCE_COW bit */
1424d1980131SDavid Sterba 	smp_mb__before_atomic();
1425f1ebcc74SLiu Bo 
1426f1ebcc74SLiu Bo 	/*
1427f1ebcc74SLiu Bo 	 * We do not need to cow a block if
1428f1ebcc74SLiu Bo 	 * 1) this block is not created or changed in this transaction;
1429f1ebcc74SLiu Bo 	 * 2) this block does not belong to TREE_RELOC tree;
1430f1ebcc74SLiu Bo 	 * 3) the root is not forced COW.
1431f1ebcc74SLiu Bo 	 *
1432f1ebcc74SLiu Bo 	 * What is forced COW:
143301327610SNicholas D Steeves 	 *    when we create snapshot during committing the transaction,
143452042d8eSAndrea Gelmini 	 *    after we've finished copying src root, we must COW the shared
1435f1ebcc74SLiu Bo 	 *    block to ensure the metadata consistency.
1436f1ebcc74SLiu Bo 	 */
14375d4f98a2SYan Zheng 	if (btrfs_header_generation(buf) == trans->transid &&
14385d4f98a2SYan Zheng 	    !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN) &&
14395d4f98a2SYan Zheng 	    !(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
1440f1ebcc74SLiu Bo 	      btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)) &&
144127cdeb70SMiao Xie 	    !test_bit(BTRFS_ROOT_FORCE_COW, &root->state))
14425d4f98a2SYan Zheng 		return 0;
14435d4f98a2SYan Zheng 	return 1;
14445d4f98a2SYan Zheng }
14455d4f98a2SYan Zheng 
1446d352ac68SChris Mason /*
1447d352ac68SChris Mason  * cows a single block, see __btrfs_cow_block for the real work.
144801327610SNicholas D Steeves  * This version of it has extra checks so that a block isn't COWed more than
1449d352ac68SChris Mason  * once per transaction, as long as it hasn't been written yet
1450d352ac68SChris Mason  */
1451d397712bSChris Mason noinline int btrfs_cow_block(struct btrfs_trans_handle *trans,
14525f39d397SChris Mason 		    struct btrfs_root *root, struct extent_buffer *buf,
14535f39d397SChris Mason 		    struct extent_buffer *parent, int parent_slot,
14549631e4ccSJosef Bacik 		    struct extent_buffer **cow_ret,
14559631e4ccSJosef Bacik 		    enum btrfs_lock_nesting nest)
145602217ed2SChris Mason {
14570b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
14586702ed49SChris Mason 	u64 search_start;
1459f510cfecSChris Mason 	int ret;
1460dc17ff8fSChris Mason 
146183354f07SJosef Bacik 	if (test_bit(BTRFS_ROOT_DELETING, &root->state))
146283354f07SJosef Bacik 		btrfs_err(fs_info,
146383354f07SJosef Bacik 			"COW'ing blocks on a fs root that's being dropped");
146483354f07SJosef Bacik 
14650b246afaSJeff Mahoney 	if (trans->transaction != fs_info->running_transaction)
146631b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "trans %llu running %llu\n",
1467c1c9ff7cSGeert Uytterhoeven 		       trans->transid,
14680b246afaSJeff Mahoney 		       fs_info->running_transaction->transid);
146931b1a2bdSJulia Lawall 
14700b246afaSJeff Mahoney 	if (trans->transid != fs_info->generation)
147131b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "trans %llu running %llu\n",
14720b246afaSJeff Mahoney 		       trans->transid, fs_info->generation);
1473dc17ff8fSChris Mason 
14745d4f98a2SYan Zheng 	if (!should_cow_block(trans, root, buf)) {
147564c12921SJeff Mahoney 		trans->dirty = true;
147602217ed2SChris Mason 		*cow_ret = buf;
147702217ed2SChris Mason 		return 0;
147802217ed2SChris Mason 	}
1479c487685dSChris Mason 
1480ee22184bSByongho Lee 	search_start = buf->start & ~((u64)SZ_1G - 1);
1481b4ce94deSChris Mason 
1482f616f5cdSQu Wenruo 	/*
1483f616f5cdSQu Wenruo 	 * Before CoWing this block for later modification, check if it's
1484f616f5cdSQu Wenruo 	 * the subtree root and do the delayed subtree trace if needed.
1485f616f5cdSQu Wenruo 	 *
1486f616f5cdSQu Wenruo 	 * Also We don't care about the error, as it's handled internally.
1487f616f5cdSQu Wenruo 	 */
1488f616f5cdSQu Wenruo 	btrfs_qgroup_trace_subtree_after_cow(trans, root, buf);
1489f510cfecSChris Mason 	ret = __btrfs_cow_block(trans, root, buf, parent,
14909631e4ccSJosef Bacik 				 parent_slot, cow_ret, search_start, 0, nest);
14911abe9b8aSliubo 
14921abe9b8aSliubo 	trace_btrfs_cow_block(root, buf, *cow_ret);
14931abe9b8aSliubo 
1494f510cfecSChris Mason 	return ret;
14952c90e5d6SChris Mason }
14966702ed49SChris Mason 
1497d352ac68SChris Mason /*
1498d352ac68SChris Mason  * helper function for defrag to decide if two blocks pointed to by a
1499d352ac68SChris Mason  * node are actually close by
1500d352ac68SChris Mason  */
15016b80053dSChris Mason static int close_blocks(u64 blocknr, u64 other, u32 blocksize)
15026702ed49SChris Mason {
15036b80053dSChris Mason 	if (blocknr < other && other - (blocknr + blocksize) < 32768)
15046702ed49SChris Mason 		return 1;
15056b80053dSChris Mason 	if (blocknr > other && blocknr - (other + blocksize) < 32768)
15066702ed49SChris Mason 		return 1;
150702217ed2SChris Mason 	return 0;
150802217ed2SChris Mason }
150902217ed2SChris Mason 
1510ce6ef5abSDavid Sterba #ifdef __LITTLE_ENDIAN
1511ce6ef5abSDavid Sterba 
1512ce6ef5abSDavid Sterba /*
1513ce6ef5abSDavid Sterba  * Compare two keys, on little-endian the disk order is same as CPU order and
1514ce6ef5abSDavid Sterba  * we can avoid the conversion.
1515ce6ef5abSDavid Sterba  */
1516ce6ef5abSDavid Sterba static int comp_keys(const struct btrfs_disk_key *disk_key,
1517ce6ef5abSDavid Sterba 		     const struct btrfs_key *k2)
1518ce6ef5abSDavid Sterba {
1519ce6ef5abSDavid Sterba 	const struct btrfs_key *k1 = (const struct btrfs_key *)disk_key;
1520ce6ef5abSDavid Sterba 
1521ce6ef5abSDavid Sterba 	return btrfs_comp_cpu_keys(k1, k2);
1522ce6ef5abSDavid Sterba }
1523ce6ef5abSDavid Sterba 
1524ce6ef5abSDavid Sterba #else
1525ce6ef5abSDavid Sterba 
1526081e9573SChris Mason /*
1527081e9573SChris Mason  * compare two keys in a memcmp fashion
1528081e9573SChris Mason  */
1529310712b2SOmar Sandoval static int comp_keys(const struct btrfs_disk_key *disk,
1530310712b2SOmar Sandoval 		     const struct btrfs_key *k2)
1531081e9573SChris Mason {
1532081e9573SChris Mason 	struct btrfs_key k1;
1533081e9573SChris Mason 
1534081e9573SChris Mason 	btrfs_disk_key_to_cpu(&k1, disk);
1535081e9573SChris Mason 
153620736abaSDiego Calleja 	return btrfs_comp_cpu_keys(&k1, k2);
1537081e9573SChris Mason }
1538ce6ef5abSDavid Sterba #endif
1539081e9573SChris Mason 
1540f3465ca4SJosef Bacik /*
1541f3465ca4SJosef Bacik  * same as comp_keys only with two btrfs_key's
1542f3465ca4SJosef Bacik  */
1543e1f60a65SDavid Sterba int __pure btrfs_comp_cpu_keys(const struct btrfs_key *k1, const struct btrfs_key *k2)
1544f3465ca4SJosef Bacik {
1545f3465ca4SJosef Bacik 	if (k1->objectid > k2->objectid)
1546f3465ca4SJosef Bacik 		return 1;
1547f3465ca4SJosef Bacik 	if (k1->objectid < k2->objectid)
1548f3465ca4SJosef Bacik 		return -1;
1549f3465ca4SJosef Bacik 	if (k1->type > k2->type)
1550f3465ca4SJosef Bacik 		return 1;
1551f3465ca4SJosef Bacik 	if (k1->type < k2->type)
1552f3465ca4SJosef Bacik 		return -1;
1553f3465ca4SJosef Bacik 	if (k1->offset > k2->offset)
1554f3465ca4SJosef Bacik 		return 1;
1555f3465ca4SJosef Bacik 	if (k1->offset < k2->offset)
1556f3465ca4SJosef Bacik 		return -1;
1557f3465ca4SJosef Bacik 	return 0;
1558f3465ca4SJosef Bacik }
1559081e9573SChris Mason 
1560d352ac68SChris Mason /*
1561d352ac68SChris Mason  * this is used by the defrag code to go through all the
1562d352ac68SChris Mason  * leaves pointed to by a node and reallocate them so that
1563d352ac68SChris Mason  * disk order is close to key order
1564d352ac68SChris Mason  */
15656702ed49SChris Mason int btrfs_realloc_node(struct btrfs_trans_handle *trans,
15665f39d397SChris Mason 		       struct btrfs_root *root, struct extent_buffer *parent,
1567de78b51aSEric Sandeen 		       int start_slot, u64 *last_ret,
1568a6b6e75eSChris Mason 		       struct btrfs_key *progress)
15696702ed49SChris Mason {
15700b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
15716b80053dSChris Mason 	struct extent_buffer *cur;
15726702ed49SChris Mason 	u64 blocknr;
1573e9d0b13bSChris Mason 	u64 search_start = *last_ret;
1574e9d0b13bSChris Mason 	u64 last_block = 0;
15756702ed49SChris Mason 	u64 other;
15766702ed49SChris Mason 	u32 parent_nritems;
15776702ed49SChris Mason 	int end_slot;
15786702ed49SChris Mason 	int i;
15796702ed49SChris Mason 	int err = 0;
15806b80053dSChris Mason 	u32 blocksize;
1581081e9573SChris Mason 	int progress_passed = 0;
1582081e9573SChris Mason 	struct btrfs_disk_key disk_key;
15836702ed49SChris Mason 
15840b246afaSJeff Mahoney 	WARN_ON(trans->transaction != fs_info->running_transaction);
15850b246afaSJeff Mahoney 	WARN_ON(trans->transid != fs_info->generation);
158686479a04SChris Mason 
15876b80053dSChris Mason 	parent_nritems = btrfs_header_nritems(parent);
15880b246afaSJeff Mahoney 	blocksize = fs_info->nodesize;
15895dfe2be7SFilipe Manana 	end_slot = parent_nritems - 1;
15906702ed49SChris Mason 
15915dfe2be7SFilipe Manana 	if (parent_nritems <= 1)
15926702ed49SChris Mason 		return 0;
15936702ed49SChris Mason 
15945dfe2be7SFilipe Manana 	for (i = start_slot; i <= end_slot; i++) {
15956702ed49SChris Mason 		int close = 1;
1596a6b6e75eSChris Mason 
1597081e9573SChris Mason 		btrfs_node_key(parent, &disk_key, i);
1598081e9573SChris Mason 		if (!progress_passed && comp_keys(&disk_key, progress) < 0)
1599081e9573SChris Mason 			continue;
1600081e9573SChris Mason 
1601081e9573SChris Mason 		progress_passed = 1;
16026b80053dSChris Mason 		blocknr = btrfs_node_blockptr(parent, i);
1603e9d0b13bSChris Mason 		if (last_block == 0)
1604e9d0b13bSChris Mason 			last_block = blocknr;
16055708b959SChris Mason 
16066702ed49SChris Mason 		if (i > 0) {
16076b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i - 1);
16086b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
16096702ed49SChris Mason 		}
16105dfe2be7SFilipe Manana 		if (!close && i < end_slot) {
16116b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i + 1);
16126b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
16136702ed49SChris Mason 		}
1614e9d0b13bSChris Mason 		if (close) {
1615e9d0b13bSChris Mason 			last_block = blocknr;
16166702ed49SChris Mason 			continue;
1617e9d0b13bSChris Mason 		}
16186702ed49SChris Mason 
1619*206983b7SJosef Bacik 		cur = btrfs_read_node_slot(parent, i);
1620*206983b7SJosef Bacik 		if (IS_ERR(cur))
162164c043deSLiu Bo 			return PTR_ERR(cur);
1622e9d0b13bSChris Mason 		if (search_start == 0)
16236b80053dSChris Mason 			search_start = last_block;
1624e9d0b13bSChris Mason 
1625e7a84565SChris Mason 		btrfs_tree_lock(cur);
16266b80053dSChris Mason 		err = __btrfs_cow_block(trans, root, cur, parent, i,
1627e7a84565SChris Mason 					&cur, search_start,
16286b80053dSChris Mason 					min(16 * blocksize,
16299631e4ccSJosef Bacik 					    (end_slot - i) * blocksize),
16309631e4ccSJosef Bacik 					BTRFS_NESTING_COW);
1631252c38f0SYan 		if (err) {
1632e7a84565SChris Mason 			btrfs_tree_unlock(cur);
16336b80053dSChris Mason 			free_extent_buffer(cur);
16346702ed49SChris Mason 			break;
1635252c38f0SYan 		}
1636e7a84565SChris Mason 		search_start = cur->start;
1637e7a84565SChris Mason 		last_block = cur->start;
1638f2183bdeSChris Mason 		*last_ret = search_start;
1639e7a84565SChris Mason 		btrfs_tree_unlock(cur);
1640e7a84565SChris Mason 		free_extent_buffer(cur);
16416702ed49SChris Mason 	}
16426702ed49SChris Mason 	return err;
16436702ed49SChris Mason }
16446702ed49SChris Mason 
164574123bd7SChris Mason /*
16465f39d397SChris Mason  * search for key in the extent_buffer.  The items start at offset p,
16475f39d397SChris Mason  * and they are item_size apart.  There are 'max' items in p.
16485f39d397SChris Mason  *
164974123bd7SChris Mason  * the slot in the array is returned via slot, and it points to
165074123bd7SChris Mason  * the place where you would insert key if it is not found in
165174123bd7SChris Mason  * the array.
165274123bd7SChris Mason  *
165374123bd7SChris Mason  * slot may point to max if the key is bigger than all of the keys
165474123bd7SChris Mason  */
1655e02119d5SChris Mason static noinline int generic_bin_search(struct extent_buffer *eb,
1656310712b2SOmar Sandoval 				       unsigned long p, int item_size,
1657310712b2SOmar Sandoval 				       const struct btrfs_key *key,
1658be0e5c09SChris Mason 				       int max, int *slot)
1659be0e5c09SChris Mason {
1660be0e5c09SChris Mason 	int low = 0;
1661be0e5c09SChris Mason 	int high = max;
1662be0e5c09SChris Mason 	int ret;
16635cd17f34SDavid Sterba 	const int key_size = sizeof(struct btrfs_disk_key);
1664be0e5c09SChris Mason 
16655e24e9afSLiu Bo 	if (low > high) {
16665e24e9afSLiu Bo 		btrfs_err(eb->fs_info,
16675e24e9afSLiu Bo 		 "%s: low (%d) > high (%d) eb %llu owner %llu level %d",
16685e24e9afSLiu Bo 			  __func__, low, high, eb->start,
16695e24e9afSLiu Bo 			  btrfs_header_owner(eb), btrfs_header_level(eb));
16705e24e9afSLiu Bo 		return -EINVAL;
16715e24e9afSLiu Bo 	}
16725e24e9afSLiu Bo 
1673be0e5c09SChris Mason 	while (low < high) {
16745cd17f34SDavid Sterba 		unsigned long oip;
16755cd17f34SDavid Sterba 		unsigned long offset;
16765cd17f34SDavid Sterba 		struct btrfs_disk_key *tmp;
16775cd17f34SDavid Sterba 		struct btrfs_disk_key unaligned;
16785cd17f34SDavid Sterba 		int mid;
16795cd17f34SDavid Sterba 
1680be0e5c09SChris Mason 		mid = (low + high) / 2;
16815f39d397SChris Mason 		offset = p + mid * item_size;
16825cd17f34SDavid Sterba 		oip = offset_in_page(offset);
16835f39d397SChris Mason 
16845cd17f34SDavid Sterba 		if (oip + key_size <= PAGE_SIZE) {
16855cd17f34SDavid Sterba 			const unsigned long idx = offset >> PAGE_SHIFT;
16865cd17f34SDavid Sterba 			char *kaddr = page_address(eb->pages[idx]);
1687934d375bSChris Mason 
16885cd17f34SDavid Sterba 			tmp = (struct btrfs_disk_key *)(kaddr + oip);
16895cd17f34SDavid Sterba 		} else {
16905cd17f34SDavid Sterba 			read_extent_buffer(eb, &unaligned, offset, key_size);
16915f39d397SChris Mason 			tmp = &unaligned;
1692479965d6SChris Mason 		}
1693479965d6SChris Mason 
1694be0e5c09SChris Mason 		ret = comp_keys(tmp, key);
1695be0e5c09SChris Mason 
1696be0e5c09SChris Mason 		if (ret < 0)
1697be0e5c09SChris Mason 			low = mid + 1;
1698be0e5c09SChris Mason 		else if (ret > 0)
1699be0e5c09SChris Mason 			high = mid;
1700be0e5c09SChris Mason 		else {
1701be0e5c09SChris Mason 			*slot = mid;
1702be0e5c09SChris Mason 			return 0;
1703be0e5c09SChris Mason 		}
1704be0e5c09SChris Mason 	}
1705be0e5c09SChris Mason 	*slot = low;
1706be0e5c09SChris Mason 	return 1;
1707be0e5c09SChris Mason }
1708be0e5c09SChris Mason 
170997571fd0SChris Mason /*
171097571fd0SChris Mason  * simple bin_search frontend that does the right thing for
171197571fd0SChris Mason  * leaves vs nodes
171297571fd0SChris Mason  */
1713a74b35ecSNikolay Borisov int btrfs_bin_search(struct extent_buffer *eb, const struct btrfs_key *key,
1714e3b83361SQu Wenruo 		     int *slot)
1715be0e5c09SChris Mason {
1716e3b83361SQu Wenruo 	if (btrfs_header_level(eb) == 0)
17175f39d397SChris Mason 		return generic_bin_search(eb,
17185f39d397SChris Mason 					  offsetof(struct btrfs_leaf, items),
17190783fcfcSChris Mason 					  sizeof(struct btrfs_item),
17205f39d397SChris Mason 					  key, btrfs_header_nritems(eb),
17217518a238SChris Mason 					  slot);
1722f775738fSWang Sheng-Hui 	else
17235f39d397SChris Mason 		return generic_bin_search(eb,
17245f39d397SChris Mason 					  offsetof(struct btrfs_node, ptrs),
1725123abc88SChris Mason 					  sizeof(struct btrfs_key_ptr),
17265f39d397SChris Mason 					  key, btrfs_header_nritems(eb),
17277518a238SChris Mason 					  slot);
1728be0e5c09SChris Mason }
1729be0e5c09SChris Mason 
1730f0486c68SYan, Zheng static void root_add_used(struct btrfs_root *root, u32 size)
1731f0486c68SYan, Zheng {
1732f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
1733f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
1734f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) + size);
1735f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
1736f0486c68SYan, Zheng }
1737f0486c68SYan, Zheng 
1738f0486c68SYan, Zheng static void root_sub_used(struct btrfs_root *root, u32 size)
1739f0486c68SYan, Zheng {
1740f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
1741f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
1742f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) - size);
1743f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
1744f0486c68SYan, Zheng }
1745f0486c68SYan, Zheng 
1746d352ac68SChris Mason /* given a node and slot number, this reads the blocks it points to.  The
1747d352ac68SChris Mason  * extent buffer is returned with a reference taken (but unlocked).
1748d352ac68SChris Mason  */
17494b231ae4SDavid Sterba struct extent_buffer *btrfs_read_node_slot(struct extent_buffer *parent,
17504b231ae4SDavid Sterba 					   int slot)
1751bb803951SChris Mason {
1752ca7a79adSChris Mason 	int level = btrfs_header_level(parent);
1753416bc658SJosef Bacik 	struct extent_buffer *eb;
1754581c1760SQu Wenruo 	struct btrfs_key first_key;
1755416bc658SJosef Bacik 
1756fb770ae4SLiu Bo 	if (slot < 0 || slot >= btrfs_header_nritems(parent))
1757fb770ae4SLiu Bo 		return ERR_PTR(-ENOENT);
1758ca7a79adSChris Mason 
1759ca7a79adSChris Mason 	BUG_ON(level == 0);
1760ca7a79adSChris Mason 
1761581c1760SQu Wenruo 	btrfs_node_key_to_cpu(parent, &first_key, slot);
1762d0d20b0fSDavid Sterba 	eb = read_tree_block(parent->fs_info, btrfs_node_blockptr(parent, slot),
1763581c1760SQu Wenruo 			     btrfs_node_ptr_generation(parent, slot),
1764581c1760SQu Wenruo 			     level - 1, &first_key);
1765fb770ae4SLiu Bo 	if (!IS_ERR(eb) && !extent_buffer_uptodate(eb)) {
1766416bc658SJosef Bacik 		free_extent_buffer(eb);
1767fb770ae4SLiu Bo 		eb = ERR_PTR(-EIO);
1768416bc658SJosef Bacik 	}
1769416bc658SJosef Bacik 
1770416bc658SJosef Bacik 	return eb;
1771bb803951SChris Mason }
1772bb803951SChris Mason 
1773d352ac68SChris Mason /*
1774d352ac68SChris Mason  * node level balancing, used to make sure nodes are in proper order for
1775d352ac68SChris Mason  * item deletion.  We balance from the top down, so we have to make sure
1776d352ac68SChris Mason  * that a deletion won't leave an node completely empty later on.
1777d352ac68SChris Mason  */
1778e02119d5SChris Mason static noinline int balance_level(struct btrfs_trans_handle *trans,
177998ed5174SChris Mason 			 struct btrfs_root *root,
178098ed5174SChris Mason 			 struct btrfs_path *path, int level)
1781bb803951SChris Mason {
17820b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
17835f39d397SChris Mason 	struct extent_buffer *right = NULL;
17845f39d397SChris Mason 	struct extent_buffer *mid;
17855f39d397SChris Mason 	struct extent_buffer *left = NULL;
17865f39d397SChris Mason 	struct extent_buffer *parent = NULL;
1787bb803951SChris Mason 	int ret = 0;
1788bb803951SChris Mason 	int wret;
1789bb803951SChris Mason 	int pslot;
1790bb803951SChris Mason 	int orig_slot = path->slots[level];
179179f95c82SChris Mason 	u64 orig_ptr;
1792bb803951SChris Mason 
179398e6b1ebSLiu Bo 	ASSERT(level > 0);
1794bb803951SChris Mason 
17955f39d397SChris Mason 	mid = path->nodes[level];
1796b4ce94deSChris Mason 
1797ac5887c8SJosef Bacik 	WARN_ON(path->locks[level] != BTRFS_WRITE_LOCK);
17987bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
17997bb86316SChris Mason 
18001d4f8a0cSChris Mason 	orig_ptr = btrfs_node_blockptr(mid, orig_slot);
180179f95c82SChris Mason 
1802a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
18035f39d397SChris Mason 		parent = path->nodes[level + 1];
1804bb803951SChris Mason 		pslot = path->slots[level + 1];
1805a05a9bb1SLi Zefan 	}
1806bb803951SChris Mason 
180740689478SChris Mason 	/*
180840689478SChris Mason 	 * deal with the case where there is only one pointer in the root
180940689478SChris Mason 	 * by promoting the node below to a root
181040689478SChris Mason 	 */
18115f39d397SChris Mason 	if (!parent) {
18125f39d397SChris Mason 		struct extent_buffer *child;
1813bb803951SChris Mason 
18145f39d397SChris Mason 		if (btrfs_header_nritems(mid) != 1)
1815bb803951SChris Mason 			return 0;
1816bb803951SChris Mason 
1817bb803951SChris Mason 		/* promote the child to a root */
18184b231ae4SDavid Sterba 		child = btrfs_read_node_slot(mid, 0);
1819fb770ae4SLiu Bo 		if (IS_ERR(child)) {
1820fb770ae4SLiu Bo 			ret = PTR_ERR(child);
18210b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
1822305a26afSMark Fasheh 			goto enospc;
1823305a26afSMark Fasheh 		}
1824305a26afSMark Fasheh 
1825925baeddSChris Mason 		btrfs_tree_lock(child);
18269631e4ccSJosef Bacik 		ret = btrfs_cow_block(trans, root, child, mid, 0, &child,
18279631e4ccSJosef Bacik 				      BTRFS_NESTING_COW);
1828f0486c68SYan, Zheng 		if (ret) {
1829f0486c68SYan, Zheng 			btrfs_tree_unlock(child);
1830f0486c68SYan, Zheng 			free_extent_buffer(child);
1831f0486c68SYan, Zheng 			goto enospc;
1832f0486c68SYan, Zheng 		}
18332f375ab9SYan 
1834d9d19a01SDavid Sterba 		ret = tree_mod_log_insert_root(root->node, child, 1);
1835d9d19a01SDavid Sterba 		BUG_ON(ret < 0);
1836240f62c8SChris Mason 		rcu_assign_pointer(root->node, child);
1837925baeddSChris Mason 
18380b86a832SChris Mason 		add_root_to_dirty_list(root);
1839925baeddSChris Mason 		btrfs_tree_unlock(child);
1840b4ce94deSChris Mason 
1841925baeddSChris Mason 		path->locks[level] = 0;
1842bb803951SChris Mason 		path->nodes[level] = NULL;
18436a884d7dSDavid Sterba 		btrfs_clean_tree_block(mid);
1844925baeddSChris Mason 		btrfs_tree_unlock(mid);
1845bb803951SChris Mason 		/* once for the path */
18465f39d397SChris Mason 		free_extent_buffer(mid);
1847f0486c68SYan, Zheng 
1848f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
18495581a51aSJan Schmidt 		btrfs_free_tree_block(trans, root, mid, 0, 1);
1850bb803951SChris Mason 		/* once for the root ptr */
18513083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
1852f0486c68SYan, Zheng 		return 0;
1853bb803951SChris Mason 	}
18545f39d397SChris Mason 	if (btrfs_header_nritems(mid) >
18550b246afaSJeff Mahoney 	    BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 4)
1856bb803951SChris Mason 		return 0;
1857bb803951SChris Mason 
18584b231ae4SDavid Sterba 	left = btrfs_read_node_slot(parent, pslot - 1);
1859fb770ae4SLiu Bo 	if (IS_ERR(left))
1860fb770ae4SLiu Bo 		left = NULL;
1861fb770ae4SLiu Bo 
18625f39d397SChris Mason 	if (left) {
1863bf77467aSJosef Bacik 		__btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
18645f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, left,
18659631e4ccSJosef Bacik 				       parent, pslot - 1, &left,
1866bf59a5a2SJosef Bacik 				       BTRFS_NESTING_LEFT_COW);
186754aa1f4dSChris Mason 		if (wret) {
186854aa1f4dSChris Mason 			ret = wret;
186954aa1f4dSChris Mason 			goto enospc;
187054aa1f4dSChris Mason 		}
18712cc58cf2SChris Mason 	}
1872fb770ae4SLiu Bo 
18734b231ae4SDavid Sterba 	right = btrfs_read_node_slot(parent, pslot + 1);
1874fb770ae4SLiu Bo 	if (IS_ERR(right))
1875fb770ae4SLiu Bo 		right = NULL;
1876fb770ae4SLiu Bo 
18775f39d397SChris Mason 	if (right) {
1878bf77467aSJosef Bacik 		__btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
18795f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, right,
18809631e4ccSJosef Bacik 				       parent, pslot + 1, &right,
1881bf59a5a2SJosef Bacik 				       BTRFS_NESTING_RIGHT_COW);
18822cc58cf2SChris Mason 		if (wret) {
18832cc58cf2SChris Mason 			ret = wret;
18842cc58cf2SChris Mason 			goto enospc;
18852cc58cf2SChris Mason 		}
18862cc58cf2SChris Mason 	}
18872cc58cf2SChris Mason 
18882cc58cf2SChris Mason 	/* first, try to make some room in the middle buffer */
18895f39d397SChris Mason 	if (left) {
18905f39d397SChris Mason 		orig_slot += btrfs_header_nritems(left);
1891d30a668fSDavid Sterba 		wret = push_node_left(trans, left, mid, 1);
189279f95c82SChris Mason 		if (wret < 0)
189379f95c82SChris Mason 			ret = wret;
1894bb803951SChris Mason 	}
189579f95c82SChris Mason 
189679f95c82SChris Mason 	/*
189779f95c82SChris Mason 	 * then try to empty the right most buffer into the middle
189879f95c82SChris Mason 	 */
18995f39d397SChris Mason 	if (right) {
1900d30a668fSDavid Sterba 		wret = push_node_left(trans, mid, right, 1);
190154aa1f4dSChris Mason 		if (wret < 0 && wret != -ENOSPC)
190279f95c82SChris Mason 			ret = wret;
19035f39d397SChris Mason 		if (btrfs_header_nritems(right) == 0) {
19046a884d7dSDavid Sterba 			btrfs_clean_tree_block(right);
1905925baeddSChris Mason 			btrfs_tree_unlock(right);
1906afe5fea7STsutomu Itoh 			del_ptr(root, path, level + 1, pslot + 1);
1907f0486c68SYan, Zheng 			root_sub_used(root, right->len);
19085581a51aSJan Schmidt 			btrfs_free_tree_block(trans, root, right, 0, 1);
19093083ee2eSJosef Bacik 			free_extent_buffer_stale(right);
1910f0486c68SYan, Zheng 			right = NULL;
1911bb803951SChris Mason 		} else {
19125f39d397SChris Mason 			struct btrfs_disk_key right_key;
19135f39d397SChris Mason 			btrfs_node_key(right, &right_key, 0);
19140e82bcfeSDavid Sterba 			ret = tree_mod_log_insert_key(parent, pslot + 1,
19150e82bcfeSDavid Sterba 					MOD_LOG_KEY_REPLACE, GFP_NOFS);
19160e82bcfeSDavid Sterba 			BUG_ON(ret < 0);
19175f39d397SChris Mason 			btrfs_set_node_key(parent, &right_key, pslot + 1);
19185f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
1919bb803951SChris Mason 		}
1920bb803951SChris Mason 	}
19215f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 1) {
192279f95c82SChris Mason 		/*
192379f95c82SChris Mason 		 * we're not allowed to leave a node with one item in the
192479f95c82SChris Mason 		 * tree during a delete.  A deletion from lower in the tree
192579f95c82SChris Mason 		 * could try to delete the only pointer in this node.
192679f95c82SChris Mason 		 * So, pull some keys from the left.
192779f95c82SChris Mason 		 * There has to be a left pointer at this point because
192879f95c82SChris Mason 		 * otherwise we would have pulled some pointers from the
192979f95c82SChris Mason 		 * right
193079f95c82SChris Mason 		 */
1931305a26afSMark Fasheh 		if (!left) {
1932305a26afSMark Fasheh 			ret = -EROFS;
19330b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
1934305a26afSMark Fasheh 			goto enospc;
1935305a26afSMark Fasheh 		}
193655d32ed8SDavid Sterba 		wret = balance_node_right(trans, mid, left);
193754aa1f4dSChris Mason 		if (wret < 0) {
193879f95c82SChris Mason 			ret = wret;
193954aa1f4dSChris Mason 			goto enospc;
194054aa1f4dSChris Mason 		}
1941bce4eae9SChris Mason 		if (wret == 1) {
1942d30a668fSDavid Sterba 			wret = push_node_left(trans, left, mid, 1);
1943bce4eae9SChris Mason 			if (wret < 0)
1944bce4eae9SChris Mason 				ret = wret;
1945bce4eae9SChris Mason 		}
194679f95c82SChris Mason 		BUG_ON(wret == 1);
194779f95c82SChris Mason 	}
19485f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 0) {
19496a884d7dSDavid Sterba 		btrfs_clean_tree_block(mid);
1950925baeddSChris Mason 		btrfs_tree_unlock(mid);
1951afe5fea7STsutomu Itoh 		del_ptr(root, path, level + 1, pslot);
1952f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
19535581a51aSJan Schmidt 		btrfs_free_tree_block(trans, root, mid, 0, 1);
19543083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
1955f0486c68SYan, Zheng 		mid = NULL;
195679f95c82SChris Mason 	} else {
195779f95c82SChris Mason 		/* update the parent key to reflect our changes */
19585f39d397SChris Mason 		struct btrfs_disk_key mid_key;
19595f39d397SChris Mason 		btrfs_node_key(mid, &mid_key, 0);
19600e82bcfeSDavid Sterba 		ret = tree_mod_log_insert_key(parent, pslot,
19610e82bcfeSDavid Sterba 				MOD_LOG_KEY_REPLACE, GFP_NOFS);
19620e82bcfeSDavid Sterba 		BUG_ON(ret < 0);
19635f39d397SChris Mason 		btrfs_set_node_key(parent, &mid_key, pslot);
19645f39d397SChris Mason 		btrfs_mark_buffer_dirty(parent);
196579f95c82SChris Mason 	}
1966bb803951SChris Mason 
196779f95c82SChris Mason 	/* update the path */
19685f39d397SChris Mason 	if (left) {
19695f39d397SChris Mason 		if (btrfs_header_nritems(left) > orig_slot) {
197067439dadSDavid Sterba 			atomic_inc(&left->refs);
1971925baeddSChris Mason 			/* left was locked after cow */
19725f39d397SChris Mason 			path->nodes[level] = left;
1973bb803951SChris Mason 			path->slots[level + 1] -= 1;
1974bb803951SChris Mason 			path->slots[level] = orig_slot;
1975925baeddSChris Mason 			if (mid) {
1976925baeddSChris Mason 				btrfs_tree_unlock(mid);
19775f39d397SChris Mason 				free_extent_buffer(mid);
1978925baeddSChris Mason 			}
1979bb803951SChris Mason 		} else {
19805f39d397SChris Mason 			orig_slot -= btrfs_header_nritems(left);
1981bb803951SChris Mason 			path->slots[level] = orig_slot;
1982bb803951SChris Mason 		}
1983bb803951SChris Mason 	}
198479f95c82SChris Mason 	/* double check we haven't messed things up */
1985e20d96d6SChris Mason 	if (orig_ptr !=
19865f39d397SChris Mason 	    btrfs_node_blockptr(path->nodes[level], path->slots[level]))
198779f95c82SChris Mason 		BUG();
198854aa1f4dSChris Mason enospc:
1989925baeddSChris Mason 	if (right) {
1990925baeddSChris Mason 		btrfs_tree_unlock(right);
19915f39d397SChris Mason 		free_extent_buffer(right);
1992925baeddSChris Mason 	}
1993925baeddSChris Mason 	if (left) {
1994925baeddSChris Mason 		if (path->nodes[level] != left)
1995925baeddSChris Mason 			btrfs_tree_unlock(left);
19965f39d397SChris Mason 		free_extent_buffer(left);
1997925baeddSChris Mason 	}
1998bb803951SChris Mason 	return ret;
1999bb803951SChris Mason }
2000bb803951SChris Mason 
2001d352ac68SChris Mason /* Node balancing for insertion.  Here we only split or push nodes around
2002d352ac68SChris Mason  * when they are completely full.  This is also done top down, so we
2003d352ac68SChris Mason  * have to be pessimistic.
2004d352ac68SChris Mason  */
2005d397712bSChris Mason static noinline int push_nodes_for_insert(struct btrfs_trans_handle *trans,
2006e66f709bSChris Mason 					  struct btrfs_root *root,
2007e66f709bSChris Mason 					  struct btrfs_path *path, int level)
2008e66f709bSChris Mason {
20090b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
20105f39d397SChris Mason 	struct extent_buffer *right = NULL;
20115f39d397SChris Mason 	struct extent_buffer *mid;
20125f39d397SChris Mason 	struct extent_buffer *left = NULL;
20135f39d397SChris Mason 	struct extent_buffer *parent = NULL;
2014e66f709bSChris Mason 	int ret = 0;
2015e66f709bSChris Mason 	int wret;
2016e66f709bSChris Mason 	int pslot;
2017e66f709bSChris Mason 	int orig_slot = path->slots[level];
2018e66f709bSChris Mason 
2019e66f709bSChris Mason 	if (level == 0)
2020e66f709bSChris Mason 		return 1;
2021e66f709bSChris Mason 
20225f39d397SChris Mason 	mid = path->nodes[level];
20237bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
2024e66f709bSChris Mason 
2025a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
20265f39d397SChris Mason 		parent = path->nodes[level + 1];
2027e66f709bSChris Mason 		pslot = path->slots[level + 1];
2028a05a9bb1SLi Zefan 	}
2029e66f709bSChris Mason 
20305f39d397SChris Mason 	if (!parent)
2031e66f709bSChris Mason 		return 1;
2032e66f709bSChris Mason 
20334b231ae4SDavid Sterba 	left = btrfs_read_node_slot(parent, pslot - 1);
2034fb770ae4SLiu Bo 	if (IS_ERR(left))
2035fb770ae4SLiu Bo 		left = NULL;
2036e66f709bSChris Mason 
2037e66f709bSChris Mason 	/* first, try to make some room in the middle buffer */
20385f39d397SChris Mason 	if (left) {
2039e66f709bSChris Mason 		u32 left_nr;
2040925baeddSChris Mason 
2041bf77467aSJosef Bacik 		__btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
2042b4ce94deSChris Mason 
20435f39d397SChris Mason 		left_nr = btrfs_header_nritems(left);
20440b246afaSJeff Mahoney 		if (left_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
204533ade1f8SChris Mason 			wret = 1;
204633ade1f8SChris Mason 		} else {
20475f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, left, parent,
20489631e4ccSJosef Bacik 					      pslot - 1, &left,
2049bf59a5a2SJosef Bacik 					      BTRFS_NESTING_LEFT_COW);
205054aa1f4dSChris Mason 			if (ret)
205154aa1f4dSChris Mason 				wret = 1;
205254aa1f4dSChris Mason 			else {
2053d30a668fSDavid Sterba 				wret = push_node_left(trans, left, mid, 0);
205454aa1f4dSChris Mason 			}
205533ade1f8SChris Mason 		}
2056e66f709bSChris Mason 		if (wret < 0)
2057e66f709bSChris Mason 			ret = wret;
2058e66f709bSChris Mason 		if (wret == 0) {
20595f39d397SChris Mason 			struct btrfs_disk_key disk_key;
2060e66f709bSChris Mason 			orig_slot += left_nr;
20615f39d397SChris Mason 			btrfs_node_key(mid, &disk_key, 0);
20620e82bcfeSDavid Sterba 			ret = tree_mod_log_insert_key(parent, pslot,
20630e82bcfeSDavid Sterba 					MOD_LOG_KEY_REPLACE, GFP_NOFS);
20640e82bcfeSDavid Sterba 			BUG_ON(ret < 0);
20655f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot);
20665f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
20675f39d397SChris Mason 			if (btrfs_header_nritems(left) > orig_slot) {
20685f39d397SChris Mason 				path->nodes[level] = left;
2069e66f709bSChris Mason 				path->slots[level + 1] -= 1;
2070e66f709bSChris Mason 				path->slots[level] = orig_slot;
2071925baeddSChris Mason 				btrfs_tree_unlock(mid);
20725f39d397SChris Mason 				free_extent_buffer(mid);
2073e66f709bSChris Mason 			} else {
2074e66f709bSChris Mason 				orig_slot -=
20755f39d397SChris Mason 					btrfs_header_nritems(left);
2076e66f709bSChris Mason 				path->slots[level] = orig_slot;
2077925baeddSChris Mason 				btrfs_tree_unlock(left);
20785f39d397SChris Mason 				free_extent_buffer(left);
2079e66f709bSChris Mason 			}
2080e66f709bSChris Mason 			return 0;
2081e66f709bSChris Mason 		}
2082925baeddSChris Mason 		btrfs_tree_unlock(left);
20835f39d397SChris Mason 		free_extent_buffer(left);
2084e66f709bSChris Mason 	}
20854b231ae4SDavid Sterba 	right = btrfs_read_node_slot(parent, pslot + 1);
2086fb770ae4SLiu Bo 	if (IS_ERR(right))
2087fb770ae4SLiu Bo 		right = NULL;
2088e66f709bSChris Mason 
2089e66f709bSChris Mason 	/*
2090e66f709bSChris Mason 	 * then try to empty the right most buffer into the middle
2091e66f709bSChris Mason 	 */
20925f39d397SChris Mason 	if (right) {
209333ade1f8SChris Mason 		u32 right_nr;
2094b4ce94deSChris Mason 
2095bf77467aSJosef Bacik 		__btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
2096b4ce94deSChris Mason 
20975f39d397SChris Mason 		right_nr = btrfs_header_nritems(right);
20980b246afaSJeff Mahoney 		if (right_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
209933ade1f8SChris Mason 			wret = 1;
210033ade1f8SChris Mason 		} else {
21015f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, right,
21025f39d397SChris Mason 					      parent, pslot + 1,
2103bf59a5a2SJosef Bacik 					      &right, BTRFS_NESTING_RIGHT_COW);
210454aa1f4dSChris Mason 			if (ret)
210554aa1f4dSChris Mason 				wret = 1;
210654aa1f4dSChris Mason 			else {
210755d32ed8SDavid Sterba 				wret = balance_node_right(trans, right, mid);
210833ade1f8SChris Mason 			}
210954aa1f4dSChris Mason 		}
2110e66f709bSChris Mason 		if (wret < 0)
2111e66f709bSChris Mason 			ret = wret;
2112e66f709bSChris Mason 		if (wret == 0) {
21135f39d397SChris Mason 			struct btrfs_disk_key disk_key;
21145f39d397SChris Mason 
21155f39d397SChris Mason 			btrfs_node_key(right, &disk_key, 0);
21160e82bcfeSDavid Sterba 			ret = tree_mod_log_insert_key(parent, pslot + 1,
21170e82bcfeSDavid Sterba 					MOD_LOG_KEY_REPLACE, GFP_NOFS);
21180e82bcfeSDavid Sterba 			BUG_ON(ret < 0);
21195f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot + 1);
21205f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
21215f39d397SChris Mason 
21225f39d397SChris Mason 			if (btrfs_header_nritems(mid) <= orig_slot) {
21235f39d397SChris Mason 				path->nodes[level] = right;
2124e66f709bSChris Mason 				path->slots[level + 1] += 1;
2125e66f709bSChris Mason 				path->slots[level] = orig_slot -
21265f39d397SChris Mason 					btrfs_header_nritems(mid);
2127925baeddSChris Mason 				btrfs_tree_unlock(mid);
21285f39d397SChris Mason 				free_extent_buffer(mid);
2129e66f709bSChris Mason 			} else {
2130925baeddSChris Mason 				btrfs_tree_unlock(right);
21315f39d397SChris Mason 				free_extent_buffer(right);
2132e66f709bSChris Mason 			}
2133e66f709bSChris Mason 			return 0;
2134e66f709bSChris Mason 		}
2135925baeddSChris Mason 		btrfs_tree_unlock(right);
21365f39d397SChris Mason 		free_extent_buffer(right);
2137e66f709bSChris Mason 	}
2138e66f709bSChris Mason 	return 1;
2139e66f709bSChris Mason }
2140e66f709bSChris Mason 
214174123bd7SChris Mason /*
2142d352ac68SChris Mason  * readahead one full node of leaves, finding things that are close
2143d352ac68SChris Mason  * to the block in 'slot', and triggering ra on them.
21443c69faecSChris Mason  */
21452ff7e61eSJeff Mahoney static void reada_for_search(struct btrfs_fs_info *fs_info,
2146e02119d5SChris Mason 			     struct btrfs_path *path,
214701f46658SChris Mason 			     int level, int slot, u64 objectid)
21483c69faecSChris Mason {
21495f39d397SChris Mason 	struct extent_buffer *node;
215001f46658SChris Mason 	struct btrfs_disk_key disk_key;
21513c69faecSChris Mason 	u32 nritems;
21523c69faecSChris Mason 	u64 search;
2153a7175319SChris Mason 	u64 target;
21546b80053dSChris Mason 	u64 nread = 0;
21555f39d397SChris Mason 	struct extent_buffer *eb;
21566b80053dSChris Mason 	u32 nr;
21576b80053dSChris Mason 	u32 blocksize;
21586b80053dSChris Mason 	u32 nscan = 0;
2159db94535dSChris Mason 
2160a6b6e75eSChris Mason 	if (level != 1)
21613c69faecSChris Mason 		return;
21623c69faecSChris Mason 
21636702ed49SChris Mason 	if (!path->nodes[level])
21646702ed49SChris Mason 		return;
21656702ed49SChris Mason 
21665f39d397SChris Mason 	node = path->nodes[level];
2167925baeddSChris Mason 
21683c69faecSChris Mason 	search = btrfs_node_blockptr(node, slot);
21690b246afaSJeff Mahoney 	blocksize = fs_info->nodesize;
21700b246afaSJeff Mahoney 	eb = find_extent_buffer(fs_info, search);
21715f39d397SChris Mason 	if (eb) {
21725f39d397SChris Mason 		free_extent_buffer(eb);
21733c69faecSChris Mason 		return;
21743c69faecSChris Mason 	}
21753c69faecSChris Mason 
2176a7175319SChris Mason 	target = search;
21776b80053dSChris Mason 
21785f39d397SChris Mason 	nritems = btrfs_header_nritems(node);
21796b80053dSChris Mason 	nr = slot;
218025b8b936SJosef Bacik 
21813c69faecSChris Mason 	while (1) {
2182e4058b54SDavid Sterba 		if (path->reada == READA_BACK) {
21836b80053dSChris Mason 			if (nr == 0)
21843c69faecSChris Mason 				break;
21856b80053dSChris Mason 			nr--;
2186e4058b54SDavid Sterba 		} else if (path->reada == READA_FORWARD) {
21876b80053dSChris Mason 			nr++;
21886b80053dSChris Mason 			if (nr >= nritems)
21896b80053dSChris Mason 				break;
21903c69faecSChris Mason 		}
2191e4058b54SDavid Sterba 		if (path->reada == READA_BACK && objectid) {
219201f46658SChris Mason 			btrfs_node_key(node, &disk_key, nr);
219301f46658SChris Mason 			if (btrfs_disk_key_objectid(&disk_key) != objectid)
219401f46658SChris Mason 				break;
219501f46658SChris Mason 		}
21966b80053dSChris Mason 		search = btrfs_node_blockptr(node, nr);
2197a7175319SChris Mason 		if ((search <= target && target - search <= 65536) ||
2198a7175319SChris Mason 		    (search > target && search - target <= 65536)) {
2199bfb484d9SJosef Bacik 			btrfs_readahead_node_child(node, nr);
22006b80053dSChris Mason 			nread += blocksize;
22013c69faecSChris Mason 		}
22026b80053dSChris Mason 		nscan++;
2203a7175319SChris Mason 		if ((nread > 65536 || nscan > 32))
22046b80053dSChris Mason 			break;
22053c69faecSChris Mason 	}
22063c69faecSChris Mason }
2207925baeddSChris Mason 
2208bfb484d9SJosef Bacik static noinline void reada_for_balance(struct btrfs_path *path, int level)
2209b4ce94deSChris Mason {
2210bfb484d9SJosef Bacik 	struct extent_buffer *parent;
2211b4ce94deSChris Mason 	int slot;
2212b4ce94deSChris Mason 	int nritems;
2213b4ce94deSChris Mason 
22148c594ea8SChris Mason 	parent = path->nodes[level + 1];
2215b4ce94deSChris Mason 	if (!parent)
22160b08851fSJosef Bacik 		return;
2217b4ce94deSChris Mason 
2218b4ce94deSChris Mason 	nritems = btrfs_header_nritems(parent);
22198c594ea8SChris Mason 	slot = path->slots[level + 1];
2220b4ce94deSChris Mason 
2221bfb484d9SJosef Bacik 	if (slot > 0)
2222bfb484d9SJosef Bacik 		btrfs_readahead_node_child(parent, slot - 1);
2223bfb484d9SJosef Bacik 	if (slot + 1 < nritems)
2224bfb484d9SJosef Bacik 		btrfs_readahead_node_child(parent, slot + 1);
2225b4ce94deSChris Mason }
2226b4ce94deSChris Mason 
2227b4ce94deSChris Mason 
2228b4ce94deSChris Mason /*
2229d397712bSChris Mason  * when we walk down the tree, it is usually safe to unlock the higher layers
2230d397712bSChris Mason  * in the tree.  The exceptions are when our path goes through slot 0, because
2231d397712bSChris Mason  * operations on the tree might require changing key pointers higher up in the
2232d397712bSChris Mason  * tree.
2233d352ac68SChris Mason  *
2234d397712bSChris Mason  * callers might also have set path->keep_locks, which tells this code to keep
2235d397712bSChris Mason  * the lock if the path points to the last slot in the block.  This is part of
2236d397712bSChris Mason  * walking through the tree, and selecting the next slot in the higher block.
2237d352ac68SChris Mason  *
2238d397712bSChris Mason  * lowest_unlock sets the lowest level in the tree we're allowed to unlock.  so
2239d397712bSChris Mason  * if lowest_unlock is 1, level 0 won't be unlocked
2240d352ac68SChris Mason  */
2241e02119d5SChris Mason static noinline void unlock_up(struct btrfs_path *path, int level,
2242f7c79f30SChris Mason 			       int lowest_unlock, int min_write_lock_level,
2243f7c79f30SChris Mason 			       int *write_lock_level)
2244925baeddSChris Mason {
2245925baeddSChris Mason 	int i;
2246925baeddSChris Mason 	int skip_level = level;
2247051e1b9fSChris Mason 	int no_skips = 0;
2248925baeddSChris Mason 	struct extent_buffer *t;
2249925baeddSChris Mason 
2250925baeddSChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2251925baeddSChris Mason 		if (!path->nodes[i])
2252925baeddSChris Mason 			break;
2253925baeddSChris Mason 		if (!path->locks[i])
2254925baeddSChris Mason 			break;
2255051e1b9fSChris Mason 		if (!no_skips && path->slots[i] == 0) {
2256925baeddSChris Mason 			skip_level = i + 1;
2257925baeddSChris Mason 			continue;
2258925baeddSChris Mason 		}
2259051e1b9fSChris Mason 		if (!no_skips && path->keep_locks) {
2260925baeddSChris Mason 			u32 nritems;
2261925baeddSChris Mason 			t = path->nodes[i];
2262925baeddSChris Mason 			nritems = btrfs_header_nritems(t);
2263051e1b9fSChris Mason 			if (nritems < 1 || path->slots[i] >= nritems - 1) {
2264925baeddSChris Mason 				skip_level = i + 1;
2265925baeddSChris Mason 				continue;
2266925baeddSChris Mason 			}
2267925baeddSChris Mason 		}
2268051e1b9fSChris Mason 		if (skip_level < i && i >= lowest_unlock)
2269051e1b9fSChris Mason 			no_skips = 1;
2270051e1b9fSChris Mason 
2271925baeddSChris Mason 		t = path->nodes[i];
2272d80bb3f9SLiu Bo 		if (i >= lowest_unlock && i > skip_level) {
2273bd681513SChris Mason 			btrfs_tree_unlock_rw(t, path->locks[i]);
2274925baeddSChris Mason 			path->locks[i] = 0;
2275f7c79f30SChris Mason 			if (write_lock_level &&
2276f7c79f30SChris Mason 			    i > min_write_lock_level &&
2277f7c79f30SChris Mason 			    i <= *write_lock_level) {
2278f7c79f30SChris Mason 				*write_lock_level = i - 1;
2279f7c79f30SChris Mason 			}
2280925baeddSChris Mason 		}
2281925baeddSChris Mason 	}
2282925baeddSChris Mason }
2283925baeddSChris Mason 
22843c69faecSChris Mason /*
2285c8c42864SChris Mason  * helper function for btrfs_search_slot.  The goal is to find a block
2286c8c42864SChris Mason  * in cache without setting the path to blocking.  If we find the block
2287c8c42864SChris Mason  * we return zero and the path is unchanged.
2288c8c42864SChris Mason  *
2289c8c42864SChris Mason  * If we can't find the block, we set the path blocking and do some
2290c8c42864SChris Mason  * reada.  -EAGAIN is returned and the search must be repeated.
2291c8c42864SChris Mason  */
2292c8c42864SChris Mason static int
2293d07b8528SLiu Bo read_block_for_search(struct btrfs_root *root, struct btrfs_path *p,
2294c8c42864SChris Mason 		      struct extent_buffer **eb_ret, int level, int slot,
2295cda79c54SDavid Sterba 		      const struct btrfs_key *key)
2296c8c42864SChris Mason {
22970b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
2298c8c42864SChris Mason 	u64 blocknr;
2299c8c42864SChris Mason 	u64 gen;
2300c8c42864SChris Mason 	struct extent_buffer *tmp;
2301581c1760SQu Wenruo 	struct btrfs_key first_key;
230276a05b35SChris Mason 	int ret;
2303581c1760SQu Wenruo 	int parent_level;
2304c8c42864SChris Mason 
2305213ff4b7SNikolay Borisov 	blocknr = btrfs_node_blockptr(*eb_ret, slot);
2306213ff4b7SNikolay Borisov 	gen = btrfs_node_ptr_generation(*eb_ret, slot);
2307213ff4b7SNikolay Borisov 	parent_level = btrfs_header_level(*eb_ret);
2308213ff4b7SNikolay Borisov 	btrfs_node_key_to_cpu(*eb_ret, &first_key, slot);
2309c8c42864SChris Mason 
23100b246afaSJeff Mahoney 	tmp = find_extent_buffer(fs_info, blocknr);
2311cb44921aSChris Mason 	if (tmp) {
2312b9fab919SChris Mason 		/* first we do an atomic uptodate check */
2313b9fab919SChris Mason 		if (btrfs_buffer_uptodate(tmp, gen, 1) > 0) {
2314448de471SQu Wenruo 			/*
2315448de471SQu Wenruo 			 * Do extra check for first_key, eb can be stale due to
2316448de471SQu Wenruo 			 * being cached, read from scrub, or have multiple
2317448de471SQu Wenruo 			 * parents (shared tree blocks).
2318448de471SQu Wenruo 			 */
2319e064d5e9SDavid Sterba 			if (btrfs_verify_level_key(tmp,
2320448de471SQu Wenruo 					parent_level - 1, &first_key, gen)) {
2321448de471SQu Wenruo 				free_extent_buffer(tmp);
2322448de471SQu Wenruo 				return -EUCLEAN;
2323448de471SQu Wenruo 			}
2324c8c42864SChris Mason 			*eb_ret = tmp;
2325c8c42864SChris Mason 			return 0;
2326c8c42864SChris Mason 		}
2327bdf7c00eSJosef Bacik 
2328b9fab919SChris Mason 		/* now we're allowed to do a blocking uptodate check */
2329581c1760SQu Wenruo 		ret = btrfs_read_buffer(tmp, gen, parent_level - 1, &first_key);
2330bdf7c00eSJosef Bacik 		if (!ret) {
2331cb44921aSChris Mason 			*eb_ret = tmp;
2332cb44921aSChris Mason 			return 0;
2333cb44921aSChris Mason 		}
2334cb44921aSChris Mason 		free_extent_buffer(tmp);
2335b3b4aa74SDavid Sterba 		btrfs_release_path(p);
2336cb44921aSChris Mason 		return -EIO;
2337cb44921aSChris Mason 	}
2338c8c42864SChris Mason 
2339c8c42864SChris Mason 	/*
2340c8c42864SChris Mason 	 * reduce lock contention at high levels
2341c8c42864SChris Mason 	 * of the btree by dropping locks before
234276a05b35SChris Mason 	 * we read.  Don't release the lock on the current
234376a05b35SChris Mason 	 * level because we need to walk this node to figure
234476a05b35SChris Mason 	 * out which blocks to read.
2345c8c42864SChris Mason 	 */
23468c594ea8SChris Mason 	btrfs_unlock_up_safe(p, level + 1);
23478c594ea8SChris Mason 
2348e4058b54SDavid Sterba 	if (p->reada != READA_NONE)
23492ff7e61eSJeff Mahoney 		reada_for_search(fs_info, p, level, slot, key->objectid);
2350c8c42864SChris Mason 
235176a05b35SChris Mason 	ret = -EAGAIN;
235202a3307aSLiu Bo 	tmp = read_tree_block(fs_info, blocknr, gen, parent_level - 1,
2353581c1760SQu Wenruo 			      &first_key);
235464c043deSLiu Bo 	if (!IS_ERR(tmp)) {
235576a05b35SChris Mason 		/*
235676a05b35SChris Mason 		 * If the read above didn't mark this buffer up to date,
235776a05b35SChris Mason 		 * it will never end up being up to date.  Set ret to EIO now
235876a05b35SChris Mason 		 * and give up so that our caller doesn't loop forever
235976a05b35SChris Mason 		 * on our EAGAINs.
236076a05b35SChris Mason 		 */
2361e6a1d6fdSLiu Bo 		if (!extent_buffer_uptodate(tmp))
236276a05b35SChris Mason 			ret = -EIO;
2363c8c42864SChris Mason 		free_extent_buffer(tmp);
2364c871b0f2SLiu Bo 	} else {
2365c871b0f2SLiu Bo 		ret = PTR_ERR(tmp);
236676a05b35SChris Mason 	}
236702a3307aSLiu Bo 
236802a3307aSLiu Bo 	btrfs_release_path(p);
236976a05b35SChris Mason 	return ret;
2370c8c42864SChris Mason }
2371c8c42864SChris Mason 
2372c8c42864SChris Mason /*
2373c8c42864SChris Mason  * helper function for btrfs_search_slot.  This does all of the checks
2374c8c42864SChris Mason  * for node-level blocks and does any balancing required based on
2375c8c42864SChris Mason  * the ins_len.
2376c8c42864SChris Mason  *
2377c8c42864SChris Mason  * If no extra work was required, zero is returned.  If we had to
2378c8c42864SChris Mason  * drop the path, -EAGAIN is returned and btrfs_search_slot must
2379c8c42864SChris Mason  * start over
2380c8c42864SChris Mason  */
2381c8c42864SChris Mason static int
2382c8c42864SChris Mason setup_nodes_for_search(struct btrfs_trans_handle *trans,
2383c8c42864SChris Mason 		       struct btrfs_root *root, struct btrfs_path *p,
2384bd681513SChris Mason 		       struct extent_buffer *b, int level, int ins_len,
2385bd681513SChris Mason 		       int *write_lock_level)
2386c8c42864SChris Mason {
23870b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
2388c8c42864SChris Mason 	int ret;
23890b246afaSJeff Mahoney 
2390c8c42864SChris Mason 	if ((p->search_for_split || ins_len > 0) && btrfs_header_nritems(b) >=
23910b246afaSJeff Mahoney 	    BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3) {
2392c8c42864SChris Mason 		int sret;
2393c8c42864SChris Mason 
2394bd681513SChris Mason 		if (*write_lock_level < level + 1) {
2395bd681513SChris Mason 			*write_lock_level = level + 1;
2396bd681513SChris Mason 			btrfs_release_path(p);
2397bd681513SChris Mason 			goto again;
2398bd681513SChris Mason 		}
2399bd681513SChris Mason 
2400bfb484d9SJosef Bacik 		reada_for_balance(p, level);
2401c8c42864SChris Mason 		sret = split_node(trans, root, p, level);
2402c8c42864SChris Mason 
2403c8c42864SChris Mason 		BUG_ON(sret > 0);
2404c8c42864SChris Mason 		if (sret) {
2405c8c42864SChris Mason 			ret = sret;
2406c8c42864SChris Mason 			goto done;
2407c8c42864SChris Mason 		}
2408c8c42864SChris Mason 		b = p->nodes[level];
2409c8c42864SChris Mason 	} else if (ins_len < 0 && btrfs_header_nritems(b) <
24100b246afaSJeff Mahoney 		   BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 2) {
2411c8c42864SChris Mason 		int sret;
2412c8c42864SChris Mason 
2413bd681513SChris Mason 		if (*write_lock_level < level + 1) {
2414bd681513SChris Mason 			*write_lock_level = level + 1;
2415bd681513SChris Mason 			btrfs_release_path(p);
2416bd681513SChris Mason 			goto again;
2417bd681513SChris Mason 		}
2418bd681513SChris Mason 
2419bfb484d9SJosef Bacik 		reada_for_balance(p, level);
2420c8c42864SChris Mason 		sret = balance_level(trans, root, p, level);
2421c8c42864SChris Mason 
2422c8c42864SChris Mason 		if (sret) {
2423c8c42864SChris Mason 			ret = sret;
2424c8c42864SChris Mason 			goto done;
2425c8c42864SChris Mason 		}
2426c8c42864SChris Mason 		b = p->nodes[level];
2427c8c42864SChris Mason 		if (!b) {
2428b3b4aa74SDavid Sterba 			btrfs_release_path(p);
2429c8c42864SChris Mason 			goto again;
2430c8c42864SChris Mason 		}
2431c8c42864SChris Mason 		BUG_ON(btrfs_header_nritems(b) == 1);
2432c8c42864SChris Mason 	}
2433c8c42864SChris Mason 	return 0;
2434c8c42864SChris Mason 
2435c8c42864SChris Mason again:
2436c8c42864SChris Mason 	ret = -EAGAIN;
2437c8c42864SChris Mason done:
2438c8c42864SChris Mason 	return ret;
2439c8c42864SChris Mason }
2440c8c42864SChris Mason 
2441381cf658SDavid Sterba int btrfs_find_item(struct btrfs_root *fs_root, struct btrfs_path *path,
2442e33d5c3dSKelley Nielsen 		u64 iobjectid, u64 ioff, u8 key_type,
2443e33d5c3dSKelley Nielsen 		struct btrfs_key *found_key)
2444e33d5c3dSKelley Nielsen {
2445e33d5c3dSKelley Nielsen 	int ret;
2446e33d5c3dSKelley Nielsen 	struct btrfs_key key;
2447e33d5c3dSKelley Nielsen 	struct extent_buffer *eb;
2448381cf658SDavid Sterba 
2449381cf658SDavid Sterba 	ASSERT(path);
24501d4c08e0SDavid Sterba 	ASSERT(found_key);
2451e33d5c3dSKelley Nielsen 
2452e33d5c3dSKelley Nielsen 	key.type = key_type;
2453e33d5c3dSKelley Nielsen 	key.objectid = iobjectid;
2454e33d5c3dSKelley Nielsen 	key.offset = ioff;
2455e33d5c3dSKelley Nielsen 
2456e33d5c3dSKelley Nielsen 	ret = btrfs_search_slot(NULL, fs_root, &key, path, 0, 0);
24571d4c08e0SDavid Sterba 	if (ret < 0)
2458e33d5c3dSKelley Nielsen 		return ret;
2459e33d5c3dSKelley Nielsen 
2460e33d5c3dSKelley Nielsen 	eb = path->nodes[0];
2461e33d5c3dSKelley Nielsen 	if (ret && path->slots[0] >= btrfs_header_nritems(eb)) {
2462e33d5c3dSKelley Nielsen 		ret = btrfs_next_leaf(fs_root, path);
2463e33d5c3dSKelley Nielsen 		if (ret)
2464e33d5c3dSKelley Nielsen 			return ret;
2465e33d5c3dSKelley Nielsen 		eb = path->nodes[0];
2466e33d5c3dSKelley Nielsen 	}
2467e33d5c3dSKelley Nielsen 
2468e33d5c3dSKelley Nielsen 	btrfs_item_key_to_cpu(eb, found_key, path->slots[0]);
2469e33d5c3dSKelley Nielsen 	if (found_key->type != key.type ||
2470e33d5c3dSKelley Nielsen 			found_key->objectid != key.objectid)
2471e33d5c3dSKelley Nielsen 		return 1;
2472e33d5c3dSKelley Nielsen 
2473e33d5c3dSKelley Nielsen 	return 0;
2474e33d5c3dSKelley Nielsen }
2475e33d5c3dSKelley Nielsen 
24761fc28d8eSLiu Bo static struct extent_buffer *btrfs_search_slot_get_root(struct btrfs_root *root,
24771fc28d8eSLiu Bo 							struct btrfs_path *p,
24781fc28d8eSLiu Bo 							int write_lock_level)
24791fc28d8eSLiu Bo {
24801fc28d8eSLiu Bo 	struct btrfs_fs_info *fs_info = root->fs_info;
24811fc28d8eSLiu Bo 	struct extent_buffer *b;
24821fc28d8eSLiu Bo 	int root_lock;
24831fc28d8eSLiu Bo 	int level = 0;
24841fc28d8eSLiu Bo 
24851fc28d8eSLiu Bo 	/* We try very hard to do read locks on the root */
24861fc28d8eSLiu Bo 	root_lock = BTRFS_READ_LOCK;
24871fc28d8eSLiu Bo 
24881fc28d8eSLiu Bo 	if (p->search_commit_root) {
2489be6821f8SFilipe Manana 		/*
2490be6821f8SFilipe Manana 		 * The commit roots are read only so we always do read locks,
2491be6821f8SFilipe Manana 		 * and we always must hold the commit_root_sem when doing
2492be6821f8SFilipe Manana 		 * searches on them, the only exception is send where we don't
2493be6821f8SFilipe Manana 		 * want to block transaction commits for a long time, so
2494be6821f8SFilipe Manana 		 * we need to clone the commit root in order to avoid races
2495be6821f8SFilipe Manana 		 * with transaction commits that create a snapshot of one of
2496be6821f8SFilipe Manana 		 * the roots used by a send operation.
2497be6821f8SFilipe Manana 		 */
2498be6821f8SFilipe Manana 		if (p->need_commit_sem) {
24991fc28d8eSLiu Bo 			down_read(&fs_info->commit_root_sem);
2500be6821f8SFilipe Manana 			b = btrfs_clone_extent_buffer(root->commit_root);
2501be6821f8SFilipe Manana 			up_read(&fs_info->commit_root_sem);
2502be6821f8SFilipe Manana 			if (!b)
2503be6821f8SFilipe Manana 				return ERR_PTR(-ENOMEM);
2504be6821f8SFilipe Manana 
2505be6821f8SFilipe Manana 		} else {
25061fc28d8eSLiu Bo 			b = root->commit_root;
250767439dadSDavid Sterba 			atomic_inc(&b->refs);
2508be6821f8SFilipe Manana 		}
25091fc28d8eSLiu Bo 		level = btrfs_header_level(b);
2510f9ddfd05SLiu Bo 		/*
2511f9ddfd05SLiu Bo 		 * Ensure that all callers have set skip_locking when
2512f9ddfd05SLiu Bo 		 * p->search_commit_root = 1.
2513f9ddfd05SLiu Bo 		 */
2514f9ddfd05SLiu Bo 		ASSERT(p->skip_locking == 1);
25151fc28d8eSLiu Bo 
25161fc28d8eSLiu Bo 		goto out;
25171fc28d8eSLiu Bo 	}
25181fc28d8eSLiu Bo 
25191fc28d8eSLiu Bo 	if (p->skip_locking) {
25201fc28d8eSLiu Bo 		b = btrfs_root_node(root);
25211fc28d8eSLiu Bo 		level = btrfs_header_level(b);
25221fc28d8eSLiu Bo 		goto out;
25231fc28d8eSLiu Bo 	}
25241fc28d8eSLiu Bo 
25251fc28d8eSLiu Bo 	/*
2526662c653bSLiu Bo 	 * If the level is set to maximum, we can skip trying to get the read
2527662c653bSLiu Bo 	 * lock.
2528662c653bSLiu Bo 	 */
2529662c653bSLiu Bo 	if (write_lock_level < BTRFS_MAX_LEVEL) {
2530662c653bSLiu Bo 		/*
2531662c653bSLiu Bo 		 * We don't know the level of the root node until we actually
2532662c653bSLiu Bo 		 * have it read locked
25331fc28d8eSLiu Bo 		 */
253451899412SJosef Bacik 		b = __btrfs_read_lock_root_node(root, p->recurse);
25351fc28d8eSLiu Bo 		level = btrfs_header_level(b);
25361fc28d8eSLiu Bo 		if (level > write_lock_level)
25371fc28d8eSLiu Bo 			goto out;
25381fc28d8eSLiu Bo 
2539662c653bSLiu Bo 		/* Whoops, must trade for write lock */
25401fc28d8eSLiu Bo 		btrfs_tree_read_unlock(b);
25411fc28d8eSLiu Bo 		free_extent_buffer(b);
2542662c653bSLiu Bo 	}
2543662c653bSLiu Bo 
25441fc28d8eSLiu Bo 	b = btrfs_lock_root_node(root);
25451fc28d8eSLiu Bo 	root_lock = BTRFS_WRITE_LOCK;
25461fc28d8eSLiu Bo 
25471fc28d8eSLiu Bo 	/* The level might have changed, check again */
25481fc28d8eSLiu Bo 	level = btrfs_header_level(b);
25491fc28d8eSLiu Bo 
25501fc28d8eSLiu Bo out:
25511fc28d8eSLiu Bo 	p->nodes[level] = b;
25521fc28d8eSLiu Bo 	if (!p->skip_locking)
25531fc28d8eSLiu Bo 		p->locks[level] = root_lock;
25541fc28d8eSLiu Bo 	/*
25551fc28d8eSLiu Bo 	 * Callers are responsible for dropping b's references.
25561fc28d8eSLiu Bo 	 */
25571fc28d8eSLiu Bo 	return b;
25581fc28d8eSLiu Bo }
25591fc28d8eSLiu Bo 
25601fc28d8eSLiu Bo 
2561c8c42864SChris Mason /*
25624271eceaSNikolay Borisov  * btrfs_search_slot - look for a key in a tree and perform necessary
25634271eceaSNikolay Borisov  * modifications to preserve tree invariants.
256474123bd7SChris Mason  *
25654271eceaSNikolay Borisov  * @trans:	Handle of transaction, used when modifying the tree
25664271eceaSNikolay Borisov  * @p:		Holds all btree nodes along the search path
25674271eceaSNikolay Borisov  * @root:	The root node of the tree
25684271eceaSNikolay Borisov  * @key:	The key we are looking for
25694271eceaSNikolay Borisov  * @ins_len:	Indicates purpose of search, for inserts it is 1, for
25704271eceaSNikolay Borisov  *		deletions it's -1. 0 for plain searches
25714271eceaSNikolay Borisov  * @cow:	boolean should CoW operations be performed. Must always be 1
25724271eceaSNikolay Borisov  *		when modifying the tree.
257397571fd0SChris Mason  *
25744271eceaSNikolay Borisov  * If @ins_len > 0, nodes and leaves will be split as we walk down the tree.
25754271eceaSNikolay Borisov  * If @ins_len < 0, nodes will be merged as we walk down the tree (if possible)
25764271eceaSNikolay Borisov  *
25774271eceaSNikolay Borisov  * If @key is found, 0 is returned and you can find the item in the leaf level
25784271eceaSNikolay Borisov  * of the path (level 0)
25794271eceaSNikolay Borisov  *
25804271eceaSNikolay Borisov  * If @key isn't found, 1 is returned and the leaf level of the path (level 0)
25814271eceaSNikolay Borisov  * points to the slot where it should be inserted
25824271eceaSNikolay Borisov  *
25834271eceaSNikolay Borisov  * If an error is encountered while searching the tree a negative error number
25844271eceaSNikolay Borisov  * is returned
258574123bd7SChris Mason  */
2586310712b2SOmar Sandoval int btrfs_search_slot(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2587310712b2SOmar Sandoval 		      const struct btrfs_key *key, struct btrfs_path *p,
2588310712b2SOmar Sandoval 		      int ins_len, int cow)
2589be0e5c09SChris Mason {
25905f39d397SChris Mason 	struct extent_buffer *b;
2591be0e5c09SChris Mason 	int slot;
2592be0e5c09SChris Mason 	int ret;
259333c66f43SYan Zheng 	int err;
2594be0e5c09SChris Mason 	int level;
2595925baeddSChris Mason 	int lowest_unlock = 1;
2596bd681513SChris Mason 	/* everything at write_lock_level or lower must be write locked */
2597bd681513SChris Mason 	int write_lock_level = 0;
25989f3a7427SChris Mason 	u8 lowest_level = 0;
2599f7c79f30SChris Mason 	int min_write_lock_level;
2600d7396f07SFilipe David Borba Manana 	int prev_cmp;
26019f3a7427SChris Mason 
26026702ed49SChris Mason 	lowest_level = p->lowest_level;
2603323ac95bSChris Mason 	WARN_ON(lowest_level && ins_len > 0);
260422b0ebdaSChris Mason 	WARN_ON(p->nodes[0] != NULL);
2605eb653de1SFilipe David Borba Manana 	BUG_ON(!cow && ins_len);
260625179201SJosef Bacik 
2607bd681513SChris Mason 	if (ins_len < 0) {
2608925baeddSChris Mason 		lowest_unlock = 2;
260965b51a00SChris Mason 
2610bd681513SChris Mason 		/* when we are removing items, we might have to go up to level
2611bd681513SChris Mason 		 * two as we update tree pointers  Make sure we keep write
2612bd681513SChris Mason 		 * for those levels as well
2613bd681513SChris Mason 		 */
2614bd681513SChris Mason 		write_lock_level = 2;
2615bd681513SChris Mason 	} else if (ins_len > 0) {
2616bd681513SChris Mason 		/*
2617bd681513SChris Mason 		 * for inserting items, make sure we have a write lock on
2618bd681513SChris Mason 		 * level 1 so we can update keys
2619bd681513SChris Mason 		 */
2620bd681513SChris Mason 		write_lock_level = 1;
2621bd681513SChris Mason 	}
2622bd681513SChris Mason 
2623bd681513SChris Mason 	if (!cow)
2624bd681513SChris Mason 		write_lock_level = -1;
2625bd681513SChris Mason 
262609a2a8f9SJosef Bacik 	if (cow && (p->keep_locks || p->lowest_level))
2627bd681513SChris Mason 		write_lock_level = BTRFS_MAX_LEVEL;
2628bd681513SChris Mason 
2629f7c79f30SChris Mason 	min_write_lock_level = write_lock_level;
2630f7c79f30SChris Mason 
2631bb803951SChris Mason again:
2632d7396f07SFilipe David Borba Manana 	prev_cmp = -1;
26331fc28d8eSLiu Bo 	b = btrfs_search_slot_get_root(root, p, write_lock_level);
2634be6821f8SFilipe Manana 	if (IS_ERR(b)) {
2635be6821f8SFilipe Manana 		ret = PTR_ERR(b);
2636be6821f8SFilipe Manana 		goto done;
2637be6821f8SFilipe Manana 	}
2638925baeddSChris Mason 
2639eb60ceacSChris Mason 	while (b) {
2640f624d976SQu Wenruo 		int dec = 0;
2641f624d976SQu Wenruo 
26425f39d397SChris Mason 		level = btrfs_header_level(b);
264365b51a00SChris Mason 
264402217ed2SChris Mason 		if (cow) {
26459ea2c7c9SNikolay Borisov 			bool last_level = (level == (BTRFS_MAX_LEVEL - 1));
26469ea2c7c9SNikolay Borisov 
2647c8c42864SChris Mason 			/*
2648c8c42864SChris Mason 			 * if we don't really need to cow this block
2649c8c42864SChris Mason 			 * then we don't want to set the path blocking,
2650c8c42864SChris Mason 			 * so we test it here
2651c8c42864SChris Mason 			 */
265264c12921SJeff Mahoney 			if (!should_cow_block(trans, root, b)) {
265364c12921SJeff Mahoney 				trans->dirty = true;
265465b51a00SChris Mason 				goto cow_done;
265564c12921SJeff Mahoney 			}
26565d4f98a2SYan Zheng 
2657bd681513SChris Mason 			/*
2658bd681513SChris Mason 			 * must have write locks on this node and the
2659bd681513SChris Mason 			 * parent
2660bd681513SChris Mason 			 */
26615124e00eSJosef Bacik 			if (level > write_lock_level ||
26625124e00eSJosef Bacik 			    (level + 1 > write_lock_level &&
26635124e00eSJosef Bacik 			    level + 1 < BTRFS_MAX_LEVEL &&
26645124e00eSJosef Bacik 			    p->nodes[level + 1])) {
2665bd681513SChris Mason 				write_lock_level = level + 1;
2666bd681513SChris Mason 				btrfs_release_path(p);
2667bd681513SChris Mason 				goto again;
2668bd681513SChris Mason 			}
2669bd681513SChris Mason 
26709ea2c7c9SNikolay Borisov 			if (last_level)
26719ea2c7c9SNikolay Borisov 				err = btrfs_cow_block(trans, root, b, NULL, 0,
26729631e4ccSJosef Bacik 						      &b,
26739631e4ccSJosef Bacik 						      BTRFS_NESTING_COW);
26749ea2c7c9SNikolay Borisov 			else
267533c66f43SYan Zheng 				err = btrfs_cow_block(trans, root, b,
2676e20d96d6SChris Mason 						      p->nodes[level + 1],
26779631e4ccSJosef Bacik 						      p->slots[level + 1], &b,
26789631e4ccSJosef Bacik 						      BTRFS_NESTING_COW);
267933c66f43SYan Zheng 			if (err) {
268033c66f43SYan Zheng 				ret = err;
268165b51a00SChris Mason 				goto done;
268254aa1f4dSChris Mason 			}
268302217ed2SChris Mason 		}
268465b51a00SChris Mason cow_done:
2685eb60ceacSChris Mason 		p->nodes[level] = b;
268652398340SLiu Bo 		/*
268752398340SLiu Bo 		 * Leave path with blocking locks to avoid massive
268852398340SLiu Bo 		 * lock context switch, this is made on purpose.
268952398340SLiu Bo 		 */
2690b4ce94deSChris Mason 
2691b4ce94deSChris Mason 		/*
2692b4ce94deSChris Mason 		 * we have a lock on b and as long as we aren't changing
2693b4ce94deSChris Mason 		 * the tree, there is no way to for the items in b to change.
2694b4ce94deSChris Mason 		 * It is safe to drop the lock on our parent before we
2695b4ce94deSChris Mason 		 * go through the expensive btree search on b.
2696b4ce94deSChris Mason 		 *
2697eb653de1SFilipe David Borba Manana 		 * If we're inserting or deleting (ins_len != 0), then we might
2698eb653de1SFilipe David Borba Manana 		 * be changing slot zero, which may require changing the parent.
2699eb653de1SFilipe David Borba Manana 		 * So, we can't drop the lock until after we know which slot
2700eb653de1SFilipe David Borba Manana 		 * we're operating on.
2701b4ce94deSChris Mason 		 */
2702eb653de1SFilipe David Borba Manana 		if (!ins_len && !p->keep_locks) {
2703eb653de1SFilipe David Borba Manana 			int u = level + 1;
2704eb653de1SFilipe David Borba Manana 
2705eb653de1SFilipe David Borba Manana 			if (u < BTRFS_MAX_LEVEL && p->locks[u]) {
2706eb653de1SFilipe David Borba Manana 				btrfs_tree_unlock_rw(p->nodes[u], p->locks[u]);
2707eb653de1SFilipe David Borba Manana 				p->locks[u] = 0;
2708eb653de1SFilipe David Borba Manana 			}
2709eb653de1SFilipe David Borba Manana 		}
2710b4ce94deSChris Mason 
2711995e9a16SNikolay Borisov 		/*
2712995e9a16SNikolay Borisov 		 * If btrfs_bin_search returns an exact match (prev_cmp == 0)
2713995e9a16SNikolay Borisov 		 * we can safely assume the target key will always be in slot 0
2714995e9a16SNikolay Borisov 		 * on lower levels due to the invariants BTRFS' btree provides,
2715995e9a16SNikolay Borisov 		 * namely that a btrfs_key_ptr entry always points to the
2716995e9a16SNikolay Borisov 		 * lowest key in the child node, thus we can skip searching
2717995e9a16SNikolay Borisov 		 * lower levels
2718995e9a16SNikolay Borisov 		 */
2719995e9a16SNikolay Borisov 		if (prev_cmp == 0) {
2720995e9a16SNikolay Borisov 			slot = 0;
2721995e9a16SNikolay Borisov 			ret = 0;
2722995e9a16SNikolay Borisov 		} else {
2723995e9a16SNikolay Borisov 			ret = btrfs_bin_search(b, key, &slot);
2724995e9a16SNikolay Borisov 			prev_cmp = ret;
2725415b35a5SLiu Bo 			if (ret < 0)
2726415b35a5SLiu Bo 				goto done;
2727995e9a16SNikolay Borisov 		}
2728b4ce94deSChris Mason 
2729f624d976SQu Wenruo 		if (level == 0) {
2730be0e5c09SChris Mason 			p->slots[level] = slot;
273187b29b20SYan Zheng 			if (ins_len > 0 &&
2732e902baacSDavid Sterba 			    btrfs_leaf_free_space(b) < ins_len) {
2733bd681513SChris Mason 				if (write_lock_level < 1) {
2734bd681513SChris Mason 					write_lock_level = 1;
2735bd681513SChris Mason 					btrfs_release_path(p);
2736bd681513SChris Mason 					goto again;
2737bd681513SChris Mason 				}
2738bd681513SChris Mason 
273933c66f43SYan Zheng 				err = split_leaf(trans, root, key,
2740cc0c5538SChris Mason 						 p, ins_len, ret == 0);
2741b4ce94deSChris Mason 
274233c66f43SYan Zheng 				BUG_ON(err > 0);
274333c66f43SYan Zheng 				if (err) {
274433c66f43SYan Zheng 					ret = err;
274565b51a00SChris Mason 					goto done;
274665b51a00SChris Mason 				}
27475c680ed6SChris Mason 			}
2748459931ecSChris Mason 			if (!p->search_for_split)
2749f7c79f30SChris Mason 				unlock_up(p, level, lowest_unlock,
27504b6f8e96SLiu Bo 					  min_write_lock_level, NULL);
275165b51a00SChris Mason 			goto done;
275265b51a00SChris Mason 		}
2753f624d976SQu Wenruo 		if (ret && slot > 0) {
2754f624d976SQu Wenruo 			dec = 1;
2755f624d976SQu Wenruo 			slot--;
2756f624d976SQu Wenruo 		}
2757f624d976SQu Wenruo 		p->slots[level] = slot;
2758f624d976SQu Wenruo 		err = setup_nodes_for_search(trans, root, p, b, level, ins_len,
2759f624d976SQu Wenruo 					     &write_lock_level);
2760f624d976SQu Wenruo 		if (err == -EAGAIN)
2761f624d976SQu Wenruo 			goto again;
2762f624d976SQu Wenruo 		if (err) {
2763f624d976SQu Wenruo 			ret = err;
2764f624d976SQu Wenruo 			goto done;
2765f624d976SQu Wenruo 		}
2766f624d976SQu Wenruo 		b = p->nodes[level];
2767f624d976SQu Wenruo 		slot = p->slots[level];
2768f624d976SQu Wenruo 
2769f624d976SQu Wenruo 		/*
2770f624d976SQu Wenruo 		 * Slot 0 is special, if we change the key we have to update
2771f624d976SQu Wenruo 		 * the parent pointer which means we must have a write lock on
2772f624d976SQu Wenruo 		 * the parent
2773f624d976SQu Wenruo 		 */
2774f624d976SQu Wenruo 		if (slot == 0 && ins_len && write_lock_level < level + 1) {
2775f624d976SQu Wenruo 			write_lock_level = level + 1;
2776f624d976SQu Wenruo 			btrfs_release_path(p);
2777f624d976SQu Wenruo 			goto again;
2778f624d976SQu Wenruo 		}
2779f624d976SQu Wenruo 
2780f624d976SQu Wenruo 		unlock_up(p, level, lowest_unlock, min_write_lock_level,
2781f624d976SQu Wenruo 			  &write_lock_level);
2782f624d976SQu Wenruo 
2783f624d976SQu Wenruo 		if (level == lowest_level) {
2784f624d976SQu Wenruo 			if (dec)
2785f624d976SQu Wenruo 				p->slots[level]++;
2786f624d976SQu Wenruo 			goto done;
2787f624d976SQu Wenruo 		}
2788f624d976SQu Wenruo 
2789f624d976SQu Wenruo 		err = read_block_for_search(root, p, &b, level, slot, key);
2790f624d976SQu Wenruo 		if (err == -EAGAIN)
2791f624d976SQu Wenruo 			goto again;
2792f624d976SQu Wenruo 		if (err) {
2793f624d976SQu Wenruo 			ret = err;
2794f624d976SQu Wenruo 			goto done;
2795f624d976SQu Wenruo 		}
2796f624d976SQu Wenruo 
2797f624d976SQu Wenruo 		if (!p->skip_locking) {
2798f624d976SQu Wenruo 			level = btrfs_header_level(b);
2799f624d976SQu Wenruo 			if (level <= write_lock_level) {
2800f624d976SQu Wenruo 				btrfs_tree_lock(b);
2801f624d976SQu Wenruo 				p->locks[level] = BTRFS_WRITE_LOCK;
2802f624d976SQu Wenruo 			} else {
2803fd7ba1c1SJosef Bacik 				__btrfs_tree_read_lock(b, BTRFS_NESTING_NORMAL,
2804fd7ba1c1SJosef Bacik 						       p->recurse);
2805f624d976SQu Wenruo 				p->locks[level] = BTRFS_READ_LOCK;
2806f624d976SQu Wenruo 			}
2807f624d976SQu Wenruo 			p->nodes[level] = b;
2808f624d976SQu Wenruo 		}
280965b51a00SChris Mason 	}
281065b51a00SChris Mason 	ret = 1;
281165b51a00SChris Mason done:
28125f5bc6b1SFilipe Manana 	if (ret < 0 && !p->skip_release_on_error)
2813b3b4aa74SDavid Sterba 		btrfs_release_path(p);
2814be0e5c09SChris Mason 	return ret;
2815be0e5c09SChris Mason }
2816be0e5c09SChris Mason 
281774123bd7SChris Mason /*
28185d9e75c4SJan Schmidt  * Like btrfs_search_slot, this looks for a key in the given tree. It uses the
28195d9e75c4SJan Schmidt  * current state of the tree together with the operations recorded in the tree
28205d9e75c4SJan Schmidt  * modification log to search for the key in a previous version of this tree, as
28215d9e75c4SJan Schmidt  * denoted by the time_seq parameter.
28225d9e75c4SJan Schmidt  *
28235d9e75c4SJan Schmidt  * Naturally, there is no support for insert, delete or cow operations.
28245d9e75c4SJan Schmidt  *
28255d9e75c4SJan Schmidt  * The resulting path and return value will be set up as if we called
28265d9e75c4SJan Schmidt  * btrfs_search_slot at that point in time with ins_len and cow both set to 0.
28275d9e75c4SJan Schmidt  */
2828310712b2SOmar Sandoval int btrfs_search_old_slot(struct btrfs_root *root, const struct btrfs_key *key,
28295d9e75c4SJan Schmidt 			  struct btrfs_path *p, u64 time_seq)
28305d9e75c4SJan Schmidt {
28310b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
28325d9e75c4SJan Schmidt 	struct extent_buffer *b;
28335d9e75c4SJan Schmidt 	int slot;
28345d9e75c4SJan Schmidt 	int ret;
28355d9e75c4SJan Schmidt 	int err;
28365d9e75c4SJan Schmidt 	int level;
28375d9e75c4SJan Schmidt 	int lowest_unlock = 1;
28385d9e75c4SJan Schmidt 	u8 lowest_level = 0;
28395d9e75c4SJan Schmidt 
28405d9e75c4SJan Schmidt 	lowest_level = p->lowest_level;
28415d9e75c4SJan Schmidt 	WARN_ON(p->nodes[0] != NULL);
28425d9e75c4SJan Schmidt 
28435d9e75c4SJan Schmidt 	if (p->search_commit_root) {
28445d9e75c4SJan Schmidt 		BUG_ON(time_seq);
28455d9e75c4SJan Schmidt 		return btrfs_search_slot(NULL, root, key, p, 0, 0);
28465d9e75c4SJan Schmidt 	}
28475d9e75c4SJan Schmidt 
28485d9e75c4SJan Schmidt again:
28495d9e75c4SJan Schmidt 	b = get_old_root(root, time_seq);
2850315bed43SNikolay Borisov 	if (!b) {
2851315bed43SNikolay Borisov 		ret = -EIO;
2852315bed43SNikolay Borisov 		goto done;
2853315bed43SNikolay Borisov 	}
28545d9e75c4SJan Schmidt 	level = btrfs_header_level(b);
28555d9e75c4SJan Schmidt 	p->locks[level] = BTRFS_READ_LOCK;
28565d9e75c4SJan Schmidt 
28575d9e75c4SJan Schmidt 	while (b) {
2858abe9339dSQu Wenruo 		int dec = 0;
2859abe9339dSQu Wenruo 
28605d9e75c4SJan Schmidt 		level = btrfs_header_level(b);
28615d9e75c4SJan Schmidt 		p->nodes[level] = b;
28625d9e75c4SJan Schmidt 
28635d9e75c4SJan Schmidt 		/*
28645d9e75c4SJan Schmidt 		 * we have a lock on b and as long as we aren't changing
28655d9e75c4SJan Schmidt 		 * the tree, there is no way to for the items in b to change.
28665d9e75c4SJan Schmidt 		 * It is safe to drop the lock on our parent before we
28675d9e75c4SJan Schmidt 		 * go through the expensive btree search on b.
28685d9e75c4SJan Schmidt 		 */
28695d9e75c4SJan Schmidt 		btrfs_unlock_up_safe(p, level + 1);
28705d9e75c4SJan Schmidt 
2871995e9a16SNikolay Borisov 		ret = btrfs_bin_search(b, key, &slot);
2872cbca7d59SFilipe Manana 		if (ret < 0)
2873cbca7d59SFilipe Manana 			goto done;
28745d9e75c4SJan Schmidt 
2875abe9339dSQu Wenruo 		if (level == 0) {
2876abe9339dSQu Wenruo 			p->slots[level] = slot;
2877abe9339dSQu Wenruo 			unlock_up(p, level, lowest_unlock, 0, NULL);
2878abe9339dSQu Wenruo 			goto done;
2879abe9339dSQu Wenruo 		}
2880abe9339dSQu Wenruo 
28815d9e75c4SJan Schmidt 		if (ret && slot > 0) {
28825d9e75c4SJan Schmidt 			dec = 1;
2883abe9339dSQu Wenruo 			slot--;
28845d9e75c4SJan Schmidt 		}
28855d9e75c4SJan Schmidt 		p->slots[level] = slot;
28865d9e75c4SJan Schmidt 		unlock_up(p, level, lowest_unlock, 0, NULL);
28875d9e75c4SJan Schmidt 
28885d9e75c4SJan Schmidt 		if (level == lowest_level) {
28895d9e75c4SJan Schmidt 			if (dec)
28905d9e75c4SJan Schmidt 				p->slots[level]++;
28915d9e75c4SJan Schmidt 			goto done;
28925d9e75c4SJan Schmidt 		}
28935d9e75c4SJan Schmidt 
2894abe9339dSQu Wenruo 		err = read_block_for_search(root, p, &b, level, slot, key);
28955d9e75c4SJan Schmidt 		if (err == -EAGAIN)
28965d9e75c4SJan Schmidt 			goto again;
28975d9e75c4SJan Schmidt 		if (err) {
28985d9e75c4SJan Schmidt 			ret = err;
28995d9e75c4SJan Schmidt 			goto done;
29005d9e75c4SJan Schmidt 		}
29015d9e75c4SJan Schmidt 
29025d9e75c4SJan Schmidt 		level = btrfs_header_level(b);
29035d9e75c4SJan Schmidt 		btrfs_tree_read_lock(b);
29040b246afaSJeff Mahoney 		b = tree_mod_log_rewind(fs_info, p, b, time_seq);
2905db7f3436SJosef Bacik 		if (!b) {
2906db7f3436SJosef Bacik 			ret = -ENOMEM;
2907db7f3436SJosef Bacik 			goto done;
2908db7f3436SJosef Bacik 		}
29095d9e75c4SJan Schmidt 		p->locks[level] = BTRFS_READ_LOCK;
29105d9e75c4SJan Schmidt 		p->nodes[level] = b;
29115d9e75c4SJan Schmidt 	}
29125d9e75c4SJan Schmidt 	ret = 1;
29135d9e75c4SJan Schmidt done:
29145d9e75c4SJan Schmidt 	if (ret < 0)
29155d9e75c4SJan Schmidt 		btrfs_release_path(p);
29165d9e75c4SJan Schmidt 
29175d9e75c4SJan Schmidt 	return ret;
29185d9e75c4SJan Schmidt }
29195d9e75c4SJan Schmidt 
29205d9e75c4SJan Schmidt /*
29212f38b3e1SArne Jansen  * helper to use instead of search slot if no exact match is needed but
29222f38b3e1SArne Jansen  * instead the next or previous item should be returned.
29232f38b3e1SArne Jansen  * When find_higher is true, the next higher item is returned, the next lower
29242f38b3e1SArne Jansen  * otherwise.
29252f38b3e1SArne Jansen  * When return_any and find_higher are both true, and no higher item is found,
29262f38b3e1SArne Jansen  * return the next lower instead.
29272f38b3e1SArne Jansen  * When return_any is true and find_higher is false, and no lower item is found,
29282f38b3e1SArne Jansen  * return the next higher instead.
29292f38b3e1SArne Jansen  * It returns 0 if any item is found, 1 if none is found (tree empty), and
29302f38b3e1SArne Jansen  * < 0 on error
29312f38b3e1SArne Jansen  */
29322f38b3e1SArne Jansen int btrfs_search_slot_for_read(struct btrfs_root *root,
2933310712b2SOmar Sandoval 			       const struct btrfs_key *key,
2934310712b2SOmar Sandoval 			       struct btrfs_path *p, int find_higher,
2935310712b2SOmar Sandoval 			       int return_any)
29362f38b3e1SArne Jansen {
29372f38b3e1SArne Jansen 	int ret;
29382f38b3e1SArne Jansen 	struct extent_buffer *leaf;
29392f38b3e1SArne Jansen 
29402f38b3e1SArne Jansen again:
29412f38b3e1SArne Jansen 	ret = btrfs_search_slot(NULL, root, key, p, 0, 0);
29422f38b3e1SArne Jansen 	if (ret <= 0)
29432f38b3e1SArne Jansen 		return ret;
29442f38b3e1SArne Jansen 	/*
29452f38b3e1SArne Jansen 	 * a return value of 1 means the path is at the position where the
29462f38b3e1SArne Jansen 	 * item should be inserted. Normally this is the next bigger item,
29472f38b3e1SArne Jansen 	 * but in case the previous item is the last in a leaf, path points
29482f38b3e1SArne Jansen 	 * to the first free slot in the previous leaf, i.e. at an invalid
29492f38b3e1SArne Jansen 	 * item.
29502f38b3e1SArne Jansen 	 */
29512f38b3e1SArne Jansen 	leaf = p->nodes[0];
29522f38b3e1SArne Jansen 
29532f38b3e1SArne Jansen 	if (find_higher) {
29542f38b3e1SArne Jansen 		if (p->slots[0] >= btrfs_header_nritems(leaf)) {
29552f38b3e1SArne Jansen 			ret = btrfs_next_leaf(root, p);
29562f38b3e1SArne Jansen 			if (ret <= 0)
29572f38b3e1SArne Jansen 				return ret;
29582f38b3e1SArne Jansen 			if (!return_any)
29592f38b3e1SArne Jansen 				return 1;
29602f38b3e1SArne Jansen 			/*
29612f38b3e1SArne Jansen 			 * no higher item found, return the next
29622f38b3e1SArne Jansen 			 * lower instead
29632f38b3e1SArne Jansen 			 */
29642f38b3e1SArne Jansen 			return_any = 0;
29652f38b3e1SArne Jansen 			find_higher = 0;
29662f38b3e1SArne Jansen 			btrfs_release_path(p);
29672f38b3e1SArne Jansen 			goto again;
29682f38b3e1SArne Jansen 		}
29692f38b3e1SArne Jansen 	} else {
29702f38b3e1SArne Jansen 		if (p->slots[0] == 0) {
29712f38b3e1SArne Jansen 			ret = btrfs_prev_leaf(root, p);
2972e6793769SArne Jansen 			if (ret < 0)
29732f38b3e1SArne Jansen 				return ret;
2974e6793769SArne Jansen 			if (!ret) {
297523c6bf6aSFilipe David Borba Manana 				leaf = p->nodes[0];
297623c6bf6aSFilipe David Borba Manana 				if (p->slots[0] == btrfs_header_nritems(leaf))
297723c6bf6aSFilipe David Borba Manana 					p->slots[0]--;
2978e6793769SArne Jansen 				return 0;
2979e6793769SArne Jansen 			}
29802f38b3e1SArne Jansen 			if (!return_any)
29812f38b3e1SArne Jansen 				return 1;
29822f38b3e1SArne Jansen 			/*
29832f38b3e1SArne Jansen 			 * no lower item found, return the next
29842f38b3e1SArne Jansen 			 * higher instead
29852f38b3e1SArne Jansen 			 */
29862f38b3e1SArne Jansen 			return_any = 0;
29872f38b3e1SArne Jansen 			find_higher = 1;
29882f38b3e1SArne Jansen 			btrfs_release_path(p);
29892f38b3e1SArne Jansen 			goto again;
2990e6793769SArne Jansen 		} else {
29912f38b3e1SArne Jansen 			--p->slots[0];
29922f38b3e1SArne Jansen 		}
29932f38b3e1SArne Jansen 	}
29942f38b3e1SArne Jansen 	return 0;
29952f38b3e1SArne Jansen }
29962f38b3e1SArne Jansen 
29972f38b3e1SArne Jansen /*
299874123bd7SChris Mason  * adjust the pointers going up the tree, starting at level
299974123bd7SChris Mason  * making sure the right key of each node is points to 'key'.
300074123bd7SChris Mason  * This is used after shifting pointers to the left, so it stops
300174123bd7SChris Mason  * fixing up pointers when a given leaf/node is not in slot 0 of the
300274123bd7SChris Mason  * higher levels
3003aa5d6bedSChris Mason  *
300474123bd7SChris Mason  */
3005b167fa91SNikolay Borisov static void fixup_low_keys(struct btrfs_path *path,
30065f39d397SChris Mason 			   struct btrfs_disk_key *key, int level)
3007be0e5c09SChris Mason {
3008be0e5c09SChris Mason 	int i;
30095f39d397SChris Mason 	struct extent_buffer *t;
30100e82bcfeSDavid Sterba 	int ret;
30115f39d397SChris Mason 
3012234b63a0SChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
3013be0e5c09SChris Mason 		int tslot = path->slots[i];
30140e82bcfeSDavid Sterba 
3015eb60ceacSChris Mason 		if (!path->nodes[i])
3016be0e5c09SChris Mason 			break;
30175f39d397SChris Mason 		t = path->nodes[i];
30180e82bcfeSDavid Sterba 		ret = tree_mod_log_insert_key(t, tslot, MOD_LOG_KEY_REPLACE,
30190e82bcfeSDavid Sterba 				GFP_ATOMIC);
30200e82bcfeSDavid Sterba 		BUG_ON(ret < 0);
30215f39d397SChris Mason 		btrfs_set_node_key(t, key, tslot);
3022d6025579SChris Mason 		btrfs_mark_buffer_dirty(path->nodes[i]);
3023be0e5c09SChris Mason 		if (tslot != 0)
3024be0e5c09SChris Mason 			break;
3025be0e5c09SChris Mason 	}
3026be0e5c09SChris Mason }
3027be0e5c09SChris Mason 
302874123bd7SChris Mason /*
302931840ae1SZheng Yan  * update item key.
303031840ae1SZheng Yan  *
303131840ae1SZheng Yan  * This function isn't completely safe. It's the caller's responsibility
303231840ae1SZheng Yan  * that the new key won't break the order
303331840ae1SZheng Yan  */
3034b7a0365eSDaniel Dressler void btrfs_set_item_key_safe(struct btrfs_fs_info *fs_info,
3035b7a0365eSDaniel Dressler 			     struct btrfs_path *path,
3036310712b2SOmar Sandoval 			     const struct btrfs_key *new_key)
303731840ae1SZheng Yan {
303831840ae1SZheng Yan 	struct btrfs_disk_key disk_key;
303931840ae1SZheng Yan 	struct extent_buffer *eb;
304031840ae1SZheng Yan 	int slot;
304131840ae1SZheng Yan 
304231840ae1SZheng Yan 	eb = path->nodes[0];
304331840ae1SZheng Yan 	slot = path->slots[0];
304431840ae1SZheng Yan 	if (slot > 0) {
304531840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot - 1);
30467c15d410SQu Wenruo 		if (unlikely(comp_keys(&disk_key, new_key) >= 0)) {
30477c15d410SQu Wenruo 			btrfs_crit(fs_info,
30487c15d410SQu Wenruo 		"slot %u key (%llu %u %llu) new key (%llu %u %llu)",
30497c15d410SQu Wenruo 				   slot, btrfs_disk_key_objectid(&disk_key),
30507c15d410SQu Wenruo 				   btrfs_disk_key_type(&disk_key),
30517c15d410SQu Wenruo 				   btrfs_disk_key_offset(&disk_key),
30527c15d410SQu Wenruo 				   new_key->objectid, new_key->type,
30537c15d410SQu Wenruo 				   new_key->offset);
30547c15d410SQu Wenruo 			btrfs_print_leaf(eb);
30557c15d410SQu Wenruo 			BUG();
30567c15d410SQu Wenruo 		}
305731840ae1SZheng Yan 	}
305831840ae1SZheng Yan 	if (slot < btrfs_header_nritems(eb) - 1) {
305931840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot + 1);
30607c15d410SQu Wenruo 		if (unlikely(comp_keys(&disk_key, new_key) <= 0)) {
30617c15d410SQu Wenruo 			btrfs_crit(fs_info,
30627c15d410SQu Wenruo 		"slot %u key (%llu %u %llu) new key (%llu %u %llu)",
30637c15d410SQu Wenruo 				   slot, btrfs_disk_key_objectid(&disk_key),
30647c15d410SQu Wenruo 				   btrfs_disk_key_type(&disk_key),
30657c15d410SQu Wenruo 				   btrfs_disk_key_offset(&disk_key),
30667c15d410SQu Wenruo 				   new_key->objectid, new_key->type,
30677c15d410SQu Wenruo 				   new_key->offset);
30687c15d410SQu Wenruo 			btrfs_print_leaf(eb);
30697c15d410SQu Wenruo 			BUG();
30707c15d410SQu Wenruo 		}
307131840ae1SZheng Yan 	}
307231840ae1SZheng Yan 
307331840ae1SZheng Yan 	btrfs_cpu_key_to_disk(&disk_key, new_key);
307431840ae1SZheng Yan 	btrfs_set_item_key(eb, &disk_key, slot);
307531840ae1SZheng Yan 	btrfs_mark_buffer_dirty(eb);
307631840ae1SZheng Yan 	if (slot == 0)
3077b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, 1);
307831840ae1SZheng Yan }
307931840ae1SZheng Yan 
308031840ae1SZheng Yan /*
3081d16c702fSQu Wenruo  * Check key order of two sibling extent buffers.
3082d16c702fSQu Wenruo  *
3083d16c702fSQu Wenruo  * Return true if something is wrong.
3084d16c702fSQu Wenruo  * Return false if everything is fine.
3085d16c702fSQu Wenruo  *
3086d16c702fSQu Wenruo  * Tree-checker only works inside one tree block, thus the following
3087d16c702fSQu Wenruo  * corruption can not be detected by tree-checker:
3088d16c702fSQu Wenruo  *
3089d16c702fSQu Wenruo  * Leaf @left			| Leaf @right
3090d16c702fSQu Wenruo  * --------------------------------------------------------------
3091d16c702fSQu Wenruo  * | 1 | 2 | 3 | 4 | 5 | f6 |   | 7 | 8 |
3092d16c702fSQu Wenruo  *
3093d16c702fSQu Wenruo  * Key f6 in leaf @left itself is valid, but not valid when the next
3094d16c702fSQu Wenruo  * key in leaf @right is 7.
3095d16c702fSQu Wenruo  * This can only be checked at tree block merge time.
3096d16c702fSQu Wenruo  * And since tree checker has ensured all key order in each tree block
3097d16c702fSQu Wenruo  * is correct, we only need to bother the last key of @left and the first
3098d16c702fSQu Wenruo  * key of @right.
3099d16c702fSQu Wenruo  */
3100d16c702fSQu Wenruo static bool check_sibling_keys(struct extent_buffer *left,
3101d16c702fSQu Wenruo 			       struct extent_buffer *right)
3102d16c702fSQu Wenruo {
3103d16c702fSQu Wenruo 	struct btrfs_key left_last;
3104d16c702fSQu Wenruo 	struct btrfs_key right_first;
3105d16c702fSQu Wenruo 	int level = btrfs_header_level(left);
3106d16c702fSQu Wenruo 	int nr_left = btrfs_header_nritems(left);
3107d16c702fSQu Wenruo 	int nr_right = btrfs_header_nritems(right);
3108d16c702fSQu Wenruo 
3109d16c702fSQu Wenruo 	/* No key to check in one of the tree blocks */
3110d16c702fSQu Wenruo 	if (!nr_left || !nr_right)
3111d16c702fSQu Wenruo 		return false;
3112d16c702fSQu Wenruo 
3113d16c702fSQu Wenruo 	if (level) {
3114d16c702fSQu Wenruo 		btrfs_node_key_to_cpu(left, &left_last, nr_left - 1);
3115d16c702fSQu Wenruo 		btrfs_node_key_to_cpu(right, &right_first, 0);
3116d16c702fSQu Wenruo 	} else {
3117d16c702fSQu Wenruo 		btrfs_item_key_to_cpu(left, &left_last, nr_left - 1);
3118d16c702fSQu Wenruo 		btrfs_item_key_to_cpu(right, &right_first, 0);
3119d16c702fSQu Wenruo 	}
3120d16c702fSQu Wenruo 
3121d16c702fSQu Wenruo 	if (btrfs_comp_cpu_keys(&left_last, &right_first) >= 0) {
3122d16c702fSQu Wenruo 		btrfs_crit(left->fs_info,
3123d16c702fSQu Wenruo "bad key order, sibling blocks, left last (%llu %u %llu) right first (%llu %u %llu)",
3124d16c702fSQu Wenruo 			   left_last.objectid, left_last.type,
3125d16c702fSQu Wenruo 			   left_last.offset, right_first.objectid,
3126d16c702fSQu Wenruo 			   right_first.type, right_first.offset);
3127d16c702fSQu Wenruo 		return true;
3128d16c702fSQu Wenruo 	}
3129d16c702fSQu Wenruo 	return false;
3130d16c702fSQu Wenruo }
3131d16c702fSQu Wenruo 
3132d16c702fSQu Wenruo /*
313374123bd7SChris Mason  * try to push data from one node into the next node left in the
313479f95c82SChris Mason  * tree.
3135aa5d6bedSChris Mason  *
3136aa5d6bedSChris Mason  * returns 0 if some ptrs were pushed left, < 0 if there was some horrible
3137aa5d6bedSChris Mason  * error, and > 0 if there was no room in the left hand block.
313874123bd7SChris Mason  */
313998ed5174SChris Mason static int push_node_left(struct btrfs_trans_handle *trans,
31402ff7e61eSJeff Mahoney 			  struct extent_buffer *dst,
3141971a1f66SChris Mason 			  struct extent_buffer *src, int empty)
3142be0e5c09SChris Mason {
3143d30a668fSDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
3144be0e5c09SChris Mason 	int push_items = 0;
3145bb803951SChris Mason 	int src_nritems;
3146bb803951SChris Mason 	int dst_nritems;
3147aa5d6bedSChris Mason 	int ret = 0;
3148be0e5c09SChris Mason 
31495f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
31505f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
31510b246afaSJeff Mahoney 	push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
31527bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
31537bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
315454aa1f4dSChris Mason 
3155bce4eae9SChris Mason 	if (!empty && src_nritems <= 8)
3156971a1f66SChris Mason 		return 1;
3157971a1f66SChris Mason 
3158d397712bSChris Mason 	if (push_items <= 0)
3159be0e5c09SChris Mason 		return 1;
3160be0e5c09SChris Mason 
3161bce4eae9SChris Mason 	if (empty) {
3162971a1f66SChris Mason 		push_items = min(src_nritems, push_items);
3163bce4eae9SChris Mason 		if (push_items < src_nritems) {
3164bce4eae9SChris Mason 			/* leave at least 8 pointers in the node if
3165bce4eae9SChris Mason 			 * we aren't going to empty it
3166bce4eae9SChris Mason 			 */
3167bce4eae9SChris Mason 			if (src_nritems - push_items < 8) {
3168bce4eae9SChris Mason 				if (push_items <= 8)
3169bce4eae9SChris Mason 					return 1;
3170bce4eae9SChris Mason 				push_items -= 8;
3171bce4eae9SChris Mason 			}
3172bce4eae9SChris Mason 		}
3173bce4eae9SChris Mason 	} else
3174bce4eae9SChris Mason 		push_items = min(src_nritems - 8, push_items);
317579f95c82SChris Mason 
3176d16c702fSQu Wenruo 	/* dst is the left eb, src is the middle eb */
3177d16c702fSQu Wenruo 	if (check_sibling_keys(dst, src)) {
3178d16c702fSQu Wenruo 		ret = -EUCLEAN;
3179d16c702fSQu Wenruo 		btrfs_abort_transaction(trans, ret);
3180d16c702fSQu Wenruo 		return ret;
3181d16c702fSQu Wenruo 	}
3182ed874f0dSDavid Sterba 	ret = tree_mod_log_eb_copy(dst, src, dst_nritems, 0, push_items);
31835de865eeSFilipe David Borba Manana 	if (ret) {
318466642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
31855de865eeSFilipe David Borba Manana 		return ret;
31865de865eeSFilipe David Borba Manana 	}
31875f39d397SChris Mason 	copy_extent_buffer(dst, src,
31885f39d397SChris Mason 			   btrfs_node_key_ptr_offset(dst_nritems),
31895f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
3190123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
31915f39d397SChris Mason 
3192bb803951SChris Mason 	if (push_items < src_nritems) {
319357911b8bSJan Schmidt 		/*
3194bf1d3425SDavid Sterba 		 * Don't call tree_mod_log_insert_move here, key removal was
3195bf1d3425SDavid Sterba 		 * already fully logged by tree_mod_log_eb_copy above.
319657911b8bSJan Schmidt 		 */
31975f39d397SChris Mason 		memmove_extent_buffer(src, btrfs_node_key_ptr_offset(0),
31985f39d397SChris Mason 				      btrfs_node_key_ptr_offset(push_items),
3199e2fa7227SChris Mason 				      (src_nritems - push_items) *
3200123abc88SChris Mason 				      sizeof(struct btrfs_key_ptr));
3201bb803951SChris Mason 	}
32025f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
32035f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
32045f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
32055f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
320631840ae1SZheng Yan 
3207bb803951SChris Mason 	return ret;
3208be0e5c09SChris Mason }
3209be0e5c09SChris Mason 
321097571fd0SChris Mason /*
321179f95c82SChris Mason  * try to push data from one node into the next node right in the
321279f95c82SChris Mason  * tree.
321379f95c82SChris Mason  *
321479f95c82SChris Mason  * returns 0 if some ptrs were pushed, < 0 if there was some horrible
321579f95c82SChris Mason  * error, and > 0 if there was no room in the right hand block.
321679f95c82SChris Mason  *
321779f95c82SChris Mason  * this will  only push up to 1/2 the contents of the left node over
321879f95c82SChris Mason  */
32195f39d397SChris Mason static int balance_node_right(struct btrfs_trans_handle *trans,
32205f39d397SChris Mason 			      struct extent_buffer *dst,
32215f39d397SChris Mason 			      struct extent_buffer *src)
322279f95c82SChris Mason {
322355d32ed8SDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
322479f95c82SChris Mason 	int push_items = 0;
322579f95c82SChris Mason 	int max_push;
322679f95c82SChris Mason 	int src_nritems;
322779f95c82SChris Mason 	int dst_nritems;
322879f95c82SChris Mason 	int ret = 0;
322979f95c82SChris Mason 
32307bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
32317bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
32327bb86316SChris Mason 
32335f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
32345f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
32350b246afaSJeff Mahoney 	push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
3236d397712bSChris Mason 	if (push_items <= 0)
323779f95c82SChris Mason 		return 1;
3238bce4eae9SChris Mason 
3239d397712bSChris Mason 	if (src_nritems < 4)
3240bce4eae9SChris Mason 		return 1;
324179f95c82SChris Mason 
324279f95c82SChris Mason 	max_push = src_nritems / 2 + 1;
324379f95c82SChris Mason 	/* don't try to empty the node */
3244d397712bSChris Mason 	if (max_push >= src_nritems)
324579f95c82SChris Mason 		return 1;
3246252c38f0SYan 
324779f95c82SChris Mason 	if (max_push < push_items)
324879f95c82SChris Mason 		push_items = max_push;
324979f95c82SChris Mason 
3250d16c702fSQu Wenruo 	/* dst is the right eb, src is the middle eb */
3251d16c702fSQu Wenruo 	if (check_sibling_keys(src, dst)) {
3252d16c702fSQu Wenruo 		ret = -EUCLEAN;
3253d16c702fSQu Wenruo 		btrfs_abort_transaction(trans, ret);
3254d16c702fSQu Wenruo 		return ret;
3255d16c702fSQu Wenruo 	}
3256bf1d3425SDavid Sterba 	ret = tree_mod_log_insert_move(dst, push_items, 0, dst_nritems);
3257bf1d3425SDavid Sterba 	BUG_ON(ret < 0);
32585f39d397SChris Mason 	memmove_extent_buffer(dst, btrfs_node_key_ptr_offset(push_items),
32595f39d397SChris Mason 				      btrfs_node_key_ptr_offset(0),
32605f39d397SChris Mason 				      (dst_nritems) *
32615f39d397SChris Mason 				      sizeof(struct btrfs_key_ptr));
3262d6025579SChris Mason 
3263ed874f0dSDavid Sterba 	ret = tree_mod_log_eb_copy(dst, src, 0, src_nritems - push_items,
3264ed874f0dSDavid Sterba 				   push_items);
32655de865eeSFilipe David Borba Manana 	if (ret) {
326666642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
32675de865eeSFilipe David Borba Manana 		return ret;
32685de865eeSFilipe David Borba Manana 	}
32695f39d397SChris Mason 	copy_extent_buffer(dst, src,
32705f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
32715f39d397SChris Mason 			   btrfs_node_key_ptr_offset(src_nritems - push_items),
3272123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
327379f95c82SChris Mason 
32745f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
32755f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
327679f95c82SChris Mason 
32775f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
32785f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
327931840ae1SZheng Yan 
328079f95c82SChris Mason 	return ret;
328179f95c82SChris Mason }
328279f95c82SChris Mason 
328379f95c82SChris Mason /*
328497571fd0SChris Mason  * helper function to insert a new root level in the tree.
328597571fd0SChris Mason  * A new node is allocated, and a single item is inserted to
328697571fd0SChris Mason  * point to the existing root
3287aa5d6bedSChris Mason  *
3288aa5d6bedSChris Mason  * returns zero on success or < 0 on failure.
328997571fd0SChris Mason  */
3290d397712bSChris Mason static noinline int insert_new_root(struct btrfs_trans_handle *trans,
32915f39d397SChris Mason 			   struct btrfs_root *root,
3292fdd99c72SLiu Bo 			   struct btrfs_path *path, int level)
329374123bd7SChris Mason {
32940b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
32957bb86316SChris Mason 	u64 lower_gen;
32965f39d397SChris Mason 	struct extent_buffer *lower;
32975f39d397SChris Mason 	struct extent_buffer *c;
3298925baeddSChris Mason 	struct extent_buffer *old;
32995f39d397SChris Mason 	struct btrfs_disk_key lower_key;
3300d9d19a01SDavid Sterba 	int ret;
33015c680ed6SChris Mason 
33025c680ed6SChris Mason 	BUG_ON(path->nodes[level]);
33035c680ed6SChris Mason 	BUG_ON(path->nodes[level-1] != root->node);
33045c680ed6SChris Mason 
33057bb86316SChris Mason 	lower = path->nodes[level-1];
33067bb86316SChris Mason 	if (level == 1)
33077bb86316SChris Mason 		btrfs_item_key(lower, &lower_key, 0);
33087bb86316SChris Mason 	else
33097bb86316SChris Mason 		btrfs_node_key(lower, &lower_key, 0);
33107bb86316SChris Mason 
3311a6279470SFilipe Manana 	c = alloc_tree_block_no_bg_flush(trans, root, 0, &lower_key, level,
33129631e4ccSJosef Bacik 					 root->node->start, 0,
3313cf6f34aaSJosef Bacik 					 BTRFS_NESTING_NEW_ROOT);
33145f39d397SChris Mason 	if (IS_ERR(c))
33155f39d397SChris Mason 		return PTR_ERR(c);
3316925baeddSChris Mason 
33170b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
3318f0486c68SYan, Zheng 
33195f39d397SChris Mason 	btrfs_set_header_nritems(c, 1);
33205f39d397SChris Mason 	btrfs_set_node_key(c, &lower_key, 0);
3321db94535dSChris Mason 	btrfs_set_node_blockptr(c, 0, lower->start);
33227bb86316SChris Mason 	lower_gen = btrfs_header_generation(lower);
332331840ae1SZheng Yan 	WARN_ON(lower_gen != trans->transid);
33247bb86316SChris Mason 
33257bb86316SChris Mason 	btrfs_set_node_ptr_generation(c, 0, lower_gen);
33265f39d397SChris Mason 
33275f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
3328d5719762SChris Mason 
3329925baeddSChris Mason 	old = root->node;
3330d9d19a01SDavid Sterba 	ret = tree_mod_log_insert_root(root->node, c, 0);
3331d9d19a01SDavid Sterba 	BUG_ON(ret < 0);
3332240f62c8SChris Mason 	rcu_assign_pointer(root->node, c);
3333925baeddSChris Mason 
3334925baeddSChris Mason 	/* the super has an extra ref to root->node */
3335925baeddSChris Mason 	free_extent_buffer(old);
3336925baeddSChris Mason 
33370b86a832SChris Mason 	add_root_to_dirty_list(root);
333867439dadSDavid Sterba 	atomic_inc(&c->refs);
33395f39d397SChris Mason 	path->nodes[level] = c;
3340ac5887c8SJosef Bacik 	path->locks[level] = BTRFS_WRITE_LOCK;
334174123bd7SChris Mason 	path->slots[level] = 0;
334274123bd7SChris Mason 	return 0;
334374123bd7SChris Mason }
33445c680ed6SChris Mason 
33455c680ed6SChris Mason /*
33465c680ed6SChris Mason  * worker function to insert a single pointer in a node.
33475c680ed6SChris Mason  * the node should have enough room for the pointer already
334897571fd0SChris Mason  *
33495c680ed6SChris Mason  * slot and level indicate where you want the key to go, and
33505c680ed6SChris Mason  * blocknr is the block the key points to.
33515c680ed6SChris Mason  */
3352143bede5SJeff Mahoney static void insert_ptr(struct btrfs_trans_handle *trans,
33536ad3cf6dSDavid Sterba 		       struct btrfs_path *path,
3354143bede5SJeff Mahoney 		       struct btrfs_disk_key *key, u64 bytenr,
3355c3e06965SJan Schmidt 		       int slot, int level)
33565c680ed6SChris Mason {
33575f39d397SChris Mason 	struct extent_buffer *lower;
33585c680ed6SChris Mason 	int nritems;
3359f3ea38daSJan Schmidt 	int ret;
33605c680ed6SChris Mason 
33615c680ed6SChris Mason 	BUG_ON(!path->nodes[level]);
3362f0486c68SYan, Zheng 	btrfs_assert_tree_locked(path->nodes[level]);
33635f39d397SChris Mason 	lower = path->nodes[level];
33645f39d397SChris Mason 	nritems = btrfs_header_nritems(lower);
3365c293498bSStoyan Gaydarov 	BUG_ON(slot > nritems);
33666ad3cf6dSDavid Sterba 	BUG_ON(nritems == BTRFS_NODEPTRS_PER_BLOCK(trans->fs_info));
336774123bd7SChris Mason 	if (slot != nritems) {
3368bf1d3425SDavid Sterba 		if (level) {
3369bf1d3425SDavid Sterba 			ret = tree_mod_log_insert_move(lower, slot + 1, slot,
3370a446a979SDavid Sterba 					nritems - slot);
3371bf1d3425SDavid Sterba 			BUG_ON(ret < 0);
3372bf1d3425SDavid Sterba 		}
33735f39d397SChris Mason 		memmove_extent_buffer(lower,
33745f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot + 1),
33755f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot),
3376123abc88SChris Mason 			      (nritems - slot) * sizeof(struct btrfs_key_ptr));
337774123bd7SChris Mason 	}
3378c3e06965SJan Schmidt 	if (level) {
3379e09c2efeSDavid Sterba 		ret = tree_mod_log_insert_key(lower, slot, MOD_LOG_KEY_ADD,
3380e09c2efeSDavid Sterba 				GFP_NOFS);
3381f3ea38daSJan Schmidt 		BUG_ON(ret < 0);
3382f3ea38daSJan Schmidt 	}
33835f39d397SChris Mason 	btrfs_set_node_key(lower, key, slot);
3384db94535dSChris Mason 	btrfs_set_node_blockptr(lower, slot, bytenr);
338574493f7aSChris Mason 	WARN_ON(trans->transid == 0);
338674493f7aSChris Mason 	btrfs_set_node_ptr_generation(lower, slot, trans->transid);
33875f39d397SChris Mason 	btrfs_set_header_nritems(lower, nritems + 1);
33885f39d397SChris Mason 	btrfs_mark_buffer_dirty(lower);
338974123bd7SChris Mason }
339074123bd7SChris Mason 
339197571fd0SChris Mason /*
339297571fd0SChris Mason  * split the node at the specified level in path in two.
339397571fd0SChris Mason  * The path is corrected to point to the appropriate node after the split
339497571fd0SChris Mason  *
339597571fd0SChris Mason  * Before splitting this tries to make some room in the node by pushing
339697571fd0SChris Mason  * left and right, if either one works, it returns right away.
3397aa5d6bedSChris Mason  *
3398aa5d6bedSChris Mason  * returns 0 on success and < 0 on failure
339997571fd0SChris Mason  */
3400e02119d5SChris Mason static noinline int split_node(struct btrfs_trans_handle *trans,
3401e02119d5SChris Mason 			       struct btrfs_root *root,
3402e02119d5SChris Mason 			       struct btrfs_path *path, int level)
3403be0e5c09SChris Mason {
34040b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
34055f39d397SChris Mason 	struct extent_buffer *c;
34065f39d397SChris Mason 	struct extent_buffer *split;
34075f39d397SChris Mason 	struct btrfs_disk_key disk_key;
3408be0e5c09SChris Mason 	int mid;
34095c680ed6SChris Mason 	int ret;
34107518a238SChris Mason 	u32 c_nritems;
3411be0e5c09SChris Mason 
34125f39d397SChris Mason 	c = path->nodes[level];
34137bb86316SChris Mason 	WARN_ON(btrfs_header_generation(c) != trans->transid);
34145f39d397SChris Mason 	if (c == root->node) {
3415d9abbf1cSJan Schmidt 		/*
341690f8d62eSJan Schmidt 		 * trying to split the root, lets make a new one
341790f8d62eSJan Schmidt 		 *
3418fdd99c72SLiu Bo 		 * tree mod log: We don't log_removal old root in
341990f8d62eSJan Schmidt 		 * insert_new_root, because that root buffer will be kept as a
342090f8d62eSJan Schmidt 		 * normal node. We are going to log removal of half of the
342190f8d62eSJan Schmidt 		 * elements below with tree_mod_log_eb_copy. We're holding a
342290f8d62eSJan Schmidt 		 * tree lock on the buffer, which is why we cannot race with
342390f8d62eSJan Schmidt 		 * other tree_mod_log users.
3424d9abbf1cSJan Schmidt 		 */
3425fdd99c72SLiu Bo 		ret = insert_new_root(trans, root, path, level + 1);
34265c680ed6SChris Mason 		if (ret)
34275c680ed6SChris Mason 			return ret;
3428b3612421SChris Mason 	} else {
3429e66f709bSChris Mason 		ret = push_nodes_for_insert(trans, root, path, level);
34305f39d397SChris Mason 		c = path->nodes[level];
34315f39d397SChris Mason 		if (!ret && btrfs_header_nritems(c) <
34320b246afaSJeff Mahoney 		    BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3)
3433e66f709bSChris Mason 			return 0;
343454aa1f4dSChris Mason 		if (ret < 0)
343554aa1f4dSChris Mason 			return ret;
34365c680ed6SChris Mason 	}
3437e66f709bSChris Mason 
34385f39d397SChris Mason 	c_nritems = btrfs_header_nritems(c);
34395d4f98a2SYan Zheng 	mid = (c_nritems + 1) / 2;
34405d4f98a2SYan Zheng 	btrfs_node_key(c, &disk_key, mid);
34417bb86316SChris Mason 
3442a6279470SFilipe Manana 	split = alloc_tree_block_no_bg_flush(trans, root, 0, &disk_key, level,
34434dff97e6SJosef Bacik 					     c->start, 0, BTRFS_NESTING_SPLIT);
34445f39d397SChris Mason 	if (IS_ERR(split))
34455f39d397SChris Mason 		return PTR_ERR(split);
344654aa1f4dSChris Mason 
34470b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
3448bc877d28SNikolay Borisov 	ASSERT(btrfs_header_level(c) == level);
34495f39d397SChris Mason 
3450ed874f0dSDavid Sterba 	ret = tree_mod_log_eb_copy(split, c, 0, mid, c_nritems - mid);
34515de865eeSFilipe David Borba Manana 	if (ret) {
345266642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
34535de865eeSFilipe David Borba Manana 		return ret;
34545de865eeSFilipe David Borba Manana 	}
34555f39d397SChris Mason 	copy_extent_buffer(split, c,
34565f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
34575f39d397SChris Mason 			   btrfs_node_key_ptr_offset(mid),
3458123abc88SChris Mason 			   (c_nritems - mid) * sizeof(struct btrfs_key_ptr));
34595f39d397SChris Mason 	btrfs_set_header_nritems(split, c_nritems - mid);
34605f39d397SChris Mason 	btrfs_set_header_nritems(c, mid);
3461aa5d6bedSChris Mason 	ret = 0;
3462aa5d6bedSChris Mason 
34635f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
34645f39d397SChris Mason 	btrfs_mark_buffer_dirty(split);
34655f39d397SChris Mason 
34666ad3cf6dSDavid Sterba 	insert_ptr(trans, path, &disk_key, split->start,
3467c3e06965SJan Schmidt 		   path->slots[level + 1] + 1, level + 1);
3468aa5d6bedSChris Mason 
34695de08d7dSChris Mason 	if (path->slots[level] >= mid) {
34705c680ed6SChris Mason 		path->slots[level] -= mid;
3471925baeddSChris Mason 		btrfs_tree_unlock(c);
34725f39d397SChris Mason 		free_extent_buffer(c);
34735f39d397SChris Mason 		path->nodes[level] = split;
34745c680ed6SChris Mason 		path->slots[level + 1] += 1;
3475eb60ceacSChris Mason 	} else {
3476925baeddSChris Mason 		btrfs_tree_unlock(split);
34775f39d397SChris Mason 		free_extent_buffer(split);
3478be0e5c09SChris Mason 	}
3479aa5d6bedSChris Mason 	return ret;
3480be0e5c09SChris Mason }
3481be0e5c09SChris Mason 
348274123bd7SChris Mason /*
348374123bd7SChris Mason  * how many bytes are required to store the items in a leaf.  start
348474123bd7SChris Mason  * and nr indicate which items in the leaf to check.  This totals up the
348574123bd7SChris Mason  * space used both by the item structs and the item data
348674123bd7SChris Mason  */
34875f39d397SChris Mason static int leaf_space_used(struct extent_buffer *l, int start, int nr)
3488be0e5c09SChris Mason {
348941be1f3bSJosef Bacik 	struct btrfs_item *start_item;
349041be1f3bSJosef Bacik 	struct btrfs_item *end_item;
3491be0e5c09SChris Mason 	int data_len;
34925f39d397SChris Mason 	int nritems = btrfs_header_nritems(l);
3493d4dbff95SChris Mason 	int end = min(nritems, start + nr) - 1;
3494be0e5c09SChris Mason 
3495be0e5c09SChris Mason 	if (!nr)
3496be0e5c09SChris Mason 		return 0;
3497dd3cc16bSRoss Kirk 	start_item = btrfs_item_nr(start);
3498dd3cc16bSRoss Kirk 	end_item = btrfs_item_nr(end);
3499a31356b9SDavid Sterba 	data_len = btrfs_item_offset(l, start_item) +
3500a31356b9SDavid Sterba 		   btrfs_item_size(l, start_item);
3501a31356b9SDavid Sterba 	data_len = data_len - btrfs_item_offset(l, end_item);
35020783fcfcSChris Mason 	data_len += sizeof(struct btrfs_item) * nr;
3503d4dbff95SChris Mason 	WARN_ON(data_len < 0);
3504be0e5c09SChris Mason 	return data_len;
3505be0e5c09SChris Mason }
3506be0e5c09SChris Mason 
350774123bd7SChris Mason /*
3508d4dbff95SChris Mason  * The space between the end of the leaf items and
3509d4dbff95SChris Mason  * the start of the leaf data.  IOW, how much room
3510d4dbff95SChris Mason  * the leaf has left for both items and data
3511d4dbff95SChris Mason  */
3512e902baacSDavid Sterba noinline int btrfs_leaf_free_space(struct extent_buffer *leaf)
3513d4dbff95SChris Mason {
3514e902baacSDavid Sterba 	struct btrfs_fs_info *fs_info = leaf->fs_info;
35155f39d397SChris Mason 	int nritems = btrfs_header_nritems(leaf);
35165f39d397SChris Mason 	int ret;
35170b246afaSJeff Mahoney 
35180b246afaSJeff Mahoney 	ret = BTRFS_LEAF_DATA_SIZE(fs_info) - leaf_space_used(leaf, 0, nritems);
35195f39d397SChris Mason 	if (ret < 0) {
35200b246afaSJeff Mahoney 		btrfs_crit(fs_info,
3521efe120a0SFrank Holton 			   "leaf free space ret %d, leaf data size %lu, used %d nritems %d",
3522da17066cSJeff Mahoney 			   ret,
35230b246afaSJeff Mahoney 			   (unsigned long) BTRFS_LEAF_DATA_SIZE(fs_info),
35245f39d397SChris Mason 			   leaf_space_used(leaf, 0, nritems), nritems);
35255f39d397SChris Mason 	}
35265f39d397SChris Mason 	return ret;
3527d4dbff95SChris Mason }
3528d4dbff95SChris Mason 
352999d8f83cSChris Mason /*
353099d8f83cSChris Mason  * min slot controls the lowest index we're willing to push to the
353199d8f83cSChris Mason  * right.  We'll push up to and including min_slot, but no lower
353299d8f83cSChris Mason  */
3533f72f0010SDavid Sterba static noinline int __push_leaf_right(struct btrfs_path *path,
353444871b1bSChris Mason 				      int data_size, int empty,
353544871b1bSChris Mason 				      struct extent_buffer *right,
353699d8f83cSChris Mason 				      int free_space, u32 left_nritems,
353799d8f83cSChris Mason 				      u32 min_slot)
353800ec4c51SChris Mason {
3539f72f0010SDavid Sterba 	struct btrfs_fs_info *fs_info = right->fs_info;
35405f39d397SChris Mason 	struct extent_buffer *left = path->nodes[0];
354144871b1bSChris Mason 	struct extent_buffer *upper = path->nodes[1];
3542cfed81a0SChris Mason 	struct btrfs_map_token token;
35435f39d397SChris Mason 	struct btrfs_disk_key disk_key;
354400ec4c51SChris Mason 	int slot;
354534a38218SChris Mason 	u32 i;
354600ec4c51SChris Mason 	int push_space = 0;
354700ec4c51SChris Mason 	int push_items = 0;
35480783fcfcSChris Mason 	struct btrfs_item *item;
354934a38218SChris Mason 	u32 nr;
35507518a238SChris Mason 	u32 right_nritems;
35515f39d397SChris Mason 	u32 data_end;
3552db94535dSChris Mason 	u32 this_item_size;
355300ec4c51SChris Mason 
355434a38218SChris Mason 	if (empty)
355534a38218SChris Mason 		nr = 0;
355634a38218SChris Mason 	else
355799d8f83cSChris Mason 		nr = max_t(u32, 1, min_slot);
355834a38218SChris Mason 
355931840ae1SZheng Yan 	if (path->slots[0] >= left_nritems)
356087b29b20SYan Zheng 		push_space += data_size;
356131840ae1SZheng Yan 
356244871b1bSChris Mason 	slot = path->slots[1];
356334a38218SChris Mason 	i = left_nritems - 1;
356434a38218SChris Mason 	while (i >= nr) {
3565dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
3566db94535dSChris Mason 
356731840ae1SZheng Yan 		if (!empty && push_items > 0) {
356831840ae1SZheng Yan 			if (path->slots[0] > i)
356931840ae1SZheng Yan 				break;
357031840ae1SZheng Yan 			if (path->slots[0] == i) {
3571e902baacSDavid Sterba 				int space = btrfs_leaf_free_space(left);
3572e902baacSDavid Sterba 
357331840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
357431840ae1SZheng Yan 					break;
357531840ae1SZheng Yan 			}
357631840ae1SZheng Yan 		}
357731840ae1SZheng Yan 
357800ec4c51SChris Mason 		if (path->slots[0] == i)
357987b29b20SYan Zheng 			push_space += data_size;
3580db94535dSChris Mason 
3581db94535dSChris Mason 		this_item_size = btrfs_item_size(left, item);
3582db94535dSChris Mason 		if (this_item_size + sizeof(*item) + push_space > free_space)
358300ec4c51SChris Mason 			break;
358431840ae1SZheng Yan 
358500ec4c51SChris Mason 		push_items++;
3586db94535dSChris Mason 		push_space += this_item_size + sizeof(*item);
358734a38218SChris Mason 		if (i == 0)
358834a38218SChris Mason 			break;
358934a38218SChris Mason 		i--;
3590db94535dSChris Mason 	}
35915f39d397SChris Mason 
3592925baeddSChris Mason 	if (push_items == 0)
3593925baeddSChris Mason 		goto out_unlock;
35945f39d397SChris Mason 
35956c1500f2SJulia Lawall 	WARN_ON(!empty && push_items == left_nritems);
35965f39d397SChris Mason 
359700ec4c51SChris Mason 	/* push left to right */
35985f39d397SChris Mason 	right_nritems = btrfs_header_nritems(right);
359934a38218SChris Mason 
36005f39d397SChris Mason 	push_space = btrfs_item_end_nr(left, left_nritems - push_items);
36018f881e8cSDavid Sterba 	push_space -= leaf_data_end(left);
36025f39d397SChris Mason 
360300ec4c51SChris Mason 	/* make room in the right data area */
36048f881e8cSDavid Sterba 	data_end = leaf_data_end(right);
36055f39d397SChris Mason 	memmove_extent_buffer(right,
36063d9ec8c4SNikolay Borisov 			      BTRFS_LEAF_DATA_OFFSET + data_end - push_space,
36073d9ec8c4SNikolay Borisov 			      BTRFS_LEAF_DATA_OFFSET + data_end,
36080b246afaSJeff Mahoney 			      BTRFS_LEAF_DATA_SIZE(fs_info) - data_end);
36095f39d397SChris Mason 
361000ec4c51SChris Mason 	/* copy from the left data area */
36113d9ec8c4SNikolay Borisov 	copy_extent_buffer(right, left, BTRFS_LEAF_DATA_OFFSET +
36120b246afaSJeff Mahoney 		     BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
36138f881e8cSDavid Sterba 		     BTRFS_LEAF_DATA_OFFSET + leaf_data_end(left),
3614d6025579SChris Mason 		     push_space);
36155f39d397SChris Mason 
36165f39d397SChris Mason 	memmove_extent_buffer(right, btrfs_item_nr_offset(push_items),
36175f39d397SChris Mason 			      btrfs_item_nr_offset(0),
36180783fcfcSChris Mason 			      right_nritems * sizeof(struct btrfs_item));
36195f39d397SChris Mason 
362000ec4c51SChris Mason 	/* copy the items from left to right */
36215f39d397SChris Mason 	copy_extent_buffer(right, left, btrfs_item_nr_offset(0),
36225f39d397SChris Mason 		   btrfs_item_nr_offset(left_nritems - push_items),
36230783fcfcSChris Mason 		   push_items * sizeof(struct btrfs_item));
362400ec4c51SChris Mason 
362500ec4c51SChris Mason 	/* update the item pointers */
3626c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
36277518a238SChris Mason 	right_nritems += push_items;
36285f39d397SChris Mason 	btrfs_set_header_nritems(right, right_nritems);
36290b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
36307518a238SChris Mason 	for (i = 0; i < right_nritems; i++) {
3631dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
3632cc4c13d5SDavid Sterba 		push_space -= btrfs_token_item_size(&token, item);
3633cc4c13d5SDavid Sterba 		btrfs_set_token_item_offset(&token, item, push_space);
3634db94535dSChris Mason 	}
3635db94535dSChris Mason 
36367518a238SChris Mason 	left_nritems -= push_items;
36375f39d397SChris Mason 	btrfs_set_header_nritems(left, left_nritems);
363800ec4c51SChris Mason 
363934a38218SChris Mason 	if (left_nritems)
36405f39d397SChris Mason 		btrfs_mark_buffer_dirty(left);
3641f0486c68SYan, Zheng 	else
36426a884d7dSDavid Sterba 		btrfs_clean_tree_block(left);
3643f0486c68SYan, Zheng 
36445f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
3645a429e513SChris Mason 
36465f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
36475f39d397SChris Mason 	btrfs_set_node_key(upper, &disk_key, slot + 1);
3648d6025579SChris Mason 	btrfs_mark_buffer_dirty(upper);
364902217ed2SChris Mason 
365000ec4c51SChris Mason 	/* then fixup the leaf pointer in the path */
36517518a238SChris Mason 	if (path->slots[0] >= left_nritems) {
36527518a238SChris Mason 		path->slots[0] -= left_nritems;
3653925baeddSChris Mason 		if (btrfs_header_nritems(path->nodes[0]) == 0)
36546a884d7dSDavid Sterba 			btrfs_clean_tree_block(path->nodes[0]);
3655925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
36565f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
36575f39d397SChris Mason 		path->nodes[0] = right;
365800ec4c51SChris Mason 		path->slots[1] += 1;
365900ec4c51SChris Mason 	} else {
3660925baeddSChris Mason 		btrfs_tree_unlock(right);
36615f39d397SChris Mason 		free_extent_buffer(right);
366200ec4c51SChris Mason 	}
366300ec4c51SChris Mason 	return 0;
3664925baeddSChris Mason 
3665925baeddSChris Mason out_unlock:
3666925baeddSChris Mason 	btrfs_tree_unlock(right);
3667925baeddSChris Mason 	free_extent_buffer(right);
3668925baeddSChris Mason 	return 1;
366900ec4c51SChris Mason }
3670925baeddSChris Mason 
367100ec4c51SChris Mason /*
367244871b1bSChris Mason  * push some data in the path leaf to the right, trying to free up at
367374123bd7SChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
367444871b1bSChris Mason  *
367544871b1bSChris Mason  * returns 1 if the push failed because the other node didn't have enough
367644871b1bSChris Mason  * room, 0 if everything worked out and < 0 if there were major errors.
367799d8f83cSChris Mason  *
367899d8f83cSChris Mason  * this will push starting from min_slot to the end of the leaf.  It won't
367999d8f83cSChris Mason  * push any slot lower than min_slot
368074123bd7SChris Mason  */
368144871b1bSChris Mason static int push_leaf_right(struct btrfs_trans_handle *trans, struct btrfs_root
368299d8f83cSChris Mason 			   *root, struct btrfs_path *path,
368399d8f83cSChris Mason 			   int min_data_size, int data_size,
368499d8f83cSChris Mason 			   int empty, u32 min_slot)
3685be0e5c09SChris Mason {
368644871b1bSChris Mason 	struct extent_buffer *left = path->nodes[0];
368744871b1bSChris Mason 	struct extent_buffer *right;
368844871b1bSChris Mason 	struct extent_buffer *upper;
368944871b1bSChris Mason 	int slot;
369044871b1bSChris Mason 	int free_space;
369144871b1bSChris Mason 	u32 left_nritems;
369244871b1bSChris Mason 	int ret;
369344871b1bSChris Mason 
369444871b1bSChris Mason 	if (!path->nodes[1])
369544871b1bSChris Mason 		return 1;
369644871b1bSChris Mason 
369744871b1bSChris Mason 	slot = path->slots[1];
369844871b1bSChris Mason 	upper = path->nodes[1];
369944871b1bSChris Mason 	if (slot >= btrfs_header_nritems(upper) - 1)
370044871b1bSChris Mason 		return 1;
370144871b1bSChris Mason 
370244871b1bSChris Mason 	btrfs_assert_tree_locked(path->nodes[1]);
370344871b1bSChris Mason 
37044b231ae4SDavid Sterba 	right = btrfs_read_node_slot(upper, slot + 1);
3705fb770ae4SLiu Bo 	/*
3706fb770ae4SLiu Bo 	 * slot + 1 is not valid or we fail to read the right node,
3707fb770ae4SLiu Bo 	 * no big deal, just return.
3708fb770ae4SLiu Bo 	 */
3709fb770ae4SLiu Bo 	if (IS_ERR(right))
371091ca338dSTsutomu Itoh 		return 1;
371191ca338dSTsutomu Itoh 
3712bf77467aSJosef Bacik 	__btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
371344871b1bSChris Mason 
3714e902baacSDavid Sterba 	free_space = btrfs_leaf_free_space(right);
371544871b1bSChris Mason 	if (free_space < data_size)
371644871b1bSChris Mason 		goto out_unlock;
371744871b1bSChris Mason 
371844871b1bSChris Mason 	/* cow and double check */
371944871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, right, upper,
3720bf59a5a2SJosef Bacik 			      slot + 1, &right, BTRFS_NESTING_RIGHT_COW);
372144871b1bSChris Mason 	if (ret)
372244871b1bSChris Mason 		goto out_unlock;
372344871b1bSChris Mason 
3724e902baacSDavid Sterba 	free_space = btrfs_leaf_free_space(right);
372544871b1bSChris Mason 	if (free_space < data_size)
372644871b1bSChris Mason 		goto out_unlock;
372744871b1bSChris Mason 
372844871b1bSChris Mason 	left_nritems = btrfs_header_nritems(left);
372944871b1bSChris Mason 	if (left_nritems == 0)
373044871b1bSChris Mason 		goto out_unlock;
373144871b1bSChris Mason 
3732d16c702fSQu Wenruo 	if (check_sibling_keys(left, right)) {
3733d16c702fSQu Wenruo 		ret = -EUCLEAN;
3734d16c702fSQu Wenruo 		btrfs_tree_unlock(right);
3735d16c702fSQu Wenruo 		free_extent_buffer(right);
3736d16c702fSQu Wenruo 		return ret;
3737d16c702fSQu Wenruo 	}
37382ef1fed2SFilipe David Borba Manana 	if (path->slots[0] == left_nritems && !empty) {
37392ef1fed2SFilipe David Borba Manana 		/* Key greater than all keys in the leaf, right neighbor has
37402ef1fed2SFilipe David Borba Manana 		 * enough room for it and we're not emptying our leaf to delete
37412ef1fed2SFilipe David Borba Manana 		 * it, therefore use right neighbor to insert the new item and
374252042d8eSAndrea Gelmini 		 * no need to touch/dirty our left leaf. */
37432ef1fed2SFilipe David Borba Manana 		btrfs_tree_unlock(left);
37442ef1fed2SFilipe David Borba Manana 		free_extent_buffer(left);
37452ef1fed2SFilipe David Borba Manana 		path->nodes[0] = right;
37462ef1fed2SFilipe David Borba Manana 		path->slots[0] = 0;
37472ef1fed2SFilipe David Borba Manana 		path->slots[1]++;
37482ef1fed2SFilipe David Borba Manana 		return 0;
37492ef1fed2SFilipe David Borba Manana 	}
37502ef1fed2SFilipe David Borba Manana 
3751f72f0010SDavid Sterba 	return __push_leaf_right(path, min_data_size, empty,
375299d8f83cSChris Mason 				right, free_space, left_nritems, min_slot);
375344871b1bSChris Mason out_unlock:
375444871b1bSChris Mason 	btrfs_tree_unlock(right);
375544871b1bSChris Mason 	free_extent_buffer(right);
375644871b1bSChris Mason 	return 1;
375744871b1bSChris Mason }
375844871b1bSChris Mason 
375944871b1bSChris Mason /*
376044871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
376144871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
376299d8f83cSChris Mason  *
376399d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
376499d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us do all the
376599d8f83cSChris Mason  * items
376644871b1bSChris Mason  */
37678087c193SDavid Sterba static noinline int __push_leaf_left(struct btrfs_path *path, int data_size,
376844871b1bSChris Mason 				     int empty, struct extent_buffer *left,
376999d8f83cSChris Mason 				     int free_space, u32 right_nritems,
377099d8f83cSChris Mason 				     u32 max_slot)
377144871b1bSChris Mason {
37728087c193SDavid Sterba 	struct btrfs_fs_info *fs_info = left->fs_info;
37735f39d397SChris Mason 	struct btrfs_disk_key disk_key;
37745f39d397SChris Mason 	struct extent_buffer *right = path->nodes[0];
3775be0e5c09SChris Mason 	int i;
3776be0e5c09SChris Mason 	int push_space = 0;
3777be0e5c09SChris Mason 	int push_items = 0;
37780783fcfcSChris Mason 	struct btrfs_item *item;
37797518a238SChris Mason 	u32 old_left_nritems;
378034a38218SChris Mason 	u32 nr;
3781aa5d6bedSChris Mason 	int ret = 0;
3782db94535dSChris Mason 	u32 this_item_size;
3783db94535dSChris Mason 	u32 old_left_item_size;
3784cfed81a0SChris Mason 	struct btrfs_map_token token;
3785cfed81a0SChris Mason 
378634a38218SChris Mason 	if (empty)
378799d8f83cSChris Mason 		nr = min(right_nritems, max_slot);
378834a38218SChris Mason 	else
378999d8f83cSChris Mason 		nr = min(right_nritems - 1, max_slot);
379034a38218SChris Mason 
379134a38218SChris Mason 	for (i = 0; i < nr; i++) {
3792dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
3793db94535dSChris Mason 
379431840ae1SZheng Yan 		if (!empty && push_items > 0) {
379531840ae1SZheng Yan 			if (path->slots[0] < i)
379631840ae1SZheng Yan 				break;
379731840ae1SZheng Yan 			if (path->slots[0] == i) {
3798e902baacSDavid Sterba 				int space = btrfs_leaf_free_space(right);
3799e902baacSDavid Sterba 
380031840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
380131840ae1SZheng Yan 					break;
380231840ae1SZheng Yan 			}
380331840ae1SZheng Yan 		}
380431840ae1SZheng Yan 
3805be0e5c09SChris Mason 		if (path->slots[0] == i)
380687b29b20SYan Zheng 			push_space += data_size;
3807db94535dSChris Mason 
3808db94535dSChris Mason 		this_item_size = btrfs_item_size(right, item);
3809db94535dSChris Mason 		if (this_item_size + sizeof(*item) + push_space > free_space)
3810be0e5c09SChris Mason 			break;
3811db94535dSChris Mason 
3812be0e5c09SChris Mason 		push_items++;
3813db94535dSChris Mason 		push_space += this_item_size + sizeof(*item);
3814be0e5c09SChris Mason 	}
3815db94535dSChris Mason 
3816be0e5c09SChris Mason 	if (push_items == 0) {
3817925baeddSChris Mason 		ret = 1;
3818925baeddSChris Mason 		goto out;
3819be0e5c09SChris Mason 	}
3820fae7f21cSDulshani Gunawardhana 	WARN_ON(!empty && push_items == btrfs_header_nritems(right));
38215f39d397SChris Mason 
3822be0e5c09SChris Mason 	/* push data from right to left */
38235f39d397SChris Mason 	copy_extent_buffer(left, right,
38245f39d397SChris Mason 			   btrfs_item_nr_offset(btrfs_header_nritems(left)),
38255f39d397SChris Mason 			   btrfs_item_nr_offset(0),
38265f39d397SChris Mason 			   push_items * sizeof(struct btrfs_item));
38275f39d397SChris Mason 
38280b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info) -
38295f39d397SChris Mason 		     btrfs_item_offset_nr(right, push_items - 1);
38305f39d397SChris Mason 
38313d9ec8c4SNikolay Borisov 	copy_extent_buffer(left, right, BTRFS_LEAF_DATA_OFFSET +
38328f881e8cSDavid Sterba 		     leaf_data_end(left) - push_space,
38333d9ec8c4SNikolay Borisov 		     BTRFS_LEAF_DATA_OFFSET +
38345f39d397SChris Mason 		     btrfs_item_offset_nr(right, push_items - 1),
3835be0e5c09SChris Mason 		     push_space);
38365f39d397SChris Mason 	old_left_nritems = btrfs_header_nritems(left);
383787b29b20SYan Zheng 	BUG_ON(old_left_nritems <= 0);
3838eb60ceacSChris Mason 
3839c82f823cSDavid Sterba 	btrfs_init_map_token(&token, left);
3840db94535dSChris Mason 	old_left_item_size = btrfs_item_offset_nr(left, old_left_nritems - 1);
3841be0e5c09SChris Mason 	for (i = old_left_nritems; i < old_left_nritems + push_items; i++) {
38425f39d397SChris Mason 		u32 ioff;
3843db94535dSChris Mason 
3844dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
3845db94535dSChris Mason 
3846cc4c13d5SDavid Sterba 		ioff = btrfs_token_item_offset(&token, item);
3847cc4c13d5SDavid Sterba 		btrfs_set_token_item_offset(&token, item,
3848cc4c13d5SDavid Sterba 		      ioff - (BTRFS_LEAF_DATA_SIZE(fs_info) - old_left_item_size));
3849be0e5c09SChris Mason 	}
38505f39d397SChris Mason 	btrfs_set_header_nritems(left, old_left_nritems + push_items);
3851be0e5c09SChris Mason 
3852be0e5c09SChris Mason 	/* fixup right node */
385331b1a2bdSJulia Lawall 	if (push_items > right_nritems)
385431b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "push items %d nr %u\n", push_items,
3855d397712bSChris Mason 		       right_nritems);
385634a38218SChris Mason 
385734a38218SChris Mason 	if (push_items < right_nritems) {
38585f39d397SChris Mason 		push_space = btrfs_item_offset_nr(right, push_items - 1) -
38598f881e8cSDavid Sterba 						  leaf_data_end(right);
38603d9ec8c4SNikolay Borisov 		memmove_extent_buffer(right, BTRFS_LEAF_DATA_OFFSET +
38610b246afaSJeff Mahoney 				      BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
38623d9ec8c4SNikolay Borisov 				      BTRFS_LEAF_DATA_OFFSET +
38638f881e8cSDavid Sterba 				      leaf_data_end(right), push_space);
38645f39d397SChris Mason 
38655f39d397SChris Mason 		memmove_extent_buffer(right, btrfs_item_nr_offset(0),
38665f39d397SChris Mason 			      btrfs_item_nr_offset(push_items),
38675f39d397SChris Mason 			     (btrfs_header_nritems(right) - push_items) *
38680783fcfcSChris Mason 			     sizeof(struct btrfs_item));
386934a38218SChris Mason 	}
3870c82f823cSDavid Sterba 
3871c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
3872eef1c494SYan 	right_nritems -= push_items;
3873eef1c494SYan 	btrfs_set_header_nritems(right, right_nritems);
38740b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
38755f39d397SChris Mason 	for (i = 0; i < right_nritems; i++) {
3876dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
3877db94535dSChris Mason 
3878cc4c13d5SDavid Sterba 		push_space = push_space - btrfs_token_item_size(&token, item);
3879cc4c13d5SDavid Sterba 		btrfs_set_token_item_offset(&token, item, push_space);
3880db94535dSChris Mason 	}
3881eb60ceacSChris Mason 
38825f39d397SChris Mason 	btrfs_mark_buffer_dirty(left);
388334a38218SChris Mason 	if (right_nritems)
38845f39d397SChris Mason 		btrfs_mark_buffer_dirty(right);
3885f0486c68SYan, Zheng 	else
38866a884d7dSDavid Sterba 		btrfs_clean_tree_block(right);
3887098f59c2SChris Mason 
38885f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
3889b167fa91SNikolay Borisov 	fixup_low_keys(path, &disk_key, 1);
3890be0e5c09SChris Mason 
3891be0e5c09SChris Mason 	/* then fixup the leaf pointer in the path */
3892be0e5c09SChris Mason 	if (path->slots[0] < push_items) {
3893be0e5c09SChris Mason 		path->slots[0] += old_left_nritems;
3894925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
38955f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
38965f39d397SChris Mason 		path->nodes[0] = left;
3897be0e5c09SChris Mason 		path->slots[1] -= 1;
3898be0e5c09SChris Mason 	} else {
3899925baeddSChris Mason 		btrfs_tree_unlock(left);
39005f39d397SChris Mason 		free_extent_buffer(left);
3901be0e5c09SChris Mason 		path->slots[0] -= push_items;
3902be0e5c09SChris Mason 	}
3903eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
3904aa5d6bedSChris Mason 	return ret;
3905925baeddSChris Mason out:
3906925baeddSChris Mason 	btrfs_tree_unlock(left);
3907925baeddSChris Mason 	free_extent_buffer(left);
3908925baeddSChris Mason 	return ret;
3909be0e5c09SChris Mason }
3910be0e5c09SChris Mason 
391174123bd7SChris Mason /*
391244871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
391344871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
391499d8f83cSChris Mason  *
391599d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
391699d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us push all the
391799d8f83cSChris Mason  * items
391844871b1bSChris Mason  */
391944871b1bSChris Mason static int push_leaf_left(struct btrfs_trans_handle *trans, struct btrfs_root
392099d8f83cSChris Mason 			  *root, struct btrfs_path *path, int min_data_size,
392199d8f83cSChris Mason 			  int data_size, int empty, u32 max_slot)
392244871b1bSChris Mason {
392344871b1bSChris Mason 	struct extent_buffer *right = path->nodes[0];
392444871b1bSChris Mason 	struct extent_buffer *left;
392544871b1bSChris Mason 	int slot;
392644871b1bSChris Mason 	int free_space;
392744871b1bSChris Mason 	u32 right_nritems;
392844871b1bSChris Mason 	int ret = 0;
392944871b1bSChris Mason 
393044871b1bSChris Mason 	slot = path->slots[1];
393144871b1bSChris Mason 	if (slot == 0)
393244871b1bSChris Mason 		return 1;
393344871b1bSChris Mason 	if (!path->nodes[1])
393444871b1bSChris Mason 		return 1;
393544871b1bSChris Mason 
393644871b1bSChris Mason 	right_nritems = btrfs_header_nritems(right);
393744871b1bSChris Mason 	if (right_nritems == 0)
393844871b1bSChris Mason 		return 1;
393944871b1bSChris Mason 
394044871b1bSChris Mason 	btrfs_assert_tree_locked(path->nodes[1]);
394144871b1bSChris Mason 
39424b231ae4SDavid Sterba 	left = btrfs_read_node_slot(path->nodes[1], slot - 1);
3943fb770ae4SLiu Bo 	/*
3944fb770ae4SLiu Bo 	 * slot - 1 is not valid or we fail to read the left node,
3945fb770ae4SLiu Bo 	 * no big deal, just return.
3946fb770ae4SLiu Bo 	 */
3947fb770ae4SLiu Bo 	if (IS_ERR(left))
394891ca338dSTsutomu Itoh 		return 1;
394991ca338dSTsutomu Itoh 
3950bf77467aSJosef Bacik 	__btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
395144871b1bSChris Mason 
3952e902baacSDavid Sterba 	free_space = btrfs_leaf_free_space(left);
395344871b1bSChris Mason 	if (free_space < data_size) {
395444871b1bSChris Mason 		ret = 1;
395544871b1bSChris Mason 		goto out;
395644871b1bSChris Mason 	}
395744871b1bSChris Mason 
395844871b1bSChris Mason 	/* cow and double check */
395944871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, left,
39609631e4ccSJosef Bacik 			      path->nodes[1], slot - 1, &left,
3961bf59a5a2SJosef Bacik 			      BTRFS_NESTING_LEFT_COW);
396244871b1bSChris Mason 	if (ret) {
396344871b1bSChris Mason 		/* we hit -ENOSPC, but it isn't fatal here */
396479787eaaSJeff Mahoney 		if (ret == -ENOSPC)
396544871b1bSChris Mason 			ret = 1;
396644871b1bSChris Mason 		goto out;
396744871b1bSChris Mason 	}
396844871b1bSChris Mason 
3969e902baacSDavid Sterba 	free_space = btrfs_leaf_free_space(left);
397044871b1bSChris Mason 	if (free_space < data_size) {
397144871b1bSChris Mason 		ret = 1;
397244871b1bSChris Mason 		goto out;
397344871b1bSChris Mason 	}
397444871b1bSChris Mason 
3975d16c702fSQu Wenruo 	if (check_sibling_keys(left, right)) {
3976d16c702fSQu Wenruo 		ret = -EUCLEAN;
3977d16c702fSQu Wenruo 		goto out;
3978d16c702fSQu Wenruo 	}
39798087c193SDavid Sterba 	return __push_leaf_left(path, min_data_size,
398099d8f83cSChris Mason 			       empty, left, free_space, right_nritems,
398199d8f83cSChris Mason 			       max_slot);
398244871b1bSChris Mason out:
398344871b1bSChris Mason 	btrfs_tree_unlock(left);
398444871b1bSChris Mason 	free_extent_buffer(left);
398544871b1bSChris Mason 	return ret;
398644871b1bSChris Mason }
398744871b1bSChris Mason 
398844871b1bSChris Mason /*
398974123bd7SChris Mason  * split the path's leaf in two, making sure there is at least data_size
399074123bd7SChris Mason  * available for the resulting leaf level of the path.
399174123bd7SChris Mason  */
3992143bede5SJeff Mahoney static noinline void copy_for_split(struct btrfs_trans_handle *trans,
399344871b1bSChris Mason 				    struct btrfs_path *path,
399444871b1bSChris Mason 				    struct extent_buffer *l,
399544871b1bSChris Mason 				    struct extent_buffer *right,
399644871b1bSChris Mason 				    int slot, int mid, int nritems)
3997be0e5c09SChris Mason {
399894f94ad9SDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
3999be0e5c09SChris Mason 	int data_copy_size;
4000be0e5c09SChris Mason 	int rt_data_off;
4001be0e5c09SChris Mason 	int i;
4002d4dbff95SChris Mason 	struct btrfs_disk_key disk_key;
4003cfed81a0SChris Mason 	struct btrfs_map_token token;
4004cfed81a0SChris Mason 
40055f39d397SChris Mason 	nritems = nritems - mid;
40065f39d397SChris Mason 	btrfs_set_header_nritems(right, nritems);
40078f881e8cSDavid Sterba 	data_copy_size = btrfs_item_end_nr(l, mid) - leaf_data_end(l);
40085f39d397SChris Mason 
40095f39d397SChris Mason 	copy_extent_buffer(right, l, btrfs_item_nr_offset(0),
40105f39d397SChris Mason 			   btrfs_item_nr_offset(mid),
40115f39d397SChris Mason 			   nritems * sizeof(struct btrfs_item));
40125f39d397SChris Mason 
40135f39d397SChris Mason 	copy_extent_buffer(right, l,
40143d9ec8c4SNikolay Borisov 		     BTRFS_LEAF_DATA_OFFSET + BTRFS_LEAF_DATA_SIZE(fs_info) -
40153d9ec8c4SNikolay Borisov 		     data_copy_size, BTRFS_LEAF_DATA_OFFSET +
40168f881e8cSDavid Sterba 		     leaf_data_end(l), data_copy_size);
401774123bd7SChris Mason 
40180b246afaSJeff Mahoney 	rt_data_off = BTRFS_LEAF_DATA_SIZE(fs_info) - btrfs_item_end_nr(l, mid);
40195f39d397SChris Mason 
4020c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
40215f39d397SChris Mason 	for (i = 0; i < nritems; i++) {
4022dd3cc16bSRoss Kirk 		struct btrfs_item *item = btrfs_item_nr(i);
4023db94535dSChris Mason 		u32 ioff;
4024db94535dSChris Mason 
4025cc4c13d5SDavid Sterba 		ioff = btrfs_token_item_offset(&token, item);
4026cc4c13d5SDavid Sterba 		btrfs_set_token_item_offset(&token, item, ioff + rt_data_off);
40270783fcfcSChris Mason 	}
402874123bd7SChris Mason 
40295f39d397SChris Mason 	btrfs_set_header_nritems(l, mid);
40305f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
40316ad3cf6dSDavid Sterba 	insert_ptr(trans, path, &disk_key, right->start, path->slots[1] + 1, 1);
40325f39d397SChris Mason 
40335f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
40345f39d397SChris Mason 	btrfs_mark_buffer_dirty(l);
4035eb60ceacSChris Mason 	BUG_ON(path->slots[0] != slot);
40365f39d397SChris Mason 
4037be0e5c09SChris Mason 	if (mid <= slot) {
4038925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
40395f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
40405f39d397SChris Mason 		path->nodes[0] = right;
4041be0e5c09SChris Mason 		path->slots[0] -= mid;
4042be0e5c09SChris Mason 		path->slots[1] += 1;
4043925baeddSChris Mason 	} else {
4044925baeddSChris Mason 		btrfs_tree_unlock(right);
40455f39d397SChris Mason 		free_extent_buffer(right);
4046925baeddSChris Mason 	}
40475f39d397SChris Mason 
4048eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
404944871b1bSChris Mason }
405044871b1bSChris Mason 
405144871b1bSChris Mason /*
405299d8f83cSChris Mason  * double splits happen when we need to insert a big item in the middle
405399d8f83cSChris Mason  * of a leaf.  A double split can leave us with 3 mostly empty leaves:
405499d8f83cSChris Mason  * leaf: [ slots 0 - N] [ our target ] [ N + 1 - total in leaf ]
405599d8f83cSChris Mason  *          A                 B                 C
405699d8f83cSChris Mason  *
405799d8f83cSChris Mason  * We avoid this by trying to push the items on either side of our target
405899d8f83cSChris Mason  * into the adjacent leaves.  If all goes well we can avoid the double split
405999d8f83cSChris Mason  * completely.
406099d8f83cSChris Mason  */
406199d8f83cSChris Mason static noinline int push_for_double_split(struct btrfs_trans_handle *trans,
406299d8f83cSChris Mason 					  struct btrfs_root *root,
406399d8f83cSChris Mason 					  struct btrfs_path *path,
406499d8f83cSChris Mason 					  int data_size)
406599d8f83cSChris Mason {
406699d8f83cSChris Mason 	int ret;
406799d8f83cSChris Mason 	int progress = 0;
406899d8f83cSChris Mason 	int slot;
406999d8f83cSChris Mason 	u32 nritems;
40705a4267caSFilipe David Borba Manana 	int space_needed = data_size;
407199d8f83cSChris Mason 
407299d8f83cSChris Mason 	slot = path->slots[0];
40735a4267caSFilipe David Borba Manana 	if (slot < btrfs_header_nritems(path->nodes[0]))
4074e902baacSDavid Sterba 		space_needed -= btrfs_leaf_free_space(path->nodes[0]);
407599d8f83cSChris Mason 
407699d8f83cSChris Mason 	/*
407799d8f83cSChris Mason 	 * try to push all the items after our slot into the
407899d8f83cSChris Mason 	 * right leaf
407999d8f83cSChris Mason 	 */
40805a4267caSFilipe David Borba Manana 	ret = push_leaf_right(trans, root, path, 1, space_needed, 0, slot);
408199d8f83cSChris Mason 	if (ret < 0)
408299d8f83cSChris Mason 		return ret;
408399d8f83cSChris Mason 
408499d8f83cSChris Mason 	if (ret == 0)
408599d8f83cSChris Mason 		progress++;
408699d8f83cSChris Mason 
408799d8f83cSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
408899d8f83cSChris Mason 	/*
408999d8f83cSChris Mason 	 * our goal is to get our slot at the start or end of a leaf.  If
409099d8f83cSChris Mason 	 * we've done so we're done
409199d8f83cSChris Mason 	 */
409299d8f83cSChris Mason 	if (path->slots[0] == 0 || path->slots[0] == nritems)
409399d8f83cSChris Mason 		return 0;
409499d8f83cSChris Mason 
4095e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
409699d8f83cSChris Mason 		return 0;
409799d8f83cSChris Mason 
409899d8f83cSChris Mason 	/* try to push all the items before our slot into the next leaf */
409999d8f83cSChris Mason 	slot = path->slots[0];
4100263d3995SFilipe Manana 	space_needed = data_size;
4101263d3995SFilipe Manana 	if (slot > 0)
4102e902baacSDavid Sterba 		space_needed -= btrfs_leaf_free_space(path->nodes[0]);
41035a4267caSFilipe David Borba Manana 	ret = push_leaf_left(trans, root, path, 1, space_needed, 0, slot);
410499d8f83cSChris Mason 	if (ret < 0)
410599d8f83cSChris Mason 		return ret;
410699d8f83cSChris Mason 
410799d8f83cSChris Mason 	if (ret == 0)
410899d8f83cSChris Mason 		progress++;
410999d8f83cSChris Mason 
411099d8f83cSChris Mason 	if (progress)
411199d8f83cSChris Mason 		return 0;
411299d8f83cSChris Mason 	return 1;
411399d8f83cSChris Mason }
411499d8f83cSChris Mason 
411599d8f83cSChris Mason /*
411644871b1bSChris Mason  * split the path's leaf in two, making sure there is at least data_size
411744871b1bSChris Mason  * available for the resulting leaf level of the path.
411844871b1bSChris Mason  *
411944871b1bSChris Mason  * returns 0 if all went well and < 0 on failure.
412044871b1bSChris Mason  */
412144871b1bSChris Mason static noinline int split_leaf(struct btrfs_trans_handle *trans,
412244871b1bSChris Mason 			       struct btrfs_root *root,
4123310712b2SOmar Sandoval 			       const struct btrfs_key *ins_key,
412444871b1bSChris Mason 			       struct btrfs_path *path, int data_size,
412544871b1bSChris Mason 			       int extend)
412644871b1bSChris Mason {
41275d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
412844871b1bSChris Mason 	struct extent_buffer *l;
412944871b1bSChris Mason 	u32 nritems;
413044871b1bSChris Mason 	int mid;
413144871b1bSChris Mason 	int slot;
413244871b1bSChris Mason 	struct extent_buffer *right;
4133b7a0365eSDaniel Dressler 	struct btrfs_fs_info *fs_info = root->fs_info;
413444871b1bSChris Mason 	int ret = 0;
413544871b1bSChris Mason 	int wret;
41365d4f98a2SYan Zheng 	int split;
413744871b1bSChris Mason 	int num_doubles = 0;
413899d8f83cSChris Mason 	int tried_avoid_double = 0;
413944871b1bSChris Mason 
4140a5719521SYan, Zheng 	l = path->nodes[0];
4141a5719521SYan, Zheng 	slot = path->slots[0];
4142a5719521SYan, Zheng 	if (extend && data_size + btrfs_item_size_nr(l, slot) +
41430b246afaSJeff Mahoney 	    sizeof(struct btrfs_item) > BTRFS_LEAF_DATA_SIZE(fs_info))
4144a5719521SYan, Zheng 		return -EOVERFLOW;
4145a5719521SYan, Zheng 
414644871b1bSChris Mason 	/* first try to make some room by pushing left and right */
414733157e05SLiu Bo 	if (data_size && path->nodes[1]) {
41485a4267caSFilipe David Borba Manana 		int space_needed = data_size;
41495a4267caSFilipe David Borba Manana 
41505a4267caSFilipe David Borba Manana 		if (slot < btrfs_header_nritems(l))
4151e902baacSDavid Sterba 			space_needed -= btrfs_leaf_free_space(l);
41525a4267caSFilipe David Borba Manana 
41535a4267caSFilipe David Borba Manana 		wret = push_leaf_right(trans, root, path, space_needed,
41545a4267caSFilipe David Borba Manana 				       space_needed, 0, 0);
415544871b1bSChris Mason 		if (wret < 0)
415644871b1bSChris Mason 			return wret;
415744871b1bSChris Mason 		if (wret) {
4158263d3995SFilipe Manana 			space_needed = data_size;
4159263d3995SFilipe Manana 			if (slot > 0)
4160e902baacSDavid Sterba 				space_needed -= btrfs_leaf_free_space(l);
41615a4267caSFilipe David Borba Manana 			wret = push_leaf_left(trans, root, path, space_needed,
41625a4267caSFilipe David Borba Manana 					      space_needed, 0, (u32)-1);
416344871b1bSChris Mason 			if (wret < 0)
416444871b1bSChris Mason 				return wret;
416544871b1bSChris Mason 		}
416644871b1bSChris Mason 		l = path->nodes[0];
416744871b1bSChris Mason 
416844871b1bSChris Mason 		/* did the pushes work? */
4169e902baacSDavid Sterba 		if (btrfs_leaf_free_space(l) >= data_size)
417044871b1bSChris Mason 			return 0;
417144871b1bSChris Mason 	}
417244871b1bSChris Mason 
417344871b1bSChris Mason 	if (!path->nodes[1]) {
4174fdd99c72SLiu Bo 		ret = insert_new_root(trans, root, path, 1);
417544871b1bSChris Mason 		if (ret)
417644871b1bSChris Mason 			return ret;
417744871b1bSChris Mason 	}
417844871b1bSChris Mason again:
41795d4f98a2SYan Zheng 	split = 1;
418044871b1bSChris Mason 	l = path->nodes[0];
418144871b1bSChris Mason 	slot = path->slots[0];
418244871b1bSChris Mason 	nritems = btrfs_header_nritems(l);
418344871b1bSChris Mason 	mid = (nritems + 1) / 2;
418444871b1bSChris Mason 
41855d4f98a2SYan Zheng 	if (mid <= slot) {
41865d4f98a2SYan Zheng 		if (nritems == 1 ||
41875d4f98a2SYan Zheng 		    leaf_space_used(l, mid, nritems - mid) + data_size >
41880b246afaSJeff Mahoney 			BTRFS_LEAF_DATA_SIZE(fs_info)) {
41895d4f98a2SYan Zheng 			if (slot >= nritems) {
41905d4f98a2SYan Zheng 				split = 0;
41915d4f98a2SYan Zheng 			} else {
41925d4f98a2SYan Zheng 				mid = slot;
41935d4f98a2SYan Zheng 				if (mid != nritems &&
41945d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
41950b246afaSJeff Mahoney 				    data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
419699d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
419799d8f83cSChris Mason 						goto push_for_double;
41985d4f98a2SYan Zheng 					split = 2;
41995d4f98a2SYan Zheng 				}
42005d4f98a2SYan Zheng 			}
42015d4f98a2SYan Zheng 		}
42025d4f98a2SYan Zheng 	} else {
42035d4f98a2SYan Zheng 		if (leaf_space_used(l, 0, mid) + data_size >
42040b246afaSJeff Mahoney 			BTRFS_LEAF_DATA_SIZE(fs_info)) {
42055d4f98a2SYan Zheng 			if (!extend && data_size && slot == 0) {
42065d4f98a2SYan Zheng 				split = 0;
42075d4f98a2SYan Zheng 			} else if ((extend || !data_size) && slot == 0) {
42085d4f98a2SYan Zheng 				mid = 1;
42095d4f98a2SYan Zheng 			} else {
42105d4f98a2SYan Zheng 				mid = slot;
42115d4f98a2SYan Zheng 				if (mid != nritems &&
42125d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
42130b246afaSJeff Mahoney 				    data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
421499d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
421599d8f83cSChris Mason 						goto push_for_double;
42165d4f98a2SYan Zheng 					split = 2;
42175d4f98a2SYan Zheng 				}
42185d4f98a2SYan Zheng 			}
42195d4f98a2SYan Zheng 		}
42205d4f98a2SYan Zheng 	}
42215d4f98a2SYan Zheng 
42225d4f98a2SYan Zheng 	if (split == 0)
42235d4f98a2SYan Zheng 		btrfs_cpu_key_to_disk(&disk_key, ins_key);
42245d4f98a2SYan Zheng 	else
42255d4f98a2SYan Zheng 		btrfs_item_key(l, &disk_key, mid);
42265d4f98a2SYan Zheng 
4227ca9d473aSJosef Bacik 	/*
4228ca9d473aSJosef Bacik 	 * We have to about BTRFS_NESTING_NEW_ROOT here if we've done a double
4229ca9d473aSJosef Bacik 	 * split, because we're only allowed to have MAX_LOCKDEP_SUBCLASSES
4230ca9d473aSJosef Bacik 	 * subclasses, which is 8 at the time of this patch, and we've maxed it
4231ca9d473aSJosef Bacik 	 * out.  In the future we could add a
4232ca9d473aSJosef Bacik 	 * BTRFS_NESTING_SPLIT_THE_SPLITTENING if we need to, but for now just
4233ca9d473aSJosef Bacik 	 * use BTRFS_NESTING_NEW_ROOT.
4234ca9d473aSJosef Bacik 	 */
4235a6279470SFilipe Manana 	right = alloc_tree_block_no_bg_flush(trans, root, 0, &disk_key, 0,
4236ca9d473aSJosef Bacik 					     l->start, 0, num_doubles ?
4237ca9d473aSJosef Bacik 					     BTRFS_NESTING_NEW_ROOT :
4238ca9d473aSJosef Bacik 					     BTRFS_NESTING_SPLIT);
4239f0486c68SYan, Zheng 	if (IS_ERR(right))
424044871b1bSChris Mason 		return PTR_ERR(right);
4241f0486c68SYan, Zheng 
42420b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
424344871b1bSChris Mason 
42445d4f98a2SYan Zheng 	if (split == 0) {
424544871b1bSChris Mason 		if (mid <= slot) {
424644871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
42476ad3cf6dSDavid Sterba 			insert_ptr(trans, path, &disk_key,
42482ff7e61eSJeff Mahoney 				   right->start, path->slots[1] + 1, 1);
424944871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
425044871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
425144871b1bSChris Mason 			path->nodes[0] = right;
425244871b1bSChris Mason 			path->slots[0] = 0;
425344871b1bSChris Mason 			path->slots[1] += 1;
425444871b1bSChris Mason 		} else {
425544871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
42566ad3cf6dSDavid Sterba 			insert_ptr(trans, path, &disk_key,
42572ff7e61eSJeff Mahoney 				   right->start, path->slots[1], 1);
425844871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
425944871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
426044871b1bSChris Mason 			path->nodes[0] = right;
426144871b1bSChris Mason 			path->slots[0] = 0;
4262143bede5SJeff Mahoney 			if (path->slots[1] == 0)
4263b167fa91SNikolay Borisov 				fixup_low_keys(path, &disk_key, 1);
42645d4f98a2SYan Zheng 		}
4265196e0249SLiu Bo 		/*
4266196e0249SLiu Bo 		 * We create a new leaf 'right' for the required ins_len and
4267196e0249SLiu Bo 		 * we'll do btrfs_mark_buffer_dirty() on this leaf after copying
4268196e0249SLiu Bo 		 * the content of ins_len to 'right'.
4269196e0249SLiu Bo 		 */
427044871b1bSChris Mason 		return ret;
427144871b1bSChris Mason 	}
427244871b1bSChris Mason 
427394f94ad9SDavid Sterba 	copy_for_split(trans, path, l, right, slot, mid, nritems);
427444871b1bSChris Mason 
42755d4f98a2SYan Zheng 	if (split == 2) {
4276cc0c5538SChris Mason 		BUG_ON(num_doubles != 0);
4277cc0c5538SChris Mason 		num_doubles++;
4278cc0c5538SChris Mason 		goto again;
42793326d1b0SChris Mason 	}
428044871b1bSChris Mason 
4281143bede5SJeff Mahoney 	return 0;
428299d8f83cSChris Mason 
428399d8f83cSChris Mason push_for_double:
428499d8f83cSChris Mason 	push_for_double_split(trans, root, path, data_size);
428599d8f83cSChris Mason 	tried_avoid_double = 1;
4286e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
428799d8f83cSChris Mason 		return 0;
428899d8f83cSChris Mason 	goto again;
4289be0e5c09SChris Mason }
4290be0e5c09SChris Mason 
4291ad48fd75SYan, Zheng static noinline int setup_leaf_for_split(struct btrfs_trans_handle *trans,
4292ad48fd75SYan, Zheng 					 struct btrfs_root *root,
4293ad48fd75SYan, Zheng 					 struct btrfs_path *path, int ins_len)
4294ad48fd75SYan, Zheng {
4295ad48fd75SYan, Zheng 	struct btrfs_key key;
4296ad48fd75SYan, Zheng 	struct extent_buffer *leaf;
4297ad48fd75SYan, Zheng 	struct btrfs_file_extent_item *fi;
4298ad48fd75SYan, Zheng 	u64 extent_len = 0;
4299ad48fd75SYan, Zheng 	u32 item_size;
4300ad48fd75SYan, Zheng 	int ret;
4301ad48fd75SYan, Zheng 
4302ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4303ad48fd75SYan, Zheng 	btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4304ad48fd75SYan, Zheng 
4305ad48fd75SYan, Zheng 	BUG_ON(key.type != BTRFS_EXTENT_DATA_KEY &&
4306ad48fd75SYan, Zheng 	       key.type != BTRFS_EXTENT_CSUM_KEY);
4307ad48fd75SYan, Zheng 
4308e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) >= ins_len)
4309ad48fd75SYan, Zheng 		return 0;
4310ad48fd75SYan, Zheng 
4311ad48fd75SYan, Zheng 	item_size = btrfs_item_size_nr(leaf, path->slots[0]);
4312ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
4313ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
4314ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
4315ad48fd75SYan, Zheng 		extent_len = btrfs_file_extent_num_bytes(leaf, fi);
4316ad48fd75SYan, Zheng 	}
4317b3b4aa74SDavid Sterba 	btrfs_release_path(path);
4318ad48fd75SYan, Zheng 
4319ad48fd75SYan, Zheng 	path->keep_locks = 1;
4320ad48fd75SYan, Zheng 	path->search_for_split = 1;
4321ad48fd75SYan, Zheng 	ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
4322ad48fd75SYan, Zheng 	path->search_for_split = 0;
4323a8df6fe6SFilipe Manana 	if (ret > 0)
4324a8df6fe6SFilipe Manana 		ret = -EAGAIN;
4325ad48fd75SYan, Zheng 	if (ret < 0)
4326ad48fd75SYan, Zheng 		goto err;
4327ad48fd75SYan, Zheng 
4328ad48fd75SYan, Zheng 	ret = -EAGAIN;
4329ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4330a8df6fe6SFilipe Manana 	/* if our item isn't there, return now */
4331a8df6fe6SFilipe Manana 	if (item_size != btrfs_item_size_nr(leaf, path->slots[0]))
4332ad48fd75SYan, Zheng 		goto err;
4333ad48fd75SYan, Zheng 
4334109f6aefSChris Mason 	/* the leaf has  changed, it now has room.  return now */
4335e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= ins_len)
4336109f6aefSChris Mason 		goto err;
4337109f6aefSChris Mason 
4338ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
4339ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
4340ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
4341ad48fd75SYan, Zheng 		if (extent_len != btrfs_file_extent_num_bytes(leaf, fi))
4342ad48fd75SYan, Zheng 			goto err;
4343ad48fd75SYan, Zheng 	}
4344ad48fd75SYan, Zheng 
4345ad48fd75SYan, Zheng 	ret = split_leaf(trans, root, &key, path, ins_len, 1);
4346f0486c68SYan, Zheng 	if (ret)
4347f0486c68SYan, Zheng 		goto err;
4348ad48fd75SYan, Zheng 
4349ad48fd75SYan, Zheng 	path->keep_locks = 0;
4350ad48fd75SYan, Zheng 	btrfs_unlock_up_safe(path, 1);
4351ad48fd75SYan, Zheng 	return 0;
4352ad48fd75SYan, Zheng err:
4353ad48fd75SYan, Zheng 	path->keep_locks = 0;
4354ad48fd75SYan, Zheng 	return ret;
4355ad48fd75SYan, Zheng }
4356ad48fd75SYan, Zheng 
435725263cd7SDavid Sterba static noinline int split_item(struct btrfs_path *path,
4358310712b2SOmar Sandoval 			       const struct btrfs_key *new_key,
4359459931ecSChris Mason 			       unsigned long split_offset)
4360459931ecSChris Mason {
4361459931ecSChris Mason 	struct extent_buffer *leaf;
4362459931ecSChris Mason 	struct btrfs_item *item;
4363459931ecSChris Mason 	struct btrfs_item *new_item;
4364459931ecSChris Mason 	int slot;
4365ad48fd75SYan, Zheng 	char *buf;
4366459931ecSChris Mason 	u32 nritems;
4367ad48fd75SYan, Zheng 	u32 item_size;
4368459931ecSChris Mason 	u32 orig_offset;
4369459931ecSChris Mason 	struct btrfs_disk_key disk_key;
4370459931ecSChris Mason 
4371459931ecSChris Mason 	leaf = path->nodes[0];
4372e902baacSDavid Sterba 	BUG_ON(btrfs_leaf_free_space(leaf) < sizeof(struct btrfs_item));
4373b9473439SChris Mason 
4374dd3cc16bSRoss Kirk 	item = btrfs_item_nr(path->slots[0]);
4375459931ecSChris Mason 	orig_offset = btrfs_item_offset(leaf, item);
4376459931ecSChris Mason 	item_size = btrfs_item_size(leaf, item);
4377459931ecSChris Mason 
4378459931ecSChris Mason 	buf = kmalloc(item_size, GFP_NOFS);
4379ad48fd75SYan, Zheng 	if (!buf)
4380ad48fd75SYan, Zheng 		return -ENOMEM;
4381ad48fd75SYan, Zheng 
4382459931ecSChris Mason 	read_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf,
4383459931ecSChris Mason 			    path->slots[0]), item_size);
4384ad48fd75SYan, Zheng 
4385459931ecSChris Mason 	slot = path->slots[0] + 1;
4386459931ecSChris Mason 	nritems = btrfs_header_nritems(leaf);
4387459931ecSChris Mason 	if (slot != nritems) {
4388459931ecSChris Mason 		/* shift the items */
4389459931ecSChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + 1),
4390459931ecSChris Mason 				btrfs_item_nr_offset(slot),
4391459931ecSChris Mason 				(nritems - slot) * sizeof(struct btrfs_item));
4392459931ecSChris Mason 	}
4393459931ecSChris Mason 
4394459931ecSChris Mason 	btrfs_cpu_key_to_disk(&disk_key, new_key);
4395459931ecSChris Mason 	btrfs_set_item_key(leaf, &disk_key, slot);
4396459931ecSChris Mason 
4397dd3cc16bSRoss Kirk 	new_item = btrfs_item_nr(slot);
4398459931ecSChris Mason 
4399459931ecSChris Mason 	btrfs_set_item_offset(leaf, new_item, orig_offset);
4400459931ecSChris Mason 	btrfs_set_item_size(leaf, new_item, item_size - split_offset);
4401459931ecSChris Mason 
4402459931ecSChris Mason 	btrfs_set_item_offset(leaf, item,
4403459931ecSChris Mason 			      orig_offset + item_size - split_offset);
4404459931ecSChris Mason 	btrfs_set_item_size(leaf, item, split_offset);
4405459931ecSChris Mason 
4406459931ecSChris Mason 	btrfs_set_header_nritems(leaf, nritems + 1);
4407459931ecSChris Mason 
4408459931ecSChris Mason 	/* write the data for the start of the original item */
4409459931ecSChris Mason 	write_extent_buffer(leaf, buf,
4410459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, path->slots[0]),
4411459931ecSChris Mason 			    split_offset);
4412459931ecSChris Mason 
4413459931ecSChris Mason 	/* write the data for the new item */
4414459931ecSChris Mason 	write_extent_buffer(leaf, buf + split_offset,
4415459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, slot),
4416459931ecSChris Mason 			    item_size - split_offset);
4417459931ecSChris Mason 	btrfs_mark_buffer_dirty(leaf);
4418459931ecSChris Mason 
4419e902baacSDavid Sterba 	BUG_ON(btrfs_leaf_free_space(leaf) < 0);
4420459931ecSChris Mason 	kfree(buf);
4421ad48fd75SYan, Zheng 	return 0;
4422ad48fd75SYan, Zheng }
4423ad48fd75SYan, Zheng 
4424ad48fd75SYan, Zheng /*
4425ad48fd75SYan, Zheng  * This function splits a single item into two items,
4426ad48fd75SYan, Zheng  * giving 'new_key' to the new item and splitting the
4427ad48fd75SYan, Zheng  * old one at split_offset (from the start of the item).
4428ad48fd75SYan, Zheng  *
4429ad48fd75SYan, Zheng  * The path may be released by this operation.  After
4430ad48fd75SYan, Zheng  * the split, the path is pointing to the old item.  The
4431ad48fd75SYan, Zheng  * new item is going to be in the same node as the old one.
4432ad48fd75SYan, Zheng  *
4433ad48fd75SYan, Zheng  * Note, the item being split must be smaller enough to live alone on
4434ad48fd75SYan, Zheng  * a tree block with room for one extra struct btrfs_item
4435ad48fd75SYan, Zheng  *
4436ad48fd75SYan, Zheng  * This allows us to split the item in place, keeping a lock on the
4437ad48fd75SYan, Zheng  * leaf the entire time.
4438ad48fd75SYan, Zheng  */
4439ad48fd75SYan, Zheng int btrfs_split_item(struct btrfs_trans_handle *trans,
4440ad48fd75SYan, Zheng 		     struct btrfs_root *root,
4441ad48fd75SYan, Zheng 		     struct btrfs_path *path,
4442310712b2SOmar Sandoval 		     const struct btrfs_key *new_key,
4443ad48fd75SYan, Zheng 		     unsigned long split_offset)
4444ad48fd75SYan, Zheng {
4445ad48fd75SYan, Zheng 	int ret;
4446ad48fd75SYan, Zheng 	ret = setup_leaf_for_split(trans, root, path,
4447ad48fd75SYan, Zheng 				   sizeof(struct btrfs_item));
4448ad48fd75SYan, Zheng 	if (ret)
4449459931ecSChris Mason 		return ret;
4450ad48fd75SYan, Zheng 
445125263cd7SDavid Sterba 	ret = split_item(path, new_key, split_offset);
4452ad48fd75SYan, Zheng 	return ret;
4453ad48fd75SYan, Zheng }
4454ad48fd75SYan, Zheng 
4455ad48fd75SYan, Zheng /*
4456ad48fd75SYan, Zheng  * This function duplicate a item, giving 'new_key' to the new item.
4457ad48fd75SYan, Zheng  * It guarantees both items live in the same tree leaf and the new item
4458ad48fd75SYan, Zheng  * is contiguous with the original item.
4459ad48fd75SYan, Zheng  *
4460ad48fd75SYan, Zheng  * This allows us to split file extent in place, keeping a lock on the
4461ad48fd75SYan, Zheng  * leaf the entire time.
4462ad48fd75SYan, Zheng  */
4463ad48fd75SYan, Zheng int btrfs_duplicate_item(struct btrfs_trans_handle *trans,
4464ad48fd75SYan, Zheng 			 struct btrfs_root *root,
4465ad48fd75SYan, Zheng 			 struct btrfs_path *path,
4466310712b2SOmar Sandoval 			 const struct btrfs_key *new_key)
4467ad48fd75SYan, Zheng {
4468ad48fd75SYan, Zheng 	struct extent_buffer *leaf;
4469ad48fd75SYan, Zheng 	int ret;
4470ad48fd75SYan, Zheng 	u32 item_size;
4471ad48fd75SYan, Zheng 
4472ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4473ad48fd75SYan, Zheng 	item_size = btrfs_item_size_nr(leaf, path->slots[0]);
4474ad48fd75SYan, Zheng 	ret = setup_leaf_for_split(trans, root, path,
4475ad48fd75SYan, Zheng 				   item_size + sizeof(struct btrfs_item));
4476ad48fd75SYan, Zheng 	if (ret)
4477ad48fd75SYan, Zheng 		return ret;
4478ad48fd75SYan, Zheng 
4479ad48fd75SYan, Zheng 	path->slots[0]++;
4480fc0d82e1SNikolay Borisov 	setup_items_for_insert(root, path, new_key, &item_size, 1);
4481ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4482ad48fd75SYan, Zheng 	memcpy_extent_buffer(leaf,
4483ad48fd75SYan, Zheng 			     btrfs_item_ptr_offset(leaf, path->slots[0]),
4484ad48fd75SYan, Zheng 			     btrfs_item_ptr_offset(leaf, path->slots[0] - 1),
4485ad48fd75SYan, Zheng 			     item_size);
4486ad48fd75SYan, Zheng 	return 0;
4487459931ecSChris Mason }
4488459931ecSChris Mason 
4489459931ecSChris Mason /*
4490d352ac68SChris Mason  * make the item pointed to by the path smaller.  new_size indicates
4491d352ac68SChris Mason  * how small to make it, and from_end tells us if we just chop bytes
4492d352ac68SChris Mason  * off the end of the item or if we shift the item to chop bytes off
4493d352ac68SChris Mason  * the front.
4494d352ac68SChris Mason  */
449578ac4f9eSDavid Sterba void btrfs_truncate_item(struct btrfs_path *path, u32 new_size, int from_end)
4496b18c6685SChris Mason {
4497b18c6685SChris Mason 	int slot;
44985f39d397SChris Mason 	struct extent_buffer *leaf;
44995f39d397SChris Mason 	struct btrfs_item *item;
4500b18c6685SChris Mason 	u32 nritems;
4501b18c6685SChris Mason 	unsigned int data_end;
4502b18c6685SChris Mason 	unsigned int old_data_start;
4503b18c6685SChris Mason 	unsigned int old_size;
4504b18c6685SChris Mason 	unsigned int size_diff;
4505b18c6685SChris Mason 	int i;
4506cfed81a0SChris Mason 	struct btrfs_map_token token;
4507cfed81a0SChris Mason 
45085f39d397SChris Mason 	leaf = path->nodes[0];
4509179e29e4SChris Mason 	slot = path->slots[0];
4510179e29e4SChris Mason 
4511179e29e4SChris Mason 	old_size = btrfs_item_size_nr(leaf, slot);
4512179e29e4SChris Mason 	if (old_size == new_size)
4513143bede5SJeff Mahoney 		return;
4514b18c6685SChris Mason 
45155f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
45168f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
4517b18c6685SChris Mason 
45185f39d397SChris Mason 	old_data_start = btrfs_item_offset_nr(leaf, slot);
4519179e29e4SChris Mason 
4520b18c6685SChris Mason 	size_diff = old_size - new_size;
4521b18c6685SChris Mason 
4522b18c6685SChris Mason 	BUG_ON(slot < 0);
4523b18c6685SChris Mason 	BUG_ON(slot >= nritems);
4524b18c6685SChris Mason 
4525b18c6685SChris Mason 	/*
4526b18c6685SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4527b18c6685SChris Mason 	 */
4528b18c6685SChris Mason 	/* first correct the data pointers */
4529c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
4530b18c6685SChris Mason 	for (i = slot; i < nritems; i++) {
45315f39d397SChris Mason 		u32 ioff;
4532dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
4533db94535dSChris Mason 
4534cc4c13d5SDavid Sterba 		ioff = btrfs_token_item_offset(&token, item);
4535cc4c13d5SDavid Sterba 		btrfs_set_token_item_offset(&token, item, ioff + size_diff);
4536b18c6685SChris Mason 	}
4537db94535dSChris Mason 
4538b18c6685SChris Mason 	/* shift the data */
4539179e29e4SChris Mason 	if (from_end) {
45403d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
45413d9ec8c4SNikolay Borisov 			      data_end + size_diff, BTRFS_LEAF_DATA_OFFSET +
4542b18c6685SChris Mason 			      data_end, old_data_start + new_size - data_end);
4543179e29e4SChris Mason 	} else {
4544179e29e4SChris Mason 		struct btrfs_disk_key disk_key;
4545179e29e4SChris Mason 		u64 offset;
4546179e29e4SChris Mason 
4547179e29e4SChris Mason 		btrfs_item_key(leaf, &disk_key, slot);
4548179e29e4SChris Mason 
4549179e29e4SChris Mason 		if (btrfs_disk_key_type(&disk_key) == BTRFS_EXTENT_DATA_KEY) {
4550179e29e4SChris Mason 			unsigned long ptr;
4551179e29e4SChris Mason 			struct btrfs_file_extent_item *fi;
4552179e29e4SChris Mason 
4553179e29e4SChris Mason 			fi = btrfs_item_ptr(leaf, slot,
4554179e29e4SChris Mason 					    struct btrfs_file_extent_item);
4555179e29e4SChris Mason 			fi = (struct btrfs_file_extent_item *)(
4556179e29e4SChris Mason 			     (unsigned long)fi - size_diff);
4557179e29e4SChris Mason 
4558179e29e4SChris Mason 			if (btrfs_file_extent_type(leaf, fi) ==
4559179e29e4SChris Mason 			    BTRFS_FILE_EXTENT_INLINE) {
4560179e29e4SChris Mason 				ptr = btrfs_item_ptr_offset(leaf, slot);
4561179e29e4SChris Mason 				memmove_extent_buffer(leaf, ptr,
4562179e29e4SChris Mason 				      (unsigned long)fi,
45637ec20afbSDavid Sterba 				      BTRFS_FILE_EXTENT_INLINE_DATA_START);
4564179e29e4SChris Mason 			}
4565179e29e4SChris Mason 		}
4566179e29e4SChris Mason 
45673d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
45683d9ec8c4SNikolay Borisov 			      data_end + size_diff, BTRFS_LEAF_DATA_OFFSET +
4569179e29e4SChris Mason 			      data_end, old_data_start - data_end);
4570179e29e4SChris Mason 
4571179e29e4SChris Mason 		offset = btrfs_disk_key_offset(&disk_key);
4572179e29e4SChris Mason 		btrfs_set_disk_key_offset(&disk_key, offset + size_diff);
4573179e29e4SChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot);
4574179e29e4SChris Mason 		if (slot == 0)
4575b167fa91SNikolay Borisov 			fixup_low_keys(path, &disk_key, 1);
4576179e29e4SChris Mason 	}
45775f39d397SChris Mason 
4578dd3cc16bSRoss Kirk 	item = btrfs_item_nr(slot);
45795f39d397SChris Mason 	btrfs_set_item_size(leaf, item, new_size);
45805f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
4581b18c6685SChris Mason 
4582e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
4583a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
4584b18c6685SChris Mason 		BUG();
45855f39d397SChris Mason 	}
4586b18c6685SChris Mason }
4587b18c6685SChris Mason 
4588d352ac68SChris Mason /*
45898f69dbd2SStefan Behrens  * make the item pointed to by the path bigger, data_size is the added size.
4590d352ac68SChris Mason  */
4591c71dd880SDavid Sterba void btrfs_extend_item(struct btrfs_path *path, u32 data_size)
45926567e837SChris Mason {
45936567e837SChris Mason 	int slot;
45945f39d397SChris Mason 	struct extent_buffer *leaf;
45955f39d397SChris Mason 	struct btrfs_item *item;
45966567e837SChris Mason 	u32 nritems;
45976567e837SChris Mason 	unsigned int data_end;
45986567e837SChris Mason 	unsigned int old_data;
45996567e837SChris Mason 	unsigned int old_size;
46006567e837SChris Mason 	int i;
4601cfed81a0SChris Mason 	struct btrfs_map_token token;
4602cfed81a0SChris Mason 
46035f39d397SChris Mason 	leaf = path->nodes[0];
46046567e837SChris Mason 
46055f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
46068f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
46076567e837SChris Mason 
4608e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < data_size) {
4609a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
46106567e837SChris Mason 		BUG();
46115f39d397SChris Mason 	}
46126567e837SChris Mason 	slot = path->slots[0];
46135f39d397SChris Mason 	old_data = btrfs_item_end_nr(leaf, slot);
46146567e837SChris Mason 
46156567e837SChris Mason 	BUG_ON(slot < 0);
46163326d1b0SChris Mason 	if (slot >= nritems) {
4617a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
4618c71dd880SDavid Sterba 		btrfs_crit(leaf->fs_info, "slot %d too large, nritems %d",
4619d397712bSChris Mason 			   slot, nritems);
4620290342f6SArnd Bergmann 		BUG();
46213326d1b0SChris Mason 	}
46226567e837SChris Mason 
46236567e837SChris Mason 	/*
46246567e837SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
46256567e837SChris Mason 	 */
46266567e837SChris Mason 	/* first correct the data pointers */
4627c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
46286567e837SChris Mason 	for (i = slot; i < nritems; i++) {
46295f39d397SChris Mason 		u32 ioff;
4630dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
4631db94535dSChris Mason 
4632cc4c13d5SDavid Sterba 		ioff = btrfs_token_item_offset(&token, item);
4633cc4c13d5SDavid Sterba 		btrfs_set_token_item_offset(&token, item, ioff - data_size);
46346567e837SChris Mason 	}
46355f39d397SChris Mason 
46366567e837SChris Mason 	/* shift the data */
46373d9ec8c4SNikolay Borisov 	memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
46383d9ec8c4SNikolay Borisov 		      data_end - data_size, BTRFS_LEAF_DATA_OFFSET +
46396567e837SChris Mason 		      data_end, old_data - data_end);
46405f39d397SChris Mason 
46416567e837SChris Mason 	data_end = old_data;
46425f39d397SChris Mason 	old_size = btrfs_item_size_nr(leaf, slot);
4643dd3cc16bSRoss Kirk 	item = btrfs_item_nr(slot);
46445f39d397SChris Mason 	btrfs_set_item_size(leaf, item, old_size + data_size);
46455f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
46466567e837SChris Mason 
4647e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
4648a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
46496567e837SChris Mason 		BUG();
46505f39d397SChris Mason 	}
46516567e837SChris Mason }
46526567e837SChris Mason 
4653da9ffb24SNikolay Borisov /**
4654da9ffb24SNikolay Borisov  * setup_items_for_insert - Helper called before inserting one or more items
4655da9ffb24SNikolay Borisov  * to a leaf. Main purpose is to save stack depth by doing the bulk of the work
4656da9ffb24SNikolay Borisov  * in a function that doesn't call btrfs_search_slot
4657da9ffb24SNikolay Borisov  *
4658da9ffb24SNikolay Borisov  * @root:	root we are inserting items to
4659da9ffb24SNikolay Borisov  * @path:	points to the leaf/slot where we are going to insert new items
4660da9ffb24SNikolay Borisov  * @cpu_key:	array of keys for items to be inserted
4661da9ffb24SNikolay Borisov  * @data_size:	size of the body of each item we are going to insert
4662da9ffb24SNikolay Borisov  * @nr:		size of @cpu_key/@data_size arrays
466374123bd7SChris Mason  */
4664afe5fea7STsutomu Itoh void setup_items_for_insert(struct btrfs_root *root, struct btrfs_path *path,
4665310712b2SOmar Sandoval 			    const struct btrfs_key *cpu_key, u32 *data_size,
4666fc0d82e1SNikolay Borisov 			    int nr)
4667be0e5c09SChris Mason {
46680b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
46695f39d397SChris Mason 	struct btrfs_item *item;
46709c58309dSChris Mason 	int i;
46717518a238SChris Mason 	u32 nritems;
4672be0e5c09SChris Mason 	unsigned int data_end;
4673e2fa7227SChris Mason 	struct btrfs_disk_key disk_key;
467444871b1bSChris Mason 	struct extent_buffer *leaf;
467544871b1bSChris Mason 	int slot;
4676cfed81a0SChris Mason 	struct btrfs_map_token token;
4677fc0d82e1SNikolay Borisov 	u32 total_size;
4678fc0d82e1SNikolay Borisov 	u32 total_data = 0;
4679fc0d82e1SNikolay Borisov 
4680fc0d82e1SNikolay Borisov 	for (i = 0; i < nr; i++)
4681fc0d82e1SNikolay Borisov 		total_data += data_size[i];
4682fc0d82e1SNikolay Borisov 	total_size = total_data + (nr * sizeof(struct btrfs_item));
4683cfed81a0SChris Mason 
468424cdc847SFilipe Manana 	if (path->slots[0] == 0) {
468524cdc847SFilipe Manana 		btrfs_cpu_key_to_disk(&disk_key, cpu_key);
4686b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, 1);
468724cdc847SFilipe Manana 	}
468824cdc847SFilipe Manana 	btrfs_unlock_up_safe(path, 1);
468924cdc847SFilipe Manana 
46905f39d397SChris Mason 	leaf = path->nodes[0];
469144871b1bSChris Mason 	slot = path->slots[0];
469274123bd7SChris Mason 
46935f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
46948f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
4695eb60ceacSChris Mason 
4696e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < total_size) {
4697a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
46980b246afaSJeff Mahoney 		btrfs_crit(fs_info, "not enough freespace need %u have %d",
4699e902baacSDavid Sterba 			   total_size, btrfs_leaf_free_space(leaf));
4700be0e5c09SChris Mason 		BUG();
4701d4dbff95SChris Mason 	}
47025f39d397SChris Mason 
4703c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
4704be0e5c09SChris Mason 	if (slot != nritems) {
47055f39d397SChris Mason 		unsigned int old_data = btrfs_item_end_nr(leaf, slot);
4706be0e5c09SChris Mason 
47075f39d397SChris Mason 		if (old_data < data_end) {
4708a4f78750SDavid Sterba 			btrfs_print_leaf(leaf);
47097269ddd2SNikolay Borisov 			btrfs_crit(fs_info,
47107269ddd2SNikolay Borisov 		"item at slot %d with data offset %u beyond data end of leaf %u",
47115f39d397SChris Mason 				   slot, old_data, data_end);
4712290342f6SArnd Bergmann 			BUG();
47135f39d397SChris Mason 		}
4714be0e5c09SChris Mason 		/*
4715be0e5c09SChris Mason 		 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4716be0e5c09SChris Mason 		 */
4717be0e5c09SChris Mason 		/* first correct the data pointers */
47180783fcfcSChris Mason 		for (i = slot; i < nritems; i++) {
47195f39d397SChris Mason 			u32 ioff;
4720db94535dSChris Mason 
4721dd3cc16bSRoss Kirk 			item = btrfs_item_nr(i);
4722cc4c13d5SDavid Sterba 			ioff = btrfs_token_item_offset(&token, item);
4723cc4c13d5SDavid Sterba 			btrfs_set_token_item_offset(&token, item,
4724cc4c13d5SDavid Sterba 						    ioff - total_data);
47250783fcfcSChris Mason 		}
4726be0e5c09SChris Mason 		/* shift the items */
47279c58309dSChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + nr),
47285f39d397SChris Mason 			      btrfs_item_nr_offset(slot),
47290783fcfcSChris Mason 			      (nritems - slot) * sizeof(struct btrfs_item));
4730be0e5c09SChris Mason 
4731be0e5c09SChris Mason 		/* shift the data */
47323d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
47333d9ec8c4SNikolay Borisov 			      data_end - total_data, BTRFS_LEAF_DATA_OFFSET +
4734be0e5c09SChris Mason 			      data_end, old_data - data_end);
4735be0e5c09SChris Mason 		data_end = old_data;
4736be0e5c09SChris Mason 	}
47375f39d397SChris Mason 
473862e2749eSChris Mason 	/* setup the item for the new data */
47399c58309dSChris Mason 	for (i = 0; i < nr; i++) {
47409c58309dSChris Mason 		btrfs_cpu_key_to_disk(&disk_key, cpu_key + i);
47419c58309dSChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot + i);
4742dd3cc16bSRoss Kirk 		item = btrfs_item_nr(slot + i);
47439c58309dSChris Mason 		data_end -= data_size[i];
4744fc0716c2SNikolay Borisov 		btrfs_set_token_item_offset(&token, item, data_end);
4745cc4c13d5SDavid Sterba 		btrfs_set_token_item_size(&token, item, data_size[i]);
47469c58309dSChris Mason 	}
474744871b1bSChris Mason 
47489c58309dSChris Mason 	btrfs_set_header_nritems(leaf, nritems + nr);
4749b9473439SChris Mason 	btrfs_mark_buffer_dirty(leaf);
4750aa5d6bedSChris Mason 
4751e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
4752a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
4753be0e5c09SChris Mason 		BUG();
47545f39d397SChris Mason 	}
475544871b1bSChris Mason }
475644871b1bSChris Mason 
475744871b1bSChris Mason /*
475844871b1bSChris Mason  * Given a key and some data, insert items into the tree.
475944871b1bSChris Mason  * This does all the path init required, making room in the tree if needed.
476044871b1bSChris Mason  */
476144871b1bSChris Mason int btrfs_insert_empty_items(struct btrfs_trans_handle *trans,
476244871b1bSChris Mason 			    struct btrfs_root *root,
476344871b1bSChris Mason 			    struct btrfs_path *path,
4764310712b2SOmar Sandoval 			    const struct btrfs_key *cpu_key, u32 *data_size,
476544871b1bSChris Mason 			    int nr)
476644871b1bSChris Mason {
476744871b1bSChris Mason 	int ret = 0;
476844871b1bSChris Mason 	int slot;
476944871b1bSChris Mason 	int i;
477044871b1bSChris Mason 	u32 total_size = 0;
477144871b1bSChris Mason 	u32 total_data = 0;
477244871b1bSChris Mason 
477344871b1bSChris Mason 	for (i = 0; i < nr; i++)
477444871b1bSChris Mason 		total_data += data_size[i];
477544871b1bSChris Mason 
477644871b1bSChris Mason 	total_size = total_data + (nr * sizeof(struct btrfs_item));
477744871b1bSChris Mason 	ret = btrfs_search_slot(trans, root, cpu_key, path, total_size, 1);
477844871b1bSChris Mason 	if (ret == 0)
477944871b1bSChris Mason 		return -EEXIST;
478044871b1bSChris Mason 	if (ret < 0)
4781143bede5SJeff Mahoney 		return ret;
478244871b1bSChris Mason 
478344871b1bSChris Mason 	slot = path->slots[0];
478444871b1bSChris Mason 	BUG_ON(slot < 0);
478544871b1bSChris Mason 
4786fc0d82e1SNikolay Borisov 	setup_items_for_insert(root, path, cpu_key, data_size, nr);
4787143bede5SJeff Mahoney 	return 0;
478862e2749eSChris Mason }
478962e2749eSChris Mason 
479062e2749eSChris Mason /*
479162e2749eSChris Mason  * Given a key and some data, insert an item into the tree.
479262e2749eSChris Mason  * This does all the path init required, making room in the tree if needed.
479362e2749eSChris Mason  */
4794310712b2SOmar Sandoval int btrfs_insert_item(struct btrfs_trans_handle *trans, struct btrfs_root *root,
4795310712b2SOmar Sandoval 		      const struct btrfs_key *cpu_key, void *data,
4796310712b2SOmar Sandoval 		      u32 data_size)
479762e2749eSChris Mason {
479862e2749eSChris Mason 	int ret = 0;
47992c90e5d6SChris Mason 	struct btrfs_path *path;
48005f39d397SChris Mason 	struct extent_buffer *leaf;
48015f39d397SChris Mason 	unsigned long ptr;
480262e2749eSChris Mason 
48032c90e5d6SChris Mason 	path = btrfs_alloc_path();
4804db5b493aSTsutomu Itoh 	if (!path)
4805db5b493aSTsutomu Itoh 		return -ENOMEM;
48062c90e5d6SChris Mason 	ret = btrfs_insert_empty_item(trans, root, path, cpu_key, data_size);
480762e2749eSChris Mason 	if (!ret) {
48085f39d397SChris Mason 		leaf = path->nodes[0];
48095f39d397SChris Mason 		ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
48105f39d397SChris Mason 		write_extent_buffer(leaf, data, ptr, data_size);
48115f39d397SChris Mason 		btrfs_mark_buffer_dirty(leaf);
481262e2749eSChris Mason 	}
48132c90e5d6SChris Mason 	btrfs_free_path(path);
4814aa5d6bedSChris Mason 	return ret;
4815be0e5c09SChris Mason }
4816be0e5c09SChris Mason 
481774123bd7SChris Mason /*
48185de08d7dSChris Mason  * delete the pointer from a given node.
481974123bd7SChris Mason  *
4820d352ac68SChris Mason  * the tree should have been previously balanced so the deletion does not
4821d352ac68SChris Mason  * empty a node.
482274123bd7SChris Mason  */
4823afe5fea7STsutomu Itoh static void del_ptr(struct btrfs_root *root, struct btrfs_path *path,
4824afe5fea7STsutomu Itoh 		    int level, int slot)
4825be0e5c09SChris Mason {
48265f39d397SChris Mason 	struct extent_buffer *parent = path->nodes[level];
48277518a238SChris Mason 	u32 nritems;
4828f3ea38daSJan Schmidt 	int ret;
4829be0e5c09SChris Mason 
48305f39d397SChris Mason 	nritems = btrfs_header_nritems(parent);
4831be0e5c09SChris Mason 	if (slot != nritems - 1) {
4832bf1d3425SDavid Sterba 		if (level) {
4833bf1d3425SDavid Sterba 			ret = tree_mod_log_insert_move(parent, slot, slot + 1,
4834a446a979SDavid Sterba 					nritems - slot - 1);
4835bf1d3425SDavid Sterba 			BUG_ON(ret < 0);
4836bf1d3425SDavid Sterba 		}
48375f39d397SChris Mason 		memmove_extent_buffer(parent,
48385f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot),
48395f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot + 1),
4840d6025579SChris Mason 			      sizeof(struct btrfs_key_ptr) *
4841d6025579SChris Mason 			      (nritems - slot - 1));
484257ba86c0SChris Mason 	} else if (level) {
4843e09c2efeSDavid Sterba 		ret = tree_mod_log_insert_key(parent, slot, MOD_LOG_KEY_REMOVE,
4844e09c2efeSDavid Sterba 				GFP_NOFS);
484557ba86c0SChris Mason 		BUG_ON(ret < 0);
4846be0e5c09SChris Mason 	}
4847f3ea38daSJan Schmidt 
48487518a238SChris Mason 	nritems--;
48495f39d397SChris Mason 	btrfs_set_header_nritems(parent, nritems);
48507518a238SChris Mason 	if (nritems == 0 && parent == root->node) {
48515f39d397SChris Mason 		BUG_ON(btrfs_header_level(root->node) != 1);
4852eb60ceacSChris Mason 		/* just turn the root into a leaf and break */
48535f39d397SChris Mason 		btrfs_set_header_level(root->node, 0);
4854bb803951SChris Mason 	} else if (slot == 0) {
48555f39d397SChris Mason 		struct btrfs_disk_key disk_key;
48565f39d397SChris Mason 
48575f39d397SChris Mason 		btrfs_node_key(parent, &disk_key, 0);
4858b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, level + 1);
4859be0e5c09SChris Mason 	}
4860d6025579SChris Mason 	btrfs_mark_buffer_dirty(parent);
4861be0e5c09SChris Mason }
4862be0e5c09SChris Mason 
486374123bd7SChris Mason /*
4864323ac95bSChris Mason  * a helper function to delete the leaf pointed to by path->slots[1] and
48655d4f98a2SYan Zheng  * path->nodes[1].
4866323ac95bSChris Mason  *
4867323ac95bSChris Mason  * This deletes the pointer in path->nodes[1] and frees the leaf
4868323ac95bSChris Mason  * block extent.  zero is returned if it all worked out, < 0 otherwise.
4869323ac95bSChris Mason  *
4870323ac95bSChris Mason  * The path must have already been setup for deleting the leaf, including
4871323ac95bSChris Mason  * all the proper balancing.  path->nodes[1] must be locked.
4872323ac95bSChris Mason  */
4873143bede5SJeff Mahoney static noinline void btrfs_del_leaf(struct btrfs_trans_handle *trans,
4874323ac95bSChris Mason 				    struct btrfs_root *root,
48755d4f98a2SYan Zheng 				    struct btrfs_path *path,
48765d4f98a2SYan Zheng 				    struct extent_buffer *leaf)
4877323ac95bSChris Mason {
48785d4f98a2SYan Zheng 	WARN_ON(btrfs_header_generation(leaf) != trans->transid);
4879afe5fea7STsutomu Itoh 	del_ptr(root, path, 1, path->slots[1]);
4880323ac95bSChris Mason 
48814d081c41SChris Mason 	/*
48824d081c41SChris Mason 	 * btrfs_free_extent is expensive, we want to make sure we
48834d081c41SChris Mason 	 * aren't holding any locks when we call it
48844d081c41SChris Mason 	 */
48854d081c41SChris Mason 	btrfs_unlock_up_safe(path, 0);
48864d081c41SChris Mason 
4887f0486c68SYan, Zheng 	root_sub_used(root, leaf->len);
4888f0486c68SYan, Zheng 
488967439dadSDavid Sterba 	atomic_inc(&leaf->refs);
48905581a51aSJan Schmidt 	btrfs_free_tree_block(trans, root, leaf, 0, 1);
48913083ee2eSJosef Bacik 	free_extent_buffer_stale(leaf);
4892323ac95bSChris Mason }
4893323ac95bSChris Mason /*
489474123bd7SChris Mason  * delete the item at the leaf level in path.  If that empties
489574123bd7SChris Mason  * the leaf, remove it from the tree
489674123bd7SChris Mason  */
489785e21bacSChris Mason int btrfs_del_items(struct btrfs_trans_handle *trans, struct btrfs_root *root,
489885e21bacSChris Mason 		    struct btrfs_path *path, int slot, int nr)
4899be0e5c09SChris Mason {
49000b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
49015f39d397SChris Mason 	struct extent_buffer *leaf;
49025f39d397SChris Mason 	struct btrfs_item *item;
4903ce0eac2aSAlexandru Moise 	u32 last_off;
4904ce0eac2aSAlexandru Moise 	u32 dsize = 0;
4905aa5d6bedSChris Mason 	int ret = 0;
4906aa5d6bedSChris Mason 	int wret;
490785e21bacSChris Mason 	int i;
49087518a238SChris Mason 	u32 nritems;
4909be0e5c09SChris Mason 
49105f39d397SChris Mason 	leaf = path->nodes[0];
491185e21bacSChris Mason 	last_off = btrfs_item_offset_nr(leaf, slot + nr - 1);
491285e21bacSChris Mason 
491385e21bacSChris Mason 	for (i = 0; i < nr; i++)
491485e21bacSChris Mason 		dsize += btrfs_item_size_nr(leaf, slot + i);
491585e21bacSChris Mason 
49165f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
4917be0e5c09SChris Mason 
491885e21bacSChris Mason 	if (slot + nr != nritems) {
49198f881e8cSDavid Sterba 		int data_end = leaf_data_end(leaf);
4920c82f823cSDavid Sterba 		struct btrfs_map_token token;
49215f39d397SChris Mason 
49223d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
4923d6025579SChris Mason 			      data_end + dsize,
49243d9ec8c4SNikolay Borisov 			      BTRFS_LEAF_DATA_OFFSET + data_end,
492585e21bacSChris Mason 			      last_off - data_end);
49265f39d397SChris Mason 
4927c82f823cSDavid Sterba 		btrfs_init_map_token(&token, leaf);
492885e21bacSChris Mason 		for (i = slot + nr; i < nritems; i++) {
49295f39d397SChris Mason 			u32 ioff;
4930db94535dSChris Mason 
4931dd3cc16bSRoss Kirk 			item = btrfs_item_nr(i);
4932cc4c13d5SDavid Sterba 			ioff = btrfs_token_item_offset(&token, item);
4933cc4c13d5SDavid Sterba 			btrfs_set_token_item_offset(&token, item, ioff + dsize);
49340783fcfcSChris Mason 		}
4935db94535dSChris Mason 
49365f39d397SChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot),
493785e21bacSChris Mason 			      btrfs_item_nr_offset(slot + nr),
49380783fcfcSChris Mason 			      sizeof(struct btrfs_item) *
493985e21bacSChris Mason 			      (nritems - slot - nr));
4940be0e5c09SChris Mason 	}
494185e21bacSChris Mason 	btrfs_set_header_nritems(leaf, nritems - nr);
494285e21bacSChris Mason 	nritems -= nr;
49435f39d397SChris Mason 
494474123bd7SChris Mason 	/* delete the leaf if we've emptied it */
49457518a238SChris Mason 	if (nritems == 0) {
49465f39d397SChris Mason 		if (leaf == root->node) {
49475f39d397SChris Mason 			btrfs_set_header_level(leaf, 0);
49489a8dd150SChris Mason 		} else {
49496a884d7dSDavid Sterba 			btrfs_clean_tree_block(leaf);
4950143bede5SJeff Mahoney 			btrfs_del_leaf(trans, root, path, leaf);
49519a8dd150SChris Mason 		}
4952be0e5c09SChris Mason 	} else {
49537518a238SChris Mason 		int used = leaf_space_used(leaf, 0, nritems);
4954aa5d6bedSChris Mason 		if (slot == 0) {
49555f39d397SChris Mason 			struct btrfs_disk_key disk_key;
49565f39d397SChris Mason 
49575f39d397SChris Mason 			btrfs_item_key(leaf, &disk_key, 0);
4958b167fa91SNikolay Borisov 			fixup_low_keys(path, &disk_key, 1);
4959aa5d6bedSChris Mason 		}
4960aa5d6bedSChris Mason 
496174123bd7SChris Mason 		/* delete the leaf if it is mostly empty */
49620b246afaSJeff Mahoney 		if (used < BTRFS_LEAF_DATA_SIZE(fs_info) / 3) {
4963be0e5c09SChris Mason 			/* push_leaf_left fixes the path.
4964be0e5c09SChris Mason 			 * make sure the path still points to our leaf
4965be0e5c09SChris Mason 			 * for possible call to del_ptr below
4966be0e5c09SChris Mason 			 */
49674920c9acSChris Mason 			slot = path->slots[1];
496867439dadSDavid Sterba 			atomic_inc(&leaf->refs);
49695f39d397SChris Mason 
497099d8f83cSChris Mason 			wret = push_leaf_left(trans, root, path, 1, 1,
497199d8f83cSChris Mason 					      1, (u32)-1);
497254aa1f4dSChris Mason 			if (wret < 0 && wret != -ENOSPC)
4973aa5d6bedSChris Mason 				ret = wret;
49745f39d397SChris Mason 
49755f39d397SChris Mason 			if (path->nodes[0] == leaf &&
49765f39d397SChris Mason 			    btrfs_header_nritems(leaf)) {
497799d8f83cSChris Mason 				wret = push_leaf_right(trans, root, path, 1,
497899d8f83cSChris Mason 						       1, 1, 0);
497954aa1f4dSChris Mason 				if (wret < 0 && wret != -ENOSPC)
4980aa5d6bedSChris Mason 					ret = wret;
4981aa5d6bedSChris Mason 			}
49825f39d397SChris Mason 
49835f39d397SChris Mason 			if (btrfs_header_nritems(leaf) == 0) {
4984323ac95bSChris Mason 				path->slots[1] = slot;
4985143bede5SJeff Mahoney 				btrfs_del_leaf(trans, root, path, leaf);
49865f39d397SChris Mason 				free_extent_buffer(leaf);
4987143bede5SJeff Mahoney 				ret = 0;
49885de08d7dSChris Mason 			} else {
4989925baeddSChris Mason 				/* if we're still in the path, make sure
4990925baeddSChris Mason 				 * we're dirty.  Otherwise, one of the
4991925baeddSChris Mason 				 * push_leaf functions must have already
4992925baeddSChris Mason 				 * dirtied this buffer
4993925baeddSChris Mason 				 */
4994925baeddSChris Mason 				if (path->nodes[0] == leaf)
49955f39d397SChris Mason 					btrfs_mark_buffer_dirty(leaf);
49965f39d397SChris Mason 				free_extent_buffer(leaf);
4997be0e5c09SChris Mason 			}
4998d5719762SChris Mason 		} else {
49995f39d397SChris Mason 			btrfs_mark_buffer_dirty(leaf);
5000be0e5c09SChris Mason 		}
50019a8dd150SChris Mason 	}
5002aa5d6bedSChris Mason 	return ret;
50039a8dd150SChris Mason }
50049a8dd150SChris Mason 
500597571fd0SChris Mason /*
5006925baeddSChris Mason  * search the tree again to find a leaf with lesser keys
50077bb86316SChris Mason  * returns 0 if it found something or 1 if there are no lesser leaves.
50087bb86316SChris Mason  * returns < 0 on io errors.
5009d352ac68SChris Mason  *
5010d352ac68SChris Mason  * This may release the path, and so you may lose any locks held at the
5011d352ac68SChris Mason  * time you call it.
50127bb86316SChris Mason  */
501316e7549fSJosef Bacik int btrfs_prev_leaf(struct btrfs_root *root, struct btrfs_path *path)
50147bb86316SChris Mason {
5015925baeddSChris Mason 	struct btrfs_key key;
5016925baeddSChris Mason 	struct btrfs_disk_key found_key;
5017925baeddSChris Mason 	int ret;
50187bb86316SChris Mason 
5019925baeddSChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, 0);
5020925baeddSChris Mason 
5021e8b0d724SFilipe David Borba Manana 	if (key.offset > 0) {
5022925baeddSChris Mason 		key.offset--;
5023e8b0d724SFilipe David Borba Manana 	} else if (key.type > 0) {
5024925baeddSChris Mason 		key.type--;
5025e8b0d724SFilipe David Borba Manana 		key.offset = (u64)-1;
5026e8b0d724SFilipe David Borba Manana 	} else if (key.objectid > 0) {
5027925baeddSChris Mason 		key.objectid--;
5028e8b0d724SFilipe David Borba Manana 		key.type = (u8)-1;
5029e8b0d724SFilipe David Borba Manana 		key.offset = (u64)-1;
5030e8b0d724SFilipe David Borba Manana 	} else {
50317bb86316SChris Mason 		return 1;
5032e8b0d724SFilipe David Borba Manana 	}
50337bb86316SChris Mason 
5034b3b4aa74SDavid Sterba 	btrfs_release_path(path);
5035925baeddSChris Mason 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5036925baeddSChris Mason 	if (ret < 0)
5037925baeddSChris Mason 		return ret;
5038925baeddSChris Mason 	btrfs_item_key(path->nodes[0], &found_key, 0);
5039925baeddSChris Mason 	ret = comp_keys(&found_key, &key);
5040337c6f68SFilipe Manana 	/*
5041337c6f68SFilipe Manana 	 * We might have had an item with the previous key in the tree right
5042337c6f68SFilipe Manana 	 * before we released our path. And after we released our path, that
5043337c6f68SFilipe Manana 	 * item might have been pushed to the first slot (0) of the leaf we
5044337c6f68SFilipe Manana 	 * were holding due to a tree balance. Alternatively, an item with the
5045337c6f68SFilipe Manana 	 * previous key can exist as the only element of a leaf (big fat item).
5046337c6f68SFilipe Manana 	 * Therefore account for these 2 cases, so that our callers (like
5047337c6f68SFilipe Manana 	 * btrfs_previous_item) don't miss an existing item with a key matching
5048337c6f68SFilipe Manana 	 * the previous key we computed above.
5049337c6f68SFilipe Manana 	 */
5050337c6f68SFilipe Manana 	if (ret <= 0)
50517bb86316SChris Mason 		return 0;
5052925baeddSChris Mason 	return 1;
50537bb86316SChris Mason }
50547bb86316SChris Mason 
50553f157a2fSChris Mason /*
50563f157a2fSChris Mason  * A helper function to walk down the tree starting at min_key, and looking
5057de78b51aSEric Sandeen  * for nodes or leaves that are have a minimum transaction id.
5058de78b51aSEric Sandeen  * This is used by the btree defrag code, and tree logging
50593f157a2fSChris Mason  *
50603f157a2fSChris Mason  * This does not cow, but it does stuff the starting key it finds back
50613f157a2fSChris Mason  * into min_key, so you can call btrfs_search_slot with cow=1 on the
50623f157a2fSChris Mason  * key and get a writable path.
50633f157a2fSChris Mason  *
50643f157a2fSChris Mason  * This honors path->lowest_level to prevent descent past a given level
50653f157a2fSChris Mason  * of the tree.
50663f157a2fSChris Mason  *
5067d352ac68SChris Mason  * min_trans indicates the oldest transaction that you are interested
5068d352ac68SChris Mason  * in walking through.  Any nodes or leaves older than min_trans are
5069d352ac68SChris Mason  * skipped over (without reading them).
5070d352ac68SChris Mason  *
50713f157a2fSChris Mason  * returns zero if something useful was found, < 0 on error and 1 if there
50723f157a2fSChris Mason  * was nothing in the tree that matched the search criteria.
50733f157a2fSChris Mason  */
50743f157a2fSChris Mason int btrfs_search_forward(struct btrfs_root *root, struct btrfs_key *min_key,
5075de78b51aSEric Sandeen 			 struct btrfs_path *path,
50763f157a2fSChris Mason 			 u64 min_trans)
50773f157a2fSChris Mason {
50783f157a2fSChris Mason 	struct extent_buffer *cur;
50793f157a2fSChris Mason 	struct btrfs_key found_key;
50803f157a2fSChris Mason 	int slot;
50819652480bSYan 	int sret;
50823f157a2fSChris Mason 	u32 nritems;
50833f157a2fSChris Mason 	int level;
50843f157a2fSChris Mason 	int ret = 1;
5085f98de9b9SFilipe Manana 	int keep_locks = path->keep_locks;
50863f157a2fSChris Mason 
5087f98de9b9SFilipe Manana 	path->keep_locks = 1;
50883f157a2fSChris Mason again:
5089bd681513SChris Mason 	cur = btrfs_read_lock_root_node(root);
50903f157a2fSChris Mason 	level = btrfs_header_level(cur);
5091e02119d5SChris Mason 	WARN_ON(path->nodes[level]);
50923f157a2fSChris Mason 	path->nodes[level] = cur;
5093bd681513SChris Mason 	path->locks[level] = BTRFS_READ_LOCK;
50943f157a2fSChris Mason 
50953f157a2fSChris Mason 	if (btrfs_header_generation(cur) < min_trans) {
50963f157a2fSChris Mason 		ret = 1;
50973f157a2fSChris Mason 		goto out;
50983f157a2fSChris Mason 	}
50993f157a2fSChris Mason 	while (1) {
51003f157a2fSChris Mason 		nritems = btrfs_header_nritems(cur);
51013f157a2fSChris Mason 		level = btrfs_header_level(cur);
5102e3b83361SQu Wenruo 		sret = btrfs_bin_search(cur, min_key, &slot);
5103cbca7d59SFilipe Manana 		if (sret < 0) {
5104cbca7d59SFilipe Manana 			ret = sret;
5105cbca7d59SFilipe Manana 			goto out;
5106cbca7d59SFilipe Manana 		}
51073f157a2fSChris Mason 
5108323ac95bSChris Mason 		/* at the lowest level, we're done, setup the path and exit */
5109323ac95bSChris Mason 		if (level == path->lowest_level) {
5110e02119d5SChris Mason 			if (slot >= nritems)
5111e02119d5SChris Mason 				goto find_next_key;
51123f157a2fSChris Mason 			ret = 0;
51133f157a2fSChris Mason 			path->slots[level] = slot;
51143f157a2fSChris Mason 			btrfs_item_key_to_cpu(cur, &found_key, slot);
51153f157a2fSChris Mason 			goto out;
51163f157a2fSChris Mason 		}
51179652480bSYan 		if (sret && slot > 0)
51189652480bSYan 			slot--;
51193f157a2fSChris Mason 		/*
5120de78b51aSEric Sandeen 		 * check this node pointer against the min_trans parameters.
5121260db43cSRandy Dunlap 		 * If it is too old, skip to the next one.
51223f157a2fSChris Mason 		 */
51233f157a2fSChris Mason 		while (slot < nritems) {
51243f157a2fSChris Mason 			u64 gen;
5125e02119d5SChris Mason 
51263f157a2fSChris Mason 			gen = btrfs_node_ptr_generation(cur, slot);
51273f157a2fSChris Mason 			if (gen < min_trans) {
51283f157a2fSChris Mason 				slot++;
51293f157a2fSChris Mason 				continue;
51303f157a2fSChris Mason 			}
51313f157a2fSChris Mason 			break;
51323f157a2fSChris Mason 		}
5133e02119d5SChris Mason find_next_key:
51343f157a2fSChris Mason 		/*
51353f157a2fSChris Mason 		 * we didn't find a candidate key in this node, walk forward
51363f157a2fSChris Mason 		 * and find another one
51373f157a2fSChris Mason 		 */
51383f157a2fSChris Mason 		if (slot >= nritems) {
5139e02119d5SChris Mason 			path->slots[level] = slot;
5140e02119d5SChris Mason 			sret = btrfs_find_next_key(root, path, min_key, level,
5141de78b51aSEric Sandeen 						  min_trans);
5142e02119d5SChris Mason 			if (sret == 0) {
5143b3b4aa74SDavid Sterba 				btrfs_release_path(path);
51443f157a2fSChris Mason 				goto again;
51453f157a2fSChris Mason 			} else {
51463f157a2fSChris Mason 				goto out;
51473f157a2fSChris Mason 			}
51483f157a2fSChris Mason 		}
51493f157a2fSChris Mason 		/* save our key for returning back */
51503f157a2fSChris Mason 		btrfs_node_key_to_cpu(cur, &found_key, slot);
51513f157a2fSChris Mason 		path->slots[level] = slot;
51523f157a2fSChris Mason 		if (level == path->lowest_level) {
51533f157a2fSChris Mason 			ret = 0;
51543f157a2fSChris Mason 			goto out;
51553f157a2fSChris Mason 		}
51564b231ae4SDavid Sterba 		cur = btrfs_read_node_slot(cur, slot);
5157fb770ae4SLiu Bo 		if (IS_ERR(cur)) {
5158fb770ae4SLiu Bo 			ret = PTR_ERR(cur);
5159fb770ae4SLiu Bo 			goto out;
5160fb770ae4SLiu Bo 		}
51613f157a2fSChris Mason 
5162bd681513SChris Mason 		btrfs_tree_read_lock(cur);
5163b4ce94deSChris Mason 
5164bd681513SChris Mason 		path->locks[level - 1] = BTRFS_READ_LOCK;
51653f157a2fSChris Mason 		path->nodes[level - 1] = cur;
5166f7c79f30SChris Mason 		unlock_up(path, level, 1, 0, NULL);
51673f157a2fSChris Mason 	}
51683f157a2fSChris Mason out:
5169f98de9b9SFilipe Manana 	path->keep_locks = keep_locks;
5170f98de9b9SFilipe Manana 	if (ret == 0) {
5171f98de9b9SFilipe Manana 		btrfs_unlock_up_safe(path, path->lowest_level + 1);
5172f98de9b9SFilipe Manana 		memcpy(min_key, &found_key, sizeof(found_key));
5173f98de9b9SFilipe Manana 	}
51743f157a2fSChris Mason 	return ret;
51753f157a2fSChris Mason }
51763f157a2fSChris Mason 
51773f157a2fSChris Mason /*
51783f157a2fSChris Mason  * this is similar to btrfs_next_leaf, but does not try to preserve
51793f157a2fSChris Mason  * and fixup the path.  It looks for and returns the next key in the
5180de78b51aSEric Sandeen  * tree based on the current path and the min_trans parameters.
51813f157a2fSChris Mason  *
51823f157a2fSChris Mason  * 0 is returned if another key is found, < 0 if there are any errors
51833f157a2fSChris Mason  * and 1 is returned if there are no higher keys in the tree
51843f157a2fSChris Mason  *
51853f157a2fSChris Mason  * path->keep_locks should be set to 1 on the search made before
51863f157a2fSChris Mason  * calling this function.
51873f157a2fSChris Mason  */
5188e7a84565SChris Mason int btrfs_find_next_key(struct btrfs_root *root, struct btrfs_path *path,
5189de78b51aSEric Sandeen 			struct btrfs_key *key, int level, u64 min_trans)
5190e7a84565SChris Mason {
5191e7a84565SChris Mason 	int slot;
5192e7a84565SChris Mason 	struct extent_buffer *c;
5193e7a84565SChris Mason 
51946a9fb468SJosef Bacik 	WARN_ON(!path->keep_locks && !path->skip_locking);
5195e7a84565SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
5196e7a84565SChris Mason 		if (!path->nodes[level])
5197e7a84565SChris Mason 			return 1;
5198e7a84565SChris Mason 
5199e7a84565SChris Mason 		slot = path->slots[level] + 1;
5200e7a84565SChris Mason 		c = path->nodes[level];
52013f157a2fSChris Mason next:
5202e7a84565SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
520333c66f43SYan Zheng 			int ret;
520433c66f43SYan Zheng 			int orig_lowest;
520533c66f43SYan Zheng 			struct btrfs_key cur_key;
520633c66f43SYan Zheng 			if (level + 1 >= BTRFS_MAX_LEVEL ||
520733c66f43SYan Zheng 			    !path->nodes[level + 1])
5208e7a84565SChris Mason 				return 1;
520933c66f43SYan Zheng 
52106a9fb468SJosef Bacik 			if (path->locks[level + 1] || path->skip_locking) {
521133c66f43SYan Zheng 				level++;
5212e7a84565SChris Mason 				continue;
5213e7a84565SChris Mason 			}
521433c66f43SYan Zheng 
521533c66f43SYan Zheng 			slot = btrfs_header_nritems(c) - 1;
521633c66f43SYan Zheng 			if (level == 0)
521733c66f43SYan Zheng 				btrfs_item_key_to_cpu(c, &cur_key, slot);
521833c66f43SYan Zheng 			else
521933c66f43SYan Zheng 				btrfs_node_key_to_cpu(c, &cur_key, slot);
522033c66f43SYan Zheng 
522133c66f43SYan Zheng 			orig_lowest = path->lowest_level;
5222b3b4aa74SDavid Sterba 			btrfs_release_path(path);
522333c66f43SYan Zheng 			path->lowest_level = level;
522433c66f43SYan Zheng 			ret = btrfs_search_slot(NULL, root, &cur_key, path,
522533c66f43SYan Zheng 						0, 0);
522633c66f43SYan Zheng 			path->lowest_level = orig_lowest;
522733c66f43SYan Zheng 			if (ret < 0)
522833c66f43SYan Zheng 				return ret;
522933c66f43SYan Zheng 
523033c66f43SYan Zheng 			c = path->nodes[level];
523133c66f43SYan Zheng 			slot = path->slots[level];
523233c66f43SYan Zheng 			if (ret == 0)
523333c66f43SYan Zheng 				slot++;
523433c66f43SYan Zheng 			goto next;
523533c66f43SYan Zheng 		}
523633c66f43SYan Zheng 
5237e7a84565SChris Mason 		if (level == 0)
5238e7a84565SChris Mason 			btrfs_item_key_to_cpu(c, key, slot);
52393f157a2fSChris Mason 		else {
52403f157a2fSChris Mason 			u64 gen = btrfs_node_ptr_generation(c, slot);
52413f157a2fSChris Mason 
52423f157a2fSChris Mason 			if (gen < min_trans) {
52433f157a2fSChris Mason 				slot++;
52443f157a2fSChris Mason 				goto next;
52453f157a2fSChris Mason 			}
5246e7a84565SChris Mason 			btrfs_node_key_to_cpu(c, key, slot);
52473f157a2fSChris Mason 		}
5248e7a84565SChris Mason 		return 0;
5249e7a84565SChris Mason 	}
5250e7a84565SChris Mason 	return 1;
5251e7a84565SChris Mason }
5252e7a84565SChris Mason 
52537bb86316SChris Mason /*
5254925baeddSChris Mason  * search the tree again to find a leaf with greater keys
52550f70abe2SChris Mason  * returns 0 if it found something or 1 if there are no greater leaves.
52560f70abe2SChris Mason  * returns < 0 on io errors.
525797571fd0SChris Mason  */
5258234b63a0SChris Mason int btrfs_next_leaf(struct btrfs_root *root, struct btrfs_path *path)
5259d97e63b6SChris Mason {
52603d7806ecSJan Schmidt 	return btrfs_next_old_leaf(root, path, 0);
52613d7806ecSJan Schmidt }
52623d7806ecSJan Schmidt 
52633d7806ecSJan Schmidt int btrfs_next_old_leaf(struct btrfs_root *root, struct btrfs_path *path,
52643d7806ecSJan Schmidt 			u64 time_seq)
52653d7806ecSJan Schmidt {
5266d97e63b6SChris Mason 	int slot;
52678e73f275SChris Mason 	int level;
52685f39d397SChris Mason 	struct extent_buffer *c;
52698e73f275SChris Mason 	struct extent_buffer *next;
5270925baeddSChris Mason 	struct btrfs_key key;
5271925baeddSChris Mason 	u32 nritems;
5272925baeddSChris Mason 	int ret;
5273bd681513SChris Mason 	int next_rw_lock = 0;
5274925baeddSChris Mason 
5275925baeddSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
5276d397712bSChris Mason 	if (nritems == 0)
5277925baeddSChris Mason 		return 1;
5278925baeddSChris Mason 
52798e73f275SChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, nritems - 1);
52808e73f275SChris Mason again:
52818e73f275SChris Mason 	level = 1;
52828e73f275SChris Mason 	next = NULL;
5283bd681513SChris Mason 	next_rw_lock = 0;
5284b3b4aa74SDavid Sterba 	btrfs_release_path(path);
52858e73f275SChris Mason 
5286a2135011SChris Mason 	path->keep_locks = 1;
52878e73f275SChris Mason 
52883d7806ecSJan Schmidt 	if (time_seq)
52893d7806ecSJan Schmidt 		ret = btrfs_search_old_slot(root, &key, path, time_seq);
52903d7806ecSJan Schmidt 	else
5291925baeddSChris Mason 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5292925baeddSChris Mason 	path->keep_locks = 0;
5293925baeddSChris Mason 
5294925baeddSChris Mason 	if (ret < 0)
5295925baeddSChris Mason 		return ret;
5296925baeddSChris Mason 
5297a2135011SChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
5298168fd7d2SChris Mason 	/*
5299168fd7d2SChris Mason 	 * by releasing the path above we dropped all our locks.  A balance
5300168fd7d2SChris Mason 	 * could have added more items next to the key that used to be
5301168fd7d2SChris Mason 	 * at the very end of the block.  So, check again here and
5302168fd7d2SChris Mason 	 * advance the path if there are now more items available.
5303168fd7d2SChris Mason 	 */
5304a2135011SChris Mason 	if (nritems > 0 && path->slots[0] < nritems - 1) {
5305e457afecSYan Zheng 		if (ret == 0)
5306168fd7d2SChris Mason 			path->slots[0]++;
53078e73f275SChris Mason 		ret = 0;
5308925baeddSChris Mason 		goto done;
5309925baeddSChris Mason 	}
53100b43e04fSLiu Bo 	/*
53110b43e04fSLiu Bo 	 * So the above check misses one case:
53120b43e04fSLiu Bo 	 * - after releasing the path above, someone has removed the item that
53130b43e04fSLiu Bo 	 *   used to be at the very end of the block, and balance between leafs
53140b43e04fSLiu Bo 	 *   gets another one with bigger key.offset to replace it.
53150b43e04fSLiu Bo 	 *
53160b43e04fSLiu Bo 	 * This one should be returned as well, or we can get leaf corruption
53170b43e04fSLiu Bo 	 * later(esp. in __btrfs_drop_extents()).
53180b43e04fSLiu Bo 	 *
53190b43e04fSLiu Bo 	 * And a bit more explanation about this check,
53200b43e04fSLiu Bo 	 * with ret > 0, the key isn't found, the path points to the slot
53210b43e04fSLiu Bo 	 * where it should be inserted, so the path->slots[0] item must be the
53220b43e04fSLiu Bo 	 * bigger one.
53230b43e04fSLiu Bo 	 */
53240b43e04fSLiu Bo 	if (nritems > 0 && ret > 0 && path->slots[0] == nritems - 1) {
53250b43e04fSLiu Bo 		ret = 0;
53260b43e04fSLiu Bo 		goto done;
53270b43e04fSLiu Bo 	}
5328d97e63b6SChris Mason 
5329234b63a0SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
53308e73f275SChris Mason 		if (!path->nodes[level]) {
53318e73f275SChris Mason 			ret = 1;
53328e73f275SChris Mason 			goto done;
53338e73f275SChris Mason 		}
53345f39d397SChris Mason 
5335d97e63b6SChris Mason 		slot = path->slots[level] + 1;
5336d97e63b6SChris Mason 		c = path->nodes[level];
53375f39d397SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
5338d97e63b6SChris Mason 			level++;
53398e73f275SChris Mason 			if (level == BTRFS_MAX_LEVEL) {
53408e73f275SChris Mason 				ret = 1;
53418e73f275SChris Mason 				goto done;
53428e73f275SChris Mason 			}
5343d97e63b6SChris Mason 			continue;
5344d97e63b6SChris Mason 		}
53455f39d397SChris Mason 
5346925baeddSChris Mason 		if (next) {
5347bd681513SChris Mason 			btrfs_tree_unlock_rw(next, next_rw_lock);
53485f39d397SChris Mason 			free_extent_buffer(next);
5349925baeddSChris Mason 		}
53505f39d397SChris Mason 
53518e73f275SChris Mason 		next = c;
5352bd681513SChris Mason 		next_rw_lock = path->locks[level];
5353d07b8528SLiu Bo 		ret = read_block_for_search(root, path, &next, level,
5354cda79c54SDavid Sterba 					    slot, &key);
53558e73f275SChris Mason 		if (ret == -EAGAIN)
53568e73f275SChris Mason 			goto again;
53575f39d397SChris Mason 
535876a05b35SChris Mason 		if (ret < 0) {
5359b3b4aa74SDavid Sterba 			btrfs_release_path(path);
536076a05b35SChris Mason 			goto done;
536176a05b35SChris Mason 		}
536276a05b35SChris Mason 
53635cd57b2cSChris Mason 		if (!path->skip_locking) {
5364bd681513SChris Mason 			ret = btrfs_try_tree_read_lock(next);
5365d42244a0SJan Schmidt 			if (!ret && time_seq) {
5366d42244a0SJan Schmidt 				/*
5367d42244a0SJan Schmidt 				 * If we don't get the lock, we may be racing
5368d42244a0SJan Schmidt 				 * with push_leaf_left, holding that lock while
5369d42244a0SJan Schmidt 				 * itself waiting for the leaf we've currently
5370d42244a0SJan Schmidt 				 * locked. To solve this situation, we give up
5371d42244a0SJan Schmidt 				 * on our lock and cycle.
5372d42244a0SJan Schmidt 				 */
5373cf538830SJan Schmidt 				free_extent_buffer(next);
5374d42244a0SJan Schmidt 				btrfs_release_path(path);
5375d42244a0SJan Schmidt 				cond_resched();
5376d42244a0SJan Schmidt 				goto again;
5377d42244a0SJan Schmidt 			}
53788e73f275SChris Mason 			if (!ret) {
5379fd7ba1c1SJosef Bacik 				__btrfs_tree_read_lock(next,
5380bf77467aSJosef Bacik 						       BTRFS_NESTING_RIGHT,
5381fd7ba1c1SJosef Bacik 						       path->recurse);
53828e73f275SChris Mason 			}
5383bd681513SChris Mason 			next_rw_lock = BTRFS_READ_LOCK;
5384bd681513SChris Mason 		}
5385d97e63b6SChris Mason 		break;
5386d97e63b6SChris Mason 	}
5387d97e63b6SChris Mason 	path->slots[level] = slot;
5388d97e63b6SChris Mason 	while (1) {
5389d97e63b6SChris Mason 		level--;
5390d97e63b6SChris Mason 		c = path->nodes[level];
5391925baeddSChris Mason 		if (path->locks[level])
5392bd681513SChris Mason 			btrfs_tree_unlock_rw(c, path->locks[level]);
53938e73f275SChris Mason 
53945f39d397SChris Mason 		free_extent_buffer(c);
5395d97e63b6SChris Mason 		path->nodes[level] = next;
5396d97e63b6SChris Mason 		path->slots[level] = 0;
5397a74a4b97SChris Mason 		if (!path->skip_locking)
5398bd681513SChris Mason 			path->locks[level] = next_rw_lock;
5399d97e63b6SChris Mason 		if (!level)
5400d97e63b6SChris Mason 			break;
5401b4ce94deSChris Mason 
5402d07b8528SLiu Bo 		ret = read_block_for_search(root, path, &next, level,
5403cda79c54SDavid Sterba 					    0, &key);
54048e73f275SChris Mason 		if (ret == -EAGAIN)
54058e73f275SChris Mason 			goto again;
54068e73f275SChris Mason 
540776a05b35SChris Mason 		if (ret < 0) {
5408b3b4aa74SDavid Sterba 			btrfs_release_path(path);
540976a05b35SChris Mason 			goto done;
541076a05b35SChris Mason 		}
541176a05b35SChris Mason 
54125cd57b2cSChris Mason 		if (!path->skip_locking) {
5413ac5887c8SJosef Bacik 			__btrfs_tree_read_lock(next, BTRFS_NESTING_RIGHT,
5414fd7ba1c1SJosef Bacik 					       path->recurse);
5415bd681513SChris Mason 			next_rw_lock = BTRFS_READ_LOCK;
5416bd681513SChris Mason 		}
5417d97e63b6SChris Mason 	}
54188e73f275SChris Mason 	ret = 0;
5419925baeddSChris Mason done:
5420f7c79f30SChris Mason 	unlock_up(path, 0, 1, 0, NULL);
54218e73f275SChris Mason 
54228e73f275SChris Mason 	return ret;
5423d97e63b6SChris Mason }
54240b86a832SChris Mason 
54253f157a2fSChris Mason /*
54263f157a2fSChris Mason  * this uses btrfs_prev_leaf to walk backwards in the tree, and keeps
54273f157a2fSChris Mason  * searching until it gets past min_objectid or finds an item of 'type'
54283f157a2fSChris Mason  *
54293f157a2fSChris Mason  * returns 0 if something is found, 1 if nothing was found and < 0 on error
54303f157a2fSChris Mason  */
54310b86a832SChris Mason int btrfs_previous_item(struct btrfs_root *root,
54320b86a832SChris Mason 			struct btrfs_path *path, u64 min_objectid,
54330b86a832SChris Mason 			int type)
54340b86a832SChris Mason {
54350b86a832SChris Mason 	struct btrfs_key found_key;
54360b86a832SChris Mason 	struct extent_buffer *leaf;
5437e02119d5SChris Mason 	u32 nritems;
54380b86a832SChris Mason 	int ret;
54390b86a832SChris Mason 
54400b86a832SChris Mason 	while (1) {
54410b86a832SChris Mason 		if (path->slots[0] == 0) {
54420b86a832SChris Mason 			ret = btrfs_prev_leaf(root, path);
54430b86a832SChris Mason 			if (ret != 0)
54440b86a832SChris Mason 				return ret;
54450b86a832SChris Mason 		} else {
54460b86a832SChris Mason 			path->slots[0]--;
54470b86a832SChris Mason 		}
54480b86a832SChris Mason 		leaf = path->nodes[0];
5449e02119d5SChris Mason 		nritems = btrfs_header_nritems(leaf);
5450e02119d5SChris Mason 		if (nritems == 0)
5451e02119d5SChris Mason 			return 1;
5452e02119d5SChris Mason 		if (path->slots[0] == nritems)
5453e02119d5SChris Mason 			path->slots[0]--;
5454e02119d5SChris Mason 
54550b86a832SChris Mason 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5456e02119d5SChris Mason 		if (found_key.objectid < min_objectid)
5457e02119d5SChris Mason 			break;
54580a4eefbbSYan Zheng 		if (found_key.type == type)
54590a4eefbbSYan Zheng 			return 0;
5460e02119d5SChris Mason 		if (found_key.objectid == min_objectid &&
5461e02119d5SChris Mason 		    found_key.type < type)
5462e02119d5SChris Mason 			break;
54630b86a832SChris Mason 	}
54640b86a832SChris Mason 	return 1;
54650b86a832SChris Mason }
5466ade2e0b3SWang Shilong 
5467ade2e0b3SWang Shilong /*
5468ade2e0b3SWang Shilong  * search in extent tree to find a previous Metadata/Data extent item with
5469ade2e0b3SWang Shilong  * min objecitd.
5470ade2e0b3SWang Shilong  *
5471ade2e0b3SWang Shilong  * returns 0 if something is found, 1 if nothing was found and < 0 on error
5472ade2e0b3SWang Shilong  */
5473ade2e0b3SWang Shilong int btrfs_previous_extent_item(struct btrfs_root *root,
5474ade2e0b3SWang Shilong 			struct btrfs_path *path, u64 min_objectid)
5475ade2e0b3SWang Shilong {
5476ade2e0b3SWang Shilong 	struct btrfs_key found_key;
5477ade2e0b3SWang Shilong 	struct extent_buffer *leaf;
5478ade2e0b3SWang Shilong 	u32 nritems;
5479ade2e0b3SWang Shilong 	int ret;
5480ade2e0b3SWang Shilong 
5481ade2e0b3SWang Shilong 	while (1) {
5482ade2e0b3SWang Shilong 		if (path->slots[0] == 0) {
5483ade2e0b3SWang Shilong 			ret = btrfs_prev_leaf(root, path);
5484ade2e0b3SWang Shilong 			if (ret != 0)
5485ade2e0b3SWang Shilong 				return ret;
5486ade2e0b3SWang Shilong 		} else {
5487ade2e0b3SWang Shilong 			path->slots[0]--;
5488ade2e0b3SWang Shilong 		}
5489ade2e0b3SWang Shilong 		leaf = path->nodes[0];
5490ade2e0b3SWang Shilong 		nritems = btrfs_header_nritems(leaf);
5491ade2e0b3SWang Shilong 		if (nritems == 0)
5492ade2e0b3SWang Shilong 			return 1;
5493ade2e0b3SWang Shilong 		if (path->slots[0] == nritems)
5494ade2e0b3SWang Shilong 			path->slots[0]--;
5495ade2e0b3SWang Shilong 
5496ade2e0b3SWang Shilong 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5497ade2e0b3SWang Shilong 		if (found_key.objectid < min_objectid)
5498ade2e0b3SWang Shilong 			break;
5499ade2e0b3SWang Shilong 		if (found_key.type == BTRFS_EXTENT_ITEM_KEY ||
5500ade2e0b3SWang Shilong 		    found_key.type == BTRFS_METADATA_ITEM_KEY)
5501ade2e0b3SWang Shilong 			return 0;
5502ade2e0b3SWang Shilong 		if (found_key.objectid == min_objectid &&
5503ade2e0b3SWang Shilong 		    found_key.type < BTRFS_EXTENT_ITEM_KEY)
5504ade2e0b3SWang Shilong 			break;
5505ade2e0b3SWang Shilong 	}
5506ade2e0b3SWang Shilong 	return 1;
5507ade2e0b3SWang Shilong }
5508