xref: /openbmc/linux/fs/btrfs/ctree.c (revision 572c83acdcdafeb04e70aa46be1fa539310be20c)
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) {
1067*572c83acSJosef Bacik 		btrfs_tree_unlock(cow);
1068*572c83acSJosef 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) {
1076*572c83acSJosef Bacik 			btrfs_tree_unlock(cow);
1077*572c83acSJosef 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) {
1110*572c83acSJosef Bacik 				btrfs_tree_unlock(cow);
1111*572c83acSJosef 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 
12819ec72677SJosef Bacik 	btrfs_set_path_blocking(path);
1282300aa896SDavid Sterba 	btrfs_set_lock_blocking_read(eb);
12839ec72677SJosef Bacik 
12845d9e75c4SJan Schmidt 	if (tm->op == MOD_LOG_KEY_REMOVE_WHILE_FREEING) {
12855d9e75c4SJan Schmidt 		BUG_ON(tm->slot != 0);
1286da17066cSJeff Mahoney 		eb_rewin = alloc_dummy_extent_buffer(fs_info, eb->start);
1287db7f3436SJosef Bacik 		if (!eb_rewin) {
12889ec72677SJosef Bacik 			btrfs_tree_read_unlock_blocking(eb);
1289db7f3436SJosef Bacik 			free_extent_buffer(eb);
1290db7f3436SJosef Bacik 			return NULL;
1291db7f3436SJosef Bacik 		}
12925d9e75c4SJan Schmidt 		btrfs_set_header_bytenr(eb_rewin, eb->start);
12935d9e75c4SJan Schmidt 		btrfs_set_header_backref_rev(eb_rewin,
12945d9e75c4SJan Schmidt 					     btrfs_header_backref_rev(eb));
12955d9e75c4SJan Schmidt 		btrfs_set_header_owner(eb_rewin, btrfs_header_owner(eb));
1296c3193108SJan Schmidt 		btrfs_set_header_level(eb_rewin, btrfs_header_level(eb));
12975d9e75c4SJan Schmidt 	} else {
12985d9e75c4SJan Schmidt 		eb_rewin = btrfs_clone_extent_buffer(eb);
1299db7f3436SJosef Bacik 		if (!eb_rewin) {
13009ec72677SJosef Bacik 			btrfs_tree_read_unlock_blocking(eb);
1301db7f3436SJosef Bacik 			free_extent_buffer(eb);
1302db7f3436SJosef Bacik 			return NULL;
1303db7f3436SJosef Bacik 		}
13045d9e75c4SJan Schmidt 	}
13055d9e75c4SJan Schmidt 
13069ec72677SJosef Bacik 	btrfs_tree_read_unlock_blocking(eb);
13075d9e75c4SJan Schmidt 	free_extent_buffer(eb);
13085d9e75c4SJan Schmidt 
1309d3beaa25SJosef Bacik 	btrfs_set_buffer_lockdep_class(btrfs_header_owner(eb_rewin),
1310d3beaa25SJosef Bacik 				       eb_rewin, btrfs_header_level(eb_rewin));
131147fb091fSJan Schmidt 	btrfs_tree_read_lock(eb_rewin);
1312f1ca7e98SJosef Bacik 	__tree_mod_log_rewind(fs_info, eb_rewin, time_seq, tm);
131357911b8bSJan Schmidt 	WARN_ON(btrfs_header_nritems(eb_rewin) >
1314da17066cSJeff Mahoney 		BTRFS_NODEPTRS_PER_BLOCK(fs_info));
13155d9e75c4SJan Schmidt 
13165d9e75c4SJan Schmidt 	return eb_rewin;
13175d9e75c4SJan Schmidt }
13185d9e75c4SJan Schmidt 
13198ba97a15SJan Schmidt /*
13208ba97a15SJan Schmidt  * get_old_root() rewinds the state of @root's root node to the given @time_seq
13218ba97a15SJan Schmidt  * value. If there are no changes, the current root->root_node is returned. If
13228ba97a15SJan Schmidt  * anything changed in between, there's a fresh buffer allocated on which the
13238ba97a15SJan Schmidt  * rewind operations are done. In any case, the returned buffer is read locked.
13248ba97a15SJan Schmidt  * Returns NULL on error (with no locks held).
13258ba97a15SJan Schmidt  */
13265d9e75c4SJan Schmidt static inline struct extent_buffer *
13275d9e75c4SJan Schmidt get_old_root(struct btrfs_root *root, u64 time_seq)
13285d9e75c4SJan Schmidt {
13290b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
13305d9e75c4SJan Schmidt 	struct tree_mod_elem *tm;
133130b0463aSJan Schmidt 	struct extent_buffer *eb = NULL;
133230b0463aSJan Schmidt 	struct extent_buffer *eb_root;
1333efad8a85SFilipe Manana 	u64 eb_root_owner = 0;
13347bfdcf7fSLiu Bo 	struct extent_buffer *old;
1335a95236d9SJan Schmidt 	struct tree_mod_root *old_root = NULL;
13364325edd0SChris Mason 	u64 old_generation = 0;
1337a95236d9SJan Schmidt 	u64 logical;
1338581c1760SQu Wenruo 	int level;
13395d9e75c4SJan Schmidt 
134030b0463aSJan Schmidt 	eb_root = btrfs_read_lock_root_node(root);
1341bcd24dabSDavid Sterba 	tm = __tree_mod_log_oldest_root(eb_root, time_seq);
13425d9e75c4SJan Schmidt 	if (!tm)
134330b0463aSJan Schmidt 		return eb_root;
13445d9e75c4SJan Schmidt 
1345a95236d9SJan Schmidt 	if (tm->op == MOD_LOG_ROOT_REPLACE) {
13465d9e75c4SJan Schmidt 		old_root = &tm->old_root;
13475d9e75c4SJan Schmidt 		old_generation = tm->generation;
1348a95236d9SJan Schmidt 		logical = old_root->logical;
1349581c1760SQu Wenruo 		level = old_root->level;
1350a95236d9SJan Schmidt 	} else {
135130b0463aSJan Schmidt 		logical = eb_root->start;
1352581c1760SQu Wenruo 		level = btrfs_header_level(eb_root);
1353a95236d9SJan Schmidt 	}
13545d9e75c4SJan Schmidt 
13550b246afaSJeff Mahoney 	tm = tree_mod_log_search(fs_info, logical, time_seq);
1356834328a8SJan Schmidt 	if (old_root && tm && tm->op != MOD_LOG_KEY_REMOVE_WHILE_FREEING) {
135730b0463aSJan Schmidt 		btrfs_tree_read_unlock(eb_root);
135830b0463aSJan Schmidt 		free_extent_buffer(eb_root);
1359581c1760SQu Wenruo 		old = read_tree_block(fs_info, logical, 0, level, NULL);
136064c043deSLiu Bo 		if (WARN_ON(IS_ERR(old) || !extent_buffer_uptodate(old))) {
136164c043deSLiu Bo 			if (!IS_ERR(old))
1362416bc658SJosef Bacik 				free_extent_buffer(old);
13630b246afaSJeff Mahoney 			btrfs_warn(fs_info,
13640b246afaSJeff Mahoney 				   "failed to read tree block %llu from get_old_root",
13650b246afaSJeff Mahoney 				   logical);
1366834328a8SJan Schmidt 		} else {
13677bfdcf7fSLiu Bo 			eb = btrfs_clone_extent_buffer(old);
13687bfdcf7fSLiu Bo 			free_extent_buffer(old);
1369834328a8SJan Schmidt 		}
1370834328a8SJan Schmidt 	} else if (old_root) {
1371efad8a85SFilipe Manana 		eb_root_owner = btrfs_header_owner(eb_root);
137230b0463aSJan Schmidt 		btrfs_tree_read_unlock(eb_root);
137330b0463aSJan Schmidt 		free_extent_buffer(eb_root);
13740b246afaSJeff Mahoney 		eb = alloc_dummy_extent_buffer(fs_info, logical);
1375834328a8SJan Schmidt 	} else {
1376300aa896SDavid Sterba 		btrfs_set_lock_blocking_read(eb_root);
137730b0463aSJan Schmidt 		eb = btrfs_clone_extent_buffer(eb_root);
13789ec72677SJosef Bacik 		btrfs_tree_read_unlock_blocking(eb_root);
137930b0463aSJan Schmidt 		free_extent_buffer(eb_root);
1380834328a8SJan Schmidt 	}
1381834328a8SJan Schmidt 
13828ba97a15SJan Schmidt 	if (!eb)
13838ba97a15SJan Schmidt 		return NULL;
1384a95236d9SJan Schmidt 	if (old_root) {
13855d9e75c4SJan Schmidt 		btrfs_set_header_bytenr(eb, eb->start);
13865d9e75c4SJan Schmidt 		btrfs_set_header_backref_rev(eb, BTRFS_MIXED_BACKREF_REV);
1387efad8a85SFilipe Manana 		btrfs_set_header_owner(eb, eb_root_owner);
13885d9e75c4SJan Schmidt 		btrfs_set_header_level(eb, old_root->level);
13895d9e75c4SJan Schmidt 		btrfs_set_header_generation(eb, old_generation);
1390a95236d9SJan Schmidt 	}
1391d3beaa25SJosef Bacik 	btrfs_set_buffer_lockdep_class(btrfs_header_owner(eb), eb,
1392d3beaa25SJosef Bacik 				       btrfs_header_level(eb));
1393d3beaa25SJosef Bacik 	btrfs_tree_read_lock(eb);
139428da9fb4SJan Schmidt 	if (tm)
13950b246afaSJeff Mahoney 		__tree_mod_log_rewind(fs_info, eb, time_seq, tm);
139628da9fb4SJan Schmidt 	else
139728da9fb4SJan Schmidt 		WARN_ON(btrfs_header_level(eb) != 0);
13980b246afaSJeff Mahoney 	WARN_ON(btrfs_header_nritems(eb) > BTRFS_NODEPTRS_PER_BLOCK(fs_info));
13995d9e75c4SJan Schmidt 
14005d9e75c4SJan Schmidt 	return eb;
14015d9e75c4SJan Schmidt }
14025d9e75c4SJan Schmidt 
14035b6602e7SJan Schmidt int btrfs_old_root_level(struct btrfs_root *root, u64 time_seq)
14045b6602e7SJan Schmidt {
14055b6602e7SJan Schmidt 	struct tree_mod_elem *tm;
14065b6602e7SJan Schmidt 	int level;
140730b0463aSJan Schmidt 	struct extent_buffer *eb_root = btrfs_root_node(root);
14085b6602e7SJan Schmidt 
1409bcd24dabSDavid Sterba 	tm = __tree_mod_log_oldest_root(eb_root, time_seq);
14105b6602e7SJan Schmidt 	if (tm && tm->op == MOD_LOG_ROOT_REPLACE) {
14115b6602e7SJan Schmidt 		level = tm->old_root.level;
14125b6602e7SJan Schmidt 	} else {
141330b0463aSJan Schmidt 		level = btrfs_header_level(eb_root);
14145b6602e7SJan Schmidt 	}
141530b0463aSJan Schmidt 	free_extent_buffer(eb_root);
14165b6602e7SJan Schmidt 
14175b6602e7SJan Schmidt 	return level;
14185b6602e7SJan Schmidt }
14195b6602e7SJan Schmidt 
14205d4f98a2SYan Zheng static inline int should_cow_block(struct btrfs_trans_handle *trans,
14215d4f98a2SYan Zheng 				   struct btrfs_root *root,
14225d4f98a2SYan Zheng 				   struct extent_buffer *buf)
14235d4f98a2SYan Zheng {
1424f5ee5c9aSJeff Mahoney 	if (btrfs_is_testing(root->fs_info))
1425faa2dbf0SJosef Bacik 		return 0;
1426fccb84c9SDavid Sterba 
1427d1980131SDavid Sterba 	/* Ensure we can see the FORCE_COW bit */
1428d1980131SDavid Sterba 	smp_mb__before_atomic();
1429f1ebcc74SLiu Bo 
1430f1ebcc74SLiu Bo 	/*
1431f1ebcc74SLiu Bo 	 * We do not need to cow a block if
1432f1ebcc74SLiu Bo 	 * 1) this block is not created or changed in this transaction;
1433f1ebcc74SLiu Bo 	 * 2) this block does not belong to TREE_RELOC tree;
1434f1ebcc74SLiu Bo 	 * 3) the root is not forced COW.
1435f1ebcc74SLiu Bo 	 *
1436f1ebcc74SLiu Bo 	 * What is forced COW:
143701327610SNicholas D Steeves 	 *    when we create snapshot during committing the transaction,
143852042d8eSAndrea Gelmini 	 *    after we've finished copying src root, we must COW the shared
1439f1ebcc74SLiu Bo 	 *    block to ensure the metadata consistency.
1440f1ebcc74SLiu Bo 	 */
14415d4f98a2SYan Zheng 	if (btrfs_header_generation(buf) == trans->transid &&
14425d4f98a2SYan Zheng 	    !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN) &&
14435d4f98a2SYan Zheng 	    !(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
1444f1ebcc74SLiu Bo 	      btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)) &&
144527cdeb70SMiao Xie 	    !test_bit(BTRFS_ROOT_FORCE_COW, &root->state))
14465d4f98a2SYan Zheng 		return 0;
14475d4f98a2SYan Zheng 	return 1;
14485d4f98a2SYan Zheng }
14495d4f98a2SYan Zheng 
1450d352ac68SChris Mason /*
1451d352ac68SChris Mason  * cows a single block, see __btrfs_cow_block for the real work.
145201327610SNicholas D Steeves  * This version of it has extra checks so that a block isn't COWed more than
1453d352ac68SChris Mason  * once per transaction, as long as it hasn't been written yet
1454d352ac68SChris Mason  */
1455d397712bSChris Mason noinline int btrfs_cow_block(struct btrfs_trans_handle *trans,
14565f39d397SChris Mason 		    struct btrfs_root *root, struct extent_buffer *buf,
14575f39d397SChris Mason 		    struct extent_buffer *parent, int parent_slot,
14589631e4ccSJosef Bacik 		    struct extent_buffer **cow_ret,
14599631e4ccSJosef Bacik 		    enum btrfs_lock_nesting nest)
146002217ed2SChris Mason {
14610b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
14626702ed49SChris Mason 	u64 search_start;
1463f510cfecSChris Mason 	int ret;
1464dc17ff8fSChris Mason 
146583354f07SJosef Bacik 	if (test_bit(BTRFS_ROOT_DELETING, &root->state))
146683354f07SJosef Bacik 		btrfs_err(fs_info,
146783354f07SJosef Bacik 			"COW'ing blocks on a fs root that's being dropped");
146883354f07SJosef Bacik 
14690b246afaSJeff Mahoney 	if (trans->transaction != fs_info->running_transaction)
147031b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "trans %llu running %llu\n",
1471c1c9ff7cSGeert Uytterhoeven 		       trans->transid,
14720b246afaSJeff Mahoney 		       fs_info->running_transaction->transid);
147331b1a2bdSJulia Lawall 
14740b246afaSJeff Mahoney 	if (trans->transid != fs_info->generation)
147531b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "trans %llu running %llu\n",
14760b246afaSJeff Mahoney 		       trans->transid, fs_info->generation);
1477dc17ff8fSChris Mason 
14785d4f98a2SYan Zheng 	if (!should_cow_block(trans, root, buf)) {
147964c12921SJeff Mahoney 		trans->dirty = true;
148002217ed2SChris Mason 		*cow_ret = buf;
148102217ed2SChris Mason 		return 0;
148202217ed2SChris Mason 	}
1483c487685dSChris Mason 
1484ee22184bSByongho Lee 	search_start = buf->start & ~((u64)SZ_1G - 1);
1485b4ce94deSChris Mason 
1486b4ce94deSChris Mason 	if (parent)
14878bead258SDavid Sterba 		btrfs_set_lock_blocking_write(parent);
14888bead258SDavid Sterba 	btrfs_set_lock_blocking_write(buf);
1489b4ce94deSChris Mason 
1490f616f5cdSQu Wenruo 	/*
1491f616f5cdSQu Wenruo 	 * Before CoWing this block for later modification, check if it's
1492f616f5cdSQu Wenruo 	 * the subtree root and do the delayed subtree trace if needed.
1493f616f5cdSQu Wenruo 	 *
1494f616f5cdSQu Wenruo 	 * Also We don't care about the error, as it's handled internally.
1495f616f5cdSQu Wenruo 	 */
1496f616f5cdSQu Wenruo 	btrfs_qgroup_trace_subtree_after_cow(trans, root, buf);
1497f510cfecSChris Mason 	ret = __btrfs_cow_block(trans, root, buf, parent,
14989631e4ccSJosef Bacik 				 parent_slot, cow_ret, search_start, 0, nest);
14991abe9b8aSliubo 
15001abe9b8aSliubo 	trace_btrfs_cow_block(root, buf, *cow_ret);
15011abe9b8aSliubo 
1502f510cfecSChris Mason 	return ret;
15032c90e5d6SChris Mason }
15046702ed49SChris Mason 
1505d352ac68SChris Mason /*
1506d352ac68SChris Mason  * helper function for defrag to decide if two blocks pointed to by a
1507d352ac68SChris Mason  * node are actually close by
1508d352ac68SChris Mason  */
15096b80053dSChris Mason static int close_blocks(u64 blocknr, u64 other, u32 blocksize)
15106702ed49SChris Mason {
15116b80053dSChris Mason 	if (blocknr < other && other - (blocknr + blocksize) < 32768)
15126702ed49SChris Mason 		return 1;
15136b80053dSChris Mason 	if (blocknr > other && blocknr - (other + blocksize) < 32768)
15146702ed49SChris Mason 		return 1;
151502217ed2SChris Mason 	return 0;
151602217ed2SChris Mason }
151702217ed2SChris Mason 
1518ce6ef5abSDavid Sterba #ifdef __LITTLE_ENDIAN
1519ce6ef5abSDavid Sterba 
1520ce6ef5abSDavid Sterba /*
1521ce6ef5abSDavid Sterba  * Compare two keys, on little-endian the disk order is same as CPU order and
1522ce6ef5abSDavid Sterba  * we can avoid the conversion.
1523ce6ef5abSDavid Sterba  */
1524ce6ef5abSDavid Sterba static int comp_keys(const struct btrfs_disk_key *disk_key,
1525ce6ef5abSDavid Sterba 		     const struct btrfs_key *k2)
1526ce6ef5abSDavid Sterba {
1527ce6ef5abSDavid Sterba 	const struct btrfs_key *k1 = (const struct btrfs_key *)disk_key;
1528ce6ef5abSDavid Sterba 
1529ce6ef5abSDavid Sterba 	return btrfs_comp_cpu_keys(k1, k2);
1530ce6ef5abSDavid Sterba }
1531ce6ef5abSDavid Sterba 
1532ce6ef5abSDavid Sterba #else
1533ce6ef5abSDavid Sterba 
1534081e9573SChris Mason /*
1535081e9573SChris Mason  * compare two keys in a memcmp fashion
1536081e9573SChris Mason  */
1537310712b2SOmar Sandoval static int comp_keys(const struct btrfs_disk_key *disk,
1538310712b2SOmar Sandoval 		     const struct btrfs_key *k2)
1539081e9573SChris Mason {
1540081e9573SChris Mason 	struct btrfs_key k1;
1541081e9573SChris Mason 
1542081e9573SChris Mason 	btrfs_disk_key_to_cpu(&k1, disk);
1543081e9573SChris Mason 
154420736abaSDiego Calleja 	return btrfs_comp_cpu_keys(&k1, k2);
1545081e9573SChris Mason }
1546ce6ef5abSDavid Sterba #endif
1547081e9573SChris Mason 
1548f3465ca4SJosef Bacik /*
1549f3465ca4SJosef Bacik  * same as comp_keys only with two btrfs_key's
1550f3465ca4SJosef Bacik  */
1551e1f60a65SDavid Sterba int __pure btrfs_comp_cpu_keys(const struct btrfs_key *k1, const struct btrfs_key *k2)
1552f3465ca4SJosef Bacik {
1553f3465ca4SJosef Bacik 	if (k1->objectid > k2->objectid)
1554f3465ca4SJosef Bacik 		return 1;
1555f3465ca4SJosef Bacik 	if (k1->objectid < k2->objectid)
1556f3465ca4SJosef Bacik 		return -1;
1557f3465ca4SJosef Bacik 	if (k1->type > k2->type)
1558f3465ca4SJosef Bacik 		return 1;
1559f3465ca4SJosef Bacik 	if (k1->type < k2->type)
1560f3465ca4SJosef Bacik 		return -1;
1561f3465ca4SJosef Bacik 	if (k1->offset > k2->offset)
1562f3465ca4SJosef Bacik 		return 1;
1563f3465ca4SJosef Bacik 	if (k1->offset < k2->offset)
1564f3465ca4SJosef Bacik 		return -1;
1565f3465ca4SJosef Bacik 	return 0;
1566f3465ca4SJosef Bacik }
1567081e9573SChris Mason 
1568d352ac68SChris Mason /*
1569d352ac68SChris Mason  * this is used by the defrag code to go through all the
1570d352ac68SChris Mason  * leaves pointed to by a node and reallocate them so that
1571d352ac68SChris Mason  * disk order is close to key order
1572d352ac68SChris Mason  */
15736702ed49SChris Mason int btrfs_realloc_node(struct btrfs_trans_handle *trans,
15745f39d397SChris Mason 		       struct btrfs_root *root, struct extent_buffer *parent,
1575de78b51aSEric Sandeen 		       int start_slot, u64 *last_ret,
1576a6b6e75eSChris Mason 		       struct btrfs_key *progress)
15776702ed49SChris Mason {
15780b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
15796b80053dSChris Mason 	struct extent_buffer *cur;
15806702ed49SChris Mason 	u64 blocknr;
1581ca7a79adSChris Mason 	u64 gen;
1582e9d0b13bSChris Mason 	u64 search_start = *last_ret;
1583e9d0b13bSChris Mason 	u64 last_block = 0;
15846702ed49SChris Mason 	u64 other;
15856702ed49SChris Mason 	u32 parent_nritems;
15866702ed49SChris Mason 	int end_slot;
15876702ed49SChris Mason 	int i;
15886702ed49SChris Mason 	int err = 0;
1589f2183bdeSChris Mason 	int parent_level;
15906b80053dSChris Mason 	int uptodate;
15916b80053dSChris Mason 	u32 blocksize;
1592081e9573SChris Mason 	int progress_passed = 0;
1593081e9573SChris Mason 	struct btrfs_disk_key disk_key;
15946702ed49SChris Mason 
15955708b959SChris Mason 	parent_level = btrfs_header_level(parent);
15965708b959SChris Mason 
15970b246afaSJeff Mahoney 	WARN_ON(trans->transaction != fs_info->running_transaction);
15980b246afaSJeff Mahoney 	WARN_ON(trans->transid != fs_info->generation);
159986479a04SChris Mason 
16006b80053dSChris Mason 	parent_nritems = btrfs_header_nritems(parent);
16010b246afaSJeff Mahoney 	blocksize = fs_info->nodesize;
16025dfe2be7SFilipe Manana 	end_slot = parent_nritems - 1;
16036702ed49SChris Mason 
16045dfe2be7SFilipe Manana 	if (parent_nritems <= 1)
16056702ed49SChris Mason 		return 0;
16066702ed49SChris Mason 
16078bead258SDavid Sterba 	btrfs_set_lock_blocking_write(parent);
1608b4ce94deSChris Mason 
16095dfe2be7SFilipe Manana 	for (i = start_slot; i <= end_slot; i++) {
1610581c1760SQu Wenruo 		struct btrfs_key first_key;
16116702ed49SChris Mason 		int close = 1;
1612a6b6e75eSChris Mason 
1613081e9573SChris Mason 		btrfs_node_key(parent, &disk_key, i);
1614081e9573SChris Mason 		if (!progress_passed && comp_keys(&disk_key, progress) < 0)
1615081e9573SChris Mason 			continue;
1616081e9573SChris Mason 
1617081e9573SChris Mason 		progress_passed = 1;
16186b80053dSChris Mason 		blocknr = btrfs_node_blockptr(parent, i);
1619ca7a79adSChris Mason 		gen = btrfs_node_ptr_generation(parent, i);
1620581c1760SQu Wenruo 		btrfs_node_key_to_cpu(parent, &first_key, i);
1621e9d0b13bSChris Mason 		if (last_block == 0)
1622e9d0b13bSChris Mason 			last_block = blocknr;
16235708b959SChris Mason 
16246702ed49SChris Mason 		if (i > 0) {
16256b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i - 1);
16266b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
16276702ed49SChris Mason 		}
16285dfe2be7SFilipe Manana 		if (!close && i < end_slot) {
16296b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i + 1);
16306b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
16316702ed49SChris Mason 		}
1632e9d0b13bSChris Mason 		if (close) {
1633e9d0b13bSChris Mason 			last_block = blocknr;
16346702ed49SChris Mason 			continue;
1635e9d0b13bSChris Mason 		}
16366702ed49SChris Mason 
16370b246afaSJeff Mahoney 		cur = find_extent_buffer(fs_info, blocknr);
16386b80053dSChris Mason 		if (cur)
1639b9fab919SChris Mason 			uptodate = btrfs_buffer_uptodate(cur, gen, 0);
16406b80053dSChris Mason 		else
16416b80053dSChris Mason 			uptodate = 0;
16425708b959SChris Mason 		if (!cur || !uptodate) {
16436b80053dSChris Mason 			if (!cur) {
1644581c1760SQu Wenruo 				cur = read_tree_block(fs_info, blocknr, gen,
1645581c1760SQu Wenruo 						      parent_level - 1,
1646581c1760SQu Wenruo 						      &first_key);
164764c043deSLiu Bo 				if (IS_ERR(cur)) {
164864c043deSLiu Bo 					return PTR_ERR(cur);
164964c043deSLiu Bo 				} else if (!extent_buffer_uptodate(cur)) {
1650416bc658SJosef Bacik 					free_extent_buffer(cur);
165197d9a8a4STsutomu Itoh 					return -EIO;
1652416bc658SJosef Bacik 				}
16536b80053dSChris Mason 			} else if (!uptodate) {
1654581c1760SQu Wenruo 				err = btrfs_read_buffer(cur, gen,
1655581c1760SQu Wenruo 						parent_level - 1,&first_key);
1656018642a1STsutomu Itoh 				if (err) {
1657018642a1STsutomu Itoh 					free_extent_buffer(cur);
1658018642a1STsutomu Itoh 					return err;
1659018642a1STsutomu Itoh 				}
16606702ed49SChris Mason 			}
1661f2183bdeSChris Mason 		}
1662e9d0b13bSChris Mason 		if (search_start == 0)
16636b80053dSChris Mason 			search_start = last_block;
1664e9d0b13bSChris Mason 
1665e7a84565SChris Mason 		btrfs_tree_lock(cur);
16668bead258SDavid Sterba 		btrfs_set_lock_blocking_write(cur);
16676b80053dSChris Mason 		err = __btrfs_cow_block(trans, root, cur, parent, i,
1668e7a84565SChris Mason 					&cur, search_start,
16696b80053dSChris Mason 					min(16 * blocksize,
16709631e4ccSJosef Bacik 					    (end_slot - i) * blocksize),
16719631e4ccSJosef Bacik 					BTRFS_NESTING_COW);
1672252c38f0SYan 		if (err) {
1673e7a84565SChris Mason 			btrfs_tree_unlock(cur);
16746b80053dSChris Mason 			free_extent_buffer(cur);
16756702ed49SChris Mason 			break;
1676252c38f0SYan 		}
1677e7a84565SChris Mason 		search_start = cur->start;
1678e7a84565SChris Mason 		last_block = cur->start;
1679f2183bdeSChris Mason 		*last_ret = search_start;
1680e7a84565SChris Mason 		btrfs_tree_unlock(cur);
1681e7a84565SChris Mason 		free_extent_buffer(cur);
16826702ed49SChris Mason 	}
16836702ed49SChris Mason 	return err;
16846702ed49SChris Mason }
16856702ed49SChris Mason 
168674123bd7SChris Mason /*
16875f39d397SChris Mason  * search for key in the extent_buffer.  The items start at offset p,
16885f39d397SChris Mason  * and they are item_size apart.  There are 'max' items in p.
16895f39d397SChris Mason  *
169074123bd7SChris Mason  * the slot in the array is returned via slot, and it points to
169174123bd7SChris Mason  * the place where you would insert key if it is not found in
169274123bd7SChris Mason  * the array.
169374123bd7SChris Mason  *
169474123bd7SChris Mason  * slot may point to max if the key is bigger than all of the keys
169574123bd7SChris Mason  */
1696e02119d5SChris Mason static noinline int generic_bin_search(struct extent_buffer *eb,
1697310712b2SOmar Sandoval 				       unsigned long p, int item_size,
1698310712b2SOmar Sandoval 				       const struct btrfs_key *key,
1699be0e5c09SChris Mason 				       int max, int *slot)
1700be0e5c09SChris Mason {
1701be0e5c09SChris Mason 	int low = 0;
1702be0e5c09SChris Mason 	int high = max;
1703be0e5c09SChris Mason 	int ret;
17045cd17f34SDavid Sterba 	const int key_size = sizeof(struct btrfs_disk_key);
1705be0e5c09SChris Mason 
17065e24e9afSLiu Bo 	if (low > high) {
17075e24e9afSLiu Bo 		btrfs_err(eb->fs_info,
17085e24e9afSLiu Bo 		 "%s: low (%d) > high (%d) eb %llu owner %llu level %d",
17095e24e9afSLiu Bo 			  __func__, low, high, eb->start,
17105e24e9afSLiu Bo 			  btrfs_header_owner(eb), btrfs_header_level(eb));
17115e24e9afSLiu Bo 		return -EINVAL;
17125e24e9afSLiu Bo 	}
17135e24e9afSLiu Bo 
1714be0e5c09SChris Mason 	while (low < high) {
17155cd17f34SDavid Sterba 		unsigned long oip;
17165cd17f34SDavid Sterba 		unsigned long offset;
17175cd17f34SDavid Sterba 		struct btrfs_disk_key *tmp;
17185cd17f34SDavid Sterba 		struct btrfs_disk_key unaligned;
17195cd17f34SDavid Sterba 		int mid;
17205cd17f34SDavid Sterba 
1721be0e5c09SChris Mason 		mid = (low + high) / 2;
17225f39d397SChris Mason 		offset = p + mid * item_size;
17235cd17f34SDavid Sterba 		oip = offset_in_page(offset);
17245f39d397SChris Mason 
17255cd17f34SDavid Sterba 		if (oip + key_size <= PAGE_SIZE) {
17265cd17f34SDavid Sterba 			const unsigned long idx = offset >> PAGE_SHIFT;
17275cd17f34SDavid Sterba 			char *kaddr = page_address(eb->pages[idx]);
1728934d375bSChris Mason 
17295cd17f34SDavid Sterba 			tmp = (struct btrfs_disk_key *)(kaddr + oip);
17305cd17f34SDavid Sterba 		} else {
17315cd17f34SDavid Sterba 			read_extent_buffer(eb, &unaligned, offset, key_size);
17325f39d397SChris Mason 			tmp = &unaligned;
1733479965d6SChris Mason 		}
1734479965d6SChris Mason 
1735be0e5c09SChris Mason 		ret = comp_keys(tmp, key);
1736be0e5c09SChris Mason 
1737be0e5c09SChris Mason 		if (ret < 0)
1738be0e5c09SChris Mason 			low = mid + 1;
1739be0e5c09SChris Mason 		else if (ret > 0)
1740be0e5c09SChris Mason 			high = mid;
1741be0e5c09SChris Mason 		else {
1742be0e5c09SChris Mason 			*slot = mid;
1743be0e5c09SChris Mason 			return 0;
1744be0e5c09SChris Mason 		}
1745be0e5c09SChris Mason 	}
1746be0e5c09SChris Mason 	*slot = low;
1747be0e5c09SChris Mason 	return 1;
1748be0e5c09SChris Mason }
1749be0e5c09SChris Mason 
175097571fd0SChris Mason /*
175197571fd0SChris Mason  * simple bin_search frontend that does the right thing for
175297571fd0SChris Mason  * leaves vs nodes
175397571fd0SChris Mason  */
1754a74b35ecSNikolay Borisov int btrfs_bin_search(struct extent_buffer *eb, const struct btrfs_key *key,
1755e3b83361SQu Wenruo 		     int *slot)
1756be0e5c09SChris Mason {
1757e3b83361SQu Wenruo 	if (btrfs_header_level(eb) == 0)
17585f39d397SChris Mason 		return generic_bin_search(eb,
17595f39d397SChris Mason 					  offsetof(struct btrfs_leaf, items),
17600783fcfcSChris Mason 					  sizeof(struct btrfs_item),
17615f39d397SChris Mason 					  key, btrfs_header_nritems(eb),
17627518a238SChris Mason 					  slot);
1763f775738fSWang Sheng-Hui 	else
17645f39d397SChris Mason 		return generic_bin_search(eb,
17655f39d397SChris Mason 					  offsetof(struct btrfs_node, ptrs),
1766123abc88SChris Mason 					  sizeof(struct btrfs_key_ptr),
17675f39d397SChris Mason 					  key, btrfs_header_nritems(eb),
17687518a238SChris Mason 					  slot);
1769be0e5c09SChris Mason }
1770be0e5c09SChris Mason 
1771f0486c68SYan, Zheng static void root_add_used(struct btrfs_root *root, u32 size)
1772f0486c68SYan, Zheng {
1773f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
1774f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
1775f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) + size);
1776f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
1777f0486c68SYan, Zheng }
1778f0486c68SYan, Zheng 
1779f0486c68SYan, Zheng static void root_sub_used(struct btrfs_root *root, u32 size)
1780f0486c68SYan, Zheng {
1781f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
1782f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
1783f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) - size);
1784f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
1785f0486c68SYan, Zheng }
1786f0486c68SYan, Zheng 
1787d352ac68SChris Mason /* given a node and slot number, this reads the blocks it points to.  The
1788d352ac68SChris Mason  * extent buffer is returned with a reference taken (but unlocked).
1789d352ac68SChris Mason  */
17904b231ae4SDavid Sterba struct extent_buffer *btrfs_read_node_slot(struct extent_buffer *parent,
17914b231ae4SDavid Sterba 					   int slot)
1792bb803951SChris Mason {
1793ca7a79adSChris Mason 	int level = btrfs_header_level(parent);
1794416bc658SJosef Bacik 	struct extent_buffer *eb;
1795581c1760SQu Wenruo 	struct btrfs_key first_key;
1796416bc658SJosef Bacik 
1797fb770ae4SLiu Bo 	if (slot < 0 || slot >= btrfs_header_nritems(parent))
1798fb770ae4SLiu Bo 		return ERR_PTR(-ENOENT);
1799ca7a79adSChris Mason 
1800ca7a79adSChris Mason 	BUG_ON(level == 0);
1801ca7a79adSChris Mason 
1802581c1760SQu Wenruo 	btrfs_node_key_to_cpu(parent, &first_key, slot);
1803d0d20b0fSDavid Sterba 	eb = read_tree_block(parent->fs_info, btrfs_node_blockptr(parent, slot),
1804581c1760SQu Wenruo 			     btrfs_node_ptr_generation(parent, slot),
1805581c1760SQu Wenruo 			     level - 1, &first_key);
1806fb770ae4SLiu Bo 	if (!IS_ERR(eb) && !extent_buffer_uptodate(eb)) {
1807416bc658SJosef Bacik 		free_extent_buffer(eb);
1808fb770ae4SLiu Bo 		eb = ERR_PTR(-EIO);
1809416bc658SJosef Bacik 	}
1810416bc658SJosef Bacik 
1811416bc658SJosef Bacik 	return eb;
1812bb803951SChris Mason }
1813bb803951SChris Mason 
1814d352ac68SChris Mason /*
1815d352ac68SChris Mason  * node level balancing, used to make sure nodes are in proper order for
1816d352ac68SChris Mason  * item deletion.  We balance from the top down, so we have to make sure
1817d352ac68SChris Mason  * that a deletion won't leave an node completely empty later on.
1818d352ac68SChris Mason  */
1819e02119d5SChris Mason static noinline int balance_level(struct btrfs_trans_handle *trans,
182098ed5174SChris Mason 			 struct btrfs_root *root,
182198ed5174SChris Mason 			 struct btrfs_path *path, int level)
1822bb803951SChris Mason {
18230b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
18245f39d397SChris Mason 	struct extent_buffer *right = NULL;
18255f39d397SChris Mason 	struct extent_buffer *mid;
18265f39d397SChris Mason 	struct extent_buffer *left = NULL;
18275f39d397SChris Mason 	struct extent_buffer *parent = NULL;
1828bb803951SChris Mason 	int ret = 0;
1829bb803951SChris Mason 	int wret;
1830bb803951SChris Mason 	int pslot;
1831bb803951SChris Mason 	int orig_slot = path->slots[level];
183279f95c82SChris Mason 	u64 orig_ptr;
1833bb803951SChris Mason 
183498e6b1ebSLiu Bo 	ASSERT(level > 0);
1835bb803951SChris Mason 
18365f39d397SChris Mason 	mid = path->nodes[level];
1837b4ce94deSChris Mason 
1838bd681513SChris Mason 	WARN_ON(path->locks[level] != BTRFS_WRITE_LOCK &&
1839bd681513SChris Mason 		path->locks[level] != BTRFS_WRITE_LOCK_BLOCKING);
18407bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
18417bb86316SChris Mason 
18421d4f8a0cSChris Mason 	orig_ptr = btrfs_node_blockptr(mid, orig_slot);
184379f95c82SChris Mason 
1844a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
18455f39d397SChris Mason 		parent = path->nodes[level + 1];
1846bb803951SChris Mason 		pslot = path->slots[level + 1];
1847a05a9bb1SLi Zefan 	}
1848bb803951SChris Mason 
184940689478SChris Mason 	/*
185040689478SChris Mason 	 * deal with the case where there is only one pointer in the root
185140689478SChris Mason 	 * by promoting the node below to a root
185240689478SChris Mason 	 */
18535f39d397SChris Mason 	if (!parent) {
18545f39d397SChris Mason 		struct extent_buffer *child;
1855bb803951SChris Mason 
18565f39d397SChris Mason 		if (btrfs_header_nritems(mid) != 1)
1857bb803951SChris Mason 			return 0;
1858bb803951SChris Mason 
1859bb803951SChris Mason 		/* promote the child to a root */
18604b231ae4SDavid Sterba 		child = btrfs_read_node_slot(mid, 0);
1861fb770ae4SLiu Bo 		if (IS_ERR(child)) {
1862fb770ae4SLiu Bo 			ret = PTR_ERR(child);
18630b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
1864305a26afSMark Fasheh 			goto enospc;
1865305a26afSMark Fasheh 		}
1866305a26afSMark Fasheh 
1867925baeddSChris Mason 		btrfs_tree_lock(child);
18688bead258SDavid Sterba 		btrfs_set_lock_blocking_write(child);
18699631e4ccSJosef Bacik 		ret = btrfs_cow_block(trans, root, child, mid, 0, &child,
18709631e4ccSJosef Bacik 				      BTRFS_NESTING_COW);
1871f0486c68SYan, Zheng 		if (ret) {
1872f0486c68SYan, Zheng 			btrfs_tree_unlock(child);
1873f0486c68SYan, Zheng 			free_extent_buffer(child);
1874f0486c68SYan, Zheng 			goto enospc;
1875f0486c68SYan, Zheng 		}
18762f375ab9SYan 
1877d9d19a01SDavid Sterba 		ret = tree_mod_log_insert_root(root->node, child, 1);
1878d9d19a01SDavid Sterba 		BUG_ON(ret < 0);
1879240f62c8SChris Mason 		rcu_assign_pointer(root->node, child);
1880925baeddSChris Mason 
18810b86a832SChris Mason 		add_root_to_dirty_list(root);
1882925baeddSChris Mason 		btrfs_tree_unlock(child);
1883b4ce94deSChris Mason 
1884925baeddSChris Mason 		path->locks[level] = 0;
1885bb803951SChris Mason 		path->nodes[level] = NULL;
18866a884d7dSDavid Sterba 		btrfs_clean_tree_block(mid);
1887925baeddSChris Mason 		btrfs_tree_unlock(mid);
1888bb803951SChris Mason 		/* once for the path */
18895f39d397SChris Mason 		free_extent_buffer(mid);
1890f0486c68SYan, Zheng 
1891f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
18925581a51aSJan Schmidt 		btrfs_free_tree_block(trans, root, mid, 0, 1);
1893bb803951SChris Mason 		/* once for the root ptr */
18943083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
1895f0486c68SYan, Zheng 		return 0;
1896bb803951SChris Mason 	}
18975f39d397SChris Mason 	if (btrfs_header_nritems(mid) >
18980b246afaSJeff Mahoney 	    BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 4)
1899bb803951SChris Mason 		return 0;
1900bb803951SChris Mason 
19014b231ae4SDavid Sterba 	left = btrfs_read_node_slot(parent, pslot - 1);
1902fb770ae4SLiu Bo 	if (IS_ERR(left))
1903fb770ae4SLiu Bo 		left = NULL;
1904fb770ae4SLiu Bo 
19055f39d397SChris Mason 	if (left) {
1906bf77467aSJosef Bacik 		__btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
19078bead258SDavid Sterba 		btrfs_set_lock_blocking_write(left);
19085f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, left,
19099631e4ccSJosef Bacik 				       parent, pslot - 1, &left,
1910bf59a5a2SJosef Bacik 				       BTRFS_NESTING_LEFT_COW);
191154aa1f4dSChris Mason 		if (wret) {
191254aa1f4dSChris Mason 			ret = wret;
191354aa1f4dSChris Mason 			goto enospc;
191454aa1f4dSChris Mason 		}
19152cc58cf2SChris Mason 	}
1916fb770ae4SLiu Bo 
19174b231ae4SDavid Sterba 	right = btrfs_read_node_slot(parent, pslot + 1);
1918fb770ae4SLiu Bo 	if (IS_ERR(right))
1919fb770ae4SLiu Bo 		right = NULL;
1920fb770ae4SLiu Bo 
19215f39d397SChris Mason 	if (right) {
1922bf77467aSJosef Bacik 		__btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
19238bead258SDavid Sterba 		btrfs_set_lock_blocking_write(right);
19245f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, right,
19259631e4ccSJosef Bacik 				       parent, pslot + 1, &right,
1926bf59a5a2SJosef Bacik 				       BTRFS_NESTING_RIGHT_COW);
19272cc58cf2SChris Mason 		if (wret) {
19282cc58cf2SChris Mason 			ret = wret;
19292cc58cf2SChris Mason 			goto enospc;
19302cc58cf2SChris Mason 		}
19312cc58cf2SChris Mason 	}
19322cc58cf2SChris Mason 
19332cc58cf2SChris Mason 	/* first, try to make some room in the middle buffer */
19345f39d397SChris Mason 	if (left) {
19355f39d397SChris Mason 		orig_slot += btrfs_header_nritems(left);
1936d30a668fSDavid Sterba 		wret = push_node_left(trans, left, mid, 1);
193779f95c82SChris Mason 		if (wret < 0)
193879f95c82SChris Mason 			ret = wret;
1939bb803951SChris Mason 	}
194079f95c82SChris Mason 
194179f95c82SChris Mason 	/*
194279f95c82SChris Mason 	 * then try to empty the right most buffer into the middle
194379f95c82SChris Mason 	 */
19445f39d397SChris Mason 	if (right) {
1945d30a668fSDavid Sterba 		wret = push_node_left(trans, mid, right, 1);
194654aa1f4dSChris Mason 		if (wret < 0 && wret != -ENOSPC)
194779f95c82SChris Mason 			ret = wret;
19485f39d397SChris Mason 		if (btrfs_header_nritems(right) == 0) {
19496a884d7dSDavid Sterba 			btrfs_clean_tree_block(right);
1950925baeddSChris Mason 			btrfs_tree_unlock(right);
1951afe5fea7STsutomu Itoh 			del_ptr(root, path, level + 1, pslot + 1);
1952f0486c68SYan, Zheng 			root_sub_used(root, right->len);
19535581a51aSJan Schmidt 			btrfs_free_tree_block(trans, root, right, 0, 1);
19543083ee2eSJosef Bacik 			free_extent_buffer_stale(right);
1955f0486c68SYan, Zheng 			right = NULL;
1956bb803951SChris Mason 		} else {
19575f39d397SChris Mason 			struct btrfs_disk_key right_key;
19585f39d397SChris Mason 			btrfs_node_key(right, &right_key, 0);
19590e82bcfeSDavid Sterba 			ret = tree_mod_log_insert_key(parent, pslot + 1,
19600e82bcfeSDavid Sterba 					MOD_LOG_KEY_REPLACE, GFP_NOFS);
19610e82bcfeSDavid Sterba 			BUG_ON(ret < 0);
19625f39d397SChris Mason 			btrfs_set_node_key(parent, &right_key, pslot + 1);
19635f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
1964bb803951SChris Mason 		}
1965bb803951SChris Mason 	}
19665f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 1) {
196779f95c82SChris Mason 		/*
196879f95c82SChris Mason 		 * we're not allowed to leave a node with one item in the
196979f95c82SChris Mason 		 * tree during a delete.  A deletion from lower in the tree
197079f95c82SChris Mason 		 * could try to delete the only pointer in this node.
197179f95c82SChris Mason 		 * So, pull some keys from the left.
197279f95c82SChris Mason 		 * There has to be a left pointer at this point because
197379f95c82SChris Mason 		 * otherwise we would have pulled some pointers from the
197479f95c82SChris Mason 		 * right
197579f95c82SChris Mason 		 */
1976305a26afSMark Fasheh 		if (!left) {
1977305a26afSMark Fasheh 			ret = -EROFS;
19780b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
1979305a26afSMark Fasheh 			goto enospc;
1980305a26afSMark Fasheh 		}
198155d32ed8SDavid Sterba 		wret = balance_node_right(trans, mid, left);
198254aa1f4dSChris Mason 		if (wret < 0) {
198379f95c82SChris Mason 			ret = wret;
198454aa1f4dSChris Mason 			goto enospc;
198554aa1f4dSChris Mason 		}
1986bce4eae9SChris Mason 		if (wret == 1) {
1987d30a668fSDavid Sterba 			wret = push_node_left(trans, left, mid, 1);
1988bce4eae9SChris Mason 			if (wret < 0)
1989bce4eae9SChris Mason 				ret = wret;
1990bce4eae9SChris Mason 		}
199179f95c82SChris Mason 		BUG_ON(wret == 1);
199279f95c82SChris Mason 	}
19935f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 0) {
19946a884d7dSDavid Sterba 		btrfs_clean_tree_block(mid);
1995925baeddSChris Mason 		btrfs_tree_unlock(mid);
1996afe5fea7STsutomu Itoh 		del_ptr(root, path, level + 1, pslot);
1997f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
19985581a51aSJan Schmidt 		btrfs_free_tree_block(trans, root, mid, 0, 1);
19993083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
2000f0486c68SYan, Zheng 		mid = NULL;
200179f95c82SChris Mason 	} else {
200279f95c82SChris Mason 		/* update the parent key to reflect our changes */
20035f39d397SChris Mason 		struct btrfs_disk_key mid_key;
20045f39d397SChris Mason 		btrfs_node_key(mid, &mid_key, 0);
20050e82bcfeSDavid Sterba 		ret = tree_mod_log_insert_key(parent, pslot,
20060e82bcfeSDavid Sterba 				MOD_LOG_KEY_REPLACE, GFP_NOFS);
20070e82bcfeSDavid Sterba 		BUG_ON(ret < 0);
20085f39d397SChris Mason 		btrfs_set_node_key(parent, &mid_key, pslot);
20095f39d397SChris Mason 		btrfs_mark_buffer_dirty(parent);
201079f95c82SChris Mason 	}
2011bb803951SChris Mason 
201279f95c82SChris Mason 	/* update the path */
20135f39d397SChris Mason 	if (left) {
20145f39d397SChris Mason 		if (btrfs_header_nritems(left) > orig_slot) {
201567439dadSDavid Sterba 			atomic_inc(&left->refs);
2016925baeddSChris Mason 			/* left was locked after cow */
20175f39d397SChris Mason 			path->nodes[level] = left;
2018bb803951SChris Mason 			path->slots[level + 1] -= 1;
2019bb803951SChris Mason 			path->slots[level] = orig_slot;
2020925baeddSChris Mason 			if (mid) {
2021925baeddSChris Mason 				btrfs_tree_unlock(mid);
20225f39d397SChris Mason 				free_extent_buffer(mid);
2023925baeddSChris Mason 			}
2024bb803951SChris Mason 		} else {
20255f39d397SChris Mason 			orig_slot -= btrfs_header_nritems(left);
2026bb803951SChris Mason 			path->slots[level] = orig_slot;
2027bb803951SChris Mason 		}
2028bb803951SChris Mason 	}
202979f95c82SChris Mason 	/* double check we haven't messed things up */
2030e20d96d6SChris Mason 	if (orig_ptr !=
20315f39d397SChris Mason 	    btrfs_node_blockptr(path->nodes[level], path->slots[level]))
203279f95c82SChris Mason 		BUG();
203354aa1f4dSChris Mason enospc:
2034925baeddSChris Mason 	if (right) {
2035925baeddSChris Mason 		btrfs_tree_unlock(right);
20365f39d397SChris Mason 		free_extent_buffer(right);
2037925baeddSChris Mason 	}
2038925baeddSChris Mason 	if (left) {
2039925baeddSChris Mason 		if (path->nodes[level] != left)
2040925baeddSChris Mason 			btrfs_tree_unlock(left);
20415f39d397SChris Mason 		free_extent_buffer(left);
2042925baeddSChris Mason 	}
2043bb803951SChris Mason 	return ret;
2044bb803951SChris Mason }
2045bb803951SChris Mason 
2046d352ac68SChris Mason /* Node balancing for insertion.  Here we only split or push nodes around
2047d352ac68SChris Mason  * when they are completely full.  This is also done top down, so we
2048d352ac68SChris Mason  * have to be pessimistic.
2049d352ac68SChris Mason  */
2050d397712bSChris Mason static noinline int push_nodes_for_insert(struct btrfs_trans_handle *trans,
2051e66f709bSChris Mason 					  struct btrfs_root *root,
2052e66f709bSChris Mason 					  struct btrfs_path *path, int level)
2053e66f709bSChris Mason {
20540b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
20555f39d397SChris Mason 	struct extent_buffer *right = NULL;
20565f39d397SChris Mason 	struct extent_buffer *mid;
20575f39d397SChris Mason 	struct extent_buffer *left = NULL;
20585f39d397SChris Mason 	struct extent_buffer *parent = NULL;
2059e66f709bSChris Mason 	int ret = 0;
2060e66f709bSChris Mason 	int wret;
2061e66f709bSChris Mason 	int pslot;
2062e66f709bSChris Mason 	int orig_slot = path->slots[level];
2063e66f709bSChris Mason 
2064e66f709bSChris Mason 	if (level == 0)
2065e66f709bSChris Mason 		return 1;
2066e66f709bSChris Mason 
20675f39d397SChris Mason 	mid = path->nodes[level];
20687bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
2069e66f709bSChris Mason 
2070a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
20715f39d397SChris Mason 		parent = path->nodes[level + 1];
2072e66f709bSChris Mason 		pslot = path->slots[level + 1];
2073a05a9bb1SLi Zefan 	}
2074e66f709bSChris Mason 
20755f39d397SChris Mason 	if (!parent)
2076e66f709bSChris Mason 		return 1;
2077e66f709bSChris Mason 
20784b231ae4SDavid Sterba 	left = btrfs_read_node_slot(parent, pslot - 1);
2079fb770ae4SLiu Bo 	if (IS_ERR(left))
2080fb770ae4SLiu Bo 		left = NULL;
2081e66f709bSChris Mason 
2082e66f709bSChris Mason 	/* first, try to make some room in the middle buffer */
20835f39d397SChris Mason 	if (left) {
2084e66f709bSChris Mason 		u32 left_nr;
2085925baeddSChris Mason 
2086bf77467aSJosef Bacik 		__btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
20878bead258SDavid Sterba 		btrfs_set_lock_blocking_write(left);
2088b4ce94deSChris Mason 
20895f39d397SChris Mason 		left_nr = btrfs_header_nritems(left);
20900b246afaSJeff Mahoney 		if (left_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
209133ade1f8SChris Mason 			wret = 1;
209233ade1f8SChris Mason 		} else {
20935f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, left, parent,
20949631e4ccSJosef Bacik 					      pslot - 1, &left,
2095bf59a5a2SJosef Bacik 					      BTRFS_NESTING_LEFT_COW);
209654aa1f4dSChris Mason 			if (ret)
209754aa1f4dSChris Mason 				wret = 1;
209854aa1f4dSChris Mason 			else {
2099d30a668fSDavid Sterba 				wret = push_node_left(trans, left, mid, 0);
210054aa1f4dSChris Mason 			}
210133ade1f8SChris Mason 		}
2102e66f709bSChris Mason 		if (wret < 0)
2103e66f709bSChris Mason 			ret = wret;
2104e66f709bSChris Mason 		if (wret == 0) {
21055f39d397SChris Mason 			struct btrfs_disk_key disk_key;
2106e66f709bSChris Mason 			orig_slot += left_nr;
21075f39d397SChris Mason 			btrfs_node_key(mid, &disk_key, 0);
21080e82bcfeSDavid Sterba 			ret = tree_mod_log_insert_key(parent, pslot,
21090e82bcfeSDavid Sterba 					MOD_LOG_KEY_REPLACE, GFP_NOFS);
21100e82bcfeSDavid Sterba 			BUG_ON(ret < 0);
21115f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot);
21125f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
21135f39d397SChris Mason 			if (btrfs_header_nritems(left) > orig_slot) {
21145f39d397SChris Mason 				path->nodes[level] = left;
2115e66f709bSChris Mason 				path->slots[level + 1] -= 1;
2116e66f709bSChris Mason 				path->slots[level] = orig_slot;
2117925baeddSChris Mason 				btrfs_tree_unlock(mid);
21185f39d397SChris Mason 				free_extent_buffer(mid);
2119e66f709bSChris Mason 			} else {
2120e66f709bSChris Mason 				orig_slot -=
21215f39d397SChris Mason 					btrfs_header_nritems(left);
2122e66f709bSChris Mason 				path->slots[level] = orig_slot;
2123925baeddSChris Mason 				btrfs_tree_unlock(left);
21245f39d397SChris Mason 				free_extent_buffer(left);
2125e66f709bSChris Mason 			}
2126e66f709bSChris Mason 			return 0;
2127e66f709bSChris Mason 		}
2128925baeddSChris Mason 		btrfs_tree_unlock(left);
21295f39d397SChris Mason 		free_extent_buffer(left);
2130e66f709bSChris Mason 	}
21314b231ae4SDavid Sterba 	right = btrfs_read_node_slot(parent, pslot + 1);
2132fb770ae4SLiu Bo 	if (IS_ERR(right))
2133fb770ae4SLiu Bo 		right = NULL;
2134e66f709bSChris Mason 
2135e66f709bSChris Mason 	/*
2136e66f709bSChris Mason 	 * then try to empty the right most buffer into the middle
2137e66f709bSChris Mason 	 */
21385f39d397SChris Mason 	if (right) {
213933ade1f8SChris Mason 		u32 right_nr;
2140b4ce94deSChris Mason 
2141bf77467aSJosef Bacik 		__btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
21428bead258SDavid Sterba 		btrfs_set_lock_blocking_write(right);
2143b4ce94deSChris Mason 
21445f39d397SChris Mason 		right_nr = btrfs_header_nritems(right);
21450b246afaSJeff Mahoney 		if (right_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
214633ade1f8SChris Mason 			wret = 1;
214733ade1f8SChris Mason 		} else {
21485f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, right,
21495f39d397SChris Mason 					      parent, pslot + 1,
2150bf59a5a2SJosef Bacik 					      &right, BTRFS_NESTING_RIGHT_COW);
215154aa1f4dSChris Mason 			if (ret)
215254aa1f4dSChris Mason 				wret = 1;
215354aa1f4dSChris Mason 			else {
215455d32ed8SDavid Sterba 				wret = balance_node_right(trans, right, mid);
215533ade1f8SChris Mason 			}
215654aa1f4dSChris Mason 		}
2157e66f709bSChris Mason 		if (wret < 0)
2158e66f709bSChris Mason 			ret = wret;
2159e66f709bSChris Mason 		if (wret == 0) {
21605f39d397SChris Mason 			struct btrfs_disk_key disk_key;
21615f39d397SChris Mason 
21625f39d397SChris Mason 			btrfs_node_key(right, &disk_key, 0);
21630e82bcfeSDavid Sterba 			ret = tree_mod_log_insert_key(parent, pslot + 1,
21640e82bcfeSDavid Sterba 					MOD_LOG_KEY_REPLACE, GFP_NOFS);
21650e82bcfeSDavid Sterba 			BUG_ON(ret < 0);
21665f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot + 1);
21675f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
21685f39d397SChris Mason 
21695f39d397SChris Mason 			if (btrfs_header_nritems(mid) <= orig_slot) {
21705f39d397SChris Mason 				path->nodes[level] = right;
2171e66f709bSChris Mason 				path->slots[level + 1] += 1;
2172e66f709bSChris Mason 				path->slots[level] = orig_slot -
21735f39d397SChris Mason 					btrfs_header_nritems(mid);
2174925baeddSChris Mason 				btrfs_tree_unlock(mid);
21755f39d397SChris Mason 				free_extent_buffer(mid);
2176e66f709bSChris Mason 			} else {
2177925baeddSChris Mason 				btrfs_tree_unlock(right);
21785f39d397SChris Mason 				free_extent_buffer(right);
2179e66f709bSChris Mason 			}
2180e66f709bSChris Mason 			return 0;
2181e66f709bSChris Mason 		}
2182925baeddSChris Mason 		btrfs_tree_unlock(right);
21835f39d397SChris Mason 		free_extent_buffer(right);
2184e66f709bSChris Mason 	}
2185e66f709bSChris Mason 	return 1;
2186e66f709bSChris Mason }
2187e66f709bSChris Mason 
218874123bd7SChris Mason /*
2189d352ac68SChris Mason  * readahead one full node of leaves, finding things that are close
2190d352ac68SChris Mason  * to the block in 'slot', and triggering ra on them.
21913c69faecSChris Mason  */
21922ff7e61eSJeff Mahoney static void reada_for_search(struct btrfs_fs_info *fs_info,
2193e02119d5SChris Mason 			     struct btrfs_path *path,
219401f46658SChris Mason 			     int level, int slot, u64 objectid)
21953c69faecSChris Mason {
21965f39d397SChris Mason 	struct extent_buffer *node;
219701f46658SChris Mason 	struct btrfs_disk_key disk_key;
21983c69faecSChris Mason 	u32 nritems;
21993c69faecSChris Mason 	u64 search;
2200a7175319SChris Mason 	u64 target;
22016b80053dSChris Mason 	u64 nread = 0;
22025f39d397SChris Mason 	struct extent_buffer *eb;
22036b80053dSChris Mason 	u32 nr;
22046b80053dSChris Mason 	u32 blocksize;
22056b80053dSChris Mason 	u32 nscan = 0;
2206db94535dSChris Mason 
2207a6b6e75eSChris Mason 	if (level != 1)
22083c69faecSChris Mason 		return;
22093c69faecSChris Mason 
22106702ed49SChris Mason 	if (!path->nodes[level])
22116702ed49SChris Mason 		return;
22126702ed49SChris Mason 
22135f39d397SChris Mason 	node = path->nodes[level];
2214925baeddSChris Mason 
22153c69faecSChris Mason 	search = btrfs_node_blockptr(node, slot);
22160b246afaSJeff Mahoney 	blocksize = fs_info->nodesize;
22170b246afaSJeff Mahoney 	eb = find_extent_buffer(fs_info, search);
22185f39d397SChris Mason 	if (eb) {
22195f39d397SChris Mason 		free_extent_buffer(eb);
22203c69faecSChris Mason 		return;
22213c69faecSChris Mason 	}
22223c69faecSChris Mason 
2223a7175319SChris Mason 	target = search;
22246b80053dSChris Mason 
22255f39d397SChris Mason 	nritems = btrfs_header_nritems(node);
22266b80053dSChris Mason 	nr = slot;
222725b8b936SJosef Bacik 
22283c69faecSChris Mason 	while (1) {
2229e4058b54SDavid Sterba 		if (path->reada == READA_BACK) {
22306b80053dSChris Mason 			if (nr == 0)
22313c69faecSChris Mason 				break;
22326b80053dSChris Mason 			nr--;
2233e4058b54SDavid Sterba 		} else if (path->reada == READA_FORWARD) {
22346b80053dSChris Mason 			nr++;
22356b80053dSChris Mason 			if (nr >= nritems)
22366b80053dSChris Mason 				break;
22373c69faecSChris Mason 		}
2238e4058b54SDavid Sterba 		if (path->reada == READA_BACK && objectid) {
223901f46658SChris Mason 			btrfs_node_key(node, &disk_key, nr);
224001f46658SChris Mason 			if (btrfs_disk_key_objectid(&disk_key) != objectid)
224101f46658SChris Mason 				break;
224201f46658SChris Mason 		}
22436b80053dSChris Mason 		search = btrfs_node_blockptr(node, nr);
2244a7175319SChris Mason 		if ((search <= target && target - search <= 65536) ||
2245a7175319SChris Mason 		    (search > target && search - target <= 65536)) {
22462ff7e61eSJeff Mahoney 			readahead_tree_block(fs_info, search);
22476b80053dSChris Mason 			nread += blocksize;
22483c69faecSChris Mason 		}
22496b80053dSChris Mason 		nscan++;
2250a7175319SChris Mason 		if ((nread > 65536 || nscan > 32))
22516b80053dSChris Mason 			break;
22523c69faecSChris Mason 	}
22533c69faecSChris Mason }
2254925baeddSChris Mason 
22552ff7e61eSJeff Mahoney static noinline void reada_for_balance(struct btrfs_fs_info *fs_info,
2256b4ce94deSChris Mason 				       struct btrfs_path *path, int level)
2257b4ce94deSChris Mason {
2258b4ce94deSChris Mason 	int slot;
2259b4ce94deSChris Mason 	int nritems;
2260b4ce94deSChris Mason 	struct extent_buffer *parent;
2261b4ce94deSChris Mason 	struct extent_buffer *eb;
2262b4ce94deSChris Mason 	u64 gen;
2263b4ce94deSChris Mason 	u64 block1 = 0;
2264b4ce94deSChris Mason 	u64 block2 = 0;
2265b4ce94deSChris Mason 
22668c594ea8SChris Mason 	parent = path->nodes[level + 1];
2267b4ce94deSChris Mason 	if (!parent)
22680b08851fSJosef Bacik 		return;
2269b4ce94deSChris Mason 
2270b4ce94deSChris Mason 	nritems = btrfs_header_nritems(parent);
22718c594ea8SChris Mason 	slot = path->slots[level + 1];
2272b4ce94deSChris Mason 
2273b4ce94deSChris Mason 	if (slot > 0) {
2274b4ce94deSChris Mason 		block1 = btrfs_node_blockptr(parent, slot - 1);
2275b4ce94deSChris Mason 		gen = btrfs_node_ptr_generation(parent, slot - 1);
22760b246afaSJeff Mahoney 		eb = find_extent_buffer(fs_info, block1);
2277b9fab919SChris Mason 		/*
2278b9fab919SChris Mason 		 * if we get -eagain from btrfs_buffer_uptodate, we
2279b9fab919SChris Mason 		 * don't want to return eagain here.  That will loop
2280b9fab919SChris Mason 		 * forever
2281b9fab919SChris Mason 		 */
2282b9fab919SChris Mason 		if (eb && btrfs_buffer_uptodate(eb, gen, 1) != 0)
2283b4ce94deSChris Mason 			block1 = 0;
2284b4ce94deSChris Mason 		free_extent_buffer(eb);
2285b4ce94deSChris Mason 	}
22868c594ea8SChris Mason 	if (slot + 1 < nritems) {
2287b4ce94deSChris Mason 		block2 = btrfs_node_blockptr(parent, slot + 1);
2288b4ce94deSChris Mason 		gen = btrfs_node_ptr_generation(parent, slot + 1);
22890b246afaSJeff Mahoney 		eb = find_extent_buffer(fs_info, block2);
2290b9fab919SChris Mason 		if (eb && btrfs_buffer_uptodate(eb, gen, 1) != 0)
2291b4ce94deSChris Mason 			block2 = 0;
2292b4ce94deSChris Mason 		free_extent_buffer(eb);
2293b4ce94deSChris Mason 	}
22948c594ea8SChris Mason 
2295b4ce94deSChris Mason 	if (block1)
22962ff7e61eSJeff Mahoney 		readahead_tree_block(fs_info, block1);
2297b4ce94deSChris Mason 	if (block2)
22982ff7e61eSJeff Mahoney 		readahead_tree_block(fs_info, block2);
2299b4ce94deSChris Mason }
2300b4ce94deSChris Mason 
2301b4ce94deSChris Mason 
2302b4ce94deSChris Mason /*
2303d397712bSChris Mason  * when we walk down the tree, it is usually safe to unlock the higher layers
2304d397712bSChris Mason  * in the tree.  The exceptions are when our path goes through slot 0, because
2305d397712bSChris Mason  * operations on the tree might require changing key pointers higher up in the
2306d397712bSChris Mason  * tree.
2307d352ac68SChris Mason  *
2308d397712bSChris Mason  * callers might also have set path->keep_locks, which tells this code to keep
2309d397712bSChris Mason  * the lock if the path points to the last slot in the block.  This is part of
2310d397712bSChris Mason  * walking through the tree, and selecting the next slot in the higher block.
2311d352ac68SChris Mason  *
2312d397712bSChris Mason  * lowest_unlock sets the lowest level in the tree we're allowed to unlock.  so
2313d397712bSChris Mason  * if lowest_unlock is 1, level 0 won't be unlocked
2314d352ac68SChris Mason  */
2315e02119d5SChris Mason static noinline void unlock_up(struct btrfs_path *path, int level,
2316f7c79f30SChris Mason 			       int lowest_unlock, int min_write_lock_level,
2317f7c79f30SChris Mason 			       int *write_lock_level)
2318925baeddSChris Mason {
2319925baeddSChris Mason 	int i;
2320925baeddSChris Mason 	int skip_level = level;
2321051e1b9fSChris Mason 	int no_skips = 0;
2322925baeddSChris Mason 	struct extent_buffer *t;
2323925baeddSChris Mason 
2324925baeddSChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2325925baeddSChris Mason 		if (!path->nodes[i])
2326925baeddSChris Mason 			break;
2327925baeddSChris Mason 		if (!path->locks[i])
2328925baeddSChris Mason 			break;
2329051e1b9fSChris Mason 		if (!no_skips && path->slots[i] == 0) {
2330925baeddSChris Mason 			skip_level = i + 1;
2331925baeddSChris Mason 			continue;
2332925baeddSChris Mason 		}
2333051e1b9fSChris Mason 		if (!no_skips && path->keep_locks) {
2334925baeddSChris Mason 			u32 nritems;
2335925baeddSChris Mason 			t = path->nodes[i];
2336925baeddSChris Mason 			nritems = btrfs_header_nritems(t);
2337051e1b9fSChris Mason 			if (nritems < 1 || path->slots[i] >= nritems - 1) {
2338925baeddSChris Mason 				skip_level = i + 1;
2339925baeddSChris Mason 				continue;
2340925baeddSChris Mason 			}
2341925baeddSChris Mason 		}
2342051e1b9fSChris Mason 		if (skip_level < i && i >= lowest_unlock)
2343051e1b9fSChris Mason 			no_skips = 1;
2344051e1b9fSChris Mason 
2345925baeddSChris Mason 		t = path->nodes[i];
2346d80bb3f9SLiu Bo 		if (i >= lowest_unlock && i > skip_level) {
2347bd681513SChris Mason 			btrfs_tree_unlock_rw(t, path->locks[i]);
2348925baeddSChris Mason 			path->locks[i] = 0;
2349f7c79f30SChris Mason 			if (write_lock_level &&
2350f7c79f30SChris Mason 			    i > min_write_lock_level &&
2351f7c79f30SChris Mason 			    i <= *write_lock_level) {
2352f7c79f30SChris Mason 				*write_lock_level = i - 1;
2353f7c79f30SChris Mason 			}
2354925baeddSChris Mason 		}
2355925baeddSChris Mason 	}
2356925baeddSChris Mason }
2357925baeddSChris Mason 
23583c69faecSChris Mason /*
2359c8c42864SChris Mason  * helper function for btrfs_search_slot.  The goal is to find a block
2360c8c42864SChris Mason  * in cache without setting the path to blocking.  If we find the block
2361c8c42864SChris Mason  * we return zero and the path is unchanged.
2362c8c42864SChris Mason  *
2363c8c42864SChris Mason  * If we can't find the block, we set the path blocking and do some
2364c8c42864SChris Mason  * reada.  -EAGAIN is returned and the search must be repeated.
2365c8c42864SChris Mason  */
2366c8c42864SChris Mason static int
2367d07b8528SLiu Bo read_block_for_search(struct btrfs_root *root, struct btrfs_path *p,
2368c8c42864SChris Mason 		      struct extent_buffer **eb_ret, int level, int slot,
2369cda79c54SDavid Sterba 		      const struct btrfs_key *key)
2370c8c42864SChris Mason {
23710b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
2372c8c42864SChris Mason 	u64 blocknr;
2373c8c42864SChris Mason 	u64 gen;
2374c8c42864SChris Mason 	struct extent_buffer *tmp;
2375581c1760SQu Wenruo 	struct btrfs_key first_key;
237676a05b35SChris Mason 	int ret;
2377581c1760SQu Wenruo 	int parent_level;
2378c8c42864SChris Mason 
2379213ff4b7SNikolay Borisov 	blocknr = btrfs_node_blockptr(*eb_ret, slot);
2380213ff4b7SNikolay Borisov 	gen = btrfs_node_ptr_generation(*eb_ret, slot);
2381213ff4b7SNikolay Borisov 	parent_level = btrfs_header_level(*eb_ret);
2382213ff4b7SNikolay Borisov 	btrfs_node_key_to_cpu(*eb_ret, &first_key, slot);
2383c8c42864SChris Mason 
23840b246afaSJeff Mahoney 	tmp = find_extent_buffer(fs_info, blocknr);
2385cb44921aSChris Mason 	if (tmp) {
2386b9fab919SChris Mason 		/* first we do an atomic uptodate check */
2387b9fab919SChris Mason 		if (btrfs_buffer_uptodate(tmp, gen, 1) > 0) {
2388448de471SQu Wenruo 			/*
2389448de471SQu Wenruo 			 * Do extra check for first_key, eb can be stale due to
2390448de471SQu Wenruo 			 * being cached, read from scrub, or have multiple
2391448de471SQu Wenruo 			 * parents (shared tree blocks).
2392448de471SQu Wenruo 			 */
2393e064d5e9SDavid Sterba 			if (btrfs_verify_level_key(tmp,
2394448de471SQu Wenruo 					parent_level - 1, &first_key, gen)) {
2395448de471SQu Wenruo 				free_extent_buffer(tmp);
2396448de471SQu Wenruo 				return -EUCLEAN;
2397448de471SQu Wenruo 			}
2398c8c42864SChris Mason 			*eb_ret = tmp;
2399c8c42864SChris Mason 			return 0;
2400c8c42864SChris Mason 		}
2401bdf7c00eSJosef Bacik 
2402cb44921aSChris Mason 		/* the pages were up to date, but we failed
2403cb44921aSChris Mason 		 * the generation number check.  Do a full
2404cb44921aSChris Mason 		 * read for the generation number that is correct.
2405cb44921aSChris Mason 		 * We must do this without dropping locks so
2406cb44921aSChris Mason 		 * we can trust our generation number
2407cb44921aSChris Mason 		 */
2408bd681513SChris Mason 		btrfs_set_path_blocking(p);
2409bd681513SChris Mason 
2410b9fab919SChris Mason 		/* now we're allowed to do a blocking uptodate check */
2411581c1760SQu Wenruo 		ret = btrfs_read_buffer(tmp, gen, parent_level - 1, &first_key);
2412bdf7c00eSJosef Bacik 		if (!ret) {
2413cb44921aSChris Mason 			*eb_ret = tmp;
2414cb44921aSChris Mason 			return 0;
2415cb44921aSChris Mason 		}
2416cb44921aSChris Mason 		free_extent_buffer(tmp);
2417b3b4aa74SDavid Sterba 		btrfs_release_path(p);
2418cb44921aSChris Mason 		return -EIO;
2419cb44921aSChris Mason 	}
2420c8c42864SChris Mason 
2421c8c42864SChris Mason 	/*
2422c8c42864SChris Mason 	 * reduce lock contention at high levels
2423c8c42864SChris Mason 	 * of the btree by dropping locks before
242476a05b35SChris Mason 	 * we read.  Don't release the lock on the current
242576a05b35SChris Mason 	 * level because we need to walk this node to figure
242676a05b35SChris Mason 	 * out which blocks to read.
2427c8c42864SChris Mason 	 */
24288c594ea8SChris Mason 	btrfs_unlock_up_safe(p, level + 1);
24298c594ea8SChris Mason 	btrfs_set_path_blocking(p);
24308c594ea8SChris Mason 
2431e4058b54SDavid Sterba 	if (p->reada != READA_NONE)
24322ff7e61eSJeff Mahoney 		reada_for_search(fs_info, p, level, slot, key->objectid);
2433c8c42864SChris Mason 
243476a05b35SChris Mason 	ret = -EAGAIN;
243502a3307aSLiu Bo 	tmp = read_tree_block(fs_info, blocknr, gen, parent_level - 1,
2436581c1760SQu Wenruo 			      &first_key);
243764c043deSLiu Bo 	if (!IS_ERR(tmp)) {
243876a05b35SChris Mason 		/*
243976a05b35SChris Mason 		 * If the read above didn't mark this buffer up to date,
244076a05b35SChris Mason 		 * it will never end up being up to date.  Set ret to EIO now
244176a05b35SChris Mason 		 * and give up so that our caller doesn't loop forever
244276a05b35SChris Mason 		 * on our EAGAINs.
244376a05b35SChris Mason 		 */
2444e6a1d6fdSLiu Bo 		if (!extent_buffer_uptodate(tmp))
244576a05b35SChris Mason 			ret = -EIO;
2446c8c42864SChris Mason 		free_extent_buffer(tmp);
2447c871b0f2SLiu Bo 	} else {
2448c871b0f2SLiu Bo 		ret = PTR_ERR(tmp);
244976a05b35SChris Mason 	}
245002a3307aSLiu Bo 
245102a3307aSLiu Bo 	btrfs_release_path(p);
245276a05b35SChris Mason 	return ret;
2453c8c42864SChris Mason }
2454c8c42864SChris Mason 
2455c8c42864SChris Mason /*
2456c8c42864SChris Mason  * helper function for btrfs_search_slot.  This does all of the checks
2457c8c42864SChris Mason  * for node-level blocks and does any balancing required based on
2458c8c42864SChris Mason  * the ins_len.
2459c8c42864SChris Mason  *
2460c8c42864SChris Mason  * If no extra work was required, zero is returned.  If we had to
2461c8c42864SChris Mason  * drop the path, -EAGAIN is returned and btrfs_search_slot must
2462c8c42864SChris Mason  * start over
2463c8c42864SChris Mason  */
2464c8c42864SChris Mason static int
2465c8c42864SChris Mason setup_nodes_for_search(struct btrfs_trans_handle *trans,
2466c8c42864SChris Mason 		       struct btrfs_root *root, struct btrfs_path *p,
2467bd681513SChris Mason 		       struct extent_buffer *b, int level, int ins_len,
2468bd681513SChris Mason 		       int *write_lock_level)
2469c8c42864SChris Mason {
24700b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
2471c8c42864SChris Mason 	int ret;
24720b246afaSJeff Mahoney 
2473c8c42864SChris Mason 	if ((p->search_for_split || ins_len > 0) && btrfs_header_nritems(b) >=
24740b246afaSJeff Mahoney 	    BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3) {
2475c8c42864SChris Mason 		int sret;
2476c8c42864SChris Mason 
2477bd681513SChris Mason 		if (*write_lock_level < level + 1) {
2478bd681513SChris Mason 			*write_lock_level = level + 1;
2479bd681513SChris Mason 			btrfs_release_path(p);
2480bd681513SChris Mason 			goto again;
2481bd681513SChris Mason 		}
2482bd681513SChris Mason 
2483c8c42864SChris Mason 		btrfs_set_path_blocking(p);
24842ff7e61eSJeff Mahoney 		reada_for_balance(fs_info, p, level);
2485c8c42864SChris Mason 		sret = split_node(trans, root, p, level);
2486c8c42864SChris Mason 
2487c8c42864SChris Mason 		BUG_ON(sret > 0);
2488c8c42864SChris Mason 		if (sret) {
2489c8c42864SChris Mason 			ret = sret;
2490c8c42864SChris Mason 			goto done;
2491c8c42864SChris Mason 		}
2492c8c42864SChris Mason 		b = p->nodes[level];
2493c8c42864SChris Mason 	} else if (ins_len < 0 && btrfs_header_nritems(b) <
24940b246afaSJeff Mahoney 		   BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 2) {
2495c8c42864SChris Mason 		int sret;
2496c8c42864SChris Mason 
2497bd681513SChris Mason 		if (*write_lock_level < level + 1) {
2498bd681513SChris Mason 			*write_lock_level = level + 1;
2499bd681513SChris Mason 			btrfs_release_path(p);
2500bd681513SChris Mason 			goto again;
2501bd681513SChris Mason 		}
2502bd681513SChris Mason 
2503c8c42864SChris Mason 		btrfs_set_path_blocking(p);
25042ff7e61eSJeff Mahoney 		reada_for_balance(fs_info, p, level);
2505c8c42864SChris Mason 		sret = balance_level(trans, root, p, level);
2506c8c42864SChris Mason 
2507c8c42864SChris Mason 		if (sret) {
2508c8c42864SChris Mason 			ret = sret;
2509c8c42864SChris Mason 			goto done;
2510c8c42864SChris Mason 		}
2511c8c42864SChris Mason 		b = p->nodes[level];
2512c8c42864SChris Mason 		if (!b) {
2513b3b4aa74SDavid Sterba 			btrfs_release_path(p);
2514c8c42864SChris Mason 			goto again;
2515c8c42864SChris Mason 		}
2516c8c42864SChris Mason 		BUG_ON(btrfs_header_nritems(b) == 1);
2517c8c42864SChris Mason 	}
2518c8c42864SChris Mason 	return 0;
2519c8c42864SChris Mason 
2520c8c42864SChris Mason again:
2521c8c42864SChris Mason 	ret = -EAGAIN;
2522c8c42864SChris Mason done:
2523c8c42864SChris Mason 	return ret;
2524c8c42864SChris Mason }
2525c8c42864SChris Mason 
2526381cf658SDavid Sterba int btrfs_find_item(struct btrfs_root *fs_root, struct btrfs_path *path,
2527e33d5c3dSKelley Nielsen 		u64 iobjectid, u64 ioff, u8 key_type,
2528e33d5c3dSKelley Nielsen 		struct btrfs_key *found_key)
2529e33d5c3dSKelley Nielsen {
2530e33d5c3dSKelley Nielsen 	int ret;
2531e33d5c3dSKelley Nielsen 	struct btrfs_key key;
2532e33d5c3dSKelley Nielsen 	struct extent_buffer *eb;
2533381cf658SDavid Sterba 
2534381cf658SDavid Sterba 	ASSERT(path);
25351d4c08e0SDavid Sterba 	ASSERT(found_key);
2536e33d5c3dSKelley Nielsen 
2537e33d5c3dSKelley Nielsen 	key.type = key_type;
2538e33d5c3dSKelley Nielsen 	key.objectid = iobjectid;
2539e33d5c3dSKelley Nielsen 	key.offset = ioff;
2540e33d5c3dSKelley Nielsen 
2541e33d5c3dSKelley Nielsen 	ret = btrfs_search_slot(NULL, fs_root, &key, path, 0, 0);
25421d4c08e0SDavid Sterba 	if (ret < 0)
2543e33d5c3dSKelley Nielsen 		return ret;
2544e33d5c3dSKelley Nielsen 
2545e33d5c3dSKelley Nielsen 	eb = path->nodes[0];
2546e33d5c3dSKelley Nielsen 	if (ret && path->slots[0] >= btrfs_header_nritems(eb)) {
2547e33d5c3dSKelley Nielsen 		ret = btrfs_next_leaf(fs_root, path);
2548e33d5c3dSKelley Nielsen 		if (ret)
2549e33d5c3dSKelley Nielsen 			return ret;
2550e33d5c3dSKelley Nielsen 		eb = path->nodes[0];
2551e33d5c3dSKelley Nielsen 	}
2552e33d5c3dSKelley Nielsen 
2553e33d5c3dSKelley Nielsen 	btrfs_item_key_to_cpu(eb, found_key, path->slots[0]);
2554e33d5c3dSKelley Nielsen 	if (found_key->type != key.type ||
2555e33d5c3dSKelley Nielsen 			found_key->objectid != key.objectid)
2556e33d5c3dSKelley Nielsen 		return 1;
2557e33d5c3dSKelley Nielsen 
2558e33d5c3dSKelley Nielsen 	return 0;
2559e33d5c3dSKelley Nielsen }
2560e33d5c3dSKelley Nielsen 
25611fc28d8eSLiu Bo static struct extent_buffer *btrfs_search_slot_get_root(struct btrfs_root *root,
25621fc28d8eSLiu Bo 							struct btrfs_path *p,
25631fc28d8eSLiu Bo 							int write_lock_level)
25641fc28d8eSLiu Bo {
25651fc28d8eSLiu Bo 	struct btrfs_fs_info *fs_info = root->fs_info;
25661fc28d8eSLiu Bo 	struct extent_buffer *b;
25671fc28d8eSLiu Bo 	int root_lock;
25681fc28d8eSLiu Bo 	int level = 0;
25691fc28d8eSLiu Bo 
25701fc28d8eSLiu Bo 	/* We try very hard to do read locks on the root */
25711fc28d8eSLiu Bo 	root_lock = BTRFS_READ_LOCK;
25721fc28d8eSLiu Bo 
25731fc28d8eSLiu Bo 	if (p->search_commit_root) {
2574be6821f8SFilipe Manana 		/*
2575be6821f8SFilipe Manana 		 * The commit roots are read only so we always do read locks,
2576be6821f8SFilipe Manana 		 * and we always must hold the commit_root_sem when doing
2577be6821f8SFilipe Manana 		 * searches on them, the only exception is send where we don't
2578be6821f8SFilipe Manana 		 * want to block transaction commits for a long time, so
2579be6821f8SFilipe Manana 		 * we need to clone the commit root in order to avoid races
2580be6821f8SFilipe Manana 		 * with transaction commits that create a snapshot of one of
2581be6821f8SFilipe Manana 		 * the roots used by a send operation.
2582be6821f8SFilipe Manana 		 */
2583be6821f8SFilipe Manana 		if (p->need_commit_sem) {
25841fc28d8eSLiu Bo 			down_read(&fs_info->commit_root_sem);
2585be6821f8SFilipe Manana 			b = btrfs_clone_extent_buffer(root->commit_root);
2586be6821f8SFilipe Manana 			up_read(&fs_info->commit_root_sem);
2587be6821f8SFilipe Manana 			if (!b)
2588be6821f8SFilipe Manana 				return ERR_PTR(-ENOMEM);
2589be6821f8SFilipe Manana 
2590be6821f8SFilipe Manana 		} else {
25911fc28d8eSLiu Bo 			b = root->commit_root;
259267439dadSDavid Sterba 			atomic_inc(&b->refs);
2593be6821f8SFilipe Manana 		}
25941fc28d8eSLiu Bo 		level = btrfs_header_level(b);
2595f9ddfd05SLiu Bo 		/*
2596f9ddfd05SLiu Bo 		 * Ensure that all callers have set skip_locking when
2597f9ddfd05SLiu Bo 		 * p->search_commit_root = 1.
2598f9ddfd05SLiu Bo 		 */
2599f9ddfd05SLiu Bo 		ASSERT(p->skip_locking == 1);
26001fc28d8eSLiu Bo 
26011fc28d8eSLiu Bo 		goto out;
26021fc28d8eSLiu Bo 	}
26031fc28d8eSLiu Bo 
26041fc28d8eSLiu Bo 	if (p->skip_locking) {
26051fc28d8eSLiu Bo 		b = btrfs_root_node(root);
26061fc28d8eSLiu Bo 		level = btrfs_header_level(b);
26071fc28d8eSLiu Bo 		goto out;
26081fc28d8eSLiu Bo 	}
26091fc28d8eSLiu Bo 
26101fc28d8eSLiu Bo 	/*
2611662c653bSLiu Bo 	 * If the level is set to maximum, we can skip trying to get the read
2612662c653bSLiu Bo 	 * lock.
2613662c653bSLiu Bo 	 */
2614662c653bSLiu Bo 	if (write_lock_level < BTRFS_MAX_LEVEL) {
2615662c653bSLiu Bo 		/*
2616662c653bSLiu Bo 		 * We don't know the level of the root node until we actually
2617662c653bSLiu Bo 		 * have it read locked
26181fc28d8eSLiu Bo 		 */
261951899412SJosef Bacik 		b = __btrfs_read_lock_root_node(root, p->recurse);
26201fc28d8eSLiu Bo 		level = btrfs_header_level(b);
26211fc28d8eSLiu Bo 		if (level > write_lock_level)
26221fc28d8eSLiu Bo 			goto out;
26231fc28d8eSLiu Bo 
2624662c653bSLiu Bo 		/* Whoops, must trade for write lock */
26251fc28d8eSLiu Bo 		btrfs_tree_read_unlock(b);
26261fc28d8eSLiu Bo 		free_extent_buffer(b);
2627662c653bSLiu Bo 	}
2628662c653bSLiu Bo 
26291fc28d8eSLiu Bo 	b = btrfs_lock_root_node(root);
26301fc28d8eSLiu Bo 	root_lock = BTRFS_WRITE_LOCK;
26311fc28d8eSLiu Bo 
26321fc28d8eSLiu Bo 	/* The level might have changed, check again */
26331fc28d8eSLiu Bo 	level = btrfs_header_level(b);
26341fc28d8eSLiu Bo 
26351fc28d8eSLiu Bo out:
26361fc28d8eSLiu Bo 	p->nodes[level] = b;
26371fc28d8eSLiu Bo 	if (!p->skip_locking)
26381fc28d8eSLiu Bo 		p->locks[level] = root_lock;
26391fc28d8eSLiu Bo 	/*
26401fc28d8eSLiu Bo 	 * Callers are responsible for dropping b's references.
26411fc28d8eSLiu Bo 	 */
26421fc28d8eSLiu Bo 	return b;
26431fc28d8eSLiu Bo }
26441fc28d8eSLiu Bo 
26451fc28d8eSLiu Bo 
2646c8c42864SChris Mason /*
26474271eceaSNikolay Borisov  * btrfs_search_slot - look for a key in a tree and perform necessary
26484271eceaSNikolay Borisov  * modifications to preserve tree invariants.
264974123bd7SChris Mason  *
26504271eceaSNikolay Borisov  * @trans:	Handle of transaction, used when modifying the tree
26514271eceaSNikolay Borisov  * @p:		Holds all btree nodes along the search path
26524271eceaSNikolay Borisov  * @root:	The root node of the tree
26534271eceaSNikolay Borisov  * @key:	The key we are looking for
26544271eceaSNikolay Borisov  * @ins_len:	Indicates purpose of search, for inserts it is 1, for
26554271eceaSNikolay Borisov  *		deletions it's -1. 0 for plain searches
26564271eceaSNikolay Borisov  * @cow:	boolean should CoW operations be performed. Must always be 1
26574271eceaSNikolay Borisov  *		when modifying the tree.
265897571fd0SChris Mason  *
26594271eceaSNikolay Borisov  * If @ins_len > 0, nodes and leaves will be split as we walk down the tree.
26604271eceaSNikolay Borisov  * If @ins_len < 0, nodes will be merged as we walk down the tree (if possible)
26614271eceaSNikolay Borisov  *
26624271eceaSNikolay Borisov  * If @key is found, 0 is returned and you can find the item in the leaf level
26634271eceaSNikolay Borisov  * of the path (level 0)
26644271eceaSNikolay Borisov  *
26654271eceaSNikolay Borisov  * If @key isn't found, 1 is returned and the leaf level of the path (level 0)
26664271eceaSNikolay Borisov  * points to the slot where it should be inserted
26674271eceaSNikolay Borisov  *
26684271eceaSNikolay Borisov  * If an error is encountered while searching the tree a negative error number
26694271eceaSNikolay Borisov  * is returned
267074123bd7SChris Mason  */
2671310712b2SOmar Sandoval int btrfs_search_slot(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2672310712b2SOmar Sandoval 		      const struct btrfs_key *key, struct btrfs_path *p,
2673310712b2SOmar Sandoval 		      int ins_len, int cow)
2674be0e5c09SChris Mason {
26755f39d397SChris Mason 	struct extent_buffer *b;
2676be0e5c09SChris Mason 	int slot;
2677be0e5c09SChris Mason 	int ret;
267833c66f43SYan Zheng 	int err;
2679be0e5c09SChris Mason 	int level;
2680925baeddSChris Mason 	int lowest_unlock = 1;
2681bd681513SChris Mason 	/* everything at write_lock_level or lower must be write locked */
2682bd681513SChris Mason 	int write_lock_level = 0;
26839f3a7427SChris Mason 	u8 lowest_level = 0;
2684f7c79f30SChris Mason 	int min_write_lock_level;
2685d7396f07SFilipe David Borba Manana 	int prev_cmp;
26869f3a7427SChris Mason 
26876702ed49SChris Mason 	lowest_level = p->lowest_level;
2688323ac95bSChris Mason 	WARN_ON(lowest_level && ins_len > 0);
268922b0ebdaSChris Mason 	WARN_ON(p->nodes[0] != NULL);
2690eb653de1SFilipe David Borba Manana 	BUG_ON(!cow && ins_len);
269125179201SJosef Bacik 
2692bd681513SChris Mason 	if (ins_len < 0) {
2693925baeddSChris Mason 		lowest_unlock = 2;
269465b51a00SChris Mason 
2695bd681513SChris Mason 		/* when we are removing items, we might have to go up to level
2696bd681513SChris Mason 		 * two as we update tree pointers  Make sure we keep write
2697bd681513SChris Mason 		 * for those levels as well
2698bd681513SChris Mason 		 */
2699bd681513SChris Mason 		write_lock_level = 2;
2700bd681513SChris Mason 	} else if (ins_len > 0) {
2701bd681513SChris Mason 		/*
2702bd681513SChris Mason 		 * for inserting items, make sure we have a write lock on
2703bd681513SChris Mason 		 * level 1 so we can update keys
2704bd681513SChris Mason 		 */
2705bd681513SChris Mason 		write_lock_level = 1;
2706bd681513SChris Mason 	}
2707bd681513SChris Mason 
2708bd681513SChris Mason 	if (!cow)
2709bd681513SChris Mason 		write_lock_level = -1;
2710bd681513SChris Mason 
271109a2a8f9SJosef Bacik 	if (cow && (p->keep_locks || p->lowest_level))
2712bd681513SChris Mason 		write_lock_level = BTRFS_MAX_LEVEL;
2713bd681513SChris Mason 
2714f7c79f30SChris Mason 	min_write_lock_level = write_lock_level;
2715f7c79f30SChris Mason 
2716bb803951SChris Mason again:
2717d7396f07SFilipe David Borba Manana 	prev_cmp = -1;
27181fc28d8eSLiu Bo 	b = btrfs_search_slot_get_root(root, p, write_lock_level);
2719be6821f8SFilipe Manana 	if (IS_ERR(b)) {
2720be6821f8SFilipe Manana 		ret = PTR_ERR(b);
2721be6821f8SFilipe Manana 		goto done;
2722be6821f8SFilipe Manana 	}
2723925baeddSChris Mason 
2724eb60ceacSChris Mason 	while (b) {
2725f624d976SQu Wenruo 		int dec = 0;
2726f624d976SQu Wenruo 
27275f39d397SChris Mason 		level = btrfs_header_level(b);
272865b51a00SChris Mason 
272902217ed2SChris Mason 		if (cow) {
27309ea2c7c9SNikolay Borisov 			bool last_level = (level == (BTRFS_MAX_LEVEL - 1));
27319ea2c7c9SNikolay Borisov 
2732c8c42864SChris Mason 			/*
2733c8c42864SChris Mason 			 * if we don't really need to cow this block
2734c8c42864SChris Mason 			 * then we don't want to set the path blocking,
2735c8c42864SChris Mason 			 * so we test it here
2736c8c42864SChris Mason 			 */
273764c12921SJeff Mahoney 			if (!should_cow_block(trans, root, b)) {
273864c12921SJeff Mahoney 				trans->dirty = true;
273965b51a00SChris Mason 				goto cow_done;
274064c12921SJeff Mahoney 			}
27415d4f98a2SYan Zheng 
2742bd681513SChris Mason 			/*
2743bd681513SChris Mason 			 * must have write locks on this node and the
2744bd681513SChris Mason 			 * parent
2745bd681513SChris Mason 			 */
27465124e00eSJosef Bacik 			if (level > write_lock_level ||
27475124e00eSJosef Bacik 			    (level + 1 > write_lock_level &&
27485124e00eSJosef Bacik 			    level + 1 < BTRFS_MAX_LEVEL &&
27495124e00eSJosef Bacik 			    p->nodes[level + 1])) {
2750bd681513SChris Mason 				write_lock_level = level + 1;
2751bd681513SChris Mason 				btrfs_release_path(p);
2752bd681513SChris Mason 				goto again;
2753bd681513SChris Mason 			}
2754bd681513SChris Mason 
2755160f4089SFilipe Manana 			btrfs_set_path_blocking(p);
27569ea2c7c9SNikolay Borisov 			if (last_level)
27579ea2c7c9SNikolay Borisov 				err = btrfs_cow_block(trans, root, b, NULL, 0,
27589631e4ccSJosef Bacik 						      &b,
27599631e4ccSJosef Bacik 						      BTRFS_NESTING_COW);
27609ea2c7c9SNikolay Borisov 			else
276133c66f43SYan Zheng 				err = btrfs_cow_block(trans, root, b,
2762e20d96d6SChris Mason 						      p->nodes[level + 1],
27639631e4ccSJosef Bacik 						      p->slots[level + 1], &b,
27649631e4ccSJosef Bacik 						      BTRFS_NESTING_COW);
276533c66f43SYan Zheng 			if (err) {
276633c66f43SYan Zheng 				ret = err;
276765b51a00SChris Mason 				goto done;
276854aa1f4dSChris Mason 			}
276902217ed2SChris Mason 		}
277065b51a00SChris Mason cow_done:
2771eb60ceacSChris Mason 		p->nodes[level] = b;
277252398340SLiu Bo 		/*
277352398340SLiu Bo 		 * Leave path with blocking locks to avoid massive
277452398340SLiu Bo 		 * lock context switch, this is made on purpose.
277552398340SLiu Bo 		 */
2776b4ce94deSChris Mason 
2777b4ce94deSChris Mason 		/*
2778b4ce94deSChris Mason 		 * we have a lock on b and as long as we aren't changing
2779b4ce94deSChris Mason 		 * the tree, there is no way to for the items in b to change.
2780b4ce94deSChris Mason 		 * It is safe to drop the lock on our parent before we
2781b4ce94deSChris Mason 		 * go through the expensive btree search on b.
2782b4ce94deSChris Mason 		 *
2783eb653de1SFilipe David Borba Manana 		 * If we're inserting or deleting (ins_len != 0), then we might
2784eb653de1SFilipe David Borba Manana 		 * be changing slot zero, which may require changing the parent.
2785eb653de1SFilipe David Borba Manana 		 * So, we can't drop the lock until after we know which slot
2786eb653de1SFilipe David Borba Manana 		 * we're operating on.
2787b4ce94deSChris Mason 		 */
2788eb653de1SFilipe David Borba Manana 		if (!ins_len && !p->keep_locks) {
2789eb653de1SFilipe David Borba Manana 			int u = level + 1;
2790eb653de1SFilipe David Borba Manana 
2791eb653de1SFilipe David Borba Manana 			if (u < BTRFS_MAX_LEVEL && p->locks[u]) {
2792eb653de1SFilipe David Borba Manana 				btrfs_tree_unlock_rw(p->nodes[u], p->locks[u]);
2793eb653de1SFilipe David Borba Manana 				p->locks[u] = 0;
2794eb653de1SFilipe David Borba Manana 			}
2795eb653de1SFilipe David Borba Manana 		}
2796b4ce94deSChris Mason 
2797995e9a16SNikolay Borisov 		/*
2798995e9a16SNikolay Borisov 		 * If btrfs_bin_search returns an exact match (prev_cmp == 0)
2799995e9a16SNikolay Borisov 		 * we can safely assume the target key will always be in slot 0
2800995e9a16SNikolay Borisov 		 * on lower levels due to the invariants BTRFS' btree provides,
2801995e9a16SNikolay Borisov 		 * namely that a btrfs_key_ptr entry always points to the
2802995e9a16SNikolay Borisov 		 * lowest key in the child node, thus we can skip searching
2803995e9a16SNikolay Borisov 		 * lower levels
2804995e9a16SNikolay Borisov 		 */
2805995e9a16SNikolay Borisov 		if (prev_cmp == 0) {
2806995e9a16SNikolay Borisov 			slot = 0;
2807995e9a16SNikolay Borisov 			ret = 0;
2808995e9a16SNikolay Borisov 		} else {
2809995e9a16SNikolay Borisov 			ret = btrfs_bin_search(b, key, &slot);
2810995e9a16SNikolay Borisov 			prev_cmp = ret;
2811415b35a5SLiu Bo 			if (ret < 0)
2812415b35a5SLiu Bo 				goto done;
2813995e9a16SNikolay Borisov 		}
2814b4ce94deSChris Mason 
2815f624d976SQu Wenruo 		if (level == 0) {
2816be0e5c09SChris Mason 			p->slots[level] = slot;
281787b29b20SYan Zheng 			if (ins_len > 0 &&
2818e902baacSDavid Sterba 			    btrfs_leaf_free_space(b) < ins_len) {
2819bd681513SChris Mason 				if (write_lock_level < 1) {
2820bd681513SChris Mason 					write_lock_level = 1;
2821bd681513SChris Mason 					btrfs_release_path(p);
2822bd681513SChris Mason 					goto again;
2823bd681513SChris Mason 				}
2824bd681513SChris Mason 
2825b4ce94deSChris Mason 				btrfs_set_path_blocking(p);
282633c66f43SYan Zheng 				err = split_leaf(trans, root, key,
2827cc0c5538SChris Mason 						 p, ins_len, ret == 0);
2828b4ce94deSChris Mason 
282933c66f43SYan Zheng 				BUG_ON(err > 0);
283033c66f43SYan Zheng 				if (err) {
283133c66f43SYan Zheng 					ret = err;
283265b51a00SChris Mason 					goto done;
283365b51a00SChris Mason 				}
28345c680ed6SChris Mason 			}
2835459931ecSChris Mason 			if (!p->search_for_split)
2836f7c79f30SChris Mason 				unlock_up(p, level, lowest_unlock,
28374b6f8e96SLiu Bo 					  min_write_lock_level, NULL);
283865b51a00SChris Mason 			goto done;
283965b51a00SChris Mason 		}
2840f624d976SQu Wenruo 		if (ret && slot > 0) {
2841f624d976SQu Wenruo 			dec = 1;
2842f624d976SQu Wenruo 			slot--;
2843f624d976SQu Wenruo 		}
2844f624d976SQu Wenruo 		p->slots[level] = slot;
2845f624d976SQu Wenruo 		err = setup_nodes_for_search(trans, root, p, b, level, ins_len,
2846f624d976SQu Wenruo 					     &write_lock_level);
2847f624d976SQu Wenruo 		if (err == -EAGAIN)
2848f624d976SQu Wenruo 			goto again;
2849f624d976SQu Wenruo 		if (err) {
2850f624d976SQu Wenruo 			ret = err;
2851f624d976SQu Wenruo 			goto done;
2852f624d976SQu Wenruo 		}
2853f624d976SQu Wenruo 		b = p->nodes[level];
2854f624d976SQu Wenruo 		slot = p->slots[level];
2855f624d976SQu Wenruo 
2856f624d976SQu Wenruo 		/*
2857f624d976SQu Wenruo 		 * Slot 0 is special, if we change the key we have to update
2858f624d976SQu Wenruo 		 * the parent pointer which means we must have a write lock on
2859f624d976SQu Wenruo 		 * the parent
2860f624d976SQu Wenruo 		 */
2861f624d976SQu Wenruo 		if (slot == 0 && ins_len && write_lock_level < level + 1) {
2862f624d976SQu Wenruo 			write_lock_level = level + 1;
2863f624d976SQu Wenruo 			btrfs_release_path(p);
2864f624d976SQu Wenruo 			goto again;
2865f624d976SQu Wenruo 		}
2866f624d976SQu Wenruo 
2867f624d976SQu Wenruo 		unlock_up(p, level, lowest_unlock, min_write_lock_level,
2868f624d976SQu Wenruo 			  &write_lock_level);
2869f624d976SQu Wenruo 
2870f624d976SQu Wenruo 		if (level == lowest_level) {
2871f624d976SQu Wenruo 			if (dec)
2872f624d976SQu Wenruo 				p->slots[level]++;
2873f624d976SQu Wenruo 			goto done;
2874f624d976SQu Wenruo 		}
2875f624d976SQu Wenruo 
2876f624d976SQu Wenruo 		err = read_block_for_search(root, p, &b, level, slot, key);
2877f624d976SQu Wenruo 		if (err == -EAGAIN)
2878f624d976SQu Wenruo 			goto again;
2879f624d976SQu Wenruo 		if (err) {
2880f624d976SQu Wenruo 			ret = err;
2881f624d976SQu Wenruo 			goto done;
2882f624d976SQu Wenruo 		}
2883f624d976SQu Wenruo 
2884f624d976SQu Wenruo 		if (!p->skip_locking) {
2885f624d976SQu Wenruo 			level = btrfs_header_level(b);
2886f624d976SQu Wenruo 			if (level <= write_lock_level) {
2887f624d976SQu Wenruo 				if (!btrfs_try_tree_write_lock(b)) {
2888f624d976SQu Wenruo 					btrfs_set_path_blocking(p);
2889f624d976SQu Wenruo 					btrfs_tree_lock(b);
2890f624d976SQu Wenruo 				}
2891f624d976SQu Wenruo 				p->locks[level] = BTRFS_WRITE_LOCK;
2892f624d976SQu Wenruo 			} else {
2893f624d976SQu Wenruo 				if (!btrfs_tree_read_lock_atomic(b)) {
2894f624d976SQu Wenruo 					btrfs_set_path_blocking(p);
2895fd7ba1c1SJosef Bacik 					__btrfs_tree_read_lock(b, BTRFS_NESTING_NORMAL,
2896fd7ba1c1SJosef Bacik 							       p->recurse);
2897f624d976SQu Wenruo 				}
2898f624d976SQu Wenruo 				p->locks[level] = BTRFS_READ_LOCK;
2899f624d976SQu Wenruo 			}
2900f624d976SQu Wenruo 			p->nodes[level] = b;
2901f624d976SQu Wenruo 		}
290265b51a00SChris Mason 	}
290365b51a00SChris Mason 	ret = 1;
290465b51a00SChris Mason done:
2905b4ce94deSChris Mason 	/*
2906b4ce94deSChris Mason 	 * we don't really know what they plan on doing with the path
2907b4ce94deSChris Mason 	 * from here on, so for now just mark it as blocking
2908b4ce94deSChris Mason 	 */
2909b9473439SChris Mason 	if (!p->leave_spinning)
2910b4ce94deSChris Mason 		btrfs_set_path_blocking(p);
29115f5bc6b1SFilipe Manana 	if (ret < 0 && !p->skip_release_on_error)
2912b3b4aa74SDavid Sterba 		btrfs_release_path(p);
2913be0e5c09SChris Mason 	return ret;
2914be0e5c09SChris Mason }
2915be0e5c09SChris Mason 
291674123bd7SChris Mason /*
29175d9e75c4SJan Schmidt  * Like btrfs_search_slot, this looks for a key in the given tree. It uses the
29185d9e75c4SJan Schmidt  * current state of the tree together with the operations recorded in the tree
29195d9e75c4SJan Schmidt  * modification log to search for the key in a previous version of this tree, as
29205d9e75c4SJan Schmidt  * denoted by the time_seq parameter.
29215d9e75c4SJan Schmidt  *
29225d9e75c4SJan Schmidt  * Naturally, there is no support for insert, delete or cow operations.
29235d9e75c4SJan Schmidt  *
29245d9e75c4SJan Schmidt  * The resulting path and return value will be set up as if we called
29255d9e75c4SJan Schmidt  * btrfs_search_slot at that point in time with ins_len and cow both set to 0.
29265d9e75c4SJan Schmidt  */
2927310712b2SOmar Sandoval int btrfs_search_old_slot(struct btrfs_root *root, const struct btrfs_key *key,
29285d9e75c4SJan Schmidt 			  struct btrfs_path *p, u64 time_seq)
29295d9e75c4SJan Schmidt {
29300b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
29315d9e75c4SJan Schmidt 	struct extent_buffer *b;
29325d9e75c4SJan Schmidt 	int slot;
29335d9e75c4SJan Schmidt 	int ret;
29345d9e75c4SJan Schmidt 	int err;
29355d9e75c4SJan Schmidt 	int level;
29365d9e75c4SJan Schmidt 	int lowest_unlock = 1;
29375d9e75c4SJan Schmidt 	u8 lowest_level = 0;
29385d9e75c4SJan Schmidt 
29395d9e75c4SJan Schmidt 	lowest_level = p->lowest_level;
29405d9e75c4SJan Schmidt 	WARN_ON(p->nodes[0] != NULL);
29415d9e75c4SJan Schmidt 
29425d9e75c4SJan Schmidt 	if (p->search_commit_root) {
29435d9e75c4SJan Schmidt 		BUG_ON(time_seq);
29445d9e75c4SJan Schmidt 		return btrfs_search_slot(NULL, root, key, p, 0, 0);
29455d9e75c4SJan Schmidt 	}
29465d9e75c4SJan Schmidt 
29475d9e75c4SJan Schmidt again:
29485d9e75c4SJan Schmidt 	b = get_old_root(root, time_seq);
2949315bed43SNikolay Borisov 	if (!b) {
2950315bed43SNikolay Borisov 		ret = -EIO;
2951315bed43SNikolay Borisov 		goto done;
2952315bed43SNikolay Borisov 	}
29535d9e75c4SJan Schmidt 	level = btrfs_header_level(b);
29545d9e75c4SJan Schmidt 	p->locks[level] = BTRFS_READ_LOCK;
29555d9e75c4SJan Schmidt 
29565d9e75c4SJan Schmidt 	while (b) {
2957abe9339dSQu Wenruo 		int dec = 0;
2958abe9339dSQu Wenruo 
29595d9e75c4SJan Schmidt 		level = btrfs_header_level(b);
29605d9e75c4SJan Schmidt 		p->nodes[level] = b;
29615d9e75c4SJan Schmidt 
29625d9e75c4SJan Schmidt 		/*
29635d9e75c4SJan Schmidt 		 * we have a lock on b and as long as we aren't changing
29645d9e75c4SJan Schmidt 		 * the tree, there is no way to for the items in b to change.
29655d9e75c4SJan Schmidt 		 * It is safe to drop the lock on our parent before we
29665d9e75c4SJan Schmidt 		 * go through the expensive btree search on b.
29675d9e75c4SJan Schmidt 		 */
29685d9e75c4SJan Schmidt 		btrfs_unlock_up_safe(p, level + 1);
29695d9e75c4SJan Schmidt 
2970995e9a16SNikolay Borisov 		ret = btrfs_bin_search(b, key, &slot);
2971cbca7d59SFilipe Manana 		if (ret < 0)
2972cbca7d59SFilipe Manana 			goto done;
29735d9e75c4SJan Schmidt 
2974abe9339dSQu Wenruo 		if (level == 0) {
2975abe9339dSQu Wenruo 			p->slots[level] = slot;
2976abe9339dSQu Wenruo 			unlock_up(p, level, lowest_unlock, 0, NULL);
2977abe9339dSQu Wenruo 			goto done;
2978abe9339dSQu Wenruo 		}
2979abe9339dSQu Wenruo 
29805d9e75c4SJan Schmidt 		if (ret && slot > 0) {
29815d9e75c4SJan Schmidt 			dec = 1;
2982abe9339dSQu Wenruo 			slot--;
29835d9e75c4SJan Schmidt 		}
29845d9e75c4SJan Schmidt 		p->slots[level] = slot;
29855d9e75c4SJan Schmidt 		unlock_up(p, level, lowest_unlock, 0, NULL);
29865d9e75c4SJan Schmidt 
29875d9e75c4SJan Schmidt 		if (level == lowest_level) {
29885d9e75c4SJan Schmidt 			if (dec)
29895d9e75c4SJan Schmidt 				p->slots[level]++;
29905d9e75c4SJan Schmidt 			goto done;
29915d9e75c4SJan Schmidt 		}
29925d9e75c4SJan Schmidt 
2993abe9339dSQu Wenruo 		err = read_block_for_search(root, p, &b, level, slot, key);
29945d9e75c4SJan Schmidt 		if (err == -EAGAIN)
29955d9e75c4SJan Schmidt 			goto again;
29965d9e75c4SJan Schmidt 		if (err) {
29975d9e75c4SJan Schmidt 			ret = err;
29985d9e75c4SJan Schmidt 			goto done;
29995d9e75c4SJan Schmidt 		}
30005d9e75c4SJan Schmidt 
30015d9e75c4SJan Schmidt 		level = btrfs_header_level(b);
300265e99c43SNikolay Borisov 		if (!btrfs_tree_read_lock_atomic(b)) {
30035d9e75c4SJan Schmidt 			btrfs_set_path_blocking(p);
30045d9e75c4SJan Schmidt 			btrfs_tree_read_lock(b);
30055d9e75c4SJan Schmidt 		}
30060b246afaSJeff Mahoney 		b = tree_mod_log_rewind(fs_info, p, b, time_seq);
3007db7f3436SJosef Bacik 		if (!b) {
3008db7f3436SJosef Bacik 			ret = -ENOMEM;
3009db7f3436SJosef Bacik 			goto done;
3010db7f3436SJosef Bacik 		}
30115d9e75c4SJan Schmidt 		p->locks[level] = BTRFS_READ_LOCK;
30125d9e75c4SJan Schmidt 		p->nodes[level] = b;
30135d9e75c4SJan Schmidt 	}
30145d9e75c4SJan Schmidt 	ret = 1;
30155d9e75c4SJan Schmidt done:
30165d9e75c4SJan Schmidt 	if (!p->leave_spinning)
30175d9e75c4SJan Schmidt 		btrfs_set_path_blocking(p);
30185d9e75c4SJan Schmidt 	if (ret < 0)
30195d9e75c4SJan Schmidt 		btrfs_release_path(p);
30205d9e75c4SJan Schmidt 
30215d9e75c4SJan Schmidt 	return ret;
30225d9e75c4SJan Schmidt }
30235d9e75c4SJan Schmidt 
30245d9e75c4SJan Schmidt /*
30252f38b3e1SArne Jansen  * helper to use instead of search slot if no exact match is needed but
30262f38b3e1SArne Jansen  * instead the next or previous item should be returned.
30272f38b3e1SArne Jansen  * When find_higher is true, the next higher item is returned, the next lower
30282f38b3e1SArne Jansen  * otherwise.
30292f38b3e1SArne Jansen  * When return_any and find_higher are both true, and no higher item is found,
30302f38b3e1SArne Jansen  * return the next lower instead.
30312f38b3e1SArne Jansen  * When return_any is true and find_higher is false, and no lower item is found,
30322f38b3e1SArne Jansen  * return the next higher instead.
30332f38b3e1SArne Jansen  * It returns 0 if any item is found, 1 if none is found (tree empty), and
30342f38b3e1SArne Jansen  * < 0 on error
30352f38b3e1SArne Jansen  */
30362f38b3e1SArne Jansen int btrfs_search_slot_for_read(struct btrfs_root *root,
3037310712b2SOmar Sandoval 			       const struct btrfs_key *key,
3038310712b2SOmar Sandoval 			       struct btrfs_path *p, int find_higher,
3039310712b2SOmar Sandoval 			       int return_any)
30402f38b3e1SArne Jansen {
30412f38b3e1SArne Jansen 	int ret;
30422f38b3e1SArne Jansen 	struct extent_buffer *leaf;
30432f38b3e1SArne Jansen 
30442f38b3e1SArne Jansen again:
30452f38b3e1SArne Jansen 	ret = btrfs_search_slot(NULL, root, key, p, 0, 0);
30462f38b3e1SArne Jansen 	if (ret <= 0)
30472f38b3e1SArne Jansen 		return ret;
30482f38b3e1SArne Jansen 	/*
30492f38b3e1SArne Jansen 	 * a return value of 1 means the path is at the position where the
30502f38b3e1SArne Jansen 	 * item should be inserted. Normally this is the next bigger item,
30512f38b3e1SArne Jansen 	 * but in case the previous item is the last in a leaf, path points
30522f38b3e1SArne Jansen 	 * to the first free slot in the previous leaf, i.e. at an invalid
30532f38b3e1SArne Jansen 	 * item.
30542f38b3e1SArne Jansen 	 */
30552f38b3e1SArne Jansen 	leaf = p->nodes[0];
30562f38b3e1SArne Jansen 
30572f38b3e1SArne Jansen 	if (find_higher) {
30582f38b3e1SArne Jansen 		if (p->slots[0] >= btrfs_header_nritems(leaf)) {
30592f38b3e1SArne Jansen 			ret = btrfs_next_leaf(root, p);
30602f38b3e1SArne Jansen 			if (ret <= 0)
30612f38b3e1SArne Jansen 				return ret;
30622f38b3e1SArne Jansen 			if (!return_any)
30632f38b3e1SArne Jansen 				return 1;
30642f38b3e1SArne Jansen 			/*
30652f38b3e1SArne Jansen 			 * no higher item found, return the next
30662f38b3e1SArne Jansen 			 * lower instead
30672f38b3e1SArne Jansen 			 */
30682f38b3e1SArne Jansen 			return_any = 0;
30692f38b3e1SArne Jansen 			find_higher = 0;
30702f38b3e1SArne Jansen 			btrfs_release_path(p);
30712f38b3e1SArne Jansen 			goto again;
30722f38b3e1SArne Jansen 		}
30732f38b3e1SArne Jansen 	} else {
30742f38b3e1SArne Jansen 		if (p->slots[0] == 0) {
30752f38b3e1SArne Jansen 			ret = btrfs_prev_leaf(root, p);
3076e6793769SArne Jansen 			if (ret < 0)
30772f38b3e1SArne Jansen 				return ret;
3078e6793769SArne Jansen 			if (!ret) {
307923c6bf6aSFilipe David Borba Manana 				leaf = p->nodes[0];
308023c6bf6aSFilipe David Borba Manana 				if (p->slots[0] == btrfs_header_nritems(leaf))
308123c6bf6aSFilipe David Borba Manana 					p->slots[0]--;
3082e6793769SArne Jansen 				return 0;
3083e6793769SArne Jansen 			}
30842f38b3e1SArne Jansen 			if (!return_any)
30852f38b3e1SArne Jansen 				return 1;
30862f38b3e1SArne Jansen 			/*
30872f38b3e1SArne Jansen 			 * no lower item found, return the next
30882f38b3e1SArne Jansen 			 * higher instead
30892f38b3e1SArne Jansen 			 */
30902f38b3e1SArne Jansen 			return_any = 0;
30912f38b3e1SArne Jansen 			find_higher = 1;
30922f38b3e1SArne Jansen 			btrfs_release_path(p);
30932f38b3e1SArne Jansen 			goto again;
3094e6793769SArne Jansen 		} else {
30952f38b3e1SArne Jansen 			--p->slots[0];
30962f38b3e1SArne Jansen 		}
30972f38b3e1SArne Jansen 	}
30982f38b3e1SArne Jansen 	return 0;
30992f38b3e1SArne Jansen }
31002f38b3e1SArne Jansen 
31012f38b3e1SArne Jansen /*
310274123bd7SChris Mason  * adjust the pointers going up the tree, starting at level
310374123bd7SChris Mason  * making sure the right key of each node is points to 'key'.
310474123bd7SChris Mason  * This is used after shifting pointers to the left, so it stops
310574123bd7SChris Mason  * fixing up pointers when a given leaf/node is not in slot 0 of the
310674123bd7SChris Mason  * higher levels
3107aa5d6bedSChris Mason  *
310874123bd7SChris Mason  */
3109b167fa91SNikolay Borisov static void fixup_low_keys(struct btrfs_path *path,
31105f39d397SChris Mason 			   struct btrfs_disk_key *key, int level)
3111be0e5c09SChris Mason {
3112be0e5c09SChris Mason 	int i;
31135f39d397SChris Mason 	struct extent_buffer *t;
31140e82bcfeSDavid Sterba 	int ret;
31155f39d397SChris Mason 
3116234b63a0SChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
3117be0e5c09SChris Mason 		int tslot = path->slots[i];
31180e82bcfeSDavid Sterba 
3119eb60ceacSChris Mason 		if (!path->nodes[i])
3120be0e5c09SChris Mason 			break;
31215f39d397SChris Mason 		t = path->nodes[i];
31220e82bcfeSDavid Sterba 		ret = tree_mod_log_insert_key(t, tslot, MOD_LOG_KEY_REPLACE,
31230e82bcfeSDavid Sterba 				GFP_ATOMIC);
31240e82bcfeSDavid Sterba 		BUG_ON(ret < 0);
31255f39d397SChris Mason 		btrfs_set_node_key(t, key, tslot);
3126d6025579SChris Mason 		btrfs_mark_buffer_dirty(path->nodes[i]);
3127be0e5c09SChris Mason 		if (tslot != 0)
3128be0e5c09SChris Mason 			break;
3129be0e5c09SChris Mason 	}
3130be0e5c09SChris Mason }
3131be0e5c09SChris Mason 
313274123bd7SChris Mason /*
313331840ae1SZheng Yan  * update item key.
313431840ae1SZheng Yan  *
313531840ae1SZheng Yan  * This function isn't completely safe. It's the caller's responsibility
313631840ae1SZheng Yan  * that the new key won't break the order
313731840ae1SZheng Yan  */
3138b7a0365eSDaniel Dressler void btrfs_set_item_key_safe(struct btrfs_fs_info *fs_info,
3139b7a0365eSDaniel Dressler 			     struct btrfs_path *path,
3140310712b2SOmar Sandoval 			     const struct btrfs_key *new_key)
314131840ae1SZheng Yan {
314231840ae1SZheng Yan 	struct btrfs_disk_key disk_key;
314331840ae1SZheng Yan 	struct extent_buffer *eb;
314431840ae1SZheng Yan 	int slot;
314531840ae1SZheng Yan 
314631840ae1SZheng Yan 	eb = path->nodes[0];
314731840ae1SZheng Yan 	slot = path->slots[0];
314831840ae1SZheng Yan 	if (slot > 0) {
314931840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot - 1);
31507c15d410SQu Wenruo 		if (unlikely(comp_keys(&disk_key, new_key) >= 0)) {
31517c15d410SQu Wenruo 			btrfs_crit(fs_info,
31527c15d410SQu Wenruo 		"slot %u key (%llu %u %llu) new key (%llu %u %llu)",
31537c15d410SQu Wenruo 				   slot, btrfs_disk_key_objectid(&disk_key),
31547c15d410SQu Wenruo 				   btrfs_disk_key_type(&disk_key),
31557c15d410SQu Wenruo 				   btrfs_disk_key_offset(&disk_key),
31567c15d410SQu Wenruo 				   new_key->objectid, new_key->type,
31577c15d410SQu Wenruo 				   new_key->offset);
31587c15d410SQu Wenruo 			btrfs_print_leaf(eb);
31597c15d410SQu Wenruo 			BUG();
31607c15d410SQu Wenruo 		}
316131840ae1SZheng Yan 	}
316231840ae1SZheng Yan 	if (slot < btrfs_header_nritems(eb) - 1) {
316331840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot + 1);
31647c15d410SQu Wenruo 		if (unlikely(comp_keys(&disk_key, new_key) <= 0)) {
31657c15d410SQu Wenruo 			btrfs_crit(fs_info,
31667c15d410SQu Wenruo 		"slot %u key (%llu %u %llu) new key (%llu %u %llu)",
31677c15d410SQu Wenruo 				   slot, btrfs_disk_key_objectid(&disk_key),
31687c15d410SQu Wenruo 				   btrfs_disk_key_type(&disk_key),
31697c15d410SQu Wenruo 				   btrfs_disk_key_offset(&disk_key),
31707c15d410SQu Wenruo 				   new_key->objectid, new_key->type,
31717c15d410SQu Wenruo 				   new_key->offset);
31727c15d410SQu Wenruo 			btrfs_print_leaf(eb);
31737c15d410SQu Wenruo 			BUG();
31747c15d410SQu Wenruo 		}
317531840ae1SZheng Yan 	}
317631840ae1SZheng Yan 
317731840ae1SZheng Yan 	btrfs_cpu_key_to_disk(&disk_key, new_key);
317831840ae1SZheng Yan 	btrfs_set_item_key(eb, &disk_key, slot);
317931840ae1SZheng Yan 	btrfs_mark_buffer_dirty(eb);
318031840ae1SZheng Yan 	if (slot == 0)
3181b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, 1);
318231840ae1SZheng Yan }
318331840ae1SZheng Yan 
318431840ae1SZheng Yan /*
3185d16c702fSQu Wenruo  * Check key order of two sibling extent buffers.
3186d16c702fSQu Wenruo  *
3187d16c702fSQu Wenruo  * Return true if something is wrong.
3188d16c702fSQu Wenruo  * Return false if everything is fine.
3189d16c702fSQu Wenruo  *
3190d16c702fSQu Wenruo  * Tree-checker only works inside one tree block, thus the following
3191d16c702fSQu Wenruo  * corruption can not be detected by tree-checker:
3192d16c702fSQu Wenruo  *
3193d16c702fSQu Wenruo  * Leaf @left			| Leaf @right
3194d16c702fSQu Wenruo  * --------------------------------------------------------------
3195d16c702fSQu Wenruo  * | 1 | 2 | 3 | 4 | 5 | f6 |   | 7 | 8 |
3196d16c702fSQu Wenruo  *
3197d16c702fSQu Wenruo  * Key f6 in leaf @left itself is valid, but not valid when the next
3198d16c702fSQu Wenruo  * key in leaf @right is 7.
3199d16c702fSQu Wenruo  * This can only be checked at tree block merge time.
3200d16c702fSQu Wenruo  * And since tree checker has ensured all key order in each tree block
3201d16c702fSQu Wenruo  * is correct, we only need to bother the last key of @left and the first
3202d16c702fSQu Wenruo  * key of @right.
3203d16c702fSQu Wenruo  */
3204d16c702fSQu Wenruo static bool check_sibling_keys(struct extent_buffer *left,
3205d16c702fSQu Wenruo 			       struct extent_buffer *right)
3206d16c702fSQu Wenruo {
3207d16c702fSQu Wenruo 	struct btrfs_key left_last;
3208d16c702fSQu Wenruo 	struct btrfs_key right_first;
3209d16c702fSQu Wenruo 	int level = btrfs_header_level(left);
3210d16c702fSQu Wenruo 	int nr_left = btrfs_header_nritems(left);
3211d16c702fSQu Wenruo 	int nr_right = btrfs_header_nritems(right);
3212d16c702fSQu Wenruo 
3213d16c702fSQu Wenruo 	/* No key to check in one of the tree blocks */
3214d16c702fSQu Wenruo 	if (!nr_left || !nr_right)
3215d16c702fSQu Wenruo 		return false;
3216d16c702fSQu Wenruo 
3217d16c702fSQu Wenruo 	if (level) {
3218d16c702fSQu Wenruo 		btrfs_node_key_to_cpu(left, &left_last, nr_left - 1);
3219d16c702fSQu Wenruo 		btrfs_node_key_to_cpu(right, &right_first, 0);
3220d16c702fSQu Wenruo 	} else {
3221d16c702fSQu Wenruo 		btrfs_item_key_to_cpu(left, &left_last, nr_left - 1);
3222d16c702fSQu Wenruo 		btrfs_item_key_to_cpu(right, &right_first, 0);
3223d16c702fSQu Wenruo 	}
3224d16c702fSQu Wenruo 
3225d16c702fSQu Wenruo 	if (btrfs_comp_cpu_keys(&left_last, &right_first) >= 0) {
3226d16c702fSQu Wenruo 		btrfs_crit(left->fs_info,
3227d16c702fSQu Wenruo "bad key order, sibling blocks, left last (%llu %u %llu) right first (%llu %u %llu)",
3228d16c702fSQu Wenruo 			   left_last.objectid, left_last.type,
3229d16c702fSQu Wenruo 			   left_last.offset, right_first.objectid,
3230d16c702fSQu Wenruo 			   right_first.type, right_first.offset);
3231d16c702fSQu Wenruo 		return true;
3232d16c702fSQu Wenruo 	}
3233d16c702fSQu Wenruo 	return false;
3234d16c702fSQu Wenruo }
3235d16c702fSQu Wenruo 
3236d16c702fSQu Wenruo /*
323774123bd7SChris Mason  * try to push data from one node into the next node left in the
323879f95c82SChris Mason  * tree.
3239aa5d6bedSChris Mason  *
3240aa5d6bedSChris Mason  * returns 0 if some ptrs were pushed left, < 0 if there was some horrible
3241aa5d6bedSChris Mason  * error, and > 0 if there was no room in the left hand block.
324274123bd7SChris Mason  */
324398ed5174SChris Mason static int push_node_left(struct btrfs_trans_handle *trans,
32442ff7e61eSJeff Mahoney 			  struct extent_buffer *dst,
3245971a1f66SChris Mason 			  struct extent_buffer *src, int empty)
3246be0e5c09SChris Mason {
3247d30a668fSDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
3248be0e5c09SChris Mason 	int push_items = 0;
3249bb803951SChris Mason 	int src_nritems;
3250bb803951SChris Mason 	int dst_nritems;
3251aa5d6bedSChris Mason 	int ret = 0;
3252be0e5c09SChris Mason 
32535f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
32545f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
32550b246afaSJeff Mahoney 	push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
32567bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
32577bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
325854aa1f4dSChris Mason 
3259bce4eae9SChris Mason 	if (!empty && src_nritems <= 8)
3260971a1f66SChris Mason 		return 1;
3261971a1f66SChris Mason 
3262d397712bSChris Mason 	if (push_items <= 0)
3263be0e5c09SChris Mason 		return 1;
3264be0e5c09SChris Mason 
3265bce4eae9SChris Mason 	if (empty) {
3266971a1f66SChris Mason 		push_items = min(src_nritems, push_items);
3267bce4eae9SChris Mason 		if (push_items < src_nritems) {
3268bce4eae9SChris Mason 			/* leave at least 8 pointers in the node if
3269bce4eae9SChris Mason 			 * we aren't going to empty it
3270bce4eae9SChris Mason 			 */
3271bce4eae9SChris Mason 			if (src_nritems - push_items < 8) {
3272bce4eae9SChris Mason 				if (push_items <= 8)
3273bce4eae9SChris Mason 					return 1;
3274bce4eae9SChris Mason 				push_items -= 8;
3275bce4eae9SChris Mason 			}
3276bce4eae9SChris Mason 		}
3277bce4eae9SChris Mason 	} else
3278bce4eae9SChris Mason 		push_items = min(src_nritems - 8, push_items);
327979f95c82SChris Mason 
3280d16c702fSQu Wenruo 	/* dst is the left eb, src is the middle eb */
3281d16c702fSQu Wenruo 	if (check_sibling_keys(dst, src)) {
3282d16c702fSQu Wenruo 		ret = -EUCLEAN;
3283d16c702fSQu Wenruo 		btrfs_abort_transaction(trans, ret);
3284d16c702fSQu Wenruo 		return ret;
3285d16c702fSQu Wenruo 	}
3286ed874f0dSDavid Sterba 	ret = tree_mod_log_eb_copy(dst, src, dst_nritems, 0, push_items);
32875de865eeSFilipe David Borba Manana 	if (ret) {
328866642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
32895de865eeSFilipe David Borba Manana 		return ret;
32905de865eeSFilipe David Borba Manana 	}
32915f39d397SChris Mason 	copy_extent_buffer(dst, src,
32925f39d397SChris Mason 			   btrfs_node_key_ptr_offset(dst_nritems),
32935f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
3294123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
32955f39d397SChris Mason 
3296bb803951SChris Mason 	if (push_items < src_nritems) {
329757911b8bSJan Schmidt 		/*
3298bf1d3425SDavid Sterba 		 * Don't call tree_mod_log_insert_move here, key removal was
3299bf1d3425SDavid Sterba 		 * already fully logged by tree_mod_log_eb_copy above.
330057911b8bSJan Schmidt 		 */
33015f39d397SChris Mason 		memmove_extent_buffer(src, btrfs_node_key_ptr_offset(0),
33025f39d397SChris Mason 				      btrfs_node_key_ptr_offset(push_items),
3303e2fa7227SChris Mason 				      (src_nritems - push_items) *
3304123abc88SChris Mason 				      sizeof(struct btrfs_key_ptr));
3305bb803951SChris Mason 	}
33065f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
33075f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
33085f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
33095f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
331031840ae1SZheng Yan 
3311bb803951SChris Mason 	return ret;
3312be0e5c09SChris Mason }
3313be0e5c09SChris Mason 
331497571fd0SChris Mason /*
331579f95c82SChris Mason  * try to push data from one node into the next node right in the
331679f95c82SChris Mason  * tree.
331779f95c82SChris Mason  *
331879f95c82SChris Mason  * returns 0 if some ptrs were pushed, < 0 if there was some horrible
331979f95c82SChris Mason  * error, and > 0 if there was no room in the right hand block.
332079f95c82SChris Mason  *
332179f95c82SChris Mason  * this will  only push up to 1/2 the contents of the left node over
332279f95c82SChris Mason  */
33235f39d397SChris Mason static int balance_node_right(struct btrfs_trans_handle *trans,
33245f39d397SChris Mason 			      struct extent_buffer *dst,
33255f39d397SChris Mason 			      struct extent_buffer *src)
332679f95c82SChris Mason {
332755d32ed8SDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
332879f95c82SChris Mason 	int push_items = 0;
332979f95c82SChris Mason 	int max_push;
333079f95c82SChris Mason 	int src_nritems;
333179f95c82SChris Mason 	int dst_nritems;
333279f95c82SChris Mason 	int ret = 0;
333379f95c82SChris Mason 
33347bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
33357bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
33367bb86316SChris Mason 
33375f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
33385f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
33390b246afaSJeff Mahoney 	push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
3340d397712bSChris Mason 	if (push_items <= 0)
334179f95c82SChris Mason 		return 1;
3342bce4eae9SChris Mason 
3343d397712bSChris Mason 	if (src_nritems < 4)
3344bce4eae9SChris Mason 		return 1;
334579f95c82SChris Mason 
334679f95c82SChris Mason 	max_push = src_nritems / 2 + 1;
334779f95c82SChris Mason 	/* don't try to empty the node */
3348d397712bSChris Mason 	if (max_push >= src_nritems)
334979f95c82SChris Mason 		return 1;
3350252c38f0SYan 
335179f95c82SChris Mason 	if (max_push < push_items)
335279f95c82SChris Mason 		push_items = max_push;
335379f95c82SChris Mason 
3354d16c702fSQu Wenruo 	/* dst is the right eb, src is the middle eb */
3355d16c702fSQu Wenruo 	if (check_sibling_keys(src, dst)) {
3356d16c702fSQu Wenruo 		ret = -EUCLEAN;
3357d16c702fSQu Wenruo 		btrfs_abort_transaction(trans, ret);
3358d16c702fSQu Wenruo 		return ret;
3359d16c702fSQu Wenruo 	}
3360bf1d3425SDavid Sterba 	ret = tree_mod_log_insert_move(dst, push_items, 0, dst_nritems);
3361bf1d3425SDavid Sterba 	BUG_ON(ret < 0);
33625f39d397SChris Mason 	memmove_extent_buffer(dst, btrfs_node_key_ptr_offset(push_items),
33635f39d397SChris Mason 				      btrfs_node_key_ptr_offset(0),
33645f39d397SChris Mason 				      (dst_nritems) *
33655f39d397SChris Mason 				      sizeof(struct btrfs_key_ptr));
3366d6025579SChris Mason 
3367ed874f0dSDavid Sterba 	ret = tree_mod_log_eb_copy(dst, src, 0, src_nritems - push_items,
3368ed874f0dSDavid Sterba 				   push_items);
33695de865eeSFilipe David Borba Manana 	if (ret) {
337066642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
33715de865eeSFilipe David Borba Manana 		return ret;
33725de865eeSFilipe David Borba Manana 	}
33735f39d397SChris Mason 	copy_extent_buffer(dst, src,
33745f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
33755f39d397SChris Mason 			   btrfs_node_key_ptr_offset(src_nritems - push_items),
3376123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
337779f95c82SChris Mason 
33785f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
33795f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
338079f95c82SChris Mason 
33815f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
33825f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
338331840ae1SZheng Yan 
338479f95c82SChris Mason 	return ret;
338579f95c82SChris Mason }
338679f95c82SChris Mason 
338779f95c82SChris Mason /*
338897571fd0SChris Mason  * helper function to insert a new root level in the tree.
338997571fd0SChris Mason  * A new node is allocated, and a single item is inserted to
339097571fd0SChris Mason  * point to the existing root
3391aa5d6bedSChris Mason  *
3392aa5d6bedSChris Mason  * returns zero on success or < 0 on failure.
339397571fd0SChris Mason  */
3394d397712bSChris Mason static noinline int insert_new_root(struct btrfs_trans_handle *trans,
33955f39d397SChris Mason 			   struct btrfs_root *root,
3396fdd99c72SLiu Bo 			   struct btrfs_path *path, int level)
339774123bd7SChris Mason {
33980b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
33997bb86316SChris Mason 	u64 lower_gen;
34005f39d397SChris Mason 	struct extent_buffer *lower;
34015f39d397SChris Mason 	struct extent_buffer *c;
3402925baeddSChris Mason 	struct extent_buffer *old;
34035f39d397SChris Mason 	struct btrfs_disk_key lower_key;
3404d9d19a01SDavid Sterba 	int ret;
34055c680ed6SChris Mason 
34065c680ed6SChris Mason 	BUG_ON(path->nodes[level]);
34075c680ed6SChris Mason 	BUG_ON(path->nodes[level-1] != root->node);
34085c680ed6SChris Mason 
34097bb86316SChris Mason 	lower = path->nodes[level-1];
34107bb86316SChris Mason 	if (level == 1)
34117bb86316SChris Mason 		btrfs_item_key(lower, &lower_key, 0);
34127bb86316SChris Mason 	else
34137bb86316SChris Mason 		btrfs_node_key(lower, &lower_key, 0);
34147bb86316SChris Mason 
3415a6279470SFilipe Manana 	c = alloc_tree_block_no_bg_flush(trans, root, 0, &lower_key, level,
34169631e4ccSJosef Bacik 					 root->node->start, 0,
3417cf6f34aaSJosef Bacik 					 BTRFS_NESTING_NEW_ROOT);
34185f39d397SChris Mason 	if (IS_ERR(c))
34195f39d397SChris Mason 		return PTR_ERR(c);
3420925baeddSChris Mason 
34210b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
3422f0486c68SYan, Zheng 
34235f39d397SChris Mason 	btrfs_set_header_nritems(c, 1);
34245f39d397SChris Mason 	btrfs_set_node_key(c, &lower_key, 0);
3425db94535dSChris Mason 	btrfs_set_node_blockptr(c, 0, lower->start);
34267bb86316SChris Mason 	lower_gen = btrfs_header_generation(lower);
342731840ae1SZheng Yan 	WARN_ON(lower_gen != trans->transid);
34287bb86316SChris Mason 
34297bb86316SChris Mason 	btrfs_set_node_ptr_generation(c, 0, lower_gen);
34305f39d397SChris Mason 
34315f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
3432d5719762SChris Mason 
3433925baeddSChris Mason 	old = root->node;
3434d9d19a01SDavid Sterba 	ret = tree_mod_log_insert_root(root->node, c, 0);
3435d9d19a01SDavid Sterba 	BUG_ON(ret < 0);
3436240f62c8SChris Mason 	rcu_assign_pointer(root->node, c);
3437925baeddSChris Mason 
3438925baeddSChris Mason 	/* the super has an extra ref to root->node */
3439925baeddSChris Mason 	free_extent_buffer(old);
3440925baeddSChris Mason 
34410b86a832SChris Mason 	add_root_to_dirty_list(root);
344267439dadSDavid Sterba 	atomic_inc(&c->refs);
34435f39d397SChris Mason 	path->nodes[level] = c;
344495449a16Schandan 	path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
344574123bd7SChris Mason 	path->slots[level] = 0;
344674123bd7SChris Mason 	return 0;
344774123bd7SChris Mason }
34485c680ed6SChris Mason 
34495c680ed6SChris Mason /*
34505c680ed6SChris Mason  * worker function to insert a single pointer in a node.
34515c680ed6SChris Mason  * the node should have enough room for the pointer already
345297571fd0SChris Mason  *
34535c680ed6SChris Mason  * slot and level indicate where you want the key to go, and
34545c680ed6SChris Mason  * blocknr is the block the key points to.
34555c680ed6SChris Mason  */
3456143bede5SJeff Mahoney static void insert_ptr(struct btrfs_trans_handle *trans,
34576ad3cf6dSDavid Sterba 		       struct btrfs_path *path,
3458143bede5SJeff Mahoney 		       struct btrfs_disk_key *key, u64 bytenr,
3459c3e06965SJan Schmidt 		       int slot, int level)
34605c680ed6SChris Mason {
34615f39d397SChris Mason 	struct extent_buffer *lower;
34625c680ed6SChris Mason 	int nritems;
3463f3ea38daSJan Schmidt 	int ret;
34645c680ed6SChris Mason 
34655c680ed6SChris Mason 	BUG_ON(!path->nodes[level]);
3466f0486c68SYan, Zheng 	btrfs_assert_tree_locked(path->nodes[level]);
34675f39d397SChris Mason 	lower = path->nodes[level];
34685f39d397SChris Mason 	nritems = btrfs_header_nritems(lower);
3469c293498bSStoyan Gaydarov 	BUG_ON(slot > nritems);
34706ad3cf6dSDavid Sterba 	BUG_ON(nritems == BTRFS_NODEPTRS_PER_BLOCK(trans->fs_info));
347174123bd7SChris Mason 	if (slot != nritems) {
3472bf1d3425SDavid Sterba 		if (level) {
3473bf1d3425SDavid Sterba 			ret = tree_mod_log_insert_move(lower, slot + 1, slot,
3474a446a979SDavid Sterba 					nritems - slot);
3475bf1d3425SDavid Sterba 			BUG_ON(ret < 0);
3476bf1d3425SDavid Sterba 		}
34775f39d397SChris Mason 		memmove_extent_buffer(lower,
34785f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot + 1),
34795f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot),
3480123abc88SChris Mason 			      (nritems - slot) * sizeof(struct btrfs_key_ptr));
348174123bd7SChris Mason 	}
3482c3e06965SJan Schmidt 	if (level) {
3483e09c2efeSDavid Sterba 		ret = tree_mod_log_insert_key(lower, slot, MOD_LOG_KEY_ADD,
3484e09c2efeSDavid Sterba 				GFP_NOFS);
3485f3ea38daSJan Schmidt 		BUG_ON(ret < 0);
3486f3ea38daSJan Schmidt 	}
34875f39d397SChris Mason 	btrfs_set_node_key(lower, key, slot);
3488db94535dSChris Mason 	btrfs_set_node_blockptr(lower, slot, bytenr);
348974493f7aSChris Mason 	WARN_ON(trans->transid == 0);
349074493f7aSChris Mason 	btrfs_set_node_ptr_generation(lower, slot, trans->transid);
34915f39d397SChris Mason 	btrfs_set_header_nritems(lower, nritems + 1);
34925f39d397SChris Mason 	btrfs_mark_buffer_dirty(lower);
349374123bd7SChris Mason }
349474123bd7SChris Mason 
349597571fd0SChris Mason /*
349697571fd0SChris Mason  * split the node at the specified level in path in two.
349797571fd0SChris Mason  * The path is corrected to point to the appropriate node after the split
349897571fd0SChris Mason  *
349997571fd0SChris Mason  * Before splitting this tries to make some room in the node by pushing
350097571fd0SChris Mason  * left and right, if either one works, it returns right away.
3501aa5d6bedSChris Mason  *
3502aa5d6bedSChris Mason  * returns 0 on success and < 0 on failure
350397571fd0SChris Mason  */
3504e02119d5SChris Mason static noinline int split_node(struct btrfs_trans_handle *trans,
3505e02119d5SChris Mason 			       struct btrfs_root *root,
3506e02119d5SChris Mason 			       struct btrfs_path *path, int level)
3507be0e5c09SChris Mason {
35080b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
35095f39d397SChris Mason 	struct extent_buffer *c;
35105f39d397SChris Mason 	struct extent_buffer *split;
35115f39d397SChris Mason 	struct btrfs_disk_key disk_key;
3512be0e5c09SChris Mason 	int mid;
35135c680ed6SChris Mason 	int ret;
35147518a238SChris Mason 	u32 c_nritems;
3515be0e5c09SChris Mason 
35165f39d397SChris Mason 	c = path->nodes[level];
35177bb86316SChris Mason 	WARN_ON(btrfs_header_generation(c) != trans->transid);
35185f39d397SChris Mason 	if (c == root->node) {
3519d9abbf1cSJan Schmidt 		/*
352090f8d62eSJan Schmidt 		 * trying to split the root, lets make a new one
352190f8d62eSJan Schmidt 		 *
3522fdd99c72SLiu Bo 		 * tree mod log: We don't log_removal old root in
352390f8d62eSJan Schmidt 		 * insert_new_root, because that root buffer will be kept as a
352490f8d62eSJan Schmidt 		 * normal node. We are going to log removal of half of the
352590f8d62eSJan Schmidt 		 * elements below with tree_mod_log_eb_copy. We're holding a
352690f8d62eSJan Schmidt 		 * tree lock on the buffer, which is why we cannot race with
352790f8d62eSJan Schmidt 		 * other tree_mod_log users.
3528d9abbf1cSJan Schmidt 		 */
3529fdd99c72SLiu Bo 		ret = insert_new_root(trans, root, path, level + 1);
35305c680ed6SChris Mason 		if (ret)
35315c680ed6SChris Mason 			return ret;
3532b3612421SChris Mason 	} else {
3533e66f709bSChris Mason 		ret = push_nodes_for_insert(trans, root, path, level);
35345f39d397SChris Mason 		c = path->nodes[level];
35355f39d397SChris Mason 		if (!ret && btrfs_header_nritems(c) <
35360b246afaSJeff Mahoney 		    BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3)
3537e66f709bSChris Mason 			return 0;
353854aa1f4dSChris Mason 		if (ret < 0)
353954aa1f4dSChris Mason 			return ret;
35405c680ed6SChris Mason 	}
3541e66f709bSChris Mason 
35425f39d397SChris Mason 	c_nritems = btrfs_header_nritems(c);
35435d4f98a2SYan Zheng 	mid = (c_nritems + 1) / 2;
35445d4f98a2SYan Zheng 	btrfs_node_key(c, &disk_key, mid);
35457bb86316SChris Mason 
3546a6279470SFilipe Manana 	split = alloc_tree_block_no_bg_flush(trans, root, 0, &disk_key, level,
35474dff97e6SJosef Bacik 					     c->start, 0, BTRFS_NESTING_SPLIT);
35485f39d397SChris Mason 	if (IS_ERR(split))
35495f39d397SChris Mason 		return PTR_ERR(split);
355054aa1f4dSChris Mason 
35510b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
3552bc877d28SNikolay Borisov 	ASSERT(btrfs_header_level(c) == level);
35535f39d397SChris Mason 
3554ed874f0dSDavid Sterba 	ret = tree_mod_log_eb_copy(split, c, 0, mid, c_nritems - mid);
35555de865eeSFilipe David Borba Manana 	if (ret) {
355666642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
35575de865eeSFilipe David Borba Manana 		return ret;
35585de865eeSFilipe David Borba Manana 	}
35595f39d397SChris Mason 	copy_extent_buffer(split, c,
35605f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
35615f39d397SChris Mason 			   btrfs_node_key_ptr_offset(mid),
3562123abc88SChris Mason 			   (c_nritems - mid) * sizeof(struct btrfs_key_ptr));
35635f39d397SChris Mason 	btrfs_set_header_nritems(split, c_nritems - mid);
35645f39d397SChris Mason 	btrfs_set_header_nritems(c, mid);
3565aa5d6bedSChris Mason 	ret = 0;
3566aa5d6bedSChris Mason 
35675f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
35685f39d397SChris Mason 	btrfs_mark_buffer_dirty(split);
35695f39d397SChris Mason 
35706ad3cf6dSDavid Sterba 	insert_ptr(trans, path, &disk_key, split->start,
3571c3e06965SJan Schmidt 		   path->slots[level + 1] + 1, level + 1);
3572aa5d6bedSChris Mason 
35735de08d7dSChris Mason 	if (path->slots[level] >= mid) {
35745c680ed6SChris Mason 		path->slots[level] -= mid;
3575925baeddSChris Mason 		btrfs_tree_unlock(c);
35765f39d397SChris Mason 		free_extent_buffer(c);
35775f39d397SChris Mason 		path->nodes[level] = split;
35785c680ed6SChris Mason 		path->slots[level + 1] += 1;
3579eb60ceacSChris Mason 	} else {
3580925baeddSChris Mason 		btrfs_tree_unlock(split);
35815f39d397SChris Mason 		free_extent_buffer(split);
3582be0e5c09SChris Mason 	}
3583aa5d6bedSChris Mason 	return ret;
3584be0e5c09SChris Mason }
3585be0e5c09SChris Mason 
358674123bd7SChris Mason /*
358774123bd7SChris Mason  * how many bytes are required to store the items in a leaf.  start
358874123bd7SChris Mason  * and nr indicate which items in the leaf to check.  This totals up the
358974123bd7SChris Mason  * space used both by the item structs and the item data
359074123bd7SChris Mason  */
35915f39d397SChris Mason static int leaf_space_used(struct extent_buffer *l, int start, int nr)
3592be0e5c09SChris Mason {
359341be1f3bSJosef Bacik 	struct btrfs_item *start_item;
359441be1f3bSJosef Bacik 	struct btrfs_item *end_item;
3595be0e5c09SChris Mason 	int data_len;
35965f39d397SChris Mason 	int nritems = btrfs_header_nritems(l);
3597d4dbff95SChris Mason 	int end = min(nritems, start + nr) - 1;
3598be0e5c09SChris Mason 
3599be0e5c09SChris Mason 	if (!nr)
3600be0e5c09SChris Mason 		return 0;
3601dd3cc16bSRoss Kirk 	start_item = btrfs_item_nr(start);
3602dd3cc16bSRoss Kirk 	end_item = btrfs_item_nr(end);
3603a31356b9SDavid Sterba 	data_len = btrfs_item_offset(l, start_item) +
3604a31356b9SDavid Sterba 		   btrfs_item_size(l, start_item);
3605a31356b9SDavid Sterba 	data_len = data_len - btrfs_item_offset(l, end_item);
36060783fcfcSChris Mason 	data_len += sizeof(struct btrfs_item) * nr;
3607d4dbff95SChris Mason 	WARN_ON(data_len < 0);
3608be0e5c09SChris Mason 	return data_len;
3609be0e5c09SChris Mason }
3610be0e5c09SChris Mason 
361174123bd7SChris Mason /*
3612d4dbff95SChris Mason  * The space between the end of the leaf items and
3613d4dbff95SChris Mason  * the start of the leaf data.  IOW, how much room
3614d4dbff95SChris Mason  * the leaf has left for both items and data
3615d4dbff95SChris Mason  */
3616e902baacSDavid Sterba noinline int btrfs_leaf_free_space(struct extent_buffer *leaf)
3617d4dbff95SChris Mason {
3618e902baacSDavid Sterba 	struct btrfs_fs_info *fs_info = leaf->fs_info;
36195f39d397SChris Mason 	int nritems = btrfs_header_nritems(leaf);
36205f39d397SChris Mason 	int ret;
36210b246afaSJeff Mahoney 
36220b246afaSJeff Mahoney 	ret = BTRFS_LEAF_DATA_SIZE(fs_info) - leaf_space_used(leaf, 0, nritems);
36235f39d397SChris Mason 	if (ret < 0) {
36240b246afaSJeff Mahoney 		btrfs_crit(fs_info,
3625efe120a0SFrank Holton 			   "leaf free space ret %d, leaf data size %lu, used %d nritems %d",
3626da17066cSJeff Mahoney 			   ret,
36270b246afaSJeff Mahoney 			   (unsigned long) BTRFS_LEAF_DATA_SIZE(fs_info),
36285f39d397SChris Mason 			   leaf_space_used(leaf, 0, nritems), nritems);
36295f39d397SChris Mason 	}
36305f39d397SChris Mason 	return ret;
3631d4dbff95SChris Mason }
3632d4dbff95SChris Mason 
363399d8f83cSChris Mason /*
363499d8f83cSChris Mason  * min slot controls the lowest index we're willing to push to the
363599d8f83cSChris Mason  * right.  We'll push up to and including min_slot, but no lower
363699d8f83cSChris Mason  */
3637f72f0010SDavid Sterba static noinline int __push_leaf_right(struct btrfs_path *path,
363844871b1bSChris Mason 				      int data_size, int empty,
363944871b1bSChris Mason 				      struct extent_buffer *right,
364099d8f83cSChris Mason 				      int free_space, u32 left_nritems,
364199d8f83cSChris Mason 				      u32 min_slot)
364200ec4c51SChris Mason {
3643f72f0010SDavid Sterba 	struct btrfs_fs_info *fs_info = right->fs_info;
36445f39d397SChris Mason 	struct extent_buffer *left = path->nodes[0];
364544871b1bSChris Mason 	struct extent_buffer *upper = path->nodes[1];
3646cfed81a0SChris Mason 	struct btrfs_map_token token;
36475f39d397SChris Mason 	struct btrfs_disk_key disk_key;
364800ec4c51SChris Mason 	int slot;
364934a38218SChris Mason 	u32 i;
365000ec4c51SChris Mason 	int push_space = 0;
365100ec4c51SChris Mason 	int push_items = 0;
36520783fcfcSChris Mason 	struct btrfs_item *item;
365334a38218SChris Mason 	u32 nr;
36547518a238SChris Mason 	u32 right_nritems;
36555f39d397SChris Mason 	u32 data_end;
3656db94535dSChris Mason 	u32 this_item_size;
365700ec4c51SChris Mason 
365834a38218SChris Mason 	if (empty)
365934a38218SChris Mason 		nr = 0;
366034a38218SChris Mason 	else
366199d8f83cSChris Mason 		nr = max_t(u32, 1, min_slot);
366234a38218SChris Mason 
366331840ae1SZheng Yan 	if (path->slots[0] >= left_nritems)
366487b29b20SYan Zheng 		push_space += data_size;
366531840ae1SZheng Yan 
366644871b1bSChris Mason 	slot = path->slots[1];
366734a38218SChris Mason 	i = left_nritems - 1;
366834a38218SChris Mason 	while (i >= nr) {
3669dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
3670db94535dSChris Mason 
367131840ae1SZheng Yan 		if (!empty && push_items > 0) {
367231840ae1SZheng Yan 			if (path->slots[0] > i)
367331840ae1SZheng Yan 				break;
367431840ae1SZheng Yan 			if (path->slots[0] == i) {
3675e902baacSDavid Sterba 				int space = btrfs_leaf_free_space(left);
3676e902baacSDavid Sterba 
367731840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
367831840ae1SZheng Yan 					break;
367931840ae1SZheng Yan 			}
368031840ae1SZheng Yan 		}
368131840ae1SZheng Yan 
368200ec4c51SChris Mason 		if (path->slots[0] == i)
368387b29b20SYan Zheng 			push_space += data_size;
3684db94535dSChris Mason 
3685db94535dSChris Mason 		this_item_size = btrfs_item_size(left, item);
3686db94535dSChris Mason 		if (this_item_size + sizeof(*item) + push_space > free_space)
368700ec4c51SChris Mason 			break;
368831840ae1SZheng Yan 
368900ec4c51SChris Mason 		push_items++;
3690db94535dSChris Mason 		push_space += this_item_size + sizeof(*item);
369134a38218SChris Mason 		if (i == 0)
369234a38218SChris Mason 			break;
369334a38218SChris Mason 		i--;
3694db94535dSChris Mason 	}
36955f39d397SChris Mason 
3696925baeddSChris Mason 	if (push_items == 0)
3697925baeddSChris Mason 		goto out_unlock;
36985f39d397SChris Mason 
36996c1500f2SJulia Lawall 	WARN_ON(!empty && push_items == left_nritems);
37005f39d397SChris Mason 
370100ec4c51SChris Mason 	/* push left to right */
37025f39d397SChris Mason 	right_nritems = btrfs_header_nritems(right);
370334a38218SChris Mason 
37045f39d397SChris Mason 	push_space = btrfs_item_end_nr(left, left_nritems - push_items);
37058f881e8cSDavid Sterba 	push_space -= leaf_data_end(left);
37065f39d397SChris Mason 
370700ec4c51SChris Mason 	/* make room in the right data area */
37088f881e8cSDavid Sterba 	data_end = leaf_data_end(right);
37095f39d397SChris Mason 	memmove_extent_buffer(right,
37103d9ec8c4SNikolay Borisov 			      BTRFS_LEAF_DATA_OFFSET + data_end - push_space,
37113d9ec8c4SNikolay Borisov 			      BTRFS_LEAF_DATA_OFFSET + data_end,
37120b246afaSJeff Mahoney 			      BTRFS_LEAF_DATA_SIZE(fs_info) - data_end);
37135f39d397SChris Mason 
371400ec4c51SChris Mason 	/* copy from the left data area */
37153d9ec8c4SNikolay Borisov 	copy_extent_buffer(right, left, BTRFS_LEAF_DATA_OFFSET +
37160b246afaSJeff Mahoney 		     BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
37178f881e8cSDavid Sterba 		     BTRFS_LEAF_DATA_OFFSET + leaf_data_end(left),
3718d6025579SChris Mason 		     push_space);
37195f39d397SChris Mason 
37205f39d397SChris Mason 	memmove_extent_buffer(right, btrfs_item_nr_offset(push_items),
37215f39d397SChris Mason 			      btrfs_item_nr_offset(0),
37220783fcfcSChris Mason 			      right_nritems * sizeof(struct btrfs_item));
37235f39d397SChris Mason 
372400ec4c51SChris Mason 	/* copy the items from left to right */
37255f39d397SChris Mason 	copy_extent_buffer(right, left, btrfs_item_nr_offset(0),
37265f39d397SChris Mason 		   btrfs_item_nr_offset(left_nritems - push_items),
37270783fcfcSChris Mason 		   push_items * sizeof(struct btrfs_item));
372800ec4c51SChris Mason 
372900ec4c51SChris Mason 	/* update the item pointers */
3730c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
37317518a238SChris Mason 	right_nritems += push_items;
37325f39d397SChris Mason 	btrfs_set_header_nritems(right, right_nritems);
37330b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
37347518a238SChris Mason 	for (i = 0; i < right_nritems; i++) {
3735dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
3736cc4c13d5SDavid Sterba 		push_space -= btrfs_token_item_size(&token, item);
3737cc4c13d5SDavid Sterba 		btrfs_set_token_item_offset(&token, item, push_space);
3738db94535dSChris Mason 	}
3739db94535dSChris Mason 
37407518a238SChris Mason 	left_nritems -= push_items;
37415f39d397SChris Mason 	btrfs_set_header_nritems(left, left_nritems);
374200ec4c51SChris Mason 
374334a38218SChris Mason 	if (left_nritems)
37445f39d397SChris Mason 		btrfs_mark_buffer_dirty(left);
3745f0486c68SYan, Zheng 	else
37466a884d7dSDavid Sterba 		btrfs_clean_tree_block(left);
3747f0486c68SYan, Zheng 
37485f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
3749a429e513SChris Mason 
37505f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
37515f39d397SChris Mason 	btrfs_set_node_key(upper, &disk_key, slot + 1);
3752d6025579SChris Mason 	btrfs_mark_buffer_dirty(upper);
375302217ed2SChris Mason 
375400ec4c51SChris Mason 	/* then fixup the leaf pointer in the path */
37557518a238SChris Mason 	if (path->slots[0] >= left_nritems) {
37567518a238SChris Mason 		path->slots[0] -= left_nritems;
3757925baeddSChris Mason 		if (btrfs_header_nritems(path->nodes[0]) == 0)
37586a884d7dSDavid Sterba 			btrfs_clean_tree_block(path->nodes[0]);
3759925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
37605f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
37615f39d397SChris Mason 		path->nodes[0] = right;
376200ec4c51SChris Mason 		path->slots[1] += 1;
376300ec4c51SChris Mason 	} else {
3764925baeddSChris Mason 		btrfs_tree_unlock(right);
37655f39d397SChris Mason 		free_extent_buffer(right);
376600ec4c51SChris Mason 	}
376700ec4c51SChris Mason 	return 0;
3768925baeddSChris Mason 
3769925baeddSChris Mason out_unlock:
3770925baeddSChris Mason 	btrfs_tree_unlock(right);
3771925baeddSChris Mason 	free_extent_buffer(right);
3772925baeddSChris Mason 	return 1;
377300ec4c51SChris Mason }
3774925baeddSChris Mason 
377500ec4c51SChris Mason /*
377644871b1bSChris Mason  * push some data in the path leaf to the right, trying to free up at
377774123bd7SChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
377844871b1bSChris Mason  *
377944871b1bSChris Mason  * returns 1 if the push failed because the other node didn't have enough
378044871b1bSChris Mason  * room, 0 if everything worked out and < 0 if there were major errors.
378199d8f83cSChris Mason  *
378299d8f83cSChris Mason  * this will push starting from min_slot to the end of the leaf.  It won't
378399d8f83cSChris Mason  * push any slot lower than min_slot
378474123bd7SChris Mason  */
378544871b1bSChris Mason static int push_leaf_right(struct btrfs_trans_handle *trans, struct btrfs_root
378699d8f83cSChris Mason 			   *root, struct btrfs_path *path,
378799d8f83cSChris Mason 			   int min_data_size, int data_size,
378899d8f83cSChris Mason 			   int empty, u32 min_slot)
3789be0e5c09SChris Mason {
379044871b1bSChris Mason 	struct extent_buffer *left = path->nodes[0];
379144871b1bSChris Mason 	struct extent_buffer *right;
379244871b1bSChris Mason 	struct extent_buffer *upper;
379344871b1bSChris Mason 	int slot;
379444871b1bSChris Mason 	int free_space;
379544871b1bSChris Mason 	u32 left_nritems;
379644871b1bSChris Mason 	int ret;
379744871b1bSChris Mason 
379844871b1bSChris Mason 	if (!path->nodes[1])
379944871b1bSChris Mason 		return 1;
380044871b1bSChris Mason 
380144871b1bSChris Mason 	slot = path->slots[1];
380244871b1bSChris Mason 	upper = path->nodes[1];
380344871b1bSChris Mason 	if (slot >= btrfs_header_nritems(upper) - 1)
380444871b1bSChris Mason 		return 1;
380544871b1bSChris Mason 
380644871b1bSChris Mason 	btrfs_assert_tree_locked(path->nodes[1]);
380744871b1bSChris Mason 
38084b231ae4SDavid Sterba 	right = btrfs_read_node_slot(upper, slot + 1);
3809fb770ae4SLiu Bo 	/*
3810fb770ae4SLiu Bo 	 * slot + 1 is not valid or we fail to read the right node,
3811fb770ae4SLiu Bo 	 * no big deal, just return.
3812fb770ae4SLiu Bo 	 */
3813fb770ae4SLiu Bo 	if (IS_ERR(right))
381491ca338dSTsutomu Itoh 		return 1;
381591ca338dSTsutomu Itoh 
3816bf77467aSJosef Bacik 	__btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
38178bead258SDavid Sterba 	btrfs_set_lock_blocking_write(right);
381844871b1bSChris Mason 
3819e902baacSDavid Sterba 	free_space = btrfs_leaf_free_space(right);
382044871b1bSChris Mason 	if (free_space < data_size)
382144871b1bSChris Mason 		goto out_unlock;
382244871b1bSChris Mason 
382344871b1bSChris Mason 	/* cow and double check */
382444871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, right, upper,
3825bf59a5a2SJosef Bacik 			      slot + 1, &right, BTRFS_NESTING_RIGHT_COW);
382644871b1bSChris Mason 	if (ret)
382744871b1bSChris Mason 		goto out_unlock;
382844871b1bSChris Mason 
3829e902baacSDavid Sterba 	free_space = btrfs_leaf_free_space(right);
383044871b1bSChris Mason 	if (free_space < data_size)
383144871b1bSChris Mason 		goto out_unlock;
383244871b1bSChris Mason 
383344871b1bSChris Mason 	left_nritems = btrfs_header_nritems(left);
383444871b1bSChris Mason 	if (left_nritems == 0)
383544871b1bSChris Mason 		goto out_unlock;
383644871b1bSChris Mason 
3837d16c702fSQu Wenruo 	if (check_sibling_keys(left, right)) {
3838d16c702fSQu Wenruo 		ret = -EUCLEAN;
3839d16c702fSQu Wenruo 		btrfs_tree_unlock(right);
3840d16c702fSQu Wenruo 		free_extent_buffer(right);
3841d16c702fSQu Wenruo 		return ret;
3842d16c702fSQu Wenruo 	}
38432ef1fed2SFilipe David Borba Manana 	if (path->slots[0] == left_nritems && !empty) {
38442ef1fed2SFilipe David Borba Manana 		/* Key greater than all keys in the leaf, right neighbor has
38452ef1fed2SFilipe David Borba Manana 		 * enough room for it and we're not emptying our leaf to delete
38462ef1fed2SFilipe David Borba Manana 		 * it, therefore use right neighbor to insert the new item and
384752042d8eSAndrea Gelmini 		 * no need to touch/dirty our left leaf. */
38482ef1fed2SFilipe David Borba Manana 		btrfs_tree_unlock(left);
38492ef1fed2SFilipe David Borba Manana 		free_extent_buffer(left);
38502ef1fed2SFilipe David Borba Manana 		path->nodes[0] = right;
38512ef1fed2SFilipe David Borba Manana 		path->slots[0] = 0;
38522ef1fed2SFilipe David Borba Manana 		path->slots[1]++;
38532ef1fed2SFilipe David Borba Manana 		return 0;
38542ef1fed2SFilipe David Borba Manana 	}
38552ef1fed2SFilipe David Borba Manana 
3856f72f0010SDavid Sterba 	return __push_leaf_right(path, min_data_size, empty,
385799d8f83cSChris Mason 				right, free_space, left_nritems, min_slot);
385844871b1bSChris Mason out_unlock:
385944871b1bSChris Mason 	btrfs_tree_unlock(right);
386044871b1bSChris Mason 	free_extent_buffer(right);
386144871b1bSChris Mason 	return 1;
386244871b1bSChris Mason }
386344871b1bSChris Mason 
386444871b1bSChris Mason /*
386544871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
386644871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
386799d8f83cSChris Mason  *
386899d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
386999d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us do all the
387099d8f83cSChris Mason  * items
387144871b1bSChris Mason  */
38728087c193SDavid Sterba static noinline int __push_leaf_left(struct btrfs_path *path, int data_size,
387344871b1bSChris Mason 				     int empty, struct extent_buffer *left,
387499d8f83cSChris Mason 				     int free_space, u32 right_nritems,
387599d8f83cSChris Mason 				     u32 max_slot)
387644871b1bSChris Mason {
38778087c193SDavid Sterba 	struct btrfs_fs_info *fs_info = left->fs_info;
38785f39d397SChris Mason 	struct btrfs_disk_key disk_key;
38795f39d397SChris Mason 	struct extent_buffer *right = path->nodes[0];
3880be0e5c09SChris Mason 	int i;
3881be0e5c09SChris Mason 	int push_space = 0;
3882be0e5c09SChris Mason 	int push_items = 0;
38830783fcfcSChris Mason 	struct btrfs_item *item;
38847518a238SChris Mason 	u32 old_left_nritems;
388534a38218SChris Mason 	u32 nr;
3886aa5d6bedSChris Mason 	int ret = 0;
3887db94535dSChris Mason 	u32 this_item_size;
3888db94535dSChris Mason 	u32 old_left_item_size;
3889cfed81a0SChris Mason 	struct btrfs_map_token token;
3890cfed81a0SChris Mason 
389134a38218SChris Mason 	if (empty)
389299d8f83cSChris Mason 		nr = min(right_nritems, max_slot);
389334a38218SChris Mason 	else
389499d8f83cSChris Mason 		nr = min(right_nritems - 1, max_slot);
389534a38218SChris Mason 
389634a38218SChris Mason 	for (i = 0; i < nr; i++) {
3897dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
3898db94535dSChris Mason 
389931840ae1SZheng Yan 		if (!empty && push_items > 0) {
390031840ae1SZheng Yan 			if (path->slots[0] < i)
390131840ae1SZheng Yan 				break;
390231840ae1SZheng Yan 			if (path->slots[0] == i) {
3903e902baacSDavid Sterba 				int space = btrfs_leaf_free_space(right);
3904e902baacSDavid Sterba 
390531840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
390631840ae1SZheng Yan 					break;
390731840ae1SZheng Yan 			}
390831840ae1SZheng Yan 		}
390931840ae1SZheng Yan 
3910be0e5c09SChris Mason 		if (path->slots[0] == i)
391187b29b20SYan Zheng 			push_space += data_size;
3912db94535dSChris Mason 
3913db94535dSChris Mason 		this_item_size = btrfs_item_size(right, item);
3914db94535dSChris Mason 		if (this_item_size + sizeof(*item) + push_space > free_space)
3915be0e5c09SChris Mason 			break;
3916db94535dSChris Mason 
3917be0e5c09SChris Mason 		push_items++;
3918db94535dSChris Mason 		push_space += this_item_size + sizeof(*item);
3919be0e5c09SChris Mason 	}
3920db94535dSChris Mason 
3921be0e5c09SChris Mason 	if (push_items == 0) {
3922925baeddSChris Mason 		ret = 1;
3923925baeddSChris Mason 		goto out;
3924be0e5c09SChris Mason 	}
3925fae7f21cSDulshani Gunawardhana 	WARN_ON(!empty && push_items == btrfs_header_nritems(right));
39265f39d397SChris Mason 
3927be0e5c09SChris Mason 	/* push data from right to left */
39285f39d397SChris Mason 	copy_extent_buffer(left, right,
39295f39d397SChris Mason 			   btrfs_item_nr_offset(btrfs_header_nritems(left)),
39305f39d397SChris Mason 			   btrfs_item_nr_offset(0),
39315f39d397SChris Mason 			   push_items * sizeof(struct btrfs_item));
39325f39d397SChris Mason 
39330b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info) -
39345f39d397SChris Mason 		     btrfs_item_offset_nr(right, push_items - 1);
39355f39d397SChris Mason 
39363d9ec8c4SNikolay Borisov 	copy_extent_buffer(left, right, BTRFS_LEAF_DATA_OFFSET +
39378f881e8cSDavid Sterba 		     leaf_data_end(left) - push_space,
39383d9ec8c4SNikolay Borisov 		     BTRFS_LEAF_DATA_OFFSET +
39395f39d397SChris Mason 		     btrfs_item_offset_nr(right, push_items - 1),
3940be0e5c09SChris Mason 		     push_space);
39415f39d397SChris Mason 	old_left_nritems = btrfs_header_nritems(left);
394287b29b20SYan Zheng 	BUG_ON(old_left_nritems <= 0);
3943eb60ceacSChris Mason 
3944c82f823cSDavid Sterba 	btrfs_init_map_token(&token, left);
3945db94535dSChris Mason 	old_left_item_size = btrfs_item_offset_nr(left, old_left_nritems - 1);
3946be0e5c09SChris Mason 	for (i = old_left_nritems; i < old_left_nritems + push_items; i++) {
39475f39d397SChris Mason 		u32 ioff;
3948db94535dSChris Mason 
3949dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
3950db94535dSChris Mason 
3951cc4c13d5SDavid Sterba 		ioff = btrfs_token_item_offset(&token, item);
3952cc4c13d5SDavid Sterba 		btrfs_set_token_item_offset(&token, item,
3953cc4c13d5SDavid Sterba 		      ioff - (BTRFS_LEAF_DATA_SIZE(fs_info) - old_left_item_size));
3954be0e5c09SChris Mason 	}
39555f39d397SChris Mason 	btrfs_set_header_nritems(left, old_left_nritems + push_items);
3956be0e5c09SChris Mason 
3957be0e5c09SChris Mason 	/* fixup right node */
395831b1a2bdSJulia Lawall 	if (push_items > right_nritems)
395931b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "push items %d nr %u\n", push_items,
3960d397712bSChris Mason 		       right_nritems);
396134a38218SChris Mason 
396234a38218SChris Mason 	if (push_items < right_nritems) {
39635f39d397SChris Mason 		push_space = btrfs_item_offset_nr(right, push_items - 1) -
39648f881e8cSDavid Sterba 						  leaf_data_end(right);
39653d9ec8c4SNikolay Borisov 		memmove_extent_buffer(right, BTRFS_LEAF_DATA_OFFSET +
39660b246afaSJeff Mahoney 				      BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
39673d9ec8c4SNikolay Borisov 				      BTRFS_LEAF_DATA_OFFSET +
39688f881e8cSDavid Sterba 				      leaf_data_end(right), push_space);
39695f39d397SChris Mason 
39705f39d397SChris Mason 		memmove_extent_buffer(right, btrfs_item_nr_offset(0),
39715f39d397SChris Mason 			      btrfs_item_nr_offset(push_items),
39725f39d397SChris Mason 			     (btrfs_header_nritems(right) - push_items) *
39730783fcfcSChris Mason 			     sizeof(struct btrfs_item));
397434a38218SChris Mason 	}
3975c82f823cSDavid Sterba 
3976c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
3977eef1c494SYan 	right_nritems -= push_items;
3978eef1c494SYan 	btrfs_set_header_nritems(right, right_nritems);
39790b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
39805f39d397SChris Mason 	for (i = 0; i < right_nritems; i++) {
3981dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
3982db94535dSChris Mason 
3983cc4c13d5SDavid Sterba 		push_space = push_space - btrfs_token_item_size(&token, item);
3984cc4c13d5SDavid Sterba 		btrfs_set_token_item_offset(&token, item, push_space);
3985db94535dSChris Mason 	}
3986eb60ceacSChris Mason 
39875f39d397SChris Mason 	btrfs_mark_buffer_dirty(left);
398834a38218SChris Mason 	if (right_nritems)
39895f39d397SChris Mason 		btrfs_mark_buffer_dirty(right);
3990f0486c68SYan, Zheng 	else
39916a884d7dSDavid Sterba 		btrfs_clean_tree_block(right);
3992098f59c2SChris Mason 
39935f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
3994b167fa91SNikolay Borisov 	fixup_low_keys(path, &disk_key, 1);
3995be0e5c09SChris Mason 
3996be0e5c09SChris Mason 	/* then fixup the leaf pointer in the path */
3997be0e5c09SChris Mason 	if (path->slots[0] < push_items) {
3998be0e5c09SChris Mason 		path->slots[0] += old_left_nritems;
3999925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
40005f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
40015f39d397SChris Mason 		path->nodes[0] = left;
4002be0e5c09SChris Mason 		path->slots[1] -= 1;
4003be0e5c09SChris Mason 	} else {
4004925baeddSChris Mason 		btrfs_tree_unlock(left);
40055f39d397SChris Mason 		free_extent_buffer(left);
4006be0e5c09SChris Mason 		path->slots[0] -= push_items;
4007be0e5c09SChris Mason 	}
4008eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
4009aa5d6bedSChris Mason 	return ret;
4010925baeddSChris Mason out:
4011925baeddSChris Mason 	btrfs_tree_unlock(left);
4012925baeddSChris Mason 	free_extent_buffer(left);
4013925baeddSChris Mason 	return ret;
4014be0e5c09SChris Mason }
4015be0e5c09SChris Mason 
401674123bd7SChris Mason /*
401744871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
401844871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
401999d8f83cSChris Mason  *
402099d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
402199d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us push all the
402299d8f83cSChris Mason  * items
402344871b1bSChris Mason  */
402444871b1bSChris Mason static int push_leaf_left(struct btrfs_trans_handle *trans, struct btrfs_root
402599d8f83cSChris Mason 			  *root, struct btrfs_path *path, int min_data_size,
402699d8f83cSChris Mason 			  int data_size, int empty, u32 max_slot)
402744871b1bSChris Mason {
402844871b1bSChris Mason 	struct extent_buffer *right = path->nodes[0];
402944871b1bSChris Mason 	struct extent_buffer *left;
403044871b1bSChris Mason 	int slot;
403144871b1bSChris Mason 	int free_space;
403244871b1bSChris Mason 	u32 right_nritems;
403344871b1bSChris Mason 	int ret = 0;
403444871b1bSChris Mason 
403544871b1bSChris Mason 	slot = path->slots[1];
403644871b1bSChris Mason 	if (slot == 0)
403744871b1bSChris Mason 		return 1;
403844871b1bSChris Mason 	if (!path->nodes[1])
403944871b1bSChris Mason 		return 1;
404044871b1bSChris Mason 
404144871b1bSChris Mason 	right_nritems = btrfs_header_nritems(right);
404244871b1bSChris Mason 	if (right_nritems == 0)
404344871b1bSChris Mason 		return 1;
404444871b1bSChris Mason 
404544871b1bSChris Mason 	btrfs_assert_tree_locked(path->nodes[1]);
404644871b1bSChris Mason 
40474b231ae4SDavid Sterba 	left = btrfs_read_node_slot(path->nodes[1], slot - 1);
4048fb770ae4SLiu Bo 	/*
4049fb770ae4SLiu Bo 	 * slot - 1 is not valid or we fail to read the left node,
4050fb770ae4SLiu Bo 	 * no big deal, just return.
4051fb770ae4SLiu Bo 	 */
4052fb770ae4SLiu Bo 	if (IS_ERR(left))
405391ca338dSTsutomu Itoh 		return 1;
405491ca338dSTsutomu Itoh 
4055bf77467aSJosef Bacik 	__btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
40568bead258SDavid Sterba 	btrfs_set_lock_blocking_write(left);
405744871b1bSChris Mason 
4058e902baacSDavid Sterba 	free_space = btrfs_leaf_free_space(left);
405944871b1bSChris Mason 	if (free_space < data_size) {
406044871b1bSChris Mason 		ret = 1;
406144871b1bSChris Mason 		goto out;
406244871b1bSChris Mason 	}
406344871b1bSChris Mason 
406444871b1bSChris Mason 	/* cow and double check */
406544871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, left,
40669631e4ccSJosef Bacik 			      path->nodes[1], slot - 1, &left,
4067bf59a5a2SJosef Bacik 			      BTRFS_NESTING_LEFT_COW);
406844871b1bSChris Mason 	if (ret) {
406944871b1bSChris Mason 		/* we hit -ENOSPC, but it isn't fatal here */
407079787eaaSJeff Mahoney 		if (ret == -ENOSPC)
407144871b1bSChris Mason 			ret = 1;
407244871b1bSChris Mason 		goto out;
407344871b1bSChris Mason 	}
407444871b1bSChris Mason 
4075e902baacSDavid Sterba 	free_space = btrfs_leaf_free_space(left);
407644871b1bSChris Mason 	if (free_space < data_size) {
407744871b1bSChris Mason 		ret = 1;
407844871b1bSChris Mason 		goto out;
407944871b1bSChris Mason 	}
408044871b1bSChris Mason 
4081d16c702fSQu Wenruo 	if (check_sibling_keys(left, right)) {
4082d16c702fSQu Wenruo 		ret = -EUCLEAN;
4083d16c702fSQu Wenruo 		goto out;
4084d16c702fSQu Wenruo 	}
40858087c193SDavid Sterba 	return __push_leaf_left(path, min_data_size,
408699d8f83cSChris Mason 			       empty, left, free_space, right_nritems,
408799d8f83cSChris Mason 			       max_slot);
408844871b1bSChris Mason out:
408944871b1bSChris Mason 	btrfs_tree_unlock(left);
409044871b1bSChris Mason 	free_extent_buffer(left);
409144871b1bSChris Mason 	return ret;
409244871b1bSChris Mason }
409344871b1bSChris Mason 
409444871b1bSChris Mason /*
409574123bd7SChris Mason  * split the path's leaf in two, making sure there is at least data_size
409674123bd7SChris Mason  * available for the resulting leaf level of the path.
409774123bd7SChris Mason  */
4098143bede5SJeff Mahoney static noinline void copy_for_split(struct btrfs_trans_handle *trans,
409944871b1bSChris Mason 				    struct btrfs_path *path,
410044871b1bSChris Mason 				    struct extent_buffer *l,
410144871b1bSChris Mason 				    struct extent_buffer *right,
410244871b1bSChris Mason 				    int slot, int mid, int nritems)
4103be0e5c09SChris Mason {
410494f94ad9SDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
4105be0e5c09SChris Mason 	int data_copy_size;
4106be0e5c09SChris Mason 	int rt_data_off;
4107be0e5c09SChris Mason 	int i;
4108d4dbff95SChris Mason 	struct btrfs_disk_key disk_key;
4109cfed81a0SChris Mason 	struct btrfs_map_token token;
4110cfed81a0SChris Mason 
41115f39d397SChris Mason 	nritems = nritems - mid;
41125f39d397SChris Mason 	btrfs_set_header_nritems(right, nritems);
41138f881e8cSDavid Sterba 	data_copy_size = btrfs_item_end_nr(l, mid) - leaf_data_end(l);
41145f39d397SChris Mason 
41155f39d397SChris Mason 	copy_extent_buffer(right, l, btrfs_item_nr_offset(0),
41165f39d397SChris Mason 			   btrfs_item_nr_offset(mid),
41175f39d397SChris Mason 			   nritems * sizeof(struct btrfs_item));
41185f39d397SChris Mason 
41195f39d397SChris Mason 	copy_extent_buffer(right, l,
41203d9ec8c4SNikolay Borisov 		     BTRFS_LEAF_DATA_OFFSET + BTRFS_LEAF_DATA_SIZE(fs_info) -
41213d9ec8c4SNikolay Borisov 		     data_copy_size, BTRFS_LEAF_DATA_OFFSET +
41228f881e8cSDavid Sterba 		     leaf_data_end(l), data_copy_size);
412374123bd7SChris Mason 
41240b246afaSJeff Mahoney 	rt_data_off = BTRFS_LEAF_DATA_SIZE(fs_info) - btrfs_item_end_nr(l, mid);
41255f39d397SChris Mason 
4126c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
41275f39d397SChris Mason 	for (i = 0; i < nritems; i++) {
4128dd3cc16bSRoss Kirk 		struct btrfs_item *item = btrfs_item_nr(i);
4129db94535dSChris Mason 		u32 ioff;
4130db94535dSChris Mason 
4131cc4c13d5SDavid Sterba 		ioff = btrfs_token_item_offset(&token, item);
4132cc4c13d5SDavid Sterba 		btrfs_set_token_item_offset(&token, item, ioff + rt_data_off);
41330783fcfcSChris Mason 	}
413474123bd7SChris Mason 
41355f39d397SChris Mason 	btrfs_set_header_nritems(l, mid);
41365f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
41376ad3cf6dSDavid Sterba 	insert_ptr(trans, path, &disk_key, right->start, path->slots[1] + 1, 1);
41385f39d397SChris Mason 
41395f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
41405f39d397SChris Mason 	btrfs_mark_buffer_dirty(l);
4141eb60ceacSChris Mason 	BUG_ON(path->slots[0] != slot);
41425f39d397SChris Mason 
4143be0e5c09SChris Mason 	if (mid <= slot) {
4144925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
41455f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
41465f39d397SChris Mason 		path->nodes[0] = right;
4147be0e5c09SChris Mason 		path->slots[0] -= mid;
4148be0e5c09SChris Mason 		path->slots[1] += 1;
4149925baeddSChris Mason 	} else {
4150925baeddSChris Mason 		btrfs_tree_unlock(right);
41515f39d397SChris Mason 		free_extent_buffer(right);
4152925baeddSChris Mason 	}
41535f39d397SChris Mason 
4154eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
415544871b1bSChris Mason }
415644871b1bSChris Mason 
415744871b1bSChris Mason /*
415899d8f83cSChris Mason  * double splits happen when we need to insert a big item in the middle
415999d8f83cSChris Mason  * of a leaf.  A double split can leave us with 3 mostly empty leaves:
416099d8f83cSChris Mason  * leaf: [ slots 0 - N] [ our target ] [ N + 1 - total in leaf ]
416199d8f83cSChris Mason  *          A                 B                 C
416299d8f83cSChris Mason  *
416399d8f83cSChris Mason  * We avoid this by trying to push the items on either side of our target
416499d8f83cSChris Mason  * into the adjacent leaves.  If all goes well we can avoid the double split
416599d8f83cSChris Mason  * completely.
416699d8f83cSChris Mason  */
416799d8f83cSChris Mason static noinline int push_for_double_split(struct btrfs_trans_handle *trans,
416899d8f83cSChris Mason 					  struct btrfs_root *root,
416999d8f83cSChris Mason 					  struct btrfs_path *path,
417099d8f83cSChris Mason 					  int data_size)
417199d8f83cSChris Mason {
417299d8f83cSChris Mason 	int ret;
417399d8f83cSChris Mason 	int progress = 0;
417499d8f83cSChris Mason 	int slot;
417599d8f83cSChris Mason 	u32 nritems;
41765a4267caSFilipe David Borba Manana 	int space_needed = data_size;
417799d8f83cSChris Mason 
417899d8f83cSChris Mason 	slot = path->slots[0];
41795a4267caSFilipe David Borba Manana 	if (slot < btrfs_header_nritems(path->nodes[0]))
4180e902baacSDavid Sterba 		space_needed -= btrfs_leaf_free_space(path->nodes[0]);
418199d8f83cSChris Mason 
418299d8f83cSChris Mason 	/*
418399d8f83cSChris Mason 	 * try to push all the items after our slot into the
418499d8f83cSChris Mason 	 * right leaf
418599d8f83cSChris Mason 	 */
41865a4267caSFilipe David Borba Manana 	ret = push_leaf_right(trans, root, path, 1, space_needed, 0, slot);
418799d8f83cSChris Mason 	if (ret < 0)
418899d8f83cSChris Mason 		return ret;
418999d8f83cSChris Mason 
419099d8f83cSChris Mason 	if (ret == 0)
419199d8f83cSChris Mason 		progress++;
419299d8f83cSChris Mason 
419399d8f83cSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
419499d8f83cSChris Mason 	/*
419599d8f83cSChris Mason 	 * our goal is to get our slot at the start or end of a leaf.  If
419699d8f83cSChris Mason 	 * we've done so we're done
419799d8f83cSChris Mason 	 */
419899d8f83cSChris Mason 	if (path->slots[0] == 0 || path->slots[0] == nritems)
419999d8f83cSChris Mason 		return 0;
420099d8f83cSChris Mason 
4201e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
420299d8f83cSChris Mason 		return 0;
420399d8f83cSChris Mason 
420499d8f83cSChris Mason 	/* try to push all the items before our slot into the next leaf */
420599d8f83cSChris Mason 	slot = path->slots[0];
4206263d3995SFilipe Manana 	space_needed = data_size;
4207263d3995SFilipe Manana 	if (slot > 0)
4208e902baacSDavid Sterba 		space_needed -= btrfs_leaf_free_space(path->nodes[0]);
42095a4267caSFilipe David Borba Manana 	ret = push_leaf_left(trans, root, path, 1, space_needed, 0, slot);
421099d8f83cSChris Mason 	if (ret < 0)
421199d8f83cSChris Mason 		return ret;
421299d8f83cSChris Mason 
421399d8f83cSChris Mason 	if (ret == 0)
421499d8f83cSChris Mason 		progress++;
421599d8f83cSChris Mason 
421699d8f83cSChris Mason 	if (progress)
421799d8f83cSChris Mason 		return 0;
421899d8f83cSChris Mason 	return 1;
421999d8f83cSChris Mason }
422099d8f83cSChris Mason 
422199d8f83cSChris Mason /*
422244871b1bSChris Mason  * split the path's leaf in two, making sure there is at least data_size
422344871b1bSChris Mason  * available for the resulting leaf level of the path.
422444871b1bSChris Mason  *
422544871b1bSChris Mason  * returns 0 if all went well and < 0 on failure.
422644871b1bSChris Mason  */
422744871b1bSChris Mason static noinline int split_leaf(struct btrfs_trans_handle *trans,
422844871b1bSChris Mason 			       struct btrfs_root *root,
4229310712b2SOmar Sandoval 			       const struct btrfs_key *ins_key,
423044871b1bSChris Mason 			       struct btrfs_path *path, int data_size,
423144871b1bSChris Mason 			       int extend)
423244871b1bSChris Mason {
42335d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
423444871b1bSChris Mason 	struct extent_buffer *l;
423544871b1bSChris Mason 	u32 nritems;
423644871b1bSChris Mason 	int mid;
423744871b1bSChris Mason 	int slot;
423844871b1bSChris Mason 	struct extent_buffer *right;
4239b7a0365eSDaniel Dressler 	struct btrfs_fs_info *fs_info = root->fs_info;
424044871b1bSChris Mason 	int ret = 0;
424144871b1bSChris Mason 	int wret;
42425d4f98a2SYan Zheng 	int split;
424344871b1bSChris Mason 	int num_doubles = 0;
424499d8f83cSChris Mason 	int tried_avoid_double = 0;
424544871b1bSChris Mason 
4246a5719521SYan, Zheng 	l = path->nodes[0];
4247a5719521SYan, Zheng 	slot = path->slots[0];
4248a5719521SYan, Zheng 	if (extend && data_size + btrfs_item_size_nr(l, slot) +
42490b246afaSJeff Mahoney 	    sizeof(struct btrfs_item) > BTRFS_LEAF_DATA_SIZE(fs_info))
4250a5719521SYan, Zheng 		return -EOVERFLOW;
4251a5719521SYan, Zheng 
425244871b1bSChris Mason 	/* first try to make some room by pushing left and right */
425333157e05SLiu Bo 	if (data_size && path->nodes[1]) {
42545a4267caSFilipe David Borba Manana 		int space_needed = data_size;
42555a4267caSFilipe David Borba Manana 
42565a4267caSFilipe David Borba Manana 		if (slot < btrfs_header_nritems(l))
4257e902baacSDavid Sterba 			space_needed -= btrfs_leaf_free_space(l);
42585a4267caSFilipe David Borba Manana 
42595a4267caSFilipe David Borba Manana 		wret = push_leaf_right(trans, root, path, space_needed,
42605a4267caSFilipe David Borba Manana 				       space_needed, 0, 0);
426144871b1bSChris Mason 		if (wret < 0)
426244871b1bSChris Mason 			return wret;
426344871b1bSChris Mason 		if (wret) {
4264263d3995SFilipe Manana 			space_needed = data_size;
4265263d3995SFilipe Manana 			if (slot > 0)
4266e902baacSDavid Sterba 				space_needed -= btrfs_leaf_free_space(l);
42675a4267caSFilipe David Borba Manana 			wret = push_leaf_left(trans, root, path, space_needed,
42685a4267caSFilipe David Borba Manana 					      space_needed, 0, (u32)-1);
426944871b1bSChris Mason 			if (wret < 0)
427044871b1bSChris Mason 				return wret;
427144871b1bSChris Mason 		}
427244871b1bSChris Mason 		l = path->nodes[0];
427344871b1bSChris Mason 
427444871b1bSChris Mason 		/* did the pushes work? */
4275e902baacSDavid Sterba 		if (btrfs_leaf_free_space(l) >= data_size)
427644871b1bSChris Mason 			return 0;
427744871b1bSChris Mason 	}
427844871b1bSChris Mason 
427944871b1bSChris Mason 	if (!path->nodes[1]) {
4280fdd99c72SLiu Bo 		ret = insert_new_root(trans, root, path, 1);
428144871b1bSChris Mason 		if (ret)
428244871b1bSChris Mason 			return ret;
428344871b1bSChris Mason 	}
428444871b1bSChris Mason again:
42855d4f98a2SYan Zheng 	split = 1;
428644871b1bSChris Mason 	l = path->nodes[0];
428744871b1bSChris Mason 	slot = path->slots[0];
428844871b1bSChris Mason 	nritems = btrfs_header_nritems(l);
428944871b1bSChris Mason 	mid = (nritems + 1) / 2;
429044871b1bSChris Mason 
42915d4f98a2SYan Zheng 	if (mid <= slot) {
42925d4f98a2SYan Zheng 		if (nritems == 1 ||
42935d4f98a2SYan Zheng 		    leaf_space_used(l, mid, nritems - mid) + data_size >
42940b246afaSJeff Mahoney 			BTRFS_LEAF_DATA_SIZE(fs_info)) {
42955d4f98a2SYan Zheng 			if (slot >= nritems) {
42965d4f98a2SYan Zheng 				split = 0;
42975d4f98a2SYan Zheng 			} else {
42985d4f98a2SYan Zheng 				mid = slot;
42995d4f98a2SYan Zheng 				if (mid != nritems &&
43005d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
43010b246afaSJeff Mahoney 				    data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
430299d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
430399d8f83cSChris Mason 						goto push_for_double;
43045d4f98a2SYan Zheng 					split = 2;
43055d4f98a2SYan Zheng 				}
43065d4f98a2SYan Zheng 			}
43075d4f98a2SYan Zheng 		}
43085d4f98a2SYan Zheng 	} else {
43095d4f98a2SYan Zheng 		if (leaf_space_used(l, 0, mid) + data_size >
43100b246afaSJeff Mahoney 			BTRFS_LEAF_DATA_SIZE(fs_info)) {
43115d4f98a2SYan Zheng 			if (!extend && data_size && slot == 0) {
43125d4f98a2SYan Zheng 				split = 0;
43135d4f98a2SYan Zheng 			} else if ((extend || !data_size) && slot == 0) {
43145d4f98a2SYan Zheng 				mid = 1;
43155d4f98a2SYan Zheng 			} else {
43165d4f98a2SYan Zheng 				mid = slot;
43175d4f98a2SYan Zheng 				if (mid != nritems &&
43185d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
43190b246afaSJeff Mahoney 				    data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
432099d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
432199d8f83cSChris Mason 						goto push_for_double;
43225d4f98a2SYan Zheng 					split = 2;
43235d4f98a2SYan Zheng 				}
43245d4f98a2SYan Zheng 			}
43255d4f98a2SYan Zheng 		}
43265d4f98a2SYan Zheng 	}
43275d4f98a2SYan Zheng 
43285d4f98a2SYan Zheng 	if (split == 0)
43295d4f98a2SYan Zheng 		btrfs_cpu_key_to_disk(&disk_key, ins_key);
43305d4f98a2SYan Zheng 	else
43315d4f98a2SYan Zheng 		btrfs_item_key(l, &disk_key, mid);
43325d4f98a2SYan Zheng 
4333ca9d473aSJosef Bacik 	/*
4334ca9d473aSJosef Bacik 	 * We have to about BTRFS_NESTING_NEW_ROOT here if we've done a double
4335ca9d473aSJosef Bacik 	 * split, because we're only allowed to have MAX_LOCKDEP_SUBCLASSES
4336ca9d473aSJosef Bacik 	 * subclasses, which is 8 at the time of this patch, and we've maxed it
4337ca9d473aSJosef Bacik 	 * out.  In the future we could add a
4338ca9d473aSJosef Bacik 	 * BTRFS_NESTING_SPLIT_THE_SPLITTENING if we need to, but for now just
4339ca9d473aSJosef Bacik 	 * use BTRFS_NESTING_NEW_ROOT.
4340ca9d473aSJosef Bacik 	 */
4341a6279470SFilipe Manana 	right = alloc_tree_block_no_bg_flush(trans, root, 0, &disk_key, 0,
4342ca9d473aSJosef Bacik 					     l->start, 0, num_doubles ?
4343ca9d473aSJosef Bacik 					     BTRFS_NESTING_NEW_ROOT :
4344ca9d473aSJosef Bacik 					     BTRFS_NESTING_SPLIT);
4345f0486c68SYan, Zheng 	if (IS_ERR(right))
434644871b1bSChris Mason 		return PTR_ERR(right);
4347f0486c68SYan, Zheng 
43480b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
434944871b1bSChris Mason 
43505d4f98a2SYan Zheng 	if (split == 0) {
435144871b1bSChris Mason 		if (mid <= slot) {
435244871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
43536ad3cf6dSDavid Sterba 			insert_ptr(trans, path, &disk_key,
43542ff7e61eSJeff Mahoney 				   right->start, path->slots[1] + 1, 1);
435544871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
435644871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
435744871b1bSChris Mason 			path->nodes[0] = right;
435844871b1bSChris Mason 			path->slots[0] = 0;
435944871b1bSChris Mason 			path->slots[1] += 1;
436044871b1bSChris Mason 		} else {
436144871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
43626ad3cf6dSDavid Sterba 			insert_ptr(trans, path, &disk_key,
43632ff7e61eSJeff Mahoney 				   right->start, path->slots[1], 1);
436444871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
436544871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
436644871b1bSChris Mason 			path->nodes[0] = right;
436744871b1bSChris Mason 			path->slots[0] = 0;
4368143bede5SJeff Mahoney 			if (path->slots[1] == 0)
4369b167fa91SNikolay Borisov 				fixup_low_keys(path, &disk_key, 1);
43705d4f98a2SYan Zheng 		}
4371196e0249SLiu Bo 		/*
4372196e0249SLiu Bo 		 * We create a new leaf 'right' for the required ins_len and
4373196e0249SLiu Bo 		 * we'll do btrfs_mark_buffer_dirty() on this leaf after copying
4374196e0249SLiu Bo 		 * the content of ins_len to 'right'.
4375196e0249SLiu Bo 		 */
437644871b1bSChris Mason 		return ret;
437744871b1bSChris Mason 	}
437844871b1bSChris Mason 
437994f94ad9SDavid Sterba 	copy_for_split(trans, path, l, right, slot, mid, nritems);
438044871b1bSChris Mason 
43815d4f98a2SYan Zheng 	if (split == 2) {
4382cc0c5538SChris Mason 		BUG_ON(num_doubles != 0);
4383cc0c5538SChris Mason 		num_doubles++;
4384cc0c5538SChris Mason 		goto again;
43853326d1b0SChris Mason 	}
438644871b1bSChris Mason 
4387143bede5SJeff Mahoney 	return 0;
438899d8f83cSChris Mason 
438999d8f83cSChris Mason push_for_double:
439099d8f83cSChris Mason 	push_for_double_split(trans, root, path, data_size);
439199d8f83cSChris Mason 	tried_avoid_double = 1;
4392e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
439399d8f83cSChris Mason 		return 0;
439499d8f83cSChris Mason 	goto again;
4395be0e5c09SChris Mason }
4396be0e5c09SChris Mason 
4397ad48fd75SYan, Zheng static noinline int setup_leaf_for_split(struct btrfs_trans_handle *trans,
4398ad48fd75SYan, Zheng 					 struct btrfs_root *root,
4399ad48fd75SYan, Zheng 					 struct btrfs_path *path, int ins_len)
4400ad48fd75SYan, Zheng {
4401ad48fd75SYan, Zheng 	struct btrfs_key key;
4402ad48fd75SYan, Zheng 	struct extent_buffer *leaf;
4403ad48fd75SYan, Zheng 	struct btrfs_file_extent_item *fi;
4404ad48fd75SYan, Zheng 	u64 extent_len = 0;
4405ad48fd75SYan, Zheng 	u32 item_size;
4406ad48fd75SYan, Zheng 	int ret;
4407ad48fd75SYan, Zheng 
4408ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4409ad48fd75SYan, Zheng 	btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4410ad48fd75SYan, Zheng 
4411ad48fd75SYan, Zheng 	BUG_ON(key.type != BTRFS_EXTENT_DATA_KEY &&
4412ad48fd75SYan, Zheng 	       key.type != BTRFS_EXTENT_CSUM_KEY);
4413ad48fd75SYan, Zheng 
4414e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) >= ins_len)
4415ad48fd75SYan, Zheng 		return 0;
4416ad48fd75SYan, Zheng 
4417ad48fd75SYan, Zheng 	item_size = btrfs_item_size_nr(leaf, path->slots[0]);
4418ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
4419ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
4420ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
4421ad48fd75SYan, Zheng 		extent_len = btrfs_file_extent_num_bytes(leaf, fi);
4422ad48fd75SYan, Zheng 	}
4423b3b4aa74SDavid Sterba 	btrfs_release_path(path);
4424ad48fd75SYan, Zheng 
4425ad48fd75SYan, Zheng 	path->keep_locks = 1;
4426ad48fd75SYan, Zheng 	path->search_for_split = 1;
4427ad48fd75SYan, Zheng 	ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
4428ad48fd75SYan, Zheng 	path->search_for_split = 0;
4429a8df6fe6SFilipe Manana 	if (ret > 0)
4430a8df6fe6SFilipe Manana 		ret = -EAGAIN;
4431ad48fd75SYan, Zheng 	if (ret < 0)
4432ad48fd75SYan, Zheng 		goto err;
4433ad48fd75SYan, Zheng 
4434ad48fd75SYan, Zheng 	ret = -EAGAIN;
4435ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4436a8df6fe6SFilipe Manana 	/* if our item isn't there, return now */
4437a8df6fe6SFilipe Manana 	if (item_size != btrfs_item_size_nr(leaf, path->slots[0]))
4438ad48fd75SYan, Zheng 		goto err;
4439ad48fd75SYan, Zheng 
4440109f6aefSChris Mason 	/* the leaf has  changed, it now has room.  return now */
4441e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= ins_len)
4442109f6aefSChris Mason 		goto err;
4443109f6aefSChris Mason 
4444ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
4445ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
4446ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
4447ad48fd75SYan, Zheng 		if (extent_len != btrfs_file_extent_num_bytes(leaf, fi))
4448ad48fd75SYan, Zheng 			goto err;
4449ad48fd75SYan, Zheng 	}
4450ad48fd75SYan, Zheng 
4451ad48fd75SYan, Zheng 	btrfs_set_path_blocking(path);
4452ad48fd75SYan, Zheng 	ret = split_leaf(trans, root, &key, path, ins_len, 1);
4453f0486c68SYan, Zheng 	if (ret)
4454f0486c68SYan, Zheng 		goto err;
4455ad48fd75SYan, Zheng 
4456ad48fd75SYan, Zheng 	path->keep_locks = 0;
4457ad48fd75SYan, Zheng 	btrfs_unlock_up_safe(path, 1);
4458ad48fd75SYan, Zheng 	return 0;
4459ad48fd75SYan, Zheng err:
4460ad48fd75SYan, Zheng 	path->keep_locks = 0;
4461ad48fd75SYan, Zheng 	return ret;
4462ad48fd75SYan, Zheng }
4463ad48fd75SYan, Zheng 
446425263cd7SDavid Sterba static noinline int split_item(struct btrfs_path *path,
4465310712b2SOmar Sandoval 			       const struct btrfs_key *new_key,
4466459931ecSChris Mason 			       unsigned long split_offset)
4467459931ecSChris Mason {
4468459931ecSChris Mason 	struct extent_buffer *leaf;
4469459931ecSChris Mason 	struct btrfs_item *item;
4470459931ecSChris Mason 	struct btrfs_item *new_item;
4471459931ecSChris Mason 	int slot;
4472ad48fd75SYan, Zheng 	char *buf;
4473459931ecSChris Mason 	u32 nritems;
4474ad48fd75SYan, Zheng 	u32 item_size;
4475459931ecSChris Mason 	u32 orig_offset;
4476459931ecSChris Mason 	struct btrfs_disk_key disk_key;
4477459931ecSChris Mason 
4478459931ecSChris Mason 	leaf = path->nodes[0];
4479e902baacSDavid Sterba 	BUG_ON(btrfs_leaf_free_space(leaf) < sizeof(struct btrfs_item));
4480b9473439SChris Mason 
4481b4ce94deSChris Mason 	btrfs_set_path_blocking(path);
4482b4ce94deSChris Mason 
4483dd3cc16bSRoss Kirk 	item = btrfs_item_nr(path->slots[0]);
4484459931ecSChris Mason 	orig_offset = btrfs_item_offset(leaf, item);
4485459931ecSChris Mason 	item_size = btrfs_item_size(leaf, item);
4486459931ecSChris Mason 
4487459931ecSChris Mason 	buf = kmalloc(item_size, GFP_NOFS);
4488ad48fd75SYan, Zheng 	if (!buf)
4489ad48fd75SYan, Zheng 		return -ENOMEM;
4490ad48fd75SYan, Zheng 
4491459931ecSChris Mason 	read_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf,
4492459931ecSChris Mason 			    path->slots[0]), item_size);
4493ad48fd75SYan, Zheng 
4494459931ecSChris Mason 	slot = path->slots[0] + 1;
4495459931ecSChris Mason 	nritems = btrfs_header_nritems(leaf);
4496459931ecSChris Mason 	if (slot != nritems) {
4497459931ecSChris Mason 		/* shift the items */
4498459931ecSChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + 1),
4499459931ecSChris Mason 				btrfs_item_nr_offset(slot),
4500459931ecSChris Mason 				(nritems - slot) * sizeof(struct btrfs_item));
4501459931ecSChris Mason 	}
4502459931ecSChris Mason 
4503459931ecSChris Mason 	btrfs_cpu_key_to_disk(&disk_key, new_key);
4504459931ecSChris Mason 	btrfs_set_item_key(leaf, &disk_key, slot);
4505459931ecSChris Mason 
4506dd3cc16bSRoss Kirk 	new_item = btrfs_item_nr(slot);
4507459931ecSChris Mason 
4508459931ecSChris Mason 	btrfs_set_item_offset(leaf, new_item, orig_offset);
4509459931ecSChris Mason 	btrfs_set_item_size(leaf, new_item, item_size - split_offset);
4510459931ecSChris Mason 
4511459931ecSChris Mason 	btrfs_set_item_offset(leaf, item,
4512459931ecSChris Mason 			      orig_offset + item_size - split_offset);
4513459931ecSChris Mason 	btrfs_set_item_size(leaf, item, split_offset);
4514459931ecSChris Mason 
4515459931ecSChris Mason 	btrfs_set_header_nritems(leaf, nritems + 1);
4516459931ecSChris Mason 
4517459931ecSChris Mason 	/* write the data for the start of the original item */
4518459931ecSChris Mason 	write_extent_buffer(leaf, buf,
4519459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, path->slots[0]),
4520459931ecSChris Mason 			    split_offset);
4521459931ecSChris Mason 
4522459931ecSChris Mason 	/* write the data for the new item */
4523459931ecSChris Mason 	write_extent_buffer(leaf, buf + split_offset,
4524459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, slot),
4525459931ecSChris Mason 			    item_size - split_offset);
4526459931ecSChris Mason 	btrfs_mark_buffer_dirty(leaf);
4527459931ecSChris Mason 
4528e902baacSDavid Sterba 	BUG_ON(btrfs_leaf_free_space(leaf) < 0);
4529459931ecSChris Mason 	kfree(buf);
4530ad48fd75SYan, Zheng 	return 0;
4531ad48fd75SYan, Zheng }
4532ad48fd75SYan, Zheng 
4533ad48fd75SYan, Zheng /*
4534ad48fd75SYan, Zheng  * This function splits a single item into two items,
4535ad48fd75SYan, Zheng  * giving 'new_key' to the new item and splitting the
4536ad48fd75SYan, Zheng  * old one at split_offset (from the start of the item).
4537ad48fd75SYan, Zheng  *
4538ad48fd75SYan, Zheng  * The path may be released by this operation.  After
4539ad48fd75SYan, Zheng  * the split, the path is pointing to the old item.  The
4540ad48fd75SYan, Zheng  * new item is going to be in the same node as the old one.
4541ad48fd75SYan, Zheng  *
4542ad48fd75SYan, Zheng  * Note, the item being split must be smaller enough to live alone on
4543ad48fd75SYan, Zheng  * a tree block with room for one extra struct btrfs_item
4544ad48fd75SYan, Zheng  *
4545ad48fd75SYan, Zheng  * This allows us to split the item in place, keeping a lock on the
4546ad48fd75SYan, Zheng  * leaf the entire time.
4547ad48fd75SYan, Zheng  */
4548ad48fd75SYan, Zheng int btrfs_split_item(struct btrfs_trans_handle *trans,
4549ad48fd75SYan, Zheng 		     struct btrfs_root *root,
4550ad48fd75SYan, Zheng 		     struct btrfs_path *path,
4551310712b2SOmar Sandoval 		     const struct btrfs_key *new_key,
4552ad48fd75SYan, Zheng 		     unsigned long split_offset)
4553ad48fd75SYan, Zheng {
4554ad48fd75SYan, Zheng 	int ret;
4555ad48fd75SYan, Zheng 	ret = setup_leaf_for_split(trans, root, path,
4556ad48fd75SYan, Zheng 				   sizeof(struct btrfs_item));
4557ad48fd75SYan, Zheng 	if (ret)
4558459931ecSChris Mason 		return ret;
4559ad48fd75SYan, Zheng 
456025263cd7SDavid Sterba 	ret = split_item(path, new_key, split_offset);
4561ad48fd75SYan, Zheng 	return ret;
4562ad48fd75SYan, Zheng }
4563ad48fd75SYan, Zheng 
4564ad48fd75SYan, Zheng /*
4565ad48fd75SYan, Zheng  * This function duplicate a item, giving 'new_key' to the new item.
4566ad48fd75SYan, Zheng  * It guarantees both items live in the same tree leaf and the new item
4567ad48fd75SYan, Zheng  * is contiguous with the original item.
4568ad48fd75SYan, Zheng  *
4569ad48fd75SYan, Zheng  * This allows us to split file extent in place, keeping a lock on the
4570ad48fd75SYan, Zheng  * leaf the entire time.
4571ad48fd75SYan, Zheng  */
4572ad48fd75SYan, Zheng int btrfs_duplicate_item(struct btrfs_trans_handle *trans,
4573ad48fd75SYan, Zheng 			 struct btrfs_root *root,
4574ad48fd75SYan, Zheng 			 struct btrfs_path *path,
4575310712b2SOmar Sandoval 			 const struct btrfs_key *new_key)
4576ad48fd75SYan, Zheng {
4577ad48fd75SYan, Zheng 	struct extent_buffer *leaf;
4578ad48fd75SYan, Zheng 	int ret;
4579ad48fd75SYan, Zheng 	u32 item_size;
4580ad48fd75SYan, Zheng 
4581ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4582ad48fd75SYan, Zheng 	item_size = btrfs_item_size_nr(leaf, path->slots[0]);
4583ad48fd75SYan, Zheng 	ret = setup_leaf_for_split(trans, root, path,
4584ad48fd75SYan, Zheng 				   item_size + sizeof(struct btrfs_item));
4585ad48fd75SYan, Zheng 	if (ret)
4586ad48fd75SYan, Zheng 		return ret;
4587ad48fd75SYan, Zheng 
4588ad48fd75SYan, Zheng 	path->slots[0]++;
4589fc0d82e1SNikolay Borisov 	setup_items_for_insert(root, path, new_key, &item_size, 1);
4590ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4591ad48fd75SYan, Zheng 	memcpy_extent_buffer(leaf,
4592ad48fd75SYan, Zheng 			     btrfs_item_ptr_offset(leaf, path->slots[0]),
4593ad48fd75SYan, Zheng 			     btrfs_item_ptr_offset(leaf, path->slots[0] - 1),
4594ad48fd75SYan, Zheng 			     item_size);
4595ad48fd75SYan, Zheng 	return 0;
4596459931ecSChris Mason }
4597459931ecSChris Mason 
4598459931ecSChris Mason /*
4599d352ac68SChris Mason  * make the item pointed to by the path smaller.  new_size indicates
4600d352ac68SChris Mason  * how small to make it, and from_end tells us if we just chop bytes
4601d352ac68SChris Mason  * off the end of the item or if we shift the item to chop bytes off
4602d352ac68SChris Mason  * the front.
4603d352ac68SChris Mason  */
460478ac4f9eSDavid Sterba void btrfs_truncate_item(struct btrfs_path *path, u32 new_size, int from_end)
4605b18c6685SChris Mason {
4606b18c6685SChris Mason 	int slot;
46075f39d397SChris Mason 	struct extent_buffer *leaf;
46085f39d397SChris Mason 	struct btrfs_item *item;
4609b18c6685SChris Mason 	u32 nritems;
4610b18c6685SChris Mason 	unsigned int data_end;
4611b18c6685SChris Mason 	unsigned int old_data_start;
4612b18c6685SChris Mason 	unsigned int old_size;
4613b18c6685SChris Mason 	unsigned int size_diff;
4614b18c6685SChris Mason 	int i;
4615cfed81a0SChris Mason 	struct btrfs_map_token token;
4616cfed81a0SChris Mason 
46175f39d397SChris Mason 	leaf = path->nodes[0];
4618179e29e4SChris Mason 	slot = path->slots[0];
4619179e29e4SChris Mason 
4620179e29e4SChris Mason 	old_size = btrfs_item_size_nr(leaf, slot);
4621179e29e4SChris Mason 	if (old_size == new_size)
4622143bede5SJeff Mahoney 		return;
4623b18c6685SChris Mason 
46245f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
46258f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
4626b18c6685SChris Mason 
46275f39d397SChris Mason 	old_data_start = btrfs_item_offset_nr(leaf, slot);
4628179e29e4SChris Mason 
4629b18c6685SChris Mason 	size_diff = old_size - new_size;
4630b18c6685SChris Mason 
4631b18c6685SChris Mason 	BUG_ON(slot < 0);
4632b18c6685SChris Mason 	BUG_ON(slot >= nritems);
4633b18c6685SChris Mason 
4634b18c6685SChris Mason 	/*
4635b18c6685SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4636b18c6685SChris Mason 	 */
4637b18c6685SChris Mason 	/* first correct the data pointers */
4638c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
4639b18c6685SChris Mason 	for (i = slot; i < nritems; i++) {
46405f39d397SChris Mason 		u32 ioff;
4641dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
4642db94535dSChris Mason 
4643cc4c13d5SDavid Sterba 		ioff = btrfs_token_item_offset(&token, item);
4644cc4c13d5SDavid Sterba 		btrfs_set_token_item_offset(&token, item, ioff + size_diff);
4645b18c6685SChris Mason 	}
4646db94535dSChris Mason 
4647b18c6685SChris Mason 	/* shift the data */
4648179e29e4SChris Mason 	if (from_end) {
46493d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
46503d9ec8c4SNikolay Borisov 			      data_end + size_diff, BTRFS_LEAF_DATA_OFFSET +
4651b18c6685SChris Mason 			      data_end, old_data_start + new_size - data_end);
4652179e29e4SChris Mason 	} else {
4653179e29e4SChris Mason 		struct btrfs_disk_key disk_key;
4654179e29e4SChris Mason 		u64 offset;
4655179e29e4SChris Mason 
4656179e29e4SChris Mason 		btrfs_item_key(leaf, &disk_key, slot);
4657179e29e4SChris Mason 
4658179e29e4SChris Mason 		if (btrfs_disk_key_type(&disk_key) == BTRFS_EXTENT_DATA_KEY) {
4659179e29e4SChris Mason 			unsigned long ptr;
4660179e29e4SChris Mason 			struct btrfs_file_extent_item *fi;
4661179e29e4SChris Mason 
4662179e29e4SChris Mason 			fi = btrfs_item_ptr(leaf, slot,
4663179e29e4SChris Mason 					    struct btrfs_file_extent_item);
4664179e29e4SChris Mason 			fi = (struct btrfs_file_extent_item *)(
4665179e29e4SChris Mason 			     (unsigned long)fi - size_diff);
4666179e29e4SChris Mason 
4667179e29e4SChris Mason 			if (btrfs_file_extent_type(leaf, fi) ==
4668179e29e4SChris Mason 			    BTRFS_FILE_EXTENT_INLINE) {
4669179e29e4SChris Mason 				ptr = btrfs_item_ptr_offset(leaf, slot);
4670179e29e4SChris Mason 				memmove_extent_buffer(leaf, ptr,
4671179e29e4SChris Mason 				      (unsigned long)fi,
46727ec20afbSDavid Sterba 				      BTRFS_FILE_EXTENT_INLINE_DATA_START);
4673179e29e4SChris Mason 			}
4674179e29e4SChris Mason 		}
4675179e29e4SChris Mason 
46763d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
46773d9ec8c4SNikolay Borisov 			      data_end + size_diff, BTRFS_LEAF_DATA_OFFSET +
4678179e29e4SChris Mason 			      data_end, old_data_start - data_end);
4679179e29e4SChris Mason 
4680179e29e4SChris Mason 		offset = btrfs_disk_key_offset(&disk_key);
4681179e29e4SChris Mason 		btrfs_set_disk_key_offset(&disk_key, offset + size_diff);
4682179e29e4SChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot);
4683179e29e4SChris Mason 		if (slot == 0)
4684b167fa91SNikolay Borisov 			fixup_low_keys(path, &disk_key, 1);
4685179e29e4SChris Mason 	}
46865f39d397SChris Mason 
4687dd3cc16bSRoss Kirk 	item = btrfs_item_nr(slot);
46885f39d397SChris Mason 	btrfs_set_item_size(leaf, item, new_size);
46895f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
4690b18c6685SChris Mason 
4691e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
4692a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
4693b18c6685SChris Mason 		BUG();
46945f39d397SChris Mason 	}
4695b18c6685SChris Mason }
4696b18c6685SChris Mason 
4697d352ac68SChris Mason /*
46988f69dbd2SStefan Behrens  * make the item pointed to by the path bigger, data_size is the added size.
4699d352ac68SChris Mason  */
4700c71dd880SDavid Sterba void btrfs_extend_item(struct btrfs_path *path, u32 data_size)
47016567e837SChris Mason {
47026567e837SChris Mason 	int slot;
47035f39d397SChris Mason 	struct extent_buffer *leaf;
47045f39d397SChris Mason 	struct btrfs_item *item;
47056567e837SChris Mason 	u32 nritems;
47066567e837SChris Mason 	unsigned int data_end;
47076567e837SChris Mason 	unsigned int old_data;
47086567e837SChris Mason 	unsigned int old_size;
47096567e837SChris Mason 	int i;
4710cfed81a0SChris Mason 	struct btrfs_map_token token;
4711cfed81a0SChris Mason 
47125f39d397SChris Mason 	leaf = path->nodes[0];
47136567e837SChris Mason 
47145f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
47158f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
47166567e837SChris Mason 
4717e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < data_size) {
4718a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
47196567e837SChris Mason 		BUG();
47205f39d397SChris Mason 	}
47216567e837SChris Mason 	slot = path->slots[0];
47225f39d397SChris Mason 	old_data = btrfs_item_end_nr(leaf, slot);
47236567e837SChris Mason 
47246567e837SChris Mason 	BUG_ON(slot < 0);
47253326d1b0SChris Mason 	if (slot >= nritems) {
4726a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
4727c71dd880SDavid Sterba 		btrfs_crit(leaf->fs_info, "slot %d too large, nritems %d",
4728d397712bSChris Mason 			   slot, nritems);
4729290342f6SArnd Bergmann 		BUG();
47303326d1b0SChris Mason 	}
47316567e837SChris Mason 
47326567e837SChris Mason 	/*
47336567e837SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
47346567e837SChris Mason 	 */
47356567e837SChris Mason 	/* first correct the data pointers */
4736c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
47376567e837SChris Mason 	for (i = slot; i < nritems; i++) {
47385f39d397SChris Mason 		u32 ioff;
4739dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
4740db94535dSChris Mason 
4741cc4c13d5SDavid Sterba 		ioff = btrfs_token_item_offset(&token, item);
4742cc4c13d5SDavid Sterba 		btrfs_set_token_item_offset(&token, item, ioff - data_size);
47436567e837SChris Mason 	}
47445f39d397SChris Mason 
47456567e837SChris Mason 	/* shift the data */
47463d9ec8c4SNikolay Borisov 	memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
47473d9ec8c4SNikolay Borisov 		      data_end - data_size, BTRFS_LEAF_DATA_OFFSET +
47486567e837SChris Mason 		      data_end, old_data - data_end);
47495f39d397SChris Mason 
47506567e837SChris Mason 	data_end = old_data;
47515f39d397SChris Mason 	old_size = btrfs_item_size_nr(leaf, slot);
4752dd3cc16bSRoss Kirk 	item = btrfs_item_nr(slot);
47535f39d397SChris Mason 	btrfs_set_item_size(leaf, item, old_size + data_size);
47545f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
47556567e837SChris Mason 
4756e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
4757a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
47586567e837SChris Mason 		BUG();
47595f39d397SChris Mason 	}
47606567e837SChris Mason }
47616567e837SChris Mason 
4762da9ffb24SNikolay Borisov /**
4763da9ffb24SNikolay Borisov  * setup_items_for_insert - Helper called before inserting one or more items
4764da9ffb24SNikolay Borisov  * to a leaf. Main purpose is to save stack depth by doing the bulk of the work
4765da9ffb24SNikolay Borisov  * in a function that doesn't call btrfs_search_slot
4766da9ffb24SNikolay Borisov  *
4767da9ffb24SNikolay Borisov  * @root:	root we are inserting items to
4768da9ffb24SNikolay Borisov  * @path:	points to the leaf/slot where we are going to insert new items
4769da9ffb24SNikolay Borisov  * @cpu_key:	array of keys for items to be inserted
4770da9ffb24SNikolay Borisov  * @data_size:	size of the body of each item we are going to insert
4771da9ffb24SNikolay Borisov  * @nr:		size of @cpu_key/@data_size arrays
477274123bd7SChris Mason  */
4773afe5fea7STsutomu Itoh void setup_items_for_insert(struct btrfs_root *root, struct btrfs_path *path,
4774310712b2SOmar Sandoval 			    const struct btrfs_key *cpu_key, u32 *data_size,
4775fc0d82e1SNikolay Borisov 			    int nr)
4776be0e5c09SChris Mason {
47770b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
47785f39d397SChris Mason 	struct btrfs_item *item;
47799c58309dSChris Mason 	int i;
47807518a238SChris Mason 	u32 nritems;
4781be0e5c09SChris Mason 	unsigned int data_end;
4782e2fa7227SChris Mason 	struct btrfs_disk_key disk_key;
478344871b1bSChris Mason 	struct extent_buffer *leaf;
478444871b1bSChris Mason 	int slot;
4785cfed81a0SChris Mason 	struct btrfs_map_token token;
4786fc0d82e1SNikolay Borisov 	u32 total_size;
4787fc0d82e1SNikolay Borisov 	u32 total_data = 0;
4788fc0d82e1SNikolay Borisov 
4789fc0d82e1SNikolay Borisov 	for (i = 0; i < nr; i++)
4790fc0d82e1SNikolay Borisov 		total_data += data_size[i];
4791fc0d82e1SNikolay Borisov 	total_size = total_data + (nr * sizeof(struct btrfs_item));
4792cfed81a0SChris Mason 
479324cdc847SFilipe Manana 	if (path->slots[0] == 0) {
479424cdc847SFilipe Manana 		btrfs_cpu_key_to_disk(&disk_key, cpu_key);
4795b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, 1);
479624cdc847SFilipe Manana 	}
479724cdc847SFilipe Manana 	btrfs_unlock_up_safe(path, 1);
479824cdc847SFilipe Manana 
47995f39d397SChris Mason 	leaf = path->nodes[0];
480044871b1bSChris Mason 	slot = path->slots[0];
480174123bd7SChris Mason 
48025f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
48038f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
4804eb60ceacSChris Mason 
4805e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < total_size) {
4806a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
48070b246afaSJeff Mahoney 		btrfs_crit(fs_info, "not enough freespace need %u have %d",
4808e902baacSDavid Sterba 			   total_size, btrfs_leaf_free_space(leaf));
4809be0e5c09SChris Mason 		BUG();
4810d4dbff95SChris Mason 	}
48115f39d397SChris Mason 
4812c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
4813be0e5c09SChris Mason 	if (slot != nritems) {
48145f39d397SChris Mason 		unsigned int old_data = btrfs_item_end_nr(leaf, slot);
4815be0e5c09SChris Mason 
48165f39d397SChris Mason 		if (old_data < data_end) {
4817a4f78750SDavid Sterba 			btrfs_print_leaf(leaf);
48187269ddd2SNikolay Borisov 			btrfs_crit(fs_info,
48197269ddd2SNikolay Borisov 		"item at slot %d with data offset %u beyond data end of leaf %u",
48205f39d397SChris Mason 				   slot, old_data, data_end);
4821290342f6SArnd Bergmann 			BUG();
48225f39d397SChris Mason 		}
4823be0e5c09SChris Mason 		/*
4824be0e5c09SChris Mason 		 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4825be0e5c09SChris Mason 		 */
4826be0e5c09SChris Mason 		/* first correct the data pointers */
48270783fcfcSChris Mason 		for (i = slot; i < nritems; i++) {
48285f39d397SChris Mason 			u32 ioff;
4829db94535dSChris Mason 
4830dd3cc16bSRoss Kirk 			item = btrfs_item_nr(i);
4831cc4c13d5SDavid Sterba 			ioff = btrfs_token_item_offset(&token, item);
4832cc4c13d5SDavid Sterba 			btrfs_set_token_item_offset(&token, item,
4833cc4c13d5SDavid Sterba 						    ioff - total_data);
48340783fcfcSChris Mason 		}
4835be0e5c09SChris Mason 		/* shift the items */
48369c58309dSChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + nr),
48375f39d397SChris Mason 			      btrfs_item_nr_offset(slot),
48380783fcfcSChris Mason 			      (nritems - slot) * sizeof(struct btrfs_item));
4839be0e5c09SChris Mason 
4840be0e5c09SChris Mason 		/* shift the data */
48413d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
48423d9ec8c4SNikolay Borisov 			      data_end - total_data, BTRFS_LEAF_DATA_OFFSET +
4843be0e5c09SChris Mason 			      data_end, old_data - data_end);
4844be0e5c09SChris Mason 		data_end = old_data;
4845be0e5c09SChris Mason 	}
48465f39d397SChris Mason 
484762e2749eSChris Mason 	/* setup the item for the new data */
48489c58309dSChris Mason 	for (i = 0; i < nr; i++) {
48499c58309dSChris Mason 		btrfs_cpu_key_to_disk(&disk_key, cpu_key + i);
48509c58309dSChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot + i);
4851dd3cc16bSRoss Kirk 		item = btrfs_item_nr(slot + i);
48529c58309dSChris Mason 		data_end -= data_size[i];
4853fc0716c2SNikolay Borisov 		btrfs_set_token_item_offset(&token, item, data_end);
4854cc4c13d5SDavid Sterba 		btrfs_set_token_item_size(&token, item, data_size[i]);
48559c58309dSChris Mason 	}
485644871b1bSChris Mason 
48579c58309dSChris Mason 	btrfs_set_header_nritems(leaf, nritems + nr);
4858b9473439SChris Mason 	btrfs_mark_buffer_dirty(leaf);
4859aa5d6bedSChris Mason 
4860e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
4861a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
4862be0e5c09SChris Mason 		BUG();
48635f39d397SChris Mason 	}
486444871b1bSChris Mason }
486544871b1bSChris Mason 
486644871b1bSChris Mason /*
486744871b1bSChris Mason  * Given a key and some data, insert items into the tree.
486844871b1bSChris Mason  * This does all the path init required, making room in the tree if needed.
486944871b1bSChris Mason  */
487044871b1bSChris Mason int btrfs_insert_empty_items(struct btrfs_trans_handle *trans,
487144871b1bSChris Mason 			    struct btrfs_root *root,
487244871b1bSChris Mason 			    struct btrfs_path *path,
4873310712b2SOmar Sandoval 			    const struct btrfs_key *cpu_key, u32 *data_size,
487444871b1bSChris Mason 			    int nr)
487544871b1bSChris Mason {
487644871b1bSChris Mason 	int ret = 0;
487744871b1bSChris Mason 	int slot;
487844871b1bSChris Mason 	int i;
487944871b1bSChris Mason 	u32 total_size = 0;
488044871b1bSChris Mason 	u32 total_data = 0;
488144871b1bSChris Mason 
488244871b1bSChris Mason 	for (i = 0; i < nr; i++)
488344871b1bSChris Mason 		total_data += data_size[i];
488444871b1bSChris Mason 
488544871b1bSChris Mason 	total_size = total_data + (nr * sizeof(struct btrfs_item));
488644871b1bSChris Mason 	ret = btrfs_search_slot(trans, root, cpu_key, path, total_size, 1);
488744871b1bSChris Mason 	if (ret == 0)
488844871b1bSChris Mason 		return -EEXIST;
488944871b1bSChris Mason 	if (ret < 0)
4890143bede5SJeff Mahoney 		return ret;
489144871b1bSChris Mason 
489244871b1bSChris Mason 	slot = path->slots[0];
489344871b1bSChris Mason 	BUG_ON(slot < 0);
489444871b1bSChris Mason 
4895fc0d82e1SNikolay Borisov 	setup_items_for_insert(root, path, cpu_key, data_size, nr);
4896143bede5SJeff Mahoney 	return 0;
489762e2749eSChris Mason }
489862e2749eSChris Mason 
489962e2749eSChris Mason /*
490062e2749eSChris Mason  * Given a key and some data, insert an item into the tree.
490162e2749eSChris Mason  * This does all the path init required, making room in the tree if needed.
490262e2749eSChris Mason  */
4903310712b2SOmar Sandoval int btrfs_insert_item(struct btrfs_trans_handle *trans, struct btrfs_root *root,
4904310712b2SOmar Sandoval 		      const struct btrfs_key *cpu_key, void *data,
4905310712b2SOmar Sandoval 		      u32 data_size)
490662e2749eSChris Mason {
490762e2749eSChris Mason 	int ret = 0;
49082c90e5d6SChris Mason 	struct btrfs_path *path;
49095f39d397SChris Mason 	struct extent_buffer *leaf;
49105f39d397SChris Mason 	unsigned long ptr;
491162e2749eSChris Mason 
49122c90e5d6SChris Mason 	path = btrfs_alloc_path();
4913db5b493aSTsutomu Itoh 	if (!path)
4914db5b493aSTsutomu Itoh 		return -ENOMEM;
49152c90e5d6SChris Mason 	ret = btrfs_insert_empty_item(trans, root, path, cpu_key, data_size);
491662e2749eSChris Mason 	if (!ret) {
49175f39d397SChris Mason 		leaf = path->nodes[0];
49185f39d397SChris Mason 		ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
49195f39d397SChris Mason 		write_extent_buffer(leaf, data, ptr, data_size);
49205f39d397SChris Mason 		btrfs_mark_buffer_dirty(leaf);
492162e2749eSChris Mason 	}
49222c90e5d6SChris Mason 	btrfs_free_path(path);
4923aa5d6bedSChris Mason 	return ret;
4924be0e5c09SChris Mason }
4925be0e5c09SChris Mason 
492674123bd7SChris Mason /*
49275de08d7dSChris Mason  * delete the pointer from a given node.
492874123bd7SChris Mason  *
4929d352ac68SChris Mason  * the tree should have been previously balanced so the deletion does not
4930d352ac68SChris Mason  * empty a node.
493174123bd7SChris Mason  */
4932afe5fea7STsutomu Itoh static void del_ptr(struct btrfs_root *root, struct btrfs_path *path,
4933afe5fea7STsutomu Itoh 		    int level, int slot)
4934be0e5c09SChris Mason {
49355f39d397SChris Mason 	struct extent_buffer *parent = path->nodes[level];
49367518a238SChris Mason 	u32 nritems;
4937f3ea38daSJan Schmidt 	int ret;
4938be0e5c09SChris Mason 
49395f39d397SChris Mason 	nritems = btrfs_header_nritems(parent);
4940be0e5c09SChris Mason 	if (slot != nritems - 1) {
4941bf1d3425SDavid Sterba 		if (level) {
4942bf1d3425SDavid Sterba 			ret = tree_mod_log_insert_move(parent, slot, slot + 1,
4943a446a979SDavid Sterba 					nritems - slot - 1);
4944bf1d3425SDavid Sterba 			BUG_ON(ret < 0);
4945bf1d3425SDavid Sterba 		}
49465f39d397SChris Mason 		memmove_extent_buffer(parent,
49475f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot),
49485f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot + 1),
4949d6025579SChris Mason 			      sizeof(struct btrfs_key_ptr) *
4950d6025579SChris Mason 			      (nritems - slot - 1));
495157ba86c0SChris Mason 	} else if (level) {
4952e09c2efeSDavid Sterba 		ret = tree_mod_log_insert_key(parent, slot, MOD_LOG_KEY_REMOVE,
4953e09c2efeSDavid Sterba 				GFP_NOFS);
495457ba86c0SChris Mason 		BUG_ON(ret < 0);
4955be0e5c09SChris Mason 	}
4956f3ea38daSJan Schmidt 
49577518a238SChris Mason 	nritems--;
49585f39d397SChris Mason 	btrfs_set_header_nritems(parent, nritems);
49597518a238SChris Mason 	if (nritems == 0 && parent == root->node) {
49605f39d397SChris Mason 		BUG_ON(btrfs_header_level(root->node) != 1);
4961eb60ceacSChris Mason 		/* just turn the root into a leaf and break */
49625f39d397SChris Mason 		btrfs_set_header_level(root->node, 0);
4963bb803951SChris Mason 	} else if (slot == 0) {
49645f39d397SChris Mason 		struct btrfs_disk_key disk_key;
49655f39d397SChris Mason 
49665f39d397SChris Mason 		btrfs_node_key(parent, &disk_key, 0);
4967b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, level + 1);
4968be0e5c09SChris Mason 	}
4969d6025579SChris Mason 	btrfs_mark_buffer_dirty(parent);
4970be0e5c09SChris Mason }
4971be0e5c09SChris Mason 
497274123bd7SChris Mason /*
4973323ac95bSChris Mason  * a helper function to delete the leaf pointed to by path->slots[1] and
49745d4f98a2SYan Zheng  * path->nodes[1].
4975323ac95bSChris Mason  *
4976323ac95bSChris Mason  * This deletes the pointer in path->nodes[1] and frees the leaf
4977323ac95bSChris Mason  * block extent.  zero is returned if it all worked out, < 0 otherwise.
4978323ac95bSChris Mason  *
4979323ac95bSChris Mason  * The path must have already been setup for deleting the leaf, including
4980323ac95bSChris Mason  * all the proper balancing.  path->nodes[1] must be locked.
4981323ac95bSChris Mason  */
4982143bede5SJeff Mahoney static noinline void btrfs_del_leaf(struct btrfs_trans_handle *trans,
4983323ac95bSChris Mason 				    struct btrfs_root *root,
49845d4f98a2SYan Zheng 				    struct btrfs_path *path,
49855d4f98a2SYan Zheng 				    struct extent_buffer *leaf)
4986323ac95bSChris Mason {
49875d4f98a2SYan Zheng 	WARN_ON(btrfs_header_generation(leaf) != trans->transid);
4988afe5fea7STsutomu Itoh 	del_ptr(root, path, 1, path->slots[1]);
4989323ac95bSChris Mason 
49904d081c41SChris Mason 	/*
49914d081c41SChris Mason 	 * btrfs_free_extent is expensive, we want to make sure we
49924d081c41SChris Mason 	 * aren't holding any locks when we call it
49934d081c41SChris Mason 	 */
49944d081c41SChris Mason 	btrfs_unlock_up_safe(path, 0);
49954d081c41SChris Mason 
4996f0486c68SYan, Zheng 	root_sub_used(root, leaf->len);
4997f0486c68SYan, Zheng 
499867439dadSDavid Sterba 	atomic_inc(&leaf->refs);
49995581a51aSJan Schmidt 	btrfs_free_tree_block(trans, root, leaf, 0, 1);
50003083ee2eSJosef Bacik 	free_extent_buffer_stale(leaf);
5001323ac95bSChris Mason }
5002323ac95bSChris Mason /*
500374123bd7SChris Mason  * delete the item at the leaf level in path.  If that empties
500474123bd7SChris Mason  * the leaf, remove it from the tree
500574123bd7SChris Mason  */
500685e21bacSChris Mason int btrfs_del_items(struct btrfs_trans_handle *trans, struct btrfs_root *root,
500785e21bacSChris Mason 		    struct btrfs_path *path, int slot, int nr)
5008be0e5c09SChris Mason {
50090b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
50105f39d397SChris Mason 	struct extent_buffer *leaf;
50115f39d397SChris Mason 	struct btrfs_item *item;
5012ce0eac2aSAlexandru Moise 	u32 last_off;
5013ce0eac2aSAlexandru Moise 	u32 dsize = 0;
5014aa5d6bedSChris Mason 	int ret = 0;
5015aa5d6bedSChris Mason 	int wret;
501685e21bacSChris Mason 	int i;
50177518a238SChris Mason 	u32 nritems;
5018be0e5c09SChris Mason 
50195f39d397SChris Mason 	leaf = path->nodes[0];
502085e21bacSChris Mason 	last_off = btrfs_item_offset_nr(leaf, slot + nr - 1);
502185e21bacSChris Mason 
502285e21bacSChris Mason 	for (i = 0; i < nr; i++)
502385e21bacSChris Mason 		dsize += btrfs_item_size_nr(leaf, slot + i);
502485e21bacSChris Mason 
50255f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
5026be0e5c09SChris Mason 
502785e21bacSChris Mason 	if (slot + nr != nritems) {
50288f881e8cSDavid Sterba 		int data_end = leaf_data_end(leaf);
5029c82f823cSDavid Sterba 		struct btrfs_map_token token;
50305f39d397SChris Mason 
50313d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
5032d6025579SChris Mason 			      data_end + dsize,
50333d9ec8c4SNikolay Borisov 			      BTRFS_LEAF_DATA_OFFSET + data_end,
503485e21bacSChris Mason 			      last_off - data_end);
50355f39d397SChris Mason 
5036c82f823cSDavid Sterba 		btrfs_init_map_token(&token, leaf);
503785e21bacSChris Mason 		for (i = slot + nr; i < nritems; i++) {
50385f39d397SChris Mason 			u32 ioff;
5039db94535dSChris Mason 
5040dd3cc16bSRoss Kirk 			item = btrfs_item_nr(i);
5041cc4c13d5SDavid Sterba 			ioff = btrfs_token_item_offset(&token, item);
5042cc4c13d5SDavid Sterba 			btrfs_set_token_item_offset(&token, item, ioff + dsize);
50430783fcfcSChris Mason 		}
5044db94535dSChris Mason 
50455f39d397SChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot),
504685e21bacSChris Mason 			      btrfs_item_nr_offset(slot + nr),
50470783fcfcSChris Mason 			      sizeof(struct btrfs_item) *
504885e21bacSChris Mason 			      (nritems - slot - nr));
5049be0e5c09SChris Mason 	}
505085e21bacSChris Mason 	btrfs_set_header_nritems(leaf, nritems - nr);
505185e21bacSChris Mason 	nritems -= nr;
50525f39d397SChris Mason 
505374123bd7SChris Mason 	/* delete the leaf if we've emptied it */
50547518a238SChris Mason 	if (nritems == 0) {
50555f39d397SChris Mason 		if (leaf == root->node) {
50565f39d397SChris Mason 			btrfs_set_header_level(leaf, 0);
50579a8dd150SChris Mason 		} else {
5058f0486c68SYan, Zheng 			btrfs_set_path_blocking(path);
50596a884d7dSDavid Sterba 			btrfs_clean_tree_block(leaf);
5060143bede5SJeff Mahoney 			btrfs_del_leaf(trans, root, path, leaf);
50619a8dd150SChris Mason 		}
5062be0e5c09SChris Mason 	} else {
50637518a238SChris Mason 		int used = leaf_space_used(leaf, 0, nritems);
5064aa5d6bedSChris Mason 		if (slot == 0) {
50655f39d397SChris Mason 			struct btrfs_disk_key disk_key;
50665f39d397SChris Mason 
50675f39d397SChris Mason 			btrfs_item_key(leaf, &disk_key, 0);
5068b167fa91SNikolay Borisov 			fixup_low_keys(path, &disk_key, 1);
5069aa5d6bedSChris Mason 		}
5070aa5d6bedSChris Mason 
507174123bd7SChris Mason 		/* delete the leaf if it is mostly empty */
50720b246afaSJeff Mahoney 		if (used < BTRFS_LEAF_DATA_SIZE(fs_info) / 3) {
5073be0e5c09SChris Mason 			/* push_leaf_left fixes the path.
5074be0e5c09SChris Mason 			 * make sure the path still points to our leaf
5075be0e5c09SChris Mason 			 * for possible call to del_ptr below
5076be0e5c09SChris Mason 			 */
50774920c9acSChris Mason 			slot = path->slots[1];
507867439dadSDavid Sterba 			atomic_inc(&leaf->refs);
50795f39d397SChris Mason 
5080b9473439SChris Mason 			btrfs_set_path_blocking(path);
508199d8f83cSChris Mason 			wret = push_leaf_left(trans, root, path, 1, 1,
508299d8f83cSChris Mason 					      1, (u32)-1);
508354aa1f4dSChris Mason 			if (wret < 0 && wret != -ENOSPC)
5084aa5d6bedSChris Mason 				ret = wret;
50855f39d397SChris Mason 
50865f39d397SChris Mason 			if (path->nodes[0] == leaf &&
50875f39d397SChris Mason 			    btrfs_header_nritems(leaf)) {
508899d8f83cSChris Mason 				wret = push_leaf_right(trans, root, path, 1,
508999d8f83cSChris Mason 						       1, 1, 0);
509054aa1f4dSChris Mason 				if (wret < 0 && wret != -ENOSPC)
5091aa5d6bedSChris Mason 					ret = wret;
5092aa5d6bedSChris Mason 			}
50935f39d397SChris Mason 
50945f39d397SChris Mason 			if (btrfs_header_nritems(leaf) == 0) {
5095323ac95bSChris Mason 				path->slots[1] = slot;
5096143bede5SJeff Mahoney 				btrfs_del_leaf(trans, root, path, leaf);
50975f39d397SChris Mason 				free_extent_buffer(leaf);
5098143bede5SJeff Mahoney 				ret = 0;
50995de08d7dSChris Mason 			} else {
5100925baeddSChris Mason 				/* if we're still in the path, make sure
5101925baeddSChris Mason 				 * we're dirty.  Otherwise, one of the
5102925baeddSChris Mason 				 * push_leaf functions must have already
5103925baeddSChris Mason 				 * dirtied this buffer
5104925baeddSChris Mason 				 */
5105925baeddSChris Mason 				if (path->nodes[0] == leaf)
51065f39d397SChris Mason 					btrfs_mark_buffer_dirty(leaf);
51075f39d397SChris Mason 				free_extent_buffer(leaf);
5108be0e5c09SChris Mason 			}
5109d5719762SChris Mason 		} else {
51105f39d397SChris Mason 			btrfs_mark_buffer_dirty(leaf);
5111be0e5c09SChris Mason 		}
51129a8dd150SChris Mason 	}
5113aa5d6bedSChris Mason 	return ret;
51149a8dd150SChris Mason }
51159a8dd150SChris Mason 
511697571fd0SChris Mason /*
5117925baeddSChris Mason  * search the tree again to find a leaf with lesser keys
51187bb86316SChris Mason  * returns 0 if it found something or 1 if there are no lesser leaves.
51197bb86316SChris Mason  * returns < 0 on io errors.
5120d352ac68SChris Mason  *
5121d352ac68SChris Mason  * This may release the path, and so you may lose any locks held at the
5122d352ac68SChris Mason  * time you call it.
51237bb86316SChris Mason  */
512416e7549fSJosef Bacik int btrfs_prev_leaf(struct btrfs_root *root, struct btrfs_path *path)
51257bb86316SChris Mason {
5126925baeddSChris Mason 	struct btrfs_key key;
5127925baeddSChris Mason 	struct btrfs_disk_key found_key;
5128925baeddSChris Mason 	int ret;
51297bb86316SChris Mason 
5130925baeddSChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, 0);
5131925baeddSChris Mason 
5132e8b0d724SFilipe David Borba Manana 	if (key.offset > 0) {
5133925baeddSChris Mason 		key.offset--;
5134e8b0d724SFilipe David Borba Manana 	} else if (key.type > 0) {
5135925baeddSChris Mason 		key.type--;
5136e8b0d724SFilipe David Borba Manana 		key.offset = (u64)-1;
5137e8b0d724SFilipe David Borba Manana 	} else if (key.objectid > 0) {
5138925baeddSChris Mason 		key.objectid--;
5139e8b0d724SFilipe David Borba Manana 		key.type = (u8)-1;
5140e8b0d724SFilipe David Borba Manana 		key.offset = (u64)-1;
5141e8b0d724SFilipe David Borba Manana 	} else {
51427bb86316SChris Mason 		return 1;
5143e8b0d724SFilipe David Borba Manana 	}
51447bb86316SChris Mason 
5145b3b4aa74SDavid Sterba 	btrfs_release_path(path);
5146925baeddSChris Mason 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5147925baeddSChris Mason 	if (ret < 0)
5148925baeddSChris Mason 		return ret;
5149925baeddSChris Mason 	btrfs_item_key(path->nodes[0], &found_key, 0);
5150925baeddSChris Mason 	ret = comp_keys(&found_key, &key);
5151337c6f68SFilipe Manana 	/*
5152337c6f68SFilipe Manana 	 * We might have had an item with the previous key in the tree right
5153337c6f68SFilipe Manana 	 * before we released our path. And after we released our path, that
5154337c6f68SFilipe Manana 	 * item might have been pushed to the first slot (0) of the leaf we
5155337c6f68SFilipe Manana 	 * were holding due to a tree balance. Alternatively, an item with the
5156337c6f68SFilipe Manana 	 * previous key can exist as the only element of a leaf (big fat item).
5157337c6f68SFilipe Manana 	 * Therefore account for these 2 cases, so that our callers (like
5158337c6f68SFilipe Manana 	 * btrfs_previous_item) don't miss an existing item with a key matching
5159337c6f68SFilipe Manana 	 * the previous key we computed above.
5160337c6f68SFilipe Manana 	 */
5161337c6f68SFilipe Manana 	if (ret <= 0)
51627bb86316SChris Mason 		return 0;
5163925baeddSChris Mason 	return 1;
51647bb86316SChris Mason }
51657bb86316SChris Mason 
51663f157a2fSChris Mason /*
51673f157a2fSChris Mason  * A helper function to walk down the tree starting at min_key, and looking
5168de78b51aSEric Sandeen  * for nodes or leaves that are have a minimum transaction id.
5169de78b51aSEric Sandeen  * This is used by the btree defrag code, and tree logging
51703f157a2fSChris Mason  *
51713f157a2fSChris Mason  * This does not cow, but it does stuff the starting key it finds back
51723f157a2fSChris Mason  * into min_key, so you can call btrfs_search_slot with cow=1 on the
51733f157a2fSChris Mason  * key and get a writable path.
51743f157a2fSChris Mason  *
51753f157a2fSChris Mason  * This honors path->lowest_level to prevent descent past a given level
51763f157a2fSChris Mason  * of the tree.
51773f157a2fSChris Mason  *
5178d352ac68SChris Mason  * min_trans indicates the oldest transaction that you are interested
5179d352ac68SChris Mason  * in walking through.  Any nodes or leaves older than min_trans are
5180d352ac68SChris Mason  * skipped over (without reading them).
5181d352ac68SChris Mason  *
51823f157a2fSChris Mason  * returns zero if something useful was found, < 0 on error and 1 if there
51833f157a2fSChris Mason  * was nothing in the tree that matched the search criteria.
51843f157a2fSChris Mason  */
51853f157a2fSChris Mason int btrfs_search_forward(struct btrfs_root *root, struct btrfs_key *min_key,
5186de78b51aSEric Sandeen 			 struct btrfs_path *path,
51873f157a2fSChris Mason 			 u64 min_trans)
51883f157a2fSChris Mason {
51893f157a2fSChris Mason 	struct extent_buffer *cur;
51903f157a2fSChris Mason 	struct btrfs_key found_key;
51913f157a2fSChris Mason 	int slot;
51929652480bSYan 	int sret;
51933f157a2fSChris Mason 	u32 nritems;
51943f157a2fSChris Mason 	int level;
51953f157a2fSChris Mason 	int ret = 1;
5196f98de9b9SFilipe Manana 	int keep_locks = path->keep_locks;
51973f157a2fSChris Mason 
5198f98de9b9SFilipe Manana 	path->keep_locks = 1;
51993f157a2fSChris Mason again:
5200bd681513SChris Mason 	cur = btrfs_read_lock_root_node(root);
52013f157a2fSChris Mason 	level = btrfs_header_level(cur);
5202e02119d5SChris Mason 	WARN_ON(path->nodes[level]);
52033f157a2fSChris Mason 	path->nodes[level] = cur;
5204bd681513SChris Mason 	path->locks[level] = BTRFS_READ_LOCK;
52053f157a2fSChris Mason 
52063f157a2fSChris Mason 	if (btrfs_header_generation(cur) < min_trans) {
52073f157a2fSChris Mason 		ret = 1;
52083f157a2fSChris Mason 		goto out;
52093f157a2fSChris Mason 	}
52103f157a2fSChris Mason 	while (1) {
52113f157a2fSChris Mason 		nritems = btrfs_header_nritems(cur);
52123f157a2fSChris Mason 		level = btrfs_header_level(cur);
5213e3b83361SQu Wenruo 		sret = btrfs_bin_search(cur, min_key, &slot);
5214cbca7d59SFilipe Manana 		if (sret < 0) {
5215cbca7d59SFilipe Manana 			ret = sret;
5216cbca7d59SFilipe Manana 			goto out;
5217cbca7d59SFilipe Manana 		}
52183f157a2fSChris Mason 
5219323ac95bSChris Mason 		/* at the lowest level, we're done, setup the path and exit */
5220323ac95bSChris Mason 		if (level == path->lowest_level) {
5221e02119d5SChris Mason 			if (slot >= nritems)
5222e02119d5SChris Mason 				goto find_next_key;
52233f157a2fSChris Mason 			ret = 0;
52243f157a2fSChris Mason 			path->slots[level] = slot;
52253f157a2fSChris Mason 			btrfs_item_key_to_cpu(cur, &found_key, slot);
52263f157a2fSChris Mason 			goto out;
52273f157a2fSChris Mason 		}
52289652480bSYan 		if (sret && slot > 0)
52299652480bSYan 			slot--;
52303f157a2fSChris Mason 		/*
5231de78b51aSEric Sandeen 		 * check this node pointer against the min_trans parameters.
5232260db43cSRandy Dunlap 		 * If it is too old, skip to the next one.
52333f157a2fSChris Mason 		 */
52343f157a2fSChris Mason 		while (slot < nritems) {
52353f157a2fSChris Mason 			u64 gen;
5236e02119d5SChris Mason 
52373f157a2fSChris Mason 			gen = btrfs_node_ptr_generation(cur, slot);
52383f157a2fSChris Mason 			if (gen < min_trans) {
52393f157a2fSChris Mason 				slot++;
52403f157a2fSChris Mason 				continue;
52413f157a2fSChris Mason 			}
52423f157a2fSChris Mason 			break;
52433f157a2fSChris Mason 		}
5244e02119d5SChris Mason find_next_key:
52453f157a2fSChris Mason 		/*
52463f157a2fSChris Mason 		 * we didn't find a candidate key in this node, walk forward
52473f157a2fSChris Mason 		 * and find another one
52483f157a2fSChris Mason 		 */
52493f157a2fSChris Mason 		if (slot >= nritems) {
5250e02119d5SChris Mason 			path->slots[level] = slot;
5251b4ce94deSChris Mason 			btrfs_set_path_blocking(path);
5252e02119d5SChris Mason 			sret = btrfs_find_next_key(root, path, min_key, level,
5253de78b51aSEric Sandeen 						  min_trans);
5254e02119d5SChris Mason 			if (sret == 0) {
5255b3b4aa74SDavid Sterba 				btrfs_release_path(path);
52563f157a2fSChris Mason 				goto again;
52573f157a2fSChris Mason 			} else {
52583f157a2fSChris Mason 				goto out;
52593f157a2fSChris Mason 			}
52603f157a2fSChris Mason 		}
52613f157a2fSChris Mason 		/* save our key for returning back */
52623f157a2fSChris Mason 		btrfs_node_key_to_cpu(cur, &found_key, slot);
52633f157a2fSChris Mason 		path->slots[level] = slot;
52643f157a2fSChris Mason 		if (level == path->lowest_level) {
52653f157a2fSChris Mason 			ret = 0;
52663f157a2fSChris Mason 			goto out;
52673f157a2fSChris Mason 		}
5268b4ce94deSChris Mason 		btrfs_set_path_blocking(path);
52694b231ae4SDavid Sterba 		cur = btrfs_read_node_slot(cur, slot);
5270fb770ae4SLiu Bo 		if (IS_ERR(cur)) {
5271fb770ae4SLiu Bo 			ret = PTR_ERR(cur);
5272fb770ae4SLiu Bo 			goto out;
5273fb770ae4SLiu Bo 		}
52743f157a2fSChris Mason 
5275bd681513SChris Mason 		btrfs_tree_read_lock(cur);
5276b4ce94deSChris Mason 
5277bd681513SChris Mason 		path->locks[level - 1] = BTRFS_READ_LOCK;
52783f157a2fSChris Mason 		path->nodes[level - 1] = cur;
5279f7c79f30SChris Mason 		unlock_up(path, level, 1, 0, NULL);
52803f157a2fSChris Mason 	}
52813f157a2fSChris Mason out:
5282f98de9b9SFilipe Manana 	path->keep_locks = keep_locks;
5283f98de9b9SFilipe Manana 	if (ret == 0) {
5284f98de9b9SFilipe Manana 		btrfs_unlock_up_safe(path, path->lowest_level + 1);
5285b4ce94deSChris Mason 		btrfs_set_path_blocking(path);
5286f98de9b9SFilipe Manana 		memcpy(min_key, &found_key, sizeof(found_key));
5287f98de9b9SFilipe Manana 	}
52883f157a2fSChris Mason 	return ret;
52893f157a2fSChris Mason }
52903f157a2fSChris Mason 
52913f157a2fSChris Mason /*
52923f157a2fSChris Mason  * this is similar to btrfs_next_leaf, but does not try to preserve
52933f157a2fSChris Mason  * and fixup the path.  It looks for and returns the next key in the
5294de78b51aSEric Sandeen  * tree based on the current path and the min_trans parameters.
52953f157a2fSChris Mason  *
52963f157a2fSChris Mason  * 0 is returned if another key is found, < 0 if there are any errors
52973f157a2fSChris Mason  * and 1 is returned if there are no higher keys in the tree
52983f157a2fSChris Mason  *
52993f157a2fSChris Mason  * path->keep_locks should be set to 1 on the search made before
53003f157a2fSChris Mason  * calling this function.
53013f157a2fSChris Mason  */
5302e7a84565SChris Mason int btrfs_find_next_key(struct btrfs_root *root, struct btrfs_path *path,
5303de78b51aSEric Sandeen 			struct btrfs_key *key, int level, u64 min_trans)
5304e7a84565SChris Mason {
5305e7a84565SChris Mason 	int slot;
5306e7a84565SChris Mason 	struct extent_buffer *c;
5307e7a84565SChris Mason 
53086a9fb468SJosef Bacik 	WARN_ON(!path->keep_locks && !path->skip_locking);
5309e7a84565SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
5310e7a84565SChris Mason 		if (!path->nodes[level])
5311e7a84565SChris Mason 			return 1;
5312e7a84565SChris Mason 
5313e7a84565SChris Mason 		slot = path->slots[level] + 1;
5314e7a84565SChris Mason 		c = path->nodes[level];
53153f157a2fSChris Mason next:
5316e7a84565SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
531733c66f43SYan Zheng 			int ret;
531833c66f43SYan Zheng 			int orig_lowest;
531933c66f43SYan Zheng 			struct btrfs_key cur_key;
532033c66f43SYan Zheng 			if (level + 1 >= BTRFS_MAX_LEVEL ||
532133c66f43SYan Zheng 			    !path->nodes[level + 1])
5322e7a84565SChris Mason 				return 1;
532333c66f43SYan Zheng 
53246a9fb468SJosef Bacik 			if (path->locks[level + 1] || path->skip_locking) {
532533c66f43SYan Zheng 				level++;
5326e7a84565SChris Mason 				continue;
5327e7a84565SChris Mason 			}
532833c66f43SYan Zheng 
532933c66f43SYan Zheng 			slot = btrfs_header_nritems(c) - 1;
533033c66f43SYan Zheng 			if (level == 0)
533133c66f43SYan Zheng 				btrfs_item_key_to_cpu(c, &cur_key, slot);
533233c66f43SYan Zheng 			else
533333c66f43SYan Zheng 				btrfs_node_key_to_cpu(c, &cur_key, slot);
533433c66f43SYan Zheng 
533533c66f43SYan Zheng 			orig_lowest = path->lowest_level;
5336b3b4aa74SDavid Sterba 			btrfs_release_path(path);
533733c66f43SYan Zheng 			path->lowest_level = level;
533833c66f43SYan Zheng 			ret = btrfs_search_slot(NULL, root, &cur_key, path,
533933c66f43SYan Zheng 						0, 0);
534033c66f43SYan Zheng 			path->lowest_level = orig_lowest;
534133c66f43SYan Zheng 			if (ret < 0)
534233c66f43SYan Zheng 				return ret;
534333c66f43SYan Zheng 
534433c66f43SYan Zheng 			c = path->nodes[level];
534533c66f43SYan Zheng 			slot = path->slots[level];
534633c66f43SYan Zheng 			if (ret == 0)
534733c66f43SYan Zheng 				slot++;
534833c66f43SYan Zheng 			goto next;
534933c66f43SYan Zheng 		}
535033c66f43SYan Zheng 
5351e7a84565SChris Mason 		if (level == 0)
5352e7a84565SChris Mason 			btrfs_item_key_to_cpu(c, key, slot);
53533f157a2fSChris Mason 		else {
53543f157a2fSChris Mason 			u64 gen = btrfs_node_ptr_generation(c, slot);
53553f157a2fSChris Mason 
53563f157a2fSChris Mason 			if (gen < min_trans) {
53573f157a2fSChris Mason 				slot++;
53583f157a2fSChris Mason 				goto next;
53593f157a2fSChris Mason 			}
5360e7a84565SChris Mason 			btrfs_node_key_to_cpu(c, key, slot);
53613f157a2fSChris Mason 		}
5362e7a84565SChris Mason 		return 0;
5363e7a84565SChris Mason 	}
5364e7a84565SChris Mason 	return 1;
5365e7a84565SChris Mason }
5366e7a84565SChris Mason 
53677bb86316SChris Mason /*
5368925baeddSChris Mason  * search the tree again to find a leaf with greater keys
53690f70abe2SChris Mason  * returns 0 if it found something or 1 if there are no greater leaves.
53700f70abe2SChris Mason  * returns < 0 on io errors.
537197571fd0SChris Mason  */
5372234b63a0SChris Mason int btrfs_next_leaf(struct btrfs_root *root, struct btrfs_path *path)
5373d97e63b6SChris Mason {
53743d7806ecSJan Schmidt 	return btrfs_next_old_leaf(root, path, 0);
53753d7806ecSJan Schmidt }
53763d7806ecSJan Schmidt 
53773d7806ecSJan Schmidt int btrfs_next_old_leaf(struct btrfs_root *root, struct btrfs_path *path,
53783d7806ecSJan Schmidt 			u64 time_seq)
53793d7806ecSJan Schmidt {
5380d97e63b6SChris Mason 	int slot;
53818e73f275SChris Mason 	int level;
53825f39d397SChris Mason 	struct extent_buffer *c;
53838e73f275SChris Mason 	struct extent_buffer *next;
5384925baeddSChris Mason 	struct btrfs_key key;
5385925baeddSChris Mason 	u32 nritems;
5386925baeddSChris Mason 	int ret;
53878e73f275SChris Mason 	int old_spinning = path->leave_spinning;
5388bd681513SChris Mason 	int next_rw_lock = 0;
5389925baeddSChris Mason 
5390925baeddSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
5391d397712bSChris Mason 	if (nritems == 0)
5392925baeddSChris Mason 		return 1;
5393925baeddSChris Mason 
53948e73f275SChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, nritems - 1);
53958e73f275SChris Mason again:
53968e73f275SChris Mason 	level = 1;
53978e73f275SChris Mason 	next = NULL;
5398bd681513SChris Mason 	next_rw_lock = 0;
5399b3b4aa74SDavid Sterba 	btrfs_release_path(path);
54008e73f275SChris Mason 
5401a2135011SChris Mason 	path->keep_locks = 1;
54028e73f275SChris Mason 	path->leave_spinning = 1;
54038e73f275SChris Mason 
54043d7806ecSJan Schmidt 	if (time_seq)
54053d7806ecSJan Schmidt 		ret = btrfs_search_old_slot(root, &key, path, time_seq);
54063d7806ecSJan Schmidt 	else
5407925baeddSChris Mason 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5408925baeddSChris Mason 	path->keep_locks = 0;
5409925baeddSChris Mason 
5410925baeddSChris Mason 	if (ret < 0)
5411925baeddSChris Mason 		return ret;
5412925baeddSChris Mason 
5413a2135011SChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
5414168fd7d2SChris Mason 	/*
5415168fd7d2SChris Mason 	 * by releasing the path above we dropped all our locks.  A balance
5416168fd7d2SChris Mason 	 * could have added more items next to the key that used to be
5417168fd7d2SChris Mason 	 * at the very end of the block.  So, check again here and
5418168fd7d2SChris Mason 	 * advance the path if there are now more items available.
5419168fd7d2SChris Mason 	 */
5420a2135011SChris Mason 	if (nritems > 0 && path->slots[0] < nritems - 1) {
5421e457afecSYan Zheng 		if (ret == 0)
5422168fd7d2SChris Mason 			path->slots[0]++;
54238e73f275SChris Mason 		ret = 0;
5424925baeddSChris Mason 		goto done;
5425925baeddSChris Mason 	}
54260b43e04fSLiu Bo 	/*
54270b43e04fSLiu Bo 	 * So the above check misses one case:
54280b43e04fSLiu Bo 	 * - after releasing the path above, someone has removed the item that
54290b43e04fSLiu Bo 	 *   used to be at the very end of the block, and balance between leafs
54300b43e04fSLiu Bo 	 *   gets another one with bigger key.offset to replace it.
54310b43e04fSLiu Bo 	 *
54320b43e04fSLiu Bo 	 * This one should be returned as well, or we can get leaf corruption
54330b43e04fSLiu Bo 	 * later(esp. in __btrfs_drop_extents()).
54340b43e04fSLiu Bo 	 *
54350b43e04fSLiu Bo 	 * And a bit more explanation about this check,
54360b43e04fSLiu Bo 	 * with ret > 0, the key isn't found, the path points to the slot
54370b43e04fSLiu Bo 	 * where it should be inserted, so the path->slots[0] item must be the
54380b43e04fSLiu Bo 	 * bigger one.
54390b43e04fSLiu Bo 	 */
54400b43e04fSLiu Bo 	if (nritems > 0 && ret > 0 && path->slots[0] == nritems - 1) {
54410b43e04fSLiu Bo 		ret = 0;
54420b43e04fSLiu Bo 		goto done;
54430b43e04fSLiu Bo 	}
5444d97e63b6SChris Mason 
5445234b63a0SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
54468e73f275SChris Mason 		if (!path->nodes[level]) {
54478e73f275SChris Mason 			ret = 1;
54488e73f275SChris Mason 			goto done;
54498e73f275SChris Mason 		}
54505f39d397SChris Mason 
5451d97e63b6SChris Mason 		slot = path->slots[level] + 1;
5452d97e63b6SChris Mason 		c = path->nodes[level];
54535f39d397SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
5454d97e63b6SChris Mason 			level++;
54558e73f275SChris Mason 			if (level == BTRFS_MAX_LEVEL) {
54568e73f275SChris Mason 				ret = 1;
54578e73f275SChris Mason 				goto done;
54588e73f275SChris Mason 			}
5459d97e63b6SChris Mason 			continue;
5460d97e63b6SChris Mason 		}
54615f39d397SChris Mason 
5462925baeddSChris Mason 		if (next) {
5463bd681513SChris Mason 			btrfs_tree_unlock_rw(next, next_rw_lock);
54645f39d397SChris Mason 			free_extent_buffer(next);
5465925baeddSChris Mason 		}
54665f39d397SChris Mason 
54678e73f275SChris Mason 		next = c;
5468bd681513SChris Mason 		next_rw_lock = path->locks[level];
5469d07b8528SLiu Bo 		ret = read_block_for_search(root, path, &next, level,
5470cda79c54SDavid Sterba 					    slot, &key);
54718e73f275SChris Mason 		if (ret == -EAGAIN)
54728e73f275SChris Mason 			goto again;
54735f39d397SChris Mason 
547476a05b35SChris Mason 		if (ret < 0) {
5475b3b4aa74SDavid Sterba 			btrfs_release_path(path);
547676a05b35SChris Mason 			goto done;
547776a05b35SChris Mason 		}
547876a05b35SChris Mason 
54795cd57b2cSChris Mason 		if (!path->skip_locking) {
5480bd681513SChris Mason 			ret = btrfs_try_tree_read_lock(next);
5481d42244a0SJan Schmidt 			if (!ret && time_seq) {
5482d42244a0SJan Schmidt 				/*
5483d42244a0SJan Schmidt 				 * If we don't get the lock, we may be racing
5484d42244a0SJan Schmidt 				 * with push_leaf_left, holding that lock while
5485d42244a0SJan Schmidt 				 * itself waiting for the leaf we've currently
5486d42244a0SJan Schmidt 				 * locked. To solve this situation, we give up
5487d42244a0SJan Schmidt 				 * on our lock and cycle.
5488d42244a0SJan Schmidt 				 */
5489cf538830SJan Schmidt 				free_extent_buffer(next);
5490d42244a0SJan Schmidt 				btrfs_release_path(path);
5491d42244a0SJan Schmidt 				cond_resched();
5492d42244a0SJan Schmidt 				goto again;
5493d42244a0SJan Schmidt 			}
54948e73f275SChris Mason 			if (!ret) {
54958e73f275SChris Mason 				btrfs_set_path_blocking(path);
5496fd7ba1c1SJosef Bacik 				__btrfs_tree_read_lock(next,
5497bf77467aSJosef Bacik 						       BTRFS_NESTING_RIGHT,
5498fd7ba1c1SJosef Bacik 						       path->recurse);
54998e73f275SChris Mason 			}
5500bd681513SChris Mason 			next_rw_lock = BTRFS_READ_LOCK;
5501bd681513SChris Mason 		}
5502d97e63b6SChris Mason 		break;
5503d97e63b6SChris Mason 	}
5504d97e63b6SChris Mason 	path->slots[level] = slot;
5505d97e63b6SChris Mason 	while (1) {
5506d97e63b6SChris Mason 		level--;
5507d97e63b6SChris Mason 		c = path->nodes[level];
5508925baeddSChris Mason 		if (path->locks[level])
5509bd681513SChris Mason 			btrfs_tree_unlock_rw(c, path->locks[level]);
55108e73f275SChris Mason 
55115f39d397SChris Mason 		free_extent_buffer(c);
5512d97e63b6SChris Mason 		path->nodes[level] = next;
5513d97e63b6SChris Mason 		path->slots[level] = 0;
5514a74a4b97SChris Mason 		if (!path->skip_locking)
5515bd681513SChris Mason 			path->locks[level] = next_rw_lock;
5516d97e63b6SChris Mason 		if (!level)
5517d97e63b6SChris Mason 			break;
5518b4ce94deSChris Mason 
5519d07b8528SLiu Bo 		ret = read_block_for_search(root, path, &next, level,
5520cda79c54SDavid Sterba 					    0, &key);
55218e73f275SChris Mason 		if (ret == -EAGAIN)
55228e73f275SChris Mason 			goto again;
55238e73f275SChris Mason 
552476a05b35SChris Mason 		if (ret < 0) {
5525b3b4aa74SDavid Sterba 			btrfs_release_path(path);
552676a05b35SChris Mason 			goto done;
552776a05b35SChris Mason 		}
552876a05b35SChris Mason 
55295cd57b2cSChris Mason 		if (!path->skip_locking) {
5530bd681513SChris Mason 			ret = btrfs_try_tree_read_lock(next);
55318e73f275SChris Mason 			if (!ret) {
55328e73f275SChris Mason 				btrfs_set_path_blocking(path);
5533fd7ba1c1SJosef Bacik 				__btrfs_tree_read_lock(next,
5534bf77467aSJosef Bacik 						       BTRFS_NESTING_RIGHT,
5535fd7ba1c1SJosef Bacik 						       path->recurse);
55368e73f275SChris Mason 			}
5537bd681513SChris Mason 			next_rw_lock = BTRFS_READ_LOCK;
5538bd681513SChris Mason 		}
5539d97e63b6SChris Mason 	}
55408e73f275SChris Mason 	ret = 0;
5541925baeddSChris Mason done:
5542f7c79f30SChris Mason 	unlock_up(path, 0, 1, 0, NULL);
55438e73f275SChris Mason 	path->leave_spinning = old_spinning;
55448e73f275SChris Mason 	if (!old_spinning)
55458e73f275SChris Mason 		btrfs_set_path_blocking(path);
55468e73f275SChris Mason 
55478e73f275SChris Mason 	return ret;
5548d97e63b6SChris Mason }
55490b86a832SChris Mason 
55503f157a2fSChris Mason /*
55513f157a2fSChris Mason  * this uses btrfs_prev_leaf to walk backwards in the tree, and keeps
55523f157a2fSChris Mason  * searching until it gets past min_objectid or finds an item of 'type'
55533f157a2fSChris Mason  *
55543f157a2fSChris Mason  * returns 0 if something is found, 1 if nothing was found and < 0 on error
55553f157a2fSChris Mason  */
55560b86a832SChris Mason int btrfs_previous_item(struct btrfs_root *root,
55570b86a832SChris Mason 			struct btrfs_path *path, u64 min_objectid,
55580b86a832SChris Mason 			int type)
55590b86a832SChris Mason {
55600b86a832SChris Mason 	struct btrfs_key found_key;
55610b86a832SChris Mason 	struct extent_buffer *leaf;
5562e02119d5SChris Mason 	u32 nritems;
55630b86a832SChris Mason 	int ret;
55640b86a832SChris Mason 
55650b86a832SChris Mason 	while (1) {
55660b86a832SChris Mason 		if (path->slots[0] == 0) {
5567b4ce94deSChris Mason 			btrfs_set_path_blocking(path);
55680b86a832SChris Mason 			ret = btrfs_prev_leaf(root, path);
55690b86a832SChris Mason 			if (ret != 0)
55700b86a832SChris Mason 				return ret;
55710b86a832SChris Mason 		} else {
55720b86a832SChris Mason 			path->slots[0]--;
55730b86a832SChris Mason 		}
55740b86a832SChris Mason 		leaf = path->nodes[0];
5575e02119d5SChris Mason 		nritems = btrfs_header_nritems(leaf);
5576e02119d5SChris Mason 		if (nritems == 0)
5577e02119d5SChris Mason 			return 1;
5578e02119d5SChris Mason 		if (path->slots[0] == nritems)
5579e02119d5SChris Mason 			path->slots[0]--;
5580e02119d5SChris Mason 
55810b86a832SChris Mason 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5582e02119d5SChris Mason 		if (found_key.objectid < min_objectid)
5583e02119d5SChris Mason 			break;
55840a4eefbbSYan Zheng 		if (found_key.type == type)
55850a4eefbbSYan Zheng 			return 0;
5586e02119d5SChris Mason 		if (found_key.objectid == min_objectid &&
5587e02119d5SChris Mason 		    found_key.type < type)
5588e02119d5SChris Mason 			break;
55890b86a832SChris Mason 	}
55900b86a832SChris Mason 	return 1;
55910b86a832SChris Mason }
5592ade2e0b3SWang Shilong 
5593ade2e0b3SWang Shilong /*
5594ade2e0b3SWang Shilong  * search in extent tree to find a previous Metadata/Data extent item with
5595ade2e0b3SWang Shilong  * min objecitd.
5596ade2e0b3SWang Shilong  *
5597ade2e0b3SWang Shilong  * returns 0 if something is found, 1 if nothing was found and < 0 on error
5598ade2e0b3SWang Shilong  */
5599ade2e0b3SWang Shilong int btrfs_previous_extent_item(struct btrfs_root *root,
5600ade2e0b3SWang Shilong 			struct btrfs_path *path, u64 min_objectid)
5601ade2e0b3SWang Shilong {
5602ade2e0b3SWang Shilong 	struct btrfs_key found_key;
5603ade2e0b3SWang Shilong 	struct extent_buffer *leaf;
5604ade2e0b3SWang Shilong 	u32 nritems;
5605ade2e0b3SWang Shilong 	int ret;
5606ade2e0b3SWang Shilong 
5607ade2e0b3SWang Shilong 	while (1) {
5608ade2e0b3SWang Shilong 		if (path->slots[0] == 0) {
5609ade2e0b3SWang Shilong 			btrfs_set_path_blocking(path);
5610ade2e0b3SWang Shilong 			ret = btrfs_prev_leaf(root, path);
5611ade2e0b3SWang Shilong 			if (ret != 0)
5612ade2e0b3SWang Shilong 				return ret;
5613ade2e0b3SWang Shilong 		} else {
5614ade2e0b3SWang Shilong 			path->slots[0]--;
5615ade2e0b3SWang Shilong 		}
5616ade2e0b3SWang Shilong 		leaf = path->nodes[0];
5617ade2e0b3SWang Shilong 		nritems = btrfs_header_nritems(leaf);
5618ade2e0b3SWang Shilong 		if (nritems == 0)
5619ade2e0b3SWang Shilong 			return 1;
5620ade2e0b3SWang Shilong 		if (path->slots[0] == nritems)
5621ade2e0b3SWang Shilong 			path->slots[0]--;
5622ade2e0b3SWang Shilong 
5623ade2e0b3SWang Shilong 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5624ade2e0b3SWang Shilong 		if (found_key.objectid < min_objectid)
5625ade2e0b3SWang Shilong 			break;
5626ade2e0b3SWang Shilong 		if (found_key.type == BTRFS_EXTENT_ITEM_KEY ||
5627ade2e0b3SWang Shilong 		    found_key.type == BTRFS_METADATA_ITEM_KEY)
5628ade2e0b3SWang Shilong 			return 0;
5629ade2e0b3SWang Shilong 		if (found_key.objectid == min_objectid &&
5630ade2e0b3SWang Shilong 		    found_key.type < BTRFS_EXTENT_ITEM_KEY)
5631ade2e0b3SWang Shilong 			break;
5632ade2e0b3SWang Shilong 	}
5633ade2e0b3SWang Shilong 	return 1;
5634ade2e0b3SWang Shilong }
5635